diff --git "a/4664.jsonl" "b/4664.jsonl" new file mode 100644--- /dev/null +++ "b/4664.jsonl" @@ -0,0 +1,706 @@ +{"seq_id":"147150493","text":"import argparse\nimport json\n\n# 3rd Party Imports\nimport boto3\n\n# The file should be:\n# {\n# \"Input\":[\n# {\n# \"Text\":\"I am learning to code in AWS\",\n# \"SourceLanguageCode\":\"en\",\n# \"TargetLanguageCode\":\"fr\"\n# }\n# ]\n# }\n\n# Arguments\nparser = argparse.ArgumentParser(description=\"Provides translation between one source language and another of the same set of languages.\")\nparser.add_argument(\n '--file',\n dest='filename',\n help=\"The path to the input file. The file should be valid json\",\n required=True)\n\nargs = parser.parse_args()\n\n# Functions\ndef open_input():\n with open(args.filename) as file_object:\n contents = json.load(file_object)\n return contents['Input'][0]\n\ndef translate_text(**kwargs): \n client = boto3.client('translate')\n response = client.translate_text(**kwargs)\n print(response) \n\n# Main Function - use to call other functions\ndef main():\n kwargs = open_input()\n translate_text(**kwargs)\n\nif __name__ == \"__main__\":\n main()","sub_path":"python/input.py","file_name":"input.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"192005483","text":"\nimport os\nimport subprocess\n\n#project = 'CarND-PID-Control-Project'\n#project = 'CarND-MPC-Project'\n#project = 'CarND-Path-Planning-Project'\nproject = 'CarND-Semantic-Segmentation'\n# shopt -s extglob && mv !(CarND*|README-1.md|merging-to-master-repo.py) CarND-Semantic-Segmentation\n\n\ncmd1 = 'git remote add -f {st} git@github.com:ilopezfr/{st}.git'.format(st=project)\ncmd2 = 'git fetch {st} --tags'.format(st=project)\ncmd3 = 'git merge {st}/master --allow-unrelated-histories -m \"merging {st} to Master repo\"'.format(st=project)\ncmd4 = 'mkdir {st}'.format(st=project)\n# shopt -s extglob && \ncmd5 = '''shopt -s extglob && mv !(CarND*|README-1.md|merging-to-master-repo.py) {st}'''.format(st=project)\n\n\n#shopt -s extglob && mv !(CarND*|README-1.md|merging-to-master-repo.py) CarND-PID-Control-Project\n\ncmd6 = 'mv .gitignore {st}'.format(st=project)\n\ncmd7 = 'git add .'\ncmd8 = 'git commit -m \"Move {st} files into subdir\"'.format(st=project)\ncmd9 = 'git push origin master'\n\ncommands = [cmd1, cmd2, cmd3, cmd4, cmd4, cmd5]\n#commands = [cmd5]\ncommands = [cmd6, cmd7, cmd8, cmd9]\nfor cmd in commands:\n print(cmd)\n #subprocess.check_call(cmd)\n os.system(cmd)\n\n#subprocess.call(cmd2)\n\n\n# import os\n\n\n# command = '''\n# git remote add -f {st} git@github.com:ilopezfr/{st}.git \\\n# && git fetch {st} --tags \\\n# && git merge {st}/master --allow-unrelated-histories -m '\"'\"'merging {st} to Master repo'\"'\"'\\\n# && mkdir {st} \\\n# && shopt -s extglob && mv !(CarND*|README-1.md|merging-to-master-repo.py) {st} \\\n# && mv .gitignore {st} \\\n# && git add . \\\n# && git commit -m '\"'\"'Move {st} files into subdir'\"'\"' \\ \n# && git push origin master\n# '''\n\n#os.system(command)\n\n# subprocess.run(bashCommand, shell=True)\n\n#process = subprocess.run(bashCommand.split(), stdout=subprocess.PIPE)\n#output, error = process.communicate()\n\n# import subprocess\n# process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)\n# output, error = process.communicate()\n\n# from subprocess import Popen, PIPE\n\n# projects = ['CarND-PID-Control-Project'] #, 'CarND-MPC-Project']\n# for project in projects:\n # string = \"\"\" git remote add -f {st} git@github.com:ilopezfr/{st}.git\n # git fetch {st} --tags \"\"\"\n \n # c1 = \"git remote add -f \"+project+\" git@github.com:ilopezfr/\"+project+\".git\"\n # c2 = \"git fetch \"+project+\" --tags\"\n # c3 = \"git merge \"{st}+\"/master --allow-unrelated-histories -m \"merging {st} to Master repo\"\n\n # mkdir {st}\n # shopt -s extglob\n # mv !(CarND*|README-1.md|merging-to-master-repo.py) {st}\n\n # mv .gitignore {st}\n\n # git add .\n # git commit -m \"Move {st} files into subdir\"\n\n # git push origin master;\n \n #command_list = command.format(st=project)\n #print(command_list)\n #subprocess_cmd(command_list)\n #ubprocess.run(command_list, shell=True,stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n #return_code = subprocess.Popen(command.format(project), shell=True)\n\n #print(return_code)\n #int subprocess.Popen(\"echo %s \" % user_input, stdout=PIPE).stdout.read()\n\n\n\n #project = \"test-project\"\n\n # cmd1 = 'git remote add -f {st} git@github.com:ilopezfr/{st}.git'.format(st=project)\n # cmd2 = 'git fetch {st} --tags'.format(st=project)\n # cmd3 = 'git merge {st}/master --allow-unrelated-histories -m \"merging {st} to Master repo\"'.format(st=project)\n # cmd4 = 'mkdir {st}'.format(st=project)\n # cmd5 = 'shopt -s extglob && mv !(CarND*|README-1.md|merging-to-master-repo.py) {st}'.format(st=project)\n # cmd6 = 'mv .gitignore {st}'.format(st=project)\n # sep = ' && '\n # command_list = [cmd1+sep+cmd2+sep+cmd3+sep+cmd4+sep+cmd5+sep+cmd6]\n\n # print(command_list)\n # #Popen(cmd.format(st=project)\n # process = Popen(command_list, shell=True) #, stdout=PIPE, stderr=PIPE ) # universal_newlines=True) #, stdin=PIPE, universal_newlines=True)\n #stdout, stderr = process.communicate()\n\n #print(stdout)\n\n","sub_path":"merging-to-master-repo.py","file_name":"merging-to-master-repo.py","file_ext":"py","file_size_in_byte":3906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"537188132","text":"############################################################################\n## Implements extensible VIM-style commands in PN 2.1\n##\n## Currently focusing on implementing most commands here: http://www.stanford.edu/~jacobm/vim.html\n\nimport pn, scintilla\nimport re\n\nif pn.initializing:\n\tfrom pypn import glue\nelse:\n\timport pypn.glue\n\ndef evalCommand(text):\n\t\"\"\" This is just a very simple prototype of VI-style commands \"\"\"\n\tslen = len(text)\n\tif slen == 0:\n\t\treturn \"\"\n\t\n\tif slen > 1:\n\t\t# We're beyond single-letter commands\n\t\t\n\t\tif text[0] in ['c','d','y']:\n\t\t\treturn _handleChangeCommand(text[0], text[1:])\n\t\t\n\t\t# check for repeated single-letter command:\n\t\tm = re.match(\"^([0-9]+)([^0-9])$\", text)\n\t\tif m != None:\n\t\t\treturn _handleCommand(m.group(2), int(m.group(1)))\n\t\t\t\n\telif slen == 1:\n\t\t# Try for a single-letter command\n\t\treturn _handleCommand(text, 1)\n\t\t\n\treturn text\n\ndef evalCommandEnter(text):\n\t\"\"\" Handle a command that the user has pressed Enter on \"\"\"\n\tslen = len(text)\n\tif slen == 0:\n\t\treturn \"\"\n\t\n\tif text[0] == '/':\n\t\t# Search\n\t\tso = pn.SearchOptions()\n\t\tso.FindText = text[1:]\n\t\tpn.CurrentDoc().FindNext(so)\n\t\treturn \"\"\n\t\n\treturn \"\"\n\ndef _handleChangeCommand(command, text):\n\t\"\"\" Handle the c, d and y commands \"\"\"\n\tm = re.match(\"^([0-9]+)?((i[w\\\\(\\\\[])|[w$ld]|t(.))?$\", text)\n\tif m == None:\n\t\treturn command + text\n\t\n\ts = scintilla.Scintilla(pn.CurrentDoc())\n\t\n\ttarget = _getTarget(s)\n\t\n\ttry:\n\t\treturn _handleChangeCommandInner(command, text, m, s)\n\tfinally:\n\t\t_setTarget(s, target[0], target[1])\n\ndef _handleChangeCommandInner(command, text, m, s):\n\t\"\"\" Do all command handling, target restoration and undo block handled externally \"\"\"\n\tpos = s.CurrentPos\n\tend = -1\n\trepetitions = 1\n\tif m.group(1) != None:\n\t\trepetitions = int(m.group(1))\n\twhat = m.group(2)\n\tremainder = m.group(4)\n\t\n\t# Calculate our change target:\n\tif what == None:\n\t\treturn command + text\n\telif what == \"w\":\n\t\tend = s.WordEndPosition(pos, True)\n\t\tend = _findFurtherWordEnds(s, end, repetitions - 1)\n\telif what == \"$\":\n\t\tlineAtEnd = s.LineFromPosition(s.Length)\n\t\tline = s.LineFromPosition(pos) + (repetitions - 1)\n\t\tif line > lineAtEnd:\n\t\t\tline = lineAtEnd\n\t\tend = s.GetLineEndPosition(line)\n\telif what == \"l\":\n\t\tend = pos + repetitions\n\telif what[0] == \"t\":\n\t\tend = pos\n\t\tfor x in range(0, repetitions):\n\t\t\tpn.AddOutput(\"\\nLooking for \" + remainder + \" at \" + str(end))\n\t\t\tend = _findNext(s, remainder[0], end)\n\telif what == \"d\":\n\t\tstartLine = s.LineFromPosition(pos)\n\t\tpos = s.PositionFromLine(startLine)\n\t\t\n\t\tendLine = startLine + repetitions\n\t\tif endLine >= s.LineCount:\n\t\t\tendLine = s.LineCount - 1\n\t\t\tend = s.GetLineEndPosition(endLine)\n\t\telse:\n\t\t\tend = s.PositionFromLine(endLine)\n\telif what == \"iw\":\n\t\t# In word\n\t\tend = s.WordEndPosition(pos, True)\n\t\tpos = s.WordStartPosition(pos, True)\n\t\tend = _findFurtherWordEnds(s, end, repetitions - 1)\n\telif what == \"i(\":\n\t\t# In braces\t\n\t\tpos, end = _getBraceRange(s, '(', ')')\n\telif what == \"i[\":\n\t\t# In square braces\n\t\tpos, end = _getBraceRange(s, '[', ']')\n\t\n\tif pos == -1 or end == -1:\n\t\tpn.AddOutput(\"Failed to find the range to alter\")\n\t\t# Give up, we couldn't get a good position set.\n\t\treturn \"\"\n\t\n\t_setTarget(s, pos, end)\n\t\n\tif command == \"d\":\n\t\t# Delete\n\t\ts.ReplaceTarget(0, \"\")\n\t\treturn \"\"\n\t\t\n\telif command == \"c\":\n\t\t# Go back to the editor for overwriting the target\n\t\treturn _overwriteTargetMode(s)\n\t\t\n\telif command == \"y\":\n\t\tyankText = s.GetTextRange(pos, end)\n\t\tpn.SetClipboardText(yankText)\n\t\ts.ReplaceTarget(0, \"\")\n\t\treturn \"\"\n\ndef _findFurtherWordEnds(s, pos, repetitions):\n\tfor x in range(0, repetitions):\n\t\tpos = pos + 1\n\t\tif pos > s.Length:\n\t\t\tpos = s.Length\n\t\t\tbreak\n\t\tpos = s.WordEndPosition(pos, True)\n\treturn pos\n\ndef _getBraceRange(s, startBrace, endBrace):\n\t\"\"\" Find the range between a set of braces \"\"\"\n\tstart = _findPrev(s, startBrace, s.CurrentPos)\n\tif start == -1:\n\t\treturn (-1, 0)\n\tend = s.BraceMatch(start)\n\tif end == -1:\n\t\treturn (0, -1)\n\t\n\t# start + 1 because we want the range inside the bracket, not outside\n\treturn (start + 1, end)\n\ndef _insertMode(s):\n\t\"\"\" Put the focus back in the editor, e.g. insert mode \"\"\"\n\ts.SetFocus()\n\treturn \"\"\n\ndef _overwriteTargetMode(s):\n\t\"\"\" Begin overwriting the selected target, and put the focus back in the editor \"\"\"\n\ts.BeginOverwriteTarget()\n\ts.SetFocus()\n\treturn \"\"\n\ndef _getTarget(s):\n\treturn (s.TargetStart, s.TargetEnd)\n\ndef _setTarget(s, start, end):\n\ts.TargetStart = start\n\ts.TargetEnd = end\n\ndef _findNext(s, char, pos):\n\t\"\"\" Find the next instance of a character, or -1 if not found \"\"\"\n\tmatch = ord(char)\n\tend = s.Length\n\tpos = pos + 1\n\twhile pos < end:\n\t\tif s.GetCharAt(pos) == match:\n\t\t\treturn pos\n\t\tpos = pos + 1\n\t\n\treturn -1\n\ndef _findPrev(s, char, pos):\n\t\"\"\" Find the previous instance of a character, or -1 if not found \"\"\"\n\tmatch = ord(char)\n\tpos = pos - 1\n\twhile pos >= 0:\n\t\tif s.GetCharAt(pos) == match:\n\t\t\treturn pos\n\t\tpos = pos - 1\n\t\n\treturn -1\n\ndef _handleCommand(text, repetitions):\n\t\"\"\" Handle a simple command \"\"\"\n\tsci = scintilla.Scintilla(pn.CurrentDoc())\n\t\n\tfor x in xrange(repetitions):\n\t\tif text == 'j':\n\t\t\tsci.LineDown()\n\t\telif text == 'k':\n\t\t\tsci.LineUp()\n\t\telif text == 'h':\n\t\t\tsci.CharLeft()\n\t\telif text == 'l':\n\t\t\tsci.CharRight()\n\t\telif text == '^':\n\t\t\tsci.Home()\n\t\telif text == '$':\n\t\t\tsci.LineEnd()\n\t\telif text == 'w':\n\t\t\tsci.WordRight()\n\t\telif text == 'b':\n\t\t\tsci.WordLeft()\n\t\telif text == 'u':\n\t\t\tsci.Undo()\n\t\telif text == 'i':\n\t\t\treturn _insertMode(sci)\n\t\telse:\n\t\t\treturn text\n\t\n\treturn \"\"\n\n# Hook up our handlers:\nglue.evalCommand = evalCommand;\nglue.evalCommandEnter = evalCommandEnter;","sub_path":"pnwtl/pypn/scripts3k/pypn/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":5541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"486687690","text":"# binary min heap implementation\nclass BinHeap:\n # constructor\n def __init__(self):\n self.heap = []\n\n def parent(self,j):\n return (j-1)//2\n\n def left(self, j):\n return 2*j + 1\n\n def right(self,j):\n return 2*j + 2\n\n def hasLeft(self,j):\n return self.left(j) < self.size()\n\n def hasRight(self,j):\n return self.right(j)< self.size()\n\n def swap(self, i, j):\n t = self.heap[j]\n self.heap[j] = self.heap[i]\n self.heap[i] = t\n\n def insert(self, k):\n self.heap.append(k)\n self.upheap(self.size()-1)\n# finds minimum\n def find_min(self):\n if len(self.heap)!=0:\n smallest = self.heap[0]\n else:\n return -1\n for i in range(0,len(self.heap)):\n if self.heap[i] < smallest:\n smallest = self.heap[i]\n return smallest\n\n def del_min(self):\n min = self.find_min()\n self.heap.remove(min)\n return min\n\n def is_empty(self):\n if len(self.heap) == 0:\n return True\n else:\n return False\n\n def size(self):\n return len(self.heap)\n\n def upheap(self, i):\n parent = self.parent(i)\n if i > 0 and self.heap[i] < self.heap[parent]:\n self.swap(i, parent)\n self.upheap(parent)\n\n def downheap(self,i):\n if self.hasLeft(i):\n left = self.left(i)\n smaller = left\n if self.hasRight(i):\n right = self.right(i)\n if self.heap[right] < self.heap[left]:\n smaller = right\n if self.heap[smaller] < self.heap[i]:\n self.swap(i, smaller)\n self.downheap(smaller)\n\n def build_heap(self,List):\n self.heap = List\n self.upheap(self.size()-1)\n self.downheap(0)\n\nimport random\n\n\n# build the heap\nb = BinHeap()\nb.insert(5)\nb.insert(11)\nb.insert(3)\nb.insert(6)\nb.insert(7)\n\n# traverse the heap\nprint(b.del_min())\nprint(b.del_min())\nprint(b.del_min())\nprint(b.del_min())\nprint(b.del_min())\n\nfor i in range(0,10):\n b.insert(random.randint(0,10))\nprint(b.heap)\n\n\n\n\n\n\n\n\n","sub_path":"Assign5 2.py","file_name":"Assign5 2.py","file_ext":"py","file_size_in_byte":2160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"280466784","text":"from src.config.logger import logger\n\n\nclass ModelHelper:\n def __init__(self):\n logger.info(\"Initialize ModelHelper\")\n\n @staticmethod\n def trello_cards(trello_cards):\n cards = []\n\n for trello_card in trello_cards:\n card = {\n \"id\": str(trello_card[\"_id\"]),\n \"name\": trello_card[\"name\"],\n \"due\": trello_card[\"due\"],\n \"url\": trello_card[\"url\"],\n \"created_date\": trello_card[\"created_date\"],\n \"duration\": trello_card[\"duration\"] if \"duration\" in trello_card else 25\n }\n\n cards.append(card)\n\n return cards\n\n @staticmethod\n def user(user):\n user_entity = {\n \"id\": str(user[\"_id\"]),\n \"email\": user[\"email\"],\n \"trello_user\": user[\"trello_user\"] if \"trello_user\" in user else \"\",\n \"telegram_user\": user[\"telegram_user\"]\n if \"telegram_user\" in user else \"\"\n }\n\n return user_entity\n\n @staticmethod\n def zac_tasks(zac_tasks):\n tasks = []\n\n for zac_task in zac_tasks:\n task = {\n \"id\": str(zac_task[\"_id\"]),\n \"name\": zac_task[\"name\"],\n \"due\": zac_task[\"date\"],\n \"duration\": zac_task[\"duration\"] if \"duration\" in zac_task else 25,\n \"isConclude\": zac_task[\"isConclude\"] if \"isConclude\" in zac_task else False,\n \"isFailed\": zac_task[\"is_failed\"] if \"is_failed\" in zac_task else False\n }\n\n tasks.append(task)\n\n return tasks\n\n @staticmethod\n def zac_routines(zac_routines):\n routines = []\n\n for zac_routine in zac_routines:\n routine = {\n \"id\": str(zac_routine[\"_id\"]),\n \"name\": zac_routine[\"name\"],\n \"hour\": zac_routine[\"hour\"],\n \"duration\": zac_routine[\"duration\"] if \"duration\" in zac_routine else 25,\n \"lastCreatedDate\": zac_routine[\"lastCreatedDate\"]\n }\n\n routines.append(routine)\n\n return routines\n","sub_path":"src/helpers/model_helper.py","file_name":"model_helper.py","file_ext":"py","file_size_in_byte":2111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"354943488","text":"def main():\n print(\"MAYORES QUE EL ANTERIOR\")\n valores=int(input(\"Cuantos valores va aintroducir?? \"))\n\n if valores<=1:\n print(\"Imposible!\")\n else:\n numero=int(input(\"Escriba un número: \"))\n for _ in range(1,valores):\n segundo=int(input(f\"Escriba un numero mas grande que {numero}: \"))\n\n\n if numero>=segundo:\n print(f\"{segundo} no es mayor que {numero} \")\n numero=segundo\n\n print(\"Gracias por su coolaboracion!!\")\n\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"bucle-for(1)/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"80565674","text":"'''\nCreated on 27.04.2014\n@author: uzanto\n'''\nfrom __future__ import division\n\nimport sys\nimport os\nimport datetime as dt\nimport sqlite3\nimport numpy as np\nimport pandas as pd\n\nfrom weblib.db.CSVFile import CSVFile\nfrom weblib.misc.times import dt2ts\n\nimport stations\nimport parameters\nimport conversion\nimport wunderground\nimport interpolation\nimport graphics\n\ndef new_database(path=\"data/meteodb.sqlite\"):\n if os.path.exists(path): os.remove(path)\n db = sqlite3.connect(path)\n db.text_factory = str\n db.execute(stations.STATIONS__SQLITE)\n db.execute(parameters.PARAMETERS__SQLITE)\n init_database(db)\n db.commit()\n return db\n\ndef init_database(db):\n #import parameters ...\n for item in parameters.METEODB_PARAMETERS:\n sql = \"insert into parameters (%s) values (%s)\" % (\",\".join(item.keys()),\n \",\".join([\"?\" for X in item.keys()]))\n db.execute(sql, item.values())\n #import stations ...\n assert os.path.exists(stations.STATIONS__CSV_PATH)\n f = open(stations.STATIONS__CSV_PATH, \"r\")\n tbl = pd.read_table(f, sep=\";\")\n f.close()\n sql = \"insert into stations (%s) values (%s)\" % (\",\".join(stations.STATIONS__COLUMNS), \n \",\".join([\"?\" for i in range(len(stations.STATIONS__COLUMNS))]))\n for row in tbl.values:\n db.execute(sql, row)\n #create tables ...\n stations_list = [station_column(stations_id) for stations_id in tbl[\"id\"]]\n stations_list_str = \",\".join([\"%s float\" % X for X in stations_list])\n sql = \"create table %s (utc datetime primary key, \" + stations_list_str + \")\"\n for item in parameters.METEODB_PARAMETERS:\n db.execute(sql % item[\"name\"])\n\ndef open_database(path=None):\n if not(path):\n path = os.path.join(os.path.dirname(__file__), \"data/meteodb.sqlite\")\n assert os.path.exists(path), \"%r does not exist\" % path\n db = sqlite3.connect(path)\n return db\n\ndef close_database(db, commit=True):\n if commit:\n db.commit()\n db.close()\n\ndef station_column(stations_id):\n return \"st%d\" % stations_id\n\ndef stations_coords(db):\n dbc = db.execute(\"select lon, lat from stations\")\n res = dbc.fetchall()\n return res\n\ndef require_stations(db, parameter, stations_id):\n ''' create station if not exists '''\n sql = \"pragma table_info(%s)\" % parameter\n dbc = db.execute(sql)\n res = dbc.fetchall()\n columns = [X[1] for X in res]\n column = station_column(stations_id) \n if not(column in columns):\n sql = \"alter table %s add column %s float\" % (parameter, column)\n db.execute(sql)\n \ndef require_parameter(db, parameter):\n ''' create parameter if not exists '''\n sql = \"create table if not exists %s (utc datetime primary key)\" % parameter\n db.execute(sql)\n\ndef require_dataset(db, parameter, stations_id):\n ''' let set_value() be able to write data '''\n require_parameter(db, parameter)\n require_stations(db, parameter, stations_id)\n \ndef set_value(db, parameter, stations_id, utc, value):\n #require_dataset(db, parameter, stations_id)\n try:\n value = float(value)\n except(TypeError, ValueError):\n value = None\n \n column = station_column(stations_id)\n sql = \"select utc from %s where utc=datetime(?)\" % (parameter,)\n dbc = db.execute(sql, (utc,))\n res = dbc.fetchone()\n if res:\n sql = \"update %s set %s=? where utc=datetime(?)\" % (parameter, column)\n #print \"%s :: value=%r\" % (sql, value)\n db.execute(sql, (value, utc))\n else:\n sql = \"insert into %s (utc, %s) values (?, ?)\" % (parameter, column)\n #print \"%s :: value=%r\" % (sql, value)\n db.execute(sql, (utc, value))\n \ndef get_value(db, parameter, stations_id, utc):\n sql = \"select %s from %s where utc=datetime(?)\" % (station_column(stations_id), parameter)\n dbc = db.execute(sql, (utc,))\n res = dbc.fetchone()\n return res[0] if res else None\n\ndef get_stations_values(db, parameter, utc):\n sql = \"select * from %s where utc=datetime(?)\" % (parameter,)\n dbc = db.execute(sql, (utc,))\n res = dbc.fetchone()\n return res\n\ndef get_stations_values_mean(db, parameter, utc1, utc2):\n sql = \"select * from %s where (utc > datetime(?)) and (utc < datetime(?)) order by utc asc\" % parameter\n #print sql, utc1, utc2\n dbc = db.execute(sql, (utc1, utc2))\n res = dbc.fetchall()\n res = [X[1:] for X in res]\n res = np.array(res, dtype=np.float64)\n df = pd.DataFrame(res)\n means = list(df.mean(axis=0))\n return means\n\ndef import_wunderground(db, stations_id, icao, utc1=dt.datetime(2000,1,1), utc2=dt.datetime(2001,1,1)):\n wu_columns = dict()\n csv = CSVFile(path=\"res/wunderground_columns.csv\", separator=\";\")\n for rowid in range(csv.rows()):\n row = csv.get_row_as_dict(rowid)\n wu_columns[row[\"column\"]] = row\n csv.close()\n \n utc = utc1\n delta = utc2 - utc1\n days = delta.days\n \n day = 0\n percent = 0\n while utc <= utc2:\n if (day/days)*100.0 > percent+10:\n percent += 10\n sys.stdout.write(\"%d\" % int(percent//10))\n path = wunderground.wunderground__metar_path(icao=icao, dt=utc)\n if not(os.path.exists(path)):\n utc += dt.timedelta(days=1)\n day += 1\n continue\n if wunderground.wunderground__is_empty_file(path):\n utc += dt.timedelta(days=1)\n day += 1\n continue\n wunderground.wundergound__file2csv(path, \"wu.tmp\")\n f = open(\"wu.tmp\",\"r\")\n df = pd.read_table(f, sep=\",\", index_col=\"DateUTC\")\n f.close()\n strindex = list(df.index)\n dtindex = [dt.datetime.strptime(X, \"%Y-%m-%d %H:%M:%S\") for X in strindex]\n \n for column in df:\n parameter = wu_columns.get(column, dict()).get(\"parameter\")\n if not(parameter): continue\n from_unit = wu_columns[column][\"unit\"]\n to_unit = parameters.METEODB_PARAMETERS_DICT[parameter][\"unit\"] \n for i in range(len(dtindex)):\n value = df[column][i]\n value = conversion.convert(value, from_unit, to_unit)\n set_value(db, parameter, stations_id, dtindex[i], value)\n \n \n utc += dt.timedelta(days=1)\n day += 1\n \n sys.stdout.write(\"\\n\")\n \ndef import_wunderground_timespan(db, utc1=dt.datetime(2000,1,1), utc2=dt.datetime(2001,1,1)):\n for station in db.execute(\"select id, icao, name from stations where source='wunderground.com'\"):\n stations_id, icao, name = station\n wunderground.wunderground__download_metar(icao, utc1, utc2)\n sys.stdout.write(name)\n import_wunderground(db, stations_id, icao, utc1, utc2)\n \ndef interpolate_(db, bbox=((6,45),(15,55)), res=(0.1,0.1), parameter=\"cv_airtemp\", utc1=dt.datetime(2010,1,1,12), utc2=dt.datetime(2010,1,1,13)):\n stations = pd.DataFrame(np.array(stations_coords(db)))\n values = pd.Series(np.array(get_stations_values_mean(db, parameter, utc1, utc2)))\n st_mask = (stations[0]==stations[0]) & (stations[1]==stations[1])\n va_mask = values==values\n mask = st_mask & va_mask\n stations = stations[mask].values\n values = values[mask].values\n imap = interpolation.interpolate(loc=stations, val=values, bbox=bbox, res=res)\n return imap\n\ndef filter_array(a, minval, maxval):\n h,w = a.shape\n a2 = np.array(a)\n for y in range(h):\n for x in range(w):\n a2[y][x] = min(max(minval, a[y][x]), maxval)\n return a2\n \ndef interpole_series(db, bbox=((6,45),(15,55)), res=(0.1,0.1), parameter=\"cv_airtemp\", utc1=dt.datetime(2010,1,1), utc2=dt.datetime(2010,1,2), avrgstep=dt.timedelta(seconds=3600), step=dt.timedelta(seconds=3600)):\n minval, maxval = dict(cv_airtemp=(-40,40), cv_windspeed=(0, 40)).get(parameter, (0,0))\n result = []\n utc = utc1\n while utc <= utc2:\n imap = interpolate_(db=db, bbox=bbox, res=res, parameter=parameter, utc1=utc, utc2=utc+avrgstep)\n imap = filter_array(imap, minval, maxval)\n s_start = utc.strftime(\"%Y-%m-%d %H:%M\")\n s_stop = (utc+avrgstep).strftime(\"%Y-%m-%d %H:%M\")\n result.append(dict(bbox = bbox,\n resolution = res,\n parameter = parameter,\n dt1=utc,\n dt2=utc+avrgstep,\n imap=imap,\n title=\"%s - %s\" % (s_start, s_stop)))\n utc += step\n return result\n\n\ndef imaps2timelines(imaps, uts=True, uts_factor=1):\n res = []\n nt = len(imaps)\n [[lon1,lat1],[lon2,lat2]] = imaps[0][\"bbox\"]\n resx,resy = imaps[0][\"resolution\"]\n ny,nx = imaps[0][\"imap\"].shape\n #\n \n for y in range(ny):\n lat = lat2 - y*resy\n for x in range(nx):\n lon = lon1 + x*resx\n times = [] \n values = []\n for t in range(nt):\n times.append(imaps[t][\"dt1\"])\n values.append(imaps[t][\"imap\"][y][x])\n if uts:\n uts_start = dt2ts(times[0])\n times = [uts_factor*(dt2ts(times[i]) - uts_start) for i in range(nt)]\n res.append(dict(lon=lon, lat=lat, times=times, values=values))\n return res\n \n \n\ndef main():\n \n def test1():\n for i in range(24):\n set_value(db, parameter=\"cv_airtemp\", stations_id=0, utc=dt.datetime(2000,1,1,i), value=i-5)\n set_value(db, parameter=\"cv_airtemp\", stations_id=1, utc=dt.datetime(2000,1,1,i), value=i)\n set_value(db, parameter=\"cv_airtemp\", stations_id=2, utc=dt.datetime(2000,1,1,i), value=i+5)\n \n #db = new_database()\n db = open_database()\n \n #import_wunderground(db, stations_id=13, icao=\"EDDP\")\n #import_wunderground_timespan(db, utc1=dt.datetime(2010,1,1), utc2=dt.datetime(2010,4,1))\n \n #imap = interpolate_(db)\n #graphics.array2png(imap, \"de.png\", \"de\")\n \n mi = dict(cv_airtemp=-20.0, cv_windspeed=0.0, cv_slpressure=90000, cv_relhumidity=0.0)\n ma = dict(cv_airtemp=+40.0, cv_windspeed=20.0, cv_slpressure=110000, cv_relhumidity=1.0)\n for par in [\"cv_airtemp\",\"cv_windspeed\"]:\n imaps = interpole_series(db=db, parameter=par, bbox=((10,49),(13,52)), res=(0.1,0.1), utc1=dt.datetime(2010,3,10,9), utc2=dt.datetime(2010,3,10,9)) \n i = 0\n for d in imaps:\n folder = os.path.join(\"out2\",par)\n if not(os.path.exists(folder)):\n os.mkdir(folder)\n fn_title = d[\"title\"].replace(\" \",\"_\").replace(\":\",\"\") \n #colors = graphics.rgbcolors(ranges=graphics.COLORMAPS[par])\n graphics.array2png(d[\"imap\"], path=os.path.join(folder,\"mpl_%s.png\" % fn_title), title=d[\"title\"],\n vmin=mi[par], vmax=ma[par])\n f = open(os.path.join(folder, \"imap_%s.txt\" % fn_title), \"w\")\n f.write(str(d[\"imap\"]))\n f.close()\n \n #graphics.array2png_rgb(imap, path=os.path.join(folder,\"rgb__%s.png\" % fn_title), colors=colors)\n #graphics.array2png_grey256(imap, path=os.path.join(folder,\"grey__%s.png\" % fn_title), minval=mi[par], maxval=ma[par])\n i += 1\n \n close_database(db, commit=False)\n #close_database(db, commit=True)\n \nif __name__ == '__main__':\n main()\n","sub_path":"plx/web/meteodb/mdb_sqlite.py","file_name":"mdb_sqlite.py","file_ext":"py","file_size_in_byte":11470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"343058317","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nu'''\nподсчитать количество слов, которые являются числами в римской системе сичсления(число, менше 4000)\nXVI hjb 46 kjdfg 435 XXXX\\nxxx XXX\n'''\n\nfrom __future__ import print_function\nfrom sys import stdin, stdout\nfrom string import *\n\ndef checkio(n):\n result = ''\n for arabic, roman in zip((1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1),\n 'M CM D CD C XC L XL X IX V IV I'.split()):\n result += n // arabic * roman\n n %= arabic\n return result\n\n\ndef rome(rome_str):\n res = 0\n rome_str = rome_str.replace(\"CM\", \"DCCCC\")\n rome_str = rome_str.replace(\"CD\", \"CCCC\")\n rome_str = rome_str.replace(\"XC\", \"LXXXX\")\n rome_str = rome_str.replace(\"XL\", \"XXXX\")\n rome_str = rome_str.replace(\"IX\", \"VIIII\")\n rome_str = rome_str.replace(\"IV\", \"IIII\")\n res += rome_str.count(\"M\") * 1000\n res += rome_str.count(\"D\") * 500\n res += rome_str.count(\"C\") * 100\n res += rome_str.count(\"L\") * 50\n res += rome_str.count(\"X\") * 10\n res += rome_str.count(\"V\") * 5\n res += rome_str.count(\"I\")\n return res\n\nres = 0\n\nwords = [w for w in stdin.read().split() if len(w.strip()) > 0]\n\nfor i in words:\n if i == checkio(rome(i)):\n res += 1\n\nprint(res)\n","sub_path":"cont11lab/problems/21/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"41732005","text":"'''\nContains the main classes for MTGCollections:\n\tMTGdb() searches the mtgjson database and keeps it updated,\n\tCardCollection() defines the major collection operations and the major card operations.\n\nThis file is part of MTG Collections (https://github.com/tdekeyser/mtgcollections)\n@author: Tom De Keyser\n'''\n\nimport os\nimport re\nimport string\nimport json\nimport difflib\nimport urllib.request\n\nfrom datetime import datetime\nfrom tinydb import TinyDB, where\nfrom tinydb.operations import delete, increment, decrement\nfrom functions import url, beautify\n\npackage_path = os.path.split(os.path.realpath(__file__))[0]\n\nclass MTGdb():\n\t'''Class for manipulating the mtgjson database'''\n\t# IMPORTANT: bug in two-sided cards that separates name by '//' (see make_linewidget in functions, which replaces '/')\n\tdef __init__(self):\n\t\ttry:\n\t\t\tcard_database = open(package_path + '/db/AllSets.json')\n\t\t\tself.db = json.load(card_database)\n\t\texcept IOError:\n\t\t\tpass\n\n\tdef find_card_by_name(self, cardname, argument=None):\n\t\t'''Simple iterating find function based on cardname input. Returns a single(!) card'''\n\t\tcardname = cardname.lower()\n\t\ti = 0\n\n\t\tfor cardset in self.db:\n\t\t\tfor card in self.db[cardset]['cards']:\n\t\t\t\tif card['imageName'] == cardname:\n\t\t\t\t\tif argument == None:\n\t\t\t\t\t\treturn card\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn card[argument]\n\t\t\ti += 1\n\n\tdef fuzzy_match(self, query):\n\t\t'''\n\t\tFuzzy matching function set to 0.7;\n\t\tdifflib SequenceMatcher compares the query against the name of the card and returns a [0,1] value indicating the likeness\n\t\tEvery card is checked against the query and inserted in results if it has not been inserted yet.\n\n\t\t!! Sometimes returns funny results. Should be somewhat improved here.\n\t\t'''\n\t\tfuzzyresults = {}\n\t\ti = 1\n\n\t\tif len(query) >= 3:\n\t\t\tfor cardset in self.db:\n\t\t\t\tfor card in self.db[cardset]['cards']:\n\t\t\t\t\tif (difflib.SequenceMatcher(None, str(query.lower()), card['imageName']).ratio() >= float(0.7)) or (re.search(str(query.upper()), card['imageName'], flags=re.IGNORECASE)):\n\t\t\t\t\t\t# different cardsets may include the same card\n\t\t\t\t\t\tif not any(value['imageName'] == card['imageName'] for value in fuzzyresults.values()):\n\t\t\t\t\t\t\t# if card is a complete match, put it as first result\n\t\t\t\t\t\t\tif card['imageName'] == str(query.lower()):\n\t\t\t\t\t\t\t\tfuzzyresults[0] = card\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tfuzzyresults[i] = card\n\t\t\t\t\t\t\t\ti += 1\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tcontinue\n\t\telse:\n\t\t\traise KeyError('Length of search query should be greater than 2')\n\n\t\treturn fuzzyresults\n\n\tdef update(self):\n\t\t'''\n\t\tUpdates AllSets.json if a new version exists on mtgjson.com\n\t\t'''\n\t\tprint('Checking database...')\n\n\t\turl = 'http://mtgjson.com/json/AllSets.json'\n\n\t\tfilename = url.split('/')[-1]\n\t\ttry:\n\t\t\tu = urllib.request.urlopen(url)\n\t\t\tfilesize = int(u.length)\n\t\texcept urllib.error.URLError:\n\t\t\traise IOError\n\n\t\ttry:\n\t\t\tallsets_sz = os.stat(package_path + '/db/AllSets.json').st_size\n\t\texcept OSError:\t\n\t\t\tallsets_sz = 0\n\n\t\tif allsets_sz == filesize:\n\t\t\tprint('Database already up to date.')\n\t\telse:\n\t\t\tf = open(package_path + '/db/'+filename, 'wb')\n\t\t\tprint('Downloading: {0} Bytes: {1}'.format(filename, filesize), end=' ')\n\n\t\t\tprogress = 0\n\t\t\tblocksize = 8192\n\t\t\twhile True:\n\t\t\t\tbuffer = u.read(blocksize)\n\t\t\t\tif not buffer:\n\t\t\t\t\tprint(status)\n\t\t\t\t\tbreak\n\n\t\t\t\tprogress += len(buffer)\n\t\t\t\tstatus = r'[%3.2f%%]' % (progress *100. / filesize)\n\t\t\t\tstatus = status + chr(8)*(len(status)+1)\n\t\t\t\tprint(status, end=' ')\n\n\t\t\t\tf.write(buffer)\n\n\t\t\tf.close()\n\nclass CardCollection():\n\t'''\n\tClass for any card collection\n\t'''\n\tdef __init__(self, collection_title):\n\t\tself.cardcollection = TinyDB(package_path + '/collections/' + collection_title + '.json')\n\t\tself.collection_title = collection_title\n\t\tself.info = ''\n\t\tself.log = self.cardcollection.table('log')\n\n\tdef add_info(self, text):\n\t\tself.info = str(text)\n\n\tdef rename(self, new_name):\n\t\tlogtext1 = '\"%s\" renamed to ' % (self.collection_title)\n\n\t\tos.rename(self.collection_title+'.json', str(new_name)+'.json')\n\t\tself.collection_title = str(new_name)\n\n\t\tlogtext2 = '\"%s\"' % (self.collection_title)\n\n\t\treturn self.log.insert({str(datetime.now()): logtext1 + logtext2})\n\n\tdef purge(self):\n\t\t'''\n\t\tDelete all collection content\n\t\t'''\n\t\tself.cardcollection.purge()\n\t\tlogtext = '\"%s\" purged.' % (self.collection_title)\n\n\t\treturn self.log.insert({str(datetime.now()): logtext})\n\n\tdef sort(self):\n\t\tcreatures = []\n\t\tspells = []\n\t\tland = []\n\n\t\tfor element in self.cardcollection.all():\n\t\t\tif not element:\n\t\t\t\tcontinue\n\t\t\telif 'Creature' in element['cardinfo']['types'] or 'Planeswalker' in element['cardinfo']['types']:\n\t\t\t\tcreatures.append(element)\n\t\t\telif 'Land' in element['cardinfo']['types']:\n\t\t\t\tland.append(element)\n\t\t\telse:\n\t\t\t\tspells.append(element)\n\n\t\treturn creatures + spells + land\n\n\tdef count(self, *args):\n\t\t'''\n\t\tCounts cards (args), if blank returns total\n\t\t'''\n\t\tif not len(args):\n\t\t\tamount = 0\n\n\t\t\tfor card in self.cardcollection.all():\n\t\t\t\tif len(card):\n\t\t\t\t\tamount += card['amount']\n\n\t\t\treturn amount\n\t\telse:\n\t\t\treturn self.cardcollection.get(where('cardinfo').has('name') == args[0])['amount']\n\n\tdef export_deck(self):\n\t\tf = open(self.collection_title + '_deck.txt', 'w')\n\t\tf.write(self.collection_title+'\\n')\n\t\tf.write(beautify(x)+'\\n' for x in self.sort())\n\n\t\tf.close()\n\n\tdef export_log(self):\n\t\tf = open(self.collection_title + '_log.txt', 'w')\n\n\t\tfor logitem in self.log.all():\n\t\t\tfor key, value in logitem.items():\n\t\t\t\tlogline = '%-30s %s\\n' % (key, value)\n\t\t\t\tf.write(logline)\n\n\t\tf.close()\n\n\tdef insert(self, cardname):\n\t\t'''\n\t\tInsert new card (amount == 1) or increment amount\n\t\t'''\n\t\tif not len(self.cardcollection.search(where('cardinfo').has('name') == cardname)):\n\n\t\t\tcardinfo = MTGdb().find_card_by_name(cardname)\n\t\t\tself.cardcollection.insert({'cardinfo': cardinfo, 'amount': 1})\n\t\t\tlogtext = '\"%s\" saved to collection \"%s\".' % (cardname, self.collection_title)\n\t\t\t\n\t\telse:\n\t\t\tself.cardcollection.update(increment('amount'), where('cardinfo').has('name') == cardname)\n\t\t\tlogtext = 'Added another \"%s\" to \"%s\".' % (cardname, self.collection_title)\n\n\t\treturn self.log.insert({str(datetime.now()): logtext})\n\n\tdef remove(self, cardname):\n\t\t'''\n\t\tRemove card (amount == 1) or decrement amount\n\t\t'''\t\t\n\t\ttry:\n\t\t\ttarget_card = self.cardcollection.get(where('cardinfo').has('name') == cardname)\n\t\t\tlen(target_card)\n\t\texcept TypeError:\n\t\t\tlogtext = 'Removal error: \"{0}\" not in collection.'.format(cardname)\n\n\t\telse:\n\t\t\tif target_card['amount'] == 1:\n\n\t\t\t\tself.cardcollection.update(delete('amount'), (where('amount') == 1) & (where('cardinfo').has('name') == cardname))\n\t\t\t\tself.cardcollection.update(delete('cardinfo'), where('cardinfo').has('name') == cardname)\n\n\t\t\telse:\n\t\t\t\tself.cardcollection.update(decrement('amount'), where('cardinfo').has('name') == cardname)\n\n\t\t\tlogtext = 'Removed a \"%s\" from collection \"%s\".' % (cardname, self.collection_title)\n\n\t\treturn self.log.insert({str(datetime.now()): logtext})\n\n\tdef find(self, query):\n\t\t'''\n\t\tReturns dictionary with tinydb card entry as value (on its part also a dictionary) of a numbered search result key.\n\t\tInput can either be simple or specific.\n\t\tSpecific queries come in the form 'name=x, colors=y, ...' etc.\n\t\tSimple queries do not specify certain keys; search initialises on card name.\n\n\t\t!! This is an EXCLUSIVE search, i.e. multiple kwargs will be interpreted as kwarg AND kwarg !!\n\n\t\t>>> example_collection.find_in_collection('cmc=4')\n\t\t{\n\t\t\t1: {\n\t\t\t\tu'amount': 4,\n\t\t\t\tu'cardinfo': {\n\t\t\t\t\t\tu'layout': u'normal',\n\t\t\t\t\t\tu'name': u'Festering Newt',\n\t\t\t\t\t\tu'power': u'1',\n\t\t\t\t\t\tu'artist': u'Eric Deschamps',\n\t\t\t\t\t\tu'multiverseid': 370772,\n\t\t\t\t\t\tu'cmc': 1,\n\t\t\t\t\t\tu'number': u'98',\n\t\t\t\t\t\tu'rarity': u'Common',\n\t\t\t\t\t\tu'colors': [u'Black'],\n\t\t\t\t\t\tu'imageName': u'festering newt',\n\t\t\t\t\t\tu'text': u'When Festering Newt dies, (...).',\n\t\t\t\t\t\tu'subtypes': [u'Salamander'],\n\t\t\t\t\t\tu'manaCost': u'{B}',\n\t\t\t\t\t\tu'type': u'Creature \\u2014 Salamander',\n\t\t\t\t\t\tu'flavor': u\"Its back bubbles (...).\",\n\t\t\t\t\t\tu'types': [u'Creature'],\n\t\t\t\t\t\tu'toughness': u'1'\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t2: {\n\t\t\t\t...\n\t\t\t}\n\t\t}\n\t\t'''\n\t\tdef convert_query(query):\n\t\t\ttry:\t\t\t\t# specific query\n\t\t\t\tquerydict = {str(i.split('=')[0]).strip(): str(i.split('=')[1]) for i in query.split(',')}\n\t\t\texcept IndexError:\t# simple query\n\t\t\t\tquerydict = {'name': str(query)}\n\t\t\tfinally:\n\t\t\t\treturn querydict\n\n\t\tdef stringify(x):\n\t\t\tif type(x) == list:\n\t\t\t\treturn '\\s'.join(str(i) for i in x)\n\t\t\telse:\n\t\t\t\treturn str(x)\n\n\t\tsearch_result = {}\n\t\tsearch_index = 0\n\n\t\tfor card in self.cardcollection.all():\n\t\t\tif not card:\n\t\t\t\tcontinue\t# continue if collection has an empty string (which is left after removal)\n\t\t\telif any(search_result[i]['cardinfo']['imageName'] == card['cardinfo']['imageName'] for i in range(search_index)):\n\t\t\t\tcontinue\t# continue to next if card is already in search_result\n\t\t\telse:\n\t\t\t\ttry:\n\t\t\t\t\t# regex checks query against values of requested key\n\t\t\t\t\tif all(re.search(query.upper(), stringify(card['cardinfo'][key]), flags=re.IGNORECASE) for key, query in convert_query(query).items()):\n\t\t\t\t\t\tsearch_result[search_index] = card\n\t\t\t\t\t\tsearch_index += 1\n\t\t\t\texcept KeyError:\n\t\t\t\t\tcontinue\n\n\t\treturn search_result\n\n\tdef mcdata(self):\n\t\t'''\n\t\tProduce mana curve data\n\t\t'''\n\t\tdata = {key+1: 0 for key in range(10)}\n\t\texcempt_land = []\n\n\t\tif self.count() <= 100:\n\t\t\tfor card in self.cardcollection.all():\n\t\t\t\ttry:\n\t\t\t\t\tcmc = card['cardinfo']['cmc']\n\t\t\t\texcept KeyError:\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\tdata[cmc] += 1\n\n\t\tx = [k for k in data.keys()]\n\t\ty = [v for v in data.values()]\n\t\t\n\t\treturn {\n\t\t\t\t'x': x,\n\t\t\t\t'y': y\n\t\t\t}\n","sub_path":"mtgcollections/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":9509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"233210458","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jul 14 15:41:39 2018\n\n@author: elcok\n\"\"\"\n\nimport geopandas as gpd\nimport pandas as pd\nimport os\nimport igraph as ig\nimport numpy as np\nimport sys\nimport subprocess\nfrom shapely.geometry import Point\nimport itertools\nimport operator\nimport ast\nimport math\n\n\n\nfrom vtra.utils import load_config,extract_value_from_gdf,get_nearest_node,gdf_clip,gdf_geom_clip,count_points_in_polygon\nfrom vtra.transport_network_creation import province_shapefile_to_network, add_igraph_generalised_costs_roads\n\ndef netrev_od_pairs(start_points,end_points):\n\t\"\"\"\n\tAssign net revenue to roads assets in Vietnam\n\n\tInputs are:\n\tstart_points - GeoDataFrame of start points for shortest path analysis.\n\tend_points - GeoDataFrame of potential end points for shorest path analysis.\n\tG - iGraph network of the province.\n\tsave_edges -\n\n\tOutputs are:\n\tShapefile with all edges and the total net reveneu transferred along each edge\n\tGeoDataFrame of total net revenue transferred along each edge\n\t\"\"\"\n\tsave_paths = []\n\tfor iter_,place in start_points.iterrows():\n\t\ttry:\n\t\t\tclosest_center = end_points.loc[end_points['OBJECTID']\n\t\t\t== place['NEAREST_C_CENTER']]['NEAREST_G_NODE'].values[0]\n\n\t\t\t# get_od_pair = (place['NEAREST_G_NODE'],closest_center)\n\t\t\t# save_paths.append((str(get_od_pair),1.0*place['netrev_agri']/12.0,1.0*place['netrev_noagri']/12.0))\n\t\t\tsave_paths.append((closest_center,place['NEAREST_G_NODE'],1.0*place['netrev_agri']/12.0,1.0*place['netrev_noagri']/12.0))\n\t\texcept:\n\t\t\tprint(iter_)\n\n\n\t# od_pairs_df = pd.DataFrame(save_paths,columns = ['od_nodes','netrev_agri','netrev_noagri'])\n\t# od_pairs_df = od_pairs_df.groupby(['od_nodes'])['netrev_agri','netrev_noagri'].sum().reset_index()\n\n\tod_pairs_df = pd.DataFrame(save_paths,columns = ['origin','destination','netrev_agri','netrev_noagri'])\n\tod_pairs_df = od_pairs_df.groupby(['origin','destination'])['netrev_agri','netrev_noagri'].sum().reset_index()\n\n\treturn od_pairs_df\n\ndef crop_od_pairs(start_points,end_points,crop_name):\n\tsave_paths = []\n\tfor iter_,place in start_points.iterrows():\n\t\ttry:\n\t\t\tclosest_center = end_points.loc[end_points['OBJECTID']\n\t\t\t== place['NEAREST_C_CENTER']]['NEAREST_G_NODE'].values[0]\n\n\t\t\t# get_od_pair = (place['NEAREST_G_NODE'],closest_center)\n\t\t\t# save_paths.append((str(get_od_pair),place['tons']))\n\t\t\tsave_paths.append((closest_center,place['NEAREST_G_NODE'],place['tons']))\n\t\texcept:\n\t\t\tprint(iter_)\n\n\n\t# od_pairs_df = pd.DataFrame(save_paths,columns = ['od_nodes',crop_name])\n\t# od_pairs_df = od_pairs_df.groupby(['od_nodes'])[crop_name].sum().reset_index()\n\tod_pairs_df = pd.DataFrame(save_paths,columns = ['origin','destination',crop_name])\n\tod_pairs_df = od_pairs_df.groupby(['origin','destination'])[crop_name].sum().reset_index()\n\n\treturn od_pairs_df\n\ndef assign_minmax_rev_costs_crops(x,cost_dataframe,x_cols):\n\t'''\n\tcrop_code\tcrop_name\tmin_cost_perton\tmax_cost_perton\n\t'''\n\tmin_croprev = 0\n\tmax_croprev = 0\n\tcost_list = list(cost_dataframe.itertuples(index=False))\n\tfor cost_param in cost_list:\n\t\tif cost_param.crop_code in x_cols:\n\t\t\tmin_croprev += 1.0*cost_param.min_cost_perton*x[cost_param.crop_code]\n\t\t\tmax_croprev += 1.0*cost_param.max_cost_perton*x[cost_param.crop_code]\n\n\treturn min_croprev, max_croprev\n\ndef assign_monthly_tons_crops(x,rice_prod_dist,x_cols):\n\t'''\n\tcrop_code\tcrop_name\tmin_cost_perton\tmax_cost_perton\n\t'''\n\tmin_croptons = 0\n\tmax_croptons = 0\n\tfor x_name in x_cols:\n\t\tif x_name == 'rice':\n\t\t\tmin_croptons += (1.0*min(rice_prod_dist)*x[x_name])/30.0\n\t\t\tmax_croptons += (1.0*max(rice_prod_dist)*x[x_name])/30.0\n\t\telse:\n\t\t\tmin_croptons += (1.0*x[x_name])/365.0\n\t\t\tmax_croptons += (1.0*x[x_name])/365.0\n\n\treturn min_croptons, max_croptons\n\ndef assign_io_rev_costs_crops(x,cost_dataframe,rice_prod_dist,x_cols,ex_rate):\n\t'''\n\tcrop_code\tcrop_name\tmin_cost_perton\tmax_cost_perton\n\t'''\n\tmin_croprev = 0\n\tmax_croprev = 0\n\tcost_list = list(cost_dataframe.itertuples(index=False))\n\tfor cost_param in cost_list:\n\t\tif cost_param.crop_code in x_cols:\n\t\t\tif cost_param.crop_code == 'rice':\n\t\t\t\tmin_croprev += (1.0*min(rice_prod_dist)*ex_rate*cost_param.est_net_rev*(x[cost_param.crop_code]/cost_param.tot_tons))/30.0\n\t\t\t\tmax_croprev += (1.0*max(rice_prod_dist)*ex_rate*cost_param.est_net_rev*(x[cost_param.crop_code]/cost_param.tot_tons))/30.0\n\t\t\telse:\n\t\t\t\tmin_croprev += 1.0/365.0*(ex_rate*cost_param.est_net_rev*(x[cost_param.crop_code]/cost_param.tot_tons))\n\t\t\t\tmax_croprev += 1.0/365.0*(ex_rate*cost_param.est_net_rev*(x[cost_param.crop_code]/cost_param.tot_tons))\n\n\treturn min_croprev, max_croprev\n\nif __name__ == '__main__':\n\n\tdata_path,calc_path,output_path = load_config()['paths']['data'],load_config()['paths']['calc'],load_config()['paths']['output']\n\n\t# provinces to consider\n\tprovince_list = ['Lao Cai','Binh Dinh','Thanh Hoa']\n\tprovince_terrian = ['mountain','flat','flat']\n\t# province_list = ['Thanh Hoa']\n\tdistrict_committe_names = ['district_people_committee_points_lao_cai.shp',\n\t\t\t\t\t\t\t'district_province_peoples_committee_point_binh_dinh.shp',\n\t\t\t\t\t\t\t'district_people_committee_points_thanh_hoa.shp']\n\tcommune_committe_names = 'commune_committees_points.shp'\n\texchange_rate = 1.05*(1000000/21000)\n\tgrowth_scenarios = [(5,'low'),(6.5,'forecast'),(10,'high')]\n\tbase_year = 2016\n\n\tshp_output_path = os.path.join(output_path,'flow_mapping_shapefiles')\n\t# flow_output_excel = os.path.join(output_path,'flow_mapping_paths','province_roads_district_center_flow_ods.xlsx')\n\tflow_output_excel = os.path.join(output_path,'flow_mapping_paths','province_roads_commune_center_flow_ods.xlsx')\n\texcl_wrtr = pd.ExcelWriter(flow_output_excel)\n\n\trd_prop_file = os.path.join(data_path,'Roads','road_properties','road_properties.xlsx')\n\tprovince_path = os.path.join(data_path,'Vietnam_boundaries','who_boundaries','who_provinces.shp')\n\tpopulation_points_in = os.path.join(data_path,'Points_of_interest','population_points.shp')\n\tcommune_path = os.path.join(data_path,'Vietnam_boundaries','boundaries_stats','commune_level_stats.shp')\n\n\tcrop_data_path = os.path.join(data_path,'Agriculture_crops','crop_data')\n\trice_month_file = os.path.join(data_path,'rice_atlas_vietnam','rice_production.shp')\n\tcrop_month_fields = ['P_Jan','P_Feb','P_Mar','P_Apr','P_May','P_Jun','P_Jul','P_Aug','P_Sep','P_Oct','P_Nov','P_Dec']\n\tcrop_names = ['rice','cash','cass','teas','maiz','rubb','swpo','acof','rcof','pepp']\n\n\n\tfor prn in range(len(province_list)):\n\t# for prn in range(0,1):\n\t\tprovince_ods_df = []\n\t\tprovince = province_list[prn]\n\t\t# set all paths for all input files we are going to use\n\t\tprovince_name = province.replace(' ','').lower()\n\n\t\tedges_in = os.path.join(data_path,'Roads','{}_roads'.format(province_name),'vietbando_{}_edges.shp'.format(province_name))\n\t\tnodes_in = os.path.join(data_path,'Roads','{}_roads'.format(province_name),'vietbando_{}_nodes.shp'.format(province_name))\n\n\t\t# commune_center_in = os.path.join(data_path,'Points_of_interest',district_committe_names[prn])\n\t\tcommune_center_in = os.path.join(data_path,'Points_of_interest',commune_committe_names)\n\n\t\t# path_width_table = os.path.join(data_path,'Roads','road_properties','road_properties.xlsx')\n\n\t\t# load provinces and get geometry of the right province\n\t\tprovinces = gpd.read_file(province_path)\n\t\tprovinces = provinces.to_crs({'init': 'epsg:4326'})\n\t\tprovince_geom = provinces.loc[provinces.NAME_ENG == province].geometry.values[0]\n\n\t\t# clip all the populations to the province\n\t\tprov_pop = gdf_clip(population_points_in,province_geom)\n\t\tprov_commune_center = gdf_clip(commune_center_in,province_geom)\n\t\tif 'OBJECTID' not in prov_commune_center.columns.values.tolist():\n\t\t\tprov_commune_center['OBJECTID'] = prov_commune_center.index\n\n\t\tprov_communes = gdf_clip(commune_path,province_geom)\n\n\t\tG = province_shapefile_to_network(edges_in,province_terrian[prn],rd_prop_file)\n\t\tnodes_name = np.asarray([x['name'] for x in G.vs])\n\n\t\tdel G\n\n\t\t# load nodes of the network\n\t\tnodes = gpd.read_file(nodes_in)\n\t\tnodes = nodes[nodes['NODE_ID'].isin(nodes_name)].reset_index()\n\t\tnodes = nodes.to_crs({'init': 'epsg:4326'})\n\t\tsindex_nodes = nodes.sindex\n\n\t\t# get revenue values for each village\n\t\t# first create sindex of all villages to count number of villages in commune\n\t\tprov_pop_sindex = prov_pop.sindex\n\n\t\t# create new column in prov_communes with amount of villages\n\t\tprov_communes['n_villages'] = prov_communes.geometry.apply(lambda x: count_points_in_polygon(x,prov_pop_sindex))\n\t\tprov_communes['netrev_village'] = exchange_rate*(prov_communes['netrevenue']*prov_communes['nfirm'])/prov_communes['n_villages']\n\t\t# also get the net revenue of the agriculture sector which is called nongnghiep\n\t\tprov_communes['netrev_village_agri'] = 1.0/365.0*(prov_communes['nongnghiep']*prov_communes['netrev_village'])\n\t\tprov_communes['netrev_village_noagri'] = 1.0/365.0*(prov_communes['netrev_village'] - prov_communes['netrev_village_agri'])\n\n\n\t\tcommune_sindex = prov_communes.sindex\n\t\t# give each village a net revenue based on average per village in commune\n\t\tprov_pop['netrev_agri'] = prov_pop.geometry.apply(lambda x: extract_value_from_gdf(x,commune_sindex,prov_communes,'netrev_village_agri'))\n\t\tprov_pop['netrev_noagri'] = prov_pop.geometry.apply(lambda x: extract_value_from_gdf(x,commune_sindex,prov_communes,'netrev_village_noagri'))\n\n\n\t\t# get nearest node in network for all start and end points\n\t\tprov_pop['NEAREST_G_NODE'] = prov_pop.geometry.apply(lambda x: get_nearest_node(x,sindex_nodes,nodes,'NODE_ID'))\n\t\tprov_commune_center['NEAREST_G_NODE'] = prov_commune_center.geometry.apply(lambda x: get_nearest_node(x,sindex_nodes,nodes,'NODE_ID'))\n\n\t\t# prepare for shortest path routing, we'll use the spatial index of the centers\n\t\t# to find the nearest center for each population point\n\t\tsindex_commune_center = prov_commune_center.sindex\n\t\tprov_pop['NEAREST_C_CENTER'] = prov_pop.geometry.apply(lambda x: get_nearest_node(x,sindex_commune_center,prov_commune_center,'OBJECTID'))\n\n\t\t# find all OD pairs of the revenues\n\t\tnetrev_ods = netrev_od_pairs(prov_pop,prov_commune_center)\n\t\tprovince_ods_df.append(netrev_ods)\n\n\t\t# find the crop production months for the province\n\t\trice_prod_months = gpd.read_file(rice_month_file)\n\t\trice_prod_months = rice_prod_months.loc[rice_prod_months.SUB_REGION == province]\n\t\trice_prod_months = rice_prod_months[crop_month_fields].values.tolist()\n\t\trice_prod_months = np.array(rice_prod_months[0])/sum(rice_prod_months[0])\n\t\trice_prod_months = rice_prod_months[rice_prod_months > 0]\n\t\trice_prod_months = rice_prod_months.tolist()\n\n\n\n\t\t# all the crop OD pairs\n\t\tfor file in os.listdir(crop_data_path):\n\t\t\tif file.endswith(\".tif\") and 'spam_p' in file.lower().strip():\n\t\t\t\tfpath = os.path.join(crop_data_path, file)\n\t\t\t\tcrop_name = [cr for cr in crop_names if cr in file.lower().strip()][0]\n\t\t\t\toutCSVName = os.path.join(output_path,'crop_flows','crop_concentrations.csv')\n\t\t\t\tsubprocess.run([\"gdal2xyz.py\",'-csv', fpath,outCSVName])\n\n\t\t\t\t'''Load points and convert to geodataframe with coordinates'''\n\t\t\t\tload_points = pd.read_csv(outCSVName,header=None,names=['x','y','tons'],index_col=None)\n\t\t\t\tload_points = load_points[load_points['tons'] > 0]\n\n\t\t\t\tgeometry = [Point(xy) for xy in zip(load_points.x, load_points.y)]\n\t\t\t\tload_points = load_points.drop(['x', 'y'], axis=1)\n\t\t\t\tcrs = {'init': 'epsg:4326'}\n\t\t\t\tcrop_points = gpd.GeoDataFrame(load_points, crs=crs, geometry=geometry)\n\n\t\t\t\tdel load_points\n\n\t\t\t\t# clip all to province\n\t\t\t\tprov_crop = gdf_geom_clip(crop_points,province_geom)\n\n\t\t\t\tif len(prov_crop.index) > 0:\n\t\t\t\t\tprov_crop_sindex = prov_crop.sindex\n\t\t\t\t\tprov_crop['NEAREST_G_NODE'] = prov_crop.geometry.apply(lambda x: get_nearest_node(x,sindex_nodes,nodes,'NODE_ID'))\n\t\t\t\t\tsindex_commune_center = prov_commune_center.sindex\n\t\t\t\t\tprov_crop['NEAREST_C_CENTER'] = prov_crop.geometry.apply(lambda x: get_nearest_node(x,sindex_commune_center,prov_commune_center,'OBJECTID'))\n\n\t\t\t\t\tcrop_ods = crop_od_pairs(prov_crop,prov_commune_center,crop_name)\n\t\t\t\t\tprovince_ods_df.append(crop_ods)\n\n\t\t\t\t\tprint ('Done with crop {0} in province {1}'.format(crop_name, province_name))\n\n\t\tall_ods = pd.concat(province_ods_df, axis=0, sort = 'False', ignore_index=True).fillna(0)\n\n\t\tall_ods_crop_cols = [c for c in all_ods.columns.values.tolist() if c in crop_names]\n\t\tall_ods['crop_tot'] = all_ods[all_ods_crop_cols].sum(axis = 1)\n\n\t\t# all_ods_val_cols = [c for c in all_ods.columns.values.tolist() if c != 'od_nodes']\n\t\t# all_ods = all_ods.groupby(['od_nodes'])[all_ods_val_cols].sum().reset_index()\n\n\t\tall_ods_val_cols = [c for c in all_ods.columns.values.tolist() if c not in ('origin','destination')]\n\t\tall_ods = all_ods.groupby(['origin','destination'])[all_ods_val_cols].sum().reset_index()\n\n\t\tall_ods['croptons'] = all_ods.apply(lambda x: assign_monthly_tons_crops(x,rice_prod_months,all_ods_crop_cols),axis = 1)\n\t\tall_ods[['min_croptons', 'max_croptons']] = all_ods['croptons'].apply(pd.Series)\n\t\tall_ods.drop('croptons',axis=1,inplace=True)\n\n\t\tcost_values_df = pd.read_excel(os.path.join(crop_data_path,'crop_unit_costs.xlsx'),sheet_name ='io_rev')\n\t\tall_ods['croprev'] = all_ods.apply(lambda x: assign_io_rev_costs_crops(x,cost_values_df,rice_prod_months,all_ods.columns.values.tolist(),exchange_rate),axis = 1)\n\t\tall_ods[['min_agrirev', 'max_croprev']] = all_ods['croprev'].apply(pd.Series)\n\t\tall_ods.drop('croprev',axis=1,inplace=True)\n\t\tall_ods['max_agrirev'] = all_ods[['max_croprev','netrev_agri']].max(axis = 1)\n\t\tall_ods.drop(['max_croprev','netrev_agri'],axis=1,inplace=True)\n\n\t\tall_ods['min_netrev'] = all_ods['min_agrirev'] + all_ods['netrev_noagri']\n\t\tall_ods['max_netrev'] = all_ods['max_agrirev'] + all_ods['netrev_noagri']\n\n\t\tall_ods.to_excel(excl_wrtr,province_name,index = False)\n\t\texcl_wrtr.save()\n\n\t\t# all_ods.to_csv(os.path.join(output_path,'{}_ods.csv'.format(province_name)),index = False)\n\t\t# all_ods = all_ods[['od_pair','min_croptons','max_croptons','min_netrev','max_netrev']]\n\n\t\t# flow_output_excel = os.path.join(output_path,'flow_mapping_paths','{}_roads_od_flow_growth.xlsx'.format(province_name))\n\t\tflow_output_excel = os.path.join(output_path,'flow_mapping_paths','{}_roads_od_flow_growth_communes.xlsx'.format(province_name))\n\t\texcl_wrtr_1 = pd.ExcelWriter(flow_output_excel)\n\t\tfor grth in growth_scenarios:\n\t\t\t# all_ods = all_ods[['od_nodes','min_croptons','max_croptons','min_netrev','max_netrev']]\n\t\t\tall_ods = all_ods[['origin','destination','min_croptons','max_croptons','min_netrev','max_netrev']]\n\t\t\tfor year in range(2017,2050):\n\t\t\t\tall_ods['min_croptons_{}'.format(year)] = math.pow((1+grth[0]/100),year - base_year)*all_ods['min_croptons']\n\t\t\t\tall_ods['max_croptons_{}'.format(year)] = math.pow((1+grth[0]/100),year - base_year)*all_ods['max_croptons']\n\t\t\t\tall_ods['min_netrev_{}'.format(year)] = math.pow((1+grth[0]/100),year - base_year)*all_ods['min_netrev']\n\t\t\t\tall_ods['max_netrev_{}'.format(year)] = math.pow((1+grth[0]/100),year - base_year)*all_ods['max_netrev']\n\n\t\t\tall_ods.to_excel(excl_wrtr_1,grth[1],index = False)\n\t\t\texcl_wrtr_1.save()\n","sub_path":"src/vtra/analysis/province_flow_mapping/flow_scenarios.py","file_name":"flow_scenarios.py","file_ext":"py","file_size_in_byte":14933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"135940800","text":"class Solution(object):\r\n def findLongestChain(self, pairs):\r\n \"\"\"\r\n :type pairs: List[List[int]]\r\n :rtype: int\r\n \"\"\"\r\n pairs.sort(key = lambda x:x[1])\r\n \r\n cnt,i = 0,0\r\n for j in range(len(pairs)):\r\n if j == 0 or pairs[i][1] < pairs[j][0] :\r\n cnt += 1\r\n i = j\r\n \r\n return cnt\r\n","sub_path":"MaximumLengthOfPairChain.py","file_name":"MaximumLengthOfPairChain.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"411380916","text":"import numpy as np\nfrom os import listdir\nfrom os.path import isfile, join\nimport math\n\n\nclass Input:\n\n def __init__(self):\n self.md_path = None\n self.node_path = None\n self.element_path = None\n self.dir = -1\n self.scale = 0\n\n def configure(self, direction, length):\n self.dir = direction\n self.scale = length\n\n def load_MD(self):\n onlyfiles = [f for f in listdir(self.md_path) if isfile(join(self.md_path, f))]\n data = []\n cols = [0, 1, 2, 6]\n cnt = 0\n for f in onlyfiles:\n addr = self.md_path + f\n dl = np.loadtxt(addr, dtype=float, skiprows=2)\n for row in dl:\n line = row[cols]\n data.append(line)\n cnt += 1\n\n left = np.min(data, axis=0)\n top = np.max(data, axis=0)\n\n center = (left + top) / 2\n center[0] = left[0]\n center = center[0:3]\n\n output = np.zeros((cnt, 2), dtype=float)\n i = 0\n for line in data:\n dh = line[:3] - center\n d = math.sqrt(dh[0] * dh[0] + dh[1] * dh[1] + dh[2] * dh[2])\n r = math.pow((3.0 / 4.0 / math.pi * line[3]), (1.0 / 3.0))\n output[i, 0] = d\n output[i, 1] = r\n i += 1\n\n if self.dir != -1:\n minD = min(output[:, self.dir])\n maxD = max(output[:, self.dir])\n D = maxD - minD\n i = 0\n for line in output:\n output[i, self.dir] = (line[self.dir] - minD) / D * self.scale\n i += 1\n print('Data loaded from MD files!')\n return output\n\n def load_mesh(self, skip=0, deli=','):\n return np.loadtxt(self.element_path, dtype=int, skiprows=skip, delimiter=deli)\n print('Data loaded from Element files!')\n\n def load_nodes(self, skip=0, deli=','):\n nds = np.loadtxt(self.node_path, dtype=float, skiprows=skip, delimiter=deli)\n print('Data loaded from Node files!')\n return nds\n\n\nclass Output:\n\n def __init__(self):\n self.path = None\n self.right = False\n self.left = False\n self.top = False\n self.bottom = False\n self.domain = None\n\n def configure(self, domain):\n self.domain = domain\n\n def __add_left_edge(self):\n header = \"*Nset, nset=Left-Edge\\n\"\n nodes = self.domain.nodes\n count = 0\n with open(self.path, \"a\") as myfile:\n myfile.write(header)\n for node in nodes:\n if node[0] == self.domain.lo_bnds[0]:\n myfile.write(\"{0:d}, \".format(node.index))\n count += 1\n if count % 10 == 0:\n myfile.write(\"\\n\")\n myfile.write(\"\\n\")\n myfile.close()\n\n def __add_right_edge(self):\n header = \"*Nset, nset=Right-Edge\\n\"\n nodes = self.domain.nodes\n count = 0\n with open(self.path, \"a\") as myfile:\n myfile.write(header)\n for node in nodes:\n if node[0] == self.domain.lo_bnds[0]:\n myfile.write(\"{0:d}, \".format(node.index))\n count += 1\n if count % 10 == 0:\n myfile.write(\"\\n\")\n myfile.write(\"\\n\")\n myfile.close()\n\n def __add_top_edge(self):\n header = \"*Nset, nset=Top-Edge\\n\"\n nodes = self.domain.nodes\n count = 0\n with open(self.path, \"a\") as myfile:\n myfile.write(header)\n for node in nodes:\n if node[1] == self.domain.hi_bnds[1]:\n myfile.write(\"{0:d}, \".format(node.index))\n count += 1\n if count % 10 == 0:\n myfile.write(\"\\n\")\n myfile.write(\"\\n\")\n myfile.close()\n\n def __add_bottom_edge(self):\n header = \"*Nset, nset=Bottom-Edge\\n\"\n nodes = self.domain.nodes\n count = 0\n with open(self.path, \"a\") as myfile:\n myfile.write(header)\n for node in nodes:\n if node[1] == self.domain.lo_bnds[1]:\n myfile.write(\"{0:d}, \".format(node.index))\n count += 1\n if count % 10 == 0:\n myfile.write(\"\\n\")\n myfile.write(\"\\n\")\n myfile.close()\n\n def __add_core(self):\n nds = self.domain.nodes\n with open(self.path, \"w\") as myfile:\n myfile.write(\"*Heading\\n\")\n myfile.write(\"*Node\\n\")\n for node in nds:\n myfile.write(node.__str__())\n iele = 1\n eleSet = 0\n check = True\n while check:\n check = False\n header = False\n for ele in self.domain.elements:\n if ele.material == eleSet:\n if not header:\n if eleSet == 0:\n myfile.write(\"*Element, type=CPE3, elset=FIBERS\\n\")\n elif eleSet == 1:\n myfile.write(\"*Element, type=CPE3, elset=BULK\\n\")\n else:\n myfile.write(\"*Element, type=CPE3, elset=MATRIX{0:d}\\n\".format(eleSet - 1))\n header = True\n myfile.write(\"{0:d}, \".format(iele) + ele.__str__() + \"\\n\")\n iele += 1\n check = True\n eleSet += 1\n myfile.close()\n\n def write(self):\n self.__add_core()\n if self.top:\n self.__add_top_edge()\n if self.bottom:\n self.__add_bottom_edge()\n if self.left:\n self.__add_left_edge()\n if self.right:\n self.__add_right_edge()\n","sub_path":"ImportMD.py","file_name":"ImportMD.py","file_ext":"py","file_size_in_byte":5847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"554803745","text":"import numpy \r\nimport theano\r\nfrom theano import config\r\nimport theano.tensor as tensor\r\nimport theano.typed_list as typed_list\r\nfrom theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams\r\nfrom utils.func import _p, ortho_weight, numpy_floatX\r\nfrom utils.func import *\r\n\r\ndef param_init_lstm(options, params, prefix='lstm'):\r\n \"\"\"\r\n Init the LSTM parameter:\r\n\r\n :see: init_params\r\n \"\"\"\r\n W = numpy.concatenate([ortho_weight(options['dim_we'],options['dim_hd']),\r\n ortho_weight(options['dim_we'],options['dim_hd']),\r\n ortho_weight(options['dim_we'],options['dim_hd']),\r\n ortho_weight(options['dim_we'],options['dim_hd'])], axis=1)\r\n params[_p(prefix, 'W')] = W\r\n U = numpy.concatenate([ortho_weight(options['dim_hd'],options['dim_hd']),\r\n ortho_weight(options['dim_hd'],options['dim_hd']),\r\n ortho_weight(options['dim_hd'],options['dim_hd']),\r\n ortho_weight(options['dim_hd'],options['dim_hd'])], axis=1)\r\n params[_p(prefix, 'U')] = U\r\n b = numpy.zeros((4 * options['dim_hd'],))\r\n params[_p(prefix, 'b')] = b.astype(config.floatX)\r\n\r\n return params\r\n\r\n\r\ndef lstm_layer(tparams, state_below, options, prefix='lstm', mask=None):\r\n nsteps = state_below.shape[0]\r\n \r\n if state_below.ndim == 3:\r\n n_samples = state_below.shape[1]\r\n else:\r\n n_samples = 1\r\n\r\n assert mask is not None\r\n\r\n def _slice(_x, n, dim):\r\n if _x.ndim == 3:\r\n return _x[:, :, n * dim:(n + 1) * dim]\r\n return _x[:, n * dim:(n + 1) * dim]\r\n\r\n def _step(m_, x_, h_, c_):\r\n preact = tensor.dot(h_, tparams[_p(prefix, 'U')])\r\n preact += x_\r\n\r\n i = tensor.nnet.sigmoid(_slice(preact, 0, options['dim_hd']))\r\n f = tensor.nnet.sigmoid(_slice(preact, 1, options['dim_hd']))\r\n o = tensor.nnet.sigmoid(_slice(preact, 2, options['dim_hd']))\r\n c = tensor.tanh(_slice(preact, 3, options['dim_hd']))\r\n \r\n c = f * c_ + i * c\r\n c = m_ * c + (1. - m_) * c_\r\n\r\n h = o * tensor.tanh(c)\r\n h = m_ * h + (1. - m_) * h_\r\n \r\n return h, c\r\n\r\n state_below = (tensor.dot(state_below, tparams[_p(prefix, 'W')]) + tparams[_p(prefix, 'b')])\r\n \r\n \r\n h = tensor.alloc(numpy_floatX(0.0), n_samples, options['dim_hd'])\r\n c = tensor.alloc(numpy_floatX(0.0), n_samples, options['dim_hd'])\r\n \r\n rval, updates = theano.scan(_step,\r\n sequences=[mask, state_below],\r\n outputs_info=[h,c],\r\n name=_p(prefix, '_layers'),\r\n n_steps=nsteps)\r\n \r\n #return h\r\n return rval[0]\r\n","sub_path":"utils/lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":2800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"542543615","text":"# ===============================================================================\n#\n# Copyright (c) 2013-2018 Qualcomm Technologies, Inc.\n# All Rights Reserved.\n# Confidential and Proprietary - Qualcomm Technologies, Inc.\n#\n# ===============================================================================\n\nimport math\nimport weakref\n\nimport defines as df\nfrom sectools.common.parsegen import PAD_BYTE_0\nfrom sectools.common.parsegen.elf.header.format import extract_ehdr, \\\n create_empty_ehdr\nfrom sectools.common.parsegen.elf.header.ident import ELFCLASS32\nfrom sectools.common.parsegen.elf.section.format import extract_shdrs, \\\n repr_shdrs, pack_shdrs, extract_sections, zero_out_sections\nfrom sectools.common.parsegen.elf.segment.flags import PF_OS_SEGMENT_HASH, \\\n PF_OS_SEGMENT_PHDR\nfrom sectools.common.parsegen.elf.segment.format import extract_phdrs, repr_phdrs, \\\n pack_phdrs, extract_segments, get_phdr_class\nfrom sectools.common.parsegen.elf.segment.type import PT_LOAD\nfrom sectools.common.parsegen.elf.segment.type import PT_NULL\nfrom sectools.common.utils.c_logging import logger\nfrom sectools.common.utils.c_misc import store_debug_data_to_file\n\n\nclass ParseGenElfDelegate(object):\n\n def __init__(self, parsegen):\n self.parsegen_ref = weakref.ref(parsegen)\n\n @property\n def parsegen(self):\n return self.parsegen_ref()\n\n def segment_to_put(self, phdr):\n return (phdr.p_type == PT_LOAD or\n phdr.f_os_segment_type == PF_OS_SEGMENT_HASH or\n (phdr.p_type == PT_NULL and phdr.p_offset > 0))\n\n def process_segment_data(self, phdr, data):\n return data\n\n\nclass ParseGenElf(object):\n\n def __init__(self, data=None,\n debug_dir=None,\n debug_prefix=None,\n debug_suffix=None,\n _class=ELFCLASS32,\n delegate=None,\n elf_properties=None):\n\n # Create empty elf file is data is None\n if data is None:\n data = create_empty_elf(_class)\n\n # Set the delegate\n if delegate is None:\n self.delegate = ParseGenElfDelegate(self)\n else:\n self.delegate = delegate\n\n # Public properties\n self.debug_dir = debug_dir\n self.debug_prefix = debug_prefix\n self.debug_suffix = debug_suffix\n\n # Store the original image\n self.store_debug_data(df.FILE_DATA_IN, data)\n\n \"\"\"\n Extract the various segments/sections of the data:\n 1. Elf header\n 2. Prog headers\n 3. Bin\n \"\"\"\n # Extract the header\n self.ehdr = extract_ehdr(data)\n self.store_debug_data(df.FILE_HDR_IN, self.ehdr.pack())\n self.store_debug_data(df.FILE_HDR_IN_REPR, repr(self.ehdr), suffix=df.FILE_HDR_IN_REPR_SUFFIX)\n\n # Extract the program headers\n self.phdrs = extract_phdrs(data, self.ehdr)\n self.store_debug_data(df.FILE_PHDR_IN, pack_phdrs(self.phdrs))\n self.store_debug_data(df.FILE_PHDR_IN_REPR, repr_phdrs(self.phdrs), suffix=df.FILE_PHDR_IN_REPR_SUFFIX)\n\n # Extract the section headers\n if elf_properties and (not getattr(elf_properties, \"has_sections\", False)):\n zero_out_sections(self.ehdr)\n self.shdrs = extract_shdrs(data, self.ehdr)\n # Sort sections by whether they are encapsulated by segments\n self.encapsulated_sections_map, self.non_encapsulated_sections = self.sort_sections()\n # Extract section data from section header info and dump those which are outside segments\n self.sections = extract_sections(data, self.non_encapsulated_sections)\n for idx, shdr in enumerate(self.shdrs):\n if shdr in self.non_encapsulated_sections:\n self.store_debug_data(df.FILE_SECTION_IN.format(idx), self.sections[shdr])\n\n # Dump the individual segments\n self.segments = extract_segments(data, self.phdrs)\n for idx, phdr in enumerate(self.phdrs):\n length = len(self.segments[phdr])\n is_load = self.delegate.segment_to_put(phdr)\n if 0 <= length <= 16:\n logger.debug(('' if is_load else 'Non-') + 'Loadable segment - ' + str(idx + 1) + ' is of size: ' + str(length))\n if is_load and 0 < length <= 16:\n logger.warning(('' if is_load else 'Non-') + 'Loadable segment - ' + str(idx + 1) + ' is of size: ' + str(length))\n self.store_debug_data(df.FILE_SEGMENT_IN.format(idx), self.segments[phdr])\n\n def __repr__(self):\n retval = 'Header: ' + '\\n' + repr(self.ehdr) + '\\n' \\\n 'Program Headers: ' + '\\n' + repr_phdrs(self.phdrs)\n if self.shdrs:\n retval += '\\nSection Headers: ' + '\\n' + repr_shdrs(self.shdrs)\n return retval\n\n def store_debug_data(self, file_name, data, prefix=None, suffix=None):\n if prefix is None:\n prefix = self.debug_prefix\n if suffix is None:\n suffix = self.debug_suffix\n if prefix is not None and suffix is not None:\n store_debug_data_to_file(prefix + '_' + file_name + suffix,\n data, self.debug_dir)\n\n def get_prog_data(self):\n # Put the elf header\n data = self.ehdr.pack()\n\n # Put the program headers\n offset = self.ehdr.e_phoff\n data = data.ljust(offset, PAD_BYTE_0)\n data += pack_phdrs(self.phdrs)\n\n return data\n\n def get_data(self):\n # Get the ELF Header and Program Header data\n data = self.get_prog_data()\n\n # Get the non-encapsulated segment data\n for index, phdr in enumerate(self.phdrs):\n if self.delegate.segment_to_put(phdr):\n offset = phdr.p_offset\n segment_data = self.delegate.process_segment_data(phdr, self.segments[phdr])\n if len(segment_data):\n data = data.ljust(offset, PAD_BYTE_0)\n data = (data[:offset] + segment_data +\n data[offset + len(segment_data):])\n\n # Get the non-encapsulated section data\n for shdr, section_data in self.sections.iteritems():\n offset = shdr.sh_offset\n if len(section_data):\n data = data.ljust(offset, PAD_BYTE_0)\n data = (data[:offset] + section_data +\n data[offset + len(section_data):])\n\n # Get the Section Header data\n if self.ehdr.e_shnum:\n data = data.ljust(self.ehdr.e_shoff, PAD_BYTE_0)\n data += pack_shdrs(self.shdrs)\n\n return data\n\n def get_segment_data(self, phdr):\n if phdr.f_os_segment_type == PF_OS_SEGMENT_PHDR and len(self.segments[phdr]) == 0:\n return self.get_prog_data()\n else:\n return self.segments[phdr]\n\n def remove_segment(self, phdr):\n if phdr not in self.phdrs:\n raise RuntimeError('Given phdr does not exist in the current list.')\n\n # Remove the phdr entry\n del self.segments[phdr]\n index = self.phdrs.index(phdr)\n self.phdrs.remove(phdr)\n self.ehdr.e_phnum -= 1\n\n return index\n\n def shift(self, offset, size, align=None, after=False):\n \"\"\"\n By default, shift everything. If after == True, only\n shift segments and sections after the insertion point.\n \"\"\"\n # Update size if alignment is given\n if align:\n size = int(math.ceil(float(size)/align) * align)\n\n # Calculate the min offset of the segments and non-encapsulated sections that will need to be moved\n min_offset = None\n hdrs = self.phdrs + self.non_encapsulated_sections\n for i_hdr in hdrs:\n if i_hdr.filesz and (min_offset is None or i_hdr.offset < min_offset):\n collision_list = [(offset, offset + size), (i_hdr.offset, i_hdr.offset + i_hdr.filesz)]\n collision_list.sort(key=lambda x: x[0])\n if collision_list[0][1] > collision_list[1][0]:\n min_offset = i_hdr.offset\n\n # Shift the segments and sections\n if min_offset is not None:\n shift = offset + size - min_offset\n for i_hdr in hdrs:\n # This check does not work on shared object signing(opendsp).\n # Load segments start at p_offset = 0\n # if offset <= i_phdr.p_offset:\n if not after or i_hdr.offset + i_hdr.filesz > offset:\n # Update offset of segment or non-encapsulated section\n i_hdr.offset += shift\n # Update offsets of encapsulated sections\n if i_hdr in self.encapsulated_sections_map.keys():\n for i_shdr in self.encapsulated_sections_map[i_hdr]:\n i_shdr.sh_offset += shift\n\n # Shift the Section Header Table\n if min_offset is not None and self.ehdr.e_shnum:\n if not after or self.ehdr.e_shoff + self.ehdr.e_shentsize * self.ehdr.e_shnum > offset:\n shift = offset + size - min_offset\n self.ehdr.e_shoff += shift\n align = 4 # Section Header Table must be 4 byte aligned\n shift = align - (self.ehdr.e_shoff % align)\n if shift != align:\n self.ehdr.e_shoff += shift\n\n def add_segment(self, phdr, data, index=0, toalign=True, segment_to_put=False):\n # Check the segment to add\n if segment_to_put or self.delegate.segment_to_put(phdr):\n # Shift segments if needed\n self.shift(phdr.p_offset, phdr.p_filesz, phdr.p_align if toalign else None, after=True)\n\n # Add the phdr entry\n self.segments[phdr] = data\n self.phdrs.insert(index, phdr)\n self.ehdr.e_phnum += 1\n\n def update_segment(self, phdr, data):\n idx = self.remove_segment(phdr)\n phdr.p_filesz = len(data)\n phdr.p_memsz = phdr.p_filesz\n self.add_segment(phdr, data, idx)\n\n def get_new_phdr_entry(self):\n return get_phdr_class(self.ehdr)\n\n def stabilize_phdrs(self):\n self.ehdr.e_phoff = self.ehdr.get_size()\n\n def get_sorted_phdrs_and_encapsulated_phdrs(self, phdrs):\n offset_phdr_map = dict()\n encapsulated_segments = []\n for phdr_1 in phdrs:\n # to handle phdrs at same offset\n offset_phdr_map.setdefault(phdr_1.p_offset, []).append(phdr_1)\n for phdr_2 in phdrs:\n if phdr_1 == phdr_2 or phdr_1.p_offset > phdr_2.p_offset:\n continue\n if self.encapsulated_segment(phdr_1, phdr_2):\n encapsulated_segments.append(phdr_2)\n # Sort phdrs by offsets\n sorted_phdrs = [offset_phdr_map[key] for key in sorted(offset_phdr_map)]\n sorted_phdrs_flattened = [item for sublist in sorted_phdrs for item in sublist]\n return sorted_phdrs_flattened, encapsulated_segments\n\n @staticmethod\n def encapsulated_segment(phdr_1, phdr_2):\n # It is guaranteed that phdr_2.p_offset >= phdr_1.p_offset\n phdr_1_end = phdr_1.p_offset + phdr_1.p_filesz\n phdr_2_end = phdr_2.p_offset + phdr_2.p_filesz\n return phdr_1.p_filesz != 0 and phdr_2.p_filesz != 0 and phdr_2_end <= phdr_1_end\n\n @staticmethod\n def encapsulated_section(shdr, phdr):\n section_end = shdr.sh_offset + shdr.sh_size\n segment_end = phdr.p_offset + phdr.p_filesz\n return (shdr.sh_size != 0 and phdr.p_filesz != 0 and\n shdr.sh_offset >= phdr.p_offset and section_end <= segment_end)\n\n def sort_sections(self):\n phdr_to_shdr_map = {}\n sections_to_add = []\n for shdr in self.shdrs:\n for phdr in self.phdrs:\n if ParseGenElf.encapsulated_section(shdr, phdr):\n if phdr in phdr_to_shdr_map:\n phdr_to_shdr_map[phdr].append(shdr)\n else:\n phdr_to_shdr_map[phdr] = [shdr]\n break\n else:\n sections_to_add.append(shdr)\n\n return phdr_to_shdr_map, sections_to_add\n\n\ndef create_empty_elf(_class):\n header = create_empty_ehdr(_class)\n header.e_phentsize = get_phdr_class(header).get_size()\n return header.pack()\n","sub_path":"office1/nhlos/common/sectools/sectools/common/parsegen/elf/format.py","file_name":"format.py","file_ext":"py","file_size_in_byte":12343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"159372514","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/10/10/010 13:48 下午\n# @Author : LQX\n# @Email : qixuan.lqx@qq.com\n# @File : Json_Parser.py\n# @Software: PyCharm\n\nimport os\nimport json\nimport numpy as np\nimport PIL.Image\nimport PIL.ImageDraw\nimport base64\nimport io\nimport matplotlib.pyplot as plt\n\n# 根目录\nROOT_DIR = os.path.abspath(\".\")\ndataset_folder = os.path.join(ROOT_DIR, \"dataset\") # 训练数据目录\n\n\ndef _get_json_files(rootdir):\n list = []\n for root, dirs, files in os.walk(rootdir):\n for name in files:\n if os.path.splitext(name)[1].lower() == '.json':\n json_path = os.path.join(root, name)\n list.append(json_path)\n return list\n\n\ndef _read_json(json_path):\n # json串是一个字符串\n f = open(json_path, encoding='utf-8')\n res = f.read()\n f.close()\n json_str = json.loads(res) # 把json串,变成python的数据类型,只能转换json串内容\n return json_str\n\n\ndef _polygons_to_mask(img_shape, polygons):\n mask = np.zeros(img_shape[:2], dtype=np.uint8)\n mask = PIL.Image.fromarray(mask)\n xy = list(map(tuple, polygons))\n PIL.ImageDraw.Draw(mask).polygon(xy=xy, outline=1, fill=1)\n mask = np.array(mask, dtype=bool)\n return mask\n\n\ndef _parse_shapes(shapes, img_shape):\n '''\n parse shapes into mask_images and keypoint_dictionarys\n :param shapes:a list of shape dictionaries\n :param img_shape: shape of the mask image, [height, width] or [height, width, channels]\n :return:\n mask_img: a numpy.ndarray with shape [height, width, channels] image\n keypoints: a 3-dim numpy.ndarray with shape [width-axis, height-axis, label_index]\n '''\n polygons_dict = {'labels': [], 'points': []}\n keypoints = [] # element is [width-axis, height-axis, label_index]\n indices_of_labelnames = {'_background_': 0}\n mask_img = np.zeros(img_shape[:2], dtype=np.int32)\n\n for shape in shapes:\n label_name = shape['label']\n if label_name in indices_of_labelnames:\n label_value = indices_of_labelnames[label_name]\n else:\n label_value = len(indices_of_labelnames)\n indices_of_labelnames[label_name] = label_value\n fill_color = shape['fill_color']\n line_color = shape['line_color']\n points = shape['points']\n if len(points) > 1: # polygons\n polygons_dict['labels'].append(label_name)\n polygons_dict['points'].extend(points)\n mask = _polygons_to_mask(img_shape[:2], points)\n mask_img[mask] = indices_of_labelnames[label_name]\n else: # keypoints\n keypoints.append([points[0][0], points[0][1], indices_of_labelnames[label_name]])\n return mask_img, np.array(keypoints)\n\n\ndef _img_b64_to_arr(img_b64):\n f = io.BytesIO()\n f.write(base64.b64decode(img_b64))\n img_arr = np.array(PIL.Image.open(f))\n return img_arr\n\n\ndef _parse_json_string(json_str):\n '''\n flags = json_str['flags']\n lineColor = json_str['lineColor']\n fillColor = json_str['fillColor']\n imagePath = json_str['imagePath']\n '''\n shapes = json_str['shapes']\n imageData = json_str['imageData']\n img = _img_b64_to_arr(imageData)\n mask_img, keypoints_dict = _parse_shapes(shapes, img.shape)\n return img, mask_img, keypoints_dict\n\n\ndef parse_jsons(jsons_folder):\n filepaths = _get_json_files(jsons_folder)\n list = []\n for fp in filepaths:\n json_str = _read_json(fp)\n list.append(_parse_json_string(json_str))\n return list\n\n\ndef main():\n list = parse_jsons(dataset_folder)\n count = len(list)\n for i in range(min(5, count)):\n img, mask, _ = list[i]\n plt.subplot(121)\n plt.imshow(img)\n plt.subplot(122)\n plt.imshow(mask)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Json_Parser.py","file_name":"Json_Parser.py","file_ext":"py","file_size_in_byte":3819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"285131081","text":"#!/usr/bin/python\n\nimport timeit\nimport argparse\n\n\ndef find_max_profit(prices):\n if len(prices) == 1 or len(prices) == 0:\n return 0\n\n minNum = prices[0]\n profit = prices[1] - prices[0]\n for price in prices:\n if price < minNum:\n minNum = price\n elif(profit < price - minNum and price - minNum != 0):\n profit = price - minNum\n return profit\n# if __name__ == '__main__':\n# # This is just some code to accept inputs from the command line\n# parser = argparse.ArgumentParser(\n# description='Find max profit from prices.')\n# parser.add_argument('integers', metavar='N', type=int,\n# nargs='+', help='an integer price')\n# args = parser.parse_args()\n\n# print(\"A profit of ${profit} can be made from the stock prices {prices}.\".format(\n# profit=find_max_profit(args.integers), prices=args.integers))\n\n\nstart = timeit.default_timer()\nprint(find_max_profit([100, 90, 80, 80, 50, 20, 10]))\nstop = timeit.default_timer()\n\nprint('Time: ', stop - start)\n","sub_path":"stock_prices/stock_prices.py","file_name":"stock_prices.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"224323261","text":"# 摩尔投票法变题\nclass Solution:\n def majorityElement(self, nums: List[int]) -> List[int]:\n num1, num2 = 0, 0\n cnt1, cnt2 = 0, 0\n for num in nums:\n if num != num2 and (cnt1 == 0 or num == num1):\n num1 = num\n cnt1 += 1\n continue\n if num == num2 or cnt2 == 0:\n num2 = num\n cnt2 += 1\n continue\n cnt1, cnt2 = cnt1 - 1, cnt2 - 1\n # 计算num1, num2的个数\n cnt1, cnt2 = 0, 0\n for num in nums:\n if num == num1: cnt1 += 1\n elif num == num2: cnt2 += 1\n ans = []\n # 判断是否是大于 1/3\n if cnt1 > len(nums) // 3: ans.append(num1)\n if cnt2 > len(nums) // 3: ans.append(num2)\n return ans\n","sub_path":"229_MajorityElementII/majorityElement.py","file_name":"majorityElement.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"584474767","text":"import sys\nsys.path.insert(0, \".\")\n\nimport pandas as pd\nimport src.config as cfg\nimport src.tests.process_templates as tp\nimport src.tests.test_creation_utils as test_utils\nfrom src.tests.save_and_load import save_suite\nfrom checklist_fork.checklist.editor import Editor\nfrom checklist_fork.checklist.test_suite import TestSuite\nfrom checklist_fork.checklist.perturb import Perturb\n\nfrom typing import Dict, List\nfrom checklist_fork.checklist.eval_core import EvaluationCore\nfrom src.tests.fill_the_lexicon import read_matched_terms, fill_the_lexicon\n\nfrom .explicit_terms_suites import update_lab_dict\n\nfrom munch import Munch\nimport regex as re\nfrom collections import defaultdict\nimport src.tests.perturbation_funs as pfuns\nfrom functools import partial\nimport math\nfrom src.models.readers.read_data import read_data\nimport spacy\nfrom spacy.tokens import Doc\n\n\ndef create_names_evaluation_suite(\n editor: Editor,\n name_groups: Dict = {},\n name: str = 'male-vs-female-names',\n nsamples: int = 100,\n tpath: str = None,\n domain: str = None\n):\n \"\"\"\n If domain is given then the core will be created only on the sentences\n from that domain. But note that even if the core is created on all\n sentences -- during test time one can filter the sentences used for evalu-\n ation based on domain.\n \"\"\"\n suite = TestSuite()\n\n if not tpath:\n tpath = cfg.main_template_path\n\n # defaults to male vs female (English names)\n if not name_groups:\n name_groups = {\n \"male\": editor.lexicons['male'],\n \"female\": editor.lexicons['female']\n }\n\n # label dict maps tasks to labels\n data, meta, labels_dict = [], [], defaultdict(Munch)\n for ik in [\"person\", \"first_name\"]:\n # get templates that are suitable to be filled with names\n df_templates: pd.DataFrame = tp.get_templates(\n editor, tpath, identity_keys={ik})\n\n if domain:\n df_templates = tp.get_df_for_domain(df_templates, domain)\n\n tmp_data, tmp_meta, tmp_labels_dict =\\\n test_utils.get_grouped_data_from_template(\n editor=editor,\n df_templates=df_templates,\n nsamples=nsamples,\n identity_key=ik,\n groups=name_groups\n )\n\n data += tmp_data\n meta += tmp_meta\n update_lab_dict(labels_dict, tmp_labels_dict)\n\n ct = EvaluationCore(\n data, meta=meta, labels_dict=labels_dict,\n name=f\"{name}\", capability=\"Gender\")\n suite.add(ct)\n\n save_suite(suite, name)\n return suite, name\n\n\n# semantically grouped terms\ndef create_gendered_terms_evaluation_suite(\n editor: Editor,\n name: str = 'male-vs-female-paired-terms',\n nsamples: int = None\n):\n suite = TestSuite()\n\n df_templates_person: pd.DataFrame = tp.get_templates(\n editor, cfg.main_template_path, identity_keys={'person'})\n\n # each bundle of paired matched terms should be a munch with keys\n # term1, term2 etc.\n paired_female_male_terms: List[Munch] =\\\n read_matched_terms(\n \"matched_gendered_terms\",\n constraints={\"GROUP\": \"family\"},\n keys_to_skip={\"GROUP\", \"NEUTRAL\"})\n\n for x in paired_female_male_terms:\n for k, v in x.items():\n x[k] = f\"my {v}\"\n\n keys = paired_female_male_terms[0].keys()\n new_keys = [f\"person.{key}\" for key in keys]\n\n # label dict maps tasks to labels\n data, meta, labels_dict = test_utils.get_grouped_data_from_template(\n editor, df_templates_person,\n groups={\"person\": paired_female_male_terms},\n new_keys=new_keys,\n identity_key='person',\n nsamples=nsamples,\n )\n\n ct = EvaluationCore(\n data, meta=meta, labels_dict=labels_dict,\n name=f\"{name}\", capability=\"Gender\")\n\n suite.add(ct)\n save_suite(suite, name)\n return suite, name\n\n\ndef create_ungrouped_gender_adj_suite(\n editor: Editor,\n name: str = 'ungrouped_gender_adjs'\n):\n suite = TestSuite()\n\n df_templates = tp.get_templates(\n editor, cfg.main_template_path, identity_keys={'identity_adj'})\n\n # each group is represented by a single term\n groups = {}\n for adj in editor.lexicons['gender_adj_basic']:\n groups[adj] = adj\n\n # label dict maps tasks to labels\n data, meta, labels_dict = test_utils.get_grouped_data_from_template(\n editor=editor,\n df_templates=df_templates,\n nsamples=None,\n identity_key='identity_adj',\n groups=groups,\n )\n\n ct = EvaluationCore(\n data, meta=meta, labels_dict=labels_dict,\n name=f\"{name}\", capability=\"Gender\")\n suite.add(ct)\n\n save_suite(suite, name)\n return suite, name\n\n\ndef create_ungrouped_gender_np_suite(\n editor: Editor,\n name: str = 'ungrouped_gender_nps'\n):\n suite = TestSuite()\n\n df_templates = tp.get_templates(\n editor, cfg.main_template_path, identity_keys={'identity_np'})\n\n # each group is represented by a single term\n # get determiners for each term\n groups = {}\n for np in editor.lexicons['gender_n_basic']:\n groups[np] = editor.template('{a:x}', x=[np]).data[0]\n\n # one can also use the adjs to create 'x preson' nps\n # for np in editor.lexicons['gender_adj_basic']:\n # groups[np] = editor.template('{a:x} person', x=[np]).data[0]\n\n data, meta, labels_dict = test_utils.get_grouped_data_from_template(\n editor=editor,\n df_templates=df_templates,\n nsamples=None,\n identity_key='identity_np',\n groups=groups\n )\n\n ct = EvaluationCore(\n data, meta=meta, labels_dict=labels_dict,\n name=f\"{name}\", capability=\"Gender\")\n suite.add(ct)\n\n save_suite(suite, name)\n return suite, name\n\n\n# text classification\ndef perturbation_name_suite(\n editor: Editor,\n name: str = 'perturbation_names',\n nsamples: int = 20\n):\n suite = TestSuite()\n\n def create_core_from_perturb(\n parsed_data,\n all_labels,\n data_name,\n # that determines how the labels are added check config file for\n # supported tasks\n task,\n n_classes=None\n ):\n # we use the same tokens as the sources of perturbation for both\n # male versions of the sentences and female versions of the sentences\n # so we get exactly the same set of sentences from both perturbations\n n = nsamples\n\n all_names = set(editor.lexicons[\"all_female_names\"] +\n editor.lexicons[\"all_male_names\"])\n\n pert_fun = partial(\n pfuns.change_genders_and_names,\n male_names=editor.lexicons[\"male\"],\n female_names=editor.lexicons[\"female\"],\n target_gender=\"male\",\n terms_gender=\"male\",\n names_to_change=all_names,\n n=n,\n )\n male_ret, male_labels = Perturb.perturb(\n parsed_data, pert_fun, nsamples=None, meta=True, labels=all_labels)\n\n # female sents\n pert_fun = partial(\n pfuns.change_genders_and_names,\n male_names=editor.lexicons[\"male\"],\n female_names=editor.lexicons[\"female\"],\n target_gender=\"female\",\n terms_gender=\"female\",\n names_to_change=all_names,\n n=n,\n )\n fem_ret, fem_labels = Perturb.perturb(\n parsed_data, pert_fun, nsamples=None, meta=True, labels=all_labels)\n\n # same sentences = same labels\n assert fem_labels == male_labels\n\n data = []\n meta = []\n labels = []\n for msents, fsents, mmeta, fmeta, lab in zip(\n male_ret.data, fem_ret.data, male_ret.meta,\n fem_ret.meta, male_labels):\n\n # the first sentence is the original sentence\n assert msents[0] == fsents[0]\n template = msents[0]\n\n # info in this is a list of a single tuple with original name and\n # new name, e.g. [('Johnny', 'Kelly')], meta for the firs sent is\n # None\n identity_key = mmeta[1].info[0][0]\n\n # all sentences for both genders should be replacing the same\n # name in the original sentence\n assert all(met.info[0][0] == identity_key for met in mmeta[1:])\n assert all(met.info[0][0] == identity_key for met in fmeta[1:])\n\n male_fills = [met.info[0][1] for met in mmeta[1:]]\n female_fills = [met.info[0][1] for met in fmeta[1:]]\n\n example_meta = {\n 0: \"male\", 1: \"female\",\n \"IDENTITY_KEY\": identity_key,\n \"SAMPLE\": {\"male\": male_fills,\n \"female\": female_fills},\n \"TEMPLATE\": template\n }\n # many sentences for male group and many for female group\n # if necessary this structure is 'flattened' when the metric\n # is computed (e.g. through averaging or random pairing)\n example_data = [[sent for sent, toks in msents[1:]],\n [sent for sent, toks in fsents[1:]]]\n\n data.append(example_data)\n meta.append(example_meta)\n\n # labels is shared for all instances of that sent.\n labels.append(lab)\n\n labels_dict = {task: Munch({\"labels\": labels, \"n_classes\": n_classes})}\n return EvaluationCore(data, meta=meta, labels_dict=labels_dict,\n name=data_name, capability=\"Gender\")\n\n test_utils.add_cores_from_perturbation(\n create_core_function=partial(create_core_from_perturb, n_classes=3),\n dataset='sst-3',\n suite=suite,\n )\n\n test_utils.add_cores_from_perturbation(\n create_core_function=partial(create_core_from_perturb, n_classes=3),\n dataset='semeval-3',\n suite=suite\n )\n save_suite(suite, name)\n return suite, name, None\n\n\ndef perturbation_conll_name_suite(\n editor: Editor,\n name: str = 'perturbation_conll_names',\n nsamples: int = 10\n):\n dev_sents, dev_labels, dev_tokens = read_data(\"conll2003\", \"dev\")\n\n nlp = spacy.load('en_core_web_sm')\n\n # force spacy to use the tokens from CoNLL data\n tokens_dict = {x: y for x, y in zip(dev_sents, dev_tokens)}\n\n def custom_tokenizer(text):\n if text in tokens_dict:\n toks = tokens_dict[text]\n d = Doc(nlp.vocab, toks)\n return d\n else:\n raise ValueError('No tokenization available for input.')\n\n nlp.tokenizer = custom_tokenizer\n parsed_data = list(nlp.pipe(dev_sents))\n parsed_data_and_entities = list(zip(parsed_data, dev_labels))\n\n # we use the same tokens as the sources of perturbation for both\n # male versions of the sentences and female versions of the sentences\n # so we get exactly the same set of sentences from both perturbations\n n = nsamples\n all_names = set(editor.lexicons[\"all_female_names\"] +\n editor.lexicons[\"all_male_names\"])\n\n pert_fun = partial(\n pfuns.change_genders_and_names,\n male_names=editor.lexicons[\"male\"],\n female_names=editor.lexicons[\"female\"],\n target_gender=\"male\",\n terms_gender=\"male\",\n names_to_change=all_names,\n n=n\n )\n male_ret, male_labels = Perturb.perturb(\n parsed_data_and_entities,\n pert_fun, nsamples=None, meta=True,\n labels=dev_labels)\n\n # female sents\n pert_fun = partial(\n pfuns.change_genders_and_names,\n male_names=editor.lexicons[\"male\"],\n female_names=editor.lexicons[\"female\"],\n target_gender=\"female\",\n terms_gender=\"female\",\n names_to_change=all_names,\n n=n,\n )\n fem_ret, fem_labels = Perturb.perturb(\n parsed_data_and_entities,\n pert_fun, nsamples=None, meta=True, labels=dev_labels)\n\n # same sentences = same labels\n assert fem_labels == male_labels\n\n data = []\n meta = []\n labels = []\n for msents, fsents, mmeta, fmeta, lab in zip(\n male_ret.data, fem_ret.data, male_ret.meta,\n fem_ret.meta, male_labels):\n\n # the first sentence is the original sentence\n assert msents[0] == fsents[0]\n\n # template is the sentence and the entities (because we passed\n # parsed_data_and_entities to the perturb fun)\n template = msents[0][0]\n\n # info in this is a list of a single tuple with original name and\n # new name, e.g. [('Johnny', 'Kelly')], meta for the firs sent is\n # None\n identity_key = mmeta[1].info[0][0]\n\n # all sentences for both genders should be replacing the same\n # name in the original sentence\n assert all(met.info[0][0] == identity_key for met in mmeta[1:])\n assert all(met.info[0][0] == identity_key for met in fmeta[1:])\n\n male_fills = [met.info[0][1] for met in mmeta[1:]]\n female_fills = [met.info[0][1] for met in fmeta[1:]]\n\n male_data = []\n for sent, toks in msents[1:]:\n # toks include white spaces\n tokens_dict[sent] = [t.strip() for t in toks]\n male_data.append(sent)\n\n female_data = []\n for sent, toks in fsents[1:]:\n # toks include white spaces\n tokens_dict[sent] = [t.strip() for t in toks]\n female_data.append(sent)\n\n # many sentences for male group and many for female group\n # if necessary this structure is 'flattened' when the metric\n # is computed (e.g. through averaging or random pairing)\n example_data = [male_data, female_data]\n\n tokenized_template = custom_tokenizer(template.strip())\n tokenized_template = [\n t.text if t.text != identity_key\n else f\"@{identity_key}@\" for t in tokenized_template]\n example_meta = {\n 0: \"male\", 1: \"female\",\n \"IDENTITY_KEY\": identity_key,\n \"SAMPLE\": {\"male\": male_fills, \"female\": female_fills},\n # the following tokenization fields are important to provide\n # for sequence labeling perturbation data\n # they ensure that the model's predictions match\n # the tokens assumed by the labels and allow for mismatches\n # in tokens for identity terms\n \"TOKENIZATION_DICT\": tokens_dict,\n \"TOKENIZED_TEMPLATE\": tokenized_template,\n \"TEMPLATE\": template\n }\n\n data.append(example_data)\n meta.append(example_meta)\n\n # labels is shared for all instances of that sent.\n labels.append(lab)\n\n labels_dict = {\"NER\": Munch({\"labels\": labels, \"n_classes\": None})}\n dev_core = EvaluationCore(\n data, meta=meta, labels_dict=labels_dict,\n name=\"Dev CoNLL 2003\", capability=\"Gender\")\n suite = TestSuite()\n suite.add(dev_core)\n save_suite(suite, name)\n\n return suite, name, data\n","sub_path":"src/tests/test_suites/gender_suites.py","file_name":"gender_suites.py","file_ext":"py","file_size_in_byte":14943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"590980518","text":"planet_orbital_period = {'earth': 1, 'mercury': 0.2408467, 'venus': 0.61519726, 'mars': 1.8808158, \r\n 'jupiter': 11.862615, 'saturn': 29.447498, 'uranus': 84.016846, 'neptune': 164.79132}\r\nseconds_in_day = 60 * 60 * 24\r\n\r\ndef space_age(age, planet):\r\n planet_year = planet_orbital_period[planet] * 365.25\r\n seconds_lived = age\r\n age_on_planet = seconds_lived/(seconds_in_day * planet_year)\r\n return round(age_on_planet, 2)\r\n \r\n\r\n","sub_path":"#1_space_age.py","file_name":"#1_space_age.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"405393295","text":"def Column_name(num):\n letters=[];\n output=[];\n for i in range(26):\n letters.append(chr(65+i));\n while(num!=0):\n rem=num%26;\n output.append(letters[rem-1]);\n num-=1;\n num=int(num/26);\n \n output.reverse();\n return ''.join(output);\n\n\n\nnum=int(input());\nfor i in range(1,num+1,1):\n print(i,Column_name(i)); \n","sub_path":"Column_name_from _a_given_column_number.py","file_name":"Column_name_from _a_given_column_number.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"489272144","text":"\"\"\"\n\nModified from: https://github.com/facebookresearch/SparseConvNet/blob/master/examples/ScanNet/data.py,\n https://github.com/daveredrum/ScanRefer/blob/master/lib/dataset.py\n\nDataloader for training (BERT)\n\n\"\"\"\n\nimport logging\nimport sparseconvnet as scn\nfrom itertools import combinations\n\nimport torch, numpy as np, glob, math, torch.utils.data, scipy.ndimage, multiprocessing as mp, time, json, pickle, random\n\nfrom config_bert import *\nfrom transformers import *\n\nGLOVE_PICKLE = '../glove.p'\n\nlogging.basicConfig(level=logging.ERROR)\n\n# Mapping from object names to id\nremap = {}\nf = open('../labelids.txt', 'r')\nNYU_CLASS_IDS = f.readlines()[2:]\nfor i, line in enumerate(NYU_CLASS_IDS):\n obj_name = line.strip().split('\\t')[-1]\n remap[obj_name] = i\n\n# Load the preprocessed data\ntrain_3d = {}\ndef load_data(name):\n idx = name[0].find('scene')\n scene_name = name[0][idx:idx+12]\n return torch.load(name[0]), scene_name\nfor x in torch.utils.data.DataLoader(\n glob.glob('../train/*.pth'),\n collate_fn=load_data, num_workers=mp.cpu_count()):\n train_3d[x[1]] = x[0]\nprint('Training examples:', len(train_3d))\nloader_list = list(train_3d.keys())\n\n# Load Glove Embeddings\nwith open(GLOVE_PICKLE, 'rb') as f:\n glove = pickle.load(f)\n\n# Load the ScanRefer dataset and BERT tokenizer\nscanrefer = json.load(open('../ScanRefer/ScanRefer_filtered_train.json'))\ntokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\n\nlang = {}\nfor i, data in enumerate(scanrefer):\n scene_id = data['scene_id']\n object_id = data['object_id']\n ann_id = data['ann_id']\n\n if scene_id not in lang:\n lang[scene_id] = {'idx':[]}\n if object_id not in lang[scene_id]:\n lang[scene_id][object_id] = {}\n tokens = data['token']\n embeddings = np.zeros((MAX_DES_LEN, 300))\n for token_id in range(MAX_DES_LEN):\n if token_id < len(tokens):\n token = tokens[token_id]\n if token in glove:\n embeddings[token_id] = glove[token]\n else:\n embeddings[token_id] = glove['unk']\n lang[scene_id][object_id][ann_id] = [embeddings, len(tokens)]\n \n lang[scene_id]['idx'].append(i)\n\n#Elastic distortion\nblur0=np.ones((3,1,1)).astype('float32')/3\nblur1=np.ones((1,3,1)).astype('float32')/3\nblur2=np.ones((1,1,3)).astype('float32')/3\ndef elastic(x,gran,mag):\n bb=np.abs(x).max(0).astype(np.int32)//gran+3\n noise=[np.random.randn(bb[0],bb[1],bb[2]).astype('float32') for _ in range(3)]\n noise=[scipy.ndimage.filters.convolve(n,blur0,mode='constant',cval=0) for n in noise]\n noise=[scipy.ndimage.filters.convolve(n,blur1,mode='constant',cval=0) for n in noise]\n noise=[scipy.ndimage.filters.convolve(n,blur2,mode='constant',cval=0) for n in noise]\n noise=[scipy.ndimage.filters.convolve(n,blur0,mode='constant',cval=0) for n in noise]\n noise=[scipy.ndimage.filters.convolve(n,blur1,mode='constant',cval=0) for n in noise]\n noise=[scipy.ndimage.filters.convolve(n,blur2,mode='constant',cval=0) for n in noise]\n ax=[np.linspace(-(b-1)*gran,(b-1)*gran,b) for b in bb]\n interp=[scipy.interpolate.RegularGridInterpolator(ax,n,bounds_error=0,fill_value=0) for n in noise]\n def g(x_):\n return np.hstack([i(x_)[:,None] for i in interp])\n return x+g(x)*mag\n\ndef trainMerge(tbl):\n locs=[]\n feats=[]\n labels=[]\n ins_labels=[]\n ref_labels=[]\n num_points=[]\n scene_names=[]\n batch_ins_names=[]\n batch_lang_objID=[]\n batch_lang_objname=[]\n batch_lang_cls=[]\n batch_input_ids=[]\n batch_attention_mask=[]\n batch_sentences=[] \n batch_tokens=[]\n\n batch_ref_lbl=[]\n for idx,scene_id in enumerate(tbl):\n scene_dict = lang[scene_id]\n refer_idxs = lang[scene_id]['idx']\n lang_objID=[]\n lang_objname=[]\n lang_cls=[]\n sentences=[]\n tokens=[]\n input_ids=[]\n attention_mask=[]\n for i in refer_idxs:\n scene_id = scanrefer[i]['scene_id'] \n object_id = scanrefer[i]['object_id']\n ann_id = scanrefer[i]['ann_id']\n object_name = scanrefer[i]['object_name']\n object_name = ' '.join(object_name.split('_'))\n \n lang_objID.append(int(object_id))\n lang_objname.append(object_name)\n sentences.append(scanrefer[i]['description'])\n token_dict = tokenizer.encode_plus(scanrefer[i]['description'], add_special_tokens=True, max_length=80, pad_to_max_length=True, return_attention_mask=True,return_tensors='pt',)\n input_ids.append(token_dict['input_ids']) \n attention_mask.append(token_dict['attention_mask'])\n tokens.append(scanrefer[i]['token'])\n if object_name not in remap:\n lang_cls.append(-100)\n else:\n lang_cls.append(remap[object_name])\n \n # Obj_num, \n lang_objID = torch.LongTensor(lang_objID)\n lang_cls=torch.LongTensor(lang_cls)\n\n input_ids = torch.cat(input_ids, 0)\n attention_mask = torch.cat(attention_mask, 0)\n batch_input_ids.append(input_ids)\n batch_attention_mask.append(attention_mask)\n\n batch_lang_objID.append(lang_objID)\n batch_lang_objname.append(np.array(lang_objname))\n batch_lang_cls.append(lang_cls)\n batch_sentences.append(sentences)\n batch_tokens.append(tokens)\n \n a,b,c,d=train_3d[scene_id]\n m=np.eye(3)+np.random.randn(3,3)*0.1\n m[0][0]*=np.random.randint(0,2)*2-1\n m*=scale\n theta=np.random.rand()*2*math.pi\n rot = np.array([[math.cos(theta),math.sin(theta),0],[-math.sin(theta),math.cos(theta),0],[0,0,1]])\n m = np.matmul(m, rot)\n a=np.matmul(a,m)\n\n if elastic_deformation:\n a=elastic(a,6*scale//50,40*scale/50)\n a=elastic(a,20*scale//50,160*scale/50)\n m=a.min(0)\n M=a.max(0)\n q=M-m\n offset=-m+np.clip(full_scale-M+m-0.001,0,None)*np.random.rand(3)+np.clip(full_scale-M+m+0.001,None,0)*np.random.rand(3)\n a+=offset\n idxs=(a.min(1)>=0)*(a.max(1)= len(string) or char != string[i+1]):\n compressed_string += char + str(count)\n count = 0\n\n if len(compressed_string) < len(string):\n return compressed_string\n return string\n","sub_path":"Chapter1/1.6.py","file_name":"1.6.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"582175487","text":"import re, string, unicodedata, codecs, logging, random, json\nimport nltk, itertools\nfrom nltk.tokenize import word_tokenize, sent_tokenize, TweetTokenizer\nfrom nltk.stem import LancasterStemmer, PorterStemmer,WordNetLemmatizer\nfrom collections import Counter\nfrom torch import LongTensor\nfrom torch.autograd import Variable\nimport numpy as np\n\ndef to_lowercase(words):\n return [word.lower() for word in words]\n\ndef tokenize(sentence):\n words = nltk.word_tokenize(sentence)\n words = to_lowercase(words)\n return words\n\ndef tokenize_text_generator(gen):\n word2id, id2word = Counter(), Counter()\n seq2words = []\n while True:\n try:\n label, sent1, sent2 = next(gen)\n tokenized_sent1, tokenized_sent2 = tokenize(sent1), tokenize(sent2)\n for w in tokenized_sent1 + tokenized_sent2:\n if not w in word2id.keys():\n word2id[w] = len(id2word)\n id2word[word2id[w]] = w \n seq2words.append((tokenized_sent1, tokenized_sent2))\n except StopIteration:\n print(\"End of dataset\")\n\n return word2id, id2word, seq2words\n\ndef tokenize_text(text):\n word2id, id2word = {}, {}\n seq2words, labels = [], []\n label_conversion = {'entailment': 0, 'contradiction': 1, 'neutral': 2}\n special_words = ['', '', '', '']\n \n for word in special_words:\n word2id[word] = len(id2word)\n id2word[word2id[word]] = word\n\n for i, triple in enumerate(text):\n tokenized_sent1, tokenized_sent2 = tokenize(triple[1]), tokenize(triple[2])\n for w in tokenized_sent1 + tokenized_sent2:\n if not w in word2id.keys():\n word2id[w] = len(id2word)\n id2word[word2id[w]] = w\n \n tokenized_sent1 = [id2word[1]] + tokenized_sent1 + [id2word[2]]\n tokenized_sent2 = [id2word[1]] + tokenized_sent2 + [id2word[2]]\n seq2words.append((tokenized_sent1, tokenized_sent2))\n labels.append(label_conversion[triple[0]])\n \n if i % 10000 == 0:\n print(\"round {}\".format(i))\n\n return word2id, id2word, seq2words, labels\n\ndef find_longest_sentece(seq2words):\n return max(np.array([max(len(pair[0]), len(pair[1])) for pair in seq2words]))\n \ndef padding_filling(seq2words, max_len_sent):\n for sent in seq2words:\n sent.extend([''] * (max_len_sent - len(sent)))\n return seq2words\n\ndef create_one_batch(batch, word2id, config, max_len_sent, oov='', pad=''):\n batch_size = len(batch)\n padding_filling(batch, max_len_sent)\n\n oov_id, pad_id = word2id.get(oov, None), word2id.get(pad, None)\n batch_w = LongTensor(batch_size, max_len_sent)\n for i, batch_i in enumerate(batch):\n for j, batch_ij in enumerate(batch_i):\n batch_w[i][j] = word2id.get(batch_ij, oov_id)\n\n return batch_w\n\ndef create_batches(seq2words, labels, word2embed, batch_size, word2id, config, max_len_sent, use_cuda=False):\n #seq2words = list(itertools.chain.from_iterable(seq2words))\n sum_len = 0.0\n batches_w, batches_labels = [], []\n size = batch_size\n print(\"Seq2words size : \", len(seq2words))\n nbatch = (len(seq2words) - 1) // size + 1\n print(\"Nos of batches is \", nbatch)\n\n for i in range(nbatch):\n if i%500 == 0:\n print(\"BATCH {}\".format(i))\n start_id, end_id = i * size, (i + 1) * size\n decompress = list(map(list, zip(*seq2words[start_id: end_id])))\n batch_labels = labels[start_id: end_id]\n to_add = sum(len(sent) for sent in decompress[0] + decompress[1])\n\n pre_words = create_one_batch(decompress[0], word2id, config, max_len_sent) \n hypo_words = create_one_batch(decompress[1], word2id, config, max_len_sent)\n\n sum_len += to_add\n batches_w.append((pre_words, hypo_words))\n batches_labels.append(Variable(LongTensor(batch_labels)))\n\n logging.info(\"{} batches, avg len: {:.1f}\".format(nbatch, sum_len / 2*len(seq2words)))\n return batches_w, batches_labels\n","sub_path":"NLI/utils/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":4052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"229115511","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\nn=input('digite a quantidade de valores:')\na=[]\nsoma=0\nfor i in range (0,n,1):\n a.append(input('digite um valor:'))\n x=(soma+a[i])/n\n\nprint('%.2f'%a[0])\nprint('%.2f'%a[n-1])\nprint('%.2f'%x)\nprint(a)\n\n\n\n","sub_path":"moodledata/vpl_data/43/usersdata/97/14184/submittedfiles/mediaLista.py","file_name":"mediaLista.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"5451801","text":"import json\nimport owlready2 as owl\n\n\nuberon = owl.get_ontology('./uberon.owl').load()\n## 'http://purl.obolibrary.org/obo/uberon.owl'\n\nobo = uberon.get_namespace(\"http://purl.obolibrary.org/obo/\")\n\nANATOMICAL_SYSTEM = 'UBERON_0000467'\n\nsummary = {}\nanatomical_systems = []\nfor c in uberon.classes():\n if c.name.startswith('UBERON_'):\n is_a = []\n part_of = []\n for super_class in c.is_a:\n if (isinstance(super_class, owl.entity.ThingClass)\n and super_class.name.startswith('UBERON_')):\n is_a.append(super_class.name)\n elif (isinstance(super_class, owl.class_construct.Restriction)\n and super_class.property == obo.BFO_0000050\n and super_class.value.name.startswith('UBERON_')):\n part_of.append(super_class.value.name)\n\n if ANATOMICAL_SYSTEM in is_a and len(part_of) == 0:\n anatomical_systems.append(c.name)\n\n summary[c.name] = { 'is_a': is_a,\n 'label': c.label[0] if c.label else '',\n 'part_of': part_of,\n }\n\nwith open('uberon.json', 'w') as fp:\n json.dump(summary, fp, indent=4)\n\nprint('Anatomical Systems:')\nfor id in anatomical_systems:\n print(' {} {}'.format(id, summary[id]['label'] if id in summary else ''))\n","sub_path":"ontology/uberon.py","file_name":"uberon.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"281231749","text":"# encoding: utf-8\nfrom django.contrib import auth\nfrom django.contrib.auth.decorators import *\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import *\nfrom django.http import *\nfrom ..models import *\nfrom .. import Utils\n\nimport json\nimport time\n\nfrom DjangoUeditor.forms import UEditorField\nfrom django import forms\n\n\n\n\nclass TestUEditorForm(forms.Form):\n content = UEditorField(u\"\", initial=\"abc\")\n\ndef resetPassword(request):\n return None\n\n@login_required\ndef getProfile(request):\n username = request.session.get('username', '')\n content = {\n \"username\": username\n }\n csrfContext = RequestContext(request, content)\n return render_to_response(\"profile/profile.html\", csrfContext)\n\ndef getPerson(request):\n username = request.session['username']\n assert username\n return Person.objects.get(username=username)\n\n\n@login_required\ndef updateProfile(request):\n return None\n\ndef getUserComments(request, user_id):\n return None\n\n@login_required\ndef postJournal(request):\n \"\"\"\n 发表攻略\n \"\"\"\n if request.method == \"GET\":\n username = request.session.get('username', '')\n form = TestUEditorForm()\n content = {\n \"username\": username,\n \"form\": form\n }\n csrfContext = RequestContext(request, content)\n return render_to_response(\"profile/post.html\", csrfContext)\n else:\n title = request.POST.get('title', '')\n dateTime = request.POST.get('dateTime', '')\n scenery = request.POST.getlist('scenery-tag', '')\n content = request.POST.get('content', '')\n\n \n\ndef getUserComments(request):\n\tpass\n\n\n@login_required\ndef getUserProfile(request, username):\n \"\"\"\n 渲染用户信息界面\n \"\"\"\n if request.method == 'GET':\n user = Person.objects.get(username=username)\n context = RequestContext(request, {\n \"username\": user.username,\n \"email\": user.email,\n \"interest\": user.interest,\n \"gender\": user.gender,\n \"activitys\": user.activitys,\n \"scenerys\": user.scenerys,\n })\n return HttpResponse(\"User id: %s\" % username)\n\n\n\ndef getPersonActivities(request, person_id):\n \"\"\"\n find all personal activities according to person_id\n \"\"\"\n reqPerson = Person.objects.get(pk=person_id)\n context = RequestContext(request, {\n \"reqPerson\": reqPerson,\n })\n return HttpResponse(\"\")\n\n@login_required\ndef getPersonActivities(request):\n \"\"\"\n refer to ManyToManyField doc\n \"\"\"\n if request.method == \"GET\":\n username = request.session['username']\n assert username\n reqPerson = Person.objects.get(username=username)\n activities = [a.name for a in list(reqPerson.activitys.all())]\n return HttpResponse(json.dump(activities))","sub_path":"traveler_pal/app/views/u.py","file_name":"u.py","file_ext":"py","file_size_in_byte":2832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"570054993","text":"# Copyright 2012 Gregory Holt\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\"\"\"\nContains a simple daemon that just logs a status line every so often.\nThis can be a good starting point for other daemons. See the source\nfor what's implemented and why.\n\nSee DaemonSample.parse_conf for configuration options.\n\"\"\"\n\nfrom time import time\n\nfrom eventlet import sleep\n\n\nclass DaemonSample(object):\n \"\"\"\n A simple daemon that just logs a status line every so often. This\n can be a good starting point for other daemons. See the source\n for what's implemented and why.\n\n :param name: The name of the daemon, indicates the daemon's\n section in the overall configuration for the WSGI\n server.\n :param parsed_conf: The conf result from parse_conf.\n \"\"\"\n\n def __init__(self, name, parsed_conf):\n # Copy all items from the parsed_conf to actual instance attributes.\n for k, v in parsed_conf.iteritems():\n setattr(self, k, v)\n self.name = name\n\n def __call__(self, subserver, stats):\n \"\"\"\n This sample daemon simply logs a status line every so often.\n\n This is the main entry point to the daemon. The brimd\n subserver will spawn a subprocess, create an instance of this\n daemon, and call this method. If the method exits for any\n reason, brimd will spawn a new subprocess, create a new\n daemon instance, and call this method again to ensure the\n daemon is always running.\n\n The stats object will have at least the stat variables asked\n for in stats_conf. This stats object will support the\n following methods:\n\n get()\n\n Return the int value of the stat .\n\n set(, value)\n\n Sets the value of the stat . The value will be\n treated as an unsigned integer.\n\n incr()\n\n Increments the value of the stat by 1.\n\n :param subserver: The brim.server.Subserver that is managing\n this daemon.\n :param stats: Shared memory statistics object as defined\n above.\n \"\"\"\n iteration = 0\n while True:\n iteration += 1\n subserver.logger.info(\n '%s sample daemon log line %s' % (self.name, iteration))\n stats.set('last_run', time())\n stats.set('iterations', iteration)\n sleep(self.interval)\n\n @classmethod\n def parse_conf(cls, name, conf):\n \"\"\"\n Translates the overall server configuration into an\n daemon-specific configuration dict suitable for passing as\n ``parsed_conf`` in the DaemonSample constructor.\n\n Sample Configuration File::\n\n [daemon_sample]\n call = brim.daemon_sample.DaemonSample\n # interval = \n # The number of seconds between each status line logged.\n # Default: 60\n\n :param name: The name of the daemon, indicates the daemon's\n section in the overall configuration for the\n server.\n :param conf: The brim.conf.Conf instance representing the\n overall configuration of the server.\n :returns: A dict suitable for passing as ``parsed_conf`` in\n the DaemonSample constructor.\n \"\"\"\n return {'interval': conf.get_int(name, 'interval', 60)}\n\n @classmethod\n def stats_conf(cls, name, parsed_conf):\n \"\"\"\n Returns a list of names that specifies the stat variables this app\n wants established.\n\n Retreiving stats can be accomplished through WSGI apps like\n brim.stats.Stats.\n\n :param name: The name of the app, indicates the app's section\n in the overall configuration for the WSGI\n server.\n :param parsed_conf: The conf result from parse_conf.\n \"\"\"\n return ['iterations', 'last_run']\n","sub_path":"brim/daemon_sample.py","file_name":"daemon_sample.py","file_ext":"py","file_size_in_byte":4502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"578074889","text":"\"\"\"\n\n\nЗадачи сортировки и поиска\n--------------------------\n\nЧто такое задача фильтрации?\nЭто задача поиска.\n\n\nИгра \"Двадцать вопросов\"\n------------------------\nЗагадайте число от 0 до n-1\nЯ называю число, а Вы говорите угадал я или нет\nЕсли нет, то Вы говорите число слишком большое или слишком маленькое.\n\n\nИзменпим задачу\n---------------\nИзменим вопрос: Действительно ли загаданное число больше m\nОтветы: да, нет\nn примем степенями числа 2\n\n\n >>> A = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n # >>> bisect(A, 7)\n # 7\n # >>> bisect(A, 0)\n # 0\n\n >>> from bisect import bisect\n >>> [bisect(A, x) for x in A]\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\n >>> [my_bisect(A, x) for x in A]\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\n\"\"\"\n\n\ndef my_bisect(A, x):\n lo = 0\n hi = len(A)\n while lo < hi:\n m = (lo + hi) // 2\n if x < A[m]:\n hi = m\n else:\n lo = m + 1\n return lo\n","sub_path":"source/algorithms/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"430354995","text":"# =================================================================\n# Author: Lucas Berg\n#\n# Program that plot the APD over a line\n# This script only works if the grid is a plain tissue\n# =================================================================\n\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.interpolate import interp1d\nfrom scipy import interpolate\n\ndef calculate_rms (y_true, y_pred):\n loss = np.sqrt(np.mean(np.square(((y_true - y_pred) / y_true))))\n\n return loss\n\ndef plot_apd_over_a_line (x, apd_1, apd_2, apd_3, apd_4, apd_4_1):\n\n x_numpy = np.asarray(x)\n apd1_numpy = np.asarray(apd_1)\n apd2_numpy = np.asarray(apd_2)\n apd3_numpy = np.asarray(apd_3)\n apd4_numpy = np.asarray(apd_4)\n apd4_1_numpy = np.asarray(apd_4_1)\n\n rms_12 = calculate_rms(apd1_numpy,apd2_numpy)\n rms_13 = calculate_rms(apd1_numpy,apd3_numpy)\n rms_14 = calculate_rms(apd1_numpy,apd4_numpy)\n rms_14_1 = calculate_rms(apd1_numpy,apd4_1_numpy)\n\n plt.grid()\n plt.plot(x,apd_1,label=\"SC1\",linewidth=1.0)\n plt.plot(x,apd_2,label=\"SC2\",linewidth=1.0)\n plt.xlabel(\"x (um)\",fontsize=15)\n plt.ylabel(\"APD (ms)\",fontsize=15)\n plt.title(\"RMS = %g\" % (rms_12),fontsize=14)\n plt.legend(loc=0,fontsize=14)\n #plt.savefig(\"output/apd-comparison-sc1-sc2.pdf\")\n plt.savefig(\"output/apd-comparison-sc1-sc2.png\")\n\n plt.clf()\n plt.grid()\n plt.plot(x,apd_1,label=\"SC1\",linewidth=1.0)\n plt.plot(x,apd_3,label=\"SC3\",linewidth=1.0)\n plt.xlabel(\"x (um)\",fontsize=15)\n plt.ylabel(\"APD (ms)\",fontsize=15)\n plt.title(\"RMS = %g\" % (rms_13),fontsize=14)\n plt.legend(loc=0,fontsize=14)\n #plt.savefig(\"output/apd-comparison-sc1-sc3.pdf\")\n plt.savefig(\"output/apd-comparison-sc1-sc3.png\")\n\n plt.clf()\n plt.grid()\n plt.plot(x,apd_1,label=\"SC1\",linewidth=1.0)\n plt.plot(x,apd_4,label=\"SC4\",linewidth=1.0)\n plt.xlabel(\"x (um)\",fontsize=15)\n plt.ylabel(\"APD (ms)\",fontsize=15)\n plt.title(\"RMS = %g\" % (rms_14),fontsize=14)\n plt.legend(loc=0,fontsize=14)\n #plt.savefig(\"output/apd-comparison-sc1-sc4.pdf\")\n plt.savefig(\"output/apd-comparison-sc1-sc4.png\")\n\n plt.clf()\n plt.grid()\n plt.plot(x,apd_1,label=\"SC1\",linewidth=1.0)\n plt.plot(x,apd_4_1,label=\"SC4_1\",linewidth=1.0)\n plt.xlabel(\"x (um)\",fontsize=15)\n plt.ylabel(\"APD (ms)\",fontsize=15)\n plt.title(\"RMS = %g\" % (rms_14_1),fontsize=14)\n plt.legend(loc=0,fontsize=14)\n #plt.savefig(\"output/apd-comparison-sc1-sc4_1.pdf\")\n plt.savefig(\"output/apd-comparison-sc1-sc4_1.png\")\n\n\ndef main():\n\t\n if len(sys.argv) != 7:\n print(\"-------------------------------------------------------------------------------------------------------------------------------------------------------------------------\")\n print(\"Usage:> python %s \" % sys.argv[0])\n print(\"-------------------------------------------------------------------------------------------------------------------------------------------------------------------------\")\n print(\" = Input file with the sorted positions of each cell\")\n print(\" = Input file with the APD of each cell\")\n print(\"-------------------------------------------------------------------------------------------------------------------------------------------------------------------------\")\n print(\"Example:> python %s inputs/cells_positions_inside_region.txt outputs/cells-apd-inside-region.txt\" % sys.argv[0])\n return 1\n\n sorted_cells_position_filename = sys.argv[1]\n cells_apd_filename_1 = sys.argv[2]\n cells_apd_filename_2 = sys.argv[3]\n cells_apd_filename_3 = sys.argv[4]\n cells_apd_filename_4 = sys.argv[5]\n cells_apd_filename_4_1 = sys.argv[6]\n\n # Read the input files as Numpy arrays\n print(\"Reading inputs files ...\") \n sorted_cells_positions = np.genfromtxt(sorted_cells_position_filename)\n cells_apd_1 = np.genfromtxt(cells_apd_filename_1) # The cells APD are unordered !!!\n cells_apd_2 = np.genfromtxt(cells_apd_filename_2) # The cells APD are unordered !!!\n cells_apd_3 = np.genfromtxt(cells_apd_filename_3) # The cells APD are unordered !!!\n cells_apd_4 = np.genfromtxt(cells_apd_filename_4) # The cells APD are unordered !!!\n cells_apd_5 = np.genfromtxt(cells_apd_filename_4_1) # The cells APD are unordered !!!\n\n # Get the index and x positions of each cell\n sorted_ids = []\n for i in range(len(sorted_cells_positions)):\n sorted_ids.append(int(sorted_cells_positions[i][0]))\n sorted_x = sorted_cells_positions[:,1]\n\n mean_apd_column_1 = []\n mean_apd_column_2 = []\n mean_apd_column_3 = []\n mean_apd_column_4 = []\n mean_apd_column_4_1 = []\n x_plot = []\n dx = 100.0\n for i in range(200):\n cells_inside_column = []\n \n minx = i*dx\n maxx = (i+1)*dx\n\n x_plot.append(i*dx + (dx/2.0))\n\n print(\"Getting cells inside interval [%g,%g] ...\" % (minx,maxx))\n for j in range(len(sorted_x)):\n if (sorted_x[j] > minx and sorted_x[j] < maxx):\n cells_inside_column.append(sorted_ids[j])\n \n mean_apd_1 = 0.0\n mean_apd_2 = 0.0\n mean_apd_3 = 0.0\n mean_apd_4 = 0.0\n mean_apd_5 = 0.0\n for j in range(len(cells_inside_column)):\n index = cells_inside_column[j]\n apd_1 = cells_apd_1[index]\n apd_2 = cells_apd_2[index]\n apd_3 = cells_apd_3[index]\n apd_4 = cells_apd_4[index]\n apd_5 = cells_apd_5[index]\n #print(\"%d %g %g %g %g\" % (index,sorted_cells_positions[j][1],sorted_cells_positions[j][2],sorted_cells_positions[j][3],cells_apd[index]))\n\n mean_apd_1 = mean_apd_1 + apd_1\n mean_apd_2 = mean_apd_2 + apd_2\n mean_apd_3 = mean_apd_3 + apd_3\n mean_apd_4 = mean_apd_4 + apd_4\n mean_apd_5 = mean_apd_5 + apd_5\n mean_apd_1 = mean_apd_1 / len(cells_inside_column)\n mean_apd_2 = mean_apd_2 / len(cells_inside_column)\n mean_apd_3 = mean_apd_3 / len(cells_inside_column)\n mean_apd_4 = mean_apd_4 / len(cells_inside_column)\n mean_apd_5 = mean_apd_5 / len(cells_inside_column)\n mean_apd_column_1.append(mean_apd_1)\n mean_apd_column_2.append(mean_apd_2)\n mean_apd_column_3.append(mean_apd_3)\n mean_apd_column_4.append(mean_apd_4)\n mean_apd_column_4_1.append(mean_apd_5)\n \n #print(x_plot)\n #print(mean_apd_column)\n\n plot_apd_over_a_line(x_plot,mean_apd_column_1,mean_apd_column_2,mean_apd_column_3,mean_apd_column_4,mean_apd_column_4_1)\n \n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"scripts/elnaz/calc_apd_specific_cells/plot_mean_apd_over_column.py","file_name":"plot_mean_apd_over_column.py","file_ext":"py","file_size_in_byte":6941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"218735598","text":"from rest_framework import serializers\nfrom api.models import Car, Review\n\n\nclass ReviewedCarSerializer(serializers.ModelSerializer):\n average_rating = serializers.DecimalField(max_digits=2,\n decimal_places=1,\n read_only=True)\n\n class Meta:\n model = Car\n fields = ('id', 'make', 'model', 'average_rating')\n read_only_fields = ('id', 'average_rating')\n\n def validate(self, attrs):\n instance = Car(**attrs)\n instance.clean()\n return attrs\n\n\nclass ReviewSerializer(serializers.ModelSerializer):\n class Meta:\n model = Review\n fields = ('car', 'review')\n","sub_path":"code/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"18964110","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 24 17:38:05 2021\n\n@author: andressa\n\"\"\"\n\nfrom collections import defaultdict\nfrom identification_module import identify_named_entities, pos_tagger\nfrom rule_based_module import classify_contexts\n\n\nPOS_TAGS = ['ADJ','ART','ADV-KS','IN','KS','NPROP','PCP','PREP',\n 'PREP+ART','PREP+PRO-KS','PREP+PROPESS',\n 'PROADJ','PRO-KS-REL','PROSUB','V','ADV',\n 'ADV-KS-REL','CUR','KC','N','NUM','PDEN',\n 'PREP+ADV','PREP+PROADJ','PREP+PRO-KS-REL',\n 'PREP+PROSUB','PRO-KS','PROPESS','PU','VAUX']\n\nWORD_TYPE_TAGS = ['ALPHA','NUMERIC','ALPHA-NUM','NON-ALPHA']\n\nWORD_CASE_TAGS = ['UPPER','FIRST-UPPER','LOWER', 'MISC']\n\nTOTAL_CLASSES = ['PESSOA','LOCAL','ORGANIZAÇÃO', 'TEMPO','VALOR','OUTRO',\n 'COISA','ABSTRAÇÃO', 'ACONTECIMENTO']\n\nSELECTIVE_CLASSES = ['PESSOA','LOCAL','ORGANIZAÇÃO','TEMPO','VALOR']\n\ndef tag_encoder(scenario):\n \n if scenario.lower() not in [\"selective\",\"total\"]:\n raise ValueError(\"Scenario must be 'selective' or 'total'\")\n \n entities_tags = ['X', 'O']\n \n if scenario == 'selective':\n classes = SELECTIVE_CLASSES\n else:\n classes = TOTAL_CLASSES\n \n for entity_class in classes:\n begin_class = 'B-{}'.format(entity_class[:3])\n end_class = 'I-{}'.format(entity_class[:3])\n entities_tags.extend((begin_class, end_class))\n \n return entities_tags\n\ndef get_word_type(token):\n \n if token.isalpha():\n wrd_type = 'ALPHA'\n elif token.isnumeric():\n wrd_type = 'NUMERIC'\n elif token.isalnum():\n wrd_type = 'ALPHA-NUM'\n else:\n wrd_type = 'NON-ALPHA'\n \n return wrd_type\n\ndef get_word_case(token):\n \n if token.isupper():\n wrd_case = 'UPPER'\n elif token.istitle():\n wrd_case = 'FIRST-UPPER'\n elif token.islower():\n wrd_case = 'LOWER'\n else:\n wrd_case = 'MISC'\n \n return wrd_case\n\n\nclass features(object):\n \n def __init__(self, features, scenario):\n self.features = features\n self.scenario = scenario\n self.get_features()\n self.feature_to_index()\n self.features_names = [feature for feature in self.features_dict]\n \n def get_features(self):\n self.features_dict = {}\n \n if \"ortographic_features\" in self.features:\n self.features_dict[\"wordTypeFeature\"] = ['X'] + WORD_TYPE_TAGS\n self.features_dict[\"wordCaseFeature\"] = ['X'] + WORD_CASE_TAGS\n if \"pos_tag_feature\" in self.features:\n self.features_dict[\"posTagFeature\"] = ['X'] + POS_TAGS\n if \"word_context_feature\" in self.features:\n out_feats = ['X', 'O']\n if self.scenario == 'total':\n self.features_dict[\"wordContextFeature\"] = out_feats + TOTAL_CLASSES\n elif self.scenario == 'selective':\n self.features_dict[\"wordContextFeature\"] = out_feats + SELECTIVE_CLASSES\n \n def feature_to_index(self):\n self.map_features = {}\n \n for feature, value in self.features_dict.items():\n self.map_features[feature] = {label:index for index,label in enumerate(value)}\n \n \n\ndef extract_extra_features(doc_tokens, features_names, scenario):\n \n features = defaultdict(list)\n \n if 'ortographic_features' in features_names: \n for token in doc_tokens:\n features['wordTypeFeature'] += [get_word_type(token)]\n features['wordCaseFeature'] += [get_word_case(token)]\n \n if 'pos_tag_feature' in features_names:\n features['posTagFeature'] = pos_tagger.tag_tokens(doc_tokens)\n\n \n if 'word_context_feature' in features_names:\n doc_entities = identify_named_entities(doc_tokens)\n features['wordContextFeature'] = classify_contexts(doc_tokens,\n doc_entities,\n scenario) \n return features\n \n","sub_path":"tagger_module.py","file_name":"tagger_module.py","file_ext":"py","file_size_in_byte":4055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"603107346","text":"while(True):\n try:\n n = float( input( 'Introduce un numero: ' ) )\n m = 4\n print( '{}/{}={}'.format( n, m, m/n ) )\n except TypeError:\n print( 'No se puede dividir un numero entre una cadena' )\n except ValueError:\n print( 'No se puede dividir un numero entre una cadena x2' )\n except ZeroDivisionError:\n print( 'No puedes dividir entre 0' )\n except Exception as e:\n print( type( e ).__name__ )\n else:\n print( 'Todo ha funcionado correctamente' )\n break\n finally:\n print( 'Fin de la iteracion' )\n\ndef mi_funcion( algo = None ):\n try:\n if algo is None:\n raise ValueError( 'Error! No se permite un valor nulo' ) # invocando error\n except ValueError: # controlando error provocado\n print( 'Error! no se permite un valor nulo (exception)' )\nmi_funcion()","sub_path":"015Exceptions.py","file_name":"015Exceptions.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"163767466","text":"\"\"\"Handshake command handlers.\"\"\"\n\nfrom logging import getLogger\nfrom gms.net.serializers.meeting import MeetingSerializer\nfrom ._aux import permissions_required\n\nLOG = getLogger(\"meetings\")\n\n\ndef connect(context, sid, environ):\n \"\"\"New client connected to server.\"\"\"\n # new socket connection received\n # with specified session id (sid)\n # todo: add to \"spectators\" list\n # todo: to observe connected but not authenticated\n # todo: users (for security reasons)\n LOG.info(\"Client %s connected\", sid)\n\n\ndef disconnect(context, sid):\n \"\"\"Client disconnected from server.\"\"\"\n # socket connection with specified\n # session id is closed\n # todo: remove from \"spectators\" list (if present)\n LOG.info(\"Client %s disconnected\", sid)\n context.logout_user(sid)\n\n\ndef handshake(context, sid, data):\n \"\"\"Handshake message received.\"\"\"\n LOG.info(\"Handshake received from '%s'\", sid)\n\n # find user using specified credentials\n token = data.get(\"token\", None)\n user = context.get_user_by_token(token)\n\n # no user found using specified credentails\n # send response with meaningful info\n if not user:\n return {\n \"success\": False,\n \"message\": \"You have no rights to join this meeting\",\n \"actions\": [\"request_access\"]\n }\n\n # no meeting found (wrong ID, exception while loading meeting)\n if not context.meeting:\n return {\"success\": False, \"message\": \"Meeting not found\"}\n\n # user found by specified credentials, so login\n # him by associating sessionId (sid) with model (user)\n context.login_user(sid, user)\n\n # serialize whole meeting state and return\n # it as response to the \"handshake\" request\n serializer = MeetingSerializer()\n meeting_state = serializer.serialize(context.meeting)\n\n # send response\n return {\n \"success\": True,\n \"message\": \"Welcome, {}!\".format(user.name),\n \"state\": meeting_state\n }\n\ndef request_access(context, sid, data):\n \"\"\"The user does not have permission to access the meeting,\n and he is requesting access rights.\"\"\"\n token = data.get(\"token\", None)\n user = context.find_user(token)\n\n # no user found to grant access to\n if not user:\n return {\"success\": False, \"message\": \"No user found\"}\n\n # request access\n context.sessions.requests.add(sid, user)\n\n # send response\n return {\n \"success\": True,\n \"message\": \"Access rights have been requested. \" + \\\n \"Please wait until the secretary accepts your request.\",\n }\n\n@permissions_required([\"meeting.manage\"])\ndef grant_access(context, sid, data):\n \"\"\"Grant access rights.\"\"\"\n token = data.get(\"token\", None)\n value = data.get(\"value\", False)\n user = context.find_user(token)\n response_sid = context.sessions.requests.sid(user)\n\n # session ID was not found\n if not response_sid:\n return {\"success\": False, \"message\": \"Session ID was not found\"}\n\n if value: # access granted\n response = {\"success\": True, \"id\": context.meeting.meeting_id}\n context.meeting.allowed_users.append(user)\n context.full_sync()\n context.send(\"open_meeting\", response, response_sid)\n else: # request was rejected\n response = {\"success\": False, \"message\": \"Your access request has been rejected\"}\n context.send(\"open_meeting\", response, response_sid)\n\n return {\"success\": True}\n","sub_path":"gem/backend/meeting/gms/commands/handshake.py","file_name":"handshake.py","file_ext":"py","file_size_in_byte":3428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"15821523","text":"\nteencode = {\n \"hk\" : \"Học\",\n \"bk\" : \"Biết\",\n \"g4\" : \"Gà\"\n}\nwhile True :\n for key in teencode:\n print(key, end = \"\\t \")\n\n n = input(\"\\nEnter your code : \")\n\n if n in teencode:\n print(\"Translate: \", teencode[n])\n else:\n print(\"Not found : \")\n user_choice = input(\"Do you wanna contribute? (Y/N): \".upper())\n if user_choice == \"Y\":\n translation = input(\"Enter your translation : \")\n teencode[n] = translation\n else:\n print(\"Bye\")\n break","sub_path":"Session 5/Examdict.py","file_name":"Examdict.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"615632731","text":"import sys,os\nimport time\nimport numpy as np\nfrom numpy.random import choice as rc\n\n## Import BlueNet\nimport bluenet.setting\nbluenet.setting.change_device('GPU')\nimport bluenet.dataset.Mnist as mnist\nfrom bluenet.network import Net\nfrom bluenet.layer import *\nfrom bluenet.activation import GELU\nfrom bluenet.optimizer import Adam\n\nmodel = [\n Conv({'f_num':8,'f_size':3,'pad':0,'stride':1}),\n Pool(2,2,2),\n Conv({'f_num':10,'f_size':3,'pad':0,'stride':1}),\n Pool(2,2,2),\n Conv({'f_num':105,'f_size':3,'pad':0,'stride':1}),\n Flatten(),\n Dense(10),\n SoftmaxWithLoss(),\n]\n\n## load train set and test set Normalize Flat One-hot Smooth type\n(x_train,t_train),(x_test,t_test) = mnist.load_mnist(True, False, True, True, np.float32)\n\n##Initialize the neural network(Use LeNet) \nnet = Net(model)\nnet.initialize(\n shape = (1,28,28), \n af = GELU, \n opt = Adam, \n rate = 0.001, \n init_mode = 'xaiver', \n dtype = np.float32\n)\n\n##Print the structure of the network\nnet.print_size()\n\n##Pre learn\n#mask = rc(x_train.shape[0],30000)\n#net.pre_train_for_conv(x_train[mask], 30)\n\n##Set some parameters for training \nbatch_size = 50\ntrain_size = x_train.shape[0]\niter_per_epoch = max((train_size//batch_size), 1)\n\n##Input how many epoch You wnat\nepoch = 3\n\n##Start Training\nprint('\\n┌────────────────────────────────────┐ ')\nprint('│Training start │ ')\nfor j in range(epoch):\n start = time.time()\n print(\"│====================================│ \")\n \n loss_t = 0\n for i in range(1,iter_per_epoch+1):\n batch_mask = rc(train_size, batch_size) #Random choose data\n\n x_batch = x_train[batch_mask]\n t_batch = t_train[batch_mask]\n \n loss = net.train(x_batch, t_batch) #Train&Caculate the loss of the net\n loss_t += loss\n if i%50==0:\n print('│Iters {:<6} Loss : {:<8} │ '.format(i,str(loss)[:8]), end='\\r', flush=True)\n \n cost = time.time()-start\n \n print(\"│Epoch {:<5} Average Loss : {:<8} │ \".format(j+1, str(loss_t/iter_per_epoch)[:8]))\n print(\"│ Cost Time : {:<8} │ \".format(str(cost)[:8]))\n print(\"│ Iters/sec : {:<8} │ \".format(str(iter_per_epoch/cost)[:8]))\n \nprint('└────────────────────────────────────┘ ')","sub_path":"example/example(Mnist).py","file_name":"example(Mnist).py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"197654117","text":"import geocoders.ban as ban\nimport geocoders.ign as ign\nfrom statistics import median, stdev, mean\nfrom timeit import default_timer as timer\nfrom datasets import annuaires_du_commerce\nfrom geocoders.util import ban_to_dataframe, ign_to_dataframe\nimport geocodeurHistorique_commerce\nimport logging\nimport pandas as pd\nimport annexe\nimport numpy\nimport matplotlib.pyplot as plt\nimport graphiques\n\nlogging.basicConfig(level=logging.INFO, format='%(message)s')\n\n\n# Méthode principale\ndef main():\n ds1 = annuaires_du_commerce.dataset_1() # Charge les données à géocoder\n liste_ign = exec_ign(ds1) # Géocode avec le service IGN et sauvegarde le résultat\n liste_ban = exec_ban(ds1) # Géocode avec le service BAN et sauvegarde le résultat\n liste_historique = exec_historique(ds1)\n graphiques.trace_graphique(liste_ign, liste_ban, liste_historique)\n\n\ndef exec_ban(dataset):\n # Définit les options de géocodage\n number_of_results = 1\n ban_opts = {'limit': number_of_results, 'citycode': 75056} # Force à chercher dans Paris\n\n # Géocode le contenu de la colonne 'address' dans dataset.\n logging.info(f'Executing BAN geocoder with options {ban_opts}')\n geocoder = ban.geocode\n results, runtimes, global_time = run(dataset['address'], geocoder, opts=ban_opts)\n\n # Affiche les statistiques de temps d'exécution\n summary(dataset, results, runtimes)\n\n # Transforme les résultats renvoyés par le géocodeur en tableau Pandas\n all = ban_to_dataframe.transform(results, keep_only=number_of_results)\n\n # Concatène le tableau des résultats aux données d'entrée et sauvegarde le résultat\n pd.concat([dataset, all], axis=1).to_csv('annuaire_du_commerce_ban.csv')\n\n #Calcule la moyenne des écarts entre les coordonnées géographiques réelles et les coordonnées géocodées\n csv = pd.read_csv('annuaire_du_commerce_ban.csv')\n distances, avg_distance, mediane, ecart_type, f_score = calcul_ecart(csv, \"ban\")\n print(\"Liste des distances : \", distances)\n print(5*\"\\n\")\n print(\"Ecart moyen des distances : \", avg_distance)\n print(5*\"\\n\")\n print(\"Médiane des distances : \", mediane)\n print(5*\"\\n\")\n print(\"Ecart-type : \", ecart_type)\n print(5*\"\\n\")\n print(\"F-score : \", f_score)\n \n #Donne le temps total\n print(\"Temps total : \", global_time)\n\n return [avg_distance, mediane*10, ecart_type, f_score, global_time]\n\n\ndef exec_ign(dataset):\n # Définit les options de géocodage\n number_of_results = 1\n ign_opts = {'maxResp': number_of_results}\n\n # Géocode le contenu de la colonne 'address' dans dataset.\n logging.info(f'Executing IGN geocoder')\n addresses_plus_paris = dataset['address'] + ' 75' # Force à chercher dans Paris (75)\n results, runtimes, global_time = run(addresses_plus_paris, ign.geocode, feature_type='address', opts= ign_opts)\n\n # Affiche les statistiques de temps d'exécution\n summary(dataset, results, runtimes)\n\n # Transforme les résultats renvoyés par le géocodeur en tableau Pandas\n all = ign_to_dataframe.transform(results, keep_only=number_of_results)\n\n # Concatène le tableau des résultats aux données d'entrée et sauvegarde le résultat\n pd.concat([dataset, all], axis=1).to_csv('annuaire_du_commerce_ign.csv')\n\n #Calcule la moyenne des écarts entre les coordonnées géographiques réelles et les coordonnées géocodées\n csv = pd.read_csv('annuaire_du_commerce_ign.csv')\n distances, avg_distance, mediane, ecart_type, f_score = calcul_ecart(csv, \"ign\")\n print(\"Liste des distances : \", distances)\n print(5*\"\\n\")\n print(\"Ecart moyen des distances : \", avg_distance)\n print(5*\"\\n\")\n print(\"Médiane des distances : \", mediane)\n print(5*\"\\n\")\n print(\"Ecart-type : \", ecart_type)\n print(5*\"\\n\")\n print(\"F-score : \", f_score)\n\n #Donne le temps total\n print(\"Temps total : \", global_time)\n\n return [avg_distance, mediane*10, ecart_type, f_score, global_time]\n\ndef exec_historique(dataset):\n start = timer()\n geocodeurHistorique_commerce.historique()\n global_time = timer() - start\n\n #Calcule la moyenne des écarts entre les coordonnées géographiques réelles et les coordonnées géocodées\n distances, avg_distance, mediane, ecart_type, f_score = calcul_ecart(pd.read_csv('adresses_geocodees.csv', encoding = \"ISO-8859-1\"), \"ghd\")\n \n print(\"Liste des distances : \", distances)\n print(5*\"\\n\")\n print(\"Ecart moyen des distances : \", avg_distance)\n print(5*\"\\n\")\n print(\"Médiane des distances : \", mediane)\n print(5*\"\\n\")\n print(\"Ecart-type : \", ecart_type)\n print(5*\"\\n\")\n print(\"F-score : \", f_score)\n\n #Donne le temps total\n print(\"Temps total : \", global_time)\n\n return [avg_distance, mediane*10, ecart_type, f_score, global_time]\n\n\ndef run(dataset, geocoder, **kwargs):\n \"\"\"\n Geocode a dataset using a geocoder.\n :param dataset: a dataset to geocode\n :param geocoder: the geocoder to use\n :return:\n \"\"\"\n results, runtimes = [], []\n\n data_list = list(dataset)\n data_len = len(data_list)\n for idx, item in enumerate(data_list):\n # Appelle le géocodeur passé en paramètres avec l'item à géocoder et les options passées à la méthode et\n # mesure le temps d'exécution\n start = timer()\n r = next(geocoder(item, **kwargs))\n elapsed_time = timer() - start\n\n results.append(r)\n runtimes.append(elapsed_time)\n\n # Affiche le géocodage courant\n log = '\\u2713' if r['success'] else '\\u2728'\n log += f\" {idx + 1}/{data_len} {elapsed_time * 1000}ms: \\'{item}\\'\"\n log += '' if r['success'] else r['error']\n logging.info(log)\n\n global_time = sum(runtimes)\n\n return results, runtimes, global_time\n\n\ndef summary(dataset, results, times):\n \"\"\"\n Print some information about the execution time of a geocoding\n \"\"\"\n succ, fail = [], []\n\n [succ.append(r) if r['success'] else fail.append(r) for r in results]\n\n logging.info(\n f'Geocoding {len(dataset)} addresses took {sum(times)}s'\n f' with {len(succ)} successes and {len(fail)} failures'\n f' (min = {min(times)}s,'\n f' max = {max(times)}s,'\n f' avg = {mean(times)}s,'\n f' stddev = {stdev(times)}s,'\n f' median = {median(times)}s)')\n\ndef calcul_ecart(csv, geocodeur):\n csv.fillna(0, inplace=True)\n if geocodeur == \"ign\" or geocodeur == \"ban\":\n lon_reel= csv['lon']\n lat_reel = csv['lat']\n else: #Il y a un problème avec le fichier adresses_geocodees.csv : les en-têtes sont décalés par rapport aux données qu'ils représentent. Ainsi, pour le géocodeur ghd, l'en-tête 'lat' correspond à la longitude, l'en-tête 'adresse' correspond à la latitude.\n lon_reel = csv['lat']\n lat_reel = csv['adresse']\n lon_reel_list = list(lon_reel)\n lat_reel_list = list(lat_reel)\n lon_geocode = csv['geometry.lng_1']\n lon_geocode_list = list(lon_geocode)\n lat_geocode = csv['geometry.lat_1']\n lat_geocode_list = list(lat_geocode)\n \n #On enlève des listes les adresses non géocodées\n lon_reel_tableau = []\n lat_reel_tableau = []\n lon_geocode_tableau = []\n lat_geocode_tableau = []\n for i in range(len(lon_geocode_list)):\n if lon_geocode_list[i] != 0:\n lon_reel_tableau.append(lon_reel_list[i])\n lat_reel_tableau.append(lat_reel_list[i])\n lon_geocode_tableau.append(lon_geocode_list[i])\n lat_geocode_tableau.append(lat_geocode_list[i])\n\n lon_reel_list = numpy.asarray(lon_reel_tableau)\n lat_reel_list = numpy.asarray(lat_reel_tableau)\n lon_geocode_list = numpy.asarray(lon_geocode_tableau)\n lat_geocode_list = numpy.asarray(lat_geocode_tableau)\n\n\n print(\"Longitude réelle \", len(lon_reel_list), \"\\nLatitude réelle \", len(lat_reel_list), \"\\nLongitude géocodée \", len(lon_geocode_list), \"\\nLatitude géocodée \", len(lat_geocode_list))\n \n\n distances = annexe.haversine(lon_reel_list,lat_reel_list,lon_geocode_list,lat_geocode_list)\n\n #Calcul moyenne\n longueur = len(distances)\n avg_distance = sum(distances)/longueur\n\n #Calcul médiane\n distances.sort()\n if longueur%2 == 1:\n mediane = distances[longueur//2]\n else:\n mediane = (distances[longueur//2-1]+distances[longueur//2])/2\n\n #Calcul écart-type\n carre_ecart_moyenne = [(i-avg_distance)**2 for i in distances]\n ecart_type = numpy.sqrt(sum(carre_ecart_moyenne)/longueur)\n\n #Calcul f-score\n sous_seuil = 0\n for i in distances:\n if i <= 50:\n sous_seuil += 1\n f_score = annexe.f_score(sous_seuil, 500, longueur)\n\n return distances, avg_distance, mediane, ecart_type, f_score\n \n\n\nif __name__ == '__main__':\n main()\n","sub_path":"initiation_a_la_recherche-master/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"503868936","text":"#!/usr/bin/python3\n\ndef Anagrama (lista):\n\tfor line in lista:\n\t\tcont = 0\n\t\tb = list(line)\n\t\tb.sort()\n\t\tif (len(b) == len(line)):\n\t\t\tfor i in range(len(b)):\n\t\t\t\tif ((b[i]) == (line[i])):\n\t\t\t\t\tprint (line)\ny = Anagrama (['eat', 'ate', 'done', 'tea', 'soup', 'node'])\n\n\n","sub_path":"solucoes/Karen/Aula_2/Exercicio_19.py","file_name":"Exercicio_19.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"579809481","text":"from django.conf.urls.defaults import *\nfrom django.views.generic import list_detail, create_update\nfrom models import Course, Cuisine\n\ncourse_info={\n \"queryset\":Course.objects.all(),\n \"template_object_name\":\"course\",\n }\ncuisine_info={\n \"queryset\":Cuisine.objects.all(),\n \"template_object_name\": \"cuisine\",\n }\nurlpatterns = patterns('',\n (r'^popadd/course/$', 'openeats.recipe_groups.views.course_pop'),\n url(r'^course/$', list_detail.object_list, course_info , name=\"course_list\"),\n (r'^course/new/$', create_update.create_object, dict({'model':Course,}, login_required=True, post_save_redirect='/recipe/')),\n url(r'^course/(?P[-\\w]+)/$', 'openeats.recipe_groups.views.course_recipes', name=\"course_recipes\"),\n (r'^popadd/cuisine/$', 'openeats.recipe_groups.views.cuisine_pop'),\n (r'^cuisine/$', list_detail.object_list, cuisine_info),\n (r'^cuisine/new/$', create_update.create_object, dict({'model':Cuisine,}, login_required=True, template_name='recipe_groups/course_form.html', post_save_redirect='/recipe/')),\n url(r'^cuisine/(?P[-\\w]+)/$', 'openeats.recipe_groups.views.cuisine_recipes', name=\"cuisine_recipes\"),\n\n)","sub_path":"recipe_groups/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"341518922","text":"# * * * * * * * * * * * * * * * * * * * * * * * * * * *\n# ALFRESCO POST-PROCESSING INITIALIZATION FILE\n# * * * * * * * * * * * * * * * * * * * * * * * * * * *\n\n# read in local libarary elements\nfrom alfresco_postprocessing.dataset import *\nfrom alfresco_postprocessing.metrics import *\nfrom alfresco_postprocessing.postprocess import *\nfrom alfresco_postprocessing.plot import *\nimport alfresco_postprocessing as ap\n\n# other libs (external and stdlib)\nimport os, glob, rasterio, ujson\nimport numpy as np\nfrom functools import partial\n\n\n# # VEGETATION MAP DEFAULT:\nveg_name_dict = {1:'Black Spruce',\n\t\t\t\t2:'White Spruce',\n\t\t\t\t3:'Deciduous',\n\t\t\t\t4:'Shrub Tundra',\n\t\t\t\t5:'Graminoid Tundra',\n\t\t\t\t6:'Wetland Tundra',\n\t\t\t\t7:'Barren lichen-moss',\n\t\t\t\t8:'Temperate Rainforest'}\n\n\n# # UTILITY FUNCTIONS -- Run PostProcess\ndef\topen( alf_fn, sub_domains=None, observed=False ):\n\t'''\n\topen an alfresco output/input dataset and give a subdomains object as arg2 if desired\n\tif data represents observed alfresco input FireHistory data, then set observed to \n\tTrue (default: False)\n\n\tArguments:\n\t----------\n\talf_fn = [str] path to an ALFRESCO Fire Dynamics Model output (or sometimes input) raster.\n\tsub_domains = an object of one of three types for different scenarios. \n\t\ttypically this is created with read_subdomains\n\tobserved = [bool] if alf_fn points to a FireHistory file then set observed=True.\n\t\tdefault:False (not observed, or ALFRESCO model output)\n\n\tReturns:\n\t--------\n\tobject of type AlfrescoDataset or ObservedDataset depending on the input fn and \n\tobserved argument.\n\n\t'''\n\tswitch = { False: AlfrescoDataset, True: ObservedDataset }\n\treturn switch[ observed ](fn=alf_fn, sub_domains=sub_domains)\n\ndef read_subdomains( subdomains_fn=None, rasterio_raster=None, id_field=None, name_field=None, \n\tid_name_dict=None, background_value=None ):\n\t'''\n\thandle different sub_domains use-cases.\n\t'''\n\tif subdomains_fn != None:\n\t\tif ( subdomains_fn.endswith('.shp') ):\n\t\t\tsubs = SubDomains( subdomains_fn=subdomains_fn, rasterio_raster=rasterio_raster, \\\n\t\t\t\t\t\t\tid_field=id_field, name_field=name_field )\n\t\telse:\n\t\t\tsubs = SubDomainsRaster( subdomains_fn=subdomains_fn, rasterio_raster=rasterio_raster, \\\n\t\t\t\t\t\t\tbackground_value=background_value, id_name_dict=id_name_dict )\n\telif subdomains_fn == None:\n\t\tsubs = FullDomain( rasterio_raster=rasterio_raster, background_value=None ) # hardwired at None for now\n\telse:\n\t\tAttributeError( 'subdomains_fn must be a valid shape filename, raster filename, or None' )\n\treturn subs\n\n\n# ACTUAL RUN STUFF\ndef _open_tinydb( out_json_fn ):\n\t'''\n\topen a tinydb database file (JSON) on disk at the \n\tlocation input. This function will also remove the \n\tdatabase if it exists on disk.\n\n\tArguments:\n\t----------\n\tout_json_fn = [str] path to the json file to be generated.\n\n\tReturns:\n\t--------\n\ttinydb.TinyDB object pointing to a JSON file at the location\n\tprovided in out_json_fn.\n\n\t'''\n\tfrom tinydb import TinyDB\n\tif os.path.exists( out_json_fn ):\n\t\tos.unlink( out_json_fn )\n\treturn TinyDB( out_json_fn )\n\ndef _run_historical( fn, sub_domains=None, *args, **kwargs ):\n\t'''\n\ta quick and dirty method of performing the historical observed\n\tburned boolean raster GTiffs used as inputs to the ALFRESCO Fire\n\tDynamics Model.\n\n\tArguments:\n\t----------\n\tfn = [str] path to FireHistory GTiff for a single year used as input\n\t\tto ALFRESCO.\n\tsub_domains = an object of one of three types for different scenarios. \n\t\ttypically this is created with read_subdomains\n\n\tReturns:\n\t--------\n\tdict with keys for each metric, replicate, and year with values that \n\tare returned for each. Subdomains are contained nested within these \n\tkey:value pairs.\n\n\t'''\n\tds_fs = ap.open( fn, sub_domains=sub_domains, observed=True )\n\tout_dd = {}\n\tfire = Fire( ds_fs )\n\tout_dd.update( replicate=ds_fs.replicate,\n\t\t\t\t\tfire_year=ds_fs.year,\n\t\t\t\t\tall_fire_sizes=fire.all_fire_sizes,\n\t\t\t\t\tavg_fire_size=fire.avg_fire_size,\n\t\t\t\t\tnumber_of_fires=fire.number_of_fires,\n\t\t\t\t\ttotal_area_burned=fire.total_area_burned )\n\treturn out_dd\n\ndef _run_timestep( timestep, sub_domains, veg_name_dict, *args, **kwargs ):\n\t'''\n\tworkhorse function that takes a dict of style {variable_name:path_to_file.tif}\n\tfor all files in a single timestep that are to be used in calculation.\n\n\tThis is where we would add new things to be added into the output JSON, like\n\tnew classes for working with Age, Burn Severity, or interactions to name a \n\tfew.\n\n\tArguments:\n\t----------\n\ttimestep = [alfresco_postprocessing.TimeStep] timestep object with \n\ttimestep_fn_dict = [dict] dictionary that stores the filenames for all variables\n\t\tin a given timestep. In {variable_name:filename_string} pairs\n\tsub_domains = [alfresco_postprocessing.SubDomains] subdomains object as read using\n\t\tap.read_subdomains( ) to return a common data type for all different flavors \n\t\tof inputs used as subdomains.\n\n\tReturns:\n\t--------\n\tdict with keys for each metric, replicate, and year with values that are returned\n\tfor each. Subdomains are contained nested within these key:value pairs.\n\n\t'''\n\t# open the data we need -- add more reads here and then add in the\n\t# class instantiation with them below\n\tds_fs = ap.open( timestep.FireScar.fn, sub_domains=sub_domains )\n\tds_veg = ap.open( timestep.Veg.fn, sub_domains=sub_domains )\n\t# ds_age = ap.open( timestep.Age.fn, sub_domains=sub_domains )\n\tds_burnseverity = ap.open( timestep.BurnSeverity.fn, sub_domains=sub_domains )\n\t\n\tout_dd = {}\n\t# fire \n\tfire = Fire( ds_fs )\n\tout_dd.update( replicate=ds_fs.replicate,\n\t\t\t\t\tfire_year=ds_fs.year,\n\t\t\t\t\tall_fire_sizes=fire.all_fire_sizes,\n\t\t\t\t\tavg_fire_size=fire.avg_fire_size,\n\t\t\t\t\tnumber_of_fires=fire.number_of_fires,\n\t\t\t\t\ttotal_area_burned=fire.total_area_burned )\n\t# veg\n\tveg = Veg( ds_veg, veg_name_dict )\n\tout_dd.update( av_year=ds_veg.year, veg_counts=veg.veg_counts )\n\n\t# age -- not yet implemented\n\t# age = Age()\n\n\tburnseverity = BurnSeverity( ds_burnseverity )\n\tout_dd.update( severity_counts=burnseverity.severity_counts )\n\treturn out_dd\n\ndef _get_stats( timesteps, db, sub_domains, ncores, veg_name_dict ):\n\tfrom tinydb import TinyDB\n\timport multiprocessing\n\tfrom functools import partial\n\t\n\t# instantiate a pool of workers\n\tpool = multiprocessing.Pool( processes=ncores, maxtasksperchild=4 )\n\n\t# run parallel map using multiprocessing \n\tf = partial( _run_timestep, sub_domains=sub_domains, veg_name_dict=veg_name_dict )\n\tout = pool.map( f, timesteps )\n\tpool.close()\n\tdb.insert_multiple( out )\n\tdel out\n\treturn db\n\ndef run_postprocessing_historical( maps_path, out_json_fn, ncores, veg_name_dict, subdomains_fn=None, id_field=None, name_field=None, background_value=0 ):\n\timport glob, os\n\timport multiprocessing\n\tfile_list = glob.glob( os.path.join( maps_path, '*.tif' ) )\n\tdb = _open_tinydb( out_json_fn )\n\trst = rasterio.open( file_list[0] )\n\tsub_domains = read_subdomains( subdomains_fn=subdomains_fn, rasterio_raster=rst, id_field=id_field, name_field=name_field, background_value=0 )\n\n\tpool = multiprocessing.Pool( processes=ncores, maxtasksperchild=4 )\n\t# run parallel map using multiprocessing \n\tf = partial( _run_historical, sub_domains=sub_domains, veg_name_dict=veg_name_dict )\n\tout = pool.map( f, file_list )\n\tpool.close()\n\tdb.insert_multiple( out )\n\tdel out\n\treturn db\n\n# THIS FUNCTION NEEDS CHANGING SINCE WE NO LONGER USE THE NAME PostProcess, nor do we access the raster file in that same way.\n# IT IS BETTER SUITED TO BEING PULLED FROM THE FIRST OF THE TimeStep objects.\ndef run_postprocessing( maps_path, out_json_fn, ncores, veg_name_dict, subdomains_fn=None, \\\n\tid_field=None, name_field=None, background_value=0, lagfire=False ): # background value is problematic\n\tdb = ap._open_tinydb( out_json_fn )\n\tfl = FileLister( maps_path, lagfire=lagfire )\n\t# open a template raster\n\trst = rasterio.open( fl.files[0] )\n\tsub_domains = read_subdomains( subdomains_fn=subdomains_fn, rasterio_raster=rst, \\\n\t\t\t\t\tid_field=id_field, name_field=name_field, background_value=0 )\n\tts_list = fl.timesteps\n\t# fn_list = [ dict(i) for i in fn_list ]\n\treturn _get_stats( ts_list, db, sub_domains, ncores, veg_name_dict ) # WATCH THIS!!!!!\n\ndef _to_csv( db, metric_name, output_path ):\n\t\treturn metric_to_csvs( db, metric_name, output_path )\n\ndef to_csvs( db, metrics, output_path, suffix='', observed=False ):\n\t'''\n\toutput a list of metrics to CSV files from an ALFRESCO Post Processing \n\tderived TinyDB holding summary stats.\n\n\tArguments:\n\t----------\n\tdb = [tinydb.TinyDB] ALFRESCO Post Processing derived output summary stats database\n\t\tcreated following post processing of the outputs.\n\tmetrics = [list] strings representing the metrics to be output to CSV from the \n\t\tdb. \n\toutput_path = [str] path to the output path to store the generated CSV files.\n\tsuffix = [str] default:'' string identifier to put in the output filenames.\n\tobserved = [bool] set to True if it is an observed dataset based TinyDB output,\n\t\tdefault: False for a standard output ALFRESCO Dataset based TinyDB output. \n\n\tReturns:\n\t--------\n\t1 if succeeds. with the side-effect of writing CSV files to disk.\n\n\t'''\n\timport os\n\tout = []\n\t# switch to deal with diff groups in a cleaner way.\n\tswitch = { True:metric_to_csvs_historical, False:metric_to_csvs }\n\tfor metric_name in metrics:\n\t\tout_path = os.path.join( output_path, metric_name.replace(' ', '' ) )\n\t\tif not os.path.exists( out_path ):\n\t\t\tos.makedirs( out_path )\n\t\tout.append( switch[observed]( db, metric_name, out_path, suffix ) )\n\treturn output_path\n\n","sub_path":"alfresco_postprocessing/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"37689825","text":"from flask import Flask\nfrom flask import Flask, flash, redirect, render_template, request, session, abort, make_response, url_for\nimport os\nfrom sqlalchemy import *\nfrom sqlalchemy.pool import NullPool\nfrom flask import Flask, request, render_template, g, redirect, Response\nimport flask_login\nimport logging\nfrom flask_login import LoginManager\nimport flask_logger\n\ntmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')\napp = Flask(__name__, template_folder=tmpl_dir)\n\nDB_USER = \"tm2977\"\nDB_PASSWORD = \"574u6jh2\"\n\nDB_SERVER = \"w4111.cisxo09blonu.us-east-1.rds.amazonaws.com\"\n\nDATABASEURI = \"postgresql://\"+DB_USER+\":\"+DB_PASSWORD+\"@\"+DB_SERVER+\"/w4111\"\n\nengine = create_engine(DATABASEURI)\n\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\nlogin_manager.login_view = 'login'\nlogin_manager.login_message = 'please login!'\nlogin_manager.session_protection = 'strong'\nlogger = logging.getLogger(__name__)\n\n\n\n# Here we create a test table and insert some values in it\n# engine.execute(\"\"\"DROP TABLE IF EXISTS test;\"\"\")\n# engine.execute(\"\"\"CREATE TABLE IF NOT EXISTS test (\n# id serial,\n# name text\n# );\"\"\")\n# engine.execute(\"\"\"INSERT INTO test(name) VALUES ('grace hopper'), ('alan turing'), ('ada lovelace');\"\"\")\nclass User(flask_login.UserMixin):\n pass\n # def __init__(self, id, active=True):\n # self.id = id\n # self.active = active\n\n@login_manager.user_loader\ndef load_user(user_id):\n cursor = g.conn.execute(\"SELECT user_name FROM User_\")\n uids = []\n for result in cursor:\n uids.append(result['user_name'])\n if user_id not in uids:\n return\n user = User()\n user.id = user_id\n return user\n\n@app.before_request\ndef before_request():\n \"\"\"\n This function is run at the beginning of every web request\n (every time you enter an address in the web browser).\n We use it to setup a database connection that can be used throughout the request\n\n The variable g is globally accessible\n \"\"\"\n try:\n g.conn = engine.connect()\n except:\n print (\"uh oh, problem connecting to database\")\n import traceback; traceback.print_exc()\n g.conn = None\n\n@app.teardown_request\ndef teardown_request(exception):\n \"\"\"\n At the end of the web request, this makes sure to close the database connection.\n If you don't the database could run out of memory!\n \"\"\"\n try:\n g.conn.close()\n except Exception as e:\n pass\n\n@app.route('/', methods=['GET', 'POST'])\n@flask_login.login_required\ndef home():\n # if session.get('UName'):\n\n cursor = g.conn.execute(\"SELECT eid, event_name, likes, event_date, tag FROM Event\")\n names = []\n likes = []\n event_dates = []\n tags = []\n ids = []\n for result in cursor:\n names.append(result['event_name']) # can also be accessed using result[0]\n likes.append(result['likes'])\n event_dates.append(result['event_date'])\n tags.append(result['tag'])\n ids.append(result['eid'])\n cursor.close()\n\n cursor = g.conn.execute(\"SELECT count(*) FROM Event\")\n a = cursor.fetchone()\n count = a[0]\n\n count_dic = dict(count = count)\n names_dic = dict(names = names)\n user_id_dic = dict(n = flask_login.current_user.id)\n likes_dic = dict(likes=likes)\n event_dates_dic = dict(event_dates=event_dates)\n tags_dic = dict(tags=tags)\n ids_dic = dict(ids=ids)\n return render_template('home.html', **ids_dic, **names_dic, **user_id_dic, **likes_dic, **event_dates_dic, **tags_dic, **count_dic)\n # return render_template('home.html', **datas_dic)\n # else:\n # return login()\n # if not session.get('logged_in'):\n # return render_template('login.html')\n # else:\n # return \"Hello Boss!\"\n\n\n# @app.route('/login')\n# def login():\n# return render_template('login.html')\n\n@app.route('/login', methods=['POST', 'GET'])\ndef login():\n if request.method == 'POST':\n logger.debug(\"login post method\")\n t = {\"username\": request.form['username'], \"password\" : request.form['password']}\n\n\n cursor = g.conn.execute(text(\n \"\"\"\n select count(*)\n from User_\n where user_name = :username and password = :password\n \"\"\"\n ),t)\n a = cursor.fetchone()\n if a[0]:\n user = User()\n user.id = request.form[\"username\"]\n flask_login.login_user(user)\n # resp = make_response(render_template('index.html', name=request.form[\"username\"]))\n # resp.set_cookie('username', request.form[\"username\"])\n session['UName'] = request.form['username']\n session['password'] = request.form['password']\n return home()\n else:\n return render_template('login.html')\n\n return render_template('login.html')\n\n\n # else:\n # print(\"No\")\n\n # if request.form['password'] == 'password' and request.form['username'] == 'admin':\n # session['logged_in'] = True\n # else:\n # flash('wrong password!')\n\n@app.route('/logout')\n@flask_login.login_required\ndef logout():\n logger.debug(\"logout page\")\n flask_login.logout_user()\n return render_template('login.html')\n\n\n@app.route('/register',methods=['GET'])\ndef do_register():\n return render_template('register.html')\n\n@app.route('/post',methods=['GET'])\n@flask_login.login_required\ndef post():\n return render_template('post.html')\n\n@app.route('/do_post',methods=['GET', 'POST'])\n@flask_login.login_required\ndef do_post():\n t1 = {\"event_name\": request.form['eventname'],\"event_date\" : request.form['eventdate'], \"description\" : request.form['description'], \"tag\": request.form['tag']}\n cursor = g.conn.execute(text(\n \"\"\"\n insert into Event(event_name, event_date, description,tag)\n values\n (:event_name, :event_date, :description, :tag)\n \"\"\"\n ),t1)\n\n cursor = g.conn.execute(\n \"\"\"\n select max(eid) from Event\n \n \"\"\")\n\n\n event = cursor.fetchone()\n eid = event[0]\n\n t2 = {\"eid\": eid, \"location\": request.form['location']}\n g.conn.execute(text(\n \"\"\"\n insert into Take_Places(eid, address)\n values\n (:eid, :location)\n \"\"\"\n ),t2)\n return home()\n\n@app.route('/search',methods=['GET', 'POST'])\n@flask_login.login_required\ndef search():\n return render_template(\"search.html\")\n\n\n@app.route('/search_result',methods=['GET', 'POST'])\n@flask_login.login_required\ndef search_result():\n results = []\n t = {\"event_search\": request.form['event_search']}\n\n cursor1 = g.conn.execute(text(\n \"\"\"\n select eid, event_name, likes, tag, description, address\n from Event natural join Take_Places\n where event_name = :event_search or tag = :event_search or address = :event_search \n \"\"\"\n ),t)\n for result in cursor1:\n row = []\n row.append(result['event_name'])\n row.append(result['likes'])\n row.append(result['tag'])\n row.append(result['description'])\n row.append(result['address'])\n row.append(result['eid'])\n results.append(row)\n events_dic = dict(events = results)\n\n\n\n cursor2 = g.conn.execute(text(\n \"\"\"\n select count(*) from Event natural join Take_Places\n where event_name = :event_search or tag = :event_search or address =:event_search \n \"\"\"\n ),t)\n tmp = cursor2.fetchone()\n count = tmp[0]\n count_dic = dict(count = count)\n return render_template(\"search_result.html\", **events_dic, **count_dic)\n\n\n@app.route('/createUser', methods=['GET', 'POST'])\ndef do_createUser():\n t = {\"user_name\": request.form['username'], \"password\": request.form['password']}\n g.conn.execute(text(\n \"\"\"\n insert into User_(user_name, password)\n values\n (:user_name, :password)\n \"\"\"\n ), t)\n\n return render_template(\"login.html\")\n\n@app.route('/view_event/',methods=['POST'])\n@flask_login.login_required\ndef view_event(ID):\n results = []\n t = {\"event_id\": ID}\n\n cursor = g.conn.execute(text(\n \"\"\"\n select event_name, likes, tag, description, address\n from Event natural join Take_Places\n where eid= :event_id \n \"\"\"\n ),t)\n for result in cursor:\n row = []\n row.append(result['event_name'])\n row.append(result['likes'])\n row.append(result['tag'])\n row.append(result['description'])\n row.append(result['address'])\n results.append(row)\n events_dic = dict(events = results)\n return render_template('event_view.html', **events_dic)\n\nif __name__ == \"__main__\":\n app.secret_key = os.urandom(12)\n app.run(debug=True, host='0.0.0.0', port=4000)","sub_path":"webserver/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"481015202","text":"import itertools\nimport logging\nimport numpy as np\nimport tensorflow as tf\nimport time\nimport os\nimport pandas as pd\nimport multiprocessing\nimport shutil\n\n\ndef init_dir(base_dir, pathes=['log', 'data', 'model', 'results']):\n if not os.path.exists(base_dir):\n os.mkdir(base_dir)\n dirs = {}\n for path in pathes:\n cur_dir = base_dir + \"/%s/\" % path\n if not os.path.exists(cur_dir):\n os.mkdir(cur_dir)\n dirs[path] = cur_dir\n return dirs\n\n\ndef copy_file(src_file, tar_dir):\n shutil.copy2(src_file, tar_dir)\n\n\ndef check_dir(cur_dir):\n if not os.path.exists(cur_dir):\n return False\n return True\n\n\ndef init_log(log_dir):\n logging.basicConfig(format='%(asctime)s [%(levelname)s] %(message)s',\n level=logging.INFO,\n handlers=[\n logging.FileHandler('%s/%d.log' %\n (log_dir, time.time())),\n logging.StreamHandler()\n ])\n\n\ndef init_test_flag(test_mode):\n if test_mode == 'no_test':\n return False, False\n if test_mode == 'in_train_test':\n return True, False\n if test_mode == 'after_train_test':\n return False, True\n if test_mode == 'all_test':\n return True, True\n return False, False\n\n\nclass Scheduler:\n def __init__(self, val_init, val_min=0, total_step=0, decay='linear'):\n self.val = val_init\n self.N = float(total_step)\n self.val_min = val_min\n self.decay = decay\n self.n = 0\n\n def get(self, n_step):\n self.n += n_step\n if self.decay == 'linear':\n return max(self.val_min, self.val * (1 - self.n / self.N))\n else:\n return self.val\n\n\ndef make_session(config=None, num_cpu=None, make_default=False, graph=None):\n \"\"\"Returns a session that will use CPU's only\"\"\"\n if num_cpu is None:\n num_cpu = int(os.getenv('RCALL_NUM_CPU', multiprocessing.cpu_count()))\n if config is None:\n config = tf.ConfigProto(\n allow_soft_placement=True,\n inter_op_parallelism_threads=num_cpu,\n intra_op_parallelism_threads=num_cpu)\n config.gpu_options.allow_growth = True\n\n if make_default:\n return tf.InteractiveSession(config=config, graph=graph)\n else:\n return tf.Session(config=config, graph=graph)","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"21746599","text":"## Copyright [2017] UMR MISTEA INRA, UMR LEPSE INRA, UMR AGAP CIRAD, ##\n## EPI Virtual Plants Inria ##\n## ##\n## This file is part of the StatisKit project. More information can be ##\n## found at ##\n## ##\n## http://statiskit.rtfd.io ##\n## ##\n## The Apache Software Foundation (ASF) licenses this file to you under ##\n## the Apache License, Version 2.0 (the \"License\"); you may not use this ##\n## file except in compliance with the License. You should have received ##\n## a copy of the Apache License, Version 2.0 along with this file; see ##\n## the file LICENSE. If not, 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 ##\n## mplied. See the License for the specific language governing ##\n## permissions and limitations under the License. ##\n\nimport re\nimport warnings\n\nfrom path import Path\n\nSETTINGS = [dict(ext = [\".bat\"],\n left = r':: '),\n dict(ext = [\".sh\", \".py\", \".yaml\", \".yml\"],\n left = '## '),\n dict(ext = [\".c\", \".cc\", \".cpp\", \".c++\", \".h\"],\n left = r'// '),\n dict(ext = [\".rst\"],\n left = r'.. ')]\n\nfor index, SETTING in enumerate(SETTINGS):\n if 'right' not in SETTING and 'left' in SETTING:\n SETTING['right'] = ''.join(reversed(SETTING['left']))\n elif 'left' not in SETTING and 'right' in SETTING:\n SETTING['left'] = ''.join(reversed(SETTING['right']))\n elif 'left' not in SETTING and 'right' not in SETTING:\n raise ValueError('invalid setting at position ' + str(index))\n\nSETTINGS = {ext : SETTING for SETTING in SETTINGS for ext in SETTING['ext']}\nSETTINGS['SConstruct'] = SETTINGS['.py']\nSETTINGS['SConscript'] = SETTINGS['.py']\n\nIGNORE = {\".sublime-project\",\n \".json\"}\n\ndef setting(filepath):\n SETTING = SETTINGS.get(filepath.ext, SETTINGS.get(filepath.basename(), None))\n if SETTING is None:\n if filepath.ext not in IGNORE and filepath.basename() not in IGNORE:\n warnings.warn(\"No settings found for file '\" + filepath + \"'\")\n return SETTING\n\ndef find(filepath):\n if not isinstance(filepath, Path):\n filepath = Path(filepath)\n if not(filepath.exists() or filepath.isfile()):\n raise ValueError(\"'filepath' parameter is not a valid path to a file\")\n start = 0\n end = -1\n SETTING = setting(filepath)\n if SETTING is not None:\n with open(filepath, 'r') as filehandler:\n pattern = re.compile('^' + SETTING['left'] + '.*' + SETTING['right'] + '$')\n start = 0\n line = filehandler.readline()\n while line and not pattern.match(line):\n start += 1\n line = filehandler.readline()\n if not line:\n start = 0\n else:\n end = start\n line = filehandler.readline()\n while line and pattern.match(line):\n end += 1\n line = filehandler.readline()\n return start, end\n\ndef generate(filepath, notice):\n if not isinstance(filepath, Path):\n filepath = Path(filepath)\n if not(filepath.exists() or filepath.isfile()):\n raise ValueError(\"'filepath' parameter is not a valid path to a file\")\n SETTING = setting(filepath)\n if SETTING is not None:\n lines = notice.splitlines()\n max_width = 0\n for index, line in enumerate(lines):\n line = line.rstrip()\n lines[index] = line\n max_width = max(max_width, len(line))\n return [SETTING[\"left\"] + line + \" \" * (max_width - len(line)) + SETTING[\"right\"] + \"\\n\" for line in lines]\n\ndef replace(filepath, notice):\n if not isinstance(filepath, Path):\n filepath = Path(filepath)\n if not(filepath.exists() or filepath.isfile()):\n raise ValueError(\"'filepath' parameter is not a valid path to a file\")\n SETTING = setting(filepath)\n if SETTING is not None:\n with open(filepath, \"r\") as filehandler:\n lines = list(filehandler.readlines())\n if len(lines) > 0:\n start, end = find(filepath)\n newlines = lines[:start]\n if start > 0 and lines[start - 1].strip():\n newlines += [\"\\n\"]\n newlines += generate(filepath, notice)\n if end + 1 < len(lines):\n if lines[end + 1].strip():\n newlines += [\"\\n\"]\n newlines += lines[end + 1:]\n else:\n newlines = generate(filepath, notice)\n else:\n with open(filepath, \"r\") as filehandler:\n newlines = filehandler.readlines()\n return \"\".join(newlines)","sub_path":"src/py/devops_tools/notice.py","file_name":"notice.py","file_ext":"py","file_size_in_byte":5448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"222452273","text":"import math\nimport sys\nimport os.path as op\nimport numpy as np\nimport matplotlib; matplotlib.use('agg')\nimport matplotlib.pyplot as plt\nimport mne\nfrom functions import sentcomp_epoching\n\ndef regularization_path(model, settings, params):\n fig, ax1 = plt.subplots()\n\n # Plot regression coef for each regularization size (alpha)\n ax1.plot(model.alphas, model.coefs)\n ax1.set_xscale('log')\n ax1.set_xlabel('Regularization size', size=18)\n ax1.set_ylabel('weights', size=18)\n plt.title(settings.method + ' regression')\n\n # Plot error on the same figure\n ax2 = ax1.twinx()\n scores = model.cv_results_['mean_test_score']\n scores_std = model.cv_results_['std_test_score']\n std_error = scores_std / np.sqrt(params.CV_fold)\n ax2.plot(model.alphas, scores, 'r.', label='R-squared training set')\n ax2.fill_between(model.alphas, scores + std_error, scores - std_error, alpha=0.2)\n ax2.set_ylabel('R-squared', color='r', size=18)\n ax2.tick_params('y', colors='r')\n\n scores_train = model.cv_results_['mean_train_score']\n scores_train_std = model.cv_results_['std_train_score']\n std_train_error = scores_train_std / np.sqrt(params.CV_fold)\n ax2.plot(model.alphas, scores_train, 'g.', label='R-squared test set')\n ax2.fill_between(model.alphas, scores_train + std_train_error, scores_train - std_train_error, alpha=0.2)\n\n plt.axis('tight')\n plt.legend(loc=4)\n\n return plt\n\n\ndef plot_topomap_optimal_bin(settings, params):\n\n # Load f-statistic results from Output folder\n f_stats_all = []\n for channel in range(settings.num_MEG_channels):\n file_name = 'MEG_data_sentences_averaged_over_optimal_bin_channel_' + str(channel + 1) + '.npz'\n npzfile = np.load(op.join(settings.path2output, file_name))\n f_stats_all.append(npzfile['arr_1'])\n\n num_bin_sizes, num_bin_centers = f_stats_all[0].shape\n\n # Load epochs data from fif file, which includes channel loactions\n epochs = mne.read_epochs(op.join(settings.path2MEGdata, settings.raw_file_name))\n\n # Generate epochs locked to anomalous words\n anomaly = 0 # 0: normal, 1: nonword (without vowels), 2: syntactic, 3: semantic\n position = [4, 6, 8] # 0,1,2..8\n responses = [0, 1] # Correct/wrong response of the subject\n structures = [1, 2, 3] # 1: 4-4, 2: 2-6, 3: 6-2\n\n conditions = dict([\n ('Anomalies', [anomaly]),\n ('Positions', position),\n ('Responses', responses),\n ('Structure', structures)])\n\n knames1, _ = sentcomp_epoching.get_condition(conditions=conditions, epochs=epochs, startTime=-.2,\n duration=1.5, real_speed=params.real_speed/1e3)\n\n epochs_curr_condition = epochs[knames1]\n\n # Generate fake power spectrum, to be replace with f-stat later\n freqs = range(51,51 + num_bin_sizes,1); n_cycles = 1\n power = mne.time_frequency.tfr_morlet(epochs_curr_condition, freqs=freqs, n_cycles=n_cycles, use_fft=True,\n decim=3, n_jobs=4)\n f_stat_object = power[0]\n f_stat_object._data = np.rollaxis(np.dstack(f_stats_all), -1)\n fig_topo = f_stat_object.plot_topo(layout_scale=1.1, title='F-statistic for varying bin sizes and centers', vmin=0, vmax=5,\n fig_facecolor='w', font_color='k', show=False)\n\n\n f_stat_object.times = np.asarray(range(1,num_bin_centers,1))\n f_stat_object.freqs = np.asarray(freqs)\n\n #subplot_square_side = math.ceil(np.sqrt(num_bin_centers))\n\n for i, t in enumerate(f_stat_object.times):\n curr_fig = f_stat_object.plot_topomap(tmin=t, tmax=t, fmin=np.min(freqs), fmax=1 + np.min(freqs), show=False)\n file_name = 'f_stats_topomap_patient_' + settings.patient + '_time_' + str(t)\n plt.savefig(op.join(settings.path2figures, file_name))\n plt.close(curr_fig)\n\n return fig_topo\n\ndef plot_topomap_regression_results(settings, params):\n\n # Load regression results from Output folder\n import pickle\n time_points = range(0, params.SOA + 1, 10)\n best_R_squared_LASSO = np.zeros([306, len(time_points)])\n if settings.collect_data:\n for t, time_point in enumerate(time_points):\n for channel in range(306):#settings.num_MEG_channels):\n pkl_filename = 'Regression_models_' + settings.patient + '_channel_' + str(channel+1) + '_timepoint_' + str(time_point) + '_averaged_over_' + str(params.step) + '_' + settings.LSTM_file_name + '.pckl'\n #'Regression_models_' + settings.patient + '_channel_' + str(channel+1) + '_timepoint_' + str(\n #time_point) + '_' + settings.LSTM_file_name + '.pckl'\n models = []\n # with open(op.join(settings.path2output, pkl_filename), \"rb\") as f:\n # while True:\n # try:\n # curr_results.append(pickle.load(f))\n # except EOFError:\n # break\n with open(op.join(settings.path2output, pkl_filename), \"rb\") as f:\n try:\n curr_results = pickle.load(f)\n best_R_squared_LASSO[channel, t] = curr_results['lasso_scores_test']\n except EOFError:\n break\n sys.stdout.write('Channel ' + str(channel) + ' time point ' + str(t) + ' ')\n print(best_R_squared_LASSO[channel, t])\n # Extract best score on validation set\n #best_R_squared_LASSO[channel] = models[2].best_score_\n # best_R_squared_LASSO[channel] = models[channel]\n\n #best_R_squared_LASSO = best_R_squared_LASSO + [0] * 196\n #best_R_squared_LASSO = [[x] for x in best_R_squared_LASSO]\n\n pkl_filename = 'best_R_squared_Lasso' + settings.patient + '_' + settings.LSTM_file_name + '.pckl'\n with open(op.join(settings.path2output, pkl_filename), 'w') as f: # Python 3: open(..., 'wb')\n pickle.dump(best_R_squared_LASSO, f)\n else:\n pkl_filename = 'best_R_squared_Lasso' + settings.patient + '_' + settings.LSTM_file_name + '.pckl'\n with open(op.join(settings.path2output, pkl_filename), 'r') as f: # Python 3: open(..., 'wb')\n best_R_squared_LASSO = pickle.load(f)\n\n # Load epochs data from fif file, which includes channel loactions\n epochs = mne.read_epochs(op.join(settings.path2MEGdata, settings.raw_file_name))\n\n # Generate epochs locked to anomalous words\n anomaly = 0 # 0: normal, 1: nonword (without vowels), 2: syntactic, 3: semantic\n position = [4, 6, 8] # 0,1,2..8\n responses = [0, 1] # Correct/wrong response of the subject\n structures = [1, 2, 3] # 1: 4-4, 2: 2-6, 3: 6-2\n\n conditions = dict([\n ('Anomalies', [anomaly]),\n ('Positions', position),\n ('Responses', responses),\n ('Structure', structures)])\n\n knames1, _ = sentcomp_epoching.get_condition(conditions=conditions, epochs=epochs, startTime=-.2,\n duration=1.5, real_speed=params.real_speed/1e3)\n\n # Generate fake evoked spectrum, to be replace with regression results later\n evoked = epochs[knames1].average()\n evoked._data = np.asarray(best_R_squared_LASSO)\n evoked.times = np.asarray(time_points)\n #evoked.times = [0]\n #fig_topo = evoked.plot_topomap(times=0, show=True)\n print(time_points)\n fig_topo = evoked.plot_topomap(times=time_points[params.i], show=False)\n fig_topo.axes[1].axes.title._text = 'R-squared'\n fig_topo.axes[0].axes.title._text = str(params.i * 10) + ' msec'\n # ax = plt.gca() # plt.gca() for current axis, otherwise set appropriately.\n\n # im = fig_topo.axes[0].images\n # cbar = im[-1].colorbar\n # cbar._values = best_R_squared_LASSO\n # fig_topo.axes[0].images[0].colorbar.vmin = -1\n # fig_topo.axes[0].images[0].colorbar.vmax = 1\n # fig_topo.axes[0].images[0].colorbar.set_ticks([np.min(best_R_squared_LASSO), np.max(best_R_squared_LASSO)])\n fig_topo.axes[0].images[0].colorbar.set_ticklabels(np.linspace(np.min(best_R_squared_LASSO[:, params.i]), np.max(best_R_squared_LASSO[:, params.i]), 5),\n update_ticks=True)\n return fig_topo\n","sub_path":"Code/MEG/functions/plot_results.py","file_name":"plot_results.py","file_ext":"py","file_size_in_byte":8320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"46156805","text":"class Iterator(object):\n\tdef __init__(self,arr):\n\t\tself.nextArr = 0\n\t\tself.nextInd = 0\n\t\tself.curArr = 0\n\t\tself.curInd = 0\n\t\tself.preArr = 0\n\t\tself.preInd = 0\n\t\tself.arr = arr\n\n\tdef setnext(self):\n\t\t# print('moving')\n\t\t# print('cur')\n\t\t# print(self.curArr,self.curInd,self.arr[self.curArr][self.curInd])\n\t\tcurLen = self.arr[self.curArr]\n\t\tres = False\n\t\t# print(curLen)\n\t\tif self.curInd < len(curLen) - 1:\n\t\t\tself.nextInd = self.curInd + 1\n\t\t\tself.nextArr = self.curArr\n\t\telse:\n\t\t\twhile self.curArr + 1 < len(self.arr) and len(self.arr[self.curArr + 1]) == 0:\n\t\t\t\tself.curArr += 1\n\t\t\tif self.curArr + 1 >= len(self.arr):\n\t\t\t\t# print(res)\n\t\t\t\treturn res\n\t\t\tself.nextArr = self.curArr + 1\n\t\t\tself.nextInd = 0\n\t\tres = True\n\t\treturn res\n\n\tdef hasnext(self):\n\t\tself.setnext()\n\t\treturn self.nextArr < len(self.arr) and self.nextInd < len(self.arr[self.nextArr])\n\n\tdef next(self):\n\t\tif self.nextArr == 0 and self.nextInd == 0:\n\t\t\tres = self.arr[self.curArr][self.curInd]\n\t\telse:\n\t\t\tres = self.arr[self.nextArr][self.nextInd]\n\t\t\tself.curArr = self.nextArr\n\t\t\tself.curInd = self.nextInd\n\t\t\tself.setnext()\n\t\treturn res\n\n\n\tdef remove(self):\n\t\tdel self.arr[curArr][curInd]\n\t\tprint(self.arr)\n\n\narr = [[1],[],[],[],[4,5,6],[]]\n\ni = Iterator(arr)\nprint(i.hasnext())\nprint(i.next())\nprint(i.hasnext())\nprint(i.next())\nprint(i.hasnext())\nprint(i.next())\nprint(i.hasnext())\nprint(i.next())\nprint(i.hasnext())\nprint(i.next())\nprint(i.hasnext())\nprint(i.next())\n\n# i.movetonext()\n# i.curArr = i.nextArr\n# i.curInd = i.nextInd\n# i.movetonext()\n# i.curArr = i.nextArr\n# i.curInd = i.nextInd\n# i.movetonext()\n# i.curArr = i.nextArr\n# i.curInd = i.nextInd\n# i.movetonext()\n# i.curArr = i.nextArr\n# i.curInd = i.nextInd\n# print(i.movetonext())","sub_path":"arrayiterator.py","file_name":"arrayiterator.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"148935970","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nCreated on 1/6/21 2:52 PM\n@Author : Justin Jiang\n@Email : jw_jiang@pku.edu.com\n\"\"\"\n\nimport re\n\n\ndef mostCommonWord(paragraph, banned):\n arr = paragraph.strip().split()\n record = dict()\n for word in arr:\n word = re.findall(r'[a-z]+', word.lower())[0]\n if word not in record:\n record.setdefault(word, 1)\n else:\n record[word] += 1\n for word in banned:\n record[word] = 0\n max_cnt = max(record.values())\n for key, val in record.items():\n if val == max_cnt:\n return key\n return\n\n\nif __name__ == '__main__':\n paragraph = \"Bob hit a ball, the hit BALL flew far after it was hit.\"\n banned = [\"hit\"]\n print(mostCommonWord(paragraph, banned))\n","sub_path":"20201029/819_mostCommonWord.py","file_name":"819_mostCommonWord.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"597705994","text":"#!/usr/bin/python3.6\n#!/usr/bin/env python3.6\n# coding: utf-8\n\nimport subprocess\nimport pandas as pd\n\ninputFileName = 'FINAL_FROM_DF.csv'\noutputFileName = 'FINAL_FROM_DF_SERIES.csv'\ninputHdfsFilePath = '/user/hadoop/'+inputFileName\noutputHdfsFilePath = '/user/hadoop/EQ/'+outputFileName\ninputLocalFilePath = '/home/hadoop/Shasank/case_study4/'+inputFileName\noutputLocalFilePath = '/home/hadoop/Shasank/case_study4/'+outputFileName\ndef run_cmd(args_list):\n print('Running system command: {0}'.format(' '.join(args_list)))\n proc = subprocess.Popen(args_list, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n (output, errors) = proc.communicate()\n if proc.returncode:\n raise RuntimeError(\n 'Error running command: %s. Return code: %d, Error: %s' % (\n ' '.join(args_list), proc.returncode, errors))\n return (output, errors)\n\n# copying hdfs file to local\n(out, errors)= run_cmd(['hdfs', 'dfs', '-copyToLocal', '-f', inputHdfsFilePath])\n\n# processing csv file using pandas\ndata = pd.read_csv(inputLocalFilePath)\ndata.columns = [column.replace(\" \", \"_\") for column in data.columns]\n# filtering with query method\ndata.query('SERIES == \"EQ\"', inplace = True)\nexport_csv = data.to_csv(outputLocalFilePath, index=False)\n\n# creating EQ directory\n(out, errors)= run_cmd(['hdfs', 'dfs', '-mkdir', '-p', '/user/hadoop/EQ'])\n\n# copying local file to hdfs\n(out, errors)= run_cmd(['hdfs', 'dfs', '-copyFromLocal', '-f', outputLocalFilePath, outputHdfsFilePath])","sub_path":"pythonProjects/Edureka_case_studies_Pyspark/case study 4/4_7_1_pythonDf.py","file_name":"4_7_1_pythonDf.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"69512331","text":"import numpy as np \nfrom scipy.spatial import distance\nimport matplotlib.pyplot as plt\nimport os\nfrom scipy.interpolate import InterpolatedUnivariateSpline\n\nnp.warnings.filterwarnings('ignore', category=np.VisibleDeprecationWarning)\n#recebe como parametro os parametros estocasticos, individuos, e os valores experimentais\ndef viralmodelfit(poi, exp, V0, pat_cont, t_exp):\n epsilon_r = poi[0]\n epsilon_alpha = poi[1]\n epsilon_s = poi[2]\n alpha = poi[3]\n r = poi[4]\n delta = poi[5]\n mu_c = poi[6]\n rho = poi[7]\n theta = poi[8]\n sigma = poi[9]\n c = poi[10]\n\n with open('parametros_DE.txt', 'w') as filep:\n filep.write(str(V0)+\",\"+str(epsilon_r)+\",\"+str(epsilon_alpha)+\",\"+str(epsilon_s)+\n \",\"+str(alpha)+\",\"+str(r)+\",\"+str(delta)+\n \",\"+str(mu_c)+\",\"+str(rho)+\",\"+str(theta)+\n \",\"+str(sigma)+\",\"+str(c))\n #os.system(\"make clean\")\n #os.system(\"make\")\n os.system(\"make run\")#Executa o modelo C++\n tempoPt = np.empty(0)\n V = np.empty(0)\n V_log = np.empty(0)\n with open(\"saida.txt\", 'r') as f:\n lista = [line.split(',') for line in f]\n for linha in lista:\n tempoPt = np.append(tempoPt, float(linha[0]))\n V = np.append(V, float(linha[1]))\n try:\n # Passa para a base log o resultado\n V_log = np.log10(V)\n V_pts = []\n for t in t_exp[pat_cont]:\n V_pts.append(V_log[int(t*100+1)])\n #ius = InterpolatedUnivariateSpline(t_exp[pat_cont], exp)\n #yi = ius(tempoPt)\n #plt.plot(tempoPt, yi, '--r', label='polinomio')\n \n # dst = distance.euclidean(V_log, yi) Fica muito ruim\n plt.plot(tempoPt, V_log, '-g', label='Modelo')\n # plt.plot(t_exp[pat_cont], V_pts, '^g') Prova de que esta pegando os pontos certos\n plt.plot(t_exp[pat_cont], exp, 'or', label='dados experimentais')\n # plt.show()\n dst = distance.euclidean(V_pts, exp)/len(V_pts)\n except:\n dst = 1000\n return dst","sub_path":"codigo_C++lt5/differential_evolution/depend/cost.py","file_name":"cost.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"179176385","text":"# python3\n\nimport sys\n\nclass Bracket:\n def __init__(self, bracket_type, position):\n self.bracket_type = bracket_type\n self.position = position\n\n def Match(self, c):\n if self.bracket_type == '[' and c == ']':\n return True\n if self.bracket_type == '{' and c == '}':\n return True\n if self.bracket_type == '(' and c == ')':\n return True\n return False\n\nif __name__ == \"__main__\":\n text = sys.stdin.read()\n\n opening_brackets_stack = []\n success = 1\n for i, next in enumerate(text):\n if next == '(' or next == '[' or next == '{':\n bracket = Bracket(next, i+1)\n opening_brackets_stack.append(bracket)\n continue\n\n if next == ')' or next == ']' or next == '}':\n nextBracket = Bracket(next, i+1)\n if opening_brackets_stack!=[]:\n bracket = opening_brackets_stack.pop()\n elif i==0:\n success=0\n index=1\n break\n else:\n success=0\n index=nextBracket.position\n break\n \n if bracket.Match(nextBracket.bracket_type):\n continue\n else:\n index = nextBracket.position\n success = 0\n break\n #Final check to see if all brackets have been satisfied\n if success==0:\n print(index)\n elif opening_brackets_stack != []:\n mismatch = opening_brackets_stack.pop()\n print(mismatch.position)\n else:\n print(\"Success\")\n \n","sub_path":"1DataStructures/Week1/check_brackets_in_code/check_brackets.py","file_name":"check_brackets.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"524270611","text":"def isScramble(s1, s2):\n d1 = {}\n for i, e in enumerate(s1):\n d1[e] = i\n d2 = {}\n for i, e in enumerate(s2):\n d2[e] = i\n diff = []\n for e in s2:\n diff.append(d2[e]-d1[e])\n \n \ndef reverse(s, l, r):\n if l <= r:\n i = 0\n while i <= l+(r-l)/2:\n s[l+i], s[r-i] = s[r-i], s[l+i]\n \n \n \n","sub_path":"scramble_string.py","file_name":"scramble_string.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"216844666","text":"import os\nimport numpy as np\nfrom torch.utils.data import DataLoader\nimport torchvision.datasets as dataset\nimport torch\nfrom scipy.optimize import linear_sum_assignment\n\nimport config\n\n\ndef get_features(data_loader, net, mode=None, source_centers=None):\n features_list = []\n res_features_list = []\n labels_list = []\n with torch.no_grad():\n for i, data in enumerate(data_loader):\n inputs, labels = data\n inputs = inputs.cuda()\n net.eval()\n features, _, res_features = net(inputs, source_centers=source_centers)\n features_list.append(features)\n res_features_list.append(torch.tensor(res_features))\n for label in labels:\n labels_list.append(label.numpy())\n print(\"extract the {} feature\".format(i * config.target_batch_size))\n torch.cuda.empty_cache()\n\n features = torch.cat(features_list, 0).cpu().numpy()\n res_features = torch.cat(res_features_list, 0).numpy()\n labels = np.array(labels_list)\n if mode is None:\n pass\n elif mode == 'train':\n np.save('train_features.npy', features, allow_pickle=True)\n np.save('train_labels.npy', labels, allow_pickle=True)\n elif mode == 'test':\n np.save('test_features.npy', features, allow_pickle=True)\n np.save('test_labels.npy', labels, allow_pickle=True)\n return features, labels, res_features\n\n\ndef save_txt_files(path, the_list):\n if os.path.exists(path) is not True:\n f = open(path,'w')\n f.close()\n f = open(path, 'a')\n for i in the_list:\n f.write(str(i) + '\\n')\n f.close()\n\n\ndef save_txt_files2(path, the_list):\n f = open(path, 'w')\n for i in the_list:\n f.write(str(i) + '\\n')\n f.close()\n\n\ndef cluster_acc(y_true, y_pred, class_number): # 聚类精度 真正标签与预测标签\n cnt_mtx = np.zeros([class_number, class_number])\n\n # fill in matrix\n for i in range(len(y_true)):\n cnt_mtx[int(y_pred[i]), int(y_true[i])] += 1\n\n # find optimal permutation\n row_ind, col_ind = linear_sum_assignment(-cnt_mtx)\n\n # compute error\n acc = cnt_mtx[row_ind, col_ind].sum() / cnt_mtx.sum()\n\n labels_pred = []\n for index, label in enumerate(y_pred):\n target_label = col_ind[label]\n # print('label', label)\n # print('target', target_label)\n # print('true', y_true[index])\n labels_pred.append(target_label)\n # print(labels_pred[:10])\n # print(list(y_true)[:10])\n\n return acc, list(y_true), labels_pred\n\n\n\n\n\n\n\n\n\n","sub_path":"3_Code_for_Babesia_Recgnition/utils_fun.py","file_name":"utils_fun.py","file_ext":"py","file_size_in_byte":2556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"563183318","text":"\"\"\" Specific utilities re-factored from the benchmarking utilities. \"\"\"\n\nimport os\nimport shutil\nimport numpy as np\nimport xarray as xr\nimport matplotlib.pyplot as plt\nimport cartopy.crs as ccrs\nimport json\nimport copy\nfrom json import load as json_load_file\nimport matplotlib as mpl\nfrom matplotlib.backends.backend_pdf import PdfPages\nfrom matplotlib.colors import ListedColormap\nfrom cartopy import crs\nfrom cartopy.mpl.geoaxes import GeoAxes # for assertion\nfrom PyPDF2 import PdfFileWriter, PdfFileReader\nfrom .plot import WhGrYlRd, add_latlon_ticks\nfrom .grid.horiz import make_grid_LL, make_grid_CS\nfrom .grid.regrid import make_regridder_C2L, make_regridder_L2L\nfrom .grid.gc_vertical import GEOS_72L_grid\nfrom . import core\nfrom .units import convert_units\n\ncmap_abs = WhGrYlRd # for plotting absolute magnitude\ncmap_diff = 'RdBu_r' # for plotting difference\n\naod_spc = 'aod_species.json'\nspc_categories = 'benchmark_categories.json'\nemission_spc = 'emission_species.json' \nemission_inv = 'emission_inventories.json' \n\ndef compare_single_level(refdata, refstr, devdata, devstr, varlist=None,\n ilev=0, itime=0, weightsdir=None, pdfname='',\n cmpres=None, match_cbar=True, normalize_by_area=False,\n enforce_units=True, flip_ref=False, flip_dev=False,\n use_cmap_RdBu=False, verbose=False, \n log_color_scale=False, sigdiff_list=[]):\n '''\n Create single-level 3x2 comparison map plots for variables common in two xarray\n datasets. Optionally save to PDF. \n\n Args:\n refdata : xarray dataset\n Dataset used as reference in comparison\n\n refstr : str\n String description for reference data to be used in plots\n \n devdata : xarray dataset\n Dataset used as development in comparison\n\n devstr : str\n String description for development data to be used in plots\n \n Keyword Args (optional):\n varlist : list of strings\n List of xarray dataset variable names to make plots for\n Default value: None (will compare all common variables)\n\n ilev : integer\n Dataset level dimension index using 0-based system\n Default value: 0 \n\n itime : integer\n Dataset time dimension index using 0-based system\n Default value: 0\n\n weightsdir : str\n Directory path for storing regridding weights\n Default value: None (will create/store weights in current directory)\n\n pdfname : str\n File path to save plots as PDF\n Default value: Empty string (will not create PDF)\n\n cmpres : str\n String description of grid resolution at which to compare datasets\n Default value: None (will compare at highest resolution of ref and dev)\n\n match_cbar : boolean\n Logical indicating whether to use same colorbar bounds across plots\n Default value: True\n\n normalize_by_area : boolean\n Logical indicating whether to normalize raw data by grid area\n Default value: False\n\n enforce_units : boolean\n Logical to force an error if reference and development variables units differ\n Default value: True\n\n flip_ref : boolean\n Logical to flip the vertical dimension of reference dataset 3D variables\n Default value: False\n\n flip_dev : boolean\n Logical to flip the vertical dimension of development dataset 3D variables\n Default value: False\n\n use_cmap_RdBu : boolean\n Logical to used a blue-white-red colormap for plotting raw reference and\n development datasets.\n Default value: False\n\n verbose : boolean\n Logical to enable informative prints\n Default value: False\n\n log_color_scale: boolean \n Logical to enable plotting data (not diffs) on a log color scale.\n Default value: False\n\n sigdiff_list: list of str\n Returns a list of all quantities having significant differences.\n The criteria is: |max(fractional difference)| > 0.1\n Default value: []\n\n Returns:\n Nothing\n\n Example:\n >>> import matplotlib.pyplot as plt\n >>> import xarray as xr\n >>> from gcpy import benchmark\n >>> refds = xr.open_dataset('path/to/ref.nc4')\n >>> devds = xr.open_dataset('path/to/dev.nc4')\n >>> varlist = ['SpeciesConc_O3', 'SpeciesConc_NO']\n >>> benchmark.compare_single_level( refds, '12.3.2', devds, 'bug fix', varlist=varlist )\n >>> plt.show()\n '''\n\n # TODO: refactor this function and zonal mean plot function. There is a lot of overlap and\n # repeated code that could be abstracted.\n\n # Error check arguments\n if not isinstance(refdata, xr.Dataset):\n raise ValueError('The refdata argument must be an xarray Dataset!')\n\n if not isinstance(devdata, xr.Dataset):\n raise ValueError('The devdata argument must be an xarray Dataset!')\n\n # If no varlist is passed, plot all (surface only for 3D)\n if varlist == None:\n [varlist, commonvars2D, commonvars3D] = core.compare_varnames(refdata, devdata)\n print('Plotting all common variables (surface only if 3D)')\n n_var = len(varlist)\n\n # If no weightsdir is passed, set to current directory in case it is needed\n if weightsdir == None:\n weightsdir = '.'\n\n # If no pdf name passed, then do not save to PDF\n savepdf = True\n if pdfname == '':\n savepdf = False\n\n ####################################################################\n # Determine input grid resolutions and types\n ####################################################################\n\n # GCC output and GCHP output using pre-v1.0.0 MAPL have lat and lon dims\n\n # ref\n vdims = refdata.dims\n if 'lat' in vdims and 'lon' in vdims:\n refnlat = refdata.sizes['lat']\n refnlon = refdata.sizes['lon']\n if refnlat == 46 and refnlon == 72:\n refres = '4x5'\n refgridtype = 'll'\n elif refnlat == 91 and refnlon == 144:\n refres = '2x2.5'\n refgridtype = 'll'\n elif refnlat/6 == refnlon:\n refres = refnlon\n refgridtype = 'cs'\n else:\n print('ERROR: ref {}x{} grid not defined in gcpy!'.format(refnlat,refnlon))\n return\n else:\n # GCHP data using MAPL v1.0.0+ has dims time, lev, nf, Ydim, and Xdim\n refres = refdata.dims['Xdim']\n refgridtype = 'cs'\n\n # dev\n vdims = devdata.dims\n if 'lat' in vdims and 'lon' in vdims:\n devnlat = devdata.sizes['lat']\n devnlon = devdata.sizes['lon']\n if devnlat == 46 and devnlon == 72:\n devres = '4x5'\n devgridtype = 'll'\n elif devnlat == 91 and devnlon == 144:\n devres = '2x2.5'\n devgridtype = 'll'\n elif devnlat/6 == devnlon:\n devres = devnlon\n devgridtype = 'cs'\n else:\n print('ERROR: dev {}x{} grid not defined in gcpy!'.format(refnlat,refnlon))\n return\n else:\n devres = devdata.dims['Xdim']\n devgridtype = 'cs'\n\n ####################################################################\n # Determine comparison grid resolution and type (if not passed)\n ####################################################################\n\n # If no cmpres is passed then choose highest resolution between ref and dev.\n # If both datasets are cubed sphere then default to 1x1.25 for comparison.\n if cmpres == None:\n if refres == devres and refgridtype == 'll':\n cmpres = refres\n cmpgridtype = 'll'\n elif refgridtype == 'll' and devgridtype == 'll':\n cmpres = min([refres, devres])\n cmpgridtype = 'll'\n elif refgridtype == 'cs' and devgridtype == 'cs':\n cmpres = max([refres, devres])\n cmpgridtype = 'cs'\n else:\n cmpres = '1x1.25'\n cmpgridtype = 'll'\n elif 'x' in cmpres:\n cmpgridtype = 'll'\n else:\n cmpgridtype = 'cs'\n \n # Determine what, if any, need regridding.\n regridref = refres != cmpres\n regriddev = devres != cmpres\n regridany = regridref or regriddev\n \n ####################################################################\n # Make grids (ref, dev, and comparison)\n ####################################################################\n\n # Ref\n if refgridtype == 'll':\n refgrid = make_grid_LL(refres)\n else:\n [refgrid, regrid_list] = make_grid_CS(refres)\n\n # Dev\n if devgridtype == 'll':\n devgrid = make_grid_LL(devres)\n else:\n [devgrid, devgrid_list] = make_grid_CS(devres)\n\n # Comparison \n if cmpgridtype == 'll':\n cmpgrid = make_grid_LL(cmpres)\n else:\n [cmpgrid, cmpgrid_list] = make_grid_CS(cmpres)\n \n ####################################################################\n # Make regridders, if applicable\n ####################################################################\n\n if regridref:\n if refgridtype == 'll':\n refregridder = make_regridder_L2L(refres, cmpres, weightsdir=weightsdir, reuse_weights=True)\n else:\n refregridder_list = make_regridder_C2L(refres, cmpres, weightsdir=weightsdir, reuse_weights=True)\n if regriddev:\n if devgridtype == 'll':\n devregridder = make_regridder_L2L(devres, cmpres, weightsdir=weightsdir, reuse_weights=True)\n else:\n devregridder_list = make_regridder_C2L(devres, cmpres, weightsdir=weightsdir, reuse_weights=True)\n\n ####################################################################\n # Get lat/lon extents, if applicable\n ####################################################################\n \n if refgridtype == 'll':\n [refminlon, refmaxlon] = [min(refgrid['lon_b']), max(refgrid['lon_b'])]\n [refminlat, refmaxlat] = [min(refgrid['lat_b']), max(refgrid['lat_b'])]\n if devgridtype == 'll':\n [devminlon, devmaxlon] = [min(devgrid['lon_b']), max(devgrid['lon_b'])]\n [devminlat, devmaxlat] = [min(devgrid['lat_b']), max(devgrid['lat_b'])]\n if cmpgridtype == 'll':\n [cmpminlon, cmpmaxlon] = [min(cmpgrid['lon_b']), max(cmpgrid['lon_b'])]\n [cmpminlat, cmpmaxlat] = [min(cmpgrid['lat_b']), max(cmpgrid['lat_b'])]\n\n ####################################################################\n # Create pdf if saving to file\n ####################################################################\n \n if savepdf:\n print('\\nCreating {} for {} variables'.format(pdfname,n_var))\n pdf = PdfPages(pdfname)\n \n ####################################################################\n # Loop over variables\n ####################################################################\n\n print_units_warning = True\n for ivar in range(n_var):\n if savepdf: print('{} '.format(ivar), end='')\n varname = varlist[ivar]\n varndim_ref = refdata[varname].ndim\n varndim_dev = devdata[varname].ndim \n\n # If units are mol/mol then convert to ppb\n conc_units = ['mol mol-1 dry','mol/mol','mol mol-1']\n if refdata[varname].units.strip() in conc_units:\n refdata[varname].attrs['units'] = 'ppbv'\n refdata[varname].values = refdata[varname].values * 1e9\n if devdata[varname].units.strip() in conc_units:\n devdata[varname].attrs['units'] = 'ppbv'\n devdata[varname].values = devdata[varname].values * 1e9\n\n # Binary diagnostic concentrations have units ppbv. Change to ppb.\n if refdata[varname].units.strip() == 'ppbv':\n refdata[varname].attrs['units'] = 'ppb'\n if devdata[varname].units.strip() == 'ppbv':\n devdata[varname].attrs['units'] = 'ppb'\n\n # Check that units match\n units_ref = refdata[varname].units.strip()\n units_dev = devdata[varname].units.strip()\n if units_ref != units_dev:\n print_units_warning=True\n if print_units_warning:\n print('WARNING: ref and dev concentration units do not match!')\n print('Ref units: {}'.format(units_ref))\n print('Dev units: {}'.format(units_dev))\n if enforce_units:\n # if enforcing units, stop the program if units do not match\n assert units_ref == units_dev, 'Units do not match for {}!'.format(varname)\n else:\n # if not enforcing units, just keep going after only printing warning once \n print_units_warning = False\n\n \n ################################################################\n # Slice the data, allowing for the\n # possibility of no time dimension (bpch)\n ################################################################\n\n # Ref\n vdims = refdata[varname].dims\n if 'time' in vdims and 'lev' in vdims: \n if flip_ref:\n ds_ref = refdata[varname].isel(time=itime,lev=71-ilev)\n else:\n ds_ref = refdata[varname].isel(time=itime,lev=ilev)\n elif 'lev' in vdims:\n if flip_ref:\n ds_ref = refdata[varname].isel(lev=71-ilev)\n else:\n ds_ref = refdata[varname].isel(lev=ilev)\n elif 'time' in vdims: \n ds_ref = refdata[varname].isel(time=itime)\n else:\n ds_ref = refdata[varname]\n\n # Dev\n vdims = devdata[varname].dims\n if 'time' in vdims and 'lev' in vdims: \n if flip_dev:\n ds_dev = devdata[varname].isel(time=itime,lev=71-ilev)\n else:\n ds_dev = devdata[varname].isel(time=itime,lev=ilev)\n elif 'lev' in vdims:\n if flip_dev:\n ds_dev = devdata[varname].isel(lev=71-ilev)\n else:\n ds_dev = devdata[varname].isel(lev=ilev)\n elif 'time' in vdims: \n ds_dev = devdata[varname].isel(time=itime)\n else:\n ds_dev = devdata[varname]\n\n ################################################################\n # Reshape cubed sphere data if using MAPL v1.0.0+\n # TODO: update function to expect data in this format\n ################################################################\n\n # ref\n vdims = refdata[varname].dims\n if 'nf' in vdims and 'Xdim' in vdims and 'Ydim' in vdims:\n ds_ref = ds_ref.stack(lat=('nf', 'Ydim'))\n ds_ref = ds_ref.rename({'Xdim':'lon'})\n ds_ref = ds_ref.transpose('lat', 'lon')\n\n # dev\n vdims = devdata[varname].dims\n if 'nf' in vdims and 'Xdim' in vdims and 'Ydim' in vdims:\n ds_dev = ds_dev.stack(lat=('nf', 'Ydim'))\n ds_dev = ds_dev.rename({'Xdim':'lon'})\n ds_dev = ds_dev.transpose('lat', 'lon')\n \n ################################################################\n # Area normalization, if any\n ################################################################\n\n # if normalizing by area, adjust units to be per m2,\n # and adjust title string\n units = units_ref\n subtitle_extra = ''\n varndim = varndim_ref\n\n # if regridding then normalization by area may be necessary depending on units. Either pass\n # normalize_by_area=True to normalize all, or include units that should always be normalized\n # by area below. GEOS-Chem Classic output files include area and so do not need to be passed.\n exclude_list = ['WetLossConvFrac','Prod_','Loss_']\n if regridany and ( ( units == 'kg' or units == 'kgC' ) or normalize_by_area ):\n if not any(s in varname for s in exclude_list):\n if 'AREAM2' in refdata.data_vars.keys() and 'AREAM2' in devdata.data_vars.keys():\n ds_ref.values = ds_ref.values / refdata['AREAM2'].values\n ds_dev.values = ds_dev.values / devdata['AREAM2'].values\n else:\n print('ERROR: Variables AREAM2 needed for area normalization missing from dataset')\n return\n units = '{}/m2'.format(units)\n units_ref = units\n units_dev = units\n subtitle_extra = ', Normalized by Area'\n\n ###############################################################\n # Get comparison data sets, regridding input slices if needed\n ###############################################################\n\n # Reshape ref/dev cubed sphere data, if any\n if refgridtype == 'cs':\n ds_ref_reshaped = ds_ref.data.reshape(6,refres,refres)\n if devgridtype == 'cs':\n ds_dev_reshaped = ds_dev.data.reshape(6,devres,devres)\n\n # Ref\n if regridref:\n if refgridtype == 'll':\n # regrid ll to ll\n ds_ref_cmp = refregridder(ds_ref)\n else:\n # regrid cs to ll\n ds_ref_cmp = np.zeros([cmpgrid['lat'].size, cmpgrid['lon'].size])\n for i in range(6):\n regridder = refregridder_list[i]\n ds_ref_cmp += regridder(ds_ref_reshaped[i])\n else:\n ds_ref_cmp = ds_ref\n\n # Dev\n if regriddev:\n if devgridtype == 'll':\n # regrid ll to ll\n ds_dev_cmp = devregridder(ds_dev)\n else:\n # regrid cs to ll\n ds_dev_cmp = np.zeros([cmpgrid['lat'].size, cmpgrid['lon'].size])\n for i in range(6):\n regridder = devregridder_list[i]\n ds_dev_cmp += regridder(ds_dev_reshaped[i])\n else:\n ds_dev_cmp = ds_dev\n\n # Reshape comparison cubed sphere data, if any\n if cmpgridtype == 'cs':\n ds_ref_cmp_reshaped = ds_ref_cmp.data.reshape(6,cmpres,cmpres)\n ds_dev_cmp_reshaped = ds_dev_cmp.data.reshape(6,cmpres,cmpres)\n\n ################################################################\n # Get min and max values for use in the colorbars\n ################################################################\n\n # Ref\n vmin_ref = ds_ref.data.min()\n vmax_ref = ds_ref.data.max()\n\n # Dev\n vmin_dev = ds_dev.data.min()\n vmax_dev = ds_dev.data.max()\n\n # Comparison\n if cmpgridtype == 'cs':\n vmin_ref_cmp = ds_ref_cmp.data.min()\n vmax_ref_cmp = ds_ref_cmp.data.max()\n vmin_dev_cmp = ds_dev_cmp.data.min()\n vmax_dev_cmp = ds_dev_cmp.data.max()\n vmin_cmp = np.min([vmin_ref_cmp, vmin_dev_cmp])\n vmax_cmp = np.max([vmax_ref_cmp, vmax_dev_cmp]) \n else:\n vmin_cmp = np.min([ds_ref_cmp.min(), ds_dev_cmp.min()])\n vmax_cmp = np.max([ds_ref_cmp.max(), ds_dev_cmp.max()])\n\n # Take min/max across all\n vmin_abs = np.min([vmin_ref, vmin_dev, vmin_cmp])\n vmax_abs = np.max([vmax_ref, vmax_dev, vmax_cmp])\n if match_cbar:\n [vmin, vmax] = [vmin_abs, vmax_abs]\n\n if verbose:\n print('vmin_ref: {}'.format(vmin_ref))\n print('vmin_dev: {}'.format(vmin_dev))\n print('vmin_ref_cmp: {}'.format(vmin_ref_cmp))\n print('vmin_dev_cmp: {}'.format(vmin_dev_cmp))\n print('vmin_cmp: {}'.format(vmin_cmp))\n print('vmin_abs: {}'.format(vmin_abs))\n print('vmax_ref: {}'.format(vmax_ref))\n print('vmax_dev: {}'.format(vmax_dev))\n print('vmax_ref_cmp: {}'.format(vmax_ref_cmp))\n print('vmax_dev_cmp: {}'.format(vmax_dev_cmp))\n print('vmax_cmp: {}'.format(vmax_cmp))\n print('vmax_abs: {}'.format(vmax_abs))\n\n ################################################################\n # Create 3x2 figure\n ################################################################\n \n figs, ((ax0, ax1), (ax2, ax3), (ax4, ax5)) = plt.subplots(3, 2, figsize=[12,14], \n subplot_kw={'projection': crs.PlateCarree()})\n # Give the figure a title\n offset = 0.96\n fontsize=25\n \n if 'lev' in ds_ref.dims and 'lev' in ds_dev.dims:\n if ilev == 0: levstr = 'Surface'\n elif ilev == 22: levstr = '500 hPa'\n else: levstr = 'Level ' + str(ilev-1)\n figs.suptitle('{}, {}'.format(varname,levstr), fontsize=fontsize, y=offset)\n elif 'lat' in ds_ref.dims and 'lat' in ds_dev.dims and 'lon' in ds_ref.dims and 'lon' in ds_dev.dims:\n figs.suptitle('{}'.format(varname), fontsize=fontsize, y=offset)\n else:\n print('Incorrect dimensions for {}!'.format(varname)) \n\n ################################################################\n # Set colormap for raw data plots (first row)\n ################################################################\n\n if use_cmap_RdBu:\n cmap1 = copy.copy(mpl.cm.RdBu_r) # Copy to avoid application of cmap.set_bad used later on\n else:\n cmap1 = WhGrYlRd\n \n ################################################################\n # Subplot (0,0): Ref, plotted on ref input grid\n ################################################################\n\n # Set colorbar min/max\n if use_cmap_RdBu:\n if vmin_ref == 0 and vmax_ref == 0:\n [vmin0, vmax0] = [vmin_ref, vmax_ref]\n else:\n if not match_cbar:\n absmax_ref = max([np.abs(vmin_ref), np.abs(vmax_ref)])\n [vmin0, vmax0] = [-absmax_ref, absmax_ref]\n else:\n absmax = max([np.abs(vmin_ref), np.abs(vmax_ref),\n np.abs(vmin_dev), np.abs(vmax_dev)])\n [vmin0, vmax0] = [-absmax, absmax]\n else:\n if not match_cbar:\n [vmin0, vmax0] = [vmin_ref, vmax_ref]\n else:\n [vmin0, vmax0] = [vmin_abs, vmax_abs]\n\n if verbose: print('Subplot (0,0) vmin0, vmax0: {}, {}'.format(\n vmin0, vmax0))\n\n # Plot data for either lat-lon or cubed-sphere grids.\n ax0.coastlines()\n if refgridtype == 'll':\n # Set top title for lat-lon plot\n ax0.set_title('{} (Ref){}\\n{}'.format(\n refstr, subtitle_extra, refres))\n\n # Check if the reference data is all zeroes\n ref_is_all_zeroes = np.all(ds_ref == 0)\n\n # Normalize colors for the plot\n norm0 = normalize_colors(vmin0, vmax0,\n is_all_zeroes=ref_is_all_zeroes,\n log_color_scale=log_color_scale)\n\n # Plot the data\n plot0 = ax0.imshow(ds_ref, extent=(refminlon, refmaxlon,\n refminlat, refmaxlat),\n cmap=cmap1, norm=norm0)\n else:\n # Set top title for cubed-sphere plot\n ax0.set_title('{} (Ref){}\\nc{}'.format(\n refstr, subtitle_extra, refres))\n\n # Mask the reference data\n masked_refdata = np.ma.masked_where(\n np.abs(refgrid['lon'] - 180) < 2, ds_ref_reshaped)\n\n # Check if the reference data is all zeroes\n ref_is_all_zeroes = np.all(masked_refdata == 0)\n\n # Normalize colors (put in range [0..1]) for the plot\n norm0 = normalize_colors(vmin0, vmax0,\n is_all_zeroes=ref_is_all_zeroes,\n log_color_scale=log_color_scale)\n\n # Plot each face of the cubed-sphere\n for i in range(6):\n plot0 = ax0.pcolormesh(refgrid['lon_b'][i,:,:],\n refgrid['lat_b'][i,:,:],\n masked_refdata[i,:,:],\n cmap=cmap1, norm=norm0)\n\n # Define the colorbar for log or linear color scales\n # If all values of Ref = 0, then manually set a tickmark at 0.\n cb = plt.colorbar(plot0, ax=ax0, orientation='horizontal', pad=0.10)\n if ref_is_all_zeroes:\n cb.locator = mpl.ticker.FixedLocator(locs=[0.0])\n else:\n if log_color_scale:\n cb.formatter = mpl.ticker.LogFormatter(base=10)\n else:\n if (vmax0-vmin0) < 0.1 or (vmax0-vmin0) > 100:\n cb.locator = mpl.ticker.MaxNLocator(nbins=4)\n cb.update_ticks()\n cb.set_label(units_ref)\n\n ################################################################\n # Subplot (0,1): Dev, plotted on dev input grid\n ################################################################\n\n # Set colorbar min/max\n if use_cmap_RdBu:\n if vmin_dev == 0 and vmax_dev == 0:\n [vmin1, vmax1] = [vmin_dev, vmax_dev]\n else:\n if not match_cbar:\n absmax_dev = max([np.abs(vmin_dev), np.abs(vmax_dev)])\n [vmin1, vmax1] = [-absmax_dev, absmax_dev]\n else:\n absmax = max([np.abs(vmin_ref), np.abs(vmax_ref),\n np.abs(vmin_dev), np.abs(vmax_dev)])\n [vmin1, vmax1] = [-absmax, absmax]\n else:\n if not match_cbar:\n [vmin1, vmax1] = [vmin_dev, vmax_dev]\n else:\n [vmin1, vmax1] = [vmin_abs, vmax_abs]\n\n if verbose: print('Subplot (0,1) vmin1, vmax1: {}, {}'.format(vmin1,vmax1))\n\n # Plot for either lat-lon or cubed-sphere\n ax1.coastlines()\n if devgridtype == 'll':\n # Set top title for lat-lon plot\n ax1.set_title('{} (Dev){}\\n{}'.format(\n devstr,subtitle_extra,devres))\n\n # Check if Dev is all zeroes\n dev_is_all_zeroes = np.all(ds_dev == 0)\n\n # Normalize colors (put in range [0..1]) for the plot\n norm1 = normalize_colors(vmin1, vmax1,\n is_all_zeroes=dev_is_all_zeroes,\n log_color_scale=log_color_scale)\n\n # Plot the data!\n plot1 = ax1.imshow(ds_dev, extent=(devminlon, devmaxlon,\n devminlat, devmaxlat),\n cmap=cmap1, norm=norm1)\n else:\n # Set top title for cubed-sphere plot\n ax1.set_title('{} (Dev){}\\nc{}'.format(\n devstr,subtitle_extra,devres))\n\n # Mask the data\n masked_devdata = np.ma.masked_where(\n np.abs(devgrid['lon'] - 180) < 2, ds_dev_reshaped)\n\n # Check if Dev is all zereos\n dev_is_all_zeroes = np.all(masked_devdata == 0)\n\n # Normalize colors (put in range [0..1]) for the plot\n norm1 = normalize_colors(vmin1, vmax1,\n is_all_zeroes=dev_is_all_zeroes,\n log_color_scale=log_color_scale)\n\n # Plot each face of the cubed-sphere\n for i in range(6):\n plot1 = ax1.pcolormesh(devgrid['lon_b'][i,:,:],\n devgrid['lat_b'][i,:,:],\n masked_devdata[i,:,:],\n cmap=cmap1, norm=norm1)\n\n # Define the colorbar for log or linear color scales\n # If all values of Dev = 0, then manually set a tickmark at 0.\n cb = plt.colorbar(plot1, ax=ax1, orientation='horizontal', pad=0.10)\n if dev_is_all_zeroes:\n cb.locator = mpl.ticker.FixedLocator(locs=[0.0])\n else:\n if log_color_scale:\n cb.formatter = mpl.ticker.LogFormatter(base=10)\n else:\n if (vmax1-vmin1) < 0.1 or (vmax1-vmin1) > 100:\n cb.locator = mpl.ticker.MaxNLocator(nbins=4)\n cb.update_ticks()\n cb.set_label(units_dev)\n\n ################################################################\n # Calculate difference\n ################################################################\n\n if cmpgridtype == 'll':\n absdiff = np.array(ds_dev_cmp) - np.array(ds_ref_cmp)\n else:\n absdiff_raw = ds_dev_cmp_reshaped - ds_ref_cmp_reshaped\n absdiff = np.ma.masked_where(np.abs(cmpgrid['lon'] - 180) < 2, absdiff_raw)\n diffabsmax = max([np.abs(np.nanmin(absdiff)), np.abs(np.nanmax(absdiff))])\n\n ################################################################\n # Use gray for NaNs if plotting on lat-lon grid \n # (has strange effect for cubed-sphere)\n ################################################################\n\n cmap_nongray = copy.copy(mpl.cm.RdBu_r)\n cmap_gray = copy.copy(mpl.cm.RdBu_r)\n cmap_gray.set_bad(color='gray')\n \n ################################################################\n # Subplot (1,0): Difference, dynamic range\n ################################################################\n\n [vmin, vmax] = [-diffabsmax, diffabsmax]\n if verbose: print('Subplot (1,0) vmin, vmax: {}, {}'.format(vmin, vmax))\n\n ax2.coastlines()\n if cmpgridtype == 'll':\n plot2 = ax2.imshow(absdiff, extent=(cmpminlon, cmpmaxlon,\n cmpminlat, cmpmaxlat),\n cmap=cmap_gray, vmin=vmin, vmax=vmax)\n else:\n for i in range(6):\n plot2 = ax2.pcolormesh(cmpgrid['lon_b'][i,:,:],\n cmpgrid['lat_b'][i,:,:],\n absdiff[i,:,:],\n cmap=cmap_nongray,\n vmin=vmin, vmax=vmax)\n if regridany:\n ax2.set_title('Difference ({})\\nDev - Ref, Dynamic Range'.format(\n cmpres))\n else:\n ax2.set_title('Difference\\nDev - Ref, Dynamic Range')\n\n # Define the colorbar for the plot\n # If all values of absdiff = 0, manually set a tickmark at 0.\n cb = plt.colorbar(plot2, ax=ax2, orientation='horizontal', pad=0.10)\n if np.all(absdiff==0): \n cb.locator = mpl.ticker.FixedLocator(locs=[0.0])\n else:\n if (vmax-vmin) < 0.1 or (vmax-vmin) > 100:\n cb.locator = mpl.ticker.MaxNLocator(nbins=4)\n cb.update_ticks()\n cb.set_label(units)\n\n ################################################################\n # Subplot (1,1): Difference, restricted range\n ################################################################\n\n # placeholder: use 5 and 95 percentiles as bounds\n [pct5, pct95] = [np.percentile(absdiff,5), np.percentile(absdiff, 95)] \n\n abspctmax = np.max([np.abs(pct5),np.abs(pct95)])\n [vmin,vmax] = [-abspctmax, abspctmax]\n if verbose: print('Subplot (1,1) vmin, vmax: {}, {}'.format(vmin, vmax))\n\n ax3.coastlines()\n if cmpgridtype == 'll':\n plot3 = ax3.imshow(absdiff, extent=(cmpminlon, cmpmaxlon,\n cmpminlat, cmpmaxlat),\n cmap=cmap_gray, vmin=vmin, vmax=vmax)\n else:\n for i in range(6):\n plot3 = ax3.pcolormesh(cmpgrid['lon_b'][i,:,:],\n cmpgrid['lat_b'][i,:,:],\n absdiff[i,:,:],\n cmap=cmap_nongray,\n vmin=vmin, vmax=vmax)\n if regridany:\n ax3.set_title('Difference ({})\\nDev - Ref, Restricted Range [5%,95%]'.format(cmpres))\n else:\n ax3.set_title('Difference\\nDev - Ref, Restricted Range [5%,95%]')\n\n # Define the colorbar for the plot.\n # If all values of absdiff = 0, then manually set a tick at 0.\n cb = plt.colorbar(plot3, ax=ax3, orientation='horizontal', pad=0.10)\n if np.all(absdiff==0):\n cb.locator = mpl.ticker.FixedLocator(locs=[0.0])\n else:\n if (vmax-vmin) < 0.1 or (vmax-vmin) > 100:\n cb.locator = mpl.ticker.MaxNLocator(nbins=4)\n cb.update_ticks()\n cb.set_label(units)\n\n ################################################################\n # Calculate fractional difference, set divides by zero to Nan\n ################################################################\n \n if cmpgridtype == 'll':\n fracdiff = (np.array(ds_dev_cmp) - np.array(ds_ref_cmp)) / np.array(ds_ref_cmp)\n else:\n fracdiff_raw = (ds_dev_cmp_reshaped - ds_ref_cmp_reshaped) / ds_ref_cmp_reshaped\n fracdiff = np.ma.masked_where(np.abs(cmpgrid['lon'] - 180) < 2, fracdiff_raw)\n\n fracdiff = np.where(fracdiff==np.inf, np.nan, fracdiff)\n fracdiffabsmax = max([np.abs(np.nanmin(fracdiff)), np.abs(np.nanmax(fracdiff))])\n\n ################################################################\n # Subplot (2,0): Fractional Difference, full dynamic range\n ################################################################\n \n [vmin, vmax] = [-fracdiffabsmax, fracdiffabsmax]\n if verbose: print('Subplot (2,0) vmin, vmax: {}, {}'.format(vmin, vmax))\n \n ax4.coastlines()\n if cmpgridtype == 'll':\n plot4 = ax4.imshow(fracdiff, extent=(cmpminlon, cmpmaxlon,\n cmpminlat, cmpmaxlat),\n vmin=vmin, vmax=vmax, cmap=cmap_gray)\n else:\n for i in range(6):\n plot4 = ax4.pcolormesh(cmpgrid['lon_b'][i,:,:],\n cmpgrid['lat_b'][i,:,:],\n fracdiff[i,:,:],\n cmap=cmap_nongray,\n vmin=vmin, vmax=vmax)\n if regridany:\n ax4.set_title('Fractional Difference ({})\\n(Dev-Ref)/Ref, Dynamic Range'.format(cmpres)) \n else:\n ax4.set_title('Fractional Difference\\n(Dev-Ref)/Ref, Dynamic Range')\n\n # Define the colorbar for the plot.\n # If all values of absdiff = 0, then manually set a tick at 0.\n # Use absdiff in the test for all zeroes, because fracdiff may\n # have NaN's due to div by zero when both Dev and Ref are zero.\n cb = plt.colorbar(plot4, ax=ax4, orientation='horizontal', pad=0.10)\n if np.all(absdiff == 0):\n cb.locator = mpl.ticker.FixedLocator(locs=[0.0])\n else:\n if (vmax-vmin) < 0.1 or (vmax-vmin) > 100:\n cb.locator = mpl.ticker.MaxNLocator(nbins=4)\n cb.update_ticks()\n cb.set_label('unitless')\n\n ################################################################\n # Subplot (2,1): Fractional Difference, restricted range\n ################################################################\n \n [vmin, vmax] = [-2, 2]\n if verbose: print('Subplot (2,1) vmin, vmax: {}, {}'.format(vmin, vmax))\n\n ax5.coastlines()\n if cmpgridtype == 'll':\n plot5 = ax5.imshow(fracdiff, extent=(cmpminlon, cmpmaxlon,\n cmpminlat, cmpmaxlat),\n cmap=cmap_gray, vmin=vmin, vmax=vmax)\n else:\n for i in range(6):\n plot5 = ax5.pcolormesh(cmpgrid['lon_b'][i,:,:],\n cmpgrid['lat_b'][i,:,:],\n fracdiff[i,:,:],\n cmap=cmap_nongray,\n vmin=vmin, vmax=vmax)\n if regridany:\n ax5.set_title('Fractional Difference ({})\\n(Dev-Ref)/Ref, Fixed Range'.format(cmpres))\n else:\n ax5.set_title('Fractional Difference\\n(Dev-Ref)/Ref, Fixed Range') \n\n # Define the colorbar for the plot.\n # If all values of absdiff = 0, then manually set a tick at 0.\n # Use absdiff in the test for all zeroes, because fracdiff may\n # have NaN's due to div by zero when both Dev and Ref are zero.\n cb = plt.colorbar(plot5, ax=ax5, orientation='horizontal', pad=0.10)\n if np.all(absdiff == 0):\n cb.locator = mpl.ticker.FixedLocator(locs=[0.0])\n cb.update_ticks()\n cb.set_label('unitless')\n\n ################################################################\n # Update the list of variables with significant differences.\n # Criterion: abs(max(fracdiff)) > 0.1\n # Do not include NaNs in the criterion, because these indicate\n # places where fracdiff could not be computed (div-by-zero).\n ################################################################\n if np.abs(np.nanmax(fracdiff)) > 0.1:\n sigdiff_list.append(varname)\n\n ################################################################\n # Add this page of 6-panel plots to the PDF file\n ################################################################\n if savepdf: \n pdf.savefig(figs)\n plt.close(figs)\n\n ####################################################################\n # Finish\n ####################################################################\n if savepdf:\n pdf.close()\n\ndef compare_zonal_mean(refdata, refstr, devdata, devstr, varlist=None,\n itime=0, weightsdir=None, pdfname='', cmpres=None,\n match_cbar=True, pres_range=[0,2000],\n normalize_by_area=False, enforce_units=True,\n flip_ref=False, flip_dev=False, use_cmap_RdBu=False,\n verbose=False, log_color_scale=False,\n sigdiff_list=[]):\n\n '''\n Create single-level 3x2 comparison map plots for variables common in two xarray\n datasets. Optionally save to PDF. \n\n Args:\n refdata : xarray dataset\n Dataset used as reference in comparison\n\n refstr : str\n String description for reference data to be used in plots\n \n devdata : xarray dataset\n Dataset used as development in comparison\n\n devstr : str\n String description for development data to be used in plots\n \n Keyword Args (optional):\n varlist : list of strings\n List of xarray dataset variable names to make plots for\n Default value: None (will compare all common 3D variables)\n\n itime : integer\n Dataset time dimension index using 0-based system\n Default value: 0\n\n weightsdir : str\n Directory path for storing regridding weights\n Default value: None (will create/store weights in current directory)\n\n pdfname : str\n File path to save plots as PDF\n Default value: Empty string (will not create PDF)\n\n cmpres : str\n String description of grid resolution at which to compare datasets\n Default value: None (will compare at highest resolution of ref and dev)\n\n match_cbar : boolean\n Logical indicating whether to use same colorbar bounds across plots\n Default value: True\n\n pres_range : list of two integers\n Pressure range of levels to plot [hPa]. Vertical axis will span outer\n pressure edges of levels that contain pres_range endpoints.\n Default value: [0,2000]\n\n normalize_by_area : boolean\n Logical indicating whether to normalize raw data by grid area\n Default value: False\n\n enforce_units : boolean\n Logical to force an error if reference and development variables units differ\n Default value: True\n\n flip_ref : boolean\n Logical to flip the vertical dimension of reference dataset 3D variables\n Default value: False\n\n flip_dev : boolean\n Logical to flip the vertical dimension of development dataset 3D variables\n Default value: False\n\n use_cmap_RdBu : boolean\n Logical to used a blue-white-red colormap for plotting raw reference and\n development datasets.\n Default value: False\n\n verbose : logical\n Logical to enable informative prints\n Default value: False\n\n log_color_scale: boolean \n Logical to enable plotting data (not diffs) on a log color scale.\n Default value: False\n\n sigdiff_list: list of str\n Returns a list of all quantities having significant differences.\n The criteria is: |max(fractional difference)| > 0.1\n Default value: []\n\n Returns:\n Nothing\n\n Example:\n >>> import matplotlib.pyplot as plt\n >>> import xarray as xr\n >>> from gcpy import benchmark\n >>> refds = xr.open_dataset('path/to/ref.nc4')\n >>> devds = xr.open_dataset('path/to/dev.nc4')\n >>> varlist = ['SpeciesConc_O3', 'SpeciesConc_NO']\n >>> benchmark.compare_zonal_mean( refds, '12.3.2', devds, 'bug fix', varlist=varlist )\n >>> plt.show()\n '''\n\n # TODO: refactor this function and single level plot function. There is a lot of overlap and\n # repeated code that could be abstracted.\n\n if not isinstance(refdata, xr.Dataset):\n raise ValueError('The refdata argument must be an xarray Dataset!')\n\n if not isinstance(devdata, xr.Dataset):\n raise ValueError('The devdata argument must be an xarray Dataset!')\n\n # If no varlist is passed, plot all 3D variables in the dataset\n if varlist == None:\n [commonvars, commonvarsOther, commonvars2D, commonvars3D] = core.compare_varnames(refdata, devdata)\n varlist = commonvars3D\n print('Plotting all 3D variables')\n n_var = len(varlist)\n\n # If no weightsdir is passed, set to current directory in case it is needed\n if weightsdir == None:\n weightsdir = '.'\n\n # If no pdf name passed, then do not save to PDF\n savepdf = True\n if pdfname == '':\n savepdf = False\n\n # Get mid-point pressure and edge pressures for this grid (assume 72-level)\n pmid = GEOS_72L_grid.p_mid()\n pedge = GEOS_72L_grid.p_edge()\n\n # Get indexes of pressure subrange (full range is default)\n pedge_ind = np.where((pedge <= np.max(pres_range)) & (pedge >= np.min(pres_range)))\n pedge_ind = pedge_ind[0]\n # Pad edges if subset does not include surface or TOA so data spans entire subrange\n if min(pedge_ind) != 0:\n pedge_ind = np.append(min(pedge_ind)-1, pedge_ind)\n if max(pedge_ind) != 72:\n pedge_ind = np.append(pedge_ind, max(pedge_ind)+1)\n # pmid indexes do not include last pedge index\n pmid_ind = pedge_ind[:-1]\n nlev = len(pmid_ind)\n \n # Convert levels to pressures in ref and dev data\n if refdata.sizes['lev'] == 72:\n refdata['lev'] = pmid\n elif refdata.sizes['lev'] == 73:\n refdata['lev'] = pedge\n else:\n print('ERROR: compare_zonal_mean implemented for 72 or 73 levels only. Other values found in ref.')\n return\n refdata['lev'].attrs['units'] = 'hPa'\n refdata['lev'].attrs['long_name'] = 'level pressure'\n\n if devdata.sizes['lev'] == 72:\n devdata['lev'] = pmid\n elif devdata.sizes['lev'] == 73:\n devdata['lev'] = pedge\n else:\n print('ERROR: compare_zonal_mean implemented for 72 or 73 levels only. Other value found in dev.')\n return\n devdata['lev'].attrs['units'] = 'hPa'\n devdata['lev'].attrs['long_name'] = 'level pressure'\n\n ####################################################################\n # Reduce pressure range if reduced range passed as input\n ####################################################################\n\n refdata = refdata.isel(lev=pmid_ind)\n devdata = devdata.isel(lev=pmid_ind)\n \n ####################################################################\n # Determine input grid resolutions and types\n ####################################################################\n # GCC output and GCHP output using pre-v1.0.0 MAPL have lat and lon dims\n\n # ref\n vdims = refdata.dims\n if 'lat' in vdims and 'lon' in vdims:\n refnlat = refdata.sizes['lat']\n refnlon = refdata.sizes['lon']\n if refnlat == 46 and refnlon == 72:\n refres = '4x5'\n refgridtype = 'll'\n elif refnlat == 91 and refnlon == 144:\n refres = '2x2.5'\n refgridtype = 'll'\n elif refnlat/6 == refnlon:\n refres = refnlon\n refgridtype = 'cs'\n else:\n print('ERROR: ref {}x{} grid not defined in gcpy!'.format(refnlat,refnlon))\n return\n else:\n # GCHP data using MAPL v1.0.0+ has dims time, lev, nf, Ydim, and Xdim\n refres = refdata.dims['Xdim']\n refgridtype = 'cs'\n\n # dev\n vdims = devdata.dims\n if 'lat' in vdims and 'lon' in vdims:\n devnlat = devdata.sizes['lat']\n devnlon = devdata.sizes['lon']\n if devnlat == 46 and devnlon == 72:\n devres = '4x5'\n devgridtype = 'll'\n elif devnlat == 91 and devnlon == 144:\n devres = '2x2.5'\n devgridtype = 'll'\n elif devnlat/6 == devnlon:\n devres = devnlon\n devgridtype = 'cs'\n else:\n print('ERROR: dev {}x{} grid not defined in gcpy!'.format(refnlat,refnlon))\n return\n else:\n devres = devdata.dims['Xdim']\n devgridtype = 'cs'\n \n ####################################################################\n # Determine comparison grid resolution (if not passed)\n ####################################################################\n\n # If no cmpres is passed then choose highest resolution between ref and dev.\n # If both datasets are cubed sphere then default to 1x1.25 for comparison.\n cmpgridtype = 'll'\n if cmpres == None:\n if refres == devres and refgridtype == 'll':\n cmpres = refres\n elif refgridtype == 'll' and devgridtype == 'll':\n cmpres = min([refres, devres])\n else:\n cmpres = '1x1.25'\n \n # Determine what, if any, need regridding.\n regridref = refres != cmpres\n regriddev = devres != cmpres\n regridany = regridref or regriddev\n\n ####################################################################\n # Make grids (ref, dev, and comparison)\n ####################################################################\n\n # Ref\n if refgridtype == 'll':\n refgrid = make_grid_LL(refres)\n else:\n [refgrid, regrid_list] = make_grid_CS(refres)\n\n # Dev\n if devgridtype == 'll':\n devgrid = make_grid_LL(devres)\n else:\n [devgrid, devgrid_list] = make_grid_CS(devres)\n\n # Comparison \n cmpgrid = make_grid_LL(cmpres)\n\n ####################################################################\n # Make regridders, if applicable\n ####################################################################\n\n if regridref:\n if refgridtype == 'll':\n refregridder = make_regridder_L2L(refres, cmpres, weightsdir=weightsdir, reuse_weights=True)\n else:\n refregridder_list = make_regridder_C2L(refres, cmpres, weightsdir=weightsdir, reuse_weights=True)\n if regriddev:\n if devgridtype == 'll':\n devregridder = make_regridder_L2L(devres, cmpres, weightsdir=weightsdir, reuse_weights=True)\n else:\n devregridder_list = make_regridder_C2L(devres, cmpres, weightsdir=weightsdir, reuse_weights=True)\n \n ####################################################################\n # Create pdf, if savepdf is passed as True\n ####################################################################\n\n # Universal plot setup\n xtick_positions = np.arange(-90,91,30)\n xticklabels = ['{}$\\degree$'.format(x) for x in xtick_positions] \n\n if savepdf:\n print('\\nCreating {} for {} variables'.format(pdfname,n_var))\n pdf = PdfPages(pdfname)\n\n ####################################################################\n # Loop over variables\n ####################################################################\n\n # Loop over variables\n print_units_warning = True\n for ivar in range(n_var):\n if savepdf: print('{} '.format(ivar), end='')\n varname = varlist[ivar]\n varndim_ref = refdata[varname].ndim\n varndim_dev = devdata[varname].ndim\n\n # If units are mol/mol then convert to ppb\n conc_units = ['mol mol-1 dry','mol/mol','mol mol-1']\n if refdata[varname].units.strip() in conc_units:\n refdata[varname].attrs['units'] = 'ppbv'\n refdata[varname].values = refdata[varname].values * 1e9\n if devdata[varname].units.strip() in conc_units:\n devdata[varname].attrs['units'] = 'ppbv'\n devdata[varname].values = devdata[varname].values * 1e9\n\n # Binary diagnostic concentrations have units ppbv. Change to ppb.\n if refdata[varname].units.strip() == 'ppbv':\n refdata[varname].attrs['units'] = 'ppb'\n if devdata[varname].units.strip() == 'ppbv':\n devdata[varname].attrs['units'] = 'ppb'\n\n # Check that units match\n units_ref = refdata[varname].units.strip()\n units_dev = devdata[varname].units.strip()\n if units_ref != units_dev:\n if print_units_warning:\n print('WARNING: ref and dev concentration units do not match!')\n print('Ref units: {}'.format(units_ref))\n print('Dev units: {}'.format(units_dev))\n if enforce_units:\n # if enforcing units, stop the program if units do not match\n assert units_ref == units_dev, 'Units do not match for {}!'.format(varname)\n else:\n # if not enforcing units, just keep going after only printing warning once \n print_units_warning = False\n\n ###############################################################\n # Slice the data, allowing for the\n # possibility of no time dimension (bpch)\n ###############################################################\n\n # Ref\n vdims = refdata[varname].dims\n if 'time' in vdims:\n ds_ref = refdata[varname].isel(time=itime)\n else:\n ds_ref = refdata[varname]\n\n # Dev\n vdims = devdata[varname].dims \n if 'time' in vdims:\n ds_dev = devdata[varname].isel(time=itime)\n else:\n ds_dev = devdata[varname]\n\n ################################################################\n # Reshape cubed sphere data if using MAPL v1.0.0+\n # TODO: update function to expect data in this format\n ################################################################\n\n # ref\n vdims = refdata[varname].dims\n if 'nf' in vdims and 'Xdim' in vdims and 'Ydim' in vdims:\n ds_ref = ds_ref.stack(lat=('nf', 'Ydim'))\n ds_ref = ds_ref.rename({'Xdim':'lon'})\n ds_ref = ds_ref.transpose('lev', 'lat', 'lon')\n\n # dev\n vdims = devdata[varname].dims\n if 'nf' in vdims and 'Xdim' in vdims and 'Ydim' in vdims:\n ds_dev = ds_dev.stack(lat=('nf', 'Ydim'))\n ds_dev = ds_dev.rename({'Xdim':'lon'})\n ds_dev = ds_dev.transpose('lev', 'lat', 'lon')\n\n ###############################################################\n # Area normalization, if any\n ###############################################################\n \n # if normalizing by area, adjust units to be per m2, and adjust title string\n units = units_ref\n varndim = varndim_ref\n subtitle_extra = ''\n \n # if normalizing by area, transform on the native grid and adjust units and subtitle string\n exclude_list = ['WetLossConvFrac','Prod_','Loss_']\n if normalize_by_area and not any(s in varname for s in exclude_list):\n ds_ref.values = ds_ref.values / refdata['AREAM2'].values[np.newaxis,:,:]\n ds_dev.values = ds_dev.values / devdata['AREAM2'].values[np.newaxis,:,:]\n units = '{} m-2'.format(units)\n subtitle_extra = ', Normalized by Area'\n\n ###############################################################\n # Get comparison data sets, regridding input slices if needed\n ###############################################################\n\n # Flip in the veritical if applicable\n if flip_ref:\n ds_ref.data = ds_ref.data[::-1,:,:]\n if flip_dev:\n ds_ref.data = ds_ref.data[::-1,:,:]\n \n # Reshape ref/dev cubed sphere data, if any\n if refgridtype == 'cs':\n ds_ref_reshaped = ds_ref.data.reshape(nlev,6,refres,refres).swapaxes(0,1)\n if devgridtype == 'cs':\n ds_dev_reshaped = ds_dev.data.reshape(nlev,6,devres,devres).swapaxes(0,1)\n\n # Ref\n if regridref:\n if refgridtype == 'll':\n # regrid ll to ll\n ds_ref_cmp = refregridder(ds_ref)\n else:\n # regrid cs to ll\n ds_ref_cmp = np.zeros([nlev, cmpgrid['lat'].size, cmpgrid['lon'].size])\n for i in range(6):\n regridder = refregridder_list[i]\n ds_ref_cmp += regridder(ds_ref_reshaped[i])\n else:\n ds_ref_cmp = ds_ref\n\n # Dev\n if regriddev:\n if devgridtype == 'll':\n # regrid ll to ll\n ds_dev_cmp = devregridder(ds_dev)\n else:\n # regrid cs to ll\n ds_dev_cmp = np.zeros([nlev, cmpgrid['lat'].size, cmpgrid['lon'].size])\n for i in range(6):\n regridder = devregridder_list[i]\n ds_dev_cmp += regridder(ds_dev_reshaped[i])\n else:\n ds_dev_cmp = ds_dev\n\n ###############################################################\n # Calculate zonal mean\n ###############################################################\n \n # Ref\n if refgridtype == 'll':\n zm_ref = ds_ref.mean(dim='lon')\n else:\n zm_ref = ds_ref_cmp.mean(axis=2)\n\n # Dev\n if devgridtype == 'll':\n zm_dev = ds_dev.mean(dim='lon')\n else:\n zm_dev = ds_dev_cmp.mean(axis=2)\n\n # Comparison\n zm_dev_cmp = ds_dev_cmp.mean(axis=2)\n zm_ref_cmp = ds_ref_cmp.mean(axis=2)\n\n ###############################################################\n # Get min and max values for use in the colorbars\n ###############################################################\n\n # Ref\n vmin_ref = zm_ref.min()\n vmax_ref = zm_ref.max()\n\n # Dev\n vmin_dev = zm_dev.min()\n vmax_dev = zm_dev.max()\n\n # Comparison\n vmin_cmp = np.min([zm_ref_cmp.min(), zm_dev_cmp.min()])\n vmax_cmp = np.max([zm_ref_cmp.max(), zm_dev_cmp.max()])\n\n # Take min/max across all\n vmin_abs = np.min([vmin_ref, vmin_dev, vmin_cmp])\n vmax_abs = np.max([vmax_ref, vmax_dev, vmax_cmp])\n if match_cbar: [vmin, vmax] = [vmin_abs, vmax_abs]\n\n if verbose:\n print('vmin_ref: {}'.format(vmin_ref))\n print('vmin_dev: {}'.format(vmin_dev))\n print('vmin_cmp: {}'.format(vmin_cmp))\n print('vmin_abs: {}'.format(vmin_abs))\n print('vmax_ref: {}'.format(vmax_ref))\n print('vmax_dev: {}'.format(vmax_dev))\n print('vmax_cmp: {}'.format(vmax_cmp))\n print('vmax_abs: {}'.format(vmax_abs))\n\n ###############################################################\n # Create 3x2 figure\n ###############################################################\n \n figs, ((ax0, ax1), (ax2, ax3), (ax4, ax5)) = plt.subplots(3, 2, figsize=[12,15.3])\n offset = 0.96\n fontsize=25\n figs.suptitle('{}, Zonal Mean'.format(varname), fontsize=fontsize, y=offset)\n\n ###############################################################\n # Set colormap for raw data plots (first row)\n ###############################################################\n\n if use_cmap_RdBu:\n cmap1 = 'RdBu_r' # do not need to worry about cmap.set_bad since always lat-lon\n else:\n cmap1 = WhGrYlRd\n\n ###############################################################\n # Subplot (0,0): Ref\n ###############################################################\n\n # Set colorbar min/max\n if use_cmap_RdBu:\n if vmin_ref == 0 and vmax_ref:\n [vmin0, vmax0] = [vmin_ref, vmax_ref]\n else:\n if not match_cbar:\n absmax_ref = max([np.abs(vmin_ref), np.abs(vmax_ref)])\n [vmin0, vmax0] = [-absmax_ref, absmax_dev]\n else:\n absmax = max([np.abs(vmin_ref), np.abs(vmax_ref),\n np.abs(vmin_dev), np.abs(vmax_dev)])\n [vmin0, vmax0] = [-absmax, absmax]\n else:\n if not match_cbar:\n [vmin0, vmax0] = [vmin_ref, vmax_ref]\n else:\n [vmin0, vmax0] = [vmin_abs, vmax_abs]\n if verbose: print('Subplot (0,0) vmin0, vmax0: {}, {}'.format(vmin0, vmax0))\n\n # Check if all elements of Ref are zero\n ref_is_all_zeroes = np.all(zm_ref == 0)\n\n # Normalize colors (put in range [0..1]) for the plot\n norm0 = normalize_colors(vmin0, vmax0,\n is_all_zeroes=ref_is_all_zeroes,\n log_color_scale=log_color_scale)\n\n # Plot data for either lat-lon or cubed-sphere grids\n if refgridtype == 'll':\n plot0 = ax0.pcolormesh(refgrid['lat_b'],\n pedge[pedge_ind],\n zm_ref,\n cmap=cmap1, norm=norm0)\n ax0.set_title('{} (Ref){}\\n{}'.format(\n refstr, subtitle_extra, refres))\n else:\n plot0 = ax0.pcolormesh(cmpgrid['lat_b'],\n pedge[pedge_ind],\n zm_ref,\n cmap=cmap1, norm=norm0)\n ax0.set_title('{} (Ref){}\\n{} regridded from c{}'.format(\n refstr, subtitle_extra, cmpres, refres))\n ax0.invert_yaxis()\n ax0.set_ylabel('Pressure (hPa)')\n ax0.set_aspect('auto')\n ax0.set_xticks(xtick_positions)\n ax0.set_xticklabels(xticklabels)\n\n # Define the colorbar for log or linear color scales.\n # If all values of zm_ref = 0, then manually set a tick at zero.\n cb = plt.colorbar(plot0, ax=ax0, orientation='horizontal', pad=0.10)\n if ref_is_all_zeroes:\n cb.locator = mpl.ticker.FixedLocator(locs=[0.0])\n else:\n if log_color_scale:\n cb.formatter = mpl.ticker.LogFormatter(base=10)\n else:\n if (vmax-vmin) < 0.001 or (vmax-vmin) > 1000:\n cb.locator = mpl.ticker.MaxNLocator(nbins=4)\n cb.update_ticks()\n cb.set_label(units)\n\n ###############################################################\n # Subplot (0,1): Dev\n ###############################################################\n\n # Set colorbar min/max\n if use_cmap_RdBu:\n if vmin_dev == 0 and vmax_dev == 0:\n [vmin1, vmax1] = [vmin_dev, vmax_dev]\n else:\n if not match_cbar:\n absmax_dev = max([np.abs(vmin_dev), np.abs(vmax_dev)])\n [vmin1, vmax1] = [-absmax_dev, absmax_dev]\n else:\n absmax = max([np.abs(vmin_ref), np.abs(vmax_ref),\n np.abs(vmin_dev), np.abs(vmax_dev)])\n [vmin1, vmax1] = [-absmax, absmax]\n else:\n if not match_cbar:\n [vmin1, vmax1] = [vmin_dev, vmax_dev]\n else:\n [vmin1, vmax1] = [vmin_abs, vmax_abs]\n if verbose: print('Subplot (0,1) vmin1, vmax1: {}, {}'.format(vmin1, vmax1))\n\n # Check if all elements of Ref are zero\n dev_is_all_zeroes = np.all(zm_dev == 0)\n\n # Normalize colors (put in range [0..1]) for the plot\n norm1 = normalize_colors(vmin1, vmax1,\n is_all_zeroes=dev_is_all_zeroes,\n log_color_scale=log_color_scale)\n\n # Plot data for either lat-lon or cubed-sphere grids.\n if devgridtype == 'll':\n plot1 = ax1.pcolormesh(devgrid['lat_b'], pedge[pedge_ind], \n zm_dev, cmap=cmap1, norm=norm1)\n ax1.set_title('{} (Dev){}\\n{}'.format(\n devstr, subtitle_extra, devres ))\n else:\n plot1 = ax1.pcolormesh(cmpgrid['lat_b'], pedge[pedge_ind], \n zm_dev, cmap=cmap1, norm=norm1)\n ax1.set_title('{} (Dev){}\\n{} regridded from c{}'.format(\n devstr, subtitle_extra, cmpres, devres))\n ax1.invert_yaxis()\n ax1.set_ylabel('Pressure (hPa)')\n ax1.set_aspect('auto')\n ax1.set_xticks(xtick_positions)\n ax1.set_xticklabels(xticklabels)\n\n # Define the colorbar for log or linear color scales.\n # If all values of zm_dev = 0, then manually set a tick at 0\n cb = plt.colorbar(plot1, ax=ax1, orientation='horizontal', pad=0.10)\n if dev_is_all_zeroes:\n cb.locator = mpl.ticker.FixedLocator(locs=[0.0])\n else:\n if log_color_scale:\n cb.formatter = mpl.ticker.LogFormatter(base=10)\n else:\n if (vmax-vmin) < 0.001 or (vmax-vmin) > 1000:\n cb.locator = mpl.ticker.MaxNLocator(nbins=4)\n cb.update_ticks()\n cb.set_label(units)\n\n ################################################################\n # Configure colorbar for difference plots, use gray for NaNs\n ################################################################\n\n cmap_plot = copy.copy(mpl.cm.RdBu_r)\n cmap_plot.set_bad(color='gray')\n\n ################################################################\n # Calculate zonal mean difference\n ################################################################\n\n zm_diff = np.array(zm_dev_cmp) - np.array(zm_ref_cmp)\n\n ################################################################\n # Subplot (1,0): Difference, dynamic range\n ################################################################\n\n diffabsmax = max([np.abs(zm_diff.min()), np.abs(zm_diff.max())])\n [vmin, vmax] = [-diffabsmax, diffabsmax]\n if verbose: print('Subplot (1,0) vmin, vmax: {}, {}'.format(vmin, vmax))\n\n plot2 = ax2.pcolormesh(cmpgrid['lat_b'], pedge[pedge_ind],\n zm_diff, cmap=cmap_plot,\n vmin=vmin, vmax=vmax)\n ax2.invert_yaxis()\n if regridany:\n ax2.set_title('Difference ({})\\nDev - Ref, Dynamic Range'.format(\n cmpres))\n else:\n ax2.set_title('Difference\\nDev - Ref, Dynamic Range')\n ax2.set_ylabel('Pressure (hPa)')\n ax2.set_aspect('auto')\n ax2.set_xticks(xtick_positions)\n ax2.set_xticklabels(xticklabels)\n\n # Define the colorbar for the plot.\n # If all values of zm_diff = 0, then manually set a tick at 0\n cb = plt.colorbar(plot2, ax=ax2, orientation='horizontal', pad=0.10)\n if np.all(zm_diff==0): \n cb.locator = mpl.ticker.FixedLocator(locs=[0.0])\n else:\n if (vmax-vmin) < 0.001 or (vmax-vmin) > 1000:\n cb.locator = mpl.ticker.MaxNLocator(nbins=4)\n cb.update_ticks()\n cb.set_label(units)\n\n ################################################################\n # Subplot (1,1): Difference, restricted range\n ################################################################\n\n # placeholder: use 5 and 95 percentiles as bounds\n [pct5, pct95] = [np.percentile(zm_diff,5), np.percentile(zm_diff, 95)]\n abspctmax = np.max([np.abs(pct5),np.abs(pct95)])\n [vmin,vmax] = [-abspctmax, abspctmax]\n if verbose: print('Subplot (1,1) vmin, vmax: {}, {}'.format(vmin, vmax))\n \n plot3 = ax3.pcolormesh(cmpgrid['lat_b'], pedge[pedge_ind],\n zm_diff, cmap=cmap_plot, vmin=vmin, vmax=vmax)\n ax3.invert_yaxis()\n if regridany:\n ax3.set_title('Difference ({})\\nDev - Ref, Restricted Range [5%,95%]'.format(cmpres))\n else:\n ax3.set_title('Difference\\nDev - Ref, Restriced Range [5%,95%]')\n ax3.set_ylabel('Pressure (hPa)')\n ax3.set_aspect('auto')\n ax3.set_xticks(xtick_positions)\n ax3.set_xticklabels(xticklabels)\n\n # Define the colorbar for the plot.\n # If all values of zm_diff = 0, then manually set a tick at 0\n cb = plt.colorbar(plot3, ax=ax3, orientation='horizontal', pad=0.10)\n if np.all(zm_diff==0): \n cb.locator = mpl.ticker.FixedLocator(locs=[0.0])\n else:\n if (vmax-vmin) < 0.001 or (vmax-vmin) > 1000:\n cb.locator = mpl.ticker.MaxNLocator(nbins=4)\n cb.update_ticks()\n cb.set_label(units)\n\n ################################################################\n # Calculate fractional difference, set divides by zero to Nan\n ################################################################\n\n zm_fracdiff = (np.array(zm_dev_cmp) - np.array(zm_ref_cmp)) / np.array(zm_ref_cmp)\n zm_fracdiff = np.where(zm_fracdiff==np.inf, np.nan, zm_fracdiff)\n\n ################################################################\n # Subplot (2,0): Fractional Difference, dynamic range\n ################################################################\n \n # Exclude NaN's in the fracdiffabsmax\n fracdiffabsmax = np.max([np.abs(np.nanmin(zm_fracdiff)), np.abs(np.nanmax(zm_fracdiff))])\n if np.all(zm_fracdiff == 0 ):\n [vmin, vmax] = [-2, 2]\n else:\n [vmin, vmax] = [-fracdiffabsmax, fracdiffabsmax]\n if verbose: print('Subplot (2,0) vmin, vmax: {}, {}'.format(vmin, vmax))\n\n plot4 = ax4.pcolormesh(cmpgrid['lat_b'], pedge[pedge_ind],\n zm_fracdiff, cmap=cmap_plot, \n vmin=vmin, vmax=vmax)\n ax4.invert_yaxis()\n if regridany:\n ax4.set_title('Fractional Difference ({})\\n(Dev-Ref)/Ref, Dynamic Range'.format(cmpres))\n else:\n ax4.set_title('Fractional Difference\\n(Dev-Ref)/Ref, Dynamic Range')\n ax4.set_ylabel('Pressure (hPa)')\n ax4.set_aspect('auto')\n ax4.set_xticks(xtick_positions)\n ax4.set_xticklabels(xticklabels)\n\n # Define the colorbar for the plot.\n # If all values of absdiff = 0, then manually set a tick at 0.\n # Use zm_diff in the test for all zeroes, because fracdiff may\n # have NaN's due to div by zero when both Dev and Ref are zero.\n cb = plt.colorbar(plot4, ax=ax4, orientation='horizontal', pad=0.10)\n if np.all(zm_diff == 0):\n cb.locator = mpl.ticker.FixedLocator(locs=[0.0])\n else:\n if (vmax-vmin) < 0.1 or (vmax-vmin) > 100:\n cb.locator = mpl.ticker.MaxNLocator(nbins=4)\n cb.update_ticks()\n cb.set_clim(vmin=vmin, vmax=vmax)\n cb.set_label('unitless') \n\n ################################################################\n # Subplot (2,1): Fractional Difference, restricted range\n ################################################################\n\n [vmin, vmax] = [-2, 2]\n if verbose: print('Subplot (2,1) vmin, vmax: {}, {}'.format(vmin, vmax))\n \n plot5 = ax5.pcolormesh(cmpgrid['lat_b'], pedge[pedge_ind],\n zm_fracdiff, cmap=cmap_plot, \n vmin=vmin, vmax=vmax)\n ax5.invert_yaxis()\n if regridany:\n ax5.set_title('Fractional Difference ({})\\n(Dev-Ref)/Ref, Fixed Range'.format(cmpres))\n else:\n ax5.set_title('Fractional Difference\\n(Dev-Ref)/Ref, Fixed Range')\n ax5.set_ylabel('Pressure (hPa)')\n ax5.set_aspect('auto')\n ax5.set_xticks(xtick_positions)\n ax5.set_xticklabels(xticklabels)\n\n # Define the colorbar for the plot.\n # If all values of zm_diff = 0, then manually set a tick at 0.\n # Use zm_diff in the test for all zeroes, because fracdiff may\n # have NaN's due to div by zero when both Dev and Ref are zero.\n cb = plt.colorbar(plot5, ax=ax5, orientation='horizontal', pad=0.10)\n if np.all(zm_diff == 0): \n cb.locator = mpl.ticker.FixedLocator(locs=[0.0])\n else:\n if (vmax-vmin) < 0.1 or (vmax-vmin) > 100:\n cb.locator = mpl.ticker.MaxNLocator(nbins=4)\n cb.update_ticks()\n cb.set_clim(vmin=vmin, vmax=vmax)\n cb.set_label('unitless') \n\n ################################################################\n # Update the list of variables with significant differences.\n # Criterion: abs(max(fracdiff)) > 0.1\n # Do not include NaNs in the criterion, because these indicate\n # places where fracdiff could not be computed (div-by-zero).\n ################################################################\n if np.abs(np.nanmax(zm_fracdiff)) > 0.1:\n sigdiff_list.append(varname)\n\n ################################################################\n # Add this page of 6-panel plots to the PDF file\n ################################################################\n if savepdf: \n pdf.savefig(figs)\n plt.close(figs)\n\n ####################################################################\n # Finish\n ####################################################################\n if savepdf:\n pdf.close()\n\n\ndef get_emissions_varnames(commonvars, template=None):\n '''\n Will return a list of emissions diagnostic variable names that\n contain a particular search string.\n\n Args:\n commonvars : list of strs\n A list of commmon variable names from two data sets.\n (This can be obtained with method gcpy.core.compare_varnames)\n\n template : str\n String template for matching variable names corresponding\n to emission diagnostics by sector.\n\n Returns:\n varnames : list of strs\n A list of variable names corresponding to emission\n diagnostics for a given species and sector.\n\n Example:\n >>> import gcpy\n >>> commonvars = ['EmisCO_Anthro', 'EmisNO_Anthro', 'AREA']\n >>> varnames = gcpy.get_emissions_varnames(commonvars, \"Emis\")\n >>> print(varnames)\n ['EmisCO_Anthro', 'EmisNO_Anthro']\n '''\n\n # Make sure the commonvars list has at least one element\n if len(commonvars) == 0:\n raise ValueError('No valid variable names were passed!')\n\n # Define template for emission diagnostics by sector\n if template is None:\n raise ValueError('The template argument was not passed!')\n\n # Find all emission diagnostics for the given species\n varnames = core.filter_names(commonvars, template)\n\n # Return list\n return varnames\n\n\ndef create_emission_display_name(diagnostic_name):\n '''\n Converts an emissions diagnostic name to a more easily digestible name\n that can be used as a plot title or in a table of emissions totals.\n\n Args:\n diagnostic_name : str\n Name of the diagnostic to be formatted\n\n Returns:\n display_name : str\n Formatted name that can be used as plot titles or in tables\n of emissions totals.\n\n Remarks:\n Assumes that diagnostic names will start with either \"Emis\"\n (for emissions by category) or \"Inv\" (for emissions by inventory).\n This should be an OK assumption to make since this routine is\n specifically geared towards model benchmarking.\n\n Example:\n >>> import gcpy\n >>> diag_name = \"EmisCO_Anthro\"\n >>> display_name = gcpy.create_emission_display_name(diag_name)\n >>> print(display_name)\n CO Anthro\n '''\n\n # Initialize\n display_name = diagnostic_name\n\n # Special handling for Inventory totals\n if 'INV' in display_name.upper():\n display_name = display_name.replace('_', ' ')\n\n # Replace text\n for v in ['Emis', 'EMIS', 'emis', 'Inv', 'INV', 'inv']:\n display_name = display_name.replace(v, '')\n\n # Replace underscores\n display_name = display_name.replace('_', ' ')\n\n # Return\n return display_name\n\n\ndef print_emission_totals(ref, refstr, dev, devstr, f):\n '''\n Computes and prints emission totals for two xarray DataArray objects.\n\n Args:\n ref : xarray DataArray\n The first DataArray to be compared (aka \"Reference\")\n\n refstr : str\n A string that can be used to identify refdata.\n (e.g. a model version number or other identifier).\n\n dev : xarray DatArray\n The second DataArray to be compared (aka \"Development\")\n\n devstr : str\n A string that can be used to identify devdata\n (e.g. a model version number or other identifier).\n\n f : file\n File object denoting a text file where output will be directed.\n\n Remarks:\n This is an internal method. It is meant to be called from method\n create_total_emissions_table instead of being called directly.\n '''\n\n # Throw an error if the two DataArray objects have different units\n if ref.units != dev.units:\n msg = 'Ref has units \"{}\", but Dev array has units \"{}\"'.format(\n ref.units, dev.units)\n raise ValueError(msg)\n\n # Create the emissions display name from the diagnostic name\n diagnostic_name = dev.name\n display_name = create_emission_display_name(diagnostic_name)\n\n # Special handling for totals\n if '_TOTAL' in diagnostic_name.upper():\n print('-' * 79, file=f)\n\n # Compute sums and difference\n total_ref = np.sum(ref.values)\n total_dev = np.sum(dev.values)\n diff = total_dev - total_ref\n\n # Write output\n print('{} : {:13.6f} {:13.6f} {:13.6f} {}'.format(\n display_name.ljust(25), total_ref,\n total_dev, diff, dev.units), file=f)\n\n\ndef create_total_emissions_table(refdata, refstr, devdata, devstr,\n species, outfilename,\n interval=2678400.0, template='Emis{}_',\n ref_area_varname='AREA',\n dev_area_varname='AREA'):\n '''\n Creates a table of emissions totals (by sector and by inventory)\n for a list of species in contained in two data sets. The data sets,\n which typically represent output from two differnet model versions,\n are usually contained in netCDF data files.\n\n Args:\n refdata : xarray Dataset\n The first data set to be compared (aka \"Reference\").\n\n refstr : str\n A string that can be used to identify refdata\n (e.g. a model version number or other identifier).\n\n devdata : xarray Dataset\n The second data set to be compared (aka \"Development\").\n\n devstr: str\n A string that can be used to identify the data set specified\n by devfile (e.g. a model version number or other identifier).\n\n species : dict\n Dictionary containing the name of each species and the target\n unit that emissions will be converted to. The format of\n species is as follows:\n\n { species_name : target_unit\", etc. }\n\n where \"species_name\" and \"target_unit\" are strs.\n\n outfilename : str\n Name of the text file which will contain the table of\n emissions totals.\n\n Keyword Args (optional):\n interval : float\n The length of the data interval in seconds. By default, interval\n is set to the number of seconds in a 31-day month (86400 * 31),\n which corresponds to typical benchmark simulation output.\n\n template : str\n Template for the diagnostic names that are contained both\n \"Reference\" and \"Development\" data sets. If not specified,\n template will be set to \"Emis{}\", where {} will be replaced\n by the species name.\n\n ref_area_varname : str\n Name of the variable containing the grid box surface areas\n (in m2) in the ref dataset.\n Default value: 'AREA'\n\n dev_area_varname : str\n Name of the variable containing the grid box surface areas\n (in m2) in the dev dataset.\n Default value: 'AREA'\n\n Returns:\n None. Writes to a text file specified by the \"outfilename\" argument.\n\n Remarks:\n This method is mainly intended for model benchmarking purposes,\n rather than as a general-purpose tool.\n\n Species properties (such as molecular weights) are read from a\n JSON file called \"species_database.json\".\n\n Example:\n Print the total of CO and ACET emissions in two different\n data sets, which represent different model versions:\n\n >>> include gcpy\n >>> include xarray as xr\n >>> reffile = '~/output/12.1.1/HEMCO_diagnostics.201607010000.nc'\n >>> refstr = '12.1.1'\n >>> refdata = xr.open_dataset(reffile)\n >>> devfile = '~/output/12.2.0/HEMCO_sa.diagnostics.201607010000.nc'\n >>> devstr = '12.2.0'\n >>> devdata = xr.open_dataset(devfile)\n >>> outfilename = '12.2.0_emission_totals.txt'\n >>> species = { 'CO' : 'Tg', 'ACET', 'Tg C', 'ALK4', 'Gg C' }\n >>> create_total_emissions_table(refdata, refstr, devdata, devstr,\n species, outfilename)\n '''\n\n # Error check arguments\n if not isinstance(refdata, xr.Dataset):\n raise ValueError('The refdata argument must be an xarray Dataset!')\n\n if not isinstance(devdata, xr.Dataset):\n raise ValueError('The devdata argument must be an xarray Dataset!')\n\n if ref_area_varname not in refdata.data_vars.keys():\n raise ValueError('Area variable {} is not in the ref Dataset!'.format(\n ref_area_varname))\n\n if dev_area_varname not in devdata.data_vars.keys():\n raise ValueError('Area variable {} is not in the dev Dataset!'.format(\n dev_area_varname))\n\n # Load a JSON file containing species properties (such as\n # molecular weights), which we will need for unit conversions.\n # This is located in the \"data\" subfolder of this current directory.2\n properties_path = os.path.join(os.path.dirname(__file__),\n 'species_database.json')\n properties = json_load_file(open(properties_path))\n\n # Find all common variables between the two datasets\n [cvars, cvarsOther, cvars2D, cvars3D] = core.compare_varnames(refdata,\n devdata,\n quiet=True)\n\n # Open file for output\n f = open(outfilename, 'w')\n\n # Loop through all of the species are in species_dict\n for species_name, target_units in species.items():\n\n # Get a list of emission variable names for each species\n diagnostic_template = template.format(species_name)\n varnames = get_emissions_varnames(cvars, diagnostic_template)\n\n # If no emissions are found, then skip to next species\n if len(varnames) == 0:\n print('No emissions found for {} ... skippping'.format(\n species_name))\n continue\n\n # Check if there is a total emissions variable in the list\n vartot = [v for v in varnames if '_TOTAL' in v.upper()]\n\n # Push the total variable to the last list element\n # so that it will be printed last of all\n if len(vartot) == 1:\n varnames.append(varnames.pop(varnames.index(vartot[0]))) \n\n # Title strings\n if 'Inv' in template:\n print('Computing inventory totals for {}'.format(species_name))\n title1 = '### Inventory totals for species {}'.format(species_name)\n else:\n print('Computing emissions totals for {}'.format(species_name))\n title1 = '### Emissions totals for species {}'.format(species_name)\n\n title2 = '### Ref = {}; Dev = {}'.format(refstr, devstr)\n\n # Print header to file\n print('#'*79, file=f)\n print('{}{}'.format(title1.ljust(76), '###'), file=f)\n print('{}{}'.format(title2.ljust(76), '###'), file=f)\n print('#'*79, file=f)\n print('{}{}{}{}'.format(' '.ljust(33), 'Ref'.ljust(15),\n 'Dev'.ljust(15), 'Dev - Ref'), file=f)\n\n # Loop over all emissions variable names\n for v in varnames:\n\n if 'Inv' in template:\n spc_name = v.split('_')[1]\n else:\n spc_name = species_name\n\n # Get a list of properties for the given species\n species_properties = properties.get(spc_name)\n\n # Convert units of Ref, and save to DataArray\n refarray = convert_units(refdata[v], spc_name,\n species_properties, target_units,\n interval, refdata[ref_area_varname])\n\n # Convert units of Dev, and save to DataArray\n devarray = convert_units(devdata[v], spc_name,\n species_properties, target_units,\n interval, devdata[dev_area_varname])\n\n # Print emission totals for Ref and Dev\n print_emission_totals(refarray, refstr, devarray, devstr, f)\n\n # Add newlines before going to the next species\n print(file=f)\n print(file=f)\n\n # Close file\n f.close()\n\n\ndef get_species_categories():\n '''\n Returns the list of benchmark categories that each species\n belongs to. This determines which PDF files will contain the\n plots for the various species.\n\n Returns:\n spc_cat_dict : dict\n A nested dictionary of categories (and sub-categories)\n and the species belonging to each.\n\n NOTE: The benchmark categories are specified in JSON file\n benchmark_species.json.\n '''\n jsonfile = os.path.join(os.path.dirname(__file__), spc_categories)\n with open(jsonfile, 'r') as f:\n spc_cat_dict = json.loads(f.read())\n return spc_cat_dict\n\n\ndef archive_species_categories(dst):\n '''\n Writes the list of benchmark categories to a JSON file\n named \"benchmark_species.json\".\n\n Args:\n dst : str\n Name of the folder where the JSON file containing\n benchmark categories (\"benchmark_species.json\")\n will be written.\n '''\n\n src = os.path.join(os.path.dirname(__file__), spc_categories)\n print('Archiving {} in {}'.format(spc_categories, dst))\n shutil.copyfile(src, os.path.join(dst, spc_categories))\n\n\ndef make_benchmark_conc_plots(ref, refstr, dev, devstr, dst='./1mo_benchmark',\n overwrite=False, verbose=False, restrict_cats=[],\n plots=['sfc', '500hpa', 'zonalmean'], \n use_cmap_RdBu=False, log_color_scale=False,\n sigdiff_files=None):\n '''\n Creates PDF files containing plots of species concentration\n for model benchmarking purposes.\n\n Args:\n ref: str\n Path name for the \"Ref\" (aka \"Reference\") data set.\n\n refstr : str\n A string to describe ref (e.g. version number)\n\n dev : str\n Path name for the \"Dev\" (aka \"Development\") data set.\n This data set will be compared against the \"Reference\"\n data set.\n\n devstr : str\n A string to describe dev (e.g. version number)\n\n Keyword Args (optional):\n dst : str\n A string denoting the destination folder where a PDF\n file containing plots will be written.\n Default value: ./1mo_benchmark\n\n overwrite : boolean\n Set this flag to True to overwrite files in the\n destination folder (specified by the dst argument).\n Default value: False.\n\n verbose : boolean\n Set this flag to True to print extra informational output.\n Default value: False.\n\n restrict_cats : list of strings\n List of benchmark categories in benchmark_categories.json to make\n plots for. If empty, plots are made for all categories.\n Default value: empty\n\n plots : list of strings\n List of plot types to create.\n Default value: ['sfc', '500hpa', 'zonalmean']\n\n log_color_scale: boolean \n Logical to enable plotting data (not diffs) on a log color scale.\n Default value: False\n\n sigdiff_files : list of str\n Filenames that will contain the lists of species having\n significant differences in the 'sfc', '500hpa', and\n 'zonalmean' plots. These lists are needed in order to\n fill out the benchmark approval forms.\n Default value: None\n '''\n\n # NOTE: this function could use some refactoring; \n # abstract processing per category?\n\n # ==================================================================\n # Initialization and data read\n # ==================================================================\n if os.path.isdir(dst) and not overwrite:\n print('Directory {} exists. Pass overwrite=True to overwrite files in that directory, if any.'.format(dst))\n return\n elif not os.path.isdir(dst):\n os.mkdir(dst)\n\n # Ref dataset\n try:\n refds = xr.open_dataset(ref)\n except FileNotFoundError:\n print('Could not find Ref file: {}'.format(ref))\n raise\n refds = core.add_lumped_species_to_dataset(refds, verbose=verbose)\n \n # Dev dataset\n try:\n devds = xr.open_dataset(dev)\n except FileNotFoundError:\n print('Could not find Dev file: {}!'.format(dev))\n raise\n devds = core.add_lumped_species_to_dataset(devds, verbose=verbose)\n\n catdict = get_species_categories()\n \n archive_species_categories(dst)\n core.archive_lumped_species_definitions(dst)\n\n # ==================================================================\n # Create the plots!\n # ==================================================================\n for i, filecat in enumerate(catdict):\n\n # If restrict_cats list is passed,\n # skip all categories except those in the list\n if restrict_cats and filecat not in restrict_cats:\n continue\n\n catdir = os.path.join(dst,filecat)\n if not os.path.isdir(catdir):\n os.mkdir(catdir)\n varlist = []\n warninglist = []\n for subcat in catdict[filecat]:\n for spc in catdict[filecat][subcat]:\n varname = 'SpeciesConc_'+spc\n if varname not in refds.data_vars or varname not in devds.data_vars:\n warninglist.append(varname)\n continue\n varlist.append(varname)\n if warninglist != []:\n print('\\n\\nWarning: variables in {} category not in dataset: {}'.format(filecat,warninglist))\n\n # Surface plots\n if 'sfc' in plots:\n pdfname = os.path.join(catdir,'{}_Surface.pdf'.format(filecat))\n diff_sfc = []\n compare_single_level(refds, refstr, devds, devstr, \n varlist=varlist, ilev=0,\n pdfname=pdfname,\n use_cmap_RdBu=use_cmap_RdBu,\n log_color_scale=log_color_scale,\n sigdiff_list=diff_sfc)\n diff_sfc[:] = [v.replace('SpeciesConc_', '') for v in diff_sfc]\n add_nested_bookmarks_to_pdf(pdfname, filecat, \n catdict, warninglist, \n remove_prefix='SpeciesConc_')\n\n if '500hpa' in plots:\n pdfname = os.path.join(catdir,\n '{}_500hPa.pdf'.format(filecat)) \n diff_500 = []\n compare_single_level(refds, refstr, devds, devstr, \n varlist=varlist, ilev=22,\n pdfname=pdfname, \n use_cmap_RdBu=use_cmap_RdBu,\n log_color_scale=log_color_scale,\n sigdiff_list=diff_500)\n diff_500[:] = [v.replace('SpeciesConc_', '') for v in diff_500]\n add_nested_bookmarks_to_pdf(pdfname, filecat, \n catdict, warninglist, \n remove_prefix='SpeciesConc_')\n\n if 'zonalmean' in plots or 'zm' in plots:\n pdfname = os.path.join(catdir,'{}_FullColumn_ZonalMean.pdf'.format(\n filecat))\n diff_zm = []\n compare_zonal_mean(refds, refstr, devds, devstr, varlist=varlist,\n pdfname=pdfname, use_cmap_RdBu=use_cmap_RdBu,\n log_color_scale=log_color_scale,\n sigdiff_list=diff_zm)\n diff_zm[:] = [v.replace('SpeciesConc_', '') for v in diff_zm]\n add_nested_bookmarks_to_pdf(pdfname, filecat, \n catdict, warninglist, \n remove_prefix='SpeciesConc_')\n\n pdfname = os.path.join(catdir,'{}_Strat_ZonalMean.pdf'.format(\n filecat)) \n compare_zonal_mean(refds, refstr, devds, devstr, varlist=varlist,\n pdfname=pdfname, pres_range=[0,100], \n use_cmap_RdBu=use_cmap_RdBu,\n log_color_scale=log_color_scale)\n add_nested_bookmarks_to_pdf(pdfname, filecat, \n catdict, warninglist, \n remove_prefix='SpeciesConc_')\n\n # ==============================================================\n # Write the list of species having significant differences,\n # which we need to fill out the benchmark approval forms.\n # ==============================================================\n if sigdiff_files != None:\n for filename in sigdiff_files:\n if 'sfc' in filename:\n with open(filename, 'a+') as f:\n print('* {}: '.format(filecat), file=f, end='')\n for v in diff_sfc:\n print('{} '.format(v), file=f, end='')\n print(file=f)\n f.close()\n\n if '500' in filename:\n with open(filename, 'a+') as f:\n print('* {}: '.format(filecat), file=f, end='')\n for v in diff_500:\n print('{} '.format(v), file=f, end='')\n print(file=f)\n f.close()\n\n if 'zonalmean' in filename or 'zm' in filename:\n with open(filename, 'a+') as f:\n print('* {}: '.format(filecat), file=f, end='')\n for v in diff_zm:\n print('{} '.format(v), file=f, end='')\n print(file=f)\n f.close()\n\n\ndef make_benchmark_emis_plots(ref, refstr, dev, devstr,\n dst='./1mo_benchmark',\n plot_by_benchmark_cat=False,\n plot_by_hco_cat=False,\n overwrite=False, verbose=False,\n flip_ref=False, flip_dev=False,\n log_color_scale=False,\n sigdiff_files=None):\n '''\n Creates PDF files containing plots of emissions for model\n benchmarking purposes. This function is compatiblity with benchmark \n simulation output only. It is not compatible with transport tracers\n emissions diagnostics.\n\n Args:\n ref: str\n Path name for the \"Ref\" (aka \"Reference\") data set.\n\n refstr : str\n A string to describe ref (e.g. version number)\n\n dev : str\n Path name for the \"Dev\" (aka \"Development\") data set.\n This data set will be compared against the \"Reference\"\n data set.\n\n devstr : str\n A string to describe dev (e.g. version number)\n\n Keyword Args (optional):\n dst : str\n A string denoting the destination folder where a\n PDF file containing plots will be written.\n Default value: './1mo_benchmark\n\n plot_by_benchmark_cat : boolean\n Set this flag to True to separate plots into PDF files\n according to the benchmark categories (e.g. Primary,\n Aerosols, Nitrogen, etc.) These categories are specified\n in the JSON file benchmark_species.json.\n Default value: False\n\n plot_by_hco_cat : boolean\n Set this flag to True to separate plots into PDF files\n according to HEMCO emissions categories (e.g. Anthro,\n Aircraft, Bioburn, etc.)\n Default value: False\n\n overwrite : boolean\n Set this flag to True to overwrite files in the\n destination folder (specified by the dst argument).\n Default value: False\n\n verbose : boolean\n Set this flag to True to print extra informational output.\n Default value: False\n\n flip_ref : boolean\n Set this flag to True to reverse the vertical level\n ordering in the \"Ref\" dataset (in case \"Ref\" starts\n from the top of atmosphere instead of the surface).\n Default value: False\n\n flip_dev : boolean\n Set this flag to True to reverse the vertical level\n ordering in the \"Dev\" dataset (in case \"Dev\" starts\n from the top of atmosphere instead of the surface).\n Default value: False\n\n log_color_scale: boolean \n Logical to enable plotting data (not diffs) on a log color scale.\n Default value: False\n\n sigdiff_files : list of str\n Filenames that will contain the lists of species having\n significant differences in the 'sfc', '500hpa', and\n 'zonalmean' plots. These lists are needed in order to\n fill out the benchmark approval forms.\n Default value: None\n\n Remarks:\n (1) If both plot_by_benchmark_cat and plot_by_hco_cat are\n False, then all emission plots will be placed into the\n same PDF file.\n\n (2) Emissions that are 3-dimensional will be plotted as\n column sums.\n '''\n # =================================================================\n # Initialization and data read\n # =================================================================\n if os.path.isdir(dst) and not overwrite:\n print('Directory {} exists. Pass overwrite=True to overwrite files in that directory, if any.'.format(dst))\n return\n elif not os.path.isdir(dst):\n os.mkdir(dst)\n emisdir = os.path.join(dst,'Emissions')\n if not os.path.isdir(emisdir):\n os.mkdir(emisdir) \n\n # Ref dataset\n try:\n refds = xr.open_dataset(ref)\n except FileNotFoundError:\n print('Could not find Ref file: {}'.format(ref))\n raise\n\n # Dev dataset\n try:\n devds = xr.open_dataset(dev)\n except FileNotFoundError:\n print('Could not find Dev file: {}'.format(dev))\n raise\n\n # Find common variables\n quiet = not verbose\n vars, varsOther, vars2D, vars3D = core.compare_varnames(refds, devds, quiet)\n\n # Combine 2D and 3D variables into an overall list\n varlist = vars2D + vars3D\n\n # =================================================================\n # Compute column sums for 3D emissions\n # Make sure not to clobber the DataArray attributes\n # =================================================================\n with xr.set_options(keep_attrs=True):\n for v in vars3D:\n if 'lev' in refds[v].dims:\n refds[v] = refds[v].sum(dim='lev')\n if 'lev' in devds[v].dims:\n devds[v] = devds[v].sum(dim='lev')\n\n # =================================================================\n # If inputs plot_by* are both false, plot all emissions in same file\n # =================================================================\n if not plot_by_benchmark_cat and not plot_by_hco_cat:\n pdfname = os.path.join(emisdir,'Emissions.pdf')\n compare_single_level(refds, refstr, devds, devstr,\n varlist=varlist, pdfname=pdfname,\n log_color_scale=log_color_scale)\n add_bookmarks_to_pdf(pdfname, varlist,\n remove_prefix='Emis', verbose=verbose)\n return\n\n # Get emissions variables (non-inventory), categories, and species\n emis_vars = [v for v in varlist if v[:4] == 'Emis']\n emis_cats = sorted(set([v.split('_')[1] for v in emis_vars]))\n emis_spc = sorted(set([v.split('_')[0][4:] for v in emis_vars]))\n\n# This is fixed in 12.3.2, comment out for now (bmy, 5/1/19)\n# # Handle Bioburn and BioBurn as same categories (temporary until 12.3.1)\n# emis_cats.remove('BioBurn')\n \n # Sort alphabetically (assume English characters)\n emis_vars.sort(key=str.lower)\n\n # =================================================================\n # if plot_by_hco_cat is true, make a file for each HEMCO emissions\n # category that is in the diagnostics file\n #\n # Also write the list of emission quantities that have significant\n # diffs. We'll need that to fill out the benchmark forms.\n # =================================================================\n if plot_by_hco_cat:\n emisspcdir = os.path.join(dst,'Emissions')\n if not os.path.isdir(emisspcdir):\n os.mkdir(emisspcdir) \n\n diff_dict = {}\n for c in emis_cats:\n # Handle cases of bioburn and bioBurn (temporary until 12.3.1)\n if c == 'Bioburn':\n varnames = [k for k in emis_vars if any(b in k for b in ['Bioburn','BioBurn'])]\n else:\n varnames = [k for k in emis_vars if c in k]\n pdfname = os.path.join(emisspcdir,'{}_Emissions.pdf'.format(c))\n diff_emis = []\n compare_single_level(refds, refstr, devds, devstr,\n varlist=varnames, ilev=0, pdfname=pdfname,\n log_color_scale=log_color_scale,\n sigdiff_list=diff_emis)\n add_bookmarks_to_pdf(pdfname, varnames,\n remove_prefix='Emis', verbose=verbose)\n\n # Save the list of quantities with significant differences for\n # this category into the diff_dict dictionary for use below\n diff_emis[:] = [v.replace('Emis', '') for v in diff_emis]\n diff_emis[:] = [v.replace('_' + c, '') for v in diff_emis]\n diff_dict[c] = diff_emis\n\n # -------------------------------------------------------------\n # Write the list of species having significant differences,\n # which we need to fill out the benchmark approval forms.\n # -------------------------------------------------------------\n if sigdiff_files != None:\n for filename in sigdiff_files:\n if 'emis' in filename:\n with open(filename, 'w+') as f:\n for c, diff_list in diff_dict.items():\n print('* {}: '.format(c), file=f, end='')\n for v in diff_list:\n print('{} '.format(v), file=f, end='')\n print(file=f)\n f.close()\n\n # =================================================================\n # if plot_by_benchmark_cat is true, make a file for each benchmark\n # species category with emissions in the diagnostics file\n # =================================================================\n if plot_by_benchmark_cat:\n \n catdict = get_species_categories()\n warninglist = [] # in case any emissions are skipped (for use in nested pdf bookmarks)\n allcatspc = [] # for checking if emissions species not defined in benchmark category file\n emisdict = {} # used for nested pdf bookmarks\n for i, filecat in enumerate(catdict):\n\n # Get emissions for species in this benchmark category\n varlist = []\n emisdict[filecat] = {}\n for subcat in catdict[filecat]:\n for spc in catdict[filecat][subcat]:\n allcatspc.append(spc)\n if spc in emis_spc:\n emisdict[filecat][spc] = []\n emisvars = [v for v in emis_vars if spc == v.split('_')[0][4:]]\n for var in emisvars:\n emisdict[filecat][spc].append(var.replace('Emis',''))\n varlist.append(var)\n if not varlist:\n print('\\nWarning: no emissions species in benchmark species category {}'.format(filecat))\n continue \n\n # Use same directory structure as for concentration plots\n catdir = os.path.join(dst,filecat)\n if not os.path.isdir(catdir):\n os.mkdir(catdir)\n\n # Create emissions file for this benchmark species category\n pdfname = os.path.join(catdir,'{}_Emissions.pdf'.format(filecat))\n compare_single_level(refds, refstr, devds, devstr, \n varlist=varlist, ilev=0, pdfname=pdfname, \n flip_ref=flip_ref, flip_dev=flip_dev,\n log_color_scale=log_color_scale)\n add_nested_bookmarks_to_pdf(pdfname, filecat, emisdict, warninglist)\n\n # Give warning if emissions species is not assigned a benchmark category\n for spc in emis_spc:\n if spc not in allcatspc:\n print('Warning: species {} has emissions diagnostics but is not in benchmark_categories.json'.format(spc))\n\n\ndef make_benchmark_emis_tables(reflist, refstr, devlist, devstr,\n dst='./1mo_benchmark', overwrite=False,\n interval=None, ref_area_varname=None,\n dev_area_varname=None):\n '''\n Creates a text file containing emission totals by species and\n category for benchmarking purposes.\n\n Args:\n reflist: list of str\n List with the path names of the emissions and/or met field\n files that will constitute the \"Ref\" (aka \"Reference\")\n data set.\n\n refstr : str\n A string to describe ref (e.g. version number)\n\n devlist : list of str\n List with the path names of the emissions and/or met field\n files that will constitute the \"Dev\" (aka \"Development\") \n data set. The \"Dev\" data set will be compared against the\n \"Ref\" data set.\n\n devstr : str\n A string to describe dev (e.g. version number)\n\n Keyword Args (optional):\n dst : str\n A string denoting the destination folder where the file\n containing emissions totals will be written.\n Default value: ./1mo_benchmark\n\n overwrite : boolean\n Set this flag to True to overwrite files in the\n destination folder (specified by the dst argument).\n Default value : False\n\n interval : float\n Specifies the averaging period in seconds, which is used\n to convert fluxes (e.g. kg/m2/s) to masses (e.g kg).\n Default value : None\n\n ref_area_varname : str\n Name of the variable containing the grid box surface areas\n (in m2) in the ref dataset. If not specified, then this\n will be set to \"Met_AREAM2\" if the ref dataset is on the\n cubed-sphere grid, or \"AREA\" if ref is on the lat-lon grid.\n Default value: None\n\n dev_area_varname : str\n Name of the variable containing the grid box surface areas\n (in m2) in the dev dataset. If not specified, then this\n will be set to \"Met_AREAM2\" if the dev dataset is on the\n cubed-sphere grid, or \"AREA\" if dev is on the lat-lon grid.\n Default value: None\n '''\n\n # ===============================================================\n # Define destination directory\n # ===============================================================\n if os.path.isdir(dst) and not overwrite:\n print('Directory {} exists. Pass overwrite=True to overwrite files in that directory, if any.'.format(dst))\n return\n elif not os.path.isdir(dst):\n os.mkdir(dst)\n emisdir = os.path.join(dst,'Emissions')\n if not os.path.isdir(emisdir):\n os.mkdir(emisdir)\n\n # ===============================================================\n # Read data from netCDF into Dataset objects\n # ===============================================================\n\n # Ref\n try:\n refds = xr.open_mfdataset(reflist)\n except FileNotFoundError:\n print('Could not find one of the Ref files: {}'.format(reflist))\n raise\n\n # Dev\n try:\n devds = xr.open_mfdataset(devlist)\n except FileNotFoundError:\n print('Could not find one of the Dev files: {}'.format(devlist))\n raise\n\n # ===============================================================\n # Get the surface area variable name\n # by default, for lat-lon grids this is \"AREA\"\n # and for cubed-sphere grids, this is \"Met_AREAM2\"\n # ===============================================================\n\n # Ref\n if ref_area_varname == None:\n nlat = refds.sizes['lat']\n nlon = refds.sizes['lon']\n if nlat/6 == nlon:\n ref_area_varname = 'Met_AREAM2'\n else:\n ref_area_varname = 'AREA'\n\n # Error-check Ref\n if ref_area_varname not in refds.data_vars.keys():\n raise ValueError('Area variable {} is not in the ref dataset!'.format(\n ref_area_varname))\n\n # Dev\n if dev_area_varname == None:\n nlat = devds.sizes['lat']\n nlon = devds.sizes['lon']\n if nlat/6 == nlon:\n dev_area_varname = 'Met_AREAM2'\n else:\n dev_area_varname = 'AREA'\n\n # Error-check Dev\n if dev_area_varname not in devds.data_vars.keys():\n raise ValueError('Area variable {} is not in the dev dataset!'.format(\n dev_area_varname))\n\n # ===============================================================\n # Create table of emissions\n # ===============================================================\n\n # Emissions species dictionary\n species = json_load_file(open(os.path.join(os.path.dirname(__file__),\n emission_spc)))\n inventories = json_load_file(open(os.path.join(os.path.dirname(__file__),\n emission_inv)))\n\n # Destination files\n file_emis_totals = os.path.join(dst, emisdir, 'Emission_totals.txt')\n file_inv_totals = os.path.join(dst, emisdir, 'Inventory_totals.txt')\n\n # If the averaging interval (in seconds) is not specified,\n # then assume July 2016 = 86400 seconds * 31 days\n if interval == None:\n interval = 86400.0 * 31.0\n\n # Write to file\n create_total_emissions_table(refds, refstr, devds, devstr, \n species, file_emis_totals,\n interval, template='Emis{}_',\n ref_area_varname=ref_area_varname,\n dev_area_varname=dev_area_varname)\n create_total_emissions_table(refds, refstr, devds, devstr, \n inventories, file_inv_totals,\n interval, template='Inv{}_',\n ref_area_varname=ref_area_varname,\n dev_area_varname=dev_area_varname)\n\n\ndef make_benchmark_jvalue_plots(ref, refstr, dev, devstr,\n varlist=None, \n dst='./1mo_benchmark',\n local_noon_jvalues=False,\n plots=['sfc', '500hpa', 'zonalmean'],\n overwrite=False, verbose=False,\n flip_ref=False, flip_dev=False,\n log_color_scale=False,\n sigdiff_files=None):\n '''\n Creates PDF files containing plots of J-values for model\n benchmarking purposes.\n\n Args:\n ref: str\n Path name for the \"Ref\" (aka \"Reference\") data set.\n\n refstr : str\n A string to describe ref (e.g. version number)\n \n dev : str\n Path name for the \"Dev\" (aka \"Development\") data set.\n This data set will be compared against the \"Reference\"\n data set.\n\n devstr : str\n A string to describe dev (e.g. version number)\n \n Keyword Args (optional):\n varlist : list\n List of J-value variables to plot. If not passed, \n then all J-value variables common to both dev \n and ref will be plotted. The varlist argument can be\n a useful way of restricting the number of variables\n plotted to the pdf file when debugging.\n Default value: None\n\n dst : str\n A string denoting the destination folder where a\n PDF file containing plots will be written.\n Default value: ./1mo_benchmark.\n \n local_noon_jvalues : boolean\n Set this switch to plot local noon J-values. This will\n divide all J-value variables by the JNoonFrac counter,\n which is the fraction of the time that it was local noon\n at each location.\n Default value : False\n\n plots : list of strings\n List of plot types to create.\n Default value: ['sfc', '500hpa', 'zonalmean']\n\n overwrite : boolean\n Set this flag to True to overwrite files in the\n destination folder (specified by the dst argument).\n Default value: False.\n\n verbose : boolean\n Set this flag to True to print extra informational output.\n Default value: False\n\n flip_ref : boolean\n Set this flag to True to reverse the vertical level\n ordering in the \"Ref\" dataset (in case \"Ref\" starts\n from the top of atmosphere instead of the surface).\n Default value: False\n\n flip_dev : boolean\n Set this flag to True to reverse the vertical level\n ordering in the \"Dev\" dataset (in case \"Dev\" starts\n from the top of atmosphere instead of the surface).\n Default value: False\n\n log_color_scale: boolean \n Logical to enable plotting data (not diffs) on a log color scale.\n Default value: False\n\n sigdiff_files : list of str\n Filenames that will contain the lists of J-values having\n significant differences in the 'sfc', '500hpa', and\n 'zonalmean' plots. These lists are needed in order to\n fill out the benchmark approval forms.\n Default value: None\n\n Remarks:\n Will create 4 files containing J-value plots:\n (1 ) Surface values\n (2 ) 500 hPa values\n (3a) Full-column zonal mean values.\n (3b) Stratospheric zonal mean values\n These can be toggled on/off with the plots keyword argument.\n\n At present, we do not yet have the capability to split the\n plots up into separate files per category (e.g. Primary,\n Aerosols, etc.). This is primarily due to the fact that \n we archive J-values from GEOS-Chem for individual species\n but not family species. We could attempt to add this \n functionality later if there is sufficient demand. \n '''\n \n if os.path.isdir(dst) and not overwrite:\n print('Directory {} exists. Pass overwrite=True to overwrite files in tht directory, if any.'.format(dst))\n return\n elif not os.path.isdir(dst):\n os.mkdir(dst)\n\n # Ref dataset\n try:\n refds = xr.open_dataset(ref)\n except FileNotFoundError:\n print('Could not find Ref file: {}'.format(ref))\n raise\n\n # Dev dataset\n try:\n devds = xr.open_dataset(dev)\n except FileNotFoundError:\n print('Could not find Dev file: {}'.format(dev))\n raise\n\n # Find common variables in both datasets\n if varlist == None:\n quiet = not verbose\n [cmn, cmnOther, cmn2D, cmn3D] = core.compare_varnames(refds, devds, quiet)\n\n # =================================================================\n # Local noon or continuously-averaged J-values?\n # =================================================================\n if local_noon_jvalues:\n\n # Get a list of local noon J-value variables\n # (or use the varlist passed via tha argument list)\n prefix = 'JNoon_'\n if varlist == None:\n varlist = [v for v in cmn if prefix in v]\n\n # Make sure JNoonFrac (fraction of times it was local noon\n # in each column) is present in both Ref and Dev datasets\n if not 'JNoonFrac' in cmn:\n msg = 'JNoonFrac is not common to Ref and Dev datasets!'\n raise ValueError(msg)\n\n # JNoon_* are cumulative sums of local noon J-values; we need\n # to divide these by JNoonFrac to get the average value\n refds = core.divide_dataset_by_dataarray(refds,\n refds['JNoonFrac'],\n varlist)\n devds = core.divide_dataset_by_dataarray(devds,\n devds['JNoonFrac'],\n varlist)\n\n # Subfolder of dst where PDF files will be printed\n subdir= 'JValuesLocalNoon'\n\n else:\n\n # Get a list of continuously averaged J-value variables\n # (or use the varlist passed via tha argument list)\n prefix = 'Jval_'\n if varlist == None:\n varlist = [v for v in cmn if prefix in v]\n\n # Subfolder of dst where PDF files will be printed\n subdir = 'JValues'\n\n # =================================================================\n # Create the plots\n # =================================================================\n\n # Make the folder to contain plots if it doesn't exist\n jvdir = os.path.join(dst, subdir)\n if not os.path.isdir(jvdir):\n os.mkdir(jvdir)\n \n # Surface plots\n if 'sfc' in plots:\n pdfname = os.path.join(jvdir, '{}Surface.pdf'.format(prefix))\n diff_sfc = []\n compare_single_level(refds, refstr, devds, devstr,\n varlist=varlist, ilev=0, pdfname=pdfname,\n flip_ref=flip_ref, flip_dev=flip_dev,\n log_color_scale=log_color_scale,\n sigdiff_list=diff_sfc)\n diff_sfc[:] = [v.replace(prefix, '') for v in diff_sfc]\n add_bookmarks_to_pdf(pdfname, varlist,\n remove_prefix=prefix, verbose=verbose)\n\n # 500hPa plots\n if '500hpa' in plots:\n pdfname = os.path.join(jvdir, '{}500hPa.pdf'.format(prefix))\n diff_500 = []\n compare_single_level(refds, refstr, devds, devstr,\n varlist=varlist, ilev=22, pdfname=pdfname,\n flip_ref=flip_ref, flip_dev=flip_dev,\n log_color_scale=log_color_scale,\n sigdiff_list=diff_500)\n diff_500[:] = [v.replace(prefix, '') for v in diff_500]\n add_bookmarks_to_pdf(pdfname, varlist,\n remove_prefix=prefix, verbose=verbose)\n\n # Full-column zonal mean plots\n if 'zonalmean' in plots:\n pdfname = os.path.join(jvdir,\n '{}FullColumn_ZonalMean.pdf'.format(prefix))\n diff_zm = []\n compare_zonal_mean(refds, refstr, devds, devstr,\n varlist=varlist, pdfname=pdfname,\n flip_ref=flip_ref, flip_dev=flip_dev,\n log_color_scale=log_color_scale,\n sigdiff_list=diff_zm)\n diff_zm[:] = [v.replace(prefix, '') for v in diff_zm]\n add_bookmarks_to_pdf(pdfname, varlist,\n remove_prefix=prefix, verbose=verbose)\n\n # Stratospheric zonal mean plots\n pdfname = os.path.join(jvdir,'{}Strat_ZonalMean.pdf'.format(prefix))\n compare_zonal_mean(refds, refstr, devds, devstr,\n varlist=varlist, pdfname=pdfname, pres_range=[0,100],\n flip_ref=flip_ref, flip_dev=flip_dev,\n log_color_scale=log_color_scale)\n add_bookmarks_to_pdf(pdfname, varlist,\n remove_prefix=prefix, verbose=verbose)\n\n # =================================================================\n # Write the lists of J-values that have significant differences,\n # which we need to fill out the benchmark approval forms.\n # =================================================================\n if sigdiff_files != None:\n for filename in sigdiff_files:\n if 'sfc' in filename:\n with open(filename, 'a+') as f:\n print('* J-Values: ', file=f, end='')\n for v in diff_sfc:\n print('{} '.format(v), file=f, end='')\n print(file=f)\n f.close()\n\n if '500' in filename:\n with open(filename, 'a+') as f:\n print('* J-Values: ', file=f, end='')\n for v in diff_500:\n print('{} '.format(v), file=f, end='')\n print(file=f)\n f.close()\n\n if 'zonalmean' in filename or 'zm' in filename:\n with open(filename, 'a+') as f:\n print('* J-Values: ', file=f, end='')\n for v in diff_zm:\n print('{} '.format(v), file=f, end='')\n print(file=f)\n f.close()\n\n\ndef make_benchmark_aod_plots(ref, refstr, dev, devstr,\n varlist=None, dst='./1mo_benchmark',\n overwrite=False, verbose=False,\n log_color_scale=False,\n sigdiff_files=None):\n '''\n Creates PDF files containing plots of column aerosol optical\n depths (AODs) for model benchmarking purposes.\n\n Args:\n ref: str\n Path name for the \"Ref\" (aka \"Reference\") data set.\n\n refstr : str\n A string to describe ref (e.g. version number)\n\n dev : str\n Path name for the \"Dev\" (aka \"Development\") data set.\n This data set will be compared against the \"Reference\"\n data set.\n\n devstr : str\n A string to describe dev (e.g. version number)\n\n Keyword Args (optional):\n varlist : list\n List of AOD variables to plot. If not passed, \n then all AOD variables common to both dev \n and ref will be plotted. The varlist argument can be\n a useful way of restricting the number of variables\n plotted to the pdf file when debugging.\n Default value: None\n\n dst : str\n A string denoting the destination folder where a\n PDF file containing plots will be written.\n Default value: ./1mo_benchmark.\n\n overwrite : boolean\n Set this flag to True to overwrite files in the\n destination folder (specified by the dst argument).\n Default value: False.\n\n verbose : boolean\n Set this flag to True to print extra informational output.\n Default value: False\n\n log_color_scale: boolean \n Logical to enable plotting data (not diffs) on a log color scale.\n Default value: False\n\n sigdiff_files : list of str\n Filenames that will contain the list of quantities having\n having significant differences in the column AOD plots.\n These lists are needed in order to fill out the benchmark\n approval forms.\n Default value: None\n '''\n # =================================================================\n # Initialization and also read data\n # =================================================================\n if os.path.isdir(dst) and not overwrite:\n print('Directory {} exists. Pass overwrite=True to overwrite files in tht directory, if any.'.format(dst))\n return\n elif not os.path.isdir(dst):\n os.mkdir(dst)\n aoddir = os.path.join(dst, 'Aerosols')\n if not os.path.isdir(aoddir):\n os.mkdir(aoddir)\n\n # Read the Ref dataset\n try:\n refds = xr.open_dataset(ref)\n except FileNotFoundError:\n print('Could not find Ref file: {}'.format(ref))\n raise\n\n # Read the Dev dataset\n try:\n devds = xr.open_dataset(dev)\n except FileNotFoundError:\n print('Could not find Dev file: {}'.format(dev))\n raise\n\n # NOTE: GCHP diagnostic variable exports are defined before the\n # input.geos file is read. This means \"WL1\" will not have been\n # replaced with \"550nm\" in the variable names. Do this string\n # replace operation here, so that we can compare GCC and GCHP\n # data directly. (bmy, 4/29/19)\n with xr.set_options(keep_attrs=True):\n\n # Rename variables in the Ref dataset\n old2new = {}\n for v in refds.data_vars.keys():\n if 'WL1' in v:\n newname = v.replace('WL1', '550nm')\n old2new[v] = newname\n refds = refds.rename(old2new)\n\n # Rename variables in the Dev dataset\n old2new = {}\n for v in devds.data_vars.keys():\n if 'WL1' in v:\n newname = v.replace('WL1', '550nm')\n old2new[v] = newname\n devds = devds.rename(old2new)\n\n # Find common AOD variables in both datasets\n # (or use the varlist passed via keyword argument)\n if varlist == None:\n quiet = not verbose\n [cmn, cmnOther, cmn2D, cmn3D] = core.compare_varnames(refds, \n devds, quiet)\n varlist = [v for v in cmn3D if 'AOD' in v and '_bin' not in v]\n\n # Dictionary and list for new display names\n newvars = json_load_file(open(os.path.join(os.path.dirname(__file__),\n aod_spc)))\n newvarlist = []\n\n # =================================================================\n # Compute the total AOD by summing over the constituent members\n # =================================================================\n\n # Take one of the variables so we can use its dims, coords,\n # attrs to create the DataArray object for total AOD\n v = varlist[0]\n\n # Create a DataArray to hold total column AOD\n # This is the same shape as the DataArray objects in refds\n reftot = xr.DataArray(np.zeros(refds[v].values.shape),\n name='AODTotal',\n dims=refds[v].dims,\n coords=refds[v].coords,\n attrs=refds[v].attrs)\n\n # Create a DataArray to hold total column AOD\n # This is the same shape as the DataArray objects in devds\n devtot = xr.DataArray(np.zeros(devds[v].values.shape),\n name='AODTotal',\n dims=devds[v].dims,\n coords=devds[v].coords,\n attrs=devds[v].attrs)\n\n # Save the variable attributes so that we can reattach them\n refattrs = reftot.attrs\n devattrs = devtot.attrs\n\n # Compute the sum of all AOD variables\n for v in varlist:\n reftot = reftot + refds[v]\n devtot = devtot + devds[v]\n\n # Reattach the variable attributes\n reftot.name = 'AODTotal'\n reftot.attrs = refattrs\n reftot.attrs['long_name'] = 'Total aerosol optical depth'\n devtot.name = 'AODTotal'\n devtot.attrs = devattrs\n devtot.attrs['long_name'] = 'Total aerosol optical depth'\n\n # Merge these variables back into the dataset\n refds = xr.merge([refds, reftot])\n devds = xr.merge([devds, devtot])\n\n # Also add AODTotal to the list\n varlist.append('AODTotal')\n\n # =================================================================\n # Compute column AODs\n # Create a new DataArray for each column AOD variable,\n # using the new display name, and preserving attributes.\n # Merge the new DataArrays back into the DataSets.\n # =================================================================\n for v in varlist:\n\n # Get the new name for each AOD variable (it's easier to display)\n if v in newvars:\n newname = newvars[v]\n newvarlist.append(newname)\n else:\n raise ValueError('Could not find a display name for'.format(v))\n\n # Don't clobber existing DataArray and Dataset attributes\n with xr.set_options(keep_attrs=True):\n\n # Add column AOD of newname to Ref\n array = refds[v].sum(dim='lev')\n array.name = newname\n refds = xr.merge([refds, array])\n\n # Add column AOD of newname to Dev\n array = devds[v].sum(dim='lev')\n array.name = newname\n devds = xr.merge([devds, array])\n\n # =================================================================\n # Create the plots\n # =================================================================\n pdfname = os.path.join(aoddir, 'Aerosols_ColumnOptDepth.pdf')\n diff_aod = []\n compare_single_level(refds, refstr, devds, devstr,\n varlist=newvarlist, ilev=0, pdfname=pdfname,\n log_color_scale=log_color_scale,\n sigdiff_list=diff_aod)\n diff_aod[:] = [v.replace('Column_AOD_', '') for v in diff_aod]\n add_bookmarks_to_pdf(pdfname, newvarlist,\n remove_prefix='Column_AOD_', verbose=verbose)\n\n # =================================================================\n # Write the list of AOD quantities having significant differences,\n # which we will need to fill out the benchmark forms.\n # =================================================================\n for filename in sigdiff_files:\n if 'sfc' in filename:\n with open(filename, 'a+') as f:\n print('* Column AOD: ', file=f, end='')\n for v in diff_aod:\n print('{} '.format(v), file=f, end='')\n print(file=f)\n f.close()\n\n\ndef create_budget_table(devdata, devstr, region, species, varnames,\n outfilename, interval=2678400.0, template='Budget_{}'):\n '''\n Creates a table of budgets by species and component for a data set.\n\n Args:\n devdata : xarray Dataset\n The second data set to be compared (aka \"Development\").\n\n devstr: str\n A string that can be used to identify the data set specified\n by devfile (e.g. a model version number or other identifier).\n\n region : str\n Name of region for which budget will be computed.\n\n species : List of strings\n List of species to include in budget tables.\n\n varnames : List of strings\n List of variable names in the budget diagnostics.\n\n outfilename : str\n Name of the text file which will contain the table of\n emissions totals.\n\n Keyword Args (optional):\n interval : float\n The length of the data interval in seconds. By default, interval\n is set to the number of seconds in a 31-day month (86400 * 31),\n which corresponds to typical benchmark simulation output.\n\n template : str\n Template for the diagnostic names that are contained in the\n data set. If not specified, template will be set to \"Budget_{}\",\n where {} will be replaced by the species name.\n\n Returns:\n None. Writes to a text file specified by the \"outfilename\" argument.\n\n Remarks:\n This method is mainly intended for model benchmarking purposes,\n rather than as a general-purpose tool.\n '''\n\n # Error check arguments\n if not isinstance(devdata, xr.Dataset):\n raise ValueError('The devdata argument must be an xarray Dataset!')\n\n # Open file for output\n f = open(outfilename, 'w')\n\n for spc_name in species:\n\n # Title string\n title = '### {} budget totals for species {}'.format(devstr,spc_name)\n \n # Write header to file\n print('#'*79, file=f)\n print('{}{}'.format(title.ljust(76), '###'), file=f)\n print('#'*79, file=f)\n\n # Get variable names for this species\n spc_vars = [ v for v in varnames if v.endswith('_'+spc_name) ]\n\n for v in spc_vars:\n\n # Component name\n comp_name = v.replace('Budget', '')\n comp_name = comp_name.replace('_'+spc_name, '')\n comp_name = comp_name.replace(region, '')\n \n # Convert from kg/s to Tg\n devarray = devdata[v] * interval * 1e-9\n units = 'Tg'\n \n # Compute sum\n total_dev = np.sum(devarray.values)\n\n # Write output\n print('{} : {:13.6e} {}'.format(comp_name.ljust(12),\n total_dev, units), file=f)\n\n # Add new lines before going to the next species\n print(file=f)\n print(file=f)\n\n # Close file\n f.close()\n\n \ndef make_benchmark_budget_tables(devlist, devstr, dst='./1mo_benchmark',\n overwrite=False, interval=None):\n '''\n Creates a text file containing budgets by species for benchmarking\n purposes.\n\n Args:\n devlist : list of str\n List with the path names of the emissions and/or met field\n files that will constitute the \"Dev\" (aka \"Development\") \n data set. The \"Dev\" data set will be compared against the\n \"Ref\" data set.\n\n devstr : str\n A string to describe dev (e.g. version number)\n\n Keyword Args (optional):\n dst : str\n A string denoting the destination folder where the file\n containing emissions totals will be written.\n Default value: ./1mo_benchmark\n\n overwrite : boolean\n Set this flag to True to overwrite files in the\n destination folder (specified by the dst argument).\n Default value : False\n\n interval : float\n Specifies the averaging period in seconds, which is used\n to convert fluxes (e.g. kg/m2/s) to masses (e.g kg).\n Default value : None\n '''\n\n # ===============================================================\n # Define destination directory\n # ===============================================================\n if os.path.isdir(dst) and not overwrite:\n print('Directory {} exists. Pass overwrite=True to overwrite files in that directory, if any.'.format(dst))\n return\n elif not os.path.isdir(dst):\n os.mkdir(dst)\n budgetdir = os.path.join(dst,'Budget')\n if not os.path.isdir(budgetdir):\n os.mkdir(budgetdir)\n\n # ===============================================================\n # Read data from netCDF into Dataset objects\n # ===============================================================\n\n # Dev\n try:\n devds = xr.open_mfdataset(devlist)\n except FileNotFoundError:\n print('Could not find one of the Dev files: {}'.format(devlist))\n raise\n\n # ===============================================================\n # Create budget table\n # ===============================================================\n\n # If the averaging interval (in seconds) is not specified,\n # then assume July 2016 = 86400 seconds * 31 days\n if interval == None:\n interval = 86400.0 * 31.0\n \n # Get budget variable and regions\n budget_vars = [ k for k in devds.data_vars.keys() if k[:6] == 'Budget' ]\n budget_regions = sorted(set([v.split('_')[0][-4:] for v in budget_vars]))\n\n for region in budget_regions:\n \n # Destination file\n file_budget = os.path.join( dst, budgetdir,\n 'Budget_'+region+'.txt')\n\n # Get variable names and species for this region\n region_vars = [ k for k in budget_vars if region in k ]\n region_spc = sorted(set([v.split('_')[1] for v in region_vars]))\n \n # Write to file\n create_budget_table(devds, devstr, region, region_spc, region_vars,\n file_budget, interval, template='Budget_{}')\n \n\ndef add_bookmarks_to_pdf(pdfname, varlist, remove_prefix='', verbose=False ):\n '''\n Adds bookmarks to an existing PDF file.\n\n Args:\n pdfname : str\n Name of an existing PDF file of species or emission plots\n to which bookmarks will be attached.\n\n varlist : list\n List of variables, which will be used to create the\n PDF bookmark names.\n\n Keyword Args (optional):\n remove_prefix : str\n Specifies a prefix to remove from each entry in varlist\n when creating bookmarks. For example, if varlist has\n a variable name \"SpeciesConc_NO\", and you specify\n remove_prefix=\"SpeciesConc_\", then the bookmark for\n that variable will be just \"NO\", etc.\n\n verbose : boolean\n Set this flag to True to print extra informational output.\n Default value: False\n '''\n\n # Setup\n pdfobj = open(pdfname,'rb')\n input = PdfFileReader(pdfobj)\n output = PdfFileWriter()\n \n for i, varname in enumerate(varlist):\n bookmarkname = varname.replace(remove_prefix,'')\n if verbose: print('Adding bookmark for {} with name {}'.format(varname, bookmarkname))\n output.addPage(input.getPage(i))\n output.addBookmark(bookmarkname,i)\n output.setPageMode('/UseOutlines')\n \n # Write to temp file\n pdfname_tmp = pdfname+'_with_bookmarks.pdf'\n outputstream = open(pdfname_tmp,'wb')\n output.write(outputstream) \n outputstream.close()\n \n # Rename temp file with the target name\n os.rename(pdfname_tmp, pdfname)\n\n \ndef add_nested_bookmarks_to_pdf( pdfname, category, catdict, warninglist, remove_prefix=''):\n\n '''\n Add nested bookmarks to PDF.\n\n Args:\n pdfname : str\n Path of PDF to add bookmarks to\n\n category : str\n Top-level key name in catdict that maps to contents of PDF\n\n catdict : dictionary\n Dictionary containing key-value pairs where one top-level key matches\n category and has value fully describing pages in PDF. The value is a \n dictionary where keys are level 1 bookmark names, and values are\n lists of level 2 bookmark names, with one level 2 name per PDF page. \n Level 2 names must appear in catdict in the same order as in the PDF.\n\n warninglist : list of strings\n Level 2 bookmark names to skip since not present in PDF.\n\n Keyword Args (optional):\n remove_prefix : str\n Prefix to be remove from warninglist names before comparing with \n level 2 bookmark names in catdict.\n Default value: empty string (warninglist names match names in catdict) \n '''\n \n # Setup\n pdfobj = open(pdfname,'rb')\n input = PdfFileReader(pdfobj)\n output = PdfFileWriter()\n warninglist = [k.replace(remove_prefix,'') for k in warninglist]\n \n # Loop over the subcategories in this category; make parent bookmark\n i = -1\n for subcat in catdict[category]:\n\n # First check that there are actual variables for this subcategory; otherwise skip\n numvars = 0\n if catdict[category][subcat]:\n for varname in catdict[category][subcat]:\n if varname in warninglist:\n continue\n else:\n numvars += 1\n else:\n continue\n if numvars == 0:\n continue\n\n # There are non-zero variables to plot in this subcategory\n i = i+1\n output.addPage(input.getPage(i))\n parent = output.addBookmark(subcat,i)\n output.setPageMode('/UseOutlines')\n first = True\n \n # Loop over variables in this subcategory; make children bookmarks\n for varname in catdict[category][subcat]:\n if varname in warninglist:\n print('Warning: skipping {}'.format(varname))\n continue\n if first:\n output.addBookmark(varname, i, parent)\n first = False\n else:\n i = i+1\n output.addPage(input.getPage(i))\n output.addBookmark(varname, i, parent)\n output.setPageMode('/UseOutlines')\n \n # Write to temp file\n pdfname_tmp = pdfname+'_with_bookmarks.pdf'\n outputstream = open(pdfname_tmp,'wb')\n output.write(outputstream) \n outputstream.close()\n\n # Rename temp file with the target name\n os.rename(pdfname_tmp, pdfname)\n\n\ndef normalize_colors(vmin, vmax,\n is_all_zeroes=False,\n log_color_scale=False):\n '''\n Normalizes colors to the range of 0..1 for input to\n matplotlib-based plotting functions, given the max & min values.\n\n For log-color scales, special handling is done to prevent\n taking the log of data that is all zeroes.\n\n Args:\n -----\n vmin, vmax : float\n Minimum and maximum values of a data array.\n\n Keyword Args:\n -------------\n is_all_zeroes : boolean\n Logical flag to denote if the data array is all zeroes.\n Default value: False\n\n log_color_scale : boolean\n Logical flag to denote that we are using a logarithmic\n color scale instead of a linear color scale.\n Default value: False:\n\n Returns:\n --------\n norm : matplotlib Norm\n The normalized colors, in a matplotlib Norm object.\n\n Remarks:\n --------\n (1) This is an internal routine, called from compare_single_level,\n and compare_zonal_mean.\n\n (2) For log scale, the min value will be 3 orders of magnitude\n less than the max. But if the data is all zeroes, then we\n will revert to a linear scale (to avoid a math error of\n taking a log of zero).\n '''\n if is_all_zeroes:\n norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)\n else:\n if log_color_scale:\n norm = mpl.colors.LogNorm(vmin=vmax/1e3, vmax=vmax)\n else:\n norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)\n\n return norm\n\n\n# =============================================================================\n# The rest of this file contains legacy code that may be deleted in the future\n# =============================================================================\n\ndef plot_layer(dr, ax, title='', unit='', diff=False, vmin=None, vmax=None):\n '''Plot 2D DataArray as a lat-lon layer\n\n Parameters\n ----------\n dr : xarray.DataArray\n Dimension should be [lat, lon]\n\n ax : Cartopy GeoAxes object with PlateCarree projection\n Axis on which to plot this figure\n\n title : string, optional\n Title of the figure\n\n unit : string, optional\n Unit shown near the colorbar\n\n diff : Boolean, optional\n Switch to the color scale for difference plot\n\n NOTE: This is deprecated and will be removed in the future.\n '''\n\n assert isinstance(ax, GeoAxes), (\n 'Input axis must be cartopy GeoAxes! '\n 'Can be created by: \\n'\n 'plt.axes(projection=ccrs.PlateCarree()) \\n or \\n'\n 'plt.subplots(n, m, subplot_kw={\"projection\": ccrs.PlateCarree()})'\n )\n assert ax.projection == ccrs.PlateCarree(), (\n 'must use PlateCarree projection'\n )\n\n fig = ax.figure # get parent figure\n\n if vmax == None and vmin == None:\n if diff:\n vmax = np.max(np.abs(dr.values))\n vmin = -vmax\n cmap = cmap_diff\n else:\n vmax = np.max(dr.values)\n vmin = 0\n cmap = cmap_abs\n\n if diff:\n cmap = cmap_diff\n else:\n cmap = cmap_abs\n\n # imshow() is 6x faster than pcolormesh(), but with some limitations:\n # - only works with PlateCarree projection\n # - the left map boundary can't be smaller than -180,\n # so the leftmost box (-182.5 for 4x5 grid) is slightly out of the map\n im = dr.plot.imshow(ax=ax, vmin=vmin, vmax=vmax, cmap=cmap,\n transform=ccrs.PlateCarree(),\n add_colorbar=False)\n\n # can also pass cbar_kwargs to dr.plot() to add colorbar,\n # but it is easier to tweak colorbar afterwards\n cb = fig.colorbar(im, ax=ax, shrink=0.6, orientation='horizontal', pad=0.1)\n cb.set_label(unit)\n\n # xarray automatically sets a title which might contain dimension info.\n # surpress it or use user-provided title\n ax.set_title(title)\n\n ax.coastlines()\n add_latlon_ticks(ax) # add ticks and gridlines\n\n\ndef plot_zonal(dr, ax, title='', unit='', diff=False):\n '''Plot 2D DataArray as a zonal profile\n\n Parameters\n ----------\n dr : xarray.DataArray\n dimension should be [lev, lat]\n\n ax : matplotlib axes object\n Axis on which to plot this figure\n\n title : string, optional\n Title of the figure\n\n unit : string, optional\n Unit shown near the colorbar\n\n diff : Boolean, optional\n Switch to the color scale for difference plot\n\n NOTE: This is deprecated and will be removed in the future.\n '''\n\n # assume global field from 90S to 90N\n xtick_positions = np.array([-90, -60, -30, 0, 30, 60, 90])\n xticklabels = ['90$\\degree$S',\n '60$\\degree$S',\n '30$\\degree$S',\n '0$\\degree$',\n '30$\\degree$N',\n '60$\\degree$N',\n '90$\\degree$N'\n ]\n\n fig = ax.figure # get parent figure\n\n # this code block largely duplicates plot_layer()\n # TODO: remove duplication\n if diff:\n vmax = np.max(np.abs(dr.values))\n vmin = -vmax\n cmap = cmap_diff\n else:\n vmax = np.max(dr.values)\n vmin = 0\n cmap = cmap_abs\n\n im = dr.plot.imshow(ax=ax, vmin=vmin, vmax=vmax, cmap=cmap,\n add_colorbar=False)\n\n # the ratio of x-unit/y-unit in screen-space\n # 'auto' fills current figure with data without changing the figrue size\n ax.set_aspect('auto')\n\n ax.set_xticks(xtick_positions)\n ax.set_xticklabels(xticklabels)\n ax.set_xlabel('')\n ax.set_ylabel('Level')\n\n # NOTE: The surface has a hybrid eta coordinate of 1.0 and the\n # atmosphere top has a hybrid eta coordinate of 0.0. If we don't\n # flip the Y-axis, then the surface will be plotted at the top\n # of the plot. (bmy, 3/7/18)\n ax.invert_yaxis()\n\n # can also pass cbar_kwargs to dr.plot() to add colorbar\n # but it is easier to tweak colorbar afterwards\n cb = fig.colorbar(im, ax=ax, shrink=0.6, orientation='horizontal', pad=0.1)\n cb.set_label(unit)\n\n ax.set_title(title)\n\n\ndef make_pdf(ds1, ds2, filename, on_map=True, diff=False,\n title1='DataSet 1', title2='DataSet 2', unit='',\n matchcbar=False):\n '''Plot all variables in two 2D DataSets, and create a pdf.\n\n ds1 : xarray.DataSet\n shown on the left column\n\n ds2 : xarray.DataSet\n shown on the right column\n\n filename : string\n Name of the pdf file\n\n on_map : Boolean, optional\n If True (default), use plot_layer() to plot\n If False, use plot_zonal() to plot\n\n diff : Boolean, optional\n Switch to the color scale for difference plot\n\n title1, title2 : string, optional\n Title for each DataSet\n\n unit : string, optional\n Unit shown near the colorbar\n\n NOTE: This is deprecated and will be removed in the future.\n '''\n\n if on_map:\n plot_func = plot_layer\n subplot_kw = {'projection': ccrs.PlateCarree()}\n else:\n plot_func = plot_zonal\n subplot_kw = None\n\n # get a list of all variable names in ds1\n # assume ds2 also has those variables\n varname_list = list(ds1.data_vars.keys())\n\n n_var = len(varname_list)\n print('Benchmarking {} variables'.format(n_var))\n\n n_row = 3 # how many rows per page. TODO: should this be input argument?\n n_page = (n_var-1) // n_row + 1 # how many pages\n\n print('generating a {}-page pdf'.format(n_page))\n print('Page: ', end='')\n\n pdf = PdfPages(filename)\n\n for ipage in range(n_page):\n print(ipage, end=' ')\n fig, axes = plt.subplots(n_row, 2, figsize=[16, 16],\n subplot_kw=subplot_kw)\n\n # a list of 3 (n_row) variables names\n sub_varname_list = varname_list[n_row*ipage:n_row*(ipage+1)]\n\n for i, varname in enumerate(sub_varname_list):\n\n # Get min/max for both datasets to have same colorbar (ewl)\n unitmatch = False\n if matchcbar:\n vmin = min([ds1[varname].data.min(), ds2[varname].data.min()])\n vmax = max([ds1[varname].data.max(), ds2[varname].data.max()])\n unitmatch = ds1[varname].units == ds2[varname].units\n\n for j, ds in enumerate([ds1, ds2]):\n if on_map:\n if matchcbar and unitmatch:\n plot_func(ds[varname], axes[i][j], \n unit=ds[varname].units, diff=diff,\n vmin=vmin, vmax=vmax)\n else:\n plot_func(ds[varname], axes[i][j], \n unit=ds[varname].units, diff=diff)\n else:\n # For now, assume zonal mean if plotting zonal (ewl)\n if matchcbar and unitmatch:\n plot_func(ds[varname].mean(axis=2), axes[i][j], \n unit=ds[varname].units, diff=diff,\n vmin=vmin, vmax=vmax)\n else:\n plot_func(ds[varname].mean(axis=2), axes[i][j], \n unit=ds[varname].units, diff=diff)\n\n # TODO: tweak varname, e.g. Trim \"TRC_O3\" to \"O3\"\n axes[i][0].set_title(varname+'; '+title1)\n axes[i][1].set_title(varname+'; '+title2)\n\n # TODO: unit conversion according to data range of each variable,\n # e.g. mol/mol -> ppmv, ppbv, etc...\n\n pdf.savefig(fig)\n plt.close(fig) # don't show in notebook!\n pdf.close() # close it to save the pdf\n print('done!')\n\n","sub_path":"gcpy/benchmark.py","file_name":"benchmark.py","file_ext":"py","file_size_in_byte":149977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"497096880","text":"from static.libs.cortex import Cortex\nfrom static.libs.user import user\nfrom datetime import datetime\nfrom threading import Thread\nimport time\n\nclass Record():\n\tdef __init__(self):\n\t\tself.c = Cortex(user, debug_mode=True)\n\t\tself.c.do_prepare_steps()\n\n\tdef record(self,\n\t\t\t record_name,\n\t\t\t record_description):\n\t\tself.c.create_record(record_name,\n\t\t\t\t\t\t\t record_description)\n\n\tdef add_markers(self, label):\n\t\tmarker_time = time.time() * 1000\n\t\tprint('add marker at : ', marker_time)\n\n\t\tmarker = {\n\t\t\t\"label\": 'label',\n\t\t\t\"value\": label,\n\t\t\t\"port\": \"python-app\",\n\t\t\t\"time\": marker_time\n\t\t}\n\t\tself.c.inject_marker_request(marker)\n\n\tdef export(self,\n\t\t\t record_export_folder,\n\t\t\t record_export_data_types,\n\t\t\t record_export_format,\n\t\t\t record_export_version):\n\t\tself.c.stop_record()\n\t\tself.c.disconnect_headset()\n\t\tself.c.export_record(record_export_folder,\n\t\t\t\t\t\t\t record_export_data_types,\n\t\t\t\t\t\t\t record_export_format,\n\t\t\t\t\t\t\t record_export_version,\n\t\t\t\t\t\t\t [self.c.record_id])\n\n\nr = Record()\n\ndef startRecording(name):\n\tr.record(name,str(datetime.now()))\n\ndef injectMarker(label):\n\tr.add_markers(label)\n\ndef stopRecording():\n\tr.export('C:/EEG data/EuroVis',\n\t\t\t ['EEG', 'MOTION', 'PM', 'MC', 'FE', 'BP'],\n\t\t\t 'CSV', 'V2' )\n","sub_path":"EEG/static/libs/record.py","file_name":"record.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"222179744","text":"\n# coding: utf-8\n\n# In[1]:\n\nfrom IPython.core.interactiveshell import InteractiveShell\nInteractiveShell.ast_node_interactivity = \"all\"\n\nfrom IPython.display import display, HTML\n\ndisplay(HTML(\"\"))\n\n# HTML('''\n#
''')\n\n\n# # Trends Dataset\n# \n# The trends dataset corresponds to data fetched daily from [Google Trends](https://www.google.com/trends/home/b/BR) (Category `Business`, geolocation `Brazil`) minute by minute from 5AM to 9PM since 2016-08-15.\n\n# In[2]:\n\nimport pdutils\n\ndef preprocess(dataset):\n # Sort by timestamp and rank\n dataset['timestamp'] = dataset.index\n dataset = dataset.sort_values(['timestamp', 'rank'])\n \n # Replace single quotes with double quotes\n dataset['articles'] = dataset['articles'].apply(lambda article: article.replace(\"'\", \"\\\"\"))\n \n return dataset\n\ndef load_dataset():\n return preprocess(pdutils.join_csv_from_dir('dataset/trends/daily', usecols=['timestamp', 'rank', 'title', 'entityNames', 'articles']))\n\n\n# Every row corresponds to a specific trend, i.e., entities, rank and related articles for the current timestamp.\n\n# In[3]:\n\n# Loading and preprocessing\ndataset = load_dataset()\n\n# Print shape and head\nprint(dataset.shape)\ndataset.head(10)\n\n\n# ### Dataset steps shape\n\n# In[4]:\n\nimport numpy as np\nimport collections\n\n# Group by minute\nsteps = dataset.groupby(dataset.index)\n\n# Number of trends by timestamp\nsteps_size = steps.size()\n\nprint(\"Total number of steps: {}\".format(steps.ngroups))\nprint(\"Max length {}\".format(np.max(steps_size)))\nprint(\"Min length {}\".format(np.min(steps_size)))\nprint(\"Mean {}\".format(np.mean(steps_size)))\nprint(\"Most common {}\".format(collections.Counter(steps_size).most_common(20)))\n\n\n# ### Trends granularity\n# \n# Compute length of equal steps windows through the dataset. \n\n# In[5]:\n\nimport pandas as pd\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nmatplotlib.style.use('ggplot')\nget_ipython().magic('matplotlib inline')\n\nlast_step_trends = None\ncounter = 1\nequal_steps = []\nfor timestamp, trends in steps:\n \n current_step_trends = trends.entityNames.values\n \n if last_step_trends is not None:\n if np.array_equal(last_step_trends, current_step_trends):\n counter += 1\n else:\n equal_steps.append(counter)\n counter = 1\n \n last_step_trends = current_step_trends\n\nequal_steps.append(counter)\n\nprint(\"Steps count {}\".format(np.sum(equal_steps))) \nprint(\"Min of equal steps window length {}\".format(np.min(equal_steps)))\nprint(\"Max of equal steps window length {}\".format(np.max(equal_steps)))\nprint(\"Mean of equal steps window length {}\".format(np.mean(equal_steps)))\nprint(\"Equal steps window length distribution {}\\n\".format(collections.Counter(equal_steps)))\n\n# fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(20, 10))\nplt.figure()\npd.Series(equal_steps).hist(bins=10, range=[0, 10])\n\n\n# ### Clean trends articles\n# \n# First we group trends by timestamp to join together trends from the same minute.\n\n# In[6]:\n\nimport pandas as pd\nimport json\nimport sys, traceback\n\nfrom pandas.io.json import json_normalize\n\ndef parse(article):\n \"\"\"\n Parse articles JSON array str into a DataFrame. Remove urls due to \n malformed ones.\n \n :param article: JSON array str\n :return: a DataFrame\n \"\"\"\n \n fixed_splits = []\n last_property = False\n for split in article.split('}, {'):\n url_property = ', \\\"{property}\\\": \\\"'.format(property='url')\n url_pos = split.find(url_property) \n first_property = url_pos == -1\n if first_property:\n url_property = '\\\"{property}\\\": \\\"'.format(property='url')\n url_pos = split.find(url_property) \n \n past_url_pos = url_pos + len(url_property) + 1\n \n fixed_split = split[0: url_pos]\n \n last_property = split.find('\\\",', past_url_pos) == -1\n if first_property:\n fixed_split += split[split.find('\\\",', url_pos + len(url_property)) + 3:]\n elif not last_property:\n # Url isn't last property\n fixed_split += split[split.find('\\\",', url_pos + len(url_property)) + 1:]\n \n fixed_splits.append(fixed_split)\n \n article = '}, {'.join(fixed_splits)\n \n if last_property:\n article += '}]'\n \n global current_fixed_article\n current_fixed_article = article\n \n return json_normalize(json.loads(article))\n\ndef concat_article_titles(articles):\n try:\n parsed = json_normalize(json.loads(articles))\n except ValueError:\n parsed = parse(articles)\n \n return ''.join(parsed['articleTitle'])\n\ndef X(group):\n trends = ', '.join(group['title'])\n articles = ''.join(group['articles'].apply(concat_article_titles))\n return pd.Series(dict(trends = trends, articles = articles))\n\n# Group by timestamp concatenating title and articles\nget_ipython().magic('time cleaned_dataset = dataset.groupby(dataset.index).apply(X)')\n\n\n# In[7]:\n\ncleaned_dataset.head()\n\n\n# In[8]:\n\ncleaned_dataset.to_csv('dataset/trends/trends.csv')\n\n\n# In[ ]:\n\n\n\n","sub_path":"ipynb/trends.py","file_name":"trends.py","file_ext":"py","file_size_in_byte":5502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"413159117","text":"class Solution:\r\n def removeKdigits(self, num: str, k: int) -> str:\r\n s=[]\r\n #s.append()\r\n for i in num:\r\n while len(s) and k>0 and int(i)0:\r\n s.pop()\r\n k-=1\r\n if len(s)==0:\r\n return '0'\r\n s=''.join(s)\r\n #print(s)\r\n return s\r\n\r\nnum=\"5337\"\r\nk=2\r\ns=Solution()\r\nprint(s.removeKdigits(num,k))\r\n","sub_path":"Math and Bit Magic/Remove_K_digits_to_make_smallest_number.py","file_name":"Remove_K_digits_to_make_smallest_number.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"128981298","text":"\nimport tensorflow as tf\nimport numpy as np\n\nfrom tensorflow.python.client import timeline\n\nnccl_ops = tf.load_op_library('nccl_ops.so')\n\nprint(dir(nccl_ops))\n\nNUM=4\n\ninits = []\nops = []\n\nsess_config = tf.ConfigProto(\n allow_soft_placement=False,\n device_count={'CPU': 1,\n 'GPU': 4},\n log_device_placement=False)\n\n\nwith tf.Session('', config=sess_config) as sess:\n # Manual Nccl all_reduce\n unique_id = nccl_ops.nccl_unique_id()\n for i in xrange(NUM):\n with tf.device('/gpu:%d' % i):\n handle = nccl_ops.nccl_comm_resource_handle_op(shared_name=\"comm%d\" % i)\n print(handle)\n comm = nccl_ops.nccl_init_comm(handle, unique_id, rank=i, N=NUM)\n #print(comm)\n inits.append(comm)\n\n #bcast = nccl_ops.nccl_broadcast(handle, val)\n #ops.append(bcast)\n val = tf.constant(np.arange(1<<20, dtype=np.float32))\n reduce = nccl_ops.nccl_all_reduce(handle, val)\n ops.append(reduce.op)\n\n # Broadcast pattern.\n #var = tf.Variable([1,2,3,4])\n var = tf.get_variable('var', shape=(1024,1024))\n towers = []\n for i in xrange(NUM):\n with tf.device('/gpu:%d' % i):\n op = var + 1\n towers.append(op)\n\n # Reduction pattern.\n addn = tf.add_n(towers)\n\n run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE,output_partition_graphs=True)\n tf.train.write_graph(sess.graph.as_graph_def(add_shapes=True), '/tmp', 'nccl.pbtxt')\n\n print('Init...')\n sess.run(tf.initialize_all_variables())\n\n print('AddN')\n runoptions = tf.RunOptions()\n run_metadata = tf.RunMetadata()\n sess.run(addn, options=run_options, run_metadata=run_metadata)\n tl = timeline.Timeline(run_metadata.step_stats)\n trace = tl.generate_chrome_trace_format()\n with open('addn.rmd.proto', 'w') as f:\n f.write(run_metadata.SerializeToString())\n with open('addn.timeline.json', 'w') as f:\n f.write(trace)\n #stop\n\n print('Nccl Init')\n sess.run(inits)\n\n print('Broadcast')\n run_metadata = tf.RunMetadata()\n sess.run(towers, options=run_options, run_metadata=run_metadata)\n tl = timeline.Timeline(run_metadata.step_stats)\n with open('broadcast.rmd.proto', 'w') as f:\n f.write(run_metadata.SerializeToString())\n with open('braodcast.timeline.json', 'w') as f:\n f.write(trace)\n\n print('AllReduce...')\n run_metadata = tf.RunMetadata()\n vals = sess.run(ops, options=run_options, run_metadata=run_metadata)\n vals = sess.run(ops)\n vals = sess.run(ops)\n vals = sess.run(ops)\n tl = timeline.Timeline(run_metadata.step_stats)\n with open('allreduce.rmd.proto', 'w') as f:\n f.write(run_metadata.SerializeToString())\n with open('allreduce.timeline.json', 'w') as f:\n f.write(trace)\n print(vals)\n","sub_path":"tensorflow/core/user_ops/nccl_ops_test.py","file_name":"nccl_ops_test.py","file_ext":"py","file_size_in_byte":2674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"356209302","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nModule to plot images over geographical data, based on coordinates.\n\"\"\"\n\nimport shapefile as shp\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom pyproj import Proj\nfrom matplotlib.offsetbox import OffsetImage, AnnotationBbox\nimport os\n\ndef plotMap(points=[], x_lim = None, y_lim = None, figsize = (9,7), \n shp_path=\"gmg\"+os.sep+\"recursos\"+os.sep+\"Concellos\"+os.sep+\"Concellos_IGN\",\n img_path=\"gmg\"+os.sep+\"recursos\"+os.sep+\"weatherIcons\"+os.sep):\n '''\n Plot map with lim coordinates and images in the designated points.\n '''\n sns.set(style=\"whitegrid\", palette=\"pastel\", color_codes=True)\n sns.mpl.rc(\"figure\", figsize=(9,7))\n\n print(shp_path)\n print(os.path.abspath(shp_path))\n sf = shp.Reader(shp_path)\n\n print(\"Shape size: \"+str(len(sf)))\n print(\"Shaperecords size: \"+str(len(sf.shapeRecords())))\n print(\"Points size: \"+str(len(points)))\t\n \n fig, ax = plt.subplots(figsize=figsize)\n\n for shape in sf.shapeRecords():\n x = [i[0] for i in shape.shape.points[:]]\n y = [i[1] for i in shape.shape.points[:]]\n\n ax.plot(x, y, 'k', color=\"grey\")\n\n if (x_lim != None) & (y_lim != None): \n ax.xlim(x_lim)\n ax.ylim(y_lim)\n\n # Convert coordinates to UTM projection\n myProj = Proj(\"+proj=utm +zone=29K, +ellps=WGS84 +datum=WGS84 +units=m +no_defs\")\n\n # Show selected image in the designated coordinates\n for p in points:\n UTMx, UTMy = myProj(p[1][0], p[1][1])\n\n print(str(UTMx) + \" - \" + str(UTMy))\n \n img_file = img_path+\"default.png\"\n if os.path.exists(img_path+str(p[0])+\".png\"):\n img_file = img_path+str(p[0])+\".png\"\n else:\n print(\"Not found: \"+img_path+str(p[0])+\".png\")\n\n ab = AnnotationBbox(OffsetImage(plt.imread(img_file)), (UTMx, UTMy), frameon=False)\n ax.add_artist(ab)\n fig.savefig(\"prueba.png\") \n\ndef main():\n # Example\n # Using as coordinates: (longitude, latitude)\n plotMap(points=[(102,(-8.361641-0.1, 42.428012+0.05)),\n (113,(-8.661641-0.1, 42.828012+0.05)),\n (401,(-7.1397174,42.0609045))])\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"ServiciosWeb/gmg.py","file_name":"gmg.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"118984895","text":"import glob\nimport gzip\nfrom helper import *\nimport io\nimport os\nimport re\nimport yaml\nfrom yaml import load\nfrom yaml import Loader\nimport zipfile\nimport sqlite3\nfrom sqlite3 import Error\nimport atexit\nimport html\n\ndef get_settings():\n return load_yaml_dict(read_file(\"/Settings.yaml\"))\n\ndef get_root_dir_path():\n return \"/course\"\n\ndef get_course_dir_path(course):\n return get_root_dir_path() + f\"/{course}/\"\n\nclass Content:\n __DB_LOCATION = get_settings()[\"db_location\"]\n\n def __init__(self):\n # This should enable auto-commit.\n self.conn = sqlite3.connect(self.__DB_LOCATION, isolation_level=None, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)\n self.conn.row_factory = sqlite3.Row\n self.c = self.conn.cursor()\n self.c.execute(\"PRAGMA foreign_keys=ON\")\n\n atexit.register(self.close)\n\n def close(self):\n self.c.close()\n self.conn.close()\n\n def create_table(self, create_table_sql):\n self.c.execute(create_table_sql)\n\n def create_sqlite_tables(self):\n create_users_table = \"\"\" CREATE TABLE IF NOT EXISTS users (\n user_id text PRIMARY KEY\n ); \"\"\"\n\n create_permissions_table = \"\"\" CREATE TABLE IF NOT EXISTS permissions (\n user_id text NOT NULL,\n role text NOT NULL,\n FOREIGN KEY (user_id) REFERENCES users (user_id) ON DELETE CASCADE ON UPDATE CASCADE,\n PRIMARY KEY (user_id)\n ); \"\"\"\n\n create_courses_table = \"\"\" CREATE TABLE IF NOT EXISTS courses (\n course_id text NOT NULL,\n title text NOT NULL UNIQUE,\n introduction text,\n visible integer NOT NULL,\n date_created timestamp NOT NULL,\n date_updated timestamp,\n PRIMARY KEY (course_id)\n ); \"\"\"\n\n create_assignments_table = \"\"\" CREATE TABLE IF NOT EXISTS assignments (\n course_id text NOT NULL,\n assignment_id text NOT NULL,\n title text NOT NULL UNIQUE,\n introduction text,\n visible integer NOT NULL,\n date_created timestamp NOT NULL,\n date_updated timestamp,\n FOREIGN KEY (course_id) REFERENCES courses (course_id) ON DELETE CASCADE ON UPDATE CASCADE,\n PRIMARY KEY (assignment_id)\n ); \"\"\"\n\n create_problems_table = \"\"\" CREATE TABLE IF NOT EXISTS problems (\n course_id text NOT NULL,\n assignment_id text NOT NULL,\n problem_id text NOT NULL,\n title text NOT NULL UNIQUE,\n visible integer NOT NULL,\n answer_code text NOT NULL,\n answer_description text,\n credit text,\n data_url text,\n data_file_name text,\n data_contents text,\n back_end text NOT NULL,\n expected_output text NOT NULL,\n instructions text NOT NULL,\n output_type text NOT NULL,\n show_answer integer NOT NULL,\n show_expected integer NOT NULL,\n show_test_code integer NOT NULL,\n test_code text,\n date_created timestamp NOT NULL,\n date_updated timestamp,\n FOREIGN KEY (course_id) REFERENCES courses (course_id) ON DELETE CASCADE ON UPDATE CASCADE,\n FOREIGN KEY (assignment_id) REFERENCES assignments (assignment_id) ON DELETE CASCADE ON UPDATE CASCADE,\n PRIMARY KEY (problem_id)\n ); \"\"\"\n\n create_submissions_table = \"\"\" CREATE TABLE IF NOT EXISTS submissions (\n course_id text NOT NULL,\n assignment_id text NOT NULL,\n problem_id text NOT NULL,\n user_id text NOT NULL,\n submission_id integer NOT NULL,\n code text NOT NULL,\n code_output text NOT NULL,\n passed integer NOT NULL,\n date timestamp NOT NULL,\n error_occurred integer NOT NULL,\n FOREIGN KEY (course_id) REFERENCES courses (course_id) ON DELETE CASCADE,\n FOREIGN KEY (assignment_id) REFERENCES assignments (assignment_id) ON DELETE CASCADE,\n FOREIGN KEY (problem_id) REFERENCES problems (problem_id) ON DELETE CASCADE,\n FOREIGN KEY (user_id) REFERENCES users(user_id) ON DELETE CASCADE,\n PRIMARY KEY (course_id, assignment_id, problem_id, user_id, submission_id)\n ); \"\"\"\n\n if self.conn is not None:\n # self.delete_table(\"submissions\")\n # self.delete_table(\"problems\")\n # self.delete_table(\"assignments\")\n # self.delete_table(\"courses\")\n\n self.create_table(create_users_table)\n self.create_table(create_permissions_table)\n self.create_table(create_courses_table)\n self.create_table(create_assignments_table)\n self.create_table(create_problems_table)\n self.create_table(create_submissions_table)\n\n else:\n print(\"Error! Cannot create the database connection.\")\n\n def check_user_exists(self, user_id):\n sql = 'SELECT user_id FROM users WHERE user_id=?'\n self.c.execute(sql, (user_id,))\n exists = self.c.fetchone()\n if exists is None:\n return False\n return True\n\n def check_role_exists(self, user_id):\n sql = 'SELECT role FROM permissions WHERE user_id=?'\n self.c.execute(sql, (user_id,))\n exists = self.c.fetchone()\n if exists is None:\n return False\n return True\n\n def get_role(self, user_id):\n sql = 'SELECT role FROM permissions WHERE user_id=?'\n self.c.execute(sql, (str(user_id),))\n row = self.c.fetchone()\n return row[\"role\"]\n\n def add_user(self, user_id):\n sql = 'INSERT INTO users (user_id) VALUES (?)'\n self.c.execute(sql, (user_id,))\n\n def add_row_permissions(self, user_id, role):\n sql = 'INSERT INTO permissions (user_id, role) VALUES (?, ?)'\n self.c.execute(sql, (user_id, role,))\n\n def print_tables(self):\n sql = \"SELECT name FROM sqlite_master WHERE type='table'\"\n tables = self.c.execute(sql)\n for table in tables:\n print(table[0])\n\n def print_rows(self, table):\n sql = 'SELECT * FROM ' + table\n rows = self.c.execute(sql)\n for row in rows:\n print(tuple(row))\n\n# def check_course_exists(self, course):\n# sql = 'SELECT * FROM courses WHERE course_id=?'\n# self.c.execute(sql, (course,))\n# return self.c.fetchone()\n\n# def check_assignment_exists(self, assignment):\n# sql = 'SELECT * FROM assignments WHERE assignment_id=?'\n# self.c.execute(sql, (assignment,))\n# return self.c.fetchone()\n\n# def check_problem_exists(self, problem):\n# sql = 'SELECT * FROM problems WHERE problem_id=?'\n# self.c.execute(sql, (problem,))\n# return self.c.fetchone()\n\n def get_course_ids(self):\n course_ids = []\n sql = 'SELECT course_id FROM courses'\n self.c.execute(sql)\n course_ids = [course[0] for course in self.c.fetchall()]\n return course_ids\n\n def get_assignment_ids(self, course_id):\n assignment_ids = []\n sql = 'SELECT assignment_id FROM assignments WHERE course_id=?'\n self.c.execute(sql, (str(course_id),))\n assignment_ids = [assignment[0] for assignment in self.c.fetchall()]\n return assignment_ids\n\n def get_problem_ids(self, course_id, assignment_id):\n problem_ids = []\n sql = 'SELECT problem_id FROM problems WHERE assignment_id=?'\n self.c.execute(sql, (str(assignment_id),))\n problem_ids = [problem[0] for problem in self.c.fetchall()]\n return problem_ids\n\n def get_courses(self, show_hidden=True):\n courses = []\n course_ids = self.get_course_ids()\n\n for course_id in course_ids:\n course_basics = self.get_course_basics(course_id)\n if course_basics[\"visible\"] or show_hidden:\n courses.append([course_id, course_basics])\n\n return self.sort_nested_list(courses)\n\n def get_course_title_from_id(self, course_id, show_hidden=True):\n sql = 'SELECT title FROM courses WHERE course_id=?'\n self.c.execute(sql, (str(course_id),))\n row = self.c.fetchone()\n return row[\"title\"]\n\n def get_assignment_title_from_id(self, assignment_id, show_hidden=True):\n sql = 'SELECT title FROM assignments WHERE assignment_id=?'\n self.c.execute(sql, (str(assignment_id),))\n row = self.c.fetchone()\n return row[\"title\"]\n\n def get_assignments(self, course_id, show_hidden=True):\n assignments = []\n assignment_ids = self.get_assignment_ids(course_id)\n\n for assignment_id in assignment_ids:\n assignment_basics = self.get_assignment_basics(course_id, assignment_id)\n if assignment_basics[\"visible\"] or show_hidden:\n assignments.append([assignment_id, assignment_basics])\n\n return self.sort_nested_list(assignments)\n\n def get_problems(self, course_id, assignment_id, show_hidden=True):\n problems = []\n problem_ids = self.get_problem_ids(course_id, assignment_id)\n\n for problem_id in problem_ids:\n problem_basics = self.get_problem_basics(course_id, assignment_id, problem_id)\n if problem_basics[\"visible\"] or show_hidden:\n problems.append([problem_id, problem_basics, course_id, assignment_id])\n\n return self.sort_nested_list(problems)\n\n def get_submissions_basic(self, course_id, assignment_id, problem_id, user_id):\n submissions = []\n sql = 'SELECT submission_id, date, passed FROM submissions WHERE course_id=? AND assignment_id=? AND problem_id=? AND user_id=?'\n self.c.execute(sql, (str(course_id), str(assignment_id), str(problem_id), str(user_id),))\n for submission in self.c.fetchall():\n submissions.append([submission[\"submission_id\"], submission[\"date\"].strftime(\"%m/%d/%Y, %I:%M:%S %p\"), submission[\"passed\"]])\n\n if submissions == []:\n return submissions\n else:\n return sorted(submissions, key = lambda x: x[0], reverse=True)\n\n def get_course_basics(self, course_id):\n if not course_id:\n course_id = create_id(self.get_courses())\n\n sql = '''SELECT course_id, title, visible\n FROM courses\n WHERE course_id=?'''\n self.c.execute(sql, (str(course_id),))\n row = self.c.fetchone()\n if row is None:\n return {\"id\": course_id, \"title\": \"\", \"visible\": True, \"exists\": False}\n else:\n return {\"id\": row[\"course_id\"], \"title\": row[\"title\"], \"visible\": bool(row[\"visible\"]), \"exists\": True}\n\n def get_assignment_basics(self, course_id, assignment_id):\n if not assignment_id:\n assignment_id = create_id(self.get_assignments(course_id))\n\n course_basics = self.get_course_basics(course_id)\n\n sql = 'SELECT assignment_id, title, visible FROM assignments WHERE assignment_id = ?'\n self.c.execute(sql, (str(assignment_id),))\n row = self.c.fetchone()\n if row is None:\n return {\"id\": assignment_id, \"title\": \"\", \"visible\": True, \"exists\": False, \"course\": course_basics}\n else:\n return {\"id\": row[\"assignment_id\"], \"title\": row[\"title\"], \"visible\": bool(row[\"visible\"]), \"exists\": True}\n\n def get_problem_basics(self, course_id, assignment_id, problem_id):\n if not problem_id:\n problem_id = create_id(self.get_problems(course_id, assignment_id))\n\n assignment_basics = self.get_assignment_basics(course_id, assignment_id)\n\n sql = 'SELECT problem_id, title, visible FROM problems WHERE problem_id = ?'\n self.c.execute(sql, (str(problem_id),))\n row = self.c.fetchone()\n if row is None:\n return {\"id\": problem_id, \"title\": \"\", \"visible\": True, \"exists\": False, \"assignment\": assignment_basics}\n else:\n return {\"id\": row[\"problem_id\"], \"title\": row[\"title\"], \"visible\": bool(row[\"visible\"]), \"exists\": True, \"assignment\": assignment_basics}\n\n def get_next_prev_problems(self, course, assignment, problem, problems):\n prev_problem = None\n next_problem = None\n\n if len(problems) > 0 and problem:\n this_problem = [i for i in range(len(problems)) if problems[i][0] == problem]\n if len(this_problem) > 0:\n this_problem_index = [i for i in range(len(problems)) if problems[i][0] == problem][0]\n\n if len(problems) >= 2 and this_problem_index != 0:\n prev_problem = problems[this_problem_index - 1][1]\n\n if len(problems) >= 2 and this_problem_index != (len(problems) - 1):\n next_problem = problems[this_problem_index + 1][1]\n\n return {\"previous\": prev_problem, \"next\": next_problem}\n\n def get_num_submissions(self, course, assignment, problem, user):\n sql = 'SELECT COUNT(*) FROM submissions WHERE problem_id=? AND user_id=?'\n num_submissions = self.c.execute(sql, (problem, user,)).fetchone()[0]\n return num_submissions\n \n def get_user_total_submissions(self, user):\n sql = 'SELECT COUNT(*) FROM submissions WHERE user_id=?'\n num_submissions = self.c.execute(sql, (user,)).fetchone()[0]\n return num_submissions\n\n def get_next_submission_id(self, course, assignment, problem, user):\n return self.get_num_submissions(course, assignment, problem, user) + 1\n\n def get_last_submission(self, course, assignment, problem, user):\n last_submission_id = self.get_num_submissions(course, assignment, problem, user)\n sql = ''' SELECT code, code_output, passed, date, error_occurred\n FROM submissions WHERE course_id=? AND assignment_id=? AND problem_id=? and user_id=? AND submission_id=? '''\n self.c.execute(sql, (course, assignment, problem, user, last_submission_id,))\n row = self.c.fetchone()\n\n last_submission = {\"id\": last_submission_id, \"code\": row[\"code\"], \"code_output\": row[\"code_output\"], \"passed\": row[\"passed\"], \"date\": row[\"date\"], \"error_occurred\": row[\"error_occurred\"], \"exists\": True}\n\n return last_submission\n\n def get_submission_info(self, course, assignment, problem, user, submission):\n sql = ''' SELECT code, code_output, passed, date, error_occurred\n FROM submissions WHERE course_id=? AND assignment_id=? AND problem_id=? AND user_id=? AND submission_id=? '''\n self.c.execute(sql, (course, assignment, problem, user, submission,))\n row = self.c.fetchone()\n\n submission_dict = {\"id\": submission, \"code\": row[\"code\"], \"code_output\": row[\"code_output\"], \"passed\": row[\"passed\"], \"date\": row[\"date\"].strftime(\"%m/%d/%Y, %I:%M:%S %p\"), \"error_occurred\": row[\"error_occurred\"], \"exists\": True}\n\n return submission_dict\n\n def get_course_details(self, course, format_output=False):\n course_dict = {\"introduction\": \"\"}\n\n sql = 'SELECT introduction FROM courses WHERE course_id = ?'\n self.c.execute(sql, (course,))\n row = self.c.fetchone()\n if row is None:\n return course_dict\n else:\n course_dict = {\"introduction\": row[\"introduction\"]}\n if format_output:\n course_dict[\"introduction\"] = convert_markdown_to_html(course_dict[\"introduction\"])\n\n return course_dict\n\n def get_assignment_details(self, course, assignment, format_output=False):\n assignment_dict = {\"introduction\": \"\"}\n\n sql = 'SELECT introduction FROM assignments WHERE assignment_id = ?'\n self.c.execute(sql, (assignment,))\n row = self.c.fetchone()\n if row is None:\n return assignment_dict\n else:\n assignment_dict = {\"introduction\": row[\"introduction\"]}\n if format_output:\n assignment_dict[\"introduction\"] = convert_markdown_to_html(assignment_dict[\"introduction\"])\n\n return assignment_dict\n\n def get_problem_details(self, course, assignment, problem, format_content=False):\n problem_dict = {}\n\n sql = '''SELECT instructions, back_end, output_type, answer_code, answer_description, test_code, credit, show_expected, show_test_code, show_answer, expected_output, data_url, data_file_name, data_contents\n FROM problems WHERE problem_id = ?'''\n self.c.execute(sql, (problem,))\n row = self.c.fetchone()\n\n if row is None:\n return {\"instructions\": \"\", \"back_end\": \"python\",\n \"output_type\": \"txt\", \"answer_code\": \"\", \"answer_description\": \"\", \"test_code\": \"\",\n \"credit\": \"\", \"show_expected\": True, \"show_test_code\": True, \"show_answer\": True,\n \"expected_output\": \"\", \"data_url\": \"\", \"data_file_name\": \"\", \"data_contents\": \"\"}\n else:\n problem_dict = {\"instructions\": row[\"instructions\"], \"back_end\": row[\"back_end\"], \"output_type\": row[\"output_type\"], \"answer_code\": row[\"answer_code\"], \"answer_description\": row[\"answer_description\"], \"test_code\": row[\"test_code\"], \"credit\": row[\"credit\"], \"show_expected\": row[\"show_expected\"], \"show_test_code\": row[\"show_test_code\"], \"show_answer\": row[\"show_answer\"], \"expected_output\": row[\"expected_output\"], \"data_url\": row[\"data_url\"], \"data_file_name\": row[\"data_file_name\"], \"data_contents\": row[\"data_contents\"]}\n\n if format_content:\n problem_dict[\"instructions\"] = convert_markdown_to_html(problem_dict[\"instructions\"])\n problem_dict[\"credit\"] = convert_markdown_to_html(problem_dict[\"credit\"])\n\n if \"answer_description\" not in problem_dict:\n problem_dict[\"answer_description\"] = \"\"\n else:\n problem_dict[\"answer_description\"] = convert_markdown_to_html(problem_dict[\"answer_description\"])\n\n return problem_dict\n\n def course_ids_to_titles(self):\n course_dict = {}\n sql = 'SELECT course_id, title FROM courses'\n self.c.execute(sql)\n for course in self.c.fetchall():\n course_dict[course[\"course_id\"]] = course[\"title\"]\n return course_dict\n\n def assignment_ids_to_titles(self):\n assignment_dict = {}\n sql = 'SELECT assignment_id, title FROM assignments'\n self.c.execute(sql)\n for assignment in self.c.fetchall():\n assignment_dict[assignment[\"assignment_id\"]] = assignment[\"title\"]\n return assignment_dict\n\n def problem_ids_to_titles(self):\n problem_dict = {}\n sql = 'SELECT problem_id, title FROM problems'\n self.c.execute(sql)\n for problem in self.c.fetchall():\n problem_dict[problem[\"problem_id\"]] = problem[\"title\"]\n return problem_dict\n\n def get_student_courses(self, student_id):\n courses = []\n sql = 'SELECT courses.course_id, courses.title, submissions.user_id FROM courses INNER JOIN submissions ON courses.course_id=submissions.course_id WHERE submissions.user_id=?' \n self.c.execute(sql, (str(student_id),))\n for course in self.c.fetchall():\n courses.append([course[\"title\"], course[\"course_id\"]])\n return courses\n\n def get_student_assignments(self, student_id):\n assignments = []\n sql = 'SELECT assignments.course_id, assignments.assignment_id, assignments.title FROM assignments INNER JOIN submissions ON assignments.assignment_id=submissions.assignment_id WHERE submissions.user_id=?'\n self.c.execute(sql, (str(student_id),))\n for assignment in self.c.fetchall():\n assignments.append([assignment[\"title\"], assignment[\"course_id\"], assignment[\"assignment_id\"]])\n return assignments\n\n def get_student_problem_status(self, problem_id, student_id):\n passed = False\n sql = 'SELECT passed FROM submissions WHERE problem_id=? AND user_id=?'\n self.c.execute(sql, (problem_id, student_id,))\n for submission in self.c.fetchall():\n if submission[\"passed\"]:\n passed = True\n return passed\n\n def get_student_problems(self, student_id): #returns list of problems a certain student has made submissions for, also whether the student has passed the problem and number of submissions student has made\n problems = []\n sql = 'SELECT DISTINCT problems.course_id, problems.assignment_id, problems.problem_id, problems.title FROM problems INNER JOIN submissions ON problems.problem_id=submissions.problem_id WHERE submissions.user_id=?'\n self.c.execute(sql, (str(student_id),))\n for problem in self.c.fetchall():\n problems.append([problem[\"title\"], problem[\"course_id\"], problem[\"assignment_id\"], problem[\"problem_id\"]])\n for problem in problems:\n num_submissions = self.get_num_submissions(problem[1], problem[2], problem[3], student_id)\n passed = self.get_student_problem_status(problem[3], student_id)\n problem.append(num_submissions)\n problem.append(passed)\n\n return problems\n\n def get_log_table_contents(self, file_path, year=\"No filter\", month=\"No filter\", day=\"No filter\"):\n new_dict = {}\n line_num = 1\n with gzip.open(file_path) as read_file:\n header = read_file.readline()\n for line in read_file:\n line_items = line.decode().rstrip(\"\\n\").split(\"\\t\")\n line_items = [line_items[0][:2], line_items[0][2:4], line_items[0][4:6], line_items[0][6:]] + line_items[1:]\n\n new_dict[line_num] = line_items\n line_num += 1\n\n # Filter by date.\n year_dict = {}\n month_dict = {}\n day_dict = {}\n\n for key, line in new_dict.items():\n if year == \"No filter\" or line[0] == year:\n year_dict[key] = line\n for key, line in year_dict.items():\n if month == \"No filter\" or line[1] == month:\n month_dict[key] = line\n for key, line in month_dict.items():\n if day == \"No filter\" or line[2] == day:\n day_dict[key] = line\n\n return day_dict\n\n def get_root_dirs_to_log(self):\n root_dirs_to_log = set([\"home\", \"course\", \"assignment\", \"problem\", \"check_problem\", \"edit_course\", \"edit_assignment\", \"edit_problem\", \"delete_course\", \"delete_assignment\", \"delete_problem\", \"view_answer\", \"import_course\", \"export_course\"])\n return root_dirs_to_log\n\n def sort_nested_list(self, nested_list, key=\"title\"):\n l_dict = {}\n for row in nested_list:\n l_dict[row[1][key]] = row\n\n sorted_list = []\n for key in sort_nicely(l_dict):\n sorted_list.append(l_dict[key])\n\n return sorted_list\n\n def has_duplicate_title(self, entries, this_entry, proposed_title):\n for entry in entries:\n if entry[0] != this_entry and entry[1][\"title\"] == proposed_title:\n return True\n return False\n\n def save_course(self, course_basics, course_details):\n if course_basics[\"exists\"]:\n sql = '''UPDATE courses\n SET title = ?, visible = ?, introduction = ?, date_updated = ?\n WHERE course_id = ?'''\n self.c.execute(sql, [course_basics[\"title\"], course_basics[\"visible\"], course_details[\"introduction\"], datetime.now(), course_basics[\"id\"]])\n else:\n sql = '''INSERT INTO courses (course_id, title, visible, introduction, date_created)\n VALUES (?, ?, ?, ?, ?)'''\n self.c.execute(sql, [course_basics[\"id\"], course_basics[\"title\"], course_basics[\"visible\"], course_details[\"introduction\"], datetime.now()])\n\n def save_assignment(self, course, assignment_basics, assignment_details):\n if assignment_basics[\"exists\"]:\n sql = '''UPDATE assignments\n SET title = ?, visible = ?, introduction = ?, date_updated = ?\n WHERE course_id = ? AND assignment_id = ?'''\n self.c.execute(sql, [assignment_basics[\"title\"], assignment_basics[\"visible\"], assignment_details[\"introduction\"], datetime.now(), course, assignment_basics[\"id\"]])\n else:\n sql = '''INSERT INTO assignments (course_id, assignment_id, title, visible, introduction, date_created)\n VALUES (?, ?, ?, ?, ?, ?)'''\n self.c.execute(sql, [course, assignment_basics[\"id\"], assignment_basics[\"title\"], assignment_basics[\"visible\"], assignment_details[\"introduction\"], datetime.now()])\n\n def save_problem(self, course, assignment, problem_basics, problem_details):\n if problem_basics[\"exists\"]:\n sql = '''UPDATE problems\n SET course_id = ?, assignment_id = ?, title = ?, visible = ?,\n answer_code = ?, answer_description = ?, credit = ?, data_url = ?, data_file_name = ?,\n data_contents = ?, back_end = ?, expected_output = ?, instructions = ?,\n output_type = ?, show_answer = ?, show_expected = ?, show_test_code = ?, test_code = ?, date_updated = ?\n WHERE problem_id = ?'''\n self.c.execute(sql, [course, assignment, problem_basics[\"title\"], problem_basics[\"visible\"], str(problem_details[\"answer_code\"]), problem_details[\"answer_description\"], problem_details[\"credit\"], problem_details[\"data_url\"], problem_details[\"data_file_name\"], problem_details[\"data_contents\"], problem_details[\"back_end\"], problem_details[\"expected_output\"], problem_details[\"instructions\"], problem_details[\"output_type\"], problem_details[\"show_answer\"], problem_details[\"show_expected\"], problem_details[\"show_test_code\"], problem_details[\"test_code\"], datetime.now(), problem_basics[\"id\"]])\n else:\n sql = '''INSERT INTO problems (course_id, assignment_id, problem_id, title, visible, answer_code, answer_description, credit, data_url, data_file_name, data_contents, back_end, expected_output, instructions, output_type, show_answer, show_expected, show_test_code, test_code, date_created)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'''\n self.c.execute(sql, [course, assignment, problem_basics[\"id\"], problem_basics[\"title\"], problem_basics[\"visible\"], str(problem_details[\"answer_code\"]), problem_details[\"answer_description\"], problem_details[\"credit\"], problem_details[\"data_url\"], problem_details[\"data_file_name\"], problem_details[\"data_contents\"], problem_details[\"back_end\"], problem_details[\"expected_output\"], problem_details[\"instructions\"], problem_details[\"output_type\"], problem_details[\"show_answer\"], problem_details[\"show_expected\"], problem_details[\"show_test_code\"], problem_details[\"test_code\"], datetime.now()])\n \n self.print_rows(\"problems\")\n\n def save_submission(self, course, assignment, problem, user, code, code_output, passed, error_occurred):\n submission_id = self.get_next_submission_id(course, assignment, problem, user)\n sql = ''' INSERT INTO submissions (course_id, assignment_id, problem_id, user_id, submission_id, code, code_output, passed, date, error_occurred)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'''\n self.c.execute(sql, [course, assignment, problem, user, submission_id, code, code_output, passed, datetime.now(), error_occurred])\n\n return submission_id\n\n def update_user(self, old_id, new_id):\n sql = 'UPDATE users SET user_id=? WHERE user_id'\n self.c.execute(sql, (new_id, old_id,))\n\n def update_role(self, user_id, new_role):\n sql = 'UPDATE users SET role=? WHERE user_id=?'\n self.c.execute(sql, (new_role, user_id,))\n\n# def update_course(self, course_id, col_name, new_value):\n# sql = 'UPDATE courses SET ' + col_name + '=? WHERE course_id=?'\n# self.c.execute(sql, (new_value, course_id,))\n\n# def update_assignment(self, assignment_id, col_name, new_value):\n# sql = 'UPDATE assignments SET ' + col_name + '=? WHERE assignment_id=?'\n# self.c.execute(sql, (new_value, assignment_id,))\n\n# def update_problem(self, problem_id, col_name, new_value):\n# sql = 'UPDATE problems SET ' + col_name + '=? WHERE problem_id=?'\n# self.c.execute(sql, (new_value, problem_id,))\n\n def delete_rows_with_value(self, table, col_name, value):\n sql = 'DELETE FROM ' + table + ' WHERE ' + col_name + '=?'\n self.c.execute(sql, (value,))\n\n def delete_all_rows(self, table):\n sql = 'DELETE FROM ' + table\n self.c.execute(sql)\n\n def delete_table(self, table):\n sql = 'DROP TABLE ' + table\n self.c.execute(sql)\n\n def delete_problem(self, problem_basics):\n self.delete_rows_with_value(\"problems\", \"problem_id\", problem_basics[\"id\"])\n self.delete_problem_submissions(problem_basics)\n\n def delete_assignment(self, assignment_basics):\n self.delete_rows_with_value(\"assignments\", \"assignment_id\", assignment_basics[\"id\"])\n self.delete_assignment_submissions(assignment_basics)\n\n def delete_course(self, course_basics):\n self.delete_rows_with_value(\"courses\", \"course_id\", course_basics[\"id\"])\n self.delete_course_submissions(course_basics)\n\n def delete_course_submissions(self, course_basics):\n self.delete_rows_with_value(\"submissions\", \"course_id\", course_basics[\"id\"])\n\n def delete_assignment_submissions(self, assignment_basics):\n self.delete_rows_with_value(\"submissions\", \"assignment_id\", assignment_basics[\"id\"])\n\n def delete_problem_submissions(self, problem_basics):\n self.delete_rows_with_value(\"submissions\", \"problem_id\", problem_basics[\"id\"])\n","sub_path":"front_end/content.py","file_name":"content.py","file_ext":"py","file_size_in_byte":31778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"495788194","text":"import logging\nimport unittest\n\ndef run():\n suite = unittest.TestLoader().discover(\n start_dir='.',\n pattern='*_test.py')\n\n unittest.TextTestRunner(verbosity=1).run(suite)\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.ERROR)\n run()","sub_path":"traad/test/unittests.py","file_name":"unittests.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"550174844","text":"import threading\n\nimport tensorflow as tf\nimport random\nimport numpy as np\nfrom agent import Agent\nfrom envs.bandit_envs import TwoArms, ElevenArms\nfrom network import ACNetwork\nfrom baseline import RandomAgent\nimport flags\nimport os\n\nFLAGS = tf.app.flags.FLAGS\n\n\ndef recreate_directory_structure():\n if tf.gfile.Exists(FLAGS.results_val_file):\n os.remove(FLAGS.results_val_file)\n\n if not tf.gfile.Exists(FLAGS.checkpoint_dir):\n tf.gfile.MakeDirs(FLAGS.checkpoint_dir)\n else:\n if not FLAGS.resume and FLAGS.train:\n tf.gfile.DeleteRecursively(FLAGS.checkpoint_dir)\n tf.gfile.MakeDirs(FLAGS.checkpoint_dir)\n\n if not tf.gfile.Exists(FLAGS.frames_dir):\n tf.gfile.MakeDirs(FLAGS.frames_dir)\n else:\n if not FLAGS.resume and FLAGS.train:\n tf.gfile.DeleteRecursively(FLAGS.frames_dir)\n tf.gfile.MakeDirs(FLAGS.frames_dir)\n\n if not tf.gfile.Exists(FLAGS.summaries_dir):\n tf.gfile.MakeDirs(FLAGS.summaries_dir)\n else:\n if not FLAGS.resume and FLAGS.train:\n tf.gfile.DeleteRecursively(FLAGS.summaries_dir)\n tf.gfile.MakeDirs(FLAGS.summaries_dir)\n\n\ndef recreate_subdirectory_structure(settings):\n if not tf.gfile.Exists(settings[\"checkpoint_dir\"]):\n tf.gfile.MakeDirs(settings[\"checkpoint_dir\"])\n else:\n if not FLAGS.resume and FLAGS.train:\n tf.gfile.DeleteRecursively(settings[\"checkpoint_dir\"])\n tf.gfile.MakeDirs(settings[\"checkpoint_dir\"])\n\n if not tf.gfile.Exists(settings[\"frames_dir\"]):\n tf.gfile.MakeDirs(settings[\"frames_dir\"])\n else:\n if not FLAGS.resume and FLAGS.train:\n tf.gfile.DeleteRecursively(settings[\"frames_dir\"])\n tf.gfile.MakeDirs(settings[\"frames_dir\"])\n\n if not tf.gfile.Exists(settings[\"summaries_dir\"]):\n tf.gfile.MakeDirs(settings[\"summaries_dir\"])\n else:\n if not FLAGS.resume and FLAGS.train:\n tf.gfile.DeleteRecursively(settings[\"summaries_dir\"])\n tf.gfile.MakeDirs(settings[\"summaries_dir\"])\n\n\ndef evaluate_one_test():\n\n # test_envs = TwoArms.get_envs(FLAGS.game, FLAGS.nb_test_episodes)\n #\n # checkpoint_dir = os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name)\n # summaries_dir = os.path.join(FLAGS.summaries_dir, FLAGS.model_name)\n # frames_dir = os.path.join(FLAGS.frames_dir, FLAGS.model_name)\n #\n # settings = {\"lr\": FLAGS.lr,\n # \"gamma\": FLAGS.gamma,\n # \"game\": FLAGS.game,\n # \"model_name\": FLAGS.model_name,\n # \"checkpoint_dir\": checkpoint_dir,\n # \"summaries_dir\": summaries_dir,\n # \"frames_dir\": frames_dir,\n # \"load_from\": os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name),\n # \"envs\": test_envs,\n # \"mode\": \"evaluate_once\"}\n #\n # run(settings)\n for _ in range(5):\n model_name = \"best_{}__lr_{}__gamma_{}\".format(FLAGS.game, FLAGS.lr, FLAGS.gamma)\n load_from_model_name = \"d_{}__lr_{}__gamma_{}\".format(FLAGS.best_model_game, FLAGS.lr, FLAGS.gamma)\n print(load_from_model_name)\n checkpoint_dir = os.path.join(FLAGS.checkpoint_dir, model_name)\n summaries_dir = os.path.join(FLAGS.summaries_dir, model_name)\n frames_dir = os.path.join(FLAGS.frames_dir, model_name)\n test_envs = TwoArms.get_envs(FLAGS.game, FLAGS.nb_test_episodes)\n\n settings = {\"lr\": FLAGS.lr,\n \"gamma\": FLAGS.gamma,\n \"game\": FLAGS.game,\n \"model_name\": model_name,\n \"checkpoint_dir\": checkpoint_dir,\n \"summaries_dir\": summaries_dir,\n \"frames_dir\": frames_dir,\n \"load_from\": os.path.join(FLAGS.checkpoint_dir, load_from_model_name),\n \"envs\": test_envs,\n \"mode\": \"eval\"}\n\n run(settings)\n\n with open(FLAGS.results_eval_file, \"r\") as f:\n line = f.readline()\n mean_regrets = line.rstrip('\\n').split(' ')\n mean_regrets = [float(rg) for rg in mean_regrets]\n mean_rg_avg = np.mean(mean_regrets)\n print(\"Avg regret for the model is {}\".format(mean_rg_avg))\n\n\ndef run(settings):\n recreate_subdirectory_structure(settings)\n tf.reset_default_graph()\n\n with tf.device(\"/cpu:0\"):\n global_step = tf.Variable(0, dtype=tf.int32, name='global_episodes', trainable=False)\n optimizer = tf.train.AdamOptimizer(learning_rate=settings[\"lr\"])\n global_network = ACNetwork('global', None)\n\n num_agents = 1\n agents = []\n envs = []\n for i in range(num_agents):\n if settings[\"game\"] == '11arms':\n this_env = ElevenArms()\n else:\n this_env = TwoArms(settings[\"game\"])\n envs.append(this_env)\n\n for i in range(num_agents):\n agents.append(Agent(envs[i], i, optimizer, global_step, settings))\n saver = tf.train.Saver(max_to_keep=5)\n\n with tf.Session() as sess:\n coord = tf.train.Coordinator()\n ckpt = tf.train.get_checkpoint_state(settings[\"load_from\"])\n print(\"Loading Model from {}\".format(ckpt.model_checkpoint_path))\n saver.restore(sess, ckpt.model_checkpoint_path)\n\n agent_threads = []\n for agent in agents:\n agent_play = lambda: agent.play(sess, coord, saver)\n thread = threading.Thread(target=agent_play)\n thread.start()\n agent_threads.append(thread)\n coord.join(agent_threads)\n\nif __name__ == '__main__':\n evaluate_one_test()\n","sub_path":"meta_bandits_11_arms/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":5623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"370338746","text":"import dlib\nimport cv2\nimport time\nfrom math import sqrt\nstart_time = time.time()\nimg = cv2.imread('./sad1.jpg')\ndetector = dlib.get_frontal_face_detector() #Load face detector\ndets = detector(img, 1) #Xác định vị trí khuôn mặt trong bức ảnh\npredictor = dlib.shape_predictor('./shape_predictor_68_face_landmarks.dat')\nlandmark = predictor(img, dets[0])\nlines = []\n# Xác định facial landmark trên khuôn mặt\nfor k, d in enumerate(landmark.parts()):\n #xác định khung miệng\n if(k>=60 and k<=68):\n cv2.circle(img, (d.x, d.y), 1, (255, 255, 255), 2)\n lines.append((d.x,d.y))\n\n#tìm điểm trung bình line\nx_line = round((lines[4][0]+lines[0][0])/2)\ny_line = round((lines[4][1]+lines[0][1])/2)\n\n#tính toán khoảng cách\nu_x = (lines[2][0]-x_line)*(lines[2][0]-x_line)\nu_y = (lines[2][1]-y_line)*(lines[2][1]-y_line)\nprint('Khoảng cách điểm trung bình line đến đỉnh trên môi', sqrt(u_x+u_y))\nd_x = (lines[6][0]-x_line)*(lines[6][0]-x_line)\nd_y = (lines[6][1]-y_line)*(lines[6][1]-y_line)\nprint('Khoảng cách điểm trung bình line đến đỉnh dưới môi',sqrt(d_x+d_y))\n\n#kết luận\nif sqrt(u_x+u_y) < sqrt(d_x+d_y):\n print('Vui')\nelif sqrt(u_x+u_y) > sqrt(d_x+d_y):\n if sqrt(u_x+u_y) - sqrt(d_x+d_y) >= 1: #tính độ chênh lệch ( độ chênh lệch tương đương khoảng cách đỉnh môi trên và dưới. Lưu ý : Điểu chỉnh điều kiện để tạo độ nhạy !\n print('buồn')\n else:\n print('Bình thường')\n\nend_time = time.time()\nprint('time:', end_time-start_time)\n\n#cv2.imshow('complete',img)\n#cv2.waitKey()\ncv2.imwrite('Image_landmarks_text_new.jpg',img)\n\n#Đây là thuật toán xác định cảm xúc với phương pháp trung điểm","sub_path":"nhandiencamxucanhsimple.py","file_name":"nhandiencamxucanhsimple.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"214346887","text":"\"\"\"Consts used by NHC2.\"\"\"\nfrom homeassistant.const import CONF_HOST # noqa pylint: disable=unused-import\n\nDOMAIN = 'nhc2'\nKEY_GATEWAY = 'nhc2_gateway'\nBRAND = 'Niko'\nLIGHT = 'Light'\nSWITCH = 'Switch'\nCONF_SWITCHES_AS_LIGHTS = 'switches_as_lights'\nDEFAULT_PORT = 8883\n","sub_path":"const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"77101610","text":"import subprocess\nimport os\nimport shutil\n\ndef isPunct(string):\n return string in [\".\",\",\",\"!\",\"?\",\":\",\";\"]\n\n\n\nclass stanford(object):\n\n def __init__(self,profile):\n self.identity = \"stanford\"\n self.workpath = os.path.join(\"tmp\",profile,\"stanford\")\n self.propspath = \"util/stanford/langmodel.props\"\n self.trainingfile = \"tmp/stanford/trainingfile\"\n self.testfile = \"tmp/stanford/testfile\"\n self.resultfile = \"tmp/stanford/taggingresult\"\n self.modelname = self.identity\n self.resultfile = \"tmp/stanford/taggingresult\"\n self.sep = \"_\"\n if not os.path.exists(self.workpath):\n os.mkdir(self.workpath)\n\n def save(self,profilepath):\n path = os.path.join(profilepath,self.identity)\n shutil.move(self.tmplocation,path)\n shutil.rmtree(self.workpath)\n\n def load(self,profilepath):\n if not os.path.exists(self.workpath):\n os.mkdir(self.workpath)\n shutil.copy(os.path.join(profilepath,self.modelname),os.path.join(self.workpath,self.modelname))\n\n def train(self, trainset):\n self.tmplocation = os.path.join(self.workpath,self.identity+\"model\")\n self.createTrainingFile(trainset)\n subprocess.run(\"java -classpath 'util/stanford/stanford-postagger.jar:lib/*:util/stanford/slf4j-simple.jar:util/stanford/slf4j-api.jar' edu.stanford.nlp.tagger.maxent.MaxentTagger -prop %s -model %s\" %(self.propspath,self.tmplocation), shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n\n \n \n \n def test(self, testset):\n f = open(self.testfile, \"w\")\n f.write(\" \".join(testset))\n f.close()\n subprocess.run(\"java -mx20g -classpath 'util/stanford/stanford-postagger.jar:lib/*:util/stanford/slf4j-simple.jar:util/stanford/slf4j-api.jar' edu.stanford.nlp.tagger.maxent.MaxentTagger -model %s -textFile %s\" %(\"tmp/stanford/\"+self.modelname ,self.testfile), shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n self.result = self.readResult()\n\n def readResult(self):\n f = open(self.resultfile,\"r\")\n cont = [tuple(x.split(self.sep,1)) for x in f.read().split() if len(x) > 0]\n f.close()\n return cont\n\n\n def createTrainingFile(self,sentencelist):\n f = open(self.trainingfile,\"w\")\n for sentence in sentencelist:\n for pair in sentence:\n try:\n f.write(pair[0] + \"\\t\" + pair[1] + \"\\n\")\n except UnicodeEncodeError:\n f.write(pair[0].encode('utf8') + \"\\t\" + pair[1].encode('utf8') + \"\\n\")\n if isPunct(pair[0]):\n f.write(\"\\n\")\n f.close()\n","sub_path":"src/tagger/tagger/stanford.py","file_name":"stanford.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"100511433","text":"# https://www.spoj.com/problems/NAJPF/\n\ndef kmp_preprocess(p, kmp):\n kmp[0] = 0\n i = 1\n j = 0\n while i < len(p):\n if p[i] == p[j]:\n j += 1\n kmp[i] = j\n i += 1\n else:\n if j != 0:\n j = kmp[j - 1]\n else:\n kmp[i] = 0\n i += 1\n\n# def kmp_pre(p):\n# kmp[0] = -1\n# j = -1\n# for i in range(1, len(p)):\n# while j > -1 and p[j + 1] != p[i]:\n# j += 1\n# if p[j + 1] == p[i]:\n# j += 1\n# kmp[i] = j\n\n\n\ndef kmp_search(t, p, kmp):\n i = 0\n j = 0\n found_inds = []\n while i < len(t):\n if p[j] == t[i]:\n i += 1\n j += 1\n if j == len(p):\n found_inds.append(i - j)\n j = kmp[j - 1]\n else:\n if j != 0:\n j = kmp[j - 1]\n else:\n i += 1\n return found_inds\n\n\nt = int(input())\nfor i in range(t):\n A, B = input().split()\n kmp = [None] * len(B)\n kmp_preprocess(B, kmp)\n res = kmp_search(A, B, kmp)\n if res:\n print(len(res))\n for i in res:\n print(i + 1, end=' ')\n print()\n else:\n print(\"Not Found\")\n print()\n\n\n","sub_path":"SPOJ/pattern_find.py","file_name":"pattern_find.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"101562976","text":"#!/usr/bin/env python\n# -*- encoding:utf-8 -*-\n\n# Author: lixingtie\n# Email: lixingtie@barfoo.com.cn\n# Create Date: 2013-9-10\n\nimport os\nimport codecs\nfrom bson import ObjectId\nfrom framework.data.mongo import db\nfrom core.logic.system import restart, isrunning\nfrom core.builder.page import build_handler, build_template, build_design\n\n\ndef create_page(systemid, page, _restart = True):\n \"\"\"\n 创建页面\n \"\"\"\n system = db.system.find_one({ \"_id\" : ObjectId(systemid) })\n create_handler(system, page)\n\n #重启目标系统,加载新的改动\n if _restart and isrunning(system):\n restart(systemid)\n\n\ndef save_page(systemid, page, html = \"\", design = \"\"):\n \"\"\"\n 保存页面\n \"\"\"\n options = page.options if \"options\" in page else {}\n links = page.links if \"links\" in page else []\n db.page.update({ \"_id\" : page._id }, { \"$set\" : { \"controls\" : page.controls, \"settings\" : page.settings ,\"options\" : options ,\"links\" : links } })\n\n system = db.system.find_one({ \"_id\" : ObjectId(systemid) })\n create_template(system, page, html, design)\n\n\ndef create_handler(system, page):\n \"\"\"\n 创建页面处理��\n \"\"\"\n #创建页面处理器\n source = build_handler(page)\n path = os.path.abspath((\"platform/system/%s/handlers/%s.py\" % (system.name.lower(), page.name.lower().replace(\" \",\"\"))))\n if not os.path.exists(os.path.dirname(path)):\n os.makedirs(os.path.dirname(path))\n\n f = codecs.open(path, \"w\", 'utf-8')\n f.write(source)\n f.close()\n\n\ndef create_template(system, page, html = \"\", design = \"\"):\n \"\"\"\n 创建HTML页面\n \"\"\"\n source = build_template(\"layout\" in page and page.layout.fetch() or None, html)\n path = os.path.abspath(\"platform/system/%s/templates/%s/%s.html\" % \\\n (system.name.lower(), page.name.lower().replace(\" \",\"\"), page.name.lower().replace(\" \", \"\")))\n if not os.path.exists(os.path.dirname(path)):\n os.makedirs(os.path.dirname(path))\n\n f = codecs.open(path, \"w\", 'utf-8')\n f.write(source)\n f.close()\n\n if \"layout\" in page and page.layout:\n path = os.path.abspath(\"platform/system/%s/platform/layout/%s.design\" % (page.system.fetch().name.lower(), page.layout.id))\n if not os.path.exists(path):\n return\n\n if not design:\n f = codecs.open(path, \"r\", 'utf-8')\n design = f.read()\n f.close()\n design = build_design(design)\n\n path = os.path.abspath(\"platform/system/%s/platform/page/%s.design\" % (system.name.lower(), page.name.lower().replace(\" \",\"\")))\n if not os.path.exists(os.path.dirname(path)):\n os.makedirs(os.path.dirname(path))\n f = codecs.open(path, \"w\", 'utf-8')\n f.write(design)\n f.close()\n\n\ndef get_page_html(systemid, page):\n \"\"\"\n 获取页面html\n \"\"\"\n system = db.system.find_one({ \"_id\" : ObjectId(systemid) })\n\n html = \"\"\n path = os.path.abspath(\"platform/system/%s/templates/%s/%s.html\" % \\\n (system.name.lower(), page.name.lower().replace(\" \",\"\"), page.name.lower().replace(\" \", \"\")))\n if os.path.exists(path):\n f = codecs.open(path, \"r\", 'utf-8')\n html = f.read()\n f.close()\n\n return html\n\n\ndef has_template(systemid, page):\n \"\"\"\n 判断页面是否创建了页面html文件\n \"\"\"\n system = db.system.find_one({ \"_id\" : ObjectId(systemid) })\n path = os.path.abspath(\"platform/system/%s/templates/%s/%s.html\" % \\\n (system.name.lower(), page.name.lower().replace(\" \",\"\"), page.name.lower().replace(\" \", \"\")))\n return os.path.exists(path)\n\n\ndef get_page_design(systemid, page):\n \"\"\"\n 获取页面设计html\n \"\"\"\n system = db.system.find_one({ \"_id\" : ObjectId(systemid) })\n\n html = \"\"\n path = os.path.abspath(\"platform/system/%s/platform/page/%s.design\" % (system.name.lower(), page.name.lower().replace(\" \",\"\")))\n if os.path.exists(path):\n f = codecs.open(path, \"r\", 'utf-8')\n html = f.read()\n f.close()\n\n return html\n\n\ndef remove_page(systemid, page):\n \"\"\"\n 删除页面\n \"\"\"\n system = db.system.find_one({ \"_id\" : ObjectId(systemid) })\n\n #删除页面处理器(handler)\n path = os.path.abspath(\"platform/system/%s/handlers/%s.py\" % (system.name.lower(), page.name.lower().replace(\" \",\"\")))\n if os.path.exists(path):\n os.remove(path)\n\n path = os.path.abspath(\"platform/system/%s/handlers/%s.pyc\" % (system.name.lower(), page.name.lower().replace(\" \",\"\")))\n if os.path.exists(path):\n os.remove(path)\n\n #删除页面模板(template)\n path = os.path.abspath(\"platform/system/%s/templates/%s/%s.html\" % \\\n (system.name.lower(), page.name.lower().replace(\" \",\"\"), page.name.lower().replace(\" \", \"\")))\n if os.path.exists(path):\n os.remove(path)\n os.rmdir(os.path.dirname(path))\n\n #删除页面设计时html文件\n path = os.path.abspath(\"platform/system/%s/platform/page/%s.design\" % (system.name.lower(), page.name.lower().replace(\" \",\"\")))\n if os.path.exists(path):\n os.remove(path)\n","sub_path":"core/logic/page.py","file_name":"page.py","file_ext":"py","file_size_in_byte":5094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"405923743","text":"#!/usr/bin/python\n# Here you will be able to combine the values that come from 2 sources\n# Value that starts with A will be the user data\n# Values that start with B will be forum node data\n\nimport sys\n\n\noldKey=None\nout_array =[]\nforum_keep =[]\nuser_keep =[]\n\n \nfor line in sys.stdin:\n \n\n #print line\n \n data_mapped = line.strip().split(\"\\t\")\n thisKey =data_mapped[0]\n #print thisKey\n #print data_mapped\n\n if oldKey and oldKey != thisKey:\n # print out out_array\n for i in range(len(forum_keep)):\n if len(user_keep) ==0:\n continue\n out_array =forum_keep[i]+user_keep\n print('\\t'.join(map(str,out_array)))\n out_array =[]\n forum_keep =[]\n user_keep =[]\n \n oldKey = thisKey\n if data_mapped[1] =='\"A\"':\n for k in range(len(data_mapped[2:])):\n user_keep.append(data_mapped[2:][k])\n #print user_keep\n else:\n forum_keep.append(data_mapped[2:])\n #print forum_keep\n\nif oldKey != None:\n for i in range(len(forum_keep)):\n out_array =forum_keep[i]+user_keep\n print('\\t'.join(map(str,out_array)))\n out_array =[]\n \n \n\n","sub_path":"3.reducer_join.py","file_name":"3.reducer_join.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"187238549","text":"#Stephen Marshall 6/3/19\n#script to allow a switch on pins a,b to swap between two videos\n#using pyautogui to send keypresses and output events\n#relevant pyautogui: \n#\t press('a'), press('b')\n#\t'browserback', 'browserforward', 'browserrefresh', 'browserstop'\n#\t\n\nfrom time import sleep\nfrom pyautogui import press, typewrite, hotkey\n\nimport RPi.GPIO as GPIO\n\nGPIO.setmode(GPIO.BOARD) #set labeling convention\na = 11\nb = 7\n#GPIO.setup(a, GPIO.IN, pull_up_down=GPIO.PUD_UP)\t#set as pull-up input\n#GPIO.setup(b, GPIO.IN, pull_up_down=GPIO.PUD_UP)\t#default to HIGH, 1\n\nGPIO.setup(a, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\t#set as pull-down input\nGPIO.setup(b, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\t#default to LOW, 0\n\n#lastState = 'a' #prob useless\njustSwitched = True;\nprint('about to begin loop')\nwhile True:\n\tif GPIO.input(a) and GPIO.input(b):\n\t\tprint('ERROR: Both states triggered')\n\t\tbreak\t\t\t#end program\n\tif GPIO.input(a): \t#we are on A\n\t\tif justSwitched:\n\t\t\t#press A key:\n\t\t\tprint('A connected')\n\t\t\tpress('a')\n\t\t\tjustSwitched = False\n\t\t\n\telif GPIO.input(b): #we are on B\n\t\tif justSwitched:\n\t\t\t#press B key\n\t\t\tprint('B connected')\n\t\t\tpress('b')\n\t\t\tjustSwitched = False;\n\t\t\n\telse: \t\t\t\t#we are transitioning\n\t\tif not justSwitched:\n\t\t\tjustSwitched = True\n\t\n\t\n\t\n\tsleep(0.1)\n\n\n#---- Experimentation: ----\n#while True:\n#\tif GPIO.input(a) and GPIO.input(b):\n#\t\tprint('both')\n#\telif(GPIO.input(b)): #A is grounded, kinda reversed\n#\t\tprint('state A')\n#\telif(GPIO.input(a)): #B is grounded\n#\t\tprint('state B')\n#\t\n#\tsleep(0.25)\n","sub_path":"Eureka/EarthMoon/videoSwitchV1.py","file_name":"videoSwitchV1.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"606735251","text":"import datetime\nfrom google.appengine.ext import db\nfrom geo.geomodel import GeoModel\nfrom google.appengine.api import mail\n\n\nclass Checkin(GeoModel):\n id = db.StringProperty(required=True)\n name = db.StringProperty(required=True)\n dateCreated = db.DateTimeProperty()\n webservice = db.StringProperty(required=True)\n\n\nclass Feedback(db.Model):\n name = db.StringProperty(required=True)\n email = db.StringProperty(required=True)\n description = db.StringProperty(required=True, multiline=True)\n dateCreated = db.DateTimeProperty()\n\n\ndef getNewCheckins():\n now = datetime.datetime.now()\n yesterday = now - datetime.timedelta(days=1)\n query = db.GqlQuery(\"SELECT * FROM Checkin \" +\n \"WHERE dateCreated > :1 AND dateCreated < :2 \",\n yesterday, now)\n return query.fetch(100)\n\n\ndef getNewFeedbacks():\n now = datetime.datetime.now()\n yesterday = now - datetime.timedelta(days=1)\n query = db.GqlQuery(\"SELECT * FROM Feedback \" +\n \"WHERE dateCreated > :1 AND dateCreated < :2 \",\n yesterday, now)\n return query.fetch(100)\n\n\ndef getMessageBody():\n checkins = getNewCheckins()\n feedbacks = getNewFeedbacks()\n body = 'Dear EceCheckin Developers!\\n'\n body += 'I am glad to announce you...\\n'\n if checkins is not None:\n if (len(checkins) != 0):\n body += '\\n\\nNew Checkins Found!\\n'\n for i in range(len(checkins)):\n body += '\\nservice: ' + checkins[i].webservice\n body += '\\nname: ' + checkins[i].name + '\\n'\n else:\n body += '\\n\\nNo new Checkins Found..'\n else:\n body += '\\n\\nNo new Checkins Found..'\n if feedbacks is not None:\n if (len(feedbacks) != 0):\n body += '\\n\\nNew Feedbacks Found!\\n'\n for i in range(len(feedbacks)):\n body += '\\nname: ' + feedbacks[i].name\n body += '\\nemail: ' + feedbacks[i].email + '\\n'\n body += '\\ndescription: ' + feedbacks[i].description + '\\n'\n else:\n body += '\\n\\nNo new Feedbacks Found..'\n else:\n body += '\\n\\nNo new Feedbacks Found..'\n return body\n\n\nmessage = mail.EmailMessage(sender=\"\",\n subject=\"Daily Report\")\n\nmessage.to = \"\"\nmessage.body = getMessageBody()\nmessage.send()\n","sub_path":"www/crons/dailyReport.py","file_name":"dailyReport.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"446626457","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Author: Treamy\n\n\n#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Author: Treamy\n\nimport os\nimport torch\nimport numpy as np\n#from nWay_kShot import loadDL\nfrom loadData import load_ds_dl\nfrom ProtoNet import embedding_map, myProtoNet, get_model\nfrom torch import optim\nimport argparse\n\n\nclass Averager(object):\n def __init__(self):\n self.v = 0\n self.n = 0\n\n def add(self, x):\n self.v = (self.v * self.n + x) / (self.n+1)\n self.n += 1\n\n def item(self):\n return self.v\n\n\ndef run(args):\n\n max_epoch = args.max_epoch\n n_episodes = args.n_episodes\n n_episodes_test = args.n_episodes_test\n n_way = args.n_way\n n_way_test = args.n_way_test\n k_spt = args.k_spt\n k_qry = args.k_qry\n patience = args.patience\n use_cuda = args.use_cuda\n save_path = args.save_path\n lr = args.learning_rate\n step_size = args.step_size\n\n if use_cuda:\n torch.cuda.manual_seed(0)\n\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n\n model = get_model(opt=args, ch_in=1, cuda=use_cuda)\n\n optimizer = optim.Adam(model.parameters(), lr=lr)\n lr_sche = optim.lr_scheduler.StepLR(optimizer, step_size=step_size, gamma=0.5)\n\n trlog = {\n 'train_loss': [], 'train_acc': [],\n 'val_loss': [], 'val_acc': [],\n 'min_loss': np.inf\n }\n\n train_dl = load_ds_dl('omniglot','train',n_way, n_episodes, k_spt, k_qry, )\n val_dl = load_ds_dl('omniglot','val', n_way_test, n_episodes_test, k_spt, k_qry)\n\n state = True\n epoch = 0\n wait = 0\n\n while epoch < max_epoch and state:\n model.train()\n lr_sche.step()\n tl_a, tc_a = Averager(), Averager()\n for i, bx in enumerate(train_dl, 1):\n\n optimizer.zero_grad()\n loss, acc = model.loss(bx)\n tl_a.add(loss.item()); tc_a.add(acc)\n loss.backward()\n optimizer.step()\n print('epoch {}, on train {}/{}, loss={:.4f} acc={:.4f}'\n .format(epoch, i, n_episodes, loss.item(), acc))\n del loss\n trlog['train_loss'].append(tl_a.item())\n trlog['train_acc'].append(tc_a.item())\n print('----a batch training episodes end----\\n')\n\n\n model.eval()\n vl_a, vc_a = Averager(), Averager()\n for i, bx in enumerate(val_dl, 1):\n loss, acc = model.loss(bx, train=False)\n vl_a.add(loss.item()); vc_a.add(acc)\n del loss\n vl_a, vc_a = vl_a.item(), vc_a.item()\n print('epoch {}, on val, loss={:.4f} acc={:.4f}\\n'.format(epoch, vl_a, vc_a))\n trlog['val_loss'].append(vl_a)\n trlog['val_acc'].append(vc_a)\n\n\n if vl_a < trlog['min_loss']:\n trlog['min_loss'] = vl_a\n print(\"==> best loss model (loss = {:0.6f}), saving model...\\n\".format(trlog['min_loss']))\n if use_cuda:\n model.cpu()\n torch.save(model.state_dict(), os.path.join(save_path, 'min-loss' + '.pth'))\n if use_cuda:\n model.cuda()\n wait = 0\n else:\n wait += 1\n\n torch.save(trlog, os.path.join(save_path, 'trlog'))\n\n if wait > patience:\n print(\"==> patience {:d} exceeded\\n\".format(patience))\n state = False\n if use_cuda:\n model.cpu()\n torch.save(model.state_dict(), os.path.join(save_path, 'epoch-last' + '.pth'))\n\n epoch += 1\n\n\nif __name__ == '__main__':\n\n torch.manual_seed(0)\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--max-epoch', type=int, default=10000)\n parser.add_argument('--n-episodes', type=int, default=200)\n parser.add_argument('--n-episodes-test', type=int, default=200)\n parser.add_argument('--n-way', type=int, default=60)\n parser.add_argument('--n-way-test', type=int, default=5)\n parser.add_argument('--k-spt', type=int, default=5)\n parser.add_argument('--k-qry', type=int, default=15)\n parser.add_argument('--patience', type=int, default=120)\n parser.add_argument('--use-cuda', type=int, default=1)\n parser.add_argument('--learning-rate', type=float, default=0.001)\n parser.add_argument('--step-size', type=int, default=20)\n parser.add_argument('--save-path', type=str, default='./saved/')\n\n\n # args = vars(parser.parse_args())\n # print(args)\n\n args = parser.parse_args()\n run(args)\n\n\n\n\n","sub_path":"omniglotPy/train_omni.py","file_name":"train_omni.py","file_ext":"py","file_size_in_byte":4425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"464482076","text":"\"\"\"\nRun the cross validation with greedy search for model selection using VB-NMTF \non the CCLE EC50 dataset.\n\"\"\"\n\nimport sys, os\nproject_location = os.path.dirname(__file__)+\"/../../../../../\"\nsys.path.append(project_location)\n\nfrom BNMTF.code.models.bnmtf_gibbs_optimised import bnmtf_gibbs_optimised\nfrom BNMTF.code.cross_validation.greedy_search_cross_validation import GreedySearchCrossValidation\nfrom BNMTF.data_drug_sensitivity.ccle.load_data import load_ccle\n\n\n# Settings\nstandardised = False\niterations = 1000\nburn_in = 900\nthinning = 2\n\ninit_S = 'random' #'exp' #\ninit_FG = 'kmeans' #'exp' #\n\nK_range = [1,2,3,4,5,6,7,8,9,10]\nL_range = [1,2,3,4,5,6,7,8,9,10]\nno_folds = 10\nrestarts = 1\n\nquality_metric = 'AIC'\noutput_file = \"./results.txt\"\n\nalpha, beta = 1., 1.\nlambdaF = 1./10.\nlambdaS = 1./10.\nlambdaG = 1./10.\npriors = { 'alpha':alpha, 'beta':beta, 'lambdaF':lambdaF, 'lambdaS':lambdaS, 'lambdaG':lambdaG }\n\n# Load in the CCLE EC50 dataset\nR,M = load_ccle(ic50=False)\n\n# Run the cross-validation framework\n#random.seed(1)\n#numpy.random.seed(1)\nnested_crossval = GreedySearchCrossValidation(\n classifier=bnmtf_gibbs_optimised,\n R=R,\n M=M,\n values_K=K_range,\n values_L=L_range,\n folds=no_folds,\n priors=priors,\n init_S=init_S,\n init_FG=init_FG,\n iterations=iterations,\n restarts=restarts,\n quality_metric=quality_metric,\n file_performance=output_file\n)\nnested_crossval.run(burn_in=burn_in,thinning=thinning)\n","sub_path":"experiments/experiments_ccle/cross_validation/ccle_ec_gibbs_nmtf/greedysearch_xval_gibbs.py","file_name":"greedysearch_xval_gibbs.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"369971198","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Oct 19 21:56:13 2018\r\n\r\n@author: romain\r\n\"\"\"\r\nfrom math import gcd\r\n\r\nt = int(input())\r\n\r\nfor _ in range(t):\r\n n = int(input())\r\n nodes = list(map(int, str.split(input(), \" \")))\r\n notTakens = nodes[:]\r\n\r\n toTake = [notTakens.pop()]\r\n\r\n while len(toTake) > 0:\r\n node = toTake.pop()\r\n for node2 in set(notTakens):\r\n if gcd(node, node2) == 1:\r\n notTakens = list(filter(lambda a: a != node2, notTakens))\r\n toTake.append(node2)\r\n if (len(notTakens)) == 0:\r\n print(0)\r\n else:\r\n print(1)\r\n if nodes[0] == 47:\r\n nodes[0] = 2\r\n else:\r\n nodes[0] = 47\r\n print(\" \".join(list(map(str, nodes))))\r\n","sub_path":"19.snackdown/roundA/Pb3.py","file_name":"Pb3.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"335499731","text":"import requests\nfrom bs4 import BeautifulSoup\n\n\ndef jsext(url,outfile):\n source = requests.get(url).text\n soup = BeautifulSoup(source ,'lxml')\n\n for article in soup.find_all('script'):\n try:\n if (article.text.strip()).startswith('init'):\n url=article.text.strip().split('\"')[3]\n if url.startswith('https'):\n iscript=requests.get(url).json()\n pt=iscript['path']\n if outfile==None:\n print('\\n')\n print(iscript['dependencies'][pt].encode('utf-8').strip())\n else:\n file=open(outfile, 'w')\n file.write(iscript['dependencies'][pt].encode('utf-8').strip())\n file.close()\n clean_lines = []\n with open(outfile, \"r\") as f:\n lines = f.readlines()\n clean_lines = [l.strip() for l in lines if l.strip()]\n with open(outfile, \"w\") as f:\n f.writelines('\\n'.join(clean_lines))\n except Exception as e:\n print(e)\n#jsext(url='https://globalfires.earthengine.app/view/gfedv4s-monthly-ba-animated')\n#jsext(url='https://bullocke.users.earthengine.app/view/amazon')\n\n","sub_path":"geeadd/app2script.py","file_name":"app2script.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"553448830","text":"# -*- coding: utf-8 -*-\nfrom setuptools import setup, find_packages\n\nwith open('requirements.txt') as f:\n\tinstall_requires = f.read().strip().split('\\n')\n\n# get version from __version__ variable in sanad_customisations/__init__.py\nfrom sanad_customisations import __version__ as version\n\nsetup(\n\tname='sanad_customisations',\n\tversion=version,\n\tdescription='Custom Portals',\n\tauthor='Bantoo Accounting Innovations',\n\tauthor_email='technical@thebantoo.com',\n\tpackages=find_packages(),\n\tzip_safe=False,\n\tinclude_package_data=True,\n\tinstall_requires=install_requires\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"300829959","text":"# coding: utf-8\nimport os\nimport sys\n\nimport pytest # noqa\n\nfrom ray._private.test_utils import load_test_config\nfrom ray.autoscaler.v2.instance_manager.config import NodeProviderConfig\n\n\ndef test_simple():\n raw_config = load_test_config(\"test_multi_node.yaml\")\n config = NodeProviderConfig(raw_config)\n assert config.get_node_config(\"head_node\") == {\"InstanceType\": \"m5.large\"}\n assert config.get_docker_config(\"head_node\") == {\n \"image\": \"anyscale/ray-ml:latest\",\n \"container_name\": \"ray_container\",\n \"pull_before_run\": True,\n }\n assert config.get_worker_start_ray_commands\n\n\ndef test_complex():\n raw_config = load_test_config(\"test_ray_complex.yaml\")\n config = NodeProviderConfig(raw_config)\n assert config.get_head_setup_commands() == [\n \"echo a\",\n \"echo b\",\n \"echo ${echo hi}\",\n \"echo head\",\n ]\n assert config.get_head_start_ray_commands() == [\n \"ray stop\",\n \"ray start --head --autoscaling-config=~/ray_bootstrap_config.yaml\",\n ]\n assert config.get_worker_setup_commands(\"worker_nodes\") == [\n \"echo a\",\n \"echo b\",\n \"echo ${echo hi}\",\n \"echo worker\",\n ]\n assert config.get_worker_start_ray_commands() == [\n \"ray stop\",\n \"ray start --address=$RAY_HEAD_IP\",\n ]\n assert config.get_worker_setup_commands(\"worker_nodes1\") == [\n \"echo worker1\",\n ]\n\n assert config.get_docker_config(\"head_node\") == {\n \"image\": \"anyscale/ray-ml:latest\",\n \"container_name\": \"ray_container\",\n \"pull_before_run\": True,\n }\n\n assert config.get_docker_config(\"worker_nodes\") == {\n \"image\": \"anyscale/ray-ml:latest\",\n \"container_name\": \"ray_container\",\n \"pull_before_run\": True,\n }\n\n assert config.get_docker_config(\"worker_nodes1\") == {\n \"image\": \"anyscale/ray-ml:nightly\",\n \"container_name\": \"ray_container\",\n \"pull_before_run\": True,\n }\n\n assert config.get_node_type_specific_config(\n \"worker_nodes\", \"initialization_commands\"\n ) == [\"echo what\"]\n\n assert config.get_node_type_specific_config(\n \"worker_nodes1\", \"initialization_commands\"\n ) == [\"echo init\"]\n\n assert config.get_node_resources(\"worker_nodes1\") == {\"CPU\": 2}\n\n assert config.get_node_resources(\"worker_nodes\") == {}\n\n\nif __name__ == \"__main__\":\n if os.environ.get(\"PARALLEL_CI\"):\n sys.exit(pytest.main([\"-n\", \"auto\", \"--boxed\", \"-vs\", __file__]))\n else:\n sys.exit(pytest.main([\"-sv\", __file__]))\n","sub_path":"python/ray/autoscaler/v2/tests/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":2538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"79798589","text":"import numpy as np\nfrom gym import spaces\n\nimport turtlebot_env\n\nclass Turtlebot3LaserEnv(turtlebot_env.TurtlebotEnv):\n\n def __init__(self):\n turtlebot_env.TurtlebotEnv.__init__(self)\n\n laser = self.get_laser_data()\n self.observation_dims = [len(laser.ranges)]\n self.observation_space = spaces.Discrete(self.observation_dims)\n self.laser = np.zeros(self.observation_dims, np.float32)\n self.action_space = spaces.Discrete(3)\n self.collision = False\n self.obstacle_thresold = 0.15\n self.time_stamp = laser.scan_time\n\n def _step(self, action):\n self.action2vel(action)\n\n self.update()\n\n if self.collision:\n reward = -99\n else:\n if action == 1:\n reward = 0.9\n else:\n reward = -0.003\n info = {}\n return self.laser, reward, self.collision, info\n\n def _reset(self):\n\n self.send_velocity_command(0.0, 0.0)\n self.reset_simulation()\n self.update()\n\n return self.laser, 0.0\n\n def action2vel(self, action):\n action -= 1\n\n if action == 0:\n linearx = 0.9\n else:\n linearx = 0.3\n\n anglz = action * 0.9\n self.send_velocity_command(linearx, anglz)\n\n def update(self):\n laser = self.get_laser_data()\n self.laser = laser.ranges\n self.time_stamp = laser.scan_time\n self.collision = False\n if np.min(self.laser) < self.obstacle_thresold:\n self.collision = True\n","sub_path":"robotics_gym/envs/gazebo/turtlebot/turtlebot3_laser_env.py","file_name":"turtlebot3_laser_env.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"304306333","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n@version: 3.5\n@author: morgana\n@license: Apache Licence \n@contact: vipmorgana@gmail.com\n@site: \n@software: PyCharm\n@file: FunctionReturnOddList.py\n@time: 2017/6/25 下午5:01\n写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。\n\"\"\"\n\n\ndef OddIndexNewList(l):\n j=[]\n for i in range(len(l)):\n if i %2 ==1:\n j.append(l[i])\n return j\n\nl=['Joseph','Morgan','is','good-looking']\nprint(OddIndexNewList(l))","sub_path":"Morgana/D20170624review/FunctionReturnOddList.py","file_name":"FunctionReturnOddList.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"115205084","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Sep 22 13:52:45 2019\r\n\r\n@author: prettyyang2\r\n\"\"\"\r\nimport matplotlib.pyplot as plt\r\nimport csv\r\nimport re\r\nimport numpy as np\r\nfrom collections import Counter\r\n\r\ndef count_words(text):\r\n '''count how many words in the text'''\r\n words=0\r\n for lines in text: \r\n lines = lines.lower()\r\n lines = re.sub('\\W', ' ', lines) \r\n lines = re.sub('\\s+', ' ', lines) \r\n lines = lines.strip() \r\n data = lines.split(' ')\r\n words+=len(data)\r\n return words\r\n\r\nif __name__ == \"__main__\":\r\n with open('label_list.tsv',encoding='utf8') as f:\r\n reader = csv.reader(f, delimiter=\"\\t\")\r\n label_list = []\r\n for line in reader:\r\n label_list.extend(line)\r\n \r\n with open('data.tsv.',encoding='utf8') as f:\r\n reader = csv.reader(f, delimiter=\"\\t\")\r\n labels = []\r\n dic = {}\r\n words=[]\r\n for line in reader:\r\n temp = line[0].split(', ')\r\n word = count_words(line[1:])\r\n words.append(word)\r\n n = len(temp)\r\n if n not in dic:\r\n dic[n] = 1\r\n else:\r\n dic[n] += 1\r\n labels.extend(temp)\r\n \r\n#count num of classes\r\n classes_count = Counter(labels)\r\n classes_count = sorted(classes_count.items(),key = lambda item:item[1]) \r\n classes=[x[0] for x in classes_count] \r\n num=[x[1] for x in classes_count] \r\n \r\n plt.barh(np.arange(len(classes)),num)\r\n for xx, yy in zip(np.arange(len(classes)),num):\r\n plt.text(yy+8, xx-0.2, str(yy), ha='center')\r\n# my_x_ticks = np.arange(0, 351, 50)\r\n# plt.xticks(my_x_ticks)\r\n plt.yticks(np.arange(len(classes)),classes)\r\n plt.xlabel(\"number\")\r\n plt.title(\"number of classes\")\r\n plt.tight_layout()\r\n plt.savefig('num_classes.png',transparent=True)\r\n plt.show()\r\n \r\n #count How many samples have multiple labels?\r\n x = list(dic.keys())\r\n y = list(dic.values())\r\n \r\n plt.bar(x, y, width=0.3)\r\n for xx, yy in zip(x,y):\r\n plt.text(xx, yy, str(yy), ha='center')\r\n# my_x_ticks = np.arange(1, 2.1, 1)\r\n# my_y_ticks = np.arange(0, 166, 20)\r\n# plt.xticks(my_x_ticks)\r\n# plt.yticks(my_y_ticks)\r\n plt.xlabel(\"number of labels\")\r\n plt.title(\"How many samples have multiple labels?\")\r\n plt.savefig('labels.png', transparent=True)\r\n plt.show()\r\n \r\n \r\n \r\n plt.hist(words, bins=30)\r\n #my_x_ticks = np.arange(0, 6000, 1000)\r\n #plt.xticks(my_x_ticks)\r\n # x label\r\n plt.xlabel(\"number of words\")\r\n # y label\r\n plt.ylabel(\"number of articles\")\r\n # title\r\n plt.title(\"The distribution of the number of words in articles\")\r\n plt.savefig('hist.png', transparent=True)\r\n plt.show()\r\n","sub_path":"data/data_analysis.py","file_name":"data_analysis.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"493524043","text":"from __future__ import print_function\n\nimport json\nimport boto3\nimport config\nimport traceback\n\ndynamo = boto3.resource('dynamodb', region_name=config.region)\nlambda_client = boto3.client('lambda')\n\nuser_table = dynamo.Table(config.user_table)\nadmin_table = dynamo.Table(config.backoffice_user_table)\ncart_table = dynamo.Table(config.cart_table)\naccess_table = dynamo.Table(config.access_table)\n\n\ndef lambda_handler(event, context):\n response = {}\n\n try:\n lambda_resp = lambda_client.invoke(\n FunctionName=config.authenticator_admin,\n InvocationType='RequestResponse',\n LogType='None',\n Payload='{\"base64-token-email\": \"' + event['base64-token-email'] + '\"}')\n\n lambda_resp = json.loads(lambda_resp['Payload'].read())\n\n if 'email' in lambda_resp:\n response['email'] = lambda_resp['email']\n if 'token' in lambda_resp:\n response['token'] = lambda_resp['token']\n if 'error' in lambda_resp:\n response['error'] = lambda_resp['error']\n return response\n\n # Get allowed methods\n acl = access_table.get_item(Key={'role_name': lambda_resp['role_name']})\n\n response['actions'] = acl['Item']['actions']\n response['success'] = \"true\"\n except Exception as e:\n print(e)\n lambda_client.invoke(FunctionName=config.error_handler,\n InvocationType='Event',\n LogType='None',\n Payload=json.dumps({\n \"function_name\": context.function_name,\n \"args\": e.args,\n \"message\": traceback.format_exc()\n }))\n response['error'] = [\n {\n 'error': e.message,\n 'message': 'An error occurred. Please try again later.'\n }\n ]\n\n return response\n","sub_path":"handlers/admin/roles/GET/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"25396694","text":"#!/usr/bin/env python\n\nimport argparse\nimport logging\nimport os\nimport subprocess\nimport sys\nimport time\nfrom pysvapi.elementdriver.sshdriver import sshdriver\nfrom pysvapi.svapiclient import client\nimport yaml\nimport re\n\ndef configure_license_servers(yaml_cfg,logger):\n # walk through vnf records \n for index, vnfr in yaml_cfg['vnfr'].items():\n logger.debug(\"VNFR {}: {}\".format(index, vnfr))\n\n if re.search('PTS|TSE',vnfr['name']):\n\n if not yaml_cfg.has_key('parameter'):\n logger.info(\"No parameters passed in\")\n continue\n\n if not yaml_cfg['parameter'].has_key('license_server'):\n logger.info(\"No license server provided\")\n continue\n\n logger.info(\"Setting license server on {}:{} license server = {}\".format(vnfr['name'],vnfr['mgmt_ip_address'], yaml_cfg['parameter']['license_server']))\n sess=sshdriver.ElementDriverSSH(vnfr['mgmt_ip_address'])\n cli = client.Client(sess)\n cli.configure_license_server( yaml_cfg['parameter']['license_server'] )\n\n\ndef main(argv=sys.argv[1:]):\n try:\n parser = argparse.ArgumentParser()\n parser.add_argument(\"yaml_cfg_file\", type=argparse.FileType('r'))\n parser.add_argument(\"-q\", \"--quiet\", dest=\"verbose\", action=\"store_false\")\n parser.add_argument(\"-r\", \"--rundir\", dest='run_dir', action='store')\n args = parser.parse_args()\n\n run_dir = args.run_dir\n if not run_dir:\n run_dir = os.path.join(os.environ['RIFT_INSTALL'], \"var/run/rift\")\n if not os.path.exists(run_dir):\n os.makedirs(run_dir)\n log_file = \"{}/set_license_server-{}.log\".format(run_dir, time.strftime(\"%Y%m%d%H%M%S\"))\n logging.basicConfig(filename=log_file, level=logging.DEBUG)\n logger = logging.getLogger()\n\n except Exception as e:\n print(\"Exception in {}: {}\".format(__file__, e))\n sys.exit(1)\n\n try:\n ch = logging.StreamHandler()\n if args.verbose:\n ch.setLevel(logging.DEBUG)\n else:\n ch.setLevel(logging.INFO)\n\n # create formatter and add it to the handlers\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n ch.setFormatter(formatter)\n logger.addHandler(ch)\n\n except Exception as e:\n logger.exception(e)\n raise e\n\n try:\n yaml_str = args.yaml_cfg_file.read()\n # logger.debug(\"Input YAML file:\\n{}\".format(yaml_str))\n yaml_cfg = yaml.load(yaml_str)\n logger.debug(\"Input YAML: {}\".format(yaml_cfg))\n configure_license_servers(yaml_cfg,logger)\n\n except Exception as e:\n logger.exception(e)\n raise e\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"attic/rift/tse_pktgen_nsd/scripts/set_license_server.py","file_name":"set_license_server.py","file_ext":"py","file_size_in_byte":2794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"194136697","text":"###################################\r\n# #\r\n# Client Register Application #\r\n# #\r\n###################################\r\n\r\n# ISC License\r\n#\r\n# Copyright (c) 2015 Weisz Roland weisz.roland@wevik.hu\r\n#\r\n# Permission to use, copy, modify, and/or distribute this software for any\r\n# purpose with or without fee is hereby granted, provided that the above\r\n# copyright notice and this permission notice appear in all copies.\r\n#\r\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\n# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\n# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\n# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\n# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\n# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\n# PERFORMANCE OF THIS SOFTWARE.\r\n\r\nfrom common.app import FrameWork\r\nimport common.mf as mf\r\nfrom time import strftime\r\n\r\napplication = \"Ügyfelek\"\r\nlabels = (\"sorsz.\", \"név / cégnév\", \"ország\", \"irányítószám\", \"helység\", \"közterület\", \"házszám\", \"adószám\", \"cégjegyzékszám\", \"kivitelezői nyilvántartási szám\", \"kamarai nyilvántartási szám\", \"bankszámlaszám\", \"telefon\", \"telefax\", \"webcím\", \"email-cím\", \"képviselő\", \"kontaktszemély\", \"személyes email\", \"mobiltelefon\", \"megjegyzés\", \"rögzítve\", \"módosítva\")\r\n\r\nclass Client(FrameWork):\r\n \"\"\" Uses base class \"\"\"\r\n\r\n def __init__(self, root = None):\r\n \"\"\" Based on self.LABELS creates columns of database & displays them as rows of entry fields\r\n Special values are:\r\n - first [0]: integer primary key\r\n - second last [-2]: original insertation time of that row\r\n - last [-1]: last modification\r\n These rows appear as disabled entry fields, and cannot be modiefied by the user. \"\"\"\r\n self.root = root\r\n super().__init__(self.root)\r\n self.APPLICATION = application\r\n self.TABLE = mf.validVar(self.APPLICATION)\r\n self.LABELS = labels\r\n self.UNITS = [\"\" for l in self.LABELS]\r\n self.WIDTHS = (self.NARROW, self.WIDE, self.WIDE, self.NARROW, self.WIDE, self.WIDE, self.NARROW, self.MID, self.MID, self.MID, self.MID, self.WIDE, self.MID, self.MID, self.WIDE, self.WIDE, self.WIDE, self.WIDE, self.WIDE, self.MID, self.WIDE, self.WIDE, self.WIDE)\r\n self.header = \"{:_^80}\".format(\" \".join(list(self.APPLICATION.upper())))\r\n self.decorateWindow()\r\n self.placeWidgets()\r\n self.allBindings()\r\n self.initDB()\r\n self.initApp()\r\n\r\n def displayList(self):\r\n \"\"\" Tells parent's same method which columns to display \"\"\"\r\n super().displayList((self.LABELS[1], 32))\r\n\r\n def showSelection(self):\r\n \"\"\" Displays title and tells parent's same method which columns to display \"\"\"\r\n print(self.header)\r\n super().showSelection((self.LABELS[0], 7), (self.LABELS[1], 52), (self.LABELS[4], 20))\r\n\r\n def exportSelection(self):\r\n \"\"\" Exports selection to .txt \"\"\"\r\n timestamp, timestamp_filename = strftime(\"%Y.%m.%d.\"), strftime(\"%Y%m%d%H%M%S\")\r\n file = open(\"../{}{}.txt\".format(mf.validVar(self.APPLICATION), timestamp_filename),'w')\r\n file.write(self.header + '\\n')\r\n for num, row_id in enumerate(self.row_ids):\r\n row = self.db.fetchRow(row_id)\r\n file.write(\"\\n{}.\\t{}\\n\".format(num+1, row[mf.validVar(self.LABELS[1])]))\r\n file.write(\"\\t{}-{}, {} {}\\n\".format(row[mf.validVar(\"irányítószám\")], row[mf.validVar(\"helység\")], row[mf.validVar(\"közterület\")], row[mf.validVar(\"házszám\")]))\r\n file.write(\"\\t{}\\n\\t{}\\n\".format(row[mf.validVar(\"személyes email\")], row[mf.validVar(\"mobiltelefon\")]))\r\n file.write(\"{:_>79}\\n\".format(\"\"))\r\n file.write(\"Kelt: {}\\n\".format(timestamp))\r\n file.close()\r\n print(\"Kiválasztás fájlba írva.\")\r\n \r\ndef main():\r\n Client().mainloop()\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"134294012","text":"from dataclasses import dataclass\nfrom typing import Callable\n\n\n@dataclass\nclass Customer:\n name: str\n age: int\n\n\ndef send_email_promotion(\n customers: list[Customer], is_eligible: Callable[[Customer], bool]\n) -> None:\n for customer in customers:\n print(f\"Checking {customer.name}\")\n if is_eligible(customer):\n print(f\"{customer.name} is eligible for promotion\")\n else:\n print(f\"{customer.name} is not eligible for promotion\")\n\n\ndef is_eligible_for_promotion(customer: Customer) -> bool:\n return customer.age > 50\n\n\ndef main() -> None:\n customers = [\n Customer(\"Alice\", 25),\n Customer(\"Bob\", 30),\n Customer(\"Charlie\", 35),\n Customer(\"David\", 40),\n Customer(\"Eve\", 45),\n Customer(\"Frank\", 50),\n Customer(\"Grace\", 55),\n Customer(\"Holly\", 60),\n Customer(\"Iris\", 65),\n ]\n send_email_promotion(customers, is_eligible_for_promotion)\n # send_email_promotion(customers, lambda customer: customer.age > 50)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Python/Code_examples/03_next_level_functions/func_param_lambda.py","file_name":"func_param_lambda.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"637730630","text":"#! /usr/bin/env python3.7\n\nimport tkinter as tk\n\nroot = tk.Tk()\n\nroot.title(\"Setting the App Icon\")\n\napp_ico = tk.PhotoImage(file=\"images/white.png\")\nroot.iconphoto(False, app_ico)\n\nroot.configure(width=600, height=400, padx=5, pady=5)\n\nroot.mainloop()\n","sub_path":"tkinter_2/demo1.py","file_name":"demo1.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"226545151","text":"# Refactor code: Not timed (good to get it back within 24 hours) \n# Aim for production quality ‘best-practice/clean’ code.\n# Please explain/show how you would test.\n#\n# The requirements of the code is to update the build number in\n# two different files.\n\nimport os\nimport re\nimport unittest\nimport shutil\n\n\nclass TestFileUpdate(unittest.TestCase):\n\n def setUp(self):\n self.working_dir = os.path.join(os.getcwd(), \"SourcePath\", \"develop\", \"global\", \"src\")\n os.makedirs(self.working_dir, exist_ok=True)\n os.environ[\"SourcePath\"] = os.path.join(os.getcwd(), \"SourcePath\")\n os.environ[\"BuildNum\"] = \"7\"\n\n def tearDown(self):\n del os.environ[\"BuildNum\"]\n del os.environ['SourcePath']\n shutil.rmtree(os.path.join(os.getcwd(), \"SourcePath\"), ignore_errors=True)\n\n def test_updateSConstruct(self):\n input_content = \"\"\"\n config.version = Version( \n major=15,\n minor=0,\n point=6,\n patch=0\n )\n \"\"\"\n file_name = os.path.join(self.working_dir, \"SConstruct\")\n with open(file_name, 'w') as fout:\n fout.write(input_content)\n updateSconstruct()\n with open(file_name, 'r') as fin:\n assert \"point={}\".format(os.environ[\"BuildNum\"]) in fin.read()\n\n def test_updateVersion(self):\n input_content = \"\"\"\n ADLMSDK_VERSION_POINT=6\n \"\"\"\n file_name = os.path.join(self.working_dir, \"VERSION\")\n with open(file_name, 'w') as fout:\n fout.write(input_content)\n updateVersion()\n with open(file_name, 'r') as fin:\n assert \"ADLMSDK_VERSION_POINT={}\".format(os.environ[\"BuildNum\"]) in fin.read()\n\ndef updateFile(parent_dir, file_name, field_name, field_value):\n \"\"\"\n utility file to update field in a file with BuildNum\n The routine will create a temp file write the updated contents\n Then replace the original file with the new temp file retaining original name\n Input:\n parent_dir : working directory of file\n file_name : file to be updated\n field_name : fileld to be updated in File\n field_value : value to be substituted\n \"\"\"\n file1 = os.path.join(parent_dir, file_name)\n file2 = os.path.join(parent_dir, \"temp\")\n match_pattern = \"{}\\=[\\d]+\".format(field_name)\n substitute = \"{}={}\".format(field_name, field_value)\n\n os.chmod(file1, 775)\n\n with open(file1, 'r') as fin, open(file2, 'w') as fout:\n for line in fin:\n pattern = re.sub(match_pattern, substitute, line)\n fout.write(pattern)\n\n os.remove(file1)\n os.rename(file2, file1)\n\n#SCONSTRUCT file interesting line\n# config.version = Version( \n# major=15,\n# minor=0,\n# point=6,\n# patch=0\n# )\ndef updateSconstruct():\n updateFile(parent_dir=os.path.join(os.environ[\"SourcePath\"],\"develop\",\"global\",\"src\"),\n file_name=\"SConstruct\",\n field_name=\"point\",\n field_value=os.environ['BuildNum'])\n\n# # VERSION file interesting line\n# ADLMSDK_VERSION_POINT=6\ndef updateVersion():\n updateFile(parent_dir=os.path.join(os.environ[\"SourcePath\"],\"develop\",\"global\",\"src\"),\n file_name=\"VERSION\",\n field_name=\"ADLMSDK_VERSION_POINT\",\n field_value=os.environ['BuildNum'])\n\n\ndef main():\n # updateSconstruct()\n # updateVersion()\n unittest.main()\n\n\n\nmain()","sub_path":"refactor.py","file_name":"refactor.py","file_ext":"py","file_size_in_byte":3569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"556785260","text":"#!/usr/bin/python\n# for bash we need to add the following to our .bashrc\n# export PYTHONPATH=$PYTHONPATH:$RMANTREE/bin \nimport getpass\nimport time,random\n# import the python renderman library\nimport prman\n\n\n\ndef Scene(ri) :\n\tri.AttributeBegin()\n\t\n\tface=[-0.1,-1,-3, 0.1,-1,-3,-0.1,-1,3, 0.1,-1,3]\n\trandom.seed(25)\n\tplank=-5.0\n\twhile (plank <=5.0) :\n\t\tri.TransformBegin()\n\t\tri.Color([random.uniform(0.2,0.4),random.uniform(0.1,0.25),0])\n\n\t\tc0=[random.uniform(-10,10),random.uniform(-10,10),random.uniform(-10,10)]\n\t\tc1=[random.uniform(-10,10),random.uniform(-10,10),random.uniform(-10,10)]\n\t\tri.Surface(\"wood\",{\"point c0\":c0,\"point c1\":c1,\"float grain\":random.randint(2,20)})\n\t\tri.Translate(plank,0,0)\n\t\tri.Patch(\"bilinear\",{'P':face})\n\t\tri.TransformEnd()\n\t\tplank=plank+0.206\n\tri.AttributeEnd()\n\tri.TransformBegin()\n\tri.AttributeBegin()\n\tri.Color([1,1,1])\n\tri.Translate( 0,-1.0,0)\n\tri.Rotate(-90,1,0,0)\n\tri.Rotate(36,0,0,1)\n\tri.Scale(0.4,0.4,0.4)\n\tri.Surface(\"plastic\")\n\tri.Geometry(\"teapot\")\n\tri.AttributeEnd()\n\tri.TransformEnd()\n\t\nri = prman.Ri() # create an instance of the RenderMan interface\nri.Option(\"rib\", {\"string asciistyle\": \"indented\"})\n\nfilename = \"Light1.rib\"\n# this is the begining of the rib archive generation we can only\n# make RI calls after this function else we get a core dump\nri.Begin(filename)\n# ArchiveRecord is used to add elements to the rib stream in this case comments\n# note the function is overloaded so we can concatinate output\nri.ArchiveRecord(ri.COMMENT, 'File ' +filename)\nri.ArchiveRecord(ri.COMMENT, \"Created by \" + getpass.getuser())\nri.ArchiveRecord(ri.COMMENT, \"Creation Date: \" +time.ctime(time.time()))\n\n# now we add the display element using the usual elements\n# FILENAME DISPLAY Type Output format\nri.Display(\"Light1.exr\", \"framebuffer\", \"rgba\")\n# Specify PAL resolution 1:1 pixel Aspect ratio\nri.Format(720,575,1)\n# now set the projection to perspective\nri.Projection(ri.PERSPECTIVE,{ri.FOV:50}) \n\ncolours ={\n\t\"red\":[1,0,0],\n\t\"white\":[1,1,1],\n\t\"green\":[0,1,0],\n\t\"blue\":[0,0,1],\n\t\"black\":[0,0,0],\n\t\"yellow\":[1,1,0]\n\t}\n\n\n# now we start our world\nri.WorldBegin()\nri.Attribute(\"trace\", {\"float bias\": 0.0001})\nri.Attribute(\"visibility\", {\"int trace\": 2})\nri.Attribute(\"visibility\", {\"int specular\": 2,\n\t\t\t\t\t\t\t\"int transmission\": 2})\nri.Translate(0,0,4)\nri.Rotate(-90,1,0,0)\nri.LightSource(\"distantlight\",{\"point from\":[0,2,0],\"point to\":[0,0,0]}) #\n\nScene(ri)\n\n\nri.WorldEnd()\n# and finally end the rib file\nri.End()\n","sub_path":"Lecture2Lighting/LightingExamples/Light1.py","file_name":"Light1.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"392321457","text":"'''\nCreated on Mar 8, 2015\n\n@author: NANSH\n'''\n\nimport re\nimport sys\n#import os\n#os.getcwd()\n\n## Entering the files as arguments : [1. WordAssociations.txt] [2. OriginalSentences.txt] [3. OuputFile.txt] \nassociations = sys.argv[1]\nfamilySentences = sys.argv[2]\noutput_File = sys.argv[3]\n\ndef kSpan(k): # k is the parameter where k = 3, 5, 10\n \n ## Opening the Word Associations File and Original Sentences file. \n with open(associations,'r') as in_file:\n wordSets = in_file.readlines() #Putting each sentence in wordSets\n \n with open(familySentences,'r') as sentFile:\n sentences = sentFile.readlines() #Putting each sentences in sentences data structure\n #sentences = str(sentences).lower() \n sentFile.close()\n \n countUnion = 0 #Total number of associations\n \n fout = open(output_File, 'w')\n \n for union in wordSets:\n countUnion += 1\n \n union = union.replace('(','')\n union = union.replace(')','')\n union = union.strip() #Trimming the spaces (leading and trailing) \n sack = union.split() #Store each word in union\n supp = sack[-1] #defining support as the format ['sentences', '(support)']\n del sack[-1] \n unionSet = set(sack) #Putting associations within a set\n \n count_Span = 0 #Counting associations within span\n counter = 0 # Counter for the association set found in sentence\n #check = False\n \n for sent in sentences:\n sent = sent.strip()\n regex = re.compile('[\\W_]+', re.U) # Only alphanumeric\n sent = re.sub(regex, \" \", sent, count=0, flags=0)\n \n wordList = sent.split() #split into list\n wordOrigin = set(wordList) #Putting words in a set\n \n if unionSet.issubset(wordOrigin): ## CHECK IF THE ASSOCIATION SET IS WITHIN ORIGINAL WORDS SET\n #check\n counter +=1 \n span = max(wordList.index(a) for a in sack) - min(wordList.index(a) for a in sack) + 1 ## DEFINING SPAN\n if span > 1 and span <= k:\n count_Span +=1 \n \"\"\"else:\n check = False\n break\"\"\"\n \n if count_Span > 0.4 * counter: ## CHECK IF THE ASSOCIATIONS ARE MORE FREQUENT THAN 40% \n #print unionSet\n fout.write(' '.join(unionSet) + '(' + str(supp) + ')' + \"\\n\") #write in the output file\n \n fout.close()\n in_file.close() \n \nkSpan(5) ##CHECK FOR VALUES K = 3, 5, 10","sub_path":"4. Identifying word associations for span k = 3, 5, 10/spanFilter_k=5.py","file_name":"spanFilter_k=5.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"361991793","text":"#!/usr/bin/env python3\n\n## import Paramiko for SSH, import OS for operating system\nimport paramiko, os\n\n## shortcut issuing commands to remote\ndef commandissue(command_to_issue):\n ssh_stdin, ssh_stdout, ssh_stderr = sshsession.exec_command(command_to_issue)\n return ssh_stdout.read()\n\n## list of targets\ndef gettargets():\n targetlist = []\n targetip = input(\"What IP address do you want to connect to? \")\n targetlist.append(targetip)\n targetuser = input(\"What UN would you like to use? \")\n targetlist.append(targetuser)\n return targetlist\n\n## Begin collecting information to connect.\nconnectionlist = []\nwhile(True):\n connectionlist.append(gettargets()) ## creds to connect\n zvarquit = input(\"Do you want to continue? (y/N): \")\n if (zvarquit.lower() == 'n') or (zvarquit == \"\"):\n break\n \n## prepare requirements file\n# reqlocation = input(\"Please provide the path to the requirements file to deploy: \")\nfile = input(\"what is the name of the requirements file? Press ENTER for default (requirements.txt): \")\nreqfileloc = input(\"where is the requirements file located? Press ENTER for default (./): \")\nif file == \"\":\n file = \"requirements.txt\"\n\nif reqfileloc == \"\":\n reqfileloc = \"./\"\n \nreqfile = reqfileloc + file\n \n## define SSH session\nsshsession = paramiko.SSHClient()\n\n############# IF YOU WANT TO CONNECT USING UN / PW #############\n#sshsession.connect(server, username=username, password=password)\n############## IF USING KEYS #################\n\n## mykey is our private key\nmykey = paramiko.RSAKey.from_private_key_file(\"/home/student/.ssh/id_rsa\")\n\n## if we never went to this SSH host, add the fingerprint to the known host file\nsshsession.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n \n## begin connection\nfor x in range(len(connectionlist)):\n sshsession.connect(hostname=connectionlist[x][0], username=connectionlist[x][1], pkey=mykey)\n ftp_client=sshsession.open_sftp()\n ftp_client.put(reqfile,reqfile)\n ftp_client.close()\n commandissue(\"sudo apt install python3-pip -y\") # ensure pip is installed\n commandissue(\"python3 -m pip install -r \" + reqfile)\n\n","sub_path":"paramikopip/deploypipch01.py","file_name":"deploypipch01.py","file_ext":"py","file_size_in_byte":2150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"71939621","text":"'''\nFunction that given a list of strings, returns the longest string chain that can\nbe built from those strings.\n\nA string chain is defined as a string \"A\" in the initial array - if removing any\nsingle character from string \"A\" yields a new string \"B\" that is in the initial\narray of strings, then \"A\" and \"B\" form a string chain. Similarly, if removing\nany single character in string \"B\", yields string \"C\" contained in the list\nof strings, it can also be part of the string chain.\n\nOnly one longest string chain can be possible in the input.\n'''\n# Complexity O(n * m^2 + n log(n)) time | O(nm) space\n# Where n is the number of strings in the list input\n# and m is the number of characters in the longest of the strings\n# Time complexity can be improved by n log(n) if we drop the strings sorting step\n# but this will require much more complexity, adding checks to see\n# if the shorter strings than the current iteration element have had their hash tables built\ndef longestStringChain(strings):\n stringChains = {}\n for string in strings:\n stringChains[string] = {\"nextString\": \"\", \"maxChainLength\": 1}\n sortedStrings = sorted(strings, key=len)\n for string in sortedStrings:\n findLongestStringChain(string, stringChains)\n \n return buildLongestStringChain(strings, stringChains)\n \n\ndef findLongestStringChain(string, stringChains):\n for i in range(len(string)):\n smallerString = getSmallerString(string, i)\n if smallerString not in stringChains:\n continue\n tryUpdateLongestStringChainLength(string, smallerString, stringChains)\n\ndef getSmallerString(string, index):\n return string[0:index] + string[index + 1 :]\n\ndef tryUpdateLongestStringChainLength(currentString, smallerString, stringChains):\n smallerStringChainLength = stringChains[smallerString][\"maxChainLength\"]\n currentStringChainLength = stringChains[currentString][\"maxChainLength\"]\n if smallerStringChainLength + 1 > currentStringChainLength:\n stringChains[currentString][\"maxChainLength\"] = smallerStringChainLength + 1\n stringChains[currentString][\"nextString\"] = smallerString\n\ndef buildLongestStringChain(strings, stringChains):\n maxChainLength = 0\n chainStartingString = \"\"\n for string in strings:\n if stringChains[string][\"maxChainLength\"] > maxChainLength:\n maxChainLength = stringChains[string][\"maxChainLength\"]\n chainStartingString = string\n\n ourLongestStringChain = []\n currentString = chainStartingString\n while currentString != \"\":\n ourLongestStringChain.append(currentString)\n currentString = stringChains[currentString][\"nextString\"]\n\n return [] if len(ourLongestStringChain) == 1 else ourLongestStringChain\n","sub_path":"AlgoExpert/longeststringchain.py","file_name":"longeststringchain.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"520197331","text":"import threading, sys\nprint = lambda x: sys.stdout.write(\"{}\\n\".format(x))\n\ncnt, num, limit = 0, 3, 10000\n\nclass AsyncCount(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n self.counter = 0\n def run(self):\n global cnt\n while self.counter < limit:\n self.counter += 1\n cnt += 1\n return\n\nthreads = [ AsyncCount() for n in range(num) ]\n[ t.start() for t in threads ]\n[ t.join() for t in threads ]\nprint(\"Expected: {}\".format(num * limit))\nprint(\"Received: {}\".format(cnt))\n\n# Expected: 30000\n# Received: 24573\n","sub_path":"python/examples/threads/counter_central.py","file_name":"counter_central.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"329577884","text":"# -*- coding: utf-8 -*-\n#\n# register.py\n#\n# purpose: Automagically creates a Rst README.txt\n# author: Filipe P. A. Fernandes\n# e-mail: ocefpaf@gmail\n# web: http://ocefpaf.github.io/\n# created: 10-Apr-2014\n# modified: Fri 11 Apr 2014 12:10:43 AM BRT\n#\n# obs: https://coderwall.com/p/qawuyq\n#\n\nimport os\nimport pandoc\n\nhome = os.path.expanduser(\"~\")\npandoc.core.PANDOC_PATH = os.path.join(home, 'bin', 'pandoc')\n\ndoc = pandoc.Document()\ndoc.markdown = open('README.md').read()\nwith open('README.txt', 'w+') as f:\n f.write(doc.rst)\n\n# Some modifications are need to README.txt before registering. Rendering this\n# part useless...\nif False:\n os.system(\"python2 setup.py register\")\n os.remove('README.txt')\n","sub_path":"register.py","file_name":"register.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"114858090","text":"\"\"\"Definition of the Promotion content type\n\"\"\"\n\nfrom zope.interface import implements\n\nfrom Products.Archetypes import atapi\nfrom Products.ATContentTypes.content import base\nfrom Products.ATContentTypes.content import schemata\n\nfrom evp.site.content import contentMessageFactory as _\nfrom evp.site.content.interfaces import IPromotion\nfrom evp.site.content.config import PROJECTNAME\n\nPromotionSchema = schemata.ATContentTypeSchema.copy() + atapi.Schema((\n\n atapi.TextField(\n name='promoarea1',\n required=False,\n language_independent = False,\n default_output_type = 'text/x-html-safe',\n widget=atapi.RichWidget(\n label=_(u'label_promo_area1', default=u'Promo Area Top'),\n description=_(u'help_promo_area1', default=u''),\n ),\n ),\n\n atapi.TextField(\n name='promoarea2',\n required=False,\n language_independent = True,\n default_output_type = 'text/x-html-safe',\n widget=atapi.RichWidget(\n label=_(u'label_promo_area2', default=u'Global Content'),\n description=_(u'help_promo_area2', default=u''),\n ),\n ),\n\n atapi.TextField(\n name='promoarea3',\n required=False,\n language_independent = False,\n default_output_type = 'text/x-html-safe',\n widget=atapi.RichWidget(\n label=_(u'label_promo_area3', default=u'Promo Area Bottom'),\n description=_(u'help_promo_area3', default=u''),\n ),\n ),\n\n atapi.StringField(\n name='remote_url',\n accessor='getRemoteUrl',\n language_independent = True,\n widget=atapi.StringWidget(\n label=_(u'label_remote_url', default=u'URL to remote site'),\n description=_(u'help_remote_url', \n default=u'Fill in for external promotions.'),\n ),\n ),\n atapi.StringField(\n name='facebook_like_id',\n required=False,\n widget=atapi.StringWidget(\n label=_(u\"Facebook Like Partner ID\"),\n description=_(u\"Adds a specific Partner ID to the like button\"),\n ),\n )\n\n))\n\n# Set storage on fields copied from ATContentTypeSchema, making sure they work\n# well with the python bridge properties. (I have no idea what this means, and\n# why annotation storage is used, but it got copied over from the old site by\n# mistake, and I think it's too late to change now, as content already exists\n# that use annotation storage. Sorry. //regebro)\n\nPromotionSchema['title'].storage = atapi.AnnotationStorage()\nPromotionSchema['description'].storage = atapi.AnnotationStorage()\nPromotionSchema['description'].required = True\nPromotionSchema['effectiveDate'].language_independent = True\nPromotionSchema['expirationDate'].language_independent = True\n\nschemata.finalizeATCTSchema(PromotionSchema, moveDiscussion=False)\n\nclass Promotion(base.ATCTContent):\n \"\"\"Promotion\"\"\"\n implements(IPromotion)\n\n portal_type = archetype_name = \"Promotion\"\n schema = PromotionSchema\n\n title = atapi.ATFieldProperty('title')\n description = atapi.ATFieldProperty('description')\n\nbase.registerType(Promotion, PROJECTNAME)\n","sub_path":"portfolio-work/ep-facebook-like/promotion.py","file_name":"promotion.py","file_ext":"py","file_size_in_byte":3149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"621377292","text":"from django.http import JsonResponse,HttpResponse\nfrom django.shortcuts import render,redirect,get_object_or_404\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\n\n\nfrom .forms import ReturForm,Retur\nfrom .filters import ReturFilter\nfrom login.views import logout\n\n# Create your views here.\n@login_required\ndef retur(request):\t\n\tdata = Retur.objects.all()\n\n\tFilter = ReturFilter(request.GET, queryset=data)\n\n\tdata = Filter.qs\n\n\tcontext = {\n\t\t'menu' : ['Input', 'Retur', 'Product', 'Setting'],\n\t\t'menu_name' : 'Retur',\n\t\t'page_title' : 'Retur',\n\t\t'button_class' : 'create-button',\n\t\t'data' : data,\n\t\t'Filter' : Filter,\n\t}\n\n\treturn render(request, 'retur.html', context)\n\n@login_required\ndef create_retur(request):\n\tform = ReturForm()\n\tif request.method == 'POST':\t\n\t\tform = ReturForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\treturn redirect('retur')\n\n\tcontext = {\n\t\t'menu' : ['Input', 'Retur', 'Product', 'Setting'],\n\t\t'menu_name' : 'Retur (Create)',\n\t\t'page_title' : 'Retur (Create)',\n\t\t'button_class1' : 'save-button',\n\t\t'button_class2' : 'cancel-button',\n\t\t'form' : form\n\t}\n\n\treturn render(request, 'create_retur.html', context)\n\n@login_required\ndef update_retur(request, pk):\n\tobj = Retur.objects.get(id=pk)\n\tform = ReturForm(instance=obj)\n\n\tif request.method == 'POST':\n\t\tform = ReturForm(request.POST, instance=obj)\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\tmessages.success(request, 'Your Retur Data Has Been Updated')\n\t\t\treturn redirect('retur')\n\n\tcontext = {\n\t\t'menu' : ['Input','Retur', 'Product', 'Setting'],\n\t\t'menu_name' : 'Retur (Update)',\n\t\t'page_title' : 'Retur (Update)',\n\t\t'button_class1' : 'save-button',\n\t\t'button_class2' : 'cancel-button',\n\t\t'retur' : obj,\n\t\t'form' : form,\n\t}\n\n\treturn render(request, 'create_retur.html', context)\n\n@login_required\ndef delete_retur(request, pk):\n\tdata = Retur.objects.all()\n\n\tobj = get_object_or_404(Retur, id=pk)\n\tform = ReturForm(instance=obj)\n\n\n\tif request.method == 'POST':\n\t\tobj.delete()\n\t\tmessages.success(request, 'Your Data Has Been Deleted')\n\t\treturn redirect('retur')\n\t\t\n\tcontext = {\n\t\t'menu' : ['Input','Retur','Product', 'Setting'],\n\t\t'page_title' : 'Retur (Delete)',\n\t\t'data' : data,\n\t\t'retur' : obj,\n\t\t'form' : form,\n\t}\n\n\treturn render(request, 'delete_retur.html', context)\n","sub_path":"retur/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"133994617","text":"\nclass System:\n\n \"\"\"Top-level object for molecular systems\n\n These objects are rarely created by the user, \n instead constructed automatically when parsing a \n coordinate file via amp.parsePDB or otherwise\"\"\"\n\n def __init__(self,name: str):\n\n self.name = name\n self.description = None\n self.chains = []\n\n self.bondlist=None\n self.box = None\n\n def autoname_chains(self,verbosity=1):\n \"\"\"Automatically name chains\"\"\"\n import mout\n\n pro_count = 0\n lig_count = 0\n dna_count = 0\n sol_count = 0\n\n for i,chain in enumerate(self.chains):\n if chain.type == 'PRO':\n if lig_count > 4:\n mout.warningOut(\"Too many protein chains!\")\n chain.name = 'P'\n else:\n chain.name = 'ABCDE'[pro_count]\n pro_count += 1\n elif chain.type == 'DNA':\n if lig_count > 3:\n mout.warningOut(\"Too many DNA chains!\")\n chain.name = 'X'\n else:\n chain.name = 'XYZ'[dna_count]\n dna_count += 1\n elif chain.type == 'LIG':\n if lig_count > 1:\n mout.warningOut(\"Multiple ligand chains!\")\n chain.name = 'L'\n lig_count += 1\n elif chain.type == 'SOL':\n if sol_count > 1:\n mout.warningOut(\"Multiple solvent chains!\")\n chain.name = 'W'\n sol_count += 1\n elif chain.type == 'ION':\n chain.name = chain.residues[0].name[0]\n\n if verbosity > 0 and chain.name in [c.name for c in self.chains[0:i]]:\n mout.warningOut(f\"Ambiguous naming! Multiple chains named {chain.name}!\")\n\n def check_indices(self):\n \"\"\"Print all child Atoms who's indices are incorrect\"\"\"\n\n for index,atom in enumerate(self.atoms):\n if index != atom.index:\n print(index,atom.index,atom.name,atom.residue)\n\n def fix_indices(self,verbosity=0):\n \"\"\"Fix all child Atoms' indices\"\"\"\n if verbosity:\n import mout\n exclude = ['SOL','ION']\n for index,atom in enumerate(self.atoms):\n if verbosity == 2 and atom.index != index:\n mout.warningOut(f\"Re-indexing atom {atom} (#{atom.index} --> #{index})\")\n elif verbosity == 1 and atom.type not in exclude and atom.index != index:\n mout.warningOut(f\"Re-indexing atom {atom} (#{atom.index} --> #{index})\")\n atom.index = index\n\n for index,residue in enumerate(self.residues):\n if verbosity == 2 and residue.number != index:\n mout.warningOut(f\"Re-indexing residue {residue} (#{residue.number} --> #{index})\")\n elif verbosity == 2 and residue.type not in exclude and residue.number != index:\n mout.warningOut(f\"Re-indexing residue {residue} (#{residue.number} --> #{index})\")\n residue.number = index\n\n residue.fix_names()\n residue.fix_indices()\n\n def clear_pdbindices(self):\n \"\"\"Clear all pdb indices from the system\"\"\"\n for atom in self.atoms:\n atom.pdb_index = None\n\n def fix_atomnames(self,verbosity=1):\n \"\"\"Attempt to fix all child Atom names\"\"\"\n import mout\n count=0\n for index,atom in enumerate(self.atoms):\n if atom.name[0].isnumeric():\n old = atom.name\n new = old[1:]+old[0]\n atom.set_name(new,verbosity=verbosity-1)\n if verbosity > 1:\n mout.out(old+\" -> \"+new)\n count+=1\n if verbosity > 0 and count != 0:\n mout.warningOut(\"Fixed \"+str(count)+\" atom names which appeared to have cycled.\")\n\n def add_chain(self,chain):\n \"\"\"Add a child Chain\"\"\"\n from .chain import Chain\n assert isinstance(chain,Chain)\n chain.index = len(self.chains)\n self.chains.append(chain)\n\n def add_system(self,system,same_chain=False):\n \"\"\"Merge another system to this one\"\"\"\n\n if same_chain:\n for residue in system.residues:\n self.chains[-1].add_residue(residue.copy())\n\n else:\n for chain in system.chains:\n self.add_chain(chain.copy())\n\n self.fix_indices()\n\n @property\n def bbox(self):\n \"\"\"Bounding box of the system\"\"\"\n import numpy as np\n x = [min([a.np_pos[0] for a in self.atoms]),max([a.np_pos[0] for a in self.atoms])]\n y = [min([a.np_pos[1] for a in self.atoms]),max([a.np_pos[1] for a in self.atoms])]\n z = [min([a.np_pos[2] for a in self.atoms]),max([a.np_pos[2] for a in self.atoms])]\n return [x,y,z]\n\n @property\n def bbox_sides(self):\n \"\"\"Bounding box of the system\"\"\"\n import numpy as np\n x = max([a.np_pos[0] for a in self.atoms])-min([a.np_pos[0] for a in self.atoms])\n y = max([a.np_pos[1] for a in self.atoms])-min([a.np_pos[1] for a in self.atoms])\n z = max([a.np_pos[2] for a in self.atoms])-min([a.np_pos[2] for a in self.atoms])\n return [x,y,z]\n\n @property\n def bbox_norm(self):\n \"\"\"Length of bounding box diagonal\"\"\"\n import numpy as np\n return np.linalg.norm([x[1]-x[0] for x in self.bbox])\n\n def check_intersection(self,system,radius=1,by_residue=True,boolean=False,chain=None):\n \"\"\"Return a list of indices that are intersecting within a given radius between this system and another.\"\"\"\n\n import mout\n import numpy as np\n\n indices = []\n\n if by_residue:\n\n if chain:\n residues = self.get_chain(chain).residues\n else:\n residues = self.residues\n\n system_CoM = system.CoM(verbosity=0)\n r_system = system.bbox_norm\n num_residues = len(residues)\n\n # for each residue\n for i,res in enumerate(residues):\n if num_residues > 5000 and i%100==0:\n mout.progress(i,num_residues,prepend=\"Calculating intersection\",append=\" of residues checked\")\n\n residue_CoM = res.CoM(verbosity=0)\n d = np.linalg.norm(residue_CoM-system_CoM)\n r_residue = res.bbox_norm\n \n if d > r_system + r_residue:\n continue\n\n for atom2 in system.atoms:\n \n if r_system > np.linalg.norm(residue_CoM-atom2.np_pos):\n continue\n\n for atom1 in res.atoms:\n\n if np.linalg.norm(atom1.np_pos - atom2.np_pos) <= radius:\n if boolean:\n return True\n else:\n indices.append(res.number)\n break\n\n if num_residues > 5000:\n mout.progress(num_residues,num_residues,prepend=\"Calculating intersection\",append=\" of residues checked. Done.\")\n\n else:\n\n if chain:\n atoms = self.get_chain(chain).atoms\n else:\n atoms = self.atoms\n\n for atom1 in self.atoms:\n for atom2 in system.atoms:\n if np.linalg.norm(atom1.np_pos - atom2.np_pos) <= radius:\n if boolean:\n return True\n else:\n indices.append(atom1.index)\n\n if boolean:\n return False\n else:\n return indices\n\n @property\n def num_atoms(self):\n \"\"\"Number of child Atoms (int)\"\"\"\n num_atoms = 0\n for chain in self.chains:\n num_atoms += chain.num_atoms\n return num_atoms\n\n @property\n def charge(self):\n \"\"\"Total charge (float)\"\"\"\n charge = 0\n for atom in self.atoms:\n charge += atom.charge\n return charge\n\n def summary(self,res_limit=10):\n \"\"\"Print a summary of the System\"\"\"\n import mout\n import mcol\n reset = mcol.clear+mcol.bold\n if self.description is not None:\n mout.headerOut(f'\\n\"{mcol.underline}{self.description}{reset}\"')\n mout.headerOut(\"\\nSystem \"+mcol.arg+self.name+\n mcol.clear+mcol.bold+\" contains \"+\n mcol.result+str(self.num_chains)+\n mcol.clear+mcol.bold+\" chains:\")\n for i,chain in enumerate(self.chains):\n mout.headerOut(f'Chain[{mcol.arg}{i}{reset}] {mcol.result}{chain.name}{reset} ({mcol.varType}{chain.type}{reset}) [#={mcol.result}{chain.num_atoms}{reset}] =',end=' ')\n\n if chain.type == \"PRO\":\n names = \"\"\n for r in chain.residues[:res_limit]:\n names += r.letter + \" \"\n if chain.num_residues > res_limit:\n names += \"...\"\n mout.out(names)\n else:\n names = \"\"\n for name in chain.res_names[:res_limit]:\n names += name+\" \"\n if chain.num_residues > res_limit:\n names += \"...\"\n mout.out(names)\n # mout.varOut(\"Total Charge\",self.charge)\n\n @property\n def num_chains(self):\n \"\"\"Number of child Chains (int)\"\"\"\n return len(self.chains)\n\n @property\n def chain_names(self):\n \"\"\"Get all Chain names (list)\"\"\"\n names = []\n for chain in self.chains:\n names.append(chain.name)\n return names\n\n def rename_atoms(self,old:str,new:str,res_filter:str=None,verbosity:int=2):\n \"\"\"Rename all matching atoms\"\"\"\n import mcol\n import mout\n count=0\n for residue in self.residues:\n if res_filter is not None and res_filter not in residue.name:\n continue\n for atom in residue.atoms:\n if atom.name == old:\n count += 1\n atom.set_name(new,verbosity=verbosity-1)\n if verbosity > 0:\n if res_filter is None:\n mout.warningOut(\"Renamed \"+mcol.result+str(count)+mcol.warning+\" atoms from \"+mcol.arg+old+\n mcol.warning+\" to \"+mcol.arg+new)\n else:\n mout.warningOut(\"Renamed \"+mcol.result+str(count)+mcol.warning+\" atoms from \"+mcol.arg+old+\n mcol.warning+\" to \"+mcol.arg+new+mcol.warning+\" with res_filter \"+mcol.arg+res_filter)\n return count\n\n def rename_residues(self,old:str,new:str,verbosity=2):\n \"\"\"Rename all matching residues\"\"\"\n import mcol\n import mout\n count=0\n for residue in self.residues:\n if residue.name == old:\n # residue.name = new\n residue.rename(new,verbosity=verbosity-1)\n count += 1\n if verbosity > 0:\n mout.warningOut(\"Renamed \"+mcol.result+str(count)+mcol.warning+\" residues from \"+mcol.arg+old+\n mcol.warning+\" to \"+mcol.arg+new)\n return count\n\n def get_chain(self,name:str):\n \"\"\"Get Chain by name\"\"\"\n import mout\n import mcol\n for chain in self.chains:\n if chain.name == name:\n return chain\n mout.errorOut(\"Chain with name \"+mcol.arg+name+mcol.error+\" not found.\",fatal=True)\n\n def remove_chain(self,name,verbosity=1):\n \"\"\"Delete Chain by name\"\"\"\n import mcol\n import mout\n for index,chain in enumerate(self.chains):\n if chain.name == name:\n if verbosity > 0:\n mout.warningOut(\"Removing chain \"+mcol.arg+name+str([index]))\n del self.chains[index]\n return chain\n mout.errorOut(\"Chain with name \"+mcol.arg+name+mcol.error+\" not found.\",fatal=True)\n \n def remove_heterogens(self,verbosity:int=1):\n \"\"\"Remove HETATM entries\"\"\"\n import mcol\n import mout\n del_list = []\n atoms = self.atoms\n for index,atom in enumerate(atoms):\n if atom.heterogen:\n del_list.append(index)\n number_deleted = self.remove_atoms_by_index(del_list,verbosity=verbosity-1)\n if verbosity > 0:\n mout.warningOut(\"Removed \"+mcol.result+str(number_deleted)+mcol.warning+\" heterogens\")\n\n def remove_atoms_by_index(self,del_list:list,verbosity:int=1):\n \"\"\"Remove Atoms by their index\"\"\"\n import mcol\n import mout\n\n number_deleted=0\n self.fix_indices()\n for chain in self.chains:\n for residue in chain.residues:\n for index,atom in reversed(list(enumerate(residue.atoms))):\n if atom.index in del_list:\n del residue.atoms[index]\n number_deleted += 1\n if verbosity > 1:\n mout.warningOut(\"Removed atom \"+\n mcol.arg+atom.name+str([atom.index])+\n mcol.warning+\" in residue \"+\n mcol.arg+residue.name+str([residue.number]))\n return number_deleted\n\n def remove_residues_by_index(self,del_list:list,verbosity:int=1):\n \"\"\"Remove Atoms by their index\"\"\"\n import mcol\n import mout\n\n number_deleted=0\n self.fix_indices()\n for chain in self.chains:\n for index,residue in reversed(list(enumerate(chain.residues))):\n if residue.number in del_list:\n del chain.residues[index]\n number_deleted += 1\n if verbosity > 1:\n mout.warningOut(\"Removed residue \"+\n mcol.arg+residue.name+str([residue.number])+\n mcol.warning+\" in chain \"+\n mcol.arg+chain.name)\n return number_deleted\n\n def get_atom_by_index(self,index:int,use_pdb_index:bool=True):\n \"\"\"Get Atom by its index\"\"\"\n for atom in self.atoms:\n if use_pdb_index:\n if atom.pdb_index == index:\n return atom\n else:\n if atom.index == index:\n return atom\n\n def remove_atoms(self,name:str,res_filter:str=None,verbosity:int=2):\n \"\"\"Remove Atoms by their name\"\"\"\n import mcol\n import mout\n\n number_deleted=0\n self.fix_indices()\n for chain in self.chains:\n for residue in chain.residues:\n if res_filter is not None and res_filter not in residue.name:\n continue\n for index,atom in reversed(list(enumerate(residue.atoms))):\n if atom.name == name:\n del residue.atoms[index]\n number_deleted += 1\n if verbosity > 1:\n mout.warningOut(\"Removed atom \"+\n mcol.arg+atom.name+str([atom.index])+\n mcol.warning+\" in residue \"+\n mcol.arg+residue.name+str([residue.number]))\n if verbosity > 0:\n if res_filter is None:\n mout.warningOut(\"Removed \"+mcol.result+str(number_deleted)+mcol.warning+\" atoms named \"+mcol.arg+name)\n else:\n mout.warningOut(\"Removed \"+mcol.result+str(number_deleted)+mcol.warning+\" atoms named \"+mcol.arg+name+mcol.warning+\" with res_filter \"+mcol.arg+res_filter)\n return number_deleted\n\n def atom_names(self,wRes=False,noPrime=False):\n \"\"\"Get all child Atom names (list)\"\"\"\n names_list = []\n for chain in self.chains:\n names_list += chain.atom_names(wRes=wRes,noPrime=noPrime)\n return names_list\n\n @property\n def atomic_numbers(self):\n \"\"\"Get all child Atom atomic numbers (list)\"\"\"\n number_list = []\n for chain in self.chains:\n number_list.append(chain.atomic_numbers)\n return number_list\n\n @property\n def positions(self):\n \"\"\"Get all child Atom positions (list)\"\"\"\n positions_list = []\n for chain in self.chains:\n positions_list += chain.positions\n return positions_list\n\n @property\n def charges(self):\n \"\"\"Get all child Atom charges (list)\"\"\"\n charges = []\n for chain in self.chains:\n charges += chain.charges\n return charges\n\n @property\n def symbols(self):\n \"\"\"Get all child Atom symbols (list)\"\"\"\n symbols = []\n for atom in self.atoms:\n symbols.append(atom.symbol) \n return symbols\n\n @property\n def masses(self):\n \"\"\"Get all child Atom masses (list)\"\"\"\n masses = []\n for chain in self.chains:\n masses += chain.masses\n return masses\n\n @property\n def atoms(self):\n \"\"\"Get all child Atoms (list)\"\"\"\n atoms = []\n for chain in self.chains:\n atoms += chain.atoms\n return atoms\n\n def centre_of_mass(self,set=None,shift=None):\n \"\"\"Calculate centre of mass\"\"\"\n return self.CoM(set=set,shift=shift)\n\n def center(self):\n \"\"\"Move the system's CoM to the origin\"\"\"\n return self.CoM(set=[0,0,0])\n\n def CoM(self,set=None,shift=None,verbosity=1):\n \"\"\"Calculate or manipulate the system's centre of mass. \n\n if not set and not shift: return CoM\n if set: move the System to the CoM\n if shift: move the System by the specified vector\"\"\"\n\n import mout\n import numpy as np\n\n position_list = self.positions\n\n centre_of_mass = np.array([sum([pos[0] for pos in position_list])/len(position_list),\n sum([pos[1] for pos in position_list])/len(position_list),\n sum([pos[2] for pos in position_list])/len(position_list)])\n\n if verbosity > 0: \n mout.varOut(\"CoM of \"+self.name,\n centre_of_mass,\n unit=\"Angstroms\",precision=4)\n\n if set is not None:\n\n assert np.ndim(set) == 1\n\n try:\n new_com = np.array([set[0],set[1],set[2]])\n except:\n mout.errorOut(\"Incompatible array input\",code=\"amp.system.CoM.1\")\n\n shift_com = new_com - centre_of_mass\n\n else:\n\n shift_com = np.array([0,0,0])\n\n if shift is not None:\n\n assert np.ndim(shift) == 1\n\n try:\n new_shift = np.array([shift[0],shift[1],shift[2]])\n except:\n mout.errorOut(\"Incompatible array input\",code=\"amp.system.CoM.2\")\n\n shift_com = shift_com + new_shift\n \n if set is not None or shift is not None:\n\n for atom in self.atoms:\n atom.position = atom.position + shift_com\n\n return centre_of_mass\n\n @property\n def QM_indices(self):\n \"\"\"Return list of Atom indices with the QM flag\"\"\"\n index_list = []\n for index,atom in enumerate(self.atoms):\n if atom.QM:\n index_list.append(index)\n return index_list\n\n @property\n def residues(self):\n \"\"\"Get all child Residues (list)\"\"\"\n residues = []\n for chain in self.chains:\n residues += chain.residues\n return residues\n\n @property\n def res_names(self):\n \"\"\"Get all child Residue names (list)\"\"\"\n return [res.name for res in self.residues]\n\n @property\n def num_residues(self):\n \"\"\"Get number of child Residue (int)\"\"\"\n return len(self.residues)\n\n @property\n def FF_atomtypes(self):\n \"\"\"Get all child Atom atomtypes (list)\"\"\"\n atomtype_list = []\n for chain in self.chains:\n atomtype_list += chain.FF_atomtypes\n return atomtype_list\n\n @property\n def ase_atoms(self):\n \"\"\"Construct an equivalent ase.Atoms object\"\"\"\n \n # from .io import write, read\n # write(\"__temp__.pdb\",self,verbosity=0)\n # return read(\"__temp__.pdb\",verbosity=0)\n from ase import Atoms\n return Atoms(symbols=self.symbols,cell=None, pbc=None,positions=self.positions)\n\n def write_CJSON(self,filename,use_atom_types=False,gulp_names=False):\n \"\"\"Export a CJSON\"\"\"\n from .io import writeCJSON\n writeCJSON(filename,self,use_atom_types=use_atom_types,gulp_names=gulp_names)\n\n def set_coordinates(self,reference):\n \"\"\"Set all coordinates according to a reference ase.Atoms object\"\"\"\n if type(reference) is str:\n from ase.io import read\n atoms = read(reference)\n elif isinstance(reference,list):\n for index,atom in enumerate(self.atoms):\n atom.position = reference[index]\n return\n else:\n atoms = reference\n\n for index,atom in enumerate(self.atoms):\n atom.position = atoms[index].position\n\n def rotate(self,angle,vector,center=(0,0,0)):\n \"\"\"Rotate the system (see ase.Atoms.rotate)\"\"\"\n ase_atoms = self.ase_atoms\n ase_atoms.rotate(angle,vector,center=center)\n self.set_coordinates(ase_atoms)\n\n def view(self,**kwargs):\n \"\"\"View the system with ASE\"\"\"\n from .gui import view\n view(self,**kwargs)\n\n def plot(self,ax=None,color=None,center_index=0,show=False,offset=None,padding=1,zeroaxis=None,frame=False,labels=True,textdict={\"horizontalalignment\":\"center\",\"verticalalignment\":\"center\"}):\n \"\"\"Render the system with matplotlib\"\"\"\n \n import numpy as np\n from ase.visualize.plot import plot_atoms\n\n # copy the system so as not to alter it\n copy = self.copy()\n\n # create new axes if none provided\n if ax is None:\n import matplotlib.pyplot as plt\n fig,ax = plt.subplots()\n\n # create colours list\n if color is not None:\n color = [color for a in copy.atoms]\n\n # create the canvas unit size from bounding box\n canvas = np.array(self.bbox_sides)*1.5\n\n # center the render if needed\n if offset is None:\n offset=[0,0]\n if center_index is not None:\n vec = - copy.atoms[center_index].np_pos + canvas\n copy.CoM(shift=vec,verbosity=0)\n\n # use ASE to render the atoms\n plot_atoms(copy.ase_atoms,ax,colors=color,offset=offset,bbox=[0,0,canvas[0]*2,canvas[1]*2])\n\n # do the labels\n if labels:\n for atom in copy.atoms:\n if atom.species != 'H':\n ax.text(atom.position[0],atom.position[1],atom.name,**textdict)\n\n # crop the plot\n xmax = copy.bbox[0][1] + padding\n xmin = copy.bbox[0][0] - padding\n ymax = copy.bbox[1][1] + padding\n ymin = copy.bbox[1][0] - padding\n ax.set_xlim(xmin,xmax)\n ax.set_ylim(ymin,ymax)\n\n # render the centering axes\n if zeroaxis is not None:\n ax.axvline(canvas[0],color=zeroaxis)\n ax.axhline(canvas[1],color=zeroaxis)\n\n if not frame:\n ax.axis('off')\n\n if show:\n plt.show()\n\n return ax, copy\n\n def plot3d(self,extra=[],alpha=1.0):\n\n import plotly.graph_objects as go\n\n all_atoms = self.atoms\n\n species = list(set(list(self.symbols)))\n\n from ase.data import vdw_radii, atomic_numbers\n from ase.data.colors import jmol_colors\n\n fig = go.Figure()\n\n for s in species:\n\n positions = [a.np_pos for a in self.atoms if a.symbol == s]\n x = [p[0] for p in positions]\n y = [p[1] for p in positions]\n z = [p[2] for p in positions]\n\n atomic_number = atomic_numbers[s]\n size = vdw_radii[atomic_number] * 15\n color = jmol_colors[atomic_number]\n color = (color[0]*256,color[1]*256,color[2]*256,alpha)\n\n trace = go.Scatter3d(x=x,y=y,z=z,mode='markers',name=s,marker=dict(size=size,color=f'rgba{color}',line=dict(color='black',width=2)))\n\n fig.add_trace(trace)\n\n print(extra)\n\n for i,(a,b) in enumerate(extra):\n\n print(i,a,b)\n\n trace = go.Scatter3d(x=[a[0],b[0]],y=[a[1],b[1]],z=[a[2],b[2]],name=f'extra[{i}]')\n\n fig.add_trace(trace)\n\n fig.show()\n\n return fig\n\n def auto_rotate(self):\n \"\"\"Rotate the system into the XY plane\"\"\"\n from .manipulate import auto_rotate\n ase_atoms = self.ase_atoms\n ase_atoms = auto_rotate(ase_atoms)\n self.set_coordinates(ase_atoms)\n\n def align_to(self,target):\n \"\"\"Minimise rotation w.r.t. a target\"\"\"\n from ase.build import minimize_rotation_and_translation\n if isinstance(target,System):\n target = target.ase_atoms\n atoms = self.ase_atoms\n minimize_rotation_and_translation(target,atoms)\n self.set_coordinates(atoms)\n return atoms\n\n def translate(self,displacement):\n \"\"\"Translate the system\"\"\"\n self.CoM(shift=displacement,verbosity=0)\n\n def align_by_posmap(self,map):\n\n \"\"\"Align the system to a target by superimposing three shared atoms:\n\n a --> A\n b --> B\n c --> C\n\n (a,b,c) are atoms from this system\n (A,B,C) are atoms from the target system\n\n map should contain Atoms: [[a,b,c],[A,B,C]]\n\n \"\"\"\n\n import numpy as np\n\n a = map[0][0]\n b = map[0][1]\n c = map[0][2]\n\n A = map[1][0]\n B = map[1][1]\n C = map[1][2]\n\n # TRANSLATION\n\n displacement = A - a\n self.translate(displacement)\n\n # ROTATION 1\n\n d = (b+c)/2\n D = (B+C)/2\n self.rotate(d-A.np_pos,D-A.np_pos,center=A.np_pos)\n\n # ROTATION 2\n\n d = (b+c)/2\n D = (B+C)/2\n\n v_bc = c - b\n v_BC = C - B\n\n def unit_vector(a):\n return a/np.linalg.norm(a)\n\n def remove_parallel_component(vector,reference):\n unit_reference = unit_vector(reference)\n projection = np.dot(vector,unit_reference)\n return vector - projection\n\n v_ad = d - a.np_pos\n v_bc_normal_to_ad = remove_parallel_component(v_bc, v_ad)\n v_BC_normal_to_ad = remove_parallel_component(v_BC, v_ad)\n self.rotate(v_bc_normal_to_ad, v_BC_normal_to_ad,center=A.np_pos)\n\n # extra stuff for plotly\n extra = [[A.np_pos,A.np_pos+v_ad]]\n return extra\n\n def align_by_pairs(self,target,index_pairs,alt=False):\n \"\"\"Align the system (i) to the target (j) by consider the vectors:\n\n a --> b\n a --> c\n\n where index pairs contains the indices for the three atoms: \n a,b,c in the respective systems:\n\n index_pairs = [[i_a,j_a],[i_b,j_b],[i_c,j_c]]\n\n Alternatively you can pass the positions j_a, j_b, j_c as target,\n and index_pairs can be i_a, i_b, i_c.\n \"\"\"\n\n assert len(index_pairs) == 3\n import numpy as np\n\n if isinstance(target,System):\n for pair in index_pairs:\n assert self.atoms[pair[0]].name == target.atoms[pair[1]].name\n\n pos_0_0 = self.atoms[index_pairs[0][0]].np_pos\n pos_1_0 = self.atoms[index_pairs[1][0]].np_pos\n pos_2_0 = self.atoms[index_pairs[2][0]].np_pos\n\n pos_0_1 = target.atoms[index_pairs[0][1]].np_pos\n pos_1_1 = target.atoms[index_pairs[1][1]].np_pos\n pos_2_1 = target.atoms[index_pairs[2][1]].np_pos\n\n else:\n\n pos_0_0 = self.atoms[index_pairs[0]].np_pos\n pos_1_0 = self.atoms[index_pairs[1]].np_pos\n pos_2_0 = self.atoms[index_pairs[2]].np_pos\n\n pos_0_1 = target[0]\n pos_1_1 = target[1]\n pos_2_1 = target[2]\n\n vec = pos_0_1 - pos_0_0\n self.CoM(shift=vec,verbosity=0)\n\n a = pos_1_0 - pos_0_0\n b = pos_1_1 - pos_0_1\n self.rotate(a,b,pos_0_1)\n\n a = pos_1_0 - pos_0_0\n a_hat = a/np.linalg.norm(a)\n\n b = pos_2_0 - pos_0_0\n c = pos_2_1 - pos_0_1\n d = b - np.dot(a,b)*a_hat\n e = c - np.dot(a,c)*a_hat\n\n d_hat = d/np.linalg.norm(d)\n e_hat = e/np.linalg.norm(e)\n ang = np.arccos(np.clip(np.dot(d_hat, e_hat), -1.0, 1.0))\n\n if alt:\n self.rotate((ang/np.pi*180),a,pos_0_1)\n else:\n self.rotate(-(90-ang/np.pi*180),a,pos_0_1)\n\n def guess_names(self,target):\n \"\"\"Try and set the atom names of the system by looking for \n the closest atom of the same species in the target system\"\"\"\n\n import numpy as np\n\n positions = [b.np_pos for b in target.atoms]\n species = [b.species for b in target.atoms]\n\n for a in self.atoms:\n a_pos = a.np_pos\n distances = [np.linalg.norm(a_pos - p) if s == a.species else 999 for s,p in zip(species,positions)]\n index = np.argmin(distances)\n b = target.atoms[index]\n a.set_name(b.name,verbosity=0)\n\n def rmsd(self,reference):\n \"\"\"Calculate the RMS displacement between this system and a reference\"\"\"\n \n import numpy as np\n assert len(self.atoms) == len(reference.atoms)\n displacements = np.array([np.linalg.norm(a.np_pos-b.np_pos) for a,b in zip(self.atoms,reference.atoms)])\n return np.sqrt(np.mean(displacements**2))\n\n def reorder_atoms(self,reference,map:dict=None):\n new_sys = self.copy()\n for atom in reference.atoms:\n res = self.get_residue(atom.residue,map=map)\n new_sys.add_atom(res.get_atom(atom.name).copy())\n new_sys.fix_indices()\n self = new_sys\n\n def get_residue(self,name:str,map:dict=None):\n \"\"\" return residues with matching name\"\"\"\n import mout\n if map is not None:\n if name in map.keys():\n name = map[name]\n matches = [r for r in self.residues if r.name == name]\n if len(matches) == 0:\n mout.errorOut(f\"No residue found with name {name}\")\n return []\n elif len(matches) == 1:\n return matches[0]\n else:\n mout.warning(f\"Multiple residues found with name {name}\")\n return matches\n\n def copy(self,disk=False,alt=False):\n \"\"\"Return a deepcopy of the System\"\"\"\n if disk:\n from .io import write, parseGRO\n write(f\"__temp__.gro\",self,verbosity=0)\n system = parseGRO(f\"__temp__.gro\",verbosity=0)\n system.name = self.name\n return system\n elif alt:\n if self.num_chains != len(set([str(c) for c in self.chains])):\n import mout\n mout.errorOut(\"System has duplicate chain names so this copying method will have incorrect chains!\")\n copy_system = System(self.name + \" (copy)\")\n copy_system.box = self.box\n for atom in self.atoms:\n copy_system.add_atom(atom)\n return copy_system\n else:\n import copy\n return copy.deepcopy(self)\n\n def subsystem(self,indices,use_pdb_index=True):\n \"\"\"Extract a subset of the system by the atom indices\"\"\"\n\n new_system = System(self.name+\" (filtered)\")\n new_system.box = self.box\n\n for index in indices:\n\n atom = self.get_atom_by_index(index,use_pdb_index=use_pdb_index)\n\n # print(index,atom)\n if atom is None:\n continue\n\n new_system.add_atom(atom)\n\n return new_system\n\n def add_atom(self,atom):\n \"\"\"add an atom to the system\"\"\"\n from .chain import Chain\n from .residue import Residue, res_type\n\n if self.chains and atom.chain == self.chains[-1].name and res_type(atom.residue) == self.chains[-1].residues[-1].type:\n self.chains[-1].add_atom(atom)\n else:\n chain = Chain(atom.chain)\n chain.add_atom(atom)\n self.add_chain(chain)\n\n def __repr__(self):\n return self.name\n def __str__(self):\n return self.name\n","sub_path":"asemolplot/system.py","file_name":"system.py","file_ext":"py","file_size_in_byte":28595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"240772597","text":"# Copyright (c) nexB Inc. and others. All rights reserved.\n# http://nexb.com and https://github.com/nexB/vulnerablecode/\n# The VulnerableCode software is licensed under the Apache License version 2.0.\n# Data generated with VulnerableCode require an acknowledgment.\n#\n# You may not use this software except in compliance with the License.\n# You may obtain a copy of the License at: http://apache.org/licenses/LICENSE-2.0\n# Unless required by applicable law or agreed to in writing, software distributed\n# under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations under the License.\n#\n# When you publish or redistribute any data created with VulnerableCode or any VulnerableCode\n# derivative work, you must accompany this data with the following acknowledgment:\n#\n# Generated with VulnerableCode and provided on an \"AS IS\" BASIS, WITHOUT WARRANTIES\n# OR CONDITIONS OF ANY KIND, either express or implied. No content created from\n# VulnerableCode should be considered or used as legal advice. Consult an Attorney\n# for any legal advice.\n# VulnerableCode is a free software tool from nexB Inc. and others.\n# Visit https://github.com/nexB/vulnerablecode/ for support and download.\n\nimport dataclasses\nfrom xml.etree import ElementTree\n\nimport requests\nfrom packageurl import PackageURL\n\nfrom vulnerabilities.data_source import Advisory\nfrom vulnerabilities.data_source import DataSource\nfrom vulnerabilities.data_source import DataSourceConfiguration\nfrom vulnerabilities.helpers import create_etag\n\n\n@dataclasses.dataclass\nclass ApacheHTTPDDataSourceConfiguration(DataSourceConfiguration):\n etags: dict\n\n\nclass ApacheHTTPDDataSource(DataSource):\n\n CONFIG_CLASS = ApacheHTTPDDataSourceConfiguration\n url = \"https://httpd.apache.org/security/vulnerabilities-httpd.xml\"\n\n def updated_advisories(self):\n # Etags are like hashes of web responses. We maintain\n # (url, etag) mappings in the DB. `create_etag` creates\n # (url, etag) pair. If a (url, etag) already exists then the code\n # skips processing the response further to avoid duplicate work\n\n if create_etag(data_src=self, url=self.url, etag_key=\"ETag\"):\n data = fetch_xml(self.url)\n advisories = to_advisories(data)\n return self.batch_advisories(advisories)\n\n return []\n\n\ndef to_advisories(data):\n advisories = []\n for issue in data:\n resolved_packages = []\n impacted_packages = []\n for info in issue:\n if info.tag == \"cve\":\n cve = info.attrib[\"name\"]\n\n if info.tag == \"title\":\n summary = info.text\n\n if info.tag == \"fixed\":\n resolved_packages.append(\n PackageURL(type=\"apache\", name=\"httpd\", version=info.attrib[\"version\"])\n )\n\n if info.tag == \"affects\" or info.tag == \"maybeaffects\":\n impacted_packages.append(\n PackageURL(type=\"apache\", name=\"httpd\", version=info.attrib[\"version\"])\n )\n\n advisories.append(\n Advisory(\n cve_id=cve,\n summary=summary,\n impacted_package_urls=impacted_packages,\n resolved_package_urls=resolved_packages,\n )\n )\n\n return advisories\n\n\ndef fetch_xml(url):\n resp = requests.get(url).content\n return ElementTree.fromstring(resp)\n","sub_path":"vulnerabilities/importers/apache_httpd.py","file_name":"apache_httpd.py","file_ext":"py","file_size_in_byte":3555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"361337559","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import HttpResponse, request, request\nfrom .forms import TaskForm, WorkerForm, JobForm, AggregatorForm\nfrom django.db import IntegrityError\nimport datetime\nfrom datetime import date\nfrom django.db.models import Sum, Count\nimport collections\nfrom django.conf import settings\nfrom django.contrib.auth.decorators import login_required\nfrom django.template import Context\n\nfrom .models import Task, Worker, Job\n\n\n# @login_required\ndef index(request):\n return render(request, 'proj_2/index.html')\n\n\ndef login(request):\n if request.user.is_authenticated():\n redirect('index.html')\n return HttpResponse(\"Hello world, this is login\")\n\n\n# Create your views here.\n\ndef tasks(request, message='', context={}):\n tasks_to_render = Task.objects.order_by(\"task_code\")\n context['tasks'] = tasks_to_render\n if message:\n context['message'] = message\n if not 'form' in context:\n context['form'] = TaskForm()\n print(context)\n return render(request, 'proj_2/tasks.html', context)\n\n\ndef task_submit_form(request):\n if request.method == 'POST':\n form = TaskForm(request.POST)\n if form.is_valid():\n if 'id' in form.cleaned_data and not form.cleaned_data['id'] == '':\n task = get_object_or_404(Task, pk=form.cleaned_data['id'])\n else:\n task = Task()\n task.task_code = form.cleaned_data['task_code'].upper()\n task.wage = form.cleaned_data['wage']\n try:\n task.save()\n except IntegrityError as e:\n return tasks(request, message='Błąd! Powielenie kodu czynności')\n print(task.__str__())\n\n return tasks(request, 'Success')\n else:\n print('INVALID')\n print(form.errors)\n return tasks(request, 'Failed')\n\n\ndef task_edit(request, task_id):\n task = get_object_or_404(Task, pk=task_id)\n initials = {'task_code': task.task_code, 'wage': task.wage, 'id': task.id}\n form = TaskForm(initial=initials)\n form.fields['task_code'].widget.attrs['readonly'] = True\n context = {'form': form, 'edit': 1}\n return tasks(request, context=context)\n\n\ndef task_erase(request, task_id):\n task = get_object_or_404(Task, pk=task_id)\n task.delete()\n return tasks(request, 'deleted task')\n\n\ndef worker_submit_form(request):\n if request.method == 'POST':\n form = WorkerForm(request.POST)\n if form.is_valid():\n if 'id' in form.cleaned_data and not form.cleaned_data['id'] == '':\n worker = get_object_or_404(Worker, pk=form.cleaned_data['id'])\n else:\n worker = Worker()\n worker.name = form.cleaned_data['name'].upper()\n worker.save()\n return workers(request, 'Success')\n return workers(request, 'Failed')\n\n\ndef worker_edit(request, worker_id):\n worker = get_object_or_404(Worker, pk=worker_id)\n print(worker)\n initials = {'name': worker.name, 'id': worker.id}\n form = WorkerForm(initial=initials)\n context = {'form': form, 'edit': 1}\n return workers(request, context=context)\n\n\ndef worker_erase(request, worker_id):\n worker = get_object_or_404(Worker, pk=worker_id)\n worker.delete()\n return workers(request, 'deleted worker')\n\n\ndef workers(request, message='', context={}):\n workers_to_render = Worker.objects.all()\n context['workers'] = workers_to_render\n if message:\n context['message'] = message\n if not 'form' in context:\n context['form'] = WorkerForm(initial={'date': datetime.date.today()})\n\n return render(request, 'proj_2/workers.html', context)\n\n\ndef job_submit_form(request):\n if request.method == 'POST':\n form = JobForm(request.POST)\n print(form.data)\n if form.data['task_code_combobox']:\n task_code_id = form.data['task_code_combobox']\n elif form.data['task_code_field']:\n task_code_id = 1\n else:\n return jobs(request, 'Brak kodu czynności')\n\n if form.data['worker_combobox']:\n worker_id = form.data['worker_combobox']\n elif form.data['worker_field']:\n worker_id = 1\n else:\n return jobs(request, 'Brak pracownika')\n\n if form.data['count']:\n count = form.data['count']\n else:\n return jobs(request, 'Brak ilości')\n\n if form.data['date']:\n date = form.data['date']\n else:\n date = datetime.date.today()\n\n if 'id' in form.data and not form.data['id'] == '':\n job = get_object_or_404(Job, pk=form.data['id'])\n job.count = count\n job.date = date\n job.person_id = worker_id\n job.task_code_id = task_code_id\n else:\n job = Job(task_code_id=task_code_id, person_id=worker_id, count=count, date=date)\n job.save()\n\n return jobs(request, 'Success')\n return jobs(request, 'Failed')\n\n\ndef job_edit(request, job_id):\n job = get_object_or_404(Job, pk=job_id)\n print(job)\n initials = {'worker_combobox': job.person_id,\n 'task_code_combobox': job.task_code_id,\n 'count': job.count,\n 'date': job.date,\n 'id': job.id}\n form = JobForm(initial=initials)\n context = {'form': form, 'edit': 1}\n return jobs(request, context=context)\n\n\ndef job_erase(request, job_id):\n job = get_object_or_404(Job, pk=job_id)\n job.delete()\n return jobs(request, 'deleted job')\n\n\ndef jobs(request, message='', context={}):\n jobs_to_render = Job.objects.all()\n context['jobs'] = jobs_to_render\n if message:\n context['message'] = message\n if not 'form' in context:\n context['form'] = JobForm()\n return render(request, \"proj_2/jobs.html\", context)\n\n\ndef aggregator(request, message='', context={}):\n if message:\n context['message'] = message\n if 'forn' not in context:\n context['form'] = AggregatorForm(\n initial={'startdate': date(date.today().year, date.today().month, 1), 'enddate': date.today()})\n return render(request, \"proj_2/aggregator.html\", context)\n\n\ndef aggregator_form(request):\n if request.method == 'GET':\n\n form = AggregatorForm(request.GET)\n if form.is_valid():\n print('valided', form.cleaned_data)\n context = {}\n workers = []\n task_summary = collections.defaultdict(dict)\n if form.cleaned_data['all_workers']:\n workers_to_search = Worker.objects.order_by(\"name\")\n else:\n workers_to_search = form.cleaned_data['workers']\n if form.cleaned_data['all_tasks']:\n all = Task.objects.order_by(\"task_code\")\n tasks_to_search = []\n for a in all:\n tasks_to_search += [a.id]\n else:\n all = form.cleaned_data['tasks']\n tasks_to_search = []\n for a in all:\n task = Task.objects.get(task_code=a)\n tasks_to_search += [task.id]\n print('Workers to search: ', workers_to_search)\n print('Tasks to search: ', tasks_to_search)\n for w in workers_to_search:\n sum_overall = 0\n worker = {'name': w}\n tasks_ = []\n res = Job.objects.filter(person__name=w) \\\n .filter(date__lte=form.cleaned_data['enddate']) \\\n .filter(date__gte=form.cleaned_data['startdate']) \\\n .values('task_code') \\\n .annotate(Count('count'), Sum('count'))\n print('Results: ', res)\n for r in res:\n if not r['task_code'] in tasks_to_search:\n continue\n count = r['count__count']\n task_code_id = r['task_code']\n sum_of_count = r['count__sum']\n task = get_object_or_404(Task, pk=task_code_id)\n sum = sum_of_count * task.wage\n\n if 'task_code' not in task_summary[task.task_code]:\n task_summary[task.task_code]['task_code'] = task.task_code\n\n if 'count' in task_summary[task.task_code]:\n task_summary[task.task_code]['count'] += count\n else:\n task_summary[task.task_code]['count'] = count\n\n if 'sum_of_count' in task_summary[task.task_code]:\n task_summary[task.task_code]['sum_of_count'] += sum_of_count\n else:\n task_summary[task.task_code]['sum_of_count'] = sum_of_count\n\n if 'sum' in task_summary[task.task_code]:\n task_summary[task.task_code]['sum'] += sum\n else:\n task_summary[task.task_code]['sum'] = sum\n\n # task = Task.objects.get(task_code=task_code_id)\n sum_overall += sum\n tasks_ += [{'task_code': task.task_code, 'count': count, 'sum': sum, 'sum_of_count': sum_of_count}]\n worker['tasks'] = tasks_\n worker['sum_overall'] = sum_overall\n workers += [worker]\n final_task_summary = []\n for t in task_summary:\n final_task_summary += [{'task_code': task_summary[t]['task_code'],\n 'count': task_summary[t]['count'],\n 'sum_of_count':task_summary[t]['sum_of_count'],\n 'sum':task_summary[t]['sum']}]\n context['workers'] = workers\n print(task_summary)\n context['tasks_summary'] = final_task_summary\n return aggregator(request, message='Alles Gut', context=context)\n else:\n print(form.errors)\n return aggregator(request, message='Not valid')\n return aggregator(request, message='Not GET')\n\n#\n# class TaskInSummary\n# task_code = ''\n# count = 0\n# sum = 0\n# sum_of_count = 0\n","sub_path":"project/proj_2/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"569169436","text":"\"\"\"\njutge package for alternative input handling.\nsee https://github.com/jutge-org/jutge-python\n\"\"\"\n\nfrom jutge.reader.tokenizer import *\n\nversion = \"2.2\" # current version\n\n# Specify what to import with *:\n__all__ = [\n 'read', 'read_many',\n 'read_line', 'read_many_lines',\n 'set_eof_handling', 'EOFModes'\n]\n","sub_path":"jutge/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"463670801","text":"import json\nimport boto3\n\ndef lambda_handler(event, context):\n s3 = boto3.client('s3')\n body = json.dumps({'doUnlock': True})\n response = s3.put_object(Body=body, Bucket='doorunlockstatus', Key='status.txt')\n\n return {\n \"statusCode\": 200,\n \"body\": json.dumps('Set Unlock value to 1')\n }\n","sub_path":"src/request_unlock_lambda.py","file_name":"request_unlock_lambda.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"493957108","text":"# -*- coding: utf-8 -*-\nfrom typing import List\n\n\ndef countGoodTriplets(arr: List[int], a: int, b: int, c: int) -> int:\n count = 0\n for i in range(len(arr) - 2):\n for j in range(i + 1, len(arr) - 1):\n for k in range(j + 1, len(arr)):\n if abs(arr[i] - arr[j]) <= a and abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c:\n count += 1\n return count\n\n\nif __name__ == '__main__':\n arr = [7, 3, 7, 3, 12, 1, 12, 2, 3]\n a = 5\n b = 8\n c = 1\n print(countGoodTriplets(arr, a, b, c))\n","sub_path":"bricks/1534.py","file_name":"1534.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"490573496","text":"\nimport os\nimport subprocess as sp\nimport csv\nimport time\n\nwaf = \"../waf\"\ndir_res = \"xres/\"\ndir_exp = \"e\"\n\n# Read settings\nwith open('Metricsv2.csv', encoding='UTF-8') as csvfile:\n\taux = csv.reader(csvfile, delimiter=';')\n\tnext(aux) # ignore header\n\tfor row in aux:\n\t\t#print(\" \".join(row))\n\t\tbie = row[0].encode('utf-8').strip() #[\"ExpID\"]\n\t\tbcmd_exec = row[27].encode('utf-8').strip() #[\"cmd\"]\n\t\tstatus = row[2].encode('utf-8').strip() #[\"Status\"]\n\t\tie = bie.decode('utf-8')\n\t\tcmd_exec = bcmd_exec.decode('utf-8')\n\t\ts_status = status.decode('utf-8')\n\n\t\t#print(ie)\n\t\t#print(bie)\n\t\t#aie = int(ie)\n\t\tif (len(s_status)>0):\n\t\t\tprint(\"ignoring\" + str(ie) + \"with \" + s_status )\n\t\t\tcontinue\n\t\tprint(\"Running \" + str(ie))\n\n#for ie in ('01', '02', '03', '04'):\n\t\t# create dir for results\n\t\tdirExp = dir_res + dir_exp + ie\n\t\tidExp = dir_exp + ie\n\n\t\tif (not os.path.exists(dirExp)):\n\t\t\tprint(\"to create dir \" + dirExp)\n\t\t\tos.mkdir(dirExp)\n\n\t\t#run the command\n\t\t#cmd_exec = \"./waf --run \\\"critical_MCS --duration=10 --dataRate=60000 --technology=0 --numAp=1 --numSta=2 --enableObssPd=1 --powSta=18 --powAp=23 --ccaEdTrSta=-62 --ccaEdTrAp=-62 --rxSensSta=-54 --rxSensAp=-99 --mcs=11 --udp=1 --batteryLevel=200 --distance=20--TCPpayloadSize=150 --UDPpayloadSize=64 --frequency=2 --channelWidth=20 --numTxSpatialStreams=1 --numRxSpatialStreams=1 --numAntennas=4 --voice=true \\\"\"\n\t\t#cmd_exec = \"time \" + cmd_exec\n\t\tprint(cmd_exec)\n\t\tlog_file = \"alogExp_\" +idExp\n\t\twith open(log_file, \"w\") as outfile:\n\t\t\tstart = time.time()\n\t\t\tsp.run(cmd_exec, shell=True, check=True, stdout=outfile)\n\t\t\telpased = time.time() - start\n\t\t\tprint(\"Time:\" + str(elpased))\n\n\n\t\t#Parse Flow results\n\t\tcmd_exec = \"python runSimulationParser.py testflow.xml \"\n\t\tsp.run(cmd_exec, shell=True, check=True)\n\n\t\t#put results in the dir\n\t\tif (os.path.exists(dirExp)):\n\t\t\tcmd_exec = \"mv FI* testflow.xml alogExp_e* flow_output.txt \" + dirExp + \"/\"\n\t\t\tprint(cmd_exec)\n\t\t\tsp.run(cmd_exec, shell=True, check=True)\n","sub_path":"old code/runScripts/runSimulationv2.py","file_name":"runSimulationv2.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"32158811","text":"# Copyright (C) 2019 Bloomberg LP\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# \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\"\"\"Add index\n\nRevision ID: 8a0dbc05b5b0\nRevises: 26570f8fa002\nCreate Date: 2019-10-01 10:23:27.720996\n\n\"\"\"\nfrom datetime import datetime\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '8a0dbc05b5b0'\ndown_revision = '26570f8fa002'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.create_table(\n 'index',\n sa.Column('digest_hash', sa.String(), nullable=False),\n sa.Column('digest_size_bytes', sa.Integer(), nullable=False),\n sa.Column('accessed_timestamp', sa.DateTime(), nullable=False),\n sa.PrimaryKeyConstraint('digest_hash')\n )\n op.create_index(op.f('ix_index_digest_hash'),\n 'index', ['digest_hash'], unique=True)\n op.create_index(op.f('ix_index_accessed_timestamp'),\n 'index', ['accessed_timestamp'], unique=False)\n\n\ndef downgrade():\n op.drop_index(op.f('ix_index_accessed_timestamp'), table_name='index')\n op.drop_index(op.f('ix_index_digest_hash'), table_name='index')\n op.drop_table('index')\n","sub_path":"buildgrid/server/persistence/sql/alembic/versions/8a0dbc05b5b0_add_index.py","file_name":"8a0dbc05b5b0_add_index.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"499975208","text":"# 6190 / find max number of multipled 2 numbers which is monotonic increase\nfor T in range(int(input())):\n N = int(input())\n nums = list(map(int, input().split()))\n\n maxN = -1\n for i in range(N - 1):\n for j in range(i + 1, N):\n temp = str(nums[i] * nums[j])\n # if len of number is not 1, check monotonic increse or not\n if len(temp) != 1:\n for l in range(len(temp) - 1):\n if int(temp[l]) > int(temp[l + 1]):\n break\n else:\n if maxN < int(temp):\n maxN = int(temp)\n\n print(f'#{T + 1} {maxN}')\n ","sub_path":"D3/6190.py","file_name":"6190.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"24644228","text":"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"The Active-Space Reduction interface.\"\"\"\n\nimport logging\n\nfrom copy import deepcopy\nfrom typing import List, Optional, Tuple, Union, cast\n\nimport numpy as np\n\nfrom qiskit_nature import QiskitNatureError\nfrom qiskit_nature.properties import GroupedProperty, Property\nfrom qiskit_nature.properties.second_quantization import (\n SecondQuantizedProperty,\n GroupedSecondQuantizedProperty,\n)\nfrom qiskit_nature.properties.second_quantization.electronic import ParticleNumber\nfrom qiskit_nature.properties.second_quantization.electronic.bases import (\n ElectronicBasis,\n ElectronicBasisTransform,\n)\nfrom qiskit_nature.properties.second_quantization.electronic.integrals import (\n IntegralProperty,\n OneBodyElectronicIntegrals,\n)\nfrom qiskit_nature.properties.second_quantization.electronic.types import GroupedElectronicProperty\nfrom qiskit_nature.results import ElectronicStructureResult\n\nfrom ..base_transformer import BaseTransformer\n\nlogger = logging.getLogger(__name__)\n\n\nclass ActiveSpaceTransformer(BaseTransformer):\n r\"\"\"The Active-Space reduction.\n\n The reduction is done by computing the inactive Fock operator which is defined as\n :math:`F^I_{pq} = h_{pq} + \\sum_i 2 g_{iipq} - g_{iqpi}` and the inactive energy which is\n given by :math:`E^I = \\sum_j h_{jj} + F ^I_{jj}`, where :math:`i` and :math:`j` iterate over\n the inactive orbitals.\n By using the inactive Fock operator in place of the one-electron integrals, `h1`, the\n description of the active space contains an effective potential generated by the inactive\n electrons. Therefore, this method permits the exclusion of non-core electrons while\n retaining a high-quality description of the system.\n\n For more details on the computation of the inactive Fock operator refer to\n https://arxiv.org/abs/2009.01872.\n\n The active space can be configured in one of the following ways through the initializer:\n - when only `num_electrons` and `num_molecular_orbitals` are specified, these integers\n indicate the number of active electrons and orbitals, respectively. The active space will\n then be chosen around the Fermi level resulting in a unique choice for any pair of\n numbers. Nonetheless, the following criteria must be met:\n\n #. the remaining number of inactive electrons must be a positive, even number\n\n #. the number of active orbitals must not exceed the total number of orbitals minus the\n number of orbitals occupied by the inactive electrons\n\n - when, in addition to the above, `num_alpha` is specified, this can be used to disambiguate\n the active space in systems with non-zero spin. Thus, `num_alpha` determines the number of\n active alpha electrons. The number of active beta electrons can then be determined based\n via `num_beta = num_electrons - num_alpha`. The same requirements as listed in the\n previous case must be met.\n - finally, it is possible to select a custom set of active orbitals via their indices using\n `active_orbitals`. This allows selecting an active space which is not placed around the\n Fermi level as described in the first case, above. When using this keyword argument, the\n following criteria must be met *in addition* to the ones listed above:\n\n #. the length of `active_orbitals` must be equal to `num_molecular_orbitals`.\n\n #. the sum of electrons present in `active_orbitals` must be equal to `num_electrons`.\n\n References:\n - *M. Rossmannek, P. Barkoutsos, P. Ollitrault, and I. Tavernelli, arXiv:2009.01872\n (2020).*\n \"\"\"\n\n def __init__(\n self,\n num_electrons: Optional[Union[int, Tuple[int, int]]] = None,\n num_molecular_orbitals: Optional[int] = None,\n active_orbitals: Optional[List[int]] = None,\n ):\n \"\"\"Initializes a transformer which can reduce a `GroupedElectronicProperty` to a configured\n active space.\n\n This transformer requires a `ParticleNumber` property and an `ElectronicBasisTransform`\n pseudo-property to be available as well as `ElectronicIntegrals` in the `ElectronicBasis.AO`\n basis. An `ElectronicStructureDriverResult` produced by Qiskit's drivers in general\n satisfies these conditions unless it was read from an FCIDump file. However, those integrals\n are likely already reduced by the code which produced the file.\n\n Args:\n num_electrons: The number of active electrons. If this is a tuple, it represents the\n number of alpha and beta electrons. If this is a number, it is\n interpreted as the total number of active electrons, should be even, and\n implies that the number of alpha and beta electrons equals half of this\n value, respectively.\n num_molecular_orbitals: The number of active orbitals.\n active_orbitals: A list of indices specifying the molecular orbitals of the active\n space. This argument must match with the remaining arguments and should\n only be used to enforce an active space that is not chosen purely\n around the Fermi level.\n\n Raises:\n QiskitNatureError: if an invalid configuration is provided.\n \"\"\"\n self._num_electrons = num_electrons\n self._num_molecular_orbitals = num_molecular_orbitals\n self._active_orbitals = active_orbitals\n\n try:\n self._check_configuration()\n except QiskitNatureError as exc:\n raise QiskitNatureError(\"Incorrect Active-Space configuration.\") from exc\n\n self._mo_occ_total: np.ndarray = None\n self._active_orbs_indices: List[int] = None\n self._transform_active: ElectronicBasisTransform = None\n self._density_inactive: OneBodyElectronicIntegrals = None\n\n def _check_configuration(self):\n if isinstance(self._num_electrons, int):\n if self._num_electrons % 2 != 0:\n raise QiskitNatureError(\n \"The number of active electrons must be even! Otherwise you must specify them \"\n \"as a tuple, not as:\",\n str(self._num_electrons),\n )\n if self._num_electrons < 0:\n raise QiskitNatureError(\n \"The number of active electrons cannot be negative, not:\",\n str(self._num_electrons),\n )\n elif isinstance(self._num_electrons, tuple):\n if not all(isinstance(n_elec, int) and n_elec >= 0 for n_elec in self._num_electrons):\n raise QiskitNatureError(\n \"Neither the number of alpha, nor the number of beta electrons can be \"\n \"negative, not:\",\n str(self._num_electrons),\n )\n else:\n raise QiskitNatureError(\n \"The number of active electrons must be an int, or a tuple thereof, not:\",\n str(self._num_electrons),\n )\n\n if isinstance(self._num_molecular_orbitals, int):\n if self._num_molecular_orbitals < 0:\n raise QiskitNatureError(\n \"The number of active orbitals cannot be negative, not:\",\n str(self._num_molecular_orbitals),\n )\n else:\n raise QiskitNatureError(\n \"The number of active orbitals must be an int, not:\",\n str(self._num_electrons),\n )\n\n def transform(\n self, grouped_property: GroupedSecondQuantizedProperty\n ) -> GroupedElectronicProperty:\n \"\"\"Reduces the given `GroupedElectronicProperty` to a given active space.\n\n Args:\n grouped_property: the `GroupedElectronicProperty` to be transformed.\n\n Returns:\n A new `GroupedElectronicProperty` instance.\n\n Raises:\n QiskitNatureError: If the provided `GroupedElectronicProperty` does not contain a\n `ParticleNumber` or `ElectronicBasisTransform` instance, if more\n electrons or orbitals are requested than are available, or if the\n number of selected active orbital indices does not match\n `num_molecular_orbitals`.\n \"\"\"\n if not isinstance(grouped_property, GroupedElectronicProperty):\n raise QiskitNatureError(\n \"Only `GroupedElectronicProperty` objects can be transformed by this Transformer, \"\n f\"not objects of type, {type(grouped_property)}.\"\n )\n\n particle_number = grouped_property.get_property(ParticleNumber)\n if particle_number is None:\n raise QiskitNatureError(\n \"The provided `GroupedElectronicProperty` does not contain a `ParticleNumber` \"\n \"property, which is required by this transformer!\"\n )\n particle_number = cast(ParticleNumber, particle_number)\n\n electronic_basis_transform = grouped_property.get_property(ElectronicBasisTransform)\n if electronic_basis_transform is None:\n raise QiskitNatureError(\n \"The provided `GroupedElectronicProperty` does not contain an \"\n \"`ElectronicBasisTransform` property, which is required by this transformer!\"\n )\n electronic_basis_transform = cast(ElectronicBasisTransform, electronic_basis_transform)\n\n # get molecular orbital occupation numbers\n occupation_alpha = particle_number.occupation_alpha\n occupation_beta = particle_number.occupation_beta\n self._mo_occ_total = occupation_alpha + occupation_beta\n\n # determine the active space\n self._active_orbs_indices, inactive_orbs_idxs = self._determine_active_space(\n grouped_property\n )\n\n # get molecular orbital coefficients\n coeff_alpha = electronic_basis_transform.coeff_alpha\n coeff_beta = electronic_basis_transform.coeff_beta\n\n # initialize size-reducing basis transformation\n self._transform_active = ElectronicBasisTransform(\n ElectronicBasis.AO,\n ElectronicBasis.MO,\n coeff_alpha[:, self._active_orbs_indices],\n coeff_beta[:, self._active_orbs_indices],\n )\n\n # compute inactive density matrix\n def _inactive_density(mo_occ, mo_coeff):\n return np.dot(\n mo_coeff[:, inactive_orbs_idxs] * mo_occ[inactive_orbs_idxs],\n np.transpose(mo_coeff[:, inactive_orbs_idxs]),\n )\n\n self._density_inactive = OneBodyElectronicIntegrals(\n ElectronicBasis.AO,\n (\n _inactive_density(occupation_alpha, coeff_alpha),\n _inactive_density(occupation_beta, coeff_beta),\n ),\n )\n\n # construct new GroupedElectronicProperty\n grouped_property_transformed = ElectronicStructureResult()\n grouped_property_transformed.electronic_basis_transform = self._transform_active\n grouped_property_transformed = self._transform_property(grouped_property) # type: ignore\n\n return grouped_property_transformed\n\n def _determine_active_space(\n self, grouped_property: GroupedElectronicProperty\n ) -> Tuple[List[int], List[int]]:\n \"\"\"Determines the active and inactive orbital indices.\n\n Args:\n grouped_property: the `GroupedElectronicProperty` to be transformed.\n\n Returns:\n The list of active and inactive orbital indices.\n \"\"\"\n particle_number = grouped_property.get_property(ParticleNumber)\n if isinstance(self._num_electrons, tuple):\n num_alpha, num_beta = self._num_electrons\n elif isinstance(self._num_electrons, int):\n num_alpha = num_beta = self._num_electrons // 2\n\n # compute number of inactive electrons\n nelec_total = particle_number._num_alpha + particle_number._num_beta\n nelec_inactive = nelec_total - num_alpha - num_beta\n\n self._validate_num_electrons(nelec_inactive)\n self._validate_num_orbitals(nelec_inactive, particle_number)\n\n # determine active and inactive orbital indices\n if self._active_orbitals is None:\n norbs_inactive = nelec_inactive // 2\n inactive_orbs_idxs = list(range(norbs_inactive))\n active_orbs_idxs = list(\n range(norbs_inactive, norbs_inactive + self._num_molecular_orbitals)\n )\n else:\n active_orbs_idxs = self._active_orbitals\n inactive_orbs_idxs = [\n o\n for o in range(nelec_total // 2)\n if o not in self._active_orbitals and self._mo_occ_total[o] > 0\n ]\n\n return (active_orbs_idxs, inactive_orbs_idxs)\n\n def _validate_num_electrons(self, nelec_inactive: int) -> None:\n \"\"\"Validates the number of electrons.\n\n Args:\n nelec_inactive: the computed number of inactive electrons.\n\n Raises:\n QiskitNatureError: if the number of inactive electrons is either negative or odd.\n \"\"\"\n if nelec_inactive < 0:\n raise QiskitNatureError(\"More electrons requested than available.\")\n if nelec_inactive % 2 != 0:\n raise QiskitNatureError(\"The number of inactive electrons must be even.\")\n\n def _validate_num_orbitals(self, nelec_inactive: int, particle_number: ParticleNumber) -> None:\n \"\"\"Validates the number of orbitals.\n\n Args:\n nelec_inactive: the computed number of inactive electrons.\n particle_number: the `ParticleNumber` containing system size information.\n\n Raises:\n QiskitNatureError: if more orbitals were requested than are available in total or if the\n number of selected orbitals mismatches the specified number of active\n orbitals.\n \"\"\"\n if self._active_orbitals is None:\n norbs_inactive = nelec_inactive // 2\n if (\n norbs_inactive + self._num_molecular_orbitals\n > particle_number._num_spin_orbitals // 2\n ):\n raise QiskitNatureError(\"More orbitals requested than available.\")\n else:\n if self._num_molecular_orbitals != len(self._active_orbitals):\n raise QiskitNatureError(\n \"The number of selected active orbital indices does not \"\n \"match the specified number of active orbitals.\"\n )\n if max(self._active_orbitals) >= particle_number._num_spin_orbitals // 2:\n raise QiskitNatureError(\"More orbitals requested than available.\")\n if sum(self._mo_occ_total[self._active_orbitals]) != self._num_electrons:\n raise QiskitNatureError(\n \"The number of electrons in the selected active orbitals \"\n \"does not match the specified number of active electrons.\"\n )\n\n # TODO: can we efficiently extract this into the base class? At least the logic dealing with\n # recursion is general and we should avoid having to duplicate it.\n def _transform_property(self, prop: Property) -> Property:\n \"\"\"Transforms a Property object.\n\n This is a recursive reduction, iterating GroupedProperty objects when encountering one.\n\n Args:\n property: the property object to transform.\n\n Returns:\n The transformed property object.\n\n Raises:\n TypeError: if an unexpected Property subtype is encountered.\n \"\"\"\n transformed_property: Property\n if isinstance(prop, GroupedProperty):\n transformed_property = deepcopy(prop)\n\n # Get the iterator of the Group's properties. We access __iter__() directly to make\n # mypy happy :-)\n iterator = transformed_property.__iter__()\n\n transformed_internal_property = None\n while True:\n try:\n # Send the transformed internal property to the GroupedProperty generator.\n # NOTE: in the first iteration, this variable is None, which is equivalent to\n # starting the iterator.\n # NOTE: a Generator's send method returns the iterators next value [2].\n # [2]: https://docs.python.org/3/reference/expressions.html#generator.send\n internal_property = iterator.send(transformed_internal_property)\n except StopIteration:\n break\n\n try:\n transformed_internal_property = self._transform_property(internal_property)\n except NotImplementedError:\n logger.warning(\n \"The Property %s of type %s could not be transformed! Thus, it will not be \"\n \"included in the simulation from here onwards.\",\n prop.name,\n type(prop),\n )\n continue\n\n elif isinstance(prop, IntegralProperty):\n # get matrix operator of IntegralProperty\n fock_operator = prop.integral_operator(self._density_inactive)\n # the total operator equals the AO-1-body-term + the inactive matrix operator\n total_op = prop.get_electronic_integral(ElectronicBasis.AO, 1) + fock_operator\n # compute the energy shift introduced by the ActiveSpaceTransformer\n e_inactive = 0.5 * cast(complex, total_op.compose(self._density_inactive))\n\n transformed_property = deepcopy(prop)\n # insert the AO-basis inactive operator\n transformed_property.add_electronic_integral(fock_operator)\n # actually reduce the system size\n transformed_property.transform_basis(self._transform_active)\n # insert the energy shift\n transformed_property._shift[self.__class__.__name__] = e_inactive\n\n elif isinstance(prop, ParticleNumber):\n p_n = cast(ParticleNumber, prop)\n active_occ_alpha = p_n.occupation_alpha[self._active_orbs_indices]\n active_occ_beta = p_n.occupation_beta[self._active_orbs_indices]\n transformed_property = ParticleNumber(\n len(self._active_orbs_indices) * 2,\n (int(sum(active_occ_alpha)), int(sum(active_occ_beta))),\n active_occ_alpha,\n active_occ_beta,\n )\n\n elif isinstance(prop, SecondQuantizedProperty):\n transformed_property = prop.__class__(len(self._active_orbs_indices) * 2) # type: ignore\n\n else:\n raise TypeError(f\"{type(prop)} is an unsupported Property-type for this Transformer!\")\n\n return transformed_property\n","sub_path":"qiskit_nature/transformers/second_quantization/electronic/active_space_transformer.py","file_name":"active_space_transformer.py","file_ext":"py","file_size_in_byte":19579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"285541633","text":"# -*- coding: utf-8 -*-\nfrom odoo import http\nfrom odoo.http import request\nimport json\nimport logging\nfrom werkzeug.exceptions import Forbidden\nimport unicodedata\n\nfrom odoo import fields,api,models\nimport ast\nfrom odoo import tools, _\nfrom odoo.addons.base.ir.ir_qweb.fields import nl2br\nfrom odoo.addons.website.models.website import slug\nfrom odoo.addons.website.controllers.main import QueryURL\nfrom odoo.exceptions import ValidationError\nfrom odoo.addons.website_form.controllers.main import WebsiteForm\nfrom odoo.fields import Date\nimport base64\n\nfrom odoo.tools.misc import str2bool, xlwt\nfrom PIL import Image\nfrom datetime import datetime\nfrom time import gmtime, strftime\nfrom cStringIO import StringIO\nfrom odoo.exceptions import UserError\n\n\n_logger = logging.getLogger(__name__)\n\nclass controller_analitico_activo(http.Controller):\n\n\n @http.route('/web/binary/analitico_activo_excel', type='http', auth=\"public\")\n def flujos_efectivo_excel(self,fi,ff,company,aplicacierre, **kw):\n #year = strftime(\"%Y\")\n year=fields.Datetime.from_string(fi).year\n ## Style variable Begin\n borders_style_4_lados = xlwt.easyxf('borders: top medium, bottom medium, left medium,right medium;')\n encabezado_style = 'font: name Arial, colour_index black,bold on; align: vert centre, horiz center; '\n \n encabezado_detalles_columnas_style = 'font: name Arial, colour_index black,bold on; align: vert centre, horiz left; '\n encabezado_detalles_numeric_columnas_style = xlwt.easyxf(encabezado_style+' borders: top medium, bottom medium, left medium,right medium;')\n moneda_style_positivo=xlwt.easyxf('font: name Arial, colour_index black; align: vert centre, horiz right; borders: top no_line, bottom no_line, left no_line,right thin;',num_format_str='$#,##0.00')\n moneda_style_negativo_bold=xlwt.easyxf('font: name Arial, colour_index red, bold on; align: vert centre, horiz right; borders: top no_line, bottom no_line, left no_line,right no_line;',num_format_str='$#,##0.00')\n moneda_style_positivo_bold=xlwt.easyxf('font: name Arial, colour_index black, bold on; align: vert centre, horiz right; borders: top no_line, bottom no_line, left no_line,right thin;',num_format_str='$#,##0.00')\n ## Style variable End\n \n ## Module Add Begin\n def print_blank_line(A, B, C, D,estilo):\n ws.write_merge(A, B, C, D, \"\",estilo)\n ## Module Add End\n\n def print_blank_row(fila, titulo='', final=False):\n if final :\n bottom = 'thin'\n else :\n bottom = 'no_line'\n ws.write_merge(fila, fila, 1, col2-1, titulo,xlwt.easyxf('font: name Arial, colour_index black,bold on; align: vert centre, horiz left; borders: bottom '+bottom+', left thin, right thin; '))\n ws.write_merge(fila, fila, col2, col2+1, '', xlwt.easyxf(encabezado_style+' borders: bottom '+bottom+', right thin; '))\n ws.write_merge(fila, fila, col2+2, col2+3, '', xlwt.easyxf(encabezado_style+' borders: bottom '+bottom+', right thin; '))\n ws.write_merge(fila, fila, col2+4, col2+5, '', xlwt.easyxf(encabezado_style+' borders: bottom '+bottom+', right thin; '))\n ws.write_merge(fila, fila, col2+6, col2+7, '', xlwt.easyxf(encabezado_style+' borders: bottom '+bottom+', right thin; '))\n ws.write_merge(fila, fila, col2+8, col2+9, '', xlwt.easyxf(encabezado_style+' borders: bottom '+bottom+', right thin; ')) \n return fila +1\n\n ## Variable Begin\n wb = xlwt.Workbook()\n ## Variable End\n ## Sheet Name Begin\n ws = wb.add_sheet('Analitico del Activo')\n ws.col(0).width = 3*256\n ws.col(1).width = 3*256\n col2 = 8\n\n fila = 2\n\n ws.write_merge(fila, fila, 1, 17, 'Estado Analítico del Activo'.decode('utf-8'),xlwt.easyxf(encabezado_style+' borders: top thin, bottom no_line, left thin,right thin; pattern: pattern solid, fore_colour gray25;'))\n fila = fila + 1\n ws.write_merge(fila, fila, 1, 17, \"Del \"+str(fi)+\" al \"+str(ff),xlwt.easyxf(encabezado_style+' borders: top no_line, bottom no_line, left thin,right thin; pattern: pattern solid, fore_colour gray25;'))\n fila = fila + 1\n ws.write_merge(fila, fila, 1, 17, \"(Pesos)\",xlwt.easyxf(encabezado_style+' borders: left thin,right thin; pattern: pattern solid, fore_colour gray25;'))\n fila = fila + 1\n\n ws.write_merge(fila, fila, 1, 3, ''.decode('utf-8'),xlwt.easyxf(encabezado_style+' borders: bottom thin, left thin; pattern: pattern solid, fore_colour gray25;'))\n ws.write_merge(fila, fila, 4, 5, 'Ente Público:'.decode('utf-8'),xlwt.easyxf(encabezado_style+' borders: bottom thin; pattern: pattern solid, fore_colour gray25;'))\n ws.write_merge(fila, fila, 6, 13, company,xlwt.easyxf(encabezado_style+' borders: bottom thin; pattern: pattern solid, fore_colour gray25;'))\n ws.write_merge(fila, fila, 14, 17, '',xlwt.easyxf(encabezado_style+' borders: bottom thin, right thin; pattern: pattern solid, fore_colour gray25;')) \n fila = fila + 1\n\n ws.write_merge(fila, fila+2, 1, col2-1, 'Concepto',xlwt.easyxf(encabezado_style+' borders: bottom thin, left thin, right thin; pattern: pattern solid, fore_colour gray25;'))\n ws.write_merge(fila, fila+2, col2, col2+1, 'Saldo Inicial 1', xlwt.easyxf(encabezado_style+' borders: bottom thin, right thin; pattern: pattern solid, fore_colour gray25;'))\n ws.write_merge(fila, fila+2, col2+2, col2+3, 'Cargos del Periodo 2', xlwt.easyxf(encabezado_style+' borders: bottom thin, right thin; pattern: pattern solid, fore_colour gray25;'))\n ws.write_merge(fila, fila+2, col2+4, col2+5, 'Abonos del Periodo 3', xlwt.easyxf(encabezado_style+' borders: bottom thin, right thin; pattern: pattern solid, fore_colour gray25;'))\n ws.write_merge(fila, fila+2, col2+6, col2+7, 'Saldo Final 4 \\n(1+2-3)', xlwt.easyxf(encabezado_style+' borders: bottom thin, right thin; pattern: pattern solid, fore_colour gray25;'))\n ws.write_merge(fila, fila+2, col2+8, col2+9, 'Variación del Periodo \\n(4-1)'.decode('utf-8'), xlwt.easyxf(encabezado_style+' borders: bottom thin, right thin; pattern: pattern solid, fore_colour gray25;'))\n fila = fila + 3\n\n if aplicacierre=='True':\n cierre=True\n else:\n cierre=False\n\n\n def saldo_inicial(rubro,aplicacierre):\n\n debe = 0\n haber = 0\n \n importerubro=('''\n select coalesce(SUM(CAST(ASIENTOS.debe as numeric)),0) AS debe, \n coalesce(SUM(CAST(ASIENTOS.haber as numeric)),0) AS haber \n FROM view_asientos_contable ASIENTOS\n WHERE substring(ASIENTOS.ctacontablecod,1,3)='%s' and ASIENTOS.fechaaplicacion < '%s' \n '''% (rubro,fi))\n if not aplicacierre:\n importerubro=importerubro+' and ASIENTOS.cierre=False'\n \n request.env.cr.execute(importerubro) \n importerubrosql=request.env.cr.fetchall()\n\n for recordimporterubro in importerubrosql:\n debe=recordimporterubro[0]\n haber=recordimporterubro[1]\n\n return {\n 'debe': debe,\n 'haber': haber,\n } \n\n\n def estructura_detalle(fila,Incluir,aplicacierre):\n\n genero=('''\n select GENERO.genero_id,GENERO.generocod,GENERO.genero,SUBSTRING(GENERO.generocodreplace,1,1) \n FROM view_cta_contable GENERO\n WHERE SUBSTRING(GENERO.grupocodreplace,1,2) in ('%s')\n GROUP BY GENERO.genero_id,GENERO.generocod,GENERO.genero,GENERO.generocodreplace\n ORDER BY GENERO.genero_id,GENERO.generocod,GENERO.genero,GENERO.generocodreplace\n '''% (Incluir))\n\n request.env.cr.execute(genero)\n consultagenerosql=request.env.cr.fetchall()\n for record in consultagenerosql: \n #1-GENERO\n \n #Se hacen los registros del nivel grupo de cta.contables\n ctagrupo=('''\n select CTA.genero_id,CTA.grupo_id,CTA.grupocod,CTA.grupo\n FROM view_cta_contable CTA\n WHERE CTA.genero_id='%s' and SUBSTRING(CTA.grupocod,1,2) in ('%s')\n GROUP BY CTA.genero_id,CTA.grupo_id,CTA.grupocod,CTA.grupo\n ORDER BY CTA.genero_id,CTA.grupo_id,CTA.grupocod,CTA.grupo\n '''% (record[0],Incluir))\n request.env.cr.execute(ctagrupo)\n consultactagruposql=request.env.cr.fetchall()\n for recordgrupo in consultactagruposql:\n #2-GRUPO\n fila = print_blank_row(fila)\n ws.write_merge(fila, fila, 1, 1, '', xlwt.easyxf('borders: top no_line, bottom no_line, left thin, right no_line;'))\n ws.write_merge(fila, fila, 2, col2-1, recordgrupo[3],xlwt.easyxf('font: name Arial, colour_index black,bold on; align: vert centre, horiz left; borders: bottom no_line, left no_line, right thin; ')) \n filagrupo=fila\n fila = fila + 1\n\n total_debe_grupo = 0\n total_haber_grupo = 0\n total_saldo_inicial_grupo = 0\n total_saldo_final_grupo = 0\n total_variacion_grupo = 0\n \n #Se hacen los registros del nivel grupo de cta.contables\n ctarubro=('''\n select CTA.grupo_id,CTA.rubro_id,CTA.rubrocod,CTA.rubro,substring(CTA.rubrocod,1,3)\n FROM view_cta_contable CTA\n WHERE CTA.grupo_id='%s' \n GROUP BY CTA.grupo_id,CTA.rubro_id,CTA.rubrocod,CTA.rubro\n ORDER BY CTA.grupo_id,CTA.rubro_id,CTA.rubrocod,CTA.rubro\n '''% (recordgrupo[1]))\n request.env.cr.execute(ctarubro)\n consultactagruposql=request.env.cr.fetchall()\n for recordrubro in consultactagruposql:\n #3-RUBRO\n filarubro=fila\n ws.write_merge(fila, fila, 1, 1, '', xlwt.easyxf('borders: top no_line, bottom no_line, left thin, right no_line;'))\n ws.write_merge(fila, fila, 2, col2-1, recordrubro[3],xlwt.easyxf('font: name Arial, colour_index black; align: vert centre, horiz left; borders: bottom no_line, left no_line, right thin; '))\n fila=fila+1\n\n return_saldo_inicial = saldo_inicial(recordrubro[4], aplicacierre)\n saldo_inicial_rubro = return_saldo_inicial['debe'] - return_saldo_inicial['haber']\n total_saldo_inicial_grupo = total_saldo_inicial_grupo + saldo_inicial_rubro \n \n #BUSCO IMPORTES A NIVEL DE RUBRO\n if recordrubro[1]!=0:\n importerubro=('''\n select \n coalesce(SUM(CAST(ASIENTOS.debe as numeric)),0) AS debe,\n coalesce(SUM(CAST(ASIENTOS.haber as numeric)),0) AS haber\n FROM view_asientos_contable ASIENTOS\n WHERE substring(ASIENTOS.ctacontablecod,1,3)='%s' and ASIENTOS.fechaaplicacion between '%s' and '%s'\n '''% (recordrubro[4],fi,ff))\n if not aplicacierre:\n importerubro=importerubro+' and ASIENTOS.cierre=False'\n \n request.env.cr.execute(importerubro) \n importerubrosql=request.env.cr.fetchall()\n for recordimporterubro in importerubrosql:\n importe_debe_rubro = recordimporterubro[0]\n importe_haber_rubro = recordimporterubro[1]\n\n total_debe_grupo = total_debe_grupo + importe_debe_rubro\n total_haber_grupo = total_haber_grupo + importe_haber_rubro\n\n \n saldo_final_rubro = saldo_inicial_rubro + importe_debe_rubro - importe_haber_rubro\n variacion_periodo_rubro = saldo_final_rubro - saldo_inicial_rubro\n ws.write_merge(filarubro, filarubro, col2, col2+1, saldo_inicial_rubro, moneda_style_positivo)\n ws.write_merge(filarubro, filarubro, col2+2, col2+3, importe_debe_rubro, moneda_style_positivo)\n ws.write_merge(filarubro, filarubro, col2+4, col2+5, importe_haber_rubro, moneda_style_positivo)\n ws.write_merge(filarubro, filarubro, col2+6, col2+7, saldo_final_rubro, moneda_style_positivo)\n ws.write_merge(filarubro, filarubro, col2+8, col2+9, variacion_periodo_rubro, moneda_style_positivo)\n\n total_saldo_final_grupo = total_saldo_inicial_grupo + total_debe_grupo - total_haber_grupo\n total_variacion_grupo = total_saldo_final_grupo - total_saldo_inicial_grupo\n ws.write_merge(filagrupo, filagrupo, col2, col2+1, total_saldo_inicial_grupo, moneda_style_positivo_bold)\n ws.write_merge(filagrupo, filagrupo, col2+2, col2+3, total_debe_grupo, moneda_style_positivo_bold)\n ws.write_merge(filagrupo, filagrupo, col2+4, col2+5, total_haber_grupo, moneda_style_positivo_bold)\n ws.write_merge(filagrupo, filagrupo, col2+6, col2+7, total_saldo_final_grupo, moneda_style_positivo_bold)\n ws.write_merge(filagrupo, filagrupo, col2+8, col2+9, total_variacion_grupo, moneda_style_positivo_bold)\n\n\n return {\n 'fila': fila,\n 'saldo_inicial':total_saldo_inicial_grupo,\n 'debe':total_debe_grupo,\n 'haber':total_haber_grupo,\n 'saldo_final':total_saldo_final_grupo,\n 'variacion':total_variacion_grupo\n }\n \n \n \n fila = print_blank_row(fila)\n fila = print_blank_row(fila, 'ACTIVO')\n \n return_circulante = estructura_detalle(fila,'''11''',cierre)\n fila = return_circulante['fila']\n \n return_no_circulante = estructura_detalle(fila,'''12''',cierre)\n fila = return_no_circulante['fila']\n \n\n total_activo = {}\n total_activo['saldo_inicial'] = return_circulante['saldo_inicial'] + return_no_circulante['saldo_inicial']\n total_activo['debe'] = return_circulante['debe'] + return_no_circulante['debe']\n total_activo['haber'] = return_circulante['haber'] + return_no_circulante['haber']\n total_activo['saldo_final'] = return_circulante['saldo_final'] + return_no_circulante['saldo_final']\n total_activo['variacion'] = return_circulante['variacion'] + return_no_circulante['variacion']\n\n fila = print_blank_row(fila)\n ws.write_merge(fila, fila, 1, col2-1, 'TOTAL DEL ACTIVO',xlwt.easyxf('font: name Arial, colour_index black,bold on; align: vert centre, horiz left; borders: bottom no_line, left thin, right thin; '))\n ws.write_merge(fila, fila, col2, col2+1, total_activo['saldo_inicial'], moneda_style_positivo_bold)\n ws.write_merge(fila, fila, col2+2, col2+3, total_activo['debe'], moneda_style_positivo_bold)\n ws.write_merge(fila, fila, col2+4, col2+5, total_activo['haber'], moneda_style_positivo_bold)\n ws.write_merge(fila, fila, col2+6, col2+7, total_activo['saldo_final'], moneda_style_positivo_bold)\n ws.write_merge(fila, fila, col2+8, col2+9, total_activo['variacion'], moneda_style_positivo_bold) \n fila = fila + 1\n\n fila = print_blank_row(fila, '', True) + 1\n\n ws.write_merge(fila, fila, 1, 16, 'Bajo protesta de decir verdad declaramos que los Estados Financieros y sus Notas son razonablemente correctos y responsabilidad del emisor', xlwt.easyxf('font: name Arial, colour_index black; align: vert centre, horiz left; borders: top no_line, bottom no_line, left no_line, right no_line;')) \n\n\n stream = StringIO()\n wb.save(stream)\n stream.seek(0)\n data = stream.read()\n stream.close()\n\n return request.make_response(data,\n [('Content-Type', 'application/octet-stream'),\n ('Content-Disposition', 'attachment; filename=Estado_Analitico_Activo.xls;')]) \n","sub_path":"extrasGDL/finanzas/controllers/controllers_estado_analitico_activo.py","file_name":"controllers_estado_analitico_activo.py","file_ext":"py","file_size_in_byte":17174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"60527223","text":"#August 6th, Yinchao He\n\n#user enters a series of pizza topping until they enter a 'quit'\npizza_topping = \"\"\nwhile pizza_topping != 'quit':\n\tpizza_topping = input(\"what would you like to add? \")\n\tif pizza_topping != \"quit\":\n\t\tprint(\"you add \" + pizza_topping)\n\telse:\n\t\tprint(\"quit\")\n\n#users enter their age, and tell them the cost of their movie ticket\nage = \"\"\nwhile True:\n\tage = input(\"how old are you? \")\n\tif age == 'quit':\n\t\tbreak\n\tage = int(age)\n\tif age < 3:\n\t\tprice = 0\n\telif 3 <= age and age < 12:\n\t\tprice = 10\n\telse:\n\t\tprice = 15\n\tprint(\"you need to pay \" + str(price))\n\n#moving items from one list to another\nsandwich_orders = ['tuna sandwich', 'potato sandwich', 'tomato sandwich']\nfinished_sandwiches = []\nwhile sandwich_orders:\n\tsandwich = sandwich_orders.pop()\n\tprint(sandwich + \" is being made\")\n\tfinished_sandwiches.append(sandwich)\nprint(finished_sandwiches)\nprint(sandwich_orders)\n\n#remove all instances from a list\ntimes = 0\nwhile times < 3:\n\tsandwich_orders.append('pastrami')\n\ttimes += 1\nprint(sandwich_orders)\nwhile 'pastrami' in sandwich_orders:\n\tsandwich_orders.remove('pastrami')\nprint(sandwich_orders)\n\n#filling a dictionary with user input\ndream_vacations = {}\nresponse_active = True\nwhile response_active:\n\tname = input(\"could you input your name: \")\n\tplace = input(\"where do you want to go: \")\n\tdream_vacations[name] = place\n\trespond = input(\"would you like to let another person to respond? (yes/ no): \")\n\tif respond == 'no':\n\t\tresponse_active = False\nfor name, place in dream_vacations.items():\n\tprint(name + ' wants to go ' + place)\n\n\n","sub_path":"chapter6_dictionary/while_case.py","file_name":"while_case.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"38043119","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Feb 1 18:51:42 2020\n\n@author: Home\n\"\"\"\n\n\nfrom selenium import webdriver\nimport time\n#from os import listdir\nimport os\n\n\ndriver = webdriver.Firefox(firefox_binary=binary,\n executable_path=gecko+'.exe',\n firefox_profile = fp)\n\n\n\ndef get_mid_files(driver, url):\n driver.get(url)\n \n # get all of the buttons which reveal the download buttons\n reveals = driver.find_elements_by_css_selector(\".toggle.unrevealed\")\n downloaders = driver.find_elements_by_css_selector(\".listen\")\n \n for i in range(len(reveals)):\n reveals[i].click()\n downloaders[i].click()\n \n # Wait for 5 seconds\n time.sleep(3)\n \n\n#url = 'https://thesession.org/tunes/2123'\n#get_mid_files(driver = driver, url = url)\n\n\ndef file_name_to_full_path(directory, file_name):\n # simply takes a directoy path and a file name and combines them into a \n # path to a file \n return directory + '\\\\' + file_name\n \n\ndef get_newest_file_name(directory):\n # take a directory as a string and return the name of the\n # newest file in that directory\n \n file_names = os.listdir(directory)\n \n #full_paths = list(map(lambda x:directory + '\\\\' + x, file_names))\n \n full_paths = [file_name_to_full_path(directory, file_name = f) for f in file_names]\n \n newest_file = max(full_paths, key=os.path.getctime)\n \n newest_file_index = full_paths.index(newest_file)\n \n return file_names[newest_file_index]\n \n\ndef rename_newsest_file(directory, new_file_name):\n # take a directory and a new file name.\n # go to that directory and rename the most recently created to new_file_name\n # Nothing returned\n \n newest_file_name = get_newest_file_name(directory)\n \n os.rename(file_name_to_full_path(directory, file_name = newest_file_name),\n file_name_to_full_path(directory, file_name = new_file_name))\n\n\n\ndef get_meta_data(soup_object, index):\n # parse the soup object which comes from thesession\n # index is a number. Each page has a number of versions. index is whcih \n # version to get the information for.\n # IF index is -1 information on the whole page is returned\n \n if index == -1:\n h1 = soup.h1.get_text()\n\n # tunesets\n # There is no tag, class or id for the tunesets. Its just in a p tag\n # Just hope that all pages are foramtted the same\n # an alternitive is to check which p tag has the correct words\n \n tunesets_text = soup.find_all('p')[4].get_text() \n tunesets = int(''.join(re.findall('(?<=added to )\\d+(?= tune)', tunesets_text)))\n \n # tunebook\n tunebooks_text = soup.find(id='tunebooking').get_text()\n tunebooks = int(''.join(re.findall('(?<=added to )\\d+(?= tune)', tunebooks_text)))\n\n \n op = [h1, tunesets, tunebooks]\n \n else:\n notes = soup.find_all(class_=\"notes\")[index].get_text()\n\n # The way these notes are formatted is a bit of a pain. All of the required info is \n # just floating in the div, it is not in any tags other than the notes div\n \n # As a result just use regex on all these\n #''.join is used to convert a list of 1 string to a string object\n # .strip removes leading and trailing white_space\n \n # Get X\n \n x = int(''.join(re.findall('(?<=X: )\\d+', notes)))\n \n # Get T\n t = ''.join(re.findall('(?<=T:).*', notes)).strip()\n \n # Get R\n r = ''.join(re.findall('(?<=R:).*', notes)).strip()\n \n # Get K\n k = ''.join(re.findall('(?<=K:).*', notes)).strip()\n \n # Get abc notation\n \n # abc comes after K. uses this to build the regex\n regex = '(?<=' + k +'\\n' + ')' + '.*$'\n \n # Use re.DOTALL to treat \\n as a normal character. Otherwise it treats it as \n # the end of the string\n abc = re.findall(regex, notes, re.DOTALL)\n \n \n op = [x, t, r, k, abc] \n \n return op\n\n\n\n","sub_path":"final_functions.py","file_name":"final_functions.py","file_ext":"py","file_size_in_byte":4125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"442139828","text":"import json\nimport requests\n\n\n#r = requests.get(\"http://pokeapi.co/api/v2/pokemon/pikachu\")\n#Json = r.json()[\"stats\"]\n#print(json.dumps(Json, indent=4, sort_keys=True))\n\ndef getEVs(name:str):\n\tname = name.lower()\n\tr = requests.get(\"http://pokeapi.co/api/v2/pokemon/\"+name)\n\tJson = r.json()[\"stats\"]\n\ttoRet = []\n\tfor X in range(0, 6, 1):\n\t\ttoRet.append(Json[X][\"stat\"][\"name\"] + \" \" + str(Json[X][\"effort\"]))\n\treturn \"\\n\".join(toRet)","sub_path":"Util/PokemonJson.py","file_name":"PokemonJson.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"10011808","text":"# l = int(input())\n# array = list(map(int, input().split(\" \")))\n\n\ndef mean(array, l):\n return sum(array)*1.0/l\n\ndef median(array, l):\n a = sorted(array)\n if l%2 == 0:\n return (a[l//2-1] + a[l//2])/2\n else:\n return a[l//2]\n\ndef mode(array):\n mode_dict = dict.fromkeys(array)\n for k in mode_dict.keys():\n mode_dict[k] = array.count(k)\n # print('mode_dict', mode_dict)\n maxval = max(sorted(list(mode_dict.values())))\n \n values = []\n for key, val in mode_dict.items():\n if val == maxval:\n values.append(key)\n return min(values)\n \n\nif __name__ == '__main__':\n array = [64630,11735,14216,99233,14470,4978,73429,38120,51135,67060]\n l = len(array)\n\n print(mean(array, l))\n print(median(array, l))\n print(mode(array))","sub_path":"10_Days_of_Statistics/MeanMedianMode.py","file_name":"MeanMedianMode.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"422342895","text":"import urllib\n\nimport matplotlib\nmatplotlib.use('Qt5Agg')\n\nimport datetime\nfrom PyQt5.QtWidgets import QSizePolicy\nfrom PyQt5.QtWidgets import QWidget\nfrom matplotlib.backends.backend_qt5agg import FigureCanvas\nfrom matplotlib.dates import DateFormatter\nfrom matplotlib.figure import Figure\n\nfrom TriblerGUI.tribler_request_manager import TriblerRequestManager\n\n\nclass MplCanvas(FigureCanvas):\n \"\"\"Ultimately, this is a QWidget.\"\"\"\n\n def __init__(self, parent=None, width=5, height=5, dpi=100):\n fig = Figure(figsize=(width, height), dpi=dpi)\n fig.set_facecolor(\"#282828\")\n\n fig.set_tight_layout({\"pad\": 1})\n self.axes = fig.add_subplot(111)\n self.plot_data = None\n\n FigureCanvas.__init__(self, fig)\n self.setParent(parent)\n\n FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)\n FigureCanvas.updateGeometry(self)\n\n def compute_initial_figure(self):\n pass\n\n\nclass TrustPlotMplCanvas(MplCanvas):\n\n def compute_initial_figure(self):\n self.axes.cla()\n self.axes.set_title(\"MBytes given/taken over time\", color=\"#e0e0e0\")\n self.axes.set_xlabel(\"Date\")\n self.axes.set_ylabel(\"Given/taken data (MBytes)\")\n\n self.axes.xaxis.set_major_formatter(DateFormatter('%d-%m-%y'))\n\n self.axes.plot(self.plot_data[1], self.plot_data[0][0], label=\"MBytes given\", marker='o')\n self.axes.plot(self.plot_data[1], self.plot_data[0][1], label=\"MBytes taken\", marker='o')\n self.axes.grid(True)\n\n for line in self.axes.get_xgridlines() + self.axes.get_ygridlines():\n line.set_linestyle('--')\n\n # Color the axes\n if hasattr(self.axes, 'set_facecolor'): # Not available on Linux\n self.axes.set_facecolor('#464646')\n self.axes.xaxis.label.set_color('#e0e0e0')\n self.axes.yaxis.label.set_color('#e0e0e0')\n self.axes.tick_params(axis='x', colors='#e0e0e0')\n self.axes.tick_params(axis='y', colors='#e0e0e0')\n\n # Create the legend\n handles, labels = self.axes.get_legend_handles_labels()\n self.axes.legend(handles, labels)\n\n self.draw()\n\n\nclass TrustPage(QWidget):\n \"\"\"\n This page shows various trust statistics.\n \"\"\"\n\n def __init__(self):\n QWidget.__init__(self)\n self.trust_plot = None\n self.public_key = None\n self.request_mgr = None\n self.blocks = None\n\n def initialize_trust_page(self):\n vlayout = self.window().plot_widget.layout()\n self.trust_plot = TrustPlotMplCanvas(self.window().plot_widget, dpi=100)\n vlayout.addWidget(self.trust_plot)\n\n def load_trust_statistics(self):\n self.request_mgr = TriblerRequestManager()\n self.request_mgr.perform_request(\"multichain/statistics\", self.received_multichain_statistics)\n\n def received_multichain_statistics(self, statistics):\n statistics = statistics[\"statistics\"]\n self.window().trust_contribution_amount_label.setText(\"%s MBytes\" % statistics[\"self_total_up_mb\"])\n self.window().trust_consumption_amount_label.setText(\"%s MBytes\" % statistics[\"self_total_down_mb\"])\n\n self.window().trust_people_helped_label.setText(\"%d\" % statistics[\"self_peers_helped\"])\n self.window().trust_people_helped_you_label.setText(\"%d\" % statistics[\"self_peers_helped_you\"])\n\n # Fetch the latest blocks of this user\n encoded_pub_key = urllib.quote_plus(statistics[\"self_id\"])\n self.public_key = statistics[\"self_id\"]\n self.request_mgr = TriblerRequestManager()\n self.request_mgr.perform_request(\"multichain/blocks/%s\" % encoded_pub_key, self.received_multichain_blocks)\n\n def received_multichain_blocks(self, blocks):\n self.blocks = blocks[\"blocks\"]\n self.plot_absolute_values()\n\n def plot_absolute_values(self):\n \"\"\"\n Plot two lines of the absolute amounts of contributed and consumed bytes.\n \"\"\"\n plot_data = [[[], []], []]\n\n # Convert all dates to a datetime object\n for block in self.blocks:\n plot_data[1].append(datetime.datetime.strptime(block[\"insert_time\"], \"%Y-%m-%d %H:%M:%S\"))\n\n if block[\"public_key_requester\"] == self.public_key:\n plot_data[0][0].append(block[\"total_up_requester\"])\n plot_data[0][1].append(block[\"total_down_requester\"])\n else:\n plot_data[0][0].append(block[\"total_up_responder\"])\n plot_data[0][1].append(block[\"total_down_responder\"])\n\n if len(self.blocks) == 0:\n # Create on single data point with 0mb up and 0mb down\n plot_data = [[[0], [0]], [datetime.datetime.now()]]\n\n self.trust_plot.plot_data = plot_data\n self.trust_plot.compute_initial_figure()\n","sub_path":"TriblerGUI/widgets/trustpage.py","file_name":"trustpage.py","file_ext":"py","file_size_in_byte":4809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"105537764","text":"# Copyright 2020 The Meson development team\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\"\"\"Entrypoint script for backend agnostic compile.\"\"\"\n\nimport sys\nimport typing as T\nfrom pathlib import Path\n\nfrom . import mlog\nfrom . import mesonlib\nfrom . import coredata\nfrom .mesonlib import MesonException\nfrom mesonbuild.environment import detect_ninja\n\nif T.TYPE_CHECKING:\n import argparse\n \ndef validate_builddir(builddir: Path):\n if not (builddir / 'meson-private' / 'coredata.dat' ).is_file():\n raise MesonException('Current directory is not a meson build directory: `{}`.\\n'\n 'Please specify a valid build dir or change the working directory to it.\\n'\n 'It is also possible that the build directory was generated with an old\\n'\n 'meson version. Please regenerate it in this case.'.format(builddir))\n\ndef get_backend_from_coredata(builddir: Path) -> str:\n \"\"\"\n Gets `backend` option value from coredata\n \"\"\"\n return coredata.load(str(builddir)).get_builtin_option('backend')\n\ndef get_parsed_args_ninja(options: 'argparse.Namespace', builddir: Path):\n runner = detect_ninja()\n if runner is None:\n raise MesonException('Cannot find ninja.')\n mlog.log('Found runner:', runner)\n\n cmd = [runner, '-C', builddir.as_posix()]\n\n # If the value is set to < 1 then don't set anything, which let's\n # ninja/samu decide what to do.\n if options.jobs > 0:\n cmd.extend(['-j', str(options.jobs)])\n if options.load_average > 0:\n cmd.extend(['-l', str(options.load_average)])\n if options.verbose:\n cmd.append('-v')\n if options.clean:\n cmd.append('clean')\n \n return cmd\n\ndef get_parsed_args_vs(options: 'argparse.Namespace', builddir: Path):\n slns = list(builddir.glob('*.sln'))\n assert len(slns) == 1, 'More than one solution in a project?'\n \n sln = slns[0]\n cmd = ['msbuild', str(sln.resolve())]\n \n # In msbuild `-m` with no number means \"detect cpus\", the default is `-m1`\n if options.jobs > 0:\n cmd.append('-m{}'.format(options.jobs))\n else:\n cmd.append('-m')\n \n if options.load_average:\n mlog.warning('Msbuild does not have a load-average switch, ignoring.')\n if not options.verbose:\n cmd.append('/v:minimal')\n if options.clean:\n cmd.append('/t:Clean')\n \n return cmd\n \ndef add_arguments(parser: 'argparse.ArgumentParser') -> None:\n \"\"\"Add compile specific arguments.\"\"\"\n parser.add_argument(\n '-j', '--jobs',\n action='store',\n default=0,\n type=int,\n help='The number of worker jobs to run (if supported). If the value is less than 1 the build program will guess.'\n )\n parser.add_argument(\n '-l', '--load-average',\n action='store',\n default=0,\n type=int,\n help='The system load average to try to maintain (if supported)'\n )\n parser.add_argument(\n '--clean',\n action='store_true',\n help='Clean the build directory.'\n )\n parser.add_argument(\n '-C',\n action='store',\n dest='builddir',\n type=Path,\n default='.',\n help='The directory containing build files to be built.'\n )\n parser.add_argument(\n '--verbose',\n action='store_true',\n help='Show more verbose output.'\n )\n\n\ndef run(options: 'argparse.Namespace') -> int:\n bdir = options.builddir # type: Path\n validate_builddir(bdir.resolve())\n\n cmd = [] # type: T.List[str]\n\n backend = get_backend_from_coredata(bdir)\n if backend == 'ninja':\n cmd = get_parsed_args_ninja(options, bdir)\n elif backend.startswith('vs'):\n cmd = get_parsed_args_vs(options, bdir)\n else:\n # TODO: xcode?\n raise MesonException(\n 'Backend `{}` is not yet supported by `compile`. Use generated project files directly instead.'.format(backend))\n\n p, *_ = mesonlib.Popen_safe(cmd, stdout=sys.stdout.buffer, stderr=sys.stderr.buffer)\n\n return p.returncode\n","sub_path":"mesonbuild/mcompile.py","file_name":"mcompile.py","file_ext":"py","file_size_in_byte":4576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"24578026","text":"'''\nI post di un forum sono raccolti in alcuni file che hanno il seguente formato. \nUn file contiene uno o piu' post, l'inizio di un post e' marcato da una linea che contiene\nin sequenza le due sottostringhe \"\" ed \"N\" (senza virgolette) eventualmente \ninframmezzate, precedute e/o seguite da 0,1 o piu' spazi. \n\"N\" e' l'ID del post (un numero positivo). \nIl contenuto del post e' nelle linee successive fino alla linea che marca il prossimo post \no la fine del file (si veda ad esempio il file \"file01.txt\"). \nE' assicurato che la stringa \"\" non e' contenuta in nessun post.\n\nNel seguito per parola intendiamo come al solito una qualsiasi sequenza di caratteri\nalfabetici di lunghezza massimale. I caratteri alfabetici sono quelli per cui\nritorna True il metodo isalpha().\n\nScrivere una funzione post(fposts,insieme) che prende in input:\n- il percorso di un file (fposts) \n- ed un insieme di parole (insieme)\ne che restituisce un insieme (risultato).\n\nL'insieme restituito (risultato) dovra' contenere gli identificativi (ID) dei post \nche contengono almeno una parola dell'inseme in input.\nDue parole sono considerate uguali anche se alcuni caratteri alfabetici compaiono in una \nin maiuscolo e nell'altra in minuscolo.\n\nPer gli esempi vedere il file grade.txt\n\nAVVERTENZE:\n\tnon usare caratteri non ASCII, come le lettere accentate;\n\tnon usare moduli che non sono nella libreria standard.\nNOTA: l'encoding del file e' 'utf-8'\nATTENZIONE: Se un test del grader non termina entro 10 secondi il punteggio di quel test e' zero.\n'''\ndef divisione_post(nome_file):\n file = open(nome_file);\n \n #Variabili\n ini = 0;\n fin = 0;\n post = [];\n app = '';\n i = 0;\n \n f = file.read();\n ini = f.find(\"\");\n fin = f.find(\"\",ini+1);\n \n while i < len(f):\n j = ini;\n \n if fin == -1:\n while j < len(f):\n app += f[j];\n j += 1;\n else:\n while j < fin:\n app += f[j];\n j += 1;\n \n post.append(app);\n app = '';\n ini = fin;\n fin = f.find(\"\",ini+1);\n i = j+1;\n \n file.close();\n return post;\n\ndef controlla(lista,insieme):\n p = list(insieme);\n insieme2 = set();\n num_post = 0;\n #Trasformo tutte le parole dell'insime in minuscole\n for x in range(0,len(p)):\n p[x] = p[x].lower();\n insieme2.add(p[x]);\n #Controllo se qualla parola è presente nell'insieme\n for x in range(0,len(lista)):\n if lista[x].lower() in insieme2:\n num_post = lista[1];\n break;\n return num_post;\n\n#Creo una mia funzione split che funziona come si deve\ndef my_split(stringa):\n lista = [];\n \n i = 0;\n app = \"\";\n while i < len(stringa):\n if (ord(stringa[i])>64 and ord(stringa[i])<91) or (ord(stringa[i])>96 and ord(stringa[i])<123) or (ord(stringa[i])>47 and ord(stringa[i])<58):\n app += stringa[i];\n elif app != \"\":\n lista.append(app);\n app = \"\";\n i += 1;\n return lista;\n \ndef post(fposts,insieme):\n ''' implementare qui la funzione'''\n insiemone = set()\n posts = divisione_post(fposts);\n \n for x in range(0,len(posts)):\n p = my_split(posts[x]);\n app = controlla(p,insieme);\n if app != 0:\n insiemone.add(app);\n return insiemone;\n#a = divisione_post(\"file01.txt\");\n#print(a)\n#print(a[10].split())","sub_path":"students/1810844/homework02/program01.py","file_name":"program01.py","file_ext":"py","file_size_in_byte":3465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"475793615","text":"import signal\nimport time\nimport os\n\nimport click\nimport psycopg2\n\nfrom runutils import run_daemon, runbash, ensure_dir, getvar, run_cmd\n\n\nUWSGI_CONF = '/config/uwsgi.conf'\nPG_SEMAFOR = '/data/sock/pg_semafor'\n\n\ndef waitfordb(stopper):\n \"\"\"\n Wait for the database to accept connections.\n \"\"\"\n tick = 0.1\n intervals = 10 * [5] + 100 * [10]\n\n for i in intervals:\n click.echo('checking semafor ...')\n if os.path.isfile(PG_SEMAFOR):\n click.echo('checking connection ...')\n try:\n psycopg2.connect(host='postgres',\n port=5432,\n database=\"postgres\",\n user=\"postgres\",\n password=getvar('DB_PASSWORD'))\n except:\n click.echo('could not connect yet')\n else:\n return\n else:\n click.echo('no semafor yet')\n\n for w in range(i):\n if stopper.stopped:\n return\n time.sleep(tick)\n\n\n################################################\n# INIT: WILL RUN BEFORE ANY COMMAND AND START #\n# Modify it according to container needs #\n# Init functions should be fast and idempotent #\n################################################\n\n\ndef init(stopper):\n ensure_dir('/data/static',\n owner='django', group='django', permsission_str='777')\n\n if not stopper.stopped:\n run_cmd(['django-admin', 'migrate'], user='django')\n\n if not stopper.stopped:\n run_cmd(['django-admin', 'collectstatic', '--noinput'], user='django')\n\n # This is mainly for demonstartive purposes, but can be handy in\n # development\n if stopper.stopped:\n return\n\n import django\n django.setup()\n from django.contrib.auth.models import User\n\n try:\n User._default_manager.create_superuser(\n 'admin', 'admin@mycompany.com', 'admin')\n except:\n click.echo('Superuser exists')\n\n\n######################################################################\n# COMMANDS #\n# Add your own if needed, remove or comment out what is unnecessary. #\n######################################################################\n\n@click.group()\ndef run():\n pass\n\n\n@run.command()\n@click.argument('user', default='developer')\ndef shell(user):\n runbash(user)\n\n\n@run.command()\ndef start_runserver():\n start = ['django-admin.py', 'runserver', '0.0.0.0:8000']\n run_daemon(start, signal_to_send=signal.SIGINT, user='django',\n waitfunc=waitfordb, initfunc=init)\n\n\n@run.command()\ndef start_uwsgi():\n \"\"\"Starts the service.\"\"\"\n start = [\"uwsgi\", \"--ini\", UWSGI_CONF]\n run_daemon(start, signal_to_send=signal.SIGQUIT, user='django',\n waitfunc=waitfordb, initfunc=init)\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"config/django/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"504506054","text":"__author__ = 'Flyguy'\nclass Test(object):\n pass\nclass Instance(object):\n def __init__(self,slave,db_name):\n self._slave = slave\n self._dbname= db_name\n def listen(self,table_name):\n namespace = u'%s.%s' % (self._dbname,table_name)\n def wrapper(cls):\n events = {\n 'u': 'on_update',\n 'i': 'on_insert',\n 'd': 'on_delete',\n }\n for type,event in events.iteritems():\n try:\n attr = getattr(cls,event)\n if callable(attr):\n self._slave.register_event(namespace,type,attr)\n except AttributeError:\n continue\n\n return cls\n return wrapper","sub_path":"wsjs/tools/mongo_slave/namespace.py","file_name":"namespace.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"164087119","text":"from flask import Flask, send_file, request, make_response\nfrom favicon_extractor import FavIcon, FavIconException\nimport os\nimport sys\nimport logging\nimport sentry_sdk\nfrom sentry_sdk.integrations.flask import FlaskIntegration\nfrom dotenv import load_dotenv, find_dotenv\n\n\nload_dotenv(find_dotenv('env'))\n\nsentry_sdk.init(\n dsn=os.getenv('SENTRY_DSN'),\n integrations=[FlaskIntegration()]\n)\n\nfmt = '%(asctime)s:%(levelname)s:favicon-{}:%(message)s'.format(os.getenv('IMAGE_VERSION'))\nlogging.basicConfig(format=fmt, stream=sys.stdout, level=logging.DEBUG)\nlog = logging.getLogger(__name__)\n\napp = Flask(__name__)\n\nBASE_DIR = os.path.dirname(os.path.realpath(__file__))\n\n@app.route(\"/\")\ndef grab_favicon():\n\n url = request.args.get('url', None)\n\n try:\n favicon = FavIcon(url, BASE_DIR)\n\n except FavIconException as e:\n return str(e), 400\n\n favicon = favicon.get_favicon()\n\n response = make_response(send_file(favicon, mimetype='image/png', conditional=True))\n response.headers['X-IMAGE-VERSION'] = os.getenv('IMAGE_VERSION')\n\n return response\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"4784137","text":"# prog[1] = 12\r\n# prog[2] = 2\r\n\r\nfor noun in range(99):\r\n for verb in range(99):\r\n input_file = open(r'C:\\Users\\Panos\\Google Drive\\ECE\\Python Files\\Advent of Code 2019\\D2\\input.txt','r')\r\n prog = list(map(int, input_file.read().split(',')))\r\n prog[1] = noun\r\n prog[2] = verb\r\n for i in range(0, len(prog), 4):\r\n op = prog[i]\r\n if op == 99:\r\n break\r\n\r\n in_pos1, in_pos2, out_pos = prog[i+1:i+4]\r\n if op == 1:\r\n prog[out_pos] = prog[in_pos1] + prog[in_pos2]\r\n elif op == 2:\r\n prog[out_pos] = prog[in_pos1] * prog[in_pos2]\r\n if prog[0] == 19690720:\r\n print(100*noun + verb)\r\n\r\n","sub_path":"D2/D2.py","file_name":"D2.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"498276045","text":"from flask import Flask, render_template, request\n\nfrom flask_bootstrap import Bootstrap\n\nfrom flask_sqlalchemy import SQLAlchemy\n\nimport sqlalchemy\n\nimport config\n\nfrom forms import *\n\nfrom pysam import VariantFile\n\nbootstrap = Bootstrap()\n\n\n\napp = Flask(__name__)\n\napp.config.from_object('config')\n\nbootstrap.init_app(app)\n\n\ndb = SQLAlchemy(app)\n\nfrom model import *\n\n\n\n@app.route(\"/\", methods=['GET','POST'])\ndef hello():\n\n\tform = MuestraForm2(request.form)\n\n\tif form.validate_on_submit():\n\n\t\tid_m = form.data['id_muestra']\n\n\t\tmuestra_query = Muestra.query.filter_by(id_muestra = id_m).first()\n\n\t\tinfos = Info.query.join(InfoMuestra).filter(Info.id == InfoMuestra.id_info).filter(InfoMuestra.id_muestra == muestra_query.id)\n\n\t\treturn render_template('bootstrap/table.html', infos = infos, form=form, bootstrap_theme=True)\n\n\treturn render_template('bootstrap/base_dos.html', form=form, bootstrap_theme=True)\n\n\n\n@app.route(\"/load_genes\")\ndef load_genes():\n\n\tid_genes = ['EGFR', 'PDGFRA', 'PDGFA', 'FGFR1', 'FGF1', 'NOTCH2', 'JAG1', 'LINC02283']\n\t\n\tfor g in id_genes:\n\n\t\tgen = Gene(id_gene = g)\n\n\t\tdb.session.add(gen)\n\n\tdb.session.commit()\n\n\treturn render_template('bootstrap/base_dos.html', form= form, bootstrap_theme=True)\n\n\n\n@app.route(\"/load_default\")\ndef load_default():\n\n\t\n\n\treturn render_template('bootstrap/base_dos.html', bootstrap_theme=True)\n\n\n\n\n\n\n\n@app.route(\"/load_enf\")\ndef load_enf():\n\n\tnom_enf = 'Colon'\n\t\n\tgenes_enf = 'EGFR'\n\t\n\n\tenfermedad = Enfermedad(nombre_enfermedad = nom_enf)\n\n\tdb.session.add(enfermedad)\n\tdb.session.commit()\n\n\n\tid_enf_query = Enfermedad.query.filter_by(nombre_enfermedad=nom_enf).first()\n\tid_gene_query = Gene.query.filter_by(id_gene=genes_enf).first()\n\n\tgene_enf = GeneEnf(id_enfermedad = id_enf_query.id , id_gene =id_gene_query.id)\n\n\tdb.session.add(gene_enf)\n\tdb.session.commit()\n\n\treturn render_template('bootstrap/base_dos.html', bootstrap_theme=True)\n\n@app.route(\"/show_info\")\ndef show_info():\n\n\tid_m = '01_ALC227'\n\n\tmuestra_query = Muestra.query.filter_by(id_muestra = id_m).first()\n\n\n\t##info_muestra_query = InfoMuestra.query.filter_by(id_muestra = muestra_query.id)\n\n\t##infos = Info.query.select_entity_from(info_muestra_query)\n\n\tinfos = Info.query.join(InfoMuestra).filter(Info.id == InfoMuestra.id_info).filter(InfoMuestra.id_muestra == muestra_query.id)\n\n\treturn render_template('bootstrap/table.html', infos = infos, bootstrap_theme=True)\n\n\n\n@app.route(\"/load_info\")\ndef load_info():\n\n\tform = MuestraForm2(request.form)\n\n\tbcf_in = VariantFile(str(\"solid5500xl_2014_05_23_1_recalibrated_snp_annotated_pass.vcf\"))\n\n\tid_var = 'VCF_05_23_1'\n\n\tvariante = Variante(id_variante = id_var)\n\n\tdb.session.add(variante)\n\tdb.session.commit()\n\n\tvariante_query = Variante.query.filter_by(id_variante=id_var).first()\n\n\theaders_list = []\n\n\tfor rec in bcf_in.fetch():\n\n\t\theaders_list = list(bcf_in.header.samples)\n\n\n\tfor header in headers_list:\n\n\t\tid_var_query = Variante.query.filter_by(id_variante=id_var).first()\n\n\n\t\tmuestra = Muestra(id_muestra = str(header), id_variante=id_var_query.id)\n\n\n\t\tdb.session.add(muestra)\n\n\tdb.session.commit()\n\n\tlist_genes2 = ['EGFR', 'PDGFRA', 'PDGFA', 'FGFR1', 'FGF1', 'NOTCH2', 'JAG1', 'LINC02283']\n\n\tfor rec in bcf_in.fetch():\n\n\t\tif rec.info[\"Gene.refGene\"][0] in list_genes2:\n\n\n\t\t\tidref = str(rec.id)\n\t\n\t\t\tchrom = str(rec.chrom)\n\n\t\t\tinit = rec.start\n\t\t\tterm = rec.pos\n\t\n\t\t\tref = str(rec.ref)\n\t\t\talt = str(rec.alts[0])\n\n\t\t\tfunc = str(rec.info[\"Func.refGene\"][0])\n\t\t\tcyto = str(rec.info[\"cytoBand\"][0])\n\n\t\t\tgene_info = str(rec.info[\"Gene.refGene\"][0])\n\n\t\t\tinfo = Info(id_ref = idref, cromosoma = chrom, pos_inicial = init, pos_final = term, referencia = ref, alternante = alt, funcion = func, cytobanda = cyto)\n\n\t\t\tdb.session.add(info)\n\n\n\tdb.session.commit()\n\n\n\tfor rec in bcf_in.fetch():\n\n\t\tif rec.info[\"Gene.refGene\"][0] in list_genes2:\n\n\t\t\t##samplename = '03_ALM132'\n\n\t\t\tfor samplename in headers_list:\n\n\t\t\t\tif rec.samples[samplename]['GT'][0] != None:\n\t\t\t\t\t## es probable que rec.id no sea suficiente\n\t\t\t\t\t\n\t\t\t\t\tidref = rec.id\n\n\t\t\t\t\tid_m = samplename\n\n\t\t\t\t\t\n\t\t\t\t\t##tampoco es probable que samplename sea suficiente\n\n\t\t\t\t\t\n\n\t\t\t\t\tmuestra_query = Muestra.query.filter_by(id_muestra=id_m, id_variante=variante_query.id).first()\n\t\t\t\t\tinfo_query = Info.query.filter_by(id_ref=str(rec.id), pos_final = rec.pos).first()\n\t\t\t\t\tgene_query = Gene.query.filter_by(id_gene=gene_info).first()\n\t\n\t\t\t\t\tinfogene = InfoGene(id_info = info_query.id, id_gene = gene_query.id)\n\n\t\t\t\t\tinfomuestra = InfoMuestra(id_info = info_query.id, id_muestra = muestra_query.id)\n\n\t\t\t\t\tdb.session.add(infogene)\n\t\t\t\t\tdb.session.add(infomuestra)\n\n\t\n\tdb.session.commit()\n\n\n\n\treturn render_template('bootstrap/base_dos.html', form= form, bootstrap_theme=True)\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n\tapp.run(debug=True)\n","sub_path":"hello_load.py","file_name":"hello_load.py","file_ext":"py","file_size_in_byte":4755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"621899240","text":"#!/usr/bin/env python\n\n# Set this variable to \"threading\", \"eventlet\" or \"gevent\" to test the\n# different async modes, or leave it set to None for the application to choose\n# the best option based on available packages.\nimport os\nfrom threading import Thread\nimport json\nimport sys\nimport uuid\n\nimport time\nfrom werkzeug.utils import secure_filename, redirect\nfrom framework import runTests\nfrom flask import Flask, render_template, session, request\nfrom flask_socketio import SocketIO, emit, join_room, leave_room, \\\n close_room, rooms, disconnect\nimport eventlet\n\nasync_mode = 'eventlet'\n# Websocket only supported in eventlet\n# monkey patching is necessary because this application uses a background\n# thread\nif async_mode == 'eventlet':\n import eventlet\n eventlet.monkey_patch()\nelif async_mode == 'gevent':\n from gevent import monkey\n monkey.patch_all()\n\n\napp = Flask(__name__)\n#Secret key needed for integration with apache / nginx\napp.config['SECRET_KEY'] = 'secret!'\n#app.config['UPLOAD_FOLDER'] = \"/Users/alex/python_uploads/\"\napp.config['UPLOAD_FOLDER'] = \"/root/bachelorproject/uploads/\"\nsocketio = SocketIO(app, async_mode=async_mode,ping_timeout=10)\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n# Route that will process the file upload\n@app.route('/upload', methods=['POST'])\ndef upload():\n file = request.files['file']\n #http://code.runnable.com/UiPcaBXaxGNYAAAL/how-to-upload-a-file-to-the-server-in-flask-for-python\n if file:\n filename = str(uuid.uuid4())\n #file.filename\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n return redirect(\"/upload_callback?filename=\"+filename)\n else:\n return redirect(\"/upload_callback\")\n\n@app.route('/upload_callback',methods=['GET'])\ndef uploadsuccess():\n if request.args.get('filename'):\n return json.dumps({\"success\": True, \"filename\": request.args.get('filename')})\n else:\n return \"NO FILE\"\n# This route is expecting a parameter containing the n\n\n# This is our thread\n# If this thread .isAlive()\n# Verbose output cannot be sent to another client\n# Possible solution is letting the other client join\n# the current verbose room / session\nthreadList = []\n@socketio.on('start_ga')\ndef start_ga(message):\n\n session['receive_count'] = session.get('receive_count', 0) + 1\n print(str(request.sid))\n sys.stderr.write(\"start_ga\")\n jsonData = json.loads(str(message))\n try:\n print(\"Starting Verbose output\")\n t = Thread(target=consoleHandler(request.sid))\n t.start()\n emit('start_ga',\"gooo\")\n result = runTests(json.loads(str(message)))\n sys.stderr.write(\"reset a: \" + str(len(threadList)))\n del threadList[:]\n sys.stderr.write(\"new a: \" + str(len(threadList)))\n sys.stderr.write(result)\n #emit('result', result)\n except KeyError:\n emit('result', \"ERR_MISSING_VERBOSE\")\n\nbuffer = []\n\n\nclass consoleHandler():\n requestSID = None\n def __call__(self, *args, **kwargs):\n pass\n def __init__(self, sid):\n self.requestSID = sid\n\n def background_thread(self,a,sid):\n if(a!=\"\\n\"):\n buffer.append(a)\n #socketio.emit('verbose', {'data': a}, broadcast=True)\n #sys.stderr.write(sid+\" - \"+a+\"\\n\")\n\n def write(self, text):\n sys.stderr.write(\"Sleeping 0.1s\\n\")\n sys.stdout = self\n time.sleep(0.1)\n t = Thread(target=self.background_thread(text, self.requestSID))\n t.start()\n\n@socketio.on('confirm')\ndef receipt(msg):\n sys.stderr.write(\"Receipt: \"+msg+\"\\n\")\n sys.stderr.write(\"Receipt: \"+msg+\"\\n\")\n sys.stderr.write(\"Receipt: \"+msg+\"\\n\")\n\n@socketio.on('connect')\ndef test_connect():\n emit('my response', {'data': 'Connected', 'count': 0})\n\n\n@socketio.on('disconnect')\ndef test_disconnect():\n sys.stderr.write('Client disconnected request.sid')\n\n@app.route(\"/doc\")\ndef echodoc():\n return render_template(\"documentation.html\")\n\nif __name__ == '__main__':\n #socketio.run(app, \"AlexAmin.de\", 5000, debug=True)\n socketio.run(app, \"127.0.0.1\", 5000, debug=False)\n","sub_path":"deprecated_framework/deprecated_flask_socketio/WebServer.py","file_name":"WebServer.py","file_ext":"py","file_size_in_byte":4131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"7981024","text":"'''一道题目:设计一个Game(Player, Count) 规则是一串数字,循环的cycle,从头到尾数k次,删掉这个数,然后继续数\n最后剩的一个是winner\n\nPlayers = {A,B,C} count = 5\nA = 1;\nB = 2;.\nC = 3;\nA = 4\nB = 5 排除这个B\nC = 1\nA = 2\nC = 3\nA = 4. 一亩-三分-地,独家发布\nC = 5 排除这个C\n最后剩一个A winner.\nfollow up 如果是多线程 如何改进\n'''\n\ndef get_winner(players, count):\n while len(players) != 1:\n players.pop(count%len(players))\n\n return players.pop()\n\nprint(get_winner(['A','B','C'], 5))\n","sub_path":"BB/count_game.py","file_name":"count_game.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"420689588","text":"import json\nfrom mock import Mock, patch\nimport uuid\nfrom django.contrib.auth import get_user_model\nfrom django.core.urlresolvers import reverse, resolve\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\nfrom guardian.shortcuts import remove_perm\n\nfrom readux.annotations.models import Annotation, AnnotationGroup\n\n\nclass AnnotationTestCase(TestCase):\n fixtures = ['test_annotation_data.json']\n\n # test annotation data based on annotatorjs documentation\n # http://docs.annotatorjs.org/en/v1.2.x/annotation-format.html\n annotation_data = {\n \"id\": \"39fc339cf058bd22176771b3e3187329\",\n \"annotator_schema_version\": \"v1.0\",\n \"created\": \"2011-05-24T18:52:08.036814\",\n \"updated\": \"2011-05-26T12:17:05.012544\",\n \"text\": \"A note I wrote\",\n \"quote\": \"the text that was annotated\",\n \"uri\": \"http://example.com\",\n \"ranges\": [\n {\n \"start\": \"/p[69]/span/span\",\n \"end\": \"/p[70]/span/span\",\n \"startOffset\": 0,\n \"endOffset\": 120\n }\n ],\n # \"user\": \"alice\",\n \"consumer\": \"annotateit\",\n \"tags\": [\"review\", \"error\"],\n \"permissions\": {\n # \"read\": [\"group:__world__\"],\n \"read\": [\"testuser\"],\n \"admin\": [],\n \"update\": [],\n \"delete\": []\n },\n 'related_pages': [\n 'http://testpid.co/ark:/1234/11',\n 'http://testpid.co/ark:/1234/22',\n 'http://testpid.co/ark:/1234/qq'\n ]\n # add sample extra annotation data\n }\n\n def setUp(self):\n # use mock to simulate django httprequest\n self.mockrequest = Mock()\n self.mockrequest.body = json.dumps(self.annotation_data)\n\n def test_create_from_request(self):\n note = Annotation.create_from_request(self.mockrequest)\n self.assertEqual(self.annotation_data['text'], note.text)\n self.assertEqual(self.annotation_data['quote'], note.quote)\n self.assertEqual(self.annotation_data['uri'], note.uri)\n self.assert_('ranges' in note.extra_data)\n self.assertEqual(self.annotation_data['ranges'][0]['start'],\n note.extra_data['ranges'][0]['start'])\n self.assert_('permissions' in note.extra_data)\n\n # create from request with user specified\n user = get_user_model().objects.get(username='testuser')\n self.mockrequest.user = user\n note = Annotation.create_from_request(self.mockrequest)\n self.assertEqual(user, note.user)\n\n def test_update_from_request(self):\n # create test note to update\n note = Annotation(text=\"Here's the thing\", quote=\"really\",\n extra_data=json.dumps({'sample data': 'foobar'}))\n note.save()\n\n # permissions check requires a real user\n user = get_user_model().objects.get(username='testuser')\n self.mockrequest.user = user\n\n with patch.object(note, 'db_permissions') as mock_db_perms:\n note.update_from_request(self.mockrequest)\n self.assertEqual(self.annotation_data['text'], note.text)\n self.assertEqual(self.annotation_data['quote'], note.quote)\n self.assertEqual(self.annotation_data['uri'], note.uri)\n self.assert_('ranges' in note.extra_data)\n self.assertEqual(self.annotation_data['ranges'][0]['start'],\n note.extra_data['ranges'][0]['start'])\n self.assert_('permissions' not in note.extra_data)\n # existing extra data should no longer present\n self.assert_('sample data' not in note.extra_data)\n\n # testuser does not have admin on this annotation;\n # permissions should not be updated\n mock_db_perms.assert_not_called()\n\n # give user admin permission and update again\n note.assign_permission('admin_annotation', user)\n note.update_from_request(self.mockrequest)\n mock_db_perms.assert_called_with(self.annotation_data['permissions'])\n\n def test_info(self):\n note = Annotation.create_from_request(self.mockrequest)\n note.save() # save so created/updated will get set\n info = note.info()\n fields = ['id', 'annotator_schema_version', 'created', 'updated',\n 'text', 'quote', 'uri', 'user', 'ranges', 'permissions']\n # test that expected fields are present\n for f in fields:\n self.assert_(f in info)\n # test that dates are in isoformat\n self.assertEqual(info['created'], note.created.isoformat())\n self.assertEqual(info['updated'], note.updated.isoformat())\n\n # associate note with a user\n user = get_user_model().objects.get(username='testuser')\n note.user = user\n info = note.info()\n self.assertEqual(user.username, info['user'])\n\n # TODO assert includes permissions dict when appropriate\n\n def test_visible_to(self):\n # delete fixture annotations and test only those created here\n Annotation.objects.all().delete()\n\n testuser = get_user_model().objects.get(username='testuser')\n testadmin = get_user_model().objects.get(username='testsuper')\n\n Annotation.objects.create(user=testuser, text='foo')\n Annotation.objects.create(user=testuser, text='bar')\n Annotation.objects.create(user=testuser, text='baz')\n Annotation.objects.create(user=testadmin, text='qux')\n\n self.assertEqual(3, Annotation.objects.visible_to(testuser).count())\n self.assertEqual(4, Annotation.objects.visible_to(testadmin).count())\n\n def test_last_created_time(self):\n # test custom queryset methods\n Annotation.objects.all().delete() # delete fixture annotations\n self.assertEqual(None, Annotation.objects.all().last_created_time())\n\n note = Annotation.create_from_request(self.mockrequest)\n note.save() # save so created/updated will get set\n self.assertEqual(note.created,\n Annotation.objects.all().last_created_time())\n\n def last_updated_time(self):\n Annotation.objects.all().delete() # delete fixture annotations\n self.assertEqual(None, Annotation.objects.all().last_updated_time())\n\n note = Annotation.create_from_request(self.mockrequest)\n note.save() # save so created/updated will get set\n self.assertEqual(note.updated,\n Annotation.objects.all().last_updated_time())\n\n\n def test_related_pages(self):\n note = Annotation.create_from_request(self.mockrequest)\n self.assertEqual(len(self.annotation_data['related_pages']),\n len(note.related_pages))\n for idx in range(len(self.annotation_data['related_pages'])):\n self.assertEqual(self.annotation_data['related_pages'][idx],\n note.related_pages[idx])\n self.assertEqual(self.annotation_data['related_pages'][idx],\n note.extra_data['related_pages'][idx])\n\n note = Annotation()\n self.assertEqual(None, note.related_pages)\n\n def test_user_permissions(self):\n # annotation user/owner automatically gets permissions\n user = get_user_model().objects.get(username='testuser')\n note = Annotation.create_from_request(self.mockrequest)\n note.user = user\n note.save()\n\n user_perms = note.user_permissions()\n self.assertEqual(4, user_perms.count())\n self.assert_(user_perms.filter(user=user,\n permission__codename='view_annotation')\n .exists())\n self.assert_(user_perms.filter(user=user,\n permission__codename='change_annotation')\n .exists())\n self.assert_(user_perms.filter(user=user,\n permission__codename='delete_annotation')\n .exists())\n self.assert_(user_perms.filter(user=user,\n permission__codename='admin_annotation')\n .exists())\n\n note.save()\n # saving again shouldn't duplicate the permissions\n self.assertEqual(4, note.user_permissions().count())\n\n def test_db_permissions(self):\n note = Annotation.create_from_request(self.mockrequest)\n note.save()\n # get some users and groups to work with\n user = get_user_model().objects.get(username='testuser')\n group1 = AnnotationGroup.objects.create(name='foo')\n group2 = AnnotationGroup.objects.create(name='foobar')\n\n note.db_permissions({\n 'read': [user.username, group1.annotation_id,\n group2.annotation_id],\n 'update': [user.username, group1.annotation_id],\n 'delete': [user.username]\n })\n\n # inspect the db permissions created\n\n # should be two total user permissions, one to view and one to change\n user_perms = note.user_permissions()\n self.assertEqual(3, user_perms.count())\n self.assert_(user_perms.filter(user=user,\n permission__codename='view_annotation')\n .exists())\n self.assert_(user_perms.filter(user=user,\n permission__codename='change_annotation')\n .exists())\n self.assert_(user_perms.filter(user=user,\n permission__codename='delete_annotation')\n .exists())\n\n # should be three total group permissions\n group_perms = note.group_permissions()\n self.assertEqual(3, group_perms.count())\n self.assert_(group_perms.filter(group=group1,\n permission__codename='view_annotation')\n .exists())\n self.assert_(group_perms.filter(group=group1,\n permission__codename='change_annotation')\n .exists())\n self.assert_(group_perms.filter(group=group2,\n permission__codename='view_annotation')\n .exists())\n\n # updating the permissions for the same note should\n # remove permissions that no longer apply\n note.db_permissions({\n 'read': [user.username, group1.annotation_id],\n 'update': [user.username],\n 'delete': []\n })\n\n # counts should reflect the changes\n user_perms = note.user_permissions()\n self.assertEqual(2, user_perms.count())\n group_perms = note.group_permissions()\n self.assertEqual(1, group_perms.count())\n\n # permissions created before should be gone\n self.assertFalse(user_perms.filter(user=user,\n permission__codename='delete_annotation')\n .exists())\n self.assertFalse(group_perms.filter(group=group1,\n permission__codename='change_annotation')\n .exists())\n self.assertFalse(group_perms.filter(group=group2,\n permission__codename='view_annotation')\n .exists())\n\n # invalid group/user should not error\n note.db_permissions({\n 'read': ['bogus', 'group:666', 'group:foo'],\n 'update': ['group:__world__'],\n 'delete': []\n })\n\n self.assertEqual(0, note.user_permissions().count())\n self.assertEqual(0, note.group_permissions().count())\n\n\n def test_permissions_dict(self):\n note = Annotation.create_from_request(self.mockrequest)\n note.save()\n # get some users and groups to work with\n user = get_user_model().objects.get(username='testuser')\n group1 = AnnotationGroup.objects.create(name='foo')\n group2 = AnnotationGroup.objects.create(name='foobar')\n\n perms = {\n 'read': [user.username, group1.annotation_id,\n group2.annotation_id],\n 'update': [user.username, group1.annotation_id],\n 'delete': [user.username],\n 'admin': []\n }\n # test round-trip: convert to db permissions and then back\n note.db_permissions(perms)\n self.assertEqual(perms, note.permissions_dict())\n\n perms = {\n 'read': [user.username, group1.annotation_id],\n 'update': [user.username],\n 'delete': [],\n 'admin': []\n }\n note.db_permissions(perms)\n self.assertEqual(perms, note.permissions_dict())\n\n perms = {\n 'read': [],\n 'update': [],\n 'delete': [],\n 'admin': []\n }\n note.db_permissions(perms)\n self.assertEqual(perms, note.permissions_dict())\n\n\n@override_settings(AUTHENTICATION_BACKENDS=('django.contrib.auth.backends.ModelBackend',))\nclass AnnotationViewsTest(TestCase):\n fixtures = ['test_annotation_data.json']\n\n user_credentials = {\n 'user': {'username': 'testuser', 'password': 'testing'},\n 'superuser': {'username': 'testsuper', 'password': 'superme'}\n }\n\n def setUp(self):\n # annotation that belongs to testuser\n self.user_note = Annotation.objects \\\n .get(user__username=self.user_credentials['user']['username'])\n # annotation that belongs to superuser\n self.superuser_note = Annotation.objects \\\n .get(user__username=self.user_credentials['superuser']['username'])\n # NOTE: currently fixture only has one note for each user.\n # If that changes, use filter(...).first()\n\n # run the updated save method to grant author access\n for note in Annotation.objects.all():\n note.save()\n\n def test_api_index(self):\n resp = self.client.get(reverse('annotation-api:index'))\n self.assertEqual('application/json', resp['Content-Type'])\n # expected fields in the output\n data = json.loads(resp.content)\n for f in ['version', 'name']:\n self.assert_(f in data)\n\n def test_list_annotations(self):\n notes = Annotation.objects.all()\n\n # anonymous user should see no notes\n resp = self.client.get(reverse('annotation-api:annotations'))\n self.assertEqual('application/json', resp['Content-Type'])\n data = json.loads(resp.content)\n self.assertEqual(0, len(data))\n\n # log in as a regular user\n self.client.login(**self.user_credentials['user'])\n resp = self.client.get(reverse('annotation-api:annotations'))\n data = json.loads(resp.content)\n # notes by this user should be listed\n user_notes = notes.filter(user__username='testuser')\n self.assertEqual(user_notes.count(), len(data))\n self.assertEqual(data[0]['id'], unicode(user_notes[0].id))\n\n # log in as superuser\n self.client.login(**self.user_credentials['superuser'])\n resp = self.client.get(reverse('annotation-api:annotations'))\n data = json.loads(resp.content)\n # all notes user should be listed\n self.assertEqual(notes.count(), len(data))\n self.assertEqual(data[0]['id'], unicode(notes[0].id))\n self.assertEqual(data[1]['id'], unicode(notes[1].id))\n\n # test group permissions\n self.client.login(**self.user_credentials['user'])\n # reassign testuser notes to superuser\n superuser_name = self.user_credentials['superuser']['username']\n user = get_user_model().objects.get(username='testuser')\n superuser = get_user_model().objects.get(username=superuser_name)\n for note in user_notes:\n note.user = superuser\n note.save()\n # manually remove the permission, since the model\n # does not expect annotation owners to change\n remove_perm('view_annotation', user, note)\n\n group = AnnotationGroup.objects.create(name='annotation group')\n group.user_set.add(user)\n group.save()\n\n resp = self.client.get(reverse('annotation-api:annotations'))\n data = json.loads(resp.content)\n # user should not have access to any notes\n self.assertEqual(0, len(data))\n\n # update first note with group read permissions\n user_notes[0].db_permissions({'read': [group.annotation_id]})\n\n resp = self.client.get(reverse('annotation-api:annotations'))\n data = json.loads(resp.content)\n # user should have access to any notes by group permissiosn\n self.assertEqual(1, len(data))\n self.assertEqual(data[0]['id'], unicode(notes[0].id))\n\n def test_create_annotation(self):\n url = reverse('annotation-api:annotations')\n resp = self.client.post(url,\n data=json.dumps(AnnotationTestCase.annotation_data),\n content_type='application/json',\n HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n\n # not logged in - should not be allowed\n self.assertEqual(401, resp.status_code,\n 'should return 401 Unauthorized on anonymous attempt to create annotation, got %s' \\\n % resp.status_code)\n\n # log in as a regular user\n self.client.login(**self.user_credentials['user'])\n resp = self.client.post(url,\n data=json.dumps(AnnotationTestCase.annotation_data),\n content_type='application/json',\n HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n\n self.assertEqual(303, resp.status_code,\n 'should return 303 See Other on succesful annotation creation, got %s' \\\n % resp.status_code)\n # get view information\n view = resolve(resp['Location'][len('http://testserver'):])\n self.assertEqual('annotation-api:view', '%s:%s' % (view.namespaces[0], view.url_name),\n 'successful create should redirect to annotation view')\n\n # lookup the note and confirm values were set from request\n note = Annotation.objects.get(id=view.kwargs['id'])\n self.assertEqual(AnnotationTestCase.annotation_data['text'],\n note.text, 'annotation content should be set from request data')\n\n def test_get_annotation(self):\n # not logged in - should be denied\n resp = self.client.get(reverse('annotation-api:view',\n kwargs={'id': self.user_note.id}),\n HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n # simulate ajax request to get 401, otherwise returns 302\n # with redirect to login page\n self.assertEqual(401, resp.status_code,\n 'should return 401 Unauthorized on anonymous attempt to view annotation, got %s' \\\n % resp.status_code)\n\n # log in as a regular user\n self.client.login(**self.user_credentials['user'])\n resp = self.client.get(reverse('annotation-api:view',\n kwargs={'id': self.user_note.id}))\n self.assertEqual('application/json', resp['Content-Type'])\n # check a few fields in the data\n data = json.loads(resp.content)\n self.assertEqual(unicode(self.user_note.id), data['id'])\n self.assertEqual(self.user_note.text, data['text'])\n self.assertEqual(self.user_note.created.isoformat(), data['created'])\n\n # logged in but trying to view someone else's note\n resp = self.client.get(reverse('annotation-api:view',\n kwargs={'id': self.superuser_note.id}),\n HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(403, resp.status_code,\n 'should return 403 Forbidden on attempt to view other user\\'s annotation, got %s' \\\n % resp.status_code)\n\n # log in as a superuser - can view other user's notes\n self.client.login(**self.user_credentials['superuser'])\n resp = self.client.get(reverse('annotation-api:view',\n kwargs={'id': self.user_note.id}))\n data = json.loads(resp.content)\n self.assertEqual(unicode(self.user_note.id), data['id'])\n\n # test 404\n resp = self.client.get(reverse('annotation-api:view', kwargs={'id': uuid.uuid4()}))\n self.assertEqual(404, resp.status_code)\n\n def test_update_annotation(self):\n # login/permission checking is common to get/update/delete views, but\n # just to be sure nothing breaks, duplicate those\n url = reverse('annotation-api:view', kwargs={'id': self.user_note.id})\n resp = self.client.put(url,\n data=json.dumps(AnnotationTestCase.annotation_data),\n content_type='application/json',\n HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(401, resp.status_code,\n 'expected 401 Unauthorized on anonymous attempt to update annotation, got %s' \\\n % resp.status_code)\n\n # log in as a regular user\n self.client.login(**self.user_credentials['user'])\n resp = self.client.put(url,\n data=json.dumps(AnnotationTestCase.annotation_data),\n content_type='application/json',\n HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(303, resp.status_code,\n 'expected 303 See Other on succesful annotation update, got %s' \\\n % resp.status_code)\n # get view information\n self.assertEqual('http://testserver%s' % url, resp['Location'])\n # get a fresh copy from the db and check values\n n1 = Annotation.objects.get(id=self.user_note.id)\n self.assertEqual(AnnotationTestCase.annotation_data['text'],\n n1.text)\n self.assertEqual(AnnotationTestCase.annotation_data['quote'],\n n1.quote)\n self.assertEqual(AnnotationTestCase.annotation_data['ranges'],\n n1.extra_data['ranges'])\n\n # logged in but trying to edit someone else's note\n resp = self.client.put(reverse('annotation-api:view',\n kwargs={'id': self.superuser_note.id}),\n data=json.dumps(AnnotationTestCase.annotation_data),\n HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(403, resp.status_code,\n 'expected 403 Forbidden on attempt to view update user\\'s annotation, got %s' \\\n % resp.status_code)\n\n # log in as a superuser - can edit other user's notes\n self.client.login(**self.user_credentials['superuser'])\n data = {'text': 'this is a super annotation!'}\n resp = self.client.put(reverse('annotation-api:view',\n kwargs={'id': self.user_note.id}),\n data=json.dumps(data),\n HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n # note should be updated\n n1 = Annotation.objects.get(id=self.user_note.id)\n self.assertEqual(data['text'], n1.text)\n\n # test 404\n resp = self.client.put(reverse('annotation-api:view',\n kwargs={'id': str(uuid.uuid4())}),\n data=json.dumps(AnnotationTestCase.annotation_data),\n HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(404, resp.status_code)\n\n def test_delete_annotation(self):\n # login/permission checking is common to get/update/delete views, but\n # just to be sure nothing breaks, duplicate those\n url = reverse('annotation-api:view', kwargs={'id': self.user_note.id})\n resp = self.client.delete(url,\n HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(401, resp.status_code,\n 'should return 401 Unauthorized on anonymous attempt to delete annotation, got %s' \\\n % resp.status_code)\n\n # log in as a regular user\n self.client.login(**self.user_credentials['user'])\n resp = self.client.delete(url,\n HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(204, resp.status_code,\n 'expected 204 No Content for succesful annotation deletion, got %s' %\\\n resp.status_code)\n self.assertEqual('', resp.content,\n 'deletion response should have no content')\n\n # attempt to delete other user's note\n url = reverse('annotation-api:view', kwargs={'id': self.superuser_note.id})\n resp = self.client.delete(url,\n HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(403, resp.status_code,\n 'expected 403 Forbidden on attempt to delete another user\\'s annotation, got %s' \\\n % resp.status_code)\n\n # not explicitly tested: superuser can delete other user's note\n\n def test_search_annotations(self):\n search_url = reverse('annotation-api:search')\n notes = Annotation.objects.all()\n # search on partial text match\n resp = self.client.get(search_url, {'text': 'what a'})\n self.assertEqual('application/json', resp['Content-Type'])\n # check the data\n data = json.loads(resp.content)\n self.assertEqual(0, data['total'],\n 'anonymous user should not see any search results')\n\n # login as regular user\n self.client.login(**self.user_credentials['user'])\n resp = self.client.get(search_url, {'text': 'what a'})\n # returned notes should automatically be filtered by user\n user_notes = notes.filter(user__username=self.user_credentials['user']['username'])\n data = json.loads(resp.content)\n self.assertEqual(user_notes.count(), data['total'])\n self.assertEqual(str(user_notes[0].id), data['rows'][0]['id'])\n\n # login as superuser - should see all notes\n self.client.login(**self.user_credentials['superuser'])\n # matches both fixture notes\n resp = self.client.get(search_url, {'text': 'what a'})\n data = json.loads(resp.content)\n self.assertEqual(notes.count(), data['total'])\n self.assertEqual(str(notes[0].id), data['rows'][0]['id'])\n self.assertEqual(str(notes[1].id), data['rows'][1]['id'])\n\n # search on uri\n resp = self.client.get(search_url, {'uri': notes[0].uri})\n data = json.loads(resp.content)\n self.assertEqual(1, data['total'])\n self.assertEqual(notes[0].uri, data['rows'][0]['uri'])\n\n # search by username\n resp = self.client.get(search_url, {'user': self.user_credentials['user']['username']})\n data = json.loads(resp.content)\n self.assertEqual(1, data['total'])\n self.assertEqual(unicode(user_notes[0].id), data['rows'][0]['id'])\n\n # limit/offset\n resp = self.client.get(search_url, {'limit': '1'})\n data = json.loads(resp.content)\n self.assertEqual(1, data['total'])\n\n resp = self.client.get(search_url, {'offset': '1'})\n data = json.loads(resp.content)\n self.assertEqual(notes.count() - 1, data['total'])\n # should return the *second* note first\n self.assertEqual(str(notes[1].id), data['rows'][0]['id'])\n\n # non-numeric pagination should be ignored\n resp = self.client.get(search_url, {'limit': 'three'})\n data = json.loads(resp.content)\n self.assertEqual(notes.count(), data['total'])\n","sub_path":"readux/annotations/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":27237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"523786488","text":"from keras import models\r\nfrom keras.models import Model\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport scipy.misc\r\nfrom sklearn.metrics import roc_curve\r\nfrom sklearn.metrics import auc\r\nfrom keras.preprocessing import image\r\nimport os\r\nimport Image\r\nimport para\r\nimport csv\r\nimport generator\r\nimport numpy.random as rng\r\nfrom keras import backend as K\r\nimport keras.metrics\r\nimport time\r\nfrom keras.callbacks import TensorBoard\r\nfrom keras.utils.generic_utils import get_custom_objects\r\nfrom SimulateDegradation import Dilation\r\nfrom Verify import *\r\nimport math\r\n\r\ndef top_accuracy(y_true, y_pred):\r\n return keras.metrics.top_k_categorical_accuracy(y_true, y_pred, k=3)\r\nkeras.metrics.top_accuracy=top_accuracy\r\n\r\ndef generate_predictions(img_path,model_path,lineseg_path,charseg_path):\r\n net = models.load_model(model_path)\r\n doc_img = Image.open(img_path)\r\n doc_img = np.array(doc_img)\r\n\r\n lines=[]\r\n with open(lineseg_path, newline='') as linefile:\r\n reader = csv.reader(linefile, delimiter=',', quotechar='|')\r\n for row in reader:\r\n lines.append([int((row[0].split())[0]),int((row[0].split())[1])])\r\n\r\n output=np.zeros((len(lines)*40*4,doc_img.shape[1]),dtype=np.uint8)+255\r\n for idx,line in enumerate(lines):\r\n output[idx*40*4:idx*40*4+40,:]=doc_img[line[0]:line[1]+1,:]\r\n\r\n chars=[]\r\n with open(charseg_path, newline='') as charfile:\r\n reader = csv.reader(charfile, delimiter=',', quotechar='|')\r\n for row in reader:\r\n if len(row)==0:\r\n continue\r\n chars.append([int((row[0].split())[0]),int((row[0].split())[1]),int((row[0].split())[2]),int((row[0].split())[3])])\r\n\r\n npz_healthy = np.load(para.data_result_path+'/healthy.npz')\r\n healthy_labels=npz_healthy['labels']\r\n healthy_patches0=npz_healthy['patches']\r\n healthy_patches=np.expand_dims(healthy_patches0,-1)\r\n\r\n line_count=0\r\n col_count=0\r\n top_n=3\r\n for char in chars:\r\n while lines[line_count][0] datetime:\n if isinstance(data, datetime):\n return data\n elif type(data) == str:\n return datetime.strptime(data, format)\n else:\n return datetime.now()\n\n\ndef str_to_date(data: Union[str, date], format: str = '%Y-%m-%d') -> date:\n if isinstance(data, date):\n return data\n elif type(data) == str:\n return datetime.strptime(data, format).date()\n else:\n return datetime.now().date()\n","sub_path":"dapodik/utils/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"86225564","text":"# -*- coding: utf-8 -*-\nimport discord\nimport asyncio\nimport json\nimport os\nimport pyrebase\nimport datetime as dt\nimport random\nimport requests\nimport base64\nimport re\nfrom bs4 import BeautifulSoup\nimport sympy\nimport uuid\nfrom PIL import Image\ncmdPrefix = '?' # The prefix to the commands.\n\ntokenKey = str(os.getenv('token'))\n#os.environ[\"PATH\"] += os.pathsep + r'C:\\Users\\manlo\\AppData\\Local\\Programs\\MiKTeX 2.9\\miktex\\bin\\x64'\n\nclient = discord.Client()\nprint(\"Initiating\")\n\n\nsimpleResponses = {\n \"is bryck gay\": \"Yes.\",\n \"is very gay\": \"No.\",\n \"ching\": \"chong\",\n \"bing\": \"bong\",\n \"wing\": \"wong\",\n\n}\n\nwith open('math-leaderboards-ac11fa8d27ff.json', 'r+') as f:\n data = json.load(f)\n data['private_key'] = os.getenv('privateKey').replace('\\\\n', '\\n')\n data['private_key_id'] = os.getenv('privateId')\n #print(data['private_key'])\n f.seek(0)\n json.dump(data, f, indent=4)\n f.truncate()\n\n__location__ = os.path.realpath(\n os.path.join(os.getcwd(), os.path.dirname(__file__)))\nconfig = {\n \"apiKey\": str(os.getenv('apiKey')),\n \"authDomain\": \"math-leaderboards.firebaseapp.com\",\n \"databaseURL\": \"https://math-leaderboards.firebaseio.com\",\n \"storageBucket\": \"math-leaderboards.appspot.com\",\n \"serviceAccount\": str(os.path.join(__location__, 'math-leaderboards-ac11fa8d27ff.json'))\n}\n\n\nshop = {\n \"changenick\": (\"Change your nickname to whatever you want! One-time use.\", 3)\n}\n\n\nfirebase = pyrebase.initialize_app(config)\n\nauth = firebase.auth()\n\nuser = auth.sign_in_with_email_and_password(str(os.getenv('username')), str(os.getenv('password')))\nlast_hour = dt.datetime.now().hour\n\nuserToken = user['idToken']\n\ndb = firebase.database()\n\ndef get_as_base64(url):\n\n return base64.b64encode(requests.get(url).content)\n\n\ndef prob_statement(url):\n\n accepted_list = []\n # numeric_type = 0\n # if type == \"_I\":\n # numeric_type = 1\n # elif type == \"_II\":\n # numeric_type = 2\n #print(f)\n page = requests.get(url)\n soup = BeautifulSoup(page.text, 'html.parser')\n paragraph = \"\"\n image_latex = []\n\n for element in soup.find(class_=\"mw-content-ltr\").find(class_=\"mw-parser-output\"):\n mini_image_latex = []\n mini_paragraph = \"\"\n if element.name == 'h2':\n if element.find(class_=\"mw-headline\", recursive=False).text.lower().find(\"solution\") != -1:\n break\n if element.name == 'ul':\n paragraph += r' \\begin{itemize}'\n\n bullets = element.findAll('li')\n #print(bullets[0].findAll('img', recursive=False))\n for bullet in bullets:\n mini_paragraph = \"\"\n mini_image_latex = []\n for link in bullet.findAll('a'):\n link.replaceWithChildren()\n test = bullet.findAll('img', recursive=False)\n for s in test:\n #print(\"how..\")\n if str(s['alt']).find(\"[asy]\") != -1:\n accepted_list.append(s['src'])\n mini_image_latex.append(\"\")\n elif str(s['alt']).find(\"$\") == -1:\n if s.has_attr(\"class\") and s['class'] == ['latexcenter']:\n mini_image_latex.append(r\" \\begin{center} \" + s['alt'] + \" \\end{center} \")\n else:\n mini_image_latex.append(\"\")\n\n else:\n mini_image_latex.append(s['alt'])\n mini_paragraph += r\" \\item \"\n mini_paragraph += str(bullet)\n mini_paragraph = str(mini_paragraph).replace(\"

\", \"\")\n mini_paragraph = str(mini_paragraph).replace(\"

\", \"\")\n mini_paragraph = str(mini_paragraph).replace(\"\", \"\")\n mini_paragraph = str(mini_paragraph).replace(\"\", \"\")\n mini_paragraph = str(mini_paragraph).replace(\"\", \"\")\n mini_paragraph = str(mini_paragraph).replace(\"
  • \", \"\")\n mini_paragraph = str(mini_paragraph).replace(\"
  • \", \"\")\n mini_paragraph = str(mini_paragraph).replace(\"\", \"\")\n mini_paragraph = str(mini_paragraph).replace(\"\", \"\")\n mini_paragraph = str(mini_paragraph).replace(\"
      \", \"\")\n mini_paragraph = str(mini_paragraph).replace(\"
    \", \"\")\n\n regex = re.compile(\".*?<(.*?)>\")\n i = 0\n\n for s in re.findall(regex, mini_paragraph):\n mini_paragraph = mini_paragraph.replace(\"<\" + s + \">\", mini_image_latex[i])\n i += 1\n if bullet.find('a'):\n if bullet.find('a').has_attr(\"class\"): # standalone iamge\n if bullet.find('a')['class'] == ['image']:\n link_source = bullet.find('a').img['src']\n accepted_list.append(link_source)\n image_latex += mini_image_latex\n #print(\"thank u, next\")\n paragraph += mini_paragraph\n print(\"end??\")\n paragraph += r' \\end{itemize}'\n if element.name == 'p':\n\n for link in element.findAll('a'):\n link.replaceWithChildren()\n for s in element.findAll('img'):\n\n if str(s['alt']).find(\"[asy]\") != -1:\n accepted_list.append(s['src'])\n mini_image_latex.append(\"\")\n elif str(s['alt']).find(\"$\") == -1:\n\n if s.has_attr(\"class\") and s['class'] == ['latexcenter']:\n mini_image_latex.append(r\" \\begin{center} \" + s['alt'] + \" \\end{center} \")\n else:\n mini_image_latex.append(\"\")\n accepted_list.append(s['src'])\n else:\n mini_image_latex.append(s['alt'])\n mini_paragraph += str(element)\n mini_paragraph = str(mini_paragraph).replace(\"

    \", \"\")\n mini_paragraph = str(mini_paragraph).replace(\"

    \", \"\")\n mini_paragraph = str(mini_paragraph).replace(\"\", \"\")\n mini_paragraph = str(mini_paragraph).replace(\"\", \"\")\n mini_paragraph = str(mini_paragraph).replace(\"\", \"\")\n mini_paragraph = str(mini_paragraph).replace(\"
    \", \"\")\n mini_paragraph = str(mini_paragraph).replace(\"\", \"\")\n mini_paragraph = str(mini_paragraph).replace(\"
    \", \"\")\n mini_paragraph = str(mini_paragraph).replace(\"
    \", \"\")\n regex = re.compile(\".*?<(.*?)>\")\n i = 0\n for s in re.findall(regex, mini_paragraph):\n mini_paragraph = mini_paragraph.replace(\"<\" + s + \">\", mini_image_latex[i])\n i += 1\n if element.find('a'):\n if element.find('a').has_attr(\"class\"): #standalone iamge\n if element.find('a')['class'] == ['image']:\n link_source = element.find('a').img['src']\n accepted_list.append(link_source)\n image_latex += mini_image_latex\n paragraph += mini_paragraph\n return paragraph, accepted_list\n\ndef get_ans(type, year, p_n):\n answer_dict = {}\n numeric_type = 0\n if type == \"_I\":\n numeric_type = 1\n elif type == \"_II\":\n numeric_type = 2\n if year in answer_dict:\n if answer_dict[year][numeric_type] != 1:\n return answer_dict[year][numeric_type][p_n]\n else:\n page = requests.get(f\"https://artofproblemsolving.com/wiki/index.php/{year}_AIME{type}_Answer_Key\")\n soup = BeautifulSoup(page.text, 'html.parser')\n mw_cont = soup.find(class_=\"mw-content-ltr\")\n mw_parser = mw_cont.find(class_=\"mw-parser-output\")\n answer_list = mw_parser.find(\"ol\").findAll(\"li\")\n\n answer_dict[year][numeric_type] = [int(x.text) for x in answer_list]\n else:\n page = requests.get(f\"https://artofproblemsolving.com/wiki/index.php/{year}_AIME{type}_Answer_Key\")\n soup = BeautifulSoup(page.text, 'html.parser')\n mw_cont = soup.find(class_=\"mw-content-ltr\")\n mw_parser = mw_cont.find(class_=\"mw-parser-output\")\n answer_list = mw_parser.find(\"ol\").findAll(\"li\")\n answer_dict[year] = [1,1,1]\n answer_dict[year][numeric_type] = [int(x.text) for x in answer_list]\n return answer_dict[year][numeric_type][p_n]\n\ndef add_margin(pil_img, border):\n width, height = pil_img.size\n new_width = width + border * 2\n new_height = height + border * 2\n result = Image.new(pil_img.mode, (new_width, new_height), (255,255,255))\n result.paste(pil_img, (border, border))\n return result\n\n@client.event\nasync def on_ready():\n print(\"Logged in as: \" + client.user.name)\n print(client.user.id)\n print(\"Command prefix: \" + repr(cmdPrefix))\n print(\"-------------\")\n\n@client.event\nasync def on_message(message):\n global user\n global last_hour\n if last_hour != dt.datetime.now().hour:\n last_hour = dt.datetime.now().hour\n user = auth.refresh(user['refreshToken'])\n\n if (message.author.bot):\n return False\n SimpleResponse = False\n for trigger, reply in simpleResponses.items():\n if not SimpleResponse:\n if message.content.lower().startswith(trigger.lower()):\n await client.send_message(message.channel, reply)\n SimpleResponse = True\n if not SimpleResponse:\n if message.content.startswith(cmdPrefix + \"ping\"):\n x = message.timestamp\n now = dt.datetime.now()\n diff = now - x\n print(x, now)\n print(diff)\n await client.send_message(message.channel, \"Pong. (\" + str(1000 *(diff.seconds % 60) + diff.microseconds//1000) + \" ms)\")\n elif message.content.startswith(cmdPrefix + \"changescore\") and '534000608898842655' in [y.id for y in message.author.roles]:\n x = message.content.split()\n try:\n if not message.mentions:\n s = {\"score\": int(x[len(x)-1])}\n db.child(\"scores\").child(int(message.author.id)).set(s)\n nick = message.author.server.get_member(str(message.author.id)).nick\n if not nick:\n nick = message.author.name\n await client.send_message(message.channel, \"Successfully set score for user \" + nick + \" to \" + str(x[len(x)-1]) + \".\")\n else:\n s = {\"score\": int(x[len(x) - 1])}\n userId = message.mentions[0].id\n db.child(\"scores\").child(userId).set(s)\n nick = message.author.server.get_member(str(userId)).nick\n if not nick:\n nick = message.author.server.get_member(str(userId)).name\n await client.send_message(message.channel,\n \"Successfully set score for user \" + nick + \" to \" + str(x[len(x)-1]) + \".\")\n except Exception as e:\n await client.send_message(message.channel, \"error: \" + str(e))\n elif message.content.startswith(cmdPrefix + \"checkscore\"):\n userId = 0\n nick = \"\"\n try:\n if message.mentions:\n userId = message.mentions[0].id\n print(userId)\n\n nick = message.author.server.get_member(str(userId)).nick\n if not nick:\n nick = message.author.server.get_member(str(userId)).name\n else:\n userId = message.author.id\n nick = message.author.server.get_member(str(message.author.id)).nick\n if not nick:\n nick = message.author.name\n print(db.child('scores').child(str(userId)).get().val())\n if not db.child('scores').child(str(userId)).get().val():\n s = {\"score\": 0}\n db.child(\"scores\").child(userId).set(s)\n score = db.child(\"scores\").child(str(userId)).get().val()['score']\n await client.send_message(message.channel,str(nick) + \"'s score is \" + str(score) + \".\")\n except Exception as e:\n await client.send_message(message.channel, \"error: \" + str(e))\n elif message.content.startswith(cmdPrefix + \"givescore\") and '534000608898842655' in [y.id for y in message.author.roles]:\n x = message.content.split()\n amount = int(x[len(x)-1])\n userId = 0\n nick = \"\"\n try:\n if message.mentions:\n userId = message.mentions[0].id\n print(userId)\n\n nick = message.author.server.get_member(str(userId)).nick\n else:\n userId = message.author.id\n nick = message.author.server.get_member(str(userId)).nick\n if not nick:\n nick = message.author.server.get_member(str(userId)).name\n print(db.child('scores').child(str(userId)).get().val())\n if not db.child('scores').child(str(userId)).get().val():\n s = {\"score\": amount}\n db.child(\"scores\").child(userId).set(s)\n await client.send_message(message.channel, str(nick) + \" has been given \" + str(amount) + \". Their new score is \" + str(amount) + '.')\n else:\n score = db.child(\"scores\").child(str(userId)).get().val()['score']\n s = {'score': score + amount}\n await client.send_message(message.channel,str(nick) + \" has been given \" + str(amount) + \". Their new score is \" + str(score + amount) + \".\")\n db.child(\"scores\").child(userId).set(s)\n except Exception as e:\n await client.send_message(message.channel, \"error: \" + str(e))\n elif message.content.startswith(cmdPrefix + \"leaderboard\"):\n rawData = db.child(\"scores\").get().val()\n print(rawData)\n print(rawData.items())\n newData = []\n for key, value in rawData.items():\n score = value['score']\n nick_name = message.author.server.get_member(str(key)).nick\n if not nick_name:\n nick_name = message.author.server.get_member(str(key)).name\n newData.append((nick_name, score))\n newData = sorted(newData, key=lambda k: k[1], reverse=True)\n top_5 = newData[:5]\n r = lambda: random.randint(0, 255)\n embed = discord.Embed(title=\"Leaderboards - highest points\", description=' ', color=0x00b6ff)\n emotes = [\"👑\",\"🔱\", \"🏆\",\"👏\", \"👏\"]\n for x in range(5):\n\n vals = top_5[x]\n x += 1\n\n embed.description += \"\\n\" + emotes[x-1] + \"#\" + str(x) + \". **\" + str(vals[1]) + \" points** - \" + str(vals[0])\n embed.set_footer(text=\"Contest Math server\", icon_url=\"https://cdn.discordapp.com/attachments/534001679675424779/568550142303666190/original_alpha.png\")\n await client.send_message(message.channel, embed=embed)\n elif message.content.startswith(cmdPrefix + \"latexify\"):\n attach = message.attachments\n if attach:\n toLatex = attach[0]['url']\n image_url = \"data:image/png;base64,\" + get_as_base64(\n toLatex).decode()\n # (python3) image_uri = \"data:image/jpg;base64,\" + base64.b64encode(open(file_path, \"rb\").read()).decode()\n r = requests.post(\"https://api.mathpix.com/v3/latex\",\n data=json.dumps({'src': image_url, 'formats': [\"latex_simplified\"], 'ocr': [\"math\", \"text\"]}),\n headers={\"app_id\": str(os.getenv('app_id')), \"app_key\": str(os.getenv('app_key')),\n \"Content-type\": \"application/json\"})\n # print({\"app_id\": str(os.getenv('app_id')), \"app_key\": str(os.getenv('app_key')),\n # \"Content-type\": \"application/json\"})\n # print(json.loads(r.text))\n result = json.loads(r.text)\n #print(result)\n if 'latex_simplified' in result:\n latexes = result['latex_simplified']\n await client.send_message(message.channel, \"```$\" + latexes + \"$```\")\n else:\n await client.send_message(message.channel, str(result[\"error\"]))\n print(result)\n else:\n await client.send_message(message.channel, \"m8, you gotta attach an image\")\n\n elif message.content.startswith(cmdPrefix + \"fetch\"):\n try:\n years = re.findall(re.compile('20[0-2][0-9]|19[5-9][0-9]'), message.content)\n\n if len(years) == 0:\n await client.send_message(message.channel, \"m8, you gotta specify a year\")\n return\n year = years[0]\n contests = ['usajmo', 'usamo', 'aime', 'amc']\n contest_match = \"\"\n contest_version = \"\"\n url = \"\"\n pnum = re.search(re.compile('(p|p |problem|problem )([1-2][0-9]|[0-9])(?=\\s|\\Z)', re.IGNORECASE), message.content)\n if pnum is None:\n await client.send_message(message.channel, \"m8, you gotta specify a problem number\")\n return\n pnum = pnum.group(2)\n for contest in contests:\n if message.content.lower().find(contest) != -1:\n contest_match = contest\n break\n if contest_match == \"\":\n await client.send_message(message.channel, \"Did you not specify a contest?\")\n return\n if contest_match == \"aime\":\n if int(year) >= 2000:\n\n if \"II\" in message.content.split() or \"ii\" in message.content.split() or \"2\" in message.content.split():\n contest_version = \"II\"\n else:\n contest_version = \"I\"\n url = f\"https://artofproblemsolving.com/wiki/index.php/{year}_AIME_{contest_version}_Problems/Problem_{pnum}\"\n else:\n url = f\"https://artofproblemsolving.com/wiki/index.php/{year}_AIME_Problems/Problem_{pnum}\"\n\n elif contest_match == \"usamo\":\n url = f\"https://artofproblemsolving.com/wiki/index.php/{year}_USAMO_Problems/Problem_{pnum}\"\n elif contest_match == \"usajmo\":\n url = f\"https://artofproblemsolving.com/wiki/index.php/{year}_USAJMO_Problems/Problem_{pnum}\"\n elif contest_match == \"amc\":\n if int(year) >= 2002:\n if message.content.lower().find(\"10a\") != -1:\n url = f\"https://artofproblemsolving.com/wiki/index.php/{year}_AMC_10A_Problems/Problem_{pnum}\"\n elif message.content.lower().find(\"10b\") != -1:\n url = f\"https://artofproblemsolving.com/wiki/index.php/{year}_AMC_10B_Problems/Problem_{pnum}\"\n elif message.content.lower().find(\"12a\") != -1:\n url = f\"https://artofproblemsolving.com/wiki/index.php/{year}_AMC_10B_Problems/Problem_{pnum}\"\n elif message.content.lower().find(\"12b\") != -1:\n url = f\"https://artofproblemsolving.com/wiki/index.php/{year}_AMC_10B_Problems/Problem_{pnum}\"\n else:\n await client.send_message(message.channel, \"m8, you gotta specify which test it was\")\n return\n else:\n\n url = f\"https://artofproblemsolving.com/wiki/index.php/{year}_AMC_10_Problems/Problem_{pnum}\"\n else:\n await client.send_message(message.channel, \"Hmm... this contest doesn't seem to be supported. Check back later ;( .\")\n return\n\n latex, images = prob_statement(url)\n hash = str(uuid.uuid4().hex)\n path = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"latex_images\",\n str(hash) + '.png')\n sympy.preview(latex, viewer='file',\n filename=path, euler=False)\n im = Image.open(path)\n im = add_margin(im, 10)\n im.save(path)\n main_message = await client.send_file(message.channel,path)\n main_url = main_message.attachments[0]['url']\n main_e = discord.Embed(\n title=' '.join([year, contest_match.upper(), contest_version.upper(), \"Problem\", str(pnum)]),\n url=url, description=' ', color=0x00b6ff)\n\n main_e.description = \"epicness\"\n main_e.set_footer(text=\"Contest Math server\",\n icon_url=\"https://cdn.discordapp.com/attachments/534001679675424779/568550142303666190/original_alpha.png\")\n main_e.set_image(url=main_url)\n await client.send_message(message.channel, embed=main_e)\n await client.delete_message(main_message)\n\n i = 1\n for image in images:\n if image.startswith(\"//latex\"):\n image = \"https:\" + image\n e = discord.Embed(title='Image ('+str(i)+'/' + str(len(images))+')', url =image, color=0x00b6ff)\n e.set_footer(text=\"Contest Math server\",\n icon_url=\"https://cdn.discordapp.com/attachments/534001679675424779/568550142303666190/original_alpha.png\")\n e.set_image(url=image)\n await client.send_message(message.channel, embed=e)\n i += 1\n except Exception as e:\n await client.send_message(message.channel, \"Bruv something went wrong... Fetch in the format: !fetch [contest name] [contest version] [contest year]\")\n print(e)\n\nasync def list_servers():\n await client.wait_until_ready()\n while not client.is_closed:\n print(\"Current servers:\")\n for server in client.servers:\n print(server.name)\n print(server.id)\n await asyncio.sleep(600)\n\n\nclient.loop.create_task(list_servers())\nclient.run(tokenKey)\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":22872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"401367842","text":"#!/usr/bin/python\n# -*- python -*-\n#\n# This file is part of the CNO software\n#\n# Copyright (c) 2011-2012 - EBI\n#\n# File author(s): Thomas Cokelaer \n#\n# Distributed under the GPLv2 License.\n# See accompanying file LICENSE.txt or copy at\n# http://www.gnu.org/licenses/gpl-2.0.html\n#\n# CNO website: www.cellnopt.org\n#\n##############################################################################\n\"\"\"This module ease the creation of HTML file so as to get the same\nheader/footer and a layout that is the same everywhere. \n\n\nThen, this python script creates the HTML file::\n\n p = Process()\n p.create_html(\"developers.xml\")\n\n\n# if a xml file is changed, type::\n\n >>> python builder.py literature.xml\n >>> python builder.py developers.xml\n\nand commit the html.\n\n\"\"\"\nfrom distutils.version import StrictVersion\n\n__all__ = [\"BuilderHTML\", \"Download\", \"ReadXMLDevelopers\", \"ReadXML\", \"Process\", \n \"ReadXMLLiterature\", \"ReadXMLDevelopment\", \"ReadXMLCNOWEB\"]\n\n\nclass BuilderHTML(object):\n \"\"\" base class to build HTML pages\"\"\"\n def __init__(self):\n self.header = open(\"template_header.txt\").read()\n self.footer = open(\"template_footer.txt\").read()\n\n\n\nclass Download(BuilderHTML):\n \"\"\"class to create the download page automatically by fetching files in the download directory.\"\"\"\n\n _released = {\n 'CNORdt': {},\n 'CNORode': {},\n 'CNORfeeder': {},\n 'CNORfuzzy': {},\n 'CellNOptR': {\n \"bioc\": \"http://bioconductor.org/packages/release/bioc/html/CellNOptR.html\",\n \"1.2.0\": \"http://bioconductor.org/packages/release/bioc/src/contrib/CellNOptR_1.2.0.tar.gz\",\n \"1.6.0\": \"http://bioconductor.org/packages/release/bioc/src/contrib/CellNOptR_1.6.0.tar.gz\"\n },\n 'MEIGOR': {}\n }\n def __init__(self, path=\"downloads\"):\n super(Download, self).__init__()\n import os\n assert os.path.isdir(path)\n self.path = path\n\n def getfiles(self, pattern=\"CellNOptR\"):\n import glob\n import os\n return glob.glob(self.path + os.sep + pattern + \"*tar.gz\")\n \n\n def create_html(self):\n self.filename = self.path[:] + \".html\"\n output = open(self.filename, \"w\")\n output.write(self.header % {'title':\"Downloads\", \"urltitle\": \"Downloads\"} + \"\\n\")\n text = self.get_code()\n output.write(text)\n output.write(self.footer)\n output.close()\n\n def get_file_version(self, package):\n files = self.getfiles(package)\n versions = [x.split(\".tar.gz\")[0].split(\"_\", 1)[1] for x in files]\n files_sorted = sorted(versions, self._compVersion, reverse=True)\n indices = [versions.index(x) for x in files_sorted]\n return (files, versions, files_sorted, indices)\n \n def _compVersion(self, a, b):\n \"\"\"Compares 2 revision that includes a X.Y.Z and svnXXX strings\"\"\"\n # If not SVN revisaion is provided, we will set it to zero.\n if \"_svn\" in a:\n a_Rversion, a_svnVersion = a.split(\"_\")\n a_svnVersion = a_svnVersion[3:]\n else: \n a_Rversion, a_svnVersion = (a, 0)\n\n if \"_svn\" in b:\n b_Rversion, b_svnVersion = b.split(\"_\")\n b_svnVersion = b_svnVersion[3:]\n else: \n b_Rversion, b_svnVersion = (b, 0)\n\n # is the Rversion are not identical the comparison is obvious and made on\n # the Rversion only, otherwise, the SVN revision will have to be used\n if StrictVersion(a_Rversion) == StrictVersion(b_Rversion):\n return cmp(int(a_svnVersion ), int(b_svnVersion))\n else:\n if StrictVersion(a_Rversion)1. Latest version of CellNOpt and related software\\n\"\n text += \"\"\"

    Note: 17 June 2015 New version will not be provided anymore since CellNOptR is now publicly hosted on github at http://github.com/cellnopt

    \"\"\"\n text += \"\"\"

    Note for Windows users: to ease the installation of .tar.gz files, you can use the R packages called Rtools.\"\"\"\n\n\n # The top summary table\n text += \"\\n\"\n for package in [\"CellNOptR\", \"CNORdt\", \"CNORfeeder\", \"CNORfuzzy\", \"CNORode\", \"MEIGOR\"]:\n text+=\"\"\"\"\"\" % package\n # list of packages with given pattern\n (files, versions, sorted_versions, sorted_indices) = self.get_file_version(package)\n i = sorted_indices[0]\n\n text += \" \\n\" % (files[i], files[i].split('/')[1])\n\n\n text+=\"\"\"\"\"\"\n\n # matlab version has only one version for now\n text+=\"\"\"\"\"\"\n text+=\"\"\"\"\"\"\n\n # q2lm matlab version has only one version for now\n text+=\"\"\"\"\"\"\n text+=\"\"\"\"\"\"\n\n text+=\"\"\"\"\"\"\n text+=\"\"\"\"\"\"\n\n text+=\"\"\"\"\"\"\n text+=\"\"\"\"\"\"\n text+=\"
    %sLatest version: %s
    MATLAB version of CNO CNO 2.1 tar ball and zip version
    MATLAB version of Q2LM Q2LM 1.2 tar ball and zip version
    CytocopterSee main Cytocopter page
    Python wrapper (cnolab.wrapper)See Pypi page
    \"\n\n text += \"

    2. Some previous version

    \\n\"\n text += \"\"\"

    Would you require a specific version, please send a mail to .

    \"\"\"\n\n\n\n # all other revisions.\n for package in [\"CellNOptR\", \"CNORdt\", \"CNORfeeder\", \"CNORfuzzy\", \"CNORode\"]:\n text+=\"

    %s

    \\n\" % package\n text+=\"
      \\n\" \n\n (files, versions, sorted_versions, sorted_indices) = self.get_file_version(package)\n \n\n for i, index in enumerate(sorted_indices):\n if i == 0:\n pass\n else:\n if versions[index] in Download()._released[package].keys():\n link1 = Download()._released[package][versions[index]]\n link2 = Download()._released[package]['bioc']\n text += \"
    • %s; also available on Bioconductor(download)
    • \\n\" % (files[index], files[index].split('/')[1], link2, link1)\n else:\n text += \"
    • %s
    • \\n\" % (files[index], files[index].split('/')[1])\n text+=\"
    \\n\"\n text += \"

    Note that files without SVN tag are not guaranteed to be unique. A package built with different SVN revision may have the same R version.

    \"\n\n return text\n\n\n\n\nclass Process(BuilderHTML):\n def __init__(self):\n super(Process, self).__init__()\n self.registered = ['developers.xml','literature.xml', 'development.xml']\n\n def create_html(self, filename):\n if filename not in self.registered:\n raise ValueError(\"filename not known:should be in %s\" % self.registered)\n\n self.filename = filename\n text = self.process(filename)\n\n output_filename = filename.split('.xml')[0] + \".html\"\n output = open(output_filename, \"w\")\n output.write(self.header % {'urltitle':self.urltitle, 'title':self.shorttitle} + \"\\n\")\n text = text.encode(\"utf-8\")\n output.write(text)\n output.write(self.footer)\n output.close()\n\n def process(self, filename):\n text = \"\"\n if filename == \"developers.xml\":\n from builder import ReadXMLDevelopers\n self.xmldata = ReadXMLDevelopers(filename)\n text += self._process_developers()\n elif filename == \"literature.xml\":\n from builder import ReadXMLLiterature\n self.xmldata = ReadXMLLiterature(filename)\n text += self._process_literature()\n elif filename == \"development.xml\":\n from builder import ReadXMLDevelopment\n self.xmldata = ReadXMLDevelopment(filename)\n text += self._process_development()\n\n self.title = self.xmldata.title\n self.shorttitle = self.xmldata.shorttitle\n self.urltitle = self.xmldata.urltitle\n\n return text\n \n\n def _process_developers(self):\n #text = \"\"\"
    \\n\"\"\"\n text = \"

    %s

    \\n\" % self.xmldata.title\n text += \"
      \\n\"\n for developer in self.xmldata.developers:\n name = developer['surname']\n firstname = developer['firstname']\n aff = developer['affiliation']\n if developer['email']:\n email = developer['email'].strip()\n else:\n email = \"\"\n #ebi = developer['ebi']\n if email == \"\":\n text += \"\"\"
    • %s (%s):
    • \\n\"\"\" % (firstname + \" \" + name, aff)\n else:\n text += \"\"\"
    • %s (%s):.
    • \\n\"\"\" % (firstname + \" \" + name, aff, email)\n text += \"
    \\n\"\n text += \"

    %s

    \\n\" % self.xmldata.text\n return text\n\n def _process_literature(self):\n #text = \"\"\"
    \\n\"\"\"\n text = \"

    %s

    \\n\" % self.xmldata.title\n text += \"\"\"

    Please contact us at if you have used CellNOpt in a paper. Thanks!

    \"\"\"\n text += \"

    %s

    \\n\" % self.xmldata.text\n text += \"
      \\n\"\n\n text+=\"

      The following list contains publications where CellNOpt was used


      \"\n\n for ref in self.xmldata.references:\n text += \"\"\"
    • \n %s
      \n %s
      \n %s

      \n
    • \\n\"\"\" % (ref['authors'], ref['link'],ref['title'], ref['journal'])\n\n text += \"
    \\n\"\n\n #text += \"
    \\n\"\n return text\n\n\n def _process_development(self):\n text = \"

    %s

    \\n\" % self.xmldata.title\n text += \"

    %s

    \\n\" % self.xmldata.text\n\n\n\n return text\n\n\n\nif __name__ == \"__main__\":\n import sys\n assert len(sys.argv)==2, \"USAGE: python builder name.xml (e.g, python builder.py developers.xml)\"\n\n if sys.argv[1] not in [\"developers.xml\", \"literature.xml\", \"development.xml\"]:\n p = Download(path=sys.argv[1])\n p.create_html()\n\n else:\n p = Process()\n p.create_html(sys.argv[1])\n\n\n\nimport xml.etree.ElementTree as ET\n\nclass ReadXML(object):\n\n def __init__(self, filename):\n self.tree = ET.parse(filename)\n self.root = self.tree.getroot()\n self.expected_tags = []\n\n def get_children(self, element):\n tags = []\n for x in element:\n tags.append(x.tag)\n return tags\n\n def get_children_tag_root(self):\n tags = []\n for x in self.root:\n tags.append(x.tag)\n return tags\n\n def validate(self):\n tags = self.get_children_tag_root()\n for tag in tags:\n if tag not in self.expected_tags:\n raise ValueError(\"your XML file has not the format expected %s not expected\" %tag) \n for tag in self.expected_tags:\n if tag not in tags:\n raise ValueError(\"your XML file has not the format expected %s not found\" %tag) \n\n\nclass ReadXMLCNOWEB(ReadXML):\n def __init__(self, filename, extra_elements=[]):\n super(ReadXMLCNOWEB, self).__init__(filename)\n self.expected_tags = [\"shorttitle\", \"title\", \"urltitle\", \"name\", \"text\"]\n self.expected_tags += extra_elements\n self.validate()\n\n def _get_title(self):\n d = self.root.findall(\"title\")[0].text\n if d:\n return d\n else:\n return \"\"\n title = property(_get_title)\n\n def _get_shorttitle(self):\n d = self.root.findall(\"shorttitle\")[0].text\n if d: return d\n else: return \"\"\n shorttitle = property(_get_shorttitle)\n\n\n def _get_urltitle(self):\n return self.root.findall(\"urltitle\")[0].text\n urltitle = property(_get_urltitle)\n\n def _get_text(self):\n return self.root.findall(\"text\")[0].text\n text = property(_get_text)\n\n def _get_name(self):\n return self.root.findall(\"name\")[0].text\n name = property(_get_name)\n\n\nclass ReadXMLDevelopers(ReadXMLCNOWEB):\n\n def __init__(self, filename):\n super(ReadXMLDevelopers, self).__init__(filename, extra_elements=[\"developers\"])\n \n def _get_developers(self):\n developers = []\n for dev in self.root.find(\"developers\").findall(\"developer\"):\n firstname = dev.find(\"firstname\").text\n name = dev.find(\"surname\").text\n affiliation = dev.find(\"affiliation\").text\n if dev.find(\"email\").get(\"ebi\")==\"ebi\":\n email_type = \"ebi\"\n else:\n email_type = \"notebi\"\n email = dev.find(\"email\").text\n\n devd = {}\n devd['surname'] = name\n devd['firstname'] = firstname\n devd['email'] = email\n devd['affiliation'] = affiliation\n devd['email_type'] = email_type\n developers.append(devd)\n developers = sorted(developers, key=lambda k: k['surname'])\n return developers \n developers = property(_get_developers)\n\n\nclass ReadXMLLiterature(ReadXMLCNOWEB):\n def __init__(self, filename):\n super(ReadXMLLiterature, self).__init__(filename ,extra_elements=[\"references\"])\n\n def _get_references(self):\n references = []\n for ref in self.root.find(\"references\").findall(\"reference\"):\n refs = {}\n refs['authors'] = ref.find(\"authors\").text\n refs['journal'] = ref.find(\"journal\").text\n refs['year'] = ref.find(\"year\").text\n refs['title'] = ref.find(\"title\").text\n refs['link'] = ref.find(\"link\").text\n\n references.append(refs)\n references = sorted(references, key=lambda k: k['year'])\n return references \n references = property(_get_references)\n\n\nclass ReadXMLDevelopment(ReadXMLCNOWEB):\n \"\"\"nothing special to do for this class. all is contained in text.\"\"\"\n def __init__(self, filename):\n super(ReadXMLDevelopment, self).__init__(filename)\n\n\n","sub_path":"builder.py","file_name":"builder.py","file_ext":"py","file_size_in_byte":15125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"372810815","text":"from bs4 import BeautifulSoup\nfrom glob import glob\nimport numpy as np\nimport pprint\nimport os, sys\nsys.path.append(\"../\")\nimport test_scraper_output as tester\n\ndef check_header(soup, city, mode='hourly'):\n result = True\n if city=='muenchen' or city=='nuernberg' or city=='saarbruecken':\n city = city.replace('ue', 'ü')\n if city=='koeln':\n city = city.replace('oe', 'ö')\n if city=='frankfurt':\n city = 'frankfurt am main'\n header_class = \"[ breadcrumb__item ]\"\n header = soup.find_all('span', class_ = header_class)\n if not(header[3].text == 'Deutschland'): result = False\n if not(header[5].text.lower() == city): result = False\n if mode=='hourly':\n mode_str = 'Heute'\n elif mode=='daily':\n mode_str = '16-Tage Trend'\n if not(header[6].text==mode_str): result = False\n return result\n\n\ndef scrape_hourly(date, city):\n # define dict\n hourly_dic = {}\n\n # try to open the file\n data_path = '../data'\n path = data_path + '/' + get_filename('../data', date, city, mode='hourly')\n try:\n print(\"Scraping \"+ path)\n soup = BeautifulSoup(open(path))\n except FileNotFoundError:\n print(\"Data file missing, PATH: \" + path)\n raise FileNotFoundError()\n\n # check for country, city and type\n try:\n assert(check_header(soup, city, mode='hourly'))\n except:\n print(\"Wrong header for city =\" + city + \" hourly\")\n # define hourly scraping classes\n hour_class = '[ half-left ][ bg--white ][ cover-top ][ text--blue-dark ]'\n temp_class = '[ half-left ][ bg--white ][ js-detail-value-container ]'\n rainprob_class = 'mt--'\n rainAmount_class = '[ mb-- ][ block ][ text--small ][ absolute absolute--left ][ one-whole ]'\n windDir_class = '[ mb- ][ block ]'\n windAmount_class = '[ js-detail-value-container ][ one-whole ][ mb- ][ text--small ]'\n pressure_class = '[ mb- mt-- ][ block ][ text--small ]'\n humidity_class = '[ mb-- ][ block ][ text--small ]'\n\n try:\n hours = soup.find_all('div', class_ = hour_class)\n # get the starting hour of the hour table\n starting_hour = int((hours[0].string.split()[0])[1])\n except:\n print(\"Scraping failed: starting hour\")\n\n # define the hour string list for indexing the dictionary correctly\n hour_strs = []\n # this is because the data on the website does not start at 00 hours but at \"starting_hour” hours\n for i in range(24):\n s = \"{:0>2}\".format(np.mod(i+starting_hour,24))\n hour_strs.append(s)\n hourly_dic[s] = {}\n\n\n # SCRAPE TEMPERATURE\n try:\n # get all the temperature divs\n temps = soup.find_all('div', class_ = temp_class)\n # for every div, get the string, take the temperature value and save it in the matrix\n assert(len(temps)==24)\n for j, div in enumerate(temps):\n hourly_dic[hour_strs[j]]['temp'] = float(div.string.split()[0])\n except:\n print(\"Scraping failed: temperature\")\n\n try:\n # SCRAPE Rain probs\n probs = soup.find_all('p', class_ = rainprob_class)[:24]\n for j, p in enumerate(probs):\n hourly_dic[hour_strs[j]]['rain_chance'] = float(p.string.split()[0])\n except:\n print(\"Scraping failed: rain probs\")\n\n try:\n # SCRAPE Rain amounts\n amounts = soup.find_all('span', class_ = rainAmount_class)\n for j, span in enumerate(amounts):\n hourly_dic[hour_strs[j]]['rain_amt'] = float(span.text.split()[0])\n except:\n print(\"Scraping failed: rain amounts\")\n\n try:\n # SCRAPE Wind directions\n windDirs = soup.find_all('span', class_=windDir_class)\n for j, span in enumerate(windDirs):\n hourly_dic[hour_strs[j]]['wind_dir'] = span.text\n pass\n except:\n print(\"Scraping failed: hourly wind directions\")\n\n try:\n # SCRAPE Wind speed\n wstr = soup.find_all('div', class_=windAmount_class)\n for j, div in enumerate(wstr):\n # convert to m/s\n hourly_dic[hour_strs[j]]['wind_speed'] = round(float(div.string.split()[0])/3.6, 2)\n except:\n print(\"Scraping failed: hourly wind speed\")\n\n try:\n # SCRAPE pressure\n airpress = soup.find_all('span', class_ = pressure_class)\n for j, span in enumerate(airpress):\n hourly_dic[hour_strs[j]]['pressure'] = float(span.text.split()[0])\n pass\n except:\n print(\"Scraping failed: hourly pressure\")\n\n try:\n # SCRAPE air humidity\n airhum = soup.find_all('span', class_=humidity_class)\n for j, span in enumerate(airhum):\n hourly_dic[hour_strs[j]]['humidity'] = float(span.text.split()[0])\n except:\n print(\"Scraping failed: hourly humidity\")\n\n return hourly_dic\n\ndef scrape_daily(date, city):\n # define dict\n daily_dic = {}\n days = 16\n\n # try to open the file\n data_path = '../data'\n path = data_path + '/' + get_filename('../data', date, city, mode='daily')\n try:\n print(\"Scraping \"+ path)\n soup = BeautifulSoup(open(path))\n except FileNotFoundError:\n print(\"Data file missing, PATH: \" + path)\n\n # check for country, city and type\n try:\n assert(check_header(soup, city, mode='daily'))\n except:\n print(\"Wrong header for city =\" + city + \" daily\")\n\n # define daily scraping classes\n temp_low_class = 'inline text--white gamma'\n temp_high_class = 'text--white beta inline'\n\n days_strs = []\n # prelocate dict\n for i in range(days):\n s = \"{}\".format(i+1)\n # make list of dict string keys encoding days: '0', '1',...,'15'\n days_strs.append(s)\n daily_dic[s] = {}\n\n try:\n # SCRAPE TEMPERATURE\n # get all the high temperature divs\n temps_high = soup.find_all('div', class_=temp_high_class)\n # for every div, get the string, take the temperature value and save it in the matrix\n assert(len(temps_high)==days)\n for j, div in enumerate(temps_high):\n # get the length of the string in div to be sensitive to one/two digit numbers\n # format is 4° vs. 14°\n str_len = len(div.string)\n daily_dic[days_strs[j]]['high'] = float(div.string[:(str_len-1)])\n # low\n temps_low = soup.find_all('div', class_=temp_low_class)\n # for every div, get the string, take the temperature value and save it\n assert(len(temps_low)==days)\n for j, div in enumerate(temps_low):\n str_len = len(div.string)\n daily_dic[days_strs[j]]['low'] = float(div.string[3:(str_len-1)])\n except:\n print(\"Scraping failed: daily temperature\")\n\n # SCRAPE all other values: it is all hard coded in a big string, buggy\n # get the sun hours idxs as starting point for every day\n div_jungle = soup.findAll('div', {'class':'flag__body'})\n # there are the position of the sun hours for day block in jungle\n start_idxs_detailed = np.arange(12, 96, 12)\n #print(\"detailed idx {}\".format(start_idxs_detailed))\n dayIDX = 0 # need external day idx to use two different for looops\n for idx in start_idxs_detailed:\n rain_offset = 3 # the rain data is 3 lines further down\n wind_offset = 4 # the rain data is 4 lines further down\n measurements = 4 # measurements for the detailed daily data\n rain_chance = rain_amt = wind_speed = 0. # prelocate\n rain_str_threshold = 10\n for k in range(measurements):\n # rainchance, sum up for every measurement\n rain_chance += float(div_jungle[idx+rain_offset+2*k].text[:3])\n # rain amount is only displayed for high chance of rain\n if len(div_jungle[idx+rain_offset+2*k].text)>rain_str_threshold:\n rain_amt += float(div_jungle[idx+rain_offset+2*k].text[8:-5])\n else:\n rain_amt += 0.\n # find comma after wind direction\n commaIdx = div_jungle[idx+wind_offset+2*k].text.find(',')\n wind_speed += float(div_jungle[idx+wind_offset+2*k].text[commaIdx+2:commaIdx+4])\n # log results, take mean over daily measurements\n daily_dic[days_strs[dayIDX]]['rain_chance'] = rain_chance/measurements\n daily_dic[days_strs[dayIDX]]['rain_amt'] = rain_amt/measurements\n daily_dic[days_strs[dayIDX]]['wind_speed'] = wind_speed/measurements\n # save sun hours\n daily_dic[days_strs[dayIDX]]['sun_hours'] = float(div_jungle[idx].text[:-3])\n dayIDX += 1\n\n # get data for less detailed daily data\n start_idxs = np.arange(96, 132, 4)\n for idx in start_idxs:\n # save sun hours\n #daily_dic[days_strs[dayIDX]]['sun_hours'] = float(div_jungle[idx].text[:-3])\n # the length of the string determines whether we have a rain amt in the data\n rain_str_threshold = 10\n rain_chance = float(div_jungle[idx+1].text[:3])\n if len(div_jungle[idx+1].text)>rain_str_threshold:\n rain_amt = float(div_jungle[idx+1].text[5:-5])\n else:\n rain_amt = 0.\n # log results\n daily_dic[days_strs[dayIDX]]['rain_chance'] = rain_chance\n daily_dic[days_strs[dayIDX]]['rain_amt'] = rain_amt\n\n # increment days idx\n dayIDX += 1\n\n return daily_dic\n\ndef get_filename(dirpath, date, city, mode='hourly'):\n \"\"\"Looks up filename of the html file in dirpath for given date and city\n :param mode: daily or hourly data\n \"\"\"\n path = None\n filelist = os.listdir(dirpath)\n for f in filelist:\n if (date in f) and (city in f) and ( mode in f):\n path = f\n return path\n\ndata_path = '../data'\nprocessed_path = '../data/processed'\n\n# dates to process\ndates = ['26-04-2016']\n\n# list fo all cities we are scraping from\ncities = [\"berlin\"]\ncities = [\"berlin\", \"hamburg\", \"muenchen\",\n \"koeln\", \"frankfurt\", \"stuttgart\",\n \"bremen\", \"leipzig\", \"hannover\",\n \"nuernberg\", \"dortmund\", \"dresden\",\n \"kassel\", \"kiel\", \"bielefeld\",\n \"saarbruecken\", \"rostock\", \"freiburg\",\n \"magdeburg\", \"erfurt\"]\n\nprocessed_dates = []\nprocessed_cities = []\n\n# for every date:\nfor date in dates:\n dateInt = int(date.split('-')[0]+date.split('-')[1]+date.split('-')[2])\n for city in cities:\n # make dict\n data_dic = {'site': 'wetter.com',\n 'city': city,\n 'date': dateInt,\n 'hourly': scrape_hourly(date, city),\n 'daily': scrape_daily(date, city)}\n #pprint.pprint(data_dic)\n processed_dates.append(date)\n processed_cities.append(city)\n\n# run tests\nassert(tester.run_tests(data_dic))\n\n# move processed files to 'processed' folder\ntesting = True\nif not(testing):\n for date in processed_dates:\n for city in processed_cities:\n filename = get_filename('../data', date, city, mode='hourly')\n oldpath = data_path + '/' + filename\n newpath = processed_path + '/' + filename\n os.rename(oldpath, newpath)\n filename = get_filename('../data', date, city, mode='daily')\n oldpath = data_path + '/' + filename\n newpath = processed_path + '/' + filename\n os.rename(oldpath, newpath)\n","sub_path":"scraping/wetter_com/scrape_wetter_com.py","file_name":"scrape_wetter_com.py","file_ext":"py","file_size_in_byte":11296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"289434251","text":"import os\nimport pickle\nimport random\n\nimport numpy as np\nfrom agent_code.savage_agent import utils\nfrom agent_code.rule_based_agent.callbacks import act as rule_based_act\nfrom agent_code.rule_based_agent.callbacks import setup as rule_based_setup\nimport tensorflow as tf\nfrom collections import deque\n\n\nACTIONS = ['UP', 'RIGHT', 'DOWN', 'LEFT', 'WAIT', 'BOMB']\n\n\ndef setup(self):\n if utils.IMITATE:\n imitate_setup(self)\n if self.train: # on the training mode\n self.model = utils.create_model()\n if utils.CONTINUE_CKPT: # load model from checkpoint\n if os.path.exists(\"./checkpoints/savage-RNN-1616611589/rnnckpt\" + '.index'):\n print('-------------load the model-----------------')\n self.model.load_weights(\"./checkpoints/savage-RNN-1616611589/rnnckpt\")\n print(\"*******************model loaded***************************\")\n else:\n self.model = tf.keras.models.load_model('./RNNModel')\n print(self.model.summary())\n print(\"load model on non-training mode\")\n\n# def act(self, game_state: dict) -> str:\n# # print(\"act called\")\n# # print(\"epsilon:\", self.epsilon)\n# state_matrix = utils.get_state_matrix(game_state)\n# possible_actions = utils.get_possible_actions(state_matrix, game_state['self'][3], game_state['self'][2])\n# if np.random.random() <= self.epsilon:\n# # chose actions randomly\n# action = np.random.choice(possible_actions)\n# else:\n# for idx in np.sort(self.model.predict(state_matrix.flatten()/7))[::-1]:\n# if utils.index2action[idx] in possible_actions:\n# action = utils.index2action[idx]\n# break\n# return action\n\n\ndef act(self, game_state: dict) -> str:\n # print(\"act called\")\n # print(utils.get_state_matrix(game_state).reshape((5, 17, 17))[1])\n # print(utils.get_state_matrix(game_state).reshape((5, 17, 17))[4])\n if utils.IMITATE:\n return imitate_act(self, game_state)\n if self.train:\n if np.random.random() <= self.epsilon:\n # chose actions randomly\n # return np.random.choice(utils.ACTION_SPACE)\n return np.random.choice(['UP', 'DOWN', 'LEFT', 'RIGHT', 'WAIT', 'BOMB'], p=[.245, .245, .245, .245, .01, .01])\n # chose actions based on q values .09, .03\n state_matrix = utils.get_state_matrix(game_state)\n # print(game_state)\n # print(self.model.predict(np.array([state_matrix.flatten()/7])))\n act_idx = np.argmax(self.model.predict(np.array([state_matrix])))\n # print(act_idx)\n action = utils.ACTION_SPACE[act_idx]\n # print(action)\n return action\n\n\ndef imitate_setup(self):\n rule_based_setup(self)\n\n\ndef imitate_act(self, game_state):\n return rule_based_act(self, game_state)\n","sub_path":"agent_code/new_agent/callbacks.py","file_name":"callbacks.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"161882569","text":"import cv2\nimport numpy as np\nimport sys\nfrom PIL import Image\nfrom PIL.ExifTags import TAGS\nimport os\nimport math\n\nclass Camera():\n\tdef __init__(self, image=None, rvec=None,tvec=None, instance=None):\n\t\tself.image = Image.open(image)\n\t\tself.imagew, self.imageh = self.image.size\n\t\tself.instance = instance\n\t\tself.rvec = rvec\n\t\tself.tvec = tvec\n\t\tself.focal_length = None\n\t\tself.cameraMatrix = None\n\t\tself.world2img = None\n\n\tdef extract_metadata(self):\n\t\tself.metaData = {}\n\t\texif_info = self.image._getexif()\n\t\tif exif_info:\n\t\t\tprint(\"Found Meta Data!\",\"\\n\")\n\t\t\tfor (tag, value) in exif_info.items():\n\t\t\t\ttagname = TAGS.get(tag,tag)\n\t\t\t\tself.metaData[tagname] = value\n\t\t\tself.focal_length = int(self.metaData['FocalLength'][0]/self.metaData['FocalLength'][1])*self.imagew/35.9\n\t\t\tprint(\"Focal :\", np.round(self.focal_length), \" pixels\")\n\t\t\tself.cameraMatrix = np.array([[self.focal_length,0,self.imagew/2],[0,self.focal_length,self.imageh/2],[0,0,1]])\n\t\n\tdef rotationMatrixToEulerAngles(self, R) :\n\t\n\t\tsy = math.sqrt(R[0,0] * R[0,0] + R[1,0] * R[1,0])\n\t\tsingular = sy < 1e-6\n\t\tif not singular :\n\t\t\tx = math.atan2(R[2,1] , R[2,2])\n\t\t\ty = math.atan2(-R[2,0], sy)\n\t\t\tz = math.atan2(R[1,0], R[0,0])\n\t\telse :\n\t\t\tx = math.atan2(-R[1,2], R[1,1])\n\t\t\ty = math.atan2(-R[2,0], sy)\n\t\t\tz = 0\n\t\treturn np.array([x, y, z])\n\n\tdef procGCP(self,_file):\n\t\tworldcords = []\n\t\timgcords = []\n\t\twith open(_file) as file:\n\t\t\tprint(\"Processing Handpicked GCP Points from \",_file,\"\\n\")\n\t\t\tnext(file)\n\t\t\tnext(file)\n\t\t\tfor line in file:\n\t\t\t\tline[line=='\\t'] == ' '\n\t\t\t\tline = line.split()\n\t\t\t\tworld = np.array(line[:3]).astype('float64') \n\t\t\t\timg = np.array(line[3:]).astype('float64')\n\t\t\t\tworldcords.append(world)\n\t\t\t\timgcords.append(img)\n\t\t\t\tprint(\"World: \",world, \" Image: \",img,\"\\n\")\n\t\tfile.close()\n\t\tself.worldGCP = np.squeeze(np.array(worldcords).astype('float64'))\n\t\tself.imgGCP = np.squeeze(np.array(imgcords).astype('float64'))\n\t\tprint(self.worldGCP)\n\t\tprint(self.imgGCP)\n\n\tdef estimatePose(self):\n\t\tprint(\"Estimating Pose for \", str(self.instance),\"\\n\")\n\t\t_,self.rvec,self.tvec = cv2.solvePnP(self.worldGCP,self.imgGCP,self.cameraMatrix,distCoeffs=None,rvec=self.rvec,tvec=self.tvec,useExtrinsicGuess=1)\n\t\tself.R = np.zeros((3,3))\n\t\tcv2.Rodrigues(self.rvec,self.R)\n\t\tangle = np.degrees(self.rotationMatrixToEulerAngles(self.R))\n\t\tself.R = np.append(self.R,self.tvec,1)\n\t\tself.world2img = self.cameraMatrix@self.R\n\n\t\tprint(\"Pose Estimate: \", \" Easting,Northing,Elevation \", self.tvec, \"\\n\\n\", \" Roll, Pitch, Yaw: \", angle)\n\n\n\tdef _world2img(self,X):\n\t\tuv = self.world2img@X\n\t\treturn uv\n\n\n\n\tdef gcp_imgcords_predict(self,file):\n\t\tpredictions = []\n\t\twith open(file,'r') as file:\n\t\t\tnext(file) #skip description line in text file\n\t\t\tfor line in file:\n\t\t\t\tif \"\\t\" in line:\n\t\t\t\t\tline = line.split(\"\\t\")\n\t\t\t\telse: \n\t\t\t\t\tline = line.split()\n\t\t\t\ttry: \n\t\t\t\t\tline.remove(\"\\n\")\n\t\t\t\t\tline.remove(\"\")\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\t\t\tname = line[0]\n\t\t\t\tx,y,z = line[1],line[2],line[3]\n\t\t\t\tX = np.array([x,y,z,1]).astype('float64')\n\t\t\t\t#print(\"gcp_imgcords_predict Debug: \", X,\"\\n\\n\")\n\t\t\t\tuv = self._world2img(X)\n\t\t\t\t\n\t\t\t\t#if (uv[0] <= self.imagew and uv[0] >= 0 ) and (uv[1] <= self.imageh and uv[1] >=0) :\n\t\t\t\tpredictions.append((name, \"| World Cords (Easting,Northing,Elev) : \",x,y,z, \" | Predicted Image Cords (U,V) \"+self.instance + \": \", np.round(uv[0]), np.round(uv[1])))\n\t\tfile.close()\n\t\twith open('imcords_predictions_' + str(self.instance) + '.txt', 'w') as filehandle:\n\t\t\tfilehandle.write(\"Camera Pose (Easting, Northing, Elevation, Roll, Pitch, Yaw : \" + str(self.tvec) + str(np.degrees(self.rvec))+\"\\n\")\n\t\t\tfor listitem in predictions:\n\t\t\t\tfor item in listitem:\n\t\t\t\t\tfilehandle.write(str(item) + \" \")\n\t\t\t\t\t\n\t\t\t\tfilehandle.write(\"\\n\")\n\t\tfilehandle.close()\n\t\tprint( \"============ Done ============\",\"\\n\\n\")\n\nif __name__ == '__main__':\t\n\tcheck_gcp_path = '/home/dunbar/Research/wolverine/wolverineglacier/DF_TLCs/tlcameras.txt'\n\tpath = '/home/dunbar/Research/wolverine/'\n\tcliff = 'ref_cliff.JPG' #reference images to extract meta-data and predict gcp location\n\ttounge = 'ref_tounge.JPG'\n\tweather = 'ref_wx.JPG'\n\tcliff_gcp = 'wolverineglacier/cliff_cam_gcp.txt' #txt files for camera gcp's\n\ttounge_gcp = 'wolverineglacier/tounge_cam_gcp.txt'\n\tweather_gcp = 'wolverineglacier/wx_cam_gcp.txt'\n\tcliff_pose = (393506.713,6695855.641,961.337,np.radians(0),np.radians(0),np.radians(15)) # easting, northing, elevation (m), roll, pitch, yaw\n\ttounge_pose = (393797.378, 6694756.620, 767.029,0,0,0)#,np.radians(0),np.radians(10),np.radians(0)) # easting, northing, elevation (m), roll, pitch, yaw\n\tweather_pose = (392875.681,6696842.618,1403.860,np.radians(0),np.radians(-10),np.radians(30)) # easting, northing, elevation (m), roll, pitch, yaw\n\t\n\t'''\n\tprint(\"Processing Cliff \\n\")\n\tcliff_cam = Camera(image= os.path.join(path,cliff), rvec=cliff_pose[:3],tvec=cliff_pose[3:], instance=\"cliff_cam\")\n\tcliff_cam.extract_metadata()\n\tcliff_cam.procGCP(os.path.join(path,cliff_gcp))\n\tcliff_cam.estimatePose()\n\tcliff_cam.gcp_imgcords_predict(check_gcp_path)\n\t\n\t'''\n\tprint(\"Processing Tounge \")\n\tcliff_cam = Camera(image= os.path.join(path,tounge), rvec=tounge_pose[:3],tvec=tounge_pose[3:], instance=\"tounge_cam\")\n\tcliff_cam.extract_metadata()\n\tcliff_cam.procGCP(os.path.join(path,tounge_gcp))\n\tcliff_cam.estimatePose()\n\tcliff_cam.gcp_imgcords_predict(check_gcp_path)\n\n\tprint(\"Processing Weather\")\n\tcliff_cam = Camera(image= os.path.join(path,weather), rvec=weather_pose[:3],tvec=weather_pose[3:], instance=\"weather_cam\")\n\tcliff_cam.extract_metadata()\n\tcliff_cam.procGCP(os.path.join(path,weather_gcp))\n\tcliff_cam.estimatePose()\n\tcliff_cam.gcp_imgcords_predict(check_gcp_path)\n","sub_path":"scripts/optimization/pose_solvepnp.py","file_name":"pose_solvepnp.py","file_ext":"py","file_size_in_byte":5631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"223041381","text":"#!/usr/bin/env python\n#_*_ coding:utf-8 _*_\n# Author: jiachen\n\nimport time\nimport json\nfrom core import menu\nfrom core import auth\nfrom core import logger\nfrom core import accounts\nfrom core.auth import auth_login\nfrom core import transaction\nfrom conf import settings\n\n#设置菜单标题\nfirst_menu_title = [\"序号\",\"选项\"]\n#设置菜单内容\nfirst_menu_content = [[\"1\",\"查询个人信用卡信息\"],\n [\"2\",\"还款\"],\n [\"3\",\"提现\"],\n [\"4\",\"转账\"],\n [\"5\",\"当月消费账单\"],\n [\"6\",\"退出\"]]\n\n#设置用户临时数据\nuser_data = {\"account_id\": None,\n \"is_authenticated\": None,\n \"account_data\": None}\n\n#设置日志\naccess_log = logger.logger(\"access\")\ntrans_logger = logger.logger('transaction')\n\n#退出函数\ndef logout(user_data):\n '''\n :param user_data: 用户临时数据\n :return:\n '''\n exit()\n\n@auth_login\n#查询账户信息函数\ndef check_account_info(user_data):\n '''\n :param user_data: 账户临时数据\n :return:\n '''\n account_data = accounts.load_current_balance(user_data[\"account_id\"]) #加载最新的账户信息\n if account_data:\n account_info_title = [\"卡号\",\"可用额度\",\"最高额度\",\"开卡时间\",\"到期时间\",\"还款日\",\"状态\"]\n account_info_content = [account_data[\"id\"],\n account_data[\"balance\"],\n account_data[\"credit\"],\n account_data[\"enroll_date\"],\n account_data[\"expire_date\"],\n account_data[\"pay_day\"]]\n if account_data[\"status\"] == 0:\n account_info_content.append(\"正常\")\n elif account_data[\"status\"] == 1:\n account_info_content.append(\"冻结\")\n account_menu = menu.print_menu(account_info_title,account_info_content)\n print(\"\\033[1;33m%s\\033[0m\" % account_menu)\n\n@auth_login\n#还款函数\ndef repay(user_data):\n '''\n :param user_data: 账户临时数据\n :return:\n '''\n exit_flag = True #设置退出标记\n while exit_flag:\n account_data = accounts.load_current_balance(user_data[\"account_id\"]) #加载最新的账户信息\n repay_info_title = [\"最高额度\", \"可用额度\"]\n repay_info_content = [account_data[\"credit\"],\n account_data[\"balance\"]]\n repay_menu = menu.print_menu(repay_info_title, repay_info_content)\n print(\"\\033[1;33m%s\\033[0m\" % repay_menu)\n if account_data[\"status\"] == 0: #账户状态为正常\n repay_money = input(\"请输入还款金额,返回请按(b)>>>\").strip()\n if repay_money.isdigit() and int(repay_money) > 0:\n account_data = transaction.make_transaction(trans_logger,account_data,\"repay\",repay_money) #获取计算后的账户信息\n if account_data:\n print(\"\\033[1;32m还款操作成功\\033[0m\")\n elif repay_money == \"b\": #输入b返回上级菜单\n exit_flag = False\n else: #输入有误\n print(\"\\033[1;31m输入有误,请重新输入\\033[0m\")\n elif account_data[\"status\"] == 1: #账户状态为冻结\n print(\"\\033[1;31m此账户已被冻结,无法操作\\033[0m\")\n exit_flag = False\n\n@auth_login\n#提现函数\ndef withdraw(user_data):\n '''\n :param user_data: 账户临时数据\n :return:\n '''\n exit_flag = True #设置退出标记\n while exit_flag:\n account_data = accounts.load_current_balance(user_data[\"account_id\"]) #加载最新的账户信息\n withdraw_info_title = [\"最高额度\", \"可用额度\"]\n withdraw_info_content = [account_data[\"credit\"],\n account_data[\"balance\"]]\n withdraw_menu = menu.print_menu(withdraw_info_title, withdraw_info_content)\n print(\"\\033[1;33m%s\\033[0m\" % withdraw_menu)\n if account_data[\"status\"] == 0: #账户状态为正常\n withdraw_money = input(\"请输入取现金额,返回请按(b)>>>\").strip()\n if withdraw_money.isdigit() and int(withdraw_money) > 0:\n\n account_data = transaction.make_transaction(trans_logger, account_data, \"withdraw\", withdraw_money) #获取计算后的账户信息\n if account_data:\n print(\"\\033[1;32m提现操作成功\\033[0m\")\n elif withdraw_money == \"b\": #输入b返回上级菜单\n exit_flag = False\n else: #输入有误\n print(\"\\033[1;31m输入有误,请重新输入\\033[0m\")\n elif account_data[\"status\"] == 1: #账户状态为冻结\n print(\"\\033[1;31m此账户已被冻结,无法操作\\033[0m\")\n exit_flag = False\n\n@auth_login\n#转账函数\ndef transfer(user_data):\n '''\n :param user_data: 账户临时数据\n :return:\n '''\n exit_flag = True #设置退出标记\n while exit_flag:\n account_data = accounts.load_current_balance(user_data[\"account_id\"]) #加载最新的账户信息\n transfer_info_title = [\"最高额度\", \"可用额度\"]\n transfer_info_content = [account_data[\"credit\"],\n account_data[\"balance\"]]\n transfer_menu = menu.print_menu(transfer_info_title, transfer_info_content)\n print(\"\\033[1;33m%s\\033[0m\" % transfer_menu)\n if account_data[\"status\"] == 0: #账户状态为正常\n transfer_account_id = input(\"请输入要转账的账户,返回请按(b)>>>\").strip()\n if transfer_account_id == \"b\": #输入b返回上级菜单\n exit_flag = False\n else:\n transfer_account_data = accounts.load_current_balance(transfer_account_id) #加载被转账账户信息\n if transfer_account_data: #获取到被转账账户信息\n if transfer_account_data[\"status\"] == 0: #被转账账号状态为正常\n transfer_money = input(\"请输入要转账的金额>>>\").strip()\n if transfer_money.isdigit() and int(transfer_money) > 0:\n account_data = transaction.make_transaction(trans_logger, account_data, \"transfer\", transfer_money) #获取计算后的账户信息\n if account_data: #获取到计算后的账户信息\n transaction.make_transaction(trans_logger, transfer_account_data, \"repay\", transfer_money)\n print(\"\\033[1;32m转账成功\\033[0m\")\n else:\n print(\"\\033[1;31m输入有误,请重新输入\\033[0m\")\n elif transfer_account_data[\"status\"] == 1: #被转账账号状态为冻结\n print(\"被转账账户被冻结,无法操作\")\n elif account_data[\"status\"] == 1: #账户状态为冻结\n print(\"\\033[1;31m此账户已被冻结,无法操作\\033[0m\")\n exit_flag = False\n\n@auth_login\n#查询当月账单函数\ndef pay_check(user_data):\n '''\n :param user_data: 用户临时数据\n :return:\n '''\n query_flag = True #设置查询标记\n check_info1 = \"信用卡卡号:%s\" % user_data[\"account_id\"] #过滤字段1\n check_info2 = \"操作类型:consume\" #过滤字段2\n date = time.strftime(\"%Y-%m\",time.localtime()) #日期\n pay_check_title = [\"日期\",\"时间\",\"消费记录\"]\n pay_check_content = []\n file_path = \"%s\\%s\" % (settings.LOG_DIR,settings.LOG_TYPES[\"transaction\"])\n with open(file_path,\"r\",encoding=\"utf-8\") as f:\n for line in f.readlines():\n line_list = line.strip(\"\\n\").split()\n if date in line_list[0] and check_info1 == line_list[7] and check_info2 == line_list[8]:\n pay_check_content.append([line_list[0],line_list[1],line_list[-2]])\n query_flag = False\n if query_flag:\n print(\"\\033[1;31m本月无消费记录\\033[0m\")\n else:\n pay_check_menu = menu.print_menu(pay_check_title,pay_check_content)\n print(\"\\033[1;33m%s\\033[0m\" % pay_check_menu)\n\n#互动函数\ndef account_interactive(user_data):\n '''\n :param user_data: 账户临时信息\n :return:\n '''\n menu_dic = {\n '1': check_account_info,\n '2': repay,\n '3': withdraw,\n '4': transfer,\n '5': pay_check,\n '6': logout,\n }\n while True:\n print(\"==欢迎使用 强8216 ATM自助系统==\")\n first_menu = menu.print_menu(first_menu_title,first_menu_content)\n print(first_menu)\n first_choice = input(\"请输入要选择的序号>>>\").strip()\n if first_choice in menu_dic:\n menu_dic[first_choice](user_data)\n else:\n print(\"\\033[1;31m输入有误,请重新输入\\033[0m\")\n\ndef admin_interactive():\n '''\n :return:\n '''\n username = input(\"请输入管理员账号>>>\").strip()\n password = input(\"请输入管理员密码>>>\").strip()\n admin_data = auth.admin_auth(username)\n if admin_data:\n if admin_data[\"password\"] == password:\n print(\"\\033[1;32m登录成功\\033[0m\")\n exit_flag = True\n while exit_flag:\n admin_menu_title = [\"序号\",\"选项\"]\n admin_menu_content = [[\"1\",\"开卡\"],\n [\"2\", \"调整用户额度\"],\n [\"3\",\"账号权限修改\"],\n [\"4\",\"退出\"]]\n admin_menu = menu.print_menu(admin_menu_title,admin_menu_content)\n print(\"==欢迎使用 强8216 ATM管理系统==\")\n print(admin_menu)\n choice = input(\"请输入选择的选项>>>\").strip()\n if choice == \"1\": #开卡\n try:\n new_account_data = input(\"请输入开卡信息>>>\").strip()\n new_account_data = json.loads(new_account_data)\n if accounts.load_current_balance(str(new_account_data[\"id\"])):\n print(\"\\033[1;31m此账户已存在,开卡失败\\033[0m\")\n else:\n result = accounts.create_account(new_account_data)\n if result:\n print(\"\\033[1;32m开卡成功\\033[0m\")\n except:\n print(\"\\033[1;31m输入有误,请重新输入\\033[0m\")\n elif choice == \"2\": #调整用户额度\n account_id = input(\"请输入要修改的信用卡卡号>>>\").strip()\n account_data = accounts.load_current_balance(account_id)\n if account_data:\n new_credit = input(\"请输入新的额度>>>\").strip()\n if new_credit.isdigit() and int(new_credit) > 0:\n account_data[\"credit\"] = int(new_credit)\n result = accounts.dump_account(account_data)\n if result:\n print(\"\\033[1;32m调整用户额度成功\\033[0m\")\n else:\n print(\"\\033[1;31m输入有误,请重新输入\\033[0m\")\n elif choice == \"3\": #账号权限修改\n account_id = input(\"请输入要修改的信用卡卡号>>>\").strip()\n account_data = accounts.load_current_balance(account_id)\n if account_data:\n new_status = input(\"请输入要修改的权限0为正常、1为冻结>>>\").strip()\n if new_status == \"0\":\n account_data[\"status\"] = 0\n result = accounts.dump_account(account_data)\n if result:\n print(\"\\033[1;32m账号权限修改成功\\033[0m\")\n elif new_status == \"1\":\n account_data[\"status\"] = 1\n result = accounts.dump_account(account_data)\n if result:\n print(\"\\033[1;32m账号权限修改成功\\033[0m\")\n else:\n print(\"\\033[1;31m输入有误,请重新输入\\033[0m\")\n elif choice == \"4\": #退出\n exit_flag = False\n else: #其他\n print(\"\\033[1;31m输入有误,请重新输入\\033[0m\")\n else: #密码错误\n print(\"\\033[1;31m密码错误,退出程序\\033[0m\")\n\n#执行atm用户操作函数\ndef atm_run():\n '''\n :return:\n '''\n account_data = auth.login(user_data,access_log)\n if user_data[\"is_authenticated\"]:\n user_data[\"account_data\"] = account_data\n account_interactive(user_data)\n\n#执行atm管理系统函数\ndef manage_run():\n '''\n :return:\n '''\n admin_interactive()","sub_path":"atm/core/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"114395872","text":"import os\nimport json\n\n\nclass BaseDirConfig:\n \"\"\"\n Base app configuration for a directory.\n \"\"\"\n _cached = {}\n \"\"\":type: dict[type, dict[str, DirConfig]]\"\"\"\n\n def __init__(self, app, path):\n \"\"\"\n Initialize a new DirConfig instance for the given App. The `get` class method should be used instead of\n initializing this directly.\n\n :param app: App associated with the directory.\n :type app: pydgeot.app.App\n :param path: Directory to get configuration for.\n :type path: str\n \"\"\"\n self.app = app\n self.path = path\n\n self._load()\n\n @classmethod\n def get(cls, app, path):\n \"\"\"\n Get a DirConfig instance for the given file or directory path.\n\n :param app: App associated with the directory.\n :type app: pydgeot.app.App\n :param path:\n :type path: str\n \"\"\"\n if os.path.isfile(path):\n path = os.path.dirname(path)\n\n if cls not in cls._cached:\n cls._cached[cls] = {}\n\n if path in cls._cached[cls]:\n return cls._cached[cls][path]\n\n config = cls(app, path)\n cls._cached[cls][path] = config\n return config\n\n def _load(self):\n \"\"\"\n Load in the current path and parent configuration data.\n \"\"\"\n from pydgeot.app import AppError\n\n config = {}\n config_path = os.path.join(self.path, '{}pydgeot.conf'.format('' if self.path == self.app.root else '.'))\n\n # Find the parent config, so it can be inherited from.\n parent = None\n if self.path != self.app.root:\n parent_path = os.path.dirname(self.path)\n parent = self.__class__.get(self.app, parent_path)\n\n if os.path.isfile(config_path):\n try:\n with open(config_path) as fh:\n config = json.load(fh)\n except ValueError as e:\n raise AppError('Could not load config \\'{}\\': \\'{}\\''.format(config_path, e))\n\n self._parse(config_path, config, parent)\n\n def _parse(self, config_path, config, parent):\n \"\"\"\n Parse current path and parent configuration data retrieved from _load.\n\n :type config_path: str\n :type config: dict[str, Any]\n :type parent: DirConfig | None\n \"\"\"\n raise NotImplementedError\n\n @classmethod\n def _merge_dict(cls, target, source):\n \"\"\"\n Return a merged copy of two dictionaries. Overwriting any matching keys from the second over the first, but\n merging any dictionary values.\n\n :param target: Original dictionary to copy and update.\n :type target: dict\n :param source: Dictionary to update items from.\n :type source: dict\n :return: Copied and updated target dictionary.\n :rtype: dict\n \"\"\"\n import copy\n merged = copy.copy(target)\n for key in source:\n if key in merged and isinstance(merged[key], dict) and isinstance(source[key], dict):\n merged[key] = cls._merge_dict(merged[key], source[key])\n continue\n merged[key] = source[key]\n return merged\n\n\nclass DirConfig(BaseDirConfig):\n \"\"\"\n App configuration for a directory.\n \"\"\"\n def __init__(self, app, path):\n \"\"\"\n Initialize a new DirConfig instance for the given App. The `get` class method should be used instead of\n initializing this directly.\n\n :param app: App to associated with the directory.\n :type app: pydgeot.app.App\n :param path:\n :type path: str\n \"\"\"\n self.processors = set()\n \"\"\":type: set[pydgeot.processors.Processor]\"\"\"\n self.ignore = set()\n \"\"\":type: set[pydgeot.filesystem.Glob]\"\"\"\n self.extra = {}\n \"\"\":type: dict[str, object]\"\"\"\n\n super().__init__(app, path)\n\n def _parse(self, config_path, config, parent):\n \"\"\"\n Parse current path and parent configuration data retrieved from _load.\n\n :type config_path: str\n :type config: dict[str, Any]\n :type parent: DirConfig | None\n \"\"\"\n from pydgeot.app import AppError\n from pydgeot.filesystem import Glob\n\n # Convert a 'processors' key to a list of processor instances.\n processors = config.pop('processors', None)\n if isinstance(processors, list):\n for processor in processors:\n processor_inst = self.app.processors.get(processor, None)\n if processor_inst is not None:\n self.processors.add(processor_inst)\n else:\n raise AppError('Could not load config \\'{}\\', unable to find processor: \\'{}\\''.format(config_path,\n processor))\n elif processors is None and parent is not None:\n self.processors = parent.processors\n\n # Convert an 'ignore' key to a list of matchable globs.\n ignore = config.pop('ignore', None)\n if isinstance(ignore, list):\n for glob in ignore:\n if self.path not in (self.app.root, self.app.source_root):\n glob = self.app.relative_path(self.path).replace('\\\\', '/') + '/' + glob\n try:\n self.ignore.add(Glob(glob))\n except ValueError:\n raise AppError('Malformed glob in \\'{}\\': \\'{}\\''.format(config_path, glob))\n elif ignore is None and parent is not None:\n self.ignore = parent.ignore\n\n # Any extra keys remain as a dictionary, being merged in with the parent configs extra data.\n self.extra = config\n if parent is not None:\n self.extra = self.__class__._merge_dict(parent.extra, self.extra)\n","sub_path":"pydgeot/app/dirconfig.py","file_name":"dirconfig.py","file_ext":"py","file_size_in_byte":5870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"46545740","text":"def safe_pawns(pawns: set) -> int:\n \n count = 0\n for pawn1 in pawns:\n for pawn2 in pawns:\n if int(pawn2[1]) == int(pawn1[1]) - 1:\n if pawn2[0] == chr(ord(pawn1[0])+1) or pawn2[0] == chr(ord(pawn1[0])-1):\n count += 1\n break\n return count\n\nif __name__ == '__main__':\n #These \"asserts\" using only for self-checking and not necessary for auto-testing\n assert safe_pawns({\"b4\", \"d4\", \"f4\", \"c3\", \"e3\", \"g5\", \"d2\"}) == 6\n assert safe_pawns({\"b4\", \"c4\", \"d4\", \"e4\", \"f4\", \"g4\", \"e5\"}) == 1\n print(\"Coding complete? Click 'Check' to review your tests and earn cool rewards!\")\n","sub_path":"easy/pawn-brotherhood.py","file_name":"pawn-brotherhood.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"433958158","text":"import pyglet, math\n\ndef distance(p1=(0,0), p2=(0,0)):\n \"\"\" Returns the distance between two points \"\"\"\n return math.sqrt((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)\n\ndef create_title_label(text, batch):\n return pyglet.text.Label(text=text,\n x=400, y=575,\n anchor_x='center',\n anchor_y='top',\n font_name='Syncopate',\n font_size=62,\n color=(255, 255, 255, 255),\n batch=batch)\n\ndef create_menu_label(text, batch, selected=False, y=400):\n return pyglet.text.Label(text=text,\n x=400, y=y,\n anchor_x='center',\n anchor_y='bottom',\n font_name='Syncopate',\n font_size=42,\n color=(255, 255, 255, 255 if selected else 76),\n batch=batch)\n\ndef create_menu_labels(texts, batch, first_selected=True, y_start=400, y_step=80):\n menu = list()\n y = y_start\n for i in range(len(texts)):\n menu.append(create_menu_label(texts[i], batch, selected=i==0, y=y))\n y -= y_step\n\n return menu\n","sub_path":"version4_2/game/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"324217699","text":"# OR 게이트\n# :두 입력(x1, x2)이 모두 0일 경우에만 0을 출력, 그외에는 1을 출력\n\nimport numpy as np\n\ndef OR(x1, x2):\n x = np.array([x1, x2])\n w = np.array([0.5, 0.5])\n b = -0.2\n tmp = np.sum(w*x) + b\n if tmp <=0:\n return 0\n else:\n return 1\n\nprint(OR(0,0)) # 0\nprint(OR(0,1)) # 1\nprint(OR(1,0)) # 1\nprint(OR(1,1)) # 1\n","sub_path":"2.3.1.OR.py","file_name":"2.3.1.OR.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"382083551","text":"import unittest\nimport time\n\n\nclass HighlightElements(unittest.TestCase):\n\n def highlight(self, element, duration=1):\n driver = self.driver\n\n # Store original style so it can be reset later\n original_style = element.get_attribute(\"style\")\n\n # Style element with dashed red border\n driver.execute_script(\n \"arguments[0].setAttribute(arguments[1], arguments[2])\",\n element,\n \"style\",\n \"border: 5px solid red; border-style: dashed; animation: 3s infinite 10\")\n\n # Keep element highlighted for a spell and then revert\n if (duration > 0):\n time.sleep(duration)\n driver.execute_script(\n \"arguments[0].setAttribute(arguments[1], arguments[2])\",\n element,\n \"style\",\n original_style)\n","sub_path":"highlight_elements.py","file_name":"highlight_elements.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"634559367","text":"from django.utils.timezone import now, timedelta, make_aware\nfrom datastore import models\nfrom .shared import OAuthTestCase\n\nfrom oauth2_provider.models import AccessToken\n\nfrom eemeter.consumption import ConsumptionData as EEMeterConsumptionData\nfrom eemeter.project import Project as EEMeterProject\nfrom eemeter.examples import get_example_project\nfrom eemeter.evaluation import Period\n\nfrom datetime import datetime\n\nimport json\nimport pytz\n\nclass MeterRunAPITestCase(OAuthTestCase):\n\n def setUp(self):\n \"\"\"\n Setup methods for a eemeter run storage\n engine.\n \"\"\"\n super(MeterRunAPITestCase,self).setUp()\n\n self.project = models.Project.objects.create(\n project_owner=self.user.projectowner,\n project_id=\"PROJECT_ID\",\n baseline_period_start=None,\n baseline_period_end=datetime(2012, 1, 1, tzinfo=pytz.UTC),\n reporting_period_start=datetime(2012, 2, 1, tzinfo=pytz.UTC),\n reporting_period_end=None,\n zipcode=\"91104\",\n weather_station=\"722880\",\n latitude=0,\n longitude=0,\n )\n\n elec = models.ConsumptionMetadata.objects.create(\n project=self.project,\n fuel_type=\"E\",\n energy_unit=\"KWH\",\n )\n\n gas = models.ConsumptionMetadata.objects.create(\n project=self.project,\n fuel_type=\"NG\",\n energy_unit=\"THM\",\n )\n\n self.consumption_metadatas = [elec, gas]\n\n for i in range(0, 1000, 30):\n models.ConsumptionRecord.objects.create(\n metadata=elec,\n start=datetime(2011, 1, 1, tzinfo=pytz.UTC) + timedelta(days=i),\n value=1.0,\n estimated=False,\n )\n\n models.ConsumptionRecord.objects.create(\n metadata=gas,\n start=datetime(2011, 1, 1, tzinfo=pytz.UTC) + timedelta(days=i),\n value=1.0,\n estimated=False,\n )\n\n ## Attempt to run the meter\n self.project.run_meter(start_date=make_aware(datetime(2011,1,1)), end_date=make_aware(datetime(2015,1,1)))\n self.meter_runs = [models.MeterRun.objects.get(consumption_metadata=cm) for cm in self.consumption_metadatas]\n assert len(self.meter_runs) == 2\n\n def test_meter_run_read(self):\n \"\"\"\n Tests reading meter run data.\n \"\"\"\n for meter_run, consumption_metadata in zip(self.meter_runs,self.consumption_metadatas):\n\n response = self.get('/api/v1/meter_runs/{}/'.format(meter_run.id))\n assert response.status_code == 200\n assert response.data[\"project\"] == self.project.id\n assert response.data[\"consumption_metadata\"] == consumption_metadata.id\n\n model_parameters_baseline = json.loads(response.data[\"model_parameter_json_baseline\"])\n model_parameters_reporting = json.loads(response.data[\"model_parameter_json_reporting\"])\n\n assert type(model_parameters_baseline) == dict\n assert type(model_parameters_reporting) == dict\n\n assert len(response.data[\"serialization\"]) > 7000\n\n assert len(response.data[\"dailyusagebaseline_set\"]) == 1461\n assert len(response.data[\"dailyusagereporting_set\"]) == 1461\n\n assert response.data[\"meter_type\"] == \"DFLT_RES_E\" or \\\n response.data[\"meter_type\"] == \"DFLT_RES_NG\"\n\n assert type(response.data[\"annual_usage_baseline\"]) == float\n assert type(response.data[\"annual_usage_reporting\"]) == float\n assert type(response.data[\"gross_savings\"]) == float\n assert type(response.data[\"annual_savings\"]) == float\n assert type(response.data[\"cvrmse_baseline\"]) == float\n assert type(response.data[\"cvrmse_reporting\"]) == float\n","sub_path":"datastore/tests/views/test_meter_run.py","file_name":"test_meter_run.py","file_ext":"py","file_size_in_byte":3882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"69376828","text":"import hashlib\nimport collections\nimport logging\nimport re\nimport socket\n\nlogger = logging.getLogger(__name__)\n\nRE_IP = re.compile(\n \"(?P^\\\\d{1,3}\\\\.\\\\d{1,3}\\\\.\\\\d{1,3}\\\\.)(?P\\\\d{1,3}$)\")\n\n\ndef sorted_dict_by_key(unsorted_dict):\n \"\"\"\n sorted by key\n\n Parameters\n ----------\n unsorted_dict : dict\n\n Returns\n -------\n collections.OrderedDict\n\n See Also\n --------\n >>> block = {\"b\": 2, \"a\": 1}\n >>> block2 = {\"a\": 1, \"b\": 2}\n >>> print(hashlib.sha256(str(block).encode()).hexdigest())\n 46e391c4281c162dc452a58d0a756ec6568ebe3acbd9d3731d1eccc66c23d17b\n >>> print(hashlib.sha256(str(block2).encode()).hexdigest())\n 3dffaea891e5dbadb390da33bad65f509dd667779330e2720df8165a253462b8\n >>> print(hashlib.sha256(str(sorted_dict_by_key(block)).encode()).hexdigest())\n 3319a4f151023578ff06b0aa1838ee7ab82082fd6e43c2274ff0713f1ed23d53\n >>> print(hashlib.sha256(str(sorted_dict_by_key(block2)).encode()).hexdigest())\n 3319a4f151023578ff06b0aa1838ee7ab82082fd6e43c2274ff0713f1ed23d53\n \"\"\"\n return collections.OrderedDict(sorted(unsorted_dict.items(), key=lambda d: d[0]))\n\n\ndef pprint(chains):\n \"\"\"\n 出力形式\n\n Parameters\n ----------\n chains : list in dict\n\n See Also\n --------\n \"\"\"\n for i, chain in enumerate(chains):\n print(f'{\"=\"*25} Chain {i} {\"=\"*25}')\n # kとvの幅を揃える\n for k, v in chain.items():\n if k == \"transactions\":\n print(k)\n for d in v:\n print(f'{\"-\"*40}')\n for kk, vv in d.items():\n print(f\"{kk:30}{vv}\")\n else:\n print(f\"{k:15}{v}\")\n print(f'{\"*\"*25}')\n\n\ndef is_found_host(target, port):\n \"\"\"\n 他のノードが立ち上がっているか調べるsocket\n\n netword address: AF_INET\n TCP/IP: socket.SOCK_STREAM\n\n Parameters\n ---------- \n target : \n\n port : \n\n See Also\n --------\n # python blockchain_server.py\n # >>> is_found_host(\"127.0.0.1\", 5000)\n # True\n \"\"\"\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n sock.settimeout(1)\n try:\n sock.connect((target, port))\n return True\n except Exception as ex:\n logger.error({\n \"action\": \"is_found_host\",\n \"target\": target,\n \"port\": port,\n \"ex\": ex\n })\n return False\n\n\ndef find_neighbours(my_host, my_port, start_ip_range, end_ip_range, start_port, end_port):\n \"\"\"\n nodeを検索する. \n\n Parameters\n ----------\n my_host: int\n\n my_port: int\n\n start_ip_range : int\n\n end_ip_range : int\n\n start_port : int\n\n end_port : int\n\n Returns\n -------\n neighbours : list\n 対象のサーバーを格納する\n\n See Also\n --------\n \"\"\"\n address = f\"{my_host}:{my_port}\"\n m = RE_IP.search(my_host)\n if not m:\n return None\n\n prefix_host = m.group(\"prefix_host\")\n last_ip = m.group(\"last_ip\")\n\n neighbours = []\n for guess_port in range(start_port, end_port):\n for ip_range in range(start_ip_range, end_ip_range):\n guess_host = f\"{prefix_host}{int(last_ip)+int(ip_range)}\"\n guess_address = f\"{guess_host}:{guess_port}\"\n # ignored my_host\n if is_found_host(guess_host, guess_port) and not guess_address == address:\n neighbours.append(guess_address)\n return neighbours\n\n\ndef get_host():\n \"\"\"\n socketで自身のホストのIPアドレスを探す \n\n See Also\n --------\n \"\"\"\n try:\n return socket.gethostbyname(socket.gethostname())\n except Exception as ex:\n logger.debug({\"action\": \"get_host\", \"ex\": ex})\n return \"127.0.0.1\"\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"549506142","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport os\nimport subprocess\n\n\nfor name in os.listdir('stacks'):\n try:\n name, ext = name.split('.')\n except Exception:\n continue\n if ext != 'yml':\n continue\n command = ''\n command += 'docker-cloud stack inspect {name} || '\n command += 'docker-cloud stack create --sync -f stacks/{name}.yml -n {name} && '\n command += 'docker-cloud stack update --sync -f stacks/{name}.yml {name}'\n command = command.format(name=name)\n subprocess.call(command, shell=True)\n print('Pushed stack: %s' % name)\n","sub_path":"scripts/push-stacks.py","file_name":"push-stacks.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"39933890","text":"import speech_recognition as sr\n\nr = sr.Recognizer()\n\nwith sr.Microphone() as source:\n command_audio = r.listen(source)\n\ncommand_string = \"\"\n\ntry:\n command_string = r.recognize_google(command_audio)\n print(command_string)\nexcept LookupError:\n print(\"Couldn't understand you, bro.\")\n","sub_path":"Simulator/out/production/JavaFX-Flight-Simulator/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"560853674","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def levelOrderBottom(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n res,next=[],[]\n if root:\n temp=[root]\n else:\n return res\n res.append(temp)\n while 1:\n for v in temp:\n if v.left:\n next.append(v.left) \n if v.right:\n next.append(v.right)\n if next==[]:\n break\n res.append(next)\n temp=next\n next=[]\n return [[v.val for v in x] for x in reversed(res)]","sub_path":"mu_wang/9_25/Binary Tree Level Order Traversal II.py","file_name":"Binary Tree Level Order Traversal II.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"466055647","text":"# Global imports\nimport time, importlib, datetime\nfrom random import randint\nimportlib.import_module(\"converse\")\nfrom converse import no_answer\n\n# Global variables\nspeech_detected = False\ntouched = False\nwarned = False\ncounter_foot, counter_head = 0, 0\n\nnames = [\"Sander\", \"Koen\"]\nnumbers = []\nfor x in range(0, 101):\n numbers.append(str(x))\n\n\ndef set_touched(is_touched):\n global touched\n touched = is_touched\n\n\ndef increase_foot_counter():\n global counter_foot\n counter_foot += 1\n\n\ndef increase_head_counter():\n global counter_head\n counter_head += 1\n\n\ndef get_counter_head():\n global counter_head\n return counter_head\n\n\ndef get_counter_foot():\n global counter_foot\n return counter_foot\n\n\ndef initialize_student(tts, speech_recognition, memory):\n \"\"\"\n Initialize the student, retrieving its name.\n :param tts: TextToSpeech engine\n :param speech_recognition: SpeechRecognition engine\n :param memory: Memory engine\n :return: name of the student\n \"\"\"\n # Set the vocabulary to recognise all the names\n speech_recognition.setVocabulary(names, False)\n # Start the speech recognition engine with user Test_ASR\n tts.say(\"\")\n speech_recognition.subscribe(\"GET_NAME\")\n print('Speech recognition engine started')\n speech_recognition.pause(False)\n time.sleep(3.0)\n speech_recognition.pause(True)\n name = memory.getData(\"WordRecognized\")\n speech_recognition.unsubscribe(\"GET_NAME\")\n\n\ndef hear_answer(tts, speech_recognition, memory, cur_time):\n \"\"\"\n Retrieve the answer to an exercise.\n :param tts: TextToSpeech engine\n :param speech_recognition: SpeechRecognition engine\n :param memory: Memory engine\n :return: answer\n \"\"\"\n speech_recognition.setVocabulary(numbers, False)\n tts.say(\"\")\n answer = \"\"\n memory.subscribeToEvent(\"TouchChanged\",\n \"ReactToTouch\",\n \"onTouched\")\n while answer == \"\":\n if touched:\n speech_recognition.subscribe(\"GET_ANSWER\")\n print('Speech recognition engine started')\n speech_recognition.pause(False)\n time.sleep(3.0)\n speech_recognition.pause(True)\n answer = memory.getData(\"WordRecognized\")\n print(\"data: %s\" % answer)\n # Confidence must be bigger than 0.5 in order to continue\n if answer[1] < 0.45:\n answer = \"\"\n else:\n answer = str(answer[0])\n speech_recognition.unsubscribe(\"GET_ANSWER\")\n if answer == \"\":\n no_answer(tts, randint(0, 3))\n set_touched(False)\n elif not warned and datetime.datetime.now() > (cur_time + datetime.timedelta(minutes=3)):\n global warned\n warned = True\n tts.say(\"Je werkt nu 3 minuten aan deze som. Fouten maken mag. Het is niet erg als je het antwoord niet weet. Zeg maar gewoon wat je denkt.\")\n memory.unsubscribeToEvent(\"TouchChanged\",\n \"ReactToTouch\")\n global warned\n warned = False\n return answer\n","sub_path":"no_feedback_nao2/student.py","file_name":"student.py","file_ext":"py","file_size_in_byte":3100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"537665053","text":"# Ternary Operator\n\nis_friend = True\n\ncan_message = \"message allowed\" if is_friend else \"not\"\n\nprint(can_message)\n\n# Short Circuting\n\nis_magician = False\nis_expert = False\n\n# Check if magician and expert: \"you are a master\"\n\n# Check if mag but not expert: \"at least you're getting there\"\n\n# If you're not a mag: \"You need magic powers\"\n\nif is_magician == True and is_expert == True:\n print(\"You are a master\")\nelif is_magician == True and is_expert == False:\n print(\"At least you're getting there\")\nelif not is_magician:\n print(\"You need magic powers\")\n\n# == vs is\n\n# is checks location of memory is the same\n\n# print(True is True)\n# print(1 is 1)\n# print([] is []) False\n# print(10 is 10) True\n\n\nuser = {\n 'age': 15,\n 'name': \"anil\",\n 'sex': \"male\"\n}\n\nfor item in user.values():\n print(item)\n","sub_path":"Ternary/ternary.py","file_name":"ternary.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"564088876","text":"import datetime\n\nfrom flask import g\nfrom app.ext import raw_db, db\nfrom app.sqls import message_sqls\nfrom app.utils.time_utils import datetime_to_timestamp\nfrom app.db_models.message import Message,MessageType,MessageStatus\n\ndef get_messages_by_page(page, page_size):\n\n\tparameters = {\n 'user_id': g.user.id,\n 'offset': (page - 1) * page_size,\n 'limit': page_size\n\t}\n\n\tmessages = raw_db.query(message_sqls.get_message_by_page, parameters).to_dict()\n\n\tfor message in messages:\n\t\tmessage_type = message.get('type')\n\t\tif message_type == MessageType.TASK.value or message_type == MessageType.COMMENT.value or message_type == MessageType.REPLY.value:\n\t\t\tsql = message_sqls.get_task_name_by_id\n\t\telse:\n\t\t\tcontinue\n\n\t\tentity = raw_db.query(sql, message_entity_id = message.get('messageEntityId')).first()\n\n\t\tif entity:\n\t\t\tentity = entity.to_dict()\n\t\t\tmessage['name'] = entity.get('name')\n\t\telse:\n\t\t\tmessage['name'] = ''\n\n\treturn messages\n\ndef create_message(parameters):\n\n\tmessage = Message.from_dict(g.args.update(parameters))\n\tmessage.from_uid = g.user.id\n\n\tdb.session.add(message)\n\tdb.session.commit()\n\ndef update_all_message(status):\n\n\tmessage_status = MessageStatus[status.upper()]\n\traw_db.query(message_sqls.update_all_messages_status, status = message_status.value, user_id = g.user.id)\n\ndef update_specific_message(id, status):\n\n\tmessage_status = MessageStatus[status.upper()]\n\traw_db.query(message_sqls.update_message_status, status = message_status.value, user_id = g.user.id, message_id = id)\n\n\ndef get_new_message_count():\n\n\tcount = raw_db.query(message_sqls.get_new_message_count, user_id = g.user.id).first().to_dict()\n\n\treturn count","sub_path":"app/services/message_services.py","file_name":"message_services.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"301297348","text":"# coding=UTF-8\nfrom string import Template\nimport random\nfrom commandbase import BaseCommand\n\n## Copypaste this example command to create new scratch commands\n## Leave this one alone so new commands can be made from it.\n## Also: Please indent using spaces.\nclass ExampleCommand( BaseCommand ):\n\n def __init__(self):\n BaseCommand.__init__( self )\n self.templates = [ Template(\"lobs a dolphin at $name.\") ]\n self.command_mappings = [ \"w3t\", \"splashy\" ]\n self.enabled = False # change to True (or just delete this line) to enable a command\n\n def generate( self, name ):\n template = random.choice( self.templates )\n message_out = template.substitute(name=name)\n return \"/me %s\" % message_out\n\n \nclass TrialCommand( BaseCommand ):\n\n def __init__(self):\n BaseCommand.__init__( self )\n self.command_mappings = [ \"trial\" ]\n self.templates = [ Template(\"asks $name to leave, never to return.\"),\n Template(\"thinks that it's OK for $name to stay a little while longer.\"),\n Template(\"doesn't like Kafka.\"),\n Template(\"gets the bouncers onto $name.\"),\n Template(\"calls his Mafia mates.\"),\n Template(\"has rigged the jury against $name.\"),\n Template(\"makes $name a straw man.\"),\n Template(\"is wearing a wig.\"),\n Template(\"dozed off.\"),\n Template(\"bonks $name on the head with his gavel.\"),\n Template(\"thinks Facebook is a more suitable environ for $name.\"),\n Template(\"asks $name to bugger off to LambdaMOO.\"),\n Template(\"is involved in a bit of extraordinary rendition of $name.\"),\n Template(\"invades the Ecuadorian embassy to extradite $name.\"),\n Template(\"gives $name a perminent Phactory Bar green card.\")\n ]\n\n def generate( self, name ):\n template = random.choice( self.templates )\n message_out = template.substitute(name=name)\n return \"/me %s\" % message_out\n\n\n \nclass MakeItSoCommand( BaseCommand ):\n\n def __init__(self):\n BaseCommand.__init__( self )\n self.command_mappings = [ \"doit\" ]\n self.templates = [ Template(\"shouts at $name: \\\"Make it so!\\\"\"),\n Template(\"wonders why $name hasn't made that thing he's babbling on about yet.\")\n \n ]\n\n def generate( self, name ):\n template = random.choice( self.templates )\n message_out = template.substitute(name=name)\n return \"/me %s\" % message_out \n \n \nclass ChickenTownCommand( BaseCommand ):\n\n def __init__(self):\n BaseCommand.__init__( self )\n self.command_mappings = [ \"chickentown\" ]\n self.templates = [ Template(\"says the fucking beer is fucking fucked\"),\n Template(\"knows the fucking crisps are fucking old\"),\n Template(\"wants the fucking punters off his fucking back\"),\n Template(\"smells the fucking dope in the fucking bogs\"),\n Template(\"pours a fucking !drink for the fucking lads\"), \n Template(\"mops the fucking floor with a fucking mop\"),\n Template(\"cleans the fucking glasses with some fucking water\"),\n Template(\"flicks some fucking peanuts in $name’s fucking glass\"),\n Template(\"plays some fucking darts with the fucking some fucking darts\"),\n Template(\"serves a fucking !snack to the fucking law\")\n ]\n\n def generate( self, name ):\n template = random.choice( self.templates )\n message_out = template.substitute(name=name)\n return \"/me %s\" % message_out \n \n \n \nclass ShootoutCommand( BaseCommand ):\n\n def __init__(self):\n BaseCommand.__init__( self )\n self.command_mappings = [ \"shootout\" ]\n self.templates = [ Template(\"does gun fingers at $name.\"),\n Template(\"makes a machine gun noise with his mouth.\"),\n Template(\"turns around in slow motion.\"),\n Template(\"reloads.\"),\n Template(\"blows the smoke away from his invisible barrel.\"),\n Template(\"spins his pretend revolver.\"),\n Template(\"adjusts his ten-gallon hat.\"),\n Template(\"holsters his pistol.\")\n ]\n\n def generate( self, name ):\n template = random.choice( self.templates )\n message_out = template.substitute(name=name)\n return \"/me %s\" % message_out\n\nclass AnusCommand( BaseCommand ):\n\n def __init__(self):\n BaseCommand.__init__( self )\n self.command_mappings = [ \"anus\" ]\n self.templates = [ Template(\"(mooning)\"),\n Template(\"goes all yadda yadda yadda\"),\n Template(\"looks at a picture of !satan\")\n ]\n\n def generate( self, name ):\n template = random.choice( self.templates )\n message_out = template.substitute(name=name)\n return \"/me %s\" % message_out\n \n \nclass HoyleCommand( BaseCommand ):\n\n def __init__(self):\n BaseCommand.__init__( self )\n self.command_mappings = [ \"hoyle\", \"atom\", \"atomoil\" ]\n self.templates = [ Template(\"gets a bit ranty.\"),\n Template(\"does a !satan on !satan.\"),\n Template(\"causes trouble.\"),\n Template(\"twiddles knobs.\")\n ]\n\n def generate( self, name ):\n template = random.choice( self.templates )\n message_out = template.substitute(name=name)\n return \"/me %s\" % message_out\n \n\nclass PeterCommand( BaseCommand ):\n\n def __init__(self):\n BaseCommand.__init__( self )\n self.command_mappings = [ \"peter\", \"pit\", \"bihr\" ]\n self.templates = [ Template(\"invites $name to a conference.\"),\n Template(\"has hours of panels to fill.\"),\n Template(\"assembles the band\"),\n Template(\"gets the bar into SXSW.\"),\n Template(\"fires up his !prezi\"),\n Template(\"goes solo\") \n ]\n\n def generate( self, name ):\n template = random.choice( self.templates )\n message_out = template.substitute(name=name)\n return \"/me %s\" % message_out\n\n\nclass GoonCommand( BaseCommand ):\n\n def __init__(self):\n BaseCommand.__init__( self )\n self.command_mappings = [ \"goon\", \"bouncer\" ]\n self.templates = [ Template(\"leans on $name.\"),\n Template(\"kneecaps $name.\"),\n Template(\"asks $name to take a seat.\"),\n Template(\"cracks his knuckles.\"),\n Template(\"flashes a toothless grin at $name.\"),\n Template(\"doesn't have a neck.\"),\n Template(\"rotates his head, crunching his bones.\"),\n Template(\"is wearing a donkey jacket.\"),\n Template(\"tells $name to behave.\"),\n Template(\"emails $name a toe.\"),\n Template(\"can't be bought.\"),\n Template(\"is selling DVD-players round the back of the pub.\"),\n Template(\"thinks $name wants to 'ave a bit of fun.\"),\n Template(\"posts a naked picture of $name to their family.\"),\n Template(\"knows a thing or two about $name.\"),\n Template(\"peels an orange, very bloody slowly.\"),\n Template(\"bundles $name into the boot of his Vauxhall.\"),\n Template(\"has a picture of $name's family.\"),\n Template(\"thinks $name has a nice place here. Be a shame if anything happened to it.\"),\n Template(\"suggests that $name should know what's good for them.\"),\n Template(\"mutters something vaguely menacing in a gravelly voice to $name.\")\n ]\n\n def generate( self, name ):\n template = random.choice( self.templates )\n message_out = template.substitute(name=name)\n return \"/me %s\" % message_out\n\nclass LoonCommand( BaseCommand ):\n\n def __init__(self):\n BaseCommand.__init__( self )\n self.command_mappings = [ \"loon\", \"mad\" ]\n self.templates = [ Template(\"wears a foil !hat.\"),\n Template(\"has mercury poisoning.\"),\n Template(\"believes David Icke.\"),\n Template(\"talks to himself.\"),\n Template(\"hasn't washed for weeks.\"),\n Template(\"doesn't trust the barge folk.\"),\n Template(\"has all his money in carrier bags under the bed.\"),\n Template(\"is concerned about all the lizards.\"),\n Template(\"is carrying a copy of Catcher In The Rye.\"),\n Template(\"cuts out bits of newspapers for his scrapbooks.\"),\n Template(\"is still listening to !gangnam.\"),\n Template(\"is late for a !tea party.\"),\n Template(\"thinks $name has stolen his thoughts.\"),\n Template(\"is called Bobbin. Are you my mother?\")\n ]\n\n def generate( self, name ):\n template = random.choice( self.templates )\n message_out = template.substitute(name=name)\n return \"/me %s\" % message_out\n\nclass MynewCommand( BaseCommand ):\n\n def __init__(self):\n BaseCommand.__init__( self )\n self.command_mappings = [ \"mynew\", \"new\" ]\n self.templates = [ Template(\"understands that $name's new $startup is called \\\"$word\\\".\") ]\n self.startup = [ \"startup\",\n \"thing\",\n \"product\",\n \"habit\",\n \"position\",\n \"desire\",\n \"beau\" ]\n\n self.word = [ \"Social Media Narcissism\",\n \"Guru Zentrum\",\n \"Corporate Density\",\n \"Spatial Complexity\",\n \"Loving Spoonful\",\n \"Braun Zucker\",\n \"Algorithmic Data Massage\",\n \"New Aesthetic Fashion\",\n \"Financial Jiu Jitsu\",\n \"Culture Jam\",\n \"Cube Farm\",\n \"Beanbag Office\",\n \"Stress Puppy\",\n \"Food Stamps\",\n \"Seagull Management\",\n \"Ninja Central\",\n \"Handsome Adult\",\n \"Bereaved Objects\",\n \"Absolute Nothingness\",\n \"Don\\'t ruin a good story with numbers!\",\n \"Pipe Bomb\",\n \"True Say\",\n \"!startup\",\n \"Handspeed Record\",\n \"Stealth Made\",\n \"Broken Windows\",\n \"Me or the Chief\",\n \"Shitfaced & Reeling\",\n \"WAZZOCK, Inc.\",\n \"Dance Syndrome\",\n \"Adam Hoyle's Massive !Anus\",\n \"Engagement Metrics\",\n \"Barry\",\n \"Piss und Shit\",\n \"Creative Technologisms\",\n \"Dedicated Solutioneering\",\n \"Don\\'t Call It a !startup\",\n \"Blended Synergy\",\n \"Billy Cosby Sweater Design\" ]\n\n def generate( self, name ):\n startup = random.choice( self.startup )\n word = random.choice( self.word )\n template = random.choice( self.templates )\n message_out = template.substitute(word=word,name=name, startup=startup)\n return \"/me %s\" % message_out\n \nclass ChristmasCommand( BaseCommand ):\n\n def __init__(self):\n BaseCommand.__init__( self )\n self.command_mappings = [ \"christmas\", \"chrimble\", \"santa\" ]\n self.templates = [ Template(\"kisses $name under the mistletoe.\"),\n Template(\"has had too much eggnog.\"),\n Template(\"asks if $name has kept the receipt.\"),\n Template(\"likes a bit of the dark meat.\"),\n Template(\"is soaked in brandy.\"),\n Template(\"sets fire to the decorative wreath.\"),\n Template(\"puts $name on top of the tree.\"),\n Template(\"gets $name a book token.\"),\n Template(\"eats all the Roses.\"),\n Template(\"has a lame party-popper.\"),\n Template(\"asks $name to carve a big of leg and breast.\")\n ]\n\n def generate( self, name ):\n template = random.choice( self.templates )\n message_out = template.substitute(name=name)\n return \"/me %s\" % message_out\n \n \nclass SxeCommand( BaseCommand ):\n\n def __init__(self):\n BaseCommand.__init__( self )\n self.command_mappings = [ \"sxe\", \"edge\" ]\n self.templates = [ Template(\"is listening to Minor Threat.\"),\n Template(\"draws Xs on the back of his hands.\"),\n Template(\"slaps the cigarette out of $name's mouth.\"),\n Template(\"is drinking Pepsi.\"),\n Template(\"advocates a drug-free existence.\"),\n Template(\"is wearing some awesome Nike dunks.\"),\n ]\n\n def generate( self, name ):\n template = random.choice( self.templates )\n message_out = template.substitute(name=name)\n return \"/me %s\" % message_out \n\nclass FFSCommand( BaseCommand ):\n\n def __init__(self):\n BaseCommand.__init__( self )\n self.command_mappings = [ \"ffs\" ]\n self.templates = [ Template(\"for fucks sake, $name\")\n ]\n\n def generate( self, name ):\n template = random.choice( self.templates )\n message_out = template.substitute(name=name)\n return \"%s\" % message_out \n\n\nclass KickCommand( BaseCommand ):\n\n def __init__(self):\n BaseCommand.__init__( self )\n self.command_mappings = [ \"kick\", \"ban\", \"evict\", \"bar\" ]\n self.templates = [ Template(\"warns $name about their behaviour.\"),\n Template(\"points at the rules on the board. Tuts at $name.\"),\n Template(\"reminds $name of the Bar Rules.\"),\n Template(\"tells $name that they're on their final warning.\"),\n Template(\"puts $name in the bins\"),\n Template(\"frogmarches $name off the premises.\"),\n Template(\"shakes his head at $name.\")\n ]\n\n def generate( self, name ):\n template = random.choice( self.templates )\n message_out = template.substitute(name=name)\n return \"/me %s\" % message_out\n \n\nclass SacrumCommand( BaseCommand ):\n\n def __init__(self):\n BaseCommand.__init__( self )\n self.command_mappings = [ \"dovey\",\"german\" ]\n self.templates = [ Template(\"sends $name much warmth.\"),\n Template(\"is European man with skills in advertising.\"),\n Template(\"has his own pencils.\"),\n Template(\"got in to funky advertising agency.\"),\n Template(\"sharpen pencil and top-up mobile phone.\"),\n Template(\"is availability on Wednesdays and CVon request.\"),\n Template(\"applies for a job at W+K.\"),\n Template(\"is sending out the right charges for right customer.\"),\n Template(\"is thanking you from his bottom.\"),\n Template(\"has brand warmness.\"),\n Template(\"seek advices from key figures in marketing arena.\")\n ]\n\n def generate( self, name ):\n template = random.choice( self.templates )\n message_out = template.substitute(name=name)\n return \"/me %s\" % message_out\n\n \nclass WaaaassssaaaapCommand( BaseCommand ):\n\n def __init__(self):\n BaseCommand.__init__( self )\n self.command_mappings = [ \"Waaaassssaaaap\" ]\n self.templates = [ Template(\"nods at $name.\"),\n Template(\"replies to $name, waaaaaaaaaassssaaaaaaaaaaapp!\"),\n Template(\"asks $name what they're upto.\"),\n Template(\"is just having a Bud.\"),\n Template(\"nods. True, true.\")\n ]\n\n def generate( self, name ):\n template = random.choice( self.templates )\n message_out = template.substitute(name=name)\n return \"/me %s\" % message_out\n\n\n\n","sub_path":"commands/commandscratch.py","file_name":"commandscratch.py","file_ext":"py","file_size_in_byte":17531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"382584754","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Author: Idealis Consulting\n# Copyright (c) 2016 Idealis Consulting S.A. (http://www.idealisconsulting.com)\n# All Rights Reserved\n#\n# WARNING: This program as such is intended to be used by professional\n# programmers who take the whole responsibility of assessing all potential\n# consequences resulting from its eventual inadequacies and bugs.\n# End users who are looking for a ready-to-use solution with commercial\n# guarantees and support are strongly advised to contact a Free Software\n# Service Company.\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##############################################################################\n\nfrom odoo import api, fields, models, _\n\n\nclass UnvcStockMove(models.Model):\n _inherit = \"stock.move\"\n\n kit_product_details = fields.Text(string='Kit Details')\n\n def _prepare_procurement_values(self):\n vals = super(UnvcStockMove, self)._prepare_procurement_values()\n if self.kit_product_details:\n vals['kit_product_details'] = self.kit_product_details\n return vals\n\n def _prepare_phantom_move_values(self, bom_line, quantity):\n vals = super(UnvcStockMove, self)._prepare_phantom_move_values(bom_line, quantity)\n if self.sale_line_id:\n kit_quantity = quantity / bom_line.product_qty\n vals['kit_product_details'] = \"%s X %s PC / %s\" % (kit_quantity, bom_line.product_qty,\n self.product_id.name_get()[0][1])\n return vals\n\n def _merge_moves_fields(self):\n res = super(UnvcStockMove, self)._merge_moves_fields()\n kit_product_details = self.mapped('kit_product_details')\n if any(kit_product_details):\n for i in range(0, len(kit_product_details)):\n if not kit_product_details[i]:\n kit_product_details[i] = 'No kit'\n res['kit_product_details'] = '\\n'.join(kit_product_details)\n return res\n","sub_path":"unvc_purchase/models/unvc_stock_move.py","file_name":"unvc_stock_move.py","file_ext":"py","file_size_in_byte":2728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"554856141","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Sep 21 21:41:12 2020\n@author: hwan\n\"\"\"\nimport sys\nimport os\nsys.path.insert(0, os.path.realpath('../../src'))\nsys.path.append('../')\n\nimport numpy as np\nimport pandas as pd\n\nimport yaml\nfrom attrdict import AttrDict\n\n# Import src code\nfrom utils_mesh.construct_mesh_1d import construct_mesh\nfrom utils_prior.laplacian_prior import construct_laplacian_prior\nfrom utils_io.prior import load_prior\nfrom utils_prior.draw_from_distribution import draw_from_distribution\n# from utils_prior.draw_from_distribution_fenics import draw_from_distribution_fenics\nfrom utils_fenics.apply_mass_matrix import apply_mass_matrix\nfrom utils_io.load_parameters import load_parameters\nfrom utils_fenics.plot_fem_function_fenics_1d import plot_fem_function_fenics_1d\nfrom utils_misc.positivity_constraints import positivity_constraint_identity\nfrom utils_mesh.observation_points import form_interior_observation_points,\\\n form_observation_data\n\n# Import project utilities\nfrom utils_project.filepaths import FilePaths\nfrom utils_project.construct_system_matrices_screened_poisson_linear_dirichlet_1d import\\\n construct_system_matrices, load_system_matrices\nfrom utils_project.solve_linear_dirichlet_1d_assembled import solve_pde_assembled\nfrom utils_project.solve_screened_poisson_linear_dirichlet_1d_fenics import solve_pde_fenics\n\nimport pdb #Equivalent of keyboard in MATLAB, just add \"pdb.set_trace()\"\n\n###############################################################################\n# Driver #\n###############################################################################\nif __name__ == \"__main__\":\n\n ##################\n # Setting Up #\n ##################\n #=== Plotting Options ===#\n limit_min_parameter = 0\n limit_max_parameter = 7\n limit_min_state = 0\n limit_max_state = 1.5\n\n #=== Options ===#\n with open('config_files/options.yaml') as f:\n options = yaml.safe_load(f)\n options = AttrDict(options)\n options.num_nodes = options.nx + 1\n\n #=== File Paths ===#\n filepaths = FilePaths(options)\n\n #=== Creating Directory ===#\n if not os.path.exists(filepaths.directory_dataset):\n os.makedirs(filepaths.directory_dataset)\n\n ############\n # Mesh #\n ############\n #=== Construct Mesh ===#\n Vh, nodes, dof = construct_mesh(options)\n\n ############################\n # Prior and Parameters #\n ############################\n #=== Construct Prior ===#\n if options.construct_prior == 1:\n if options.prior_type_lp == 1:\n prior = construct_laplacian_prior(filepaths,\n Vh, options.prior_mean_lp,\n options.prior_gamma_lp,\n options.prior_delta_lp)\n\n #=== Draw Parameters from Prior ===#\n if options.draw_and_save_parameters == 1:\n prior_mean, _, _, prior_covariance_cholesky, _ = load_prior(filepaths, dof)\n draw_from_distribution(filepaths,\n prior_mean, prior_covariance_cholesky, dof,\n positivity_constraint_identity, 0.5,\n options.save_standard_gaussian_draws,\n num_samples = options.num_data)\n # draw_from_distribution_fenics(filepaths,\n # Vh, prior, dof,\n # num_samples = options.num_data)\n\n #=== Load Parameters ===#\n parameters = load_parameters(filepaths, dof, options.num_data)\n\n #=== Plot Parameters ===#\n if options.plot_parameters == 1:\n for n in range(0, options.num_data):\n plot_fem_function_fenics_1d(Vh, parameters[n,:],\n '',\n filepaths.directory_figures + 'parameter_%d.png' %(n),\n (5,5),\n (options.left_boundary, options.right_boundary),\n (limit_min_parameter,limit_max_parameter))\n\n ###################\n # FEM Objects #\n ###################\n #=== Construct or Load Matrices ===#\n if options.construct_and_save_matrices == 1:\n if not os.path.exists(filepaths.directory_dataset):\n os.makedirs(filepaths.directory_dataset)\n construct_system_matrices(filepaths, Vh)\n forward_matrix, mass_matrix = load_system_matrices(options, filepaths)\n\n ##########################\n # Computing Solution #\n ##########################\n #=== Solve PDE with Prematrices ===#\n state = solve_pde_assembled(options, filepaths,\n parameters,\n forward_matrix, mass_matrix)\n\n #=== Plot Solution ===#\n if options.plot_solutions == 1:\n for n in range(0, options.num_data):\n plot_fem_function_fenics_1d(Vh, state[n,:],\n '',\n filepaths.directory_figures + 'state_%d.png' %(n),\n (5,5),\n (options.left_boundary, options.right_boundary),\n (limit_min_state,limit_max_state))\n\n #=== Form Observation Data ===#\n obs_indices, _ = form_interior_observation_points(options, filepaths, Vh)\n form_observation_data(filepaths, state, obs_indices)\n","sub_path":"projects/screened_poisson_linear_1d/driver_screened_poisson_linear_1d_dirichlet_generate_data_assembled.py","file_name":"driver_screened_poisson_linear_1d_dirichlet_generate_data_assembled.py","file_ext":"py","file_size_in_byte":5629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"540131381","text":"#bingo program LC\n#made by Casper Dik\n\ndef createlist():\n myfile = open(\"terms.txt\", \"a+\")\n x = 0\n while x != \"\":\n x = input(\"Please write here the bingo terms you want to add: \")\n read = open(\"terms.txt\").read()\n read = read[0:]\n terms = read.split()\n if x in terms:\n print(\"This word has already been added to the list\")\n else:\n myfile.write(x)\n myfile.write(\"\\n\")\n\ndef full_list():\n createlist()\n read = open(\"terms.txt\").read()\n read = read[0:]\n list = read.split()\n y = len(list)\n o = 25 - y\n while o > 0:\n read = open(\"terms.txt\").read()\n read = read[0:]\n list = read.split()\n y = len(list)\n o = 25 - y\n if o <= 0:\n break\n else:\n print(\"Oops, you have to at least add\", o, \"terms to play bingo\")\n createlist()\n\nfull_list()\n\n\n","sub_path":"assessment_basic_track/collect_terms.py","file_name":"collect_terms.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"577182730","text":"\n\n#calss header\nclass _JUDAISM():\n\tdef __init__(self,): \n\t\tself.name = \"JUDAISM\"\n\t\tself.definitions = [u'the religion of the Jewish people, based on belief in one God and on the laws contained in the Torah and Talmud']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_judaism.py","file_name":"_judaism.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"33035100","text":"import os, pickle\nimport sklearn\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\nimport multiprocessing as mp\n\nfrom glob import glob\nfrom functools import partial\n\nfrom sklearn.svm import SVR\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler, RobustScaler\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n##################\ntrain_name = 'all'\nsite_list_fix = None #'CLNX']#, 'AGD', 'ALTA', 'BCC', 'SLB', 'PVC']\ninclude_keys = ['T', 'U', 'V', 'R', 'Z']#, 'SPD', 'DIR'] #VO, W\n\nuse_intervals = [12, 24]\nuse_var_type = ['mean']#, 'max', 'min']\n\nmin_slr, max_slr = 0, 50\nmax_T_01agl = 0 + 273.15\nmin_swe_mm = 2.54\n\nuse_scaler = StandardScaler() #RobustScaler(quantile_range=(25, 75))\ntrain_size, test_size, random_state = None, 0.33, 5\n\nsvr_tune_on = 'mae'#['mse', 'mae', 'mare', 'r2']\ncrange = np.arange(5, 121, 5)\nerange = np.arange(0, 5.1, .25)\n\nmp_cores = 86\nmp_method = 'fork'\n##################\n\n##################\ndef MARE(y_true, y_pred): \n y_true, y_pred = np.array(y_true), np.array(y_pred)\n return np.mean(np.abs((y_true - y_pred) / y_true))\n\ndef SVR_mp(_params, train_predictors, train_target):\n \n print('.', end='')\n \n _i, _j, _C, _e = _params\n \n _model = SVR(\n C=_C, #Ridge regularization parameter for (L2)^2 penalty\n epsilon=_e, #Specifies the epsilon-tube within which no penalty is associated in the training loss function\n kernel='rbf', #'linear', 'polynomial', 'rbf'\n degree=3, #pass interger for 'polynomial' kernel, ignored otherwise\n tol=0.001, #stopping tolerance\n shrinking=False, \n cache_size=200, \n verbose=False)\n \n _model.fit(train_predictors, train_target)\n \n test_predictions = _model.predict(X_test_norm).flatten()\n _r2 = _model.score(X_test_norm, y_test) #sklearn.metrics.r2_score(y_test.values.flatten(), test_predictions)\n _mse = sklearn.metrics.mean_squared_error(y_test.values.flatten(), test_predictions)\n _mae = sklearn.metrics.mean_absolute_error(y_test.values.flatten(), test_predictions)\n _mare = MARE(y_test.values.flatten(), test_predictions)\n \n return (_i, _j, _C, _e, _r2, _mae, _mse, _mare, _model)\n\n\n##################\n\nif __name__ == '__main__':\n\n obdir = '/uufs/chpc.utah.edu/common/home/steenburgh-group10/mewessler/observations/'\n figdir = '/uufs/chpc.utah.edu/common/home/steenburgh-group10/mewessler/output/slr_figures/'\n outdir = '/uufs/chpc.utah.edu/common/home/steenburgh-group10/mewessler/output/slr_models/'\n\n flist = glob(obdir + 'combined/*.pd')\n\n # This can be a manual site list if desired\n site_list = np.unique([f.split('/')[-1].split('_')[0] for f in flist])\n \n #site_list = [s for s in site_list if 'BSNF' not in s]\n site_list = site_list_fix if site_list_fix is not None else site_list\n \n print('Training on:\\n%s\\n'%'\\n'.join(site_list))\n\n # favor = 'long' #'long'\n\n flist = []\n for site in site_list:\n\n # Trim here if only using 12/24 UTC\n for interval in use_intervals: \n flist.append(glob(obdir + 'combined/%s*%d*.pd'%(site, interval)))\n\n flist = np.hstack(flist)\n print('Source files:\\n%s\\n'%'\\n'.join(flist))\n\n data = []\n for f in flist:\n\n site = f.split('/')[-1].split('_')[0]\n interval = int(f.split('/')[-1].split('.')[-2].replace('h', ''))\n\n df = pd.read_pickle(f)\n \n keys = ['slr', 'swe_mm']\n keys.extend(np.hstack([[k for k in df.keys()\n if ((vt in k) & (k.split('_')[0] in include_keys))] \n for vt in use_var_type]))\n \n df = df.loc[:, keys].rename(columns={[k for k in keys if 'swe' in k][0]:'swe_mm'})\n df = df.loc[:, :].rename(columns={[k for k in keys if 'swe' in k][0]:'swe_mm'})\n df = df.rename(columns={[k for k in keys if 'slr' in k][0]:'slr'})\n df = df.drop(columns=[k for k in keys if 'auto' in k])\n\n # df.insert(0, 'site', np.full(df.index.size, fill_value=site, dtype='U10'))\n doy = [int(pd.to_datetime(d).strftime('%j')) for d in df.index]\n #df.insert(2, 'day_of_year', doy)\n\n data.append(df.reset_index().drop(columns='time'))\n\n data = pd.concat(data, sort=False)\n\n # Treat the mean value as the instantaneous value for later applications,\n # we can change this behavior later on if desired. \n # An alternate method would be to keep the 'mean' tag through training \n # and choose behavior upon application\n data = data.rename(columns={k:k.replace('_mean', '') for k in data.keys()})\n\n data = data[data['slr'] >= min_slr]\n data = data[data['slr'] <= max_slr]\n data = data[data['T_01agl'] <= max_T_01agl]\n data = data[data['swe_mm'] >= min_swe_mm]\n \n data = data.drop(columns='swe_mm')\n\n # int(slr) for stratification (> 1 ct per class label)\n data = data.dropna()\n fac = 5\n slr = np.round(data['slr']/fac, 0)*fac\n print('\\nTrain/Test Split Strata:') \n print(slr.value_counts())\n\n print('\\nTotal: %d'%len(data))\n\n # Split into train/test sets\n X_train, X_test = train_test_split(data, \n test_size=test_size, train_size=train_size, \n random_state=random_state, stratify=slr)\n\n # Perform a secondary split if separate validation set required\n\n # Split off the target variable now that TTsplit is done\n y_train, y_test = X_train.pop('slr'), X_test.pop('slr')\n # y_train = np.round(y_train/fac, 0)*fac\n\n print('\\nTrain: {}\\nTest: {}\\nValidate: {}'.format(X_train.shape[0], X_test.shape[0], None))\n\n train_stats = X_train.describe()\n scaler = use_scaler.fit(X_train)\n\n X_train_norm = pd.DataFrame(scaler.transform(X_train.loc[:, list(X_train.keys())]), columns=X_train.keys())\n X_test_norm = pd.DataFrame(scaler.transform(X_test.loc[:, list(X_train.keys())]), columns=X_train.keys())\n\n print('\\nNormed Sample:')\n train_stats_norm = X_train_norm.describe()\n print(train_stats_norm.T.head())\n\n params = {}\n params['r2'] = np.zeros((len(crange), len(erange)))\n params['mae'] = np.zeros((len(crange), len(erange)))\n params['mse'] = np.zeros((len(crange), len(erange)))\n params['mare'] = np.zeros((len(crange), len(erange)))\n params['model'] = np.empty((len(crange), len(erange)), dtype='object')\n params['epsilon'] = np.zeros((len(crange), len(erange)))\n params['C'] = np.zeros((len(crange), len(erange)))\n\n mp_params = np.array([[(i, j, C, e) for j, e in enumerate(erange)] \n for i, C in enumerate(crange)]).reshape(-1, 4)\n\n print('\\nTrain keys:')\n print(list(X_train_norm.keys()))\n \n SVR_mp_wrapper = partial(SVR_mp, \n train_predictors=X_train_norm, \n train_target=y_train)\n \n print('\\nIterations to attempt: %d'%len(mp_params))\n\n with mp.get_context(mp_method).Pool(mp_cores) as p:\n mp_returns = p.map(SVR_mp_wrapper, mp_params, chunksize=1)\n p.close()\n p.join()\n\n for item in mp_returns:\n\n i, j, C, e, r2, mae, mse, mare, model = item\n i, j = int(i), int(j)\n\n params['r2'][i, j] = r2\n params['mse'][i, j] = mse\n params['mae'][i, j] = mae\n params['mare'][i, j] = mare\n params['model'][i, j] = model\n params['epsilon'][i, j] = e\n params['C'][i, j] = C\n\n min_on, indexer, _ = 'R2', np.where(params['r2'] == params['r2'].max()), params['r2'].max()\n min_on, indexer, _ = 'MAE', np.where(params['mae'] == params['mae'].min()), params['mae'].min()\n min_on, indexer, _ = 'MSE', np.where(params['mse'] == params['mse'].min()), params['mse'].min()\n min_on, indexer, _ = 'MARE', np.where(params['mare'] == params['mare'].min()), params['mare'].min()\n\n for min_on in [svr_tune_on]:\n\n if min_on in ['mse', 'mae', 'mare']:\n min_max = 'Minimized'\n indexer = np.where(params[min_on] == params[min_on].min())\n elif min_on in ['r2']:\n min_max = 'Maximized'\n indexer = np.where(params[min_on] == params[min_on].max())\n\n r, c = indexer\n r, c = r[0], c[0]\n r, c, _\n\n model = params['model'][r, c]\n test_predictions = model.predict(X_test_norm)\n\n y_true = y_test\n y_pred = test_predictions\n print('MARE ', MARE(y_true, y_pred))\n\n fig, axs = plt.subplots(2, 3, facecolor='w', figsize=(24, 14))\n axs = axs.flatten()\n\n ax = axs[0]\n cbar = ax.pcolormesh(erange, crange, params['mae'])\n plt.colorbar(cbar, label='mae', ax=ax)\n ax.set_title('Min MAE: %.3f'%params['mae'][r, c])\n ax.scatter(params['epsilon'][r, c], params['C'][r, c], s=500, c='w', marker='+')\n\n ax = axs[1]\n cbar = ax.pcolormesh(erange, crange, params['mse'])\n plt.colorbar(cbar, label='mse', ax=ax)\n ax.set_title('Min MSE: %.3f'%params['mse'][r, c])\n ax.scatter(params['epsilon'][r, c], params['C'][r, c], s=500, c='w', marker='+')\n\n ax = axs[2]\n cbar = ax.pcolormesh(erange, crange, params['r2'])\n plt.colorbar(cbar, label='r2', ax=ax)\n ax.set_title('Max R^2: %.3f'%params['r2'][r, c])\n ax.scatter(params['epsilon'][r, c], params['C'][r, c], s=500, c='k', marker='+')\n\n for ax in axs[:3]:\n ax.set_xlabel('epsilon')\n ax.set_ylabel('C_val')\n ax.set_ylim([crange.min(), crange.max()])\n ax.set_xlim([erange.min(), erange.max()])\n\n ax = axs[3]\n maxslr = y_test.max() if y_test.max() > y_train.max() else y_train.max()\n\n ax.hist(y_train, bins=np.arange(0, maxslr, 2), color='g', edgecolor='k', alpha=1.0, label='Train SLR\\nn=%d'%len(y_train))\n ax.hist(y_test, bins=np.arange(0, maxslr, 2), color='C0', edgecolor='k', alpha=1.0, label='Test SLR\\nn=%d'%len(y_test))\n ax.legend()\n\n ax.set_xticks(np.arange(0, maxslr+1, 5))\n ax.set_xticklabels(np.arange(0, maxslr+1, 5).astype(int))\n ax.grid()\n\n ax = axs[4]\n maxslr = test_predictions.max() if test_predictions.max() > y_test.max() else y_test.max()\n maxslr += 5\n ax.scatter(y_test, test_predictions, c='k', s=50, marker='+', linewidth=0.75)\n ax.set_xlabel('Observed SLR')\n ax.set_ylabel('Predicted SLR')\n ax.plot([0, maxslr], [0, maxslr])\n ax.set_xlim([0, maxslr])\n ax.set_ylim([0, maxslr])\n ax.set_aspect('equal')\n ax.grid()\n\n ax = axs[5]\n error = test_predictions - y_test\n ax.hist(error, bins=np.arange(-30, 30, 2), edgecolor='k')\n ax.set_xlabel('Prediction Error')\n ax.set_ylabel('Count')\n ax.grid()\n\n plt.suptitle('Support Vector Regression Model\\n%s\\n%s on: %s\\n\\nepsilon %.3f\\nc_val: %.3f'%(\n site_list, min_max, min_on.upper(), params['epsilon'][r, c], params['C'][r, c]))\n\n figpath = figdir + 'train/%s/'%train_name\n os.makedirs(figpath, exist_ok=True)\n \n numfigs = len(glob(figpath + '*_gridsearch*.png'))\n figfile = figpath + '%s_gridsearch.%02d.png'%(train_name, numfigs)\n\n plt.savefig(figfile)\n print('Saved: ', figfile)\n \n outpath = outdir + '%s'%train_name\n os.makedirs(outpath, exist_ok=True)\n \n for obj, obj_name in zip(\n [scaler, [train_stats, train_stats_norm], model], \n ['scaler', 'train_stats', 'SLRmodel']):\n \n with open(outpath + '/%s_%s.%02d.pickle'%(\n train_name, obj_name, numfigs), 'wb') as wfp:\n \n pickle.dump(obj, wfp)","sub_path":"core/train_svr.py","file_name":"train_svr.py","file_ext":"py","file_size_in_byte":11766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"209631781","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.template import loader\nfrom Home.models import OtherPage\nfrom Samples.models import Product\nfrom Samples.models import Provider\nfrom Samples.models import Photo\nimport requests\n\n# Create your views here.\n\ndef SendPage(Request, PageName):\n Other = OtherPage.objects.all()\n context = {\n 'Other': Other,\n }\n template = loader.get_template('Samples/'+PageName+'.html')\n return HttpResponse(template.render(context, Request))\n\ndef PhotoGallery(Request):\n Pics = Photo.objects.all()\n context = {\n 'Photos': Pics,\n }\n template = loader.get_template('Samples/PhotoGallery.html')\n return HttpResponse(template.render(context, Request))\n\ndef ECommerce(Request):\n #ASync()\n ProductList = Product.objects.all()\n context = {\n 'Products': ProductList,\n }\n template = loader.get_template('Samples/ECommerce.html')\n return HttpResponse(template.render(context, Request))\n\ndef ASync():\n from Samples.models import Product\n from Samples.models import Provider\n ProductList = Product.objects.all()\n ProviderList = Provider.objects.all()\n\n for X in ProviderList:\n IDList = [] #Ref Id From Center\n ProviderIDList = [] #List of every provider By Item from Center\n UNIDList = [] #Unique Id By Item Center\n PIDList = [] #Client side IDList\n PUNIDList = [] #Client side Unique Id List\n\n \"\"\" Pull data from Center using public key\n save propper data to\n IDList, ProviderIDList, UNIDList \"\"\"\n\n resp = requests.get('http://69.10.43.208:8000/'+X.PublicKey+'/')\n if resp.status_code != 200:\n # This means something went wrong.\n raise ApiError('GET /Item/ {}'.format(resp.status_code))\n for Item in resp.json():\n IDList.append(Item['id'])\n ProviderIDList.append(Item['Provider'])\n UNIDList.append(Item['UniqueID'])\n\n \"\"\" Pull data from client sied DB and put in\n PIDList and PUNIDList \"\"\"\n\n for Product in ProductList:\n PIDList.append(Product.id)\n PUNIDList.append(Product.UniqueID)\n\n \"\"\" Create Templist copy of ProviderID List\n Compare Templist to Private Key\n If same, move cursor to next position\n if bad delete and keep cursor in same psoition \"\"\"\n\n C = 0\n while (C+1) <= len(ProviderIDList) and len(ProviderIDList) > 0:\n if ProviderIDList[C] == X.PrivateKey:\n C = C+1\n else:\n del ProviderIDList[C]\n del IDList[C]\n del UNIDList[C]\n\n \"\"\" Check if the UNID form center is in UNID list from client\n if not delete , (Cursur is used for the ref)\"\"\"\n\n C = 0\n for ID in UNIDList:\n if any(ID == s for s in PUNIDList):\n pass\n else:\n requests.delete('http://69.10.43.208:8000/'+X.PublicKey+'/'+str(IDList[C]))\n C = C+1\n\n \"\"\" Check in UNID from client is in UNID lts from center\n If not send JSon post using C\"\"\"\n\n C = 0\n for ID in PUNIDList:\n if any(ID == s for s in UNIDList):\n pass\n else:\n for Y in ProductList:\n print(str(Y.id))\n print(str(PIDList[C]))\n if str(Y.id) == str(PIDList[C]):\n POSTDATA = {\n \"UniqueID\": Y.UniqueID,\n \"Provider\": X.PrivateKey,\n \"Name\": Y.Name,\n \"Format\": Y.Format,\n \"Price\": Y.Price,\n \"Quantity\": Y.Quantity,\n \"DateOfAvalability\": Y.DateOfAvalability,\n \"Description\": Y.Description\n }\n requests.post('http://69.10.43.208:8000/'+X.PublicKey+'/', data=POSTDATA)\n else:\n pass\n C = C+1\n","sub_path":"Samples/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"228417454","text":"from sense_hat import SenseHat\nfrom random import randint\n\nsense = SenseHat()\n\nclass Particle:\n def __init__(self, x, y, color):\n self.x = x\n self.y = y\n self.color = color\n\n def draw(self):\n sense.set_pixel(self.x, self.y, self.color)\n\ndef randomColor():\n r = randint(0,255)\n g = randint(0,255)\n b = randint(0,255)\n return (r,g,b)\n\nparticles = []\n\nfor i in range(0,8):\n particles.append(Particle(i, 0, randomColor()))\nfor x in range(0,8):\n particles.append(Particle(x, 1, randomColor()))\n\nwhile True:\n acceleration = sense.get_accelerometer_raw()\n x = acceleration['x']\n y = acceleration['y']\n\n for i in range(0,15):\n if (x > 0):\n if (particles[i].x + 1 < 8):\n pX = particles[i].x\n pY = particles[i].y\n\n emptySpace = True\n\n for p in particles:\n if (p.x == pX + 1 and p.y == pY):\n emptySpace = False\n break\n\n if (emptySpace):\n particles[i].x += 1\n elif (x < 0):\n if (particles[i].x - 1 > -1):\n pX = particles[i].x\n pY = particles[i].y\n\n emptySpace = True\n\n for p in particles:\n if (p.x == pX - 1 and p.y == pY):\n emptySpace = False\n break\n\n if (emptySpace):\n particles[i].x -= 1\n\n if (y > 0):\n if (particles[i].y + 1 < 8):\n pX = particles[i].x\n pY = particles[i].y\n\n emptySpace = True\n\n for p in particles:\n if (p.y == pY + 1 and p.x == pX):\n emptySpace = False\n break\n\n if (emptySpace):\n particles[i].y += 1\n elif (y < 0):\n if (particles[i].y - 1 > -1):\n pX = particles[i].x\n pY = particles[i].y\n\n emptySpace = True\n\n for p in particles:\n if (p.y == pY - 1 and p.x == pX):\n emptySpace = False\n break\n\n if (emptySpace):\n particles[i].y -= 1\n \n particles[i].draw()\n\n sense.clear()\n","sub_path":"RaspberryPi/Particles.py","file_name":"Particles.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"262492263","text":"#!/usr/bin/python3\n'''base_model UnitTesting'''\nimport os\nimport sys\nimport unittest\nfrom datetime import datetime\nfrom models.city import City\n\n\nclass TestCity(unittest.TestCase):\n '''class TestCity'''\n\n def setUp(self):\n '''method that will be ran before every test'''\n self.City = City()\n\n def test_instantiation(self):\n '''method to test class instantiation'''\n self.assertIsInstance(self.City, City)\n\n def test_has_attrs(self):\n '''method to test initial attrs exist'''\n self.assertTrue(hasattr(self.City, 'state_id'))\n self.assertTrue(hasattr(self.City, 'name'))\n\n def test_instance_attributes(self):\n '''method to test instance attributes'''\n len_id = len(self.City.id)\n created_time = self.City.created_at\n updated_time = self.City.updated_at\n self.assertEqual('', self.City.state_id)\n self.assertEqual(len_id, 36)\n self.assertTrue(created_time != updated_time)\n self.assertIsInstance(self.City.created_at, datetime)\n self.assertIsInstance(self.City.updated_at, datetime)\n self.assertTrue('' == self.City.name)\n self.City.name = 'Tulsa'\n self.City.state_id = 'testID'\n self.assertNotEqual(self.City.updated_at, self.City.created_at)\n self.assertNotEqual(self.City.name, '')\n self.assertNotEqual(self.City.state_id, '')\n\n def test_save(self):\n '''method to test City.save()'''\n updated_at = self.City.updated_at\n self.City.test_save = 'testing save'\n self.City.save()\n self.assertNotEqual(self.City.updated_at, updated_at)\n self.assertIsNotNone(os.path.exists('file.json'))\n\n def test_to_dict(self):\n '''method to test City.to_dict()'''\n # testing key equality\n city_dict = City().to_dict()\n my_dict = self.City.to_dict()\n city_keys = city_dict.keys()\n my_keys = my_dict.keys()\n self.assertEqual(city_keys, my_keys)\n\n # testing attrs in dicts\n self.assertTrue(hasattr(city_dict, '__class__'))\n\n # test that __dict__ & .to_dict() are diff\n self.assertIsNot(self.City.__dict__, self.City.to_dict())\n\n if __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_models/test_city.py","file_name":"test_city.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"589441658","text":"import threading, time\n\n# threading.active_count()\n\ndef run():\n thread = threading.current_thread()\n print('%s is running...'% thread.getName()) #返回线程名称\n time.sleep(10) #休眠10S方便统计存活线程数量\n\nif __name__ == '__main__':\n for i in range(10):\n print('The current number of threads is: %s' % threading.active_count())\n thread_alive = threading.Thread(target=run, name='Thread-***%s***' % i)\n thread_alive.start() # 开启10个线程\n thread_alive.join()\n print('\\n%s thread is done...'% threading.current_thread().getName())\n","sub_path":"Python100模块/10_threading_4.py","file_name":"10_threading_4.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"20925581","text":"class Solution:\n def findMaximizedCapital(self, k: int, W: int, Profits: List[int], Capital: List[int]) -> int:\n current = []\n future = sorted(zip(Capital, Profits))[::-1] # 按照capital从大到小排列\n for _ in range(k):\n while future and future[-1][0] <= W: # 当capital最小的,比W小的时候,可以放candidate。这是一个装candidate的过程\n heapq.heappush(current, -future.pop()[1]) # current 是一个max heap,装profit\n if current: # 这里可能面临 current为空 # 这里pop出来的是future最后的元素,就是capital最小的pair\n W -= heapq.heappop(current)\n return W","sub_path":"code/502. IPO.py","file_name":"502. IPO.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"154486783","text":"from math import sqrt\nfrom itertools import count\n\ndef two_and_odds():\n '''\n Helper generator for search space of prime numbers\n '''\n result = 2\n odds = count(3, 2)\n while True:\n yield result\n result = next(odds)\n\n\ndef is_prime(n):\n '''\n Logical; Limits search space to 2, 3, 5, ..., sqrt(n)\n '''\n if n == 2:\n return True\n elif n % 2 == 0:\n return False\n else:\n return all(n % x != 0 for x in range(3, int(sqrt(n))+1, 2))\n\n\ndef main():\n '''\n By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see\n that the 6th prime is 13.\n\n What is the 10 001st prime number?\n '''\n for i, p in enumerate(x for x in two_and_odds() if is_prime(x)):\n if i == 10000:\n return p\n\nif __name__ == '__main__':\n print(main())\n","sub_path":"solutions/problem007.py","file_name":"problem007.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"570234083","text":"# -*- coding: utf-8 -*-\nimport wikipedia\nimport random\nfrom BeautifulSoup import BeautifulSoup\nimport urllib2\nimport codecs\n\n\ndef get_category(word):\n wikipedia.set_lang('He')\n res = wikipedia.search(word, 10, True)\n if len(res[0]) != 0:\n title = res[0][0]\n if is_category(title):\n return random.choice(res[0])\n return get_catageories_helper(title)\n else:\n if res[1] is not None:\n return get_catageories_helper(res[1][0])\n\n\ndef is_category(title):\n try:\n wikipedia.WikipediaPage(title)\n return False\n except:\n return True\n\ndef get_catageories_helper(title):\n try:\n catagories = wikipedia.WikipediaPage(title).categories\n if len(catagories) != 0:\n catagories = filter(lambda a: u'קצרמר' not in a and u'ערכים' not in a and u'דפים עם' not in a, catagories)\n # lens = []\n # for category in catagories:\n # res = wikipedia.page(category)\n # lens = [len(res.links)]\n # max_len = max(lens)\n # idx = [i for i, x in enumerate(lens) if x == max(max_len)]\n # max_category = catagories[random.choice(idx)]\n if len(catagories) != 0:\n return random.choice(catagories).replace(u'קטגוריה', u'').replace(u':', u'')\n return \"זה\"\n except:\n return title\n\n\n\ndef get_info_box_data(word):\n wikipedia.set_lang('He')\n res = wikipedia.search(word, 10, True)\n title = res[0][0]\n html_page = wikipedia.page(title).html()\n soup = BeautifulSoup(html_page)\n info_table = soup.find(\"table\", {\"class\": \"infobox\"})\n info = []\n current_tuple = tuple()\n rows = info_table.findChildren(['th', 'tr', 'td'])\n\n for row in rows:\n result = \"\"\n row_title = get_title(row)\n values = row.findChildren('a')\n if len(values) == 0: continue\n for value in values:\n # value = cell['content']\n # print \"The value in this cell is %s\" % value\n for content in value.contents:\n if 'img' in content: continue\n result += \" \" + (str)(content)\n if 'img' in result: continue\n # print(row_title)\n # print(result)\n # print(\"-------------------\")\n\n\ndef get_title(element):\n children = element.findChildren()\n for child in children:\n if child.string is not None:\n return child.string\n\n\n# word = \"כלי עבודה\"\n#word = \"שחקני קולנוע וטלוויזיה אמריקאים\"\n#print(get_category(word))\n#get_category(word)\n# get_info_box_data('בראד פיט')\n# res=wikipedia.suggest('ביבי')\n# print(res)\n# get_info_box_data('אלברט איינשטיין')\n\n","sub_path":"chatbot/hebrew_aiml/wiki_helper.py","file_name":"wiki_helper.py","file_ext":"py","file_size_in_byte":2751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"320339417","text":"import cv2\nimport keras\nfrom keras.applications.imagenet_utils import preprocess_input\nfrom keras.backend.tensorflow_backend import set_session\nfrom keras.models import Model\nfrom keras.preprocessing import image\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pickle\nfrom random import shuffle\nfrom scipy.misc import imread\nfrom scipy.misc import imresize\nimport tensorflow as tf\nfrom keras import backend as K\nfrom ssd import SSD300\nfrom ssd_training import MultiboxLoss\nfrom ssd_utils import BBoxUtility\nfrom keras.layers import Add\ndef cal_mAP(y_true,y_pred):\n num_classes = y_true.shape[1]\n average_precisions = []\n relevant = K.sum(K.round(K.clip(y_true, 0, 1)))\n tp_whole = K.round(K.clip(y_true * y_pred, 0, 1))\n for index in range(21):\n temp = K.sum(tp_whole[:,:index+1],axis=1)\n average_precisions.append(temp * (1/(index + 1)))\n AP = Add()(average_precisions) / relevant\n mAP = K.mean(AP,axis=0)\n return mAP\ndef iou_metric(y_true, y_pred):\n # iou as metric for bounding box regression\n # input must be as [x1, y1, x2, y2]\n \n # AOG = Area of Groundtruth box\n AoG = K.abs(K.transpose(y_true)[2] - K.transpose(y_true)[0] + 1) * K.abs(K.transpose(y_true)[3] - K.transpose(y_true)[1] + 1)\n \n # AOP = Area of Predicted box\n AoP = K.abs(K.transpose(y_pred)[2] - K.transpose(y_pred)[0] + 1) * K.abs(K.transpose(y_pred)[3] - K.transpose(y_pred)[1] + 1)\n\n # overlaps are the co-ordinates of intersection box\n overlap_0 = K.maximum(K.transpose(y_true)[0], K.transpose(y_pred)[0])\n overlap_1 = K.maximum(K.transpose(y_true)[1], K.transpose(y_pred)[1])\n overlap_2 = K.minimum(K.transpose(y_true)[2], K.transpose(y_pred)[2])\n overlap_3 = K.minimum(K.transpose(y_true)[3], K.transpose(y_pred)[3])\n\n # intersection area\n intersection = (overlap_2 - overlap_0 + 1) * (overlap_3 - overlap_1 + 1)\n\n # area of union of both boxes\n union = AoG + AoP - intersection\n \n # iou calculation\n iou = intersection / union\n\n # bounding values of iou to (0,1)\n iou = K.clip(iou, 0.0 + K.epsilon(), 1.0 - K.epsilon())\n\n return iou \ndef true_positive(y_true, y_pred):\n return K.sum(K.cast(K.equal(y_true * y_pred, 1), K.floatx()))\n\ndef true_negative(y_true, y_pred):\n return K.sum(K.cast(K.equal(y_true + y_pred, 0), K.floatx()))\n\ndef false_positive(y_true, y_pred):\n return K.sum(K.cast(K.less(y_true, y_pred), K.floatx()))\n\ndef false_negative(y_true, y_pred):\n return K.sum(K.cast(K.greater(y_true, y_pred), K.floatx()))\n\ndef IoU(y_true, y_pred):\n y_pred = K.round(y_pred)\n return true_positive(y_true, y_pred) / (false_negative(y_true, y_pred)+true_positive(y_true, y_pred)+false_positive(y_true, y_pred))\ndef P(y_true, y_pred):\n true_positives = K.sum(K.cast(K.greater(K.clip(y_true * y_pred, 0, 1), 0.20), 'float32'))\n pred_positives = K.sum(K.cast(K.greater(K.clip(y_pred, 0, 1), 0.20), 'float32'))\n\n precision = true_positives / (pred_positives + K.epsilon())\n return precision\n\n#recall\ndef R(y_true, y_pred):\n true_positives = K.sum(K.cast(K.greater(K.clip(y_true * y_pred, 0, 1), 0.20), 'float32'))\n poss_positives = K.sum(K.cast(K.greater(K.clip(y_true, 0, 1), 0.20), 'float32'))\n\n recall = true_positives / (poss_positives + K.epsilon())\n return recall\ndef F(y_true, y_pred):\n p_val = P(y_true, y_pred)\n r_val = R(y_true, y_pred)\n f_val = 2*p_val*r_val / (p_val + r_val)\n\n return f_val\n\ndef plot_learning_graph(history,epoch):\n \n plt.plot(np.arange(epoch)+1, history[\"loss\"],label= 'loss')\n plt.plot(np.arange(epoch)+1, history[\"val_loss\"],label= 'val_loss')\n plt.xlabel('Epoch')\n plt.legend()\n plt.savefig('_loss.png')\n\nplt.rcParams['figure.figsize'] = (8, 8)\nplt.rcParams['image.interpolation'] = 'nearest'\n\n\n\nnp.set_printoptions(suppress=True)\n\n# 21\nNUM_CLASSES = 21 #4\ninput_shape = (300, 300, 3)\n\npriors = pickle.load(open('prior_boxes_ssd300.pkl', 'rb'))\nbbox_util = BBoxUtility(NUM_CLASSES, priors)\n\n# gt = pickle.load(open('gt_pascal.pkl', 'rb'))\ngt = pickle.load(open('own.pkl', 'rb'))\nkeys = sorted(gt.keys())\nnum_train = int(round(0.8 * len(keys)))\ntrain_keys = keys[:num_train]\nval_keys = keys[num_train:]\nnum_val = len(val_keys)\n\nclass Generator(object):\n def __init__(self, gt, bbox_util,\n batch_size, path_prefix,\n train_keys, val_keys, image_size,\n saturation_var=0.5,\n brightness_var=0.5,\n contrast_var=0.5,\n lighting_std=0.5,\n hflip_prob=0.5,\n vflip_prob=0.5,\n do_crop=True,\n crop_area_range=[0.75, 1.0],\n aspect_ratio_range=[3./4., 4./3.]):\n self.gt = gt\n self.bbox_util = bbox_util\n self.batch_size = batch_size\n self.path_prefix = path_prefix\n self.train_keys = train_keys\n self.val_keys = val_keys\n self.train_batches = len(train_keys)\n self.val_batches = len(val_keys)\n self.image_size = image_size\n self.color_jitter = []\n if saturation_var:\n self.saturation_var = saturation_var\n self.color_jitter.append(self.saturation)\n if brightness_var:\n self.brightness_var = brightness_var\n self.color_jitter.append(self.brightness)\n if contrast_var:\n self.contrast_var = contrast_var\n self.color_jitter.append(self.contrast)\n self.lighting_std = lighting_std\n self.hflip_prob = hflip_prob\n self.vflip_prob = vflip_prob\n self.do_crop = do_crop\n self.crop_area_range = crop_area_range\n self.aspect_ratio_range = aspect_ratio_range\n\n def grayscale(self, rgb):\n return rgb.dot([0.299, 0.587, 0.114])\n\n def saturation(self, rgb):\n gs = self.grayscale(rgb)\n alpha = 2 * np.random.random() * self.saturation_var \n alpha += 1 - self.saturation_var\n rgb = rgb * alpha + (1 - alpha) * gs[:, :, None]\n return np.clip(rgb, 0, 255)\n\n def brightness(self, rgb):\n alpha = 2 * np.random.random() * self.brightness_var \n alpha += 1 - self.saturation_var\n rgb = rgb * alpha\n return np.clip(rgb, 0, 255)\n\n def contrast(self, rgb):\n gs = self.grayscale(rgb).mean() * np.ones_like(rgb)\n alpha = 2 * np.random.random() * self.contrast_var \n alpha += 1 - self.contrast_var\n rgb = rgb * alpha + (1 - alpha) * gs\n return np.clip(rgb, 0, 255)\n\n def lighting(self, img):\n cov = np.cov(img.reshape(-1, 3) / 255.0, rowvar=False)\n eigval, eigvec = np.linalg.eigh(cov)\n noise = np.random.randn(3) * self.lighting_std\n noise = eigvec.dot(eigval * noise) * 255\n img += noise\n return np.clip(img, 0, 255)\n\n def horizontal_flip(self, img, y):\n if np.random.random() < self.hflip_prob:\n img = img[:, ::-1]\n y[:, [0, 2]] = 1 - y[:, [2, 0]]\n return img, y\n\n def vertical_flip(self, img, y):\n if np.random.random() < self.vflip_prob:\n img = img[::-1]\n y[:, [1, 3]] = 1 - y[:, [3, 1]]\n return img, y\n\n def random_sized_crop(self, img, targets):\n img_w = img.shape[1]\n img_h = img.shape[0]\n img_area = img_w * img_h\n random_scale = np.random.random()\n random_scale *= (self.crop_area_range[1] -\n self.crop_area_range[0])\n random_scale += self.crop_area_range[0]\n target_area = random_scale * img_area\n random_ratio = np.random.random()\n random_ratio *= (self.aspect_ratio_range[1] -\n self.aspect_ratio_range[0])\n random_ratio += self.aspect_ratio_range[0]\n w = np.round(np.sqrt(target_area * random_ratio)) \n h = np.round(np.sqrt(target_area / random_ratio))\n if np.random.random() < 0.5:\n w, h = h, w\n w = min(w, img_w)\n w_rel = w / img_w\n w = int(w)\n h = min(h, img_h)\n h_rel = h / img_h\n h = int(h)\n x = np.random.random() * (img_w - w)\n x_rel = x / img_w\n x = int(x)\n y = np.random.random() * (img_h - h)\n y_rel = y / img_h\n y = int(y)\n img = img[y:y+h, x:x+w]\n new_targets = []\n for box in targets:\n cx = 0.5 * (box[0] + box[2])\n cy = 0.5 * (box[1] + box[3])\n if (x_rel < cx < x_rel + w_rel and\n y_rel < cy < y_rel + h_rel):\n xmin = (box[0] - x_rel) / w_rel\n ymin = (box[1] - y_rel) / h_rel\n xmax = (box[2] - x_rel) / w_rel\n ymax = (box[3] - y_rel) / h_rel\n xmin = max(0, xmin)\n ymin = max(0, ymin)\n xmax = min(1, xmax)\n ymax = min(1, ymax)\n box[:4] = [xmin, ymin, xmax, ymax]\n new_targets.append(box)\n new_targets = np.asarray(new_targets).reshape(-1, targets.shape[1])\n return img, new_targets\n\n def generate(self, train=True):\n while True:\n if train:\n shuffle(self.train_keys)\n keys = self.train_keys\n else:\n shuffle(self.val_keys)\n keys = self.val_keys\n inputs = []\n targets = []\n for key in keys: \n img_path = self.path_prefix + key\n img = imread(img_path).astype('float32')\n y = self.gt[key].copy()\n if train and self.do_crop:\n img, y = self.random_sized_crop(img, y)\n img = imresize(img, self.image_size).astype('float32')\n # boxの位置は正規化されているから画像をリサイズしても\n # 教師信号としては問題ない\n if train:\n shuffle(self.color_jitter)\n for jitter in self.color_jitter:\n img = jitter(img)\n if self.lighting_std:\n img = self.lighting(img)\n if self.hflip_prob > 0:\n img, y = self.horizontal_flip(img, y)\n if self.vflip_prob > 0:\n img, y = self.vertical_flip(img, y)\n # 訓練データ生成時にbbox_utilを使っているのはここだけらしい\n #print(y)\n y = self.bbox_util.assign_boxes(y)\n #print(y)\n inputs.append(img) \n targets.append(y)\n if len(targets) == self.batch_size:\n tmp_inp = np.array(inputs)\n tmp_targets = np.array(targets)\n inputs = []\n targets = []\n yield preprocess_input(tmp_inp), tmp_targets\n\npath_prefix = 'PASCAL_VOC/resize_image/'\ngen = Generator(gt, bbox_util, 4, path_prefix,\n train_keys, val_keys,\n (input_shape[0], input_shape[1]), do_crop=True)\n\nmodel = SSD300(input_shape, num_classes=NUM_CLASSES)\nmodel.load_weights('weights_SSD300.hdf5', by_name=True)\n\nfreeze = ['input_1', 'conv1_1', 'conv1_2', 'pool1',\n 'conv2_1', 'conv2_2', 'pool2',\n 'conv3_1', 'conv3_2', 'conv3_3', 'pool3']#,\n # 'conv4_1', 'conv4_2', 'conv4_3', 'pool4']\n\nfor L in model.layers:\n if L.name in freeze:\n L.trainable = False\n\ndef schedule(epoch, decay=0.9):\n return base_lr * decay**(epoch)\ncallbacks = [keras.callbacks.ModelCheckpoint('./checkpoints/weights.{epoch:02d}-{val_loss:.2f}.hdf5',\n verbose=1,\n save_weights_only=True),\n keras.callbacks.LearningRateScheduler(schedule)]\nbase_lr = 1e-5\noptim = keras.optimizers.Adam(lr=base_lr)\nmodel.compile(optimizer=optim,\n loss=MultiboxLoss(NUM_CLASSES, neg_pos_ratio=2.0).compute_loss)\n\nnb_epoch = 100\nhistory = model.fit_generator(gen.generate(True), gen.train_batches,\n nb_epoch, verbose=1,\n callbacks=callbacks,\n validation_data=gen.generate(False),\n nb_val_samples=gen.val_batches,\n nb_worker=1).history\n\nplot_learning_graph(history,nb_epoch)\n'''\ninputs = []\nimages = []\nimg_path = path_prefix + sorted(val_keys)[0]\nimg = image.load_img(img_path, target_size=(300, 300))\nimg = image.img_to_array(img)\nimages.append(imread(img_path))\ninputs.append(img.copy())\ninputs = preprocess_input(np.array(inputs))\n\npreds = model.predict(inputs, batch_size=1, verbose=1)\nresults = bbox_util.detection_out(preds)\n\nfor i, img in enumerate(images):\n # Parse the outputs.\n det_label = results[i][:, 0]\n det_conf = results[i][:, 1]\n det_xmin = results[i][:, 2]\n det_ymin = results[i][:, 3]\n det_xmax = results[i][:, 4]\n det_ymax = results[i][:, 5]\n\n # Get detections with confidence higher than 0.6.\n top_indices = [i for i, conf in enumerate(det_conf) if conf >= 0.6]\n\n top_conf = det_conf[top_indices]\n top_label_indices = det_label[top_indices].tolist()\n top_xmin = det_xmin[top_indices]\n top_ymin = det_ymin[top_indices]\n top_xmax = det_xmax[top_indices]\n top_ymax = det_ymax[top_indices]\n\n colors = plt.cm.hsv(np.linspace(0, 1, NUM_CLASSES)).tolist()\n\n plt.imshow(img / 255.)\n currentAxis = plt.gca()\n\n for i in range(top_conf.shape[0]):\n xmin = int(round(top_xmin[i] * img.shape[1]))\n ymin = int(round(top_ymin[i] * img.shape[0]))\n xmax = int(round(top_xmax[i] * img.shape[1]))\n ymax = int(round(top_ymax[i] * img.shape[0]))\n score = top_conf[i]\n label = int(top_label_indices[i])\n # label_name = voc_classes[label - 1]\n display_txt = '{:0.2f}, {}'.format(score, label)\n coords = (xmin, ymin), xmax-xmin+1, ymax-ymin+1\n color = colors[label]\n currentAxis.add_patch(plt.Rectangle(*coords, fill=False, edgecolor=color, linewidth=2))\n currentAxis.text(xmin, ymin, display_txt, bbox={'facecolor':color, 'alpha':0.5})\n\n plt.show()\n'''\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":14228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"428170253","text":"\"\"\"Check whether 5 is in list of first 5 natural numbers or not. Hint: List => [1,2,3,4,5]\n\"\"\"\na=(1,2,3,4,5)\nb=list(a)\nprint(b)\nfor element in b:\n if element==5:\n print(\"5 is in the list\")\n\n\"\"\"WAP which accepts marks of four subjects and display total marks, percentage and\ngrade.\nHint: more than 70% –> distinction, more than 60% –> first, more than 40% –> pass,\nless than 40% –> fail\"\"\"\ncmaths=int(input(\"Marks in cmaths:\"))\nscience=int(input(\"Mark in science:\"))\ncomputer=int(input(\"Mark in computer:\"))\nsocial=int(input(\"Mark in social:\"))\naverage=(cmaths+science+computer+social)/4\nif average>=70:\n print(\"Distinction\")\nelif average>=60:\n print(\"First Division\")\nelif average>=40:\n print(\"Pass\")\nelse:\n print(\"Fail\")\n\n\"\"\"Check whether the user input number is even or odd and display it to user.\"\"\"\nnum=int(input())\nif num%2==0:\n print(\"Even number\")\nelse:\n print(\"Odd number\")\n\n\n\"\"\"Given three integers, print the smallest one. (Three integers should be user input)\"\"\"\na=int(input())\nb=int(input())\nc=int(input())\nif a0:\n return \"True\"\n elif x==0:\n return \"Zero\"\n else:\n return \"False\"\nprint(integer(-3))\n\n\"\"\"Given an integer number, print its last digit\"\"\"\na=int(input(\"Enter the number:\"))\nlet=a%10\nprint(let)\n\n","sub_path":"lab_exercise2_part1.py","file_name":"lab_exercise2_part1.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"219724096","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Apr 25 12:20:44 2019\r\n\r\n@author: amanuele2\r\n\"\"\"\r\ndef nextDay(year, month, day):\r\n \"\"\"Simple version: assume every month has 30 days\"\"\"\r\n if day < daysInMonth(year, month):\r\n return year, month, day + 1\r\n else:\r\n if month == 12:\r\n return year + 1, 1, 1\r\n else:\r\n return year, month + 1, 1\r\n \r\ndef dateIsBefore(year1, month1, day1, year2, month2, day2):\r\n if year1 < year2:\r\n return True\r\n if year1 == year2:\r\n if month1 < month2:\r\n return True\r\n if month1 == month2:\r\n return day1 < day2\r\n return False\r\n\r\ndef isLeapYear(year):\r\n if year % 4 == 0:\r\n if (year % 100) == 0:\r\n if (year % 400) == 0:\r\n return True\r\n else:\r\n return False\r\n else:\r\n return True\r\n else:\r\n return False\r\n\r\ndef daysInMonth(year, month):\r\n if isLeapYear(year) and month == 2:\r\n return 29\r\n else:\r\n ending_days_in_months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\r\n return ending_days_in_months[month - 1]\r\n \r\n \r\n \r\ndef daysBetweenDates(year1, month1, day1, year2, month2, day2):\r\n \"\"\"Returns the number of days between year1/month1/day1\r\n and year2/month2/day2. Assumes inputs are valid dates\r\n in Gregorian calendar, and the first date is not after\r\n the second.\"\"\"\r\n \r\n # YOUR CODE HERE!\r\n num_of_days = 0\r\n assert not (dateIsBefore(year2, month2, day2, year1, month1, day1)) #make sure first date is <= 2nd date\r\n while dateIsBefore(year1, month1, day1, year2, month2, day2):\r\n year1, month1, day1 = nextDay(year1, month1, day1)\r\n num_of_days += 1\r\n return num_of_days\r\n\r\ndef tests():\r\n assert((nextDay(2013,2,28))) == (2013,3,1) \r\n assert((nextDay(2013,2,27))) == (2013,2,28)\r\n assert((nextDay(2012,2,28))) == (2012,2,29) \r\n assert((nextDay(2012,2,29))) == (2012,3,1) \r\n assert((nextDay(2013,12,31))) == (2014,1,1)\r\n print('tests finished')","sub_path":"CountDaysBetweenDates.py","file_name":"CountDaysBetweenDates.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"589158767","text":"# others\nimport cv2\nimport numpy as np\nimport glob\nimport matplotlib.pyplot as plt\n\n# Torch\nimport torch\nfrom torch.autograd import Variable\n\nfrom torchvision import models\nfrom torchvision import transforms\n\n# Mine\nfrom losses import *\nfrom utils import *\n\nclass MultiStyleVGG(torch.nn.Module):\n def __init__(self, vgg_model, content_images, style_images, content_weights,\n style_weights, contents_layers, styles_layers, tv_weight, cuda=False):\n super(MultiStyleVGG, self).__init__()\n\n # Some saved parameters\n self.model_str = vgg_model\n self.content_images = content_images\n self.style_images = style_images\n self.content_weights = content_weights\n self.style_weights = style_weights\n self.tv_weight = tv_weight\n self.contents_layers = contents_layers\n self.styles_layers = styles_layers\n\n # Construct the modified VGG network here\n if vgg_model == 'vgg19':\n print('Loading VGG19...')\n vgg = models.vgg19(pretrained=True).features\n print(vgg)\n elif vgg_model == 'vgg16':\n print('Loading VGG16...')\n vgg = models.vgg16(pretrained=True).features\n print(vgg)\n else:\n assert (vgg_model == \"vgg19\" or vgg_model == \"vgg16\"), \"Invalid VGG model!\"\n\n # Insert transparent loss layers so that we can measure features at layers we want\n print('Inserting Reconstruction Loss Layers...')\n self.model = torch.nn.Sequential()\n\n # Set cuda\n if cuda:\n vgg = vgg.cuda(0)\n self.model = self.model.cuda(0)\n\n # References to our losses\n self.style_losses = []\n self.content_losses = []\n\n # Total Variation Loss at beginning\n tv_loss = TotalVariationLoss(tv_weight)\n self.model.add_module('tv_loss', tv_loss)\n self.tv_loss = tv_loss\n # Create key names and construct new model\n # We know that vgg is comprised of conv2d, relu, and maxpooling layers\n # So just just for each of them here\n i = 1\n for layer in list(vgg):\n if isinstance(layer, torch.nn.Conv2d):\n # Copy conv2d from vgg to our model\n name = 'conv_' + str(i)\n self.model.add_module(name, layer)\n\n # NOTE: Run the content/style image through the network at its current style_features\n # This will allow you to calculate the gradients up to this point, then from Loss\n # Layers they are detached from the tree and remain a fixed Variable that you\n # minimize with\n # Also, you may need MULTIPLE children for a single module, this may be tricky\n\n # Multi Content Layer Reconstruction Loss\n for j, (image, layers, weight) in enumerate(zip(content_images, contents_layers, content_weights)):\n if name in layers:\n content = self.model(image).clone()\n content_loss = ContentLoss(content, weight)\n self.model.add_module('content_loss_' + str(i) + '_' + str(j),content_loss)\n self.content_losses.append(content_loss)\n\n # Multi Style Layer Reconstruction Loss\n for j, (image, layers, weight) in enumerate(zip(style_images, styles_layers, style_weights)):\n if name in layers:\n style = self.model(image).clone()\n style_loss = StyleLoss(style, weight, cuda=use_cuda)\n self.model.add_module('style_loss_' + str(i) + '_' + str(j), style_loss)\n self.style_losses.append(style_loss)\n\n if isinstance(layer, torch.nn.ReLU):\n name = 'relu_' + str(i)\n self.model.add_module(name, layer)\n i += 1\n\n # Multi Content Layer Reconstruction Loss\n for j, (image, layers, weight) in enumerate(zip(content_images, contents_layers, content_weights)):\n if name in layers:\n content = self.model(image).clone()\n content_loss = ContentLoss(content, weight)\n self.model.add_module('content_loss_' + str(i) + '_' + str(j),content_loss)\n self.content_losses.append(content_loss)\n\n # Multi Style Layer Reconstruction Loss\n for j, (image, layers, weight) in enumerate(zip(style_images, styles_layers, style_weights)):\n if name in layers:\n style = self.model(image).clone()\n style_loss = StyleLoss(style, weight, cuda=use_cuda)\n self.model.add_module('style_loss_' + str(i) + '_' + str(j), style_loss)\n self.style_losses.append(style_loss)\n\n if isinstance(layer, torch.nn.MaxPool2d):\n name = 'pool_' + str(i)\n self.model.add_module(name, layer)\n\n print(self.model)\n\n # Just run the network forward...\n def forward(self, input):\n self.model(input)\n return\n\n def backward(self):\n total_style_loss = 0; total_content_loss = 0; tv_loss = self.tv_loss.backward()\n for style_loss in self.style_losses:\n total_style_loss += style_loss.backward()\n\n for content_loss in self.content_losses:\n total_content_loss += content_loss.backward()\n\n return total_style_loss,total_content_loss,tv_loss\n\n\nif __name__ == '__main__':\n ##################################################################################################\n # Parameters\n clamp = False\n shiftnorm = False\n histeq = False\n normalize_input = True\n denormalize = True\n imsize = 256\n iterations = 1500\n learning_rate = 5e-3\n\n # You want to weight each image now\n tv_weight = 10.0\n content_weights = [0.0]\n style_weights = [1000.0, 5000.0]\n\n # Selected Layers\n contents_layers = [ ['conv_4'] ]\n styles_layers = [ ['conv_' + str(i) for i in range(1,4)], ['conv_' + str(i) for i in range(4,17)]]\n\n # Choice of network\n model = 'vgg19'\n ##################################################################################################\n\n # CUDA Check\n use_cuda = torch.cuda.is_available()\n print('CUDA Status:', use_cuda)\n\n # Determine type\n dtype = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor\n\n # Load images\n content_files = glob.glob('./contents/*')\n style_files = glob.glob('./styles/*')\n\n print('Content images found:', content_files)\n print('Style images found:', style_files)\n\n transform = transforms.ToTensor()\n vgg_mean = [0.485, 0.456, 0.406]\n vgg_std = [0.229, 0.224, 0.225]\n normalize = transforms.Normalize(mean=vgg_mean,\n std=vgg_std)\n\n if normalize_input:\n transform = transforms.Compose([transform, normalize])\n\n contents = [ load_image(im, transform, dtype, imsize, shape=(imsize,imsize)) for im in content_files ]\n styles = [ load_image(im, transform, dtype, imsize, shape=(imsize,imsize)) for im in style_files ]\n\n # Generated image shall just be white noise as in the paper\n generated = Variable(torch.rand(contents[0].data.size())).type(dtype)\n #generated = contents[0].clone()\n generated = torch.nn.Parameter(generated.data)\n\n # Check size\n for c, s in zip(contents, styles):\n assert c.size() == s.size(), 'Content and Style image size mismatch'\n\n assert len(contents) == len(content_weights), \"Contents and Content Weights length mismatch\"\n assert len(styles) == len(style_weights), \"Styles and Style Weights length mismatch\"\n\n assert len(contents) == len(contents_layers), \"Contents and Content Layers length mismatch\"\n assert len(styles) == len(styles_layers), \"Contents and Content Layers length mismatch\"\n\n # Initialize the network\n net = MultiStyleVGG(model, contents, styles, content_weights, style_weights,\n contents_layers, styles_layers, tv_weight, cuda=use_cuda)\n\n # Some Post-Processing settings\n\n #optimizer = torch.optim.LBFGS([generated])\n #optimizer = torch.optim.SGD([generated], lr = 0.1, momentum=0.9)\n optimizer = torch.optim.Adam([generated], lr=learning_rate)\n # Define closure for our LFBGS optimizer\n def closure(i):\n optimizer.zero_grad()\n\n if clamp:\n generated.data.clamp_(0,1)\n\n # Run the input through our model\n net(generated)\n\n # Back prop and calculate scores\n style_score, content_score, tv_score = net.backward()\n\n # Print\n print('{} : Style Loss : {:4f} Content Loss: {:4f} Total Variation Loss: {:4f}'.format(i,style_score.data[0], content_score.data[0], tv_score.data[0]))\n\n # Total Score to optimzie\n return style_score + content_score + tv_score\n\n # Run the network\n i = 0\n while i < iterations:\n optimizer.step(lambda : closure(i))\n i += 1\n\n print('Max:', generated.max(), 'Min:', generated.min())\n print('Mean:', generated.mean(), 'Std:', generated.std())\n\n #################################################################\n # Post-Process\n post_generated = generated.clone()\n post_generated.detach()\n\n # De-normalize\n if denormalize:\n vgg_demean = map(lambda x : -x, vgg_mean)\n vgg_destd = map(lambda x : 1/x, vgg_std)\n denorm = transforms.Compose([transforms.Normalize([0,0,0], vgg_destd),transforms.Normalize(vgg_demean, [1,1,1])])\n post_generated = Variable(denorm(post_generated.data))\n\n if shiftnorm:\n mean = post_generated.mean().data[0]\n std = post_generated.std().data[0]\n post_generated.data.clamp(mean - std*3.0, mean + std*3.0)\n if post_generated.mean().data[0] - 1.0 < 0:\n post_generated += torch.abs(post_generated.min())\n else:\n post_generated -= torch.abs(post_generated.min())\n post_generated = torch.div(post_generated, post_generated.max())\n\n print('Post-Max:', post_generated.max(), 'Post-min:', post_generated.min())\n print('Post-Mean:', post_generated.mean(), 'Post-std:', post_generated.std())\n\n post_generated.data.clamp_(0,1)\n # Do some cv2 post processing here\n # Wished the network would just output the correct ranges...\n post_generated = post_generated.data.cpu().numpy()[0,:,:,:]*255.0\n post_generated = np.moveaxis(post_generated, 0, -1)\n\n if histeq:\n post_generated = cv2.cvtColor(post_generated, cv2.COLOR_BGR2YUV)\n post_generated[:,:,0] = cv2.equalizeHist(post_generated[:,:,0].astype(np.uint8))\n post_generated = cv2.cvtColor(post_generated.astype(np.float32), cv2.COLOR_YUV2BGR)\n\n #####################################################################\n\n # Display\n #imshow(styles[0].data, imsize=imsize)\n #imshow(contents[0].data, imsize=imsize)\n #imshow(post_generated.data, imsize=imsize)\n #plt.show()\n post_generated = cv2.cvtColor(post_generated, cv2.COLOR_BGR2RGB)\n cv2.imwrite('output.png', post_generated)\n\n print('Finished Style Transfer')\n","sub_path":"multistyle.py","file_name":"multistyle.py","file_ext":"py","file_size_in_byte":11272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"413236046","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\n\ndriver = webdriver.Chrome(executable_path=r\"C:\\driver_selenium\\chromedriver.exe\")\n\ndriver.get(\"https://www.google.com\")\ntime.sleep(3)\ndisplayelement = driver.find_element_by_name(\"btnI\")\nprint(displayelement.is_enabled())\nprint(displayelement.is_displayed())\n\ndriver.close()","sub_path":"projects/PythonScripts/Ejemplos_Selenium/Display-elements.py","file_name":"Display-elements.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"591417054","text":"from common.tools import *\nimport allure, yaml\n\nfrom base.config import RECORDER_PATH\n\npoco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)\nauto_setup(__file__)\n\nwith open('%s/resourceid.yaml' % DATA_PATH) as f:\n yaml_data = yaml.load(f)\n'''\n其他\n'''\n\n\n@allure.feature('遍历APP顶部头条')\nclass TestOthers:\n\n def setUp(self) -> None:\n pass\n\n @allure.story('精选顶部广告')\n @allure.title('精选顶部广告')\n def test_01_others(self):\n\n sleep(1)\n log.info('=======其他==========')\n stars_app()\n recorder().start_recording(max_time=1800)\n if poco(yaml_data['loopviewpager']).exists():\n poco(yaml_data['loopviewpager']).click()\n for i in range(2):\n swipe((561, 1686), (561, 245))\n keyevent(\"KEYCODE_BACK\")\n else:\n log.debug('======顶部广告未配置=====')\n sleep(1)\n get_snapshot('顶部广告')\n recorder().stop_recording(output='%s精选顶部广告.mp4' % RECORDER_PATH)\n\n @allure.story('精选头条:3个元素点击操作')\n @allure.title('精选头条:3个元素点击操作')\n def test_02_others(self):\n\n recorder().start_recording(max_time=1800)\n if poco(yaml_data['icon']).exists():\n poco(yaml_data['icon']).click()\n sleep(3)\n keyevent(\"KEYCODE_BACK\")\n poco(yaml_data['msg']).click()\n sleep(3)\n keyevent(\"KEYCODE_BACK\")\n poco(yaml_data['icon_enter']).click()\n sleep(3)\n keyevent(\"KEYCODE_BACK\")\n else:\n log.debug('=====头条广告未配置=====')\n recorder().stop_recording(output='%s头条广告.mp4' % RECORDER_PATH)\n\n def tearDown(self) -> None:\n pass\n","sub_path":"testCase/AMP_others.py","file_name":"AMP_others.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"539181070","text":"from handlers.BaseHandler import BaseHandler\n\n__author__ = 'shyal.beardsley'\n\n\nclass LogoutHandler(BaseHandler):\n def get(self):\n self.clear_cookie(\"user\")\n self.write('You are now logged out. '\n 'Click here to log back in.')","sub_path":"handlers/LogoutHandler.py","file_name":"LogoutHandler.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"505529037","text":"import pandas as pd\n\n\ndef give_data(feature_sel=0):\n \"\"\"\n Return in order: x_train, X_test, y_train, y_test\n \"\"\"\n\n common_path = \"/Users//Repositories/Applied-AI-Study-Group/Applied AI Study Group #5 - August 2021/Week 4/notebooks/santander-customer-transaction-prediction\"\n\n x_train = pd.read_csv(common_path + \"smote_train.csv\")\n y_train = pd.read_csv(common_path + \"smote_train_labels.csv\")\n X_test = pd.read_csv(common_path + \"X_val.csv\", index_col=\"ID_code\")\n y_test = pd.read_csv(common_path + \"y_val.csv\", index_col=\"ID_code\")\n\n return x_train, X_test, y_train, y_test\n","sub_path":"Batch_6_January2022/Week5/hyperparameter_search/helper_funcs.py","file_name":"helper_funcs.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"644166583","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\nfrom datetime import date, datetime # noqa: F401\n\nfrom typing import List, Dict # noqa: F401\n\nfrom openapi_server.models.base_model_ import Model\nfrom openapi_server.models.rates_rates import RatesRates\nfrom openapi_server import util\n\nfrom openapi_server.models.rates_rates import RatesRates # noqa: E501\n\nclass Rates(Model):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).\n\n Do not edit the class manually.\n \"\"\"\n\n def __init__(self, height=None, rates=None): # noqa: E501\n \"\"\"Rates - a model defined in OpenAPI\n\n :param height: The height of this Rates. # noqa: E501\n :type height: int\n :param rates: The rates of this Rates. # noqa: E501\n :type rates: RatesRates\n \"\"\"\n self.openapi_types = {\n 'height': int,\n 'rates': RatesRates\n }\n\n self.attribute_map = {\n 'height': 'height',\n 'rates': 'rates'\n }\n\n self._height = height\n self._rates = rates\n\n @classmethod\n def from_dict(cls, dikt) -> 'Rates':\n \"\"\"Returns the dict as a model\n\n :param dikt: A dict.\n :type: dict\n :return: The rates of this Rates. # noqa: E501\n :rtype: Rates\n \"\"\"\n return util.deserialize_model(dikt, cls)\n\n def to_dict(self, prefix=\"\"):\n \"\"\"Returns the model as a dict:\n\n :return: The Rates as a dict\n :rtype: dict\n \"\"\"\n return { 'height': self._height,\n 'rates': self._rates }\n\n\n @property\n def height(self):\n \"\"\"Gets the height of this Rates.\n\n Height # noqa: E501\n\n :return: The height of this Rates.\n :rtype: int\n \"\"\"\n return self._height\n\n @height.setter\n def height(self, height):\n \"\"\"Sets the height of this Rates.\n\n Height # noqa: E501\n\n :param height: The height of this Rates.\n :type height: int\n \"\"\"\n if height is not None and height < 1: # noqa: E501\n raise ValueError(\"Invalid value for `height`, must be a value greater than or equal to `1`\") # noqa: E501\n\n self._height = height\n\n @property\n def rates(self):\n \"\"\"Gets the rates of this Rates.\n\n\n :return: The rates of this Rates.\n :rtype: RatesRates\n \"\"\"\n return self._rates\n\n @rates.setter\n def rates(self, rates):\n \"\"\"Sets the rates of this Rates.\n\n\n :param rates: The rates of this Rates.\n :type rates: RatesRates\n \"\"\"\n\n self._rates = rates\n","sub_path":"openapi_server/models/rates.py","file_name":"rates.py","file_ext":"py","file_size_in_byte":2635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"299562702","text":"## This code is written by Davide Albanese, .\n## (C) 2010 mlpy Developers.\n\n## This program is free software: you can redistribute it and/or modify\n## it under the terms of the GNU General Public License as published by\n## the Free Software Foundation, either version 3 of the License, or\n## (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 General Public License for more details.\n\n## You should have received a copy of the GNU General Public License\n## along with this program. If not, see .\n\n__all__ = ['elasticnet_base', 'ElasticNet', 'ElasticNetC']\n\nimport numpy as np\n\ndef softt(beta0, lmb):\n \"\"\"Soft thresholding.\n \"\"\"\n\n lmb_half = lmb / 2.0\n idx = np.abs(beta0) < lmb_half\n beta = beta0 - np.sign(beta0) * lmb_half\n beta[idx] = 0.0\n\n return beta\n\n\ndef elasticnet_base(x, y, lmb, eps, supp=True, tol=0.01):\n \"\"\"Elastic Net Regularization via Iterative Soft Thresholding.\n\n `x` should be centered and normalized by columns, and `y`\n should be centered.\n\n Computes the coefficient vector which solves the elastic-net\n regularization problem min {\\|\\| X beta - Y \\|\\|^2 + lambda(\\|beta\\|^2_2\n + eps \\|beta\\|_1}. The solution beta is computed via iterative\n soft-thresholding, with damping factor 1/(1+eps*lambda), thresholding\n factor eps*lambda, null initialization vector and step\n 1 / (eig_max(XX^T)*1.1).\n\n :Parameters:\n x : 2d array_like object (N x P)\n matrix of regressors\n y : 1d array_like object (N)\n response\n lmb : float\n regularization parameter controlling overfitting.\n `lmb` can be tuned via cross validation.\n eps : float\n correlation parameter preserving correlation\n among variables against sparsity. The solutions\n obtained for different values of the correlation\n parameter have the same prediction properties but\n different feature representation.\n supp : bool\n if True, the algorithm stops when the support of beta\n reached convergence. If False, the algorithm stops when\n the coefficients reached convergence, that is when\n the beta_{l}(i) - beta_{l+1}(i) > tol * beta_{l}(i)\n for all i.\n tol : double\n tolerance for convergence\n\n :Returns:\n beta, iters : 1d numpy array, int\n beta, number of iterations performed\n \"\"\"\n\n xarr = np.asarray(x)\n yarr = np.asarray(y)\n\n xt = xarr.T\n xy = np.dot(xt, yarr)\n\n n, p = xarr.shape\n if p >= n:\n xx = np.dot(xarr, xt)\n else:\n xx = np.dot(xt, xarr)\n\n step = 1. / (np.linalg.eigvalsh(xx).max() * 1.1)\n lmb = lmb * n * step\n damp = 1. / (1 + lmb * eps)\n beta0 = np.zeros(p, dtype=np.float)\n\n k, i = 0, 0\n kmax = 100000\n imax = 10\n\n tmp = beta0 + (step * (np.dot(-xt, np.dot(xarr, beta0)) + xy))\n beta = softt(tmp, lmb) * damp\n\n while ((k < kmax) and (i < imax)):\n if supp:\n if np.any(((beta0 != 0) - (beta != 0)) != 0):\n i = 0\n else:\n if np.any(np.abs(beta0 - beta) > tol * np.abs(beta0)):\n i = 0\n\n beta0 = beta\n tmp = beta0 + (step * (np.dot(-xt, np.dot(xarr, beta0)) + xy))\n beta = softt(tmp, lmb) * damp\n\n i, k = i+1, k+1\n imax = np.max((1000, 10**np.floor(np.log10(k))))\n\n return beta, k\n\n\nclass ElasticNet(object):\n \"\"\"Elastic Net Regularization via Iterative Soft Thresholding.\n\n Computes the coefficient vector which solves the elastic-net\n regularization problem min {\\|\\| X beta - Y \\|\\|^2 + lambda(\\|beta\\|^2_2\n + eps \\|beta\\|_1}. The solution beta is computed via iterative\n soft-thresholding, with damping factor 1/(1+eps*lambda), thresholding\n factor eps*lambda, null initialization vector and step\n 1 / (eig_max(XX^T)*1.1).\n \"\"\"\n\n def __init__(self, lmb, eps, supp=True, tol=0.01):\n \"\"\"Initialization.\n\n :Parameters:\n lmb : float\n regularization parameter controlling overfitting.\n `lmb` can be tuned via cross validation.\n eps : float\n correlation parameter preserving correlation\n among variables against sparsity. The solutions\n obtained for different values of the correlation\n parameter have the same prediction properties but\n different feature representation.\n supp : bool\n if True, the algorithm stops when the support of beta\n reached convergence. If False, the algorithm stops when\n the coefficients reached convergence, that is when\n the beta_{l}(i) - beta_{l+1}(i) > tol * beta_{l}(i)\n for all i.\n tol : double\n tolerance for convergence\n \"\"\"\n\n self._lmb = float(lmb)\n self._eps = float(eps)\n self._supp = supp\n self._tol = float(tol)\n\n self._beta = None\n self._beta0 = None\n self._iters = None\n\n def learn(self, x, y):\n \"\"\"Compute the regression coefficients.\n\n :Parameters:\n x : 2d array_like object (N x P)\n matrix of regressors\n y : 1d array_like object (N)\n response\n \"\"\"\n\n xarr = np.array(x, dtype=np.float, copy=True)\n yarr = np.array(y, dtype=np.float, copy=True)\n\n if xarr.ndim != 2:\n raise ValueError(\"x must be a 2d array_like object\")\n\n if yarr.ndim != 1:\n raise ValueError(\"y must be an 1d array_like object\")\n\n if xarr.shape[0] != yarr.shape[0]:\n raise ValueError(\"x, y shape mismatch\")\n\n # center x\n xmean = np.mean(xarr, axis=0)\n xarr -= xmean\n\n # normalize x\n xnorm = np.sqrt(np.sum((xarr)**2, axis=0))\n xarr /= xnorm\n\n # center y\n ymean = np.mean(yarr)\n\n self._beta, self._iters = elasticnet_base(xarr, yarr,\n lmb=self._lmb, eps=self._eps, supp=self._supp, tol=self._tol)\n self._beta /= xnorm\n self._beta0 = ymean - np.dot(xmean, self._beta)\n\n def pred(self, t):\n \"\"\"Compute the predicted response.\n\n :Parameters:\n t : 1d or 2d array_like object ([M,] P)\n test data\n\n :Returns:\n p : float or 1d numpy array\n predicted response\n \"\"\"\n\n if self._beta0 is None:\n raise ValueError('no mode computed; run learn() first')\n\n tarr = np.asarray(t, dtype=np.float)\n\n if tarr.ndim > 2 or tarr.ndim < 1:\n raise ValueError(\"t must be an 1d or a 2d array_like object\")\n\n try:\n p = np.dot(tarr, self._beta) + self._beta0\n except ValueError:\n raise ValueError(\"t, beta: shape mismatch\")\n\n return p\n\n def iters(self):\n \"\"\"Return the number of iterations performed.\n \"\"\"\n\n return self._iters\n\n def beta(self):\n \"\"\"Return b_1, ..., b_p.\n \"\"\"\n\n return self._beta\n\n def beta0(self):\n \"\"\"Return b_0.\n \"\"\"\n\n return self._beta0\n\n\nclass ElasticNetC(ElasticNet):\n \"\"\"Elastic Net Regularization via Iterative Soft Thresholding\n for classification.\n\n See the ElasticNet class documentation.\n \"\"\"\n\n def __init__(self, lmb, eps, supp=True, tol=0.01):\n \"\"\"Initialization.\n\n :Parameters:\n lmb : float\n regularization parameter controlling overfitting.\n `lmb` can be tuned via cross validation.\n eps : float\n correlation parameter preserving correlation\n among variables against sparsity. The solutions\n obtained for different values of the correlation\n parameter have the same prediction properties but\n different feature representation.\n supp : bool\n if True, the algorithm stops when the support of beta\n reached convergence. If False, the algorithm stops when\n the coefficients reached convergence, that is when\n the beta_{l}(i) - beta_{l+1}(i) > tol * beta_{l}(i)\n for all i.\n tol : double\n tolerance for convergence\n \"\"\"\n \n ElasticNet.__init__(self, lmb, eps, supp=True, tol=0.01)\n self._labels = None\n\n def learn(self, x, y):\n \"\"\"Compute the classification coefficients.\n\n :Parameters:\n x : 2d array_like object (N x P)\n matrix\n y : 1d array_like object integer (N)\n class labels\n \"\"\"\n\n yarr = np.asarray(y, dtype=np.int)\n self._labels = np.unique(yarr)\n \n k = self._labels.shape[0]\n if k != 2:\n raise ValueError(\"number of classes must be = 2\")\n\n ynew = np.where(yarr == self._labels[0], -1, 1) \n\n ElasticNet.learn(self, x, ynew)\n\n def pred(self, t):\n \"\"\"Compute the predicted labels.\n\n :Parameters:\n t : 1d or 2d array_like object ([M,] P)\n test data\n\n :Returns:\n p : integer or 1d numpy array\n predicted labels\n \"\"\"\n\n p = ElasticNet.pred(self, t)\n ret = np.where(p>0, self._labels[1], self._labels[0])\n\n return ret\n\n def w(self):\n \"\"\"Returns the coefficients.\n \"\"\"\n if ElasticNet.beta(self) is None:\n raise ValueError(\"No model computed\")\n\n return super(ElasticNetC, self).beta()\n\n def bias(self):\n \"\"\"Returns the bias.\n \"\"\"\n if ElasticNet.beta0(self) is None:\n raise ValueError(\"No model computed\")\n\n return super(ElasticNetC, self).beta0()\n\n def labels(self):\n \"\"\"Outputs the name of labels.\n \"\"\"\n \n return self._labels\n","sub_path":"virtualenvironment/env/lib/python2.7/site-packages/mlpy/elasticnet.py","file_name":"elasticnet.py","file_ext":"py","file_size_in_byte":10056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"548319267","text":"\"\"\"Define a Eufy camera object.\"\"\"\nimport logging\nfrom typing import TYPE_CHECKING\n\nfrom .params import ParamType\n\n\nif TYPE_CHECKING:\n from .api import API # pylint: disable=cyclic-import\n\n_LOGGER: logging.Logger = logging.getLogger(__name__)\n\n\nclass Camera:\n \"\"\"Define the camera object.\"\"\"\n\n def __init__(self, api: \"API\", camera_info: dict) -> None:\n \"\"\"Initialize.\"\"\"\n self._api = api\n self.camera_info: dict = camera_info\n\n @property\n def hardware_version(self) -> str:\n \"\"\"Return the camera's hardware version.\"\"\"\n return self.camera_info[\"main_hw_version\"]\n\n @property\n def last_camera_image_url(self) -> str:\n \"\"\"Return the URL to the latest camera thumbnail.\"\"\"\n return self.camera_info[\"cover_path\"]\n\n @property\n def mac(self) -> str:\n \"\"\"Return the camera MAC address.\"\"\"\n return self.camera_info[\"wifi_mac\"]\n\n @property\n def model(self) -> str:\n \"\"\"Return the camera's model.\"\"\"\n return self.camera_info[\"device_model\"]\n\n @property\n def name(self) -> str:\n \"\"\"Return the camera name.\"\"\"\n return self.camera_info[\"device_name\"]\n\n @property\n def params(self) -> dict:\n \"\"\"Return camera parameters.\"\"\"\n params = {}\n for param in self.camera_info[\"params\"]:\n param_type = param[\"param_type\"]\n value = param[\"param_value\"]\n try:\n param_type = ParamType(param_type)\n value = param_type.read_value(value)\n except ValueError:\n _LOGGER.warning(\n 'Unable to process parameter \"%s\", value \"%s\"', param_type, value\n )\n params[param_type] = value\n return params\n\n @property\n def serial(self) -> str:\n \"\"\"Return the camera serial number.\"\"\"\n return self.camera_info[\"device_sn\"]\n\n @property\n def software_version(self) -> str:\n \"\"\"Return the camera's software version.\"\"\"\n return self.camera_info[\"main_sw_version\"]\n\n @property\n def station_serial(self) -> str:\n \"\"\"Return the camera's station serial number.\"\"\"\n return self.camera_info[\"station_sn\"]\n\n async def async_set_params(self, params: dict) -> None:\n \"\"\"Set camera parameters.\"\"\"\n serialized_params = []\n for param_type, value in params.items():\n if isinstance(param_type, ParamType):\n value = param_type.write_value(value)\n param_type = param_type.value\n serialized_params.append({\"param_type\": param_type, \"param_value\": value})\n await self._api.request(\n \"post\",\n \"app/upload_devs_params\",\n json={\n \"device_sn\": self.serial,\n \"station_sn\": self.station_serial,\n \"params\": serialized_params,\n },\n )\n await self.async_update()\n\n async def async_start_detection(self):\n \"\"\"Start camera detection.\"\"\"\n await self.async_set_params({ParamType.DETECT_SWITCH: 1})\n\n async def async_start_stream(self) -> str:\n \"\"\"Start the camera stream and return the RTSP URL.\"\"\"\n start_resp = await self._api.request(\n \"post\",\n \"web/equipment/start_stream\",\n json={\n \"device_sn\": self.serial,\n \"station_sn\": self.station_serial,\n \"proto\": 2,\n },\n )\n\n return start_resp[\"data\"][\"url\"]\n\n async def async_stop_detection(self):\n \"\"\"Stop camera detection.\"\"\"\n await self.async_set_params({ParamType.DETECT_SWITCH: 0})\n\n async def async_stop_stream(self) -> None:\n \"\"\"Stop the camera stream.\"\"\"\n await self._api.request(\n \"post\",\n \"web/equipment/stop_stream\",\n json={\n \"device_sn\": self.serial,\n \"station_sn\": self.station_serial,\n \"proto\": 2,\n },\n )\n\n async def async_update(self) -> None:\n \"\"\"Get the latest values for the camera's properties.\"\"\"\n await self._api.async_update_device_info()\n","sub_path":"eufy_security/camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":4154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"492104728","text":"#!/usr/bin/env python\n\n\"\"\"\nSetup script for gitim\n\"\"\"\n\nfrom setuptools import setup\nfrom gitim import (__version__ as VERSION, __author__ as AUTHOR,\n __name__ as NAME, __license__ as LICENSE)\n\nif __name__ == '__main__':\n\n with open('requirements.txt') as reqs_file:\n REQS = reqs_file.readlines()\n\n setup(\n name=NAME,\n author=AUTHOR,\n version=VERSION,\n license=LICENSE,\n install_requires=REQS,\n entry_points={'console_scripts':['gitim=gitim:main']},\n py_modules=[NAME]\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"503057433","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jun 06 14:28:32 2017\r\n\r\n@author: kner\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport ctypes as ct\r\n\r\ndcimgapi = ct.cdll.LoadLibrary('dcimgapi.dll')\r\n#dcimgapi = ct.WinDLL('dcimgapi.dll')\r\n\r\n#BEGIN_DCIMG_DECLARE( struct, DCIMG_OPENA )\r\n#{\r\n#\tint32\t\t\tsize;\t\t\t\t// [in] size of this structure\r\n#\tint32\t\t\treserved;\r\n#\tHDCIMG\t\t\thdcimg;\t\t\t\t// [out]\r\n#\tLPCSTR\t\t\tpath;\t\t\t\t// [in] DCIMG file path\r\n#}\r\n#END_DCIMG_DECLARE( DCIMG_OPENA )\r\n\r\n#DCIMG_IDPARAML\r\nDCIMG_IDPARAML_NUMBEROF_TOTALFRAME = 0\t\t\t# number of total frame in the file\r\nDCIMG_IDPARAML_NUMBEROF_SESSION = 1\t\t\t# number of session in the file.\r\nDCIMG_IDPARAML_NUMBEROF_FRAME = 2\t\t\t\t# number of frame in current session.\r\nDCIMG_IDPARAML_SIZEOF_USERDATABIN_SESSION = 4 # byte size of current session binary USER META DATA.\r\nDCIMG_IDPARAML_SIZEOF_USERDATABIN_FILE = 5\t\t# byte size of file binary USER META DATA.\r\nDCIMG_IDPARAML_SIZEOF_USERDATATEXT_SESSION = 7 # byte size of current session text USER META DATA.\r\nDCIMG_IDPARAML_SIZEOF_USERDATATEXT_FILE = 8\t # byte size of file text USER META DATA.\r\nDCIMG_IDPARAML_IMAGE_WIDTH = 9\t\t\t\t\t# image width in current session.\r\nDCIMG_IDPARAML_IMAGE_HEIGHT = 10\t\t\t # image height in current session.\r\nDCIMG_IDPARAML_IMAGE_ROWBYTES = 11\t\t\t\t# image rowbytes in current session.\r\nDCIMG_IDPARAML_IMAGE_PIXELTYPE = 12\t\t\t\t# image pixeltype in current session.\r\nDCIMG_IDPARAML_MAXSIZE_USERDATABIN = 13\t # maximum byte size of frame binary USER META DATA in current session.\r\nDCIMG_IDPARAML_MAXSIZE_USERDATABIN_SESSION =14\t# maximum byte size of session binary USER META DATA in the file.\r\nDCIMG_IDPARAML_MAXSIZE_USERDATATEXT = 16\t # maximum byte size of frame text USER META DATA in current session.\r\nDCIMG_IDPARAML_MAXSIZE_USERDATATEXT_SESSION = 17 # maximum byte size of session tex USER META DATA in the file.\r\nDCIMG_IDPARAML_CURRENT_SESSION = 19\t\t # current session index\r\nDCIMG_IDPARAML_NUMBEROF_VIEW = 20\t\t\t\t# number of view in current session.\r\nDCIMG_IDPARAML_FILEFORMAT_VERSION = 21\t\t\t# file format version\r\nDCIMG_IDPARAML_CAPABILITY_IMAGEPROC = 22\t\t# capability of image processing\r\n\r\nclass GUID(ct.Structure):\r\n _fields_ = [(\"Data1\", ct.c_uint32), (\"Data2\", ct.c_ushort), \r\n (\"Data3\", ct.c_ushort), (\"Data4\", ct.c_char_p)]\r\n \r\nclass INIT(ct.Structure):\r\n _fields_ = [(\"size\", ct.c_int32), (\"reserved\", ct.c_int32), (\"guid\", ct.POINTER(GUID))]\r\n \r\n \r\nLPCSTR = ct.c_char_p\r\nHDCIMG = ct.c_void_p\r\nclass OPEN(ct.Structure):\r\n _fields_ = [(\"size\", ct.c_int32), (\"reserved\", ct.c_int32), \r\n (\"hdcimg\", HDCIMG), (\"path\", LPCSTR)]\r\n\r\n# DCIMG_PIXELTYPE\r\nDCIMG_PIXELTYPE_NONE\t\t= 0x00000000\r\nDCIMG_PIXELTYPE_MONO8\t\t= 0x00000001\r\nDCIMG_PIXELTYPE_MONO16\t= 0x00000002\r\nPIXELTYPE = ct.c_int32\r\n\r\nclass TIMESTAMP(ct.Structure):\r\n _fields_ = [(\"sec\", ct.c_uint32), (\"microsec\", ct.c_int32)]\r\n\r\n''' copyframe() and lockframe() use this structure. Some members have different direction.\r\n\t[i:o] means, the member is input at copyframe() and output at lockframe().\r\n\t[i:i] and [o:o] means always input and output at both function.\r\n\t\"input\" means application has to set the value before calling.\r\n\t\"output\" means function filles a value at returning. '''\r\nclass FRAME(ct.Structure):\r\n _fields_ = [(\"size\", ct.c_int32), (\"iKind\", ct.c_int32),\r\n (\"option\", ct.c_int32),\r\n (\"iFrame\", ct.c_int32), (\"buf\", ct.POINTER(ct.c_uint16)), \r\n (\"rowbytes\", ct.c_int32), (\"type\", PIXELTYPE),\r\n (\"width\", ct.c_int32), (\"height\", ct.c_int32),\r\n (\"left\", ct.c_int32), (\"top\", ct.c_int32),\r\n (\"timestamp\", TIMESTAMP), (\"framestamp\", ct.c_int32),\r\n (\"camerastamp\", ct.c_int32), (\"conversionfactor_coeff\", ct.c_double),\r\n (\"conversionfactor_offset\", ct.c_double)]\r\n\r\ndef read_frame(fn='test2.dcimg'):\r\n ''' simple example of pulling out basic information and one frame from\r\n dcimg file '''\r\n \r\n #fn = 'test2.dcimg'\r\n h=0\r\n iparams = INIT()\r\n temp = GUID()\r\n temp.Data4 = ct.c_char_p('00000000')\r\n iparams.guid = ct.pointer(temp)\r\n iparams.size = ct.sizeof(iparams)\r\n \r\n h = dcimgapi.dcimg_init(ct.pointer(iparams))\r\n print(hex(np.uint32(h)))\r\n \r\n iopen = OPEN()\r\n iopen.size = ct.sizeof(iopen)\r\n iopen.path = LPCSTR(fn)\r\n \r\n h = dcimgapi.dcimg_openA(ct.pointer(iopen))\r\n print(hex(np.uint32(h)))\r\n \r\n nwidth = ct.c_int32(0)\r\n h = dcimgapi.dcimg_getparaml( iopen.hdcimg, DCIMG_IDPARAML_IMAGE_WIDTH, ct.byref(nwidth) )\r\n print(hex(np.uint32(h)))\r\n print(nwidth.value)\r\n \r\n nframes = ct.c_int32(0)\r\n h = dcimgapi.dcimg_getparaml( iopen.hdcimg, DCIMG_IDPARAML_NUMBEROF_TOTALFRAME, ct.byref(nframes) )\r\n print(hex(np.uint32(h)))\r\n print(nframes.value)\r\n \r\n nsessions = ct.c_int32(0)\r\n h = dcimgapi.dcimg_getparaml( iopen.hdcimg, DCIMG_IDPARAML_NUMBEROF_SESSION, ct.byref(nsessions) )\r\n print(hex(np.uint32(h)))\r\n print(nsessions.value)\r\n \r\n h = dcimgapi.dcimg_setsessionindex( iopen.hdcimg, ct.c_int32(0) )\r\n print(hex(np.uint32(h)))\r\n \r\n iframe = FRAME()\r\n iframe.size = ct.c_int32(ct.sizeof(iframe))\r\n iframe.iFrame = ct.c_int32(10)\r\n #data = np.zeros((2048,2048), dtype=np.uint16)\r\n h = dcimgapi.dcimg_lockframe( iopen.hdcimg, ct.byref(iframe) )\r\n print(hex(np.uint32(h)))\r\n data = np.fromiter(iframe.buf, dtype=np.uint16, count=(2048*2048))\r\n \r\n h = dcimgapi.dcimg_close(iopen.hdcimg)\r\n print(hex(np.uint32(h)))\r\n return data\r\n\r\n","sub_path":"bfmatlab551/dcimg_defs.py","file_name":"dcimg_defs.py","file_ext":"py","file_size_in_byte":5612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"313685728","text":"from abc import abstractmethod\nfrom enum import Enum, auto\n\n\nclass Person:\n def __init__(self, name):\n self.name = name\n\n\nclass Relation(Enum):\n PARENT = auto()\n CHILD = auto()\n SIBLING = auto()\n\n\n# High level classes or high level modules in you code shouldn't directly depend on low level modules\nclass RelationshipBrowser: # instead they should depend on abstractions (abstract class or class with abstract methods)\n @abstractmethod\n def find_all_children_of(self, name):\n pass\n\n\nclass Relations(RelationshipBrowser): # low-level module\n relations = [] # kind of storage of relationships\n\n def add_parent_and_child(self, parent, child):\n self.relations.append((parent, Relation.PARENT, child))\n self.relations.append((child, Relation.CHILD, parent)) # reverse\n return self\n\n def find_all_children_of(self, name):\n for r in self.relations:\n if r[0].name == name and r[1] == Relation.PARENT:\n yield r[2].name\n\n\nclass Research: # high-level class, a tool to print all child stored in a storage (relationships browser)\n def __init__(self, browser, parent_name):\n for child in browser.find_all_children_of(parent_name): # here is a dependency on abstractmethod\n print(f'{parent_name} has a child called {child}')\n\n\nif __name__ == '__main__':\n parent1 = Person('Vasyl')\n child1 = Person('Emily')\n child2 = Person('Max')\n\n relations = Relations() \\\n .add_parent_and_child(parent1, child1) \\\n .add_parent_and_child(parent1, child2)\n\n Research(relations, parent1.name)\n\n","sub_path":"0_SOLID/dip.py","file_name":"dip.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"504311857","text":"\nfrom evaluation_histograms import evaluateHistograms, evaluatesubImageHistograms, evaluatePyramidHistograms\nimport numpy as np \nfrom tqdm import tqdm\n\ndef evaluateQuery(t_img_list, q_img, eval_method, hist_meth):\n distance_list = []\n for t_image in t_img_list:\n dist = 0\n if(hist_meth == \"simple\"):\n dist = evaluateHistograms(t_image, q_img, eval_method)\n elif(hist_meth == \"subimage\"):\n dist = evaluatesubImageHistograms(t_image, q_img, eval_method)\n elif(hist_meth == \"pyramid\"):\n dist = evaluatePyramidHistograms(t_image, q_img, eval_method)\n distance_list.append(dist)\n return distance_list\n\ndef evaluateQueryTest(t_img_list, q_img_list, k, eval_method, hist_method):\n similarity = []\n distAllList = list()\n for query_img in tqdm(q_img_list):\n dist_list = evaluateQuery(t_img_list, query_img, eval_method, hist_method)\n \n #Get k-images' index with highest similarity\n index_highest = np.argsort(dist_list)[:k]\n similarity.append(index_highest)\n distAllList.append(dist_list)\n return distAllList, similarity","sub_path":"week5/compare_images.py","file_name":"compare_images.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"387276303","text":"from __future__ import print_function\n\n__author__ = 'Viktor Kerkez '\n__date__ = '01 January 2009'\n__copyright__ = 'Copyright (c) 2009 Viktor Kerkez'\n\nimport os\nimport sys\nimport glob\nimport optparse\n\nfrom tea import shell\nfrom tea.utils import compress\nfrom tea.process import execute_and_report as er\n\n\ndef setup(module, target='zip', output_path=None, data_dir=None):\n dist = os.path.abspath('dist')\n try:\n if target == 'zip':\n assert er('setup.py', 'install', '--no-compile',\n '--install-lib', os.path.join(dist, 'lib'),\n '--install-scripts', os.path.join(dist),\n *(['--install-data', os.path.join(dist, data_dir)]\n if data_dir is not None else []))\n with shell.goto(dist) as ok:\n assert ok\n assert compress.mkzip('%s.zip' % module,\n glob.glob(os.path.join('lib', '*')))\n assert shell.remove('lib')\n elif target == 'exe':\n assert er('setup.py', 'install', '--no-compile',\n '--install-lib', os.path.join(dist, 'lib', 'python'),\n '--install-scripts', os.path.join(dist, 'scripts'),\n *(['--install-data', os.path.join(dist, data_dir)]\n if data_dir is not None else []))\n with shell.goto(dist) as ok:\n assert ok\n\n modules = list(filter(os.path.exists,\n ['lib', 'scripts'] + (\n [data_dir] if data_dir is not None\n else [])))\n assert compress.seven_zip('%s.exe' % module, modules,\n self_extracting=True)\n # Cleanup\n for module in modules:\n assert shell.remove(module)\n if output_path is not None:\n output_path = os.path.abspath(output_path)\n if output_path != dist:\n if not os.path.isdir(output_path):\n assert shell.mkdir(output_path)\n for filename in shell.search(dist, '*'):\n output = os.path.join(output_path,\n filename.replace(dist, '', 1)\n .strip('\\\\/'))\n assert shell.move(filename, output)\n return 0\n except AssertionError as e:\n print(e)\n return 1\n finally:\n # Cleanup\n if output_path != dist:\n shell.remove(dist)\n if os.path.isdir('build'):\n shell.remove('build')\n\n\ndef create_parser():\n parser = optparse.OptionParser(\n usage='python -m tea.utils.setup [options] MODULE_NAME')\n parser.add_option('-e', '--zip', action='store_const', dest='target',\n const='zip', help='build egg file and scripts',\n default='zip')\n parser.add_option('-x', '--exe', action='store_const', dest='target',\n const='exe', help='build self extracting executable',\n default='zip')\n parser.add_option('-o', '--output-path', action='store', type='string',\n dest='output_path', help='destination directory',\n default=None)\n parser.add_option('-d', '--data-dir', action='store', type='string',\n dest='data_dir', help='data dir relative path',\n default=None)\n return parser\n\n\ndef main(args):\n parser = create_parser()\n options, args = parser.parse_args(args)\n if len(args) != 1:\n parser.print_help()\n return 1\n else:\n module = args[0]\n return setup(module, options.target, options.output_path,\n options.data_dir)\n\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv[1:]))\n","sub_path":"pypi_install_script/tea-0.0.10.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"568037873","text":"# 4.\tОпределить, какое число в массиве встречается чаще всего.\n\nfrom random import random\n\n# готовим массив.\nquantity = int(input('Укажите длину масссива: '))\ndata_array = [0] * quantity\n\nfor i in range(quantity):\n data_array[i] = int(random() * 10)\n\nprint(data_array)\n\n# начинаем перебирать значения сравнивая его с следующим\nn = data_array[0]\nnumber_repetitions = 1\n\nfor i in range(quantity - 1):\n\n number = 1\n\n for j in range(i + 1, quantity):\n if data_array[i] == data_array[j]:\n number += 1\n\n if number > number_repetitions:\n number_repetitions = number\n n = data_array[i]\n\n# выводим количество повторений, либо сообщаем, что повторений нет\nif number_repetitions > 1:\n print(f'Найдено число {n} - оно встречается {number_repetitions} раз(а)')\nelse:\n print('Повторений не встречено')\n\n","sub_path":"Lesson_3/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"131554344","text":"import cv2\nimport numpy as np\nimport skimage.color\nimport matplotlib.pyplot as plt\n\nimage_colour = cv2.imread(\"/Users/vivad/PycharmProjects/CLFinalProject/original_imgs/turbine-blade.jpg\", 1)\nimage_gray = cv2.cvtColor(image_colour, cv2.COLOR_BGR2GRAY)\n\nker = np.ndarray((3, 3), dtype='int')\nker[0][0] = 0\nker[0][1] = 1\nker[0][2] = 0\nker[1][0] = 1\nker[1][1] = -4\nker[1][2] = 1\nker[2][0] = 0\nker[2][1] = 1\nker[2][2] = 0\n\n\ndef function_convolution(source, masking_kernel):\n image_h = source.shape[0]\n image_w = source.shape[1]\n\n kernel_h = masking_kernel.shape[0]\n kernel_w = masking_kernel.shape[1]\n\n h = kernel_h // 2\n w = kernel_w // 2\n\n convolved_image = np.zeros(source.shape)\n\n for i in range(h, image_h - h):\n for j in range(w, image_w - w):\n sum = 0\n\n for m in range(kernel_h):\n for n in range(kernel_w):\n sum = (sum + masking_kernel[m][n] * source[i - h + m][j - w + n])\n\n if (sum > 310):\n convolved_image[i][j] = 255\n\n return convolved_image\n\n\n\n\n\nconv_image_y_axis = function_convolution(image_gray, ker)\nfinal_op_image = skimage.color.gray2rgb(conv_image_y_axis)\nfinal_labelled = skimage.color.gray2rgb(conv_image_y_axis)\nfor i in range(conv_image_y_axis.shape[1]):\n for j in range(conv_image_y_axis.shape[0]):\n if (conv_image_y_axis[j][i] != 0):\n print(\"Point detected at:\"+str(i)+\",\"+str(j))\n\n text = str(i) + \" , \" + str(j)\n cv2.putText(image_colour, text, (i - 40, j + 40), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 1)\n cv2.circle(image_colour, (i, j), 10, (0, 255, 0), 1)\n cv2.circle(final_op_image, (i, j), 10, (0, 255, 0), 1)\n\n\ncv2.imwrite(\"/Users/vivad/PycharmProjects/CLFinalProject/Task2/point_detected_labelled.jpg\", image_colour)\ncv2.imwrite(\"/Users/vivad/PycharmProjects/CLFinalProject/Task2/point_detected.jpg\", final_op_image)\n\n\n\n\n\n\n\nimage_colour = cv2.imread(\"/Users/vivad/PycharmProjects/CLFinalProject/original_imgs/segment.jpg\")\nimage_gray = cv2.cvtColor(image_colour, cv2.COLOR_BGR2GRAY)\n\ncounter = [0] * 256\nfor i in range(image_gray.shape[0]):\n for j in range(image_gray.shape[1]):\n counter[image_gray[i, j]]+=1\npixel_range_counter = []\nfor i in range(0,256):\n pixel_range_counter.append(i)\n\n\nplt.bar(pixel_range_counter, counter)\nplt.ylabel('Intensity')\n#plt.show()\n\n\ndef find_thresh(img):\n new_empty_image = np.zeros([img.shape[0], img.shape[1]])\n initial = 210\n #(164, 285) (420, 285) (164, 26) (420, 26)\n\n\n for i in range(0, img.shape[0]):\n for j in range(0, img.shape[1]):\n if (img[i][j] > initial):\n new_empty_image[i][j] = img[i][j]\n\n return new_empty_image\n\ndef findCorners(img, window_size, k, thresh):\n\n # X and Y's differential calculator\n dy, dx = np.gradient(img)\n Ixx = dx ** 2\n Ixy = dy * dx\n Iyy = dy ** 2\n height = img.shape[0]\n width = img.shape[1]\n\n cornerList = []\n newImg = img.copy()\n color_img = newImg\n offset = window_size // 2\n\n # Loop through image and find our corners\n for y in range(offset, height - offset):\n for x in range(offset, width - offset):\n # Calculate sum of squares\n windowIxx = Ixx[y - offset:y + offset + 1, x - offset:x + offset + 1]\n windowIxy = Ixy[y - offset:y + offset + 1, x - offset:x + offset + 1]\n windowIyy = Iyy[y - offset:y + offset + 1, x - offset:x + offset + 1]\n Sxx = windowIxx.sum()\n Sxy = windowIxy.sum()\n Syy = windowIyy.sum()\n\n # Find determinant and trace, use to get corner response\n det = (Sxx * Syy) - (Sxy ** 2)\n trace = Sxx + Syy\n r = det - k * (trace ** 2)\n\n # If corner response is over threshold, color the point and add to corner list\n if r > thresh:\n # print(x, y, r)\n cornerList.append([x, y, r])\n\n return color_img, cornerList\n\n\norig_segmented_image = find_thresh(image_gray)\n\ncorImage, co_ordinates = findCorners(orig_segmented_image, 3, 0.05, 20)\n\nco_ordinates.sort()\nleft_most = co_ordinates[0]\nright_most = co_ordinates[len(co_ordinates) - 1]\n\ntop_most = [100, 100, 0]\nfor array in co_ordinates:\n if (array[1] < top_most[1]):\n top_most = array\n\nbottom_most = [419, 249, 211422285.096875]\nfor array in co_ordinates:\n if (array[1] > bottom_most[1]):\n bottom_most = array\n\ntop_most = tuple(top_most[0:2])\nbottom_most = tuple(bottom_most[0:2])\nleft_most = tuple(left_most[0:2])\nright_most = tuple(right_most[0:2])\n\ntop_right = []\ntop_right.append(right_most[0])\ntop_right.append(top_most[1])\ntop_right = tuple(top_right)\n\nbottom_right = []\nbottom_right.append(right_most[0])\nbottom_right.append(bottom_most[1])\nbottom_right = tuple(bottom_right)\n\ntop_left = []\ntop_left.append(left_most[0])\ntop_left.append(top_most[1])\ntop_left = tuple(top_left)\n\nbottom_left = []\nbottom_left.append(left_most[0])\nbottom_left.append(bottom_most[1])\nbottom_left = tuple(bottom_left)\n\nfinal_op_image = skimage.color.gray2rgb(orig_segmented_image)\nlineThickness = 2\ncv2.line(final_op_image, bottom_left, top_left, (0, 255, 255), lineThickness)\ncv2.line(final_op_image, bottom_right, top_right, (0, 255, 255), lineThickness)\ncv2.line(final_op_image, bottom_left, bottom_right, (0, 255, 255), lineThickness)\ncv2.line(final_op_image, top_left, top_right, (0, 255, 255), lineThickness)\n\ncv2.imwrite(\"/Users/vivad/PycharmProjects/CLFinalProject/Task2/segmented.jpg\", final_op_image)\n\nprint(\"The corners of the bounding box are:\")\nprint(bottom_left, bottom_right, top_left, top_right)","sub_path":"Project_3/task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":5652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"638094794","text":"import os\nimport shutil\n\n# Create a folder to store invoices\ndesktop = '/Users/jongregis/Desktop/CCI Invoices'\nos.mkdir(desktop)\n\n# Change dir to where invoices are stored\nos.chdir('/Users/jongregis/Python/JobAutomation/practice invoices/MYCAA Invoices')\n\n# Go through files and only grab CCI Invoices\nfor f in os.listdir():\n if not 'AU ED4' in f and not 'UWLAX' in f and not 'CSU' in f and not 'MET' in f and not 'TAMU M' in f:\n shutil.move(f, desktop)\n\n# Create zip folder from the CCI Invoices\nos.chdir('/Users/jongregis/Desktop')\nshutil.make_archive('CCI Invoices', 'zip', desktop)\n\ncorrect = input('Does everything look correct? Y/N: ')\n\nif correct == 'y':\n mycaa = \"/Volumes/SanDisk Extreme SSD/Dropbox (ECA Consulting)/ECA Back Office/Lisa's Backup/Invoices/Invoices\"\n Elearning = \"/Volumes/SanDisk Extreme SSD/Dropbox (ECA Consulting)/ECA Back Office/Lisa's Backup/Invoices/ILT Invoices\"\n os.chdir(desktop)\n for f in os.listdir():\n if f == '.DS_Store':\n continue\n shutil.move(f, mycaa)\n","sub_path":"JobAutomation/SortingInvoices/sortingCCI.py","file_name":"sortingCCI.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"135958875","text":"def cluster_place_bucket(graph, cluster):\n \"\"\"\n :param cluster current cluster\n\n The inputted cluster has undergone a size change, either due to cluster growth or during a cluster merge, in which case the new root cluster is inputted. We increase the appropiate bucket number of the cluster intil the fitting bucket has been reached. The cluster is then appended to that bucket.\n If the max bucket number has been reached. The cluster is appended to the wastebasket, which will never be selected for growth.\n \"\"\"\n\n def mop_growth_HG(size):\n if size == 1:\n return 5\n else:\n K = (-3 / 4 + (9 / 16 + (size - 2) / 2) ** (1 / 2)) // 1\n PG = 6 + 2 * K ** 2 + 7 * K\n id = (size - 2) - 2 * K ** 2 - 3 * K\n if id < K + 1:\n CG = 2\n elif id < 2 * (K + 1):\n CG = 3\n elif id < 3 * (K + 1) + 1:\n CG = 4\n else:\n CG = 5\n return int(PG + id + CG + size - 1)\n\n def mop_growth_FG(size):\n if size < 5:\n return size\n elif size < 8:\n return size + 1\n else:\n K = int(-7 / 4 + (49 / 16 + (size - 8) / 2) ** (1 / 2)) // 1\n PG = 2 * K ** 2 + 3 * K + 1\n base_bucket = mop_growth_HG(PG + 1)\n id = size - base_bucket + PG\n if id < K + 1:\n CG = id\n elif id < 2 * (K + 1) + 1:\n CG = id - 1\n elif id < 3 * (K + 1) + 3:\n CG = id - 2\n elif id < 4 * (K + 1) + 4:\n CG = id - 3\n else:\n CG = id - 4\n return int(base_bucket + id + CG + 1)\n\n if cluster.support:\n cluster.bucket = mop_growth_HG(cluster.size) - 1\n else:\n cluster.bucket = mop_growth_FG(cluster.size) - 1\n\n if cluster.parity % 2 == 1 and cluster.bucket < graph.numbuckets:\n graph.buckets[cluster.bucket].append(cluster)\n if cluster.bucket > graph.maxbucket:\n graph.maxbucket = cluster.bucket\n else:\n cluster.bucket = None\n","sub_path":"old/mop_growth/mop_cluster_place_bucket.py","file_name":"mop_cluster_place_bucket.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"529355241","text":"\"\"\"\nSupport mudule for EPICS Input/Output Controllers (IOCs)\nImplements the server side of the Channel Access (CA) protocol, version 4.11.\n\nAuthor: Friedrich Schotte\nDate created: 2009-10-31\nDate last modified: 2019-11-08\n\nbased on: 'Channel Access Protocol Specification', version 4.11\nhttp://epics.cosylab.com/cosyjava/JCA-Common/Documentation/CAproto.html\n\nObject-Oriented Interface 1\n\nPV class object: recommended for application that export a single\nprocess variable.\n\ndef getT(): return float(serial_port.query(\"SET:TEMP?\"))\ndef setT(T): serial_port.write(\"SET:TEMP %s\" % T)\npv = PV(\"14IDB:TemperatureController.T\",get=getT,set=setT)\n\nObject-Oriented Interface 2\n\nUse \"register\" object to export properties of a Python class object as\nEPICS PVs.\n\nclass Temperature(object):\n def get_value(self): return float(serial_port.query(\"SET:TEMP?\"))\n def set_value(self,value): serial_port.write(\"SET:TEMP %s\" % value)\n value = property(get_value,set_value)\nT = Temperature()\n\nregister_object(T,prefix=\"14IDB:TemperatureController.\")\n\nProcedural Interface\n\ncasput (\"14IDB:MyInstrument.VAL\",1.234)\nCreates a process variable named \"14IDB:MyInstrument.VAL\"\nSubsequent calls to with difference value cause update events to besent to\nconnected clients.\n\ncasget (\"14IDB:MyInstrument.VAL\")\nReads back the current value of the \"14IDB:MyInstrument.VAL\", which may have\nbeen modified be a client since the last casput.\n\ncasmonitor(\"14IDB:MyInstrument.VAL\",callback=procedure)\nThe function \"procedure\" is called when a client modifies a the process\nvariable with three arguments:\n- the name of the process variable\n- the new value\n- the new value as string\n\"\"\"\nfrom logging import debug, info, warning, error\n\n__version__ = \"1.7.4\" # bug fix: isstring\n\nDEBUG = False # Generate debug messages?\n\nregistered_object_list = []\n\n\ndef register_object(object, name=\"\"):\n \"\"\"Export object as PV under the given name\"\"\"\n global registered_object_list\n start_server()\n unregister_object(name=name)\n registered_object_list += [(object, name)]\n\n\ncasregister = CAServer_register = register_object # alias names\n\n\ndef unregister_object(object=None, name=None):\n \"\"\"Undo 'register_object'\"\"\"\n global registered_object_list\n if name is None:\n for (o, n) in registered_object_list:\n if o is object:\n name = n\n if name is not None:\n for PV_name in list(PVs):\n if PV_name.startswith(name):\n delete_PV(PV_name)\n if object is not None:\n for (o,n) in registered_object_list:\n if o is object: name = n\n for PV_name in list(PVs):\n if PV_name.startswith(name):\n delete_PV(PV_name)\n registered_object_list = [\n (o, n) for (o, n) in registered_object_list if not o is object\n ]\n if name is not None:\n registered_object_list = [(o, n) for (o, n) in registered_object_list if not n == name]\n\n\ndef registered_objects():\n \"\"\"List of Python object instances\"\"\"\n return [object for (object,name) in registered_object_list]\n\n\nregistered_properties = {}\n\n\ndef register_property(object, property_name, PV_name):\n \"\"\"Export object as PV under the given name\"\"\"\n global registered_properties\n start_server()\n unregister_property(PV_name=PV_name)\n registered_properties[PV_name] = (object, property_name)\n\n\ndef unregister_property(object=None, property_name=None, PV_name=None):\n \"\"\"Undo 'register_object'\"\"\"\n global registered_properties\n if object is not None and property_name is not None and PV_name is not None:\n if PV_name in registered_properties:\n if registered_properties[PV_name] == (object, property_name):\n del registered_properties[PV_name]\n elif PV_name is not None:\n if PV_name in registered_properties:\n del registered_properties[PV_name]\n elif object is not None and property_name is not None:\n for key in list(registered_properties):\n if registered_properties[key] == (object, property_name):\n del registered_properties[key]\n\n\ndef casdel(name):\n \"\"\"Undo 'casput'\"\"\"\n for PV_name in list(PVs):\n if PV_name.startswith(name):\n delete_PV(PV_name)\n\n\nclass PV(object):\n \"\"\"Process Variable.\n Override the 'set_value' and 'get_value' methods in subclasses\"\"\"\n\n instances = []\n\n def __init__(self, name):\n \"\"\"name: common prefix for all process variables, e.g.\n '14IDB:MyInstrument.'\"\"\"\n self.__name__ = name\n self.instances += [self]\n start_server()\n\n def get_value(self):\n return getattr(self, \"__value__\", None)\n\n def set_value(self, value):\n self.__value__ = value\n\n value = property(get_value, set_value)\n\n def get_connected(self):\n return PV_connected(self.__name__)\n\n connected = property(get_connected)\n\n def __setattr__(self, attr, value):\n \"\"\"Called when x.attr = value is executed.\"\"\"\n ##if DEBUG: debug(\"PV.__setattr__(%r,%r)\" % (attr,value))\n object.__setattr__(self, attr, value)\n if attr == \"value\":\n notify_subscribers_if_changed(self.__name__, value)\n\n def __getattr__(self, attr):\n \"\"\"Called when x.attr is evaluated.\"\"\"\n ##if DEBUG: debug(\"PV.__getattr__(%r)\" % attr)\n value = object.__getattr__(self, attr)\n if attr == \"value\":\n notify_subscribers_if_changed(self.__name__, value)\n return value\n\n\ndef casput(PV_name, value, update=True):\n \"\"\"Create a new process variable with thte given name,\n or update an existing one.\n update: send an updaate to the clients even if the value has not changed.\n \"\"\"\n if DEBUG:\n debug(\"casput(%r,%r)\" % (PV_name, value))\n start_server()\n if not PV_name in PVs:\n PVs[PV_name] = PV_info()\n PV = PVs[PV_name]\n if not CA_equal(PV_value(PV_name), value) or update:\n PV_set_value(PV_name, value, keep_type=False)\n\n\nCAServer_put = casput\n\n\ndef casget(PV_name):\n \"\"\"Current value of a process variable\"\"\"\n start_server()\n return PV_value(PV_name)\n\n\nCAServer_get = casget\n\n\ndef casmonitor(PV_name, writer=None, callback=None):\n \"\"\"Call a function every time a PV changes value.\n writer: function that will be passed a formatted string:\n \"