diff --git "a/2553.jsonl" "b/2553.jsonl" new file mode 100644--- /dev/null +++ "b/2553.jsonl" @@ -0,0 +1,622 @@ +{"seq_id":"152669768","text":"#!/usr/bin/env python\n\nfrom setuptools import setup, find_packages\nimport io\n\nwith open('./requirements.txt') as reqs_txt:\n requirements = [line for line in reqs_txt]\n\nsetup(\n name='py-common',\n version='1.5.0',\n description=\"Python common SDKs for Arxanchain.\",\n long_description=io.open('README.md', encoding='utf-8').read(),\n url='https://github.com/arxanchain/py-common/',\n download_url='https://github.com/arxanchain/py-common/',\n packages=find_packages(),\n platforms='any',\n install_requires=requirements,\n include_package_data=True,\n zip_safe=False,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"295209675","text":"\"\"\"\nTests for `tasks.py`.\n\"\"\"\n\nimport datetime\n\nimport freezegun\nfrom django.test import TestCase\n\nfrom user.backend import models, tasks\nfrom user.backend.tests import factories\n\n\nclass DeactivateUnverifiedUsersTest(TestCase):\n def setUp(self):\n super().setUp()\n self.now = datetime.datetime.now()\n self.older_than = 7\n\n def test_deactivate_unverified_users(self):\n # A user just now registered.\n with freezegun.freeze_time(self.now):\n self.new_user = factories.UnverifiedUserFactory()\n # A user exists from some time ago and is eligible to be deactivated.\n with freezegun.freeze_time(self.now - datetime.timedelta(days=self.older_than + 1)):\n self.old_user = factories.UnverifiedUserFactory()\n\n # Both users are currently unverified.\n assert models.UnverifiedUser.objects.count() == 2\n assert models.DeactivatedUser.objects.count() == 0\n\n # Run job to make the older user deactivated. They will both still remain unverified.\n tasks.deactivate_unverified_users.delay(older_than=self.older_than)\n\n # Confirm both are unverified but one user is now deactivated, and that is the older user.\n assert list(models.UnverifiedUser.objects.order_by(\"created\")) == [self.old_user, self.new_user]\n assert models.DeactivatedUser.objects.get() == self.old_user.user.deactivated\n\n def test_deactivate_unverified_users_none(self):\n \"\"\"No unverified users exist at all and thus nothing happens.\"\"\"\n assert models.UnverifiedUser.objects.count() == 0\n assert models.DeactivatedUser.objects.count() == 0\n tasks.deactivate_unverified_users.delay(older_than=self.older_than)\n assert models.UnverifiedUser.objects.count() == 0\n assert models.DeactivatedUser.objects.count() == 0\n\n def test_deactivate_unverified_users_none_before_cutoff(self):\n \"\"\"No unverified users exist before the cutoff and thus noone is deactivated.\"\"\"\n # A user just now registered.\n with freezegun.freeze_time(self.now):\n self.new_user = factories.UnverifiedUserFactory()\n # A user exists from some time ago, but is still not eligible to be deactivated.\n with freezegun.freeze_time(self.now - datetime.timedelta(days=self.older_than - 1)):\n self.old_but_not_that_old_user = factories.UnverifiedUserFactory()\n\n # Both users are currently unverified.\n assert models.UnverifiedUser.objects.count() == 2\n assert models.DeactivatedUser.objects.count() == 0\n\n # Run job; since both are not eligible to be deactivated, nothing should happen.\n tasks.deactivate_unverified_users.delay(older_than=self.older_than)\n\n # Confirm both are stil unverified and no new deactivated user exists.\n assert list(models.UnverifiedUser.objects.order_by(\"created\")) == [\n self.old_but_not_that_old_user,\n self.new_user,\n ]\n assert models.DeactivatedUser.objects.count() == 0\n\n\nclass DeleteDeactivatedAndUnverifiedUsersTest(TestCase):\n def setUp(self):\n super().setUp()\n self.now = datetime.datetime.now()\n self.older_than = 30\n\n def test_delete_deactivated_and_unverified_users(self):\n with freezegun.freeze_time(self.now):\n self.verified_user = factories.MslmUserFactory()\n self.unverified_user = factories.UnverifiedUserFactory()\n with freezegun.freeze_time(self.now - datetime.timedelta(days=self.older_than + 1)):\n self.deactivated_user = factories.DeactivatedUserFactory()\n self.deactivated_and_unverified_user = factories.DeactivatedUserFactory()\n factories.UnverifiedUserFactory(user=self.deactivated_and_unverified_user.user)\n\n # 1 verified (A), 1 unverified (B), 1 deactivated (C), 1 deactivated and unverified (D).\n assert models.MslmUser.objects.count() == 4\n # B and D.\n assert models.UnverifiedUser.objects.count() == 2\n # C and D.\n assert models.DeactivatedUser.objects.count() == 2\n # D.\n assert models.MslmUser.objects.filter(unverified__isnull=False, deactivated__isnull=False).count() == 1\n\n tasks.delete_deactivated_and_unverified_users.delay(older_than=self.older_than)\n\n # 1 verified (A), 1 unverified (B), 1 deactivated (C).\n assert models.MslmUser.objects.count() == 3\n # B.\n assert models.UnverifiedUser.objects.count() == 1\n # C.\n assert models.DeactivatedUser.objects.count() == 1\n # D is gone.\n assert models.MslmUser.objects.filter(unverified__isnull=False, deactivated__isnull=False).count() == 0\n # Confirming that it is only D that's gone.\n with self.assertRaises(models.MslmUser.DoesNotExist):\n self.deactivated_and_unverified_user.user.refresh_from_db()\n","sub_path":"user/backend/tests/test_tasks.py","file_name":"test_tasks.py","file_ext":"py","file_size_in_byte":4879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"288259340","text":"\"\"\"\n Starts and rallies games\n\"\"\"\n\nimport discord\nimport asyncio\nimport json\nfrom discord.ext import commands\nfrom chowder import chowder_cog\n\nwith open(\"games/game_config.json\", \"r\") as read_file:\n config = json.load(read_file)\n game_config = config[\"games\"]\n\nclass GameCog(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.in_game = False\n self.current_game = None\n\n async def rally(self, ctx, game, initiator):\n \"\"\"Rallies people for a game.\"\"\"\n await self.set_game_status(game)\n\n message = await ctx.send(\"Yo, **\" + initiator.mention + \"** is tryna play **\" + game + \"**. React here with \" + game_config[game][\"emote\"] + \" in the next \" + str(game_config[game][\"wait_time\"]) + \" seconds if you're in\")\n await message.add_reaction(game_config[game][\"emote\"])\n\n # Wait for people to join\n await asyncio.sleep(game_config[game][\"wait_time\"])\n\n # If the game was stopped while rallying, end\n if not self.in_game:\n return\n\n message = await ctx.channel.fetch_message(message.id)\n reaction = discord.utils.find(lambda r: str(r.emoji) == game_config[game][\"emote\"], message.reactions)\n\n players = await reaction.users().flatten()\n players.remove(self.bot.user)\n if initiator not in players:\n players.append(initiator)\n\n if len(players) < game_config[game][\"min_players\"]:\n await ctx.send(\"Dead game, we need at least \" + str(game_config[game][\"min_players\"]) + \" people\")\n await self.clear_game_status()\n return\n\n return players\n\n @commands.group(name=\"play\", brief=\"Initiates a game.\")\n async def play(self, ctx, game):\n if ctx.channel.id not in config[\"channels\"] or ctx.author == self.bot.user:\n return\n\n if not game:\n await ctx.send(\"Uhh hello? What game \" + chowder_cog.get_condescending_name() + \"?\")\n return\n\n games = game_config.keys()\n if game not in games:\n await ctx.send(\"Wtf is \" + game + \"? I only know these games: \" + ', '.join([g for g in games]))\n return\n\n initiator = ctx.author\n start_req = game_config[game][\"start_req\"]\n if initiator.top_role.position < start_req:\n await ctx.send(\"Sorry \" + chowder_cog.get_condescending_name() + \", you're not high enough rank to start a game of \" + game + \". Try getting promoted.\")\n return\n if self.in_game:\n await ctx.send(\"Sorry \" + chowder_cog.get_condescending_name() + \", I'm in a game of \" + self.current_game + \" already\")\n return\n\n players = await self.rally(ctx, game, initiator)\n\n # TODO actually start the game\n\n @commands.command(name=\"stop\", brief=\"Stops game if there's a game in progress.\")\n async def stop(self, ctx):\n if ctx.channel.id not in config[\"channels\"] or ctx.author == self.bot.user:\n return\n\n if not self.in_game:\n await ctx.send(\"Stop what? I'm not doing anything \" + chowder_cog.get_condescending_name())\n return\n \n game = self.current_game\n\n if ctx.author.top_role.position < game_config[game][\"stop_req\"]:\n await ctx.send(\"Sorry \" + chowder_cog.get_condescending_name() + \", you're not high enough stop a game of \" + game + \". Try getting promoted.\")\n return\n\n await ctx.send(\"Rip \" + game)\n await self.clear_game_status()\n\n\n async def clear_game_status(self):\n self.in_game = False\n self.current_game = None\n await self.bot.change_presence(activity=None)\n\n async def set_game_status(self, game):\n self.in_game = True\n self.current_game = game\n await self.bot.change_presence(activity=discord.Game(name=game))\n\ndef setup(bot):\n bot.add_cog(GameCog(bot))","sub_path":"games/game_cog.py","file_name":"game_cog.py","file_ext":"py","file_size_in_byte":3885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"304401360","text":"\"\"\"!\n\\file greektext.py\n\nRepresents a brut greek text object. Greek Text is considered at document level\n\"\"\"\n# simple text object\n\nfrom typing import List, Dict\nimport os\nimport pdb\nimport re\n\nfrom agsearch.textinfo import TextInfo\nfrom agsearch.terminfo import TermInfo\nfrom agsearch.utils import DATA_DIR\nfrom agsearch.utils import PUNCTUATIONS\nfrom agsearch.greekprocessing import GreekProcessing\nfrom greek_accentuation.characters import base\nfrom cltk.stop.greek.stops import STOPS_LIST\nfrom cltk.corpus.greek.alphabet import filter_non_greek\n\n\nclass GreekText:\n \"\"\"!\n \\brief Document object that contains text string\n \"\"\"\n\n def __init__(\n self, chunks: List[str], has_chunks: bool, is_clean: bool, text_id: str\n ):\n \"\"\"!\n \\brief Constructor for text/document object\n \"\"\"\n\n ## chunks of strings attributed to text.\n self.chunks = chunks\n\n ## whether text has a single chunk or multiple chunks\n self.has_chunks = has_chunks\n\n ## whether text is cleaned up before considered as a valid document\n self.is_clean = is_clean\n\n ## a unique identifier for the text in the collection\n self.text_id = text_id\n\n ## term frequency dictionary for document\n self.term_freq: Dict[str, int] = {}\n\n @classmethod\n def get_terms(cls, chunks: List[str], sep: str) -> Dict[str, int]:\n \"\"\"!\n \\brief Obtain term count from given chunks.\n\n \\param chunks a set of text parts.\n \\param sep separator for text inside chunk\n\n We strip each term using sep and for each resulting non empty string we\n increment its slot in terms dictionary\n \"\"\"\n terms: Dict[str, int] = {}\n for chunk in chunks:\n chunk_terms = [t.strip() for t in chunk.split(sep) if t]\n for t in chunk_terms:\n if t in terms:\n terms[t] += 1\n else:\n terms[t] = 1\n return terms\n\n @classmethod\n def from_info(cls, info: TextInfo, chunk_sep: str = \" \"):\n \"\"\"!\n \\brief create text from text info\n\n \\param info info we are going to use for creating text\n \\param chunk_sep we assume that text inside chunk is separated by space\n\n Create a text/document from given text info\n \"\"\"\n text_id = info.text_id\n text_path = os.path.join(DATA_DIR, info.local_path)\n text: str = GreekProcessing.read_text(text_path)\n greek_processor = GreekProcessing(text)\n text = greek_processor.clean_text(text)\n terms: Dict[str, int] = {}\n chunks: List[str] = []\n if info.has_chunks:\n chunks = text.split(info.chunk_separator)\n chunks = [greek_processor.clean_chunk(c) for c in chunks if c]\n terms = cls.get_terms(chunks, chunk_sep)\n else:\n chunks = [text]\n chunks = [greek_processor.clean_chunk(c) for c in chunks if c]\n terms = cls.get_terms(chunks, chunk_sep)\n #\n text_obj = Text(\n chunks=chunks, has_chunks=info.has_chunks, is_clean=True, text_id=text_id\n )\n text_obj.term_freq = terms\n return text_obj\n\n def to_doc_counts(self) -> Dict[str, Dict[str, int]]:\n \"\"\"!\n \\brief obtain doc per term count from term frequency dict\n\n From term frequency dictionary which contains term frequencies per\n document, we obtain document per term count.\n \"\"\"\n term_doc_id_counts: Dict[str, Dict[str, int]] = {}\n for term, count in self.term_freq.items():\n doc_id_count = {self.text_id: count}\n term_doc_id_counts[term] = doc_id_count\n return term_doc_id_counts\n","sub_path":"agsearch/greektext.py","file_name":"greektext.py","file_ext":"py","file_size_in_byte":3743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"426332252","text":"\"\"\"\nPGP\n\n\"\"\"\n\nimport re\n\nimport canopy\nimport gnupg\nimport web\n\n__all__ = [\"get_keys\", \"get_key\"]\n\n\napp, kv, sql, view = canopy.branch(__name__, __doc__, keyid=r\"[\\dA-F]{16}\")\nkv.define({\"keys:{keyid}\": \"hash\"})\ngpg = gnupg.GPG(gnupghome=str(canopy.tree / \"trunk/security/pgp\"))\ngpg.encoding = \"utf-8\"\n\n\ndef get_keys():\n \"\"\"\"\"\"\n keys = {}\n for key in gpg.list_keys():\n key[\"name\"], key[\"email\"] = re.fullmatch(r\"(.+) <(.+)>\",\n key[\"uids\"][0]).groups()\n # key[\"name\"], key[\"modifier\"], key[\"email\"] = \\\n # re.fullmatch(r\"(.+) \\((.+)\\) <(.+)>\", key[\"uids\"][0]).groups()\n keys[key[\"keyid\"]] = key\n return keys\n\n\ndef get_key(keyid):\n \"\"\"\"\"\"\n return gpg.export_keys(keyid)\n\n\n@app.route(r\"\")\nclass PGP:\n\n def GET(self):\n return view.index(self.delegate(Sign), self.delegate(Keys))\n\n\n@app.route(r\"sign\")\nclass Sign:\n\n private = True\n\n def GET(self):\n payload = web.form(payload=None).payload\n signature = None\n if payload:\n signature = gpg.sign(payload)\n return view.sign(payload, signature, get_keys())\n\n\n@app.route(r\"keys\")\nclass Keys:\n\n def GET(self):\n return view.keys(get_keys())\n\n def POST(self):\n form = web.form(\"key_type\", \"key_length\")\n details = {\"name_real\": canopy.kvdb[\"name\"],\n \"name_comment\": canopy.kvdb[\"host\"],\n \"name_email\": canopy.epiphytes[\"Email\"].get_address(),\n \"key_type\": form.key_type,\n \"key_length\": int(form.key_length)}\n keyid = gpg.gen_key(gpg.gen_key_input(**details)) # type: gnupg.GenKey\n raise web.Created(view.key_created(keyid),\n \"/security/pgp/keys/{}\".format(keyid))\n\n\n@app.route(r\"keys/{keyid}\")\nclass Key:\n\n def GET(self):\n return view.key(get_keys()[self.keyid],\n self.delegate(KeyData, shift_headers=False))\n\n\n@app.route(r\"keys/{keyid}.asc\")\nclass KeyData:\n\n public = True\n\n def GET(self):\n return get_key(self.keyid)\n\n\n# @app.route(r\"lookup\")\n# class Lookup:\n#\n# def GET(self):\n# op = web.form(\"op\").op.strip(\"_\")\n# try:\n# handler = getattr(self, op)\n# except AttributeError:\n# raise web.BadRequest(\"operation `{}` not supported\".format(op))\n# return handler()\n#\n# def get():\n# \"\"\"\n# The \"get\" operation requests keys from the keyserver. A string that\n# specifies which key(s) to return is provided in the \"search\"\n# variable.\n#\n# The response to a successful \"get\" request is a HTTP document\n# containing a keyring as specified in RFC-2440 [4], section 11.1, and\n# ASCII armored as specified in section 6.2.\n#\n# The response may be wrapped in any HTML or other text desired, except\n# that the actual key data consisting of an initial line break, the\n# \"-----BEGIN PGP PUBLIC KEY BLOCK-----\" header, the armored key data\n# itself, the \"-----END PGP PUBLIC KEY BLOCK-----\" header, and a final\n# line break MUST NOT be modified from the form specified in [4].\n#\n# If no keys match the request, the keyserver should return an\n# appropriate HTTP error code such as 404 (\"Not Found\").\n#\n# \"\"\"\n# search = flask.request.args.get('search', None)\n# if search is None:\n# resp = flask.make_response(\"Missing required search parameter\",\n# 500)\n# return resp\n#\n# search = clean_search(search)\n#\n# # Require that the search term is a fingerprint/key id\n# # (filter out fulltext matches against uid fields for this method).\n# try:\n# match = ctx.get_key(search)\n# except gpgme.GpgmeError:\n# match = None\n#\n# if match is None:\n# return flask.make_response(\"No key matching \"\n# \"search={}\".format(search), 404)\n#\n# keydata = BytesIO()\n# ctx.export(search, keydata)\n#\n# if keydata:\n# resp = flask.make_response(keydata.getvalue(), 200)\n# resp.mimetype=\"text/plain\"\n# return resp\n#\n# return flask.make_response(\"No key matching search=%s\" % (search),\n# 404)\n#\n# def index():\n# \"\"\"\n# The \"index\" operation requests a list of keys on the keyserver that\n# match the text or key ID in the \"search\" variable. Historically, the\n# \"index\" operation returned a human readable HTML document containing\n# links for each found key, but this is not required.\n#\n# If the \"index\" operation is not supported, the keyserver should\n# return an appropriate HTTP error code such as 501 (\"Not\n# Implemented\").\n#\n# \"\"\"\n# search = flask.request.args.get('search', None)\n# if search is None:\n# resp = flask.make_response(\"Missing required argument: search\",\n# 400)\n# return resp\n#\n# search = clean_search(search)\n#\n# if len(search) < 4:\n# resp = flask.make_response(\"Search must be at least \"\n# \"four characters\", 500)\n# return resp\n#\n# matches = []\n# for k in ctx.keylist():\n# match_uid = False\n# for uid in k.uids:\n# if search in uid.uid.upper():\n# match_uid = True\n# break\n#\n# for subkey in k.subkeys:\n# if match_uid or search in subkey.fpr:\n# matches.append(str(subkey.fpr))\n#\n# if matches:\n# resp = flask.make_response(\"\\n\".join(matches), 200)\n# resp.mimetype=\"text/plain\"\n# return resp\n#\n# return flask.make_response(\"No keys matching search \"\n# \"request: {}\".format(search), 404)\n#\n# @staticmethod\n# def vindex():\n# \"\"\"\n# The `vindex` operation is similar to `index` in that it provides a\n# list of keys on the keyserver that match the text of key ID in the\n# `search` variable. Historically, a `vindex` response was the same\n# as `index` with the addition of showing the signatures on each key,\n# but this is not required.\n#\n# \"\"\"\n# raise web.NotImplemented(\"VIndex search is not supported.\")\n#\n#\n# @app.route(r\"add\")\n# class Add:\n#\n# def POST(self):\n# \"\"\"\n# store the urlencoded ASCII armored keyring(s) provided in `keytext`\n#\n# \"\"\"\n# keytext = web.form(\"keytext\").keytext\n# gpg.import_keys(keytext)\n# raise web.Created(\"key(s) added\")\n","sub_path":"canopy_security/pgp/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"466667197","text":"import bpy\r\n\r\n\r\nclass HOPS_OT_MOD_Weighted_Normal(bpy.types.Operator):\r\n bl_idname = \"hops.mod_weighted_normal\"\r\n bl_label = \"Add Weighted Normal Modifier\"\r\n bl_options = {'REGISTER', 'UNDO'}\r\n bl_description = \"\"\"LMB - Add Weighted Normal Modifier\r\nLMB + CTRL - Add new Weighted Normal Modifier\r\n\r\n\"\"\"\r\n\r\n @classmethod\r\n def poll(cls, context):\r\n selected = context.selected_objects\r\n for obj in selected:\r\n return getattr(obj, \"type\", \"\") == \"MESH\"\r\n\r\n def invoke(self, context, event):\r\n for object in context.selected_objects:\r\n if event.ctrl:\r\n self.add_normal_modifier(object)\r\n else:\r\n if not self.normal_modifiers(object):\r\n self.add_normal_modifier(object)\r\n return {\"FINISHED\"}\r\n\r\n @staticmethod\r\n def normal_modifiers(object):\r\n return [modifier for modifier in object.modifiers if modifier.type == \"WEIGHTED_NORMAL\"]\r\n\r\n def add_normal_modifier(self, object):\r\n object.modifiers.new(name=\"Weighted Normal\", type=\"WEIGHTED_NORMAL\")\r\n object.modifiers[\"Weighted Normal\"].keep_sharp = True\r\n","sub_path":"All_In_One/addons/HOps/operators/modifiers/weighted_normal.py","file_name":"weighted_normal.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"224761760","text":"import evolutionGen\nimport Morpion\nfrom random import *\nimport numpy\nimport time\nimport copy\nimport matplotlib.pyplot as plt\n# Just disables the warning, doesn't enable AVX/FMA\n#import os\n#os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n\nentree = numpy.ndarray(shape=(4, 1),\n dtype=numpy.float32)\n\nsortie = numpy.ndarray(shape=(4, 1),\n dtype=numpy.float32)\n\nentree[0] = [1]\nentree[1] = [0.5]\nentree[2] = [0]\nentree[3] = [0.1]\n#entree[4] = [0.8,0.4]\n#entree[5] = [0.12,0.56]\n\nsortie[0] = [0.5]\nsortie[1] = [0.5]\nsortie[2] = [1]\nsortie[3] = [0.8]\n#sortie[4] = [0.8,0.4]\n#sortie[5] = [0.12,0.56]\n\n#Init \ntest = evolutionGen.evolutionGen(20,9,9)\nmonMorpion = Morpion.Morpion()\n#Série de tests\n\n\n#Test apprentissage règles\nlistePieceOutput = []\nlistePieceInput = []\n\n#listeTest = []\n\nactionIASimulee = numpy.ndarray(shape=(9, 1),\n dtype=numpy.float32)\n\nlossValues = []\ncategorical_accuracyValues = []\n\nactionIASimulee = numpy.zeros(9)\n#test.listeIA[0].reseau.load_weights('morpionIA_1.h5')\nif(False):\n \n monMorpion.simulationPartie(listePieceInput,listePieceOutput,3000)\n for i in range(200):\n #On feed l'IA avec un des move possibles\n history = test.listeIA[0].reseau.fit(numpy.asarray(listePieceInput),numpy.asarray(listePieceOutput),epochs=10,verbose=1)\n\n # Plot training & validation accuracy values\n fig, ax1 = plt.subplots()\n \n ax2 = ax1.twinx()\n lossValues = lossValues + (copy.copy(history.history['loss']))\n categorical_accuracyValues = categorical_accuracyValues + (copy.copy(history.history['categorical_accuracy']))\n ax1.plot(lossValues, 'g-')\n ax2.plot(categorical_accuracyValues, 'b-')\n ax1.set_xlabel('Epochs')\n ax1.set_ylabel('loss')\n ax2.set_ylabel('categorical_accuracy')\n plt.savefig('Train_.png')\n plt.close()\n\n\n test.listeIA[0].reseau.save_weights('morpionIA_1.h5')\n\n #On test l'IA\n result = test.listeIA[0].reseau.predict(numpy.asarray(listePieceInput))\n\n cnt_error = 0\n result = result.tolist()\n #listePieceOutput = listePieceOutput.tolist()\n\n for k in range(len(listePieceInput)):\n temp_1 = result[k]\n temp_2 = listePieceOutput[k].tolist()\n if(temp_1.index(max(temp_1)) != temp_2.index(max(temp_2))):\n cnt_error+=1\n\n print(\"Error :\" + str(cnt_error) + \" / \" + str(len(listePieceInput)) + \" soit \" + str( (cnt_error/len(listePieceInput)) * 100.0) + \"% d'erreur\")\n\n\ncntScoreIA_old = 0\nwhile(1):\n\n #t_start = time.time()\n\n #for i in range(entree.shape[0]-1):\n\n # test.result(entree[i],sortie[i])\n \n # test.tracerCourbe()\n\n\n \n\n for J1 in range(len(test.listeIA)):\n for J2 in range(len(test.listeIA)):\n #On check si les joueurs sont bien différents\n if(J1 != J2):\n #La partie ne s'arrête que quand le flag est passé à True\n while(monMorpion.finPartie == False):\n #Tour J1\n result = monMorpion.tourJ_UN(test.listeIA[J1].result(numpy.asarray(monMorpion.getListePionJ_UN()))) #Un mauvais déplacement est compté négativement\n if(result == -2):\n test.listeIA[J1].score += -20\n monMorpion.finPartie = False\n #On passe à la partie suivante\n break\n #partie gagnée\n elif(result == 1):\n test.listeIA[J1].score += 100\n #Partie perdue pour le J2\n test.listeIA[J2].score += -10\n else:\n #Chaque tour bien joué est récompensé\n test.listeIA[J1].score += 10\n #Tour J2\n result = monMorpion.tourJ_DEUX(test.listeIA[J2].result(numpy.asarray(monMorpion.getListePionJ_DEUX()))) #Un mauvais déplacement est compté négativement\n if(result == -2):\n test.listeIA[J2].score += -20\n monMorpion.finPartie = False\n #On passe à la partie suivante\n break\n #partie gagnée\n elif(result == 1):\n test.listeIA[J2].score += 100\n #Partie perdue pour le J1\n test.listeIA[J1].score += -10\n else:\n #Chaque tour bien joué est récompensé\n test.listeIA[J2].score += 10\n #Partie suivante\n monMorpion.initPartie()\n\n if(test.newGen() == -1):\n break\n #save meilleure IA\n test.listeMeilleurIA[0].reseau.save_weights('morpionBestIA.h5')\n\n #On teste notre meilleure IA\n cntVictoireIA = 0\n cntVictoireJ2 = 0\n cntMauvaisDeplacement = 0\n cntBonDeplacement = 0\n #On save les moves\n listeMoveJ1J2 = []\n cnt = 1\n for i in range(100): #On fait 10 parties\n #La partie ne s'arrête que quand le flag est passé à True\n while(monMorpion.finPartie == False):\n #Tour J1\n result = monMorpion.tourJ_UN(copy.copy(test.listeIA[0].result(numpy.asarray(monMorpion.getListePionJ_UN())))) #Un mauvais déplacement est compté négativement\n listeMoveJ1J2.append(copy.copy(monMorpion.getListePionJ_UN()))\n if(result == -2):\n cntMauvaisDeplacement += 1\n monMorpion.finPartie = False\n #On passe à la partie suivante\n break\n #partie gagnée\n elif(result == 1):\n cntVictoireIA += 1\n else:\n cntBonDeplacement += 1\n\n #Tour J2\n\n move = monMorpion.getAllMovePossible()\n\n #Dans le cas où aucuns déplacement n'est possible\n if(len(move) == 0):\n break\n moveChoisi = move[randint(0,len(move)-1)]\n #On max l'index du move\n actionIASimulee[moveChoisi] = 1.0\n #On fait le move\n result = monMorpion.tourJ_DEUX(copy.copy(actionIASimulee))\n listeMoveJ1J2.append(copy.copy(monMorpion.getListePionJ_UN()))\n\n if(result == 1):\n cntVictoireJ2 += 1\n #On min l'index du move\n actionIASimulee[moveChoisi] = 0.0\n\n #Fin de partie\n #Partie suivante\n monMorpion.enregistrerPartie(numpy.asarray(listeMoveJ1J2),\"Partie_.txt\",cnt)\n listeMoveJ1J2.clear()\n cnt += 1\n monMorpion.initPartie()\n cntScoreIA = (100 * cntVictoireIA) + cntBonDeplacement - (cntMauvaisDeplacement * 1) \n if(cntScoreIA_old < cntScoreIA):\n print(\"Meilleure IA !!!!\")\n cntScoreIA_old = copy.copy(cntScoreIA)\n test.listeIA[0].score = copy.copy(test.listeMeilleurScore[0]+10)\n test.listeMeilleurIA.insert(0,copy.copy(test.listeIA[0]))\n test.listeIA[0].score = 0\n test.listeMeilleurIA.pop()\n test.listeMeilleurScore.insert(0,copy.copy(test.listeMeilleurScore[0]+10))\n test.listeMeilleurScore.pop()\n\n test.listeIA[0].reseau.save_weights('morpionBestIA_TEST.h5')\n\n\n #On affiche les résultats\n print(\"Victoire IA :\" + str(cntVictoireIA) + \"/100\" + \" Victoire J2 :\" + str(cntVictoireJ2) + \"/100\" + \" Parties nulles : \" + str(100-(cntVictoireIA+cntVictoireJ2)))\n print(\"Bon move : \" + str(cntBonDeplacement) + \"/\" + str(cntBonDeplacement+cntMauvaisDeplacement) + \" Mauvais move :\" + str(cntMauvaisDeplacement) )\n test.tracerCourbe()\n\n \n\n #t_stop = time.time()\n #delta_time = t_stop - t_start\n #print(\"Time_tot : \" + str(delta_time) + \"\\n\")\n\n","sub_path":"Resultats/PythonApplicationEvolutionGen.py","file_name":"PythonApplicationEvolutionGen.py","file_ext":"py","file_size_in_byte":7864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"583474402","text":"from importing_modules import *\napp = Flask(__name__)\n\nglobal players, rooms\n\nplayers = []\nrooms = {}\nroom_json = json.load(open(\"template_room.json\"))\nuser_json = json.load(open(\"template_user.json\"))\n\n@app.route('/')\ndef root():\n return(\"Project root\")\n\n@app.route('/get-user-id', methods=['POST'])\ndef get_user_id():\n while True:\n player_id = random.randint(0, 100)\n if player_id not in players:\n players.append(player_id)\n else: break\n return(jsonify(\n USER_ID=player_id\n))\n\n@app.route('/create', methods=['POST'])\ndef create_root():\n data = request.args\n if (not data or not data['user_id']): abort(400, 'User id not found')\n else: user_id = data['user_id']\n while True:\n room_id = random.randint(0, 100)\n if room_id not in rooms.keys():\n rooms[room_id] = dict(room_json)\n rooms[room_id]['id'] = room_id\n break # Create function to enter new room\n return(jsonify(\n rooms[room_id]\n ))\napp.run()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"} +{"seq_id":"247755361","text":"import sys, getopt,platform\n\nclass Colours:\n normal = u\"\\u001b[0m\"\n \n def __init__(self):\n g = []\n for i in range(0, 16):\n for j in range(0, 16):\n code = str(i * 16 + j)\n ll = u\"\\u001b[38;5;\" + code + \"m\"\n g.append(ll)\n for i in range(0, 16):\n for j in range(0, 16):\n code = str(i * 16 + j)\n ll = u\"\\u001b[48;5;\" + code + \"m\"\n g.append(ll)\n self.all_colours = g\n dict1 = {}\n for x in self.all_colours:\n i+=1\n dict1[i] = x\n self.colours = dict1\n ms = {\n \"green\":dict1[62],\n \"red\":dict1[212],\n \"pink\":dict1[180],\n \"white\":dict1[31]\n }\n if platform.system() == \"Windows\":\n for x in self.colours.items():\n self.colours[x] = \"\"\n self.normal = \"\"\n def colours_help(self):\n dict1 = {}\n print(\"--------------------------------\\nUse The Responsible Number:-\\n--------------------------------\")\n for i,x in self.colours.items():\n dict1[i] = x\n sys.stdout.write(x+str(i).ljust(4)+self.normal)\n sys.stdout.write(self.normal+\"\\n\")\n def colour(self,colour,text,**kwargs):\n cc = \"\"\n for key,value in kwargs.items():\n if key == \"second\":cc = self.colours[value].replace(\" \",\"\")\n else:continue\n if colour > max([x for x,y in self.colours.items()]) or colour < 1:\n raise Exception(self.colours[176]+\"Wrong Colour code\\nPlease Execute: python3 -m Colours -colour\"+self.normal)\n \n return cc+self.colours[colour]+text+self.normal\n\nif __name__ == \"__main__\":\n l = sys.argv[1:]\n if len(l)<1:print(Colours().colour(17,\"Enter -h or --help to get more info\\nEnter -c or --colours to list colours and Responsible number\"))\n \n try:\n opts, args = getopt.getopt(l,\"ch\")\n except getopt.GetoptError:\n print(Colours().colour(17,\"Enter -h or --help to get more info\\nEnter -c or --colours to list colours and Responsible number\"))\n sys.exit(2)\n for opt,arg in opts:\n \n if opt in (\"-c\",\"--colours\",):\n Colours().colours_help()\n if opt in (\"-h\",\"--help\"):\n print(f'''\n{Colours().colour(233,\"Usage(1):-\")} {Colours().colour(170,\"python3 -m Colours