diff --git "a/1797.jsonl" "b/1797.jsonl" new file mode 100644--- /dev/null +++ "b/1797.jsonl" @@ -0,0 +1,1166 @@ +{"seq_id":"37467004270","text":"from django.urls import path, include\n\nfrom main.views import base_view, new_question_view, \\\n tag_questions_view, settings_view, hot_questions, login, logout_view, QuestionView\n\napp_name = 'main'\nurlpatterns = [\n path(r'', base_view),\n path(r'hot', hot_questions),\n path(r'new_question/', new_question_view),\n path(r'question//', QuestionView.as_view(), name='question'),\n path(r'tag', tag_questions_view),\n path(r'settings', settings_view),\n path(r'signin', login),\n path(r'logout/', logout_view),\n\n]\n","repo_name":"MurMurt/TechnoPark_Web","sub_path":"main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"17568165053","text":"\"\"\" Afficher une pyramide \"\"\"\n\n# Afficher un escalier constitué d'un caractère et d'un nombre d'étages donné en paramètre.\n\nimport sys\n\ndef build_pyramid(char, rows):\n\n space = 2 * rows - 2 # used for number of spaces\n\n for i in range(0, rows):\n for j in range(0, space):\n print(end=\" \")\n \n space = space - 2 # decrement space value for each iteration\n \n for j in range(0, i +1):\n display = \"%s \" % (char) \n print(display, end=\" \") # print the stars\n print(\"\")\n\n\ntry:\n symbol = sys.argv[1]\n line = int(sys.argv[2])\nexcept:\n sys.exit(\" ERROR \")\n\n\nbuild_pyramid(symbol, line)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# MY OWN BUILD, almost complete...\n\"\"\"\ndef printSymb(char, row):\n\n #symList = list(char.split(\" \"))\n #print(symList)\n \n #################################################################\n \n # blank spaces...\n \n #################################################################\n baseList = []\n baseList.append(char)\n \n listOfList = []\n listOfList.append(baseList)\n #print(listOfList)\n \n basicAdd = 3\n rowConter = 1\n\n while rowConter != row:\n\n newList = []\n basicAdd += 2\n newList.append(char*basicAdd)\n listOfList.append(newList)\n rowConter += 1\n\n if rowConter == row:\n print(*listOfList, sep='\\n')\n print(\"END\")\n break\n else:\n continue\n\n\n# print the symbol but NOT as pyramid AND arg problems for row numbers\ndef printSymbols(char, row):\n\n symList = list(char.split(\" \"))\n #print(symList)\n\n basicAdd = 3\n rowConter = 1\n\n while rowConter != row:\n\n basicAdd += 2\n symList.append(char*basicAdd)\n rowConter += 1\n\n if rowConter == row:\n print(*symList, sep='\\n')\n print(\"END\")\n break\n else:\n continue\n\n\nsymbol = sys.argv[1]\nline = int(sys.argv[2])\n\n#printSymbols(symbol, line)\nprintSymb(symbol, line)\"\"\"\n","repo_name":"NN-Guillaume/Air_level","sub_path":"air11.py","file_name":"air11.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"34374545213","text":"\"\"\"\nChecks nodes and updates DNS records accordingly\n\nIt doesn't actually do any healthchecks itself, it just updates DNS records for\nall cluster worker nodes. Each worker node also gets an AWS Route53 healthcheck\nwhich does the actual healthcheck and removes it from DNS if it fails. The\nhealthchecks check cwm-worker-ingress /healthz path, so if the ingress stops\nresponding the node is removed from DNS.\n\nIn addition to the DNS healthchecks, the cwm-worker-ingress checks redis key\nnode:healthy, if key is missing the /healthz path returns an error. nodes_checker\nupdates this redis key to true for all worker nodes and to false for any nodes\nwhich are not currently listed as worker nodes - so nodes which are removed\nwill instantly stop serving.\n\"\"\"\nfrom cwm_worker_operator import config\nfrom cwm_worker_operator.daemon import Daemon\n\n\ndef set_node_healthy_keys(domains_config, deployments_manager):\n healthy_node_name_ips = {}\n # set healthy redis key of healthy nodes - so that ingress will report them as healthy\n for node in deployments_manager.iterate_cluster_nodes():\n if node['is_worker']:\n healthy_node_name_ips[node['name']] = node['public_ip']\n domains_config.set_node_healthy(node['name'], True)\n # del healthy redis key for nodes which have a key but are not in list of healthy nodes\n for node_name in domains_config.iterate_healthy_node_names():\n if node_name not in healthy_node_name_ips:\n domains_config.set_node_healthy(node_name, False)\n return healthy_node_name_ips\n\n\ndef update_dns_records(deployments_manager, healthy_node_name_ips):\n dns_healthchecks = {}\n dns_records = {}\n # collect node names of existing dns healthchecks / records\n # delete records which need updating for recreation\n update_required_healthcheck_node_names = set()\n update_required_records_node_names = set()\n for dns_healthcheck in deployments_manager.iterate_dns_healthchecks():\n dns_healthchecks[dns_healthcheck['node_name']] = {'id': dns_healthcheck['id'], 'ip': dns_healthcheck['ip']}\n if dns_healthcheck['node_name'] in healthy_node_name_ips and dns_healthcheck['ip'] != healthy_node_name_ips[\n dns_healthcheck['node_name']]:\n deployments_manager.delete_dns_healthcheck(dns_healthcheck['id'])\n update_required_healthcheck_node_names.add(dns_healthcheck['node_name'])\n for dns_record in deployments_manager.iterate_dns_records():\n dns_records[dns_record['node_name']] = {'id': dns_record['id'], 'ip': dns_record['ip']}\n if dns_record['node_name'] in update_required_healthcheck_node_names or (dns_record['node_name'] in healthy_node_name_ips and dns_record['ip'] != healthy_node_name_ips[dns_record['node_name']]):\n deployments_manager.delete_dns_record(dns_record['id'])\n update_required_records_node_names.add(dns_record['node_name'])\n # set dns healthcheck and record for nodes which are in list of healthy nodes but have a missing healthcheck or record\n for node_name, node_ip in healthy_node_name_ips.items():\n if node_name not in dns_healthchecks or node_name in update_required_healthcheck_node_names:\n healthcheck_id = deployments_manager.set_dns_healthcheck(node_name, node_ip)\n else:\n healthcheck_id = dns_healthchecks[node_name]['id']\n if node_name not in dns_records or node_name in update_required_records_node_names:\n deployments_manager.set_dns_record(node_name, node_ip, healthcheck_id)\n return dns_healthchecks, dns_records\n\n\ndef delete_dns_records(deployments_manager, healthy_node_name_ips, dns_healthchecks, dns_records):\n # delete dns records for nodes which are not in list of healthy nodes\n for node_name, dns_record in dns_records.items():\n if node_name not in healthy_node_name_ips:\n deployments_manager.delete_dns_record(dns_record['id'])\n # delete dns healthcheck for nodes which are not in list of healthy nodes\n for node_name, healthcheck in dns_healthchecks.items():\n if node_name not in healthy_node_name_ips:\n deployments_manager.delete_dns_healthcheck(healthcheck['id'])\n\n\ndef run_single_iteration(domains_config, deployments_manager, **_):\n healthy_node_name_ips = set_node_healthy_keys(domains_config, deployments_manager)\n dns_healthchecks, dns_records = update_dns_records(deployments_manager, healthy_node_name_ips)\n delete_dns_records(deployments_manager, healthy_node_name_ips, dns_healthchecks, dns_records)\n\n\ndef start_daemon(once=False, domains_config=None, deployments_manager=None):\n Daemon(\n name=\"nodes_checker\",\n sleep_time_between_iterations_seconds=config.NODES_CHECKER_SLEEP_TIME_BETWEEN_ITERATIONS_SECONDS,\n domains_config=domains_config,\n run_single_iteration_callback=run_single_iteration,\n deployments_manager=deployments_manager\n ).start(\n once=once,\n with_prometheus=False\n )\n","repo_name":"CloudWebManage/cwm-worker-operator","sub_path":"cwm_worker_operator/nodes_checker.py","file_name":"nodes_checker.py","file_ext":"py","file_size_in_byte":4986,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"36602013252","text":"# Name That Permutation\r\n\r\nfact = [1]\r\n\r\nif __name__ == '__main__':\r\n for i in range(1, 51):\r\n fact.append(fact[i-1] * i)\r\n while True:\r\n try:\r\n n, k = map(int, input().split())\r\n ans = [i + 1 for i in range(n)]\r\n while True:\r\n if n == 1:\r\n print(ans[0])\r\n break\r\n print(ans.pop(k // fact[n-1]), end=' ')\r\n k %= fact[n-1]\r\n n -= 1\r\n except EOFError:\r\n break","repo_name":"mohsendb7008/Online-Judge-Solutions","sub_path":"Kattis/namethatpermutation.py","file_name":"namethatpermutation.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"9712138327","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport os\nimport sys\n\nfrom unittest import loader, TextTestRunner\n\ntest_path = os.path.join(os.path.dirname(__file__), 'tests')\ntest_loader = loader.TestLoader()\n\nif __name__ == \"__main__\":\n\n runner = TextTestRunner(verbosity=2)\n test_result = runner.run(test_loader.discover(test_path)).wasSuccessful()\n\n if test_result is False:\n sys.exit(1)\n else:\n sys.exit(0)\n","repo_name":"alice1017/coadlib","sub_path":"testrunner.py","file_name":"testrunner.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"23242321926","text":"import os\nimport sys\nimport unittest\n\npkg_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) # noqa\nsys.path.insert(0, pkg_root) # noqa\n\nfrom dss.storage.identifiers import (ObjectIdentifier, FileFQID, BundleTombstoneID, BundleFQID, CollectionFQID,\n CollectionTombstoneID, BUNDLE_PREFIX, FILE_PREFIX, COLLECTION_PREFIX)\nfrom tests.infra import testmode\n\n\n@testmode.standalone\nclass TestObjectIdentifier(unittest.TestCase):\n\n def test_to_str(self):\n uuid = \"0ddba11-0000-4a6b-8f0d-a7d2105c23be\"\n version = \"2017-12-05T235728.441373Z\"\n tests = [BundleFQID, FileFQID, CollectionFQID]\n for identity in tests:\n with self.subTest(identity.__name__):\n self.assertEquals(\n str(identity(uuid=uuid, version=version)),\n f\"{uuid}.{version}\"\n )\n\n tests = [CollectionTombstoneID, BundleTombstoneID]\n for identity in tests:\n with self.subTest(identity.__name__):\n self.assertEquals(\n str(identity(uuid=uuid, version=version)),\n f\"{uuid}.{version}.dead\"\n )\n self.assertEquals(\n str(identity(uuid=uuid, version=None)),\n f\"{uuid}.dead\"\n )\n\n def test_from_key(self):\n \"\"\"\n Test that the from key method correctly returns the right types of identifiers\n \"\"\"\n uuid = \"ca11ab1e-0000-4a6b-8f0d-a7d2105c23be\"\n version = \"2017-12-05T235728.441373Z\"\n self.assertEquals(\n BundleFQID(uuid, version),\n ObjectIdentifier.from_key(f\"{BUNDLE_PREFIX}/{uuid}.{version}\"),\n )\n self.assertEquals(\n FileFQID(uuid, version),\n ObjectIdentifier.from_key(f\"{FILE_PREFIX}/{uuid}.{version}\"),\n )\n self.assertEquals(\n CollectionFQID(uuid, version),\n ObjectIdentifier.from_key(f\"{COLLECTION_PREFIX}/{uuid}.{version}\"),\n )\n self.assertEquals(\n CollectionTombstoneID(uuid, version),\n ObjectIdentifier.from_key(f\"{COLLECTION_PREFIX}/{uuid}.{version}.dead\"),\n )\n self.assertEquals(\n BundleTombstoneID(uuid, version),\n ObjectIdentifier.from_key(f\"{BUNDLE_PREFIX}/{uuid}.{version}.dead\"),\n )\n self.assertRaises(\n ValueError,\n lambda: ObjectIdentifier.from_key(f\"{BUNDLE_PREFIX}/trash\"),\n )\n self.assertRaises(\n ValueError,\n lambda: ObjectIdentifier.from_key(f\"trash/{uuid}.{version}.dead\"),\n )\n\n def test_to_key(self):\n uuid = \"0ddba11-0000-4a6b-8f0d-a7d2105c23be\"\n version = \"2017-12-05T235728.441373Z\"\n tests = [(BundleFQID, BUNDLE_PREFIX), (FileFQID, FILE_PREFIX), (CollectionFQID, COLLECTION_PREFIX)]\n for identity, prefix in tests:\n with self.subTest(identity.__name__):\n self.assertEquals(\n identity(uuid=uuid, version=version).to_key(),\n f\"{prefix}/{uuid}.{version}\"\n )\n\n tests = [(CollectionTombstoneID, COLLECTION_PREFIX), (BundleTombstoneID, BUNDLE_PREFIX)]\n for identity, prefix in tests:\n with self.subTest(identity.__name__):\n self.assertEquals(\n identity(uuid=uuid, version=version).to_key(),\n f\"{prefix}/{uuid}.{version}.dead\"\n )\n self.assertEquals(\n identity(uuid=uuid, version=None).to_key(),\n f\"{prefix}/{uuid}.dead\"\n )\n\n def test_to_key_prefix(self):\n uuid = \"0ddba11-0000-4a6b-8f0d-a7d2105c23be\"\n version = \"2017-12-05T235728.441373Z\"\n self.assertEquals(\n BundleFQID(uuid=uuid, version=version).to_key_prefix(),\n f\"{BUNDLE_PREFIX}/{uuid}.{version}\"\n )\n self.assertEquals(\n BundleFQID(uuid=uuid, version=None).to_key_prefix(),\n f\"{BUNDLE_PREFIX}/{uuid}.\"\n )\n\n def test_tombstone_is_fully_qualified(self):\n uuid = \"0ddba11-0000-4a6b-8f0d-a7d2105c23be\"\n version = \"2017-12-05T235728.441373Z\"\n self.assertTrue(\n BundleTombstoneID(uuid=uuid, version=version).is_fully_qualified(),\n )\n self.assertFalse(\n BundleTombstoneID(uuid=uuid, version=None).is_fully_qualified(),\n )\n\n def test_tombstone_to_bundle_fqid(self):\n uuid = \"0ddba11-0000-4a6b-8f0d-a7d2105c23be\"\n version = \"2017-12-05T235728.441373Z\"\n self.assertTrue(\n BundleTombstoneID(uuid=uuid, version=version).to_fqid(),\n BundleFQID(uuid=uuid, version=version),\n )\n self.assertRaises(\n ValueError,\n lambda: BundleTombstoneID(uuid=uuid, version=None).to_fqid(),\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"HumanCellAtlas/data-store","sub_path":"tests/test_object_identifier.py","file_name":"test_object_identifier.py","file_ext":"py","file_size_in_byte":4965,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"40"} +{"seq_id":"4445556790","text":"class Solution(object):\r\n def maxSlidingWindow(self, nums, k):\r\n \"\"\"\r\n :type nums: List[int]\r\n :type k: int\r\n :rtype: List[int]\r\n \"\"\"\r\n if not nums: return []\r\n window,res=[],[]\r\n #window stores indices,and res stores result\r\n for i,x in enumerate(nums):\r\n if i>=k and window[0]<=i-k:\r\n window.pop(0)\r\n while window and nums[window[-1]]<=x:\r\n window.pop()\r\n window.append(i)\r\n if i>=k-1:\r\n res.append(nums[window[0]])\r\n return res","repo_name":"Sprinter1999/Algorithm","sub_path":"LeetCode/Leetcode-2019Summer/Leetcode239(sliding max).py","file_name":"Leetcode239(sliding max).py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"40"} +{"seq_id":"41880005609","text":"'''\nCreated on Jun 6, 2013\n\n@author: netzsooc\n'''\nfrom porterstemmer import Stemmer\n\nstop = [\"the\", \"for\", \"of\", \"a\", \"and\", \"to\", \"in\", \"an\"]\nignore = \"(),:'\\\"\"\n\n\ndef get_terms(doc, index=None, ignorechars=ignore, stopwords=stop):\n if index:\n return set([index[Stemmer()(term.lower().\n translate(term.maketrans('','',ignorechars)))]\n for term in doc.split() \n if term.lower() not in stopwords])\n return set([Stemmer()(term.lower().\n translate(term.maketrans('','',ignorechars)))\n for term in doc.split() \n if term.lower() not in stopwords])\n\n\ndef index_words(termset):\n my_map = {}\n i = 0\n for term in termset:\n my_map[term] = i\n i += 1\n return my_map\n\n\ndef get_vocabulary(docs, ignorechars=ignore, stopwords=stop):\n vocab = set()\n for doc in docs:\n terms_in_doc = get_terms(doc, False, ignorechars, stopwords)\n vocab = vocab.union(terms_in_doc)\n return vocab\n\n\ndef cov(term_set, docs):\n if len(term_set) == 0:\n return set()\n return set([d for d in docs.keys()\n if term_set.issubset(docs[d])])","repo_name":"netzsooc/Doc_ClusteringPy","sub_path":"DocumentClustering/src/Process/prepro.py","file_name":"prepro.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"22625381192","text":"from django.shortcuts import render\nfrom enroll.forms import SignUpform\nfrom django.contrib import messages\n\n# Create your views here.\n\ndef sign_up(request):\n if request.method == 'POST':\n form = SignUpform(request.POST)\n if form.is_valid():\n form.save()\n messages.success(request, 'Account Created Successfully!')\n form = SignUpform()\n else:\n form = SignUpform()\n return render(request, 'enroll/singup.html', {'form': form})","repo_name":"cientme/my_dj_code","sub_path":"djcode/djcode61_/authentications/authantication62AddFields/enroll/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"35211740551","text":"import sys\ninput = sys.stdin.readline\n\nn, k = map(int, input().split())\ndata = []\nfor i in range(n):\n w, v = map(int, input().split())\n if w <= k:\n data.append((w, v))\nif len(data) > 0:\n dp = [[0]*(k+1) for _ in range(len(data))]\n w, v = data[0]\n for i in range(w, k+1):\n dp[0][i] = v\n for i in range(1, len(data)):\n w, v = data[i]\n for j in range(w):\n dp[i][j] = dp[i-1][j]\n for j in range(w, k+1):\n dp[i][j] = max(dp[i-1][j], dp[i-1][j-w]+v)\n print(dp[-1][k])\nelse:\n print(0)\n","repo_name":"hyh1016/boj-with-python","sub_path":"python/dp/12865.py","file_name":"12865.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"70915548599","text":"from mysql.connector import connect, Error # pip3 mysql-connector-python\nimport hashlib\nimport os\nfrom Crypto.Cipher import AES\n\n## Utils ##\ndef toBinary(filename):\n # Convert digital data to binary format\n with open(filename, 'rb') as file:\n binaryData = file.read()\n return binaryData\n\ndef toHash(data):\n return str(int(hashlib.sha1(str(data).encode(\"UTF-8\")).hexdigest(),16))[:16]\n\ndef toByte(data):\n return data.encode(\"utf-8\")\n## Utils ###\n\n## Encrypt ##\ndef encryptImg(key,data):\n byte_key = toByte(key)\n cipher = AES.new(byte_key, AES.MODE_CFB) # CFB mode\n ciphered_data = cipher.encrypt(data) # Only need to encrypt the data, no padding required for this mode\n return ciphered_data,cipher.iv\n## Encrypt ##\n\n## Upload Func ##\ndef uploadData(key):\n try:\n connection = connect(host='192.168.0.62', # Pi-Server IP\n database='dataset',\n user='picam',\n password='picam')\n\n # Upload dengan Loop\n for dirname, dirnames, filenames in os.walk('data'):\n for filename in filenames:\n # Operasi File\n file = os.path.join(dirname, filename)\n folder = dirname.rsplit(\"/\")[1]\n cursor = connection.cursor()\n\n # Enkripsikan File\n imgFile = toBinary(file)\n encImgFile,imgIV = encryptImg(key,imgFile)\n # Hash File Enkripsi\n imgHash = toHash(encImgFile)\n\n # SQL String\n sql_insert = \"\"\"INSERT INTO imageset_encrypted\n (imgNama, imgFile, imgIV, imgHash) VALUES (%s,%s,%s,%s)\"\"\"\n\n # Konversi Data ke Tuple\n insert_data = (folder, encImgFile, imgIV, imgHash)\n result = cursor.execute(sql_insert, insert_data)\n connection.commit()\n print(\"Insert Name \"+folder+\" : Success - Error : \", result)\n\n except Error as error:\n print(\"=> Upload Failed {}\".format(error))\n\n finally:\n if connection.is_connected():\n cursor.close()\n connection.close()\n print(\"=> Upload Finished\")\n## Upload Func ##\n\ndef main():\n print(\"> Upload Data Set\")\n key = \"FTIKUSM-LPPM2122\"\n uploadData(key)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"alauddinmaulanahirzan/EncryptedCameraRecognition","sub_path":"DatasetUpload_encVer.py","file_name":"DatasetUpload_encVer.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"2244448084","text":"# -------------------------------------------------------------------------------\r\n# Name: module1\r\n# Purpose:\r\n#\r\n# Author: florins\r\n#\r\n# Created: 03/12/2018\r\n# Copyright: (c) florins 2018\r\n# Licence: \r\n# -------------------------------------------------------------------------------\r\n\r\nimport turtle\r\n\r\nwn = turtle.Screen()\r\nwn.bgcolor(\"lightgreen\")\r\nflorin = turtle.Turtle()\r\nflorin.shape(\"turtle\")\r\nflorin.color(\"blue\")\r\nflorin.pensize(3)\r\nflorin.speed(5)\r\n\r\n'''\r\nfor i in range(4):\r\n for i in range(4):\r\n florin.forward(20)\r\n florin.left(90)\r\n florin.penup()\r\n florin.forward(40)\r\n florin.pendown()\r\n'''\r\n\r\n# EX 2\r\n'''\r\nsize = 20\r\nfor i in range(5):\r\n for i in range(4):\r\n florin.forward(size)\r\n florin.left(90)\r\n florin.right(135)\r\n florin.penup()\r\n florin.forward(15)\r\n florin.left(135)\r\n florin.pendown()\r\n size += 20\r\n'''\r\n\r\n\r\n# Ex 3\r\ndef draw_poly(broasca, n, sz):\r\n for i in range(n):\r\n broasca.forward(sz)\r\n broasca.left(360/n)\r\n\r\n\r\n#draw_poly(florin, 8, 50)\r\n\r\n# Ex 4\r\n'''\r\ndef square(broasca):\r\n for i in range(4):\r\n broasca.forward(100)\r\n broasca.left(90)\r\n\r\nfor i in range(20):\r\n square(florin)\r\n florin.right(20)\r\n'''\r\n\r\n# Ex 5\r\n\r\n'''\r\ndef draw_patrat(broasca, latura):\r\n broasca.left(91) # If you change here the angle to 90 you will get the first draw.\r\n broasca.forward(latura)\r\n\r\nsize = 2\r\n\r\nfor i in range(100):\r\n size = size + 3\r\n draw_patrat(florin, size)\r\n'''\r\n\r\n# Ex 6\r\n\r\n\r\ndef draw_equitriangle(t, sz):\r\n draw_poly(t, 3, sz)\r\n\r\n#draw_equitriangle(florin, 100)\r\n\r\n# Ex 7\r\n\r\n\r\ndef sum_to(n):\r\n sum = 0\r\n for i in range(n+1):\r\n sum = sum + i\r\n print(sum)\r\n# sum_to(10)\r\n\r\n# Ex 8\r\n\r\n\r\ndef area_of_circle(r):\r\n area = 3.14159 * r**2\r\n print(area)\r\n return area\r\n\r\n\r\n# Ex 9\r\ndef draw_star():\r\n for i in range(5):\r\n florin.right(144)\r\n florin.forward(100)\r\n\r\n\r\n# Ex 10\r\nfor i in range(5):\r\n draw_star()\r\n # florin.right(144)\r\n # florin.penup()\r\n florin.right(144)\r\n florin.forward(400)\r\n florin.pendown()\r\n\r\nwn.mainloop()\r\n","repo_name":"Florins13/How-to-Think-Like-a-Computer-Scientist","sub_path":"4. Functions.py","file_name":"4. Functions.py","file_ext":"py","file_size_in_byte":2160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"22460059172","text":"\"\"\"\nSimple script to get douban book tags.\nYou may need requests and beautifulsoup4 to use it.\nUsage:\n python get_tags.py > tags.txt\n\"\"\"\nimport requests\nfrom bs4 import BeautifulSoup as bs\n\nurl = \"https://book.douban.com/tag/\"\n\nr = requests.get(url)\n\nsoup = bs(r.text, 'lxml')\n\ntables = soup.find_all('table', class_='tagCol')\nfor t in tables:\n for td in t.find_all('td'):\n print(td.a.string)\n","repo_name":"dyinnz/drift_booklist","sub_path":"spider/get_tags.py","file_name":"get_tags.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"21113498883","text":"from django.urls import path\n\n\nfrom .views import BlogView, \\\n BlogDetailView, \\\n AboutView, \\\n IndexView, \\\n BlogCreateView, \\\n BlogUpdateView, \\\n BlogDeleteView, \\\n ViewBlog, \\\n ContactCreateView\n\napp_name = 'core'\n\nurlpatterns = [\n path('', IndexView.as_view(), name='index_view'),\n path('blog/', BlogView.as_view(), name='blog_view'),\n path('blog-detail//', BlogDetailView.as_view(), name='blog_detail'),\n path('contact/', ContactCreateView.as_view(), name='contact'),\n path('about/', AboutView.as_view(), name='about'),\n path('add-blog/', BlogCreateView.as_view(), name='add_blog'),\n path('update-blog/', BlogUpdateView.as_view(), name='update_blog'),\n path('delete-blog/', BlogDeleteView.as_view(), name='delete-blog'),\n path('view-blog', ViewBlog.as_view(), name='view-blog'),\n ]\n","repo_name":"safwanvk/Zabblog","sub_path":"core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"17175615948","text":"# Copyright 2004-2008 Roman Yakovenko.\r\n# Distributed under the Boost Software License, Version 1.0. (See\r\n# accompanying file LICENSE_1_0.txt or copy at\r\n# http://www.boost.org/LICENSE_1_0.txt)\r\n\r\nimport os\r\nimport unittest\r\nimport autoconfig\r\nimport parser_test_case\r\n\r\nfrom pygccxml import parser\r\nfrom pygccxml import declarations\r\n\r\nclass tester_t( parser_test_case.parser_test_case_t ):\r\n def __init__(self, *args):\r\n parser_test_case.parser_test_case_t.__init__(self, *args)\r\n self.__files = [\r\n 'core_ns_join_1.hpp'\r\n , 'core_ns_join_2.hpp'\r\n , 'core_ns_join_3.hpp'\r\n , 'core_membership.hpp'\r\n , 'core_class_hierarchy.hpp'\r\n , 'core_types.hpp'\r\n , 'core_diamand_hierarchy_base.hpp'\r\n , 'core_diamand_hierarchy_derived1.hpp'\r\n , 'core_diamand_hierarchy_derived2.hpp'\r\n , 'core_diamand_hierarchy_final_derived.hpp'\r\n , 'core_overloads_1.hpp'\r\n , 'core_overloads_2.hpp'\r\n , 'typedefs_base.hpp'\r\n ]\r\n \r\n #~ for i, f in enumerate(self.__files):\r\n #~ f = parser.create_cached_source_fc( os.path.join( autoconfig.data_directory, f)\r\n #~ , os.path.join( autoconfig.data_directory, f + '.xml') )\r\n #~ self.__files[i] = f\r\n prj_reader = parser.project_reader_t( self.config )\r\n self.decls = prj_reader.read_files( self.__files\r\n , compilation_mode=parser.COMPILATION_MODE.FILE_BY_FILE )\r\n\r\n def test_printer(self):\r\n writer = lambda decl: None\r\n declarations.print_declarations( self.decls, writer=writer )\r\n #declarations.print_declarations( self.decls )\r\n\r\n def test__str__(self):\r\n decls = declarations.make_flatten(self.decls)\r\n for decl in decls:\r\n str(decl)\r\n\r\ndef create_suite():\r\n suite = unittest.TestSuite()\r\n suite.addTest( unittest.makeSuite(tester_t))\r\n return suite\r\n\r\ndef run_suite():\r\n unittest.TextTestRunner(verbosity=2).run( create_suite() )\r\n\r\nif __name__ == \"__main__\":\r\n run_suite()\r\n","repo_name":"robotics-at-maryland/tortuga","sub_path":"deps/pygccxml/unittests/decl_printer_tester.py","file_name":"decl_printer_tester.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"40"} +{"seq_id":"33576435660","text":"import csv\r\nimport os\r\nfrom proto_lib import analyze_patterns, summarizer_to_SAX, retrieve_weekdays\r\nfrom saxpy.sax import ts_to_string\r\nfrom saxpy.znorm import znorm\r\nfrom saxpy.alphabet import cuts_for_asize\r\nfrom saxpy.paa import paa\r\nimport numpy as np\r\nimport torch\r\n\r\nweekday_dict = { 1 : \"Monday\",\r\n 2 : \"Tuesday\",\r\n 3 : \"Wednesday\",\r\n 4 : \"Thursday\",\r\n 5 : \"Friday\",\r\n 6 : \"Saturday\",\r\n 7 : \"Sunday\" }\r\n\r\ndb_fn_prefix = \"series_db_WIT_concat\"\r\n\r\n# Parameters for SPADE\r\nmin_conf = 0.8\r\nmin_sup = 0.2\r\npath = \".\" # Path for pattern data\r\ncygwin_path = r\"C:\\cygwin64\\bin\" # Path to Cygwin\r\noutput_filename = 'WIT_sequences_concat.csv'\r\nheader = [\"Sequence\",\"Series\",\"Summary\",\"Truth\",\"SAX\",\"sid\",\"uid\"]\r\n\r\n# If stops prematurely, start from most recent sid, uid\r\ndef retrieveLastSpot():\r\n if output_filename not in os.listdir(\".\"):\r\n return 0, 0\r\n\r\n with open(output_filename,newline='') as csvfile:\r\n csvreader = csv.reader(csvfile)\r\n sid = 0\r\n uid = 0\r\n for row in csvreader:\r\n if row == header:\r\n continue\r\n sid = int(row[-2])\r\n uid = int(row[-1])\r\n\r\n return sid, uid\r\n\r\nif __name__ == \"__main__\":\r\n data_path = \"mfp_data\"\r\n directory = os.listdir(data_path)\r\n\r\n sid, uid = retrieveLastSpot()\r\n\r\n if uid == 0:\r\n with open(output_filename,'w',newline='') as csvfile:\r\n csvwriter = csv.writer(csvfile)\r\n csvwriter.writerow(header)\r\n\r\n file_cnt = uid\r\n for filename in directory:\r\n if \".csv\" not in filename:\r\n continue\r\n elif file_cnt > 0: # Each file is a different user. Skip latest user in file since pattern output isn't the same every time (otherwise could be duplicates)\r\n file_cnt -= 1\r\n continue\r\n\r\n # Retrieve data\r\n with open(data_path + '/' + filename,newline='') as csvfile:\r\n csvreader = csv.reader(csvfile)\r\n calories = []\r\n dates = []\r\n header = True\r\n for row in csvreader:\r\n if header:\r\n header = False\r\n continue\r\n if len(row) == 0:\r\n continue\r\n else:\r\n calories.append(int(row[1]))\r\n dates.append(row[0])\r\n\r\n # Remove last week if it isn't full\r\n series_length = len(calories)\r\n cutoff = series_length % 7\r\n\r\n if cutoff:\r\n calories = calories[:-1*cutoff]\r\n\r\n # Normalize data\r\n pre_norm = calories\r\n calories = znorm(np.array(calories))\r\n\r\n # Retrieve weekdays\r\n dates = retrieve_weekdays(\"MyFitnessPal\",dates,weekday_dict)\r\n\r\n num_variations = int(len(calories))\r\n output = []\r\n for _ in range(num_variations):\r\n first = [calories[0].item()]\r\n second = calories[1:].tolist()\r\n calories = torch.tensor(second + first)\r\n dates = dates[-1:] + dates[:-1]\r\n\r\n # Retrieve input sequence\r\n series_str = \"\"\r\n for i in range(len(calories)):\r\n series_str += str(calories[i])\r\n if i != len(calories)-1:\r\n series_str += \"|\"\r\n\r\n # Setup\r\n attr = \"MyFitnessPal\"\r\n attr_list = [attr]\r\n key_list = [\"Calorie Intake\"]\r\n alpha_size = 5\r\n alpha_sizes = [alpha_size]\r\n tw = 7\r\n TW = \"weeks\"\r\n alpha = 0.9\r\n age = 23\r\n activity_level = \"active\"\r\n proto_cnt = 0\r\n\r\n # Construct mapping from letters in alphabet to integers (starting at 1)\r\n import string\r\n alphabet = string.ascii_lowercase\r\n alphabet_list = [alphabet]\r\n letter_map = dict()\r\n for i in range(alpha_size):\r\n letter_map[alphabet[i]] = i+1\r\n letter_map_list = [letter_map]\r\n\r\n # SAX\r\n full_sax_rep = ts_to_string(calories, cuts_for_asize(alpha_size))\r\n sax = list(full_sax_rep)\r\n sax_list = [full_sax_rep]\r\n tw_sax_list = [ts_to_string(paa(calories,tw), cuts_for_asize(alpha_size))]\r\n\r\n # Retrieve summaries\r\n summary_list, supports, proto_cnt, numsum_list, summarizers_list = analyze_patterns(key_list,sax_list,alphabet_list,letter_map_list,weekday_dict,tw,alpha_sizes,db_fn_prefix,path,cygwin_path,min_conf,min_sup,proto_cnt,weekdays=dates)\r\n\r\n\r\n for i in range(len(summary_list)):\r\n\r\n # Get SAX version of pattern\r\n input_str = \"\"\r\n pre_list = summarizers_list[i][0][0]\r\n suf_list = summarizers_list[i][1][0]\r\n\r\n pre_list = [summarizer_to_SAX(x,alpha_size) for x in pre_list if x not in weekday_dict.values()]\r\n suf_list = [summarizer_to_SAX(x,alpha_size) for x in suf_list if x not in weekday_dict.values()]\r\n\r\n pre_sax = ''.join(pre_list)\r\n suf_sax = ''.join(suf_list)\r\n\r\n find_sax = pre_sax + suf_sax\r\n\r\n # Find indices of all instances of pattern\r\n import re\r\n indices = [x.start() for x in re.finditer('(?='+find_sax+')',full_sax_rep)]\r\n\r\n # Find weeks starting at instances of patterns\r\n input_str = \"\"\r\n for index in indices:\r\n index_range = range(index,min(index+tw,len(calories)-1))\r\n for j in index_range:\r\n input_str += str(calories[j]) + \"|\"\r\n input_str = input_str[:-1]\r\n\r\n #if len(input_str.split(\"|\")) < 100:\r\n #print(pre_norm)\r\n #print(calories)\r\n #input(series_str)\r\n\r\n output.append([input_str,series_str,summary_list[i],supports[i],full_sax_rep,sid,uid])\r\n sid += 1\r\n\r\n with open(output_filename,'a+',newline='') as csvfile:\r\n csvwriter = csv.writer(csvfile)\r\n for i in range(len(output)):\r\n csvwriter.writerow(output[i])\r\n\r\n uid += 1\r\n\r\n print(len(directory) - uid, \"users remaining\")\r\n\r\n\r\n print(\"done\")","repo_name":"neato47/Neural-Numeric-To-Text-Generation","sub_path":"build_wit_dataset.py","file_name":"build_wit_dataset.py","file_ext":"py","file_size_in_byte":6384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"9215881680","text":"import psycopg2\nimport os\n\n#conn = psycopg2.connect(database=\"postgres\", user=\"postgres\", port=\"5432\", password=\"password\")\nconn = psycopg2.connect(database=\"postgres\", host=\"/home/\" + os.environ['USER'] + \"/postgres\", port=\"5432\")\nprint (\"Database Connection Succesful\")\nprint (\"\")\ncursor = conn.cursor()\n\n#query 1\nnumerator = 0\ndenominator = 0\ncursor.execute(\"SELECT count(*) FROM STUDENT WHERE (SUBJ = 'ABC' OR SUBJ = 'DEF');\")\ndenominator = float(cursor.fetchone()[0])\nfor i in range(1,21):\n cursor.execute(\"\"\"SELECT count(*) FROM STUDENT WHERE (SUBJ = 'ABC' OR SUBJ = 'DEF') AND UNITS = %s;\"\"\", (str(i),))\n numerator = float(cursor.fetchone()[0])\n percent = (numerator/denominator)*100\n print(\"attempt \" + str(i) + \" unit \" + str(percent))\n\nprint (\"\")\n#query 2\ngplist = []\nfor i in range(1,21):\n cursor.execute(\"\"\"SELECT GP FROM STUDENT WHERE (SUBJ = 'ABC' OR SUBJ = 'DEF') AND UNITS = %s AND GRADE != 'P' AND GRADE != 'NP' AND GRADE != ' ' AND GRADE != 'S'\n AND GRADE != 'I' AND GRADE != 'IP' AND GRADE != 'NG' AND GRADE != 'NS' AND GRADE != 'U' AND GRADE != 'W04' AND GRADE != 'W10' AND GRADE != 'WD1'\n AND GRADE != 'WD2' AND GRADE != 'WD4' AND GRADE != 'WDC' AND GRADE != 'WI' AND GRADE != 'WN' AND GRADE != 'XR' AND GRADE != 'Y';\"\"\", (str(i),))\n for row in cursor.fetchall():\n gplist.append(float(row[0]))\n avg = sum(gplist) / float(len(gplist))\n print(\"attempt \" + str(i) + \" unit avg gpa: \" + str(\"{0:.2f}\".format(avg)))\n \nconn.close()\n","repo_name":"ialmazan/Programming-Languages","sub_path":"Python/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"14685170916","text":"import re\nfrom nltk.util import ngrams\n\ns = \"natural language processing (NLP) is an area of computer science \" \\\n \"and aitificial intelligence concerned with the interactions\" \\\n \"between computer and human language.\"\n \ns = s.lower()\ns = re.sub(r'[^a-zA-z0-9\\s]', '', s)\n\ntokens = [token for token in s.split(\" \")if token != \"\"]\n\noutput = list(ngrams(tokens,3))\n\nprint (output)\n ","repo_name":"Akash-Dinkar-Bhujbal/NLP-Practicals","sub_path":"nlp 3.py","file_name":"nlp 3.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"38601853401","text":"import numpy as np\r\n\r\nfrom .Utilities import get_feature\r\nfrom .Utilities import get_feature_svm\r\nfrom .Utilities import load_model\r\nfrom .Utilities import Radar\r\n\r\nDATA_PATH = 'DataSet/Berlin'\r\n# CLASS_LABELS = (\"Angry\", \"Happy\", \"Neutral\", \"Sad\")\r\n\r\nCLASS_LABELS = (\"Angry\", \"Fearful\", \"Happy\", \"Neutral\", \"Sad\", \"Surprise\")\r\n# CLASS_LABELS = (\"angry\", \"fear\", \"happy\", \"neutral\", \"sad\", \"surprise\")\r\n\r\n\r\ndef load(model_name=\"SVM\"):\r\n if model_name == \"LSTM\" or model_name == \"CNN\":\r\n model = load_model(model_name=model_name, load_model=\"DNN\")\r\n elif model_name == \"SVM\" or model_name == \"MLP\":\r\n model = load_model(model_name=model_name, load_model=\"ML\")\r\n else:\r\n print(\"情感识别模型选择有误\")\r\n\r\n return model\r\n\r\n\r\ndef test(file_path: str, model_name=\"SVM\", get_radar=False, model=None):\r\n if model_name == \"LSTM\":\r\n LSTM(file_path, get_radar, model)\r\n elif model_name == \"CNN\":\r\n CNN(file_path, get_radar, model)\r\n elif model_name == \"SVM\":\r\n SVM(file_path, get_radar, model)\r\n elif model_name == \"MLP\":\r\n MLP(file_path, get_radar, model)\r\n else:\r\n print(\"情感识别模型选择有误\")\r\n\r\n\r\ndef LSTM(file_path: str, get_radar=False, model=None):\r\n if model is None:\r\n print(\"情感识别模型载入出错\")\r\n return\r\n NUM_LABELS = len(CLASS_LABELS)\r\n result = np.argmax(model.predict(np.array([get_feature(file_path)])))\r\n result_prob = model.predict(np.array([get_feature(file_path)]))[0]\r\n _print_result(result, result_prob)\r\n if get_radar:\r\n Radar(result_prob, CLASS_LABELS, NUM_LABELS)\r\n\r\n\r\ndef CNN(file_path: str, get_radar=False, model=None):\r\n if model is None:\r\n print(\"情感识别模型载入出错\")\r\n return\r\n\r\n FLATTEN = False\r\n test = np.array([get_feature(file_path, flatten=FLATTEN)])\r\n in_shape = test[0].shape\r\n test = test.reshape(test.shape[0], in_shape[0], in_shape[1], 1)\r\n print('Recogntion: ', CLASS_LABELS[np.argmax(model.predict(test))])\r\n\r\n\r\ndef MLP(file_path: str, get_radar=False, model=None):\r\n if model is None:\r\n print(\"情感识别模型载入出错\")\r\n return\r\n FLATTEN = True\r\n NUM_LABELS = len(CLASS_LABELS)\r\n\r\n result = model.predict(np.array([get_feature(file_path, flatten=FLATTEN)]))\r\n result_prob = model.predict_proba(\r\n np.array([get_feature(file_path, flatten=FLATTEN)]))\r\n _print_result(result, result_prob)\r\n if get_radar:\r\n Radar(result_prob, CLASS_LABELS, NUM_LABELS)\r\n\r\n\r\ndef SVM(file_path: str, get_radar=False, model=None):\r\n if model is None:\r\n print(\"情感识别模型载入出错\")\r\n return\r\n NUM_LABELS = len(CLASS_LABELS)\r\n\r\n result = model.predict(np.array([get_feature_svm(file_path, mfcc_len=48)]))\r\n result_prob = model.predict_proba(\r\n np.array([get_feature_svm(file_path, mfcc_len=48)]))[0]\r\n _print_result(result, result_prob)\r\n if get_radar:\r\n Radar(result_prob, CLASS_LABELS, NUM_LABELS)\r\n\r\ndef _print_result(result, result_prob):\r\n print('Recogntion: ', CLASS_LABELS[result[0] - 1])\r\n print('Probability: ', result_prob)\r\n# SVM(\"test.wav\")\r\n","repo_name":"XLab-Tongji/SemanticAnalysis","sub_path":"AI/Emotion/SER.py","file_name":"SER.py","file_ext":"py","file_size_in_byte":3184,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"6701355906","text":"def middle_point(function, begin, end, eps):\n count = 0\n while True:\n middle = (begin + end) / 2.0\n dxm = (function(middle + eps) - function(middle - eps)) / (2 * eps)\n count += 2\n if abs(dxm) < eps:\n return (middle, count)\n if dxm > 0:\n end = middle\n else:\n begin = middle\n\n\ndef chords(function, begin, end, eps):\n dxb = (function(begin + eps) - function(begin - eps)) / (2 * eps)\n dxe = (function(end + eps) - function(end - eps)) / (2 * eps)\n count = 4\n while True:\n x = begin - dxb / (dxb - dxe) * (begin - end)\n dxx = (function(x + eps) - function(x - eps)) / (2 * eps)\n count += 2\n if abs(dxx) < eps:\n return (x, count)\n if dxx > 0:\n end = x\n dxe = dxx\n else:\n begin = x\n dxb = dxx\n\n\ndef nuton(function, x0, eps):\n x = x0\n count = 0\n while True:\n f_1 = function(x + eps)\n f_2 = function(x - eps)\n count += 2\n dx1 = (f_1 - f_2) / (2 * eps)\n if abs(dx1) <= eps:\n return (x, count)\n f_0 = function(x)\n count += 1\n if count > 1000:\n return (None, None)\n dx2 = (f_1 - 2 * f_0 + f_2) / (eps * eps)\n x = x - dx1 / dx2\n","repo_name":"kosachevds/math_opt","sub_path":"lab_1/numericmethods.py","file_name":"numericmethods.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"19688869435","text":"import os\nimport pathlib\n\nfrom flask import current_app\nfrom flask_login import current_user\n\nfrom .decorators import make_async\nfrom .errors import ValidationError\nfrom .models import UserFile\nfrom .naming_rules import get_all_pways_path, get_comparison_dir\nfrom .admin import export_detail_path\n\nfrom helpers import compare_projects as cp\n\n\ndef get_comparison_table(proj_ids: list, nice_names=None, caption=None):\n \"\"\"Get pathway enrichment comparison for multiple pathways.\n\n Order of input Project IDs determines reference (1st ID), comparison (2nd),\n and other (3rd onwards, optional).\n\n Args:\n proj_ids (list): list of project IDs.\n nice_names (list): (optional) list of names to use for projects in\n output, otherwise uses proj_suffix specified at upload time.\n caption (str): (optional) Name for comparison shown in first cell of\n styled output.\n\n Returns:\n styler pd.DataFrame if get_styled else ordinary pd.DataFrame.\n\n \"\"\"\n # requires app context\n is_vip = True in [r.name == 'vip' for r in current_user.roles]\n n_ids = len(proj_ids)\n if is_vip:\n query = UserFile.query.filter_by(run_complete=1)\n else:\n query = UserFile.query.filter_by(user_id=current_user.id, run_complete=1)\n projs = query.filter(UserFile.file_id.in_(proj_ids)).all()\n if len(projs) != n_ids:\n raise ValidationError(\"Invalid project(s) requested\")\n # Ensure project ordering matches proj_ids\n proj_dict = {i.file_id: i for i in projs}\n projs = [proj_dict[i] for i in proj_ids]\n if nice_names is None:\n categ_names = [p.proj_suffix for p in projs]\n else:\n if len(nice_names) != n_ids:\n raise ValidationError(\"IDs and names have different lengths.\")\n categ_names = list(nice_names)\n tsv_dict = dict()\n n_dict = dict()\n for proj_name, proj in zip(categ_names, projs):\n proj_id = proj.file_id\n all_path = get_all_pways_path(proj)\n summary_exists = os.path.exists(all_path)\n if not summary_exists:\n print(f\"Gathering pathway details for proj={proj_id}.\")\n export_detail_path(proj)\n tsv_dict[proj_name] = all_path\n n_dict[proj_name] = proj.n_patients\n # app = current_app._get_current_object()\n out_dir = get_comparison_dir(current_user.id, proj_ids)\n os.makedirs(out_dir, exist_ok=True)\n build_comparison_tables(categ_names, tsv_dict, n_dict,\n caption=caption, out_dir=out_dir)\n\n\n@make_async\ndef build_comparison_tables(categ_names, tsv_dict, n_dict, caption=None,\n out_dir=None):\n complete_file = os.path.join(out_dir, '.complete')\n if os.path.exists(complete_file):\n return # Files already created\n df = cp.gather_pathways(categ_names, tsv_dict, n_dict)\n ref_name = categ_names[0]\n compared_name = categ_names[1]\n other_compared = categ_names[2:]\n comp = cp.identify_enrichment(ref_name, compared_name, df,\n other_compared=other_compared)\n\n caption = f\"{ref_name} > {compared_name}\" if caption is None else caption\n styled = cp.get_styled_comparison(comp, caption)\n # SAVE EXCEL\n excel_path = os.path.join(out_dir, 'comparison.xlsx')\n styled.to_excel(excel_path, sheet_name=f\"{caption}\")\n # SAVE HTML\n html = styled.render()\n html_path = os.path.join(out_dir, 'comparison.html')\n with open(html_path, 'w') as out:\n out.write(html)\n # SAVE 'COMPLETE' INDICATOR FILE\n pathlib.Path(complete_file).touch()\n\n\ndef proj_str_from_ids(proj_ids):\n proj_str = '/'.join([str(i) for i in proj_ids])\n return proj_str\n\n\ndef proj_ids_from_str(proj_id_str):\n proj_ids = proj_id_str.split('/')\n return proj_ids\n\n","repo_name":"sggaffney/pathscore","sub_path":"app/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":3782,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"40"} +{"seq_id":"12235455099","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 28 13:28:33 2020\n\n@author: KENG\n\"\"\"\n\nimport numpy as np\n\nclass KENG_Tx2Bit:\n def __init__(self,PAM_order):\n self.PAM_order=PAM_order\n self.level_value = np.linspace(- PAM_order + 1 , PAM_order -1 ,PAM_order)\n level_classification=np.array([float('-Inf')])\n level_classification=np.append(level_classification,np.linspace(- PAM_order + 2,PAM_order - 2,PAM_order-1))\n self.level_classification=np.append(level_classification,float('Inf'))\n \n def return_Tx(self, Tx_Signal):\n self.Tx_signal_symbol=np.zeros([np.size(Tx_Signal),1])\n for i in range(0, self.PAM_order):\n self.Tx_signal_symbol[list(self.level_classification[i+1]>Tx_Signal) and \n list(self.level_classification[i]<=Tx_Signal)]=self.level_value[i]\n\n return self.Tx_signal_symbol","repo_name":"KENGQQ/pycharm_coherent_64QAM","sub_path":"KENG_Tx2Bit.py","file_name":"KENG_Tx2Bit.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"12289314280","text":"import matplotlib\nfrom matplotlib import pyplot as plt\nfrom skimage import io, color\n\n\nmatplotlib.rc('font', size=7)\n\n\nfig, axes = plt.subplots(nrows=1, ncols=3, figsize=(6, 3))\nimages = [io.imread('fig_pl%i.png' % i) for i in range(1, 4)]\ntitles = ['(a) Normal photograph', '(b) Photoluminescence', '(c) Processed']\n\nfor ax, im, ti in zip(axes, images, titles):\n ax.imshow(color.gray2rgb(im), interpolation='nearest')\n ax.axis('off')\n ax.set_title(ti)\n\nplt.tight_layout()\nplt.savefig('fig_pl.eps', dpi=600, bbox_inches='tight')\nplt.savefig('fig_pl.png', dpi=600, bbox_inches='tight')\n","repo_name":"scikit-image/scikit-image-paper","sub_path":"skimage/figures/fig_pl.py","file_name":"fig_pl.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"40"} +{"seq_id":"31031122624","text":"import html\nfrom io import BytesIO\n\nfrom telegram import ChatAction, ParseMode\nfrom telegram.error import BadRequest, TelegramError\nfrom telegram.ext import CommandHandler, Filters, MessageHandler\nfrom telegram.utils.helpers import mention_html\n\nimport priscia.modules.sql.global_bans_sql as sql\nfrom priscia import (\n MESSAGE_DUMP,\n OWNER_ID,\n STRICT_GBAN,\n SUDO_USERS,\n SUPPORT_USERS,\n dispatcher,\n spamwtc,\n)\nfrom priscia.modules.helper_funcs.alternate import send_action\nfrom priscia.modules.helper_funcs.chat_status import is_user_admin, user_admin\nfrom priscia.modules.helper_funcs.extraction import extract_user, extract_user_and_text\nfrom priscia.modules.helper_funcs.filters import CustomFilters\nfrom priscia.modules.sql.users_sql import get_all_chats\n\nGBAN_ENFORCE_GROUP = 6\n\nGBAN_ERRORS = {\n \"Bots can't add new chat members\",\n \"Channel_private\",\n \"Chat not found\",\n \"Can't demote chat creator\",\n \"Chat_admin_required\",\n \"Group chat was deactivated\",\n \"Method is available for supergroup and channel chats only\",\n \"Method is available only for supergroups\",\n \"Need to be inviter of a user to kick it from a basic group\",\n \"Not enough rights to restrict/unrestrict chat member\",\n \"Not in the chat\",\n \"Only the creator of a basic group can kick group administrators\",\n \"Peer_id_invalid\",\n \"User is an administrator of the chat\",\n \"User_not_participant\",\n \"Reply message not found\",\n \"Can't remove chat owner\",\n}\n\nUNGBAN_ERRORS = {\n \"Bots can't add new chat members\",\n \"Channel_private\",\n \"Chat not found\",\n \"Can't demote chat creator\",\n \"Chat_admin_required\",\n \"Group chat was deactivated\",\n \"Method is available for supergroup and channel chats only\",\n \"Method is available only for supergroups\",\n \"Need to be inviter of a user to kick it from a basic group\",\n \"Not enough rights to restrict/unrestrict chat member\",\n \"Not in the chat\",\n \"Only the creator of a basic group can kick group administrators\",\n \"Peer_id_invalid\",\n \"User is an administrator of the chat\",\n \"User_not_participant\",\n \"Reply message not found\",\n \"User not found\",\n}\n\n\ndef gban(update, context):\n message = update.effective_message\n chat = update.effective_chat\n args = context.args\n user_id, reason = extract_user_and_text(message, args)\n\n if not user_id:\n message.reply_text(\"You don't seem to be referring to a user.\")\n return\n\n if user_id == OWNER_ID:\n message.reply_text(\"Nice try -_- but I'm never gonna gban him.\")\n return\n\n if int(user_id) in SUDO_USERS:\n message.reply_text(\n \"I spy, with my little eye... a sudo user war! Why are you guys turning on each other?\"\n )\n return\n\n if int(user_id) in SUPPORT_USERS:\n message.reply_text(\n \"OOOH someone's trying to gban a support user! *grabs popcorn*\"\n )\n return\n\n if user_id == context.bot.id:\n message.reply_text(\"-_- So funny, lets gban myself why don't I? Nice try.\")\n return\n\n try:\n user_chat = context.bot.get_chat(user_id)\n except BadRequest as excp:\n message.reply_text(excp.message)\n return\n\n if user_chat.type != \"private\":\n message.reply_text(\"That's not a user!\")\n return\n\n if user_chat.first_name == \"\":\n message.reply_text(\"This is a deleted account! no point to gban them...\")\n return\n\n if sql.is_user_gbanned(user_id):\n if not reason:\n message.reply_text(\n \"This user is already gbanned; I'd change the reason, but you haven't given me one...\"\n )\n return\n\n old_reason = sql.update_gban_reason(\n user_id, user_chat.username or user_chat.first_name, reason\n )\n user_id, new_reason = extract_user_and_text(message, args)\n\n if old_reason:\n banner = update.effective_user\n bannerid = banner.id\n bannername = banner.first_name\n new_reason = (\n f\"{new_reason} // GBanned by {bannername} banner id: {bannerid}\"\n )\n\n context.bot.sendMessage(\n MESSAGE_DUMP,\n \"Global Ban Reason Update\"\n \"\\nSudo Admin: {}\"\n \"\\nUser: {}\"\n \"\\nID: {}\"\n \"\\nPrevious Reason: {}\"\n \"\\nNew Reason: {}\".format(\n mention_html(banner.id, banner.first_name),\n mention_html(\n user_chat.id, user_chat.first_name or \"Deleted Account\"\n ),\n user_chat.id,\n old_reason,\n new_reason,\n ),\n parse_mode=ParseMode.HTML,\n )\n\n message.reply_text(\n \"This user is already gbanned, for the following reason:\\n\"\n \"{}\\n\"\n \"I've gone and updated it with your new reason!\".format(\n html.escape(old_reason)\n ),\n parse_mode=ParseMode.HTML,\n )\n\n else:\n message.reply_text(\n \"This user is already gbanned, but had no reason set; I've gone and updated it!\"\n )\n\n return\n\n message.reply_text(\n f\"Beginning of Global Ban for {mention_html(user_chat.id, user_chat.first_name)}\"\n f\"\\nWith ID: {user_chat.id}\"\n f\"\\nReason: {reason or 'No reason given'}\",\n parse_mode=ParseMode.HTML,\n )\n\n banner = update.effective_user\n bannerid = banner.id\n bannername = banner.first_name\n reason = f\"{reason} // GBanned by {bannername} banner id: {bannerid}\"\n\n context.bot.sendMessage(\n MESSAGE_DUMP,\n \"New Global Ban\"\n \"\\n#GBAN\"\n \"\\nStatus: Enforcing\"\n \"\\nSudo Admin: {}\"\n \"\\nUser: {}\"\n \"\\nID: {}\"\n \"\\nReason: {}\".format(\n mention_html(banner.id, banner.first_name),\n mention_html(user_chat.id, user_chat.first_name),\n user_chat.id,\n reason or \"No reason given\",\n ),\n parse_mode=ParseMode.HTML,\n )\n\n try:\n context.bot.kick_chat_member(chat.id, user_chat.id)\n except BadRequest:\n pass\n sql.gban_user(user_id, user_chat.username or user_chat.first_name, reason)\n\n\ndef ungban(update, context):\n message = update.effective_message\n args = context.args\n user_id = extract_user(message, args)\n if not user_id:\n message.reply_text(\"You don't seem to be referring to a user.\")\n return\n\n user_chat = context.bot.get_chat(user_id)\n if user_chat.type != \"private\":\n message.reply_text(\"That's not a user!\")\n return\n\n if not sql.is_user_gbanned(user_id):\n message.reply_text(\"This user is not gbanned!\")\n return\n\n banner = update.effective_user\n\n message.reply_text(\n \"I'll give {} a second chance, globally.\".format(user_chat.first_name)\n )\n\n context.bot.sendMessage(\n MESSAGE_DUMP,\n \"Regression of Global Ban\"\n \"\\n#UNGBAN\"\n \"\\nStatus: Ceased\"\n \"\\nSudo Admin: {}\"\n \"\\nUser: {}\"\n \"\\nID: {}\".format(\n mention_html(banner.id, banner.first_name),\n mention_html(user_chat.id, user_chat.first_name),\n user_chat.id,\n ),\n parse_mode=ParseMode.HTML,\n )\n\n chats = get_all_chats()\n for chat in chats:\n chat_id = chat.chat_id\n\n # Check if this group has disabled gbans\n if not sql.does_chat_gban(chat_id):\n continue\n\n try:\n member = context.bot.get_chat_member(chat_id, user_id)\n if member.status == \"kicked\":\n context.bot.unban_chat_member(chat_id, user_id)\n\n except BadRequest as excp:\n if excp.message not in UNGBAN_ERRORS:\n message.reply_text(\"Could not un-gban due to: {}\".format(excp.message))\n context.bot.send_message(\n OWNER_ID, \"Could not un-gban due to: {}\".format(excp.message)\n )\n return\n except TelegramError:\n pass\n\n sql.ungban_user(user_id)\n\n context.bot.sendMessage(\n MESSAGE_DUMP,\n \"User {} has been successfully un-gbanned!\".format(\n mention_html(user_chat.id, user_chat.first_name)\n ),\n parse_mode=ParseMode.HTML,\n )\n message.reply_text(\"Person has been un-gbanned.\")\n\n\n@send_action(ChatAction.UPLOAD_DOCUMENT)\ndef gbanlist(update, context):\n banned_users = sql.get_gban_list()\n\n if not banned_users:\n update.effective_message.reply_text(\n \"There aren't any gbanned users! You're kinder than I expected...\"\n )\n return\n\n banfile = \"List of retards.\\n\"\n for user in banned_users:\n banfile += \"[x] {} - {}\\n\".format(user[\"name\"], user[\"user_id\"])\n if user[\"reason\"]:\n banfile += \"Reason: {}\\n\".format(user[\"reason\"])\n\n with BytesIO(str.encode(banfile)) as output:\n output.name = \"gbanlist.txt\"\n update.effective_message.reply_document(\n document=output,\n filename=\"gbanlist.txt\",\n caption=\"Here is the list of currently gbanned users.\",\n )\n\n\ndef check_and_ban(update, user_id, should_message=True):\n\n try:\n spmban = spamwtc.get_ban(int(user_id))\n if spmban:\n update.effective_chat.kick_member(user_id)\n if should_message:\n update.effective_message.reply_text(\n f\"This person has been detected as spambot by @SpamWatch and has been removed!\\nReason: {spmban.reason}\",\n parse_mode=ParseMode.HTML,\n )\n return\n except Exception:\n pass\n\n if sql.is_user_gbanned(user_id):\n update.effective_chat.kick_member(user_id)\n if should_message:\n usr = sql.get_gbanned_user(user_id)\n greason = usr.reason\n if not greason:\n greason = \"No reason given\"\n\n update.effective_message.reply_text(\n f\"*Alert! this user was GBanned and have been removed!*\\n*Reason*: {greason}\",\n parse_mode=ParseMode.MARKDOWN,\n )\n return\n\n\ndef enforce_gban(update, context):\n # Not using @restrict handler to avoid spamming - just ignore if cant gban.\n if (\n not sql.does_chat_gban(update.effective_chat.id)\n or not update.effective_chat.get_member(context.bot.id).can_restrict_members\n ):\n return\n user = update.effective_user\n chat = update.effective_chat\n msg = update.effective_message\n\n if user and not is_user_admin(chat, user.id):\n check_and_ban(update, user.id)\n\n if msg.new_chat_members:\n new_members = update.effective_message.new_chat_members\n for mem in new_members:\n check_and_ban(update, mem.id)\n\n if msg.reply_to_message:\n user = msg.reply_to_message.from_user\n if user and not is_user_admin(chat, user.id):\n check_and_ban(update, user.id, should_message=False)\n\n\n@user_admin\ndef gbanstat(update, context):\n args = context.args\n if len(args) > 0:\n if args[0].lower() in [\"on\", \"yes\"]:\n sql.enable_gbans(update.effective_chat.id)\n update.effective_message.reply_text(\n \"I've enabled Spam Sheild in this group. This will help protect you \"\n \"from spammers, unsavoury characters, and the biggest trolls.\"\n )\n elif args[0].lower() in [\"off\", \"no\"]:\n sql.disable_gbans(update.effective_chat.id)\n update.effective_message.reply_text(\n \"I've disabled Spam sheild in this group. GBans wont affect your users \"\n \"anymore. You'll be less protected from any trolls and spammers \"\n \"though!\"\n )\n else:\n update.effective_message.reply_text(\n \"Give me some arguments to choose a setting! on/off, yes/no!\\n\\n\"\n \"Your current setting is: {}\\n\"\n \"When True, any gbans that happen will also happen in your group. \"\n \"When False, they won't, leaving you at the possible mercy of \"\n \"spammers.\".format(sql.does_chat_gban(update.effective_chat.id))\n )\n\n\ndef __stats__():\n return \"× {} gbanned users.\".format(sql.num_gbanned_users())\n\n\ndef __user_info__(user_id):\n is_gbanned = sql.is_user_gbanned(user_id)\n\n text = \"Globally banned: {}\"\n\n if int(user_id) in SUDO_USERS + SUPPORT_USERS:\n return \"\"\n if is_gbanned:\n text = text.format(\"Yes\")\n user = sql.get_gbanned_user(user_id)\n if user.reason:\n text += \"\\nReason: {}\".format(html.escape(user.reason))\n text += \"\\n\\nAppeal at @fvllprojekt if you think it's invalid.\"\n else:\n text = text.format(\"No\")\n return text\n\n\ndef __migrate__(old_chat_id, new_chat_id):\n sql.migrate_chat(old_chat_id, new_chat_id)\n\n\ndef __chat_settings__(chat_id, user_id):\n return \"This chat is enforcing *gbans*: `{}`.\".format(sql.does_chat_gban(chat_id))\n\n\n__help__ = \"\"\"\n*Admin only:*\n × /spamshield : Will disable or enable the effect of Spam protection in your group.\n\nSpam shield uses @Spamwatch API and Global bans to remove Spammers as much as possible from your chatroom!\n\n*What is SpamWatch?*\n\nSpamWatch maintains a large constantly updated ban-list of spambots, trolls, bitcoin spammers and unsavoury characters.\nPriscia will constantly help banning spammers off from your group automatically So, you don't have to worry about spammers storming your group[.](https://telegra.ph/file/c1051d264a5b4146bd71e.jpg)\n\"\"\"\n\n__mod_name__ = \"Spam Shield\"\n\nGBAN_HANDLER = CommandHandler(\n \"gban\",\n gban,\n pass_args=True,\n filters=CustomFilters.sudo_filter | CustomFilters.support_filter,\n)\nUNGBAN_HANDLER = CommandHandler(\n \"ungban\",\n ungban,\n pass_args=True,\n filters=CustomFilters.sudo_filter | CustomFilters.support_filter,\n)\nGBAN_LIST = CommandHandler(\n \"gbanlist\",\n gbanlist,\n filters=CustomFilters.sudo_filter | CustomFilters.support_filter,\n)\n\nGBAN_STATUS = CommandHandler(\n \"spamshield\", gbanstat, pass_args=True, filters=Filters.chat_type.groups\n)\n\nGBAN_ENFORCER = MessageHandler(Filters.all & Filters.chat_type.groups, enforce_gban)\n\ndispatcher.add_handler(GBAN_HANDLER)\ndispatcher.add_handler(UNGBAN_HANDLER)\ndispatcher.add_handler(GBAN_LIST)\ndispatcher.add_handler(GBAN_STATUS)\n\nif STRICT_GBAN: # enforce GBANS if this is set\n dispatcher.add_handler(GBAN_ENFORCER, GBAN_ENFORCE_GROUP)\n","repo_name":"falla-vall/Priscia","sub_path":"priscia/modules/global_bans.py","file_name":"global_bans.py","file_ext":"py","file_size_in_byte":14921,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"40"} +{"seq_id":"73887815481","text":"from exceldef import *\nfrom menudef import *\nimport re\n\nclass Aplicacion():\n ventana = 0\n posx_y = 0\n r_ant = 0\n c_ant = 0\n bcolor = \"blue\"\n fcolor = \"white\"\n\n def __init__(self):\n ''' Construye la ventana principal aplicación '''\n\n self.raiz = Tk()\n self.raiz.geometry('800x300')\n self.raiz.resizable(True, True)\n fecha_actualizado = ver_celda(\"Grapas - Corte de varilla\", 2, 1)\n self.raiz.title(\"NAVE DE GRAPAS Actualizado a \" + fecha_actualizado.strftime('%d %b %Y'))\n\n self.mmat = [[\"\" for x in range(8)] for y in range(10)]\n self.verproducc()\n\n menubar = creamenu(self.raiz)\n self.raiz.config(menu=menubar)\n self.m = Menu(self.raiz, tearoff=0)\n # self.m.add_command(label=\"Historial temperaturas\", command=lambda:menudef.coladasAnteriores(self.raiz))\n self.m.add_command(label=\"Historial temperaturas\", command=lambda: self.abrir(\"Temperaturas\"))\n self.m.add_command(label=\"Fatiga\", command=lambda: self.abrir(\"Fatiga\"))\n self.raiz.mainloop()\n\n def abrir(self, ttitulo):\n ''' Construye una ventana de diálogo '''\n # self.dialogo = Toplevel()\n # Aplicacion.ventana += 1\n Aplicacion.posx_y += 50\n # tamypos = '300x300+' + str(Aplicacion.posx_y) + '+' + str(Aplicacion.posx_y)\n # self.dialogo.geometry(tamypos)\n # self.dialogo.resizable(True, True)\n # ident = self.dialogo.winfo_id()\n\n top = Toplevel()\n top.title(ttitulo)\n top.geometry(\"500x500+\" + str(Aplicacion.posx_y) + '+' + str(Aplicacion.posx_y))\n boton = Button(top, text='Cerrar', command=top.destroy)\n boton.pack(side=BOTTOM, padx=10, pady=10)\n\n # self.raiz.wait_window(self.dialogo)\n\n def verproducc(self):\n self.pon_tit()\n ts, filas = ver_sheets('EstadoProducc', 1, 99)\n\n j = 0 # filas\n i = 0 # columnas\n salef = False\n for tsa in ts:\n for v in tsa:\n bcolor = self.bcolor\n fcolor = self.fcolor\n if v != None:\n if v == 'Skl1':\n bcolor = \"green\"\n if v == 'Skl12':\n bcolor = \"orange\"\n if v != 'Skl12' and v != 'Skl1' and j == 1:\n bcolor = \"red\"\n if v != 0 and j < 8:\n text = 'R%s/C%s' % (i + 3, j)\n b = Label(self.raiz, width=10, background=bcolor, foreground=fcolor, text='{:>10}'.format(v),\n borderwidth=2, relief=\"groove\")\n self.mmat[i][j] = v\n b.grid(row=i + 3, column=j)\n b.bind('', lambda e, text=text: self.handle_click(text))\n b.bind(\"\", self.do_popup)\n else:\n salef = True\n i += 1\n break\n j += 1\n if salef:\n break\n i += 1\n j = 0\n\n def handle_click(self, coorde):\n '''Acciones al cliquear una celda'''\n act = re.findall(r\"R\\d+\", coorde)\n ac1 = act[0].replace(\"R\", \"\")\n ac = int(ac1)\n act = re.findall(r\"C\\d+\", coorde)\n ac2 = act[0].replace(\"C\", \"\")\n bc = int(ac2)\n\n tt = self.mmat[ac - 3][bc]\n tcolada = self.mmat[ac - 3][0]\n b = Label(self.raiz, width=10, background=\"yellow\", foreground=\"black\",\n text='{:>10}'.format(tt), borderwidth=2, relief=\"solid\")\n b.grid(row=ac, column=bc)\n b.bind(\"\", self.do_popup)\n\n if self.r_ant > 0:\n tt_ant = self.mmat[self.r_ant - 3][self.c_ant]\n b = Label(self.raiz, width=10, background=self.bcolor, foreground=self.fcolor, text='{:>10}'.format(tt_ant),\n borderwidth=2, relief=\"groove\")\n b.grid(row=self.r_ant, column=self.c_ant)\n b.bind(\"\", self.do_popup)\n coorde = 'R%s/C%s' % (self.r_ant, self.c_ant)\n b.bind('', lambda e, text=coorde: self.handle_click(coorde))\n\n # celda abajo\n b = Label(self.raiz, width=10, background=\"white\", foreground=\"black\",\n text='{:>10}'.format(tcolada), borderwidth=2, relief=\"solid\")\n b.grid(row=17, column=2)\n\n self.r_ant = ac\n self.c_ant = bc\n\n def do_popup(self, event):\n '''Para poner el menú del botón izquierdo'''\n try:\n self.m.tk_popup(event.x_root, event.y_root)\n finally:\n self.m.grab_release()\n\n def pon_tit(self):\n titulos = ('COLADA', 'TIPO', 'CORTE VAR.', 'URP', 'HORNO', 'INSPECCIÓN', 'PINTURA', 'EXPEDIDOS')\n for i in range(len(titulos)):\n lbl = Label(self.raiz, width=10, background='yellow', foreground='black', text=titulos[i],\n borderwidth=2, relief=\"groove\")\n lbl.grid(column=i, row=1)\n","repo_name":"JLSanGir/VentJL","sub_path":"ventana.py","file_name":"ventana.py","file_ext":"py","file_size_in_byte":5040,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"31363455989","text":"from heap import Heap\n\n\nclass MinHeap(Heap):\n def __init__(self, capacity=10, initial_heap=None):\n Heap.__init__(self, capacity, initial_heap)\n\n def insert(self, item):\n if self.is_full():\n raise Exception(\"MinHeap is full.\")\n \n self.heap[self._next_empty_slot()] = item\n self._percolate_up(self._next_empty_slot())\n self.size += 1\n\n \n def _percolate_up(self, index):\n def swap(li, i1, i2):\n temp = li[i1]\n li[i1] = li[i2]\n li[i2] = temp\n\n if not self._has_parent(index): # do nothing if you reached the top\n return\n if self.heap[index] > self.heap[self._parent_index(index)]: # do nothing if the parent is less than the child\n return\n \n swap(self.heap, index, self._parent_index(index))\n self._percolate_up(self._parent_index(index))\n \n\n def remove_min(self):\n if self.is_empty():\n raise Exception(\"MinHeap is empty.\")\n\n item = self.heap[0]\n self.heap[0] = self.heap[self._next_empty_slot() - 1]\n self.size -= 1\n self._percolate_down(0)\n return item \n\n\n def _percolate_down(self, index):\n def swap(li, i1, i2):\n temp = li[i1]\n li[i1] = li[i2]\n li[i2] = temp\n def min(li, i1, i2):\n if li[i1] < li[i2]:\n return i1\n else:\n return i2\n\n if not self._has_left_child(index): # heap is inserted from left to right, so if there is no left child, the node must be a leaf\n return\n if not self._has_right_child(index): # node is parent of left leaf node only\n if index != min(self.heap, index, self._left_child_index(index)): # left child is smaller than parent\n swap(self.heap, index, self._left_child_index(index)) \n return\n # otherwise the hole has two children\n\n # minimum of parent and two children\n min_index = min(self.heap, index, min(self.heap, self._left_child_index(index), \n self._right_child_index(index)))\n if min_index == self._left_child_index(index): # case where left child is smallest\n swap(self.heap, index, self._left_child_index(index))\n self._percolate_down(self._left_child_index(index))\n elif min_index == self._right_child_index(index): # case where right child is smallest\n swap(self.heap, index, self._right_child_index(index))\n self._percolate_down(self._right_child_index(index))\n\n\n @staticmethod\n def heapify(li):\n def swap(li, i1, i2):\n temp = li[i1]\n li[i1] = li[i2]\n li[i2] = temp\n def percolate_up(li, index):\n parent_index = (index - 1) // 2\n\n if parent_index < 0: return # has no parent\n if li[index] > li[parent_index]: return # parent is smaller\n swap(li, index, parent_index)\n percolate_up(li, parent_index)\n \n for n in range(len(li)):\n percolate_up(li, n)\n \n return li\n\n\ndef main():\n import random as r\n h = MinHeap()\n l = []\n for i in range(10): \n l.append(r.randint(0, 100))\n\n print(f\"Before: {l}\")\n for item in l: \n h.insert(item)\n l = []\n\n while not h.is_empty(): \n l.append(h.remove_min())\n print(f\"After: {l}\")\n\n l = []\n for i in range(11): \n l.append(r.randint(0, 100))\n\n print(f\"\\nBefore: {l}\")\n h = MinHeap(len(l), MinHeap.heapify(l))\n l = []\n while not h.is_empty(): \n l.append(h.remove_min())\n print(f\"After: {l}\")\n\n print(\"\\nThis will cause an exception: \")\n h.remove_min()\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"WillChamness/DataStructuresAndAlgorithms","sub_path":"Heap/min_heap.py","file_name":"min_heap.py","file_ext":"py","file_size_in_byte":3769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"15927781528","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 14 16:32:56 2018\n\n@author: hm1234\n\"\"\"\n\nimport pickle\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.interpolate as interpolate\nfrom mpl_toolkits.mplot3d import Axes3D\n \n###############################################################################\n##### load the pickles\n\nwith open('psi_r_28819.pickle', 'rb') as handle:\n psi_r_28819 = pickle.load(handle)\nwith open('psi_r_30417.pickle', 'rb') as handle:\n psi_r_30417 = pickle.load(handle)\nwith open('psi_rz_28819.pickle', 'rb') as handle:\n psi_rz_28819 = pickle.load(handle)\nwith open('psi_rz_30417.pickle', 'rb') as handle:\n psi_rz_30417 = pickle.load(handle)\n\nwith open('ayc_r_28819.pickle', 'rb') as handle:\n ayc_r_28819 = pickle.load(handle)\nwith open('ayc_ne_28819.pickle', 'rb') as handle:\n ayc_ne_28819 = pickle.load(handle)\nwith open('ayc_te_28819.pickle', 'rb') as handle:\n ayc_te_28819 = pickle.load(handle)\nwith open('ayc_r_30417.pickle', 'rb') as handle:\n ayc_r_30417 = pickle.load(handle)\nwith open('ayc_ne_30417.pickle', 'rb') as handle:\n ayc_ne_30417 = pickle.load(handle)\nwith open('ayc_te_30417.pickle', 'rb') as handle:\n ayc_te_30417 = pickle.load(handle)\n\nwith open('efm_grid_r_28819.pickle', 'rb') as handle:\n efm_grid_r_28819 = pickle.load(handle)\nwith open('efm_grid_z_28819.pickle', 'rb') as handle:\n efm_grid_z_28819 = pickle.load(handle)\nwith open('efm_grid_r_30417.pickle', 'rb') as handle:\n efm_grid_r_30417 = pickle.load(handle)\nwith open('efm_grid_z_30417.pickle', 'rb') as handle:\n efm_grid_z_30417 = pickle.load(handle)\n \n###############################################################################\n##### let's declare some arrays\n\n# 2-dimensional (r,z) at different times\n# psi as function of radius in m\npsi_x = psi_rz_28819['x']\n# psi as function of time in s\npsi_t = psi_rz_28819['time']\n# value of psi at specific radius, time, and z\npsi_dat = psi_rz_28819['data']\n\n# psi grid values\n# same as psi_x\nefm_grid_r = efm_grid_r_28819['data'].squeeze()\n# would be psi_z i.e. z location of flux\nefm_grid_z = efm_grid_z_28819['data'].squeeze()\n\n# channel number vs radius\n# x is the channel number\nayc_r_x = ayc_r_28819['x']\n# t is the time\nayc_r_t = ayc_r_28819['time']\n# dat is the radius correesponding to specific channel number at some time t\nayc_r_dat = ayc_r_28819['data']\n\n# electron temperature data given as a function of time and channel number\n# channel number\nayc_te_x = ayc_te_28819['x']\n# time\nayc_te_t = ayc_te_28819['time']\n# T_e at channel number and time\nayc_te_dat = ayc_te_28819['data']\n\n# arbitrary value to check slices of data\nchk = 20\n# marker size for plotting\nmrk = 2\n\n###############################################################################\n##### do some stuff\n\n# find the z=0 coordinate\nz0_axis = np.where(efm_grid_z == 0)[0][0]\n# define psi only along the z0 axis\npsi_dat_z0 = psi_dat[:,z0_axis,:]\n\n#print('psi_dat_z0 has shape:', psi_dat_z0.shape, 'but want:', ayc_r_dat.shape)\n\n# used to see how good the interpolation is in the time axis\ninterp_test = interpolate.interp1d(psi_t, psi_dat_z0[:,chk],\n kind='cubic', fill_value='extrapolate')\ntest = interp_test(ayc_r_t)\n\n# used to see how good the interpolation is in the radial direction\ninterp_test = interpolate.interp1d(psi_x, psi_dat_z0[chk],\n kind='cubic', fill_value='extrapolate')\ntest2 = interp_test(ayc_r_dat[chk])\n\n#psi_t_interp = []\n#\n#for i in range(0, len(psi_x)):\n# interp_test = interpolate.interp1d(psi_t, psi_dat_z0[:,i], kind='cubic',\n# fill_value='extrapolate')\n# psi_t_interp.append(interp_test(ayc_r_t))\n# \n#psi_t_interp = np.array(psi_t_interp)\n#\n#print('psi_t_interp has shape:', psi_t_interp.shape)\n#\n#psi_x_interp = []\n#\n#for i in range(0, len(psi_t)):\n# interp_test = interpolate.interp1d(psi_x, psi_dat_z0[i], kind='cubic',\n# fill_value='extrapolate')\n# psi_x_interp.append(interp_test(ayc_r_dat[i]))\n# \n#psi_x_interp = np.array(psi_x_interp)\n#\n#print('psi_x_interp has shape:', psi_x_interp.shape)\n\n\n###############################################################################\n##### interpolation\n\n# interpolation of psi data so that it corresponds to the same channel number\n# and time as the electron temperature data\n# perform 2 seperate 1d interpolations. Not ideal but was struggling with 2d\n# interpolation. Have some fun trying scikit learn and knn approach :D\n\npsi_t_interp = []\n\nfor i in range(0, len(psi_x)):\n interp_test = interpolate.interp1d(psi_t, psi_dat_z0[:,i], kind='cubic',\n fill_value='extrapolate')\n psi_t_interp.append(interp_test(ayc_r_t))\n \npsi_t_interp = np.array(psi_t_interp).T\n# psi_t_interp is psi but with same time values as T_e data\n\n#print('psi_t_interp has shape:', psi_t_interp.shape)\n\npsi_x_interp = []\n\nfor i in range(0, psi_t_interp.shape[0]):\n interp_test = interpolate.interp1d(psi_x, psi_t_interp[i], kind='cubic',\n fill_value='extrapolate')\n psi_x_interp.append(interp_test(ayc_r_dat[i]))\n \npsi_x_interp = np.array(psi_x_interp)\n# psi_t_interp is psi but with same channel number values as T_e data\n# since the time data is also the same the outputted array should be the\n# correct shape\n\npsi_dat_z0_new = psi_x_interp\n\n#print('psi_x_interp has shape:', psi_x_interp.shape)\n\n###############################################################################\n##### some mapping?\n\n# after interpolation we have psi and T_e at the same channel numbers and time\n# just gotta map channel number to psi. easy right? :'( \n\ntme = ayc_te_t\npsi_ch = np.linspace(1, len(ayc_te_x), len(ayc_te_x))\n\na = np.ndarray.flatten(ayc_te_dat)\nb = np.ndarray.flatten(psi_dat_z0_new)\n#\nTe_grd = ayc_te_dat\n#\n#for i in range(0, len(ayc_te_t)):\n# for j in range(0, len(ayc_te_t)):\n# Te_grd[i][j] = psi_dat_z0_new[i][j]\n\n#fig = plt.figure()\n#ax = fig.gca(projection='3d')\n#for i in range(0, len(tme)):\n# ax.plot(psi_dat_z0_new[i], ayc_te_dat[i])\n\n\n\n\n\n###############################################################################\n##### plotting\n\nplt.figure()\nplt.contourf(tme, psi_ch, ayc_te_dat.T, 33)\nplt.colorbar()\nplt.xlabel('time (s)')\nplt.ylabel('channel number')\nplt.title('$T_{e}$')\n\nplt.figure()\nplt.contourf(tme, psi_ch, psi_dat_z0_new.T, 33)\nplt.colorbar()\nplt.xlabel('time (s)')\nplt.ylabel('channel number')\nplt.title('psi_new at z=0')\n\nplt.figure()\nplt.plot(psi_ch, psi_dat_z0_new[chk])\nplt.xlabel('channel number')\nplt.ylabel('$\\Psi$', rotation=0)\n\nplt.figure()\nplt.plot(psi_ch, ayc_te_dat[chk])\nplt.xlabel('channel number')\nplt.ylabel('$T_{e}$', rotation=0)\n\nplt.figure()\nplt.plot(psi_dat_z0_new[chk,:], ayc_te_dat[chk,:])\nplt.xlabel('$\\Psi$')\nplt.ylabel('$T_{e}$', rotation=0)\n\n#plt.figure()\n#plt.contour(efm_grid_r, efm_grid_z, psi_dat[chk,:,:], 33)\n#plt.axis('equal')\n#plt.colorbar()\n#plt.ylabel('z (m)')\n#plt.xlabel('radial position (m)')\n#plt.title('$\\Psi (r,z)$')\n#\n#plt.figure()\n#plt.contourf(psi_x, psi_t, psi_dat_z0, 33)\n#plt.colorbar()\n#plt.ylabel('time (s)')\n#plt.xlabel('radial position (m)')\n#plt.title('psi at z=0')\n#\n#plt.figure()\n#plt.contour(psi_dat_z0, 33)\n#\n#plt.figure()\n#plt.contour(psi_dat_z0_new, 33)\n#\n#plt.figure()\n#plt.plot(ayc_r_x, ayc_r_dat[chk])\n#plt.xlabel('radial index (channel number)')\n#plt.ylabel('radial position (m)')\n#\n#plt.figure()\n#plt.plot(psi_t, psi_dat_z0[:,chk], 'bx', ms=mrk)\n#plt.plot(ayc_r_t, test, 'ro', ms=mrk)\n#plt.xlabel('time (s)')\n#plt.ylabel('$\\Psi$', rotation=0)\n#\n#plt.figure()\n#plt.plot(psi_x, psi_dat_z0[chk], 'bx', ms=mrk)\n#plt.plot(ayc_r_dat[chk], test2, 'ro', ms=mrk)\n#plt.xlabel('radial position (m)')\n#plt.ylabel('$\\Psi$', rotation=0)\n\n\n###############################################################################\n##### Fancy animations\n\n#for i in range(0, psi_rz_28819['time'].shape[0]):\n# fig = plt.figure()\n# plt.contour(efm_grid_r.squeeze(), efm_grid_z.squeeze(),\n# psi_dat[i,:,:], 50)\n# plt.colorbar()\n# plt.ylabel('z (m)')\n# plt.xlabel('radial position (m)')\n# plt.title('$\\Psi (r,z)$')\n# print(i)\n# plt.savefig(str(i).zfill(4) +'.png')\n# plt.close(fig)\n\n#for i in range(0, len(tme)):\n# fig = plt.figure()\n# plt.plot(psi_dat_z0_new[i], ayc_te_dat[i])\n# plt.xlabel('$\\Psi$')\n# plt.ylabel('$T_{e}$', rotation=0)\n# plt.title('$T_{e}$ vs $\\Psi$')\n# print(i)\n# plt.savefig(str(i).zfill(4) +'.png')\n# plt.close(fig)\n\nplt.show()\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"hahahasan/MSc-pre-process","sub_path":"initial_freia/mapping_old/mapping1.py","file_name":"mapping1.py","file_ext":"py","file_size_in_byte":8629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"40928020049","text":"\"\"\"\ntime complexity: O(logn)\nspace complexity: O(1)\n\"\"\"\n\ndef binary_search(arr, target):\n left, right = 0, len(arr) - 1\n\n while left <= right:\n mid = left + (right - left) // 2 # Calculate the middle index\n if arr[mid] == target:\n return mid # Target found at index 'mid'\n elif arr[mid] < target:\n left = mid + 1 # Search the right half\n else:\n right = mid - 1 # Search the left half\n\n return -1 # Target not found\n\n# Example usage:\narr = [1, 2, 3, 4, 5, 6, 7, 8, 9]\ntarget = 6\nresult = binary_search(arr, target)\nif result != -1:\n print(f\"Element found at index {result}\")\nelse:\n print(\"Element not found\")\n\n","repo_name":"aruzhanpjo/Data-Structures-Algorithms-Python","sub_path":"003_SearchingAlgorithms/03_binarySearch.py","file_name":"03_binarySearch.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"43767511426","text":"import csv\r\nwith open('year2017.csv') as file_obj:\r\n file_data = csv.reader(file_obj)\r\n csv_list = list(file_data)\r\n wounded = []\r\n for row in csv_list[1:]:\r\n val = row[10]\r\n if row[10] != '':\r\n wounded.append(float(val))\r\n print(int(sum(wounded)))\r\n ","repo_name":"AvishekRoy16/Data-Science","sub_path":"1-Working With Files/Total-Wounded.py","file_name":"Total-Wounded.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"9488889927","text":"from glob import glob\nimport numpy as np\n\ndef get_graph_structure(adj_matrix, threshold=None):\n if adj_matrix.ndim != 3 or adj_matrix.shape[0] != adj_matrix.shape[1] or adj_matrix.shape[2] != 1:\n raise ValueError(\"Input matrix must be of shape N x N x 1\")\n\n adj_matrix = adj_matrix[:, :, 0] # Convert the input matrix to 2D (N x N)\n\n # Only keep the top N entries\n if threshold != None:\n sorted_arr = np.sort(adj_matrix.flatten())\n threshold = sorted_arr[-threshold]\n adj_matrix[adj_matrix 1383645272 & category = 0 & total_rating > 80 & platforms = 48; sort total_rating desc;'\n )\n\nmy_json = byte_array.decode('utf8').replace(\"'\", '\"')\n\ndata = json.loads(my_json)\nfor game in data:\n if (not game[\"id\"] in game_id_list):\n game_id_list.append(game[\"id\"])\n\n\n\n\nbyte_array = wrapper.api_request(\n 'games',\n 'fields id, name, total_rating; limit 25; offset 0; where first_release_date > 1383645272 & category = 0 & total_rating > 80 & platforms = {34,39}; sort total_rating desc;'\n )\n\nmy_json = byte_array.decode('utf8').replace(\"'\", '\"')\n\ndata = json.loads(my_json)\nfor game in data:\n if (not game[\"id\"] in game_id_list):\n game_id_list.append(game[\"id\"])\n\n\nbyte_array = wrapper.api_request(\n 'games',\n 'fields id, name, total_rating; limit 15; offset 0; where first_release_date > 1383645272 & category = 0 & total_rating > 80 & platforms = 167; sort total_rating desc;'\n )\n\nmy_json = byte_array.decode('utf8').replace(\"'\", '\"')\n\ndata = json.loads(my_json)\nfor game in data:\n if (not game[\"id\"] in game_id_list):\n game_id_list.append(game[\"id\"])\n\n\nbyte_array = wrapper.api_request(\n 'games',\n 'fields id, name, total_rating; limit 15; offset 0; where first_release_date > 1383645272 & category = 0 & total_rating > 5 & platforms = {6,167,169}; sort total_rating desc;'\n )\n\nmy_json = byte_array.decode('utf8').replace(\"'\", '\"')\n\ndata = json.loads(my_json)\nfor game in data:\n if (not game[\"id\"] in game_id_list):\n game_id_list.append(game[\"id\"])\n\n\nbyte_array = wrapper.api_request(\n 'games',\n 'fields id, name, total_rating; limit 30; offset 0; where first_release_date > 1383645272 & category = 0 & total_rating > 5 & platforms = {6,48,49}; sort total_rating desc;'\n )\n\nmy_json = byte_array.decode('utf8').replace(\"'\", '\"')\n\ndata = json.loads(my_json)\nfor game in data:\n if (not game[\"id\"] in game_id_list):\n game_id_list.append(game[\"id\"])\n\nprint(len(game_id_list))\n\nfile = open(\"game_ids.txt\", \"w\")\nfor game_id in game_id_list:\n file.write(str(game_id) + \"\\n\")\n \nfile.close()\nexit()\n\n\nmy_json = byte_array.decode('utf8').replace(\"'\", '\"')\n#print(my_json)\n#print('- ' * 20)\n\n# Load the JSON to a Python list & dump it back out as formatted JSON\ndata = json.loads(my_json)\nfor game in data:\n print(game[\"id\"])\ns = json.dumps(data, indent=4, sort_keys=True)\nfile = open(\"games.json\", \"w\")\nfile.write(s)\nfile.close()\nexit()\n\nbyte_array = wrapper.api_request(\n 'platforms',\n 'fields id, name; limit 500; offset 0; sort id asc;'\n )\n# parse into JSON however you like...\n\nplatforms_json = json.loads(byte_array)\nfile = open('platforms.json', 'w')\njson.dump(platforms_json, file)\nfile.close()\n\n\n\nbyte_array = wrapper.api_request(\n 'covers',\n 'fields id, url; offset 0; where id=105006;'\n )\n\nprint(json.loads(byte_array))\n\ngenres_byte_array = wrapper.api_request(\n 'genres',\n 'fields id, name; limit 100;'\n )\n\n\ngenres_json = json.loads(genres_byte_array)\nfile = open('genres.json', 'w')\njson.dump(genres_json, file)\nfile.close()\n\n\n# Protobuf API request\n\"\"\"\nbyte_array = wrapper.api_request(\n 'games.pb', # Note the '.pb' suffix at the endpoint\n 'fields id, name; offset 0; where platforms=48;'\n )\ngames_message = GameResult()\ngames_message.ParseFromString(byte_array) # Fills the protobuf message object with the response\n\"\"\"\n\n","repo_name":"GameInn36/data-wrapper","sub_path":"game_id_extractor.py","file_name":"game_id_extractor.py","file_ext":"py","file_size_in_byte":3890,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"25312354786","text":"import sys\n\nabstring=list(sys.stdin.readline().strip())\n\n#a의 개수만큼 연속 a string이 있어야 함!\nnumberofa=abstring.count('a')\n\nmin=1e9\nfor i in range(len(abstring)):\n if i+numberofa<=len(abstring):\n searchArr=abstring[i:i+numberofa]\n change=searchArr.count('b')\n if change=self.pos.x+values[0][0] and cursor.pos.x<=self.pos.x+values[1][0] and cursor.pos.y>=self.pos.y+values[0][1] and cursor.pos.y<=self.pos.y+values[1][1] and not self.isFrozen and cursor.eventType=='left' and cursor.isClicking:\r\n self.pressState = state\r\n break\r\n else:\r\n self.pressState = 'None'\r\n else:\r\n self.pressState = 'None'\r\n \r\n def draw(self,screen):\r\n Shape.draw(self,screen)\r\n screen.blit(states[self.pressState], self.pos.toTuple()) \r\n\r\n def get_showWhenRunning(self):\r\n return True\r\n\r\n def get_type(self):\r\n return 'Shape.PressButton'","repo_name":"touchard-trophees-nsi/trophees-nsi","sub_path":"scripts/components/input/directionalButton.py","file_name":"directionalButton.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"31447359928","text":"#!/usr/bin/env python\n#Author = Lee Yeong Hui\n\nfrom pprint import pprint \nfrom jnpr.junos import Device\nfrom os.path import dirname, join\nfrom datetime import datetime\nimport getpass\nimport yaml\nimport sys\n\ntry:\n userID = raw_input(\"Enter username: \")\nexcept: \n userID = input(\"Enter username: \")\nuserPW = getpass.getpass(\"Enter password: \")\n\n# Get relative directory \ncurrentDir = dirname(__file__)\n\n# Get hosts.yml relative directory \nfilePath = join(currentDir, \"hosts.yml\")\n\n# Read hosts.yml\nwith open(filePath, 'r') as rd:\n\thosts = yaml.load (rd.read())\n\n# Get versions.yml relative directory\nfilePath = join(currentDir, \"versions.yml\")\n\n# Read versions.yml \nwith open(filePath,'r') as rd: \n versions = yaml.load (rd.read())\n\naListofDevice = []\n# Connect to each device to get data \nfor host in hosts: \n try:\n print('Collecting data on ' + host)\n #use port 22 if 830 does not work/set system services netconf ssh is not configured\n dev = Device(host=host, user=userID, password=userPW, port=\"22\") \n dev.open()\n # print all facts\n #pprint(dev.facts)\n aDevice = {\n 'model' : dev.facts['model'], \n 'hostname' : dev.facts['hostname'],\n 'serialnumber' : dev.facts['serialnumber'],\n 'uptime' : dev.facts['RE0']['up_time'],\n 'cursoftware' : dev.facts['version'],\n 'desiresoftware' : '',\n 'softwarechangerequired' : 'yes'\n }\n print ('Data collected from ' + host)\n aListofDevice.append(aDevice)\n except Exception as e:\n print (e)\n\n# compare versions \nfor device in aListofDevice:\n for model in versions:\n if model['model'] == device['model']:\n device['desiresoftware'] = model['version']\n if model['version'] == aDevice['cursoftware']:\n device['softwarechangerequired'] = 'no' \n\n# print output on terminal \nprint ('\\n\\nTotal hosts were checked: %d' % (len(hosts)))\nprint ('-' * 200)\nprint ('HOSTNAME\\t\\t\\tMODEL\\t\\tS/NUMBER\\t\\tCURRENT_SW\\t\\tDESIRE_SW\\tSOFTWARE_CHG_REQUIRED\\tUPTIME')\nprint ('-' * 200)\n\n# print output to txt\n# get current date time \ncurrentDateTime = datetime.now()\n# Get hosts.yml relative directory \nfileName = '{:%d-%b-%y-%H-%M}-getfacts.txt'.format(currentDateTime)\nfilePath = join(currentDir, fileName)\noutputFile = open(filePath,\"w\")\noutputFile.write ('Total hosts were checked: %d\\n' % (len(hosts)))\noutputFile.write ('-' * 200 + '\\n')\noutputFile.write('HOSTNAME\\t\\t\\tMODEL\\t\\tS/NUMBER\\t\\tCURRENT_SW\\t\\tDESIRE_SW\\tSOFTWARE_CHG_REQUIRED\\tUPTIME\\n')\noutputFile.write ('-' * 200 + '\\n')\n\n# for device in sorted(aListofDevice, key = lambda i:i['softwarechangerequired']): / list no software change required first \n# reverse direction / list need software change required first \nfor device in sorted(aListofDevice, key = lambda i:i['softwarechangerequired'], reverse=True):\n print ('%s\\t\\t%s\\t\\t%s\\t\\t%s\\t\\t%s\\t\\t%s\\t\\t%s' % (device['hostname'], device['model'], device['serialnumber'], device['cursoftware'], device['desiresoftware'], device['softwarechangerequired'], device['uptime']))\n outputFile.write('%s\\t\\t%s\\t\\t%s\\t\\t%s\\t\\t%s\\t\\t%s\\t\\t%s\\n' % (device['hostname'], device['model'], device['serialnumber'], device['cursoftware'], device['desiresoftware'], device['softwarechangerequired'], device['uptime']))\nprint ('-' * 200)\n\n# close outputFile\noutputFile.close()","repo_name":"leeyeonghui/getfacts_checkversion_recommendupgrade","sub_path":"getfacts_cv_ru.py","file_name":"getfacts_cv_ru.py","file_ext":"py","file_size_in_byte":3395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"26541929730","text":"from pyfirmata import Arduino, SERVO, OUTPUT, util\nimport time\n\nport = \"COM6\"\nled = 12\nboard = Arduino(port)\nboard.digital[led].mode = OUTPUT\nbuzzer = 10\nbuzzer = board.get_pin(f'd:{buzzer}:o')\n\ndef finalOutput(pin,value):\n board.digital[led].write(value)\n\n\ndef blink(led):\n count = 0\n while True:\n count +=1\n\n for i in range(1,101):\n if i % 2 != 0:\n value = 1\n finalOutput(led,value)\n buzzer.write(0)\n time.sleep(0.001)\n else:\n value = 0\n finalOutput(led,value)\n buzzer.write(1)\n time.sleep(0.002)\n# blink(led)\n\ndef blink2():\n count = 0\n while True:\n count +=1\n print(count,end=\"\")\n\n if count == 101:\n buzzer.write(1)\n break\n\n for i in range(1,101):\n if i % 3 == 0:\n buzzer.write(1)\n time.sleep(1)\n elif i % 5 == 0:\n buzzer.write(0)\n time.sleep(0.4)\n else:\n buzzer.write(0)\n time.sleep(0.01)\n\n# blink2()\n \n\nfor i in range(1,51):\n if i % 2 == 0:\n blink(led)\n time.sleep(5)\n else:\n blink2()\n time.sleep(9)\n","repo_name":"03prashantpk/Arduino---Projects","sub_path":"Basic/arduino_basic.py","file_name":"arduino_basic.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"42601514717","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\n\r\n\r\ndef __if_number_get_string(number):\r\n converted_str = number\r\n if isinstance(number, int) or \\\r\n isinstance(number, float):\r\n converted_str = str(number)\r\n return converted_str\r\ndef get_unicode(strOrUnicode, encoding='utf-8'):\r\n strOrUnicode = __if_number_get_string(strOrUnicode)\r\n if isinstance(strOrUnicode, unicode):\r\n return strOrUnicode\r\n return unicode(strOrUnicode, encoding, errors='ignore')\r\n\r\n\r\ndef get_string(strOrUnicode, encoding='utf-8'):\r\n strOrUnicode = __if_number_get_string(strOrUnicode)\r\n if isinstance(strOrUnicode, str):\r\n return strOrUnicode.encode(encoding)\r\n return strOrUnicode\r\ndef CleanText(textt):\r\n inStr = textt\r\n try:\r\n return str(inStr)\r\n except:\r\n pass\r\n outStr = \"\"\r\n for i in inStr:\r\n try:\r\n outStr = outStr + str(i)\r\n except:\r\n if unicodeToAsciiMap.has_key(i):\r\n outStr = outStr + unicodeToAsciiMap[i]\r\n else:\r\n outStr = outStr + \"_\"\r\n return outStr\r\n\r\n\r\n\r\ndef ReadURL(url):\r\n # URL = 'https://www.monster.com/jobs/search/?q=Software-Developer&where=Australia'\r\n # URL = 'https://www.pinterest.com/justin_jaro/character-design/'\r\n\r\n page = requests.get(url)\r\n # soup = BeautifulSoup(page.content, 'html.parser')\r\n # soup = BeautifulSoup(page.content, 'html.parser')\r\n soup = BeautifulSoup(page.content, 'lxml')\r\n # results = soup.find_all(class_='Collection')\r\n # images = soup.findAll(\"img\", {\"class\": \"GrowthUnauthPinImage__Image\"}) \r\n # titleinfo = soup.findAll(\"h1\", {\"data-test-id\": \"UnauthBestPinCardTitle\"}) \r\n results = soup.find_all('div', class_='Hvp Jea MtH sLG zI7 iyn Hsu')\r\n # titleinfo = soup.findAll(\"div\",attrs={\"class\":\"Hvp Jea MtH sLG zI7 iyn Hsu\"})\r\n div = soup.select('div.iyn')\r\n\r\n # titleinfo = soup.prettify().encode('utf-8').decode('ascii', 'ignore')\r\n # titleinfo = soup.select('[data-test-id=\"UnauthBestPinCardTitle\"]')\r\n imagesb = soup.find(\"div\", {\"data-test-id\": \"pin-closeup-image\"}) \r\n imagess = []\r\n imageinfo = {}\r\n print(imagesb)\r\n for image in imagesb:\r\n newimagee = []\r\n imagesc = image.findAll(\"a\")\r\n imagesource = image.find(\"img\" )\r\n imageinfo = {\"Url\",imagesource[\"src\"].encode('utf-8').decode('ascii', 'ignore'),\r\n \"Caption\",imagesource[\"alt\"].encode('utf-8').decode('ascii', 'ignore'),\r\n \r\n }\r\n newimagee.append(imagesc[0][\"title\"].encode('utf-8').decode('ascii', 'ignore'))\r\n newimagee.append(imagesource[0][\"alt\"].encode('utf-8').decode('ascii', 'ignore'))\r\n newimagee.append(imagesource[0][\"src\"].encode('utf-8').decode('ascii', 'ignore'))\r\n imagess.append(newimagee)\r\n \r\n print(imageinfo)\r\n # print(str(get_string(imagess[0][0]), 'UTF-8'))\r\n # print(str(get_string(imagess[0][1]), 'UTF-8'))\r\n # print(str(get_string(imagess[0][2]), 'UTF-8'))\r\n\r\n # print(imagess[0][0].encode('ascii', 'ignore'))\r\n # results = soup.find_all('img', class_='.GrowthUnauthPinImage__Image')\r\n # results = soup.find_all('img', class_='.GrowthUnauthPinImage__Image')\r\n # print(results)\r\n return imagess\r\n\r\n \r\nif __name__ == '__main__':\r\n print(\"Read Board is Main\")\r\n ReadURL('https://www.pinterest.com/pin/384776361909475578/')\r\n# job_elems = results.find_all('section', class_='card-content')\r\n\r\n","repo_name":"vltmedia/ArtSpire_Pinterest_Scraper","sub_path":"python/ReadPin.py","file_name":"ReadPin.py","file_ext":"py","file_size_in_byte":3499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"21325223492","text":"import os\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nfrom unittest import result\r\n\r\ndata_dir = '/content/drive/MyDrive/SPM_model_train_eval/DSECompanyData'\r\n\r\n################ Just chnage start and end index ##############\r\nstart_index = 149\r\nend_index = 150\r\n##########################################\r\n\r\ndata_files = os.listdir(data_dir)[start_index:end_index] #'ACI.csv'\r\n\r\n# print(type(data_files))\r\n# print(data_files[:2])\r\nprint('data files: ', data_files)\r\n\r\nnum_classes = 2\r\nclass_names = ['closing_price', 'volume']\r\ntrain_test_ratio = .10\r\nwindow = 100\r\n\r\nEPOCHS = 100\r\nBATCH_SIZE = 32\r\n\r\n# optimizer = \"sgd\"\r\noptimizer_fn = \"adam\"\r\n# optimizer = \"rmsprop\"\r\nloss_fn = 'mse'\r\n\r\nlearning_rate = 0.01\r\nmomentum = 0.9\r\nmodel_name = \"CNN\"\r\n\r\n# paths and directories\r\nresult_dir = '/content/drive/MyDrive/SPM_model_train_eval/results'\r\n\r\n\r\n# train_dir = \"/content/Dog_vs_Cat/train\"\r\n# valid_dir = \"/content/Dog_vs_Cat/valid\"\r\n# test_dir = \"/content/Dog_vs_Cat/test\"\r\nscaler = MinMaxScaler(feature_range=(0,1))\r\n\r\nversion = '1.0'\r\n","repo_name":"sadikul1500/Machine-Learning","sub_path":"DSE_Market_Prediction/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"72562054521","text":"import paho.mqtt.client as mqtt\nimport json\n# import time, datatime\nimport time\nfrom datetime import datetime\n\nbroker = '127.0.0.1'\nport = 1883\n\nSET_1_TOPIC = \"AquaFarm/Set1\"\n\ndef connect_mqtt():\n def on_connect(client, userdata, flags, rc):\n if rc == 0:\n print(\"Connected to MQTT Broker!\")\n else:\n print(\"Failed to connect, return code %d\\n\", rc)\n # Set Connecting Client ID\n client = mqtt.Client(client_id=\"Set1Subscriber\")\n client.username_pw_set(username=\"Subscriber1\",password=\"Subscriber11234\")\n client.on_connect = on_connect\n client.connect(broker, port)\n # client.enable_logger(logger=MQTT_LOG_DEBUG)\n return client\n\ndef subscribe(client: mqtt):\n def on_message(client, userdata, msg):\n print(\"===================================================\")\n print(datetime.now())\n print(msg.topic, \": \", msg.payload)\n hexString = \"\"\n valueObject = {}\n topic = \"\"\n for i in range(len(msg.payload)):\n variable = hex(msg.payload[i])[2:]\n if ( len(variable) == 1 ):\n hexString += \"0\" + variable\n else:\n hexString += hex(msg.payload[i])[2:]\n if(hexString[:2] == \"0f\"):\n EChexString = hexString\n EC = round(int(EChexString[6:14], 16) * 0.1/ 10, 2)\n topic = msg.topic + \"/EC/Value\"\n valueObject[\"EC\"] = EC\n if(hexString[:2] == \"0a\"):\n PHhexString=PHhexString = hexString\n PH = round(int(PHhexString[6:10], 16) * 0.1 / 10, 2)\n topic = msg.topic + \"/Ph/Value\"\n valueObject[\"PH\"] = PH\n if(hexString[:2] == \"01\"):\n WaterTemphexString = hexString\n WaterTemp = round(int(WaterTemphexString[6:10], 16) / 100 - 50, 2)\n topic = msg.topic + \"/WaterTemp/Value\"\n valueObject[\"WaterTemp\"] = WaterTemp\n if (topic and valueObject):\n client.publish(topic, json.dumps(valueObject))\n print(topic, valueObject)\n MQTT_TOPIC = [(SET_1_TOPIC, 1)]\n client.subscribe(MQTT_TOPIC)\n client.on_message = on_message\n\ntry:\n time.sleep(20)\n print(datetime.now())\n client = connect_mqtt()\n subscribe(client)\n client.loop_forever()\nexcept Exception as ex:\n print(\"exception\")\n print(ex)\n pass\n","repo_name":"justinlctstudy96/aquafarm_doc","sub_path":"AWS_EC2/mqtt/mqtt_set1_subscribe.py","file_name":"mqtt_set1_subscribe.py","file_ext":"py","file_size_in_byte":2343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"10789278815","text":"# Time: O(n)\n# Space: O(1)\n\nclass Solution(object):\n def countGoodRectangles(self, rectangles):\n \"\"\"\n :type rectangles: List[List[int]]\n :rtype: int\n \"\"\"\n result = mx = 0\n for l, w in rectangles:\n side = min(l, w)\n if side > mx:\n result, mx = 1, side\n elif side == mx:\n result += 1\n return result\n","repo_name":"kamyu104/LeetCode-Solutions","sub_path":"Python/number-of-rectangles-that-can-form-the-largest-square.py","file_name":"number-of-rectangles-that-can-form-the-largest-square.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","stars":4314,"dataset":"github-code","pt":"40"} +{"seq_id":"1053297254","text":"\"\"\"\n@File : 显示图像情形2.py\n\n@Author: sivan Wu\n\n@Date : 2020/1/11 10:44 上午\n\n@Desc : 显示图像.py中我们首先读取图像之后才将创建窗口将图像送进去,现在我们可以先创建窗口,再将读取的图像送入\n建 议:一 种 特 殊 的 情 况 是, 你 也 可 以 先 创 建 一 个 窗 口, 之 后 再 加 载 图 像。 这 种 情 况 下,\n你 可 以 决 定 窗 口 是 否 可 以 调 整 大 小。 使 用 到 的 函 数 是 cv2.namedWindow()。 初 始 设 定 函 数\n标 签 是 cv2.WINDOW_AUTOSIZE。 但 是 如 果 你 把 标 签 改 成 cv2.WINDOW_NORMAL, 你就可以调整窗口大小了。\n当图像维度太大, 或者要添加轨迹条时,调整窗口大小将会很有用\n\"\"\"\n\n\nimport cv2\n\nIMAGE_PATH = \"../data/timg.jpeg\"\nimage_gray = cv2.imread(IMAGE_PATH, cv2.IMREAD_GRAYSCALE) # cv2.IMREAD_GRAYSCALE = 0\ncv2.namedWindow(\"win_name\", cv2.WINDOW_AUTOSIZE)\ncv2.imshow(\"win_name\", image_gray)\ncv2.waitKey(0)\ncv2.destroyWindow(\"win_name\")\n\n\n\n","repo_name":"sivanWu0222/OpenCV_Python","sub_path":"Chapter 4/显示图像情形2.py","file_name":"显示图像情形2.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"11410873323","text":"from flask import Flask, render_template, request\nfrom keras.models import load_model\nfrom keras_preprocessing.image import load_img\nfrom keras_preprocessing.image import img_to_array\nfrom keras.applications.vgg16 import preprocess_input\nimport numpy as np\n\n\napp = Flask(__name__)\n\n\n# model.make_predict_function()\n\n\ndef predict_label(img_path):\n model = load_model('model_3.h5')\n image = load_img(img_path, target_size=(240, 320))\n # convert the image pixels to a numpy array\n image = img_to_array(image)\n # reshape data for the model\n # image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))\n # Expand dimentions only for vgg\n image = np.expand_dims(image, axis=0)\n # prepare the image for the VGG model only\n # image = preprocess_input(image)\n # predict the probability across all output classes\n label = model.predict(image)\n print(label)\n label_list = []\n if label[0][0] == 1:\n result_0 = 'Eosinophil'\n label_list.append(result_0)\n if label[0][1] == 1:\n result_1 = 'Lymphocyte'\n label_list.append(result_1)\n if label[0][2] == 1:\n result_2 = 'Monocyte'\n label_list.append(result_2)\n\n if label[0][3] == 1:\n result_3 = 'Neutrophil'\n label_list.append(result_3)\n return label_list\n\n\n# Flask\n# routes\n@app.route(\"/\", methods=['GET', 'POST'])\ndef main():\n return render_template(\"index.html\")\n\n\n@app.route(\"/about\")\ndef about_page():\n return \"Please subscribe Artificial Intelligence Hub..!!!\"\n\n\n@app.route(\"/submit\", methods=['GET', 'POST'])\ndef get_output():\n if request.method == 'POST':\n img = request.files['my_image']\n img_path = \"static/\" + img.filename\n img.save(img_path)\n\n pr = predict_label(img_path)\n for i in pr:\n print(i)\n\n return render_template(\"index.html\", prediction=pr, img_path=img_path)\n\n\nif __name__ == '__main__':\n # app.debug = True\n app.run(debug=True)\n","repo_name":"DevMed22/Summer-training-22","sub_path":"AI/Blood-cells-detection/flask-app.py","file_name":"flask-app.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"12276219360","text":"from ListNode import ListNode, listNodeList\n\n\"\"\"\nMerge two sorted linked lists and return it as a new list.\nThe new list should be made by splicing together the nodes of the first two lists.\n\nExample:\n\nInput: 1->2->4, 1->3->4\nOutput: 1->1->2->3->4->4\n\"\"\"\nclass Solution:\n def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n dummy = ListNode(0)\n cur = dummy\n while l1 is not None and l2 is not None:\n if l1.val<=l2.val:\n cur.next = l1\n cur, l1 = cur.next, l1.next\n else:\n cur.next = l2\n cur, l2 = cur.next, l2.next\n if l1 is not None:\n cur.next = l1\n if l2 is not None:\n cur.next = l2\n return dummy.next\n\nif __name__==\"__main__\":\n l1 = listNodeList([1,2,4])\n l2 = listNodeList([1,3,4])\n tmp = MergeTwoSortedLists()\n result = tmp.mergeTwoLists(l1, l2)\n print(result)\n","repo_name":"ellinx/LC-python","sub_path":"MergeTwoSortedLists.py","file_name":"MergeTwoSortedLists.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"1554151116","text":"# This is a sample Python script.\r\n\r\nimport os\r\nimport logging\r\nimport other_tasks\r\nimport tele_bot_task\r\nimport twitter_task_con\r\nimport withdrawal_conversation\r\nfrom big_text import *\r\nfrom do_other import *\r\n# import join_group_con\r\nfrom telegram.ext import *\r\nfrom telegram.replykeyboardmarkup import ReplyKeyboardMarkup\r\n\r\n# from operations import withdraw, is_valid\r\n# from tronpy import Tron\r\n\r\nlogging.basicConfig(\r\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\r\n level=logging.INFO)\r\n\r\n\r\ndef start(update, context):\r\n sender = update.message.reply_text\r\n chat_id = update.message.chat_id\r\n username = update.message.chat.username\r\n text = update.message.text\r\n if str(username) == \"None\":\r\n sender(\"No username found for your account\")\r\n sender(\"Please set username for your telegram\\n\"\r\n \"1)Go telegram account settings\\n\"\r\n \"2)Click username\\n\"\r\n \"3)Set unique and simplified username\")\r\n else:\r\n checking_exist = mydb[\"people\"]\r\n bot.sendMessage(chat_id=chat_id, text=\"This KMC TRX earning bot\\n\"\r\n \"You can earn TRX by doing tasks\\n\"\r\n \"Also You can create task for other to do\\n\\n\")\r\n\r\n main_buttons(update, context)\r\n for i in checking_exist.find({}):\r\n if username == i[\"username\"]:\r\n break\r\n else:\r\n link = f\"https://telegram.me/earn_trx_ind_bot?start={chat_id}\"\r\n checking_exist.insert_one({\"_id\": chat_id, \"username\": username, \"referral\": link,\r\n \"ref_count\": 0, \"TRX_balance\": 0.0, \"ref_income\": 0.0,\r\n 'earned_total': 0.0, 'payout_avail': 0.0, \"ref_by\": \"None\"})\r\n bot.sendMessage(chat_id=1291659507, text=\"New user found @\" + str(username))\r\n referal(text, username, chat_id)\r\n\r\n\r\ndef referal(text, username, chat_id):\r\n get_id = text.replace(\"/start\", '')\r\n if len(get_id) > 0:\r\n ref = mydb[\"people\"]\r\n try:\r\n get = ref.find_one({\"_id\": int(get_id)})\r\n get_invitee = get[\"_id\"]\r\n ref.update_one({\"_id\": get_invitee}, {\"$inc\": {\"ref_count\": 1}})\r\n ref.update_one({\"_id\": chat_id}, {\"$set\": {'ref_by': get_invitee}})\r\n bot.sendMessage(chat_id=get_invitee, text=f\"You got new referral: @{username}\")\r\n except:\r\n pass\r\n\r\n\r\ndef msg_hand(update, context):\r\n chat_id = update.message.chat_id\r\n # username = update.message.chat.username\r\n sender = update.message.reply_text\r\n text = update.message.text\r\n if 'Do Task💸' == text:\r\n task_page(update, context, text=\"Choose task method!\")\r\n elif \"Proof task📥\" == text:\r\n task_list(update, context)\r\n elif 'Balance⚖' == text:\r\n people = mydb['people']\r\n get = people.find_one({'_id': chat_id})\r\n bot.sendMessage(chat_id=chat_id, text=f\"Balance: {get['TRX_balance']} TRX\\n\\n\"\r\n f\"Total Earned: {get['earned_total']} TRX\\n\\n\"\r\n f\"Available for payout:\\n\"\r\n f\"{get['payout_avail']} TRX\",\r\n reply_to_message_id=update.message.message_id)\r\n elif 'Deposit➕' == text:\r\n bot.sendMessage(chat_id=chat_id, text=\"Send TRX to this address(TRC-20):\\n\"\r\n \"TSPZcEraokyNAuFR4Shgyn5D4ycsWjJhrL\\n\\n\"\r\n \"Then send TXID of your transaction\\n\\n\"\r\n \"After transaction fill below google form:\\n\"\r\n \"https://surveyheart.com/form/626a84d84a8aaf49225347e7\\n\\n\"\r\n \"NEWS: Auto deposit will be enabled SOON\",\r\n parse_mode=\"html\", reply_to_message_id=update.message.message_id)\r\n\r\n elif 'Referral link📎' == text:\r\n get_link = mydb['people']\r\n get = get_link.find_one({\"_id\": chat_id})\r\n bot.sendMessage(chat_id=chat_id, text=f\"Your referral count: {get['ref_count']}\\n\\n\"\r\n f\"You have earned {get['ref_income']} TRX by referrals\\n\\n\"\r\n f\"Referral link: \\n{get['referral']}\\n\\n\"\r\n f\"You can withdraw your referral income or spend it on ads\\n\\n\"\r\n f\"You will earn 7% commission when your friends do task \"\r\n f\"or create task\\n\\n\",\r\n reply_to_message_id=update.message.message_id)\r\n if text == \"More❕\":\r\n reply_keyboard = [[\"Withdraw➖\", \"Support👤\"], [\"About💬\", \"Rules🔖\"], [\"Back↩\"]]\r\n sender(\"Use below buttons for quick access\",\r\n reply_markup=ReplyKeyboardMarkup(reply_keyboard, resize_keyboard=True, one_time_keyboard=True),\r\n reply_to_message_id=update.message.message_id)\r\n elif 'Rules🔖' == text:\r\n bot.sendMessage(chat_id=chat_id, text=rules, reply_to_message_id=update.message.message_id)\r\n elif \"About💬\" == text:\r\n bot.sendMessage(chat_id=chat_id, text=about, reply_to_message_id=update.message.message_id)\r\n elif \"Support👤\" == text:\r\n bot.sendMessage(chat_id=chat_id, text=\"Support group link:\\n\"\r\n \"https://t.me/+dFsICH3quPRhYjVl\\n\\n\"\r\n \"Join our support group to get more benefits\\n\\n\"\r\n \"Note: ADMIN WILL NEVER DM YOU FIRST!\\n\\n\"\r\n \"Admin support: @PugalKMC\", reply_to_message_id=update.message.message_id)\r\n elif \"add_trx \" in text:\r\n text = update.message.text\r\n text1 = text.replace(\"add_trx \", '')\r\n separate = text1.split(\"{}\")\r\n get_id = int(separate[0])\r\n get_trx = int(separate[1])\r\n people = mydb['people']\r\n try:\r\n people.update_one({\"_id\": get_id}, {\"$inc\": {\"TRX_balance\": get_trx}})\r\n bot.sendMessage(chat_id=chat_id, text=f\"{get_trx} trx added to {get_id} account\")\r\n except:\r\n bot.sendMessage(chat_id=chat_id, text=\"Wrong format or other error\")\r\n elif \"reduce_trx \" in text:\r\n text = update.message.text\r\n text1 = text.replace(\"reduce_trx \", '')\r\n separate = text1.split(\"{}\")\r\n try:\r\n get_id = int(separate[0])\r\n get_trx = int(separate[1])\r\n people = mydb['people']\r\n user = people.find_one({\"_id\": get_id})\r\n if (user['payout_avail'] - get_trx) < 0:\r\n bot.sendMessage(chat_id=chat_id, text=\"Can't detect trx! out of range!!\")\r\n else:\r\n if user['payout_avail'] >= get_trx:\r\n people.update_one({\"_id\": get_id}, {\"$inc\": {\"TRX_balance\": -get_trx, 'payout_avail': -get_trx}})\r\n bot.sendMessage(chat_id=chat_id, text=f\"{get_trx} trx reduced to {get_id} account\")\r\n else:\r\n people.update_one({\"_id\": get_id}, {\"$inc\": {\"TRX_balance\": -get_trx}})\r\n bot.sendMessage(chat_id=chat_id, text=f\"{get_trx} trx reduced to {get_id} account\")\r\n except:\r\n bot.sendMessage(chat_id=chat_id, text=\"Wrong format or other error\")\r\n elif \"send_msg \" in text:\r\n after = text.replace(\"send_msg \", \"\")\r\n infos = after.split(\"{}\")\r\n # try:\r\n # full_node = HttpProvider('https://api.trongrid.io')\r\n # solidity_node = HttpProvider('https://api.trongrid.io')\r\n # event_server = HttpProvider('https://api.trongrid.io')\r\n #\r\n # tron = Tron(full_node=full_node,\r\n # solidity_node=solidity_node,\r\n # event_server=event_server)\r\n #\r\n # tron.private_key = '009faab68456edf92132cc74a580316d159bdc10a544bda7f82a52175968a323'\r\n # tron.default_address = 'TSPZcEraokyNAuFR4Shgyn5D4ycsWjJhrL'\r\n #\r\n # # added message\r\n # send = tron.trx.send_transaction('TEo84EXz7ZmaQkLXPwmkLnEhQd1DqH2DNU', 1)\r\n #\r\n # print(send)\r\n # bot.sendMessage(chat_id=chat_id, text=send)\r\n # except:\r\n # bot.sendMessage(chat_id=chat_id, text=\"Error in transaction\")\r\n try:\r\n id = infos[0]\r\n msg = infos[1]\r\n bot.sendMessage(chat_id=id, text=msg)\r\n bot.sendMessage(chat_id=chat_id, text=\"Message sent!\")\r\n except:\r\n bot.sendMessage(chat_id=chat_id, text=\"Improper format\")\r\n elif \"announcement_user \" in text:\r\n people = mydb[\"people\"]\r\n after = text.replace(\"announcement_user \", \"\")\r\n for i in people.find({}):\r\n bot.sendMessage(chat_id=i[\"_id\"], text=f\"New Announcement!:\\n\\n\"\r\n f\"{after}\")\r\n else:\r\n bot.sendMessage(chat_id=chat_id, text=\"Message sent to all users!\")\r\n\r\n elif text == \"Back↩\" or text == \"cancel\":\r\n main_buttons(update, context)\r\n\r\n\r\ndef select_task_method(update, context):\r\n chat_id = update.message.chat_id\r\n markup = ReplyKeyboardMarkup([['Bot Chats💬', 'Other Method📂'], [\"Twitter Post🔜\", \"cancel\"]],\r\n one_time_keyboard=True,\r\n resize_keyboard=True)\r\n bot.sendMessage(chat_id=chat_id, text=\"Please select task method you want to create:\\n\\n\"\r\n \"1)Bot Chats💬: This option will help you easily gain members for your \"\r\n \"group\\n\"\r\n \"This bot will auto verify members to provide reward.\\n\\n\"\r\n \"2)Other Method📁: this option will be manual verification by \"\r\n \"your self, So you need to give details for doing task \"\r\n \"in description.\", reply_markup=markup,\r\n reply_to_message_id=update.message.message_id)\r\n\r\n\r\ndef approve_list():\r\n cmd = mydb[\"pending\"]\r\n cmds = [\"nothing\"]\r\n for i in cmd.find({}):\r\n cmds.append(i[\"create_id\"])\r\n return cmds\r\n\r\n\r\ndef commands(update, context):\r\n text = update.message.text\r\n after = text.replace(\"/\", '')\r\n tasks = mydb[\"tasks\"]\r\n if \"approve\" in text:\r\n pending = mydb['pending']\r\n get = pending.find_one({\"create_id\": after})\r\n if str(get) != \"None\":\r\n tasks.insert_one(get)\r\n pending.delete_one({\"create_id\": after})\r\n update.message.reply_text(\"Task permitted successfully\")\r\n elif \"permit_task_\" in text:\r\n reuse = text.replace(\"/permit_task_\", '')\r\n get_task_id = int(reuse[0:6])\r\n get_chat_id = int(reuse[6:])\r\n people = mydb['people']\r\n tasks = mydb['tasks']\r\n task_get = tasks.find_one({'cmd_id': f'task_{get_task_id}'})\r\n if str(task_get) != \"None\":\r\n done_by_list = list(task_get['done_by'])\r\n approve_list = list(task_get['pending'])\r\n try:\r\n reward = (float(task_get['trx_per']) / 100) * 90\r\n people.update_one({'_id': get_chat_id}, {'$inc': {\"TRX_balance\": float(reward),\r\n \"payout_avail\": float(reward),\r\n \"earned_total\": float(reward)}})\r\n get_refer_by = people.find_one({\"_id\": get_chat_id})\r\n ref_income = (reward / 100) * 7\r\n people.update_one({\"_id\": get_refer_by['ref_by']}, {\"$inc\": {\"ref_income\": ref_income,\r\n \"TRX_balance\": ref_income,\r\n \"payout_avail\": ref_income,\r\n \"earned_total\": ref_income}})\r\n\r\n if (task_get['limit']) == (task_get['done'] + 1):\r\n tasks.delete_one({'cmd_id': f'task_{get_task_id}'})\r\n bot.sendMessage(chat_id=task_get['chat_id'],\r\n text=f\"your task: /{task_get['cmd_id']} has completed\\n\\n\"\r\n f\"Task totally done by {task_get['limit']} users\")\r\n approve_list.remove(after)\r\n done_by_list.append(int(get_chat_id))\r\n tasks.update_one({\"cmd_id\": f'task_{get_task_id}'}, {'$inc': {\"done\": 1}})\r\n tasks.update_one({\"cmd_id\": f'task_{get_task_id}'}, {\"$set\": {\"done_by\": done_by_list}})\r\n tasks.update_one({\"cmd_id\": f'task_{get_task_id}'}, {'$set': {'pending': approve_list}})\r\n update.message.reply_text(\"Task approved!\")\r\n except:\r\n update.message.reply_text(\"Task already approved!\")\r\n\r\n elif \"task_\" in text:\r\n get = tasks.find_one({'cmd_id': after})\r\n if str(get) != \"None\":\r\n do_task(update, context)\r\n\r\n\r\ndef cancel(update, context):\r\n main_buttons(update, context)\r\n return ConversationHandler.END\r\n\r\n\r\n#\r\n# webhook_url = \"https://webhook.site/48184ba5-39e5-4f29-bc4c-bb8cb7790f22\"\r\n# # 5123712096:AAFoWsAeO_sJyrsl0upMa-LUCeHE-k8AWYE\r\nAPI_KEY = \"5394324389:AAH9kDST-U9o4L7wXzdAyVLS5Ti1_pT0gbI\"\r\n\r\n# PORT = int(os.environ.get(\"PORT\", 3978))\r\n\r\n\r\n# r = requests.post(webhook_url)\r\n\r\n# 5394324389:AAGvCQN8ogbnwj1MStLHmvu7Kb9e3uQiF_4 trx bot\r\n\r\n\r\ndef main():\r\n updater = Updater(API_KEY)\r\n dp = updater.dispatcher\r\n job_queue = updater.job_queue\r\n # job_queue.run_repeating(send_message_job, interval=10.0, first=0.0)\r\n dp.add_handler(CommandHandler(\"start\", start))\r\n dp.add_handler(MessageHandler(Filters.command, commands))\r\n dp.add_handler(MessageHandler(Filters.text('Back↩'), main_buttons))\r\n task = ConversationHandler(entry_points=[CallbackQueryHandler(task_select)],\r\n states={TWO: [MessageHandler(Filters.photo, get_photo)],\r\n THREE: [MessageHandler(Filters.text, confirm_task)]\r\n }, fallbacks=[MessageHandler(Filters.text, confirm_task)])\r\n\r\n # chat_member_task = ConversationHandler(entry_points=[MessageHandler(Filters.text(\"Chat Member\"), chat_member)],\r\n # states={\r\n # CHAT_MEMBER_CREATE: [MessageHandler(Filters.text, MEMBER_TASK_TIT)]\r\n # })\r\n\r\n other_task = ConversationHandler(\r\n entry_points=[MessageHandler(Filters.text('Other Method📂'), other_tasks.task_new)],\r\n states={other_tasks.CREATE: [MessageHandler(Filters.text, other_tasks.get_title)],\r\n other_tasks.TITLE: [MessageHandler(Filters.text, other_tasks.get_total)],\r\n other_tasks.TRX_TOTAL: [MessageHandler(Filters.text, other_tasks.get_per)],\r\n other_tasks.TRX_PER: [\r\n MessageHandler(Filters.text, other_tasks.description)],\r\n other_tasks.LINK: [MessageHandler(Filters.text, other_tasks.get_link)],\r\n other_tasks.CONFIRM: [\r\n MessageHandler(Filters.text, other_tasks.confirm_create)]\r\n }, fallbacks=[MessageHandler(Filters.text(\"cancel\"), cancel)]\r\n )\r\n\r\n withdrawal = ConversationHandler(\r\n entry_points=[MessageHandler(Filters.text(\"Withdraw➖\"), withdrawal_conversation.withdraw_con)],\r\n states={withdrawal_conversation.ADDRESS: [MessageHandler(Filters.text,\r\n withdrawal_conversation.check_address)],\r\n withdrawal_conversation.AMOUNT: [MessageHandler(Filters.text,\r\n withdrawal_conversation.with_amount)],\r\n withdrawal_conversation.CONFIRM_WITH: [MessageHandler(Filters.text,\r\n withdrawal_conversation.confirm_withrawal)]},\r\n fallbacks=[])\r\n # join_group_task = ConversationHandler(\r\n # entry_points=[MessageHandler(Filters.text('Chat Members🆕'),join_group_con)]\r\n # )\r\n # twitter_task = ConversationHandler(\r\n # entry_points=[MessageHandler(Filters.text(\"Twitter Post\"), twitter_task_con.twitter_task)],\r\n # states={\r\n # twitter_task_con.GET_LINK: [MessageHandler(Filters.text, twitter_task_con.get_link)],\r\n # twitter_task_con.GET_TOTAL: [MessageHandler(Filters.text, twitter_task_con.get_total)],\r\n # twitter_task_con.GET_PER: [MessageHandler(Filters.text, twitter_task_con.trx_per)],\r\n # twitter_task_con.CONFIRM: [MessageHandler(Filters.text, twitter_task_con.confirm)]\r\n # }, fallbacks=[])\r\n\r\n \"\"\"Telegram bot task add and remove\"\"\"\r\n tele_task_add = ConversationHandler(\r\n entry_points=[MessageHandler(Filters.text('Bot Chats💬'), tele_bot_task.tele_task)],\r\n states={\r\n tele_bot_task.GET_LINK: [MessageHandler(Filters.text, tele_bot_task.get_link)],\r\n tele_bot_task.GET_BOT: [MessageHandler(Filters.text, tele_bot_task.get_bot)],\r\n tele_bot_task.GET_DESCRIPTION: [MessageHandler(Filters.text, tele_bot_task.get_description)],\r\n tele_bot_task.GET_TOTAL: [MessageHandler(Filters.text, tele_bot_task.get_total)],\r\n tele_bot_task.CONFIRM: [MessageHandler(Filters.text, tele_bot_task.confirm)]\r\n }, fallbacks=[]\r\n )\r\n # Telegram task do conversation\r\n do_telegram = ConversationHandler(\r\n entry_points=[MessageHandler(Filters.text(\"Chat Bot🆕\"), tele_bot_task.get_task)],\r\n states={\r\n tele_bot_task.INLINE_TELE: [CallbackQueryHandler(tele_bot_task.go_telegram,\r\n pattern='^' + \"started\" + '$'),\r\n MessageHandler(Filters.text, tele_bot_task.skip_tele_do)],\r\n tele_bot_task.CHECK_WORK: [MessageHandler(Filters.text, tele_bot_task.check_work)]\r\n }, fallbacks=[]\r\n )\r\n\r\n dp.add_handler(do_telegram)\r\n dp.add_handler(tele_task_add)\r\n # dp.add_handler(twitter_task)\r\n dp.add_handler(withdrawal)\r\n dp.add_handler(other_task)\r\n dp.add_handler(task)\r\n # dp.add_handler(MessageHandler(Filters.text(\"Chat Bot🆕\"), tele_bot_task.get_task))\r\n dp.add_handler(MessageHandler(Filters.text([\"Twitter🔜\", \"Twitter Post🔜\"]), twitter_task_con.message))\r\n dp.add_handler(MessageHandler(Filters.text('Create Task📜'), select_task_method))\r\n dp.add_handler(MessageHandler(Filters.text, msg_hand))\r\n # updater.start_webhook(listen=\"0.0.0.0\",\r\n # port=PORT,\r\n # url_path=API_KEY)\r\n # updater.bot.setWebhook('https://mywebhook/5394324389:AAH9kDST-U9o4L7wXzdAyVLS5Ti1_pT0gbI')\r\n # updater.bot.setWebhook(\"https://trx-earn-bot.herokuapp.com/\" + \"5394324389:AAGvCQN8ogbnwj1MStLHmvu7Kb9e3uQiF_4\")\r\n updater.start_polling()\r\n updater.idle()\r\n\r\n\r\n# https://webhook.site/48184ba5-39e5-4f29-bc4c-bb8cb7790f22\r\nmain()\r\n","repo_name":"pugalkmc/ad-bot-V02","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":19647,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"23396122531","text":"# invoer\n\nuur1 = int(input(\"geef uur van vertrek vanaf haar eigen huis: \"))\nmin1 = int(input(\"geef min van vertrek vanaf haar eigen huis: \"))\n\nuur2 = int(input(\"geef uur van aankomst bij het huis van haar vriendin: \"))\nmin2 = int(input(\"geef min van aankomst bij het huis van haar vriendin: \"))\n\nuur3 = int(input(\"geef uur van vertrek vanaf het huis van haar vriendin: \"))\nmin3 = int(input(\"geef min van vertrek vanaf het huis van haar vriendin: \"))\n\nuur4 = int(input(\"geef uur van aankomst bij haar eigen huis: \"))\nmin4 = int(input(\"geef min van aankomst bij haar eigen huis: \"))\n\n# bereking\n\ny1 = (uur1 * 60) + min1\ny2 = (uur2 * 60) + min2\ny3 = (uur3 * 60) + min3\ny4 = (uur4 * 60) + min4\n\nyy = y4 - y1\ny0 = y3 - y2\n\nvertrek = y4 - y1 + (720 - (720 * (yy / abs(yy))))\npauze = y3 - y2 + (720 - (720 * (y0 / abs(y0))))\n\ny5 = (vertrek - pauze) / 2\ny6 = y3 + y5\n\nuur_eind = y6 // 60\nmin_eind = y6 % 60\nspeciaal = uur_eind - 24\nuur_eind -= 12 + (12 * (speciaal / abs(speciaal)))\n\n# uitvoer\n\nprint(int(uur_eind))\nprint(int(min_eind))\n","repo_name":"EmielThomaes/5WWIPython","sub_path":"04+Variabelen/De gestopte klok.py","file_name":"De gestopte klok.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"28847168122","text":"from django.shortcuts import render, redirect\nfrom .models import Category, Task\nfrom django.views import View\n\n\nclass Index(View):\n def get(self, request):\n return render(request, 'index.html')\n\n\nclass Categories(View):\n def get(self, request):\n categories = Category.objects.all()\n return render(request, 'categories.html', {\n 'categories': categories\n })\n\n\nclass AddCategory(View):\n def post(self, request):\n name = request.POST.get('name')\n color = request.POST.get('color')\n if color and name:\n category = Category(\n name=name,\n color=color\n )\n category.save()\n return redirect('categories-list')\n\n def get(self, request):\n return render(request, 'add_category.html')\n\n\nclass EditCategory(View):\n def post(self, request, category_id):\n category = Category.objects.get(id=category_id)\n name = request.POST.get('name')\n color = request.POST.get('color')\n if color and name:\n category.name = name\n category.color = color\n category.save()\n return redirect('categories-list')\n\n def get(self, request, category_id):\n category = Category.objects.get(id=category_id)\n return render(request, 'edit_category.html', {\n 'category': category\n })\n\n\nclass DeleteCategory(View):\n def get(self, request, category_id):\n category = Category.objects.get(id=category_id)\n category.delete()\n return redirect('categories-list')\n\n\nclass Tasks(View):\n def get(self, request):\n tasks = Task.objects.all()\n categories = Category.objects.all()\n return render(request, 'tasks.html', {\n 'tasks': tasks,\n 'categories': categories\n })\n\n\nclass AddTask(View):\n def get(self, request):\n categories = Category.objects.all()\n return render(request, 'add_task.html', {\n 'categories': categories\n })\n\n def post(self, request):\n category = request.POST.get('category')\n name = request.POST.get('name')\n description = request.POST.get('description')\n task = Task()\n task.category_id = category\n task.name = name\n task.description = description\n task.save()\n return redirect('tasks')\n\n\nclass EditTask(View):\n def get(self, request, task_id):\n task = Task.objects.get(id=task_id)\n categories = Category.objects.all()\n return render(request, 'edit_task.html', {\n 'task': task,\n 'categories': categories\n })\n\n def post(self, request, task_id):\n task = Task.objects.get(id=task_id)\n name = request.POST.get('name')\n description = request.POST.get('description')\n category_id = request.POST.get('category')\n if name and category_id and description:\n task.name = name\n task.description = description\n task.category_id = category_id\n task.save()\n return redirect('tasks')\n\n\nclass DeleteTask(View):\n def get(self, request, task_id):\n task = Task.objects.get(id=task_id)\n task.delete()\n return redirect('tasks')","repo_name":"majoreq/todo_list","sub_path":"todolist/tasks/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"36027905412","text":"x=int(input())\r\non=0\r\nout=0\r\nfor i in range(x):\r\n n=int(input())\r\n if n>=10 and n<=20:\r\n on+=1\r\n else:\r\n out+=1\r\nprint(\"{} in\".format(on))\r\nprint(\"{} out\".format(out))\r\n ","repo_name":"Jahid-Hasan-Jony/Problem-Solving-Solution","sub_path":"URI_Online_Judge(Beecrowd)/1072.py","file_name":"1072.py","file_ext":"py","file_size_in_byte":200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"71430142843","text":"import discord\nfrom discord.ext import commands\nfrom bs4 import BeautifulSoup\nfrom time import ctime\nimport logging\nimport traceback\nimport asyncio\nimport aiohttp\nfrom configparser import ConfigParser\n\ntoken = 'tokenhere'\n\nlogger = logging.getLogger('discord')\nlogger.setLevel(logging.INFO)\nhandler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')\nhandler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))\nlogger.addHandler(handler)\n\nconfig = ConfigParser()\nconfig.read('data.ini')\n\nclass linkThing:\n url = \"\"\n title = \"\"\n body = \"\"\n\n\ndef get_prefix(bot, message):\n server = message.server\n if config.has_section(server.id) == True:\n get_prefix = config.get(server.id, 'botprefix')\n prefixes = [get_prefix]\n return commands.when_mentioned_or(*prefixes)(bot, message)\n else:\n prefixes = ['~']\n return commands.when_mentioned_or(*prefixes)(bot, message)\n\nbot = commands.Bot(command_prefix=get_prefix)\n\n@bot.event\nasync def on_ready():\n print('Logged in as: '+bot.user.name)\n print('Bot ID: '+bot.user.id)\n print('Invite Link Below')\n print('------')\n print('https://discordapp.com/oauth2/authorize?client_id={}&scope=bot&permissions=8'.format(bot.user.id))\n print('------')\n for server in bot.servers:\n print(\"Connected to server: {} with id: {}\".format(server, server.id))\n print('------')\n\n\nasync def connect():\n print('Logging in...')\n while not bot.is_closed:\n try:\n await bot.start(token)\n except:\n await asyncio.sleep(5)\n\n\n@bot.command(pass_context=True)\nasync def setprefix(ctx, message):\n \"\"\" default is ~setprefix (up to 2)\"\"\"\n server = ctx.message.server\n author = ctx.message.author\n if config.has_section(server.id) == True:\n if author.id == config.get(server.id, 'ownerid'):\n if len(message) > 2:\n await bot.say('prefix commands can only be up to two chars long')\n else:\n with open('data.ini', 'w+', encoding=\"utf-8\") as configfile:\n config.set(str(server.id), 'botprefix', message)\n config.write(configfile)\n await bot.say('prefix updated to {!r}'.format(message))\n\n if config.has_section(server.id) == False:\n await bot.say('I dont have a config for this channel')\n\n if ctx.message.author.id != config.get(server.id, 'ownerid'):\n owner = config.get(server.id, 'ownerid')\n await bot.say('{} you are not authorized to use this command, please contact'\n ' <@'.format(author.mention) + owner + '>')\n\n\n@bot.command(pass_context=True)\nasync def addchannel(ctx):\n \"\"\" use only in the channel you want to add it to, no arguments to give\"\"\"\n server = ctx.message.server\n if config.has_section(server.id) != True:\n server = ctx.message.server\n channel = ctx.message.channel\n author = ctx.message.author\n await bot.say('couldnt find your config, creating one now.')\n with open('data.ini', 'w+', encoding=\"utf-8\") as configfile:\n config.add_section(str(server.id))\n config.set(str(server.id), 'servername', str(server))\n config.set(str(server.id), 'channelname', str(channel))\n config.set(str(server.id), 'channelID', str(channel.id))\n config.set(str(server.id), 'owner', str(author))\n config.set(str(server.id), 'ownerid', str(author.id))\n config.set(str(server.id), 'botprefix', '~')\n config.write(configfile)\n else:\n channelname = config.get(server.id, 'channelname')\n servername = config.get(server.id, 'servername')\n owner = config.get(server.id, 'ownerid')\n await bot.say('the bot has already been set up for channel {!r} on server {!r} '\n 'to change this please talk to <@'.format(channelname, servername) + owner + '>')\n\n\n@bot.command(pass_context=True)\nasync def news():\n \"\"\"Fetches news, no args.\"\"\"\n await bot.say(\"fetching now..\")\n async with aiohttp.ClientSession() as client:\n listOfLinks = await fetch(client)\n try:\n for x in listOfLinks:\n embed = discord.Embed(colour=discord.Colour(0x608f30),\n description=\"```\" + x.body[2:] + '...'\"```\" + \"Read more [here](\" + x.url + \")\", )\n embed.set_footer(text=ctime())\n await bot.say(\n content=\"**\" + x.title + \"**\",\n embed=embed)\n except:\n logging.warning(traceback.format_exc()) # logs the error\n await bot.say('there was a problem fetching the news...')\n with open('traceback.log', 'a+') as log:\n log.write('\\n' + ctime() + '\\n')\n log.write(traceback.format_exc())\n\n\n\nasync def fetch(client):\n \"\"\"fetches the information\"\"\"\n async with client.get('https://www.pcgamer.com/news/') as resp:\n assert resp.status == 200\n response = await resp.text()\n try:\n soup = BeautifulSoup(response, 'html.parser')\n href_list = []\n title_list = []\n\n for href in soup.find_all(\"div\", {\"class\": \"feature-block-item-wrapper\"}):\n url = href.find('a', href=True)\n url = url['href']\n href_list.append(url)\n\n for title in soup.find_all('figure', attrs={'class': 'feature-block-item'}):\n title = title.find('span', {'article-name'})\n title = title.text\n title_list.append(title)\n\n body_list_string = []\n for url in href_list:\n body_list = []\n async with client.get(url) as resp:\n assert resp.status == 200\n response = await resp.text()\n soup = BeautifulSoup(response, 'html.parser')\n results = soup.find_all(\"p\", {\"class\": None})\n for body in results:\n body = body.text\n body_list.append(body)\n\n body_list = body_list[:3]\n body_list_string.append(str(body_list).replace(\"\\\\\", \"\")[:200])\n\n listOfLinks = list()\n\n for x, yz in enumerate(href_list):\n newLinkItem = linkThing()\n newLinkItem.url = href_list[x]\n newLinkItem.title = title_list[x]\n newLinkItem.body = body_list_string[x]\n listOfLinks.append(newLinkItem)\n\n return listOfLinks\n\n except:\n logging.warning(traceback.format_exc()) # logs the error\n with open('traceback.log', 'a+') as log:\n log.write('\\n' + ctime() + '\\n')\n log.write(traceback.format_exc())\n\n\nbot.loop.run_until_complete(connect())\n","repo_name":"Jollyblue/discord_bots","sub_path":"news_bot/newsbot.py","file_name":"newsbot.py","file_ext":"py","file_size_in_byte":6801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"16825654970","text":"import cv2\nimport os\nfrom pathlib import Path\nimport multiprocessing as mp\nimport numpy as np\nimport sys\nimport datetime\n\nfrom log import Logger\n\nTHRESH_VALUE = 100 # Pixel value less than THRESH_VALUE is converted to white\n # and greater than THRESH_VALUE is converted to black\n\nEPSILON_FACTOR = 0.01 #default 0.01\n\nMIN_WIDTH = 100 # minimum width of the reactangle to be extracted\n\nMIN_HEIGHT = 100 # minimum height of the reactangle to be extracted\n\nMAX_WIDTH = 6000 # maximum width of the reactangle to be extracted\n\nMAX_HEIGHT = 6000 # maximum height of the reactangle to be extracted\n\n#CPU_COUNT returns the no of threads available\n#so that we can use all the available threads\n#during the execution of the program\nCPU_COUNT=mp.cpu_count()\n\ndef page_to_notice(path, newspaper, page, output_path,no_of_newspaper_pages):\n \"\"\"\n Extract rectangular contour from image of each page of PDF\n path= current path of the file\n newspaper= name of the newspaper folder inside the Images folder\n page= name of the image file in the newspaper folder inside Images folder\n output_path= path of the subimage folder\n page_count= no of pages processed\n no_of_newspaper_pages= total no of pages in the newspaper folder\n \"\"\"\n \n #Read the image of the page\n img = cv2.imread(str(path.parent.joinpath(\"Images\", newspaper, page)))\n\n # convert RGB to grayscale\n img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # BINARY_INV thresholding so that the rectangles are white and background is black\n ret, thresh = cv2.threshold(img_gray, THRESH_VALUE, 255, cv2.THRESH_BINARY_INV)\n\n # Find contours in the image\n contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n print(f\"\\t==>Extracting Notice from {newspaper[:-11]} page [%s/%s]\" % (page.split(\"_pg_\")[1].split(\".\")[0], no_of_newspaper_pages))\n\n count=0\n for contour in contours:\n # Find the area of contour\n rect_area = cv2.contourArea(contour)\n\n # Filter contours based on area\n if rect_area < MIN_WIDTH * MIN_HEIGHT:\n continue\n\n #Approximate the contour curve with specified precision ie. EPSILON\n #More infohttps://docs.opencv.org/4.x/d3/dc0/group__imgproc__shape.html#ga0012a5fdaea70b8a9970165d98722b4c\n EPSILON= EPSILON_FACTOR * cv2.arcLength(contour, True)\n poly = cv2.approxPolyDP(contour,EPSILON, True)\n\n #Coordinates of the rectangular contour\n x, y, w, h = cv2.boundingRect(contour)\n\n # Filter contours based on width and height and no of sides\n if len(poly)==4 and w >= MIN_WIDTH and h >= MIN_HEIGHT and w <= MAX_WIDTH and h <= MAX_HEIGHT:\n count =count+1\n\n #Cropping the ROI\n cropped_image = img[y: y + h, x: x + w]\n # cv2.drawContours(img, contour_subimage, -1, (0,0,224), 10)\n # cv2.putText(img, \"x= \"+str(x)+\" and y= \"+str(y), (x,y-30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,255,0), 3)\n filename = str(output_path.joinpath(page.split(\".\")[0] +\"_id_\"+str(count) + '.png'))\n cv2.imwrite(filename, cropped_image)\n # cv2.imwrite(filename, img)\n\n\ndef extract_notice():\n sys.stdout=Logger()\n\n print(\"\\n========Extracting rectangular contour=======\\n\")\n path = Path(__file__).parent\n notice_path = path.parent.joinpath(\"subimage\")\n\n if not notice_path.exists():\n os.mkdir(notice_path)\n\n try:\n newspaper_collection = os.listdir(path.parent.joinpath(\"Images\"))\n except FileNotFoundError:\n print(f\"==>\\n'Images' folder not found in: \\n{path.parent}\\n\")\n exit()\n\n if len(newspaper_collection)==0:\n print(f\"==>\\n'Images' folder is empty in: \\n{path.parent}\\n<==\")\n exit()\n \n all_newspaper_images=[]\n\n#Making a list of all the images present in the Images folder\n#This is done to make multiprocessing more effictient\n for newspaper in newspaper_collection: \n newspaper_path = path.parent.joinpath(\"Images\", newspaper)\n newspaper_pages = sorted(os.listdir(newspaper_path))\n if len(newspaper_pages)==0:\n print(f\"==>\\n{newspaper} folder is empty in: \\n{path.parent.joinpath('Images')}\\n<==\")\n continue\n no_of_newspaper_pages = len(newspaper_pages)\n for page in newspaper_pages:\n all_newspaper_images.append([page,newspaper,no_of_newspaper_pages])\n\n #Multiprocessing the execution of the program\n processs=[]\n newspaper_count = 0\n CPU_USED=0 \n page_count = 0\n\n for page,newspaper,no_of_newspaper_pages in all_newspaper_images: \n newspaper_count += 1 \n print(f\"Processing Newspaper: {newspaper} ===================[{newspaper_count}/{len(all_newspaper_images)}]\")\n output_path = path.parent.joinpath(\"subimage\", newspaper)\n\n if not path.parent.joinpath(output_path).exists():\n os.mkdir(output_path)\n\n page_count += 1\n CPU_USED+=1 #number of processes used so far\n\n #If the no of processes are less than CPU_COUNT, \n # continue adding new processes\n if CPU_USED<=CPU_COUNT: \n process=mp.Process(target=page_to_notice, args=(path,newspaper, page, output_path, no_of_newspaper_pages))\n processs.append(process)\n\n #If the no of processes are equal tto CPU_COUNT,\n #Or if no further process can be added,\n # then start the execution of the processes\n if CPU_USED==CPU_COUNT or page_count==len(all_newspaper_images):\n\n #Start the execution of the processes\n for process in processs:\n process.start()\n \n #Wait for the processes to finish\n #This is done to make sure that all the processes are finished\n #before moving to the next newspaper\n #After the processes are finished, it is terminated\n for process in processs:\n process.join()\n process.terminate()\n processs=[]\n CPU_USED=0\n\nif __name__ == \"__main__\":\n sys.stdout=Logger(str(datetime.datetime.now()))\n extract_notice()\n","repo_name":"Ashmin-Bhattarai/Tender-Notice-Extraction","sub_path":"source/notice_extraction.py","file_name":"notice_extraction.py","file_ext":"py","file_size_in_byte":5955,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"41"} +{"seq_id":"5780617279","text":"class Solution:\n def addBoldTag(self, s: str, words: List[str]) -> str:\n # Merge Intervals\n intervals = []\n for word in words:\n wl = len(word)\n index = s.find(word)\n while index != -1:\n intervals.append([index, index + wl])\n # Update index by 1 and find next word: s = \"zzz\", word = \"zz\"\n index += 1\n index = s.find(word, index)\n if len(intervals) == 0:\n return s\n intervals.sort(key = lambda x: (x[0], x[1]))\n merge = [intervals[0]]\n for i in range(1, len(intervals)):\n if merge[-1][1] >= intervals[i][0]:\n merge[-1][1] = max(merge[-1][1], intervals[i][1])\n else:\n merge.append(intervals[i])\n\n res = \"\"\n prev = 0\n for start, end in merge:\n res += s[prev:start]\n res += \"\"\n res += s[start:end]\n res += \"\"\n prev = end\n if prev < len(s):\n res += s[prev:]\n \n return res\n","repo_name":"wyliadrian/LeetCode","sub_path":"616-add-bold-tag-in-string/616-add-bold-tag-in-string_1.py","file_name":"616-add-bold-tag-in-string_1.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"24108302724","text":"print(\"penis\")\n#EMBEDDER\nimport torch\nimport numpy as np\nimport time\nfrom sklearn import svm\nmodel = torch.hub.load('torchvggish', 'vggish', source = 'local')\nmodel.eval()\n\n# For onboard computation, comment out all but return to disable any optimsations\ndef optimisation(embed):\n embed = quantization(embed)\n embed = pruning(embed)\n embed = fusing(embed)\n return embed\n\n# Converts embed from float to int to improve performance\ndef quantization(embed):\n return (np.array(embed, dtype='int'))\n\ndef pruning(embed):\n THRESHOLD_VALUE = 100\n return embed\n # return (np.where(embed > THRESHOLD_VALUE, 255, 0))\n\ndef fusing(embed):\n return embed\n\nguessFile = \"client_audio.wav\" # Change back to client_audio.wav\n#import files\npinchFile = \"pinch5mintraining.wav\"\nstrokeFile = \"stroke5mintraining.wav\"\nbackgroundFile = \"BackgroundNoise.wav\"\n\n#embed the file\npinchEmbed = model.forward(pinchFile)\nstrokeEmbed = model.forward(strokeFile)\nbackgroundEmbed = model.forward(backgroundFile)\n\nguessEmbed = model.forward(guessFile)\nnumpyGuessEmbed = [ item.detach().numpy() for item in guessEmbed]\n#np conversion\nnumpyPinchEmbed = [ item.detach().numpy() for item in pinchEmbed]\nnumpyBackgroundEmbed = [ item.detach().numpy() for item in backgroundEmbed]\nnumpyStrokeEmbed = [ item.detach().numpy() for item in strokeEmbed]\nfullEmbed = np.concatenate((numpyBackgroundEmbed,numpyStrokeEmbed,numpyPinchEmbed), axis=0)\n#CLASSIFICATION\n#define the target and target names\n#target = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]\ntarget = []\nnumpyTarget = np.array(target)\ntarget_names = ['Pinch','Nothing','Stroke']\nfor item in numpyBackgroundEmbed:\n target.append(0)\nfor item in numpyStrokeEmbed:\n target.append(1)\nfor item in numpyPinchEmbed:\n target.append(2)\nnumpyTarget = np.array(target)\n#define classifier and train the data\nclf = svm.SVC(kernel='linear')\nclf.fit(fullEmbed,numpyTarget)\n\n#set up a test 1 second\n#testPinch = \"EarPinchTestData2.wav\"\n#testPinchEmbed = model.forward(testPinch)\n#numpyTestPinchEmbed = [ item.detach().numpy() for item in testPinchEmbed]\n\n#testStroke = \"EarStrokeTestData2.wav\"\n#testStrokeEmbed = model.forward(testStroke)\n#numpyTestStrokeEmbed = [ item.detach().numpy() for item in testStrokeEmbed]\n\n# Optimisation (3/3)\n#numpyTestPinchEmbed = optimisation(numpyTestPinchEmbed)\n#numpyTestStrokeEmbed = optimisation(numpyTestStrokeEmbed)\nnumpyGuessEmbed = optimisation(numpyGuessEmbed)\n# print(len(numpyTestEmbed))\n\n# testValue = (numpyTestEmbed[15])\n# testValue = testValue.reshape(1,-1)\n\n# predict the result\n# testResult = clf.predict(testValue)\n\n###########################################################\n#overallPinchTest = 0\n#overallNothingTest = 0\n#overallStrokeTest = 0\n#for item in numpyTestPinchEmbed:\n# testValue = (item)\n# testValue = testValue.reshape(1,-1)\n#\n# testResult = clf.predict(testValue)\n# overallPinchTest = overallPinchTest + testResult[0]\n#overallPinchTest = overallPinchTest / len(numpyTestPinchEmbed)\n#print(\"Closer to 0 = Pinch\")\n#print(\"Closer to 2 = Stroke\")\n#print(\"The average value for the pinch test data is:\")\n#print(overallPinchTest)\noverallGuess = 0\nfor item in numpyGuessEmbed:\n testValue = (item)\n testValue = testValue.reshape(1,-1)\n\n testResult = clf.predict(testValue)\n print(testResult[0])\n overallGuess = overallGuess + testResult[0]\n\noverallGuess = overallGuess / len(numpyGuessEmbed)\nprint(\"guess value is\")\nprint(overallGuess)\nif (overallGuess < 0.5) and (overallGuess >= 0):\n print(\"NOTHING\")\nelif (overallGuess >= 0.5) and (overallGuess <= 1):\n print(\"STROKE\")\nelif (overallGuess >= 1) and (overallGuess <= 2):\n print(\"PINCH\")\nelse:\n print(\"error\")\n","repo_name":"SamLowth00/cognitiveAssignment","sub_path":"VGGishEmbed.py","file_name":"VGGishEmbed.py","file_ext":"py","file_size_in_byte":3829,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"41"} +{"seq_id":"30324575401","text":"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport glob, os\nimport pandas as pd\n\n#change directory to following folder\nos.chdir(r\"C:\\Users\\nicoj\\netcase\\1-Start-UP\\Triathlon\\Aktivitaeten_csv\")\n\ndirectory_link = r\"C:\\Users\\nicoj\\netcase\\1-Start-UP\\Triathlon\\Aktivitaeten_csv\"\n\n#initiate list with activities:\nact_list = []\nfor file in glob.glob(\"*.*\"):\n if str(file).count(\".csv\")==1:\n act_list.append(file)\n\n\n\napp = dash.Dash()\n\n\nLaufen_dates = []\nBike_dates = []\nSSwim_dates = []\nFSwim_dates = []\nfor act in act_list:\n if act.count(\"Laufen\")==1:\n #fill laufen_dates with the date of the current activity\n Laufen_dates.append(act.split(\"_\")[1])\n if act.count(\"Radfahren\")==1:\n #fill bike_dates with the date of the current activity\n Bike_dates.append(act.split(\"_\")[1])\n if act.count(\"Schwimmbadschwimmen\")==1:\n #schwimmbadschwimmen\n SSwim_dates.append(act.split(\"_\")[1])\n if act.count(\"Freiwasserschwimmen\")==1:\n FSwim_dates.append(act.split(\"_\")[1])\n\n\nAct_Dict = {'Radfahren': Bike_dates,\n 'Laufen': Laufen_dates,\n \"Schwimmbadschwimmen\" : SSwim_dates,\n \"Freiwasserschwimmen\" : FSwim_dates\n }\n\nnames = list(Act_Dict.keys())\nnestedOptions = Act_Dict[names[0]]\n\napp.layout = html.Div(\n [\n html.Div([\n dcc.Dropdown(\n id='name-dropdown', # choose activity type\n options=[{'label':name, 'value':name} for name in names],\n value = list(Act_Dict.keys())[0]\n ),\n ],style={'width': '20%', 'display': 'inline-block'}),\n html.Div([\n dcc.Dropdown(\n id='opt-dropdown', # chose single activity\n ),\n ],style={'width': '20%', 'display': 'inline-block'}\n ),\n html.Div([\n dcc.Dropdown(\n id='plot-dropdown', # chose property to plot\n ),\n ],style={'width': '20%', 'display': 'inline-block'}\n ),\n\n html.Hr(),\n html.Div(id='output-graph')\n ]\n)\n\n@app.callback(\n dash.dependencies.Output('opt-dropdown', 'options'),\n [dash.dependencies.Input('name-dropdown', 'value')]\n)\ndef update_date_dropdown(name):\n global test\n test = name\n return [{'label': i, 'value': i} for i in Act_Dict[name]]\n\n@app.callback(\n dash.dependencies.Output('plot-dropdown', 'options'),\n [dash.dependencies.Input('opt-dropdown', 'value')]\n)\ndef choose_plot_content(activity):\n print(\"ACTIVITY:\", activity)\n columns = list(pd.read_csv(os.path.join(directory_link + \"/\" + test + \"_\" + activity + \"_\" + \".csv\"), index_col = 0).columns)\n print(\"COLUMNS:\", columns)\n global activity_to_plot\n activity_to_plot = activity\n return [{'label': i, 'value': i} for i in columns]\n\n@app.callback(\n dash.dependencies.Output(component_id='output-graph', component_property='children'),\n [dash.dependencies.Input(component_id='plot-dropdown', component_property='value')]\n)\ndef update_value(input_data):\n print(\"INPUT_DATA\", input_data)\n print(\"TYPE_INPUT_DATA:\", type(input_data))\n print(\"TEST\", test)\n print(\"ACTIVITY_TO_PLOT:\", activity_to_plot)\n\n df = pd.read_csv(os.path.join(directory_link + \"/\" + test + \"_\" + activity_to_plot + \"_\" + \".csv\"))\n\n return dcc.Graph(\n id='example-graph',\n figure={\n 'data': [\n {'x': df.index, 'y': df[input_data]*3.6, 'type': 'line', 'name': input_data},\n ],\n 'layout': {\n 'title': input_data\n }\n }\n )\n\n\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n","repo_name":"nicvoigt/Triathlon_Dashboard","sub_path":"Dashboard/Dropdown_overview.py","file_name":"Dropdown_overview.py","file_ext":"py","file_size_in_byte":3646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"27239995342","text":"from autoarray.mask import mask_2d\r\nfrom autoarray.structures import arrays, grids, vector_fields\r\nfrom autoarray.plot.mat_wrap import visuals as vis\r\n\r\nfrom matplotlib import patches as ptch\r\nimport typing\r\nfrom typing import List\r\n\r\n\r\nclass Visuals1D(vis.Visuals1D):\r\n\r\n pass\r\n\r\n\r\nclass Visuals2D(vis.Visuals2D):\r\n def __init__(\r\n self,\r\n origin: grids.Grid2D = None,\r\n border: grids.Grid2D = None,\r\n mask: mask_2d.Mask2D = None,\r\n positions: grids.Grid2DIrregular = None,\r\n grid: grids.Grid2D = None,\r\n pixelization_grid: grids.Grid2D = None,\r\n vector_field: vector_fields.VectorField2DIrregular = None,\r\n patches: typing.Union[ptch.Patch] = None,\r\n array_overlay: arrays.Array2D = None,\r\n light_profile_centres: grids.Grid2DIrregular = None,\r\n mass_profile_centres: grids.Grid2DIrregular = None,\r\n multiple_images: grids.Grid2DIrregular = None,\r\n critical_curves: grids.Grid2DIrregular = None,\r\n caustics: grids.Grid2DIrregular = None,\r\n indexes: typing.Union[List[int], List[List[int]]] = None,\r\n pixelization_indexes: typing.Union[List[int], List[List[int]]] = None,\r\n ):\r\n\r\n super().__init__(\r\n mask=mask,\r\n positions=positions,\r\n grid=grid,\r\n pixelization_grid=pixelization_grid,\r\n vector_field=vector_field,\r\n patches=patches,\r\n array_overlay=array_overlay,\r\n origin=origin,\r\n border=border,\r\n indexes=indexes,\r\n pixelization_indexes=pixelization_indexes,\r\n )\r\n\r\n self.light_profile_centres = light_profile_centres\r\n self.mass_profile_centres = mass_profile_centres\r\n self.multiple_images = multiple_images\r\n self.critical_curves = critical_curves\r\n self.caustics = caustics\r\n\r\n def plot_via_plotter(self, plotter, grid_indexes=None, mapper=None):\r\n\r\n super().plot_via_plotter(\r\n plotter=plotter, grid_indexes=grid_indexes, mapper=mapper\r\n )\r\n\r\n if self.light_profile_centres is not None:\r\n plotter.light_profile_centres_scatter.scatter_grid(\r\n grid=self.light_profile_centres\r\n )\r\n\r\n if self.mass_profile_centres is not None:\r\n plotter.mass_profile_centres_scatter.scatter_grid(\r\n grid=self.mass_profile_centres\r\n )\r\n\r\n if self.multiple_images is not None:\r\n plotter.multiple_images_scatter.scatter_grid(grid=self.multiple_images)\r\n\r\n if self.critical_curves is not None:\r\n try:\r\n plotter.critical_curves_plot.plot_grid(grid=self.critical_curves)\r\n except TypeError:\r\n pass\r\n\r\n if self.caustics is not None:\r\n try:\r\n plotter.caustics_plot.plot_grid(grid=self.caustics)\r\n except TypeError:\r\n pass\r\n","repo_name":"jonathanfrawley/PyAutoGalaxy_copy","sub_path":"autogalaxy/plot/mat_wrap/lensing_visuals.py","file_name":"lensing_visuals.py","file_ext":"py","file_size_in_byte":2957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"4159469948","text":"\n\nimport sys\n\nn, p, m = [int(x) for x in sys.stdin.readline().split()]\nplayers = []\nfor i in range(n):\n players.append(sys.stdin.readline().strip())\n\nscores = {x: 0 for x in players}\n\nfor i in range(m):\n line = sys.stdin.readline().strip().split()\n scores[line[0]] += int(line[1])\n\nwinners = []\nfor player in players:\n if scores[player] >= p:\n winners.append(player)\n\nif len(winners) > 0:\n for winner in winners:\n print(winner + \" wins!\")\nelse:\n print(\"No winner!\")","repo_name":"gabriele-tombesi/codex_optimal_proj","sub_path":"Completions/davinci_runs/test/test_T0.5_k2_1000/intro-questions.txt_dir/4815/first_pys/solution_5.py","file_name":"solution_5.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"41"} +{"seq_id":"71333554363","text":"import sys\nsys.path.append('../')\nfrom persist import read, save\nfrom model import *\n\ndef setup():\n gb = Course('Math','Fall 2017')\n joe = Student('Joe', 'Davis', 'joe@pdx.edu')\n mary = Student('Mary', 'Wilcox', 'm2w@pdx.edu')\n gb.students.append(joe)\n gb.students.append(mary)\n quizzes = Category(gb, 'Quizzes', 25)\n mid1 = Category(gb, 'Midterm1', 15)\n gb.categories.append(quizzes)\n gb.categories.append(mid1)\n quiz1 = Gradeable(gb, 'Quiz1', quizzes, 15)\n quiz2 = Gradeable(gb, 'Quiz2', quizzes, 15)\n exam1 = Gradeable(gb, 'Exam1', mid1, 15)\n for i in range(3):\n quiz1.add_question(5)\n quiz2.add_question(5)\n exam1.add_question(5)\n gb.gradeables.append(quiz1)\n gb.gradeables.append(quiz2)\n gb.gradeables.append(exam1)\n\n for question in quiz1.questions:\n s = gb.get_score(joe, quiz1, question)\n s.value = 4\n s = gb.get_score(mary, quiz1, question)\n s.value = 5\n\n return gb\n\ndef setup_big():\n gb = Course('Math','Fall 2017')\n for i in range(50):\n gb.students.append(Student(\"abc\",\"def\",\"g@gmail.com\"))\n\n quizzes = Category(gb, 'Quizzes', 25)\n mid1 = Category(gb, 'Midterm1', 15)\n final = Category(gb, 'Final', 20)\n homework = Category(gb, 'Homework', 15)\n\n gb.categories.append(quizzes)\n gb.categories.append(mid1)\n gb.categories.append(final)\n gb.categories.append(homework)\n \n exam1 = Gradeable(gb, 'Exam1', mid1, 15)\n \n for i in range(10):\n quiz = Gradeable(gb, 'Quiz{0:d}'.format(i), quizzes, 100)\n hw = Gradeable(gb, 'Homework{0:d}'.format(i), homework, 100)\n for j in range(20):\n quiz.add_question(5)\n hw.add_question(5)\n gb.gradeables.append(quiz)\n gb.gradeables.append(hw)\n gb.gradeables.append(exam1)\n\n for s in gb.students:\n for g in gb.gradeables:\n for question in g.questions:\n s = gb.get_score(s, g, question)\n s.value = 4\n return gb\n\n\ndef test_save_and_load():\n gb = setup()\n save(gb,'test.json')\n gb2 = read('test.json')\n assert len(gb2.students) == 2\n assert len(gb2.categories) == 2\n assert len(gb2.gradeables) == 3\n\n# check performance for 20k scores (about 0.28s) json file about 1.7Mb\ndef test_save_and_load_big():\n gb = setup_big()\n save(gb,'test.json')\n gb2 = read('test.json')\n assert len(gb2.students) == 50\n assert len(gb2.gradeables) == 21\n assert len(gb2.scores) == 20*50*20\n","repo_name":"ddrake/Gradebook","sub_path":"tests/persist_test.py","file_name":"persist_test.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"10408208050","text":"import tkinter as tk\nimport tkinter as tk\nimport random\n\ndef new_word():\n color_label[\"fg\"] = random.choice(colors) # задаем случайный цвет слова из списка и присваеваем обьекту color_label\n color_label[\"text\"] = random.choice(colors) # задаем случайное слово из списка и присваеваем обьекту color_label\n\n\ndef check(event):\n print(\"Проверка\")\n global score # правильные попытки\n global fails # неправильные попытки\n\n if time_left > 0:\n user_color = entry.get() # вытаскиваем слово из поля\n word_color = color_label[\"fg\"] # вытаскиваем цвет слова\n if user_color == word_color:\n print(\"да\")\n score += 1\n score_label[\"text\"] = f\"Правильно: {score}\"\n else:\n print(\"нет\")\n fails += 1\n fails_label[\"text\"] = f\"Неправильно: {fails}\"\n new_word() # генерируем новое слово\n entry.delete(0, \"end\") # очищаем текст в поле ввода\n\ndef timer():\n global time_left\n if time_left > 0:\n time_left -= 1\n time_label[\"text\"] = f\"Осталось секунд: {time_left}\"\n time_label.after(1000, timer)\n\n\nwindow = tk.Tk()\nwindow.title(\"Назови цвет\")\nwindow.geometry(\"350x250\")\nscore = 0\nfails = 0\ntime_left = 15\ncolors = [\"red\", \"blue\", \"green\", \"pink\", \"black\", \"yellow\", \"orange\", \"purple\", \"brown\", \"white\"]\n\ninstructions = tk.Label(window, text=\"Введи цвет слова, а не слово! Жми Enter, чтобы играть.\", font=(\"Helvetica\", 10))\ninstructions.place(x=10, y=10)\n\ncolor_label = tk.Label(window,text=\"color\", font=('Helvetica', 60))\ncolor_label.place(x=10, y=80)\n\nentry = tk.Entry(window, font=('Helvetica', 10))\nentry.place(x=10, y=180)\n\nscore_label = tk.Label(window, text=f\"Правильно: {score}\", font=(\"Helvetica\", 10))\nscore_label.place(x=10, y=40)\n\nfails_label = tk.Label(window, text=f\"Неправильно: {fails} \", font=(\"Helvetica\", 10))\nfails_label.place(x=10, y=60)\n\ntime_label = tk.Label(window, text=f\"Осталось секунд: {time_left}\" )\ntime_label.place(x=10, y=210)\n\nentry.focus_set()\nnew_word()\nwindow.bind(\"\", check)\n#timer()\ntime_label.after(1000,timer) #у элементов окна есть команда after, которая позволяет выполнять указанную функцию через заданный промежуток времени в миллисекундах\nwindow.mainloop()","repo_name":"alexed34/hello_word","sub_path":"Part1/1,17.py","file_name":"1,17.py","file_ext":"py","file_size_in_byte":2692,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"6767067088","text":"import numpy as np\nfrom astropy.io import fits\nfrom astropy import wcs\nfrom astropy.coordinates import SkyCoord, EarthLocation, AltAz, ICRS, Longitude, Latitude\nimport astropy.units as u\nfrom astropy.time import Time\nfrom astropy.table import Table, vstack\n\nimport matplotlib.pylab as plt\n\n# restore list of photometry tables, one per image\ntemp = np.load('full_night.npz')\nphot_tables = temp['phot_tables'][()]\ntemp.close()\n\nhdulist = fits.open('initial_wcs.fits')\nw = wcs.WCS(hdulist[0].header)\nhdulist.close()\n\nlsst_location = EarthLocation(lat=-30.2444*u.degree, lon=-70.7494*u.degree, height=2650.0*u.meter)\n\n\ndef coord_trans(ptable, w):\n \"\"\"\n Take a photometry table and add ra and dec cols\n \"\"\"\n time = Time(ptable['mjd'].max(), format='mjd')\n az, alt = w.all_pix2world(ptable['xcenter'], ptable['ycenter'], 0)\n coords = AltAz(az=az*u.degree, alt=alt*u.degree, location=lsst_location, obstime=time)\n sky_coords = coords.transform_to(ICRS)\n ptable['alt_rough'] = coords.alt\n ptable['az_rough'] = coords.az\n ptable['ra_rough'] = sky_coords.ra\n ptable['dec_rough'] = sky_coords.dec\n return ptable\n\n\nra_r = []\ndec_r = []\nmjd = []\n\nfor ptable in phot_tables:\n ptable = coord_trans(ptable, w)\n ra_r.extend(ptable['ra_rough'].value.tolist())\n dec_r.extend(ptable['dec_rough'].value.tolist())\n mjd.extend(ptable['mjd'].tolist())\n\nnames = ['ra', 'dec', 'mjd']\ntypes = [float]*3\ndata = np.array([ra_r, dec_r, mjd])\n\n\n#phot_table = vstack(phot_tables)\n\n\n# np.savez('phot_tables_rough_wcs.npz', phot_tables=phot_tables)\n\n# Looks like the projection is a little wonky at higher airmass.\n\n","repo_name":"lsst/all_sky_phot","sub_path":"data/obsolete/wcs_full_night.py","file_name":"wcs_full_night.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"41"} +{"seq_id":"6629785623","text":"import argparse\nimport logging\nimport os\nimport sys\n\nimport hypertune\nimport numpy as np\nimport pandas as pd\nfrom sklearn import model_selection\n\nfrom trainer import model\nfrom trainer import utils\n\nfrom sklearn.model_selection import cross_val_score\n\n# https://www.geeksforgeeks.org/implementing-pca-in-python-with-scikit-learn/\n# https://www.kaggle.com/uciml/breast-cancer-wisconsin-data\n\ndef _train_and_evaluate(estimator, train, flags):\n \n \n y = train['diagnosis']\n X = train.drop(['diagnosis'], axis=1)\n\n logging.info(y.shape)\n logging.info(X.shape)\n \n logging.info('fitting the model...')\n estimator.fit(X, y)\n\n\n utils.dump_model(flags.bucket_name, estimator, flags.bucket_folder+'/model/')\n logging.info('saved model!')\n\n\n\ndef run_experiment(flags):\n \n model_data = utils.get_dwc_data(flags.table_name, float(flags.table_size),flags.package_name)\n model_data.fillna(0, inplace=True)\n logging.info(str(model_data.shape[0]) + ' rows')\n logging.info(model_data.head())\n\n logging.info('data retrieved successfully')\n \n\n estimator = model.get_estimator(flags)\n\n _train_and_evaluate(estimator, model_data, flags)\n\n\ndef _parse_args(argv):\n \"\"\"Parses command-line arguments.\"\"\"\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--table_name', type=str)\n parser.add_argument('--table_size', type=str)\n parser.add_argument('--n_components', type=str)\n parser.add_argument('--job-dir', type=str)\n parser.add_argument('--bucket_name', type=str)\n parser.add_argument('--bucket_folder', type=str)\n parser.add_argument('--package_name', type=str)\n \n return parser.parse_args(argv)\n\n\ndef main():\n \"\"\"Entry point.\"\"\"\n logging.info('model starting')\n\n flags = _parse_args(sys.argv[1:])\n \n logging.basicConfig(level='INFO')\n run_experiment(flags)\n\n\nif __name__ == '__main__':\n main()","repo_name":"SAP-samples/datasphere-fedml","sub_path":"GCP/sample-notebooks/PCAPipeline/PCAPipeline/trainer/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"41"} +{"seq_id":"73257148603","text":"#! python3\n\n\ndef getInput():\n i = 0\n text_entry = []\n while True:\n raw_string = input('Say something (\\\\end to quit): ')\n if raw_string == '\\\\end':\n break\n else:\n text_entry.append(raw_string)\n i += 1\n continue\n return text_entry\n\n\ndef processRawList(rawList):\n finished_output = ''\n for phrase in rawList:\n words = phrase.split(' ')\n if words[-1].endswith(('.', '!', '?')):\n punct = ' '\n elif words[-1] == '':\n punct = ''\n # could use the startswith method here\n elif check_question(words[0]):\n punct = '? '\n else:\n punct = '. '\n finished_output += phrase.capitalize() + punct\n return finished_output\n\n\ndef check_question(first_word):\n question_words = ('when', 'where', 'what', 'why', 'who', 'which',\n 'how', 'is', \"what's\", \"how's\", \"whose\", \"who's\")\n for i in range(len(question_words)):\n if first_word.lower() == question_words[i]:\n return True\n\n\nprint(processRawList(getInput()))\n","repo_name":"AzraFlow/PythonMegaCourse","sub_path":"Section8/textpro.py","file_name":"textpro.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"32077274391","text":"from pathlib import Path\nfrom .apf_trigger_reader import APFTriggerReader\nfrom .utils import SpacyRawSentenceSplitter\n\nif __name__ == \"__main__\":\n\n reader = APFTriggerReader(dict(), None, SpacyRawSentenceSplitter())\n\n file_path = 'data/LDC2006T06//en_train.files'\n\n file_path = Path(file_path)\n search_dir = file_path.parent\n\n snts = []\n for doc_name in reader._read_doc_names(file_path):\n # Text and annotations are given with `.sgm` and `.apf.xml` file pairs.\n sgm_path = search_dir / f'{doc_name}.sgm'\n sgm_text = reader._read_sgm_text(sgm_path)\n for idx, sentence in enumerate(reader._sentence_splitter.split_sentences(sgm_text)):\n sentence = sentence.strip()\n if idx < 2 or not sentence or len(sentence) < 10:\n continue\n snts.append(sentence)\n snts.append('')\n\n with open('en_train.corpus.txt', 'w', encoding='utf-8') as f:\n for snt in snts:\n f.write(snt)\n f.write('\\n')\n","repo_name":"YerevaNN/zsee","sub_path":"zsee/data/extract_texts.py","file_name":"extract_texts.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"41"} +{"seq_id":"13870321527","text":"import os\nimport numpy as np\nimport torch\nimport torch.utils.data\nfrom src.dataset import ImageDS, BorderPredictionDS, denorm\nfrom src.utils import plot, my_collate, random_rotation_flip\nfrom src.architecture import CNNBase, BorderPredictionNet\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\nimport tqdm\nimport dill as pickle\n\n\ndef evaluate_model(model: torch.nn.Module, dataloader: torch.utils.data.DataLoader, device: torch.device, ds_stats: tuple):\n \"\"\"Function for evaluation of a model `model` on the data in `dataloader` on device `device`\"\"\"\n # get dataset mean and std\n mean, std = ds_stats\n img_min, img_max = - mean / std, (1 - mean) / std \n # Define a loss (mse loss)\n mse = torch.nn.MSELoss()\n # We will accumulate the mean loss in variable `loss`\n loss = torch.tensor(0., device=device)\n with torch.no_grad(): # We do not need gradients for evaluation\n # Loop over all samples in `dataloader`\n for data in tqdm.tqdm(dataloader, desc=\"scoring\", position=0):\n # Get a sample and move inputs and targets to device\n inputs, targets, mask, file_names = data\n inputs = inputs.to(device)\n targets = targets.to(device)\n mask = mask.to(device)\n \n # Get outputs for network\n outputs = model(inputs, mask)\n \n # Here we could clamp the outputs to the minimum and maximum values of inputs for better performance\n outputs = torch.clamp(outputs, img_min, img_max)\n\n # Calculate mean mse loss over all samples in dataloader (accumulate mean losses in `loss`)\n loss += torch.stack([mse(output, target) for output, target in zip(outputs, targets)]).sum()\n loss /= len(dataloader.dataset)\n\n return loss\n\n\ndef main(results_path, network_config: dict, learningrate: int = 1e-3, batch_size: int = 16, weight_decay: float = 1e-5,\n n_updates: int = int(1e5), device: torch.device = torch.device(\"cuda:0\")):\n \"\"\"Main function that takes hyperparameters and performs training and evaluation of model\"\"\"\n # Prepare a path to plot to\n plotpath = os.path.join(results_path, 'plots')\n os.makedirs(plotpath, exist_ok=True)\n \n # Load dataset\n p = \"data/data_train\"\n ds = ImageDS(p)\n \n # load mean and std\n with open(\"files/image_stats.pkl\", \"rb\") as f:\n mean, std = pickle.load(f)\n\n # Split dataset into training, validation, and test set randomly\n trainingset = torch.utils.data.Subset(ds, indices=np.arange(int(len(ds)*(4/5))))\n validationset = torch.utils.data.Subset(ds, indices=np.arange(int(len(ds)*(4/5)),len(ds)))\n\n # Create datasets and dataloaders with rotated targets without augmentation (for evaluation)\n tf_eval = transforms.Compose([\n transforms.ToTensor(),\n transforms.Resize((90,90))\n ])\n trainingset_eval = BorderPredictionDS(dataset=trainingset, ds_stats = (mean, std), transform_chain=tf_eval, border_mode=\"fix\")\n validationset = BorderPredictionDS(dataset=validationset, ds_stats = (mean, std), transform_chain=tf_eval, border_mode=\"fix\")\n trainloader = DataLoader(trainingset_eval, batch_size=1, shuffle=False, num_workers=0, collate_fn=my_collate)\n valloader = DataLoader(validationset, batch_size=1, shuffle=False, num_workers=0, collate_fn=my_collate)\n \n # Create datasets and dataloaders with rotated targets with augmentation (for training)\n tf_aug = transforms.Compose([\n transforms.ToTensor(),\n transforms.RandomResizedCrop((90,90)),\n transforms.Lambda(lambda x: random_rotation_flip(x))\n ])\n trainingset_augmented = BorderPredictionDS(dataset=trainingset, ds_stats = (mean, std), transform_chain=tf_aug, border_mode=\"rand\")\n trainloader_augmented = DataLoader(trainingset_augmented, batch_size=batch_size, shuffle=True, num_workers=0, collate_fn=my_collate)\n \n # Define a tensorboard summary writer that writes to directory \"results_path/tensorboard\"\n writer = SummaryWriter(log_dir=os.path.join(results_path, 'tensorboard'))\n \n # Create Network \n cnn = CNNBase(**network_config)\n #cnn = CNNBaseMulti(**network_config)\n net = BorderPredictionNet(cnn)\n net.to(device)\n \n # Get mse loss function\n mse = torch.nn.MSELoss()\n \n # Get adam optimizer\n optimizer = torch.optim.Adam(net.parameters(), lr=learningrate, weight_decay=weight_decay)\n \n print_stats_at = 1e2 # print status to tensorboard every x updates\n plot_at = 1e4 # plot every x updates\n validate_at = 5e3 # evaluate model on validation set and check for new best model every x updates\n update = 0 # current update counter\n best_validation_loss = np.inf # best validation loss so far\n update_progess_bar = tqdm.tqdm(total=n_updates, desc=f\"loss: {np.nan:7.5f}\", position=0) # progressbar\n\n # Save initial model as \"best\" model (will be overwritten later)\n torch.save(net, os.path.join(results_path, 'best_model.pt'))\n \n # Train until n_updates update have been reached\n while update < n_updates:\n for data in trainloader_augmented:\n # Get next samples in `trainloader_augmented`\n inputs, targets, mask, ids = data\n inputs = inputs.to(device)\n targets = targets.to(device)\n mask = mask.to(device)\n \n # Reset gradients\n optimizer.zero_grad()\n\n # Get outputs for network\n outputs = net(inputs, mask)\n \n # Calculate loss, do backward pass, and update weights\n loss = mse(outputs, targets)\n loss.backward()\n optimizer.step()\n \n # Print current status and score\n if update % print_stats_at == 0 and update > 0:\n writer.add_scalar(tag=\"training/loss\",\n scalar_value=loss.cpu(),\n global_step=update)\n \n # Plot output\n# if update % plot_at == 0:\n# plot(inputs.detach().cpu().numpy(), targets.detach().cpu().numpy(), outputs.detach().cpu().numpy(),\n# plotpath, update)\n \n # Evaluate model on validation set\n if update % validate_at == 0 and update > 0:\n val_loss = evaluate_model(net, dataloader=valloader, device=device, ds_stats=(mean, std))\n writer.add_scalar(tag=\"validation/loss\", scalar_value=val_loss.cpu(), global_step=update)\n # Add weights as arrays to tensorboard\n for i, param in enumerate(net.parameters()):\n writer.add_histogram(tag=f'validation/param_{i}', values=param.cpu(),\n global_step=update)\n # Add gradients as arrays to tensorboard\n for i, param in enumerate(net.parameters()):\n writer.add_histogram(tag=f'validation/gradients_{i}',\n values=param.grad.cpu(),\n global_step=update)\n # Save best model for early stopping\n if best_validation_loss > val_loss:\n best_validation_loss = val_loss\n torch.save(net, os.path.join(results_path, 'best_model.pt'))\n with open(os.path.join(results_path, \"best_validation_loss.txt\"), \"w\") as f:\n f.write(\"Best validation loss: %s\" % best_validation_loss)\n \n update_progess_bar.set_description(f\"loss: {loss:7.5f}\", refresh=True)\n update_progess_bar.update()\n \n # Increment update counter, exit if maximum number of updates is reached\n update += 1\n if update >= n_updates:\n break\n\n update_progess_bar.close()\n print('Finished Training!')\n \n # Load best model and compute score on test set\n print(f\"Computing scores for best model\")\n net = torch.load(os.path.join(results_path, 'best_model.pt'))\n val_loss = evaluate_model(net, dataloader=valloader, device=device, ds_stats=(mean, std))\n train_loss = evaluate_model(net, dataloader=trainloader, device=device, ds_stats=(mean, std))\n \n print(f\"Scores:\")\n print(f\"validation loss: {val_loss}\")\n print(f\"training loss: {train_loss}\")\n \n # Write result to file\n with open(os.path.join(results_path, 'results.txt'), 'w') as fh:\n print(f\"Scores:\", file=fh)\n print(f\"validation loss: {val_loss}\", file=fh)\n print(f\"training loss: {train_loss}\", file=fh)\n\n\nif __name__ == '__main__':\n import argparse\n import json\n \n parser = argparse.ArgumentParser()\n parser.add_argument('config_file', help='path to config file', type=str)\n args = parser.parse_args()\n config_file = args.config_file\n \n with open(config_file, 'r') as fh:\n config = json.load(fh)\n main(**config)\n","repo_name":"sirluk/image_extrapolation_with_pytorch","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"34852192497","text":"#!/usr/bin/env python3\n# Get cheap symbols, and their categories\n\nimport json\nimport os\n# Local\nimport sys, os\nsys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../'))\nfrom lib.filters import get_contracts_cheaper_than\n\n# Main\n# Check params\nif len(sys.argv) < 2:\n print('Provide industry')\n exit(2)\nindustry = sys.argv[1]\n\ntry:\n contracts = get_contracts_cheaper_than(3)\nexcept Exception as e:\n print('ERROR: Could not get contracts:', e)\n exit(1)\n\nret = {\n symbol: info\n for symbol, info\n in contracts.items()\n if info['industry'] == industry\n}\nprint(json.dumps(ret))\n","repo_name":"webclinic017/fintools-clientportal-api","sub_path":"bin/get_lt_for_industry.py","file_name":"get_lt_for_industry.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"42236441558","text":"import os\nimport json\n\nfrom unipath import Path\n\n\ndef setup_env():\n env = Path(__file__).ancestor(2).child('.env.json')\n if env.isfile():\n with open(env) as data_file:\n env_variables = json.load(data_file)\n for env_key, env_value in env_variables.items():\n os.environ[env_key] = env_value\n","repo_name":"JasonMize/critterlopers","sub_path":"conf/setup_env.py","file_name":"setup_env.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"26428613340","text":"\"\"\"Test trained model\"\"\"\nimport os\nimport argparse\nimport torch\nimport numpy as np\nfrom models.pretrained import test_model\nfrom data.data_processing import load_split_train_test\nfrom data.plots import plot_roc, class_bar_plot, confusion_matrix_plot\n\nPARSER = argparse.ArgumentParser(\n description='Use transfer learning on pre-trained models to make new image classifier')\nOPTIONAL = PARSER._action_groups.pop()\nREQUIRED = PARSER.add_argument_group('required arguments')\nREQUIRED.add_argument('-d', '--data_dir',\n help='Path to data dir. Path must contain dirs of images named as each class',\n required=True)\nREQUIRED.add_argument('-m', '--model_path',\n help='Path to model to test', required=True)\nOPTIONAL.add_argument('-b', '--batch_size',\n help='Number of images per batch. Default: 20',\n default=20)\nOPTIONAL.add_argument('-f', '--fig_dir',\n help='Directory to save generated figures. \\\n Default: data/results/testing/figures',\n default='data/results/testing/figures')\nOPTIONAL.add_argument('-o', '--output_dir',\n help='Directory to save generated output. \\\n Default: data/results/testing/csv',\n default='data/results/testing/csv')\nPARSER._action_groups.append(OPTIONAL)\nargs = PARSER.parse_args()\n\n# Ensure output directories exist\nfor folder in [args.fig_dir, args.output_dir]:\n try:\n os.makedirs(folder)\n except FileExistsError:\n # directory already exists\n pass\n\n\nRUN_NAME = args.model_path.split('.')[0].replace('/', '-')\nMODEL_NAME = args.model_path.split('-')[-1].split('.')[0]\n\nif 'inception' in args.model_path:\n CROP_SIZE = 299\n INCEPTION = True\nelse:\n CROP_SIZE = 224\n INCEPTION = False\n\nEVAL_LOADER, _ = load_split_train_test(args.data_dir, args.batch_size,\n 0, CROP_SIZE, None)\n\nMODEL = torch.load(args.model_path)\nDEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nNUM_CLASSES = len(EVAL_LOADER.dataset.classes)\nCONF_MATRIX, TEST_ACC, Y_TRUE, Y_SCORE = test_model(MODEL, DEVICE, EVAL_LOADER, MODEL_NAME)\n\n# Plot class counts\nclass_bar_plot(EVAL_LOADER, args.fig_dir, RUN_NAME)\n\n# Save output\nconfusion_matrix_plot(EVAL_LOADER, CONF_MATRIX, args.fig_dir, RUN_NAME)\nnp.savetxt(f'{args.output_dir}{os.sep}{RUN_NAME}-conf_matrix.csv',\n CONF_MATRIX, fmt='%1.8f', delimiter=',', newline='\\n')\nwith open(f'{args.output_dir}{os.sep}{RUN_NAME}-faccuracy.csv', 'w') as f:\n f.write(str(TEST_ACC))\n\nplot_roc(Y_TRUE, Y_SCORE, NUM_CLASSES, args.output_dir, args.fig_dir, RUN_NAME, )\n","repo_name":"grossular/pancreas-classification","sub_path":"src/test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":2736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"44146521703","text":"import warnings\nimport itertools\nimport numpy as np\nimport matplotlib.pyplot as plt\nwarnings.filterwarnings(\"ignore\")\nplt.style.use('fivethirtyeight')\nimport pandas as pd\nimport statsmodels.api as sm\nimport matplotlib\nmatplotlib.rcParams['axes.labelsize'] = 14\nmatplotlib.rcParams['xtick.labelsize'] = 12\nmatplotlib.rcParams['ytick.labelsize'] = 12\nmatplotlib.rcParams['text.color'] = 'k'\n\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport shutil\nimport pandas as pd\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import r2_score, mean_squared_error\nimport ml_metrics as metrics\n\nfrom fbprophet import Prophet\n\n\n#%% Load data\n\ndata_sheets = [\n # 'A1_no_negatives.xlsx',\n # 'A1.xlsx',\n # 'A2.xlsx',\\\n # 'A3.xlsx',\\\n 'A4.xlsx'\n ]\n\noptions = [\n # 'Main Data',\\\n # 'A2',\\\n # 'A3',\\\n 'A4'\n ]\n\nfor sheet in data_sheets:\n for opt in options:\n\n data_to_input = sheet\n option = opt\n\n data_name = data_to_input[0:-5] + '_' + str(option)\n if os.path.exists('.' + os.sep + data_name):\n shutil.rmtree('.' + os.sep + data_name)\n os.mkdir('.' + os.sep + data_name)\n current_dir = '.' + os.sep + data_name\n\n print('Loading data...please wait')\n df = pd.read_excel(data_to_input, str(option), convert_float=True,\n dtype={'a': np.float64, 'b': np.int32})\n\n print(\"DATA BEING ANALYZED: \", data_to_input)\n print(\"TAB: \", opt)\n\n print('------------------------------------------------------------------')\n\ndf['date'] += pd.to_timedelta(df.hour, unit='h')\ndf = df.sort_values(by=['date'])\n\ndata = df\ndata = data.filter(items = ['date', 'Energy (kWh)'])\n\n# scaler = StandardScaler()\n# data = scaler.fit_transform(data)\n\ndata = data.rename(columns={ \"Energy (kWh)\": \"energy\"})\ndata = data.set_index('date')\n\ny = data['energy']\ny = y.resample('MS').mean()\n\n\n#%% Data Decomposition\nfrom pylab import rcParams\nrcParams['figure.figsize'] = 18, 8\ndecomposition = sm.tsa.seasonal_decompose(y, model='additive', period = 30)\nfig = decomposition.plot()\nplt.show()\nplt.savefig(current_dir + os.sep + 'DATA_DECOMPOSITION.png')\nplt.close()\n\n#%% Fit an ARIMA\np = d = q = range(0, 2)\npdq = list(itertools.product(p, d, q))\nseasonal_pdq = [(x[0], x[1], x[2], 12) for x in list(itertools.product(p, d, q))]\nprint('Examples of parameter combinations for Seasonal ARIMA...')\nprint('SARIMAX: {} x {}'.format(pdq[1], seasonal_pdq[1]))\nprint('SARIMAX: {} x {}'.format(pdq[1], seasonal_pdq[2]))\nprint('SARIMAX: {} x {}'.format(pdq[2], seasonal_pdq[3]))\nprint('SARIMAX: {} x {}'.format(pdq[2], seasonal_pdq[4]))\n\nwarnings.filterwarnings(\"ignore\")\nfor param in pdq:\n for param_seasonal in seasonal_pdq:\n try:\n mod = sm.tsa.statespace.SARIMAX(endog=train.Rides,\\\n trend='n',\\\n order=(1,0,1),\\\n seasonal_order=(1,0,1,12))\n\n results = mod.fit()\n\n print('ARIMA{}x{}12 - AIC:{}'.format(param, param_seasonal, results.aic))\n except:\n continue\n\nmod = sm.tsa.statespace.SARIMAX(y,\n order=(1, 0, 1),\n seasonal_order=(1, 0, 1, 12),\n enforce_stationarity=False,\n enforce_invertibility=False)\nresults = mod.fit()\nprint(results.summary().tables[1])\n\n#%% Model Diagnostics\n\nresults.plot_diagnostics(figsize=(16, 8))\nplt.show()\nplt.savefig(current_dir + os.sep + 'SARIMAX_DIAGNOSTICS.png')\nplt.close()\n\n#%% Validating Forecast\nstart_forecast = 100\npred = results.get_prediction(start=start_forecast, dynamic=False)\npred_ci = pred.conf_int()\n\nax = y.plot(label='observed')\npred.predicted_mean.plot(ax=ax, label='Predictions', alpha=.7)\n\nax.fill_between(pred_ci.index,\n pred_ci.iloc[:, 0],\n pred_ci.iloc[:, 1], color='k', alpha=.2)\n\nax.set_xlabel('Date')\nax.set_ylabel('Energy')\nplt.legend()\n\nplt.show()\nplt.savefig(current_dir + os.sep + 'SARIMAX_VALIDATION.png')\nplt.close()\n\ny_forecasted = pred.predicted_mean\ny_truth = y[100:]\n\n#%% Accuracy metrics\n\n# Accuracy metrics\ndef forecast_accuracy(forecast, actual):\n mape = np.mean(np.abs(forecast - actual)/np.abs(actual)) # MAPE\n rmse = np.mean((forecast - actual)**2)**.5 # RMSE\n mse = mean_squared_error(actual,forecast) # mse\n r2 = r2_score(actual,forecast) #r2\n print({'mape':mape, 'rmse':rmse, 'mse':mse, 'r2':r2})\n return({mape, rmse, mse, r2})\n\nmape, rmse, mse, r2 = forecast_accuracy(y_forecasted, y_truth)\n\nmetrics = pd.DataFrame(data = (mape, rmse, mse, r2),\\\n index = ('mape', 'rmse', 'mse', 'r2'))\nmetrics.to_csv(current_dir + os.sep + 'SARIMAX_METRICS.csv')\n\n#%% Forecast 1y\nyears = 1\npred_uc = results.get_forecast(steps=12*years)\npred_ci = pred_uc.conf_int()\nax = y.plot(label='observed', figsize=(14, 7))\npred_uc.predicted_mean.plot(ax=ax, label='Forecast')\nax.fill_between(pred_ci.index,\n pred_ci.iloc[:, 0],\n pred_ci.iloc[:, 1], color='k', alpha=.25)\nax.set_xlabel('Date')\nax.set_ylabel('Energy')\nplt.legend()\nplt.show()\nplt.savefig(current_dir + os.sep + 'SARIMAX_FORECAST_1y.png')\nplt.close()\n\n#%% Forecast 5y\nyears = 5\npred_uc = results.get_forecast(steps=12*years)\npred_ci = pred_uc.conf_int()\nax = y.plot(label='observed', figsize=(14, 7))\npred_uc.predicted_mean.plot(ax=ax, label='Forecast')\nax.fill_between(pred_ci.index,\n pred_ci.iloc[:, 0],\n pred_ci.iloc[:, 1], color='k', alpha=.25)\nax.set_xlabel('Date')\nax.set_ylabel('Energy')\nplt.legend()\nplt.show()\nplt.savefig(current_dir + os.sep + 'SARIMAX_FORECAST_5y.png')\nplt.close()\n\n#%% Data Pre-processing\ndata = df\ndata = data.filter(items = ['date', 'Energy (kWh)'])\n\ndata = data.rename(columns={ \"Energy (kWh)\": \"energy\"})\ndata = data.set_index('date')\n\ny = data['energy']\ny = y.resample('W').mean()\n\ndata = y.to_frame()\ndata = data.reset_index()\n\ndata = data.rename(columns={\"date\": \"ds\", \"energy\": \"y\"})\n\n#%% Fit a PROPHET\nprint('Training a prophet...')\nm = Prophet()\nm.fit(data)\n\n#%% Forecast 1 year\nyears = 1\nfuture = m.make_future_dataframe(periods=365*years)\nfuture.tail()\n\nforecast = m.predict(future)\nforecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()\n\nfig1 = m.plot(forecast)\nplt.savefig(current_dir + os.sep + 'PROPHET_FORECAST_1y.png')\nplt.close()\n\nfig2 = m.plot_components(forecast)\nplt.savefig(current_dir + os.sep + 'PROPHET_COMPONENTS.png')\nplt.close()\n\n#%% Forecast 5 years\nyears = 5\nfuture = m.make_future_dataframe(periods=365*years)\nfuture.tail()\n\nforecast = m.predict(future)\nforecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()\n\nfig1 = m.plot(forecast)\nplt.savefig(current_dir + os.sep + 'PROPHET_FORECAST_5y.png')\nplt.close()\n\n#%% Accuracy Metrics\n\nmetric_df = forecast.set_index('ds')[['yhat']].join(data.set_index('ds').y)\\\n .dropna().reset_index()\n\nmape, rmse, mse, r2 = forecast_accuracy(metric_df.yhat, metric_df.y)\n\nmetrics = pd.DataFrame(data = (mape, rmse, mse, r2),\\\n index = ('mape', 'rmse', 'mse', 'r2'))\nmetrics.to_csv(current_dir + os.sep + 'PROPHET_METRICS.csv')\n","repo_name":"quaesito/time-series-forecast-sarimax-prophet","sub_path":"energy_prediction.py","file_name":"energy_prediction.py","file_ext":"py","file_size_in_byte":7287,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"41"} +{"seq_id":"31479949317","text":"from imutils.object_detection import non_max_suppression\nfrom utils import text_filter\n\nimport numpy as np\nimport pytesseract\nimport argparse\nimport cv2\nimport re\nimport os\n\n\ndef _decode_predictions(scores, geometry):\n # grab the number of rows and columns from the scores volume, then\n # initialize our set of bounding box rectangles and corresponding0\n # confidence scores\n (numRows, numCols) = scores.shape[2:4]\n rects = []\n confidences = []\n\n # loop over the number of rows\n for y in range(0, numRows):\n # extract the scores (probabilities), followed by the\n # geometrical data used to derive potential bounding box\n # coordinates that surround text\n scoresData = scores[0, 0, y]\n xData0 = geometry[0, 0, y]\n xData1 = geometry[0, 1, y]\n xData2 = geometry[0, 2, y]\n xData3 = geometry[0, 3, y]\n anglesData = geometry[0, 4, y]\n\n # loop over the number of columns\n for x in range(0, numCols):\n # if our score does not have a minimum of 0.5 probability, ignore it\n if scoresData[x] < 0.5:\n continue\n\n # compute the offset factor as our resulting feature\n # maps will be 4x smaller than the input image\n (offsetX, offsetY) = (x * 4.0, y * 4.0)\n\n # extract the rotation angle for the prediction and\n # then compute the sin and cosine\n angle = anglesData[x]\n cos = np.cos(angle)\n sin = np.sin(angle)\n\n # use the geometry volume to derive the width and height\n # of the bounding box\n h = xData0[x] + xData2[x]\n w = xData1[x] + xData3[x]\n\n # compute both the starting and ending (x, y)-coordinates\n # for the text prediction bounding box\n endX = int(offsetX + (cos * xData1[x]) + (sin * xData2[x]))\n endY = int(offsetY - (sin * xData1[x]) + (cos * xData2[x]))\n startX = int(endX - w)\n startY = int(endY - h)\n\n # add the bounding box coordinates and probability score\n # to our respective lists\n rects.append((startX, startY, endX, endY))\n confidences.append(scoresData[x])\n\n # return a tuple of the bounding boxes and associated confidences\n return rects, confidences\n\n\ndef _apply_pytesseract_predictions(image, rW, rH, boxes):\n \"\"\"\n Extract the texts using pytesseract from the text boxes detected with the text detector.\n :param image:\n :param rH:\n :param rW:\n :param boxes: decoded predictions from the EAST text detector.\n :return: the list of all detected texts.\n \"\"\"\n texts = []\n\n # loop over the bounding boxes\n for (startX, startY, endX, endY) in boxes:\n (origH, origW) = image.shape[:2]\n # scale the bounding box coordinates based on the respective ratios\n startX = int(startX * rW)\n startY = int(startY * rH)\n endX = int(endX * rW)\n endY = int(endY * rH)\n\n # remove extreme numbers\n startX = max(0, startX)\n startY = max(0, startY)\n endX = min(origW, endX)\n endY = min(origH, endY)\n\n # extract the actual padded ROI\n roi = image[startY:endY, startX:endX]\n\n # in order to apply Tesseract v4 to OCR text we must supply\n # (1) a language, (2) an OEM flag of 4, indicating that the we\n # wish to use the LSTM neural net model for OCR, and finally\n # (3) an OEM value, in this case, 7 which implies that we are\n # treating the ROI as a single line of text\n config = \"-l eng --oem 1 --psm 7\"\n text = pytesseract.image_to_string(roi, config=config)\n\n texts.append(text)\n\n return texts\n\n\nclass EastTextDetector:\n __east_net = None\n __layer_names = None\n\n def __init__(self) -> None:\n super().__init__()\n # load the pre-trained EAST text detector\n print(\"[INFO] Loading pre-trained EAST text detector...\")\n self.__east_net = cv2.dnn.readNet(os.path.dirname(__file__) + \"/frozen_east_text_detection.pb\")\n self.__layer_names = [\"feature_fusion/Conv_7/Sigmoid\", \"feature_fusion/concat_3\"]\n\n def extract_text(self, input_img):\n (origH, origW) = input_img.shape[:2]\n\n # set the new width and height and then determine the ratio in change\n # for both the width and height\n # use default of 320 & 320\n (newW, newH) = (320, 320)\n rW = origW / float(newW)\n rH = origH / float(newH)\n\n # resize the image and grab the new image dimensions\n image = cv2.resize(input_img, (newW, newH))\n (H, W) = image.shape[:2]\n\n # construct a blob from the image and then perform a forward pass of\n # the model to obtain the two output layer sets\n blob = cv2.dnn.blobFromImage(image, 1.0, (W, H), (123.68, 116.78, 103.94), swapRB=True, crop=False)\n self.__east_net.setInput(blob)\n (scores, geometry) = self.__east_net.forward(self.__layer_names)\n\n # decode the predictions, then apply non-maxima suppression to\n # suppress weak, overlapping bounding boxes\n (rects, confidences) = _decode_predictions(scores, geometry)\n boxes = non_max_suppression(np.array(rects), probs=confidences)\n\n # extract the text using pytesseract\n texts = _apply_pytesseract_predictions(input_img.copy(), rW, rH, boxes)\n\n nprTextsFilter = text_filter.NprTextsFilter()\n dates, numbers = nprTextsFilter.filterDatesAndPlates(texts)\n return dates, numbers\n\n def extract_numbers_first_date(self, input_img):\n \"\"\"\n Extract the detected date and numbers.\n The date is always one, so we only return the first.\n\n :param input_img: the frame upon which we run the text detection and recognition.\n :return: detected date or None if it is not existent, and all detected number plate texts.\n \"\"\"\n dates, numbers = self.extract_text(input_img)\n return dates[0] if len(dates) > 0 else None, numbers\n","repo_name":"ambroziepaval/Number-Plate-Recognition","sub_path":"textdetection/text_recognition.py","file_name":"text_recognition.py","file_ext":"py","file_size_in_byte":6070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"9073018475","text":"## @file\r\n#\r\n# Copyright (c) 2018, Intel Corporation. All rights reserved.
\r\n# SPDX-License-Identifier: BSD-2-Clause-Patent\r\n#\r\n\r\nfrom ctypes import *\r\n\r\nclass EFI_GUID(Structure):\r\n _fields_ = [\r\n ('Guid1', c_uint32),\r\n ('Guid2', c_uint16),\r\n ('Guid3', c_uint16),\r\n ('Guid4', ARRAY(c_uint8, 8)),\r\n ]\r\n\r\nclass EFI_TIME(Structure):\r\n _fields_ = [\r\n ('Year', c_uint16),\r\n ('Month', c_uint8),\r\n ('Day', c_uint8),\r\n ('Hour', c_uint8),\r\n ('Minute', c_uint8),\r\n ('Second', c_uint8),\r\n ('Pad1', c_uint8),\r\n ('Nanosecond', c_uint32),\r\n ('TimeZone', c_int16),\r\n ('Daylight', c_uint8),\r\n ('Pad2', c_uint8),\r\n ]\r\n\r\nEFI_VARIABLE_NON_VOLATILE = 0x00000001\r\nEFI_VARIABLE_BOOTSERVICE_ACCESS = 0x00000002\r\nEFI_VARIABLE_RUNTIME_ACCESS = 0x00000004\r\nEFI_VARIABLE_HARDWARE_ERROR_RECORD = 0x00000008\r\nEFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS = 0x00000020\r\nEFI_VARIABLE_APPEND_WRITE = 0x00000040\r\nEFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS = 0x00000010\r\n","repo_name":"shafiuzzaman-md/harden-HBFA","sub_path":"HBFA/UefiHostFuzzTestCasePkg/Seed/Include/Uefi.py","file_name":"Uefi.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"41"} +{"seq_id":"29519369540","text":"import os\nimport json\nimport pytest\nimport jsonschema\nfrom datacatalog.jsonschemas.schema import JSONSchemaBaseObject\n\nHERE = os.path.dirname(os.path.abspath(__file__))\nPARENT = os.path.dirname(HERE)\nDATA_DIR = os.path.join(HERE, 'data/sampleset')\n\ndef resolver(base_uri=JSONSchemaBaseObject.BASEREF, schema='sample_set'):\n remote_uri = base_uri + schema + '.json'\n return jsonschema.RefResolver('', '').resolve_remote(remote_uri)\n\n@pytest.mark.networked\n@pytest.mark.parametrize(\"jsonfile\", [('17016_87542.json'), ('20249.json'), ('95463.json'), ('Novelchassis_Nand_gate_controls.json'), ('Novelchassis_Nand_gate_samples.json'), ('r1btfp5k2edgn_r1btpym75nsdh_samples.json'), ('r1bzc55fpurbj.json'), ('samples_nc.json'), ('62215.json'), ('r1bsmgdayg2yq_r1bsu7tb7bsuk_samples.json')])\ndef test_validate_sample_set(jsonfile):\n class formatChecker(jsonschema.FormatChecker):\n def __init__(self):\n jsonschema.FormatChecker.__init__(self)\n\n res = resolver(schema='sample_set')\n jsonpath = os.path.join(DATA_DIR, jsonfile)\n instance = json.load(open(jsonpath, 'r'))\n assert jsonschema.validate(\n instance, res, format_checker=formatChecker()) is None\n","repo_name":"SD2E/python-datacatalog","sub_path":"tests/test_010_validate_jsonschema.py","file_name":"test_010_validate_jsonschema.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"9302862833","text":"import turtle\n\nwindow = turtle.Screen()\nwindow.bgcolor(\"orange\")\n\nsam = turtle.Turtle()\nsam.shape(\"turtle\")\nsam.color(\"black\")\nsam.speed(30)\n\ndef draw_squares():\n step = 0\n square = 4\n while step < square:\n sam.forward(100)\n sam.right(90)\n step +=1\n\ndraw_squares()\n\nsquares = 0\ncircle = 36\nwhile squares < circle:\n sam.right(10)\n draw_squares()\n squares +=1\n\nsam.right(90)\nsam.forward(300)\n\n\nwindow.exitonclick()\n","repo_name":"tiifffany/ipnd","sub_path":"part4/miniproject/draw_turtles.py","file_name":"draw_turtles.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"73989404923","text":"from django.conf.urls import url\nfrom . import views\n\n\nurlpatterns = [\n url(r'^$', views.wiki_list, name='wiki_list'),\n url(r'^(?P\\d+)/$', views.wiki_details, name='wiki_details'),\n url(r'^(?P\\d+)/add/$', views.add_wiki, name='add_wiki'),\n url(r'^(?P\\d+)/edit/$', views.edit_wiki, name='edit_wiki'),\n url(r'^(?P\\d+)/delete/$', views.delete_wiki, name='delete_wiki'),\n]","repo_name":"kavzov/draft","sub_path":"backend/taiga/wiki/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"8926405404","text":"#! /usr/bin/env python3\n\nfrom solution import Solution\n\ndef main():\n sol = Solution()\n height = [1, 8, 6, 2, 5, 4, 8, 3, 7]\n\n ans = sol.maxArea(height)\n print(f\"height = {height}\")\n print(f\"ans = {ans}\")\n\n#---------------Execution---------------#\nif __name__ == '__main__':\n main()\n","repo_name":"Coslate/LeetCode","sub_path":"P11_Container_With_Most_Water/Python/my_imp/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"31700028891","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport tkinter\nimport matplotlib\nmatplotlib.use('TkAgg')\n\n\nX = 2 * np.random.rand(100, 1)\ny = 4 + 3 * X + np.random.randn(100, 1)\n\n#print(X)\n\nX_b = np.c_[np.ones((100, 1)), X] # add x0 = 1 to each instance\n#print(X_b)\n\ntheta_best = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y)\n\n#print(theta_best)\n\nX_new = np.array([[0], [2]])\nprint(X_new)\n\nX_test = np.c_[np.ones((2, 2)), X_new] # add x0 = 1 to each instance\nprint(X_test)\n\n\nX_new_b = np.c_[np.ones((2, 1)), X_new] # add x0 = 1 to each instance\nprint(X_new_b)\n\ny_predict = X_new_b.dot(theta_best)\nprint(y_predict)\n\nfig, ax = plt.subplots(1,1,figsize=(14,14), dpi= 80)\n\nplt.plot(X_new, y_predict, \"r-\")\nplt.plot(X, y, \"b.\")\nplt.axis([0, 2, 0, 15])\n#plt.savefig(\"mygraph.png\")\nplt.show()\n\n","repo_name":"paulomiranda10/data-science-studies","sub_path":"LinearRegressionHousing/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"43426938718","text":"import cv2\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nimport math\r\n\r\nimg = cv2.imread('test2.png',cv2.IMREAD_GRAYSCALE)\r\ndft = cv2.dft(np.float32(img), flags=cv2.DFT_COMPLEX_OUTPUT) # 将空间域转换为频率域\r\ndft_shift = np.fft.fftshift(dft) # 将低频部分移动到图像中心\r\n\r\n\r\n\r\nimg2 = cv2.imread('img.jpg',cv2.IMREAD_GRAYSCALE)\r\ndft2 = cv2.dft(np.float32(img2), flags=cv2.DFT_COMPLEX_OUTPUT) # 将空间域转换为频率域\r\ndft_shift2 = np.fft.fftshift(dft2) # 将低频部分移动到图像中心\r\n\r\nf = cv2.magnitude(dft_shift[:, :, 0], dft_shift[:, :, 1])\r\nf2 = cv2.magnitude(dft_shift2[:, :, 0], dft_shift2[:, :, 1])\r\n\r\nplt.figure()\r\nplt.subplot(121),plt.imshow(20*np.log(f+1),cmap='gray')\r\nplt.subplot(122),plt.imshow(20*np.log(f2+1),cmap='gray')\r\nplt.show()","repo_name":"liyue983/DIPClass","sub_path":"final/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"21290853307","text":"#!usr/bin/python3\n\nimport itertools\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom collections import defaultdict\n#import enchant\n\nclass FunctionWords(TransformerMixin):\n def __init__(self, top=2500):\n self.top = top\n\n def fit(self, X, y=None):\n functionwords = {}\n labels = list(set(y))\n self.f = [[] for i in labels]\n for i in range(len(X)):\n label = y[i]\n for doc in X[i]:\n for token in doc:\n if len(token)>3 and not token[0]=='#':\n if token.lower() in functionwords:\n functionwords[token.lower()][labels.index(label)]+=1\n else:\n functionwords[token.lower()]=[1]*len(labels)\n for token, counts in functionwords.items():\n for i in range(len(counts)):\n self.f[i].append((token, counts[i]/sum(counts)))\n for j in range(len(self.f)):\n self.f[j] = [k[0] for k in sorted(self.f[j], key=lambda x: x[1], reverse=True)[:self.top]]\n return self\n\n def transform(self, X):\n newX = []\n for x in X:\n newx = [0]*len(self.f)\n tokens = list(itertools.chain(*x))\n tokens = [i.lower() for i in tokens]\n for i in range(len(self.f)):\n newx[i]+=len(set(self.f[i]).intersection(tokens))\n newX.append(newx)\n return newX\n \nclass PosVec(TransformerMixin):\n def __init__(self, Xtrain, pos_train, pos_test):\n self.Xtrain = Xtrain\n self.pos_train = pos_train\n self.pos_test = pos_test\n\n def fit(self, X, y=None):\n return self\n\n def transform(self, X):\n newX = []\n if len(self.pos_test)==0 or len(X)==len(self.pos_train):\n for x in X:\n postags = self.pos_train[self.Xtrain.index(x)]\n newX.append(' '.join(postags))\n else:\n for x in X:\n postags = self.pos_test[X.index(x)]\n newX.append(' '.join(postags))\n return newX\n\nclass FirstOrder(TransformerMixin):\n '''Parent class for second order real valued features'''\n def fit(self, X, y=None):\n return self\n\n def transform(self, X):\n newX = [[self.calculate(x)] for x in X]\n return newX\n\nclass SecondOrderReal(TransformerMixin):\n '''Parent class for second order real valued features'''\n def fit(self, X, y=None):\n labels = list(set(y))\n values = {key: 0 for key in labels}\n counts = {key: 0 for key in labels}\n for i in range(len(X)):\n value = self.calculate(X[i])\n values[y[i]] += value\n counts[y[i]] += 1\n for key in values: # get value relative to count\n values[key] = values[key] / counts[key]\n for key in values: # get value relative to other labels\n values[key] = (values[key]*len(labels)) / sum(values.values())\n self.dist = values.values()\n return self\n\n def transform(self, X):\n newX = []\n values = [self.calculate(x) for x in X] # get values\n avg = sum(values)/len(values)\n for value in values:\n avgvalue = value/avg\n newX.append([avgvalue - i for i in self.dist])\n return newX\n\nclass AverageWordLength(SecondOrderReal):\n '''Calculates average token length for author'''\n def calculate(self, x):\n total = 0\n tokens = 0\n for tweet in x:\n for token in tweet:\n if len(token)>1:\n total+=len(token)\n tokens+=1\n try:\n result = total/tokens\n except:\n result = 0\n return result\n\nclass AverageSentenceLength(SecondOrderReal):\n '''Calculates average sentence length (in tokens) for author'''\n def calculate(self, x):\n sentences = 0\n tokens = 0\n for tweet in x:\n sentences+=1\n tokens+=len(tweet)\n result = tokens/sentences\n return result\n\nclass StartsWithCapital(SecondOrderReal):\n '''Percentage of tweets that start with capital letter'''\n def calculate(self, user_tweets):\n starts_with_capital = 0\n for user_tweet in user_tweets:\n if len(user_tweet) > 0:\n if user_tweet[0][0].isupper():\n starts_with_capital += 1\n result = starts_with_capital/len(user_tweets)\n return result\n\nclass EndsWithPunctuation(SecondOrderReal):\n '''Percentage of tweets that end with punctuation'''\n def calculate(self, user_tweets):\n ends_with_punctuation = 0\n punctuation = ['!', '.', '?']\n for user_tweet in user_tweets:\n if len(user_tweet) > 0:\n if user_tweet[-1][-1] in punctuation:\n ends_with_punctuation += 1\n result = ends_with_punctuation/len(user_tweets)\n return result\n\nclass Misspell(SecondOrderReal):\n def __init__(self, language):\n self.language = language\n if self.language == 'english':\n self.d = enchant.Dict('en')\n if self.language == 'spanish':\n self.d = enchant.Dict('es')\n if self.language == 'dutch':\n self.d = enchant.Dict('nl')\n\n def calculate(self, user_tweets): \n all_tokens_user = 0\n for user_tweet in user_tweets:\n mspl = 0\n for token in user_tweet:\n if self.d.check(token) == False:\n mspl += 1\n all_tokens_user += len(user_tweet)\n result = mspl/all_tokens_user\n return result\n \nclass PunctuationByTweet(SecondOrderReal):\n '''Average of percentage of punctuation characters per tweet'''\n def calculate(self, user_tweets):\n average_count = 0\n punctuation = [',', '.', ';', '!', '?', '-']\n for user_tweet in user_tweets:\n if len(user_tweet) > 0:\n punctuation_count = 0\n number_of_characters = 0\n for tok in user_tweet:\n number_of_characters += len(tok)\n if tok[-1] in punctuation:\n punctuation_count += 1\n average_count += punctuation_count / number_of_characters\n \n result = average_count/len(user_tweets)\n return result\n\n \nclass CapitalizedTokens(SecondOrderReal):\n '''Average of percentage of capitalized tokens per tweet'''\n def calculate(self, user_tweets):\n average_count = 0\n for user_tweet in user_tweets:\n if len(user_tweet) > 0:\n capitalized_count = 0\n for tok in user_tweet:\n if tok[0].isupper():\n if tok not in ['AT_USER', 'URL', 'NUMBER']:\n capitalized_count += 1\n average_count += capitalized_count / len(user_tweet)\n \n result = average_count/len(user_tweets)\n return result\n\nclass CapitalLetters(SecondOrderReal):\n '''Average of percentage of capitalized letters per tweet'''\n def calculate(self, user_tweets):\n average_count = 0\n \n for user_tweet in user_tweets:\n if len(user_tweet) > 0:\n capital_letter_count = 0\n number_of_characters = 0\n for tok in user_tweet:\n number_of_characters += len(tok)\n for character in tok:\n if character.isupper():\n capital_letter_count += 1\n average_count += capital_letter_count / number_of_characters\n \n result = average_count/len(user_tweets)\n return result\n\nclass EmoticonNoses(SecondOrderReal):\n\t'''Average of percentage of emoticons with noses, out of total emoticons, per tweet'''\n\tdef calculate(self, user_tweets):\n\t\taverage_count = 0\n\t\tnum_emoticon_tweets = 0\n\t\tfor user_tweet in user_tweets:\n\t\t\tnose_count = 0\n\t\t\temoticon_count = 0\n\t\t\tfor tok in user_tweet:\n\t\t\t\tif ':-' in tok: # nose emoticon\n\t\t\t\t\tnose_count += 1\n\t\t\t\tif len(tok) > 1 and tok[0] in [':', ';', '=']: # any emoticon\n\t\t\t\t\temoticon_count += 1\n#\t\t\t\t\tprint(tok)\n#\t\t\t\t\tprint(len(tok))\n#\t\t\tprint(emoticon_count)\n\t\t\tif emoticon_count > 0:\n\t\t\t\tnum_emoticon_tweets += 1\n#\t\t\t\tprint('num_emoticon_Tweets: %s' % num_emoticon_tweets)\n\t\t\t\taverage_count += nose_count / emoticon_count\n\t\ttry:\n\t\t\tresult = average_count / num_emoticon_tweets\n\t\texcept ZeroDivisionError:\n\t\t\tresult = 0.5 # Impute 0.5 for emoticon-less users\n#\t\tprint('result: %.2f' % result)\n\t\treturn result\n\nclass EmoticonReverse(SecondOrderReal):\n\t'''Average of percentage of reverse emoticons (:, out of total emoticons, per tweet'''\n\tdef calculate(self, user_tweets):\n\t\taverage_count = 0\n\t\tnum_emoticon_tweets = 0\n\t\tfor user_tweet in user_tweets:\n\t\t\treverse_count = 0\n\t\t\temoticon_count = 0\n\t\t\tfor tok in user_tweet:\n\t\t\t\tif len(tok) > 1 and tok[0] in [':', ';', '=']: # any emoticon\n\t\t\t\t\temoticon_count += 1\n\t\t\t\tif len(tok) > 1 and tok[-1] in [':', ';', '=']: # any reverse emoticon\n\t\t\t\t\treverse_count += 1 \n\t\t\t\t\temoticon_count += 1\n\t\t\tif emoticon_count > 0:\n\t\t\t\tnum_emoticon_tweets += 1\n\t\t\t\taverage_count += reverse_count / emoticon_count\n\t\ttry:\n\t\t\tresult = average_count / num_emoticon_tweets\n\t\texcept ZeroDivisionError:\n\t\t\tresult = 0.5 # Impute 0.5 for emoticon-less users\n\t\treturn result\n\nclass EmoticonCount(SecondOrderReal):\n\t'''Average of percentage of tokens that are emoticons, per tweet'''\n\tdef calculate(self, user_tweets):\n\t\taverage_count = 0\n\t\tfor user_tweet in user_tweets:\n\t\t\temoticon_count = 0\n\t\t\tfor tok in user_tweet:\n\t\t\t\tif len(tok) > 1 and (tok[0] in [':', ';', '='] or tok[-1] in [':', ';', '=']):\n\t\t\t\t\temoticon_count += 1\n\t\t\ttry:\n\t\t\t\taverage_count += emoticon_count / len(user_tweet)\n\t\t\texcept ZeroDivisionError:\n\t\t\t\taverage_count += 0\n\n\t\tresult = average_count / len(user_tweets)\n\t\treturn result\n\nclass EmoticonEmotion(SecondOrderReal):\n\t'''Average of percentage of happy emoticons, out of total emoticons, per tweet'''\n\tdef calculate(self, user_tweets):\n\t\taverage_count = 0\n\t\tnum_emoticon_tweets = 0\n\t\tfor user_tweet in user_tweets:\n\t\t\thappy_count = 0\n\t\t\temoticon_count = 0\n\t\t\tfor tok in user_tweet:\n\t\t\t\tif len(tok) > 1 and tok[0] in [':', ';', '=']: # any emoticon\n\t\t\t\t\temoticon_count += 1\n\t\t\t\t\tif tok[-1] in [')', 'D', 'P', ']']:\n\t\t\t\t\t\thappy_count += 1\n\t\t\t\tif len(tok) > 1 and tok[-1] in [':', ';', '=']:\n\t\t\t\t\temoticon_count += 1 \n\t\t\t\t\tif tok[0] in [')', 'D', 'P', ']']:\n\t\t\t\t\t\thappy_count += 1\n\t\t\tif emoticon_count > 0:\n\t\t\t\tnum_emoticon_tweets += 1\n\t\t\t\taverage_count += happy_count / emoticon_count\n\t\ttry:\n\t\t\tresult = average_count / num_emoticon_tweets\n\t\texcept ZeroDivisionError:\n\t\t\tresult = 0.5 # Impute 0.5 for emoticon-less users\n\t\treturn result\n\nclass VocabularyRichness(SecondOrderReal):\n '''Percentage of unique words per user'''\n \n def calculate(self, user_tweets):\n dict = {}\n tokens = 0\n for user_tweet in user_tweets:\n if len(user_tweet) > 0:\n for tok in user_tweet:\n dict[tok]= dict.get(tok, 0) + 1\n tokens+=1\n unique_words = [k for (k, v) in dict.items() if v == 1]\n count = len(unique_words)\n \n result = count/tokens\n return result\n","repo_name":"sixhobbits/ngram","sub_path":"src/features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":11407,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"41"} +{"seq_id":"73770700283","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\n# Parameters\n# `starting_field is a complex 2D field`\n# `wavenumber` of the isotropic, homogeneous medium\n# `dd` the pitch of the x, y sampling grid\n# `distance` to be propagated\n# `p1` is a 3-tuple of the propagation coordinate in 3D. Origin is at the center of the field\ndef propagate_to_point_np(starting_field, dd, wavenumber, p1):\n assert len(p1) == 3\n\n nx, ny = np.shape(starting_field)\n x = (np.arange(0, nx) - nx/2) * dd\n y = (np.arange(0, ny) - ny/2) * dd\n\n yy, xx = np.meshgrid(y, x)\n\n # x, y, and z components of the vector that connects input points to the ouput point\n r01_x = xx - p1[0]\n r01_y = yy - p1[1]\n r01_z = np.full(shape=(nx, ny), fill_value=p1[2])\n\n # distance between all input coordinates and the propagation point\n abs_r01 = np.sqrt(r01_x**2 + r01_y**2 + r01_z**2)\n\n # is equivalent to cosine of angle r01 make with normal\n cos_r01 = r01_z / abs_r01\n\n return wavenumber/(2*np.pi*1j) * np.sum(starting_field * np.exp(1j*wavenumber*abs_r01) / abs_r01 * cos_r01) * dd**2\n\n\ndef propagate_point_np_test():\n aperture = 1e-4\n x = np.linspace(-aperture/2, aperture/2, 100)\n y = x\n dd = x[1] - x[0]\n\n yy, xx = np.meshgrid(y, x)\n\n f = 1e-3\n wavenumber = 2*np.pi/633e-9\n phi = -wavenumber * np.sqrt(xx**2 + y**2 + f**2)\n starting_field = np.exp(1j*phi)\n\n e_field_p1 = propagate_to_point_np(starting_field, dd, wavenumber, (0., 0., f))\n print(np.abs(e_field_p1))\n\n plt.imshow(np.angle(starting_field))\n plt.colorbar()\n plt.show()\n\n def get_total_field(xx, yy):\n return propagate_to_point_np(starting_field, dd, wavenumber, (xx, yy, f))\n\n get_total_field = np.vectorize(get_total_field)\n\n total_field = get_total_field(xx, yy)\n intensity = np.abs(total_field)**2\n\n plt.imshow(intensity)\n plt.colorbar()\n plt.show()\n\n print(np.mean(intensity))\n\n\n\n\n\nif __name__=='__main__':\n propagate_point_np_test()","repo_name":"JamesWhitehead5/AngularPropagateTensorflow","sub_path":"Rayleigh-Sommerfeld.py","file_name":"Rayleigh-Sommerfeld.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"21835613278","text":"import numpy as np\r\nfrom sklearn.ensemble import AdaBoostClassifier\r\nfrom sklearn.model_selection import KFold\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.naive_bayes import GaussianNB\r\nfrom sklearn.svm import SVC, LinearSVC\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.gaussian_process import GaussianProcessClassifier\r\n\r\ntraining_dataset = np.loadtxt(r'training_data.csv', delimiter=',')\r\n\r\n# obtain the attributes\r\nX = training_dataset[:, 0:-1]\r\n\r\n# obtain the classes\r\ny = training_dataset[:, -1]\r\n\r\nrandom_forest = RandomForestClassifier()\r\ndecision_tree = DecisionTreeClassifier()\r\nk_neighbours = KNeighborsClassifier()\r\nnaive_bayes = GaussianNB()\r\nsvc = LinearSVC()\r\nlogistic_reg = LogisticRegression()\r\ngaussian_process = GaussianProcessClassifier()\r\n\r\n# Create adaboost classifier object\r\nadaboost = AdaBoostClassifier(n_estimators=50, learning_rate=1)\r\n# adaboost = AdaBoostClassifier(n_estimators=50, base_estimator=random_forest, learning_rate=1)\r\n# adaboost = AdaBoostClassifier(n_estimators=50, base_estimator=decision_tree, learning_rate=1)\r\n# -adaboost = AdaBoostClassifier(n_estimators=50, base_estimator=k_neighbours, learning_rate=1)-\r\n# -adaboost = AdaBoostClassifier(n_estimators=50, base_estimator=naive_bayes, learning_rate=1)-\r\n# -adaboost = AdaBoostClassifier(n_estimators=50, base_estimator=svc, learning_rate=1)-\r\n# -adaboost = AdaBoostClassifier(n_estimators=50, base_estimator=logistic_reg, learning_rate=1)-\r\n# -adaboost = AdaBoostClassifier(n_estimators=50, base_estimator=gaussian_process, learning_rate=1)-\r\n\r\nk_fold = KFold(n_splits=10)\r\n\r\nprint(\"\")\r\nprint(\"The validation used in this experiment is:\")\r\nprint(k_fold)\r\nprint(\"\")\r\nprint(\"The classifier used in this experiment is:\")\r\nprint(adaboost)\r\nprint(\"=======\")\r\nprint(\"Training performed on the training data:\")\r\n\r\nscore_collection = []\r\nfold_number = 0\r\nfor train_index, test_index in k_fold.split(X):\r\n print(\"Fold: \" + str(fold_number))\r\n X_train, X_test = X[train_index], X[test_index]\r\n y_train, y_test = y[train_index], y[test_index]\r\n\r\n adaboost.fit(X_train, y_train)\r\n\r\n predictions = adaboost.predict(X_test)\r\n\r\n accuracy = accuracy_score(y_test, predictions)\r\n score_collection.append(accuracy)\r\n fold_number = fold_number + 1\r\naccuracy = np.mean(score_collection)\r\nstandard_deviation = np.std(score_collection)\r\nprint(\"Finished training via validation:\")\r\nprint(\"Accuracy: \" + str(accuracy * 100) + \", Standard deviation: \" + str(standard_deviation * 100))\r\n","repo_name":"jessica-lal/FYPcode","sub_path":"classify-adaboost.py","file_name":"classify-adaboost.py","file_ext":"py","file_size_in_byte":2673,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"26398337564","text":"s1 = set((1,2,3,4))\ns2 = {1, 5, 7, 9, 3}\n'''print(s1)\nprint(type(s1))\nprint(s2)'''\nfor x in s1:\n print(x)\nFruits = { \"mango\", \"carrot\",\"onion\",\"grapes\"}\nprint(\"onion\" in Fruits)\nFruits.add(\"orange\")\nprint(Fruits)\nTropical = {\"mango\",\"apple\", \"banana\", \"cherry\"}\nAll = Fruits.union(Tropical)\nprint(All)\nFruits.remove(\"onion\")\nprint(Fruits)\nu1 = {1,2,3,4}\nu2 = {5,8,6,7}\nu3 = u1.isdisjoint(u2)\nprint(u3)","repo_name":"Tiger-a11y/PythonProjects","sub_path":"Sets.py","file_name":"Sets.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"35709062221","text":"#!/usr/bin/env python3\nfrom __future__ import print_function\n\nimport sys\nsys.path.append(\"//media/juro/DATA/Work/Elections/code/python\")\n\nimport copy\nfrom datetime import datetime\nfrom googleapiclient.discovery import build\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\nfrom google.oauth2.credentials import Credentials\nfrom math import isnan\nimport numpy as np\nfrom numpy import matlib\nimport os.path\nimport pandas as pd\nfrom pandasql import sqldf\nimport scipy.sparse\nimport scipy.sparse.linalg\n\nimport config\nimport google_api_functions\nimport location_functions\nimport plotting_functions\nimport seaborn as sns\n\n####################################################################################################################\n# DOWNLOAD THE PARTY NUMBERS AND NAMES\n####################################################################################################################\nservice = google_api_functions.establish_connection()\n\n# # Call the Sheets API\nresult = service.spreadsheets().values().get(spreadsheetId=config.SPREADSHEET_ID,\n range=config.RANGE_PARTY_NAMES).execute()\nvalues = result.get('values', [])\n\n#Find the number of parties:\ndf_parties = pd.DataFrame(values, columns = ['party_ID', 'party_name'])\n\n########################################################################################################################\n# SELECTING THE PROPER VALUE OF v\n########################################################################################################################\n\n# theta_set = [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1]\n# low_set = [0.5,0.6,0.7,0.8,0.9,1]\n# high_set = [1,1.1,1.2,1.3,1.4,1.5]\n#\n#\n# # theta_set = [0,0.05,0.1,0.15,0.2,0.25,0.3,0.35,0.4,0.45,0.5,0.55,0.6,0.65,0.7,0.75,0.8,0.85,0.9,0.95,1]\n# # low_set = [0.5,0.7,0.9]\n# # high_set = [1.1,1.3,1.5]\n#\n# K=len(theta_set)\n# df = pd.DataFrame(columns=['low', 'high', 'theta', 'phase','squared_difference'])\n# phase = 0\n# for phase in range(0,4):\n# for low in low_set:\n# for high in high_set:\n# # for theta in theta_set:\n# # print(datetime.now().strftime('%Y-%m-%d %H:%M:%S') + \": \" + \"Wrangling data for low = \" + str(low) + \", high = \" + str(high) + \", phase = \" + str(phase) + \" and theta = \" + str(theta) + \".\")\n# print(datetime.now().strftime('%Y-%m-%d %H:%M:%S') + \": \" + \"Wrangling data for low = \" + str(\n# low) + \", high = \" + str(high) + \", phase = \" + str(phase) + \".\")\n# # df_squared_difference = pd.read_csv(config.data_path + \"simulation/theta_\" + str(theta) + \"low_\" + str(low) + \"high_\" + str(high) + \".csv\").iloc[:,[phase]]\n# df_squared_difference = pd.read_csv(\n# config.data_path + \"simulation/low_\" + str(low) + \"high_\" + str(\n# high) + \".csv\").iloc[:, [phase]]\n# N = len(df_squared_difference)\n# df_squared_difference.columns=['squared_difference']\n# df_phase = pd.DataFrame(columns = ['phase'])\n# for i in range(0,N):\n# df_phase.loc[-1] = [phase]\n# df_phase.index = df_phase.index + 1 # shifting index\n# df_phase = df_phase.sort_index()\n#\n# # df_theta = pd.DataFrame(columns=['theta'])\n# # for i in range(0, N):\n# # df_theta.loc[-1] = [theta]\n# # df_theta.index = df_theta.index + 1 # shifting index\n# # df_theta = df_theta.sort_index()\n#\n# df_low = pd.DataFrame(columns=['low'])\n# for i in range(0, N):\n# df_low.loc[-1] = [low]\n# df_low.index = df_low.index + 1 # shifting index\n# df_low = df_low.sort_index()\n#\n# df_high = pd.DataFrame(columns=['high'])\n# for i in range(0, N):\n# df_high.loc[-1] = [high]\n# df_high.index = df_high.index + 1 # shifting index\n# df_high = df_high.sort_index()\n#\n# # df_temp = pd.concat([df_low, df_high, df_theta, df_phase, df_squared_difference], axis=1)\n# df_temp = pd.concat([df_low, df_high, df_phase, df_squared_difference], axis=1)\n# df = pd.concat([df,df_temp], axis=0)\n#\n# for low in low_set:\n# for high in high_set:\n# # print(datetime.now().strftime('%Y-%m-%d %H:%M:%S') + \": \" + \"Printing figure for low = \" + str(\n# # low) + \", high = \" + str(high) + \", phase = \" + str(phase) + \" and theta = \" + str(theta) + \".\")\n# print(datetime.now().strftime('%Y-%m-%d %H:%M:%S') + \": \" + \"Printing figure for low = \" + str(\n# low) + \", high = \" + str(high) + \", phase = \" + str(phase) + \".\")\n# # df_temp = sqldf(\"select * from df where low=\" + str(low) + \" and high=\" + str(high) + \" and phase=\" + str(phase) + \" and theta<1.5\")\n# df_temp = sqldf(\"select * from df where low=\" + str(low) + \" and high=\" + str(high))\n# figures_path = config.root_path + \"figures/\"\n# figure_name = \"low_\" + str(low) + \"_high_\" + str(high)\n# figure_title = \"low_\" + str(low) + \"_high_\" + str(high)\n# x_variable = 'phase'\n# y_variable = 'squared_difference'\n# x_label = 'phase'\n# y_label = 'squared_difference'\n# x_variable_label = 'phase'\n# y_variable_label = 'squared_difference'\n# plotting_functions.box_plot(df_temp, figures_path, figure_name, figure_title, x_variable, x_variable_label, x_label, y_variable, y_label)\n\n########################################################################################################################\n# SELECTING THE PROPER VALUE OF y\n########################################################################################################################\ncolumns = ['low','high','sigma','simulation','phase', 'party_ID', 'squared_difference', 'difference']\n# sigma_set = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]\n# low_set = [0.7, 0.9]\n# high_set = [1.1, 1.3]\nsigma_set = [0.5]\nlow_set = [0.7]\nhigh_set = [1.3]\ndf = pd.DataFrame(columns=columns)\ndf_temp_temp = pd.DataFrame(columns=columns)\nN = 100 #Number of phases\nlast_df_index = 0\n\nsigma = 0.5\nlow = 0.7\nhigh = 1.3\nphase = 0\nsimulation = 0\nrelevant_parties = [2, 3, 5, 8, 10 ,11, 14, 16, 17, 18, 21]\nfor sigma in sigma_set:\n for low in low_set:\n for high in high_set:\n for simulation in range(1,150):\n print(datetime.now().strftime('%Y-%m-%d %H:%M:%S') + \": \" + \"Wrangling data for sigma = \" + str(sigma) + \", low = \" + str(low) + \", high = \" + str(high) + \", simulation = \" + str(simulation) + \".\")\n df_temp = pd.read_csv(config.data_path + \"simulation_y/y\" + \"_sigma_\" + str(sigma) + \"_low_\" + str(low) + \"_high_\" + str(high) + \"_simulation_\" + str(simulation) +\".csv\")\n K = df_temp.shape[1]\n for phase in range(0, N):\n for party_ID in relevant_parties:\n # squared_difference = ((df_temp.iloc[phase,:] - df_temp.iloc[N-1,:])/df_temp.iloc[N-1,:])**2\n squared_difference = ((df_temp.iloc[phase, party_ID] - df_temp.iloc[N - 1, party_ID]) / df_temp.iloc[N - 1,party_ID]) ** 2\n difference = ((df_temp.iloc[phase, party_ID] - df_temp.iloc[N - 1, party_ID]) / df_temp.iloc[N - 1, party_ID])\n # mean_squared_difference = np.max(squared_difference.iloc[relevant_parties])\n a_row = pd.Series([low, high, sigma, simulation, phase, party_ID, squared_difference, difference])\n row_df = pd.DataFrame([a_row])\n row_df.columns = columns\n df = pd.concat([df, row_df])\n\n\ndf.loc[df['squared_difference'].isna(), 'squared_difference'] = 0\ndf_backup = copy.deepcopy(df)\ndf = copy.deepcopy(df_backup)\n\ndf_quantile = pd.DataFrame(columns= ['low','high','sigma','phase','difference_lower_quantile','difference_upper_quantile', 'mu', 'sigma_squared'])\nfor sigma in sigma_set:\n for low in low_set:\n for high in high_set:\n for phase in range(0,N):\n df_temp = df[(df[\"low\"]==low) & (df[\"high\"]==high) & (df[\"sigma\"]==sigma) & (df[\"phase\"]==phase)]\n a_row = pd.Series([low, high, sigma, phase, df_temp.difference.quantile(0.05), df_temp.difference.quantile(0.95), df_temp.difference.mean(), df_temp.difference.var()])\n row_df = pd.DataFrame([a_row])\n row_df.columns = ['low','high','sigma','phase','difference_lower_quantile','difference_upper_quantile', 'mu', 'sigma_squared']\n df_quantile = pd.concat([df_quantile, row_df])\n\n\n#Only select Sas, sme rodina, za ludi, sns, olano, ps_spolu atd.\n# df = sqldf(\"select * from df where party_ID in (3,4,6,9,11,12,15,17,18,19,22)\")\n\n# party_ID = 3\nfor low in low_set:\n for high in high_set:\n for phase in range(0, N):\n df_temp = sqldf(\"select * from df where phase=\" + str(phase) + \" and low=\" + str(low) + \" and high=\" + str(high))\n df_temp2 = sqldf(\"select * from df_quantile where phase=\" + str(phase) + \" and low=\" + str(low) + \" and high=\" + str(high))\n figures_path = config.root_path + \"figures/\"\n figure_name = \"low_\" + str(low) + \"_high_\" + str(high) + \"_phase_\" + str(phase)\n figure_title = \"low_\" + str(low) + \"_high_\" + str(high) + \"_phase_\" + str(phase)\n x_variable = 'difference'\n # y_variable = ''\n x_label = 'difference'\n # y_label = 'squared_difference'\n x_variable_label = 'difference'\n # y_variable_label = 'squared_difference'\n plotting_functions.hist_plot(df_temp, figures_path, figure_name, figure_title, x_variable, x_variable_label, x_label, float(df_temp2[\"mu\"]) , float(df_temp2[\"sigma_squared\"]))\n\n","repo_name":"JuroHledik/Elections","sub_path":"code/python/model_selection.py","file_name":"model_selection.py","file_ext":"py","file_size_in_byte":9895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"33609630383","text":"import os\nfrom .process_object import Process\nfrom actinia_core.core.geodata_download_importer import (\n GeoDataDownloadImportSupport,\n)\n\n__license__ = \"GPLv3\"\n__author__ = \"Sören Gebbert\"\n__copyright__ = (\n \"Copyright 2016-2018, Sören Gebbert and mundialis GmbH & Co. KG\"\n)\n__maintainer__ = \"Sören Gebbert\"\n__email__ = \"soerengebbert@googlemail.com\"\n\nSUPPORTED_MIMETYPES = [\n \"application/zip\",\n \"application/tiff\",\n \"application/gml\",\n]\n\nSCENE_SUFFIXES = {\n \"LT04\": [\n \"_B1.TIF\",\n \"_B2.TIF\",\n \"_B3.TIF\",\n \"_B4.TIF\",\n \"_B5.TIF\",\n \"_B6.TIF\",\n \"_B7.TIF\",\n \"_MTL.txt\",\n ],\n \"LT05\": [\n \"_B1.TIF\",\n \"_B2.TIF\",\n \"_B3.TIF\",\n \"_B4.TIF\",\n \"_B5.TIF\",\n \"_B6.TIF\",\n \"_B7.TIF\",\n \"_MTL.txt\",\n ],\n \"LE07\": [\n \"_B1.TIF\",\n \"_B2.TIF\",\n \"_B3.TIF\",\n \"_B4.TIF\",\n \"_B5.TIF\",\n \"_B6_VCID_2.TIF\",\n \"_B6_VCID_1.TIF\",\n \"_B7.TIF\",\n \"_B8.TIF\",\n \"_MTL.txt\",\n ],\n \"LC08\": [\n \"_B1.TIF\",\n \"_B2.TIF\",\n \"_B3.TIF\",\n \"_B4.TIF\",\n \"_B5.TIF\",\n \"_B6.TIF\",\n \"_B7.TIF\",\n \"_B8.TIF\",\n \"_B9.TIF\",\n \"_B10.TIF\",\n \"_B11.TIF\",\n \"_MTL.txt\",\n ],\n}\n\nRASTER_SUFFIXES = {\n \"LT04\": [\".1\", \".2\", \".3\", \".4\", \".5\", \".6\", \".7\"],\n \"LT05\": [\".1\", \".2\", \".3\", \".4\", \".5\", \".6\", \".7\"],\n \"LE07\": [\".1\", \".2\", \".3\", \".4\", \".5\", \".61\", \".62\", \".7\", \".8\"],\n \"LC08\": [\n \".1\",\n \".2\",\n \".3\",\n \".4\",\n \".5\",\n \".6\",\n \".7\",\n \".8\",\n \".9\",\n \".10\",\n \".11\",\n ],\n}\n\n\nSCENE_BANDS = {\n \"LT04\": [\"B1\", \"B2\", \"B3\", \"B4\", \"B5\", \"B6\", \"B7\", \"MTL\"],\n \"LT05\": [\"B1\", \"B2\", \"B3\", \"B4\", \"B5\", \"B6\", \"B7\", \"MTL\"],\n \"LE07\": [\n \"B1\",\n \"B2\",\n \"B3\",\n \"B4\",\n \"B5\",\n \"B6_VCID_2\",\n \"B6_VCID_1\",\n \"B7\",\n \"B8\",\n \"MTL\",\n ],\n \"LC08\": [\n \"B1\",\n \"B2\",\n \"B3\",\n \"B4\",\n \"B5\",\n \"B6\",\n \"B7\",\n \"B8\",\n \"B9\",\n \"B10\",\n \"B11\",\n \"MTL\",\n ],\n}\n\n\ndef extract_sensor_id_from_scene_id(scene_id):\n \"\"\"Extract the sensor id from a Landsat scene id\n\n Args:\n scene_id (str): The landsat scene id\n\n Returns:\n (str)\n The sencor id\n\n \"\"\"\n return scene_id.split(\"_\")[0]\n\n\ndef scene_id_to_google_url(scene_id, suffix):\n \"\"\"Convert a landsat scene id into the public google download URL for the\n required file\n\n Args:\n scene_id (str): The Landsat scene id\n suffix (str): The suffix of the file to create the url for, i.e.:\n \"_B1.TIF\" or \"_MTL.txt\"\n Returns:\n (str)\n The URL to the scene file\n \"\"\"\n # new URL example\n # https://storage.googleapis.com/gcp-public-data-landsat/LC08/01/001/004/\n # LC08_L1GT_001004_20130910_20170502_01_T2/\n # LC08_L1GT_001004_20130910_20170502_01_T2_B1.TIF\n\n # Create the download URL components from the Landsat scene id\n landsat_sensor_id = extract_sensor_id_from_scene_id(scene_id)\n path = scene_id.split(\"_\")[2][:3]\n row = scene_id.split(\"_\")[2][3:]\n\n url = (\n \"https://storage.googleapis.com/gcp-public-data-landsat/\"\n f\"{landsat_sensor_id}/01/{path}/{row}/{scene_id}/{scene_id}{suffix}\"\n )\n return url\n\n\ndef datetime_to_grass_datetime_string(dt):\n \"\"\"Convert a python datetime object into a GRASS datetime string\"\"\"\n # GRASS datetime month names\n month_names = [\n \"\",\n \"jan\",\n \"feb\",\n \"mar\",\n \"apr\",\n \"may\",\n \"jun\",\n \"jul\",\n \"aug\",\n \"sep\",\n \"oct\",\n \"nov\",\n \"dec\",\n ]\n\n # Check for time zone info in the datetime object\n if dt.tzinfo is not None:\n tz = dt.tzinfo.utcoffset(0)\n if tz.seconds > 86400 / 2:\n tz = (tz.seconds - 86400) / 60\n else:\n tz = tz.seconds / 60\n\n string = \"%.2i %s %.2i %.2i:%.2i:%.2i %+.4i\" % (\n dt.day,\n month_names[dt.month],\n dt.year,\n dt.hour,\n dt.minute,\n dt.second,\n tz,\n )\n else:\n string = \"%.2i %s %.4i %.2i:%.2i:%.2i\" % (\n dt.day,\n month_names[dt.month],\n dt.year,\n dt.hour,\n dt.minute,\n dt.second,\n )\n\n return string\n\n\nclass LandsatProcessing(GeoDataDownloadImportSupport):\n \"\"\"\"\"\"\n\n def __init__(\n self,\n config,\n scene_id,\n temp_file_path,\n download_cache,\n send_resource_update,\n message_logger,\n ):\n \"\"\"A collection of functions to generate Landsat4-8 scene related\n import and processing commands. Each function returns a process chain\n that can be executed by the async processing classes.\n\n Args:\n config: The Actinia Core configuration object\n scene_id (str): The scene id for which all bands should be\n downloaded\n temp_file_path: The path to the temporary directory to store\n temporary files. It is assumed that this path is\n available when the generated commands are executed.\n download_cache (str): The path to the download cache\n send_resource_update: The function to call for resource updates\n message_logger: The message logger to be used\n\n \"\"\"\n\n GeoDataDownloadImportSupport.__init__(\n self,\n config,\n temp_file_path,\n download_cache,\n send_resource_update,\n message_logger,\n None,\n )\n\n self.scene_id = scene_id\n self.landsat_sensor_id = None\n self.url_list = []\n self.raster_names = []\n self.band_raster_names = {}\n self.ndvi_name = None\n\n def _setup(self):\n \"\"\"\n Setup the download of the required Landsat scene from the Google Cloud\n Storage.\n\n Check the download cache if the file already exists, to avoid redundant\n downloads. The downloaded files will be stored in a temporary\n directory. After the download of all files completes, the downloaded\n files will be moved to the download cache. This avoids broken files in\n case a download was interrupted or stopped by termination.\n\n This method uses wget to gather the landsat scenes from the Google\n Cloud Storage landsat archive using public https address.\n \"\"\"\n\n GeoDataDownloadImportSupport._setup(self)\n self.landsat_sensor_id = extract_sensor_id_from_scene_id(self.scene_id)\n\n count = 0\n # Create file names, urls and check the download cache\n for suffix in SCENE_SUFFIXES[self.landsat_sensor_id]:\n file_name = \"%s%s\" % (self.scene_id, suffix)\n # This is the file path in the download cache directory\n file_path = os.path.join(self.user_download_cache_path, file_name)\n self.file_list.append(file_path)\n # This is the download path\n temp_file_path = os.path.join(self.temp_file_path, file_name)\n # Create the download URL\n url = scene_id_to_google_url(self.scene_id, suffix)\n\n self.url_list.append(url)\n self.copy_file_list.append((temp_file_path, file_path))\n count += 1\n\n def get_import_process_list(self):\n count = 0\n import_commands = []\n\n for file_path in self.file_list:\n if \"_MTL.TXT\" not in file_path.upper():\n raster_name = \"%s%s\" % (\n self.scene_id,\n RASTER_SUFFIXES[self.landsat_sensor_id][count],\n )\n self.raster_names.append(raster_name)\n self.band_raster_names[\n SCENE_BANDS[self.landsat_sensor_id][count]\n ] = raster_name\n p = self.get_raster_import_command(\n file_path=file_path, raster_name=raster_name\n )\n import_commands.append(p)\n count += 1\n\n return import_commands\n\n def get_i_landsat_toar_process_list(self, atcor_method):\n option = \"uncorrected\"\n\n if atcor_method == \"DOS4\":\n option = \"dos4\"\n\n if atcor_method == \"DOS1\":\n option = \"dos1\"\n\n toar_commands = []\n\n p = Process(\n exec_type=\"grass\",\n executable=\"i.landsat.toar\",\n executable_params=[\n \"input=%s.\" % self.scene_id,\n \"metfile=%s_%s\"\n % (\n os.path.join(self.user_download_cache_path, self.scene_id),\n \"MTL.txt\",\n ),\n \"method=%s\" % option,\n \"output=%s_%s.\" % (self.scene_id, atcor_method),\n \"--q\",\n ],\n id=f\"top_of_atmosphere_{self.scene_id}\",\n skip_permission_check=True,\n )\n toar_commands.append(p)\n return toar_commands\n\n def get_i_vi_process_list(self, atcor_method, processing_method):\n self.ndvi_name = \"%s_%s_%s\" % (\n self.scene_id,\n atcor_method,\n processing_method,\n )\n\n ndvi_commands = []\n\n ivi = \"i.vi\"\n ivi_params = list()\n if self.landsat_sensor_id == \"LC08\":\n ivi_params.append(\n \"red=%s_%s%s\" % (self.scene_id, atcor_method, \".4\")\n )\n ivi_params.append(\n \"nir=%s_%s%s\" % (self.scene_id, atcor_method, \".5\")\n )\n ivi_params.append(\n \"green=%s_%s%s\" % (self.scene_id, atcor_method, \".3\")\n )\n ivi_params.append(\n \"blue=%s_%s%s\" % (self.scene_id, atcor_method, \".2\")\n )\n ivi_params.append(\n \"band5=%s_%s%s\" % (self.scene_id, atcor_method, \".7\")\n )\n ivi_params.append(\n \"band7=%s_%s%s\" % (self.scene_id, atcor_method, \".8\")\n )\n else:\n ivi_params.append(\n \"red=%s_%s%s\" % (self.scene_id, atcor_method, \".3\")\n )\n ivi_params.append(\n \"nir=%s_%s%s\" % (self.scene_id, atcor_method, \".4\")\n )\n ivi_params.append(\n \"green=%s_%s%s\" % (self.scene_id, atcor_method, \".2\")\n )\n ivi_params.append(\n \"blue=%s_%s%s\" % (self.scene_id, atcor_method, \".1\")\n )\n ivi_params.append(\n \"band5=%s_%s%s\" % (self.scene_id, atcor_method, \".5\")\n )\n ivi_params.append(\n \"band7=%s_%s%s\" % (self.scene_id, atcor_method, \".7\")\n )\n\n ivi_params.append(\"viname=%s\" % processing_method.lower())\n ivi_params.append(\"output=%s\" % self.ndvi_name)\n\n p = Process(\n exec_type=\"grass\",\n executable=ivi,\n executable_params=ivi_params,\n id=f\"i_vi_{processing_method.lower()}_{self.ndvi_name}\",\n skip_permission_check=True,\n )\n ndvi_commands.append(p)\n\n p = Process(\n exec_type=\"grass\",\n executable=\"r.colors\",\n executable_params=[\"map=%s\" % self.ndvi_name, \"color=ndvi\"],\n id=f\"set_colors_{processing_method.lower()}_{self.ndvi_name}\",\n skip_permission_check=True,\n )\n ndvi_commands.append(p)\n\n return ndvi_commands\n","repo_name":"actinia-org/actinia-core","sub_path":"src/actinia_core/core/common/landsat_processing_library.py","file_name":"landsat_processing_library.py","file_ext":"py","file_size_in_byte":11677,"program_lang":"python","lang":"en","doc_type":"code","stars":70,"dataset":"github-code","pt":"41"} +{"seq_id":"71230102843","text":"import pymongo\nimport pprint\n\nclient = pymongo.MongoClient(\"mongodb://localhost:60000/\")\n\n# mydb = myclient[\"mydatabase\"]\n# mycol = mydb[\"customers\"]\n# mydict = { \"name\": \"John\", \"address\": \"Highway 37\" }\n# x = mycol.insert_one(mydict)\n\ndb = client[\"database\"]\ncollection = db[\"authors\"]\n\nposts = db.posts\npost = {\"author\": \"Ananmay\", \"text\": \"My First Database!\"}\n\nresult = collection.insert_one(post)\n\nprint(result.inserted_id)\n","repo_name":"ananmayjain/rideshare","sub_path":"databases/mongodb_server.py","file_name":"mongodb_server.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"38907854297","text":"class ItemToPurchase:\n \n def __init__(self):\n \n self.item_name=None\n self.item_price=0.0\n self.item_quantity=0\n \n \n def print_item_cost(self):\n print(self.item_name+\" \"+str(self.item_quantity)+' @ $'+str(self.item_price)+' = $'+str(self.item_price*self.item_quantity))\n return self.item_price*self.item_quantity\n \n \nif __name__ == \"__main__\":\n \n \n item1=ItemToPurchase()\n item2=ItemToPurchase()\n \n\n item1.item_name=input('Item 1\\nEnter the item name:\\n')\n item1.item_price=int(input('Enter the item price:\\n'))\n item1.item_quantity=int(input('Enter the item quantity:\\n'))\n \n\n \n item2.item_name=input('\\nItem 2\\nEnter the item name:\\n')\n item2.item_price=int(input('Enter the item price:\\n'))\n item2.item_quantity=int(input('Enter the item quantity:\\n'))\n \n \n print('\\nTOTAL COST')\n value1=item1.print_item_cost()\n value2=item2.print_item_cost()\n print('\\nTotal: $'+str(value1+value2))\n","repo_name":"wombywill/Coding-partner-assignments","sub_path":"9 10 soenglun.py","file_name":"9 10 soenglun.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"39835288289","text":"### analysis.py\n'''\nauthor: Nathan Branson\ndescription: contains functions for plotting shooting locations and \n shooting percentages.\n\nDATA: (see Documentation.pdf for full descriptions)\n shot_num: int\n shooter: int\n goalie_hand: R=0;L=1\n Hand: R=0;L=1\n type_shot_0: OH=0;SA=1;UH=2;BH=3;BTB=4;twister=5\n type_shot_1: Stationary=0;OtR=1;QS=2\n loc_x: [-20,20]\n loc_y: [0,20]\n dist: float\n loc_goal: [0,29] (subject to change)\n result: goal=0;save=1;miss=2;pipe=3;blocked=4\n screened: Y=0;N=1;N/A=2\n HUDL Timestamp: float\n Notes: string\n'''\n\nfrom cmath import sqrt\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport datetime\nimport pathlib\nfrom visualization import *\n\n\ndef shot_percentage(data, show=True, hand=\"both\"):\n\n #shot_data = data['result']\n goals = 0\n shots = 0\n sog = 0\n shot_per = 0\n for i in data:\n if i == 0:\n goals += 1\n if i == 0 or i == 1:\n sog += 1\n shots += 1\n\n shot_per = (goals/shots) * 100\n sog_per = (sog/shots) * 100\n\n if show:\n print(\"goal per: \", goals, \"/\", shots)\n print(round(shot_per, 2), \"%\")\n print()\n print(\"shots on goal per: \", sog, \"/\", shots)\n print(round(sog_per, 2), \"%\")\n \n return goals, shot_per, sog, sog_per, shots\n\ndef plot_shot_locs(data, shot_hand='B', max_dist=100, min_dist=-20, player = -1, game = \"\", extra = False, date = \"\", pic_dir = \"\"):\n # hand: Both-B ; Right-R ; Left-L\n\n field = make_field(size = \"half\", extra = True)\n fig = field[0]\n ax = field[1]\n\n data_loc_x = data['loc_x']\n data_loc_y = data['loc_y']\n shooters = data['shooter']\n data_dist = data['dist']\n hand_arr = data['shot_hand']\n result = data['result']#.tolist()\n loc_goal = data['loc_goal']\n hand = data['shot_hand']\n type_shot_0 = data['type_shot_0']\n type_shot_1 = data['type_shot_1']\n\n # colors for goal, save, miss, block, pipe\n make = 'green'\n miss = 'purple'\n save = 'red'\n block = 'blue'\n pipe = 'orange'\n \n loc_xs, loc_ys, new_result, new_loc_goal, new_hand = [], [], [], [], []\n new_type_shot_0, new_type_shot_1 = [], []\n\n if player < 0:\n loc_xs = data_loc_x\n loc_ys = data_loc_y\n new_result = result\n new_loc_goal = loc_goal\n new_hand = hand\n\n else: \n for i in range(len(shooters)):\n if shooters[i] == player:\n loc_xs.append(data_loc_x[i])\n loc_ys.append(data_loc_y[i])\n new_result.append(result[i])\n new_hand.append(hand[i])\n if loc_goal[i]>-1:\n new_loc_goal.append(int(loc_goal[i]))\n else:\n new_loc_goal.append('N')\n if(type_shot_0[i]>-1):\n new_type_shot_0.append(int(type_shot_0[i]))\n new_type_shot_1.append(int(type_shot_1[i]))\n else:\n new_type_shot_0.append('N')\n new_type_shot_1.append('N')\n\n goals, shot_per, sog, sog_per, shots = shot_percentage(new_result, show = False)\n \n loc_x, loc_y, new_new_result, new_new_hand = [], [], [], []\n\n for i in new_hand:\n if i == 0:\n new_new_hand.append('R')\n elif i == 1:\n new_new_hand.append('L')\n else:\n new_new_hand.append('N')\n\n if shot_hand == 'R':\n for i in range(len(data_loc_x)):\n if hand_arr[i,1] == 0:\n loc_x.append(loc_xs[i])\n loc_y.append(loc_ys[i])\n new_new_result.append(new_result[i])\n elif shot_hand == 'L':\n for i in range(len(data_loc_x)):\n if hand_arr[i] == 1:\n loc_x.append(loc_xs[i])\n loc_y.append(loc_ys[i])\n new_new_result.append(new_result[i])\n else:\n loc_x = loc_xs\n loc_y = loc_ys\n new_new_result = new_result\n \n loc_x_ma, loc_y_ma = [], [] # make\n loc_x_mi, loc_y_mi = [], [] # miss\n loc_x_sa, loc_y_sa = [], [] # save\n loc_x_pi, loc_y_pi = [], [] # pipe\n loc_x_bl, loc_y_bl = [], [] # block\n\n for i in range(len(new_new_result)):\n if new_new_result[i]==0:\n loc_x_ma.append(loc_x[i])\n loc_y_ma.append(loc_y[i])\n elif new_new_result[i] == 1:\n loc_x_sa.append(loc_x[i])\n loc_y_sa.append(loc_y[i])\n elif new_new_result[i] == 2:\n loc_x_mi.append(loc_x[i])\n loc_y_mi.append(loc_y[i])\n elif new_new_result[i] == 3:\n loc_x_pi.append(loc_x[i])\n loc_y_pi.append(loc_y[i])\n else:\n loc_x_bl.append(loc_x[i])\n loc_y_bl.append(loc_y[i])\n\n dist_arr = []\n\n j = 0\n for i in range(len(loc_x)):\n dist = sqrt((loc_x[i]**2)+(loc_y[i])**2).real\n dist_arr.append(round(dist, 2))\n '''if dist >= min_dist and dist <= max_dist:\n loc_x[j] = loc_x[i]\n loc_y[j] = loc_y[i]\n j += 1'''\n avg_dist = round(sum(dist_arr)/len(dist_arr),2)\n\n ax.scatter(loc_x_ma, loc_y_ma, color=make, alpha=.5, edgecolors=\"black\", s=60, label='goal' )\n ax.scatter(loc_x_sa, loc_y_sa, color=save, alpha=.5, edgecolors=\"black\", s=60, label='save' )\n ax.scatter(loc_x_mi, loc_y_mi, color=miss, alpha=.5, edgecolors=\"black\", s=60, label='miss' )\n ax.scatter(loc_x_bl, loc_y_bl, color=block, alpha=.5, edgecolors=\"black\", s=60, label='block')\n ax.scatter(loc_x_pi, loc_y_pi, color=pipe, alpha=.5, edgecolors=\"black\", s=60, label='pipe' )\n\n\n # text box showing shooting percentages and average distance\n props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\n textstr = '\\n'.join((r'goals: $\\frac{%d}{%d}=%.2f$' % (goals,shots,round(shot_per, 2), ), r'shots on goal: $\\frac{%d}{%d}=%.2f$' % (sog,shots,round(sog_per, 2), )\n , r'avg distance shot: $%.2f$' % (round(avg_dist, 2), )))\n props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\n ax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=14, verticalalignment='top', bbox=props)\n ax.legend(loc = [0.88, 0.8155])\n\n # title of chart\n if game == \"\":\n if player>-1:\n plt.title(r'Shot Chart for #%d' % player)\n text = (pic_dir + r'/Shot_%d.png' % player)\n plt.savefig(text)\n else:\n plt.title(\"Shot Chart Team\")\n plt.savefig(pic_dir + '/Shot_team.png')\n else:\n if player>-1:\n text = '\\n'.join([r'Shot Chart for #%d' % player, game])\n plt.title(text)\n text = pic_dir + r'/' + game + '/' + date + r'_Shot_' + game + r'_%d.png' % player\n \n else:\n text = '\\n'.join([r'Shot Chart for Team', game])\n plt.title(text)\n text = pic_dir + '/' + game + '/' + date + '_Shot_'+game+'_team.png'\n print(text)\n plt.savefig(text)\n\n\n if extra:\n for i, txt in enumerate(new_loc_goal):\n ax.annotate(txt, (loc_x[i]+.1, loc_y[i]+.1))\n for i, txt in enumerate(new_new_hand):\n ax.annotate(txt, (loc_x[i]+.85, loc_y[i]+.1))\n for i, txt in enumerate(new_type_shot_0):\n ax.annotate(txt, (loc_x[i]+1.35, loc_y[i]+.1))\n for i, txt in enumerate(new_type_shot_1):\n ax.annotate(txt, (loc_x[i]+1.85, loc_y[i]+.1))\n for i, txt in enumerate(dist_arr):\n ax.annotate(txt, (loc_x[i]+2.3, loc_y[i]+.1))\n im = plt.imread('images/goal.png') # insert local path of the image.\n newax = fig.add_axes([0.8,0.8,0.2,0.2], anchor='NE', zorder=1)\n newax.imshow(im)\n newax.axis('off') \n\n print(text)\n plt.savefig(text)\n\n\ndef plot_goal_locs(data):#, fig):\n goal = make_goal()\n #ax = fig[1]\n # x, y\n\n spots = []\n xv, yv = 0, 1.5\n for i in range(4):\n xh,yh = 0, 1.5\n for j in range(4):\n spots.append([[xv,yv],[xh,yh]]) \n xh = xh +1.5\n yh = yh + 1.5\n xv = xv +1.5\n yv = yv + 1.5\n\n for i in range(len(spots)):\n rect = mpl.patches.Rectangle((spots[i][0][0],\n spots[i][1][0]),1.5,1.5,edgecolor = 'black', color = None,\n linewidth = 2, facecolor = 'red')\n plt.gca().add_patch(rect)\n\n\n plt.show()\n","repo_name":"nate-branson/Lacrosse-Data-Analytics","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":8572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"12215341973","text":"# -*- coding: utf-8 -*-\n\"\"\"\n# Support Vector Classification\n\"\"\"\n\nimport warnings\nimport seaborn as se\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.svm import SVC\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.model_selection import train_test_split\nfrom imblearn.over_sampling import RandomOverSampler\nfrom sklearn.preprocessing import LabelEncoder,StandardScaler\nfrom sklearn.metrics import classification_report,plot_confusion_matrix\nwarnings.filterwarnings('ignore')\n\n\"\"\"### Importing dataset\n\nPandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools.\n\nWe will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry.\n\"\"\"\n\n#df=pd.read_csv(file_path)\n#df.head()\nimport pandas as pd\nimport io\nfrom google.colab import files\n\nuploaded = files.upload()\nimport io\n\ndf = pd.read_csv(io.BytesIO(uploaded['heart.csv']))\n\n\"\"\"### Feature Selections\n\nIt is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model.\n\nWe will assign all the required input features to X and target/outcome to Y.\n\"\"\"\n\nX = df[['Age','Sex','ChestPainType','RestingBP','Cholesterol','FastingBS','RestingECG','MaxHR','ExerciseAngina','Oldpeak','ST_Slope']]\nY = df['HeartDisease']\n\n\"\"\"### Data Preprocessing\n\nSince the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the datasets by encoding them to integer classes.\n\n\"\"\"\n\ndef NullClearner(df):\n if(isinstance(df, pd.Series) and (df.dtype in [\"float64\",\"int64\"])):\n df.fillna(df.mean(),inplace=True)\n return df\n elif(isinstance(df, pd.Series)):\n df.fillna(df.mode()[0],inplace=True)\n return df\n else:return df\ndef EncodeX(df):\n return pd.get_dummies(df)\ndef EncodeY(df):\n if len(df.unique())<=2:\n return df\n else:\n un_EncodedT=np.sort(pd.unique(df), axis=-1, kind='mergesort')\n df=LabelEncoder().fit_transform(df)\n EncodedT=[xi for xi in range(len(un_EncodedT))]\n print(\"Encoded Target: {} to {}\".format(un_EncodedT,EncodedT))\n return df\n\n\"\"\"Calling preprocessing functions on the feature and target set.\n\n\"\"\"\n\nx=X.columns.to_list()\nfor i in x:\n X[i]=NullClearner(X[i])\nX=EncodeX(X)\nY=EncodeY(NullClearner(Y))\nX.head()\n\n\"\"\"#### Correlation Map\n\nIn order to check the correlation between the features, we will plot a correlation matrix. It is effective in summarizing a large amount of data where the goal is to see patterns.\n\"\"\"\n\nf,ax = plt.subplots(figsize=(18, 18))\nmatrix = np.triu(X.corr())\nse.heatmap(X.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax, mask=matrix)\nplt.show()\n\n\"\"\"#### Distribution Of Target Variable\"\"\"\n\nplt.figure(figsize = (10,6))\nse.countplot(Y)\n\n\"\"\"### Data Splitting\n\nThe train-test split is a procedure for evaluating the performance of an algorithm. The procedure involves taking a dataset and dividing it into two subsets. The first subset is utilized to fit/train the model. The second subset is used for prediction. The main motive is to estimate the performance of the model on new data.\n\"\"\"\n\nx_train,x_test,y_train,y_test=train_test_split(X,Y,test_size=0.2,random_state=123)\n\n\"\"\"#### Handling Target Imbalance\n\nThe challenge of working with imbalanced datasets is that most machine learning techniques will ignore, and in turn have poor performance on, the minority class, although typically it is performance on the minority class that is most important.\n\nOne approach to addressing imbalanced datasets is to oversample the minority class. The simplest approach involves duplicating examples in the minority class.We will perform overspampling using imblearn library. \n\"\"\"\n\nx_train,y_train = RandomOverSampler(random_state=123).fit_resample(x_train, y_train)\n\n\"\"\"### Model\nSupport vector machines (SVMs) are a set of supervised learning methods used for classification, regression and outliers detection.\n\nA Support Vector Machine is a discriminative classifier formally defined by a separating hyperplane. In other terms, for a given known/labelled data points, the SVM outputs an appropriate hyperplane that classifies the inputted new cases based on the hyperplane. In 2-Dimensional space, this hyperplane is a line separating a plane into two segments where each class or group occupied on either side.\n\nHere we have used SVC, the svc implementation is based on libsvm. \n\n* #### Model Tuning Parameters\n > - C -> Regularization parameter. The strength of the regularization is inversely proportional to C. Must be strictly positive.\n\n > - kernel -> Specifies the kernel type to be used in the algorithm. It must be one of ‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’ or a callable. If none is given, ‘rbf’ will be used. If a callable is given it is used to pre-compute the kernel matrix from data matrices; that matrix should be an array of shape (n_samples, n_samples).\n\n > - gamma -> Gamma is a hyperparameter that we have to set before the training model. Gamma decides how much curvature we want in a decision boundary.\n\n > - degree -> Degree of the polynomial kernel function (‘poly’). Ignored by all other kernels.Using degree 1 is similar to using a linear kernel. Also, increasing degree parameter leads to higher training times.\n\"\"\"\n\nmodel=make_pipeline(StandardScaler(),SVC(random_state=123))\nmodel.fit(x_train,y_train)\n\n\"\"\"#### Model Accuracy\n\n\nscore() method return the mean accuracy on the given test data and labels.\n\nIn multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.\n\"\"\"\n\nprint(\"Accuracy score {:.2f} %\\n\".format(model.score(x_test,y_test)*100))\n\n\"\"\"#### Confusion matrix\n\nA confusion matrix is utilized to understand the performance of the classification model or algorithm in machine learning for a given test set where results are known.\n\"\"\"\n\nplot_confusion_matrix(model,x_test,y_test,cmap=plt.cm.Blues)\n\n\"\"\"\n#### Classification Report\n\nA Classification report is used to measure the quality of predictions from a classification algorithm. How many predictions are True, how many are False.\n\n* where:\n - Precision:- Accuracy of positive predictions.\n - Recall:- Fraction of positives that were correctly identified.\n - f1-score:- percent of positive predictions were correct\n - support:- Support is the number of actual occurrences of the class in the specified dataset.\"\"\"\n\nprint(classification_report(y_test,model.predict(x_test)))\n","repo_name":"KatariaPawan/Classification_Predicting_Heart_Disease","sub_path":"support_vector_classifier.py","file_name":"support_vector_classifier.py","file_ext":"py","file_size_in_byte":6992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"39524835292","text":"f = open(\"data.txt\")\n\nl = []\ncount = 0\n\nfor lines in f:\n line = lines.split()\n pairs = line[0].split(\",\")\n pair1 = pairs[0].split(\"-\")\n pair2 = pairs[1].split(\"-\")\n num1 = [eval(i) for i in pair1]\n num2 = [eval(i) for i in pair2]\n \n # TASK ONE\n if num1[0] == num2[0] and num1[1] == num2[1]:\n count += 1\n continue\n if num2[1] >= num1[1] and num2[0] <= num1[0]:\n count += 1\n if num1[1] >= num2[1] and num1[0] <= num2[0]:\n count += 1\n \n # TASK TWO\n # if num1[0] >= num2[0] and num1[0] <= num2[1]:\n # count += 1\n # continue\n # if num2[0] >= num1[0] and num2[0] <= num1[1]:\n # count += 1\n\nprint(count)","repo_name":"stevetoddy/advent2022","sub_path":"day_4/advent_4.py","file_name":"advent_4.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"74447654202","text":"# Embedded file name: scripts/client/gui/Scaleform/daapi/view/lobby/profile/ProfileTechnique.py\nimport BigWorld\nfrom account_helpers import AccountSettings\nfrom account_helpers.AccountSettings import PROFILE_TECHNIQUE_MEMBER\nfrom dossiers2.ui.achievements import ACHIEVEMENT_BLOCK, MARK_ON_GUN_RECORD, HONORED_RANK_RECORD\nfrom gui import GUI_NATIONS_ORDER_INDEX\nfrom gui.Scaleform.daapi.settings.views import VIEW_ALIAS\nfrom gui.Scaleform.daapi.view.AchievementsUtils import AchievementsUtils\nfrom gui.Scaleform.daapi.view.lobby.hof.hof_helpers import getHofRatingUrlForVehicle, getHofDisabledKeys, onServerSettingsChange, isHofButtonNew, setHofButtonOld\nfrom gui.Scaleform.daapi.view.lobby.hof.web_handlers import createHofWebHandlers\nfrom gui.Scaleform.daapi.view.lobby.profile.ProfileUtils import ProfileUtils, DetailedStatisticsUtils, STATISTICS_LAYOUT, FORT_STATISTICS_LAYOUT, FALLOUT_STATISTICS_LAYOUT\nfrom gui.Scaleform.daapi.view.meta.ProfileTechniqueMeta import ProfileTechniqueMeta\nfrom gui.Scaleform.genConsts.ACHIEVEMENTS_ALIASES import ACHIEVEMENTS_ALIASES\nfrom gui.Scaleform.genConsts.PROFILE_CONSTANTS import PROFILE_CONSTANTS\nfrom gui.Scaleform.genConsts.PROFILE_DROPDOWN_KEYS import PROFILE_DROPDOWN_KEYS\nfrom gui.Scaleform.locale.PROFILE import PROFILE\nfrom gui.Scaleform.locale.RES_ICONS import RES_ICONS\nfrom gui.shared import g_eventBus, events, EVENT_BUS_SCOPE\nfrom gui.shared.gui_items.Vehicle import VEHICLE_TABLE_TYPES_ORDER_INDICES_REVERSED\nfrom gui.shared.gui_items.dossier import dumpDossier\nfrom gui.shared.gui_items.dossier.achievements.MarkOfMasteryAchievement import isMarkOfMasteryAchieved\nfrom gui.shared.gui_items.dossier.stats import UNAVAILABLE_MARKS_OF_MASTERY\nfrom helpers import i18n, dependency\nfrom nations import NAMES\nfrom skeletons.gui.game_control import IVehicleComparisonBasket\nfrom skeletons.gui.lobby_context import ILobbyContext\nfrom skeletons.gui.server_events import IEventsCache\n_MARK_ON_GUN_MIN_LVL = 5\n\nclass ProfileTechnique(ProfileTechniqueMeta):\n comparisonBasket = dependency.descriptor(IVehicleComparisonBasket)\n lobbyContext = dependency.descriptor(ILobbyContext)\n eventsCache = dependency.descriptor(IEventsCache)\n\n def __init__(self, *args):\n super(ProfileTechnique, self).__init__(*args)\n selectedData = self._selectedData\n self._selectedVehicleIntCD = selectedData.get('itemCD') if selectedData else None\n return\n\n def showVehiclesRating(self):\n setHofButtonOld(PROFILE_CONSTANTS.HOF_VIEW_RATING_BUTTON)\n self.eventsCache.onProfileVisited()\n g_eventBus.handleEvent(events.LoadViewEvent(VIEW_ALIAS.BROWSER_VIEW, ctx={'url': getHofRatingUrlForVehicle(self._selectedVehicleIntCD),\n 'returnAlias': VIEW_ALIAS.LOBBY_PROFILE,\n 'allowRightClick': True,\n 'webHandlers': createHofWebHandlers(),\n 'itemCD': self._selectedVehicleIntCD,\n 'disabledKeys': getHofDisabledKeys(),\n 'onServerSettingsChange': onServerSettingsChange}), EVENT_BUS_SCOPE.LOBBY)\n\n def _populate(self):\n super(ProfileTechnique, self)._populate()\n self._setRatingButton()\n self.lobbyContext.getServerSettings().onServerSettingsChange += self.__onServerSettingChanged\n\n def _dispose(self):\n self.lobbyContext.getServerSettings().onServerSettingsChange -= self.__onServerSettingChanged\n super(ProfileTechnique, self)._dispose()\n\n def _getInitData(self, accountDossier = None, isFallout = False):\n dropDownProvider = [self._dataProviderEntryAutoTranslate(PROFILE_DROPDOWN_KEYS.ALL), self._dataProviderEntryAutoTranslate(PROFILE_DROPDOWN_KEYS.EPIC_RANDOM), self._dataProviderEntryAutoTranslate(PROFILE_DROPDOWN_KEYS.RANKED)]\n self._dataProviderEntryAutoTranslate(PROFILE_DROPDOWN_KEYS.FALLOUT)\n if accountDossier is not None and accountDossier.getHistoricalStats().getVehicles():\n dropDownProvider.append(self._dataProviderEntryAutoTranslate(PROFILE_DROPDOWN_KEYS.HISTORICAL))\n dropDownProvider.append(self._dataProviderEntryAutoTranslate(PROFILE_DROPDOWN_KEYS.TEAM))\n if accountDossier is not None and accountDossier.getRated7x7Stats().getVehicles():\n dropDownProvider.append(self._dataProviderEntryAutoTranslate(PROFILE_DROPDOWN_KEYS.STATICTEAM))\n dropDownProvider.append(self._dataProviderEntryAutoTranslate(PROFILE_DROPDOWN_KEYS.CLAN))\n if self.lobbyContext.getServerSettings().isStrongholdsEnabled():\n dropDownProvider.extend((self._dataProviderEntryAutoTranslate(PROFILE_DROPDOWN_KEYS.FORTIFICATIONS_SORTIES), self._dataProviderEntryAutoTranslate(PROFILE_DROPDOWN_KEYS.FORTIFICATIONS_BATTLES)))\n storedData = self._getStorageData()\n return {'dropDownProvider': dropDownProvider,\n 'tableHeader': self._getTableHeader(isFallout),\n 'selectedColumn': storedData['selectedColumn'],\n 'selectedColumnSorting': storedData['selectedColumnSorting']}\n\n def _setRatingButton(self):\n if self._battlesType == PROFILE_DROPDOWN_KEYS.ALL and self.lobbyContext.getServerSettings().isHofEnabled():\n self.as_setRatingButtonS({'enabled': True,\n 'visible': True})\n if isHofButtonNew(PROFILE_CONSTANTS.HOF_VIEW_RATING_BUTTON):\n self.as_setBtnCountersS([{'componentId': PROFILE_CONSTANTS.HOF_VIEW_RATING_BUTTON,\n 'count': '1'}])\n else:\n self.as_setBtnCountersS([])\n else:\n self.as_setRatingButtonS({'enabled': False,\n 'visible': False})\n\n def setSelectedTableColumn(self, index, sortDirection):\n storedDataId = self._getStorageId()\n storedData = AccountSettings.getFilter(storedDataId)\n storedData['selectedColumn'] = index\n storedData['selectedColumnSorting'] = sortDirection\n AccountSettings.setFilter(storedDataId, storedData)\n\n def invokeUpdate(self):\n super(ProfileTechnique, self).invokeUpdate()\n self._setRatingButton()\n\n def _getStorageId(self):\n return PROFILE_TECHNIQUE_MEMBER\n\n def _getStorageData(self):\n return AccountSettings.getFilter(self._getStorageId())\n\n def _getTableHeader(self, isFallout = False):\n if self._battlesType == PROFILE_DROPDOWN_KEYS.ALL or self._battlesType == PROFILE_DROPDOWN_KEYS.EPIC_RANDOM or self._battlesType == PROFILE_DROPDOWN_KEYS.RANKED:\n markOfMasteryEnabled = True\n else:\n markOfMasteryEnabled = False\n return (self._createTableBtnInfo('nationIndex', 36, 0, PROFILE.SECTION_TECHNIQUE_SORT_TOOLTIP_NATION, 'ascending', iconSource=RES_ICONS.MAPS_ICONS_FILTERS_NATIONS_ALL, inverted=True),\n self._createTableBtnInfo('typeIndex', 34, 1, PROFILE.SECTION_TECHNIQUE_SORT_TOOLTIP_TECHNIQUE, 'descending', iconSource=RES_ICONS.MAPS_ICONS_FILTERS_TANKS_ALL),\n self._createTableBtnInfo('level', 32, 2, PROFILE.SECTION_TECHNIQUE_SORT_TOOLTIP_LVL, 'descending', iconSource=RES_ICONS.MAPS_ICONS_BUTTONS_TAB_SORT_BUTTON_LEVEL),\n self._createTableBtnInfo('shortUserName', 154, 7, PROFILE.SECTION_TECHNIQUE_SORT_TOOLTIP_NAME, 'ascending', label=PROFILE.SECTION_TECHNIQUE_BUTTONBAR_VEHICLENAME, inverted=True, sortType='string'),\n self._createTableBtnInfo('battlesCount', 74, 3, PROFILE.SECTION_TECHNIQUE_SORT_TOOLTIP_BATTLESCOUNT, 'descending', label=PROFILE.SECTION_SUMMARY_SCORES_TOTALBATTLES),\n self._createTableBtnInfo('winsEfficiency', 74, 4, PROFILE.SECTION_TECHNIQUE_SORT_TOOLTIP_WINS if isFallout else PROFILE.SECTION_TECHNIQUE_SORT_TOOLTIP_WINRATE, 'descending', label=PROFILE.SECTION_TECHNIQUE_BUTTONBAR_TOTALWINS),\n self._createTableBtnInfo('avgExperience', 90, 5, PROFILE.SECTION_TECHNIQUE_SORT_TOOLTIP_AVGEXP, 'descending', label=PROFILE.SECTION_TECHNIQUE_BUTTONBAR_AVGEXPERIENCE),\n self._createTableBtnInfo('markOfMastery', 83, 6, PROFILE.SECTION_TECHNIQUE_SORT_TOOLTIP_MARKSOFMASTERY, 'descending', label=PROFILE.SECTION_TECHNIQUE_BUTTONBAR_CLASSINESS, enabled=markOfMasteryEnabled))\n\n def _createTableBtnInfo(self, iconId, buttonWidth, sortOrder, toolTip, defaultSortDirection, label = '', iconSource = '', inverted = False, sortType = 'numeric', showSeparator = True, enabled = True):\n return {'id': iconId,\n 'buttonWidth': buttonWidth,\n 'sortOrder': sortOrder,\n 'toolTip': toolTip,\n 'defaultSortDirection': defaultSortDirection,\n 'label': label,\n 'iconSource': iconSource,\n 'inverted': inverted,\n 'sortType': sortType,\n 'showSeparator': showSeparator,\n 'ascendingIconSource': RES_ICONS.MAPS_ICONS_BUTTONS_TAB_SORT_BUTTON_ASCPROFILESORTARROW,\n 'descendingIconSource': RES_ICONS.MAPS_ICONS_BUTTONS_TAB_SORT_BUTTON_DESCPROFILESORTARROW,\n 'buttonHeight': 40,\n 'enabled': enabled}\n\n def getEmptyScreenLabel(self):\n emptyScreenLabelsDictionary = {PROFILE_DROPDOWN_KEYS.ALL: PROFILE.SECTION_TECHNIQUE_EMPTYSCREENLABEL_BATTLETYPE_ALL,\n PROFILE_DROPDOWN_KEYS.FALLOUT: PROFILE.SECTION_TECHNIQUE_EMPTYSCREENLABEL_BATTLETYPE_FALLOUT,\n PROFILE_DROPDOWN_KEYS.TEAM: PROFILE.SECTION_TECHNIQUE_EMPTYSCREENLABEL_BATTLETYPE_TEAM,\n PROFILE_DROPDOWN_KEYS.STATICTEAM: PROFILE.SECTION_TECHNIQUE_EMPTYSCREENLABEL_BATTLETYPE_STATICTEAM,\n PROFILE_DROPDOWN_KEYS.HISTORICAL: PROFILE.SECTION_TECHNIQUE_EMPTYSCREENLABEL_BATTLETYPE_HISTORICAL,\n PROFILE_DROPDOWN_KEYS.CLAN: PROFILE.SECTION_TECHNIQUE_EMPTYSCREENLABEL_BATTLETYPE_GLOBALMAP,\n PROFILE_DROPDOWN_KEYS.RANKED: PROFILE.SECTION_TECHNIQUE_EMPTYSCREENLABEL_BATTLETYPE_RANKED,\n PROFILE_DROPDOWN_KEYS.FORTIFICATIONS_BATTLES: PROFILE.SECTION_TECHNIQUE_EMPTYSCREENLABEL_BATTLETYPE_FORTBATTLES,\n PROFILE_DROPDOWN_KEYS.FORTIFICATIONS_SORTIES: PROFILE.SECTION_TECHNIQUE_EMPTYSCREENLABEL_BATTLETYPE_FORTSORTIES,\n PROFILE_DROPDOWN_KEYS.EPIC_RANDOM: PROFILE.SECTION_TECHNIQUE_EMPTYSCREENLABEL_BATTLETYPE_EPICRANDOM}\n return i18n.makeString(emptyScreenLabelsDictionary[self._battlesType])\n\n def _sendAccountData(self, targetData, accountDossier):\n super(ProfileTechnique, self)._sendAccountData(targetData, accountDossier)\n self.as_setInitDataS(self._getInitData(accountDossier, self._battlesType == PROFILE_DROPDOWN_KEYS.FALLOUT))\n self.as_responseDossierS(self._battlesType, self._getTechniqueListVehicles(targetData), '', self.getEmptyScreenLabel())\n\n def _getTechniqueListVehicles(self, targetData, addVehiclesThatInHangarOnly = False):\n result = []\n if self.lobbyContext.getServerSettings().isEpicRandomMarkOfMasteryEnabled():\n __markOfMasteryBattles = (PROFILE_DROPDOWN_KEYS.ALL, PROFILE_DROPDOWN_KEYS.EPIC_RANDOM, PROFILE_DROPDOWN_KEYS.RANKED)\n else:\n __markOfMasteryBattles = (PROFILE_DROPDOWN_KEYS.ALL, PROFILE_DROPDOWN_KEYS.RANKED)\n showMarkOfMastery = self._battlesType in __markOfMasteryBattles and targetData.getMarksOfMastery() != UNAVAILABLE_MARKS_OF_MASTERY\n for intCD, (battlesCount, wins, xp) in targetData.getVehicles().iteritems():\n avgXP = xp / battlesCount if battlesCount else 0\n vehicle = self.itemsCache.items.getItemByCD(intCD)\n if vehicle is not None:\n isInHangar = vehicle.invID > 0\n if addVehiclesThatInHangarOnly and not isInHangar:\n continue\n if self._battlesType == PROFILE_DROPDOWN_KEYS.FALLOUT:\n winsEfficiency = wins\n winsEfficiencyStr = BigWorld.wg_getIntegralFormat(winsEfficiency)\n else:\n winsEfficiency = 100.0 * wins / battlesCount if battlesCount else 0\n winsEfficiencyStr = BigWorld.wg_getIntegralFormat(round(winsEfficiency)) + '%'\n if showMarkOfMastery:\n markOfMastery = targetData.getMarkOfMasteryForVehicle(intCD)\n if not isMarkOfMasteryAchieved(markOfMastery):\n markOfMastery = ProfileUtils.UNAVAILABLE_VALUE\n else:\n markOfMastery = ProfileUtils.UNAVAILABLE_VALUE\n result.append({'id': intCD,\n 'inventoryID': vehicle.invID,\n 'shortUserName': vehicle.shortUserName,\n 'battlesCount': battlesCount,\n 'winsEfficiency': winsEfficiency,\n 'winsEfficiencyStr': winsEfficiencyStr,\n 'avgExperience': avgXP,\n 'userName': vehicle.userName,\n 'typeIndex': VEHICLE_TABLE_TYPES_ORDER_INDICES_REVERSED[vehicle.type],\n 'nationIndex': GUI_NATIONS_ORDER_INDEX[NAMES[vehicle.nationID]],\n 'nationID': vehicle.nationID,\n 'level': vehicle.level,\n 'markOfMastery': markOfMastery,\n 'markOfMasteryBlock': ACHIEVEMENT_BLOCK.TOTAL,\n 'tankIconPath': vehicle.iconSmall,\n 'typeIconPath': '../maps/icons/filters/tanks/%s.png' % vehicle.type,\n 'isInHangar': isInHangar,\n 'compareModeAvailable': self.comparisonBasket.isEnabled()})\n\n return result\n\n def requestData(self, data):\n pass\n\n def _receiveVehicleDossier(self, vehicleIntCD, databaseId):\n vehDossier = self.itemsCache.items.getVehicleDossier(vehicleIntCD, databaseId)\n achievementsList = None\n specialMarksStats = []\n specialRankedStats = []\n if self._battlesType in (PROFILE_DROPDOWN_KEYS.ALL, PROFILE_DROPDOWN_KEYS.EPIC_RANDOM):\n achievementsEnabled = True\n if self._battlesType == PROFILE_DROPDOWN_KEYS.ALL:\n stats = vehDossier.getRandomStats()\n elif self._battlesType == PROFILE_DROPDOWN_KEYS.EPIC_RANDOM:\n stats = vehDossier.getEpicRandomStats()\n achievementsEnabled = self.lobbyContext.getServerSettings().isEpicRandomAchievementsEnabled()\n if achievementsEnabled:\n achievementsList = self.__getAchievementsList(stats, vehDossier)\n if self.__showMarksOnGun(vehicleIntCD):\n if self._battlesType != PROFILE_DROPDOWN_KEYS.EPIC_RANDOM or self.lobbyContext.getServerSettings().isEpicRandomMarksOnGunEnabled():\n specialMarksStats.append(self.__packAchievement(stats, vehDossier, MARK_ON_GUN_RECORD))\n elif self._battlesType == PROFILE_DROPDOWN_KEYS.TEAM:\n stats = vehDossier.getTeam7x7Stats()\n achievementsList = self.__getAchievementsList(stats, vehDossier)\n elif self._battlesType == PROFILE_DROPDOWN_KEYS.STATICTEAM:\n stats = vehDossier.getRated7x7Stats()\n achievementsList = self.__getAchievementsList(stats, vehDossier)\n elif self._battlesType == PROFILE_DROPDOWN_KEYS.HISTORICAL:\n stats = vehDossier.getHistoricalStats()\n achievementsList = self.__getAchievementsList(stats, vehDossier)\n elif self._battlesType == PROFILE_DROPDOWN_KEYS.FORTIFICATIONS_SORTIES:\n stats = vehDossier.getFortSortiesStats()\n elif self._battlesType == PROFILE_DROPDOWN_KEYS.FORTIFICATIONS_BATTLES:\n stats = vehDossier.getFortBattlesStats()\n elif self._battlesType == PROFILE_DROPDOWN_KEYS.CLAN:\n stats = vehDossier.getGlobalMapStats()\n elif self._battlesType == PROFILE_DROPDOWN_KEYS.FALLOUT:\n stats = vehDossier.getFalloutStats()\n elif self._battlesType == PROFILE_DROPDOWN_KEYS.RANKED:\n stats = vehDossier.getRankedStats()\n achievementsList = self.__getAchievementsList(stats, vehDossier)\n specialRankedStats.append(self.__packAchievement(stats, vehDossier, HONORED_RANK_RECORD))\n else:\n raise ValueError('Profile Technique: Unknown battle type: ' + self._battlesType)\n if achievementsList is not None:\n achievementsList.insert(0, specialRankedStats)\n achievementsList.insert(1, specialMarksStats)\n if self._battlesType == PROFILE_DROPDOWN_KEYS.FORTIFICATIONS_BATTLES:\n layout = FORT_STATISTICS_LAYOUT\n elif self._battlesType == PROFILE_DROPDOWN_KEYS.FALLOUT:\n layout = FALLOUT_STATISTICS_LAYOUT\n else:\n layout = STATISTICS_LAYOUT\n preparedStatistics = DetailedStatisticsUtils.getStatistics(stats, self._userID is None, layout)\n self._selectedVehicleIntCD = vehicleIntCD\n self.as_responseVehicleDossierS({'detailedData': preparedStatistics,\n 'achievements': achievementsList})\n return\n\n def __getAchievementsList(self, targetData, vehDossier):\n packedList = []\n achievements = targetData.getAchievements(True)\n for achievementBlockList in achievements:\n packedList.append(AchievementsUtils.packAchievementList(achievementBlockList, vehDossier.getDossierType(), dumpDossier(vehDossier), self._userID is None, True, ACHIEVEMENTS_ALIASES.GREY_COUNTER))\n\n return packedList\n\n def __onServerSettingChanged(self, diff):\n if 'hallOfFame' in diff:\n self._setRatingButton()\n\n def __packAchievement(self, stats, vehDossier, record):\n \"\"\"\n The method packs desired achievement record for the provided vehicle dossier.\n :param stats: vehicle's stats block (_VehiclesStatsBlock instance)\n :param vehDossier: VehicleDossier instance\n :param record: one from dossiers2/ui/achievements.py\n :return: dict\n \"\"\"\n return AchievementsUtils.packAchievement(stats.getAchievement(record), vehDossier.getDossierType(), dumpDossier(vehDossier), self._userID is None)\n\n def __showMarksOnGun(self, vehicleIntCD):\n \"\"\"\n Checks whether mark on gun should be shown\n :param vehicleIntCD: vehicle's int compact descriptor\n :return: bool\n \"\"\"\n return self.itemsCache.items.getItemByCD(int(vehicleIntCD)).level >= _MARK_ON_GUN_MIN_LVL","repo_name":"kusaku/wotscripts","sub_path":"scripts/client/gui/Scaleform/daapi/view/lobby/profile/ProfileTechnique.py","file_name":"ProfileTechnique.py","file_ext":"py","file_size_in_byte":17983,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"41"} +{"seq_id":"39338439817","text":"def max2(list):\n m1, m2 = (list[0], list[1]) if list[0] > list[1] else (list[1], list[0])\n\n for index in range(2, len(list)):\n if list[index] > m1:\n m2 = m1\n m1 = list[index]\n elif list[index] > m2:\n m2 = list[index]\n return m1,m2\n\nif __name__ == '__main__':\n print(max2([2,65,6,1,6,333332,67,214,61314,2,1,0]))\n","repo_name":"JSherlock1899/python_learn","sub_path":"DAY04/max2.py","file_name":"max2.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"486648770","text":"'''\r\n\r\n10Decimal to Oct\r\n\r\n'''\r\n\r\n\r\n\r\nx = int(input())\r\noct_num = oct(x)\r\nremove_prefix = oct_num[2:]\r\nprint(remove_prefix)\r\n\r\n#I was going to use format like down below\r\n#And there is error like 'ValueError: Unknown format code 'o' for object of type 'str'\r\n#print('{0:o}'.format(oct_num))\r\n\r\n\r\n'''\r\n\r\ndecimal to hexadecimal\r\n\r\n'''\r\n\r\ny = int(input())\r\nhex_num = hex(y)\r\nremove_prefix_hex = hex_num[2:]\r\nremove_prefix_hex = remove_prefix_hex.upper()\r\nprint(remove_prefix_hex)\r\n\r\n'''\r\nOcta -> decimal\r\n'''\r\n\r\nz = input()\r\ndecimal = int(z,8)\r\nprint(decimal)\r\n\r\n'''\r\nhexa to Octa\r\n\r\n'''\r\n\r\nz = hex(input())\r\nz = oct(z)\r\nprint(z)\r\n\r\n","repo_name":"djoo1028/AlgoritmProblems","sub_path":"Codeup-100problem_challenge/Q1031.py","file_name":"Q1031.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"4160489466","text":"import sys\nfrom collections import Counter\n\n\ndef major_element(test):\n numbers = test.split(',')\n counter = Counter(numbers)\n most_common = counter.most_common()[0]\n if most_common[1] > len(numbers)/2:\n return most_common[0]\n return 'None'\n\n\nif __name__ == '__main__':\n test_cases = open(sys.argv[1], 'r')\n for test in test_cases:\n test = test.rstrip()\n if test:\n print(major_element(test))\n test_cases.close()","repo_name":"catalinc/codeeval-solutions","sub_path":"src/python/major_element.py","file_name":"major_element.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"510716198","text":"import xarray as xr\nimport numpy as np\nimport get_models as gm\n\n\n#####Arctic_liq_fw_salt_and_vol_decomp_CESM2.py#######\n#Decomposes the anomalous salt and volume contributions to the ocean\n#fw flux through the Arctic gateways following Holland et al. 2006\n#s=s_mean + s', u=u_mean+u' where u_mean,s_mean are the 2000-2100\n#mean salinity and velocity in each grid cell and u',s' are temporal\n#departures from that mean. The relevant terms in the integrals for the\n#fluxes are then s'*u_mean (salinity contribution) and s_mean*u' (velocity contribution)\ninstitution='NCAR'\nmodel='CESM2'\nexperiment='ssp585' #ssp126, or ssp585\n#Current number of ensemble members:\n#Historical: CAM-11\n#SSP126: CAM-3\n#SSP585: CAM-3\n#Get the right number for the end value for the for loop because the number of ensemble members\n#differs across the models and simulations\nens_num_dict={'historical':np.arange(1,12),'ssp126':[4,10,11],\n\t'ssp585':[4,10,11]}\nens_nums=ens_num_dict[experiment]\nnmax=len(ens_nums)\n\n#Set constants and get model output\n#Constants\ns_ref=34.8 #Reference salinity [PSU]\nkm3yr=(1e-9)*(365*86400) #Convert from [m3/s] to [km3/yr]\nm3sv=1e-6 #Convert from [m3/s] to [Sv] [1 Sv = 10^6 m3/s]\nm3tokm3=1e-9 #Convert from [m3] to [km3]\n\n#Read in ocean and sea ice grid info outside of the for loop--get this from local direcs\nsimulation, time_period=gm.choose_model_and_sim(model,'historical',ens_mem='001')\ndirec_o='/glade/collections/cdg/timeseries-cmip6/'+simulation+'/ocn/proc/tseries/month_1/'\nxdo=xr.open_dataset(direc_o+simulation+'.pop.h.SALT.185001-201412.nc')\n#Ocean\noarea=xdo['TAREA']*0.0001 #T cell area [cm^2], converted to [m^2]\nodepth=xdo['HT']*0.01 #T cell ocean depth [cm], converted to [m]\nDYU=xdo['DYU']*0.01 #U cell y-spacing [cm], converted to [m]\nDXU=xdo['DXU']*0.01 #U cell x-spacing, converted to [m]\nDXT=xdo['DXT']*0.01 #T cell x-spacing, converted to [m]\nDYT=xdo['DYT']*0.01 #T cell y-spacing, converted to [m]\nHUW=xdo['HUW']*0.01 #U cell widths on west sides [cm], converted to [m]\nHUS=xdo['HUS']*0.01 #U cell widths on south sides [cm], converted to [m]\nHTE=xdo['HTE']*0.01 #T cell widths on east sides [cm], converted to [m]\nHTN=xdo['HTN']*0.01 #T cell widths on north sides [cm], converted to [m]\nzt=xdo['z_t']*0.01 #Depth of center of each ocean layer [cm], converted to [m]\ndz=xdo['dz']*0.01 #Ocean layer thickness [cm], converted to [m]\n#Rename zt and dz vertical dimension from 'z_t' to 'lev'\n#to be consistent with CMIP6 output\nzt=zt.rename({'z_t':'lev'})\ndz=dz.rename({'z_t':'lev'})\n\n#Read in ice/ocean output for each ensemble member and compute the fluxes\nfor ens_num in ens_nums:\n\tprint('Starting Ensemble Member '+str('%i' %ens_num)) # +'/'+str('%i' %nmax))\n\tvariant='r'+str('%i' %ens_num)+'i1p1f1'\n\t#For getting the historical and ssp files\n\tsimhist,miphist,tp_hist=gm.choose_model_and_sim_cmip6(model,'historical',variant)\n\tsimssp, mipssp, tp_ssp=gm.choose_model_and_sim_cmip6(model,experiment,variant)\n\n\t#Ocean directory for CanESM5 for CMIP6\n\tdirec_hist='/glade/collections/cmip/CMIP6/'+miphist+'/'+institution+'/'+model+'/historical/'+variant+'/Omon/'\n\tdirec_ssp='/glade/collections/cmip/CMIP6/'+mipssp+'/'+institution+'/'+model+'/'+experiment+'/'+variant+'/Omon/'\n\n\t#Ocean variables\n\tprint('Getting ocean variables')\n\t#Historical\n\t#Get salinity and velocities\n\txdo=xr.open_mfdataset(direc_hist+'so/gn/latest/so_Omon_'+simhist+'*201412.nc',combine='by_coords',data_vars='minimal')\n\tsalthist=xdo['so'].sel({'time':slice('2000-01-01',None)}) #ocean salinity in PSU\n\txdo=xr.open_mfdataset(direc_hist+'uo/gn/latest/uo_Omon_'+simhist+'*201412.nc',combine='by_coords',data_vars='minimal')\n\tuhist=xdo['uo'].sel({'time':slice('2000-01-01',None)}) #ocean zonal velocity in [m/s]\n\txdo=xr.open_mfdataset(direc_hist+'vo/gn/latest/vo_Omon_'+simhist+'*201412.nc',combine='by_coords',data_vars='minimal')\n\tvhist=xdo['vo'].sel({'time':slice('2000-01-01',None)}) #ocean meridional velocity in [m/s]\n\t#ssp\n\t#Get salinity and velocities\n\txdo=xr.open_mfdataset(direc_ssp+'so/gn/latest/so_Omon_'+simssp+'*.nc',combine='by_coords',data_vars='minimal')\n\tsaltssp=xdo['so'] #ocean salinity in PSU\n\txdo=xr.open_mfdataset(direc_ssp+'uo/gn/latest/uo_Omon_'+simssp+'*.nc',combine='by_coords',data_vars='minimal')\n\tussp=xdo['uo'] #ocean zonal velocity in [m/s]\n\txdo=xr.open_mfdataset(direc_ssp+'vo/gn/latest/vo_Omon_'+simssp+'*.nc',combine='by_coords',data_vars='minimal')\n\tvssp=xdo['vo'] #ocean meridional velocity in [m/s]\n\n\t#Concatenate\n\tsalt=xr.concat([salthist,saltssp],dim='time')\n\tu=xr.concat([uhist,ussp],dim='time')\n\tv=xr.concat([vhist,vssp],dim='time')\n\n\tprint('Model output read in and ready for computation')\n\n\t#########1. Liquid flux decomposition through Arctic Gateways [km3/yr]\n\n\t##--------Bering Strait\n\t#Liquid flux through Bering Strait: x=[199,200], y=332 #Indices on full world\n\t#Compute the fw volume relative to 34.8\n\t#Northward (positive) velocities are into the Arctic so the sign convention is correct\n\tj=332\n\tistart=199\n\tiend=200\n\tkmax=4 #maximum number of depth levels across the transect\n\tsaltber=salt[:,0:kmax,j,istart:iend+1].load()\n\tvber=v[:,0:kmax,j-1:j+1,istart-1:iend+1]\n\tvber=vber.where(xr.ufuncs.isfinite(vber),other=0).compute()\n\tDYUber=DYU[j-1:j+1,istart-1:iend+1].load()\n\tDXUber=HUS[j,istart-1:iend+1].load()\n\tDXTber=DXT[j,istart:iend+1].load()\n\tdzber=dz[0:kmax].load()\n\t#Average meridional velocities in y first\n\tvber=(vber[:,:,0]*DYUber[0]+vber[:,:,1]*DYUber[1])/(DYUber[0]+DYUber[1])\n\t#Average in x\n\tvmid=xr.DataArray(data=np.zeros_like(saltber),coords=saltber.coords,dims=saltber.dims)\n\tvmid[:,:,0]=(vber[:,:,0]*DXUber[0]+vber[:,:,1]*DXUber[1])/sum(DXUber[0:2])\n\tvmid[:,:,1]=(vber[:,:,1]*DXUber[1]+vber[:,:,2]*DXUber[2])/sum(DXUber[1:])\n\t\n\t#Compute mean and anomalies for salinity and velocity\n\tvmid_mn=vmid.mean('time')\n\tsalt_mn=saltber.mean('time')\n\tvmid_anom=vmid-vmid_mn\n\tsalt_anom=saltber-salt_mn\n\t#Compute anomalous velocity (volume) and salinity contributions\n\tber_area=dzber*DXTber\n\tber_vol_cont=((s_ref-salt_mn)/s_ref)*vmid_anom*ber_area\n\tber_salt_cont=(-1.0*salt_anom/s_ref)*vmid_mn*ber_area\n\tber_liq_flux_vol_cont=km3yr*ber_vol_cont.sum(dim=('lev','nlon'))\n\tber_liq_flux_salt_cont=km3yr*ber_salt_cont.sum(dim=('lev','nlon'))\n\t#Split for salinities above and below s_ref\n\tber_liq_flux_vol_cont_below_sref=km3yr*ber_vol_cont.where(saltber<=s_ref,other=0).sum(dim=('lev','nlon'))\n\tber_liq_flux_vol_cont_above_sref=km3yr*ber_vol_cont.where(saltber>s_ref,other=0).sum(dim=('lev','nlon'))\n\tber_liq_flux_salt_cont_below_sref=km3yr*ber_salt_cont.where(saltber<=s_ref,other=0).sum(dim=('lev','nlon'))\n\tber_liq_flux_salt_cont_above_sref=km3yr*ber_salt_cont.where(saltber>s_ref,other=0).sum(dim=('lev','nlon'))\n\n\n\t##--------Nares Strait\n\t#Liquid flux through Nares: x=237, y=[376,377] #Indices on full world\n\t#Compute the fw volume relative to 34.8\n\t#Flow out of Nares is east (positive) so to keep with the Arctic sign covention, multiply by -1\n\t#Nares is only 2 grid cells wide, and the walls are vertical\n\tjstart=376\n\tjend=377\n\ti=237\n\tkmax=11 #Maximum number of depth levels across the transect\n\tsaltnar=salt[:,0:kmax,jstart:jend+1,i].load()\n\tunar=u[:,0:kmax,jstart-1:jend+1,i-1:i+1]\n\tunar=unar.where(xr.ufuncs.isfinite(unar),other=0).compute()\n\tDXUnar=DXU[jstart-1:jend+1,i-1:i+1].load()\n\tDYUnar=HUW[jstart-1:jend+1,i].load()\n\tDYTnar=DYT[jstart:jend+1,i].load()\n\tdznar=dz[0:kmax].load()\n\t#Average zonal velocities in x first\n\tunar=(unar[:,:,:,0]*DXUnar[:,0]+unar[:,:,:,1]*DXUnar[:,1])/(DXUnar[:,0]+DXUnar[:,1])\n\t#Average in y\n\tumid=xr.DataArray(data=np.zeros_like(saltnar),coords=saltnar.coords,dims=saltnar.dims)\n\tumid[:,:,0]=-1.0*(unar[:,:,0]*DYUnar[0]+unar[:,:,1]*DYUnar[1])/sum(DYUnar[0:2])\n\tumid[:,:,1]=-1.0*(unar[:,:,1]*DYUnar[1]+unar[:,:,2]*DYUnar[2])/sum(DYUnar[1:])\n\n\t#Compute mean and anomalies for salinity and velocity\n\tumid_mn=umid.mean('time')\n\tsalt_mn=saltnar.mean('time')\n\tumid_anom=umid-umid_mn\n\tsalt_anom=saltnar-salt_mn\n\t#Compute anomalous velocity (volume) and salinity contributions\n\tnar_area=dznar*DYTnar\n\tnar_vol_cont=((s_ref-salt_mn)/s_ref)*umid_anom*nar_area\n\tnar_salt_cont=(-1.0*salt_anom/s_ref)*umid_mn*nar_area\n\tnar_liq_flux_vol_cont=km3yr*nar_vol_cont.sum(dim=('lev','nlat'))\n\tnar_liq_flux_salt_cont=km3yr*nar_salt_cont.sum(dim=('lev','nlat'))\n\t#Split for salinities above and below s_ref\n\tnar_liq_flux_vol_cont_below_sref=km3yr*nar_vol_cont.where(saltnar<=s_ref,other=0).sum(dim=('lev','nlat'))\n\tnar_liq_flux_vol_cont_above_sref=km3yr*nar_vol_cont.where(saltnar>s_ref,other=0).sum(dim=('lev','nlat'))\n\tnar_liq_flux_salt_cont_below_sref=km3yr*nar_salt_cont.where(saltnar<=s_ref,other=0).sum(dim=('lev','nlat'))\n\tnar_liq_flux_salt_cont_above_sref=km3yr*nar_salt_cont.where(saltnar>s_ref,other=0).sum(dim=('lev','nlat'))\n\n\n\t##--------Barrow Strait\n\t#Liquid fw flux through Barrow Strait: x=[233,237], y=360 #Indices on full world map\n\t#Compute the fw volume relative to 34.8\n\t#Northward (positive) velocities are OUT OF the Arctic so multiply by -1 to get the right sign convention\n\tj=360\n\tistart=233\n\tiend=237\n\tkmax=25 #maximum number of depth levels across the transect\n\tirange=np.arange(istart,iend+1)\n\tsaltbrw=salt[:,0:kmax,j,istart:iend+1].load()\n\tvbrw=v[:,0:kmax,j-1:j+1,istart-1:iend+1]\n\tvbrw=vbrw.where(xr.ufuncs.isfinite(vbrw),other=0).compute()\n\tDYUbrw=DYU[j-1:j+1,istart-1:iend+1].load()\n\tDXUbrw=HUS[j,istart-1:iend+1].load()\n\tDXTbrw=DXT[j,istart:iend+1].load()\n\tdzbrw=dz[0:kmax].load()\n\t#Average meridional velocities in y first\n\tvbrw=(vbrw[:,:,0]*DYUbrw[0]+vbrw[:,:,1]*DYUbrw[1])/(DYUbrw[0]+DYUbrw[1])\n\t#Average in x\n\tvmid=xr.DataArray(data=np.zeros_like(saltbrw),coords=saltbrw.coords,dims=saltbrw.dims)\n\tfor i in range(0,len(irange)):\n\t\tvmid[:,:,i]=-1.0*(vbrw[:,:,i]*DXUbrw[i]+vbrw[:,:,i+1]*DXUbrw[i+1])/sum(DXUbrw[i:i+2])\n\n\t#Compute mean and anomalies for salinity and velocity\n\tvmid_mn=vmid.mean('time')\n\tsalt_mn=saltbrw.mean('time')\n\tvmid_anom=vmid-vmid_mn\n\tsalt_anom=saltbrw-salt_mn\n\t#Compute anomalous velocity (volume) and salinity contributions\n\tbrw_area=dzbrw*DXTbrw\n\tbrw_vol_cont=((s_ref-salt_mn)/s_ref)*vmid_anom*brw_area\n\tbrw_salt_cont=(-1.0*salt_anom/s_ref)*vmid_mn*brw_area\n\tbrw_liq_flux_vol_cont=km3yr*brw_vol_cont.sum(dim=('lev','nlon'))\n\tbrw_liq_flux_salt_cont=km3yr*brw_salt_cont.sum(dim=('lev','nlon'))\n\t#Split for salinities above and below s_ref\n\tbrw_liq_flux_vol_cont_below_sref=km3yr*brw_vol_cont.where(saltbrw<=s_ref,other=0).sum(dim=('lev','nlon'))\n\tbrw_liq_flux_vol_cont_above_sref=km3yr*brw_vol_cont.where(saltbrw>s_ref,other=0).sum(dim=('lev','nlon'))\n\tbrw_liq_flux_salt_cont_below_sref=km3yr*brw_salt_cont.where(saltbrw<=s_ref,other=0).sum(dim=('lev','nlon'))\n\tbrw_liq_flux_salt_cont_above_sref=km3yr*brw_salt_cont.where(saltbrw>s_ref,other=0).sum(dim=('lev','nlon'))\n\n\t\n\t##--------Fram Strait\n\t#Liquid flux through Fram Strait, x=[98,106], y=[370,378]. Indices on full world. This is\n\t#is a 45˚ line so it doesn't have a complex pattern for the grid cells it passes through\n\t#Fram is oriented such that eastward (positive) velocities are into the Arctic, whereas northward (positive)\n\t#velocities are out of the Arcitc, so multiply v by -1\n\t#Compute the fw volume relative to 34.8\n\tistart=98\n\tiend=106\n\tjstart=370\n\tjend=378\n\tkmax=47 #maximum number of depth levels across the transect\n\ti_range=np.arange(istart,iend+1)\n\tj_range=np.arange(jstart,jend+1)\n\n\tsaltfram=salt[:,0:kmax,jstart:jend+1,istart:iend+1].load()\n\tufram=u[:,0:kmax,jstart-1:jend+1,istart-1:iend+1] #one point larger in x,y for midpoint averaging\n\tufram=ufram.where(xr.ufuncs.isfinite(ufram),other=0).compute()\n\tvfram=v[:,0:kmax,jstart-1:jend+1,istart-1:iend+1] #one point larger in x,y for midpoint averaging\n\tvfram=vfram.where(xr.ufuncs.isfinite(vfram),other=0).compute()\n\tDYUfram=HUW[jstart-1:jend+1,istart-1:iend+1].load() #one point larger in x,y for midpoint averaging\n\tHTNfram=HTN[jstart:jend+1,istart:iend+1].load()\n\tDXUfram=DXU[jstart-1:jend+1,istart-1:iend+1].load() #one point larger in x,y for midpoint averaging\n\tHTEfram=HTE[jstart:jend+1,istart:iend+1].load()\n\tdzfram=dz[0:kmax].load()\n\tumid=xr.DataArray(data=np.zeros_like(saltfram),coords=saltfram.coords,dims=saltfram.dims)\n\tvmid=xr.DataArray(data=np.zeros_like(saltfram),coords=saltfram.coords,dims=saltfram.dims)\n\n\ti_range_enum=np.arange(len(i_range))\n\tfor (i,j) in zip(i_range_enum,i_range_enum):\n\t\t#Avg in x first\n\t\tumidx=(ufram[:,:,j:j+2,i]*DXUfram[j:j+2,i]+ufram[:,:,j:j+2,i+1]*DXUfram[j:j+2,i+1])/DXUfram[j:j+2,i:i+2].sum(dim='nlon')\n\t\tvmidx=(vfram[:,:,j:j+2,i]*DXUfram[j:j+2,i]+vfram[:,:,j:j+2,i+1]*DXUfram[j:j+2,i+1])/DXUfram[j:j+2,i:i+2].sum(dim='nlon')\n\t\t#Then in y\n\t\tumid[:,:,j,i]=(umidx[:,:,0]*DYUfram[j,i]+umidx[:,:,1]*DYUfram[j+1,i])/DYUfram[j:j+2,i].sum(dim='nlat')\n\t\tvmid[:,:,j,i]=-1.0*(vmidx[:,:,0]*DYUfram[j,i]+vmidx[:,:,1]*DYUfram[j+1,i])/DYUfram[j:j+2,i].sum(dim='nlat')\n\t#Compute the fluxes\n\tvel_scale=0.5*np.sqrt(2) #The unit normal into the Arctic for the Fram line makes a 45˚ angle with u and v\n\t#Can only do this if u,v arrays are same size and values are colocated\n\tfram_vel=(umid+vmid)*vel_scale\n\tfram_area=dzfram*np.sqrt(HTEfram*HTEfram+HTNfram*HTNfram)\n\t#Compute mean and anomalies for salinity and velocity\n\tvel_mn=fram_vel.mean('time')\n\tsalt_mn=saltfram.mean('time')\n\tvel_anom=fram_vel-vel_mn\n\tsalt_anom=saltfram-salt_mn\n\t#Compute anomalous velocity (volume) and salinity contributions\n\tfram_vol_cont=((s_ref-salt_mn)/s_ref)*vel_anom*fram_area\n\tfram_salt_cont=(-1.0*salt_anom/s_ref)*vel_mn*fram_area\n\tfram_liq_flux_vol_cont=km3yr*fram_vol_cont.sum(dim=('lev','nlon','nlat'))\n\tfram_liq_flux_salt_cont=km3yr*fram_salt_cont.sum(dim=('lev','nlon','nlat'))\n\t#Split for salinities above and below s_ref\n\tfram_liq_flux_vol_cont_below_sref=km3yr*fram_vol_cont.where(saltfram<=s_ref,other=0).sum(dim=('lev','nlon','nlat'))\n\tfram_liq_flux_vol_cont_above_sref=km3yr*fram_vol_cont.where(saltfram>s_ref,other=0).sum(dim=('lev','nlon','nlat'))\n\tfram_liq_flux_salt_cont_below_sref=km3yr*fram_salt_cont.where(saltfram<=s_ref,other=0).sum(dim=('lev','nlon','nlat'))\n\tfram_liq_flux_salt_cont_above_sref=km3yr*fram_salt_cont.where(saltfram>s_ref,other=0).sum(dim=('lev','nlon','nlat'))\n\n\n\t##--------Barents Sea Opening (BSO)\n\t#Liquid flux through the BSO, x=[79,90], y=[355,366]. Indices on full world. This is\n\t#is a 45˚ line so it doesn't have a complex pattern for the grid cells it passes through\n\t#The BSO is oriented such that eastward (positive) velocities are into the Arctic, whereas northward (positive)\n\t#velocities are out of the Arcitc, so multiply v by -1\n\t#Compute the fw volume relative to 34.8\n\tistart=79\n\tiend=90\n\tjstart=355\n\tjend=366\n\tkmax=47 #maximum number of depth levels across the transect\n\ti_range=np.arange(istart,iend+1)\n\tj_range=np.arange(jstart,jend+1)\n\n\tsaltbso=salt[:,0:kmax,jstart:jend+1,istart:iend+1].load()\n\tubso=u[:,0:kmax,jstart-1:jend+1,istart-1:iend+1] #one point larger in x,y for midpoint averaging\n\tubso=ubso.where(xr.ufuncs.isfinite(ubso),other=0).compute()\n\tvbso=v[:,0:kmax,jstart-1:jend+1,istart-1:iend+1] #one point larger in x,y for midpoint averaging\n\tvbso=vbso.where(xr.ufuncs.isfinite(vbso),other=0).compute()\n\tDYUbso=HUW[jstart-1:jend+1,istart-1:iend+1].load() #one point larger in x,y for midpoint averaging\n\tHTNbso=HTN[jstart:jend+1,istart:iend+1].load()\n\tDXUbso=DXU[jstart-1:jend+1,istart-1:iend+1].load() #one point larger in x,y for midpoint averaging\n\tHTEbso=HTE[jstart:jend+1,istart:iend+1].load()\n\tdzbso=dz[0:kmax].load()\n\tumid=xr.DataArray(data=np.zeros_like(saltbso),coords=saltbso.coords,dims=saltbso.dims)\n\tvmid=xr.DataArray(data=np.zeros_like(saltbso),coords=saltbso.coords,dims=saltbso.dims)\n\n\ti_range_enum=np.arange(len(i_range))\n\tfor (i,j) in zip(i_range_enum,i_range_enum):\n\t\t#Avg in x first\n\t\tumidx=(ubso[:,:,j:j+2,i]*DXUbso[j:j+2,i]+ubso[:,:,j:j+2,i+1]*DXUbso[j:j+2,i+1])/DXUbso[j:j+2,i:i+2].sum(dim='nlon')\n\t\tvmidx=(vbso[:,:,j:j+2,i]*DXUbso[j:j+2,i]+vbso[:,:,j:j+2,i+1]*DXUbso[j:j+2,i+1])/DXUbso[j:j+2,i:i+2].sum(dim='nlon')\n\t\t#Then in y\n\t\tumid[:,:,j,i]=(umidx[:,:,0]*DYUbso[j,i]+umidx[:,:,1]*DYUbso[j+1,i])/DYUbso[j:j+2,i].sum(dim='nlat')\n\t\tvmid[:,:,j,i]=-1.0*(vmidx[:,:,0]*DYUbso[j,i]+vmidx[:,:,1]*DYUbso[j+1,i])/DYUbso[j:j+2,i].sum(dim='nlat')\n\t#Compute the fluxes\n\tvel_scale=0.5*np.sqrt(2) #The unit normal into the Arctic for the BSO line makes a 45˚ angle with u and v\n\t#Can only do this if u,v arrays are same size and values are colocated\n\tbso_vel=(umid+vmid)*vel_scale\n\tbso_area=dzbso*np.sqrt(HTEbso*HTEbso+HTNbso*HTNbso)\n\t#Compute mean and anomalies for salinity and velocity\n\tvel_mn=bso_vel.mean('time')\n\tsalt_mn=saltbso.mean('time')\n\tvel_anom=bso_vel-vel_mn\n\tsalt_anom=saltbso-salt_mn\n\t#Compute anomalous velocity (volume) and salinity contributions\n\tbso_vol_cont=((s_ref-salt_mn)/s_ref)*vel_anom*bso_area\n\tbso_salt_cont=(-1.0*salt_anom/s_ref)*vel_mn*bso_area\n\tbso_liq_flux_vol_cont=km3yr*bso_vol_cont.sum(dim=('lev','nlon','nlat'))\n\tbso_liq_flux_salt_cont=km3yr*bso_salt_cont.sum(dim=('lev','nlon','nlat'))\n\t#Split for salinities above and below s_ref\n\tbso_liq_flux_vol_cont_below_sref=km3yr*bso_vol_cont.where(saltbso<=s_ref,other=0).sum(dim=('lev','nlon','nlat'))\n\tbso_liq_flux_vol_cont_above_sref=km3yr*bso_vol_cont.where(saltbso>s_ref,other=0).sum(dim=('lev','nlon','nlat'))\n\tbso_liq_flux_salt_cont_below_sref=km3yr*bso_salt_cont.where(saltbso<=s_ref,other=0).sum(dim=('lev','nlon','nlat'))\n\tbso_liq_flux_salt_cont_above_sref=km3yr*bso_salt_cont.where(saltbso>s_ref,other=0).sum(dim=('lev','nlon','nlat'))\n\n\t##--------Davis Strait\n\t#Liquid flux through Davis Strait: x=[293,304], y=364 #Indices on full world\n\t#Compute the fw volume relative to 34.8\n\t#Northward (positive) velocities are into the Arctic so the sign convention is correct\n\tj=364\n\tistart=293\n\tiend=304\n\tkmax=36 #maximum number of depth levels across the transect\n\tirange=np.arange(istart,iend+1)\n\tsaltdav=salt[:,0:kmax,j,istart:iend+1].load()\n\tvdav=v[:,0:kmax,j-1:j+1,istart-1:iend+1]\n\tvdav=vdav.where(xr.ufuncs.isfinite(vdav),other=0).compute()\n\tDYUdav=DYU[j-1:j+1,istart-1:iend+1].load()\n\tDXUdav=HUS[j,istart-1:iend+1].load()\n\tDXTdav=DXT[j,istart:iend+1].load()\n\tdzdav=dz[0:kmax].load()\n\t#Average meridional velocities in y first\n\tvdav=(vdav[:,:,0]*DYUdav[0]+vdav[:,:,1]*DYUdav[1])/(DYUdav[0]+DYUdav[1])\n\t#Average in x\n\tvmid=xr.DataArray(data=np.zeros_like(saltdav),coords=saltdav.coords,dims=saltdav.dims)\n\tfor i in range(0,len(irange)):\n\t\tvmid[:,:,i]=(vdav[:,:,i]*DXUdav[i]+vdav[:,:,i+1]*DXUdav[i+1])/sum(DXUdav[i:i+2])\n\n\t#Compute mean and anomalies for salinity and velocity\n\tvmid_mn=vmid.mean('time')\n\tsalt_mn=saltdav.mean('time')\n\tvmid_anom=vmid-vmid_mn\n\tsalt_anom=saltdav-salt_mn\n\t#Compute anomalous velocity (volume) and salinity contributions\n\tdav_area=dzdav*DXTdav\n\tdav_vol_cont=((s_ref-salt_mn)/s_ref)*vmid_anom*dav_area\n\tdav_salt_cont=(-1.0*salt_anom/s_ref)*vmid_mn*dav_area\n\tdav_liq_flux_vol_cont=km3yr*dav_vol_cont.sum(dim=('lev','nlon'))\n\tdav_liq_flux_salt_cont=km3yr*dav_salt_cont.sum(dim=('lev','nlon'))\n\t#Split for salinities above and below s_ref\n\tdav_liq_flux_vol_cont_below_sref=km3yr*dav_vol_cont.where(saltdav<=s_ref,other=0).sum(dim=('lev','nlon'))\n\tdav_liq_flux_vol_cont_above_sref=km3yr*dav_vol_cont.where(saltdav>s_ref,other=0).sum(dim=('lev','nlon'))\n\tdav_liq_flux_salt_cont_below_sref=km3yr*dav_salt_cont.where(saltdav<=s_ref,other=0).sum(dim=('lev','nlon'))\n\tdav_liq_flux_salt_cont_above_sref=km3yr*dav_salt_cont.where(saltdav>s_ref,other=0).sum(dim=('lev','nlon'))\n\n\tprint('Liquid flux decomposition done!')\n\n\t#########2. Save the output\n\tsv_dims=['time'] #['ensemble','time']\n\tdvs={'ber_liq_flux_vol_cont':(sv_dims,ber_liq_flux_vol_cont),'ber_liq_flux_salt_cont':(sv_dims,ber_liq_flux_salt_cont),\n\t 'ber_liq_flux_vol_cont_above_sref':(sv_dims,ber_liq_flux_vol_cont_above_sref),\n\t 'ber_liq_flux_vol_cont_below_sref':(sv_dims,ber_liq_flux_vol_cont_below_sref),\n\t 'ber_liq_flux_salt_cont_above_sref':(sv_dims,ber_liq_flux_salt_cont_above_sref),\n\t 'ber_liq_flux_salt_cont_below_sref':(sv_dims,ber_liq_flux_salt_cont_below_sref),\n\t 'nares_liq_flux_vol_cont':(sv_dims,nar_liq_flux_vol_cont),'nares_liq_flux_salt_cont':(sv_dims,nar_liq_flux_salt_cont),\n\t 'nares_liq_flux_vol_cont_above_sref':(sv_dims,nar_liq_flux_vol_cont_above_sref),\n\t 'nares_liq_flux_vol_cont_below_sref':(sv_dims,nar_liq_flux_vol_cont_below_sref),\n\t 'nares_liq_flux_salt_cont_above_sref':(sv_dims,nar_liq_flux_salt_cont_above_sref),\n\t 'nares_liq_flux_salt_cont_below_sref':(sv_dims,nar_liq_flux_salt_cont_below_sref),\n\t 'brw_liq_flux_vol_cont':(sv_dims,brw_liq_flux_vol_cont),'brw_liq_flux_salt_cont':(sv_dims,brw_liq_flux_salt_cont),\n\t 'brw_liq_flux_vol_cont_above_sref':(sv_dims,brw_liq_flux_vol_cont_above_sref),\n\t 'brw_liq_flux_vol_cont_below_sref':(sv_dims,brw_liq_flux_vol_cont_below_sref),\n\t 'brw_liq_flux_salt_cont_above_sref':(sv_dims,brw_liq_flux_salt_cont_above_sref),\n\t 'brw_liq_flux_salt_cont_below_sref':(sv_dims,brw_liq_flux_salt_cont_below_sref),\n\t 'fram_liq_flux_vol_cont':(sv_dims,fram_liq_flux_vol_cont),'fram_liq_flux_salt_cont':(sv_dims,fram_liq_flux_salt_cont),\n\t 'fram_liq_flux_vol_cont_above_sref':(sv_dims,fram_liq_flux_vol_cont_above_sref),\n\t 'fram_liq_flux_vol_cont_below_sref':(sv_dims,fram_liq_flux_vol_cont_below_sref),\n\t 'fram_liq_flux_salt_cont_above_sref':(sv_dims,fram_liq_flux_salt_cont_above_sref),\n\t 'fram_liq_flux_salt_cont_below_sref':(sv_dims,fram_liq_flux_salt_cont_below_sref),\n\t 'bso_liq_flux_vol_cont':(sv_dims,bso_liq_flux_vol_cont),'bso_liq_flux_salt_cont':(sv_dims,bso_liq_flux_salt_cont),\n\t 'bso_liq_flux_vol_cont_above_sref':(sv_dims,bso_liq_flux_vol_cont_above_sref),\n\t 'bso_liq_flux_vol_cont_below_sref':(sv_dims,bso_liq_flux_vol_cont_below_sref),\n\t 'bso_liq_flux_salt_cont_above_sref':(sv_dims,bso_liq_flux_salt_cont_above_sref),\n\t 'bso_liq_flux_salt_cont_below_sref':(sv_dims,bso_liq_flux_salt_cont_below_sref),\n\t 'davis_liq_flux_vol_cont':(sv_dims,dav_liq_flux_vol_cont),'davis_liq_flux_salt_cont':(sv_dims,dav_liq_flux_salt_cont),\n\t 'davis_liq_flux_vol_cont_above_sref':(sv_dims,dav_liq_flux_vol_cont_above_sref),\n\t 'davis_liq_flux_vol_cont_below_sref':(sv_dims,dav_liq_flux_vol_cont_below_sref),\n\t 'davis_liq_flux_salt_cont_above_sref':(sv_dims,dav_liq_flux_salt_cont_above_sref),\n\t 'davis_liq_flux_salt_cont_below_sref':(sv_dims,dav_liq_flux_salt_cont_below_sref)}\n\tds=xr.Dataset(data_vars=dvs, coords={'time':u.coords['time']}) #you can use any variable here that has a time coord\n\t#Change units attributes to be km3/yr, check the encoding params and the attributes\n\tfor a in [v for v in ds.variables if 'flux' in v]:\n\t\tds[a].attrs['units']='km3 yr-1'\n\t#Save it as a netcdf\n\tsvdirec='/glade/u/home/zanowski/ArcticFW/'\n\t#Opening in 'a' mode overwrites exsiting variables and 'w' overwrites the whole file\n\tds.to_netcdf(path=svdirec+'Arctic_fw_flux_salt_and_vol_decomp_ts_'+model+'_'+experiment.lower()+'_'+str('%02i' %ens_num)+'.nc')\n\tprint('Output for ensemble member '+str('%02i' %ens_num)+' saved!')\n\n","repo_name":"HannahZanowski/CMIP6_ArcticFW","sub_path":"Arctic_liq_fw_salt_and_vol_decomp_CESM2.py","file_name":"Arctic_liq_fw_salt_and_vol_decomp_CESM2.py","file_ext":"py","file_size_in_byte":22906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"18379928955","text":"import container\n\ndef clone(obj):\n corpse = container.Container(\"corpse\", __file__)\n corpse.add_names(\"corpse\")\n corpse.set_description('corpse of a %s' % (obj._short_desc), 'This is the foul-smelling corpse of a %s. It looks nasty.' % (obj._short_desc))\n corpse.set_weight(obj.get_weight())\n corpse.set_volume(obj.get_volume())\n corpse.set_max_weight_carried(obj.max_weight_carried)\n corpse.set_max_volume_carried(obj.max_volume_carried)\n corpse.add_names('corpse')\n return corpse\n","repo_name":"davedotluebke/old-skool-text-game","sub_path":"corpse.py","file_name":"corpse.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"40"} +{"seq_id":"10814669789","text":"import turtle\r\n\r\nvucutrengi = 'red'\r\nvucutgölgesi = ''\r\ngözrengi = '' \r\ngözçiz = '#dddddd'\r\n\r\ns = turtle.getscreen()\r\nt = turtle.Turtle()\r\n\r\ndef body():\r\n t.pensize(20)\r\n\r\n t.fillcolor(vucutrengi)\r\n t.begin_fill()\r\n\r\n t.right(90)\r\n t.forward(50)\r\n t.right(180)\r\n t.circle(40, -180)\r\n t.right(180)\r\n t.forward(200)\r\n\r\n t.right(180)\r\n t.circle(100, -180)\r\n\r\n t.backward(20)\r\n t.left(15)\r\n t.circle(500, -20)\r\n t.backward(20)\r\n\r\n t.circle(40, -180)\r\n t.left(7)\r\n t.backward(50)\r\n\r\n t.up()\r\n t.left(90)\r\n t.forward(10)\r\n t.right(90)\r\n t.down()\r\n t.right(240)\r\n t.circle(50, -70)\r\n\r\n t.end_fill()\r\n\r\n\r\ndef glass():\r\n t.up()\r\n t.right(230)\r\n t.forward(100)\r\n t.left(90)\r\n t.forward(20)\r\n t.right(90)\r\n\r\n t.down()\r\n t.fillcolor(gözçiz)\r\n t.begin_fill()\r\n\r\n t.right(150)\r\n t.circle(90, -55)\r\n\r\n t.right(180)\r\n t.forward(1)\r\n t.right(180)\r\n t.circle(10, -65)\r\n t.right(180)\r\n t.forward(110)\r\n t.right(180)\r\n \r\n t.circle(50, -190)\r\n t.right(170)\r\n t.forward(80)\r\n\r\n t.right(180)\r\n t.circle(45, -30)\r\n\r\n t.end_fill()\r\n\r\ndef backpack():\r\n t.up()\r\n t.right(60)\r\n t.forward(100)\r\n t.right(90)\r\n t.forward(75)\r\n\r\n t.fillcolor(vucutrengi)\r\n t.begin_fill()\r\n\r\n t.down()\r\n t.forward(30)\r\n t.right(255)\r\n\r\n t.circle(300, -30)\r\n t.right(260)\r\n t.forward(30)\r\n\r\n t.end_fill()\r\n\r\n\r\nbody()\r\nglass()\r\nbackpack()\r\n\r\nt.screen.exitonclick()\r\n","repo_name":"emjan58/Amongus","sub_path":"among us.py","file_name":"among us.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"ar","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"70506580601","text":"import numpy as np\r\n\r\ndef Add_Window_Horizon(data, window=3, horizon=1, single=False):\r\n '''\r\n :param data: shape [B, ...]\r\n :param window:\r\n :param horizon:\r\n :return: X is [B, W, ...], Y is [B, H, ...]\r\n '''\r\n length = len(data)\r\n end_index = length - horizon - window + 1\r\n X = [] #windows\r\n Y = [] #horizon\r\n index = 0\r\n if single:\r\n while index < end_index:\r\n X.append(data[index:index+window])\r\n Y.append(data[index+window+horizon-1:index+window+horizon])\r\n index = index + 1\r\n else:\r\n while index < end_index:\r\n X.append(data[index:index+window])\r\n Y.append(data[index+window:index+window+horizon])\r\n index = index + 1\r\n X = np.array(X)\r\n Y = np.array(Y)\r\n return X, Y\r\n\r\nif __name__ == '__main__':\r\n from data.load_raw_data import Load_Sydney_Demand_Data\r\n path = '../data/1h_data_new3.csv'\r\n data = Load_Sydney_Demand_Data(path)\r\n print(data.shape)\r\n X, Y = Add_Window_Horizon(data, horizon=2)\r\n print(X.shape, Y.shape)\r\n\r\n\r\n","repo_name":"LeiBAI/AGCRN","sub_path":"lib/add_window.py","file_name":"add_window.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","stars":249,"dataset":"github-code","pt":"40"} +{"seq_id":"41658984513","text":"import socket\nimport threading\n\nimport time\nfrom queue import Queue\n\nimport config\n\nfrom com.talk import recv_cmd, send_cmd, decode_msg, encode_msg\nfrom utils.thread_utils import ThreadValue\nfrom log import GlobalLogger as logger\n\nfrom server.gamer import UnloggedGamer, GamerGroup\nfrom server.handlers import get_handler\nfrom server.account import GamerAccount\nfrom server.game import GameLogic\nfrom server.message import ServerMessage\nfrom server.timer.timer_manager import TimerManager\nfrom vals.state import *\nfrom vals.error import ServerHandlingError, DecodeError\nfrom vals.command import *\n\n\nclass Server:\n def __init__(self):\n\n self.GamerAccount = GamerAccount(config.server.UsrAccountAddr)\n\n # 创建套接字\n self.WelcomeSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # 设置服务器使用固定地址\n self.WelcomeSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n # 绑定端口\n self.WelcomeSocket.bind(('', config.connect.ServerPort))\n\n self.UnloggedGamers = [] # socket已连接,但是逻辑还没有登录的玩家\n self.Gamers = GamerGroup(config.game.MaxGamer) # 已登录的玩家群组\n self.GameRoundPerGamer = config.game.MaxRound # 每一个玩家出题的循环次数\n self.ServerMessage = ServerMessage() # 服务器端发送消息模板类\n self.TimerManager = TimerManager() # 服务器端计时器管理实例,可以方便地创建定时器\n self.GamerCmdListenThreads = [] # 游戏状态消息循环监听的消息接受线程列表\n self.GameLogic = None # 游戏逻辑实体类\n self.CmdQueue = Queue() # 监听消息线程间通信队列\n self.GameBeginFlag = ThreadValue(True) # 指示游戏是否开始的标志\n self.MessageLoopFlag = True # 指示消息循环是否退出的标志\n\n def send_cmd_by_id(self, id_, command, **kwargs):\n gamer = self.Gamers.get_gamer_by_id(id_)\n gamer.send_cmd(command=command, **kwargs)\n\n def send_all_cmd(self, command, **kwargs):\n for g in self.Gamers:\n g.send_cmd(command, **kwargs)\n\n def send_all_cmd_unlogged(self, command, **kwargs):\n for g in self.UnloggedGamers:\n g.send_cmd(command, **kwargs)\n\n def run(self):\n logger.info('Server.run',\n 'Server is running now')\n self.login_state()\n\n # 对所有gamer,启动监听其请求的线程\n for g in self.Gamers:\n t = threading.Thread(target=g.listen_gamer_command, args=(self.CmdQueue,), daemon=True)\n self.GamerCmdListenThreads.append(t)\n\n for t in self.GamerCmdListenThreads:\n t.start()\n\n self.game_state()\n\n def game_state(self):\n logger.debug('server.gamer_state',\n 'entering game state')\n # 初始化游戏逻辑\n self.GameLogic = GameLogic(len(self.Gamers))\n\n for round_index in range(self.GameRoundPerGamer):\n # 游戏循环次数等于玩家数量\n for cur_gamer_index in range(len(self.Gamers)):\n cur_gamer = self.Gamers[cur_gamer_index]\n\n self.GameLogic.init_game_state(cur_gamer.Id)\n self.send_all_cmd(**make_newround_command())\n # 将当前出题者加入到已回答玩家列表中,防止其自己猜自己\n self.GameLogic.add_answered_gamer_id(cur_gamer.Id)\n # 发送开始画图和通告画图者的通知\n paint_message = self.ServerMessage.make_paint_inform_message(cur_gamer.UserName)\n self.send_all_cmd(**make_inform_command(paint_message))\n # 当前画图者发出开始画图指令\n cur_gamer.send_cmd(**make_begin_paint_command())\n\n # 进入指令处理循环\n self.MessageLoopFlag = True\n while self.MessageLoopFlag:\n msg = self.CmdQueue.get() # 阻塞队列,处理接受到的命令\n try:\n cmd, cmd_body = decode_msg(msg, raise_exception=True)\n handler = get_handler(S_GAME_STATE, cmd)\n handler(self,\n cur_gamer=cur_gamer,\n raw_message=msg,\n **cmd_body)\n except DecodeError as de:\n logger.error('server.game_state',\n f'decoding error in game message loop: {de}')\n except Exception as e:\n she = ServerHandlingError(cmd, cmd_body, e)\n logger.error('server.game_state',\n f'unknown error when handling in game state: {she}')\n\n # 关闭游戏\n self.close()\n\n def handle_host_begin_game_cmd(self, host_index=0):\n logger.debug('handle_host_cmd',\n 'host handling threading start!')\n while True:\n if len(self.UnloggedGamers) != 0:\n cmd, body = self.UnloggedGamers[host_index].recv_cmd()\n logger.debug('handle_host_cmd',\n f'cmd: {cmd}, body:{body}')\n handler = get_handler(S_LOGIN_STATE, cmd, supress_log=True)\n handler(self, gamer=self.UnloggedGamers[host_index], **body)\n\n # 该线程如果接收到了主机有关游戏开始的命令后就退出\n if cmd == CMD_BEGIN_GAME:\n return\n else:\n time.sleep(1)\n\n def login_state(self):\n # 欢迎socket监听3秒就开始监听主机命令\n self.WelcomeSocket.settimeout(config.server.ServerAcceptInterval)\n self.WelcomeSocket.listen(100) # todo: 划定最大连接数量\n\n login_threads = []\n # 外层循环接受玩家连接\n while True:\n # 接受玩家连接的套接字\n gamer = self.accept_new_gamer()\n if gamer is None: # accept内部逻辑会判断是否停止接受更多玩家,以None返回\n break\n\n # 每一个连接的套接字都启用一个线程处理登录\n login_thread = threading.Thread(None,\n target=gamer.check_login,\n args=(self,))\n login_thread.start()\n\n # 主机线程处理\n if len(self.UnloggedGamers) == 1:\n # 必须等到主机登录线程结束以后再启动主机的监听线程\n # 同时,主机没有登录成功时,阻塞其他玩家的登录\n login_thread.join()\n host_thread = threading.Thread(None,\n target=self.handle_host_begin_game_cmd,\n args=(0,))\n login_threads.append(host_thread)\n host_thread.start()\n else:\n login_threads.append(login_thread)\n\n # 等待所有玩家登录就绪\n # todo: 玩家登录目前没有超时检查\n for login_thread in login_threads:\n login_thread.join()\n\n # 关闭欢迎socket\n self.WelcomeSocket.close()\n\n def accept_new_gamer(self):\n '''\n 使用欢迎套接字来接受玩家连接,同时监听Host的开始游戏命令来终止\n 接受更多的玩家连接\n :return: 玩家连接的套接字和地址,如果游戏开始则返回None\n '''\n self.WelcomeSocket.settimeout(config.server.HostCommandInterval) # 设置accept退出的检查周期\n while self.GameBeginFlag.get_val():\n try:\n con_socket, addr = self.WelcomeSocket.accept()\n logger.info('Server.login', 'new gamer connecting...')\n gamer = UnloggedGamer(len(self.UnloggedGamers), addr, con_socket)\n # 接受到新玩家以后加入到gamer列表中\n # 由于accept套接字的时候是串行的,因此不需���互斥读写未登录玩家列表\n self.UnloggedGamers.append(gamer)\n return gamer\n # socket超时后检查游戏开始的全局flag是否被修改\n except socket.timeout:\n pass\n return None\n\n def close(self):\n self.send_all_cmd(**make_end_game_command())\n for gamer in self.Gamers:\n gamer.close()\n self.WelcomeSocket.close()\n\n\nif __name__ == '__main__':\n s = Server()\n # p1 = Thread(target=s.run, args=())\n # p1.start()\n # time.sleep(10)\n # print('sending!')\n # s.send_request(0, 'timer', {'id':0})\n #\n # p1.join()\n s.run()\n\n","repo_name":"Asichurter/YouDrawIGuess","sub_path":"server/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":8948,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"42170947999","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass Net(nn.Module):\n\n def __init__(self):\n #I believe that this line of code is just to make it easy to use this class in other classes; no function for my purpose\n super(Net, self).__init__()\n \n # 1 input image channel, 6 output channels, 5x5 square convolution\n # kernel\n #Are these just for when doing image processing?\n #https://pytorch-zh.readthedocs.io/en/latest/nn.html\n self.conv1 = nn.Conv2d(1, 6, 5)\n self.conv2 = nn.Conv2d(6, 16, 5)\n \n # an affine operation: y = Wx + b\n #class torch.nn.Linear(in_features, out_features, bias=True)\n #creates 3 layers\n self.fc1 = nn.Linear(16 * 5 * 5, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 10)\n\n def forward(self, x):\n # Max pooling over a (2, 2) window\n x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))\n # If the size is a square you can only specify a single number\n x = F.max_pool2d(F.relu(self.conv2(x)), 2)\n x = x.view(-1, self.num_flat_features(x))\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n def num_flat_features(self, x):\n size = x.size()[1:] # all dimensions except the batch dimension\n num_features = 1\n for s in size:\n num_features *= s\n return num_features\n\n\nnet = Net()\nprint(net)","repo_name":"medinal2000/tlab","sub_path":"pythonPractice/torch_practice/torch_example_image.py","file_name":"torch_example_image.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"37720582502","text":"'''Crie um programa onde 4 jogadores joguem um dado (1 a6) e tenham resultados\naleatórios. Guarde esses resultados em um dicionário. No final, coloque esse\ndicionário em ordem, sabendo que o vencedor tirou o maior número no dado.\nColocar pausas entre os resultados'''\nfrom random import randint\nfrom time import sleep\njogo = dict()\njogador = list()\nprint('Valores sorteados: ')\nfor i in range(1,5):\n for c in range(1,5):\n num_sort = randint(1, 6)\n jogador.append(jogo.copy())\n print(f'O jogador {i} tirou {num_sort} no dado.')\nprint('Ranking dos jogadores: ')\n# for k, v in jogo.items():\n# print(f'{i}º lugar: jogador {k} com {v}')\n# sleep(1)\n\n# for i in range(1, 5):\n# print(f'{i}º lugar: jogador {jogador} com {num_sort}')\n\n\n","repo_name":"andreagonzalez/Python","sub_path":"ex091.py","file_name":"ex091.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"42177377101","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import api, models, fields, _\nfrom odoo.exceptions import ValidationError, UserError\n\n\nclass LandedCost(models.Model):\n _inherit = 'stock.landed.cost'\n\n analytic_tag_id = fields.Many2one(\n 'account.analytic.tag', string=\"Analytic tag\",\n help=\"Analytic tag associated with the invoice. E.g. DIN1\")\n\n def search_tags(self):\n \n if self.cost_lines:\n raise ValidationError(_(\"The cost lines were already generated.\"))\n\n invoices = self.env['account.move'].search([]).filtered(\n lambda r: self.analytic_tag_id in r.analytic_tag_ids)\n\n if not invoices:\n raise ValidationError(_(\n \"There are no results for this analytic tag.\"))\n\n cost_lines = {}\n for invoice_line in invoices.mapped('invoice_line_ids'):\n if invoice_line.product_id.landed_cost_ok:\n cost_lines.update({\n invoice_line.product_id: cost_lines.get(\n invoice_line.product_id, 0.0) + invoice_line.price_unit,\n })\n\n if not cost_lines:\n raise ValidationError(_(\n \"No landed cost product was found for this analytic tag.\"))\n\n self.write({\n 'cost_lines': [(0, 0, {\n 'product_id': product.id,\n 'name': product.name or '',\n 'split_method': product.split_method_landed_cost or 'equal',\n 'price_unit': price,\n 'account_id': product.property_account_expense_id.id or product.categ_id.property_account_expense_categ_id.id,\n }) for product, price in cost_lines.items()],\n })\n\n\n def get_valuation_lines(self):\n \"\"\"Overwrites the original method to include average in the validation\n of the cost methods.\"\"\"\n lines = []\n\n for move in self.mapped('picking_ids').mapped('move_lines'):\n if move.product_id.valuation != 'real_time' or move.product_id.cost_method not in ['fifo', 'average']:\n continue\n vals = {\n 'product_id': move.product_id.id,\n 'move_id': move.id,\n 'quantity': move.product_qty,\n 'former_cost': move.product_id.standard_price,\n 'weight': move.product_id.weight * move.product_qty,\n 'volume': move.product_id.volume * move.product_qty\n }\n lines.append(vals)\n\n if not lines and self.mapped('picking_ids'):\n raise UserError(_(\n 'The selected picking does not contain any move that would be '\n 'impacted by landed costs. Landed costs are only possible for '\n 'products configured in real time valuation with real price '\n 'costing method. Please make sure it is the case, or you '\n 'selected the correct picking'))\n return lines\n\n\nclass AdjustmentLines(models.Model):\n _inherit = 'stock.valuation.adjustment.lines'\n\n new_cost = fields.Float(\n compute='_compute_new_cost',\n help=\"Former Cost (Per unit) + Additional Landed Cost / Quantity\")\n\n def _compute_new_cost(self):\n \"\"\"Computes the new cost amount\"\"\"\n for record in self:\n record.new_cost = (\n record.final_cost + record.additional_landed_cost\n / record.quantity)\n","repo_name":"thiemed3/Thiemed","sub_path":"stock_landed_costs_tags/models/stock_landed_cost.py","file_name":"stock_landed_cost.py","file_ext":"py","file_size_in_byte":3408,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"23745903230","text":"import logging\nimport os\nimport sys\nimport time\n\nimport aiohttp\nfrom dotenv import load_dotenv\n\nimport bot_main\nfrom modules import admin_commands\nfrom utils import logger\n\ndebug = True\nquiet = False\n\n\nfor arg in sys.argv:\n if arg == '-q':\n print(\"Quiet mode enabled\")\n quiet = True\n\n\n# Start the logging system\nlogger.init(debug, quiet)\nlog = logging.getLogger(__name__)\n\n\n# Get token from .env file\nload_dotenv()\ntoken = os.getenv(\"TOKEN\")\nassert token is not None, \"No token in .env file\"\n\n\nattempts = 5\n\nwhile attempts > 0:\n attempts -= 1\n try:\n # Run the Bot\n log.info(\"Starting bot\")\n bot_main.run_bot(token)\n\n except aiohttp.ClientConnectionError:\n log.info(\"Failed to connect, retrying\")\n time.sleep(5)\n continue\n\n finally:\n # Stop logging queue listener and flush queue\n logger.stop()\n\n # If shutting down because of restart, execute main with the same arguments\n if admin_commands.restart:\n print(\"Restarting...\")\n\n if sys.platform.startswith('linux'):\n argv = [sys.executable, __file__] + sys.argv[1:]\n else:\n argv = [f\"\\\"{sys.executable}\\\"\", f\"\\\"{__file__}\\\"\"] + sys.argv[1:]\n\n try:\n print(f\"Running command: 'os.execv({sys.executable}, {argv})'\")\n os.execv(sys.executable, argv)\n except Exception as e:\n print(e)\n logger.start()\n log.error(f\"Command: 'os.execv({sys.executable}, {argv})' failed.\")\n log.error(e)\n log.fatal(\"Cannot restart. exiting.\")\n logger.stop()\n break\n","repo_name":"Frnot/good-music-bot","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"30677169804","text":"import math\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport yaml\nfrom matplotlib.patches import Ellipse\n\nstats = yaml.safe_load(open(\"stats_QP30_thresh7_segmented_FPN\", \"r\").read())\n\n# color palatte\ncolors = [\n \"#c19277\", # mpeg\n \"#62959c\", # ours\n \"#9dad7f\", # dds\n \"#d9dab0\", # eaar\n \"#a98b98\", # cloudseg\n \"#c1c0b9\", # reducto\n]\n\nname2color = {\n \"mpeg\": \"#c19277\", # mpeg\n \"accmpeg\": \"#62959c\", # ours\n \"dds\": \"#9dad7f\", # dds\n \"eaar\": \"#d9dab0\", # eaar\n \"cloudseg\": \"#a98b98\", # cloudseg\n \"reducto\": \"#c1c0b9\", # reducto\n \"vigil\": \"#8c96c6\",\n}\n\n# set default visualization parameters\nplt.style.use(\"ggplot\")\nplt.rcParams[\"font.size\"] = 30\nplt.rc(\"font\", family=\"sans-serif\")\nplt.rcParams[\"font.weight\"] = \"medium\"\nplt.rcParams[\"pdf.fonttype\"] = 42\n\n\ndef savefig(filename, fig):\n import time\n\n timestr = time.strftime(\"%Y%m%d-%H%M%S\")\n fig.savefig(f\"{filename}.jpg\", bbox_inches=\"tight\")\n\n\ndef get_delay(x):\n\n RTT = 0.1\n\n # grant\n streaming_delay = RTT + x[\"bw\"] * 8 / (0.5 * 1e6) / 180\n\n encoding_delay = 0.131\n if \"reducto\" in x[\"video_name\"]:\n encoding_delay = 0.0435\n\n if \"roi\" in x[\"video_name\"]:\n encoding_delay += 0.08\n\n if \"dds\" in x[\"video_name\"] or \"eaar\" in x[\"video_name\"]:\n # a round trip\n encoding_delay += RTT\n\n if \"dds\" in x[\"video_name\"]:\n encoding_delay += RTT + 0.131\n\n if \"reducto\" in x[\"video_name\"]:\n # reducto logic runs for 25ms\n encoding_delay += 0.247\n\n if \"vigil\" in x[\"video_name\"]:\n # vigil runs for 0.17s cause it operates on lower resolution\n encoding_delay += 0.17\n\n x[\"streaming_delay\"] = streaming_delay\n x[\"encoding_delay\"] = encoding_delay\n x[\"delay\"] = streaming_delay + encoding_delay\n\n\nfor x in stats:\n get_delay(x)\n\nfig, ax = plt.subplots(figsize=(10, 7))\n\nawstream = [i for i in stats if \"dashcamcropped_1_qp_\" in i[\"video_name\"]]\naccmpeg = [i for i in stats if \"roi\" in i[\"video_name\"]]\n\nax.scatter(\n [i[\"delay\"] for i in awstream],\n [i[\"f1\"] for i in awstream],\n label=\"AWStream\",\n c=name2color[\"mpeg\"],\n s=200,\n)\nax.scatter(\n [i[\"delay\"] for i in accmpeg],\n [i[\"f1\"] for i in accmpeg],\n label=\"AccMPEG\",\n c=name2color[\"accmpeg\"],\n s=200,\n)\n\nax.set_xlabel(\"Delay (s)\")\nax.set_ylabel(\"Accuracy\")\nax.set_xlim(left=0)\nax.legend()\n\nsavefig(\"delay-accuracy\", fig)\n","repo_name":"KuntaiDu/AccMPEG","sub_path":"artifact/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"40"} +{"seq_id":"8008400008","text":"import os, subprocess\nimport threading, time\nfrom queue import PriorityQueue\n\n\nn = [x for x in input().split()]\nplaylist_id = os.path.basename(__file__)\nplaylist_id = playlist_id[8:-4]\nfilz = []\nexit_flag = 0\n\n\nif len(n) == 1:\n s = int(n[0])\nelse:\n s = 5\n\ndef initialize():\n global filz\n\n l = 0\n os.chdir(playlist_id)\n if subprocess.run(['dir', '/b', '..*.bat'], shell=True, stderr=subprocess.PIPE,\n stdout=subprocess.io.open(\"manager.txt\", \"w+\")).stderr != b'':\n return 0\n with open('manager.txt', 'r') as f:\n filz = f.readlines()\n\n for l in range(len(filz[0])):\n if filz[0][l] == '-':\n break\n\n FFilz = []\n for fil in filz:\n FFilz.append(fil[2:l])\n filz = FFilz\n\n subprocess.run(['del', 'manager.txt'], shell=True)\n os.chdir('..')\n return 1\n\nclass Scheduler(threading.Thread):\n def __init__(self, q):\n threading.Thread.__init__(self)\n self.q = q\n def run(self):\n download_a_file(self.q)\n\ndef download_a_file(q):\n while not exit_flag:\n queueLock.acquire()\n fil = ''\n bat = 'noting'\n if not q.empty():\n fil = q.get()\n if subprocess.run(['dir', '/b', fil+'*mp4'], shell=True, stderr=subprocess.PIPE).stderr != b'':\n bat = playlist_id + '\\\\..' + fil + '-' + playlist_id + '-' + fil + '.bat'\n queueLock.release()\n time.sleep(.1)\n if bat != 'noting':\n try:\n print('downloading file '+fil)\n subprocess.run([bat])\n except Exception as e:\n print('Something wrong while downloading file '+fil)\n print(e)\n if subprocess.run(['dir', '/b', fil+'*mp4'], shell=True, stderr=subprocess.PIPE).stderr != b'':\n queueLock.acquire()\n q.put(fil)\n queueLock.release()\n\n else:\n queueLock.release()\n time.sleep(.1)\n\n\nif initialize():\n queueLock = threading.Lock()\n downloads_queue = PriorityQueue(len(filz))\n schedulers = []\n\n for i in range(s):\n scheduler = Scheduler(downloads_queue)\n scheduler.start()\n schedulers.append(scheduler)\n\n queueLock.acquire()\n for fil in filz:\n downloads_queue.put(fil)\n queueLock.release()\n\n while not downloads_queue.empty():\n pass\n\n exit_flag = 1\n\n for scheduler in schedulers:\n scheduler.join()\n print('finished')\n","repo_name":"IbrahimGamalSaleh/Projects","sub_path":"Utilities/Youtube Playlists Downloader/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":2518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"13400432229","text":"'''\n将GA算法每一代最优解保存下来的 csv 转为实际的 config配置\n'''\nimport pandas as pd\nimport shutil\nimport random\nfrom sklearn.ensemble import GradientBoostingRegressor\nimport pandas as pd\nimport lightgbm as lgb\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport pickle\nimport joblib\nfrom sklearn.preprocessing import StandardScaler, normalize\n\nname='xgb'\n\ndf = pd.read_csv('./searching_config/'+name+'generationbestConf.csv')\ndf = df.drop('runtime', 1)\nsparkConfRangeDf = pd.read_excel('Spark_conf_range.xlsx')\nsparkConfRangeDf.set_index('SparkConf', inplace=True)\nconfDict = sparkConfRangeDf.to_dict('index')\n\n\n\n\n\ndef formatConf(conf, value):\n res = ''\n # 处理精度\n if confDict[conf]['pre'] == 1:\n res = round(value)\n elif confDict[conf]['pre'] == 0.01:\n res = round(value, 2)\n # 添加单位\n if not pd.isna(confDict[conf]['unit']):\n # 布尔值\n if confDict[conf]['unit'] == 'flag':\n res = str(bool(res)).lower()\n # 列表形式的参数(spark.serializer、spark.io.compression.codec等)\n elif confDict[conf]['unit'] == 'list':\n rangeList = confDict[conf]['Range'].split(' ')\n res = rangeList[res]\n # 拼接上单位\n else:\n res = str(res) + confDict[conf]['unit']\n else:\n res = str(res)\n return res\n\n\n# 遍历csv每一组配置生成一个配置文件\nprint('-----写入配置开始-----')\nfor index, row in df.iterrows():\n # 打开配置文件模板\n fTemp = open('configTemp', 'r')\n # 复制模板,并追加配置\n fNew = open('./config/'+name+'/config' + str(index),'w')\n shutil.copyfileobj(fTemp, fNew, length=1024)\n try:\n for i, item in row.items():\n fNew.write(' ')\n fNew.write(i)\n fNew.write('\\t')\n fNew.write(formatConf(i, item))\n fNew.write('\\n')\n finally:\n fNew.close()\nprint('-----写入配置完成-----')\n","repo_name":"1Katherine/ade","sub_path":"gby/csvToConf.py","file_name":"csvToConf.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"16488474371","text":"\"\"\"\nContains Item class defining an item in the game and add items\nfunction to initialize all items in the game and add them into a dictionary\nto be used by the game class.\n\"\"\"\nfrom utility import *\n\n\nclass Item:\n \"\"\"Class that defines an item in the game.\"\"\"\n def __init__(self, name, description, location, color, x_position,\n y_position):\n \"\"\"Initializes an instance of item class.\"\"\"\n self.name = name\n self.description = description\n self.location = location\n self.color = color\n self.x_position = x_position\n self.y_position = y_position\n self.picked_up = False\n\ndef add_items():\n \"\"\"Returns a dictionary of items necissary for Adventure Game.\"\"\"\n items_list = dict()\n\n # Initialize Hogwarts a History object\n hogwarts_a_history = Item(\"Hogwarts a History\", \"Fantastic book detailing \"\n + \"the history of Hogwarts School of Witchcraft and Wizardry\\n\",\n \"Great Hall\", \"blue\", window_width/25, window_height/2)\n\n items_list[0] = hogwarts_a_history\n\n # Initialize the Sword of Gryffindor\n sword_of_gryffindor = Item(\"Sword of Gryffindor\", \"Powerful sword embedded with \"\n + \"basalisk venom. Presents itself to any worthy Gryffindor\\n\",\n \"Gryffindor Common Room\", \"red\", window_width/25, window_height/2)\n\n items_list[1] = sword_of_gryffindor\n\n # Initialize Basalisk Fang\n basalisk_fang = Item(\"Basalisk Fang\", \"Basalisk fang containing highly toxic \"\n + \"basalisk venom. Can be used to destroy horcruxes\\n\",\n \"Dungeons\", \"white\", window_width/25, window_height/2)\n\n items_list[2] = basalisk_fang\n\n # Initialize Firebolt\n firebolt = Item(\"Firebolt\", \"Firebolt. An international standard broom with \"\n + \"stellar speed and handling.\\n\", \"Main Entrance\",\n \"burlywood4\", window_width*3/4, window_height/2)\n \n items_list[3] = firebolt\n\n # Initialize Hedwig\n hedwig = Item(\"Hedwig\", \"Hedwig. A beautiful snow owl. A wonderful companion \"\n + \"for your dangerous journey.\\n\", \"Hagrid's Hut\", \"white\",\n window_width*3/4, window_height/2)\n\n items_list[4] = hedwig\n\n # Initialize Butterbeer\n butterbeer = Item(\"Butterbeer\", \"Butterbeer. A tasty treat served warm or cold.\\n\",\n \"Upstairs Corridor\", \"yellow\", window_width/2, window_height/2)\n \n items_list[5] = butterbeer\n\n # Initialize invisibility cloak\n invisibility_cloak = Item(\"Invisibility Cloak\", \"Invisibility Cloak. Not a\" \n + \" bad thing to have just in case!\\n\", \"Room of Requirement\", \n \"white\", window_width/2, window_height/2)\n\n items_list[6] = invisibility_cloak\n\n # Initialize wizard chess set\n wizard_chess = Item(\"Wizard Chess\", \"Wizard Chess. A fun, slightly more brutal,\"\n + \" take on normal chess.\\n\", \"Ravenclaw Common Room\", \"gray52\",\n window_width/2, window_height/2)\n\n items_list[7] = wizard_chess\n\n # Returns list of items\n return items_list\n\ndef print_items(current_location, screen, items):\n \"\"\"Adds all items in the current location to the current canvas.\"\"\"\n for i in items:\n if (items[i].location == current_location) and (items[i].picked_up == False):\n\n x1 = items[i].x_position - item_size\n y1 = items[i].y_position - item_size\n\n x2 = items[i].x_position + item_size\n y2 = items[i].y_position + item_size\n\n screen.create_rectangle(x1, y1, x2, y2, fill=items[i].color)","repo_name":"mattmeyerink/Adventure_Game","sub_path":"items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":3474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"14377082454","text":"__all__ = ()\n\nimport json\n\nfrom pysp.solutionioextensions import \\\n (IPySPSolutionSaverExtension,\n IPySPSolutionLoaderExtension)\nfrom pysp.phutils import indexToString\nfrom pyomo.common.plugin import implements, SingletonPlugin\nfrom pysp.util.config import (PySPConfigBlock,\n safe_declare_common_option)\nfrom pysp.util.configured_object import (PySPConfiguredObject,\n PySPConfiguredExtension)\n\ntry:\n from six.moves import zip_longest\nexcept:\n zip_longest = None\n\ndef load_node_solution(tree_node, solution):\n for varname in solution:\n varsol = solution[varname]\n for index, val in varsol:\n if type(index) is list:\n variable_id = \\\n tree_node._name_index_to_id[(varname, tuple(index))]\n else:\n variable_id = tree_node._name_index_to_id[(varname, index)]\n tree_node._solution[variable_id] = val\n\nclass JSONSolutionLoaderExtension(PySPConfiguredExtension,\n PySPConfiguredObject,\n SingletonPlugin):\n\n implements(IPySPSolutionLoaderExtension)\n\n @classmethod\n def _declare_options(cls, options=None):\n if options is None:\n options = PySPConfigBlock()\n\n safe_declare_common_option(options,\n \"input_name\")\n safe_declare_common_option(options,\n \"load_stages\")\n\n return options\n\n _default_options_prefix = \"jsonloader_\"\n\n #\n # Note: Do not try to user super() or access the\n # class name inside the __init__ method when\n # a class derives from a SingletonPlugin. Due to\n # how Pyutilib implements its Singleton type,\n # the __class__ cell will be empty.\n # (See: https://stackoverflow.com/questions/\n # 13126727/how-is-super-in-python-3-implemented)\n #\n def __init__(self):\n PySPConfiguredExtension.__init__(self)\n\n def load(self, manager):\n\n if self.get_option(\"input_name\") is not None:\n stage_solutions = None\n # Do NOT open file in 'binary' mode when loading JSON\n # (produces an error in Python3)\n with open(self.get_option(\"input_name\"), 'r') as f:\n stage_solutions = json.load(f)\n cntr = 0\n if self.get_option('load_stages') > len(manager.scenario_tree.stages):\n raise ValueError(\"The value of the %s option (%s) can not be greater than \"\n \"the number of time stages in the local scenario tree (%s)\"\n % (self.get_full_option_name('load_stages'),\n self.get_option('load_stages'),\n len(manager.scenario_tree.stages)))\n if self.get_option('load_stages') > len(stage_solutions):\n raise ValueError(\"The value of the %s option (%s) can not be greater than \"\n \"the number of time stages in the scenario tree solution \"\n \"stored in %s (%s)\"\n % (self.get_full_option_name('load_stages'),\n self.get_option('load_stages'),\n self.get_option('input_name'),\n len(stage_solutions)))\n for stage, stage_solution in zip_longest(manager.scenario_tree.stages,\n stage_solutions):\n if stage_solution is None:\n break\n if (self.get_option('load_stages') <= 0) or \\\n (cntr+1 <= self.get_option('load_stages')):\n if stage is None:\n raise RuntimeError(\n \"Local scenario tree has fewer stages (%s) than what is \"\n \"held by the solution loaded from file %s. Use the \"\n \"option %s to limit the number of stages that \"\n \"are loaded.\" % (cntr,\n self.get_option('input_name'),\n self.get_full_option_name('load_stages')))\n cntr += 1\n for tree_node in stage.nodes:\n try:\n node_solution = stage_solution[tree_node.name]\n except KeyError:\n raise KeyError(\"Local scenario tree contains a tree node \"\n \"that was not found in the solution at time\"\n \"-stage %s: %s\" % (cntr, tree_node.name))\n load_node_solution(tree_node, node_solution)\n else:\n break\n print(\"Loaded scenario tree solution for %s time stages \"\n \"from file %s\" % (cntr, self.get_option('input_name')))\n return True\n\n print(\"No value was set for %s option 'input_name'. \"\n \"Nothing will be saved.\" % (type(self).__name__))\n return False\n\ndef extract_node_solution(tree_node):\n solution = {}\n for variable_id in tree_node._standard_variable_ids:\n varname, index = tree_node._variable_ids[variable_id]\n # store variable solution data as a list of (index, value)\n # tuples We avoid nesting another dictionary mapping index ->\n # value because (a) its cheaper and more lightweight as a list\n # and (b) because json serializes all dictionary keys as\n # strings (meaning an index of None is not recoverable)\n if varname not in solution:\n solution[varname] = []\n if variable_id in tree_node._solution:\n solution[varname].append((index, tree_node._solution[variable_id]))\n else:\n name, index = tree_node._variable_ids[variable_id]\n full_name = name+indexToString(index)\n print(\"%s: node solution missing for variable with scenario tree \"\n \"id %s (%s)\"\n % (tree_node.name, variable_id, full_name))\n return None\n for varname in list(solution.keys()):\n solution[varname] = sorted(solution[varname], key=lambda x: x[0])\n return solution\n\nclass JSONSolutionSaverExtension(PySPConfiguredExtension,\n PySPConfiguredObject,\n SingletonPlugin):\n\n implements(IPySPSolutionSaverExtension)\n\n @classmethod\n def _declare_options(cls, options=None):\n if options is None:\n options = PySPConfigBlock()\n\n safe_declare_common_option(options,\n \"output_name\")\n safe_declare_common_option(options,\n \"save_stages\")\n\n return options\n\n _default_options_prefix = \"jsonsaver_\"\n\n #\n # Note: Do not try to user super() or access the\n # class name inside the __init__ method when\n # a class derives from a SingletonPlugin. Due to\n # how Pyutilib implements its Singleton type,\n # the __class__ cell will be empty.\n # (See: https://stackoverflow.com/questions/\n # 13126727/how-is-super-in-python-3-implemented)\n #\n def __init__(self):\n PySPConfiguredExtension.__init__(self)\n\n def save(self, manager):\n\n if self.get_option(\"output_name\") is not None:\n stage_solutions = []\n # Do NOT open file in 'binary' mode when dumping JSON\n # (produces an error in Python3)\n with open(self.get_option('output_name'), 'w') as f:\n cntr = 0\n for stage in manager.scenario_tree.stages:\n if (self.get_option('save_stages') <= 0) or \\\n (cntr+1 <= self.get_option('save_stages')):\n cntr += 1\n node_solutions = {}\n for tree_node in stage.nodes:\n _node_solution = extract_node_solution(tree_node)\n if _node_solution is None:\n print(\"No solution appears to be stored in node with \"\n \"name %s. No solution will be saved.\"\n % (tree_node.name))\n return False\n node_solutions[tree_node.name] = _node_solution\n stage_solutions.append(node_solutions)\n else:\n break\n json.dump(stage_solutions, f, indent=2, sort_keys=True)\n print(\"Saved scenario tree solution for %s time stages \"\n \"to file %s\" % (cntr, self.get_option('output_name')))\n return True\n\n print(\"No value was set for %s option 'output_name'. \"\n \"Nothing will be saved.\" % (type(self).__name__))\n return False\n","repo_name":"Pyomo/pysp","sub_path":"pysp/plugins/jsonio.py","file_name":"jsonio.py","file_ext":"py","file_size_in_byte":9161,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"40"} +{"seq_id":"34764285861","text":"import os\n\nfrom ament_index_python.packages import get_package_share_directory\nfrom controller_manager.controller_manager_services import (\n configure_controller,\n list_controllers,\n load_controller,\n switch_controllers,\n unload_controller,\n)\nfrom controller_manager_msgs.msg import ControllerState\nfrom controller_manager_msgs.srv import SwitchController\nfrom python_qt_binding import loadUi\nfrom python_qt_binding.QtCore import QAbstractTableModel, Qt, QTimer\nfrom python_qt_binding.QtGui import QCursor, QFont, QIcon, QStandardItem, QStandardItemModel\nfrom python_qt_binding.QtWidgets import QHeaderView, QMenu, QStyledItemDelegate, QWidget\nfrom qt_gui.plugin import Plugin\nfrom ros2param.api import call_get_parameters, call_list_parameters\nfrom ros2service.api import get_service_names_and_types\n\nfrom .update_combo import update_combo\n\n\nclass ControllerManager(Plugin):\n \"\"\"Graphical frontend for interacting with the controller manager.\"\"\"\n\n _cm_update_freq = 1 # Hz\n\n def __init__(self, context):\n super().__init__(context)\n self.setObjectName(\"ControllerManager\")\n\n # Create QWidget and extend it with all the attributes and children\n # from the UI file\n self._widget = QWidget()\n ui_file = os.path.join(\n get_package_share_directory(\"rqt_controller_manager\"),\n \"resource\",\n \"controller_manager.ui\",\n )\n loadUi(ui_file, self._widget)\n self._widget.setObjectName(\"ControllerManagerUi\")\n\n # Pop-up that displays controller information\n self._popup_widget = QWidget()\n ui_file = os.path.join(\n get_package_share_directory(\"rqt_controller_manager\"), \"resource\", \"controller_info.ui\"\n )\n loadUi(ui_file, self._popup_widget)\n self._popup_widget.setObjectName(\"ControllerInfoUi\")\n\n # Show _widget.windowTitle on left-top of each plugin (when\n # it's set in _widget). This is useful when you open multiple\n # plugins at once. Also if you open multiple instances of your\n # plugin at once, these lines add number to make it easy to\n # tell from pane to pane.\n if context.serial_number() > 1:\n self._widget.setWindowTitle(f\"{self._widget.windowTitle()} {context.serial_number()}\")\n # Add widget to the user interface\n context.add_widget(self._widget)\n\n # Initialize members\n self._cm_name = \"\" # Name of the selected controller manager's node\n self._controllers = [] # State of each controller\n self._table_model = None\n\n # Store reference to node\n self._node = context.node\n\n # Controller state icons\n path = get_package_share_directory(\"rqt_controller_manager\")\n self._icons = {\n \"active\": QIcon(f\"{path}/resource/led_green.png\"),\n \"finalized\": QIcon(f\"{path}/resource/led_off.png\"),\n \"inactive\": QIcon(f\"{path}/resource/led_red.png\"),\n \"unconfigured\": QIcon(f\"{path}/resource/led_off.png\"),\n }\n\n # Controllers display\n table_view = self._widget.table_view\n table_view.setContextMenuPolicy(Qt.CustomContextMenu)\n table_view.customContextMenuRequested.connect(self._on_ctrl_menu)\n\n table_view.doubleClicked.connect(self._on_ctrl_info)\n\n header = table_view.horizontalHeader()\n header.setSectionResizeMode(QHeaderView.ResizeToContents)\n header.setContextMenuPolicy(Qt.CustomContextMenu)\n header.customContextMenuRequested.connect(self._on_header_menu)\n\n # Timer for controller manager updates\n self._update_cm_list_timer = QTimer(self)\n self._update_cm_list_timer.setInterval(int(1000.0 / self._cm_update_freq))\n self._update_cm_list_timer.timeout.connect(self._update_cm_list)\n self._update_cm_list_timer.start()\n\n # Timer for running controller updates\n self._update_ctrl_list_timer = QTimer(self)\n self._update_ctrl_list_timer.setInterval(int(1000.0 / self._cm_update_freq))\n self._update_ctrl_list_timer.timeout.connect(self._update_controllers)\n self._update_ctrl_list_timer.start()\n\n # Signal connections\n w = self._widget\n w.cm_combo.currentIndexChanged[str].connect(self._on_cm_change)\n\n def shutdown_plugin(self):\n self._update_cm_list_timer.stop()\n self._update_ctrl_list_timer.stop()\n self._popup_widget.hide()\n\n def save_settings(self, plugin_settings, instance_settings):\n instance_settings.set_value(\"cm_name\", self._cm_name)\n\n def restore_settings(self, plugin_settings, instance_settings):\n # Restore last session's controller_manager, if present\n self._update_cm_list()\n cm_name = instance_settings.value(\"cm_name\")\n cm_combo = self._widget.cm_combo\n cm_list = [cm_combo.itemText(i) for i in range(cm_combo.count())]\n try:\n idx = cm_list.index(cm_name)\n cm_combo.setCurrentIndex(idx)\n except ValueError:\n pass\n\n def _update_cm_list(self):\n update_combo(self._widget.cm_combo, _list_controller_managers(self._node))\n\n def _on_cm_change(self, cm_name):\n self._cm_name = cm_name\n\n if cm_name:\n self._update_controllers()\n\n def _update_controllers(self):\n if not self._cm_name:\n return\n\n # Find controllers associated to the selected controller manager\n controllers = self._list_controllers()\n\n # Update controller display, if necessary\n if self._controllers != controllers:\n self._controllers = controllers\n self._show_controllers() # NOTE: Model is recomputed from scratch\n\n def _list_controllers(self):\n \"\"\"\n List the controllers associated to a controller manager node.\n\n @return List of controllers associated to a controller manager\n node. Contains both stopped/running controllers, as returned by\n the C{list_controllers} service, plus uninitialized controllers with\n returned by the C{list_parameters} service..\n @rtype [str]\n \"\"\"\n # Add loaded controllers first\n controllers = list_controllers(self._node, self._cm_name).controller\n\n # Append potential controller configs found in the node's parameters\n for name in _get_parameter_controller_names(self._node, self._cm_name):\n add_ctrl = all(name != ctrl.name for ctrl in controllers)\n if add_ctrl:\n type_str = _get_controller_type(self._node, self._cm_name, name)\n uninit_ctrl = ControllerState(name=name, type=type_str)\n controllers.append(uninit_ctrl)\n return controllers\n\n def _show_controllers(self):\n table_view = self._widget.table_view\n self._table_model = ControllerTable(self._controllers, self._icons)\n table_view.setModel(self._table_model)\n\n def _on_ctrl_menu(self, pos):\n # Get data of selected controller\n row = self._widget.table_view.rowAt(pos.y())\n if row < 0:\n return # Cursor is not under a valid item\n\n ctrl = self._controllers[row]\n\n # Show context menu\n menu = QMenu(self._widget.table_view)\n if ctrl.state == \"active\":\n action_deactivate = menu.addAction(self._icons[\"inactive\"], \"Deactivate\")\n action_kill = menu.addAction(self._icons[\"finalized\"], \"Deactivate and Unload\")\n elif ctrl.state == \"inactive\":\n action_activate = menu.addAction(self._icons[\"active\"], \"Activate\")\n action_unload = menu.addAction(self._icons[\"unconfigured\"], \"Unload\")\n elif ctrl.state == \"unconfigured\":\n action_configure = menu.addAction(self._icons[\"inactive\"], \"Configure\")\n action_spawn = menu.addAction(self._icons[\"active\"], \"Configure and Activate\")\n else:\n # Controller isn't loaded\n action_load = menu.addAction(self._icons[\"unconfigured\"], \"Load\")\n action_configure = menu.addAction(self._icons[\"inactive\"], \"Load and Configure\")\n action_activate = menu.addAction(self._icons[\"active\"], \"Load, Configure and Activate\")\n\n action = menu.exec_(self._widget.table_view.mapToGlobal(pos))\n\n # Evaluate user action\n if ctrl.state == \"active\":\n if action is action_deactivate:\n self._deactivate_controller(ctrl.name)\n elif action is action_kill:\n self._deactivate_controller(ctrl.name)\n unload_controller(self._node, self._cm_name, ctrl.name)\n elif ctrl.state in (\"finalized\", \"inactive\"):\n if action is action_activate:\n self._activate_controller(ctrl.name)\n elif action is action_unload:\n unload_controller(self._node, self._cm_name, ctrl.name)\n elif ctrl.state == \"unconfigured\":\n if action is action_configure:\n configure_controller(self._node, self._cm_name, ctrl.name)\n elif action is action_spawn:\n load_controller(self._node, self._cm_name, ctrl.name)\n self._activate_controller(ctrl.name)\n else:\n # Assume controller isn't loaded\n if action is action_load:\n load_controller(self._node, self._cm_name, ctrl.name)\n elif action is action_configure:\n load_controller(self._node, self._cm_name, ctrl.name)\n configure_controller(self._node, self._cm_name, ctrl.name)\n elif action is action_activate:\n load_controller(self._node, self._cm_name, ctrl.name)\n configure_controller(self._node, self._cm_name, ctrl.name)\n self._activate_controller(ctrl.name)\n\n def _on_ctrl_info(self, index):\n popup = self._popup_widget\n\n ctrl = self._controllers[index.row()]\n popup.ctrl_name.setText(ctrl.name)\n popup.ctrl_type.setText(ctrl.type)\n\n res_model = QStandardItemModel()\n model_root = QStandardItem(\"Claimed Interfaces\")\n res_model.appendRow(model_root)\n for claimed_interface in ctrl.claimed_interfaces:\n hw_iface_item = QStandardItem(claimed_interface)\n model_root.appendRow(hw_iface_item)\n\n popup.resource_tree.setModel(res_model)\n popup.resource_tree.setItemDelegate(FontDelegate(popup.resource_tree))\n popup.resource_tree.expandAll()\n popup.move(QCursor.pos())\n popup.show()\n\n def _on_header_menu(self, pos):\n header = self._widget.table_view.horizontalHeader()\n\n # Show context menu\n menu = QMenu(self._widget.table_view)\n action_toggle_auto_resize = menu.addAction(\"Toggle Auto-Resize\")\n action = menu.exec_(header.mapToGlobal(pos))\n\n # Evaluate user action\n if action is action_toggle_auto_resize:\n if header.resizeMode(0) == QHeaderView.ResizeToContents:\n header.setSectionResizeMode(QHeaderView.Interactive)\n else:\n header.setSectionResizeMode(QHeaderView.ResizeToContents)\n\n def _activate_controller(self, name):\n switch_controllers(\n node=self._node,\n controller_manager_name=self._cm_name,\n deactivate_controllers=[],\n activate_controllers=[name],\n strict=SwitchController.Request.STRICT,\n activate_asap=False,\n timeout=0.3,\n )\n\n def _deactivate_controller(self, name):\n switch_controllers(\n node=self._node,\n controller_manager_name=self._cm_name,\n deactivate_controllers=[name],\n activate_controllers=[],\n strict=SwitchController.Request.STRICT,\n activate_asap=False,\n timeout=0.3,\n )\n\n\nclass ControllerTable(QAbstractTableModel):\n \"\"\"\n Model containing controller information for tabular display.\n\n The model allows display of basic read-only information like controller\n name and state.\n \"\"\"\n\n def __init__(self, controller_info, icons, parent=None):\n QAbstractTableModel.__init__(self, parent)\n self._data = controller_info\n self._icons = icons\n\n def rowCount(self, parent):\n return len(self._data)\n\n def columnCount(self, parent):\n return 2\n\n def headerData(self, col, orientation, role):\n if orientation != Qt.Horizontal or role != Qt.DisplayRole:\n return None\n if col == 0:\n return \"controller\"\n elif col == 1:\n return \"state\"\n\n def data(self, index, role):\n if not index.isValid():\n return None\n\n ctrl = self._data[index.row()]\n\n if role == Qt.DisplayRole:\n if index.column() == 0:\n return ctrl.name\n elif index.column() == 1:\n return ctrl.state or \"not loaded\"\n\n if role == Qt.DecorationRole and index.column() == 0:\n return self._icons.get(ctrl.state)\n\n if role == Qt.FontRole and index.column() == 0:\n bf = QFont()\n bf.setBold(True)\n return bf\n\n if role == Qt.TextAlignmentRole and index.column() == 1:\n return Qt.AlignCenter\n\n\nclass FontDelegate(QStyledItemDelegate):\n \"\"\"\n Simple delegate for customizing font weight and italization.\n\n Simple delegate for customizing font weight and italization when displaying resources claimed\n by a controller.\n \"\"\"\n\n def paint(self, painter, option, index):\n if not index.parent().isValid():\n # Root level\n option.font.setWeight(QFont.Bold)\n if index.parent().isValid() and not index.parent().parent().isValid():\n # Hardware interface level\n option.font.setItalic(True)\n option.font.setWeight(QFont.Bold)\n QStyledItemDelegate.paint(self, painter, option, index)\n\n\ndef _get_controller_type(node, node_name, ctrl_name):\n \"\"\"\n Get the controller's type from the controller manager node with the call_get_parameter service.\n\n @param node_name Controller manager node's name\n @type node_name str\n @param ctrl_name Controller name\n @type ctrl_name str\n @return Controller type\n @rtype str\n \"\"\"\n response = call_get_parameters(node=node, node_name=node_name, parameter_names=[ctrl_name])\n return response.values[0].string_value if response.values else \"\"\n\n\ndef _list_controller_managers(node):\n \"\"\"\n List controller manager nodes that are active.\n\n Does this by looking for a service that should be exclusive to a controller manager node.\n The \"list_controllers\" service is used to determine if a node is a controller manager.\n @return List of controller manager node names\n @rtype list of str\n \"\"\"\n return [\n name.rstrip(\"list_controllers\").rstrip(\"/\")\n for name, _ in get_service_names_and_types(node=node)\n if name.endswith(\"list_controllers\")\n ]\n\n\ndef _get_parameter_controller_names(node, node_name):\n \"\"\"Get list of ROS parameter names that potentially represent a controller configuration.\"\"\"\n parameter_names = call_list_parameters(node=node, node_name=node_name)\n suffix = \".type\"\n return [n[: -len(suffix)] for n in parameter_names.result().result.names if n.endswith(suffix)]\n","repo_name":"ros-controls/ros2_control","sub_path":"rqt_controller_manager/rqt_controller_manager/controller_manager.py","file_name":"controller_manager.py","file_ext":"py","file_size_in_byte":15371,"program_lang":"python","lang":"en","doc_type":"code","stars":332,"dataset":"github-code","pt":"40"} +{"seq_id":"25480119483","text":"from enum import Enum\n\nfrom troposphere import Template, Ref, Parameter, ImportValue, Sub, Output, Export\nfrom troposphere.ec2 import SecurityGroup\nfrom troposphere.ecs import Cluster, Service, NetworkConfiguration, AwsvpcConfiguration, \\\n LoadBalancer as EcsLoadBalancer, \\\n TaskDefinition, ContainerDefinition, LogConfiguration, PortMapping\nfrom troposphere.elasticloadbalancingv2 import TargetGroup, LoadBalancer, Listener, Action\nfrom troposphere.logs import LogGroup\n\nfrom sample000.common import output_template_file\nfrom sample000.resource import CommonResource\n\n\nclass ExportName(Enum):\n ALB_SECURITY_GROUP = 'sample-fargate-alb-security-group'\n TASK_SECURITY_GROUP = 'sample-fargate-task-security-group'\n TARGET_GROUP = 'sample-fargate-alb-target-group'\n\n\ndef create_fargate_template():\n __create_security_group()\n\n __create_load_balancer()\n\n __create_ecs()\n\n\ndef __create_security_group():\n template = Template()\n\n alb_security_group = template.add_resource(\n resource=SecurityGroup(\n title='SampleAlbSecurityGroup',\n GroupDescription='sample-fargate',\n SecurityGroupIngress=[\n {\n 'IpProtocol': 'tcp',\n 'ToPort': 80,\n 'FromPort': 80,\n 'CidrIp': '0.0.0.0/0'\n }\n ],\n VpcId=ImportValue(CommonResource.ExportName.VPC_ID.value)\n )\n )\n template.add_output(\n output=Output(\n title=alb_security_group.title,\n Value=Ref(alb_security_group),\n Export=Export(name=ExportName.ALB_SECURITY_GROUP.value)\n )\n )\n\n task_security_group = template.add_resource(\n resource=SecurityGroup(\n title='SampleTaskSecurityGroup',\n GroupDescription='sample-fargate',\n SecurityGroupIngress=[\n {\n 'IpProtocol': 'tcp',\n 'ToPort': 80,\n 'FromPort': 80,\n 'CidrIp': '0.0.0.0/0'\n },\n ],\n VpcId=ImportValue(CommonResource.ExportName.VPC_ID.value)\n )\n )\n template.add_output(\n output=Output(\n title=task_security_group.title,\n Value=Ref(task_security_group),\n Export=Export(name=ExportName.TASK_SECURITY_GROUP.value)\n )\n )\n\n output_template_file(template, 'sg.yml')\n\n return alb_security_group, task_security_group\n\n\ndef __create_load_balancer():\n template = Template()\n load_balancer = template.add_resource(\n resource=LoadBalancer(\n title='SampleFargateLoadBalancer',\n Name='sample-fargate-load-balancer',\n Subnets=[\n ImportValue(CommonResource.ExportName.PUBLIC_SUBNET_A_ID.value),\n ImportValue(CommonResource.ExportName.PUBLIC_SUBNET_B_ID.value)\n ],\n SecurityGroups=[\n ImportValue(ExportName.ALB_SECURITY_GROUP.value)\n ],\n Scheme='internet-facing'\n )\n )\n\n target_group = template.add_resource(\n resource=TargetGroup(\n title='SampleFargateTargetGroup',\n Port=80,\n Protocol='HTTP',\n TargetType='ip',\n VpcId=ImportValue(CommonResource.ExportName.VPC_ID.value)\n )\n )\n template.add_output(\n output=Output(\n title=target_group.title,\n Value=Ref(target_group),\n Export=Export(name=ExportName.TARGET_GROUP.value)\n )\n )\n\n template.add_resource(\n resource=Listener(\n title='SampleFargateListener',\n DefaultActions=[\n Action(\n Type='forward',\n TargetGroupArn=Ref(target_group)\n )\n ],\n LoadBalancerArn=Ref(load_balancer),\n Port=80,\n Protocol='HTTP'\n )\n )\n\n output_template_file(template, 'alb.yml')\n\n return target_group\n\n\ndef __create_ecs():\n template = Template()\n\n desired_count = template.add_parameter(\n parameter=Parameter(\n title='DesiredCount',\n Default=1,\n Type='Number'\n )\n )\n\n cpu = template.add_parameter(\n parameter=Parameter(\n title='Cpu',\n Default=256,\n Type='Number'\n )\n )\n\n memory = template.add_parameter(\n parameter=Parameter(\n title='Memory',\n Default=512,\n Type='Number'\n )\n )\n\n cluster = template.add_resource(\n resource=Cluster(\n title='SampleCluster',\n )\n )\n\n log_group = template.add_resource(\n resource=LogGroup(\n title='SampleLogGroup',\n LogGroupName='/aws/ecs/sample'\n )\n )\n\n container_name = 'sample-nginx'\n\n task_definition = template.add_resource(\n resource=TaskDefinition(\n title='SampleTaskDefinition',\n Cpu=Ref(cpu),\n Family='sample-fargate-task',\n RequiresCompatibilities=['FARGATE'],\n Memory=Ref(memory),\n NetworkMode='awsvpc',\n ExecutionRoleArn=Sub('arn:aws:iam::${AWS::AccountId}:role/ecsTaskExecutionRole'),\n ContainerDefinitions=[\n ContainerDefinition(\n Image='nginx:latest',\n Name=container_name,\n PortMappings=[\n PortMapping(\n ContainerPort=80,\n HostPort=80,\n Protocol='tcp'\n )\n ],\n LogConfiguration=LogConfiguration(\n LogDriver='awslogs',\n Options={\n 'awslogs-region': Ref('AWS::Region'),\n 'awslogs-group': Ref(log_group),\n 'awslogs-stream-prefix': 'nginx'\n }\n )\n )\n ]\n )\n )\n\n template.add_resource(\n resource=Service(\n title='SampleService',\n ServiceName='sample-fargate',\n Cluster=Ref(cluster),\n DesiredCount=Ref(desired_count),\n TaskDefinition=Ref(task_definition),\n LaunchType='FARGATE',\n NetworkConfiguration=NetworkConfiguration(\n AwsvpcConfiguration=AwsvpcConfiguration(\n AssignPublicIp='ENABLED',\n SecurityGroups=[\n ImportValue(ExportName.TASK_SECURITY_GROUP.value)\n ],\n Subnets=[\n ImportValue(CommonResource.ExportName.PUBLIC_SUBNET_A_ID.value),\n ImportValue(CommonResource.ExportName.PUBLIC_SUBNET_B_ID.value),\n ]\n )\n ),\n LoadBalancers=[\n EcsLoadBalancer(\n ContainerName=container_name,\n ContainerPort=80,\n TargetGroupArn=ImportValue(ExportName.TARGET_GROUP.value)\n )\n ]\n )\n )\n output_template_file(template, 'ecs.yml')\n\n\nif __name__ == '__main__':\n create_fargate_template()\n","repo_name":"suzuxander/samples","sub_path":"python/python-016/ecs.py","file_name":"ecs.py","file_ext":"py","file_size_in_byte":7320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"11868808164","text":"import webapp2\n\nfrom google.appengine.api import memcache\n\nfrom appstats_logger.middleware import stats_logger_wsgi_middleware\n\n\nclass HelloHandler(webapp2.RequestHandler):\n \"\"\"Make some RPCs so we can check the profiling data.\"\"\"\n def get(self):\n self.test_memcache()\n self.test_memcache()\n\n memcache.set_multi({'key': 'value', 'other': 'value'})\n memcache.get_multi(['key', 'other', 'thing'])\n\n self.response.out.write('Hello world')\n\n def test_memcache(self):\n memcache.set('key', 'value')\n memcache.get('key')\n\n\napp = webapp2.WSGIApplication([\n ('/', HelloHandler),\n])\n\napp = stats_logger_wsgi_middleware(app)\n\n\n","repo_name":"robertkluin/appstats-logger","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"5860061014","text":"## 37. Sudoku Solver\n## https://leetcode.com/problems/sudoku-solver/\n\nclass Solution:\n def solveSudoku(self, board: List[List[str]]) -> None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n \"\"\"\n sudicti = {i:set([\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"]) for i in range(9)}\n sudictj = {j:set([\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"]) for j in range(9)}\n sudictk = {k:set([\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"]) for k in range(9)}\n options = {}\n # optioni = {}\n # optionj = {}\n # optionk = {}\n for i,row in enumerate(board):\n for j,row_col in enumerate(row):\n k = 3*(i//3)+(j//3)\n if row_col==\".\":\n options.update({(i,j,k):set()})\n # optioni[i] = {}\n # optionj[j] = {}\n # optionk[k] = {}\n else:\n sudicti[i].discard(row_col)\n sudictj[j].discard(row_col)\n sudictk[k].discard(row_col)\n \n # dissolve = set()\n for i,j,k in options:\n options[(i,j,k)] = sudicti[i]&sudictj[j]&sudictk[k]\n # optioni[i].update({(j,k):1})\n # optionj[j].update({(i,k):1})\n # optionk[k].update({(i,j):1})\n # if len(options[(i,j,k)])==1:\n # dissolve.add((i,j,k))\n \n # while dissolve:\n # i,j,k = dissolve.pop()\n # board[i][j] = options.pop((i,j,k)).pop()\n # sudicti[i].discard(board[i][j])\n # sudicti[j].discard(board[i][j])\n # sudicti[k].discard(board[i][j])\n # # options.pop((i,j,k))\n # optioni[i].pop((j,k))\n # optionj[j].pop((i,k))\n # optionk[k].pop((i,j))\n # if not(optioni[i]):\n # optioni.pop(i)\n # else:\n # for nj,nk in optioni[i]:\n # options[(i,nj,nk)].discard(board[i][j])\n # if len(options[(i,nj,nk)])==1:\n # dissolve.add((i,nj,nk))\n # if not(optionj[j]):\n # optionj.pop(j)\n # else:\n # for ni,nk in optionj[j]:\n # options[(ni,j,nk)].discard(board[i][j])\n # if len(options[(ni,j,nk)])==1:\n # dissolve.add((ni,j,nk))\n # if not(optionk[k]):\n # optionk.pop(k)\n # else:\n # for ni,nj in optionk[k]:\n # options[(ni,nj,k)].discard(board[i][j])\n # if len(options[(ni,nj,k)])==1:\n # dissolve.add((ni,nj,k))\n \n # for i in range(9):\n # eli = sudicti[i]\n # if len(eli)==0:\n # sudicti.pop(i)\n # else:\n # print(f\"{len(eli)}:row={i}:{eli}\")\n # for j in range(9):\n # elj = sudictj[j]\n # if len(elj)==0:\n # sudictj.pop(j)\n # else:\n # print(f\"{len(elj)}:col={j}:{elj}\")\n # for k in range(9):\n # elk = sudictk[k]\n # if len(elk)==0:\n # sudictk.pop(k)\n # else:\n # print(f\"{len(elk)}:grd={k}:{elk}\")\n \n # print(len(options))\n self.sudo_koo(board, options, sudicti, sudictj, sudictk)\n # print(len(options))\n \n def sudo_koo(self, board, options, sudicti, sudictj, sudictk):\n if len(options)==0:\n return True\n (i,j,k),ion = options.popitem()\n \n for elem in ion:\n if (elem in sudicti[i]&sudictj[j]&sudictk[k]):\n sudicti[i].remove(elem)\n sudictj[j].remove(elem)\n sudictk[k].remove(elem)\n if self.sudo_koo(board, options, sudicti, sudictj, sudictk):\n board[i][j] = elem\n return True\n else:\n sudicti[i].add(elem)\n sudictj[j].add(elem)\n sudictk[k].add(elem)\n else:\n continue\n options[(i,j,k)] = ion\n return False\n ","repo_name":"sayanbasak0/letscode","sub_path":"python3/p37_hard.py","file_name":"p37_hard.py","file_ext":"py","file_size_in_byte":4197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"18537180910","text":"from django.urls import path, include\n\nfrom . import views\n\napp_name = 'accounts'\n\nurlpatterns = [\n path('login', views.LoginView.as_view(), name='login'),\n path('register', views.RegisterView.as_view(), name='register'),\n path('logout', views.LogoutView.as_view(), name='logout'),\n path('users/', include([\n \n path('instructor', views.InstructorView.as_view(),name='instructor-course'),\n path('instructor/addcourse',views.CreateCourseView.as_view(), name='add-course'),\n path('instructor/yourcourses',views.YourCourseView.as_view(),name='your-courses'),\n path('instructor/addlessons',views.AddLessonView.as_view(), name='add-lesson'),\n\n path('my-courses', views.EnrolledCoursesListView.as_view(), name='enrolled-courses'),\n path('my-courses//view', views.StartLessonView.as_view(), name='course-lessons'),\n path('my-courses//lessons/', views.LessonView.as_view(), name='course-lessons-single'),\n path('profile', views.ProfileUpdateView.as_view(), name='my-profile'),\n \n ])),\n]\n","repo_name":"Mahak-Bhansali/EduFlix_Project","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"69846553720","text":"from src.AF.AF import AF\nfrom src.AF.Estado import Estado\n\n\ndef uniao_automatos(af1: AF, af2: AF) -> AF:\n \"\"\"\n Faz a união de dois autômatos por &-transiçõa\n :param af1: AF1 a ser unido\n :param af2: AF2 a ser unido\n :return: AF resultante a união dos autômatos af1 e af2\n \"\"\"\n\n # por conveniência na hora de apresentar resultados e debuggar,\n # vamos trocar os nomes dos estados do segundo AF\n af2.change_estados_nomes()\n\n af_new: AF = AF()\n af_new.qtd_estados = af1.qtd_estados + af2.qtd_estados + 1\n af_new.estados = af1.estados + af2.estados\n af_new.estados_finais = af1.estados_finais + af2.estados_finais\n\n for letra in af1.alfabeto + af2.alfabeto:\n if letra not in af_new.alfabeto:\n af_new.alfabeto.append(letra)\n\n af_new.is_deterministico = False\n\n # caso não tenha & no alfabeto, adicionar\n if \"&\" not in af_new.alfabeto:\n af_new.alfabeto.append(\"&\")\n\n # para fazer a união entre dois estados, é necessário\n # fazer um novo estado e fazer união por epsilon-transição\n # para seus antigos estados iniciais\n estado_new: Estado = Estado(\"EstadoUniao\")\n estado_new.add_transicao(\"&\", af1.estado_inicial)\n estado_new.add_transicao(\"&\", af2.estado_inicial)\n af_new.estado_inicial = estado_new\n af_new.estado_now = af_new.estado_inicial\n af_new.estados.append(estado_new)\n\n return af_new\n","repo_name":"AnthonyKamers/lexical-syntax-parser","sub_path":"src/Utils/utilsAF.py","file_name":"utilsAF.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"41633862686","text":"from typing import List, Optional\n\nfrom fastapi import APIRouter, Body, Depends\n\nfrom watchmen_auth import PrincipalService\nfrom watchmen_data_kernel.cache import CacheService\nfrom watchmen_meta.common import ask_meta_storage, ask_snowflake_generator\nfrom watchmen_meta.system import DataSourceService\nfrom watchmen_model.admin import UserRole\nfrom watchmen_model.common import DataPage, DataSourceId, Pageable\nfrom watchmen_model.system import DataSource\nfrom watchmen_rest import get_any_admin_principal, get_super_admin_principal\nfrom watchmen_rest.util import raise_400, raise_403, raise_404\nfrom watchmen_rest_doll.doll import ask_hide_datasource_pwd_enabled, ask_tuple_delete_enabled\nfrom watchmen_rest_doll.util import trans, trans_readonly\nfrom watchmen_utilities import ArrayHelper, is_blank, is_empty\nfrom .utils import attach_tenant_name\n\nrouter = APIRouter()\n\n\ndef get_data_source_service(principal_service: PrincipalService) -> DataSourceService:\n\treturn DataSourceService(ask_meta_storage(), ask_snowflake_generator(), principal_service)\n\n\ndef clear_pwd(data_source: DataSource):\n\tif ask_hide_datasource_pwd_enabled():\n\t\tdata_source.password = None\n\n\n@router.get('/datasource', tags=[UserRole.ADMIN, UserRole.SUPER_ADMIN], response_model=DataSource)\nasync def load_data_source_by_id(\n\t\tdata_source_id: Optional[DataSourceId] = None,\n\t\tprincipal_service: PrincipalService = Depends(get_any_admin_principal)\n) -> DataSource:\n\tif is_blank(data_source_id):\n\t\traise_400('Data source id is required.')\n\tif not principal_service.is_super_admin():\n\t\tif data_source_id != principal_service.get_tenant_id():\n\t\t\traise_403()\n\n\tdata_source_service = get_data_source_service(principal_service)\n\n\tdef action() -> DataSource:\n\t\t# noinspection PyTypeChecker\n\t\tdata_source: DataSource = data_source_service.find_by_id(data_source_id)\n\t\tif data_source is None:\n\t\t\traise_404()\n\t\tclear_pwd(data_source)\n\t\treturn data_source\n\n\treturn trans_readonly(data_source_service, action)\n\n\n@router.post('/datasource', tags=[UserRole.SUPER_ADMIN], response_model=DataSource)\nasync def save_data_source(\n\t\tdata_source: DataSource, principal_service: PrincipalService = Depends(get_super_admin_principal)\n) -> DataSource:\n\tdata_source_service = get_data_source_service(principal_service)\n\n\t# noinspection DuplicatedCode\n\tdef action(a_data_source: DataSource) -> DataSource:\n\t\tif data_source_service.is_storable_id_faked(a_data_source.dataSourceId):\n\t\t\tdata_source_service.redress_storable_id(a_data_source)\n\t\t\t# noinspection PyTypeChecker\n\t\t\ta_data_source: DataSource = data_source_service.create(a_data_source)\n\t\telse:\n\t\t\t# if hide pwd enabled and requested pwd is empty, copy from existing\n\t\t\tif is_empty(a_data_source.password) and ask_hide_datasource_pwd_enabled():\n\t\t\t\texisting_data_source: Optional[DataSource] = data_source_service.find_by_id(a_data_source.dataSourceId)\n\t\t\t\tif existing_data_source is not None:\n\t\t\t\t\ta_data_source.password = existing_data_source.password\n\t\t\t# noinspection PyTypeChecker\n\t\t\ta_data_source: DataSource = data_source_service.update(a_data_source)\n\t\tCacheService.data_source().put(a_data_source)\n\t\treturn a_data_source\n\n\treturn trans(data_source_service, lambda: action(data_source))\n\n\nclass QueryDataSourceDataPage(DataPage):\n\tdata: List[DataSource]\n\n\n@router.post('/datasource/name', tags=[UserRole.ADMIN, UserRole.SUPER_ADMIN], response_model=QueryDataSourceDataPage)\nasync def find_data_sources_by_name(\n\t\tquery_name: Optional[str] = None, pageable: Pageable = Body(...),\n\t\tprincipal_service: PrincipalService = Depends(get_any_admin_principal)\n) -> QueryDataSourceDataPage:\n\tdata_source_service = get_data_source_service(principal_service)\n\n\t# noinspection DuplicatedCode\n\tdef action() -> QueryDataSourceDataPage:\n\t\ttenant_id = None\n\t\tif principal_service.is_tenant_admin():\n\t\t\ttenant_id = principal_service.get_tenant_id()\n\t\tif is_blank(query_name):\n\t\t\t# noinspection PyTypeChecker\n\t\t\treturn data_source_service.find_by_text(None, tenant_id, pageable)\n\t\telse:\n\t\t\t# noinspection PyTypeChecker\n\t\t\treturn data_source_service.find_by_text(query_name, tenant_id, pageable)\n\n\tpage = trans_readonly(data_source_service, action)\n\tpage.data = attach_tenant_name(page.data, principal_service)\n\tpage.data = ArrayHelper(page.data).each(clear_pwd).to_list()\n\treturn page\n\n\n@router.get('/datasource/all', tags=[UserRole.ADMIN], response_model=List[DataSource])\nasync def find_all_data_sources(\n\t\tprincipal_service: PrincipalService = Depends(get_any_admin_principal)) -> List[DataSource]:\n\tdata_source_service = get_data_source_service(principal_service)\n\n\tdef action() -> List[DataSource]:\n\t\ttenant_id = None\n\t\tif principal_service.is_tenant_admin():\n\t\t\ttenant_id = principal_service.get_tenant_id()\n\t\treturn data_source_service.find_all(tenant_id)\n\n\tdata_source_list = attach_tenant_name(trans_readonly(data_source_service, action), principal_service)\n\treturn ArrayHelper(data_source_list).each(clear_pwd).to_list()\n\n\n@router.delete('/datasource', tags=[UserRole.SUPER_ADMIN], response_model=DataSource)\nasync def delete_data_source_by_id_by_super_admin(\n\t\tdata_source_id: Optional[DataSourceId] = None,\n\t\tprincipal_service: PrincipalService = Depends(get_super_admin_principal)\n) -> DataSource:\n\tif not ask_tuple_delete_enabled():\n\t\traise_404('Not Found')\n\n\tif is_blank(data_source_id):\n\t\traise_400('Data source id is required.')\n\n\tdata_source_service = get_data_source_service(principal_service)\n\n\tdef action() -> DataSource:\n\t\t# noinspection PyTypeChecker\n\t\tdata_source: DataSource = data_source_service.delete(data_source_id)\n\t\tif data_source is None:\n\t\t\traise_404()\n\t\tCacheService.data_source().remove(data_source_id)\n\t\treturn data_source\n\n\treturn trans(data_source_service, action)\n","repo_name":"Indexical-Metrics-Measure-Advisory/watchmen","sub_path":"packages/watchmen-rest-doll/src/watchmen_rest_doll/system/data_source_router.py","file_name":"data_source_router.py","file_ext":"py","file_size_in_byte":5697,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"40"} +{"seq_id":"37850356168","text":"from os.path import isdir\n\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand, CommandError\nfrom optparse import make_option\nfrom os.path import abspath\n\nfrom storage.archiver import VideoArchiver, ImageArchiver, Archiver\n\nfrom logger import init_logging\nlogger = init_logging(__name__)\n\n\n\nclass Command(BaseCommand):\n args = ''\n help = 'Archive the supplied directory tree'\n\n def add_arguments(self, parser):\n parser.add_argument('--debug',\n action='store_true',\n dest='debug',\n default=False,\n help='Load pdb and halt on startup'),\n parser.add_argument('--break-on-add',\n action='store_true',\n dest='break_on_add',\n default=False,\n help='Load pdb and halt before adding files'),\n parser.add_argument('--images',\n action='store_true',\n dest='images',\n default=False,\n help=\"Archive images\"),\n parser.add_argument('--videos',\n action='store_true',\n dest='videos',\n default=False,\n help=\"Archive videos\"),\n parser.add_argument('--media',\n action='store_true',\n dest='media',\n default=False,\n help=\"Archive media (images & video)\"),\n parser.add_argument('--files',\n action='store_true',\n dest='allfiles',\n default=False,\n help=\"Archive all files - being implemented\"),\n parser.add_argument('srcdir',\n help=\"Archive source directory\")\n parser.add_argument('dstdir', nargs='?',\n help=\"Archive source directory\")\n\n def handle(self, *args, **options):\n\n logger.info(\"Archive starting\")\n if options['debug']:\n import pdb\n pdb.set_trace()\n\n logger.info(\"Archiving: {0}\".format(abspath(options['srcdir'])))\n\n if not isdir(options['srcdir']):\n msg = \"Supplied path is not a directory: {0}\".format(options['srcdir'])\n logger.fatal(msg)\n raise CommandError(msg)\n\n if options['images'] or options['media']:\n dest = settings.IMAGES_ARCHIVE\n archiver = ImageArchiver(options['srcdir'], dest, break_on_add=options['break_on_add'])\n archiver.archive()\n\n if options['videos'] or options['media']:\n dest = settings.IMAGES_ARCHIVE\n archiver = VideoArchiver(options['srcdir'], dest, break_on_add=options['break_on_add'])\n archiver.archive()\n\n if options['allfiles']:\n import pdb; pdb.set_trace()\n dest = options['dstdir']\n archiver = FileArchiver(args[0], dest, break_on_add=options['break_on_add'])\n archiver.archive()\n\n logger.info(\"Archive finished\")\n\n return\n","repo_name":"akgrant43/storagemgr","sub_path":"storagemgr/storage/management/commands/archive.py","file_name":"archive.py","file_ext":"py","file_size_in_byte":2858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"32284339895","text":"from itertools import combinations\nimport sys\n\ninput =sys.stdin.readline\n\ndef dfs(now,next,cnt):\n if visited[now][next]=total:\n MIN=total\n answer.append([a,b,total])\n\nn,m = map(int,input().split())\ngraph= [[] for _ in range(n+1)]\nanswer=[]\nINF=int(1e9)\nvisited=[[INF]*(n+1) for _ in range(n+1)]\nfor i in range(m):\n a,b= map(int,input().split())\n graph[a].append(b)\n graph[b].append(a)\n\nfor i in range(n+1):\n visited[i][i]=0\n\nfor i in range(1,n+1):\n for j in graph[i]:\n dfs(i,j,1)\n\ncomb = combinations(range(1,n+1),2)\nMIN=int(1e9)\nfor a,b in list(comb):\n score(a,b,MIN)\nanswer.sort(key = lambda x:(x[2],x[0],x[1]))\nprint(answer[0][0],answer[0][1],answer[0][2])","repo_name":"kimth007kim/python_algorithm","sub_path":"코테스터디/2022/0424/21278 호석이 두마리 치킨.py","file_name":"21278 호석이 두마리 치킨.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"7503191026","text":"from yaml import load, dump, Loader\nimport os\nfrom logger import logger\n\nclass Config(object):\n def __init__(self, config_path):\n self.config_path = config_path\n self.config = self.load_config()\n \n @logger.catch\n def load_config(self):\n # check if config file exists\n if not os.path.exists(self.config_path):\n raise FileNotFoundError('Config file not found')\n # check extension\n if not self.config_path.endswith('.yaml'):\n raise ValueError('Config file must be a yaml file')\n with open(self.config_path, 'r') as f:\n return load(f, Loader=Loader)\n \n @logger.catch\n def __getitem__(self, key):\n if key in self.config:\n return self.config[key]\n elif '.' in key:\n keys = key.split('.')\n value = self.config\n for k in keys:\n if k in value:\n value = value[k]\n else:\n raise KeyError(f'Key {k} not found in config')\n return value\n","repo_name":"TankNee/ncgm-tsr","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"71364905720","text":"from flask import Flask, render_template, request, redirect, url_for,flash, session\nfrom flask_behind_proxy import FlaskBehindProxy\nfrom app.models import User,db, CommentEvent, Reply, Attendance\nfrom app.forms import LoginForm, RegistrationForm, CommentForm\nfrom flask_sqlalchemy import SQLAlchemy\nfrom app.ticketmaster_api import search_events, suggest_events, get_event_details\nfrom datetime import datetime\nimg = {'d': '/img/dog.jpg', 'c': '/img/cat.jpg','s': '/img/sunset.jpg'}\ndef home():\n return render_template('index.html', entry=True)\ndef err():\n return render_template('err.html',subtitle='Oh no!', text='The username and/or password entered is not correct. Please try again or sign up.',entry=True)\ndef login():\n form = LoginForm()\n if form.validate_on_submit(): # checks if entries are valid\n user=User.query.filter_by(user_name=form.username.data).first()\n if user:\n session['user_name'] = form.username.data\n return redirect(url_for('event_landing'))\n else:\n return redirect(url_for('err'))\n return render_template('login.html', title='Log In', form=form, entry=True)\n##@app.route('/logout')\n\ndef logout():\n session.pop('username', None)\n return redirect(url_for('home'))\n\ndef signup():\n form = RegistrationForm()\n if form.validate_on_submit(): # checks if entries are valid\n user = User(name=form.name.data,user_name=form.username.data,email=form.email.data,password=form.password.data,pronouns=form.pronouns.data, avatar=img[form.avatar.data])\n session['user_name'] = form.username.data\n db.session.add(user)\n db.session.commit()\n return redirect(url_for('event_landing'))\n return render_template('signup.html', title='Sign Up', form=form, entry=True)\n\ndef event_landing():\n events = suggest_events()\n user = User.query.filter_by(user_name=session['user_name']).first()\n your_events = get_user_event(user.user_name)\n return render_template('event_landing.html', your_events=your_events, suggested_events=events, user=user, entry=False)\n\ndef profile():\n user_name = request.form.get('user_name')\n prof_user = User.query.filter_by(user_name=user_name).first()\n curr_user = User.query.filter_by(user_name=session['user_name']).first()\n upcoming_events = get_user_event(prof_user.user_name)\n return render_template('profile.html', upcoming_events=upcoming_events, prof_user=prof_user, user=curr_user)\n\n\n\ndef search():\n search_query = request.form.get('search')\n user = User.query.filter_by(user_name=session['user_name']).first()\n if search_query:\n search_results = search_events(search_query)\n if len(search_results) > 0:\n return render_template(\n 'search_result.html', search_results=search_results, user=user\n )\n return render_template('search_result.html', search_results=None, user=user, entry=False)\n\ndef add_comment():\n user_name = session.get('user_name')\n comment = request.form.get('user_comment')\n event_id = request.form.get('event_id')\n event_details = get_event_details(event_id)\n current_time = datetime.now()\n user = User.query.filter_by(user_name=session['user_name']).first()\n comment = CommentEvent(event_id=event_id, user_name=user_name, comment=comment, timestamp=current_time)\n db.session.add(comment)\n db.session.commit()\n form = CommentForm()\n in_db = bool(Attendance.query.filter_by(user_name=user_name).first())\n attendees = Attendance.query.filter_by(event_id=event_id).all()\n event_comments = CommentEvent.query.filter_by(event_id=event_id).all()\n return render_template(\n 'event_comments.html',event_details=event_details,\n event_comments=event_comments,attendees=attendees,\n form=form, in_db=in_db, user=user, entry=False\n )\n\ndef add_reply():\n user_name = session.get('user_name')\n reply = request.form.get('reply')\n event_id = request.form.get('event_id')\n event_details = get_event_details(event_id)\n user = User.query.filter_by(user_name=session['user_name']).first()\n comment_id = request.form.get('comment_id')\n comment = CommentEvent.query.filter_by(id=comment_id).first()\n #how are we getting comment id\n in_db = bool(Attendance.query.filter_by(user_name=user_name).first())\n reply = Reply(comment_id=comment_id,event_id=event_id, user_name=user_name, reply=reply)\n db.session.add(reply)\n db.session.commit()\n form = CommentForm()\n attendees = Attendance.query.filter_by(event_id=event_id).all()\n comment_replies = Reply.query.filter_by(comment_id=comment_id).all()\n return render_template(\n 'event_replies.html', event_details=event_details, comment=comment, comment_id=comment_id,\n replies=comment_replies,user=user,attendees=attendees,\n form=form, in_db=in_db, entry=False\n )\ndef event_comments():\n user_name = session.get('user_name')\n event_id = request.form.get('event_id')\n user = User.query.filter_by(user_name=session['user_name']).first()\n event_details = get_event_details(event_id) #gets event object\n #query the comments database for comments with that event id\n event_comments = CommentEvent.query.filter_by(event_id=event_id).all()\n form = CommentForm()\n attendees = Attendance.query.filter_by(event_id=event_id).all()\n in_db = bool(Attendance.query.filter_by(event_id=event_id, user_name=user_name).first())\n return render_template('event_comments.html', event_details=event_details,\n event_comments=event_comments,attendees=attendees,form=form, user=user,in_db=in_db, entry=False)\n\ndef event_replies():\n user_name = session.get('user_name')\n event_id = request.form.get('event_id')\n user = User.query.filter_by(user_name=session['user_name']).first()\n comment_id = request.form.get('comment_id')\n comment = CommentEvent.query.filter_by(id=comment_id).first()\n event_details = get_event_details(event_id)\n #query database for replies with that comment id\n attendees = Attendance.query.filter_by(event_id=event_id).all()\n comment_replies = Reply.query.filter_by(comment_id=comment_id).all()\n in_db = bool(Attendance.query.filter_by(event_id=event_id, user_name=user_name).first()) \n form = CommentForm()\n return render_template('event_replies.html', event_details=event_details,comment=comment,comment_id=comment_id,attendees=attendees,\n replies=comment_replies, form=form, in_db=in_db, user=user,entry=False)\n\ndef add_attendee():\n \"\"\"\n Adds user to Attendance\n \"\"\"\n user_name = session.get('user_name')\n event_id = request.form.get('event_id')\n if user_name:\n already_attending = Attendance.query.filter_by(event_id=event_id, user_name=user_name).first()\n if not already_attending:\n attendee = Attendance(event_id=event_id, user_name=user_name)\n db.session.add(attendee)\n db.session.commit()\n return redirect(url_for('event_landing'))\n\ndef remove_attendee():\n \"\"\"\n Removes a attendee from table\n \"\"\"\n user_name = session.get('user_name')\n event_id = request.form.get('event_id')\n attendee = Attendance.query.filter_by(user_name=user_name, event_id=event_id).first()\n if attendee:\n db.session.delete(attendee)\n db.session.commit()\n return event_comments()\n\ndef get_user_event(user_name):\n user_events = Attendance.query.filter_by(user_name=user_name).all()\n ret_events = []\n for event in user_events:\n ret_events.append(get_event_details(event.event_id))\n return ret_events\n\n","repo_name":"pablo-cs/crowd-clique","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":7593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"23396243581","text":"def splits(getal):\n stap = 0\n for i in str(getal):\n stap += 1\n if stap == 1:\n getal_1 = int(i)\n elif stap == 2:\n getal_2 = int(i)\n elif stap == 3:\n getal_3 = int(i)\n else:\n getal_4 = int(i)\n return getal_1, getal_2, getal_3, getal_4\n\ndef oplopende_cijfers(a, b, c, d):\n hoogste_cijfer = max(a, b, c, d)\n laagste_cijfer = min(a, b, c, d)\n middelste_cijfer_1 = max(min(a, b), min(b, c), min(a, c))\n middelste_cijfer_2 = a + b + c + d - hoogste_cijfer - laagste_cijfer - middelste_cijfer_1\n return laagste_cijfer, min(middelste_cijfer_1, middelste_cijfer_2), max(middelste_cijfer_1, middelste_cijfer_2), hoogste_cijfer\n\ndef op_af_getallen(a, b, c, d):\n oplopend = str(a) + str(b) + str(c) + str(d)\n aflopend = str(d) + str(c) + str(b) + str(a)\n return oplopend, aflopend\n\ndef verschil(a, b):\n verschil = int(a) - int(b)\n return str(verschil)\n\ndef kaprekar(getal):\n uitkomst = ''\n while getal != 6174:\n getal_1, getal_2, getal_3, getal_4 = splits(getal)\n laagste, mid_laag, mid_hoog, hoogste = oplopende_cijfers(getal_1, getal_2, getal_3, getal_4)\n cijfer_1, cijfer_2 = op_af_getallen(laagste, mid_laag, mid_hoog, hoogste)\n getal = int(verschil(cijfer_2, cijfer_1))\n uitkomst += '{} - {} = {}\\n'.format(cijfer_2, cijfer_1, getal)\n return uitkomst.strip()\n\n","repo_name":"EmielThomaes/5WWIPython","sub_path":"08_Functies/6174.py","file_name":"6174.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"42630843853","text":"import pygame\nfrom constantes import *\nfrom auxiliar import Auxiliar\nfrom player import Player\n\nclass Platform():\n def __init__(self,x,y,w,h,type=0):\n self.image= Auxiliar.getSurfaceFromSeparateFiles(\"JUEGO/images/tileset/forest/Tiles/{0}.png\",1,18,)[type]\n self.image = pygame.transform.scale(self.image,(w,h))\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = y\n self.colision_tierra_rect = pygame.Rect(self.rect.x,self.rect.y, self.rect.w, GROUND_RECT_H)#crear rectangulo\n\n\n \n\n def draw(self,screen):\n if(DEBUG):\n pygame.draw.rect(screen,ROJO,self.rect)\n\n screen.blit(self.image,self.rect)\n \n if(DEBUG):\n pygame.draw.rect(screen,VERDE,self.colision_tierra_rect)\n \n ","repo_name":"ThomasAlbertella/pp_lab1_albertella_thomas","sub_path":"JUEGO/plataform.py","file_name":"plataform.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"17058388378","text":"import os\nimport json\nimport imageio\n\nimport numpy as np\n\ndef load_blender(root:str, bg_white:bool=True, downsample:int=0, test_skip:int=8):\n splits = ['train', 'val', 'test']\n metas = {}\n\n # Load annotation?\n for s in splits:\n with open(os.path.join(root, f'transforms_{s}'), 'r') as fp:\n metas[s] = json.load(fp)\n\n all_iamges = []\n all_poses = []\n counts = [0]\n \n # Load images.\n for s in splits:\n meta = metas[s]\n images = []\n poses = []\n # What is test_skip?\n if s == 'train' or test_skip == 0:\n skip = 1\n else:\n skip = test_skip\n \n for frame in meta['frame'][::skip]:\n file_name = os.path.join(root, frame['file_path'] + '.png')\n # images = [image1, image2, image3, ...]\n images.append(imageio.imread(file_name))\n poses.append(np.array(file_name['transform_matrix']))\n \n # Normalization\n images = (np.array(images) / 255.).astype(np.float32)\n poses = np.array(poses).astype(np.float32)\n \n # counts = [0, 1, 3, 6, ...] ?\n counts.append(counts[-1] + images.shape[0])\n all_images.append(images)\n all_poses.append(poses)\n \n # what is i_split?\n i_split = [np.arange(counts[i], counts[i+1]) for i in range(len(counts)-1)]\n images = np.concatenate(all_images, 0)\n gt_extrinsic = np.concatenate(all_poses, 0)\n \n heigth, width = images[0].shape[:2]\n camera_angle_x = float(metas['train']['camera_angle_x'])\n focal = .5 * width / np.tan(.5 * camera_angle_x)\n \n if downsample:\n height, width = int(height//downsample), int(width//downsample)\n focal = focal/downsample\n \n images_reduced = np.zeros((images.shape[0], height, width, images.shape[3]))\n for i, image in enumerate(images):\n images_reduced[i] = cv2.resize(image, (width, height), interpolation=cv2.INTER_AREA)\n images = images_reduced\n \n # It needs when downsample is false.\n height, width = int(height), int(width)\n gt_intrinsic = np.array([\n [focal, 0, 0.5*width],\n [0, focal, 0.5*height],\n [0, 0, 1]])\n \n if bg_white:\n images = images[..., :3] * images[..., -1:] + (1.0-images[..., -1:])\n else:\n images = images[..., :3] * images[..., -1:]\n return images, [gt_intrinsic, gt_extrinsic], [height, width], i_split\n","repo_name":"louixlouis/MachineLearning","sub_path":"NeRF/load_blender.py","file_name":"load_blender.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"19721133453","text":"import sys\n\nfrom possibleterm.possibleterm import findPossibleValue\nfrom semantics.semantics import exprFromList\nfrom instrument.task import SynthTask\nfrom decisiontree.treelearning import TreeLearner, genmoreconstraint\n\n\ndef main():\n task = SynthTask(sys.argv[1])\n if task.ins is task.ori:\n exit(0)\n possiblevalue = list(map(lambda l: exprFromList(l, [task.functionProto]),\n findPossibleValue(task.ins.bmExpr)))\n moreconstraint = genmoreconstraint(task.productions, task.ins.inputlist, task.ins.inputtylist)\n treelearner = TreeLearner(task.ins.semchecker, task.ins.z3checker, possiblevalue, moreconstraint)\n expr = treelearner.mainalgo()\n task.functionProto.expr = expr\n print(task.functionProto)\n #print(treelearner.mainalgo())\n #expr = Expr('ite', Expr('>=', Expr('x'), Expr('y')), Expr('x'), Expr('y'))\n #print(sem.check(expr, {'x': 1, 'y': 2}))\n #expr = Expr('ite', Expr('<=', Expr('x'), Expr('y')), Expr('x'), Expr('y'))\n #print(sem.check(expr, {'x': 1, 'y': 2}))\n\n\n\nif __name__ == '__main__':\n main()\n\n\n","repo_name":"RU-Automated-Reasoning-Group/CS515","sub_path":"SyGuS/programs/decisiontree/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"40"} +{"seq_id":"38902339698","text":"# cook your dish here\nimport numpy as np\n\narr = np.array([])\n\nn = int(input())\nwhile n > 0:\n size = int(input())\n for i in range(size):\n np.append(arr, input())\n max1 = arr[0]\n for i in range(size):\n if arr[i] > max1:\n max1 = arr[i]\n\n if max1 % 2 == 0:\n print(max1 + 2)\n else:\n print(max1 + 1)\n\n n = n - 1\n print(\"hello\")\n\n\n\n","repo_name":"2000031964-ramasai/class1.py","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"24460377983","text":"class Solution:\n \"\"\"\n @param poured: an integer\n @param query_row: an integer\n @param query_glass: an integer\n @return: return a double\n \"\"\"\n # Hint: Take care of numbers' structure\n def champagneTower(self, poured, query_row, query_glass):\n # write your code here\n res = [[0.0] * i for i in range(1, query_row + 2)]\n res[0][0] = poured\n\n for i in range(query_row):\n for j in range(len(res[i])):\n if res[i][j] <= 1:\n continue\n res[i + 1][j] += (res[i][j] - 1.0) / 2.0\n res[i + 1][j + 1] += (res[i][j] - 1.0) / 2.0\n\n return float(res[query_row][query_glass]) if res[query_row][query_glass] < 1 else 1.0\n","repo_name":"HaydenInEdinburgh/LintCode","sub_path":"1018_champagne_tower.py","file_name":"1018_champagne_tower.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"29359018776","text":"import sys\nfrom mainGUI import *\nimport numpy as np\nimport json\nimport pandas as pd\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn import preprocessing\nfrom fpgrowth.utils import make_prediction, read_pickle\nfrom matplotlib import pyplot as plt\nimport pickle as pkl\nimport math\nfrom math import exp\n\nclass MyForm(QtWidgets.QMainWindow):\n def __init__(self, parent=None):\n QtWidgets.QWidget.__init__(self, parent)\n self.ui = Ui_MainWindow()\n self.ui.setupUi(self)\n self.ui.spinBox.setValue(10)\n self.ui.spinBox_2.setValue(10)\n self.ui.mdiArea.addSubWindow(self.ui.NeuralNetwork)\n self.ui.mdiArea.addSubWindow(self.ui.AssociationRule)\n self.ui.mdiArea.addSubWindow(self.ui.HierarchicalClustering)\n self.ui.pushButton.clicked.connect(self.train_nn)\n self.ui.pushButton_2.clicked.connect(self.run_clustering)\n self.ui.pushButton_3.clicked.connect(self.create_nn_csv)\n self.ui.ar_button.clicked.connect(self.suggest_assoc)\n\n def train_nn(self):\n global X_train\n global y_train\n global bias1, bias2, weight1, weight2\n\n # NN Parameters\n train_data = X_train\n train_target = y_train\n learning_rate = 0.1\n num_input_neurons = len(X_train[0])\n num_hidden_neurons = self.ui.spinBox.value()\n num_output_neurons = y_train.max() + 1\n\n # initialize weights\n weight1 = np.random.default_rng().standard_normal(size=(num_input_neurons, num_hidden_neurons),\n dtype=np.float32) - 0.5\n bias1 = np.random.default_rng().standard_normal(size=num_hidden_neurons, dtype=np.float32) - 0.5\n weight2 = np.random.default_rng().standard_normal(size=(num_hidden_neurons, num_output_neurons),\n dtype=np.float32) - 0.5\n bias2 = np.random.default_rng().standard_normal(size=num_output_neurons, dtype=np.float32) - 0.5\n\n # setting the loop parameters\n error_diff = float(\"inf\")\n iteration = 0\n curr_error = 0\n prev_error = 0\n stopping_error = 0.000001\n train_data_length = len(train_data)\n max_iteration = self.ui.spinBox_2.value()\n all_output_signals = np.zeros((20, 20), np.float32)\n np.fill_diagonal(all_output_signals, 1.0)\n\n import time\n start_time = time.time()\n # main loop\n while error_diff > stopping_error and iteration < max_iteration:\n running_error = 0\n for index_row in range(train_data_length):\n # adjust input and output signals\n input_signals = np.array(train_data[index_row], dtype=np.float32)\n output_signals = all_output_signals[train_target.iloc[index_row]]\n\n # calculate feed forward from input layer\n z_inj = np.add(input_signals @ weight1, bias1)\n\n # activation function\n zj = 1.0 / (1.0 + np.exp(-z_inj))\n\n # calculate feed forward from hidden layer\n y_ink = np.add(zj @ weight2, bias2)\n\n # activation function\n yk = 1.0 / (1.0 + np.exp(-y_ink))\n\n # calculate the error\n output_error = output_signals - yk\n small_delta_k = np.multiply(np.multiply(output_error, yk), (1 - yk))\n running_error += output_error @ output_error\n\n # back propagate the error\n small_delta_in_j = small_delta_k @ weight2.T\n small_delta_j = np.multiply(np.multiply(zj, small_delta_in_j), (1 - zj))\n\n # update weights and biases\n bias1 += np.multiply(learning_rate, small_delta_j)\n weight1 += np.multiply(np.mat(input_signals).T * np.mat(small_delta_j), learning_rate)\n bias2 += np.multiply(learning_rate, small_delta_k)\n weight2 += np.multiply(np.mat(zj).T * np.mat(small_delta_k), learning_rate)\n\n # accumulating Total Squared Error\n curr_error += running_error\n\n # printing loop info\n error_diff = abs(prev_error - curr_error)\n if (iteration % 2 == 0) or (error_diff < stopping_error):\n print('Error: ', curr_error, ', epoch: ', iteration, ', error difference: ', error_diff)\n print(\">> %s second\" % (time.time() - start_time))\n\n iteration += 1\n prev_error = curr_error\n curr_error = 0\n\n # finishing\n print(\">> %s seconds\" % (time.time() - start_time))\n self.ui.label_2.setText(\"Done Training!\")\n\n def create_nn_csv(self):\n # set input and output variables\n test_set = vectors_test\n output_nn = [None] * len(test_set)\n\n # main loop to produce the result\n for iter1 in range(len(test_set)):\n # adjust input signals\n input_test = vectors_test[iter1]\n\n # calculate the feed forward\n z_inj = np.add(input_test @ weight1, bias1)\n zj = 1.0 / (1.0 + np.exp(-z_inj))\n y_ink = np.add(zj @ weight2, bias2)\n yk = 1.0 / (1.0 + np.exp(-y_ink))\n\n # record the result to output array\n output_nn[iter1] = np.argmax(yk)\n\n # create the dataframe to write csv\n dframe = pd.DataFrame(data=output_nn)\n y2 = dframe.apply(le.inverse_transform)\n item_id_dframe = pd.DataFrame(itemID_test)\n df_output = pd.concat([item_id_dframe, y2], axis=1)\n df_output.columns = ['id', 'cuisine']\n df_output.to_csv('output_submission.csv', index=False)\n\n # finishing\n print('writing Predictions to csv file complete')\n self.ui.label_2.setText(\"Done creating submission!\")\n\n def suggest_assoc(self):\n ingredients = self.ui.ar_text_box.text().split(\",\")\n suggestions = make_prediction(ingredients=set(ingredients), top_n_suggestions=5,\n rules_path=\"./fpgrowth/rules.pkl\")\n suggestion_list = [','.join(suggestion[0]) for suggestion in suggestions]\n self.ui.ar_list_widget.clear()\n if suggestions:\n self.ui.ar_list_widget.addItems(suggestion_list)\n else:\n self.ui.ar_list_widget.addItem(\"No associated items found\")\n\n def run_clustering(self):\n data = X_train[:1000]\n k = 10\n print(f'=====\\nRunning Agglomerative Hierarchical Clustering algorithm with k={k}...')\n # Start with every element in its own cluster\n clusters = {}\n print(f'# Elements={len(data)}')\n for i, x in enumerate(data):\n clusters[single_tuple(i)] = x\n # Run ACH\n global merges\n merges = []\n clusters = cluster(data, clusters, k)\n print(f'-----\\nGenerated {len(clusters)} final clusters:')\n for i, elements in enumerate(clusters.keys()):\n distribution = {}\n print(f'\\nCluster #{i+1}/{len(clusters.keys())}:')\n for i in range(len(elements)):\n #print(f'[{elements[i]}]={meal_region[elements[i]]}: {itemList[elements[i]]}')\n region = meal_region[elements[i]]\n if distribution.get(region) == None:\n distribution[region] = 1\n else:\n distribution[region] += 1\n for region in distribution:\n print(f'{region} = \\t{distribution[region]/len(elements) * 100}%')\n\n # Cached the results as running the whole algorithm is time-consuming\n with open('ahc/cache.pkl', 'rb') as f:\n Z = pkl.load(f)\n # Make the dendrogram without a plot to make a label function\n from scipy.cluster.hierarchy import dendrogram\n plt.title('Hierarchical Clustering Dendrogram')\n plt.xlabel('Distance')\n plt.ylabel('Cuisine (Element ID)')\n D = dendrogram(\n Z,\n no_plot=True,\n p = 25,\n truncate_mode = 'lastp',\n )\n leaves = D[\"leaves\"]\n # Get string labels for elements\n labels = []\n for index in leaves:\n region = meal_region[index]\n labels.append(region)\n # A function to substitue the string labels\n temp = {leaves[index]: labels[index] for index in range(len(leaves))}\n def llf(index):\n return \"{} (ID#{})\".format(temp[index], index)\n # Make the dendrogram\n dendrogram(\n Z,\n orientation='right',\n distance_sort='descending',\n leaf_label_func=llf,\n p = 25,\n truncate_mode = 'lastp',\n show_contracted=True\n )\n plt.show()\n\ndef cluster(data, centroids, k):\n # Runtime monitoring\n import time\n # Cluster until k clusters are made\n print(f'Clustering with k={k} with {len(centroids)} initial clusters...')\n next_index = len(centroids)\n # Track merges to build dendrogram\n merges = []\n while (len(centroids) > k):\n start = time.time()\n clusters = {}\n cluster_keys = {}\n distances = {}\n idx = 0;\n keys = list(centroids.keys())\n # Get the distances between all clusters\n for i in range(len(keys) - 1):\n ikey = keys[i]\n for j in range(i + 1, len(keys)):\n jkey = keys[j]\n cluster_keys[idx] = [ikey, jkey]\n clusters[idx] = ikey + jkey\n distances[idx] = euclidean_distance(centroids[ikey], centroids[jkey])\n idx += 1\n # Get smallest distance\n sorted_distances = {k: v for k, v in sorted(distances.items(), key=lambda item: item[1])}\n indices = list(sorted_distances.keys())\n index = indices[0]\n distance = sorted_distances[index]\n # Calculate the new centroid\n centroid = compute_centroid(data, clusters[index])\n centroids[clusters[index]] = centroid\n merges.append([clusters[index], distance, len(cluster_keys[index])])\n # Remove the old centroid\n for cluster_key in cluster_keys[index]:\n centroids.pop(cluster_key)\n print(f'Found {len(centroids)} clusters in {time.time() - start} seconds')\n return centroids\n\n# Go through the elements in the cluster and average the values across all their indices\ndef compute_centroid(dataset, clusters):\n attributes = len(dataset[0])\n centroid = [0.0] * attributes\n for idx in range(len(clusters)):\n element_index = clusters[idx]\n element = dataset[element_index]\n for i in range(attributes):\n centroid[i] += float(element[i])\n for i in range(attributes):\n centroid[i] /= len(clusters)\n return centroid\n\n# Return a tuple with a single value\ndef single_tuple(value):\n return ((value,))\n\n# Get the euclidian distance between the two points\ndef euclidean_distance(x, y):\n # Only measure the indices for which at least one of the points has a value\n # In other words ignore elements that are missing for both to save computation time and space\n total_points = {}\n for i, key in enumerate(x):\n if key > 0:\n if i not in list(total_points.keys()):\n total_points[i] = [0, 0]\n total_points[i][0] = 1\n if y[i] > 0:\n if i not in list(total_points.keys()):\n total_points[i] = [0, 0]\n total_points[i][1] = 1\n total_keys = list(total_points.keys())\n total_keys.sort()\n # Calculate the distance\n result = 0\n for key in total_keys:\n result += pow(float(total_points[key][0]) - float(total_points[key][1]), 2)\n result = result ** 0.5\n return result\n\n\ndef setup_data():\n print(\"Setting the data...\")\n # Reading the Yummly dataset\n with open('./train.json', encoding='utf-8', errors='replace') as dataset:\n data = dataset.read()[3:-3]\n data = data.split(\"},\")\n data.append(\"temp\")\n rows = []\n for row in data[:-1]:\n row = row + \"}\"\n rows.append(json.loads(row))\n\n # split the json file info into id, region, and ingredients\n global itemList\n itemList = []\n itemID = []\n global meal_region\n meal_region = []\n for row in rows:\n m = \"\"\n itemID.append(row['id'])\n meal_region.append(row['cuisine'])\n for each1 in row['ingredients']:\n # replace space in the ingredients with underscore\n each1 = each1.replace(' ', '_')\n m += each1 + ' '\n itemList.append(m)\n\n # binaryzing train data\n vectorizer = CountVectorizer()\n vectors = vectorizer.fit_transform(itemList).toarray()\n\n # List of ingredients for association rule suggestion\n global rules\n rules = []\n\n # Read the ingredient list from file\n rules = read_pickle(\"./fpgrowth/rules.pkl\")\n\n # Now, processing test data\n with open('./test.json', encoding='utf-8', errors='replace') as testset:\n data = testset.read()[3:-3]\n data = data.split(\"},\")\n data.append(\"temp\")\n meals_test = []\n for row in data[:-1]:\n row = row + \"}\"\n meals_test.append(json.loads(row))\n\n # split the json file info into id, region, and ingredients\n itemList_test = []\n global itemID_test\n itemID_test = []\n meal_cuisine_test = []\n for each in meals_test:\n m = \"\"\n itemID_test.append(each['id'])\n for row in each['ingredients']:\n row = row.replace(' ', '_')\n m += row + ' '\n itemList_test.append(m)\n\n # binaryzing test data with train data vocabulary\n vectorizer2 = CountVectorizer(vocabulary=vectorizer.vocabulary_)\n global vectors_test\n vectors_test = vectorizer2.fit_transform(itemList_test).toarray()\n\n # creating training dataframe\n global le\n le = preprocessing.LabelEncoder()\n data = {\"cuisine\": meal_region}\n dataframe = pd.DataFrame(data)\n y = dataframe.apply(le.fit_transform)\n global X_train\n global y_train\n X_train = vectors\n y_train = y['cuisine']\n\n\nglobal X_train\nglobal y_train\nglobal vectors_test\nglobal bias1, bias2, weight1, weight2\nglobal le\nglobal itemID_test\nglobal itemList\n\nif __name__ == '__main__':\n app = QtWidgets.QApplication(sys.argv)\n setup_data()\n myapp = MyForm()\n myapp.run_clustering()\n #myapp.show()\n #sys.exit(app.exec_())\n sys.exit()\n","repo_name":"Keerthisaraa/DataMiner","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"14460682280","text":"# python -m unittest tests.test_data_collection\r\n# test_data_collection.py\r\nimport unittest\r\nimport sys\r\nimport os\r\nimport pandas as pd\r\nsys.path.append('./scripts')\r\nfrom data_collection import DataCollector\r\n\r\nclass TestDataCollection(unittest.TestCase):\r\n \"\"\"The TestDataCollection is a test class for the DataCollector class.\"\"\"\r\n\r\n def test_add(self):\r\n \"\"\"Test the add function.\"\"\"\r\n result = 5\r\n self.assertEqual(result, 5)\r\n \r\n def test_fetch_auctions(self):\r\n \"\"\"Test the _fetch_auctions method of DataCollector class.\"\"\"\r\n # Setup\r\n notebook_dir = os.getcwd()\r\n data_dir = os.path.join(notebook_dir, \"..\", \"data\")\r\n data_collector = DataCollector(data_dir)\r\n data_collector._fetch_auctions()\r\n data_collector.disconnectDB()\r\n assert True\r\n \r\n def test_fetch_vehicles(self):\r\n \"\"\"Test the _fetch_vehicles method of DataCollector class.\"\"\"\r\n # Setup\r\n notebook_dir = os.getcwd()\r\n data_dir = os.path.join(notebook_dir, \"..\", \"data\")\r\n data_collector = DataCollector(data_dir)\r\n data_collector._fetch_vehicles()\r\n data_collector.disconnectDB()\r\n \r\n def test_fetch_all(self):\r\n \"\"\"Test the fetch_all method of DataCollector class.\"\"\"\r\n # Setup\r\n notebook_dir = os.getcwd()\r\n data_dir = os.path.join(notebook_dir, \"..\", \"data\")\r\n data_collector = DataCollector(data_dir)\r\n data_collector.fetch_all()\r\n data_collector.disconnectDB()\r\n \r\n def test_fetch_inspections(self):\r\n \"\"\"Test the _fetch_inspections method of DataCollector class.\"\"\"\r\n # Setup\r\n notebook_dir = os.getcwd()\r\n data_dir = os.path.join(notebook_dir, \"..\", \"data\")\r\n data_collector = DataCollector(data_dir)\r\n data_collector._fetch_inspections()\r\n data_collector.disconnectDB()\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","repo_name":"Mengjun74/autozen_car_valuation","sub_path":"tests/test_data_collection.py","file_name":"test_data_collection.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"20818308973","text":"#Export all symbols to XML.\n#@author Rena\n#@category Symbol\n#@keybinding\n#@menupath\n#@toolbar\nimport xml.etree.ElementTree as ET\n\nAF = currentProgram.getAddressFactory()\nlisting = currentProgram.getListing()\n\ndef addrToInt(addr):\n\treturn int(str(addr), 16)\n\ndef intToAddr(addr):\n\treturn AF.getAddress(\"0x%08X\" % addr)\n\ndef checkCanceled():\n if monitor.isCancelled(): raise \"Cancelled\"\n\nfilterFuncPrefixes = (\"FUN_\", \"LAB_\")\ndef filterFunc(func):\n\tif func.name.startswith(filterFuncPrefixes): return False\n\treturn True\n\nfilterLabelPrefixes = (\n\t\"BYTE_\",\n\t\"DAT_\",\n\t\"DWORD_\",\n\t\"FLOAT_\",\n\t#\"fptr_\",\n\t\"LAB_\",\n\t\"padding_\",\n\t\"PTR_\",\n\t\"s_\",\n\t\"ZLB_\",\n)\ndef filterData(sym):\n\tif sym.label is None or sym.label == \"\": return False\n\tif sym.label == \"padding\": return False\n\tif sym.label.startswith(filterLabelPrefixes): return False\n\treturn True\n\ndef isGenericParamName(name):\n \"\"\"Check if name is a generic parameter name.\"\"\"\n if name is None:\n raise ValueError(\"parameter name is None\")\n return name.startswith('param')\n\ndef listParams(func):\n for param in func.getParameters():\n checkCanceled()\n reg = param.getRegister()\n stackOffs = None\n if reg is None:\n reg = 'stack'\n try: stackOffs = hex(param.getStackOffset())\n except:\n print(\"No register or stack for param %r in func 0x%X\" % (\n param, addrToInt(func.body.minAddress)))\n reg = None\n else: reg = reg.getName()\n pName = param.getName()\n if isGenericParamName(pName): pName = None\n pType = param.getDataType().getName()\n if pType == 'undefined': pType = None\n elif pType == 'undefined8' and reg is not None and reg.startswith('f'):\n pType = 'double'\n\n res = {\n 'type': pType,\n 'name': pName,\n 'reg': reg,\n 'stackOffset': stackOffs,\n }\n # XXX use some fancy comprehension shit\n r = {}\n for k, v in res.items():\n if v is None: pass\n else: r[k] = str(v)\n yield r\n\n\ndef listFuncs():\n for func in filter(filterFunc, listing.getFunctions(True)):\n checkCanceled()\n ret = func.getReturnType()\n if ret is not None and ret.getName() != 'undefined':\n ret = ret.getName()\n else:\n ret = None\n yield {\n 'start': addrToInt(func.body.minAddress),\n 'end': addrToInt(func.body.maxAddress),\n #'proto': str(func.signature.prototypeString),\n 'name': str(func.name),\n 'params': list(listParams(func)),\n 'comment': getPlateComment(func.body.minAddress),\n 'return': ret,\n }\n\ndef listSyms():\n\tfor sym in filter(filterData, listing.getDefinedData(True)):\n\t\tcheckCanceled()\n\t\tyield {\n\t\t\t\"name\": str(sym.label),\n\t\t\t\"start\": addrToInt(sym.minAddress),\n\t\t\t\"end\": addrToInt(sym.maxAddress),\n\t\t\t\"type\": str(sym.dataType.displayName),\n\t\t}\n\nnFuncs, nSyms = 0, 0\neRoot = ET.Element('symbols')\neFuncs = ET.SubElement(eRoot, 'functions')\neData = ET.SubElement(eRoot, 'data')\ntree = ET.ElementTree(eRoot)\n\noutPath = str(askFile(\"Export Symbols\", \"Export\"))\n\n# Export functions\nmonitor.setMessage(\"Listing functions...\")\n# addr, size, vAddr, align, name\nfor func in listFuncs():\n eFunc = ET.SubElement(eFuncs, 'function', {\n 'address': '0x%08X' % func['start'],\n 'length': '0x%08X' % ((func['end'] - func['start'])+1),\n 'name': func['name'],\n })\n if func['comment'] is not None:\n ET.SubElement(eFunc, 'comment').text = func['comment']\n if func['return'] is not None:\n ET.SubElement(eFunc, 'return', {'type':func['return']})\n eParams = ET.SubElement(eFunc, 'params')\n for param in func['params']:\n ET.SubElement(eParams, 'param', param)\n nFuncs += 1\n\n# Export data\nmonitor.setMessage(\"Listing data...\")\nfor sym in listSyms():\n eSym = ET.SubElement(eData, 'symbol', {\n 'address': '0x%08X' % sym['start'],\n 'length': '0x%08X' % ((sym['end'] - sym['start'])+1),\n 'name': sym['name'],\n 'type': sym['type'],\n })\n nSyms += 1\n\ntree.write(outPath)\nprint(\"Wrote %d functions, %d symbols\" % (nFuncs, nSyms))\n","repo_name":"RenaKunisaki/GhidraScripts","sub_path":"ExportSymbols.py","file_name":"ExportSymbols.py","file_ext":"py","file_size_in_byte":4270,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"40"} +{"seq_id":"14237861572","text":"import re\r\nimport json\r\n\r\n# 驗證key有沒有缺1\r\ndef is_valid(data):\r\n # check type of data\r\n if not isinstance(data, dict):\r\n return False\r\n\r\n # check key\r\n valid_keys = [\"ad_network\", \"date\", \"app_name\", \"unit_id\", \"request\", \"revenue\", \"imp\"]\r\n data_keys = [key for key in data]\r\n \r\n if valid_keys != data_keys:\r\n return False\r\n\r\n # check value type\r\n valid_value_type = {key: str for key in valid_keys}\r\n for key, value in data.items():\r\n if not isinstance(value, valid_value_type[key]):\r\n return False\r\n\r\n # check value format\r\n # ad_network\r\n valid_value_format = {\r\n \"ad_network\": r\"^[A-Z]+$\",\r\n \"date\": r\"^(202[0-2]|20[01]\\d|1[\\d]{3})-(0[1-9]|1[0-2])-([0][1-9]|[12][\\d]|3[01])$\",\r\n \"app_name\": r\"^LINETV$\",\r\n \"unit_id\": r\"^[\\d]+$\",\r\n \"request\": r\"^[1-5][\\d]{2}$\",\r\n \"revenue\": r\"^-?\\d+.\\d+$|^-?\\d+$\",\r\n \"imp\": r\"^\\d+$\"\r\n }\r\n for key, value in data.items():\r\n p = re.compile(valid_value_format[key])\r\n if not p.match(value):\r\n print(key)\r\n return False\r\n\r\n return True","repo_name":"zzozfe/line_tv","sub_path":"line_test.py","file_name":"line_test.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"32731668063","text":"import numpy as N\nimport pylab as P\nfrom assimulo.problem import Explicit_Problem #Imports the problem formulation from Assimulo\nfrom assimulo.solvers.sundials import CVode #Imports the solver CVode from Assimulo\n\ndef rhs(t,y):\n A =N.array([[0,1],[-2,-1]])\n yd=N.dot(A,y)\n\n return yd\n\ny0=N.array([1.0,1.0])\nt0=0.0\n\nmodel = Explicit_Problem(rhs, y0, t0) #Create an Assimulo problem\nmodel.name = 'Linear Test ODE' #Specifies the name of problem (optional)\n\nsim = CVode(model)\n\ntfinal = 10.0 #Specify the final time\n\nt, y = sim.simulate(tfinal) #Use the .simulate method to simulate and provide the final time\n\n#Plots the result\nP.plot(t,y)\nP.show()\n","repo_name":"simonschmidt/FMNN-project3","sub_path":"assimulotest.py","file_name":"assimulotest.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"20981349948","text":"import pygame\nimport math\nimport random\n\nfrom db.storagedriver import StorageDriver\nfrom screen.game_screen_class import GameScreen\n\n\n\nclass Menu(GameScreen):\n def __init__(self, w, h):\n # pokaz myszke\n pygame.mouse.set_visible(True)\n super().__init__(w, h)\n \n self.storage_driver = StorageDriver()\n \n self.garage_button = pygame.image.load('textures/buttons/garagebtn.png').convert_alpha()\n self.garage_button_rect = self.garage_button.get_rect(center = (300, 470))\n self.start_button = pygame.image.load('textures/buttons/playbtn.png').convert_alpha()\n self.start_button_rect = self.start_button.get_rect(center = (300, 320))\n self.stats_button = pygame.image.load('textures/buttons/statsbtn.png').convert_alpha()\n self.stats_button_rect = self.stats_button.get_rect(center = (300, 620))\n self.change_user_button = pygame.image.load('textures/buttons/cubtn.png').convert_alpha()\n self.change_user_button_rect = self.change_user_button.get_rect(center = (300, 750))\n \n # mute / unmute management\n self.mute_button = pygame.image.load('textures/buttons/mutebtn.png').convert_alpha()\n self.mute_button = pygame.transform.rotozoom(self.mute_button, 0, 0.25)\n self.unmute_button = pygame.image.load('textures/buttons/unmutebtn.png').convert_alpha()\n self.unmute_button = pygame.transform.rotozoom(self.unmute_button, 0, 0.12)\n self.soundbtn = None \n self.soundbtn_rect = None\n self.sounds = self.storage_driver.get_sounds()\n self.create_sound_btn_rects()\n\n self.high_score = self.storage_driver.get_highscore()[0]\n self.username = self.storage_driver.get_current_username()\n \n self.text1 = self.font.render(\"press SPACE to start\", True, 'black')\n self.text_rect1 = self.text1.get_rect(center = (self.w//2, 180))\n self.text2 = pygame.font.Font(\"textures/font.ttf\", 30).render(\"WROCLAW MOST WANTED\", True, 'black')\n self.text_rect2 = self.text2.get_rect(center = (self.w//2, 80))\n\n self.text3 = self.font.render(f\"CURRENT HIGH SCORE: {self.high_score}\", True, 'black')\n self.text_rect3 = self.text3.get_rect(center = (self.w//2, 220))\n\n self.text4 = self.font.render(f\"CURRENT USER: {self.username}\", True, 'black')\n self.text_rect4 = self.text4.get_rect(center = (self.w//2, 140))\n\n\n def create_sound_btn_rects(self):\n if not self.sounds:\n self.soundbtn = self.unmute_button\n self.soundbtn_rect = self.unmute_button.get_rect(center=(50,750))\n else:\n self.soundbtn = self.mute_button\n self.soundbtn_rect = self.mute_button.get_rect(center=(50,750))\n \n def toggle_sounds(self):\n if self.soundbtn_rect.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:\n self.sounds = not self.sounds\n self.storage_driver.set_sounds(self.sounds)\n self.create_sound_btn_rects()\n if not self.sounds:\n pygame.mixer.stop()\n else:\n pygame.mixer.unpause()\n print(self.sounds)\n pygame.time.wait(150)\n \n \n\n def display_menu_bg(self):\n self.screen.fill('lightblue')\n self.screen.blit(self.text1, self.text_rect1)\n self.screen.blit(self.text2, self.text_rect2)\n self.screen.blit(self.text3, self.text_rect3)\n self.screen.blit(self.text4, self.text_rect4)\n\n def display_buttons(self):\n self.screen.blit(self.garage_button, self.garage_button_rect)\n self.screen.blit(self.start_button, self.start_button_rect)\n self.screen.blit(self.stats_button, self.stats_button_rect)\n self.screen.blit(self.change_user_button, self.change_user_button_rect)\n self.screen.blit(self.soundbtn, self.soundbtn_rect)\n\n def click_button(self) -> int:\n # !!!! zwraca odpowiedni numer stanu, zgodny z GameState.State\n # 2 - GAME, 4 - GARAGE, jeszcze stats nie jest zrobione\n \n if self.garage_button_rect.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:\n return 4\n # tu powinien zmienić się stan maszyny stanów na garage\n \n if self.start_button_rect.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:\n return 2\n # tu powinien zmienić się stan maszyny stanów na game (powinna się zacząć gra)\n \n if self.stats_button_rect.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:\n return 5\n # tu powinien zmienić się stan muzyki na off ale nie ma jeszcze muzyki\n\n if self.change_user_button_rect.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:\n return 6\n # wejście do ekranu zmiany użytkownika\n","repo_name":"ignacy7312/2d-car-game","sub_path":"screen/menu_module.py","file_name":"menu_module.py","file_ext":"py","file_size_in_byte":4933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"27704975358","text":"\"\"\"class Student:\r\n pass\r\n\r\nE1= Student()\r\nMark= Student()\r\n\"\"\"\r\n\r\nclass Employee:\r\n def __init__(self,name1,age1,sex1,location1):\r\n self.name = name1\r\n self.age = age1\r\n self.sex = sex1\r\n self.location = location1\r\n def show(self):\r\n print(\"NAME: %s, AGE: %i, SEX: %s, LOCATION: %s \"%(self.name , self.age, self.sex, self.location))\r\n\"\"\"E1 = Employee()\r\nE1.name = \"Nikhil\"\r\nE1.age = 18\r\nE1.sex = \"Male\"\r\nE1.location = \"Pune\"\r\nE1.show()\"\"\"\r\n\r\n\"\"\"E2 = Employee()\r\nE2.name = \"Maya\"\r\nE2.age = 19\r\nE2.sex = \"Female\"\r\nE2.location = \"Mumbai\"\r\nE2.show()\"\"\"\r\nE1 = Employee(\"Nikhil\", 18, \"Male\",\"Pune\")\r\nE2 = Employee(\"May\", 19, \"Female\",\"Mumbai\")\r\nE3 = Employee(\"Ram\", 21, \"Male\",\"Nashik\")\r\nE1.show()\r\nE2.show()\r\nE3.show()\r\n\r\n\r\n\r\n ","repo_name":"NikhilWaghmode09/Practicing-Python","sub_path":"oop1.py","file_name":"oop1.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"9416101224","text":"from sqlalchemy.ext.declarative import DeclarativeMeta\r\nimport json\r\n\r\n\r\n# gets parameter from either the path or body in the request\r\ndef get_param(req, param, par_type):\r\n par = req.params.get(param)\r\n if not par:\r\n try:\r\n req_body = req.get_json()\r\n except ValueError:\r\n return None\r\n else:\r\n par = req_body.get(param)\r\n\r\n if(par_type == \"int\"):\r\n par = int(par)\r\n if(par_type == \"string\"):\r\n par = str(par)\r\n else:\r\n pass\r\n\r\n return par\r\n\r\n\r\n# sqlalchemy response to list with dicts, and remove unwanted data\r\ndef prepare_data(db_data, var_list):\r\n return_list = []\r\n for rindex, item in enumerate(db_data):\r\n for iindex, var in enumerate(var_list):\r\n var_attr = getattr(item, var[0])\r\n obj_dict = var_attr.__dict__\r\n del obj_dict[\"_sa_instance_state\"]\r\n try:\r\n return_list[rindex].append(obj_dict)\r\n except IndexError:\r\n return_list.append([obj_dict])\r\n return return_list\r\n\r\n\r\ndef get_user_id_by_token(token):\r\n from .models import Token\r\n from .db_connection import request_session\r\n\r\n session = request_session()\r\n if \"earer\" in token:\r\n data = session.query(Token).filter(Token.token == token[7:]).first()\r\n else:\r\n data = session.query(Token).filter(Token.token == token).first()\r\n session.close()\r\n \r\n return data.__dict__['user_id']\r\n\r\n\r\n# function for encoding sql alchemy data to json\r\nclass AlchemyEncoder(json.JSONEncoder):\r\n def default(self, obj):\r\n if isinstance(obj.__class__, DeclarativeMeta):\r\n # an SQLAlchemy class\r\n fields = {}\r\n for field in [x for x in dir(obj) if not x.startswith('_') and x != 'metadata']:\r\n data = obj.__getattribute__(field)\r\n try:\r\n json.dumps(data) # this will fail on non-encodable values, like other classes\r\n fields[field] = data\r\n except TypeError:\r\n fields[field] = None\r\n # a json-encodable dict\r\n return fields","repo_name":"Mc-Markus/SSP","sub_path":"resources/functions_shared.py","file_name":"functions_shared.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"4007982570","text":"\n# coding: utf-8\n\n#import libraries and modules\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\ncolor = sns.color_palette()\nplt.style.use('ggplot')\n\n#load and read all six csv datasets as dataframe objects and then look into them\n\n# aisles.csv -- contains aisles identifier and name of the aisles\n# unique in aisle_id\naisles = pd.read_csv('.../aisles.csv')\nprint('Total aisles: {}'.format(aisles.shape))\nprint(aisles.head(5))\n\n#cheking for missing values\nmissing = aisles.isnull().sum().sort_values(ascending=False)\nprint(\"Missing data: \", missing)\n\n# departments.csv -- contains department identifer and name of the department\n# unique in department_id\ndepartments = pd.read_csv('../departments.csv')\nprint('Total departments: {}'.format(departments.shape))\nprint(departments.head(5))\n\nmissing = departments.isnull().sum().sort_values(ascending=False)\nprint(\"Missing data: \", missing)\n\n# products.csv -- contains all product information\n# unique in product_id\nproducts = pd.read_csv('../products.csv')\nprint('Total products: {}'.format(products.shape))\nprint(products.head(5))\n\nmissing = products.isnull().sum().sort_values(ascending=False)\nprint(\"Missing data: \", missing)\n\n# orders.csv -- contains all order and customer purchase information\n# tells us which set (prior, train, test) an order belongs to\n# unique in order_id\norders = pd.read_csv('../orders.csv')\nprint('Total orders: {}'.format(orders.shape))\nprint(orders.head(5))\n\nmissing = orders.isnull().sum().sort_values(ascending=False)\nprint(\"Missing data: \", missing)\n\n# order_products_prior.csv -- contains previous orders for all customers\n#unique in order_id & product_id\norders_prior = pd.read_csv('../order_products_prior.csv')\nprint('Total prior orders: {}'.format(orders_prior.shape))\nprint(orders_prior.head(5))\n\nmissing = orders_prior.isnull().sum().sort_values(ascending=False)\nprint(\"Missing data: \", missing)\n\n# order_products_train.csv -- contains last orders for all customers\n#unique in order_id & product_id\norders_train = pd.read_csv('../order_products_train.csv')\nprint('Total last orders: {}'.format(orders_train.shape))\nprint(orders_prior.head(5))\n\nmissing = orders_train.isnull().sum().sort_values(ascending=False)\nprint(\"Missing data: \", missing)\n\n#combine order_products_prior.csv and order_products_train.csv into one dataframe\norders_products = pd.concat([orders_prior, orders_train], axis=0)\nprint(\"Total is: \", orders_products.shape)\nprint(orders_products.head(5))\n\n# combine aisles.csv, departments.csv and products.csv into one dataframe\nproducts_data = pd.merge(left=pd.merge(left=products, right=departments, how='left'), right=aisles, how='left')\n\n# to make product_name and aisle more usable and remove spaces between words\nproducts_data.product_name = products_data.product_name.str.replace(' ', '_').str.lower()\nproducts_data.aisle = products_data.aisle.str.replace(' ', '_').str.lower()\n\nprint(\"Total rows: \", products_data.shape)\nprint(products_data.head(5))\n\n# 'eval_set' in orders.csv informs the given order goes to which of the three datasets (prior, train or test)\ncount_set = orders.eval_set.value_counts()\nprint(count_set)\n\n# define function to count the number of unique customers\ndef customer_count(x):\n return len(np.unique(x))\n\ncustomer = orders.groupby(\"eval_set\")[\"user_id\"].aggregate(customer_count)\nprint(customer)\n\n# number of unique orders and unique products\nunique_orders = len(set(orders_products.order_id))\nunique_products = len(set(orders_products.product_id))\nprint(\"There are %s orders for %s products\" %(unique_orders, unique_products))\n\n#number of products that customers usually order\ndata = orders_products.groupby(\"order_id\")[\"add_to_cart_order\"].aggregate(\"max\").reset_index()\ndata = data.add_to_cart_order.value_counts()\nplt.figure(figsize=(12, 8))\nsns.barplot(data.index, data.values, alpha=0.8)\nplt.xticks(rotation='vertical')\nplt.ylabel('Number of Orders', fontsize=12)\nplt.xlabel('Number of products added in order', fontsize=12)\nplt.show()\n\n#the number of orders made by each costumer in the whole dataset\ndata = orders.groupby('user_id')['order_id'].apply(lambda x: len(x.unique())).reset_index()\ndata = data.groupby('order_id').aggregate(\"count\")\n\nsns.set_style(\"whitegrid\")\nf, ax = plt.subplots(figsize=(15, 12))\nsns.barplot(data.index, data.user_id)\nplt.ylabel('Numbers of Customers')\nplt.xlabel('Number of Orders per customer')\nplt.xticks(rotation='vertical')\nplt.show()\n\n# time at which people usually order products\n# hours of order in a day\ndata = orders.groupby(\"order_id\")[\"order_hour_of_day\"].aggregate(\"sum\").reset_index()\ndata = data.order_hour_of_day.value_counts()\nsns.set_style('darkgrid')\nplt.figure(figsize=(12, 8))\nsns.barplot(data.index, data.values)\nplt.ylabel('Number of orders', fontsize=12)\nplt.xlabel('Hours of order in a day', fontsize=12)\nplt.title('When people buy groceries online?', fontweight='bold')\nplt.xticks(rotation='vertical')\nplt.show()\n\n# order and day of a week\ndata = orders.groupby(\"order_id\")[\"order_dow\"].aggregate(\"sum\").reset_index()\ndata = data.order_dow.value_counts()\ndays=[ 'sat','sun', 'mon', 'tue', 'wed', 'thu', 'fri']\nplt.figure(figsize=(12,8))\nsns.barplot(data.index, data.values)\nplt.ylabel('Number of orders', fontsize=12)\nplt.xlabel('Days of order in a week', fontsize=12)\nplt.title(\"Frequency of order by week day\", fontweight='bold')\nplt.xticks(rotation='vertical')\nplt.xticks(np.arange(7), ( 'sat','sun', 'mon', 'tue', 'wed', 'thu', 'fri'))\nplt.show()\n\n# When do they order again? time interval between orders\nplt.figure(figsize=(12,8))\nsns.countplot(x=\"days_since_prior_order\", data=orders)\nplt.ylabel('Nuumber of Orders', fontsize=12)\nplt.xlabel('Days since prior order', fontsize=12)\nplt.xticks(rotation='vertical')\nplt.xticks(np.arange(31))\nplt.title(\"Time interval between orders\", fontsize=15)\nplt.show()\n\n# percentage of reorders in prior set #\nprint(orders_prior.reordered.sum() / orders_prior.shape[0])\n\n# percentage of reorders in train set #\nprint(orders_train.reordered.sum() / orders_train.shape[0])\n\n#reorder frequency\ndata = orders_products.groupby(\"reordered\")[\"product_id\"].aggregate({'Total_products': 'count'}).reset_index()\ndata['Ratios'] = data[\"Total_products\"].apply(lambda x: x /data['Total_products'].sum())\ndata\ndata = data.groupby(['reordered']).sum()['Total_products'].sort_values(ascending=False)\nsns.set_style('darkgrid')\nf, ax = plt.subplots(figsize=(6, 8))\nsns.barplot(data.index, data.values)\nplt.ylabel('Number of Products', fontsize=12)\nplt.xlabel('Not Reordered = 0 and Reordered = 1', fontsize=12)\nplt.title('Reorder Frequency', fontweight='bold')\nplt.ticklabel_format(style='plain', axis='y')\nplt.show()\n\n\n#merge products_data with the orders_products data.\norders_products_all = pd.merge(orders_products, products_data, on='product_id', how='left')\nprint(\"Total rows: \", orders_products_all.shape)\nprint(orders_products_all.head(5))\n\n#merge products_data with the orders_prior data.\norders_prior_all = pd.merge(orders_prior, products_data, on='product_id', how='left')\nprint(\"Total rows: \", orders_prior_all.shape)\nprint(orders_prior_all.head(5))\n\n#which products are ordered the most\ndata = orders_products.groupby(\"product_id\")[\"reordered\"].aggregate({'Total_reorders': 'count'}).reset_index()\ndata = pd.merge(data, products[['product_id', 'product_name']], how='left', on=['product_id'])\ndata = data.sort_values(by='Total_reorders', ascending=False)[:10]\nprint(data)\n\n\ndata = orders_products.groupby(\"product_id\")[\"reordered\"].aggregate({'Total_reorders': 'count'}).reset_index()\ndata = pd.merge(data, products[['product_id', 'product_name']], how='left', on=['product_id'])\ndata = data.sort_values(by='Total_reorders', ascending=False)[:10]\ndata = data.groupby(['product_name']).sum()['Total_reorders'].sort_values(ascending=False)\nsns.set_style('darkgrid')\nf, ax = plt.subplots(figsize=(12, 8))\nplt.xticks(rotation='vertical')\nsns.barplot(data.index, data.values)\nplt.ylabel('Number of Reorders', fontsize=12)\nplt.xlabel('Most ordered Products', fontsize=12)\nplt.title('which products are ordered the most', fontweight = 'bold')\nplt.show()\n\n#most important aisles: best selling\ndata = orders_prior_all['aisle'].value_counts()\nplt.figure(figsize=(12,10))\nsns.barplot(data.index, data.values, alpha=0.8)\nplt.ylabel('Number of Occurrences', fontsize=12)\nplt.xlabel('Aisle', fontsize=12)\nplt.title('Important Aisles', fontweight ='bold')\nplt.xticks(rotation='vertical')\nplt.show()\n\n#customer's favorite best selling departments (number of orders)\ndata = orders_prior_all['department'].value_counts()\nplt.figure(figsize=(12,10))\nsns.barplot(data.index, data.values, alpha=0.8)\nplt.ylabel('Number of Occurrences', fontsize=12)\nplt.xlabel('Department', fontsize=12)\nplt.title(\"Departments wise distribution of products\", fontweight='bold')\nplt.xticks(rotation='vertical')\nplt.show()\n","repo_name":"harshadevireddy/Instacart-Product-Recommendation","sub_path":"EDA.py","file_name":"EDA.py","file_ext":"py","file_size_in_byte":8866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"113352148","text":"import os\nfrom contextlib import closing\nfrom fixtures.zenith_fixtures import PostgresFactory, ZenithPageserver\n\npytest_plugins = (\"fixtures.zenith_fixtures\", \"fixtures.benchmark_fixture\")\n\ndef get_timeline_size(repo_dir: str, tenantid: str, timelineid: str):\n path = \"{}/tenants/{}/timelines/{}\".format(repo_dir, tenantid, timelineid)\n\n totalbytes = 0\n for root, dirs, files in os.walk(path):\n for name in files:\n totalbytes += os.path.getsize(os.path.join(root, name))\n\n if 'wal' in dirs:\n dirs.remove('wal') # don't visit 'wal' subdirectory\n\n return totalbytes\n\n#\n# Run a very short pgbench test.\n#\n# Collects three metrics:\n#\n# 1. Time to initialize the pgbench database (pgbench -s5 -i)\n# 2. Time to run 5000 pgbench transactions\n# 3. Disk space used\n#\ndef test_pgbench(postgres: PostgresFactory, pageserver: ZenithPageserver, pg_bin, zenith_cli, zenbenchmark, repo_dir: str):\n # Create a branch for us\n zenith_cli.run([\"branch\", \"test_pgbench_perf\", \"empty\"])\n\n pg = postgres.create_start('test_pgbench_perf')\n print(\"postgres is running on 'test_pgbench_perf' branch\")\n\n # Open a connection directly to the page server that we'll use to force\n # flushing the layers to disk\n psconn = pageserver.connect();\n pscur = psconn.cursor()\n\n # Get the timeline ID of our branch. We need it for the 'do_gc' command\n with closing(pg.connect()) as conn:\n with conn.cursor() as cur:\n cur.execute(\"SHOW zenith.zenith_timeline\")\n timeline = cur.fetchone()[0]\n\n connstr = pg.connstr()\n\n # Initialize pgbench database, recording the time and I/O it takes\n with zenbenchmark.record_pageserver_writes(pageserver, 'pageserver_writes'):\n with zenbenchmark.record_duration('init'):\n pg_bin.run_capture(['pgbench', '-s5', '-i', connstr])\n\n # Flush the layers from memory to disk. This is included in the reported\n # time and I/O\n pscur.execute(f\"do_gc {pageserver.initial_tenant} {timeline} 0\")\n\n # Run pgbench for 5000 transactions\n with zenbenchmark.record_duration('5000_xacts'):\n pg_bin.run_capture(['pgbench', '-c1', '-t5000', connstr])\n\n # Flush the layers to disk again. This is *not' included in the reported time,\n # though.\n pscur.execute(f\"do_gc {pageserver.initial_tenant} {timeline} 0\")\n\n # Report disk space used by the repository\n timeline_size = get_timeline_size(repo_dir, pageserver.initial_tenant, timeline)\n zenbenchmark.record('size', timeline_size / (1024*1024), 'MB')\n","repo_name":"gurjeet/zenith-clone","sub_path":"test_runner/performance/test_perf_pgbench.py","file_name":"test_perf_pgbench.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"14824854677","text":"import i18n\nfrom dash import Dash\nfrom dash_bootstrap_components.themes import BOOTSTRAP\n\nfrom src.components.layout import LayoutBuilder\nfrom src.data.loader import load_transaction_data\nfrom src.data.source import DataSource\n\nLOCALE = 'pt'\nDATA_PATH = './data/transactions.csv'\n\n\ndef main() -> None:\n i18n.set('locale', LOCALE)\n i18n.load_path.append('locale')\n data = load_transaction_data(DATA_PATH, locale=LOCALE)\n data = DataSource(data)\n\n app = Dash(external_stylesheets=[BOOTSTRAP])\n app.title = i18n.t(\"general.app_title\")\n layout_builder = LayoutBuilder(app, data, LOCALE)\n app.layout = layout_builder.create_layout()\n app.run()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"tiagopache/financial-dashboard","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"17145646668","text":"#/usr/bin/env python3\n\n# Libraries\nfrom scapy.all import sr1,IP,ICMP\n\n# Global Values\nTARGETS = ['192.168.1.1','192.168.1.2']\n\n# Ping command\ndef ping(host):\n timeout = 3 # Set Timeout(Second)\n icmp_pkg = IP(dst=host)/ICMP() # Create ICMP Package\n response = sr1(\n icmp_pkg, # Package\n verbose=False, # Verbose set False\n timeout=timeout # Set Timeout\n )\n if response is None or \"host-unreachable\" in str(response):\n return False\n else:\n return True\n\nfor target in TARGETS:\n print(target + \"->\" + str(ping(target)))\n","repo_name":"keraattin/kerem.tech","sub_path":"How to Check Servers ​Up or Not(Ping) with​ Python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"35905243990","text":"###################################################################################\n################### Negative Domains of the function t -> g(x,mu+tLv) #############\n###################################################################################\n#\n# Author Yassine Laguel\n# Last Modification : 10/08/2017\n#\n# Algorithm based on the theoretical paper :\n# \"Eventual convexity of probability constraints with elliptical distributions\" \n# from Wim Van Ackooij and Jerome Malick \n#\n# We consider a Chance Constraint Problem of the form\n# phi(x) = IP( g(x,\\xi) <= 0 ),\n#\n# xi is an elliptical random vector of dimension m, with \n# mean mu and correlation matrix R,\n# \n# x is assumed to be such that g(x,mu) < 0\n#\n# We compute here the domains where the function t -> g(x,mu+tLv)\n# is negative. The algorithm depends on the informations the user \n# gives in the file Inputs.py.\n# \n# The problem and related techniques that appear here do not depend on the \n# method that will be used to compute the probability IP( g(x,\\xi) <= 0 ) \n# (which can be Monte Carlo or Quasi Monte Carlo for instance)\n# It rather depends on the information on the informations given on g, like its \n# derivative when given.\n#\n# The main method of this class is \"domains\" which returns a list of couples [a_i,b_i]\n# such that a_0 < b_0 < a_1 < ... < a_n < b_n and for which g( x , mu + tLv ) < 0 \n# for any t in [a_i,b_i] .\n#\n\nfrom scipy import optimize as optim\nimport numpy as np\nimport sys\n\nsys.setrecursionlimit(100000) # useful for the recursive calls of the function interval_with_root\n\n# python Class aimed at storing the domains where the function t -> g(x,mu+tLv) is negative. \nclass zeros_of_g:\n def __init__(self, inputs, x, v):\n \n self.inputs = inputs # information given by the user in the file Inputs.py \n \n self.x = x # value of x used in the computation g(x,mu+tLv) \n # Dimension of x must be inputs.n\n \n self.Lv = np.dot(inputs.L, v) # value of the vector Lv used in the computation \n # of g(x,mu+tLv). L is the Choleski matrix such that R = L^tL\n \n self.precision = 0.001 # We suppose here that for any real numbers a < b such that b-a < self.precision\n # there is no t real strictly in [a,b] such that g(x,mu+tLv) == 0\n \n \n self.borne = 20.0 # We don't study the domains that are not in [0,self.borne]\n # Indeed as we compose Fr by rho and as Fr decreases very quickly, \n # we do here the approximation Fr(t) = 0 if t > 100\n \n self.free_roots_domains = [[self.borne,\n self.borne - self.precision]] ### we suppose here that there aren't roots at the extremity of the given interval\n\n ### Returns g(x,mu+tLv)\n def g_xv(self, t):\n res = self.inputs.g(self.x, self.inputs.mu + t * self.Lv)\n return res\n\n ### Returns the gradient of g_xv evaluated in t\n def gradient_g_xv(self, t):\n A = self.inputs.g_jac_z(self.x, self.inputs.mu + t * self.Lv)\n res = np.dot(A, self.Lv)\n return res[0,0]\n\n ### Returns a zero using Newton-Raphson's method\n def nearest_root_by_newton(self, t):\n return optim.newton(self.g_xv, t, self.gradient_g_xv)\n\n ### Returns a root of g_xv in [a,b] using a mixed Newton's algorithm\n ### and secant method. Convergence is guarented.\n ### Needs f(a)*f(b) < 0\n def root_in(self, a, b):\n u = a\n v = b\n res = v - self.g_xv(v) * (v - u) / (self.g_xv(v) - self.g_xv(u))\n while (abs(self.g_xv(res)) > 0.00000001):\n\n if (-self.g_xv(res) * self.g_xv(a) > 0):\n v = res\n else:\n u = res\n\n if (self.gradient_g_xv(v) != 0):\n res = v - self.g_xv(v) / self.gradient_g_xv(v)\n if not ((res >= u) and (res <= v)):\n res = v - self.g_xv(v) * (v - u) / (self.g_xv(v) - self.g_xv(u))\n\n return res\n\n ### Returns an interval in [a,b] which contains a root of g_xv if this root exists\n ### else returns [-1,-1]. Algorithm based on bisection.\n def interval_with_root(self, a, b):\n #print(\"Use of Interval_with_roots\")\n\n\n if (a == -1):\n return [-1, -1]\n elif (-1 * self.g_xv(a) * self.g_xv(b) > 0): # if a et b produce opposite signs\n return [a, b]\n\n elif (b - a < self.precision): # we suppose here that two roots cannot be separated by a distance less than self.precision\n return [-1, -1]\n\n else:\n m = (a + b) / 2.0\n res0 = self.interval_with_root(a, m)\n if (res0[0] != -1):\n return res0\n else:\n return self.interval_with_root(m, b)\n\n ### Returns a list of the roots of g_xv in the interval [a,b]\n def list_of_roots(self, a, b):\n interval = self.interval_with_root(a, b)\n if (interval[0] == -1):\n return [];\n else:\n x = self.root_in(interval[0], interval[1])\n res = self.list_of_roots(a, x - self.precision)\n res.append(x)\n list_aux = self.list_of_roots(x + self.precision, b)\n res.extend(list_aux)\n return res\n\n ### Returns the list of intervals in which g_xv is negative\n def domains_general_case(self):\n \n l = [0.0]\n roots = self.list_of_roots(0, self.borne)\n l.extend(roots)\n l.append(self.borne)\n n = len(l)\n counter = 0\n res = []\n\n while counter + 1 < n:\n x = self.g_xv( (l[counter] + l[counter + 1]) / 2)\n if x < 0:\n res.append([l[counter], l[counter + 1]])\n\n counter += 1\n \n return res\n \n def domains_in_convex_case(self):\n if self.g_xv(self.borne) > 0.00000001 :\n rho = self.root_in(0.0,self.borne) # a direct newton_raphson would be convenient \n # but the one from scipy.optimize doesn't work because\n # (it seems to change modyfy and recall the estimation of the root you\n # give to it...)\n return [[0.0,rho]]\n else :\n return [[0.0,self.borne]]\n \n def domains(self):\n if self.inputs.g_convex_in_z :\n return self.domains_in_convex_case()\n else :\n return self.domains_general_case()\n","repo_name":"yassine-laguel/pychance","sub_path":"NegativeDomains.py","file_name":"NegativeDomains.py","file_ext":"py","file_size_in_byte":6632,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"14371616534","text":"import requests\nfrom flask import current_app\nfrom opentelemetry import trace\n\ntracer = trace.get_tracer(__name__)\n\n\ndef can_link(id: str) -> bool:\n \"\"\"\n Check if the participant is allowed to link their account\n :return: whether the participant can link\n \"\"\"\n with tracer.start_as_current_span(\"can-link\"):\n base = current_app.config[\"APPLICATION_PORTAL_URL\"]\n response = requests.get(base + f\"/discord/can-link?id={id}\")\n response.raise_for_status()\n\n return response.json().get(\"status\", False)\n","repo_name":"WaffleHacks/discord-linking","sub_path":"discord_linking/dependencies/registration.py","file_name":"registration.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"8738258890","text":"#!/usr/bin/env python\r\nimport sys\r\nimport os\r\n\r\nif len(sys.argv) != 3:\r\n print(\"create_dummies.py <00_file> \")\r\n sys.exit()\r\nelse:\r\n zero_name = sys.argv[1]\r\n ff_name = sys.argv[2]\r\n\r\nfo_z = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), zero_name), \"wb\")\r\nfo_f = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), ff_name), \"wb\")\r\n\r\nfo_z.write(bytearray([0x00] * 1024 * 1024 * 4))\r\nfo_f.write(bytearray([0xff] * 1024 * 1024 * 4))\r\n\r\nfo_z.close()\r\nfo_f.close()\r\n","repo_name":"tewtal/sm_practice_hack","sub_path":"resources/create_dummies.py","file_name":"create_dummies.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"42"} +{"seq_id":"15344506064","text":"# 手动获取一帧原始相机彩色和深度图像(不带图像识别)\n\n# -*- coding: utf-8 -*-:\nimport sys\nfrom openni import openni2\nimport numpy as np\nimport cv2\n\nf_x = 575.868\nf_y = 575.868\nc_x = 322.993\nc_y = 244.211\nmax_depth = 4000\nmin_depth = 20\nRESOULTION_X = 640\nRESOULTION_Y = 480\nDATA_PATH = './data/'\n\n# 输入一个m*n的二维numpy矩阵,输出水平翻转后的矩阵\ndef horizontalFlip(arr):\n h,w = arr.shape\n arr_180 = arr.reshape(1, int(arr.size))\n arr_180 = arr_180[0][::-1].reshape(h, w)\n return arr_180[::-1]\n\ndef convertDepthToPointCloud(depth_img,frame_cnt):\n width = 640\n height = 480\n valid_count = 307200\n if depth_img is None:\n print(\"depth frame is NULL!\")\n return 0\n\n fdx = f_x * ((float)(width) / RESOULTION_X)\n fdy = f_y * ((float)(height) / RESOULTION_Y)\n u0 = c_x * ((float)(width)/ RESOULTION_X)\n v0 = c_y * ((float)(height) / RESOULTION_Y)\n\n # 初始化点云文件\n PLY_FILE = DATA_PATH + 'pointcloud_' + str(frame_cnt)+'.ply'\n with open(PLY_FILE, 'w') as f:\n f.write(\"ply\\n\")\n f.write(\"format ascii 1.0\\n\")\n f.write(\"element vertex %d\\n\" %valid_count)\n f.write(\"property float x\\n\")\n f.write(\"property float y\\n\")\n f.write(\"property float z\\n\")\n f.write(\"property uchar red\\n\")\n f.write(\"property uchar green\\n\")\n f.write(\"property uchar blue\\n\")\n f.write(\"end_header\\n\")\n\n # 对每个像素点操作\n for v in range(height):\n for u in range(width):\n # depth = depth_img[v * width + u]\n depth = depth_img[v,u]\n # 统计有效深度点\n if (depth <= 0 and depth < min_depth and depth > max_depth):\n continue\n valid_count += 1\n\n # 转换点云数据\n tx = (u - u0) / fdx\n ty = (v - v0) / fdy\n world_x = depth * tx\n world_y = depth * ty\n world_z = depth\n \n # 存储点云数据\n f.write(\"%f %f %f 255 255 255\\n\" %(world_x, world_y, world_z))\n\n return 1\n\ndef read_depth_image(depth_stream):\n depth_frame = depth_stream.read_frame() # 获取一帧深度图\n raw_buf = depth_frame.get_buffer_as_uint16()\n buf_array = np.array([raw_buf[i] for i in range(640*480)])\n depth_image = buf_array.reshape(480,640)\n\n # depth_image = np.frombuffer(raw_buf, dtype=np.uint16)\n # depth_image.shape = (1, 480, 640)\n # depth_image = np.concatenate((depth_image, depth_image, depth_image), axis=0)\n # depth_image = np.swapaxes(depth_image, 0, 2)\n # depth_image = np.swapaxes(depth_image, 0, 1)\n depth_image = horizontalFlip(depth_image)\n return depth_image\n\ndef read_color_image(color_stream):\n color_frame = color_stream.read_frame() # 获取一帧彩色图\n raw_buf = color_frame.get_buffer_as_triplet()\n b_array = np.array([raw_buf[i][0] for i in range(640*480)])\n g_array = np.array([raw_buf[i][1] for i in range(640*480)])\n r_array = np.array([raw_buf[i][2] for i in range(640*480)])\n\n # convert to uint8 image\n color_image = np.zeros([480,640,3])\n color_image[:, :, 0] = r_array.reshape(480, 640)\n color_image[:, :, 1] = g_array.reshape(480, 640)\n color_image[:, :, 2] = b_array.reshape(480, 640)\n # if FLIP:\n # color_image = np.flipud(color_image.astype(np.uint8))\n\n color_image = np.fliplr(color_image.astype(np.uint8))\n return color_image\n\ndef save_color_image(color_image,frame_cnt): # 保存RGB图像文件\n RGB_FILE = DATA_PATH + 'img_' + str(frame_cnt)+'.png'\n # color_image = cv2.flip(color_image,1,dst=None) # 水平镜像\n cv2.imwrite(RGB_FILE, color_image) \n\ndef get_a_frame(dStream,cStream,frame_cnt):\n depth_img = read_depth_image(dStream)\n color_img = read_color_image(cStream)\n\n # 循环直到成功获取一帧深度和彩色图\n while(depth_img is None or color_img is None ):\n depth_img = read_depth_image(dStream)\n color_img = read_color_image(cStream)\n \n # 展示深度图和RGB图\n # cv2.imshow('depth', depth_img)\n # cv2.imshow('color', color_img)\n # key = cv2.waitKey(1)\n # if int(key) == ord('q'):\n # break\n \n # 转换并保存点云文件\n convertDepthToPointCloud(depth_img,frame_cnt)\n\n # 保存彩色图\n save_color_image(color_img,frame_cnt)\n \n print(\"Successfully get a frame.\\r\\n\")\n return 1\n\nif __name__ == \"__main__\": \n\n openni2.initialize() # openni初始化\n dev = openni2.Device.open_any() # 打开相机设备\n print(\"Device detected.\\r\\n\")\n print(dev.get_device_info())\n\n # 创建并设置深度图数据流\n depth_stream = dev.create_depth_stream()\n \n # 图像模式注册,彩色图与深度图对齐\n dev.set_image_registration_mode(openni2.IMAGE_REGISTRATION_DEPTH_TO_COLOR) \n\n # depth_stream.configure_mode(640,480,30,openni2.PIXEL_FORMAT_DEPTH_1_MM) # width, height, fps, pixel_format \n dMode = depth_stream.get_video_mode()\n dMode.resolutionX = 640\n dMode.resolutionY = 480\n dMode.fps = 30\n dMode.pixelFormat = openni2.PIXEL_FORMAT_DEPTH_1_MM\n depth_stream.set_video_mode(dMode) \n depth_stream.start() \n\n # 创建彩色图数据流\n color_stream = dev.create_color_stream() # 创建彩色图数据流\n # color_stream.configure_mode(640,480,30,openni2.PIXEL_FORMAT_RGB888) # width, height, fps, pixel_format \n cMode = color_stream.get_video_mode()\n cMode.resolutionX = 640\n cMode.resolutionY = 480\n cMode.fps = 30\n cMode.pixelFormat = openni2.PIXEL_FORMAT_RGB888\n # cMode.set_white_balance(4000)\n # cMode.set_exposure(50)\n color_stream.set_video_mode(cMode)\n color_stream.camera.set_auto_white_balance(True)\n color_stream.camera.set_auto_exposure(True)\n # color_stream.camera.set_exposure(10000)\n\n # 彩色图和深度图同步\n dev.set_depth_color_sync_enabled(True)\n\n color_stream.start()\n\n # 获取数据流\n frame_cnt = 1\n while True:\n command = input(\"Wait for command(c or e): \")\n if command == 'c':\n success = get_a_frame(depth_stream,color_stream,frame_cnt)\n frame_cnt += 1\n else:\n print(\"Finished. Ending Device.\")\n break\n\n\n # 结束,关闭\n depth_stream.stop()\n color_stream.stop()\n openni2.unload()\n dev.close()\n\n","repo_name":"yongxic97/soft_robot_arm_definitive","sub_path":"Vision/read_and_save_origin_frame_manual.py","file_name":"read_and_save_origin_frame_manual.py","file_ext":"py","file_size_in_byte":6474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"10180467332","text":"'''\nboolean input here: \n\na = bool(input(\"Enter your value \"))\nb = bool(input(\"enter your second value: \"))\nprint(a)\nprint(b) \n\nany non empty string is evaluated as True and Empty string is evaluated aas false. \n'''\nis_true = True\nis_false = False\nif is_true and is_false : \n print(\"Hi\")\nelif is_true or is_false: \n print(\"hi there vai\")\nelse : \n print(\" okay\")","repo_name":"AAM-Mustahid/100Days-Challenge-","sub_path":"Day 03/logical.py","file_name":"logical.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"41996738354","text":"from django import forms\nfrom . import models\n\n\n# class ProductForm(forms.Form):\nclass ProductForm(forms.ModelForm):\n category = forms.ModelChoiceField(queryset=models.Category.objects.all(), empty_label=None,\n widget=forms.Select(attrs={'class': 'form-control'}))\n new_category = forms.CharField(required=False, widget=forms.TextInput(attrs={'class': 'form-control'}))\n discount_price = forms.DecimalField(required=False, widget=forms.NumberInput(attrs={'placeholder': 'Цена со скидкой'}))\n\n class Meta:\n model = models.Product\n fields = ['title', 'category', 'new_category', 'cover', 'price', 'discount_price', 'size', 'color']\n widgets = {\n 'title': forms.TextInput(attrs={'placeholder': 'Название', 'label': 'Название'}),\n 'category': forms.RadioSelect(attrs={'placeholder': 'Категория', 'label': 'Категория'}, ),\n 'new_category': forms.TextInput(attrs={'placeholder': 'Новая категория', 'label': 'Новая категория'}, ),\n 'price': forms.NumberInput(attrs={'placeholder': 'Цена'}),\n # 'discount_price': forms.NumberInput(attrs={'placeholder': 'Цена со скидкой'}),\n 'size': forms.CheckboxSelectMultiple(attrs={'class': 'size-choices'}),\n # 'size': forms.RadioSelect(attrs={'class': 'size-choices'}),\n 'color': forms.CheckboxSelectMultiple(attrs={'class': 'color-choices'}),\n }\n","repo_name":"sozubova/womazing","sub_path":"shop/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"1059148164","text":"from tkinter import *\nimport time\nroot = Tk()\n\ncanvas = Canvas(root, width='600', height='600')\ncanvas.pack()\n\ndef carpet(a, x, y):\n time.sleep(0.0001)\n canvas.update()\n\n if a < 40:\n return 0\n else: \n rectangle = canvas.create_rectangle(x+a/4, y+a/4, x+a/4*3, y+a/4*3, fill=\"\", width=a/20)\n \n carpet(a/2, x, y)\n carpet(a/2, x+a/4*2, y)\n carpet(a/2, x, y+a/4*2)\n carpet(a/2,x+a/4*2,y+a/4*2)\n\n\ncarpet(600, 0, 0)\n\nroot.mainloop()","repo_name":"green-fox-academy/peter-keller-python-javascript","sub_path":"Week-03/day-05/square_grid.py","file_name":"square_grid.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"3354336780","text":"#Status: All Cases passed\n#Since constraints were way too small, I didn't bother optimizing the algorithm & code\n\nimport math;\n\ndef special_problem_count (chapters, problem_count, prob_per_page):\n\tindex = 0;\n\tspecial = 0;\n\n\tfor ch in range (1, chapters+1):\n\t\tpages_reqd = math.ceil (problem_count [ch-1] / prob_per_page);\n\t\tfp, lp = 1, min (prob_per_page, problem_count [ch-1]);\n\n\t\twhile (pages_reqd):\n\t\t\tindex += 1;\n\t\t\tpages_reqd -= 1;\n\t\t\tif (index <= lp and index >= fp): special += 1;\n\n\t\t\tfp = lp+1;\n\t\t\tlp = min (lp + prob_per_page, problem_count [ch-1]);\n\n\treturn special;\n\nchapters, prob_per_page = [int (i) for i in input ().split ()];\nproblem_count = [int (i) for i in input ().split ()];\n\nprint (special_problem_count (chapters, problem_count, prob_per_page));\n","repo_name":"duaraghav8/Hackerrank-Problems","sub_path":"lisas_handbook.py","file_name":"lisas_handbook.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"42"} +{"seq_id":"31871669695","text":"import configparser\n\n\nclass cfgMaker:\n def cfg(self, datas, root):\n config = configparser.RawConfigParser()\n config.optionxform = str\n config['PROJECT'] = {'PROJECT_NAME': 'crowl',\n 'START_URL': datas[0]}\n config['CRAWLER'] = {'USER_AGENT': 'Crowl (+https://www.crowl.tech/)',\n 'ROTATE_USER_AGENTS': False,\n 'DOWNLOAD_DELAY': 0.5,\n 'CONCURRENT_REQUESTS': datas[1]}\n config['EXTRACTION'] = {'LINKS': True,\n 'LINKS_UNIQUE': False,\n 'CONTENT': True,\n 'DEPTH': datas[2],\n 'MAX_REQUESTS': 20000,\n 'CHECK_LANG': datas[3],\n 'SURFER': datas[4]\n }\n config['OUTPUT'] = {'crowl.CrowlCsvPipeline': 100}\n\n with open(root + '/config.ini', 'w') as configfile:\n config.write(configfile)\n","repo_name":"drogbadvc/crawlit","sub_path":"components/ConfigMaker.py","file_name":"ConfigMaker.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"42"} +{"seq_id":"36371945629","text":"def contains_digits(a,b):\n\td_a = sorted(list(str(a)))\n\td_b = sorted(list(str(b)))\n\treturn d_a == d_b\n\n\n\nfor i in range(10,1000000):\n\tfor k in range(2,7):\n\t\tif not contains_digits(i,k*i):\n\t\t\tbreak\n\telse:\n\t\tprint(i)\n\t\tfor k in range(2,7):\n\t\t\tprint(i*k)\n\t\tbreak","repo_name":"RobertAlden/Python","sub_path":"ProjectEuler/problem52.py","file_name":"problem52.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"13289233205","text":"#!/usr/bin/env python\n\n\"\"\"Create a new CDR action or modify an existing one.\n\"\"\"\n\nfrom cdrcgi import Controller\n\n\nclass Control(Controller):\n \"\"\"Top-level logic for editing interface.\"\"\"\n\n EDIT_ACTIONS = \"EditActions.py\"\n SUBMENU = \"Action Menu\"\n DELETE = \"Delete Action\"\n SAVE_CHANGES = \"Save Changes\"\n SAVE_NEW = \"Save New Action\"\n\n def delete(self):\n \"\"\"Delete the current action and return to the parent menu.\"\"\"\n self.action.delete(self.session)\n self.return_to_actions_menu(self.action.name)\n\n def populate_form(self, page):\n \"\"\"Add the field sets and custom style rules to the page.\n\n Pass:\n page - HTMLPage object to be filled out\n \"\"\"\n\n page.form.append(page.hidden_field(\"action\", self.action.name or \"\"))\n fieldset = page.fieldset(\"Action Identification\")\n fieldset.append(page.text_field(\"name\", value=self.action.name))\n opts = dict(value=self.action.comment, rows=5)\n fieldset.append(page.textarea(\"comment\", **opts))\n page.form.append(fieldset)\n fieldset = page.fieldset(\"Options\")\n label = \"Permissions set per doctype?\"\n opts = dict(value=\"doctype-specific\", label=label)\n if self.action.doctype_specific == \"Y\":\n opts[\"checked\"] = True\n fieldset.append(page.checkbox(\"options\", **opts))\n page.form.append(fieldset)\n\n def return_to_actions_menu(self, deleted=None):\n \"\"\"Go back to the menu listing all the CDR actions.\"\"\"\n\n opts = dict(deleted=deleted) if deleted else {}\n self.navigate_to(self.EDIT_ACTIONS, self.session.name, **opts)\n\n def run(self):\n \"\"\"Override base class so we can handle the extra buttons.\"\"\"\n\n try:\n if self.request == self.DELETE:\n return self.delete()\n elif self.request in (self.SAVE_CHANGES, self.SAVE_NEW):\n return self.save()\n elif self.request == self.SUBMENU:\n return self.return_to_actions_menu()\n except Exception as e:\n self.bail(f\"Failure: {e}\")\n Controller.run(self)\n\n def save(self):\n \"\"\"Save the new or modified action object.\"\"\"\n\n self.action.name = self.name\n self.action.comment = self.comment\n self.action.doctype_specific = \"Y\" if self.doctype_specific else \"N\"\n if self.action.id:\n self.action.modify(self.session)\n self.subtitle = f\"Action {self.name!r} successfully updated\"\n else:\n self.action.add(self.session)\n self.subtitle = f\"Action {self.name!r} successfully added\"\n self.action = self.session.get_action(self.name)\n self.show_form()\n\n @property\n def action(self):\n \"\"\"Object for the CDR action being edited/created.\"\"\"\n\n if not hasattr(self, \"_action\"):\n name = self.fields.getvalue(\"action\")\n if name:\n self._action = self.session.get_action(name)\n else:\n self._action = self.session.Action(\"\", \"N\")\n return self._action\n\n @action.setter\n def action(self, value):\n \"\"\"Allow replacement after a save.\"\"\"\n self._action = value\n\n @property\n def buttons(self):\n \"\"\"Add our custom navigation buttons.\"\"\"\n\n if not hasattr(self, \"_buttons\"):\n self._buttons = [self.SUBMENU, self.ADMINMENU, self.LOG_OUT]\n if self.action.id:\n self._buttons.insert(0, self.DELETE)\n self._buttons.insert(0, self.SAVE_CHANGES)\n else:\n self._buttons.insert(0, self.SAVE_NEW)\n return self._buttons\n\n @property\n def comment(self):\n \"\"\"Get the comment value from the form field.\"\"\"\n return self.fields.getvalue(\"comment\")\n\n @property\n def doctype_specific(self):\n \"\"\"True if permissions for this action are doctype-specific.\"\"\"\n\n if not hasattr(self, \"_doctype_specific\"):\n if \"doctype-specific\" in self.fields.getlist(\"options\"):\n self._doctype_specific = True\n else:\n self._doctype_specific = False\n return self._doctype_specific\n\n @property\n def name(self):\n \"\"\"Current value of the form's name field.\"\"\"\n return self.fields.getvalue(\"name\")\n\n @property\n def subtitle(self):\n \"\"\"Dynamic string for display under the main banner.\"\"\"\n\n if not hasattr(self, \"_subtitle\"):\n if self.name:\n self._subtitle = f\"Editing {self.name!r} action\"\n else:\n self._subtitle = \"Adding New Action\"\n return self._subtitle\n\n @subtitle.setter\n def subtitle(self, value):\n \"\"\"Provide status information after a save.\"\"\"\n self._subtitle = value\n\n\nif __name__ == \"__main__\":\n \"\"\"Don't execute the script if we've been loaded as a module.\"\"\"\n Control().run()\n","repo_name":"NCIOCPL/cdr-admin","sub_path":"Inetpub/wwwroot/cgi-bin/cdr/EditAction.py","file_name":"EditAction.py","file_ext":"py","file_size_in_byte":4939,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"42"} +{"seq_id":"26677532638","text":"\"\"\"Replace i, e, and \\pi with \\iunit, \\expe, and \\cpi respectively.\"\"\"\n\nimport re\nimport sys\n\n# for compatibility with Python 3\ntry:\n from itertools import izip\nexcept ImportError:\n izip = zip\n\nimport parentheses\nfrom utilities import writeout\nfrom utilities import readin\n\nEQ_STARTS = [\n r'\\begin{equation}',\n r'\\begin{equation*}',\n r'\\begin{align}',\n r'\\begin{eqnarray}',\n r'\\begin{eqnarray*}',\n r'\\begin{multline}',\n r'\\begin{multline*}']\nEQ_ENDS = [\n r'\\end{equation}',\n r'\\end{equation*}',\n r'\\end{align}',\n r'\\end{eqnarray}',\n r'\\begin{eqnarray*}',\n r'\\begin{multline}',\n r'\\begin{multline*}']\n\nIND_START = r'\\index{'\n\nNAME = 0\nSEEN = 1\n\nCASES_START = r'\\begin{cases}'\nCASES_END = r'\\end{cases}'\n\nEQMIX_START = r'\\begin{equationmix}'\nEQMIX_END = r'\\end{equationmix}'\n\nSTD_REGEX = r'.*?###open_(\\d+)###.*?###close_\\1###'\n\n\ndef main():\n if len(sys.argv) != 3:\n\n fname = \"ZE.1.tex\"\n ofname = \"ZES.tex\"\n\n else:\n\n fname = sys.argv[1]\n ofname = sys.argv[2]\n\n writeout(ofname, remove_special(readin(fname)))\n\n\ndef remove_special(content):\n \"\"\"Removes the excess pieces from the given content and returns the updated version as a string.\"\"\"\n\n # various flags that will help us keep track of what elements we are\n # inside of currently\n inside = {\n \"constraint\": [r'\\constraint{', False],\n \"substitution\": [r'\\substitution{', False],\n \"drmfnote\": [r'\\drmfnote{', False],\n \"drmfname\": [r'\\drmfname{', False],\n \"proof\": [r'\\proof{', False]\n }\n\n should_replace = False\n in_ind = False\n in_eq = False\n\n pi_pat = re.compile(r'(\\s*)\\\\pi(\\s*\\b|[aeiou])')\n # expe_kk = re.compile(r'(?:\\\\)\\b([^d\\\\]?\\W*)\\s*e\\s*\\^')\n # expe_pat = re.compile(r'(?:\\\\)?\\b([^d\\\\]?\\W*)\\s*e\\s*\\^')\n expe_kk = re.compile(r'(?0}',\n r'\\\\ZZ_{\\\\ge0}']\n\n spaces_pat = re.compile(r' {2,}')\n paren_pat = re.compile(r'\\(\\s*(.*?)\\s*\\)')\n\n dollar_pat = re.compile(r'(? bool:\n if x < 0: return False\n\n num, mirrorx = x, 0\n while num > 0:\n mirrorx = mirrorx*10 + num%10\n num = num // 10\n \n return x == mirrorx","repo_name":"JunYe1993/Python-Starter","sub_path":"Python3/LeetCode/0009-Palindrome_Number/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"15356027328","text":"def insertSort(arr):\n for i in range(1, len(arr)):\n key = arr[i]\n j = i - 1\n while (j >= 0 and arr[j] > key):\n arr[j + 1] = arr[j]\n j -= 1\n arr[j + 1] = key\n\ndef main():\n A = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 4]\n insertSort(A)\n print (A)\n\nmain()\n","repo_name":"Balieiro13/MAC0122","sub_path":"practice/insertsort.py","file_name":"insertsort.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"23450315429","text":"import sys\n\nfrom twisted.internet import error, protocol\n\nclass ProcessIOProtocol(protocol.ProcessProtocol):\n\n def __init__(self, stdin, process_success_cb, process_failure_cb, print_stderr=False):\n self.stdin = stdin\n self.stdout = ''\n self.stderr = ''\n self.status = None\n self.print_stderr = print_stderr\n\n self.process_success_cb = process_success_cb\n self.process_failure_cb = process_failure_cb\n\n def connectionMade(self):\n self.transport.write(self.stdin)\n self.transport.closeStdin()\n\n def outReceived(self, data):\n self.stdout += data\n\n def errReceived(self, data):\n self.stderr += data\n if self.print_stderr:\n sys.stderr.write(data)\n\n def processEnded(self, reason):\n if isinstance(reason.value, error.ProcessDone):\n self.process_success_cb(self.stdout, self.stderr)\n else:\n self.process_failure_cb(self.stdout, self.stderr)\n\n\n","repo_name":"Griffon26/scrumboardtracker","sub_path":"scrumboardtracker/processioprotocol.py","file_name":"processioprotocol.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"42"} +{"seq_id":"28348646636","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n__author__ = 'sunny'\r\n__mtime__ = '2017/2/14'\r\n# code is far away from bugs with the god animal protecting\r\n I love animals. They taste delicious.\r\n ┏┓ ┏┓\r\n ┏┛┻━━━┛┻┓\r\n ┃ ☃ ┃\r\n ┃ ┳┛ ┗┳ ┃\r\n ┃ ┻ ┃\r\n ┗━┓ ┏━┛\r\n ┃ ┗━━━┓\r\n ┃ ┣┓\r\n ┃  ┏┛\r\n ┗┓┓┏━┳┓┏┛\r\n ┃┫┫ ┃┫┫\r\n ┗┻┛ ┗┻┛\r\n\"\"\"\r\nimport time\r\nimport json\r\n\r\nimport tornado\r\nfrom tornado import web, gen, ioloop\r\nfrom Controller.DbHandler import DB_Handler\r\nfrom Common.MyExecption import ApiException\r\nfrom Common.StaticFunc import ErrorCode, Set_return_dicts\r\nimport Common.config as config\r\nfrom Common.Common import GetStoreId\r\n# 这个并发库在python3自带在python2需要安装sudo pip install futures\r\nfrom concurrent.futures import ThreadPoolExecutor\r\n\r\n\r\nclass Base_Handler(web.RequestHandler):\r\n def __init__(self, application, request, **kwargs):\r\n super(Base_Handler, self).__init__(application, request, **kwargs)\r\n self.executor = ThreadPoolExecutor(10)\r\n self.__keyWord = None\r\n self.func = None\r\n self.dbhelp = DB_Handler()\r\n # 请求ip\r\n self.spbill_create_ip = self.request.remote_ip\r\n self.deviceName = self.request.headers.get(\"Devicename\", \"\")\r\n self.connect = config.connect\r\n try:\r\n self.storeId = GetStoreId()\r\n except:\r\n self.storeId = None\r\n\r\n # 设置头部\r\n def set_default_headers(self):\r\n self.set_header('Access-Control-Allow-Origin', '*')\r\n self.set_header('Access-Control-Allow-Headers', '*')\r\n self.set_header('Content-type', 'application/json')\r\n\r\n # 获取表单内容\r\n def get_all_argument(self):\r\n argument = self.request.arguments\r\n result = dict()\r\n for name, value in argument.items():\r\n if len(value) == 1:\r\n result[name] = value[0].decode()\r\n else:\r\n for data in value:\r\n data = data.decode()\r\n result[name] = value\r\n\r\n return result\r\n\r\n @web.asynchronous\r\n @gen.coroutine\r\n def get(self, *args, **kwargs):\r\n try:\r\n # 异步\r\n yield tornado.gen.Task(ioloop.IOLoop.instance().add_timeout, time.time())\r\n if args != ():\r\n self.__keyWord = args[0]\r\n\r\n get_Data = self.get_all_argument()\r\n # print ('get:',get_Data)\r\n if len(args) > 1:\r\n get_Data['args'] = list(args)\r\n get_Data['args'].remove(self.__keyWord)\r\n\r\n checkSheBei = self.dbhelp.CheckSheBei(self.spbill_create_ip, self.deviceName)\r\n if checkSheBei == False:\r\n raise ApiException(ErrorCode.UserStateError)\r\n elif checkSheBei == 2:\r\n raise ApiException(ErrorCode.UserStateWaitError)\r\n\r\n if self.__keyWord:\r\n # result = self.func(self.__keyWord,get_Data)\r\n result = yield self.func(self.__keyWord, get_Data)\r\n else:\r\n result = yield self.func(get_Data)\r\n # result = self.func(get_Data)\r\n\r\n TransmissionResult = json.dumps(result)\r\n # print ('get_send:{}'.format(TransmissionResult))\r\n\r\n self.write(TransmissionResult)\r\n self.finish()\r\n\r\n except ApiException as e:\r\n self.write(json.dumps(Set_return_dicts(forWorker=e.error_result['forWorker'],\r\n code=e.error_result['errorCode'],\r\n forUser=e.error_result['forUser'])))\r\n self.finish()\r\n\r\n except:\r\n self.write(json.dumps(Set_return_dicts(forWorker='不合法的参数',\r\n code=ErrorCode.ParameterError,\r\n forUser='请求超时')))\r\n\r\n self.finish()\r\n\r\n @web.asynchronous\r\n @gen.coroutine\r\n def post(self, *args, **kwargs):\r\n try:\r\n # 异步\r\n yield tornado.gen.Task(ioloop.IOLoop.instance().add_timeout, time.time())\r\n if args != ():\r\n self.__keyWord = args[0]\r\n\r\n # json传输\r\n try:\r\n get_Data = json.loads(self.request.body.decode())\r\n except:\r\n try:\r\n get_Data = self.get_all_argument()\r\n except:\r\n raise ApiException(ErrorCode.JsonError)\r\n # print ('post:',get_Data)\r\n\r\n checkSheBei = self.dbhelp.CheckSheBei(self.spbill_create_ip, self.deviceName)\r\n if checkSheBei == False:\r\n raise ApiException(ErrorCode.UserStateError)\r\n elif checkSheBei == 2:\r\n raise ApiException(ErrorCode.UserStateWaitError)\r\n\r\n if self.__keyWord:\r\n result = yield self.func(self.__keyWord, get_Data)\r\n # result = self.func(self.__keyWord,get_Data)\r\n else:\r\n result = yield self.func(get_Data)\r\n # result = self.func(get_Data)\r\n\r\n TransmissionResult = json.dumps(result)\r\n # print ('post_send{}'.format(TransmissionResult))\r\n self.write(TransmissionResult.encode('utf-8'))\r\n self.finish()\r\n\r\n except ApiException as e:\r\n self.write(json.dumps(Set_return_dicts(forWorker=e.error_result['forWorker'],\r\n code=e.error_result['errorCode'],\r\n forUser=e.error_result['forUser'])))\r\n\r\n self.finish()\r\n","repo_name":"jinshang123/GitHub","sub_path":"Controller/Api/BaseHandler.py","file_name":"BaseHandler.py","file_ext":"py","file_size_in_byte":5978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"26455648020","text":"from pywebcopy import save_webpage\n\nfrom .handler_base import HandlerBase\n\n\nclass ClonePageHandlerSettings:\n def __init__(self, enabled, save_path):\n self.enabled = enabled\n self.save_path = save_path\n\n\nclass ClonePageHandler(HandlerBase):\n def __init__(self, settings=None):\n super().__init__(settings)\n\n def is_applicable(self, crawled_data):\n return self.settings.enabled and \"full_website_name\" in crawled_data\n\n def apply(self, crawled_data):\n save_webpage(\n # url of the website\n url=crawled_data[\"full_website_name\"],\n # folder where the copy will be saved\n project_folder=self.settings.save_path,\n bypass_robots=True,\n debug=False,\n open_in_browser=False,\n delay=None,\n threaded=False,\n )\n","repo_name":"wipkirill/fetch-tool","sub_path":"src/handler/clone_page_handler.py","file_name":"clone_page_handler.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"12346697433","text":"\"\"\" Functions for working with VCF files. Each function either takes a VCF or\na line from a VCF file\n\nJeff Hsu\n\"\"\"\n\nfrom itertools import cycle\nimport functools\nimport numpy as np\nimport pandas as pd\nfrom .genotype import Genotype\n\n\ndef parse_chr(entry):\n try:\n chrom = int(entry.lstrip(\"chr\"))\n return(chrom)\n except ValueError:\n print(\"Chromosomes must be numeric\")\n\n\n\ndef parse_geno(entry, GT=0):\n \"\"\" \n :TODO \n Need to somehow keep phase, maybe use multi_index, but only\n works if haplotype is contigous across whole section. Maybe\n groups to denote haplotype regions?\n \"\"\"\n try:\n g = entry.split(\":\")[GT]\n except:\n g = entry.split(\":\")[0]\n if g == \"0/0\" or g == \"0|0\" or g == '0':\n return 0\n elif g == \"1/1\" or g == \"1|1\" or g=='1':\n return 2\n elif g == \"0/1\" or g == \"0|1\" or g == \"1/0\" or g == \"1|0\":\n return 1\n else:\n return np.NaN\n\n\nclass VCF(Genotype):\n \"\"\" A pandas dataframe wrapper for VCF files.\n \"\"\"\n\n\n def __init__(self, vcf_file, chunksize = None, allelic_ratio=False,\n haplotypes = False, chrom_converter=None):\n \"\"\" Initialize with a VCF file with genotyping information\n \"\"\"\n fh = open(vcf_file)\n meta, samples, num_meta = self._skip_headers(fh)\n fh.close()\n self._meta = meta\n self._parse_meta()\n self.samples = samples\n self.info_dict = []\n sex_chromosomes = ['X', 'Y']\n convertor = {}\n #convertor = dict((k + 9 , parse_geno) for k in range(len(samples)))\n #convertor = dict((k + 9 , allele_ratio) for k in range(len(samples)))\n if chrom_converter:\n convertor[0] = chrom_converter\n #convertor[\"INFO\"] = self._parse_info\n self.vcf = pd.read_table(vcf_file, sep=\"\\t\",\n skiprows = xrange(num_meta),\n converters = convertor,\n chunksize = chunksize,\n )\n pg=functools.partial(parse_geno,GT = self.vcf.ix[0,8].split(\":\").index(\"GT\"))\n self.geno = self.vcf.ix[:,9:].applymap(pg)\n #self.vcf.rename(columns = {'#CHROM': 'CHROM'}, inplace=True)\n rsID = self.vcf[\"ID\"]\n novel = [str(i) + \"_\" + str(j) + \"_\" + str(k) for (i, j, k)\\\n in zip(list(self.vcf[\"#CHROM\"][rsID==\".\"]),\n list(self.vcf[\"POS\"][rsID == \".\"]),\n list(self.vcf[\"ALT\"][rsID == \".\"])\n )\n ]\n self.novel = novel\n rsID.loc[rsID == \".\"] = np.asarray(novel)\n self.vcf.index = pd.Index(rsID)\n self.geno.index = self.vcf.index\n info_dict = self._split_info(self.vcf.INFO)\n # Parsing the INFO\n def flag_parse(info_dict, key):\n try:\n info_dict[key]\n return(True)\n except KeyError:\n return(False)\n\n def empty_field(info_dict, key):\n try:\n return(info_dict[key])\n except KeyError:\n return(np.NaN)\n\n def string_field(info_dict, key):\n try:\n return(info_dict[key])\n except KeyError:\n return('')\n\n # Need a better way to do this\n for i in self.info:\n if i[2] == np.bool:\n info_field = pd.Series(np.asarray(\n [flag_parse(k, i[0]) for k in info_dict],\n dtype = i[2]), index = self.vcf.index)\n #self.vcf[i[0]] = info_field\n elif i[1] > 1:\n # :TODO This needs to be fixed\n pass\n elif i[2] == np.float64 or i[2] == np.int:\n # :FIXME float an integer\n info_field = pd.Series(np.asarray(\n [empty_field(k, i[0]) for k in info_dict],\n dtype = np.float64), index = self.vcf.index)\n self.vcf[i[0]] = info_field\n elif i[2] == '|S20':\n info_field = pd.Series(np.asarray(\n [string_field(k, i[0]) for k in info_dict],\n dtype = i[2]), index = self.vcf.index)\n elif i[0] == 'Dels':\n # For some reason this is null in some fields\n pass\n elif i[0] in ['CIEND', 'CIPOS', 'END', 'HOMLEN', 'HOMSEQ',\n 'SVLEN', 'SVTYPE', 'AA']:\n # :TODO This needs to be fixed \n pass\n else:\n info_field = pd.Series(np.asarray([k[i[0]] for k in info_dict],\n dtype = i[1]),\n index = self.vcf.index)\n #self.vcf[i[0]] = info_field\n del self.vcf['INFO']\n del self.vcf['ID']\n # Parse GENO\n def _parse_haplotype(entry):\n g = entry.split(\":\")[0]\n try:\n g = g.split(\"|\")\n return((int(g[0]), int(g[1])))\n except ValueError:\n return np.NaN\n except KeyError:\n print(\"Welp\")\n\n\n def _allele_ratio(entry):\n try:\n t_i = sum([int(i) for i in\\\n entry.split(\":\")[1].split(\",\")])\n alt_allele = int(entry.split(\":\")[1].split(\",\")[1])\n allele_ratio = alt_allele/float(t_i)\n return allele_ratio\n except IndexError:\n return np.NaN\n except ValueError:\n return np.NaN\n except ZeroDivisionError:\n return np.NaN\n\n # Create new dataframes for haplotypes and allele ratios\n if 'AD' in self.gformat:\n # Parse out allele ratios automatically\n self.ar = pd.DataFrame({'temp': np.zeros(len(self.vcf.index),\n dtype=np.float)},\n index = self.vcf.index)\n if haplotypes:\n def bicycle(iterable, repeat=1):\n for item in iterable:\n for _ in xrange(repeat):\n yield item\n\n haplo_i = cycle([1,2])\n haplo_index = [(i, haplo_i.next())\\\n for i in bicycle(self.samples, repeat=2)]\n haplo_index = pd.MultiIndex.from_tuples(haplo_index, names =\\\n ['Individual',\n 'Allele'])\n self.haps = pd.DataFrame(np.zeros((len(self.vcf.index),\n 2*len(self.samples)),\n dtype = np.float),\n columns = haplo_index,\n index = self.vcf.index\n )\n \"\"\"\n for ind in self.samples:\n if haplotypes:\n haps = [_parse_haplotype(i) for i in self.vcf[ind]]\n self.haps[(ind,1)] =\\\n np.asarray([i[0] for i in haps], dtype = np.float)\n self.haps[(ind,2)] =\\\n np.asarray([i[0] for i in haps], dtype = np.float)\n del haps\n\n else:\n geno = np.asarray([_parse_geno(i) for i in self.vcf[ind]],\n dtype = np.float64)\n if 'AD' in self.gformat:\n a_r = np.asarray([_allele_ratio(i) for i in self.vcf[ind]],\n dtype = np.float64)\n self.ar[ind] = a_r\n if haplotypes:\n pass\n else:\n self.vcf[ind] = geno\n \"\"\"\n\n if 'AD' in self.gformat:\n del self.ar['temp']\n\n if haplotypes:\n pass\n\n def _parse_meta(self):\n \"\"\" Parses meta information and returns a list of the INFO and FORMAT\n fields.\n\n Okay so all VCF files are slightly different. \n Why is the number sometimes a letter? \n :TODO work on edge cases\n \"\"\"\n convert = {\n 'Integer': np.int,\n 'Float': np.float64,\n 'Flag': np.bool,\n 'String': '|S20',\n }\n self.info = []\n self.gformat = []\n meta_lines = self._meta.split(\"\\n\")\n meta_lines = [i[2:] for i in meta_lines]\n for line in meta_lines:\n if line[0:4] == 'INFO':\n line = line.lstrip(\"INFO=<\").rstrip(\">\")\n line = line.split(\",\")\n try:\n self.info.append((line[0].split(\"=\")[1],\n line[1].split(\"=\")[1],\n convert[line[2].split(\"=\")[1]]))\n except KeyError:\n print(line)\n print('Improperly formatted meta information')\n #info.append(line[line.find(' d[snp][0] and newvcf.ix[n,0].endswith(chrom):\n newrow = newvcf.ix[n,:]\n newrow.ix[1] = d[snp][0]\n newrow.ix[2] = d[snp][2]\n newrow.ix[3] = d[snp][1]\n newrow.ix[4] = '.'\n newrow.ix[5] = '.'\n newrow.ix[6] = 'GT'\n for i in range(7,len(newrow)):\n newrow.ix[i] = '1/1'\n to_add[n+m]=pd.DataFrame(newrow).transpose()\n break\n elif n == newvcf.shape[0]-1:\n newrow = newvcf.ix[n,:]\n newrow.ix[1] = d[snp][0]\n newrow.ix[2] = d[snp][2]\n newrow.ix[3] = d[snp][1]\n newrow.ix[4] = '.'\n newrow.ix[5] = '.'\n newrow.ix[6] = 'GT'\n for i in range(7,len(newrow)):\n newrow.ix[i] = '1/1'\n to_add[n+m+1]=pd.DataFrame(newrow).transpose()\n break\n\n for i in sorted(to_add.keys()):\n newvcf = pd.concat([newvcf.ix[:i,:],to_add[i],newvcf.ix[i:,:]])\n\n newvcf = newvcf[newvcf['POS'].map(lambda x: x not in dels)]\n\n newobj = deepcopy(self)\n newobj.vcf = newvcf\n #pg = functools.partial(parse_geno,GT = self.vcf.ix[0,6].split(\":\").index(\"GT\"))\n newobj.geno = newobj.vcf.ix[:,7:].applymap(parse_geno, \n GT=self.vcf.ix[0,6].split(\":\").index(\"GT\"))\n return newobj\n\n\ndef pos_line_convert(line):\n \"\"\" Convert chr:pos into a integer\n \"\"\"\n line = line.rstrip(\"\\n\").split(\"\\t\")\n try:\n return int(line[1]) + (int(line[0].lstrip(\"chr\"))*200000000)\n except ValueError:\n print(\"Malformed VCF file\")\n\n\ndef count_alleles(line):\n line = line.rstrip(\"\\n\").split(\"\\t\")\n line = line[9:]\n def no_counts(data):\n try:\n allele_count = tuple([int(i) for i in\\\n data.split(\":\")[1].split(\",\")])\n return allele_count\n except IndexError:\n return None\n except ValueError:\n return None\n allele_counts = [no_counts(i) for i in line]\n return(allele_counts)\n\n\n\ndef is_indel(line):\n \"\"\" Returns if a line is an indel or not\n \"\"\"\n line = line.rstrip(\"\\n\").split(\"\\t\")\n if len(line[3]) > 1 or len(line[4]) > 1:\n return True\n else:\n return False\n","repo_name":"jeffhsu3/genda","sub_path":"genda/formats/panVCF.py","file_name":"panVCF.py","file_ext":"py","file_size_in_byte":22138,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"42"} +{"seq_id":"17441920579","text":"\"\"\"\nLigature Finder\n===============\n\nLooks for ligature glyphs matching a glyph selector and tries to write ligature rules\nwhich compose them. e.g. given::\n\n LoadPlugin LigatureFinder;\n Routine ligatures {\n LigatureFinder /kinzi.*/;\n };\n\nIf you have glyphs `kinzi_ai`, `kinzi` and `ai`, this will write a rule\n`Substitute kinzi ai -> kinzi_ai;`.\n\"\"\"\n\nimport fontFeatures\nfrom . import FEZVerb\n\nPARSEOPTS = dict(use_helpers=True)\nGRAMMAR = \"\"\"\n?start: action\naction: glyphselector\n\"\"\"\nimport re\n\nVERBS = [\"LigatureFinder\"]\n\nclass LigatureFinder(FEZVerb):\n def action(self, args):\n parser = self.parser\n ligatures = sorted(args[0].resolve(parser.fontfeatures, parser.font),key=lambda a:len(a))\n rv = []\n glyphnames = \"|\".join(sorted(parser.font.keys(),key=lambda a:len(a)))\n for l in ligatures:\n for liglen in range(5,0,-1):\n ligre = \"^\" + (\"(\"+glyphnames+\")_\") * liglen + \"(\" + glyphnames + \")$\"\n m = re.match(ligre, l)\n if m:\n rv.append(fontFeatures.Substitution(\n [ [c] for c in m.groups()], replacement=[[l]]\n ))\n break\n return [fontFeatures.Routine(rules=rv)]\n","repo_name":"googlefonts/fez","sub_path":"lib/fez/LigatureFinder.py","file_name":"LigatureFinder.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"42"} +{"seq_id":"13587855366","text":"\"\"\"Script for pre-processing raw data\"\"\"\n\nimport logging\nimport argparse\nfrom data_preprocessing import TriLetterExtractor, process_datasets_to_file\nfrom tokenizer import TwinBertTokenizer\nfrom transformers import BertTokenizer\n\nlogger = logging.getLogger(__name__)\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--teacher_data_path', type=str, default=\"../../../data/QK_Graph/QK_ANN_Neighbor_Teacher.tsv\", help=\"Path to teacher data\")\nparser.add_argument('--teacher_data_save_path', type=str, default=\"../data/QK_ANN_Neighbor/Teacher/\", help=\"Path to save teacher data\")\nparser.add_argument('--teacher_eval_data_path', type=str, default=\"../../../data/QK_Graph/QK_ANN_Neighbor_Teacher.tsv\", help=\"Path to teacher eval data\")\nparser.add_argument('--teacher_eval_data_save_path', type=str, default=\"../data/QK_ANN_Neighbor/Teacher_Eval/\", help=\"Path to save teacher eval data\")\nparser.add_argument('--validation_data_path', type=str, default=\"../../../data/QK_Graph/QK_ANN_Neighbor_Validation.tsv\", help=\"Path to validation data\")\nparser.add_argument('--validation_data_save_path', type=str, default=\"../data/QK_ANN_Neighbor/Validation/\", help=\"Path to save validation data\")\nparser.add_argument('--vocab_path', type=str, default=\"../config/l3g.txt\", help=\"Path to vocab file, only used by triletter tokenizer\")\nparser.add_argument('--chunksize', type=int, default=1e6, help=\"Pandas loading chunksize\")\nparser.add_argument('--skip_chunk', type=int, default=0, help=\"Number of chunks to skip\")\nparser.add_argument('--n_chunk', type=int, default=0, help=\"Number of chunks to process\")\nparser.add_argument('--tokenizer_type', type=str, default=\"bpe\", help=\"Tokenizer type\")\nparser.add_argument('--max_n_letters', type=int, default=20, help=\"Only used by triletter tokenizer\")\nparser.add_argument('--max_seq_len', type=int, default=16, help=\"Max length of sequence\")\nparser.add_argument('--tokenizer_name', type=str, default=\"bert-base-uncased\", help=\"Pre-trained Bert tokenizer name\")\nparser.add_argument('--a_fanouts', type=str, default=\"3\", help=\"a fanouts\")\nparser.add_argument('--b_fanouts', type=str, default=\"3\", help=\"b fanouts\")\nargs = parser.parse_args()\n\n\ndef main():\n logging.basicConfig(\n format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\",\n datefmt=\"%m/%d/%Y %H:%M:%S\",\n level=logging.INFO,\n )\n\n if args.tokenizer_type == \"triletter\":\n extractor = TriLetterExtractor(args.vocab_path)\n else:\n extractor = BertTokenizer.from_pretrained(args.tokenizer_name)\n\n try:\n process_datasets_to_file(args.teacher_data_path, extractor, args.teacher_data_save_path, max_seq_len=args.max_seq_len, max_n_letters=args.max_n_letters, int_label=False, chunksize=args.chunksize, a_fanouts=list(map(int, args.a_fanouts.split(\",\"))), b_fanouts=list(map(int, args.b_fanouts.split(\",\"))), skip_chunk=args.skip_chunk, n_chunk=args.n_chunk)\n except Exception as e:\n logger.info(e)\n logger.info(\"Cannot load from raw teacher data\")\n\n\n try:\n process_datasets_to_file(args.teacher_eval_data_path, extractor, args.teacher_eval_data_save_path, max_seq_len=args.max_seq_len, max_n_letters=args.max_n_letters, int_label=False, chunksize=args.chunksize, top=1000000, convert_to_int=True, a_fanouts=list(map(int, args.a_fanouts.split(\",\"))), b_fanouts=list(map(int, args.b_fanouts.split(\",\"))), n_chunk=args.n_chunk)\n except Exception as e:\n logger.info(e)\n logger.info(\"Cannot load from raw teacher eval data\")\n\n\n try:\n print(\"Start processing validation data\")\n process_datasets_to_file(args.validation_data_path, extractor, args.validation_data_save_path, max_seq_len=args.max_seq_len, max_n_letters=args.max_n_letters, int_label=True, chunksize=args.chunksize, a_fanouts=list(map(int, args.a_fanouts.split(\",\"))), b_fanouts=list(map(int, args.b_fanouts.split(\",\"))))\n except Exception as e:\n logger.info(e)\n logger.info(\"Cannot load from raw validation data\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"microsoft/TextGNN","sub_path":"src/create_tf_record_data.py","file_name":"create_tf_record_data.py","file_ext":"py","file_size_in_byte":4036,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"42"} +{"seq_id":"13665470021","text":"from rdflib import Graph, URIRef, BNode, Literal, Namespace\nfrom rdflib.namespace import RDF, FOAF\n\ndef createRDF(list_of_notaries, list_of_translators):\n\n notaryClass = URIRef(\"https://www.merriam-webster.com/dictionary/notary%20public\")\n translatorClass = URIRef(\"https://www.merriam-webster.com/dictionary/translator\")\n addressClass = URIRef(\"https://dictionary.cambridge.org/dictionary/english/address\")\n gg = Graph()\n gg.add((notaryClass, RDF.type, FOAF.Person))\n gg.add((translatorClass, RDF.type, FOAF.Person))\n\n for i in range(5):\n notary = list_of_notaries[i]\n identificator = str(notary[\"firstName\"] +\"_\"+ notary[\"lastName\"]).replace(\" \",\"_\")\n # print(identificator)\n address =BNode()\n person_notary = URIRef(\"http://example.org/people/\"+identificator)\n gg.add((person_notary, RDF.type, notaryClass))\n gg.add((person_notary, FOAF.id, Literal(notary[\"id\"])))\n gg.add((person_notary, FOAF.firstName, Literal(notary[\"firstName\"])))\n gg.add((person_notary, FOAF.lastName, Literal(notary[\"lastName\"])))\n gg.add((person_notary, FOAF.phone, Literal(notary[\"phoneNo\"])))\n gg.add((person_notary, FOAF.authorizationNumber, Literal(notary[\"authorisation_no\"])))\n gg.add((person_notary, FOAF.schedule, Literal(notary[\"schedule\"])))\n gg.add((person_notary, FOAF.services, Literal(notary[\"services\"])))\n gg.add((person_notary, FOAF.documents, Literal(\"[]\")))\n gg.add((address, FOAF.county, Literal(notary[\"county\"])))\n gg.add((address, FOAF.locality, Literal(notary[\"locality\"])))\n gg.add((address, FOAF.city, Literal(notary[\"city\"])))\n gg.add((address, FOAF.street, Literal(notary[\"address\"])))\n gg.add((address, FOAF.country, Literal(notary[\"country\"])))\n gg.add((address, FOAF.streetNr, Literal(notary[\"streetNumber\"])))\n gg.add((address, FOAF.zipCode, Literal(notary[\"zipCode\"])))\n gg.add((address, FOAF.others, Literal(notary[\"others\"])))\n gg.add((person_notary, FOAF.address, address))\n #TO DO DOCUMENTS\n\n\n for i in range(5):\n translator = list_of_translators[i]\n identificator = str(translator[\"firstName\"] + \"_\" + translator[\"lastName\"]).replace(\" \", \"_\")\n\n address =BNode()\n person_translator = URIRef(\"http://example.org/people/\" + identificator)\n gg.add((person_translator, RDF.type, translatorClass))\n gg.add((person_translator, FOAF.id, Literal(translator[\"id\"])))\n gg.add((person_translator, FOAF.firstName, Literal(translator[\"firstName\"])))\n gg.add((person_translator, FOAF.lastName, Literal(translator[\"lastName\"])))\n gg.add((person_translator, FOAF.phone, Literal(translator[\"phoneNo\"])))\n gg.add((person_translator, FOAF.authorizationNumber, Literal(translator[\"authorisation_no\"])))\n gg.add((person_translator, FOAF.schedule, Literal(translator[\"schedule\"])))\n gg.add((person_translator, FOAF.services, Literal(translator[\"services\"])))\n gg.add((person_translator, FOAF.documents, Literal(\"[]\")))\n gg.add((address, FOAF.county, Literal(translator[\"county\"])))\n gg.add((address, FOAF.locality, Literal(translator[\"locality\"])))\n gg.add((address, FOAF.city, Literal(translator[\"city\"])))\n gg.add((address, FOAF.street, Literal(translator[\"address\"])))\n gg.add((address, FOAF.country, Literal(translator[\"country\"])))\n gg.add((address, FOAF.streetNr, Literal(translator[\"streetNumber\"])))\n gg.add((address, FOAF.zipCode, Literal(translator[\"zipCode\"])))\n gg.add((address, FOAF.others, Literal(translator[\"others\"])))\n gg.add((person_translator, FOAF.address, address))\n gg.add((person_translator, FOAF.languages, Literal(translator[\"languages\"])))\n\n file2 = open(\"output.txt\", \"wb\")\n file2.write(gg.serialize(format='turtle'))\n","repo_name":"Cati96/notis","sub_path":"convertCSVtoRDF/CreateRDF.py","file_name":"CreateRDF.py","file_ext":"py","file_size_in_byte":3899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"17285023728","text":"import polars as pl\nfrom scipy.stats import kruskal\n\n\nclass KruskalWallisTest:\n \"\"\"Kruskal-Wallis test: Use this test to compare the medians of three or more independent samples.\"\"\"\n\n def __init__(self, file_path, explanatory_attribute, response_attribute):\n \"\"\"_summary_\n\n Args:\n file_path (_type_): _description_\n explanatory_attribute (_type_): _description_\n response_attribute (_type_): _description_\n \"\"\"\n self.data = pl.read_csv(file_path)\n self.explanatory_attribute = explanatory_attribute\n self.response_attribute = response_attribute\n\n def run(self):\n \"\"\"Fit and run the Kruskal-Wallis model on the data.\"\"\"\n groups = [self.data[self.response_attribute][self.data[self.explanatory_attribute] == g]\n for g in self.data[self.explanatory_attribute].unique()]\n _, p_val = kruskal(*groups)\n return p_val\n\n def is_significant(self, alpha=0.05):\n \"\"\"Test the significance of the Kruskal-Wallis results.\n\n :param alpha: Significance level (Default value = 0.05)\n\n \"\"\"\n p_val = self.run()\n if p_val < alpha:\n return True\n else:\n return False\n","repo_name":"JosephWoodall/turbo-barnacle","sub_path":"src/inferential_statistics/kruskalWallisTest.py","file_name":"kruskalWallisTest.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"17759763030","text":"import random\nimport time\nimport threading\n\n# Utility functions\n\n# To represent players\n# TODO: use an Enum\ndef red():\n return -1\ndef black():\n return 1\ndef other_player(who):\n return -who\n\n# To represent pieces\ndef tile(i,j):\n return (i,j)\ndef player_piece(who):\n return (-1,who)\n\n\n# Additional functions to help the Position class\n\n# Represent the board as a one-dimensional array of length 16\n# rather than a 4x4 two-dimensional array,\n# Why?\n# * Speed\n# * We care about certain sets of locations, and nothing else\n# (adjacency and directions are irrelevant)\n\n\n# Encode a two-dimensional location as a number in the range 0 to 15\ndef loc(i,j):\n return i + j*4\n\n\ndef get_perimeter():\n '''Return a list of the perimeter locations, encoded using loc'''\n perimeter = set()\n for i in range(4):\n perimeter.add(loc(i,0))\n perimeter.add(loc(i,3))\n perimeter.add(loc(0,i))\n perimeter.add(loc(3,i))\n return list(perimeter)\n\n\ndef get_victory_configs():\n '''Return a list of victory configurations\n Each victory configuration is a list of four locations,\n encoded using loc\n A player wins by controlling all four locations\n (of any of the 19 configurations)'''\n\n v_configs = []\n # rows\n for i in range(4):\n v_configs.append([loc(i,j) for j in range(4)])\n # columns\n for i in range(4):\n v_configs.append([loc(j,i) for j in range(4)])\n # main diagonal\n v_configs.append([loc(i,i) for i in range(4)])\n # anti-diagonal\n v_configs.append([loc(i,3-i) for i in range(4)])\n # the 2x2 blocks\n for i in range(3):\n for j in range(3):\n config = []\n for ii in range(2):\n for jj in range(2):\n config.append(loc(i+ii,j+jj))\n v_configs.append(config)\n return v_configs\n\n\n\nclass Position:\n '''Encapsulates a position of the game, including info on who moves next,\n and what the most recent move was'''\n \n def __init__(self,pieces,next_player,previous_piece):\n '''Create a new Position with the specified 4x4 array\n of pieces, the specified next-player-to-move,\n and specified previous piece'''\n\n self.pieces = [None for i in range(4*4)]\n self.tile_count = 0\n for i in range(4):\n for j in range(4):\n self.pieces[loc(i,j)] = pieces[i][j]\n # non-tile pieces (player tokens) are\n # distinguished by the -1 in their first coordinate\n if pieces[i][j][0] != -1:\n self.tile_count += 1\n\n self.next_player = next_player\n self.previous_piece = previous_piece\n \n self.perimeter = get_perimeter()\n self.checks = get_victory_configs()\n\n\n\n\n def get_piece(self,i,j):\n '''Get the piece at location (i,j)'''\n return self.pieces[loc(i,j)]\n\n def whose_move(self):\n '''Return the player who moves next'''\n return self.next_player\n\n # return a list of Moves\n def get_moves(self):\n if self.previous_piece is None:\n return [Move(self,p) for p in self.perimeter]\n\n moves = []\n for i in range(4*4):\n piece = self.pieces[i]\n if(piece[0] == -1):\n continue\n if (piece[0] == self.previous_piece[0] or\n piece[1] == self.previous_piece[1]):\n moves.append(i)\n return [Move(self,p) for p in moves]\n\n\n # return (1,score) if victory for black\n # return (-1,-score) if victory for red\n # return (0,blah) if neither,\n # where blah is a numerical value that will help us\n # sort moves later.\n # add 1, 10, or 100\n def score(self):\n running_total = 0\n for config in self.checks:\n reds = blacks = 0\n for pos in config:\n if self.pieces[pos] == player_piece(black()):\n blacks += 1\n elif self.pieces[pos] == player_piece(red()):\n reds += 1\n if(reds > 0 and blacks > 0):\n break\n if(reds > 0 and blacks > 0):\n continue\n if blacks == 4:\n return (1,self.tile_count)\n if reds == 4:\n return (-1,-self.tile_count)\n if blacks > 0:\n running_total += 10**blacks\n elif reds > 0:\n running_total -= 10**reds\n\n # also check for victory via no moves remaining\n if not self.get_moves():\n if self.next_player == red():\n return (1,self.tile_count)\n else:\n return (-1,-self.tile_count)\n\n return (0,running_total)\n \n # return red() or black() if one of those one, else return 0\n def check_victory(self):\n (winner,details) = self.score()\n return winner\n\n \n def eval(self):\n '''Evaluate a position, by analyzing it completely using\n the helper class Analysis'''\n immediate_score = self.score()\n if immediate_score[0] != 0:\n return immediate_score\n (score,move) = self.alpha_beta_helper((2,0),(-2,0),0)\n return score\n # # (2,0) is higher than any possible score,\n # # and (-2,0) is lower than any possible score\n # return Analysis(self).alpha_beta_helper((2,0),(-2,0))\n\n def best_move(self):\n '''Return an optimal move (as a Move object),\n or None if the game is over'''\n print(\"Best move called on \\n\" + str(self))\n immediate_score = self.score()\n if immediate_score[0] != 0:\n return None\n (score,move) = self.alpha_beta_helper((2,0),(-2,0),0)\n return move\n\n\n\n\n # get a hashable description of this position\n def get_key(self):\n return (tuple(self.pieces),self.next_player,self.previous_piece)\n\n\n\n def alpha_beta_helper(self,upper,lower,depth):\n '''Recursively evaluate this position,\n Assumption: self is non-terminal, upper >= lower\n Return (s,move) where\n min(upper,max(lower,s)) = min(upper,max(lower,score))\n where score is the true final score under perfect play,\n AND if lower < s < upper, then move is an optimal move.''' \n\n # first try all the moves and collect their scores\n def assess_move(move):\n move.do()\n score = self.score()\n move.undo()\n return score\n\n move_list = []\n for m in self.get_moves():\n score = assess_move(m)\n if(score[0] == self.next_player):\n return (score,m) # it's optimal\n elif(score[0] == -self.next_player):\n garbage = (score,m)\n else:\n move_list.append((score,m))\n \n if len(move_list) == 0:\n # all moves were (equally) terrible\n return garbage\n \n # sort the moves\n if(self.next_player > 0):\n # Black is maximizing the score\n move_list.sort(key = (lambda x: x[0]), reverse = True)\n else:\n # Red is minimizing the score\n move_list.sort(key = (lambda x: x[0]), reverse = False)\n # strip off the immediate scores\n move_list = [move for (score,move) in move_list]\n \n if(self.next_player > 0):\n bestScore = lower\n bestMove = None\n for move in move_list:\n move.do()\n (score,junk) = self.alpha_beta_helper(upper,bestScore,depth+1)\n move.undo()\n if(score > bestScore):\n bestScore = score\n bestMove = move\n if(score >= upper):\n return (bestScore,bestMove)\n return (bestScore,bestMove)\n else:\n bestScore = upper\n bestMove = None\n for move in move_list:\n move.do()\n (score,junk) = self.alpha_beta_helper(bestScore,lower,depth+1)\n move.undo()\n if(score < bestScore):\n bestScore = score\n bestMove = move\n if(score <= lower):\n return (bestScore,bestMove)\n return (bestScore,bestMove)\n\n # Let's see whether I can do this correctly\n inner_ab = alpha_beta_helper\n cache = {}\n def alpha_beta_helper(self,upper,lower,depth):\n key = self.get_key()\n if key in Position.cache:\n return Position.cache[key]\n (score,move) = Position.inner_ab(self,upper,lower,depth)\n if depth < 4 and lower < score and score < upper:\n Position.cache[key] = (score,move)\n return (score,move)\n \n \n \n \n \n\n def __str__(self):\n retval = \"\"\n for i in range(4):\n for j in range(4):\n p = loc(i,j)\n piece= self.pieces[p]\n if(piece == (-1,-1)):\n retval += \"Red \"\n elif piece==(-1,1):\n retval += \"Black \"\n else:\n retval += str(self.pieces[p]) + \" \"\n retval += \"\\n\"\n retval += (\"Black\" if self.next_player > 0 else \"Red\") + \" to move\"\n retval += \", also prev piece is \" + str(self.previous_piece)\n return retval\n\n\n\n\nclass Move:\n '''Abstract representation of a possible move in a position.\n Calling do() changes the original position, and then calling\n undo() undoes it. These calls must alternate.'''\n \n def __init__(self,parent,location):\n '''Move(p,Position.loc(i,j)) creates an abstract\n rep of a move in position p, at location (i,j)'''\n self.parent = parent\n self.location = location\n \n def do(self):\n '''Carry out the move'''\n position = self.parent\n self.old_previous = position.previous_piece\n position.previous_piece = position.pieces[self.location]\n position.pieces[self.location] = player_piece(position.next_player)\n position.next_player = other_player(position.next_player)\n position.tile_count -= 1\n\n def undo(self):\n '''Undo a move that has been carried out'''\n position = self.parent\n position.next_player = other_player(position.next_player)\n position.pieces[self.location] = position.previous_piece\n position.previous_piece = self.old_previous\n position.tile_count += 1\n\n def get_location(self):\n '''Return the location of the move'''\n i = self.location % 4\n j = self.location // 4\n return (i,j)\n\n\n","repo_name":"willij6/niya-solver","sub_path":"analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":10701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"24675839075","text":"from amr_utils.alignments import AMR_Alignment\nfrom amr_utils.amr_readers import AMR_Reader\nimport penman\n\n\nfrom penman.model import Model\nclass TreePenmanModel(Model):\n def deinvert(self, triple):\n return triple\n\n def invert(self, triple):\n return triple\n\ndef node_map(amr1, amr2):\n node_labels = {}\n for n in amr1.nodes:\n candidate_nodes = [n2 for n2 in amr2.nodes if amr1.nodes[n].lower()==amr2.nodes[n2].lower()]\n\n if len(candidate_nodes)>1:\n neighbors = {n2: [f'{amr2.nodes[s]}_{r}_{amr2.nodes[t]}'.lower() for s, r, t in amr2.edges if n2 in [s, t]] for n2 in candidate_nodes}\n n_neighbors = [f'{amr1.nodes[s]}_{r}_{amr1.nodes[t]}'.lower() for s, r, t in amr1.edges if n in [s, t]]\n candidate_nodes = [n2 for n2 in candidate_nodes if set(neighbors[n2]) == set(n_neighbors)]\n if len(candidate_nodes)>1:\n neighbors2 = {n2: [s for s, r, t in amr2.edges if n2 == t] + [t for s, r, t in amr2.edges if n2 == s] for n2 in\n candidate_nodes}\n neighbors2 = {n2: [f'{amr2.nodes[s]}_{r}_{amr2.nodes[t]}'.lower() for s, r, t in amr2.edges if s in neighbors2[n2] or t in neighbors2[n2]] for n2 in\n candidate_nodes}\n n_neighbors2 = [s for s, r, t in amr1.edges if n == t] + [t for s, r, t in amr1.edges if n == s]\n n_neighbors2 = [f'{amr1.nodes[s]}_{r}_{amr1.nodes[t]}'.lower() for s, r, t in amr1.edges if s in n_neighbors2 or t in n_neighbors2]\n candidate_nodes = [n2 for n2 in candidate_nodes if set(neighbors2[n2]) == set(n_neighbors2)]\n if len(candidate_nodes)!=1:\n raise Exception('No match found:', amr1.id, n)\n node_labels[n] = candidate_nodes[0]\n return node_labels\n\ndef edge_map(amr1, amr2):\n node_labels = node_map(amr1, amr2)\n edge_labels = {}\n for s,r,t in amr1.edges:\n candidate_edges = [(s2,r2,t2) for s2,r2,t2 in amr2.edges if node_labels[s]==s2 and r.lower()==r2.lower() and node_labels[t]==t2]\n if len(candidate_edges)!=1:\n raise Exception('No match found:', amr1.id, s,r,t)\n edge_labels[(s,r,t)] = candidate_edges[0]\n return edge_labels\n\n\n\n\n\ndef main():\n file = '../data/szubert/szubert_amrs.isi_alignments.txt'\n ids_file = '../data/szubert/szubert_ids.isi.txt'\n output = '../data/szubert/szubert_amrs.isi.txt'\n\n amr_file1 = '../data/ldc_train.txt'\n amr_file2 = '../data/szubert/szubert_amrs.txt'\n reader = AMR_Reader()\n amrs = reader.load(amr_file1, remove_wiki=True)\n szubert_amrs = reader.load(amr_file2, remove_wiki=True)\n szubert_amr_ids = [amr.id for amr in szubert_amrs]\n amrs += szubert_amrs\n amrs = {amr.id:amr for amr in amrs}\n\n amr_ids = []\n with open(ids_file, encoding='utf8') as f:\n for line in f:\n if line:\n amr_ids.append(line.strip())\n\n isi_amrs, isi_alignments = reader.load(file, output_alignments=True)\n\n subgraph_alignments = {}\n relation_alignments = {}\n for isi_amr in isi_amrs:\n if isi_amr.id not in szubert_amr_ids: continue\n amr = amrs[isi_amr.id]\n if len(amr.tokens)!=len(isi_amr.tokens):\n raise Exception('Inconsistent Tokenization:', amr.id)\n node_labels = node_map(isi_amr, amr)\n edge_labels = edge_map(isi_amr, amr)\n isi_aligns = isi_alignments[amr.id]\n subgraph_alignments[amr.id] = []\n relation_alignments[amr.id] = []\n for i,tok in enumerate(amr.tokens):\n aligns = [align for align in isi_aligns if i in align.tokens]\n nodes = [node_labels[n] for align in aligns for n in align.nodes]\n edges = [edge_labels[e] for align in aligns for e in align.edges]\n subgraph_alignments[amr.id].append(AMR_Alignment(type='subgraph', tokens=[i], nodes=nodes))\n relation_alignments[amr.id].append(AMR_Alignment(type='relation', tokens=[i], edges=edges))\n reader.save_alignments_to_json(output.replace('.txt','.subgraph_alignments.json'), subgraph_alignments)\n reader.save_alignments_to_json(output.replace('.txt', '.relation_alignments.json'), relation_alignments)\n\n for amr in szubert_amrs:\n if amr.id not in subgraph_alignments:\n raise Exception('Missing AMR:',amr.id)\n\nif __name__=='__main__':\n main()","repo_name":"ablodge/leamr","sub_path":"scripts/read_isi_alignments.py","file_name":"read_isi_alignments.py","file_ext":"py","file_size_in_byte":4332,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"42"} +{"seq_id":"28051218711","text":"#P1949 우수마을\nfrom sys import stdin, setrecursionlimit\n\nsetrecursionlimit(10**6)\nstdin = open('./input.txt', 'r')\n\nn = int(stdin.readline())\ntree = [[] for _ in range(n+1)]\npeople = [0] + list(map(int, stdin.readline().split()))\ndp = [[people[i], 0] for i in range(n+1)]\n# print(dp)\n\nfor _ in range(n-1):\n a, b = map(int, stdin.readline().split())\n tree[a].append(b)\n tree[b].append(a)\n\n# 방문리스트\nvisited = [False] * (n+1)\ndef dfs(x):\n visited[x] = True\n for i in tree[x]:\n if not visited[i]:\n dfs(i)\n dp[x][0] += dp[i][1]\n dp[x][1] += max(dp[i])\n # print(x, dp)\n\ndfs(1)\nprint(max(dp[1])) ","repo_name":"SungHyun627/Problem_Solving","sub_path":"PS풀이저장소/트리에서의 DP/P1949(우수마을)/P1949.py","file_name":"P1949.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"42"} +{"seq_id":"38978916087","text":"# coding=utf-8\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport threading\nimport time\nimport datetime\nimport os\nimport common as common\nimport traceback\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36'\n}\n\ndef request_ipolist(url=\"http://vip.stock.finance.sina.com.cn/q/view/hk_IPOList.php\"):\n try:\n response = requests.get(url, headers=headers)\n if response.status_code == 200:\n ret = parse_result(response.text.encode(\"latin1\").decode(\"GBK\"))\n return ret\n except requests.RequestException:\n return None\n except Exception as e:\n common.print_err(traceback.format_exc(e))\n return None\n\ndef parse_result(html):\n soup = BeautifulSoup(html, 'lxml')\n ipolist_table = soup.findAll(\"div\", {\"class\": \"content\"})[0]\n\n ret = []\n items = ipolist_table.findAll(\"tbody\")[0].findAll(\"tr\")\n for item in items:\n \"\"\"\n\t\t01871\n\t\t向中国际控股有限公司\n\t\t1.42-1.28\t\t\n\t\t100000000\n\t\t0.00\n\t\t2019-10-11至2019-10-16\t\t\n\t\t2019-10-24\n\t\t--\n\t\t--\n\t\t--\n \"\"\"\n elements_type1 = item.findAll(\"td\")\n elements_type2 = item.findAll(\"th\")\n element = {\n \"code\" : elements_type1[0].get_text().strip(),\n \"name\" : elements_type1[1].get_text().strip(),\n \"price\" : elements_type1[2].get_text().strip(),\n \"quantity\" : elements_type2[0].get_text().strip(),\n \"got_money\" : elements_type2[1].get_text().strip(),\n \"date_of_offering_begin\" : elements_type1[3].get_text().strip().split(\"至\")[0],\n \"date_of_offering_end\": elements_type1[3].get_text().strip().split(\"至\")[-1],\n \"date_of_listing\" : elements_type1[4].get_text().strip()\n }\n ret.append(element)\n # print(element)\n return ret\n\n\n\n\n# 定时任务\n# =========================================\n\nclass TimingJob(threading.Thread):\n\n def __init__(self, name, time_list = [], bot=None):\n threading.Thread.__init__(self)\n self.name = name\n self.time_list = time_list\n self.time_index_for_next_task = None\n if self.time_list:\n self.time_index_for_next_task = 0\n self.bot = bot\n\n def get_next_time_index(self):\n total_time_number = len(self.time_list)\n self.time_index_for_next_task += 1\n if self.time_index_for_next_task == total_time_number:\n self.time_index_for_next_task = 0\n\n def run(self):\n print(\"start:\" + self.name)\n while True:\n if self.time_index_for_next_task is None:\n self.task()\n else:\n # 获取当前时间与日期比对\n current_time = common.current_time(fmt='%H:%M')\n # current_time = \"00:32\"\n if current_time == self.time_list[self.time_index_for_next_task]:\n self.task()\n self.get_next_time_index()\n time.sleep(5)\n\n def task(self):\n datas = request_ipolist()\n # datas = request_ipolist(url=\"http://47.75.216.239:8080/demo.html\")\n if datas:\n current_date = common.current_time(fmt='%Y-%m-%d')\n common.print_info(\"---------------当前日期: %s---------------\" % current_date)\n info = \"\"\n for data in datas:\n # 招股\n date_of_offering_begin = data.get(\"date_of_offering_begin\")\n date_of_offering_end = data.get(\"date_of_offering_end\")\n if (date_of_offering_begin <= current_date) & (current_date <= date_of_offering_end):\n info += \"---新股招股---\\n日期: %s至%s\\n代码: %s\\n价格: %s\\n名称: %s\\n\\n\" % \\\n (date_of_offering_begin,\n date_of_offering_end,\n data.get(\"code\"),\n data.get(\"price\"),\n data.get(\"name\"))\n common.print_info(info)\n # 暗盘\n date_of_listing = data.get(\"date_of_listing\")\n date_dark_pools = common.date_add_day(date_of_listing, -1)\n if date_dark_pools == current_date:\n info += \"---今日暗盘---\\n日期: %s 04:15PM\\n代码: %s\\n价格: %s\\n名称: %s\" % \\\n (date_dark_pools,\n data.get(\"code\"),\n data.get(\"price\"),\n data.get(\"name\"))\n common.print_info(info)\n if info:\n self.bot.send(info)\n\nif __name__ == \"__main__\":\n # request_ipolist()\n # job = TimingJob(\"new shares\", time_list=[\"00:39\", \"00:40\",\"09:00\",\"10:00\"])\n job = TimingJob(\"new shares\", time_list=[])\n job.run()\n # print(common.current_time(fmt='%Y-%m-%d %H'))","repo_name":"satomic/funny-toolkits","sub_path":"hkshares/ipolist.py","file_name":"ipolist.py","file_ext":"py","file_size_in_byte":5173,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"42"} +{"seq_id":"21902933280","text":"from starlette.testclient import TestClient\nfrom app.main import app\n\nclient = TestClient(app)\n\ndef test_ping():\n response = client.post(\"/admin/?token=jessica\",\n headers={\"X-Token\": \"fake-super-secret-token\"})\n print(f\"response : {response}\")\n assert response.status_code == 200\n assert response.json() == {\"message\": \"Admin getting schwifty\"}\n","repo_name":"southcoast-py/South-Coast-PY","sub_path":"API/fastapi/src/tests/test_internal/test_internal_admin.py","file_name":"test_internal_admin.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"27831658309","text":"# Pythoni inbuilt/downloaded files\nimport numpy as np\nimport pygame\nimport sys\n\nfrom map import MapData\n\n# Oma enda failid\nfrom menu import Menu\n#from vision import LightSource\nfrom camera import Camera # box_target_camera\nfrom inventory import Inventory\nfrom update import PlayerUpdate # update_player, render_player\nfrom render import RenderPictures # map_render\nfrom collisions import Collisions # check_collisions, collison_terrain, collision_hitbox\nfrom objects import ObjectManagement\nfrom render import CreateCollisionBoxes # object_list_creation\nfrom components import StaminaComponent\nfrom variables import UniversalVariables\n\n\nclass Game:\n pygame.init()\n pygame.display.set_caption(\"Glorious Adventure - BETA\")\n\n # ******************** PLAYER *******ds************* #\n player_rect = None # seda ei pea olema, aga mdea, suht perses. Code settib r2igelt self argumente, mida ei eksisteeri\n\n # ******************** FPS, FONT ******************** #\n clock = pygame.time.Clock() # fps\n font = pygame.font.SysFont(\"Verdana\", 20) # font\n\n # ******************** MENU ******************** #\n screen = UniversalVariables.screen\n menu_state = \"main\"\n game_paused = False\n\n def run(self) -> None:\n while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:\n if self.game_paused == False: \n self.game_paused = True\n else:\n self.game_paused = False\n self.menu_state = \"main\"\n \n self.screen.fill((79, 68, 65)) # Fill with a background color (black in this case)\n\n # Vaatab kas mäng on pausi peale pandud või mitte\n if self.game_paused != True:\n PlayerUpdate.update_player(self) # Uuendab mängija asukohta, ja muid asju\n Camera.box_target_camera(self) # Kaamera\n\n StaminaComponent.stamina_bar_update(self) # Stamina bar\n\n # collision things\n Collisions.collison_terrain(self)\n Collisions.check_collisions(self) # Vaatab mängija kokkup6rkeid objecktidega\n\n CreateCollisionBoxes.object_list_creation(self) # Creatib UniversalVariables.collision_boxes\n RenderPictures.map_render(self) # Renderib terraini\n\n if Collisions.render_after == True: # Renderib objectid peale playerit. Illusioon et player on objecti taga.\n ObjectManagement.place_and_render_object(self) # Renderib objektid\n PlayerUpdate.render_player(self) # Renderib playeri (+ tema recti)\n else: # self.render_after == False\n PlayerUpdate.render_player(self)\n ObjectManagement.place_and_render_object(self) # Renderib objektid\n\n Inventory.handle_mouse_click(self) # Inventorisse clickimise systeem\n\n if Inventory.render_inv:\n Inventory.render_craftable_items(self)\n\n #light_source.x, light_source.y = UniversalVariables.player_x, UniversalVariables.player_y\n PlayerUpdate.render_HUD(self) # Render HUD_class (health- ,food- ,stamina bar)\n PlayerUpdate.render_general(self) # inventory, fps counteri\n #Vision.find_walls() # eksperiment\n else:\n Menu.settings_menu(self)\n pygame.display.update()\n\nif __name__ == \"__main__\":\n game = Game()\n game.run()\n","repo_name":"SIKASZZU/GloriousAdventure","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":3698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"22852869156","text":"'''\nShortest Path in a Grid with Obstacles Elimination\nYou are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step.\n\nReturn the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1.\n\n \n\nExample 1:\n\nInput: \ngrid = \n[[0,0,0],\n [1,1,0],\n [0,0,0],\n [0,1,1],\n [0,0,0]], \nk = 1\nOutput: 6\nExplanation: \nThe shortest path without eliminating any obstacle is 10. \nThe shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).\nExample 2:\n\nInput: \ngrid = \n[[0,1,1],\n [1,1,1],\n [1,0,0]], \nk = 1\nOutput: -1\nExplanation: \nWe need to eliminate at least two obstacles to find such a walk.\n \n\nConstraints:\n\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 40\n1 <= k <= m * n\ngrid[i][j] == 0 or 1\ngrid[0][0] == grid[m - 1][n - 1] == 0\n'''\nclass Solution(object):\n def shortestPath(self, grid, k):\n \"\"\"\n :type grid: List[List[int]]\n :type k: int\n :rtype: int\n \"\"\"\n m = len(grid)\n n = len(grid[0])\n\n queue = [(0, 0, k)]\n visited = set()\n result = 0\n directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n\n while len(queue) > 0:\n size = len(queue)\n for _ in range(size):\n i, j, curr_k = queue.pop(0)\n if i == m - 1 and j == n - 1:\n return result\n for d in directions:\n new_i = i + d[0]\n new_j = j + d[1]\n\n if 0 <= new_i < m and 0 <= new_j < n:\n if grid[new_i][new_j] == 1 and (new_i, new_j, curr_k - 1) not in visited and curr_k > 0:\n queue.append((new_i, new_j, curr_k - 1))\n visited.add((new_i, new_j, curr_k - 1))\n elif grid[new_i][new_j] == 0 and (new_i, new_j, curr_k) not in visited:\n queue.append((new_i, new_j, curr_k))\n visited.add((new_i, new_j, curr_k))\n\n result = result + 1\n\n return -1","repo_name":"JerinPaulS/Python-Programs","sub_path":"ShortestPathInAGridWithObsElim.py","file_name":"ShortestPathInAGridWithObsElim.py","file_ext":"py","file_size_in_byte":2324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"42823700809","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def getMinimumDifference(self, root: Optional[TreeNode]) -> int:\n \n \n inorder = []\n def dfs(node):\n if not node:\n return\n \n dfs(node.left)\n inorder.append(node.val)\n dfs(node.right)\n \n dfs(root)\n \n mnm = inf\n \n for i in range(1, len(inorder)):\n mnm = min(mnm, abs(inorder[i] - inorder[i-1]))\n \n return mnm\n \n \n ","repo_name":"NaolJK/Leetcode","sub_path":"0530-minimum-absolute-difference-in-bst/0530-minimum-absolute-difference-in-bst.py","file_name":"0530-minimum-absolute-difference-in-bst.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"29514371582","text":"import datetime\r\n\r\nimport requests\r\nimport json\r\nimport base64\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport matplotlib.dates as mdate\r\nimport time\r\nimport matplotlib.ticker as mtick\r\nfrom operator import itemgetter \r\nimport os\r\n\r\n# API_ADDRESS = \"https://api.smartsensor.abb.com\"\r\nfrom docx import *\r\nfrom docx.shared import Inches\r\n\r\n\r\n\r\ndef authenticate(api_key, addr):\r\n # Returns authentication token for the given API Key\r\n url = f\"{addr}/Auth/Key\"\r\n body = {'apiKey': api_key, 'deviceUID': \"string\"}\r\n # Making a request\r\n r = requests.post(url, json=body)\r\n if r.status_code == 200:\r\n # Converting json response to dictionary\r\n result = json.loads(r.text)\r\n # Getting the token from the dictionary\r\n token = result[\"authToken\"]\r\n return token\r\n else:\r\n return \"\"\r\n\r\n\r\ndef collect_latest_raw_data(api_key, addr, sn, id):\r\n token = authenticate(api_key, addr)\r\n url = f\"{addr}/Sensor/Feature/Value/{sn}\"\r\n params = {'sensorTypeID': id, 'featureTypes': \"RawDataCollectionCSV\", 'complexObject': True}\r\n header = {'Authorization': f'Bearer {token}'}\r\n\r\n r = requests.get(url, params=params, headers=header)\r\n if r.status_code == 200:\r\n result = json.loads(r.text)\r\n # Getting the file name and content from the response\r\n file_name = result[0][\"featureValue\"][0]['fileName']\r\n content_encoded = result[0][\"featureValue\"][0]['fileContent']\r\n # Decoding base64 content\r\n content_bytes = content_encoded.encode('ascii')\r\n file_bytes = base64.b64decode(content_bytes)\r\n file_content = file_bytes.decode('ascii')\r\n # Writing csv file\r\n with open(file_name, 'w') as f:\r\n f.write(file_content)\r\n print(f\"File {file_name} successfully written\")\r\n\r\n\r\ndef get_sensor_feature(api_key, addr, sn, id, feature_types):\r\n token = authenticate(api_key, addr)\r\n url = f\"{addr}/Sensor/Feature/{sn}\"\r\n params = {'sensorTypeID': id, 'featureTypes': \"SensorSelfTest\", }\r\n header = {'Authorization': f'Bearer {token}'}\r\n\r\n response = requests.get(url, params=params, headers=header)\r\n\r\n if response.content is b'':\r\n return None\r\n response_json = json.loads(response.content)\r\n\r\n # Return None if the response code indicates an error\r\n if response.status_code != 200:\r\n # self._logger.debug('Error: Response Code ' + str(response.status_code) + \" \" + response_json)\r\n return None\r\n return response_json\r\n\r\n # return requests.get('Sensor/Feature/' + str(sn), {'sensorTypeID': id, # 'featureTypes': feature_types})\r\n\r\n\r\ndef collect_all_raw_data(api_key, addr , sn, id, start_date, end_date):\r\n token = authenticate(api_key, addr)\r\n url = f\"{adde}/Sensor/Feature/{sn}\"\r\n params = {'sensorTypeID': id, 'featureTypes': \"RawDataCollectionCSV\", 'from': start_date, 'to': end_date,\r\n 'complexObject': True}\r\n header = {'Authorization': f'Bearer {token}'}\r\n\r\n r = requests.get(url, params=params, headers=header)\r\n if r.status_code == 200:\r\n result = json.loads(r.text)\r\n # Getting the file name and content from the response\r\n for res in result:\r\n file_name = res[\"featureValue\"][0]['fileName']\r\n content_encoded = res[\"featureValue\"][0]['fileContent']\r\n # Decoding base64 content\r\n content_bytes = content_encoded.encode('ascii')\r\n file_bytes = base64.b64decode(content_bytes)\r\n file_content = file_bytes.decode('ascii')\r\n # Writing csv file\r\n with open(file_name, 'w') as f:\r\n f.write(file_content)\r\n print(f\"File {file_name} successfully written\")\r\n\r\n\r\ndef flatten_json(y):\r\n out = {}\r\n\r\n def flatten(x, name=''):\r\n if type(x) is dict:\r\n for a in x:\r\n flatten(x[a], name + a + '_')\r\n elif type(x) is list:\r\n i = 0\r\n for a in x:\r\n flatten(a, name + str(i) + '_')\r\n i += 1\r\n else:\r\n out[name[:-1]] = x\r\n\r\n flatten(y)\r\n return out\r\n\r\n\r\ndef main():\r\n # User input:\r\n # api_key - key obtained from portal,\r\n # sensor_serial_number - sensor that\r\n # we want to read raw data from\r\n # sensor_type_id - the id of the sensor type.\r\n # For mounted bearigs the type is 3\r\n #prod_key = \"TXpabU5HTXhNV010WTJFek1pMDBZMkZtTFdJeFpEQXROekUyWkRJNFlUSTNPRFZq\"\r\n prod_key = \"WkdKaE9XVmtZemt0WTJSbE5pMDBObVk0TFdJd09UTXRObUl3WWpjMVpETXlORE5s\"\r\n beta_key = \"TjJFek1UUm1ZamN0TkdGa01TMDBaamxtTFRrNVpEQXRNamN5WVdFeFpXSm1OekU1\"\r\n\r\n sensor_list = [# Back test stand sensors from read_warr.py\r\n # ['10006245'],\r\n # ['10002402'],\r\n # ['10002617'],\r\n # ['10012626'],\r\n # ['10001880'],\r\n # ['10000275'],\r\n # ['10004413'],\r\n # ['10000156'],\r\n # ['10001188'],\r\n # ['10003563'],\r\n # ['10009399'],\r\n # ['10000705'],\r\n # ['10000155'],\r\n # ['10001991'],\r\n # ['10001217'],\r\n # ['10010020'],\r\n # ['10002635'],\r\n # ['10009991'],\r\n # ['10003992'],\r\n # ['10001206'],\r\n # ['10002879'],\r\n # ['10001219'],\r\n # ['10002631'],\r\n # ['10002602'],\r\n # ['10001975'],\r\n # ['10001216'],\r\n # ['10000709'],\r\n # ['10002620'],\r\n # ['10001213'],\r\n # ['10001773'],\r\n # ['10002633'],\r\n # ['10000704'],\r\n # ['10006524'],\r\n # ['10001211'],\r\n # ['10010018'],\r\n # ['10001979'],\r\n # ['10004938'],\r\n # ['10001222'],\r\n # ['10024969'],\r\n # ['10000887'],\r\n # ['10002628'],\r\n # ['10004992'],\r\n # ['10001218'],\r\n # ['10014754'],\r\n # ['10000710'],\r\n # ['10003697'],\r\n # ['10002896'],\r\n # ['10014836'],\r\n # ['10001891'],\r\n # ['10002630'],\r\n # ['10004982'],\r\n # ['10004130'],\r\n # ['10002247'],\r\n\r\n # ['10001798'], # GSI bucket elevatior\r\n # ['10003280'], # prod app test with 200k connections\r\n\r\n \r\n\r\n # ['10002374'], # x1 (prod)\r\n # ['10003551'], # X2 (beta)\r\n # ['10003563'], # dead\r\n # ['10003562'],\r\n # ['10002372'],\r\n # ['10003560'],\r\n # ['10003559'],\r\n # ['10003558'],\r\n# ['10002353'], # dead\r\n# ['10003556'], # dead\r\n# ['10003555'],\r\n# ['10003554'],\r\n# ['10002351'],\r\n# ['10003552'],\r\n# ['10002346'],\r\n# ['10003550'],\r\n# ['10002349'],\r\n# ['10003548'],\r\n# ['10003547'],\r\n# ['10001792'],\r\n# ['10002373'],\r\n# ['10003581'],\r\n# ['10003580'],\r\n# ['10003579'],\r\n# ['10002354'],\r\n# ['10003577'],\r\n# ['10003576'],\r\n# ['10002336'],\r\n# ['10002352'],\r\n# ['10003573'],\r\n# ['10003572'],\r\n# ['10003571'],\r\n# ['10002350'],\r\n# ['10002347'],\r\n# ['10003568'],\r\n# ['10003567'],\r\n# ['10002348'],\r\n# ['10003569'],\r\n# ['10002339'],\r\n# ['10001793'],\r\n# ['10002340'],\r\n# ['10003564'],\r\n# ['10003561'],\r\n# ['10003578'],\r\n# ['10002345'],\r\n# ['10003549'],\r\n# ['10003553'],\r\n# ['10003570'],\r\n# ['10002344'],\r\n# ['10003566'],\r\n# ['10003565'],\r\n# ['10003582'],\r\n# ['10003557'],\r\n# ['10003574'],\r\n# ['10002343'],\r\n# ['10002341'],\r\n# ['10003575'],\r\n# ['10002335'],\r\n# ['10003546'],\r\n# ['10001797'],\r\n\r\n# # Penn waste\r\n# ['10004471'],\r\n# ['10004472'],\r\n# ['10004473'],\r\n# ['10004474'],\r\n# ['10004475'],\r\n# ['10004476'],\r\n# ['10004477'],\r\n# ['10004478'],\r\n# ['10004479'],\r\n# ['10004480'],\r\n# ['10004481'],\r\n# ['10004482'],\r\n# ['10004483'],\r\n# ['10004484'],\r\n# ['10004485'],\r\n# ['10004486'],\r\n# ['10004487'],\r\n# ['10004488'],\r\n# ['10004489'],\r\n# ['10004490'],\r\n# ['10004509'],\r\n# ['10004511'],\r\n# ['10004512'],\r\n# ['10004513'],\r\n# ['10004514'],\r\n# ['10004515'],\r\n# ['10004516'],\r\n# ['10004517'],\r\n# ['10004518'],\r\n# ['10004519'],\r\n# ['10004520'],\r\n# ['10004521'],\r\n# ['10004522'],\r\n# ['10004523'],\r\n# ['10004524'],\r\n# ['10004525'],\r\n# ['10004526'],\r\n# ['10004527'],\r\n# ['10004528'],\r\n# ['10004529'],\r\n# ['10004530'],\r\n# ['10004531'],\r\n# ['10004532'],\r\n# ['10004533'],\r\n# ['10004534'],\r\n# ['10004535'],\r\n# ['10004536'],\r\n# ['10004537'],\r\n# ['10004538'],\r\n# ['10004539'],\r\n# ['10004540'],\r\n# ['10004541'],\r\n# ['10004542'],\r\n# ['10004543'],\r\n# ['10004544'],\r\n# ['10004545'],\r\n# ['10004546'],\r\n# ['10004547'],\r\n# ['10004548'],\r\n# ['10004549'],\r\n# ['10004550'],\r\n# ['10008093'],\r\n# ['10009395'],\r\n# ['10015941'],\r\n# ['10015942'],\r\n# ['10021469'],\r\n\r\n# # Rogers group\r\n# ['10004847'],\r\n# ['10004848'],\r\n# ['10004849'],\r\n# ['10004852'],\r\n# ['10004853'],\r\n# ['10004854'],\r\n# ['10004855'],\r\n# ['10004856'],\r\n# ['10004857'],\r\n# ['10004858'],\r\n# ['10004859'],\r\n# ['10004860'],\r\n# ['10004861'],\r\n# ['10004866'],\r\n# ['10004867'],\r\n# ['10004868'],\r\n# ['10004870'],\r\n# ['10004871'],\r\n# ['10004873'],\r\n# ['10004874'],\r\n# ['10004875'],\r\n# ['10004877'],\r\n# ['10004881'],\r\n# ['10004883'],\r\n# ['10004885'],\r\n# ['10009368'],\r\n# ['10009370'],\r\n# ['10009391'],\r\n# ['10009394'],\r\n# ['10009399'],\r\n# ['10015935'],\r\n # ['10015938'],\r\n # ['10021723'],\r\n # ['10021725'],\r\n\r\n # #DGV plant\r\n # ['50:31:AD:02:06:45', '10001084'],\r\n # ['10002879'],\r\n # ['10002880'],\r\n ['10002881'],\r\n ['10002882'],\r\n ['10002883'],\r\n ['10002886'],\r\n# ['10002887'],\r\n# ['10002891'],\r\n# ['10002892'],\r\n# ['10002896'],\r\n# ['10009367'],\r\n# ['10021823'],\r\n# ['10021824'],\r\n# ['10021826'],\r\n # ['10021837'],\r\n # ['10021840'],\r\n # ['10021841'],\r\n # ['10021849'],\r\n # ['10021852'],\r\n # ['10021854'],\r\n # ['10021855'],\r\n # ['10021856'],\r\n # ['10004056'], \r\n ['10004055'], # 260J Centrifuge non drive\r\n ['10004051'], # 320 centerfuge non drive side\r\n ['10004052'], # 320 centerfuge. Drive side\r\n\r\n ]\r\n\r\n # delete old docs\r\n if os.path.exists(\"./all_sensors.docx\"):\r\n os.remove(\"./all_sensors.docx\")\r\n if os.path.exists(\"./dead_sensors.docx\"):\r\n os.remove(\"./dead_sensors.docx\")\r\n if os.path.exists(\"./alive_sensors.docx\"):\r\n os.remove(\"./alive_sensors.docx\")\r\n\r\n cnt = 0\r\n doc = Document()\r\n\r\n for sn in sensor_list:\r\n\r\n if cnt % 2:\r\n api_add = \"https://beta.api.smartsensor.abb.com\"\r\n api_key = beta_key\r\n else:\r\n api_add = \"https://api.smartsensor.abb.com\"\r\n api_key = prod_key\r\n\r\n api_add = \"https://api.smartsensor.abb.com\"\r\n api_key = prod_key\r\n print(api_add)\r\n print(api_key)\r\n\r\n\r\n sensor_serial_number = sn[0]\r\n sensor_type_id = 3\r\n start_date = \"2020.01.13\"\r\n end_date = \"2020.09.23\"\r\n feature_values = get_sensor_feature(api_key, api_add, sensor_serial_number, 3, 'SensorSelfTest')\r\n\r\n #print(feature_values)\r\n f_sort = sorted(feature_values, key=itemgetter('featureKeySequenceNo'))\r\n #print(f_sort)\r\n\r\n\r\n lst = []\r\n # csv = open(\"test_csv.csv\", \"w\") # \"w\" indicates that you're writing strings to the file\r\n for f in f_sort:\r\n lst.append(flatten_json(f['featureValue']))\r\n\r\n lst_sorted = sorted(lst, key=itemgetter('timestamp'))\r\n #print(lst_sorted)\r\n\r\n x_val = []\r\n x_val = [x['timestamp'] for x in lst_sorted]\r\n y_temp = [x['numberOfActivations'] for x in lst_sorted]\r\n print(x_val)\r\n # print(y_temp)\r\n \r\n\r\n # remove invalid number of conn entries\r\n y_vals = [0 if x is None else x for x in y_temp] # replace none with 0\r\n\r\n # idx = 0\r\n # trim_lst = []\r\n # for z in y_vals:\r\n # if z == 0:\r\n # trim_lst.append(idx)\r\n # idx = idx + 1\r\n\r\n # idx = 0\r\n # for t in trim_lst:\r\n # del y_vals[t-idx]\r\n # del x_val[t-idx]\r\n # idx = idx + 1\r\n\r\n \r\n #remove invalid dates, before 2018 (1514768400)\r\n idx = 0\r\n trim_lst = []\r\n for z in x_val:\r\n if z < 1514768400:\r\n trim_lst.append(idx)\r\n idx = idx + 1\r\n\r\n idx = 0\r\n for t in trim_lst:\r\n #del y_vals[t - idx]\r\n y_vals.pop(t - idx)\r\n x_val.pop(t-idx)\r\n idx = idx + 1\r\n\r\n print(x_val)\r\n print(y_vals)\r\n\r\n if len(y_vals) > 1:\r\n plt.clf()\r\n plt.plot(x_val, y_vals)\r\n #plt.xticks(np.arange(min(x_val), max(x_val)+1, 1.0))\r\n # plt.bar(x_val, ydiff, 0.5, color='Red')\r\n plt.ylabel(\"Total Number of Resets\")\r\n \r\n\r\n\r\n if x_val[len(x_val) - 1] < (time.time() - 604800): # if last entry more than a week ago sensor is probably dead\r\n # create plot\r\n if len(y_vals) <= 3:\r\n plt.title(\"SN \" + sensor_serial_number + \" DEAD!!\" + \"\\nWarning: 3 or less data points, may not be reliable\")\r\n else: \r\n plt.title(\"SN \" + sensor_serial_number + \" DEAD!!\")\r\n\r\n \r\n ax = plt.gca()\r\n \r\n plt.gcf().autofmt_xdate()\r\n ax.xaxis.set_major_locator(mtick.AutoLocator())\r\n ax.xaxis.set_minor_locator(mtick.AutoMinorLocator())\r\n\r\n ax.xaxis.set_major_formatter(\r\n mtick.FuncFormatter(lambda pos, _: time.strftime(\"%m-%d-%Y\", time.localtime(pos))))\r\n\r\n plt.tight_layout()\r\n \r\n # check whether or not dead_sensors.docx exists and if not then create it\r\n if os.path.isfile('./dead_sensors.docx') is True:\r\n doc = Document('./dead_sensors.docx')\r\n else:\r\n doc = Document()\r\n\r\n # add plot to alive_sensors.docx\r\n plt.savefig('./matplotlibExample.png')\r\n doc.add_picture('./matplotlibExample.png', width=Inches(5.5))\r\n\r\n plt.clf()\r\n plt.cla()\r\n doc.save('./dead_sensors.docx')\r\n\r\n # add plot to all_sensors.docx after checking if all_sensors.docx exists\r\n if os.path.isfile('./all_sensors.docx') is True:\r\n doc = Document('./all_sensors.docx')\r\n else:\r\n doc = Document()\r\n doc.add_picture('./matplotlibExample.png', width=Inches(5.5))\r\n doc.save('./all_sensors.docx')\r\n \r\n else:\r\n # create plot\r\n if len(y_vals) <= 3:\r\n plt.title(\"SN \" + sensor_serial_number + \"\\nWarning: 3 or less data points, may not be reliable\")\r\n else: \r\n plt.title(\"SN \" + sensor_serial_number)\r\n\r\n doc = Document()\r\n ax = plt.gca()\r\n \r\n plt.gcf().autofmt_xdate()\r\n ax.xaxis.set_major_locator(mtick.AutoLocator())\r\n ax.xaxis.set_minor_locator(mtick.AutoMinorLocator())\r\n\r\n ax.xaxis.set_major_formatter(\r\n mtick.FuncFormatter(lambda pos, _: time.strftime(\"%m-%d-%Y\", time.localtime(pos))))\r\n\r\n plt.tight_layout()\r\n\r\n # check whether or not alive_sensors.docx exists and if not then create it\r\n if os.path.isfile('./alive_sensors.docx') is True:\r\n doc = Document('./alive_sensors.docx')\r\n else:\r\n doc = Document()\r\n\r\n # add plot to alive_sensors.docx\r\n plt.savefig('./matplotlibExample.png')\r\n doc.add_picture('./matplotlibExample.png', width=Inches(5.5))\r\n\r\n plt.clf()\r\n plt.cla()\r\n doc.save('./alive_sensors.docx')\r\n\r\n # add plot to all_sensors.docx after checking if all_sensors.docx exists\r\n if os.path.isfile('./all_sensors.docx') is True:\r\n doc = Document('./all_sensors.docx')\r\n else:\r\n doc = Document()\r\n doc.add_picture('./matplotlibExample.png', width=Inches(5.5))\r\n doc.save('./all_sensors.docx')\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"mollypabst/Warranty_Data","sub_path":"retrieve_warranty_data.py","file_name":"retrieve_warranty_data.py","file_ext":"py","file_size_in_byte":16590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"74821538367","text":"#!/usr/bin/env python3\n\nfrom PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter\nfrom os import path\nfrom glob import glob\nimport sys\nimport subprocess\nimport argparse\n\n\n# Returns a directory which specified file is in.\ndef find_file_directory(file_path):\n last_char_index = file_path.rfind(\"/\")\n if last_char_index == -1:\n return \".\"\n else:\n return file_path[:last_char_index]\n\n\n# Finds and returns an output file name that does not exist in the given target dir.\ndef find_output_file_name(target_dir, output_name):\n i = 0\n out = output_name\n while path.exists(path.join(target_dir, \"{}.pdf\".format(out))):\n out = output_name + str(i)\n i += 1\n return out\n\n\n# Finds and returns all file names of specific type in the dirrectory.\ndef find_files(target_dir, file_ext):\n return glob(path.join(target_dir, \"*.{}\".format(file_ext)))\n\n\n# Merges all PDFs in the given directory.\ndef merge_pdfs(target_dir, output_dir=None):\n # Find pdfs in the given directory.\n pdfs = find_files(target_dir, \"pdf\")\n merger = PdfFileMerger()\n\n if len(pdfs) < 1:\n print(\"ERROR: No pdfs found in the provided directory.\")\n sys.exit(1)\n\n # Merge pdfs.\n print(\"Found and merging the following pdfs:\")\n for pdf in pdfs:\n print(pdf)\n merger.append(pdf)\n\n if output_dir == None:\n output_dir = target_dir\n\n # Check if to be writen file does not exist already.\n output_name = find_output_file_name(output_dir, \"merged\")\n\n # Output merged pdf.\n output_path = path.join(output_dir, \"{}.pdf\".format(output_name))\n merger.write(output_path)\n print(\"Merged pdfs outputed to: {}\".format(output_path))\n merger.close()\n\n\n# Compresses given PDF and outputs it to a new pdf file.\ndef compress_pdf(target_pdf, output_dir=None):\n # Find output dir if not specified.\n if output_dir == None:\n output_dir = find_file_directory(target_pdf)\n # Find available output file name.\n output_name = find_output_file_name(output_dir, \"compressed\")\n\n # Find full output path.\n output_path = path.join(output_dir, \"{}.pdf\".format(output_name))\n\n # Run compression.\n ret_code = subprocess.call(\n \"python3 ./compress/compress.py -o {} {}\".format(output_path, target_pdf), shell=True)\n if ret_code == 0:\n print(\"Compressed pdf outputed to: {}\".format(output_path))\n\n\n# Splits PDF into two on the given split_page\ndef split_pdf(target_pdf, split_page, output_dir=None):\n\n input_pdf = PdfFileReader(open(target_pdf, \"rb\"))\n\n if split_page > input_pdf.numPages or split_page < 1:\n print(\"ERROR: PAGE is out of bounds.\")\n sys.exit(1)\n\n print(\"Found and spliting {}...\".format(target_pdf))\n\n out_pdf1 = PdfFileWriter()\n out_pdf2 = PdfFileWriter()\n\n # Build two new pdfs.\n for page in range(split_page):\n out_pdf1.addPage(input_pdf.getPage(page))\n\n for page in range(split_page, input_pdf.getNumPages()):\n out_pdf2.addPage(input_pdf.getPage(page))\n\n # Find output dir if not specified.\n if output_dir == None:\n output_dir = find_file_directory(target_pdf)\n\n # Find available output file name.\n output_name = find_output_file_name(output_dir, \"split\")\n\n # Find full output paths.\n output_path1 = path.join(output_dir, \"{}_1.pdf\".format(output_name))\n output_path2 = path.join(output_dir, \"{}_2.pdf\".format(output_name))\n\n # Write newly split pdfs.\n with open(output_path1, 'wb') as file1:\n out_pdf1.write(file1)\n\n with open(output_path2, 'wb') as file2:\n out_pdf2.write(file2)\n\n print(\"PDF succesfully splitted to the following files:\\n{}\\n{}\".format(\n output_path1, output_path2))\n\n\ndef main():\n parser = argparse.ArgumentParser()\n\n # Create an argument group as the script can do one thing at a time: merge, split or compress.\n group = parser.add_mutually_exclusive_group()\n group.add_argument(\"-md\", \"--merge_dir\", action=\"store_true\",\n help=\"merge all pdfs found in the provided INPUT directory\")\n group.add_argument(\n \"-s\", \"--split\", action=\"store_true\", help=\"split INPUT pdf on the given PAGE\")\n group.add_argument(\"-c\", \"--compress\",\n help=\"compress INPUT pdf\", action=\"store_true\")\n\n # Input/output arguments. Page argument.\n parser.add_argument(\n \"-i\", \"--input\", help=\"target file/directory\", required=True)\n parser.add_argument(\n \"-o\", \"--output\", help=\"if not specified, output defaults to the input file directory\", required=False)\n parser.add_argument(\n \"-p\", \"--page\", help=\"page to split the pdf on\", type=int)\n\n # Parse arguments\n args = parser.parse_args()\n\n # Check if OUTPUT is a valid directory if provided.\n if args.output != None:\n if not path.isdir(args.output):\n print(\"ERROR: check if OUTPUT is a valid directory.\")\n sys.exit(1)\n\n # Merge\n if args.merge_dir:\n # Check if INPUT is a valid directory.\n if not path.isdir(args.input):\n print(\"ERROR: check if INPUT is a valid directory.\")\n sys.exit(1)\n merge_pdfs(args.input, args.output)\n # Compress\n if args.compress:\n # Check if INPUT file exists.\n compress_pdf(args.input, args.output)\n # Split\n if args.split:\n if not args.page == None:\n split_pdf(args.input, args.page, args.output)\n else:\n print(\"ERROR: PAGE is not specified.\")\n sys.exit(1)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"d1j/pdfmerger","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"20994773139","text":"\nrow1 = [\"⬜️\",\"️⬜️\",\"️⬜️\"]\nrow2 = [\"⬜️\",\"⬜️\",\"️⬜️\"]\nrow3 = [\"⬜️️\",\"⬜️️\",\"⬜️️\"]\nmap = [row1, row2, row3]\nprint(f\"{row1}\\n{row2}\\n{row3}\")\nposition = input(\"Where do you want to put the treasure? \")\n\n#horizontal = int(position[0])\n#vertical = int(position[1])\n\n#map[vertical - 1][horizontal - 1] = \"X\"\n#if input is 23, then 2 is the vertical and 3 is the horizontal\n\ncolumn = int(position[1]) - 1 \nrow = int(position[0]) - 1\nmap[column][row] = \"X\"\n\n#The code converts the input into row and column indices by subtracting 1 from each digit to account for zero-based indexing in Python.\n\nprint(f\"{row1}\\n{row2}\\n{row3}\")\n\n#why is the X ouputted when the map ie printed again? \n","repo_name":"NoahJenkins/100DaysOfCode","sub_path":"Day 4/treasure_map.py","file_name":"treasure_map.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"42"} +{"seq_id":"18451638984","text":"# Databricks notebook source\nimport pyspark\n\n# COMMAND ----------\n\ndf = sqlContext.sql(\"SELECT * FROM default_of_credit_card_clients_1_csv\")\nprint(\"Total number of rows: %d\" % df.count())\n\n\n# COMMAND ----------\n\ndf.show(10)\n\n# COMMAND ----------\n\nfrom pyspark import SparkContext\nfrom pyspark.sql import SparkSession\n\nspark = SparkSession.builder.appName(\"CreditCard\").master(\"local[*]\") .getOrCreate()\n\n\n\n\n# COMMAND ----------\n\nfrom pyspark.mllib.linalg import Vectors\nfrom pyspark.mllib.regression import LabeledPoint\n\ntransformed_df = df.rdd.map(lambda row: LabeledPoint(row[-1], Vectors.dense(row[0:-1])))\n\nsplits = [0.7, 0.3]\ntraining_data, test_data = transformed_df.randomSplit(splits, 13579)\n\nprint(\"Number of training set rows: %d\" % training_data.count())\nprint(\"Number of test set rows: %d\" % test_data.count())\n\n# COMMAND ----------\n\nfrom pyspark.mllib.tree import RandomForest\nfrom time import *\n\nstart_time = time()\n\nmodel = RandomForest.trainClassifier(training_data, numClasses=2, categoricalFeaturesInfo={},numTrees=25, featureSubsetStrategy=\"auto\", impurity=\"gini\",maxDepth=4, maxBins=32, seed=13579)\n\nend_time = time()\nelapsed_time = end_time - start_time\nprint(\"Time to train model: %.3f seconds\" % elapsed_time)\n\n# COMMAND ----------\n\npredictions = model.predict(test_data.map(lambda x: x.features))\nlabels_and_predictions = test_data.map(lambda x: x.label).zip(predictions)\nacc = labels_and_predictions.filter(lambda x: x[0] == x[1]).count() / float(test_data.count())\nprint(\"Model accuracy: %.3f%%\" % (acc * 100))\n\n# COMMAND ----------\n\nfrom pyspark.mllib.tree import GradientBoostedTrees, GradientBoostedTreesModel\n\nfrom time import *\nstart_time = time()\n\ngbt = GradientBoostedTrees.trainClassifier(training_data,\n categoricalFeaturesInfo={}, numIterations=3)\n\nend_time = time()\nelapsed_time = end_time - start_time\nprint(\"Time to train model: %.3f seconds\" % elapsed_time)\n\n# COMMAND ----------\n\npredictions = gbt.predict(test_data.map(lambda x: x.features))\nlabels_and_predictions = test_data.map(lambda x: x.label).zip(predictions)\nacc = labels_and_predictions.filter(lambda x: x[0] == x[1]).count() / float(test_data.count())\nprint(\"Model accuracy: %.3f%%\" % (acc * 100))\n\n# COMMAND ----------\n\nfrom pyspark.mllib.classification import SVMWithSGD, SVMModel\nfrom time import *\nstart_time = time()\nsvm = SVMWithSGD.train(training_data, iterations=10)\nend_time = time()\nelapsed_time = end_time - start_time\nprint(\"Time to train model: %.3f seconds\" % elapsed_time)\n\n# COMMAND ----------\n\npredictions = svm.predict(test_data.map(lambda x: x.features))\nlabels_and_predictions = test_data.map(lambda x: x.label).zip(predictions)\nacc = labels_and_predictions.filter(lambda x: x[0] == x[1]).count() / float(test_data.count())\nprint(\"Model accuracy: %.3f%%\" % (acc * 100))\n\n\n\n\n\n","repo_name":"ArunRengaraman/Creditcard_BDA","sub_path":"Creditcard.py","file_name":"Creditcard.py","file_ext":"py","file_size_in_byte":2841,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"5582966810","text":"# -*- coding: utf-8 -*-\n\n'''\nProblem40 「Champernowne's constant」\n\nAn irrational decimal fraction is created by concatenating the positive integers:\n\n0.123456789101112131415161718192021...\n\nIt can be seen that the 12th digit of the fractional part is 1.\nIf d(n) represents the nth digit of the fractional part, find the value of the following expression.\n\nd(1) × d(10) × d(100) × d(1000) × d(10000) × d(100000) × d(1000000)\n(チャンパーノウン定数の小数第n位の数をd(n)とするとき、d(1) × d(10) × d(100) × d(1000) × d(10000) × d(100000) × d(1000000)の値を求めよ。)\n'''\n\nimport time\n\ndef d(n):\n if n < 10:\n return n\n\n # n桁目が何桁の数の一部なのかを調べる\n # index = 3であれば100〜999の数の一部\n index = 1\n digit = 0\n while True:\n if digit + monopolizing_length_dict[index] > n:\n break\n else:\n digit += monopolizing_length_dict[index]\n index += 1\n\n # (index)桁の数の「何番目」の数字の「何文字目」かを求めて返す。\n # (left_digits // index) + 1が上記の「何番目」に該当\n # left_digits % indexが上記の「何文字目」に該当\n left_digits = n - digit\n return int(str(range(10 ** (index - 1), 10 ** index)[left_digits // index])[left_digits % index - 1])\n\nif __name__ == '__main__':\n start = time.time()\n\n THRESHOLD = 10 ** 6\n\n # 何桁の線数桁数まで辞書に入れるべきかを計算(dict_digit)\n dict_digit = 0\n sum_of_digit = 0\n while True:\n if sum_of_digit > THRESHOLD:\n break\n else:\n dict_digit += 1\n sum_of_digit = dict_digit * 9 * 10 ** (dict_digit - 1)\n\n # 1桁の数字(1〜9)、2桁の数字(10〜99)で何桁専有しているかを辞書に。\n # n桁の場合、n * (10^n - 10^(n-1)) = n * 9 * 10^(n-1)\n monopolizing_length_dict = {index: index * 9 * 10 ** (index - 1) for index in range(1, dict_digit + 1)}\n\n answer = 1\n for index_of_ten in range(7):\n print(d(10 ** index_of_ten))\n answer *= d(10 ** index_of_ten)\n\n print(answer) # answer 210\n\n elapsed_time = time.time() - start\n print(\"elapsed_time:{}\".format(round(elapsed_time, 5)) + \"[sec]\") # 0.00012sec\n","repo_name":"Kazzle619/Project_Euler","sub_path":"project_euler_40.py","file_name":"project_euler_40.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"11360928188","text":"#!/usr/bin/env python3\n\"\"\"Python notes on Networks\"\"\"\n__appname__ = \"networks.py\"\n__author__ = \"Joseph Palmer \"\n__version__ = \"0.0.1\"\n__license__ = \"License for this code/\"\n__date__ = \"Nov-2018\"\n\n## imports ##\nimport sys\nimport networkx as nx\nimport scipy as sc\nimport matplotlib.pyplot as p\n\ndef GenRdmAdjList(N = 2, C = 0.5):\n \"\"\"GenRdmAdjList - Make a random adjacent C list.\n\n :param N: int\n :param C: int\n \"\"\"\n Ids = range(N)\n ALst = []\n for i in Ids:\n if sc.random.uniform(0,1,1) < C:\n Lnk = sc.random.choice(Ids,2).tolist()\n if Lnk[0] != Lnk[1]: #avoid self (e.g., cannibalistic) loops\n ALst.append(Lnk)\n return ALst\n# using a uniform random distribution between [0,1] to generate a \n# connectance probability between each species pair.\n\n# assign number of species and connectance\nMaxN = 30\nC = 0.75\n\n# generate an adjacency list representing a random food web\nAdjL = sc.array(GenRdmAdjList(MaxN, C))\nprint(AdjL)\n# The two columns of numbers correspond to the consumer and resource ids\n\nSps = sc.unique(AdjL) # get species ids, species node date\nSizRan = ([-10,10]) # use log10 scale\nSizs = sc.random.uniform(SizRan[0],SizRan[1],MaxN)\nprint(Sizs)\n\n# visualise the distribution generated\np.hist(Sizs) #log10 scale\np.hist(10 ** Sizs) #raw scale\n\n# close all open plots\np.close('all')\n\n# use a circular configuration. For this, we need to calculate the \n# coordinates, easily done using networkx\npos = nx.circular_layout(Sps)\n\n# generate a networkx graph object\nG = nx.Graph()\n\n# add the nodes and links (edges) to it.\nG.add_nodes_from(Sps)\nG.add_edges_from(tuple(AdjL)) # this function needs a tuple input\n\n# Generate node sizes that are proportional to (log) body sizes\nNodSizs= 1000 * (Sizs-min(Sizs))/(max(Sizs)-min(Sizs))\n\n# draw the plot\nnx.draw_networkx(G, pos, node_size = NodSizs)\n\n# save the figure as pdf\nfig1 = p.figure()\nfig1.savefig(\"../Results/Plots/DrawFW.pdf\")\n\n\n\n","repo_name":"joseph-palmer/CMEECourseWork","sub_path":"Week7/Code/DrawFW.py","file_name":"DrawFW.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"41959783130","text":"from __future__ import annotations\nfrom typing import List\nfrom unittest import TestCase, main as unittest_main\nfrom abc import ABC\n\n\nclass Creature:\n def __init__(self, attack: int, health: int) -> None:\n self.health = health\n self.attack = attack\n\n\nclass CardGame(ABC):\n def __init__(self, creatures: List[Creature]):\n self.creatures = creatures\n\n # return -1 if both creatures alive or both dead after combat\n # otherwise, return the _index_ of winning creature\n def combat(self, c1_index: int, c2_index: int) -> int:\n creature_1 = self.creatures[c1_index]\n creature_2 = self.creatures[c2_index]\n\n won_1 = self.hit(attacker=creature_1, defender=creature_2)\n won_2 = self.hit(attacker=creature_2, defender=creature_1)\n\n if (won_1 and won_2) or (not won_1 and not won_2):\n return -1\n else:\n if won_1:\n return c1_index\n else:\n return c2_index\n\n def hit(self, attacker: Creature, defender: Creature) -> bool:\n pass # implement this in derive\n\n\nclass TemporaryDamageCardGame(CardGame):\n def __init__(self, creatures):\n super().__init__(creatures)\n\n def hit(self, attacker: Creature, defender: Creature) -> bool:\n return defender.health - attacker.attack <= 0\n\n\nclass PermanentDamageCardGame(CardGame):\n def __init__(self, creatures: List[Creature]) -> None:\n super().__init__(creatures)\n\n def hit(self, attacker: Creature, defender: Creature) -> bool:\n defender.health -= attacker.attack\n return defender.health <= 0\n\n\nclass Evaluate(TestCase):\n def test_impasse(self):\n c1 = Creature(1, 2)\n c2 = Creature(1, 2)\n game = TemporaryDamageCardGame([c1, c2])\n self.assertEqual(\n -1, game.combat(0, 1), \"Combat should yield -1 since nobody died.\"\n )\n self.assertEqual(\n -1, game.combat(0, 1), \"Combat should yield -1 since nobody died.\"\n )\n\n def test_temporary_murder(self):\n c1 = Creature(1, 1)\n c2 = Creature(2, 2)\n game = TemporaryDamageCardGame([c1, c2])\n self.assertEqual(1, game.combat(0, 1))\n\n def test_double_murder(self):\n c1 = Creature(2, 1)\n c2 = Creature(2, 2)\n game = TemporaryDamageCardGame([c1, c2])\n self.assertEqual(-1, game.combat(0, 1))\n\n def test_permanent_damage_death(self):\n c1 = Creature(1, 2)\n c2 = Creature(1, 3)\n game = PermanentDamageCardGame([c1, c2])\n self.assertEqual(-1, game.combat(0, 1), \"Nobody should win this battle.\")\n self.assertEqual(1, c1.health)\n self.assertEqual(2, c2.health)\n self.assertEqual(1, game.combat(0, 1), \"Creature at index 1 should win this\")\n\n\nif __name__ == \"__main__\":\n unittest_main()\n","repo_name":"titoeb/python-desing-patterns","sub_path":"python_design_patterns/template_method/ex.py","file_name":"ex.py","file_ext":"py","file_size_in_byte":2827,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"14497863533","text":"empty_dict = {}\nbriece = {\n \"day\" : \"A period of twenty-four hours, mostly misspent\",\n \"positive\" : \"Mistaken at the pot of one's voise\",\n \"misfortune\" : \"The kind of fortune that never misses\"\n }\nlol = [['a','b'], ['c','d'],['e','f']]\ndict(lol)\nlot = [ ('a', 'b'), ('c', 'd'), ('e', 'f') ]\ndict(lot)\ntol = (['a', 'b'], ['c', 'd'], ['e', 'f'])\ndict(tol)\nlos = [ 'ab', 'cd', 'ef' ]\ndict(los)\ntos = ('ab', 'cd', 'ef')\ndict(tos)\n\npythons = {\n 'Chapman':'Graham',\n 'Cleese':'John',\n 'Idle':'Eric',\n 'Jones':'Terry',\n 'Palin':'Michael',\n}\n\npythons['Gilliam'] = 'Terry' # add new item to dict\n\nothers = {\n 'Marx':'Grucho',\n 'Howard':'Moe'\n}\n\npythons.update(others)\nprint(pythons)\ndel pythons['Howard']\n\n# pythons.clear()\nkey = 'Marx1'\nprint(pythons.get(key, \"%s isn't in pythons\" % key)) # find key in a dict","repo_name":"dolomaniuk/FirstStepsInPython","sub_path":"dictionary/f_dict.py","file_name":"f_dict.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"26677718267","text":"'''\r\nНаписать программу, которая обходит не взвешенный ориентированный граф без петель,\r\nв котором все вершины связаны, по алгоритму поиска в глубину (Depth-First Search).\r\na. граф должен храниться в виде списка смежности;\r\nb. генерация графа выполняется в отдельной функции, которая принимает на вход число вершин.\r\n'''\r\n\r\n\r\n# создаём граф, где все вершины связаны друг с другом, но без петель\r\ndef create_graph(l):\r\n return {i + 1: [j + 1 for j in range(l) if i != j] for i in range(l)}\r\n\r\n\r\ndef depth_first_search(graph, start, end, visited=None, way=None):\r\n if visited == None:\r\n visited = {i + 1: False for i in range(end + 1)}\r\n way = []\r\n visited[start] = True\r\n way.append(start)\r\n for w in graph[start]:\r\n if not visited[w]:\r\n depth_first_search(graph, w, end, visited, way)\r\n return way\r\n\r\n\r\na = 5 # количество вершин графа\r\nnew_graph = create_graph(a)\r\nprint(new_graph)\r\nprint(depth_first_search(new_graph, 1, a))\r\n# Для интереса ниже добавил другой граф, где будет более наглядно виден обход в глубину\r\n#primer = {1: [2, 3], 2: [4], 3: [5], 4: [7], 5: [6], 6: [], 7: []}\r\n#print(depth_first_search(primer, 1, max(primer)))\r\n","repo_name":"IliaMikhailov/algoritms_python_homework","sub_path":"lesson_8_task_3.py","file_name":"lesson_8_task_3.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"69892321093","text":"import ctypes.wintypes\nfrom configparser import ConfigParser\nimport math\nimport multiprocessing\nimport time\nimport os\n\n\nclass XInputGamepad(ctypes.Structure):\n _fields_ = [\n ('wButtons', ctypes.wintypes.WORD),\n ('bLeftTrigger', ctypes.wintypes.BYTE),\n ('bRightTrigger', ctypes.wintypes.BYTE),\n ('sThumbLX', ctypes.wintypes.SHORT),\n ('sThumbLY', ctypes.wintypes.SHORT),\n ('sThumbRX', ctypes.wintypes.SHORT),\n ('sThumbRY', ctypes.wintypes.SHORT)\n ]\n\n\nclass XInputState(ctypes.Structure):\n _fields_ = [\n ('dwPacketNumber', ctypes.wintypes.DWORD),\n ('Gamepad', XInputGamepad),\n ]\n\n\nclass XInputVibration(ctypes.Structure):\n _fields_ = [\n ('wLeftMotorSpeed', ctypes.wintypes.WORD),\n ('wRightMotorSpeed', ctypes.wintypes.WORD)\n ]\n\n\nclass XInput:\n API = ctypes.windll.xinput1_4\n TRIGGERS = {\n 'LEFT_TRIGGER': 'bLeftTrigger',\n 'RIGHT_TRIGGER': 'bRightTrigger',\n }\n THUMBS = {\n 'LEFT_THUMB_X': 'sThumbLX',\n 'LEFT_THUMB_-X': 'sThumbLX',\n 'LEFT_THUMB_Y': 'sThumbLY',\n 'LEFT_THUMB_-Y': 'sThumbLY',\n 'RIGHT_THUMB_X': 'sThumbRX',\n 'RIGHT_THUMB_-X': 'sThumbRX',\n 'RIGHT_THUMB_Y': 'sThumbRY',\n 'RIGHT_THUMB_-Y': 'sThumbRY',\n }\n AXES = {\n **TRIGGERS,\n **THUMBS\n }\n BUTTONS = {\n 'DPAD_UP': 0x0001,\n 'DPAD_DOWN': 0x0002,\n 'DPAD_LEFT': 0x0004,\n 'DPAD_RIGHT': 0x0008,\n 'START': 0x0010,\n 'BACK': 0x0020,\n 'LEFT_THUMB': 0x0040,\n 'RIGHT_THUMB': 0x0080,\n 'LEFT_SHOULDER': 0x0100,\n 'RIGHT_SHOULDER': 0x0200,\n 'A': 0x1000,\n 'B': 0x2000,\n 'X': 0x4000,\n 'Y': 0x8000\n }\n TRIGGER_MAGNITUDE = 256\n THUMB_MAGNITUDE = 32768\n MOTOR_MAGNITUDE = 65535\n ERROR_SUCCESS = 0\n vibration_process = None\n\n def __init__(self, config_file, gamepad_number=0):\n self.gamepad_number = gamepad_number\n self.state = XInputState()\n self.gamepad = self.state.Gamepad\n config = ConfigParser()\n config.read(config_file)\n self.config = config['gamepad']\n\n def __del__(self):\n self.disable_vibration()\n\n def get_state(self):\n previous_state = self.state.dwPacketNumber\n error_code = self.API.XInputGetState(\n ctypes.wintypes.WORD(self.gamepad_number),\n ctypes.pointer(self.state))\n if error_code != self.ERROR_SUCCESS:\n raise Exception('Gamepad number {} is not connected'.format(self.gamepad_number))\n return previous_state != self.state.dwPacketNumber\n\n def is_button_press(self, button):\n if button not in self.BUTTONS:\n raise Exception('Invalid button. Got: \"{}\"'.format(button))\n return bool(self.BUTTONS[button] & self.gamepad.wButtons)\n\n def get_axis_value(self, axis):\n if axis not in self.AXES:\n raise Exception('Invalid axis, Got: {}'.format(axis))\n return getattr(self.gamepad, self.AXES[axis])\n\n def get_trigger_value(self, trigger):\n return self.get_axis_value(trigger) & 0xFF\n\n def get_thumb_value(self, thumb):\n return self.get_axis_value(thumb)\n\n def get_magnitude(self, axis_type):\n return getattr(self, axis_type + '_MAGNITUDE')\n\n def get_sensitivity(self, axis_type):\n return self.config.getfloat(axis_type + '_SENSITIVITY')\n\n def get_normalized_value(self, axis: str):\n if axis not in self.AXES.keys():\n raise Exception('Invalid axis. Got: \"{}\"'.format(axis))\n axis_type = axis.split('_')[1]\n raw_value = getattr(\n self,\n 'get_{}_value'.format(axis_type.lower()))(axis)\n magnitude = self.get_magnitude(axis_type)\n sensitivity = self.get_sensitivity(axis_type)\n return (raw_value / magnitude) * sensitivity\n\n def get_dead_zone(self, axis_type):\n return self.config.getfloat(axis_type + '_DEAD_ZONE')\n\n def is_axis_change(self, axis):\n if axis not in self.AXES.keys():\n raise Exception('Invalid axis. Got: \"{}\"'.format(axis))\n axis_type = axis.split('_')[1]\n axis_value = self.get_normalized_value(axis) / self.get_sensitivity(axis_type)\n if '-' in axis and axis_value > 0 or '-' not in axis and axis_value < 0:\n return False\n dead_zone = self.get_dead_zone(axis_type)\n return abs(axis_value) > dead_zone\n\n def is_thumb_move(self, thumb):\n return self.is_axis_change(thumb)\n\n def is_trigger_press(self, trigger):\n return self.is_axis_change(trigger)\n\n def set_vibration(self, left_motor, right_motor):\n if not (0 <= left_motor <= 1 and 0 <= right_motor <= 1):\n raise Exception('Motor speeds must be between 0 - 1.')\n vibration = XInputVibration(\n ctypes.wintypes.WORD(math.floor(left_motor * self.MOTOR_MAGNITUDE)),\n ctypes.wintypes.WORD(math.floor(right_motor * self.MOTOR_MAGNITUDE))\n )\n self.API.XInputSetState(\n ctypes.wintypes.DWORD(self.gamepad_number),\n ctypes.pointer(vibration)\n )\n\n def disable_vibration(self, duration=0):\n time.sleep(duration)\n vibration = XInputVibration(\n ctypes.wintypes.WORD(0),\n ctypes.wintypes.WORD(0)\n )\n self.API.XInputSetState(\n ctypes.wintypes.WORD(self.gamepad_number),\n ctypes.pointer(vibration)\n )\n try:\n self.vibration_process.terminate()\n except AttributeError:\n pass\n\n def set_debounce_vibration(self, left_motor, right_motor, duration):\n self.set_vibration(left_motor, right_motor)\n try:\n self.vibration_process.terminate()\n except AttributeError:\n pass\n self.vibration_process = multiprocessing.Process(\n target=self.disable_vibration,\n args=(duration,)\n )\n self.vibration_process.start()\n\n\nif __name__ == '__main__':\n x = XInput('default.ini')\n while True:\n output = {}\n if not x.get_state() and output:\n print('\\n'.join(['{} = {}'.format(key, value) for key, value in output.items()]))\n time.sleep(0.2)\n os.system('cls')\n continue\n for thumb in x.THUMBS.keys():\n if x.is_thumb_move(thumb):\n output[thumb] = x.get_thumb_value(thumb)\n else:\n output[thumb] = 0\n for trigger in x.TRIGGERS.keys():\n if x.is_trigger_press(trigger):\n output[trigger] = x.get_trigger_value(trigger)\n else:\n output[trigger] = 0\n for button in x.BUTTONS.keys():\n output[button] = x.is_button_press(button)\n x.set_debounce_vibration(0.3, 0.3, 0.1)\n print('\\n'.join(['{} = {}'.format(key, value) for key, value in output.items()]))\n time.sleep(0.2)\n os.system('cls')\n","repo_name":"izdwuut/xbox-mapper-tutorial","sub_path":"xinput.py","file_name":"xinput.py","file_ext":"py","file_size_in_byte":6988,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"44"} +{"seq_id":"38266079647","text":"from cradmin_legacy import css_icon_map\n\n\nFONT_AWESOME = css_icon_map.FONT_AWESOME.copy()\nFONT_AWESOME.update({\n 'devilry-breadcrumb-suffix': 'fa fa-angle-right',\n 'devilry-pageheader-back': 'fa fa-angle-left',\n 'devilry-link-forward': 'fa fa-angle-right',\n 'devilry-account': 'fa fa-user',\n})\n","repo_name":"devilry/devilry-django","sub_path":"devilry/devilry_cradmin/devilry_css_icon_map.py","file_name":"devilry_css_icon_map.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"44"} +{"seq_id":"15146242409","text":"import xlwt\nimport base64\nfrom io import StringIO\nfrom odoo import api, fields, models, _\nimport platform\n\nclass PurchaseReportOut(models.Model):\n _name = 'purchase.report.out'\n _description = 'purchase order report'\n\n purchase_data = fields.Char('Name', size=256)\n file_name = fields.Binary('Purchase Excel Report', readonly=True)\n purchase_work = fields.Char('Name', size=256)\n file_names = fields.Binary('Purchase CSV Report', readonly=True)\n\n\nclass WizardWizards(models.Model):\n _name = 'wizard.reports'\n _description = 'purchase wizard'\n\n#purchase order excel report button actions\n# @api.multi\n def action_purchase_report(self):\n#XLS report\n custom_value = {}\n label_lists=['PO','POR','CLIENTREF','BARCODE','DEFAULTCODE','NAME','QTY','VENDORPRODUCTCODE','TITLE', 'PARTNERNAME', 'EMAIL', 'PHONE', 'MOBILE', 'STREET', 'STREET2', 'ZIP', 'CITY', 'COUNTRY']\n order = self.env['purchase.order'].browse(self._context.get('active_ids', list()))\n workbook = xlwt.Workbook()\n for rec in order:\n purchase = []\n for line in rec.order_line:\n product = {}\n product ['product_id'] = line.product_id.name\n product ['product_qty'] = line.product_qty\n product ['qty_received'] = line.qty_received\n product ['qty_invoiced'] = line.qty_invoiced\n product ['price_unit'] = line.price_unit\n product ['taxes_id'] = line.taxes_id.name\n product ['price_subtotal'] = str(line.price_subtotal)+' '+line.currency_id.symbol\n purchase.append(product)\n\n custom_value['products'] = purchase\n custom_value ['partner_id'] = rec.partner_id.name\n custom_value ['partner_ref'] = rec.partner_ref\n custom_value ['payment_term_id'] = rec.payment_term_id.name\n custom_value ['date_order'] = rec.date_order\n custom_value ['partner_no'] = rec.name\n custom_value ['amount_total'] = str(rec.amount_total)+' '+rec.currency_id.symbol\n custom_value ['amount_untaxed'] = str(rec.amount_untaxed)+' '+rec.currency_id.symbol\n custom_value ['amount_tax'] = str(rec.amount_tax)+' '+rec.currency_id.symbol\n\n style0 = xlwt.easyxf('font: name Times New Roman bold on;borders:left thin, right thin, top thin, bottom thin;align: horiz right;', num_format_str='#,##0.00')\n style1 = xlwt.easyxf('font: name Times New Roman bold on;borders:left thin, right thin, top thin, bottom thin;align: horiz center;', num_format_str='#,##0.00')\n style2 = xlwt.easyxf('font:height 400,bold True;borders:left thin, right thin, top thin, bottom thin;', num_format_str='#,##0.00')\n style3 = xlwt.easyxf('font:bold True;borders:left thin, right thin, top thin, bottom thin;', num_format_str='#,##0.00')\n style4 = xlwt.easyxf('font:bold True; borders:top double,right thin;align: horiz right;', num_format_str='#,##0.00')\n style5 = xlwt.easyxf('font: name Times New Roman bold on;borders:left thin, right thin, top thin, bottom thin;align: horiz center;', num_format_str='#,##0')\n style6 = xlwt.easyxf('font: name Times New Roman bold on;borders:left thin, right thin, top thin, bottom thin;', num_format_str='#,##0.00')\n style7 = xlwt.easyxf('font:bold True; borders:top double;', num_format_str='#,##0.00')\n style8 = xlwt.easyxf('font: name Times New Roman bold on;borders:left thin, right thin, top thin, bottom thin;align: horiz right;', num_format_str='DD-MM-YYYY')\n style3_1 = xlwt.easyxf('font: name Times New Roman bold on;borders:left thin;align: horiz right;', num_format_str='#,##0.00')\n style4_1 = xlwt.easyxf('borders:top thin;', num_format_str='#,##0.00')\n style5_1 = xlwt.easyxf('borders:left thin;', num_format_str='#,##0.00')\n style6_1 = xlwt.easyxf('font:bold True; borders:top double;', num_format_str='#,##0.00')\n style7_1 = xlwt.easyxf('borders:left thin,bottom thin,right thin;', num_format_str='#,##0.00')\n style8_1 = xlwt.easyxf('borders:right thin;', num_format_str='#,##0.00')\n sheet = workbook.add_sheet(rec.name)\n \n sheet.write_merge(2, 3, 3, 6, 'Purchase Order :', style2)\n sheet.write_merge(2, 3, 7, 8, custom_value['partner_no'], style2) \n sheet.write(5, 1, 'Vendor', style3)\n sheet.write(6, 1, '',style3_1)\n sheet.write(7, 1, '',style3_1)\n sheet.write(8, 1, '',style3_1)\n sheet.write(9, 1, '',style3_1)\n sheet.write(5, 3, '',style4_1)\n sheet.write(5, 4, '',style4_1)\n sheet.write(5, 5, '',style4_1)\n sheet.write(5, 6, '',style4_1)\n sheet.write(5, 7, '',style4_1)\n sheet.write(8, 12,'', style5_1)\n sheet.write(9, 12,'', style5_1)\n sheet.write(5, 2, custom_value['partner_id'], style0) \n sheet.write_merge(5, 5, 8, 9, 'Order Date', style3)\n sheet.write_merge(5, 5, 10, 11, custom_value['date_order'], style8) \n sheet.write_merge(6, 6, 8, 9, 'Vendor Reference', style3)\n sheet.write_merge(6, 6, 10, 11, custom_value['partner_ref'], style0)\n sheet.write_merge(7, 7, 8, 9, 'Payment Terms', style3)\n sheet.write_merge(7, 7, 10, 11, custom_value['payment_term_id'], style0)\n\n sheet.write(10, 1, 'S NO', style1) \n sheet.write_merge(10, 10, 2, 3, 'PRODUCT', style1)\n sheet.write_merge(10, 10, 4, 5, 'QUANTITY', style1) \n sheet.write_merge(10, 10, 6, 7, 'UNIT PRICE', style1)\n sheet.write_merge(10, 10, 8, 10, 'TAXES', style1) \n sheet.write(10, 11, 'SUBTOTAL', style1)\n \n n = 11; m=10; i = 1\n for product in custom_value['products']:\n sheet.write(n, 1, i, style5) \n sheet.write_merge(n, n, 2, 3, product['product_id'], style6) \n sheet.write_merge(n, n, 4, 5, product['product_qty'], style0)\n sheet.write_merge(n, n, 6, 7, product['price_unit'], style0)\n sheet.write_merge(n, n, 8, 10, product['taxes_id'], style0)\n sheet.write(n, 11, product['price_subtotal'], style0) \n n += 1; m +=1; i += 1\n sheet.write_merge(n+1, n+1, 9, 10, 'Untaxed Amount', style7)\n sheet.write(n+1, 11, custom_value['amount_untaxed'], style4)\n sheet.write_merge(n+2, n+2, 9, 10, 'Taxes', style7)\n sheet.write(n+2, 11, custom_value['amount_tax'], style4)\n sheet.write_merge(n+3, n+3, 9, 10, 'Total', style6_1)\n sheet.write(n+3, 11, custom_value['amount_total'], style4)\n sheet.write(m+1, 1, '', style3_1)\n sheet.write(m+1, 11, '', style8_1)\n sheet.write(n+1, 1, '', style3_1)\n sheet.write(n+2, 1, '', style3_1)\n sheet.write(n+3, 1, '', style3_1)\n sheet.write_merge(n+4,n+4,1, 11, '', style7_1)\n#CSV report\n datas = []\n for values in order:\n for value in values.order_line:\n if value.product_id.seller_ids:\n item = [\n str(value.order_id.name or ''),\n str(''),\n str(''),\n str(value.product_id.barcode or ''),\n str(value.product_id.default_code or ''),\n str(value.product_id.name or ''),\n str(value.product_qty or ''),\n str(value.product_id.seller_ids[0].product_code or ''),\n str(value.partner_id.title or ''),\n str(value.partner_id.name or ''),\n str(value.partner_id.email or ''),\n str(value.partner_id.phone or ''),\n str(value.partner_id.mobile or ''),\n str(value.partner_id.street or ''),\n str(value.partner_id.street2 or ''),\n str(value.partner_id.zip or ''),\n str(value.partner_id.city or ''),\n str(value.partner_id.country_id.name or ' '),\n ]\n datas.append(item)\n\n output = StringIO()\n label = ';'.join(label_lists)\n output.write(label)\n output.write(\"\\n\")\n\n for data in datas:\n record = ';'.join(data)\n output.write(record)\n output.write(\"\\n\")\n data = base64.b64encode(bytes(output.getvalue(),\"utf-8\"))\n\n if platform.system() == 'Linux':\n filename = ('/tmp/Purchase Report' +'.xls')\n else:\n filename = ('Purchase Report' +'.xls')\n\n workbook.save(filename)\n fp = open(filename, \"rb\")\n file_data = fp.read()\n out = base64.encodestring(file_data)\n\n # Files actions\n attach_vals = {\n 'purchase_data': 'Purchase Report'+ '.xls',\n 'file_name': out,\n 'purchase_work':'Purchase'+ '.csv',\n 'file_names':data,\n }\n\n act_id = self.env['purchase.report.out'].create(attach_vals)\n fp.close()\n return {\n 'type': 'ir.actions.act_window',\n 'res_model': 'purchase.report.out',\n 'res_id': act_id.id,\n 'view_type': 'form',\n 'view_mode': 'form',\n 'context': self.env.context,\n 'target': 'new',\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"AbdulrhmanGad/zania","sub_path":"purchase_order_xlsx/wizard/purchase_xls.py","file_name":"purchase_xls.py","file_ext":"py","file_size_in_byte":9785,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"44"} +{"seq_id":"71255553732","text":"from os import system\r\nfrom time import sleep\r\nimport random\r\nfrom hangman_art import stages, logo\r\nfrom hangman_words import word_list\r\n\r\ndef playGame():\r\n\tanswer = random.choice(word_list).upper()\r\n\tplaceholder = \"_\" * len(answer)\r\n\tlives = 6\r\n\tprint(logo)\r\n\twhile lives != 0 and not did_player_win(answer, placeholder):\r\n\t\t\r\n\t\tprint(f\"Currently: {placeholder}\\n\")\r\n\t\tguess = input(\"Guess a letter: \").upper()\r\n\t\tsystem('cls')\r\n\r\n\t\tif guess in answer:\r\n\t\t\tplaceholder = updatePlaceholder(placeholder, answer, guess)\r\n\t\t\tprint(f\"Correct!\")\r\n\t\telse:\r\n\t\t\tprint(f\"Wrong!\")\r\n\t\t\tlives -= 1\r\n\t\tprint(f\"Lives: {lives}\")\t\t\r\n\t\tprint(stages[lives])\r\n\t\t\r\n\r\n\tif lives == 0:\r\n\t\tprint(f\"You didn't guess the word \\\"{answer}\\\". Better luck next time!\\n\")\r\n\telse:\r\n\t\tprint(f\"Congratulations! You guessed the word \\\"{answer}\\\"\")\r\n\tsleep(10)\r\n\r\n\r\ndef updatePlaceholder(placeholder, answer, guess):\r\n\tplaceholder_list = list(placeholder)\r\n\tfor i in range(len(answer)):\r\n\t\tif answer[i] == guess:\r\n\t\t\tplaceholder_list[i] = guess\r\n\tplaceholder = ''.join(placeholder_list)\r\n\treturn placeholder\r\n\r\ndef did_player_win(answer, placeholder):\r\n\tif answer == placeholder:\r\n\t\treturn True\r\n\treturn False\r\n\r\nplayGame()\t\t","repo_name":"dhinogz/hangman","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"2538201735","text":"# -*- coding: utf-8 -*-\nfrom .builtins import Frame\nfrom .graph import Graph, SearchSpace\nfrom .logger import get_default_logger\nfrom .store import ScopeStore, get_default_scope_store\nfrom .strategies import get_default_strategy\n\n\nclass NoMoreNodesError(Exception):\n \"\"\"\n This exception is launched when a node generator is exhausted.\n \"\"\"\n pass\n\n\nclass MaxNodesReachedError(Exception):\n \"\"\"\n This exception is raised when the maximum number of allowed nodes is reached during the search.\n \"\"\"\n def __init__(self, node_counter):\n super().__init__()\n self.node_counter = node_counter\n\n def __repr__(self):\n return '%s(Number of nodes: %d)' % (self.__class__.__name__, self.node_counter)\n\n\nclass Solver(object): # pylint: disable=too-many-instance-attributes\n \"\"\"\n This class represents a generic problem solver. The Solver represents its search space using a `Graph`,\n each `Node` in the graph represent a decision to be made or an action to be executed.\n The way the Solver is configured is through different search/test/selection/execution strategies that can\n be configured.\n Attributes:\n domain(Graph): Is the domain representing the set of nodes defining how the search is done. Each of this\n nodes is instantiated and added to the search space graph.\n is_solution(function): A function to call to check if a solution has been found.\n evaluator(function): Is a function that assigns weights to the nodes being evaluated at the current\n search step.\n selector(function): Is a selection operator to choose one node once they have been weighted.\n test(function): Is a function to check if a testable node is true or not.\n execute(function): Is a function to execute an actionable node.\n expand(function): Is a method that given the current node in the search space, generates the next\n set of nodes that need to be evaluated.\n logger(Logger): Is the logger used to print information about the search.\n max_nodes(int): Is a limit over the maximum number of nodes to generate, when this number is reached\n a `MaxNodesReachedError` exception is raised.\n backtrack(bool): Where backtracking can be used or not to explore previously discarded nodes on\n the search space.\n \"\"\"\n\n def __init__(self, domain: Graph, solution_checker):\n self.domain = domain\n self.is_solution = solution_checker\n self.evaluator = get_default_strategy('evaluation')\n self.selector = get_default_strategy('selection')\n self.test = get_default_strategy('test')\n self.execute = get_default_strategy('execution')\n self.expand = get_default_strategy('generation')\n self.logger = get_default_logger()\n self.max_nodes = None\n self.builtins = None\n self.backtrack = True\n\n def create_init_frame(self, store: ScopeStore=None, search_space: Graph=None):\n return Frame(self, store, search_space)\n\n def eval(self, *args, store: ScopeStore=None, search_space: Graph=None, from_frame: Frame=None):\n current_nodes = args\n if not search_space:\n search_space = from_frame.search_space if from_frame else SearchSpace(selector=self.selector)\n frame = from_frame or self.create_init_frame(store or get_default_scope_store(), search_space)\n while not self.is_solution(**frame.ro_builtins):\n current_nodes = self.step(current_nodes, frame, search_space)\n frame.next_frame()\n return frame\n\n def step(self, current_nodes, frame: Frame, search_space: Graph):\n if frame.node_counter == self.max_nodes:\n raise MaxNodesReachedError(frame.node_counter)\n self.logger.debug('Number of expanded nodes: %d', frame.node_counter)\n instances = self.instantiate(current_nodes, frame, search_space)\n self.logger.debug('Instances: %s', instances)\n self.eval_nodes(instances, frame, search_space)\n frame.selected = self.select(frame, search_space)\n # manage deltas here, changes on the context\n self.logger.debug('Selected Node: %s', frame.selected)\n self.execute(node=frame.selected, domain=self.domain, **frame.w_builtins)\n if not self.backtrack:\n search_space.close_all()\n return self.expand(node=frame.selected, domain=self.domain)\n\n def instantiate(self, dmn_nodes, frame: Frame, search_space: Graph): # pylint: disable=no-self-use\n parent = frame.selected\n snode = search_space.node_builder\n context_id = parent.context_id if parent else frame.INIT_CONTEXT_ID\n return list(snode(reference=node.node_id, in_nodes=parent, context_id=context_id) for node in dmn_nodes)\n\n def eval_nodes(self, instances, frame: Frame, search_space: Graph):\n parent = frame.selected\n evaluations = self.evaluator(parent=parent, nodes=instances, **frame.ro_builtins)\n self.logger.debug('New nodes weights: %s', evaluations)\n for node, weight in zip(instances, evaluations):\n if weight is not None:\n # discard those modules that have not been weighted\n setattr(node, 'weight', weight)\n search_space.update_node(node)\n search_space.open_node(node)\n self.logger.debug('There are %d open nodes.', search_space.get_len_open_nodes())\n\n def select(self, frame: Frame, search_space: Graph):\n for selection in search_space.get_open_nodes():\n test = self.test(selection, domain=self.domain, **frame.ro_builtins)\n self.logger.debug(\"Test of %s is %s\", selection, test)\n search_space.close_node(selection)\n if test:\n return selection\n raise NoMoreNodesError()\n","repo_name":"Oscar-Garcia/pyplan","sub_path":"pyplan/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":5839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"14206396759","text":"def solution(n, lost, reserve):\n n_lost = list(set(lost) - set(reserve))\n n_reserve = list(set(reserve) - set(lost))\n answer = n - len(n_lost)\n \n for i in range(len(n_lost)):\n if (n_lost[i] - 1) in n_reserve:\n answer += 1\n n_reserve.remove(n_lost[i]-1)\n elif (n_lost[i] + 1) in n_reserve:\n answer += 1\n n_reserve.remove(n_lost[i]+1)\n else:\n continue\n return answer","repo_name":"ChoHyoungSeo/Algorithm_prac","sub_path":"python/programmers/greedy_1.py","file_name":"greedy_1.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"30346127673","text":"import pandas as pd\nimport math\n\n\nclass DTNode:\n def __init__(self, node_type=\"label\", label=None, gini_index=None, feature_name=None, left_attr_collection=None,\n right_attr_collection=None, left=None, right=None):\n self.node_type = node_type\n self.label = label\n self.gini_index = gini_index\n self.feature_name = feature_name\n self.left_attr_collection = left_attr_collection # this will be a `list` type\n self.right_attr_collection = right_attr_collection\n self.left = left\n self.right = right\n\n\nclass DT:\n def __init__(self, data, target_feature):\n self.data = data\n self.target_feature = target_feature\n self.features = self._get_features()\n remaining_features = self.features.copy()\n del remaining_features[self.target_feature]\n self.root = self._build_tree(self.data.copy(), remaining_features.copy())\n\n def _get_feature_attr_sets(self, attrs):\n attr_sets = []\n set_count = 2 ** (len(attrs) - 1) - 1\n for i in range(1, set_count + 1):\n attr_set = []\n for j in range(len(attrs)):\n if (1 << j) & i:\n attr_set.append(attrs[j])\n attr_sets.append([attr_set, list(set(attrs) - set(attr_set))])\n\n return attr_sets\n\n def predict(self, record):\n decision_path = []\n node = self.root\n\n while node.node_type != 'label':\n decision_path.append(str(node.feature_name) + '=' + str(record[node.feature_name]))\n if record[node.feature_name] in node.left_attr_collection:\n node = node.left\n else:\n node = node.right\n\n decision_path.append(f\"[prediction={node.label}]\")\n\n return decision_path\n\n def _get_features(self):\n features = {}\n\n feature_names = list(self.data.columns)\n for feature in feature_names:\n features[feature] = set(self.data.get(feature))\n\n return features\n\n def _build_tree(self, data, features):\n if len(features) == 0:\n target_attr_value_list = list(data.get(self.target_feature))\n target_attr_value_count = {}\n for attr_value in target_attr_value_list:\n if attr_value in target_attr_value_count:\n target_attr_value_count[attr_value] = target_attr_value_count[attr_value] + 1\n else:\n target_attr_value_count[attr_value] = 1\n\n max_attr_value_count = 0\n max_attr = ''\n for attr_value in target_attr_value_count:\n if max_attr_value_count < target_attr_value_count[attr_value]:\n max_attr_value_count = target_attr_value_count[attr_value]\n max_attr = attr_value\n\n return DTNode(label=max_attr)\n\n if len(set(data.get(self.target_feature))) == 1:\n return DTNode(label=data.get(self.target_feature).iloc[0])\n\n feature_gini_indices = {}\n feature_attr_set = {}\n\n for feature_name in features:\n attr_sets = self._get_feature_attr_sets(list(features[feature_name]))\n for attr_set in attr_sets:\n subset_data_left = pd.DataFrame()\n for attr in attr_set[0]:\n subset_data_left = subset_data_left.append(data.loc[data[feature_name] == attr])\n\n subset_data_right = pd.DataFrame()\n for attr in attr_set[1]:\n subset_data_right = subset_data_right.append(data.loc[data[feature_name] == attr])\n\n gini_index_left = self._get_gini_index(subset_data_left)\n gini_index_right = self._get_gini_index(subset_data_right)\n\n n1 = len(subset_data_left)\n n2 = len(subset_data_right)\n gini_index = (n1 / (n1 + n2)) * gini_index_left + (n2 / (n1 + n2)) * gini_index_right\n\n if feature_name in feature_gini_indices:\n if feature_gini_indices[feature_name] > gini_index:\n feature_gini_indices[feature_name] = gini_index\n feature_attr_set[feature_name] = attr_set\n else:\n feature_gini_indices[feature_name] = gini_index\n feature_attr_set[feature_name] = attr_set\n\n min_gini_index = 1\n min_gini_index_feature = ''\n min_gini_index_attr_set = []\n for feature_name in feature_gini_indices:\n if feature_gini_indices[feature_name] < min_gini_index:\n min_gini_index = feature_gini_indices[feature_name]\n min_gini_index_feature = feature_name\n min_gini_index_attr_set = feature_attr_set[feature_name]\n\n left_tree_data = pd.DataFrame()\n for attr in min_gini_index_attr_set[0]:\n left_tree_data = left_tree_data.append(data.loc[data[min_gini_index_feature] == attr])\n\n right_tree_data = pd.DataFrame()\n for attr in min_gini_index_attr_set[1]:\n right_tree_data = right_tree_data.append(data.loc[data[min_gini_index_feature] == attr])\n\n subtree_tree_features = features.copy()\n del subtree_tree_features[min_gini_index_feature]\n\n node = DTNode(node_type='internal', label=None, gini_index=min_gini_index, feature_name=min_gini_index_feature,\n left_attr_collection=min_gini_index_attr_set[0],\n right_attr_collection=min_gini_index_attr_set[1])\n\n node.left = self._build_tree(left_tree_data.copy(), subtree_tree_features.copy())\n node.right = self._build_tree(right_tree_data.copy(), subtree_tree_features.copy())\n\n return node\n\n def _get_gini_index(self, data):\n label_counts = {}\n\n for label in data.get(self.target_feature):\n if label in label_counts:\n label_counts[label] += 1\n else:\n label_counts[label] = 1\n\n sample_count = sum([label_counts[label] for label in label_counts])\n probability_sqr_sum = sum([(label_counts[label] / sample_count) ** 2 for label in label_counts])\n\n return 1 - probability_sqr_sum\n\n\ndata = pd.read_csv('data.csv')\n\ndt = DT(data, 'profit')\n\nprint(dt.predict({'price': 'low', 'maintenance': 'high', 'capacity': 5, 'airbag': 'no'}))\n","repo_name":"chandrakishorSingh/semester-2-materials","sub_path":"introduction-to-machine-learning/assignments/1/2/decision_tree_gini.py","file_name":"decision_tree_gini.py","file_ext":"py","file_size_in_byte":6361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"34209220535","text":"#!/usr/bin/env python3\n\n# import rospy\n# from sensor_msgs.msg import Image\n# from cv_bridge import CvBridge\n# import cv2\n# import os\n# import numpy as np\n\n# class Nodo(object):\n# def __init__(self):\n# # Params\n# self.image = None\n# self.br = CvBridge()\n# # Node cycle rate (in Hz).\n# self.loop_rate = rospy.Rate(30)\n\n# # Publishers\n# self.pub = rospy.Publisher('imagetimer', Image, queue_size=10)\n\n# # Subscribers\n# rospy.Subscriber(\"/camera/color/image_raw\",Image,self.callback)\n\n# def callback(self, msg):\n# rospy.loginfo('Image received...')\n# self.image = self.br.imgmsg_to_cv2(msg)\n\n\n# def start(self):\n# rospy.loginfo(\"Timing images\")\n# #rospy.spin()\n# while not rospy.is_shutdown():\n# rospy.loginfo('publishing image')\n# #br = CvBridge()\n# if self.image is not None:\n# self.pub.publish(self.br.cv2_to_imgmsg(self.image))\n# self.loop_rate.sleep()\n\n# if __name__ == '__main__':\n# rospy.init_node(\"imagetimer111\", anonymous=True)\n# my_node = Nodo()\n# my_node.start()\n\n#!/usr/bin/env python\nfrom __future__ import print_function\n\nimport roslib\n# roslib.load_manifest('my_package')\nimport sys\nimport rospy\nimport cv2\nfrom std_msgs.msg import String\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge, CvBridgeError\n\nclass image_converter:\n\n def __init__(self):\n self.image_pub = rospy.Publisher(\"/nose/color/image_raw\",Image)\n\n self.bridge = CvBridge()\n self.image_sub = rospy.Subscriber(\"/camera/color/image_raw\",Image,self.callback)\n\n def callback(self,data):\n try:\n cv_image = self.bridge.imgmsg_to_cv2(data, \"bgr8\")\n except CvBridgeError as e:\n print(e)\n\n (rows,cols,channels) = cv_image.shape\n if cols > 60 and rows > 60 :\n cv2.circle(cv_image, (50,50), 10, 255)\n\n cv2.imshow(\"Image window\", cv_image)\n cv2.waitKey(3)\n\n try:\n self.image_pub.publish(self.bridge.cv2_to_imgmsg(cv_image, \"bgr8\"))\n except CvBridgeError as e:\n print(e)\n\ndef main(args):\n ic = image_converter()\n rospy.init_node('image_converter', anonymous=True)\n try:\n rospy.spin()\n except KeyboardInterrupt:\n print(\"Shutting down\")\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n main(sys.argv)\n","repo_name":"richtong888/Nose_Detect","sub_path":"catkin_ws/src/Dlib_detection/src/image_subscriber.py","file_name":"image_subscriber.py","file_ext":"py","file_size_in_byte":2360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"11786050430","text":"cancion = {\n 'artista': 'Metallica', \n 'cancion': 'Enter Sandman',\n 'lanzamiento': 1992,\n 'likes': 3000\n}\nprint(cancion)\n#accede a un elemento\nprint(cancion['artista'])\n#mezclar con un string \nartista= cancion['artista']\nprint(f'Estoy escuchando a {artista}')\n#agregar nuevos valores\ncancion['playlist'] = 'Heavy Metal'\nprint(cancion)\n#reemplazar valor existente \ncancion['cancion'] = 'Seek & Destroy'\nprint(cancion)\n#eliminar valor\ndel cancion['lanzamiento']\nprint(cancion)","repo_name":"conimorales/Programaci-n-con-Python","sub_path":"python_udemy/12-diccionario.py","file_name":"12-diccionario.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"37485027298","text":"import turtle \nimport time # Allows us to use turtles\nwn = turtle.Screen() # Creates a playground for turtles\nmamene = turtle.Turtle() # Create a turtle, assign to mamene\n\n # Tell mamene to move forward by 50 units \nmamene.width(8)\nmamene.left(90)\nmamene.color(\"green\")\nmamene.circle(45,360)\nmamene.right(180)\nmamene.circle(45,450)\nmamene.right(180)\nmamene.left(90)\nmamene.forward(200)\nmamene.left(180)\nmamene.circle(45,-180)\nmamene.left(90)\nmamene.forward(90)\nmamene.left(180)\nmamene.forward(90)\nmamene.right(90)\nmamene.forward(200)\nmamene.penup()\nmamene.right(90)\nmamene.forward(45)\nmamene.right(90)\nmamene.forward(215)\nmamene.pendown()\nmamene.forward(30)\nwn.mainloop() # Wait for user to close window","repo_name":"funnybr0ther/Python-Bac1","sub_path":"projet_NASA.py","file_name":"projet_NASA.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"19452633906","text":"from datetime import datetime\nfrom pathlib import Path\nfrom pyshell.commands.command import ICommand\nfrom pyshell.commands.command_flags import CommandFlags\nfrom pyshell.commands.command_metadata import CommandMetadata\nfrom pyshell.commands.command_result import CommandResult\nfrom pyshell.commands.sync_command_result import SyncCommandResult\nfrom pyshell.core.pyshell import PyShell\nfrom pyshell.core.platform_statics import PlatformStatics\nfrom pyshell.tracing.caller_info import CallerInfo\nimport sys\nfrom typing import Optional, Sequence\n\nclass ExternalCommand(ICommand):\n \"\"\"\n Base class for commands that run external executables.\n PyShell scripts may use this command to run executables for which PyShell\n does not have native support for. Running a command via this class instead\n of running it via `subprocess` will allow PyShell to log the command and\n handle any errors using the standard PyShell error handling mechanisms.\n @ingroup commands\n \"\"\"\n def __init__(self,\n name: str | Path,\n args: str | Path | Sequence[str | Path] | None = None,\n locate_executable: bool = True,\n cmd_flags: int = CommandFlags.STANDARD):\n \"\"\"\n Initializes the command.\n @param name The name of the command being run. This should be the name\n of the executable/command being run but should not include any of\n the arguments.\n @param args The argument(s) to pass to the command.\n @param locate_executable Whether to locate the executable in the PATH.\n If this is true, this constructor will throw if the executable cannot\n be found in the PATH.\n @param cmd_flags Flags for the command.\n \"\"\"\n # Store arguments in a uniform state regardless of input type\n self._name = str(name)\n if isinstance(args, str) or isinstance(args, Path):\n args = [args]\n elif not args:\n args = []\n self._args = [str(a) for a in args]\n self._flags = cmd_flags\n self._origin = CallerInfo.closest_external_frame()\n self._locate_executable = locate_executable\n\n\n @property\n def metadata(self) -> CommandMetadata:\n \"\"\"\n The metadata for the command.\n \"\"\"\n return CommandMetadata(\n self._name,\n self._args,\n self._flags,\n self.scanner\n )\n\n\n @property\n def command_name(self) -> str:\n \"\"\"\n The name of the command being run.\n This contains the name of the executable/command being run but does not\n include any of the arguments.\n \"\"\"\n return self._name\n\n\n @property\n def args(self) -> Sequence[str]:\n \"\"\"\n The arguments passed to the command.\n \"\"\"\n return self._args\n\n\n @property\n def full_command(self) -> Sequence[str]:\n \"\"\"\n The full command being run, including the command name and all arguments.\n \"\"\"\n return [self.command_name] + self._args\n\n\n @property\n def origin(self) -> CallerInfo:\n \"\"\"\n Gets the location that the command was created at.\n This location will always be the location in the script that uses\n PyShell, not an internal PyShell location.\n \"\"\"\n return self._origin\n\n\n def __call__(self,\n pyshell: Optional[PyShell] = None,\n cwd: str | Path | None = None) -> CommandResult:\n \"\"\"\n Runs the command on the specified backend.\n @param pyshell PyShell instance to execute the command via.\n @param cwd The current working directory to use for the command. If this\n is not provided, the pyshell instance's cwd will be used.\n \"\"\"\n pyshell = self._resolve_pyshell_instance(pyshell)\n\n # Verify that the executable exists in the PATH if requested\n error_msg: Optional[str] = None\n if self._locate_executable:\n try:\n exe_path = PlatformStatics.resolve_using_path(self._name)\n except FileNotFoundError:\n error_msg = f\"Executable '{self._name}' not found in PATH.\\n\"\n else:\n exe_path = self._name\n if not Path(exe_path).is_file():\n error_msg = f\"Executable '{exe_path}' not found.\\n\"\n\n # If the executable could not be found, print an error message and\n # return a failed result\n if error_msg:\n error_msg += \"Note: Command was declared at \" + \\\n f\"{self.origin.file_path}:{self.origin.line_number}\"\n print(error_msg, file=sys.stderr)\n return SyncCommandResult(\n self._name,\n self._args,\n str(cwd) if cwd else str(pyshell.cwd),\n error_msg,\n 1,\n False,\n datetime.now(),\n datetime.now()\n )\n\n # Make sure that all arguments to the command are valid\n error_msg = self._validate_args()\n if error_msg:\n return SyncCommandResult(\n self._name,\n self._args,\n str(cwd) if cwd else str(pyshell.cwd),\n error_msg,\n 1,\n False,\n datetime.now(),\n datetime.now()\n )\n\n return pyshell.run(self.metadata, cwd)\n\n\n def _validate_args(self) -> Optional[str]:\n \"\"\"\n Validates the arguments for the command.\n This method should be overridden by subclasses to validate the arguments\n for the command. If the arguments are valid, this method should\n return None. If the arguments are invalid, this method should return\n a string describing the error.\n @returns None if the arguments are valid, or a string describing the\n error if the arguments are invalid.\n \"\"\"\n return None\n","repo_name":"zkWildfire/PyShell","sub_path":"source/pyshell/commands/external_command.py","file_name":"external_command.py","file_ext":"py","file_size_in_byte":5930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"8040133885","text":"from lib2to3.pgen2.pgen import DFAState\nfrom gary import OkexSpot\n\nclass Strategy:\n def __init__(self):\n self.exchange = OkexSpot(\n symbol=\"BTC-USDT\",\n access_key=\"d8b0ca99-1037-4d70-988d-7521d7cd7449\",\n secret_key=\"7A2D7339EFC6B18924FD7C911B414A4B\",\n passphrase=\"QAczY8mYg9tSSg4%\",\n host=None\n )\n print(\"Strategy start run...\")\n def get_info(self):\n trade, error = self.exchange.get_trade()\n print(\"trade:\", trade)\n print(\"error:\", error)\nif __name__ == '__main__':\n import time\n strategy = Strategy()\n strategy.get_info()","repo_name":"eminentgu/ML_learning_notes","sub_path":"草稿本/量化/okex/zhihu/strategy.py","file_name":"strategy.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"25844867285","text":"from flask import Blueprint, request, Response, json\nfrom ponyexpress.models.package import Package\nfrom ponyexpress.models.node import Node\nfrom ponyexpress.api.exceptions import *\n\nquery = Blueprint('query', __name__)\n\n\ndef hypermedia_headers(uri, page, paginator):\n #add pagination headers\n link = []\n\n if paginator.has_next:\n url = '<%s?page=%s&limit=%s>; rel=\"next\"' % (uri, paginator.next_num, paginator.per_page)\n link.append(url)\n\n if paginator.has_prev:\n url = '<%s?page=%s&limit=%s>; rel=\"prev\"' % (uri, paginator.prev_num, paginator.per_page)\n link.append(url)\n\n if page < paginator.pages:\n url = '<%s?page=%s&limit=%s>; rel=\"last\"' % (uri, paginator.pages, paginator.per_page)\n link.append(url)\n\n if page > 1 and paginator.pages > 1:\n url = '<%s?page=%s&limit=%s>; rel=\"first\"' % (uri, 1, paginator.per_page)\n link.append(url)\n\n headers = {\n 'Link': ','.join(link)\n }\n\n return headers\n\n\n@query.route('/v1/reports', methods=['GET'])\ndef reports():\n result = []\n\n limit = int(request.args.get('limit', 100))\n page = int(request.args.get('page', 1))\n\n if (10 <= limit <= 100) and page >= 1:\n #queried_nodes = Node.query.limit(limit).offset(offset)\n paginator = Node.query.paginate(page=page, per_page=limit, error_out=False)\n else:\n raise InvalidAPIUsage('Invalid request', 410)\n\n if paginator:\n for n in paginator.items:\n res = {\n 'id': n.name,\n 'packages': [],\n }\n result.append(res)\n\n headers = hypermedia_headers(request.base_url, page, paginator)\n\n return Response(json.dumps(result), mimetype='application/json', headers=headers)\n else:\n raise InvalidAPIUsage('Invalid request', 410)\n\n","repo_name":"TelekomCloud/pony-express","sub_path":"ponyexpress/api/v1/reports.py","file_name":"reports.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"44"} +{"seq_id":"28959551028","text":"from os import close\n\n\nCreationO = open(file=\"Creation.txt\",mode=\"r\")\nCreation = CreationO.readline(1)\nnameO = open(\"name.txt\",\"a+\")\nageO = open(\"age.txt\",\"a+\")\ncountryO = open(\"country.txt\",\"a+\")\n#^^^Importing files^^^\n#\\/Short creation\\/\nif Creation == \"0\":\n CreationO.close\n print(\"Welcome plese add informations to use this system\")\n name = input(\"Name: \")\n age = input(\"age in words: \")\n country = input(\"Country: \")\n print(\"Thanks!\")\n nameO.write(name)\n ageO.write(age)\n countryO.write(country)\n CreationO = open(file=\"Creation.txt\",mode=\"w+\")\n CreationO.write(\"True\")\n#\\/First code(pick action)\\/\nprint(\"Hello\",nameO.readline(1))\nprint(\"I'm Si your bot asistent\")\nprint(\"what you want to do?\")\nprint(\"1.show me the apps \\n2.wants to do the setup again\")\n\n \n\n","repo_name":"Wrxw/WindowS-1.00","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"6178949957","text":"# Codejam 2020, Round 1A: Pattern Matching\n\n\nclass Pattern:\n def __init__(self, fragments):\n self.prefix = fragments[0]\n self.suffix = fragments[-1]\n self.middle = \"\".join(fragments[1:-1])\n\n\ndef match_patterns(patterns):\n prefix = max((p.prefix for p in patterns), key=len)\n suffix = max((p.suffix for p in patterns), key=len)\n\n prefix_check = all(prefix.startswith(p.prefix) for p in patterns)\n suffix_check = all(suffix.endswith(p.suffix) for p in patterns)\n\n if prefix_check and suffix_check:\n middle = \"\".join(p.middle for p in patterns)\n return prefix + middle + suffix\n return '*'\n\n\n# I/O Code\nnum_cases = int(input())\nfor case in range(1, num_cases + 1):\n N = int(input())\n patterns = [Pattern(input().split('*')) for _ in range(N)]\n\n result = match_patterns(patterns)\n print('Case #{}: {}'.format(case, result))\n","repo_name":"theXYZT/codejam-2020","sub_path":"Round 1A/pattern-matching.py","file_name":"pattern-matching.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"44"} +{"seq_id":"4595952205","text":"import gym\nfrom gym import spaces\nimport numpy as np\nfrom tkinter import *\n\n\ndef calculate_reward(grid, solution):\n width = len(grid[0])\n height = len(grid)\n reward = 0\n\n for i in range(width):\n for j in range(height):\n if grid[i][j] != solution[i][j]:\n reward -= 1\n return reward\n\n\ndef generate_random_grid(height, width):\n # generate random playground fill with bools\n grid = np.random.choice(a=[False, True], size=(width, height)).tolist()\n return grid\n\n\ndef read_columns_from_grid(grid):\n columns = []\n for col in range(len(grid)):\n column = [row[col] for row in grid]\n last_false = -1\n c = []\n for i, cell in enumerate(column):\n if not cell:\n if last_false + 1 < i:\n c.append(len(column[last_false + 1:i]))\n last_false = i\n if last_false + 1 < len(column):\n c.append(len(column[last_false + 1:len(column)]))\n columns.append(c)\n\n return columns\n\n\ndef read_rows_from_grid(grid):\n rows = []\n for row in grid:\n r = []\n last_false = -1\n for i, cell in enumerate(row):\n if not cell:\n if last_false + 1 < i:\n r.append(len(row[last_false+1:i]))\n last_false = i\n if last_false+1 < len(row):\n r.append(len(row[last_false+1:len(row)]))\n rows.append(r)\n return rows\n\n\ndef generated_grid_with_numbers(grid, columns, rows):\n table = []\n extra_width = int(len(columns) / 2) + 1\n width = len(columns) + extra_width\n extra_height = int(len(rows) / 2) + 1\n height = len(rows) + extra_height\n\n for i in range(width):\n t = [0] * extra_width\n if width <= (i + len(columns)):\n for ind, x in enumerate(columns[i - len(t)]):\n t[ind] += x\n table.append(t)\n table = np.array(table).T.tolist()\n for i in range(len(rows)):\n t = [0] * extra_height\n for ind, x in enumerate(rows[i]):\n t[ind] += x\n table.append(t + grid[i])\n return table\n\n\nclass NonogramEnv(gym.Env):\n \"\"\"Custom Environment that follows gym interface\"\"\"\n metadata = {'render.modes': ['human']}\n\n def __init__(self, width, height):\n super(NonogramEnv, self).__init__()\n\n self.game_width = width\n self.game_height = height\n\n # Define action and observation space\n # They must be gym.spaces objects\n # Example when using discrete actions:\n self.action_space = spaces.Discrete(2 * self.game_width * self.game_height)\n # Example for using image as input:\n self.observation_space = spaces.Discrete(\n (self.game_width + int(self.game_width / 2) + 1) * (self.game_height + int(self.game_height / 2) + 1))\n\n self.game_grid = generate_random_grid(self.game_height, self.game_width)\n self.solution = self.game_grid.copy()\n self.columns = read_columns_from_grid(self.game_grid)\n self.rows = read_rows_from_grid(self.game_grid)\n\n def step(self, action):\n # Execute one time step within the environment\n\n self._take_step(action)\n\n reward = calculate_reward(self.game_grid, self.solution)\n # print(\"action, reward: \", action, reward)\n\n obs = self._next_observation()\n done = not any(self.game_grid)\n\n return obs, reward, done, {}\n\n def reset(self):\n # Reset the state of the environment to an initial state\n # self.game_grid = np.empty((self.game_width, self.game_height))\n data = [None] * self.game_width * self.game_height\n self.game_grid = np.reshape(data, (self.game_width, self.game_height)).tolist()\n return self._next_observation() # TODO\n\n def render(self, mode='human', close=False):\n # Render the environment to the screen\n\n table = generated_grid_with_numbers(self.game_grid, self.columns, self.rows)\n # print(table)\n\n print_table = []\n for row in table:\n print_table.append(['' if i is None else i for i in row])\n\n root = Tk()\n t = Table(root, print_table)\n root.mainloop()\n\n return None # TODO\n\n def _next_observation(self):\n return generated_grid_with_numbers(self.game_grid, self.columns, self.rows)\n\n def _take_step(self, action):\n value = True if action >= self.game_width*self.game_height else False\n if value:\n action -= 25\n\n row_index = int(action/self.game_width)\n col_index = action - row_index*self.game_width\n self.game_grid[row_index][col_index] = value\n\n\nclass Table:\n\n def __init__(self, root, data):\n\n width = len(data[0])\n height = len(data)\n\n # code for creating table\n for i in range(width):\n for j in range(height):\n self.e = Entry(root, width=20, fg='black',\n font=('Arial', 16, 'bold'))\n\n self.e.grid(row=i, column=j)\n self.e.insert(END, data[i][j])\n","repo_name":"OleApp/Nonogram_DQN_Solver","sub_path":"NonogramEnv.py","file_name":"NonogramEnv.py","file_ext":"py","file_size_in_byte":5067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"13252665246","text":"'''\nGiven a string s, find the length of the longest substring without repeating characters.\n\n\n\nExample 1:\n\nInput: s = \"abcabcbb\"\nOutput: 3\nExplanation: The answer is \"abc\", with the length of 3.\nExample 2:\n\nInput: s = \"bbbbb\"\nOutput: 1\nExplanation: The answer is \"b\", with the length of 1.\nExample 3:\n\nInput: s = \"pwwkew\"\nOutput: 3\nExplanation: The answer is \"wke\", with the length of 3.\nNotice that the answer must be a substring, \"pwke\" is a subsequence and not a substring.\nExample 4:\n\nInput: s = \"\"\nOutput: 0\n'''\n\n\ndef lengthOfLongestSubstring(s: str) -> int:\n str_len = len(s)\n char_dict = [0] * 128\n right = left = 0\n res = 0\n while right < str_len:\n right_char = s[right]\n char_dict[ord(right_char)] += 1\n\n while char_dict[ord(right_char)] > 1:\n left_char = s[left]\n char_dict[ord(left_char)] -= 1\n left += 1\n\n res = max(res, right - left + 1)\n right += 1\n\n return res\n\n\ns = \"abcabcbb\"\nexpected_ret_val = 3\nret_val = lengthOfLongestSubstring(s)\nif expected_ret_val != ret_val:\n print(\"expected to get:\" + str(expected_ret_val) + \", BUT instead got:\" + str(ret_val))\n exit(1)\n\ns = \"bbbbb\"\nexpected_ret_val = 1\nret_val = lengthOfLongestSubstring(s)\nif expected_ret_val != ret_val:\n print(\"expected to get:\" + str(expected_ret_val) + \", BUT instead got:\" + str(ret_val))\n exit(1)\n\ns = \"pwwkew\"\nexpected_ret_val = 3\nret_val = lengthOfLongestSubstring(s)\nif expected_ret_val != ret_val:\n print(\"expected to get:\" + str(expected_ret_val) + \", BUT instead got:\" + str(ret_val))\n exit(1)\n\ns = \"tmmzuxt\"\nexpected_ret_val = 5\nret_val = lengthOfLongestSubstring(s)\nif expected_ret_val != ret_val:\n print(\"expected to get:\" + str(expected_ret_val) + \", BUT instead got:\" + str(ret_val))\n exit(1)","repo_name":"guyavrah1986/learnPython","sub_path":"learnPython/questions/aws/longestSubStringWithoutRepatingCharacters.py","file_name":"longestSubStringWithoutRepatingCharacters.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"7392134401","text":"# Reconstruct adjacency matrix by Rui Zhang\r\ndef Reconstruct(self, beta):\r\n # X : n*d\r\n n, d = self.X.size()\r\n A = (self.X).mm(self.X.T)\r\n A[A < 1e-4] = 0\r\n F = torch.sigmoid(A)\r\n S = torch.zeros(n, n)\r\n E = L2_distance_2(self.X, self.X)\r\n A_alpha = (F - beta * E)\r\n for i2 in range(n):\r\n tran = EProjSimplex_new(A_alpha[:, i2:i2 + 1], 1)\r\n S[:, i2:i2 + 1] = tran\r\n S = (S + S.T) / 2\r\n return S\r\n\r\n\r\ndef EProjSimplex_new(v, k=1):\r\n ft = 1\r\n n = v.shape[0]\r\n v0 = v - torch.mean(v) + k / n\r\n vmin = torch.min(v0)\r\n v1_0 = torch.zeros(n, 1)\r\n if vmin < 0:\r\n f = 1\r\n lambda_m = 0\r\n while abs(f) > 1e-4:\r\n v1 = v0 - lambda_m\r\n posidx = v1 > 0\r\n npos = sum(posidx.float())\r\n g = -npos\r\n f = sum(v1[posidx]) - k\r\n lambda_m = lambda_m - f / (g + 1e-6)\r\n ft = ft + 1\r\n v1_0 = v1_0.type(v1.type())\r\n if ft > 100:\r\n x = torch.max(v1, v1_0)\r\n break\r\n x = torch.max(v1, v1_0)\r\n else:\r\n x = v0\r\n return x\r\n","repo_name":"LCHJ/BAGE_Unsupervised_Graph_Embedding_via_Adaptive_Pytorch","sub_path":"Graph_Embedding/functions/Rui Zhang.py","file_name":"Rui Zhang.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"10814446550","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n'''\n@File : 翻转二叉树.py\n@Time : 2020/08/21 22:14:41\n@Author : Dll \n@Contact : dengll1783600@foxmail.com\n@Desc : 翻转二叉树的所有节点\n'''\n\n# here put the import lib\n'''\n翻转一棵二叉树。\n示例:\n输入:\n 4\n / \\\n 2 7\n / \\ / \\\n1 3 6 9\n输出:\n 4\n / \\\n 7 2\n / \\ / \\\n9 6 3 1\n\n这道题的主要思路就是从上到下交换子树,再交换子树的子树,循环下去……,把每一个节点的子树交换后,即可。\n所以核心的任务就是遍历节点了,不管是用递归还是迭代,都行。\n思路一:递归,包括前序遍历、中序遍历、后序遍历\n思路二:迭代,层次遍历,把节点一个个放在队列中\n'''\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n \n # 自己想的方法,直接交换镜像位置的节点的值,但是有些案例跑不通,费解……\n # return root\n # def invert(node1, node2):\n # if not node1 and not node2:\n # return \n # elif not node1 and node2:\n # node1 = TreeNode(node2.val)\n # node2 = TreeNode(None)\n # elif not node2 and node1:\n # node2 = TreeNode(node1.val) \n # node1 = TreeNode(None)\n # else:\n # node1.val, node2.val = node2.val, node1.val\n # invert(node1.left, node2.right)\n # invert(node1.right, node2.left)\n # invert(root.left, root.right)\n # return root\n \n # 递归:前序遍历\n def invertTree1(self, root: TreeNode) -> TreeNode:\n if root is None:\n return root\n # 先交换当前节点的左右子树\n root.left, root.right = root.right, root.left\n # 递归左子节点\n self.invertTree1(root.left)\n # 递归右子节点\n self.invertTree1(root.right)\n return root\n \n # 递归:中序遍历\n def invertTree2(self, root: TreeNode) -> TreeNode:\n if root is None:\n return root\n # 先交换左子节点\n self.invertTree2(root.left)\n # 再交换当前节点\n root.left, root.right = root.right, root.left\n # 最后交换右子节点,注意此时的右子节点已经是root.left了\n self.invertTree2(root.left)\n return root\n \n # 递归:后序遍历\n def invertTree3(self, root: TreeNode) -> TreeNode:\n if root is None:\n return root\n # 递归左子节点\n self.invertTree3(root.left)\n # 递归右子节点\n self.invertTree3(root.right)\n # 交换左右子树\n root.left, root.right = root.right, root.left\n return root\n\n # 层次遍历\n def invertTree4(self, root: TreeNode) -> TreeNode:\n if root is None:\n return root\n queue = [root]\n while queue:\n node = queue.pop(0)\n node.left, node.right = node.right, node.left\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n return root\n","repo_name":"bigsmallwhite/algorithm_learning","sub_path":"leetcode/树/5-翻转二叉树.py","file_name":"5-翻转二叉树.py","file_ext":"py","file_size_in_byte":3269,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"36474612182","text":"from tornado.escape import json_decode\nfrom tornado.testing import AsyncTestCase, gen_test\n\nfrom stringdb.api import StringDB\nfrom proteomicsdb.api import ProteomicsDB\nfrom interactome_atlas.api import InteractomeAtlas\n\nclass TestStringDB(AsyncTestCase):\n @gen_test\n def test_get_string_ids(self):\n s = StringDB()\n res = yield s.get_string_ids([\"MANEA_MOUSE\", \"DPP10_MOUSE\", \"ASIC1_MOUSE\"], 10090)\n\n @gen_test\n def test_get_string_ids(self):\n s = StringDB()\n res = yield s.get_interaction([\"MANEA_MOUSE\", \"DPP10_MOUSE\", \"ASIC1_MOUSE\"], 10090, \"physical\")\n\n @gen_test\n def test_enrichment(self):\n s = StringDB()\n res = yield s.get_enrichment([\"MANEA_MOUSE\"], [\"MANEA_MOUSE\", \"DPP10_MOUSE\", \"ASIC1_MOUSE\"], 10090)\n print(res)\n\nclass TestProteomicsDB(AsyncTestCase):\n @gen_test\n def test_get_expression(self):\n p = ProteomicsDB()\n res = yield p.get_expression(\"P00533\")\n print(json_decode(res)[\"d\"][\"results\"][0])\n\nclass TestInteractomeAtlas(AsyncTestCase):\n @gen_test\n def test_get_interactome(self):\n i = InteractomeAtlas()\n res = yield i.get_interactions(\"COL4A3BP\")\n print(json_decode(json_decode(res))[\"all_interactions\"])","repo_name":"noatgnu/cactus","sub_path":"tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"5264774888","text":"from sklearn.datasets import load_boston\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import SGDRegressor\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.preprocessing import StandardScaler\n\n\nif __name__ == \"__main__\":\n boston = load_boston()\n\n boston = load_boston()\n boston = load_boston()\n\n X_train_boston, X_test_boston, y_train_boston, y_test_boston = train_test_split(boston.data,\n boston.target,\n test_size=0.2,\n random_state=42)\n\n robust = SGDRegressor(loss='huber',\n penalty='l2',\n alpha=0.0001,\n fit_intercept=False,\n max_iter=100,\n shuffle=True,\n verbose=1,\n epsilon=0.1,\n random_state=42,\n learning_rate='invscaling',\n eta0=0.01,\n power_t=0.5)\n\n sc_boston = StandardScaler()\n X_train_boston = sc_boston.fit_transform(X_train_boston)\n X_test_boston = sc_boston.transform(X_test_boston)\n\n robust.fit(X_train_boston, y_train_boston)\n\n print(mean_squared_error(y_test_boston, robust.predict(X_test_boston)) ** 0.5)\n\n\n pass\n\n","repo_name":"sungheeyun/optmlstat","sub_path":"experiments/online_learning.py","file_name":"online_learning.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"44"} +{"seq_id":"37236280304","text":"from typing import Dict, Any\nfrom random import uniform\nimport asyncio\nimport logging\nimport time\n\nfrom mautrix.bridge import Bridge\nfrom mautrix.types import RoomID, UserID\nfrom mautrix.util.opt_prometheus import Gauge\n\n\nfrom .version import version, linkified_version\nfrom .config import Config\nfrom .db import upgrade_table, init as init_db\nfrom .matrix import MatrixHandler\nfrom .signal import SignalHandler\nfrom .user import User\nfrom .portal import Portal\nfrom .puppet import Puppet\nfrom .web import ProvisioningAPI\nfrom . import commands\n\nACTIVE_USER_METRICS_INTERVAL_S = 60\nONE_DAY_MS = 24 * 60 * 60 * 1000\nSYNC_JITTER = 10\n\nMETRIC_ACTIVE_PUPPETS = Gauge('bridge_active_puppets_total', 'Number of active Signal users bridged into Matrix')\nMETRIC_BLOCKING = Gauge('bridge_blocked', 'Is the bridge currently blocking messages')\nclass SignalBridge(Bridge):\n module = \"mautrix_signal\"\n name = \"mautrix-signal\"\n command = \"python -m mautrix-signal\"\n description = \"A Matrix-Signal puppeting bridge.\"\n repo_url = \"https://github.com/mautrix/signal\"\n real_user_content_key = \"net.maunium.signal.puppet\"\n version = version\n markdown_version = linkified_version\n config_class = Config\n matrix_class = MatrixHandler\n upgrade_table = upgrade_table\n\n matrix: MatrixHandler\n signal: SignalHandler\n config: Config\n provisioning_api: ProvisioningAPI\n periodic_sync_task: asyncio.Task\n periodic_active_metrics_task: asyncio.Task\n bridge_blocked: bool = False\n\n def prepare_db(self) -> None:\n super().prepare_db()\n init_db(self.db)\n\n def prepare_bridge(self) -> None:\n self.signal = SignalHandler(self)\n super().prepare_bridge()\n cfg = self.config[\"bridge.provisioning\"]\n self.provisioning_api = ProvisioningAPI(self, cfg[\"shared_secret\"])\n self.az.app.add_subapp(cfg[\"prefix\"], self.provisioning_api.app)\n\n async def start(self) -> None:\n User.init_cls(self)\n self.add_startup_actions(Puppet.init_cls(self))\n Portal.init_cls(self)\n if self.config[\"bridge.resend_bridge_info\"]:\n self.add_startup_actions(self.resend_bridge_info())\n self.add_startup_actions(self.signal.start())\n await super().start()\n self.periodic_sync_task = asyncio.create_task(self._periodic_sync_loop())\n self.periodic_active_metrics_task = asyncio.create_task(self._loop_active_puppet_metric())\n\n async def stop(self) -> None:\n await super().stop()\n await self.db.stop()\n asyncio.create_task(Portal.start_disappearing_message_expirations())\n\n @staticmethod\n async def _actual_periodic_sync_loop(log: logging.Logger, interval: int) -> None:\n while True:\n try:\n await asyncio.sleep(interval)\n except asyncio.CancelledError:\n return\n log.info(\"Executing periodic syncs\")\n for user in User.by_username.values():\n # Add some randomness to the sync to avoid a thundering herd\n await asyncio.sleep(uniform(0, SYNC_JITTER))\n try:\n await user.sync()\n except asyncio.CancelledError:\n return\n except Exception:\n log.exception(\"Error while syncing %s\", user.mxid)\n\n async def _periodic_sync_loop(self) -> None:\n log = logging.getLogger(\"mau.periodic_sync\")\n interval = self.config[\"bridge.periodic_sync\"]\n if interval <= 0:\n log.debug(\"Periodic sync is not enabled\")\n return\n log.debug(\"Starting periodic sync loop\")\n await self._actual_periodic_sync_loop(log, interval)\n log.debug(\"Periodic sync stopped\")\n\n def prepare_stop(self) -> None:\n self.add_shutdown_actions(self.signal.stop())\n for puppet in Puppet.by_custom_mxid.values():\n puppet.stop()\n\n async def resend_bridge_info(self) -> None:\n self.config[\"bridge.resend_bridge_info\"] = False\n self.config.save()\n self.log.info(\"Re-sending bridge info state event to all portals\")\n async for portal in Portal.all_with_room():\n await portal.update_bridge_info()\n self.log.info(\"Finished re-sending bridge info state events\")\n\n async def get_user(self, user_id: UserID, create: bool = True) -> User:\n return await User.get_by_mxid(user_id, create=create)\n\n async def get_portal(self, room_id: RoomID) -> Portal:\n return await Portal.get_by_mxid(room_id)\n\n async def get_puppet(self, user_id: UserID, create: bool = False) -> Puppet:\n return await Puppet.get_by_mxid(user_id, create=create)\n\n async def get_double_puppet(self, user_id: UserID) -> Puppet:\n return await Puppet.get_by_custom_mxid(user_id)\n\n def is_bridge_ghost(self, user_id: UserID) -> bool:\n return bool(Puppet.get_id_from_mxid(user_id))\n\n async def _update_active_puppet_metric(self, log: logging.Logger) -> None:\n maxActivityDays = self.config['bridge.limits.puppet_inactivity_days']\n minActivityDays = self.config['bridge.limits.min_puppet_activity_days']\n users = await Puppet.all_with_initial_activity()\n currentMs = time.time() / 1000\n activeUsers = 0\n for user in users:\n daysOfActivity = (user.last_activity_ts - user.first_activity_ts / 1000) / ONE_DAY_MS\n # If maxActivityTime is not set, they are always active\n isActive = maxActivityDays is None or (currentMs - user.last_activity_ts) <= (maxActivityDays * ONE_DAY_MS) \n if isActive and daysOfActivity > minActivityDays:\n activeUsers += 1\n blockOnLimitReached = self.config['bridge.limits.block_on_limit_reached']\n maxPuppetLimit = self.config['bridge.limits.max_puppet_limit']\n if blockOnLimitReached is not None and maxPuppetLimit is not None:\n self.bridge_blocked = maxPuppetLimit < activeUsers\n METRIC_BLOCKING.set(int(self.bridge_blocked))\n log.debug(\"Current active puppet count is %d\", activeUsers)\n METRIC_ACTIVE_PUPPETS.set(activeUsers)\n\n async def _loop_active_puppet_metric(self) -> None:\n log = logging.getLogger(\"mau.active_puppet_metric\")\n\n while True:\n try:\n await asyncio.sleep(ACTIVE_USER_METRICS_INTERVAL_S)\n except asyncio.CancelledError:\n return\n log.info(\"Executing periodic active puppet metric check\")\n try:\n await self._update_active_puppet_metric(log)\n except asyncio.CancelledError:\n return\n except Exception as e:\n log.exception(\"Error while checking\", e)\n\n async def count_logged_in_users(self) -> int:\n return len([user for user in User.by_username.values() if user.username])\n\n async def manhole_global_namespace(self, user_id: UserID) -> Dict[str, Any]:\n return {\n **await super().manhole_global_namespace(user_id),\n \"User\": User,\n \"Portal\": Portal,\n \"Puppet\": Puppet,\n }\n\n\nSignalBridge().run()\n","repo_name":"terrorizer1980/mautrix-signal","sub_path":"mautrix_signal/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":7163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"44"} +{"seq_id":"2927729788","text":"\n# coding: utf-8\n\n# ### name : Omkar Thawakar\n# #### Reg No : 2015BCS003 __ ____Roll_No : A-08 _____ Batch: A-01 \n# #### Aim : Implement General Fuzzy Min Max Neural Network Classifier \n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\n\n\n# In[84]:\n\n\nclass GFuzzyMinMaxNN:\n \n def __init__(self,sensitivity,theta=0.4):\n self.gamma = sensitivity\n self.hyperboxes = {}\n self.clasess = None\n self.V = []\n self.W = []\n self.U = []\n self.hyperbox_class = []\n self.theta = theta\n \n \n def func(self,r,gamma):\n if r*gamma>1:\n return 1\n elif 0<=r*gamma<=1 :\n return r*gamma\n else:\n return 0\n\n def fuzzy_membership(self,x,v,w):\n gamma = self.gamma\n xh_l , xh_u = x[0],x[1]\n return min([min(1-self.func(xh_u[i]-w[i] , gamma ) , 1-self.func(v[i]-xh_l[i] , gamma) ) for i in range(len(v))])\n\n \n def get_hyperbox(self,x,d):\n xh_l,xh_u = x[0],x[1]\n tmp = [0 for i in range(self.clasess)]\n tmp[d[0]-1] = 1\n \n \"\"\"\n If no hyperbox present initially so create new\n \"\"\"\n if len(self.V)==0 and len(self.W)==0 :\n self.V.append(xh_l)\n self.W.append(xh_u)\n self.hyperbox_class.append(d)\n self.U.append(tmp)\n expand = False\n return len(self.V)-1 , expand \n \n \"\"\"\n returns the most sutaible hyperbox for input pattern x\n otherwise None\n \"\"\"\n mylist = []\n \n for i in range(len(self.V)):\n if self.hyperbox_class[i]==[0]:\n test = [0 for _ in range(len(xh_l))]\n for _ in range(len(xh_l)):\n if self.theta >= (max(self.W[i][_],xh_u[_])-min(self.V[i][_],xh_l[_])):\n test[_]=1\n else:\n pass\n if test == [1 for _ in range(len(x))] :\n expand = True\n \"\"\"\n Label hyperbox with class label of input pattern\n \"\"\"\n self.hyperbox_class[i][0]=d[0] \n return i,expand\n elif self.hyperbox_class[i]==d:\n mylist.append((self.fuzzy_membership(x,self.V[i],self.W[i])))\n else:\n mylist.append(-1)\n \n if len(mylist)>0:\n for box in sorted(mylist)[::-1]:\n i = mylist.index(box)\n test = [0 for i in range(len(xh_l))]\n for _ in range(len(xh_l)):\n if self.theta >= (max(self.W[i][_],xh_u[_])-min(self.V[i][_],xh_l[_])):\n test[_]=1\n else:\n pass\n\n if test == [1 for _ in range(len(x))] :\n expand = True\n return i,expand\n\n '''\n No hyperbox follow expansion criteria so create new\n '''\n self.V.append(xh_l)\n self.W.append(xh_u)\n self.hyperbox_class.append(d)\n self.U.append(tmp)\n expand = False\n return len(self.V)-1 , expand\n \n else:\n \"\"\"\n If no hyperbox present for pattern x of class d so create new \n \"\"\"\n self.V.append(xh_l)\n self.W.append(xh_u)\n self.hyperbox_class.append(d)\n self.U.append(tmp)\n expand = False\n return len(self.V)-1,expand\n \n def expand(self,x,key):\n xh_l,xh_u = x[0],x[1]\n self.V[key] = [min(self.V[key][i],xh_l[i]) for i in range(len(xh_l))]\n self.W[key] = [max(self.W[key][i],xh_u[i]) for i in range(len(xh_u))]\n \n \n def overlap_Test(self):\n del_old = 1\n del_new = 1\n box_1,box_2,delta = -1,-1,-1\n for j in range(len(self.V)):\n if self.hyperbox_class[j] == [0] :\n for k in range(j+1,len(self.V)):\n for i in range(len(self.V[j])):\n \n \"\"\"\n Test Four cases given by Patrick Simpson\n \"\"\"\n \n if (self.V[j][i] < self.V[k][i] < self.W[j][i] < self.W[k][i]) :\n del_new = min(del_old,self.V[j][i]-self.V[k][i])\n elif (self.V[k][i] < self.V[j][i] < self.W[k][i] < self.W[j][i]) :\n del_new = min(del_old,self.W[k][i]-self.V[j][i])\n elif (self.V[j][i] < self.V[k][i] < self.W[k][i] < self.W[j][i]) :\n del_new = min(del_old,min(self.W[k][i]-self.V[j][i], self.W[j][i]-self.V[k][i]))\n elif (self.V[k][i] < self.V[j][i] < self.W[j][i] < self.W[k][i]) :\n del_new = min(del_old,min(self.W[j][i]-self.V[k][i], self.W[k][i]-self.V[j][i]))\n \n \"\"\"\n Check dimension for which overlap is minimum\n \"\"\"\n #print(del_old , del_new , del_old-del_new , i)\n if del_old - del_new > 0.0 :\n delta = i\n box_1,box_2 = j,k\n del_old = del_new\n del_new = 1\n else:\n pass\n \n else:\n for k in range(j+1,len(self.V)):\n if self.hyperbox_class[j]==self.hyperbox_class[k] :\n pass\n else:\n for i in range(len(self.V[j])):\n\n \"\"\"\n Test Four cases given by Patrick Simpson\n \"\"\"\n\n if (self.V[j][i] < self.V[k][i] < self.W[j][i] < self.W[k][i]) :\n del_new = min(del_old,self.V[j][i]-self.V[k][i])\n elif (self.V[k][i] < self.V[j][i] < self.W[k][i] < self.W[j][i]) :\n del_new = min(del_old,self.W[k][i]-self.V[j][i])\n elif (self.V[j][i] < self.V[k][i] < self.W[k][i] < self.W[j][i]) :\n del_new = min(del_old,min(self.W[k][i]-self.V[j][i], self.W[j][i]-self.V[k][i]))\n elif (self.V[k][i] < self.V[j][i] < self.W[j][i] < self.W[k][i]) :\n del_new = min(del_old,min(self.W[j][i]-self.V[k][i], self.W[k][i]-self.V[j][i]))\n\n \"\"\"\n Check dimension for which overlap is minimum\n \"\"\"\n #print(del_old , del_new , del_old-del_new , i)\n if del_old - del_new > 0.0 :\n delta = i\n box_1,box_2 = j,k\n del_old = del_new\n del_new = 1\n else:\n pass\n \n return delta , box_1, box_2\n \n \n def contraction(self,delta,box_1,box_2):\n if (self.V[box_1][delta] < self.V[box_2][delta] < self.W[box_1][delta] < self.W[box_2][delta]) :\n self.W[box_1][delta] = (self.W[box_1][delta]+self.V[box_2][delta])/2\n self.V[box_2][delta] = (self.W[box_1][delta]+self.V[box_2][delta])/2 \n \n elif (self.V[box_2][delta] < self.V[box_1][delta] < self.W[box_2][delta] < self.W[box_1][delta]) :\n self.W[box_2][delta] = (self.W[box_2][delta]+self.V[box_1][delta])/2\n self.V[box_1][delta] = (self.W[box_2][delta]+self.V[box_1][delta])/2\n \n elif (self.V[box_1][delta] < self.V[box_2][delta] < self.W[box_2][delta] < self.W[box_1][delta]) :\n if (self.W[box_2][delta]-self.V[box_1][delta])< (self.W[box_1][delta]-self.V[box_2][delta]):\n self.V[box_1][delta] = self.W[box_2][delta]\n else:\n self.W[box_1][delta] = self.V[box_2][delta]\n \n elif (self.V[box_2][delta] < self.V[box_1][delta] < self.W[box_1][delta] < self.W[box_2][delta]) :\n if (self.W[box_2][delta]-self.V[box_1][delta])< (self.W[box_1][delta]-self.V[box_2][delta]):\n self.W[box_2][delta] = self.V[box_1][delta]\n else:\n self.V[box_2][delta] = self.W[box_1][delta]\n \n def predict(self,x):\n mylist = []\n for i in range(len(self.V)):\n mylist.append([self.fuzzy_membership(x,self.V[i],self.W[i])])\n \n result = np.multiply(mylist,self.U)\n for i in range(self.clasess):\n print('pattern {} belongs to class {} with fuzzy membership value : {}'.format(x,i+1,max(result[:,i])))\n \n \n \n def train(self,X,d_,epochs):\n self.clasess = len(np.unique(np.array(d_)))\n for _ in range(epochs):\n print('epoch : {}'.format(_+1))\n print('='*70)\n\n for x,d in zip(X,d_):\n '''Get most sutaible hyperbox!!'''\n i , expand = self.get_hyperbox(x,d)\n\n print('input pattern : ',x , d)\n print('Hyperbox : {} , {} '.format(self.V[i],self.W[i]) )\n\n if expand:\n self.expand(x,i)\n print(\"Expanded Hyperbox : \",self.V[i] , self.W[i])\n \n \"\"\"\n As hyperbox expanded cheak overlap and contract according \n to cases given by Gabrys and Bargiela\n \"\"\"\n self.overlap_Test()\n \n\n print('='*70)\n \n print('final hyperbox : ')\n print('V : ',self.V)\n print('W : ',self.W)\n \n\n\n# In[51]:\n\n\nfuzzy = GFuzzyMinMaxNN(1,theta=0.3) \n\n\n# ## Dataset\n\n# In[52]:\n\n\nfuzzy.fuzzy_membership([[0.4,0.3],[0.4,0.3]],[0.4,0.3],[0.4,0.3])\n\n\n# In[53]:\n\n\nX = [[[0.4,0.3],[0.4,0.3]],[[0.6,0.25],[0.6,0.25]],[[0.7,0.2],[0.7,0.2]]]\nd = [[1],[1],[0]]\n\n\n# In[54]:\n\n\nfuzzy.train(X,d,1)\n\n\n# ### Testing of pattern \n\n# In[55]:\n\n\nfor x in X:\n fuzzy.predict(x)\n print('='*80)\n\n\n# ### Visualization of HyperBoxes\n\n# In[60]:\n\n\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\n\ndef draw_box(ax,a,b,color):\n if a==b :\n ax.scatter(a[0],a[1] , marker='*', c=color)\n else:\n width = abs(a[0] - b[0])\n height = abs(a[1] - b[1])\n ax.add_patch(patches.Rectangle(a, width, height, fill=False,edgecolor=color))\n \n\n\"\"\"\n plot dataset\n\"\"\"\nfig1 = plt.figure()\nax = fig1.add_subplot(111, aspect='equal',alpha=0.7)\n\n \n\"\"\"\n plot Hyperboxes\n\"\"\"\nfor i in range(len(fuzzy.V)):\n if fuzzy.hyperbox_class[i]==[1]:\n draw_box(ax,fuzzy.V[i],fuzzy.W[i],color='g')\n else:\n draw_box(ax,fuzzy.V[i],fuzzy.W[i],color='r')\n \nfor i in range(len(X)):\n if d[i] == [0]:\n draw_box(ax,X[i][0],X[i][1],color='r')\n #ax.scatter(X[i][0],X[i][1] , marker='o', c='g')\n elif d[i] == [1]:\n draw_box(ax,X[i][0],X[i][1],color='g')\n #ax.scatter(X[i][0],X[i][1] , marker='o', c='g')\n else:\n draw_box(ax,X[i][0],X[i][1],color='r')\n #ax.scatter(X[i][0],X[i][1] , marker='*', c='r')\n \nplt.xlabel('Dimension 1')\nplt.ylabel('Dimension 2')\nplt.title('Hyperboxes created during training')\nplt.xlim([0,1])\nplt.ylim([0,1])\n#plt.legend(('class 1','class 2'))\nplt.show()\n\n\n# In[59]:\n\n\nX[0][0] , fuzzy.V[0]\n\n\n# ## Iris Dataset Classification using Fuzzy Min Max NN\n\n# In[62]:\n\n\ndata = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', names=['PW','PL','SW','SL','Class'])\n\n\n# In[63]:\n\n\ndata['Class'] = data['Class'].replace(['Iris-setosa', 'Iris-versicolor','Iris-virginica'], [1,2,3])\n\n\n# In[64]:\n\n\nnp.random.shuffle(data.values)\n\n\n# In[65]:\n\n\ndata = data.sample(frac=1) #shuffle dataframe sample\n\n\n# In[66]:\n\n\ndata.head()\n\n\n# In[67]:\n\n\ndf = data[['PW','PL','SW','SL']]\n\n\n# In[68]:\n\n\ndf.head()\n\n\n# In[69]:\n\n\nnormalized_df=(df-df.min())/(df.max()-df.min())\n\n\n# In[70]:\n\n\ndata['Class'].values\n\n\n# In[71]:\n\n\n#choose 50% training and 50% testing sample\ntrain,test = normalized_df.values[:75,:4],normalized_df.values[75:,:4] \ntrain_labels,test_labels = data['Class'].values[:75],data['Class'].values[75:]\ntrain_labels,test_labels = train_labels.reshape((-1,1)),test_labels.reshape((-1,1))\n\n\n# In[72]:\n\n\ntrain.shape,test.shape\n\n\n# In[73]:\n\n\ntrain_labels.shape,test_labels.shape\n\n\n# In[74]:\n\n\ntrain,test = train.tolist(),test.tolist()\ntrain_labels,test_labels = train_labels.tolist(),test_labels.tolist()\n\n\n# In[76]:\n\n\nfor i in range(len(train)):\n train[i] = [train[i],train[i]]\nfor i in range(len(test)):\n test[i] = [test[i],test[i]]\n\n\n# In[77]:\n\n\ntrain[0]\n\n\n# In[95]:\n\n\nfuzzy = GFuzzyMinMaxNN(1,theta=0.5)\n\n\n# In[96]:\n\n\nfuzzy.train(train,train_labels,1)\n\n\n# In[97]:\n\n\nlen(fuzzy.V),len(fuzzy.W)\n\n\n# In[101]:\n\n\nfuzzy.V[74] , fuzzy.W[74]\n\n\n# ## In dimension 1 & 2\n\n# In[98]:\n\n\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\n\ndef draw_box(ax,a,b,color):\n if a==b :\n ax.scatter(a[0],a[1] , marker='*', c=color)\n else:\n width = abs(a[0] - b[0])\n height = abs(a[1] - b[1])\n ax.add_patch(patches.Rectangle(a, width, height, fill=False,edgecolor=color))\n \n\n\"\"\"\n plot dataset\n\"\"\"\nfig1 = plt.figure()\nax = fig1.add_subplot(111, aspect='equal',alpha=0.7)\n\n \n\"\"\"\n plot Hyperboxes\n\"\"\"\nfor i in range(len(fuzzy.V)):\n if fuzzy.hyperbox_class[i]==[1]:\n draw_box(ax,fuzzy.V[i],fuzzy.W[i],color='r')\n elif fuzzy.hyperbox_class[i]==[2]:\n draw_box(ax,fuzzy.V[i],fuzzy.W[i],color='g')\n else:\n draw_box(ax,fuzzy.V[i],fuzzy.W[i],color='b')\n \nfor i in range(len(train)):\n if train_labels[i] == [1]:\n draw_box(ax,train[i][0],train[i][1],color='r')\n \n elif train_labels[i] == [2]:\n draw_box(ax,train[i][0],train[i][1],color='g')\n \n else:\n draw_box(ax,train[i][0],train[i][1],color='b')\n \n \nplt.xlabel('Dimension 1')\nplt.ylabel('Dimension 2')\nplt.title('Hyperboxes created during training')\nplt.xlim([0,1])\nplt.ylim([0,1])\n#plt.legend(('class 1','class 2'))\nplt.show()\n\n\n# In[102]:\n\n\ndef get_class(x):\n mylist = []\n for i in range(len(fuzzy.V)):\n mylist.append([fuzzy.fuzzy_membership(x,fuzzy.V[i],fuzzy.W[i])])\n result = np.multiply(mylist,fuzzy.U)\n mylist=[]\n for i in range(fuzzy.clasess):\n mylist.append(max(result[:,i]))\n \n #print(mylist)\n #print(mylist.index(max(mylist))+1,max(mylist))\n #print('pattern belongs to class {} with fuzzy membership : {}'.format(mylist.index(max(mylist))+1,max(mylist)))\n return [mylist.index(max(mylist))+1]\n \n\n\n# In[103]:\n\n\ndef score(train,train_labels):\n counter=0\n wronge=0\n for i in range(len(train)):\n if get_class(train[i]) == train_labels[i] :\n counter+=1\n else:\n wronge+=1\n \n print('No of misclassification : {}'.format(wronge))\n return (counter/len(train_labels))*100\n\n\n# In[104]:\n\n\nprint('Accuracy (train) : {} %'.format(score(train,train_labels)))\n\n\n# In[105]:\n\n\nprint('Accuracy (test) : {} %'.format(score(test,test_labels)))\n\n","repo_name":"OmkarThawakar/FuzzyMinMax","sub_path":"GFMM/GFMM.py","file_name":"GFMM.py","file_ext":"py","file_size_in_byte":15897,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"44"} +{"seq_id":"39224615244","text":"#Use a version of Kruskal's algo and Union-Find structure to implement simple k-clustering\nimport random\nfrom datetime import datetime\nfrom unionFind import UnionFind\n\n#note this is an undirected graph\ndef generateGraph(n):\n #this graph will be complete by necessity of k-cluter problem\n #graph is represented as a list of lists where each graph[i] represents a node\n #and each graph[i][j] represents the cost or distance between node i and j\n #clearly the graph will be symmetric and graph[i][i] = 0 (the distance to yourself is 0)\n random.seed(datetime.now())\n graph = [[None]*n for _ in range(n)]\n edgeList = []\n for i in range(0,n):\n graph[i][i] = 0 #distance to yourself is 0\n for j in range(i+1,n):\n currDist = random.randint(1,25)\n graph[i][j] = currDist\n graph[j][i] = currDist\n currEdge = (currDist,i,j) #each edge is a tuple of the form (cost,start,end) note start,end is arbitrary since undirected\n edgeList.append(currEdge)\n return graph, edgeList\n\ndef runKruskal(graph,edgeList,k):\n #runs kruskal to generate a k-clustering\n #aka groups nodes into k components such that maximizes the spacing between components\n unionFind = UnionFind(list(range(0,len(graph[0]))))\n edgeList.sort(key = lambda x:x[0]) #sort edge list by cost\n while (unionFind.numOfComponents > k):\n currEdge = edgeList.pop(0) #smallest available edge\n startComponent = unionFind.findComponent(currEdge[1]) #component of start node\n endComponent = unionFind.findComponent(currEdge[2])\n if (startComponent != endComponent):\n unionFind.union(startComponent,endComponent)\n cluster = unionFind.listComponents()\n return cluster\n\n#plz ignore how ugly this is\ndef findSpacing(graph,cluster):\n minSpacing = 100 #start min spacing higher than highest possible edge weight\n for i in range(0,len(cluster)): #for each cluster\n for j in range(0,len(cluster[i])): #for each point in this cluster\n currPoint = cluster[i][j]\n for k in range(i+1,len(cluster)): #look at each other cluster\n for w in range(0,len(cluster[k])): #for each point in this other cluster\n otherPoint = cluster[k][w]\n if graph[currPoint][otherPoint] < minSpacing:\n minSpacing = graph[currPoint][otherPoint]\n return minSpacing\n\ndef randomCluster(n,k):\n #generates some random cluster of n nodes into k components\n #use this to 'verify' that runKruskal() is optimal\n cluster = [[] for _ in range(k)]\n nodesUsed = []\n for i in range(0,k): #use this just to make sure each cluster gets at least one node\n currNode = random.randint(0,n-1)\n while (currNode in nodesUsed): #make sure we havent already used this node\n currNode = random.randint(0,n-1)\n nodesUsed.append(currNode)\n cluster[i].append(currNode)\n #randomly distribute the remaining nodes\n for i in range(0,n):\n if i not in nodesUsed:\n nodesUsed.append(i)\n currCluster = random.randint(0,k-1)\n cluster[currCluster].append(i)\n return cluster\n\na,b = generateGraph(5)\nprint(a)\nc = runKruskal(a,b,2)\nprint(c)\nprint(findSpacing(a,c))\nd = randomCluster(5,2)\nprint(d)\nprint(findSpacing(a,d))\n","repo_name":"willjrowe/algorithmDesign","sub_path":"kClustering.py","file_name":"kClustering.py","file_ext":"py","file_size_in_byte":3348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"3770431556","text":"from ai_utils.utils.hostinfo import HostInfoClass as HostInfo\nfrom ai_utils.phases.abstract_phase import AbstractPhaseClass\n\nclass NoisyReconPhaseClass(AbstractPhaseClass):\n TrackerId = \"126\"\n Subject = \"Local Network Reconnaissance\"\n Description = \"Local Network Reconnaissance\"\n\n def __init__(self, isPhaseCritical, minimumPortToCheck, maximumPortToCheck, numberOfNeighbors):\n AbstractPhaseClass.__init__(self, isPhaseCritical)\n self.MinimumPortToCheck = minimumPortToCheck\n self.MaximumPortToCheck = maximumPortToCheck\n self.NumberOfNeighbors = numberOfNeighbors\n self.ReconData = {\n 'public_ip' : None,\n 'open_ports' : []\n }\n\n def Setup(self):\n if self.MaximumPortToCheck < self.MinimumPortToCheck:\n self.PhaseReporter.Error('MaximumPortToCheck {0} smaller than MinimumPortToCheck {1}'.format(self.MaximumPortToCheck, self.MinimumPortToCheck))\n return False\n return True\n\n def OnFoundPort(self, result):\n self.PhaseReporter.Info(result)\n self.ReconData['open_ports'].append(result)\n\n def Recon(self):\n self.PhaseReporter.Info(\"Beginning local reconnaissance\")\n publicIp = HostInfo.GetPublicIpAddress()\n if publicIp:\n self.ReconData['public_ip'] = publicIp\n HostInfo.GetOpenLocalPorts(self.MinimumPortToCheck, self.MaximumPortToCheck, self.OnFoundPort)\n HostInfo.GetNeighborOpenPorts(self.NumberOfNeighbors, self.MinimumPortToCheck, self.MaximumPortToCheck, self.OnFoundPort)\n return self.ReconData is not None\n\n def Run(self):\n phaseSuccessful = self.Recon()\n if phaseSuccessful:\n self.PhaseResult['recon_data_retrieved'] = str(self.ReconData)\n self.PhaseReporter.Info('Local network reconnaissance was successful')\n else:\n self.PhaseReporter.Info('Local network reconnaissance failed')\n return phaseSuccessful\n","repo_name":"ryanleh/TEE-Phase-Transform","sub_path":"scenario_creator/bin/ai_utils/phases/network_recon.py","file_name":"network_recon.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"4291885196","text":"from AtomGrid import *\nfrom VDE.VASPMoleculeFeature import VASP_DataExtract\nimport numpy as np\n\n\ndef encode_method_test():\n a = VASP_DataExtract(vasp_dir=\"data\\Pd_CH_s_fcc_stand.cif\")\n c = a.get_output_as_atom3Dspace()\n e = a.get_energy_info()\n\n coord, energy, atom_case = c.generate_data()\n\n a = AtomGrid(coord,atom_case)\n\n\n a.get_grid_border()\n a.make_grid(\n minX=-0.5,\n maxX=7,\n minY=-3,\n maxY=7.5,\n minZ=-0.5,\n maxZ=9.5,\n resolutionX=100,\n resolutionY=100,\n resolutionZ=100\n )\n\n train_index = [1]\n\n en2 = a.grid_encode(train_index)[0]\n en1 = a.grid_encode1(train_index)[0]\n\n # en2 方法比en1快很多很多,同时要比较一下编码结果是否一致\n print(en1)\n print(\"_______________________\")\n print(en2)\n print(en1-en2)\n print(np.sum(en1-en2))\n\n\n\nif __name__ == '__main__':\n encode_method_test()","repo_name":"B-C-WANG/GridAtomNN","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"17733417157","text":"import platform\nfrom typing import Any\n\nfrom mcdreforged.api.types import PluginServerInterface\nfrom mcdreforged.api.utils.serializer import serialize\n\n\ndef is_windows() -> bool:\n return platform.platform().__contains__('Windows')\n\n\ndef is_int_var(obj: Any) -> bool:\n if type(obj) == int:\n return True\n else:\n try:\n int(str(obj))\n except ValueError:\n return False\n return True\n\n\ndef is_dict_var(obj: Any) -> bool:\n if type(obj) == dict:\n return True\n else:\n try:\n return isinstance(eval(str(obj)), dict)\n except SyntaxError:\n return False\n\n\ndef is_list_var(obj: Any) -> bool:\n if type(obj) == list:\n return True\n else:\n try:\n return isinstance(eval(str(obj)), list)\n except SyntaxError:\n return False\n\n\ndef process_arg_server(server: PluginServerInterface) -> PluginServerInterface:\n server.func_is_server_running = server.is_server_running()\n server.func_is_server_startup = server.is_server_startup()\n server.func_is_rcon_running = server.is_rcon_running()\n server.func_get_server_pid = server.get_server_pid()\n server.func_get_server_pid_all = server.get_server_pid_all()\n server.func_get_server_information = str(serialize(server.get_server_information()))\n server.func_get_data_folder = server.get_data_folder()\n server.func_get_plugin_file_path = server.get_plugin_file_path('hooks')\n server.func_get_plugin_list = str(server.get_plugin_list())\n server.func_get_unloaded_plugin_list = str(server.get_unloaded_plugin_list())\n server.func_get_disabled_plugin_list = str(server.get_disabled_plugin_list())\n server.func_get_mcdr_language = server.get_mcdr_language()\n server.func_get_mcdr_config = str(server.get_mcdr_config())\n return server\n","repo_name":"OptiJava/hooks","sub_path":"hooks/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"44"} +{"seq_id":"72017188933","text":"import numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.keras import Model\nfrom tensorflow.keras import Input\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras import layers\n\nfrom numpy import linalg as LA\n# Set data type\nDTYPE='float32'\ntf.keras.backend.set_floatx(DTYPE)\n\ndef vecterize(weights):\n '''\n transfer the weight tensor to a vector\n '''\n\n v=tf.reshape(weights[0],shape=[-1,1])\n for weight in weights[1:]:\n v=tf.concat([v,tf.reshape(weight,shape=[-1,1])],axis=0)\n return v\ndef tranfer_weight(vector,nums=40):\n\n '''\n transfer the vector tensor to the weight tensor,default NN has 3 hiddlen layer with resnet structure.\n '''\n\n res=[0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n \n res[0]=tf.reshape(vector[0:nums*1],[1,nums])\n res[1]=tf.reshape(vector[nums*1:nums*2],[nums])\n\n res[2]=tf.reshape(vector[nums*2:nums*(2+nums)],[nums,nums])\n res[3]=tf.reshape(vector[nums*(2+nums):nums*(3+nums)],[nums])\n\n res[4]=tf.reshape(vector[nums*(3+nums):nums*(2*nums+3)],[nums,nums])\n res[5]=tf.reshape(vector[nums*(2*nums+3):nums*(2*nums+4)],[nums])\n\n res[6]=tf.reshape(vector[nums*(2*nums+4):nums*(3*nums+4)],[nums,nums])\n res[7]=tf.reshape(vector[nums*(3*nums+4):nums*(3*nums+5)],[nums])\n\n res[8]=tf.reshape(vector[nums*(3*nums+5):nums*(4*nums+5)],[nums,nums])\n res[9]=tf.reshape(vector[nums*(4*nums+5):nums*(4*nums+6)],[nums])\n\n res[10]=tf.reshape(vector[nums*(4*nums+6):nums*(5*nums+6)],[nums,nums])\n res[11]=tf.reshape(vector[nums*(5*nums+6):nums*(5*nums+7)],[nums])\n\n res[12]=tf.reshape(vector[nums*(5*nums+7):nums*(5*nums+8)],[nums,1])\n res[13]=tf.reshape(vector[nums*(5*nums+8):],[1])\n return res\n\ndef cus_model(num_neurons_per_layer=40,activation='tanh',Resnet=False):\n # define the layers\n x_in = Input(shape=(1,))\n \n x1=Dense(num_neurons_per_layer,\n activation=tf.keras.activations.get(activation),\n kernel_initializer='glorot_normal')(x_in)\n x1_=Dense(num_neurons_per_layer,\n activation=tf.keras.activations.get(activation),\n kernel_initializer='glorot_normal')(x1)\n x2=Dense(num_neurons_per_layer,\n activation=tf.keras.activations.get(activation),\n kernel_initializer='glorot_normal')(x1_)\n x2_=Dense(num_neurons_per_layer,\n activation=tf.keras.activations.get(activation),\n kernel_initializer='glorot_normal')(x2)\n\n x3_=Dense(num_neurons_per_layer,\n activation=tf.keras.activations.get(activation),\n kernel_initializer='glorot_normal')(x2_)\n \n x3=Dense(num_neurons_per_layer,\n activation=tf.keras.activations.get(activation),\n kernel_initializer='glorot_normal')(x3_)\n if Resnet:\n \tx_add=layers.Add()([x3, x_in])\n \tx_out_=Dense(1)(x_add)\n else:\n \tx_out_=Dense(1)(x3)\n\n \n x_out=(x_in*x_in-1)*(x_in*x_in-1)*x_out_-1\n model=Model(inputs=x_in, outputs=x_out)\n return model\n\n@tf.function\ndef mix_gradient(node,model):\n\n '''\n Bulid a computational graph to calculate the every order derivates for the input\n '''\n with tf.GradientTape(persistent=True) as tape:\n tape.watch(node)\n tape.watch(model.trainable_variables)\n u=model(node)\n u_x=tape.gradient(u,node)\n u_theta=tape.gradient(u,model.trainable_variables)\n u_xtheta=tape.gradient(u_x,model.trainable_variables)\n\n del tape\n return u_x,vecterize(u_theta),vecterize(u_xtheta)\n\ndef gradient_node(node,model,dim=1):\n\t'''after set the weight of model is theta_k, calculate the laplacian u with respect to x'''\n\tif dim==1:\n\t\twith tf.GradientTape(persistent=True) as tape:\n\t\t\ttape.watch(node)\n\t\t\tu=model(node)\n\t\t\tu_x=tape.gradient(u,node)\n\t\tu_xx=tape.gradient(u_x,node)\n\t\tdel tape\n\t\treturn u,u_xx\n\tif dim==2:\n\t\tpass\n\t\t\t\n\n@tf.function\ndef gradient_theta(x,model):\n\n\t''' \n\tu_theta\n\tBuild the graph to calculate the derivatives respect to the weight of NN at different input points.\n\t'''\n\t \n\tu = model(x)\n\tu_theta = tf.gradients(u, model.trainable_variables)\n\treturn vecterize(u_theta)\n\n\ndef calculate_coefs_laplacian(sample_size,model,source_f):\n Coef_matrix=0\n Coef_b=0\n sample=tf.random.uniform([sample_size,1],-1,1)\n u, Laplace_u = gradient_node(sample, model)\n # u=model(sample)\n f=source_f(sample,u)#source function\n\n #calculate the u_theta at different data points and calculate the Monte Carlo integration\n #This step can be accelerated with parallel operations, By map in Python (但是会很吃内存)\n for i in range(sample_size):\n x=sample[i]\n u_theta=gradient_theta(x,model)\n\n Coef_matrix+=2*(tf.matmul(u_theta,tf.transpose(u_theta)))/sample_size\n\n Coef_b+=(Laplace_u[i]+f[i])*u_theta*2/sample_size\n return Coef_matrix,-tf.reshape(Coef_b,[-1,1])\n\n\ndef calculate_coefs(sample_size,model,source_f):\n Coef_matrix=0\n Coef_b=0\n sample=tf.random.uniform([sample_size,1],-1,1)\n # u,Laplace_u=self.gradient_node(sample)\n u=model(sample)\n f=source_f(sample,u)#source function\n\n #calculate the u_theta at different data points and calculate the Monte Carlo integration\n #This step can be accelerated with parallel operations, By map in Python (但是会很吃内存)\n for i in range(sample_size):\n x=sample[i]\n u_x,u_theta,u_xtheta=mix_gradient(x,model)\n\n Coef_matrix+=2*(tf.matmul(u_theta,tf.transpose(u_theta)))/sample_size\n\n Coef_b+=(u_x*u_xtheta+f[i]*u_theta)*2/sample_size\n return Coef_matrix,-tf.reshape(Coef_b,[-1,1])\n\n\ndef move_part_step(Coef_M,Coef_b,lam,para_nums=8321):\n A=Coef_M+lam*tf.linalg.diag(tf.ones(para_nums))\n return tf.matmul(tf.linalg.inv(A),Coef_b)\ndef Solve_regularization_system_tf(Coef_M,Coef_b,lam,para_nums=8321,dt=0.001):\n A=Coef_M+lam*tf.linalg.diag(tf.ones(para_nums))\n return dt*tf.matmul(tf.linalg.inv(A),Coef_b)\ndef Solve_regularization_system(Coef_M,Coef_b,lam,para_nums=8321,dt=0.001):\n A=Coef_M+lam*tf.linalg.diag(tf.ones(para_nums))\n return dt*LA.inv(A)@Coef_b\n\n\n","repo_name":"LinMulikas/Neural-Network-PDE","sub_path":"Archieve/OnsagerVariationPOP.py","file_name":"OnsagerVariationPOP.py","file_ext":"py","file_size_in_byte":6177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"74700989573","text":"# Chapter05-2\n# 파이썬 심화\n\n# 파이썬 클래스 관련 메소드 심화\n# private 속성실습\n# - self.__a : `__` 이용한 private 변수 생성하여 instence 에서 접근불가능하게 만든다.\n# - Getter, Setter 이용하여 메소드를 활용해서 변경가능하게 만든다.\n# - 변수명으로 method 생성하는 것이 관례\n# \t\t - Getter : @property 어노테이션 이용함\n# \t - Setter : @[getter 메소드명].setter / Getter의 메소드명과 동일하게 생성해야함.\n# __slot__ 예제 - 메모리 절감효과\n# 객체슬라이딩, 인덱싱\n# ABC, 상속, 오버라이딩\n\n# 파이썬 클래스 특별 메소드 심화 활용 및 상속\n# Class ABC\n\n# class 선언\nclass VectorP(object):\n\tdef __init__(self, x, y):\n\t\tself.__x = float(x)\n\t\tself.__y = float(y)\n\n\tdef __iter__(self):\n\t\tprint('__init__ call')\n\t\treturn (i for i in (self.__x, self.__y)) # Generator\n\n\t# Getter 역활\n\t@property\n\tdef x(self):\n\t\tprint('Called property X')\n\t\treturn self.__x\n\n\t# Setter 역활 - getter와 이름이 동일해야한다.\n\t@x.setter\n\tdef x(self, v):\n\t\tprint('Called property X Setter')\n\t\tself.__x = v\n\n\t# Getter 역활\n\t@property\n\tdef y(self):\n\t\tprint('Called property Y')\n\t\treturn self.__y\n\n\t# Setter 역활 - getter와 이름이 동일해야한다.\n\t@y.setter\n\tdef y(self, v):\n\t\tprint('Called property Y Setter')\n\t\tif v < 30:\n\t\t\traise ValueError('30 below is not possible')\n\t\tself.__y = float(v)\n\nv = VectorP(20, 40)\n# 객체선언\n\n# '__' = private , 인스턴스를 이용하더라도 접근불가\n# print('EX1-1 -', v.__x, v.__y)\n\n# Getter, Setter\nprint(v.x)\nv.x = 10\nv.y = 40\nprint('EX1-2 -', dir(v), v.__dict__)\nprint('EX1-3 -', v.x, v.y)\n\n# Iter 확인\nfor val in v:\n\tprint('EX1-4 -', val)\n\nprint()\nprint()\n\n# __slot__\n# 파이썬 인터프리터에게 통보\n# 핵심 : 해당 클래스가 가지는 속성을 제한\n# __dict__ 속성 최적화 -> 다수 객체 생성시 -> 메모리 사용 공간 대폭 감소\n# 해당 클래스에 만들어진 인스턴스 속성 관리에 딕셔너리 대신 Set 형태를 사용\n# 반드시 문자열로 입력해야 한다.\n# 참조설명 - https://planbs.tistory.com/entry/Python-slots\n# 알려진(known) 속성들로 구성된 클래스들의 경우 이러한 구조는 딕셔너리가 낭비하는 RAM 때문에 병목이 발생할 수 있습니다.\n# 클래스 레벨에 __slots__라는 변수를 설정해서, 해당 클래스에 의해 만들어진 객체의 인스턴스 속성 관리에 딕셔너리 대신\n# 속성에 대한 고정된(fixed) set을 사용하도록 할 수 있습니다.\n\nclass TestA(object):\n\t__slots__ = ('a',)\n\nclass TestB:\n\tpass\n\nuse_slot = TestA()\nno_slot = TestB()\n\nprint('EX2-1 -', use_slot)\n# print('EX2-2 -', use_slot.__dict__) # error\nprint('EX2-3 -', no_slot)\nprint('EX2-4 -', no_slot.__dict__)\n\n# 메모리 사용량 비교\nimport timeit\n\n# 측정을 위한 함수 선언\ndef repeat_outer(obj):\n\tdef repeat_inner():\n\t\tobj.a = 'TEST'\n\t\tdel obj.a\n\n\treturn repeat_inner\n\nprint(min(timeit.repeat(repeat_outer(use_slot), number=10000)))\nprint(min(timeit.repeat(repeat_outer(no_slot), number=10000)))\n\nprint()\nprint()\n\n# 객체 슬라이싱\nclass Objects:\n\tdef __init__(self):\n\t\tself._numbers = [n for n in range(1, 100, 3)]\n\n\tdef __len__(self):\n\t\treturn len(self._numbers)\n\n\tdef __getitem__(self, idx):\n\t\treturn self._numbers[idx]\n\ns = Objects()\n\nprint('EX3-1 -', s.__dict__)\nprint('EX3-2 -', len(s))\nprint('EX3-3 -', len(s._numbers))\nprint('EX3-4 -', s[1:100])\nprint('EX3-5 -', s[-1])\n# 시퀀스객체[::증가폭]\nprint('EX3-5 -', s[::10])\n# 시퀀스객체[시작인덱스::증가폭]\nprint('EX3-6 -', s[::5])\n\n# 파이썬 추상클래스\n# 참고 : https://docs.python.org/3/library/collections.abc.html\n\n# 추상클래스 사용이유\n# 자체적으로 객체 생성 불가\n# 상속을 통해서 자식 클래스에서 인스턴스를 생성해야함\n# 개발과 관련된 공통된 내용(필드, 메소드)을 추출 및 통합해서 공통된 내용으로 작성하게 하는 것\n\n# Sequence 상속 받지 않았지만, 자동으로 __iter__, __contailn__ 기능 작동\n# 객체 전체를 자동으로조사 -> 시퀀스 프로토콜\n\nclass IterTestA:\n\tdef __getitem__(self, item):\n\t\tprint(repr(item))\n\t\treturn range(1, 50, 2)[item] # range(1, 50, 2)\n\ni1 = IterTestA()\nprint('EX4-1 -', i1[4])\nprint('EX4-2 -', i1[4:10])\nprint('EX4-3 -', 3 in i1[1:10])\n# print('EX4-4 -', [i for i in i1]) # 이해가 안됨\n# print('EX4-4 -', [i for i in i1[:]])\n\nprint()\nprint()\n\n# Sequence 상속\n# 요구사항인 추상메소드를 모두 구현해야 동작\n\nfrom collections.abc import Sequence\n\nclass IterTestB(Sequence):\n\tdef __getitem__(self, item):\n\t\tprint('__getitem__', repr(item))\n\t\treturn range(1, 50, 2)[item] # range(1, 50, 2)\n\n\tdef __len__(self, idx):\n\t\tprint('__len__', repr(idx))\n\t\treturn len(range(1, 50, 2)[idx])\n\ni2 = IterTestB()\nprint('EX4-5 -', i2[4])\nprint('EX4-6 -', i2[4:10])\nprint('EX4-7 -', 3 in i2[1:10])\nprint()\nprint()\n# abc 활용예제 - abstract class\nimport abc\n\nclass RandomMachine(abc.ABC): # metaclass=abc.ABCMeta(3.4이하)\n\t# __metaclass__ = abc.ABCMeta\n\n\t# 추상메소드\n\t@abc.abstractmethod\n\tdef load(self, iterobj):\n\t\t\"\"\"Iterable 항목추가\"\"\"\n\n\t# 추상메소드\n\t@abc.abstractmethod\n\tdef pick(self):\n\t\t\"\"\"무작위 항목 뽑기\"\"\"\n\n\tdef inspect(self):\n\t\titems = []\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\titems.append(self.pick())\n\t\t\texcept LookupError:\n\t\t\t\tbreak\n\t\t\treturn tuple(sorted(items))\n\nimport random\n\nclass CraneMachine(RandomMachine):\n\tdef __init__(self, items):\n\t\tself._readomizer = random.SystemRandom()\n\t\tself._items = []\n\t\tself.load(items)\n\n\tdef load(self, iterobj):\n\t\tself._items.extend(iterobj)\n\t\tself._readomizer.shuffle(self._items)\n\n\tdef pick(self):\n\t\ttry:\n\t\t\treturn self._items.pop()\n\t\texcept IndexError: # item이 더이상 없을때 에러발생함.\n\t\t\t\traise LookupError('Empty Crane Box')\n\n\tdef __call__(self):\n\t\treturn self.pick()\n\n# 서브클래스 확인 - issubclass(자식, 부모)\nprint('EX5-1 -', issubclass(RandomMachine, CraneMachine))\nprint('EX5-2 -', issubclass(CraneMachine, RandomMachine))\n\n# 상속 구조 확인\nprint('EX5-3 -', CraneMachine.__mro__)\ncm = CraneMachine(range(1, 100)) # 추상메소드 구현 안하면 에러\n\nprint('EX5-4 -', cm._items)\nprint('EX5-5 -', cm.pick())\nprint('EX5-6 -', cm())\nprint('EX5-7 -', cm.inspect())\n\n","repo_name":"sseonmo/python_basic","sub_path":"ADVANCED/chapter05_02.py","file_name":"chapter05_02.py","file_ext":"py","file_size_in_byte":6375,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"37344550035","text":"from selenium import webdriver\r\nfrom selenium.webdriver import ActionChains\r\nimport time\r\n\r\nbrowser = webdriver.Chrome(executable_path=\"C:\\\\Users\\\\Manish\\\\Downloads\\\\Pendrive Data\\\\Python Files\\\\drivers\\\\chromedriver.exe\")\r\nbrowser.get(\"http://www.dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-3.html\")\r\n\r\ndragElement = browser.find_element(\"xpath\",\"/html/body/div[2]/div[2]/div/div[12]\")\r\ndropElement = browser.find_element(\"xpath\",\"/html/body/div[2]/div[3]/div[1]\")\r\n\r\nactions = ActionChains(browser)\r\nactions.drag_and_drop(dragElement,dropElement).perform()\r\n\r\ntime.sleep(5)\r\nbrowser.quit()\r\n","repo_name":"lf7854/Selenium-Practice","sub_path":"mouseDragandDrop.py","file_name":"mouseDragandDrop.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"7758480209","text":"import os\n\n\nfrom celery import Celery\nfrom celery.schedules import crontab\n\n# Set the default Django settings module for the 'celery' program.\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"mindx.settings\")\napp = Celery(\"mindx\")\n\n# Using a string here means the worker doesn't have to serialize\n# the configuration object to child processes.\n# - namespace='CELERY' means all celery-related configuration keys\n# should have a `CELERY_` prefix.\napp.config_from_object(\"django.conf:settings\", namespace=\"CELERY\")\n\n# Load task modules from all registered Django apps.\napp.autodiscover_tasks()\n\n# create scheduler task with crontab every minute to send report to admin\n# create crontab run every beginning of monday and wednesday\napp.conf.beat_schedule = {\n \"send-report-every-monday-and-wednesday\": {\n \"task\": \"unity.tasks.report_scheduler\",\n \"schedule\": crontab(minute=0, hour=0, day_of_week=\"mon,wed\"),\n },\n}\n","repo_name":"aldoritma/konigle-technical-test","sub_path":"mindx/mindx/celery.py","file_name":"celery.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"34743890401","text":"# -- coding:UTF-8 --\nfrom app import app,db\nfrom app.models import SingleChoice,MultipleChoice,EssayQuestion,Template,Answer\nfrom app.models import User,Task,Receiver,receivers\nimport pdb\n\nuser1 = User(id =16340045, username = 'xiaotong', email = 'xiaotong@qq.com')\nuser1.set_password('xiaozhu')\n\nuser2 = User(id = 16340046, username = 'xiaohang', email = 'xiaohang@qq.com')\nuser2.set_password('xiaozhu2')\n\nsingechoice1 = SingleChoice(question = '单选题问题1',options = ['选项1', '选项2'])\nsingechoice2 = SingleChoice(question = '单选题问题2',options = ['选项1', '选项2','选项3'])\n\nmultiplechoice1 = MultipleChoice(question = '多选题问题1',options = ['选项1','选项2'])\nmultiplechoice2 = MultipleChoice(question = '多选题问题2',options = ['选项1','选项2','选项3'])\n\nessayquestion1 = EssayQuestion(question = '问答题题目1')\nessayquestion2 = EssayQuestion(question = '问答题题目2')\n\ntemplate1 = Template(\\\n\tsingle_choices = [singechoice1,singechoice2],\\\n\tmultiple_choices = [multiplechoice1],\\\n\tessay_questions = [])\ntemplate2 = Template(\\\n\tsingle_choices = [],\\\n\tmultiple_choices = [multiplechoice2],\\\n\tessay_questions = [essayquestion1,essayquestion2])\n\n\ntask1 = Task(\n\tid = 1,\n\ttitle = 'task1',\n\tsponsor = user1\n\t)\ntask2 = Task(\n\tid = 2,\n\ttitle = 'task2',\n\tsponsor = user2,\n\ttemplate = template1\n\t)\n\n\nreceiver1 = Receiver(uid=user1.id, tid=task1.id, finished = True)\nreceiver2 = Receiver(uid=user2.id, tid=task2.id, finished = True,paid = True)\n\ndb.session.add_all([user1,user2,task1,task2,receiver1,receiver2,template1,template2])\ndb.session.commit()\n\nanswer1 = Answer(\\\n\treceiver_id = receiver1.id,\\\n\tanswers = ['01', '100', '11'])\nanswer2 = Answer(\\\n\treceiver_id = receiver2.id,\\\n\tanswers = ['101', '问答题1回答', '问答题2回答'])\n\ntask2.answers = [answer1,answer2]\n\ndb.session.add_all([answer1,answer2])\ndb.session.commit()\n\npdb.set_trace()\n","repo_name":"sysucodingfarmers/MakeMoney","sub_path":"server/initSql.py","file_name":"initSql.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"15485230743","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun May 12 20:40:26 2019\n\n@author: AlMaMi\n\"\"\"\n\nimport sys\nimport pickle\nfrom PyQt5.QtWidgets import (QApplication, QMainWindow, QComboBox, QWidget,\n QLineEdit, QFileDialog, QGridLayout, QHBoxLayout,\n QVBoxLayout, QLabel, QAction, QDesktopWidget, \n QActionGroup, QMenu, QListWidget, QAbstractItemView)\n\nfrom hplc_import_window import hplc_import_window\nfrom hplc_calibration_window import hplc_calibration_window\nfrom hplc_visualization_window import hplc_visualization_window\nfrom pyHPLC.hplc_prediction import hplc_prediction\n\n\nclass main_window(QMainWindow):\n\n def __init__(self):\n super().__init__()\n self.init_window()\n self.define_widgets()\n self.position_widgets()\n self.connect_event_handlers()\n\n self.hplc_datasets = {}\n self.hplc_file_names = {}\n self.hplc_calibrations = {}\n\n def init_window(self):\n self.setGeometry(500, 500, 1200, 100) # xPos,yPos,width, heigth\n self.center() # center function is defined below\n self.setWindowTitle('HPLC data analysis')\n\n self.statusBar().showMessage('Welcome')\n menubar = self.menuBar()\n file_menu = menubar.addMenu('&File')\n visualize_menu = menubar.addMenu('&Visualize')\n preprocess_menu = menubar.addMenu('&Preprocessing')\n calibration_menu = menubar.addMenu('&Calibration')\n analysis_menu = menubar.addMenu('&Analyze data')\n\n import_filter_menu = QMenu('Dataset import filter', self)\n self.import_filter_group = QActionGroup(import_filter_menu)\n # Any entry in the following list generates a new entry in import\n # filter submenu\n self.import_filters = ['3D ASCII data', 'Pickled hplc_data object']\n for import_filter in self.import_filters:\n import_action = QAction(import_filter, import_filter_menu,\n checkable=True,\n checked=import_filter==self.import_filters[0])\n import_filter_menu.addAction(import_action)\n self.import_filter_group.addAction(import_action)\n self.import_filter_group.setExclusive(True)\n file_menu.addMenu(import_filter_menu)\n\n import_dataset_action = QAction('Import dataset', self)\n import_dataset_action.setShortcut('Ctrl+I')\n import_dataset_action.setStatusTip('Import dataset')\n import_dataset_action.triggered.connect(self.open_import_window)\n\n open_dataset_action = QAction('Open dataset from file', self)\n open_dataset_action.setShortcut('Ctrl+O')\n open_dataset_action.setStatusTip('Open dataset from file')\n open_dataset_action.triggered.connect(self.open_dataset)\n\n save_dataset_action = QAction('Save dataset to file', self)\n save_dataset_action.setShortcut('Ctrl+S')\n save_dataset_action.setStatusTip('Save dataset to file')\n save_dataset_action.triggered.connect(self.save_dataset)\n\n open_calibration_action = QAction('Open calibration from file', self)\n open_calibration_action.setStatusTip('Open calibration from file')\n open_calibration_action.triggered.connect(self.open_calibration)\n\n save_calibration_action = QAction('Save calibration to file', self)\n save_calibration_action.setStatusTip('Save calibration to file')\n save_calibration_action.triggered.connect(self.save_calibration)\n\n file_menu.addMenu(import_filter_menu)\n file_menu.addAction(import_dataset_action)\n file_menu.addAction(open_dataset_action)\n file_menu.addAction(save_dataset_action)\n file_menu.addAction(open_calibration_action)\n file_menu.addAction(save_calibration_action)\n\n elugram_viewer_action = QAction('2D elugram viewer', self)\n elugram_viewer_action.triggered.connect(self.open_elugram_window)\n\n spectrum_viewer_action = QAction('2D spectrum viewer', self)\n spectrum_viewer_action.triggered.connect(self.open_spectrum_window)\n\n visualize_menu.addAction(elugram_viewer_action)\n visualize_menu.addAction(spectrum_viewer_action)\n\n calibration_viewer_action = QAction('Calibration wizard', self)\n calibration_viewer_action.triggered.connect(\n self.open_calibration_window)\n\n calibration_menu.addAction(calibration_viewer_action)\n\n simple_cls_action = QAction('Simple cls analysis', self)\n simple_cls_action.triggered.connect(\n self.analyze_dataset)\n \n analysis_menu.addAction(simple_cls_action)\n\n self.container0 = QWidget(self)\n self.setCentralWidget(self.container0)\n\n self.grid_container = QGridLayout()\n self.container0.setLayout(self.grid_container)\n\n def define_widgets(self):\n # Interesting preprocessing options: Baseline correction, normalize\n # with internal standard. Should both be integrated into hplc_data.\n self.dataset_selection_label = QLabel('Active dataset')\n self.dataset_selection_combo = QComboBox()\n\n self.calibration_selection_label = QLabel('Active calibration')\n self.calibration_selection_list = QListWidget()\n self.calibration_selection_list.setSelectionMode(QAbstractItemView.ExtendedSelection)\n\n def position_widgets(self):\n self.dataset_selection_layout = QVBoxLayout()\n self.dataset_selection_layout.addWidget(self.dataset_selection_label)\n self.dataset_selection_layout.addWidget(self.dataset_selection_combo)\n self.dataset_selection_layout.addStretch(1)\n\n self.calibration_selection_layout = QVBoxLayout()\n self.calibration_selection_layout.addWidget(\n self.calibration_selection_label)\n self.calibration_selection_layout.addWidget(\n self.calibration_selection_list)\n\n self.hplc_data_selection_layout = QHBoxLayout()\n self.hplc_data_selection_layout.addLayout(\n self.dataset_selection_layout)\n self.hplc_data_selection_layout.addLayout(\n self.calibration_selection_layout)\n self.hplc_data_selection_layout.addStretch(1)\n\n self.grid_container.addLayout(\n self.hplc_data_selection_layout, 0, 1, 1, 1)\n\n # self.grid_container.addWidget(self.import_options_label, *(1, 1), 1, 1)\n # self.spectra_plot_limits_layout.addStretch(1)\n\n def connect_event_handlers(self):\n self.dataset_selection_combo.currentIndexChanged.connect(\n self.update_windows)\n self.calibration_selection_list.itemClicked.connect(self.set_active_calibrations)\n\n def open_calibration_window(self):\n self.hplc_calibration_window = hplc_calibration_window(self)\n self.hplc_calibration_window.show()\n\n def open_elugram_window(self):\n self.hplc_elugram_window = hplc_visualization_window(self, mode='elugram')\n self.hplc_elugram_window.show()\n\n def open_spectrum_window(self):\n self.hplc_spectrum_window = hplc_visualization_window(self, mode='spectrum')\n self.hplc_spectrum_window.show()\n\n def open_import_window(self):\n self.hplc_import_window = hplc_import_window(self)\n self.hplc_import_window.show()\n\n def analyze_dataset(self):\n # Analysis is currently performed on one elugram region only.\n # hplc_prediction can process multiple regions simultaneously, so that\n # still needs to be used here.\n curr_dataset = self.hplc_datasets[self.dataset_selection_combo.currentText()]\n curr_calibrations = []\n for calib in self.active_calibrations:\n curr_calibrations.append(self.hplc_calibrations[calib])\n # curr_calibration = self.hplc_calibrations[self.calibration_selection_combo.currentText()]\n\n predicted_concentrations = hplc_prediction(\n curr_dataset, [curr_calibrations])\n\n print('Simple CLS:', predicted_concentrations.simple_prediction(mode='cls'))\n print('Simple PCR:', predicted_concentrations.simple_prediction(mode='pcr'))\n print('Advanced:', predicted_concentrations.advanced_prediction())\n\n def update_windows(self):\n try:\n self.hplc_elugram_window.set_active_dataset()\n except:\n pass\n try:\n self.hplc_calibration_window.set_active_dataset()\n except:\n pass\n\n def open_dataset(self):\n file_type = 'HPLC dataset file (*.hplc)'\n file_name, _ = QFileDialog.getOpenFileName(\n self, 'Open HPLC dataset file', filter=file_type)\n dataset_name = file_name.split('/')[-1]\n\n if file_name != '':\n with open(file_name, 'rb') as filehandle:\n self.hplc_datasets[dataset_name] = pickle.load(filehandle)\n\n datasets_import_paths = []\n for curr_dataset in self.hplc_datasets[dataset_name]:\n datasets_import_paths.append(curr_dataset.import_path)\n self.hplc_file_names[dataset_name] = datasets_import_paths\n\n dataset_names = [\n self.dataset_selection_combo.itemText(i)\n for i in range(self.dataset_selection_combo.count())]\n\n if dataset_name not in dataset_names:\n self.dataset_selection_combo.addItem(dataset_name)\n\n def save_dataset(self):\n curr_dataset = self.dataset_selection_combo.currentText()\n\n file_type = 'HPLC dataset file (*.hplc)'\n file_name, _ = QFileDialog.getSaveFileName(\n self, 'Save active HPLC dataset file', curr_dataset + '.hplc',\n filter=file_type)\n\n if file_name != '':\n with open(file_name, 'wb') as filehandle:\n pickle.dump(self.hplc_datasets[curr_dataset], filehandle)\n\n def open_calibration(self):\n file_type = 'HPLC calibration file (*.calib)'\n file_name, _ = QFileDialog.getOpenFileName(\n self, 'Open HPLC calibration file', filter=file_type)\n calibration_name = file_name.split('/')[-1]\n\n if file_name != '':\n if calibration_name not in self.hplc_calibrations.keys():\n self.calibration_selection_list.addItem(calibration_name)\n\n with open(file_name, 'rb') as filehandle:\n self.hplc_calibrations[calibration_name] = pickle.load(\n filehandle)\n\n # calibration_names = [\n # self.calibration_selection_combo.itemText(i)\n # for i in range(self.calibration_selection_combo.count())]\n\n # if calibration_name not in calibration_names:\n # self.calibration_selection_combo.addItem(calibration_name)\n\n # # the rest is for the QListWidget, currently experimental\n # calibration_names_1 = []\n # counter = 0\n # finished = False\n # while finished == False:\n # curr_item = self.calibration_selection_list.item(counter)\n # if curr_item is None:\n # finished = True\n # else:\n # calibration_names_1.append(curr_item.text())\n # counter += 1\n\n def save_calibration(self):\n # curr_calibration = self.calibration_selection_combo.currentText()\n\n for curr_calibration in self.active_calibrations:\n file_type = 'HPLC calibration file (*.calib)'\n file_name, _ = QFileDialog.getSaveFileName(\n self, 'Save active HPLC calibration file',\n curr_calibration + '.calib', filter=file_type)\n\n if file_name != '':\n with open(file_name, 'wb') as filehandle:\n pickle.dump(\n self.hplc_calibrations[curr_calibration], filehandle)\n\n def center(self): # centers object on screen\n qr = self.frameGeometry()\n cp = QDesktopWidget().availableGeometry().center()\n qr.moveCenter(cp)\n self.move(qr.topLeft())\n\n def set_active_calibrations(self):\n selected = self.calibration_selection_list.selectedItems()\n self.active_calibrations = []\n for curr_item in selected:\n self.active_calibrations.append(curr_item.text())\n\napp = QApplication(sys.argv)\n \nwindow = main_window()\n\nwindow.show()\n#app.exec_()\nsys.exit(app.exec_())\n \n\n\n","repo_name":"AlexanderSouthan/pyHPLC","sub_path":"src/pyHPLC/gui_hplc/hplc_main_window.py","file_name":"hplc_main_window.py","file_ext":"py","file_size_in_byte":12383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"23316961475","text":"import json\nimport shutil\n\nfrom IPython.core.display import display, HTML\n\ndef configure(n):\n config = {\n 'version' : 'ev3',\n 'number' : n\n }\n with open('../task/robot_config.json', 'w') as f:\n json.dump(config, f)\n shutil.copyfile('./functions.py', '../task/functions.py')\n print(\"\\x1b[32mConfiguració completa.\\x1b[0m\")\n\n display(HTML('

Ara ja podeu continuar, començant la primera tasca de programació: provareu el robot a vore si respon i es mou correctament.

>>> Prova de connexió

'))\n\ndef next_notebook(nb):\n if nb=='moviments':\n display(HTML('

Ja podeu passar a la pàgina següent, on aprendreu a controlar els moviments del robot:

>>> Moviments del robot

'))\n elif nb=='quadrat':\n display(HTML('

Ara ja podeu continuar, bona sort!

>>> Exercici de moviment

'))\n elif nb=='sensors':\n display(HTML('

Fins ara heu aprés a controlar el moviment del robot, i també a programar bucles, no està gens malament!

Per a continuar, anem a vore els altres components del robot, els sensors, que ens permetran fer programes encara més sofisticats.

>>> Sensors

'))\n elif nb=='touch':\n display(HTML('

Ara ja podeu passar al primer exercici amb sensors:

>>> Tacte

'))\n elif nb=='navigation':\n display(HTML('

Ara ja podeu continuar.

>>> Exercici de navegació

'))\n elif nb=='sound':\n display(HTML('

Ara ja podeu continuar.

>>> Sensor de so

'))\n elif nb=='light':\n display(HTML('

Ara ja podeu continuar.

>>> Sensor de llum

'))\n elif nb=='ultrasonic':\n display(HTML('

Ara ja podeu continuar.

>>> Sensor ultrasònic

'))\n elif nb=='sumo':\n display(HTML('

Ara ja podeu continuar.

>>> El Gran Repte

'))\n else:\n pass\n\nimport ev3_dc as ev3\n\ndef connect():\n global brick\n global address\n global mB; global mC\n global ts; global gy; global us; global cl; global so\n global snd\n global tempo\n global connected_robot\n with open('robot_config.json', 'r') as f:\n config = json.load(f)\n n = config['number']\n try:\n address = {1: '00:16:53:51:07:8F',\\\n\t\t 2: '00:16:53:53:F1:8D',\\\n\t\t 3: '',\\\n\t\t 4: '00:16:53:51:5F:3C',\\\n\t\t 5: '00:16:53:53:83:0C'}\n brick = ev3.EV3(protocol=ev3.BLUETOOTH, host=address[n])\n mB = ev3.Motor(ev3.PORT_B, ev3_obj=brick)\n mC = ev3.Motor(ev3.PORT_C, ev3_obj=brick)\n ts = ev3.Touch(ev3.PORT_1, ev3_obj=brick)\n #so = ev3.SoundSensor('in2')\n #so.mode='DB'\n us = ev3.Ultrasonic(ev3.PORT_4, ev3_obj=brick)\n cl = ev3.Color(ev3.PORT_3, ev3_obj=brick)\n snd = ev3.Sound(ev3_obj=brick)\n tempo = 0.25\n connected_robot = n\n print(\"\\x1b[32mRobot %d connectat.\\x1b[0m\" % n)\n except KeyError:\n print(\"\\x1b[31mNúmero de robot incorrecte.\\x1b[0m\")\n except ev3.exceptions.NoEV3:\n print(\"\\x1b[31mNo es pot connectar amb el robot.\\x1b[0m\")\n except OSError:\n print(\"\\x1b[33mError de connexió. Intenta-ho de nou, si segueix sense funcionar avisa el professor.\\x1b[0m\")\n\ndef disconnect():\n try:\n brick.__del__()\n print(\"\\x1b[32mRobot %d desconnectat.\\x1b[0m\" % connected_robot)\n except NameError:\n print(\"\\x1b[31mNo hi ha connexió amb el robot.\\x1b[0m\")\n\ndef stop():\n try:\n mB.stop()\n mC.stop()\n except (NameError, EOFError, OSError):\n print(\"\\x1b[31mNo hi ha connexió amb el robot.\\x1b[0m\")\n\ndef forward(speed=100,speed_B=100,speed_C=100):\n move(speed_B=min(abs(speed),abs(speed_B)),speed_C=min(abs(speed),abs(speed_C)))\n \ndef backward(speed=100,speed_B=100,speed_C=100):\n move(speed_B=-min(abs(speed),abs(speed_B)),speed_C=-min(abs(speed),abs(speed_C)))\n \ndef left(speed=100):\n move(speed_B=0,speed_C=abs(speed))\n\ndef right(speed=100):\n move(speed_B=abs(speed),speed_C=0)\n \ndef left_sharp(speed=100):\n move(speed_B=-abs(speed),speed_C=abs(speed))\n \ndef right_sharp(speed=100):\n move(speed_B=abs(speed),speed_C=-abs(speed))\n\nimport math\n\ndef move(speed_B=0,speed_C=0):\n max_speed = 100\n direction_B = int(math.copysign(1, speed_B))\n speed_B = int(abs(speed_B))\n direction_C = int(math.copysign(1, speed_C))\n speed_C = int(abs(speed_C))\n if speed_B > 100:\n speed_B = 100\n print(\"\\x1b[33mLa velocitat màxima és 100.\\x1b[0m\")\n if speed_C > 100:\n speed_C = 100\n print(\"\\x1b[33mLa velocitat màxima és 100.\\x1b[0m\")\n try:\n speed_B = int(speed_B*max_speed/100)\n speed_C = int(speed_C*max_speed/100)\n if speed_B > 0:\n mB.speed=speed_B\n if speed_C > 0:\n mC.speed=speed_C\n if speed_B > 0:\n mB.start_move(direction=direction_B)\n if speed_C > 0:\n mC.start_move(direction=direction_C)\n except (NameError, EOFError, OSError):\n print(\"\\x1b[31mNo hi ha connexió amb el robot.\\x1b[0m\")\n \ndef touch():\n return ts.touched\n\n#def gyro():\n# return gy.value()\n\ndef sound():\n return 0\n\ndef ultrasonic():\n try:\n return us.distance / 10\n except TypeError:\n return 2.55\n\ndef light():\n return cl.reflected\n\n#def beep():\n# snd.beep()\n \ndef play_tone(f,t):\n snd.tone(f,int(t*tempo))\n \n#def speak(s):\n# snd.speak(s).wait()\n \nfrom IPython.display import clear_output\n\ndef read_and_print(sensor):\n try:\n while True:\n clear_output(wait=True)\n print(sensor())\n except KeyboardInterrupt:\n pass\n \ndef test_sensors():\n try:\n while True:\n clear_output(wait=True)\n print(\" Touch: %d\\n Light: %d\\n Sound: %d\\nUltrasonic: %.2f\" % (touch(),light(),sound(), ultrasonic()))\n except KeyboardInterrupt:\n pass\n \nimport matplotlib.pyplot as plt\n\ndef plot(l):\n plt.plot(l)\n","repo_name":"RobInLabUJI/MindstormsColab","sub_path":"ev3colab/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":6484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"40585160928","text":"import sys\nimport argparse\nimport json\nimport logging\nimport re\n\nimport binlink\nimport common\nimport morestd\nimport tools\n\n\nlast_line_re = re.compile(\n r\"(?P.*?)\"\n r\"\\s+\"\n r\"(?P.*?)\"\n r\"\\s+\"\n r\"(?P.*?)\"\n r\"\\s+\"\n r\"(?P.*?)( | - )\"\n r\"(?P.*?)\\s*($|\\()\"\n r\"(?P.*?)(\\)|$)\"\n r\".*\"\n)\n\n\ndef gather():\n last = morestd.shell.cmd(\"/usr/bin/last -F -w\")\n\n results = []\n for line in last['stdout'].splitlines():\n match = last_line_re.match(line)\n if match:\n results.append(match.groupdict())\n return results\n\n\n@binlink.register(\"sec-gather-unixsessions\")\ndef cmdline(version):\n parser = argparse.ArgumentParser(description='Output unix login sessions')\n common.arg_add_defaults(parser, version=version, annotate=True)\n args = parser.parse_args()\n common.configure_logger(args.debug)\n\n results = gather()\n sys.stdout.write(json.dumps({\"unixsessions\": results}, indent=4))\n","repo_name":"fboender/sec-tools","sub_path":"src/bins/gather_unixsessions.py","file_name":"gather_unixsessions.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"44"} +{"seq_id":"14556021353","text":"import re\nimport csv\nimport numpy as np\nimport pandas as pd\nimport requests as rq\nfrom bs4 import BeautifulSoup\n\nlivros_para_comprar = []\n\nlinks = pd.read_csv('links_estante.csv')\n\nfor index, rows in links.iterrows():\n\n dic_livro = {}\n\n url = 'https://www.estantevirtual.com.br{}'.format(links['link'][index])\n print(url)\n response = rq.get(url)\n html = BeautifulSoup(response.text, 'html.parser')\n\n article = html.find('article', {'class': 'livro-exemplar'})\n #print(article)\n dic_livro['Nome do Livro'] = article.find('h1', {'class': 'livro-titulo'}).get_text().strip()\n dic_livro['Autor'] = article.find('h2', {'class': 'livro-autor'}).get_text().strip()\n #print(dic_livro)\n\n div_preço = html.find('div', {'class': 'info-livro-vendedor-aside'})\n #print(div_preço)\n dic_livro['Valor'] = div_preço.find('strong', {'class': 'livro-preco-valor'}).get_text().strip()\n dic_livro['Frete'] = div_preço.find('span', {'class': 'livro-preco-frete'}).get_text().strip().strip('+').strip('envio*').strip()\n #print(dic_livro)\n\n section = html.find('section', {'class': 'livro__info m-info'})\n #print(section)\n dic_livro['Condição'] = section.find_all('p')[0].get_text().strip('Tipo:').strip().strip().strip()\n dic_livro['Editora'] = section.find('p', {'class': 'livro-specs info-publisher'}).get_text().strip().strip('Editora:').strip()\n dic_livro['Ano de Publicação'] = section.find('p', {'class': 'livro-specs info-year'}).get_text().strip().strip('Ano:').strip()\n dic_livro['ISBN'] = section.find_all('p')[5].get_text().strip().strip('ISBN:').strip()\n dic_livro['Idioma'] = section.find('p', {'class': 'livro-specs info-language'}).get_text().strip().strip('Idioma:').strip()\n #dic_livro['Descrição da condição'] = section.find('span', {'itemprop': 'description'}).get_text().strip()\n #print(dic_livro)\n\n aside = html.find('aside', {'class': 'sobre-o-livreiro'})\n #print(aside)\n dic_livro['Loja'] = [a['href'] for a in html.select('a[href]')][100:101]\n dic_livro['Reviews da Loja'] = aside.find('div', {'class': 'seller-review-box'}).get_text().strip().strip()\n #print(dic_livro)\n livros_para_comprar.append(dic_livro)\n\n #print(livros_para_comprar)\n\nlivros = pd.DataFrame(livros_para_comprar)\n\nlivros.to_csv('livros_para_estante.csv', index=False)\n\nprint(livros)\n\nfor livro in livros_para_comprar:\n print(livros)","repo_name":"pedrofnsc1/estante_virtual","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"14205648939","text":"# from itertools import permutations\n# n, m = map(int, input().split())\n# nums = []\n# for i in range(1, n+1):\n# for _ in range(m):\n# nums.append(i)\n# for nums in sorted(list(set(permutations(nums, m)))):\n# print(*nums)\n\ndef dfs():\n if len(ans) == M:\n print(' '.join(map(str, ans)))\n return\n \n for i in range(1,N+1):\n ans.append(i)\n dfs()\n ans.pop()\n\nif __name__ == '__main__':\n N, M = map(int, input().split())\n ans = []\n dfs()","repo_name":"ChoHyoungSeo/Algorithm_prac","sub_path":"python/boj/15651.py","file_name":"15651.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"17453240209","text":"# This Source Code Form is subject to the terms of the GNU\n# General Public License, v.3.0. If a copy of the GPL was not distributed with this\n# file, You can obtain one at https://www.gnu.org/licenses/gpl-3.0.en.html\n# For The-TG-Bot-3.0\n\nimport aria2p\nimport asyncio\nimport json\nimport math\nimport os\nimport time\nimport subprocess\nimport httplib2\nfrom datetime import datetime\nfrom mimetypes import guess_type\nfrom apiclient.discovery import build\nfrom apiclient.http import MediaFileUpload\nfrom apiclient.errors import ResumableUploadError\nfrom hachoir.metadata import extractMetadata\nfrom hachoir.parser import createParser\nfrom telethon.tl.types import DocumentAttributeVideo, DocumentAttributeAudio\n\n\n\ncmd = \"aria2c --enable-rpc --rpc-listen-all=false --rpc-listen-port 6800 --max-connection-per-server=10 --rpc-max-request-size=1024M --seed-time=0.01 --min-split-size=10M --follow-torrent=mem --split=10 --daemon=true\"\naria2_is_running = os.system(cmd)\naria2 = aria2p.API(aria2p.Client(\n host=\"http://localhost\", port=6800, secret=\"\"))\nEDIT_SLEEP_TIME_OUT = 10\nthumb_image_path = ENV.DOWNLOAD_DIRECTORY + \"/thumb_image.jpg\"\nREDIRECT_URI = \"urn:ietf:wg:oauth:2.0:oob\"\nG_DRIVE_F_PARENT_ID = None\nG_DRIVE_DIR_MIME_TYPE = \"application/vnd.google-apps.folder\"\n\n\n@client.on(events(pattern=\"leech ?(.*)\"))\nasync def magnet_download(event):\n if event.fwd_from:\n return\n var = event.pattern_match.group(1)\n if not var:\n rep = event.get_reply_message()\n var = rep.text\n # print(var)\n uris = [var]\n # Add URL Into Queue\n try:\n download = aria2.add_uris(uris, options=None, position=None)\n except Exception as e:\n await log(str(e))\n return await event.delete()\n\n gid = download.gid\n complete = None\n await progress_status(gid=gid, event=event, previous=None)\n file = aria2.get_download(gid)\n if file.followed_by_ids:\n new_gid = await check_metadata(gid)\n await progress_status(gid=new_gid, event=event, previous=None)\n while complete != True:\n file = aria2.get_download(gid)\n complete = file.is_complete\n try:\n msg = \"**Leeching:** \"+str(file.name) + \"\\n**Speed:** \" + str(file.download_speed_string())+\"\\n**Progress:** \"+str(\n file.progress_string())+\"\\n**Total Size:** \"+str(file.total_length_string())+\"\\n**ETA:** \"+str(file.eta_string())+\"\\n\\n\"\n await event.edit(msg)\n await asyncio.sleep(10)\n except Exception as e:\n await log(str(e))\n pass\n\n await event.edit(f\"```{file.name}``` leeched successfully!\")\n\n\ndef get_video_thumb(file, output=None, width=90):\n metadata = extractMetadata(createParser(file))\n p = subprocess.Popen([\n 'ffmpeg', '-i', file,\n '-ss', str(int((0, metadata.get('duration').seconds)\n [metadata.has('duration')] / 2)),\n '-filter:v', 'scale={}:-1'.format(width),\n '-vframes', '1',\n output,\n ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)\n if not p.returncode and os.path.lexists(file):\n return output\n\n\n# Get mime type and name of given file\ndef file_ops(file_path):\n mime_type = guess_type(file_path)[0]\n mime_type = mime_type if mime_type else \"text/plain\"\n file_name = file_path.split(\"/\")[-1]\n return file_name, mime_type\n\n\nasync def create_token_file(token_file, event):\n # Run through the OAuth flow and retrieve credentials\n flow = OAuth2WebServerFlow(\n CLIENT_ID,\n CLIENT_SECRET,\n OAUTH_SCOPE,\n redirect_uri=REDIRECT_URI\n )\n authorize_url = flow.step1_get_authorize_url()\n async with event.client.conversation(ENV.LOGGER_GROUP) as conv:\n await conv.send_message(f\"Go to the following link in your browser: {authorize_url} and reply the code\")\n response = conv.wait_event(events.NewMessage(\n outgoing=True,\n chats=ENV.LOGGER_GROUP\n ))\n response = await response\n code = response.message.message.strip()\n credentials = flow.step2_exchange(code)\n storage = Storage(token_file)\n storage.put(credentials)\n return storage\n\n\ndef authorize(token_file, storage):\n # Get credentials\n if storage is None:\n storage = Storage(token_file)\n credentials = storage.get()\n # Create an httplib2.Http object and authorize it with our credentials\n http = httplib2.Http()\n credentials.refresh(http)\n http = credentials.authorize(http)\n return http\n\n\nasync def upload_file(http, file_path, file_name, mime_type, event, parent_id):\n # Create Google Drive service instance\n drive_service = build(\"drive\", \"v2\", http=http, cache_discovery=False)\n # File body description\n media_body = MediaFileUpload(file_path, mimetype=mime_type, resumable=True)\n body = {\n \"title\": file_name,\n \"description\": \"Uploaded using @Unibot gDrive v2\",\n \"mimeType\": mime_type,\n }\n if parent_id is not None:\n body[\"parents\"] = [{\"id\": parent_id}]\n # Permissions body description: anyone who has link can upload\n # Other permissions can be found at https://developers.google.com/drive/v2/reference/permissions\n permissions = {\n \"role\": \"reader\",\n \"type\": \"anyone\",\n \"value\": None,\n \"withLink\": True\n }\n # Insert a file\n file = drive_service.files().insert(body=body, media_body=media_body)\n response = None\n display_message = \"\"\n while response is None:\n status, response = file.next_chunk()\n await asyncio.sleep(1)\n if status:\n percentage = int(status.progress() * 100)\n progress_str = \"[{0}{1}]\\nProgress: {2}%\\n\".format(\n \"\".join([\"█\" for i in range(math.floor(percentage / 5))]),\n \"\".join([\"░\" for i in range(20 - math.floor(percentage / 5))]),\n round(percentage, 2)\n )\n current_message = f\"uploading to gDrive\\nFile Name: {file_name}\\n{progress_str}\"\n if display_message != current_message:\n try:\n await event.edit(current_message)\n display_message = current_message\n except Exception as e:\n logger.info(str(e))\n pass\n file_id = response.get(\"id\")\n try:\n # Insert new permissions\n drive_service.permissions().insert(fileId=file_id, body=permissions).execute()\n except:\n pass\n # Define file instance and get url for download\n file = drive_service.files().get(fileId=file_id).execute()\n download_url = file.get(\"webContentLink\")\n return download_url\n\n\ndef get_lst_of_files(input_directory, output_lst):\n filesinfolder = os.listdir(input_directory)\n for file_name in filesinfolder:\n current_file_name = os.path.join(input_directory, file_name)\n if os.path.isdir(current_file_name):\n return get_lst_of_files(current_file_name, output_lst)\n output_lst.append(current_file_name)\n return output_lst\n\n\nasync def create_directory(http, directory_name, parent_id):\n drive_service = build(\"drive\", \"v2\", http=http, cache_discovery=False)\n permissions = {\n \"role\": \"reader\",\n \"type\": \"anyone\",\n \"value\": None,\n \"withLink\": True\n }\n file_metadata = {\n \"title\": directory_name,\n \"mimeType\": G_DRIVE_DIR_MIME_TYPE\n }\n if parent_id is not None:\n file_metadata[\"parents\"] = [{\"id\": parent_id}]\n file = drive_service.files().insert(body=file_metadata).execute()\n file_id = file.get(\"id\")\n try:\n drive_service.permissions().insert(fileId=file_id, body=permissions).execute()\n except:\n pass\n logger.info(\"Created Gdrive Folder:\\nName: {}\\nID: {} \".format(\n file.get(\"title\"), file_id))\n return file_id\n\n\nasync def DoTeskWithDir(http, input_directory, event, parent_id):\n list_dirs = os.listdir(input_directory)\n if len(list_dirs) == 0:\n return parent_id\n r_p_id = None\n for a_c_f_name in list_dirs:\n current_file_name = os.path.join(input_directory, a_c_f_name)\n if os.path.isdir(current_file_name):\n current_dir_id = await create_directory(http, a_c_f_name, parent_id)\n r_p_id = await DoTeskWithDir(http, current_file_name, event, current_dir_id)\n else:\n file_name, mime_type = file_ops(current_file_name)\n # current_file_name will have the full path\n g_drive_link = await upload_file(http, current_file_name, file_name, mime_type, event, parent_id)\n r_p_id = parent_id\n # TODO: there is a #bug here :(\n return r_p_id\n\n\nasync def log(text):\n LOGGER = ENV.LOGGER_GROUP\n await client.send_message(LOGGER, text)\n\n\nasync def check_metadata(gid):\n file = aria2.get_download(gid)\n new_gid = file.followed_by_ids[0]\n logger.info(\"Changing GID \"+gid+\" to \"+new_gid)\n return new_gid\n\n\nasync def progress_status(gid, event, previous):\n global req_file\n try:\n file = aria2.get_download(gid)\n req_file = str(file.name)\n if not file.is_complete:\n if not file.error_message:\n msg = \"**Leeching**: `\"+str(file.name) + \"`\\n**Speed**: \" + str(file.download_speed_string())+\"\\n**Progress**: \"+str(file.progress_string(\n ))+\"\\n**Total Size**: \"+str(file.total_length_string())+\"\\n**Status**: \"+str(file.status)+\"\\n**ETA**: \"+str(file.eta_string())+\"\\n\\n\"\n if previous != msg:\n await event.edit(msg)\n previous = msg\n else:\n logger.info(str(file.error_message))\n await log(\"Error : `{}`\".format(str(file.error_message)))\n return\n await asyncio.sleep(EDIT_SLEEP_TIME_OUT)\n await progress_status(gid, event, previous)\n else:\n await event.edit(f\"```{file.name}``` leeched successfully!\")\n return\n except Exception as e:\n if \" not found\" in str(e) or \"'file'\" in str(e):\n await log(str(e))\n return await event.delete()\n elif \" depth exceeded\" in str(e):\n file.remove(force=True)\n await log(str(e))\n else:\n await log(str(e))\n return await event.delete()\n\nENV.HELPER.update({\n \"leech\": \"\\\n```.leech (or as a reply to a magnet link)```\\\n\\nUsage: Downloads the torrent to the local machine.\\\n\"\n})\n","repo_name":"thepriyamkalra/The-TG-Bot","sub_path":"modules/leech.py","file_name":"leech.py","file_ext":"py","file_size_in_byte":10480,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"44"} +{"seq_id":"191303075","text":"import numpy as np\nimport pandas as pd\n\ninfo_csv = './data_creation.csv'\nartist = 'foofighters'\nartist = artist.lower().replace(\" \", \"\")\n\ndf = pd.read_csv(info_csv)\ndf_filtered = df.query('artist==\"' + artist + '\"')\n\noutfile = './' + artist + '_timelist.csv'\ndf_out = pd.DataFrame(np.zeros((len(df_filtered), 2)))\ndf_out.iloc[:, 0] = np.array(df_filtered.iloc[:, 3])\ndf_out.iloc[:, 1] = np.array(df_filtered.iloc[:, 4])\nprint(df_out)\ndf_out.to_csv(outfile, header=False, index=False)\n","repo_name":"zhepeiw/cnnBenchmark","sub_path":"prepData/timelist.py","file_name":"timelist.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"1579342991","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nimport csv\nfrom milo.users.models import User\nfrom milo.users.templatetags.user_tags import *\n\ndef export_csv(request):\n users = User.objects.all().order_by(\"-id\")\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = 'attachment; filename=\"users.csv\"'\n\n writer = csv.writer(response)\n writer.writerow(['Username', \n 'Birthday', \n 'Eligible', \n 'Random Number',\n 'BizzFuzz',\n ])\n\n for user in users:\n writer.writerow([user.username, \n user.birthday_date or \"\", \n user_allowed(user),\n str(user.random_number or \"\"),\n str(modulo(user.random_number) or \"\"), \n ])\n \n return response\n","repo_name":"lpatkowski/Milo","sub_path":"milo/milo/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"70117447492","text":"from features import get_features_by_team\n\ncountNan = 0\ndef fill_XY(res, filename, feat, year):\n global countNan\n with open(filename, newline='') as file:\n file.readline()\n for line in file:\n row = line.strip().split(',')\n if int(row[0]) != year:# or row[6] != 'N':\n continue\n wTeam = int(row[2])\n lTeam = int(row[4])\n\n if 'Nan' in (feat[wTeam]+feat[lTeam]):\n countNan += 1\n continue\n\n if wTeam < lTeam:\n res[year]['X'].append(feat[wTeam]+feat[lTeam])\n res[year]['Y'].append(1)\n res[year]['teams'].append([filename,year,wTeam,lTeam])\n else:\n res[year]['X'].append(feat[lTeam]+feat[wTeam])\n res[year]['Y'].append(0)\n res[year]['teams'].append([filename,year,lTeam,wTeam])\n\n\ndef get_XY_by_year(nYear = 1):\n res = dict()\n for year in range(1985+nYear,2017):\n print(year)\n temp = get_features_by_team(year, nYear)\n feat = dict()\n for key in temp:\n feat[key] = temp[key].get_features()\n res[year] = {'X': list(), 'Y': list(), 'teams': list()}\n fill_XY(res, './data/RegularSeasonCompactResults.csv', feat, year)\n fill_XY(res, './data/TourneyCompactResults.csv', feat, year)\n print(countNan)\n return res\n","repo_name":"TeamLux/ncaa-mlmm-2017","sub_path":"src/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"41635253538","text":"import os,glob,shutil,time\nfrom PIL import Image\n\nimport argparse\n\nparser = argparse.ArgumentParser(\n prog = 'copies floppies',\n description = 'floppier floppy copier')\n\nparser.add_argument(\"FloppyDirectory\", type=str)\nparser.add_argument(\"OutputDirectory\", type=str)\n\nargs = parser.parse_args()\n\nfloppy = args.FloppyDirectory\ndest = args.OutputDirectory\n\nlocaltime = time.localtime()\n\ntimedir = str(localtime.tm_mon)+\"-\"+str(localtime.tm_mday)+\"-\"+str(localtime.tm_year)\n\nsessiondir = dest+\"/\"+timedir\n\nif not os.path.exists(sessiondir):\n print(\"Making Directory: \"+sessiondir)\n os.mkdir(sessiondir)\nelse:\n print(\"Directory \"+sessiondir+\" already exists, using...\")\n\ntry:\n curflop = max([int(s.replace('floppy-','')) for s in next(os.walk(sessiondir))[1]]) + 1\nexcept:\n curflop = 1\n\nworkingdir = \"\"\n\nwhile True:\n workingdir = sessiondir+\"/floppy-\"+str(curflop)\n\n input(\"Press any key to copy that floppy...\")\n files = glob.glob(floppy+\"*\")\n if len(files) == 0:\n print(\"There is no floppy to copy!!! (or it contains no files.)\")\n else:\n os.mkdir(workingdir)\n print(\"Created Directory: \"+workingdir)\n\n for file in files:\n\n print(\"Copying file \"+file+\" to \"+workingdir+\" ...\")\n\n try:\n shutil.copy2(file, workingdir)\n except:\n print(\"Error copying file: \"+file+\"! Skipping...\")\n\n for file in files:\n print(\"Deleting file \"+file+\" ...\")\n try:\n os.remove(file)\n except:\n print(\"Error deleting file: \"+file+\"! Skipping...\")\n curflop += 1\n print(\"Done!\\n\")\n","repo_name":"FlavoredSaucer/mavica-junk","sub_path":"postprocess.py","file_name":"postprocess.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"22588401879","text":"import torch\nimport numpy as np\n\n# 最小二乘法\nx = torch.tensor([[2.], [4.]])\n# x = np.array([[2], [4]])\nw = 4\ny = w * x\n\nw = x.T@y@((x.T@x).inverse()) # inverse() 求矩阵的逆\n# w = x.T@y@(np.linalg.inv(x.T@x)) # 同上\nprint(w)\n","repo_name":"choococo/MoMLearning","sub_path":"1.mathLearning/01.math/test05.py","file_name":"test05.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"700963839","text":"from rest_framework import serializers\nfrom apps.stroy.models import Category, SubCategory, Product, ProductImage, Size, Color, ProductComment, CommentLike, CartItem, ProductLike, Newsletter, Question, Answer\nfrom django.conf import settings\nfrom .validators import validate_star_rating\n\nclass CategorySerializer(serializers.ModelSerializer):\n class Meta:\n model = Category\n fields = ('id', 'name_uz', 'name_ru', 'slug', 'image')\n\n\nclass SubCategorySerializer(serializers.ModelSerializer):\n class Meta:\n model = SubCategory\n fields = ('id', 'name_uz', 'name_ru', 'slug', 'image', 'category', 'banner', 'width', 'height', 'banner_link')\n\n def to_representation(self, instance):\n data = super().to_representation(instance)\n data['image'] = settings.BASE_URL + data['image']\n return data\n\n\nclass ProductImageSerializer(serializers.ModelSerializer):\n image = serializers.SerializerMethodField()\n\n class Meta:\n model = ProductImage\n fields = ('id', 'product', 'image')\n \n def get_image(self, obj):\n return settings.BASE_URL + obj.image.url\n\n\nclass SizeSerializer(serializers.ModelSerializer):\n class Meta:\n model = Size\n fields = ('id', 'name_uz', 'name_ru', 'product')\n\n\nclass ColorSerializer(serializers.ModelSerializer):\n class Meta:\n model = Color\n fields = ('id', 'name_uz', 'name_ru', 'product')\n\n\nclass ProductSerializer(serializers.ModelSerializer):\n category = SubCategorySerializer()\n images = serializers.SerializerMethodField()\n sizes = serializers.SerializerMethodField()\n colors = serializers.SerializerMethodField()\n \n class Meta:\n model = Product\n fields = ['id', 'name_uz', 'name_ru', 'price', 'price_with_discount', 'in_discount', 'discount_percent', 'category', 'count', 'weight', 'product_type', 'images', 'sizes', 'colors', 'control', 'purpose', 'material', 'xususiyatlari', 'brand', 'sotuvchi', 'description', 'views', 'avarage_rating', 'comments', 'created_at']\n \n def get_images(self, obj):\n queryset = obj.productimage_set.all()\n serializer = ProductImageSerializer(queryset, many=True)\n return serializer.data\n\n def get_sizes(self, obj):\n queryset = obj.size_set.all()\n serializer = SizeSerializer(queryset, many=True)\n return serializer.data\n \n def get_colors(self, obj):\n queryset = obj.color_set.all()\n serializer = ColorSerializer(queryset, many=True)\n return serializer.data\n\n\nclass ProductCommentSerializer(serializers.ModelSerializer):\n user_liked_or_disliked_or_not = serializers.SerializerMethodField()\n\n class Meta:\n model = ProductComment\n fields = ('id', 'product', 'user', 'comment', 'stars', 'created_at', 'likes_count', 'dislikes_count', 'user_liked_or_disliked_or_not')\n read_only_fields = ('user', 'created_at', 'user_liked_or_disliked_or_not', 'likes_count', 'dislikes_count')\n\n \n def get_user_liked_or_disliked_or_not(self, obj):\n request = self.context.get('request')\n user = request.user\n if request.user.is_authenticated:\n if user in obj.likes.all():\n return 'like'\n elif user in obj.dislikes.all():\n return 'dislike'\n else:\n return 'none'\n return 'none'\n \n def validate_stars(self, value):\n validate_star_rating(value)\n return value\n \n def to_representation(self, instance):\n data = super().to_representation(instance)\n data['user'] = instance.user.full_name\n return data\n \n\nclass CommentLikeSerializer(serializers.Serializer):\n comment = serializers.PrimaryKeyRelatedField(queryset=ProductComment.objects.all(), required=True)\n\n def create(self, validated_data):\n request = self.context.get('request')\n comment = validated_data['comment']\n\n if request.user.is_authenticated:\n print(\"Came here auth___________\")\n if request.user in comment.likes.all():\n print(\"Came here liked___________\")\n comment.likes.remove(request.user)\n return comment\n elif request.user in comment.dislikes.all():\n comment.dislikes.remove(request.user)\n comment.likes.add(request.user)\n return comment\n else:\n comment.likes.add(request.user)\n return comment\n return comment\n\n\nclass CommentDislikeSerializer(serializers.Serializer):\n comment = serializers.PrimaryKeyRelatedField(queryset=ProductComment.objects.all(), required=True)\n\n def create(self, validated_data):\n request = self.context.get('request')\n comment = validated_data['comment']\n\n if request.user.is_authenticated:\n if request.user in comment.dislikes.all():\n comment.dislikes.remove(request.user)\n return comment\n elif request.user in comment.likes.all():\n comment.likes.remove(request.user)\n comment.dislikes.add(request.user)\n return comment\n else:\n comment.dislikes.add(request.user)\n return comment\n return comment\n \n\nclass CartItemSerializer(serializers.ModelSerializer):\n user = serializers.StringRelatedField()\n quantity = serializers.IntegerField(required=False, default=1)\n\n class Meta:\n model = CartItem\n fields = ['id', 'product','session_key', 'quantity', 'user', 'date_added']\n read_only_fields = ('user', 'session_key', 'date_added')\n\n def create(self, validated_data):\n request = self.context.get('request')\n if request.user.is_authenticated:\n validated_data['user'] = request.user\n cart_item = CartItem.objects.filter(user=request.user, product=validated_data['product']).last()\n if cart_item:\n cart_item.quantity += validated_data['quantity']\n cart_item.save()\n return cart_item\n return super().create(validated_data)\n session_key = request.session.session_key\n if not session_key:\n request.session.save()\n session_key = request.session.session_key\n validated_data['session_key'] = session_key\n cart_item = CartItem.objects.filter(session_key=session_key, product=validated_data['product']).last()\n if cart_item:\n cart_item.quantity += validated_data['quantity']\n cart_item.save()\n return cart_item\n return super().create(validated_data)\n \n\n def to_representation(self, instance):\n data = super().to_representation(instance)\n data['product'] = ProductSerializer(instance.product).data\n data['price'] = instance.product.price_with_discount * instance.quantity\n data['image'] = settings.BASE_URL + instance.product.productimage_set.first().image.url\n return data\n\n\nclass ProductLikeSerializer(serializers.ModelSerializer):\n class Meta:\n model = ProductLike\n fields = (\"id\", \"user\", \"session_key\", \"product\")\n read_only_fields = (\"user\", \"session_key\")\n \n def create(self, validated_data):\n request = self.context.get('request')\n if request.user.is_authenticated:\n if ProductLike.objects.filter(user=request.user, product=validated_data['product']).exists():\n raise serializers.ValidationError('You have already liked this product')\n validated_data['user'] = request.user\n return super().create(validated_data)\n session_key = request.session.session_key\n if not session_key:\n request.session.save()\n session_key = request.session.session_key\n if ProductLike.objects.filter(session_key=session_key, product=validated_data['product']).exists():\n raise serializers.ValidationError('You have already liked this product')\n validated_data['session_key'] = session_key\n return super().create(validated_data)\n \n def to_representation(self, instance):\n data = super().to_representation(instance)\n data['product'] = ProductSerializer(instance.product).data\n data['image'] = settings.BASE_URL + instance.product.productimage_set.first().image.url\n data['session_key'] = None\n return data\n\n\nclass NewsletterSerializer(serializers.ModelSerializer):\n class Meta:\n model = Newsletter\n fields = ('id', 'phone_number', 'created_at')\n read_only_fields = ('created_at',)\n\n\nclass QuestionSerializer(serializers.ModelSerializer):\n answers = serializers.SerializerMethodField(required=False, read_only=True)\n\n class Meta:\n model = Question\n fields = ('id', 'user', 'product', 'question','answers', 'created_at', 'updated_at')\n read_only_fields = ('created_at', 'updated_at', 'user', 'product')\n\n def get_answers(self, obj):\n answers = Answer.objects.filter(question=obj)\n return AnswerSerializer(answers, many=True).data\n \n def to_representation(self, instance):\n data = super().to_representation(instance)\n data['user'] = instance.user.full_name\n return data\n \n\nclass AnswerSerializer(serializers.ModelSerializer):\n by_admin = serializers.BooleanField(read_only=True)\n user = serializers.StringRelatedField(read_only=True)\n\n class Meta:\n model = Answer\n fields = ('id', 'question', 'answer', 'user', 'by_admin', 'created_at', 'updated_at')\n \n def to_representation(self, instance):\n data = super().to_representation(instance)\n data['question'] = instance.question.question\n return data\n ","repo_name":"sevbo2003/stroy-market","sub_path":"stroy_market/apps/stroy/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":9785,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"44"} +{"seq_id":"11444439255","text":"#!/usr/bin/python3\n\nprint(\"Hello welcome to the coffee shop\\n\")\n\n\nmenu=\"coffee, tea and wather\"\nname=input(\"Hello what's your name\\n\")\nbeverage=input(\"What do you want to drink \"+ name +\" from the menu \"+menu+\"\\n\")\n\nprint(\"your \"+beverage+\" gonna be ready soon \\n\")\n\nprice=4\nunits=int(input(\"how many units you want? \\n\"))\n\nmax_units=100\nif units>max_units:\n print(\"we just have \"+str(max_units)+\" unitsgit sta\")\nelse:\n print(\"the value of your order is: \"+str(price*units)+ \" USD\")\n print(name+ \" your \"+ beverage + \" is going to be ready soon\")\n","repo_name":"alfilsoft/cloud-camp","sub_path":"python/exercise-1.py","file_name":"exercise-1.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"35734593277","text":"import numpy as np \nimport pandas as pd\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfrom IPython.core.interactiveshell import InteractiveShell\nInteractiveShell.ast_node_interactivity = \"all\"\nimport matplotlib.pyplot as plt\nimport seaborn as sns \nimport missingno as msno\n\npd.set_option('display.max_rows',200)\npd.set_option('display.max_columns',100)\nimport pickle\nfrom scipy.special import boxcox1p\nfrom scipy.stats import boxcox_normmax\n\ndef data_preprocess():\n\ttrain = pd.read_csv('data/train.csv')\n\ttest = pd.read_csv('data/test.csv')\n\n\n\t# Combining dataset-----------------------------------------------\n\ttrain_y = train['SalePrice']\n\tdata = pd.concat((train,test),sort= False).reset_index(drop=True)\n\tdata.drop(['SalePrice','Id'],axis=1,inplace=True)\n\tdata.rename(columns={'1stFlrSF':'FirstFlrSF','2ndFlrSF':'SecondFlrSF','3SsnPorch':'ThreeSsnPorch'}, inplace=True)\n\n\n\ttrain_y = np.log(train_y + 1) \n\n\t#Missing Data-------------------------------------------------------\n\tmissing_data = pd.DataFrame(data.isnull().sum()).reset_index()\n\tmissing_data.columns = ['ColumnName','MissingCount']\n\n\tmissing_data['PercentMissing'] = round(missing_data['MissingCount']/data.shape[0],3)*100\n\tmissing_data =missing_data.sort_values(by = 'MissingCount',ascending = False).reset_index(drop = True)\n\n\t\n\n\t#Drop the PoolQ,MiscFeature and Alley columns \n\tdata.drop(['PoolQC','MiscFeature','Alley'],axis=1,inplace=True)\n\tffill= list(missing_data.ColumnName[18:34])\n\tdata[ffill] = data[ffill].fillna(method = 'ffill')\n\n\n\n\t\n\tcol_for_zero = ['Fence','FireplaceQu','GarageFinish','GarageQual','GarageCond','GarageType','BsmtExposure','BsmtCond','BsmtQual','BsmtFinType2','BsmtFinType1','MasVnrType']\n\tdata[col_for_zero] = data[col_for_zero].fillna('None')\n\tdata['LotFrontage'] = data['LotFrontage'].fillna(data['LotFrontage'].dropna().mean())\n\tdata['GarageYrBlt'] = data['GarageYrBlt'].fillna(data['GarageYrBlt'].dropna().median())\n\tdata['MasVnrArea'] = data['MasVnrArea'].fillna(data['MasVnrArea'].dropna().median())\n\n\n\n\tdata['YrBltAndRemod']=data['YearBuilt']+data['YearRemodAdd']\n\tdata['TotalSF']=data['TotalBsmtSF'] + data['FirstFlrSF'] + data['SecondFlrSF']\n\tdata['Total_sqr_footage'] = (data['BsmtFinSF1'] + data['BsmtFinSF2'] +data['FirstFlrSF'] + data['SecondFlrSF'])\n\tdata['Total_Bathrooms'] = (data['FullBath'] + (0.5 * data['HalfBath']) +data['BsmtFullBath'] + (0.5 * data['BsmtHalfBath']))\n\tdata['Total_porch_sf'] = (data['OpenPorchSF'] + data['ThreeSsnPorch'] + data['EnclosedPorch'] + data['ScreenPorch'] + data['WoodDeckSF'])\n\tdata['hasfence'] = data['Fence'].apply(lambda x: 0 if x == 0 else 1).astype(str)\n\tdata['hasmasvnr'] = data['MasVnrArea'].apply(lambda x: 0 if x == 0 else 1).astype(str)\n\tdata['haspool'] = data['PoolArea'].apply(lambda x: 1 if x > 0 else 0).astype(str)\n\tdata['has2ndfloor'] = data['SecondFlrSF'].apply(lambda x: 1 if x > 0 else 0).astype(str)\n\tdata['hasgarage'] = data['GarageArea'].apply(lambda x: 1 if x > 0 else 0).astype(str)\n\tdata['hasbsmt'] = data['TotalBsmtSF'].apply(lambda x: 1 if x > 0 else 0).astype(str)\n\tdata['hasfireplace'] = data['Fireplaces'].apply(lambda x: 1 if x > 0 else 0).astype(str)\n\tdata['MSSubClass'] = data['MSSubClass'].astype(str)\n\tdata['YrSold'] = data['YrSold'].astype(str)\n\tdata['MoSold'] = data['MoSold'].astype(str)\n\n\n\n\tnum_var=[key for key in dict(data.dtypes) if dict(data.dtypes)[key] in ['float64', 'int64', 'float32', 'int32']]\n\tcat_var=[key for key in dict(data.dtypes) if dict(data.dtypes)[key] in ['object']]\n\t\n\tnumerical_data = data[num_var]\n\tcategorical_data = data[cat_var]\n\n\n\n\t#skew X variables\n\tskew_data = numerical_data.apply(lambda x: x.skew()).sort_values(ascending=False)\n\n\n\thigh_skew = skew_data[skew_data > 0.5]\n\tskew_index = high_skew.index\n\n\tfor i in skew_index:\n\t data[i] = boxcox1p(data[i], boxcox_normmax(data[i] + 1))\n\n\n\tfor c_feature in categorical_data.columns:\n \t categorical_data[c_feature] = categorical_data[c_feature].astype('category')\n \t categorical_data = create_dummies(categorical_data , c_feature)\n\t\t \n\tnumerical_data.drop('PoolArea',axis=1,inplace=True)\n\tnumerical_data = numerical_data.apply(outlier_capp)\n\tnumerical_data['PoolArea'] = data.PoolArea\n\n\n\n\n\tfinal_data = pd.concat([categorical_data,numerical_data,train_y],axis=1)\n\tfinal_data.columns= [var.strip().replace('.', '_') for var in final_data.columns]\n\tfinal_data.columns= [var.strip().replace('&', '_') for var in final_data.columns]\n\tfinal_data.columns= [var.strip().replace(' ', '_') for var in final_data.columns]\n\n\toverfit = []\n\tfor i in final_data.columns:\n\t counts = final_data[i].value_counts()\n\t zeros = counts.iloc[0]\n\t if zeros / len(final_data) * 100 > 99.94:\n\t \toverfit.append(i)\n\n\n\tfinal_data.drop(overfit,axis=1,inplace=True)\n\n\n\t#splitting the data set into two sets\n\tfinal_train = final_data.loc[final_data.SalePrice.isnull()==0]\n\tfinal_test = final_data.loc[final_data.SalePrice.isnull()==1]\n\tfinal_train = final_train.drop('SalePrice',axis=1)\n\tfinal_test = final_test.drop('SalePrice',axis=1)\n\n\n\ttrain_x = final_train\n\n\ttest_X = final_test\n\treturn train_x,train_y,test_X\n\n\ndef outlier_capp(x):\n x = x.clip(upper = x.quantile(0.90))\n x = x.clip(lower = x.quantile(0.10))\n return x\n\n\n\ndef create_dummies(df,colname):\n col_dummies = pd.get_dummies(df[colname],prefix =colname)\n col_dummies.drop(col_dummies.columns[0],axis=1,inplace=True)\n df = pd.concat([df,col_dummies],axis=1)\n df.drop(colname,axis=1,inplace=True)\n return df\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Rhavutcu/-Kaggle-House-Prices-","sub_path":"data_pre.py","file_name":"data_pre.py","file_ext":"py","file_size_in_byte":5468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"74370171972","text":"import os, sys, re, csv, statistics\nimport argparse, logging, warnings\nfrom Bio import SeqIO\nfrom Bio.SeqIO.QualityIO import FastqGeneralIterator\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\n\n## Script for plotting average PHRED score per read and outputting data frames of PHRED averages\n## Requires Biopython, Numpy, and Matplotlib\n## Required Input: Two shuffled, paired-end .fastq files with equal numbers of forward (R1) and reverse (R2) reads\n## Output: Two .png files and/or two .csv files\n## Function: A closure for file extension checking\n\ndef ext_check(expected_ext, openner):\n def extension(filename):\n if not filename.lower().endswith(expected_ext):\n raise ValueError()\n return openner(filename)\n return extension\n\n## Two shuffled, paired-end .fastq files expected as input\n\nparser = argparse.ArgumentParser(description='Computes sequence lengths and average PHRED for shuffled paired reads in fastq', usage=\"plotDoubleShuffledFastq.py filepath/filename1.fastq filepath/filename2.fastq\")\n\nparser.add_argument('filename1', nargs='+', type=ext_check('.fastq', argparse.FileType('r')))\nparser.add_argument('filename2', nargs='+', type=ext_check('.fastq', argparse.FileType('r')))\n\n## outputType enables suppression of dataframe (.csv) output files or suppression of histogram (.png) output files\nparser.add_argument('--outputType', '-o', default='F', choices=['F', 'P', 'C'], help=\"--outputType F for full output (plots and .csv), P for plots only, and C for csv file with no plot.\")\n\nargs = parser.parse_args()\n\nprint(args.filename1[0].name)\nprint(args.filename2[0].name)\n\n## File names used in plot titles\nmyTitle1 = re.split(r'[\\.\\/]', args.filename1[0].name)\nmyTitle2 = re.split(r'[\\.\\/]', args.filename2[0].name)\n\nprint(myTitle1[len(myTitle1) - 2])\nprint(myTitle2[len(myTitle2) - 2])\n\ncsvRow1 = []\nforwardLen1 = []\nreverseLen1 = []\nforwardAvg1 = []\nreverseAvg1 = []\n\ncsvRow2 = []\nforwardLen2 = []\nreverseLen2 = []\nforwardAvg2 = []\nreverseAvg2 = []\n\niter = 0\n\nmyFastq1 = open(args.filename1[0].name, \"r\")\nmyFastq2 = open(args.filename2[0].name, \"r\")\n\nfor record in SeqIO.parse(myFastq1, \"fastq\"):\n if(iter % 2 == 0):\n #print(\"%s,%i,%0.2f,\" % (record.description, len(record.seq), statistics.mean(record.letter_annotations[\"phred_quality\"])), end=\"\")\n forwardAvg1.append(statistics.mean(record.letter_annotations[\"phred_quality\"]))\n elif(iter % 2 == 1):\n strand = record.description.split(\" \")\n #print(\"%s,%i,%0.2f\" % (strand[1], len(record.seq), statistics.mean(record.letter_annotations[\"phred_quality\"])))\n reverseAvg1.append(statistics.mean(record.letter_annotations[\"phred_quality\"]))\n iter = iter + 1\n\n\nfor record in SeqIO.parse(myFastq2, \"fastq\"):\n if(iter % 2 == 0):\n #print(\"%s,%i,%0.2f,\" % (record.description, len(record.seq), statistics.mean(record.letter_annotations[\"phred_quality\"])), end=\"\")\n forwardAvg2.append(statistics.mean(record.letter_annotations[\"phred_quality\"]))\n elif(iter % 2 == 1):\n strand = record.description.split(\" \")\n #print(\"%s,%i,%0.2f\" % (strand[1], len(record.seq), statistics.mean(record.letter_annotations[\"phred_quality\"])))\n reverseAvg2.append(statistics.mean(record.letter_annotations[\"phred_quality\"]))\n iter = iter + 1\n\n#forwardAvg1 = np.random.normal(size = 500000) + 30\n#reverseAvg1 = 1.5*np.random.normal(size = 500000) + 25\n\nif(args.outputType != 'C'):\n SMALL_SIZE = 20\n MEDIUM_SIZE = 24\n BIG_SIZE = 30\n fig1, axes1 = plt.subplots(nrows=2, ncols=1, sharex=True, sharey=True, figsize=(14,20))\n\n ## Plot PHRED Quality for R1 reads as 1D histogram\n axes1[0].xaxis.label.set_size(MEDIUM_SIZE)\n axes1[0].yaxis.label.set_size(MEDIUM_SIZE)\n axes1[0].tick_params(axis='x', labelsize=SMALL_SIZE)\n axes1[0].tick_params(axis='y', labelsize=SMALL_SIZE)\n axes1[0].hist(forwardAvg1, bins = 40, color='blue')\n axes1[0].set_title(\"R1 MiSeq \" + myTitle1[len(myTitle1) - 2], fontsize = BIG_SIZE)\n axes1[0].set(ylabel='Read Counts')\n\n ## Plot PHRED Quality for R2 reads as 1D histogram\n axes1[1].xaxis.label.set_size(MEDIUM_SIZE)\n axes1[1].yaxis.label.set_size(MEDIUM_SIZE)\n axes1[1].tick_params(axis='x', labelsize=SMALL_SIZE)\n axes1[1].tick_params(axis='y', labelsize=SMALL_SIZE)\n axes1[1].hist(forwardAvg2, bins = 40, color='blue')\n axes1[1].set_title(\"R1 iSeq \" + myTitle2[len(myTitle2) - 2], fontsize = BIG_SIZE)\n axes1[1].set(ylabel='Read Counts')\n axes1[1].set(xlabel='Average Read Quality')\n fig1.savefig('/scicomp/home-pure/ydn3/test_Python3.9.1/test_Biopython/fwd_miSeq_and_iSeq_PHRED.png')\n fig2, axes2 = plt.subplots(nrows=2, ncols=1, sharex=True, sharey=True, figsize=(14,20))\n\n ## Plot PHRED Quality for R1 reads as 1D histogram\n axes2[0].xaxis.label.set_size(MEDIUM_SIZE)\n axes2[0].yaxis.label.set_size(MEDIUM_SIZE)\n axes2[0].tick_params(axis='x', labelsize=SMALL_SIZE)\n axes2[0].tick_params(axis='y', labelsize=SMALL_SIZE)\n axes2[0].hist(reverseAvg1, bins = 40, color='red')\n axes2[0].set_title(\"R2 MiSeq \" + myTitle1[len(myTitle1) - 2], fontsize = BIG_SIZE)\n axes2[0].set(ylabel='Read Counts')\n\n ## Plot PHRED Quality for R2 reads as 1D histogram\n axes2[1].xaxis.label.set_size(MEDIUM_SIZE)\n axes2[1].yaxis.label.set_size(MEDIUM_SIZE)\n axes2[1].tick_params(axis='x', labelsize=SMALL_SIZE)\n axes2[1].tick_params(axis='y', labelsize=SMALL_SIZE)\n axes2[1].hist(reverseAvg2, bins = 40, color='red')\n axes2[1].set_title(\"R2 iSeq \" + myTitle2[len(myTitle2) - 2], fontsize = BIG_SIZE)\n axes2[1].set(ylabel='Read Counts')\n axes2[1].set(xlabel='Average Read Quality')\n fig2.savefig('/scicomp/home-pure/ydn3/test_Python3.9.1/test_Biopython/rev_miSeq_and_iSeq_PHRED.png')\n\nif(args.outputType != 'P'):\n totalMiSeqPHRED = { \"R1_MiSeq_PHRED\" : forwardAvg1, \"R2_MiSeq_PHRED\" : reverseAvg1 }\n totaliSeqPHRED = { \"R1_iSeq_PHRED\" : forwardAvg2, \"R2_iSeq_PHRED\" : reverseAvg2 }\n dfMiSeqPHRED = pd.DataFrame(totalMiSeqPHRED)\n dfiSeqPHRED = pd.DataFrame(totaliSeqPHRED)\n dfMiSeqPHRED.to_csv('/scicomp/home-pure/ydn3/test_Python3.9.1/test_Biopython/fwd_rev_miSeq_PHRED.csv') \n dfiSeqPHRED.to_csv('/scicomp/home-pure/ydn3/test_Python3.9.1/test_Biopython/fwd_rev_iSeq_PHRED.csv') \n","repo_name":"darlenewagner/NGS_Plot_Widgets","sub_path":"plotDoubleShuffledFastq.py","file_name":"plotDoubleShuffledFastq.py","file_ext":"py","file_size_in_byte":6639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"14645033454","text":"import rich\nimport torch\nfrom transformers import DistilBertModel\n\nfrom models.core import CoreTweeSent\n\nDISTILBERT_DESC = (\n \"DistilBert Model with a Dropout layer and two Linear layers as output...\"\n)\n\n\nclass DistilBertSentiment(CoreTweeSent):\n def __init__(self, **hparams):\n super().__init__(**hparams)\n self.desc = DISTILBERT_DESC\n\n self.distilbert = DistilBertModel.from_pretrained(\"distilbert-base-cased\")\n self.drop = torch.nn.Dropout(self.distilbert.config.seq_classif_dropout)\n\n distilbert_dim = self.distilbert.config.dim\n self.pre_classifier = torch.nn.Linear(distilbert_dim, distilbert_dim)\n self.classifier = torch.nn.Linear(distilbert_dim, 3)\n # self.freeze_distilbert()\n\n def freeze_distilbert(self):\n if isinstance(self.distilbert, DistilBertModel):\n self.distilbert.eval()\n self.distilbert.requires_grad = False\n for param in self.distilbert.parameters():\n param.requires_grad = False\n\n def forward(\n self, attention_mask: torch.IntTensor, input_ids: torch.IntTensor, **kwargs\n ) -> torch.Tensor:\n output = self.distilbert(attention_mask=attention_mask, input_ids=input_ids)\n\n hidden_state = output[0] # (bs, seq_len, dim)\n output = hidden_state[:, 0] # (bs, dim)\n\n output = torch.relu(self.pre_classifier(output))\n output = self.drop(output)\n return self.classifier(output)\n","repo_name":"presedo93/tweesent-gym","sub_path":"models/distilbert.py","file_name":"distilbert.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"27951323068","text":"#!/usr/bin/env python\n# -*- codinng:utf-8 -*-\nimport pygame\nfrom pygame.sprite import Sprite\n\n\nclass Alien(Sprite):\n\tdef __init__(self, ai_settings, screen):\n\t\tsuper(Alien, self).__init__()\n\t\tself.ai_settings = ai_settings\n\t\tself.screen = screen\n\n\t\t# 加载Alien的图像,并试着其rect属性\n\t\tself.image = pygame.image.load('images/alien_ship.bmp')\n\t\tself.rect = self.image.get_rect()\n\n\t\t# 设置初始坐标,使每个外星人初始状态都在左上角\n\t\tself.rect.x = self.rect.width\n\t\tself.rect.y = self.rect.height\n\n\t\t# 存储外星人的准确位置\n\t\tself.x = float(self.rect.x)\n\n\tdef blitme(self):\n\t\t# 在指定位置绘制外星人\n\t\tself.screen.blit(self.image, self.rect)\n\n\tdef check_edge(self):\n\t\t# 如果外星人位于屏幕边缘,则返回True\n\t\tscreen_rect = self.screen.get_rect()\n\t\tif self.rect.right >= screen_rect.right:\n\t\t\treturn True\n\t\telif self.rect.left <= screen_rect.left:\n\t\t\treturn True\n\n\tdef update(self):\n\t\t# 向左或者向右移动外星人\n\t\tself.x += (self.ai_settings.alien_speed_factor * self.ai_settings.fleet_direction)\n\t\tself.rect.x = self.x\n","repo_name":"Ranngo/Spaceship_Game","sub_path":"Spaceship_Game/alien.py","file_name":"alien.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"21582422489","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon 15 at 12:38:17 2022\n\n@author: hpopo\n\"\"\"\n\nimport numpy as np\nfrom matplotlib import pyplot as pp\n#dipole values\n\nfilename = \"MHDGEO_20150618_002000.dat\"\nf = open(filename, \"r\")\n\nf.readline()\nf.readline()\nlong = []\nlat = []\nalt = []\nb_up = []\nb_north = []\nb_east = []\nfor line in f:\n f_new = line.split()\n long.append(float(f_new[0]))\n lat.append(float(f_new[1]))\n alt.append(int(f_new[2]))\n b_up.append(float(f_new[3]))\n b_north.append(float(f_new[4]))\n b_east.append(float(f_new[5]))\n\nb_up = np.array(b_up)\nb_north = np.array((b_north))\nb_east = np.array((b_east))\n#b_total = np.zeros((len(b_east), len(b_north), len(b_up)))\n\n\nalt2 = list(set(alt))\nalt2.sort()\nprint(\"{}\".format(alt2))\n\nuser_alt = input(\"Choose an Altitude:\")\n\nif int(user_alt) in alt[:]:\n print('Value Accepted')\n pp.contourf((long, lat, b_up), levels = 25)\n\nelse:\n print(\"Invalid Altitude\")\n \npp.xlabel(\"Longitude\")\npp.ylabel(\"Latitude\")\npp.title(\"B_Up with Respect to Longitude and Latitude\")\npp.show\n\n\n \nf.close()\n\n \n \n\n","repo_name":"hanpopo/Mars_Project","sub_path":"Mag_Field.py","file_name":"Mag_Field.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"34222724414","text":"import argparse\nimport datetime\nimport os\nimport random\nimport sys\n\nfrom modules import cleaner, tokenizer\nfrom modules.weighting import TfWeighting, TfIdfWeighting\nfrom modules.classifier import SvmClassifier\n\ndef f_measure(precision, recall):\n return 2 * ((precision * recall) / (precision + recall))\n\nparser = argparse.ArgumentParser(description='Evaluate classifier model using ten folds cross validation.')\nparser.add_argument('-n', '--ngrams', type=int, default=1, help='How many n used in n-grams scheme, default \"1\"')\nparser.add_argument('-w', '--weight', dest='weighting', default='tf', choices=['tf', 'tfidf'], help='Weighting scheme: term frequency or term frequency-inverse document frequency, default \"tf\"')\nparser.add_argument('-d', '--data', default='all', choices=['all', 'under', 'over'], help='Use all data, undersampled data, or oversampled data, default \"all\"')\nparser.add_argument('-o', '--output', default='evaluation.csv', help='File name for output CSV, e.g. evaluation.csv')\nargs = parser.parse_args()\n\nprint('Options:')\nprint('Ngrams: {}'.format(args.ngrams))\nprint('Weighting scheme: {}'.format(args.weighting))\nprint('Data imbalance handle: {}\\n'.format(args.data))\n\ntraffic_tweets = [(line, 'traffic') for line in open('tweets_corpus/traffic_tweets_combined.txt')]\nnon_traffic_tweets = [(line, 'non_traffic') for line in open('tweets_corpus/random_tweets.txt')] + \\\n [(line, 'non_traffic') for line in open('tweets_corpus/non_traffic_tweets.txt')]\nrandom.shuffle(traffic_tweets)\nrandom.shuffle(non_traffic_tweets)\n\nif args.data == 'all':\n pass\nelif args.data == 'under':\n traffic_tweets = traffic_tweets[:min([len(traffic_tweets), len(non_traffic_tweets)])]\n non_traffic_tweets = non_traffic_tweets[:min([len(traffic_tweets), len(non_traffic_tweets)])]\nelif args.data == 'over':\n mul = int(max([len(traffic_tweets), len(non_traffic_tweets)]) / min([len(traffic_tweets), len(non_traffic_tweets)]))\n if len(traffic_tweets) > len(non_traffic_tweets):\n non_traffic_tweets = non_traffic_tweets * (mul + 1)\n non_traffic_tweets = non_traffic_tweets[:len(traffic_tweets)]\n else:\n traffic_tweets = traffic_tweets * (mul + 1)\n traffic_tweets = traffic_tweets[:len(non_traffic_tweets)]\n\nlabeled_tweets = (traffic_tweets + non_traffic_tweets)\nrandom.shuffle(labeled_tweets)\n\nprint('Start analysis with total:', len(labeled_tweets), 'data')\nprint('Traffic tweets:', len(traffic_tweets),'data')\nprint('Non traffic tweets:', len(non_traffic_tweets),'data')\n\ncleaned_tweets = cleaner.clean_tweets(labeled_tweets)\nprint(cleaned_tweets[:3])\n\ntokenized_tweets = tokenizer.tokenize_tweets(cleaned_tweets, args.ngrams)\nprint(len(tokenized_tweets))\nprint(tokenized_tweets[:3])\n\nif args.weighting == 'tf':\n weighter = TfWeighting(tokenized_tweets)\nelif args.weighting == 'tfidf':\n weighter = TfIdfWeighting(tokenized_tweets)\n\ndataset = weighter.get_features()\nprint(dataset[:3])\n# svm_model = SvmClassifier(dataset)\n\nwith open(os.path.dirname(__file__) + args.output, 'a') as f:\n f.write('\"{}\"\\r\\n'.format(sys.argv))\n f.write('\"{}\"\\r\\n'.format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))\n f.write('\"Start analysis with total: {} data\"\\r\\n'.format(len(labeled_tweets)))\n f.write('\"Traffic tweets: {} data\"\\r\\n'.format(len(traffic_tweets)))\n f.write('\"Non traffic tweets: {} data\"\\r\\n\\r\\n'.format(len(non_traffic_tweets)))\n\ndata_format = '\"{}\",\"{}\",\"{}\",\"{}\",\"{}\",\"{}\",\"{}\",\"{}\",\"{}\",\"{}\"\\r\\n'\nwith open(os.path.dirname(__file__) + args.output, 'a') as f:\n f.write(data_format.format(\n 'Iteration',\n 'Training time',\n 'True positive',\n 'True negative',\n 'False positive',\n 'False negative',\n 'Accuracy',\n 'Precision',\n 'Recall',\n 'F-measure'\n ))\n\nsvm_times = []\nsvm_true_positives = []\nsvm_true_negatives = []\nsvm_false_positives = []\nsvm_false_negatives = []\nsvm_accuracies = []\nsvm_precisions = []\nsvm_recalls = []\nsvm_f_measures = []\n\nfold = 10\n\nfor i in range(fold):\n train_set = dataset[0:i*int(len(dataset)/fold)] + dataset[(i+1)*int(len(dataset)/fold):len(dataset)]\n test_set = dataset[i*int(len(dataset)/fold):(i+1)*int(len(dataset)/fold)]\n\n print('\\nIteration', (i+1))\n print('Training data:', len(train_set), 'data')\n print('Test data:', len(test_set), 'data')\n\n # SVM\n svm_classifier = SvmClassifier(train_set)\n\n svm_true_positive = 0\n svm_true_negative = 0\n svm_false_positive = 0\n svm_false_negative = 0\n for index, (feature, label) in enumerate(test_set):\n observed = svm_classifier.classify(feature)\n if label == 'traffic' and observed == 'traffic':\n svm_true_positive += 1\n if label == 'non_traffic' and observed == 'non_traffic':\n svm_true_negative += 1\n if label == 'traffic' and observed == 'non_traffic':\n svm_false_positive += 1\n if label == 'non_traffic' and observed == 'traffic':\n svm_false_negative += 1\n\n svm_time = svm_classifier.get_training_time()\n svm_accuracy = (svm_true_positive + svm_true_negative) / (svm_true_positive + svm_true_negative + svm_false_positive + svm_false_negative)\n svm_precision = svm_true_positive / (svm_true_positive + svm_false_positive)\n svm_recall = svm_true_positive / (svm_true_positive + svm_false_negative)\n svm_f_measure = f_measure(svm_precision, svm_recall)\n\n svm_times.append(svm_time)\n svm_true_positives.append(svm_true_positive)\n svm_true_negatives.append(svm_true_negative)\n svm_false_positives.append(svm_false_positive)\n svm_false_negatives.append(svm_false_negative)\n svm_accuracies.append(svm_accuracy)\n svm_precisions.append(svm_precision)\n svm_recalls.append(svm_recall)\n svm_f_measures.append(svm_f_measure)\n\n with open(os.path.dirname(__file__) + args.output, 'a') as f:\n f.write(data_format.format(\n i + 1,\n svm_time,\n svm_true_positive,\n svm_true_negative,\n svm_false_positive,\n svm_false_negative,\n svm_accuracy,\n svm_precision,\n svm_recall,\n svm_f_measure\n ))\n\n print('SVM Classifier:')\n print('\\t', 'Training time:', svm_time)\n print('\\t', 'True positive:', svm_true_positive)\n print('\\t', 'True negative:', svm_true_negative)\n print('\\t', 'False positive:', svm_false_positive)\n print('\\t', 'False negative:', svm_false_negative)\n print('\\t', 'Accuracy:', svm_accuracy)\n print('\\t', 'Precision:', svm_precision)\n print('\\t', 'Recall:', svm_recall)\n print('\\t', 'F-Measure:', svm_f_measure)\n\n\nwith open(os.path.dirname(__file__) + args.output, 'a') as f:\n f.write((data_format + '\\r\\n\\r\\n').format(\n 'Total',\n sum(svm_times) / len(svm_times),\n sum(svm_true_positives) / len(svm_true_positives),\n sum(svm_true_negatives) / len(svm_true_negatives),\n sum(svm_false_positives) / len(svm_false_positives),\n sum(svm_false_negatives) / len(svm_false_negatives),\n sum(svm_accuracies) / len(svm_accuracies),\n sum(svm_precisions) / len(svm_precisions),\n sum(svm_recalls) / len(svm_recalls),\n sum(svm_f_measures) / len(svm_f_measures)\n ))\n\nprint('\\nSummary SVM Classifier:')\nprint('\\tAverage training time:', sum(svm_times) / len(svm_times))\nprint('\\tAverage true positive:', sum(svm_true_positives) / len(svm_true_positives))\nprint('\\tAverage true negative:', sum(svm_true_negatives) / len(svm_true_negatives))\nprint('\\tAverage false positives:', sum(svm_false_positives) / len(svm_false_positives))\nprint('\\tAverage false negatives:', sum(svm_false_negatives) / len(svm_false_negatives))\nprint('\\tAverage accuracy:', sum(svm_accuracies) / len(svm_accuracies))\nprint('\\tAverage precision:', sum(svm_precisions) / len(svm_precisions))\nprint('\\tAverage recall:', sum(svm_recalls) / len(svm_recalls))\nprint('\\tAverage F-Measure:', sum(svm_f_measures) / len(svm_f_measures))\n","repo_name":"dwiajik/twit-macet-mining-v2","sub_path":"evaluate_ten_folds.py","file_name":"evaluate_ten_folds.py","file_ext":"py","file_size_in_byte":8000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"7770585121","text":"from setup_tools.config import config\nfrom setup_tools.jobs import add_job\nfrom setup_tools.installers import async_proc, fetch_file\n\n\ndef install_aws():\n async def aws():\n installed = await async_proc('aws --version')\n if not installed['returncode']:\n print('aws cli is installed')\n return True\n\n print('aws cli not installed')\n if config.dry_run:\n return True\n\n print('Installing aws cli')\n url = \"https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip\"\n filename = await fetch_file('xx', url)\n await async_proc(f'unzip {filename}', cwd=config.sources_home)\n await async_proc('sudo ./aws/install', cwd=config.sources_home)\n\n add_job(aws(), run_on_dry=True)\n","repo_name":"hfrentzel/dotfiles","sub_path":"clis/aws.py","file_name":"aws.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"11294218808","text":"#!/usr/bin/python3\n\nimport sys\n\n'''\nScript spliting multi-sdf file into multiple files\nUSAGE : python split_sdf.py XX.sdf\n'''\n\ndef split_file(sdffile, name):\n\n\tnew_molecule = True\n\tfirst = True\n\tpdblist=[]\n\n\tfor line in sdffile:\n\t\tif new_molecule:\n\t\t\tpdbname = line.strip().split()[0]\n\t\t\tprint(pdbname)\n\t\t\tif not pdbname in pdblist :\n\t\t\t\toutput = open(\"{}.sdf\".format(pdbname),\"w\")\n\t\t\t\tpdblist.append(pdbname)\n\t\t\telse : \n\t\t\t\tocc = pdblist.count(pdbname)\n\t\t\t\toutput = open(\"{}_{}.sdf\".format(pdbname, occ),\"w\")\n\t\t\tnew_molecule = False\n\t\t\t\n\t\toutput.write(line)\n\t\tif line.strip() == \"$$$$\":\n\t\t\tnew_molecule = True\n\t\t\toutput.close()\n\t\t\n\n \nif __name__ == \"__main__\":\n\n if len(sys.argv) < 2:\n sys.exit(\"require two arguments: python split_sdf.py XX.sdf\")\n \n sdfs = open(sys.argv[1],\"r\").readlines()\n name = sys.argv[1].split(\".\")[0]\n split_file(sdfs, name)\n","repo_name":"haddocking/haddocking.github.io","sub_path":"education/HADDOCK24/shape-small-molecule/scripts/split_sdf.py","file_name":"split_sdf.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"44"} +{"seq_id":"74066445891","text":"import serial\nimport uuid\nimport struct\nimport wave\nfrom argparse import ArgumentParser\n\nparser = ArgumentParser()\nparser.add_argument(\"--label\", dest=\"label\", help=\"Label\", type=str, required=True)\nparser.add_argument(\"--port\", dest=\"port\", help=\"Port\", type=str, required=True)\nargs = parser.parse_args()\n\nport = args.port # e.g. /dev/ttyACM0\nlabel = args.label # e.g. red\n\nbaudrate = 115200\nsample_rate = 16000\naudio_len = 1\naudio_ch = 1\nnum_bytes_per_sample = 2\n\nnum_records = 0\nis_recording = False\naudio_buffer = []\nser = serial.Serial()\nser.port = port\nser.baudrate = baudrate\nser.open()\nser.flushInput()\n\nwhile True:\n ser_bytes = ser.readline() # read a '\\n' terminated line\n try:\n sample = int(ser_bytes[0:len(ser_bytes)-1].decode(\"utf-8\"))\n if is_recording == False:\n is_recording = True\n audio_buffer.append(sample)\n except ValueError:\n if is_recording == True:\n is_recording = False\n filename = label + \"_\"+ str(uuid.uuid4()) + \".wav\"\n print(\"Captured audio: [Sample-rate|Num-samples]\", sample_rate, len(audio_buffer))\n audio_obj = wave.open(filename, 'wb')\n audio_obj.setnchannels(audio_ch)\n audio_obj.setframerate(sample_rate)\n audio_obj.setsampwidth(num_bytes_per_sample)\n for sample in audio_buffer:\n sample_bytes = struct.pack(' freq * PARTS[label] and img_hash not in hash_stat))\\\n and compression_rate > 0.05:\n filename = \"{}_{}.png\".format(task_id, count)\n path = os.path.join(DATASETDIR, filename)\n cv2.imwrite(path, image)\n images_to_labels.append(','.join((filename, label)))\n last_hash = img_hash\n hash_stat.add(str(img_hash))\n success, image = vidcap.read()\n img_hash = colorhash(Image.fromarray(image), binbits=7)\n count += 1\n return count, images_to_labels\n\ndef extract_frames(vidcap, frames, destination, width, height):\n success, image = vidcap.read()\n images = []\n frame_id = 0\n for filename, props in frames.items():\n frame = props[\"frame\"]\n image_id = props[\"image_id\"]\n while frame_id < frame:\n success, image = vidcap.read()\n frame_id += 1\n path = os.path.join(destination, filename)\n cv2.imwrite(path, image)\n images.append({\"id\": image_id, \"file_name\": filename, \"width\": width, \"height\": height})\n return images\n\ndef create_coco(pathologies):\n COCO = {\"images\":[],\"annotations\":[],\"categories\": []}\n COCO[\"categories\"].append({\"id\": 0, \"name\": \"Pathology\", \"supercategory\": \"none\"})\n i = 1\n for pathologie in pathologies:\n COCO[\"categories\"].append({\"id\": i, \"name\": pathologie, \"supercategory\": \"Pathology\"})\n i += 1\n return COCO\n\n# url = \"https://api.scale.com/v1/tasks\"\n# headers = {\"Accept\": \"application/json\"}\n# auth = HTTPBasicAuth('test_a02653c3326a4da9bfabb3fadd61873b', '') # No password\n# response = requests.request(\"GET\", url, headers=headers, auth=auth)\n#download batch_file\nURLS = ['https://storage.yandexcloud.net/cvproject/labeled_data/next_ten_x8mio8__.json',\n 'https://storage.yandexcloud.net/cvproject/labeled_data/first10_35gvxn__.json',\n 'https://storage.yandexcloud.net/cvproject/labeled_data/colono2__.json']\nif os.path.isfile(os.path.join(DATASETDIR,'data.json')):\n with open(os.path.join(DATASETDIR,'data.json')) as f:\n data = json.load(f)\nelse:\n data = []\n for url in URLS:\n print(url)\n r = requests.get(url)\n data += r.json()\n\nCOCO = create_coco(PATHOLOGIES)\nNAVIGATION = []\nannotation_id = 0\nimages_with_annotations = 0\nfor video in data:\n try:\n task_id = video[\"task_id\"]\n if task_id not in TASKS:\n continue\n if video.get('completed_at') is None:\n continue\n #download video\n if 'originalUrl' in video['metadata']:\n video_url = video['metadata']['originalUrl']\n videofilename = video_url.split('/')[-1]\n else:\n video_url = video['attachmentS3Downloads'][-1]['s3URL']\n videofilename = video['metadata']['filename']\n meta = video[\"metadata\"][\"video\"]\n width = video[\"metadata\"][\"video\"][\"resolution\"][\"w\"]\n height = video[\"metadata\"][\"video\"][\"resolution\"][\"h\"]\n #r = requests.get(video_url)\n print(videofilename)\n if not os.path.isfile(videofilename):\n print(\"download video\")\n download_file(video_url, videofilename)\n else:\n print(\"video downloaded, skip\")\n response = video[\"response\"]\n #navigation\n if 'data' not in response['events']:\n r = requests.get(response['events']['url'])\n events = r.json()\n response['events']['data'] = events\n else:\n events = response['events']['data']\n start = 0\n label = \"Void\"\n label_ranged = False\n vidcap = cv2.VideoCapture(videofilename)\n for event in events:\n if event[\"label\"] == \"Pathologie\":\n continue\n #print(event)\n if not label_ranged:\n #print(\"{} from {} until {}\".format(label, start, event[\"start\"]))\n start, end = start, event[\"start\"]\n start, images_to_labels = extract_frame(vidcap, start, end, label, task_id)\n NAVIGATION += images_to_labels\n label = event[\"label\"]\n if event[\"type\"] == \"range\":\n #print(\"{} from {} until {}\".format(label, event[\"start\"], event[\"end\"]))\n start, end = event[\"start\"], event[\"end\"]\n start, images_to_labels = extract_frame(vidcap, start, end, label, task_id)\n label_ranged = True\n else:\n label_ranged = False\n NAVIGATION += images_to_labels\n \n #segmentation\n if 'data' not in response['annotations']:\n r = requests.get(response['annotations']['url'])\n annotations = r.json()\n response['annotations']['data'] = annotations\n else:\n annotations = response['annotations']['data']\n frames = {}\n vidcap = cv2.VideoCapture(videofilename)\n for key, annotation in annotations.items():\n imagefilename = \"{}_{}.png\".format(task_id, annotation[\"frames\"][0][\"key\"])\n if imagefilename not in frames:\n frames[imagefilename] = {\n \"image_id\": images_with_annotations,\n \"frame\": annotation[\"frames\"][0][\"key\"]\n }\n images_with_annotations += 1\n obj = {}\n obj[\"id\"] = annotation_id\n obj[\"image_id\"] = frames[imagefilename][\"image_id\"]\n obj[\"category_id\"] = PATHOLOGIES.index(annotation[\"label\"]) + 1\n obj[\"segmentation\"] = [[]]\n for vertice in annotation[\"frames\"][0][\"vertices\"]:\n obj[\"segmentation\"][0] += [vertice[\"x\"],vertice[\"y\"]]\n COCO[\"annotations\"].append(obj)\n annotation_id += 1\n COCO[\"images\"] += extract_frames(vidcap, frames, DATASETDIR, width, height)\n except Exception as e:\n raise\nprint(json.dumps(STAT,indent = 4))\n\n\nwith open(os.path.join(DATASETDIR,\"annotations_coco.json\"),\"w\") as f:\n f.write(json.dumps(COCO, indent = 4))\nwith open(os.path.join(DATASETDIR,\"navigation.csv\"),\"w\") as f:\n f.write('\\n'.join(NAVIGATION))\nwith open(os.path.join(DATASETDIR,\"data.json\"), \"w\") as f:\n f.write(json.dumps(data,indent=4))","repo_name":"rogdenis/GastroNet","sub_path":"parse_scale_labeled_data.py","file_name":"parse_scale_labeled_data.py","file_ext":"py","file_size_in_byte":9123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"24133093855","text":"\"\"\"\nFile: nwlConstructor.py\nDesc:\n 脚本 - 从诗人提及的地点中\n 使用自定义的规则\n 构建地点之间的关联关系\n\"\"\"\n\nimport os\nimport json\nimport settings\nimport networkx as nx\nfrom collections import Counter\nfrom module.ColorLogDecorator import ColorLogDecorator\n\nINPUT_DIR = os.path.join(settings.INPUT_PATH, \"nerResult\")\nOUTPUT_DIR = os.path.join(settings.OUTPUT_PATH, 'networkRaw')\nABS_THRESHOLD = 1\nNUM_THRESHOLD = 10\n\n\ndef __flush_str(msg: str):\n fixed_len = 70\n if len(msg) <= fixed_len:\n return msg.ljust(fixed_len, ' ')\n else:\n return msg[0:fixed_len - 3] + \"...\"\n\n\ndef main():\n ColorLogDecorator.active()\n print(ColorLogDecorator.green(\"- START -\", \"strong\"))\n\n # the data structure\n all_filepath_list = []\n graph = nx.DiGraph()\n\n # step 1: init all file list\n print(ColorLogDecorator.yellow(__flush_str(\"Step 1 - init files list\")), end=\"\")\n for dynasty in os.listdir(INPUT_DIR):\n dynasty_path = os.path.join(INPUT_DIR, dynasty)\n for file in os.listdir(dynasty_path):\n msg = \"Step 1 - init files list: {}\".format(dynasty + \" \" + file)\n msg = __flush_str(msg)\n msg = ColorLogDecorator.yellow(msg)\n print(\"\\r{}\".format(msg), end=\"\")\n\n file_path = os.path.join(dynasty_path, file)\n all_filepath_list.append(file_path)\n all_filepath_list.sort()\n print(\"\\r\" + ColorLogDecorator.yellow(__flush_str(\"Step 1 - init files list: Done\")))\n\n # step 2: construct the network\n print(ColorLogDecorator.yellow(__flush_str(\"Step 2 - construct network\")), end=\"\")\n for index in range(len(all_filepath_list)):\n with open(all_filepath_list[index], 'r+', encoding='utf-8', errors='ignore') as f:\n content = json.load(f)\n\n msg = __flush_str(\"Step 2 - construct network {:.2f}%: handle {}\".format(\n (index + 1) * 100 / len(all_filepath_list),\n all_filepath_list[index]\n ))\n msg = ColorLogDecorator.yellow(msg)\n print(\"\\r{}\".format(msg), end=\"\")\n location_counter = Counter(content[\"location\"])\n location_list = location_counter.most_common()\n for i in range(len(location_list)):\n location1 = location_list[i][0]\n location1_num = location_list[i][1]\n if location1_num <= NUM_THRESHOLD:\n continue\n for j in range(i, len(location_list)):\n if i != j:\n location2 = location_list[j][0]\n location2_num = location_list[j][1]\n if location2_num <= NUM_THRESHOLD:\n continue\n if abs(location1_num - location2_num) <= ABS_THRESHOLD:\n if not graph.has_node(location1):\n graph.add_node(location1)\n if not graph.has_node(location2):\n graph.add_node(location2)\n if location1_num >= location2_num:\n x = location1\n y = location2\n else:\n x = location2\n y = location1\n graph.add_edge(x, y)\n print(\"\\r\" + ColorLogDecorator.yellow(__flush_str(\"Step 2 - construct network: Done\")))\n\n # step 3: the result output\n print(ColorLogDecorator.yellow(\"Step 3 - output data in gexf\"), end=\"\")\n if not os.path.exists(OUTPUT_DIR):\n os.makedirs(OUTPUT_DIR)\n nx.write_gexf(graph, os.path.join(OUTPUT_DIR, \"location.gexf\"))\n print(ColorLogDecorator.yellow(\": Done\"))\n print(ColorLogDecorator.green(\"- ALL DONE -\", \"strong\"))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"sigmarising/poetry-data-network","sub_path":"nwlConstructor.py","file_name":"nwlConstructor.py","file_ext":"py","file_size_in_byte":3755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"11910575817","text":"from gdeck import gdeck\nimport pytest\n\n\ndef test_card():\n card_obj = gdeck.Card(\"Wizard\", \"Oz\")\n assert str(card_obj) == \"Wizard of Oz\"\n\n\ndef test_card_instance():\n card_obj = gdeck.Card(\"Wizard\", \"Oz\")\n assert isinstance(card_obj, gdeck.Card)\n\n\ndef test_deck():\n deck_str = \"[Ace of Diamonds, Ace of Hearts, Ace of Clubs, Ace of Spades,\" \\\n \" 2 of Diamonds, 2 of Hearts, 2 of Clubs, 2 of Spades,\" \\\n \" 3 of Diamonds, 3 of Hearts, 3 of Clubs, 3 of Spades,\" \\\n \" 4 of Diamonds, 4 of Hearts, 4 of Clubs, 4 of Spades,\" \\\n \" 5 of Diamonds, 5 of Hearts, 5 of Clubs, 5 of Spades,\" \\\n \" 6 of Diamonds, 6 of Hearts, 6 of Clubs, 6 of Spades,\" \\\n \" 7 of Diamonds, 7 of Hearts, 7 of Clubs, 7 of Spades,\" \\\n \" 8 of Diamonds, 8 of Hearts, 8 of Clubs, 8 of Spades,\" \\\n \" 9 of Diamonds, 9 of Hearts, 9 of Clubs, 9 of Spades,\" \\\n \" 10 of Diamonds, 10 of Hearts, 10 of Clubs, 10 of Spades,\" \\\n \" Jack of Diamonds, Jack of Hearts, Jack of Clubs, Jack of Spades,\" \\\n \" Queen of Diamonds, Queen of Hearts, Queen of Clubs, Queen of Spades,\" \\\n \" King of Diamonds, King of Hearts, King of Clubs, King of Spades]\"\n deck = gdeck.Deck()\n assert deck_str == str(deck)\n\n\ndef test_deck_instance():\n deck_obj = gdeck.Deck()\n assert isinstance(deck_obj, gdeck.Deck)\n\n\ndef test_deck_iter():\n deck_obj = gdeck.Deck()\n assert isinstance(iter(deck_obj), gdeck.Deck)\n\n\ndef test_deck_len():\n deck_obj = gdeck.Deck()\n assert len(deck_obj) == 52\n\n\ndef test_deck_getitem():\n deck_obj = gdeck.Deck()\n assert str(deck_obj[0:9]) == \"[Ace of Diamonds, Ace of Hearts, Ace of Clubs, Ace of Spades,\" \\\n \" 2 of Diamonds, 2 of Hearts, 2 of Clubs, 2 of Spades, 3 of Diamonds]\"\n\n\ndef test_deck_next():\n with pytest.raises(StopIteration):\n deck_obj = gdeck.Deck()\n for deck in iter(deck_obj):\n next(deck_obj)\n next(deck_obj)\n","repo_name":"CelebradoJonathan/gdeck","sub_path":"tests/test_gdeck.py","file_name":"test_gdeck.py","file_ext":"py","file_size_in_byte":2054,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"74264557572","text":"def solution(fees, records):\r\n answer = []\r\n cars = {}\r\n for r in records:\r\n times, id, inout = r.split()\r\n if id not in cars.keys():\r\n cars[id] = [times]\r\n else:\r\n cars[id].append(times)\r\n\r\n cars_time = {}\r\n for c in cars.keys():\r\n cars_time[c] = 0\r\n lst = cars[c]\r\n if len(lst) % 2 == 1:\r\n lst.append(\"23:59\")\r\n for i in range(0, len(lst), 2):\r\n h, m = lst[i].split(\":\")\r\n hh, mm = lst[i + 1].split(\":\")\r\n in_time = int(h) * 60 + int(m)\r\n out_time = int(hh) * 60 + int(mm)\r\n cars_time[c] += (out_time - in_time)\r\n\r\n result = []\r\n for ct in cars_time.keys():\r\n money = 0\r\n if cars_time[ct] < fees[0]:\r\n money = fees[1]\r\n else:\r\n money = fees[1]\r\n cars_time[ct] -= fees[0]\r\n if cars_time[ct] % fees[2] > 0:\r\n money += (cars_time[ct] // fees[2] + 1) * fees[3]\r\n else:\r\n money += (cars_time[ct] // fees[2]) * fees[3]\r\n result.append([ct, money])\r\n\r\n result.sort(key=lambda x: x[0])\r\n for r in result:\r\n answer.append(r[1])\r\n return answer","repo_name":"aeriheo/Problem-Solving","sub_path":"220525/Programmers_92341.py","file_name":"Programmers_92341.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"71914067333","text":"# importing the Kratos Library\nimport KratosMultiphysics\nimport KratosMultiphysics.SolidMechanicsApplication as KratosSolid\nimport KratosMultiphysics.PfemSolidMechanicsApplication as KratosPFEMSolid\nimport KratosMultiphysics.ContactMechanicsApplication as KratosContact\n\nimport os.path\n\nimport numpy as np\n\ndef Factory( custom_settings, Model):\n if(type(custom_settings) != KratosMultiphysics.Parameters):\n raise Exception(\"expected input shall be a Parameters object, encapsulating a json string\")\n return ConePenetrationUtility(Model, custom_settings[\"Parameters\"])\n\n\nclass ConePenetrationUtility(KratosMultiphysics.Process):\n #\n\n def __init__(self, model_part, custom_settings):\n\n KratosMultiphysics.Process.__init__(self)\n\n\n ##settings string in json format\n default_settings = KratosMultiphysics.Parameters(\"\"\"\n {\n \"cone_radius\" : 0.01784,\n \"u2_initial_depth\" : 0.0332,\n \"velocity\" : 0.02,\n \"dissipation_set\" : false,\n \"dissipation_depth\" : 0.2676\n }\n \"\"\")\n\n settings = custom_settings\n settings.ValidateAndAssignDefaults(default_settings)\n\n self.model_part = model_part['Main_Domain']\n\n self.Y0 = settings[\"u2_initial_depth\"].GetDouble()\n self.Vy = settings[\"velocity\"].GetDouble()\n self.radius = settings[\"cone_radius\"].GetDouble()\n\n self.dissipation_set = settings[\"dissipation_set\"].GetBool()\n if ( self.dissipation_set):\n self.dissipation_depth = settings[\"dissipation_depth\"].GetDouble()\n\n\n problem_path = os.getcwd()\n self.figure_path = os.path.join(problem_path, \"cone_penetration_data.csv\")\n\n\n def ExecuteBeforeOutputStep(self):\n\n delta_time = self.model_part.ProcessInfo[KratosMultiphysics.DELTA_TIME]\n\n\n for node in self.model_part.GetNodes(0):\n delta_disp = node.GetSolutionStepValue(KratosMultiphysics.DISPLACEMENT)\n delta_disp = delta_disp - node.GetSolutionStepValue(KratosMultiphysics.DISPLACEMENT, 1)\n for ii in range(0,2):\n delta_disp[ii] = delta_disp[ii] / delta_time\n if (node.SolutionStepsDataHas(KratosMultiphysics.VELOCITY)):\n node.SetSolutionStepValue(KratosMultiphysics.VELOCITY, delta_disp)\n\n def ExecuteAfterOutputStep(self):\n\n\n for node in self.model_part.GetNodes(0):\n if ( node.SolutionStepsDataHas( KratosMultiphysics.CONTACT_FORCE)):\n CF = node.GetSolutionStepValue(KratosMultiphysics.CONTACT_FORCE)\n CF = 0.0*CF\n node.SetSolutionStepValue( KratosMultiphysics.CONTACT_FORCE, CF)\n\n if ( node.SolutionStepsDataHas( KratosContact.CONTACT_STRESS)):\n CF = node.GetSolutionStepValue( KratosContact.CONTACT_STRESS)\n CF = 0.0*CF\n node.SetSolutionStepValue( KratosContact.CONTACT_STRESS, CF)\n\n\n if ( node.SolutionStepsDataHas( KratosContact.EFFECTIVE_CONTACT_FORCE)):\n CF = node.GetSolutionStepValue( KratosContact.EFFECTIVE_CONTACT_FORCE)\n CF = 0.0*CF\n node.SetSolutionStepValue( KratosContact.EFFECTIVE_CONTACT_FORCE, CF)\n\n if ( node.SolutionStepsDataHas( KratosContact.EFFECTIVE_CONTACT_STRESS)):\n CF = node.GetSolutionStepValue( KratosContact.EFFECTIVE_CONTACT_STRESS)\n CF = 0.0*CF\n node.SetSolutionStepValue( KratosContact.EFFECTIVE_CONTACT_STRESS, CF)\n\n if ( node.SolutionStepsDataHas( KratosSolid.DISPLACEMENT_REACTION)):\n #print(node)\n for step in range(0,2):\n CF = node.GetSolutionStepValue( KratosSolid.DISPLACEMENT_REACTION, step)\n normal = node.GetSolutionStepValue( KratosMultiphysics.NORMAL, step);\n #print('NODE', node.Id, ' normal', normal)\n #print(' step ', step, 'REACTION', CF)\n CF = 0.0*CF\n #print(' step ', step, 'REACTION', CF)\n node.SetSolutionStepValue( KratosSolid.DISPLACEMENT_REACTION, step, CF)\n #print('----------')\n\n #\n def ExecuteFinalizeSolutionStep(self):\n\n Q = self._GetResistance();\n Friction = self._GetFriction();\n\n U22 = self._GetPorePressureU2();\n U33 = self._GetPorePressureU3()\n U11 = self._GetPorePressureU1();\n\n time = self._GetStepTime(); # - self.GetStepDeltaTime();\n\n line_value = str(time) + \" , \" + str(Q) + \" , \" + str(Friction) + \" , \" + str(U22) + \" , \" + str(U11) + \" , \" + str(U33) + \" \\n\"\n\n figure_file = open(self.figure_path, \"a\")\n figure_file.write(line_value)\n figure_file.close()\n\n self.MakeTheOtherFile();\n\n # make the other stupid file just to check everything is sort of correct\n def MakeTheOtherFile(self):\n\n time = self._GetStepTime()\n\n problem_path = os.getcwd()\n self.other_file = os.path.join(problem_path, \"other_file_data.csv\")\n self.other_file = open( self.other_file, \"a\")\n\n time = str(time) + \" \\n \"\n self.other_file.write(time)\n\n\n\n YLim = self.Y0 - self.Vy * self._GetStepTime();\n YLim = self._GetU2Position()\n\n for node in self.model_part.GetNodes(0):\n Force = node.GetSolutionStepValue( KratosMultiphysics.CONTACT_FORCE);\n if ( ( abs(Force[0]) + abs(Force[1]) > 1.0e-7 ) or (node.X0 < 1e-5 and node.Y > YLim-0.1) ) :\n x = node.X;\n y = node.Y;\n Force = node.GetSolutionStepValue( KratosMultiphysics.CONTACT_FORCE);\n Stress = node.GetSolutionStepValue( KratosContact.CONTACT_STRESS);\n EfForce = node.GetSolutionStepValue( KratosContact.EFFECTIVE_CONTACT_FORCE);\n EfStress = node.GetSolutionStepValue( KratosContact.EFFECTIVE_CONTACT_STRESS);\n WP = node.GetSolutionStepValue( KratosMultiphysics.WATER_PRESSURE);\n\n line = str(x) + \" \" + str(y) + \" \" + str(YLim) + \" \" + str(WP) + \" \"\n line = line + self.AddVector( Force)\n line = line + self.AddVector( Stress)\n line = line + self.AddVector( EfForce)\n line = line + self.AddVector( EfStress)\n line = line + \"\\n\"\n self.other_file.write(line)\n\n\n self.other_file.close()\n\n def AddVector( self, vector):\n line = str(vector[0]) + \" \" + str(vector[1]) + \" \"\n return line\n #\n def _GetStepTime(self):\n\n return self.model_part.ProcessInfo[KratosMultiphysics.TIME]\n\n #\n def _GetStepDeltaTime(self):\n\n return self.model_part.ProcessInfo[KratosMultiphysics.DELTA_TIME]\n\n def _GetU2Position(self):\n avance = self.Vy*self._GetStepTime()\n if ( self.dissipation_set):\n if ( avance > self.dissipation_depth):\n avance = self.dissipation_depth\n YSearch = self.Y0 - avance;\n return YSearch\n\n\n def _GetPorePressureU2(self):\n YSearch = self._GetU2Position()\n U22 = self._GetPorePressureShaft( YSearch)\n return U22\n\n def _GetPorePressureU3(self):\n YSearch = self._GetU2Position()\n YSearch = YSearch + 7.5*self.radius\n U33 = self._GetPorePressureShaft( YSearch )\n return U33\n\n def _GetPorePressureU1(self):\n YSearch = self._GetU2Position()\n YSearch = YSearch - self.radius / np.tan(30.0*3.14159/180.0)/2.0\n U11 = self._GetPorePressureShaft( YSearch )\n return U11\n\n\n def _GetResistance(self):\n result = 0.0;\n YLim = self.Y0 - self.Vy * self._GetStepTime();\n YLim = self._GetU2Position()\n for node in self.model_part.GetNodes(0):\n if ( node.Y < YLim):\n Force = node.GetSolutionStepValue( KratosMultiphysics.CONTACT_FORCE);\n result = result + Force[1];\n\n return result;\n\n #\n def _GetFriction(self):\n result = 0;\n YMin = self._GetU2Position()\n YMax = YMin + 7.5*self.radius;\n\n for node in self.model_part.GetNodes(0):\n if (node.Y >= YMin):\n if (node.Y <= YMax):\n Force = node.GetSolutionStepValue( KratosMultiphysics.CONTACT_FORCE);\n result = result + Force[1];\n\n return result;\n\n\n def _GetPorePressureShaft(self, YSearch):\n\n nodes = self.model_part.GetNodes();\n if ( nodes[3].HasDofFor( KratosMultiphysics.WATER_PRESSURE) ):\n variable = KratosMultiphysics.WATER_PRESSURE;\n elif (nodes[3].HasDofFor( KratosMultiphysics.PRESSURE ) ):\n variable = KratosMultiphysics.PRESSURE;\n else:\n return 0.0;\n\n YBestTop = 100000000;\n YBestBottom = -100000000;\n nBestTop = -100;\n nBestBottom = -100;\n\n for node in self.model_part.GetNodes(0):\n Force = node.GetSolutionStepValue( KratosMultiphysics.CONTACT_FORCE);\n condition1 = abs(Force[0]) + abs(Force[1]) > 1e-8;\n Normal = node.GetSolutionStepValue( KratosMultiphysics.NORMAL);\n condition2 = ( abs(Normal[0]) + abs(Normal[1]) > 1e-8 and node.X < 3*self.radius);\n condition3 = abs( node.GetSolutionStepValue(variable)) > 1e-8\n condition3 = node.Is(KratosMultiphysics.RIGID) == False\n if ( ( condition1 or condition2) and condition3):\n YThis = node.Y;\n if ( (YThis-YSearch) > 0 ):\n if ( abs( YThis-YSearch ) < abs( YBestTop - YSearch) ):\n nBestTop = node.Id;\n YBestTop = YThis;\n elif ( (YThis-YSearch) <= 0):\n if ( abs( YThis-YSearch) < abs( YBestBottom - YSearch) ):\n nBestBottom = node.Id\n YBestBottom = YThis;\n\n if ( (nBestTop < 1) or (nBestBottom < 1) ):\n print( ' In the Usomething. NotFound Contacting nodes that are in the range of this kind of thing')\n return 0.0\n\n # Now i want to kwnow if there is an element that has these nodes\n ReallyFound = False;\n for elem in self.model_part.GetElements(0):\n a = [1, 2, 3]\n conec = [];\n found = 0\n for thisNodeGeom in elem.GetNodes():\n thisNode = thisNodeGeom.Id\n if (thisNode == nBestTop):\n found = found + 1\n if (thisNode == nBestBottom ):\n found = found + 1\n if ( found == 2):\n ReallyFound = True;\n break\n\n if ( ReallyFound == False):\n print( ' In the U Something. The two nodes do not share an element ')\n return 0.0\n\n DeltaY = abs(YBestBottom - YBestTop);\n NTop = 1- abs(YBestTop -YSearch) / DeltaY;\n NBottom = 1 - NTop;\n\n if (NTop > 1.0 or NTop < 0):\n print( 'ULTRA MEGA STUPID ERROR ')\n\n if (NBottom > 1.0 or NBottom < 0):\n print( 'ULTRA MEGA STUPID ERROR ')\n\n\n uBottom = nodes[nBestBottom].GetSolutionStepValue(variable);\n uTop = nodes[nBestTop].GetSolutionStepValue(variable);\n ThisV = NTop*uTop + NBottom*uBottom;\n return ThisV;\n\n","repo_name":"KratosMultiphysics/Kratos","sub_path":"applications/PfemSolidMechanicsApplication/python_scripts/cone_penetration_utility.py","file_name":"cone_penetration_utility.py","file_ext":"py","file_size_in_byte":11331,"program_lang":"python","lang":"en","doc_type":"code","stars":906,"dataset":"github-code","pt":"44"} +{"seq_id":"23326707261","text":"'''\nCreated on 07 apr 2017\n\n@author: jimmijamma\n'''\n\nfrom praat import praatUtil as praat\nfrom numpy import mean\n\ndef hnr_main(filePath):\n \n readProgress = 0.01\n acFreqMin = 60\n voicingThreshold = 0.1\n numPeriodsPerWindow = 4.5\n tStart = None\n tEnd = None\n outputFileName = None\n \n offsets, hnrs = praat.calculateHNR(filePath,readProgress,acFreqMin,voicingThreshold,numPeriodsPerWindow,tStart,tEnd,outputFileName)\n \n hnrs=list(hnrs)\n hnrs_2=[]\n for h in hnrs:\n if h is not None:\n hnrs_2.append(h)\n HNR = mean(hnrs_2)\n \n return HNR","repo_name":"Jimmijamma/ParkinsonApp","sub_path":"signalProcessing/hnr.py","file_name":"hnr.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"25562549262","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.arange(0, 255)\nx = x.reshape((len(x), 1))\n\nbuf = np.arange(240, -1, -40).tolist()\nyticks_range = [255]\nfor i in buf:\n yticks_range.append(i)\n\n# min = max\nt_d = 1.00855*np.exp(-0.121779-0.003764*x)\nt_h = 1-0.003725*x\n\nplt.figure()\nplt.title(\"when max = min\")\nplt.plot(t_d, 'r')\nplt.plot(t_h, 'k')\nplt.legend([\"cap\", \"dcp\"])\nplt.show()\n\nsky = np.arange(255, 199, -1)\nsky = sky.reshape((len(sky), 1))\nr_sky = sky\natm = 255\nfor t in np.arange(0.1, 1.1, 0.01):\n buf = np.maximum(np.minimum((sky-atm)/t+atm, 255), 0)\n if r_sky is None:\n r_sky = buf\n else:\n r_sky = np.hstack((r_sky, buf))\nplt.figure()\n#plt.subplot(1, 2, 1)\n#plt.imshow(sky/255, cmap=\"gray\")\n#plt.yticks([0, 20, 40, 55], [255, 235, 215, 200])\n#plt.xticks([])\n#plt.subplot(1, 2, 2)\nplt.imshow(r_sky, vmin=0, cmap=\"gray\")\nplt.title(\"recovered intensity, A=\"+str(atm))\nplt.ylabel(\"original intensity\")\nplt.yticks([0, 20, 40, 55], [255, 235, 215, 200])\nplt.xlabel(\"transmission\")\nplt.xticks([1, 21, 41, 61, 81, 100], [0.1, 0.2, 0.4, 0.6, 0.8, 1.0])\nplt.show()\n\n\n# min = 0\nt_d, t_h = None, None\nfor alpha in np.arange(0, 1.005, 0.005):\n buf = np.minimum(1.00855 * np.exp(0.658466 - 0.003764 * x - 0.780245 * alpha), 1)\n if t_d is None:\n t_d = buf\n else:\n t_d = np.hstack((t_d, buf))\n buf = 1-0.003725*alpha*x\n if t_h is None:\n t_h = buf\n else:\n t_h = np.hstack((t_h, buf))\n\nplt.figure()\nplt.title(\"cap transmission\")\nplt.imshow(t_d, cmap=\"gray\")\nplt.ylabel(\"max component\")\nplt.yticks(yticks_range)\nplt.xlabel(\"min/max ratio\")\nplt.xticks([0, 40, 80, 120, 160, 200], [0, 0.2, 0.4, 0.6, 0.8, 1.0])\nplt.show()\n\nplt.figure()\nplt.imshow(t_h, cmap=\"gray\")\nplt.title(\"dcp transmission\")\nplt.ylabel(\"max component\")\nplt.yticks(yticks_range)\nplt.xlabel(\"min/max ratio\")\nplt.xticks([0, 40, 80, 120, 160, 200], [0, 0.2, 0.4, 0.6, 0.8, 1.0])\nplt.show()\n","repo_name":"SwimilTylers/dehaze-dcp-cap","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"25241527180","text":"class Example:\n \"A basic example class that returns a function object\"\n def b(self):\n return \"this is an example class\"\n\nc = Example()\n\n\nclass Square:\n def __init__(self, length, width):\n self.length = length\n self.width = width\n def area(self):\n return self.width * self.length\nr = Square(20, 2000)\nprint(\"Rectangle Area: %d\" % (r.area()))\n\n\nclass PartsColor:\n \"Creates a class\"\n def __init__(self):\n \"Create a new color for each part\"\n self.hood = \"Blue\"\n self.wheels = \"Red\"\n self.doors = \"Green\"\ne = PartsColor() # Instantiate two objects to represent points\nf = PartsColor()\n\nprint(e.hood, f.wheels, e.hood, f.wheels, e.doors, f.doors) # Assign each point a unique location\n###","repo_name":"Dingus94/MyCookbook","sub_path":"classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"17957763247","text":"\"\"\" En este archivo se escribiran los parametros a utilizar en la tarea 1\"\"\"\n\n### Parametros para leer los archivos ###\n\n# Lectura del archivo tributos\nRUTA_TRIBUTOS = \"tributos.csv\"\n\n# Lectura del archivo ambientes\nRUTA_AMBIENTES = \"ambientes.csv\"\n\n# Lectura del archivo objetos\nRUTA_OBJETOS = \"objetos.csv\"\n\n# Lectura del archivo arenas\nRUTA_ARENAS = \"arenas.csv\"\n\n### Parametros de la simulación de la hora ###\n\n# Gasto de energía al realizar la acción heroica\nENERGIA_ACCION_HEROICA = 15\n\n# Popularidad ganada al realizar la accion heroica\nPOPULARIDAD_ACCION_HEROICA = 3\n\n# Gasto de energía al atacar a un tributo\nENERGIA_ATACAR = 20\n\n# Popularidad ganada al matar a otro tributo\nPOPULARIDAD_ATACAR = 5\n\n# Popularidad gastada para obtener un objeto aleatorio\nPOPULARIDAD_PEDIR = 3\n\n# Energía ganada al hacerse bolita\nENERGIA_BOLITA = 10\n\n\n### Parametros entidad Tributo ###\n\n# Costo de popularidad al pedir un objeto aleatorio\nCOSTO_OBJETO = 3\n\n### Parametros entidad Ambiente ###\n\n# Daño que realiza el viento en el ambiente Playa\nVELOCIDAD_VIENTOS_PLAYA = 20.0\n\n# Daño que realiza la humedad en el ambiente Playa\nHUMEDAD_PLAYA = 18.0\n\n# Daño que realiza la nubosidad en el ambiente Montaña\nNUBOSIDAD_MONTANA = 9.0\n\n# Daño que realiza las precipitaciones en el ambiente Montaña\nPRECIPITACIONES_MONTANA = 21.0\n\n# Daño que realizan las precipitaciones en el ambiente Bosque\nPRECIPITACIONES_BOSQUE = 17.0\n\n# Daño que realizan los vientos en el ambiente Bosque\nVELOCIDAD_VIENTOS_BOSQUE = 4.0\n\n\n### Parametros entidad Objeto###\n\n# Cantidad de energía que puede aumentar un objeto consumible\nAUMENTAR_ENERGIA = 15\n\n# Ponderador para aumentar la fuerza de un tributo a traves de un objeto Arma\nPONDERADOR_AUMENTAR_FUERZA = 3\n\n# Aumento de agilidad que puede realizar un objeto especial\nAUMENTAR_AGILIDAD = 4\n\n# Aumento de ingenio que puede realizar un objeto especial\nAUMENTAR_INGENIO = 4\n\n\n### Parametros entidad Arena###\n\n# Probabilidad de evento\nPROBABILIDAD_EVENTO = 1","repo_name":"antoniablanco/Programacion_avanzada_2021-02","sub_path":"Tareas/T1/parametros.py","file_name":"parametros.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"26420492306","text":"import os\nimport pickle\nimport random\nimport sys\nfrom collections import defaultdict\nfrom copy import deepcopy\n\nimport numpy as np\nfrom sklearn.decomposition import PCA\nfrom tqdm import tqdm\n\nsys.path.append(\"..\")\nfrom toputils import *\n\ntgttop, _, config = read_config()\nF_DIM = 64 if tgttop == \"sz3rd\" else 256\nPCA_DIM = config[\"pca\"]\nNN = 4 # 内存原因, 分批处理\ninput_path = \"../dataset/\" + config[\"dataset\"][\"record\"]\ncamera_path = f\"../data_interface/r2cameras_{tgttop}.pkl\"\nrandom.seed(233)\n\ndef records_pca(records, k, inplace=True):\n if not inplace:\n records = deepcopy(records)\n car_f = np.array([i[4] for i in records])\n plate_f = np.array([i[5] for i in records if i[5] is not None])\n car_f = PCA(k).fit_transform(car_f)\n if plate_f.size > 0:\n plate_f = PCA(k).fit_transform(plate_f)\n j = 0\n for i, r in enumerate(records):\n r[4] = car_f[i]\n if r[5] is not None:\n r[5] = plate_f[j]\n j += 1\n return records\n\n\ndef rearrange_records(records):\n records_wt_pf = [r for r in records if r[5] is not None]\n print(\"with plate feature:\", len(records_wt_pf))\n records = [r for r in records if r[5] is None]\n print(\"without plate feature:\", len(records))\n random.shuffle(records_wt_pf)\n random.shuffle(records)\n return records_wt_pf + records\n\n\ndef main():\n r2cids = {r: set(c[\"id\"] for c in cams) for r, cams in pickle.load(open(camera_path, \"rb\")).items()}\n cids_all = set().union(*r2cids.values())\n print(\"input cameras:\", len(cids_all))\n\n for nn in range(NN):\n print(\"part:\", nn)\n cache_path = f\"data/cid2records_{tgttop}_part{nn}.pkl\"\n if os.path.exists(cache_path):\n cid2records = pickle.load(open(cache_path, \"rb\"))\n else:\n print(\"Loading records...\")\n records = np.load(input_path)[\"arr_0\"]\n print(\"input shape:\", records.shape)\n assert records.shape[1] == 2*F_DIM + 4\n N = int(len(records) / NN)\n records = records[nn*N: (nn+1)*N if nn < NN-1 else len(records)]\n cid2records = defaultdict(list)\n for r in tqdm(records): \n if int(r[2]) in cids_all:\n rid = int(r[0])\n vid = None if int(r[1]) == -1 else int(r[1])\n cid = int(r[2])\n t = int(r[3])\n cf = np.asarray(r[4:4+F_DIM])\n pf = None if np.all(r[4+F_DIM:]==0) else np.asarray(r[4+F_DIM:])\n assert len(r) == 2*F_DIM + 4\n cid2records[cid].append([rid, vid, cid, t, cf, pf])\n del records\n pickle.dump(cid2records, open(cache_path, \"wb\"))\n\n print(\"camera with records:\", len(cid2records))\n\n for r, cids in r2cids.items():\n print(r)\n rcds = [rcd for cid in cids for rcd in cid2records.get(cid, [])]\n print(\"in region records:\", len(rcds))\n pickle.dump(rcds, open(f\"data/records_{tgttop}_{r}_part{nn}.pkl\", \"wb\"))\n del cid2records\n \n print(\"Merging part results, PCA, Rearrange...\")\n keys = [\"id\", \"vehicle_id\", \"camera_id\", \"time\", \"car_feature\", \"plate_feature\"]\n for r in config[\"regions\"]:\n print(r)\n rcds = []\n for nn in range(NN):\n rcds += pickle.load(open(f\"data/records_{tgttop}_{r}_part{nn}.pkl\", \"rb\"))\n if F_DIM > PCA_DIM:\n print(\"Saving nopca result0...\")\n pickle.dump(rcds, open(f\"../data_interface/records_nopca_{tgttop}_{r}.pkl\", \"wb\"))\n print(\"PCA...\")\n rcds = records_pca(rcds, PCA_DIM, inplace=True)\n rcds = rearrange_records(rcds)\n rcds = [{k: v for k, v in zip(keys, x)} for x in rcds]\n print(\"Saving result...\")\n pickle.dump(rcds, open(f\"../data_interface/records_pca_{config['pca']}_{tgttop}_{r}.pkl\", \"wb\"))\n\n print(\"record num:\", len(rcds))\n \n gt_cnt = 0\n gt_id = set()\n for x in rcds:\n if x[\"vehicle_id\"]:\n gt_cnt += 1\n gt_id.add(x[\"vehicle_id\"])\n print(\"gt_cnt:\", gt_cnt)\n print(\"get id cnt:\", len(gt_id))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"tsinghua-fib-lab/City-Camera-Trajectory-Data","sub_path":"code/record_loader/read_record.py","file_name":"read_record.py","file_ext":"py","file_size_in_byte":4239,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"44"} +{"seq_id":"8772524045","text":"\n# http://www.usaco.org/index.php?page=viewproblem2&cpid=923\n\nn, k = map(int, input().split())\nplants = []\nfor i in range(n):\n d, w = map(int, input().split())\n plants.append((d, w))\nplants.sort()\n\ntrips = 0\nwater = k\ni = 0\nwhile i < n:\n d, w = plants[i]\n if water < w:\n # refill the watering can\n j = i - 1\n while j >= 0 and plants[j][1] < water:\n j -= 1\n if j < 0:\n # cannot water all the plants\n trips = -1\n break\n refill_d, refill_w = plants[j]\n trips += 1\n water = k - (refill_w - water)\n i = j + 1\n else:\n # water the current plant\n water -= w\n i += 1\n\nif trips >= 0:\n # watered all the plants\n print(trips)\nelse:\n # could not water all the plants\n print(-1)\n\n\n # minimizes number of trips cuz plants are already sorted by distance","repo_name":"nngngn/usaco-solutions","sub_path":"python/watering_plants.py","file_name":"watering_plants.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"22229154890","text":"from typing import Dict, List, Any, Tuple\n\nimport pandas as pd\nfrom sklearn.model_selection import ParameterGrid\nfrom sklearn.preprocessing import LabelEncoder\n\nfrom src.data.objects.stack import Stack\nfrom src.evaluation.metrics import acc_top_k\nfrom src.models.encoders.base import UnsupFeatures\nfrom src.utils import set_seed\n\n\ndef choose_non_empty_stacks(stacks: List[List[float]], fixers: List[int]) -> \\\n Tuple[List[List[float]], List[int]]:\n new_stacks, new_fixers = [], []\n\n for stack, fixer in zip(stacks, fixers):\n if len(stack) > 0:\n new_stacks.append(stack)\n new_fixers.append(fixer)\n\n return new_stacks, new_fixers\n\n\nclass ClassificationGridSearch:\n def __init__(self, model_ctor, params: Dict[str, List[Any]], encoder: UnsupFeatures):\n self._model_ctor = model_ctor\n self._param_grid = list(ParameterGrid(params))\n self._encoder = encoder\n self._label_encoder = LabelEncoder()\n self._scores = []\n\n def estimate_params(self, train_stacks: List[Stack], val_stacks: List[Stack],\n y_train: List[int], y_val: List[int]) -> \"ClassificationGridSearch\":\n self._scores = []\n train_stacks_coded = self._encoder.fit(train_stacks).transform(train_stacks)\n y_train_coded = self._label_encoder.fit_transform(y_train)\n\n val_stacks_coded, y_val_coded = [], []\n for stack, y in zip(val_stacks, y_val):\n if y in self._label_encoder.classes_:\n val_stacks_coded.append(self._encoder.transform([stack])[0])\n y_val_coded.append(self._label_encoder.transform([y])[0])\n\n print(f\"Train {len(train_stacks)} | Val {len(val_stacks)} | Filtered Val {len(val_stacks_coded)}\")\n k = len(val_stacks_coded) / len(val_stacks)\n print(f\"Normalized coeff: {round(k, 2)}\")\n\n for params in self._param_grid:\n set_seed()\n model = self._model_ctor(**params)\n model.fit(train_stacks_coded, y_train_coded)\n train_scores = acc_top_k(y_train_coded, model.predict_proba(train_stacks_coded), [1, 2, 3, 5, 10])\n val_scores = acc_top_k(y_val_coded, model.predict_proba(val_stacks_coded), [1, 2, 3, 5, 10])\n val_scores = [k * score for score in val_scores]\n\n print(f\"Params {params}\")\n print(f\"Train score {[round(score, 2) for score in train_scores]} | \"\n f\"Val score {[round(score, 2) for score in val_scores]}\")\n\n self._scores.append((params,\n [round(score, 2) for score in train_scores],\n [round(score, 2) for score in val_scores]))\n\n return self\n\n def save_results(self, file_path: str):\n df = pd.DataFrame(self._scores, columns=[\"Params\", \"Train\", \"Val\"])\n df.to_csv(file_path, index=False)\n\n","repo_name":"Sushentsev/DapStep","sub_path":"src/model_selection/grid_search.py","file_name":"grid_search.py","file_ext":"py","file_size_in_byte":2878,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"44"} +{"seq_id":"71884672453","text":"\"\"\"\r\nAin Shams University\r\nMechatronics & Automation Engineering\r\nCSE 489: Machine Vision\r\nAuthor: Ahmad Samy Shafiek - 16P9051\r\n Ahmad Tarek Shams - 16P8185\r\n Hadi Badr - 16P8216\r\n Mohamed Ayman Salah - 16P8203\r\nLibrary for image segmentation using classical methods\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport cv2\r\nimport math\r\nfrom sklearn import svm\r\n\r\n\r\ndef k_nearest_neighbor(image_path: str, k: int = 1):\r\n \"\"\"\r\n K-Nearest Neighbour Algorithm for image segmentation. Using k=1 (which is default value), yields\r\n \"Nearest-Neighbour\" classfication algorithm. Output is saved on local disk.\r\n :param image_path: path to image.\r\n :param k: Number of nearest neighbours.\r\n \"\"\"\r\n n_regions = 2 # NUMBER OF REGIONS\r\n if not k % 2:\r\n print(\"K cannot be even. K-Nearest Neighbour Algorithm Aborted.\")\r\n return 0\r\n img_raw = cv2.imread(image_path)\r\n # cv2.imshow(\"IMAGE #\" + image_path[14:-4] , img_raw)\r\n # cv2.waitKey(0)\r\n # cv2.destroyAllWindows()\r\n mean_arr = np.zeros((1, 4)) # ARRAY TO STORE MEAN RGB OF EACH BOX\r\n for label_id in range(0, n_regions):\r\n print(\"Label Region #\" + str(label_id))\r\n while True:\r\n boundingBoxes = cv2.selectROIs(\"LABEL REGION #\" + str(label_id), img_raw)\r\n if isinstance(boundingBoxes, tuple): # MAKING SURE A AT LEAST ONE BOX WAS LABELED\r\n print(\"No Region Selected. Please select Region #\" + str(label_id))\r\n else:\r\n print(\"Region \" + str(label_id) + \" labeled\")\r\n cv2.destroyAllWindows()\r\n break\r\n\r\n for row in boundingBoxes:\r\n x1 = row[0]\r\n y1 = row[1]\r\n x2 = row[2]\r\n y2 = row[3]\r\n img_crop = img_raw[y1:y1 + y2, x1:x1 + x2]\r\n mean_vector = np.mean(img_crop, axis=(0, 1))\r\n mean_vector = np.append(mean_vector, label_id).reshape(1, 4)\r\n mean_arr = np.concatenate((mean_arr, mean_vector))\r\n mean_arr = np.delete(mean_arr, 0, 0) # REMOVING FIRST ROW CONTAINING ZEROS DUE TO INITIALIZATION\r\n if k > 1: # IF K>1, CAUSE CLASSIFICATION ALGORITHM TO PERFORM NN AND KNN\r\n k_list = [1, k]\r\n else: # IF K=1, CAUSE ALGORITHM TO PERFORM NN ONLY\r\n k_list = 1\r\n\r\n for k_iter in k_list:\r\n segmented_img = np.zeros((img_raw.shape[0], img_raw.shape[1]))\r\n segmented_img_rgb = np.zeros_like(img_raw)\r\n c_rgb_sum = np.zeros((n_regions, 3))\r\n c_dist = np.zeros(n_regions) # distribution of classes after classes\r\n c_rgb = np.zeros_like(c_rgb_sum)\r\n for row in range(0, img_raw.shape[0]):\r\n for col in range(0, img_raw.shape[1]):\r\n dist = np.linalg.norm((mean_arr[:, :3]-img_raw[row, col]), axis=1) # DISTANCE TO FIRST RECTANGLE\r\n min_idx = dist.argsort()[:k_iter] # RETRIEVES INDICES OF LOWEST K DISTANCES\r\n neighbor_labels = mean_arr[min_idx, 3] # CREATES A VECTOR OF THE LABELS OF K LOWEST DISTANCES\r\n segmented_img[row, col] = \\\r\n np.bincount(neighbor_labels.astype(int)).argmax() # MOST FREQUENT LABEL IS INSERTED\r\n for label_id in range(0, n_regions):\r\n if segmented_img[row, col] == label_id:\r\n c_rgb_sum[label_id] = c_rgb_sum[label_id] + img_raw[row, col]\r\n c_dist[label_id] = c_dist[label_id] + 1\r\n\r\n for label_id in range(0, n_regions):\r\n c_rgb[label_id] = c_rgb_sum[label_id] / c_dist[label_id]\r\n\r\n for row in range(img_raw.shape[0]):\r\n for col in range(img_raw.shape[1]):\r\n for label_id in range(0, n_regions):\r\n if segmented_img[row, col] == label_id:\r\n segmented_img_rgb[row, col] = c_rgb[label_id]\r\n\r\n for label_id in range(0, n_regions):\r\n c_rgb[label_id] = c_rgb_sum[label_id] / c_dist[label_id]\r\n\r\n cv2.imshow(\"Original Image\", img_raw)\r\n cv2.imshow(\"Segmented Image\", segmented_img_rgb)\r\n cv2.imwrite(image_path[:-4] + \"_\" + str(k_iter) + \"nn.jpg\", segmented_img_rgb)\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()\r\n\r\n\r\ndef cm_cluster(image_path: str, epochs_limit: int = 20):\r\n \"\"\"\r\n C-means clustering classification algorithm for image segmentation. Output is saved on local disk.\r\n This implementation segments to two classes only.\r\n :param image_path: Path to image relative to .py file including image name.\r\n :param epochs_limit: Maximum number of iterations.\r\n \"\"\"\r\n img_raw = cv2.imread(image_path)\r\n class_rgb = np.random.randint(size=(2,3), high=255, low=0)\r\n for n in range(epochs_limit):\r\n c0_dist = np.linalg.norm(img_raw - class_rgb[0], axis=2)\r\n c1_dist = np.linalg.norm(img_raw - class_rgb[1], axis=2)\r\n segmented_img = np.zeros((img_raw.shape[0], img_raw.shape[1]))\r\n c_sum = np.zeros((2, 3))\r\n class_dist = np.zeros(2)\r\n for row in range(img_raw.shape[0]):\r\n for col in range(img_raw.shape[1]):\r\n if c0_dist[row][col] < c1_dist[row][col]:\r\n segmented_img[row][col] = 0\r\n c_sum[0] = c_sum[0] + img_raw[row][col]\r\n class_dist[0] = class_dist[0] + 1\r\n else:\r\n segmented_img[row][col] = 255\r\n c_sum[1] = c_sum[1] + img_raw[row][col]\r\n class_dist[1] = class_dist[1] + 1\r\n class_rgb[0] = c_sum[0] / class_dist[0]\r\n class_rgb[1] = c_sum[1] / class_dist[1]\r\n segmented_img_rgb = np.zeros_like(img_raw)\r\n for row in range(img_raw.shape[0]):\r\n for col in range(img_raw.shape[1]):\r\n if segmented_img[row, col] == 0:\r\n segmented_img_rgb[row, col] = class_rgb[0]\r\n else:\r\n segmented_img_rgb[row, col] = class_rgb[1]\r\n cv2.imwrite(image_path[:-4] + \"_cm_iter_\" + str(epochs_limit) + \".jpg\", segmented_img_rgb)\r\n\r\n\r\ndef bayes(image_path: str):\r\n \"\"\"\r\n\r\n :param image_path:\r\n :return:\r\n \"\"\"\r\n img_raw = cv2.imread(image_path)\r\n segmented_img_rgb = np.zeros_like(img_raw)\r\n bg_box = cv2.selectROI(\"SELECT BACKGROUND\", img_raw)\r\n ob_box = cv2.selectROI(\"SELECT OBJECT\", img_raw)\r\n cv2.destroyAllWindows()\r\n\r\n obj_cropped = img_raw[ob_box[1]: ob_box[1] + ob_box[3], ob_box[0]: ob_box[0] + ob_box[2], :]\r\n bg_cropped = img_raw[bg_box[1] : bg_box[1]+bg_box[3], bg_box[0] : bg_box[0]+ bg_box[2], :]\r\n\r\n\r\n obj_mean = np.mean(obj_cropped, axis=(0, 1))\r\n bg_mean = np.mean(bg_cropped, axis=(0, 1))\r\n\r\n # COVARIANCE CALCULATION FOR BACKGROUND\r\n sum_bg = 0\r\n for row in range(bg_cropped.shape[0]):\r\n for col in range(bg_cropped.shape[1]):\r\n delta = bg_cropped[row, col] - bg_mean\r\n delta = delta.reshape((3, 1))\r\n z = np.dot(delta, delta.T)\r\n sum_bg = sum_bg + z\r\n n = np.dot(bg_cropped.shape[0], bg_cropped.shape[1])\r\n sigma_bg = sum_bg / n\r\n sigma_bg_inv = np.linalg.inv(sigma_bg)\r\n sigma_bg_det = np.linalg.det(sigma_bg)\r\n\r\n # COVARIANCE CALCULATION FOR OBJECT\r\n sum_obj = 0\r\n for row in range(obj_cropped.shape[0]):\r\n for col in range(obj_cropped.shape[1]):\r\n delta = obj_cropped[row, col] - obj_mean\r\n delta = delta.reshape((3, 1))\r\n z = np.dot(delta, delta.T)\r\n sum_obj = sum_obj + z\r\n n = np.dot(obj_cropped.shape[0], obj_cropped.shape[1])\r\n sigma_obj = sum_obj / n\r\n sigma_obj_inv = np.linalg.inv(sigma_obj)\r\n sigma_obj_det = np.linalg.det(sigma_obj)\r\n\r\n P_obj = np.random.random(1)\r\n P_bg = 1 - P_obj\r\n # PIXEL PROBABILITY CALCULATION\r\n for row in range(img_raw.shape[0]):\r\n for col in range(img_raw.shape[1]):\r\n delta = img_raw[row][col][:] - bg_mean\r\n delta = delta.reshape((1, 3))\r\n z = ((-1.5 * np.log(2 * math.pi)) - (0.5 * np.log(sigma_bg_det)) - (\r\n 0.5 * np.dot(np.dot(delta, sigma_bg_inv), delta.T)))\r\n p_bg = pow(10, z)\r\n\r\n delta = img_raw[row, col] - obj_mean\r\n delta = delta.reshape(1, 3)\r\n z = ((-1.5 * np.log(2 * math.pi)) - (0.5 * np.log(sigma_obj_det)) - (\r\n 0.5 * np.dot(np.dot(delta, sigma_obj_inv), delta.T)))\r\n p_ob = pow(10, z)\r\n\r\n if P_obj * p_ob > P_bg * p_bg:\r\n segmented_img_rgb[row, col, :] = obj_mean\r\n else:\r\n segmented_img_rgb[row, col, :] = bg_mean\r\n\r\n cv2.imshow(\"RESULTS WITH BAYES CLASSIFIER\", segmented_img_rgb)\r\n cv2.waitKey(0)\r\n cv2.imwrite(image_path[:-4] + \"_bayes.jpg\", segmented_img_rgb)\r\n cv2.destroyAllWindows()\r\n\r\n\r\ndef svm(image_path: str):\r\n image_raw = cv2.imread(image_path)\r\n bg_box = cv2.selectROI(\"SELECT BACKGROUND\", image_raw)\r\n obj_box = cv2.selectROI(\"SELECT OBJECT\", image_raw)\r\n segmented_img_rgb = np.zeros_like(image_raw)\r\n\r\n obj_cropped = image_raw[obj_box[1]: obj_box[1] + obj_box[3], obj_box[0]: obj_box[0] + obj_box[2], :]\r\n bg_cropped = image_raw[bg_box[1]: bg_box[1] + bg_box[3], bg_box[0]: bg_box[0] + bg_box[2], :]\r\n obj_flat = obj_cropped.reshape(-1, 3)\r\n bg_flat = bg_cropped.reshape(-1, 3)\r\n\r\n obj_mean = np.mean(obj_cropped, axis=(0, 1))\r\n bg_mean = np.mean(bg_cropped, axis=(0, 1))\r\n\r\n inputX_train = np.vstack((obj_flat, bg_flat))\r\n inputY_train = np.vstack((np.ones((len(obj_flat), 1)), np.zeros((len(bg_flat), 1)))).reshape(-1)\r\n\r\n model = svm.SVC()\r\n model.fit(inputX_train, inputY_train)\r\n\r\n img_flat = image_raw.reshape(-1, 3)\r\n segmented_img = model.predict(img_flat).reshape(image_raw.shape[0], image_raw.shape[1])\r\n\r\n for row in range(segmented_img.shape[0]):\r\n for col in range(segmented_img.shape[1]):\r\n if segmented_img[row, col] == 1:\r\n segmented_img_rgb[row, col] = obj_mean\r\n else:\r\n segmented_img_rgb[row, col] = bg_mean\r\n\r\n cv2.imshow(\"RESULTS Of SVM CLASSIFIER\", segmented_img_rgb)\r\n cv2.imwrite((image_path[:,-4] + \"_svm.jpg\"), segmented_img_rgb)\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()\r\n\r\n","repo_name":"AhmadxSamy/classic_classifiers","sub_path":"algorithms.py","file_name":"algorithms.py","file_ext":"py","file_size_in_byte":10272,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"74907984134","text":"import re\nfrom collections import namedtuple, UserDict\nfrom functools import partial\nfrom logging import getLogger\n\nimport lxml.html\nimport requests\n\nfrom utils import File2\n\nlog = getLogger()\n\nOrgInfo = namedtuple('OrgInfo', ['org_id', 'changed', 'org_name', 'country', 'source'])\nASInfo = namedtuple('ASInfo', ['aut', 'changed', 'aut_name', 'org_id', 'source'])\nPotarooInfo = namedtuple('PotarooInfo', ['aut', 'aut_name', 'name', 'country', 'url'])\n\n\nclass Info:\n def __init__(self, asinfo=None, orginfo=None, potarooinfo=None):\n self._asinfo = asinfo\n self._orginfo = orginfo\n self._potarooinfo = potarooinfo\n\n @property\n def asn(self):\n if self._asinfo:\n return self._asinfo.aut\n elif self._potarooinfo:\n return self._potarooinfo.aut\n\n @property\n def asinfo(self):\n return self._asinfo\n\n @asinfo.setter\n def asinfo(self, asinfo):\n self._asinfo = asinfo\n\n @property\n def asn_name(self):\n if self._potarooinfo:\n return self._potarooinfo.name\n\n @property\n def country(self):\n if self._potarooinfo:\n return self._potarooinfo.country\n elif self._orginfo:\n return self._orginfo.country\n\n @property\n def name(self):\n if self._orginfo:\n return self._orginfo.org_name\n elif self._potarooinfo:\n return self._potarooinfo.name\n\n @property\n def org(self):\n if self._orginfo:\n return self._orginfo.org_id\n elif self._asinfo:\n return self._asinfo.aut_name\n elif self._potarooinfo:\n return self._potarooinfo.aut_name\n\n @property\n def orginfo(self):\n return self._orginfo\n\n @orginfo.setter\n def orginfo(self, orginfo):\n self._orginfo = orginfo\n\n @property\n def potarooinfo(self):\n return self._potarooinfo\n\n @potarooinfo.setter\n def potarooinfo(self, potarooinfo):\n self._potarooinfo = potarooinfo\n\n @property\n def url(self):\n if self._potarooinfo:\n return self._potarooinfo.url\n\n\nclass AS2Org(UserDict):\n def __init__(self, filename, include_potaroo=True, compression='infer'):\n super().__init__()\n log.info('Creating AS2Org tool.')\n ases, orgs = read_caida(filename, compression)\n for asn, asinfo in ases.items():\n self.data[asn] = Info(asinfo=asinfo, orginfo=orgs[asinfo.org_id])\n if include_potaroo:\n pots = {p.aut: p for p in potaroo()}\n for asn, potarooinfo in pots.items():\n if asn in self:\n self.data[asn].potarooinfo = potarooinfo\n else:\n self.data[asn] = Info(potarooinfo=potarooinfo)\n\n def __getitem__(self, asn):\n return self.data[asn].org if asn in self.data else str(asn)\n\n def info(self, asn):\n return self.data[asn]\n\n def name(self, asn):\n return self.data[asn].name if asn in self.data else str(asn)\n\n\ndef add_asn(ases, t):\n ases[int(t[0])] = ASInfo(*t)\n\n\ndef add_org(orgs, t):\n orgs[t[0]] = OrgInfo(*t)\n\n\ndef read_caida(filename, compression):\n ases = {}\n orgs = {}\n method = None\n format_re = re.compile(r'# format:\\s*(.*)')\n with File2(filename, compression=compression) as f:\n for line in f:\n m = format_re.match(line)\n if m:\n fields = m.group(1).split('|')\n method = partial(add_org, orgs) if fields[0] == 'org_id' else partial(add_asn, ases)\n elif line[0] != '#' and method is not None:\n method(line.split('|'))\n return ases, orgs\n\n\ndef potaroo(url='http://bgp.potaroo.net/cidr/autnums.html'):\n regex = re.compile(r'AS(\\d+)\\s+(-Reserved AS-|[A-Za-z0-9-]+)?(?:\\s+-\\s+)?(.*),\\s+([A-Z]{2})')\n r = requests.get(url)\n t = lxml.html.fromstring(r.text)\n t.make_links_absolute('http://bgp.potaroo.net/cidr/autnums.html')\n for line, a in zip(t.find('.//pre').text_content().splitlines()[1:], t.find('.//pre').xpath('.//a')):\n try:\n asn, aid, name, country = regex.match(line).groups()\n yield PotarooInfo(int(asn), aid, name, country, a.get('href'))\n except AttributeError:\n pass\n","repo_name":"alexmarder/MAP-IT","sub_path":"as2org_old.py","file_name":"as2org_old.py","file_ext":"py","file_size_in_byte":4256,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"44"} +{"seq_id":"74653426694","text":"from google.appengine.ext import db\nfrom blog import * \n\nclass Comments(db.Model):\n \"\"\"\n Instantiates a class to store comments(entity) data\n for Comments (table) in the datastore consisting\n of individual attributes/properties of the post.\n \"\"\"\n\n blog_post = db.IntegerProperty(required=True)\n content = db.TextProperty(required=True)\n author = db.StringProperty(default='Anonymous')\n created = db.DateTimeProperty(auto_now_add=True)\n last_modified = db.DateTimeProperty(auto_now=True)\n\n @classmethod\n def entry_and_id(cls, blog_id, content, author):\n new_comment = Comments(\n blog_post=blog_id,\n content=content,\n author=author\n )\n new_comment.put()\n return new_comment.key().id()\n\n @classmethod\n def comment_by_id(cls, comment_id):\n key = db.Key.from_path('Comments', int(comment_id))\n comment = db.get(key)\n return comment\n\n def edit(self, content):\n self.content = content\n self.put()\n\n @classmethod\n def get_comments(cls, blog_id, count):\n comments_list = db.GqlQuery(\"\"\"SELECT *\n from Comments\n where blog_post = {blog_id}\n order by created desc\n limit {count}\n \"\"\".format(\n blog_id=blog_id,\n count=count\n )\n )\n return comments_list\n\n\n","repo_name":"anumsh/MultiuserBLOG","sub_path":"models/comments.py","file_name":"comments.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"13505536005","text":"from django import forms\nfrom kiosk.models import Recipe,Jumun\n\nclass RecipeForm(forms.ModelForm):\n class Meta:\n model = Recipe\n fields = ['menu_name','menucode','price']\n labels = {'menu_name':'메뉴이름','menucode':'메뉴코드','price':'가격'}\n\nclass JumunForm(forms.ModelForm):\n class Meta:\n model = Jumun\n fields = ['today_jumun_order','count','customer_id','jumun_date','menucode_id']\n labels = {\n 'today_jumun_order':'오늘주문 수',\n 'count':'총수',\n 'customer_id':'유저이름',\n 'jumun_date':'주문날자',\n 'menucode_id':'메뉴코드'\n }\n","repo_name":"radio700/Django_simple_board","sub_path":"kiosk/form.py","file_name":"form.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"16141071576","text":"#Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, crie duas listas extras que vão conter apenas\r\n# os valores pares e os valores ímpares digitados, respectivamente. Ao final, mostre o conteúdo das três listas geradas.\r\n\r\nlistanum = []\r\npares = []\r\nimpares = []\r\n\r\nwhile True:\r\n n = (int(input('Digite um valor: ')))\r\n listanum.append(n)\r\n if n % 2 == 0:\r\n pares.append(n)\r\n else:\r\n impares.append(n)\r\n r = str(input('Quer continuar?[S/N] '))\r\n if r in \"nN\":\r\n break\r\nprint(f'Você digitou esta lista de números: {listanum}\\n'\r\n f'os números pares são {pares}\\n'\r\n f'e os números impares são {impares}')","repo_name":"fetrojan/Exercises-New-Projects","sub_path":"PythonExercicios/ex082.py","file_name":"ex082.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"28455477395","text":"from django.urls import path\nfrom django.contrib.auth.views import LogoutView\nfrom Mercaderias.views import *\n\nurlpatterns = [\n path('', inicio, name=\"inicio\"),\n path('productos/', productos, name=\"productos\"),\n path('proveedores/', proveedores, name=\"proveedores\"),\n path('compras/', compras, name=\"compras\"),\n path('stock/', stock, name=\"stock\"),\n path('altaCompra/', altaCompra, name=\"altaCompra\"),\n path('proveedorlist/', ProveedorList.as_view(), name=\"proveedorlist\"),\n path('eliminaproveedor//', ProveedorDelete.as_view(), name=\"eliminaproveedor\"),\n path('modificaproveedor//', ProveedorUpdate.as_view(), name=\"modificaproveedor\"),\n path('creaproveedor/', ProveedorCreate.as_view(), name=\"creaproveedor\"),\n path('consultaproveedor//', ProveedorDetail.as_view(), name=\"consultaproveedor\"),\n path('compraslist/', ComprasList.as_view(), name=\"compraslist\"),\n path('eliminacompras//', ComprasDelete.as_view(), name=\"eliminacompras\"),\n path('modificacompras//', ComprasUpdate.as_view(), name=\"modificacompras\"),\n path('consultacompras//', ComprasDetail.as_view(), name=\"consultacompras\"),\n path('productoslist/', ProductosList.as_view(), name=\"productoslist\"),\n path('eliminaproductos//', ProductosDelete.as_view(), name=\"eliminaproductos\"),\n path('modificaproductos//', ProductosUpdate.as_view(), name=\"modificaproductos\"),\n path('creaproductos/', ProductosCreate.as_view(), name=\"creaproductos\"),\n path('consultaproductos//', ProductosDetail.as_view(), name=\"consultaproductos\"),\n path('stocklist/', StockList.as_view(), name=\"stocklist\"),\n path('eliminastock//', StockDelete.as_view(), name=\"eliminastock\"),\n path('modificastock//', StockUpdate.as_view(), name=\"modificastock\"),\n path('consultastock//', StockDetail.as_view(), name=\"consultastock\"),\n path('login/', loginView, name=\"login\"),\n path('registro/', registro_usuario, name=\"registro\"),\n path('logout/', LogoutView.as_view(template_name='logout.html'), name=\"logout\"),\n path('editarperfil/', editar_perfil, name=\"editarperfil\"),\n path('agregaravatar/', agregar_avatar, name=\"agregaravatar\"),\n path('cargaimagen/', agregar_imagen_producto , name=\"cargaimagen\"),\n path('acerca/', acerca , name=\"acerca\"),\n]\n\n \n \n","repo_name":"marianolopez7749/Entrega_Final_Lopez","sub_path":"Tercera_pre_entrega_Lopez/tercera_pre_entrega_Lopez/Mercaderias/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"15936429825","text":"# Задача 2. Координаты\n\nimport random\n\n\ndef f(x, y):\n x += random.randint(0, 10)\n y += random.randint(0, 5)\n return x / y\n\n\ndef f2(x, y):\n x -= random.randint(0, 10)\n y -= random.randint(0, 5)\n return y / x\n\n\nline_count = 0\n\ntry:\n with open('coordinates.txt', 'r') as file, open('result.txt', 'w') as file_2:\n for line in file:\n line_count += 1\n nums_list = line.strip().split(', ')\n print(nums_list)\n number = random.randint(0, 100)\n\n try:\n res1 = f(int(nums_list[0]), int(nums_list[1]))\n res2 = f2(int(nums_list[0]), int(nums_list[1]))\n my_list = [str(item) for item in sorted([res1, res2, number])]\n file_2.write(' '.join(my_list))\n\n except ZeroDivisionError:\n print('Ошибка! На ноль делить нельзя')\n except ValueError:\n print(f'Ошибка в строке {line_count}! Проверьте содержимое файла coordinates.txt.')\nexcept FileNotFoundError:\n print('Ошибка! Проверьте наличие файла coordinates.txt.')\n","repo_name":"ProgmanZ/Modul-23.6-Tasks-HW","sub_path":"Task-02/Task-02.py","file_name":"Task-02.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"28556341554","text":"from env_cost import EnvGoTogether\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\nimport torch.nn.functional as F\r\nfrom torch.distributions import Categorical\r\nimport numpy as np\r\nfrom torch.autograd import grad\r\nfrom torch.distributions.kl import kl_divergence\r\n\r\ndef line_search(search_dir, max_step_len, constraints_satisfied, line_search_coef=0.9, max_iter=10):\r\n '''\r\n Perform a backtracking line search that terminates when constraints_satisfied\r\n return True and return the calculated step length. Return 0.0 if no step\r\n length can be found for which constraints_satisfied returns True\r\n\r\n Parameters\r\n ----------\r\n search_dir : torch.FloatTensor\r\n the search direction along which the line search is done\r\n\r\n max_step_len : torch.FloatTensor\r\n the maximum step length to consider in the line search\r\n\r\n constraints_satisfied : callable\r\n a function that returns a boolean indicating whether the constraints\r\n are met by the current step length\r\n\r\n line_search_coef : float\r\n the proportion by which to reduce the step length after each iteration\r\n\r\n max_iter : int\r\n the maximum number of backtracks to do before return 0.0\r\n\r\n Returns\r\n -------\r\n the maximum step length coefficient for which constraints_satisfied evaluates\r\n to True\r\n '''\r\n\r\n step_len = max_step_len / line_search_coef\r\n\r\n for i in range(max_iter):\r\n step_len *= line_search_coef\r\n\r\n if constraints_satisfied(step_len * search_dir, step_len):\r\n return step_len\r\n\r\n return torch.tensor(0.0)\r\n\r\ndef flatten(vecs):\r\n '''\r\n Return an unrolled, concatenated copy of vecs\r\n\r\n Parameters\r\n ----------\r\n vecs : list\r\n a list of Pytorch Tensor objects\r\n\r\n Returns\r\n -------\r\n flattened : torch.FloatTensor\r\n the flattened version of vecs\r\n '''\r\n\r\n flattened = torch.cat([v.view(-1) for v in vecs])\r\n\r\n return flattened\r\n\r\ndef set_params(parameterized_fun, new_params):\r\n '''\r\n Set the parameters of parameterized_fun to new_params\r\n\r\n Parameters\r\n ----------\r\n parameterized_fun : torch.nn.Sequential\r\n the function approximator to be updated\r\n\r\n update : torch.FloatTensor\r\n a flattened version of the parameters to be set\r\n '''\r\n\r\n n = 0\r\n for param in parameterized_fun.parameters():\r\n numel = param.numel()\r\n new_param = new_params[n:n + numel].view(param.size())\r\n param.data = new_param\r\n n += numel\r\n\r\ndef get_flat_params(parameterized_fun):\r\n '''\r\n Get a flattened view of the parameters of a function approximator\r\n\r\n Parameters\r\n ----------\r\n parameterized_fun : torch.nn.Sequential\r\n the function approximator for which the parameters are to be returned\r\n\r\n Returns\r\n -------\r\n flat_params : torch.FloatTensor\r\n a flattened view of the parameters of parameterized_fun\r\n '''\r\n parameters = parameterized_fun.parameters()\r\n flat_params = flatten([param.view(-1) for param in parameters])\r\n\r\n return flat_params\r\n\r\ndef cg_solver(Avp_fun, b, max_iter=10):\r\n '''\r\n Finds an approximate solution to a set of linear equations Ax = b\r\n\r\n Parameters\r\n ----------\r\n Avp_fun : callable\r\n a function that right multiplies a matrix A by a vector\r\n\r\n b : torch.FloatTensor\r\n the right hand term in the set of linear equations Ax = b\r\n\r\n max_iter : int\r\n the maximum number of iterations (default is 10)\r\n\r\n Returns\r\n -------\r\n x : torch.FloatTensor\r\n the approximate solution to the system of equations defined by Avp_fun\r\n and b\r\n '''\r\n\r\n x = torch.zeros_like(b)\r\n r = b.clone()\r\n p = b.clone()\r\n\r\n for i in range(max_iter):\r\n Avp = Avp_fun(p, retain_graph=True)\r\n\r\n alpha = torch.matmul(r, r) / torch.matmul(p, Avp)\r\n x += alpha * p\r\n\r\n if i == max_iter - 1:\r\n return x\r\n\r\n r_new = r - alpha * Avp\r\n beta = torch.matmul(r_new, r_new) / torch.matmul(r, r)\r\n r = r_new\r\n p = r + beta * p\r\n\r\ndef flat_grad(functional_output, inputs, retain_graph=False, create_graph=False):\r\n '''\r\n Return a flattened view of the gradients of functional_output w.r.t. inputs\r\n\r\n Parameters\r\n ----------\r\n functional_output : torch.FloatTensor\r\n The output of the function for which the gradient is to be calculated\r\n\r\n inputs : torch.FloatTensor (with requires_grad=True)\r\n the variables w.r.t. which the gradient will be computed\r\n\r\n retain_graph : bool\r\n whether to keep the computational graph in memory after computing the\r\n gradient (not required if create_graph is True)\r\n\r\n create_graph : bool\r\n whether to create a computational graph of the gradient computation\r\n itself\r\n\r\n Return\r\n ------\r\n flat_grads : torch.FloatTensor\r\n a flattened view of the gradients of functional_output w.r.t. inputs\r\n '''\r\n\r\n if create_graph == True:\r\n retain_graph = True\r\n grads = grad(functional_output, inputs, retain_graph=retain_graph, create_graph=create_graph)\r\n flat_grads = torch.cat([v.view(-1) for v in grads])\r\n return flat_grads\r\n\r\ndef detach_dist(dist):\r\n '''\r\n Return a copy of dist with the distribution parameters detached from the\r\n computational graph\r\n\r\n Parameters\r\n ----------\r\n dist: torch.distributions.distribution.Distribution\r\n the distribution object for which the detached copy is to be returned\r\n\r\n Returns\r\n -------\r\n detached_dist\r\n the detached distribution\r\n '''\r\n\r\n detached_dist = Categorical(logits=dist.logits.detach())\r\n return detached_dist\r\n\r\ndef mean_kl_first_fixed(dist_1, dist_2):\r\n '''\r\n Calculate the kl-divergence between dist_1 and dist_2 after detaching dist_1\r\n from the computational graph\r\n\r\n Parameters\r\n ----------\r\n dist_1 : torch.distributions.distribution.Distribution\r\n the first argument to the kl-divergence function (will be fixed)\r\n\r\n dist_2 : torch.distributions.distribution.Distribution\r\n the second argument to the kl-divergence function (will not be fixed)\r\n\r\n Returns\r\n -------\r\n mean_kl : torch.float\r\n the kl-divergence between dist_1 and dist_2\r\n '''\r\n dist_1_detached = detach_dist(dist_1)\r\n mean_kl = torch.mean(kl_divergence(dist_1_detached, dist_2))\r\n return mean_kl\r\n\r\ndef get_Hvp_fun(functional_output, inputs, damping_coef=0.0):\r\n '''\r\n Returns a function that calculates a Hessian-vector product with the Hessian\r\n of functional_output w.r.t. inputs\r\n\r\n Parameters\r\n ----------\r\n functional_output : torch.FloatTensor (with requires_grad=True)\r\n the output of the function of which the Hessian is calculated\r\n\r\n inputs : torch.FloatTensor\r\n the inputs w.r.t. which the Hessian is calculated\r\n\r\n damping_coef : float\r\n the multiple of the identity matrix to be added to the Hessian\r\n '''\r\n\r\n inputs = list(inputs)\r\n grad_f = flat_grad(functional_output, inputs, create_graph=True)\r\n def Hvp_fun(v, retain_graph=True):\r\n gvp = torch.matmul(grad_f, v)\r\n Hvp = flat_grad(gvp, inputs, retain_graph=retain_graph)\r\n Hvp += damping_coef * v\r\n return Hvp\r\n return Hvp_fun\r\n\r\nclass P_net(nn.Module):\r\n def __init__(self, state_dim, action_dim):\r\n super(P_net, self).__init__()\r\n self.fc1 = nn.Linear(state_dim, 256)\r\n self.fc2 = nn.Linear(256, 128)\r\n self.fc3 = nn.Linear(128, action_dim)\r\n\r\n def forward(self, x):\r\n x = F.relu(self.fc1(x))\r\n x = F.relu(self.fc2(x))\r\n action_score = self.fc3(x)\r\n return F.softmax(action_score, dim=-1)\r\n\r\nclass Q_net(nn.Module):\r\n def __init__(self, state_dim, action_dim):\r\n super(Q_net, self).__init__()\r\n self.fc1 = nn.Linear(state_dim, 256)\r\n self.fc2 = nn.Linear(256, 128)\r\n self.fc3 = nn.Linear(128, action_dim)\r\n\r\n def forward(self, x):\r\n x = F.relu(self.fc1(x))\r\n x = F.relu(self.fc2(x))\r\n q = self.fc3(x)\r\n return q\r\n\r\nclass CPO():\r\n def __init__(self, state_dim, action_dim):\r\n super(CPO, self).__init__()\r\n self.state_dim = state_dim\r\n self.action_dim = action_dim\r\n self.p_net = P_net(state_dim, action_dim)\r\n self.q_net = Q_net(state_dim, action_dim)\r\n self.c_net = Q_net(state_dim, action_dim)\r\n self.gamma = 0.99\r\n self.max_J_c = 0.1\r\n self.max_kl = 1e-2\r\n self.line_search_coef=0.9\r\n self.line_search_accept_ratio=0.1\r\n self.loss_fn = torch.nn.MSELoss()\r\n self.q_optimizer = torch.optim.Adam(self.q_net.parameters(), lr=1e-2)\r\n self.c_optimizer = torch.optim.Adam(self.c_net.parameters(), lr=1e-2)\r\n self.p_optimizer = torch.optim.Adam(self.p_net.parameters(), lr=1e-3)\r\n\r\n def get_action(self, state):\r\n state = torch.from_numpy(state).float()\r\n action_prob = self.p_net.forward(state)\r\n c = Categorical(action_prob)\r\n action = c.sample()\r\n return action.item(), action_prob[:, action.item()].item()\r\n\r\n def train_CPO(self, state_list, action_list, prob_list, reward_list, cost_list, next_state_list):\r\n # train cost\r\n state = state_list[0]\r\n next_state = next_state_list[0]\r\n for i in range(1, len(state_list)):\r\n state = np.vstack((state, state_list[i]))\r\n next_state = np.vstack((next_state, next_state_list[i]))\r\n state = torch.from_numpy(state).float()\r\n next_state = torch.from_numpy(next_state).float()\r\n next_a_prob = self.p_net.forward(next_state)\r\n for epoch in range(5):\r\n q = self.q_net.forward(state)\r\n next_q = self.q_net.forward(next_state)\r\n expect_q = q.clone()\r\n for i in range(len(state_list)):\r\n expect_q[i, action_list[i]] = reward_list[i] + self.gamma * torch.sum(next_a_prob[i, :] * next_q[i, :])\r\n loss = self.loss_fn(q, expect_q.detach())\r\n self.q_optimizer.zero_grad()\r\n loss.backward()\r\n self.q_optimizer.step()\r\n\r\n q_c = self.c_net.forward(state)\r\n next_q_c = self.c_net.forward(next_state)\r\n expect_q_c = q_c.clone()\r\n for i in range(len(state_list)):\r\n expect_q_c[i, action_list[i]] = cost_list[i] + self.gamma * torch.sum(next_a_prob[i, :] * next_q_c[i, :])\r\n loss = self.loss_fn(q_c, expect_q_c.detach())\r\n self.c_optimizer.zero_grad()\r\n loss.backward()\r\n self.c_optimizer.step()\r\n\r\n q = self.q_net.forward(state)\r\n q_c = self.c_net.forward(state)\r\n a_prob = self.p_net.forward(state)\r\n v = torch.sum(a_prob * q, 1)\r\n v_c = torch.sum(a_prob * q_c, 1)\r\n gae = torch.zeros(len(state_list), )\r\n gae_c = torch.zeros(len(state_list), )\r\n for i in range(len(state_list)):\r\n gae[i] = q[i, action_list[i]] - v[i]\r\n gae_c[i] = q_c[i, action_list[i]] - v_c[i]\r\n\r\n # train policy\r\n log_a_probs = torch.zeros(len(state_list), )\r\n for i in range(len(state_list)):\r\n log_a_probs[i] = torch.log(a_prob[i, action_list[i]])\r\n r_loss = torch.mean(gae *log_a_probs)\r\n g = flat_grad(r_loss, self.p_net.parameters(), retain_graph=True)\r\n c_loss = torch.mean(gae_c *log_a_probs)\r\n b = flat_grad(c_loss, self.p_net.parameters(), retain_graph=True)\r\n\r\n action_dists = Categorical(probs=a_prob)\r\n mean_kl = mean_kl_first_fixed(action_dists, action_dists) # kl-divergence between dist_1 and dist_2\r\n Fvp_fun = get_Hvp_fun(mean_kl, self.p_net.parameters())\r\n H_inv_g = cg_solver(Fvp_fun, g) # H**-1*g\r\n H_inv_b = cg_solver(Fvp_fun, b) # H**-1*b\r\n q = torch.matmul(g, H_inv_g)\r\n r = torch.matmul(g, H_inv_b)\r\n s = torch.matmul(b, H_inv_b)\r\n\r\n J_c = 0\r\n for i in range(len(state_list)-1, -1, -1):\r\n J_c = cost_list[i] + self.gamma * J_c\r\n c = (J_c - self.max_J_c)\r\n\r\n is_feasible = False if c > 0 and c ** 2 / s - self.max_kl > 0 else True\r\n if is_feasible:\r\n lam, nu = self.calc_dual_vars(q, r, s, c)\r\n search_dir = lam ** -1 * (H_inv_g + nu * H_inv_b)\r\n else:\r\n search_dir = -torch.sqrt(2 * self.max_kl / s) * H_inv_b\r\n\r\n # Should be positive\r\n current_policy = get_flat_params(self.p_net)\r\n new_policy = current_policy + search_dir\r\n set_params(self.p_net, new_policy)\r\n\r\n def calc_dual_vars(self, q, r, s, c):\r\n if c < 0.0 and c ** 2 / s - self.max_kl > 0.0:\r\n lam = torch.sqrt(q / (self.max_kl))\r\n nu = 0.0\r\n return lam, nu\r\n A = q - r ** 2 / s\r\n B = self.max_kl - c ** 2 / s\r\n lam_mid = r / c\r\n lam_a = torch.sqrt(A / B)\r\n lam_b = torch.sqrt(q / (self.max_kl))\r\n f_mid = -0.5 * (q / lam_mid + lam_mid * self.max_kl)\r\n f_a = -torch.sqrt(A * B) - r * c / s\r\n f_b = -torch.sqrt(q * self.max_kl)\r\n if lam_mid > 0:\r\n if c < 0:\r\n if lam_a > lam_mid:\r\n lam_a = lam_mid\r\n f_a = f_mid\r\n if lam_b < lam_mid:\r\n lam_b = lam_mid\r\n f_b = f_mid\r\n else:\r\n if lam_a < lam_mid:\r\n lam_a = lam_mid\r\n f_a = f_mid\r\n if lam_b > lam_mid:\r\n lam_b = lam_mid\r\n f_b = f_mid\r\n else:\r\n if c < 0:\r\n lam = lam_b\r\n else:\r\n lam = lam_a\r\n lam = lam_a if f_a >= f_b else lam_b\r\n nu = max(0.0, (lam * c - r) / s)\r\n return lam, nu\r\n\r\nif __name__ == '__main__':\r\n state_dim = 169\r\n action_dim = 4\r\n max_epi = 1000\r\n max_mc = 500\r\n epi_iter = 0\r\n mc_iter = 0\r\n acc_reward = 0\r\n acc_cost = 0\r\n reward_curve = []\r\n env = EnvGoTogether(13)\r\n agent = CPO(state_dim, action_dim)\r\n for epi_iter in range(max_epi):\r\n state_list = []\r\n action_list = []\r\n prob_list = []\r\n reward_list = []\r\n cost_list = []\r\n next_state_list = []\r\n for mc_iter in range(max_mc):\r\n # env.render()\r\n state = np.zeros((env.map_size, env.map_size))\r\n state[env.agt1_pos[0], env.agt1_pos[1]] = 1\r\n state = state.reshape((1, env.map_size * env.map_size))\r\n action, action_prob = agent.get_action(state)\r\n group_list = [action, 2]\r\n reward, done, cost = env.step(group_list)\r\n next_state = np.zeros((env.map_size, env.map_size))\r\n next_state[env.agt1_pos[0], env.agt1_pos[1]] = 1\r\n next_state = next_state.reshape((1, env.map_size * env.map_size,))\r\n acc_reward += reward\r\n acc_cost += cost\r\n state_list.append(state)\r\n action_list.append(action)\r\n prob_list.append(action_prob)\r\n reward_list.append(reward)\r\n cost_list.append(cost)\r\n next_state_list.append(next_state)\r\n if done:\r\n break\r\n agent.train_CPO(state_list, action_list, prob_list, reward_list, cost_list, next_state_list)\r\n print('epi', epi_iter, 'reward', acc_reward / mc_iter, 'cost', acc_cost / mc_iter, 'MC', mc_iter)\r\n env.reset()\r\n acc_reward = 0\r\n acc_cost = 0","repo_name":"Bigpig4396/PyTorch-Constrained-Policy-Optimization-CPO","sub_path":"CPO.py","file_name":"CPO.py","file_ext":"py","file_size_in_byte":15622,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"44"} +{"seq_id":"22359367115","text":"#Necessary parameters\n\n\nimport os\n\nDSNAME = \"coco\"\n\nBATCH = 1\n\nUSE_TPU = False\nMULTI_CORE = False\n\nimport torch\n\nDATA_DIR = '../dataset/'\nOUT_DIR = '../result/'\nMODEL_DIR = '../models/'\nCHECKPOINT_DIR = '../checkpoint/'\n\nTRAIN_DIR = DATA_DIR+\"train/\" # UPDATE\nTEST_DIR = DATA_DIR+\"test/\" # UPDATE\n\nos.makedirs(TRAIN_DIR, exist_ok=True)\nos.makedirs(TEST_DIR, exist_ok=True)\nos.makedirs(MODEL_DIR, exist_ok=True)\nos.makedirs(CHECKPOINT_DIR, exist_ok=True)\nos.makedirs(OUT_DIR, exist_ok=True)\n\n# DATA INFORMATION\nIMAGE_SIZE = 224\nBATCH_SIZE = 1\nGRADIENT_PENALTY_WEIGHT = 10\nNUM_EPOCHS = 10\nKEEP_CKPT = 2\n# save_model_path = MODEL_DIR\n\n\nif torch.cuda.is_available():\n DEVICE = torch.device(\"cuda:0\")\n print(\"running on the GPU\")\nelse:\n DEVICE = torch.device(\"cpu\")\n print(\"running on the CPU\")\n","repo_name":"Sgsouham/ColourizationGAN","sub_path":"param.py","file_name":"param.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"42297100964","text":"import os\nimport json\nimport subprocess\nfrom flask import Flask, abort, jsonify, session, render_template\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy.exc import SQLAlchemyError, OperationalError\nfrom pymysql import OperationalError as PyOperationalError\nfrom flask_login import LoginManager\n\nfrom werkzeug.exceptions import HTTPException, InternalServerError\nfrom http import HTTPStatus\n\nimport logging\nimport logging.handlers\nfrom .config import DevelopmentConfig, ProductionConfig\n\nfrom flask_cors import CORS, cross_origin\nfrom . mplogger import *\n\ndb = SQLAlchemy()\n\n# Configure authentication\nlogin_manager = LoginManager()\n\nif os.getenv(\"MPCONSOLE_ENV\") == 'prod':\n\tDefaultConfig = ProductionConfig\nelse:\n\tDefaultConfig = DevelopmentConfig\n\n\ndef create_app(config_object=DefaultConfig):\n\tapp = Flask(__name__)\n\tcors = CORS(app)\n\n\tapp.config.from_object(config_object)\n\tapp.config.from_pyfile('../config.cfg', silent=True)\n\tapp.config.from_pyfile('../conf_console.cfg', silent=True)\n\t# Trim White Space from templates\n\tapp.jinja_env.trim_blocks = True\n\tapp.jinja_env.lstrip_blocks = True\n\n\t# Configure SQLALCHEMY_DATABASE_URI for MySQL\n\t_uri = \"mysql+pymysql://%s:%s@%s:%s/%s\" % (app.config['DB_USER'],app.config['DB_PASS'],app.config['DB_HOST'],app.config['DB_PORT'],app.config['DB_NAME'])\n\tapp.config['SQLALCHEMY_DATABASE_URI'] = _uri\n\n\t# Configure authentication\n\tlogin_manager.init_app(app)\n\tlogin_manager.session_protection = \"strong\"\n\tlogin_manager.login_view = \"auth.login\"\n\n\t# Add Database\n\tdb.app = app\n\tdb.init_app(app)\n\n\t# Configure logging\n\tlog_file = app.config['LOGGING_LOCATION'] + \"/mpconsole.log\"\n\tif not os.path.exists(app.config['LOGGING_LOCATION']):\n\t\tos.makedirs(app.config['LOGGING_LOCATION'])\n\t\tsubprocess.call(['chmod', '2775', app.config['LOGGING_LOCATION']])\n\n\thandler = logging.handlers.TimedRotatingFileHandler(log_file, when='midnight', interval=1, backupCount=30)\n\n\t# Set default log level\n\tif app.config['DEBUG']:\n\t\tapp.logger.setLevel(logging.DEBUG)\n\telse:\n\t\tapp.logger.setLevel(logging.INFO)\n\n\tif app.config['LOGGING_LEVEL'].lower() == 'info':\n\t\tapp.logger.setLevel(logging.INFO)\n\telif app.config['LOGGING_LEVEL'].lower() == 'debug':\n\t\tapp.logger.setLevel(logging.DEBUG)\n\telif app.config['LOGGING_LEVEL'].lower() == 'warning':\n\t\tapp.logger.setLevel(logging.WARNING)\n\telif app.config['LOGGING_LEVEL'].lower() == 'error':\n\t\tapp.logger.setLevel(logging.ERROR)\n\telif app.config['LOGGING_LEVEL'].lower() == 'critical':\n\t\tapp.logger.setLevel(logging.CRITICAL)\n\telse:\n\t\tapp.logger.setLevel(logging.INFO)\n\n\tformatter = logging.Formatter(app.config['LOGGING_FORMAT'])\n\thandler.setFormatter(formatter)\n\tapp.logger.addHandler(handler)\n\n\t@app.teardown_request\n\tdef shutdown_session(exception):\n\t\tdb.session.rollback()\n\t\tdb.session.remove()\n\n\t@app.context_processor\n\tdef baseData():\n\t\tenableIntune = 0\n\t\tif app.config['ENABLE_INTUNE']:\n\t\t\tenableIntune = 1\n\n\t\treturn dict(patchGroupCount=patchGroupCount(), clientCount=clientCount(), intune=enableIntune)\n\n\tread_siteconfig_server_data(app)\n\n\tfrom .errors import errors as errors_blueprint\n\tapp.register_blueprint(errors_blueprint)\n\n\tfrom .main import main as main_blueprint\n\tapp.register_blueprint(main_blueprint, url_prefix='/')\n\n\tif app.config['ALLOW_CONTENT_DOWNLOAD']:\n\t\tfrom .content import content as content_blueprint\n\t\tapp.register_blueprint(content_blueprint, url_prefix='/mp-content')\n\n\tfrom .auth import auth as auth_blueprint\n\tapp.register_blueprint(auth_blueprint, url_prefix='/auth')\n\n\tfrom .agent import agent as agent_blueprint\n\tapp.register_blueprint(agent_blueprint, url_prefix='/agent')\n\n\tfrom .dashboard import dashboard as dashboard_blueprint\n\tapp.register_blueprint(dashboard_blueprint, url_prefix='/dashboard')\n\n\tfrom .clients import clients as clients_blueprint\n\tapp.register_blueprint(clients_blueprint, url_prefix='/clients')\n\n\tfrom .patches import patches as patches_blueprint\n\tapp.register_blueprint(patches_blueprint, url_prefix='/patches')\n\n\tfrom .registration import registration as registration_blueprint\n\tapp.register_blueprint(registration_blueprint, url_prefix='/registration')\n\n\tfrom .reports import reports as reports_blueprint\n\tapp.register_blueprint(reports_blueprint, url_prefix='/reports')\n\n\tfrom .software import software as software_blueprint\n\tapp.register_blueprint(software_blueprint, url_prefix='/software')\n\n\tfrom .osmanage import osmanage as osmanage_blueprint\n\tapp.register_blueprint(osmanage_blueprint, url_prefix='/osmanage')\n\n\tfrom .provision import provision as provision_blueprint\n\tapp.register_blueprint(provision_blueprint, url_prefix='/provision')\n\n\tfrom .console import console as console_blueprint\n\tapp.register_blueprint(console_blueprint, url_prefix='/console')\n\n\tfrom .test import test as test_blueprint\n\tapp.register_blueprint(test_blueprint, url_prefix='/test')\n\n\tfrom .maint import maint as maint_blueprint\n\tapp.register_blueprint(maint_blueprint, url_prefix='/maint')\n\n\tfrom .mdm import mdm as mdm_blueprint\n\tapp.register_blueprint(mdm_blueprint, url_prefix='/mdm')\n\n\t# MDM Schema Setup\n\tif app.config['ENABLE_INTUNE']:\n\t\t# Read Schema File and Store In App Var\n\t\tmdm_schema_file = app.config['STATIC_JSON_DIR']+\"/mdm_schema.json\"\n\t\tif os.path.exists(mdm_schema_file.strip()):\n\t\t\tschema_data = {}\n\t\t\ttry:\n\t\t\t\twith open(mdm_schema_file.strip()) as data_file:\n\t\t\t\t\tschema_data = json.load(data_file)\n\n\t\t\t\tapp.config[\"MDM_SCHEMA\"] = schema_data\n\t\t\texcept OSError:\n\t\t\t\tprint('Well darn.')\n\t\t\t\treturn\n\n\t@app.errorhandler(InternalServerError)\n\tdef handle_exception1(e):\n\t\treturn render_template('500.html'), 200\n\n\treturn app\n\n'''\n----------------------------------------------------------------\nGlobal\n----------------------------------------------------------------\n'''\ndef read_siteconfig_server_data(app):\n\n\tdata = {}\n\tif os.path.exists(app.config['SITECONFIG_FILE'].strip()):\n\t\ttry:\n\t\t\twith open(app.config['SITECONFIG_FILE'].strip()) as data_file:\n\t\t\t\tdata = json.load(data_file)\n\n\t\texcept OSError:\n\t\t\tprint('Well darn.')\n\t\t\treturn\n\n\telse:\n\t\tprint(\"Error, could not open file \" + app.config['SITECONFIG_FILE'].strip())\n\t\treturn\n\n\tif \"settings\" in data:\n\t\tapp.config['MP_SETTINGS'] = data['settings']\n\t\treturn\n\ndef patchGroupCount():\n\tfrom .model import MpPatchGroup\n\tqGet = MpPatchGroup.query.all()\n\tcount = len(qGet)\n\treturn count\n\ndef clientCount():\n\tfrom .model import MpClient\n\tqGet = MpClient.query.with_entities(MpClient.cuuid).all()\n\tcount = len(qGet)\n\treturn count\n","repo_name":"LLNL/MacPatch","sub_path":"Source/Server/apps/mpconsole/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6424,"program_lang":"python","lang":"en","doc_type":"code","stars":86,"dataset":"github-code","pt":"44"} +{"seq_id":"18930007084","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Feb 9 18:21:11 2021\r\n\r\n@author: isfan (K-Num)\r\n\"\"\"\r\n\r\n# keras imports for the dataset and building our neural network\r\nimport numpy as np\r\nimport time\r\nimport pandas as pd\r\nimport tensorflow as tf\r\nfrom keras import regularizers, models, layers\r\nfrom scipy.stats import spearmanr\r\nfrom sklearn import preprocessing\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nimport keras\r\nfrom keras.models import Sequential, model_from_json\r\nfrom keras.layers import Dense, Dropout\r\nfrom keras.utils import to_categorical\r\nimport joblib\r\nfrom sklearn.model_selection import train_test_split\r\n\r\ndef preparets(x, y, num_keypoints):\r\n assert 0 < num_keypoints < x.shape[1]\r\n x_seq = np.atleast_3d(np.array([x[:,start*num_keypoints:(start*num_keypoints+num_keypoints)] for start in range(0, int(x.shape[1]/num_keypoints))]))\r\n y_seq = np.atleast_1d(np.array([y[start*num_keypoints] for start in range(0, int(y.shape[0]/num_keypoints))]))\r\n return x_seq, y_seq\r\n\r\n'''\r\n0\tnose\r\n1\tLeft eye\r\n2\tRight eye\r\n3\tLeft ear\r\n4\tRight ear\r\n5\tLeft shoulder\r\n6\tRight shoulder\r\n7\tLeft elbow\r\n8\tRight elbow\r\n9\tLeft wrist\r\n10\tRight wrist\r\n11\tLeft pelvic region\r\n12\tRight pelvic area\r\n13\tLeft knee\r\n14\tRight knee\r\n15\tLeft ankle\r\n16\tRight ankle\r\n'''\r\nnum_keypoints = 17\r\nnum_content = 2\r\n# TEST_SIZE = 0.7\r\n\r\ndef getData(filename, lab, tar):\r\n # read csv for standing pose\r\n try:\r\n \tdf_tracefile = pd.read_csv(filename)\r\n \tframe = np.array(df_tracefile[['frame']], dtype=int)\r\n \tpose = np.array(df_tracefile[['pose_score']], dtype=float)\r\n \tbody_part = np.array(df_tracefile[['part_score']], dtype=float)\r\n \tx_coord = np.array(df_tracefile[['x_coord']], dtype=float)\r\n \ty_coord = np.array(df_tracefile[['y_coord']], dtype=float)\r\n \tlabel = np.array(df_tracefile[['label']], dtype=str)\r\n except:\r\n \traise\r\n \r\n '''Pre-Processing Data'''\r\n data = np.array([pose, body_part,x_coord,y_coord])\r\n \r\n x_seq, y_target = preparets(data[:,:,0], label[:,0], num_keypoints)\r\n _, frame = preparets(data[:,:,0], frame[:,0], num_keypoints)\r\n \r\n #For coba1.csv data\r\n # std = np.array(list(range(1, 109)))\r\n # bow = np.array(list(range(181, 270)))#181, 270\r\n # right = np.array(list(range(330, 415)))\r\n # left = np.array(list(range(544, 593)))\r\n \r\n lis = np.array(list(range(0, len(label))))\r\n \r\n lab_target = np.zeros(len(y_target), dtype=float)\r\n \r\n for i in range(len(frame)):\r\n #For stand label\r\n if (len(np.where(frame[i]==lis)[0])>0):\r\n y_target[i] = label[i][0]\r\n lab_target[i] = tar\r\n \r\n return y_target, lab_target, x_seq\r\n\r\n#Training Data\r\ny_target, lab_target, x_seq = getData(filename='coba_none.csv', lab='none', tar='0')\r\ny_target21, lab_target21, x_seq21 = getData(filename='coba_std1.csv', lab='std', tar='1')\r\ny_target22, lab_target22, x_seq22 = getData(filename='coba_std2.csv', lab='std', tar='1')\r\ny_target23, lab_target23, x_seq23 = getData(filename='coba_std3.csv', lab='std', tar='1')\r\ny_target31, lab_target31, x_seq31 = getData(filename='coba_str1.csv', lab='str', tar='2')\r\ny_target32, lab_target32, x_seq32 = getData(filename='coba_str2.csv', lab='str', tar='2')\r\ny_target33, lab_target33, x_seq33 = getData(filename='coba_str3.csv', lab='str', tar='2')\r\ny_target41, lab_target41, x_seq41 = getData(filename='coba_rgt1.csv', lab='rgt', tar='3')\r\ny_target42, lab_target42, x_seq42 = getData(filename='coba_rgt2.csv', lab='rgt', tar='3')\r\ny_target43, lab_target43, x_seq43 = getData(filename='coba_rgt3.csv', lab='rgt', tar='3')\r\ny_target51, lab_target51, x_seq51 = getData(filename='coba_lft1.csv', lab='lft', tar='4')\r\ny_target52, lab_target52, x_seq52 = getData(filename='coba_lft2.csv', lab='lft', tar='4')\r\ny_target53, lab_target53, x_seq53 = getData(filename='coba_lft3.csv', lab='lft', tar='4')\r\n\r\n#Testing Data\r\ny_target24, lab_target24, x_seq24 = getData(filename='coba_stand_test.csv', lab='std', tar='1')\r\ny_target44, lab_target44, x_seq44 = getData(filename='coba_right_test.csv', lab='rgt', tar='3')\r\ny_target54, lab_target54, x_seq54 = getData(filename='coba_left_test.csv', lab='lft', tar='4')\r\n\r\n# Combine all the training data\r\nlab_target_fin = to_categorical(np.concatenate((lab_target,\r\n lab_target21, lab_target22, lab_target23,\r\n lab_target31, lab_target32, lab_target33,\r\n lab_target41, lab_target42, lab_target43,\r\n lab_target51, lab_target52, lab_target53), axis=0))\r\nx_seq_fin = np.concatenate((x_seq,\r\n x_seq21, x_seq22, x_seq23,\r\n x_seq31, x_seq32, x_seq33,\r\n x_seq41, x_seq42, x_seq43,\r\n x_seq51, x_seq52, x_seq53), axis=0)\r\nX_input = x_seq_fin[:,4-num_content::,:].reshape(len(x_seq_fin),num_keypoints*num_content)\r\ny_target_fin = np.concatenate((y_target,\r\n y_target21, y_target22, y_target23,\r\n y_target31, y_target32, y_target33,\r\n y_target41, y_target42, y_target43,\r\n y_target51, y_target52, y_target53), axis=0)\r\n\r\n# Combine all the testing data\r\nlab_target_test = to_categorical(np.concatenate((lab_target24, lab_target44, lab_target54),axis=0))\r\nx_seq_test = np.concatenate((x_seq24, x_seq44, x_seq54), axis=0)\r\nX_input_test = x_seq_test[:,4-num_content::,:].reshape(len(x_seq_test),num_keypoints*num_content)\r\ny_target_test = np.concatenate((y_target24, y_target44, y_target54), axis=0)\r\n\r\nnormalizer = preprocessing.StandardScaler()\r\ntempNorm = normalizer.fit(X_input)\r\n\r\nscaler_file = \"yoga_scaller.save\"\r\njoblib.dump(tempNorm, scaler_file) \r\n\r\nX_input_norm = tempNorm.transform(X_input)\r\n\r\nX_input_test_norm = tempNorm.transform(X_input_test)\r\n\r\n#Training\r\nX_train, _, lab_train, _ = train_test_split(X_input_norm, lab_target_fin, test_size=0.1, random_state=42)\r\n_, _, y_train, _ = train_test_split(X_input, y_target_fin, test_size=0.1, random_state=42)\r\n\r\n#Testing\r\n_, X_test, _, lab_test = train_test_split(X_input_test_norm, lab_target_test, test_size=0.9, random_state=42)\r\n_, _, _, y_test = train_test_split(X_input_test, y_target_test, test_size=0.9, random_state=42)\r\n\r\n'''Neural Network'''\r\nTRAINED_MODEL_NAME = \"./model/yoga_net\"\r\n\r\n# # Reset the whole tensorflow graph\r\ntf.get_default_graph()\r\n\r\nmodel = Sequential()\r\nmodel.add(Dense(50, activation='relu', input_dim=num_keypoints*num_content))\r\nmodel.add(Dropout(0.2))\r\nmodel.add(Dense(20, activation='relu'))\r\nmodel.add(Dropout(0.5))\r\n# model.add(Dense(10, activation='relu'))\r\nmodel.add(Dense(len(lab_target_fin[0]), activation='softmax'))\r\n\r\n# Compile the model\r\nmodel.compile(optimizer='adam', \r\n loss='categorical_crossentropy', \r\n metrics=['accuracy'])\r\n\r\nhistory = model.fit(X_train, lab_train, epochs=100)\r\n\r\n# # summarize history for accuracy\r\n# plt.figure()\r\n# plt.plot(history.history['acc'])\r\n# plt.title('model accuracy')\r\n# plt.ylabel('accuracy')\r\n# plt.xlabel('epoch')\r\n# plt.legend(['Accuracy'], loc='upper left')\r\n# plt.show()\r\n\r\n# # summarize history for loss\r\n# plt.figure()\r\n# plt.plot(history.history['loss'])\r\n# plt.title('model loss')\r\n# plt.ylabel('loss')\r\n# plt.xlabel('epoch')\r\n# plt.legend(['loss'], loc='upper left')\r\n# plt.show()\r\n\r\npred_train= model.predict(X_train)\r\nscores = model.evaluate(X_train, lab_train, verbose=0)\r\nprint('Accuracy on training data: {}% \\nError on training data: {}'.format(scores[1]*100, 1 - scores[1])) \r\n\r\n# serialize model to JSON\r\nmodel_json = model.to_json()\r\nwith open('./model/'+'yoga_net.json', \"w\") as json_file:\r\n json_file.write(model_json)\r\n \r\n# serialize weights to HDF5\r\nmodel.save_weights(TRAINED_MODEL_NAME)\r\nprint(\"Saved model to disk\")\r\n\r\n# load the saved model\r\nwith open('./model/'+'yoga_net.json', 'r') as arch_file:\r\n loaded_model = model_from_json(arch_file.read())\r\n\r\n# load weights into new model\r\nloaded_model.load_weights(TRAINED_MODEL_NAME)\r\nprint(\"\\nLoaded model from disk\")\r\n\r\n# Compile the model\r\nloaded_model.compile(optimizer='adam', \r\n loss='categorical_crossentropy', \r\n metrics=['accuracy'])\r\nprint(\"Model Compiled\")\r\n\r\npred_test = np.empty((0,len(lab_test[0])),dtype=float)\r\n\r\nfor i in range(len(X_test)):\r\n pred_test = np.concatenate((pred_test, loaded_model.predict(X_test[i].reshape(1,-1))), axis=0)\r\n \r\n# pred_test = loaded_model.predict(X_train)\r\n\r\ny_pred = np.array([],dtype=str)\r\n\r\nfor i in range(len(pred_test)):\r\n val = np.argmax(pred_test[i], axis = 0)\r\n # print(val)\r\n if (val==1):\r\n y_pred = np.concatenate((y_pred, np.array(['std'])), axis = 0)\r\n elif(val==2):\r\n y_pred = np.concatenate((y_pred, np.array(['str'])), axis = 0)\r\n elif(val==3):\r\n y_pred = np.concatenate((y_pred, np.array(['rgt'])), axis = 0)\r\n elif(val==4):\r\n y_pred = np.concatenate((y_pred, np.array(['lft'])), axis = 0)\r\n else:\r\n y_pred = np.concatenate((y_pred, np.array(['none'])), axis = 0)\r\n\r\nscores = np.sum(y_pred==y_test)/len(y_pred)\r\nprint('Accuracy on testing data: {}% \\nError on testing data: {}'.format(scores*100, 1 - scores)) \r\n\r\n'''Parameters Coorelation'''\r\n# #spearmanr method\r\n# for i in range(num_keypoints):\r\n# corr, _ = spearmanr(x_seq[:,1,i], lab_target)\r\n# print('Spearmans correlation: %.3f' % corr)\r\n\r\n# #seaborn method\r\n# sns.set_theme(style=\"white\")\r\n\r\n# # Generate a large random dataset\r\n# d = pd.DataFrame(data=x_seq21[:,:,0].T,\r\n# columns=[\r\n# 'frame',\r\n# 'pose_score',\r\n# 'part_score',\r\n# 'x_coord',\r\n# 'y_coord',\r\n# ])\r\n\r\n# # Compute the correlation matrix\r\n# corr = d.corr()\r\n\r\n# # Generate a mask for the upper triangle\r\n# mask = np.triu(np.ones_like(corr, dtype=bool))\r\n\r\n# # Set up the matplotlib figure\r\n# f, ax = plt.subplots(figsize=(11, 9))\r\n\r\n# # Generate a custom diverging colormap\r\n# cmap = sns.diverging_palette(230, 20, as_cmap=True)\r\n\r\n# # Draw the heatmap with the mask and correct aspect ratio\r\n# sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,\r\n# square=True, linewidths=.5, cbar_kws={\"shrink\": .5})\r\n","repo_name":"fauzisfan/Yoga-Training-Classifier","sub_path":"Train_yoga.py","file_name":"Train_yoga.py","file_ext":"py","file_size_in_byte":10432,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"243292703","text":"import tkinter\r\n\r\nclass tempGUI:\r\n def __init__(self):\r\n self.main_window = tkinter.Tk()\r\n self.main_window.geometry(\"265x100\")\r\n\r\n self.fLabel = tkinter.Label(self.main_window, text = 'Fahrenheit:')\r\n self.fLabel.grid(row = 0, column = 0, sticky = \"W\")\r\n\r\n self.cLabel = tkinter.Label(self.main_window, text = \"Celsius:\")\r\n self.cLabel.grid(row = 0, column = 1, sticky = \"W\")\r\n \r\n self.fTextBox = tkinter.Entry(self.main_window, bd = 5)\r\n self.fTextBox.grid(row = 1, column = 0, sticky = \"W\")\r\n\r\n self.cTextBox = tkinter.Entry(self.main_window, bd = 5)\r\n self.cTextBox.grid(row = 1, column = 1, sticky = \"W\")\r\n\r\n self.f2cButton = tkinter.Button(self.main_window, text = \">>>>\", command = self.fToC)\r\n self.f2cButton.grid(row = 2, column = 0, sticky = \"W\")\r\n\r\n self.c2fButton = tkinter.Button(self.main_window, text = \"<<<<\", command = self.cToF)\r\n self.c2fButton.grid(row = 2, column = 1, sticky = \"W\")\r\n\r\n self.main_window.title(\"Temperature Conversion\")\r\n tkinter.mainloop()\r\n\r\n def fToC(self):\r\n conversion = (float(self.fTextBox.get()) - 32) / 1.8\r\n self.cTextBox.delete(\"0\", \"end\")\r\n self.cTextBox.insert(\"0\", conversion) \r\n\r\n def cToF(self):\r\n conversion = (float(self.cTextBox.get()) * 1.8) + 32\r\n self.fTextBox.delete(\"0\", \"end\")\r\n self.fTextBox.insert(\"0\", conversion) \r\n\r\nmy_gui = tempGUI()","repo_name":"jyoung2119/Class","sub_path":"Class/demo_labs/PythonStuff/tempCon.py","file_name":"tempCon.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"28770549116","text":"from .ExecutorBase import *\r\nfrom .dialog.ToolsDialog import ToolsDialog\r\nfrom qt import *\r\nimport time\r\nfrom PyQt4.QtGui import QDialog\r\n##########################################################################\r\n# Tooling\r\n##########################################################################\r\nclass EditToolsInContent(ExecutorBase):\r\n def execute(self):\r\n tools = self.getCurrentTools()\r\n if len(tools) < 1:\r\n return [];\r\n dialog = ToolsInContentDialogImpl(self.qtWidget_, self.sernaDoc_, tools)\r\n if QDialog.Accepted == dialog.exec_loop():\r\n return dialog.getTools()\r\n\r\n def getCurrentTools(self):\r\n tools = []\r\n tool_nodes = get_nodes(\"//prelreq/tools/tool\", self.srcDoc_)\r\n for tool_node in tool_nodes:\r\n tooln = tool_node.asGroveElement()\r\n attrs = tooln.attrs()\r\n id_val = self.structEditor_.generateId(\"%t\")\r\n idattr = get_attribute(tooln, \"id\")\r\n if not idattr:\r\n attrs.setAttribute(GroveAttr(\"id\",id_val))\r\n time.sleep(0.05)\r\n else:\r\n id_val = idattr\r\n task_key = get_datum_from_expr(\"source-key\", tool_node)\r\n vendor_code = get_datum_from_expr(\"vendor-code\", tool_node)\r\n if not vendor_code:\r\n vendor_code = \"\"\r\n tool_num = get_datum_from_expr(\"tool-num\", tool_node)\r\n tool_desc = get_datum_from_expr(\"tool-desc\", tool_node)\r\n tool_qty = get_datum_from_expr(\"tool-qty\", tool_node)\r\n tool_state = get_datum_from_expr(\"tool-state\", tool_node)\r\n tool = id_val, task_key,vendor_code, tool_num, tool_qty, tool_desc, tool_state\r\n tools.append(tool)\r\n return tools\r\n\r\n##########################################################################\r\n\r\nclass ToolsInContentDialogImpl(ToolsDialog):\r\n def __init__(self, parent, sernaDoc, tools_selection_list):\r\n ToolsDialog.__init__(self, parent)\r\n self.sernaDoc_ = sernaDoc\r\n self.parent_ = parent\r\n self.processSignal_ = True\r\n self.id_map = {}\r\n for tool in tools_selection_list:\r\n selected = False\r\n vendor_code = \"\"\r\n tool_num = \"\"\r\n task_key = \"\"\r\n stk_num = \"\"\r\n tool_desc = \"\"\r\n tool_qty = \"\"\r\n tool_state = \"\"\r\n old_qty = \"\"\r\n id_val = tool[0]\r\n if tool[1]:\r\n task_key = tool[1]\r\n if tool[2]:\r\n vendor_code = tool[2]\r\n if tool[3]:\r\n tool_num = tool[3]\r\n if tool[4]:\r\n tool_qty = tool[4]\r\n old_qty = tool_qty\r\n if tool[5]:\r\n tool_desc = tool[5]\r\n if tool[6]:\r\n tool_state = tool[6]\r\n listitem = QListViewItem(self.toolsListView_, task_key,\r\n vendor_code, tool_num, stk_num, \r\n tool_desc, old_qty, tool_state)\r\n self.id_map[listitem] = id_val\r\n #self.toolsListView_.setSelected(listitem, selected)\r\n\r\n def selectionChanged(self):\r\n if not self.processSignal_:\r\n return\r\n cur = self.toolsListView_.currentItem()\r\n if not self.toolsListView_.isSelected(cur):\r\n return\r\n deselectitems = []\r\n item = self.toolsListView_.firstChild()\r\n while item:\r\n if self.toolsListView_.isSelected(item) and cur != item and \\\r\n cur.text(1) == item.text(1) and cur.text(2) == item.text(2) and \\\r\n cur.text(3) == item.text(3) and cur.text(4) == item.text(4): \r\n deselectitems.append(item) \r\n item = item.nextSibling(item, self.toolsListView_.invisibleRootItem())\r\n self.processSignal_ = False\r\n for item in deselectitems:\r\n self.toolsListView_.setSelected(item, False, True)\r\n self.processSignal_ = True\r\n\r\n def getTools(self):\r\n tools = []\r\n item = self.toolsListView_.firstChild()\r\n while item:\r\n if self.toolsListView_.isSelected(item):\r\n tools.append(self.id_map[item].__str__())\r\n item = item.nextSibling(item, self.toolsListView_.invisibleRootItem()) \r\n return tools\r\n\r\n def help(self):\r\n self.sernaDoc_.showHelp(\"workcard-doc.html#too-dialog\")\r\n","repo_name":"taojinjing/wc-xhtml-poc","sub_path":"plug-in/workcard/workcardImpl/EditToolsInContent.py","file_name":"EditToolsInContent.py","file_ext":"py","file_size_in_byte":4479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"74150473411","text":"#from selenium import webdriver\nfrom bs4 import BeautifulSoup as bs\nfrom urllib.request import urlopen\nfrom urllib.parse import quote_plus\nimport requests\n\"\"\"\n#driver = webdriver.Chrome()\nbaseUrl = \"https://purme.org/archives/47309\"\nurl = baseUrl\nhtml = urlopen(url)\nsoup = bs(html, \"html.parser\")\nimg = soup.find_all(class_='img',limit = 2)\n\nn = 1\nfor i in img: # 이미지를 50개 저장하기 위한 반복문\n imgUrl = i['data-source'] \n with urlopen(imgUrl) as f:\n with open('C:\\Python39\\img' + url + str(n)+'.jpg','wb') as h: # 이미지 + 사진번호 + 확장자는 jpg\n img = f.read() #이미지 읽기\n h.write(img) # 이미지 저장\n n += 1\nprint('다운로드 완료')\"\"\"\n\nimport csv\nimport requests\nimport time\nfrom bs4 import BeautifulSoup\n\ndef blog_crawling(page=1):\n url = \"https://search.naver.com/search.naver?query=%ED%99%8D%EB%8C%80%20%EA%B0%9C%EB%AF%B8&nso=&where=blog&sm=tab_opt\".format(page)\n response = requests.get(url)\n\n soup = BeautifulSoup(response.text, 'html.parser')\n\n blog_post_list = []\n \n for links in soup.select('li.list-item > dl'):\n title = links.select('dt > a')\n content = links.select('dd.sh_blog_passage')\n author = links.select('dd.txt_block a')\n\n title = title[0].get('title')\n\n content = content[0].text\n\n author = author[0].text\n\n blog_post = {'author': author, 'title': title, 'content': content}\n\n blog_post_list.append(blog_post)\n\n return blog_post_list\n\ndef save_data(blog_post):\n keys = blog_post[0].keys()\n with open('blog_crawling.csv', 'w') as file:\n writer = csv.DictWriter(file, keys)\n writer.writeheader()\n writer.writerows(blog_post)\n\nblog_post_list = []\nfor i in range(1, 100, 10):\n blog_post_list.extend( blog_crawling(page=i) )\n time.sleep(2)\n\nsave_data(blog_post_list)\n\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup as bs\nimport urllib.parse\n\n\n# 네이버 검색 후 검색 결과\nbaseUrl = 'https://search.naver.com/search.naver?where=post&sm=tab_jum&query='\nplusUrl = input('검색어를 입력하세요 : ')\n# 한글 검색 자동 변환\nurl = baseUrl + urllib.parse.quote_plus(plusUrl)\nhtml = urlopen(url)\nbsObject = bs(html, \"html.parser\")\n\n# 조건에 맞는 파일을 다 출력해라\ntitle = bsObject.find_all(class_='total_info')\n\n\nfor i in title:\n print(i.attrs['title'])\n print(i.attrs['href'])\n print()","repo_name":"Canihelpme/TIL_algorithm","sub_path":"crwaling.py","file_name":"crwaling.py","file_ext":"py","file_size_in_byte":2454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"15662477531","text":"\"\"\"Module database_controllers.\"\"\"\r\nfrom pathlib import Path\r\nfrom tinydb import TinyDB\r\nfrom tinydb import where\r\n\r\nfrom models.tournament_models import Tournament\r\nfrom models.player_models import Player\r\nfrom models.tour_models import Tour\r\nfrom models.match_models import Match\r\n\r\n\r\nclass DataBase:\r\n \"\"\"Class Database.\"\"\"\r\n\r\n def save_database(self, database_name, serialized_data):\r\n \"\"\"Fonction de création de fichiers de sauvegarde pour les tournois et les joueurs.\"\"\"\r\n Path(\"save data/\").mkdir(exist_ok=True)\r\n try:\r\n db = TinyDB(f\"save data/{database_name}.json\")\r\n except FileNotFoundError:\r\n with open(f\"save data/{database_name}.json\", \"w\"):\r\n pass\r\n db = TinyDB(\"save data/\" + database_name + \".json\")\r\n\r\n db.insert(serialized_data)\r\n print(\"Sauvegarde, mise à jour effectuée avec succès.\")\r\n print()\r\n\r\n def update_tournament_database(self, database_name, serialized_data):\r\n \"\"\"Fonction de sauvgarde pour les tournois vers la base de donées.\"\"\"\r\n db = TinyDB(f\"save data/{database_name}.json\")\r\n db.update(\r\n serialized_data,\r\n where('name') == serialized_data['name']\r\n )\r\n print(f\"Tournoi {serialized_data['name']} sauvegardé, mise à jour effectuée avec succès.\")\r\n print()\r\n\r\n def update_player_rank(self, database_name, serialized_data):\r\n \"\"\"Fonction de sauvgarde pour les joueurs vers la base de donées.\"\"\"\r\n db = TinyDB(f\"save data/ {database_name}.json\")\r\n db.update(\r\n {'rank': serialized_data['rank'], 'total score': serialized_data['total score']},\r\n where('name') == serialized_data['name']\r\n )\r\n print(\r\n f\"Joueur {serialized_data['name']} {serialized_data['surname']}\\\r\n sauvegardé, mise à jour effectuée avec succès.\"\r\n )\r\n print()\r\n\r\n def loading_database(self, database_name):\r\n \"\"\"Fonction pour charger les sauvegardes de la base de données.\"\"\"\r\n try:\r\n db = TinyDB(f\"save data/{database_name}.json\")\r\n return db.all()\r\n except FileNotFoundError:\r\n pass\r\n\r\n def loading_player(self, serialized_player, loading_tournament_score=False):\r\n \"\"\"Charge un joueur.\"\"\"\r\n player = Player(\r\n serialized_player['name'],\r\n serialized_player['surname'],\r\n serialized_player['birthday date'],\r\n serialized_player['sexe'],\r\n serialized_player['rank'],\r\n serialized_player['total score']\r\n )\r\n if loading_tournament_score:\r\n player.tournament_score = serialized_player['tournament score']\r\n\r\n return player\r\n\r\n def loading_tournament(self, serialized_tournament):\r\n \"\"\"Charge un tournoi.\"\"\"\r\n load_tournament = Tournament(\r\n serialized_tournament[\"name\"],\r\n serialized_tournament[\"location\"],\r\n serialized_tournament[\"date\"],\r\n serialized_tournament[\"time control\"],\r\n [self.loading_player(\r\n player, loading_tournament_score=True\r\n ) for player in serialized_tournament[\"players\"]],\r\n serialized_tournament[\"description\"],\r\n serialized_tournament[\"number tours\"]\r\n )\r\n load_tournament.tour = self.loading_tours(serialized_tournament, load_tournament)\r\n\r\n return load_tournament\r\n\r\n def loading_tours(self, serialized_tournament, tournament):\r\n \"\"\"Charge un tours.\"\"\"\r\n load_tours = []\r\n\r\n for tour in serialized_tournament['tours']:\r\n pairs_players = []\r\n for pair in tour['pairs players']:\r\n for player in tournament.players:\r\n if player.name == pair[0]['name']:\r\n pair_player1 = player\r\n elif player.name == pair[1]['name']:\r\n pair_player2 = player\r\n pairs_players.append((pair_player1, pair_player2))\r\n load_tour = Tour(tour['name'], pairs_players, loading_match=True)\r\n\r\n load_tour.matchs = [self.loading_matchs(match, tournament) for match in tour['matchs']]\r\n load_tour.time_start = tour['time start']\r\n load_tour.time_end = tour['time end']\r\n load_tours.append(load_tour)\r\n\r\n return load_tours\r\n\r\n def loading_matchs(self, serialized_match, tournament):\r\n \"\"\"Charge un match.\"\"\"\r\n for player in tournament.players:\r\n if player.name == serialized_match['player 1']['name']:\r\n player_1 = player\r\n elif player.name == serialized_match['player 2']['name']:\r\n player_2 = player\r\n\r\n load_match = Match(pairs_players=(player_1, player_2), name=serialized_match['name'])\r\n\r\n load_match.score_player_1 = serialized_match['score player 1']\r\n load_match.score_player_2 = serialized_match['score player 2']\r\n load_match.winner = serialized_match['winner']\r\n\r\n return load_match\r\n","repo_name":"Bubhux/Projet-Manager-Chess-Tournament","sub_path":"controllers/database_controllers.py","file_name":"database_controllers.py","file_ext":"py","file_size_in_byte":5132,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"30869892279","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver import ActionChains\nimport time\n\n\ndef login(browser):\n user_id = browser.find_element(By.ID, \"ember9\")\n user_id.clear()\n user = input(\"input your username(mail address): \").strip()\n user_id.send_keys(user)\n password_id = browser.find_element(By.ID, \"ember11\")\n password_id.clear()\n password = input(\"input your password: \").strip()\n password_id.send_keys(password)\n browser.find_element(By.CLASS_NAME, \"signin-button\").click()\n\n\ndef get_class(browser):\n classes = browser.find_elements(By.CLASS_NAME, \"heading\")\n print(\"----------\")\n for x, y in enumerate(classes):\n if x == len(classes)-1:\n break\n print(str(x), \": \", y.text)\n print(\"----------\")\n choose = int(input(\"input(0-\" + str(len(classes)-2) + \") to choose the course: \"))\n while choose < 0 or choose > len(classes)-2:\n print(\"invalid number\")\n choose = int(input(\"input(0-\" + str(len(classes) - 2) + \") to choose the course: \"))\n browser.find_element(By.XPATH, \"//div[@class='zybooks-container large']/a[\" + str(choose+1) + \"]\").click()\n\n\ndef get_week(browser, action):\n xpath = \"//ul[@class='table-of-contents-list fixed-header header-absent']/li\"\n week = browser.find_elements(By.XPATH, xpath)\n choose = int(input(\"input week number(1-\" + str(len(week)) + \") or -1 to quit: \"))\n if choose == -1:\n return True\n while choose < 1 or choose > len(week):\n print(\"invalid number\")\n choose = int(input(\"input week number(1-\" + str(len(week)) + \"): \"))\n action.move_to_element(week[choose-1]).perform()\n week[choose-1].click()\n return False\n\n\ndef multiple_choice(browser, action):\n multi_choice = browser.find_elements(By.CLASS_NAME, \"zb-radio-button\")\n for x, y in enumerate(multi_choice):\n if not y.is_enabled() and not y.is_displayed():\n continue\n action.move_to_element(y).perform()\n y.click()\n\n\ndef filling(browser, action):\n show_answer_list = browser.find_elements(By.CLASS_NAME, \"show-answer-button\")\n for x, y in enumerate(show_answer_list):\n if not y.is_enabled() and not y.is_displayed():\n continue\n action.move_to_element(y).perform()\n y.click()\n time.sleep(0.1)\n y.click()\n time.sleep(0.1)\n # get answer\n answer = browser.find_elements(By.CLASS_NAME, \"forfeit-answer\")[x].text\n textarea = browser.find_elements(By.CLASS_NAME, \"ember-text-area\")[x]\n textarea.send_keys(answer)\n time.sleep(0.1)\n browser.find_elements(By.CLASS_NAME, \"check-button\")[x].click()\n time.sleep(0.5)\n\n\ndef video(browser, action):\n video_list = browser.find_elements(By.CLASS_NAME, \"start-graphic\")\n for x, y in enumerate(video_list):\n if not y.is_enabled() and not y.is_displayed():\n continue\n action.move_to_element(y).perform()\n y.click()\n time.sleep(1)\n play_button = browser.find_elements(By.CLASS_NAME, \"normalize-controls\")[x]\n # judge whether this animation is finished or not\n while True:\n time.sleep(3)\n play_button_img = browser.find_elements(By.CLASS_NAME, \"play-button\")\n if len(play_button_img) <= x: # animation is still processing\n continue\n else:\n play_button_img = play_button_img[x]\n judge_end = play_button_img.get_attribute(\"class\").find(\"rotate-180\")\n judge = play_button_img.get_attribute(\"class\").find(\"bounce\")\n if judge_end != -1: # the animation has finished\n break\n if judge != -1: # step finished\n play_button_img.click()\n\n\nif __name__ == \"__main__\":\n browser = webdriver.Chrome()\n action = ActionChains(browser)\n browser.get('https://learn.zybooks.com/library')\n # log\n login(browser)\n time.sleep(3)\n # choose class\n get_class(browser)\n time.sleep(3)\n while True:\n # choose week\n quit_judge = get_week(browser, action)\n if quit_judge:\n break\n time.sleep(1)\n # get sections inside the week\n sections = browser.find_elements(By.CLASS_NAME, \"section-title-link\")\n for i, j in enumerate(sections):\n # get into each section\n browser.find_elements(By.CLASS_NAME, \"section-title-link\")[i].click()\n time.sleep(5)\n # multiple choice\n multiple_choice(browser, action)\n print(\"finished section \" + str(i) + \"'s multiple choice problem\")\n # filling\n filling(browser, action)\n print(\"finished section \" + str(i) + \"'s filling problem\")\n # video\n video(browser, action)\n print(\"finished section \" + str(i) + \"'s video problem\")\n # back to the week page\n browser.back()\n print(\"finished section \" + str(i) + \". Progress: \" + str(i+1) + \"/\" + str(len(sections)))\n time.sleep(5)\n","repo_name":"Yujjio/Zybook_Auto_Completer","sub_path":"completer.py","file_name":"completer.py","file_ext":"py","file_size_in_byte":5093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"16631568945","text":"# coding=utf-8\n# This is a sample Python script.\n\n# Press ⌃R to execute it or replace it with your code.\n# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.\n\n\ndef print_hi(name):\n # Use a breakpoint in the code line below to debug your script.\n print(\"Hi, {0}\".format(name)) # Press ⌘F8 to toggle the breakpoint.\n\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n print_hi('PyCharm')\n\n# See PyCharm help at https://www.jetbrains.com/help/pycharm/\n\n#Hinge loss vs Empirical Risk\nimport numpy as np\nx = np.matrix([[1, 0, 1],[1, 1, 1],[1, 1, -1], [-1, 1, 1]])\ny = np.array([2, 2.7, -0.7, 2])\n\ntheta = np.array([0, 1, 2])\n\ndef hinge_loss(x, y, theta):\n z = y - np.matmul(x, theta)\n def loss(z):\n return max(0, 1-z)\n vloss = np.vectorize(loss)\n loss = vloss(z)\n return loss.mean()\n\ndef risk_loss(x, y, theta):\n z = y - np.matmul(x, theta)\n risk = np.power(z, 2)/2\n return risk.mean()\n\nhinge_loss = hinge_loss(x, y, theta)\nprint(\"Hinge loss is: \"+str(hinge_loss))\n\nrisk_loss = risk_loss(x, y, theta)\nprint(\"Risk loss is: \"+str(risk_loss))\n\nimport math\n\ndef polyterm_count(n, power):\n term_count = 0\n for d in range(1, power+1):\n current_term_count = math.comb(n+d-1, d)\n term_count += current_term_count\n print(\"Term count for dimension: \"+str(n)+\", power: \"+str(power)+\", is: \"+str(term_count))\n\npolyterm_count(150, 3)\n\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nsns.set_theme(color_codes=True)\n\ndef plot_poly():\n x = np.arange(0.1, 50, step=0.5)\n sns.regplot(x, x**2 + x**3 + x**4, order=4)\n\nplot_poly()","repo_name":"shibachenu/machine-learning-for-social-science","sub_path":"image_recognition_neural_network/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"28547663522","text":"\"\"\"\n\nПростые делители числа 13195 - это 5, 7, 13 и 29.\n\nКаков самый большой делитель числа 600851475143, являющийся простым числом?\n\nВ теории чисел, простые множители (простые делители) положительного целого числа —\nэто простые числа, которые делят это число нацело (без остатка).\n\n\"\"\"\n\nimport math\n\nimport time\n\n\n# Сначала начал писать свой начальный вариант - он оказался уже на самом начальном этапе очень тяжелым.\n# Начал гуглить. Нашел на Хабре статью: https://habr.com/ru/post/122538/ В итоге оказалось,\n# что можно использовать метод \"Решето Эратосфена\". Итого получаем следующее:\n\n\n# Получаем начальное время в секундах от начала времен для замера скорости работы данной реализации\nstart = time.time()\n\n# Идея почерпнута из метода \"Решето Эратосфена\"\n\n\nn = int(input(\"n=\"))\na = list(range(n+1))\n\na[1] = 0\nlst = []\n\ni = 2\nwhile i <= n:\n if a[i] != 0:\n lst.append(a[i])\n for j in range(i, n+1, i):\n a[j] = 0\n i += 1\n\nfor j in range(len(lst)-1,1,-1):\n if n/lst[j] == (float(n)/lst[j]):\n print(lst[j])\n break\n\n\n\n# Получаем конечное время\nprint(time.time() - start)\n\n","repo_name":"vvandriichuk/python","sub_path":"project_eilera/lesson_3.py","file_name":"lesson_3.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"8064163562","text":"\"\"\"\ncreate a data dictionary that maps distinct categorical or 'code' features\nto unique integers for retain model training and interpretation\n\"\"\"\nimport os\nimport csv\nimport json\nimport logging\nimport pickle\n\nlogger = logging.getLogger(__name__)\n\n\nclass DataDictionary():\n def __init__(self, data_dict_csv_path=None, data_dict_pkl_path=None, categorical_feature_path=None):\n self.code_cols = {}\n self.categorical_cols = {}\n self.combine_cols = []\n self.numeric_cols = []\n self.drop_cols = []\n self.code_mappings = {} \n self.data_dict_pkl_path = data_dict_pkl_path\n self.data_dict_csv_path = data_dict_csv_path\n self.categorical_feature_path = categorical_feature_path\n\n def is_categorical_var(self, col, val):\n cat_val = self.categorical_cols.get(col, None)\n if cat_val and int(val) <= int(cat_val):\n cat_col = '{}_{}'.format(col, int(val))\n return cat_col, 1\n\n return None, None\n\n\n def create_data_dict(self):\n # initial creation of pickled data dictionary\n if self.data_dict_csv_path:\n self.read_csv_data_dict()\n else:\n logger.warning(\"No input path for csv feature dictionary provided\")\n if self.data_dict_pkl_path:\n self.map_codes_to_ints()\n else:\n logger.warning(\"No output path for pickled feature mapping provided\")\n\n if self.categorical_feature_path:\n self.load_categorical_dict()\n else:\n logger.warning(\"No input path for csv categorical dictionary provided\")\n\n\n def load_data_dict(self):\n # read in precreated pickled data dictionary\n if self.data_dict_csv_path:\n self.read_csv_data_dict()\n else:\n logger.warning(\"No input path for csv feature dictionary provided\") \n if self.data_dict_pkl_path:\n self.get_code_mapping()\n else:\n logger.warning(\"No input path for pickled feature mapping provided\")\n\n\n def read_csv_data_dict(self):\n with open(self.data_dict_csv_path, \"r\") as fin:\n reader = csv.DictReader(fin)\n for row in reader:\n if (row['DataTreatment'] == 'Code'):\n self.code_cols[row['Name']] = (row['DataTreatment'], row['DataType'], row['Temporal'], row['OneHotEncoded'])\n elif (row['DataTreatment'] == 'Numeric'):\n self.numeric_cols.append(row['Name'])\n elif (row['DataTreatment'] == 'Combine'):\n self.combine_cols.append(row['Name'])\n else:\n self.drop_cols.append(row['Name']) \n\n\n def get_code_mapping(self):\n with open(self.data_dict_pkl_path, \"rb\") as fin:\n code_d = pickle.load(fin)\n self.code_mappings = dict((v,k) for k,v in code_d.items())\n\n def load_categorical_dict(self):\n # read in precreated pickled data dictionary\n if self.categorical_feature_path:\n self.read_csv_categorical_dict(self.categorical_feature_path)\n else:\n logger.warning(\"No input path for csv categorical dictionary provided\")\n\n\n def read_csv_categorical_dict(self, csv_path):\n # create dict for categorical features, {feature: n_total_levels}\n cat_name = {}\n with open(csv_path, \"r\") as fin:\n reader = csv.DictReader(fin)\n for row in reader:\n cat_name[row['Name']] = row['N']\n\n self.categorical_cols = cat_name\n\n def one_hot_encoding(self, feature):\n '''\n One-hot encoding, and rename categorical features\n :feature: dict {name: val}, e.g., {feature: 3}\n :categorical_feature_mapping: csv file with categorical features\n :return: new feature name, e.g., feature_3\n '''\n\n # create dict for categorical features, {feature: n_total_levels}\n cat_name = {}\n with open(self.categorical_feature_path, \"r\") as fin:\n reader = csv.DictReader(fin)\n for row in reader:\n cat_name[row['Name']] = row['N']\n\n (name, val), = feature.items()\n\n if cat_name.get(name):\n return '{}_{}'.format(name, val)\n\n def map_codes_to_ints(self):\n '''\n map one hot encoded features (binary) to integer feature names\n dump it to a pickle file\n \"param outpath: data_dict_pkl_path\n :return: pickle file with one hot encoded features,\n e,g, {1: feature1, 2: feature2, ...}\n '''\n all_features = sorted(list(self.code_cols.keys()) + self.numeric_cols)\n with open(self.data_dict_pkl_path, \"wb\") as fin:\n pickle.dump(dict((i,all_features[i]) for i in range(len(all_features))), fin)\n\n\nif __name__ == '__main__':\n config = dict()\n cd = os.path.dirname(os.path.realpath(__file__))\n for c in ['../config_default.json', '../config.json']:\n with open(os.path.join(cd, c), 'r') as fin:\n config.update(json.load(fin))\n # create the pickled integer feature mapping from categorical and data dictionary csv files\n data_dict_csv_path = os.path.realpath(config[\"DATA_DICTIONARY\"][\"data_dict_csv\"])\n categorical_feature_path = os.path.realpath(config[\"DATA_DICTIONARY\"][\"categorical_feature\"])\n data_dict_pkl_path = os.path.realpath(config[\"DATA_DICTIONARY\"][\"data_dict\"])\n\n ddict = DataDictionary(data_dict_csv_path, data_dict_pkl_path, categorical_feature_path)\n ddict.create_data_dict()\n","repo_name":"FredHutch/RelapseDataReformatting","sub_path":"scripts/map_categorical_features.py","file_name":"map_categorical_features.py","file_ext":"py","file_size_in_byte":5529,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"7541913609","text":"\"\"\"\nForward models for both 1D and 2D CSDs.\n\"\"\"\n\nimport autograd.numpy as np\nimport scipy.integrate\n\n\ndef b_fwd_1d(r, R):\n \"\"\"\n Computes forward model weight function b.\n :param r: vector of differences between spatial coords\n :param R: cylinder radius parameter R\n :return: values of b_fwd for elements in r (same shape as r)\n \"\"\"\n b = np.sqrt(np.square(np.divide(r, R)) + 1) - np.sqrt(np.square(np.divide(r, R)))\n return b\n\n\ndef fwd_model_1d(arr, x, z, R, varsigma=1):\n \"\"\"\n Apply fwd model to arbitrary space-time array arr; predicts at same time points as input.\n (Note: want dense input within integral bounds to get good results!)\n :param arr: matrix (nz, nt)\n :param x: x vector of observations\n :param z: z vector for predictions (can differ from x)\n :param R: forward model parameter\n :param varsigma: scalar conductivity\n :return: matrix (nx, nt)\n \"\"\"\n nx, nt = arr.shape\n nz = z.shape[0]\n res = np.zeros((nz, nt))\n for t in range(nt):\n arr_tmp = np.squeeze(arr[:, t])[:,None]\n for i in range(nz):\n A = b_fwd_1d(z[i]-x, R)\n res[i, t] = scipy.integrate.trapz(np.squeeze(A * arr_tmp), x=np.squeeze(x), axis=0)\n return R/(2*varsigma) * res\n\n\ndef b_fwd_2d(delta1, delta2, R, eps, w=None):\n \"\"\"\n Computes b weight function from forward model for parameters R, epsilon (to handle singularity).\n :param delta1: differences between spatial coords dimension 1 (vector)\n :param delta2: differences between spatial coords dimension 2 (vector)\n :param R: parameter R\n :param eps: distance of zero charge between array and CSD to handle singularity\n :return: values of b_fwd for elements in delta1, delta2\n \"\"\"\n if w is None:\n w = np.array(np.sqrt( np.square(delta1) + np.square(delta2) ))\n wt = np.log(R+eps+np.sqrt((R+eps)**2 + w**2)) - np.log(eps+np.sqrt(eps**2 + w**2))\n return wt\n\n\ndef fwd_model_2d(arr, x1, x2, z, R, eps, varsigma=1):\n \"\"\"\n Apply fwd model to space-time array arr (must be on grid of spatial locs); predicts at same time points as input.\n (Note: want dense input within integral bounds to get good results!) Output can be requested on non-grid.\n :param arr: matrix (nx1, nx2, nt)\n :param x1: x1 (nx1, 1) vector of observation spatial locations\n :param x2: x2 (nx2, 1) vector of observation spatial locations\n :param z: z (nz, 2) matrix of predicted spatial locations\n :param R: forward model parameter\n :param eps: forward model singularity parameter\n :param varsigma: scalar conductivity\n :return: matrix (nz, nt)\n \"\"\"\n nt = arr.shape[2]\n nz = z.shape[0]\n res = np.zeros((nz, nt))\n for t in range(nt):\n arr_tmp = np.squeeze(arr[:, :, t]) # (nx1, nx2)\n for i in range(nz):\n deltax1 = z[i,0] - x1 # (nx1, 1)\n deltax2 = z[i,1] - x2.T # (1, nx2)\n wt = b_fwd_2d(deltax1, deltax2, R, eps)\n toint = wt * arr_tmp # (nx1, nx2)\n res[i, t] = scipy.integrate.trapz(scipy.integrate.trapz(toint, x=np.squeeze(x1), axis=0), x=np.squeeze(x2), axis=0)\n return res #/(4*np.pi*varsigma)","repo_name":"natalieklein/gpcsd","sub_path":"src/gpcsd/forward_models.py","file_name":"forward_models.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"41"} +{"seq_id":"40418359324","text":"def solution(n, costs):\n sortlist = sorted(costs, key=lambda x: (x[2], x[0]))\n\n select = set()\n select.add(sortlist[0][0])\n answer = 0\n\n while len(select) != n:\n for i in sortlist:\n if i[0] in select and i[1] in select:\n continue\n if i[0] in select or i[1] in select:\n select.update([i[0], i[1]])\n answer += i[2]\n break\n else:\n print(i)\n\n return answer\n","repo_name":"2JooYeon/Algorithm_Study","sub_path":"InKyeong/2021하반기/greedy/210830_프로그래머스_Q42861_섬 연결하기.py","file_name":"210830_프로그래머스_Q42861_섬 연결하기.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"41"} +{"seq_id":"18888548814","text":"import argparse, os, json, time\nimport s3fs, boto3, glob\nfrom progressbar import ProgressBar, FileTransferSpeed, Bar, Percentage, ETA, Timer\nimport threading\n\n\nclass Progress(object):\n def __init__(self, bar):\n self._bar = bar\n self._seen_so_far = 0\n self._lock = threading.Lock()\n\n def __call__(self, bytes_amount):\n with self._lock:\n self._seen_so_far += bytes_amount\n self._bar.update(self._seen_so_far)\n\n\ndef upload_file(f, file, size, bucket, path, s3_boto):\n print(size)\n print(file)\n bar = ProgressBar(\n max_value=size,\n widgets=[FileTransferSpeed(), Bar(), Percentage(), Timer(), ETA()],\n )\n s3_boto.upload_fileobj(f, bucket, f\"{file}\", Callback=Progress(bar))\n\n # time.sleep(10)\n # uploaded_size = s3.du(f\"{bucket}/{file}\")\n # assert size == uploaded_size\n\n\nparser = argparse.ArgumentParser(\n description=\"Adds S3-stored pilot files to backup on AWS Glacier Deep Archive\"\n)\nparser.add_argument(\"folder\", nargs=1, help=\"Folder\")\nparser.add_argument(\n \"file_location\",\n nargs=1,\n help=\"Location where the files are, either 'local' or 'OSN'\",\n)\n\nargs = parser.parse_args()\nfolder = args.folder[0]\nlocation = args.file_location[0]\n\nbucket = \"caltechdata-backup\"\npath = \"ini210004tommorrell/\"\ns3 = s3fs.S3FileSystem()\ncurrent = s3.ls(f\"{bucket}/{path}{folder}\")\nexisting = []\nfor ex in current:\n existing.append(ex.split(f\"{bucket}/\")[1])\n second_level = s3.ls(ex)\n for sec in second_level:\n existing.append(sec.split(f\"{bucket}/\")[1])\n third_level = s3.ls(sec)\n for th in third_level:\n existing.append(th.split(f\"{bucket}/\")[1])\n\n# Now use boto version of backup location to ensure copying works\ns3_boto = boto3.client(\"s3\")\n\nif location == \"local\":\n backup_source = glob.glob(f\"{folder}/*\")\n for file in backup_source:\n if os.path.isfile(file):\n if file not in existing:\n size = os.path.getsize(file)\n print(file)\n with open(file, \"rb\") as f:\n upload_file(f, f\"{path}{file}\", size, bucket, path, s3_boto)\n else:\n for fil in glob.glob(f\"{file}/*\"):\n if fil not in existing:\n print(fil)\n size = os.path.getsize(fil)\n with open(fil, \"rb\") as f:\n upload_file(f, f\"{path}{fil}\", size, bucket, path, s3_boto)\n\nelif location == \"OSN\":\n endpoint = \"https://renc.osn.xsede.org/\"\n osn_s3 = s3fs.S3FileSystem(anon=True, client_kwargs={\"endpoint_url\": endpoint})\n # Find the files to backup\n backup_source = osn_s3.glob(f\"{path}{folder}/*\")\n for file in backup_source:\n size = osn_s3.info(file)[\"Size\"]\n if size > 0:\n # we have a fille\n if file not in existing:\n print(file)\n with osn_s3.open(file, \"rb\") as f:\n upload_file(f, file, size, bucket, path, s3_boto)\n else:\n # We have a directory, get all the files under it\n for fil in osn_s3.glob(f\"{file}/*\"):\n size = osn_s3.info(fil)[\"Size\"]\n if size > 0:\n if fil not in existing:\n print(fil)\n with osn_s3.open(fil, \"rb\") as f:\n upload_file(f, fil, size, bucket, path, s3_boto)\n else:\n for th in osn_s3.glob(f\"{fil}/*\"):\n size = osn_s3.info(th)[\"Size\"]\n if size > 0:\n if th not in existing:\n print(th)\n with osn_s3.open(th, \"rb\") as f:\n upload_file(f, th, size, bucket, path, s3_boto)\n else:\n for fo in osn_s3.glob(f\"{th}/*\"):\n size = osn_s3.info(fo)[\"Size\"]\n if fo not in existing:\n print(fo)\n with osn_s3.open(fo, \"rb\") as f:\n upload_file(f, fo, size, bucket, path, s3_boto)\nelse:\n print(f\"{args.file_location} is not a supported file location\")\n","repo_name":"caltechlibrary/caltechdata_backup","sub_path":"backup_pilot.py","file_name":"backup_pilot.py","file_ext":"py","file_size_in_byte":4318,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"30060678417","text":"from __future__ import absolute_import\n\nimport json\nimport logging\nimport os\nimport time\n\nfrom kafka import KafkaConsumer\nfrom monotonic import monotonic as time_monotonic\nfrom prometheus_client import Counter\nfrom requests import HTTPError\nfrom yaml import YAMLError\n\nfrom fiaas_deploy_daemon.log_extras import set_extras\nfrom ..base_thread import DaemonThread\nfrom ..deployer import DeployerEvent\nfrom ..specs.factory import InvalidConfiguration\n\nALLOW_WITHOUT_MESSAGES_S = int(os.getenv('ALLOW_WITHOUT_MESSAGES_MIN', 30)) * 60\nDEFAULT_NAMESPACE = u\"default\"\n\n\nclass Consumer(DaemonThread):\n \"\"\"Listen for pipeline events and generate AppSpecs for the deployer\n\n Requires the following environment variables:\n - KAFKA_PIPELINE_SERVICE_HOST: Comma separated list of kafka brokers\n - KAFKA_PIPELINE_SERVICE_PORT: Port kafka listens on\n \"\"\"\n\n def __init__(self, deploy_queue, config, reporter, spec_factory, app_config_downloader, lifecycle):\n super(Consumer, self).__init__()\n self._logger = logging.getLogger(__name__)\n self._deploy_queue = deploy_queue\n self._consumer = None\n self._config = config\n self._environment = config.environment\n self._reporter = reporter\n self._spec_factory = spec_factory\n self._app_config_downloader = app_config_downloader\n self._lifecycle = lifecycle\n self._last_message_timestamp = int(time_monotonic())\n\n def __call__(self):\n if self._consumer is None:\n self._connect_kafka()\n message_counter = Counter(\"pipeline_message_received\", \"A message from pipeline received\")\n deploy_counter = Counter(\"pipeline_deploy_triggered\", \"A message caused a deploy to be triggered\")\n for message in self._consumer:\n self._handle_message(deploy_counter, message, message_counter)\n\n def _handle_message(self, deploy_counter, message, message_counter):\n message_counter.inc()\n self._last_message_timestamp = int(time_monotonic())\n event = self._deserialize(message)\n self._logger.debug(\"Got event: %r\", event)\n if event[u\"environment\"] == self._environment:\n app_name = event[u\"project_name\"]\n try:\n lifecycle_subject = self._lifecycle.initiate(app_name=app_name,\n namespace=DEFAULT_NAMESPACE,\n deployment_id=self._deployment_id(event))\n except (NoDockerArtifactException, NoFiaasArtifactException):\n self._logger.debug(\"Ignoring event %r with missing artifacts\", event)\n return\n\n try:\n app_spec = self._create_spec(event)\n set_extras(app_spec)\n self._check_app_acceptable(app_spec)\n self._add_deployment_label(app_spec)\n self._deploy_queue.put(DeployerEvent(\"UPDATE\", app_spec, lifecycle_subject))\n self._reporter.register(app_spec, event[u\"callback_url\"])\n deploy_counter.inc()\n except YAMLError:\n self._logger.exception(\"Failure when parsing FIAAS-config for application %s\", app_name)\n self._lifecycle.failed(lifecycle_subject)\n except InvalidConfiguration:\n self._logger.exception(\"Invalid configuration for application %s\", app_name)\n self._lifecycle.failed(lifecycle_subject)\n except HTTPError:\n self._logger.exception(\"Failure when downloading FIAAS-config for application %s\", app_name)\n self._lifecycle.failed(lifecycle_subject)\n except (NotWhiteListedApplicationException, BlackListedApplicationException) as e:\n self._logger.warn(\"App %s not deployed. %s\", app_name, str(e))\n\n def _check_app_acceptable(self, app_spec):\n if self._config.whitelist and app_spec.name not in self._config.whitelist:\n raise NotWhiteListedApplicationException(\n \"{} is not a in whitelist for this cluster\".format(app_spec.name))\n if self._config.blacklist and app_spec.name in self._config.blacklist:\n raise BlackListedApplicationException(\n \"{} is banned from this cluster\".format(app_spec.name))\n\n def _connect_kafka(self):\n self._consumer = KafkaConsumer(\n \"internal.pipeline.deployment\",\n bootstrap_servers=self._build_connect_string(\"kafka_pipeline\")\n )\n\n def _create_spec(self, event):\n artifacts = self._artifacts(event)\n name = event[u\"project_name\"]\n image = artifacts[u\"docker\"]\n deployment_id = self._deployment_id(event)\n fiaas_url = artifacts[u\"fiaas\"]\n teams = event[u\"teams\"]\n tags = event[u\"tags\"]\n\n set_extras(app_name=name, namespace=DEFAULT_NAMESPACE, deployment_id=deployment_id)\n\n app_config = self._app_config_downloader.get(fiaas_url)\n\n return self._spec_factory(name, image, app_config, teams, tags, deployment_id,\n DEFAULT_NAMESPACE, None, None)\n\n def _artifacts(self, event):\n artifacts = event[u\"artifacts_by_type\"]\n if u\"docker\" not in artifacts:\n raise NoDockerArtifactException()\n if u\"fiaas\" not in artifacts:\n raise NoFiaasArtifactException()\n return artifacts\n\n def _deployment_id(self, event):\n artifacts = self._artifacts(event)\n image = artifacts[u\"docker\"]\n deployment_id = image.split(\":\")[-1][:63].lower()\n return deployment_id\n\n def _build_connect_string(self, service):\n host, port = self._config.resolve_service(service)\n connect = \",\".join(\"{}:{}\".format(host, port) for host in host.split(\",\"))\n return connect\n\n def is_alive(self):\n return super(Consumer, self).is_alive() and self._is_receiving_messages()\n\n def _is_receiving_messages(self):\n # TODO: this is a hack to handle the fact that we sometimes seem to loose contact with kafka\n self._logger.debug(\"No message for %r seconds\", int(time_monotonic()) - self._last_message_timestamp)\n return self._last_message_timestamp > int(time_monotonic()) - ALLOW_WITHOUT_MESSAGES_S\n\n @staticmethod\n def _deserialize(message):\n return json.loads(message.value)\n\n @staticmethod\n def _add_deployment_label(app_spec):\n app_spec.labels.deployment[\"fiaas/app_deployed_at\"] = str(int(round(time.time())))\n\n\nclass NoDockerArtifactException(Exception):\n pass\n\n\nclass NoFiaasArtifactException(Exception):\n pass\n\n\nclass NotWhiteListedApplicationException(Exception):\n pass\n\n\nclass BlackListedApplicationException(Exception):\n pass\n","repo_name":"vanphuong12a2/fiaas-deploy-daemon","sub_path":"fiaas_deploy_daemon/pipeline/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":6762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"41"} +{"seq_id":"38384038573","text":"import sqlalchemy\nimport logging\nfrom sqlalchemy import create_engine\nfrom sqlalchemy import update\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.dialects import mysql\nfrom sqlalchemy.exc import IntegrityError, OperationalError\nfrom helpers.mysql_connection_string import mysql_connection_string\n\n\nclass Connection(object):\n \"\"\"Database connection class\"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"Init method, needs DB_URL inside kwargs for correct work\"\"\"\n self._db_address = None\n\n self.session = None\n self._engine = None\n self.logger = logging.getLogger(__name__)\n logging.basicConfig(level=logging.INFO)\n\n try:\n self._db_address = mysql_connection_string()\n except KeyError as ke:\n self.logger.error(ke)\n\n if not self.connect():\n self.logger.critical(\"DB_URL: {}\".format(self._db_address))\n raise Exception(\"Database is disconnected\")\n\n def connect(self) -> bool:\n \"\"\"Connects to database\n\n Returns:\n True if connected correctly\n \"\"\"\n try:\n self._engine = create_engine(self._db_address, encoding=\"UTF-8\")\n session = sessionmaker(bind=self._engine, autocommit=True)\n self.session = session()\n\n # will raise exception if cannot select\n self.session.execute(\"SELECT 1\")\n except sqlalchemy.exc.OperationalError as oe:\n self.logger.error(\"Engine is not created {}\".format(oe))\n return False\n return True\n\n def close(self) -> None:\n \"\"\"Closes current session\"\"\"\n self.session.close()\n\n def insert(self, item, model):\n \"\"\"Inserts item to db model\n\n :param item: item to be inserted\n :param model: table model to insert item to\n \"\"\"\n insert_stmt = mysql.insert(model).values(**item)\n upd_stmt = insert_stmt.on_duplicate_key_update(**item)\n try:\n self.session.execute(upd_stmt)\n except OperationalError as op:\n self.logger.error(f\"Insert failed: {op}\")\n except IntegrityError as ie:\n self.logger.error(f\"Insert failed: {ie}\")\n\n def update(self, item, model):\n \"\"\"Updates item in db model\n\n :param item: item to be updated\n :param model: table model to update item to\n \"\"\"\n upd_stmt = update(model).values(**item).where(model.id == item[\"id\"])\n try:\n self.session.execute(upd_stmt)\n except OperationalError as op:\n self.logger.error(\"Update failed: {}\".format(op))\n","repo_name":"dmkovtun/text-splitter","sub_path":"src/database/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":2610,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"4966004486","text":"import numpy as np\nfrom matplotlib import pyplot as plt\n\nV_rms = 220 # rms voltage\nLightbulb_wattage = 100\nI_rms = Lightbulb_wattage/V_rms\nmu = 1.25e-6\n\nwire_y = 0.2 # the two wires are at plus and minus 0.2 m\n\n\n# use biot-savart simplified solution assuming infinite, straight wires\ndef biot_savart(r):\n return mu*I_rms/(2*np.pi*r)\n\n\n# construct grid\ny_space = np.linspace(-2*wire_y, 2*wire_y, 100)\n\nB = []\nfor y in y_space:\n # they two wires constructively interfere\n B.append(biot_savart(y - wire_y) - biot_savart(y + wire_y))\n\nB = np.array(B)\nplt.plot(y_space, B*1e6)\nplt.show()\n\n\ndef calculate_B_at(y):\n return np.interp(y, y_space, B)\n\n\nR = 0.17/2 # radius of coil in meters\nR2 = R**2\n\n\ndef integral_of_half_circle_between(x1, x2):\n return 0.5*np.sqrt(R2 - x2**2)*x2 + 0.5*R2*np.arcsin(x2/R) - (0.5*np.sqrt(R2 - x1**2)*x1 + 0.5*R2*np.arcsin(x1/R))\n\n\ndef is_inside_circle(x_, y_):\n return (x_**2 + y_**2) < R2\n\n\ndef rect_area_inside_circle(center, stepsize):\n # always use positive quadrant\n center = np.abs(center)\n # since it's symmetric always use x<=y\n center = np.sort(center)\n x1 = center[0] - stepsize/2\n x2 = center[0] + stepsize/2\n y1 = center[1] - stepsize/2\n y2 = center[1] + stepsize/2\n if not is_inside_circle(x1, y1): # completely outside circle\n return 0\n if is_inside_circle(x2, y2): # completely inside circle\n return stepsize**2\n\n \"\"\"\n now Let's say we have this rectangle\n y2 ________________________\n |a \\ | \n | \\ | \n | \\ | \n | \\ | \n | \\ | \n | \\ | \n | \\ b| \n y1 ------------------------\n x1 x2\n \n we already know that (x1, y1) is inside circle and (x2, y2) is outside\n that leaves 4 possibilities depending on (x1, y2) and (x2, y1),\n both inside, both outside, and either one inside but other outside\n let's call the corners in question a and b\n \n simplest case is a outside, b inside, then it is the integral of half circle between x1 and x2\n and then subtract th rectangle between x1 and x2 with height y1\n \n also simple is a inside b outside (pictured above) in that case it is about flipping the axis and\n using same logic, it's the integral of half circle between y1 and y2 minus the rectangle\n \n both outside is trickier, then find the intersection of half circle and x=x1 , call it y_i\n the area will be the integarl of half circle from y1 to y_i minus x1*(y_i-y1)\n \n both inside is then simple just do the integral minus rectangle below minus the rectangle above\n \"\"\"\n a = is_inside_circle(x1, y2)\n b = is_inside_circle(x2, y1)\n\n # print(a,b)\n if a:\n if b:\n # print(a,b)\n return integral_of_half_circle_between(x1, x2) - y1*stepsize \\\n - rect_area_inside_circle(np.array(center) + np.array([0, stepsize]), stepsize)\n else:\n #\n return integral_of_half_circle_between(y1, y2) - x1*stepsize\n else:\n if b:\n return integral_of_half_circle_between(x1, x2) - y1*stepsize\n else:\n y_i = np.sqrt(R**2 - x1**2)\n # print(y_i)\n return integral_of_half_circle_between(y1, y_i) - (y_i-y1)*x1\n\n\nstepsize = R/32\ngrid = np.arange(-R+stepsize/2, R, stepsize)\nfrom itertools import product\nflux = 0\nfor x, y in product(grid, grid):\n\n \"\"\" now to calculate how much of the rectangle is inside the coil\"\"\"\n A = rect_area_inside_circle((x, y), stepsize)\n\n B_here = calculate_B_at(y)\n print(B_here)\n quit()\n flux += B_here*A\n\nprint(\"flux with integral vs flux with center value times area: \", flux, np.pi*R2*calculate_B_at(0))\nI2flux = flux/I_rms\nprint(\"constant to get flux from current:\", I2flux)\n\"\"\"\nthe flux_rms through the coil at I_rms is thus known, the emf in the coil will be N*dflux/dt.\nhowever, I should be considered as the sum of frequency components, measured via fft\ngiven by arrays I_fs anf I_as for frequency and amplitude of each component.\n\nI(t) is then sum of I_as[i]*sin(2pi*I_fs[i]*t) and the derivative is then\nemf(t) = sum of N*I_as[i]*2pi*I_fs[i]*cos(2pi*I_fs[i]*t)\n\n\"\"\"\n","repo_name":"Steinarr134/MagneticFields","sub_path":"I_Coil_in_cable_running_lightbulb_simpleBiotSavart.py","file_name":"I_Coil_in_cable_running_lightbulb_simpleBiotSavart.py","file_ext":"py","file_size_in_byte":4371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"11094265823","text":"import discord\nimport pickle\nimport random\nimport os\n\nintents = discord.Intents.default()\nintents.members = True\n\n\ntoken = \"NjgxNjM4ODc2ODgzOTc2Mjcz.XlRXrA.HwKKAiDUHi_gvwCo63TqD5qz6Qw\"\n\nbot = discord.Client(intents=intents)\n\ndef create_embed(title, description, color=0, img=\"\", thumb=\"\"):\n embed = discord.Embed()\n embed.title = title\n embed.description = description\n embed.colour = color\n if(img != \"\"):\n embed.set_image(url = img)\n if(thumb != \"\"):\n embed.set_thumbnail(url = thumb)\n return embed\n\n#load an save function \ndef load_file(files):\n with open(files, 'rb') as f:\n p = pickle.load(f)\n return p\n\ndef save_file(files, save):\n with open(files, 'wb') as f:\n pickle.dump(save, f)\n\n#search file by name\ndef find(name, path):\n for root, dirs, files in os.walk(path):\n if name in files:\n return os.path.join(root, name)\n\n#On bot ready\n@bot.event\nasync def on_ready():\n #Change Activity\n await bot.change_presence(activity=discord.Game('Humeur bot'))\n print(\"Author : Nzo\\nVersion : 1.0\")\n print(\"Bot is ready \\n----------\")\n\n\n\n#On message \n@bot.event\nasync def on_message(message):\n msg_split = message.content.split(\" \")\n if message.content.startswith(\"!nickname\"):\n name_list = load_file(\"nickname_list.data\")\n\n nbr = random.randint(0, len(name_list) - 1)\n nickname = name_list[nbr]\n \n #Embed creation \n embed = discord.Embed( title= f\"**{message.author}** Voici ton nouveau pseudo **{nickname}**\", colour=discord.Colour.blue(),)\n\n \n for file in os.listdir(\"image/\"):\n if file.startswith(f\"{nickname}\"):\n search_file = file\n\n try:\n file = discord.File(f\"image/{search_file}\", filename=f\"{search_file}\")\n embed.set_image(url=f\"attachment://{search_file}\")\n find = True\n except:\n find = False\n\n if find == True:\n await message.channel.send(file=file, embed=embed)\n\n else:\n await message.channel.send(embed=embed)\n\n \n #remove nickname from list \n name_list.remove(nickname)\n save_file(\"nickname_list.data\", name_list)\n\n await message.author.edit(nick=nickname)\n\n if message.content.startswith(\"!reaction\"):\n await message.delete()\n embed = create_embed(\"Ajout réaction role\", \"Merci d'indiquer l'id du Message qui doit avoir la réaction !\") \n msg_embed = await message.channel.send(embed = embed)\n while True:\n msg_response = await bot.wait_for('message')\n if msg_response.author == message.author :\n await msg_embed.delete()\n await msg_response.delete()\n msg_reaction = await bot.get_channel(message.channel.id).fetch_message(int(msg_response.content))\n await msg_reaction.add_reaction('🧃')\n \n break\n else:\n continue \n save_file(\"reaction_id.data\", msg_response.content)\n \n \n@bot.event\n#on reaction add\nasync def on_raw_reaction_add(payload):\n #If user is bot \n if payload.user_id == bot.user.id:\n return\n if payload.emoji.name == \"🧃\":\n reaction_message_id = load_file(\"reaction_id.data\")\n if payload.message_id == int(reaction_message_id):\n guild = bot.get_guild(payload.guild_id)\n user = await bot.fetch_user(payload.user_id)\n ex_nickname = user.name\n channel = bot.get_channel(payload.channel_id)\n member = guild.get_member(int(payload.user_id))\n await member.edit(nick=f\"🧃 {ex_nickname}\")\n\nbot.run(process.env.TOKEN)","repo_name":"Biwwo/yogourt-bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"17845337124","text":"from EmoPy.src.data_generator import DataGenerator\nfrom EmoPy.src.directory_data_loader import DirectoryDataLoader\nfrom EmoPy.src.neuralnets import ConvolutionalLstmNN\nfrom pkg_resources import resource_filename\n\nvalidation_split = 0.15\n\nraw_dimensions = (48, 48)\ntarget_dimensions = (64, 64)\nchannels = 1\nverbose = True\n\nprint('--------------- Convolutional LSTM Model -------------------')\nprint('Loading data...')\ndirectory_path = resource_filename('EmoPy.examples',\"image_data/sample_image_series_directory\")\ndata_loader = DirectoryDataLoader(datapath=directory_path, validation_split=validation_split, time_delay=2)\ndataset = data_loader.load_data()\n\nif verbose:\n dataset.print_data_details()\n\nprint('Preparing training/testing data...')\ntrain_images, train_labels = dataset.get_training_data()\ntrain_gen = DataGenerator(time_delay=dataset.get_time_delay()).fit(train_images, train_labels)\ntest_images, test_labels = dataset.get_test_data()\ntest_gen = DataGenerator(time_delay=dataset.get_time_delay()).fit(test_images, test_labels)\n\nprint('Training net...')\nmodel = ConvolutionalLstmNN(target_dimensions, channels, dataset.get_emotion_index_map(), time_delay=dataset.get_time_delay())\nmodel.fit_generator(train_gen.generate(target_dimensions, batch_size=5),\n test_gen.generate(target_dimensions, batch_size=5),\n epochs=5)\n\n## if you want to save a graph of your model layers.\nmodel.save_model_graph()\n\n# Save model configuration\n# model.export_model('output/conv_lstm_model.json','output/conv_lstm_weights.h5',\"output/conv_lstm_emotion_map.json\", emotion_map)\n","repo_name":"thoughtworksarts/EmoPy","sub_path":"EmoPy/examples/convolutional_lstm_model.py","file_name":"convolutional_lstm_model.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","stars":888,"dataset":"github-code","pt":"41"} +{"seq_id":"15298119734","text":"# -*- coding:utf-8 -*-\n\nimport sys\nimport cv2 as cv\nimport numpy as np\nimport os\nfrom datetime import datetime\nfrom functools import partial\n\n# filename = os.environ[\"HOME\"]+\"/Downloads/coi_1cm_ascii.pcd\"\nfilename = sys.argv[1]\nres = 0.05\nsize = 200.0\n\n\ndef getPoint(line):\n return map(float, line.rstrip().split(\" \"))\n\n\ndef getIndex(x, y):\n return int((x+size/2.0)/res), int((size/2.0-y)/res)\n\n\nif \"__main__\" == __name__:\n print(\"Hello world!\")\n print(\"start: \", datetime.now(), filename)\n # (縦,横)\n img = np.zeros((int(size/res), int(size/res), 1), dtype=np.uint8)\n img[:, :] = 255\n # (天井からの距離,左壁からの距離)\n # img[(10,5)] = [255]\n # img[10,5] = [255,255,255]\n # 表示して[ESC]が押されるまで待つ\n # img = np.zeros((2500,2500,3), dtype=np.uint8)\n print(img.dtype)\n\n buffer = 2 ** 16\n with open(filename, \"r\") as f:\n row_length = sum(x.count('\\n') for x in iter(partial(f.read, buffer), ''))\n print(\"Row length is \" + str('{:,}'.format(row_length)))\n\n with open(filename, \"r\") as pcd:\n # ヘッダーとばす\n # head = \"\"\n # while \"DATA\" != head:\n # head = pcd.readline().rstrip().split(\" \")[0]\n i = 0\n line = pcd.readline()\n while line:\n line = np.array(line.replace(\"\\n\", \"\").split(\" \")).astype('f8')\n # print(line[3], line[4], line[5])\n if -size / 2 < line[2] < size / 2 and -size / 2 < line[3] < size / 2 and line[4] < 3.0:\n x, y = getIndex(line[2], line[3])\n if 0 < img[(y, x)]:\n img[(y, x)] -= 1\n line = pcd.readline()\n if 0 == i % 50000:\n print(\"line num : \" + str('{:,}'.format(i)) + \"/\" + str('{:,}'.format(row_length)))\n print(line)\n i += 1\n print(\"end converting\")\n print(\"end: \", datetime.now(), filename)\n cv.imwrite(str(filename.split(\".\")[0]) + \".pgm\", img)\n cv.imshow(\"image\", img)\n while cv.waitKey(33) != 27:\n pass\n\n","repo_name":"Matsukoh/3Dto2DProjection","sub_path":"projection.py","file_name":"projection.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"15792633195","text":"#!/usr/bin/python3\n\"\"\"Make join between cities and states and show speficic colum.\"\"\"\nimport MySQLdb\nfrom sys import argv\n\n# connect to db\nif __name__ == \"__main__\":\n conn = MySQLdb.connect(\n host=\"localhost\",\n port=3306,\n user=argv[1],\n passwd=argv[2],\n db=argv[3],\n charset=\"utf8\"\n )\n # Build string for make safety query selecting speficic colunm\n if \";\" not in argv[4]:\n query = \"SELECT cities.name\\\n FROM cities\\\n INNER JOIN states\\\n ON cities.state_id=states.id\\\n WHERE states.name='{}'\".format(argv[4])\n # Getting a cursor in MySQLdb python\n cur = conn.cursor()\n # Executing db queries where nama starting in N or n\n cur.execute(query)\n # Obtaining all result of queries\n query_table = cur.fetchall()\n # Printing the result one to one only if starting arg[4]\n s = \"\"\n for row in query_table:\n print(s, end=\"\")\n print(\"{}\".format(row[0]), end=\"\")\n s = \", \"\n print(\"\")\n # Close conection to cursor\n cur.close()\n # Close conection to db\n conn.close()\n","repo_name":"JoseAVallejo12/holbertonschool-higher_level_programming","sub_path":"0x0F-python-object_relational_mapping/5-filter_cities.py","file_name":"5-filter_cities.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"17304932446","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: Elmir Hodzic\n\"\"\"\n\nimport operator\n\nrecenica = \"Algorithm of Shannon - Fanovog coding implementation.\";\n\n\ndef built_dict(s):\n dictionary = {};\n \n for i in range(len(s)):\n if recenica[i] in dictionary:\n dictionary[s[i]] += 1;\n else:\n dictionary[s[i]] = 1;\n \n return dictionary;\n\ndef sort_dict(d):\n sorted_dict = sorted(d.items(), key=operator.itemgetter(1), reverse = True);\n return sorted_dict;\n\ndef initialize_list_of_codes(s):\n l = {};\n for i in range(len(s)):\n l[s[i][0]] = '';\n return l;\n \ndef sum_list_toupples(l, a, b):\n sum = 0\n for i in range(a, b):\n sum += l[i][1];\n return sum;\n\ndef divide_list(l, start, end):\n for i in range(1, end - start):\n if sum_list_toupples(l, start, start + i) >= sum_list_toupples(l, start + i, end):\n return start + i\n return -1;\n\ndef one_list_to_two(l, index):\n l1 = [];\n l2 = [];\n \n for i in range(0, index):\n l1.append(l[i]);\n \n for i in range(index, len(l)):\n l2.append(l[i]);\n \n return l1, l2;\n\ndef add_binary(dictionary,l, c):\n for i in range(len(l)):\n dictionary[l[i][0]] += c;\n\ndef make_shannon_codes(l, list_of_codes): \n left = [];\n right = [];\n (left, right) = one_list_to_two(l, divide_list(l, 0, len(l))); \n add_binary(list_of_codes, left, '0'); \n add_binary(list_of_codes, right, '1'); \n print(left, right) \n if len(right) > 1: \n make_shannon_codes(right, list_of_codes); \n\n if len(left) > 1: \n make_shannon_codes(left, list_of_codes);\n \n\ndef ShannonFano(string):\n d = built_dict(string)\n sorted_dict = sort_dict(d)\n list_of_codes = initialize_list_of_codes(sorted_dict)\n make_shannon_codes(sorted_dict, list_of_codes)\n for i in range(len(sorted_dict)):\n print(sorted_dict[i][0] ,list_of_codes[sorted_dict[i][0]], sorted_dict[i][1]);\n\nShannonFano(recenica);\n","repo_name":"ElmirHodzic/Python-examples","sub_path":"shanon-fano.py","file_name":"shanon-fano.py","file_ext":"py","file_size_in_byte":2027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"23933334457","text":"import socket\nimport pickle\nimport zlib\nimport cv2\nimport struct\nimport tkinter\nfrom tkinter import messagebox\nfrom os import walk\n\nUDP_IP = \"127.0.0.1\"\nUDP_PORT = 5005\nMESSAGE = \"Hello, World!\"\nMESSAGE_2 = \"Upload\"\n\nBUFFER_SIZE = 4096\nBUFFER_FILE = 8192\nPAYLOAD_SIZE = struct.calcsize(\">L\")\n\nTCP_IP = \"127.0.0.1\"\nTCP_PORT = 5014\n\ndef receiveVideo(sock, nombreVideo):\n isRecording = True\n while True:\n try:\n print(\"Recibiendo frame...\")\n packetSize, serverAddress = sock.recvfrom(PAYLOAD_SIZE)\n packetSize = struct.unpack(\">L\", packetSize)\n\n data = b\"\"\n print(\"Size:\", packetSize[0])\n while len(data) < packetSize[0]:\n newData, serverAddress = sock.recvfrom(BUFFER_SIZE)\n data = data + newData\n\n print(\"Actual data size received:\", len(data))\n frame = pickle.loads(zlib.decompress(data))\n\n if isRecording == True:\n cv2.imshow('ImageWindow', frame)\n\n key = cv2.waitKey(1) & 0xff\n if key == ord('p'):\n print(\"PAUSE VIDEO\")\n while True:\n\n key2 = cv2.waitKey(1) or 0xff\n cv2.imshow('ImageWindow', frame)\n\n if key2 == ord('p'):\n print(\"PLAY VIDEO\")\n break\n if key == ord('q'):\n sock.sendto(\"stop\".encode(), (UDP_IP, UDP_PORT))\n cv2.destroyAllWindows()\n break\n sendPing(sock)\n\n except socket.timeout:\n print(\"Socket timeout.\")\n break\n\n sock.close()\n print(\"Cerrando socket de transmision streaming...\")\n\n\ndef createVideoFile(bytes):\n file = open(\"video-4.mp4\", \"wb\")\n file.write(bytes)\n file.close()\n\n\ndef sendPing(sock):\n sock.sendto(\"alive\".encode(), (UDP_IP, UDP_PORT))\n\n\ndef uploadVideo(sock, videoPath):\n #Recibir el mensaje del servidor diciendo OK\n print(\"Uploading video...\")\n message, serverAddress = sock.recvfrom(BUFFER_SIZE) #El servidor debe responder con un 'OK'\n print(\"S:\", message.decode())\n\n sock.sendto(\"start\".encode(), (UDP_IP, UDP_PORT))\n\n message, serverAddress = sock.recvfrom(BUFFER_SIZE) # El servidor debe responder con un 'OK'\n\n #Abrir conexion TCP para enviar archivo\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((TCP_IP, TCP_PORT))\n\n nombre = videoPath.split('/')\n nombre = nombre[len(nombre) - 1] # Atrapo el nombre del video contenido en el path del mismo\n\n s.sendall(nombre.encode()) # Se envia el nombre del video\n\n file = open(videoPath, 'rb')\n data = file.read()\n file.close()\n\n # Enviar el tamanio del archivo para que el servidor sepa cuanto toca leer\n size = len(data)\n print(\"Size:\", size)\n size = struct.pack(\">L\", size)\n s.sendall(size) # Envio el tamaño del video\n\n s.sendall(data) #Enviamos el archivo\n\n s.close()\n tkinter.messagebox.showinfo(\"Estado de solicitud\", \"El archivo fue recibido exitosamente\")\n\n\ndef initializeVideoUpload(videoName, comboFiles):\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP\n sock.sendto(MESSAGE_2.encode(), (UDP_IP, UDP_PORT))\n\n path = './videos/' + videoName\n uploadVideo(sock, path)\n\n videosList = grabVideosList()\n print(videosList)\n print(type(videosList))\n print(\"Combo type:\", type(comboFiles))\n print(\"Combo values before,\", comboFiles['values'])\n comboFiles['values'] = videosList\n\ndef initializeVideoStream(nombreVideo):\n print(\"UDP target IP:\", UDP_IP)\n print(\"UDP target port:\", UDP_PORT)\n print(\"message:\", MESSAGE)\n\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP\n # sock.settimeout(3)\n\n print(f\"Video solicitado: {nombreVideo}\")\n\n sock.sendto(nombreVideo.encode(), (UDP_IP, UDP_PORT))\n\n receiveVideo(sock, nombreVideo)\n # createVideoFile(videoBytes)\n\n sock.close()\n\n\ndef grabVideosList():\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP\n sock.sendto('videos-list'.encode(), (UDP_IP, UDP_PORT))\n\n data, serverAddress = sock.recvfrom(BUFFER_SIZE)\n videosList = pickle.loads(data)\n print(videosList)\n return videosList\n\n\ndef grabMyVideosList():\n f = []\n for (dirpath, dirnames, filenames) in walk('./videos'):\n f.extend(filenames)\n break\n print(f)\n return f\n\n#initializeVideoStream('video-5.mp4')\n#initializeVideoUpload()\n#initializeVideoStream()\n\n","repo_name":"juanesmendez/udp-client","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4501,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"28871310872","text":"import matplotlib.pyplot as plt\r\n\r\nmaxnumero = 20 # numero de elementos a calcular\r\ncounter = 0\t # lleva la cuenta del numero de primos encontrados\r\nfibo = []\r\n\r\nfibo.append(1)\r\nfibo.append(1)\r\n\r\nfor i in range(2,maxnumero):\r\n temp = fibo[i-1]+fibo[i-2]\r\n fibo.append(temp)\r\n\r\nfor i in range(0,maxnumero):\r\n print(fibo[i])\r\n\r\nfor i in range(maxnumero-1,-1,-1):\r\n print(fibo[i])\r\n\r\nplt.plot(fibo,'ro')\r\nplt.show() \r\n","repo_name":"mariotaglia/taller-FQ2","sub_path":"python/fibonacci/fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"191493899","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.template import loader\n\nfrom ep3.models import *\n\ndef index(request):\n\tif not request.method == 'POST':\n\t\ttemplate = loader.get_template('ep3/index.html')\n\t\tform = DesenvolvedorForm()\n\t\tcontext = {'form': form}\n\t\treturn HttpResponse(template.render(context, request))\n\treturn None\n\ndef create_dev(request):\n\tform = None\n\tif request.method == 'POST':\n\t\tform = DesenvolvedorForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tdata = form.cleaned_data\n\t\t\tnew_dev = Desenvolvedor.create(data)\n\t\t\tnew_dev.save()\n\n\t\t\tnew_telefone_dev = Telefone_Desenvolvedor.create(data, new_dev)\n\t\t\tnew_telefone_dev.save()\n\n\t\t\treturn HttpResponseRedirect('/ep3/thanks/')\n\telse:\n\t\tform = DesenvolvedorForm\n\n\ttemplate_path = 'ep3/create_dev.html'\n\tcontext = {'form': form}\n\treturn render(request, template_path, context)\n\ndef update_dev(request):\n\tform = None\n\tif request.method == 'POST':\n\t\tform = DesenvolvedorForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tdata = form.cleaned_data\n\t\t\tdev = Desenvolvedor.objects.get(email=data['email'])\n\n\t\t\tdev.pnome = data['pnome']\n\t\t\tdev.snome = data['snome']\n\t\t\tdev.cep = data['cep']\n\t\t\tdev.rua = data['rua']\n\t\t\tdev.numero = data['numero']\n\t\t\tdev.cidade = data['cidade']\n\t\t\tdev.estado = data['estado']\n\t\t\tdev.ativo = data['ativo']\n\t\n\t\t\tdev.save()\n\n\t\t\treturn HttpResponseRedirect('/ep3/thanks/')\n\telse:\n\t\tform = DesenvolvedorForm\n\n\ttemplate_path = 'ep3/update_dev.html'\n\tcontext = {'form': form}\n\treturn render(request, template_path, context)\n\ndef thanks(request):\n\ttemplate_path = 'ep3/thanks.html'\n\tcontext = {}\n\n\treturn render(request, template_path, context)\n","repo_name":"bsesso/mac0350_ep3","sub_path":"mac0350_ep3/ep3/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"2925098797","text":"\"\"\"\nSource: https://leetcode.com/problems/bus-routes/\nDate: 2023/3/15\nSkill:\nRuntime: TLE\nMemory Usage:\nTime complexity:\nSpace complexity:\nConstraints:\n 1 <= routes.length <= 500.\n 1 <= routes[i].length <= 10^5\n\"\"\"\n\nimport math\nimport random\nfrom typing import List, Optional\nfrom collections import defaultdict, deque\nfrom heapq import heapify, heappush, heappop, nsmallest\nfrom bisect import bisect_left, bisect_right\nimport heapq\nimport functools\nfrom sortedcontainers import SortedList\n\n\nclass Solution:\n def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n if source == target:\n return 0\n step, q = -1, deque([source])\n edges, visited = defaultdict(set), defaultdict(int)\n visited[source] = 1\n for route in routes:\n for i in range(len(route)):\n for j in range(i+1, len(route)):\n edges[route[i]].add(route[j])\n edges[route[j]].add(route[i])\n\n while q:\n step += 1\n sz = len(q)\n for _ in range(sz):\n cur_stop = q.popleft()\n for neighbor in edges[cur_stop]:\n if not visited[neighbor]:\n if neighbor == target:\n return step + 1\n q.append(neighbor)\n visited[neighbor] = 1\n edges[neighbor].remove(cur_stop)\n\n return -1\n\n\nif __name__ == \"__main__\":\n s = Solution()\n","repo_name":"RyanPioneer/Leetcode","sub_path":"0501~1000/0815. Bus Routes/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"14193296285","text":"'''\n 시간복잡도 : O(log(n)), worst: O(n) (=> 편향된 트리)\n'''\n\n\nclass Node(object):\n def __init__(self, data):\n self.data = data\n self.left = self.right = None\n\n\nclass BinarySearchTree(object):\n def __init__(self):\n self.root = None\n\n def insert(self, data):\n self.root = self._insert_value(self.root, data)\n return self.root\n\n def _insert_value(self, node, data):\n if node is None:\n node = Node(data)\n else:\n if data <= node.data:\n node.left = self._insert_value(node.left, data)\n else:\n node.right = self._insert_value(node.right, data)\n return node\n\n def find(self, data):\n return self._find_value(self.root, data)\n\n def _find_value(self, root, data):\n if root is None or root.data == data:\n return data\n elif data < root.data:\n return self._find_value(root.left, data)\n else:\n return self._find_value(root.right, data)\n\n def get_height(self, root):\n if root is None:\n return -1\n\n left_height = self.get_height(root.left) + 1\n right_height = self.get_height(root.right) + 1\n\n return max(left_height, right_height)\n\n def delete(self, data):\n self.root, deleted = self._delete_value(self.root, data)\n return deleted\n\n def _delete_value(self, node, data):\n if node is None:\n return node, False\n\n deleted = False\n if data == node.data:\n deleted = True\n if node.left and node.right:\n parent, child = node, node.right\n # 오른쪽 서브트리의 가장 왼쪽 아래에 위치한 자손을 가져옴\n while child.left is not None:\n parent, child = child, child.left\n child.left = node.left\n\n if parent != node:\n parent.left = child.right\n child.right = node.right\n node = child\n elif node.left or node.right:\n node = node.left or node.right\n else:\n node = None\n elif data < node.data:\n node.left, deleted = self._delete_value(node.left, data)\n else:\n node.right, deleted = self._delete_value(node.right, data)\n return node, deleted\n\n # root - left - right\n def pre_order_traversal(self):\n def _pre_order_traversal(root):\n if root is None:\n pass\n else:\n print(root.data)\n _pre_order_traversal(root.left)\n _pre_order_traversal(root.right)\n _pre_order_traversal(self.root)\n\n # left - root- right\n def in_order_traversal(self):\n def _in_order_traversal(root):\n if root is None:\n pass\n else:\n _in_order_traversal(root.left)\n print(root.data)\n _in_order_traversal(root.right)\n _in_order_traversal(self.root)\n\n def post_order_traversal(self):\n def _post_order_traversal(root):\n if root is None:\n pass\n else:\n _post_order_traversal(root.left)\n _post_order_traversal(root.right)\n print(root.data)\n _post_order_traversal(self.root)\n\n def level_order_traversal(self):\n def _level_order_traversal(root):\n queue = [root]\n while queue:\n root = queue.pop(0)\n if root is not None:\n print(root.data)\n if root.left:\n queue.append(root.left)\n elif root.right:\n queue.append(root.right)\n _level_order_traversal(self.root)\n\nif __name__ == '__main__':\n array = [40, 4, 34, 45, 14, 55, 48, 13, 15, 49, 47]\n\n bst = BinarySearchTree()\n\n root = None\n for x in array:\n root = bst.insert(x)\n\n height = bst.get_height(root)\n print(height)\n\n value = bst.find(15)\n print(value)\n\n bst.pre_order_traversal()\n print('-'*30)\n bst.in_order_traversal()\n print('-' * 30)\n bst.post_order_traversal()\n print('-', 30)\n bst.level_order_traversal()\n # ind_value = bst.find(4)\n # print(find_value)","repo_name":"korea7030/pythonwork","sub_path":"Algorithm/binary_search_tree.py","file_name":"binary_search_tree.py","file_ext":"py","file_size_in_byte":4350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"24607114899","text":"#!/usr/bin/env python\n\nfrom rauth import OAuth1Session\nfrom Bio import SeqIO\nimport argparse\nimport datetime\nimport logging\nimport urllib\nimport shutil\nimport glob\nimport csv\nimport re\nimport os\nimport subprocess\n\nsourcedir=os.path.dirname(os.path.abspath(__file__))\n\nclass RmlstRest(object):\n\n def get_session_token(self):\n session_request = OAuth1Session(self.consumer_key,\n self.consumer_secret,\n access_token=self.access_token,\n access_token_secret=self.access_secret)\n url = self.test_rest_url + '/oauth/get_session_token'\n r = session_request.get(url)\n if r.status_code == 200:\n self.session_token = r.json()['oauth_token']\n self.session_secret = r.json()['oauth_token_secret']\n else:\n logging.error('ERROR: Couldn\\'t get a session token for rMLST database download. Check that your consumer '\n 'secret and access token files have valid credentials and try again.')\n quit(code=1)\n\n def get_loci_and_scheme_url(self):\n session = OAuth1Session(self.consumer_key,\n self.consumer_secret,\n access_token=self.session_token,\n access_token_secret=self.session_secret)\n r = session.get(self.test_rest_url)\n if r.status_code == 200 or r.status_code == 201:\n if re.search('json', r.headers['content-type'], flags=0):\n decoded = r.json()\n else:\n decoded = r.text\n # Extract the URLs from the returned data\n self.loci = decoded['loci']\n self.profile = decoded['schemes']\n else:\n logging.error('ERROR: Could not find URLs for rMLST download, they may have moved. Please open an issue '\n 'at https://github.com/AlexOrlek/bacterialBercow/issues and I\\'ll get things sorted out.')\n quit(code=1)\n\n def download_loci(self):\n session = OAuth1Session(self.consumer_key,\n self.consumer_secret,\n access_token=self.session_token,\n access_token_secret=self.session_secret)\n r = session.get(self.loci)\n if r.status_code == 200 or r.status_code == 201:\n if re.search('json', r.headers['content-type'], flags=0):\n decoded = r.json()\n else:\n decoded = r.text\n # Extract all the URLs in the decoded dictionary under the key 'loci'\n for locus_url in decoded['loci']:\n output_file = os.path.join(self.output_folder, '{0}.tfa'.format(os.path.split(locus_url)[1]))\n logging.info('Downloading {0}...'.format(os.path.split(locus_url)[1]))\n with open(output_file, 'w') as f:\n download = session.get(locus_url + '/alleles_fasta')\n if download.status_code == 200 or download.status_code == 201:\n if re.search('json', download.headers['content-type'], flags=0):\n decoded = download.json()\n else:\n decoded = download.text\n with open(output_file, 'w') as locus_fasta:\n locus_fasta.write(decoded)\n \n else:\n logging.error('ERROR: Could not find URLs for rMLST download, they may have moved. Please open an issue '\n 'at https://github.com/AlexOrlek/bacterialBercow/issues and I\\'ll get things sorted out.')\n quit(code=1)\n\n def download_profile(self):\n profile_file = os.path.join(self.output_folder, 'profiles.txt')\n session = OAuth1Session(self.consumer_key,\n self.consumer_secret,\n access_token=self.session_token,\n access_token_secret=self.session_secret)\n r = session.get(self.profile + '/1/profiles_csv')\n logging.info('Downloading rMLST profiles...')\n if r.status_code == 200 or r.status_code == 201:\n if re.search('json', r.headers['content-type'], flags=0):\n decoded = r.json()\n else:\n decoded = r.text\n # Write the profile file to disk\n with open(profile_file, 'w') as profile:\n profile.write(decoded)\n\n def get_request_token(self):\n session = OAuth1Session(consumer_key=self.consumer_key,\n consumer_secret=self.consumer_secret)\n # Use the test URL in the GET request\n r = session.request(method='GET',\n url=self.request_token_url,\n params={'oauth_callback': 'oob'})\n if r.status_code == 200:\n self.request_token = r.json()['oauth_token']\n self.request_secret = r.json()['oauth_token_secret']\n\n def get_access_token(self):\n authorize_url = self.test_web_url + '&page=authorizeClient&oauth_token=' + self.request_token\n print('Visit this URL in your browser: ' + authorize_url)\n verifier = input('Enter oauth_verifier from browser: ')\n session_request = OAuth1Session(consumer_key=self.consumer_key,\n consumer_secret=self.consumer_secret,\n access_token=self.request_token,\n access_token_secret=self.request_secret)\n # Perform a GET request with the appropriate keys and tokens\n r = session_request.get(self.access_token_url,\n params={\n 'oauth_verifier': verifier\n })\n # If the status code is '200' (OK), proceed\n if r.status_code == 200:\n # Save the JSON-decoded token secret and token\n self.access_token = r.json()['oauth_token']\n self.access_secret = r.json()['oauth_token_secret']\n\n def __init__(self, consumer_secret_file, output_folder):\n self.test_rest_url = 'http://rest.pubmlst.org/db/pubmlst_rmlst_seqdef'\n self.test_web_url = 'http://pubmlst.org/cgi-bin/bigsdb/bigsdb.pl?db=pubmlst_rmlst_seqdef'\n self.request_token_url = self.test_rest_url + '/oauth/get_request_token'\n self.access_token_url = self.test_rest_url + '/oauth/get_access_token'\n self.authorize_url = self.test_web_url + '&page=authorizeClient'\n self.output_folder = output_folder\n \n # Get the consumer secret set up.\n if not os.path.isfile(consumer_secret_file):\n logging.error('ERROR: Could not find consumer secret file. Please make sure the file you specified ({0}) exists '\n 'and try again.'.format(consumer_secret_file))\n quit(code=1)\n with open(consumer_secret_file) as f:\n lines = f.readlines()\n try:\n self.consumer_key = lines[0].rstrip()\n self.consumer_secret = lines[1].rstrip()\n except IndexError:\n logging.error('ERROR: Could not parse your consumer secret file. File should have supplied consumer key '\n 'on first line, and consumer secret on the second line.')\n quit(code=1) \n \n self.session_secret = str()\n self.session_token = str()\n self.loci = str()\n self.profile = str()\n self.request_token = str()\n self.request_secret = str()\n self.access_token = str()\n self.access_secret = str()\n\n\ndef create_gene_allele_file(profiles_file, gene_allele_file):\n genus_allele_info = dict()\n with open(profiles_file) as tsvfile:\n reader = csv.DictReader(tsvfile, delimiter='\\t')\n for row in reader:\n genus = row['genus']\n if genus not in genus_allele_info:\n genus_allele_info[genus] = list()\n for i in range(1, 66):\n if i < 10:\n gene = 'BACT00000' + str(i)\n else:\n gene = 'BACT0000' + str(i)\n if gene in row:\n allele_number = row[gene]\n gene_allele = '{0}_{1}'.format(gene, allele_number)\n if allele_number != 'N' and gene_allele not in genus_allele_info[genus]:\n genus_allele_info[genus].append(gene_allele)\n with open(gene_allele_file, 'w') as f:\n for genus in genus_allele_info:\n f.write(str(genus) + ':')\n for allele in genus_allele_info[genus]:\n f.write(str(allele) + ',')\n f.write('\\n')\n\n\ndef setup_rmlst_database(output_folder, consumer_secret):\n # Remove previous output folder if it existed.\n if os.path.isdir(output_folder):\n logging.info('Removing old databases...')\n shutil.rmtree(output_folder)\n os.makedirs(output_folder)\n \n # Go through the REST API in order to get profiles downloaded.\n rmlst_rest = RmlstRest(consumer_secret_file=consumer_secret,\n output_folder=output_folder)\n rmlst_rest.get_request_token()\n rmlst_rest.get_access_token()\n rmlst_rest.get_session_token()\n rmlst_rest.get_loci_and_scheme_url()\n rmlst_rest.download_loci()\n rmlst_rest.download_profile()\n\n\n logging.info('Make blast databases...')\n # For each locus fasta file create a blast database (save in blastdb sub-folder).\n cmdArgs=['bash', '%s/makeblastdbs.sh'%sourcedir, '%s'%output_folder, 'rmlst']\n subprocess.call(cmdArgs)\n\n\n \n \ndef main():\n logging.basicConfig(format='\\033[92m \\033[1m %(asctime)s \\033[0m %(message)s ',\n level=logging.INFO,\n datefmt='%Y-%m-%d %H:%M:%S')\n parser = argparse.ArgumentParser()\n parser.add_argument('-s', '--secret_file',\n type=str,\n required=True,\n help='Path to consumer secret file for rMLST database.')\n #parser.add_argument('-o', '--output_folder',\n # default='%s/databases/rmlstalleles'%sourcedir,\n # help='Path to download databases to - if folder does not exist, will be created. If folder does '\n # 'exist, will be deleted and updated sequences downloaded. Defaults to databases/rmlstalleles')\n args = parser.parse_args()\n output_folder='%s/databases/rmlstalleles'%sourcedir\n setup_rmlst_database(output_folder,\n args.secret_file)\n #download_mash_sketch(output_folder) ###not downloading mash sketch\n current_year = datetime.datetime.utcnow().year\n current_month = datetime.datetime.utcnow().month\n current_day = datetime.datetime.utcnow().day\n with open(os.path.join(output_folder, 'download_date.txt'), 'w') as f:\n f.write('{0}-{1}-{2}'.format(current_year, current_month, current_day))\n logging.info('Finished downloading rmlst database!')\n \n \nif __name__ == '__main__':\n main()\n\n\n","repo_name":"AlexOrlek/bacterialBercow","sub_path":"rmlst_setup.py","file_name":"rmlst_setup.py","file_ext":"py","file_size_in_byte":11235,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"41"} +{"seq_id":"70898708923","text":"from random import randint\n\n# Função: obter a lista de preço dos jogos\n# Retorno: dicionário com números de tentativas (chave) e preços (valor)\n#\n# Definição das variáveis utilizadas:\n#\n# index: variável de controle para auxiliar no preenchimento do dict\n# prices: dicionário contendo o número de tentativas (chave) e seus preços (valor)\n# prices_list: lista com os preços a serem adicionados no dict\n\ndef get_price_list():\n index = 0\n prices = dict()\n prices_list = [3, 24, 98, 294, 735, 1617, 3234, 6000, 10510, 17500]\n for i in range(6, 16):\n prices[i] = prices_list[index]\n index += 1\n return prices\n\n\n# Função: exibir a lista de preços\n\ndef show_price_list(dicionario):\n print(\"TABELA DE PREÇOS\\n==========================\\n\")\n for i in dicionario:\n print(\"{0} dezenas: {1} RPs\".format(i, dicionario[i]))\n print()\n\n\n# Função: exibir a lista de prêmios\n#\n# Definição das variáveis utilizadas:\n#\n# index: variável de controle\n# prizes: lista de prêmios\n\ndef show_prize():\n index = 0\n prizes = [2, 10, 50, 40000, 520000, 20000000]\n print(\"TABELA DE PRÊMIOS\\n==========================\\n\")\n for i in range(1, 7):\n print(\"{} acertos: {} RPs\".format(i, prizes[index]))\n index += 1\n print()\n\n\n# Função: verificar se a tentativa é válida ou não\n# Retorno: True se for válida, False se não\n\ndef is_valid_attempt(tentativa, dezenas):\n if(len(tentativa)!=dezenas):\n print(\"Você fez uma aposta inválida!\")\n return False\n else:\n for i in range(1, len(tentativa)):\n if(tentativa[0]==tentativa[i]):\n print(\"Aposta inválida! Há números iguais.\")\n return False\n for i in tentativa:\n if(i>60 or i<1):\n print(\"Aposta inválida! Existem números inválidos.\")\n return False\n return True\n\n# Função: gerar números aleatórios\n# Retorno: lista ordenada de números aleatórios\n\ndef generate_numbers():\n lista = []\n for i in range(0, 6):\n r = randint(1, 61)\n if(r not in lista):\n lista.append(r)\n return sorted(lista)\n\n\n# Função: verificar os acertos\n# Retorno: inteiro referente ao número de acertos\n\ndef get_hits(tentativa, sorteio):\n acertos = 0\n for i in tentativa:\n if i in sorteio:\n acertos += 1\n return acertos\n\n\n# Função: exibir resumo da jogada\n\ndef print_ticket(tentativa, sorteio, valor):\n print(\"==============================\")\n print(\"Seu jogo: \", ' '.join(list(map(str, tentativa))))\n print(\"==============================\")\n print(\"Sorteio: \", ' '.join(list(map(str, sorteio))))\n print(\"==============================\")\n print(\"Total gasto: {} RPs\".format(valor))\n print(\"==============================\")","repo_name":"kennedy-ag/lotopy","sub_path":"funcoes.py","file_name":"funcoes.py","file_ext":"py","file_size_in_byte":2653,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"40418477684","text":"import sys\ninput = sys.stdin.readline\n\nn, k = map(int, input().split())\ndata = [[0,0] for _ in range(n+1)]\nfor i in range(1,n+1):\n data[i] = list(map(int, input().split()))\nd = [[0 for _ in range(k+1)] for _ in range(n+1)]\n\nfor i in range(1, n+1):\n for j in range(1, k+1):\n if j>=data[i][0]:\n d[i][j] = max(d[i-1][j], d[i-1][j-data[i][0]]+data[i][1])\n else:\n d[i][j] = d[i-1][j]\n\nprint(d[-1][-1])\n","repo_name":"2JooYeon/Algorithm_Study","sub_path":"JooYeon/baekjoon_Q12865.py","file_name":"baekjoon_Q12865.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"41"} +{"seq_id":"7600908086","text":"import tensorflow as tf\nimport numpy as np\nimport math\nimport json\n#import matplotlib\n#import matplotlib.pyplot as plt\n#%matplotlib inline\n#matplotlib.style.use('ggplot')\n\n\n#--------------------------------------------------\n\n# Converting to tensor\n\ndef my_func(arg):\n print('\\nWe entered to function---> my_func')\n \n arg = tf.convert_to_tensor(arg)\n return arg\n\n#--------------------------------------------------\n\n# Computing significances of ith subtensor\n\ndef fraction(eigenexprssionsi, M):\n print('\\nWe entered to function---> fraction')\n \n # ai_fractions = ai_sSquare / np.sum(ai_sSquare)\n print(eigenexprssionsi)\n arr = eigenexprssionsi\n lambdaSum = np.sum(arr)\n aiFrac = np.zeros(M)\n for i in range(M):\n aiFrac[i] = arr[i] / lambdaSum\n\n return aiFrac\n#--------------------------------------------------\n\n# Calculating entropy\n\ndef ent(data):\n\n print('\\nWe entered to function---> ent')\n \n entropy = 0\n for i in range(0,len(data)):\n entropy = entropy + (data[i] * np.log2(data[i]))\n \n entropy = -1/np.log2(12) *entropy\n \n return entropy\n\n#---------------------------------------------\n\n# Main algorithm to decompose the tensor\n\ndef decom(T,N):\n\n print('\\nWe entered to function---> decom')\n \n g = tf.Variable(tf.random_normal([N]))\n\n L = 1\n N_iter = 5\n # This is for L in power method\n for i in range(L):\n X = tf.Variable(tf.random_uniform([N,N]))\n norm = tf.norm(X)\n X = X / norm\n for j in range(N_iter): # This is for N in power method\n #X = tf.einsum('abf,cdl,flk,k,bd->ac',T,T,T,g,X)\n X = tf.einsum('abf,flk,ak->bl',T,T,X)\n norm = tf.norm(X)\n X = X / norm\n E = tf.self_adjoint_eig(X, name = None)\n \n print('\\nWe just finished eigenvalue function')\n \n g = E[1][:,N-1]\n \n print('\\n End of power method\\Here we have created Eigenvector')\n\n for j in range(N_iter): # This is for N in power method\n g = tf.einsum('klm,m,l->k',T,g,g)\n norm = tf.norm(g)\n g = g / norm\n \n eigen = tf.einsum('klm,m,l,k',T,g,g,g)\n T = tf.einsum('i,j,k->ijk',g,g,g)\n init_op = tf.global_variables_initializer()\n sess = tf.Session()\n sess.run(init_op)\n return (g, sess.run(eigen),sess.run(g),T)\n\n#--------------------------------------------------\n\n#Individual tensor decomposition and significances\n\ndef Indv_decom(T, N, iteration):\n\n print('\\nWe entered to function---> Indv_decom')\n \n #T = tf.slice(T, [0,0,0], [N,N,N] )\n\n Tsum = tf.zeros([N,N,N])\n Tfirst = T\n\n init_op = tf.global_variables_initializer()\n sess = tf.Session()\n sess.run(init_op)\n\n print(\"\\n norm of original Tensor:\\n\")\n n = tf.norm(T)\n print(sess.run(n))\n \n # T = T/n\n \n Comp = np.zeros((iteration,N))\n Eigen =[]\n Indivcounter = 0\n n0 = n\n n1 = tf.constant(0.00)\n \n for i in range(iteration):\n vec, eig,comp,T = decom(T,N)\n \n init_op = tf.global_variables_initializer()\n sess = tf.Session()\n sess.run(init_op)\n\n print(sess.run(n0))\n print(sess.run(n1))\n # if eig<0 or sess.run(n0) 1.125) & (rules['confidence'] > 0.8)])\n\n# 实际场景中,数据可能不是这种0|1的格式,那就需要用one-hot编码来转换\n# 做点数据\nretail_shopping_basket = {'ID': [1, 2, 3, 4, 5, 6],\n 'Basket': [['Beer', 'Diaper', 'Pretzels', 'Chips', 'Aspirin'],\n ['Diaper', 'Beer', 'Chips', 'Lotion', 'Juice', 'BabyFood', 'Milk'],\n ['Soda', 'Chips', 'Milk'],\n ['Soup', 'Beer', 'Diaper', 'Milk', 'IceCream'],\n ['Soda', 'Coffee', 'Milk', 'Bread'],\n ['Beer', 'Chips']\n ]\n }\nretail = pd.DataFrame(retail_shopping_basket)\nretail = retail[['ID', 'Basket']]\npd.options.display.max_colwidth = 100\n# 取出id列\nretail_id = retail.drop('Basket', 1)\n# 用','来连接数组\nretail_Basket = retail.Basket.str.join(',')\n# 根据','来做one-hot编码,并转成bool格式\nretail_Basket = retail_Basket.str.get_dummies(',').astype(bool)\nretail = retail_id.join(retail_Basket)\nprint(retail)\n# 查看规则\nfrequent_item_sets_2 = apriori(retail.drop('ID', 1), use_colnames=True)\nprint(frequent_item_sets_2)\nrules2 = association_rules(frequent_item_sets_2, metric='lift')\nprint(rules2)\n\n# 拿个真实的数据集玩玩\n# https://grouplens.org/datasets/movielens/\nmovies = pd.read_csv('../data/movies.csv')\nmovies_ohe = movies.drop('genres', 1).join(movies.genres.str.get_dummies().astype(bool))\npd.options.display.max_columns = 100\nprint(movies_ohe)\n# 把movieId和title设置成df的index\nmovies_ohe.set_index(['movieId', 'title'], inplace=True)\n# 实际情况下的支持度是个绝对的概念,通常是很小的\nfrequent_item_sets_movies = apriori(movies_ohe, use_colnames=True, min_support=0.025)\n# 由于提升度是一个相对的概念,所以实际值是偏高的\nrules_movies = association_rules(frequent_item_sets_movies, metric='lift', min_threshold=1.25)\n# 查看提升度高的项集\nprint(rules_movies[(rules_movies.lift > 4)].sort_values(by=['lift'], ascending=False))\n","repo_name":"lj502766817/ML_Algorithm","sub_path":"apriori/AssociationRule.py","file_name":"AssociationRule.py","file_ext":"py","file_size_in_byte":3177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"11297255916","text":"import hashlib\nimport sys\nimport time\nfrom modules import globalVar as gl\n# from tqdm import tqdm\n\nstart = 1\ndef col(str,col):\n if col == \"green\":\n return \"\\033[1;32;40m{}\\033[0m\".format(str)\n elif col == \"red\":\n return \"\\033[1;31;40m{}\\033[0m\".format(str)\n elif col == \"yellow\":\n return \"\\033[1;33;40m{}\\033[0m\".format(str)\n elif col == \"cyan\":\n return \"\\033[1;36;40m{}\\033[0m\".format(str)\n\ndef times():\n return col(\"[\"+time.strftime(\"%H:%M:%S\", time.localtime())+\"] \",\"cyan\")\n\ndef Url_init(url):\n if url.endswith('/'):\n return url.rstrip('/')\n else:\n return url\n\ndef Path_init(path):\n if not path.startswith('/'):\n return '/'+path\n else:\n return path\n\ndef Get_Md5(str):\n my_md5 = hashlib.md5() # 获取一个MD5的加密算法对象\n my_md5.update(str) # 得到MD5消息摘要\n my_md5_Digest = my_md5.hexdigest() # 以16进制返回消息摘要,32位\n return my_md5_Digest\n\n\ndef headers_init(head):\n str = ''\n keys = head.keys()\n for i in keys:\n str += i+\":\"+head[i]+\"\\n\"\n return str\n\ndef save_init(path):\n open(path,\"w\",encoding=\"utf-8\").close()\n\n\ndef save(url,path,str,name):\n if gl.get_value(\"save_path\") != None:\n file = open(gl.get_value(\"save_path\"),\"a\",encoding=\"utf-8\")\n file.write(str+\": \"+url+\": \"+path+\": \"+name+\"\\n\")\n file.close()\n\ndef proxies_init(str):\n if str != None:\n xieyi, daili = str.split('://')\n if gl.get_value(\"url\").startswith(\"https\"):\n return {\"https\":daili}\n else:\n return {\"http\":daili}\n else:\n return str\n\n\n\ndef Error_print(err):\n if err == \"ProxyError\":\n Error = gl.get_value(\n 'color').red_warn() + gl.get_value(\n 'color').red(\" Target rejected, please check agent\")\n print(\"\\r\", end=\"\")\n print(\" \"*30+Error,\"* {}\".format(col(gl.get_value(\"ProxyError\"),\"red\"))+\" \"*21, end=\"\")\n gl.set_value(\"ProxyError\",gl.get_value(\"ProxyError\")+1)\n sys.stdout.flush()\n elif err == \"ReadTimeout\":\n Error = gl.get_value(\n 'color').red_warn() + gl.get_value(\n 'color').red(\" The response timed out. Try adjusting the -out parameter\")\n print(\"\\r\", end=\"\")\n print(\" \"*30+Error, \"* {}\".format(col(gl.get_value(\"ReadTimeout\"), \"red\")), end=\"\")\n gl.set_value(\"ReadTimeout\", gl.get_value(\"ReadTimeout\") + 1)\n sys.stdout.flush()\n elif err == \"ConnectTimeout\":\n Error = gl.get_value(\n 'color').red_warn() + gl.get_value(\n 'color').red(\" The response timed out. Try adjusting the -out parameter\")\n print(\"\\r\", end=\"\")\n print(\" \"*30+Error, \"* {}\".format(col(gl.get_value(\"ConnectTimeout\"), \"red\")), end=\"\")\n gl.set_value(\"ConnectTimeout\", gl.get_value(\"ConnectTimeout\") + 1)\n sys.stdout.flush()\n elif err == \"ConnectionError\":\n Error = gl.get_value(\n 'color').red_warn() + gl.get_value(\n 'color').red(\" Failed to connect to this website\")\n print(\"\\r\", end=\"\")\n print(\" \"*30+Error, \"* {}\".format(col(gl.get_value(\"ConnectionError\"), \"red\"))+\" \"*23, end=\"\")\n gl.set_value(\"ConnectionError\", gl.get_value(\"ConnectionError\") + 1)\n sys.stdout.flush()\n\n\ndef progress(mod,ge):\n global nr, zong\n if mod == \"md5\":\n nr = \" MD5: \"\n zong = gl.get_value(\"MD5_zong\")\n elif mod == \"url\":\n nr = \" URL: \"\n zong = gl.get_value(\"URL_zong\")\n elif mod == \"re\":\n nr = \" RE: \"\n zong = gl.get_value(\"RE_zong\")\n print(\"\\r\", end=\"\")\n print(times()+ gl.get_value(\n 'color').yel_info()+gl.get_value(\n 'color').yellow(nr + \"{}/{} \".format(ge,zong)), end=\"\")\n sys.stdout.flush()\n\ndef If_one():\n global start\n if start == 1:\n start += 1\n return \"\"\n else:\n return \"\\n\"\n# def Progress_bar(name,geshu):\n# for i in tqdm(range(geshu), desc=name, ncols=80):\n# if name == 'md5':\n# while True:\n# if gl.get_value('md5_int'):\n# pass\n\nif __name__ == '__main__':\n print(times())","repo_name":"F6JO/CmsVulScan","sub_path":"modules/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":4162,"program_lang":"python","lang":"en","doc_type":"code","stars":119,"dataset":"github-code","pt":"41"} +{"seq_id":"72923610683","text":"#Question : Given an array and a positive integer k, find the first negative integer for each and every window(contiguous subarray) of size k.\n\n# Example:\n\n# Input:\n# 1st example :\n #2(size of window {k})\n# 5 (size of an array)\n# arr=[-8 2 3 -6 10] , k = 2 \n# 2nd example : \n#2(size of window {k})\n# 8 (size of an array)\n# arr=[12 -1 -7 8 -15 30 16 28]\n# k=3\n\n# Output:\n# 1> -8 0 -6 -6\n# 2> -1 -1 -7 -15 -15 0 . \n\n#NOTE-:Gist of the logic used:-\n\n# 1. We're creating a list to store all the negative elements of a current window. At a particular point of time, the list holds negative numbers which are there in the current running window and not all the negative elements in the array. So, that we can retrieve first negative number from the current window.\n# 2. When we reached the window size, we need to perform two operations:-\n# -> First, we have to retrieve the answer that is the first negative number from the current window. We're checking if the list is empty or not. If it is empty, then there is no negative number in the current window. In that case we'll push 0 in the vector.\n# If it's not empty, then the first element in the list is the first negative number of the current window., pushing that into the vector.\n# -> Second, we need to slide the window. For that we need to remove the first element of the current window, and add the next element from the array to the window. But before removing the first element, we need to check whether it belongs to the list or not. If it belongs to the list, we need to remove it from the list, as it will not be a part of our next window. So, if the first element is found to be a negative number, then we have to remove it from the list, and this number is happened to be the front element of the list. Then, incrementing the values of i and j to slide the window.\n\ndef findFirstNegative(arr, k):\n n = len(arr)\n res = [] # List to store the first negative numbers in each window\n\n # Initialize variables\n i = 0 # Start index of the window\n j = 0 # End index of the window\n\n while j < n:\n # If the window size reaches k, find the first negative number\n if j - i + 1 == k:#In summary, the condition j - i + 1 == k is used to determine when the window size has reached k and it's time to find the first negative number within that window. It ensures that the correct window size is considered for the analysis.\n neg_index = -1 # Index of the first negative number in the window\n\n # Find the first negative number in the current window\n for idx in range(i, j + 1):\n if arr[idx] < 0:\n neg_index = idx\n break\n\n # Add the first negative number (or 0 if none found) to the result list\n res.append(arr[neg_index] if neg_index != -1 else 0)\n\n # Slide the window by incrementing the start index\n i += 1\n\n # Expand the window by incrementing the end index\n j += 1\n\n return res\n\narr = [2, -3, 4, -6, 5, -1, 4, -2, 3]\nk = 3\nresult = findFirstNegative(arr, k)\nprint(\"First Negative Numbers in each Window of Size\", k, \":\", result)\n\n","repo_name":"AyushKumar1810/PLACEMENT","sub_path":"Sliding Window/Fixed size sliding window/First Negative Number in every Window of Size K.py","file_name":"First Negative Number in every Window of Size K.py","file_ext":"py","file_size_in_byte":3165,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"7194866034","text":"# Write a program to count the frequencies of each word from a file \no=open(\"file1.txt\",\"r\")\nr=[]\nr=o.read().split()\nm={}\nfor i in r:\n count=0\n for x in r:\n if(x==i):\n count=count+1\n\n \n m[i]=count\nprint(m)\n","repo_name":"JK432/frequency-of-each-word","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"22493568357","text":"import time\n\nimport boto3\nfrom flask import Flask, render_template, redirect, request, jsonify, session\nimport LoginFunctions, PostFunctions\nimport random, string\napplication = Flask(__name__)\n\napplication.secret_key = 'cloudComputingIsFun'\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n 404 ROUTE \n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n@application.errorhandler(404)\ndef page_not_found(e):\n if 'username' in session:\n return render_template('404.html', user=session['username'].upper()),404\n else:\n return render_template('404.html'),404\n\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nSTANDARD ROUTES \n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n@application.route('/global')\ndef global_posts():\n\n globalPosts = PostFunctions.getGlobal()\n\n if 'username' in session:\n return render_template('global.html', user=session['username'].upper(), globalPosts=globalPosts, globalPostsLen=len(globalPosts))\n else:\n return render_template('global.html', globalPosts=globalPosts, globalPostsLen=len(globalPosts))\n\n@application.route('/')\ndef land_page():\n trending = PostFunctions.getTrendingPosts()\n recent = PostFunctions.getRecentPosts()\n # if user is login in change nav to show profile \"li tag\" instead of sign in and sign up\n # check if session varible set if they are change nav as aforementioned\n # else display standard template\n if 'username' in session:\n return render_template('index.html', user=session['username'].upper(), trending=trending, trendingLen=len(trending), recent=recent, recentLen=len(recent))\n else:\n return render_template('index.html', trending=trending, trendingLen=len(trending), recent=recent, recentLen=len(recent))\n\n@application.route('/signin', methods=['GET', 'POST'])\ndef login():\n if request.method == 'POST':\n username = request.form.get('username')\n password = request.form.get('password')\n # perhaps some security parsing?\n print(username)\n\n if (LoginFunctions.sign_in(username, password) != None):\n user = LoginFunctions.sign_in(username, password)\n session['username'] = username\n return redirect(\"/\")\n else:\n error = \"Wrong Username and/or Password!\"\n if 'username' in session:\n return render_template('signin.html', error=error, user=session['username'].upper())\n else:\n return render_template('signin.html', error=error)\n\n else:\n if 'username' in session:\n return render_template('signin.html', user=session['username'].upper())\n else:\n return render_template('signin.html')\n\n\n@application.route('/signup', methods=['GET', 'POST'])\ndef signup():\n if request.method == 'POST':\n username = request.form.get('username')\n password = request.form.get('password')\n # perhaps some security parsing?\n ## 1. Check if email exists\n if (LoginFunctions.check_username_exists(username)):\n error = \"Username Already Exists\"\n if 'username' in session:\n return render_template('signup.html', error=error, user=session['username'].upper())\n else:\n return render_template('signup.html', error=error)\n else:\n # create user\n if(LoginFunctions.sign_up(username, password)):\n print(\"user created\")\n # redirect to user-page\n return redirect(\"/signin\")\n else:\n error = \"Error in creating user\"\n if 'username' in session:\n return render_template('signup.html', error=error, user=session['username'].upper())\n else:\n return render_template('signup.html', error=error)\n else:\n if 'username' in session:\n return render_template('signup.html', user=session['username'].upper())\n else:\n return render_template('signup.html')\n\n@application.route('/aboutus')\ndef aboutus():\n if 'username' in session:\n return render_template('aboutus.html', user=session['username'].upper())\n else:\n return render_template('aboutus.html')\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n DASHBOARD ROUTES \n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n@application.route('/dashboard')\ndef dashboard():\n trending = PostFunctions.getTrendingPosts()\n recent = PostFunctions.getRecentPosts()\n if 'username' in session:\n # array of posts\n user_posts = PostFunctions.getUserPosts(session['username'])\n number_of_posts = len(user_posts)\n return render_template('dashboard.html', user=session['username'].upper(),\n posts=user_posts, len=number_of_posts,\n trending=trending, trendingLen=len(trending),\n recent=recent, recentLen=len(recent))\n else:\n return redirect('/')\n\n\n@application.route('/logout')\ndef logout():\n session.pop('username')\n return redirect(\"/\")\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n POST ROUTES \n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n@application.route('/post/')\ndef post(post_id):\n \"\"\"\n FLOW:\n Update view in post item in database\n\n \"\"\"\n trending = PostFunctions.getTrendingPosts()\n recent = PostFunctions.getRecentPosts()\n # if post doesnt exist revert to 404\n\n if 'username' in session:\n postObject = PostFunctions.getPasteTypeText(post_id)\n # burn paste\n if((postObject['burn'] == 1) and postObject['page_views'] >= 2):\n print('here')\n # delete post from posts\n PostFunctions.burnPost(postObject['post_id'])\n return redirect(\"/404\"), 404, {\"Refresh\": \"1; url=/404\"}\n\n\n try:\n PostFunctions.addView(post_id)\n except Exception as e:\n print(e)\n\n error = None\n if(postObject == False):\n error = \"error in fetching post\"\n return redirect(\"/404\"), 404, {\"Refresh\": \"1; url=/404\"}\n\n\n image = None\n if(postObject['type'] == \"image\"):\n ## fetch image from s3 and add give to template as base64 dataurl\n fileType = postObject['fileType']\n image = PostFunctions.getImage(postObject['post_id'], fileType)\n\n\n return render_template('post.html', user=session['username'].upper(),\n post=postObject, trending=trending,\n trendingLen=len(trending),recent=recent, recentLen=len(recent), image=image)\n\n else:\n postObject = PostFunctions.getPasteTypeText(post_id)\n if((postObject['burn'] == 1) and postObject['page_views'] >= 2):\n print('here')\n # delete post from posts\n PostFunctions.burnPost(postObject['post_id'])\n return redirect(\"/404\"), 404, {\"Refresh\": \"1; url=/404\"}\n\n if(postObject == False):\n error = \"error in fetching post\"\n return redirect(\"/404\"), 404, {\"Refresh\": \"1; url=/404\"}\n\n\n image = None\n if(postObject['type'] == \"image\"):\n ## fetch image from s3 and add give to template as base64 dataurl\n fileType = postObject['fileType']\n image = PostFunctions.getImage(postObject['post_id'], fileType)\n\n try:\n PostFunctions.addView(post_id)\n except Exception as e:\n print(e)\n\n\n return render_template('post.html', post=postObject, trending=trending, trendingLen=len(trending),recent=recent, recentLen=len(recent), image=image)\n\n@application.route('/pastetext', methods=['GET', 'POST'])\ndef pasteText():\n # create post id\n # collect all data\n # add data\n # if someone is sign in it gets added to their posts\n # type of post\n type = \"text\"\n # post body\n post = request.form.get('post')\n # for text type description can be the first 100 charcters\n description = post[:50]\n # views, number of people that have view post\n views = 0\n\n # author\n author = request.form.get('author')\n if(author == \"\"):\n author = \"Anonymous\"\n title = request.form.get('title')\n if(title == \"\"):\n title = \"untitled\"\n # hours the user wishs the post to be alive for\n ttl = request.form.get('time-to-live')\n # 10 alphanumeric random string as post id\n post_id = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(10))\n # future time to delete post\n delete_time = \"\"\n # time post created\n time_posted = int(time.time())\n # ip address of poster\n ip_address = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)\n\n if (ttl != \"burn\"):\n burn = 0\n delete_time = int(time.time()) + int(ttl) * 60 * 60\n else:\n burn = 1\n\n\n if 'username' in session:\n user = session['username']\n else:\n # not signed in\n user = \"\"\n\n if(PostFunctions.pasteText(type, post_id, post, title, description, views, author, delete_time, burn, time_posted, ip_address, user)):\n # post success\n return redirect(\"/post/{}\".format(post_id))\n else:\n # post failure\n error = \"error in creating post\"\n return render_template(\"index.html\", error=error)\n\n\n@application.route('/pasteimage', methods=['GET', 'POST'])\ndef pasteImage():\n image = request.files['img']\n # create post id\n # collect all data\n # add data\n # if someone is sign in it gets added to their posts\n # type of post\n type = \"image\"\n # post body\n # for text type description can be the first 100 charcters\n # views, number of people that have view post\n views = 0\n # author\n author = request.form.get('author')\n if(author == \"\"):\n author = \"Anonymous\"\n title = request.form.get('title')\n if(title == \"\"):\n title = \"untitled\"\n # hours the user wishs the post to be alive for\n ttl = request.form.get('time-to-live')\n # 10 alphanumeric random string as post id\n post_id = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(10))\n # future time to delete post\n delete_time = \"\"\n # time post created\n time_posted = int(time.time())\n # ip address of poster\n ip_address = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)\n\n if (ttl != \"burn\"):\n burn = 0\n delete_time = int(time.time()) + int(ttl) * 60 * 60\n else:\n burn = 1\n\n if 'username' in session:\n user = session['username']\n else:\n # not signed in\n user = \"\"\n\n print(image)\n # standard fillins\n description = \"image description\"\n post = \"image post\"\n fileType = image.filename[image.filename.index(\".\") + 0:image.filename.rindex(\".\") + 4]\n if(PostFunctions.pasteImage(type, post_id, post, title, description, views, author, delete_time, burn, time_posted, ip_address, user, image, fileType)):\n # post success\n return redirect(\"/post/{}\".format(post_id))\n else:\n # post failure\n error = \"error in creating post\"\n return render_template(\"index.html\", error=error)\n\nif __name__ == '__main__':\n application.debug = True\n application.run()\n","repo_name":"s3659610/PasteBucket","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":11046,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"15646356373","text":"import time\n\nimport pandas as pd\nimport streamlit as st\nfrom envyaml import EnvYAML\nfrom transformers import AutoTokenizer, AutoModel\n\nfrom util import text_embedding, abstractive_summarization, extractive_summarization, grammar_check, kwne_similarity, \\\n data_preprocessing, textrank, ner_finder\n\nconfig = EnvYAML(\"config.yaml\")\nbert_embedding_path = config[\"models\"][\"embedding\"]\nrut5_ru_sum_path = config[\"models\"][\"rut5_sum\"]\narchive_path = config[\"data\"][\"archive\"]\nru_sw_file = config[\"data\"][\"ru_stopwords\"]\nref_num_default = int(config[\"params\"][\"reference_number\"])\nsent_num_default = int(config[\"params\"][\"sentence_number\"])\n# sim_threshold_default = float(config[\"params\"][\"similarity_threshold\"])\n\narchive_texts = pd.read_parquet(archive_path)\ngrammar_tool = grammar_check.download_tool()\n\n\ndef get_text_features(input_text):\n input_noun_phrases = data_preprocessing.collect_np(input_text, ru_sw_file)\n input_kw = textrank.text_rank(input_noun_phrases, 15)\n input_ne = ner_finder.finder(input_text)\n input_kw_ne = kwne_similarity.unite_kw_ne(input_kw, input_ne)\n\n tokenizer = AutoTokenizer.from_pretrained(bert_embedding_path)\n model = AutoModel.from_pretrained(bert_embedding_path)\n # TODO: add file not found error\n input_vec = text_embedding.embed_labse(input_text, tokenizer, model)\n return input_vec, input_kw_ne\n\n\ndef check_grammar_on_click(input_text: str, grammar_container: st.container):\n matches = grammar_check.find_mistakes(input_text, grammar_tool)\n with grammar_container:\n for i, match in enumerate(matches):\n context, error_flag, message = grammar_check.print_match(match)\n st.write(str(i + 1) + \": \" + message)\n st.text(context + error_flag)\n if st.button(\"Спрятать проверку текста\"):\n del grammar_container\n\n\ndef filter_params_form():\n st.subheader('Параметры фильтрации документов')\n\n sources_list = sorted(archive_texts[\"source\"].unique())\n sources = st.multiselect('Выберите источник', sources_list)\n if len(sources) > 0:\n filtered_df = archive_texts[archive_texts[\"source\"].apply(lambda s: s in sources)]\n else:\n filtered_df = archive_texts.copy()\n\n dates = st.date_input(\"Задайте период поиска\", value=[])\n if len(dates) > 0:\n start, end = dates\n start = time.mktime(start.timetuple())\n end = time.mktime(end.timetuple())\n filtered_df = archive_texts[(archive_texts[\"_time\"] >= start) & (archive_texts[\"_time\"] <= end)]\n return filtered_df\n\n\ndef context_params_form():\n st.subheader('Настройки генерации бекграунда')\n\n summ_type = st.selectbox('Выберите способ',\n [\"Экстрактивная суммаризация\", \"Абстрактивная суммаризация\"])\n\n ref_num = st.slider(\"Выберите максимальное число документов для генерации бекграунда\",\n min_value=1,\n max_value=10,\n value=ref_num_default,\n step=1)\n\n # sim_threshold = st.slider(\"Выберите степень похожести найденных документов на ваш текст\",\n # min_value=0.0,\n # max_value=1.0,\n # value=0.8,\n # step=0.1)\n\n sent_num = st.slider(\"Выберите число предложений, которое нужно сформировать\",\n min_value=1,\n max_value=5,\n value=sent_num_default,\n step=1)\n return summ_type, ref_num, sent_num # sim_threshold,\n\n\ndef generate_context(filtered_df, input_vec, input_kw_ne, ref_num, summ_type, sent_num): # sim_threshold,\n if len(filtered_df) == 0:\n st.write(\"Я не нашёл подходящие под параметры фильтрации тексты. Попробуйте поменять настройки.\")\n elif len(filtered_df) > 0:\n cos_sim_ind_score = text_embedding.find_sim_texts(filtered_df.dropna(),\n input_vec,\n ref_num,\n full_output=True) # similarity_threshold,\n filtered_df = filtered_df.set_index(\"art_ind\")\n sim_ind_score = kwne_similarity.get_kwne_sim(input_kw_ne, filtered_df, cos_sim_ind_score)\n sim_ind = [x[0] for x in sim_ind_score][:ref_num]\n sim_texts_df = filtered_df.loc[sim_ind]\n\n if len(sim_texts_df) == 0:\n st.write(\"Я не нашёл подходящие под параметры фильтрации тексты. Попробуйте поменять настройки.\")\n\n sim_texts = sim_texts_df[[\"clean_text\", \"text\"]].values.tolist()\n art_inds = sim_texts_df.index\n urls = sim_texts_df[\"url\"].values\n\n if summ_type == \"Абстрактивная суммаризация\":\n context = abstractive_summarization.sum_text(sim_texts, rut5_ru_sum_path)\n for i, doc in enumerate(context):\n st.write(str(i + 1))\n st.write(doc)\n st.write(\"\\n\\n\")\n else:\n context = extractive_summarization.lexrank_sum(sim_texts, sent_num=sent_num)\n for i, doc in enumerate(context):\n st.markdown(\"[%s](%s)\" % (art_inds[i], urls[i]))\n output = \"\"\n for sentence in doc:\n output += sentence\n output += \" \"\n st.write(output)\n\n\ndef load_page():\n st.title('Генерация бекграунда')\n button_name = \"Сформировать бекграунд статьи\"\n input_text = st.text_area('Начните набирать текст в поле. '\n 'Когда текст готов, задайте настройки и нажмите \"%s\"' % button_name,\n height=700)\n input_vec, input_kw_ne = get_text_features(input_text)\n\n grammar_button = st.button(\"Проверить правописание\")\n grammar_container = st.container()\n\n if grammar_button:\n check_grammar_on_click(input_text, grammar_container)\n\n with st.expander(\"Параметры для генерации бекграунда\", expanded=False):\n with st.form(\"params_form\"):\n col1, col2 = st.columns(2)\n with col1:\n filtered_df = filter_params_form()\n with col2:\n summ_type, ref_num, sent_num = context_params_form() # sim_threshold,\n st.form_submit_button(\"Применить настройки\")\n\n gen_button = st.button(button_name)\n\n if gen_button:\n generate_context(filtered_df, input_vec, input_kw_ne, ref_num, summ_type, sent_num) # sim_threshold,\n","repo_name":"ISGNeuroTeam/CoAuthor","sub_path":"context_gen.py","file_name":"context_gen.py","file_ext":"py","file_size_in_byte":7200,"program_lang":"python","lang":"ru","doc_type":"code","stars":41,"dataset":"github-code","pt":"41"} +{"seq_id":"11920036465","text":"\"\"\"Advent Of Code #13.\"\"\"\nwith open(\"input\") as f:\n data = [d.strip() for d in f.readlines()]\n\npaper = set()\ninstructions = []\nfor d in data:\n if \",\" in d:\n x, y = d.split(\",\")\n x = int(x)\n y = int(y)\n paper.add((x, y))\n elif \"=\" in d:\n instruction, line = d.split(\"=\")\n line = int(line)\n instructions.append((instruction, line))\n\n\ndef fold_along_y(paper, line):\n \"\"\"Fold along y.\"\"\"\n paper_new = set()\n for (x, y) in paper:\n if y > line:\n y -= 2 * (y - line)\n paper_new.add((x, y))\n return paper_new\n\n\ndef fold_along_x(paper, line):\n \"\"\"Fold along x.\"\"\"\n paper_new = set()\n for (x, y) in paper:\n if x > line:\n x -= 2 * (x - line)\n paper_new.add((x, y))\n return paper_new\n\n\nfold_function = {\n \"fold along y\": fold_along_y,\n \"fold along x\": fold_along_x,\n}\n\n\n# Part 1\nfold = fold_function[instructions[0][0]]\npaper = fold(paper, instructions[0][1])\nprint(\"Part 1:\", len(paper))\nassert len(paper) == 687\n\n\n# Part 2\nfor instruction in instructions[1:]:\n fold = fold_function[instruction[0]]\n paper = fold(paper, instruction[1])\n\nmax_y = max(y for (_, y) in paper) + 1\nmax_x = max(x for (x, _) in paper) + 1\ncode = \"\"\nfor y in range(max_y):\n for x in range(max_x):\n if (x, y) in paper:\n code += \"#\"\n else:\n code += \" \"\n code = code.strip() + \"\\n\"\n\nprint(\"Part 2:\")\nprint(code)\nassert (\n code\n == \"\"\"\\\n#### ## # # ## # # ### #### ##\n# # # # # # # # # # # # # #\n### # ## # ## ### # #\n# # ## # # # # # # # # # ##\n# # # # # # # # # # # # # #\n# ### # # ## # # ### #### ###\n\"\"\"\n)\n","repo_name":"claha/advent-of-code","sub_path":"2021/13/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"32941167891","text":"#!/usr/bin/env python\n \nimport rospy\nimport actionlib\nimport math\nimport time\n# import second_qr\nimport numpy as np\nfrom transform_matrix import transform_matrix\n# from next_qr_position import next_qr_position \n \nfrom move_base_msgs.msg import MoveBaseAction, MoveBaseGoal\nfrom std_msgs.msg import String as My_string\nfrom geometry_msgs.msg import PoseStamped\nfrom geometry_msgs.msg import PoseWithCovarianceStamped\nfrom tf.transformations import *\n\n\n# [w, x, y, z] = [cos(a/2), sin(a/2) * nx, sin(a/2)* ny, sin(a/2) * nz]\n# Where a is the angle of rotation and {nx,ny,nz} is the axis of rotation. (From section 2e of Quaternion Spells )\ntmp_radius = 2\n\n# initial positions\npa0 = [(2.0, -0.5, 0.0), (0.0, 0.0, 0, 0)]\npa1 = [(2.0, -0.5, 0.0), (0.0, 0.0, 0, math.sqrt(0.5))]\n\nrandom_waypoints = [ \n [(2.0, 0.0, 0.0), (0.0, 0.0, 0.0, 1.0)],\n pa0,\n pa1,\n [(3.0, 4.0, 0.0), (0.0, 0.0, -0.64003024, -0.76812292098)]\n]\n\n#start time\nstart_time = time.time()\n\n#List with qr codes\nqr_list = []\nqr_important_list = [0, 0, 0, 0, 0]\nqr_stored_list = []\n\n#Robot current pose and orientation \ncur_robot_pose_x = 0.0\ncur_robot_pose_y = 0.0\ncur_robot_pose_z = 0.0\n\nrobot_orientation = euler_from_quaternion((0,0,0,0))\nrobot_orientation_w = 0.0\nrobot_orientation_z = 0.0\n\n#Last qr read position in camera frame\nlast_qr_camera_pose = [0.0, 0.0, 0.0]\n\n# Transformation\ntf_matrix\n\nclass QR:\n def __init__(self, data1):\n data = str(data1)\n\n split_data = data.split(\"\\\\r\\\\n\")\n counter = 0\n for i in split_data:\n i = i.split(\"=\")[1]\n split_data[counter] = i\n counter += 1\n self.split_data = split_data\n self.x=float(split_data[0])\n self.y=float(split_data[1])\n self.nx=float(split_data[2])\n self.ny=float(split_data[3])\n self.number=int(split_data[4])\n self.letter=split_data[5][0]\n self.read_time = time.time() \n\n self.camera_frame_xyz = [0.0, 0.0, 0.0]\n self.robot_frame_x = 0.0\n self.robot_frame_y = 0.0\n self.robot_frame_z = 0.0\n\ndef goal_pose(pose): \n goal_pose = MoveBaseGoal()\n goal_pose.target_pose.header.frame_id = 'map'\n goal_pose.target_pose.pose.position.x = pose[0][0]\n goal_pose.target_pose.pose.position.y = pose[0][1]\n goal_pose.target_pose.pose.position.z = pose[0][2]\n goal_pose.target_pose.pose.orientation.x = pose[1][0]\n goal_pose.target_pose.pose.orientation.y = pose[1][1]\n goal_pose.target_pose.pose.orientation.z = pose[1][2]\n goal_pose.target_pose.pose.orientation.w = pose[1][3]\n return goal_pose\n\ndef second_qr(qr1):\n # PTO 1\n x1 = qr1.x # x_info_qr_code_1_world_frame\n y1 = qr1.y # y_info_qr_code_1_world_frame\n\n # PTO 2\n x2 = qr1.nx # x_info_qr_code_2_world_frame\n y2 = qr1.ny # y_info_qr_code_2_world_frame\n\n # Distance\n dist = math.sqrt(math.pow(x1-x2,2) + math.pow(y1-y2,2))\n\n x_robot_qr1 = qr1.robot_frame_x\n y_robot_qr1 = qr1.robot_frame_y\n\n x = x2\n y = math.sqrt(math.pow(dist,2) - math.pow(x-x_robot_qr1,2)) + y_robot_qr1\n # for i in range(1,4)\n # x = x2 + i\n # y = sqrt(math.pow(dist,2) - math.pow(x-x1,2)) + y1\n\n # for i in range(1,10)\n # x = 1 + i\n # y = sqrt(dist^2 - (x-x1)^2) + y1\n\n qr2_position = []\n qr2_position = [x,y]\n return qr2_position\n\n\ndef check_qr(t_interval):\n if len(qr_list) == 0:\n return False\n if (time.time() - qr_list[-1].read_time < t_interval):\n return True\n return False\n\n\ndef update_qr_important_list():\n if (last_qr_camera_pose[0] == 0.0):\n return False\n tmp = qr_list[-1]\n if (qr_important_list[tmp.number-1] != 0):\n return False\n\n # vec takes two arguments first as x and second as y\n vec = [last_qr_camera_pose[2], -last_qr_camera_pose[0], 0, 0]\n tmp.camera_frame_xyz = vec\n \n\n # vec_rotated = quaternion_multiply(quaternion_multiply(robot_orientation, vec),quaternion_conjugate(robot_orientation))\n global robot_orientation\n tmp.robot_frame_x = cur_robot_pose_x\n # rospy.loginfo(\"I heard %f, %f, %f \\n\", tmp.robot_frame_x, tmp.robot_frame_y, tmp.robot_frame_z)\n\n tmp.robot_frame_x += (abs(vec[0]))*math.cos(robot_orientation[2])\n tmp.robot_frame_y = cur_robot_pose_y + vec[0]*math.sin(robot_orientation[2])\n tmp.robot_frame_z = cur_robot_pose_z + 0\n\n #assign qr to a right position in the list\n qr_important_list[tmp.number-1] = tmp\n qr_stored_list.append(tmp)\n\n rospy.loginfo(\"################## QR_FOUND %f ################# \\n\", tmp.number)\n rospy.loginfo(\"qr_in_robot_frame %f, %f, %f \\n\", tmp.robot_frame_x, tmp.robot_frame_y, vec[0]*math.cos(robot_orientation[2]))\n # rospy.loginfo(\"curr_robot_pos %f, %f, %f \\n\", cur_robot_pose_x, cur_robot_pose_y, cur_robot_pose_z)\n\n # rospy.loginfo(\"I heard vec %f, %f, %f \\n\", vec[0], vec[1], robot_orientation[2])\n\n # rospy.loginfo(\"I heard vec_rotated %f, %f, %f \\n\", vec_rotated[0], vec_rotated[1], vec_rotated[2])\n # rospy.loginfo(\"I heard curr_robot_pos %f, %f, %f \\n\", cur_robot_pose_x, cur_robot_pose_y, cur_robot_pose_z)\n\n return True\n\ndef print_final_word():\n print('########### Printing final word: \\n')\n for qr in qr_important_list:\n if qr != 0:\n print(qr.letter)\n continue\n\ndef qr_callback(data):\n qr_list.append(QR(data))\n\ndef qr_camera_pose_callback(data):\n x = data.pose.position.x\n y = data.pose.position.y\n z = abs(data.pose.position.z)\n if (z != 0.0):\n last_qr_camera_pose[0] = x\n last_qr_camera_pose[1] = y\n last_qr_camera_pose[2] = z\n\n#Update position of last qr in camera frame\ndef update_robot_pose_callback(pose_with_cov):\n global cur_robot_pose_x\n cur_robot_pose_x = pose_with_cov.pose.pose.position.x\n global cur_robot_pose_y\n cur_robot_pose_y = pose_with_cov.pose.pose.position.y\n global cur_robot_pose_z\n cur_robot_pose_z = pose_with_cov.pose.pose.position.z\n # print(cur_robot_pose_x)\n global robot_orientation\n \n # getting robot orientation\n robot_orientation_w = pose_with_cov.pose.pose.orientation.w\n robot_orientation_z = pose_with_cov.pose.pose.orientation.z\n q = (0, 0, robot_orientation_z, robot_orientation_w)\n euler = euler_from_quaternion(q, 'sxyz')\n robot_orientation = euler\n\n# ROS SUBSCRIBERS\nrospy.Subscriber(\"qr_codes\", My_string, qr_callback)\nrospy.Subscriber(\"visp_auto_tracker/object_position\", PoseStamped, qr_camera_pose_callback)\nrospy.Subscriber(\"amcl_pose\", PoseWithCovarianceStamped, update_robot_pose_callback)\n\nif __name__ == '__main__':\n rospy.init_node('patrol')\n client = actionlib.SimpleActionClient('move_base', MoveBaseAction) \n client.wait_for_server()\n flag = True\n tf_doesnt_exists = True\n global tf_matrix\n\n rospy.sleep(0.1)\n # tf_matrix = transform_matrix()\n # if check_qr(1):\n # if update_qr_important_list():\n # # print(tf_matrix)\n # # qr_next = next_qr_position(tf_matrix,qr_stored_list[-1])\n # rospy.loginfo(\"number: %f , x: %f, y: %f , next_x: %f , next_y: %f \\n\", qr_list[-1].number, qr_list[-1].x, qr_list[-1].y, qr_list[-1].nx, qr_list[-1].ny)\n # # print(last_qr_camera_pose)\n # # break\n\n \n for pose in random_waypoints:\n # rospy.loginfo(\"msg %s \\n\", \"new waypoint\")\n goal = goal_pose(pose)\n client.send_goal(goal)\n client.wait_for_result()\n # rospy.loginfo(\"msg %s \\n\", \"reached waypoint\")\n rospy.sleep(0.5)\n if check_qr(1):\n if update_qr_important_list():\n break\n # rospy.loginfo(\"number: %f , x: %f, y: %f , next_x: %f , next_y: %f \\n\", qr_list[-1].number, qr_list[-1].x, qr_list[-1].y, qr_list[-1].nx, qr_list[-1].ny)\n\n while tf_doesnt_exists:\n goal = goal_pose(get_pos_within_rad(qr_stored_list[-1]))\n goal = offset(pose)\n client.send_goal(goal)\n client.wait_for_result()\n rospy.sleep(0.5)\n\n if len(qr_stored_list) == 2 and tf_doesnt_exists:\n tf_matrix = transform_matrix()\n print('-------- Transformation matrix ----------- \\n')\n print(tf_matrix)\n tf_doesnt_exists = False\n \n while(len(qr_stored_list)<5):\n last_qr = qr_stored_list[-1]\n pose = next_qr_position(tf_matrix, last_qr)\n pose = offset(pose)\n goal = goal_pose(pose)\n client.send_goal(goal)\n client.wait_for_result()\n rospy.sleep(0.5)\n if check_qr(1):\n update_qr_important_list()\n #givin 200s time for task execution\n if (time.time() - start_time > 200):\n break\n\n # print(qr_important_list[1])\n # qr2 = second_qr(qr_list[-1])\n # qr2_waypoints = [[(qr2[0], qr2[1], 0.0), (0.0, 0.0, 0, 1.0)],\n # [(qr2[0], qr2[1], 0.0), (0.0, 0.0, -0.1673, 0.9859)],\n # [(qr2[0], qr2[1], 0.0), (0.0, 0.0, -math.sqrt(0.5), math.sqrt(0.5))]\n \n # for pose in qr2_waypoints:\n # rospy.loginfo(\"msg %s \\n\", \"new waypoint\")\n # goal = goal_pose(pose)\n # client.send_goal(goal)\n # client.wait_for_result()\n # rospy.loginfo(\"msg %s \\n\", \"reached waypoint\")\n # rospy.sleep(0.5)\n # if check_qr(1):\n # if update_qr_important_list():\n # break\n \n # if (time.time() - start_time > 10):\n # flag = False\n \n flag = False\n if len(qr_stored_list)<5:\n print(\"DIDNT FIND ALL THE QRS\")\n print_final_word()\n\n\n ","repo_name":"carrico200296/QRnavigation","sub_path":"smr_competition.py","file_name":"smr_competition.py","file_ext":"py","file_size_in_byte":9426,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"41"} +{"seq_id":"21652445797","text":"import imp,os,traceback\nfrom PyBirchPlugin import PyBirchPlugin\nfrom TextString import TextString\nfrom PyQt5 import QtGui\n\n\n##\n# PyBirch Plugin Architecture.\n#\n# Built with the help of: http://eli.thegreenplace.net/2012/08/07/fundamental-concepts-of-plugin-infrastructures/\n#\n# see also : http://stackoverflow.com/questions/18316820/initialize-all-the-classes-in-a-module-into-nameless-objects-in-a-list\n#\nclass PluginArchitecture:\n\n\n\tdef __init__(self):\n\t\tself.plugins = []\n\t\tself.discover_plugins()\n\t\tself.list_plugins()\n\n\tdef discover_pluginsOLD(dirs):\n\n\t\tfor dir in dirs:\n\t\t\tfor filename in os.listdir(dir):\n\t\t\t\tmodname, ext = os.path.splittext(filename)\n\t\t\t\tif ext == '.py':\n\t\t\t\t\tfile, path, descr = imp.find_module(modname,[dir])\n\t\t\t\t\tif file:\n\t\t\t\t\t\t##Loading the module register the plugin\n\t\t\t\t\t\t# in IPPluginRegistry\n\t\t\t\t\t\tmod=imp.load_module(modname,file,path,descr)\n\t\t\t\t\t\t\n\n\tdef discover_plugins(self):\n\n\t\tself.plugins=\"\"\n\t\tself.plugins=[]\n\n\t\tdir=\"plugins/\"\n\n\t\tfor filename in os.listdir(dir):\n\t\t\tmodname, ext = os.path.splitext(filename)\n\t\t\tif ext == '.py':\n\t\t\t\tfile, path, descr = imp.find_module(modname,[dir])\n\t\t\t\tif file:\n\t\t\t\t\t##Loading the module register the plugin\n\t\t\t\t\t#g in IPPluginRegistry\n\t\t\t\t\tprint(\" Module name: \"+modname)\n\t\t\t\t\t#######\n\t\t\t\t\t# This try/except block is designed to ensure that the\n\t\t\t\t\t# main client doesn't stop functioning simply because\n\t\t\t\t\t# there's a syntax error in the loading of the module.\n\t\t\t\t\t#########\n\t\t\t\t\ttry:\n\t\t\t\t\t\tmod=imp.load_module(modname,file,path,descr)\n\t\t\t\t\t\tvalue = getattr(mod, modname)\n\t\t\t\t\t\tif isinstance(value,type): \n\t\t\t\t\t\t\ttest=value()\n\t\t\t\t\t\t\tif test.get_pybirchmagic() == (\"PyBirchPluginMagic\"):\n\t\t\t\t\t\t\t\tself.plugins.append(test)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tprint(\"Not adding \"+modname+\" invalid plugin\")\n\n\t\t\t\t\t####\n\t\t\t\t\t# We still print out the stack trace so that we can troubleshoot the\n\t\t\t\t\t# plugin.\n\t\t\t\t\t####\n\t\t\t\t\texcept:\n\t\t\t\t\t\tprint(\"Error loading \"+modname+\" reason:\")\n\t\t\t\t\t\ttraceback.print_exc()\n\t\tself.list_plugins()\n\n\tdef list_plugins(self):\n\n\t\tprint(\"Listing Plugins...\")\t\n\t\tfor plugin in self.plugins:\n\t\t\ttry:\n\t\t\t\tprint(\"Plugin:\"+plugin.get_name()+\" Version: \"+plugin.get_version())\n\t\t\texcept:\n\t\t\t\tprint(\"Listing Plugins failed:\")\n\t\t\t\ttraceback.print_exc()\n\n\tdef do_user_input(self,myTextString):\n\n\t\tts = myTextString\n\n\t\tfor plugin in self.plugins:\n\t\t\ttry:\n\t\t\t\tplugin.user_input(ts)\n\t\t\texcept:\n\t\t\t\tprint(\"Dealing with server input for plugin name \"+plugin.get_name()+\" failed\")\n\t\t\t\ttraceback.print_exc()\n\n\n\n\n\n\n\tdef do_server_input(self,myTextString):\n\t\tts = myTextString\n\n\t\tfor plugin in self.plugins:\n\t\t\ttry:\n\t\t\t\tplugin.server_input(ts)\n\t\t\texcept:\n\t\t\t\tprint(\"Dealing with server input for plugin name \"+plugin.get_name()+\" failed\")\n\t\t\t\ttraceback.print_exc()\n\n\n\n\t#needs fixing! currently unused\t\n\tdef get_menu_new(self):\n\n\n\t\trescanMenu=QtGui.QMenu(\"Rescan Plugins\")\n\t\trescanAction=QtGui.QAction(\"Rescan Plugins..\",self.discover_plugins())\n\t\trescanMenu.addAction(rescanAction)\n\n\t\treturn rescanMenu \n\t\n\nif __name__ == \"__main__\":\n\n\tmyclass = PluginArchitecture()\n\tmyclass.discover_plugins()\n\n\tprint(\"Listing Valid Plugins:\")\n\tmyclass.list_plugins()\n\tprint(\"Exiting here. Program has not crashed\")\n\n\n","repo_name":"BlackXanthus/PyBirch5","sub_path":"PluginArchitecture.py","file_name":"PluginArchitecture.py","file_ext":"py","file_size_in_byte":3218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"16624179441","text":"import queue\nimport speech_recognition as sr\n\n\n# this is called from the background thread\n\nclass speech_to_text():\n def __init__(self, chat:queue.PriorityQueue) -> None:\n self.r = sr.Recognizer()\n self.m = None\n self.chat = chat\n self.stop_listening = None\n \n def transcription_callback(self, recognizer:sr.Recognizer, audio:sr.AudioData):\n # received audio data, now we'll recognize it using Whisper\n try:\n text = recognizer.recognize_whisper(audio)\n # print(\"Whisper thinks you said \" + text)\n self.chat.put((3, text))\n except sr.UnknownValueError:\n print(\"Whisper could not understand audio\")\n except sr.RequestError as e:\n print(\"Could not request results from Whisper; {0}\".format(e))\n\n def recognize_speech(self, audio_input_device:int):\n self.m = sr.Microphone(device_index=audio_input_device)\n # print(\"Microphone set up\")\n with self.m as source:\n self.r.adjust_for_ambient_noise(source) # we only need to calibrate once, before we start listening\n # start listening in the background (note that we don't have to do this inside a `with` statement)\n self.stop_listening = self.r.listen_in_background(self.m, self.transcription_callback)\n # calling this function requests that the background listener stop listening\n\n def stop_listening_for_audio(self):\n if self.stop_listening is not None:\n self.stop_listening(wait_for_stop=False) # `wait_for_stop` set to `False` to terminate immediately","repo_name":"Your-Cheese/ai-chatbot","sub_path":"transcription.py","file_name":"transcription.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"754360260","text":"from collections import namedtuple\nfrom dataclasses import dataclass\nfrom typing import Dict, Iterable, List, Set, Tuple\n\nimport aiomysql\n\n\n@dataclass\nclass BaseMessage:\n write_shards: List[int]\n timestamp: str\n author_id: int\n chat_id: int\n chat_key: str\n content: str\n\n\n@dataclass\nclass BaseUser:\n firstname: str\n lastname: str\n username: str\n user_id: int\n unread_message_count: int\n\n\nclass User(BaseUser):\n pass\n\n\n@dataclass\nclass BaseChat:\n chat_id: int\n users: Dict[int, User]\n sessions: Set[str]\n shards: Dict[str, List[int]]\n\n\nclass Message(BaseMessage):\n\n async def save(self, shard_id, conn):\n cur: aiomysql.cursors.Cursor\n async with conn.cursor() as cur:\n await cur.execute(\n 'INSERT INTO chat_message(shard_id, chat_id, timestamp, author_id, content) '\n 'VALUES (%(shard_id)s, %(chat_id)s, %(timestamp)s, %(author_id)s, %(content)s) ',\n dict(shard_id=shard_id, chat_id=self.chat_id, timestamp=self.timestamp,\n author_id=self.author_id, content=self.content)\n )\n return cur.lastrowid\n\n @classmethod\n async def mark_read(cls, user_id, chat_id, message_id, conn):\n cur: aiomysql.cursors.Cursor\n async with conn.cursor() as cur:\n await cur.execute(\n 'INSERT IGNORE INTO read_message(chat_id, user_id, message_id) '\n 'VALUES (%(chat_id)s, %(user_id)s, %(message_id)s)',\n dict(chat_id=chat_id, user_id=user_id, message_id=message_id)\n )\n\n @classmethod\n async def mark_read_many(cls, user_id, chat_id, message_ids: Iterable[int], conn):\n cur: aiomysql.cursors.Cursor\n async with conn.cursor() as cur:\n await cur.executemany(\n 'INSERT IGNORE INTO read_message(chat_id, user_id, message_id) '\n 'VALUES (%(chat_id)s, %(user_id)s, %(message_id)s)',\n [dict(chat_id=chat_id, user_id=user_id, message_id=message_id)\n for message_id in message_ids]\n )\n\n @classmethod\n async def save_many(cls, shard_id, msgs: Iterable['Message'], conn):\n cur: aiomysql.cursors.Cursor\n async with conn.cursor() as cur:\n await cur.executemany(\n 'INSERT INTO chat_message(shard_id, chat_id, timestamp, author_id, content) '\n 'VALUES (%(shard_id)s, %(chat_id)s, %(timestamp)s, %(author_id)s, %(content)s) ',\n [dict(shard_id=shard_id, chat_id=msg.chat_id, timestamp=msg.timestamp,\n author_id=msg.author_id, content=msg.content)\n for msg in msgs]\n )\n\n @classmethod\n async def load_many(cls, pool, chat_id, limit=20, before_timestamp=None):\n # TODO: реализовать пагинацию\n before_timestamp_sql = ''\n if before_timestamp:\n pass\n async with pool.acquire() as conn:\n cur: aiomysql.cursors.DictCursor\n async with conn.cursor(aiomysql.DictCursor) as cur:\n await cur.execute(\n f\"SELECT DATE_FORMAT(timestamp, '%%Y-%%m-%%dT%%TZ') AS timestamp, author_id, content, chat_id, id \"\n f\"FROM chat_message \"\n f\"WHERE chat_id = %(chat_id)s {before_timestamp_sql} \"\n f\"ORDER BY timestamp DESC LIMIT %(limit)s\",\n dict(chat_id=chat_id, limit=limit)\n )\n return await cur.fetchall()\n\n\nclass Chat(BaseChat):\n\n @staticmethod\n async def get_shards(chat_id, conn=None) -> Dict[str, List[int]]:\n shards = {'read': [], 'write': []}\n async with conn.cursor(aiomysql.DictCursor) as cur:\n await cur.execute(\n 'SELECT shard_id, `read`, `write` FROM chat_shard WHERE chat_id = %(chat_id)s',\n dict(chat_id=chat_id)\n )\n for shard in await cur.fetchall():\n if shard['read']:\n shards['read'].append(shard['shard_id'])\n if shard['write']:\n shards['write'].append(shard['shard_id'])\n\n return shards\n\n @classmethod\n async def load(cls, chat_key, conn, app_shards) -> 'Chat':\n chat = None\n cur: aiomysql.cursors.DictCursor\n async with conn.cursor(aiomysql.DictCursor) as cur:\n await cur.execute(\n \"SELECT username, firstname, lastname, u.id AS user_id, chat_id \"\n \"FROM user u \"\n \"JOIN chat_user cu ON cu.user_id = u.id \"\n \"JOIN chat c ON c.id = cu.chat_id \"\n \"WHERE c.key = %(chat_key)s\",\n dict(chat_key=chat_key)\n )\n\n for row in await cur.fetchall():\n if not chat:\n chat = Chat(\n chat_id=row['chat_id'],\n users={},\n sessions=set(),\n shards=await cls.get_shards(row['chat_id'], conn=conn),\n )\n\n chat_user_id = row['user_id']\n chat.users[chat_user_id] = User(\n user_id=chat_user_id,\n firstname=row['firstname'],\n lastname=row['lastname'],\n username=row['username'],\n unread_message_count=await chat.get_unread_message_count(chat_user_id, app_shards),\n )\n return chat\n\n async def get_unread_message_count(self, user_id, app_shards, exclude_ids: Tuple[int]=None):\n unread_message_count = 0\n\n read_shards = self.shards.get('read')\n exclude_ids_sql = ''\n extra_params = {}\n if exclude_ids:\n exclude_ids_sql = ' AND cm.id NOT IN %(exclude_ids)s'\n extra_params['exclude_ids'] = exclude_ids\n\n for shard_id in read_shards:\n shard = app_shards[shard_id]\n async with shard.acquire() as conn:\n cur: aiomysql.cursors.DictCursor\n async with conn.cursor(aiomysql.DictCursor) as cur:\n await cur.execute(\n f'SELECT count(cm.id) as unread_message_count FROM chat_message cm'\n f' LEFT OUTER JOIN read_message rm ON rm.message_id = cm.id'\n f' WHERE cm.chat_id = %(chat_id)s AND cm.author_id != %(user_id)s AND rm.id IS NULL '\n f' {exclude_ids_sql} ',\n dict(\n chat_id=self.chat_id,\n user_id=user_id,\n **extra_params\n )\n )\n unread_message_count += (await cur.fetchone())['unread_message_count']\n\n return unread_message_count\n\n @classmethod\n async def get_or_create(cls, user_id, friend_id, conn: aiomysql.Connection):\n # pool: aiomysql.pool.Pool = request.app['db_pool']\n # conn: aiomysql.Connection\n # async with pool.acquire() as conn:\n cur: aiomysql.cursors.DictCursor\n async with conn.cursor(aiomysql.DictCursor) as cur:\n await cur.execute(\n 'SELECT chat_id FROM chat_user cu WHERE user_id = %(friend_id)s '\n ' AND EXISTS(SELECT 1 FROM chat_user WHERE user_id = %(uid)s '\n ' AND chat_id = cu.chat_id) '\n ' ORDER BY chat_id DESC LIMIT 1',\n dict(\n friend_id=friend_id,\n uid=user_id\n )\n )\n chat_row = await cur.fetchone()\n if chat_row:\n chat_id = chat_row['chat_id']\n else:\n # smallest_shard_id get by max(chat_message.id) from shards\n await cur.execute(\"SELECT id FROM shard ORDER BY size LIMIT 1\")\n smallest_shard_id = (await cur.fetchone())['id']\n\n await conn.begin()\n await cur.execute(\n \"INSERT INTO chat (`type`, `key`) VALUES ('peer2peer', uuid()); \"\n )\n chat_id = cur.lastrowid\n await cur.execute(\n \"INSERT INTO chat_user (user_id, chat_id) \"\n \" VALUES (%(friend_id)s, %(chat_id)s), (%(uid)s, %(chat_id)s);\",\n dict(\n friend_id=friend_id,\n uid=user_id,\n chat_id=chat_id\n )\n )\n await cur.execute(\n \"INSERT INTO chat_shard (chat_id, shard_id, `read`, `write`) \"\n \"VALUES (%(chat_id)s, %(shard_id)s, 1, 1);\",\n dict(\n shard_id=smallest_shard_id,\n chat_id=chat_id\n )\n )\n await conn.commit()\n\n await cur.execute(\"SELECT `key` FROM chat WHERE id = %(chat_id)s\", dict(chat_id=chat_id))\n chat_key = (await cur.fetchone())['key']\n\n return chat_key\n","repo_name":"polosaty/socnet-otus-chat","sub_path":"backend/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":9100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"31628517836","text":"import os\n\nfrom backend.app.settings import BASE_DIR\nfrom backend.slider.models import Slide\nfrom backend.slider.models import Slider\nfrom django.conf import settings\nfrom django.core.files.storage import default_storage\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom django.core.management import BaseCommand\nfrom django.utils.timezone import now\nfrom faker import Faker\n\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n faker = Faker()\n i = 1\n\n img = \"uploads/products/no_photo.jpg\"\n if not default_storage.exists(img):\n img_path = os.path.join(BASE_DIR, \"files/images\") + \"/no_photo.jpg\"\n img = SimpleUploadedFile(\n name=\"no_photo.jpg\",\n content=open(img_path, \"rb\").read(),\n content_type=\"image/jpeg\",\n )\n\n for _ in range(2):\n name = faker.name()\n slider = Slider.objects.create(\n name=name,\n url=settings.APP_BASE_URL,\n title=faker.text(20),\n description=faker.text(50),\n image=img,\n )\n\n for _ in range(4):\n Slide.objects.create(\n slider_id=slider.id,\n url=settings.APP_BASE_URL,\n title=faker.text(20),\n subtitle=faker.text(20),\n description=faker.text(50),\n discount=10,\n button_label=faker.text(10),\n show_button=True,\n date_start=now(),\n date_end=now(),\n order_position=i,\n image=img,\n )\n i = i + 1\n\n self.stdout.write(self.style.SUCCESS(\"Success\"))\n","repo_name":"vasilistotskas/grooveShop","sub_path":"src/backend/core/management/commands/populate_sliders.py","file_name":"populate_sliders.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"41"} +{"seq_id":"73777037882","text":"from .abstract_dangerous_request import AbstractDangerousRequest\nfrom taskmap_pb2 import Session, Task\nfrom dangerous_task_pb2 import DangerousAssessment\nfrom utils import get_file_system, logger\nimport re\nfrom .utils.dangerous_classifier import DangerousClassifier\n\n\nclass DangerousRequestCheck(AbstractDangerousRequest):\n\n def __init__(self):\n self.dangerous_classifier = DangerousClassifier()\n \n \n def assess_user_request(self, session: Session) -> DangerousAssessment:\n\n if len(session.task_selection.elicitation_utterances) > 0 and session.task.phase == Task.TaskPhase.PLANNING:\n text = \"\"\n for utterance in session.task_selection.elicitation_utterances:\n text += utterance + '. '\n else:\n text = session.turn[-1].user_request.interaction.text\n \n request_dangerous_assessment = self.dangerous_classifier.pred(text.lower())\n logger.warn(\"User's query is: {}\".format(text))\n logger.info(f'-> dangerous_assessment.is_dangerous: {request_dangerous_assessment.is_dangerous}')\n return request_dangerous_assessment","repo_name":"grill-lab/OAT","sub_path":"functionalities/dangerous_task/wordlist_dangerous_query_check.py","file_name":"wordlist_dangerous_query_check.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"41"} +{"seq_id":"8908874859","text":"import random\n\nimport numpy as np\n\nfrom get_exp_data import Experiment\nfrom learn_decoder import learn_decoder\nfrom rank_based_accuracy_functions import get_best_worse_topics, rank_based_accuracy_exp\n\n\ndef decode_brain_to_glove():\n random.seed(42)\n exp_1 = Experiment(exp_num=1)\n exp_2 = Experiment(exp_num=2)\n exp_3 = Experiment(exp_num=3)\n\n # train on exp 1 data\n train_M = learn_decoder(exp_1.fmri_data, exp_1.glove_vectors)\n # print(f\"{train_M.shape=}\")\n\n for exp in [exp_2, exp_3]:\n print(f\"--------- EXP_{exp.exp_num} ----------\")\n accuracy, poor_rank, high_rank, extremely_high_rank = rank_based_accuracy_exp(\n fmri_data=exp.fmri_data,\n exp_vectors=exp.glove_vectors,\n train_M=train_M,\n exp_dict=exp\n )\n print(f\"\\n avg accuracy over all data: {round(np.mean(accuracy), 1)}\\n\")\n\n print(\n f\"\\n categories with rank < {exp.extremely_rank_threshold}: \\n {get_best_worse_topics(extremely_high_rank, exp)}\"\n )\n print(f\"\\n categories with rank between {exp.high_rank_threshold} - {exp.extremely_rank_threshold}: \\n{get_best_worse_topics(high_rank, exp)}\")\n print(f\"\\n categories with rank > {exp.poor_rank_threshold}: \\n{get_best_worse_topics(poor_rank, exp)}\")\n\n\nif __name__ == \"__main__\":\n decode_brain_to_glove()\n","repo_name":"keren-github/LanguageComputationCognition","sub_path":"part_1_decode_brain_to_glove.py","file_name":"part_1_decode_brain_to_glove.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"24043487172","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"Usage: ./add_num_seq.py -d -p -s [-h]\n\n -d, --directory Path to files\n -p, --pattern Filename pattern for regex\n -s, --start Starting number of the sequence\n -h, --help Help\n\n\"\"\"\n\nfrom timeit import default_timer as timer\nfrom docopt import docopt\nimport glob\nimport os\n\n# filelist=sorted(glob.glob(\"/home/prasanth/Desktop/project/prgms/dt/details/*.txt\"))\n# i=1\n\ndef add_seq(idir, ipat, iseq):\n os.chdir(idir)\n filelist=glob.glob(ipat)\n for oldname in filelist:\n # ignore directories\n if os.path.isfile(oldname):\n # keep original path\n # basepath=os.path.split(oldname)[0:3]\n basepath=oldname.split(\"Contig\")[0]\n # newname=os.path.join(basepath, \"-{}.txt\".format(str(iseq)))\n newname=basepath + \"{}.vcf.gz\".format(str(iseq))\n iseq=int(iseq)+1\n print(\"Renaming {} to {}\".format(oldname, newname))\n os.rename(oldname, newname)\n\n\nif __name__ == \"__main__\":\n __version__ = 0.1\n start_time = timer()\n args = docopt(__doc__)\n add_seq(args['--directory'], args['--pattern'], args['--start'])\n print(\"[*] Total runtime: %.3fs\" % (timer() - start_time))\n","repo_name":"The-Bioinformatics-Group/Littorina_saxatilis","sub_path":"short_genetic_variants/scripts/add_num_seq.py","file_name":"add_num_seq.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"72421906684","text":"from flask import Flask, render_template, redirect, request\nfrom mysqlconnection import connectToMySQL\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef index():\n mysql = connectToMySQL(\"pets\")\n pets = mysql.query_db(\"SELECT * FROM pets\")\n return render_template(\"index.html\", pets_html = pets)\n\n@app.route(\"/add-pet\", methods=[\"POST\"])\ndef add_pet():\n query = \"INSERT INTO pets(name, type) VALUES (%(newpet_name)s, %(newpet_type)s)\"\n data = {\n \"newpet_name\": request.form[\"name\"],\n \"newpet_type\": request.form[\"type\"]\n }\n mysql = connectToMySQL(\"pets\")\n mysql.query_db(query,data)\n \n return redirect(\"/\")\n\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"devbaj/flask_mysql","sub_path":"pets/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"17074552694","text":"#!/usr/bin/env python\n# -*-encoding:utf-8-*-\n# author: navy\n# 2022/1/10 10:46\nimport logging\n\nfrom appium.webdriver import WebElement\nfrom appium.webdriver.webdriver import WebDriver\nfrom selenium.webdriver.common.by import By\n\nfrom page.wrapper import hander_black\n\n\nclass BasePage:\n\n\n def __init__(self, driver:WebDriver = None):\n self._driver = driver\n\n def finds(self, locator, value: str = None):\n elements: list\n if isinstance(locator, tuple):\n elements = self._driver.find_elements(*locator)\n else:\n elements = self._driver.find_elements(locator, value)\n return elements\n\n @hander_black\n def find(self, locator, value: str = None):\n logging.info(locator)\n logging.info(value)\n element: WebElement\n\n if isinstance(locator, tuple):\n element = self._driver.find_element(*locator)\n else:\n element = self._driver.find_element(locator, value)\n\n return element\n\n\n def find_and_get_text(self, locator, value: str = None):\n element: WebElement\n try:\n if isinstance(locator, tuple):\n element_text = self._driver.find_element(*locator).text\n else:\n element_text = self._driver.find_element(locator, value).text\n self._error_num = 0\n self._driver.implicitly_wait(10)\n return element_text\n except Exception as e:\n self._driver.implicitly_wait(1)\n if self._error_num > self._max_num:\n raise e\n self._error_num += 1\n for ele in self._black_list:\n elelist = self._driver.find_elements(*ele)\n if len(elelist) > 0:\n elelist[0].click()\n return self.find_and_get_text(locator, value)\n raise e\n\n\n","repo_name":"navy2013/autotests","sub_path":"15-UI自动化测��框架/page/base_page.py","file_name":"base_page.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"40075271167","text":"needle = \"cd\"\nhaystack = \"abcdefg\"\n\nprint(\"Haystack: \", haystack)\nprint(\"Needle: \", needle)\n\n# delcaring the thing we will use to compare strings\ncheckList = []\nm = 0\n\n# if the needle is bigger than the haystack\nif len(haystack) < len(needle):\n print(\"Needle not found\")\n\n# first iteration of filling the thing to be checked\nfor i in range(len(needle)):\n checkList.append(haystack[i])\n\n# turning the checklist into a string for comparison\ncheckString = \"\".join(checkList)\nprint(checkString)\n\nif checkString == needle:\n print(\"Needle Found at index\", m)\n\ni = i+1\nm = m+1\n\nif i >= len(haystack):\n print(\"Needle not found\")\n\n\nwhile checkString != needle:\n checkList.remove(checkList[0])\n checkList.append(haystack[i])\n checkString = \"\".join(checkList)\n if checkString == needle:\n print(\"Needle Found at index\", m)\n print(checkString)\n print(i)\n i = i + 1\n m = m + 1\n if i >= len(haystack):\n print(\"Needle not found\")\n","repo_name":"rory-oconnell/LeetCode","sub_path":"Problems/28.py","file_name":"28.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"22751542228","text":"import json\n\nfrom Ej3.partition import partition\nimport numpy as np\nfrom Ej3.parse_numbers import parse_numbers, numbers_map\nfrom perceptron.MultiLayerPerceptron import MultiLayerPerceptron\nfrom perceptron.activation_functions import Sigmoid, Tanh\nfrom perceptron.errors import MeanSquared\nfrom perceptron.optimizer import Adam, GradientDescent\nfrom perceptron.trainer import Batch\nfrom Ej3.noise import print_number, noisify\nfrom matplotlib import pyplot as plt\n\ndef run_simulations(train_proportions, iterations, opt_method):\n json_result = {\n \"iterations\": iterations,\n \"values\": [],\n \"optimization\": opt_method\n }\n x_train = parse_numbers()\n y_train = [(1 if i % 2 == 0 else 0) for i in range(10)]\n\n for train_proportion in train_proportions:\n print(f\"training proportion {train_proportion}\")\n \"\"\"\n {\"iters\": 10,\n \"values\": [{\"dataset p\": 0.1, \"accuracy\": 0.2, \"std\": 0.05}, {\"dataset p\": 0.3, \"accuracy\": 0.8, \"std\": 0.02}]}\n \"\"\"\n training_proportion_obj = {\"training proportion \": train_proportion}\n accuracies = []\n for iter in range(iterations):\n train_x, train_y, test_x, test_y = partition(x_train, y_train, train_proportion)\n p = MultiLayerPerceptron([10], 7*5, 1, Sigmoid, Adam())\n p.train(MeanSquared, train_x, train_y, Batch(), 20000, 0.01, False)\n\n #noisified_x = [noisify(num_map[i],intensity) for i in range(len(x_train))]\n\n correct = 0\n for idx, val in enumerate(test_x):\n real_number = x_train.index(val)\n guess = p.predict(val)\n print(f\"real number {real_number}, guess: {guess}\")\n if (guess >= 0.5 and real_number % 2 == 0) or (guess < 0.5 and real_number % 2 == 1):\n correct += 1\n\n accuracy = float(correct)/len(test_x)\n accuracies.append(accuracy)\n\n training_proportion_obj[\"std\"] = np.std(accuracies)\n training_proportion_obj[\"accuracy\"] = np.mean(accuracies)\n json_result[\"values\"].append(training_proportion_obj)\n\n with open('../../result3bAccuracyVsTrainingProportion.json', 'w') as json_file:\n json.dump(json_result, json_file)\n\ndef plot_accuracy_by_proportion(opt_method):\n with open('../../result3bAccuracyVsTrainingProportion.json', 'r') as file:\n data = json.load(file)\n\n training_proportions = [item[\"training proportion \"] for item in data[\"values\"]]\n accuracies = [item[\"accuracy\"] for item in data[\"values\"]]\n\n plt.plot(training_proportions, accuracies, marker='o', linestyle='-')\n plt.xlabel('Proportion of Dataset used for Training')\n plt.ylabel('Accuracy')\n plt.title(f'Accuracy vs. Proportion of Dataset used for Training using {opt_method}', fontsize=10)\n plt.grid(True)\n plt.ylim(0.1, 1.0)\n\n plt.show()\ndef main():\n run_simulations([0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8], 10, 'ADAM')\n plot_accuracy_by_proportion('ADAM')\n\nif __name__ == '__main__':\n main()\n","repo_name":"tataabancens/SIA-Grupo-06","sub_path":"TP-3/Ej3/plot/b/accuracy_by_dataset.py","file_name":"accuracy_by_dataset.py","file_ext":"py","file_size_in_byte":3036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"19969643659","text":"#!/usr/bin/env python\n\n\"\"\"\n Unit tests based on PyUnit.\n\"\"\"\n\n# Add parent directory to python search path\n# ------------------------------------------\nimport sys\nsys.path.insert(0,'..')\n\nimport os\nimport unittest\n\nfrom utudx import utUDX, run\n\n#......................................................................\n\nclass ut(utUDX):\n\n def setUp(self):\n utUDX.setUp(self,['hello.udxt','hello/hello.udxt'])\n\n#--\n \n def test_udc_hello(self):\n self.ga('hello Caetano Veloso')\n self.assertEqual(\"\",self.ga.rword(2,3))\n self.assertEqual(\"\",self.ga.rword(3,3))\n self.assertEqual(\"\",self.ga.rword(4,3))\n\n def test_udf_hello(self):\n self.ga('d hello()')\n self.assertEqual(\"[1]\",self.ga.rword(1,1))\n self.assertEqual(\"Hello,\",self.ga.rword(1,2))\n self.assertEqual(\"GrADS\",self.ga.rword(1,3))\n self.assertEqual(\"World!\",self.ga.rword(1,5))\n\n#......................................................................\n\nif __name__ == \"__main__\":\n run(ut)\n","repo_name":"jprules321/colas","sub_path":"wgrib2-v0.1.9.4/extensions/hello/ut.py","file_name":"ut.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"1380369076","text":"import torch\nimport torch.nn as nn\nimport torchvision\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nimport torchvision.transforms as transforms\nimport torchvision.datasets as datasets\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\nimport time\nfrom PIL import Image\nimport glob\nimport keyboard\nimport random\n\ncifar10_map = {0:\"airplane\", 1:\"automobile\", 2:\"bird\", 3:\"cat\", 4:\"deer\", 5:\"dog\", 6:\"frog\", 7:\"horse\", 8:\"ship\", 9:\"truck\"}\n\n\nmodel_location = \"Model\\\\model1.pth\"\n\ndevice = torch.device(\"cpu\")\nif torch.cuda.is_available():\n device = torch.device(\"cuda\")\n print(f\"Cuda version {torch.cuda_version} enabled.\")\n\ntransform_list = transforms.Compose([\n transforms.RandomRotation(90),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n\n])\n\n# Hyperparameters\nbatch_size=32\nlearning_rate=0.00003\nepochs=200\n\n\n# Cifar10 is 32X32 Color Images\ntrain_data = datasets.CIFAR10(root=\"./CIFAR10\", transform=transform_list, train=True, download=True)\ntest_data = datasets.CIFAR10(root=\"./CIFAR10\", transform=transform_list, train=False, download=True)\n\ntrain_loader = DataLoader(dataset=train_data, shuffle=True, batch_size=batch_size)\ntest_loader = DataLoader(dataset=test_data, shuffle=True, batch_size=batch_size)\n\n\n# class CNN(nn.Module):\n# def __init__(self):\n# super(CNN, self).__init__()\n# self.conv1 = nn.Conv2d(in_channels=3, out_channels=8, kernel_size=2)\n# self.conv2 = nn.Conv2d(in_channels=8, out_channels=16, kernel_size=2)\n# self.conv3 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=2)\n# self.MP2D = nn.MaxPool2d(2) #Kernel size = 2x2\n# self.lin1 = nn.Linear(6272, 1024)\n# self.lin2 = nn.Linear(1024, 128)\n# self.lin3 = nn.Linear(128, 10)\n# self.dropoutLin = nn.Dropout(0.5)\n# self.dropoutConv = nn.Dropout(0.8)\n#\n# def forward(self, x):\n# x = F.relu(self.conv1(x))\n# # x = self.dropoutConv(x)\n# x = F.relu(self.conv2(x))\n# # x = self.dropoutConv(x)\n# x = F.relu(self.conv3(x))\n# x = self.dropoutConv(x)\n# x = self.MP2D(x)\n# # print(x.shape)\n# x = x.view(-1, 6272)\n# x = F.relu(self.lin1(x))\n# x = self.dropoutLin(x)\n# x = F.relu(self.lin2(x))\n# x = self.dropoutLin(x)\n# x = F.relu(self.lin3(x))\n# # x = self.dropoutLin(x)\n# # return F.softmax(x, dim=1)\n# return x\n\n\n##############################################################################################################\n\n\n\n\n######################################################################################################################\nmodel = torchvision.models.resnet50(pretrained=False).to(device)\n# model = CNN().to(device)\npytorch_total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\nprint(f\"Model Trainable Parameters = {pytorch_total_params}\")\nloss_function = nn.CrossEntropyLoss()\noptimizer = optim.SGD(params=model.parameters(), lr=learning_rate, momentum=0.9, weight_decay=5e-4)\nscheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=200)\n\ndef train():\n model.train()\n for epoch in range(epochs):\n model.train()\n for batch_index, (data, label) in enumerate(train_loader):\n data = data.to(device)\n label = label.to(device)\n\n predicted = model(data)\n loss = loss_function(predicted, label)\n\n optimizer.zero_grad()\n loss.backward()\n\n optimizer.step()\n\n if batch_index%50 == 0:\n print(f\"On Batch {batch_index}/{len(train_data)/batch_size}, with loss {loss.item()}\")\n print(f\"Epoch = {epoch}\")\n model.eval()\n test()\n print(\"ran\")\n torch.save(model, model_location)\n\ndef test():\n model.eval()\n len_test_data = len(test_data)\n num_correct = 0\n\n for batch_index, (data, label) in enumerate(test_loader):\n data = data.to(device)\n label = label.to(device)\n\n predicted = model(data)\n # print(predicted.shape)\n maxes = torch.argmax(predicted, dim=1)\n\n num_correct += (maxes == label).sum()\n\n print(f\"Num Correct = {num_correct}\")\n print(f\"Num Total = {len_test_data}\")\n print(f\"Percent Correct = {(num_correct/len_test_data)*100}\")\n model.train()\n\ndef load_single():\n capture_location = \"custom.jpg\"\n transform_load = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ])\n model2 = torch.load(model_location)\n model2 = model2.to(device)\n model2.eval()\n while True:\n while True:\n if keyboard.is_pressed(\"l\"):\n break;\n image_custom = cv2.imread(capture_location)\n image_custom = cv2.resize(image_custom, (32, 32))\n image_custom = transform_load(image_custom)\n with torch.no_grad():\n single_trial_tensor = image_custom.unsqueeze(0)\n single_trial_tensor = single_trial_tensor.to(device)\n test_individual(model2, single_trial_tensor)\n\n #Display\n img_show = Image.open(capture_location)\n img_show.show()\n\n\ndef test_individual(model, tensor):\n model.eval()\n with torch.no_grad():\n category_guessed = cifar10_map[model(tensor).max(1)[1].item()]\n print(f\"Guess = {category_guessed}\")\n model.train()\n\nfor epoch in range(200):\n train()\n test()\n scheduler.step()\n\n# model = torch.load(model_location).to(device)\n# test()\n# load_single()\n\n\n# fig = plt.figure(figsize=(8, 8))\n# cols, rows = 3, 3\n# for i in range(1, cols*rows+1):\n# sample_idx=random.randint(0, len(train_data))\n# img, label = train_data[sample_idx]\n# print(img.size())\n# print(img.squeeze().size())\n# fig.add_subplot(rows, cols, i)\n# plt.axis(\"off\")\n# img = transforms.Grayscale()(img)\n# plt.imshow(img.squeeze(), cmap=\"gray\")\n# plt.show()","repo_name":"Ryguy-1/CIFAR10-Workspace","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"10337146402","text":"\"\"\"\nGiven an integer input, n, determine the Fibonacci number at the n-th position. The n can be any integer\nnumber starting from 0 (including the 0).\nThe Fibonacci Number sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...\nExample 1:\nInput: n = 0\nOutput: 0\nExplanation: The first number in the sequence is 0\nExample 2:\nInput: n = 1\nOutput: 1\nExplanation: The second number in the sequence is 1\nExample 3:\nInput: n = 4\nOutput: 3\nExplanation: The fifth number in the sequence is 3\n\"\"\"\n\nfibonacci = [0, 1]\n\nnum = int(input())\nfor i in range(num):\n fibonacci.append(fibonacci[i] + fibonacci[i + 1])\n\nprint(fibonacci[num])\n","repo_name":"LongDongLo/Lessons","sub_path":"Level 1/Lesson 4/Homework.py","file_name":"Homework.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"41547909059","text":"import streamlit as st\nfrom streamlit_option_menu import option_menu\nimport http.client\nimport base64\nimport json\nimport re\nimport os\n###################################\nfrom st_aggrid import AgGrid\nfrom st_aggrid.grid_options_builder import GridOptionsBuilder\nfrom st_aggrid.shared import JsCode\n###################################\nis_exception_raised = False\noutput = None\n\ndef _max_width_():\n max_width_str = f\"max-width: 1800px;\"\n st.markdown(\n f\"\"\"\n \n \"\"\",\n unsafe_allow_html=True,\n )\n\ndef select_host(selected):\n if selected==\"AWS\":\n api_key=os.getenv('api_key_aws')\n conn_addr=os.getenv('conn_addr_aws')\n conn_req=os.getenv('conn_req_aws')\n # api_key=\"dm32GHs3S9eojhMm5SsV9FbG\"\n # conn_addr=\"gastro-web-4-1.am22ensuxenodo5ihblszm8.cloud.cnvrg.io\"\n # conn_req=\"/api/v1/endpoints/cukczelw3sytfuga7byy\"\n elif selected==\"Intel DevCloud\":\n api_key=os.getenv('api_key_intel')\n conn_addr=os.getenv('conn_addr_intel')\n conn_req=os.getenv('conn_req_intel') \n # api_key=\"WeaN8QbbKmhWZHJryoJzuUM1\"\n # conn_addr=\"ecg-web-dev-cloud-1.aaorm9bej4xwhihmdknjw5e.cloud.cnvrg.io\"\n # conn_req=\"/api/v1/endpoints/q6wmgijl7mqesrqneoau\"\n else:\n api_key=os.getenv('api_key_aws')\n conn_addr=os.getenv('conn_addr_aws')\n conn_req=os.getenv('conn_req_aws')\n # api_key=\"dm32GHs3S9eojhMm5SsV9FbG\"\n # conn_addr=\"gastro-web-4-1.am22ensuxenodo5ihblszm8.cloud.cnvrg.io\"\n # conn_req=\"/api/v1/endpoints/cukczelw3sytfuga7byy\"\n return api_key, conn_addr, conn_req\n \nst.set_page_config(page_icon=\"✂️\", page_title=\"Crohn's Treatment Outcome Prediction\", layout=\"wide\")\n\nwith st.sidebar:\n selected = option_menu(\n menu_title=\"Choose web host\", # required\n options=[\"AWS\", \"Intel DevCloud (Future)\", \"Azure (Future)\"], # required\n icons=[\"snow2\", \"bank2\", \"microsoft\"], # optional\n menu_icon=\"heart-pulse\", # optional\n default_index=0, # optional\n )\n st.info(f'web host is {selected}', icon=\"ℹ️\")\n\nc1_1, c1_2, _, _ = st.columns([3.5, 8, 8, 8])\nwith c1_1:\n st.image('./intel.png', width=100)\nwith c1_2:\n st.subheader('Developer Cloud')\n\nc1, c2 = st.columns([5,5])\nwith c1:\n st.title(\"Crohn's Treatment Outcome Prediction\")\n st.write('''\n Capsule endoscopy (CE) is a prime modality for diagnosing and monitoring Crohn's disease (CD). \n However, CE's video wasn't utilized for predicting the success of biologic therapy.\n This demo runs the Timesformer model trained on Sheba data by Intel's New AI technologies group.\n The model reaches a 20% improvement over the best existing biomarker (fecal calprotectin) while providing decision explainability and confidence level\n ''')\n st.image('CE_basic.jpg', width=200)\n st.image('footer.png')\n\nwith c2:\n api_key, conn_addr, conn_req = select_host(selected)\n uploaded_file = st.file_uploader(\"\", type=\"npy\", key=\"1\")\n if uploaded_file is not None:\n content = uploaded_file.read()\n encoded_string = base64.b64encode(content).decode(\"utf-8\")\n request_dict = {\"input_params\":encoded_string}\n payload = '{\"input_params\":' + json.dumps(request_dict) + \"}\"\n headers = {\n 'Cnvrg-Api-Key': api_key,\n 'Content-Type': \"application/json\"\n }\n\n if uploaded_file is not None:\n file_container = st.expander(\"Check your uploaded .csv\")\n with st.spinner('This might take few seconds ... '):\n try:\n conn = http.client.HTTPSConnection(conn_addr)\n st.info('Sending File to the server')\n conn.request(\"POST\", conn_req, payload, headers)\n st.info('Got server POST response')\n res = conn.getresponse()\n data = res.read()\n output = data.decode(\"utf-8\")\n except: \n st.error('Cant connect to server. Try to disable VPN!')\n is_exception_raised = True\n output = None\n\n if not is_exception_raised and output is not None:\n gender = re.sub(r'.*\\\":\\[\\\"(.*le)\\\"\\,.*',r'\\1', output)\n prob = re.sub(r'.*le\\\"\\,(0.\\d{3}).*',r'\\1', output)\n prob_perc = float(prob)*100 \n mortality_chance=re.sub(r'.*chance\\\"\\,(0.\\d{3}).*',r'\\1', output)\n mortality_chance_perc=float(mortality_chance)*100\n cardiac_ejection=re.sub(r'.*fraction\\\"\\,(0.\\d{3}).*',r'\\1', output)\n cardiac_ejection_perc=float(cardiac_ejection)*100\n\n st.metric(label=\"Non-normal cardiac ejection fraction probability\", value=f\"{mortality_chance_perc}%\")\n st.metric(label=f'Cardiac ejection fraction', value=f\"{cardiac_ejection_perc}%\")\n st.metric(label=f'Gender', value=f\"{gender}\")\n st.metric(label=f'Gender Confidence', value=f\"{prob_perc}%\")\n else:\n st.info(f\"\"\"👆 Please upload a .npy ECG file first\"\"\")\n st.stop()\n","repo_name":"amitgurintelcom/gender-ecg-app","sub_path":"app_crohn.py","file_name":"app_crohn.py","file_ext":"py","file_size_in_byte":5130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"31583355508","text":"from kanamoji import KANAMOJI\nimport logic\n\n\ndef test_randomize_choices_returns_proper_number():\n choices = logic.randomize_choices(KANAMOJI)\n assert 3 == len(choices)\n\n\ndef test_random_choices_are_defined():\n choices = logic.randomize_choices(KANAMOJI)\n for choice in choices:\n assert choice in KANAMOJI\n\n\ndef test_basic_options():\n choices = [{'romaji': 'ji'}]\n output = logic.format_options(choices)\n assert '0 - ji' == output\n\n\ndef test_two_options():\n choices = [{'romaji': 'ji'},\n {'romaji': 'ke'}]\n output = logic.format_options(choices)\n assert '0 - ji\\n1 - ke' == output\n\n\ndef test_three_options():\n choices = [{'romaji': 'ji'},\n {'romaji': 'ke'},\n {'romaji': 'ma'}]\n output = logic.format_options(choices)\n assert '0 - ji\\n1 - ke\\n2 - ma' == output\n\n\ndef test_game_answer_checking():\n game = logic.FlashCardGame('hiragana', KANAMOJI)\n game.choices = [{'romaji': 'su'}]\n game.answer = {'romaji': 'su'}\n assert game.check_answer(0)\n\n\ndef test_game_answer_bounds_checking():\n game = logic.FlashCardGame('hiragana', KANAMOJI)\n game.choices = [{'romaji': 'su'}]\n game.answer = {'romaji': 'su'}\n assert not game.check_answer(1)\n assert not game.check_answer(-1)\n\n\ndef test_game_randomizes_each_time():\n game = logic.FlashCardGame('hiragana', KANAMOJI)\n game.start_question()\n first_choices = game.choices\n first_answer = game.answer\n game.start_question()\n\n assert not first_choices == game.choices\n assert not first_answer == game.answer\n","repo_name":"nrb/jp-cli-flashcards","sub_path":"test_logic.py","file_name":"test_logic.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"20701426059","text":"from multiprocessing import Process, Pool\nimport os, time\nimport requests\nfrom bs4 import BeautifulSoup\nfrom retry.api import retry_call\nfrom time import process_time\n\nclass TixCraftCrawlerConcertPage():\n\n def __init__(self):\n self._concert_text_list=[]\n\n def request_url(self, url = None):\n headers = {\n 'Accept-Language': 'zh-TW,zh;q=0.9,en;q=0.8,en-US;q=0.7',\n 'Content-Type': 'text/html',\n 'Upgrade-Insecure-Requests':'1',\n 'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36'\n }\n proxies = {\n 'https': 'https://www.president.gov.tw/Default.aspx',\n }\n web = requests.get(url, timeout=20, proxies=proxies)\n \n status = web.status_code\n print(\"子處理程序 ID: {}, 運送結果: {}, processTime:{}\".format(os.getpid(), url, process_time()))\n if status == 200:\n return web\n \n return None\n \n def get_concert_info_html(self, url):\n # 單一場演唱會的頁面\n tixcraft_domain_name = 'https://tixcraft.com'\n concert_page_url = tixcraft_domain_name + url\n concert_web = retry_call(self.request_url, fkwargs={\"url\": concert_page_url}, tries=3)\n concert_text = None\n if concert_web:\n concert_soup = BeautifulSoup(concert_web.text, \"html5lib\")\n activity = concert_soup.select('#intro')\n concert_text = activity[0].get_text()\n\n return concert_text\n \n def process_run(self, concert_url_list):\n t1_start = process_time()\n print('主處理程序 ID:', os.getpid())\n # cpus = os.cpu_count() \n # print('cpuc:' + str(cpus))\n pool = Pool(4)\n result = pool.map(self.get_concert_info_html, concert_url_list)\n pool.close()\n pool.join()\n t1_stop = process_time()\n print(\"process:\" + str(t1_stop-t1_start))\n return result\n\ndef process_pool():\n t1_start = process_time()\n print('主處理程序 ID:', os.getpid())\n # cpus = os.cpu_count() \n # print('cpuc:' + str(cpus))\n pool = Pool(4)\n d = TixCraftCrawlerConcertPage()\n result = pool.map(d.get_concert_info_html, ['/activity/detail/24_rod', '/activity/detail/24_flybm', '/activity/detail/24_enhypen'])\n pool.close()\n pool.join()\n t1_stop = process_time()\n print(t1_stop-t1_start) \n\ndef singleProcess():\n t1_start = process_time()\n url_list = ['/activity/detail/24_rod', '/activity/detail/24_flybm', '/activity/detail/24_enhypen']\n for url in url_list:\n d = TixCraftCrawlerConcertPage()\n d.get_concert_info_html(url)\n\n t1_stop = process_time() \n print(t1_stop-t1_start)\n\nif __name__ == '__main__':\n # singleProcess()\n process_pool()\n ","repo_name":"stella0320/live-now-job","sub_path":"script/crawler/tixcraftCrawler/tixcraftCrawlerConcertPage.py","file_name":"tixcraftCrawlerConcertPage.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"4490479998","text":"import codecs\nimport json\nimport random\n\nfrom src.predicate import predicate_new, predicate_ex\n\nDATA_INPUT_DIR = json.load(codecs.open('../config/config.json'))[\"data_input_dir\"]\nRESULT_SAVE_DIR = json.load(codecs.open('../config/config.json'))[\"save_dir\"]\n\n\ndef feature_mmr(app_test_dict):\n \"\"\"\n 对测试集进行mmr的计算,基于特征工程的mmr计算\n :param app_test_dict: 输入的测试集,包含app名称和对应的实体的集合\n :return: 每个app的mmr\n \"\"\"\n test_review = json.load(open('../benchmark/similar.json', 'r', encoding='utf8'))\n\n train_data = json.load(open('../train/trainapp.json', 'r', encoding='utf8'))\n\n for i in app_test_dict:\n mmr = 0\n # top20 = list()\n review = test_review[i] # 保存的基准的相似的列表\n result_list = list()\n entity_set = set(app_test_dict[i])\n # 遍历train_data,求交集的长度\n for app in train_data:\n train_entity_set = set(train_data[app])\n result_list.append((app, len(train_entity_set.intersection(entity_set))))\n result_list.sort(key=lambda x: x[1], reverse=True)\n # result_list = result_list[:30]\n # random.shuffle(result_list)\n\n for appname, length in result_list:\n if appname == i:\n result_list.remove((appname, length))\n\n # 计算mmr\n for appname, j in result_list[:20]:\n if appname in review:\n mmr += 1 / (result_list.index((appname, j)) + 1)\n print('{}的MMR为:{}'.format(i, mmr))\n\n\ndef line_mmr(app):\n app2id_dict = json.load(open(DATA_INPUT_DIR + 'app2id_dict.json', 'r', encoding='utf8'))\n if app2id_dict.get(app, None) == None:\n app_si_dict = predicate_new(app, 20)\n test_review = json.load(open('../benchmark/similar.json', 'r', encoding='utf8'))\n benchmark_app_list = test_review[app]\n predicate_list = app_si_dict[app]\n mmr = 0\n for i in predicate_list:\n if i in benchmark_app_list:\n mmr += 1 / (predicate_list.index(i) + 1)\n print('{}的MMR为:{}'.format(app, mmr))\n else:\n app_si_dict = predicate_ex(app, 20)\n test_review = json.load(open('../benchmark/similar.json', 'r', encoding='utf8'))\n benchmark_app_list = test_review[app]\n predicate_list = app_si_dict[app]\n mmr = 0\n for i in predicate_list:\n if i in benchmark_app_list:\n mmr += 1 / (predicate_list.index(i) + 1)\n print('{}的MMR为:{}'.format(app, mmr))\n\n\nif __name__ == '__main__':\n app_test_dict = json.load(open('../test/testapp.json', 'r', encoding='utf8'))\n # feature_mmr(app_test_dict)\n for i in app_test_dict:\n line_mmr(i)\n # a = json.load(open('../temp/app3.json','r',encoding='utf8'))\n # l = []\n # for i, j in a.items():\n # for p ,o in j.items():\n # if p=='type' and o not in l:\n # l.append(o)\n # print(l)","repo_name":"zbyzby11/network_emb","sub_path":"solve/testmmr.py","file_name":"testmmr.py","file_ext":"py","file_size_in_byte":2993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"37738212785","text":"\"\"\"Variables that multiple *.py-files in this module need access to.\"\"\"\nfrom typing import Callable\n\nopen_list = []\nclosed_list = []\nsolutions = []\n\n# Storing the specification of SP net\nincidence_matrix = []\ninit_mark_vector = []\nfinal_mark_vector = []\ntransitions_by_index = dict()\n\n# variables for the ilp heuristic_to_final\nsynchronous_product = None\ntrace = None\n\n# cost function related variables\ncost_func = Callable \n","repo_name":"pmlab/pmlab-lite","sub_path":"pmlab_lite/alignments/variables.py","file_name":"variables.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"44"} +{"seq_id":"21695456283","text":"from flask import Flask, request\r\nimport pygame\r\nimport cfg\r\napp = Flask(__name__)\r\n\r\npygame.mixer.init()\r\nbeep_sound = pygame.mixer.Sound(config.effects_path / 'beep.wav')\r\nbeep = lambda: beep_sound.play() if not cfg.mute else None\r\n\r\n@app.route('/monitor/', methods=['post'])\r\ndef monitor():\r\n data = request.get_json()\r\n print(data['created_at'], data['raw_command'])\r\n beep()\r\n return 'ok'","repo_name":"SilvrDuck/brigantion","sub_path":"monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"27198660887","text":"# Movielens\nfrom Movie_Lens.movies_load import MovieLen\n\nif __name__=='__main__':\n movielen=MovieLen()\n\n # upload to mysql database\n # movielen.upload()\n \n # Users evaluate the movie must be above 10 and evaluation score of movie must be over 2.6\n movielen.filter_movies(users_minimum_number=10,evaluation_score=2.6)\n \n # Print movie info\n movielen.info()\n print('\\n\\nTop 10 Movies')\n\n # Print top 10 movies\n movielen.top_10()","repo_name":"vasnastos/AGP","sub_path":"s2022/lab03/lab03_H3.py","file_name":"lab03_H3.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"1297735136","text":"from collections import deque\n\nv = int(input())\ngraph = [[] for _ in range(v + 1)]\n\nfor _ in range(v):\n inp = list(map(int, input().split()))\n\n for i in range(1, len(inp) - 1, 2):\n graph[inp[0]].append((inp[i], inp[i + 1]))\n\ndef bfs(g, now):\n D = [-1] * (v + 1)\n D[now] = 0\n\n queue = deque([now])\n while queue:\n top = queue.popleft()\n\n for w, d in g[top]:\n if D[w] == -1:\n D[w] = D[top] + d\n queue.append(w)\n\n return D\n\nD = bfs(graph, 1)\nprint(max(bfs(graph, D.index(max(D)))))\n","repo_name":"gsa-projects/problem-solving","sub_path":"기말고사/2/1167 - 트리의 지름 - 2.py","file_name":"1167 - 트리의 지름 - 2.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"13105245256","text":"import serial\nfrom sensor_interface import SensorInterface\n\n\nclass Sensor(SensorInterface):\n\n def __init__(self, url):\n self.serial = serial.Serial(\"/dev/ttyACM0\", 9600)\n super().__init__(url)\n\n def get_serial_number(self):\n cpu_serial = \"ERROR000000000\"\n\n with open('/proc/cpuinfo', 'r') as file:\n for line in file:\n if line[0:6] == 'Serial':\n cpu_serial = line[10:26].upper()\n file.close()\n break\n\n return cpu_serial\n\n def measure(self):\n value = int(self.serial.readline())\n return value / 32\n","repo_name":"Nuurek/co-sensor-client","sub_path":"sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"28462500984","text":"from flask import Flask,render_template,request,redirect\r\nfrom BBall import *\r\n\r\napp=Flask(__name__)\r\n#here we are creating object name app,\r\n#which points to the application\r\n@app.route('/',methods=['get'])\r\ndef index():\r\n #return \"

Home Page

\"\r\n return render_template('index.html')\r\n\r\n@app.route('/login',methods=['post'])\r\ndef login():\r\n return \"

Login Page

\"\r\n\r\n\r\n@app.route('/getroster',methods=['get'])\r\ndef showroster():\r\n data=getAllPlayers()\r\n #data is the tuple of tuples\r\n return render_template('Roster.html',Roster=data)\r\n\r\n@app.route('/addplayer')\r\ndef showadd():\r\n return render_template('addplayer.html',) \r\n\r\n@app.route('/saveplayer',methods=['post'])\r\ndef saveplayer():\r\n Id=request.form['id']\r\n bid=int(Id)\r\n name=request.form['name']\r\n ppg=request.form['ppg']\r\n apg=request.form['apg']\r\n rpg=request.form['rpg']\r\n ppg_num=float(ppg)\r\n apg_num=float(apg)\r\n rpg_num=float(rpg)\r\n player=GSW(name,ppg_num,apg_num,rpg_num,bid)\r\n addPlayer(player)\r\n return redirect('/getroster')\r\n\r\n@app.route('/deleteplayer/')\r\ndef deleteplayer(i):\r\n deletePlayerById(i)\r\n return redirect('/getroster')\r\n\r\n@app.route('/getplayer/')\r\ndef getplayer(i):\r\n b=getPlayerById(i)\r\n return render_template('updateplayer.html',player=b)\r\n\r\n@app.route('/updateplayer',methods=['post'])\r\ndef updateplayer():\r\n #fetch all 5 values from update form\r\n i=request.form['bid']\r\n bid=int(i)\r\n name=request.form['name']\r\n points=request.form['ppg']\r\n ppg=float(points)\r\n assist=request.form['apg']\r\n apg=float(assist)\r\n rebounds=request.form['rpg']\r\n rpg=float(rebounds)\r\n p=GSW(name,ppg,apg,rpg,bid)#create player obj\r\n updatePlayerById(p)#call BBall update\r\n return redirect('/getroster')#take the user to /getroster\r\n\r\n'''\r\n@app.route('/hello')\r\ndef hello():\r\n return \"

Hello from Flask

\"\r\n\r\n\r\n#to run the app,\r\n#write the following code:\r\n'''\r\n\r\nif __name__=='__main__':\r\n app.run(debug=True)\r\n\r\n","repo_name":"Deekshith-B/Python-flask","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"43672282843","text":"from django.urls import path\nfrom base.views import users_views as views\n\nurlpatterns = [\n \n path('login/', views.MyTokenObtainPairView.as_view(), name='token_obtain_pair'),\n # path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),\n path('profile/', views.getUserProfile, name='users_profile'),\n path('control//', views.controlUsers, name='users_control'),\n path('', views.getUsers, name='users'),\n path('register/', views.registerUser, name='register'),\n path('register_company/', views.registerCompany, name='register_company'),\n path('myregs/', views.getMyReg, name='myregs'),\n \n]","repo_name":"noufida/incubaton_management_project","sub_path":"incubation/base/urls/users_urls.py","file_name":"users_urls.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"17716263113","text":"\n# creation du dictionnaire\nstats = {}\n# initialisation de la reponse à None\nreponse = None\n\n# tant que la réponse n'est pas une chaîne vide\nwhile reponse != \"\":\n\n\t# demander aux utilisateurs leurs couleurs préférées\n\treponse = input('Quelle est votre couleur préférée ?\\n')\n\n\t# si la dernière réponse n'est pas vide\n\tif reponse:\n\n\t\t# si la réponse existe dans le dico\n\t\tif reponse in stats:\n\t\t\t# incrément le score existant\n\t\t\tstats[reponse] = stats[reponse] + 1\n\t\t\n\t\t# si la réponse n'existe pas\n\t\telse:\n\t\t\t# mettre un score de 1\n\t\t\tstats[reponse] = 1\n\n# afficher la liste des votes en itérant\n# sur les paires clé/valeur du dictionnaire\nprint('Vote pour les couleurs :')\nfor couleur, score in stats.items():\n\tprint(\"-\", couleur, \":\", score)","repo_name":"DiagoOlivier/PythonApplication1","sub_path":"sondage.py","file_name":"sondage.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"16815640356","text":"#\n# @lc app=leetcode.cn id=41 lang=python3\n#\n# [41] 缺失的第一个正数\n#\n\n\n# @lc code=start\nclass Solution:\n def firstMissingPositive(self, nums: List[int]) -> int:\n # left在初始位置(left左侧的值满足位置i放的i+1)\n left = 0\n # right在右越界位置(表示最好预期)\n right = len(nums)\n while left < right:\n # 如果left位置放的正好是left+1,left自增1\n if nums[left] == left + 1:\n left += 1\n # 如果是大于right的数,不需要\n # 如果是等于小于left的数,不需要\n # 如果存放的数是left,right之间的val,本应被放到val-1的位置,\n # 但是val-1位置的数存放的已经是val,此时left位置的val也不需要\n elif nums[left] > right or nums[left] <= left or nums[nums[left] - 1] == nums[left]:\n # 移动到垃圾区\n right -= 1\n nums[left], nums[right] = nums[right], nums[left]\n\n # 如果不是不需要的数,但也不是left+1,将这个数放到它对应的位置(val-1)\n # 并与val-1位置上的数交换\n else:\n nums[nums[left] - 1], nums[left] = nums[left], nums[nums[left] - 1]\n return right + 1\n\n\nnums = [3, 4, 0, 2]\n# @lc code=end\n","repo_name":"chenhuiyu/Leetcode-Python","sub_path":"41.缺失的第一个正数.py","file_name":"41.缺失的第一个正数.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"20470174654","text":"# netcat.py\nimport argparse\nimport socket\nimport subprocess\nimport sys\nfrom threading import Thread\n\nparser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,\n description='BHP Net Tool',\n epilog='''\\\nExamples:\n netcat.py -t 192.168.0.1 -p 5555 -l -c\n netcat.py -t 192.168.0.1 -p 5555 -l -u c:\\\\target.exe\n netcat.py -t 192.168.0.1 -p 5555 -l -e 'cat /etc/passwd'\n echo 'ABCDEFGHI' | ./netcat.py -t 192.168.11.12 -p 135''')\n\nparser.add_argument(\n '-l', '--listen', help='listen on [host]:[port] for incoming connections', action='store_true')\nparser.add_argument('-e', '--execute', default=None,\n help='execute the given file upon receiving a connection')\nparser.add_argument('-c', '--command',\n help='initialize a command shell', action='store_true')\nparser.add_argument(\n '-u', '--upload', help='upon receiving connection upload a file and write to [destination]')\nparser.add_argument('-t', '--target', default=None)\nparser.add_argument('-p', '--port', default=None, type=int)\nargs = parser.parse_args()\n\n\ndef client_sender(buffer):\n client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n # 標的ホストへ接続\n client.connect((args.target, args.port))\n if len(buffer):\n client.send(buffer)\n while True:\n recv_len = 1\n response = \"\"\n\n # 標的ホストからのデータを待機\n while recv_len:\n data = client.recv(4096)\n recv_len = len(data)\n response += data.decode('utf-8')\n if recv_len < 4096:\n break\n print(response.rstrip(), end=\"\")\n\n # 追加の入力を待機\n buffer = input()\n if buffer == \"\":\n continue\n if buffer == \"exit\":\n client.send(b\"exit\")\n break\n client.send(buffer.encode('utf-8'))\n client.close()\n except:\n print('[*] Exception! Exiting...')\n client.close()\n\n\ndef server_loop():\n # 待機するIPアドレスが指定されていない場合は\n # 全てのインターフェースで接続を待機\n if not args.target:\n args.target = \"0.0.0.0\"\n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server.bind((args.target, args.port))\n\n server.listen(5)\n while True:\n client_socket, addr = server.accept()\n\n # クライアントからの新しい接���を処理するスレッドの起動\n client_thread = Thread(target=client_handler, args=(client_socket,))\n client_thread.start()\n\n\ndef run_command(command):\n # クライアントから送られてきた改行文字を取り除く\n command = command.rstrip()\n try:\n output = subprocess.check_output(\n command, stderr=subprocess.STDOUT, shell=True\n )\n except:\n output = b\"Fail to execute command.\"\n return output\n\n\ndef client_handler(client_socket):\n \"\"\" オプション処理部分 \"\"\"\n if args.upload:\n file_buffer = b\"\"\n while True:\n data = client_socket.recv(1024)\n file_buffer += data\n if len(data) < 1024:\n break\n try:\n file_descriptor = open(args.upload, 'wb')\n file_descriptor.write(file_buffer)\n file_descriptor.close()\n\n client_socket.send(\"Successfully saved file to {}\".format(\n args.upload).encode('utf-8'))\n except:\n client_socket.send(\"Failed to save file to {}\".format(\n args.upload).encode('utf-8'))\n if args.execute:\n output = run_command(args.execute)\n client_socket.send(output)\n\n # プロンプトの表示\n if args.command:\n prompt = b\" \"\n client_socket.send(prompt)\n\n while True:\n # 改行文字を受け取るまでデータを受信\n recv_len = 1\n cmd_buffer = \"\"\n while recv_len:\n buffer = client_socket.recv(1024)\n recv_len = len(buffer)\n cmd_buffer += buffer.decode('utf-8')\n if recv_len < 1024:\n break\n if cmd_buffer == \"exit\":\n client_socket.close()\n break\n\n # コマンドの実行結果を取得\n response = run_command(cmd_buffer)\n\n # コマンドの実行結果を送信\n client_socket.send(response + prompt)\n\n\ndef main():\n # クライアントモード および サーバモードで必要な引数(オプション)がなかった場合、helpを表示して終了\n if not args.listen and args.target and args.port:\n buffer = sys.stdin.read()\n client_sender(buffer.encode('utf-8'))\n elif args.listen:\n server_loop()\n else:\n parser.print_help()\n sys.exit(1)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"codon-sec/Pentest_Tips","sub_path":"Network/netcat.py","file_name":"netcat.py","file_ext":"py","file_size_in_byte":5087,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"36724752684","text":"import torch\nimport torch.utils.data as Data\nimport random\nimport numpy as np\nfrom MyScaler import scale\nimport pandas as pd\n\n\ndef convert(data_in):\n result = None\n for d in data_in:\n if d == '':\n break\n if result is None:\n result = np.array(d.split(','))\n else:\n temp = np.array(d.split(','))\n result = np.c_[result, temp]\n result = result.astype(float)\n result = scale(result.T)\n x = result[:, :-1].astype(float)\n add_zeros = np.zeros(len(x))\n x = np.c_[x, add_zeros]\n x = np.reshape(x, (len(x), 4, 4))\n y = result[:, -1].astype(int)\n x, y = torch.FloatTensor(x), torch.LongTensor(y)\n x = torch.unsqueeze(x, dim=1)\n return x, y\n\n\nclass MyDataset(Data.Dataset):\n def __init__(self, file_path, n_raws, shuffle=False):\n \"\"\"\n file_path: the path to the dataset file\n n_raws: each time put n_raws sample into memory for shuffle\n shuffle: whether the data need to shuffle\n \"\"\"\n file_raws = 0\n # get the count of all samples\n with open(file_path, 'r') as f:\n for _ in f:\n file_raws += 1\n self.file_path = file_path\n self.file_raws = file_raws\n self.n_raws = n_raws\n self.shuffle = shuffle\n\n def initial(self):\n self.f_input = open(self.file_path, 'r')\n self.samples = list()\n # put nraw samples into memory\n for _ in range(self.n_raws):\n data = self.f_input.readline() # data contains the feature and label\n if data:\n self.samples.append(data)\n else:\n break\n self.current_sample_num = len(self.samples)\n self.index = list(range(self.current_sample_num))\n if self.shuffle:\n random.shuffle(self.samples)\n\n def __len__(self):\n return self.file_raws\n\n def __getitem__(self, item):\n idx = self.index[0]\n data = self.samples[idx]\n self.index = self.index[1:]\n self.current_sample_num -= 1\n\n if self.current_sample_num <= 0:\n # all the samples in the memory have been used, need to get the new samples\n self.samples.clear()\n for _ in range(self.n_raws):\n data = self.f_input.readline() # data contains the feature and label\n if data:\n self.samples.append(data)\n else:\n break\n self.current_sample_num = len(self.samples)\n self.index = list(range(self.current_sample_num))\n if self.shuffle:\n random.shuffle(self.samples)\n return data\n","repo_name":"QuinceyLee/Anomaly_Detection","sub_path":"MyDataset.py","file_name":"MyDataset.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"7767413698","text":"#%% IMPORT\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.mlab import griddata #Para o gráfico colorido\n#%% VARIÁVEIS\ndef n(): #Número de cargas\n return 100\n\ndef a(): #Semi-eixo maior\n return 100\n\ndef b(): #Semi-eixo menor\n return 50\n\n\n#%% CONDIÇÕES INICIAIS\ndef initial_condition_np(a,b,n):\n x = np.random.randint(-a,a, size = n)\n lim = np.around(b*np.sqrt(1-(x/a)**2))\n y = np.random.uniform(-1*lim,lim, size = n)#Repara que desse jeito ele gera uma distribuição mais densa nas pontas da elipse\n y = y.astype(int)\n charges = np.zeros((n,2), dtype = int) #Cria array com as posições das cargas\n charges[:,0] = x\n charges[:,1] = y\n charges = np.unique(charges, axis=0) #Exclui cargas sobrepostas \n return charges\n\n\n# %% VARIAÇÃO DE POTENCIAL\ndef Delta_pot(charges, charge_i, charge_i_new, i, condicao, potencial):\n #pote: energia de interação da partícula i com a partícula k\n #total: guarda a soma das energias de interações\n #condicao: 1 - carga fixa ; 0 - sem carga fixa\n #potencial: 0 - log; 1 - 1/r\n \n pote_old = np.zeros(1) #Tamanho 1 porquê entra só a coordenada inicial da partícula i\n pote_new = np.zeros(4) #Tamanho 4 porquê entra as coordenadas dos 4 movimentos possíveis da partícula i (norte, sul, leste, oeste)\n total_old = np.zeros(1)\n total_new = np.zeros(4) \n \n if potencial == 0:\n if condicao == 1:\n carga_fixa = [a+20,b+20]\n total_old = -(len(charges)/2)*np.log(np.sqrt(np.sum((charge_i - carga_fixa)**2)))\n total_new = -(len(charges)/2)*np.log(np.sqrt(np.sum((charge_i_new - carga_fixa)**2, axis = 1)))\n \n for k in range(len(charges)):\n if i!=k: #Não calculamos a energia de interação de uma partícula com ela mesma\n charge_k = charges[k, :]\n pote_old = np.log(np.sqrt(np.sum((charge_i - charge_k)**2)))\n pote_new = np.log(np.sqrt(np.sum((charge_i_new - charge_k)**2, axis = 1)))\n total_old = total_old- pote_old\n total_new = total_new- pote_new\n Delta_U = total_new - total_old\n min_index = np.argmin(Delta_U) #Pega o primeiro índice do menor Delta_U\n Delta_U_min = Delta_U[min_index] #Pega o valor do menor Delta_U\n return Delta_U_min, min_index\n \n \n if potencial == 1:\n if condicao == 1:\n carga_fixa = [a+20,b+20]\n total_old = -(len(charges)/2)*(np.sqrt(np.sum((charge_i - carga_fixa)**2)))\n total_new = -(len(charges)/2)*(np.sqrt(np.sum((charge_i_new - carga_fixa)**2, axis = 1)))\n \n for k in range(len(charges)):\n if i!=k: #Não calculamos a energia de interação de uma partícula com ela mesma\n charge_k = charges[k, :]\n pote_old = np.sqrt(np.sum((charge_i - charge_k)**2))\n pote_new = np.sqrt(np.sum((charge_i_new - charge_k)**2, axis = 1))\n total_old = total_old- pote_old\n total_new = total_new- pote_new\n Delta_U = total_new - total_old\n min_index = np.argmin(Delta_U) #Pega o primeiro índice do menor Delta_U\n Delta_U_min = Delta_U[min_index] #Pega o valor do menor Delta_U\n return Delta_U_min, min_index\n \n\n\n\n#%% SIMULAÇÃO\ndef simulate(a, b, n, charges, condicao, potencial):\n variacao = np.array([[1,0], [-1,0], [0,1], [0,-1]]) #Matriz de variação, contém os movimentos possíveis (norte, sul, leste, oeste)\n index_charges = np.arange(len(charges))\n flag = 0\n while flag!=int(len(charges)): #Cada iteração é um ciclo que roda por todas as partículas\n flag = 0\n np.random.shuffle(index_charges) #Fahttps://www.facebook.com/z um shuffle nos index_charges, para que simulemos a escolha aleatória das partículas\n for i in index_charges:\n charges_new = np.copy(charges) \n charge_i = np.copy(charges[i, :]) #Pego a partícula com indice i\n \n R = abs(np.random.randn()) + 1 #Gera uma variável gausiana aleatória\n elipse = (charges[i][0]/a)**2+(charges[i][1]/b)**2 #x²/a² + y²/b²\n step = int(R*(b)**(1- elipse)) #Tamanho do passo, no que quanto mais proximo da elipse, o expoente se aproxima de 0\n \n charge_i_new = charge_i + step*variacao #Aplico a variação para todas as direções possíveis para a partícula i\n for I in range(4): #Aqui quero ver se o movimento que eu to realizando é permitido, ou seja, se a partícula cai pra fora da elipse ou ocupa o lugar de outra carga\n charges_new[i, :] = charge_i_new[I, :] \n elipse = (charge_i_new[I, 0]/a)**2 + (charge_i_new[I, 1]/b)**2 #x²/a² + y²/b²\n if(elipse <= 1) and (len(np.unique(charges_new, axis=0)) == len(charges)):\n continue\n else:\n charge_i_new[ I, :] = charge_i_new[I, :] - step*variacao[I, :] #Caso a partícula não satisfaça as duas condições, volto ela pra sua posição inicial\n #Note que voltar pra posição inicial implica que o Delta_U para esse movimento vai ser 0 \n Delta_U_min, min_index = Delta_pot(charges, charge_i, charge_i_new, i, condicao, potencial) #Vou pegar a menor variação energia dentre os movimentos e o índice que causa essa variação\n if Delta_U_min<0:\n charges[i, :] = charge_i + step*variacao[min_index, :] #Movo a partícula pra a direção que causa maior diminuição da energia\n elif Delta_U_min>=0:\n flag = flag + 1 #Se a menor variação de energia da partícula é nula, contamos 1 a mais no flag\n #Note que o flag reinicia a cada ciclo\n #Se o número de partículas cuja menor variação de energia é 0 for igual ao número de partículas, alcançamos um mínimo local.\n return charges\n\n#%% CAMPO ELETRICO\ndef campo_eletrico(a, b, charges, condicao, potencial):\n\n #Cria os pontos em que serão calculados os campos\n x = np.arange(-a,a) #x vai ser distribuido com passo 1 de -a até a\n lim = np.around(b*np.sqrt(1-(x/a)**2)) #calculo os y possível dentro da elípse\n y = np.random.uniform(-1*lim,lim, size = len(x)) #y será uma resposta aleatória com os seus valores possíveis, a quantidade é igual a quantidade de x\n y = y.astype(int)\n ponto = np.zeros((len(x),2), dtype = float) #Os pontos estão dentro da elipse\n ponto[:,0] = x\n ponto[:,1] = y\n \n #Array para guardar o campo em cada ponto calculado\n campo = np.zeros((len(x),2),dtype = float)\n \n for i in range(len(x)):\n \n qn = (len(charges))/2\n \n ponto_fixo = [a+20,b+20]\n \n if potencial == 0: #Potencial logaritimo --> campo é 1/r (vetorial r/r**2)\n for k in range(len(charges)):\n charge_k = charges[k,:]\n campo[i] = campo[i] + np.true_divide((ponto[i] - charge_k),((np.sum((ponto[i] - charge_k)**2))))\n \n if condicao == 1:\n campo[i] = campo[i] + qn*np.true_divide((ponto[i] - ponto_fixo),(np.sum((ponto[i] - ponto_fixo)**2)))\n campo[i] = np.sqrt(np.sum(campo[i]**2))\n \n if potencial == 1:#Potencial 1/r --> campo é 1/r**2 (vetorial r/r**3)\n for k in range(len(charges)):\n charge_k = charges[k,:]\n campo[i] = campo[i] + np.true_divide((ponto[i]-charge_k),(np.sum((ponto[i]-charge_k)**3)))\n \n if condicao == 1:\n campo[i] = campo[i] + qn*np.true_divide((ponto[i]-ponto_fixo),(np.sum((ponto[i]-ponto_fixo)**3)))\n campo[i] = np.sqrt(np.sum(campo[i]**2))\n \n #Campo passa a ser um array 1D pra poder ser passado pro gráfico, é o campo em módulo\n \n campo = campo.ravel()\n index = np.arange(0,len(campo),2)\n campo = np.delete(campo, index)\n \n #Define malha\n xi = np.linspace(-a, a, 100)\n yi = np.linspace(-b, b, 50)\n # Coloca os pontos na malha\n zi = griddata(ponto[:,0], ponto[:,1], campo, xi, yi, interp='linear')\n #Transforma em gráfico colorido\n CS = plt.contour(xi, yi, zi, 15, linewidths=0.5, colors='k')\n CS = plt.contourf(xi, yi, zi, 15,\n vmax=abs(zi).max(), vmin=-abs(zi).max())\n plt.colorbar() #Barra de cor\n #Plotando\n #plt.scatter(ponto[:,0], ponto[:,1], marker='o', s=5, zorder=10) #Apenas para ver os pontos onde foram calculados o campo\n plt.xlim(-a, a)\n plt.ylim(-b, b)\n plt.title('Gráfico do campo elétrico' )\n plt.show()\n #plt.savefig('loucura.png')\n #print(campo[0],ponto[0],campo[len(x)-1],ponto[len(x)-1])\n return campo\n\n\n#%% PLOT\ndef plot(a, b, charges_0, charges, condicao):\n #Copia as posições iniciais em x e y\n x_0 = charges_0[:, 0]\n y_0 = charges_0[:, 1]\n \n #Copia as posições finais em x e y\n x = charges[:, 0]\n y = charges[:, 1]\n \n #Define a superfície da elipse\n x_superficie = np.linspace(-a, a, 1000) #Para gerar a superfície\n y_superficie = b*np.sqrt(1-(x_superficie/a)**2)\n \n if condicao == 1:\n plt.plot(a+20,b+20,marker='o',color='pink')\n \n plt.axes().set_aspect('equal') #Mesmo aspect ratio para que vejamos a deformação da elipse\n plt.grid()\n plt.title(\"Condutor elíptico bidimensional\")\n plt.xlabel('x')\n plt.ylabel('y')\n plt.plot(x_superficie, y_superficie, color='grey') #Superfície\n plt.plot(x_superficie, -y_superficie, color='grey') #Superfície\n plt.scatter(x_0, y_0, s=3, color='red', label = 'Inicial') #Inicial\n plt.scatter(x, y, s=3, color='darkblue', label ='Final') #Final\n plt.legend(loc=4)\n plt.savefig('plot.pdf')\n plt.show()\n\n\n#%% CÁLCULOS (LARGE STEP)\n\na = a()\nb = b()\nn = n()\n\ncondicao = 1\npotencial = 0\n\nstart = time.time()\n\ncharges = initial_condition_np(a,b,n)\n\ncharges_0 = np.copy(charges)\n\ncharges = simulate(a,b,n, charges,condicao,potencial)\n\ncampo_inicial = campo_eletrico(a,b,charges_0,condicao,potencial)\n\ncampo = campo_eletrico(a,b,charges,condicao,potencial)\n\nend = time.time()\n\nprint('Tempo de simulação: ' + str(end - start))\n\n\n#%% PLOT (LARGE STEP)\nplot(a, b, charges_0, charges, condicao)\n","repo_name":"eletromagcomp/projeto1","sub_path":"campo_cargafixa_potdiferentes.py","file_name":"campo_cargafixa_potdiferentes.py","file_ext":"py","file_size_in_byte":10320,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"17638543633","text":"import calendar\nfrom dateutil.relativedelta import relativedelta\nfrom datetime import timedelta\nimport datetime\n\n\ndef max_day():\n # Part check this month and this year\n today = datetime.date.today()\n this_month = int(today.strftime(\"%m\"))\n this_year = int(today.strftime(\"%Y\"))\n\n last_month = int((today - relativedelta(months=1)).strftime(\"%m\"))\n last_year = int((today - relativedelta(months=1)).strftime(\"%Y\"))\n\n # monthrange include('year', 'month')[1] < return last day of month\n days_in_this_month = calendar.monthrange(this_year, this_month)[1]\n days_in_last_month = calendar.monthrange(last_year, last_month)[1]\n\n # find max day between two month\n max_day = max(days_in_this_month, days_in_last_month)\n\n print(\"max day of this 2 month is: \", max_day)\n print(\"----------------------------------------\")\n\nmax_day()\n","repo_name":"jfornqz/Collect_code_python3","sub_path":"check_day_in_month.py","file_name":"check_day_in_month.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"28914014713","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\n#\n# Complete the 'searchSuggestions' function below.\n#\n# The function is expected to return a 2D_STRING_ARRAY.\n# The function accepts following parameters:\n# 1. STRING_ARRAY repository\n# 2. STRING customerQuery\n#\n\ndef searchSuggestions(repository, customerQuery):\n # Write your code here\n output = []\n search = \"\"\n for word in customerQuery:\n search = search + word\n matching = []\n if len(search)>1:\n print(len(search))\n for words in repository: \n print(\n \"checking \" + words\n )\n #if words not in matching:\n if search == words[0: len(search)]:\n matching.append(words)\n matching.sort()\n print(matching)\n output.append(matching)\n return output\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n repository_count = int(input().strip())\n\n repository = []\n\n for _ in range(repository_count):\n repository_item = input()\n repository.append(repository_item)\n\n customerQuery = input()\n\n result = searchSuggestions(repository, customerQuery)\n\n fptr.write('\\n'.join([' '.join(x) for x in result]))\n fptr.write('\\n')\n\n fptr.close()\n","repo_name":"mingmanhk/pythonpractice","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"34976604991","text":"\"\"\"\nAuthor : Byunghyun Ban\nEmail : bhban@kakao.com\n\"\"\"\n\nimport utils as U\nimport time\nimport pyexcel as px\nimport os\nimport random\n\n\ndef add_line_to_xlsx(filename, line):\n data_array = px.get_array(file_name=filename)\n data_array.append(line)\n px.save_as(array=data_array, dest_file_name=filename)\n\n\ndef build_contents(filename):\n out_filename = \"out_\" + filename\n data_array = px.get_array(file_name=filename)\n header = data_array[0]\n data_array = data_array[1:]\n random.shuffle(data_array)\n\n errored_filename = \"ERROR_\" + filename.split(\".\")[0] + '.txt'\n\n header += [\"발음기호\", \"품사\", \"의미\"]\n\n if out_filename not in os.listdir():\n data_array = [header]\n px.save_as(array=data_array, dest_file_name=out_filename)\n\n if errored_filename not in os.listdir():\n error_file = open(errored_filename, 'w', encoding=\"utf8\")\n error_file.write(\"에러 발생한 단어\")\n error_file.close()\n\n processed_file = px.get_array(file_name=out_filename)\n\n processed_words = []\n for line in processed_file:\n word = line[0]\n processed_words.append(word)\n\n for line in data_array:\n word = line[0]\n if word in processed_words:\n continue\n\n print(\"Processing \" + word + \"... \")\n\n try:\n _, _, pron, meaning = U.get_single_word(word)\n except:\n time.sleep(2)\n try:\n _, _, pron, meaning = U.get_single_word(word)\n except:\n print(\" Error!\")\n error_file = open(errored_filename, 'a')\n error_file.write(\"\\n\" + word)\n error_file.close()\n continue\n try:\n pron = pron[1][pron[1].index(\"[\") + 1: pron[1].index(\"]\")].strip()\n if \";\" in pron:\n pron = pron[:pron.index(\";\")]\n pron = \"[\" + pron + \"]\"\n except:\n pron = \"-1\"\n\n if not meaning:\n error_file = open(errored_filename, 'a', encoding=\"utf8\")\n error_file.write(word)\n error_file.close()\n\n for el in meaning:\n line_copy = line + [pron, el[0], el[1]]\n add_line_to_xlsx(out_filename, line_copy)\n print(\"\\t\\t\" + str(line_copy))\n\n processed_words.append(word)\n","repo_name":"needleworm/bigdata_voca","sub_path":"bigdata analysis/meanings.py","file_name":"meanings.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"21612469703","text":"'''\nMonster is the super-class that governs the behavior of monsters\nusing the AI. Individual monsters have different stats and colors.\n'''\n\nfrom Actors.Actor import *\nfrom Behaviors.MonsterAI import MonsterAI\n\nclass Monster(Actor):\n def __init__(self, row, col, color, dungeon_map):\n super().__init__(row, col, color)\n # the AI needs to know the layout of the dungeon to navigate\n self.ai = MonsterAI(dungeon_map)\n\n '''\n Overwritten to use the AI to determine the move to make.\n Returns true if they AI spent their turn moving, false if not.\n If false, the AI might be able to attack (which will happen in the main runner)\n '''\n def move(self, player, dungeon_map):\n next_move = self.ai.next_move(self, player)\n\n # The AI says not to move, so just face the player\n if next_move.row == self.row and next_move.col == self.col:\n self.facing = self.determine_direction(player.row, player.col)\n return False\n # The AI says to move, so face the way we're moving\n else:\n self.facing = self.determine_direction(next_move.row, next_move.col)\n\n # Checking for collisions with other monsters\n if dungeon_map.grid[next_move.row][next_move.col] == FLOOR:\n self.row = next_move.row\n self.col = next_move.col\n return True\n return False\n\nclass SkullMonster(Monster):\n def __init__(self, row, col, dungeon_map):\n super().__init__(row, col, arcade.color.BONE, dungeon_map)\n\n self.max_hp = 20\n self.curr_hp = self.max_hp\n self.attack = 15\n self.defense = 10\n\n def __str__(self):\n return \"scary floating skull\"\n\nclass LampMonster(Monster):\n def __init__(self, row, col, dungeon_map):\n super().__init__(row, col, arcade.color.ALLOY_ORANGE, dungeon_map)\n self.max_hp = 15\n self.curr_hp = self.max_hp\n self.attack = 12\n self.defense = 15\n def __str__(self):\n return \"giant robot lamp\"\n\nclass FishMonster(Monster):\n def __init__(self, row, col, dungeon_map):\n super().__init__(row, col, arcade.color.AIR_SUPERIORITY_BLUE, dungeon_map)\n self.max_hp = 30\n self.curr_hp = self.max_hp\n self.attack = 12\n self.defense = 10\n def __str__(self):\n return \"skeletal floating fish\"\n","repo_name":"DragonQuills/PPW-Dungeon-Crawler","sub_path":"Actors/Monster.py","file_name":"Monster.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"5043051724","text":"import base64\nfrom io import BytesIO\n\nfrom PIL import Image\nfrom PIL import ImageDraw\nfrom PIL import ImageFont\n\nimport model.product as product\nimport model.wood as wood\n\ndef show_default_preview(model_id, wood_id):\n mask = product.get_products_mask(model_id)\n mask = Image.open(BytesIO(base64.b64decode(mask[0]['model_mask'].decode('utf-8'))))\n mask = mask.convert(\"RGBA\")\n width, height = mask.size\n\n wood_type = wood.get_wood_by_id(wood_id)\n wood_type = Image.open(BytesIO(base64.b64decode(wood_type['image'].decode('utf-8'))))\n wood_type = wood_type.convert(\"RGBA\")\n\n files = [wood_type, mask]\n result = Image.new(\"RGBA\", (width, height))\n\n for i in range(0, len(files)):\n result.paste(files[i], (0, 0), files[i])\n\n img = BytesIO()\n result.save(img, format='PNG')\n img = img.getvalue()\n result_encoded = base64.b64encode(img)\n return result_encoded\n\n\ndef show_preview(model_id, wood_id, design_id, message):\n mask = product.get_products_mask(model_id)\n mask = Image.open(BytesIO(base64.b64decode(mask[0]['model_mask'].decode('utf-8'))))\n mask = mask.convert(\"RGBA\")\n width, height = mask.size\n\n wood_type = wood.get_wood_by_id(wood_id)\n wood_type = Image.open(BytesIO(base64.b64decode(wood_type['image'].decode('utf-8'))))\n wood_type = wood_type.convert(\"RGBA\")\n\n design_type = wood.get_design_by_id(design_id)\n design_type = Image.open(BytesIO(base64.b64decode(design_type['mask'].decode('utf-8'))))\n design_type = design_type.convert(\"RGBA\")\n\n files = [wood_type, design_type, mask]\n result = Image.new(\"RGBA\", (width, height))\n\n for i in range(0, len(files)):\n result.paste(files[i], (0, 0), files[i])\n\n if message:\n draw = ImageDraw.Draw(result)\n font = ImageFont.truetype(font=\"static/fonts/Pacifico-Regular.ttf\", size=48)\n w, h = draw.textsize(message, font=font)\n message_background = wood_type.crop((0, 0, w, h))\n result.paste(message_background, (int(((width - w) / 2)), int(((height - h) / 2))), message_background)\n draw.text(((width - w) / 2, (height - h) / 2), message, (110, 90, 60), font=font, align=\"right\")\n\n img = BytesIO()\n result.save(img, format='PNG')\n img = img.getvalue()\n result_encoded = base64.b64encode(img)\n\n return result_encoded\n","repo_name":"DhruvPatel27/P9_New_Product_Customizor_App","sub_path":"model/customization.py","file_name":"customization.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"7853673928","text":"def longestCommonPrefix(strs):\n '''\n goal: find the longest common prefix in every string of strs\n strs: list[str]\n return: str\n '''\n if not strs:\n return ''\n # Implementing Trie: O(S) time [O(m) to find LCP after creating trie], O(S) space\n \n \n # divide and conquer: O(mn) time, O(mlog n) space \n def divideAndConquer(strs,l,r):\n if r-l == 1:\n return strs[l]\n mid = (r+l)//2\n left = divideAndConquer(strs, l, mid)\n right = divideAndConquer(strs, mid, r)\n \n for i in range(min(len(left),len(right))):\n if left[i] != right[i]:\n return left[:i]\n return left[:min(len(left),len(right))]\n \n return divideAndConquer(strs, 0, len(strs))\n \n # check every index of every string: O(mn) time [m: length of strs, n: length of shortest s], O(1) space\n idx = 0\n while True:\n for s in strs:\n if idx == len(s):\n return s\n if s[idx] != strs[0][idx]:\n return s[:idx]\n idx += 1\n \n # binary search: O(mnlogm) time, O(1) space\n def isCommon(strs,mid): # O(n)\n for s in strs[1:]:\n if strs[0][:mid] != s[:mid]:\n return False\n return True \n \n low, high = 0, float('inf')\n for s in strs: # O(m)\n high = min(len(s),high)\n \n while low <= high: # log(m)\n mid = (low+high)//2\n print(mid)\n if isCommon(strs,mid):\n low = mid+1\n else:\n high = mid-1\n return strs[0][:(low+high)//2]\n ","repo_name":"xynlophyl/learning_compsci","sub_path":"data structures/strings/longestCommonPrefix.py","file_name":"longestCommonPrefix.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"5721972578","text":"import json\r\nimport argparse\r\n\r\nparser = argparse.ArgumentParser(description='Package Frag models exported from Blender.')\r\nparser.add_argument('configFile', metavar='C', type=str, nargs='?', default='package.config.json', help='the configuration file to use')\r\nparser.add_argument('-i', '--input', metavar='I', type=str, nargs=1, required=False, help='override the input folder path')\r\nparser.add_argument('-o', '--output', metavar='O', type=str, nargs=1, required=False, help='override the output folder path')\r\nparser.add_argument('-d', '--dryRun', dest='dryRun', action='store_true', required=False, help='outputs a log without creating any packages')\r\nparser.add_argument('-l', '--logLevel', metavar='L', type=str, nargs=1, required=False, choices=['error', 'warn', 'info', 'debug'], default=['info'], help='logging level')\r\nargs = parser.parse_args()\r\n\r\nwith open(args.configFile, 'rt', encoding='utf-8-sig') as file:\r\n global config\r\n config = json.load(file)\r\n\r\nif args.input is None:\r\n if not 'input' in config or len(config['input']) == 0:\r\n config['input'] = '.\\\\'\r\nelse:\r\n config['input'] = args.input[0]\r\n\r\nif args.output is None:\r\n if not 'output' in config or len(config['output']) == 0:\r\n config['output'] = '.\\\\'\r\nelse:\r\n config['output'] = args.output[0]\r\n\r\nconfig['dryRun'] = args.dryRun\r\n\r\nif args.logLevel is None:\r\n config['logLevel'] = 2\r\nelse:\r\n if args.logLevel[0] == 'error': config['logLevel'] = 0\r\n if args.logLevel[0] == 'warn': config['logLevel'] = 1\r\n elif args.logLevel[0] == 'info': config['logLevel'] = 2\r\n elif args.logLevel[0] == 'debug': config['logLevel'] = 3\r\n\r\n# print(config)\r\n","repo_name":"Bikeman868/frag","sub_path":"tools/packaging/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"8700494084","text":"#%%\nimport sys\nimport numpy as np\nimport pandas as pd\n# np.set_printoptions(suppress=True)\n\n### comment when submit\n# import matplotlib.pyplot as plt\n###\n\n#%%\nraw_data = sys.argv[1]\ntest_data = sys.argv[2]\nX_train_file = sys.argv[3]\nY_train_file = sys.argv[4]\nX_test_file = sys.argv[5]\noutput_csv = sys.argv[6]\n# X_train_file = \"data/X_train\"\n# Y_train_file = \"data/Y_train\"\n# X_test_file = \"data/X_test\"\n# output_csv = \"adagrad_pred.csv\"\n\n#%%\nX = np.genfromtxt(X_train_file, delimiter=',', skip_header=1)\nY = np.genfromtxt(Y_train_file, delimiter=',', skip_header=0)\n\nX_test = np.genfromtxt(X_test_file, delimiter=',', skip_header=1)\nprint(\"X.shape\", X.shape)\nprint(\"Y.shape\", Y.shape)\nprint(\"X_test.shape\", X_test.shape)\n#%%\ndef train_valid_split(X, y, valid_size=0.2, random_state=42):\n n_train = int((1 - valid_size) * len(X))\n n_test = len(X) - n_train\n n_samples = len(X)\n\n rng = np.random.RandomState(random_state)\n permutation = rng.permutation(n_samples)\n ind_test = permutation[:n_test]\n ind_train = permutation[n_test:(n_test + n_train)]\n\n X_train = X[ind_train]\n X_valid = X[ind_test]\n y_train = y[ind_train]\n y_valid = y[ind_test]\n\n return X_train, X_valid, y_train, y_valid\n# X_train, X_valid, y_train, y_valid = train_valid_split(X, Y, valid_size=0.2, random_state=42)\n# print(X_train.shape, y_train.shape, X_valid.shape, y_valid.shape)\n\n#%%\n# Use np.clip to prevent overflow\ndef sigmoid(z):\n res = 1 / (1.0 + np.exp(-z))\n return np.clip(res, 1e-6, 1-1e-6)\n\n# Feature normalize, only on continues variable\ndef normalizeAll(x_train, x_test):\n x_all = np.concatenate((x_train, x_test), axis = 0)\n mean = np.mean(x_all, axis = 0)\n std = np.std(x_all, axis = 0)\n np.save(\"mean106.npy\", mean)\n np.save(\"std106.npy\", std)\n\n index = [0, 1, 3, 4, 5]\n mean_vec = np.zeros(x_all.shape[1])\n std_vec = np.ones(x_all.shape[1])\n mean_vec[index] = mean[index]\n std_vec[index] = std[index]\n x_all_nor = (x_all - mean_vec) / std_vec\n\n x_train_nor = x_all_nor[0:x_train.shape[0]]\n x_test_nor = x_all_nor[x_train.shape[0]:]\n\n return x_train_nor, x_test_nor\n#%%\n# Gradient descent using adagrad\ndef train(X, Y, lr=0.05, epoch=100000, valid_size=0.2, printStep=100, early_stop_steps=50):\n x_train, x_valid, y_train, y_valid = train_valid_split(X, Y, valid_size=valid_size, random_state=42)\n print(x_train.shape, y_train.shape, x_valid.shape, y_valid.shape)\n\n b = 0.0\n w = np.zeros(x_train.shape[1])\n # lr = 0.05\n # epoch = 100 \n b_lr = 0\n w_lr = np.ones(x_train.shape[1])\n \n min_val_cost = 1e10\n cnt = 0\n history = {\n 'loss': [],\n 'val_loss': [],\n }\n for e in range(epoch):\n z = np.dot(x_train, w) + b\n pred = sigmoid(z)\n loss = y_train - pred\n\n b_grad = -1*np.sum(loss)\n w_grad = -1*np.dot(loss, x_train)\n\n b_lr += b_grad**2\n w_lr += w_grad**2\n\n\n b = b-lr/np.sqrt(b_lr)*b_grad\n w = w-lr/np.sqrt(w_lr)*w_grad\n\n loss = -1*np.mean(y_train*np.log(pred+1e-100) + (1-y_train)*np.log(1-pred+1e-100))\n valid_pred = sigmoid(np.dot(x_valid, w) + b)\n val_loss = -1*np.mean(y_valid*np.log(valid_pred+1e-100) + (1-y_valid)*np.log(1-valid_pred+1e-100))\n history['loss'].append(loss)\n history['val_loss'].append(val_loss)\n\n if(e+1)%printStep == 0:\n print('epoch:{}\\nloss:{} | val_loss:{}\\n'.format(e+1, loss, val_loss))\n\n if val_loss < min_val_cost:\n min_val_cost = val_loss\n cnt = 0\n else:\n cnt += 1\n\n if cnt > early_stop_steps:\n print(f\"early stop! val_loss {min_val_cost} don't decrease in {early_stop_steps} iters\")\n break \n\n return w, b, history\n\n#%%\ndef normalize(X, sel_cols=[0,1,3,4,5], own_norm=False):\n if own_norm:\n mean = np.mean(X, axis = 0)\n std = np.std(X, axis = 0) \n else:\n mean = np.load(\"mean106.npy\")\n std = np.load(\"std106.npy\")\n mean_vec = np.zeros(X.shape[1])\n std_vec = np.ones(X.shape[1])\n mean_vec[sel_cols] = mean[sel_cols]\n std_vec[sel_cols] = std[sel_cols]\n\n X_norm = (X - mean_vec) / std_vec\n\n return X_norm\n\ndef accuracy(Y_pred, Y_label):\n acc = np.sum(Y_pred == Y_label)/len(Y_pred)\n return acc\n\n#%%\n### comment when submit\n# def plot_history(h):\n # plt.figure()\n # epochs = range(len(h['loss']))\n # plt.plot(epochs, h['loss'], label='train')\n # plt.plot(epochs, h['val_loss'], label='valid')\n # plt.legend()\n # plt.show()\n###\n#%%\nif __name__ == '__main__':\n \n # normalizeAll(X, X_test)\n x = normalize(X)\n w, b, history = train(x, Y, early_stop_steps=20)\n \n # plot_history(history)\n y_train_pred = np.round(sigmoid(np.dot(x, w) + b)) \n print(accuracy(Y, y_train_pred))\n\n x_test = normalize(X_test)\n y_pred = np.round(sigmoid(np.dot(x_test, w) + b))\n\n with open(output_csv, 'w') as f:\n f.write('id,label\\n')\n for i, v in enumerate(y_pred):\n f.write('%d,%d\\n' %(i+1, v))\n#%%\n","repo_name":"TSLsun/ML2019FALL","sub_path":"hw2/logistic.py","file_name":"logistic.py","file_ext":"py","file_size_in_byte":5055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"30934239765","text":"from PIL import Image\nimport cv2\nimport base64\nfrom os.path import dirname, join\nfrom com.chaquo.python import Python\n\ndef main(im):\n files_dir=str(Python.getPlatform().getApplication().getFilesDir())\n fileimg1=join(dirname(files_dir),\"input.jpg\")\n fileimg2=join(dirname(files_dir),\"output.jpg\")\n print(\"**********Reached Python**************\")\n imgb = bytes(im, 'ascii')\n img_bytes = base64.decodebytes(imgb)\n with open(fileimg1, 'wb') as ip:\n ip.write(img_bytes)\n image = cv2.imread(fileimg1)\n image_file = Image.open(fileimg1) # open colour image\n image_file = image_file.convert('L') # convert image to black and white\n image_file.save(fileimg2)\n encoded_string = ''\n with open(fileimg2, \"rb\") as op:\n encoded_string = base64.b64encode(op.read())\n return \"\"+str(encoded_string,'utf-8')\n\n","repo_name":"Ponprabhakar-pg/mad-ex-12","sub_path":"app/src/main/python/myScript.py","file_name":"myScript.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"20853351702","text":"results = []\n\nfor rounds in range(int(input())):\n\n scores = list(map(int,input().split()))\n\n for i in range(len(scores)):\n if scores[i] < 40:\n scores[i] = 40\n result = sum(scores) // len(scores)\n\n results.append(f'#{rounds + 1} {result}')\nprint('\\n'.join(results))","repo_name":"seoul-ssafy-class-2-studyclub/Eunsung","sub_path":"D3/3314 보충학습과 평균.py","file_name":"3314 보충학습과 평균.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"1289541397","text":"#!/usr/bin/python\n\n# MASTER ANALYSIS SCRIPT FOR MEDITATION NARRATIVE FREE AWARENESS STUDY\n# NOV 2021\n\nimport sys, os\nfrom subprocess import call\nimport argparse\nfrom datetime import datetime\nimport re\n\nstarttime = datetime.now()\n\nruns = [\"medopen\", \"medthink\",\"restnotask\",\"restopen\",\"restthink\"]\n\n#command line options\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\"--subjects\",help=\"process listed subjects\",nargs='+',action=\"store\")\nparser.add_argument(\"--all\",help=\"process all subjects\", action=\"store_true\")\nargs = parser.parse_args()\n\n#set paths\npathbase = \"/Volumes/Meditation/Narrative_Free_Awareness_Study/06_Data/fMRI/preprocessing\"\n\n#develop list of subjects\nsubjects = args.subjects\n\nif args.all:\n\t#Get list of subjects\n\tsubjects = os.listdir(pathbase)\n\tsubjects = [elem for elem in subjects if 'sub-' in elem]\n\tsubjects.sort()\n\n\t#check if they've been done already\n\tcandidate_subjects = subjects\n\tsubjects = []\n\t\n\tfor candidate in candidate_subjects:\n\t\ttestfolder1 = \"%s/sub-%s/preproc_restthink.feat/ICA_AROMA\" % (pathbase,candidate)\t\n\t\tif not os.path.exists(testfolder1):\n\t\t\tsubjects.append(candidate[4:7])\n\nif subjects:\n\tprint (subjects)\nelse:\n\tprint (\"Subjects must be specified. Use --all for all subjects or --subjects to list specific subjects.\")\n\tsys.exit()\n\n#Preprocessing steps\nfor subject in subjects:\n\n\tsubjectfolder = pathbase + \"/sub-\" + subject\n\tfor run in runs:\n\t\tfeatfolder = '%s/preproc_%s.feat' %(subjectfolder, run)\n\t\toutfolder = '%s/ICA_AROMA' %(featfolder)\n\t\tcommand = 'ICA_AROMA.py -feat %s -out %s' %(featfolder, outfolder)\n\t\tprint(command)\n\t\tcall(command,shell=True)\n","repo_name":"uscbci/NFA_fMRI","sub_path":"nfa_ICA_AROMA.py","file_name":"nfa_ICA_AROMA.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"9219817329","text":"import matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nfrom matplotlib import colors\nimport matplotlib.tri as mtri\nfrom matplotlib import rc\n\nimport numpy as np\nfrom math import pi, tan, acos\n\nfrom Config import Config\nLB = 2*acos(Config.VD/Config.VI)\n\nfrom hhtrajectory import dwin_SS_traj_hh, get_max_T\nfrom iwin_trajectory import iwin_SS_straight_traj\nfrom plotter import plot_traj_phy, plot_traj_thtalpha, plot_state_space_boundary, plot_sampled_SS, plot_iwin_bound\nfrom plotter import plot_dominant, plot_zero_range_barrier, plot_zha_barrier, plot_flora_barrier\nfrom sampler import sample_SS\n\ndef dwin_plots(delta, T, t=10, Nt=20, gmm=LB/2):\n fig, ax = plt.subplots()\n plt.rc('text', usetex=True)\n plt.rc('font', family='serif')\n \n xs, ss, ds, times = dwin_SS_traj_hh(delta, T, t=t, Nt=Nt, gmm=gmm)\n plot_traj_phy(ax, xs[::-1], skip=10)\n\n plt.xlabel(r'$x(m)$', fontsize=16)\n plt.ylabel(r'$y(m)$', fontsize=16)\n plt.title(r'$\\theta=\\pi-2\\gamma$, $\\delta=0.3\\pi$', fontsize=16)\n\n ax.axis('equal')\n plt.grid()\n plt.show()\n\ndef iwin_plots():\n fig, ax = plt.subplots()\n plt.rc('text', usetex=True)\n plt.rc('font', family='serif')\n \n# xs, ss = iwin_SS_straight_traj(tht=pi-LB, delta=0.3*pi, length=0.4)\n xs, ss, ds, times = iwin_SS_straight_traj(tht=pi-LB+0.2, delta=0.3*pi, length=0.4)\n plot_traj_phy(ax, xs, skip=10)\n\n plt.xlabel(r'$x(m)$', fontsize=16)\n plt.ylabel(r'$y(m)$', fontsize=16)\n plt.title(r'$\\theta=\\pi-2\\gamma$, $\\delta=0.3\\pi$', fontsize=16)\n\n ax.axis('equal')\n plt.grid()\n plt.show()\n\ndef SS_plots(gmms, theta):\n fig = plt.figure()\n ax = plt.gca(projection='3d')\n plt.rc('text', usetex=True)\n plt.rc('font', family='serif')\n \n colors = \"brg\"\n for i, gmm in enumerate(gmms):\n print(gmm)\n value, xs, ss, ds = sample_SS(gmm=gmm)\n # print(ss)\n if i == 0:\n barrier=True\n else:\n barrier=False\n plot_sampled_SS(ax, ss, color=colors[i], label=r'$\\gamma=%.2f^\\circ$'%gmm, barrier=barrier)\n # plot_state_space_boundary(ax)\n \n# xs, ss = sample_iwin_SS(tht=theta)\n # plot_sampled_SS(ax, ss, color=colors[-1], label=r'$\\theta=%.2f^\\circ$'%(2*pi - theta))\n\n# plot_dominant(ax)\n \n ax.set_xlabel(r'$\\alpha_1$', fontsize=16)\n ax.set_ylabel(r'$\\alpha_2$', fontsize=16)\n ax.set_zlabel(r'$\\theta$', fontsize=16)\n# ax.legend()\n plt.title(r'SSs', fontsize=16)\n \n plt.show()\n \ndef plot_compare():\n\n fig, ax = plt.subplots()\n plt.rc('text', usetex=True)\n plot_zero_range_barrier(ax, gmm=LB/2-0.2, color='r')\n plot_zero_range_barrier(ax, gmm=LB/2+0.01, color='slateblue')\n plot_zero_range_barrier(ax, gmm=LB/2+0.1, color='navy')\n plot_zero_range_barrier(ax, gmm=LB/2+0.3, color='blue')\n plot_zero_range_barrier(ax, gmm=LB/2+0.5, color='royalblue')\n plot_zero_range_barrier(ax, gmm=LB/2+0.7, color='cornflowerblue')\n plot_zero_range_barrier(ax, gmm=LB/2+0.9, color='lightsteelblue')\n plot_zero_range_barrier(ax, gmm=pi/2, color='lightsteelblue')\n\n plot_zha_barrier(ax)\n plot_flora_barrier(ax)\n\n plt.axis('equal')\n plt.grid()\n ax.set_xlabel(r'$x$', fontsize=16)\n ax.set_ylabel(r'$y$', fontsize=16)\n ax.tick_params(axis='both', which='major', labelsize=16)\n# ax.legend()\n plt.title(r'Barrier', fontsize=16)\n \n plt.show()\n \n# SS_plots([LB/2, LB/2+0.8], pi-LB+0.05) \n\n# delta_max = 0.1\n# gmm = LB/2+delta_max\n# Tmax = get_max_T(gmm) \n# dwin_plots(0.3*delta_max, 0.6*Tmax, gmm=gmm)\n\n\n# iwin_plots()\n# plot_compare()","repo_name":"FloraHF/TDSInum","sub_path":"results.py","file_name":"results.py","file_ext":"py","file_size_in_byte":3651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"27604299446","text":"import inspect\nfrom os.path import realpath, dirname, join\n\nclass KeywordTokenMapper:\n \"\"\"\n Maps BASIC keywords to the proper token value.\n For example, \"PRINT\" mapping to the proper byte value for that string.\n \"\"\"\n def __init__(self):\n class_folder = dirname(inspect.getsourcefile(KeywordTokenMapper))\n config_file = realpath(join(class_folder, 'keyword_tokens.txt'))\n self.mapping = self._read_config(config_file)\n\n def get_token(self, keyword: str) -> int:\n \"\"\"Returns the token value for the given keyword or 0 if not found\"\"\"\n return self.mapping.get(keyword.upper(), 0)\n\n def _read_config(self, config_file: str) -> dict:\n mapping = {}\n\n with open(config_file, 'r') as file:\n for line in file:\n line = line.strip()\n if len(line) > 0 and not line.startswith('#'):\n components = line.split()\n mapping[components[0].strip()] = int(components[1].strip(), 16)\n\n return mapping\n","repo_name":"csetera/1984-compute-circus","sub_path":"src/python/cbm/util/KeywordTokenMapper.py","file_name":"KeywordTokenMapper.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"73755735171","text":"'''\nCreated on 7/9/2016\n\n@author: javier_zardain\n\n- Escribir un programa que dado un diccionario (empleado-salario) indique si este se encuentra por debajo del sueldo minimo ($6000)\nEn caso de que lo este, agregarlo a una lista para luego ser impresa por pantalla.\n'''\nimport random\n\nnombres = [\"Juan\", \"Martin\", \"Matias\", \"Edgardo\", \"Roberto\", \"Ivana\", \"Marina\", \"Liliana\", \"Eliana\", \"Isabel\"]\n\nsalarioPorEmpleado={}\n\nfor nombre in nombres:\n salarioPorEmpleado[nombre]=random.randint(1,9)*1000\n\nprint(\"Los siguientes empleados cobran menos de $6000\")\nprint({x:v for (x,v) in salarioPorEmpleado.items() if int(v) < 6000})\n","repo_name":"gussiciliano/python101","sub_path":"2.0-funciones/ejercicios_alumnos/Zardain, Javier/Ejercicios/Ej10.py","file_name":"Ej10.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"43091498483","text":"import pygame\nfrom OpenGL.GL import *\n\n\nclass Texture:\n \"\"\"\n Class to handle texture loading.\n \"\"\"\n\n def __init__(self, name, img=None, wrap=GL_REPEAT, sample=GL_NEAREST, format=GL_RGBA, type=GL_UNSIGNED_BYTE,\n target=GL_TEXTURE_2D):\n self.name = name\n self.format = format\n self.type = type\n self.wrap = wrap\n self.sample = sample\n self.target = target\n\n self.textureid = glGenTextures(1)\n\n print('* Loading texture {} at ID {}'.format('./textures/{}'.format(name), self.textureid))\n\n self.bind()\n\n if img is None:\n # load the image from file using pyGame - any other image reading function could be used here.\n print('Loading texture: texture/{}'.format(name))\n img = pygame.image.load('./textures/{}'.format(name))\n\n # convert the python image object to a plain byte array for passing to OpenGL\n data = pygame.image.tostring(img, \"RGBA\", 1)\n\n self.height = img.get_height()\n self.width = img.get_width()\n\n # load the texture in the buffer\n glTexImage2D(self.target, 0, format, self.width, self.height, 0, format, type, data)\n else:\n # if a data array is provided use this\n glTexImage2D(self.target, 0, format, img.shape[0], img.shape[1], 0, format, type, img)\n\n # set what happens for texture coordinates outside [0,1]\n glTexParameteri(self.target, GL_TEXTURE_WRAP_S, wrap)\n glTexParameteri(self.target, GL_TEXTURE_WRAP_T, wrap)\n\n # set how sampling from the texture is done.\n glTexParameteri(self.target, GL_TEXTURE_MAG_FILTER, sample)\n glTexParameteri(self.target, GL_TEXTURE_MIN_FILTER, sample)\n\n self.unbind()\n\n def bind(self):\n glBindTexture(self.target, self.textureid)\n\n def unbind(self):\n glBindTexture(self.target, 0)\n","repo_name":"NoahYewman/Graphics","sub_path":"Coursework/texture.py","file_name":"texture.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"31191099885","text":"from django.conf.urls import url\n\nfrom .views import *\n\nurlpatterns = [\nurl(r'^bienvenido/$',index, name='question_recents_list'),\nurl(r'^encriptar/$',AesEncriptar.as_view(), name='aes_encriptar'),\nurl(r'^desencriptar/$',AesDesencriptar.as_view(), name='aes_desencriptar'),\n\n]","repo_name":"albertopinedaorozco/seguridadsoftware","sub_path":"question/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"34335397845","text":"import torch\nimport numpy as np\nimport random\n\n\ndef setup_seed(args):\n seed = args.random_seed + args.global_rank\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n np.random.seed(seed)\n random.seed(seed)\n torch.backends.cudnn.deterministic = True\n","repo_name":"hanlinxuy/RWKV_UNKNOWN","sub_path":"src/task/set_seed.py","file_name":"set_seed.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"44"} +{"seq_id":"31636717213","text":"import asyncio\nimport datetime\nimport logging\nimport time\nfrom argparse import ArgumentParser\nfrom configparser import ConfigParser\nfrom pathlib import Path\nfrom typing import Tuple\n\nfrom AdKatsDB.AdKatsDB import AdKatsDB\nfrom GameStatsAPI.GameStatsAPI import GameStatsAPI, GameStatsAPIException\nfrom InfluxDB.InfluxDB import InfluxDB\n\n\nclass PlayerCountLogger:\n def __init__(self, adk: AdKatsDB, api: GameStatsAPI, influx: InfluxDB,\n log_interval=60):\n \"\"\"\n Init PlayerCountLogger\n :param adk:\n :param api:\n :param influx:\n :param log_interval: repeat logging every x seconds\n \"\"\"\n self.adk = adk\n self.api = api\n self.influx = influx\n self.log_interval = log_interval\n\n async def _get_server_stats(self, name: str, battlelog_id):\n \"\"\"\n Get the server status for the given server.\n :param name:\n :param battlelog_id:\n :return:\n \"\"\"\n try:\n server = await self.api.get_bf4_server_detailed(name)\n except GameStatsAPIException as e:\n logging.error(str(e))\n return\n except asyncio.exceptions.TimeoutError:\n logging.error('GameStatsAPI request ended in a timeout.')\n return\n\n if battlelog_id in server['serverLink']:\n return server\n\n logging.critical(f'Unable to find API profile for {name}')\n return None\n\n async def check(self):\n servers = await self.adk.get_status_of_servers()\n\n for server in servers:\n server_stats = {\n 'playerAmount': server.used_slots,\n 'inQueue': 0,\n 'mode': 'unknown',\n 'currentMap': 'unknown',\n 'favorites': 0\n }\n if server.guid is not None:\n server_stats = await self._get_server_stats(server.name,\n server.guid)\n if server_stats is None:\n continue\n\n # this one is synchronous :) makes the whole async stuff useless\n # lazy\n self.influx.log(\n server_id=server.server_id,\n used_slots=server.used_slots,\n seeded_slots=server_stats['playerAmount'],\n max_slots=server.max_slots,\n queue=server_stats['inQueue'],\n mode=server_stats['mode'],\n cur_map=server_stats['currentMap'],\n favorites=int(server_stats['favorites']),\n )\n\n def run(self):\n loop = asyncio.get_event_loop()\n try:\n while True:\n # useless async\n # dirty workaround to have a nearly perfect logging interval\n # (:\n start = datetime.datetime.now()\n\n loop.run_until_complete(self.check())\n\n done = datetime.datetime.now()\n delta = (done - start).total_seconds()\n time.sleep(self.log_interval - delta)\n finally:\n loop.close()\n\n\ndef read_config(file_path: Path) -> Tuple[int, AdKatsDB, InfluxDB]:\n \"\"\"\n Read the config\n :param file_path:\n :return: logging_interval, adk, influx\n \"\"\"\n parser = ConfigParser()\n parser.read(file_path)\n\n section = parser['General']\n logging_interval = section.getint('logging_interval', 60)\n\n section = parser['AdKatsDB']\n adk = AdKatsDB(\n host=section['host'],\n port=int(section['port']),\n user=section['user'],\n pw=section['pw'],\n database=section['db'],\n )\n\n section = parser['InfluxDB']\n influx = InfluxDB(\n host=section['host'],\n org=section['org'],\n bucket=section['bucket'],\n token=section['token'],\n )\n return logging_interval, adk, influx\n\n\ndef main():\n parser = ArgumentParser(description='E4GL InfluxDB PlayerCount Logger')\n parser.add_argument(\n '-c', '--config',\n help='Path to config file',\n required=True,\n dest='config'\n )\n args = parser.parse_args()\n\n logging_interval, adk, influx = read_config(args.config)\n api = GameStatsAPI()\n\n logger = PlayerCountLogger(adk, api, influx, logging_interval)\n logger.run()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Hedius/BF4MetricsLogger","sub_path":"src/BF4MetricsLogger.py","file_name":"BF4MetricsLogger.py","file_ext":"py","file_size_in_byte":4349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"31110566579","text":"#!/usr/bin/python\n\nimport urllib, webbrowser, ConfigParser, os, unicodedata\n\ndef results(parsed, original_query):\n return {\n \"title\": 'Confluence search',\n \"run_args\": [parsed['~words']]\n }\n\ndef run(words):\n config = ConfigParser.SafeConfigParser()\n config.read('%s/.confluence' % os.environ['HOME'])\n baseurl = config.get('confluence', 'baseurl')\n normalized = unicodedata.normalize('NFC', words)\n encoded = urllib.quote_plus(normalized.encode('utf8'))\n url = '%s/wiki/dosearchsite.action?queryString=%s' % (baseurl, encoded)\n webbrowser.open_new_tab(url)\n","repo_name":"suer/flashlight-confluence-plugin","sub_path":"plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"25121007194","text":"# 《决胜全面建成小康社会 夺取新时代中国特色社会主义伟大胜利》词云\nimport wordcloud\nimport jieba\ntry:\n f = open(\"新时代中国特色社会主义.txt\", \"r\", encoding=\"utf-8\")\nexcept:\n print(\"文件不存在\")\nt = f.read()\nf.close()\nls = jieba.lcut(t)\ntxt = \" \".join(ls)\nw = wordcloud.WordCloud(font_path=\"msyh.ttc\", width=1000, height=700, background_color=\"white\")\nw.generate(txt)\nw.to_file(\"grwordcloud.png\")\n","repo_name":"Judenpech/Catching-a-Python","sub_path":"Exercises/w7/GovRptWordCloudv1T1.py","file_name":"GovRptWordCloudv1T1.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"34131355872","text":"from typing import List\n\nclass Solution:\n def maximumTripletValue(self, nums: List[int]) -> int:\n length = len(nums)\n maxValue=0\n for i in range(length):\n for j in range(i+1,length):\n for k in range(j+1,length):\n maxValue=max((nums[i] - nums[j]) * nums[k],maxValue)\n return maxValue\n ","repo_name":"jsw7524/Leetcode","sub_path":"100088. Maximum Value of an Ordered Triplet I/100088. Maximum Value of an Ordered Triplet I.py","file_name":"100088. Maximum Value of an Ordered Triplet I.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"72434105092","text":"import os\nfrom selenium import webdriver\nfrom selenium.webdriver.firefox.firefox_binary import FirefoxBinary\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport my_log\n\nclass MyDriver:\n def __enter__(self):\n ff_profile = webdriver.FirefoxProfile()\n ff_profile.set_preference(\"network.proxy.type\", 2);\n ff_profile.set_preference(\"network.proxy.autoconfig_url\", \"http://wpad/wpad.dat\")\n\n my_log.debug(\"selenium server:\" + os.environ['SELENIUM_SERVER'])\n\n driver = webdriver.Remote(os.environ['SELENIUM_SERVER'],\n browser_profile=ff_profile,\n desired_capabilities=webdriver.DesiredCapabilities.FIREFOX.copy())\n\n driver.implicitly_wait(20) # seconds\n self.driver = driver\n return self.driver\n def __exit__(self, type, value, traceback):\n self.driver.quit()\n\ndef Login(driver, sso):\n #login\n driver.get(\"https://global-ebusiness.oraclecorp.com/OA_HTML/AppsLogin\")\n WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.NAME, 'ssousername')))\n ele_username = driver.find_element_by_name('ssousername')\n ele_username.send_keys(sso['username'])\n driver.find_element_by_name('password').send_keys(sso['password'])\n\n driver.find_element_by_class_name('submit_btn').click()\n \ndef Nav1(driver):\n #nav \n driver.find_element_by_link_text('CN BDC Employee Self Service').click()\n driver.find_element_by_link_text('Create Timecard').click()\n\ndef FillForm1(driver):\n #fill the form\n from selenium.webdriver.support.ui import Select\n select = Select(driver.find_element_by_name('A221N1'))\n select.select_by_visible_text('Vacation in Days')\n #driver.find_element_by_name('B21_1_4').send_keys('1')\n #driver.find_element_by_name('B21_1_5').send_keys('1')\n driver.find_element_by_name('B21_1_6').send_keys('1')\n driver.find_element_by_id('review_uixr').click()\n\ndef TakeScreenShot(driver, filename):\n #take screen shot\n driver.save_screenshot(filename)\n \nimport string\nimport random\ndef id_generator(size=6, chars=string.ascii_uppercase + string.digits):\n return ''.join(random.choice(chars) for _ in range(size))\n\ndef CreateTimeCard(data, callback):\n with MyDriver() as driver:\n try:\n print('Start Create Time Card')\n Login(driver, sso=data['sso'])\n callback({\"text\":'Login done.'})\n Nav1(driver)\n callback({'text':'Nav done.'})\n FillForm1(driver)\n callback({'text':'Fill Form done.'})\n \n randfile = id_generator() +'.png'\n TakeScreenShot(driver, 'static/' + randfile)\n callback({'text':'Job done.','screen':randfile})\n\n except Exception as e:\n callback({'text':'Error:'+str(e)})\n\ndef perform(data, callback):\n CreateTimeCard(data, callback)\n \nif __name__ == \"__main__\":\n def testCallback(res):\n print(res['text'])\n \n perform({}, testCallback)\n","repo_name":"youngliuus21/act_srv","sub_path":"createtimecard.py","file_name":"createtimecard.py","file_ext":"py","file_size_in_byte":3122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"31415332817","text":"import os\r\nimport os.path\r\nimport sys\r\n\r\n# Constants\r\nASM_FILE = 1\r\nCOMP_DICT = {'0': \"110101010\", '1': \"110111111\", \"-1\": \"110111010\",\r\n 'D': \"110001100\",\r\n 'A': \"110110000\", 'M': \"111110000\", \"!D\": \"110001101\",\r\n \"!A\": \"110110001\",\r\n \"!M\": \"111110001\", \"-D\": \"110001111\", \"-A\": \"110110011\",\r\n \"-M\": \"111110011\", \"D+1\": \"110011111\", \"A+1\": \"110110111\",\r\n \"M+1\": \"111110111\", \"D-1\": \"110001110\", \"A-1\": \"110110010\",\r\n \"M-1\": \"111110010\", \"D+A\": \"110000010\", \"D+M\": \"111000010\",\r\n \"D-A\": \"110010011\", \"D-M\": \"111010011\", \"A-D\": \"110000111\",\r\n \"M-D\": \"111000111\", \"D&A\": \"110000000\", \"D&M\": \"111000000\",\r\n \"D|A\": \"110010101\", \"D|M\": \"111010101\", \"D>>\": \"010010000\",\r\n \"A>>\": \"010000000\", \"M>>\": \"011000000\", \"D<<\": \"010110000\",\r\n \"A<<\": \"010100000\", \"M<<\": \"011100000\"}\r\nDEST_DICT = {'M': \"001\", 'D': \"010\", 'A': \"100\", \"MD\": \"011\", \"AM\": \"101\",\r\n \"AD\": \"110\", \"AMD\": \"111\", \"000\": \"000\"}\r\nJUMP_DICT = {'JGT': \"001\", 'JEQ': \"010\", 'JLT': \"100\", \"JGE\": \"011\",\r\n \"JNE\": \"101\", \"JLE\": \"110\", \"JMP\": \"111\", \"000\": \"000\"}\r\n\r\n\r\ndef populate_symbol_dict():\r\n \"\"\"\r\n resets a dict it and fills it with the default symbols of hack.\r\n :return: the dict with all the default symbols pointing at the correct\r\n number for each one.\r\n \"\"\"\r\n symbols = dict()\r\n symbols[\"SP\"] = 0\r\n symbols[\"LCL\"] = 1\r\n symbols[\"ARG\"] = 2\r\n symbols[\"THIS\"] = 3\r\n symbols[\"THAT\"] = 4\r\n symbols[\"R0\"] = 0\r\n symbols[\"R1\"] = 1\r\n symbols[\"R2\"] = 2\r\n symbols[\"R3\"] = 3\r\n symbols[\"R4\"] = 4\r\n symbols[\"R5\"] = 5\r\n symbols[\"R6\"] = 6\r\n symbols[\"R7\"] = 7\r\n symbols[\"R8\"] = 8\r\n symbols[\"R9\"] = 9\r\n symbols[\"R10\"] = 10\r\n symbols[\"R11\"] = 11\r\n symbols[\"R12\"] = 12\r\n symbols[\"R13\"] = 13\r\n symbols[\"R14\"] = 14\r\n symbols[\"R15\"] = 15\r\n symbols[\"SCREEN\"] = 16384\r\n symbols[\"KBD\"] = 24576\r\n return symbols\r\n\r\n\r\ndef first_pass(symbols, lines):\r\n \"\"\"\r\n goes over the lines in lines and if there are any jump declarations\r\n then it adds those as symbols to the symbols dict.\r\n :param symbols: a dict of symbols and their number.\r\n :param lines: a list of all the lines from the asm file.\r\n :return: the lines after the jumps were written to the symbols and the\r\n whitespaces were removed.\r\n \"\"\"\r\n line_counter = 0\r\n # the lines without the jumps and whitespace\r\n new_lines = list()\r\n for line in lines:\r\n line = \"\".join(line.split())\r\n if \"/\" in line:\r\n line = line[0:line.index(\"/\")]\r\n if len(line) == 0:\r\n continue\r\n if line[0] == \"(\":\r\n symbol = line[1:-1]\r\n symbols[symbol] = line_counter\r\n else:\r\n if line != \"\\n\" and line[0] != \"/\":\r\n new_lines.append(line)\r\n line_counter += 1\r\n return new_lines\r\n\r\n\r\ndef read_file_in_args(file_name):\r\n \"\"\"\r\n reads for the file given and stores each line in a list.\r\n :param file_name: the name of the file we read.\r\n :return: the list that stores the lines.\r\n \"\"\"\r\n with open(file_name, \"r\") as file:\r\n lines = list()\r\n for line in file:\r\n lines.append(line)\r\n return lines\r\n\r\n\r\ndef go_over_lines(symbols, lines):\r\n \"\"\"\r\n goes over each line of the asm file (again) and translates each line\r\n into the appropriate 16 bit representation.\r\n :param symbols: the dict with all the symbols in the file\r\n (minus variables).\r\n :param lines: a list where each cell is a line from the asm file.\r\n :return: a list where each cell is a 16 bit code representing the\r\n corresponding line in the asm file.\r\n \"\"\"\r\n end_list = list()\r\n line_counter = 16\r\n for line in lines:\r\n bit_line = \"\"\r\n line_indicator = line[0]\r\n # if its an A instruction\r\n if line_indicator == '@':\r\n address = line[1::]\r\n # if it's a number then convert it to binary and add zeros\r\n # note: we assume the number isn't bigger then 16 bits\r\n if address.isdigit():\r\n bit_line = bin(int(address)).split('b')[1]\r\n while len(bit_line) < 16:\r\n bit_line = '0' + bit_line\r\n # if it's a variable\r\n else:\r\n if address not in symbols:\r\n symbols[address] = line_counter\r\n line_counter += 1\r\n address_num = symbols[address]\r\n bit_line = bin(int(address_num)).split('b')[1]\r\n while len(bit_line) < 16:\r\n bit_line = '0' + bit_line\r\n # its a C instruction\r\n else:\r\n bit_line += \"1\"\r\n # dividing the line to computation, destination and jump\r\n jump, dest = \"000\", \"000\"\r\n if '=' in line:\r\n dest, comp_jump = line.split('=')\r\n if ';' in comp_jump:\r\n comp, jump = comp_jump.split(';')\r\n else:\r\n comp = comp_jump\r\n else:\r\n comp, jump = line.split(';')\r\n bit_line += COMP_DICT[comp]\r\n bit_line += DEST_DICT[dest]\r\n bit_line += JUMP_DICT[jump]\r\n end_list.append(bit_line)\r\n return end_list\r\n\r\n\r\ndef main():\r\n list_of_files = list()\r\n # check if the path is a directory and fills list_of_files with all the\r\n # files names\r\n if os.path.isdir(sys.argv[ASM_FILE]):\r\n for filename in os.listdir(sys.argv[ASM_FILE]):\r\n if filename.endswith(\".asm\"):\r\n if sys.argv[ASM_FILE].endswith(\"/\"):\r\n list_of_files.append(\r\n os.path.join(sys.argv[ASM_FILE] + \"\" + filename))\r\n else:\r\n list_of_files.append(\r\n os.path.join(sys.argv[ASM_FILE] + \"/\" + filename))\r\n else:\r\n list_of_files.append(sys.argv[ASM_FILE])\r\n # go over each file and deal with it as necessary\r\n for file_name in list_of_files:\r\n relative_file_name = file_name\r\n symbols = populate_symbol_dict()\r\n lines = read_file_in_args(relative_file_name)\r\n new_lines = first_pass(symbols, lines)\r\n bit_lines = go_over_lines(symbols, new_lines)\r\n write_file = file_name[0:-3] + \"hack\"\r\n with open(write_file, \"w\") as file:\r\n for line in bit_lines:\r\n file.write(line)\r\n file.write(\"\\n\")\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"tomf0333/N2T_Assembler","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":6626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"34371376504","text":"sal= int(input('Quanto você ganha por mês? :'))\npar = int(input('Em quantos anos deseja pagar? :'))\n\ntot = sal / 5\nprint(tot)\n\nif par == (sal*30) / 100:\n print('APROVADO')\nelse:\n print('REPROVADO')\n","repo_name":"freitasSystemOutPrint/Python3","sub_path":"Mundo #02/ex-036-a011-emprestimo.py","file_name":"ex-036-a011-emprestimo.py","file_ext":"py","file_size_in_byte":206,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"25324804376","text":"'''\nTitle : 159. Longest Substring with At Most Two Distinct Characters ($$$)\nProblem : https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/description/\n : https://www.lintcode.com/problem/longest-substring-with-at-most-two-distinct-characters/description\n'''\n'''\nbrute force comparison without counter recording characters' latest position/number of repetition\nReference: https://blog.csdn.net/zhangpeterx/article/details/100051285\n'''\nclass Solution:\n def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:\n if not s: return 0\n start, prevstart, res = -1, 0, 0\n for i in range(1, len(s)):\n if s[i] != s[i-1]:\n if s[i] != s[start] and start > -1:\n res = max(res, i-prevstart)\n prevstart = start + 1\n start = i - 1 # since s[i] != s[i-1] we already found two distinct characters\n return max(res, len(s)-prevstart) # do not forget to compare with the last segment","repo_name":"jiewu-stanford/leetcode","sub_path":"159. Longest Substring with At Most Two Distinct Characters.py","file_name":"159. Longest Substring with At Most Two Distinct Characters.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"44"} +{"seq_id":"27302927979","text":"import collections\n\nimport tensorflow as tf\n\nfrom tf_transformers.data import TFProcessor\nfrom tf_transformers.data.squad_utils_sp import *\nfrom tf_transformers.data.squad_utils_sp import _compute_softmax, _get_best_indexes\nfrom tf_transformers.utils.tokenization import BasicTokenizer\n\n\ndef extract_from_dict(dict_items, key):\n holder = []\n for item in dict_items:\n holder.append(item[key])\n return holder\n\n\nclass Span_Extraction_Pipeline:\n def __init__(\n self,\n model,\n tokenizer,\n tokenizer_fn,\n SPECIAL_PIECE,\n n_best_size,\n n_best,\n max_answer_length,\n max_seq_length,\n max_query_length,\n doc_stride,\n batch_size=32,\n ):\n\n self.get_model_fn(model)\n self.tokenizer = tokenizer\n self.tokenizer_fn = tokenizer_fn\n self.SPECIAL_PIECE = SPECIAL_PIECE\n self.n_best_size = n_best_size\n self.n_best = n_best\n self.max_answer_length = max_answer_length\n\n self.basic_tokenizer = BasicTokenizer(do_lower_case=False)\n self.max_seq_length = max_seq_length\n self.max_query_length = max_query_length\n self.doc_stride = doc_stride\n self.batch_size = batch_size\n\n def get_model_fn(self, model):\n self.model_fn = None\n # keras Model\n if isinstance(model, tf.keras.Model):\n self.model_fn = model\n else:\n # saved model\n if \"saved_model\" in str(type(model)):\n # Extract signature\n self.model_pb = model.signatures[\"serving_default\"]\n\n def model_fn(x):\n return self.model_pb(**x)\n\n self.model_fn = model_fn\n if self.model_fn is None:\n raise ValueError(\"Please check the type of your model\")\n\n def run(self, dataset):\n start_logits = []\n end_logits = []\n for batch_inputs in dataset:\n model_outputs = self.model_fn(batch_inputs)\n start_logits.append(model_outputs[\"start_logits\"])\n end_logits.append(model_outputs[\"end_logits\"])\n\n # Unstack\n\n start_logits_unstacked = []\n end_logits_unstacked = []\n\n for batch_logits in start_logits:\n start_logits_unstacked.extend(tf.unstack(batch_logits))\n for batch_logits in end_logits:\n end_logits_unstacked.extend(tf.unstack(batch_logits))\n\n return start_logits_unstacked, end_logits_unstacked\n\n def convert_to_features(self, dev_examples):\n \"\"\"Convert examples to features\"\"\"\n qas_id_examples = {ex[\"qas_id\"]: ex for ex in dev_examples}\n dev_examples_cleaned = post_clean_train_squad(dev_examples, self.basic_tokenizer, is_training=False)\n qas_id_info, dev_features = example_to_features_using_fast_sp_alignment_test(\n self.tokenizer,\n dev_examples_cleaned,\n self.max_seq_length,\n self.max_query_length,\n self.doc_stride,\n self.SPECIAL_PIECE,\n )\n return qas_id_info, dev_features, qas_id_examples\n\n def convert_features_to_dataset(self, dev_features):\n \"\"\"Feaures to TF dataset\"\"\"\n # for TFProcessor\n def local_parser():\n for f in dev_features:\n yield tokenizer_fn(f)\n\n # Create dataset\n tf_processor = TFProcessor()\n dev_dataset = tf_processor.process(parse_fn=local_parser())\n self.dev_dataset = dev_dataset = tf_processor.auto_batch(dev_dataset, batch_size=self.batch_size)\n return dev_dataset\n\n def post_process(self, dev_features, qas_id_info, start_logits_unstacked, end_logits_unstacked, qas_id_examples):\n # List of qa_ids per feature\n # List of doc_offset, for shifting when an example gets splitted due to length\n qas_id_list = extract_from_dict(dev_features, \"qas_id\")\n doc_offset_list = extract_from_dict(dev_features, \"doc_offset\")\n\n # Group by qas_id -> predictions , because multiple feature may come from\n # single example :-)\n\n qas_id_logits = {}\n for i in range(len(qas_id_list)):\n qas_id = qas_id_list[i]\n example = qas_id_info[qas_id]\n feature = dev_features[i]\n assert qas_id == feature[\"qas_id\"]\n if qas_id not in qas_id_logits:\n qas_id_logits[qas_id] = {\n \"tok_to_orig_index\": example[\"tok_to_orig_index\"],\n \"aligned_words\": example[\"aligned_words\"],\n \"feature_length\": [len(feature[\"input_ids\"])],\n \"doc_offset\": [doc_offset_list[i]],\n \"passage_start_pos\": [feature[\"input_ids\"].index(self.tokenizer.sep_token) + 1],\n \"start_logits\": [start_logits_unstacked[i]],\n \"end_logits\": [end_logits_unstacked[i]],\n }\n\n else:\n qas_id_logits[qas_id][\"start_logits\"].append(start_logits_unstacked[i])\n qas_id_logits[qas_id][\"end_logits\"].append(end_logits_unstacked[i])\n qas_id_logits[qas_id][\"feature_length\"].append(len(feature[\"input_ids\"]))\n qas_id_logits[qas_id][\"doc_offset\"].append(doc_offset_list[i])\n qas_id_logits[qas_id][\"passage_start_pos\"].append(\n feature[\"input_ids\"].index(self.tokenizer.sep_token) + 1\n )\n\n qas_id_answer = {}\n skipped = []\n skipped_null = []\n global_counter = 0\n final_result = {}\n for qas_id in qas_id_logits:\n\n current_example = qas_id_logits[qas_id]\n\n _PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name\n \"PrelimPrediction\", [\"feature_index\", \"start_index\", \"end_index\", \"start_log_prob\", \"end_log_prob\"]\n )\n prelim_predictions = []\n example_features = []\n for i in range(len(current_example[\"start_logits\"])):\n f = dev_features[global_counter]\n assert f[\"qas_id\"] == qas_id\n example_features.append(f)\n global_counter += 1\n passage_start_pos = current_example[\"passage_start_pos\"][i]\n feature_length = current_example[\"feature_length\"][i]\n\n start_log_prob_list = current_example[\"start_logits\"][i].numpy().tolist()[:feature_length]\n end_log_prob_list = current_example[\"end_logits\"][i].numpy().tolist()[:feature_length]\n start_indexes = _get_best_indexes(start_log_prob_list, self.n_best_size)\n end_indexes = _get_best_indexes(end_log_prob_list, self.n_best_size)\n\n for start_index in start_indexes:\n for end_index in end_indexes:\n # We could hypothetically create invalid predictions, e.g., predict\n # that the start of the span is in the question. We throw out all\n # invalid predictions.\n if start_index < passage_start_pos or end_index < passage_start_pos:\n continue\n if end_index < start_index:\n continue\n length = end_index - start_index + 1\n if length > self.max_answer_length:\n continue\n start_log_prob = start_log_prob_list[start_index]\n end_log_prob = end_log_prob_list[end_index]\n start_idx = start_index - passage_start_pos\n end_idx = end_index - passage_start_pos\n\n prelim_predictions.append(\n _PrelimPrediction(\n feature_index=i,\n start_index=start_idx,\n end_index=end_idx,\n start_log_prob=start_log_prob,\n end_log_prob=end_log_prob,\n )\n )\n\n prelim_predictions = sorted(\n prelim_predictions, key=lambda x: (x.start_log_prob + x.end_log_prob), reverse=True\n )\n answer_dict = {}\n answer_dict[qas_id] = []\n total_scores = []\n if prelim_predictions:\n for top_n in range(self.n_best):\n best_index = prelim_predictions[top_n].feature_index\n aligned_words = current_example[\"aligned_words\"]\n try:\n tok_to_orig_index = current_example[\"tok_to_orig_index\"]\n reverse_start_index_align = tok_to_orig_index[\n prelim_predictions[top_n].start_index + example_features[best_index][\"doc_offset\"]\n ] # aligned index\n reverse_end_index_align = tok_to_orig_index[\n prelim_predictions[top_n].end_index + example_features[best_index][\"doc_offset\"]\n ]\n\n predicted_words = [\n w\n for w in aligned_words[reverse_start_index_align : reverse_end_index_align + 1]\n if w != self.SPECIAL_PIECE\n ]\n predicted_text = \" \".join(predicted_words)\n qas_id_answer[qas_id] = predicted_text\n total_scores.append(\n prelim_predictions[top_n].start_log_prob + prelim_predictions[top_n].end_log_prob\n )\n except:\n predicted_text = \"\"\n qas_id_answer[qas_id] = \"\"\n skipped.append(qas_id)\n total_scores.append(0.0 + 0.0)\n answer_dict[qas_id].append({\"text\": predicted_text})\n\n _probs = _compute_softmax(total_scores)\n\n for top_n in range(self.n_best):\n answer_dict[qas_id][top_n][\"probability\"] = _probs[top_n]\n final_result[qas_id] = qas_id_examples[qas_id]\n else:\n qas_id_answer[qas_id] = \"\"\n skipped_null.append(qas_id)\n final_result[qas_id][\"answers\"] = answer_dict\n return final_result\n\n def __call__(self, questions, contexts, qas_ids=[]):\n\n # If qas_id is empty, we assign positions as id\n if qas_ids == []:\n qas_ids = [i for i in range(len(questions))]\n # each question should have a context\n assert len(questions) == len(contexts) == len(qas_ids)\n\n dev_examples = convert_question_context_to_standard_format(questions, contexts, qas_ids)\n qas_id_info, dev_features, qas_id_examples = self.convert_to_features(dev_examples)\n dev_dataset = self.convert_features_to_dataset(dev_features)\n #self.dev_features = dev_features\n #self.qas_id_info = qas_id_info\n #self.qas_id_examples = qas_id_examples\n \n start_logits_unstacked, end_logits_unstacked = self.run(dev_dataset)\n final_result = self.post_process(dev_features, qas_id_info, start_logits_unstacked, end_logits_unstacked, qas_id_examples)\n return final_result\n","repo_name":"adbmd/tf-transformers","sub_path":"src/tf_transformers/pipeline/span_extraction_pipeline.py","file_name":"span_extraction_pipeline.py","file_ext":"py","file_size_in_byte":11381,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"32792219963","text":"import arduinoserial\n\n\n#from datetime import datetime, date, time\nfrom time import sleep\nimport logging\n\n\n\narduino_location=\"/dev/ttyACM0\"\narduino_pulse_time=300 #milliseconds to pulse 433Mhz signal\narduino_quiet_time=3 # seconds to wait for arduino to be ready after connecting and sending \narduino_between_retry_time=1 #seconds to wait between consecutive pulses\narduino_retry_times=10 #number of times to retry\n\ndef turn_on():\n trigger_pump(1)\n\ndef turn_off():\n trigger_pump(0)\n\ndef trigger_pump(state):\n\tarduino = arduinoserial.SerialPort(arduino_location, 9600)\n\tsleep(arduino_quiet_time) # wait for arduino to reboot :(\n\t\n\ttimes=arduino_retry_times\n\n\twhile(times > 0) :\n\t\tarduino.write(\"%u,%u\\n\" % (state,arduino_pulse_time))\n\t\t#wait for pulse to finish, then some more\n\t\tsleep((arduino_pulse_time/1000)+arduino_quiet_time)\n\t\tresponse= arduino.read_until(\"\\n\").strip()\n\t\t\n\t\tif (response!=\"ok\") :\n\n\t\t\tlogging.info(\"Pump trigger failed\")\n\t\t\traise Exception(\"Pump trigger failed\")\n\t\n\t\t#libary recognized cr as lf, ardunio ends line with cr/lf, so need to read twice to clear buffer\n\t\tresponse= arduino.read_until(\"\\n\").strip()\n\t\tsleep(arduino_between_retry_time)\t\n\t\ttimes -= 1\n\tlogging.info(\"Pump triggered OK\")\n\n\n\n","repo_name":"jacrify/pumpcontrol","sub_path":"pump.py","file_name":"pump.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"4566378078","text":"'''\nWork with multiple spreadsheets\n\n\nWorkbooks meant primarily for human readers, not machines, may store data about a single subject across multiple sheets. For example, a file may have a different sheet of transactions for each region or year in which a business operated.\n\nThe FreeCodeCamp New Developer Survey file is set up similarly, with samples of responses from different years in different sheets. Your task here is to compile them in one data frame for analysis.\n\npandas has been imported as pd. All sheets have been read into the ordered dictionary responses, where sheet names are keys and data frames are values, so you can get data frames with the values() method.\n\nInstructions\n100 XP\n\n- Create an empty data frame, all_responses.\n- Set up a for loop to iterate through the values in the responses dictionary.\n- Append each data frame to all_responses and reassign the result to the same variable name.\n\n'''\n\n# Create an empty data frame\nall_responses = pd.DataFrame()\n\n# Set up for loop to iterate through values in responses\nfor df in responses.values():\n # Print the number of rows being added\n print(\"Adding {} rows\".format(df.shape[0]))\n # Append df to all_responses, assign result\n all_responses = all_responses.append(df)\n\n# Graph employment statuses in sample\ncounts = all_responses.groupby(\"EmploymentStatus\").EmploymentStatus.count()\ncounts.plot.barh()\nplt.show()\n","repo_name":"chandrainf/Datacamp","sub_path":"Data Engineer with Python Track/03. Streamlined Data Ingestion with Pandas/Chapter/02. Importing Data From Excel Files/05-Work with multiple spreadsheets.py","file_name":"05-Work with multiple spreadsheets.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"40"} +{"seq_id":"72314782839","text":"\"\"\"\nExample requests:\n\nGET all users\n\ncurl http://0.0.0.0/admin/users \\\n -H 'Content-Type: application/json'\n\"\"\"\n\nfrom src.core.util.LogFactory import LogFactory\nfrom src.webserver.decorators.HTTPLogger import http_logger\nfrom src.webserver.WebServer import WebServerInit\nfrom src.core.util.ErrorFactory import errorStackTrace\n\nfrom flask import Flask, jsonify, request\n\nfrom src.core.idm.data.model.User import User\nfrom src.core.idm.data.db.UserData import UserData\n\nflask_ref: Flask = WebServerInit.flask\n\nclass AdminController:\n\n def __init__(self):\n LogFactory.MAIN_LOG.info('Start AdminController')\n\n @staticmethod\n @flask_ref.route('/admin/users', methods=['GET'])\n @http_logger\n def admin_api():\n try:\n UserData.initialize()\n allUsers = UserData.fetch_all_users()\n rUsers = []\n for user in allUsers:\n rUsers.append(user.serialize())\n return {\"users\": rUsers},200\n except Exception as e:\n LogFactory.MAIN_LOG.error(f\"Failed admin api {errorStackTrace(e)}\")\n return {\n \"response\" : \"sadness\"\n }, 500","repo_name":"xxdunedainxx/dig","sub_path":"server/src/webserver/controllers/admin/AdminController.py","file_name":"AdminController.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"20649855952","text":"#Import libraries\nimport os\nimport torch\nimport torchvision\nfrom torchinfo import summary\nfrom torchvision.utils import make_grid\nfrom PIL import Image\nimport requests\nfrom torchvision.datasets import FashionMNIST\nfrom torchvision.transforms import Compose, ToTensor, Normalize\nimport matplotlib.pyplot as plt\nfrom torch.utils.data.sampler import SubsetRandomSampler\nfrom torch.utils.data.dataloader import DataLoader\nfrom CNN import ImageClassifierNet\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchinfo import summary\nimport numpy as np\n\ndef show_example(img, label):\n print('Label: {} ({})'.format(dataset.classes[label], label))\n plt.imshow(img.squeeze(), cmap='Greys_r')\n plt.axis(False)\ndef split_indices(n, val_frac, seed):\n # Determine the size of the validation set\n n_val = int(val_frac * n)\n np.random.seed(seed)\n # Create random permutation between 0 to n-1\n idxs = np.random.permutation(n)\n # Pick first n_val indices for validation set\n return idxs[n_val:], idxs[:n_val]\ndef show_batch(dl):\n for images, labels in dl:\n fig, ax = plt.subplots(figsize=(10,10))\n ax.set_xticks([]); ax.set_yticks([])\n ax.imshow(make_grid(images, 8).permute(1, 2, 0), cmap='Greys_r')\n break\n#Definitions for enabling training on GPU\ndef get_default_device():\n \"\"\"Use GPU if available, else CPU\"\"\"\n if torch.cuda.is_available():\n return torch.device('cuda')\n else:\n return torch.device('cpu')\n\n\ndef to_device(data, device):\n \"\"\"Move tensor(s) to chosen device\"\"\"\n if isinstance(data, (list, tuple)):\n return [to_device(x, device) for x in data]\n return data.to(device, non_blocking=True)\n\n\nclass DeviceDataLoader():\n \"\"\"Wrap a dataloader to move data to a device\"\"\"\n\n def __init__(self, dl, device):\n self.dl = dl\n self.device = device\n\n def __iter__(self):\n \"\"\"Yield a batch of data after moving it to device\"\"\"\n for b in self.dl:\n yield to_device(b, self.device)\n\n def __len__(self):\n \"\"\"Number of batches\"\"\"\n return len(self.dl)\n#to train model\ndef train_model(n_epochs, model, train_dl, val_dl, loss_fn, opt_fn, lr):\n \"\"\"\n Trains the model on a dataset.\n\n Args:\n n_epochs: number of epochs\n model: ImageClassifierNet object\n train_dl: training dataloader\n val_dl: validation dataloader\n loss_fn: the loss function\n opt_fn: the optimizer\n lr: learning rate\n\n Returns:\n The trained model.\n A tuple of (model, train_losses, val_losses, train_accuracies, val_accuracies)\n \"\"\"\n # Record these values the end of each epoch\n train_losses, val_losses, train_accuracies, val_accuracies = [], [], [], []\n\n ######################\n # YOUR CODE HERE #\n ######################\n for i in range(1, n_epochs + 1):\n tr_loss = 0\n opt_fn.zero_grad()\n # get dataset from dataloader\n train_features, train_labels = next(iter(train_dl))\n val_features, val_labels = next(iter(val_dl))\n # get prediction\n train_out = model(train_features)\n val_out = model(val_features)\n # get loss\n train_loss = loss_fn(train_out, train_labels)\n val_loss = loss_fn(val_out, val_labels)\n train_losses.append(train_loss)\n val_losses.append(val_loss)\n # update weights?\n train_loss.backward()\n opt_fn.step()\n tr_loss = train_loss.item()\n\n return model, train_losses, val_losses, train_accuracies, val_accuracies\nif __name__ == '__main__':\n # Checking if hardware acceleration enabled\n if int(os.environ.get('COLAB_GPU', 0)) > 0: # os.environ['COLAB_GPU']\n print(\"*** GPU connected\")\n else:\n print(\"*** No hardware acceleration: change to GPU under Runtime > Change runtime type > Hardware accelerator\")\n\n # Transform to normalize the data and convert to a tensor\n transform = Compose([ToTensor(),\n Normalize((0.5,), (0.5,))\n ])\n\n # Download the data\n dataset = FashionMNIST('MNIST_data/', download=True, train=True, transform=transform)\n #print(dataset.classes)\n #show_example(*dataset[20])\n #show_example(*dataset[20000])\n #Create training and validation dataset\n val_frac = 0.2 # 0.3, 0.1 ## Set the fraction for the validation set\n rand_seed = 201 # to insure same split for every code execution ## Set the random seed\n\n train_indices, val_indices = split_indices(len(dataset), val_frac, rand_seed)\n print(\"#samples in training set: {}\".format(len(train_indices)))\n print(\"#samples in validation set: {}\".format(len(val_indices)))\n batch_size = 32 # 64 ## Set the batch size\n # Training sampler and data loader\n train_sampler = SubsetRandomSampler(train_indices)\n train_dl = DataLoader(dataset,\n batch_size,\n sampler=train_sampler)\n\n # Validation sampler and data loader\n val_sampler = SubsetRandomSampler(val_indices)\n val_dl = DataLoader(dataset,\n batch_size,\n sampler=val_sampler)\n #show_batch(train_dl)\n\n #Build model\n model = ImageClassifierNet()\n #summary(model, input_size=(batch_size, 1, 28, 28)) #to show # of parameters\n #enable training on gpu\n device = get_default_device()\n\n train_dl = DeviceDataLoader(train_dl, device)\n val_dl = DeviceDataLoader(val_dl, device)\n\n to_device(model, device)\n #train model\n num_epochs = 20 # Max number of training epochs\n loss_fn = nn.CrossEntropyLoss() # Define the loss function\n opt_fn = torch.optim.Adam(model.parameters(), lr=0.07) # Select an optimizer\n lr = 0.07 # Set the learning rate\n history = train_model(num_epochs, model, train_dl, val_dl, loss_fn, opt_fn, lr)\n model, train_losses, val_losses, train_accuracies, val_accuracies = history","repo_name":"esepark12/CSCE633_PA5","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"19795081546","text":"# -*- coding:utf-8 -*-\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n \"\"\"\n 题目描述\n\n 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。\n \"\"\"\n def __init__(self):\n self.left_node = None\n self.pre_node = None\n\n def Convert(self, pRootOfTree):\n # 二叉搜索树的有序遍历就是中序遍历 左-中-右\n # 采用中序递归遍历的方式,并用一个临时变量记录上次访问的节点指针.\n # 当前结点指向左指针指向前驱结点\n # 前驱结点右指针指向当前结点\n\n # 边界判断\n if not pRootOfTree:\n return None\n # 中序遍历\n self.Convert(pRootOfTree.left)\n if not self.left_node:\n self.left_node = pRootOfTree\n if self.pre_node:\n self.pre_node.right = pRootOfTree\n pRootOfTree.left = self.pre_node\n self.pre_node = pRootOfTree\n self.Convert(pRootOfTree.right)\n\n return self.left_node","repo_name":"h-j-13/Algorithms-Soulution","sub_path":"剑指offer/二叉搜索树与双向链表.py","file_name":"二叉搜索树与双向链表.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"9906805490","text":"\r\n\r\nimport math\r\n\r\n\r\nA = input(\"Enter vector A:\\n\").split(\" \")\r\n\r\nB = input(\"Enter vector B:\\n\").split(\" \")\r\n\r\n\r\nfor i in range (len(A)):\r\n A[i] = eval(A[i])\r\n B[i] = eval(B[i])\r\n\r\nsum_vectors = []\r\nfor i in range(len(A)):\r\n sum_vectors.append(A[i] + B[i]) \r\n \r\n \r\n\r\nproduct = 0\r\nfor i in range(len(sum_vectors)):\\\r\n product += (A[i] * B[i])\r\n\r\n\r\nnorm_A = 0\r\nnorm_B = 0\r\n \r\n \r\nfor a in A:\r\n norm_A += a**2 \r\nnorm_A = math.sqrt(norm_A)\r\n \r\n\r\nfor b in B:\r\n norm_B += b**2 \r\nnorm_B = math.sqrt(norm_B)\r\n\r\n\r\n#ouput\r\nprint(\"A+B =\", sum_vectors)\r\nprint(\"A.B =\", product)\r\nprint(\"|A| =\", \"{:.2f}\".format(norm_A, 3))\r\nprint(\"|B| =\", \"{:.2f}\".format(norm_B, 3))\r\n\r\n\r\n\r\n","repo_name":"MrHamdulay/csc3-capstone","sub_path":"examples/data/Assignment_6/mlsomp001/question2.py","file_name":"question2.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"43196852065","text":"import itertools as it\nimport pandas as pd\n\nout = pd.DataFrame({'riders':[\"R1\",\"R2\",\"R3\",\"R4\",\"R5\",\"R6\"],\n 'places':[1,5,4,2,3,6],\n 'elos':[1000, 1000, 1000, 1000, 1000, 1000]})\n\ndef computeELO(rider1, rider2):\n\n elo1 = 10 # how much the guz who won gained\n elo2 = 10 # loser lost pts, but positive\n\n return (elo1, elo2)\n\nout = out.sort_values('places')\n\nlength = len(list(out['places']))\nriders = list(out['riders'])\nelos = list(out['elos'])\n\nfor i in range(length):\n if i == length:\n continue\n else:\n for j in range(i + 1, length, 1):\n newELO = computeELO(riders[i], riders[j])\n elos[i] += newELO[0]\n elos[j] -= newELO[1]\n\nnewDF = pd.DataFrame({'riders':riders,\n 'elos':elos})\n\nnewDF.to_csv('NEW_ELO.csv')\n","repo_name":"ant1code/github_cycling_glicko","sub_path":"tom.py","file_name":"tom.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"1426209418","text":"from django.contrib import admin\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.urls import path, re_path, include\nimport debug_toolbar\nfrom rest_framework_simplejwt.views import (\n TokenObtainPairView,\n TokenRefreshView,\n)\nfrom .views import IndexView, json_api, json_api_day\n\n# User Customized Urls\nurlpatterns = [\n path(\"api-word/\", json_api),\n path(\"api-word//\", json_api_day),\n path('', IndexView.as_view(), name=\"home\"),\n re_path(r\"\\b(add|detail/[0-9]+)\\b/\", IndexView.as_view()),\n re_path(r\"\\b(create_word|day|day/[0-9]+)\\b/\", IndexView.as_view()),\n]\n\n# Admin & DRF Urls\nurlpatterns += [\n path('admin/', admin.site.urls),\n path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),\n path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),\n]\n\n# Django DEBUG Tools & Media Folders\nif settings.DEBUG:\n\n urlpatterns += [\n path('__debug__/', include(debug_toolbar.urls)),\n ]\n\n urlpatterns += static(\n settings.MEDIA_URL,\n document_root=settings.MEDIA_ROOT)\n","repo_name":"YongBeomKim/ReactTDD","sub_path":"server/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"14313039087","text":"# third party imports\nimport uuid\nfrom logging import getLogger\n\nimport firebase_admin\nfrom django.conf import settings\nfrom firebase_admin import credentials\nfrom pyfcm import FCMNotification as PYFCMNotification\n\ncred = credentials.Certificate(settings.FIREBASE_CONFIG_PATH)\nfirebase_admin.initialize_app(cred)\n\n\nclass FCMNotification:\n\n def __init__(self, title, message, token, notification_type=\"\", sound=True, image=\"\", pending=1, id=None):\n \"\"\"\n Initialise some default fields.\n \"\"\"\n self.push_service = PYFCMNotification(api_key=settings.FCM_KEY)\n self.title = title\n self.message = message\n self.token = token\n self.notification_type = notification_type\n self.play_sound = sound\n self.pending = pending\n self.object_id = id\n self.fcm_key = settings.FCM_KEY\n self.image = image\n\n def get_payload(self):\n \"\"\"\n Define payload-data by default fields.\n \"\"\"\n data = {\n \"type\": self.notification_type,\n \"details\": self.message,\n \"title\": self.title,\n \"message\": self.message,\n \"image\": self.image,\n \"object_id\": self.object_id,\n \"sound\": \"default\",\n \"notificationId\": str(uuid.uuid4()),\n \"show_in_foreground\": True,\n \"priority\": \"high\",\n \"actions\": \"com.w3gym\",\n \"color\": \"red\",\n \"autoCancel\": True,\n \"channelId\": \"fcm_FirebaseNotifiction_default_channel\",\n \"largeIcon\": \"ic_launcher\",\n \"lights\": True,\n \"icon\": \"ic_notif\",\n \"playSound\": self.play_sound,\n \"subText\": self.pending,\n \"vibrate\": self.play_sound,\n \"tag\": self.notification_type,\n \"group\": self.notification_type,\n \"groupSummary\": True,\n \"ongoing\": False,\n \"visibility\": \"private\",\n \"ignoreInForeground\": False,\n \"invokeApp\": True,\n \"subtitle\": self.pending,\n 'soundName': \"default\",\n 'number': 10,\n\n }\n return data\n\n def send_notification(self):\n \"\"\"\n Send notification to a single device through some default fields.\n \"\"\"\n data = self.get_payload()\n result = self.push_service.notify_single_device(\n registration_id=self.token,\n message_title=self.title,\n message_body=self.message,\n data_message=data,\n sound='default'\n )\n if not result.get('success'):\n # print(\"Error\", result, flush=True)\n getLogger().error(\"Error\", result)\n\n def send_bulk_notification(self, tokens):\n \"\"\"\n Send notification to multiple devices by providing clean-token ids\n through some default fields.\n \"\"\"\n tokens = self.push_service.clean_registration_ids(tokens)\n if tokens:\n data = self.get_payload()\n result = self.push_service.notify_multiple_devices(\n registration_ids=tokens,\n message_title=self.title,\n message_body=self.message,\n data_message=data,\n sound='default'\n )\n if not result.get('success'):\n # print(\"Error\", result, flush=True)\n getLogger().error(\"Error\", result)\n","repo_name":"Mohsin0348/demo-test","sub_path":"backend/fcm.py","file_name":"fcm.py","file_ext":"py","file_size_in_byte":3435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"15826177452","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 22 16:12:39 2018\n\n@author: Administrator\n\"\"\"\n\nimport cv2 \nfilepath = \"D:\\\\picture\\\\318394.jpg\" \nimg = cv2.imread(filepath) # 读取图片 \ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 转换灰色 \n# OpenCV人脸识别分类器 \nclassifier = cv2.CascadeClassifier( \"D:\\openvc\\haarcascade_frontalface_default.xml\" ) \ncolor = (0, 255, 0) # 定义绘制颜色 \n# 调用识别人脸 \nfaceRects = classifier.detectMultiScale( gray, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32)) \nif len(faceRects): # 大于0则检测到人脸 \n for faceRect in faceRects: # 单独框出每一张人脸 \n x, y, w, h = faceRect \n # 框出人脸 \n cv2.rectangle(img, (x, y), (x + h, y + w), color, 2) \n # 左眼 \n cv2.circle(img, (x + w // 4, y + h // 4 + 30), min(w // 8, h // 8), color) \n #右眼 \n cv2.circle(img, (x + 3 * w // 4, y + h // 4 + 30), min(w // 8, h // 8), color) \n #嘴巴 \n cv2.rectangle(img, (x + 3 * w // 8, y + 3 * h // 4), (x + 5 * w // 8, y + 7 * h // 8), color) \ncv2.imshow(\"image\", img) # 显示图像 \nc = cv2.waitKey(10) \ncv2.waitKey(0) \ncv2.destroyAllWindows()\n","repo_name":"Snailclimb/python","sub_path":"PythonSpider/openvcDemo2.py","file_name":"openvcDemo2.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","stars":241,"dataset":"github-code","pt":"40"} +{"seq_id":"21512786276","text":"import socket\nimport threading\nimport queue\nfrom typing import Optional\n\nfrom PyQt5.QtCore import QThread\n\nMAX_BUFFER = 20\n\n\nclass WebSender(QThread):\n def __init__(self, ip: str, port: int, log_updated: threading.Event):\n \"\"\"\n Initialize a WebSender object.\n\n Args:\n ip (str): The IP address of the server.\n port (int): The port number of the server.\n \"\"\"\n QThread.__init__(self)\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.sock.connect((ip, port))\n self.message_buffer = queue.Queue(maxsize=MAX_BUFFER)\n self.thread = threading.Thread(target=self._recv_thread, daemon=True)\n self.thread.start()\n self.log_updated = log_updated\n self.buffer_log = threading.Lock()\n\n def __del__(self):\n \"\"\"\n Close the socket when the WebSender object is deleted.\n \"\"\"\n self.sock.close()\n\n def _recv_thread(self):\n \"\"\"\n Internal thread function to receive data from the server and put it into the message buffer.\n \"\"\"\n while True:\n data = self.sock.recv(1024)\n if data:\n with self.buffer_log:\n self.message_buffer.put(data.decode())\n self.log_updated.set()\n\n def send_message(self, message: str):\n \"\"\"\n Send a message to the server.\n\n Args:\n message (str): The message to be sent.\n \"\"\"\n encoded_message = message.encode()\n self.sock.sendall(encoded_message)\n\n def get_log(self) -> Optional[str]:\n \"\"\"\n Get the log message from the message buffer.\n\n Returns:\n str: The log message. Returns None if the message buffer is empty.\n \"\"\"\n with self.buffer_log:\n if not self.message_buffer.empty():\n return self.message_buffer.get()\n","repo_name":"Khlff/python_tasks-project","sub_path":"client/src/main/python/web_sender.py","file_name":"web_sender.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"4280759409","text":"from django.conf import settings\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf.urls.static import static\nfrom django.conf.urls import handler404\n\nfrom posts.views import (\n index,\n search,\n blog,\n post,\n partners,\n post_create,\n post_update,\n post_delete,\n auth_accounts,\n contact,\n profile\n)\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', index, name='index'),\n path('blog/', blog, name='post-list'),\n path('search/', search, name='search'),\n path('waegahhadcaweg234dfsef/', post_create, name='post-create'),\n path('post//', post, name='post-detail'),\n path('post//wdaegahha_=ddcaweg23j4d$fsef/', post_update, name='post-update'),\n path('post//waegahhadcada2weg234dfsef/', post_delete, name='post-delete'),\n path('partners/', partners, name='partners'),\n path('contact/', contact, name='contact'),\n path('tinymce/', include('tinymce.urls')),\n\n path('accounts/', include('allauth.urls')),\n path('accounts/profile/', profile, name='profile'),\n\n # path('error/', page_404, name='page_404'),\n]\n\nhandler404 = 'posts.views.error_404_view'\n\n\nif settings.DEBUG:\n urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","repo_name":"funtixa/hodowla","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"70695499000","text":"with open('daySixteenInput.txt') as f:\n content = f.readlines()\ncontent = [x.strip() for x in content]\n\nrules = {}\nmyTicket = []\notherTickets = []\nrulesDone = False\nmyTicketDone = False\nfor line in content:\n if line == '':\n if not rulesDone:\n rulesDone = True\n else:\n myTicketDone = True\n elif not rulesDone:\n name, values = line.split(':')\n pairs = []\n for value in values.strip().split(' or '):\n pair = [int(x) for x in value.split('-')]\n pairs.append(pair)\n\n rules[name] = pairs\n\n elif rulesDone and not myTicketDone:\n if line != 'your ticket:':\n myTicket = [int(x) for x in line.split(',')]\n else:\n if line != 'nearby tickets:':\n otherTickets.append([int(x) for x in line.split(',')])\n\nticketsToPurge = []\ninvalidFieldTotal = 0\nfor i, ticket in enumerate(otherTickets):\n isInvalid = False\n for value in ticket:\n found = False\n for key in rules:\n for pair in rules[key]:\n if pair[0] <= value <= pair[1]:\n found = True\n if not found:\n invalidFieldTotal += value\n isInvalid = True\n\n if isInvalid:\n ticketsToPurge.insert(0, i) # make list backwards so its in right order to delete\n\nfor i in ticketsToPurge:\n del otherTickets[i]\n\nprint('part one sum of invalid fields: ', invalidFieldTotal)\n\nfieldDeclarations = {}\nnotFoundIndexesYet = list(range(0, len(otherTickets[0])))\nindexInListToCheck = 0\nrulesNotFound = list(rules.keys())\n\nwhile len(notFoundIndexesYet) != 0:\n index = notFoundIndexesYet[indexInListToCheck]\n possibleFields = rulesNotFound\n for ticket in otherTickets:\n newPossibleFields = []\n for rule in possibleFields:\n validForField = False\n for pair in rules[rule]:\n if pair[0] <= ticket[index] <= pair[1]:\n validForField = True\n\n if validForField:\n newPossibleFields.append(rule)\n\n possibleFields = newPossibleFields\n\n if len(possibleFields) == 1:\n fieldDeclarations[possibleFields[0]] = index\n notFoundIndexesYet.pop(indexInListToCheck)\n rulesNotFound.remove(possibleFields[0])\n indexInListToCheck = 0\n else:\n indexInListToCheck += 1\n\n\nmultipleOfDepartureFields = 1\nfor key in fieldDeclarations.keys():\n if key.startswith('departure'):\n multipleOfDepartureFields *= myTicket[fieldDeclarations[key]]\n\nprint('part two Multiple of departure fields:', multipleOfDepartureFields)\n","repo_name":"BrettGoreham/AdventOfCode2020","sub_path":"day16/daySixteen.py","file_name":"daySixteen.py","file_ext":"py","file_size_in_byte":2597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"34822728740","text":"n = int(input())\n\ngrid = []\nfor i in range(n):\n temp = list(map(int, input().split()))\n grid.append(temp)\n\ndef InRange(x, y):\n global n\n return (x>=0 and x=0 and y=4:\n c += 1\n if dic[i]>m:\n m = dic[i]\n\nprint(c, m)","repo_name":"yh-habosol/Algorithm","sub_path":"LeeBros/graph/뿌요뿌요.py","file_name":"뿌요뿌요.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"33068074173","text":"list=[]\ndata = {\n '中国':'北京',\n '韩国':'首尔',\n '日本':'东京',\n '泰国':'曼谷',\n '马来西亚':'吉隆坡',\n '越南':'河内',\n '朝鲜':'平壤',\n '印度':'新德里'\n }\nfor item in data:\n list.append([item,data.get(\"%s\"%(item)),\"aaa\"])\nprint(list)\nlist1=[]\nfor key,value in data.items(): \n list1.append([key,value,\"aaa\"])\nprint(list1)\n","repo_name":"aiiw/mypy","sub_path":"字典.py","file_name":"字典.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"5527956390","text":"\nfrom collections import Counter\nimport random\n\n# tested bigram probabilites with sentences from lecture slide\ntest_corpus_1 = '''\n I am Sam \n Sam I am \n I do not like green eggs and ham \n'''\n\nclass LanguageModel:\n\tdef __init__(self, file_path=None, smoothing=True,):\n\t\tif file_path:\n\t\t\tself.load_corpus(file_path)\n\t\telse:\n\t\t\tself.corpus = None\n\t\t\tself.words = None\n\t\t\tself.freqs = None\n\t\t\tself.numTokens = None\n\t\t\tself.prod = None\n\t\t\tself.bigrams = None\n\n\t\tself.smoothing = smoothing\n\n\tdef load_corpus(self, file_path):\n\t\tif file_path == 'test_corpus_1':\n\t\t\tself.corpus = test_corpus_1\n\t\telse:\n\t\t\twith open(file_path, \"r\") as infile:\n\t\t\t\tself.corpus = infile.read()\n\t\tself.words = self.corpus.split() # split corpus into words\n\t\tself.freqs = Counter(self.words) # count frequencies of words\n\t\tself.freqs[''] = 0 # add to the dictionary\n\n\t\tfor k, v in list(self.freqs.items()):\n\t\t\tif v == 1:\n\t\t\t\tself.freqs[''] += 1\t# increment the frequency of delete all tokens with a frequency of 1\n\t\t\t\tdel self.freqs[k]\n\n\t\tself.numTokens = sum(self.freqs.values())\n\t\n\tdef uniProb(self, word):\n\t\tif self.freqs and self.numTokens:\n\t\t\treturn self.freqs[word] / self.numTokens\n\n\tdef product(self, nums):\n\t\tprod = 1\n\t\tfor num in nums: \n\t\t\tprod = prod * num\n\t\treturn prod\n\n\tdef unigramModel(self, sentence):\n\t\tsentence = sentence.split()\n\t\tfor i in range(len(sentence)):\n\t\t\tif sentence[i] not in self.freqs:\n\t\t\t\tsentence[i] = ''\n\n\t\treturn self.product(self.uniProb(word) for word in sentence)\n\n\tdef bigramProb(self, bigram):\n\t\tif self.smoothing:\n\t\t\treturn (self.corpus.count('{} {}'.format(bigram[0], bigram[1])) + 1) / (self.corpus.count(bigram[0]) + len(self.freqs))\n\t\telse:\n\t\t\treturn self.corpus.count('{} {}'.format(bigram[0], bigram[1])) / self.corpus.count(bigram[0])\n\n\tdef bigramModel(self, sentence):\n\t\tsentence = sentence.split()\n\t\tfor i in range(len(sentence)-1):\n\t\t\tsentence[i] = (sentence[i], sentence[i+1])\n\t\tsentence.pop(-1)\n\t\treturn self.product(self.bigramProb(bigram) for bigram in sentence)\n\n\tdef shannon(self):\n\t\tstart = ''\n\t\tsentence = ''\n\t\twhile start != '':\n\t\t\tbigram_freqs = {}\n\t\t\tfor i in list(self.freqs.keys()):\n\t\t\t\tif i != '':\n\t\t\t\t\tbigram_freqs[(start,i)] = self.bigramProb((start,i)) # generate dict of all possible bigrams\n\t\t\t\n\t\t\ttotal = sum(bigram_freqs.values())\n\t\t\tfor i in bigram_freqs:\n\t\t\t\tbigram_freqs[i] /= total # normalize frequencies\n\n\t\t\tbigram = random.choices(list(bigram_freqs.keys()), list(bigram_freqs.values()))\n\t\t\t\n\t\t\tsentence += bigram[0][0] + ' '\n\t\t\t\n\t\t\tstart = bigram[0][1]\n\n\t\tsentence += start\n\t\treturn sentence\n\n\n\ndef main():\n\tLM = LanguageModel('berp-training.txt')\n\n\twith open('berp-100-test.txt', \"r\") as infile:\n\t\t\t\ttest_corpus = infile.read()\n\n\twith open(\"Thomas-Derek-assgn2-unigram-out.txt\", \"wt\") as outfile:\n\t\t\t\tfor i in test_corpus.split('\\n'):\n\t\t\t\t\toutfile.write(str(LM.unigramModel(i))+'\\n')\n\twith open(\"Thomas-Derek-assgn2-bigram-out.txt\", \"wt\") as outfile:\n\t\t\t\tfor i in test_corpus.split('\\n'):\n\t\t\t\t\toutfile.write(str(LM.bigramModel(i))+'\\n')\n\twith open(\"Thomas-Derek-assgn2-bigram-rand-corpus.txt\", \"a\") as outfile:\n\t\t\t\tfor i in range(89):\n\t\t\t\t\toutfile.write(LM.shannon()+'\\n')\n\n\t\n\nif __name__ == '__main__':\n\tmain()","repo_name":"Sisyphus192/CSCI-3832","sub_path":"Thomas-Derek-assgn2.py","file_name":"Thomas-Derek-assgn2.py","file_ext":"py","file_size_in_byte":3223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"18930391654","text":"from cStringIO import StringIO\r\nfrom pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter\r\nfrom pdfminer.converter import TextConverter\r\nfrom pdfminer.layout import LAParams\r\nfrom pdfminer.pdfpage import PDFPage\r\nimport os\r\nimport os.path\r\nimport sys, getopt\r\nfrom pprint import pprint\r\nimport re\r\n\r\nMIN_RANGE_SIZE = 100\r\n\r\nerrors = []\r\nemptyTxt = []\r\n\r\nendMarks = [\".\", \"?\", \"!\"]\r\nhasNoAbstract = []\r\nhasNoReference = []\r\nhasNoRange = []\r\ninASCII = []\r\nMAX_LENGTH = 196\r\n#converts pdf, returns its text content as a string\r\n#from https://www.binpress.com/tutorial/manipulating-pdfs-with-python/167\r\ndef convert(fname, pages=None):\r\n try:\r\n if not pages:\r\n pagenums = set()\r\n else:\r\n pagenums = set(pages)\r\n\r\n output = StringIO()\r\n manager = PDFResourceManager()\r\n converter = TextConverter(manager, output, laparams=LAParams())\r\n interpreter = PDFPageInterpreter(manager, converter)\r\n\r\n infile = file(fname, 'rb')\r\n for page in PDFPage.get_pages(infile, pagenums):\r\n interpreter.process_page(page)\r\n infile.close()\r\n converter.close()\r\n text = output.getvalue()\r\n output.close\r\n return text\r\n except Exception as err:\r\n errors.append((fname, err))\r\n return None\r\n\r\n#converts all pdfs in directory pdfDir, saves all resulting txt files to txtdir\r\ndef convertMultiple(pdfDir, txtDir):\r\n if pdfDir == \"\": pdfDir = os.getcwd() + \"\\\\\" #if no pdfDir passed in\r\n for pdf in os.listdir(pdfDir): #iterate through pdfs in pdf directory\r\n fileExtension = pdf.split(\".\")[-1]\r\n if fileExtension == \"pdf\":\r\n pdfFilename = pdfDir + '/' + pdf\r\n textFilename = txtDir + '/' + pdf + \".txt\"\r\n if not os.path.isfile(textFilename):\r\n text = convert(pdfFilename) #get string of text content of pdf\r\n if not text is None:\r\n textFile = open(textFilename, \"w\") #make text file\r\n textFile.write(text) #write text to text file\r\n\r\ndef findRange(content):\r\n start = 0\r\n end = len(content)\r\n for index, line in enumerate(content):\r\n if \"ABSTRACT\" in line.replace(' ','').upper() or \"PURPOSE\" in line.replace(' ', '').upper() or \"INTRODUCTION\" in line.replace(' ', '').upper():\r\n start = index\r\n break\r\n for index, line in enumerate(content):\r\n if (\"ACKNOWLEDGMENTS\" in line.replace(' ', '').upper() or \"REFERENCES\" in line.replace(' ', '').upper()) and index > start:\r\n end = index\r\n return start, end\r\n\r\ndef isASCII(content):\r\n return content[0][:5] == '(cid:'\r\n\r\ndef convertASCII(content):\r\n converted = []\r\n # print(content)\r\n for line in content:\r\n converted_l = ''\r\n for c in re.compile('(cid:[0-9]+)').split(line):\r\n if c[:3] == 'cid':\r\n converted_l += chr(int(c[4:]))\r\n elif c == ') (':\r\n converted_l += ' '\r\n # elif c == '\\n':\r\n # converted_l += '\\n'\r\n # if c[:3] == 'cid':\r\n # converted_l += str(chr(int(c[4:])))\r\n # elif c == ' ':# or c == '\\n':\r\n # converted_l += str(c)\r\n converted_l += '\\n'\r\n converted.append(converted_l)\r\n return converted\r\n\r\ndef convertContent(content, start, end):\r\n converted = []\r\n sentence = \"\"\r\n for i in range(start, end):\r\n line = content[i]\r\n if len(line) > 0 and line[len(line)-1] == '.':\r\n line += ' '\r\n\r\n parts = [p+'.' for p in line.split('. ') if p]\r\n if len(parts) > 0 and line[len(line)-2:len(line)-1] != '. ':\r\n parts[len(parts)-1] = parts[len(parts)-1][:len(parts[len(parts)-1])-1]\r\n\r\n for part in parts:\r\n if len(sentence) == 0: # start new sentence\r\n sentence = part\r\n else:\r\n sentence += part\r\n if part[len(part)-1] == '.':\r\n if len(sentence.split(' ')) < MAX_LENGTH:\r\n converted.append(sentence)\r\n sentence = \"\"\r\n if len(sentence) > 0:\r\n # sentence is not finished at the end of the line\r\n sentence += ' '\r\n return converted\r\n\r\ndef formatText(filename):\r\n try:\r\n formattedText = \"\"\r\n f = open(filename)\r\n content = f.readlines()\r\n\r\n if len(content) == 0:\r\n emptyTxt.append(filename)\r\n return None\r\n\r\n if isASCII(content):\r\n inASCII.append(filename)\r\n content = convertASCII(content)\r\n\r\n content = filter(lambda a: a != '\\n', content) # remove blank lines\r\n content = [line[:len(line)-1] for line in content]\r\n\r\n\r\n sentence = \"\"\r\n start, end = findRange(content)\r\n if start == 0:\r\n hasNoAbstract.append(filename)\r\n if end == len(content):\r\n hasNoReference.append(filename)\r\n if end-start+1 > MIN_RANGE_SIZE:\r\n # print((start, end, content[start], content[end]))\r\n content = convertContent(content, start, end)\r\n formattedText = '\\n'.join(content)\r\n # print(filename)\r\n else:\r\n hasNoRange.append((filename, start, end))\r\n return None\r\n # if (start == 3459):\r\n # print(filename)\r\n # print((start, end, content[start], content[end-1]))\r\n\r\n # for line in content:\r\n # for part in line.split(\". \"):\r\n # print(part)\r\n # print(\"=======\")\r\n # if sentence == \"\": # start new sentence\r\n #\r\n # if \"ABSTRACT\" in line:\r\n # hasAbstract.append(filename)\r\n # break\r\n\r\n return formattedText\r\n except Exception as err:\r\n errors.append((filename, err))\r\n # print(filename)\r\n raise err\r\n return None\r\n\r\ndef formatMultiple(txtDir, formattedDir):\r\n global MAX_LENGTH\r\n # i = 0\r\n if txtDir == \"\": txtDir = os.getcwd() + \"\\\\\" #if no txtDir passed in\r\n for file in os.listdir(txtDir): #iterate through text files in txt directory\r\n fileExtension = file.split(\".\")[-1]\r\n if fileExtension == \"txt\":\r\n filename = txtDir + '/' + file\r\n formatname = formattedDir + '/' + file + '.txt'\r\n if not os.path.isfile(formatname):\r\n text = formatText(filename) #get string of text content of file\r\n if not text is None:\r\n textFile = open(formatname, \"w\") #make text file\r\n textFile.write(text) #write text to text file\r\n # i+=1\r\n # if i == 3:\r\n # break\r\n\r\n\r\n#i : info\r\n#p : pdfDir\r\n#t = txtDir\r\ndef main(argv):\r\n pdfDir = \"\"\r\n txtDir = \"\"\r\n formattedDir = \"\"\r\n try:\r\n opts, args = getopt.getopt(argv,\"ip:t:f:\")\r\n except getopt.GetoptError:\r\n print(\"pdfToT.py -p -t -f \")\r\n sys.exit(2)\r\n for opt, arg in opts:\r\n if opt == \"-i\":\r\n print(\"pdfToT.py -p -t -f \")\r\n sys.exit()\r\n elif opt == \"-p\":\r\n pdfDir = arg\r\n elif opt == \"-t\":\r\n txtDir = arg\r\n elif opt == \"-f\":\r\n formattedDir = arg\r\n convertMultiple(pdfDir, txtDir)\r\n print('Convert to PDF - Errors for : ')\r\n pprint(errors)\r\n formatMultiple(txtDir, formattedDir)\r\n print(\"=====\")\r\n print('Empty Texts are :')\r\n pprint(emptyTxt)\r\n print(\"=====\")\r\n print(\"Files without abstract :\")\r\n pprint(hasNoAbstract)\r\n print(\"=====\")\r\n print(\"Files without reference :\")\r\n pprint(hasNoReference)\r\n print(\"=====\")\r\n print(\"Files without range :\")\r\n pprint(hasNoRange)\r\n print(\"=====\")\r\n print(\"Files in ASCII :\")\r\n pprint(inASCII)\r\n print(\"Longest sentence : \" + str(MAX_LENGTH))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main(sys.argv[1:])\r\n","repo_name":"bastienvanderplaetse/qas-for-dida","sub_path":"pdfconverter/pToT.py","file_name":"pToT.py","file_ext":"py","file_size_in_byte":8038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"41528516757","text":"\"\"\"\n\n이 코드는 정확성은 다 맞으나 효율성에서 시간 초과가 발생했다... 쉽다고 생각해서 제한사항을 읽어보지도 않고 풀었다.. info의 배열의 크기가 1<=size<=50000 이기에 시간초과를 생각하고 풀어야했다... 아직 초보라 그런가 시간을 단축시킬 방법으 떠오르지 않았다.. 카카오 기술블로그와 다른 브로그를 보고 풀었다..\ninfo에 대한 모든 조합을 만들어준다. ex) java , javabackend, javabackendjunior ...로 16가지의 경우의 수가 만들어진다. -를 고려하는 경우 따로 '-' 를 넣어주지 않고 info조건을 모아 key를 만듬. ex) python - junior pizza -> pyhonjuniorpizza로 변경해 준다. info를 통해 만들어진 조합을 map에 key로하고 value를 info에 score값으로 해준다. 이제 해당 map에 있는 정보와 query조건이 일치하는 경우 query스코어보다 높은 점수의 지원자가 몇명인지 구한다(lower_bound(이진탐색이용))\n\n\nimport re\ndef solution(info, query):\n answer = []\n infoList = []\n queryList = []\n # 정보\n for i in info:\n infoList.append(i.split(\" \"))\n # 검색조건\n for i in query:\n reg = re.findall('\\d+|\\w+|[-]+',i)\n for j in reg:\n if j == 'and':\n reg.remove(j)\n queryList.append(reg)\n cc = 0\n for i in queryList:\n print(i)\n for j in infoList:\n cnt = 0\n for k in range(len(infoList[0])):\n # 숫자 체크\n regNum = re.findall('\\d+',j[k])\n if j[k] == i[k]:\n cnt +=1 \n elif i[k] == '-':\n cnt+=1\n elif regNum:\n if int(j[k]) >= int(i[k]):\n cnt+=1\n if cnt == len(infoList[0]):\n cc +=1\n answer.append(cc)\n cc = 0\n return answer\n\n\"\"\"\nfrom itertools import combinations\nimport re\ndef solution(info, query):\n answer = []\n ret = []\n map = {}\n for i in info:\n infoList = i.split( )\n key = infoList[:-1]\n score = int(infoList[-1])\n for j in range(5):\n for c in combinations(key,j): # info들의 조합을 뽑는다(ex java, javabackend ... )\n tmp = ''.join(c)\n if tmp in map:\n map[tmp].append(score) # map에 해당 score를 넣는다\n else:\n map[tmp] = [score]\n for k in map:\n map[k].sort() # dict안의 조합들을 점수순으로 정렬\n \n # 쿼리정보도 똑같이 분리해준다.\n for i in query:\n queryList = i.split(' ')\n scoreQ = int(queryList[-1])\n queryList = queryList[:-1]\n while 'and' in queryList:\n queryList.remove('and')\n while '-' in queryList:\n queryList.remove('-')\n key = \"\".join(queryList)\n if key in map: #info의 조합이 key인 map에 쿼리정보가 있다면 \n scores = map[key] # 스코어를 가져온다.\n if len(scores) > 0: # lower_bound\n start, end = 0, len(scores)\n # 정렬된 배열에서 찾고자하는 값 이상이 처음 나타나는 위치 찾기\n while start < end: #start와 end가 만나는 지점이 target값 이상이 처음 나오는 위치\n mid = (start+end) // 2\n if scores[mid] >= scoreQ:\n end = mid\n else:\n start = mid+1\n answer.append(len(scores)- start)\n else:\n answer.append(0)\n\n return answer\n","repo_name":"beomsun1234/TIL","sub_path":"algorithm/programmers/level2/2021 카카오 블라인드 - 순위검색.py","file_name":"2021 카카오 블라인드 - 순위검색.py","file_ext":"py","file_size_in_byte":3698,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"31947586796","text":"import cv2\nimport os\n\n\ni = 7000\npath = os.path.dirname(os.path.abspath(__file__))\ncap = cv2.VideoCapture(0)\n\nwhile True:\n ret1, frame = cap.read()\n cv2.imshow('window', frame)\n i += 1\n\n if cv2.waitKey(1) & 0xFF == ord('p'):\n cv2.imwrite(path + '/' + str(i) + '.jpg', frame)\n i += 1\n\n key = cv2.waitKey(1) # pauses for 3 seconds before fetching next image\n if key == 27: # if ESC is pressed, exit loop\n cv2.destroyAllWindows()\n cap.relase()\n break\n\n'''\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\ncv2.destroyAllWindows()\ncap.release()'''","repo_name":"gosikora/Gesture","sub_path":"save_photo.py","file_name":"save_photo.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"35152912786","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport contextlib\n\nfrom adanet.autoensemble.estimator import AutoEnsembleEstimator\nfrom adanet.core.estimator import Estimator\nfrom adanet.distributed.placement import RoundRobinStrategy\nfrom adanet.subnetwork import Builder\nfrom adanet.subnetwork import SimpleGenerator\nfrom adanet.subnetwork import Subnetwork\nfrom distutils.version import LooseVersion\nimport tensorflow as tf\n\n# pylint: disable=g-direct-tensorflow-import\nfrom tensorflow.python.training import session_manager as session_manager_lib\n\n# Module path changed. Try importing from new and old location to maintain\n# backwards compatibility.\n# pylint: disable=g-import-not-at-top\ntry:\n from tensorflow_estimator.python.estimator import training as training_lib\nexcept ImportError:\n from tensorflow.python.estimator import training as training_lib\n# pylint: enable=g-import-not-at-top\n# pylint: enable=g-direct-tensorflow-import\n\ntf.flags.DEFINE_enum(\"estimator_type\", \"estimator\", [\n \"estimator\",\n \"autoensemble\",\n], \"The estimator type to train.\")\n\ntf.flags.DEFINE_enum(\"placement_strategy\", \"replication\", [\n \"replication\",\n \"round_robin\",\n], \"The distributed placement strategy.\")\n\ntf.flags.DEFINE_string(\"model_dir\", \"\", \"The model directory.\")\n\nFLAGS = tf.flags.FLAGS\n\n\nclass SessionManager(session_manager_lib.SessionManager):\n \"\"\"A session manager with a shorter recovery time.\"\"\"\n\n def __init__(self,\n local_init_op=None,\n ready_op=None,\n ready_for_local_init_op=None,\n graph=None,\n recovery_wait_secs=None,\n local_init_run_options=None):\n # Reduced wait time.\n super(SessionManager, self).__init__(\n local_init_op,\n ready_op,\n ready_for_local_init_op,\n graph,\n recovery_wait_secs=.5,\n local_init_run_options=local_init_run_options)\n\n\n@contextlib.contextmanager\ndef _monkey_patch_distributed_training_times():\n \"\"\"Monkey-patches global attributes with subnetwork-specifics ones.\"\"\"\n\n old_delay_secs_per_worker = training_lib._DELAY_SECS_PER_WORKER # pylint: disable=protected-access\n old_session_manager = session_manager_lib.SessionManager\n\n # monkey-patch global attributes.\n session_manager_lib.SessionManager = SessionManager\n # Override default delay per worker to speed up tests.\n training_lib._DELAY_SECS_PER_WORKER = .2 # pylint: disable=protected-access\n\n try:\n yield\n finally:\n # Revert monkey-patches.\n session_manager_lib.SessionManager = old_session_manager\n training_lib._DELAY_SECS_PER_WORKER = old_delay_secs_per_worker # pylint: disable=protected-access\n\n\nclass _DNNBuilder(Builder):\n \"\"\"A simple DNN subnetwork builder.\"\"\"\n\n def __init__(self, name, config, layer_size=3, seed=13):\n self._name = name\n self._layer_size = layer_size\n self._config = config\n self._seed = seed\n\n @property\n def name(self):\n return self._name\n\n def build_subnetwork(self,\n features,\n logits_dimension,\n training,\n iteration_step,\n summary,\n previous_ensemble=None):\n seed = self._seed\n if previous_ensemble:\n # Increment seed so different iterations don't learn the exact same thing.\n seed += 1\n num_ps_replicas = self._config.num_ps_replicas if self._config else 0\n partitioner = tf.min_max_variable_partitioner(\n max_partitions=num_ps_replicas)\n with tf.variable_scope(\"dnn\", partitioner=partitioner):\n shared = {}\n with tf.variable_scope(\"hidden_layer\"):\n w = tf.get_variable(\n shape=[2, self._layer_size],\n initializer=tf.glorot_uniform_initializer(seed=seed),\n name=\"weight\")\n hidden_layer = tf.matmul(features[\"x\"], w)\n\n if previous_ensemble:\n other_hidden_layer = previous_ensemble.weighted_subnetworks[\n -1].subnetwork.shared[\"hidden_layer\"]\n hidden_layer = tf.concat([hidden_layer, other_hidden_layer], axis=1)\n\n # Use a leaky-relu activation so that gradients can flow even when\n # outputs are negative. Leaky relu has a non-zero slope when x < 0.\n # Otherwise success at learning is completely dependent on random seed.\n hidden_layer = tf.nn.leaky_relu(hidden_layer, alpha=.2)\n shared[\"hidden_layer\"] = hidden_layer\n\n with tf.variable_scope(\"logits\"):\n logits = tf.layers.dense(\n hidden_layer,\n logits_dimension,\n kernel_initializer=tf.glorot_uniform_initializer(seed=seed))\n\n summary.scalar(\"scalar\", 3)\n\n return Subnetwork(\n last_layer=logits, logits=logits, complexity=3, shared=shared)\n\n def build_subnetwork_train_op(self, subnetwork, loss, var_list, labels,\n iteration_step, summary, previous_ensemble):\n optimizer = tf.train.AdamOptimizer(learning_rate=.001)\n return optimizer.minimize(loss, var_list=var_list)\n\n\ndef train_and_evaluate_estimator():\n \"\"\"Runs Estimator distributed training.\"\"\"\n\n # The tf.estimator.RunConfig automatically parses the TF_CONFIG environment\n # variables during construction.\n # For more information on how tf.estimator.RunConfig uses TF_CONFIG, see\n # https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig.\n config = tf.estimator.RunConfig(\n tf_random_seed=42,\n model_dir=FLAGS.model_dir,\n session_config=tf.ConfigProto(\n log_device_placement=False,\n # Ignore other workers; only talk to parameter servers.\n # Otherwise, when a chief/worker terminates, the others will hang.\n device_filters=[\"/job:ps\"]))\n head = tf.contrib.estimator.regression_head(\n loss_reduction=tf.losses.Reduction.SUM_OVER_BATCH_SIZE)\n\n kwargs = {\n \"max_iteration_steps\": 100,\n \"force_grow\": True,\n \"delay_secs_per_worker\": .2,\n \"max_worker_delay_secs\": 1,\n \"worker_wait_secs\": .5,\n # Set low timeout to reduce wait time for failures.\n \"worker_wait_timeout_secs\": 60,\n \"config\": config\n }\n if FLAGS.placement_strategy == \"round_robin\":\n kwargs[\"experimental_placement_strategy\"] = RoundRobinStrategy()\n if FLAGS.estimator_type == \"autoensemble\":\n feature_columns = [tf.feature_column.numeric_column(\"x\", shape=[2])]\n if hasattr(tf.estimator, \"LinearEstimator\"):\n linear_estimator_fn = tf.estimator.LinearEstimator\n else:\n linear_estimator_fn = tf.contrib.estimator.LinearEstimator\n if hasattr(tf.estimator, \"DNNEstimator\"):\n dnn_estimator_fn = tf.estimator.DNNEstimator\n else:\n dnn_estimator_fn = tf.contrib.estimator.DNNEstimator\n candidate_pool = {\n \"linear\":\n linear_estimator_fn(\n head=head,\n feature_columns=feature_columns,\n optimizer=tf.train.AdamOptimizer(learning_rate=.001)),\n \"dnn\":\n dnn_estimator_fn(\n head=head,\n feature_columns=feature_columns,\n optimizer=tf.train.AdamOptimizer(learning_rate=.001),\n hidden_units=[3]),\n \"dnn2\":\n dnn_estimator_fn(\n head=head,\n feature_columns=feature_columns,\n optimizer=tf.train.AdamOptimizer(learning_rate=.001),\n hidden_units=[5])\n }\n\n estimator = AutoEnsembleEstimator(\n head=head, candidate_pool=candidate_pool, **kwargs)\n\n elif FLAGS.estimator_type == \"estimator\":\n subnetwork_generator = SimpleGenerator([\n _DNNBuilder(\"dnn1\", config, layer_size=3),\n _DNNBuilder(\"dnn2\", config, layer_size=4),\n _DNNBuilder(\"dnn3\", config, layer_size=5),\n ])\n\n estimator = Estimator(\n head=head, subnetwork_generator=subnetwork_generator, **kwargs)\n\n def input_fn():\n xor_features = [[1., 0.], [0., 0], [0., 1.], [1., 1.]]\n xor_labels = [[1.], [0.], [1.], [0.]]\n input_features = {\"x\": tf.constant(xor_features, name=\"x\")}\n input_labels = tf.constant(xor_labels, name=\"y\")\n return input_features, input_labels\n\n train_hooks = []\n # ProfilerHook raises the following error in older TensorFlow versions:\n # ValueError: The provided tag was already used for this event type.\n if LooseVersion(tf.VERSION) >= LooseVersion(\"1.13.0\"):\n train_hooks = [\n tf.train.ProfilerHook(save_steps=50, output_dir=FLAGS.model_dir)\n ]\n # Train for three iterations.\n train_spec = tf.estimator.TrainSpec(\n input_fn=input_fn, max_steps=300, hooks=train_hooks)\n eval_spec = tf.estimator.EvalSpec(\n input_fn=input_fn, steps=1, start_delay_secs=.5, throttle_secs=.5)\n\n # Calling train_and_evaluate is the official way to perform distributed\n # training with an Estimator. Calling Estimator#train directly results\n # in an error when the TF_CONFIG is setup for a cluster.\n tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)\n\n\ndef main(unused_argv):\n # Reduce hard-coded waits, delays, and timeouts for quicker tests.\n with _monkey_patch_distributed_training_times():\n train_and_evaluate_estimator()\n\n\nif __name__ == \"__main__\":\n tf.app.run()\n","repo_name":"remyaem/adanet","sub_path":"adanet/core/estimator_distributed_test_runner.py","file_name":"estimator_distributed_test_runner.py","file_ext":"py","file_size_in_byte":9224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"40"} +{"seq_id":"32618279120","text":"import numpy as np\nimport imutils\nimport cv2\nimport os\nfrom flask import flash\n\nclass FaceObject:\n \n def __init__(self):\n self.haar_file = 'haarcascade_frontalface_default.xml'\n self.face_detector = cv2.CascadeClassifier(self.haar_file)\n self.face_recognizer = cv2.face.LBPHFaceRecognizer_create()\n self.names = {}\n self.train()\n\n def detect_face(self,image):\n faces = self.face_detector.detectMultiScale(image)\n\n if len(faces) == 0:\n return None\n\n return faces\n\n def train(self):\n\n (images, labels, id) = ([], [], 0)\n datasets = 'datasets'\n for (subdirs, dirs, files) in os.walk(datasets):\n for subdir in dirs:\n self.names[id] = subdir\n subjectpath = os.path.join(datasets, subdir)\n for filename in os.listdir(subjectpath):\n path = subjectpath + '/' + filename\n lable = id\n images.append(cv2.imread(path, 0))\n labels.append(int(lable))\n id += 1\n\n\n (images,labels) = [np.array(lis) for lis in [images,labels]]\n self.face_recognizer.train(images,labels)\n\n def recognize(self,image):\n \n prediction,confidence = self.face_recognizer.predict(image)\n\n if confidence < 100:\n return self.names[prediction]\n \n return None\n\ndef allowed_file(filename, allowed_set):\n\n check = '.' in filename and filename.rsplit('.',1)[1].lower() in allowed_set\n\n return check\n\ndef remove_file_extension(filename):\n filename = os.path.splitext(filename)[0]\n\n return filename\n\ndef save_image(img, filename, uploads_path):\n try:\n cv2.imwrite(os.path.join(uploads_path, filename), img)\n flash('Image saved')\n except Exception as e:\n print(str(e))\n return str(e)\n \n","repo_name":"rameez471/LBP-Web-App","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"3315961322","text":"import os\nimport pickle\n\nimport numpy\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import OneHotEncoder\n\n# Higher verbose level = more detailed logging\nimport tinyml\nfrom tinyml.core import Backend as np\nfrom tinyml.learner import Learner\nfrom tinyml.learner.callbacks import (evaluate_classification_accuracy,\n save_model)\nfrom tinyml.losses import cross_entropy_with_softmax_loss\nfrom tinyml.models.tinyvgg16 import tinyvgg16\nfrom tinyml.optims import SGDOptimizer\n\nGPU = True\n\nif GPU:\n os.environ['TNN_GPU'] = \"True\"\n\ntinyml.utilities.logger.VERBOSE = 1\n\n\ndef load_data(filepath):\n with open(filepath, 'rb') as f:\n cat_dog_data = pickle.load(f)\n x_train = cat_dog_data['train']['data']\n y_train = cat_dog_data['train']['label']\n idx = numpy.random.permutation(len(x_train))\n x_train, y_train = numpy.asarray(x_train)[idx] / 255., numpy.asarray(\n y_train)[idx] / 255.\n x_test = cat_dog_data['test']['data']\n y_test = cat_dog_data['test']['label']\n return x_train, y_train, numpy.asarray(x_test), numpy.asarray(y_test)\n\n\ndef get_accuracy(y_predict, y_true):\n return np.mean(\n np.equal(np.argmax(y_predict, axis=-1), np.argmax(y_true, axis=-1)))\n\n\nx_train, y_train, x_test, y_test = load_data(\"./dataset/tinyimagenet.pkl\")\n\nprint(y_train.shape)\nprint(x_train.shape)\n\nif GPU:\n import cupy as cp\n x_train = cp.array(x_train)\n y_train = cp.array(y_train)\n x_test = cp.array(x_test)\n y_test = cp.array(y_test)\n\nmodel = tinyvgg16()\nmodel.summary()\ncallbacks = [evaluate_classification_accuracy, save_model]\ncargs = (x_test, y_test)\n\nlearner = Learner(model, cross_entropy_with_softmax_loss,\n SGDOptimizer(lr=0.01, momentum=0.9))\n\nTRAIN = True\n\nprint('starting training...')\n\nif TRAIN:\n learner.fit(x_train,\n y_train,\n epochs=50,\n batch_size=20,\n callbacks=callbacks,\n callbacks_interval=1,\n cargs=cargs)\n model.export('tinyimagenet.tnn')\n\nelse:\n model.load('tinyimagenet.tnn')\n\nprint('starting evaluating...')\n\ny_predict = learner.predict(x_test, batch_size=1)\n\nacc = get_accuracy(y_predict, y_test)\nprint('Testing Accuracy: {}%'.format(acc * 100))\n","repo_name":"autoai-org/Tinyml","sub_path":"examples/tiny_imagenet_cnn.py","file_name":"tiny_imagenet_cnn.py","file_ext":"py","file_size_in_byte":2330,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"40"} +{"seq_id":"8704375486","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Desafios da aula03\n\n# In[1]:\n\n\n# Importando as bibliotecas necessárias\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nimport warnings\nwarnings.simplefilter(\"ignore\")\n\n# Baixando a base de dados\nimdb = pd.read_csv(\"https://raw.githubusercontent.com/ViniViniAntunes/QuarentenaDados/master/datasets/microdados_enem/movie_metadata.csv\")\n\n# Configurando o estilo dos gráficos\nsns.set_style(\"whitegrid\")\n\n\n# # Desafio 1\n# \n# Plotar e analisar o Boxplot da média (coluna imbd_score) dos filmes em preto e branco e coloridos.\n\n# In[2]:\n\n\n# Selecionando os dados\ncolor_or_bw = imdb.query(\"color in ['Color', ' Black and White']\")\ncolor_or_bw[\"color_0_or_1\"] = (color_or_bw[\"color\"]==\"Color\") * 1\ncolor_or_bw[\"color_0_or_1\"].value_counts()\ncolor_or_bw.groupby(\"color\").median()[\"imdb_score\"]\n\n# Tamanho da figura\nplt.figure(figsize=(15, 8))\n\n# Plotando o gráfico boxplot com a seaborn\nsns.boxplot(data=color_or_bw.query(\"color_0_or_1 in [0,1]\"), \n x='color_0_or_1', y='imdb_score', \n palette=sns.color_palette(\"colorblind\")\n ).set_xticklabels(labels=[\"Preto e Branco\", \"Colorido\"])\n\n# Definindo o título\nplt.title('Avaliação dos filmes por cor', fontsize=20)\n\n# Definindo o eixo horizontal\nplt.xlabel(\"Cor do filme\", fontsize=18)\n\n# Definindo o eixo vertical\nplt.ylabel(\"Avaliação\", fontsize=18)\n\n# Rotacionando os gêneros em 45°\nplt.xticks(fontsize=12)\n\nplt.show();\n\n\n# Filmes em Preto e Branco têm, em média, avaliações maiores que filmes Coloridos. Por serem filmes mais antigos ou mais conceituais/cults, o seu público é menor. Com menos avaliações, mais provável aparecerem um maior número de notas altas.\n\n# # Desafio 2 \n# Descubra qual é o filme em nosso dataset com o maior prejuízo.\n\n# Para resolver esse desafio, criei uma coluna \"lucro\" com os valores de faturamento bruto (\"gross\") menos as despesas (\"budget\"). Depois ordenei em ordem crescente e selecionei o primeiro (o menor lucro).\n\n# In[3]:\n\n\n# Fazendo uma cópia do DataFrame\nimdb_copia = imdb.copy()\n\n# Retirando os valores duplicados\nimdb_copia = imdb_copia.drop_duplicates()\n\n# Selecionando somente os filmes americanos para que o budget e o gross não sejam influenciados por valores em outras moedas\nimdb_usa = imdb_copia.query(\"country == 'USA'\")\n\n# Criando uma coluna para o lucro dos filmes\nimdb_usa['lucro'] = imdb_usa['gross'] - imdb_usa['budget']\n\n# Selecionando o filme com maior prejuízo\nfilme_com_maior_prejuizo = imdb_usa[['movie_title', 'lucro']].sort_values(by='lucro').head(1)\n\n# Limpando a string com o nome do filme e armazenando em uma variável\nnome = filme_com_maior_prejuizo['movie_title'].values[0].split('\\xa0')[0]\n\n# Armazenando em uma variável o valor absoluto do lucro (lucro negativo = prejuízo)\nprejuizo = abs(filme_com_maior_prejuizo['lucro'].values[0].round(2))\n\n# Mostrando o nome do filme com o maior prejuízo\nprint(f'O filme com maior prejuízo foi {nome} com um prejuízo de U$ {prejuizo}')\n\n\n# # Desafio 3\n# Em aula falamos que talvez, filmes mais recentes podem ter prejuizo pois ainda não tiveram tempo de recuperar o investimento. Analise essas informações e nos conte quais foram suas conclusões.\n\n# In[4]:\n\n\n# Selecionando os filmes sem lucro\nfilmes_sem_lucro = imdb_usa[['title_year', 'lucro']].query('lucro <= 0')\n\n# Selecionando os filmes com lucro\nfilmes_com_lucro = imdb_usa[['title_year', 'lucro']].query('lucro > 0')\n\n# Tamanho da figura\nplt.figure(figsize=(15, 8))\n\n# Plotando o gráfico boxplot com a seaborn\nsns.scatterplot(x=\"title_year\", y=\"lucro\", data = filmes_sem_lucro,\n color='#F35F58')\n\nsns.scatterplot(x=\"title_year\", y=\"lucro\", data = filmes_com_lucro,\n color='#54B754')\n\n# Definindo o título\nplt.title('Lucro/prejuízo (U$) dos filmes americanos por ano de lançamento', fontsize=20)\n\n# Definindo o eixo horizontal\nplt.xlabel(\"Ano de lançamento\", fontsize=18)\n\n# Definindo o eixo vertical\nplt.ylabel(\"Lucro/Prejuízo\", fontsize=18)\n\n# Configurando o tamanho com ticks\nplt.xticks(fontsize=12)\nplt.yticks(fontsize=12)\n\n# Configurando a legenda (?)\n#plt.legend(loc='upper left')\n\nplt.show();\n\n\n# Os maiores prejuizos aconteceram nos filmes mais recentes.\n# \n\n# # Desafio 4\n# Quais foram os filmes da decada pré 2° guerra que tiveram muito lucro.\n\n# In[5]:\n\n\n# Selecionando os filmes da década pré-guerra\nfilmes_pre_guerra = imdb_usa.query('title_year < 1940')\n\n# Mostrando os top 2 filmes antes de 2ª guerra com maior lucro\nfilmes_pre_guerra[['movie_title', 'lucro']].sort_values(by='lucro', ascending=False).head(2)\n\n\n# # Desafio 5 \n# \n# No gráfico de **\"filmes_irmaos por faturamento bruto\"** temos alguns pontos estranhos entre 15 e 20. Descubra quem é o diretor \n\n# In[6]:\n\n\n# Contando quantos \"filmes-irmãos\" para cada filme (entende-se \"filmes-irmãos\" como sendo filmes feitos pelo mesmo diretor)\nfilmes_por_diretor = imdb_usa['director_name'].value_counts()\n\n# Juntando faturamento e a quantidade de filmes para cada diretor\ngross_director = imdb_usa[['director_name', 'gross']].set_index('director_name').join(filmes_por_diretor, on='director_name')\n\n# Renomeando a colunas\ngross_director.columns = ['faturamento', 'filmes_irmaos']\n\n# Tamanho da figura\nplt.figure(figsize=(15, 8))\n\n# Plotando o gráfico faturamento (U$) por \"filmes-irmãos\" com a seaborn\nsns.scatterplot(x='filmes_irmaos', y='faturamento', data=gross_director, color='#7A70A9');\n\n# Definindo o título\nplt.title('Faturamento bruto (U$) dos filmes americanos por \"filmes-irmãos\"', fontsize=20)\n\n# Definindo o eixo horizontal\nplt.xlabel('Quantidade de \"filmes-irmãos\"', fontsize=18)\n\n# Definindo o eixo vertical\nplt.ylabel(\"Faturamento bruto\", fontsize=18)\n\n# Configurando o tamanho com ticks\nplt.xticks(fontsize=12)\nplt.yticks(fontsize=12)\n\nplt.show();\n\n\n# #### Os pontos estranhos são aqueles entre 15 e 20 \"filmes-irmãos\" que têm um faturamento mais baixo que os seus \"vizinhos\".\n\n# In[7]:\n\n\nselecao = gross_director.reset_index().sort_values(by='filmes_irmaos', \n ascending=False).query('filmes_irmaos > 16 & filmes_irmaos < 20')\n# Mostrando o nome do diretor\nprint('O diretor com muitos filmes na carreira, porém com faturamento menor que os demais é:\\n\\n'\n f'\\n\\t\\t\\t\\t{selecao[\"director_name\"].values[0]}')\n\n\n# # Desafio 6 \n# Analise mais detalhadamente o gráfico pairplot, gaste um tempo pensando e tentando enteder os gráficos.\n\n# In[8]:\n\n\n# Definindo uma função de plote os gráficos de correlação entre as grandezas faturamento, despesas, lucro e ano de lançamento\n# Esse passo foi feito apenas para facilitar o próximo desafio\ndef plot_corr():\n \n # Tamanho da figura\n plt.figure(figsize=(15, 8))\n \n # Selecionando os dados para análise\n dados_correlacao = imdb_usa[[\"gross\", \"budget\", \"lucro\", \"title_year\"]]\n \n # Renomeando as colunas do DataFrame selecionado\n dados_correlacao.columns = ['Faturamento', 'Despesas', 'Lucro', 'Ano de Lançamento']\n \n # Plotando os gráficos de correlação entre as grandezas faturamento, despesas, lucro e ano de lançamento com a seaborn\n sns.pairplot(data=dados_correlacao, palette=\"RdBu\", markers='x',\n kind='reg', diag_kind=\"kde\", diag_kws=dict(shade=True), \n plot_kws={'line_kws':{'color':'#FA8072'}}\n );\n\n # Título\n print('Faturamento, despesas, lucro e ano de lançamento e suas correlações entre si')\n \n # Mostrando a figura\n plt.show();\n return\n\n# Chamando a função plot_corr()\nplot_corr()\n\n\n# #### Analisando os gráficos podemos fazer algumas observações interessantes, como:\n#
    \n#
  • Filmes mais novos tende a ter o lucro menor. Provavelmente pois teveram menos tempo para conseguir aumentar seu lucro
  • \n#
  • O investimento em filmes aumentou com o passar dos anos.
  • \n#
  • Os filmes com as maiores despesas tendem a ter um maior faturamento.
  • \n#
  • E os filmes com maior faturamento tendem a ter um lucro maior e também despesas.
  • \n#
\n\n# # Desafio 7 \n# Calcular a correlação apenas dos filmes pós anos 2000 (Jogar fora filmes antes de 2000) e interpretar essa correlação.\n\n# In[9]:\n\n\nimdb_usa.query('title_year >= 2000')[['gross', 'budget', 'lucro', 'title_year']].corr().round(2)\n\n\n# #### As duas correlações mais significativas são entre as grandezas despesas(budget) e o faturamento(gross) e as grandezas lucro e faturamento.\n\n# # Desafio 8\n# \n# Tentar encontrar uma reta, pode ser com uma régua no monitor (não faça isso), com o excel/google sheets, com o python, no gráfico que parece se aproximar com uma reta (por exemplo budget/lucro, gross/lucro)\n\n# In[10]:\n\n\n# Tamanho da figura\nplt.figure(figsize=(15, 8));\n\n# Plotando os gráficos de lucro por faturamento bruto com a seaborn\nsns.pairplot(data=imdb_usa, y_vars='lucro', x_vars='gross', palette=\"RdBu\", markers='x',\n height=6, kind='reg', diag_kind=\"kde\", diag_kws=dict(shade=True), \n plot_kws={'line_kws':{'color':'#FA8072'}}\n );\n\n# Definindo os títulos\nplt.title('Lucro versus faturamento bruto', fontsize=20)\n\n# Definindo o eixo horizontal\nplt.xlabel(\"Faturamento\", fontsize=18)\n\n# Definindo o eixo vertical\nplt.ylabel(\"Lucro\", fontsize=18)\n\n# Configurando o tamanho com ticks\nplt.yticks(fontsize=12)\n\n# Mostrando a figura\nplt.show();\n\n\n# In[11]:\n\n\n# Tamanho da figura\nplt.figure(figsize=(15, 8))\n\n# Plotando os gráficos de lucro por despesas com a seaborn\nsns.pairplot(data=imdb_usa, y_vars='lucro', x_vars='budget', palette=\"RdBu\", markers='x',\n height=6, kind='reg', diag_kind=\"kde\", diag_kws=dict(shade=True), \n plot_kws={'line_kws':{'color':'#FA8072'}}\n );\n\n# Definindo os títulos\nplt.title('Lucro versus despesas', fontsize=20)\n\n# Definindo o eixo horizontal\nplt.xlabel(\"Despesas\", fontsize=18)\n\n# Definindo o eixo vertical\nplt.ylabel(\"Lucro\", fontsize=18)\n\n# Configurando o tamanho com ticks\nplt.xticks(fontsize=12)\n\n# Mostrando a figura\nplt.show();\n\n\n# # Desafio 9 \n# \n# Analisar e interpretar a correlação de outras variáveis além das feitas em sala. Número de avaliações por ano pode ser uma boa.\n# \n\n# In[12]:\n\n\n# Criando uma matriz de correlação com os dados do DataFrame \"imdb-usa\"\ncorrelacao = imdb_usa.corr()\n\n# Criando uma matriz triangular superior\nmask = np.zeros_like(correlacao)\nmask[np.triu_indices_from(mask)] = True\n\n# Configurando o tamenho da figura\nf, ax = plt.subplots(figsize=(13,13))\n\n# Gerando um mapa de cores divergente personalizado\ncmap = sns.diverging_palette(0, 1000, l=55, s=80, as_cmap=True)\n\n# Draw the heatmap with the mask and correct aspect ratio\ncorrelacao = imdb_usa.corr().round(2)\nsns.heatmap(correlacao, mask=mask,\n square=True, linewidth=.9, cbar_kws={\"shrink\": .8}, \n cmap=cmap, annot=True)\n\nplt.title('Matrix de correlação entre as variáveis', fontsize=20)\n\nplt.show()\n\n\n# ### A correlação negativa mais forte é entre as notas atribuídas aos filmes e o seu ano de lançamento do filme\n\n# In[13]:\n\n\n# Tamanho da figura\nplt.figure(figsize=(15, 8))\n\n# Plotando o gráfico notas por ano de lançamento com a seaborn\nsns.scatterplot(x=\"title_year\", y=\"imdb_score\", data = imdb_usa[[\"imdb_score\", \"title_year\"]], color='#DD4792')\n\n# Definindo o título\nplt.title('Notas por ano de lançamento', fontsize=20)\n\n# Definindo o eixo horizontal\nplt.xlabel('Ano de lançamento', fontsize=16)\n\n# Definindo o eixo vertical\nplt.ylabel(\"Notas atribuídas\", fontsize=16)\n\n# Configurando o tamanho com ticks\nplt.xticks(fontsize=12)\n\nplt.show();\n\n\n# Os filmes antigos têm bem menos avaliações que os filmes mais recentes. Porém, suas notas são muito maiores.\n","repo_name":"ViniViniAntunes/QuarentenaDados","sub_path":"aula03.py","file_name":"aula03.py","file_ext":"py","file_size_in_byte":11741,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"73499271159","text":"# import the library of tkinter\nfrom tkinter import *\nimport sign\nimport login\nimport mod_enter\nimport admin_enter\nimport firebase as fb\nimport urllib.parse\nfrom PIL import Image, ImageTk\nimport io\n\n\nclass Menu:\n image = None\n\n def __init__(self, root):\n self.root = root\n\n path = \"window/beach_edited.png\"\n url = fb.storage.child(path).get_url(None)\n data = urllib.request.urlopen(url).read()\n im = Image.open(io.BytesIO(data))\n self.image = ImageTk.PhotoImage(im, master=self.root)\n\n Label(self.root, image=self.image).place(x=0, y=0, relwidth=1, relheight=1)\n\n Label(self.root, text=\"Welcome to TriPerAdvise!\", bg=\"#2b509c\", fg=\"#f64424\",\n font=(\"Lucida Grande\", 22, \"bold\")).place(x=30, y=12, width=500, height=50)\n Label(self.root, text=\"Plan your trip with us :)\", bg=\"#2b509c\", fg=\"#fc9d17\",\n font=(\"Lucida Grande\", 15, \"bold\")).place(x=130, y=70, width=300, height=40)\n\n sign_up = Button(root, text=\"Sign up\", command=self.signup_press, font=(\"Lucida Grande\", 15, \"bold\"),\n bg=\"white\", fg=\"#2b509c\", borderwidth=5)\n sign_up.place(x=65, y=280, width=110, height=50)\n\n log_in = Button(root, text=\"Log in\", command=self.login_press, font=(\"Lucida Grande\", 15, \"bold\"),\n borderwidth=5,\n bg=\"white\", fg=\"#2b509c\")\n log_in.place(x=385, y=280, width=110, height=50)\n\n log_in_mod = Button(root, text=\"Moderator Login\", command=self.login_mod_press, font=(\"Lucida Grande\", 10),\n borderwidth=4, fg=\"#f64424\")\n log_in_mod.place(x=100, y=395, width=180, height=35)\n\n log_in_admin = Button(root, text=\"Administrator Login\", command=self.login_admin_press,\n font=(\"Lucida Grande\", 10), borderwidth=4, fg=\"#f64424\")\n log_in_admin.place(x=280, y=395, width=180, height=35)\n\n def signup_press(self):\n master = Tk()\n master.after(1, lambda: master.focus_force())\n master.title('Sign Up')\n master.geometry(\"560x440+680+213\")\n master.resizable(False, False)\n sign.Sign_up(master)\n self.root.destroy()\n\n def login_press(self):\n master = Tk()\n master.after(1, lambda: master.focus_force())\n master.title('Log In')\n master.geometry(\"560x440+680+213\")\n master.resizable(False, False)\n login.Login(master)\n self.root.destroy()\n\n\n\n def login_mod_press(self):\n master = Tk()\n master.after(1, lambda: master.focus_force())\n master.title('Moderator Log In')\n master.geometry(\"560x440+680+213\")\n master.resizable(False, False)\n mod_enter.Moderator(master)\n self.root.destroy()\n\n\n\n def login_admin_press(self):\n master = Tk()\n master.after(1, lambda: master.focus_force())\n master.title('Administrator Log In')\n master.geometry(\"560x440+680+213\")\n master.resizable(False, False)\n admin_enter.Administrator(master)\n self.root.destroy()\n","repo_name":"NiPavel/TripApp","sub_path":"Code/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":3097,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"16810042352","text":"import os\nimport shutil\nimport uuid\n\nfrom zipfile import ZipFile\nfrom bs4 import BeautifulSoup, NavigableString, Tag\n\nfrom django.utils.text import slugify\n\nfrom .models import Page, PageTranslation\n\nXLIFF_TAG = 'xliff'\nXLIFF_SRC_LANG_ATTRIBUTE_NAME = 'srcLang'\nXLIFF_TRG_LANG_ATTRIBUTE_NAME = 'trgLang'\n\nPAGE_XLIFF_TEMPLATE = '''\n\n \n {title}\n {text}\n \n\n'''\nPAGE_TAG = 'page'\nPAGE_TITLE_TAG = 'page-title'\nPAGE_TITLE_BEGIN_TAG = ''\nPAGE_TITLE_END_TAG = ''\nPAGE_TITLE_TEMPLATE = '''{0}'''\n\nPAGE_TEXT_TAG = 'page-text'\nPAGE_TEXT_BEGIN_TAG = ''\nPAGE_TEXT_END_TAG = ''\nPAGE_TEXT_TEMPLATE = '{0}'\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nXLIFFS_DIR = os.path.join(BASE_DIR, 'xliffs')\n\nTRANSLATION_UNIT_TEMPLATE = '''\n \n \n {0}\n {1}\n \n \n'''\nENGLISH_LANGUAGE_CODE = 'en-us'\n\nclass XliffValidationException(Exception):\n pass\n\n# pylint: disable=too-few-public-methods\nclass PageXliff:\n def __init__(self, page_id, language_code, title, text):\n self.page_id = page_id\n self.language_code = language_code\n self.title = title\n self.text = text\n\n\nclass PageXliffConverter:\n @staticmethod\n def _add_navigable_string_to_empty_tag(soup):\n for el in list(soup.descendants):\n if isinstance(el, Tag) and not list(el.children) and el.name not in ('br',):\n el.append(NavigableString(' '))\n\n @staticmethod\n def _replace_all_navigable_strings(soup):\n for el in list(soup.descendants):\n if isinstance(el, NavigableString):\n el.replaceWith(NavigableString('###'))\n\n\n @staticmethod\n def _trim_tag_navigable_string(element):\n for child in list(element.children):\n if isinstance(child, NavigableString):\n child.replaceWith(NavigableString(child.string.strip()))\n\n @staticmethod\n def _trim_unit_source_target_tag_navigable_string(source_data):\n bs = BeautifulSoup(source_data, 'xml')\n elements = []\n elements.extend(list(bs.find_all('source')))\n elements.extend(list(bs.find_all('target')))\n for element in elements:\n PageXliffConverter._trim_tag_navigable_string(element)\n\n return str(bs.find())\n\n @staticmethod\n def _compare_structure_and_return_source_target(source, target):\n if target is None:\n return False, source, target\n\n source_soup = BeautifulSoup(source, 'xml')\n target_soup = BeautifulSoup(target, 'xml')\n source_prettify = source_soup.prettify()\n target_prettify = target_soup.prettify()\n PageXliffConverter._add_navigable_string_to_empty_tag(source_soup)\n PageXliffConverter._add_navigable_string_to_empty_tag(target_soup)\n PageXliffConverter._replace_all_navigable_strings(source_soup)\n PageXliffConverter._replace_all_navigable_strings(target_soup)\n\n comparing_source = source_soup.prettify()\n comparing_target = target_soup.prettify()\n\n return comparing_source == comparing_target, source_prettify, target_prettify\n\n @staticmethod\n def _replace_navigable_string_with_unit(ns_element, source, target=''):\n if source:\n unit = TRANSLATION_UNIT_TEMPLATE.format(source, target)\n temp_soup = BeautifulSoup(unit, 'xml')\n ns_element.replaceWith(temp_soup.find())\n\n @staticmethod\n def _replace_source_target_unit(source_element, target_element):\n source_children = list(source_element.children)\n target_children = list(target_element.children)\n tag_elements = []\n for source_child, target_child in zip(source_children, target_children):\n if isinstance(source_child, NavigableString) and isinstance(target_child, NavigableString):\n PageXliffConverter._replace_navigable_string_with_unit(\n source_child, source_child.string.strip(), target_child.string.strip())\n else:\n tag_elements.append((source_child, target_child,))\n\n for source_tag, target_tag in tag_elements:\n PageXliffConverter._replace_source_target_unit(source_tag, target_tag)\n\n @staticmethod\n def _replace_source_unit(element):\n children = list(element.children)\n tag_elements = []\n for child in children:\n if isinstance(child, NavigableString):\n PageXliffConverter._replace_navigable_string_with_unit(child, child.string.strip())\n else:\n tag_elements.append(child)\n\n for tag in tag_elements:\n PageXliffConverter._replace_source_unit(tag)\n\n def html_to_xliff(self, source, target=None):\n compare_result, compare_source, compare_target = self._compare_structure_and_return_source_target(\n source=source,\n target=target\n )\n source_soup = BeautifulSoup(compare_source, 'xml')\n if compare_result:\n target_soup = BeautifulSoup(compare_target, 'xml')\n self._replace_source_target_unit(source_soup, target_soup)\n else:\n self._replace_source_unit(source_soup)\n result = self._trim_unit_source_target_tag_navigable_string(source_soup.find().prettify())\n result = result.replace('', '').replace('', '')\n return result\n\n @staticmethod\n def xliff_to_html(xliff, target=True):\n bs = BeautifulSoup(xliff, \"xml\")\n elements = bs.find_all('unit')\n content_tag = 'target'\n if not target:\n content_tag = 'source'\n\n for element in elements:\n content_element = element.find(content_tag)\n if content_element:\n element.replace_with(NavigableString(content_element.get_text()))\n\n result = bs.prettify()\n\n return result.replace('', '')\n\n def page_translation_to_xliff(self, source_translation_page, target_language_code):\n result = \"\"\n source_language_code = source_translation_page.language.code\n if source_translation_page and source_language_code != target_language_code:\n target_translation_page = source_translation_page.page.get_translation(target_language_code)\n if target_translation_page:\n title = self.html_to_xliff(\n PAGE_TITLE_TEMPLATE.format(source_translation_page.title),\n PAGE_TITLE_TEMPLATE.format(target_translation_page.title)\n )\n text = self.html_to_xliff(\n PAGE_TEXT_TEMPLATE.format(source_translation_page.text),\n PAGE_TEXT_TEMPLATE.format(target_translation_page.text)\n )\n else:\n title = self.html_to_xliff(\n PAGE_TITLE_TEMPLATE.format(source_translation_page.title)\n )\n text = self.html_to_xliff(\n PAGE_TEXT_TEMPLATE.format(source_translation_page.text)\n )\n\n result = PAGE_XLIFF_TEMPLATE.format(src_lang=source_language_code,\n trg_lang=target_language_code,\n page_id=source_translation_page.page.id,\n title=title,\n text=text)\n return result\n\n # pylint: disable=too-many-locals\n def xliff_to_page_xliff(self, xliff, target=True):\n bs = BeautifulSoup(xliff, 'xml')\n xliff_element = bs.find(XLIFF_TAG)\n page_xliff = None\n error_messages = []\n if xliff_element and 'srcLang' in xliff_element.attrs and 'trgLang' in xliff_element.attrs:\n language_code = xliff_element['srcLang']\n if target:\n language_code = xliff_element['trgLang']\n page_element = xliff_element.find(PAGE_TAG)\n if page_element and 'id' in page_element.attrs:\n page_id = page_element['id']\n title_element = page_element.find(PAGE_TITLE_TAG)\n text_element = page_element.find(PAGE_TEXT_TAG)\n\n if title_element and text_element:\n title = self.xliff_to_html(title_element.prettify(), target=target)\n title = title.replace(PAGE_TITLE_BEGIN_TAG, '').replace(PAGE_TITLE_END_TAG, '').strip()\n\n text = self.xliff_to_html(text_element.prettify(), target=target)\n temp_bs = BeautifulSoup(text, 'xml')\n temp_strings = list(temp_bs.stripped_strings)\n if temp_strings:\n text = text.replace(PAGE_TEXT_BEGIN_TAG, '').replace(PAGE_TEXT_END_TAG, '').strip()\n else:\n text = ''\n page_xliff = PageXliff(page_id=page_id, language_code=language_code, title=title, text=text)\n else:\n error_messages.append('cannot find page title or text tag')\n\n else:\n error_messages.append('cannot find page tag or page id not exists.')\n else:\n error_messages.append('cannot find xliff tag or srcLang and trgLang not exists.')\n\n if error_messages:\n raise XliffValidationException('\\n'.join(error_messages))\n\n return page_xliff\n\n\nclass PageXliffHelper:\n def __init__(self, converter=None):\n if converter:\n self.converter = converter\n else:\n self.converter = PageXliffConverter()\n\n @staticmethod\n def save_file(content, file_path):\n os.makedirs(os.path.dirname(file_path), exist_ok=True)\n with open(file_path, 'w', encoding='utf-8') as file:\n file.write(content)\n\n def export_page_translation_xliff(self, source_translation_page, target_language_code, filename=None):\n\n if not filename:\n filename = 'page_{0}_{1}_{2}.xliff'.format(source_translation_page.page.id,\n source_translation_page.language.code,\n target_language_code)\n\n file_path = None\n\n xliff_content = self.converter.page_translation_to_xliff(source_translation_page, target_language_code)\n\n if xliff_content:\n file_path = os.path.join(XLIFFS_DIR, str(uuid.uuid4()), filename)\n self.save_file(xliff_content, file_path)\n\n return file_path\n\n @staticmethod\n def _create_zip_file(source_file_paths, zip_file_path):\n os.makedirs(os.path.dirname(zip_file_path), exist_ok=True)\n with ZipFile(zip_file_path, 'w') as zip_file:\n for file_path in source_file_paths:\n if os.path.isfile(file_path):\n file_name = file_path.split(os.sep)[-1]\n zip_file.write(file_path, arcname=file_name)\n\n @staticmethod\n def delete_tmp_in_xliff_folder(file_path):\n if file_path.startswith(XLIFFS_DIR):\n folder = os.path.dirname(file_path)\n files = os.listdir(folder)\n if len(files) == 1 and os.path.join(folder, files[0]) == file_path:\n shutil.rmtree(folder)\n\n @staticmethod\n def _get_xliff_directions(languages, default_language):\n source_target_langs = []\n english_language = None\n for language in languages:\n if language.code == ENGLISH_LANGUAGE_CODE:\n english_language = language\n break\n\n if default_language.code == ENGLISH_LANGUAGE_CODE or not english_language:\n for language in languages:\n if language != default_language:\n source_target_langs.append((default_language.code, language.code,))\n else:\n for language in languages:\n if language != default_language:\n if language.code == ENGLISH_LANGUAGE_CODE:\n source_target_langs.append((default_language.code, ENGLISH_LANGUAGE_CODE,))\n else:\n source_target_langs.append((ENGLISH_LANGUAGE_CODE, language.code,))\n\n return source_target_langs\n\n\n def export_page_xliffs_to_zip(self, page):\n zip_file_path = None\n xliff_files = []\n if page and len(page.region.languages) > 1:\n page_translations = list(page.translations.all())\n language_page_translation_map = {}\n for page_translation in page_translations:\n language_page_translation_map[page_translation.language.code] = page_translation\n\n default_language = page.region.default_language\n if not default_language or default_language.code not in language_page_translation_map:\n default_language = page_translations[0].language\n source_page_translation = page_translations[0]\n elif default_language.code in language_page_translation_map:\n source_page_translation = language_page_translation_map[default_language.code]\n\n xliff_directions = self._get_xliff_directions(page.region.languages, default_language)\n\n for source_language_code, target_language_code in xliff_directions:\n if source_language_code in language_page_translation_map:\n xliff_files.append(\n self.export_page_translation_xliff(language_page_translation_map[source_language_code],\n target_language_code))\n elif target_language_code != source_page_translation.language.code:\n xliff_files.append(\n self.export_page_translation_xliff(source_page_translation, target_language_code))\n\n zip_file_name = \"page_{0}.zip\".format(page.id)\n zip_file_path = os.path.join(XLIFFS_DIR, 'pages', str(uuid.uuid4()), zip_file_name)\n self._create_zip_file(xliff_files, zip_file_path)\n\n # delete xliff files after created zip file\n for xliff_file in xliff_files:\n self.delete_tmp_in_xliff_folder(xliff_file)\n\n return zip_file_path\n\n @staticmethod\n def _get_page_translation_slug(title):\n slug = slugify(title)\n if PageTranslation.objects.filter(slug=slug).exists():\n old_slug = slug\n i = 1\n while True:\n i += 1\n slug = old_slug + '-' + str(i)\n if not PageTranslation.objects.filter(slug=slug).exists():\n break\n\n return slug\n\n @staticmethod\n def save_page_xliff(page_xliff, user):\n result = False\n try:\n if page_xliff.page_id and page_xliff.title and page_xliff.text and page_xliff.language_code:\n page = Page.objects.get(id=int(page_xliff.page_id))\n page_translation = page.get_translation(page_xliff.language_code)\n if page_translation:\n page_translation.title = page_xliff.title\n page_translation.text = page_xliff.text\n page_translation.slug = PageXliffHelper._get_page_translation_slug(page_xliff.title)\n\n elif page.languages:\n target_language = None\n for language in page.region.languages:\n if page_xliff.language_code == language.code:\n target_language = language\n break\n if target_language:\n slug = PageXliffHelper._get_page_translation_slug(page_xliff.title)\n source_page_translation = list(page.translations.all())[0]\n page_translation = PageTranslation.objects.create(\n slug=slug,\n title=page_xliff.title,\n text=page_xliff.text,\n status=source_page_translation.status,\n language=target_language,\n public=source_page_translation.public,\n page=page,\n creator=user\n )\n\n if page_translation:\n page_translation.save()\n result = True\n # pylint: disable=broad-except\n except Exception:\n pass\n\n return result\n\n def import_xliff_file(self, file_path, user):\n result = False\n if file_path.startswith(XLIFFS_DIR) and file_path.endswith(('.xlf', '.xliff')) and os.path.isfile(file_path):\n with open(file_path, 'r', encoding='utf-8') as f:\n xliff_content = f.read()\n page_xliff = self.converter.xliff_to_page_xliff(xliff_content)\n if page_xliff:\n result = self.save_page_xliff(page_xliff, user)\n\n return result\n\n def import_xliffs_zip_file(self, zip_file_path, user):\n results = []\n\n if zip_file_path.startswith(XLIFFS_DIR) and zip_file_path.endswith('.zip') and os.path.isfile(zip_file_path):\n with ZipFile(zip_file_path, 'r') as zip_file:\n for file_name in zip_file.namelist():\n if file_name.endswith(('.xliff', '.xlf',)):\n with zip_file.open(file_name) as f:\n try:\n xliff_content = f.read()\n page_xliff = self.converter.xliff_to_page_xliff(xliff_content)\n if page_xliff:\n results.append((file_name, self.save_page_xliff(page_xliff, user),))\n else:\n results.append((file_name, False,))\n except XliffValidationException:\n results.append((file_name, False,))\n return results\n","repo_name":"digitalfabrik/coldaid-backend","sub_path":"src/cms/page_xliff_converter.py","file_name":"page_xliff_converter.py","file_ext":"py","file_size_in_byte":18376,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"40"} +{"seq_id":"70163965880","text":"from .common import *\n\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n# if you wat to use testing mail sending\nEMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n\nSECRET_KEY = 'secret'\n\nDEBUG = True\n\nALLOWED_HOSTS = []\n\n\nLOGIN_URL = urls.reverse_lazy('sso-dev')\n","repo_name":"emncaymaz/incidentForm","sub_path":"incidentform/settings/dev_example.py","file_name":"dev_example.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"73629415799","text":"class ChartDimensionDetail(object):\n\n def __init__(self, charts=None, dimension=None, dimensionName=None, serviceCode=None, serviceName=None, tags=None):\n \"\"\"\n :param charts: (Optional) 监控图的展示方式\n :param dimension: (Optional) 维度dimension\n :param dimensionName: (Optional) 分组名称\n :param serviceCode: (Optional) 产品线\n :param serviceName: (Optional) 分组名称\n :param tags: (Optional) 分组下metric对应的tags\n \"\"\"\n\n self.charts = charts\n self.dimension = dimension\n self.dimensionName = dimensionName\n self.serviceCode = serviceCode\n self.serviceName = serviceName\n self.tags = tags\n","repo_name":"jdcloud-api/jdcloud-sdk-python","sub_path":"jdcloud_sdk/services/monitor/models/ChartDimensionDetail.py","file_name":"ChartDimensionDetail.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"40"} +{"seq_id":"34300925295","text":"import numpy as np\nimport math\nimport numba as nb\n\n\n@nb.njit\ndef compress(original, ver, hor):\n rows, cols = original.shape\n new_rows = math.ceil(rows / ver)\n new_cols = math.ceil(cols / hor)\n\n current_matrix = np.zeros((new_rows, new_cols), dtype=np.complex64)\n for i in range(new_rows):\n for j in range(new_cols):\n row_start = i * ver\n row_end = min(row_start + ver, rows)\n col_start = j * hor\n col_end = min(col_start + hor, cols)\n current_matrix[i, j] = np.sum(original[row_start:row_end, col_start:col_end])\n\n return current_matrix\n\n\ndef rescale(arr):\n arr_min = arr.min()\n arr_max = arr.max()\n return (arr - arr_min) / (arr_max - arr_min)\n\n\ndef max_axis(arr, k=1):\n red = arr[:, :, 0]\n green = arr[:, :, 1]\n blue = arr[:, :, 2]\n mr = np.mean(np.max(red, axis=0))\n mg = np.mean(np.max(green, axis=0))\n mb = np.mean(np.max(blue, axis=0))\n arr = k * arr / np.mean([mr, mg, mb])\n arr[arr > 1] = 1\n arr = 255 * arr\n return arr","repo_name":"Spiraks/readRadio","sub_path":"my_stat.py","file_name":"my_stat.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"74348634039","text":"import pandas as pd\nimport requests\nfrom bs4 import BeautifulSoup as Soup\nimport pandas as pd\nimport os\nfrom datetime import datetime, timedelta\nimport requests\nfrom bs4 import BeautifulSoup as Soup\nimport pandas as pd\nimport os\nfrom datetime import datetime, timedelta\n\n\ndef scraping(user_location):\n locations = [\"Mumbai\", \"New Delhi\", \"Bangalore\", \"Kolkata\", \"Chennai\", \"Hyderabad\", \"Ahmedabad\", \"Pune\", \"Surat\", \"Jaipur\", \"Lucknow\", \"Kanpur\", \"Nagpur\", \"Indore\", \"Thane\", \"Bhopal\", \"Visakhapatnam\", \"Pimpri-Chinchwad\", \"Patna\", \"Vadodara\"]\n # Function to scrape data from Booking.com\n def scrape_bookingdotcom(destination, checkin_date, checkout_date):\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36'\n }\n req = requests.get(\n f\"https://www.booking.com/searchresults.en-gb.html?ss={destination}&checkin={checkin_date}&checkout={checkout_date}&offset==0\",\n headers=headers).text\n soup = Soup(req, 'html.parser')\n ap = soup.find(\"ol\", {\"class\": \"a8b500abde\"}).text\n\n df = pd.DataFrame(columns=[\"price\", \"location\", \"distance\", \"amenities\", \"ratings\", \"type\"])\n for pages in range(0, int(ap[len(ap) - 1])):\n req = requests.get(\n f\"https://www.booking.com/searchresults.en-gb.html?ss={destination}&checkin={checkin_date}&checkout={checkout_date}&offset=={pages * 25}\",\n headers=headers).text\n soup = Soup(req, 'html.parser')\n apts = soup.find_all(\"div\", {\"class\": \"d20f4628d0\"})\n rows = []\n\n for a in range(0, len(apts)):\n obj = {}\n\n try:\n obj[\"price\"] = apts[a].find(\"span\", {\"class\": \"fcab3ed991 fbd1d3018c e729ed5ab6\"}).text\n except:\n obj[\"price\"] = None\n\n try:\n obj[\"distance\"] = apts[a].find(\"span\", {\"class\": \"cb5ebe3ffb\"}).text\n except:\n obj[\"distance\"] = None\n\n try:\n ap1 = apts[a].find('a', href=True)\n link = ap1['href']\n req1 = requests.get(link, headers=headers).text\n soup2 = Soup(req1, 'html.parser')\n obj[\"amenities\"] = soup2.find(\"div\", {\"class\": \"e5e0727360\"}).text\n except:\n obj[\"amenities\"] = None\n\n try:\n obj[\"ratings\"] = apts[a].find(\"div\", {\"class\": \"b5cd09854e d10a6220b4\"}).text\n except:\n obj[\"ratings\"] = None\n\n try:\n obj[\"type\"] = apts[a].find(\"span\", {\"class\": \"df597226dd\"}).text\n except:\n obj[\"type\"] = None\n\n try:\n obj[\"location\"] = apts[a].find(\"span\", {\"class\": \"f4bd0794db b4273d69aa\"}).text\n except:\n obj[\"location\"] = None\n\n rows.append(obj)\n\n df = pd.concat([df, pd.DataFrame(rows)])\n\n # Data cleaning\n df[\"price\"] = df[\"price\"].str.replace(r\"₹\", \"\")\n df[\"price\"] = df[\"price\"].str.replace(r\" \", \"\")\n df[\"price\"] = df[\"price\"].str.replace(r\",\", \"\")\n df[\"price\"] = df[\"price\"].str.strip()\n df['price'] = pd.to_numeric(df['price'])\n df['ratings'] = pd.to_numeric(df['ratings'], errors='coerce')\n df['ratings'] = df['ratings'].fillna(df['ratings'].mean())\n\n return df\n\n # Take user input for the location, check-in date, and check-out date\n user_location=user_location.strip().capitalize()\n current_date = datetime.now().strftime(\"%Y-%m-%d\")\n checkin_date = current_date\n checkout_date = (datetime.now() + timedelta(days=1)).strftime(\"%Y-%m-%d\")\n folder_name = f\"data{current_date}\"\n data_folder_path = os.path.join(os.getcwd(), \"data\")\n if not os.path.exists(data_folder_path):\n os.makedirs(data_folder_path)\n # Step 3: Create the new folder inside the \"data\" folder\n new_folder_path = os.path.join(data_folder_path, folder_name)\n if not os.path.exists(new_folder_path):\n os.makedirs(new_folder_path)\n # Check if user input location has already been scraped\n user_location_csv = f\"{user_location}_{current_date}.csv\"\n destination_file_path = os.path.join(new_folder_path, user_location_csv)\n\n if os.path.isfile(destination_file_path):\n print(f\"Skipping {user_location}. Already scraped.\")\n user_df=pd.read_csv(destination_file_path)\n else:\n # Scrape data for the user input location\n print(f\"scraping data for{user_location}\\n\")\n df = scrape_bookingdotcom(user_location, checkin_date, checkout_date)\n\n # Save the data to a CSV file with current date in the filename\n df.to_csv(destination_file_path, index=False)\n print(f\"Scraped and saved data for {user_location}.\")\n user_df=df\n # Scrape data for remaining locations\n for location in locations:\n location_csv = f\"{location}_{current_date}.csv\"\n location_file_path = os.path.join(new_folder_path, location_csv)\n\n if not os.path.isfile(location_file_path):\n # Scrape data for the location\n print(f\"scraping data for {location}\\n\")\n\n df = scrape_bookingdotcom(location, checkin_date, checkout_date)\n\n # Save the data to a CSV file with current date in the filename\n df.to_csv(location_file_path, index=False)\n print(f\"Scraped and saved data for {location}.\")\n\n # Combine all CSV files into a single dataframe\n combined_df = pd.DataFrame()\n if user_location in locations:\n csv_files =[os.path.join(new_folder_path,f\"{location}_{current_date}.csv\") for location in locations]\n else:\n csv_files = [destination_file_path] + [os.path.join(new_folder_path,f\"{location}_{current_date}.csv\") for location in locations]\n print(csv_files)\n for csv_file in csv_files:\n if os.path.isfile(csv_file):\n df = pd.read_csv(csv_file)\n combined_df = pd.concat([combined_df, df])\n\n # Save the combined dataframe to a CSV file with current date in the filename\n combined_folder_path = os.path.join(data_folder_path,'combined')\n if not os.path.exists(combined_folder_path):\n os.makedirs(combined_folder_path)\n final_csv_filename = f\"combined_{current_date}.csv\"\n file_path = os.path.join(combined_folder_path, final_csv_filename)\n\n combined_df.to_csv(file_path, index=False)\n\n print(\"Scraping completed.\")\n return user_df\n\n\n\n","repo_name":"Hash-if-vs/Room-Price-Recommendation-System","sub_path":"datacollection.py","file_name":"datacollection.py","file_ext":"py","file_size_in_byte":6654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"42461535254","text":"from django.conf.urls import patterns, url\nfrom django.views.generic import ListView, DetailView\n\nfrom .models import Recipe\nfrom .views import RecipeFeed, IngredientListView, IngredientRecipeList, RecipeDetailView\n\n\nurlpatterns = patterns('recipe.views',\n url(r'^$', 'home', name='recipe_home'),\n url(r'^new_recipe/$', 'new_recipe', name=\"recipe_new\"),\n url(r'^submit_recipe/$', 'submit_recipe', name=\"recipe_submit\"),\n url(r'^submit_rating/$', 'submit_rating', name=\"recipe_rate\"),\n url(r'^(?P\\d{4})/(?P\\d{2})/(?P\\d{1,2})/(?P[-\\w]+)/$',\n view=RecipeDetailView.as_view(),\n name='recipe_detail'),\n url(r'^ingredients/$', IngredientListView.as_view(), name=\"recipe_ingredient_list\"),\n url(r'^ingredients/(?P\\d+)/$', IngredientRecipeList.as_view(), name=\"recipe_ingredient_search\"),\n url(r'^recipes/$', ListView.as_view(\n queryset=Recipe.objects.all().order_by(\"-created\"),\n template_name=\"recipe/archives.html\")),\n url(r'^tag/(?P\\w+)$', 'tagpage'),\n url(r'^feed/$', RecipeFeed()),\n)\n","repo_name":"kevinlondon/rehdernomics.com","sub_path":"recipe/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"36461581644","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import misc\nfrom PIL import Image\nimport os\n\n\n# User guide:\n# Specify tfrecord path from where you want to extract images.\n# Specify output directory where to save extracted images.\n\n# Tfrecord path\ntfrecord_filename = '../../../../../Documents/CarAppML/cars/cars_validation_00000-of-00002.tfrecord'\n\n# Val data directory path\nval_dir_path = '../../../../../Documents/CarAppML/cars/val_data/audi/'\n\n\nif __name__ == \"__main__\":\n record_iterator = tf.python_io.tf_record_iterator(path=tfrecord_filename)\n print(record_iterator)\n images = {}\n sess = tf.Session()\n i = 1\n for string_record in record_iterator:\n example = tf.train.Example()\n example.ParseFromString(string_record)\n height = int(example.features.feature['image/height'].int64_list.value[0])\n width = int(example.features.feature['image/width'].int64_list.value[0])\n img_string = example.features.feature['image/encoded'].bytes_list.value[0]\n img_decoded = tf.image.decode_jpeg(img_string, channels=3)\n img = sess.run(img_decoded)\n im = Image.fromarray(img)\n im.save(os.path.join(val_dir_path, 'val_image_'+str(i)+'.jpg'))\n i += 1\n\n","repo_name":"popina1994/car-recommender-application","sub_path":"machine_learning/inception/transfer_learning/reading_tfrecord.py","file_name":"reading_tfrecord.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"512529311","text":"#!/usr/bin/python3\n\"\"\"model state\n\"\"\"\nfrom sqlalchemy import Column, Integer, String\nfrom sqlalchemy.ext.declarative import declarative_base\n\nBase = declarative_base()\n\n\nclass State(Base):\n \"\"\" This is a State class inheriting from Base \"\"\"\n __tablename__ = 'states'\n\n id = Column(Integer, primary_key=True, nullable=False)\n name = Column(String(128), nullable=False)\n\n \"\"\"First you import the sqlalchemy module and then you import th necessary\n tools needed for the table you wantto create eg Column, Integer, etc...\n Thrn you import declarative_base from sqlalchemy.ext.declarative\n It will be used to creatr thr table class\n \"\"\"\n","repo_name":"Nkemjika1divine/alx-higher_level_programming","sub_path":"0x0F-python-object_relational_mapping/model_state.py","file_name":"model_state.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"31097600663","text":"#!/usr/bin/env python\nimport rospy\nimport numpy as np\nfrom std_msgs.msg import Float64\nfrom range_sensor.msg import RangeMeasurementArray\nfrom geometry_msgs.msg import Point\n# from nav_msgs.msg import Odometry\n\n\nclass RangeAnalysisNode():\n def __init__(self):\n rospy.init_node(\"range_analysis_node\")\n self.range_sub = rospy.Subscriber(\"ranges\",\n RangeMeasurementArray,\n self.range_callback,\n queue_size=1)\n self.range1_mean_pub = rospy.Publisher(\"range1_mean\",\n Float64,\n queue_size=1)\n self.range1_variance_pub = rospy.Publisher(\"range1_deviation\",\n Float64,\n queue_size=1)\n self.range2_mean_pub = rospy.Publisher(\"range2_mean\",\n Float64,\n queue_size=1)\n self.range2_variance_pub = rospy.Publisher(\"range2_deviation\",\n Float64,\n queue_size=1)\n self.range3_mean_pub = rospy.Publisher(\"range3_mean\",\n Float64,\n queue_size=1)\n self.range3_variance_pub = rospy.Publisher(\"range3_deviation\",\n Float64,\n queue_size=1)\n self.range4_mean_pub = rospy.Publisher(\"range4_mean\",\n Float64,\n queue_size=1)\n self.range4_variance_pub = rospy.Publisher(\"range4_deviation\",\n Float64,\n queue_size=1)\n\n self.ranges_bulk = [[], [], [], []]\n\n def range_callback(self, msg):\n num_measurements = len(msg.measurements)\n if num_measurements:\n for measurement in msg.measurements:\n self.ranges_bulk[measurement.id - 1].append(measurement.range)\n if len(self.ranges_bulk[measurement.id - 1]) > 200:\n self.ranges_bulk[measurement.id - 1].pop(0)\n else:\n print(\"WARNING: No measurements received!\")\n\n def run(self):\n rate = rospy.Rate(20.0)\n while not rospy.is_shutdown():\n range1_mean_msg = Float64()\n range1_variance_msg = Float64()\n range2_mean_msg = Float64()\n range2_variance_msg = Float64()\n range3_mean_msg = Float64()\n range3_variance_msg = Float64()\n range4_mean_msg = Float64()\n range4_variance_msg = Float64()\n\n range1_mean_msg.data = np.mean(self.ranges_bulk[0])\n range1_variance_msg.data = np.sqrt(np.var(self.ranges_bulk[0]))\n range2_mean_msg.data = np.mean(self.ranges_bulk[1])\n range2_variance_msg.data = np.sqrt(np.var(self.ranges_bulk[1]))\n range3_mean_msg.data = np.mean(self.ranges_bulk[2])\n range3_variance_msg.data = np.sqrt(np.var(self.ranges_bulk[2]))\n range4_mean_msg.data = np.mean(self.ranges_bulk[3])\n range4_variance_msg.data = np.sqrt(np.var(self.ranges_bulk[3]))\n\n self.range1_mean_pub.publish(range1_mean_msg)\n self.range1_variance_pub.publish(range1_variance_msg)\n self.range2_mean_pub.publish(range2_mean_msg)\n self.range2_variance_pub.publish(range2_variance_msg)\n self.range3_mean_pub.publish(range3_mean_msg)\n self.range3_variance_pub.publish(range3_variance_msg)\n self.range4_mean_pub.publish(range4_mean_msg)\n self.range4_variance_pub.publish(range4_variance_msg)\n\n rate.sleep()\n\n\ndef main():\n node = RangeAnalysisNode()\n node.run()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"RamckeM/FaV_BlueROV_ROS","sub_path":"localization/tools/range_analysis.py","file_name":"range_analysis.py","file_ext":"py","file_size_in_byte":4146,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"195337963","text":"import requests\nimport numpy as np\nimport pickle\nfrom src.text import translate_table\nimport tensorflow as tf\n\nMETHOD = \"predict\"\nVERSION = \"1\"\nURL = f\"http://localhost:8501/v{VERSION}/models/category_classifier:{METHOD}\"\n\ninstances = [\"nintendo 64\", \"tv lg c2\",\n \"samsung s5\",\n \"5200mAh Auto Detect Portable Charger External Battery Power Bank with LED light For iPhone 6 Plus 5S iPad Mini Samsung Galaxy S6 edge S5 S4 S3 Note 4 3 HTC Sony Most 5V Smart phones and Tablet (Blue)\"]\n\nresponse = requests.post(URL, json={\"instances\": instances})\n\nif response.status_code == 200:\n predictions = response.json()[\"predictions\"]\n for sample in zip(instances, predictions):\n title, logits = sample\n pred_index = tf.argmax([logits], axis=1).numpy()\n print(\"Title: \", title)\n print(\"category prediction: \", translate_table.lookup(tf.constant([pred_index])))\n print(\"---------------------------------------------------------------------------\")\nelse:\n print(response.status_code)\n","repo_name":"mmartiasg/workshop-metodologia-ml","sub_path":"notebooks/usage_api_example.py","file_name":"usage_api_example.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"663397966","text":"\"\"\"\nTests suite for the home pages app.\n\"\"\"\n\nfrom django.test import SimpleTestCase, Client\nfrom django.core.urlresolvers import reverse\n\n\nclass HomePagesTestCase(SimpleTestCase):\n \"\"\"\n Test the availability of all home pages.\n \"\"\"\n\n def test_main_home_page(self):\n \"\"\"\n Test the availability of the main home page.\n \"\"\"\n client = Client()\n response = client.get(reverse('home:index'))\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'home/home.html')\n","repo_name":"TamiaLab/carnetdumaker","sub_path":"apps/home/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"40"} +{"seq_id":"14077386935","text":"#! /usr/bin/env python3\n\n\nimport pickle\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n\ninv_and_orders = pd.read_csv('inventory_and_orders.csv', index_col=0, skipfooter=1)\\\n .iloc[:, 0:12]\n\n# Note to self: shape is (10000, 51): 10000 universes x 51 time steps\nwith open('order_streams.pkl', 'rb') as pf:\n order_streams = pickle.load(pf)\n\ntimes_to_reorder = np.zeros((order_streams.shape[0], 4), dtype='int8')\n\ncols = ['worst_case', 'industry', 'heuristic', 'optimized']\n\nfor p, policy in enumerate(cols):\n for i in range(order_streams.shape[0]):\n curr_inv = inv_and_orders.loc['inventory'].values \\\n + inv_and_orders.loc[policy].values\n t = 0\n while np.all(curr_inv >= 0):\n t += 1\n curr_inv[order_streams[i, t]] -= 1\n\n times_to_reorder[i, p] = t\n\ntimes_frame = pd.DataFrame(times_to_reorder, columns=cols)\n\nplt.style.use('seaborn-deep')\nbins = np.arange(0, 45)\n\nplt.hist(times_frame.values, bins, label=times_frame.columns)\nplt.legend(loc='upper right')\nplt.xlabel('Orders before the next re-order')\nplt.ylabel('Count of universes')\nplt.show()\n","repo_name":"ramanshahdatascience/tshirts","sub_path":"2023-02-23-talk/time_to_order_histograms/time_to_order_histograms.py","file_name":"time_to_order_histograms.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"4211499827","text":"import math\nfrom InvalidDim import InvalidDim\nclass Triangle:\n\n def __init__(self, a, b, c):\n '''\n Create a triangle with lengths greater than 0.\n '''\n try:\n if a <= 0 or b <= 0 or c <= 0:\n raise InvalidDim\n except InvalidDim:\n print(\"Invalid length.\")\n SystemExit(1)\n self.a = a\n self.b = b\n self.c = c\n\n def classify_triangle(self):\n result = \"\"\n\n if self.a != self.b and self.a != self.c and self.b != self.c:\n result = \"Scalene\"\n else:\n if self.a == self.b and self.a == self.c and self.b == self.c:\n result = \"Equilateral\"\n else:\n result = \"Isosceles\"\n return result\n\n def isRightTriangle(self):\n return round(((self.a**2) + (self.b**2)),2) == round((self.c**2),2)\n\n\n\n","repo_name":"rpatel1291/SSW567","sub_path":"Week 1/src/Triangle.py","file_name":"Triangle.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"7539215498","text":"import csv\nimport os\n\n\n# 各種出力ファイルのパス\ngroup_info_path = './result/group_information.csv'\nleague_match_result_path = './result/league_match_result.csv'\ntournament_result_path = './result/tournament_result.csv'\nmatch_history_path = './result/match_history.csv'\n\n\ndef output_group_info(groups):\n \"\"\" グループ、所属チームの情報をCSV形式で出力する \"\"\"\n\n with open(group_info_path, 'w') as f:\n writer = csv.writer(f)\n\n for group in groups:\n for team in group.teams:\n writer.writerow([team.id, group.id, team.name, team.rate]) # チームID, グループID, チーム名, レート\n\n\ndef output_leagu_match_result(i, groups):\n \"\"\" 各グループのリーグ戦の結果をCSV形式で出力する \"\"\"\n\n with open(league_match_result_path, 'a') as f:\n writer = csv.writer(f)\n\n writer.writerow([i]) # 試行回数\n for group in groups:\n print('\\n' + group.name)\n for team in group.teams:\n print('{0:5d} {1:15} {2:5d}'.format(team.id, team.name, team.points))\n writer.writerow([group.id, team.id, team.points]) # グループID, チームID, 勝点\n\n f.write('\\n')\n\n\ndef output_tournament_result(i, rounds):\n \"\"\" トーナメント戦の結果をCSV形式で出力する \"\"\"\n\n with open(tournament_result_path, 'a') as f:\n writer = csv.writer(f)\n\n writer.writerow([i]) # 試行回数\n for round in rounds:\n print([team.id for team in round.teams])\n writer.writerow([team.id for team in round.teams]) # 各ラウンドにいるチーム\n\n print([rounds[-1].winner_teams[0].id])\n writer.writerow([rounds[-1].winner_teams[0].id]) # 優勝チーム\n\n f.write('\\n')\n\n\ndef output_match_history_result(i, groups):\n \"\"\" チーム別の対戦成績をCSV形式で出力する \"\"\"\n\n with open(match_history_path, 'a') as f:\n writer = csv.writer(f)\n\n writer.writerow([i]) # 試行回数\n for group in groups:\n for team in group.teams:\n output = [team.id] + list([x for row in team.match_history for x in row])\n writer.writerow(output)\n\n f.write('\\n')\n\n\ndef remove_result_files():\n \"\"\" 各種結果出力ファイルを削除する \"\"\"\n\n if os.path.isfile(league_match_result_path):\n os.remove(league_match_result_path)\n if os.path.isfile(tournament_result_path):\n os.remove(tournament_result_path)\n if os.path.isfile(match_history_path):\n os.remove(match_history_path)\n","repo_name":"momoshiro407/world_cup_winner_simulator","sub_path":"file_controller.py","file_name":"file_controller.py","file_ext":"py","file_size_in_byte":2430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"10509212310","text":"# Level 1\n# 2021-09-09 23:16-23:28\n# https://programmers.co.kr/learn/courses/30/lessons/81301\n\nnum = {\"zero\":\"0\", \"one\":\"1\", \"two\":\"2\", \"three\":\"3\", \"four\":\"4\", \"five\":\"5\", \"six\":\"6\",\n \"seven\":\"7\", \"eight\":\"8\", \"nine\":\"9\"}\ns = \"one4seveneight\"\nfor i in num.keys():\n s= s.replace(i, num[i])\nprint(int(s))","repo_name":"yunyezl/algoitzman","sub_path":"cheongha/Programmers/숫자문자열과영단어.py","file_name":"숫자문자열과영단어.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"40"} +{"seq_id":"29437372950","text":"\"\"\"\r\nYou are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.\r\nReturn the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0.\r\nYou may assume that you have an infinite number of each kind of coin.\r\nThe answer is guaranteed to fit into a signed 32-bit integer.\r\n\r\nExample 1:\r\n\r\nInput: amount = 5, coins = [1,2,5]\r\nOutput: 4\r\nExplanation: there are four ways to make up the amount:\r\n5=5\r\n5=2+2+1\r\n5=2+1+1+1\r\n5=1+1+1+1+1\r\nExample 2:\r\n\r\nInput: amount = 3, coins = [2]\r\nOutput: 0\r\nExplanation: the amount of 3 cannot be made up just with coins of 2.\r\nExample 3:\r\n\r\nInput: amount = 10, coins = [10]\r\nOutput: 1\r\n\r\nUSING BOTTOMUP APPROACH\r\n\"\"\"\r\n# Wallet[0] = [[]]\r\n\r\n# for l in Wallet[0]:\r\n# if 1 not in Wallet:\r\n# Wallet[1] = []\r\n# print(l)\r\n# temp = list(l)\r\n# temp.append(1)\r\n# Wallet[1].append(temp)\r\n# print(Wallet)\r\n\r\n# for l in Wallet[1]:\r\n# if 2 not in Wallet:\r\n# Wallet[2] = []\r\n# print(l)\r\n# temp = list(l)\r\n# temp.append(1)\r\n# Wallet[2].append(temp)\r\n# print(Wallet)\r\n\r\n# for l in Wallet[0]:\r\n# if 2 not in Wallet:\r\n# Wallet[2] = []\r\n# print(l)\r\n# temp = list(l)\r\n# temp.append(2)\r\n# Wallet[2].append(temp)\r\n# print(Wallet)\r\n\r\n'''\r\nThis below solution takes lots of time\r\n'''\r\ndef makeCoinChanges(amount, coins):\r\n #Only use to find minimum number of coins 1)comment the Wallet 2)Uncomment the M[] related code 3)return M[amount]\r\n #M = [amount+1]*(amount+1)\r\n #M[0] = 0\r\n\r\n \r\n Wallet = {}\r\n Wallet[0] = [[]]\r\n for j in range(1, amount+1):\r\n for i in range(0, len(coins)):\r\n if(coins[i]<=j and j-coins[i]>=0):\r\n remain_amount = j - coins[i]\r\n if j not in Wallet:\r\n Wallet[j] = []\r\n if remain_amount in Wallet:\r\n for a in Wallet[remain_amount]:\r\n temp = list(a)\r\n temp.append(coins[i])\r\n temp.sort()\r\n if temp not in Wallet[j]:\r\n Wallet[j].append(temp)\r\n print(Wallet)\r\n\r\n for keys,values in Wallet.items():\r\n print(keys)\r\n print(values)\r\n \r\n print(\"The number of ways to make an amount {} are/is {}\".format(amount, len(Wallet[amount])))\r\n\r\n'''\r\nLeetCode solution and it works\r\ndef change(self, amount: int, coins: List[int]) -> int:\r\n dp = [0]*(amount + 1)\r\n dp[0] = 1\r\n \r\n for i in range(len(coins)):\r\n for j in range(1, amount+1):\r\n if j-coins[i] >= 0:\r\n dp[j] += dp[j-coins[i]]\r\n return dp[amount]\r\n'''\r\n\r\n\r\namount = 5 \r\ncoins = [1,2,5]\r\nmakeCoinChanges(amount, coins)\r\n\r\n# amount = 5\r\n# coins = [2]\r\n# makeCoinChanges(amount, coins)\r\n\r\n# amount = 10\r\n# coins = [10]\r\n# makeCoinChanges(amount, coins)\r\n\r\n# amount = 10\r\n# coins = [5]\r\n# makeCoinChanges(amount, coins)\r\n\r\n# makeCoinChanges(500, [1,2,5])\r\n\r\n","repo_name":"anuragdogra2192/Data_structures_with_python3","sub_path":"dynamicProgramming/CoinChange2.py","file_name":"CoinChange2.py","file_ext":"py","file_size_in_byte":3134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"20114527123","text":"#Read puzzle input, striping white space and splitting moves by new line. \nwith open(\"puzzle_input.txt\") as f:\n moves = f.read().strip().split(\"\\n\")\n\n#define puzzle start point for head and tail\nhead_x, head_y = 0, 0\ntail_x, tail_y = 0, 0\n\n\n#touching\n\n#movement dictionary\nmm = {\n \"R\": [1,0],\n \"U\": [0,1],\n \"L\": [-1,0],\n \"D\": [0,-1]\n}\n","repo_name":"nickbru/advent-of-code-2022","sub_path":"day9/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"19777072000","text":"import pandas as pd\n\ndef getActualPriceValidationValues(pbldbConn, skuNumbers):\n str = \"\"\n counter = skuNumbers.size\n for i in skuNumbers:\n str = str + \"'\" + i + \"'\"\n counter = counter - 1\n if counter > 0:\n str = str + \",\"\n query = \"select bfid, price_value, sale_price_value, price_currency from pbl_cat_item where bfid in ( %s )\" % (str)\n df = pd.read_sql_query(query, pbldbConn)\n # print (df)\n return df\n\ndef getActualInventoryValidationValues(pbldbConn, skuNumbers):\n str = \"\"\n counter = skuNumbers.size\n for i in skuNumbers:\n str = str + \"'\" + i + \"'\"\n counter = counter - 1\n if counter > 0:\n str = str + \",\"\n query = \"select bfid, quantity, merchant_quantity from pbl_cat_item where bfid in (\" + str + \")\"\n df = pd.read_sql_query(query, pbldbConn)\n return df\n\ndef getInventoryThresholdValue (pbldbConn, merchantID):\n query = \"SELECT inventory_threshold FROM pbl.pbl_product_type_inventory_threshold where bf_merchant_id=\" + str(merchantID)\n invThreshold = pd.read_sql_query(query, pbldbConn)\n return invThreshold","repo_name":"ckapil/PythonTestFramework","sub_path":"CMPTestAutomation/Utils/PrepActualData.py","file_name":"PrepActualData.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"70736213560","text":"\"\"\"\ninteractive.py:\nSetup an interesting interactive env in which to play\nand try out new features.\nThis just uses agent, composite, and itime.\nWe're going to do \"bad\" import *s here because this isn't \"real\"\ncode, just a playground for experimenting.\n\"\"\"\n\nfrom lib.env import *\nfrom lib.tests.test_composite import *\n\nnewton = create_newton()\nleibniz = create_leibniz()\nhardy = create_hardy()\nramanujan = create_ramanujan()\nlittlewood = create_littlewood()\nramsey = create_ramsey()\ncalc = newton + leibniz\ncamb = create_cambguys()\nalt_camb = newton + hardy\nmaths = create_mathguys()\ngauss = Agent(\"Gauss\")\neuler = Agent(\"Euler\")\nlaplace = Agent(\"Laplace\")\ngermans = Group(\"Germans\", members=[gauss, euler])\n\nprint(\"Gauss in Germans = \", germans.ismember(str(gauss)))\n\nmaths += germans\nmath_hist = Env(\"History\", members=[maths])\n","repo_name":"gcallah/IndraABM","sub_path":"lib/interactive.py","file_name":"interactive.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"42581229424","text":"import sys, os, math\n\ntry:\n from jkPyLaTeX import TikzPicture, litBasico\n from jkPyLaTeX import CircleTikz\nexcept:\n #Configura para que el paquete jkPyLaTeX sea visible\n #Obtiene directorio relativo donde esta el archivo\n quitar=__file__.replace('/'+__file__.split('/')[-1],'')\n #Obtiene el directorio absoluto\n dir_path = os.path.dirname(os.path.realpath(__file__))\n #Elimina el subdirectorio\n dir_path=dir_path.replace(quitar,'')\n # Agrega el directorio desde donde se invoca el script para tener \n # acceso a los módulos disponibles en el mismo\n sys.path.insert(0,dir_path)\n \n from jkPyLaTeX import TikzPicture, litBasico\n from jkPyLaTeX import CircleTikz\n\n\n#Crea el documento\nfig=litBasico('nombreFigura')\n\n#Obtiene una instancia para manejar el entorno de tikzpicture\ntikzpicture=TikzPicture()\n#Crea una instancia para dibujar un círculo con parámetros por defecto\ncircle=CircleTikz(env=tikzpicture)\n#Crea una instancia para dibujar rellenando la figura con color azul\ncircle2=CircleTikz(env=tikzpicture,fill_color='blue')\n#dibuja un círuclo con centro en (1,1) cuyo radio es 1\ncircle((1,1),1)\n#Segúndo círculo que se rellena con color azul\ncircle2((2,1),1)\n\n#Genera el codigo del gráfico y se guarda en el documento\nfig(tikzpicture())\n\n#Guarda el documento latex\nfig.save('./')\n#Compila el código\nfig.genDoc(target=True)\n","repo_name":"carloskl12/jkPyLaTeX","sub_path":"example/figBasica.py","file_name":"figBasica.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"28878202801","text":"#################################################\n# File Name:merge.py\n# Author: xingpengwei\n# Mail: xingpengwei@novogene.com\n# Created Time: Sun 24 Mar 2019 09:00:38 PM CST\n#################################################\n\nimport sys\nimport numpy as np\nf1 = open('all.txt','r')\nf2 = open('merge.txt','w')\nname = []\nsize = []\nfor line in f1:\n line = line.strip()\n line1 = line.split()\n name.append(line1[0])\n size.append(line1[1])\nuniq_name =list(set(name))\nallsize2 = sum([int(aa) for aa in size])\nname_array=np.array(name)\nsize_array=np.array(size)\nmydict2 = {}\nfor each in uniq_name:\n myindex=np.where(name_array==each)[0]\n mysize = size_array[myindex]\n allsize=sum([int(temp) for temp in mysize])\n mydict2[each]=allsize\nmydict2_sorted = sorted(mydict2.items(),key=lambda x:x[1],reverse=True)\nmydict2_sorted.append(('SUM',allsize2))\nfor key,value in mydict2_sorted:\n allsize = value\n if int(allsize) <=1024:\n hsize=str('%.3f' % (int(allsize)))+'KB'\n elif 1024 < int(allsize) <=1024**2:\n hsize=str('%.3f' % (int(allsize)/1024))+'M'\n elif 1024**2 < int(allsize) <=1024**3:\n hsize=str('%.3f' % (int(allsize)/(1024**2)))+'G'\n else:\n hsize=str('%.3f' % (int(allsize)/1024**3))+'T'\n f2.write('%s,%s\\n' % (key,hsize))\nf1.close()\nf2.close()\n","repo_name":"wan230114/mytools","sub_path":"other/test/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"28724353628","text":"from jira import JIRA\n\njira_connection = JIRA(\n basic_auth=('daniela.decoud@gmail.com', 'k'),\n server=\"https://danidq.atlassian.net\"\n)\n# Create a new epic with the given name and description\nticket_options = {\n 'project': {'key': 'PROD'},\n 'summary': 'Plan de retiro anticipado',\n 'description': 'Plan de retiro anticipado',\n 'issuetype': {'name': 'Epic'},\n 'customfield_10011': 'Plan de retiro anticipado'\n}\n\nepic = jira_connection.create_issue(fields=ticket_options)\n\n# Add the specified issues to the epic\njira_connection.add_issues_to_epic(epic_id=epic.id, issue_keys=[\"PROD-1\",\"PROD-2\",\"PROD-3\"])\n","repo_name":"ddecoud/jira-create_epic","sub_path":"jira-create_epic.py","file_name":"jira-create_epic.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"38829717918","text":"from django.shortcuts import render\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nfrom rest_framework import status\nfrom .models import Board\nfrom .serializers import BoardSerializer\n\n# Create your views here.\n@api_view(['GET'])\ndef hello(request):\n return Response(\"Hello World!\")\n\n\n@api_view(['GET'])\ndef board_list(request):\n datas = Board.objects.all()\n serializer = BoardSerializer(datas, many=True)\n\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\ndef board(request, board_no):\n datas = Board.objects.filter(board_no=board_no)\n serializer = BoardSerializer(datas, many=True)\n\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\n@api_view(['POST'])\ndef board_create(request):\n serializer = BoardSerializer(data=request.data)\n\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['PUT'])\ndef board_update(request):\n params = request.data\n data = Board.objects.filter(board_no=params['board_no']).first()\n serializer = BoardSerializer(instance=data, data=params)\n\n if serializer.is_valid():\n serializer.save()\n\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['DELETE'])\ndef board_delete(request, board_no):\n data = Board.objects.get(board_no=board_no)\n data.delete()\n\n return Response(status=status.HTTP_204_NO_CONTENT)","repo_name":"junglestory/django-restapi-pg","sub_path":"restapi/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"3749495013","text":"#Chanbroset, Andreas, Bryan\nfrom umqtt.robust import MQTTClient\nimport machine as m\nimport ubinascii\nimport network\nimport time\nimport dht\nfrom machine import Pin\nfrom time import sleep\n\nsta_if = network.WLAN(network.STA_IF); sta_if.active(True)\nsta_if.scan() # Scan for available access points\nsta_if.active(True)\nsta_if.connect(\"ELIJAH-WIFI\", \"\") # Connect to an AP\nsta_if.isconnected()\ntime.sleep(3)\n\nubidotsToken = \"BBFF-SPONj6AlHG36Okio1VdmISf9jX55G2\"\nclientID = ubinascii.hexlify(m.unique_id())\nclient = MQTTClient(\"clientID\", \"industrial.api.ubidots.com\", 1883, user = ubidotsToken, password = ubidotsToken)\n\ndef checkwifi():\n while not sta_if.isconnected():\n time.sleep_ms(500)\n print(\"Connecting WiFI failed\")\n sta_if.connect()\n\n\ndef publish():\n zzzz = 25\n while True:\n checkwifi()\n client.connect()\n zzzz = (zzzz + 4) % 50\n if zzzz < 20:\n zzzz += 20\n print(\"zzzzerature: \", zzzz, \"°C\")\n sleep(1)\n msg = b'{\"zzzz\":%s, \"str\":%s}' % (zzzz, b'asdf')\n print(msg)\n client.publish(b\"/v1.6/devices/ESP32\", msg)\n time.sleep(10)\n\npublish()\n\n","repo_name":"nonwiz0/esp32","sub_path":"trafficoptimizer/ubidot.py","file_name":"ubidot.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"71530141559","text":"\nfrom langchain.agents import tool\n\n@tool\ndef count_letters(city: str) -> int:\n \"\"\"Count the letters in a given city name\"\"\"\n count = 0\n for char in city:\n if char.isalpha():\n count += 1\n return count","repo_name":"currentdivider/dress-for-weather","sub_path":"tools/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"40203764452","text":"import os\nimport argparse\nimport logging\n\nfrom twilio.rest import Client\n\nfrom speller_agent import SpellerAgentFactory\n\naccount_sid = os.getenv('TWILIO_ACCOUNT_SID', None)\nauth_token = os.getenv('TWILIO_AUTH_TOKEN', None)\n\nclient = Client(account_sid, auth_token)\n\nfrom vocode.streaming.models.telephony import TwilioConfig\nfrom vocode.streaming.telephony.config_manager.redis_config_manager import (\n RedisConfigManager,\n)\nfrom vocode.streaming.models.agent import ChatGPTAgentConfig\nfrom vocode.streaming.models.message import BaseMessage\nfrom vocode.streaming.telephony.server.base import (\n TwilioInboundCallConfig,\n TelephonyServer,\n)\n\nimport uvicorn\n\nfrom fastapi import FastAPI, Response, status\nfrom fastapi.middleware.cors import CORSMiddleware\n\n\nfrom sl_agent import SmartloopAgentFactory\n\napp = FastAPI()\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=['*'],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\nlogging.basicConfig()\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\nBASE_URL = os.getenv(\"BASE_URL\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Assort Health')\n\n parser.add_argument('command', metavar='', choices=['server'],\n help='server')\n\n args = parser.parse_args()\n\n config_manager = RedisConfigManager()\n\n telephony_server = TelephonyServer(\n base_url=BASE_URL,\n config_manager=config_manager,\n inbound_call_configs=[\n TwilioInboundCallConfig(\n url=\"/inbound_call\",\n agent_config=ChatGPTAgentConfig(\n initial_message=BaseMessage(text=\"Hello welcome to Assort Health\"),\n prompt_preamble=\"Book an appointment\",\n generate_responses=True,\n ),\n twilio_config=TwilioConfig(\n account_sid=os.environ[\"TWILIO_ACCOUNT_SID\"],\n auth_token=os.environ[\"TWILIO_AUTH_TOKEN\"],\n ),\n )\n ],\n agent_factory=SpellerAgentFactory(),\n logger=logger,\n )\n\n app.include_router(telephony_server.get_router())\n\n if args.command == 'server':\n uvicorn.run(app, host=\"0.0.0.0\", port=3000)\n\n\n","repo_name":"mehfuzh/gpt-appointment","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"16488477061","text":"\"\"\"\nContains locations class/helper functions to define\nthe locations of the game.\n\"\"\"\nfrom tkinter import *\nfrom utility import *\n\n\nclass Location:\n \"\"\"Class to define the locations in the Adventure Game.\"\"\"\n def __init__(self, canvas, room_description, top_room, bottom_room,\n left_room, right_room):\n \"\"\"\n Initializes the basic features of a room. utilized in the add\n locations function.\n \"\"\"\n self.canvas = canvas\n self.room_description = room_description\n self.top_room = top_room\n self.bottom_room = bottom_room\n self.left_room = left_room\n self.right_room = right_room\n\ndef add_locations(root):\n \"\"\"\n Funciton to return locations in the game in a dictionary to\n be utilized in the game class.\n \"\"\"\n\n # Initialize dictionary of locaitons\n locations_dict = {}\n\n # Initialize the Great Hall\n great_hall_description = \"You have entered the Great Hall!\"\n\n great_hall_top_room = \"None\"\n great_hall_bottom_room = \"Main Entrance\"\n great_hall_left_room = \"None\"\n great_hall_right_room = \"None\"\n\n great_hall = Location(Canvas(root, width=window_width,\n height=window_height, bg=\"wheat2\"), great_hall_description,\n great_hall_top_room, great_hall_bottom_room, great_hall_left_room,\n great_hall_right_room)\n\n # Add house tables to the Great Hall\n great_hall.canvas.create_rectangle(100, 250, 175 , 500, fill=\"MistyRose4\")\n great_hall.canvas.create_rectangle(275, 250, 350, 500, fill=\"MistyRose4\")\n great_hall.canvas.create_rectangle(450, 250, 525, 500, fill=\"MistyRose4\")\n great_hall.canvas.create_rectangle(625, 250, 700, 500, fill=\"MistyRose4\")\n\n # Making the walls of the great hall\n right_wall = great_hall.canvas.create_rectangle(window_width, 0,\n window_width + 10, window_height, fill=\"white\")\n left_wall = great_hall.canvas.create_rectangle(-10, 0, 0, window_height,\n fill=\"white\")\n top_wall = great_hall.canvas.create_rectangle(0, -10,\n window_width, 0, fill=\"white\")\n bottom_wall_left = great_hall.canvas.create_rectangle(0, window_height,\n left_door_boundary, window_height, fill=\"white\")\n bottom_wall_right = great_hall.canvas.create_rectangle(right_door_boundary,\n window_height, window_width, window_height, fill=\"white\")\n\n # Add high table to the great hall\n great_hall.canvas.create_rectangle(200, 50, 600, 125, fill=\"MistyRose4\")\n\n # Add great_hall to the dictionary of locations\n locations_dict[\"Great Hall\"] = great_hall\n\n # Initialize the main entrance\n main_entrance_description = \"You have now entered the Main Entrance!\"\n\n main_entrance_top_room = \"Great Hall\"\n main_entrance_bottom_room = \"Upstairs Corridor\"\n main_entrance_right_room = \"Hagrid's Hut\"\n main_entrance_left_room = \"Dungeons\"\n\n main_entrance = Location(Canvas(root, width=window_width,\n height=window_height, bg=\"wheat2\"), main_entrance_description,\n main_entrance_top_room, main_entrance_bottom_room,\n main_entrance_left_room, main_entrance_right_room)\n\n # Making the walls of the main entrance\n right_wall_top = main_entrance.canvas.create_rectangle(window_width,0,window_width+10,\n upper_door_boundary, fill=\"white\")\n right_wall_bottom = main_entrance.canvas.create_rectangle(window_width,\n lower_door_boundary,window_width+10,window_height, fill=\"white\")\n left_wall_top = main_entrance.canvas.create_rectangle(-10,0,0,\n upper_door_boundary, fill=\"white\")\n left_wall_bottom = main_entrance.canvas.create_rectangle(-10,lower_door_boundary,0,\n window_height, fill=\"white\")\n top_wall_left = main_entrance.canvas.create_rectangle(0, 0,\n left_door_boundary, 0, fill=\"white\")\n top_wall_right = main_entrance.canvas.create_rectangle(right_door_boundary,\n 0, window_width, 0, fill=\"white\")\n bottom_wall_left = main_entrance.canvas.create_rectangle(0, window_height,\n left_door_boundary, window_height, fill=\"white\")\n bottom_wall_right = main_entrance.canvas.create_rectangle(right_door_boundary,\n window_height, window_width, window_height, fill=\"white\")\n\n # Add main entrance to the dictionary of locations\n locations_dict[\"Main Entrance\"] = main_entrance\n\n # Initialize the Dungeons\n dungeons_description = \"You have now entered the Dungeons!\"\n\n # Set adjacent rooms\n dungeons_top_room = \"None\"\n dungeons_left_room = \"None\"\n dungeons_right_room = \"Main Entrance\"\n dungeons_bottom_room = \"Upstairs Corridor\"\n\n dungeons = Location(Canvas(root, width=window_width, height=window_height,\n bg=\"dark grey\"), dungeons_description, dungeons_top_room,\n dungeons_bottom_room, dungeons_left_room, dungeons_right_room)\n\n # Set the walls\n left_wall = dungeons.canvas.create_rectangle(-10, 0, 0, window_height,\n fill=\"white\")\n top_wall = dungeons.canvas.create_rectangle(0, -10,\n window_width, 0, fill=\"white\")\n bottom_wall = dungeons.canvas.create_rectangle(0, window_height,\n window_width, window_height, fill=\"white\")\n right_wall_top = dungeons.canvas.create_rectangle(window_width,0,window_width+10,\n upper_door_boundary, fill=\"white\")\n right_wall_bottom = dungeons.canvas.create_rectangle(window_width,\n lower_door_boundary,window_width+10,window_height, fill=\"white\")\n\n # Add dungeons to the list of locations\n locations_dict[\"Dungeons\"] = dungeons\n\n # Initialize Hagrid's Hut\n hagrids_hut_description = \"You are now at Hagrid's Hut!\"\n\n # Set adjacent rooms\n hagrids_hut_top_room = \"None\"\n hagrids_hut_left_room = \"Main Entrance\"\n hagrids_hut_right_room = \"None\"\n hagrids_hut_bottom_room = \"None\"\n\n hagrids_hut = Location(Canvas(root, width=window_width,\n height=window_height, bg=\"dark olive green\"), hagrids_hut_description,\n hagrids_hut_top_room, hagrids_hut_bottom_room, hagrids_hut_left_room,\n hagrids_hut_right_room)\n\n # Making the walls\n top_wall = hagrids_hut.canvas.create_rectangle(0, -10,\n window_width, 0, fill=\"white\")\n bottom_wall = hagrids_hut.canvas.create_rectangle(0, window_height,\n window_width, window_height, fill=\"white\")\n right_wall = hagrids_hut.canvas.create_rectangle(window_width, 0,\n window_width + 10, window_height, fill=\"white\")\n left_wall_top = hagrids_hut.canvas.create_rectangle(-10,0,0,\n upper_door_boundary, fill=\"white\")\n left_wall_bottom = hagrids_hut.canvas.create_rectangle(-10,lower_door_boundary,0,\n window_height, fill=\"white\")\n\n # Add Hagrids Hut to the dict of locations\n locations_dict[\"Hagrid's Hut\"] = hagrids_hut\n\n # Initialize upstairs corridor\n upstairs_corridor_description = \"You have now entered the Upstairs Corridor!\"\n\n # Set adjacent rooms\n upstairs_corridor_top_room = \"Main Entrance\"\n upstairs_corridor_left_room = \"Room of Requirement\"\n upstairs_corridor_right_room = \"Ravenclaw Common Room\"\n upstairs_corridor_bottom_room = \"Gryffindor Common Room\"\n\n upstairs_corridor = Location(Canvas(root, width=window_width,\n height=window_height, bg=\"wheat2\"), upstairs_corridor_description,\n upstairs_corridor_top_room, upstairs_corridor_bottom_room,\n upstairs_corridor_left_room, upstairs_corridor_right_room)\n\n # Making the walls\n right_wall_top = upstairs_corridor.canvas.create_rectangle(window_width,0,window_width+10,\n upper_door_boundary, fill=\"white\")\n right_wall_bottom = upstairs_corridor.canvas.create_rectangle(window_width,\n lower_door_boundary,window_width+10,window_height, fill=\"white\")\n left_wall_top = upstairs_corridor.canvas.create_rectangle(-10,0,0,\n upper_door_boundary, fill=\"white\")\n left_wall_bottom = upstairs_corridor.canvas.create_rectangle(-10,lower_door_boundary,0,\n window_height, fill=\"white\")\n top_wall_left = upstairs_corridor.canvas.create_rectangle(0, 0,\n left_door_boundary, 0, fill=\"white\")\n top_wall_right = upstairs_corridor.canvas.create_rectangle(right_door_boundary,\n 0, window_width, 0, fill=\"white\")\n bottom_wall_left = upstairs_corridor.canvas.create_rectangle(0, window_height,\n left_door_boundary, window_height, fill=\"white\")\n bottom_wall_right = upstairs_corridor.canvas.create_rectangle(right_door_boundary,\n window_height, window_width, window_height, fill=\"white\")\n\n # Add upstairs corridor to locations dictionary\n locations_dict[\"Upstairs Corridor\"] = upstairs_corridor\n\n # Initialize the Room of Requirement\n room_requirement_description = \"You have now entered the Room of Requirement!\"\n\n # Set adjacent rooms\n room_requirement_top_room = \"None\"\n room_requirement_left_room = \"None\"\n room_requirement_right_room = \"Upstairs Corridor\"\n room_requirement_bottom_room = \"None\"\n\n room_requirement = Location(Canvas(root, width=window_width,\n height=window_height, bg=\"burlywood4\"), room_requirement_description,\n room_requirement_top_room, room_requirement_bottom_room,\n room_requirement_left_room, room_requirement_right_room)\n\n # Making the walls\n left_wall = room_requirement.canvas.create_rectangle(-10, 0, 0, window_height,\n fill=\"white\")\n top_wall = room_requirement.canvas.create_rectangle(0, -10,\n window_width, 0, fill=\"white\")\n bottom_wall = room_requirement.canvas.create_rectangle(0, window_height,\n window_width, window_height, fill=\"white\")\n right_wall_top = room_requirement.canvas.create_rectangle(window_width,0,window_width+10,\n upper_door_boundary, fill=\"white\")\n right_wall_bottom = room_requirement.canvas.create_rectangle(window_width,\n lower_door_boundary,window_width+10,window_height, fill=\"white\")\n\n # Add room of requirement to the dict of locations\n locations_dict[\"Room of Requirement\"] = room_requirement\n\n # Initialize Ravenclaw Common Room\n ravenclaw_common_room_description = \"You have now entered the Ravenclaw Common Room!\"\n\n # Set Adjacent rooms\n ravenclaw_top_room = \"None\"\n ravenclaw_left_room = \"Upstairs Corridor\"\n ravenclaw_right_room = \"None\"\n ravenclaw_bottom_room = \"None\"\n\n ravenclaw_common_room = Location(Canvas(root, width=window_width,\n height=window_height, bg=\"LightBlue3\"), ravenclaw_common_room_description,\n ravenclaw_top_room, ravenclaw_bottom_room, ravenclaw_left_room,\n ravenclaw_right_room)\n\n # Making the walls\n top_wall = ravenclaw_common_room.canvas.create_rectangle(0, -10,\n window_width, 0, fill=\"white\")\n bottom_wall = ravenclaw_common_room.canvas.create_rectangle(0, window_height,\n window_width, window_height, fill=\"white\")\n right_wall = ravenclaw_common_room.canvas.create_rectangle(window_width, 0,\n window_width + 10, window_height, fill=\"white\")\n left_wall_top = ravenclaw_common_room.canvas.create_rectangle(-10,0,0,\n upper_door_boundary, fill=\"white\")\n left_wall_bottom = ravenclaw_common_room.canvas.create_rectangle(-10,lower_door_boundary,0,\n window_height, fill=\"white\")\n\n # Add ravenclaw common room to dict of locations\n locations_dict[\"Ravenclaw Common Room\"] = ravenclaw_common_room\n\n # Initialize Gryffindor Common Room\n gryffindor_common_room_description = \"You have now entered the Gryffindor Common Room!\"\n\n # Set Adjacent Rooms\n gryffindor_top_room = \"Upstairs Corridor\"\n gryffindor_left_room = \"None\"\n gryffindor_right_room = \"None\"\n gryffindor_bottom_room = \"None\"\n\n gryffindor_common_room = Location(Canvas(root, width=window_width,\n height=window_height, bg=\"firebrick4\"), gryffindor_common_room_description,\n gryffindor_top_room, gryffindor_bottom_room, gryffindor_left_room,\n gryffindor_right_room)\n\n # Setting up the walls\n bottom_wall = gryffindor_common_room.canvas.create_rectangle(0, window_height,\n window_width, window_height, fill=\"white\")\n right_wall = gryffindor_common_room.canvas.create_rectangle(window_width, 0,\n window_width + 10, window_height, fill=\"white\")\n left_wall = gryffindor_common_room.canvas.create_rectangle(-10, 0, 0, window_height,\n fill=\"white\")\n top_wall_left = gryffindor_common_room.canvas.create_rectangle(0, 0,\n left_door_boundary, 0, fill=\"white\")\n top_wall_right = gryffindor_common_room.canvas.create_rectangle(right_door_boundary,\n 0, window_width, 0, fill=\"white\")\n\n # Add Gryffindor Common Room to locations dict\n locations_dict[\"Gryffindor Common Room\"] = gryffindor_common_room\n\n #Return the completed dictionary of locations\n return locations_dict\n","repo_name":"mattmeyerink/Adventure_Game","sub_path":"locations.py","file_name":"locations.py","file_ext":"py","file_size_in_byte":14000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"36441944644","text":"# import sympy\n\nN = int(input())\n\n\n\ndef divisor(n):\n i = 1\n table = []\n while i * i <= n:\n if n % i == 0:\n table.append(i)\n table.append(n // i)\n i += 1\n table = list(set(table))\n return table\n\n# a = sympy.divisors(N)\n\nprint(sorted(divisor(N)))\n\n\n","repo_name":"poponzu/atcoder1","sub_path":"atcoder/ABC/169/169d.py","file_name":"169d.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"39457671370","text":"# 给一个正整数,输出他的下一个排列\n\n\nclass nextNumber:\n def getNextNumber(self, nums):\n n = len(nums)\n i = n-2\n while i >= 0 and nums[i] >= nums[i+1]:\n i -= 1\n if i >= 0:\n j = n-1\n while j >= 0 and nums[i] >= nums[j]:\n j -= 1\n nums[i], nums[j] = nums[j], nums[i]\n elif i == -1:\n return ['-1']\n left, right = i+1, n-1\n while left < right:\n nums[left], nums[right] = nums[right], nums[left]\n left += 1\n right -= 1\n return nums\n\n\nc = nextNumber()\na = [1234, 4321, 4312, 2302431]\nfor i in a:\n i = list(str(i))\n b = c.getNextNumber(i)\n b = int(''.join(b))\n print(b)\n","repo_name":"imlauzh/LeetCode","sub_path":"Exams/百度/0831/下一个排列.py","file_name":"下一个排列.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"30680369","text":"import matplotlib.pyplot as plt\nimport matplotlib\nimport numpy as np\nfrom config import *\nfrom matplotlib.widgets import Slider,Button,CheckButtons\n#from analyzeData import calcDensity,calcVolUptake\nmatplotlib.use(\"TkAgg\")\ndef getMinMax(press):\n min=1000\n max=-1\n for temp in press:\n T=float(temp)\n if T>max:\n max=T\n if T logging.Logger:\n logger = logging.getLogger(name)\n logger.setLevel(level)\n \"\"\"\n logger.propagate = False\n ch = logging.StreamHandler()\n ch.setLevel(level)\n formatter = logging.Formatter('[%(asctime)s][%(name)s][%(levelname)s] - %(message)s')\n ch.setFormatter(formatter)\n logger.handlers.clear()\n logger.addHandler(ch)\"\"\"\n\n return logger\n\n\ndef get_csv_logger(name=\"csv\", file_path='./results.csv', header='epoch,'\n 'train_loss_local,train_loss_global,train_acc,'\n 'valid_loss_local,valid_loss_global,valid_acc'):\n logger = logging.getLogger(name)\n logger.propagate = False\n logger.setLevel(logging.DEBUG)\n fh = logging.FileHandler(file_path)\n fh.setLevel(logging.DEBUG)\n logger.addHandler(fh)\n logger.info(header)\n\n return logger\n\n\ndef str_to_logging_level(str):\n if str.__contains__('debug') or str.__contains__('DEBUG'):\n return logging.DEBUG\n if str.__contains__('info') or str.__contains__('INFO'):\n return logging.INFO\n if str.__contains__('warning') or str.__contains__('WARNING'):\n return logging.WARNING\n if str.__contains__('error') or str.__contains__('ERROR'):\n return logging.ERROR\n if str.__contains__('critical') or str.__contains__('CRITICAL'):\n return logging.critical()\n\n raise ValueError(f'logging level {str} not known')\n\n\ndef retire_logger(logger):\n for handler in logger.handlers:\n try:\n handler.flush()\n handler.close()\n except AttributeError:\n pass\n logger.handlers.clear()\n del logger\n\n\ndef get_unique_save_path(path):\n\n split = path.split(\".\")\n if len(split) < 1:\n og_path = path\n og_end = \"\"\n else:\n og_path = \".\".join(split[:-1])\n og_end = f\".{split[-1]}\"\n i = 1\n\n while os.path.exists(path):\n path = og_path + f\"-{i}\" + og_end\n i += 1\n\n return path\n","repo_name":"bonfab/local-error-signals","sub_path":"src/utils/logging.py","file_name":"logging.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"11762138837","text":"import argparse\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.utils.data\n\nimport utils\nimport batcher\nfrom model import AcousticModel\nfrom logger import INIT_LOG, LOG_INFO\n\ntorch.manual_seed(1234)\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--n_labels\", default=5, type=int, help=\"Number of labels.\")\nparser.add_argument(\"--epochs\", default=25, type=int, help=\"Number of epochs.\")\nparser.add_argument(\"--data_balancing\",default=0,type=int,help=\"1 if balancing the training data\")\nparser.add_argument(\"--dropout\",default=0.5,type=float,help=\"dropout rate for final layer, default 0.5, put 0 for no dropout\")\nparser.add_argument(\"--optimizer\",default=\"SGD\",type=str,help=\"optimizer, Adam or SGD\")\n\nparser.add_argument(\"--num_frames\", default=500, type=int, help=\"Number of frames per sentence.\")\nparser.add_argument(\"--conv_channels\", default=256, type=int, help=\"Number of 1-D convolutional channels.\")\nparser.add_argument(\"--kernel_size\", default=5, type=int, help=\"Convolution kernel size.\")\nparser.add_argument(\"--mfcc\", default=13, type=int, help=\"Number of MFCC components.\")\nparser.add_argument(\"--output_dim\", default=128, type=int, help=\"Model output dim = FC output dim.\")\n\nparser.add_argument(\"--batch_size\", default=50, type=int, help=\"Batch size to use during training.\")\nparser.add_argument(\"--display_freq\", default=250, type=int, help=\"Display frequency\")\nparser.add_argument(\"--lr\", default=0.001, type=float, help=\"Learning rate for optimizer\")\nparser.add_argument(\"--log_file\", default='', type=str, help=\"Log file\")\nargs = parser.parse_args()\nprint(args)\n\nINIT_LOG(args.log_file)\n\n\n# ------- Data Loaders -----------------------------------\nfolders,data_folders = utils.folders_info()\n\nbatch_size = args.batch_size\ndatasets = batcher.initialize_datasets(folders,data_folders)\nclass_sample_count = [2940, 10557,5361,5618,50224]\nclass_weights = 1/torch.Tensor(class_sample_count)\n\ntrain_dataset,test_dataset,valid_dataset = datasets[0],datasets[1],datasets[2]\n\n\nsampler = None\nif args.data_balancing==1:\n train_weights = [class_weights[train_dataset.__getitem__(i)[2].item()] for i in range(len(train_dataset))]\n sampler = torch.utils.data.sampler.WeightedRandomSampler(train_weights,len(train_dataset))\n\ntrain_iterator = torch.utils.data.DataLoader(train_dataset,batch_size = batch_size,sampler = sampler)\ntest_iterator = torch.utils.data.DataLoader(test_dataset)\nvalid_iterator = torch.utils.data.DataLoader(valid_dataset)\n# --------------------------------------------------------------\n\ndevice = 'cuda'\n# ---------- Model Definition -----------\n\n\nmodel = nn.Sequential(\n AcousticModel(\n num_frames = args.num_frames,\n mfcc = args.mfcc,\n conv_channels = args.conv_channels,\n kernel_size = args.kernel_size,\n output_dim = args.output_dim,\n dropout=args.dropout\n ),\n nn.Dropout(p=args.dropout),\n nn.ReLU(),\n nn.Linear(args.output_dim,args.n_labels)).to(device)\n\n \ncriterion = nn.CrossEntropyLoss()\nif args.optimizer=='Adam':\n optimizer = optim.Adam(model.parameters(), lr=args.lr)\nelse:\n optimizer = optim.SGD(model.parameters(), lr=args.lr)\n# ----------------------------------------\n\ndef train(epoch, model, iterator, optimizer, criterion):\n loss_list = []\n acc_list = []\n\n model.train()\n\n for i, (audio,text,label) in enumerate(iterator):\n audio = audio.to(device)\n label = label.to(device)\n optimizer.zero_grad()\n predictions = model(audio)\n\n loss = criterion(predictions, label.long())\n loss.backward()\n optimizer.step()\n\n acc = (predictions.max(1)[1] == label.long()).float().mean()\n loss_list.append(loss.item())\n acc_list.append(acc.item())\n\n if i % args.display_freq == 0:\n msg = \"Epoch %02d, Iter [%03d/%03d], train loss = %.4f, train acc = %.4f\" % (\n epoch, i, len(iterator), np.mean(loss_list), np.mean(acc_list)\n )\n LOG_INFO(msg)\n loss_list.clear()\n acc_list.clear()\n\n\ndef evaluate(model, iterator, criterion):\n epoch_loss = 0\n epoch_acc = 0\n\n model.eval()\n\n with torch.no_grad():\n for (audio,text,label) in iterator:\n audio = audio.to(device)\n label = label.to(device)\n predictions = model(audio)\n loss = criterion(predictions, label.long())\n\n acc = (predictions.max(1)[1] == label.long()).float().mean()\n epoch_loss += loss.item()\n epoch_acc += acc.item()\n\n return epoch_loss / len(iterator), epoch_acc / len(iterator)\n\n\n\nbest_acc = 0\nbest_epoch = -1\nfor epoch in range(1, args.epochs + 1):\n train(epoch, model, train_iterator, optimizer, criterion)\n valid_loss, valid_acc = evaluate(model, valid_iterator, criterion)\n msg = '...Epoch %02d, val loss = %.4f, val acc = %.4f' % (\n epoch, valid_loss, valid_acc\n )\n LOG_INFO(msg)\n\n if valid_acc > best_acc:\n best_acc = valid_acc\n best_epoch = epoch\n torch.save(model.state_dict(), 'best-model_audio.pth')\n\nLOG_INFO('Test best model @ Epoch %02d' % best_epoch)\nmodel.load_state_dict(torch.load('best-model_audio.pth'))\ntest_loss, test_acc = evaluate(model, test_iterator, criterion)\nLOG_INFO('Finally, test loss = %.4f, test acc = %.4f' % (test_loss, test_acc))\n","repo_name":"hamzakeurti/dialogue-act-classification","sub_path":"baseline/run_acoustic.py","file_name":"run_acoustic.py","file_ext":"py","file_size_in_byte":5406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"24490820716","text":"import numpy as np\n\nfrom PyEMD import EEMD\nfrom PyEMD.experimental.jitemd import JitEMD, get_timeline\n\ns = np.random.random(100)\nt = get_timeline(len(s), s.dtype)\n\nemd = JitEMD()\neemd = EEMD(ext_EMD=emd)\nimfs = eemd(s, t)\n\nprint(imfs)\nprint(imfs.shape)\n","repo_name":"laszukdawid/PyEMD","sub_path":"example/jit_eemd_example.py","file_name":"jit_eemd_example.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","stars":767,"dataset":"github-code","pt":"40"} +{"seq_id":"31419166086","text":"#!/usr/bin/env/ python3\n\nemap = []\n\nwith open(\"inputs/input12.txt\") as f:\n for i, line in enumerate(f.readlines()):\n if 'S' in line:\n start = (i, line.find('S'))\n if 'E' in line:\n end = (i, line.find('E'))\n\n emap.append([ord(c) for c in line.strip()])\n\nemap[start[0]][start[1]] = ord('a')\nemap[end[0]][end[1]] = ord('z')\n\ndef neighbors(i, j):\n if i+1 < len(emap):\n yield (i+1, j)\n if i-1 >= 0:\n yield (i-1, j)\n if j+1 < len(emap[0]):\n yield (i, j+1)\n if j-1 >= 0:\n yield (i, j-1)\n\ndef print_map():\n for i, row in enumerate(emap):\n for j, x in enumerate(row):\n if (i, j) in visited:\n print(\".\", end='')\n elif (i, j) in checking:\n print(chr(x).upper(), end='')\n else:\n print(chr(x), end='')\n print()\n\nvisited = set()\nchecking = {start}\nsteps = 0\n\nwhile end not in checking:\n #print_map()\n #input()\n to_check = set()\n for i, j in checking:\n visited.add((i, j))\n for x, y in neighbors(i, j):\n if emap[x][y] - emap[i][j] <= 1 and (x, y) not in visited:\n to_check.add((x, y))\n steps += 1\n checking = to_check\n\nprint(steps)\n\nvisited = set()\nchecking = {end}\nsteps = 0\n\nwhile ord('a') not in [emap[i][j] for i, j in checking]:\n #print_map()\n #input()\n to_check = set()\n for i, j in checking:\n visited.add((i, j))\n for x, y in neighbors(i, j):\n if emap[x][y] - emap[i][j] >= -1 and (x, y) not in visited:\n to_check.add((x, y))\n steps += 1\n checking = to_check\n\nprint(steps)\n\n","repo_name":"AntonSedin/aoc-2022","sub_path":"aoc12.py","file_name":"aoc12.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"867848816","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef f(x):\n return 1 + 0.5*np.tanh(2*x)\n \nh = 0.5\n\nx = np.linspace(-2, 2, 100)\ndiff = (f(x + h/2) - f(x - h/2))/h\ndiff_a = -np.tanh(2*x)**2 + 1\n\nplt.figure()\nplt.plot(x, diff, label = 'Numerical')\nplt.plot(x, diff_a, label = 'Analytical')\nplt.xlabel('x')\nplt.legend(loc = 'best')\nplt.grid()\nplt.show()\n","repo_name":"ignaciop/python_varios","sub_path":"newman/ej515.py","file_name":"ej515.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"161871681","text":"from typing import List, Union # isort:skip\nfrom functools import partial\n\nimport torch\n\nfrom catalyst_rl.utils import get_activation_fn\n\n\ndef iou(\n outputs: torch.Tensor,\n targets: torch.Tensor,\n # values are discarded, only None check\n # used for compatibility with MultiMetricCallback\n classes: List[str] = None,\n eps: float = 1e-7,\n threshold: float = None,\n activation: str = \"Sigmoid\"\n) -> Union[float, List[float]]:\n \"\"\"\n Args:\n outputs (torch.Tensor): A list of predicted elements\n targets (torch.Tensor): A list of elements that are to be predicted\n eps (float): epsilon to avoid zero division\n threshold (float): threshold for outputs binarization\n activation (str): An torch.nn activation applied to the outputs.\n Must be one of [\"none\", \"Sigmoid\", \"Softmax2d\"]\n\n Returns:\n Union[float, List[float]]: IoU (Jaccard) score(s)\n \"\"\"\n activation_fn = get_activation_fn(activation)\n outputs = activation_fn(outputs)\n\n if threshold is not None:\n outputs = (outputs > threshold).float()\n\n # ! fix backward compatibility\n if classes is not None:\n # if classes are specified we reduce across all dims except channels\n _sum = partial(torch.sum, dim=[0, 2, 3])\n else:\n _sum = torch.sum\n\n intersection = _sum(targets * outputs)\n union = _sum(targets) + _sum(outputs)\n # this looks a bit awkward but `eps * (union == 0)` term\n # makes sure that if I and U are both 0, than IoU == 1\n # and if U != 0 and I == 0 the eps term in numerator is zeroed out\n # i.e. (0 + eps) / (U - 0 + eps) doesn't happen\n iou = (intersection + eps * (union == 0)) / (union - intersection + eps)\n\n return iou\n\n\njaccard = iou\n\n__all__ = [\"iou\", \"jaccard\"]\n","repo_name":"catalyst-team/catalyst-rl","sub_path":"catalyst_rl/utils/metrics/iou.py","file_name":"iou.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"42"} +{"seq_id":"9608078495","text":"import numpy as np\nfrom nltk.tokenize import RegexpTokenizer\nfrom sklearn.preprocessing import OneHotEncoder\nimport matplotlib.pyplot as plt\n\nclass word2vec() :\n\n # 토큰화 함수\n def _tokenizer(self, sent):\n retokenize = RegexpTokenizer(\"[\\w]+\")\n token_lst = retokenize.tokenize(sent)\n return token_lst\n\n # onehot_vector 만들기\n def onehot_vector(self, token_lst):\n enc = OneHotEncoder()\n token_array = np.asarray(token_lst).reshape(-1, 1)\n enc.fit(token_array)\n onehot = enc.transform(token_array)\n onehot_array = onehot.toarray()\n return enc, onehot, onehot_array\n\n # X, Y 만들기\n def _XY(self, onehot_array, window):\n X = []\n Y = []\n for idx in range(len(onehot_array)):\n target = onehot_array[idx]\n print(idx)\n for w in range(1, window+1):\n if idx-w >= 0:\n X.append(onehot_array[idx-w])\n Y.append(target)\n print(idx-w)\n else:\n pass\n try:\n X.append(onehot_array[idx+w])\n Y.append(target)\n print(idx+w)\n except:\n pass\n return np.asarray(X), np.asarray(Y)\n\n # 초기 weight 설정\n def _init_weights(self, onehot_array, n = 4):\n W1 = np.random.rand(onehot_array.shape[1], n)\n W2 = np.random.rand(n, onehot_array.shape[1])\n return W1, W2\n\n # softmax\n def _softmax(self, a):\n c = np.max(a)\n exp_a = np.exp(a-c)\n sum_exp_a = np.sum(exp_a)\n y = exp_a / sum_exp_a\n return y\n\n # loss 계산\n def _eval_loss (self, Y, Y_hat):\n L = -np.sum(self.Y*np.log(Y_hat))\n return L\n\n # gradient 계산\n def _gradients (self, Y_hat, weights):\n W1, W2 = weights\n W2_g = np.dot(self.H.T, (Y_hat-self.Y))\n W1_g = np.dot(self.X.T, np.dot((Y_hat-self.Y), W2.T))\n return W1_g, W2_g\n\n # 코사인 유사도 계산\n def cos_similarity(self, v1, v2):\n similarity = np.dot(v1, v2) / (np.sqrt(sum(np.square(v1))) * np.sqrt(sum(np.square(v2)))) \n return similarity\n\n # 최적화\n def optimize (self, sent, h = 4, window_size = 1, learning_rate = 0.1, epoch = 1000):\n # 토큰화\n token_lst = self._tokenizer(sent)\n \n # 초기값 설정\n enc, onehot, onehot_array = self.onehot_vector(token_lst)\n W1, W2 = self._init_weights(onehot_array, h)\n weights = W1, W2\n self.X, self.Y = self._XY(onehot_array, window_size)\n self.H = np.dot(self.X, W1)\n Z = np.dot(self.H, W2)\n Y_hat = np.apply_along_axis(self._softmax, 1, Z)\n\n # loss 저장용 리스트\n loss_lst = []\n\n # 웨이트 업데이트\n for n in range(epoch):\n\n # gradient 계산\n gradients = self._gradients(Y_hat, weights)\n\n # 업데이트\n for w, g in zip(weights, gradients):\n w -= learning_rate*g\n\n # 새롭게 Feedforward\n self.H = np.dot(self.X, W1)\n Z = np.dot(self.H, W2)\n # 각 array 별로 softmax 적용\n Y_hat = np.apply_along_axis(self._softmax, 1, Z)\n\n # 새로운 loss 계산\n L = self._eval_loss(self.Y, Y_hat)\n loss_lst.append(L)\n\n # 10번에 한 번 loss 출력\n if n%10==0:\n print(L)\n\n # 각 feature name과 임베딩 벡터 연결한 딕셔너리\n feature_name = [x[3:] for x in list(enc.get_feature_names())]\n w2v = {x:y for x, y in zip(feature_name, W1)}\n\n # 단어 임베딩 벡터 딕셔너리, loss 리스트 리턴\n return w2v, loss_lst\n\n\n\nif __name__ == \"__main__\" :\n w2v = word2vec()\n sent = 'you will never know until you try'\n word2vec, loss_lst = w2v.optimize(sent, h=4, learning_rate = 0.1, epoch = 10000)\n\n print(\"Word2Vec : {}\".format(word2vec))\n\n # Loss 그래프 출력\n x = [n for n in range(len(loss_lst))]\n plt.plot(x, loss_lst)\n plt.show()\n\n # 코사인 유사도 계산\n print('코사인 유사도:')\n print('you, will : {}'.format(w2v.cos_similarity(word2vec['you'], word2vec['will'])))\n print('never, try : {}'.format(w2v.cos_similarity(word2vec['never'], word2vec['try'])))\n","repo_name":"insightcampus/2020-inno-nlp-c-deeplearning","sub_path":"HyeonminNam/200814_word2vec_실습.py","file_name":"200814_word2vec_실습.py","file_ext":"py","file_size_in_byte":4424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"17043623128","text":"from selenium import webdriver\r\nimport time\r\nfrom bs4 import BeautifulSoup\r\nfrom selenium.webdriver.common.by import By\r\n# Khởi tạo trình duyệt Chrome\r\ndriver = webdriver.Chrome()\r\ndriver.get(\"https://pixabay.com/vi/music/\")\r\n# Tạm dừng 5 giây để trang tải và hiển thị kết quả\r\ntime.sleep(5)\r\n# Lấy mã HTML của trang hiện tại\r\nhtml = driver.page_source\r\nsoup = BeautifulSoup(html, \"html.parser\")\r\n#tìm nút play để kích vào\r\nplays=soup.find_all(\"button\", fdprocessedid=\"yji6\")\r\n#chạy từng nút play\r\nfor play in plays:\r\n play.click() #kích vào nút play\r\n Audio=soup.find(\"audio\") #sau khi ấn nút play sẽ hiện ra thanh audio\r\n file_mp3=Audio['src'] #lấy đường dẫn của file audio\r\n print(file_mp3)\r\n# Đóng trình duyệt\r\ndriver.quit()\r\n","repo_name":"ngquin102/project_crawl","sub_path":"link_audio.py","file_name":"link_audio.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"11851968896","text":"import sys\r\ninput = sys.stdin.readline\r\n\r\nxdict = {}\r\nydict = {}\r\nfor i in range(3):\r\n x, y = map(int, input().split())\r\n xdict[x] = xdict.get(x, 0) + 1\r\n ydict[y] = ydict.get(y, 0) + 1\r\nxlocation = 0\r\nylocation = 0\r\nfor i in xdict.items():\r\n if i[1] == 1:\r\n xlocation = i[0]\r\nfor j in ydict.items():\r\n if j[1] == 1:\r\n ylocation = j[0]\r\nprint(xlocation, ylocation)","repo_name":"kmk4162/TIL","sub_path":"백준/Bronze/3009. 네 번째 점/네 번째 점.py","file_name":"네 번째 점.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"42"} +{"seq_id":"3951748206","text":"import requests\nimport json\nfrom discord import Color, Embed, File\n\nfrom mpl_toolkits.basemap import Basemap\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef getStats():\n embed = Embed()\n \n try:\n ISSLocation = json.loads(requests.get(\"http://api.open-notify.org/iss-now.json\").content)\n SpaceHumans = json.loads(requests.get(\"http://api.open-notify.org/astros.json\").content)\n print(ISSLocation)\n\n except:\n embed.title = \"Failed to access space stats\"\n embed.color = 0xff0000\n return embed\n\n m = Basemap(projection='robin', lon_0=0, resolution='l')\n\n lats = [float(ISSLocation['iss_position']['latitude'])]\n lons = [float(ISSLocation['iss_position']['longitude'])]\n\n m.drawcountries(color='#ffffff', linewidth=0.5)\n m.fillcontinents(color='#c0c0c0', lake_color='#ffffff')\n\n x, y = m(lons, lats)\n plt.plot(x, y, \"bo\", color='#0000ff', markersize=5)\n\n plt.savefig(\"./data/TempData/ISSMap.png\")\n\n embed.color = 0x000033\n embed.title = \"Space\"\n embed.description = f\"The ISS is at {ISSLocation['iss_position']['latitude']} {ISSLocation['iss_position']['longitude']} and there is {SpaceHumans['number']} humans in space !\"\n\n\n HumansNames = \"\"\n HumansLocations = \"\"\n\n for human in SpaceHumans[\"people\"]:\n HumansNames += f\"{human['name']}\\n\"\n HumansLocations += f\"{human['craft']}\\n\"\n\n embed.add_field(name=\"Person Name\", value=HumansNames)\n embed.add_field(name=\"In\", value=HumansLocations)\n\n return embed","repo_name":"Camillewz24340/CamBot","sub_path":"commands/science/spacestats.py","file_name":"spacestats.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"28497707688","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# =============================================================================\n# @file rootshelve.py\n# \n# This is shelve-like database with ROOT.TFile as internal storage \n#\n# @see zipshelve\n# @see sqliteshelve\n#\n#\n# Create new DB:\n#\n# @code\n#\n# >>> import rootshelve as DBASE ## import the RootShelve module \n# >>> db = DBASE.open ('a_db', 'n') ## create new DB\n# ...\n# >>> abcde = ...\n# >>> db['some_key'] = abcde ## add information to DB\n# ...\n# >>> db.close()\n#\n# @endcode \n#\n# Access to DB in read-only mode :\n#\n# @code\n#\n# >>> import rootshelve as DBASE ## import the ZipShelve module \n# >>> db = DBASE.open ('a_db' , 'r' ) ## access existing dbase in read-only mode\n# ...\n# >>> for key in db : print(key)\n# ...\n# >>> abcd = db['some_key']\n#\n# @endcode \n#\n# Access existing DB in update mode :\n#\n# @code\n#\n# >>> import rootshelve as DBASE ## import the ZipShelve module \n# >>> db = DBASE.open ('a_db' ) ## access existing dbase in update mode\n# ...\n# >>> for key in db : print(key)\n# ...\n# >>> abcd = db['some_key']\n#\n# @endcode \n#\n# @author Vanya BELYAEV Ivan.Belyaev@cern.ch\n# @date 2015-07-31\n# \n# =============================================================================\n\"\"\" This is ROOT-based version of shelve database.\n\n Create new DB:\n\n >>> import rootshelve as DBASE ## import the ZipShelve module \n >>> db = DBASE.open ('a_db', 'n') ## create new DB\n ...\n >>> abcde = ...\n >>> db['some_key'] = abcde ## add information to DB\n ...\n >>> db.close()\n\n Access to DB in read-only mode :\n\n >>> import rootshelve as DBASE ## import the ZipShelve module \n >>> db = DBASE.open ('a_db' , 'r' ) ## access existing dbase in read-only mode\n ...\n >>> for key in db : print(key)\n ...\n >>> abcd = db['some_key']\n\n Access existing DB in update mode :\n\n >>> import rootshelve as DBASE ## import the RootShelve module \n >>> db = DBASE.open ('a_db' ) ## access existing dbase in update mode\n ...\n >>> for key in db : print(key)\n ...\n >>> abcd = db['some_key']\n \n\"\"\"\n# =============================================================================\n__author__ = \"Vanya BELYAEV Ivan.Belyaev@itep.ru\"\n__date__ = \"2015-07-31\"\n__version__ = \"$Revision$\" \n# =============================================================================\n__all__ = (\n 'RootShelf' , ## The DB-itself\n 'RootOnlyShelf' , ## \"data base\" for ROOT-only objects\n 'open' , ## helper function to hide the actual DB\n 'tmpdb' , ## helper function to create TEMPORARY RootShelve database \n )\n# =============================================================================\nfrom ostap.logger.logger import getLogger\nif '__main__' == __name__ : logger = getLogger ( 'ostap.io.rootshelve' )\nelse : logger = getLogger ( __name__ )\n# =============================================================================\nimport ROOT, shelve, zlib\nimport ostap.io.root_file \nfrom sys import version_info as python_version \nlogger.debug ( \"Simple generic ROOT-based shelve-like-database\" )\n# =============================================================================\ntry : \n from cPickle import Pickler, Unpickler, HIGHEST_PROTOCOL\nexcept ImportError : \n from pickle import Pickler, Unpickler, HIGHEST_PROTOCOL\n# ============================================================================= \ntry :\n from io import BytesIO \nexcept ImportError : \n from shelve import StringIO as BytesIO\n# =============================================================================\nPROTOCOL = 2\n# =============================================================================\n## @class RootOnlyShelf\n# Plain vanilla DBASE for ROOT-object (only)\n# essentially it is nothing more than just shelve-like interface for ROOT-files\n# @author Vanya BELYAEV Ivan.Belyaev@cern.ch\n# @date 2015-07-31\n# @attention It CRUCIALLY depends on the proper TFile-decorations\n# from ostap.io.root_file module\n# @code\n# db = RootOnlyShelf('mydb.root','c')\n# h1 = ...\n# db ['histogram'] = h1\n# db.ls()\n# @endcode \n# @see Ostap.TFileDeco\nclass RootOnlyShelf(shelve.Shelf):\n \"\"\"Plain vanilla DBASE for ROOT-object (only)\n Essentially it is nothing more than just shelve-like\n interface for ROOT-files\n Attention: It CRUCIALLY depends on the proper\n TFile-decorations from ostap.io.root_file module\n \n >>> db = RooOnlyShelf('mydb.root','c')\n >>> h1 = ...\n >>> db ['histogram'] = h1\n >>> db.ls()\n \"\"\" \n ## constructors \n # @attention it depends on proper TFile-decorations in ostap.io.root_file module\n def __init__( self ,\n filename ,\n mode ,\n writeback = False ,\n args = () ) :\n \"\"\" Create Root-only database \n >>> db = RooOnlyShelf('mydb.root','c')\n >>> h1 = ...\n \"\"\"\n self.__filename = filename \n from ostap.io.root_file import ROOTCWD, open_mode \n with ROOTCWD() : ## NB: preserve current directory in ROOT!\n rfile = ROOT.TFile.Open ( filename , open_mode ( mode ) , *args )\n shelve.Shelf.__init__ ( self , rfile , writeback )\n\n @property\n def filename ( self ) :\n \"\"\"``filename'' : the file name for root-database\"\"\"\n return self.__filename\n \n def __enter__ ( self ) : return self \n def __exit__ ( self , *_ ) : self.close ()\n\n\n# =============================================================================\n## need to disable endcode/decode for the keys \nif python_version.major > 2 :\n \n def _ros_iter_ ( self ):\n for k in self.dict.keys() : yield k\n def _ros_contains_ ( self , key ):\n return key in self.dict\n def _ros_get_ ( self , key , default = None ) :\n if key in self.dict : return self[key]\n return default\n def _ros_delitem_ ( self , key ) :\n del self.dict[key]\n try:\n del self.cache[key]\n except KeyError:\n pass\n\n RootOnlyShelf.__iter__ = _ros_iter_ \n RootOnlyShelf.__contains__ = _ros_contains_\n RootOnlyShelf.__ros_get__ = _ros_get_\n RootOnlyShelf.__delitem__ = _ros_delitem_\n \n# =============================================================================\n## get item from ROOT-file\n# @code\n# obj = db['A/B/C/histo']\n# @endcode \n# @author Vanya BELYAEV Ivan.Belyaev@cern.ch\n# @date 2015-07-31 \ndef _root_getitem_ ( self , key ) :\n \"\"\"Get the item from ROOT-file\n >>> obj = db['A/B/C/histo']\n \"\"\"\n try:\n value = self.cache[key]\n except KeyError:\n value = self.dict[ key ] \n if self.writeback:\n self.cache[key] = value\n return value\n \n# =============================================================================\n## put item into ROOT-file \n# @code\n# db['A/B/C/histo'] = obj\n# @endcode \n# @author Vanya BELYAEV Ivan.Belyaev@cern.ch\n# @date 2015-07-31 \ndef _root_setitem_ ( self , key , value ) :\n \"\"\" Put item into ROOT-file\n >>> db['A/B/C/histo'] = obj\n \"\"\"\n if self.writeback:\n self.cache[key] = value\n self.dict[ key ] = value \n\nRootOnlyShelf.__getitem__ = _root_getitem_\nRootOnlyShelf.__setitem__ = _root_setitem_\n\n# =============================================================================\n## add an object into data base\n# @code\n# dbase = ...\n# object = ...\n# dbase.ls() \n# object >> dbase ## add object into dbase \n# dbase.ls() \n# @endcode \n# @author Vanya BELYAEV Ivan.Belyaev@itep.ru\n# @date 2016-06-04\ndef _db_rrshift_ ( dbase , obj ) :\n \"\"\"Add an object into data base\n \n dbase = ...\n object = ...\n dbase.ls() \n object >> dbase ## add object into dbase \n dbase.ls() \n \"\"\"\n if hasattr ( obj , 'GetName' ) : name = obj.GetName()\n elif hasattr ( obj , 'name' ) : name = obj.name ()\n else : name = obj.__class__.__name__\n #\n dbase [ name ] = obj\n \nRootOnlyShelf.__rrshift__ = _db_rrshift_\n\n# =============================================================================\n## @class RootShelf\n# The actual class for ROOT-based shelve-like data base\n# it implement shelve-interface with underlying ROOT-file as storage\n# - ROOT-objects are stored directly in the ROOT-file,\n# - other objects are pickled and stored via ROOT.TObjString\n# @code\n# db = RootShelf( 'mydb.root' , 'c' )\n# db['histo'] = h1\n# db['tuple'] = ('a',1,h1) \n# @endcode\n# @see RootOnlyShelf \n# @author Vanya BELYAEV Ivan.Belyaev@cern.ch\n# @date 2015-07-31 \nclass RootShelf(RootOnlyShelf):\n \"\"\" The actual class for ROOT-based shelve-like data base\n it implement shelve-interface with underlyinog ROOT-fiel storage\n - ROOT-object are store ddirectly in the ROOT-file,\n - other objects are pickled and stored in ROOT.TObjString\n \n >>> db = RootShelf( 'mydb.root' , 'c' )\n >>> db['histo'] = h1\n >>> db['tuple'] = ('a',1,h1)\n \"\"\"\n def __init__( self ,\n filename ,\n mode ,\n writeback = False ,\n protocol = PROTOCOL , ## pickling protocol\n compress = zlib.Z_BEST_COMPRESSION , ## compression level \n args = () ):\n RootOnlyShelf.__init__ ( self , filename , mode , writeback , args = args )\n self.__protocol = protocol\n self.__compresslevel = compress \n @property\n def protocol ( self ) :\n \"\"\"``protocol'' : pickle protocol\"\"\"\n return self.__protocol\n @property\n def compresslevel ( self ) :\n \"\"\"``compresslevel'' : zlib compression level\n \"\"\"\n return self.__compresslevel\n \n# =============================================================================\n## get object (unpickle if needed) from dbase\n# @code\n# obj = db['A/B/C']\n# @endcode\n# @author Vanya BELYAEV Ivan.Belyaev@cern.ch\n# @date 2015-07-31 \ndef _pickled_getitem_ ( self , key ):\n \"\"\" Get object (unpickle if needed) from dbase\n >>> obj = db['A/B/C']\n \"\"\"\n ##\n try: \n value = self.cache[key]\n except KeyError:\n value = self.dict[key]\n ## blob ?\n from ostap.core.core import Ostap\n if isinstance ( value , Ostap.BLOB ) :\n ## unpack it!\n z = Ostap.blob_to_bytes ( value )\n u = zlib.decompress ( z )\n ## unpickle it! \n f = BytesIO ( u )\n value = Unpickler(f).load()\n del z , u , f \n if self.writeback:\n self.cache[key] = value\n return value\n\n# =============================================================================\n## Add object (pickle if needed) to dbase\n# @code\n# db['A/B/C'] = obj\n# @endcode\n# @author Vanya BELYAEV Ivan.Belyaev@cern.ch\n# @date 2015-07-31 \ndef _pickled_setitem_ ( self , key , value ) :\n \"\"\" Add object (pickle if needed) to dbase\n >>> db['A/B/C'] = obj\n \"\"\"\n ##\n if self.writeback:\n self.cache [ key ] = value\n\n ## not TObject? pickle it and convert to Ostap.BLOB\n if not isinstance ( value , ROOT.TObject ) :\n ## (1) pickle it \n f = BytesIO ( )\n p = Pickler ( f , self.protocol )\n p.dump ( value )\n ## (2) zip it\n z = zlib.compress ( f.getvalue() , self.compresslevel )\n ## (3) put it into BLOB \n from ostap.core.core import Ostap\n blob = Ostap.BLOB ( key ) \n status = Ostap.blob_from_bytes ( blob , z )\n value = blob \n del z , f , p \n \n ## finally use ROOT \n self.dict[key] = value\n \nRootShelf.__getitem__ = _pickled_getitem_\nRootShelf.__setitem__ = _pickled_setitem_\n\nRootShelf.__rrshift__ = _db_rrshift_\n# =============================================================================\n## helper function to open RootShelve data base\n# @code\n# import RootShelve as DBASE\n# db = DBASE.open ( 'mydb.root' , 'c' )\n# @endcode \n# @author Vanya BELYAEV Ivan.Belyaev@cern.ch\n# @date 2010-04-30\ndef open ( filename ,\n mode = 'c' ,\n writeback = False , *args ) : \n \"\"\"\n Helper function to open RootShelve data base\n >>> import RootShelve as DBASE\n >>> db = DBASE.open ( 'mydb.root' , 'c' )\n \"\"\" \n return RootShelf ( filename ,\n mode ,\n writeback , * args )\n\n# =============================================================================\n## @class TmpRootShelf\n# TEMPORARY The actual class for ROOT-based shelve-like data base\n# it implements shelve-interface with underlying ROOT-file as a storage\n# - ROOT-objects are stored directly in the ROOT-file,\n# - other objects are pickled and stored in ROOT.TObjString\n# @code\n# db = TmmRootShelf()\n# db['histo'] = h1\n# db['tuple'] = ('a',1,h1) \n# @endcode\n# @see RootShelf \n# @author Vanya BELYAEV Ivan.Belyaev@cern.ch\n# @date 2015-07-31 \nclass TmpRootShelf(RootShelf):\n \"\"\"The actual class for TEMPORARY ROOT-based shelve-like data base\n it implement shelve-intergase with underlyinog ROOT-fiel storage\n - ROOT-object are stored directly in the ROOT-file,\n - other objects are pickled and stored via ROOT.TObjString\n see RootShelf\n \"\"\"\n def __init__( self, *args ):\n \n ## create temporary file name \n import tempfile\n filename = tempfile.mktemp ( suffix = '.root' )\n \n RootShelf.__init__ ( self ,\n filename ,\n mode = 'n' ,\n writeback = False ,\n protocol = HIGHEST_PROTOCOL ,\n compress = zlib.Z_DEFAULT_COMPRESSION ,\n args = args )\n \n ## close and delete the file \n def close ( self ) :\n ## close the shelve file\n fname = self.filename \n ## super(TmpRootShelf,self).close ()\n shelve.Shelf.close ( self )\n ## delete the file\n import os\n if os.path.exists ( fname ) :\n try :\n os.unlink ( fname )\n except :\n pass\n \n# =============================================================================\n## helper function to open RootShelve data base\n# @code\n# import RootShelve as DBASE\n# db = DBASE.open ( 'mydb.root' , 'c' )\n# @endcode \n# @author Vanya BELYAEV Ivan.Belyaev@cern.ch\n# @date 2010-04-30\ndef tmpdb ( *args ) : \n \"\"\" Helper function to open TEMPPORARY RootShelve data base\n >>> import RootShelve as DBASE\n >>> db = DBASE.tmpdb()\n \"\"\" \n return TmpRootShelf ( *args )\n\n\n# =============================================================================\nif '__main__' == __name__ :\n \n from ostap.utils.docme import docme\n docme ( __name__ , logger = logger )\n \n# =============================================================================\n# The END \n# =============================================================================\n","repo_name":"Pro100Tema/ostap","sub_path":"ostap/io/rootshelve.py","file_name":"rootshelve.py","file_ext":"py","file_size_in_byte":15496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"42"} +{"seq_id":"35672550919","text":"import json\nimport os\nimport re\nimport ssl\nimport sys\n\n# Third party imports\nfrom qtpy.QtCore import QObject, Signal\n\n# Local imports\nfrom spyder import __version__\nfrom spyder.config.base import _, is_stable_version\nfrom spyder.py3compat import PY3, is_text_string\nfrom spyder.config.utils import is_anaconda\nfrom spyder.utils.programs import check_version\n\n\nif PY3:\n from urllib.request import urlopen\n from urllib.error import URLError, HTTPError\nelse:\n from urllib2 import urlopen, URLError, HTTPError\n\n\nclass WorkerUpdates(QObject):\n \"\"\"\n Worker that checks for releases using either the Anaconda\n default channels or the Github Releases page without\n blocking the Spyder user interface, in case of connection\n issues.\n \"\"\"\n sig_ready = Signal()\n\n def __init__(self, parent, startup, version=\"\", releases=None):\n QObject.__init__(self)\n self._parent = parent\n self.error = None\n self.latest_release = None\n self.startup = startup\n self.releases = releases\n\n if not version:\n self.version = __version__\n else:\n self.version = version\n\n def check_update_available(self):\n \"\"\"Checks if there is an update available.\n\n It takes as parameters the current version of Spyder and a list of\n valid cleaned releases in chronological order.\n Example: ['2.3.2', '2.3.3' ...] or with github ['2.3.4', '2.3.3' ...]\n \"\"\"\n # Don't perform any check for development versions\n if 'dev' in self.version:\n return (False, latest_release)\n\n # Filter releases\n if is_stable_version(self.version):\n releases = [r for r in self.releases if is_stable_version(r)]\n else:\n releases = [r for r in self.releases\n if not is_stable_version(r) or r in self.version]\n\n latest_release = releases[-1]\n\n return (check_version(self.version, latest_release, '<'),\n latest_release)\n\n def start(self):\n \"\"\"Main method of the WorkerUpdates worker\"\"\"\n if is_anaconda():\n self.url = 'https://repo.anaconda.com/pkgs/main'\n if os.name == 'nt':\n self.url += '/win-64/repodata.json'\n elif sys.platform == 'darwin':\n self.url += '/osx-64/repodata.json'\n else:\n self.url += '/linux-64/repodata.json'\n else:\n self.url = ('https://api.github.com/repos/'\n 'spyder-ide/spyder/releases')\n self.update_available = False\n self.latest_release = __version__\n\n error_msg = None\n\n try:\n if hasattr(ssl, '_create_unverified_context'):\n # Fix for spyder-ide/spyder#2685.\n # [Works only with Python >=2.7.9]\n # More info: https://www.python.org/dev/peps/pep-0476/#opting-out\n context = ssl._create_unverified_context()\n page = urlopen(self.url, context=context)\n else:\n page = urlopen(self.url)\n try:\n data = page.read()\n\n # Needed step for python3 compatibility\n if not is_text_string(data):\n data = data.decode()\n data = json.loads(data)\n\n if is_anaconda():\n if self.releases is None:\n self.releases = []\n for item in data['packages']:\n if ('spyder' in item and\n not re.search(r'spyder-[a-zA-Z]', item)):\n self.releases.append(item.split('-')[1])\n result = self.check_update_available()\n else:\n if self.releases is None:\n self.releases = [item['tag_name'].replace('v', '')\n for item in data]\n self.releases = list(reversed(self.releases))\n\n result = self.check_update_available()\n self.update_available, self.latest_release = result\n except Exception:\n error_msg = _('Unable to retrieve information.')\n except HTTPError:\n error_msg = _('Unable to retrieve information.')\n except URLError:\n error_msg = _('Unable to connect to the internet.

Make '\n 'sure the connection is working properly.')\n except Exception:\n error_msg = _('Unable to check for updates.')\n\n # Don't show dialog when starting up spyder and an error occur\n if not (self.startup and error_msg is not None):\n self.error = error_msg\n self.sig_ready.emit()\n","repo_name":"MarkMoretto/spyder-master","sub_path":"spyder/workers/updates.py","file_name":"updates.py","file_ext":"py","file_size_in_byte":4800,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"42"} +{"seq_id":"4394169729","text":"\"\"\"Module with functions specific to the Hyper-Suprime Cam survey.\"\"\"\n\nimport numpy as np\n\n__all__ = ['default_version', 'known_versions', 'e_2_convention',\n 'default_column_keys', 'apply_photo_z_quality_cut',\n 'selection_bias_factor']\n\ndefault_version = 'PDR2'\nknown_versions = ['PDR2', ]\ne_2_convention = 'flipped'\n\n\ndef default_column_keys(version=default_version):\n \"\"\"Return a dictionary of default column keys.\n\n Parameters\n ----------\n version : string or None, optional\n Version of the catalog.\n\n Returns\n -------\n keys : dict\n Dictionary of default column keys.\n\n Raises\n ------\n ValueError\n If `version` does not correspond to a known catalog version.\n\n \"\"\"\n if version == 'PDR2':\n keys = {\n 'ra': 'ira',\n 'dec': 'idec',\n 'z': 'photoz_best',\n 'z_low': 'photoz_err68_min',\n 'e_1': 'ishape_hsm_regauss_e1',\n 'e_2': 'ishape_hsm_regauss_e2',\n 'w': 'ishape_hsm_regauss_derived_shape_weight',\n 'm': 'ishape_hsm_regauss_derived_shear_bias_m',\n 'e_rms': 'ishape_hsm_regauss_derived_rms_e',\n 'R_2': 'ishape_hsm_regauss_resolution'}\n else:\n raise ValueError(\n \"Unkown version of DES. Supported versions are {}.\".format(\n known_versions))\n\n return keys\n\n\ndef apply_photo_z_quality_cut(table_s, global_photo_z_cuts,\n specinfo_photo_z_cuts):\n \"\"\"Apply HSC-specific photo-z cuts to the source catalog.\n\n Parameters\n ----------\n table_s : astropy.table.Table\n HSC weak lensing source catalog.\n global_photo_z_cuts : string\n Requirements for global photometric redshift quality.\n specinfo_photo_z_cuts : string\n Specinfo photo-z cuts.\n\n Returns\n -------\n table_s : astropy.table.Table\n Table containing only source passing the cuts.\n\n Raises\n ------\n ValueError\n If invalid options are passed.\n\n \"\"\"\n if global_photo_z_cuts == \"basic\":\n # Implement ~2-sigma clipping over chi^2_5.\n mask = table_s['frankenz_model_llmin'] < 6.\n elif global_photo_z_cuts == \"medium\":\n mask = table_s['frankenz_model_llmin'] < 6.\n # Remove sources with overly broad PDFs around `z_best`.\n mask = mask & (table_s['frankenz_photoz_risk_best'] < 0.25)\n elif global_photo_z_cuts == \"strict\":\n # Similar to `medium`, but stricter.\n mask = table_s['frankenz_model_llmin'] < 6.\n mask = mask & (table_s['frankenz_photoz_risk_best'] < 0.15)\n elif global_photo_z_cuts == \"none\":\n # No global photo-z cut is applied.\n mask = np.isfinite(table_s['frankenz_photoz_best'])\n else:\n raise ValueError(\"Invalid global photo-z cuts option \"\n \"{}\".format(global_photo_z_cuts))\n\n # Apply specinfo photo-z cuts\n # Should most likely be applied with corresponding redshift cuts.\n if specinfo_photo_z_cuts == \"none\":\n # No cut\n pass\n elif specinfo_photo_z_cuts == \"great\":\n # >50% of info comes from non-photo-z sources.\n mask = mask & (table_s['frankenz_model_ptype2'] < 0.5)\n elif specinfo_photo_z_cuts == \"good\":\n # >10% of info comes from non-photo-z sources.\n mask = mask & (table_s['frankenz_model_ptype2'] < 0.9)\n elif specinfo_photo_z_cuts == \"moderate\":\n # 10%-50% of info comes from non-photo-z sources.\n mask = mask & (table_s['frankenz_model_ptype2'] >= 0.5)\n mask = mask & (table_s['frankenz_model_ptype2'] < 0.9)\n elif specinfo_photo_z_cuts == \"poor\":\n # <=50% of info comes from non-photo-z sources.\n mask = mask & (table_s['frankenz_model_ptype2'] >= 0.5)\n elif specinfo_photo_z_cuts == \"poorest\":\n # <=10% of info comes from non-photo-z sources.\n mask = mask & (table_s['frankenz_model_ptype2'] >= 0.9)\n else:\n raise ValueError(\"Invalid specinfo photo-z cuts option \"\n \"= {}\".format(global_photo_z_cuts))\n\n return table_s[mask]\n\n\ndef selection_bias_factor(table_l):\n \"\"\"Compute the multiplicative selection bias.\n\n Parameters\n ----------\n table_l : astropy.table.Table\n Precompute results for the lenses.\n\n Returns\n -------\n m_sel : numpy.ndarray\n Multiplicative selection bias in each radial bin.\n\n \"\"\"\n return (\n np.sum(table_l['sum w_ls A p(R_2=0.3)'] *\n table_l['w_sys'][:, None], axis=0) /\n np.sum(table_l['sum w_ls'] * table_l['w_sys'][:, None], axis=0))\n","repo_name":"johannesulf/dsigma","sub_path":"dsigma/surveys/hsc.py","file_name":"hsc.py","file_ext":"py","file_size_in_byte":4601,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"42"} +{"seq_id":"18568527554","text":"import argparse\r\n\r\nfrom utils import *\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('--is_write', dest='is_write', action='store_true', default=False,\r\n help='write data to disk or not')\r\nparser.add_argument('--is_train', dest='is_train', action='store_true', default=False,\r\n help='write train or test data as paired data')\r\nparser.add_argument('--is_show', dest='is_show', action='store_true', default=False,\r\n help='show original and minutiae map')\r\nparser.add_argument('--resize_ratio', dest='resize_ratio', type=float, default=2.,\r\n help='resize ratio to easy check')\r\nparser.add_argument('--is_print', dest='is_print', action='store_true', default=False,\r\n help='print minutiae information or not')\r\nparser.add_argument('--interval', dest='interval', type=int, default=0, help='interval time between two imgs')\r\nargs = parser.parse_args()\r\n\r\n\r\ndef encode_minumap(minutia_list, height=320, width=280, channel=3, bs=5, resize_ratio=1.):\r\n minumap = np.zeros((height, width, channel), dtype=np.uint8)\r\n scale = 255. / 180.\r\n\r\n for i, minutiae in enumerate(minutia_list):\r\n minu_y, minu_x = minutiae[0:2]\r\n minu_direc = minutiae[2]\r\n minu_type = 'Ending' if minutiae[4] == 0 else 'Bifurcation'\r\n\r\n minumap[minu_x-bs:minu_x+bs, minu_y-bs:minu_y+bs, 0] = (np.floor(minu_direc / 2.) + 1) * scale\r\n minumap[minu_x-bs:minu_x+bs, minu_y-bs:minu_y+bs, 1] = 128 if minu_type == 'Ending' else 255\r\n\r\n resizedMinumap = minumap.copy()\r\n if resize_ratio != 1.:\r\n resizedMinumap = cv2.resize(minumap, None, fx=resize_ratio, fy=resize_ratio, interpolation=cv2.INTER_LINEAR)\r\n\r\n return minumap, resizedMinumap\r\n\r\ndef imshow(img, fpgt, reMinumap):\r\n winName = 'Show'\r\n cv2.namedWindow(winName, cv2.WINDOW_AUTOSIZE)\r\n cv2.moveWindow(winName, 0, 0)\r\n\r\n reImg = cv2.resize(img, None, fx=args.resize_ratio, fy=args.resize_ratio, interpolation=cv2.INTER_CUBIC)\r\n minuimg = fancyShow(reImg, fpgt, resize_ratio=args.resize_ratio) # draw minutiae points\r\n\r\n showImg = np.hstack([reImg, minuimg, reMinumap])\r\n\r\n cv2.imshow(winName, showImg)\r\n if cv2.waitKey(args.interval) & 0xFF == 27:\r\n sys.exit('Esc clicked!')\r\n\r\ndef imwrite(img, minumap, basePath, imgName):\r\n data = 'train' if args.is_train else 'test'\r\n save_folder = os.path.join(basePath, 'paired/{}'.format(data))\r\n\r\n if not os.path.isdir(save_folder):\r\n os.makedirs(save_folder)\r\n\r\n newImg = np.hstack([minumap, img])\r\n cv2.imwrite(os.path.join(save_folder, imgName + '.png'), newImg[:, :, ::-1])\r\n\r\n\r\ndef main(basePath, data_file):\r\n # read showing file names\r\n imgNames = []\r\n with open(data_file, 'r') as f:\r\n for imgName in csv.reader(f, delimiter='\\n'):\r\n imgNames.extend(imgName)\r\n\r\n init_logger('fpgt.log') # initialize logger()\r\n\r\n # for idx, imgName in enumerate(imgNames):\r\n for idx in range(0, len(imgNames)):\r\n imgName = imgNames[idx]\r\n print('index: {}, imgName: {}'.format(str(idx).zfill(5), imgName))\r\n\r\n img = cv2.imread(os.path.join(basePath, imgName + '.bmp'))\r\n fpgt = FPGT(imgName)\r\n if fpgt.nMinutiae != 0: # just do following operators ther are '.MINU' file\r\n minumap, reMinumap = encode_minumap(fpgt.minutiaes, resize_ratio=args.resize_ratio)\r\n\r\n if args.is_show:\r\n imshow(img, fpgt, reMinumap)\r\n\r\n if args.is_write:\r\n imwrite(img, minumap, basePath, imgName) # save as paired img\r\n\r\n\r\nif __name__ == '__main__':\r\n base_path = '../../Data/BMP_320x280'\r\n train_file = '../data/train_images.txt'\r\n test_file = '../data/test_images.txt'\r\n\r\n if args.is_train:\r\n main(base_path, train_file)\r\n else:\r\n main(base_path, test_file)\r\n","repo_name":"ChengBinJin/d-Fingerprint-Generation","sub_path":"src/makePaired.py","file_name":"makePaired.py","file_ext":"py","file_size_in_byte":3873,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"42"} +{"seq_id":"20126634820","text":"from flask import Flask, render_template, request\nimport speech_recognition as sr\nfrom pydub import AudioSegment\nfrom gtts import gTTS\nimport pyttsx3\nimport os\nimport pickle\ntemp_path = os.path.join(os.environ[\"USERPROFILE\"])\npath = temp_path+\"/Downloads/\"\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return render_template(\"index.html\")\n\n\n@app.route(\"/stt\", methods=[\"POST\"])\ndef stt():\n return render_template(\"speech_to_text.html\")\n\n\n@app.route(\"/tts\", methods=[\"POST\"])\ndef tts():\n return render_template(\"text_to_speech.html\")\n\n\n@app.route(\"/speech-to-text-using-file\",methods=[\"POST\"])\ndef speech_to_text_using_file(): \n q = open(\"lang.txt\",\"r\") \n o = q.read()\n q.close()\n file_name = \"your_file.wav\"\n r = sr.Recognizer()\n with sr.AudioFile(file_name) as source:\n audio = r.listen(source) \n text = r.recognize_google(audio,language=o) \n file = open(path+\"file.txt\",\"w\",encoding=\"utf-8\")\n file.write(text)\n file.close() \n return render_template(\"stt3.html\",message=\"File Download Successfully\") \n\n\n@app.route(\"/main\", methods=[\"POST\"])\ndef main():\n a = request.form['input']\n if a == 'mic':\n c = request.form['language']\n if c == \"hindi\":\n m = \"hi\"\n else:\n m = \"en\"\n \n return render_template(\"stt2.html\",lang=m)\n elif a == 'file':\n c = request.form['language']\n if c == \"hindi\":\n m = \"hi\"\n else:\n m = \"en\"\n i = open(\"lang.txt\",\"w\") \n i.write(m)\n i.close()\n n = request.files[\"mp3_file\"]\n n.save(\"D:/programming/Python/Machine_Learning_Projects/project_speech_to_text_or_text_to_speech/your_file.wav\")\n return render_template(\"stt3.html\")\n elif a == 'write':\n return render_template(\"tts2.html\")\n elif a == 'upload':\n n = request.files['file']\n n.save(\"D:/programming/Python/Machine_Learning_Projects/project_speech_to_text_or_text_to_speech/your_file.txt\") \n return render_template(\"tts3.html\") \n\n\n@app.route(\"/speech-to-text\",methods=['POST'])\ndef speech_to_text():\n text = request.form['converted_text']\n file = open(path+\"file.txt\",\"w\",encoding=\"utf-8\")\n file.write(text)\n file.close()\n return render_template(\"stt2.html\",message = \"File Download Successfully\")\n\n\n@app.route(\"/text-to-speech-using-file\",methods=['POST'])\ndef text_to_speech_using_file():\n text = open(\"your_file.txt\")\n a = text.read()\n mp3 = gTTS(a)\n text.close()\n mp3.save(path+\"file.mp3\")\n return render_template(\"tts3.html\",message=\"File Download Successfully\")\n\n\n@app.route(\"/text-to-speech\",methods=['POST'])\ndef text_to_speech():\n text = request.form['text']\n mp3 = gTTS(text)\n mp3.save(path+\"file.mp3\")\n return render_template(\"tts2.html\",message=\"File Download Successfully\")\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"xvinay28x/Speech_to_text_and_Text_to_speech","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2927,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"7434717086","text":"class Solution(object):\n def __init__(self):\n self.m = {}\n def numDistinct(self, s, t):\n if not s or not t:\n return 0\n \n if len(t) == 1:\n return s.count(t)\n \n if (s, t) in self.m:\n return self.m[(s, t)]\n \n ans = 0\n for i in xrange(len(s)):\n if s[i] == t[0]:\n ans += self.numDistinct(s[i+1:], t[1:])\n self.m[(s, t)] = ans\n return ans","repo_name":"hayeonk/leetcode","sub_path":"sols/distinct_subsequences.py","file_name":"distinct_subsequences.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"35297102239","text":"import numpy as np\nimport torch\n\nfrom src import patient\n\n\ndef make_train_test_lists(pos_patients, neg_patients):\n \"\"\"\n If needed make the number of patients even\n @return training_set and test_set with same number of positive and negative patients\n \"\"\"\n if(len(pos_patients) % 2 != 0):\n pos_patients = pos_patients[:-1]\n if(len(neg_patients) % 2 != 0):\n neg_patients = neg_patients[:-1]\n split_pos = np.split(np.random.permutation(pos_patients), 2)\n split_neg = np.split(np.random.permutation(neg_patients), 2)\n\n training_set = list(split_pos[0]) + list(split_neg[0])\n test_set = list(split_pos[1]) + list(split_neg[1])\n return training_set, test_set\n\n\ndef list_to_tensor(tensor_list):\n \"\"\"\n Turns a list of tensors into one big tensor\n list's tensors are concatenated on the first dimension\n \"\"\"\n tensor_nb = len(tensor_list)\n tensor_shape = tensor_list[0].numpy().shape\n tensor = torch.Tensor(np.zeros([tensor_nb, 1] + list(tensor_shape)))\n for idx in range(len(tensor_list)):\n tensor[idx, 0,] = tensor_list[idx]\n return tensor\n\ndef create_patch_target(patient_list, patient_patches, patient_df):\n \"\"\"\n Get all patches as list of tensors and targets as list\n @patient_list contains the list of patients\n @patient_patches is the dictionnary with all patients id as key and patches as values\n @patient_df is the dataframe that contains all patient's info\n \"\"\"\n all_patches = []\n all_targets = []\n for hpv_patient in patient_list:\n patches = torch.Tensor(patient_patches[hpv_patient])\n tumor_rec = patient.get_hpv_status(patient_df, hpv_patient)\n if(len(patches)):\n nb_patch = patches.numpy().shape[0]\n for idx_patch in range(nb_patch):\n all_patches.append(patches[idx_patch,:,:])\n all_targets.append(tumor_rec)\n return all_patches, all_targets \n\n\ndef get_mean_patch(train_patches):\n train_patches_tensor = list_to_tensor(train_patches)\n mean_patch = torch.mean(train_patches_tensor, 0)\n return mean_patch[0,0,:,:]\n\ndef remove_to_balance(patches, targets, disp=False):\n \"\"\"\n Returns the list of indexes of patches to remove to obtain a balanced data set\n \"\"\"\n # Make copies for safety\n patches = patches[:]\n targets = targets[:]\n\n all_pos_indexes = np.where(np.asarray(targets) == 1)[0]\n all_neg_indexes = np.where(np.asarray(targets) == 0)[0]\n\n if(disp):\n # Display number of positive and negative patches\n print('{pos_nb} positive patches'.format(pos_nb=len(all_pos_indexes)))\n print('{neg_nb} negative patches'.format(neg_nb=len(all_neg_indexes)))\n if(len(all_neg_indexes) > len(all_pos_indexes)):\n indexes_to_remove = np.random.choice(all_neg_indexes, len(all_neg_indexes) - len(all_pos_indexes), replace=False)\n else:\n indexes_to_remove = np.random.choice(all_pos_indexes, len(all_pos_indexes) - len(all_neg_indexes), replace=False)\n patches = np.delete(patches, indexes_to_remove)\n targets = np.delete(targets, indexes_to_remove)\n return patches, targets \n\ndef create_balanced_tensors(train_targets, train_patches, disp=False):\n \"\"\"\n creates balanced dataset with same number of positive and negative samples\n \"\"\"\n train_targets = train_targets[:]\n train_patches = train_patches[:]\n # Balance dataset\n train_patches, train_targets = remove_to_balance(train_patches, train_targets, disp=disp)\n\n train_targets = [torch.Tensor([int(tumor_rec), 1 - int(tumor_rec)]) for tumor_rec in train_targets]\n train_targets = list_to_tensor(train_targets)\n train_patches = list_to_tensor(train_patches)\n return train_targets, train_patches\n","repo_name":"hassony2/cancer-seminar","sub_path":"src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"35333629752","text":"# coding=utf-8\r\n\"\"\"\r\nВсе локации для игры\r\n\"\"\"\r\nimport random\r\nimport time\r\n\r\n\r\nfrom bot.data import (\r\n SHORE, CAVE, CARAVANS, WOODS\r\n)\r\n\r\n\r\nADVENTURES = [\r\n {\"command\": SHORE, \"level\": 0, \"chance\": 0},\r\n {\"command\": CAVE, \"level\": 0, \"chance\": 0},\r\n {\"command\": CARAVANS, \"level\": 0, \"chance\": 0},\r\n {\"command\": WOODS, \"level\": 0, \"chance\": 1},\r\n]\r\n\r\n\r\nclass Location(object):\r\n \"\"\" Локация, любое место в игре, куда можем отправиться \"\"\"\r\n\r\n def __init__(self, console, command, instant, prob):\r\n \"\"\"\r\n console: название в консоли\r\n command: любое значение, на которое будет ориентироваться .emoji\r\n instant: требует ли выполнение команды времени\r\n after: время, через которое поход в локацию будет доступен\r\n \"\"\"\r\n self.console = console\r\n self.command = command\r\n self.instant = instant\r\n self.prob = prob\r\n self.after = 0\r\n\r\n def postpone(self):\r\n \"\"\" Откладываем поход в локацию \"\"\"\r\n seconds = random.random() * 1200 + 900\r\n self.after = time.time() + seconds\r\n return seconds / 60\r\n\r\n @property\r\n def travel(self):\r\n \"\"\" Определяет, идем или не идем в локацию \"\"\"\r\n return random.random() <= self.prob\r\n\r\n @property\r\n def emoji(self):\r\n \"\"\" Возвращает команду, по которой осуществляется поход в локацию \"\"\"\r\n return self.command\r\n\r\n def update(self, level, available):\r\n \"\"\" Метод обновления для перезаписи \"\"\"\r\n pass\r\n\r\n\r\nclass Random(Location):\r\n \"\"\" Локация, в которой ходим по случайной команде \"\"\"\r\n @property\r\n def emoji(self):\r\n \"\"\" Одна из случайных команд \"\"\"\r\n return random.choice(self.command)\r\n\r\n\r\nclass Adventures(Location):\r\n \"\"\" Локация для всех приключений \"\"\"\r\n\r\n def __init__(self, console, command, instant, prob):\r\n super().__init__(console, command, instant, prob)\r\n self.level = 0\r\n self.available = []\r\n\r\n @property\r\n def emoji(self):\r\n for command in self.command:\r\n if command[\"command\"] not in self.available:\r\n continue\r\n\r\n if self.level < command[\"level\"]:\r\n continue\r\n\r\n if random.random() > command[\"chance\"]:\r\n continue\r\n\r\n return command[\"command\"]\r\n\r\n return \"/wtb_101\"\r\n\r\n def update(self, level, available):\r\n \"\"\" Обновляет параметры, от которых зависит выбор локации \"\"\"\r\n self.level = level\r\n self.available = [c[\"command\"] for c in self.command\r\n if c[\"command\"].lower() in available.lower()]\r\n\r\n\r\nRANDOM_COMMANDS = [\r\n \"/hero\",\r\n \"/inv\",\r\n \"/report\",\r\n \"/trades\",\r\n \"/top\",\r\n \"/worldtop\",\r\n \"/wtb_113\",\r\n \"/wtb_115\",\r\n \"/wtb_116\",\r\n \"/wtb_117\",\r\n \"/wtb_121\",\r\n \"/wtb_179\",\r\n]\r\n\r\n\r\ndef create_locations():\r\n ''' Возвращает массив новых локаций '''\r\n # На индекс 2 жестко завязано обновление локаций из файла сессий\r\n return [\r\n Location(\"запрос героя\", \"🏅Герой\", True, 0.7),\r\n Location(\"визит в замок\", \"🏰Замок\", True, 0.6),\r\n Adventures(\"поход\", ADVENTURES, False, 1),\r\n Random(\"случайную команду\", RANDOM_COMMANDS, True, 0.7),\r\n # (!) 'arena': Location(\"поход на арену\", \"(!)\", False),\r\n # (!) 'build': Location(\"поход на стройку\", \"/build_(!)\", False),\r\n ]\r\n","repo_name":"LarsFox/TelegramRPG_Bot","sub_path":"bot/locations.py","file_name":"locations.py","file_ext":"py","file_size_in_byte":4020,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"43627448596","text":"from __future__ import print_function\n\nimport grpc\nimport getpass\nimport sys\nimport json\nimport os\nimport classeur_pb2\nimport classeur_pb2_grpc\nfrom hurry.filesize import size\nimport codecs\n\nMSERVER_PORT = 50051\nCHUNK_SIZE = 65536\n\ndef checkAuthentication(stub, username, password):\n\tuserCreds = classeur_pb2.UserCredentials(\n\t\tusername = username, password = password)\n\tresponse = stub.CheckAuthentication(userCreds)\n\t#Blooper Alert! 'vailidity' in place of 'validity' in the proto file\n\treturn response.vailidity\n\ndef listFiles(stub, username):\n\tuserToken = classeur_pb2.UserToken(\n\t\tusername = username)\n\tresult = stub.ListFiles(userToken)\n\tdata = json.loads(result.filesOwned)\n\tfileList = data[\"files\"] #it will return an array of filenames\n\tfileSize = result.filesSizes\n\tprint(\"You have occupied %s space in total\"%size(fileSize))\n\ti=1\n\tfor file in fileList:\n\t\tprint(\"[%s] %s\"%(i,file))\n\t\ti+=1\n\ndef reportSize(stub, username):\n\tuserToken = classeur_pb2.UserToken(\n\t\tusername = username)\n\tresult = stub.ReportSize(userToken)\n\tprint(\"You have occupied %s space in total\"%size(result.size))\n\ndef uploadFile(stub, username):\n\tfilepath = raw_input(\"Enter the file path: \")\n\tfilename = os.path.basename(filepath)\n\ttry:\n\t\tfile = codecs.open(filepath,'r', encoding=\"Latin-1\")\n\texcept:\n\t\tprint(\"Unable to open file %s\"%filepath)\n\t\treturn\n\tfilesize = os.path.getsize(filepath)\n\tchunk_count = filesize/CHUNK_SIZE\n\tif filesize%CHUNK_SIZE:\n\t\tchunk_count+=1\n\tchunk_iterator= fileChunkIterator(file,filename,chunk_count,username)\n\tack = stub.UploadFile(chunk_iterator)\n\tif ack.response == True:\n\t\tprint(\"File uploaded successfully\")\n\telse:\n\t\tprint(\"Problem in file upload!\")\n\tfile.close()\n\ndef downloadFile(stub,username):\n\tfilename = raw_input(\"Enter the filename: \")\n\tfilename = os.path.basename(filename)\n\tfileName = classeur_pb2.FileName(fileName=filename, userName=username)\n\tchunk_iter = stub.DownloadFile(fileName)\n\tif not os.path.exists('downloads'):\n\t try:\n\t os.makedirs('downloads')\n\t except OSError as exc: # Guard against race condition\n\t if exc.errno != errno.EEXIST:\n\t raise\n\tfile = codecs.open('./downloads/'+filename, 'w', encoding=\"Latin-1\")\n\tfor chunk in chunk_iter:\n\t\tif chunk.chunkId==-1:\n\t\t\tprint(\"File not found!\")\n\t\t\tos.remove(file.name)\n\t\t\tfile.close()\n\t\t\treturn\n\t\telif chunk.chunkId==-2:\n\t\t\tprint(\"File Corrupted in cloud! Can not be downloaded!\")\n\t\t\tfile.close()\n\t\t\tos.remove(file.name)\n\t\t\treturn\n\t\tch_data = chunk.chunkData\n\t\tfile.write(ch_data)\n\tprint(\"Download Successful!\")\n\tfile.close()\n\ndef fileChunkIterator(file, filename, chunk_count, username):\n\tfilechunk = classeur_pb2.FileChunks(\n\t\tfileName = filename, chunkId = -1, chunkData = None, userName = username)\n\tfor x in xrange(chunk_count):\n\t\tchunk = file.read(CHUNK_SIZE)\n\t\tfilechunk.chunkId=x+1\n\t\tfilechunk.chunkData=chunk\n\t\tyield filechunk\n\ndef logOut(stub,username):\n\tuser = classeur_pb2.UserToken(username=username)\n\tack = stub.LogOut(user)\n\tif ack.response:\n\t\tprint('\\nSuccessfully logged out')\n\t\tsys.exit(0)\n\telse:\n\t\tprint('\\nLog out unsuccessful')\n\t\tsys.exit(1)\n\ndef run():\n\tif (len(sys.argv) < 2):\n\t\tprint(\"Usage: %s MainServer IP\" % sys.argv[0])\n\t\tsys.exit(1)\n\n\tmserver_host = sys.argv[1]\n\tmserver_host_port = mserver_host + \":\" + str(MSERVER_PORT)\n\n\twith grpc.insecure_channel(mserver_host_port) as channel:\n\t\tstub = classeur_pb2_grpc.clientHandlerStub(channel)\n\t\t#now start using the stub\n\n\t\t# username = 'nilesh'\n\t\t# success = uploadFile(stub, username)\n\n\t\tusername = raw_input(\"Please enter your username: \")\n\t\tpassword = getpass.getpass('Password: ')\n\n\t\t# TODO: uncomment below code after testing is complete!\n\t\tif checkAuthentication(stub, username, password)==True:\n\t\t\tprint(\"Congratulations! Authentication successful\")\n\t\t\twhile 1:\n\t\t\t\ttry:\n\t\t\t\t\tprint(\"Choose any option :\\n 1. List Files\\n 2. Upload File\\n 3. Download File\\n 4. Total Size\\n 5. Exit\")\n\t\t\t\t\toption = raw_input(\"Option: \")\n\t\t\t\t\toption = int(option)\n\t\t\t\t\tif option == 1:\n\t\t\t\t\t\tlistFiles(stub,username)\n\t\t\t\t\telif option == 2:\n\t\t\t\t\t\tuploadFile(stub, username)\n\t\t\t\t\telif option == 3:\n\t\t\t\t\t\tdownloadFile(stub,username)\n\t\t\t\t\telif option == 4:\n\t\t\t\t\t\treportSize(stub,username)\n\t\t\t\t\t\tpass\n\t\t\t\t\telse:\n\t\t\t\t\t\tlogOut(stub,username)\n\t\t\t\texcept:\n\t\t\t\t\tlogOut(stub,username)\n\t\telse:\n\t\t\tprint(\"Incorrect credentials! Please try again.\")\n\t\t\n\nif __name__ == \"__main__\":\n\trun()","repo_name":"sidarth164/Classeur","sub_path":"rpc/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"44303141661","text":"\nfrom sys import argv, exit\n\nif len(argv) != 3:\n\tprint(\"0%\");\n\texit()\n\nname1 = argv[1].lower();\nname2 = argv[2].lower();\n\n\nres = sum(map(ord, name1)) + sum(map(ord, name2))\n\nres %= 100\n\nprint(str(res) + \"%\")\n","repo_name":"Gencive/Love-Compatibility","sub_path":"love.py","file_name":"love.py","file_ext":"py","file_size_in_byte":208,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"72328089726","text":"from mindspore import context, nn\nfrom musictagging.model import MusicTaggerCNN\nfrom musictagging.MusicTaggerTrainer import train, BCELoss\nfrom mindspore.train import Model\nfrom mindspore.train.loss_scale_manager import FixedLossScaleManager\nimport argparse\nfrom mindspore.train.serialization import load_checkpoint, load_param_into_net\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Train model')\n parser.add_argument('--model_dir', type=str, help='model directory', default = \"./\")\n parser.add_argument('--npu', type=int, help='device ID', default = 0)\n parser.add_argument('--epoch', type=int, help='epoch number', default = 5)\n parser.add_argument('--batch', type=int, help='batch size', default = 32)\n parser.add_argument('--lr', type=float, help='learning rate', default = 0.0005)\n parser.add_argument('--ls', type=float, help='loss scale', default = 1024.0)\n parser.add_argument('--save_step', type=int, help='save check point every N step', default = 2000)\n parser.add_argument('--keep_max', type=int, help='keep maximum checkpoint number', default = 2000)\n parser.add_argument('--data_dir', type=str, help='path to train data')\n parser.add_argument('--filename', type=str, help='name of train data file')\n parser.add_argument('--num_consumer', type=int, help='number of consumer', default = 4)\n parser.add_argument('--prefix', type=str, help='prefix of model', default = \"Music_Tagger\")\n parser.add_argument('--model_name', type=str, help='preload model', default = \"\")\n \n args = parser.parse_args()\n\n context.set_context(device_target='Ascend',mode = context.GRAPH_MODE, device_id = args.npu)\n network = MusicTaggerCNN()\n if args.model_name != \"\":\n param_dict = load_checkpoint(args.model_dir + '/' + args.model_name)\n load_param_into_net(network, param_dict)\n \n net_loss = BCELoss()\n \n network.set_train(True)\n net_opt = nn.Adam(params=network.trainable_params(), learning_rate = args.lr,loss_scale = args.ls)\n\n loss_scale_manager=FixedLossScaleManager(loss_scale = args.ls, drop_overflow_update = False)\n model = Model(network, net_loss, net_opt, loss_scale_manager = loss_scale_manager)\n\n train(model = model, \n network = network, \n dataset_direct = args.data_dir,\n filename = args.filename,\n columns_list = ['feature','label'],\n num_consumer = args.num_consumer,\n batch = args.batch, \n epoch = args.epoch,\n save_checkpoint_steps = args.save_step,\n keep_checkpoint_max = args.keep_max,\n prefix = args.prefix,\n directory = args.model_dir)\n","repo_name":"Ascend/ModelZoo-TensorFlow","sub_path":"TensorFlow/built-in/audio/Music_Auto_for_TensorFlow/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"42"} +{"seq_id":"69979011328","text":"from moviepy.editor import *\nfrom gtts import *\nimport secret as s\nimport random\nimport os\nimport glob\nimport praw\nif __name__ == '__main__':\n #exit()\n\n sub = \"jokes\"\n param = []\n pause = 0.0\n\n reddit = praw.Reddit(client_id=s.CLIENT_ID,\n client_secret=s.CLIENT_SECRET,\n username=s.USERNAME, password=s.PASSWORD,\n user_agent=\"ammarkhawaja\")\n subreddit = reddit.subreddit(sub).hot(limit=10)\n\n # Clears post folder\n files = glob.glob('content/post/' + sub + '/*')\n for f in files:\n os.remove(f)\n\n for post in subreddit:\n if sub == \"jokes\":\n param = [post.selftext, \"lol\"]\n pause = 1\n if sub == \"askreddit\":\n param = [post.comments[0].body, post.comments[1].body]\n pause = 0.5\n if sub == \"showerthoughts\":\n param = [\"shower\", \"thoughts\"]\n pause = 0.5\n if not post.stickied:\n bad_post = False\n for word in s.BLACKLISTED_WORDS:\n for text in param:\n if word in text or word in post.title:\n bad_post = True\n if not bad_post:\n post.title = post.title.replace(\"/\", \" or \")\n file_title = \"content/post/\" + sub + \"/\" + post.title + \" #\" + sub + \" #reddit .mp4\"\n print(\"Audio Preparing\")\n audio_references = [\"content/title.mp3\", \"content/comment0.mp3\", \"content/comment1.mp3\", \"content/fullaudio.mp3\"]\n all_audio = gTTS(text=post.title + \" . . . \" + param[0] + \" . . . \" + param[1], lang=\"en\", slow=False).save(audio_references[3])\n title_audio = gTTS(text=post.title, lang=\"en\", slow=False).save(audio_references[0])\n comment0_audio = gTTS(text=param[0], lang=\"en\", slow=False).save(audio_references[1])\n comment1_audio = gTTS(text=param[1], lang=\"en\", slow=False).save(audio_references[2])\n\n title_audio_duration = AudioFileClip(audio_references[0]).duration\n comment0_audio_duration = AudioFileClip(audio_references[1]).duration\n comment1_audio_duration = AudioFileClip(audio_references[2]).duration\n final_audio = CompositeAudioClip([AudioFileClip(audio_references[0]),\n AudioFileClip(audio_references[1]).set_start(title_audio_duration + 1),\n AudioFileClip(audio_references[2]).set_start(title_audio_duration + comment0_audio_duration + 2)]).set_fps(44100)\n print(\"Audio Ready\")\n\n print(\"Text Preparing\")\n randomint = random.randrange(2000)\n video = VideoFileClip(\"content/backgroundmovie.mp4\").resize((1080, 1920)).subclip(randomint, randomint + 60)\n background_image = ImageClip(\"content/background.png\").set_start(0).set_duration(AudioFileClip(audio_references[0]).duration + pause).set_pos((\"center\", 500)).resize(1.1,1.1)\n title_text = TextClip(txt=post.title, font='Comic-Sans-MS-Bold', align=\"west\", fontsize=32, size=(650,300), color=\"white\", method=\"caption\").set_position((\"center\", 600)).set_duration(AudioFileClip(audio_references[0]).duration)\n comment0_text = TextClip(txt=param[0], font='Comic-Sans-MS-Bold', align=\"west\", fontsize=42, size=(700,600), color=\"white\", method=\"caption\").set_position((\"center\", \"center\")).set_duration(AudioFileClip(audio_references[1]).duration)\n comment1_text = TextClip(txt=param[1], font='Comic-Sans-MS-Bold', align=\"west\", fontsize=42, size=(700,600), color=\"white\", method=\"caption\").set_position((\"center\", \"center\")).set_duration(AudioFileClip(audio_references[2]).duration)\n\n title_text.save_frame(\"content/title_text.png\")\n comment0_text.save_frame(\"content/comment0_text.png\")\n comment1_text.save_frame(\"content/comment1_text.png\")\n print(\"Text Ready\")\n\n final_audio.write_audiofile(\"content/finalaudio.mp3\")\n video = video.set_audio(AudioFileClip(\"content/finalaudio.mp3\"))\n\n print(\"Compiling Videos\")\n finalvideo = CompositeVideoClip([\n video, background_image, title_text.set_start(0).set_duration(title_audio_duration + pause),\n comment0_text.set_start(title_audio_duration + pause).set_duration(comment0_audio_duration + pause),\n comment1_text.set_start(title_audio_duration + comment0_audio_duration + pause * 2).set_duration(comment1_audio_duration + pause)\n ]).set_duration(AudioFileClip(\"content/finalaudio.mp3\").duration + pause)\n print(\"Compiled Videos\")\n finalvideo.write_videofile(file_title, fps=30)\n\n","repo_name":"AmmarKhawaja/reddit-videocreator","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4879,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"3729863593","text":"import tensorflow as tf\nfrom tensorflow.keras import layers\nfrom model.ops import MultiChannelEmbedding, ConvolutionLayer, MaxPooling\nfrom gluonnlp import Vocab\n\n\nclass SenCNN(tf.keras.Model):\n def __init__(self, num_classes: int, vocab: Vocab) -> None:\n super(SenCNN, self).__init__()\n self._embedding = MultiChannelEmbedding(vocab)\n self._convolution = ConvolutionLayer(300)\n self._pooling = MaxPooling()\n self._dropout = layers.Dropout(0.5)\n self._fc = layers.Dense(units=num_classes) # softmax는 여기에서 안 씀\n\n def call(self, x: tf.Tensor) -> tf.Tensor:\n fmap = self._embedding(x)\n fmap = self._convolution(fmap)\n feature = self._pooling(fmap)\n feature = self._dropout(feature)\n score = self._fc(feature)\n return score","repo_name":"modudeepnlp/NLP_Tensorflow2.0","sub_path":"cnn_sm/model/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"42"} +{"seq_id":"1817494138","text":"from tkinter import *\n\nfrom PIL import ImageTk, Image\n\nfrom RunGame import *\nfrom time import sleep\nimport threading\n\n\nclass GuiControls(Frame):\n def __init__(self, root, app, fullscreen):\n self.app = app\n\n w, h = root.winfo_screenwidth(), root.winfo_screenheight()\n root.attributes('-fullscreen', fullscreen)\n root.attributes(\"-topmost\", True)\n # root.resizable(width=False, height=False)\n root.geometry(\"%dx%d+0+0\" % (w, h))\n root.configure(background='black')\n\n self.root = root\n \n Frame.__init__(self, root, width=w, height=h, background=\"#000000\", cursor='none')\n self.canvas = Canvas(self, width=w, height=h, borderwidth=0, background=\"#000000\")\n\n self.title = [\n Label(self.canvas, text=\"START NEW\", background=\"#000000\", foreground=\"#00ff00\", font=(\"Courier\", 34)),\n Label(self.canvas, text=\"CONTINUE\", background=\"#000000\", foreground=\"#00ff00\", font=(\"Courier\", 34))]\n self.selected = 0\n self.selection_max = 2\n self.set_selection()\n\n image = Image.open(\"Controls.png\")\n image_ratio = (w / image.width)\n #image_ratio = 0.5\n self.photo = ImageTk.PhotoImage(image.resize((int(image.width * image_ratio), int(image.height * image_ratio)),\n Image.ANTIALIAS))\n\n self.canvas.create_image(0, 0, anchor=\"nw\", image=self.photo)\n for i, title in enumerate(self.title):\n self.canvas.create_window(w / (len(self.title) + 1) * (i + 1), h, anchor=\"s\", window=title)\n self.canvas.pack()\n self.pack()\n\n p1_movs = [\"Move\", \"Space\", \"Escape\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\"]\n p2_movs = [\"Move\", \"Kill\", \"Return\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\"]\n\n with open('./GameConfigs/' + self.app.game_widgets[self.app.selected_gf].game_id + '.lyt') as lyt:\n for line in lyt:\n if \"Joystick 1\" in line:\n movs = p1_movs\n elif \"Joystick 2\" in line:\n movs = p2_movs\n\n lines = line.split(\"#\")\n if len(lines) > 1:\n key = lines[1].strip()\n # print(lines[0], key)\n\n if \"Axis\" in lines[0]:\n movs[0] = key\n elif \"Button 1:\" in lines[0]:\n movs[1] = key\n elif \"Button 2:\" in lines[0]:\n movs[3] = key\n elif \"Button 3:\" in lines[0]:\n movs[4] = key\n elif \"Button 4:\" in lines[0]:\n movs[5] = key\n elif \"Button 5:\" in lines[0]:\n movs[6] = key\n elif \"Button 8:\" in lines[0]:\n movs[7] = key\n elif \"Button 9:\" in lines[0]:\n movs[8] = key\n elif \"Button 10:\" in lines[0]:\n movs[9] = key\n elif \"Button 11:\" in lines[0]:\n movs[10] = key\n elif \"Button 12:\" in lines[0]:\n movs[2] = key\n\n height_joy = int(435*image_ratio)\n self.joy1 = Label(self.canvas, text=p1_movs[0], background=\"#000000\", foreground=\"#00ff00\",\n font=(\"Courier\", 34))\n self.joy1.place(relx=int(215*image_ratio)/w, rely=height_joy/h, anchor='c')\n self.joy2 = Label(self.canvas, text=p2_movs[0], background=\"#000000\", foreground=\"#00ff00\",\n font=(\"Courier\", 34))\n self.joy2.place(relx=int(795*image_ratio)/w, rely=height_joy/h, anchor='c')\n\n height_bot_row = int(580*image_ratio)\n self.but_left = Label(self.canvas, text=p1_movs[1], background=\"#000000\", foreground=\"#00ff00\",\n font=(\"Courier\", 34))\n self.but_left.place(relx=int(100*image_ratio)/w, rely=height_bot_row/h, anchor='w')\n self.but_right = Label(self.canvas, text=p2_movs[2], background=\"#000000\", foreground=\"#00ff00\",\n font=(\"Courier\", 34))\n self.but_right.place(relx=int(1180*image_ratio)/w, rely=height_bot_row/h, anchor='e')\n\n self.but_center_left = Label(self.canvas, text=p1_movs[2], background=\"#000000\", foreground=\"#00ff00\",\n font=(\"Courier\", 34))\n self.but_center_left.place(relx=int(580*image_ratio)/w, rely=height_bot_row/h, anchor='e')\n self.but_center_right = Label(self.canvas, text=p2_movs[1], background=\"#000000\", foreground=\"#00ff00\",\n font=(\"Courier\", 34))\n self.but_center_right.place(relx=int(700*image_ratio)/w, rely=height_bot_row/h, anchor='w')\n\n height_but_top = int(235 * image_ratio)\n height_but_bot = int(365 * image_ratio)\n self.p1_buts = []\n self.p2_buts = []\n for i in range(4):\n self.p1_buts.append(\n self.canvas.create_text(int((385 + i * 66) * image_ratio), height_but_top,\n anchor=\"w\", font=(\"Courier\", 15), angle=45, fill=\"#00ff00\",\n text=p1_movs[i + 3]))\n self.p2_buts.append(\n self.canvas.create_text(int((960 + i * 66) * image_ratio), height_but_top,\n anchor=\"w\", font=(\"Courier\", 15), angle=45, fill=\"#00ff00\",\n text=p2_movs[i + 3]))\n for i in range(4):\n self.p1_buts.append(\n self.canvas.create_text(int((385 + i * 66) * image_ratio), height_but_bot,\n anchor=\"w\", font=(\"Courier\", 15), angle=-45, fill=\"#00ff00\",\n text=p1_movs[i + 7]))\n self.p2_buts.append(\n self.canvas.create_text(int((960 + i * 66) * image_ratio), height_but_bot,\n anchor=\"w\", font=(\"Courier\", 15), angle=-45, fill=\"#00ff00\",\n text=p2_movs[i + 7]))\n\n root.bind(\"\", self.quit_del)\n root.bind(\"\", self.up)\n root.bind(\"\", self.down)\n root.bind(\"\", self.up)\n root.bind(\"\", self.down)\n root.focus_set()\n\n def set_selection(self):\n for i, title in enumerate(self.title):\n if i != self.selected:\n title.configure(background=\"#000000\", foreground=\"#00ff00\")\n else:\n title.configure(background=\"#00ff00\", foreground=\"#000000\")\n\n def up(self, event):\n self.selected = (self.selected + 1) % self.selection_max\n self.set_selection()\n\n def down(self, event):\n self.selected = (self.selected - 1) if (self.selected - 1) >= 0 else self.selection_max - 1\n self.set_selection()\n \n def quit_del(self, event):\n # despite destroying, nothing gets refreshed until this method ends\n self.destroy()\n self.root.destroy()\n kill_gui_controller(self.app.qjoypad)\n \n self.app.run_game_after_controls_gui_closes()\n","repo_name":"david-simoes-93/ArcadePi","sub_path":"GuiControls.py","file_name":"GuiControls.py","file_ext":"py","file_size_in_byte":7248,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"42"} +{"seq_id":"38153597225","text":"'''\nProblem: Zero Matrix\nDescription: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to O.\nSolved: True\n'''\n\ndef parse_matrix(m):\n indexes = []\n\n for i in range(len(m)):\n for j in range(len(m[i])):\n if m[i][j] == 0:\n indexes.append([i, j])\n\n for ind in indexes:\n row = ind[0]\n column = ind[1]\n\n m[row] = [0]*len(m[0])\n for i in range(len(m)):\n m[i][column] = 0\n\n return m\n\n\nmatrix1 = [[0,2,3],[4,5,6],[7,8,9]]\nmatrix2 = [[1,2,3],[4,0,6],[7,8,9]]\nmatrix3 = [[1,2,3],[4,5,6],[7,8,0]]\n\nprint(parse_matrix(matrix1))\nprint(parse_matrix(matrix2))\nprint(parse_matrix(matrix3))","repo_name":"rconjaerts/code","sub_path":"Cracking the coding interview/Arrays & Strings/q_8.py","file_name":"q_8.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"73615319487","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n#1,11,21,1211,\n#后一个是对前一个数字的解释,1个1、2个1...\n\n__author__ = 'zhangchengliang'\n\ndef earlSeq(n):\n length = len(n)\n next = []\n now = 0\n for i in range(1, length):\n if n[i] != n[now]:\n next.append(i - now)\n next.append(n[now])\n now = i\n next.append(length - now)\n next.append(n[now])\n return next\n\nwhile 1:\n n = int(input())\n m = [1]\n for i in range(n-1):\n m = earlSeq(m)\n for i in m:\n print(i, end='')\n print()","repo_name":"silence9510/jisuanke","sub_path":"计数和数数.py","file_name":"计数和数数.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"26667999313","text":"class WordCounter:\r\n def __init__(self, file_list):\r\n self._word_count = []\r\n self._chars_count = []\r\n self._line_count = []\r\n self._file_list = file_list\r\n\r\n def _counting_chars(self, file_to_read):\r\n file = open(file_to_read, \"r\")\r\n file_content= file.read()\r\n count =len(file_content)\r\n file.close()\r\n return count\r\n\r\n def _counting_words(self, file_to_read):\r\n file = open(file_to_read, \"r\")\r\n file_content = file.read()\r\n count = len(file_content.split())\r\n file.close()\r\n return count\r\n\r\n\r\n def _counting_lines(self, file_to_read):\r\n file = open(file_to_read, \"r\")\r\n file_content = file.read()\r\n count = len(file_content.splitlines())\r\n file.close()\r\n return count\r\n\r\n def returning_count_of_chars_words_lines_in_every_file(self):\r\n for file in self._file_list:\r\n\r\n self._chars_count.append(self._counting_chars(file))\r\n self._word_count.append(self._counting_words(file))\r\n self._line_count.append(self._counting_lines(file))\r\n\r\n def returning_count_of_all_chars_words_lines_provided(self):\r\n self.returning_count_of_chars_words_lines_in_every_file()\r\n count_chars=0\r\n count_words=0\r\n count_lines=0\r\n for count in self._chars_count:\r\n count_chars+= count\r\n for count in self._word_count:\r\n count_words += count\r\n for count in self._line_count:\r\n count_lines += count\r\n print(\"Chars: {}\".format(count_chars))\r\n print(\"Words: {}\".format(count_words))\r\n print(\"Lines: {}\".format(count_lines))\r\n","repo_name":"katarzynalatos/Lab_1","sub_path":"problem2/WordCounter.py","file_name":"WordCounter.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"22146561236","text":"from django.db import models\nfrom django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation\nfrom django.contrib.contenttypes.models import ContentType\nfrom imagekit.models import ProcessedImageField\nfrom imagekit.processors import ResizeToFill\nfrom django.contrib.auth.hashers import make_password, check_password\n\n\n# Create your models here.\nclass Activity(models.Model):\n name = models.CharField(max_length=64, verbose_name=\"活动名称\")\n datetime_start = models.DateTimeField(verbose_name=\"活动开始时间\") # 活动开始时间\n datetime_end = models.DateTimeField(verbose_name=\"活动结束时间\") # 活动结束时间\n main_image = models.ImageField(upload_to=\"activity\", null=True)\n number_people = models.PositiveIntegerField()\n address = models.CharField(max_length=128, verbose_name=\"活动地址\")\n orderpeople_num = models.IntegerField(verbose_name=\"当前报名人数\", default=0)\n view_number = models.PositiveIntegerField(verbose_name=\"浏览数\")\n collect_number = models.PositiveIntegerField(verbose_name=\"收藏数\", default=0)\n partner = models.ManyToManyField(to=\"Partner\") # 合作方\n important_guests = models.ManyToManyField(to=\"Account\", related_name=\"important_guests\")\n\n activity_status_choices = ((0, '正在报名'), (1, '正在进行'), (2, '已过期'))\n activity_status = models.SmallIntegerField(choices=activity_status_choices, default=0)\n\n activity_type_choices = ((0, '免费'), (1, '收费'))\n activity_type = models.SmallIntegerField(choices=activity_type_choices, default=0, verbose_name=\"活动的费用类型\")\n tag = models.ManyToManyField(to=\"Tag\", blank=True, verbose_name=\"标签\")\n comment = GenericRelation(\"Comment\")\n\n def __str__(self):\n return \"活动{\"+self.name+\"}\"\n\nclass Partner(models.Model):\n name = models.CharField(max_length=128, verbose_name=\"合作方名称\")\n breif = models.TextField(max_length=1024, verbose_name=\"合作方简介\")\n\n def __str__(self):\n return self.name + '机构'\n\nclass ActivityDetail(models.Model):\n activity = models.OneToOneField(\"Activity\", on_delete=models.SET_NULL, null=True, blank=True)\n content = models.TextField(verbose_name=\"活动详情\")\n\n def __str__(self):\n return \"{\"+self.activity.name + \"}的详情\"\n\nclass Tag(models.Model):\n # content_type 表示content type表\n # content_type = models.ForeignKey(ContentType, blank=True, null=True, verbose_name=\"类型\", on_delete=models.CASCADE)\n # # object_id表示\n # object_id = models.PositiveIntegerField(blank=True, null=True)\n # content_object = GenericForeignKey('content_type', 'object_id')\n\n name = models.CharField(max_length=64, unique=True)\n breif = models.TextField(max_length=1024, null=True)\n\n def __str__(self):\n return self.name\n\nclass Institute(models.Model):\n name = models.CharField(max_length=64, verbose_name=\"文章标题\")\n post_datetime = models.DateTimeField(verbose_name=\"文章发布日期\", auto_now_add=True)\n author = models.ForeignKey(to=\"Account\", verbose_name=\"作者\", related_name='article_author', max_length=64, on_delete=models.CASCADE, default= '')\n thumb_up = models.PositiveIntegerField(verbose_name=\"点赞数\", default=0)\n view_num = models.PositiveIntegerField(verbose_name=\"浏览数\", default=0)\n reply_num = models.PositiveIntegerField(verbose_name=\"回复数\", default=0)\n main_image = ProcessedImageField(\n upload_to=\"institute\",\n null=True,\n processors=[ResizeToFill(600, 400)],\n format='JPEG',\n options={'quality': 75}\n )\n\n tag = models.ManyToManyField(to=Tag, blank=True, verbose_name=\"标签\")\n comment = GenericRelation(\"Comment\")\n\n def __str__(self):\n return self.name\n\nclass InstituteDetail(models.Model):\n institute = models.ForeignKey(\"Institute\", on_delete=models.SET_NULL, null=True, blank=True)\n content = models.TextField(verbose_name=\"学院帖子详情\")\n\n def __str__(self):\n return \"{\"+self.institute.name + \"}的内容\"\n\nclass InstituteRec(models.Model):\n institute = models.OneToOneField(to=\"Institute\", on_delete=models.SET_NULL, blank=True, null=True)\n weights_choices = ((1, '低'), (2, '中'), (3, '高'))\n weights = models.SmallIntegerField(choices=weights_choices, default=2)\n\n def __str__(self):\n return \"{推荐}\" + self.institute.name\n\nclass subjectList(models.Model):\n name = models.CharField(max_length=64, unique=True)\n brief = models.TextField(verbose_name=\"专题的详情\")\n article = models.ManyToManyField(to=\"Institute\")\n main_image = ProcessedImageField(\n upload_to=\"subject\",\n null=True,\n processors=[ResizeToFill(825, 300)],\n format='JPEG',\n options={'quality': 75}\n )\n\n def __str__(self):\n return \"{\" + self.name + \"}专题\"\n\nclass Products(models.Model):\n name = models.CharField(max_length=64, verbose_name=\"商品名称\")\n product_img = ProcessedImageField(\n upload_to=\"products\",\n null=True,\n processors=[ResizeToFill(800, 800)],\n format='JPEG',\n options={'quality': 75}\n )\n product_type_choices = ((0, '纪念品'), (1, '书籍'), (2, '文化衫'))\n product_type = models.SmallIntegerField(choices=product_type_choices)\n price = models.DecimalField(decimal_places=2, max_digits=6, default=0)\n sale_num = models.PositiveIntegerField(verbose_name=\"销售额\", default=0)\n store_num = models.PositiveIntegerField(verbose_name=\"库存量\", default=0)\n post_date = models.DateField(verbose_name=\"发布日期\", blank=True, null=True)\n status_choices = ((0, '预定中'), (1, '售卖中'), (2, '已售空'))\n status = models.SmallIntegerField(choices=status_choices)\n def __str__(self):\n return \"{\" + self.get_product_type_display() + \"}\" + self.name\n\nclass ProductsDetail(models.Model):\n product = models.OneToOneField(\"Products\", on_delete=models.SET_NULL, null=True, blank=True)\n content = models.TextField(verbose_name=\"商品描述\",max_length=2048)\n\n def __str__(self):\n return \"{\" + self.product.name + \"}详情\"\n\nclass ProductsParams(models.Model):\n product = models.ForeignKey(to=\"Products\", on_delete=models.SET_NULL, blank=True, null=True)\n meta_key = models.CharField(max_length=64, verbose_name=\"参数名\", null=True, blank=True)\n meta_value = models.CharField(max_length=255, verbose_name=\"参数值\", null=True, blank=True)\n\n def __str__(self):\n return self.product.name + \"{\" + self.meta_key + \"} \" + self.meta_value\n\nclass Params2Products(models.Model):\n product = models.ForeignKey(Products, on_delete=models.SET_NULL, null=True, blank=True)\n param = models.ForeignKey(ProductsParams, on_delete=models.SET_NULL, null=True, blank=True)\n\nclass Comment(models.Model):\n \"\"\"通用的评论表\"\"\"\n content_type = models.ForeignKey(ContentType, blank=True, null=True, verbose_name=\"类型\", on_delete=models.CASCADE)\n object_id = models.PositiveIntegerField(blank=True, null=True)\n content_object = GenericForeignKey('content_type', 'object_id')\n\n p_node = models.ForeignKey(\"self\", blank=True, null=True, verbose_name=\"父级评论\", on_delete=models.CASCADE)\n content = models.TextField(max_length=1024)\n account = models.ForeignKey(\"Account\", verbose_name=\"会员名\", on_delete=models.CASCADE)\n disagree_number = models.IntegerField(default=0, verbose_name=\"踩\")\n agree_number = models.IntegerField(default=0, verbose_name=\"赞同数\")\n date = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return self.content\n\n class Meta:\n verbose_name_plural = \"19. 通用评论表\"\n\n# ########################### 3. 用户相关 ################################\n\nclass Account(models.Model):\n username = models.CharField(\"用户名\", max_length=64, unique=True)\n password = models.CharField(\"密码\", max_length=64)\n\n uid = models.CharField(max_length=64, blank=True, help_text='微信用户绑定和CC视频统计') # 与第3方交互用户信息时,用这个uid,以避免泄露敏感用户信息\n openid = models.CharField(max_length=128, blank=True, null=True)\n weights_choices = ((0,\"普通会员\"),(1, '青铜会员'), (2, '白银会员'), (3, '金牌会员'))\n weights = models.SmallIntegerField(choices=weights_choices, default=0)\n # 贝里余额\n balance = models.PositiveIntegerField(default=0, verbose_name=\"可提现和使用余额\", null=True)\n\n # 多对多了\n article = models.ManyToManyField(to=\"Institute\", blank=True, verbose_name=\"发布的文章\")\n activity = models.ManyToManyField(to=\"Activity\", blank=True, verbose_name=\"参加的活动\")\n # products = models.ManyToManyField(to=\"Products\", blank=True, verbose_name=\"购买的产品\")\n\n def __str__(self):\n return self.username\n\nclass UserAuthToken(models.Model):\n \"\"\"\n 用户Token表\n \"\"\"\n user = models.OneToOneField(to=\"Account\", on_delete=models.CASCADE)\n token = models.CharField(max_length=64, unique=True)","repo_name":"palmzhang2019/BCCNweb","sub_path":"app01/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":9088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"10197207322","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jan 18 17:09:47 2022\r\n\r\n@author: wangf\r\n\"\"\"\r\n\r\n\r\n\r\n\r\n# set workdir, for example, 'F:/sample/sources/out'\r\nset_dir = 'O:/TFoTF_main/sample/sources/out'\r\n\r\n# Set the pearson correlation R score cut-off, Recommend > 0.6\r\nrvalue_cutoff = 0.6\r\n\r\n# Set the type of pwm score, you can choose between 'max1', 'max3', 'total'\r\npwm_type = 'max1'\r\n\r\n# Set the pwm score cut-off, Recommended > 8 for max1\r\npwm_cutoff = 8\r\n\r\n# The previously calculated processed data\r\nrvalue_file = 'rvalue_file_CREB1.csv'\r\npwm_file = 'pwm_file_CREB1.csv'\r\n\r\n# name the result file, and the file will be created in your workdir\r\nsavefile_to = 'predict_result_CREB1.csv'\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#DO NOT modify the following codes if you do not know their meaning.\r\nimport pandas as pd\r\nimport os\r\nos.chdir(set_dir)\r\np = pd.read_csv(pwm_file)\r\nr = pd.read_csv(rvalue_file)\r\n\r\nps = p[p[pwm_type] > pwm_cutoff]\r\nrs = r[r['Max_R'] > rvalue_cutoff]\r\n\r\nlr = rs.ID.to_list()\r\nlp = ps.gene.to_list()\r\n\r\ntmp = [val for val in lr if val in lp]\r\n\r\npps = ps[ps['gene'].isin(tmp)]\r\nrrs = rs[rs['ID'].isin(tmp)]\r\n\r\nrrrs = rrs[['Name','ID','Max_R']].set_index('Name',drop=True)\r\nppps = pps[['name','total','max1','max3']].set_index('name',drop=True)\r\n\r\nss = pd.concat([rrrs,ppps],axis=1)\r\n\r\nss.to_csv(savefile_to)\r\npa = os.path.abspath (savefile_to)\r\nprint('The prediction results, i.e. the list of target genes, are saved in the path: \\'{}\\''.format(pa))\r\n\r\n\r\n\r\n\r\n","repo_name":"tuitentouten/TFoTF","sub_path":"TFoTF_filter.py","file_name":"TFoTF_filter.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"38030669605","text":"from random import *\r\ndef main():\r\n\tLENGTH = randint(5, 6)\r\n\td = [[randint(1, 9) for i in range(LENGTH)] for j in range(LENGTH)]\r\n\tNOLINK = -1\t\t\t\t#NOLINK is defined to reprent that there is no direct link between two cities\r\n\tfor i in range(len(d)):\r\n\t\tfor j in range(len(d)):\r\n\t\t\tvalue = randint (0, 9)\r\n\t\t\tif value == 5:\t\t\t\t#in case of 5, consider no link, so chances are 1 out of 10\r\n\t\t\t\td[i][j] = NOLINK\r\n\t\t\tprint (d[i][j], end = ' ')\r\n\t\tprint()\r\n\tfor i in range(LENGTH):\r\n\t\td[i][i] = 0\r\n\tfor i in range(LENGTH):\r\n\t\tprint(f'City {i} has direct link with ', end='')\r\n\t\tfor j in range(LENGTH):\r\n\t\t\tif i != j and d[i][j] != NOLINK:\r\n\t\t\t\tprint(j, end = ' ')\r\n\t\tprint()\r\nmain()\r\n","repo_name":"Fawad-Mug/Python","sub_path":"Lab/Lab 12/Lab12_2_a.py","file_name":"Lab12_2_a.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"3907683231","text":"import ml_collections\n\n# Define a Hyperparameter dictionary for easy experimentation and hyperparameter\n# optimization\n\n\ndef model_config():\n cfg_dictionary = {\n \"root_dir\": \"./Data\",\n \"relationships_file\": \"relationship.csv\",\n \"content_file\": \"content.csv\",\n \"test_file\": \"test.csv\",\n \"validation_split\": 0.9,\n \"epochs\": 10,\n \"batch_size\": 256,\n \"embedding_size\": 256,\n \"random_seed\": 42,\n \"model_checkpoint\": \"NCF99\",\n }\n configs = ml_collections.FrozenConfigDict(cfg_dictionary)\n\n return configs\n\n\ncfg = model_config()\n","repo_name":"SupreethRao99/NeuRec","sub_path":"src/configs.py","file_name":"configs.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"33707877225","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('rushtracker', '0003_auto_20150416_1603'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='rush',\n name='rating',\n field=models.IntegerField(null=True, blank=True),\n ),\n ]\n","repo_name":"mattbrandman/rushmanager","sub_path":"rushtracker/migrations/0004_auto_20150416_2225.py","file_name":"0004_auto_20150416_2225.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"28627290365","text":"from fastapi import APIRouter, Depends, HTTPException\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom weblog.db import meta, models, posts, schemas, users\n\nrouter = APIRouter()\n\n\n@router.post(\"/create\", response_model=schemas.PostRead, tags=[\"posts\"])\nasync def create(\n post: schemas.PostCreate,\n user: models.User = Depends(users.active_verified_user),\n session: AsyncSession = Depends(meta.get_async_session),\n):\n return await posts.create(session, post=post, author_id=user.id)\n\n\n@router.get(\"/list\", response_model=list[schemas.PostRead], tags=[\"posts\"])\nasync def list(\n skip: int = 0,\n limit: int = 10,\n session: AsyncSession = Depends(meta.get_async_session),\n):\n post_list = await posts.list(session, skip=skip, limit=limit)\n return post_list\n\n\n@router.get(\"/get/{post_id}\", response_model=schemas.PostRead, tags=[\"posts\"])\nasync def get(post_id: int, session: AsyncSession = Depends(meta.get_async_session)):\n post = await posts.get(session, post_id=post_id)\n if not post:\n raise HTTPException(status_code=404, detail=\"Post not found\")\n return post\n\n\n@router.delete(\"/delete/{post_id}\", tags=[\"posts\"])\nasync def delete(\n post_id: int,\n session: AsyncSession = Depends(meta.get_async_session),\n _: models.User = Depends(users.active_verified_user),\n):\n return await posts.delete(session, post_id=post_id)\n\n\n@router.patch(\"/update/{post_id}\", tags=[\"posts\"])\nasync def update(\n post_id: int,\n post: schemas.PostUpdate,\n _: models.User = Depends(users.active_verified_user),\n session: AsyncSession = Depends(meta.get_async_session),\n):\n values = post.dict(exclude_unset=True)\n return await posts.update(session, post_id=post_id, values=values)\n","repo_name":"ahbk/weblog","sub_path":"api/weblog/endpoints/posts.py","file_name":"posts.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"6453789843","text":"# Default routing imports\nfrom django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.dashboard, name='home'),\n\n # Core Functionality\n path('offers/', views.offer_overview, name='offer_overview'),\n path('offers/', views.offer, name='offer'),\n path('offers//refresh', views.offer_refresh, name='offer_refresh'),\n path('offers/', views.offer_delete, name='offer_delete'),\n path('offers/create', views.offer_create, name='offer_create'),\n path('search/', views.search, name='search'),\n\n # Profile Area\n path('profile/', views.profile, name='profile'),\n path('profile//update', views.profile_update, name='profile_update'),\n path('profile//inventory', views.profile_inventory, name='profile_inventory'),\n path('profile//inventory/update', views.profile_inventory_update, name='profile_inventory_update'),\n\n # Redirects for the me area\n path('me', views.me, name='me'),\n path('me/settings', views.me_settings, name='me_settings'),\n path('me/inventory', views.me_inventory, name='me_inventory'),\n\n # Static Pages\n path('help', views.help, name='help'),\n path('imprint', views.imprint, name='imprint'),\n\n # OpenID Redirects\n path('signup', views.signup, name='signup'),\n path('signup_confirm', views.signup_confirm)\n]\n","repo_name":"creyD/asiimov","sub_path":"src/core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"42"} +{"seq_id":"4326989758","text":"# coding:utf-8\n\n\nfrom flask import render_template, request, jsonify, session, redirect, url_for\n\nfrom Service.campusManage import CampusManage\nfrom Service.changePwd import ChangePwd\nfrom Service.loginCheck import LoginCheck\nfrom Service.noticeManage import NoticeManage\nfrom Service.redis_service import RedisService\nfrom Service.selcourseManage import SelcourseManage\nfrom Service.achievementManage import AchievementManage\nfrom Service.stu_service import StuService\nfrom WTF_Form.login_form import LoginForm\nfrom . import app_stu\nfrom Log.loginLog import LoginLog\n\n\n@app_stu.before_request\ndef before_request():\n url = request.path\n if len(url.split(\"/\")) > 3:\n stu = session.get(\"stu\")\n if stu is None:\n return render_template(\"page404.html\"), 404\n\n\n@app_stu.route(\"/\")\ndef stu_login():\n \"\"\"返回学生登录页面\"\"\"\n form = LoginForm()\n return render_template(\"student/stu_login.html\", form=form)\n\n\n@app_stu.route(\"/index\", methods=[\"POST\"])\ndef stu_index():\n \"\"\"登录成功返回学生主页\"\"\"\n data = request.form\n user = data.get(\"username\")\n password = data.get(\"password\")\n ip = request.remote_addr\n\n if user is None or password is None:\n return render_template(\"page404.html\"), 404 # 防止使用postman等工具进行访问\n\n stu = LoginCheck.stu_pwd_check(user, password)\n\n if stu is None:\n # 保存日志\n LoginLog.login_error(LoginLog.stu_log_error(user, ip))\n return render_template(\"student/stu_login.html\",\n form=LoginForm(),\n error=\"账号或密码错误!\") # 系统提示\n else:\n # 保存日志\n LoginLog.login_success(LoginLog.stu_log_success(user, ip))\n\n data = LoginCheck.stu_to_dict(stu)\n # 保存用户session\n session[\"stu\"] = stu\n pic = stu.sname[-2:]\n notice_li = NoticeManage.get_by_isover(0)\n return render_template(\"student/stu_index.html\", **data,\n pic=pic, notice_li=notice_li)\n\n\n@app_stu.route(\"/changePwd\", methods=[\"POST\"])\ndef change_pwd():\n \"\"\"修改密码操作\"\"\"\n stu = session.get(\"stu\")\n if stu is None:\n return jsonify({\n \"tip\": \"账号已下线,请重新登录!\"\n })\n\n # 获取修改密码数据\n data = request.form\n old_pwd = data.get(\"old_pwd\") # 获取原密码\n new_pwd1 = data.get(\"new_pwd1\") # 获取新密码\n new_pwd2 = data.get(\"new_pwd2\") # 获取新确认密码\n\n bl = ChangePwd.stu_change_pwd(stu.id, old_pwd, new_pwd1, new_pwd2)\n if bl is True:\n return jsonify({\"tip\": \"修改成功!\"})\n else:\n return jsonify({\"tip\": \"修改失败!\"})\n\n\n@app_stu.route(\"/stuExit\")\ndef stu_exit():\n \"\"\"退出登录操作\"\"\"\n session.pop(\"stu\", None)\n return redirect(url_for(\"app_stu.stu_login\"))\n\n\n@app_stu.route(\"/courseSelGet\")\ndef course_sel_get():\n \"\"\"学生选课信息查询\"\"\"\n sid = request.form.get(\"sid\")\n\n cosel_li = SelcourseManage.get_by_sid(sid)\n return jsonify(cosel_li)\n\n\n@app_stu.route(\"/gradeGet\")\ndef grade_get():\n \"\"\"成绩查看页面\"\"\"\n stu = session.get(\"stu\")\n if stu is None:\n return render_template(\"page404.html\"), 404\n\n achi_li = AchievementManage.get_by_sid(stu.id)\n crd_sum, gpa = StuService.count_gpaandcredits(achi_li)\n return render_template(\"student/grade_get.html\",\n achi_li=achi_li,\n crd_sum=crd_sum,\n gpa=gpa)\n\n\n@app_stu.route(\"/coursePreview\", methods=[\"POST\", \"GET\"])\ndef course_preview():\n \"\"\"课程预览页面\"\"\"\n stu = session.get(\"stu\")\n if stu is None:\n return render_template(\"page404.html\"), 404\n\n data = request.form\n page = int(data.get(\"page\", request.args.get(\"page\", 1)))\n caid = int(data.get(\"caid\", session.get(\"caid\", -1)))\n ctype = data.get(\"ctype\", session.get(\"ctype\", \"all\"))\n week = data.get(\"week\", session.get(\"week\", \"all\"))\n session[\"caid\"] = caid\n session[\"ctype\"] = ctype\n session[\"week\"] = week\n\n course_li, sum, pagenum, page = StuService.get_preview_course(caid, ctype, week, page, 3)\n campus_li = CampusManage.get_all()\n\n return render_template(\"student/course_preview.html\",\n campus_li=campus_li,\n course_li=course_li,\n page=page,\n pagenum=pagenum,\n sum=sum)\n\n\n@app_stu.route(\"/previewPage\", methods=[\"POST\", \"GET\"])\ndef preview_page():\n \"\"\"课程预选页面\"\"\"\n stu = session.get(\"stu\")\n if stu is None:\n return render_template(\"page404.html\"), 404\n\n if not RedisService.judgestu_iscan_selectcourse(stu.id):\n return render_template(\"not_allow.html\", message=\"你被禁止选课,有问题请联系管理员...\")\n\n crd_sum = StuService.count_credit(stu.id)\n if crd_sum >= 33:\n return render_template(\"not_allow.html\", message=\"所修学分已满,不需要选课...\")\n\n if RedisService.judge_can_sel(stu):\n return redirect(url_for(\"app_stu.sel_course_page\"))\n\n data = request.form\n page = int(data.get(\"page\", request.args.get(\"page\", 1)))\n caid = stu.caid\n ctype = data.get(\"ctype\", session.get(\"ctype\", \"all\"))\n week = data.get(\"week\", session.get(\"week\", \"all\"))\n session[\"caid\"] = caid\n session[\"ctype\"] = ctype\n session[\"week\"] = week\n\n course_li, sum, pagenum, page = StuService.get_preview_course(caid, ctype, week, page, 6)\n preview_li = StuService.get_predone(stu.sno)\n\n return render_template(\"student/preview_page.html\",\n course_li=course_li,\n page=page,\n pagenum=pagenum,\n sum=sum,\n preview_li=preview_li)\n\n\n@app_stu.route(\"/preview\", methods=[\"POST\"])\ndef preview():\n \"\"\"预选操作\"\"\"\n stu = session.get(\"stu\")\n if stu is None:\n return jsonify({\n \"tip\": \"账号已下线,请重新登录!\"\n })\n cid_li = request.form.get(\"cid_li\").split(\",\")\n bl = StuService.save_preview(stu.sno, cid_li)\n if bl:\n return jsonify({\"tip\": \"预选课程成功,预选的课程一个星期内有效!\"})\n else:\n return jsonify({\"tip\": \"预选课程失败!\"})\n\n\n@app_stu.route(\"/courseRecord\")\ndef course_record():\n \"\"\"学生选课记录页面\"\"\"\n stu = session.get(\"stu\")\n if stu is None:\n return render_template(\"page404.html\"), 404\n\n selcourse_li = SelcourseManage.get_by_sid(stu.id)\n return render_template(\"student/course_record.html\", selcourse_li=selcourse_li)\n\n\n@app_stu.route(\"/selCoursePage\", methods=[\"POST\", \"GET\"])\ndef sel_course_page():\n \"\"\"选课操作页面\"\"\"\n stu = session.get(\"stu\")\n if stu is None:\n return render_template(\"page404.html\"), 404\n\n if RedisService.judge_can_sel(stu) is False:\n return render_template(\"not_allow.html\", message=\"不在选课时段,无法进行选课和退选...\")\n\n if not RedisService.judgestu_iscan_selectcourse(stu.id):\n return render_template(\"not_allow.html\", message=\"你被禁止选课,有问题请联系管理员...\")\n\n crd_sum = StuService.count_credit(stu.id)\n if crd_sum >= 33:\n return render_template(\"not_allow.html\", message=\"所修学分已满,不需要选课...\")\n\n data = request.form\n page = int(data.get(\"page\", request.args.get(\"page\", 1)))\n caid = stu.caid\n ctype = data.get(\"ctype\", session.get(\"ctype\", \"all\"))\n week = data.get(\"week\", session.get(\"week\", \"all\"))\n session[\"caid\"] = caid\n session[\"ctype\"] = ctype\n session[\"week\"] = week\n\n course_li, sum, pagenum, page = StuService.get_preview_course(caid, ctype, week, page, 16)\n preview_li = StuService.get_predone(stu.sno)\n sel_li = SelcourseManage.get_by_sidnoend(stu.id)\n\n return render_template(\"student/sel_course.html\",\n course_li=course_li,\n preview_li=preview_li,\n sel_li=sel_li,\n page=page,\n pagenum=pagenum,\n sum=sum)\n\n\n@app_stu.route(\"/selCourse\", methods=[\"POST\"])\ndef sel_course():\n \"\"\"选课提交操作\"\"\"\n stu = session.get(\"stu\")\n if stu is None:\n return jsonify({\n \"tip\": \"账号已下线,请重新登录!\"\n })\n\n sel_li = request.form.get(\"sel_li\").split(\",\")\n\n bl, cids = StuService.save_sel_course(stu.id, stu.sno, stu.caid, sel_li)\n if bl:\n return jsonify({\n \"tip\": cids.split(\",\"),\n \"bl\": 200\n })\n else:\n return jsonify({\n \"tip\": cids.split(\",\"),\n \"bl\": 400\n })\n\n\n@app_stu.route(\"/selRemove\", methods=[\"POST\"])\ndef sel_remove():\n \"\"\"退选课操作\"\"\"\n stu = session.get(\"stu\")\n if stu is None:\n return jsonify({\n \"tip\": \"账号已下线,请重新登录!\"\n })\n\n cid = request.form.get(\"cid\")\n bl, tip = StuService.remove_sel_course(stu.id, stu.sno, cid, stu.caid)\n if bl:\n return jsonify({\n \"bl\": 200,\n \"tip\": tip\n })\n else:\n return jsonify({\n \"bl\": 400,\n \"tip\": tip\n })\n\n","repo_name":"wooyee-ldq/Public.elective.management.system","sub_path":"Student/route.py","file_name":"route.py","file_ext":"py","file_size_in_byte":9361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"4561132654","text":"#!/usr/bin/python3\n\"\"\"Solves the N-queens puzzle. \"\"\"\n\n\nimport sys\n\n\ndef solve_nqueens(N):\n \"\"\"\n Solve the N Queens problem and return a list of solutions.\n Each solution is represented as a list of queen positions.\n \"\"\"\n solutions = [] # Store the solutions\n queens = [] # Store the positions of the queens\n place_queen(0, queens, N, solutions)\n return solutions\n\n\ndef place_queen(row, queens, N, solutions):\n \"\"\"\n Recursive function to place queens on the chessboard.\n Backtracking is used to find all valid solutions.\n \"\"\"\n\n if row == N:\n # All queens have been successfully placed\n solutions.append(list(queens))\n return\n\n for col in range(N):\n if is_valid(row, col, queens):\n # Place a queen at position (row, col)\n queens.append(col)\n place_queen(row + 1, queens, N, solutions)\n # Backtrack by removing the last queen and trying other positions\n queens.pop()\n\n\ndef is_valid(row, col, queens):\n \"\"\"\n Check if placing a queen at position (row, col) is valid.\n Return True if there are no conflicts, False otherwise.\n \"\"\"\n for r, c in enumerate(queens):\n # Check if the current queen conflicts with\n # any previously placed queens\n if c == col or r + c == row + col or r - c == row - col:\n return False\n return True\n\n\ndef print_solutions(solutions):\n \"\"\"\n Print the solutions in the required format.\n \"\"\"\n for solution in solutions:\n chessboard = []\n for row in range(len(solution)):\n chessboard.append([row, solution[row]])\n print(chessboard)\n\n\nif __name__ == \"__main__\":\n # Validate the input arguments\n if len(sys.argv) != 2:\n print(\"Usage: nqueens N\")\n sys.exit(1)\n\n try:\n N = int(sys.argv[1])\n except ValueError:\n print(\"N must be a number\")\n sys.exit(1)\n\n if N < 4:\n print(\"N must be at least 4\")\n sys.exit(1)\n\n # Solve the N Queens problem and print the solutions\n solutions = solve_nqueens(N)\n print_solutions(solutions)\n","repo_name":"RealKingTino/alx-higher_level_programming","sub_path":"0x08-python-more_classes/101-nqueens.py","file_name":"101-nqueens.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"27367627839","text":"import torch\nfrom torch.optim import lr_scheduler\n\nimport numpy\nfrom utils import *\n# from dataLoader import *\nfrom model import *\nfrom torch.utils.tensorboard import SummaryWriter\n\n\nclass TrainerSides:\n def __init__(\n self,\n opt,\n logfile_name,\n device=None\n ):\n self.logfile_name = logfile_name\n if device is None:\n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n else:\n self.device = device\n\n print('Pretrained style:', opt.pretrained_style)\n self.StyleNet = StyleNetwork(-1).to(device)\n if not (opt.pretrained_style is None):\n self.StyleNet.load_state_dict(\n torch.load(f'{opt.pretrained_style}/Style.pth',\n map_location=torch.device(device)))\n self.StyleNet.eval() \n\n print('Pretrained sides:', opt.pretrained)\n if not ((opt.pretrained is None) or (opt.pretrained == 'None')):\n self.SidesNet = FaderNetwork().to(device)\n self.SidesNet.load_state_dict(\n torch.load(opt.pretrained + '/sides.pth',\n map_location=torch.device(device)))\n else:\n self.SidesNet = FaderNetwork().to(device)\n # self.SidesNet = FaderNetwork(normalization='instance').to(device)\n # self.SidesNet.encoder.load_state_dict(self.StyleNet.encoder.state_dict())\n \n self.SidesNet.train()\n\n self.optimizer = optim.Adam(\n list(self.SidesNet.parameters()),\n lr=opt.lr,\n betas=(opt.beta1, 0.999))\n\n self.scheduler = lr_scheduler.StepLR(\n self.optimizer,\n step_size=10, \n gamma=0.1)\n\n self.sides_weight = 1\n self.losses = {}\n self.weight_sides = opt.weight_sides\n\n def training(\n self, \n data_loader, \n data_loader_val, \n num_epochs=1, \n loss='l1', \n burnin=1000\n ):\n print(f\"Starting Training Loop with {loss} for {num_epochs} epochs...\")\n\n if loss == 'l2':\n loss = torch.nn.MSELoss(reduction='mean')\n else:\n loss = torch.nn.L1Loss(reduction='mean')\n \n dataiter = iter(data_loader_val)\n syn_tgt_test, real_tgt_test, _ = dataiter.next()\n syn_tgt_test = syn_tgt_test.to(self.device)\n real_tgt_test = real_tgt_test.to(self.device)\n\n with torch.no_grad():\n syn_assyn_test = self.StyleNet(\n syn_tgt_test[:, :, :, 64:-64], \n real=False)\n real_assyn_test = self.StyleNet(\n real_tgt_test[:, :, :, 64:-64],\n real=False)\n\n writer = SummaryWriter()\n iters = 0\n try:\n for epoch in range(num_epochs):\n for syn_tgt, real_tgt, _ in data_loader:\n syn_tgt, real_tgt =\\\n signal_to_device(syn_tgt, real_tgt, self.device)\n \n with torch.no_grad():\n syn_assyn =\\\n self.StyleNet(\n syn_tgt[:, :, :, 64:-64], real=False\n ).clone().detach() \n real_assyn =\\\n self.StyleNet(\n real_tgt[:, :, :, 64:-64], real=False\n ).clone().detach()\n \n self.SidesNet.train()\n self.SidesNet.zero_grad()\n\n reconsts_syn = self.SidesNet(syn_assyn)\n reconsts_real = self.SidesNet(real_assyn)\n\n rec_loss =\\\n loss(reconsts_syn[:, :, :, 64:-64], syn_assyn)\n rec_loss_real =\\\n loss(reconsts_real[:, :, :, 64:-64], real_assyn)\n \n rec_loss_right =\\\n loss(reconsts_syn[:, :, :, -64:], \n syn_tgt[:, :, :, -64:])\n rec_loss_left =\\\n loss(reconsts_syn[:, :, :, :64], \n syn_tgt[:, :, :, :64])\n\n if iters > burnin:\n total_loss =\\\n self.weight_sides*(rec_loss_right + rec_loss_left)\n else:\n total_loss =\\\n self.weight_sides*(rec_loss_right + rec_loss_left)+\\\n rec_loss + rec_loss_real\n\n total_loss.backward()\n self.optimizer.step()\n\n self.losses['TRAIN_center'] = rec_loss.item()\n self.losses['TRAIN_left'] = rec_loss_left.item()\n self.losses['TRAIN_right'] = rec_loss_right.item()\n self.losses['TRAIN_center_REAL'] = rec_loss_real.item()\n self.losses['TOTAL_LOSS'] = total_loss.item()\n \n if iters % 100 == 0:\n with torch.no_grad():\n self.SidesNet.eval()\n reconsts_syn_test = self.SidesNet(syn_assyn_test)\n self.losses['VAL_center'] =\\\n loss(reconsts_syn_test[:, :, :, 64:-64], \n syn_assyn_test).item()\n self.losses['VAL_left'] =\\\n loss(reconsts_syn_test[:, :, :, :64], \n syn_tgt_test[:, :, :, :64]).item()\n self.losses['VAL_right'] =\\\n loss(reconsts_syn_test[:, :, :, -64:], \n syn_tgt_test[:, :, :, -64:]).item()\n\n reconsts_real_test =\\\n self.SidesNet(real_assyn_test)\n self.losses['VAL_center_real'] =\\\n loss(reconsts_real_test[:, :, :, 64:-64], \n real_assyn_test).item()\n self.losses['VAL_left_real'] =\\\n loss(reconsts_real_test[:, :, :, :64], \n real_tgt_test[:, :, :, :64]).item()\n self.losses['VAL_right_real'] =\\\n loss(reconsts_real_test[:, :, :, -64:], \n real_tgt_test[:, :, :, -64:]).item()\n\n self.SidesNet.train()\n\n for loss_name in self.losses.keys():\n writer.add_scalar(f'Sides/{loss_name}',\n self.losses[loss_name], iters)\n \n writer.add_image('TARGET Synthetic',\n pretty_batch(syn_tgt), iters)\n writer.add_image('TARGET Real',\n pretty_batch(real_tgt), iters)\n \n writer.add_image('INPUT Synthetic',\n pretty_batch(syn_assyn), iters)\n writer.add_image('INPUT Real',\n pretty_batch(real_assyn), iters)\n\n writer.add_image('RECONSTRUCTION Synthetic',\n pretty_batch(reconsts_syn), iters)\n writer.add_image('RECONSTRUCTION Real',\n pretty_batch(reconsts_real), iters)\n\n writer.add_image('VAL TARGET Real',\n pretty_batch(real_assyn_test), iters)\n writer.add_image('VAL TARGET Synthetic',\n pretty_batch(syn_assyn_test), iters) \n writer.add_image('VAL RECONSTRUCTION Synthetic',\n pretty_batch(reconsts_syn_test), iters)\n writer.add_image('VAL RECONSTRUCTION Real',\n pretty_batch(reconsts_real_test), iters) \n\n print(f\"[{epoch}/{num_epochs}][{iters}]\\t\",\\\n f\"Total_loss: {self.losses['TOTAL_LOSS']:.2e}\")\n\n iters += 1\n self.scheduler.step()\n if (epoch % 5 == 0) and (epoch > 0):\n print(f'Autosave epoch = {epoch}')\n self.save(suffix=str(epoch))\n\n writer.flush()\n writer.close()\n self.save()\n\n except KeyboardInterrupt:\n writer.flush()\n writer.close()\n self.save()\n\n def save(self, suffix=''):\n torch.save(self.SidesNet.state_dict(), f'{self.logfile_name}/sides{suffix}.pth')\n print(f'Results saved to {self.logfile_name}')\n\n\n ","repo_name":"klanita/sigoat","sub_path":"trainSidesDA.py","file_name":"trainSidesDA.py","file_ext":"py","file_size_in_byte":8856,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"42"} +{"seq_id":"71408182846","text":"from distance_calculator import *\nfrom sklearn.cluster import KMeans\nfrom dimensionality_reducer_fns import *\nimport numpy as np\nimport pandas as pd\nimport os\n\n\nclass Kmeans:\n \"\"\"\n Represents Kmeans dimension technique\n ...\n Attributes:\n k: int\n Number of reduced features\n\n X: ndarray of shape (num_objects, num_features)\n Data matrix to be reduced\n\n Methods:\n transform(X)\n Transforms and returns X in the latent semantic space and the latent semantics\n \"\"\"\n\n def __init__(self, *args):\n \"\"\"\n :param data_matrix: input matrix of shape (num_objects, num_features)\n Data matrix to be reduced\n :param k: Number of reduced features\n\n OR\n :param folder: folder containing LDA latent features\n\n \"\"\"\n if (len(args)) == 2:\n # normal object instantiation with data_matrix and k\n A1 = args[1]\n k = args[0]\n A = np.array(A1)\n size = A.shape[0]\n # reducedMatrix = np.zeros((size, k))\n kmeans = KMeans(n_clusters=k, random_state=0).fit(A)\n self.centers = kmeans.cluster_centers_\n # DESIGN_DECISION: WHY is it size*k and not k*size? k representative objects with mean features\n self.new_object_map = np.zeros((size, k))\n self.weight = np.zeros((size))\n for i in range(0, size):\n self.new_object_map[i] = manhattan_fn(A[i], self.centers)\n # print(np.sum(self.new_object_map[i]))\n self.weight[i] = np.sum(self.new_object_map[i])\n # Since good latent semantics give high discrimination power\n # DESIGN_DECISION: variance or distance maximized? Distance as we have a center not a line or curve\n temp, self.sub_wt_pairs = get_sorted_matrix_on_weights(self.weight, self.new_object_map,\n return_order=True)\n elif (len(args)) == 1:\n self.centers = pd.read_csv(os.path.join(args[0], \"centers.csv\")).to_numpy()\n self.new_object_map = pd.read_csv(os.path.join(args[0], \"new_object_map.csv\")).to_numpy()\n self.weight = pd.read_csv(os.path.join(args[0], \"weight.csv\")).to_numpy()\n self.sub_wt_pairs = pd.read_csv(os.path.join(args[0], \"sub_wt_pairs.csv\")).to_numpy()\n else:\n raise Exception(\"Invalid object instantiation: parameters must be either , \"\n \"or .\")\n\n def get_decomposition(self):\n \"\"\"\n Parameters:\n X: ndarray of shape (num_objects, num_features)\n Data matrix to be reduced\n\n Returns:\n Transforms and returns X in the latent semantic space and the latent semantics\n \"\"\"\n return self.centers\n\n def get_latent_features(self):\n \"\"\"\n :return: centers\n \"\"\"\n return self.centers\n\n def get_vector_space(self):\n \"\"\"\n :return: vector space of PCA\n \"\"\"\n return self.new_object_map\n\n def transform(self, data_matrix):\n \"\"\"\n :param data_matrix: matrix to transform (query_objects, num_features)\n :return: pca transformed matrix\n \"\"\"\n new_map = np.zeros((len(data_matrix), len(self.centers)))\n # for j in range(len(self.centers)):\n new_map = manhattan_fn(data_matrix[:len(self.centers)], self.centers)\n return new_map\n\n def get_obj_weight_pairs(self):\n \"\"\"\n :return: objects\n :return: weights\n \"\"\"\n return self.sub_wt_pairs\n\n def save(self, folder):\n \"\"\"\n Save Kmeans to given folder\n \"\"\"\n pd.DataFrame(self.centers).to_csv(os.path.join(folder, \"centers.csv\"), index=False)\n pd.DataFrame(self.new_object_map).to_csv(os.path.join(folder, \"new_object_map.csv\"), index=False)\n pd.DataFrame(self.weight).to_csv(os.path.join(folder, \"weight.csv\"), index=False)\n pd.DataFrame(self.sub_wt_pairs).to_csv(os.path.join(folder, \"sub_wt_pairs.csv\"), index=False)\n\n def get_top_k_matches(self, k, xq):\n return manhattan(self.new_object_map, k, self.transform([xq]))\n\n","repo_name":"CodeHime/MWDB_image_similarity_search_optimizations","sub_path":"Code/src/kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":4279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"17474674022","text":"from random import choice\nfrom typing import Tuple, List, Optional\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass\n\nfrom CybORG.Shared import Observation\nfrom CybORG.Shared.Actions import Action\nfrom CybORG.Shared.Enums import DecoyType\nfrom CybORG.Simulator.Host import Host\nfrom CybORG.Simulator.Session import Session\nfrom CybORG.Simulator.State import State\n\n\n@dataclass\nclass Decoy:\n \"\"\"\n Contains information necessary to create a misinform process on a host\n \"\"\"\n service_name: str\n name: str\n open_ports: List[dict]\n process_type: str\n process_path: Optional[str] = None\n version: Optional[str] = None\n properties: Optional[List[str]] = None\n\ndef _is_host_using_port(host: Host, port: int):\n \"\"\"\n Convenience method for checking if a host is using a port\n \"\"\"\n if host.processes is not None:\n for proc in host.processes:\n for proc_state in proc.get_state():\n if proc_state.get('local_port', None) == port:\n return True\n return False\n\nclass DecoyFactory(ABC):\n \"\"\"\n Assembles process informationt to appear as a vulnerable process\n \"\"\"\n @abstractmethod\n def make_decoy(self, host: Host) -> Decoy:\n \"\"\"\n Creates a Decoy instance that contains the necessary information\n to put a decoy on a given host.\n\n :param host: Host that this decoy will be placed on\n \"\"\"\n\n @abstractmethod\n def is_host_compatible(self, host: Host) -> bool:\n \"\"\"\n Determines whether an instance of this decoy can be placed\n successfully on the given host\n\n :param host: Host to examine for compatibility with this decoy.\n \"\"\"\n\nclass SSHDDecoyFactory(DecoyFactory):\n \"\"\"\n Assembles process information to appear as an ssh server\n \"\"\"\n def make_decoy(self, host: Host) -> Decoy:\n del host\n return Decoy(service_name=\"sshd\", name=\"Sshd.exe\",\n open_ports=[{'local_port':22, 'local_address':'0.0.0.0'}],\n process_type=\"sshd\",\n process_path=\"C:\\\\Program Files\\\\OpenSSH\\\\usr\\\\sbin\")\n\n def is_host_compatible(self, host: Host) -> bool:\n return not _is_host_using_port(host, 22)\nsshd_decoy_factory = SSHDDecoyFactory()\n\nclass ApacheDecoyFactory(DecoyFactory):\n \"\"\"\n Assembles process information to appear as an apache server\n \"\"\"\n def make_decoy(self, host: Host) -> Decoy:\n del host\n return Decoy(service_name=\"apache2\", name=\"apache2\",\n open_ports=[{'local_port':80, 'local_address':'0.0.0.0'}],\n process_type=\"webserver\", properties=[\"rfi\"],\n process_path=\"/usr/sbin\")\n\n def is_host_compatible(self, host: Host) -> bool:\n return not _is_host_using_port(host, 80)\napache_decoy_factory = ApacheDecoyFactory()\n\nclass SMSSDecoyFactory(DecoyFactory):\n \"\"\"\n Assembles process information to appear as smss\n \"\"\"\n def make_decoy(self, host: Host) -> Decoy:\n del host\n return Decoy(service_name=\"smss\", name=\"Smss.exe\",\n open_ports=[{'local_port':139, 'local_address':'0.0.0.0'}],\n process_type=\"smss\")\n\n def is_host_compatible(self, host: Host) -> bool:\n return not _is_host_using_port(host, 139)\nsmss_decoy_factory = SMSSDecoyFactory()\n\nclass TomcatDecoyFactory(DecoyFactory):\n \"\"\"\n Assembles process information to appear as a tomcat server\n \"\"\"\n def make_decoy(self, host: Host) -> Decoy:\n del host\n return Decoy(service_name=\"tomcat\", name=\"Tomcat.exe\",\n open_ports=[{'local_port':443, 'local_address':'0.0.0.0'}],\n process_type=\"webserver\", properties=[\"rfi\"])\n\n def is_host_compatible(self, host: Host) -> bool:\n return not _is_host_using_port(host, 443)\n\ntomcat_decoy_factory = TomcatDecoyFactory()\n\nclass SvchostDecoyFactory(DecoyFactory):\n \"\"\"\n Assembles process information to appear as svchost\n \"\"\"\n def make_decoy(self, host: Host) -> Decoy:\n del host\n return Decoy(service_name=\"svchost\", name=\"Svchost.exe\",\n open_ports=[{'local_port':3389, 'local_address':'0.0.0.0'}],\n process_type=\"svchost\")\n\n def is_host_compatible(self, host: Host) -> bool:\n return not _is_host_using_port(host, 3389)\nsvchost_decoy_factory = SvchostDecoyFactory()\n\nclass Misinform(Action):\n \"\"\"\n Creates a misleading process on the designated host depending on\n available and compatible options.\n \"\"\"\n def __init__(self, *, session: int, agent: str, hostname: str):\n self.agent = agent\n self.session = session\n self.hostname = hostname\n self.decoy_type = DecoyType.SANDBOXING_EXPLOIT\n self.candidate_decoys = (\n sshd_decoy_factory,\n apache_decoy_factory,\n smss_decoy_factory,\n tomcat_decoy_factory,\n svchost_decoy_factory)\n\n def emu_execute(self) -> Observation:\n raise NotImplementedError\n\n def sim_execute(self, state: State) -> Observation:\n obs_fail = Observation(False)\n obs_succeed = Observation(True)\n\n sessions = [s for s in state.sessions[self.agent].values() if\n s.host == self.hostname]\n if len(sessions) == 0:\n return obs_fail\n\n session = choice(sessions)\n host = state.hosts[self.hostname]\n\n try:\n decoy_factory = self.__select_one_factory(host)\n decoy = decoy_factory.make_decoy(host)\n self.__create_process(obs_succeed, session, host, decoy)\n #print (\"Misinform Success. Result: {}\".format(result))\n\n return obs_succeed\n\n except RuntimeError:\n #print (\"Misinform FAILURE\")\n return obs_fail\n\n\n def __select_one_factory(self, host: Host) -> DecoyFactory:\n \"\"\"\n Examines all decoy factories and returns one randomly compatible one.\n Raises RuntimeError if no compatible ones are found.\n \"\"\"\n\n compatible_factories = [factory for factory in self.candidate_decoys\n if factory.is_host_compatible(host) ]\n\n if len(compatible_factories) == 0:\n raise RuntimeError(\"No compatible factory\")\n\n return choice(list(compatible_factories))\n\n def __create_process(self, obs: Observation, sess: Session, host: Host,\n decoy: Decoy) -> None:\n \"\"\"\n Creates a process & service from Decoy on current host, adds it\n to the observation.\n \"\"\"\n\n parent_pid = 1\n\n process_name = decoy.name\n username = sess.username\n version = decoy.version\n open_ports = decoy.open_ports\n process_type = decoy.process_type\n process_props = decoy.properties\n\n service_name = decoy.service_name\n\n new_proc = host.add_process(name=process_name, ppid=parent_pid,\n user=username, version=version, process_type=process_type,\n open_ports=open_ports, decoy_type=self.decoy_type,\n properties=process_props)\n\n host.add_service(service_name=service_name, process=new_proc.pid,\n session=sess)\n\n obs.add_process(hostid=self.hostname, pid=new_proc.pid,\n parent_pid=parent_pid, name=process_name,\n username=username, service_name=service_name,\n properties=process_props)\n\n def __str__(self):\n return f\"{self.__class__.__name__} {self.hostname}\"\n","repo_name":"cage-challenge/cage-challenge-1","sub_path":"CybORG/CybORG/Shared/Actions/AbstractActions/Misinform.py","file_name":"Misinform.py","file_ext":"py","file_size_in_byte":7533,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"42"} +{"seq_id":"10132351387","text":"#!/usr/bin/env python3\n\nfrom hashlib import md5\n\ninp = \"qzyelonm\"\n\nchars = \"0123456789abcdef\"\n\ndef find_64(cycles):\n triples = [[] for i in range(16)]\n keys_at = []\n i = 0\n while True:\n h = md5((inp+str(i)).encode(\"utf-8\")).hexdigest()\n for k in range(cycles):\n h = md5(h.encode(\"utf-8\")).hexdigest()\n for j in range(16): # look for \"xxxxx\"\n if chars[j]*5 in h: \n while len(triples[j]) > 0: # if found, the triples[x] will be processed and then emptied!\n num = triples[j].pop()\n if i-num <= 1000:\n keys_at.append(num)\n for j in range(len(h)-2): # look for \"xxx\"\n if h[j] == h[j+1] == h[j+2]:\n triples[chars.index(h[j])].append(i)\n break\n i += 1\n if(len(keys_at)) >= 64:\n keys_at.sort()\n if i-keys_at[63] > 1000:\n print(keys_at[63])\n break\n\nfind_64(0)\nfind_64(2016)","repo_name":"Stannislav/Advent-of-Code","sub_path":"2016/d14 --- One-Time Pad/puzzle14.py","file_name":"puzzle14.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"42"} +{"seq_id":"71394164928","text":" \n#Printing the subsequnce whose sum is k\ndef newSeq(subSum, subTup, tup, k, arr, count):\n #print(f\"subSum = {subSum} subTup = {subTup} tup = {tup}, arr = {arr}\")\n if(len(tup) == 0):\n if(subSum == k):\n arr.append(subTup)\n count += 1\n return count\n ele = tup[0]\n newTup = tup[1:]\n del tup\n #print(f\"First{i}: subSum = {subSum} subTup = {subTup} tup = {tup}, arr = {arr}\")\n count = newSeq(subSum, subTup, newTup, k, arr, count)\n newSubTup = subTup + (ele, )\n del subTup\n #print(f\"Second{i}: subSum = {subSum} subTup = {subTup} tup = {tup}, arr = {arr}\")\n count = newSeq(subSum+ele, newSubTup, newTup, k, arr, count)\n return count\n\n#Works for single digit number\ndef subseq1(sumString, string, seq, arr, k):\n if(seq == \"\"):\n if(sumString == k):\n arr.append(string)\n return arr\n popChar = seq[-1]\n popNum = int(popChar)\n seq = seq[:-1]\n subseq1(sumString, string, seq, arr, k)\n subseq1(popNum + sumString, popChar + string, seq, arr, k)\n return arr\n\nprint (\"\\n\" * 100)\nseq = [int(i) for i in input(\"Enter the subsequence: \").split(\",\")]\nk = int(input(\"Enter the value of k: \"))\narr = []\nseq = tuple(seq)\nprint(f\"Subsequence of {seq} whose sum is equal to {k} is {newSeq(0, (), seq, k, arr, 0)}\")\n\n","repo_name":"ganavijayaram/DSALearning","sub_path":"Recursion/countSubSequenceWhoseSumIsK.py","file_name":"countSubSequenceWhoseSumIsK.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"1683989356","text":"from __future__ import print_function\nfrom urllib.error import HTTPError\nimport os, boto3, json, base64\nimport urllib.request, urllib.parse\nimport logging\n\n\n\n# pass ssm name and decrypt the ssm param name\ndef decrypt_ssm(param_name):\n region = os.environ['AWS_REGION']\n try:\n ssm = boto3.client('ssm', region_name=region)\n parameter = ssm.get_parameter(Name=param_name, WithDecryption=True)\n return parameter['Parameter']['Value']\n except Exception:\n logging.exception(\"Failed to decrypt URL with SSM\")\n\ndef cloudwatch_notification(message, region):\n states = {'OK': 'good', 'INSUFFICIENT_DATA': 'warning', 'ALARM': 'danger'}\n\n return {\n \"color\": states[message['NewStateValue']],\n \"fallback\": \"Alarm {} triggered\".format(message['AlarmName']),\n \"fields\": [\n { \"title\": \"Alarm Name\", \"value\": message['AlarmName'], \"short\": True },\n { \"title\": \"Alarm Description\", \"value\": message['AlarmDescription'], \"short\": False},\n { \"title\": \"Alarm reason\", \"value\": message['NewStateReason'], \"short\": False},\n { \"title\": \"Old State\", \"value\": message['OldStateValue'], \"short\": True },\n { \"title\": \"Current State\", \"value\": message['NewStateValue'], \"short\": True },\n {\n \"title\": \"Link to Alarm\",\n \"value\": \"https://console.aws.amazon.com/cloudwatch/home?region=\" + region + \"#alarm:alarmFilter=ANY;name=\" + urllib.parse.quote(message['AlarmName']),\n \"short\": False\n }\n ]\n }\n\n\ndef default_notification(subject, message):\n return {\n \"fallback\": \"A new message\",\n \"fields\": [{\"title\": subject if subject else \"Message\", \"value\": json.dumps(message) if type(message) is dict else message, \"short\": False}]\n }\n\n\n# Send a message to a slack channel\ndef notify_slack(subject, message, region):\n slack_url = decrypt_ssm(os.environ['SLACK_WEBHOOK_URL'])\n slack_channel = os.environ['SLACK_CHANNEL']\n slack_username = os.environ['SLACK_USERNAME']\n slack_emoji = os.environ['SLACK_EMOJI']\n\n payload = {\n \"channel\": slack_channel,\n \"username\": slack_username,\n \"icon_emoji\": slack_emoji,\n \"attachments\": []\n }\n\n if type(message) is str:\n try:\n message = json.loads(message)\n except json.JSONDecodeError as err:\n logging.exception(f'JSON decode error: {err}')\n\n if \"AlarmName\" in message:\n notification = cloudwatch_notification(message, region)\n payload['text'] = \"AWS CloudWatch notification - \" + message[\"AlarmName\"]\n payload['attachments'].append(notification)\n else:\n payload['text'] = \"AWS notification\"\n payload['attachments'].append(default_notification(subject, message))\n\n data = urllib.parse.urlencode({\"payload\": json.dumps(payload)}).encode(\"utf-8\")\n req = urllib.request.Request(slack_url)\n\n try:\n result = urllib.request.urlopen(req, data)\n return json.dumps({\"code\": result.getcode(), \"info\": result.info().as_string()})\n\n except HTTPError as e:\n logging.error(\"{}: result\".format(e))\n return json.dumps({\"code\": e.getcode(), \"info\": e.info().as_string()})\n\n\ndef lambda_handler(event, context):\n if 'LOG_EVENTS' in os.environ and os.environ['LOG_EVENTS'] == 'True':\n logging.warning('Event logging enabled: `{}`'.format(json.dumps(event)))\n\n subject = event['Records'][0]['Sns']['Subject']\n message = event['Records'][0]['Sns']['Message']\n region = event['Records'][0]['Sns']['TopicArn'].split(\":\")[3]\n response = notify_slack(subject, message, region)\n\n if json.loads(response)[\"code\"] != 200:\n logging.error(\"Error: received status `{}` using event `{}` and context `{}`\".format(json.loads(response)[\"info\"], event, context))\n\n return response\n","repo_name":"prasanna12510/student-restful-api","sub_path":"generic/notify_slack_function/notify_slack.py","file_name":"notify_slack.py","file_ext":"py","file_size_in_byte":3618,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"24712511763","text":"#!/usr/bin/env python -t\n# -*- mode: Python; py-indent-offset: 2; -*-\n\nfrom __future__ import print_function\n\n# https://enigmaticcode.wordpress.com/2015/09/24/running-the-first-program/\n# Program 1 - ada1.py\n\nfrom fractions import Fraction\n\n# my implementation of the algorithm\ndef bernoulli():\n\n # results\n Bs = list()\n\n # start at n=1\n n = 1\n # calculate the sequence\n while True:\n\n # result = A0\n r = -Fraction(2 * n - 1, 2 * n + 1) / 2\n\n # A1 = n\n A = n\n # for each B[k] already determined calculate the corresponding A[k]\n for (i, B) in enumerate(Bs):\n if i > 0:\n # multiply in the 2 additional terms\n j = 2 * i - 1\n A *= Fraction(2 * n - j, 2 + j)\n j += 1\n A *= Fraction(2 * n - j, 2 + j)\n # add A[k] * B[k] into the result\n r += A * B\n\n # the computed bernoulli number is -r\n B = -r\n # return the number\n yield B\n # add it to the result list\n Bs.append(B)\n # increase n\n n += 1\n\n\n# run N iterations of the algorithm\nfrom sys import argv\nN = (10 if len(argv) < 2 else int(argv[1]))\n\nk = 1 # ada's numbering (normal numbering is k + 1)\nK = 2 * N + 1 # max k\nfor r in bernoulli():\n print(\"B[{k}] = {r}\".format(k=k, r=r))\n k += 2\n if k == K: break\n","repo_name":"enigmatic-code/py-analytical_engine","sub_path":"ada1.py","file_name":"ada1.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"42"} +{"seq_id":"42882052205","text":"import nltk\r\nfrom nltk.classify.scikitlearn import SklearnClassifier\r\n#from sklearn.naive_bayes import MultinomialNB, BernoulliNB\r\nfrom nltk.tokenize import word_tokenize\r\nfrom nltk.corpus import stopwords\r\nimport string, random, os, pickle\r\nfrom MyClassifier import MyClass\r\nfrom os.path import exists\r\n\r\n'''adjectives are a better way of understanding sentiment review, so lets make a bag of adjectives\r\nj is adjec, r is adverb, v is verb'''\r\nallowed_word_types = [\"J\"]\r\nstop_words = list(set(stopwords.words('english')))\r\n\r\n'''\r\nretrains the classifier with the same NLP learning algorithm or a new algorithm\r\nparam sk an object of a NLP learning algorithm to use. Uses a naive Bayes classifier by default\r\nparam force forces the classifier to utilize the latest training, regardless if the accuracy on\r\nthe testing set is better or worse than before.\r\n'''\r\ndef retrain_clsfyr(sk = None, force = False):\r\n if exists(\"ReviewClassifier.pickle.bak\"):\r\n os.remove(\"ReviewClassifier.pickle.bak\")\r\n os.rename(\"ReviewClassifier.pickle\", \"ReviewClassifier.pickle.bak\")\r\n clsfyr.retrain()\r\n with open(\"ReviewClassifier.pickle\", \"wb\") as f:\r\n pickle.dump(clsfyr, f)\r\n\r\ndef build_classifier(posFile, negFile, clas = None):\r\n files_pos = os.listdir(posFile)\r\n files_pos = [open(posFile+f, 'r',encoding='utf8').read() for f in files_pos]\r\n files_neg = os.listdir(negFile)\r\n files_neg = [open(negFile+f, 'r',encoding='utf8').read() for f in files_neg]\r\n \r\n '''uncomment the following two lines for better performance if you wish to change this script'''\r\n #files_pos = files_pos[0:250]\r\n #files_neg = files_neg[0:250]\r\n\r\n all_words = []\r\n documents = [] \r\n\r\n index = 1\r\n for p in files_pos:\r\n #create list of tuples where the first element of each tuple is a review and second is the label\r\n documents.append( (p, \"pos\"))\r\n \r\n #filter out punctuations\r\n filtered = p.translate(str.maketrans('', '', string.punctuation))\r\n \r\n #tokenize\r\n tokenized = word_tokenize(filtered)\r\n \r\n #filter out stopwords\r\n stopped_tokenized = [w for w in tokenized if not w in stop_words]\r\n \r\n #parts of speech tagging\r\n pos = nltk.pos_tag(stopped_tokenized)\r\n \r\n #out list of all adjectives identified by the allowed word types declared in preprocessing\r\n for w in pos:\r\n if w[1][0] in allowed_word_types:\r\n all_words.append(w[0].lower())\r\n \r\n print(str(index), \"done\")\r\n index+=1\r\n\r\n for p in files_neg:\r\n #create list of tuples where the first element of each tuple is a review and second is the label\r\n documents.append( (p, \"neg\"))\r\n \r\n #filter out punctuations\r\n filtered = p.translate(str.maketrans('', '', string.punctuation))\r\n \r\n #tokenize\r\n tokenized = word_tokenize(filtered)\r\n \r\n #filter out stopwords\r\n stopped_tokenized = [w for w in tokenized if not w in stop_words]\r\n \r\n #parts of speech tagging\r\n neg = nltk.pos_tag(stopped_tokenized)\r\n \r\n #out list of all adjectives identified by the allowed word types declared in preprocessing\r\n for w in neg:\r\n if w[1][0] in allowed_word_types:\r\n all_words.append(w[0].lower())\r\n \r\n print(str(index), \"done\")\r\n index+=1\r\n \r\n '''perform a map reduce for frequency distribution'''\r\n all_words = nltk.FreqDist(all_words)\r\n\r\n #list X most frequent words\r\n word_features = list(all_words.keys())[:500]\r\n\r\n '''\r\n function to create a dictionary of features for each review in the list document\r\n let the keys be the words in word_features\r\n let the value of each word be true of false to represent pos or neg\r\n this is vectorizing each review for the machine\r\n '''\r\n def vectorize_features(document):\r\n words = word_tokenize(document)\r\n features = {}\r\n for w in word_features:\r\n features[w] = (w in words)\r\n return features\r\n\r\n#create features for each review. each set format is tuple (vectorized list, pos/neg)\r\n feature_sets = [(vectorize_features(review), categ) for (review, categ) in documents]\r\n\r\n random.shuffle(feature_sets)\r\n\r\n training_set = feature_sets[:len(feature_sets)-100]\r\n testing_set = feature_sets[len(feature_sets)-100:]\r\n \r\n if clas:\r\n obj = SklearnClassifier(clas)\r\n classifier = obj.train(training_set)\r\n return MyClass(classifier, training_set, testing_set, word_features)\r\n else:\r\n classifier = nltk.NaiveBayesClassifier.train(training_set)\r\n return MyClass(classifier, training_set, testing_set, word_features)\r\n\r\nclsfyr = None\r\ntry:\r\n clsfyr = pickle.load(open(\"ReviewClassifier.pickle\", \"rb\"))\r\nexcept (OSError, IOError) as e:\r\n clsfyr = build_classifier('C:\\\\Users\\\\drose.CORP\\\\eclipse-workspace\\\\NLP Project\\\\train\\\\pos\\\\',\r\n 'C:\\\\Users\\\\drose.CORP\\\\eclipse-workspace\\\\NLP Project\\\\train\\\\neg\\\\')\r\n pickle_out = open(\"ReviewClassifier.pickle\", \"wb\")\r\n pickle.dump(clsfyr, pickle_out)\r\n\r\n\r\n'''now lets try to predict if a review is positive or negative'''\r\n'''uncomment the following line to retrain the classifier'''\r\n#retrain_clsfyr()\r\n\r\nprint(\"Classifier accuracy percent:\", clsfyr.getAccuracy()*100)\r\n#clsfyr.getClassifier().show_most_informative_features(15)\r\n\r\nreview = input(\"Type the review that you would like judged.\\n\")\r\nfs = [(clsfyr.vectorize(review), \"pos\")]\r\naccur = nltk.classify.accuracy(clsfyr.getClassifier(), fs)\r\nprint(\"Good review\" if accur==1.0 else \"Bad Review\")\r\n\r\n'''there are several classifier classes, but the most accurate is MultinomialNB\r\n\r\nsummarily, the MultinomialNB class is the best class to use when performing sentimental analysis on reviews.'''\r\n","repo_name":"davidstevenrose/Sentiment-Analysis","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"42530977698","text":"'''\n\n[제약사항]\n3 <= N <= 30\n2 <= M <= 40\n정답 및 학생의 답안지로 입력되는 값은 1~5 사이의 정수이다.\n\n입력\n첫번째 줄에는 테스트 케이스의 개수 T가 주어진다.\n두번째 줄부터 각 테스트 케이스가 주어진다.\n각 테스트 케이스의 첫번째 줄에는 학생의 수 N, 문제의 수 M이 공백으로 구분되어 주어진다.\n각 테스트 케이스의 두번째 줄에는 M개의 문제에 대한 정답이 공백으로 구분되어 주어진다.\n다음 N줄에 걸쳐, N명의 학생이 제출한 M개의 문제에 대한 답안지의 정보가 각 줄에 공백으로 구분되어 주어진다.\n\n출력\n각 테스트 케이 t에 대한 결과를 각 줄에 \"#t\" (테스트 케이스는 1번부터 시작)을 출력하고, 한 칸을 띄운 다음 정답을 출력한다.\n'''\ndef solution(answer, submission):\n score = 0\n bonus = 0\n M = len(answer)\n for i in range(M):\n if answer[i] == submission[i]:\n score += 1 + bonus\n bonus += 1\n else:\n bonus = 0\n\n return score\n\nT = int(input())\nfor tc in range(1, T+1):\n hs = 0\n ls = 56\n N, M = map(int, input().split())\n answer = list(map(int, input().split()))\n for _ in range(N):\n submission = list(map(int, input().split()))\n score = solution(answer, submission)\n if hs < score:\n hs = score\n if ls > score:\n ls = score\n result = hs - ls\n print(f'#{tc} {result}')","repo_name":"DKIMDK/SSAFY","sub_path":"algorithm/Aug/0821/18532_scoring.py","file_name":"18532_scoring.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"13659473925","text":"import os\nimport datetime\nimport wx\nfrom wx.lib.floatcanvas import NavCanvas\nfrom pubsub import pub\n\n\n# colors = [\"AQUAMARINE\", \"BLACK\", \"BLUE\", \"BLUE VIOLET\", \"BROWN\",\n# \"CADET BLUE\", \"CORAL\", \"CORNFLOWER BLUE\", \"CYAN\", \"DARK GREY\",\n# \"DARK GREEN\", \"DARK OLIVE GREEN\", \"DARK ORCHID\", \"DARK SLATE BLUE\",\n# \"DARK SLATE GREY\", \"DARK TURQUOISE\", \"DIM GREY\",\n# \"FIREBRICK\", \"FOREST GREEN\", \"GOLD\", \"GOLDENROD\", \"GREY\",\n# \"GREEN\", \"GREEN YELLOW\", \"INDIAN RED\", \"KHAKI\", \"LIGHT BLUE\",\n# \"LIGHT GREY\", \"LIGHT STEEL BLUE\", \"LIME GREEN\", \"MAGENTA\",\n# \"MAROON\", \"MEDIUM AQUAMARINE\", \"MEDIUM BLUE\", \"MEDIUM FOREST GREEN\",\n# \"MEDIUM GOLDENROD\", \"MEDIUM ORCHID\", \"MEDIUM SEA GREEN\",\n# \"MEDIUM SLATE BLUE\", \"MEDIUM SPRING GREEN\", \"MEDIUM TURQUOISE\",\n# \"MEDIUM VIOLET RED\", \"MIDNIGHT BLUE\", \"NAVY\", \"ORANGE\", \"ORANGE RED\",\n# \"ORCHID\", \"PALE GREEN\", \"PINK\", \"PLUM\", \"PURPLE\", \"RED\",\n# \"SALMON\", \"SEA GREEN\", \"SIENNA\", \"SKY BLUE\", \"SLATE BLUE\",\n# \"SPRING GREEN\", \"STEEL BLUE\", \"TAN\", \"THISTLE\", \"TURQUOISE\",\n# \"VIOLET\", \"VIOLET RED\", \"WHEAT\", \"WHITE\", \"YELLOW\", \"YELLOW GREEN\"]\n\n\nwildcard = \"JPG/JPEG (*.jpg)|*.jpg|\" \\\n \"PNG (*.png)|*.png|\" \\\n \"GIF (*.gif)|*.gif|\" \\\n \"ICO (*.ico)|*.ico|\" \\\n \"SVG (*.svg)|*.svg|\" \\\n \"BMP (*.bmp)|*.bmp|\" \\\n \"All files (*.*)|*.*\"\n\n\nclass DrawFrame(wx.Frame):\n def __init__(self, parent, id, title, position, size):\n wx.Frame.__init__(self, parent, id, title, position, size)\n font_medium = wx.Font(16, wx.ROMAN, wx.NORMAL, wx.NORMAL, False, '')\n\n super().SetFont(font_medium)\n\n self.Canvas = NavCanvas.NavCanvas(self, -1, (500, 500), Debug=False, BackgroundColor=\"White\").Canvas\n self.Canvas.NumBetweenBlits = 1000\n\n self.makemenuBar()\n self.CreateStatusBar()\n now = datetime.datetime.now()\n self.SetStatusText(f\"Program started at {datetime.datetime.strftime(now, '%Y, %m %d %T')} (static)\")\n\n # event handlers:\n self.Bind(wx.EVT_CLOSE, self.OnExit)\n pub.subscribe(self.DrawFromProduct, \"Go_get_it\")\n\n # *args\n self.image = None\n self.opentype = 0\n self.savetype = 0\n\n\n def makemenuBar(self):\n menuBar = wx.MenuBar()\n \n file_menu = wx.Menu()\n openItem = file_menu.Append(-1, \"&Open\\tCtrl-O\", \"Open the image file\")\n save_asItem = file_menu.Append(-1, \"&Save As\\tCtrl-Shift-S\", \"Save as a self-named file\")\n exitItem = file_menu.Append(-1, \"Exit\\tESC\", \"Terminate the program\")\n\n view_menu = wx.Menu()\n zoomItem = view_menu.Append(-1, \"Zoom in &Fit\\tCtrl-F\", \"Zoom to fit the Window\")\n clearItem = view_menu.Append(-1, \"&Clear\\tCtrl-C\", \"Clear the Canvas\")\n\n help_menu = wx.Menu()\n aboutItem = help_menu.Append(wx.ID_ABOUT, \"\", \"More information about the program\")\n \n menuBar.Append(file_menu, \"&File\")\n menuBar.Append(view_menu, \"&View\")\n menuBar.Append(help_menu, \"&Help\")\n\n self.SetMenuBar(menuBar)\n \n self.Bind(wx.EVT_MENU, self.OnOpen, openItem)\n self.Bind(wx.EVT_MENU, self.OnSave_As, save_asItem)\n self.Bind(wx.EVT_MENU, self.OnExit, exitItem)\n self.Bind(wx.EVT_MENU, self.ZoomToFit, zoomItem)\n self.Bind(wx.EVT_MENU, self.Clear, clearItem)\n self.Bind(wx.EVT_MENU, self.OnAbout, aboutItem)\n\n def DrawFromProduct(self, message):\n self.Canvas.ClearAll()\n image = wx.Image(message, wx.BITMAP_TYPE_JPEG)\n self.Canvas.AddScaledBitmap(image, (0, 0), Height=image.GetHeight(), Position=\"cc\")\n self.Canvas.Draw()\n self.Canvas.ZoomToBB()\n\n def OnOpen(self, event):\n dlg = wx.FileDialog(\n self, message=\"Choose a file\",\n defaultDir=os.getcwd(),\n defaultFile=\"\",\n wildcard=wildcard,\n style=wx.FD_OPEN |\n wx.FD_CHANGE_DIR | wx.FD_FILE_MUST_EXIST |\n wx.FD_PREVIEW\n )\n dlg.SetFilterIndex(self.opentype)\n if dlg.ShowModal() == wx.ID_OK:\n paths = dlg.GetPaths()\n self.origin_path = paths[0]\n self.opentype = dlg.GetFilterIndex()\n\n file_type = dlg.GetFilename().split(\".\")[1]\n if file_type == \"jpg\":\n self.image = wx.Image(dlg.GetFilename(), wx.BITMAP_TYPE_JPEG)\n elif file_type == \"png\":\n self.image = wx.Image(dlg.GetFilename(), wx.BITMAP_TYPE_PNG)\n elif file_type == \"gif\":\n self.image = wx.Image(dlg.GetFilename(), wx.BITMAP_TYPE_GIF)\n elif file_type == \"ico\":\n self.image = wx.Image(dlg.GetFilename(), wx.BITMAP_TYPE_ICO)\n elif file_type == \"bmp\":\n self.image = wx.Image(dlg.GetFilename(), wx.BITMAP_TYPE_BMP)\n else:\n wx.MessageBox(\"Unreadable!\", \"Error occurred\", wx.ICON_ERROR)\n\n if self.image:\n self.Canvas.ClearAll()\n self.Canvas.AddScaledBitmap(self.image, (0, 0), Height=self.image.GetSize()[1], Position=\"cc\")\n self.Canvas.Draw()\n self.Canvas.ZoomToBB()\n\n def OnSave_As(self, event):\n dlg = wx.FileDialog(\n self, message=\"Save file as ...\", defaultDir=os.getcwd(),\n defaultFile=\"\", wildcard=wildcard, style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT\n )\n dlg.SetFilterIndex(self.savetype)\n if dlg.ShowModal() == wx.ID_OK:\n self.output_path = dlg.GetPath()\n self.savetype = dlg.GetFilterIndex()\n self.Canvas.SaveAsImage(self.output_path)\n\n def Clear(self, event):\n self.Canvas.ClearAll()\n self.Canvas.Draw()\n\n def ZoomToFit(self, event):\n self.Canvas.ZoomToBB()\n\n def OnAbout(self, event):\n dlg = wx.MessageDialog(self, \"This is another frame with other program that\\n\"\n \"used wx.NavCanvas\\n\",\n \"About Me\", wx.OK | wx.ICON_INFORMATION)\n dlg.ShowModal()\n dlg.Destroy()\n\n def OnExit(self, event):\n dlg = wx.MessageDialog(None, \"Do you really want to exit?\", 'ExitDialog',\n wx.YES_NO | wx.ICON_NONE)\n result = dlg.ShowModal()\n if result == wx.ID_YES:\n self.Destroy()\n","repo_name":"as-wanger/molecular_analyzer","sub_path":"image_viewer.py","file_name":"image_viewer.py","file_ext":"py","file_size_in_byte":6481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"42007008737","text":"import torch\nimport torch.nn.functional as F\nfrom torch import nn\nfrom models.partial_conv2d import PartialConv2d\n\nclass PConvEncoder(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size, bn=True):\n super(PConvEncoder, self).__init__()\n self.pconv = PartialConv2d(in_channels, out_channels, kernel_size=kernel_size, stride=2, padding=(kernel_size-1)//2,multi_channel=True, return_mask=True)\n self.bn = bn\n self.batchnorm = nn.BatchNorm2d(out_channels)\n self.activation = nn.ReLU()\n \n def forward(self, img, mask_in):\n conv, mask = self.pconv(img, mask_in)\n if self.bn:\n conv = self.batchnorm(conv)\n conv = self.activation(conv)\n \n return conv, mask","repo_name":"ryanwongsa/Image-Inpainting","sub_path":"src/models/pconv_encoder.py","file_name":"pconv_encoder.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"42"} +{"seq_id":"74770024767","text":"\"\"\"\nCommand line interface, that communicates between user and services.\n\"\"\"\n\nimport click\nimport service\nfrom exception import ItemNotFound\n\n\n@click.group()\ndef cli():\n pass\n\n\n@click.command(\"create\")\n@click.option(\"-t\", \"--title\", type=str, required=True, help=\"Title of the note.\")\n@click.option(\n \"-m\", \"--message\", type=str, required=True, help=\"Description of the note.\"\n)\ndef create(title: str, message: str):\n \"\"\"Create note.\"\"\"\n service.create(title, message)\n\n\n@click.command(\"read\")\ndef read():\n \"\"\"Read notes.\"\"\"\n data = service.read()\n for val in data:\n print(\n f\"\"\"id: {val['id']}\ntitle: {val['title']}\nmessage {val['message']}\ncreated at: {val['created_at']}\n--------------------\"\"\"\n )\n\n\n@click.command(\"get\")\n@click.option(\"--id\", type=str, required=True, help=\"ID of the note.\")\ndef get(id):\n \"\"\"Get note.\"\"\"\n data = service.get(id)\n\n if data is None:\n print(\"element with specified id not found\")\n else:\n print(\n f\"\"\"id: {data['id']}\ntitle: {data['title']}\nmessage {data['message']}\ncreated at: {data['created_at']}\"\"\"\n )\n\n\n@click.command(\"update\")\n@click.option(\"--id\", type=str, required=True, help=\"ID of the note.\")\n@click.option(\"-t\", \"--title\", type=str, required=True, help=\"Title of the note.\")\n@click.option(\n \"-m\", \"--message\", type=str, required=True, help=\"Description of the note.\"\n)\ndef update(id: str, title: str, message: str):\n \"\"\"Update note.\"\"\"\n try:\n service.update(id, title, message)\n except ItemNotFound:\n print(\"element with specified id not found\")\n\n\n@click.command(\"delete\")\n@click.option(\"--id\", type=str, required=True, help=\"ID of the note.\")\ndef delete(id):\n \"\"\"Delete note.\"\"\"\n try:\n service.delete(id)\n except ItemNotFound:\n print(\"element with specified id not found\")\n\n\ncli.add_command(create)\ncli.add_command(read)\ncli.add_command(get)\ncli.add_command(update)\ncli.add_command(delete)\n\nif __name__ == \"__main__\":\n cli()\n","repo_name":"IvanProg00/geekbrains-app-notes","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"21431333274","text":"import requests\r\n\r\nfrom utils import cfgParse\r\nfrom tenCentApi import RecordModify, DomainListApi, RecordListApi\r\n\r\n\r\ndef get_cur_ip(url):\r\n return requests.get(url=url, timeout=5).json().get(\"ip\")\r\n\r\n\r\ndef main():\r\n ipUrl = cfgParse.get(\"route\", \"ip_url\")\r\n oldIp = cfgParse.get(\"route\", \"ip\")\r\n curIp = get_cur_ip(ipUrl)\r\n if curIp == oldIp:\r\n return\r\n data = DomainListApi().run()\r\n domains = data.get(\"domains\")\r\n for item in domains:\r\n recordLis = RecordListApi(domain=item[\"name\"]).run()\r\n domain = recordLis.get(\"domain\")\r\n records = recordLis.get(\"records\")\r\n\r\n\r\n for record in records:\r\n sub_domain = record.get(\"name\")\r\n if sub_domain == \"@\":\r\n continue\r\n\r\n RecordModify(\r\n recordId=str(record.get(\"id\")),\r\n domain=domain.get(\"name\"),\r\n subDomain=record.get(\"name\"),\r\n recordLine=record.get(\"line\"),\r\n recordType=record.get(\"type\"),\r\n value=curIp\r\n ).run()\r\n\r\n else:\r\n cfgParse.set(\"route\", \"ip\", curIp)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"NicolasCricle/DDNSTencent","sub_path":"ddnsScript.py","file_name":"ddnsScript.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"36838819371","text":"import requests, bs4, os\n\nurl = 'https://xkcd.com'\nos.makedirs('xkcd', exist_ok=True)\nwhile not url.endswith('#'):\n try:\n res = requests.get(url)\n res.raise_for_status()\n soup = bs4.BeautifulSoup(res.text, 'lxml')\n imgSrc = soup.find('div', attrs={'id': 'comic'}).img.get('src')\n imgUrl = 'http:' + imgSrc\n imgTitle = soup.find('div', attrs={'id': 'ctitle'}).text\n print('Going to url: %s (%s)' % (imgTitle, prevUrl.replace('/', '')))\n res = requests.get(imgUrl)\n imgFile = open(os.path.join(os.getcwd(), 'xkcd', os.path.basename(imgUrl)), 'wb')\n for chuck in res.iter_content(1000000):\n imgFile.write(chuck)\n imgFile.close()\n print('Downloading image: %s...' % imgUrl)\n except Exception as err:\n print('Oops, there\\'s an error: %s' % err)\n\n prevUrl = soup.find('a', attrs={'rel': 'prev'}).get('href')\n url = 'https://xkcd.com' + prevUrl\nprint('done!')\n","repo_name":"sevendollar/python","sub_path":"download-images-from-xkcd.py","file_name":"download-images-from-xkcd.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"33952196514","text":"import sys\nfrom heapq import *\n\nfrom tools import runtime\n\n# Simplified Dijkstra without weights\ndef dijkstra(edges, start, end):\n q = [(0, start)]\n visited = set()\n through = {}\n while q:\n dist, current = heappop(q)\n if current == end:\n break\n if current in visited:\n continue\n for neighbor in edges[current]:\n if neighbor not in visited:\n heappush(q, (dist + 1, neighbor))\n through[neighbor] = current\n visited.add(current)\n path = []\n current = end\n if current not in through:\n return []\n while current != start:\n path.append(current)\n current = through[current]\n path.append(start)\n path.reverse()\n return path\n\n\n@runtime\ndef main(argv=None):\n if argv is None:\n argv = sys.argv[1:]\n\n field = []\n for line in open(\"input\"):\n field.append(list(line.rstrip(\"\\n\")))\n possible_starts = []\n for i, line in enumerate(field):\n if \"S\" in line:\n start = (i, line.index(\"S\"))\n line[start[1]] = \"a\"\n if \"E\" in line:\n end = (i, line.index(\"E\"))\n line[end[1]] = \"z\"\n for j, char in enumerate(line):\n if char == \"a\":\n possible_starts.append((i, j))\n\n def get_neighbors(pos):\n x, y = pos\n neighbors = []\n if x > 0:\n if ord(field[x - 1][y]) - ord(field[x][y]) <= 1:\n neighbors.append((x - 1, y))\n if x < len(field) - 1:\n if ord(field[x + 1][y]) - ord(field[x][y]) <= 1:\n neighbors.append((x + 1, y))\n if y > 0:\n if ord(field[x][y - 1]) - ord(field[x][y]) <= 1:\n neighbors.append((x, y - 1))\n if y < len(field[0]) - 1:\n if ord(field[x][y + 1]) - ord(field[x][y]) <= 1:\n neighbors.append((x, y + 1))\n return neighbors\n\n neighbours = {}\n for i, line in enumerate(field):\n for j, _ in enumerate(line):\n neighbours[(i, j)] = get_neighbors((i, j))\n\n print(start, end)\n path = dijkstra(neighbours, start, end)\n print(\"Part 1:\", len(path) - 1)\n\n min_len = 9999\n for start in possible_starts:\n path = dijkstra(neighbours, start, end)\n if path:\n min_len = min(min_len, len(path) - 1)\n\n print(\"Part 2:\", min_len)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"robquant/adventofcode2022","sub_path":"12/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"31911210124","text":"from math import trunc\n\ncasa = float(input('Qual valor da casa? '))\nsalario = float(input('Qual seu salário? '))\nanos = float(input('Em quantos anos queres financiar? '))\n\ncalc = (anos - trunc(anos)) * 10\nmeses = trunc(anos) * 12 + calc\nmeses = trunc(meses)\n\nprestacao = casa / meses\nrenda = (30 / 100 * salario)\n\nif renda >= prestacao:\n print('Seu financiamento foi aprovado com sucesso!')\n print('O valor de sua prestação será R$: {:.2f}'.format(prestacao))\nelse:\n print('Seu financiamento não foi aprovado. A prestação supera 30% de sua renda que é de no resta R$: {}'.format(renda))\n print('Valor resta da parcela para aprovação é de R$: {:.2f}'.format(restação))","repo_name":"Marcelo-Carlos/Python","sub_path":"IF-ELSE/Aprovação-Emprestimo.py","file_name":"Aprovação-Emprestimo.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"9216992806","text":"import os\nimport pathlib\nimport sys\n\n_HERE_DIR = pathlib.Path(os.path.dirname(__file__)).resolve()\n_SRC_DIR = _HERE_DIR.parents[3]\n\nsys.path.append(str(_SRC_DIR / 'third_party' / 'node'))\nimport node\nimport node_modules\n\n\ndef main():\n try:\n node.RunNode([\n node_modules.PathToTypescript(), '--project',\n str(_HERE_DIR / 'jsconfig.json')\n ])\n except RuntimeError as e:\n # Skip first line, which is just error text added by node.RunNode().\n lines = str(e).splitlines()[1:]\n for line in lines:\n print(line)\n sys.exit(1)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"chromium/chromium","sub_path":"tools/binary_size/libsupersize/viewer/check_js.py","file_name":"check_js.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":16362,"dataset":"github-code","pt":"42"} +{"seq_id":"26508552250","text":"import sys\nsys.stdin = open('input.txt')\n\ndef find(x):\n if groups[x] == x:\n return x\n return find(groups[x])\n\ndef union(x,y):\n x = find(x)\n y = find(y)\n if x>y:\n x, y = y, x\n groups[y] = x\n\nfor test_case in range(1, int(input())+1):\n N, M = map(int, input().split())\n numbers = list(map(int, input().split()))\n groups = list(range(N+1))\n\n for i in range(0, 2*M, 2):\n union(numbers[i], numbers[i+1])\n\n result = set()\n for i in range(1, N+1):\n result.add(find(i))\n \n print(f'#{test_case} {len(result)}')\n ","repo_name":"rosieyeon/algorithmic-coding-private","sub_path":"SWEA/L5248.py","file_name":"L5248.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"24902856165","text":"from prescribing_management.models import Prescription, PrescriptionDetail\r\nfrom django.forms import ModelForm\r\n\r\n\r\nclass PrescriptionForm(ModelForm):\r\n class Meta:\r\n model = Prescription\r\n exclude = ('created_at', 'medicines', 'deleted_at', 'created_by')\r\n\r\n def __init__(self, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n for field in self.fields.values():\r\n field.widget.attrs['class'] = 'form-control'\r\n\r\n\r\nclass PrescriptionDetailForm(ModelForm):\r\n class Meta:\r\n model = PrescriptionDetail\r\n exclude = ()\r\n\r\n def __init__(self, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n for field in self.fields.values():\r\n field.widget.attrs['class'] = 'form-control'\r\n","repo_name":"mchi11/medic","sub_path":"prescribing_management/forms/prescription_forms.py","file_name":"prescription_forms.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"42"} +{"seq_id":"40337793798","text":"from django.db import migrations\n\nfrom ecommerce.utils import (\n create_update_rule,\n create_delete_rule,\n rollback_update_rule,\n rollback_delete_rule,\n)\n\n\ndef protection_rules(table_name):\n \"\"\"\n Helper function to create protection rules for a table,\n to prevent updates and deletes (but creates are still allowed)\n \"\"\"\n return [\n migrations.RunSQL(\n sql=create_delete_rule(table_name),\n reverse_sql=rollback_delete_rule(table_name),\n ),\n migrations.RunSQL(\n sql=create_update_rule(table_name),\n reverse_sql=rollback_update_rule(table_name),\n ),\n ]\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [(\"ecommerce\", \"0014_productversion_text_id\")]\n\n operations = [\n *protection_rules(\"productversion\"),\n *protection_rules(\"couponversion\"),\n *protection_rules(\"couponpaymentversion\"),\n ]\n","repo_name":"mitodl/mitxpro","sub_path":"ecommerce/migrations/0015_db_protect.py","file_name":"0015_db_protect.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"42"} +{"seq_id":"32715119314","text":"import sys\n\n\nsys.setrecursionlimit(10**9)\n\n\ndef main():\n N = int(input())\n\n for i in range(2, 4):\n while N % i == 0:\n N //= i\n\n if N == 1:\n break\n\n if N == 1:\n print(\"Yes\")\n else:\n print(\"No\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"iwbc-mzk/atcoder","sub_path":"abc/abc324/b/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"26515212697","text":"import Temp_YAML\r\n\r\nclass Account:\r\n\r\n def __init__(self, Ac_name=''):\r\n self.name = Ac_name\r\n \r\n def Account_details(self):\r\n return self.name\r\n\r\nNew_obj = Account(\"tapas\")\r\nprint(New_obj.Account_details())\r\n\r\n # Import function file Temp_YAML.py\r\nData = Temp_YAML.yml_data()\r\nprint(Data[\"VesselTypes\"][0][\"Draughts\"][0][\"Mass\"])\r\n # Example 2\r\nprint(Data[\"Vessels\"][0][\"Name\"])\r\n # Example 3\r\nprint(Data[\"Vessels\"][1][\"Name\"])","repo_name":"tapastest/Python_practice","sub_path":"My-code_backup-21-4-18/__init__ Method-Function.py","file_name":"__init__ Method-Function.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"70245760766","text":"import cv2, time, os, tensorflow as tf\nimport numpy as np\nimport time\nimport keyboard\nimport xml.etree.cElementTree as ET\nfrom collections import defaultdict\nimport shutil\nfrom tensorflow.python.keras.utils.data_utils import get_file\nfrom tensorflow.train import Example, Features, Feature, BytesList, FloatList, Int64List\nfrom tensorflow.io import serialize_tensor, TFRecordWriter\n\n# this controls the color scheme \nnp.random.seed(123)\n\n\nclass Detector:\n\n def __init__(self, modelURL, classFile):\n self.downloadModel(modelURL)\n self.loadModel()\n self.readClasses(classFile)\n self.bboxes = []\n\n\n def predictVideo(self, videoPath, threshold=0.5):\n cap = cv2.VideoCapture(videoPath)\n\n if(cap.isOpened() == False):\n print(\"Error opening Video File....\")\n return\n\n (success, image) = cap.read()\n height, width, _ = image.shape\n\n # Set the output directory for TFRecords\n output_annotations_dir = \"/mnt/data/tfrecords\"\n os.makedirs(output_annotations_dir, exist_ok=True)\n\n frame_count = 0\n\n while success:\n print(f\"Processing frame {frame_count}\")\n original_frame = image.copy() # Save a copy of the original frame\n bboxImage = self.createBoundingBox(image, threshold)\n\n # Convert the annotations to tf.train.Example format\n # Save the frame as a temporary file\n \n temp_frame_file = \"temp_frame_{}.jpg\".format(frame_count)\n cv2.imwrite(temp_frame_file, original_frame)\n\n # Pass the temporary file path to the create_tf_example function\n annotated_frame = self.create_tf_example(temp_frame_file, self.bboxes, height, width)\n\n # Remove the temporary file\n os.remove(temp_frame_file)\n\n # Write the example to a separate TFRecord file\n video_name = os.path.splitext(os.path.basename(videoPath))[0]\n annotation_file = os.path.join(output_annotations_dir, f\"{video_name}_frame_{frame_count:04d}.tfrecord\")\n with tf.io.TFRecordWriter(annotation_file) as tfrecord_writer:\n tfrecord_writer.write(annotated_frame.SerializeToString())\n print(f\"Finished writing TFRecord for frame {frame_count}\")\n\n print(f\"Number of detections: {len(self.bboxes)}\")\n\n self.bboxes = []\n (success, image) = cap.read()\n\n cv2.imshow(\"Result\", bboxImage) # Display the frame with bounding boxes\n key = cv2.waitKey(1) & 0xFF # Wait for a key press and mask the result\n\n if key == ord('q'): # Check if the pressed key is 'q'\n print('Stopping video processing manually...')\n break\n\n frame_count += 1\n\n # Organize the TFRecords after they are created\n organize_tfrecords(output_annotations_dir)\n\n # Move the processed video to another folder\n processed_video_dir = \"/mnt/data/videosParsed\"\n os.makedirs(processed_video_dir, exist_ok=True)\n video_name = os.path.basename(videoPath)\n shutil.move(videoPath, os.path.join(processed_video_dir, video_name))\n\n cap.release()\n cv2.destroyAllWindows()\n\n\n def create_tf_example(self, image_path, bboxes, image_height, image_width):\n \"\"\"\n Convert the bounding boxes to tf.train.Example format\n \"\"\"\n encoded_bboxes = []\n encoded_labels = []\n encoded_scores = []\n\n for box in bboxes:\n encoded_labels.append(box[0])\n encoded_scores.append(box[1])\n encoded_bboxes.extend([box[2], box[3], box[4], box[5]])\n\n # Read the image file\n with open(image_path, \"rb\") as image_file:\n encoded_image_data = image_file.read()\n\n # Create the Example record and include the encoded image data\n feature = Features(feature={\n 'image/encoded': Feature(bytes_list=BytesList(value=[encoded_image_data])),\n 'image/height': Feature(int64_list=Int64List(value=[image_height])),\n 'image/width': Feature(int64_list=Int64List(value=[image_width])),\n 'image/object/bbox/xmin': Feature(float_list=FloatList(value=encoded_bboxes[0::4])),\n 'image/object/bbox/ymin': Feature(float_list=FloatList(value=encoded_bboxes[1::4])),\n 'image/object/bbox/xmax': Feature(float_list=FloatList(value=encoded_bboxes[2::4])),\n 'image/object/bbox/ymax': Feature(float_list=FloatList(value=encoded_bboxes[3::4])),\n 'image/object/class/text': Feature(bytes_list=BytesList(value=[label.encode('utf-8') for label in encoded_labels])),\n 'image/object/class/confidence': Feature(float_list=FloatList(value=encoded_scores)),\n })\n\n return Example(features=feature)\n \n def createBoundingBox(self, image, threshold=0.5):\n self.bboxes = [] # Clear the list before adding new bounding boxes\n\n inputTensor = cv2.cvtColor(image.copy(), cv2.COLOR_BGR2RGB)\n inputTensor = tf.convert_to_tensor(inputTensor, dtype=tf.uint8)\n inputTensor = inputTensor[tf.newaxis, ...]\n\n detections = self.model(inputTensor)\n\n bboxs = detections['detection_boxes'][0].numpy()\n classIndexes = detections['detection_classes'][0].numpy().astype(np.int32)\n classScores = detections['detection_scores'][0].numpy()\n\n imH, imW, imC = image.shape\n\n bboxIdx = tf.image.non_max_suppression(bboxs, classScores, max_output_size=70,\n iou_threshold=threshold, score_threshold=threshold)\n\n print(bboxIdx)\n\n if len(bboxIdx) != 0:\n for i in bboxIdx:\n bbox = tuple(bboxs[i].tolist())\n classConfidence = round(100 * classScores[i])\n classIndex = classIndexes[i]\n\n classLabelText = self.classesList[classIndex].upper()\n classColor = self.colorList[classIndex]\n\n displayText = '{}: {}%'.format(classLabelText, classConfidence)\n\n ymin, xmin, ymax, xmax = bbox\n\n xmin, xmax, ymin, ymax = (xmin * imW, xmax * imW, ymin * imH, ymax * imH)\n xmin, xmax, ymin, ymax = int(xmin), int(xmax), int(ymin), int(ymax)\n\n cv2.rectangle(image, (xmin, ymin), (xmax, ymax), color=classColor, thickness=1)\n cv2.putText(image, displayText, (xmin, ymin - 10), cv2.FONT_HERSHEY_PLAIN, 1, color=classColor, thickness=1)\n\n\n self.bboxes.append([classLabelText, classConfidence, xmin, ymin, xmax, ymax])\n\n return image\n\n def readClasses(self, classesFilePath):\n with open(classesFilePath, 'r') as f:\n self.classesList = f.read().splitlines()\n\n #colors list\n self.colorList =np.random.uniform(low=0, high=255, size=(len(self.classesList), 3))\n\n print(len(self.classesList), len(self.colorList))\n\n def downloadModel(self, modelURL):\n\n fileName = os.path.basename(modelURL)\n self.modelName = fileName[:fileName.index('.')]\n\n print(fileName)\n print(self.modelName)\n\n self.cacheDir = \"./pretrained_models\"\n\n os.makedirs(self.cacheDir, exist_ok=True)\n\n get_file(fname=fileName,\n origin=modelURL, cache_dir=self.cacheDir, cache_subdir=\"checkpoints\", extract=True)\n\n def loadModel(self):\n print(\"Loading Model \" + self.modelName)\n tf.keras.backend.clear_session()\n self.model = tf.saved_model.load(os.path.join(self.cacheDir, \"checkpoints\", self.modelName, \"saved_model\"))\n\n print(\"Model \" + self.modelName + \" loaded successfully....\")\n\n\n def predictImage(self, imagePath, threshold = 0.5):\n image = cv2.imread(imagePath)\n\n bboxImage = self.createBoundingBox(image, threshold)\n\n cv2.imwrite(self.modelName + \".jpg\", bboxImage)\n cv2.imshow(\"Result\", bboxImage)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\ndef organize_tfrecords(output_annotations_dir):\n def get_group_key(file):\n # Extract the title before the second \"_\" delimiter\n return \"_\".join(file.split(\"_\")[:2])\n\n file_groups = defaultdict(list)\n\n for file in os.listdir(output_annotations_dir):\n if file.endswith('.tfrecord'):\n group_key = get_group_key(file)\n file_groups[group_key].append(file)\n\n for group_key, files in file_groups.items():\n group_folder = os.path.join(output_annotations_dir, group_key)\n\n if not os.path.exists(group_folder):\n os.makedirs(group_folder)\n\n for file in files:\n src_path = os.path.join(output_annotations_dir, file)\n dst_path = os.path.join(group_folder, file)\n shutil.move(src_path, dst_path)\n\n","repo_name":"PayvandHeydari/Computer_Vision_Applied_Project","sub_path":"AutoAnnotation/detector_frames_tfrecord.py","file_name":"detector_frames_tfrecord.py","file_ext":"py","file_size_in_byte":8815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"72060782847","text":"#!/usr/bin/env python\n\n'''\ntoolbar\n'''\n\nimport sys\nfrom PyQt4 import QtGui\n\nclass ToolBar(QtGui.QMainWindow):\n\tdef __init__(self):\n\t\tsuper(ToolBar, self).__init__()\n\t\tself.initUI()\n\n\tdef initUI(self):\n\t\texitAction = QtGui.QAction(QtGui.QIcon('exit.png'), 'Exit', self)\n\t\texitAction.setShortcut('Ctrl+Q')\n\t\texitAction.triggered.connect(self.exit)\n\n\t\tsaveAction = QtGui.QAction(QtGui.QIcon('save.png'), 'Save', self)\n\t\tsaveAction.triggered.connect(self.save)\n\n\t\tself.toolbar = self.addToolBar('Exit')\n\t\tself.toolbar.addAction(exitAction)\n\n\t\tself.toolbar2 = self.addToolBar('Save')\n\t\tself.toolbar2.addAction(saveAction)\n\n\t\tself.setGeometry(300, 300, 300, 200)\n\t\tself.setWindowTitle('Toolbar')\n\t\tself.show()\n\n\tdef save(self):\n\t\tpass\n\n\tdef exit(self):\n\t\tsys.exit()\n\ndef main():\n\tapp = QtGui.QApplication(sys.argv)\n\tex = ToolBar()\n\tsys.exit(app.exec_())\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"Crasader/codes","sub_path":"python/pyqt/toolbar.py","file_name":"toolbar.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"5126877437","text":"#!/usr/bin/env python\n# coding: utf-8\n\nfrom setuptools import setup\nfrom servicenow_api.version import __version__, __author__, __credits__\nfrom pathlib import Path\nimport os\nimport re\nfrom pip._internal.network.session import PipSession\nfrom pip._internal.req import parse_requirements\n\nreadme = Path('README.md').read_text()\nversion = __version__\nrequirements = parse_requirements(os.path.join(os.path.dirname(__file__), 'requirements.txt'), session=PipSession())\nreadme = re.sub(r\"Version: [0-9]*\\.[0-9]*\\.[0-9][0-9]*\", f\"Version: {version}\", readme)\nwith open(\"README.md\", \"w\") as readme_file:\n readme_file.write(readme)\ndescription = 'Python ServiceNow API Wrapper'\n\nsetup(\n name='servicenow-api',\n version=f\"{version}\",\n description=description,\n long_description=f'{readme}',\n long_description_content_type='text/markdown',\n url='https://github.com/Knuckles-Team/servicenow-api',\n author=__author__,\n author_email='knucklessg1@gmail.com',\n license='MIT',\n packages=['servicenow_api'],\n include_package_data=True,\n install_requires=[str(requirement.requirement) for requirement in requirements],\n py_modules=['servicenow_api'],\n package_data={'servicenow_api': ['servicenow_api']},\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'License :: Public Domain',\n 'Environment :: Console',\n 'Operating System :: POSIX :: Linux',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9',\n 'Programming Language :: Python :: 3.10',\n 'Programming Language :: Python :: 3.11',\n 'Programming Language :: Python :: 3.12',\n ]\n)\n","repo_name":"Knuckles-Team/servicenow-api","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"42"} +{"seq_id":"358951840","text":"import sys\nimport heapq as h\nlength = int(sys.stdin.readline().rstrip())\n\nclass Words():\n def __init__(self):\n self._word = []\n self.heap = []\n def add_word(self, word):\n self._word.append((len(word), word))\n \n def pop_all(self):\n self._word = set(self._word)\n while(self._word):\n h.heappush(self.heap, self._word.pop())\n while(self.heap):\n print(h.heappop(self.heap)[1])\nheap = Words()\nfor i in range(length):\n heap.add_word(sys.stdin.readline().rstrip())\nheap.pop_all()","repo_name":"pnpsuM/solved.ac","sub_path":"Class2/wordsort_1181.py","file_name":"wordsort_1181.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"29474481659","text":"\nimport stripe\nfrom django.conf import settings\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.shortcuts import render, get_object_or_404, HttpResponse\nfrom rest_framework.generics import ListAPIView, RetrieveAPIView, DestroyAPIView, CreateAPIView\nfrom products.models import *\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom rest_framework import status\nfrom django.db.models import Q\nfrom rest_framework.parsers import JSONParser\nfrom rest_framework.permissions import IsAuthenticated, IsAdminUser\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom rest_framework.permissions import AllowAny\nfrom products.serializers import ProductDetailSerializer, ProductSerializer, OrderSerializer,AddressSerializer, TransactionSerializer, CompletedOrderSerializer\nfrom datetime import datetime\nimport string\nimport random\n# Create your views here.\n\nstripe.api_key =settings.STRIPE_SECRET_KEY\n\n\n\ndef generate_ref_code():\n return ''.join(random.choices(string.ascii_lowercase + string.digits, k=20))\n\ncurrent_time=datetime.now()\n\nclass AllProductListView(ListAPIView):\n queryset=Product.objects.all()\n serializer_class=ProductSerializer\n permission_classes=[AllowAny]\n \n\nclass TopProductListView(ListAPIView):\n queryset=Product.objects.all()\n serializer_class=ProductSerializer\n permission_classes=[AllowAny]\n\n def get_queryset(self):\n result=self.queryset.filter(rating__gte=4).order_by('-rating')[0:8]\n return result\n\n\nclass LatestProductListView(ListAPIView):\n queryset=Product.objects.all()\n serializer_class=ProductSerializer\n permission_classes=[AllowAny]\n\n def get_queryset(self):\n result=self.queryset.filter(category='hoodies').order_by('-created_at')[0:6]\n return result\n\nclass ProductDetailView(RetrieveAPIView):\n permission_classes=[AllowAny]\n serializer_class=ProductDetailSerializer\n queryset=Product.objects.all()\n\n\nclass AddToCart(APIView):\n permission_classes=[IsAuthenticated]\n def post(self, request, *args, **kwargs):\n prod_id=request.data.get('prod_id', None)\n variation=request.data.get('variation', [])\n qty=request.data.get('qty', None)\n \n if prod_id is None:\n return Response({'message':'invalid request'}, status=status.HTTP_400_BAD_REQUEST)\n product=get_object_or_404(Product, pk=prod_id)\n \n min_variation_count=Variation.objects.filter(item=product).count()\n if len(variation) < min_variation_count:\n return Response({'message':'please specify the required variation'}, status=status.HTTP_204_NO_CONTENT)\n order_item_qs=OrderItem.objects.filter(product=product, user=request.user, completed=False)\n for v in variation:\n order_item_qs=order_item_qs.filter(\n Q(item_variations__exact=v)\n )\n if order_item_qs.exists():\n order_item=order_item_qs.first()\n if order_item.product.countInstock > order_item.quantity:\n order_item.quantity += 1\n order_item.save()\n order_item.quantity=order_item.product.countInstock\n else:\n order_item=OrderItem.objects.create(\n product=product,\n user=request.user,\n quantity=qty,\n completed=False\n )\n order_item.item_variations.add(*variation)\n order_item.save()\n \n order_qs=Order.objects.filter(user=request.user, isPaid=False)\n if order_qs.exists():\n order=order_qs[0]\n if not order.items.filter(product__id=order_item.id).exists():\n order.items.add(order_item)\n return Response({'message':'product added to cart'},status=status.HTTP_200_OK)\n else:\n order=Order.objects.create(\n user=request.user,\n isPaid=False\n )\n order.items.add(order_item)\n return Response({'message':'product added to cart'},status=status.HTTP_200_OK)\n\n \nclass OrderDetailView(RetrieveAPIView):\n serializer_class=OrderSerializer\n permission_classes=[IsAuthenticated, IsAdminUser]\n \n def get_object(self):\n try:\n order=Order.objects.get(user=self.request.user, isPaid=False)\n return order\n except ObjectDoesNotExist:\n return Response({'message':'you do not have any item in cart'}, status=400)\n \n\nclass OrderItemDeleteView(DestroyAPIView):\n permission_classes=[IsAuthenticated]\n queryset=OrderItem.objects.all()\n\n\nclass OrderItemQuantityUpdateView(APIView):\n def post(self, request, *args, **kwargs):\n prod_id=request.data.get('prod_id', None)\n if prod_id is None:\n return Response({'message':'invalid item id'}, status=status.HTTP_400_BAD_REQUEST)\n item=get_object_or_404(Product, pk=prod_id)\n order_qs=Order.objects.filter(user=request.user, isPaid=False)\n if order_qs.exists():\n order=order_qs[0]\n if order.items.filter(product__id=item.id).exists():\n order_item=OrderItem.objects.filter(product=item, user=request.user, completed=False)[0]\n if order_item.quantity > 1:\n order_item.quantity -=1\n order_item.save()\n else:\n order.items.remove(order_item)\n return Response(status=status.HTTP_200_OK)\n else:\n return Response({'message':'this item is not in your cart'}, status=status.HTTP_400_BAD_REQUEST)\n else:\n return Response({'message':'you do not have an active order'}, status=status.HTTP_404_NOT_FOUND)\n\n\nclass AddDeliveryAddressView(APIView):\n def post(self, request, *args, **kwargs):\n serializer=AddressSerializer(data=request.data, context={'request':request})\n if serializer.is_valid(raise_exception=True):\n serializer.save(user=request.user)\n return Response(data=serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n \n \n\n\nclass CheckUserAlreadyHasAddress(APIView):\n def get(self, request, *args, **kwargs):\n address_qs=ShippingAddress.objects.filter(user=request.user, default_add=True)\n if address_qs.exists():\n addr=address_qs[0]\n return Response({'HasDefaultAddress': True, 'address':addr.address}, status=status.HTTP_200_OK)\n return Response({'HasDefaultAddress': False}, status=status.HTTP_200_OK) \n\n\nclass UseDefaultAddressView(APIView):\n def get(self, request, *args, **kwargs):\n address=ShippingAddress.objects.get(user=request.user, default_add=True)\n new_order_qs=Order.objects.filter(user=request.user, isPaid=False)\n if new_order_qs.exists():\n new_order=new_order_qs[0]\n new_order.shippingAd=address\n new_order.shippingFee=20.0\n new_order.save()\n return Response(status=status.HTTP_200_OK)\n return Response({'message':'you do not have any active order'}, status=status.HTTP_400_BAD_REQUEST)\n\n \n\nclass GetDeliveryAddress(RetrieveAPIView):\n serializer_class=AddressSerializer\n permission_classes=[IsAuthenticated]\n \n def get_object(self):\n try:\n address=ShippingAddress.objects.get(user=self.request.user, orders__isPaid=False)\n return address\n except ObjectDoesNotExist as e:\n return None\n\nclass GetDefaultAddress(RetrieveAPIView):\n serializer_class=AddressSerializer\n permission_classes=[IsAuthenticated]\n \n def get_object(self):\n try:\n address=ShippingAddress.objects.get(user=self.request.user, default_add=True)\n return address\n except ObjectDoesNotExist as e:\n return None\n\nclass CheckCustomerCardAreadyExists(APIView):\n def get(self, request, *args, **kwargs):\n transactions=TransactionHistory.objects.filter(user=request.user)\n if transactions.exists():\n trans=transactions[0]\n if trans.stripe_customer_id is not None:\n customer_payment = stripe.Customer.list_payment_methods(\n trans.stripe_customer_id,\n type=\"card\"\n )\n payment=customer_payment.data[0]\n card_detail=payment.card\n return Response({'data':card_detail,'hasCard':True}, status=status.HTTP_200_OK)\n return Response({'hasCard':False}, status=status.HTTP_200_OK)\n \n \n \n\n\n#api endpoint to use customer saved card for current payment\nclass UseCustomerPreviousCard(APIView):\n def post(self, request, *args, **kwargs):\n order=Order.objects.get(user=request.user, isPaid=False)\n amt=int(order.get_total()) * 100\n user=request.user\n history=TransactionHistory.objects.filter(user=user)\n if history.exists():\n customer=history[0]\n payment_methods = stripe.PaymentMethod.list(\n customer=customer.stripe_customer_id,\n type='card'\n )\n payment_intent = stripe.PaymentIntent.create(\n amount=amt,\n currency='usd',\n customer=customer.stripe_customer_id,\n payment_method=payment_methods.data[0].id,\n off_session=True,\n confirm=True,\n metadata={\n 'customer_email':user.email, \n },\n )\n if payment_intent.status == 'succeeded':\n return Response({'message':' payment Successfully', 'payment_intent_status':payment_intent.status}, status=status.HTTP_200_OK)\n \n return Response({'message':'this card is invalid please enter a new card'}, status=status.HTTP_403_FORBIDDEN)\n\n\n\n\n\nclass StripeIntentView(APIView):\n def post(self, request, *args, **kwargs):\n user=request.user\n name=f\"{user.first_name} {user.last_name}\"\n #save payment detail for reused by customer\n saved_card=self.request.data['save_card']\n if saved_card is True:\n customer = stripe.Customer.create(name=name,email=user.email, phone=user.phone)\n try:\n order_qs=Order.objects.filter(user=user, isPaid=False)\n if order_qs.exists():\n order=order_qs[0]\n amt=order.get_total() \n intent = stripe.PaymentIntent.create(\n customer=customer['id'],\n setup_future_usage='off_session',\n amount=int(amt) * 100,\n currency=request.data.get('currency', 'usd'),\n automatic_payment_methods={\n 'enabled': True,\n },\n metadata={\n 'customer_email':user.email,\n 'saved_card':True\n },\n )\n return Response({\n 'clientSecret': intent['client_secret']\n }, status=status.HTTP_201_CREATED)\n except Exception as e: \n return Response({'error':str(e)}, status=status.HTTP_400_BAD_REQUEST)\n else:\n try:\n order_qs=Order.objects.filter(user=user, isPaid=False)\n if order_qs.exists():\n order=order_qs[0]\n amt=order.get_total() \n intent = stripe.PaymentIntent.create(\n amount=int(amt) * 100,\n currency=request.data.get('currency', 'usd'),\n automatic_payment_methods={\n 'enabled': True,\n },\n metadata={\n 'customer_email':user.email,\n 'saved_card':False\n },\n )\n return Response({\n 'clientSecret': intent['client_secret']\n }, status=status.HTTP_201_CREATED)\n except Exception as e: \n return Response({'error':str(e)}, status=status.HTTP_400_BAD_REQUEST)\n\n\n\n\n@csrf_exempt\n\ndef stripe_webhook_view(request): \n endpoint_secret='whsec_231dbbe88ddce282857f9b713195ff914e5b6f91e35225e9f1640ea34952b6c2'\n payload = request.body\n sig_header = request.META['HTTP_STRIPE_SIGNATURE']\n event = None\n if endpoint_secret:\n try:\n event = stripe.Webhook.construct_event(\n payload, sig_header, endpoint_secret\n )\n except ValueError as e:\n # Invalid payload\n return Response(status=status.HTTP_400_BAD_REQUEST)\n except stripe.error.SignatureVerificationError as e:\n # Invalid signature\n return Response(status=status.HTTP_400_BAD_REQUEST)\n\n if event and event['type']=='payment_intent.succeeded':\n\n intent = event['data']['object']\n print(intent)\n intent_reponse=intent['charges']['data'][0]\n customer_email=intent_reponse['metadata']['customer_email']\n amount=intent['amount']\n user=CustomUser.objects.get(email=customer_email)\n order=Order.objects.get(user=user, isPaid=False)\n #create a transaction history\n history=TransactionHistory.objects.create(\n stripe_customer_id=intent_reponse['customer'] or None,\n amount=int(amount)/100,\n user=user,\n status='success'\n\n\n )\n order_items=order.items.all()\n order_items.update(completed=True)\n for item in order_items:\n item.save()\n #update the order\n order.isPaid=True\n order.payment=history\n order.reference_code=generate_ref_code()\n order.paidAt=current_time\n order.save()\n \n elif event['type'] == 'payment_method.attached':\n payment_method = event['data']['object'] # contains a stripe.PaymentMethod\n # Then define and call a method to handle the successful attachment of a PaymentMethod.\n # handle_payment_method_attached(payment_method)\n else:\n # Unexpected event type\n print('Unhandled event type {}'.format(event['type']))\n return Response({'message':'Unhandled event type'}, status.HTTP_400_BAD_REQUEST)\n\n return HttpResponse({'success':True}, status=status.HTTP_200_OK) #sending confimation mail\n \n\nclass getTransactionHistory(ListAPIView):\n serializer_class=TransactionSerializer \n permission_classes=[IsAuthenticated] \n\n def get_queryset(self):\n return TransactionHistory.objects.filter(user=self.request.user)\n\n\nclass getCompletedOrders(ListAPIView):\n serializer_class=CompletedOrderSerializer\n permission_classes=[IsAuthenticated]\n\n def get_queryset(self):\n orders=Order.objects.filter(user=self.request.user, isPaid=True)\n if orders.exists():\n return orders\n return None\n\nclass getCompletedOrderDetail(RetrieveAPIView):\n serializer_class=CompletedOrderSerializer\n permission_classes=[IsAuthenticated]\n \n \n def get_queryset(self): \n orders=Order.objects.filter(user=self.request.user, isPaid=True)\n if orders.exists():\n return orders\n return None\n\n \n\n \n \n ","repo_name":"jameshenry2020/Advance-ecommerce-django-RESTAPI","sub_path":"products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":15577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"43549180269","text":"import random\nfrom common import Fact, Rule\n\n\ndef variablize(term):\n \"\"\"Formats a term (string) to look like a Variable.\"\"\"\n # Replace spaces by underscores and uppercase first letter of a Variable term\n term = term.replace(\" \", \"_\")\n return term[0].upper() + term[1:]\n\n\ndef predicatize(term):\n \"\"\"Formats a term (string) to look like a Predicate.\"\"\"\n # Replace spaces by underscores and lowercase first letter of a Predicate term\n term = term.replace(\" \", \"_\")\n return term[0].lower() + term[1:]\n\n\ndef constantize(term):\n \"\"\"Formats a term (string) to look like a Constant.\"\"\"\n # Replace spaces by underscores and enclose in quotes for a Constant term\n return f\"'{term.replace(' ', '_')}'\"\n\n\ndef parse_fact(fact_txt):\n \"\"\"Parses text into Fact.\n E.g.:\n - ( red X )\n - ( eats X Anne )\n \"\"\"\n invalid_format_msg = (\n f\"Invalid statement format: {fact_txt}! \"\n + \"Expected fact in the format: +/- ( predicate argument1 argument2 etc. )\"\n )\n fact_txt = fact_txt.strip()\n polarity = None\n predicate = None\n arguments = []\n polarity = fact_txt[0]\n if polarity != \"+\" and polarity != \"-\":\n raise ValueError(invalid_format_msg)\n fact_txt = fact_txt[1:].strip()\n if fact_txt.startswith(\"(\") and fact_txt.endswith(\")\"):\n fact_predicate_args_txt = fact_txt[1:][:-1].strip()\n fact_tokens = fact_predicate_args_txt.split(\" \")\n if len(fact_tokens) < 2:\n raise ValueError(invalid_format_msg)\n else:\n fact_tokens = [token.strip() for token in fact_tokens]\n predicate = fact_tokens[0]\n arguments = fact_tokens[1:]\n else:\n raise ValueError(invalid_format_msg)\n return Fact(polarity, predicate, arguments)\n\n\ndef parse_multiple_facts(multiple_facts_txt):\n \"\"\"Parses text containing a list of facts.\n E.g.:\n [ - red ( X ) , - eats ( X Anne ) ]\n \"\"\"\n facts = []\n multiple_facts_txt = multiple_facts_txt.strip()\n if multiple_facts_txt.startswith(\"[\") and multiple_facts_txt.endswith(\"]\"):\n multiple_facts_txt = multiple_facts_txt[1:][:-1].strip()\n multiple_fact_txts = multiple_facts_txt.split(\",\")\n for fact_txt in multiple_fact_txts:\n fact = parse_fact(fact_txt)\n facts.append(fact)\n else:\n fact_txt = multiple_facts_txt.strip()\n fact = parse_fact(fact_txt)\n facts.append(fact)\n return facts\n\n\ndef parse_rule(statement_txt):\n potential_rule_parts = statement_txt.split(\"->\", 1)\n lhs_txt = potential_rule_parts[0].strip()\n rhs_txt = potential_rule_parts[1].strip()\n lhs = None\n try:\n lhs = parse_multiple_facts(lhs_txt)\n except ValueError:\n raise ValueError(f\"Unable to parse statement {statement_txt} as a rule.\")\n rhs = parse_fact(rhs_txt)\n return Rule(lhs, rhs)\n\n\ndef parse_statement(statement_txt):\n # Tries to parse the given text as a rule. Expected format e.g.:\n # [ - red ( X ) , - eats ( X Anne ) ] -> - eats ( Anne , Charlie )\n # lhs is made up of a list of facts and rhs is made up of a\n # single fact.\n potential_rule_parts = statement_txt.split(\"->\", 1)\n if len(potential_rule_parts) == 2:\n return parse_rule(statement_txt)\n else:\n return parse_fact(statement_txt)\n","repo_name":"allenai/ruletaker","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3306,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"42"} +{"seq_id":"28834797006","text":"import math\nimport sys\nimport time\n\ndef main():\n cache = int(sys.argv[2]) #cache size in bytes\n line = int(sys.argv[3]) #block size of cache line\n ways = int(sys.argv[4]) #number of ways in the cache\n \n simulator = [] #empty cache simulator\n linesInCache = round(cache/line) #find all lines in a cache\n setsInCache = round(linesInCache/ways) #find number of sets in a cache\n linesInSet = round(linesInCache/setsInCache) #find all lines in a set\n \n #initialize cache values to 0\n simulator = [[0,0,0,0,0,0] for i in range(linesInCache)]\n \n #initialize set values for internal cache calculations\n counter = 0\n curSet = 0\n curWay = 0\n \n for i in range(linesInCache):\n simulator[i][0] = curSet #current set value\n simulator[i][1] = curWay #current way value\n simulator[i][2] = \"tag goes here\"\n simulator[i][4] = \"true LRU or write back\"\n counter = counter + 1\n curWay = curWay + 1\n if (counter == linesInSet):\n counter = 0\n curSet = curSet + 1\n curWay = 0\n \n #initialize values for cache access and cache misses\n access = 0\n miss = 0\n \n f = open(sys.argv[1], \"r\") #open the file\n while True:\n inLine = f.readline() #read line from file\n if inLine == \"\" or inLine == \"#eof\":\n break\n fields = inLine.split() #split line into sections for calculation purposes\n if(len(fields) != 3):\n continue\n \n #caches in memory trace are accessed \n access = access + 1\n \n #initialize values for cache hit and full set\n hit = 0\n full = 0\n \n lineAddress = int(fields[2], 16) #convert hex string to int values\n offset = lineAddress & (line - 1) #calculate offset using converted hex string and block size\n setIx = lineAddress >> int(math.log(line, 2)) & (setsInCache - 1) #calculate set index using converted hex string, block size, and number of sets in cache\n tag = lineAddress >> (int(math.log(setsInCache,2)) + int(math.log(line,2))) #calculate tag using converted hex string, number of sets in cache, and block size\n \n #Check for write command in line \n if(fields[1] == \"W\"):\n firstRow = linesInSet * int(setIx)\n for i in range(firstRow, firstRow + linesInSet):\n if(simulator[i][2] == tag): #check for hit, then write to simulator\n simulator[i][2] = tag\n simulator[i][3] = 1\n simulator[i][4] = \"write back\"\n simulator[i][5] = time.time()\n hit = 1\n break\n \n full = 1 #set is full\n maxTimeConstant = sys.maxsize #constant to check access time against\n maxRow = -1 #sets simulator index to last value\n \n #cache write miss in line\n if(hit == 0):\n miss = miss + 1\n for i in range(firstRow, firstRow + linesInSet):\n if(simulator[i][3] == 0): #check for full set\n full = 0\n break\n if(simulator[i][5] < maxTimeConstant):\n maxTimeConstant = simulator[i][5] #add new access time\n maxRow = i\n if(full == 0): #set is to be filled\n simulator[i][2] = tag\n simulator[i][3] = 1\n simulator[i][4] = \"true LRU\"\n simulator[i][5] = time.time()\n else: #set is full\n simulator[maxRow][2] = tag\n simulator[maxRow][3] = 1\n simulator[maxRow][4] = \"true LRU\"\n simulator[maxRow][5] = time.time()\n \n #Check for read command in line\n elif(fields[1] == \"R\"):\n firstRow = linesInSet * int(setIx)\n for i in range(firstRow, firstRow + linesInSet):\n if(simulator[i][2] == tag): #check if way value matches tag\n hit = 1 #if way = tag, it is a hit\n simulator[i][5] = time.time() #record access stamp\n break\n \n full = 1 #set is full\n maxTimeConstant = sys.maxsize #constant to check access time against\n maxRow = -1 #sets simulator index to last value\n \n #cache read miss in line\n if(hit == 0):\n miss = miss + 1\n for i in range(firstRow, firstRow + linesInSet):\n if(simulator[i][3] == 0): #Check for full set\n full = 0\n break\n if(simulator[i][5] < maxTimeConstant):\n maxTimeConstant = simulator[i][5] #add new access time\n maxRow = i\n if(full == 0): #set is to be filled\n simulator[i][2] = tag\n simulator[i][3] = 1\n simulator[i][4] = \"true LRU\"\n simulator[i][5] = time.time()\n else: #set is full\n simulator[maxRow][2] = tag\n simulator[maxRow][3] = 1\n simulator[maxRow][4] = \"true LRU\"\n simulator[maxRow][5] = time.time()\n \n \n #calculate the miss rate\n ratePercentage = miss/access\n rate = ratePercentage * 100\n \n #print out the miss rate\n print(\"Cache miss rate: {:0.2f}%\".format(rate, 2))\n \nif __name__ == '__main__':\n main()","repo_name":"SamDash237/CS5513","sub_path":"proj3/cachesim.py","file_name":"cachesim.py","file_ext":"py","file_size_in_byte":5143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"1658394002","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def get_path(self, root, n, path):\n if root is None: return None\n \n new_path = path + [root]\n \n if root.val == n.val: return new_path\n \n left_path = self.get_path(root.left, n, new_path)\n right_path = self.get_path(root.right, n, new_path)\n \n if left_path is not None:\n return left_path\n \n if right_path is not None:\n return right_path\n \n return None\n \n def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n p_path = self.get_path(root, p, [])\n q_path = self.get_path(root, q, [])\n \n lowest_anc = root\n for i in range(1, min(len(p_path), len(q_path))):\n if p_path[i].val == q_path[i].val:\n lowest_anc = q_path[i]\n \n return lowest_anc\n \n \n \n ","repo_name":"supby/algo_train","sub_path":"lowest_common_ancestor_bt.py","file_name":"lowest_common_ancestor_bt.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"24181444017","text":"import os\nimport util.fileutil\nfrom manager.excelmanager import *\n\n\nclass DoAction:\n def __init__(self):\n self.filelist = {}\n self.filelist_without_path = {}\n self.TAG = \"DoAction\"\n pass\n\n def Println(self, *msg):\n print(self.TAG, \" \", msg)\n\n def getFileList(self, folername=None, filter=None, callback=None):\n self.Println(\"getFileList\")\n\n if folername is None:\n if (filter is None) and len(self.filelist) > 0:\n return self.filelist\n return []\n\n if None != callback:\n callback(1)\n self.filelist, self.filelist_without_path = util.fileutil.getFileList(folername, callback)\n\n if filter is None:\n return self.filelist\n\n if None != callback:\n callback(71)\n return self.getFilteredFileList(filter, callback)\n\n def getFilteredFileList(self, filter, callback=None):\n return util.fileutil.getFilteredFileList(self.filelist, filter, callback)\n\n def get_filtered_filelist_without_path(self, filter, callback=None):\n return util.fileutil.getFilteredFileList(self.filelist_without_path, filter, callback)\n\n def get_file_list_without_path(self, foldername=[], filter=[], callback=None):\n self.Println(\"get_file_list_withou_path\")\n\n if len(foldername) == 0:\n return []\n\n self.filelist, self.filelist_without_path = util.fileutil.getFileList(foldername, callback)\n\n if len(filter) == 0:\n return self.filelist_without_path\n\n if None != callback:\n callback(71)\n return self.get_filtered_filelist_without_path(filter, callback)\n\n def OnSaveAsExcel(self):\n if len(self.filelist) == 0:\n print(\"OnSaveAsExcel: There is no file in the list\")\n return\n\n excelManager = ExcelManager()\n excelManager.saveData(self.filelist)\n\n\n def OnReset(self):\n self.filelist = {}\n","repo_name":"chobocho/GetFileList","sub_path":"src/action/doaction.py","file_name":"doaction.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"41900960781","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nimport json\nimport logging\nimport os\nimport requests\nfrom urllib.parse import parse_qs\n\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\nlogging.basicConfig(format=\"%(asctime)s- %(name)s- %(message)s\")\n\nSLACK_POST_URL = os.environ[\"SLACK_POST_URL\"]\nSLACK_CHANNEL = os.environ[\"SLACK_CHANNEL\"]\n\nPOCKET_CONSUMER_KEY = os.environ[\"POCKET_CONSUMER_KEY\"]\nPOCKET_ACCESS_TOKEN = os.environ[\"POCKET_ACCESS_TOKEN\"]\nPOCKET_GET_API_URL = \"https://getpocket.com/v3/get\"\nPOCKET_SEND_API_URL = \"https://getpocket.com/v3/send\"\nPOCKET_HEADERS = {\n \"content-type\": \"application/json;charset = UTF8\",\n \"x-accept\": \"application/json\",\n \"cache-control\": \"no-cache\"\n}\n\n\ndef unique_items():\n try:\n payload = {\n \"consumer_key\": POCKET_CONSUMER_KEY,\n \"access_token\": POCKET_ACCESS_TOKEN,\n \"detailType\" : \"complete\",\n \"count\" : 3000\n }\n res = requests.request(\"POST\", POCKET_GET_API_URL, data=json.dumps(payload), headers=POCKET_HEADERS)\n res.raise_for_status()\n res_json = res.json()\n\n actions = []\n unique_resolved_url = set()\n\n # confirm that resolved_id of item with Twitter tag is in unique_resolved_url\n for item_id in res_json[\"list\"].keys():\n item_keys = res_json[\"list\"][item_id].keys()\n in_item_keys = lambda x:x in item_keys\n if not all(map(in_item_keys, (\"resolved_url\", \"tags\"))):\n continue\n\n if res_json[\"list\"][item_id][\"resolved_url\"] in unique_resolved_url:\n action = {\n \"action\" : \"delete\",\n \"item_id\": item_id\n }\n actions.append(action)\n else:\n unique_resolved_url.add(res_json[\"list\"][item_id][\"resolved_url\"])\n\n if len(actions) > 0:\n payload = {\n \"consumer_key\": POCKET_CONSUMER_KEY,\n \"access_token\": POCKET_ACCESS_TOKEN,\n \"actions\" : actions\n }\n res = requests.request(\"POST\", POCKET_SEND_API_URL, data=json.dumps(payload), headers=POCKET_HEADERS)\n res.raise_for_status()\n\n text = \"Success! %d items were deleted.\" % len(actions)\n color = \"good\"\n except:\n text = \"Failed!\"\n color = \"#ff0000\"\n\n return { \"text\": text, \"color\": color }\n\n\ndef lambda_handler(event, context):\n token = os.environ[\"SLACK_OUTGOING_WEBHOOK_TOKEN\"]\n query = parse_qs(event.get(\"body\") or \"\")\n if query.get(\"token\", [\"\"])[0] != token:\n logger.error(\"Undefined token: %s\", query.get(\"token\", [\"\"])[0])\n return { \"statusCode\": 400 }\n\n content = unique_items()\n slack_message = {\n \"channel\" : SLACK_CHANNEL,\n \"attachments\": [\n content\n ],\n }\n\n try:\n req = requests.post(SLACK_POST_URL, data=json.dumps(slack_message))\n logger.info(\"Message posted to %s\", slack_message[\"channel\"])\n return { \"statusCode\": 200 }\n except requests.exceptions.RequestException as e:\n logger.error(\"Request failed: %s\", e)\n return { \"statusCode\": 400 }\n","repo_name":"PiroHiroPiro/pocket_command_for_slack","sub_path":"source/unique/src/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":3205,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"42"} +{"seq_id":"19896392337","text":"from vpython import *\r\nroof=sphere(radius=0.05,pos=vector(0,1,0))\r\ntheta=30*pi/180\r\nR=2\r\nball=sphere(pos=roof.pos+R*vector(sin(theta),-cos(theta),0),color=color.cyan,radius=0.1,make_trail=True)\r\nstring=cylinder(pos=roof.pos,axis=ball.pos-roof.pos,radius=0.02,opacity=0.3,color=color.red)\r\nalpha=0\r\nomega=0\r\ng=-9.81\r\ntime=0\r\ndt=0.01\r\nwhile time<10:\r\n rate(100)\r\n alpha=(g/R)*sin(theta)\r\n omega+=alpha*dt\r\n theta+=omega*dt\r\n time=time+dt\r\n ball.pos=roof.pos+R*vector(sin(theta),-cos(theta),0)\r\n string.axis=axis=ball.pos-roof.pos\r\n\r\n","repo_name":"mathiopia/projects","sub_path":"Python Scripts/c++/pendulum.py","file_name":"pendulum.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"12808546219","text":"import os\nimport tensorflow as tf\nfrom functools import reduce\nfrom tensorflow.contrib.layers.python.layers import initializers\n\n\nclass CNN(Network):\n def __init__(self, sess,\n data_format,\n history_length,\n observation_dims,\n output_size, \n trainable=True,\n hidden_activation_fn=tf.nn.relu,\n output_activation_fn=None,\n weights_initializer=initializers.xavier_initializer(),\n biases_initializer=tf.constant_initializer(0.1),\n value_hidden_sizes=[512],\n advantage_hidden_sizes=[512],\n network_output_type='dueling',\n network_header_type='nips',\n name='CNN'):\n super(CNN, self).__init__(sess, name)\n\n if data_format == 'NHWC':\n self.inputs = tf.placeholder('float32',\n [None] + observation_dims + [history_length], name='inputs')\n elif data_format == 'NCHW':\n self.inputs = tf.placeholder('float32',\n [None, history_length] + observation_dims, name='inputs')\n else:\n raise ValueError(\"unknown data_format : %s\" % data_format)\n\n self.var = {}\n self.l0 = tf.div(self.inputs, 255.)\n\n with tf.variable_scope(name):\n if network_header_type.lower() == 'nature':\n self.l1, self.var['l1_w'], self.var['l1_b'] = conv2d(self.l0,\n 32, [8, 8], [4, 4], weights_initializer, biases_initializer,\n hidden_activation_fn, data_format, name='l1_conv')\n self.l2, self.var['l2_w'], self.var['l2_b'] = conv2d(self.l1,\n 64, [4, 4], [2, 2], weights_initializer, biases_initializer,\n hidden_activation_fn, data_format, name='l2_conv')\n self.l3, self.var['l3_w'], self.var['l3_b'] = conv2d(self.l2,\n 64, [3, 3], [1, 1], weights_initializer, biases_initializer,\n hidden_activation_fn, data_format, name='l3_conv')\n self.l4, self.var['l4_w'], self.var['l4_b'] = \\\n linear(self.l3, 512, weights_initializer, biases_initializer,\n hidden_activation_fn, data_format, name='l4_conv')\n layer = self.l4\n elif network_header_type.lower() == 'nips':\n self.l1, self.var['l1_w'], self.var['l1_b'] = conv2d(self.l0,\n 16, [8, 8], [4, 4], weights_initializer, biases_initializer,\n hidden_activation_fn, data_format, name='l1_conv')\n self.l2, self.var['l2_w'], self.var['l2_b'] = conv2d(self.l1,\n 32, [4, 4], [2, 2], weights_initializer, biases_initializer,\n hidden_activation_fn, data_format, name='l2_conv')\n self.l3, self.var['l3_w'], self.var['l3_b'] = \\\n linear(self.l2, 256, weights_initializer, biases_initializer,\n hidden_activation_fn, data_format, name='l3_conv')\n layer = self.l3\n else:\n raise ValueError('Wrong DQN type: %s' % network_header_type)\n\n self.build_output_ops(layer, network_output_type,\n value_hidden_sizes, advantage_hidden_sizes, output_size,\n weights_initializer, biases_initializer, hidden_activation_fn,\n output_activation_fn, trainable)\n\n\n\n\nclass Network(object):\n def __init__(self, sess, name):\n self.sess = sess\n self.copy_op = None\n self.name = name\n self.var = {}\n\n def build_output_ops(self, input_layer, network_output_type, \n value_hidden_sizes, advantage_hidden_sizes, output_size, \n weights_initializer, biases_initializer, hidden_activation_fn, \n output_activation_fn, trainable):\n \n self.outputs, self.var['w_out'], self.var['b_out'] = linear(input_layer, output_size, weights_initializer,\n biases_initializer, output_activation_fn, trainable, name='out')\n \n\n self.max_outputs = tf.reduce_max(self.outputs, reduction_indices=1)\n self.outputs_idx = tf.placeholder('int32', [None, None], 'outputs_idx')\n self.outputs_with_idx = tf.gather_nd(self.outputs, self.outputs_idx)\n self.actions = tf.argmax(self.outputs, axis=1)\n\n def run_copy(self):\n if self.copy_op is None:\n raise Exception(\"run `create_copy_op` first before copy\")\n else:\n self.sess.run(self.copy_op)\n\n def create_copy_op(self, network):\n with tf.variable_scope(self.name):\n copy_ops = []\n\n for name in self.var.keys():\n copy_op = self.var[name].assign(network.var[name])\n copy_ops.append(copy_op)\n\n self.copy_op = tf.group(*copy_ops, name='copy_op')\n\n def calc_actions(self, observation):\n return self.actions.eval({self.inputs: observation}, session=self.sess)\n\n def calc_outputs(self, observation):\n return self.outputs.eval({self.inputs: observation}, session=self.sess)\n\n def calc_max_outputs(self, observation):\n return self.max_outputs.eval({self.inputs: observation}, session=self.sess)\n\n def calc_outputs_with_idx(self, observation, idx):\n return self.outputs_with_idx.eval(\n {self.inputs: observation, self.outputs_idx: idx}, session=self.sess)\n\n\n\ndef conv2d(x,\n output_dim,\n kernel_size,\n stride,\n weights_initializer=tf.contrib.layers.xavier_initializer(),\n biases_initializer=tf.zeros_initializer,\n activation_fn=tf.nn.relu,\n data_format='NHWC',\n padding='VALID',\n name='conv2d',\n trainable=True):\n with tf.variable_scope(name):\n if data_format == 'NCHW':\n stride = [1, 1, stride[0], stride[1]]\n kernel_shape = [kernel_size[0], kernel_size[1], x.get_shape()[1], output_dim]\n elif data_format == 'NHWC':\n stride = [1, stride[0], stride[1], 1]\n kernel_shape = [kernel_size[0], kernel_size[1], x.get_shape()[-1], output_dim]\n\n w = tf.get_variable('w', kernel_shape, \n tf.float32, initializer=weights_initializer, trainable=trainable)\n conv = tf.nn.conv2d(x, w, stride, padding, data_format=data_format)\n\n b = tf.get_variable('b', [output_dim],\n tf.float32, initializer=biases_initializer, trainable=trainable)\n out = tf.nn.bias_add(conv, b, data_format)\n\n if activation_fn != None:\n out = activation_fn(out)\n\n return out, w, b\n\ndef linear(input_,\n output_size,\n weights_initializer=initializers.xavier_initializer(),\n biases_initializer=tf.zeros_initializer,\n activation_fn=None,\n trainable=True,\n name='linear'):\n shape = input_.get_shape().as_list()\n\n if len(shape) > 2:\n input_ = tf.reshape(input_, [-1, reduce(lambda x, y: x * y, shape[1:])])\n shape = input_.get_shape().as_list()\n\n with tf.variable_scope(name):\n w = tf.get_variable('w', [shape[1], output_size], tf.float32,\n initializer=weights_initializer, trainable=trainable)\n b = tf.get_variable('b', [output_size],\n initializer=biases_initializer, trainable=trainable)\n out = tf.nn.bias_add(tf.matmul(input_, w), b)\n\n if activation_fn != None:\n return activation_fn(out), w, b\n else:\n return out, w, b\n\ndef batch_sample(probs, name='batch_sample'):\n with tf.variable_scope(name):\n uniform = tf.random_uniform(tf.shape(probs), minval=0, maxval=1)\n samples = tf.argmax(probs - uniform, dimension=1)\n return samples\n","repo_name":"chenzomi12/Deep-Reinforcement-Learning","sub_path":"chapter10/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":7177,"program_lang":"python","lang":"en","doc_type":"code","stars":129,"dataset":"github-code","pt":"42"} +{"seq_id":"24687809582","text":"# Configuration file for the Sphinx documentation builder.\n#\n# For the full list of built-in configuration values, see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\nimport sys\nfrom pathlib import Path\nsys.path.insert(0, str(Path(__file__).parents[2].resolve()))\n\n# -- Project information -----------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information\n\nproject = \"LibRecommender\"\ncopyright = \"2023, massquantity\"\nauthor = \"massquantity\"\n\n# The version info for the project you're documenting, acts as replacement for\n# |version| and |release|, also used in various other places throughout the\n# built documents.\n#\n# The short X.Y version.\nimport libreco\n\nversion = \".\".join(libreco.__version__.split(\".\")[:2])\n\n# The full version, including alpha/beta/rc tags.\nrelease = libreco.__version__\n\n# -- General configuration ---------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration\n\nextensions = [\n \"sphinx.ext.autodoc\",\n \"sphinx.ext.autosectionlabel\",\n \"sphinx.ext.autosummary\",\n \"sphinx.ext.intersphinx\",\n \"sphinx.ext.napoleon\",\n \"sphinx.ext.viewcode\",\n \"sphinx_copybutton\",\n \"sphinx_inline_tabs\",\n # \"numpydoc\",\n]\n\nnapoleon_numpy_docstring = True\nnapoleon_use_admonition_for_examples = True\nnapoleon_use_admonition_for_notes = True\nnapoleon_use_admonition_for_references = True\nnapoleon_use_ivar = True\n\ntemplates_path = [\"_templates\"]\n\n# The suffix(es) of source filenames.\n# You can specify multiple suffix as a list of string:\nsource_suffix = \".rst\"\n\n# The master toctree document.\nmaster_doc = \"index\"\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This patterns also effect to html_static_path and html_extra_path\nexclude_patterns = [\"_build\", \"Thumbs.db\", \".DS_Store\"]\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = \"default\" # sphinx\n\n# -- Options for HTML output -------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output\n\nhtml_theme = \"furo\"\n\n# Theme options are theme-specific and customize the look and feel of a theme\n# further. For a list of options available for each theme, see the\n# documentation.\nhtml_theme_options = {\"top_of_page_button\": None}\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = [\"_static\"]\nhtml_css_files = [\"css/custom.css\"]\nhtml_title = f\"Lib {release} Recommender\"\n\n# Custom sidebar templates, must be a dictionary that maps document names\n# to template names.\n#\n# The default sidebars (for documents that don't match any pattern) are\n# defined by theme itself. Builtin themes are using these templates by\n# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',\n# 'searchbox.html']``.\n#\n# html_sidebars = {}\n# html_sidebars = {'**': ['globaltoc.html', 'relations.html', 'sourcelink.html',\n# 'searchbox.html']}\n\n# intersphinx configuration\nintersphinx_mapping = {\n \"python\": (\"https://docs.python.org/3\", None),\n \"numpy\": (\"https://numpy.org/doc/stable\", None),\n \"scipy\": (\"https://docs.scipy.org/doc/scipy/\", None),\n \"pandas\": (\"https://pandas.pydata.org/pandas-docs/stable/\", None),\n}\n\nautodoc_default_options = {\n \"members\": True,\n \"member-order\": \"bysource\",\n \"inherited-members\": True\n}\n","repo_name":"massquantity/LibRecommender","sub_path":"docs/source/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":3755,"program_lang":"python","lang":"en","doc_type":"code","stars":270,"dataset":"github-code","pt":"42"} +{"seq_id":"12165192372","text":"#!/usr/bin/env python\n# coding=utf-8\n\nimport cv2\nfrom functools import partial\nimport numpy as np\n\n\ndef click_event(event, x, y, flags, params,imagem,window_name,color):\n global drawing\n if event == cv2.EVENT_LBUTTONDOWN:\n drawing=True\n if event==cv2.EVENT_MOUSEMOVE and drawing:\n center_coordinates = (x, y)\n radius = 3\n thickness = -1\n imagem = cv2.circle(imagem, center_coordinates, radius, color, thickness)\n cv2.imshow(window_name, imagem)\n if event== cv2.EVENT_LBUTTONUP:\n drawing=False\n\n\ndef main():\n image_rgb = np.ones((400, 600,3))\n k=None\n window_name = \"Imagem Desenho\"\n color=(0,0,0)\n\n while k!=ord('q'):\n # Displaying the image\n cv2.imshow(window_name, image_rgb)\n #Usando o partial, criar uma função auxiliar para colocar a variavel imagem\n p_imagem = partial(click_event,imagem=image_rgb,window_name=window_name,color=color)\n cv2.setMouseCallback(window_name, p_imagem)\n\n k=cv2.waitKey(0)\n if k==ord('r'):\n color=(0,0,255)\n if k==ord('g'):\n color=(0,255,0)\n if k==ord('b'):\n color=(255,0,0)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"samuelf98/PARI_20-21_sf","sub_path":"Aula_06/1c.py","file_name":"1c.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"13364171106","text":"from datetime import datetime\r\nimport os\r\nimport zipfile\r\n\r\nbackupFolder = \"\"\r\nbackupItems = []\r\nzipperEnv = \"\"\r\nmainPath = os.path.realpath(__file__).replace(\"\\\\\",\"/\").replace(\"main.py\",\"\")\r\ndef findName(path):\r\n\tpath = path.replace(\"\\\\\",\"/\")\r\n\tpieces = path.split(\"/\")\r\n\treturn pieces[-1]\r\n\r\n\r\nwith open(mainPath+\"/settings.txt\",\"r\") as f:\r\n\tsource = f.read()\r\n\tsplitLines = source.split(\"\\n\")\r\n\tfor item in splitLines:\r\n\t\tsplitItems = item.split(\"::\")\r\n\t\tif splitItems[0] == \"backupFolder\":\r\n\t\t\tbackupFolder = splitItems[1]\r\n\t\telif splitItems[0] == \"backupTarget\":\r\n\t\t\tbackupItems.append(splitItems[1])\r\n\t\telif splitItems[0] == \"7z\":\r\n\t\t\tzipperEnv = splitItems[1]\r\n\t\telse:\r\n\t\t\tpass\r\n\r\ntime = datetime.today().strftime('%Y-%m-%d-%H_%M_%S')\r\n\r\nfor item in backupItems:\r\n\tprint(\"------------------------ Now \"+item+\" is progressing ------------------------\")\r\n\titem = item.replace(\" \",\"-\")\r\n\titemName = findName(item)\r\n\tzipString = zipperEnv+\" a -r \"+backupFolder+\"/\"+itemName+str(time)+\".zip \"+item.replace(\"\\\\\",\"/\")\r\n\tos.system(r'\"%s\"' %zipString)\r\n\r\nprint(\"------------------------ All the backup progresses are ended successfully ------------------------\")","repo_name":"byozdemir/pybackup","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"74575239805","text":"import streamlit as st\n\nst.set_page_config(\n layout=\"centered\"\n)\n\ntab1, tab2, tab3 = st.tabs([\"FAQ\", \"Technologies\", \"Data\"])\n\nwith tab1:\n st.header(\"Frequency Asked Question\")\n\n purpose = st.expander(\"What is the purpose of this project?\")\n purpose.write(\"\"\"\n Create a machine learning model that predicts the emotions of a section of text using data from a labeled dataset.\n \"\"\")\n\n accuracy = st.expander(\"What is the accuracy of our model?\")\n accuracy.write(\"\"\"\n The current demo's model has an accuracy score of 88%\n \"\"\")\n\n takeaways = st.expander(\"What are some key takeaways from this project?\")\n takeaways.write(\n \"\"\"\n - Sometimes using techniques like Stemming aren't good as generalizations aren't helpful for computers to understand language\n \"\"\"\n )\n\nwith tab2:\n st.header(\"Technologies Used In This Project\")\n col1, col2, col3 = st.columns(3)\n technologies_badges = [\n \"![Python](https://img.shields.io/badge/python-3670A0?style=for-the-badge&logo=python&logoColor=ffdd54)\",\n \"![Pandas](https://img.shields.io/badge/pandas-%23150458.svg?style=for-the-badge&logo=pandas&logoColor=white)\",\n \"![scikit-learn](https://img.shields.io/badge/scikit--learn-%23F7931E.svg?style=for-the-badge&logo=scikit-learn&logoColor=white)\",\n \"![Matplotlib](https://img.shields.io/badge/Matplotlib-%23ffffff.svg?style=for-the-badge&logo=Matplotlib&logoColor=black)\",\n \"![Jupyter Notebook](https://img.shields.io/badge/jupyter-%23FA0F00.svg?style=for-the-badge&logo=jupyter&logoColor=white)\",\n \"![Git](https://img.shields.io/badge/git-%23F05033.svg?style=for-the-badge&logo=git&logoColor=white)\"\n ]\n for idx, tech in enumerate(technologies_badges):\n if idx % 3 == 0:\n col1.write(tech)\n elif idx % 3 == 1:\n col2.write(tech)\n else:\n col3.write(tech)\n\nwith tab3:\n st.header(\"Datasets Used In This Project\")\n st.write(\n \"\"\"\n [Emotion Dataset for Emotion Recognition Tasks](https://www.kaggle.com/datasets/parulpandey/emotion-dataset)\n\n > Dataset that contains a section of text with labels for the text that describes the emotion of the text\n\n [Second Dataset](https://github.com/dair-ai/emotion_dataset)\n\n > Dataset that contains tweets with a emotion label attached to it\n \"\"\"\n )","repo_name":"112523chen/Project_SA_CTP","sub_path":"pages/About.py","file_name":"About.py","file_ext":"py","file_size_in_byte":2387,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"42"} +{"seq_id":"38577460522","text":"import os\nimport re\nimport glob\nimport emoji\nimport codecs\nimport argparse\n\nemoji_unicode = {v: k for k, v in emoji.EMOJI_UNICODE.items()}\n\n\ndef remove_emoji(line):\n line = \"\".join(char for char in line if char not in emoji_unicode)\n try:\n pattern = re.compile(u\"([\\U00002600-\\U000027BF])|([\\U0001F1E0-\\U0001F6FF])\")\n except re.error:\n pattern = re.compile(u\"([\\u2600-\\u27BF])|([\\uD83C][\\uDF00-\\uDFFF])|([\\uD83D][\\uDC00-\\uDE4F])|\"\n u\"([\\uD83D][\\uDE80-\\uDEFF])\")\n return pattern.sub(r'', line)\n\n\ndef process_twitter_token(line):\n line = remove_emoji(line)\n line = line.lstrip().rstrip().split(\"\\t\")\n if len(line) != 2:\n return None, None\n word, label = line[0], line[1]\n if word.startswith(\"@\") or word.startswith(\"https://\") or word.startswith(\"http://\"):\n return None, None\n if word in [\">\", \""\", \"<\", \":D\", \";)\", \":)\", \"-_-\", \"=D\", \":'\", \"-__-\", \":P\", \":p\", \"RT\", \":-)\", \";-)\",\n \":(\", \":/\"]:\n return None, None\n if \"&\" in word:\n word = word.replace(\"&\", \"&\")\n if word in [\"/\", \"<\"] and label == \"O\":\n return None, None\n if len(word) == 0:\n return None, None\n return word, label\n\n\ndef convert_wnut_data(file_path, save_path):\n files = [\"train.txt\", \"valid.txt\", \"test.txt\"]\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n for file in files:\n with codecs.open(os.path.join(save_path, file), mode=\"w\", encoding=\"utf-8\") as f_out:\n with codecs.open(os.path.join(file_path, file), mode=\"r\", encoding=\"utf-8\") as f:\n words, labels = [], []\n for line in f:\n line = line.lstrip().rstrip()\n if len(line) == 0:\n if len(words) == 0:\n continue\n str_list = [\"{}\\t{}\".format(word, label) for word, label in zip(words, labels)]\n f_out.write(\"\\n\".join(str_list) + \"\\n\\n\")\n words, labels = [], []\n else:\n word, label = process_twitter_token(line)\n if word is None or label is None:\n continue\n words.append(word)\n labels.append(label)\n if len(words) != 0:\n str_list = [\"{}\\t{}\".format(word, label) for word, label in zip(words, labels)]\n f_out.write(\"\\n\".join(str_list) + \"\\n\\n\")\n\n\ndef convert_wsj_data(file_path, save_path):\n # 0-18 for training, 19-21 for development, 22-24 for testing\n train_folders = [\"0\" + str(i) if i < 10 else str(i) for i in range(19)]\n dev_folders = [str(i) for i in range(19, 22)]\n test_folders = [str(i) for i in range(22, 25)]\n folders_list = [train_folders, dev_folders, test_folders]\n save_files = [\"train.txt\", \"valid.txt\", \"test.txt\"]\n for folders, save_file in zip(folders_list, save_files):\n print(folders, save_file)\n with codecs.open(os.path.join(save_path, save_file), mode=\"w\", encoding=\"utf-8\") as f_out:\n for folder in folders:\n files = glob.glob(os.path.join(file_path, folder) + \"/*.pos\")\n files.sort()\n for file in files:\n with codecs.open(file, mode=\"r\", encoding=\"utf-8\") as f:\n words, labels = [], []\n for line in f:\n line = line.lstrip().rstrip()\n if line.startswith(\"===========\") or len(line) == 0:\n if len(words) == 0:\n continue\n str_list = [\"{}\\t{}\".format(word, label) for word, label in zip(words, labels)]\n f_out.write(\"\\n\".join(str_list) + \"\\n\\n\")\n words, labels = [], []\n else:\n tokens = line.split(\" \")\n for token in tokens:\n token = token.lstrip().rstrip()\n if token in [\"[\", \"]\"] or len(token) == 0:\n continue\n idx = token.rfind(\"/\")\n word = token[0:idx]\n word = word.replace(\"\\\\\", \"\")\n label = token[idx + 1:]\n if \"|\" in label:\n label = label.split(\"|\")[0]\n words.append(word)\n labels.append(label)\n if len(words) != 0:\n str_list = [\"{}\\t{}\".format(word, label) for word, label in zip(words, labels)]\n f_out.write(\"\\n\".join(str_list) + \"\\n\\n\")\n\n\ndef convert_conll(file_path, save_path):\n files = [\"train.txt\", \"valid.txt\", \"test.txt\"]\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n for file in files:\n with codecs.open(os.path.join(save_path, file), mode=\"w\", encoding=\"utf-8\") as f_out:\n with codecs.open(os.path.join(file_path, file), mode=\"r\", encoding=\"utf-8\") as f:\n words, labels = [], []\n for line in f:\n line = line.lstrip().rstrip()\n if len(line) == 0 or line.startswith(\"-DOCSTART-\"):\n if len(words) == 0:\n continue\n str_list = [\"{}\\t{}\".format(word, label) for word, label in zip(words, labels)]\n f_out.write(\"\\n\".join(str_list) + \"\\n\\n\")\n words, labels = [], []\n else:\n word, *_, label = line.split(\" \")\n if \"page=http\" in word or \"http\" in word:\n continue\n words.append(word)\n labels.append(label)\n if len(words) != 0:\n str_list = [\"{}\\t{}\".format(word, label) for word, label in zip(words, labels)]\n f_out.write(\"\\n\".join(str_list) + \"\\n\\n\")\n\n\ndef convert_ontonotes(file_path, save_path, token=\"pos\"):\n files = [\"ontonotes.train.iob\", \"ontonotes.development.iob\", \"ontonotes.test.iob\"]\n save_files = [\"train.txt\", \"valid.txt\", \"test.txt\"]\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n for file, save_file in zip(files, save_files):\n print(file, save_file)\n with codecs.open(os.path.join(save_path, save_file), mode=\"w\", encoding=\"utf-8\") as f_out:\n with codecs.open(os.path.join(file_path, file), mode=\"r\", encoding=\"utf-8\") as f:\n words, labels = [], []\n for line in f:\n line = line.lstrip().rstrip()\n if len(line) == 0 or line.startswith(\"#begin\"):\n if len(words) == 0:\n continue\n str_list = [\"{}\\t{}\".format(word, label) for word, label in zip(words, labels)]\n f_out.write(\"\\n\".join(str_list) + \"\\n\\n\")\n words, labels = [], []\n else:\n word, pos, ner = line.split(\" \")\n words.append(word)\n if token == \"pos\":\n labels.append(pos)\n else:\n labels.append(ner)\n if len(words) != 0:\n str_list = [\"{}\\t{}\".format(word, label) for word, label in zip(words, labels)]\n f_out.write(\"\\n\".join(str_list) + \"\\n\\n\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--file_path', type=str, required=True, help='file path')\n parser.add_argument('--save_path', type=str, required=True, help='save path')\n parser.add_argument('--dataset', type=str, required=True, help='dataset name')\n args = parser.parse_args()\n if args.dataset == 'wsj':\n convert_wsj_data(args.file_path, args.save_path)\n elif args.dataset == 'conll':\n convert_conll(args.file_path, args.save_path)\n elif args.dataset == 'wnut':\n convert_wnut_data(args.file_path, args.save_path)\n elif args.dataset == 'ontonotes':\n convert_ontonotes(args.file_path, args.save_path)\n else:\n raise ValueError('Unknown dataset...')\n","repo_name":"26hzhang/DATNet","sub_path":"utils/data_cvrt.py","file_name":"data_cvrt.py","file_ext":"py","file_size_in_byte":8628,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"42"} +{"seq_id":"1706004396","text":"from django.conf.urls import url\nfrom . import views\napp_name = 'posts'\n\nurlpatterns = [\n url(r'^home$', views.home, name='home'),\n url(r'^home/post_secret$', views.post_secret, name='post_secret'),\n url(r'^home/add_like/(?P\\d+)$', views.add_like, name='add_like'),\n url(r'^home/delete_secret/(?P\\d+)$', views.delete_secret, name='delete_secret'),\n url(r'^home/most_likes$', views.most_likes, name='most_likes'),\n]\n","repo_name":"Zainab-Kalief/secret2","sub_path":"apps/post_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"2314310150","text":"from PyQt5.QtWidgets import QVBoxLayout, QHBoxLayout, QLabel, QPushButton\n\nfrom webshuttle.adapter.incoming.ui.widget.shuttle import ShuttleFrame\n\n\nclass ShuttleFrameDialogLayout(QVBoxLayout):\n def __init__(self, shuttle_frame: ShuttleFrame, dialog, shuttles_widget):\n super().__init__()\n self.frame_name = shuttle_frame.frame_name.text()\n self.shuttles_widget = shuttles_widget\n self.draft_shuttleWidgets = shuttle_frame.draft_shuttleWidgets\n self.shuttle_widget_group = shuttle_frame.shuttle_widget_group\n\n name_hBoxLayout = QHBoxLayout()\n name_hBoxLayout.addWidget(QLabel(\"셔틀 이름 : \"))\n name_hBoxLayout.addWidget(self.draft_shuttleWidgets.name_widget)\n self.addLayout(name_hBoxLayout)\n url_hBoxLayout = QHBoxLayout()\n url_hBoxLayout.addWidget(QLabel(\"URL : \"))\n url_hBoxLayout.addWidget(self.draft_shuttleWidgets.url_widget)\n self.addLayout(url_hBoxLayout)\n period_hBoxLayout = QHBoxLayout()\n period_hBoxLayout.addWidget(QLabel(\"반복 주기(초) : \"))\n period_hBoxLayout.addWidget(self.draft_shuttleWidgets.period_widget)\n self.addLayout(period_hBoxLayout)\n classes_hBoxLayout = QHBoxLayout()\n classes_hBoxLayout.addWidget(QLabel(\"타깃 클래스 : \"))\n classes_hBoxLayout.addWidget(self.draft_shuttleWidgets.target_classes_widget)\n self.addLayout(classes_hBoxLayout)\n filtering_keyword_hBoxLayout = QHBoxLayout()\n filtering_keyword_hBoxLayout.addWidget(QLabel(\"필터링 키워드 : \"))\n filtering_keyword_hBoxLayout.addWidget(self.draft_shuttleWidgets.filtering_keyword_widget)\n self.addLayout(filtering_keyword_hBoxLayout)\n\n confirm_hBoxLayout = QHBoxLayout()\n ok_button = QPushButton(\"OK\")\n ok_button.clicked.connect(lambda: self.apply_draft(dialog))\n confirm_hBoxLayout.addWidget(ok_button)\n cancel_button = QPushButton(\"Cancel\")\n cancel_button.clicked.connect(lambda: self.cancel_draft(dialog))\n confirm_hBoxLayout.addWidget(cancel_button)\n self.addLayout(confirm_hBoxLayout)\n\n def apply_draft(self, widget):\n self.shuttle_widget_group.notify_update()\n self.shuttles_widget.save_shuttles()\n widget.close()\n\n def cancel_draft(self, widget):\n self.draft_shuttleWidgets.url_widget.setText(self.shuttle_widget_group.url_widget.text())\n self.draft_shuttleWidgets.name_widget.setText(self.shuttle_widget_group.shuttle_name_widget.text())\n self.draft_shuttleWidgets.target_classes_widget.setText(self.shuttle_widget_group.target_classes_widget.text())\n self.draft_shuttleWidgets.period_widget.setValue(self.shuttle_widget_group.period_widget.value())\n self.draft_shuttleWidgets.filtering_keyword_widget.setText(self.shuttle_widget_group.filtering_keyword_widget.text())\n self.draft_shuttleWidgets.name_widget.setText(self.frame_name)\n widget.close()\n","repo_name":"targetcoders/webshuttle","sub_path":"webshuttle/adapter/incoming/ui/widget/shuttle/ShuttleFrameDialogLayout.py","file_name":"ShuttleFrameDialogLayout.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"11118341300","text":"from tkinter import *\ndef Ghi_Am():\n import sounddevice as sd\n \n import queue\n import soundfile as sf\n import threading\n from tkinter import messagebox\n\n\n path_name = 'C:/Users/HIEN/Desktop/temp/wavs/'\n file_name = path_name + \"test.wav\"\n\n #Define the user interface\n voice_rec = Tk()\n voice_rec.geometry(\"360x200\")\n voice_rec.title(\"Voice Recorder\")\n voice_rec.config(bg=\"#107dc2\")\n\n #Create a queue to contain the audio data\n q = queue.Queue()\n #Declare variables and initialise them\n recording = False\n file_exists = False \n\n #Fit data into queue\n def callback(indata, frames, time, status):\n q.put(indata.copy())\n\n #Functions to play, stop and record audio\n #The recording is done as a thread to prevent it being the main process\n def threading_rec(x):\n if x == 1:\n #If recording is selected, then the thread is activated\n t1=threading.Thread(target= record_audio)\n t1.start()\n elif x == 2:\n #To stop, set the flag to false\n global recording\n recording = False\n messagebox.showinfo(message=\"Recording finished\")\n \n #Recording function\n def record_audio():\n #Declare global variables \n global recording \n #Set to True to record\n recording= True \n global file_exists \n #Create a file to save the audio\n messagebox.showinfo(message=\"Recording Audio. Speak into the mic\")\n path_name = 'C:/Users/HIEN/Desktop/temp/wavs/'\n file_name = path_name + \"test.wav\"\n\n with sf.SoundFile(file_name, mode='w', samplerate=22050,\n channels=1) as file:\n #Create an input stream to record audio without a preset time\n with sd.InputStream(samplerate=22050, dtype='int16', channels=1, callback=callback):\n while recording == True:\n #Set the variable to True to allow playing the audio later\n file_exists =True\n #write into file\n file.write(q.get())\n\n \n #Label to display app title\n title_lbl = Label(voice_rec, text=\"Voice Recorder\", bg=\"#107dc2\").grid(row=0, column=0, columnspan=3)\n\n #Button to record audio\n record_btn = Button(voice_rec, text=\"Record Audio\", command=lambda m=1:threading_rec(m))\n #Stop button\n stop_btn = Button(voice_rec, text=\"Stop Recording\", command=lambda m=2:threading_rec(m))\n #Play button\n \n #Position buttons\n record_btn.grid(row=1,column=1)\n stop_btn.grid(row=1,column=0)\n voice_rec.mainloop()\n\n","repo_name":"hienlevan/-CNN-Voice-recognition-of-unsigned-Vietnamese-digits","sub_path":"Ghi_Am_Audio.py","file_name":"Ghi_Am_Audio.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"17446461303","text":"import re\nimport sys\nimport shlex\nfrom os import path\nfrom queue import Empty\nimport subprocess as sp\nfrom datetime import datetime\n\ntry:\n import resources.mem as mem\n from resources.benchmarks import getObjDumpPath\nexcept ImportError as err:\n print(\"Error: \", err)\n sys.exit()\n\n\n# function to read executable file to get memory map\ndef readElf(filename, objPath=None):\n \"\"\"Extract the section header information from an ELF file, format as MemoryMap\"\"\"\n if not path.exists(filename):\n print(\"Error, filename {} does not exist!\".format(filename), file=sys.stderr)\n sys.exit()\n\n # so that we can use this outside of the \"benchmarks\" stuff\n if objPath is None:\n objdump = getObjDumpPath()\n else:\n objdump = objPath\n command = \"{} -h {}\".format(objdump, filename)\n headers = sp.check_output(shlex.split(command)).decode(\"utf-8\")\n # size is 3rd element, starting address is 4th\n\n for line in headers.split('\\n'):\n if \".init \" in line:\n lline = shlex.split(line)\n init = mem.MemorySection(lline[2], lline[3], \".init\")\n elif \".text \" in line:\n lline = shlex.split(line)\n text = mem.MemorySection(lline[2], lline[3], \".text\")\n elif \".rodata \" in line:\n lline = shlex.split(line)\n rodata = mem.MemorySection(lline[2], lline[3], \".rodata\")\n elif \".data \" in line:\n lline = shlex.split(line)\n data = mem.MemorySection(lline[2], lline[3], \".data\")\n elif \".bss \" in line:\n lline = shlex.split(line)\n bss = mem.MemorySection(lline[2], lline[3], \".bss\")\n elif \".stack \" in line:\n lline = shlex.split(line)\n stack = mem.MemorySection(lline[2], lline[3], \".stack\")\n elif \".heap\" in line:\n lline = shlex.split(line)\n heap = mem.MemorySection(lline[2], lline[3], \".heap\")\n mmap = mem.MemoryMap(init, text, rodata, data, bss, stack, heap)\n return mmap\n\n\"\"\"Example of memory section output:\n\nSections:\nIdx Name Size VMA LMA File off Algn\n 0 .text 00005d00 00100000 00100000 00010000 2**6\n CONTENTS, ALLOC, LOAD, READONLY, CODE\n 12 .heap 0140000c 00110e84 00110e84 00020010 2**0\n ALLOC\n\"\"\"\n\n\n# borrowed from https://github.com/james-ben/miscellany/blob/master/python/utils/make_nice_comments.py\ndef centerText(text, surround='-', width=72):\n text = \" \" + text + \" \"\n return \"{0:{c}^{n}}\".format(text, c=surround, n=width)\n\n\ndef getFormattedTime(now=None):\n if now is None:\n now = datetime.now()\n return now.strftime(\"%Y-%m-%d %H:%M:%S.%f\")\n\n\ndef reverseFormatTime(ts):\n return datetime.strptime(ts, \"%Y-%m-%d %H:%M:%S.%f\")\n\n\ndef changeTimeBase(t, base='us'):\n if base == \"ms\":\n runtime = t / 1000.0\n elif base == \"us\":\n runtime = t / 1000000.0\n else:\n runtime = t\n return runtime\n\n\n# center of range used to calculate +/- 10%\ndef withinFloatRange(t, center, perc=0.1):\n lw = center * (1-perc)\n up = center * (1+perc)\n return ((t < up) and (t > lw))\n\n\n# https://stackoverflow.com/a/14693789\nansi_escape = re.compile(r'\\x1B\\[[0-?]*[ -/]*[@-~]')\ndef stripANSIcodes(line):\n return ansi_escape.sub('', line)\n\n# https://stackoverflow.com/a/36598450/12940429\nhexCodes = re.compile(r'[^\\x00-\\x7f]')\ndef stripHexCodes(line):\n return hexCodes.sub('', line)\n\n\ndef emptyQueue(q):\n \"\"\"Remove all remaining messages from a queue.\"\"\"\n while True:\n try:\n q.get(timeout=0.01)\n except Empty:\n break\n","repo_name":"byuccl/coast","sub_path":"simulation/platform/resources/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3634,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"42"} +{"seq_id":"74764975166","text":"from util.db_controller import DBController\nfrom module.library_migrators.book_migrator import BookMigrator\nfrom module.library_migrators.equipment_migrator import EquipmentMigrator\n\n\ndef migrateLibrary(bookDB: DBController, equipmentDB: DBController, newDB: DBController) -> None:\n print(\n f\"Migrating book data from {bookDB.getDBName()} to {newDB.getDBName()}...\")\n migrateBook(bookDB, newDB)\n\n print(\n f\"Migrating equipment data from {equipmentDB.getDBName()} to {newDB.getDBName()}...\")\n migrateEquipment(equipmentDB, newDB)\n\n\ndef migrateBook(bookDB: DBController, newDB: DBController) -> None:\n bookMigrator = BookMigrator()\n bookMigrator.setOldDBController(bookDB)\n bookMigrator.setNewDBController(newDB)\n\n bookMigrator.addBookDepartment(0, 1)\n bookMigrator.addBookDepartment(1, 2)\n bookMigrator.addBookDepartment(2, 3)\n bookMigrator.addBookDepartment(3, 4)\n bookMigrator.addBookDepartment(4, 5)\n bookMigrator.addBookDepartment(9, 6)\n\n bookMigrator.migrateBook()\n\n\ndef migrateEquipment(equipmentDB: DBController, newDB: DBController) -> None:\n\n equipmentMigrator = EquipmentMigrator()\n equipmentMigrator.setOldDBController(equipmentDB)\n equipmentMigrator.setNewDBController(newDB)\n\n equipmentMigrator.migrateEquipment()\n\n\nif __name__ == \"__main__\":\n bookDB = DBController()\n bookDB.setDBName(\"Library2\")\n bookDB.setDB()\n\n equipmentDB = DBController()\n equipmentDB.setDBName(\"Library\")\n equipmentDB.setDB()\n\n newDB = DBController()\n newDB.setDBName(\"keeper_new\")\n newDB.setDB()\n\n migrateLibrary(bookDB, equipmentDB, newDB)\n","repo_name":"KEEPER31337/Homepage-DBMigration","sub_path":"db_migration/module/library_migrators/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"25662625267","text":"import numpy as np\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport seaborn as sns\nfrom scipy import stats \n# from sklearn import mean_squared_error\nsns.set(color_codes=True)\n\nfor _,_,files in os.walk('/home/sardesaim/depthai-tutorials-practice/4-spatialnoise/Frames/', topdown=True):\n f = files\n\nframes = []\nfor frame in f: \n frames.append(np.load('/home/sardesaim/depthai-tutorials-practice/4-spatialnoise/Frames/'+frame))\n\nxyz=[]\n\nfor i in range(frames[0].shape[0]):\n for j in range(frames[0].shape[1]):\n xyz.append((i,j,frames[0][i][j]))\n\nprint(np.array(xyz)[:,:2].shape)\nxyz=np.array(xyz)\ndf=pd.DataFrame(xyz, columns=['x','y','z'])\nprint(df.tail())\ndropz=df.index[df['z']==0].tolist()\ndropi=df.index[df['z']==65535].tolist()\nc=dropz+dropi\ndf=df.drop(df.index[c])\nprint(df.shape)\ndf_o = df[df['z'] < df['z'].quantile(.90)]\nprint(df_o.shape)\n\nxyz=df_o.to_numpy()\nplt.figure()\nax = plt.subplot(111, projection='3d')\nax.scatter(xyz[:,0], xyz[:,1], xyz[:,2], color='b')\n\nA = np.matrix(np.c_[xyz[:,0], xyz[:,1], np.ones(xyz.shape[0])])\nb = np.matrix(xyz[:,2]).T\nfit = (A.T * A).I * A.T * b\nerrors = b - A * fit\nresidual = np.linalg.norm(errors)\n\nprint(\"solution:\")\nprint(\"%f x + %f y + %f = z\" % (fit[0], fit[1], fit[2]))\nprint(\"errors:\")\nprint(errors)\nprint(\"residual:\")\nprint(residual)\nprint(\"rmse\")\nprint(np.sqrt((np.multiply(np.array(errors), np.array(errors))).mean()))\n\n# plot plane\nxlim = ax.get_xlim()\nylim = ax.get_ylim()\nX,Y = np.meshgrid(np.arange(xlim[0], xlim[1]),\n np.arange(ylim[0], ylim[1]))\nZ = np.zeros(X.shape)\nfor r in range(X.shape[0]):\n for c in range(X.shape[1]):\n Z[r,c] = fit[0] * X[r,c] + fit[1] * Y[r,c] + fit[2]\nax.plot_wireframe(X,Y,Z, color='k')\nax.set_xlabel('x')\nax.set_ylabel('y')\nax.set_zlabel('z')\nplt.show()","repo_name":"precision-sustainable-ag/PhenoCV-WeedCam","sub_path":"depthai-experiments/01-spatialnoise-rmse/calc_spatial_noise.py","file_name":"calc_spatial_noise.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"42"} +{"seq_id":"72270985727","text":"# -*- coding: utf-8 -*-\nstrLR = list(input().split())\nstr1,str2 = strLR[0],strLR[1]\nn1,n2 = len(str1),len(str2)\nif n1>=n2:\n str2 = '0'*(n1-n2)+str2\nelse:\n str1 = '0'*(n2-n1)+str1\naddP,n = 0,max(n1,n2)-1\nresult = ''\nwhile n>=0:\n tempV = int(str1[n])+int(str2[n])+addP\n print(tempV)\n if tempV==3 or tempV==2:\n addP = 1\n result = str(tempV%2)+result\n else:\n result = str(tempV)+result\n addP = 0\n n-=1\nif addP == 1: \n print(str(addP)+result)\nelse:\n print(result)","repo_name":"leihenglin/algrithms1","sub_path":"addOperation.py","file_name":"addOperation.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"8700453541","text":"import itertools\n\ns = input()\na = []\nfor _ in range(int(input())):\n a.append(input())\n\nlst = []\nfor i in range(1, len(a)+1):\n tmp = list(map(''.join, itertools.permutations(a, i)))\n for j in tmp:\n lst.append(j) \n\nprint(lst)\n\nif s in lst:\n print(1)\nelse:\n print(0)\n\n'''\nabcefg\n3\nabc\nefg\nabce\n\naaaaaaaaaa\n2\naaaa\naaa\n'''","repo_name":"datoybi/algorithm-py","sub_path":"다이내믹 프로그래밍 (easy)/62_문자열 판별(16500).py","file_name":"62_문자열 판별(16500).py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"42"} +{"seq_id":"71293072767","text":"# -*- coding=utf-8 -*-\n\nfrom tools import *\n\nfile1 = open(\"image/html/186298068.html\", \"r\", encoding=\"UTF-8\")\n\ncontent = file1.read()\nimage_urls = get_images_url(content)\n\nprint(image_urls)\n\nfile1.close()\n","repo_name":"nanonin/cs-note","sub_path":"python/crawler/crawler4chan/tools_test.py","file_name":"tools_test.py","file_ext":"py","file_size_in_byte":205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"71214005888","text":"import os\nimport unittest2 as unittest\nfrom disqus.analytics.bayes.bayes import NaiveBayes\nfrom disqus.analytics.bayes.backends import RedisBackend\nfrom disqus.analytics.bayes.classifiers import FMClassifier\nfrom django.conf import settings\nfrom redis import Redis\n\n\nPORT = 6379\n\n\nclass NaiveBayesianTest(unittest.TestCase):\n\n def setUp(self):\n self.b = NaiveBayes(backend=RedisBackend(host=HOST, port=PORT))\n self.clsfr = FMClassifier.load(os.path.join(settings.DISQUS_PATH, 'analytics', 'hadoop', 'thread_views', 'classifiers', 'fm_cmap.b'))\n\n def tearDown(self):\n pass\n\n def _clear_redis(self):\n # clear out any existing redis data\n conn = Redis(host=HOST, port=PORT)\n conn.flushdb()\n\n def _train_bayesian(self):\n v0 = ('fm', 'politics', 'cnn')\n v1 = ('fm', 'tech news', 'avc')\n v2 = ('fm', 'music', 'likefm')\n self.b.train([v0] * 10)\n self.b.train([v1] * 11)\n self.b.train([v2] * 12)\n\n def test_initial_training(self):\n self._clear_redis()\n self._train_bayesian()\n self.assertEquals('politics', self.b.classify(self.clsfr, 'politics', 'cnn')[0])\n self.assertEquals('politics', self.b.classify(self.clsfr, 'summer', 'cnn')[0])\n self.assertEquals('tech news', self.b.classify(self.clsfr, 'tech news', 'avc')[0])\n self.assertEquals('tech news', self.b.classify(self.clsfr, 'summer', 'avc')[0])\n self.assertEquals('tech news', self.b.classify(self.clsfr, 'techsummerpolitics', 'avc')[0])\n self.assertEquals('music', self.b.classify(self.clsfr, 'music', 'likefm')[0])\n self.assertEquals('music', self.b.classify(self.clsfr, 'relationships & dating', 'likefm')[0])\n\n","repo_name":"gjcourt/bayes","sub_path":"bayes/tests/backend_tests.py","file_name":"backend_tests.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"42"} +{"seq_id":"40648063814","text":"from app import connection, cursor, fake\nfrom reference_lists import games, consoles\nimport random\n\nquery = '''INSERT INTO products (brand, name, buy_price, sell_price, product_type,\n game_type, in_stock, provider_name)\n VALUES (\n %s, %s, %s, %s, %s, %s, %s, %s\n )\n'''\n\nrandom.shuffle(games)\nproduct_type = 'video_game'\nin_stock = 'no'\n\n# games\nfor _ in range(5000):\n game = random.choice(games)\n brand = game['brand']\n name = game['name']\n buy_price = random.randint(1000, 1750)\n sell_price = buy_price + random.randint(100, 500)\n buy_price *= 1000\n sell_price *= 1000\n game_type = game['gtype']\n provider_name = game['brand']\n\n bind = (brand, name, buy_price, sell_price, product_type, game_type, in_stock, provider_name)\n cursor.execute(query, bind)\n\nrandom.shuffle(consoles)\nproduct_type = 'game_console'\n\n# consoles\nfor _ in range(500):\n console = random.choice(consoles)\n brand = console['brand']\n name = console['name']\n buy_price = console['price']\n rand = random.randint(100, 1000) * 1000\n sell_price = buy_price + rand\n game_type = '-'\n provider_name = console['brand']\n\n bind = (brand, name, buy_price, sell_price, product_type, game_type, in_stock, provider_name)\n cursor.execute(query, bind)\n\nconnection.commit()\n","repo_name":"Ali-M-Tabatabaei/Game-Store","sub_path":"test_data/random_products.py","file_name":"random_products.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"41896568130","text":"# importing dependencies\nfrom torch import nn\nimport torch\n\n\ndef conv_transpose_layer(input_dim, output_dim, filter_size = (2, 2), stride = (2, 2), padding=(0, 0)):\n return nn.Sequential(\n nn.ConvTranspose2d(input_dim, output_dim, kernel_size=filter_size, stride=stride, padding=padding),\n nn.BatchNorm2d(output_dim),\n nn.LeakyReLU(0.2)\n )\n\n\ndef condensing_layer(input_dim, output_dim):\n return nn.Sequential(\n nn.Conv2d(input_dim, output_dim, kernel_size=(2, 2), stride=(2, 2)),\n nn.LeakyReLU(0.2)\n )\n\n# shape is 256 x 1024\nclass Generator(nn.Module):\n def __init__(self, input_dim=64, hidden_dim=4):\n super().__init__()\n self.model = nn.Sequential(\n conv_transpose_layer(input_dim=64, output_dim=64),\n # shape is [?, 32, 32 ,128]\n conv_transpose_layer(input_dim=64, output_dim=32),\n # shape is [?, 16, 64 ,256]\n conv_transpose_layer(input_dim=32, output_dim=32),\n # shape is [?, 8, 128 ,512]\n conv_transpose_layer(input_dim=32, output_dim=16),\n # shape is [?, 4, 256 ,1024]\n conv_transpose_layer(input_dim=16, output_dim=16),\n # shape is [?, 16, 512 ,2048]\n conv_transpose_layer(input_dim=16, output_dim=8),\n # shape is [?, 8, 1024 ,4096]\n condensing_layer(input_dim=8, output_dim=4),\n # shape is [?, 8, 512 ,2048]\n condensing_layer(input_dim=4, output_dim=3),\n # shape is [?, 3, 256 ,1024]\n )\n\n\n def forward(self, x: torch.Tensor):\n return self.model(x)\n\n\n\n\nclass Discriminator(nn.Module):\n def __init__(self, im_dim=3, hidden_dim=4, input_shape=(256, 1024)):\n super().__init__()\n\n self.model = nn.Sequential(\n condensing_layer(input_dim=im_dim, output_dim=hidden_dim), # input shape halves\n condensing_layer(input_dim=hidden_dim, output_dim=hidden_dim * 2), # input shape halves\n condensing_layer(input_dim=hidden_dim * 2, output_dim=hidden_dim * 4), # input shape halves\n condensing_layer(input_dim=hidden_dim * 4, output_dim=hidden_dim * 8), # input shape halves\n nn.Flatten(),\n nn.Linear(in_features=input_shape[0]*input_shape[1]//8, out_features=1),\n nn.Sigmoid()\n )\n\n\n def forward(self, x:torch.Tensor):\n return self.model(x)\n\n\ndef generate_noise(batch_size=1, input_shape=64, l = 16, r = 64):\n vec = torch.rand(input_shape*batch_size * l * r)\n vec = torch.reshape(vec, [batch_size, input_shape, l, r])\n return vec\n\n\n","repo_name":"ved07/cycle_gans_KC","sub_path":"GAN_implementation/networks.py","file_name":"networks.py","file_ext":"py","file_size_in_byte":2615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"40296507675","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 1 15:17:22 2018\n\n@author: USER\n\"\"\"\n\nimport numpy as np\nimport cv2\n\ndef featureMatching():\n img1 = cv2.imread(\"test1.jpg\", cv2.IMREAD_GRAYSCALE)\n img2 = cv2.imread(\"test2.jpg\", cv2.IMREAD_GRAYSCALE)\n res = None\n \n sift = cv2.xfeatures2d.SIFT_create()\n kp1, des1 = sift.detectAndCompute(img1, None)\n kp2, des2 = sift.detectAndCompute(img2, None)\n \n bf = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True)\n matches = bf.match(des1, des2)\n \n matches = sorted(matches, key=lambda x:x.distance)\n res = cv2.drawMatches(img1, kp1, img2, kp2, matches[:30], res, flags=0)\n \n cv2.imshow(\"feature matching\", res)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n \nfeatureMatching()","repo_name":"flash1117/OpenCV","sub_path":"img_feature_matching_SIFT.py","file_name":"img_feature_matching_SIFT.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"2931552296","text":"import numpy as np\r\nfrom keras.layers import *\r\nfrom keras.models import *\r\nfrom keras.activations import *\r\nfrom keras.callbacks import ModelCheckpoint,ReduceLROnPlateau\r\n\r\ndef keras_model():\r\n model=Sequential()\r\n model.add(Conv2D(32,(3,3),padding=\"same\"))\r\n model.add(Conv2D(32,(3,3),padding=\"same\"))\r\n model.add(MaxPool2D())\r\n model.add(Conv2D(64,(3,3),padding=\"same\"))\r\n model.add(Conv2D(64,(3,3),padding=\"same\"))\r\n model.add(MaxPool2D())\r\n model.add(Flatten())\r\n model.add(Dense(128,activation='relu'))\r\n # model.add(relu())\r\n model.add(Dense(256,activation='relu'))\r\n # model.add(relu())\r\n model.add(Dense(128,activation='relu'))\r\n # model.add(relu())\r\n model.add(Dense(1))\r\n \r\n model.compile(optimizer=\"adam\",loss=\"mse\")\r\n \r\n filepath=\"selfdrivingv1.h5\"\r\n \r\n checkpoint= ModelCheckpoint (filepath,verbose=1,save_best_only=True)\r\n lr=ReduceLROnPlateau(factor=0.1,patience=3,min_lr=1e-8)\r\n callbacks=[checkpoint,lr]\r\n return model,callbacks\r\n\r\n\r\nfeatures=np.load(\"features_40x40.npy\")\r\nlabels=np.load(\"labels_40x40.npy\")\r\n\r\n#augment data\r\n\r\nfeatures=np.append(features,features[:,:,::-1],axis=0)\r\nlabels=np.append(labels,-labels,axis=0)\r\nfeatures=features.reshape(features.shape[0],40,40,1)\r\nprint(features.shape)\r\n\r\nmodel,callbacks=keras_model()\r\n\r\nfrom sklearn.model_selection import train_test_split as split\r\ntrain_x,test_x,train_y,test_y=split(features,labels,test_size=0.1,random_state=1)\r\nprint(train_x[0])\r\nmodel.fit(x=train_x,y=train_y,epochs=10,batch_size=64,callbacks=callbacks,validation_data=(test_x,test_y))\r\n\r\nprint(model.summary())\r\nmodel.save(\"selfdriving1v1.h5\")\r\n","repo_name":"SCHRODlNGER/Car_Autopilot","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"33428967269","text":"import re\nfrom django import forms\nfrom .models import ClientModel\nfrom crispy_forms.helper import FormHelper\nfrom django.utils.translation import gettext_lazy as _\n\n\nclass ClientForm(forms.ModelForm): # pragma: no coverage\n class Meta:\n model = ClientModel\n fields = (\n \"photo\",\n \"client_type\",\n \"cpf_cnpj\",\n \"name_corporate\",\n \"email\",\n \"birth_date\",\n \"district\",\n \"state\",\n \"address\",\n \"sex\",\n \"rg\",\n \"cep\",\n \"complement_address\",\n \"number_address\",\n \"cell_phone\",\n \"phone\",\n \"city\",\n \"obs\",\n )\n\n widgets = {\n \"state\": forms.Select(attrs={\"class\": \"form-select clients-form__states\"}),\n \"sex\": forms.Select(attrs={\"class\": \"form-select clients-form__sex\"}),\n \"client_type\": forms.Select(\n attrs={\"class\": \"form-select clients-form__client_type\"}\n ),\n \"birth_date\": forms.TextInput(attrs={\"type\": \"date\"}),\n \"email\": forms.TextInput(attrs={\"placeholder\": \"my-email@example.com\"}),\n \"cpf_cnpj\": forms.TextInput(\n attrs={\"class\": \"clients-form__input-cpf-cnpj\"}\n ),\n \"cell_phone\": forms.TextInput(\n attrs={\"data-mask\": \"(00) 00000-0000\", \"placeholder\": \"(00) 00000-0000\"}\n ),\n \"phone\": forms.TextInput(\n attrs={\"data-mask\": \"(00) 0000-0000\", \"placeholder\": \"(00) 0000-0000\"}\n ),\n \"obs\": forms.Textarea(\n attrs={\"placeholder\": _(\"Escreva uma nota para este cliente\")}\n ),\n \"name_corporate\": forms.TextInput(\n attrs={\"placeholder\": \"Ex: Elvis Presley\"}\n ),\n \"rg\": forms.TextInput(attrs={\"placeholder\": \"Ex: 99.999.999-9\"}),\n }\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.helper = FormHelper()\n self.helper.form_show_labels = False\n\n # Limpa a mascara antes de fazer a verificação com o banco de dados.\n def clean_cpf_cnpj(self):\n data = re.sub(\"[^0-9]\", \"\", self.cleaned_data[\"cpf_cnpj\"])\n return data\n\n def clean_cell_phone(self):\n data = re.sub(\"[^0-9]\", \"\", self.cleaned_data[\"cell_phone\"])\n return data\n\n def clean_phone(self):\n data = re.sub(\"[^0-9]\", \"\", self.cleaned_data[\"phone\"])\n return data\n","repo_name":"williamcanin/crud-django-cbv","sub_path":"apps/clients/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"23006581016","text":"import os.path\nimport random\nimport glob\nfrom PIL import Image\nfrom typing import Optional, Any\n\nfrom torchvision import transforms\nfrom torch.utils.data import Dataset\nfrom lightning import LightningDataModule\nfrom torch.utils.data import DataLoader, Dataset, random_split\n\nIMG_EXTENSIONS = [\n \".jpg\",\n \".JPG\",\n \".jpeg\",\n \".JPEG\",\n \".png\",\n \".PNG\",\n \".ppm\",\n \".PPM\",\n \".bmp\",\n \".BMP\",\n \".tif\",\n \".TIF\",\n \".tiff\",\n \".TIFF\",\n]\n\n\ndef is_image_file(filename):\n return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)\n\n\ndef make_dataset(dir, max_dataset_size=float(\"inf\")):\n images = []\n assert os.path.isdir(dir) or os.path.islink(dir), (\n \"%s is not a valid directory\" % dir\n )\n\n for root, _, fnames in sorted(os.walk(dir, followlinks=True)):\n for fname in fnames:\n if is_image_file(fname):\n path = os.path.join(root, fname)\n images.append(path)\n return images[:min(max_dataset_size, len(images))]\n\n\ndef _make_power_2(img: Image, base: int = 4, method=Image.BICUBIC):\n ow, oh = img.size\n h = int(round(oh / base) * base)\n w = int(round(ow / base) * base)\n if h == oh and w == ow:\n return img\n\n return img.resize((w, h), method)\n\n\ndef get_transform(\n resize: int = 286, crop_size: int = 256, grayscale: bool = False, train: bool = True\n):\n \"\"\"\n preprocessing = resize_and_crop\n load_size = 286, crop_size=256\n return -1 to 1\n \"\"\"\n transform_list = []\n if train:\n transform_list.append(transforms.Resize(resize))\n transform_list.append(transforms.RandomCrop(crop_size))\n transform_list.append(transforms.RandomHorizontalFlip())\n\n transform_list += [transforms.ToTensor()]\n if grayscale:\n transform_list += [transforms.Normalize((0.5,), (0.5,))]\n else:\n transform_list += [transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]\n\n return transforms.Compose(transform_list)\n\n\nclass UnalignedDataset(Dataset):\n \"\"\"\n This dataset class can load unaligned/unpaired datasets.\n\n It requires two directories to host training images from domain A '/path/to/data/trainA'\n and from domain B '/path/to/data/trainB' respectively.\n You can train the model with the dataset flag '--dataroot /path/to/data'.\n Similarly, you need to prepare two directories:\n '/path/to/data/testA' and '/path/to/data/testB' during test time.\n \"\"\"\n\n def __init__(self, data_dir, phase: str):\n \"\"\"Initialize this dataset class.\n\n Args:\n opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions\n dataset_root datasets/horse2zebra\n max_dataset_size: float(int)\n \"\"\"\n # create a path '/path/to/data/trainA', '/path/to/data/trainB'\n self.dir_a = os.path.join(data_dir, phase + \"A\")\n self.dir_b = os.path.join(data_dir, phase + \"B\")\n\n self.a_paths = sorted(glob.glob(self.dir_a + \"/*.*\"))\n self.b_paths = sorted(glob.glob(self.dir_b + \"/*.*\"))\n\n self.a_size = len(self.a_paths) # get the size of dataset A\n self.b_size = len(self.b_paths) # get the size of dataset B\n\n self.is_train = phase == \"train\"\n\n def __getitem__(self, index: int):\n \"\"\"Return a data point and its metadata information.\n\n Args:\n index (int) -- a random integer for data indexing\n\n Returns:\n a dictionary that contains A, B, A_paths and B_paths\n A (tensor) -- an image in the input domain\n B (tensor) -- its corresponding image in the target domain\n A_paths (str) -- image paths\n B_paths (str) -- image paths\n \"\"\"\n a_path = self.a_paths[index % self.a_size]\n # make sure index is within then range\n # randomize the index for domain B to avoid fixed pairs.\n index_b = random.randint(0, self.b_size - 1)\n b_path = self.b_paths[index_b]\n a_img = Image.open(a_path).convert(\"RGB\")\n b_img = Image.open(b_path).convert(\"RGB\")\n # Apply image transformation\n # For CUT/FastCUT mode, if in finetuning phase (learning rate is decaying),\n # do not perform resize-crop data augmentation of CycleGAN.\n # is_finetuning = self.opt.isTrain and self.current_epoch > self.opt.n_epochs\n \n # modified_opt = util.copyconf(\n # self.opt,\n # load_size=self.opt.crop_size if is_finetuning else self.opt.load_size,\n # )\n\n # load_size = self.opt.crop_size if is_finetuning else self.opt.load_size,\n transform = get_transform(286, 256, train=self.is_train)\n a_img = transform(a_img)\n b_img = transform(b_img)\n\n return a_img, b_img\n\n def __len__(self):\n \"\"\"Return the total number of images in the dataset.\n\n As we have two datasets with potentially different number of images,\n we take a maximum of\n \"\"\"\n return max(self.a_size, self.b_size)\n\n\n\nclass UnalignedDataModule(LightningDataModule):\n \"\"\"LightningDataModule for the CIFAR10 dataset.\n\n Read the docs:\n https://lightning.ai/docs/pytorch/latest/data/datamodule.html\n \"\"\"\n def __init__(\n self,\n data_dir: str = \"data/\",\n batch_size: int = 1,\n num_workers: int = 1,\n pin_memory: bool = False,\n ) -> None:\n super().__init__()\n self.save_hyperparameters(logger=False)\n\n self.trainset: Optional[Dataset] = None\n self.validset: Optional[Dataset] = None\n self.testset: Optional[Dataset] = None\n\n def prepare_data(self) -> None:\n UnalignedDataset(self.hparams.data_dir, phase=\"train\")\n\n def setup(self, stage: Optional[str] = None) -> None:\n self.trainset = UnalignedDataset(self.hparams.data_dir, phase=\"train\")\n self.validset = UnalignedDataset(self.hparams.data_dir, phase=\"test\")\n # if not self.trainset and not self.validset and not self.testset:\n # trainset = MNIST(self.hparams.data_dir, train=True, transform=self.transforms)\n # testset = MNIST(self.hparams.data_dir, train=False, transform=self.transforms)\n # dataset = ConcatDataset(datasets=[trainset, testset])\n # self.trainset, self.validset, self.testset = random_split(\n # dataset=dataset,\n # lengths=[55_000, 5_000, 10_000],\n # generator=torch.Generator().manual_seed(42),\n # )\n\n def train_dataloader(self) -> DataLoader[Any]:\n return DataLoader(\n dataset=self.trainset,\n batch_size=self.hparams.batch_size,\n num_workers=self.hparams.num_workers,\n pin_memory=self.hparams.pin_memory,\n shuffle=True,\n )\n\n def val_dataloader(self) -> DataLoader[Any]:\n return DataLoader(\n dataset=self.validset,\n batch_size=self.hparams.batch_size,\n num_workers=self.hparams.num_workers,\n pin_memory=self.hparams.pin_memory,\n shuffle=False,\n )\n # def test_dataloader(self) -> DataLoader[Any]:\n # return\n\n\nif __name__ == \"__main__\":\n _ = UnalignedDataModule()\n\n","repo_name":"unerue/lightgan","sub_path":"src/datasets/unaligned_dataset.py","file_name":"unaligned_dataset.py","file_ext":"py","file_size_in_byte":7250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"28466904409","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jun 4 21:56:58 2018\r\n\r\n@author: LENOVO\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom sklearn import datasets\r\nfrom sklearn.tree import DecisionTreeClassifier\r\n\r\n\"\"\" 自定义函数:对数据图像进行打印输出 \"\"\"\r\ndef show(x,y):\r\n plt.scatter(x[y==0,0],x[y==0,1])\r\n plt.scatter(x[y==1,0],x[y==1,1])\r\n plt.scatter(x[y==2,0],x[y==2,1])\r\n plt.show()\r\n\r\n\"\"\" 为了方便,我们导入自带的鸢尾花的数据集,且只取后两个维度的数据 \"\"\"\r\niris = datasets.load_iris()\r\nx = iris.data[:,2:]\r\ny = iris.target\r\nshow(x,y)\r\n\r\n\"\"\" 训练决策树的分类器,决策树的划分标准使用基尼不纯度 (INI impurity) \"\"\" \r\ndt_clf = DecisionTreeClassifier(max_depth =3 ,criterion='gini')\r\ndt_clf.fit(x,y)\r\n\r\n\"\"\" 自定义函数:绘测决策边界 \"\"\"\r\ndef plot_decision_boundary(model, axis):\r\n x0,x1 = np.meshgrid(\r\n np.linspace(axis[0],axis[1],int((axis[1]-axis[0])*500)).reshape((-1,1)), #这里的reshape()中的参数可能要改\r\n np.linspace(axis[2],axis[3],int((axis[3]-axis[2])*500)).reshape((-1,1))\r\n )\r\n x_new = np.c_[x0.ravel(),x1.ravel()]\r\n y_predict = model.predict(x_new)\r\n zz = y_predict.reshape(x0.shape)\r\n from matplotlib.colors import ListedColormap\r\n custom_cmap = ListedColormap(['#EF9A9A','#FFF59D','#90CAF9'])\r\n plt.contourf(x0,x1,zz,linewidth=5,cmap=custom_cmap) \r\n\r\nplot_decision_boundary(dt_clf,axis=[0.5,7.5,0,3])\r\nshow(x,y)\r\n \r\n","repo_name":"morewine/hello_world","sub_path":"first_decision_tree.py","file_name":"first_decision_tree.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"72989222205","text":"# Python 3.x\r\n# Purpose: simple demo of how to blink an LED based on the position of the sun\r\n#\r\n# 2019 04 30 AJL Created file\r\n\r\n# standard library\r\nimport time\r\n\r\n# site packages\r\nimport RPi.GPIO as GPIO\r\nimport json\r\nimport urllib.request\r\nimport requests\r\n\r\n# loop forever or run once\r\nloop_forever = 0\r\n\r\n# setup GPIO using BCM numbering\r\nGPIO.setmode(GPIO.BCM)\r\n\r\n# Pin assignments\r\nLED_Pin = 23\r\nhltPin = 13 # exit program\r\nButton_Pin = 20\r\n\r\n# GPIO setup\r\nGPIO.setup(LED_Pin, GPIO.OUT)\r\nGPIO.setup(hltPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\r\nGPIO.setup(Button_Pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)\r\n\r\n# sunset check\r\nURLall = \"http://www.l3nhart.io/cgi-bin/SunRiseSunSetJSONwDST.py\"\r\n#URLall = \"https://api.sunrise-sunset.org/json?lat=42.4606&lng=-83.1346\"\r\n#URLall = \"http://192.168.1.91/cgi-bin/SunRiseSunSetJSONwDST.py\"\r\n\r\nwhile True:\r\n\r\n # check if we need to halt the program\r\n if GPIO.input(hltPin):\r\n GPIO.cleanup() # cleanup all GPIO\r\n print(\"Shutting Down\")\r\n exit()\r\n\r\n # check for sunset\r\n try:\r\n urlhand = requests.get(URLall)\r\n\r\n except:\r\n print ('Error SunriseSusnet.org')\r\n\r\n # read the raw response\r\n url_raw = urlhand.text\r\n print(url_raw)\r\n json_lines = urlhand.json()\r\n\r\n print ('Dump of json_lines >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')\r\n print (json_lines)\r\n\r\n # pretty print the JSON\r\n print('Pretty print of json_lines >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')\r\n print(json.dumps(json_lines, indent=4, separators=(',', ': ')))\r\n\r\n # parse the JSON - the file only contains one line\r\n\r\n # get the position of the sun (up or down)\r\n print ('Dump of sun_pos >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')\r\n sun_pos = json_lines['TheSunIs']\r\n print(sun_pos)\r\n\r\n # convert str to int\r\n isun_pos = str(sun_pos)\r\n\r\n # switch the light on if the sun has set\r\n if isun_pos:\r\n GPIO.output(LED_Pin, GPIO.LOW)\r\n else:\r\n GPIO.output(LED_Pin, GPIO.HIGH)\r\n\r\n time.sleep(60)\r\n \r\n # stop the loop or keep going\r\n if not loop_forever:\r\n exit()\r\n\r\n\r\n\r\n","repo_name":"Andy1213/Python-and-Physical-Computing","sub_path":"Sunset_Blink2.py","file_name":"Sunset_Blink2.py","file_ext":"py","file_size_in_byte":2169,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"15699978887","text":"import numpy as np\nimport cv2\n# img = cv2.imread('31062468.jpg',1)\n\n# create numpy image\nimg = np.zeros([512,512,3],np.uint8)\n\n# Draw straight line\nimg = cv2.line(img, (0,0),(255,255), (147,96,44), 10)\n\n#Draw arrowed line\nimg = cv2.arrowedLine(img, (0,255),(255,255), (147,96,44), 10)\n\n\n# Draw rectangle\nimg = cv2.rectangle(img, (355,255), (255,128), (0,0,255),10)\n\n\n# Draw circle\nimg = cv2.circle(img, (355,255), 36, (0, 255, 0), -1)\n\n\n# Text in an Image\nfont = cv2.FONT_HERSHEY_COMPLEX\nimg = cv2.putText(img,\"Chrisribia Open Cv\",(0,255),font, 4,(255,0,0), 1,cv2.LINE_AA)\ncv2.imshow(\"image liv\\ne\",img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","repo_name":"chrisribia/open-cv","sub_path":"Draw-geometricShapesOnIMages.py","file_name":"Draw-geometricShapesOnIMages.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"6214767194","text":"#!/usr/bin/env python\n\nfrom lbtoolbox.util import flipany\n\nimport os\nimport sys\nimport re\nimport inspect\nimport json\nimport pickle\nimport gzip\nfrom os.path import join as pjoin\n\nimport cv2\nimport numpy as np\nfrom scipy.io import loadmat\nfrom sklearn.preprocessing import LabelEncoder\nimport h5py\n\n\ndef here(f):\n me = inspect.getsourcefile(here)\n return pjoin(os.path.dirname(os.path.abspath(me)), f)\n\n\ndef imread(fname, resize=None):\n im = cv2.imread(fname, flags=cv2.IMREAD_COLOR)\n if im is None:\n raise ValueError(\"Couldn't load image \" + fname)\n\n if resize is not None and im.shape[:2] != resize:\n im = cv2.resize(im, resize, interpolation=cv2.INTER_LANCZOS4)\n\n # In OpenCV, color dimension is last, but theano likes it to be first.\n # (That's map of triplets vs three maps philosophy.)\n # Also convert BGR to RGB while we're at it. Not that it makes any difference.\n im = np.rollaxis(im[:,:,::-1], 2, 0)\n return im.astype(np.float32) / 256\n\n\ndef scale_all(images, size=(50, 50)):\n return [cv2.resize(im, size, interpolation=cv2.INTER_LANCZOS4) for im in images]\n\n\ndef loadall(datadir, data):\n return zip(*[[imread(pjoin(datadir, name)), lbl, name] for lbl, files in data.items() for name in files])\n\n\ndef load_tosato_clf(datadir, datafile):\n data = json.load(open(pjoin(datadir, datafile)))\n\n tr_imgs, tr_lbls, tr_names = loadall(datadir, data['train'])\n te_imgs, te_lbls, te_names = loadall(datadir, data['test'])\n\n le = LabelEncoder().fit(tr_lbls)\n return (\n np.array(tr_imgs), le.transform(tr_lbls).astype(np.int32), tr_names,\n np.array(te_imgs), le.transform(te_lbls).astype(np.int32), te_names,\n le\n )\n\n\ndef matlab_array(mat, ref, dtype):\n N = len(ref)\n arr = np.empty(N, dtype=dtype)\n for i in range(N):\n arr[i] = mat[ref[i,0]][0,0]\n return arr\n\n\ndef matlab_string(obj):\n return ''.join(chr(c) for c in obj[:,0])\n\n\ndef matlab_strings(mat, ref):\n return [matlab_string(mat[r]) for r in ref[:,0]]\n\n\ndef load_tosato_idiap(datadir, datafile):\n mat_full = h5py.File(pjoin(datadir, datafile))\n\n def load(traintest):\n container = mat_full['or_label_' + traintest]\n pan = matlab_array(mat_full, container['pan'], np.float32)\n tilt = matlab_array(mat_full, container['tilt'], np.float32)\n roll = matlab_array(mat_full, container['roll'], np.float32)\n names = matlab_strings(mat_full, container['name'])\n X = np.array([imread(pjoin(datadir, traintest, name)) for name in names])\n return X, pan, tilt, roll, names\n\n return load('train'), load('test')\n\n\ndef matlab_vector(mat, col, dtype):\n N = len(mat)\n vec = np.empty(N, dtype=dtype)\n for i in range(N):\n vec[i] = mat[i][col][0,0]\n return vec\n\n\ndef matlab_strings2(mat, col):\n return [m[col][0] for m in mat]\n\n\ndef load_tosato_caviar(datadir, datafile):\n mat = loadmat(pjoin(datadir, datafile))\n\n def load(traintest):\n gazes = matlab_vector(mat['or_label_' + traintest][0], 0, np.float32)\n xcs = matlab_vector(mat['or_label_' + traintest][0], 1, np.float32)\n ycs = matlab_vector(mat['or_label_' + traintest][0], 2, np.float32)\n sizes = matlab_vector(mat['or_label_' + traintest][0], 3, np.float32)\n names = matlab_strings2(mat['or_label_' + traintest][0], 4)\n X = np.array([imread(pjoin(datadir, traintest, name + '.jpg')) for name in names])\n return X, gazes, xcs, ycs, sizes, names\n\n return load('train'), load('test')\n\n\ndef load_towncentre(datadir, normalize_angles=True):\n panre = re.compile('pan = ([+-]?\\d+\\.\\d+)\\n')\n valre = re.compile('valid = ([01])\\n')\n angles = []\n images = []\n names = []\n for father in os.listdir(datadir):\n try:\n for son in os.listdir(pjoin(datadir, father)):\n if not son.endswith('.txt'):\n continue\n\n lpan, lval = open(pjoin(datadir, father, son)).readlines()\n if int(valre.match(lval).group(1)) == 0:\n continue\n\n angles.append(float(panre.match(lpan).group(1)))\n # Now search for the corresponding filename, unfortunately, it has more numbers encoded...\n fnames = [f for f in os.listdir(pjoin(datadir, father)) if f.startswith(son.split('.')[0]) and not f.endswith('.txt')]\n assert len(fnames) == 1, \"lolwut\"\n names.append(fnames[0])\n images.append(cv2.imread(pjoin(datadir, father, fnames[0]), flags=cv2.IMREAD_COLOR))\n except NotADirectoryError:\n pass\n\n if normalize_angles:\n angles = [(a + 360*2) % 360 for a in angles]\n\n return images, angles, names\n\n\ndef flipped_classes(X, y, n, le, old, new):\n \"\"\"\n Horizontally flips all images in `X` which are labeled as `old` and label them as `new`.\n Returns the flipped X, y, n.\n \"\"\"\n indices = np.where(y == le.transform(old))[0]\n return (\n flipany(X[indices], dim=3),\n np.full(len(indices), le.transform(new), dtype=y.dtype),\n tuple(n[i] for i in indices)\n )\n\n\ndef flipall_classes(X, y, n, le, flips):\n \"\"\"\n Applies all `flips` to the whole dataset X, y, n and returns the augmented dataset.\n \"\"\"\n fx, fy, fn = [], [], []\n for old, new in flips:\n a, b, c = flipped_classes(X, y, n, le, old, new)\n fx.append(a) ; fy.append(b) ; fn.append(c)\n return np.concatenate([X] + fx), np.concatenate([y] + fy), n + sum(fn, tuple())\n\n\ndef flipall_images(images):\n \"\"\"\n Horizontally flips all given `images`, assuming `images` to be a list of HWC tensors.\n \"\"\"\n return [flipany(img, dim=1) for img in images]\n\n\ndef flipall_angles(angles):\n \"\"\"\n Horizontally flips all angles in the `angles` array.\n \"\"\"\n return [360 - a for a in angles]\n\n\nif __name__ == '__main__':\n datadir = here('data')\n\n todos = sys.argv[1:] if len(sys.argv) > 1 else ['QMUL', 'HOCoffee', 'HOC', 'HIIT', 'IDIAP', 'CAVIAR', 'TownCentre']\n\n if 'QMUL' in todos:\n print(\"Augmenting QMUL (Without \\\" - Copy\\\")... \")\n Xtr, ytr, ntr, Xte, yte, nte, le = load_tosato_clf(datadir, 'QMULPoseHeads.json')\n Xtr, ytr, ntr = flipall_classes(Xtr, ytr, ntr, le, flips=[\n ('front', 'front'),\n ('back', 'back'),\n ('background', 'background'),\n ('left', 'right'),\n ('right', 'left'),\n ])\n pickle.dump((Xtr, Xte, ytr, yte, ntr, nte, le),\n gzip.open(pjoin(datadir, 'QMULPoseHeads-wflip.pkl.gz'), 'wb+'))\n print(len(Xtr))\n\n if 'HOCoffee' in todos:\n print(\"Augmenting HOCoffee... \")\n Xtr, ytr, ntr, Xte, yte, nte, le = load_tosato_clf(datadir, 'HOCoffee.json')\n Xtr, ytr, ntr = flipall_classes(Xtr, ytr, ntr, le, flips=[\n ('frnt', 'frnt'),\n ('rear', 'rear'),\n ('left', 'rght'),\n ('rght', 'left'),\n ('frlf', 'frrg'),\n ('frrg', 'frlf'),\n ])\n pickle.dump((Xtr, Xte, ytr, yte, ntr, nte, le),\n gzip.open(pjoin(datadir, 'HOCoffee-wflip.pkl.gz'), 'wb+'))\n print(len(Xtr))\n\n if 'HOC' in todos:\n print(\"Augmenting HOC... \")\n Xtr, ytr, ntr, Xte, yte, nte, le = load_tosato_clf(datadir, 'HOC.json')\n Xtr, ytr, ntr = flipall_classes(Xtr, ytr, ntr, le, flips=[\n ('back', 'back'),\n ('front', 'front'),\n ('left', 'right'),\n ('right', 'left'),\n ])\n pickle.dump((Xtr, Xte, ytr, yte, ntr, nte, le),\n gzip.open(pjoin(datadir, 'HOC-wflip.pkl.gz'), 'wb+'))\n print(len(Xtr))\n\n if 'HIIT' in todos:\n print(\"Augmenting HIIT... \")\n Xtr, ytr, ntr, Xte, yte, nte, le = load_tosato_clf(datadir, 'HIIT6HeadPose.json')\n Xtr, ytr, ntr = flipall_classes(Xtr, ytr, ntr, le, flips=[\n ('frnt', 'frnt'),\n ('rear', 'rear'),\n ('left', 'rght'),\n ('rght', 'left'),\n ('frlf', 'frrg'),\n ('frrg', 'frlf'),\n ])\n pickle.dump((Xtr, Xte, ytr, yte, ntr, nte, le),\n gzip.open(pjoin(datadir, 'HIIT-wflip.pkl.gz'), 'wb+'))\n print(len(Xtr))\n\n if 'IDIAP' in todos:\n print(\"Augmenting IDIAP... (lol nope, just converting)\")\n # Since this one appears to already have been flipped horizontally, there's nothing to be done.\n data = load_tosato_idiap(pjoin(datadir, 'IHDPHeadPose'), 'or_label_full.mat')\n # Can't gzip due to this [Python bug](https://bugs.python.org/issue23306).\n pickle.dump(data, open(pjoin(datadir, 'IDIAP.pkl'), 'wb+'))\n print(len(data[0][0]))\n\n if 'CAVIAR' in todos:\n print(\"Augmenting CAVIAR... (all hope is lost, no augmentation is done)\")\n data = load_tosato_caviar(pjoin(datadir, 'CAVIARShoppingCenterFull'), 'or_label.mat')\n pickle.dump(data, gzip.open(pjoin(datadir, 'CAVIAR-c.pkl.gz'), 'wb+'))\n print(len(data[0][0]))\n data = load_tosato_caviar(pjoin(datadir, 'CAVIARShoppingCenterFullOccl'), 'or_label.mat')\n pickle.dump(data, gzip.open(pjoin(datadir, 'CAVIAR-o.pkl.gz'), 'wb+'))\n print(len(data[0][0]))\n\n\n if 'TownCentre' in todos:\n print(\"Augmenting TownCentre... \")\n bbtc_img, bbtc_a, bbtc_n = load_towncentre('data/TownCentreHeadImages')\n bbtc_img50 = scale_all(bbtc_img, (50, 50))\n\n Xtc = np.array(bbtc_img50 + flipall_images(bbtc_img50))\n ytc = np.array(bbtc_a + flipall_angles(bbtc_a))\n ntc = bbtc_n + bbtc_n\n\n # BHWC -> BCHW\n Xtc = np.rollaxis(Xtc, 3, 1)\n\n pickle.dump((Xtc, ytc, ntc),\n gzip.open(pjoin(datadir, 'TownCentre.pkl.gz'), 'wb+'))\n","repo_name":"lucasb-eyer/BiternionNet","sub_path":"prepare_data.py","file_name":"prepare_data.py","file_ext":"py","file_size_in_byte":9698,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"42"} +{"seq_id":"4128416646","text":"\"\"\" https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/ \"\"\"\n\nfrom math import factorial\nfrom functools import cache\n\n# Approach 1: Using permutations and combinations\ndef count_orders(n: int) -> int:\n M = 10 ** 9 + 7\n n_fact = factorial(n) % M\n odd_product = 1\n for num in range(1, 2 * n, 2):\n odd_product = (odd_product * num) % M\n return (n_fact * odd_product) % M\n\n\n# Approach 2: Using dynamic programming\ndef count_orders_dp(n: int) -> int:\n M = 10 ** 9 + 7\n\n @cache\n def total_ways(unpicked: int, undelivered: int) -> int:\n if unpicked < 0 or undelivered < 0 or undelivered < unpicked:\n return 0\n if unpicked == 0 and undelivered == 0:\n return 1\n ways_to_pick = unpicked * total_ways(unpicked - 1, undelivered)\n ways_to_deliver = (undelivered - unpicked) * total_ways(\n unpicked, undelivered - 1\n )\n return (ways_to_pick % M + ways_to_deliver % M) % M\n\n return total_ways(n, n)\n","repo_name":"pankaj1707k/data-structs-algo","sub_path":"DynamicProgramming/count_all_valid_pickup_and_delivery_options.py","file_name":"count_all_valid_pickup_and_delivery_options.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"2432893545","text":"class Solution:\r\n def numDecodings(self, s: str) -> int:\r\n d = {len(s):1}\r\n\r\n for i in range(len(s)-1, -1, -1):\r\n if(s[i] == \"0\"):\r\n d[i] = 0\r\n else:\r\n d[i] += d[i+1]\r\n \r\n if(( i < len(s)-1 ) and (s[i] == \"1\" or (s[i] == \"2\" and s[i+1] in \"0123456\"))):\r\n d[i] += d[i+2]\r\n \r\n return d[0]","repo_name":"leej1230/leetcode","sub_path":"DecodeWays.py","file_name":"DecodeWays.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"6810392379","text":"from collections.abc import Mapping\nfrom dataclasses import dataclass\nfrom enum import Enum\nfrom functools import partial\nfrom pathlib import Path\nfrom typing import Optional, TypeAlias, Union\nfrom typing_extensions import Self\n\nfrom conduit import metrics as cdtm\nfrom conduit.models.utils import prefix_keys\nimport ethicml as em\nimport ethicml.metrics as emm\nfrom loguru import logger\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom torch import Tensor\nimport wandb\n\nfrom src.data import EvalTuple\nfrom src.utils import to_numpy\n\n__all__ = [\n \"MetricDict\",\n \"SummaryMetric\",\n \"compute_metrics\",\n \"print_metrics\",\n \"write_results_to_csv\",\n]\n\n\n@dataclass\nclass EmEvalPair:\n pred: em.Prediction\n actual: em.LabelTuple\n\n @classmethod\n def from_et(cls, et: EvalTuple, *, pred_s: bool = False) -> Self:\n return cls.from_tensors(y_pred=et.y_pred, y_true=et.y_true, s=et.s, pred_s=pred_s)\n\n @classmethod\n def from_tensors(\n cls, y_pred: Tensor, *, y_true: Tensor, s: Tensor, pred_s: bool = False\n ) -> Self:\n if len(y_pred) != len(y_true) != len(s):\n raise ValueError(\"'y_pred', 'y_true', and 's' must match in size at dimension 0.\")\n pred = em.Prediction(hard=pd.Series(to_numpy(y_pred.flatten())))\n sens_pd = pd.Series(to_numpy(tensor=s.flatten()).astype(np.float32), name=\"subgroup\")\n labels_pd = pd.Series(to_numpy(y_true.flatten()), name=\"labels\")\n actual = em.LabelTuple.from_df(s=sens_pd, y=sens_pd if pred_s else labels_pd)\n return cls(pred=pred, actual=actual)\n\n\nMetricDict: TypeAlias = dict[str, float]\n\n\nclass SummaryMetric(Enum):\n ACC = \"Accuracy\"\n ROB_ACC = \"Robust_Accuracy\"\n BAL_ACC = \"Balanced_Accuracy\"\n ROB_GAP = \"Robust_Gap\"\n TPR = \"TPR\"\n TNR = \"TNR\"\n ROB_TPR = \"Robust_TPR\"\n ROB_TNR = \"Robust_TNR\"\n ROB_TPR_GAP = \"Robust_TPR_Gap\"\n ROB_TNR_GAP = \"Robust_TNR_Gap\"\n RENYI = \"Renyi preds and s\"\n ROB_OVR_TPR = \"Robust_OvR_TPR\"\n\n\nrobust_tpr_gap = cdtm.subclasswise_metric(\n comparator=partial(cdtm.conditional_equal, y_true_cond=1), aggregator=cdtm.Aggregator.MAX_DIFF\n)\nrobust_tnr_gap = cdtm.subclasswise_metric(\n comparator=partial(cdtm.conditional_equal, y_true_cond=0), aggregator=cdtm.Aggregator.MAX_DIFF\n)\n\n\n@torch.no_grad()\ndef compute_metrics(\n pair: EmEvalPair,\n *,\n step: Optional[int] = None,\n exp_name: Optional[str] = None,\n save_summary: bool = False,\n use_wandb: bool = False,\n additional_entries: Optional[Mapping[str, float]] = None,\n prefix: Optional[str] = None,\n verbose: bool = True,\n) -> dict[str, float]:\n \"\"\"Compute accuracy and fairness metrics and log them.\n\n :param pair: predictions and labels in a format that is compatible with EthicML\n :param step: step of training (needed for logging to W&B)\n :param exp_name: name of the experiment\n :param save_summary: if True, a summary will be saved to wandb\n :param use_wandb: whether to use wandb at all\n :param additional_entries: entries that should go with in the summary\n :param prefix:\n :param verbose:\n\n :returns: dictionary with the computed metrics\n \"\"\"\n logger.info(\"Computing classification metrics\")\n predictions = pair.pred\n actual = pair.actual\n # Convert to tensor for compatibility with conduit-derived metrics.\n y_pred_t = torch.as_tensor(torch.as_tensor(predictions.hard, dtype=torch.long))\n y_true_t = torch.as_tensor(torch.as_tensor(actual.y, dtype=torch.long))\n s_t = torch.as_tensor(torch.as_tensor(actual.s, dtype=torch.long))\n\n # compute EthicML metrics\n predictions._info = {} # type: ignore\n metrics = emm.run_metrics(\n predictions=predictions,\n actual=actual,\n metrics=[emm.Accuracy(), emm.TPR(), emm.TNR(), emm.RenyiCorrelation()],\n per_sens_metrics=[emm.Accuracy(), emm.ProbPos(), emm.TPR(), emm.TNR()],\n aggregation=(\n emm.PerSens.DIFFS_RATIOS\n if torch.unique(y_true_t).shape[0] * torch.unique(s_t).shape[0] < 10\n else set()\n ),\n )\n\n # compute conduit metrics\n cdt_metrics = {\n SummaryMetric.ROB_ACC.value: cdtm.robust_accuracy,\n SummaryMetric.BAL_ACC.value: cdtm.subclass_balanced_accuracy,\n SummaryMetric.ROB_GAP.value: cdtm.robust_gap,\n SummaryMetric.ROB_TPR_GAP.value: robust_tpr_gap,\n SummaryMetric.ROB_TNR_GAP.value: robust_tnr_gap,\n SummaryMetric.ROB_TPR.value: cdtm.robust_tpr,\n SummaryMetric.ROB_TNR.value: cdtm.robust_tnr,\n SummaryMetric.ROB_OVR_TPR.value: cdtm.robust_ovr_tpr,\n }\n for name, fn in cdt_metrics.items():\n metrics[name] = fn(y_pred=y_pred_t, y_true=y_true_t, s=s_t).item()\n # replace the slash; it's causing problems\n metrics = {k.replace(\"/\", \"÷\"): v for k, v in metrics.items()}\n if exp_name:\n metrics = prefix_keys(metrics, prefix=exp_name, sep=\"/\")\n if prefix is not None:\n metrics = prefix_keys(metrics, prefix=prefix, sep=\"/\")\n\n if use_wandb:\n wandb.log(metrics, step=step)\n\n if save_summary:\n external = additional_entries or {}\n\n for metric_name, value in metrics.items():\n wandb.run.summary[metric_name] = value # type: ignore\n for metric_name, value in external.items():\n wandb.run.summary[metric_name] = value # type: ignore\n\n if verbose:\n logger.info(f\"Results for {exp_name or ''}:\")\n print_metrics(metrics)\n return metrics\n\n\ndef print_metrics(metrics: Mapping[str, Union[int, float, str]]) -> None:\n \"\"\"Print metrics such that they don't clutter everything too much.\"\"\"\n for key, value in metrics.items():\n logger.info(f\" {key}: {value:.3g}\")\n logger.info(\"---\")\n\n\ndef write_results_to_csv(\n results: Mapping[str, Union[int, float, str]], csv_dir: Path, csv_file: str\n):\n to_log = {}\n # to_log.update(flatten_dict(as_pretty_dict(cfg)))\n to_log.update(results)\n results_df = pd.DataFrame(to_log, index=[0])\n\n csv_dir.mkdir(exist_ok=True, parents=True)\n\n results_path = csv_dir / csv_file\n if results_path.exists():\n # load previous results and append new results\n previous_results = pd.read_csv(results_path)\n results_df = pd.concat(\n [previous_results, results_df], sort=False, ignore_index=True, axis=\"index\"\n )\n results_df.reset_index(drop=True).to_csv(results_path, index=False)\n logger.info(f\"Results have been written to {results_path.resolve()}\")\n","repo_name":"wearepal/support-matching","sub_path":"src/evaluation/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":6518,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"13163717683","text":"import os\nimport re\nimport sys\nimport getopt\nimport logging\nimport datetime\nimport random\nimport socks\nimport signal\nimport json\nfrom logging.handlers import RotatingFileHandler\nfrom utils.confparser import ConfParser\nfrom utils.utils import TimestampNow, VerifyPath\nimport sqlite3\nimport hues\nimport requests\nimport socket\nfrom ipwhois import IPWhois\nimport warnings\nimport time\nimport safebrowsing\nimport apprise\n\ndef create_connection(db_file):\n \"\"\" create a database connection to the SQLite database\n specified by the db_file\n\n :param db_file: database file\n :return: Connection object or None\n \"\"\"\n\n try:\n conn = sqlite3.connect(db_file, isolation_level=None)\n # debug SQL\n # conn.set_trace_callback(print)\n return conn\n except sqlite3.Error as e:\n print(e)\n return False\n\n\ndef args_parse():\n \"\"\"\n Tools options\n \"\"\"\n global ConfFile\n global fqdn_dirs\n fqdn_dirs = False\n\n if not len(sys.argv[1:]):\n usage()\n try:\n opts, args = getopt.getopt(sys.argv[1:], \"hfc:\", [\"help\", \"fqdn-dirs\", \"conf=\"])\n except getopt.GetoptError as err:\n logging.error(\" Option Error. Exiting...\" + str(err))\n usage()\n sys.exit(2)\n\n for o, a in opts:\n if o in (\"-h\", \"--help\"):\n usage()\n elif o in (\"-c\", \"--config\"):\n if os.path.isfile(a):\n ConfFile = a\n else:\n logging.error(\" Can't find configuration file. Exiting...\")\n sys.exit(1)\n elif o in (\"-f\", \"--fqdn-dirs\"):\n fqdn_dirs = True\n else:\n assert False, \"Unhandled Option\"\n return\n\n\ndef usage():\n \"\"\"\n CLI usage printing\n \"\"\"\n usage = \"\"\"\n -h --help Print this help\n -c --config Configuration file to use\n -f --fqdn-dirs Store JSON files in sub-directories based on the hostname\n \"\"\"\n print (usage)\n sys.exit(0)\n\n\ndef generate_alert_dir(path):\n \"\"\"\n Generate the hashed directory path based on current date\n \"\"\"\n # %m -> month\n # %d -> day\n # %Y -> year\n # %H -> hour\n # %M -> minute\n t_hour = time.strftime(\"%H\")\n t_minute = time.strftime(\"%M\")\n t_day = time.strftime(\"%d\")\n t_month = time.strftime(\"%m\")\n t_year = time.strftime(\"%Y\")\n path = path.replace('%H', t_hour)\n path = path.replace('%M', t_minute)\n path = path.replace('%d', t_day)\n path = path.replace('%m', t_month)\n path = path.replace('%Y', t_year)\n return path\n\n\ndef ConfAnalysis(ConfFile):\n \"\"\"\n configuration file analysis. Load global variables with parameters found\n in configuration file.\n\n :param confFile: the configuration file\n \"\"\"\n global CONF\n global DBFile\n global TABLEname\n global LogFile\n global Proxy\n global UA\n global UAFILE\n global Alerts_dir\n global Alert_Monitor_timelapse\n global Notification_Destination\n global Safe_Browsing_API_Key\n\n try:\n CONF = ConfParser(ConfFile)\n DBFile = CONF.DBFile\n TABLEname = CONF.TABLEname\n LogFile = CONF.LogFile\n Proxy = CONF.Proxy\n UA = CONF.http_UA\n Alerts_dir = generate_alert_dir(CONF.Alerts_dir)\n Alert_Monitor_timelapse = CONF.Alert_Monitor_timelapse\n Notification_Destination = CONF.Notification_Destination\n UAFILE = CONF.UAfile\n Safe_Browsing_API_Key = CONF.Safe_Browsing_API_Key\n\n except Exception as err:\n err = sys.exc_info()\n logging.error(\" ConfParser Error: \" + str(err))\n\n\ndef get_random_UserAgent_header(lines):\n \"\"\"\n build a string containing a user-agent header, randomly\n choosen inside a given list\n\n :param lines: the file containing the user-agent possible values.\n One value per line.\n :return: the header with user-agent value set.\n \"\"\"\n ua = random.choice(lines)\n headers = {'user-agent': ua}\n return headers\n\n\ndef get_requests(hostname, lines, conn, Proxy):\n \"\"\"\n build a requests object for a hostname\n\n :param hostname:\n :param lines: content of the file containing user-agents strings\n :param conn: connection to the database\n :param Proxy: connection through proxy\n\n :return: the answer to the request content or None\n \"\"\"\n\n # if the certificate is a wildcard, display it but no testing.\n # and return.\n if '*' in hostname:\n hues.warn('wildcard certificate: no request for ' + hostname)\n return None\n\n url = 'https://' + hostname\n headers = get_random_UserAgent_header(lines)\n\n # set proxy\n if Proxy:\n proxy = {\"https\": Proxy}\n else:\n proxy = \"\"\n\n try:\n r = requests.get(url, headers=headers, proxies=proxy, timeout=5)\n return r\n except requests.exceptions.SSLError as errs:\n # SSL error\n hues.error(\" {} - SSL error\".format(url))\n return None\n except requests.exceptions.ConnectionError as errc:\n # other connection error\n hues.error(\" {} - Connection error\".format(url))\n return None\n except requests.exceptions.RequestException as e:\n # A serious problem happened\n hues.error(\" {} Error: {}\".format(url, e))\n return None\n except KeyboardInterrupt:\n print(\"get_requests() - Interrupt received, stopping ...\")\n print(\"start - committing, closing DB\")\n conn.commit\n conn.close\n print(\"ending - committing, closing DB\")\n sys.exit(0)\n except Exception as ex:\n hues.error(\"get_requests() - any other kind of error: {}\".format(ex))\n return None\n\n\ndef get_webpage_title(request):\n \"\"\"\n Get the website page title\n\n :param resquest: request object\n\n :return: webpage title or \"\"\n \"\"\"\n try:\n page = request.text.strip()\n tit = re.search('(.*?)', page, re.IGNORECASE)\n if tit is not None:\n title = tit.group(1)\n else:\n title = \"\"\n return title\n except Exception as e:\n print(\"error in get_webpage_title(): \" + str(e))\n return \"\"\n\n\ndef get_ASN_Infos(ipaddr):\n \"\"\"\n Get Autonomous System Number informations linked to an ip address\n\n :param ipaddr: ip address of the website linked to the certificate common name\n\n :return: list of ASN infos: asn, asn_cidr, asn_country_code, asn_description, asn_abuse_email or the same with empty values\n \"\"\"\n try:\n warnings.filterwarnings(\"ignore\")\n obj = IPWhois(ipaddr)\n results = obj.lookup_rdap(depth=1)\n\n asn = results['asn']\n asn_cidr = results['asn_cidr']\n asn_country_code = results['asn_country_code']\n asn_description = results['asn_description']\n\n # parsing of all the entities members of the ASN record.\n # -> when finding an entity with 'abuse' role, print the email present\n # in the contact object.\n try:\n for entity in results['objects'].values():\n if 'abuse' in entity['roles']:\n asn_abuse_email = entity['contact']['email'][0]['value']\n break\n except Exception as e:\n asn_abuse_email = \"\"\n\n return asn, asn_cidr, asn_country_code, asn_description, asn_abuse_email\n\n except Exception as e:\n asn, asn_cidr, asn_country_code, asn_description, asn_abuse_email = \"\", \"\", \"\", \"\", \"\"\n return asn, asn_cidr, asn_country_code, asn_description, asn_abuse_email\n\n\ndef scan_hostname(hostname, SerialNumber, lines, Proxy, conn, site_infos):\n \"\"\"\n try scan a hostname and get informations back\n (HTTP code, page title, IP address, ASN, abuse email etc).\n\n :param hostname: the hostname present in the certificate\n :param SerialNumber: the serial number of the certificate\n :param lines: list of user-agents strings\n :param Proxy: proxy settings\n :param conn: database connection\n :param site_infos: informations extracted on the net for the given hostname\n\n :return: True if everything went fine, False if any problem has been encountered\n \"\"\"\n\n title = \"\"\n try:\n r = get_requests(hostname, lines, conn, Proxy)\n if r is not None:\n hues.success('HTTP ' + str(r.status_code) + ' - ' + hostname)\n\n # retrieve the title of the homepage\n title = get_webpage_title(r)\n\n # retrieve ASN informations\n ipaddr = socket.gethostbyname(hostname)\n asn, asn_cidr, asn_country_code, asn_description, asn_abuse_email = get_ASN_Infos(\n ipaddr)\n\n # retrieve Google Safe Browsing Lookup API status for this hostname\n if Safe_Browsing_API_Key is not '':\n sb = safebrowsing.LookupAPI(Safe_Browsing_API_Key)\n safe_browsing_status = sb.threat_matches_find(hostname)\n else:\n safe_browsing_status = \"No API key in config file\"\n\n # build the content of the alert file using certificate / webpage / ASN informations\n site_infos = {\n 'hostname': hostname,\n 'http_code': r.status_code,\n 'cert_serial_number': SerialNumber,\n 'webpage_title': title,\n 'ip_addr': ipaddr,\n 'asn': asn,\n 'asn_cidr': asn_cidr,\n 'asn_country_code': asn_country_code,\n 'asn_description': asn_description,\n 'asn_abuse_email': asn_abuse_email,\n 'safe_browsing_status': safe_browsing_status\n }\n return site_infos\n else:\n return {}\n\n except KeyboardInterrupt:\n print(\"scan_hostname() - Interrupt received, stopping ...\")\n print(\"start - committing, closing DB\")\n conn.commit\n conn.close\n print(\"ending - committing, closing DB\")\n sys.exit(0)\n\n except Exception as ex:\n hues.error(\"scan_hostname() - any other kind of error: {}\".format(ex))\n return {}\n\n\ndef parse_and_scan_all_hostnames(TABLEname, Proxy, conn):\n \"\"\"\n Parse and scan all hostnames present in DB and having StillInvestig set to null or \"\"\n\n :param TABLEname: the table name storing certificate informations in database\n :param Proxy: proxy value\n :param conn: db connection\n\n :return: True if everything went fine, False if something went wrong\n \"\"\"\n try:\n # Query rows that have not StillInvestig column already set\n # get Domain, Fingerprint and FirstSeen columns\n cur = conn.cursor()\n cur.execute(\"SELECT Domain,Fingerprint,FirstSeen FROM \" + TABLEname +\n \" WHERE StillInvestig IS NULL or StillInvestig = ''\")\n rows = cur.fetchall()\n\n # creating Alerts_dir if don't exist\n try:\n os.makedirs(Alerts_dir, mode=0o777, exist_ok=True)\n except FileExistsError:\n pass\n except:\n err = sys.exc_info()\n logging.error(\" Can't create Alerts_dir: \" + str(err))\n\n # read User Agent file\n try:\n lines = open(UAFILE).read().splitlines()\n except:\n lines = UA\n\n # load apprise instance with config file parameters if notifications are activated in the config file\n if Notification_Destination is not '':\n apobj = apprise.Apprise()\n apobj.add(Notification_Destination)\n\n # run scan on each hostname\n for row in rows:\n hostname = row[0]\n SerialNumber = row[1]\n\n site_infos = {}\n\n site_infos = scan_hostname(hostname, SerialNumber, lines, Proxy, conn, site_infos)\n\n # Is time check limit reached?\n now = datetime.datetime.strptime(str(datetime.datetime.utcnow().replace(microsecond=0).isoformat()), \"%Y-%m-%dT%H:%M:%S\")\n FirstSeen = datetime.datetime.strptime(row[2], \"%Y-%m-%dT%H:%M:%S\")\n time_delta = (now - FirstSeen).days\n if time_delta < int(Alert_Monitor_timelapse):\n if not site_infos:\n continue\n else:\n # if the site is UP, we log the timestamp in the database in order to not reprocess it\n cur.execute(\"UPDATE \" + TABLEname + \" SET StillInvestig= ? WHERE Domain = ? AND Fingerprint = ? ;\",\n (format(datetime.datetime.utcnow().replace(microsecond=0).isoformat()), hostname, SerialNumber))\n conn.commit\n if fqdn_dirs:\n # Split hostname into a reverse list (TLD first)\n words = hostname.split(\".\")[::-1]\n FQDN_dir = Alerts_dir\n for w in words:\n FQDN_dir = FQDN_dir + \"/\" + w\n try:\n os.makedirs(FQDN_dir, mode=0o777, exist_ok=True)\n except FileExistsError:\n pass\n except:\n err = sys.exc_info()\n logging.error(\" Can't create Alerts_dir: \" + str(err))\n print(\"Creating \" + FQDN_dir + \"/\" + hostname + \".json : \" + str(site_infos))\n f = open(FQDN_dir + \"/\" + hostname + \".json\", \"w\")\n else:\n print(\"Creating \" + Alerts_dir + \"/\" + hostname + \".json : \" + str(site_infos))\n # log the hostname under the form of a file under the /alerts subdirectory\n # + fill the file with informations like ASN/abuse email/IP/web page title etc\n # next task: the SOC/Cert has to investigate this host.\n f = open(Alerts_dir + \"/\" + hostname + \".json\", \"w\")\n json.dump(site_infos, f, indent=4)\n f.close()\n if Notification_Destination is not '':\n body_site_infos = str(site_infos).replace(', \\'', chr(10) + '\\'')\n body_site_infos = body_site_infos.replace('{', '')\n body_site_infos = body_site_infos.replace('}', '')\n apobj.notify(title=\"[CertStreamMonitor] Alert: \" + hostname, body=body_site_infos,)\n\n # Time's up, stop checking entry\n else:\n hues.warn(\" {} - end of monitoring reached ({} days)\".format(hostname, Alert_Monitor_timelapse))\n cur.execute(\"UPDATE \" + TABLEname + \" SET StillInvestig= '{}{}' WHERE Domain = '{}' AND Fingerprint = '{}' ;\".format(\"Stop checking on \", now.date(), hostname, SerialNumber))\n conn.commit\n\n return True\n\n except KeyboardInterrupt:\n print(\"Interrupt received, stopping ...\")\n print(\"start - committing, closing DB\")\n conn.commit\n conn.close\n print(\"ending - committing, closing DB\")\n return False\n\n except Exception as e:\n hues.error(\"parse_and_scan_all_hostnames function error: {}\".format(e))\n return False\n\n finally:\n conn.commit\n conn.close\n\n\ndef main():\n ConfAnalysis(ConfFile)\n\n # create a database connection\n conn = create_connection(DBFile)\n\n with conn:\n print(\"Test all domains in DB for Internet Presence:\")\n print(\"*********************************************\")\n parse_and_scan_all_hostnames(TABLEname, Proxy, conn)\n\n\nif __name__ == '__main__':\n args_parse()\n main()\n","repo_name":"AssuranceMaladieSec/CertStreamMonitor","sub_path":"scanhost.py","file_name":"scanhost.py","file_ext":"py","file_size_in_byte":15648,"program_lang":"python","lang":"en","doc_type":"code","stars":129,"dataset":"github-code","pt":"42"} +{"seq_id":"41819822432","text":"import numpy as np\nimport os\nimport torch\nfrom torch.utils.data import DataLoader\n\nfrom LSIM.dataset_distance import *\nfrom LSIM.distance_model import *\nfrom LSIM.distance_model_non_siamese import *\nfrom LSIM.loss import *\nfrom LSIM.trainer import *\n\n\n# SETUP FOR DATA AND MODEL\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\nuseGPU = True\n\ntrainSet = DatasetDistance(\"Training\", dataDirs=[\"Data/Smoke\", \"Data/BurgersEq\", \"Data/AdvDiff\", \"Data/Liquid\"],\n exclude=[\"plume1.\", \"plume2.\", \"plume11.\", \"plume12.\",\n \"burgersEq1.\", \"burgersEq2.\", \"burgersEq3.\", \"burgersEq4.\",\n \"burgersEq5.\", \"burgersEq6.\", \"burgersEq7.\", \"burgersEq8.\",\n \"burgersEq9.\", \"burgersEq10.\", \"burgersEq11.\", \"burgersEq12.\",\n \"advDiff1.\", \"advDiff2.\", \"advDiff3.\", \"advDiff4.\", \"advDiff5.\",\n \"advDiff6.\", \"advDiff7.\", \"advDiff8.\", \"advDiff9.\", \"advDiff10.\",\n \"drop1.\", \"drop2.\", \"drop3.\", \"drop21.\", \"drop22.\", \"drop23.\"],)\nvalSet = DatasetDistance(\"Validation\", dataDirs=[\"Data/Smoke\", \"Data/BurgersEq\", \"Data/AdvDiff\", \"Data/Liquid\"],\n include=[\"plume1.\", \"plume2.\", \"plume11.\", \"plume12.\",\n \"burgersEq1.\", \"burgersEq2.\", \"burgersEq3.\", \"burgersEq4.\",\n \"burgersEq5.\", \"burgersEq6.\", \"burgersEq7.\", \"burgersEq8.\",\n \"burgersEq9.\", \"burgersEq10.\", \"burgersEq11.\", \"burgersEq12.\",\n \"advDiff1.\", \"advDiff2.\", \"advDiff3.\", \"advDiff4.\", \"advDiff5.\",\n \"advDiff6.\", \"advDiff7.\", \"advDiff8.\", \"advDiff9.\", \"advDiff10.\",\n \"drop1.\", \"drop2.\", \"drop3.\", \"drop21.\", \"drop22.\", \"drop23.\"],)\n\ntransTrain = TransformsTrain(224, normMin=0, normMax=255)\ntransVal = TransformsInference(224, 0, normMin=0, normMax=255)\ntrainSet.setDataTransform(transTrain)\nvalSet.setDataTransform(transVal)\n\ntrainLoader = DataLoader(trainSet, batch_size=1, shuffle=True, num_workers=4)\nvalLoader = DataLoader(valSet, batch_size=1, shuffle=False, num_workers=4)\n\nmodel = DistanceModel(baseType=\"lsim\", initBase=\"pretrained\", initLin=0.1, featureDistance=\"L2\",\n frozenLayers=[], normMode=\"normDist\", useNormUpdate=False, isTrain=True, useGPU=useGPU)\nmodel.printNumParams()\n\ncriterion = CorrelationLoss(weightMSE=0.3, weightCorr=0.7, weightCrossCorr=0.0)\noptimizer = torch.optim.Adam(model.parameters(), lr=0.00001, weight_decay=0.0)\ntrainer = Trainer(model, trainLoader, optimizer, criterion, 800, False)\nvalidator = Validator(model, valLoader, criterion)\n\n\n# ACTUAL TRAINING\nprint('Starting Training')\n\nif model.normMode != \"normUnit\":\n trainer.normCalibration(1, stopEarly=0)\n\nfor epoch in range(0, 40):\n if epoch % 5 == 1:\n validator.validationStep()\n\n trainer.trainingStep(epoch+1)\n\n model.save(\"Models/TrainedLSiM_tmp.pth\", override=True, noPrint=True)\n\nprint('Finished Training')\nmodel.save(\"Models/TrainedLSiM.pth\")","repo_name":"tum-pbs/LSIM","sub_path":"Source/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":3164,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"42"} +{"seq_id":"30178411530","text":"from __future__ import absolute_import, unicode_literals\n\nfrom .base import *\nimport os\n\nenv = os.environ.copy()\nSECRET_KEY = env['SECRET_KEY']\nALLOWED_HOSTS = ['*']\nDEBUG = False\n\n# Parse database configuration from $DATABASE_URL\nimport dj_database_url\nDATABASES['default'] = dj_database_url.config()\n \n# Honor the 'X-Forwarded-Proto' header for request.is_secure()\nSECURE_SSL_REDIRECT = True\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\nEMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\nEMAIL_HOST = 'smtp.sendgrid.net'\nEMAIL_HOST_USER = env['SENDGRID_USERNAME']\nEMAIL_HOST_PASSWORD = env['SENDGRID_PASSWORD']\nEMAIL_PORT = 587\nEMAIL_USE_TLS = True\n\nCOMPRESS_OFFLINE = True\nCOMPRESS_CSS_FILTERS = [\n 'compressor.filters.css_default.CssAbsoluteFilter',\n 'compressor.filters.cssmin.CSSMinFilter',\n]\nCOMPRESS_CSS_HASHING_METHOD = 'content'\n\nRECAPTCHA_PUBLIC_KEY = os.environ.get(\"GOOGLE_RECAPTCHA_SITE_KEY\", \"\")\nRECAPTCHA_PRIVATE_KEY = os.environ.get(\"GOOGLE_RECAPTCHA_SECRET_KEY\", \"\")\nNOCAPTCHA = True\nRECAPTCHA_USE_SSL = True\n\n#set S3 as the place to store your files.\nDEFAULT_FILE_STORAGE = \"storages.backends.s3boto3.S3Boto3Storage\"\nSTATICFILES_STORAGE = \"storages.backends.s3boto3.S3Boto3Storage\"\nAWS_ACCESS_KEY_ID = os.environ.get(\"AWS_ACCESS_KEY_ID\", \"\")\nAWS_SECRET_ACCESS_KEY = os.environ.get(\"AWS_SECRET_ACCESS_KEY\", \"\")\nAWS_STORAGE_BUCKET_NAME = os.environ.get(\"S3_BUCKET_NAME\", \"\")\nAWS_QUERYSTRING_AUTH = False #This will make sure that the file URL does not have unnecessary parameters like your access key.\nAWS_S3_CUSTOM_DOMAIN = AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com'\n\n#static media settings\nSTATIC_URL = 'https://' + AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/'\nMEDIA_URL = STATIC_URL + 'media/'\nSTATICFILES_DIRS = ( os.path.join(BASE_DIR, \"static\"), )\nSTATIC_ROOT = 'staticfiles'\nADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'\nSTATICFILES_FINDERS = (\n'django.contrib.staticfiles.finders.FileSystemFinder',\n'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n)\n\ntry:\n from .local import *\nexcept ImportError:\n pass","repo_name":"lifeunion/localchurches","sub_path":"lampstands/settings/production.py","file_name":"production.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"40707211412","text":"import unbeatable_ai as ai\nimport computer as comp\nimport two_player as tp\n\n\nclass Main:\n\n def get_user_game(self):\n user = input(\"Would you like to play solo against the Unbeatable AI, or a two player game? \\n\"\n \"Please Enter 1 or 2: \")\n\n while True:\n if user == '1':\n return True\n elif user == '2':\n return False\n\n\nif __name__ == \"__main__\":\n start_game = Main()\n AI_game = start_game.get_user_game()\n\n if AI_game:\n game = ai.AI()\n X_turn = game.get_user_turn()\n game_instance = comp.Computer(None, X_turn)\n game_instance.play_game()\n\n else:\n two_player_game = tp.TwoPlayer()\n two_player_game.play_game()\n","repo_name":"Merlness/TicTacToe","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"19270085016","text":"#a two-digit number that becomes 7 times smaller after the first digit is deleted\n#naive way\nfor i in range( 1,100):\n x = i%10\n if(x*7==i):\n print(i,\" \",x)\n # a number that becomes 57 times smaller \nfor i in range(1000,10000):\n n=i%1000\n if(n*57==i):\n print(i,\" \",n)\n\n#effecient way \n# for the two-digit number problem\nfor i in range(10, 100):\n x, y = divmod(i, 10)\n if x*7 == 10*y+x:\n print(i)\n \n# for the four-digit number problem\nfor i in range(1000, 10000):\n x, y = divmod(i, 1000)\n if x*57 == 1000*y+x:\n print(i)\n \n","repo_name":"ibrahimrifatcse/Discrete-Mathematics-for-Computer-Science","sub_path":"Mathematical thinking in computer science/KnowYourRights.py","file_name":"KnowYourRights.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"3656967282","text":"import os\nimport requests\nfrom lxml import etree\nimport pymysql\n#连接数据库,数据库操作,s数据库用的是mysql\ndb=pymysql.Connect(host='localhost',port=3306,user='root',\n passwd='123456',db='tushu', charset='utf8'\n )\ncursor=db.cursor()\nurls=['https://bj.lianjia.com/ershoufang/pg{}/'.format(str(i)) for i in range(2,4)]\nroot='D://test6//'\n#建立文件夹\ntry:\n if not os.path.exists(root):\n os.mkdir(root)\n print(\"文件夹创建成功\")\n else:\n print(\"文件夹已存在\")\nexcept:\n print(\"文件夹不能存在\")\n#获取网页\ndef get_html(url):\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'\n }\n try:\n html=requests.get(url,headers=headers)\n html.encoding=html.apparent_encoding\n if html.status_code==200:\n print(\"获取源码成功\")\n except Exception as f:\n print(\"获取失败\")\n return html.text\n#处理获取到的网页\ndef parser(html):\n html=etree.HTML(html)\n titles=html.xpath(\"//div[@class='address']/div[@class='houseInfo']/a/text()\")\n daxiao=html.xpath(\"//div[@class='address']/div[@class='houseInfo']/text()[1]\")\n price=html.xpath(\"//div[@class='priceInfo']/div[@class='totalPrice']/span/text()\")\n images=html.xpath(\"//a[@class='noresultRecommend img ']/img[@class='lj-lazy']/@src\")\n age=html.xpath(\"//div[@class='info clear']/div[@class='flood']/div[@class='positionInfo']/text()[2]\")\n print(age)\n #插入数据库\n for i in range(0,len(age)):\n cursor.execute('insert into rooms(`title`,`daxiao`,`price`,`age`,`image`) value(\"{}\",\"{}\",\"{}\",\"{}\",\"{}\") '.\n format(titles[i],daxiao[i],price[i],age[i],images[i]))\n db.commit()\n print(\"正在存储%s:\"%titles[i])\nif __name__=='__main__':\n for url in urls:\n html = get_html(url)\n parser(html)\n\n\n\n\n\n","repo_name":"HuHengKai/pa-chong","sub_path":"链家.py","file_name":"链家.py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"118934023","text":"import numpy as np\nfrom scipy.stats import poisson\n\n\ndef xcorr_coef(ts1,ts2,tson,tsoff,binwidth,reject_at):\n\n duration=tsoff-tson\n trainc=np.sort(np.concatenate((ts1,ts2)))\n t1,t2=[ts1,ts2]\n if any(np.diff(trainc)tson)&(x<(tson+duration))]-tson for x in [t1,t2]]\n b=[np.histogram(x,hbin)[0] for x in [t1,t2]]\n \n # correlate\n R=np.correlate(b[0],b[1],'valid')\n \n # statistics\n N = len(hbin)\n N_A = sum(b[0])\n N_B = sum(b[1])\n E = N_A*N_B/N\n Rc = (R-E)*((N_A*N_B)**-0.5);\n sig_cutoff = 4*(N**-0.5)\n \n return (Rc,sig_cutoff)\n\n\n\n\ndef burst_ps(spiketrain,interval):\n\n crit=10\n ls=np.array(spiketrain)\n r=len(ls)/interval #expected sfr\n \n i=0\n j=i+2\n burst=[]\n while (icrit)&(jexpected)&(P!=np.inf):\n burst.append([P,actual,ls[i],ls[j]])\n j+=1\n else:\n i+=1\n j=i+2\n if actual>100:\n print(P,i,j,len(ls))\n burst=np.array(burst)\n burst2=[]\n if np.size(burst,axis=0)>1:\n u,ix,c = np.unique(burst[:,2],return_counts=True,return_inverse=True)\n for i in range(len(u)):\n b=burst[ix==i,:]\n if c[i]>1:\n burst2.append(b[np.argmax(b[:,0]),:])\n else:\n burst2.append(b[0])\n burst2=np.array(burst2)\n burst3=[]\n if np.size(burst2,axis=0)>1:\n u,ix,c = np.unique(burst2[:,3],return_counts=True,return_inverse=True)\n for i in range(len(u)):\n b=burst2[ix==i,:]\n if c[i]>1:\n burst3.append(b[np.argmax(b[:,0]),:])\n else:\n burst3.append(b[0])\n burst3=np.array(burst3)\n \n return burst3","repo_name":"codethekitty/neurophys_util","sub_path":"synchrony.py","file_name":"synchrony.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"70744167166","text":"import logging\nfrom behave import given, when, then\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\n\n\n@given('navigate to \"{url}\"')\ndef navigate_to_url(context, url):\n logging.info(f\"navigating to url {url}\")\n\n browser = context.browser\n browser.get(url)\n # clear the \"before you continue to google\" popup if it shows itself\n browser.find_element(By.ID, \"L2AGLb\").click()\n\n\n@when('search for the text \"{search_text}\"')\ndef step_impl(context, search_text):\n logging.debug(f\"searching for {search_text}\")\n\n browser = context.browser\n text_area = browser.find_element(By.NAME, \"q\")\n text_area.send_keys(search_text)\n text_area.send_keys(Keys.RETURN)\n\n\n@then(\"search results are displayed\")\ndef validate_results(context):\n logging.debug(\"validating results\")\n\n browser = context.browser\n news_results = browser.find_element(By.XPATH, '//span[text()=\"Top stories\"]')\n assert news_results.text == \"Top stories\"\n","repo_name":"MalcolmPerfect/behave-test","sub_path":"features/steps/web_selenium_steps.py","file_name":"web_selenium_steps.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"70304787967","text":"import pandas as pd\nimport streamlit as st\nimport yfinance as yf\n\n\nst.write(\"\"\"\n# Simple Stock Price App\n\nShown are the closing prices of different stocks on my watchlist\n\n\"\"\")\n\ntikrSymbol = 'GOOGL'\n\ntikrData = yf.Ticker(tikrSymbol)\n\ntikrDf = tikrData.history(period='1d', start='2010-1-31', end='2021-2-12')\n\nst.write(\"\"\"\n### Closing Price\n\"\"\")\nst.line_chart(tikrDf.Close)\nst.line_chart(tikrDf.Volume)","repo_name":"baburajr/stock-price-app","sub_path":"stock.py","file_name":"stock.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"42859768360","text":"import copy\n\nfrom GCP_utils.utils import models_dir\nfrom envs.clevr_robot_env import LangGCPEnv\nfrom stable_baselines3 import LangPPO, LangGCPPPO\nfrom stable_baselines3.common.monitor import Monitor\nfrom stable_baselines3.common.vec_env.subproc_vec_env import SubprocVecEnv\nfrom stable_baselines3.common.vec_env.dummy_vec_env import DummyVecEnv\nfrom stable_baselines3.common.vec_env.vec_normalize import VecNormalize\n\n\ndef get_args():\n import argparse\n parser = argparse.ArgumentParser(description='Algorithm arguments')\n\n # utils\n parser.add_argument('--id', type=str, default='langGCP')\n \n # parser.add_argument('--lm_type', type=str, default='policy')\n parser.add_argument('--lm_type', type=str, default='policy_cont')\n # parser.add_argument('--lm_type', type=str, default='bert_binary')\n # parser.add_argument('--lm_type', type=str, default='baseline')\n \n # parser.add_argument('--policy_epoch', type=int, default=19)\n parser.add_argument('--policy_epoch', type=int, default=20)\n \n parser.add_argument('--agent_name', type=str, default='ppogcp')\n \n parser.add_argument('--pretrain_path', type=str, default=None)\n # parser.add_argument('--pretrain_path', type=str, default='bert_binary')\n\n # agent\n parser.add_argument('--seed', type=int, default=0)\n \n parser.add_argument('--num', type=int, default=2)\n \n parser.add_argument('--lr', type=float, default=3e-4)\n \n parser.add_argument('--bs', type=int, default=512)\n \n parser.add_argument('--hidden_dim', type=int, default=128)\n parser.add_argument('--output_dim', type=int, default=32)\n parser.add_argument('--policy_language_dim', type=int, default=14)\n\n # mdp\n parser.add_argument('--fd', type=float, default=0.20)\n \n parser.add_argument('--num_obj', type=int, default=5)\n \n parser.add_argument('--action_type', type=str, default='perfect')\n parser.add_argument('--mode', type=str, default='train')\n\n args = parser.parse_args()\n\n return args\n\n\ndef make_env(args):\n def _thunk():\n if args.id == 'langGCP':\n env = LangGCPEnv(maximum_episode_steps=50, action_type=args.action_type, obs_type='order_invariant',\n direct_obs=True, use_subset_instruction=True,\n fail_dist=args.fd,\n language_model_type=args.lm_type,\n mode=args.mode,\n )\n else:\n raise NotImplementedError\n\n env = Monitor(env, None, allow_early_resets=True)\n \n return env\n\n return _thunk\n\n\ndef env_wrapper(args):\n envs = [\n make_env(args)\n for _ in range(args.num)\n ]\n\n if len(envs) > 1:\n envs = SubprocVecEnv(envs)\n else:\n envs = DummyVecEnv(envs)\n\n envs = VecNormalize(envs, norm_reward=True, norm_obs=False, training=False)\n\n return envs\n\n\nfrom GCP_utils.utils import get_best_cuda\nfrom typing import List\n\n\ndef train(\n env_list: List[VecNormalize],\n args,\n):\n env = env_list[0]\n train_env = env_list[1]\n test_env = env_list[2]\n error_env = env_list[3]\n \n agent_name = args.agent_name\n num = env.num_envs\n lr = args.lr\n ns = 512\n bs = args.bs\n \n device = f'cuda:{get_best_cuda()}'\n \n prefix = 'original'\n if args.pretrain_path is not None:\n prefix = 'pretrain'\n \n if agent_name == 'ppo':\n agent = LangPPO(\n policy='MlpPolicy',\n env=env,\n learning_rate=lr,\n n_steps=ns,\n batch_size=bs,\n tensorboard_log=f'{prefix}_baseline_train',\n device=device,\n verbose=1,\n seed=args.seed,\n )\n elif agent_name == 'ppogcp':\n model_path = models_dir.joinpath(f'{args.lm_type}_{args.seed}')\n lm_kwargs = {\n 'device': device,\n 'model_path': model_path,\n 'hidden_dim': args.hidden_dim,\n 'output_dim': args.output_dim,\n 'policy_language_dim': args.policy_language_dim,\n 'mode': 'low',\n 'is_kitchen': False,\n \"emb_dim\": 768,\n }\n if args.lm_type == 'onehot':\n pass\n elif args.lm_type in ['bert_cont', 'bert_onehot', 'bert_binary']:\n lm_kwargs.update({\n \"bert_kwargs\": {\n \"hidden_dim\": args.hidden_dim,\n \"output_dim\": args.output_dim,\n \"tune_flag\": False,\n \"device\": device,\n }})\n elif 'policy' in args.lm_type:\n lm_kwargs['epoch'] = args.policy_epoch\n elif args.lm_type in ['baseline']:\n model_path = models_dir.joinpath(f'{args.lm_type}')\n lm_kwargs['model_path'] = model_path\n else:\n raise NotImplementedError\n \n kwargs = {\n 'features_extractor_kwargs': {\n 'language_model_type': args.lm_type,\n 'language_model_kwargs': lm_kwargs, \n }\n }\n \n agent = LangGCPPPO(\n policy='LangGCPPolicy',\n env=env,\n learning_rate=lr,\n n_steps=ns,\n batch_size=bs,\n tensorboard_log=f'{prefix}_baseline_train',\n device=device,\n verbose=1,\n policy_kwargs=kwargs,\n seed=args.seed,\n )\n pretrain_models_dir = models_dir.joinpath('pretrain')\n if args.pretrain_path is not None:\n agent = LangGCPPPO.lang_load(\n pretrain_models_dir.joinpath(args.pretrain_path),\n env=env,\n learning_rate=lr,\n n_steps=ns,\n batch_size=bs,\n tensorboard_log=f'{prefix}_baseline_train',\n device=device,\n verbose=1,\n policy_kwargs=kwargs,\n seed=args.seed,\n )\n else:\n raise NotImplementedError\n\n # steps = 100000000\n steps = 2500000\n\n if 'ppo' in agent_name:\n log_interval = 1\n save_interval = 1\n save_interval = 100000000\n else:\n raise NotImplementedError\n\n if args.pretrain_path is not None:\n log_interval = 1\n save_interval = 10000000\n\n from datetime import datetime\n train_time_start = datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")\n tb_log_name = f'{train_time_start}_{args.id}_{agent_name}_num_{num}_lr_{lr}_ns_{ns}_bs_{bs}_fd_{args.fd}_lm_{args.lm_type}_nobj_{args.num_obj}_seed_{args.seed}_hidden_{args.hidden_dim}_output_{args.output_dim}'\n log_path = f'{prefix}_baseline_callback/{args.id}_{agent_name}_num_{num}_lr_{lr}_ns_{ns}_bs_{bs}_fd_{args.fd}_lm_{args.lm_type}_nobj_{args.num_obj}_seed_{args.seed}_hidden_{args.hidden_dim}_output_{args.output_dim}'\n save_path = f'{prefix}_baseline_model/{args.id}_{agent_name}_num_{num}_lr_{lr}_ns_{ns}_bs_{bs}_fd_{args.fd}_lm_{args.lm_type}_nobj_{args.num_obj}_seed_{args.seed}_hidden_{args.hidden_dim}_output_{args.output_dim}/model'\n \n from stable_baselines3.common.callbacks import EvalCallback, CallbackList\n \n eval_interval = 4\n\n save_interval = 50\n eval_interval = 50\n\n train_log_path = f'{log_path}_env_train'\n test_log_path = f'{log_path}_env_test'\n error_log_path = f'{log_path}_env_error'\n \n train_callback = EvalCallback(\n eval_env=train_env,\n log_path=train_log_path,\n deterministic=False,\n eval_freq=eval_interval * agent.n_steps,\n n_eval_episodes=40,\n name='train',\n )\n test_callback = EvalCallback(\n eval_env=test_env,\n log_path=test_log_path,\n deterministic=False,\n eval_freq=eval_interval * agent.n_steps,\n n_eval_episodes=40,\n name='test',\n )\n error_callback = EvalCallback(\n eval_env=error_env,\n log_path=error_log_path,\n deterministic=False,\n eval_freq=eval_interval * agent.n_steps,\n n_eval_episodes=40,\n name='error',\n )\n \n eval_callback = CallbackList([\n train_callback,\n test_callback,\n error_callback,\n ])\n \n agent.lang_learn(\n total_timesteps=steps,\n log_interval=log_interval,\n tb_log_name=tb_log_name,\n callback=eval_callback,\n save_interval=save_interval,\n save_path=save_path,\n )\n\n\nif __name__ == \"__main__\":\n args = get_args()\n \n eval_args = copy.deepcopy(args)\n eval_args.num = 1\n \n train_args = copy.deepcopy(eval_args)\n test_args = copy.deepcopy(eval_args)\n error_args = copy.deepcopy(eval_args)\n \n train_args.mode = 'train'\n test_args.mode = 'test'\n error_args.mode = 'error'\n \n env = env_wrapper(args)\n train_env = env_wrapper(train_args)\n test_env = env_wrapper(test_args)\n error_env = env_wrapper(error_args)\n env_list = [\n env,\n train_env,\n test_env,\n error_env,\n ] \n \n train(env_list=env_list, args=args)\n \n","repo_name":"ppq12138/TALAR","sub_path":"baseline.py","file_name":"baseline.py","file_ext":"py","file_size_in_byte":9025,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"42"} +{"seq_id":"29799804901","text":"# importing google text-to-speech (TTS) modules\nfrom gtts import gTTS\n\n# This module is imported so that we can\n# play the converted audio\n\n# The text that you want to convert to audio\nmytext = \"add your text here\"\n\n# Language in which you want to convert\nlanguage = 'en'\n# tld = 'co.uk'\n\n# Passing the text and language to the engine,\n# here we have marked slow=False. Which tells\n# the module that the converted audio should\n# have a high speed\nfile = gTTS(text=mytext, lang=language, slow=False)\n\n# Saving the converted audio in a mp3 file named\n# welcome\nfile.save(\"test.mp3\")\n","repo_name":"dir0417/Text-to-speech","sub_path":"Text-to-speech-gTTS.py","file_name":"Text-to-speech-gTTS.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"23735100366","text":"#Do, or do not. There is no try. --Yoda\n###############\n# CHAPTER 4: Py Crust: Code Structures\n############## \n\n # Comment with #\n \n# Continue Lines with \\\n \nalphabet = 'ahdhahfa' +\\\n 'ahsdhahfa' +\\\n 'ahdhafhalf'\n \n##### Compare with if, elif, and else\n \ndisaster = True\n\nif disaster: # if forget to type \":\", python will give an error\n print(\"woe!\")\nelse:\n print(\"whee!\")\n\nfurry= True\nsamll= True\n\nif furry:\n if samll:\n print(\"It is a cat.\")\n else:\n print(\"It is a bear!\")\nelse:\n if small:\n print(\"It is a skink!\")\n else:\n print(\"it is human\")\n\n# elif (meaning else if), and else\ncolor = \"puce\"\n\nif color == \"red\":\n print(\"tomato\")\nelif color == \"green\":\n print(\"its a tomato\")\nelif color == \"bee purple\":\n print(\"I donot know\")\nelse:\n print(\"I near heard\", color)\n \n# Python’s comparison operators are:\n # equality ==\n # inequality !=\n # less than <\n # less than or equal <=\n # greater than >\n # greater than or equal >=\n # membership in …\n \n ## Note that two equals signs (==) are used to test equality; remember, a single equals sign\n # (=) is what you use to assign a value to a variable.\n\n\n# What Is True?\n\nsome_list=[]\n\nif some_list:\n print(\"there is something in here\")\nelse:\n print(\"Hey, it is empty!\")\n\n# # Repeat with while\ncount=1\n\nwhile count <=5:\n print(count)\n count +=1 \n\n# Cancel with break\n\nwhile True:\n stuff= input(\"String to capitalize [type q to quit]: \")\n if stuff == \"q\":\n break\n print(stuff.capitalize())\n \n# Skip Ahead with continue\n\nwhile True:\n value = input(\"Integer, please [q to quit]:\")\n if value == 'q':\n break\n number = int(value)\n if number % 2 == 0:\n continue\n print(number, \"squared is\", number*number)\n\n# Check break Use with else\n\nnumbers = [1,3,5]\nposition = 0 \n# If the while loop ended normally (no break call), control passes to an optional else.\nwhile position < len(numbers):\n number = numbers[position]\n if number % 2 ==0:\n print('Found even number', number)\n break\n position +=1\nelse:\n print('No even number found')\n\n\n# Iterate with for\nrabbits = ['Flopsy', 'Mopsy', 'Cottontail', 'Peter']\n\ncurrent = 0\n\nwhile current < len(rabbits):\n print(rabbits[current])\n current +=1\n# or\nfor x in rabbits:\n print(x)\n\nword = 'cat'\nfor x in word:\n print(x)\n# example for dict\n\naccusation = {'room': 'ballroom', 'weapon': 'lead pipe',\n'person': 'Col. Mustard'}\n\nfor card in accusation: # or, for card in accusation.keys():\n print(card)\n\n# To iterate over the values rather than the keys, you use the dictionary’s values() function:\n \nfor value in accusation.values():\n print(value)\n\n# to return both key and value: \n\nfor x in accusation.items():\n print(x)\n \n# For each tuple returned by\n# items(), assign the first value (the key) to card and the second (the value) to contents:\n\nfor x, y in accusation.items():\n print(x,y)\n\n# Cancel with break: A break in a for loop breaks out of the loop, as it does for a while loop.\n \n# skip with \"continue\": Inserting a continue in a for loop jumps to the next iteration of the loop, as it does for\n#a while loop \n\n# Check break Use with else\n \ncheeses =[]\n\nfor cheese in cheeses:\n print('This shop has', cheese)\n break\nelse: # no break means no cheese\n print('This is not much of a cheese shop, is it')\n\ncheeses = []\nfound_one = False\n\n\nfor cheese in cheeses:\n found_one = True\n print('This shop has some lovely', cheese)\n break\n\nif not found_one:\n print('This is not much of a cheese shop, is it?')\n \n# Iterate Multiple Sequences with \"zip()\" function: \n \ndays = ['Monday', 'Tuesday', 'Wednesday']\n\nfruits = ['banana', 'orange', 'peach']\ndrinks = ['coffee', 'tea', 'beer']\ndesserts = ['tiramisu', 'ice cream', 'pie', 'pudding']\n \n \nfor day, fruit, drink, dessert in zip(days, fruits, drinks, desserts): # \n print(day, \": drink\", drink, \"- eat\", fruit, \"- enjoy\", dessert) # zip() stops when the shortest sequence is done\n \nenglish = 'Monday', 'Tuesday', 'Wednesday'\nfrench = 'Lundi', 'Mardi', 'Mercredi'\n\nlist(zip(english,french))\ndict(zip(english,french))\n \n# Generate Number Sequences with range()\n\n# The range() function returns a stream of numbers within a specified range\n\n# range(start, stop, step)\n\nfor x in range(0,3):\n print(x)\n\nlist(range(0,3))\n\nfor x in range(2,-1,-1):\n print(x)\n \n##############\n#Comprehensions\n##############\n\n# List Comprehensions\n\nnumber_list=[]\n\nfor number in range(1,6):\n number_list.append(number)\n\nnumber_list = [number for number in range(1,6)]\nnumber_list = list(range(1,6)) \nnumber_list = [number-1 for number in range(1,6)] \n\na_list = [number for number in range(1,6) if number % 2 ==1] # only odd numeber, 1, 3, 5\n\na_list = []\n\nfor number in range(1,6):\n if number % 2 == 1:\n a_list.append(number)\n \n\nrows = range(1,4)\ncols = range(1,3)\n\nfor row in rows:\n for col in cols:\n print(row,col)\n \n# making it a list of (row, col) tuples\n\nrows= range(1,4)\ncols = range(1,3)\ncells = [(row,col) for row in rows for col in cols]\nfor cell in cells:\n print(cell)\n# \nfor row, col in cells:\n print(row,col)\n\n######\n# Dictionary Comprehensions : { key_expression : value_expression for expression in iterable }\n######\n\nword= 'letters'\nletter_cpunts = {letter: word.count(letter) for letter in word}\n\nword = 'letters'\nletter_counts = {letter: word.count(letter) for letter in set(word)}\nletter_counts\n\n# Set Comprehensions: { expression for expression in iterable }\n\na_set = {number for number in range(1,6) if number % 3 == 1}\n\n\n# Generator Comprehensions\n\nnumber_thing = (number for number in range(1,6))\n\ntype(number_thing) # A generator is one way to provide data to an iterator.\n\nfor number in number_thing:\n print(number)\n\nnumber_list = list(number_thing)\nnumber_list\n\n#####################\n# Functions\n#####################\n# two things with a function\n# Define it\n# Call it\n\n#To define a Python function, you type def, the function name, parentheses enclosing\n#any input parameters to the function, and then finally, a colon (:).\n\n# def function name():\n # indent code\n \ndef do_nothing():\n pass\n\ndo_nothing()\n\ndef make_a_sound():\n print('quak')\n\nmake_a_sound()\n\ndef agree():\n return True\n\nagree()\n\nif agree():\n print('Splendid!')\nelse:\n print('that was unexpected.')\n\ndef echo(anything):\n return anything + ' ' + anything\n\necho('majid')\n#\n\ndef commentary(color):\n if color == 'red':\n return \"it is a tomato\"\n elif color == ';green':\n return \"ir is a green pepper\"\n elif color == 'bee purple':\n return \"I donot know what it is\"\n else:\n return \"I have never heard of the color\" + color + \".\"\n \n\ncomment = commentary('blue') \n\nprint(comment) \n# \nprint(do_nothing())\n\n\n##### None Is Useful: \n# Remember that zero-valued integers or floats, empty strings (''), lists ([]), tuples ((,)), dictionaries ({}), \n# and sets(set()) are all False, but are not equal to None.\n\ndef is_none(thing):\n if thing is None:\n print(\"it is none\")\n elif thing:\n print(\"it is True\")\n else:\n print(\"It is False\")\n \n\nis_none(True)\nis_none(False)\nis_none(())\nis_none(None)\n\n###########\n# Positional Arguments\n\ndef menu(wine, entree, dessert):\n return {'wine': wine, 'entree': entree, 'dessert': dessert}\n\nmenu('chardonnay','chicken', 'cake')\n\n# Keyword Arguments\nmenu(entree='beef', dessert='bagel', wine='bordeaux')\n\n# Specify Default Parameter Values\n\ndef menu(wine, entree, dessert='pudding'):\n return {'wine': wine, 'entree': entree, 'dessert': dessert}\n\nmenu('chardonnay', 'chicken')\n\n# there’s a bug: it’s empty only the first time it’s called. The second time, result still has\n# one item from the previous call:\ndef buggy(arg, result = []):\n result.append(arg)\n print(result)\n\nbuggy('a')\nbuggy('b') \n\n# re write againg: \n\ndef buggy(arg):\n result =[]\n result.append(arg)\n return result\nbuggy('a')\nbuggy('b') \n\n# to fix this: \n\ndef nonbuggy(arg, result = None):\n if result is None:\n result =[]\n result.append(arg)\n print(result)\nbuggy('a')\nbuggy('b') \n\n##############\n## Gather Positional Arguments with *\n\n# Python doesn’t have pointers\n\ndef print_args(*args):\n print('Positional argument tuple:', args)\n\nprint_args()\n\nprint_args(3, 2, 1, 'wait!', 'uh...')\n\n# If your function has required positional arguments as well, *args goes at\n# the end and grabs all the rest:\n\ndef print_more(required1, required2, *args): # *args: will merge arguments\n print('Need this one:', required1)\n print('Need this one too:', required2)\n print('All the rest:', args)\n\nprint_more('cap', 'gloves', 'scarf', 'monocle', 'mustache wax')\n\n################\n# Gather Keyword Arguments with **\n\n# You can use two asterisks (**) to group keyword arguments into a dictionary, where the\n# argument names are the keys, and their values are the corresponding dictionary values\n\ndef print_kwargs(**kwargs):\n print('keyword arguments:', kwargs)\n\nprint_kwargs(wine='merlot', entree='mutton', dessert='macaroon')\n\n\n# Docstrings\n\ndef echo(anything):\n 'echo returns its input argumnet'\n return anything\n\necho('maji')\n\ndef print_if_true(thing, check):\n '''\n Prints the first argumnet if a second argument is true.\n the operation is:\n 1. Check whether the *second* argument is true.\n 2. If it is, print the *first* argument.\n '''\n if check:\n print(thing)\n\nhelp(echo)\n\nprint(echo.__doc__)\n\n###\n# Functions Are First-Class Citizens\n###\ndef answer():\n print(42)\ndef run_something(func):\n func()\n \nrun_something(answer)\n\ndef add_args(arg1, arg2):\n print(arg1+arg2)\n\ntype(add_args)\n# this function will get arg1 and arg2 argument and call func as function.\ndef run_something_with_args(func, arg1, arg2):\n func(arg1, arg2)\n\nrun_something_with_args(add_args, 5, 9)\n#\n\ndef sum_args(*args):\n return sum(args)\n\n# a function and any number of positional arguments to pass to it:\n \ndef run_with_positional_arg(func, *args):\n return func(*args)\n\nrun_with_positional_arg(sum_args, 1,2,3,4)\n\n#######\n# Inner Functions: a function that is dynamically generated by another function\n\ndef outer(a,b): # tow functions \n def inner(c,d):\n return c + d\n return inner(a,b)\n\nouter(3,7)\n\ndef knights(saying):\n def inner(quote):\n return \"We are the knights who say: '%s'\" % quote\n return inner(saying)\n\nknights('Ni!')\n\n# Closures: a dynamically created function that remembers where it came from.\ndef knights2(saying):\n def inner2():\n return \"We are the knights who say: '%s'\" % saying\n return inner2\n\na = knights2('Duck')\nb = knights2('Hasenpfeffer')\n\na()\nb()\n\n############################################\n# Anonymous Functions: the lambda() Function\n############################################\n\n# A lambda function is an anonymous function expressed as a single statement.\n\ndef edit_story(words, func): # words: a list of words\n for word in words: # func: a function to apply to each word in words\n print(func(word))\n\n\nstairs= ['thud', 'meow', 'thud', 'hiss']\ndef enliven(word): # give that prose more punch\n return word.capitalize() + '!'\n\nedit_story(stairs, enliven) # two function\n\nedit_story(stairs, lambda word: word.capitalize() + '!')\nedit_story(stairs, lambda x: x.capitalize() + '!')\n\n\n######\n\n# Generators: A generator is a Python sequence creation object.\n######\n\ndef my_range(first=0, last=10, step=1):\n number = first\n while number < last:\n yield number # instead of return, use yield\n number += step\nranger= my_range(1,5)\n\nfor x in ranger:\n print(x)\n\n# Decorators: A decorator is a function that takes one function as input and returns another function.\n\ndef document_it(func):\n def new_function(*args, **kwargs):\n print('Running function:', func.__name__)\n print('Positional arguments:', args)\n print('Keyword arguments:', kwargs)\n result = func(*args, **kwargs)\n print('Result:', result)\n return result\n return new_function\n\ndef add_ints(a,b):\n return a + b\nadd_ints(3,5)\n\ncooler_add_ints = document_it(add_ints) # manual decorator assignment\n\ncooler_add_ints(3, 5)\n\n# alternative : \n\n@document_it\ndef add_ints(a, b):\n return a + b\n\nadd_ints(3, 5)\n\ndef square_it(func):\n def new_function(*args, **kwargs):\n result = func(*args, **kwargs)\n return result * result\n return new_function\n\n@document_it\n@square_it\ndef add_ints(a,b):\n return a + b\n\nadd_ints(3, 5)\n\n# reversing the decorator order\n@square_it\n@document_it\ndef add_ints(a, b):\n return a + b\n\nadd_ints(3, 5)\n\n## Namespaces and Scope\n\nanimal = 'fruitbat'\n\ndef print_global():\n print('inside print_global:', animal)\n\nprint('at the top level:', animal)\n\nprint_global()\n\n# will get an error\ndef change_and_print_global():\n print('inside change_and_print_global:', animal)\n animal = 'wombat'\n print('after the change:', animal) \nchange_and_print_global()\n# \ndef change_local():\n animal = 'wombat'\n print('inside change_local:', animal, id(animal))\n \n############\nanimal = 'fruitbat'\ndef change_and_print_global():\n global animal\n animal = 'wombat'\n print('inside change_and_print_global:', animal)\n\n# locals() returns a dictionary of the contents of the local namespace.\n \n# globals() returns a dictionary of the contents of the global namespace.\nanimal = 'fruitbat'\n\ndef change_local():\n animal = 'wombat' # local variable\n print('locals:',locals())\n\nchange_local()\n\n\nprint('globals:', globals()) # reformatted a little for presentation\n\n# Uses of _ and __ in Names\n# Names that begin and end with two underscores (__) are reserved for use within Python,\n\n###\n# Handle Errors with try and except\n###\n\n\n## Python uses exceptions: code that is executed when an associated error occurs\n\nshort_list = [1, 2, 3]\nposition = 5\nshort_list[position]\n\nshort_list = [1, 2, 3]\nposition = 5\n#use \"try\" to wrap your code, and \"except\" to provide the error handling\ntry:\n short_list[position]\nexcept:\n print('Need a position between 0 and', len(short_list)-1, 'but got', position)\n\n\n\n##########################\n# Things to Do\n##########################\n#1: Assign the value 7 to the variable guess_me. Then, write the conditional tests (if,\n# else, and elif) to print the string 'too low' if guess_me is less than 7, 'too high' if\n# greater than 7, and 'just right' if equal to 7.\n\nguess_me = 7\n\nif guess_me < 7:\n print('too low')\nelif guess_me > 7:\n print('too high')\nelse:\n print('just right')\n\nguess_me = 7\nstart = 1\n#2: Assign the value 7 to the variable guess_me and the value 1 to the variable start.\n#Write a while loop that compares start with guess_me. Print 'too low' if start is less than guess me. \n#If start equals guess_me, print 'found it!' and exit the loop. If start\n# is greater than guess_me, print 'oops' and exit the loop. Increment start at the end of the loop.\nwhile True:\n if start < guess_me:\n print('too low')\n elif start == guess_me:\n print('found it')\n break\n elif start > guess_me:\n print('oops')\n break\n start += 1\n# 3: Use a for loop to print the values of the list [3, 2, 1, 0].\nfor value in [3,2,1,0]:\n print(value)\n\n# 4: Use a list comprehension to make a list called even of the even numbers in range(10).\neven= [number for number in range(10) if number %2 ==0]\n\neven_list=[]\nfor number in range(10):\n if number % 2 ==0:\n even_list.append(number)\n# 5: Use a dictionary comprehension to create the dictionary squares. Use range(10) to\n# return the keys, and use the square of each key as its value.\nsquare = {key: key*key for key in range(10)}\n\n# 6: Use a set comprehension to create the set odd from the odd numbers in range(10).\nodd_set= {number for number in range(10) if number % 2 ==1}\n\n# 7: Use a generator comprehension to return the string 'Got ' and a number for the\n# numbers in range(10). Iterate through this by using a for loop.\nfor thing in ('Got %s' % number for number in range(10)):\n print(thing)\n\n# 8: Define a function called good() that returns the list ['Harry', 'Ron', 'Hermione'].\ndef good():\n return['Harry','Ron','Hermione']\n \n# 9: Define a generator function called get_odds() that returns the odd numbers from\n # range(10). Use a for loop to find and print the third value returned.\ndef get_odds():\n for number in range(10):\n if number % 2 == 1:\n print(number)\n\ndef get_oddss():\n for number in range(1,10,2):\n yield number\n\nfor count, number in enumerate(get_oddss(),1):\n if count ==3:\n print(\"The third odd numver is\", number)\n break\n\n# 10: Define a decorator called test that prints 'start' when a function is called and 'end' when it finishes.\n\ndef test(func):\n def new_func(*arg, **kwargs):\n print('start')\n result = func(*arg, **kwargs)\n print('end')\n return result\n return new_func\n\n@test\ndef greeting():\n print(\"Greetings, Earthiling\")\n \ngreeting()\n\n# 11: Define an exception called OopsException. Raise this exception to see what happens.\n# Then, write the code to catch this exception and print 'Caught an oops'.\n\nclass OopsException(Exception):\n pass\n\nraise OopsException()\n\ntry:\n raise OopsException\nexcept OopsException:\n print('Cought an oops')\n \n# 12 Use zip() to make a dictionary called movies that pairs these lists: titles =\n#['Creature of Habit', 'Crewel Fate'] and plots = ['A nun turns into a mon\n# ster', 'A haunted yarn shop'].\n\ntitles = ['Creature of Habit', 'Crewel Fate']\nplots = ['A nun turns into a monster', 'A haunted yarn shop']\n\nmovie = dict(zip(titles, plots)) \n \n\n\n\n \n\n \n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n","repo_name":"mhrizi/Python","sub_path":"Chapter_4_1.py","file_name":"Chapter_4_1.py","file_ext":"py","file_size_in_byte":17852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"73296094214","text":"import turtle\nimport math\n#设置画布尺寸\nturtle.screensize(400, 300, \"#FFE4C4\")\nturtle.pensize(1)\nturtle.pencolor(\"black\")\nturtle.speed(5)\nturtle.hideturtle()\n \n#画兔头\nturtle.fillcolor(\"white\")\nturtle.begin_fill()\nturtle.penup()\nturtle.goto(0, 80)\nturtle.seth(0)\nturtle.pendown()\nturtle.circle(-60, 90)\nturtle.left(90)\nturtle.circle(-25, 160)\nturtle.circle(-200, 20)\nturtle.goto(0, -40)\nturtle.penup()\nturtle.goto(0, 80)\nturtle.seth(180)\nturtle.pendown()\nturtle.circle(60, 90)\nturtle.right(90)\nturtle.circle(25, 160)\nturtle.circle(200, 20)\nturtle.goto(0, -40)\nturtle.end_fill()\n \n#画兔嘴巴\nturtle.penup()\nturtle.goto(0, 0)\nturtle.right(60)\nturtle.pendown()\nturtle.circle(10, 135)\nturtle.penup()\nturtle.goto(0, 0)\nturtle.seth(0)\nturtle.pendown()\nturtle.right(120)\nturtle.circle(-10, 135)\nturtle.penup()\nturtle.seth(0)\nturtle.goto(-10, -5)\nturtle.pendown()\nturtle.right(90)\nturtle.fillcolor(\"pink\")\nturtle.begin_fill()\nturtle.forward(5)\nturtle.circle(10, 180)\nturtle.forward(5)\n \n#画兔鼻子\nturtle.penup()\nturtle.seth(0)\nturtle.goto(0, 0)\nturtle.pendown()\nturtle.circle(3)\nturtle.end_fill()\n \n#画兔眼睛\n#左眼\nturtle.penup()\nturtle.seth(0)\nturtle.goto(-35, 5)\nturtle.pendown()\nturtle.fillcolor(\"white\")\nturtle.begin_fill()\nturtle.circle(12)\nturtle.end_fill()\nturtle.fillcolor(\"black\")\nturtle.begin_fill()\nturtle.circle(10)\nturtle.end_fill()\n#右眼\nturtle.penup()\nturtle.seth(0)\nturtle.goto(35, 5)\nturtle.pendown()\nturtle.fillcolor(\"white\")\nturtle.begin_fill()\nturtle.circle(12)\nturtle.end_fill()\nturtle.fillcolor(\"black\")\nturtle.begin_fill()\nturtle.circle(10)\nturtle.end_fill()\n \n#画兔耳朵\nturtle.penup() # 左耳\nturtle.seth(90)\nx1 = -5\ny1 = math.sqrt(80**2-x1**2)\nx2 = -20\ny2 = math.sqrt(80**2-x2**2)\nx3 = -10\ny3 = math.sqrt(80**2-x3**2)\nx4 = -15\ny4 = math.sqrt(80**2-x4**2)\nturtle.goto(x1, y1)\nturtle.pendown()\nturtle.fillcolor(\"white\")\nturtle.begin_fill()\nturtle.circle(100, 30)\nturtle.circle(15, 180)\nturtle.goto(x2, y2)\nturtle.end_fill()\nturtle.fillcolor(\"pink\") # 左耳上色\nturtle.penup()\nturtle.seth(90)\nturtle.goto(x3, y4)\nturtle.pendown()\nturtle.begin_fill()\nturtle.circle(100, 20)\nturtle.circle(8, 180)\nturtle.goto(x4, y4)\nturtle.end_fill()\nturtle.penup() # 右耳\nturtle.seth(90)\nx5 = 5\ny5 = math.sqrt(80**2-x5**2)\nx6 = 20\ny6 = math.sqrt(80**2-x6**2)\nx7 = 10\ny7 = math.sqrt(80**2-x7**2)\nx8 = 15\ny8 = math.sqrt(80**2-x8**2)\nturtle.goto(x5, y5)\nturtle.pendown()\nturtle.fillcolor(\"white\")\nturtle.begin_fill()\nturtle.circle(-100, 30)\nturtle.circle(-15, 180)\nturtle.goto(x6, y6)\nturtle.end_fill()\nturtle.fillcolor(\"pink\") # 右耳上色\nturtle.penup()\nturtle.seth(90)\nturtle.goto(x7, y7)\nturtle.pendown()\nturtle.begin_fill()\nturtle.circle(-100, 20)\nturtle.circle(-8, 180)\nturtle.goto(x8, y8)\nturtle.end_fill()\n \n#画兔身\nturtle.fillcolor(\"white\")\nturtle.penup() # 左边\nturtle.seth(180)\nturtle.goto(0, -40)\nturtle.begin_fill()\nturtle.pendown()\nturtle.circle(-200, 15)\nturtle.seth(-135)\nturtle.circle(100, 25)\nturtle.circle(60, 90)\nturtle.goto(0, -150)\nturtle.penup() # 右边\nturtle.seth(0)\nturtle.goto(0, -40)\nturtle.pendown()\nturtle.circle(200, 15)\nturtle.seth(-45)\nturtle.circle(-100, 25)\nturtle.circle(-60, 90)\nturtle.goto(0, -150)\nturtle.end_fill()\n \n#画兔手和脚\nturtle.fillcolor(\"white\")\nturtle.penup() # 左手\nturtle.seth(0)\nturtle.goto(-50, -40)\nturtle.begin_fill()\nturtle.pendown()\nturtle.forward(8)\nturtle.circle(-15, 180)\nturtle.forward(8)\nturtle.circle(-15, 180)\nturtle.penup() # 右手\nturtle.seth(180)\nturtle.goto(50, -40)\nturtle.pendown()\nturtle.forward(8)\nturtle.circle(15, 180)\nturtle.forward(8)\nturtle.circle(15, 180)\nturtle.end_fill()\nturtle.fillcolor(\"white\")\nturtle.penup() # 左脚\nturtle.seth(135)\nturtle.goto(-50, -150)\nturtle.begin_fill()\nturtle.pendown()\nturtle.forward(12)\nturtle.circle(-15, 180)\nturtle.forward(12)\nturtle.circle(-15, 180)\nturtle.penup() # 右脚\nturtle.seth(45)\nturtle.goto(50, -150)\nturtle.pendown()\nturtle.forward(12)\nturtle.circle(15, 180)\nturtle.forward(12)\nturtle.circle(15, 180)\nturtle.end_fill()\n \n#福字\nturtle.fillcolor(\"#CD4F39\") # 红纸\nturtle.penup()\nturtle.seth(-45)\nturtle.begin_fill()\nturtle.goto(0, -30)\nturtle.pendown()\ni = 1\nfor i in range(4):\n turtle.forward(90)\n turtle.right(90)\n i = i+1\nturtle.end_fill()\nturtle.pencolor(\"#FFDE00\") # 金字\nturtle.pensize(6)\nturtle.penup() # 点\nturtle.goto(-21, -70)\nturtle.seth(-60)\nturtle.pendown()\nturtle.forward(8)\nturtle.penup() # 横折\nturtle.goto(-30, -80)\nturtle.seth(0)\nturtle.pendown()\nturtle.forward(20)\nturtle.right(145)\nturtle.forward(35)\nturtle.penup() # 竖\nturtle.goto(-20, -90)\nturtle.seth(-90)\nturtle.pendown()\nturtle.forward(38)\nturtle.penup() # 点\nturtle.goto(-20, -90)\nturtle.seth(-45)\nturtle.pendown()\nturtle.forward(10)\nturtle.penup() # 横\nturtle.goto(0, -75)\nturtle.seth(0)\nturtle.pendown()\nturtle.forward(25)\nturtle.penup() # 口\nturtle.goto(2, -85)\nturtle.seth(-90)\nturtle.pendown()\nturtle.forward(10)\nturtle.penup()\nturtle.goto(2, -85)\nturtle.seth(0)\nturtle.pendown()\nturtle.forward(18)\nturtle.right(100)\nturtle.forward(10)\nturtle.penup()\nturtle.goto(2, -95)\nturtle.seth(0)\nturtle.pendown()\nturtle.forward(15)\nturtle.penup() # 田\nturtle.goto(-3, -105)\nturtle.seth(-90)\nturtle.pendown()\nturtle.forward(20)\nturtle.penup()\nturtle.goto(-3, -105)\nturtle.seth(0)\nturtle.pendown()\nturtle.forward(30)\nturtle.right(100)\nturtle.forward(22)\nturtle.penup()\nturtle.goto(-3, -115)\nturtle.seth(0)\nturtle.pendown()\nturtle.forward(25)\nturtle.penup()\nturtle.goto(10, -105)\nturtle.seth(-90)\nturtle.pendown()\nturtle.forward(15)\nturtle.penup()\nturtle.goto(0, -125)\nturtle.seth(0)\nturtle.pendown()\nturtle.forward(25)\n \nturtle.done()","repo_name":"xiaoqiuuuu/Turtle-project","sub_path":"material/pypicture/福兔.py","file_name":"福兔.py","file_ext":"py","file_size_in_byte":5616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"19264105081","text":"#importing required packages\nimport numpy as np\nimport cv2\n#below library is used to check OpenCV version\nimport imutils\n\n# Used to extract our 3D HSV color histogram from our images\nclass ColorDescriptor:\n # only takes a single argument, bins.\n def __init__(self, bins):\n # store the number of bins for the 3D histogram\n self.bins = bins\n\n # image we want to describe\n def describe(self, image):\n # convert the image to the HSV color space and initialize\n # the features used to quantify the image\n # RGB color space to HSV color space\n image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n # initializing our list of features to quantify and represent our image\n features = []\n\n # grab the dimensions and compute the center of the image\n (h, w) = image.shape[:2]\n (cX, cY) = (int(w * 0.5), int(h * 0.5))\n\n # Compute a 3D HSV color histogram for different regions of the image\n # instead of the entire image\n # For this will use regions-based histograms rather than global-histograms\n\n # divide the image into four rectangles/segments\n # top-left , right , bottom-left and right\n segments = [ (0, cX, 0, cY), (cX, w, 0, cY), (cX, w, cY, h),\n (0, cX, cY, h)]\n\n # construct an elliptical mask representing the center of the image\n (axesX, axesY) = (int(w * 0.75) // 2, int(h * 0.75) // 2)\n ellipMask = np.zeros(image.shape[:2], dtype = \"uint8\")\n cv2.ellipse(ellipMask, (cX, cY), (axesX, axesY), 0, 0, 360, 255, -1)\n\n # loop over the segments\n for (startX, endX, startY, endY) in segments:\n # extract a mask for each corner of the image,\n # subtracting the elliptical center from it\n cornerMask = np.zeros(image.shape[:2], dtype = \"uint8\" )\n cv2.rectangle(cornerMask, (startX, startY) , (endX, endY), 255, -1)\n cornerMask = cv2.subtract(cornerMask, ellipMask)\n\n # extracting the color histogram from the image\n # then update the feature vector\n hist = self.histogram(image, cornerMask)\n features.extend(hist)\n\n # extracting a color histogram from the elliptical region\n # then update the feature vector\n hist = self.histogram(image, ellipMask)\n features.extend(hist)\n\n # return the feature vector\n return features\n\n def histogram(self, image, mask):\n # extract a 3D color histogram from the masked region of the image\n # using the supplied number of bins per channel\n hist = cv2.calcHist( [image], [0, 1, 2], mask, self.bins, [0, 180, 0, 256, 0, 256])\n\n # normalize the histogram if we are using OpenCV 2.4\n if imutils.is_cv2():\n hist = cv2.normalize(hist).flatten()\n\n # return the histogram\n return hist\n\n \n \n","repo_name":"surenvithanage/ImageSearchEngine","sub_path":"colordescriptor.py","file_name":"colordescriptor.py","file_ext":"py","file_size_in_byte":2909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"30085985923","text":"import pandas as pd\nimport sys, json\n\n#------------------------------------------------------------------------------\n# Define relative target directories\n\npaths_arg = sys.argv[1]\n\nwith open(paths_arg) as json_paths: \n PATHS = json.load(json_paths)\n json_paths.close()\n\nraw_internal_path = PATHS['raw_internal_data_path']\ncurated_data_path = PATHS['curated_data_path']\nexternal_data_path = PATHS['external_data_path']\n\n#------------------------------------------------------------------------------\n# Retreive model metrics\n\nBNPL_metrics = pd.read_csv(curated_data_path + \"BNPL_metrics.csv\")\nBNPL_features = pd.read_csv(curated_data_path + \"BNPL_features.csv\")\n\ncustomer_metrics = pd.read_csv(curated_data_path + \"customer_metrics.csv\")\ncustomer_features = pd.read_csv(curated_data_path + \"customer_features.csv\")\n\nrevenue_metrics = pd.read_csv(curated_data_path + \"revenue_metrics.csv\")\nrevenue_features = pd.read_csv(curated_data_path + \"revenue_features.csv\")\n\ntransactions_metrics = pd.read_csv(\n curated_data_path + \"transactions_metrics.csv\")\ntransactions_features = pd.read_csv(\n curated_data_path + \"transactions_features.csv\")\n\nmetrics = {\n 'Model name': ['Predicted BNPL earnings', 'Predicted no. of Customers', \n 'Predicted Merchant Revenue', \n 'Predicted no. of Transactions'],\n 'Mean Absolute Error': [BNPL_metrics['MAE'].values[0], \n customer_metrics['MAE'].values[0],\n revenue_metrics['MAE'].values[0],\n transactions_metrics['MAE'].values[0]],\n 'RMSE': [BNPL_metrics['RMSE'].values[0], customer_metrics['RMSE'].values[0],\n revenue_metrics['RMSE'].values[0],\n transactions_metrics['RMSE'].values[0]]\n}\n\nmetrics_df = pd.DataFrame(metrics)\n\n\nBNPL_features['name'][0]\nfeature = {\n 'Model name': ['Predicted BNPL earnings', 'Predicted no. of Customers', \n 'Predicted Merchant Revenue',\n 'Predicted no. of Transactions'],\n 'First Feature': [BNPL_features['name'][0], customer_features['name'][0],\n revenue_features['name'][0], transactions_features['name'][0]],\n 'Second Feature': [BNPL_features['name'][1],customer_features['name'][1],\n revenue_features['name'][1],transactions_features['name'][1]],\n 'Third Feature': [BNPL_features['name'][2], customer_features['name'][2],\n revenue_features['name'][2], transactions_features['name'][2]]\n}\n\nfeature_df = pd.DataFrame(feature)\n\n","repo_name":"MAST30034-Applied-Data-Science/generic-buy-now-pay-later-project-group-10-bnpl","sub_path":"scripts/model_evaluation.py","file_name":"model_evaluation.py","file_ext":"py","file_size_in_byte":2573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"11253446481","text":"\"\"\"\nUpdated Clothing module, based on the Clothing contrib by Tim Ashley Jenkins\n\n## How To Use\n\n1. Inherit from `ClothedCharacter` on your main character class, or reference the code\nbelow to add the functionality yourself.\n Note: `ClothedCharacter` adds the clothing handler attribute for managing worn\n items, and modifies two of the hooks involved in returning character appearance\n to display worn vs carried items.\n2. Add the `ClothingCmdSet` to your default CharacterCmdSet\n3. Update your settings as needed. (An overview of options is further down.)\n\nTo make an item wearable, add any tag to it with the \"clothing\" category. The tag you set\nwill define what type of clothing it is, for sorting and other limitations. You can also\ninherit from the `ContribClothing` class below for additional functionality, which is recommended\nfor actual clothing items and anything which should have visible detail when worn.\n Note: The tag category for wearable items is configurable in settings.\n\n\n## Example\n\nLet's say you've set up the module for your `Character` class with all the default settings,\nand you're starting off with a simple object.\n\n> create wrist watch = A simple clock face on a leather band.\n\nThe new `wrist watch` is your default object class (probably Object) and has no tags. If\nyou try to wear it, it won't let you.\n\nTo make it a simple wearable watch, add a clothing tag to it.\n\n> tag wrist watch = accessory:clothing\n> wear wrist watch\n\nLooking at your character (e.g. Monty), you'll see the following in your description:\n `Monty is wearing a wrist watch.`\n\nNow change the type of your wrist watch to the `ContribClothing` typeclass. Assuming the module\nis in your `world` dir:\n\n> type wrist watch = world.clothing.ContribClothing\n\nLooking at your character will now show more detail on the worn watch:\n `Monty is wearing a simple clock face on a leather band.`\n\n\n## Options\n\nSeveral options can be defined in `settings.py` to modify how the module works.\n\nCLOTHING_TAG_CATEGORY (str)\n - Change the tag category for tagging objects as wearable.\nCLOTHING_WORNSTRING_MAX_LENGTH (int)\n - Players can optionally set a string describing how or where they are wearing an item.\n Set the maximum number of characters for these descriptions here, or None to disable.\nCLOTHING_TYPE_ORDER (list)\n - Defines which clothing types are displayed in what order when worn. Any types not in\n the list will be left unsorted at the end. Set to None to disable\nCLOTHING_TOTAL_LIMIT (int)\n - The maximum number of items that a character can wear. Set to None for unlimited.\nCLOTHING_TYPE_LIMITS (dict)\n - Sets the maximum number of a particular type of clothing that a character can wear.\n Any types not present as keys will only be limited by the total item limit.\nCLOTHING_AUTOCOVER_TYPES (dict of lists)\n - Sets which types of clothing will automatically cover which other, already-worn types\n of clothing. See the default for how to structure.\nCLOTHING_NO_COVER_TYPES (list)\n - Sets which types of clothing can't be used to cover things. \n\n\nThe default values are viewable at the beginning of the module.\n\"\"\"\n\nfrom collections import defaultdict\nfrom django.conf import settings\n\nfrom evennia import DefaultCharacter, DefaultObject\nfrom evennia.commands.cmdset import CmdSet\nfrom evennia.commands.default.muxcommand import MuxCommand\nfrom evennia.utils.evtable import EvTable, EvColumn\nfrom evennia.utils import list_to_string, lazy_property\n\nimport inflect\n_INFLECT = inflect.engine()\n\n\n########### Default settings ###########\n\n_CLOTHING_TAG_CATEGORY = \"clothing\"\n\n# Maximum character length of 'wear style' strings, or None to disable.\n_WORNSTRING_MAX_LENGTH = 50\n\n# Display order for different clothing types, or None to disable.\n# Any types not in the list will be unsorted at the end, but still visible.\n_CLOTHING_TYPE_ORDER = [\n \"hat\",\n \"jewelry\",\n \"top\",\n \"undershirt\",\n \"gloves\",\n \"fullbody\",\n \"bottom\",\n \"underpants\",\n \"socks\",\n \"shoes\",\n \"accessory\",\n]\n\n# The maximum number of each type of clothes that can be worn.\n# Any types not specified are not limited.\n_CLOTHING_TYPE_LIMITS = {\"hat\": 1, \"gloves\": 1, \"socks\": 1, \"shoes\": 1}\n\n# The maximum number of clothing items that can be worn, or None for unlimited.\n_CLOTHING_TOTAL_LIMIT = 20\n\n# What types will automatically cover what other types of clothes when worn.\n# Note: clothing can only auto-cover other clothing that is already being worn.\n_CLOTHING_AUTOCOVER_TYPES = {\n \"top\": [\"undershirt\"],\n \"bottom\": [\"underpants\"],\n \"fullbody\": [\"undershirt\", \"underpants\"],\n \"shoes\": [\"socks\"],\n}\n# Types that can't be used to cover other clothes.\n_CLOTHING_NO_COVER_TYPES = [\"jewelry\"]\n\n\n# Override defaults if defined in settings\nif hasattr(settings, \"CLOTHING_TAG_CATEGORY\"):\n _CLOTHING_TAG_CATEGORY = settings.CLOTHING_TAG_CATEGORY\nif hasattr(settings, \"CLOTHING_WORNSTRING_MAX_LENGTH\"):\n _WORNSTRING_MAX_LENGTH = settings.CLOTHING_WORNSTRING_MAX_LENGTH\nif hasattr(settings, \"CLOTHING_TYPE_ORDER\"):\n _CLOTHING_TYPE_ORDER = settings.CLOTHING_TYPE_ORDER\nif hasattr(settings, \"CLOTHING_TOTAL_LIMIT\"):\n _CLOTHING_TOTAL_LIMIT = settings.CLOTHING_TOTAL_LIMIT\nif hasattr(settings, \"CLOTHING_TYPE_LIMITS\"):\n _CLOTHING_TYPE_LIMITS = settings.CLOTHING_TYPE_LIMITS\nif hasattr(settings, \"CLOTHING_AUTOCOVER_TYPES\"):\n _CLOTHING_AUTOCOVER_TYPES = settings.CLOTHING_AUTOCOVER_TYPES\nif hasattr(settings, \"CLOTHING_NO_COVER_TYPES\"):\n _CLOTHING_NO_COVER_TYPES = settings.CLOTHING_NO_COVER_TYPES\n\n\n\nclass ClothingHandler():\n \"\"\"\n Tracks a character's worn objects and visible outfit.\n \"\"\"\n\n def __init__(self, obj, db_attr_key=\"clothing\", db_attr_cat=\"clothing\"):\n \"\"\"\n Initialize the handler.\n \"\"\"\n self.clothing_list = obj.attributes.get(db_attr_key, category=db_attr_cat)\n self.wearer = obj\n if not self.clothing_list:\n obj.attributes.add(db_attr_key, [], category=db_attr_cat)\n self.clothing_list = obj.attributes.get(db_attr_key, category=db_attr_cat)\n \n @property\n def all(self):\n return list(self.clothing_list)\n\n @property\n def visible(self):\n return [obj for obj in self.clothing_list if not obj.db.covered_by ]\n \n def add(self, obj, style=None, quiet=False):\n \"\"\"Wears an object on the character, optionally in a particular style.\"\"\"\n # check if new or adjusting\n if obj in self.clothing_list:\n adjust = True\n else:\n adjust = False\n self.clothing_list.append(obj)\n\n # Set clothing pose\n obj.db.worn = style\n\n # Auto-cover appropirate clothing types, as specified above\n to_cover = []\n if not adjust and True in obj.tags.has(_CLOTHING_AUTOCOVER_TYPES.keys(), category=_CLOTHING_TAG_CATEGORY, return_list=True):\n tags = []\n for key in obj.tags.get(category=_CLOTHING_TAG_CATEGORY, return_list=\"true\"):\n tags += _CLOTHING_AUTOCOVER_TYPES[key]\n outfit_list = [obj for obj in self.clothing_list if not obj.db.covered_by]\n for garment in outfit_list:\n if True in garment.tags.has(tags, category=_CLOTHING_TAG_CATEGORY, return_list=True):\n to_cover.append(_INFLECT.an(garment.name))\n garment.db.covered_by = obj\n # Return nothing if quiet\n if quiet:\n message = None\n # Return a message to echo if otherwise\n else:\n # Echo a message to the room\n if adjust:\n message = \"adjusts %s\" % _INFLECT.an(obj.name)\n else:\n message = \"puts on %s\" % _INFLECT.an(obj.name)\n if to_cover:\n message += \", covering %s\" % list_to_string(to_cover)\n message = f\"{self.wearer.name} {message}.\"\n \n return message\n \n def remove(self, obj, quiet=False):\n \"\"\"Removes worn clothes and optionally echoes to the room.\"\"\"\n obj.db.worn = None\n obj.db.covered_by = None\n clothing = self.clothing_list\n self.clothing_list.remove(obj)\n# self._set(clothing)\n\n uncovered_list = []\n # Check to see if any other clothes are covered by this object.\n for thing in self.clothing_list:\n # If anything is covered by\n if thing.db.covered_by == obj:\n thing.db.covered_by = None\n uncovered_list.append(_INFLECT.an(thing.name))\n \n if quiet:\n message = None\n \n else:\n message = \"removes %s\" % _INFLECT.an(obj.name)\n if uncovered_list:\n message += \", revealing %s\" % list_to_string(uncovered_list)\n message = f\"{self.wearer.name} {message}.\"\n \n return message\n \n def clear(self):\n for obj in list(self.clothing_list):\n obj.db.worn = None\n obj.db.covered_by = None\n self.clothing_list.remove(obj)\n\n def can_add(self, obj):\n \"\"\"\n Checks whether the object can be worn.\n \"\"\"\n clothing_type = obj.tags.get(category=_CLOTHING_TAG_CATEGORY)\n if not clothing_type:\n self.wearer.msg(\"You can't wear that.\")\n return False\n\n # Enforce overall clothing limit.\n if _CLOTHING_TOTAL_LIMIT and len(self.clothing_list) >= _CLOTHING_TOTAL_LIMIT:\n self.wearer.msg(\"You can't wear anything else.\")\n return False\n \n if clothing_type in _CLOTHING_TYPE_LIMITS:\n if self.count_type(clothing_type) >= _CLOTHING_TYPE_LIMITS[clothing_type]:\n self.wearer.msg(\"You can't wear any more of those.\")\n return False\n\n return True\n\n def can_remove(self, obj):\n if obj not in self.clothing_list:\n self.wearer.msg(\"You're not wearing that.\")\n return False\n if obj.db.covered_by:\n self.wearer.msg(\"You can't remove that, it's covered by your %s.\" % obj.db.covered_by.get_display_name(self.wearer))\n return False\n \n return True\n\n def can_cover(self, to_cover, cover_with):\n # check if clothing already covered\n if to_cover.db.covered_by:\n caller.msg(\"Your %s is already covered by %s.\" % (to_cover.name, _INFLECT.an(to_cover.db.covered_by.name)))\n return False\n\n # check if the covering item can cover things\n if not cover_with.tags.has(category=_CLOTHING_TAG_CATEGORY):\n self.wearer.msg(\"Your %s isn't clothes.\" % cover_with.get_display_name(caller))\n return False\n if True in cover_with.tags.has(_CLOTHING_NO_COVER_TYPES, category=_CLOTHING_TAG_CATEGORY, return_list=True):\n self.wearer.msg(\"You can't cover anything with %s.\" % _INFLECT.an(cover_with.name))\n return False\n if to_cover == cover_with:\n self.wearer.msg(\"You can't cover an item with itself.\")\n return False\n if cover_with.db.covered_by:\n self.caller.msg(\"Your %s is covered by %s.\" % (cover_with.name, _INFLECT.an(cover_with.db.covered_by.name)))\n return False\n\n return True\n\n def count_type(self, type):\n count = 0\n for obj in self.clothing_list:\n if obj.tags.has(type, category=_CLOTHING_TAG_CATEGORY):\n count += 1\n \n return count\n \n def get_outfit(self, sorted=True):\n \"\"\"\n Returns the appearance of all worn and visible clothing items.\n \n Args:\n sorted (bool): Whether or not the resulting list is sorted by _LAYERS_ORDER\n \n Returns:\n list of strings\n \"\"\"\n # sort the worn objects by the order options\n if sorted and _CLOTHING_TYPE_ORDER:\n obj_dict = {}\n extra = []\n for obj in self.visible:\n # separate visible clothing by type, for sorting\n type = obj.tags.get(category=_CLOTHING_TAG_CATEGORY)\n if type in _CLOTHING_TYPE_ORDER:\n if type in obj_dict:\n obj_dict[type].append(obj)\n else:\n obj_dict[type] = [obj]\n else:\n extra.append(obj)\n obj_list = []\n # add the clothing objects in the type order\n for type in _CLOTHING_TYPE_ORDER:\n if type in obj_dict:\n obj_list += obj_dict[type]\n # anything not specified in the order list goes at the end\n obj_list += extra\n else:\n obj_list = self.visible\n # get the actual appearances\n appearance_list = []\n for obj in obj_list:\n try:\n appearance = obj.get_worn_desc()\n except:\n # fallback to allow other classes of objects to be worn\n appearance = _INFLECT.an(obj.key)\n appearance_list.append(appearance)\n \n return appearance_list\n \n \n\nclass ClothedCharacter(DefaultCharacter):\n \"\"\"\n Typeclass for clothing-aware characters.\n \n Overloads base `return_appearance` hooks to include worn clothing, and adds\n a handler to manage wearables.\n \"\"\"\n # Define a new appearance template to better display clothing.\n # RECOMMENDATION: Set up the funcparser and use $pron instead of {name}\n appearance_template = \"\"\"\n{header}\n|c{name}|n\n{desc}\n\n{name} is wearing {clothing}.\n\n{name} is carrying {things}.\n{footer}\n \"\"\"\n\n @lazy_property\n def clothing(self):\n return ClothingHandler(self)\n\n def get_visible_contents(self, looker, **kwargs):\n # filter out items that are being worn, since they're handled separately\n def filter_visible(obj_list):\n return [obj for obj in obj_list if obj != looker and obj.access(looker, \"view\") and not obj in self.clothing.all]\n\n return {\n \"exits\": filter_visible(self.contents_get(content_type=\"exit\")),\n \"characters\": filter_visible(self.contents_get(content_type=\"character\")),\n \"things\": filter_visible(self.contents_get(content_type=\"object\")),\n }\n\n def return_appearance(self, looker, **kwargs):\n if not looker:\n return \"\"\n\n name = self.get_display_name(looker, **kwargs)\n desc = self.db.desc\n\n # contents\n content_names_map = self.get_content_names(looker, **kwargs)\n exits = list_to_string(content_names_map[\"exits\"])\n characters = list_to_string(content_names_map[\"characters\"])\n things = list_to_string(content_names_map[\"things\"])\n # adds the worn outfit separately\n clothing = list_to_string(self.clothing.get_outfit())\n\n return self.appearance_template.format(\n header=\"\",\n name=name,\n desc=desc,\n clothing=clothing if clothing else \"nothing\",\n characters=characters,\n things=things if things else \"nothing\",\n footer=\"\",\n ).strip()\n\n\nclass ContribClothing(DefaultObject):\n def get_worn_desc(self):\n description = self.db.desc[0].lower() + self.db.desc[1:] if len(self.db.desc) > 1 else self.db.desc.lower()\n if description[-1] in [\".\",\"!\",\"?\"]:\n description = description[:-1]\n # append worn style\n description = f\"{description} {self.db.worn}\" if self.db.worn else description\n return description\n \n \n def get_extra_info(self, looker, **kwargs):\n if self.location == looker:\n if self in looker.clothing.all:\n return \" (worn)\"\n return \" (carried)\"\n return \"\"\n\n\n# COMMANDS START HERE\n\nclass CmdWear(MuxCommand):\n \"\"\"\n Puts on an item of clothing you are holding.\n\n Usage:\n wear [= wear style]\n\n Examples:\n wear shirt\n wear scarf = wrapped loosely about the shoulders\n\n All the clothes you are wearing are appended to your description.\n If you provide a 'wear style' after the command, the message you\n provide will be displayed after the clothing's name.\n \"\"\"\n\n key = \"wear\"\n help_category = \"Clothing\"\n\n def func(self):\n \"\"\"\n This performs the actual command.\n \"\"\"\n caller = self.caller\n \n if not self.args:\n if _WORNSTRING_MAX_LENGTH:\n caller.msg(\"Usage: wear [= wear style]\")\n else:\n caller.msg(\"Usage: wear \")\n return\n\n obj = caller.search(self.lhs, candidates=caller.contents)\n if not obj:\n return\n\n if obj in caller.clothing.all and not self.rhs:\n caller.msg(\"You're already wearing that.\")\n return\n\n if self.rhs and _WORNSTRING_MAX_LENGTH:\n # If length of wearstyle exceeds limit\n if len(self.rhs) > _WORNSTRING_MAX_LENGTH:\n caller.msg(\n \"Please keep your wear style message to less than %i characters.\"\n % _WORNSTRING_MAX_LENGTH\n )\n return\n elif not _WORNSTRING_MAX_LENGTH:\n self.rhs = None\n\n if caller.clothing.can_add(obj):\n msg = caller.clothing.add(obj, style=self.rhs)\n if msg:\n caller.location.msg_contents(msg)\n\n\nclass CmdRemove(MuxCommand):\n \"\"\"\n Takes off an item of clothing.\n\n Usage:\n remove \n\n Removes an item of clothing you are wearing. You can't remove clothes\n that are being covered by something else.\n \"\"\"\n\n key = \"remove\"\n help_category = \"Clothing\"\n\n def func(self):\n \"\"\"\n This performs the actual command.\n \"\"\"\n caller = self.caller\n\n if not self.args:\n caller.msg(\"Usage: remove \")\n return\n \n obj = caller.search(self.args.strip(), candidates=caller.contents)\n if not obj:\n return\n\n if caller.clothing.can_remove(obj):\n msg = caller.clothing.remove(obj)\n if msg:\n caller.location.msg_contents(msg)\n\n\nclass CmdCover(MuxCommand):\n \"\"\"\n Covers a worn item of clothing with another you're holding or wearing.\n\n Usage:\n cover with \n\n When you cover a clothing item, it is hidden and no longer appears in\n your description until it's uncovered or the item covering it is removed.\n You can't remove an item of clothing if it's covered.\n \"\"\"\n\n key = \"cover\"\n help_category = \"clothing\"\n rhs_split = (\" with \",)\n\n def func(self):\n \"\"\"\n This performs the actual command.\n \"\"\"\n\n caller = self.caller\n if not self.rhs or not self.lhs:\n self.caller.msg(\"Usage: cover with \")\n return\n\n argslist = [ self.lhs, self.rhs ]\n objs = []\n \n for arg in argslist:\n obj = caller.search(arg, candidates=caller.contents)\n if not obj:\n return\n else:\n objs.append(obj)\n\n to_cover = objs[0]\n cover_with = objs[1]\n\n if to_cover not in caller.clothing.all:\n caller.msg(\"You're not wearing %s.\" % _INFLECT.an(to_cover.name))\n return\n \n if caller.clothing.can_cover(to_cover, cover_with):\n to_cover.db.covered_by = cover_with\n message = f\"{caller.name} covers {_INFLECT.an(to_cover.name)} with {_INFLECT.an(cover_with.name)}.\"\n if cover_with not in caller.clothing.all:\n caller.clothing.add(cover_with, quiet=True ) # Put on the item to cover with if it's not on already\n\n caller.location.msg_contents(message)\n\n\nclass CmdUncover(MuxCommand):\n \"\"\"\n Reveals a worn item of clothing that's currently covered up.\n\n Usage:\n uncover \n\n When you uncover an item of clothing, you allow it to appear in your\n description without having to take off the garment that's currently\n covering it. You can't uncover an item of clothing if the item covering\n it is also covered by something else.\n \"\"\"\n\n key = \"uncover\"\n help_category = \"clothing\"\n\n def func(self):\n \"\"\"\n This performs the actual command.\n \"\"\"\n caller = self.caller\n if not self.args:\n caller.msg(\"Usage: uncover \")\n return\n target = self.args.strip()\n obj = caller.search(target, candidates=caller.contents)\n if not obj:\n return\n\n if obj not in caller.clothing.all:\n caller.msg(\"You're not wearing %s.\" % _INFLECT.an(obj.name))\n return\n covered_by = obj.db.covered_by\n if not covered_by:\n caller.msg(\"Your %s isn't covered by anything.\" % obj.name)\n return\n if covered_by.db.covered_by:\n caller.msg(\"Your %s is under too many layers to uncover.\" % (obj.name))\n return\n message = \"{name} uncovers {clothing}.\".format(name=caller.name, clothing=_INFLECT.an(obj.name))\n caller.location.msg_contents(message)\n obj.db.covered_by = None\n\n\nclass CmdInventory(MuxCommand):\n \"\"\"\n view inventory\n\n Usage:\n inventory\n inv\n\n Shows your inventory.\n \"\"\"\n\n # Alternate version of the inventory command which separates\n # worn and carried items.\n\n key = \"inventory\"\n aliases = [\"inv\", \"i\"]\n locks = \"cmd:all()\"\n arg_regex = r\"$\"\n\n def func(self):\n \"\"\"check inventory\"\"\"\n caller = self.caller\n\n clothing = caller.clothing.all\n carried = [obj for obj in caller.contents if obj not in clothing]\n \n def _fill_columns(obj_list):\n cols_list = []\n if len(obj_list) > 10:\n if len(obj_list) < 20:\n cols_list.append(EvColumn(*obj_list[:10]))\n cols_list.append(EvColumn(*obj_list[10:]))\n\n else:\n split = int(len(obj_list)/2)\n cols_list.append(EvColumn(*obj_list[:split]))\n cols_list.append(EvColumn(*obj_list[split:]))\n\n else:\n cols_list.append(EvColumn(*obj_list))\n \n return cols_list\n\n # build carried inventory\n if len(carried) > 0:\n # group all same-named things under one name\n carried_dict = defaultdict(list)\n for thing in carried:\n carried_dict[thing.get_display_name(caller)].append(thing)\n\n # pluralize same-named things\n carried_names = []\n for thingname, thinglist in sorted(carried_dict.items()):\n nthings = len(thinglist)\n thing = thinglist[0]\n singular, plural = thing.get_numbered_name(nthings, caller, key=thingname)\n carried_names.append(singular if nthings == 1 else plural)\n carried_names = [\"%s\" % name for name in carried_names]\n\n carry_col_list = _fill_columns(carried_names)\n carry_table = EvTable(table = carry_col_list, border=\"none\")\n else:\n carry_table = \" Nothing.\"\n\n # build worn inventory\n if len(clothing) > 0:\n clothing_names = [\"|C%s|n%s\" % (_INFLECT.an(item.get_display_name(caller)), \" (hidden)\" if item.db.covered_by else \"\") for item in clothing]\n clothing_col_list = _fill_columns(clothing_names)\n clothing_table = EvTable(table = clothing_col_list, border=\"none\")\n else:\n clothing_table = \" Nothing.\"\n\n # output to caller\n caller.msg(\"|cYou are carrying:|n\")\n caller.msg(carry_table)\n caller.msg(\"|cYou are wearing:|n\")\n caller.msg(clothing_table)\n\nclass CmdDrop(MuxCommand):\n \"\"\"\n drop something\n\n Usage:\n drop \n\n Lets you drop an object from your inventory into the\n location you are currently in.\n \"\"\"\n\n key = \"drop\"\n locks = \"cmd:all()\"\n arg_regex = r\"\\s|$\"\n\n def func(self):\n \"\"\"Implement command\"\"\"\n\n caller = self.caller\n if not self.args:\n caller.msg(\"Drop what?\")\n return\n\n obj = caller.search(\n self.args,\n location=caller,\n nofound_string=\"You aren't carrying any %s.\" % self.args,\n multimatch_string=\"You carry more than one %s:\" % self.args,\n )\n if not obj:\n return\n\n if obj in caller.clothing.all:\n if not caller.clothing.can_remove(obj):\n return\n remove_msg = caller.clothing.remove(obj)\n caller.location.msg_contents(remove_msg)\n\n obj.move_to(caller.location, quiet=True)\n caller.msg(\"You drop %s.\" % _INFLECT.an(obj.name) )\n caller.location.msg_contents(\"%s drops %s.\" % (caller.name, _INFLECT.an(obj.name)), exclude=caller)\n obj.at_drop(caller)\n\n\nclass CmdGive(MuxCommand):\n \"\"\"\n give away something to someone\n Usage:\n give = \n Gives an items from your inventory to another character,\n placing it in their inventory.\n \"\"\"\n\n key = \"give\"\n locks = \"cmd:all()\"\n rhs_split = (\" to \",\"=\")\n arg_regex = r\"\\s|$\"\n\n def func(self):\n \"\"\"Implement give\"\"\"\n\n caller = self.caller\n if not self.args or not self.rhs:\n caller.msg(\"Usage: give to \")\n return\n\n obj = caller.search(\n self.lhs,\n location=caller,\n nofound_string=\"You aren't carrying %s.\" % self.lhs,\n multimatch_string=\"You carry more than one %s:\" % self.lhs,\n )\n if not obj:\n return\n target = caller.search(self.rhs)\n if not target:\n return\n if target == caller:\n caller.msg(\"You keep %s to yourself.\" % obj.key)\n return\n if not obj.location == caller:\n caller.msg(\"You are not holding %s.\" % obj.key)\n return\n\n if obj in caller.clothing.all:\n if not caller.clothing.can_remove(obj):\n return\n remove_msg = caller.clothing.remove(obj)\n caller.location.msg_contents(remove_msg)\n\n caller.msg(\"You give %s to %s.\" % (_INFLECT.an(obj.key), target.key))\n obj.move_to(target, quiet=True)\n target.msg(\"%s gives you %s.\" % (caller.key, _INFLECT.an(obj.key)))\n # Call the object's at_give() method.\n obj.at_give(caller, target)\n\n\nclass ClothedCharacterCmdSet(CmdSet):\n \"\"\"\n Command set for managing worn clothing, including an adapted version of\n `inventory` that separates carried vs worn items.\n \"\"\"\n\n def at_cmdset_creation(self):\n \"\"\"\n Populates the cmdset\n \"\"\"\n super().at_cmdset_creation()\n #\n # any commands you add below will overload the default ones.\n #\n self.add(CmdWear())\n self.add(CmdRemove())\n self.add(CmdCover())\n self.add(CmdUncover())\n self.add(CmdInventory())\n self.add(CmdDrop())\n self.add(CmdGive())\n","repo_name":"InspectorCaracal/evennia-things","sub_path":"clothing.py","file_name":"clothing.py","file_ext":"py","file_size_in_byte":27336,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"44"} +{"seq_id":"73536692613","text":"\nwhile True:\n try:\n for i in ['a','b','c']:\n print(i**2)\n except TypeError:\n print('The Code sucks!')\n break\n except:\n print('you failed')\n\n else:\n print('it workd out')\n break\n\ntry: \n x = 5\n y = 0\n z = x/y\nexcept ZeroDivisionError:\n print('You cant divide /0')\nfinally: \n print('All Done!')\n\ndef ask():\n while True:\n try:\n integer = int(input('Type in a number!'))\n except:\n print('try again')\n else:\n print('perfect!')\n break\n\nask()\n\n\n\n","repo_name":"belaboe97/Python","sub_path":"Exceptions.py","file_name":"Exceptions.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"11786607257","text":"import dash_bootstrap_components as dbc\nfrom dash import Input, Output, html\n\n# `options` is provided as an array of dictionaries\nchecklist = html.Div(\n [\n dbc.Checklist(\n [\n {\"label\": \"Option 1\", \"value\": 1},\n {\"label\": \"Option B\", \"value\": 2},\n {\"label\": \"Option III\", \"value\": 3},\n {\"label\": \"4\", \"value\": 4},\n ],\n [3],\n id=\"shorthand-checklist\",\n ),\n ],\n className=\"py-2\",\n)\n\n# All items in this list will have the value the same as the label\nselect = html.Div(\n dbc.Select(\n [\"Option 1\", \"Option B\", \"Option III\", 4],\n \"Option III\",\n id=\"shorthand-select\",\n ),\n className=\"py-2\",\n)\n\n# `options` is provided as value: label pairs - value must be a string\nradioitems = html.Div(\n [\n dbc.RadioItems(\n {\n \"1\": \"Option 1\",\n \"2\": \"Option B\",\n \"3\": \"Option III\",\n \"4\": 4,\n },\n \"3\",\n id=\"shorthand-radio\",\n ),\n ],\n className=\"py-2\",\n)\n\nshort_hand = html.Div(\n [\n dbc.Form([checklist, select, radioitems]),\n html.P(id=\"shorthand-output\"),\n ]\n)\n\n\n@app.callback(\n Output(\"shorthand-output\", \"children\"),\n [\n Input(\"shorthand-checklist\", \"value\"),\n Input(\"shorthand-select\", \"value\"),\n Input(\"shorthand-radio\", \"value\"),\n ],\n)\ndef on_form_change(checklist_value, select_value, radio_items_value):\n checklist = \", \".join([str(c) for c in checklist_value])\n\n output = (\n f\"Checklist: [{checklist}], Selected: {select_value}, \",\n f\"Radio: {radio_items_value}\",\n )\n\n return output\n","repo_name":"facultyai/dash-bootstrap-components","sub_path":"docs/components_page/components/input/short_hand.py","file_name":"short_hand.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","stars":1025,"dataset":"github-code","pt":"44"} +{"seq_id":"4896051210","text":"import requests\nimport json\njson_url='https://view.inews.qq.com/g2/getOnsInfo?name=disease_other'\nheader={\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36 SE 2.X MetaSr 1.0'\n ,\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36 Edg/96.0.1054.41'\n}\nresp=requests.get(json_url,headers=header)\njson_data=resp.text\nprint(json_data)\nd_data=json.loads(json_data)\nprint(d_data)\ndata_history=json.loads(d_data['data'])\nfor i in data_history.keys():\n print(i)\n print(data_history[i])","repo_name":"Pink-MANmm/web-crawler","sub_path":"flask爬虫/疫情爬虫.py","file_name":"疫情爬虫.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"10488144170","text":"from django.test import TestCase\nfrom django.utils import timezone\nimport la_rifa.models\nimport la_rifa.logic\n\n\n# Create your tests here.\n\n# models test\nclass RifaTest(TestCase):\n\n def create_Rifa(self, title=\"only a test\", body=\"yes, this is only a test\"):\n ri = la_rifa.models.Raffle(name=\"la rifa de pedrito\", created_at=timezone.now())\n ri.save()\n return ri\n\n\n def test_whatever_creation(self):\n self.create_Rifa()\n r = la_rifa.models.Raffle.objects.first()\n\n self.assertTrue(isinstance(r, la_rifa.models.Raffle))\n self.assertEqual(\"la rifa de pedrito\", r.name)\n return r\n\n\n def test_assign_bet(self):\n self.create_Rifa()\n r = la_rifa.models.Raffle.objects.first()\n\n la_rifa.logic.assign_bet(r, 23)\n\n\n def test_check_for_bet(self):\n self.create_Rifa()\n r = la_rifa.models.Raffle.objects.first()\n\n la_rifa.logic.assign_bet(r, 23)\n self.assertIsNotNone(la_rifa.logic.check_for_bet(r, 23))\n\n","repo_name":"tian2992/rifandel","sub_path":"la_rifa/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"32236509026","text":"from os import getcwd\nfrom urllib.parse import urlencode\nfrom pyquery import PyQuery as pq\nimport requests\nimport pandas as pd\nimport re\nimport time\nimport datetime\nimport traceback\nimport random\n\n\n# 获取全文\ndef get_longtext(mid: str):\n url = f\"https://m.weibo.cn/statuses/extend?id={mid}\"\n resp = requests.get(url, timeout=60).json()\n all_text = pq(resp['data']['longTextContent']).text().replace('\\n', '.')\n return all_text\n\n\n# 获取用户发布的微博文字和图片\ndef get_user_weibo(uid, cookie, page_num):\n base_url = 'https://m.weibo.cn/api/container/getIndex?'\n headers = {\n 'Host': 'm.weibo.cn',\n 'Referer': f'https://m.weibo.cn/u/{uid}',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',\n 'X-Requested-With': 'XMLHttpRequest',\n 'cookie': cookie\n }\n params = {\n 'type': 'uid',\n 'value': uid,\n 'containerid': '107603' + uid, # 待获取的用户的containerid. “微博”页的containerid='107603'+uid; “超话”页的containerid='231475'+uid;\n 'page': page_num\n }\n url = base_url + urlencode(params)\n try:\n response = requests.get(url, headers=headers)\n if response.status_code == 200 & response.json().get('ok') == 1:\n items = response.json().get('data').get('cards') # items是一个数组list []\n weibo_list = []\n pic_list = []\n for item in items:\n if item.get('card_type') == 9: # card_type == 9的才是博文,card_type == 11/1不清楚类型\n item = item.get('mblog') # item是一个字典dict{}\n weibo = {}\n weibo['id'] = item.get('id') # 微博的id\n weibo['text'] = item.get('text') # 微博的文字\n weibo['comments_count'] = item.get('comments_count') # 微博的评论数量\n weibo['attitudes_count'] = item.get('attitudes_count') # 微博的点赞数量\n weibo['reposts_count'] = item.get('reposts_count') # 微博的转发数量\n weibo['created_at'] = item.get('created_at') # 微博创建日期\n weibo['isLongText'] = item.get('isLongText') # 是否超过140个字符\n weibo['pic_num'] = item.get('pic_num') # 图片数量\n # 如果isLongText=true, 则获取全文\n if item.get('isLongText'):\n extend_id = re.findall(r'href=\"/status/(.+?)\"', weibo['text'])[0]\n weibo['text'] = get_longtext(extend_id)\n else:\n weibo['text'] = pq(item.get('text')).text().replace('\\n', '.')\n weibo_list.append(weibo)\n # 如果图片的数量大于0,则爬取图片url\n if item.get('pic_num') > 0:\n for pic in item.get('pics'):\n pic_url = pic['large']['url']\n pic_list.append(pic_url)\n return weibo_list, pic_list\n except Exception as e:\n print(traceback.print_exc())\n\n\n# 保存解析结果到csv文档\ndef save_result(uid, page_num, result_list):\n csv_path = getcwd() + f'\\\\{uid}.csv'\n df = pd.DataFrame(result_list)\n if page_num == 1:\n df.to_csv(csv_path, mode='w', index=False, header=True, encoding='utf-8_sig')\n else:\n df.to_csv(csv_path, mode='a', index=False, header=False, encoding='utf-8_sig')\n\n\n# 保存图片url到txt文档\ndef save_url(uid, page_num, pic_list):\n if page_num == 1:\n f = open(getcwd() + f'\\\\{uid}_img.txt', \"w\", encoding='utf-8')\n url_str = ''\n for url in pic_list:\n url_str = url_str + url + '\\n'\n f.write(url_str)\n else:\n f = open(getcwd() + f'\\\\{uid}_img.txt', \"a\", encoding='utf-8')\n url_str = ''\n for url in pic_list:\n url_str = url_str + url + '\\n'\n f.write(url_str)\n\n\n# 计算帖子发布的时间与当天0点时间的比较(为了只获取当前发布的帖子)\ndef compare_time(post_time):\n post_time = time.mktime(time.strptime(post_time, '%a %b %d %X %z %Y'))\n today_time = time.mktime(datetime.date.today().timetuple())\n return int(post_time) - int(today_time)\n\n\n# 获取单条微博的信息:创建时间\ndef get_post_time(post_id):\n url = f\"https://m.weibo.cn/statuses/show?id={post_id}\"\n resp = requests.get(url, timeout=60).json()\n create_time = resp['data']['created_at']\n return create_time\n\n\n# 获取超话参数\ndef get_super_topic_id(uid, cookie):\n base_url = 'https://m.weibo.cn/api/container/getIndex?'\n headers = {\n 'Host': 'm.weibo.cn',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',\n 'X-Requested-With': 'XMLHttpRequest',\n 'cookie': cookie # param\n }\n params = {\n 'type': 'uid',\n 'value': uid,\n 'containerid': '231475' + uid, # 待获取的用户的containerid. “微博”页的containerid='107603'+uid; “超话”页的containerid='231475'+uid;\n }\n url = base_url + urlencode(params)\n print(url)\n try:\n response = requests.get(url, headers=headers)\n if response.status_code == 200 and response.json().get('ok') == 1:\n super_topic_id = response.json().get('data').get('cardlistInfo').get('hide_oids')[0].split(':')[1]\n print('super_topic_id: ', super_topic_id)\n return super_topic_id\n except Exception as e:\n print(traceback.print_exc())\n\n\n# 获取用户关联的微博超话\ndef get_super_topic(cookie, super_topic_id, since_id):\n sleep = random.randint(1, 60)\n print('Sleep seconds: ', sleep)\n time.sleep(sleep)\n base_url = 'https://m.weibo.cn/api/container/getIndex?'\n headers = {\n 'Host': 'm.weibo.cn',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',\n 'X-Requested-With': 'XMLHttpRequest',\n 'cookie': cookie # param\n }\n params1 = {\n 'containerid': f'{super_topic_id}_-_sort_time' # param\n }\n # 存在since_id\n params2 = {\n 'containerid': f'{super_topic_id}_-_sort_time', # param\n 'since_id': since_id # param\n }\n if since_id:\n url = base_url + urlencode(params2)\n else:\n url = base_url + urlencode(params1)\n print(url)\n try:\n response = requests.get(url, headers=headers)\n if response.status_code == 200:\n # 获取当前页微博信息\n card_items = response.json().get('data').get('cards')\n pic_list = []\n result_list = []\n for card_item in card_items:\n card_groups = card_item.get('card_group')\n for item in card_groups:\n if item.get('card_type') == '9':\n item = item.get('mblog')\n time.sleep(1)\n create_time = get_post_time(item.get('id'))\n # print('create_time: ', create_time)\n if compare_time(create_time) < 0:\n # 将结果写入csv文件\n today = str(datetime.date.today())\n csv_path = getcwd() + f'\\\\{super_topic_id}_{today}.csv'\n df = pd.DataFrame(result_list)\n print(since_id)\n if since_id == '':\n df.to_csv(csv_path, mode='w', index=False, header=True, encoding='utf-8_sig')\n else:\n df.to_csv(csv_path, mode='a', index=False, header=False, encoding='utf-8_sig')\n print(u'超话获取结束')\n return None\n else:\n posts = {}\n posts['id'] = item.get('id')\n posts['user'] = str(item.get('user')['id']) # 发帖子的用户的id\n posts['text'] = item.get('text') # 文字\n posts['reposts_count'] = item.get('reposts_count') # 转发数量\n posts['comments_count'] = item.get('comments_count') # 评论数量\n posts['attitudes_count'] = item.get('attitudes_count') # 点赞数量\n posts['created_at'] = create_time # 创建时间\n posts['isLongText'] = item.get('isLongText') # 是否isLongText\n posts['is_imported_topic'] = item.get('is_imported_topic') #\n posts['pic_num'] = item.get('pic_num') # 图片数量\n posts['mblog_vip_type'] = item.get('mblog_vip_type') #\n posts['mblogtype'] = item.get('mblogtype') #\n posts['mlevel'] = item.get('mlevel') #\n posts['source'] = item.get('source') #\n # 如果isLongText=true, 则获取全文\n if item.get('isLongText'):\n extend_id = re.findall(r'href=\"/status/(.+?)\"', posts['text'])[0]\n posts['text'] = get_longtext(extend_id)\n else:\n posts['text'] = pq(item.get('text')).text().replace('\\n', '.')\n # print(posts)\n result_list.append(posts)\n # 如果图片的数量大于0,则爬取图片url\n if item.get('pic_num') > 0:\n for pic in item.get('pics'):\n pic_url = pic['large']['url']\n pic_list.append(pic_url)\n # 将结果写入csv文件\n today = str(datetime.date.today())\n csv_path = getcwd() + f'\\\\{super_topic_id}_{today}.csv'\n df = pd.DataFrame(result_list)\n print(since_id)\n if since_id == '':\n df.to_csv(csv_path, mode='w', index=False, header=True, encoding='utf-8_sig')\n else:\n df.to_csv(csv_path, mode='a', index=False, header=False, encoding='utf-8_sig')\n\n # 获取since_id, 用于下一页request\n since_id = response.json().get('data').get('pageInfo').get('since_id')\n # print('since_id: ', since_id)\n return get_super_topic(super_topic_id, since_id)\n except requests.ConnectionError as e:\n print('Error: ', e.args)\n\n\n# 获取用户基本资料:账号信息,个人信息\ndef get_user_basicinfo(uid, cookie):\n base_url = 'https://m.weibo.cn/api/container/getIndex?'\n # 要加cookie才能获取完整的基本资料,否则只能获取到前2项\n headers = {\n 'Host': 'm.weibo.cn',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',\n 'X-Requested-With': 'XMLHttpRequest',\n 'cookie': cookie\n }\n containerid = '230283' + str(uid) + '_-_INFO'\n lfid = '230283' + str(uid)\n params = {\n 'containerid': containerid, # param\n 'title': '基本资料',\n 'luicode': '10000011',\n 'lfid': lfid # param\n }\n url = base_url + urlencode(params)\n try:\n time.sleep(1)\n response = requests.get(url, headers=headers)\n if response.status_code == 200 and response.json().get('ok') == 1:\n account_items = response.json().get('data').get('cards')[0].get('card_group')\n person_items = response.json().get('data').get('cards')[1].get('card_group')\n basic_info = {'注册时间': '', '阳光信用': '', '生日': '', '感情状况': '', '所在地': '', '家乡': '', '公司': ''}\n for account_item in account_items:\n if account_item.get('card_type') == 41:\n if account_item.get('item_name') == '注册时间':\n basic_info['注册时间'] = account_item.get('item_content')\n elif account_item.get('item_name') == '阳光信用':\n basic_info['阳光信用'] = account_item.get('item_content')\n # key = account_item.get('item_name')\n # value = account_item.get('item_content')\n # basic_info.update({key: value})\n for person_item in person_items:\n if person_item.get('card_type') == 41:\n if person_item.get('item_name') == '生日':\n basic_info['生日'] = person_item.get('item_content')\n elif person_item.get('item_name') == '感情状况':\n basic_info['感情状况'] = person_item.get('item_content')\n elif person_item.get('item_name') == '所在地':\n basic_info['所在地'] = person_item.get('item_content')\n elif person_item.get('item_name') == '家乡':\n basic_info['家乡'] = person_item.get('item_content')\n elif person_item.get('item_name') == '公司':\n basic_info['公司'] = person_item.get('item_content')\n elif person_item.get('item_name') in ('大学', '高中', '中专技校', '初中', '小学', '高职', '海外'):\n key = person_item.get('item_name')\n value = person_item.get('item_content')\n basic_info.update({key: value})\n return basic_info\n except Exception as e:\n print(traceback.print_exc())\n\n\n# 获取博主关注的人\ndef get_followers(uid, cookie, page_num):\n base_url = 'https://m.weibo.cn/api/container/getSecond?'\n headers = {\n 'Host': 'm.weibo.cn',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',\n 'X-Requested-With': 'XMLHttpRequest',\n 'cookie': cookie\n }\n params = {\n 'containerid': f'100505{uid}_-_FOLLOWERS', # param\n 'page': page_num\n }\n url = base_url + urlencode(params)\n try:\n response = requests.get(url, headers=headers)\n if response.status_code == 200:\n items = response.json().get('data').get('cards')\n for item in items:\n item = item.get('user')\n followers = {}\n followers['id'] = item.get('id')\n followers['screen_name'] = item.get('screen_name') # 姓名\n followers['gender'] = item.get('gender') # 性别:f为女,m为男\n followers['statuses_count'] = item.get('statuses_count') # 发过的博客数量\n followers['verified'] = item.get('verified') # 是否认证\n followers['verified_type'] = item.get('verified_type') # -1 为没认证;0为个人认证;其余为企业认证\n followers['verified_type_ext'] = item.get('verified_type_ext') # 1为橙色V;0为黄色V\n followers['verified_reason'] = item.get('verified_reason') # 认证说明\n followers['mbrank'] = item.get('mbrank') # 会员等级\n followers['mbtype'] = item.get('mbtype') # 会员类型:12都是个人账户,0也是。2有个人账户也有企业账户,11也是企业账户\n followers['urank'] = item.get('urank') # 用户等级\n followers['follow_count'] = item.get('follow_count') # 关注数量\n followers['followers_count'] = item.get('followers_count') # 粉丝数量\n followers['description'] = item.get('description') # 简介\n # 获取更多基本资料\n more_info = get_user_basicinfo(item.get('id'))\n followers.update(more_info)\n yield followers\n except Exception as e:\n print(traceback.print_exc())\n\n\n# 获取博主的粉丝\ndef get_fans(uid, cookie, page_num):\n base_url = 'https://m.weibo.cn/api/container/getSecond?'\n headers = {\n 'Host': 'm.weibo.cn',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',\n 'X-Requested-With': 'XMLHttpRequest',\n 'cookie': cookie\n }\n params = {\n 'containerid': f'100505{uid}_-_FANS', # param\n 'page': page_num\n }\n url = base_url + urlencode(params)\n try:\n response = requests.get(url, headers=headers)\n if response.status_code == 200:\n fans_list =[]\n items = response.json().get('data').get('cards')\n for item in items:\n item = item.get('user')\n fans = {}\n fans['id'] = item.get('id')\n fans['screen_name'] = item.get('screen_name') # 姓名\n fans['gender'] = item.get('gender') # 性别:f为女,m为男\n fans['statuses_count'] = item.get('statuses_count') # 发过的博客数量\n fans['verified'] = item.get('verified') # 是否认证\n fans['verified_type'] = item.get('verified_type') # -1 为没认证;0为个人认证;其余为企业认证\n fans['mbrank'] = item.get('mbrank') # 会员等级\n fans['mbtype'] = item.get('mbtype') # 会员类型:0, 12都是个人账户;2有个人账户也有企业账户;11是企业账户\n fans['urank'] = item.get('urank') # 用户等级\n fans['follow_count'] = item.get('follow_count') # 关注数量\n fans['followers_count'] = item.get('followers_count') # 粉丝数量\n fans['description'] = item.get('description') # 简介\n # 获取更多基本资料\n more_info = get_user_basicinfo(item.get('id'))\n fans.update(more_info)\n fans_list.append(fans)\n # 将结果写入csv文件\n csv_path = getcwd() + f'\\\\{uid}_fans.csv'\n df = pd.DataFrame(fans_list)\n if page_num == 1:\n df.to_csv(csv_path, mode='w', index=False, header=True, encoding='utf-8_sig')\n else:\n df.to_csv(csv_path, mode='a', index=False, header=False, encoding='utf-8_sig')\n except Exception as e:\n print(traceback.print_exc())\n\n\n# 获取博主全部的粉丝\ndef get_fans_all(uid, cookie):\n page_num = 1\n while page_num:\n print('Begin getting data of page: ', page_num)\n base_url = 'https://m.weibo.cn/api/container/getSecond?'\n headers = {\n 'Host': 'm.weibo.cn',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',\n 'X-Requested-With': 'XMLHttpRequest',\n 'cookie': cookie\n }\n params = {\n 'containerid': f'100505{uid}_-_FANS', # param\n 'page': page_num\n }\n url = base_url + urlencode(params)\n try:\n response = requests.get(url, headers=headers)\n if response.status_code == 200 and response.json().get('ok') == 1:\n fans_list = []\n items = response.json().get('data').get('cards')\n for item in items:\n item = item.get('user')\n fans = {}\n fans['id'] = item.get('id')\n fans['screen_name'] = item.get('screen_name') # 姓名\n fans['gender'] = item.get('gender') # 性别:f为女,m为男\n fans['statuses_count'] = item.get('statuses_count') # 发过的博客数量\n fans['verified'] = item.get('verified') # 是否认证\n fans['verified_type'] = item.get('verified_type') # -1 为没认证;0为个人认证;其余为企业认证\n fans['mbrank'] = item.get('mbrank') # 会员等级\n fans['mbtype'] = item.get('mbtype') # 会员类型:0, 12都是个人账户;2有个人账户也有企业账户;11是企业账户\n fans['urank'] = item.get('urank') # 用户等级\n fans['follow_count'] = item.get('follow_count') # 关注数量\n fans['followers_count'] = item.get('followers_count') # 粉丝数量\n fans['description'] = item.get('description') # 简介\n # 获取更多基本资料\n more_info = get_user_basicinfo(item.get('id'), cookie)\n fans.update(more_info)\n fans_list.append(fans)\n # 将结果写入csv文件\n csv_path = getcwd() + f'\\\\{uid}_fans.csv'\n df = pd.DataFrame(fans_list)\n if page_num == 1:\n df.to_csv(csv_path, mode='w', index=False, header=True, encoding='utf-8_sig')\n else:\n df.to_csv(csv_path, mode='a', index=False, header=False, encoding='utf-8_sig')\n else:\n # response.json().get('ok') == 0时结束\n print('End')\n return None\n except requests.ConnectionError as e:\n print('Error: ', e.args)\n # 该轮循环结束,page_num增加1,进入下一轮循环\n print('End getting data of page: ', page_num)\n page_num = page_num + 1\n # random sleep\n sleep = random.randint(10, 120)\n print('Sleep seconds: ', sleep)\n time.sleep(sleep)\n\n\n# 获取当前/每日微博热搜50条\ndef get_realtime_hot():\n base_url = 'https://m.weibo.cn/api/container/getIndex?'\n headers = {\n 'Host': 'm.weibo.cn',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',\n 'X-Requested-With': 'XMLHttpRequest'\n }\n extparam = 'cate=10103&pos=0_0&mi_cid=100103&filter_type=realtimehot&c_type=30&display_time=' + str(int(time.time()))\n print(extparam)\n params = {\n 'containerid': '106003type=25&t=3&disable_hot=1&filter_type=realtimehot',\n 'title': '微博热搜',\n 'extparam': extparam,\n 'luicode': '10000011',\n 'lfid': '231583'\n }\n url = base_url + urlencode(params)\n print(url)\n try:\n response = requests.get(url, headers=headers)\n if response.status_code == 200:\n items = response.json().get('data').get('cards')[0].get('card_group')\n for item in items:\n hot = {}\n hot['pic'] = re.findall(r'_img_search_(.+?).png', item.get('pic'))[0] # 话题排名图片:0,1,2,3,……50\n hot['desc'] = item.get('desc') # 话题描述\n if 'desc_extr' in item:\n hot['desc_extr'] = item.get('desc_extr') # 话题被讨论数量,不是所有的都有这个字段,第0条置顶话题没有\n else:\n hot['desc_extr'] = ''\n if 'icon' in item:\n hot['icon'] = re.findall(r'_(.+?).png', item.get('icon'))[0] # 话题状态图片:沸,热,不是所有的都有这个字段\n else:\n hot['icon'] = ''\n yield hot\n except requests.ConnectionError as e:\n print('Error: ', e.args)\n\n\nif __name__ == '__main__':\n uid = '2803301701' # 待获取的用户的uid\n cookie = '' # 当前登录的用户的cookie\n # 获取某用户的超话\n # super_topic_id = get_super_topic_id(uid, cookie)\n # get_super_topic(cookie, super_topic_id, '')\n\n # 获取某用户的粉丝\n # for page_num in range(1, 3):\n # get_fans(uid, cookie, page_num)\n\n # 获取关注的人\n # for page_num in range(1, 3):\n # followers = get_followers(uid, cookie, page_num)\n # for follower in followers:\n # print(follower)\n\n # 获取微博热搜\n # hots = get_realtime_hot()\n # for hot in hots:\n # print(hot)\n\n # 获取用户的微博文字和图片url\n # for page_num in range(1, 3):\n # weibo_list, pic_list = get_user_weibo(uid, cookie, page_num)\n # # 保存解析结果到csv文档\n # save_result(uid, page_num, weibo_list)\n # # 保存图片url到txt文档\n # save_url(uid, page_num, pic_list)\n","repo_name":"JessicaBeiman/weibo_test","sub_path":"weibo.py","file_name":"weibo.py","file_ext":"py","file_size_in_byte":24871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"69979203013","text":"import pandas as pd\nimport math\nimport cv2\nimport numpy as np\nfrom PIL import Image\nimport mediapipe as mp\n\n\nmp_drawing = mp.solutions.drawing_utils\nmp_drawing_styles = mp.solutions.drawing_styles\nmp_hands = mp.solutions.hands\n\ndef removeOutliers(group):\n c = 0\n print(group[\"video\"].values[0])\n compare_stdX = 2.4*group.x.std()\n meanX = group.x.mean()\n compare_stdY = 2.4*group.y.std()\n meanY = group.y.mean()\n count = 0\n print(group[\"bp\"].values[c])\n for i in group[\"x\"].values:\n x_val = group[\"x\"].values[c]\n x_val = np.abs(x_val-meanX)\n y_val = group[\"y\"].values[c]\n y_val = np.abs(y_val-meanY)\n if x_val > compare_stdX:\n group[\"x\"].values[c] = np.NaN\n group[\"y\"].values[c] = np.NaN\n count+=1\n if y_val > compare_stdY:\n group[\"x\"].values[c] = np.NaN\n group[\"y\"].values[c] = np.NaN\n count+=1\n c+=1\n return group\n\ndef getBoxCoordinates(coord_HipX, coord_HipY, coord_NeckX, coord_NeckY, pixel_x, pixel_y, orientation=None):\n if (coord_HipX is None or coord_HipY is None or coord_NeckX is None or coord_NeckY is None):\n return (None, None, None)\n distX = abs(coord_HipX - coord_NeckX)\n distY = abs(coord_HipY - coord_NeckY)\n dist = math.sqrt(pow(distX,2) + pow(distY,2))\n size = dist*2\n if (size > pixel_y):\n size = pixel_y\n if (size > pixel_x):\n size = pixel_x\n orientation_new = 0\n if (distX > distY):\n #Horizontal Baby\n if (coord_HipX > coord_NeckX):\n orientation_new = 270\n if orientation_new == orientation or orientation is None:\n #Head to the Left, Hip to the Right\n coordX = coord_NeckX - dist*1.5\n coordY = coord_NeckY - dist\n else:\n orientation_new = 90\n if orientation_new == orientation or orientation is None:\n #Head to the Right, Hip to the Left\n coordX = coord_NeckX - dist*0.5\n coordY = coord_NeckY - dist\n else:\n #Vertical Baby\n if (coord_HipY > coord_NeckY):\n #Head on the top\n if orientation_new == orientation or orientation is None:\n coordY = coord_NeckY - dist*1.5\n coordX = coord_NeckX - dist\n else:\n #Head upside down\n if orientation_new == orientation or orientation is None:\n coordY = coord_NeckY - dist*0.5\n coordX = coord_NeckX - dist\n if orientation_new == orientation or orientation is None:\n if (coordX < 0):\n coordX = 0\n if (coordY < 0):\n coordY = 0\n if (coordX + size > int(pixel_x)):\n coordX = int(pixel_x) - size\n if (coordY + size > int(pixel_y)):\n coordY = int(pixel_y) - size\n return (coordX, coordY, size, orientation_new)\n else:\n return (None, None, None, orientation_new)\n\n\ndef addMinMax(df):\n df['min_x'] = df[x_columns].min(axis=1)\n df['max_x'] = df[x_columns].max(axis=1)\n df['min_y'] = df[y_columns].min(axis=1)\n df['max_y'] = df[y_columns].max(axis=1)\n return df\n\ndef getFaces(df, y_max, x_max, eyeLeft, eyeRight, neck, coordX, coordY, size, angle, limit=False, video_name=None, video_name_now=None):\n faces = []\n not_changed_video = True\n if df is not None:\n for index, f in df.iterrows():\n height = int(f[\"max_x\"]) - int(f[\"min_x\"])\n width = int(f[\"max_y\"]) - int(f[\"min_y\"])\n if (f[\"confidence\"] > 0.1):\n if angle == 0:\n face_coords = (f[\"min_x\"], f[\"min_y\"], f[\"max_x\"], f[\"max_y\"], f[\"eye_lmk_x_1\"], f[\"eye_lmk_y_1\"], f[\"eye_lmk_x_31\"], f[\"eye_lmk_y_31\"], f[\"confidence\"])\n elif angle == 270:\n face_coords = (f[\"min_y\"], x_max - int(f[\"min_x\"]) - width, f[\"max_y\"], x_max - int(f[\"max_x\"]) + width, f[\"eye_lmk_y_1\"], x_max - int(f[\"eye_lmk_x_1\"]), f[\"eye_lmk_y_31\"], x_max - int(f[\"eye_lmk_x_31\"]), f[\"confidence\"])\n else:\n face_coords = (y_max - int(f[\"min_y\"]) - height, int(f[\"min_x\"]), y_max - int(f[\"max_y\"]) + height, int(f[\"max_x\"]), y_max - int(f[\"eye_lmk_y_1\"]), f[\"eye_lmk_x_1\"], y_max - int(f[\"eye_lmk_y_31\"]), f[\"eye_lmk_x_31\"], f[\"confidence\"])\n if (limit):\n if (video_name_now != video_name):\n not_changed_video = False # check that faces are from the same video. If new video, stop searching\n elif (face_coords[0] >= coordX and face_coords[1] >= coordY and face_coords[2] < coordX + size and face_coords[3] < coordY + size):\n faces.append(face_coords)\n else:\n if (face_coords[0] >= coordX and face_coords[1] >= coordY and face_coords[2] < coordX + size and face_coords[3] < coordY + size):\n faces.append(face_coords)\n if (len(faces) == 0):\n if (not np.isnan(eyeLeft[0]) or not np.isnan(eyeRight[0])):\n if (np.isnan(eyeLeft[0])):\n print(\"-\")\n if (np.isnan(eyeRight[0])):\n print(\"-\")\n else:\n distX = abs(eyeLeft[0] - eyeRight[0])\n distY = abs(eyeLeft[1] - eyeRight[1])\n dist_eye = math.sqrt(pow(distX,2) + pow(distY,2))\n if (np.isnan(neck[0])):\n dist = dist_eye\n else:\n distX = abs(eyeLeft[0] - neck[0])\n distY = abs(eyeLeft[1] - neck[1])\n dist_neck = math.sqrt(pow(distX,2) + pow(distY,2))*0.5\n dist = max(dist_eye, dist_neck)\n if angle > 0:\n minX = min(eyeLeft[0], eyeRight[0]) - dist*0.5\n minY = min(eyeLeft[1], eyeRight[1]) - dist*0.5\n maxX = max(eyeLeft[0], eyeRight[0]) + dist*0.5\n maxY = max(eyeLeft[1], eyeRight[1]) + dist*0.5\n else:\n minX = min(eyeLeft[0], eyeRight[0]) - dist*0.5\n minY = min(eyeLeft[1], eyeRight[1]) - dist*0.5\n maxX = max(eyeLeft[0], eyeRight[0]) + dist*0.5\n maxY = max(eyeLeft[1], eyeRight[1]) + dist*0.5\n face_coords = (minX, minY, maxX, maxY, eyeRight[0], eyeRight[1], eyeLeft[0], eyeLeft[1], 1)\n faces.append(face_coords)\n else:\n print(\"-----\")\n if limit:\n return (faces, not_changed_video)\n else:\n return faces\n\ndef getFaceCoordsFinal(faces, faces_90, faces_270, coord_NeckX, coord_NeckY, orientation, oldEyes = True):\n dist_min = 10000\n face_coords_final = face_coords_final_old = None\n faces_loop = None\n other_faces_loop = None\n\n if orientation == 0:\n faces_loop = faces\n other_faces_loop = faces_90.append(faces_270)\n elif orientation == 90:\n faces_loop = faces_90\n other_faces_loop = faces.append(faces_270)\n elif orientation == 270:\n faces_loop = faces_270\n other_faces_loop = faces.append(faces_90)\n \n for f in faces_loop:\n face_eye_coords = (f[4], f[5])\n distX = abs(face_eye_coords[0] - coord_NeckX)\n distY = abs(face_eye_coords[1] - coord_NeckY)\n dist = math.sqrt(pow(distX,2) + pow(distY,2))\n if dist < dist_min and f[8] > 0.02:\n if orientation == 90:\n if coord_NeckX < f[0]:\n face_coords_final = (f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7])\n dist_min = dist\n elif orientation == 270:\n if coord_NeckX > f[2]:\n face_coords_final = (f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7])\n dist_min = dist\n else:\n if coord_NeckY < f[1]:\n face_coords_final = (f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7])\n dist_min = dist\n if (not oldEyes):\n if (face_coords_final is None):\n if other_faces_loop is not None:\n for f in other_faces_loop:\n face_eye_coords = (f[4], f[5])\n distX = abs(face_eye_coords[0] - coord_NeckX)\n distY = abs(face_eye_coords[1] - coord_NeckY)\n dist = math.sqrt(pow(distX,2) + pow(distY,2))\n if dist < dist_min and f[8] > 0.02:\n if orientation == 90:\n if coord_NeckX < f[0]:\n face_coords_final = (f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7])\n dist_min = dist\n elif orientation == 270:\n if coord_NeckX > f[2]:\n face_coords_final = (f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7])\n dist_min = dist\n else:\n if coord_NeckY < f[1]:\n face_coords_final = (f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7])\n dist_min = dist\n if (face_coords_final is None):\n for f in faces_loop:\n face_eye_coords = (f[4], f[5])\n distX = abs(face_eye_coords[0] - coord_NeckX)\n distY = abs(face_eye_coords[1] - coord_NeckY)\n dist = math.sqrt(pow(distX,2) + pow(distY,2))\n if dist < dist_min and f[8] > 0.02:\n face_coords_final = (f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7])\n dist_min = dist\n if (face_coords_final is None):\n if other_faces_loop is not None:\n for f in other_faces_loop:\n face_eye_coords = (f[4], f[5])\n distX = abs(face_eye_coords[0] - coord_NeckX)\n distY = abs(face_eye_coords[1] - coord_NeckY)\n dist = math.sqrt(pow(distX,2) + pow(distY,2))\n if dist < dist_min and f[8] > 0.02:\n face_coords_final = (f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7])\n dist_min = dist\n return face_coords_final\n\ndef alignFace(rightEyeCenter, leftEyeCenter, neck, size, image_s, orientation, y_max, x_max):\n if orientation == 0:\n print(\"orientation 0\")\n elif orientation == 270:\n print(\"orientation 270\")\n rightEyeCenter = (y_max - int(rightEyeCenter[1]), int(rightEyeCenter[0]))\n leftEyeCenter = (y_max - int(leftEyeCenter[1]), int(leftEyeCenter[0]))\n neck = (y_max - int(neck[1]), int(neck[0]))\n image_s = Image.fromarray(image_s).transpose(Image.ROTATE_270)\n image_s = np.array(image_s.convert('RGB'))\n else:\n print(\"orientation 90\")\n rightEyeCenter = (rightEyeCenter[1], x_max - int(rightEyeCenter[0]))\n leftEyeCenter = (leftEyeCenter[1], x_max - int(leftEyeCenter[0]))\n neck = (neck[1], x_max - int(neck[0]))\n image_s = Image.fromarray(image_s).transpose(Image.ROTATE_90)\n image_s = np.array(image_s.convert('RGB'))\n\n dY = rightEyeCenter[1] - leftEyeCenter[1]\n dX = rightEyeCenter[0] - leftEyeCenter[0]\n angle = np.degrees(np.arctan2(dY, dX))\n angle = angle - 180\n\n if ((angle > 45 and angle < 315) or (angle < -45 and angle > -315)):\n angle = 0\n\n desiredRightEyeX = 1.0 - 0.35\n dist_eye = np.sqrt((dX ** 2) + (dY ** 2))\n eyesCenter = (int((leftEyeCenter[0] + rightEyeCenter[0]) // 2), int((leftEyeCenter[1] + rightEyeCenter[1]) // 2))\n if (np.isnan(neck[0])):\n dist = dist_eye\n else:\n distX_l = abs(leftEyeCenter[0] - neck[0])\n distY_l = abs(leftEyeCenter[1] - neck[1])\n distX_r = abs(rightEyeCenter[0] - neck[0])\n distY_r = abs(rightEyeCenter[1] - neck[1])\n dist_neck_l = np.sqrt((distX_l ** 2) + (distY_l ** 2))*0.3\n dist_neck_r = np.sqrt((distX_r ** 2) + (distY_r ** 2))*0.3\n dist_neck = max(dist_neck_l, dist_neck_r)\n\n dist = max(dist_eye, dist_neck) \n if (dist_neck == dist):\n eyesCenter = (int((leftEyeCenter[0] + neck[0]) // 2), int((leftEyeCenter[1] + rightEyeCenter[1]) // 2))\n distY = (distY_l + distY_r)/2.0\n if (dist_eye < 0.3*distY):\n dist = dist*1.6\n else:\n distY = (distY_l + distY_r)/2.0\n if (dist_eye > 3*distY):\n dist = dist/1.5\n\n desiredDist = (desiredRightEyeX - 0.35)\n desiredDist *= size\n scale = desiredDist / dist\n \n M = cv2.getRotationMatrix2D(eyesCenter, angle, scale)\n tX = size * 0.5\n tY = size * 0.35\n M[0, 2] += (tX - eyesCenter[0])\n M[1, 2] += (tY - eyesCenter[1])\n (w, h) = (int(size), int(size))\n\n output = cv2.warpAffine(image_s, M, (w, h), flags=cv2.INTER_CUBIC)\n return output\n \ndef getHandData(hands, file_full, orientation, size, coordX, coordY, sizeX, sizeY, idx): \n hand_found_R = np.nan\n hand_found_L = np.nan\n origin_x_hand_L = np.nan\n origin_y_hand_L = np.nan\n origin_x_hand_R = np.nan\n origin_y_hand_R = np.nan \n \n thumb_finger_x_hand_L = np.nan\n thumb_finger_y_hand_L = np.nan\n thumb_finger_x_hand_R = np.nan\n thumb_finger_y_hand_R = np.nan\n\n index_finger_x_hand_L = np.nan\n index_finger_y_hand_L = np.nan\n index_finger_x_hand_R = np.nan\n index_finger_y_hand_R = np.nan\n\n middle_finger_x_hand_L = np.nan\n middle_finger_y_hand_L = np.nan\n middle_finger_x_hand_R = np.nan\n middle_finger_y_hand_R = np.nan\n\n ring_finger_x_hand_L = np.nan\n ring_finger_y_hand_L = np.nan\n ring_finger_x_hand_R = np.nan\n ring_finger_y_hand_R = np.nan\n\n pinky_finger_x_hand_L = np.nan\n pinky_finger_y_hand_L = np.nan\n pinky_finger_x_hand_R = np.nan\n pinky_finger_y_hand_R = np.nan\n\n img = Image.open(file_full)\n if sizeX is None or sizeY is None:\n if (orientation == 0):\n coordX_new = coordX - size*0.25\n coordY_new = coordY - size*0.1\n sizeX = size*1.5\n sizeY = size*1.6\n if (orientation == 270):\n coordX_new = coordX - size*0.1\n coordY_new = coordY - size*0.25\n sizeX = size*1.6\n sizeY = size*1.5\n if (orientation == 90):\n coordX_new = coordX - size*0.5\n coordY_new = coordY - size*0.25\n sizeX = size*1.6\n sizeY = size*1.5\n else:\n coordX_new = coordX\n coordY_new = coordY\n box = coordX_new, coordY_new, coordX_new+sizeX, coordY_new + sizeY\n img_2 = img.crop(box)\n img_2.save(\"temp + \" + str(orientation) + \".jpg\")\n\n img_cv2 = np.array(img_2.convert('RGB'))\n image = cv2.cvtColor(cv2.flip(img_cv2, 1), cv2.COLOR_RGB2BGR)\n results = hands.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))\n\n image_height, image_width, _ = image.shape\n annotated_image = image.copy()\n\n if not results.multi_hand_landmarks:\n return (hand_found_R, hand_found_L, origin_x_hand_L, origin_y_hand_L, origin_x_hand_R, origin_y_hand_R,\n thumb_finger_x_hand_L, thumb_finger_y_hand_L, thumb_finger_x_hand_R, thumb_finger_y_hand_R,\n index_finger_x_hand_L, index_finger_y_hand_L, index_finger_x_hand_R, index_finger_y_hand_R,\n middle_finger_x_hand_L, middle_finger_y_hand_L, middle_finger_x_hand_R, middle_finger_y_hand_R,\n ring_finger_x_hand_L, ring_finger_y_hand_L, ring_finger_x_hand_R, ring_finger_y_hand_R,\n pinky_finger_x_hand_L, pinky_finger_y_hand_L, pinky_finger_x_hand_R, pinky_finger_y_hand_R)\n else:\n found_left = False\n found_right = False\n for idx_r, hand_handedness in enumerate(results.multi_handedness):\n score = hand_handedness.classification[0].score\n hand_landmarks = results.multi_hand_landmarks[idx_r]\n count_landmark = 0.0\n total_landmark_x = 0\n total_landmark_y = 0\n for landmark in hand_landmarks.landmark:\n total_landmark_x += landmark.x\n total_landmark_y += landmark.y\n count_landmark += 1\n \n thumb_finger_x = hand_landmarks.landmark[4].x*sizeX + coordX_new\n thumb_finger_y = hand_landmarks.landmark[4].y*sizeY + coordY_new\n index_finger_x = hand_landmarks.landmark[8].x*sizeX + coordX_new\n index_finger_y = hand_landmarks.landmark[8].y*sizeY + coordY_new\n middle_finger_x = hand_landmarks.landmark[12].x*sizeX + coordX_new\n middle_finger_y = hand_landmarks.landmark[12].y*sizeY + coordY_new\n ring_finger_x = hand_landmarks.landmark[16].x*sizeX + coordX_new\n ring_finger_y = hand_landmarks.landmark[16].y*sizeY + coordY_new\n pinky_finger_x = hand_landmarks.landmark[20].x*sizeX + coordX_new\n pinky_finger_y = hand_landmarks.landmark[20].y*sizeY + coordY_new\n\n origin_x = total_landmark_x/count_landmark*sizeX + coordX_new\n origin_y = total_landmark_y/count_landmark*sizeY + coordY_new\n\n #distance = math.sqrt(origin_x*origin_x + origin_y*origin_y) \n\n if hand_handedness.classification[0].label == \"Left\":\n if found_left:\n #column_distance_hand_R = distance\n origin_x_hand_R = origin_x\n origin_y_hand_R = origin_y\n thumb_finger_x_hand_R = thumb_finger_x\n thumb_finger_y_hand_R = thumb_finger_y\n index_finger_x_hand_R = index_finger_x\n index_finger_y_hand_R = index_finger_y\n middle_finger_x_hand_R = middle_finger_x\n middle_finger_y_hand_R = middle_finger_y\n ring_finger_x_hand_R = ring_finger_x\n ring_finger_y_hand_R = ring_finger_y\n pinky_finger_x_hand_R = pinky_finger_x\n pinky_finger_y_hand_R = pinky_finger_y\n hand_found_R = score\n found_right = True\n else:\n #column_distance_hand_L = distance\n origin_x_hand_L = origin_x\n origin_y_hand_L = origin_y\n thumb_finger_x_hand_L = thumb_finger_x\n thumb_finger_y_hand_L = thumb_finger_y\n index_finger_x_hand_L = index_finger_x\n index_finger_y_hand_L = index_finger_y\n middle_finger_x_hand_L = middle_finger_x\n middle_finger_y_hand_L = middle_finger_y\n ring_finger_x_hand_L = ring_finger_x\n ring_finger_y_hand_L = ring_finger_y\n pinky_finger_x_hand_L = pinky_finger_x\n pinky_finger_y_hand_L = pinky_finger_y\n hand_found_L = score\n found_left = True\n if hand_handedness.classification[0].label == \"Right\":\n if found_right:\n #column_distance_hand_L = distance\n origin_x_hand_L = origin_x\n origin_y_hand_L = origin_y\n thumb_finger_x_hand_L = thumb_finger_x\n thumb_finger_y_hand_L = thumb_finger_y\n index_finger_x_hand_L = index_finger_x\n index_finger_y_hand_L = index_finger_y\n middle_finger_x_hand_L = middle_finger_x\n middle_finger_y_hand_L = middle_finger_y\n ring_finger_x_hand_L = ring_finger_x\n ring_finger_y_hand_L = ring_finger_y\n pinky_finger_x_hand_L = pinky_finger_x\n pinky_finger_y_hand_L = pinky_finger_y\n hand_found_L = score\n found_left = True\n else:\n #column_distance_hand_R = distance\n origin_x_hand_R = origin_x\n origin_y_hand_R = origin_y\n thumb_finger_x_hand_R = thumb_finger_x\n thumb_finger_y_hand_R = thumb_finger_y\n index_finger_x_hand_R = index_finger_x\n index_finger_y_hand_R = index_finger_y\n middle_finger_x_hand_R = middle_finger_x\n middle_finger_y_hand_R = middle_finger_y\n ring_finger_x_hand_R = ring_finger_x\n ring_finger_y_hand_R = ring_finger_y\n pinky_finger_x_hand_R = pinky_finger_x\n pinky_finger_y_hand_R = pinky_finger_y\n hand_found_R = score\n found_right = True\n\n mp_drawing.draw_landmarks(\n annotated_image,\n hand_landmarks,\n mp_hands.HAND_CONNECTIONS,\n mp_drawing_styles.get_default_hand_landmarks_style(),\n mp_drawing_styles.get_default_hand_connections_style())\n cv2.imwrite(\n '/content/openpose-research-keras/tmp/annotated_image' + str(idx) + '.png', cv2.flip(annotated_image, 1))\n # Draw hand world landmarks.\n if not results.multi_hand_world_landmarks:\n return (hand_found_R, hand_found_L, origin_x_hand_L, origin_y_hand_L, origin_x_hand_R, origin_y_hand_R,\n thumb_finger_x_hand_L, thumb_finger_y_hand_L, thumb_finger_x_hand_R, thumb_finger_y_hand_R,\n index_finger_x_hand_L, index_finger_y_hand_L, index_finger_x_hand_R, index_finger_y_hand_R,\n middle_finger_x_hand_L, middle_finger_y_hand_L, middle_finger_x_hand_R, middle_finger_y_hand_R,\n ring_finger_x_hand_L, ring_finger_y_hand_L, ring_finger_x_hand_R, ring_finger_y_hand_R,\n pinky_finger_x_hand_L, pinky_finger_y_hand_L, pinky_finger_x_hand_R, pinky_finger_y_hand_R)\n #for hand_world_landmarks in results.multi_hand_world_landmarks:\n # mp_drawing.plot_landmarks(\n # hand_world_landmarks, mp_hands.HAND_CONNECTIONS, azimuth=5)\n return (hand_found_R, hand_found_L, origin_x_hand_L, origin_y_hand_L, origin_x_hand_R, origin_y_hand_R,\n thumb_finger_x_hand_L, thumb_finger_y_hand_L, thumb_finger_x_hand_R, thumb_finger_y_hand_R,\n index_finger_x_hand_L, index_finger_y_hand_L, index_finger_x_hand_R, index_finger_y_hand_R,\n middle_finger_x_hand_L, middle_finger_y_hand_L, middle_finger_x_hand_R, middle_finger_y_hand_R,\n ring_finger_x_hand_L, ring_finger_y_hand_L, ring_finger_x_hand_R, ring_finger_y_hand_R,\n pinky_finger_x_hand_L, pinky_finger_y_hand_L, pinky_finger_x_hand_R, pinky_finger_y_hand_R)","repo_name":"bt403/openpose-research-keras","sub_path":"utils_feature_extraction.py","file_name":"utils_feature_extraction.py","file_ext":"py","file_size_in_byte":20031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"15258296962","text":"data = \"이의덕,이재명,권종수,이재수,박철호,강동희,이재수,김지석,최승만,이성만,박영희,박수호,전경식,송우환,김재식,이유정\"\n\n\nnames = data.split(\",\")\n\npark = 0\nkim = 0\n\nfor name in names:\n if name.startswith('박'):\n park += 1\n elif name.startswith('김'):\n kim += 1\n\nprint(kim, park) # 김씨와 박씨 count 출력\nprint(names.count('이재수')) # '이재수'란 이름 count 출력\n\n\nnames = list(set(names))\nprint(names) # 중복을 제거한 이름 출력\nprint(sorted(names)) # 중복을 제거한 이름을 오름차순으로 정렬하여 출력","repo_name":"ganzik83/TIL","sub_path":"Code ex/programming/python/종합문제 1.py","file_name":"종합문제 1.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"44"} +{"seq_id":"43093260262","text":"import time\nimport random\nimport logging\nlogging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')\n\n\n# 冒泡排序算法\ndef bubble_sort(items):\n logging.info('冒泡算法')\n for i in range(len(items)-1):\n for j in range(len(items)-1, i, -1):\n if items[j] < items[j-1]: # 后数小于前数\n items[j], items[j-1] = items[j-1], items[j] # j-1位置与j交换\n # logging.info('发生交换:' + str(items))\n check_sort(items, '原算法')\n\n\n'''冒泡排序算法实际有很多种写法,核心原理为比较相邻两数大小然后进行交换将大数或小数向列表两侧推移,上面的示例程序为将从列表末位将比较的两个数的小的数向\n列表首推移,例如列表[3,2,1]变化如下[3,2,1]->[3,1,2]->[1,3,2]->[1,2,3],将列表看作垂直堆放的一列数据从最下面的一个元素起将较小的元素换到上面,\n未经优化的冒泡算法排序次数最多为n-1次,比较次数为n(n-1)/2\n演示视频:www.bilibili.com/video/BV1qY4y1h7Lz\n(字符串比较ascii码值且只比较字符串首字符如果相同则比较下一字符且大小与长度无关,小写字母>大写字母>数字(数字为字符串格式))'''\n\n\n# 进阶1:冒泡算法的优化方案\ndef optimization_bubble_sort_1(items):\n logging.info('优化1')\n for i in range(len(items)-1):\n flag = False\n for j in range(len(items)-1, i, -1):\n if items[j] < items[j-1]: # 后数小于前数\n items[j], items[j-1] = items[j-1], items[j] # j-1位置与j交换\n flag = True # 发生交换\n logging.info('发生交换:' + str(items))\n if not flag: # 未发生交换时执行\n break\n check_sort(items, '优化1')\n\n\n'''优化方案一:由于冒泡算法每次遍历列表时如果列表无序则必定有位置交换,若无位置交换则列表已有序,由此可推得此优化方案。定义一个flag标记完成一次遍历后是\n否发生交换,若未发生交换则使用break方法结束排序'''\n\n\n# 进阶2:优化进阶(搅拌排序)\n# ∧_∧\n# (。・ω・。)つ━☆・*。\n# ⊂   ノ    ・゜+.\n#  しーJ   °。+ *´¨)\n#       .· ´¸.·*´¨) ¸.·*¨)\n#          (¸.·´ (¸.·’*\ndef optimization_bubble_sort_2(items):\n logging.info('优化2')\n for i in range(len(items) - 1):\n flag = False\n for j in range(len(items) - 1 - i): # 先进行正向排序将大数向列表末尾推移\n if items[j] > items[j + 1]:\n items[j], items[j + 1] = items[j + 1], items[j]\n logging.info('发生交换:' + str(items))\n flag = True\n if flag: # 反向排序将小数向列表前端推移\n flag = False\n for j in range(len(items) - 2 - i, 0, -1):\n if items[j - 1] > items[j]:\n items[j], items[j - 1] = items[j - 1], items[j]\n logging.info('发生交换:' + str(items))\n flag = True\n i += 1\n if not flag:\n break\n check_sort(items, '优化2')\n\n\n'''搅拌排序也叫鸡尾酒排序,原理并不复杂,与优化方案2相同采用了flag表示已经有序,增加了反向排序段,对于大部分列表可节约时间\n简单举例:列表=[1,5,4,3,2]\n优化前(bubble_sort):[1,5,4,3,2]->[1,5,4,2,3]->[1,5,2,3,4]->[1,2,3,4,5]\n优化后:[1,5,4,3,2]->[1,2,4,3,5]->[1,2,3,4,5]'''\n\n\ndef check_sort(items, function):\n i = 0\n for i in range(len(items)-1):\n if items[i] <= items[i+1]:\n continue\n else:\n print(function + '未有序')\n break\n if i == len(items)-2:\n print(function + '列表有序')\n\n\ndef run_time(function, name, list_sort): # 测试指定函数运行时间\n time_start = time.perf_counter()\n function(list_sort)\n time_end = time.perf_counter()\n sum_time = time_end - time_start\n print(name + '运行时间:' + str(sum_time))\n\n\ndef random_list(length_list): # 随机生成一个长度为length的列表\n list_rnd = random.sample([i for i in range(0, length_list)], length_list)\n return list_rnd\n\n\nif __name__ == '__main__':\n sample_list = [3, 5, 6, 9, 7, 1, 2, 4, 8, 10]\n run_time(bubble_sort, '冒泡算法', sample_list)\n run_time(optimization_bubble_sort_1, '冒泡算法优化1', sample_list)\n run_time(optimization_bubble_sort_2, '冒泡算法优化2', sample_list)\n logging.disable(logging.INFO)\n length = 30000 # 实验数据长度\n list_long = random_list(length)\n print('大型(其实还是很小)列表实验:表格长度:' + str(length))\n run_time(bubble_sort, '原算法', list_long)\n run_time(optimization_bubble_sort_1, '优化1', list_long)\n run_time(optimization_bubble_sort_2, '优化2', list_long)\n","repo_name":"myhMARS/algorithm","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4932,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"18065118277","text":"\nimport hashlib\n\n\ndef test():\n hashlib.md5(b\"abcdef609043\").hexdigest()\n hashlib.md5(b\"pqrstuv1048970\").hexdigest()\n return 0\n\n\ndef find_number(key):\n n = 1\n found = False\n while not found:\n t = key + str(n)\n if hashlib.md5(t.encode(\"utf-8\")).hexdigest()[0:5] == '00000':\n found = True\n break\n n += 1\n return n\n\n\ndef find_number2(key):\n n = 1\n found = False\n while not found:\n t = key + str(n)\n if hashlib.md5(t.encode(\"utf-8\")).hexdigest()[0:6] == '000000':\n found = True\n break\n n += 1\n return n\n\n\ntemp = find_number(\"yzbqklnj\")\nprint(f\"Found value: {temp}\")\n\ntemp = find_number2(\"yzbqklnj\")\nprint(f\"Found value: {temp}\")\n","repo_name":"mzarecky/advent-of-code","sub_path":"2015/05/day5.py","file_name":"day5.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"22191118292","text":"class Solution:\n # @param matrix, a list of lists of integers\n # RETURN NOTHING, MODIFY matrix IN PLACE.\n def setZeroes(self, matrix):\n di=[]\n dj=[]\n n=len(matrix)\n if n==0 :return \n m=len(matrix[0])\n for i in range(n):\n for j in range(m):\n if matrix[i][j]==0:\n di.append(i)\n dj.append(j)\n for k in di:\n for i in range(m):\n matrix[k][i]=0\n for k in dj :\n for i in range(n):\n for j in range(m):\n if j==k:\n matrix[i][j]=0\n print(matrix)\n\nif __name__=='__main__':\n s=Solution()\n #m=[[1,2,3],[4,0,6],[7,8,9]]\n m=[[0]] \n s.setZeroes(m)","repo_name":"liyi1013/Algorithms","sub_path":"Leetcode_oj/Set Matrix Zeroes.py","file_name":"Set Matrix Zeroes.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"2580641865","text":"# eval cc yourgame.c $(pkg-config --libs --cflags raylib) -o YourGame\n\nimport os\nimport sys\n\nif len(sys.argv) < 2:\n print(\"Usage: python build_raylib.py \")\n sys.exit(1)\n\ngame_name = sys.argv[1]\ncommand = f\"eval cc {game_name}.c $(pkg-config --libs --cflags raylib) -o {game_name}\"\nos.system(command)\n","repo_name":"BenCaunt/battlepack-combat-robot","sub_path":"crab-simulator/build_raylib.py","file_name":"build_raylib.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"71295079814","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 21 08:41:23 2022\n\n@author: hienpham\n\"\"\"\nimport argparse\nimport os\nimport pandas as pd\nfrom glob import glob\nfrom pdfminer.high_level import extract_text\n\n\n# =============================================================================\n# parser = argparse.ArgumentParser()\n# parser.add_argument(\"--input\",\n# \"-i\",\n# help=\"Input files directory\",\n# type=str)\n# \n# parser.add_argument(\"--output\",\n# \"-o\",\n# help=\"Ouput files directory\",\n# type=str)\n# \n# args = parser.parse_args()\n# rawDataPath = args.input\n# outputDir = args.output\n# =============================================================================\n\nrawDataPath = r'/home/hienpham/JD_raw/pdf/'\noutputDir = r'/home/hienpham/JD_raw/out'\nif not os.path.exists(outputDir):\n os.mkdir(outputDir)\n\ndef pdf2txt(rawDataPath, outputDir):\n pdfFiles = glob(rawDataPath + '*.pdf')\n \n \n data = []\n for file in pdfFiles:\n fileName = file.replace(rawDataPath, '').replace('.pdf', '')\n text = extract_text(file)\n data.append([text, 'assan'])\n #with open(os.path.join(outputDir, fileName + '.txt'), 'w') as f:\n # f.write(text)\n df = pd.DataFrame(data, columns=['Content', 'Label'])\n df.to_csv(outputDir + '/assan_emails.csv')\n \npdf2txt(rawDataPath, outputDir)","repo_name":"hienpham15/Job-Description-Understanding","sub_path":"utilities/pdf2txt_script.py","file_name":"pdf2txt_script.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"29035441486","text":"import pytest\n\nimport codonPython.mesh as mesh\n\n\ndef test_CheckInboxCount_ValidRequest_ReturnsJson(requests_mock, mesh_connection):\n requests_mock.get(\n url=\"http://root/messageexchange/TestMailboxId/count\",\n request_headers={\"Authorization\": \"xxxauthorizationxxx\"},\n status_code=200,\n json={\"count\": 100},\n )\n test_check_inbox_count = mesh_connection.check_inbox_count()\n assert test_check_inbox_count == 100\n assert requests_mock.call_count == 1\n\n\ndef test_CheckInboxCount_403StatusCode_ReturnsAuthenticationError(\n requests_mock, mesh_connection\n):\n requests_mock.get(\n url=\"http://root/messageexchange/TestMailboxId/count\",\n request_headers={\"Authorization\": \"xxxauthorizationxxx\"},\n status_code=403,\n )\n with pytest.raises(mesh.MESHAuthenticationError):\n mesh_connection.check_inbox_count()\n assert requests_mock.call_count == 1\n\n\ndef test_CheckInboxCount_400StatusCode_RaisesUnknownError(\n requests_mock, mesh_connection\n):\n requests_mock.get(\n url=\"http://root/messageexchange/TestMailboxId/count\",\n request_headers={\"Authorization\": \"xxxauthorizationxxx\"},\n status_code=400,\n )\n with pytest.raises(mesh.MESHUnknownError):\n mesh_connection.check_inbox_count()\n assert requests_mock.call_count == 1\n","repo_name":"codonlibrary/codonPython","sub_path":"codonPython/mesh/tests/test_check_inbox_count.py","file_name":"test_check_inbox_count.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"44"} +{"seq_id":"16172854003","text":"from country_codes import ISO3166\r\nfrom argparse import ArgumentParser\r\nfrom re import sub\r\nimport csv\r\nimport os\r\nimport json\r\nimport requests\r\n\r\n\r\ndef kebab(s):\r\n return '-'.join(\r\n sub(r\"(\\s|_|-)+\",\" \",\r\n sub(r\"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+\",\r\n lambda mo: ' ' + mo.group(0).lower(), s)).split()\r\n )\r\n\r\n\r\ndef country_to_code(country):\r\n country = kebab(country)\r\n if country in ISO3166.values():\r\n return country\r\n elif country in ISO3166:\r\n return ISO3166[country]\r\n else:\r\n exit(f\"Unknown country: {country}. The possible options are provided in country_codes.py\")\r\n\r\n\r\ndef parse_companies(api_token, industries, i_operator, revenues, employees, cities, countries, size, page, csv_path):\r\n url = \"https://api.thecompaniesapi.com/v1/companies\"\r\n aliases = {\r\n \"industries\": list(map(kebab, industries or [])),\r\n \"revenue\": revenues or [],\r\n \"totalEmployees\": employees or [],\r\n \"country.code\": list(map(country_to_code, countries or [])),\r\n \"city.code\": list(map(kebab, cities or [])),\r\n }\r\n\r\n query = []\r\n\r\n for attribute, values in aliases.items():\r\n if not values:\r\n continue\r\n\r\n search_condition = {\r\n \"attribute\": attribute,\r\n \"operator\": \"or\",\r\n \"sign\": \"equals\",\r\n \"values\": values\r\n }\r\n\r\n if attribute == \"industries\":\r\n search_condition[\"operator\"] = i_operator\r\n\r\n query.append(search_condition)\r\n\r\n params = {\"query\": json.dumps(query), \"size\": size, \"page\": page}\r\n headers = {\"Authorization\": f\"Basic {api_token}\"}\r\n response = requests.get(url, headers=headers, params=params)\r\n\r\n if response.status_code != 200:\r\n exit(f\"Error in retrieving data ({response.status_code}): {response.reason}\")\r\n\r\n data = response.json()\r\n meta = data[\"meta\"]\r\n companies = data[\"companies\"]\r\n\r\n if companies == []:\r\n exit(\"No companies found\")\r\n elif meta[\"total\"] != len(companies):\r\n print(f\"Found {meta['total']} companies. {size} companies from page {page} will be saved. To access other results, rerun the program with a different page index\")\r\n else:\r\n print(f\"Found {meta['total']} companies\")\r\n \r\n field_names = [\"Company Name\", \"Employees\", \"Revenue\", \"City\", \"Country\", \"Working Sphere\", \"Website\", \"Phone Number\",\r\n \"Facebook\", \"Instagram\", \"LinkedIn\", \"Pinterest\", \"Twitter\", \"YouTube\"]\r\n \r\n with open(csv_path, mode=\"a\", newline=\"\", encoding=\"utf-8\") as file:\r\n writer = csv.DictWriter(file, fieldnames=field_names)\r\n\r\n if file.tell() == 0:\r\n writer.writeheader()\r\n\r\n for company in companies:\r\n name = company.get(\"name\") or \"N/A\"\r\n employees = company.get(\"totalEmployees\") or \"N/A\"\r\n revenues = company.get(\"revenue\") or \"N/A\"\r\n city = (company.get(\"city\") or {}).get(\"name\") or \"N/A\"\r\n country = (company.get(\"country\") or {}).get(\"name\") or \"N/A\"\r\n working_sphere = company.get(\"industryMain\") or \"N/A\"\r\n phone_number = company.get(\"phoneNumber\") or \"N/A\"\r\n website = \"N/A\"\r\n if company.get(\"domainName\") and company.get(\"domainTld\"):\r\n website = company.get(\"domainName\") + \".\" + company.get(\"domainTld\")\r\n\r\n social_networks = company.get(\"socialNetworks\") or {}\r\n facebook = social_networks.get(\"facebook\") or \"N/A\"\r\n instagram = social_networks.get(\"instagram\") or \"N/A\"\r\n linkedin = social_networks.get(\"linkedin\") or \"N/A\"\r\n pinterest = social_networks.get(\"pinterest\") or \"N/A\"\r\n twitter = social_networks.get(\"twitter\") or \"N/A\"\r\n youtube = social_networks.get(\"youtube\") or \"N/A\"\r\n\r\n writer.writerow(\r\n {\r\n \"Company Name\": name,\r\n \"Employees\": employees,\r\n \"Revenue\": revenues,\r\n \"City\": city,\r\n \"Country\": country,\r\n \"Working Sphere\": working_sphere,\r\n \"Phone Number\": phone_number,\r\n \"Website\": website,\r\n \"Facebook\": facebook,\r\n \"Instagram\": instagram,\r\n \"LinkedIn\": linkedin,\r\n \"Pinterest\": pinterest,\r\n \"Twitter\": twitter,\r\n \"YouTube\": youtube,\r\n }\r\n )\r\n\r\n print(\"Data exported to\", csv_path)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n parser = ArgumentParser(\r\n description=\"A script for parsing companies. All search parameters should be written in kebab-case (something-like-this).\"\r\n )\r\n \r\n parser.add_argument(\"-at\", \"--api-token\", help=\"An API token for making a request.\", required=True)\r\n parser.add_argument(\"-o\", \"--output\", help=\"A file save directory (no spaces). Leave blank to save in the current working directory\")\r\n parser.add_argument(\"-s\", \"--size\", help=\"Max amount of companies to search for\", type=int, default=10)\r\n parser.add_argument(\"-p\", \"--page\", help=\"Search results page index\", type=int, default=1)\r\n parser.add_argument(\"-i\", \"--industries\", help=\"A list of industries separated by spaces (e.g., information-technology computer-science)\",\r\n nargs=\"+\")\r\n parser.add_argument(\"-io\", \"--i-operator\", help=\"An operator for the list of industries\",\r\n choices=[\"and\", \"or\"], default=\"or\")\r\n parser.add_argument(\"-r\", \"--revenues\", help=\"A list of revenue ranges separated by spaces\",\r\n choices=[\"under-1m\", \"1m-10m\", \"10m-50m\", \"50m-100m\", \"100m-200m\", \"200m-1b\", \"over-1b\"],\r\n nargs=\"+\")\r\n parser.add_argument(\"-e\", \"--employees\", help=\"A list of employee amount ranges separated by spaces\",\r\n choices=[\"1-10\", \"10-50\", \"50-200\", \"200-500\", \"500-1k\", \"1k-5k\", \"5k-10k\", \"over-10k\"],\r\n nargs=\"+\")\r\n parser.add_argument(\"-ci\", \"--cities\", help=\"A list of cities separated by spaces\",\r\n nargs=\"+\")\r\n parser.add_argument(\"-co\", \"--countries\", help=\"A list of countries (or ISO3166 country codes) separated by spaces\",\r\n nargs=\"+\")\r\n\r\n args = parser.parse_args()\r\n\r\n is_cli = args.industries or args.revenues or args.employees or args.cities or args.countries\r\n if args.output and not os.path.exists(args.output):\r\n exit(f\"Invalid path: {args.output}\")\r\n\r\n parse_companies(\r\n api_token=args.api_token, industries=args.industries, i_operator=args.i_operator,\r\n revenues=args.revenues, employees=args.employees, cities=args.cities,\r\n countries=args.countries, size=args.size, page=args.page, \r\n csv_path=os.path.join(args.output or os.getcwd(), \"company_data.csv\")\r\n )\r\n","repo_name":"BagOfButter/data_parse","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":6975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"35458026126","text":"import torch\nimport higher\nimport argparse\n\nfrom models.metaconv import MetaConv\nfrom models.metaconv_contextual import MetaConvContextual\n\n\nclass MAML:\n def __init__(self, args):\n self.args = args\n\n self.model = None\n if args.model == 'meta_conv':\n self.model = MetaConv(out_channels=self.args.n_ways)\n self.model.cuda()\n if args.model == 'meta_conv_contextual':\n self.model = MetaConvContextual(out_channels=self.args.n_ways)\n self.model.cuda()\n assert self.model is not None\n\n self.best_model = None\n\n @staticmethod\n def add_arguments(argparser: argparse.ArgumentParser):\n argparser.add_argument('--inner_steps_train', type=int, help='number of iters in inner loop ar train time', default=5)\n argparser.add_argument('--inner_steps_test', type=int, help='number of iters in inner loop ar test time', default=10)\n argparser.add_argument('--model', type=str, help='model optimized in inner loop', default='meta_conv')\n\n def get_inner_trainable_params(self):\n return self.model.parameters()\n\n def get_outer_trainable_params(self):\n return self.model.parameters()\n\n def set_train_mode(self):\n self.model.train()\n\n def set_eval_mode(self):\n self.model.eval()\n\n def run_iteration(self, meta_batch, training=False):\n if training:\n self.model.train()\n inner_steps = self.args.inner_steps_train\n else:\n self.model.eval()\n inner_steps = self.args.inner_steps_test\n\n meta_batch_loss = 0.0\n meta_batch_accuracy = 0.0\n\n meta_train_inputs, meta_train_labels = meta_batch[\"train\"]\n meta_test_inputs, meta_test_labels = meta_batch[\"test\"]\n\n inner_optimizer = torch.optim.SGD(self.get_inner_trainable_params(), lr=1e-2)\n\n for task_idx in range(self.args.tasks_num):\n # Create inner loop context using higher library\n with higher.innerloop_ctx(self.model, opt=inner_optimizer,\n copy_initial_weights=False, track_higher_grads=training) as (fmodel, diffopt):\n\n # Extract examples and labels for current task\n train_inputs = meta_train_inputs[task_idx].cuda()\n train_labels = meta_train_labels[task_idx].cuda()\n\n test_inputs = meta_test_inputs[task_idx].cuda()\n test_labels = meta_test_labels[task_idx].cuda()\n\n # Inner loop\n for _ in range(inner_steps):\n train_logits = fmodel(train_inputs)\n train_loss = torch.nn.functional.cross_entropy(train_logits, train_labels)\n\n # _, train_predictions = torch.max(train_logits, dim=1)\n # train_accuracy = (train_predictions == train_labels).sum().item() / train_labels.size(0)\n # print(train_accuracy)\n\n diffopt.step(train_loss)\n\n # Query the trained model\n test_logits = fmodel(test_inputs)\n test_loss = torch.nn.functional.cross_entropy(test_logits, test_labels)\n _, test_predictions = torch.max(test_logits, dim=1)\n\n test_accuracy = (test_predictions == test_labels).sum().item() / test_labels.size(0)\n\n # Compute metrics\n meta_batch_loss += test_loss.detach()\n meta_batch_accuracy += test_accuracy\n\n # Propagate task loss through inner loop rollup\n if training:\n torch.div(test_loss, 100 * self.args.tasks_num).backward()\n\n return meta_batch_loss, meta_batch_accuracy\n\n def get_state_dict(self):\n return {'model_state_dict': self.model.state_dict()}\n\n def load_checkpoint(self, state_dict):\n self.model.load_state_dict(state_dict['model_state_dict'])","repo_name":"ArmandNM/meta-learning","sub_path":"learners/maml.py","file_name":"maml.py","file_ext":"py","file_size_in_byte":3909,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"38271545640","text":"import sys,os\nimport os.path\n\nfrom google.auth.transport.requests import Request\nfrom google.oauth2.credentials import Credentials\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom googleapiclient.discovery import build\nfrom googleapiclient.errors import HttpError\nfrom getfilelistpy import getfilelist\n\ndef makeThumb(fromm,too):\n os.system('convert '+fromm+' -resize 800x '+too+\" 2>/dev/null\")\n\ndef getN(fil):\n #print('getN ',fil)\n os.system('exiftool -overwrite_original -all= '+fil)\n with open('google.txt','r') as f:\n lines=f.readlines()\n for line in lines: \n ll=line.strip().split()\n if(len(ll)!=2):\n continue\n if(ll[0]==fil):\n return ll[1].split('/')[-2]\n return 'ERROR'\n\nglinks={}\n\ndef processGfiles():\n global glinks\n if(os.path.exists('google.txt')):\n with open('google.txt','r') as f:\n lista=f.readlines()\n for linia in lista:\n ll=linia.split()\n if(len(ll)==2):\n glinks[ll[0].strip()]=ll[1].strip()\n\nprocessGfiles()\n\n\ndef procImg(line):\n if(line[:6]=='IMGIMG'):\n imgfile=line.split()[1].strip()\n numer=getN(imgfile)\n im=imgfile.split('.')\n im[-2]=im[-2]+'_small'\n thumbf='.'.join(im)\n if(not(os.path.exists(thumbf))):\n makeThumb(imgfile,thumbf)\n numers=getN(thumbf)\n return '[URL=https://drive.google.com/file/d/'+numer+'/preview][IMG]http://drive.google.com/uc?export=view&id='+numers+'[/IMG][/URL]'\n else:\n return line\n\ndef set_permission(service, file_id):\n print('set permission', file_id)\n try:\n permission = {'type': 'anyone',\n 'value': 'anyone',\n 'role': 'reader'}\n return service.permissions().create(fileId=file_id,body=permission).execute()\n except errors.HttpError as error:\n return print('Error while setting permission:', error)\n\ndef processFile(fil):\n with open(fil,'r') as f:\n lines=f.readlines()\n with open(fil.replace('.txt','_compiled.txt'),'w') as g:\n for line in lines:\n g.write(procImg(line))\n\nSCOPES = ['https://www.googleapis.com/auth/drive']\nrootDir=os.path.dirname(os.path.realpath(__file__))\n\nif(not(os.path.exists(rootDir+'/credentials.json'))):\n print(\"credentials.json file needed. Follow https://developers.google.com/drive/api/v3/quickstart/python to generate it\")\n sys.exit(0)\n\ndef main():\n \"\"\"Shows basic usage of the Drive v3 API.\n Prints the names and ids of the first 10 files the user has access to.\n \"\"\"\n creds = None\n \n if os.path.exists(rootDir+'/token.json'):\n creds = Credentials.from_authorized_user_file(rootDir+'/token.json', SCOPES)\n # If there are no (valid) credentials available, let the user log in.\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(\n rootDir+'/credentials.json', SCOPES)\n creds = flow.run_local_server(port=0)\n # Save the credentials for the next run\n with open(rootDir+'/token.json', 'w') as token:\n token.write(creds.to_json())\n\n try:\n service = build('drive', 'v3', credentials=creds)\n\n # Call the Drive v3 API\n cwd=os.getcwd().split('/')[-1]\n results = service.files().list(q=\"fullText contains '\"+cwd+\"'\",\n pageSize=5, fields=\"nextPageToken, files(id, name)\").execute()\n items = results.get('files', [])\n\n if not items:\n print(cwd+' not found.')\n return\n if (len(items)>1):\n print('more than one '+cwd+' found.')\n return \n item=items[0]\n print(u'{0} ({1})'.format(item['name'], item['id']))\n relacjaDirId=item['id']+''\n \n results = service.files().list(q=\"'\"+relacjaDirId+\"' in parents \",\n pageSize=500, fields=\"nextPageToken, files(id, name, webViewLink, permissions)\").execute()\n items = results.get('files', [])\n\n if not items:\n print('No files found.')\n return\n \n for item in items:\n ok=None\n #print(u'{0} ({1}, {2}, {3})'.format(item['name'], item['id'], item['webViewLink'], item['permissions']))\n \n if(item['name'] not in glinks.keys()):\n ok='nie ma'\n if('.jpg' in item['name'] or '.png' in item['name'] or '.JPG' in item['name'] or '.PNG' in item['name']):\n ok='generate'\n if(ok==None):\n print(item['name'],' exists as shareable link')\n if(ok=='generate'):\n #print(item['webViewLink'])\n print(item['name'],' generating')\n set_permission(service,item['id'])\n glinks[item['name']]=item['webViewLink'].replace('view?usp=drivesdk','preview')\n \n except HttpError as error:\n print(f'An error occurred: {error}')\n\nmain()\n\nwith open('google.txt','w') as f:\n for k,v in glinks.items():\n vv=v.replace('view?usp=sharing','preview')\n f.write(k+' '+vv+\"\\n\")\n\nprocessFile(sys.argv[1])\n \n \n \n","repo_name":"matlacki/konradus_google_drive","sub_path":"compile2.py","file_name":"compile2.py","file_ext":"py","file_size_in_byte":5124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"10203375569","text":"import gym\nfrom .atari import AtariEnv\n\n# this list is obtained from gym/envs/__init__.py\natari_list = [\n\t'Adventure', 'AirRaid', 'Alien', 'Amidar', 'Assault', 'Asterix', 'Asteroids', 'Atlantis',\n\t'BankHeist', 'BattleZone', 'BeamRider', 'Berzerk', 'Bowling', 'Boxing', 'Breakout', 'Carnival',\n\t'Centipede', 'ChopperCommand', 'CrazyClimber', 'Defender', 'DemonAttack', 'DoubleDunk',\n\t'ElevatorAction', 'Enduro', 'FishingDerby', 'Freeway', 'Frostbite', 'Gopher', 'Gravitar',\n\t'Hero', 'IceHockey', 'Jamesbond', 'JourneyEscape', 'Kangaroo', 'Krull', 'KungFuMaster',\n\t'MontezumaRevenge', 'MsPacman', 'NameThisGame', 'Phoenix', 'Pitfall', 'Pong', 'Pooyan',\n\t'PrivateEye', 'Qbert', 'Riverraid', 'RoadRunner', 'Robotank', 'Seaquest', 'Skiing',\n\t'Solaris', 'SpaceInvaders', 'StarGunner', 'Tennis', 'TimePilot', 'Tutankham', 'UpNDown',\n\t'Venture', 'VideoPinball', 'WizardOfWor', 'YarsRevenge', 'Zaxxon'\n]\n\nenvs_collection = {\n\t# Atari envs\n\t**{\n\t\tatari_name : 'atari'\n\t\tfor atari_name in atari_list\n\t}\n}\n\nmake_env_collection = {\n\t'atari': AtariEnv\n}\n\ndef make_env(args):\n\treturn make_env_collection[envs_collection[args.env]](args)\n","repo_name":"Stilwell-Git/Doubly-Bounded-Q-Learning","sub_path":"envs/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"39040339482","text":"import os\r\n\r\nimport docker\r\nfrom django_rq import job\r\n\r\nfrom xterm.consumers import send_notification_to_group\r\n\r\nDOCKER_NETWORK = os.environ.get(\"DOCKER_NETWORK\", \"d-gui-network\")\r\n\r\n@job\r\ndef run_image_task(image_name, ports, volumes, environment, name, privileged=False, nvdocker=False):\r\n client = docker.from_env()\r\n device_requests = []\r\n network = client.networks.get(DOCKER_NETWORK)\r\n\r\n if nvdocker:\r\n # Define device requests for NVIDIA GPUs\r\n device_requests += [\r\n docker.types.DeviceRequest(\r\n count=-1, # -1 specifies all available GPUs\r\n capabilities=[['gpu']], # This is the equivalent of `--gpus all`\r\n driver='nvidia'\r\n )\r\n ]\r\n\r\n traefik_labels = {\r\n \"traefik.enable\": \"true\",\r\n f\"traefik.http.routers.d-gui-{name}.rule\": f\"PathPrefix(`/novnc/{name}/`)\",\r\n f\"traefik.http.services.d-gui-{name}.loadbalancer.server.port\": \"6901\",\r\n f\"traefik.http.middlewares.d-gui-{name}-strip-prefix.stripprefix.prefixes\": f\"/novnc/{name}/\",\r\n f\"traefik.http.routers.d-gui-{name}.middlewares\": f'd-gui-{name}-strip-prefix',\r\n \"traefik.docker.network\": DOCKER_NETWORK,\r\n }\r\n\r\n container = client.containers.run(\r\n image_name,\r\n stdin_open=True,\r\n detach=True,\r\n tty=True,\r\n ports=ports,\r\n volumes=volumes,\r\n environment=environment,\r\n name=name,\r\n privileged=privileged,\r\n device_requests=device_requests,\r\n network=network.id, # Attach the container to the network\r\n labels=traefik_labels\r\n )\r\n\r\n image_name = \"none\"\r\n if container.image.tags:\r\n image_name = container.image.tags[0]\r\n container_name = container.attrs['Name'][1:]\r\n msg = f\"Container [{container_name}] ({image_name}) has been created\"\r\n\r\n message = {\r\n \"action\": \"CREATED\",\r\n \"details\": msg\r\n }\r\n send_notification_to_group(message=message)\r\n return msg\r\n\r\n@job\r\ndef run_container_task(id):\r\n client = docker.from_env()\r\n container = client.containers.get(id)\r\n container.start()\r\n container_name = container.name\r\n msg = f\"Container [{container_name}] has been started\"\r\n\r\n message = {\r\n \"action\": \"STARTED\",\r\n \"details\": msg\r\n }\r\n send_notification_to_group(message=message)\r\n\r\n return msg\r\n\r\n@job\r\ndef stop_container_task(id):\r\n client = docker.from_env()\r\n container = client.containers.get(id)\r\n container.stop()\r\n container_name = container.name\r\n msg = f\"Container [{container_name}] has been stopped\"\r\n message = {\r\n \"action\": \"STOPPED\",\r\n \"details\": msg\r\n }\r\n send_notification_to_group(message=message)\r\n return msg\r\n\r\n@job\r\ndef remove_container_task(id):\r\n client = docker.from_env()\r\n container = client.containers.get(id)\r\n container.remove()\r\n container_name = container.name\r\n msg = f\"Container [{container_name}] has been removed\"\r\n\r\n message = {\r\n \"action\": \"REMOVED\",\r\n \"details\": msg\r\n }\r\n send_notification_to_group(message=message)\r\n return msg\r\n\r\n@job\r\ndef restart_container_task(id):\r\n client = docker.from_env()\r\n container = client.containers.get(id)\r\n container.restart()\r\n container_name = container.name\r\n msg = f\"Container [{container_name}] has been restarted\"\r\n\r\n message = {\r\n \"action\": \"RESTARTED\",\r\n \"details\": msg\r\n }\r\n send_notification_to_group(message=message)\r\n return msg\r\n","repo_name":"NatLee/development-container-manager","sub_path":"src/xterm/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":3532,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"1981812893","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 9 15:18:32 2020\n\n@author: feel-liao\n\"\"\"\nimport openpyxl\nfrom openpyxl.chart import (\n Reference,\n Series,\n PieChart,\n BarChart,\n BubbleChart\n )\nwb=openpyxl.Workbook()\n# Pie Chart\ndata=[\n [\"Pie\",'Sold']\n [\"Apple\",50]\n [\"Cherry\",30]\n [\"Pumpkin\",10]\n [\"Chocolate\",40]\n ]\npie_chart=wb.active\npie_chart.title='PieChart'\n# write data to the PieChart\nfor row in data:\n pie_chart.append(row)\npie=PieChart()\nlabels=Reference(pie_chart,min_col=1,min_row=2,max_row=5)\ndata=Reference(pie_chart,min_col=2,min_row=2,max_row=5)\npie.add_data(data)\n\n","repo_name":"FeelLiao/Bioinfo_struggle_way","sub_path":"Python/PythonBase/6.其它/excel_chart.py","file_name":"excel_chart.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"44"} +{"seq_id":"1563305297","text":"# Define a daysBetweenDates procedure that would produce the\n# correct output if there was a correct nextDay procedure.\n#\n# Note that this will NOT produce correct outputs yet, since\n# our nextDay procedure assumes all months have 30 days\n# (hence a year is 360 days, instead of 365).\n# \n# if (year is not divisible by 4) then (it is a common year)\n# else if (year is not divisible by 100) then (it is a leap year)\n# else if (year is not divisible by 400) then (it is a common year)\n# else (it is a leap year)\n\ndef isLeapYear(year):\n if(year % 4 != 0):\n return False\n elif(year % 100 != 0):\n return True\n elif(year % 400 != 0):\n return False\n else:\n return True\n \n\n\ndef dayInMonth(year,month):\n if(month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12):\n return 31\n elif(month == 2):\n if(isLeapYear(year)):\n return 29\n else:\n return 28\n else:\n return 30\n\ndef nextDay(year, month, day):\n \"\"\"Simple version: assume every month has 30 days\"\"\"\n if day < dayInMonth(year,month):\n return year, month, day + 1\n else:\n if month == 12:\n return year + 1, 1, 1\n else:\n return year, month + 1, 1\n\ndef date_is_before(year1, month1, day1, year2, month2, day2):\n if(year1 < year2):\n return True\n elif(year1 == year2):\n if(month1 < month2):\n return True\n elif(month1 == month2):\n if(day1 < day2):\n return True\n return False\n\ndef daysBetweenDates(year1, month1, day1, year2, month2, day2):\n \"\"\"Returns the number of days between year1/month1/day1\n and year2/month2/day2. Assumes inputs are valid dates\n in Gregorian calendar, and the first date is not after\n the second.\"\"\"\n assert not date_is_before(year2, month2, day2, year1, month1, day1), \"Houston we've got a problem\"\n total_of_days = 0\n while date_is_before(year1, month1, day1, year2, month2, day2):\n year1, month1, day1 = nextDay(year1,month1,day1)\n total_of_days += 1\n return total_of_days\n\ndef test():\n \n assert daysBetweenDates(2013,1,1,2013,1,1) == 0\n assert daysBetweenDates(2013,1,1,2013,1,2) == 1\n assert daysBetweenDates(2012,2,27,2012,3,1) == 3\n assert daysBetweenDates(2012,1,1,2013,1,1) == 366\n assert daysBetweenDates(2013,1,1,2014,1,1) == 365\n assert nextDay(2013,1,1) == (2013,1,2)\n assert nextDay(2013,4,30) == (2013,5,1)\n assert nextDay(2012,12,31) == (2013,1,1)\n assert nextDay(2012,2,28) == (2012,2,29)\n assert nextDay(2013,2,28) == (2013,3,1)\n assert isLeapYear(2000)\n assert not isLeapYear(1900)\n assert isLeapYear(2004)\n\n\n test_cases = [((2012,9,30,2012,10,30),30), \n ((2012,1,1,2013,1,1),366),\n ((2012,9,1,2012,9,4),3)]\n \n for (args, answer) in test_cases:\n result = daysBetweenDates(*args)\n if result != answer:\n print(\"Test with data:\", args, \"failed\")\n else:\n print(\"Test case passed!\")\n\n\ntest()","repo_name":"tiago-ferreira/data-science-foundation-one","sub_path":"weekTwo/lesson1/daysBetweenDates.py","file_name":"daysBetweenDates.py","file_ext":"py","file_size_in_byte":3105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"15298057853","text":"import sys\nimport requests\nimport json\nfrom scipy import signal\nimport numpy as np\nimport pyaudio\nimport librosa\nimport time\n\ndef getFreqs(url):\n endpoint = url + '/api/filters'\n try:\n res = requests.get(endpoint)\n except BaseException as e:\n print('Error getting filters.')\n print(e)\n sys.exit(1)\n return res.json()\n\ndef filter(url):\n freqs = getFreqs(url)\n avg_gain = min(sum([freqs[x]['gain'] for x in range(len(freqs))]), 1)\n print('Gain sum = ' + str(avg_gain))\n fs = 44100 # Sample rate\n fc = max(fs/2 - np.floor(fs/2 * avg_gain), 30) - 10 # Cutoff\n fstop = min((fc + 500), fs/2) # End the transition band\n #fc = 10000\n #fstop = 10500\n ripple = 3 # 3dB ripple\n atten = 60 # 60dB attenuation\n print('cutoff = ' + str(fc))\n print('transition stop = ' + str(fstop))\n # Get the smallest order for the filter\n order, _ = signal.ellipord(fc, fstop, ripple, atten, fs=fs)\n\n return signal.ellip(order, ripple, atten, fc, fs=fs)\n\nif __name__ == '__main__':\n\n\n if(sys.version_info.major < 3):\n logging.error('Please use Python 3.x or higher')\n sys.exit(1)\n\n if len(sys.argv) != 3:\n raise ValueError('Please provide a filename.')\n print('usage: python disco-player.py ')\n sys.exit(1)\n\n URL = sys.argv[1]\n\n track_data, track_rate = librosa.load(sys.argv[2], sr=44.1e3, dtype=np.float32)\n\n # instantiate PyAudio (1)\n p = pyaudio.PyAudio()\n count = 0\n\n # Now construct the filter\n b, a = filter(URL)\n\n # define callback (2)\n def callback(in_data, frame_count, time_info, status):\n global b, a, count\n\n track_frame = track_data[frame_count*count : frame_count*(count+1)]\n\n track_left = signal.filtfilt(b, a, track_frame)\n track_right = signal.filtfilt(b, a, track_frame)\n\n ret_data = np.empty((track_left.size + track_right.size), dtype=track_left.dtype)\n ret_data[1::2] = track_left\n ret_data[0::2] = track_right\n ret_data = ret_data.astype(np.float32).tostring()\n count += 1\n return (ret_data, pyaudio.paContinue)\n\n # open stream using callback (3)\n stream = p.open(format=pyaudio.paFloat32,\n channels=2,\n rate=int(track_rate),\n output=True,\n stream_callback=callback,\n frames_per_buffer=2**16)\n\n # start the stream (4)\n stream.start_stream()\n\n # wait for stream to finish (5)\n while stream.is_active():\n b, a = filter(URL)\n time.sleep(1)\n\n # stop stream (6)\n stream.stop_stream()\n stream.close()\n\n # close PyAudio (7)\n p.terminate()\n","repo_name":"hyve9/disco","sub_path":"disco-player.py","file_name":"disco-player.py","file_ext":"py","file_size_in_byte":2711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"2708680489","text":"import os\n\nos.system('cls')\n\nprint('Переводчик с римской системы исчисления в арабскую.')\n\ntab_rome_arab_num = {\n 'I':1,\n 'V':5,\n 'X':10,\n 'L':50,\n 'C':100,\n 'D':500,\n 'M':1000\n}\n\ndef resulting_number(str_num):\n\n return_number = tab_rome_arab_num.get(str_num,0)\n\n if return_number == 0:\n print(f'Символ {str_num} не соответствует римской системе исчисления')\n\n return return_number\n\ndef pars_numbers(rome_num):\n\n num = 0\n list_num = []\n str_len = len(rome_num)\n\n while num < str_len:\n\n a = resulting_number(rome_num[num])\n\n if num + 1 == str_len:\n b = 0\n else:\n b = resulting_number(rome_num[num + 1])\n \n if a < b:\n list_num.append(-a)\n else:\n list_num.append(a) \n \n num += 1\n\n return sum(list_num)\n\ndef exchange_numbers(rome_num):\n\n arab_num = pars_numbers(rome_num)\n \n print(f'Римское число {rome_num} - это {arab_num} по арабски')\n\ninput_number = input('Введите римские цифры: ')\n\nexchange_numbers(input_number)","repo_name":"AlexKeyMAD/Study_py","sub_path":"Udemy/Less_041/RomeNumbers.py","file_name":"RomeNumbers.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"17717653758","text":"# Composer.py\n\nfrom AllNotes import letterNotes\nimport sys\n\n\n# breve > minima > semi-minima < colcheia < semi-colcheia\n# 64 32 16 8 4\n\n# gets the tone\ndef whichTone(parser):\n for pianoKey in letterNotes:\n if parser.cNote == pianoKey[2]:\n return pianoKey[0] # tone\n\n\n# converts a letter note into a midi pitch value\ndef convertNote(note, parser):\n curTone = whichTone(parser)\n\n for pianoKey in letterNotes:\n if note == pianoKey[1] and curTone == pianoKey[0]:\n return pianoKey[2]\n\n\n# sets the note\ndef do_note(action, parser):\n n = action.args['note']\n\n # checks if note needs conversion or not\n if n is not '.':\n parser.cNote = convertNote(n, parser)\n note = parser.cNote\n duration = parser.cDur\n\n if len(parser.notes) == 0:\n parser.notes = [[note, duration]]\n else:\n parser.notes.append([note, duration])\n\n\n# function to raise note.\ndef do_raise(action, parser):\n val = action.args['val']\n parser.cNote = parser.cNote + val\n\n\n# function to lower note.\ndef do_lower(action, parser):\n val = action.args['val']\n parser.cNote = parser.cNote - val\n\n\n# function to speedup note.\ndef do_faster(action, parser):\n val = action.args['val']\n parser.cDur = parser.cDur * val\n\n\n# function to slowdown note.\ndef do_slower(action, parser):\n val = action.args['val']\n parser.cDur = int(parser.cDur / val) # cast to int mandatory for mxm.midi\n\n\n# function to set the highchord\ndef do_hchord(action, parser):\n notes = [] # creates an empty list of notes\n for val in action.args['levels']:\n notes.append(parser.cNote + val)\n parser.notes.append([notes, parser.cDur])\n\n\n# function to set a pause\ndef do_pause(action, parser):\n duration = parser.cDur * action.args['val']\n parser.notes.append([0, duration])\n\n\n# function to merge notes\ndef do_merge(action, parser):\n val = action.args['val']\n duration = parser.cDur + int(val * parser.cDur)\n if duration < 0: # checks if duration is less than 0. if so, 0 is the limit\n duration = 0\n parser.notes.append([parser.cNote, duration])\n\n\n# defines a macro, and save its actions to a dictionary\ndef do_def_macro(action, parser):\n macro_name = action.args['name']\n macro_notes = action.args['notes']\n parser.macros[macro_name] = {'notes': macro_notes}\n\n\n# Runs the macro, called by name. It access the macro dictionary, and runs the stored commands\ndef do_run_macro(action, parser):\n macro_name = action.args['name']\n\n if macro_name not in parser.macros:\n print(f\"Unknown macro '{macro_name}'\", file=sys.stderr)\n exit(1)\n # saves the note and duration before the macro to restore them after it runs\n saveNote = parser.cNote\n saveDur = parser.cDur\n macro_partiture = parser.macros[macro_name]['notes']\n Composer.compose(macro_partiture, parser)\n parser.cNote = saveNote\n parser.cDur = saveDur\n\nclass Composer:\n dispatch_table = {\n \"note\": do_note,\n \"pause\": do_pause,\n \"slower\": do_slower,\n \"faster\": do_faster,\n 'raise': do_raise,\n \"lower\": do_lower,\n \"merge\": do_merge,\n \"hchord\": do_hchord,\n \"def_macro\": do_def_macro,\n \"run_macro\": do_run_macro,\n }\n\n # constructor of Composer class\n def __init__(self, action, args):\n self.name = action\n self.args = args\n\n def __repr__(self):\n return f\"Composer({self.name}, {self.args})\"\n\n # executes functions based on dispatch_table calls\n def make(self, parser):\n self.dispatch_table[self.name](self, parser)\n\n @classmethod\n def compose(cls, partiture, parser):\n for notes in partiture:\n notes.make(parser) # calls dispatch_table functions\n","repo_name":"andrefmferreira/ipca_ply_midiParser","sub_path":"Composer.py","file_name":"Composer.py","file_ext":"py","file_size_in_byte":3789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"15480367392","text":"from sklearn import linear_model\nimport numpy as np\n\n\n#create the training data set, with 2 input integers\ninput_data = np.random.randint(50, size=(20,2))\ninput_sum = np.zeros(len(input_data))\nfor row in range(len(input_data)):\n input_sum[row] = input_data[row][0] + input_data[row][1]\n\n#build a linear regression model with the training data\nlinear_regression = linear_model.LinearRegression(fit_intercept=False)\nlinear_regression.fit(input_data, input_sum)\n\n#on test data \npredicted_sum = linear_regression.predict([[991231, 30]])\nprint('the predicted sum is: ' + str(predicted_sum))","repo_name":"Prudhvihub/ml","sub_path":"sumOfTwoNum.py","file_name":"sumOfTwoNum.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"491964293","text":"import urllib.request\nimport requests\nimport codecs\nimport re\nimport os\nimport json\nfrom bs4 import BeautifulSoup\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', \"reviewer.settings\")\n\nimport django\ndjango.setup()\nfrom Gamers.models import Game, Developer, Genre, Publisher, Platform, \\\n Screenshot, Tag\n\n\n# stroe.steampowered 페이지에 있는 게임 목록을 가져옴\ndef get_appid_steam(start, end, gamelist):\n appid = []\n for i in range(start, end):\n req = urllib.request.Request(\n 'http://store.steampowered.com/search/?page=' + str(i),\n data=None,\n headers={\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \\\n AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 \\\n Safari/537.36 Edge/14.14393'\n }\n )\n\n f = urllib.request.urlopen(req).read().decode('utf-8')\n\n bs = BeautifulSoup(f, 'lxml')\n appid_row = bs.find_all(\n 'a',\n class_='search_result_row ds_collapse_flag'\n )\n \n for item in appid_row:\n try:\n gametitle = item.find('span',class_='title').text\n except:\n continue\n\n if gametitle not in gamelist:\n appid.append(item['data-ds-appid'])\n print(gametitle)\n\n return appid\n\n\n# 영어로 된 달을 숫자로 바꿈\ndef convert_release_date(release_date_raw):\n mdy = release_date_raw.split()\n\n day = mdy[0]\n month = mdy[1]\n year = mdy[2]\n\n montonum = {\n 'Jan,': '01',\n 'Feb,': '02',\n 'Mar,': '03',\n 'Apr,': '04',\n 'May,': '05',\n 'Jun,': '06',\n 'Jul,': '07',\n 'Aug,': '08',\n 'Sep,': '09',\n 'Oct,': '10',\n 'Nov,': '11',\n 'Dec,': '12'\n }\n\n for month_name, value in montonum.items():\n if month == month_name:\n month = value\n break\n\n release_date = year + '-' + month + '-' + day\n\n return release_date\n\n\n# 영어로 된 달을 숫자로 바꿈\ndef convert_release_date_2(release_date_raw):\n mdy = release_date_raw.split()\n \n month = mdy[0]\n year = mdy[1]\n\n montonum = {\n 'Jan': '01',\n 'Feb': '02',\n 'Mar': '03',\n 'Apr': '04',\n 'May': '05',\n 'Jun': '06',\n 'Jul': '07',\n 'Aug': '08',\n 'Sep': '09',\n 'Oct': '10',\n 'Nov': '11',\n 'Dec': '12'\n }\n\n for month_name, value in montonum.items():\n if month == month_name:\n month = value\n break\n\n release_date = year + '-' + month + '-' + '01'\n\n return release_date\n\n\n# 스팀에서 게임 데이터를 가져옴\n# (title, release_date, homepage, genre, developer, publisher, screenshot)\ndef get_game_data(appid):\n content_list = {}\n for item in appid:\n url = 'http://store.steampowered.com/app/' + str(item)\n req = urllib.request.Request(\n url,\n data=None,\n headers={\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \\\n AppleWebKit/537.36 (KHTML, like Gecko) \\\n Chrome/51.0.2704.79 \\\n Safari/537.36 Edge/14.14393',\n 'cookie': 'browserid=1344725717332693116; \\\n sessionid=adcfbe925844f84782bd1577; \\\n strResponsiveViewPrefs=touch; \\\n birthtime=678985201; \\\n lastagecheckage=9-July-1991; \\\n recentapps=%7B%22271590%22%3A1487220706%7D; \\\n timezoneOffset=32400,0; \\\n _ga=GA1.2.657082707.1487220674; \\\n mature_content=1'\n }\n )\n\n f = urllib.request.urlopen(req).read().decode('utf-8')\n bs = BeautifulSoup(f, 'lxml')\n\n try:\n title = bs.find('div', class_='apphub_AppName').text\n except:\n continue\n\n try:\n rw = bs.find('span', class_='date')\n except:\n rw = None\n \n try:\n homepage_raw = bs.find(\n 'a',\n class_='linkbar',\n attrs={'rel': 'noreferrer'}\n )\n except:\n homepage_raw = None\n\n if rw is None:\n release_date = None\n elif len(rw.text) == 8:\n print(rw.text)\n release_date = convert_release_date_2(rw.text)\n elif len(rw.text) == 4:\n print(rw.text)\n release_date = rw.text + '0101'\n elif len(rw.text) == 12:\n print(rw.text)\n release_date = convert_release_date(rw.text)\n else:\n release_date = None\n\n if homepage_raw is not None:\n homepage = homepage_raw['href']\n else:\n homepage = None\n\n platforms = []\n if bs.find('span', class_='platform_img win'):\n platforms.append('Windows')\n if bs.find('span', class_='platform_img mac'):\n platforms.append('Mac')\n if bs.find('span', class_='platform_img linux'):\n platforms.append('Linux')\n\n content_div = bs.find_all('div', class_='page_content')\n for page in content_div:\n if page['class'][0] == 'page_content':\n genres_raw = page.find_all('a', attrs={\"href\": re.compile('http://store.steampowered.com/genre/[.]*')})\n developers_raw = page.find_all('a', attrs={\"href\": re.compile('http://store.steampowered.com/search/\\?developer[.]*')})\n publishers_raw = page.find_all('a', attrs={\"href\": re.compile('http://store.steampowered.com/search/\\?publisher[.]*')})\n break\n\n genres = []\n developers = []\n publishers = []\n\n for g in genres_raw:\n genres.append(g.text.strip())\n\n for d in developers_raw:\n developers.append(d.text.strip())\n\n for p in publishers_raw:\n publishers.append(p.text.strip())\n\n try:\n screenshotlist = []\n screenshots = bs.findAll(\n 'a', \n class_='highlight_screenshot_link'\n )\n \n for screenshot in screenshots:\n screenshotlist.append(screenshot['href'][43:].replace('1920x1080', '600x338'))\n except:\n screenshotlist = None\n\n tags = []\n for item in bs.find_all('a', class_='app_tag'):\n tags.append(item.text.replace('\\t', '').replace('\\r', '').replace('\\n', ''))\n\n content = {}\n content['title'] = title\n content['release_date'] = release_date\n content['homepage'] = homepage\n content['platforms'] = platforms\n content['genres'] = genres\n content['developers'] = developers\n content['publishers'] = publishers\n content['screenshot'] = screenshotlist\n content['tags'] = tags\n\n content_list[title] = content\n print(\"DONE\")\n return content_list\n\n\n# Game모델 저장(genre, developer, publisher 관계연결), Screenshot모델 저장\ndef save_object(content):\n for gametitle, item in content.items():\n print(gametitle)\n obj, created = Game.objects.update_or_create(\n title=item['title']\n )\n\n if created is False:\n print(gametitle + \", PASS\")\n continue\n else:\n if item['homepage'] is not None:\n obj.homepage = item['homepage']\n if item['release_date'] is not None:\n obj.release_date = item['release_date']\n print(gametitle + \", SAVE\")\n obj.save()\n\n for platform in item['platforms']:\n temp, created = Platform.objects.get_or_create(name=platform)\n obj.platforms.add(temp)\n\n for genre in item['genres']:\n temp, created = Genre.objects.get_or_create(name=genre)\n obj.genres.add(temp)\n\n for developer in item['developers']:\n temp, created = Developer.objects.get_or_create(name=developer)\n obj.developers.add(temp)\n\n for publisher in item['publishers']:\n temp, created = Publisher.objects.get_or_create(name=publisher)\n obj.publishers.add(temp)\n\n for tag in item['tags']:\n temp, created = Tag.objects.get_or_create(name=tag)\n obj.tags.add(temp)\n\n \"\"\"\n if Screenshot.objects.filter(game=obj).exists():\n if Screenshot.objects.get(game=obj).screenshot_url == 'http://www.visitcrickhowell.co.uk/wp-content/themes/cricwip/images/noimage_595.png' and item['screenshot'] != 'http://www.visitcrickhowell.co.uk/wp-content/themes/cricwip/images/noimage_595.png':\n Screenshot.objects.get(game=obj).screenshot_url = item['screenshot']\n else:\n if item['screenshot'] is None:\n Screenshot(game=obj).save()\n else:\n Screenshot(screenshot_url=item['screenshot'], game=obj).save()\n \"\"\"\n\n for screenshot in item['screenshot']:\n if not Screenshot.objects.filter(game=obj, screenshot_url=screenshot).exists():\n Screenshot(game=obj, screenshot_url=screenshot).save()\n\n\nwith open('./gamelist.json', 'r') as f:\n gamelist = json.load(f, encoding=\"utf-8\")\n\n\ngame_list = get_game_data(get_appid_steam(1, 100, gamelist))\nsave_object(game_list)\ngamelist.update(game_list)\n\n\nwith open(\"./gamelist.json\", 'w') as f:\n json.dump(gamelist, f)\n # f.write(json.dumps(item))\n\n# print(gamelist)\n\n\n# for item in game_list:\n# if item['title'] == \"PLAYERUNKNOWN'S BATTLEGROUNDS\":\n# print(item['screenshot'])","repo_name":"leedoe/Gamers","sub_path":"Webapp/steam.py","file_name":"steam.py","file_ext":"py","file_size_in_byte":9696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"21262035332","text":"from django.urls import path\nfrom . import views\n \nurlpatterns = [\n path('', views.ApiOverview, name='home'),\n path('create/', views.add_users, name='add-users'),\n path('all/', views.view_users, name='view_users'),\n path('users//delete/', views.delete_users, name='delete-users'),\n path('update//', views.update_users, name='update-users'),\n path('all/', views.view_users, name='view_users'),\n]","repo_name":"DiegosebasRR/api_djangi","sub_path":"api_admin/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"34645904546","text":"\n\ndef get_animals(database, species):\n\treturn None\n\nfrom datetime import datetime\nfrom unittest.mock import Mock\n\nmock = Mock(spec=get_animals)\n\nexpected = [\n\t('A', datetime(2018, 5, 3, 11, 5)),\n\t('B', datetime(2010, 6, 5, 12, 1)),\n\t('C', datetime(2019, 3, 4, 10, 2))\n]\n\nmock.return_value = expected\n\ndatabase = object()\nresult = mock(database, 'Mee')\nassert result == expected\n\n# validate input argument\nmock.assert_called_once_with(database, 'Mee')\n\n\nfrom unittest.mock import ANY\nmock = Mock(spec=get_animals)\nmock('database 1', 'Mee')\nmock('database 2', 'Aee')\nmock('database 3', 'Bee')\nmock.assert_called_with(ANY, 'Bee')\n\n\nclass MyError(Exception):\n\tpass\n\nmock = Mock(spec=get_animals)\nmock.side_effect = MyError('[Error] Ohhhhhh')\ntry:\n\tresult = mock(database, 'Mee')\nexcept MyError as e:\n\tprint(e)","repo_name":"RayOct18/effective_python","sub_path":"78_mock_methods.py","file_name":"78_mock_methods.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"40785794405","text":"from egz1atesty import runtests\n\ndef snow( S ):\n ans = 0\n i = 0\n S.sort(reverse=True)\n while i < len(S) and S[i] - i > 0:\n ans += S[i] - i\n i+=1\n return ans\n\n# zmien all_tests na True zeby uruchomic wszystkie testy\nruntests( snow, all_tests = True )\n","repo_name":"Adam0s007/DSA","sub_path":"exams/asd-egz1 2022/zad_a/egz1a.py","file_name":"egz1a.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"72699691653","text":"import scipy.io\nimport os, sys\nimport numpy as np\nnp.set_printoptions(threshold=sys.maxsize)\n\ndef read_body_model():\n\n full_name = '/home/ubuntu/Documents/US/NEU/RA/skeletal_action_recognition_code/data/UTKinect/body_model.mat'\n #full_name = 'body_model_mat.mat'\n \n print('full_name ',full_name)\n mat = scipy.io.loadmat(full_name, simplify_cells=True)\n print(mat.keys())\n #bm = mat['body_model']\n bm = mat\n\n for key in bm.keys():\n bm[key] = np.array([bm[key]])\n print(key, bm[key], bm[key].shape)\n\nread_body_model()","repo_name":"balaji-kss/RSL","sub_path":"preprocess_skeleton/read_mat.py","file_name":"read_mat.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"20295268338","text":"import os\nimport sys\nimport pandas as pd\nimport numpy as np \nfrom src.Project1.exception import CustonException\nfrom src.Project1.logger import logging\nfrom src.Project1.utils import load_object\n\nclass PredictPipeline:\n def __init__(self):\n pass\n\n def predict(self ,df):\n\n try:\n model_path = 'artifacts\\model.pkl'\n preprocessor_path = 'artifacts\\preprocessor.pkl'\n model = load_object(model_path)\n preprocessor = load_object(preprocessor_path)\n\n data_scaled = preprocessor.transform(df)\n pred = model.predict(data_scaled)\n\n return pred\n except Exception as e:\n raise CustonException(e,sys)\n\n\n\nclass CustomData:\n def __init__(self , gender , race_ethnicity , parental_level_of_education , lunch , test_preparation_course , reading_score , writing_score):\n \n self.gender = gender\n self.race_ethnicity = race_ethnicity\n self.parental_level_of_education = parental_level_of_education\n self.lunch = lunch\n self.test_preparation_course = test_preparation_course\n self.reading_score = reading_score\n self.writing_score = writing_score\n\n def get_data_as_data_frame(self):\n try:\n custom_data_input_dict = {\n \"gender\" : [self.gender], \n \"race_ethnicity\" : [self.race_ethnicity],\n \"parental_level_of_education\" : [self.parental_level_of_education],\n \"lunch\" : [self.lunch],\n \"test_preparation_course\" : [self.test_preparation_course],\n \"reading_score\" : [self.reading_score],\n \"writing_score\" : [self.writing_score]\n }\n\n return pd.DataFrame(custom_data_input_dict)\n\n\n except Exception as e:\n raise CustonException(e,sys)\n\n","repo_name":"BhavyaJethwa/Student-Performance-Prediction-Project-with-AWS-deployment-","sub_path":"src/Project1/pipelines/prediction_pipeline.py","file_name":"prediction_pipeline.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"28606588065","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n@Author : Xu\n \n@Software: PyCharm\n \n@File : process.py\n \n@Time : 2020/7/26 10:32 上午\n \n@Desc :\n \n\"\"\"\n\nimport re\n\ndef data_process(msg):\n \"\"\"\n 对用户query进行预处理\n :param msg:\n :return:\n \"\"\"\n msg = msg.strip()\n if msg.startswith('你好') and len(msg) > 8:\n msg = msg.replace('你好', '')\n num = re.findall(r'\\d+', msg)\n if num:\n if len(num[0]) > 5:\n msg = '卡号是:' + msg\n return msg\n\nif __name__=='__main__':\n msg = '131231233'\n data_process(msg)","repo_name":"charlesXu86/FAQ","sub_path":"model/bot/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"41658616015","text":"from bs4 import BeautifulSoup, SoupStrainer\nimport requests\nimport xlsxwriter\nimport time\n\n\n# zadatak: sa internet stranice https://Konzum.hr skinuti sve proizvode s pripadajućim cijenama (cca 6.100 proizvoda)\n# cijene ćemo preuzeti sa stranice kategorija, gdje su navedeni proizvodi, pojedine kategorije. ne treba otvarati stranicu pojedinačnog proizvoda\n# koristim html pasrser\n# prosječno vrijeme rada 220 sekundi\n\n# identificiram se kao Firefox browser\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/111.0.1\",\n \"Accept-Encoding\": \"*\",\n \"Connection\": \"keep-alive\"}\n\nproducts = []\ncategories = []\n\nstart_time = time.perf_counter()\ns = requests.Session()\n\nresponse = s.get('https://www.konzum.hr/kreni-u-kupnju', headers=headers)\nweb_page = response.content\nsoup = BeautifulSoup(web_page, 'html.parser')\n\nfor a in soup.find_all('a', {'class': 'category-box__link'}):\n cat1 = []\n if str(a['href']).startswith('/web/'):\n cat1.append(f'https://konzum.hr{a[\"href\"]}')\n cat1.append(f'{a.find(\"h3\", {\"class\": \"category-box__title\"}).get_text()}')\n cat1.append('1')\n categories.append(cat1)\n\n\n#sada tražim kategorije po nivoima - znam da ima max 3 lvla (nav-child-wrap-level-3)\n#prvo idem nivo 2\nfor ul in soup.find_all('ul', {'class' : 'nav-child-wrap-level-2'}):\n cat2 = []\n cat2.append (f'https://konzum.hr{ul.a[\"href\"]}')\n cat2.append (str(ul.a.get_text()).strip())\n cat2.append ('2')\n categories.append(cat2)\n\n#a onda nivo 3 \nfor ul in soup.find_all('ul', {'class' : 'nav-child-wrap-level-3'}):\n for li in ul.find_all('li'):\n cat3 = []\n if li.a is not None:\n cat3.append (f'https://konzum.hr{li.a[\"href\"]}')\n cat3.append (str(li.a.get_text()).strip())\n cat3.append('3')\n categories.append(cat3)\n\n# sortiram - priprema za brisanje nadkategorija\ncategories.sort(key=lambda x: x[0])\n\n\n# čistim kategorije od glavnih kategorija. zanimaju me samo najniži nivoi\ni = 0\nbr=len(categories) - 1\nwhile br > 0:\n x = str(categories[i][0])\n x_kat = int(categories[i][2])\n y = str(categories[i+1][0])\n\n if y.startswith(x) and x_kat == 1: \n del categories[i]\n else:\n i+=1\n br-=1\n\n\nprint(f'Kategorije pronađene: {time.strftime(\"%H:%M:%S\")} h')\n\n# brojac koristim radi izračuna brzine\nbrojac=1\n\n# krećem listanje proizvoda po kategorijama\nt = time.localtime()\n\nprint(f'Proizvod broj {brojac} u {time.strftime(\"%H:%M:%S\", t)}')\n\nproducts = []\nfor category in categories:\n response = s.get(category[0], headers=headers)\n web_page = response.content\n only_article_tags = SoupStrainer('article') #gledam samo article, radi ubrzanja\n soup = BeautifulSoup(web_page, 'html.parser', parse_only=only_article_tags)\n\n for article in soup.find_all('article'):\n \n if article is not None: \n product = [\n f'https://konzum.hr{article.find(\"a\", {\"class\" : \"link-to-product\"})[\"href\"]}',\n category[1],\n str(article.div.attrs['data-ga-id']),\n str(article.div.attrs['data-ga-name']),\n float(article.div.attrs['data-ga-price'].replace(' €','').replace(',','.'))\n ]\n products.append(product)\n brojac += 1\n #ispisujem svaki 500-ti da vidim brzinu \n if brojac %500 == 0: \n t = time.localtime()\n print(f'Proizvod broj {brojac} u {time.strftime(\"%H:%M:%S\", t)}')\n\n#ubacujem nazive stupaca, radi prebacivanja u Excel\nproducts.insert(0, ['poveznica','kategorija','sifra','naziv','cijena_EUR_kom'])\n\nwith xlsxwriter.Workbook('./2 Konzum/Konzum_html.xlsx') as workbook:\n worksheet = workbook.add_worksheet()\n for row_num, products in enumerate(products):\n worksheet.write_row(row_num, 0, products)\n\nend_time = time.perf_counter()\nelapsed_time = int(end_time) - int(start_time)\nprint(elapsed_time)\n\n","repo_name":"zkradija/python-web-scraping-primjeri","sub_path":"2 Konzum/konzum_html.py","file_name":"konzum_html.py","file_ext":"py","file_size_in_byte":3998,"program_lang":"python","lang":"sh","doc_type":"code","stars":2,"dataset":"github-code","pt":"44"} +{"seq_id":"17962570097","text":"#!/usr/local/anaconda3/bin/python3\n# -*- coding: utf-8 -*-\n\"\"\"\n题目描述\n小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。\n但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。\n没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,\n你能不能也很快的找出所有和为S的连续正数序列? Good Luck!\n\n输出描述:\n输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序\n\n思路:滑动窗口\n@author: xiaozuo\n\"\"\"\nclass Solution:\n def FindContinuousSequence(self, tsum):\n \"\"\"和为S的连续正数序列\"\"\"\n # write code here\n if not tsum:return []\n l = 1\n r = 2\n res = []\n while l < r:\n val = sum(range(l ,r+1))\n if val == tsum:\n res.append(list(range(l, r+1)))\n l += 1\n elif val < tsum:\n r += 1\n else:\n l += 1\n return res","repo_name":"xiaozuo7/algorithm_python","sub_path":"offer/FindContinuousSequence.py","file_name":"FindContinuousSequence.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"72932267654","text":"\"\"\" Access to documentation from the following files:\n\n - data_streams.csv\n - headers.json\n - question_type_names.json\n - power_events.csv\n\n\"\"\"\nimport os\nfrom logging import getLogger\nfrom pkg_resources import resource_filename\nfrom ..functions.io import read_json\n\n\nlogger = getLogger(__name__)\n\n\n# Get paths to files:\nDOCPATHS = {}\ndocnames = [\n \"data_streams.csv\",\n \"headers.json\",\n \"question_type_names.json\",\n \"power_events.csv\",\n]\nfor d in docnames:\n DOCPATHS[d] = resource_filename(__name__, os.path.join(\"noncode\", d))\n\n\n\"\"\"Dictionary of data streams.\n Keys are names of data streams, e.g. 'gps'.\n STREAMS[]['type']: Either 'passive' or 'survey'.\n STREAMS[]['Android']: True if available on Android phones.\n STREAMS[]['iOS']: True if available on iPhones.\n\"\"\"\nSTREAMS = {}\nwith open(DOCPATHS[\"data_streams.csv\"], encoding=\"utf-8\") as f:\n next(f) # skip header row\n for line in f:\n line = line.replace(\"\\n\", \"\") # get rid of line breaks\n stream_name, stream_type, android, ios = line.split(\",\")\n temp_dict = {\n \"type\": stream_type,\n \"Android\": android == \"True\",\n \"iOS\": ios == \"True\",\n }\n STREAMS[stream_name] = temp_dict\n\n\n\"\"\"Dictionary of headers for raw Beiwe data.\n For a given and , look up the header with:\n HEADERS[][]\n Possible values:\n List of column labels if is available for ,\n Or the string `To do` if it hasn't been documented yet,\n Or None if the data stream isn't available for .\n\"\"\"\nHEADERS = read_json(DOCPATHS[\"headers.json\"])\n\n\n\"\"\"Dictionary of question type names.\n Keys are names of survey question types, as used in Beiwe configuration\n files. Values provide concordance for different naming conventions used\n in raw data from Android and iOS platforms.\n For example:\n >>> QUESTION_TYPES['checkbox']['Android']\n 'Checkbox Question'\n >>> QUESTION_TYPES['checkbox']['iOS']\n 'checkbox'\n\"\"\"\nQUESTION_TYPES = read_json(DOCPATHS[\"question_type_names.json\"])\n\n\n\"\"\"Dictionary of power state events.\n Keys are ['Android', 'iOS'].\n POWER_EVENTS[][] is a tuple (, ).\n Note that does not appear in raw Beiwe data. Events are\n bundled under a single variable name that corresponds to common reporting\n processes.\n The numeric does not appear in raw Beiwe data. These are intended\n to provide a convenient & consistent encoding for variable levels.\n\"\"\"\nPOWER_EVENTS = {\"Android\": {}, \"iOS\": {}} # type: ignore\nwith open(DOCPATHS[\"power_events.csv\"], encoding=\"utf-8\") as f:\n next(f) # skip header row\n for line in f:\n line = line.replace(\"\\n\", \"\") # get rid of line breaks\n event, device_os, variable, code = line.split(\",\")\n POWER_EVENTS[device_os][event] = (variable, int(code))\n","repo_name":"onnela-lab/forest","sub_path":"forest/poplar/raw/doc.py","file_name":"doc.py","file_ext":"py","file_size_in_byte":3027,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"44"} +{"seq_id":"8606739338","text":"from unittest import TestCase\n\nfrom osbot_aws.apis.Lambda import Lambda\nfrom osbot_utils.utils.Dev import Dev\n\nfrom osbot_browser.browser.Browser_Lamdba_Helper import Browser_Lamdba_Helper\nfrom osbot_browser.view_helpers.Maps_Views import Maps_Views\nfrom gw_bot.Deploy import Deploy\n\n\nclass Test_Maps_Views(TestCase):\n\n def setUp(self):\n Deploy().setup() # set local ossbot environment\n self.maps_views = Maps_Views()\n self.png_data = None\n self.result = None\n\n def tearDown(self):\n if self.result:\n Dev.pprint(self.result)\n\n if self.png_data:\n Browser_Lamdba_Helper().save_png_data(self.png_data)\n\n def test_default(self):\n self.result = self.maps_views.default(headless=False)#,channel='DJ8UA0RFT')\n\n def test_exec_js(self):\n channel = 'DJ8UA0RFT'\n channel = None\n params = [\"maps.add_component('aaa 123' , 2, 1)\"]\n\n self.result = self.maps_views.exec_js(headless=False ,channel=channel, params=params)\n\n def test_via_lambda_execution(self):\n self.test_update_lambda()\n view = 'default'\n code = ''\n aws_lambda = Lambda('osbot_browser.lambdas.lambda_browser')\n payload = {\"params\": [\"maps\", view, code],\n 'data': { 'channel' : 'DJ8UA0RFT'}}\n self.result = aws_lambda.invoke(payload)\n\n def test_via_lambda_execution__version(self):\n self.test_update_lambda()\n aws_lambda = Lambda('osbot_browser.lambdas.lambda_browser')\n payload = {\"params\": [\"maps\", \"version\"],'data': {}}\n self.result = aws_lambda.invoke(payload)\n\n def test_update_lambda_browser(self):\n Deploy().setup().deploy_lambda__browser()\n \n def test_update_lambda_oss_bot(self):\n Deploy().setup().deploy_lambda__gw_bot()","repo_name":"owasp-sbot/OSBot-Browser","sub_path":"test/view_helpers/test_Maps_Views.py","file_name":"test_Maps_Views.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"44"} +{"seq_id":"71913345413","text":"# Core imports\nimport KratosMultiphysics\nimport KratosMultiphysics.kratos_utilities as KratosUtils\nfrom KratosMultiphysics import KratosUnittest as UnitTest\nfrom KratosMultiphysics.testing.utilities import ReadModelPart\n\n# HDF5 imports\nfrom KratosMultiphysics import HDF5Application as HDF5\nfrom KratosMultiphysics.HDF5Application.point_set_output_process import Factory as PointSetOutputProcessFactory\nfrom KratosMultiphysics.HDF5Application.core.file_io import OpenHDF5File\n\n# STL imports\nimport pathlib\n\n\n\nclass TestPointSetOutputProcess(UnitTest.TestCase):\n\n communicator = KratosMultiphysics.Testing.GetDefaultDataCommunicator()\n\n\n def setUp(self):\n KratosUtils.DeleteFileIfExisting(\"test_point_set_output.h5\")\n self.communicator.Barrier()\n\n\n def tearDown(self):\n # The output file is not actually checked yet in the script,\n # so if you need to validate the results, comment the line\n # below.\n self.communicator.Barrier()\n KratosUtils.DeleteFileIfExisting(\"test_point_set_output.h5\")\n\n\n def test_PointSetOutputProcessWrite(self):\n model, model_part = self.MakeModel()\n parameters = self.parameters\n number_of_steps = 10\n\n # Write coordinates and variables\n process_parameters = KratosMultiphysics.Parameters()\n process_parameters.AddValue(\"Parameters\", parameters)\n point_set_output_process = PointSetOutputProcessFactory(process_parameters, model)\n point_set_output_process.ExecuteInitialize()\n\n for i_step in range(number_of_steps):\n # Create new step data\n model_part.CloneTimeStep(2.0 * i_step)\n model_part.ProcessInfo[KratosMultiphysics.STEP] = i_step\n\n # Modify variables\n for node in model_part.Nodes:\n for variable, increment in zip((KratosMultiphysics.DISPLACEMENT_X, KratosMultiphysics.VELOCITY), (1.0, [0.0,0.0,1.0])):\n node.SetSolutionStepValue(variable,node.GetSolutionStepValue(variable) + increment)\n\n # Print output if necessary\n if point_set_output_process.IsOutputStep():\n point_set_output_process.PrintOutput()\n\n self.communicator.Barrier()\n\n # Open output file\n file_parameters = parameters[\"file_parameters\"].Clone()\n file_parameters[\"file_access_mode\"].SetString(\"read_only\")\n with OpenHDF5File(file_parameters, model_part) as file:\n # Check output file structure\n root = \"/test_point_set_output_{}\".format(parameters[\"model_part_name\"].GetString())\n self.assertTrue(file.IsGroup(root))\n self.assertTrue(file.IsDataSet(root + \"/POSITION\"))\n\n @property\n def parameters(self) -> KratosMultiphysics.Parameters:\n parameters = KratosMultiphysics.Parameters(\"\"\"{\n \"model_part_name\" : \"main\",\n \"positions\" : [[0.0, 0.0, 0.0]],\n \"output_variables\" : [\"DISPLACEMENT_X\", \"VELOCITY\"],\n \"output_frequency\" : 3,\n \"coordinates_prefix\" : \"/test_point_set_output_\",\n \"variables_prefix\" : \"/test_point_set_output_/test_step_\",\n \"file_parameters\" : {\n \"file_name\" : \"test_point_set_output.h5\",\n \"file_access_mode\" : \"read_write\"\n }\n }\"\"\")\n\n return parameters\n\n\n @staticmethod\n def MakeModel():\n model = KratosMultiphysics.Model()\n model_part = model.CreateModelPart(\"main\")\n model_part.ProcessInfo[KratosMultiphysics.DOMAIN_SIZE] = 3\n\n model_part.AddNodalSolutionStepVariable(KratosMultiphysics.DISPLACEMENT_X)\n model_part.AddNodalSolutionStepVariable(KratosMultiphysics.VELOCITY)\n\n ReadModelPart(str(TestPointSetOutputProcess.GetInputMDPAPath()), model_part)\n\n for node in model_part.Nodes:\n node.SetSolutionStepValue(KratosMultiphysics.DISPLACEMENT_X, node.X)\n node.SetSolutionStepValue(KratosMultiphysics.VELOCITY, [node.X, node.Y, node.Z])\n\n return model, model_part\n\n\n @staticmethod\n def GetInputMDPAPath() -> pathlib.Path:\n script_directory = pathlib.Path(__file__).absolute().parent\n kratos_root_directory = script_directory.parent.parent.parent\n test_input_directory = kratos_root_directory / \"kratos\" / \"tests\" / \"auxiliar_files_for_python_unittest\"\n test_file_stem = test_input_directory / \"mdpa_files\" / \"test_processes\"\n test_file_path = pathlib.Path(str(test_file_stem) + \".mdpa\")\n\n if not test_file_path.is_file():\n raise FileNotFoundError(\"Test file not found: {}\".format(test_file_path))\n\n return test_file_stem\n\n\n\n\n\nif __name__ == \"__main__\":\n UnitTest.main()","repo_name":"KratosMultiphysics/Kratos","sub_path":"applications/HDF5Application/tests/test_point_set_output_process.py","file_name":"test_point_set_output_process.py","file_ext":"py","file_size_in_byte":4816,"program_lang":"python","lang":"en","doc_type":"code","stars":906,"dataset":"github-code","pt":"44"} +{"seq_id":"33316624644","text":"import sys\nimport os\nimport pickle\nimport pandas as pd\n\n# Load data\n# Data manipulation\n#subsetSize = int(sys.argv[1])\nratings = pd.read_csv('/Users/affo/itu/sem_6/Bachelor/code/Bach_MRS/recBole/dataset/mpd-100k/mpd-100k.inter', sep='\\t')\nratings.rename(columns={'user_id:token':'user', 'item_id:token':'item', 'rating:token':'rating'}, inplace=True)\n\n#Load model\nmodel = sys.argv[1]\nmodelName = model + '100k'\nprint(modelName)\nmodel = pickle.load(open(f'../models/{modelName}.pkl', 'rb'))\nprint(model)\nnumberOfRecommendations = int(sys.argv[2])\n\n\n# Run through all users to get recommendations\nrecommendations = {}\nfor user in ratings['user'].unique(): \n user_recs = model.recommend(user, numberOfRecommendations)\n recommendations[user] = user_recs\n\nRecsImpMF = pd.concat(recommendations,keys=recommendations.keys())\nRecsImpMF = RecsImpMF.reset_index(level=1, drop=True).reset_index()\nRecsImpMF.rename(columns={'index':'user'}, inplace=True)\nRecsImpMF.to_csv(f'/Users/affo/itu/sem_6/Bachelor/code/Bach_MRS/lenskit/recs/{modelName}.csv', index=False)\nprint(f\"Saved recommendations to /Users/affo/itu/sem_6/Bachelor/code/Bach_MRS/lenskit/recs/{modelName}.csv\")","repo_name":"affo98/Bach_MRS","sub_path":"lenskit/evaluation/lkpyRecommendations.py","file_name":"lkpyRecommendations.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"19099027858","text":"FLASK_PORT = 8888\n\n# Define application directory\nimport os\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\n# Application threads\nTHREADS_PER_PAGE = 2\n\n# Secret key for signing cookies\nsecret_key = 'landslide'\n\n# Enable protection again(Cross-site Request Forgery)\nCSRF_ENABLED = True\n","repo_name":"exopas95/test-server-management","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"7063340996","text":"#!/usr/bin/env python\n# Using this CvBridge Tutorial for converting ROS images to OpenCV2 images\n# Citation: http://wiki.ros.org/cv_bridge/Tutorials/ConvertingBetweenROSImagesAndOpenCVImagesPython\n\nimport rospy\nimport cv2\nimport sys\nimport numpy as np\n# ROS Image message\nfrom std_msgs.msg import String\nfrom sensor_msgs.msg import Image\n# ROS Image message -> OpenCV2 image converter\nfrom cv_bridge import CvBridge, CvBridgeError\n\nclass image_converter:\n def __init__(self):\n self.bridge = CvBridge()\n #retrieve a BGR image from the kinect\n self.image_sub = rospy.Subscriber('camera/rgb/image_color' , Image , self.process_img_callback)\n self.image_pub = rospy.Publisher('surveillance_system', Image)\n\n # Converts a ROS Image message to openCV images\n def ros_to_np_img(self, ros_img_msg):\n return self.bridge.imgmsg_to_cv2(ros_img_msg,'bgr8')\n\n def process_img_callback(self,data):\n #a 10Hz publishing rate\n r = rospy.Rate(10)\n while not rospy.is_shutdown():\n try:\n cv_image = ros_to_openCV_img(data)\n #Publish our image to the 'surveillance_system' topic\n self.image_pub.publish(cv_image)\n r.sleep()\n except CvBridgeError as exception:\n print(exception)\n\n\nif __name__ == '__main__':\n rospy.init_node('process_image')\n #When a image_converter object instance is initialized it will automatically run the subsriber and publisher\n img_conv = image_converter()\n try:\n #Wait for messages to arrive on the subscribed topics, and exit the node when it is killed with Ctrl+C\n rospy.spin()\n except KeyboardInterrupt:\n print(\"Shutting down\")\n #Destroy all windows that are connected to a camera.\n cv2.destroyAllWindows()\n\n","repo_name":"jackieg017/securityBot","sub_path":"security/src/securitybot/src/process_image.py","file_name":"process_image.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"11343529119","text":"# function_import --------------------\n\nfrom transformers import LayoutLMForQuestionAnswering, pipeline\nfrom PIL import Image\n\n# function_code --------------------\n\ndef extract_invoice_info(image_path: str, question: str) -> str:\n \"\"\"\n Extracts information from an invoice image using a question-answering model.\n\n Args:\n image_path (str): The path to the invoice image.\n question (str): The question to be answered based on the invoice image.\n\n Returns:\n str: The answer to the question based on the invoice image.\n \"\"\"\n nlp = pipeline(task=\"question-answering\", model='microsoft/layoutlm-base-uncased-finetuned-posnegclassification')\n\n with open(image_path, \"rb\") as f:\n byte_im = f.read()\n pil_im = Image.open(io.BytesIO(byte_im))\n result = nlp({'question': question,'context':pil_im})\n return result['answer']\n# function_code --------------------\n\n# test_function_code --------------------\n\ndef test_extract_invoice_info():\n \"\"\"\n Tests the function 'extract_invoice_info'.\n \"\"\"\n # Test case 1\n image_path = 'https://templates.invoicehome.com/invoice-template-us-neat-750px.png'\n question = 'What is the invoice number?'\n assert isinstance(extract_invoice_info(image_path, question), str)\n\n # Test case 2\n image_path = 'https://miro.medium.com/max/787/1*iECQRIiOGTmEFLdWkVIH2g.jpeg'\n question = 'What is the purchase amount?'\n assert isinstance(extract_invoice_info(image_path, question), str)\n\n # Test case 3\n image_path = 'https://www.accountingcoach.com/wp-content/uploads/2013/10/income-statement-example@2x.png'\n question = 'What are the 2020 net sales?'\n assert isinstance(extract_invoice_info(image_path, question), str)\n\n return 'All Tests Passed'\n\n\n# call_test_function_code --------------------\n\ntest_extract_invoice_info()","repo_name":"vixuowis/Research-2309","sub_path":"Exp-2/output/hf-eval-data-v3-reuslt-13b-eval/f00185_extract_invoice_info.py","file_name":"f00185_extract_invoice_info.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"16879681105","text":"# [Shaolin Temple] But Everyone Else Has Nice Shoes\n\nTOWN_MISCREANT = 9310580\nKID_SHOES = 4034657\n\nsm.removeEscapeButton()\nsm.setSpeakerID(TOWN_MISCREANT)\nsm.setBoxChat()\nsm.sendNext(\"Hey! My shoes! Thanks for giving them back, demon!\")\n\nsm.flipBoxChat()\nsm.flipBoxChatPlayerAsSpeaker()\nsm.sendNext(\"I'm not a demon!\")\n\nsm.setSpeakerID(TOWN_MISCREANT)\nsm.setBoxChat()\nsm.sendNext(\"But only demons steal shoes from little kids who don't eat their orange mushrooms!\")\n\nsm.sendNext(\"Ma told me so!\")\n\nsm.flipBoxChat()\nsm.flipBoxChatPlayerAsSpeaker()\nsm.sendNext(\"It's not nice to stereotype against demons. The demon who BORROWED your shoes asked me to return them. He just wanted to try them on\")\n\nsm.setSpeakerID(TOWN_MISCREANT)\nsm.setBoxChat()\nsm.sendNext(\"Really? Did he dance in them? Because I loooove dancing in these shoes. Maybe he and I can be friends!\")\n\nsm.consumeItem(KID_SHOES)\nsm.giveExp(2020453)\nsm.completeQuestNoRewards(parentID) # completeQuest didn't work for w/e reason.\nsm.warp(701220350)\n","repo_name":"pokiuwu/v203.4","sub_path":"scripts/quest/q62013e.py","file_name":"q62013e.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"41"} +{"seq_id":"29621533048","text":"from sqlalchemy import Column, Integer, String\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.schema import UniqueConstraint\n\nBase = declarative_base()\n\n\nclass Player(Base):\n __tablename__ = 'player'\n id = Column(Integer, primary_key=True, autoincrement=True)\n slack_id = Column(String, unique=True)\n score = Column(Integer)\n\n def __repr__(self):\n return '' % (self.slack_id, self.score)\n\n\nclass Question(Base):\n __tablename__ = 'question'\n\n id = Column(Integer, primary_key=True, autoincrement=True)\n text = Column(String)\n answer = Column(String)\n times_asked = Column(Integer, default=0)\n blamed = Column(String, default=0)\n\n __table_args__ = (\n UniqueConstraint('text', 'answer', name='_text_answer_uc'),\n )\n","repo_name":"bernardito-luis/slack_trivia_bot","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"5180559065","text":"import os\nfrom colorama import init, Fore\nfrom time import sleep\n\nclass ConsolePrinter(object):\n def __init__(self, delay = 0.05):\n self.clear = 'cls' if os.name == 'nt' else 'clear'\n self.delay = delay\n init()\n\n def notify(self, data, inspecting, boundaries):\n os.system(self.clear)\n\n for idx in range(0, len(data)):\n output = '{0: 3d}, {1}'.format(data[idx], data[idx]*'|')\n if idx in boundaries:\n print(Fore.RED + output)\n elif idx in inspecting:\n print(Fore.GREEN + output)\n else:\n print(Fore.RESET + output)\n\n sleep(self.delay)\n","repo_name":"jasonamyers/sorting","sub_path":"console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"19248769489","text":"import PddlFiles.pddlLoop as pl\nimport IOTHubActuator.decider as decider\nimport time\nimport sys\nimport DataFiles.Constants as con\nimport DATA.dummyGenerator as dg\nimport WeatherForecast.weatherReaderPy as wrp\nimport SmartCitiesCalendar.calendarreader as crp\nimport RoomModel\nimport PddlFiles.pddlWriter as writer\nfrom pathlib import Path\nimport InformActuator.sendEmail as se\nfrom IOTHubSensors import SensorHub as sh\nimport numpy as np\nimport datetime\n\ndef loadRoom():\n room = RoomModel.initRoom()\n roomfile = Path(con.ROOMJSON)\n if roomfile.is_file():\n # file exists\n import json\n\n with open(con.ROOMJSON) as json_file:\n data = json.load(json_file)\n room.curtain.name = data[\"curtain\"][\"name\"]\n room.curtain.status = data[\"curtain\"][\"status\"]\n\n room.heater.name = data[\"heater\"][\"name\"]\n room.heater.status = data[\"heater\"][\"status\"]\n\n room.light.name = data[\"light\"][\"name\"]\n room.light.status = data[\"light\"][\"status\"]\n\n room.door.name = data[\"door\"][\"name\"]\n room.door.status = data[\"door\"][\"status\"]\n\n room.cooler.name = data[\"cooler\"][\"name\"]\n room.cooler.status = data[\"cooler\"][\"status\"]\n\n room.window.name = data[\"window\"][\"name\"]\n room.window.status = data[\"window\"][\"status\"]\n print(\"data loaded\")\n\n import LightControl.L_Control as lc\n lc.initial()\n room.light.status = 0\n import DoorWindowControl.WindowControl as wc\n wc.closeWindow()\n room.window.status = 0\n import DoorWindowControl.doorControl as dc\n dc.closeDoor()\n room.door.status = 1\n\n return room\n\nif __name__ == \"__main__\":\n room = loadRoom()\n loopcount = 0\n datacontainer = np.zeros((4, 10))\n current_time = datetime.datetime.fromisoformat('2020-07-13 08:05:00+02:00')\n while True:\n #hook to manipulate status from outside\n f = open(con.TRIGGERPATH)\n c = f.read(4)\n if c == \"True\":\n room = loadRoom()\n f2 = open(con.TRIGGERPATH, \"w\")\n f2.write(\"False\")\n f2.close()\n\n # inLecture = True\n # betweenLectures = False\n # afterLastLecture = False\n # shortBeforeFirstLecture = False\n\n # print(room.presenting)\n inLecture, betweenLectures, afterLastLecture, shortBeforeFirstLecture = crp.readurl(current_time)\n outtemp, weather = wrp.readurl()\n\n humidity, temperature, lightlevel, ir_value = sh.getData()\n # humidity, temperature, lightlevel, ir_value = daga.readData()\n datacontainer[0][loopcount] = humidity\n datacontainer[1][loopcount] = temperature\n datacontainer[2][loopcount] = lightlevel\n datacontainer[3][loopcount] = ir_value\n\n\n #def write_problem(room, filename=ss.TEST_PROBLEM, wanted_temp=24, wanted_lightlevel=400,\n #outside_temp=30, heaterstatus=0, coolerstatus=0, lightstatus=0,\n #windowstatus=0, doorstatus=0, curtainstatus=0,\n #presentation=False, inlecture=True, betweenLectures=False,\n #afterLecture=False, firstLecture=False, weather=0, tem=-1, hum=-1, lightl=-1, ir_val=-1):\n writer.write_problem(room, con.TEST_PROBLEM, con.DESIRED_TEMP, con.DESIRED_LIGHTLEVEL, outtemp,\n room.heater.status, room.cooler.status,\n room.light.status,\n room.window.status, room.door.status, room.curtain.status, room.presenting,\n inLecture, betweenLectures, afterLastLecture, shortBeforeFirstLecture, weather, temperature, humidity,\n lightlevel, ir_value)\n # time.sleep(2)\n\n actions = pl.pddlLoop()\n if len(actions) > 0:\n emailcontent = decider.generate_content(actions, room)\n se.sendEmail(\"noreply.scaiot.project@gmail.com\", emailcontent)\n room.saveConfig()\n time.sleep(1)\n current_time += datetime.timedelta(minutes=10, seconds=0)\n\n loopcount += 1\n if loopcount % 10 == 0:\n from numpy import savetxt\n\n loopcount = 0\n data0 = datacontainer[0, :]\n data1 = datacontainer[1, :]\n data2 = datacontainer[2, :]\n data3 = datacontainer[3, :]\n # save to csv file\n savetxt('DATA/hum.csv', data0, delimiter=',')\n savetxt('DATA/temp.csv', data1, delimiter=',')\n savetxt('DATA/light.csv', data2, delimiter=',')\n savetxt('DATA/ir_data.csv', data3, delimiter=',')\n","repo_name":"Jinaz/scaiot-project","sub_path":"Implementation/mainInitPoint.py","file_name":"mainInitPoint.py","file_ext":"py","file_size_in_byte":4667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"73938812283","text":"\"\"\" Class for plotting customer locations and paths.\n\"\"\"\n# import matplotlib.pyplot as plt\nfrom Tkinter import *\nfrom Customer import Customer\nfrom Depot import Depot\nfrom Path import Path\n\nclass Visual():\n\n width = 700\n height = 700\n root = Tk()\n canvas = Canvas(root, width=width, height=height)\n canvas.pack()\n root.title(\"Plot\")\n\n @staticmethod\n def scale_x(x):\n return x * 5 + Visual.width/2\n @staticmethod\n def scale_y(y):\n return -y * 5 + Visual.height/2\n @staticmethod\n def scale(item):\n return Visual.scale_x(item.x), Visual.scale_y(item.y)\n\n @staticmethod\n def plot_customers(depot, customers, label = True, connect = False, color = 'blue', width = 2):\n\n list = [depot]\n for customer in customers:\n list.append(customer)\n list.append(depot)\n\n Visual.canvas.create_rectangle(Visual.scale(depot), Visual.scale(depot)[0] + 5, Visual.scale(depot)[1] + 5, fill = 'red')\n if connect:\n for i in range(len(list) - 1):\n Visual.canvas.create_line(Visual.scale(list[i]), Visual.scale(list[i+1]), fill = color, width = 2)\n if label:\n for c in customers:\n Visual.canvas.create_text(Visual.scale(c), text=str(c.number))\n\n Visual.root.update()\n\n @staticmethod\n def clear():\n Visual.canvas.delete(ALL)\n\n @staticmethod\n def plot_path(path, connect='True', color = 'blue', width = 2):\n Visual.plot_customers(Depot(0,0), path.route, connect = connect, color = color, width = width)\n\n @staticmethod\n def plot_customers_old(depot, customers, label = True, connect = False, color = 'b', marker = 'o', linewidth = 2.0):\n x = []\n y = []\n for customer in customers:\n x.append(customer.x)\n y.append(customer.y)\n if label:\n Visual.subplot.text(customer.x, customer.y, str(customer.number), weight='bold', size='smaller')\n plt.scatter(depot.x, depot.y, color = 'r')\n plt.scatter(x, y, color = color, marker = marker)\n if connect:\n x.insert(0, depot.x)\n y.insert(0, depot.y)\n x.append(depot.x)\n y.append(depot.y)\n plt.plot(x, y, color = color, linewidth = linewidth)\n\n @staticmethod\n def plot_path_old(path, connect='True', color = 'b', marker = 'o', linewidth = 2.0):\n Visual.plot_customers(Depot(0,0), path.route, connect = connect, color = color, marker = marker, linewidth= linewidth)\\\n\n @staticmethod\n def show():\n plt.show()","repo_name":"conwayje/vrptw-pgss-2016","sub_path":"scripts/Visual.py","file_name":"Visual.py","file_ext":"py","file_size_in_byte":2589,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"41"} +{"seq_id":"41883050697","text":"from flask import Flask\nfrom flask_bootstrap import Bootstrap\nfrom flask_nav import Nav\nfrom flask_nav.elements import Navbar, View, Link\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_login import LoginManager\n\napp = Flask(__name__)\napp.config.from_object('config')\nBootstrap(app)\ndb = SQLAlchemy(app)\nnav = Nav()\n\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\nlogin_manager.login_view='login'\n\n\n@nav.navigation()\ndef mynavbar():\n return Navbar(\n 'Flaskr',\n View('Home', 'index'),\n View('Dashboard', 'dashboard'),\n View('Question', 'postquestion'),\n View('Sign up', 'signup'),\n )\n\n@nav.navigation()\ndef mynavbar_login():\n return Navbar(\n 'Flaskr',\n View('Home', 'index'),\n View('Dashboard', 'dashboard'),\n View('Log out', 'logout'),\n )\nnav.register_element('top', mynavbar)\nnav.init_app(app)\n# ...\n\n\nfrom app import views, models\n","repo_name":"wufubao/flaskr","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"2807352211","text":"from tkinter import *\n\nroot = Tk()\nroot.title(\"Nado GUI\")\nroot.geometry(\"640x480+300+100\") # 가로 * 세로 + x좌표 + y좌표\nroot.resizable(True, False) # x(너비), y(높이) 값 변경 불가 (창크기 변경 불가), default는 가능함\n\ntxt = Text(root, width=30, height=5)\ntxt.pack()\ntxt.insert(END,\"글자를 입력하세요.\")\n\ne = Entry(root, width=30) # 한줄만 입력, enter가 안됨\ne.pack()\ne.insert(0,\"한 줄만입력해요\")\n\ndef btncmd():\n # 내용 출력\n print(txt.get(\"1.0\", END)) # 1 : 첫번째 라인, 0 : 0번째 column위치\n print(e.get())\n\n # 내용 삭제\n txt.delete(\"1.0\", END)\n e.delete(0, END)\nbnt = Button(root, text=\"클릭\", command=btncmd)\nbnt.pack()\n\nroot.mainloop()","repo_name":"sanha-hwang/Python_DeepDive","sub_path":"3주차/gui_basic/5.listbox.py","file_name":"5.listbox.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"71678883645","text":"import csv\nimport json\n\nfrom argparse import ArgumentParser\n\n\ndef load_data(data):\n with open(data) as f:\n data = json.load(f)\n return data\n\n\ndef write_csv(json_data):\n f = csv.writer(open(\"cis_output.csv\", \"w\"))\n # Create headers\n f.writerow([\"country\", \"country_name\", \"store_name\", \"external_id\"])\n for data in json_data:\n f.writerow([data[\"address\"][\"country\"],\n data[\"address\"][\"country_name\"],\n data[\"store_name\"],\n data[\"external_id\"],\n ])\n\n\ndef create_parser():\n parser = ArgumentParser(description=\"\"\"\n Parse json data based on file and write necessary fields in a CSV file.\"\"\")\n parser.add_argument('--path', '-p',\n required=True,\n help=\"the path to the json file\")\n return parser\n\n\nif __name__ == '__main__':\n args = create_parser().parse_args()\n\n try:\n if args.path:\n data = load_data(args.path)\n write_csv(data)\n except IOError as error:\n print(error)\n","repo_name":"ArseniD/csv_parser","sub_path":"cis_parser.py","file_name":"cis_parser.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"39137908386","text":"n = int(input())\ntowers = list(map(int, input().split()))\nstack = []\nanswer = [0 for i in range(n)]\n \nfor i in range(n):\n while stack:\n if stack[-1][1] > towers[i]:\n answer[i] = stack[-1][0] + 1\n break\n else:\n stack.pop()\n stack.append([i, towers[i]])\n \nprint(*answer)","repo_name":"Real-Man-Club/Baekjoon","sub_path":"Mootata/3회차/2493.탑.py","file_name":"2493.탑.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"4387737975","text":"# coding: utf-8\n#!/usr/bin/env python\n\nimport argparse\nimport functools\nimport time\nfrom collections import defaultdict\n\n###### arguments ######\nparser = argparse.ArgumentParser()\nparser.add_argument('-i','--Input',metavar='File',dest='input',help='Input file',type=open,required=True)\nparser.add_argument('-o','--Output',metavar='File',dest='output',help='Output file',type=argparse.FileType('w'),required=True)\nparser.add_argument('-s','--sca',metavar='Int',dest='sca',help='sca num',type=int,default=30)\nargs = parser.parse_args()\n###### arguments ######\n\n### alnSize: aligned length (alnSize1 and alnSize2 is not identity becasue of some gaps and mismatches)\n### seqSize: for example, the length of scaffold 28 is 58444652\n\n### score name1 start1 alnSize1 strand1 seqSize1 name2 start2 alnSize2 strand2 ###\n### 128431 pilon_p_hic_scaffold_28 5910316 129308 + 58444652 chr1 75305415 129355 + ###\n\ndef metric(func):\n @functools.wraps(func)\n def wrapper(*args,**kw):\n print('\\n\\nCall %s()'%func.__name__)\n print('...')\n print('%s executed in %s\\n' %(func.__name__,time.strftime('%Y%m%d%H%M%S')))\n return func(*args,**kw)\n return wrapper\n\ndef num_only(text):\n '''pilon_p_hic_scaffold_28'''\n text = text.strip().split('_')\n return int(text[4])\n\n\n\n@metric\ndef extract_sca():\n dict = defaultdict(list)\n for line in args.input:\n line = line.strip().split()\n if len(line) != 0:\n if line[0] != '#':\n if num_only(line[1]) <= args.sca:\n index = num_only(line[1])\n dict[index].append(line[6])\n else:\n continue\n SortedDict = sorted(dict.items(), key=lambda e:e[0], reverse=False)\n\n for i in SortedDict:\n print >> args.output,i[0],list(set(i[1]))\n\nextract_sca()\n","repo_name":"ZihuaLiu666/graduation_thesis","sub_path":"scripts/scaffold_hit_chromosomes.py","file_name":"scaffold_hit_chromosomes.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"2559974428","text":"import struct\nimport sys\nimport zlib\n\nPNG_MAGIC = bytearray.fromhex(\"89 50 4E 47 0D 0A 1A 0A\")\n\nclass PNGImage:\n\tdef __init__(self):\n\t\tself.name = \"\"\n\t\tself.chunks = []\n\t\tself.width = 0\n\t\tself.height = 0\n\t\tself.bitdepth = 0\n\t\tself.colortype = 0\n\t\tself.compression = 0\n\t\tself.filtering = 0\n\t\tself.interlacing = 0\n\n\tdef resolution(self):\n\t\treturn str(self.width) + \"x\" + str(self.height)\n\n\tdef __str__(self):\n\t\ts = \"{\\n\"\n\t\ts += \"\\tResolution: \" + self.resolution() + \",\\n\"\n\t\ts += \"\\tBit Depth: \" + str(self.bitdepth) + \",\\n\"\n\t\ts += \"\\tColor Type: \" + str(self.colortype) + \",\\n\"\n\t\ts += \"\\tCompression: \" + str(self.compression) + \",\\n\"\n\t\ts += \"\\tFilter: \" + str(self.filtering) + \",\\n\"\n\t\ts += \"\\tInterlace: \" + str(self.interlacing) + \"\\n\"\n\t\ts += \"}\"\n\t\treturn s\n\n\tdef _compress(self):\n\t\tfor i in self.chunks:\n\t\t\tif i.type() == \"IDAT\":\n\t\t\t\tprint('BEFORE:\\t' + str(len(i.data)))\n\t\t\t\ti.data = zlib.compress(i.data, 9)\n\t\t\t\tprint('AFTER:\\t' + str(len(i.data)))\n\t\t\t\ti.length = struct.pack(\"!I\", len(i.data))\n\t\t\t\ti.crc = zlib.crc32(i.chunk_type + i.data)\n\t\t\t\ti.crc = struct.pack(\"!I\", i.crc)\n\n\tdef _decompress(self):\n\t\tfor i in self.chunks:\n\t\t\tif i.type() == \"IDAT\":\n\t\t\t\ti.data = bytearray(zlib.decompress(i.data))\n\n\tdef write_to_file(self, filename):\n\t\tself._compress()\n\t\twith open(filename, \"wb\") as f:\n\t\t\tf.write(PNG_MAGIC)\n\t\t\tfor i in self.chunks:\n\t\t\t\tf.write(i.length)\n\t\t\t\tf.write(i.chunk_type)\n\t\t\t\tf.write(i.data)\n\t\t\t\tf.write(i.crc)\n\nclass Chunk:\n\tdef __init__(self):\n\t\tself.length = bytearray()\n\t\tself.chunk_type = bytearray()\n\t\tself.data = bytearray()\n\t\tself.crc = bytearray()\n\n\tdef __str__(self):\n\t\treturn \"{Type: \" + self.type() + \", Length: \" + str(self.size()) + \"}\"\n\n\tdef size(self):\n\t\treturn int.from_bytes(self.length, byteorder=\"big\")\n\n\tdef checksum(self):\n\t\treturn int.from_bytes(self.crc, byteorder=\"big\")\n\n\tdef type(self):\n\t\treturn self.chunk_type.decode()\n\ndef parse(filename):\n\twith open(filename, \"rb\") as f:\n\t\theader = f.read(len(PNG_MAGIC))\n\t\tif header != PNG_MAGIC:\n\t\t\tprint(\"ERROR: File is not a PNG file: \" + filename)\n\t\t\tsys.exit(1)\n\n\t\timage = PNGImage()\n\t\timage.name = filename\n\n\t\twhile True:\n\t\t\tchunk = Chunk()\n\t\t\tchunk.length = f.read(4)\n\t\t\tchunk.chunk_type = f.read(4)\n\t\t\tchunk.data = f.read(int.from_bytes(chunk.length, byteorder=\"big\"))\n\t\t\tchunk.crc = f.read(4)\n\t\t\timage.chunks.append(chunk)\n\t\t\tif chunk.type() == \"IHDR\":\n\t\t\t\t_parse_ihdr(image, chunk)\n\t\t\tif chunk.type() == \"IEND\":\n\t\t\t\timage._decompress()\n\t\t\t\treturn image\n\ndef _parse_ihdr(image, chunk):\n\timage.width = int.from_bytes(chunk.data[0:4], byteorder=\"big\")\n\timage.height = int.from_bytes(chunk.data[4:8], byteorder=\"big\")\n\timage.bitdepth = int.from_bytes(chunk.data[8:9], byteorder=\"big\")\n\timage.colortype = int.from_bytes(chunk.data[9:10], byteorder=\"big\")\n\timage.compression = int.from_bytes(chunk.data[10:11], byteorder=\"big\")\n\timage.filtering = int.from_bytes(chunk.data[11:12], byteorder=\"big\")\n\timage.interlacing = int.from_bytes(chunk.data[12:13], byteorder=\"big\")\n","repo_name":"cosimon/PyOTP","sub_path":"image/png.py","file_name":"png.py","file_ext":"py","file_size_in_byte":2960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"74099569723","text":"import os\nfrom json import dumps\nimport asyncio\nimport websockets\nfrom telegram import send_telegram\nfrom receive_data import receive_result\nimport time\nimport requests\nimport urllib\nimport os\nfrom bs4 import BeautifulSoup\nimport numpy as np\nimport pandas as pd\nfrom helper import KafkaHelper\nimport websocket\nimport thread\nimport time\nimport json\n\ndef new_crawl(link):\n url = link\n\n item_info = requests.get(url).text\n soup = BeautifulSoup(item_info, 'html.parser')\n title = soup.select('div.content03 header.title-article01 h1')[0].get_text()\n title = title.replace('\"','')\n title = title.replace(\"'\",\"\")\n time = soup.select('div.content03 header.title-article01 p')[0].get_text()[4:]\n img_url = f\"https:{soup.select('div.img-con span img')[0]['src']}\"\n raw_content = soup.select('div.story-news.article')\n # print(raw_content)\n content_p = [item.select(\"p\") for item in raw_content]\n content_text = [item.get_text().strip() for item in content_p[0]]\n content = \"\\n\".join(content_text[1:])\n content = content.replace('\"','')\n content = content.replace(\"'\",\"\")\n data_dict = {\n \"title\": title,\n \"content\": content,\n \"link\": link\n }\n data_dict[\"time\"] = time\n data_dict[\"img_url\"] = img_url\n return data_dict\n\n\n\ndef on_message(ws, message):\n print(message)\n\ndef on_error(ws, error):\n print(error)\n\ndef on_close(ws):\n print(\"### closed ###\")\n\ndef on_open(ws):\n def run(*args):\n print(\"connected!\")\n data = receive_result()\n print(data)\n chat_data = new_crawl(data[\"link\"])\n chat_data[\"result\"] = data[\"result\"]\n send_telegram(data)\n ws.send(f\"{chat_data}\".replace(\"'\",'\"'))\n while True:\n time.sleep(1)\n ws.close()\n print(\"thread terminating...\")\n\n thread.start_new_thread(run, ())\n\nif __name__ == \"__main__\":\n websocket.enableTrace(True)\n ws = websocket.WebSocketApp(\"wss://random.example.com\",\n on_message = on_message,\n on_error = on_error,\n on_close = on_close)\n ws.on_open = on_open\n ws.run_forever()\n","repo_name":"Money-fin/backend","sub_path":"websoc2.py","file_name":"websoc2.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"13375248551","text":"import numpy as np\nfrom scipy import signal\nfrom scipy.io import wavfile\n\n# Returns the frequency of the nth key\ndef key_freq(n):\n return (2**(1 / 12))**(n - 49) * 440 # Hz\n\n# Converts the note and octave into a frequency\ndef note_freq(octave, note):\n # The note progression of most octaves\n notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'] \n\n if octave == 0:\n # 0th octave has only these 3\n notes = ['A', 'A#', 'B']\n\n if note in notes:\n freq = key_freq(notes.index(note) + 1)\n return freq\n else:\n print('Err: Note not in octave!')\n return 0\n\n elif octave == 8:\n # One note in the 8th octave\n notes = ['C']\n\n if note in notes:\n freq = key_freq(88)\n return freq\n else:\n print('Err: Note not in octave!')\n return 0\n\n else:\n # Else is a normal octave\n if note in notes:\n n = 12 * (octave - 1) + notes.index(note) + 4\n freq = key_freq(n)\n return freq\n else:\n print('Err: Note not in octave!')\n return 0\n\n# This function is stolen, bit of a black box to me\ndef get_adsr_weights(frequency, duration, length, decay, sustain_level, sample_rate=44100):\n\n assert abs(sum(length)-1) < 1e-8\n assert len(length) ==len(decay) == 4\n \n intervals = int(duration*frequency)\n len_A = np.maximum(int(intervals*length[0]),1)\n len_D = np.maximum(int(intervals*length[1]),1)\n len_S = np.maximum(int(intervals*length[2]),1)\n len_R = np.maximum(int(intervals*length[3]),1)\n \n decay_A = decay[0]\n decay_D = decay[1]\n decay_S = decay[2]\n decay_R = decay[3]\n \n A = 1/np.array([(1-decay_A)**n for n in range(len_A)])\n A = A/np.nanmax(A)\n D = np.array([(1-decay_D)**n for n in range(len_D)])\n D = D*(1-sustain_level)+sustain_level\n S = np.array([(1-decay_S)**n for n in range(len_S)])\n S = S*sustain_level\n R = np.array([(1-decay_R)**n for n in range(len_R)])\n R = R*S[-1]\n \n weights = np.concatenate((A,D,S,R))\n smoothing = np.array([0.1*(1-0.1)**n for n in range(5)])\n smoothing = smoothing/np.nansum(smoothing)\n weights = np.convolve(weights, smoothing, mode='same')\n \n weights = np.repeat(weights, int(sample_rate*duration/intervals))\n tail = int(sample_rate*duration-weights.shape[0])\n if tail > 0:\n weights = np.concatenate((weights, weights[-1]-weights[-1]/tail*np.arange(tail)))\n return weights\n\n# Gets the pure frequency of a note. No timbre\ndef get_note(octave, note, duration = 0, beats = 0, bpm = 0, waveform = 'sine', \n harmonics = 10, sample_rate=44100, amplitude=4096, save = False):\n if duration == 0:\n duration = beats * (60 / bpm)\n\n frequency = note_freq(octave, note)\n freqs = []\n amps = []\n\n for n in range(1,harmonics):\n freqs.append((n + 1) * frequency)\n amps.append((0.5)**n * amplitude)\n\n t = np.linspace(0, duration, int(sample_rate*duration)) # Time axis\n\n if waveform == 'sine':\n wave = amplitude*np.sin(2*np.pi*frequency*t)\n\n for i in range(len(freqs)):\n wave += amps[i]*np.sin(2*np.pi*freqs[i]*t)\n elif waveform == 'sawtooth':\n wave = amplitude*signal.sawtooth(2 * np.pi * frequency * t)\n\n for i in range(len(freqs)):\n wave += amps[i]*signal.sawtooth(2 * np.pi * freqs[i] * t)\n elif waveform == 'square':\n wave = amplitude*signal.square(2*np.pi*frequency*t)\n\n for i in range(len(freqs)):\n wave += amps[i]*signal.square(2*np.pi*freqs[i]*t)\n\n return wave, frequency\n\n# Adds the timbre of a piano to the pure frequency\nclass Note:\n def __init__(self, note, octave, duration, waveform = 'sine', adsr = [0.05, 0.25, 0.55, 0.15], \n harmonics = 10, sustain_level = 0.1, decay = [0.085, 0.02, 0.005, 0.1], save = False):\n # vvv This is important but you dont need to worry about it vvv\n self.octave = octave\n self.note = note\n self.duration = duration\n self.waveform = waveform\n self.adsr = adsr\n self.harmonics = harmonics\n self.sustain_level = sustain_level\n self.decay = decay\n self.save = save\n # ^^^ This stuff ^^^\n\n # This just gets us a raw pitch pipe note with no adsr\n wav, f = get_note(self.octave, self.note, self.duration, \n waveform = self.waveform, harmonics = self.harmonics, save = self.save)\n # This gets us the weights for the adsr\n weights = get_adsr_weights(f, self.duration, self.adsr, decay = self.decay, \n sustain_level = self.sustain_level)\n \n # Multiply the wave by the weights and normalize amplitude to get the final thing\n dat = wav * weights\n dat = dat * (4096/np.max(dat))\n\n # If the user wants to save the wav, save the wav\n if save:\n wavfile.write(('' + str(note) + str(octave) + '.wav'), rate=44100, data=dat.astype(np.int16))\n\n # Can now reference a note C4 with C4.wav to get the sine wave data\n self.wav = dat\n\nclass Chord():\n # args is a tuple with all the input variables\n def __init__(self, noteList):\n # Note: this will only work if we assume that the duration of all the notes are the same\n \n dur = noteList[0].duration * 44100\n self.wav = np.zeros((int(dur),))\n\n # Just add the wave data for each chord inputted\n for i in noteList:\n self.wav += i.wav\n \n\n#C4 = Note('C', 4, 4)\n#G4 = Note('G', 4, 4)\n\n#C4G4 = Chord([C4, G4])\n\n# wavfile.write('firstchord.wav', rate=44100, data=C4G4.wav.astype(np.int16))\n","repo_name":"stefanarseneau/moodly","sub_path":"moodly/en/src/synth.py","file_name":"synth.py","file_ext":"py","file_size_in_byte":5712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"2752976633","text":"class Solution:\n def minSteps(self, s: str, t: str) -> int:\n from collections import Counter\n _s = Counter(s)\n _t = Counter(t)\n # 两个Counter 求并\n union = _s | _t\n total, _s_count, _t_count = 0, 0, 0\n for item in union.items():\n total += item[1]\n for item in _s.items():\n _s_count += item[1]\n for item in _t.items():\n _t_count += item[1]\n return total * 2 - _s_count - _t_count \n\ndef main():\n sol = Solution()\n _input = (\"leetcode\", \"coats\")\n _output = sol.minSteps(*_input)\n print(_output)\n\nif __name__ == '__main__':\n main()\n","repo_name":"myalos/leetcode_contest","sub_path":"282/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"24270383389","text":"from django.urls import reverse\nfrom django.test.client import RequestFactory\n\nfrom rest_framework import status\n\nfrom core.extensions.test import sample_topic, sample_user, sample_board, APITestCase\nfrom boards.models import Board\nfrom boards.serializers import BoardSerializer\n\n\nBOARDS_URL = reverse('boards:board-list')\n\n\ndef detail_board_url(board: Board) -> str:\n \"\"\"Return the details url for a board\"\"\"\n return reverse('boards:board-detail', args=(board.id,))\n\n\nclass PublicBoardApiTests(APITestCase):\n \"\"\"Tests for the publicly available board api\"\"\"\n\n def setUp(self):\n self.user = sample_user()\n\n def test_retrieve_board_list(self):\n \"\"\"Test retrieving a list of board\"\"\"\n board = sample_board(title='Test board', description='Test board description')\n sample_topic(self.user.profile, board)\n sample_board(title='Another test board', description='Another test board description')\n\n res = self.client.get(BOARDS_URL)\n\n boards = Board.objects.all().order_by('id')\n serializer = BoardSerializer(boards, many=True, context={'request': RequestFactory().get(BOARDS_URL)})\n\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(res.data, serializer.data)\n self.assertEqual(len(res.data), 2)\n self.assertAllIn(('id', 'title', 'description', 'topics', 'created_at'), res.data[0].keys())\n self.assertAllIn(('href', 'title'), res.data[0]['topics'][0].keys())\n\n def test_retrieve_board_details(self):\n \"\"\"Test retrieving a board's details\"\"\"\n board = sample_board()\n topic = sample_topic(self.user.profile, board)\n url = detail_board_url(board)\n\n res = self.client.get(url)\n\n serializer = BoardSerializer(board, context={'request': RequestFactory().get(url)})\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(res.data, serializer.data)\n self.assertEqual(res.data['topics'][0]['title'], topic.title)\n self.assertAllIn(('id', 'title', 'description', 'topics', 'created_at'), res.data.keys())\n\n def test_create_board(self):\n \"\"\"Test creating a board\"\"\"\n superuser = sample_user(superuser=True, email='super@marsimon.com')\n self.client.force_authenticate(superuser)\n payload = {\n 'title': 'New board',\n 'description': 'New board description'\n }\n res = self.client.post(BOARDS_URL, payload)\n\n self.assertEqual(res.status_code, status.HTTP_201_CREATED)\n self.assertAllIn(('id', 'title', 'description', 'topics', 'created_at'), res.data.keys())\n\n board = Board.objects.get(id=res.data['id'])\n self.assertDictMatchesAttrs(payload, board)\n\n def test_create_board_fails_for_basic_user(self):\n \"\"\"Test that creating a board fails if not a superuser\"\"\"\n self.client.force_authenticate(self.user)\n payload = {\n 'title': 'New board',\n 'description': 'New board description'\n }\n res = self.client.post(BOARDS_URL, payload)\n\n self.assertEqual(res.status_code, status.HTTP_403_FORBIDDEN)\n\n def test_updating_board(self):\n \"\"\"Test updating a board\"\"\"\n board = sample_board(description='Old description')\n superuser = sample_user(superuser=True, email='super@marsimon.com')\n self.client.force_authenticate(superuser)\n\n payload = {\n 'description': 'New description'\n }\n\n res = self.client.patch(detail_board_url(board), payload)\n\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n board.refresh_from_db()\n self.assertEqual(board.description, payload['description'])\n\n def test_update_board_fails_for_basic_user(self):\n \"\"\"Test that basic users cannot update a board\"\"\"\n old_description = 'Old desciption'\n board = sample_board(description=old_description)\n self.client.force_authenticate(self.user)\n\n payload = {\n 'description': 'New description'\n }\n\n res = self.client.patch(detail_board_url(board), payload)\n self.assertEqual(res.status_code, status.HTTP_403_FORBIDDEN)\n board.refresh_from_db()\n self.assertEqual(board.description, old_description)\n","repo_name":"simon-martineau/boards","sub_path":"backend/boards/tests/test_board_api.py","file_name":"test_board_api.py","file_ext":"py","file_size_in_byte":4286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"36102135882","text":"#########################################\n#\n# MQTT Client\n# Original source: http://www.steves-internet-guide.com/into-mqtt-python-client/\n#\n#########################################\n\nimport paho.mqtt.client as mqtt\nimport time\n\ndef message_arrived(client, userdata, message):\n print(\"message received \" ,str(message.payload.decode(\"utf-8\")))\n print(\"message topic=\",message.topic)\n print(\"message qos=\",message.qos)\n print(\"message retain flag=\",message.retain)\n\nMQTT_server=\"192.168.1.9\" \ntopic = \"message_display\"\n\nclient = mqtt.Client(\"Pi Client\")\nclient.on_message=message_arrived\n\nprint(\"Connecting to MQTT Client...\")\nclient.connect(MQTT_server) \n\nclient.loop_start()\n\nprint(\"Subscribing to topic\",topic)\nclient.subscribe(topic)\n#print(\"Publishing message to topic\",topic)\n#client.publish(\"house/bulbs/bulb1\",\"OFF\")\n\nwhile(True):\n #nothing, just wait\n time.sleep(10)\n\n\n","repo_name":"carlosbravoa/mqtt-display-pi","sub_path":"mqtt-client.py","file_name":"mqtt-client.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"72730360124","text":"# -*- coding:utf-8 -*-\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nt = TreeNode('#')\n\n\nclass Solution:\n def Level_Serialize_UseList(self, pRoot):\n if pRoot == None:\n return []\n\n level_queue = []\n node_stack = [pRoot]\n val_res = []\n\n while node_stack:\n temp_res = []\n next_stack = []\n\n for i in node_stack:\n temp_res.append(i.val)\n\n if (i.left is not None):\n next_stack.append(i.left)\n\n if (i.right is not None):\n next_stack.append(i.right)\n\n val_res.append(temp_res)\n node_stack = next_stack\n return val_res\n\n def Level_Serialize_UsePound(self, pRoot):\n if pRoot == None:\n return []\n\n node_queue = [pRoot]\n val_res = [pRoot.val]\n\n while node_queue:\n next_queue = []\n\n for node in node_queue:\n if node.left != None:\n val_res.append(node.left.val)\n next_queue.append(node.left)\n else:\n val_res.append('#')\n\n if node.right != None:\n val_res.append(node.right.val)\n next_queue.append(node.right)\n else:\n val_res.append('#')\n\n node_queue = next_queue\n return val_res\n\n # Pound 是'#'号\n def Level_Serialize_WithoutPound(self, pRoot):\n res = self.Level_Serialize_UsePound(pRoot)\n\n new_res = []\n\n for i in res:\n if i != '#':\n new_res.append(i)\n else:\n continue\n\n return new_res\n\n def Level_DeSerialize_UsePound(self, NodeValList):\n node_queue = []\n head = TreeNode(NodeValList[0])\n node_queue.append(head)\n\n i = 0\n while i < len(NodeValList):\n len_num = len(node_queue)\n\n for j in range(len_num):\n\n\n pass\n\n\nif __name__ == '__main__':\n head = TreeNode(1)\n n2 = TreeNode(2)\n n3 = TreeNode(3)\n n4 = TreeNode(4)\n n5 = TreeNode(5)\n n6 = TreeNode(6)\n n7 = TreeNode(7)\n n8 = TreeNode(8)\n head.left = n2\n n2.left = n4\n head.right = n3\n n3.left = n5\n n3.right = n6\n n5.left = n7\n n5.right = n8\n\n s = Solution()\n print(s.Level_Serialize_WithoutPound(head))\n\n print(s.Level_Serialize_UseList(head))\n\n print(s.Level_Serialize_UsePound(head))\n\n\n","repo_name":"colabearwd/CodingQuiz","sub_path":"Sword_Point_to_Offer/Binary_Tree_Serialize_DeSerialize/LevelSerializeAndDeSerialize.py","file_name":"LevelSerializeAndDeSerialize.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"72831396604","text":"with open(\"inputs/input8.txt\", \"r\") as f:\n lines = f.read().splitlines()\n\ninstructions = []\n \ndef run_instruction(state, instructions):\n (pointer, acc) = state\n op = instructions[pointer][0]\n arg = instructions[pointer][1]\n\n if op == \"acc\":\n acc += arg\n pointer += 1\n elif op == \"jmp\":\n pointer += arg\n elif op == \"nop\":\n pointer += 1\n \n return (pointer, acc)\n\ndef terminal_acc(instructions):\n visited_insts = [False] * len(instructions)\n pointer = 0\n acc = 0\n\n while True:\n (new_p, new_acc) = run_instruction((pointer, acc), instructions)\n if new_p >= len(instructions):\n return acc\n elif visited_insts[new_p]:\n return None\n else:\n visited_insts[new_p] = True\n pointer = new_p\n acc = new_acc\n\nfor line in lines:\n op = line[:3]\n arg = int(line[4:])\n instructions += [(op, arg)]\n\nfor i in range(len(instructions)):\n if instructions[i][0] == \"acc\":\n next\n else:\n if instructions[i][0] == \"nop\":\n insts_prime = instructions.copy()\n insts_prime[i] = (\"jmp\", instructions[i][1])\n else:\n insts_prime = instructions.copy()\n insts_prime[i] = (\"nop\", instructions[i][1])\n final_acc = terminal_acc(insts_prime)\n\n if final_acc != None:\n print(final_acc)\n break","repo_name":"NiQuan/AdventofCode2020","sub_path":"days/day8p2.py","file_name":"day8p2.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"21857924137","text":"# -*- coding: utf-8 -*-\n\"\"\"\n @File: timelist_processing - time_process\n \n @Time: 2020/5/15 5:59 PM\n \n @Author: lotuswang\n \n \n\"\"\"\nimport os\nimport time\nimport sys\nfrom optparse import OptionParser\nfrom multiprocessing import Pool\nimport shutil\nimport numpy as np\nimport pandas as pd\nfrom timeprocess_utils import *\nimport matplotlib.pyplot as plt\n\n\ndef get_args():\n optParser = OptionParser(usage=\"%prog [-i] [-o]\", version=\"%prog 1.0\",\n description=\"A time processing tools for IDP learning\")\n optParser.add_option('-i', '--input_file', action='store', type=\"string\",\n dest='input_fn',\n help='path to the time_list.csv')\n optParser.add_option('-o', '--output_dir', action='store', type=\"string\", dest='output_dir',\n default='./day_result/',\n help='path to store the output files')\n optParser.add_option('-t', '--tmp_dir', action='store', type=\"string\", dest='temp_dir',\n default='./tmp_file/',\n help='path to the tmp dir, which is used to store the preprocessing files')\n\n (tmp_args, _) = optParser.parse_args()\n if tmp_args.input_fn and tmp_args.output_dir:\n return tmp_args\n else:\n optParser.parse_args(['-h'])\n exit()\n\n\nif __name__ == '__main__':\n try:\n args=get_args()\n input_sg = args.input_fn.split('/')[-1][:-4]\n in_date = args.input_fn.split('/')[-1][:8]\n\n check_path(args.temp_dir)\n check_path(args.output_dir)\n\n input_df = pd.read_csv(args.input_fn)\n index = ['任务', 'start', 'end', '效能', '时间矩阵', ]\n input_df = input_df[index]\n input_df.dropna(inplace=True)\n\n input_df = generate_duration(input_fn=args.input_fn,\n input_df=input_df)\n # print(input_df)\n # input_df.to_csv(args.input_fn, index=False)\n\n\n s = get_efficient_ratio(input_df)\n # print(s)\n plt.figure()\n plt.title(in_date + ' efficience pie chart')\n plt.axis('equal') # 保证长宽相等\n plt.pie(s, explode=[0.1, 0, 0],\n labels=s.index,\n shadow=True,\n autopct='%1.2f%%', )\n plt.savefig(args.output_dir+input_sg + '-efficience_pie_chart.png')\n print(args.output_dir+input_sg + '-efficience_pie_chart.png has been saved......')\n\n m = get_timematrix_ratio(input_df)\n # print(m)\n plt.figure()\n plt.title(in_date + ' time matrix pie chart')\n plt.axis('equal') # 保证长宽相等\n plt.pie(m,\n labels=m.index,\n shadow=True,\n autopct='%1.2f%%', )\n plt.savefig(args.output_dir+input_sg + '-time_matrix_pie_chart.png')\n print(args.output_dir+input_sg + '-time_matrix_pie_chart.png has been saved......')\n\n tag_df = handle_input_df(input_df)\n time_div_list = handle_tag_df(tag_df)\n\n x = np.arange(6, 25, 1) # x坐标\n plt.figure(figsize=(10, 6))\n plt.title(in_date + ' energy trend', fontsize=20)\n plt.plot(x, np.array(time_div_list),\n lw=3, c='lightblue',\n marker='o',\n ms=4,\n label='Y1') # 绘制y1\n plt.xticks(x) # x轴的刻度\n plt.grid()\n plt.xlim(6, 24) # x轴坐标范围\n plt.ylim(0, 110) # y轴坐标范围\n plt.xlabel('time') # x轴标注\n plt.ylabel('energy') # y轴标注\n # plt.legend() # 图例\n plt.savefig(args.output_dir+input_sg + '-energy_trend.png') # 保存图片\n print(args.output_dir+input_sg + '-energy_trend.png has been saved......')\n shutil.rmtree(args.temp_dir)\n except Exception as e:\n print(e)\n\n\n\n\n\n\n\n\n","repo_name":"LotusWang0723/time_analysis","sub_path":"time_process_day.py","file_name":"time_process_day.py","file_ext":"py","file_size_in_byte":3848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"3211078074","text":"import time\r\nimport paho.mqtt.client as mqtt\r\ndef on_connect(client,userdata,flags,rc):\r\n\tprint('Connected with code'+str(rc))\r\n\t #Sub\r\n\tclient.subscribe(\"Test/#\")\r\ndef on_message(client,userdata,msg):\r\n\tprint( str(msg.payload) )\r\n\tprint('ok')\r\nclass Sendler:\r\n\tdef __init__(self,fromInput,fromOutput,date):\r\n\t\tself.fromOutput=str(fromOutput)\r\n\t\tprint('Вывожу fromOutput')\r\n\t\tprint(fromOutput)\r\n\t\tself.fromInput=str(fromInput)\r\n\t\tprint('Вывожу fromInput')\r\n\t\tprint(fromInput)\r\n\t\tself.date=str(date)\r\n\t\tprint('Вывожу time')\r\n\t\tprint(date)\r\n\tdef send(self):\r\n\t\trun=1\r\n\t\ttime.sleep(0.1)\r\n\t\tclient=mqtt.Client()\r\n\t\tclient.on_connect=on_connect\r\n\t\tclient.on_message=on_message\r\n\t\tclient.connect(\"\")\r\n\t\tclient.username_pw_set(\"\")\r\n\t\ttime.sleep(0.4)\r\n\t\tclient.loop_start()\r\n\t\twhile run<3:\r\n\t\t\tclient.publish(\"Inform\",self.fromInput+\":\"+self.fromOutput+\":\"+self.date)\r\n\t\t\ttime.sleep(1.2)\r\n\t\t\trun+=1\r\n\t\t\tprint(run)\r\n\t\tclient.loop_stop()\r\n\t\tclient.disconnect()\r\n","repo_name":"yavnolib/bottravel","sub_path":"lib/mqtt.py","file_name":"mqtt.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"41"} +{"seq_id":"7968109227","text":"from __future__ import annotations\nimport asyncio\nimport aiohttp\nfrom bs4 import BeautifulSoup\nimport requests\nimport time as time\nimport cchardet as chardet\nfrom dataclasses import dataclass\nfrom queue import Queue, LifoQueue\nfrom typing import List\n\nPAGENAME = 'MissingNo.'\nWIKIBASEURL = 'https://en.wikipedia.org'\nPAGEURL = WIKIBASEURL + '/wiki/' + PAGENAME\nGOALPAGE = \"Pokémon (TV series)\"\n\n@dataclass\nclass Page:\n title: str\n link: str\n parent: str\n history: List[str] #See if we can use this to track the history rather than doing a final traversal backwards\n\ndef getAllLinksOnPageInitialVersion(url):\n #GetRequest to the wikipedia page\n allLinksOnPage = {}\n startTime = time.time()\n source = requests.get(url).text\n requestTime = time.time()\n\n #Get all content on page before See Also, References and External links based on which section appears first\n searchableText = removeSeeAlsoAndReferences(source)\n textSplittingTime = time.time()\n soup = BeautifulSoup(searchableText,'lxml')\n # The maintext is a dic with id \"mw-content-text\"\n maintext = soup.find_all('div',id='mw-content-text')[0]\n soupTime = time.time()\n for link in maintext.find_all('a'):\n if link.has_attr('href') and link['href'][0:6] == '/wiki/' and ':' not in link['href']:\n allLinksOnPage[link.text] = WIKIBASEURL + link['href']\n afterLoopTime = time.time()\n #print(f'Timing of GET-request: {requestTime - startTime}') \n #print(f'Timing of textSplitting {textSplittingTime-requestTime}')\n #print(f'Timing of generating soup {soupTime - textSplittingTime}')\n #print(f'Timing of the looping: {afterLoopTime - soupTime}')\n return allLinksOnPage\n\ndef getALlLinksOnPage(fromPage, source):\n #Get all content on page before See Also, References and External links based on which section appears first\n searchableText = removeSeeAlsoAndReferences(source)\n\n allLinksOnPage = []\n soup = BeautifulSoup(searchableText,'lxml')\n\n # The maintext is a dic with id \"mw-content-text\"\n maintext = soup.find_all('div',id='mw-content-text')[0]\n for link in maintext.find_all('a'):\n if link.has_attr('href') and link['href'][0:6] == '/wiki/' and ':' not in link['href']:\n allLinksOnPage.append(\n Page(\n title = link.text, \n link = WIKIBASEURL + link['href'], \n parent = fromPage.title, \n history= fromPage.history + [link.text])\n )\n return allLinksOnPage\n\ndef getAllLinksOnPageAsDataClasses(fromPage: Page):\n #GetRequest to the wikipedia page\n source = requests.get(fromPage.link).text\n return getALlLinksOnPage(fromPage, source)\n\ndef removeSeeAlsoAndReferences(source):\n seeAlsoSplit = ''\n referencesSplit = ''\n externalLinksSplit = ''\n \n searchableText = source.split(seeAlsoSplit)[0].split(referencesSplit)[0].split(externalLinksSplit)[0]\n return searchableText\n\ndef processForASingleElement(queueOfPages, visitedPages, found, foundPage):\n currentPage = queueOfPages.get() # Deques the first element in the queue. \n if(currentPage.title not in visitedPages):\n linksOnPage = getAllLinksOnPageAsDataClasses(currentPage) # TODO: This needs to be done asynchronously/ in parallell\n for subPage in linksOnPage: \n if subPage.title == GOALPAGE:\n print(\"Completed!\")\n found = True\n foundPage = subPage\n break\n queueOfPages.put(subPage)\n visitedPages.add(currentPage.title)\n return found, foundPage\n\n\ndef entireProcedureSynchronous(PAGENAME, PAGEURL):\n startpage = Page(PAGENAME, PAGEURL, None, history=[PAGENAME])\n \n queueOfPages = Queue()\n queueOfPages.put(startpage)\n\n visitedPages = set()\n found = False\n foundPage = startpage\n while(queueOfPages.empty()== False and found == False):\n found, foundPage = processForASingleElement(queueOfPages, visitedPages, found, foundPage)\n if found:\n break\n return found, foundPage\n\nasync def getAllLinksOnPageAsDataClassesAsyncVersion(fromPage: Page, session: aiohttp.ClientSession):\n #GetRequest to the wikipedia page\n async with session.get(fromPage.link) as response:\n source = await response.text()\n return getALlLinksOnPage(fromPage, source)\n\nasync def consumer(queue: asyncio.Queue,\n visitedPages: set):\n async with aiohttp.ClientSession() as session:\n while True:\n #TODO: Add a check for if we have visited the page before\n \n page: Page = await queue.get()\n if page.title in visitedPages:\n continue\n visitedPages.add(page.title)\n async with session.get(page.link) as response:\n source = await response.text()\n allLinksOnPage: List[Page] = getALlLinksOnPage(page, source)\n\n for subPage in allLinksOnPage:\n if subPage.title == GOALPAGE:\n print(f\"Completed! We found the page: {subPage.history}\")\n raise (Exception(\"We found the page!\"))\n asyncio.create_task(queue.put(subPage)) # a; It creates a task that will be executed in the future. It is a way to run a function in the background, without blocking the main thread.\n\nasync def main():\n startPage = Page(PAGENAME, PAGEURL, None, history=[PAGENAME])\n\n startTime = time.time()\n queue = asyncio.Queue()\n queue.put_nowait(startPage)\n loop = asyncio.get_event_loop()\n #loop.run_until_complete(consumer(queue))\n visitedPages = set()\n futures = [asyncio.ensure_future(consumer(queue, visitedPages), loop=loop) for i in range(2)] # q: Why do we need to create 10 futures? a: Because we want to run 10 consumers in parallell.\n try:\n await asyncio.gather(*futures)\n except Exception as e:\n for t in futures:\n t.cancel()\n #loop.run_until_complete(asyncio.gather(*futures))\n #loop.close()\n endTime = time.time()\n print(f'The time it took to run the entire async procedure was: {endTime - startTime}')\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n ","repo_name":"viroshau/WikiRace","sub_path":"getLinksFromPageWikipedia.py","file_name":"getLinksFromPageWikipedia.py","file_ext":"py","file_size_in_byte":6350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"21643835115","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport pandas as pd\nfrom math import pi\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar\nfrom view.components.charts.chart_abstract import ChartAbstract\n\n\n# df = pd.DataFrame({\n# 'models': ['Model 1', 'Modelo 2','Modelo 3', 'Modelo 4', 'Modelo 5', 'Modelo 6'],\n# 'R-Cuadrado': [3, 1, 0, 4, 3, 4],\n# 'AIC': [2, 1, 6, 3, 2, 2],\n# 'Log-likehead': [0, 3, 2, 4, 4, 4],\n# 'R-cuadrado adjustado': [2, 1, 3, 4, 2,1],\n# 'RSME': [2, 5, 3, 4, 3, 1],\n# 'BIC': [2, 2, 3, 4, 3, 2]\n# })\n\n# confiBasic = {\n# 'minY':0,\n# 'maxY':5,\n# 'yticks': [1,2,3,4],\n# 'yticksStr':[\"1\",\"2\",\"3\",\"4\"],\n# 'title':'Comparativa grafica entre los diferentes modelos',\n# 'showLegend':True\n# }\n\n\n\nclass ChartRadal(ChartAbstract):\n \n def __init__(self,parent):\n self.fig,self.ax = plt.subplots(subplot_kw={'projection': 'polar'})\n super().__init__(self.fig,self.ax,parent)\n \n \n \n def makeChart(self,_config,_dataFrame):\n \n colorText = '#000000'\n colorBackground = '#FFFFFF' \n colorAxes = '#000000'\n \n self.config = _config\n self.dataFrame = _dataFrame\n \n if 'colorText' in self.config.keys():\n colorText = self.config['colorText']\n \n if 'colorAxes' in self.config.keys():\n colorAxes = self.config['colorAxes']\n \n if 'colorBackground' in self.config.keys():\n colorBackground = self.config['colorBackground']\n \n my_palette = plt.cm.get_cmap(\"Set2\", len(self.dataFrame.index))\n \n for row in range(0, len(self.dataFrame.index)):\n self.make_spider(self.dataFrame, row, my_palette(row),colorText)\n \n # Draw ylabels\n self.ax.set_rlabel_position(0)\n if 'minY' in self.config.keys() and 'maxY' in self.config.keys() :\n plt.ylim(float(self.config['minY']),float(self.config['maxY']))\n \n if 'yticks' in self.config.keys() and 'yticksStr' in self.config.keys():\n plt.yticks(self.config['yticks'], self.config['yticksStr'], color=colorText, size=7)\n \n self.fig.patch.set_alpha(0) \n # Draw title and legend\n if 'showLegend' in self.config.keys() and self.config['showLegend'] == True:\n plt.legend(labels =self.dataFrame['models'],loc='center left', bbox_to_anchor=(1, 0.5))\n self.fig.patch.set_facecolor('#000000FF')\n self.fig.patch.set_alpha(0)\n self.ax.set_facecolor(colorBackground)\n # if 'title' in config.keys():\n # plt.title(config['title'], size=11, y=1.1)\n \n def make_spider(self,_dataFrame, row, color,colorText):\n # number of variable\n categories=list(_dataFrame)[1:]\n N = len(categories)\n # What will be the angle of each axis in the plot? (we divide the plot / number of variable)\n angles = [n / float(N) * 2 * pi for n in range(N)]\n angles += angles[:1]\n \n # If you want the first axis to be on top:\n self.ax.set_theta_offset(pi / 2)\n self.ax.set_theta_direction(-1)\n\n # Draw one axe per variable + add labels labels yet\n plt.xticks(angles[:-1], categories, color=colorText, size=8)\n\n \n\n # Ind1\n values=_dataFrame.loc[row].drop('models').values.flatten().tolist()\n values += values[:1]\n self.ax.plot(angles, values, color=color, linewidth=2, linestyle='solid')\n #self.ax.fill(angles, values, color=color, alpha=0.4)\n #self.ax.legend()\n\n # Add a title\n \n","repo_name":"vasha54/apm","sub_path":"view/components/charts/chart_radal.py","file_name":"chart_radal.py","file_ext":"py","file_size_in_byte":3723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"12760266134","text":"f = open(\"4.txt\", \"r\")\nlines = f.readlines()\n\ndrawnNumberStrings = lines[0].split(\",\")\ndrawnNumbers = []\n\nfor ns in drawnNumberStrings:\n drawnNumbers.append(int(ns))\n \ndef hasBingo(indices):\n numTrailingValues = 0\n lastValue = -10\n numOfEachMod = [0] * 5\n for i in indices:\n numOfEachMod[i % 5] += 1\n \n if (lastValue + 1 == i):\n numTrailingValues += 1\n if (numTrailingValues >= 4 and i % 5 == 4):\n return True\n else:\n numTrailingValues = 0\n lastValue = i\n \n return max(numOfEachMod) >= 5\n\nL = 5 # Side length\n\nbingoTiles = []\nfor i in range(1, len(lines)):\n line = lines[i]\n assert(len(line) > 0)\n if (len(line) == 1):\n bingoTiles.append([])\n else:\n for token in line.split():\n bingoTiles[-1].append(int(token))\n\nindicesOfMarkedTiles = [] \nfor tile in bingoTiles:\n indicesOfMarkedTiles.append([])\n\nlastNumber = -1\nnumBingos = 0\nfor n in drawnNumbers:\n if (len(bingoTiles) == 0):\n break\n print(len(bingoTiles))\n print(\"num \" + str(n))\n for i in range(len(bingoTiles))[::-1]:\n if (i >= len(bingoTiles)):\n break\n tile = bingoTiles[i]\n try:\n indicesOfMarkedTiles[i].append(tile.index(n))\n print(\"Appending \" + str(tile.index(n)))\n indicesOfMarkedTiles[i].sort()\n except ValueError:\n pass\n if (hasBingo(indicesOfMarkedTiles[i])):\n print(\"Bingo for tile \" + str(tile))\n numBingos += 1\n if (len(bingoTiles) == 1):\n lastNumber = n\n winTile = bingoTiles[0]\n winMarkedIndices = indicesOfMarkedTiles[0]\n \n bingoTiles.remove(tile)\n indicesOfMarkedTiles.remove(indicesOfMarkedTiles[i])\n \n \nprint(\"nBingos \" + str(numBingos))\nassert(len(bingoTiles) == 0)\nassert(len(indicesOfMarkedTiles) == 0)\n\n\nwinSum = 0\ntotalSum = 0\nfor i in range(len(winTile)):\n val = winTile[i]\n if i not in winMarkedIndices:\n winSum += val\n totalSum += val\n\n\nprint(totalSum)\nprint(winSum)\nprint(lastNumber)\nprint(lastNumber * winSum)\n \n","repo_name":"dangerousbear/AdventOfCode20","sub_path":"4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"11825813929","text":"#!/usr/bin/env python3\n\"\"\"\nProcess the raw data acquired from Derpibooru API to get the statistically\ninteresting bits.\n\"\"\"\n\nimport arrow\nimport pickle\n\nwith open('raw-data.pickle', 'r+b') as f:\n data = pickle.load(f)\n ships = data['ships']\n today = data['today']\n\nship_statistics = dict()\n\nfor k, v in ships.items():\n stat_blob = {\n \"total\": len(v.keys()),\n \"upvotes\": 0,\n \"wilson\": 0,\n \"date\": today,\n \"artists\": set(),\n \"artists_per_day\": 0,\n \"upvotes_per_day\": 0,\n \"wilson_per_day\": 0,\n \"amount_per_day\": 0,\n }\n for image in v.values():\n stat_blob['upvotes'] += image.get('upvotes', 0)\n stat_blob['wilson'] += image.get('score', 0)\n stat_blob['date'] = min(stat_blob['date'],\n arrow.get(image.get('first_seen_at',\n today)).datetime)\n stat_blob['artists'] |= set(\n x for x in image.get('tags').split(', ')\n if x.startswith('artist:'))\n\n timespan = (today - stat_blob['date']).days\n if timespan: # It can be zero if a shipping tag is actually empty.\n stat_blob['upvotes_per_day'] = stat_blob['upvotes'] / timespan\n stat_blob['wilson_per_day'] = stat_blob['wilson'] / timespan\n stat_blob['amount_per_day'] = stat_blob['total'] / timespan\n stat_blob['artists_per_day'] = len(stat_blob['artists']) / timespan\n\n ship_statistics[k] = stat_blob\n\nwith open(\"data.pickle\", \"w+b\") as f:\n pickle.dump(ship_statistics, f)\n\nprint(\"Done!\")\n","repo_name":"methanoliver/friendliest-fleet","sub_path":"process-data.py","file_name":"process-data.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"39343970454","text":"# 49-2번의 첫번째 답\n\n# x = [1,2,3]\n# x = x -1\n# print(x)\n\n\nimport numpy as np\n\n'''\ny = np.array([1,2,3,4,5,1,2,3,4,5])\ny = y - 1\nprint(y)\n\nfrom keras.utils import np_utils\ny = np_utils.to_categorical(y) # 시작이 0 부터(자동으로 넣는다.)\nprint(y)\nprint(y.shape)\n\ny_pred = np.argmax(y, axis =1) # axis =1 , 행별로 최댓값을 뺀다.\nprint(y_pred) # y = [0 1 2 3 4 0 1 2 3 4]\ny1_pred = np.argmax(y, axis=1 )+1 \nprint(y1_pred)\n'''\n\n# 2번의 두번째 답\n\ny = np.array([1,2,3,4,5,1,2,3,4,5])\n\nprint(y.shape) # (10, )\n# y = y.reshape(-1, 1)\ny = y.reshape(10, 1) # 2차원\n\nfrom sklearn.preprocessing import OneHotEncoder # shape를 맞춰줘야 한다.\n\naaa = OneHotEncoder()\naaa.fit(y)\ny = aaa.transform(y).toarray()\n\n'''\n[[1. 0. 0. 0. 0.]\n [0. 0. 1. 0. 0.]\n [0. 0. 0. 1. 0.]\n [0. 0. 0. 0. 1.]\n [1. 0. 0. 0. 0.]\n [0. 1. 0. 0. 0.]\n [0. 0. 1. 0. 0.]\n [0. 0. 0. 1. 0.]\n [0. 0. 0. 0. 1.]]\n'''\n\nprint(y)\n\nprint(y.shape) # (10, 5)","repo_name":"elf0508/Study-bit","sub_path":"keras/keras51_homework.py","file_name":"keras51_homework.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"41749312143","text":"import os\nimport typing as t\n\nimport click\n\nfrom ._common import Completer\nfrom .bash_impl import BashCompleter\nfrom .zsh_impl import ZshCompleter\n\n\ndef _get_completer_cls(\n shell: t.Optional[str] = None,\n) -> t.Type[Completer]:\n if shell is None:\n shell = \"bash\" # default to bash completion\n if \"SHELL\" in os.environ: # see if shell matches, e.g. `/bin/zsh`\n if os.path.basename(os.environ[\"SHELL\"]) == \"zsh\":\n shell = \"zsh\"\n return {\n \"zsh\": ZshCompleter,\n \"bash\": BashCompleter,\n }.get(shell, BashCompleter)\n\n\ndef generate_completion(command: click.Command, shell: t.Optional[str] = None) -> str:\n completer_cls = _get_completer_cls(shell=shell)\n return completer_cls(command).gen_completion()\n\n\ndef print_completion(command: click.Command, shell: t.Optional[str] = None) -> None:\n click.echo(generate_completion(command, shell=shell))\n","repo_name":"sirosen/click-native-completions","sub_path":"src/click_native_completions/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"43387939098","text":"n = int(input())\nl = list(map(int,input().split()))\n\nb = []\nfor i in l:\n if i % 2 == 0:\n b.append(i)\nif len(b) == n:\n print(\"True\")\nelse:\n print(\"False\")","repo_name":"syamsuri09/codemind-python","sub_path":"Even_Array.py","file_name":"Even_Array.py","file_ext":"py","file_size_in_byte":169,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"71350338043","text":"# import the necessary libraries\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D,MaxPool2D\nimport pickle\nfrom tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.python.keras.utils.np_utils import to_categorical\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport matplotlib.pyplot as plt\n# load the generate data from pickle files.\nX = pickle.load(open('X_more.pickle','rb'))\ny = pickle.load(open('y_more.pickle','rb'))\n# Covert the labels to one-hot encoding \ny = to_categorical(y,num_classes=6)\nX = X/255.0\n\nfrom sklearn.model_selection import train_test_split\nX_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state = 42)\n\n# Define the Keras model.\nmodel = Sequential()\nmodel.add(Conv2D(filters = 32, kernel_size=(5,5), padding = 'Same',activation = 'relu',input_shape = X.shape[1:]))\nmodel.add(Conv2D(filters = 32, kernel_size=(5,5), padding = 'Same',activation = 'relu'))\nmodel.add(MaxPool2D(pool_size = (2,2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3), padding = 'same', activation='relu'))\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3), padding = 'same', activation='relu'))\nmodel.add(MaxPool2D(pool_size = (2,2), strides = (2,2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(256, activation = 'relu'))\nmodel.add(Dropout(0.25))\nmodel.add(Dense(6,activation = 'softmax'))\noptimizer = RMSprop(lr=0.001,rho = 0.9,epsilon=1e-08,decay=0.0)\nmodel.compile(optimizer=optimizer, loss = 'categorical_crossentropy',metrics=['accuracy','categorical_accuracy'])\n\nepochs= 50\nbatch_size = 32\n# Use ImageDataGenerator for augmenting the train data\ndatagen = ImageDataGenerator(featurewise_center=False,samplewise_center=False,\nfeaturewise_std_normalization=False,samplewise_std_normalization=False,zca_whitening=False,rotation_range=10,zoom_range=0.1,width_shift_range=0.1, height_shift_range=0.1,horizontal_flip=False,vertical_flip=False)\n\ndatagen.fit(X_train)\n\nhistory = model.fit(datagen.flow(X_train,y_train,batch_size= batch_size),epochs = epochs,\n validation_data=(X_test,y_test),verbose = 2, steps_per_epoch=X_train.shape[0]//batch_size)\n\n# Plot the loss and accuray graphs.\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title('Model Accuracy')\nplt.legend(['Train','Test'],loc = 'upper left')\nplt.savefig('Accuracy.png')\n\n\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model Loss')\nplt.legend(['Train','Test'],loc='upper left')\nplt.savefig('Loss.png')\n\n# Save the model.\nmodel.save('my_model_more_epochs_50_new_metrics.h5')\n","repo_name":"alphacoder01/Hand_Gesture_Recognition","sub_path":"Code/Conv_net.py","file_name":"Conv_net.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"41"} +{"seq_id":"27354659380","text":"import numpy as nm \r\nimport matplotlib.pyplot as plt\r\nimport cartopy.crs as ccrs #used to plot over an Equirectangular projection\r\nfrom skyfield.api import load, EarthSatellite \r\n#import all the necessary libraries as well as the SGP4 propogator\r\n\r\nts = load.timescale()\r\n\r\n#TLE information for chosen satelite CATSAT-2\r\nTLE=\"\"\"1 44029U 98067PV 20317.18380552 .00059143 00000+0 44070-3 0 9993\r\n2 44029 51.6377 284.2794 0001336 353.3524 6.7456 15.72187078101707\"\"\"\r\n\r\n#Separate the TLE data into individual lines\r\nL1, L2 = TLE.splitlines()\r\n\r\n#the skyfield EarthSatellite will use the SGP4 model to calculate trajectory of satellite\r\nsatellite= EarthSatellite(L1, L2, name='CATSAT-2')\r\nprint(satellite)\r\n\r\n#define orbit for one day in intervals of 0.01\r\nday = nm.arange(0, 100, 0.01) # one 24 hour orbit\r\n#date as of completing code, ts.now() function can be used as well\r\ntime = ts.utc(2020, 11, 12, 0, day)\r\n\r\n#use the skyfield geocentric and subpoint functions to obtain longitude and latitude plotting points\r\ngeocentric = satellite.at(time)\r\nsubpoint = geocentric.subpoint()\r\n\r\nfig = plt.figure(figsize=(30, 40)) #figure size\r\nax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree()) #project over a Plate Carree projection\r\nax.stock_img() #cartopy stock flat earth image, no not that kind\r\nax.coastlines() #add coastlines\r\nax.gridlines(color='black') #add gridlines to plot\r\n\r\nax.scatter(subpoint.longitude.degrees, subpoint.latitude.degrees, transform=ccrs.PlateCarree(),\r\n color='blue')\r\nplt.show()\r\n\r\n\r\n\r\n","repo_name":"bris99/SGP4-TLE-Plotting","sub_path":"Kepler.py","file_name":"Kepler.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"35963652073","text":"import sys\n\ninfile0 = open(sys.argv[1])\ninfile1 = open(sys.argv[2])\n\nfor line0,line1 in zip(infile0,infile1):\n if line0 != line1:\n print(\"====================\")\n\n output0 = ' '.join(line0.split(','))\n output1 = ' '.join(line1.split(','))\n #print(output0.strip())\n #print(output1.strip())\n\n for o in [line0,line1]:\n vals = o.split(',')\n output = \"\"\n for v in vals:\n output += \"{0:5} \".format(v)\n print(output.strip())\n","repo_name":"mattbellis/matts-work-environment","sub_path":"python/Siena_classes/ExpertTA/compare_files.py","file_name":"compare_files.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"25642495900","text":"import royalnet.utils as ru\nimport royalnet.constellation.api as rca\nimport royalnet.constellation.api.apierrors as rcae\nfrom royalnet.backpack.tables import User\nfrom rasanahal.tables import Campaign, PartecipantAssociation\n\n\nclass CampaignCreateStar(rca.ApiStar):\n summary = \"Method that creates a campaign.\"\n description = \"\"\"Given the title of the campaign, it creates the campaign and\n the association with the dungeon master (the user that creates the campaign).\n \"\"\"\n methods = [\"POST\"]\n path = \"/api/campaign/create\"\n requires_auth = True\n parameters = {\n \"title\": \"The title of the campaign\"\n }\n tags = [\"user\"]\n\n async def api(self, data: rca.ApiData) -> ru.JSON:\n user = await data.user()\n CampaignT = self.alchemy.get(Campaign)\n ParT = self.alchemy.get(PartecipantAssociation)\n new_camp: Campaign = CampaignT(\n title=data['title']\n )\n dm_assoc: PartecipantAssociation = ParT(\n user_id=user.uid,\n campaign_id=new_camp,\n is_gm=True\n )\n data.session.add(new_camp)\n data.session.add(dm_assoc)\n data.session.commit()\n return {\"campaign\": new_camp.json(True)}\n","repo_name":"Fermitech-Softworks/rasanahal-backend","sub_path":"rasanahal/stars/campaign_create.py","file_name":"campaign_create.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"73686230522","text":"from kivymd.uix.screen import MDScreen\nfrom kivymd.app import MDApp\nfrom kivy.uix.image import Image\nfrom kivymd.uix.button import MDFillRoundFlatIconButton, MDFillRoundFlatButton\nfrom kivymd.uix.textfield import MDTextField\nfrom kivymd.uix.label import MDLabel\nfrom kivymd.uix.toolbar import MDToolbar\n\n\nclass App(MDApp):\n def flip(self):\n if self.state == 0:\n self.state = 1\n self.toolbar.title = \"inverted\"\n self.input.text = \"invertation\"\n\n self.converted.text = ''\n self.label.text = \"\"\n else:\n self.state = 0\n self.toolbar.title = \"non inverted\"\n self.input.text = \"non invertation\"\n\n self.converted.text = ''\n self.label.text = \"\"\n\n def work(self, args):\n if self.state == 0:\n x = int(self.input.text, 2)\n self.converted.text = str(x)\n self.label.text = \"result: \"\n else:\n x = int(self.input.text, 2)\n self.converted.text = str(x)\n self.label.text = \"result: \"\n\n def build(self):\n self.state = 0\n self.theme_cls.primary_palette = \"Amber\"\n screen = MDScreen()\n\n self.toolbar = MDToolbar(title=\"my app\")\n self.toolbar.pos_hint = {\"top\": 1}\n self.toolbar.right_action_items = [\n [\"rotate-3d-variant\", lambda x: self.flip()]]\n screen.add_widget(self.toolbar)\n # screen.add_widget(Image(\n # source=\"logo.png\",\n # pos_hint={\"center_x\":0.5,\"center_y\":0.7}\n # ))\n self.input = MDTextField(\n text=\"give the number\",\n halign=\"center\",\n size_hint=(0.8, 1),\n pos_hint={\"center_x\": 0.5, \"center_y\": 0.5},\n font_size=22\n )\n screen.add_widget(self.input)\n self.label = MDLabel(\n # text=\"result: \",\n halign=\"center\",\n pos_hint={\"center_x\": 0.5, \"center_y\": 0.35},\n theme_text_color=\"Secondary\"\n )\n\n self.converted = MDLabel(\n # text=\"777 \",\n halign=\"center\",\n pos_hint={\"center_x\": 0.5, \"center_y\": 0.3},\n theme_text_color=\"Primary\",\n font_style=\"H5\"\n )\n screen.add_widget(self.label)\n screen.add_widget(self.converted)\n\n screen.add_widget(MDFillRoundFlatButton(\n text=\"Count\",\n font_size=17,\n pos_hint={\"center_x\": 0.5, \"center_y\": 0.15},\n on_press=self.work\n ))\n\n return screen\n\n\nif __name__ == '__main__':\n App().run()\n","repo_name":"Gargooie/android_decimal_to_int","sub_path":"main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":2608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"29781999797","text":"from calculate.view import View\nfrom calculate.operators import Operators\n\n\nclass Controller:\n def __init__(self):\n self.operator = Operators()\n self.result = None\n\n def run(self):\n \"\"\"\n Run the principal Menu and the user can choose\n which operation they would like to use.\n \"\"\"\n View.print_menu()\n is_running = True\n while is_running:\n input_message = \"Enter your choice\"\n user_input = View.get_user_input(input_message)\n if self._is_input_valid(user_input):\n self._operations(user_input)\n View.print_menu()\n is_running = self._is_not_quit(user_input)\n View.end_message()\n\n def _is_input_valid(self, user_input):\n \"\"\"\n Checks if the input corresponds to a valid operation\n\n :param user_input: User input enter in the method run().\n :return: Return True if the input corresponds to a possibility of operations\n otherwise it return False.\n \"\"\"\n return user_input in [\"1\", \"2\", \"3\", \"4\"]\n\n def _operations(self, user_input):\n \"\"\"\n Calls the function corresponding with the operation requested by the user and\n determines the operation from user input\n\n :param user_input: User input enter in the method run().\n \"\"\"\n input_message = \"Enter the expression to calculate\"\n operation = View.get_user_input(input_message)\n\n if user_input == \"1\":\n self.result = self.operator.addition(operation)\n elif user_input == \"2\":\n self.result = self.operator.subtraction(operation)\n elif user_input == \"3\":\n self.result = self.operator.multiplication(operation)\n elif user_input == \"4\":\n self.result = self.operator.division(operation)\n\n View.print_result(operation, self.result)\n View.continue_message()\n\n def _is_not_quit(self, user_input):\n \"\"\"\n Checks if the user asked to stop the script\n\n :param user_input: User input enter in the method run().\n :return: True if the user ask for exit the script.\n \"\"\"\n return user_input != \"5\"\n","repo_name":"viajeradelaluz/platzi-backend-python","sub_path":"test_your_python_project/calculator_mini-project/calculate/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"43754120542","text":"import OpenGL.GL.shaders\n\nfrom OpenGL.GL import *\n\n\ndef load_shaderfile(file: str) -> bytes:\n src = \"\"\n\n with open(file) as f:\n src = f.read()\n\n return str.encode(src)\n\n\ndef compile_shader(*args, **kwargs):\n try:\n return OpenGL.GL.shaders.compileShader(*args, **kwargs)\n except OpenGL.GL.shaders.ShaderCompilationError as err:\n print(err)\n return None\n\ndef create_program(vert_file: str, frag_file: str) -> int|None:\n vert = load_shaderfile(vert_file)\n frag = load_shaderfile(frag_file)\n\n vert = compile_shader(vert, GL_VERTEX_SHADER)\n frag = compile_shader(frag, GL_FRAGMENT_SHADER)\n\n if vert is None or frag is None:\n return None\n\n\n return OpenGL.GL.shaders.compileProgram(vert, frag)\n\n","repo_name":"ShisatOwO/shader-fun","sub_path":"gl_util/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"24229804825","text":"import matplotlib.pyplot as plt\nimport ipdb\nimport numpy as np\nfrom matplotlib.patches import Polygon\n\n\ndef boxplots(data_dict, boxColors, xlabel, ylabel, title, top=1, bottom=0, scale=0.1):\n # unpack data_dict\n data = list(data_dict.values())\n xticklabels = list(data_dict.keys())\n\n fig, ax1 = plt.subplots(figsize=(10, 6))\n fig.canvas.set_window_title(title)\n plt.subplots_adjust(left=0.075, right=0.95, top=0.9, bottom=0.25)\n\n bp = plt.boxplot(data, notch=0, sym='+', vert=1, whis=1.5)\n plt.setp(bp['boxes'], color='black')\n plt.setp(bp['whiskers'], color='black')\n plt.setp(bp['fliers'], color='red', marker='+')\n\n # Add a horizontal grid to the plot, but make it very light in color\n # so we can use it for reading data values but not be distracting\n ax1.yaxis.grid(True, linestyle='-', which='major', color='lightgrey',\n alpha=0.5)\n\n # Hide these grid behind plot objects\n ax1.set_axisbelow(True)\n ax1.set_title(title)\n ax1.set_xlabel(xlabel)\n ax1.set_ylabel(ylabel)\n\n # Now fill the boxes with desired colors\n numBoxes = len(data)\n medians = list(range(numBoxes))\n for i in range(numBoxes):\n box = bp['boxes'][i]\n boxX = []\n boxY = []\n for j in range(5):\n boxX.append(box.get_xdata()[j])\n boxY.append(box.get_ydata()[j])\n boxCoords = list(zip(boxX, boxY))\n boxPolygon = Polygon(boxCoords, facecolor=boxColors[i])\n ax1.add_patch(boxPolygon)\n # Now draw the median lines back over what we just filled in\n med = bp['medians'][i]\n medianX = []\n medianY = []\n for j in range(2):\n medianX.append(med.get_xdata()[j])\n medianY.append(med.get_ydata()[j])\n plt.plot(medianX, medianY, 'k')\n medians[i] = medianY[0]\n # Finally, overplot the sample averages, with horizontal alignment\n # in the center of each box\n # plt.plot([np.average(med.get_xdata())], [np.average(data[i])],\n # color='w', marker='*', markeredgecolor='k')\n\n # Set the axes ranges and axes labels\n ax1.set_xlim(0.5, numBoxes + 0.5)\n ax1.set_ylim(bottom, top)\n xtickNames = plt.setp(ax1, xticklabels=xticklabels)\n plt.setp(xtickNames, rotation=45)\n pos = np.arange(numBoxes) + 1\n upperLabels = [str(np.round(s, 2)) for s in medians]\n weights = ['bold', 'semibold']\n for tick, label in zip(range(numBoxes), ax1.get_xticklabels()):\n ax1.text(pos[tick], top - (top*scale), upperLabels[tick],\n horizontalalignment='center', color=boxColors[tick]) # weight=weights[k]\n\n # Finally, add a basic legend\n # plt.figtext(0.80, 0.015, '*', color='white', backgroundcolor='silver',\n # weight='roman', size='medium')\n # plt.figtext(0.815, 0.013, ' Mean Value', color='black', weight='roman',\n # size='x-small')\n\n plt.tight_layout()\n","repo_name":"chandlersquires/perturbation-transportability","sub_path":"evaluation/plot_utils.py","file_name":"plot_utils.py","file_ext":"py","file_size_in_byte":2944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"38046562116","text":"numero = int(input('Digite um número inteiro: '))\n\ni = 1\ntotal = 0\nwhile i <= numero:\n if numero % i == 0:\n total += 1\n i += 1\n\nif total == 2:\n print('primo')\nelse:\n print('não primo')\n","repo_name":"carolayneaugusto/ICCPython-USP","sub_path":"primo.py","file_name":"primo.py","file_ext":"py","file_size_in_byte":206,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"41869834727","text":"__author__ = 'Tamby Kaghdo'\n\ndef encoder(str):\n lst = [x.lower() for x in list(str)]\n d_lst = []\n for i in lst:\n count = 0\n for j in lst:\n if i == j:\n count += 1\n if count == 1:\n d_lst.append(\"(\")\n else:\n d_lst.append(\")\")\n return ''.join(d_lst)\nprint(encoder(\"din\"))# => \"(((\"\nprint(encoder(\"recede\")) #=> \"()()()\"\nprint(encoder(\"Success\")) #=> \")())())\"\nprint(encoder(\"(( @\")) #=> \"))((\"\n","repo_name":"tkaghdo/stream-enterer","sub_path":"codewars/duplicate_encoder.py","file_name":"duplicate_encoder.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"7984523424","text":"n=int(input())\r\ni=1\r\nwhile i<=n:\r\n start_char = chr(ord(\"A\") + i - 1)\r\n j=1\r\n while j<=i:\r\n print(start_char,end=\"\")\r\n j=j+1\r\n print()\r\n i=i+1","repo_name":"Sonia0612/alpha-pattern","sub_path":"alpha pattern.py","file_name":"alpha pattern.py","file_ext":"py","file_size_in_byte":171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"38379099829","text":"# -*- coding: utf-8 -*-\n##WTF?\n##题目链接,http://www.shiyanbar.com/ctf/1886\nimport base64\nfrom PIL import Image, ImageDraw\n\ndef fileRead(path):\n f = open(path, 'r')\n content = f.read()\n f.close()\n return content\n\ndef generateQrcodePhotoFromList(ls, path, types):\n width, height = 256, 256\n image = Image.new('RGB', (width, height), (255, 255, 255))\n draw = ImageDraw.Draw(image)\n for x in xrange(width):\n for y in xrange(height):\n draw.point((x, y), fill = ls[x*256+y])\n image.save(path, types)\n \ndef main(): \n content = fileRead('code.txt')\n text = base64.b64decode(content)\n\n ls = []\n for char in text:\n if char == '0':\n ls.append((255, 255, 255))\n else:\n ls.append((0, 0, 0))\n\n generateQrcodePhotoFromList(ls, 'code.jpg', 'jpeg')\n \nif __name__ == '__main__':\n main()\n","repo_name":"szysec/ctftest","sub_path":"shiyanbar/MISC/WTF.py","file_name":"WTF.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"41"} +{"seq_id":"7605580433","text":"\"\"\"\n Domain Monitor\n ~~~~~~~~~~~~~\n\n Creates a peewee database instance and defines the model classes\n\n File name: models.py\n Authors: Richard West, Meg Williamson\n Python Version: 3.6\n\"\"\"\n\nfrom datetime import datetime\nfrom peewee import *\n\n# create a peewee database instance -- our models will use this database to\n# persist information\ndb = SqliteDatabase('domain_monitor.db')\n\n\n# define a base model class that specifies which database to use.\n# this way, any subclasses will automatically use the correct database.\nclass BaseModel(Model):\n class Meta:\n database = db\n\n\n# create a domain model to specify its fields and represent our domain table declaratively\nclass Firm(BaseModel):\n firm_name = CharField()\n email_address = CharField(null=True)\n known_domain = CharField(null=True)\n\n\nclass DomainReport(BaseModel):\n domain = CharField()\n severity = CharField(null=True)\n found_at = DateField(default=datetime.now().date())\n last_checked_at = DateField()\n firm = ForeignKeyField(Firm)","repo_name":"rickwest/domain-monitor","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"73567086523","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Created by yaochao on 2017/3/30\n\nimport scrapy\n\nfrom edu_source_crawler.items import KeqqItem\nfrom edu_source_crawler.misc.coursekeyword import keywords\n\n\nclass KeqqSpider(scrapy.Spider):\n name = 'keqq'\n search_url = 'https://ke.qq.com/course/list/'\n custom_settings = {\n 'ITEM_PIPELINES': {\n 'edu_source_crawler.pipelines.KeqqMongoPipeline': 300,\n },\n }\n\n def start_requests(self):\n for index, i in enumerate(keywords):\n for keyword in i:\n request = scrapy.Request(url=self.search_url + keyword, callback=self.parse1)\n request.meta['course_type'] = index\n yield request\n\n def parse1(self, response):\n course_type = response.meta['course_type']\n lis = response.xpath('//div[@class=\"market-bd market-bd-6 course-list course-card-list-multi-wrap\"]/ul/li')\n for li in lis:\n item = KeqqItem()\n item['course_type'] = course_type\n item['url'] = li.xpath('a/@href').extract_first().strip()\n item['_id'] = item['url']\n item['img_url'] = 'https:' + li.xpath('a/img/@src').extract_first().strip()\n item['title'] = li.xpath('a/img/@alt').extract_first()\n item['description'] = li.xpath('div/span/text()').extract_first()\n yield item\n\n # next_page\n next_url = response.xpath('//*[@class=\"page-next-btn icon-font i-v-right \"]/@href').extract_first()\n if next_url:\n next_url = response.urljoin(next_url)\n request = scrapy.Request(url=next_url, callback=self.parse1)\n request.meta['course_type'] = course_type\n yield request\n","repo_name":"yaochao/edu_source_crawler","sub_path":"edu_source_crawler/spiders/keqq.py","file_name":"keqq.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"20672427598","text":"import random\n\nstart_color = (0, 0, 0)\nend_color = (255, 255, 255)\n\n\ndef setup():\n global start_color, end_color\n background(255)\n fullScreen()\n strokeWeight(displayHeight/255)\n # start_color = (255, 0, 0)\n # end_color = (0, 0, 255)\n start_color = (0, 0, 0)\n end_color = (255, 255, 255)\n \n \ndef draw():\n global start_color, end_color\n y = 0\n \n v = 150\n new_color = lambda x: x + (x//v)*random.randint(-5, 5) + ((255//v)-(x//v))*random.randint(-5, 5)\n \n start_color = (\n constrain(new_color(start_color[0]), 0, 255),\n constrain(new_color(start_color[1]), 0, 255),\n constrain(new_color(start_color[2]), 0, 255)\n )\n end_color = (\n constrain(new_color(end_color[0]), 0, 255),\n constrain(new_color(end_color[1]), 0, 255),\n constrain(new_color(end_color[2]), 0, 255)\n )\n \n start_r = start_color[0]\n end_r = end_color[0]\n scope_r = end_r - start_r\n r = lambda x: start_r + ((scope_r*x) // 256)\n \n start_g = start_color[1]\n end_g = end_color[1]\n scope_g = end_g - start_g\n g = lambda x: start_g + ((scope_g*x) // 256)\n \n start_b = start_color[2]\n end_b = end_color[2]\n scope_b = end_b - start_b\n b = lambda x: start_b + ((scope_b*x) // 256)\n \n for color_ in range(256):\n r_ = r(color_)\n g_ = g(color_)\n b_ = b(color_)\n constrain(r_, 0, 255)\n constrain(g_, 0, 255)\n constrain(b_, 0, 255)\n stroke(r_, g_, b_)\n line(0, y, displayWidth, y)\n y += displayHeight/255\n","repo_name":"jd-develop/SNT-NSI","sub_path":"NSI/première/processing/misc/sketch_gradient/sketch_gradient.pyde","file_name":"sketch_gradient.pyde","file_ext":"pyde","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"37693776561","text":"import json\nimport sfdmap\nimport sqlite3\nimport numpy as np\nimport pylab as pl\nimport matplotlib.pyplot as plt\n\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\n\ndef radec2project(ra, dec):\n return (np.radians(ra) - np.pi, np.radians(dec))\n\n## https://arxiv.org/pdf/1809.01669.pdf\n## Appendix C1. \n\n## https://www.lsst.org/scientists/simulations/opsim/opsim-v335-benchmark-surveys\n## Knutt Olsen LSST notebooks.\n\n\nverbose = False\n\n## http://ops2.lsst.org/docs/current/architecture.html\nconn = sqlite3.connect('/global/cscratch1/sd/mjwilson/LSST/minion_1016_sqlite.db')\nc = conn.cursor()\n\nif verbose:\n for Table in ['ObsHistory', 'Field', 'Proposal', 'ObsHistory_Proposal', 'Proposal_Field']:\n c.execute('PRAGMA TABLE_INFO({})'.format(Table))\n\n print([tup[1] for tup in c.fetchall()])\n\n''' \n## Pg. 27 of https://github.com/LSSTScienceCollaborations/ObservingStrategy/blob/pdf/whitepaper/LSST_Observing_Strategy_White_Paper.pdf \n\n(52, u'conf/survey/GalacticPlaneProp.conf', u'WL', 4367689744, u'minion', 1016) -- \n(53, u'conf/survey/SouthCelestialPole-18.conf', u'WL', 4367691152, u'minion', 1016) -- \n(54, u'conf/survey/Universal-18-0824B.conf', u'WLTSS', 4367690832, u'minion', 1016) -- WFD. \n(55, u'conf/survey/NorthEclipticSpur-18c.conf', u'WLTSS', 4367690768, u'minion', 1016) -- \n(56, u'conf/survey/DDcosmology1.conf', u'WLTSS', 4367691088, u'minion', 1016) -- Deep Drilling fields \n'''\n\n## A many-to-many relationship table that stores the fields fieldID from the Field table that maps to the field centers or specified by proposal propID.\nc.execute('SELECT {coi1},{coi2} FROM {tn} WHERE {cn}=54'.format(coi1='Field_fieldID', coi2='proposal_field_id', tn='Proposal_Field', cn='Proposal_propID')) \n\n## WFD: Field_fieldID, proposal_field_id.\nWFD_FieldID, WFD_PropFieldID = np.split(np.array(c.fetchall()), 2, 1)\n\n## This table maps visits to a field to the proposal or proposals that requested it.\nc.execute('SELECT {coi1},{coi2} FROM {tn} WHERE {cn} = 54'.\\\n format(coi1='ObsHistory_obsHistID', coi2='obsHistory_propID', tn='ObsHistory_Proposal', cn='Proposal_propID'))\n\n## (29, 21064471)\n## (30, 21064477)\n_ObsHistID, _PropIDs = np.split(np.array(c.fetchall()), 2, 1)\n\n## Field properties.\nc.execute('SELECT {coi1},{coi2},{coi3},{coi4} FROM {tn}'.\\\n format(coi1='fieldID', coi2='fieldFov', coi3='fieldRA', coi4='fieldDec', tn='Field'))\n\n## Max field is 5292.\n_FieldID, _FieldFOV, _FieldRa, _FieldDec = np.split(np.array(c.fetchall()), 4, 1)\n\n## This table keeps a record of each visit made by the telescope during a simulated survey.\n## Note: all visits (2 x 15s exposures) where filter is u.\nc.execute('SELECT {coi1},{coi2},{coi3},{coi4},{coi5} FROM {tn} WHERE {cn}=\"u\"'.\\\n format(coi1='Field_fieldID', coi2='expMJD', coi3='visitExpTime', coi4='fiveSigmaDepth', coi5='obsHistID', tn='ObsHistory', cn='filter'))\n\nFieldIDs, MJDs, ExpTimes, FiveSigs, ObsHistID = np.split(np.array(c.fetchall()), 5, 1)\nObsHistID = ObsHistID.astype(np.int)\n\nprint(MJDs)\n\nassert np.all(np.diff(MJDs) >= 0.)\nassert np.all(np.diff(ObsHistID) >= 0.)\nassert np.all(np.diff(_ObsHistID) >= 0.)\n\n## Closing the connection to the database file \nconn.close()\n \nWFDFIELDIDS = []\n\n## By default, a scaling of 0.86 is applied to the map values to reflect the recalibration by Schlafly & Finkbeiner (2011) \n## https://github.com/kbarbary/sfdmap. \nsfd = sfdmap.SFDMap('/global/homes/m/mjwilson/SFD/')\n\nYEAR = 5\n_ObsHistID = _ObsHistID[:np.round(YEAR * 0.1 * len(_ObsHistID)).astype(np.int)]\n\nfor i, x in enumerate(ObsHistID):\n if x in _ObsHistID:\n WFDFIELDIDS.append(FieldIDs[i])\n\n print(100. * i / len(ObsHistID))\n \nfor i, id in enumerate(_FieldID): \n if id in WFDFIELDIDS:\n ## RA, DEC [degrees].\n ebv = sfd.ebv(_FieldRa[i], _FieldDec[i])\n\n c = SkyCoord(ra=_FieldRa[i] * u.degree, dec= _FieldDec[i] * u.degree, frame='icrs')\n cg = c.galactic\n l, b = cg.l, cg.b\n\n if (ebv > 0.3) | (np.abs(b) < 10.0 * u.degree):\n ## Remove regions of high SFD extinction. Remove the first matching value. \n WFDFIELDIDS.remove(id)\n\n\nWFDFIELDIDS = np.array(WFDFIELDIDS).astype(np.int)\nuWFDIDs, uVis = np.unique(WFDFIELDIDS, return_counts=True)\n\n## Visits per WFD field.\nhitmap = dict(zip(uWFDIDs, uVis))\n\n## Current expected performance\nsingle_m5 = {'u': 23.98, 'g': 24.91, 'r': 24.42, 'i': 23.97, 'z': 23.38, 'y': 22.47}\n\nfor i, x in enumerate(hitmap.keys()): \n ## Coadded 5 sig. depth = One. Visit. 5. Sigma. Depth. + 2.5 * np.log10(np.sqrt(Vists. Per. Filter.))\n hitmap[x] = {'CoAdd5sig': single_m5['u'] + 2.5 * np.log10(np.sqrt(hitmap[x])), 'Visits': hitmap[x]} \n\nfor i, y in enumerate(_FieldID.astype(np.int)):\n y = y[0]\n\n if y in list(hitmap.keys()):\n hitmap[y] = {'CoAdd5sig': hitmap[y]['CoAdd5sig'], 'Visits': hitmap[y]['Visits'], 'RA': _FieldRa[i][0],\\\n 'DEC': _FieldDec[i][0], 'FOV': _FieldFOV[i][0]}\n \nwith open('lsst_u_fiveyr.json', 'w') as outfile:\n json.dump(hitmap, outfile)\n\nprint('\\n\\nDone.\\n\\n')\n","repo_name":"michaelJwilson/LBGCMB","sub_path":"lsst/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":6180,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"19712062615","text":"import RPi.GPIO as GPIO\nimport time\nimport pyrebase\n\n\nconfig = { \n \"apiKey\": \"AIzaSyAVaxr6n1VKLm_dw96nQymhzT82heEyxMs\",\n \"authDomain\": \"smart-egg-incubator-3a272.firebaseapp.com\",\n \"databaseURL\":\"https://smart-egg-incubator-3a272-default-rtdb.firebaseio.com/\",\n \"storageBucket\": \"smart-egg-incubator-3a272.appspot.com\"\n}\nfirebase = pyrebase.initialize_app(config)\ndb = firebase.database()\n\nGPIO.setwarnings(False)\nDC1 = 27\nDC2 = 17\nBUTTON1 = 21\nBUTTON2 = 20\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(DC1,GPIO.OUT)\nGPIO.setup(DC2,GPIO.OUT)\nGPIO.setup(BUTTON1,GPIO.IN, pull_up_down = GPIO.PUD_UP)\nGPIO.setup(BUTTON2,GPIO.IN, pull_up_down = GPIO.PUD_UP)\n\ntype_selected = db.child(\"current_value\").get().val()\ntype_selected=type_selected.replace('\"', '')\nincubate_days = db.child(\"setting\").child(\"kind_properties\").child(str(type_selected)).child(\"incubate days\").get().val()\n\n# current_incubate_time = db.child(\"current incubate time\").get().val()/60/60/24\n\ndirection = \"\"\nnext_direction = \"one\"\nlast_move_time = time.time()\ntry:\n while True:\n button1_state = GPIO.input(BUTTON1)\n button2_state = GPIO.input(BUTTON2)\n if 0 < 7 < incubate_days-3:\n\n direction=next_direction\n\n if (button1_state == 1 and button2_state == 1) or (time.time()-last_move_time>10):\n last_move_time = time.time()\n print (\"last_move_time= \",last_move_time)\n\n if direction == \"one\":\n print(direction)\n GPIO.output(DC1, GPIO.LOW)\n GPIO.output(DC2, GPIO.HIGH)\n \n elif direction == \"two\":\n GPIO.output(DC1, GPIO.HIGH)\n GPIO.output(DC2, GPIO.LOW)\n \n elif button1_state == 0 and button2_state == 1:\n print(\"button1 pressed\")\n GPIO.output(DC1, GPIO.LOW)\n GPIO.output(DC2, GPIO.LOW)\n next_direction=\"two\"\n elif button1_state == 1 and button2_state == 0:\n print(\"button2 pressed\")\n next_direction=\"one\"\n GPIO.output(DC1, GPIO.LOW)\n GPIO.output(DC2, GPIO.LOW)\n \n \n time.sleep(1)\n\n\nexcept keyboardInterrupt:\n GPIO.cleanup() \n \n","repo_name":"rubaawawda/Smart-egg-incubator","sub_path":"tyrning eggs.py","file_name":"tyrning eggs.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"36756583182","text":"# Create your views here.\n#coding = utf-8\nfrom learn.wiki.models import Wiki\nfrom django.template import loader,Context\nfrom django.http import HttpResponse,HttpResponseRedirect\nfrom django.shortcuts import render_to_response\n\ndef index(request, pagename=\"\"):\n\tif pagename:\n#\t\t pages=Wiki.objects.get_list(pagename__exact=pagename)\n\t\tpages=Wiki.objects.filter(pagename=pagename)\n\t\tif pages:\n\t\t\treturn process('wiki/page.html',pages[0])\n\t\telse:\n\t\t\treturn render_to_response('wiki/edit.html',{'pagename':pagename})\n\telse:\n#\t\t page = Wiki.objects.get_object(pagename__exact='FrontPage')\n\t\tpage = Wiki.objects.get(pagename='FrontPage')\n\t\treturn process('wiki/page.html',page)\n\t\t\ndef edit(request,pagename):\n#\t page = Wiki.objects.get_object(pagename__exact=pagename)\n\tpage = Wiki.objects.get(pagename=pagename)\n\treturn render_to_response('wiki/edit.html',{'pagename':pagename,'content':page.content})\ndef save(request,pagename):\n\tcontent = request.POST['content']\n#\t pages = Wiki.objects.get_list(pagename__exact=pagename)\n\tpages = Wiki.objects.filter(pagename=pagename)\n\tif pages:\n\t\tpages[0].content = content\n\t\tpages[0].save()\n\telse:\n\t\tpage = Wiki(pagename=pagename,content=content)\n\t\tpage.save()\n\treturn HttpResponseRedirect(\"/wiki/%s\"% pagename)\n\nimport re\n\nr = re.compile(r'\\b(([A-Z]+[a-z]){2,})\\b')\ndef process(template,page):\n\tt= loader.get_template(template)\n\tcontent = r.sub(r'\\1',page.content)\n\tcontent = re.sub(r'[\\n\\r]+','
',content)\n\tc = Context({'pagename':page.pagename,'content':content})\n\treturn HttpResponse(t.render(c))\n\t","repo_name":"quake0day/undergraduate-CAU","sub_path":"learnDjango/wiki/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"26961639666","text":"from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket\nimport urllib.parse as url_parse\nfrom include.GetParamsDto import GetParamsDto\nfrom include.MainHandler import MainHandler\n\nclients = []\n\n\nclass SimpleChat(WebSocket):\n\n def handleMessage(self):\n h = MainHandler(clients)\n h.msgHandler(self)\n # for client in clients:\n # if client != self:\n # client.sendMessage(self.data)\n # server.close()\n\n def handleConnected(self):\n print(self.request.path, 'connected')\n get_params = url_parse.parse_qs(url_parse.urlsplit(self.request.path).query)\n self.get_params = GetParamsDto(get_params)\n h = MainHandler(clients)\n h.sendCustomJson(self, {'type': 'connection'})\n clients.append(self)\n\n def handleClose(self):\n clients.remove(self)\n print(self.address, 'closed')\n h = MainHandler(clients)\n h.sendStandardJson(self, 'disconnection')\n\n\nserver = SimpleWebSocketServer('', 5577, SimpleChat)\nserver.serveforever()\n","repo_name":"apuc/websocket","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"25249099501","text":"###\n### C-c C-c for eval buffer\n### example program: ATM\n## Create variables\nuser_pin = 5544\nuser_balance = 500\n\n## define an ATM\npin_attempt = input(\"enter your PIN \")\npin_attempt = int(pin_attempt) # convert to int\n\nif pin_attempt == user_pin:\n amount_to_withdraw = int(input(\"How much would youlike to withdraw? \"))\n if amount_to_withdraw <= user_balance:\n print(\"Disbursing \" + str(amount_to_withdraw))\n print(\"Remaining balance: \" + str(user_balance - amount_to_withdraw))\n else:\n print(\"Insufficient funds.\")\nelse:\n print(\"Invalid PIN.\")\n\nprint(\"Transaction concluded.\")\n","repo_name":"kaz-yos/learning-to-program-with-python","sub_path":"2014-04-27.atm.py","file_name":"2014-04-27.atm.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"36640975207","text":"import aspose.slides as slides\n\ndef convert_to_pdf():\n #ExStart:ConvertToPDF\n # The path to the documents directory.\n dataDir = \"./examples/data/\"\n outDir = \"./examples/out/\"\n\n # Instantiate a Presentation object that represents a presentation file\n with slides.Presentation(dataDir + \"welcome-to-powerpoint.pptx\") as presentation:\n\n # Save the presentation to PDF with default options\n presentation.save(outDir + \"convert_to_pdf_out.pdf\", slides.export.SaveFormat.PDF)\n #ExEnd:ConvertToPDF ","repo_name":"aspose-slides/Aspose.Slides-for-Python-via-.NET","sub_path":"examples/src/Presentations/Conversion/ConvertToPDF.py","file_name":"ConvertToPDF.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"8954911481","text":"\"\"\"Sum of Intervals from CodeWars.\n\n4 Kyu Kata Training from CodeWars\nTry this out at: https://www.codewars.com/kata/52b7ed099cdc285c300001cd\n\"\"\"\n__start_date__ = \"2022-07-01\"\n\n# Standard Library\nfrom operator import itemgetter\n\n\ndef sum_of_intervals(inters: list[tuple[int, int]]) -> int:\n \"\"\"Given list of intervals, return range that they cover.\n\n If two intervals overlap, that range should only be counted once\n\n Args:\n inters (List[Tuple[int, int]]): List of intervals\n\n Returns:\n int: Range covered by all intervals\n \"\"\"\n\n def is_overlapping_interval(\n inter1: tuple[int, int], inter2: tuple[int, int]\n ) -> bool:\n return inter1[0] <= inter2[0] <= inter1[1]\n\n sort_inter = sorted(inters, key=itemgetter(0, 1))\n interval_set = set()\n i = 0\n while i < len(sort_inter):\n forward_inter = i + 1\n result_interval = sort_inter[i]\n while forward_inter < len(sort_inter) and is_overlapping_interval(\n result_interval, sort_inter[forward_inter]\n ):\n result_interval = result_interval[0], max(\n result_interval[1], sort_inter[forward_inter][1]\n )\n forward_inter += 1\n i = forward_inter\n interval_set.add(result_interval)\n return sum(y - x for x, y in interval_set)\n\n\nclass Notes:\n \"\"\"Learnings from other solutions.\n\n - what we aren't looking for is the mathematical calculation, we just want to\n see the number of integers this range covers. so traverse all of them\n - problem with integer traversal is speed, since O(n*m) where m is\n the avg interval length. not each integer adds to\n the solution either\n \"\"\"\n\n ...\n\n\ndef top_bottom_pointers(intervals: list[tuple[int, int]]) -> int:\n \"\"\"Computes interval range with different method. # noqa: D401.\n\n Used for answer checking.\n \"\"\"\n interval_range, top = 0, float(\"-inf\")\n for start, end in sorted(intervals, key=itemgetter(0, 1)):\n if end <= top:\n continue\n max_in_inter = int(max(start, top))\n interval_range += end - max_in_inter\n top = end\n return interval_range\n\n\nif __name__ == \"__main__\":\n print(sum_of_intervals([(0, 1), (-1, 2)]))\n print(top_bottom_pointers([(0, 1), (-1, 2)]))\n","repo_name":"rhyn0/CodeWars-Problems","sub_path":"rank_up/sum_intervals.py","file_name":"sum_intervals.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"5510108151","text":"def intro(x):\n print(f'\\033[1:33m{\"-\" * 40:^40}\\033[m')\n print(f'\\033[1:33m{x:^40}\\033[m')\n print(f'\\033[1:33m{\"-\" * 40:^40}\\033[m')\n\n\ndef line():\n print(f'\\033[1m{\"-=\" * 25}\\033[m')\n\n\ndef player(name, goals):\n print(f'O jogador {name} fez \\033[1:32m{goals} gol(s)\\033[m no campeonato!')\n\n\nintro('FICHA DE JOGADOR')\n\nline()\n\nnome = str(input('Nome do Jogador: '))\ngols = str(input('Número de Gols: '))\n\nif gols.isnumeric():\n gols = int(gols)\nelse:\n gols = 0\nif nome.strip() == '':\n player('\\033[31m\\033[m', gols)\nelse:\n nome = str(f'\\033[1:34m{nome}\\033[m')\n player(nome, gols)\n\nline()\n","repo_name":"mende1/hello-world-python","sub_path":"mundo-3/ex103.py","file_name":"ex103.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"37387740579","text":"# A very easy tube shaped puzzle. Solvable in three moves.\n\n# Import\nfrom tkinter import *\nimport tkinter as tk\nfrom random import randint\n \n# Format Window\nwindow = tk.Tk()\nwindow.title('Tube Puzzle')\nwindow.geometry('600x300')\n\n# Define Rings\nring = [0, 1, 2, 3, 4, 5, 6]\nring_len = len(ring)\n\n# Define Ring Indices\ni = 0\nj = 0\nk = 0\nl = 0\nm = 0\n\n# Format Columns\nwindow.columnconfigure(0, weight=1)\nwindow.columnconfigure(1, weight=1)\nwindow.columnconfigure(2, weight=1)\nwindow.columnconfigure(3, weight=1)\nwindow.columnconfigure(4, weight=1)\nwindow.columnconfigure(5, weight=1)\nwindow.columnconfigure(6, weight=1)\n\n# Format Rows\nwindow.rowconfigure(0, weight=1)\nwindow.rowconfigure(1, weight=1)\nwindow.rowconfigure(2, weight=1)\nwindow.rowconfigure(3, weight=1)\nwindow.rowconfigure(4, weight=1)\nwindow.rowconfigure(5, weight=1)\nwindow.rowconfigure(6, weight=1)\nwindow.rowconfigure(7, weight=1)\n\n# Prepare Output Interface\nl0 = tk.Label(window, bg='white', width=10, text=ring[i])\nl0.grid(column=1, row=1, pady=15)\n\nl1 = tk.Label(window, bg='white', width=10, text=ring[j])\nl1.grid(column=2, row=1, pady=15)\n\nl2 = tk.Label(window, bg='white', width=10, text=ring[k])\nl2.grid(column=3, row=1, pady=15)\n\nl3 = tk.Label(window, bg='white', width=10, text=ring[l])\nl3.grid(column=4, row=1, pady=15)\n\nl4 = tk.Label(window, bg='white', width=10, text=ring[m])\nl4.grid(column=5, row=1, pady=15)\n\n# Define Functions\ndef twist_up():\n # get indices\n global i\n global j\n global k\n global l\n global m\n\n # twist first, middle, and last column clockwise\n if (var1.get() == 0):\n i = (i + 1) % ring_len\n k = (k + 1) % ring_len\n m = (m + 1) % ring_len\n l0.config(text=ring[i])\n l2.config(text=ring[k])\n l4.config(text=ring[m])\n\n #twist first three columns clockwise\n elif (var1.get() == 1):\n i = (i + 1) % ring_len\n j = (j + 1) % ring_len\n k = (k + 1) % ring_len\n l0.config(text=ring[i])\n l1.config(text=ring[j])\n l2.config(text=ring[k])\n\n # twist last three columns clockwise\n elif (var1.get() == 2):\n k = (k + 1) % ring_len\n l = (l + 1) % ring_len\n m = (m + 1) % ring_len\n l2.config(text=ring[k])\n l3.config(text=ring[l])\n l4.config(text=ring[m])\n\ndef twist_down():\n # get indices\n global i\n global j\n global k\n global l\n global m\n\n # twist first, middle, and last column counter-clockwise\n if (var1.get() == 0):\n i = (i - 1) % ring_len\n k = (k - 1) % ring_len\n m = (m - 1) % ring_len\n l0.config(text=ring[i])\n l2.config(text=ring[k])\n l4.config(text=ring[m])\n\n #twist first three columns counter-clockwise\n elif (var1.get() == 1):\n i = (i - 1) % ring_len\n j = (j - 1) % ring_len\n k = (k - 1) % ring_len\n l0.config(text=ring[i])\n l1.config(text=ring[j])\n l2.config(text=ring[k])\n \n # twist last three columns counter-clockwise\n elif (var1.get() == 2):\n k = (k - 1) % ring_len\n l = (l - 1) % ring_len\n m = (m - 1) % ring_len\n l2.config(text=ring[k])\n l3.config(text=ring[l])\n l4.config(text=ring[m])\n\ndef reset():\n # set indices\n global i\n global j\n global k\n global l\n global m\n i = 0\n j = 0\n k = 0\n l = 0\n m = 0\n\n # print\n l0.config(text=ring[i])\n l1.config(text=ring[j])\n l2.config(text=ring[k])\n l3.config(text=ring[l])\n l4.config(text=ring[m])\n \n\ndef scramble():\n # get indices\n global i\n global j\n global k\n global l\n global m\n i = randint(0, ring_len - 1)\n j = 0\n k = randint(0, ring_len - 1)\n l = 0\n m = randint(0, ring_len - 1)\n\n # set indices j and l\n j = (k - m) % ring_len\n l = (k - i) % ring_len\n\n\n # print\n l0.config(text=ring[i])\n l1.config(text=ring[j])\n l2.config(text=ring[k])\n l3.config(text=ring[l])\n l4.config(text=ring[m])\n \n# Define Radio Button Variable\nvar1 = tk.IntVar()\n\n# Prepare User Input Interface\nc1 = tk.Radiobutton(window, text='Free', variable=var1, value=0)\nc1.grid(column=2, row=2, sticky=tk.W)\n\nc2 = tk.Radiobutton(window, text='Button 1', variable=var1, value=1)\nc2.grid(column=2, row=3, sticky=tk.W)\n\nc3 = tk.Radiobutton(window, text='Button 2', variable=var1, value=2)\nc3.grid(column=2, row=4, sticky=tk.W)\n\nb1 = tk.Button(window, text='up', height=1, command=twist_up)\nb1.grid(column=4, row=2)\n\nb2 = tk.Button(window, text='down', height=1, command=twist_down)\nb2.grid(column=4, row=3)\n\nb3 = tk.Button(window, text='scramble', height=1, command=scramble)\nb3.grid(column=2, row=6, sticky=tk.W)\n\nb4 = tk.Button(window, text='reset', height=1, command=reset)\nb4.grid(column=2, row=7, sticky=tk.W)\n\n# Begin Loop\nwindow.mainloop()","repo_name":"tstuebe/Puzzles","sub_path":"tube.py","file_name":"tube.py","file_ext":"py","file_size_in_byte":4797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"38201398324","text":"import shutil\nfrom pathlib import Path\n\nfrom json import load\n\nfrom .DataHolders import Block, Sprite\nfrom .BlockDefine import BlockDefinions\n\n\ndef make_sprites(json):\n\n sprites = {}\n top_blocks = {}\n\n for sprite in self.project_data[\"targets\"]:\n blocks = {}\n topBlocks = []\n for id, block in sprite[\"blocks\"].items():\n if block[\"topLevel\"]:\n block = Block(id, block[\"opcode\"], block[\"inputs\"], block[\"fields\"],block[\"topLevel\"], block[\"next\"], block[\"parent\"])\n topBlocks[id] = block\n if block[\"opcode\"] in top_blocks:\n top_blocks[block[\"opcode\"]].append({\"id\": id, \"next\": block[\"next\"], \"SpriteName\": sprite[\"name\"], \"Block\": block })\n else:\n top_blocks[block[\"opcode\"]] = [{\"id\": id, \"next\": block[\"next\"], \"SpriteName\": sprite[\"name\"] }]\n else:\n blocks.append(Block(id, block[\"opcode\"], block[\"inputs\"], block[\"fields\"],block[\"topLevel\"], block[\"next\"], block[\"parent\"]))\n \n sprites[sprite[\"name\"]] = Sprite(\n sprite[\"isStage\"], \n sprite[\"name\"], \n sprite[\"broadcasts\"], \n sprite[\"variables\"], \n sprite[\"lists\"], \n blocks, \n top_blocks,\n sprite[\"currentCostume\"], \n sprite[\"costumes\"], \n sprite[\"sounds\"],\n sprite[\"volume\"], \n sprite[\"layerOrder\"],\n sprite[\"visible\"],\n sprite[\"x\"],\n sprite[\"y\"],\n sprite[\"size\"],\n sprite[\"direction\"],\n sprite[\"draggable\"],\n sprite[\"rotationStyle\"]\n )\n\n return sprites, top_blocks\n\nclass VM:\n def __init__(self, sb3):\n pth_to = Path(\"./temp/project\").mkdir(parents=True, exist_ok=False)\n shutil.unpack_archive(sb3, pth_to , format=\"zip\")\n with open(f\"{str(pth_to)}/project.json\") as f:\n self.project_data = load(f)\n\n self.sprites, self.top_blocks = make_sprites(self.project_data)\n \n \n\n def call_top_block(self, opcode, msg = None):\n if opcode in self.top_blocks:\n for hat in self.top_blocks[opcode]:\n if opcode == \"event_whenbroadcastreceived\":\n if hat[\"Block\"].fields[\"BROADCAST_OPTION\"][0] == msg:\n \n HasNext, next = self.run_block(hat[\"next\"], hat[\"SpriteName\"])\n while HasNext:\n HasNext, next, Block_return = self.run_block(next, hat[\"SpriteName\"])\n else:\n self.run_block(hat[\"next\"]) #stuff like on flag clicked lmao\n\n\n def run_block(self, block_id, Sprite_name):\n sprite:Sprite = self.sprites[Sprite_name]\n block:Block = sprite.blocks[block_id]\n opcode = block.opcode\n ret = \"\"\n # Dont Worry about hats, they should be taken care of by calling function\n\n if opcode.startswith(\"operator_\"):\n ret = BlockDefinions.Operators.do(vm, sprite, block)\n\n if block.next is None:\n return False, None, ret\n else:\n return True, block.next, ret","repo_name":"showierdata9978/ScratchVm","sub_path":"ScratchVM/VM.py","file_name":"VM.py","file_ext":"py","file_size_in_byte":2940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"21429086926","text":"import sys, re, cgi, urllib.request, urllib.parse, urllib.error, os, os.path\nimport random, time, http.cookies, datetime, time, copy\nimport jdb, fmt\nimport jinja; from markupsafe import Markup\nimport logger; from logger import L\n\ndef initcgi (cfgfilename):\n \"\"\"\n Does three things:\n 1. Fixes any url command line argument so that it is usable by\n the cgi module (see the args() function).\n Currently the only argument accepted is a url used when this\n script run interactively for debugging. In the future it may\n also accept an option giving the location of a configuration\n file.\n 2. Reads the configuration file (location currently hardwired.)\n 3. Initializes the Python logging system so log messages will have\n a consistent format. JMdictDB developers should not call the\n logger.L function() until after this function is called.\n \"\"\"\n\n # Adjust any url argument so that the cgi module can use it.\n args()\n # If the .ini filename below has no directory separator in it,\n # it is looked for in a directory on sys.path. If it does have\n # a separator in it it is treated as a normal relative or\n # absolute path.\n cfg = jdb.cfgOpen (cfgfilename)\n logfname = cfg.get ('logging', 'LOG_FILENAME', fallback='jmdictdb.log')\n loglevel = cfg.get ('logging', 'LOG_LEVEL', fallback='warning')\n filters = parse_cfg_logfilters (\n cfg.get ('logging', 'LOG_FILTERS', fallback=''))\n logger.log_config (level=loglevel, filename=logfname, filters=filters)\n return cfg\n\n #FIXME: parseform() and other functions raise standard Python errors\n # (e.g. ValueError) for many detected problems such as a bad entry\n # or sequence number. Unexpected internal errors of course will\n # also produce Python exceptions. Currently the cgi scripts catch\n # any exceptions and display them on an error page or via the\n # logger.handler uncaught exception handler. Showing exceptions\n # that are potentially correctable by a user is ok. But showing\n # all exceptions is dangerous -- a failure to connect to a database\n # could reveal a url containing a password for example. Unexpected\n # exceptions should go only into the log file and the error page\n # sgould report something generic (\"Oops, something went wrong\").\n # Perhaps we should use a separate error class for user-relevant\n # exceptions?\n\ndef parseform (readonly=False):\n \"\"\"\\\n Do some routine tasks that are needed for (most) every page,\n specifically:\n * Call cgi.FieldStorage to parse parameters.\n * Extract the svc parameter, validate it, and open the requested database.\n * Get session id and handle log or logout requests.\n Return an 8-tuple of:\n form (cgi.FieldStorage obj)\n svc (string) -- Checked svc value.\n dbg (int) -- true if \"dbg\" url param has true value, else 0.\n cur (dbapi cursor) -- Open cursor for database defined by 'svc'.\n sid (string) -- session.id in hexidecimal form or \"\".\n sess (Session inst.) -- Session for sid or None.\n params (dict) -- Received and decoded form parameters.\n cfg (Config inst.) -- Config object from reading config.ini.\n \"\"\"\n\n cfg = initcgi (\"config.ini\") # Read config, initialize logging.\n L('lib.jmcgi.parseform').debug(\"called in %s\" % sys.modules['__main__'].__file__)\n errs=[]; sess=None; sid=''; cur=None; svc=None\n def_svc = cfg['web'].get ('DEFAULT_SVC', 'jmdict')\n if def_svc.startswith ('db_'): def_svc = def_svc[3:]\n check_server_status (cfg.get ('web', 'STATUS_DIR'))\n\n form = cgi.FieldStorage()\n L('lib.jmcgi').debug(\"query_string: %s\" % os.environ.get('QUERY_STRING'))\n for k in form.keys():\n v = ['***']*len(form.getlist(k)) if k in ('password','pw1','pw2') \\\n else form.getlist(k)\n L('lib.jmcgi.parseform').debug(\"form key %s=%r\" % (k,v))\n dbg = int (form.getfirst ('dbg') or '0')\n svc = form.getfirst ('svc') or def_svc\n #L('lib.jmcgi.parseform').debug(\"svc=%s\" % svc)\n usid = form.getfirst ('sid') or '' # No SID is \"\", not None.\n try: svc = safe (svc)\n except ValueError: errs.append ('svc=' + svc)\n if not errs:\n try: cur = jdb.dbOpenSvc (cfg, svc)\n except KeyError as e: errs.append ('svc=' + str(e))\n if errs: raise ValueError (';'.join (errs))\n\n # Login, logout, and session identification...\n scur = jdb.dbOpenSvc (cfg, svc, session=True, nokw=True)\n action = form.getfirst ('loginout') # Will be None, \"login\" or \"logout\"\n sid = get_sid_from_cookie() or ''\n sid_from_cookie = bool (sid)\n if usid: sid = usid # Use sid from url if available.\n L('lib.jmcgi.parseform').debug(\"sid=%s, from_cookie=%s, action=%s\" % (sid, sid_from_cookie, action))\n uname = form.getfirst('username') or ''\n pw = form.getfirst('password') or ''\n sid, sess = get_session (scur, action, sid, uname, pw)\n L('lib.jmcgi.parseform').debug(\"%s session, sid=%s\" % (\"got\" if sess else \"no\", sid))\n if sid: set_sid_cookie (sid, delete=(action==\"logout\"))\n if sid_from_cookie: sid=''\n scur.connection.close()\n\n # Collect the form parameters. Caller is expected to pass\n # them to the page template which will use them in the login\n # section as hidden parms so the page can be recreated after\n # a login. We leave out any param name \"result\" since that\n # is used as a confirmation message by the userupd.py page\n # and best to see it only once.\n parms = [(k,v)\n for k in list(form.keys())\n if k not in ('loginout','username','password', 'result')\n for v in form.getlist(k) ]\n\n return form, svc, dbg, cur, sid, sess, parms, cfg\n\ndef check_server_status (status_file_dir):\n location = None\n sfd = status_file_dir\n if os.access (os.path.join (sfd, 'status_maint'), os.F_OK):\n location = 'status_maint.html'\n elif os.access (os.path.join (sfd, 'status_load'), os.F_OK):\n location = 'status_load.html'\n if location:\n print (\"Location: %s\\n\" % ('../' + location))\n sys.exit (0)\n\nCOOKIE_NAME = 'jmdictdb_sid'\nSESSION_TIMEOUT = '2 hour'\n\ndef get_session (cur, action=None, sid=None, uname=None, pw=None):\n # Do the authentication action specified by 'action':\n # None -- Lookup 'sid' and return a session if there is one.\n # \"login\" -- Create a new session authenicating with 'uname'\n # and 'pw'. Return the session and its sid.\n # \"logout\" -- Lookup session 'sid' and delete it.\n #\n # cur (dbapi cursor object) -- Cursor to open jmsess database.\n # action (string) -- None, \"login\", or \"logout\".\n # sid (string) -- Session identifier if logged in or None is not.\n # uname (string)-- Username (only required if action is \"login\".)\n # pw (string)-- Password (only required if action is \"login\".)\n #\n # Returns: sid, sess\n\n sess = None\n if not action and not sid: # Not logged in\n return '', None\n if not action: # Use sid to retrieve session.\n sess = dbsession (cur, sid)\n if not sess: sid = ''\n elif action == 'logout':\n if sid: dblogout (cur, sid)\n # Don't clear 'sid' because its value will be needed\n # by caller to delete cookie.\n elif action == 'login':\n if not re.match (r'^[a-zA-Z0-9_]+$', uname): return '', None\n sid, sess = dblogin (cur, uname, pw)\n else: pass # Ignore invalid 'action' parameter.\n return sid, sess\n\ndef dbsession (cur, sid):\n # Return the session identified by 'sid' or None.\n # As a side effect, if we have a sucessful login we\n # delete all expired session records in the session\n # table. This will hopefully avoid the need for a\n # cron job to prune expired entries.\n\n sess = db_validate_sid (cur, sid)\n if not sess: return None\n db_del_old_sessions (cur)\n db_update_sid_ts (cur, sid)\n return sess\n\ndef dblogin (cur, userid, password):\n # Login by authenticating the userid/password pair.\n # and getting a session record which is returned with\n # the session id. If 'userid' has an active session\n # already, it (the most recent one if more than one)\n # is returned. If not, a new session is created.\n # Reusing existing sessions help prevent the proliferation\n # of sessions that was occuring previously.\n\n # Check userid, password validity.\n sql = \"SELECT userid FROM users \"\\\n \"WHERE userid=%s AND pw=crypt(%s, pw) AND NOT disabled\"\n rs = jdb.dbread (cur, sql, (userid, password))\n if not rs:\n L('lib.jmcgi.dblogin').debug(\"pw fail for %s\" % userid)\n time.sleep (1); return '', None\n\n # Look for an existing session (the most recent if more than one).\n sql = \"SELECT s.id,s.userid,s.ts,u.fullname,u.email,u.priv\" \\\n \" FROM sessions s JOIN users u ON u.userid=s.userid\" \\\n \" WHERE u.userid=%%s AND NOT u.disabled\" \\\n \" AND (NOW()-ts)<'%s'::INTERVAL\" \\\n \" ORDER BY ts DESC LIMIT 1\" % SESSION_TIMEOUT\n rs = jdb.dbread (cur, sql, (userid,))\n L('lib.jmcgi.dblogin').debug(\"%s: %s sessions found\" % (userid, len(rs)))\n if len (rs) == 1:\n sid = rs[0][0]\n # Update the session timestamp to 'now'.\n db_update_sid_ts (cur, sid)\n L('lib.jmcgi.dblogin').debug(\"%s: using session: %s\" % (userid,sid))\n return sid, rs[0]\n\n # No existing session found, create a new session.\n sql = \"INSERT INTO sessions(userid) VALUES(%s) RETURNING(id)\"\n cur.execute (sql, (userid,))\n sid = cur.fetchone()[0]\n cur.connection.commit()\n L('lib.jmcgi.dblogin').debug(\"%s: new session %s\" % (userid, sid))\n sess = db_validate_sid (cur, sid)\n return sid, sess\n\ndef dblogout (cur, sid):\n if not sid: return\n # Make logout delete all users sessions so that\n # a logout will remedy a disclosed sid. Of course\n # this means a logout in one winow of one machine\n # will affect every other login session.\n sql = \"DELETE FROM sessions WHERE id IN\"\\\n \"(SELECT s2.id FROM sessions s1\"\\\n \" JOIN sessions s2 ON s1.userid=s2.userid\"\\\n \" WHERE s1.id=%s)\"\n cur.execute (sql, (sid,))\n cur.connection.commit()\n\ndef db_validate_sid (cur, sid):\n # Check that 'sid' is an existing session and if so\n # return a session record. Otherwise return None.\n sql = \"SELECT s.id,s.userid,s.ts,u.fullname,u.email,u.priv\" \\\n \" FROM sessions s JOIN users u ON u.userid=s.userid\" \\\n \" WHERE id=%%s AND NOT u.disabled\" \\\n \" AND (NOW()-ts)<'%s'::INTERVAL\" \\\n % SESSION_TIMEOUT\n rs = jdb.dbread (cur, sql, (sid,))\n L('lib.jmcgi.db_validate_sid').debug(\"validating sid %s, result=%s\" % (sid, len(rs)))\n if len (rs) == 0: return None\n return rs[0]\n\ndef db_update_sid_ts (cur, sid):\n # Update the last-used timestamp for 'sid'.\n sql = \"UPDATE sessions SET ts=DEFAULT WHERE id=%s\"\n cur.execute (sql, (sid,))\n cur.connection.commit()\n\ndef db_del_old_sessions (cur):\n # Delete all sessions that are expired, for all users.\n sql = \"DELETE FROM sessions WHERE (NOW()-ts)>'%s'::INTERVAL\" \\\n % SESSION_TIMEOUT\n cur.execute (sql)\n\ndef get_sid_from_cookie ():\n sid = ''\n if 'HTTP_COOKIE' in os.environ:\n c = http.cookies.SimpleCookie()\n c.load (os.environ['HTTP_COOKIE'])\n try: sid = c[COOKIE_NAME].value\n except KeyError: pass\n return sid\n\ndef set_sid_cookie (sid, delete=False):\n # Set a cookie on the client machine by writing an http\n # Set-Cookie line to stdout. Caller is responsible for\n # calling this while http headers are being output.\n\n c = http.cookies.SimpleCookie()\n c[COOKIE_NAME] = sid\n c[COOKIE_NAME]['max-age'] = 0 if delete else 1*60*60\n print (c.output())\n\ndef is_editor (sess):\n \"\"\"Return a true value if the 'sess' object (which may be None)\n is for a logged-in editor. An editor is a user with either 'E'\n or 'A' privilege error.\"\"\"\n\n if not sess: return None\n return getattr (sess, 'priv', None) in 'EA'\n\ndef get_user (uid, svc, cfg):\n cur = jdb.dbOpenSvc (cfg, svc, session=True, nokw=True)\n sql = \"SELECT * FROM users WHERE userid=%s\"\n users = jdb.dbread (cur, sql, (uid,))\n # 'userid' is primary key of users table so we should never\n # receive more than one row.\n assert len(users)<=1, \"Too many rows received\"\n return users[0] if users else None\n\ndef adv_srch_allowed (cfg, sess):\n try: v = (cfg['search']['ENABLE_SQL_SEARCH']).lower()\n except (TypeError, ValueError, KeyError): return False\n if v == 'all': return True\n if v == 'editors' and is_editor (sess): return True\n return False\n\ndef form2qs (form):\n \"\"\"\n Convert a cgi.FieldStorage object back into a query string.\n \"\"\"\n d = []\n for k in list(form.keys()):\n for v in form.getlist (k):\n d.append ((k, v))\n qs = urllib.parse.urlencode (d)\n return qs\n\ndef args():\n \"\"\"\n Command-line argument processing for cgi scripts.\n\n Python's cgi module will process a commandline argument as though\n it had been received through the environment as it is when a script\n is run by a web server, which is very useful for debugging.\n However, it expects only the url parameters (the part of the url\n that follows the \"?\", not the full url (starting with \"http://...\").\n Accepting the full url is convenient since it allows one to copy/-\n paste urls from a browser to a commendline invocation for debugging.\n This function will remove anything preceeding the url parameters so\n that the cgi module will be happy.\n \"\"\"\n args = []; opts = object()\n if len(sys.argv) > 1:\n #args, opts = parse_cmdline()\n args = sys.argv[1:]\n\n if args:\n a1, x, a2 = args[0].partition ('?')\n if a2: sys.argv[1] = a2\n return args, opts\n\ndef clean (s):\n if not s: return ''\n if not re.search ('^[0-9A-Za-z_]+$', s):\n raise ValueError (\"clean(): Bad string received\")\n return s\n\ndef str2seq (q):\n # Convert 'q', a string of the form of either 'seq' or\n # 'seq.corp', where 'seq' is a string of digits representing\n # a seq number, and 'corp' is either a string of digits\n # representing a corpus id number or the name of a corpus.\n # The existence of the corpus, if given, is validated in\n # the KW.SRC dict. The seq number is only validated as\n # being greater than 0.\n # If sucessful, a 2-tuple of (seq-number, corpus-id) is\n # returned, where 'corpus-id' will be None if the first\n # input string format was given. Otherwise a ValueError\n # exception is raised.\n\n KW = jdb.KW\n seq_part, x, corp_part = q.partition ('.')\n try: seq = int (seq_part)\n except (ValueError, TypeError):\n raise ValueError(\"Invalid seq number '%s'.\" % (q,))\n if seq <= 0: raise ValueError(\"Invalid seq number '%s'.\" % (q,))\n corp = None\n if corp_part:\n corp = corp2id (corp_part)\n if not corp: raise ValueError(\"Invalid corpus in '%s'.\" % (q,))\n return seq, corp\n\ndef corp2id (c):\n # Convert 'c' which identifies a corpus and is either\n # the corpus id number in integer or string form or\n # the name of a corpus, to the id number of the corpus.\n # The existence id th corpus is validadedin the KW.SRC\n # dict.\n\n try: c = int (c)\n except (ValueError, TypeError): pass\n try: corpid = jdb.KW.SRC[c].id\n except KeyError: return None\n return corpid\n\ndef str2eid (e):\n n = int (e)\n if n <= 0: raise ValueError(e)\n return n\n\ndef safe (s):\n if not s: return ''\n if re.search (r'^[a-zA-Z_][a-zA-Z_0-9]*$', s): return s\n raise ValueError ()\n\ndef txt2html (s, ):\n s = cgi.escape (s)\n s = s.replace ('\\n', '
\\n')\n return s\n\ndef get_entrs (dbh, elist, qlist, errs, active=None, corpus=None):\n # Retrieve a set of Entr objects from the database, specified\n # by their entry id and/or seq numbers.\n #\n # dbh -- Open dbapi cursor to the current database.\n # elist -- List of id numbers of entries to get. Each number\n # may by either a integer or a string.\n # qlist -- List of seq numbers of entries to get. Each seq\n # number may be an integer or a string. If the latter\n # it may be followed by a period, and a corpus identifier\n # which is either the corpus id number or the corpus name.\n # errs -- Must be a list (or other append()able object) to\n # which any error messages will be appended. The error\n # messages may contain user data and should thus be\n # escaped before being used in a web page.\n # active -- If 1, only active/approved or new/(unapproved)\n # entries will be retrieved.\n # If 2, at most one entry will be returned for each seq number\n # in the results and that entry will be the most recently edited\n # (chronologically based on history records) entry if one exists\n # of the approved active entry.\n # If active is any other value or not present, all entries\n # meeting the entry-id, seq, or seq-corpus criteria will be\n # retrieved.\n # corpus -- If not none, this is a corpus id number or name\n # and will apply to any seq numbers without an explicit\n # corpus given with the number.\n #\n # If the same entry is specified more than once in 'elist' and/or\n # 'qlist' ir will only occur once in the returned object list.\n # Objects in the returned list are in no particular order.\n\n eargs = []; qargs = []; xargs = []; whr = []; corpid = None\n if corpus is not None:\n corpid = corp2id (corpus)\n if corpid is None:\n errs.append (\"Bad corpus parameter: %s\" % corpus)\n return []\n for x in (elist or []):\n try: eargs.append (str2eid (str(x)))\n except ValueError:\n errs.append (\"Bad url parameter received: \" + x)\n if eargs: whr.append (\"id IN (\" + ','.join(['%s']*len(eargs)) + \")\")\n\n for x in (qlist or []):\n try: args = list (str2seq (str(x)))\n except ValueError:\n errs.append (\"Bad parameter received: \" + x)\n else:\n if corpus and not args[1]: args[1] = corpid\n if args[1]:\n whr.append (\"(seq=%s AND src=%s)\"); qargs.extend (args)\n else:\n whr.append (\"seq=%s\"); qargs.append (args[0])\n if not whr: errs.append (\"No valid entry or seq numbers given.\")\n if errs: return None\n whr2 = ''; distinct = ''; hjoin = ''; order = ''\n try: active = int (active)\n except (ValueError, TypeError): pass\n if active == 1:\n # Following will restrict returned rows to active/approved\n # (stat=A and not unap) or new (dfrm is NULL), that is, the\n # result set will not include any stat=D or stat=R results.\n whr2 = \" AND stat=%s AND (NOT unap OR dfrm IS NULL)\"\n xargs.append (jdb.KW.STAT['A'].id)\n elif active == 2:\n # Restrict returned rows to active (no stat=D or stat=R results)\n # and most recent edit as determined by the history records (if any).\n # In no event will more than one entry per seq number be returned.\n # Note that this will necessarily return the edit from only one\n # branch when multiple branches exist which may result in surprise\n # for a user when the returned entry shows no signs of a recent\n # edit known to have been made.\n # Example of generated sql:\n # SELECT DISTINCT ON (e.seq) e.id FROM entr e LEFT JOIN hist h ON h.entr=e.id\n # WHERE e.seq=2626330 and e.stat=2 ORDER BY e.seq,h.dt DESC NULLS LAST;\n whr2 = \" AND e.stat=%s\"\n xargs.append (jdb.KW.STAT['A'].id)\n distinct = \" DISTINCT ON (e.seq)\"\n hjoin = \" LEFT JOIN hist h ON h.entr=e.id\"\n # \"NULLS LAST\" is needed below because some entries (e.g., entries\n # imported when JMdictDB is first initialized and never edited)\n # may not have history records which will result in 'dt' values of\n # NULL; we want those entries last.\n order = \" ORDER BY e.seq,h.dt DESC NULLS LAST\"\n sql = \"SELECT\" + distinct + \" e.id FROM entr e \" \\\n + hjoin + \" WHERE (\" + \" OR \".join (whr) + \")\" + whr2 + order\n entries, raw = jdb.entrList (dbh, sql, eargs+qargs+xargs, ret_tuple=True)\n if entries:\n jdb.augment_xrefs (dbh, raw['xref'])\n jdb.augment_xrefs (dbh, raw['xrer'], rev=1)\n jdb.add_xsens_lists (raw['xref'])\n jdb.mark_seq_xrefs (dbh, raw['xref'])\n return entries\n\ndef jinja_page (tmpl, output=sys.stdout, **kwds):\n httphdrs = kwds.get ('HTTP', None)\n if not httphdrs:\n if not kwds.get ('NoHTTP', None):\n httphdrs = \"Content-type: text/html\\n\"\n if not httphdrs: html = ''\n else: html = httphdrs + \"\\n\"\n env = jinja.init()\n html += jinja.render (tmpl, kwds, env)\n if output: print (html, file=output)\n return html\n\ndef err_page (errs=[], errid=None, prolog=None, epilog=None, cssclass=\"\"):\n # CAUTION: 'prolog' and 'epilog' are rendered in the errors\n # page template without html escaping and should either not\n # include any text from untrusted sources or such text must\n # be escaped by the caller.\n # The texts in 'errs' will be escaped in the errors page template;\n # if you need to include html markup in them, wrap the marked up\n # text in jmcgi.Markup().\n if isinstance (errs, str): errs = [errs]\n jinja_page ('error.jinja', svc='', errs=errs, errid=errid,\n prolog=prolog, epilog=epilog, cssclass=cssclass)\n sys.exit()\n\ndef redirect (url):\n print (\"Status: 302 Moved\")\n print (\"Location: %s\\n\" % url)\n sys.exit()\n\ndef htmlprep (entries):\n \"\"\"\\\n Prepare a list of entries for display with an html template\n by adding some additional information that is inconvenient to\n generate from within a template.\"\"\"\n\n add_p_flag (entries)\n add_restr_summary (entries)\n add_stag_summary (entries)\n add_audio_flag (entries)\n add_editable_flag (entries)\n add_unreslvd_flag (entries)\n add_pos_flag (entries)\n rev_hists (entries)\n\ndef add_p_flag (entrs):\n # Add a supplemantary attribute to each entr object in\n # list 'entrs', that has a boolean value indicating if\n # any of its readings or kanji meet wwwjdic's criteria\n # for \"P\" status (have a freq tag of \"ichi1\", \"gai1\",\n # \"spec1\", or \"news1\").\n\n for e in entrs:\n if jdb.is_p (e): e.IS_P = True\n else: e.IS_P = False\n\ndef add_restr_summary (entries):\n\n # This adds an _RESTR attribute to each reading of each entry\n # that has a restr list. The ._RESTR attribute value is a list\n # of text strings giving the kanji that *are* allowed with the\n # reading. Recall that the database (and entry object created\n # therefrom) stores the *disallowed* reading/kanji combinations\n # but one generally wants to display the *allowed* combinations.\n #\n # Also add a HAS_RESTR boolean flag to the entry if there are\n # _restr items on any reading.\n\n for e in entries:\n if not hasattr (e, '_rdng') or not hasattr (e, '_kanj'): continue\n for r in e._rdng:\n if not hasattr (r, '_restr'): continue\n rt = fmt.restrtxts (r._restr, e._kanj, '_restr')\n if rt: r._RESTR = rt\n e.HAS_RESTR = 1\n\ndef add_stag_summary (entries):\n\n # This adds a STAG attribute to each sense that has any\n # stagr or stagk restrictions. .STAG is set to a single\n # list that contains the kana or kanji texts strings that\n # are allowed for the sense under the restrictions.\n\n for e in entries:\n for s in getattr (e, '_sens', []):\n rt = []\n if getattr (s, '_stagr', None):\n rt.extend (fmt.restrtxts (s._stagr, e._rdng, '_stagr'))\n if getattr (s, '_stagk', None):\n rt.extend (fmt.restrtxts (s._stagk, e._kanj, '_stagk'))\n if rt:\n s._STAG = rt\n\ndef add_audio_flag (entries):\n\n # The display template shows audio records at the entry level\n # rather than the reading level, so we set a HAS_AUDIO flag on\n # entries that have audio records so that the template need not\n # sear4ch all readings when deciding if it should show the audio\n # block.\n # [Since the display template processes readings prior to displaying\n # audio records, perhaps the template should set its own global\n # variable when interating the readings, and use that when showing\n # an audio block. That would eliminate the need for this function.]\n\n for e in entries:\n if getattr (e, '_snd', None):\n e.HAS_AUDIO = 1; continue\n for r in getattr (e, '_rdng', []):\n if getattr (r, '_snd', None):\n e.HAS_AUDIO = 1\n break\n\ndef add_editable_flag (entries):\n\n # This is a convenience function to avoid embedding this logic\n # in the page templates. This sets a boolean EDITABLE flag on\n # each entry that says whether or not an \"Edit\" button should\n # be shown for the entry. All unapproved entries, and approved\n # active or deleted entries are editable. Rejected entries aren't.\n\n KW = jdb.KW\n for e in entries:\n e.EDITABLE = e.unap or (e.stat == KW.STAT['A'].id)\\\n or (e.stat == KW.STAT['D'].id)\n\ndef add_unreslvd_flag (entries):\n\n # This is a convenience function to avoid embedding this logic\n # in the page templates. This sets a boolean UNRESLVD flag on\n # each entry that says whether or not it has any senses that\n # have unresolved xrefs in its '_xunr' list.\n\n KW = jdb.KW\n for e in entries:\n e.UNRESLVD = False\n for s in e._sens:\n if len (getattr (s, '_xunr', [])) > 0:\n e.UNRESLVD = True\n\ndef add_pos_flag (entries):\n\n # This is a convenience function to avoid embedding this logic\n # in the page templates. This sets a boolean POS flag on\n # each entry if any senses in the entry have a part-of-speech\n # (pos) tag that is conjugatable. A POS tag is conjugatable\n # if its id number is an id number in jdb.KW.COPOS. jdb.KW.COPOS\n # in turn is populated from database view 'vcopos' which are those\n # rows in kwpos which are also referenced in table 'copos' (that\n # identifies them as conjugatable.) See also the comments for\n # view 'vcopos' in pg/conj.sql.\n # The .POS attribute set by this function is used to determine\n # if a \"Conjugations\" link should be shown for the entry.\n # We exclude nouns and na-adjectives even though the conjugator\n # will happily conjugate them as だ-predicates.\n\n KW = jdb.KW\n conjugatable_poslist = [x.id for x in jdb.KW.recs('COPOS')\n if x.kw not in ('n', 'adj-na')]\n for e in entries:\n e.POS = False\n for s in e._sens:\n for p in s._pos:\n if p.kw in conjugatable_poslist:\n e.POS = True; break\n\ndef rev_hists (entries):\n\n # Reverse the order of history items in each entry so that the\n # most recent will appear first and the oldest last.\n\n for e in entries:\n if e._hist: e._hist = list (reversed (e._hist))\n\ndef add_filtered_xrefs_old (entries, rem_unap=False):\n\n # Generate substitute _xref and _xrer lists and put them in\n # sense attribute .XREF and .XRER. These lists are copies of\n # ._xref and ._xrer but references to deleted or rejected\n # entries are removed. Additionally, if 'rem_unap' is true,\n # references to unapproved entries are also removed *if*\n # the current entry is approved.\n # The xrefs in ._xref and ._xrer must be augmented xrefs (i.e.\n # have had jdb.augment_xrefs() called on the them.)\n #\n # FIXME: have considered not displaying reverse xref if an\n # identical forward xref (to same entr/sens) exists. If\n # we want to do that, this is the place.\n\n cond = lambda e,x: (e.unap or not x.TARG.unap or not rem_unap) \\\n and x.TARG.stat==jdb.KW.STAT['A'].id\n for e in entries:\n for s in e._sens:\n s.XREF = [x for x in s._xref if cond (e, x)]\n s.XRER = [x for x in s._xrer if cond (e, x)]\n\ndef add_filtered_xrefs (entries, rem_unap=False):\n\n # Works like add_filtered_xrefs_old() above except:\n # Put all xrefs, both forward (from list s._xref) and reverse\n # from list s._xrer), into s.XREF and creates an additional\n # attribute on the s.XREF objects, .direc, that indicates whether\n # the xref is a \"from\", \"to\" or \"bidirectional\" xref. If the\n # same xref occurs in both the s._xref and s_xrer lists, it is\n # only added once and the .direc attribute set to \"bidirectional\".\n # This allows an entr display app (such as entr.py/entr.jinja) to\n # display an icon for the xref direction. This was suggested\n # on the Edict maillist by Jean-Luc Leger, 2010-07-29, Subject:\n # \"Re: Database testing - call for testers - more comments\"\n\n cond = lambda e,x: (e.unap or not x.TARG.unap or not rem_unap) \\\n and x.TARG.stat==jdb.KW.STAT['A'].id\n def setdir (x, dir):\n x.direc = dir\n return x\n\n FWD = 1; BIDIR = 0; REV = -1 # Direction of an xref.\n for e in entries:\n for s in e._sens:\n # Add all (non-excluded) forward xrefs to the xref list,\n # s.XREF. Some of these may be bi-directional (have\n # xrefs on the target that refer back to us) but we will\n # indentify those later to fixup the FWD flag to BIDIR.\n s.XREF = [setdir (copy.deepcopy(x), FWD) for x in s._xref if cond (e, x)]\n # Make dict of all the fwd xrefs.\n fwdrefs = {(x.entr,x.sens,x.xentr,x.xsens):x for x in s.XREF}\n for x in s._xrer:\n if not cond (e, x): continue\n x = copy.deepcopy (x)\n # Because we will display the reverse xref with the\n # same code that displays forward xrefs (that is, it\n # creates a link to the entry using x.xentr and x.xsens),\n # swap the (entr,sens) and (xentr,xsens) values so that\n # when (xentr,xsens) are used, they'll actually be\n # the entr,sens values which identify the entry the\n # the reverse xref is on, which is what we want.\n x.entr,x.sens,x.xentr,x.xsens = x.xentr,x.xsens,x.entr,x.sens\n # Is this reverse xref the same as a forward xref?\n if (x.entr,x.sens,x.xentr,x.xsens) in fwdrefs:\n # If so, change the forward xref's 'direc' attribute\n # from FWD to BIDIR.\n setdir (fwdrefs[(x.entr,x.sens,x.xentr,x.xsens)], BIDIR)\n # Otherwise (our xref is not bi-directional), add us to\n # the xref list as a reverse xref.\n else: s.XREF.append (setdir (x, REV))\n\ndef add_encodings (entries, gahoh_url=None):\n\n # Add encoding info which is displayed when presenting kanjidic\n # (or similar single-character) entries.\n\n for e in entries:\n if not hasattr (e, 'chr') or not e.chr: continue\n c = e.chr; c.enc = {}\n c.enc['uni'] = hex (ord (c.chr)).upper()[2:]\n c.enc['unid'] = ord (c.chr)\n c.enc['uurl'] = 'http://www.unicode.org/cgi-bin/GetUnihanData.pl?codepoint=' + c.enc['uni']\n c.enc['utf8'] = ' '.join([\"%0.2X\"%x for x in c.chr.encode('utf-8')])\n try:\n iso2022jp = c.chr.encode ('iso2022-jp')\n c.enc['iso2022jp'] = ' '.join([\"%0.2X\"%x for x in iso2022jp])\n c.enc['jis'] = ''.join([\"%0.2X\"%x for x in iso2022jp[3:5]])\n except UnicodeEncodeError: c.enc['iso2022jp'] = c.enc['jis'] = '\\u3000'\n try: c.enc['sjis'] = ''.join([\"%0.2X\"%x for x in c.chr.encode('sjis')])\n except UnicodeEncodeError: c.enc['sjis'] = '\\u3000'\n try: c.enc['eucjp'] = ''.join([\"%0.2X\"%x for x in c.chr.encode('euc-jp')])\n except UnicodeEncodeError: c.enc['eucjp'] = '\\u3000 '\n\nclass SearchItems (jdb.Obj):\n \"\"\"Convenience class for creating objects for use as an argument\n to function so2conds() that prevents using invalid attribute\n names.\"\"\"\n\n def __setattr__ (self, name, val):\n if name not in ('idtyp','idnum','src','txts','pos','misc',\n 'fld','dial','freq','kinf','rinf','grp','stat','unap',\n 'nfval','nfcmp','gaval','gacmp','ts','smtr', 'mt'):\n raise AttributeError (\"'%s' object has no attribute '%s'\"\n % (self.__class__.__name__, name))\n self.__dict__[name] = val\n\nclass SearchItemsTexts (jdb.Obj):\n \"\"\"Convenience class for creating objects for use in the 'txts'\n attribute of SearchItems objects that prevents using invalid\n attribute names.\"\"\"\n\n def __setattr__ (self, name, val):\n if name not in ('srchtxt','srchin','srchtyp','inv'):\n raise AttributeError (\"'%s' object has no attribute %s\"\n % (self.__class__.__name__, name))\n self.__dict__[name] = val\n\ndef so2conds (o):\n \"\"\"\n Convert an object containing search criteria (typically\n obtained from a web search page or gui search form) into\n a list of search \"conditions\" suitable for handing to the\n jdb.build_search_sql() function.\n\n Attributes of 'o':\n idtyp -- Either \"id\" or \"seq\". Indicates if 'idnum'\n should be interpreted as an entry id number, or\n an entry sequence number. If the former, all\n other attributes other than 'idnum' are ignored.\n If the latter, all other attributes other than\n 'idnum' and 'src' are ignored.\n idnum -- An integer that is either the entry id number\n or sequence number of the target entry. Which it\n will be interpreted is determined by the 'idtyp'\n attribute, which but also be present, if 'idnum'\n is present.\n src -- List of Corpus keywords.\n txts -- A list of objects, each with the following\n attributes:\n srchtxt -- Text string to be searched for.\n srchin --Integer indicating table to be searched:\n 1 -- Determine table by examining 'srchtxt':\n 2 -- Kanj table.\n 3 -- rdng table\n 4 -- Gloss table.\n srchtyp -- Integer indicating hot to search for\n 'srchtxt':\n 1 -- 'srchtxt' must match entire text string in table\n (i.e. and \"exact\" match.)\n 2 -- 'srchtxt' matches the leading text in table (i.e.\n anchorded at start).\n 3 -- 'srchtxt' matches a substring of text in table\n (i.e. is contained anywhere in the table's text).\n 4 -- 'srchtxt' matches the trailing text in table\n (i.e. anchored at end).\n inv -- If true, invert the search sense: find entries\n where the text doesn't match according the the\n given criteria.\n pos -- List of Part of Speech keywords.\n misc -- List of Misc (sense) keywords.\n fld -- List of Field keywords.\n dial -- List of Dialect keywords.\n kinf -- List of Kanj Info keywords.\n rinf -- List of Reading Info of Speech keywords.\n grp -- List of entry group keywords.\n stat -- List of Status keywords.\n unap -- List of Unapproved keywords. #FIXME\n freq -- List of Frequency keywords. #FIXME\n Note that an entry matches if there is either a\n matching kanj freq or a matching rdng freq. There\n is no provision to specify just one or the other.\n ts -- History min and max time limits as a 2-tuple. Each\n time value is either None or number of seconds from\n the epoch as returned by time.localtime() et.al.\n smtr -- 2-tuple of name to match with hist.name, and bool\n indicating a wildcard match is desired.\n mt -- History record match type as an int:\n 0: match any hist record\n 1: match only first hist record\n -1: match only last hist record\n\n Since it is easy to mistype attribute names, the classes\n jdb.SearchItems can be used to create an object to pass\n to so2conds. It checks attribute names and will raise an\n AttributeError in an unrecognised one is used.\n SearchItemsTexts is similar for the objects in the '.txts'\n list.\n\n Example:\n # Create a criteria object that will look for in jmdict\n # and the tanaka (examples) corpus for entries with\n # a gloss (srchin=4) containing (srchtyp=2) the text\n # \"helper\".\n\n srch_criteria = jdb.SearchItems (\n src=['jmdict','examples'],\n txts=[jdb.SearchItemsTexts (\n srchtxt=\"helper\",\n srchin=4,\n srchtyp=2)])\n\n # Convert the criteria object into a \"condition list\".\n\n condlist = so2conds (srch_criteria)\n\n # Convert the condition list into the sql and sql arguments\n # need to perform the search.\n\n sql, sql_args = build_srch_sql (condlist)\n\n # Give the sql to the entrList() function to retrieve\n # entry objects that match the search criteria.\n\n entry_list = entrList (dbcursor, sql, sql_args)\n\n # Now one can display or otherwise do something with\n # the found entries.\n\n \"\"\"\n conds = []\n n = int(getattr (o, 'idnum', None) or 0)\n if n:\n idtyp = getattr (o, 'idtyp')\n if idtyp == 'id': # Id Number\n conds.append (('entr','id=%s',[n]))\n elif idtyp == 'seq': # Seq Number\n conds.append (('entr','seq=%s',[n]))\n conds.extend (_kwcond (o, 'src', \"entr e\", \"e.src\"))\n else: raise ValueError (\"Bad 'idtyp' value: %r\" % idtyp)\n return conds\n\n for n,t in enumerate (getattr (o, 'txts', [])):\n conds.extend (_txcond (t, n))\n conds.extend (_kwcond (o, 'pos', \"pos\", \"pos.kw\"))\n conds.extend (_kwcond (o, 'misc', \"misc\", \"misc.kw\"))\n conds.extend (_kwcond (o, 'fld', \"fld\", \"fld.kw\"))\n conds.extend (_kwcond (o, 'dial', \"dial\", \"dial.kw\"))\n conds.extend (_kwcond (o, 'kinf', \"kinf\", \"kinf.kw\"))\n conds.extend (_kwcond (o, 'rinf', \"rinf\", \"rinf.kw\"))\n conds.extend (_kwcond (o, 'grp', \"grp\", \"grp.kw\"))\n conds.extend (_kwcond (o, 'src', \"entr e\", \"e.src\"))\n conds.extend (_kwcond (o, 'stat', \"entr e\", \"e.stat\"))\n conds.extend (_boolcond (o, 'unap',\"entr e\",\"e.unap\", 'unappr'))\n conds.extend (_freqcond (getattr (o, 'freq', []),\n getattr (o, 'nfval', None),\n getattr (o, 'nfcmp', None),\n getattr (o, 'gaval', None),\n getattr (o, 'gacmp', None)))\n conds.extend (_histcond (getattr (o, 'ts', None),\n getattr (o, 'smtr', None),\n getattr (o, 'mt', None)))\n return conds\n\ndef _txcond (t, n):\n txt = t.srchtxt\n intbl = getattr (t, 'srchin', 1)\n typ = getattr (t, 'srchtyp', 1)\n inv = getattr (t, 'srchnot', '')\n cond = jdb.autocond (txt, typ, intbl, inv, alias_suffix=n)\n return [cond]\n\ndef _kwcond (o, attr, tbl, col):\n vals = getattr (o, attr, None)\n if not vals: return []\n # FIXME: following hack breaks if first letter of status descr\n # is not same as kw string.\n if attr == 'stat': vals = [x[0] for x in vals]\n kwids, inv = jdb.kwnorm (attr.upper(), vals)\n if not kwids: return []\n cond = tbl, (\"%s %sIN (%s)\" % (col, inv, ','.join(str(x) for x in kwids))), []\n return [cond]\n\ndef _boolcond (o, attr, tbl, col, true_state):\n vals = getattr (o, attr, None)\n if not vals or len(vals) == 2: return []\n inv = ''\n if vals[0] != true_state: inv = 'NOT '\n cond = tbl, (inv + col), []\n return [cond]\n\ndef _histcond (ts, smtr, mt):\n conds = []\n if ts and (ts[0] or ts[1]):\n # ts[0] and[1] are 9-tuples of ints that correspond\n # to time.struct_time objects. We convert them to\n # datetime.datetime objects.\n if ts[0]: conds.append (('hist', \"dt>=%s\", [datetime.datetime.fromtimestamp(int(ts[0]))]))\n if ts[1]: conds.append (('hist', \"dt<=%s\", [datetime.datetime.fromtimestamp(int(ts[1]))]))\n if smtr and smtr[0]:\n name, wc = smtr\n if not wc: conds.append (('hist', \"lower(name)=lower(%s)\", [name]))\n else: conds.append (('hist', \"name ILIKE %s\", [wc2like (name)]))\n if mt:\n if int(mt) == 1: conds.append (('hist', \"hist=1\", []))\n if int(mt) == -1: conds.append (('hist', \"hist=(SELECT COUNT(*) FROM hist WHERE hist.entr=e.id)\", []))\n return conds\n\ndef _freqcond (freq, nfval, nfcmp, gaval, gacmp):\n # Create a pair of 3-tuples (build_search_sql() \"conditions\")\n # that build_search_sql() will use to create a sql statement\n # that will incorporate the freq-of-use criteria defined by\n # our parameters:\n #\n # $freq -- List of indexes from a freq option checkboxe, e.g. \"ichi2\".\n # $nfval -- String containing an \"nf\" number (\"1\" - \"48\").\n # $nfcmp -- String containing one of \">=\", \"=\", \"<=\".\n # NOTE: The gA freq number was a from a database of Google\n # \"hits\" for various words. The data was unreliable at the\n # time it was collected in the early 2000's and is of little\n # use anymore. The search forms no longer support gA as a\n # search criterion but the code is left in here for reference.\n # gaval -- String containing a gA number.\n # gacmp -- Same as nfcmp.\n\n # Freq items consist of a domain (such as \"ichi\" or \"nf\")\n # and a value (such as \"1\" or \"35\").\n # Process the checkboxes by creating a hash indexed by\n # by domain and with each value a list of freq values.\n\n KW = jdb.KW\n x = {}; inv = ''\n if 'NOT' in freq:\n freq.remove ('NOT')\n inv = 'NOT '\n # FIXME: we really shouldn't hardwire this...\n if 'P' in freq:\n freq.remove ('P')\n freq = list (set (freq + ['ichi1','gai1','news1','spec1']))\n for f in freq:\n # Split into text (domain) and numeric (value) parts.\n match = re.search (r'^([A-Za-z_-]+)(\\d*)$', f)\n domain, value = match.group(1,2)\n if domain == 'nf': have_nf = True\n elif domain == 'gA': have_gA = True\n else:\n # Append this value to the domain list.\n x.setdefault (domain, []).append (value)\n\n # Now process each domain and it's list of values...\n\n whr = []\n for k,v in list(x.items()):\n # Convert the domain string to a kwfreq table id number.\n kwid = KW.FREQ[k].id\n\n # The following assumes that the range of values are\n # limited to 1 and 2.\n\n # As an optimization, if there are 2 values, they must be 1 and 2,\n # so no need to check value in query, just see if the domain exists.\n # FIXME: The above is false, e.g., there could be two \"1\" values.\n # FIXME: The above assumes only 1 and 2 are allowed. Currently\n # true but may change in future.\n if len(v) == 2: whr.append (\"(freq.kw=%s)\" % kwid)\n # If there is only one value we need to look for kw with\n # that value.\n elif len(v) == 1: whr.append (\"(freq.kw=%s AND freq.value=%s)\" % (kwid, v[0]))\n # If there are more than 2 values then we look for them explicitly\n # using an IN() construct.\n elif len(v) > 2: whr.append (\n \"(freq.kw=%s AND freq.value IN (%s))\" % (k, \",\".join(v)))\n # A 0 length list should never occur.\n else: raise ValueError (\"No numeric value in freq item\")\n\n # Handle any \"nfxx\" item specially here.\n\n if nfval:\n kwid = KW.FREQ['nf'].id\n # Build list of \"where\" clause parts using the requested comparison and value.\n if nfcmp == '≤': nfcmp = '<='\n elif nfcmp == '≥': nfcmp = '>='\n whr.append (\n \"(freq.kw=%s AND freq.value%s%s)\" % (kwid, nfcmp, nfval))\n\n # Handle any \"gAxx\" item specially here.\n\n if gaval:\n kwid = KW.FREQ['gA'].id\n # Build list of \"where\" clause parts using the requested comparison and value.\n whr.append (\n \"(freq.kw=%s AND freq.value%s%s)\" % (kwid, gacmp, gaval))\n\n # If there were no freq related conditions...\n if not whr: return []\n\n # Now, @whr is a list of all the various freq related conditions that\n # were selected. We change it into a clause by connecting them all\n # with \" OR\".\n whr = (\"%s(\" + \" OR \".join(whr) + \")\") % inv\n\n # Return a triple suitable for use by build-search_sql(). That function\n # will build sql that effectivly \"AND\"s all the conditions (each specified\n # in a triple) given to it. Our freq conditions applies to two tables\n # (rfreq and kfreq) and we want them OR'd not AND'd. So we cheat and use a\n # strisk in front of table name to tell build_search_sql() to use left joins\n # rather than inner joins when refering to that condition's table. This will\n # result in the inclusion in the result set of rfreq rows that match the\n # criteria, even if there are no matching kfreq rows (and visa versa).\n # The where clause refers to both the rfreq and kfreq tables, so need only\n # be given in one constion triple rather than in each.\n\n return [(\"freq\",whr,[])]\n\ndef utt (d):\n # Convert a simple string-to-string mapping into\n # the form required by .translate().\n return dict ((ord(k), str(v)) for k,v in list(d.items()))\n\nWc_trans = utt({'*':'%', '?':'_', '%':'\\\\%', '_':'\\\\_'})\ndef wc2like (s):\n # Convert a string with wildcard characters '*' and '?' to SQL\n # \"like\" operator characters, \"%\" and \"_\", being careful of\n # escape \"\\\" characters.\n s1 = str (s)\n s1 = s1.replace ('\\\\*', '\\x01')\n s1 = s1.replace ('\\\\?', '\\x02')\n s1 = s1.translate (Wc_trans)\n s1 = s1.replace ('\\x01', '*')\n s1 = s1.replace ('\\x02', '?')\n return s1\n\ndef parse_cfg_logfilters (s):\n result = []\n for ln in s.splitlines():\n ln = ln.strip ()\n if not ln: continue\n result.append (ln)\n return result\n","repo_name":"gabriel4649/JMdictDB","sub_path":"python/lib/jmcgi.py","file_name":"jmcgi.py","file_ext":"py","file_size_in_byte":50109,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"10031414420","text":"import sys\r\nprint = sys.stdout.write\r\n\r\nN, B = map(int, input().split())\r\nban = [[False] * N for _ in range(N)]\r\n\r\nif B > N * (N - 1) or N == 2 and B > 1:\r\n print('NO')\r\n exit(0)\r\n\r\nfor i in range(1, N - 1):\r\n ban[i][i] = True\r\nban[0][N - 1] = True\r\nban[N - 1][0] = True\r\n\r\nprint('YES\\n')\r\nfor r in range(N):\r\n for c in range(N):\r\n if ban[r][c] or B == 0:\r\n print('.')\r\n else:\r\n print('#')\r\n B -= 1\r\n print('\\n')\r\n","repo_name":"wzrabbit/algorithm-practice","sub_path":"BOJ/♣ 21000~21999/21763_Bingo.py","file_name":"21763_Bingo.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"40"} +{"seq_id":"21349390299","text":"capacity = int(input())\nincome = 0\n\ncommand = input()\n\nwhile command != \"Movie time!\":\n group_count = int(command)\n\n if group_count > capacity:\n print(\"The cinema is full.\")\n print(f\"Cinema income - {income} lv.\")\n exit()\n\n capacity -= group_count\n group_tax = group_count * 5\n if group_count % 3 == 0:\n group_tax -= 5\n income += group_tax\n\n command = input()\n\nprint(f\"There are {capacity} seats left in the cinema.\")\nprint(f\"Cinema income - {income} lv.\")\n","repo_name":"marinakolova/SoftUni-Python-Courses","sub_path":"Programming-Basics-with-Python-April-2019/programming_basics_online_exam_15_and_16_june_2019/04_cinema.py","file_name":"04_cinema.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"9747589764","text":"# Goolgle Home page example\n#\n# Author: Dnpwwo, 2017\n#\n# Demonstrates HTTP connectivity.\n# After connection it performs a GET on www.google.com and receives a 302 (Page Moved) response\n# It then does a subsequent GET on the Location specified in the 302 response and receives a 200 response.\n#\n# used as base to create Sonoff Plugin\n \n\"\"\"\n\n \n \n \n \n \n \n \n \n\n\"\"\"\nimport Domoticz\nimport urllib.request\n\nclass BasePlugin:\n\n httpConn = None\n runAgain = 1\n \n def __init__(self):\n return\n\n def onStart(self):\n if Parameters[\"Mode6\"] == \"Debug\":\n Domoticz.Debugging(1)\n DumpConfigToLog()\n self.httpConn = Domoticz.Connection(Name=\"HTTP Test\", Transport=\"TCP/IP\", Protocol=\"HTTP\", Address=Parameters[\"Address\"], Port=Parameters[\"Port\"])\n self.httpConn.Connect()\n\n def onStop(self):\n Domoticz.Log(\"onStop - Plugin is stopping.\")\n\n def onConnect(self, Connection, Status, Description):\n if (Status == 0):\n Domoticz.Debug(\"Local Sonoff server connected successfully.\")\n sendData = { 'Verb' : 'GET',\n 'URL' : '/devices',\n 'Headers' : { 'Content-Type': 'text/xml; charset=utf-8', \\\n 'Connection': 'keep-alive', \\\n 'Accept': 'Content-Type: text/html; charset=UTF-8', \\\n 'Host': Parameters[\"Address\"]+\":\"+Parameters[\"Port\"], \\\n 'User-Agent':'Domoticz/1.0' }\n }\n Connection.Send(sendData)\n else:\n Domoticz.Log(\"Failed to connect (\"+str(Status)+\") to: \"+Parameters[\"Address\"]+\":\"+Parameters[\"Port\"]+\" with error: \"+Description)\n\n def onMessage(self, Connection, Data):\n #DumpHTTPResponseToLog(Data)\n # expect strData like [{\"id\":\"100017aec6\",\"state\":\"on\",\"model\":\"PSA-B01-GL\",\"version\":\"1.5.5\"},{\"id\":\"100017aec6\",\"state\":\"on\",\"model\":\"PSA-B01-GL\",\"version\":\"1.5.5\"}]\n strData = Data[\"Data\"].decode(\"utf-8\", \"ignore\")\n Status = int(Data[\"Status\"])\n #LogMessage(strData)\n\n if (Status == 200):\n # success\n Domoticz.Log(\"Response from local Sonoff server.\"+str(strData))\n self.httpConn.Disconnect()\n else:\n # problem\n Domoticz.Error(\"Local Sonoff server returned a status: \"+str(Status))\n\n # convert strData string to a python dictionary using eval\n strData_structure=eval(strData)\n\n # handle all switches provided by the local Sonoff server\n Domoticz.Log(\"loop strData_structure\")\n for Switch in strData_structure:\n sw_id=Switch[\"id\"]\n sw_state=Switch[\"state\"]\n sw_model=Switch[\"model\"]\n sw_version=Switch[\"version\"]\n Domoticz.Log(\"Sonoff switch: id=\" + str(sw_id) + \" state=\" + str(sw_state) + \" model=\" + str(sw_model) + \" version=\" + str(sw_version))\n\n # compose name off switch in Domoticz, can later be changed in GUI\n sw_name=\"Sonoff\"+str(sw_id)\n\n # Domoticz.Debug(\"Existing Devices:\" + str(Devices))\n DumpConfigToLog()\n\n # check the Sonoff id (like 100017aec6) with the sValue of existing Domoticz devices\n deviceFound = False\n for Device in Devices:\n if (Devices[Device].sValue == sw_id):\n deviceFound = True\n sw_unit=Device\n\n if (deviceFound == True):\n # existing device\n Domoticz.Debug(\"Sonoff \" + sw_id + \" is existing as Unit \" + str(sw_unit))\n Domoticz.Debug(\"Existing Sonoff switch updated from : id=\" + str(sw_id) + \" state=\" + str(sw_state) + \" model=\" + str(sw_model) + \" version=\" + str(sw_version))\n else:\n # unknown device\n Domoticz.Debug(\"Sonoff-\" + sw_id + \"is NOT existing\")\n #if NO devices defined yet, set unitnumber to 1, else set new unit number as currently max unit number + 1\n if ( len(Devices) == 0 ):\n sw_unit=1\n else:\n sw_unit=max(Devices)+1\n\n # create new device device, unit to sw_unit, nvalue to 0, sValue to sw_id of Sonoff (like 100017aec6), unit to sw_unit, Used=1 \n Domoticz.Device(Name=sw_name, Unit=sw_unit, TypeName=\"Switch\", Used=1).Create()\n UpdateDevice(sw_unit, 0 , str(sw_id)) \n Domoticz.Debug(\"New Sonoff switch created from : id=\" + str(sw_id) + \" state=\" + str(sw_state) + \" model=\" + str(sw_model) + \" version=\" + str(sw_version))\n Domoticz.Debug(\"New Sonoff switch created as unit \" + str(sw_unit) + \"and sValue \" + str(Devices[sw_unit].sValue))\n\n if ( str(sw_state).lower() == \"on\" ):\n # command is \"on\", set nValue to 1\n UpdateDevice(sw_unit, 1 ,Devices[sw_unit].sValue) \n Domoticz.Debug(\"Existing Sonoff switch updated as unit \" + str(sw_unit) + \" and sValue \" + str(Devices[sw_unit].sValue) + \" with nValue=1\")\n else:\n # command is NOT \"on\" so it must be \"off\", set nValue to 0\n UpdateDevice(sw_unit, 0 ,Devices[sw_unit].sValue) \n Domoticz.Debug(\"Existing Sonoff switch updated as unit \" + str(sw_unit) + \" and sValue \" + str(Devices[sw_unit].sValue) + \" with nValue=0\")\n\n\n def onCommand(self, Unit, Command, Level, Hue):\n Domoticz.Debug(\"onCommand called for Unit \" + str(Unit) + \": Parameter '\" + str(Command) + \"', Level: \" + str(Level))\n\n # update the Domticz device\n if ( str(Command).lower() == \"on\" ):\n UpdateDevice(Unit, 1 ,Devices[Unit].sValue)\n else:\n UpdateDevice(Unit, 0 ,Devices[Unit].sValue)\n\n # send command to Sonoff server\n Address=Parameters[\"Address\"]\n Port=Parameters[\"Port\"]\n URL=\"http://127.0.0.1:\" + Port + \"/devices/\" + Devices[Unit].sValue + \"/\" + str(Command).lower()\n Domoticz.Debug(\"Send URL : \" + URL)\n self.sonoffSend(URL)\n\n def onDisconnect(self, Connection):\n Domoticz.Debug(\"onDisconnect called for connection to: \"+Connection.Address+\":\"+Connection.Port)\n\n def onHeartbeat(self):\n if (self.httpConn.Connecting() or self.httpConn.Connected()):\n Domoticz.Debug(\"onHeartbeat called, Connection is alive.\")\n else:\n self.runAgain = self.runAgain - 1\n if self.runAgain <= 0:\n self.httpConn.Connect()\n self.runAgain = 1\n else:\n Domoticz.Debug(\"onHeartbeat called, run again in \"+str(self.runAgain)+\" heartbeats.\")\n\n def GetValue(self, arr, sKey, defValue):\n try:\n if str(sKey) in arr:\n if ( str(arr[str(sKey)]).lower() == \"none\" ):\n return defValue\n else:\n return arr[str(sKey)]\n else:\n return defValue\n except:\n return defValue\n\n def sonoffSend(self, URL):\n strData_string = str(urllib.request.urlopen(URL).read())\n Domoticz.Log(\"strData_string:\" + strData_string)\n if ('OK' in strData_string):\n Domoticz.Debug(\"Success! The local Sonoff server responded 'OK'\")\n else:\n Domoticz.Error(\"Problem! The local Sonoff server did not respond 'OK'\")\n\n\nglobal _plugin\n_plugin = BasePlugin()\n\ndef onStart():\n global _plugin\n _plugin.onStart()\n\ndef onStop():\n global _plugin\n _plugin.onStop()\n\ndef onConnect(Connection, Status, Description):\n global _plugin\n _plugin.onConnect(Connection, Status, Description)\n\ndef onMessage(Connection, Data):\n global _plugin\n _plugin.onMessage(Connection, Data)\n\ndef onCommand(Unit, Command, Level, Hue):\n global _plugin\n _plugin.onCommand(Unit, Command, Level, Hue)\n\ndef onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile):\n global _plugin\n _plugin.onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile)\n\ndef onDisconnect(Connection):\n global _plugin\n _plugin.onDisconnect(Connection)\n\ndef onHeartbeat():\n global _plugin\n _plugin.onHeartbeat()\n\n# Generic helper functions\n\ndef LogMessage(Message):\n if Parameters[\"Mode6\"] == \"File\":\n f = open(Parameters[\"HomeFolder\"]+\"http.html\",\"w\")\n f.write(Message)\n f.close()\n Domoticz.Log(\"File written\")\n\ndef DumpConfigToLog():\n for x in Parameters:\n if Parameters[x] != \"\":\n Domoticz.Debug( \"'\" + x + \"':'\" + str(Parameters[x]) + \"'\")\n Domoticz.Debug(\"Device count: \" + str(len(Devices)))\n for x in Devices:\n Domoticz.Debug(\"Device: \" + str(x) + \" - \" + str(Devices[x]))\n Domoticz.Debug(\"Device ID: '\" + str(Devices[x].ID) + \"'\")\n Domoticz.Debug(\"Device Name: '\" + Devices[x].Name + \"'\")\n Domoticz.Debug(\"Device nValue: \" + str(Devices[x].nValue))\n Domoticz.Debug(\"Device sValue: '\" + Devices[x].sValue + \"'\")\n Domoticz.Debug(\"Device LastLevel: \" + str(Devices[x].LastLevel))\n return\n\ndef DumpHTTPResponseToLog(httpDict):\n if isinstance(httpDict, dict):\n Domoticz.Log(\"HTTP Details (\"+str(len(httpDict))+\"):\")\n for x in httpDict:\n if isinstance(httpDict[x], dict):\n Domoticz.Log(\"--->'\"+x+\" (\"+str(len(httpDict[x]))+\"):\")\n for y in httpDict[x]:\n Domoticz.Log(\"------->'\" + y + \"':'\" + str(httpDict[x][y]) + \"'\")\n else:\n Domoticz.Log(\"--->'\" + x + \"':'\" + str(httpDict[x]) + \"'\")\n\ndef UpdateDevice(Unit, nValue, sValue, AlwaysUpdate=False): \n # Make sure that the Domoticz device still exists (they can be deleted) before updating it \n if (Unit in Devices):\n if ((Devices[Unit].nValue != nValue) or (Devices[Unit].sValue != sValue) or (AlwaysUpdate == True)):\n Devices[Unit].Update(nValue=nValue, sValue=str(sValue))\n Domoticz.Log(\"Update \"+str(nValue)+\":'\"+str(sValue)+\"' (\"+Devices[Unit].Name+\")\")\n return\n\n","repo_name":"gerardwr/Sonoff-Domoticz","sub_path":"Plugin V0.0.1/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":10831,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"40"} +{"seq_id":"12877741015","text":"import requests as rq\nimport json\nfrom bs4 import BeautifulSoup\nimport queue\n\n# start에 url 넣어주고 해당 url에서 찾을 수 있는 a tag의 href 속성 다 queue에 넣기\nclass Parse:\n\t#def __init__(self,start):\n\n\tdef bfs(self,start):\n\t\tsearch_q = queue.Queue()\n\t\tvisited = []\n\t\tsearch_q.put(start)\n\n\t\twhile not search_q.empty():\n\t\t\tn = search_q.get()\t#n <- url\n\t\t\tprint(\"===\"+n)\n\t\t\tvisited.append(n)\n\t\t\tres = rq.get(n)\n\t\t\ttag = BeautifulSoup(res.text, 'html.parser')\n\t\t\tfor url in tag.select('a'):\n\t\t\t\tprint(url.get_text()+\"\\n\"+url.get('href')+\"\\n\")\n\t\t\t\tsearch_q.put(\"https:/\"+url.get('href'))\n\nmain_parser = Parse()\nmain_parser.bfs(\"https://beomi.github.io/beomi.github.io_old/\")\n\n#f = open(\"crawl.txt\", 'w')\n#req = rq.get(\"https://beomi.github.io/beomi.github.io_old/\")\n\n#f.close()","repo_name":"lsy230/pr_practice","sub_path":"previous/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"72730741559","text":"import json\nfrom bert4keras.snippets import sequence_padding, open\nfrom bert4keras.snippets import DataGenerator, AutoRegressiveDecoder\nfrom bert4keras.layers import Loss\nfrom bert4keras.backend import keras, K\nfrom bert4keras.tokenizers import Tokenizer, load_vocab\nimport test4nlp.chinese_spelling_correction.config.correction_seq2seq_config as config\n\n# 加载并精简词表,建立分词器\ntoken_dict, keep_tokens = load_vocab(\n dict_path=config.dict_path,\n simplified=True,\n startswith=['[PAD]', '[UNK]', '[CLS]', '[SEP]'],\n)\ntokenizer = Tokenizer(token_dict, do_lower_case=True)\n\n\ndef get_data(train_data_path, valid_data_path):\n train_data = json.load(open(train_data_path, 'r', encoding='utf-8'))\n valid_data = json.load(open(valid_data_path, 'r', encoding='utf-8'))\n return train_data, valid_data\n\n\nclass data_generator(DataGenerator):\n \"\"\"数据生成器\n \"\"\"\n def __iter__(self, random=False):\n batch_token_ids, batch_segment_ids = [], []\n for is_end, d in self.sample(random):\n wrong = d[0]\n right = d[1]\n token_ids, segment_ids = tokenizer.encode(\n wrong, right, maxlen=config.maxlen\n )\n batch_token_ids.append(token_ids)\n batch_segment_ids.append(segment_ids)\n if len(batch_token_ids) == self.batch_size or is_end:\n batch_token_ids = sequence_padding(batch_token_ids)\n batch_segment_ids = sequence_padding(batch_segment_ids)\n yield [batch_token_ids, batch_segment_ids], None\n batch_token_ids, batch_segment_ids = [], []\n\n\n\nclass CrossEntropy(Loss):\n \"\"\"交叉熵作为loss,并mask掉输入部分\n \"\"\"\n def compute_loss(self, inputs, mask=None):\n y_true, y_mask, y_pred = inputs\n y_true = y_true[:, 1:] # 目标token_ids\n y_mask = y_mask[:, 1:] # segment_ids,刚好指示了要预测的部分\n y_pred = y_pred[:, :-1] # 预测序列,错开一位\n loss = K.sparse_categorical_crossentropy(y_true, y_pred)\n loss = K.sum(loss * y_mask) / K.sum(y_mask)\n return loss\n\n\n","repo_name":"danwei1992/test4nlp","sub_path":"chinese_spelling_correction/algor/train/utils/correction_seq2seq_utils.py","file_name":"correction_seq2seq_utils.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"71124096119","text":"#!/usr/bin/env python3\nimport datetime\nimport sys\nimport h5py\nimport numpy as np\n\nfrom PIL import Image\n\n# from https://gist.github.com/yrevar/942d3a0ac09ec9e5eb3a#file-imagenet1000_clsidx_to_labels-txt\nfrom labels import IMAGENET_LABELS\n\n\nCUDA_SRC = \"\"\"\n__global__ void conv2d(const float *inp, float *out, const float *w,\n const float *b, int inp_channels, int ksize) {\n int channel_num = threadIdx.x;\n int out_channels = blockDim.x;\n\n // pixel (x, y)\n int x = blockIdx.x;\n int y = blockIdx.y;\n\n int outidx = out_channels * gridDim.y * x +\n out_channels * y +\n channel_num;\n\n for (int i = 0; i < ksize; i++) {\n for (int j = 0; j < ksize; j++) {\n for (int k = 0; k < inp_channels; k++) {\n\n // w is 4D with dimensions: (ksize, ksize, input_channels, output_channels)\n int widx = (ksize * inp_channels * out_channels * i) +\n (inp_channels * out_channels * j) +\n (out_channels * k) +\n channel_num;\n\n // inp is 3D with dimensions: (blockDim.x + padding, blockDim.y + padding, input_channels)\n int inpidx = ((gridDim.y + ksize - 1) * inp_channels * (i + x)) +\n (inp_channels * (j + y)) +\n k;\n\n out[outidx] += inp[inpidx] * w[widx];\n }\n }\n }\n\n // add bias\n out[outidx] += b[channel_num];\n\n // relu\n if (out[outidx] < 0) {\n out[outidx] = 0.0;\n }\n}\n\"\"\"\n\n\n# from https://github.com/keras-team/keras/blob/07e13740fd181fc3ddec7d9a594d8a08666645f6/keras/applications/imagenet_utils.py#L168-L238\ndef preprocess_img(img):\n x = img.astype(np.float32)\n # 'RGB'->'BGR' (because of opencv?)\n x = x[..., ::-1]\n mean = [103.939, 116.779, 123.68]\n x[..., 0] -= mean[0]\n x[..., 1] -= mean[1]\n x[..., 2] -= mean[2]\n return x\n\n\n# from https://storage.googleapis.com/tensorflow/keras-applications/vgg16/vgg16_weights_tf_dim_ordering_tf_kernels.h5\nVGG_WTS = h5py.File(\"vgg16_weights_tf_dim_ordering_tf_kernels.h5\", \"r\")\n\n\n# layer names from https://github.com/keras-team/keras/blob/v2.9.0/keras/applications/vgg16.py#L43-L227\n# can also be obtained by executing `model.summary()` on the `Model` object\nVGG_LAYERS = ['block1_conv1', 'block1_conv2', 'block1_pool',\n 'block2_conv1', 'block2_conv2', 'block2_pool',\n 'block3_conv1', 'block3_conv2', 'block3_conv3', 'block3_pool',\n 'block4_conv1', 'block4_conv2', 'block4_conv3', 'block4_pool',\n 'block5_conv1', 'block5_conv2', 'block5_conv3', 'block5_pool',\n 'flatten',\n 'fc1', 'fc2',\n 'predictions']\n\n\n# return top predictions with probabilities from output of last layer\ndef get_top_predictions(preds, top=5):\n return {IMAGENET_LABELS[x]: preds[x] for x in (-preds).argsort()[:top]}\n\n\ndef relu(x):\n return np.maximum(x, 0)\n\n\ndef softmax(x):\n exp = np.exp(x)\n return exp / np.sum(exp)\n\n\ndef applyConv2d(w, b, inp, cuda=False):\n \"\"\"assuming odd-sized square kernel\"\"\"\n ksize = w.shape[0]\n inp_channels = inp.shape[-1]\n out_channels = w.shape[-1]\n\n # pad the input, not output: https://stackoverflow.com/a/69544897\n padded_inp = np.pad(inp, ((ksize//2, ksize//2),\n (ksize//2, ksize//2),\n (0, 0)))\n\n # output is same shape as input with more channels\n out = np.zeros(inp.shape[:2] + (out_channels,), dtype=np.float32)\n\n if cuda:\n # convert numpy arrays to pycuda.gpuarray\n in_gpu, out_gpu = pycuda.gpuarray.to_gpu(padded_inp), pycuda.gpuarray.to_gpu(out)\n w_gpu, b_gpu = pycuda.gpuarray.to_gpu(w), pycuda.gpuarray.to_gpu(b)\n\n # call cuda implementation with the GPU arrays\n cudaConv2d(in_gpu, out_gpu, w_gpu, b_gpu, np.int32(inp_channels), np.int32(ksize),\n block=(out_channels, 1, 1), grid=inp.shape[:2])\n\n # copy back the output from GPU memory\n return out_gpu.get()\n else:\n # convolve the surrounding of each pixel (3x3x3) with the kernel\n for x in range(inp.shape[0]):\n for y in range(inp.shape[1]):\n for c in range(out_channels):\n out[x][y][c] = np.tensordot(w[..., c],\n padded_inp[x:x+ksize, y:y+ksize],\n ksize)\n\n # add bias to each output channel\n for c in range(out_channels):\n out[..., c] += b[c]\n\n # apply relu activation\n return relu(out)\n\n\ndef applyMaxPool2d(inp):\n \"\"\"2x2 kernel with (2,2) stride\"\"\"\n out = np.zeros((inp.shape[0]//2, inp.shape[1]//2, inp.shape[2]), dtype=np.float32)\n for x in range(out.shape[0]):\n for y in range(out.shape[1]):\n for c in range(inp.shape[2]):\n out[x][y][c] = np.max(inp[2*x:2*(x+1), 2*y:2*(y+1), c])\n return out\n\n\ndef applyVgg16(inp, cuda=False):\n curr = inp\n outputs = []\n for layer in VGG_LAYERS:\n if \"pool\" in layer:\n out = applyMaxPool2d(curr)\n elif layer == \"flatten\":\n out = curr.flatten()\n # weight layers\n else:\n w, b = (np.array(x) for x in VGG_WTS[layer].values())\n if layer.startswith(\"fc\") or layer == \"predictions\":\n # fully connected layers are a simple matrix multiplication\n out = np.matmul(w.T, curr.reshape(-1, 1)).flatten() + b\n out = relu(out) if layer.startswith(\"fc\") else softmax(out)\n else:\n out = applyConv2d(w, b, curr, cuda)\n outputs.append(out)\n print(f\"processed {layer}: inshape: {curr.shape}, outshape: {out.shape}\")\n curr = out\n\n # return output of all hidden layers along with output layer\n # helps in inspecting output of hidden layers\n return outputs\n\n\n\nif __name__ == \"__main__\":\n # arg1 = tf/numpy/cuda\n # arg2 = image path\n\n # read sample image using PIL and resize to the size required by VGG16\n img = np.asarray(Image.open(sys.argv[2]).resize((224, 224)))\n \n # preprocess input image as done by tensorflow\n img = preprocess_img(img)\n\n if sys.argv[1] == \"tf\":\n import tensorflow as tf\n\n model = tf.keras.applications.vgg16.VGG16()\n start = datetime.datetime.now()\n outputs = [model.predict(img[np.newaxis, ...])[0]]\n end = datetime.datetime.now()\n elif sys.argv[1] == \"numpy\":\n start = datetime.datetime.now()\n outputs = applyVgg16(img)\n end = datetime.datetime.now()\n else:\n import pycuda.gpuarray\n import pycuda.autoinit\n from pycuda.compiler import SourceModule\n\n mod = SourceModule(CUDA_SRC)\n cudaConv2d = mod.get_function(\"conv2d\")\n\n start = datetime.datetime.now()\n outputs = applyVgg16(img, cuda=True)\n end = datetime.datetime.now()\n\n print(\"predictions: \", get_top_predictions(outputs[-1]))\n print(f\"computed in {end-start}\")\n","repo_name":"arpankapoor/pycuda-vgg16","sub_path":"vgg.py","file_name":"vgg.py","file_ext":"py","file_size_in_byte":6998,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"40"} +{"seq_id":"1898215497","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018/3/4 17:15\n# @Author : LiYuan_Zhang\n# @Site : \n# @File : \n# @Software: PyCharm\nimport os\nos.makedirs('/etc/ansible/hosts',mode=755,exist_ok=False)\ndef CreateHost(Host_ip):\n with open('/etc/ansible/hosts/hosts','w+',encoding='utf-8') as f:\n f.write(Host_ip)","repo_name":"qiu957919102/flask-ansible-python3.6-","sub_path":"ansiblemanager/Hostcreateversion1.py","file_name":"Hostcreateversion1.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"4339218334","text":"from iotdb.Session import Session\nfrom iotdb.utils.IoTDBConstants import TSDataType, TSEncoding, Compressor\nfrom iotdb.utils.Tablet import Tablet\nfrom iotdb.IoTDBContainer import IoTDBContainer\n\n# whether the test has passed\nfinal_flag = True\nfailed_count = 0\n\n\ndef test_fail():\n global failed_count\n global final_flag\n final_flag = False\n failed_count += 1\n\n\ndef print_message(message):\n print(\"*********\")\n print(message)\n print(\"*********\")\n assert False\n\n\ndef test_aligned_timeseries():\n with IoTDBContainer(\"iotdb:dev\") as db:\n db: IoTDBContainer\n session = Session(db.get_container_host_ip(), db.get_exposed_port(6667))\n session.open(False)\n\n if not session.is_open():\n print(\"can't open session\")\n exit(1)\n\n # set and delete databases\n session.set_storage_group(\"root.sg_test_01\")\n session.set_storage_group(\"root.sg_test_02\")\n session.set_storage_group(\"root.sg_test_03\")\n session.set_storage_group(\"root.sg_test_04\")\n\n if session.delete_storage_group(\"root.sg_test_02\") < 0:\n test_fail()\n print_message(\"delete database failed\")\n\n if session.delete_storage_groups([\"root.sg_test_03\", \"root.sg_test_04\"]) < 0:\n test_fail()\n print_message(\"delete databases failed\")\n\n # setting aligned time series.\n measurements_lst_ = [\n \"s_01\",\n \"s_02\",\n \"s_03\",\n ]\n data_type_lst_ = [\n TSDataType.BOOLEAN,\n TSDataType.INT32,\n TSDataType.INT64,\n ]\n encoding_lst_ = [TSEncoding.PLAIN for _ in range(len(data_type_lst_))]\n compressor_lst_ = [Compressor.SNAPPY for _ in range(len(data_type_lst_))]\n session.create_aligned_time_series(\n \"root.sg_test_01.d_02\",\n measurements_lst_,\n data_type_lst_,\n encoding_lst_,\n compressor_lst_,\n )\n\n # setting more aligned time series once.\n measurements_lst_ = [\n \"s_04\",\n \"s_05\",\n \"s_06\",\n \"s_07\",\n \"s_08\",\n \"s_09\",\n ]\n data_type_lst_ = [\n TSDataType.FLOAT,\n TSDataType.DOUBLE,\n TSDataType.TEXT,\n TSDataType.FLOAT,\n TSDataType.DOUBLE,\n TSDataType.TEXT,\n ]\n encoding_lst_ = [TSEncoding.PLAIN for _ in range(len(data_type_lst_))]\n compressor_lst_ = [Compressor.SNAPPY for _ in range(len(data_type_lst_))]\n session.create_aligned_time_series(\n \"root.sg_test_01.d_02\",\n measurements_lst_,\n data_type_lst_,\n encoding_lst_,\n compressor_lst_,\n )\n\n # delete time series\n try:\n session.delete_time_series(\n [\n \"root.sg_test_01.d_02.s_07\",\n \"root.sg_test_01.d_02.s_08\",\n \"root.sg_test_01.d_02.s_09\",\n ]\n )\n except Exception:\n test_fail()\n print_message(\"delete time series failed\")\n\n # checking time series\n # s_07 expecting False\n if session.check_time_series_exists(\"root.sg_test_01.d_02.s_07\"):\n test_fail()\n print_message(\"root.sg_test_01.d_02.s_07 shouldn't exist\")\n\n # s_03 expecting True\n if not session.check_time_series_exists(\"root.sg_test_01.d_02.s_03\"):\n test_fail()\n print_message(\"root.sg_test_01.d_02.s_03 should exist\")\n\n # insert one record into the database.\n measurements_ = [\"s_01\", \"s_02\", \"s_03\", \"s_04\", \"s_05\", \"s_06\"]\n values_ = [False, 10, 11, 1.1, 10011.1, \"test_record\"]\n data_types_ = [\n TSDataType.BOOLEAN,\n TSDataType.INT32,\n TSDataType.INT64,\n TSDataType.FLOAT,\n TSDataType.DOUBLE,\n TSDataType.TEXT,\n ]\n try:\n session.insert_aligned_record(\n \"root.sg_test_01.d_02\", 1, measurements_, data_types_, values_\n )\n except Exception:\n test_fail()\n print_message(\"insert record failed\")\n\n # insert multiple records into database\n measurements_list_ = [\n [\"s_01\", \"s_02\", \"s_03\", \"s_04\", \"s_05\", \"s_06\"],\n [\"s_01\", \"s_02\", \"s_03\", \"s_04\", \"s_05\", \"s_06\"],\n ]\n values_list_ = [\n [False, 22, 33, 4.4, 55.1, \"test_records01\"],\n [True, 77, 88, 1.25, 8.125, \"test_records02\"],\n ]\n data_type_list_ = [data_types_, data_types_]\n device_ids_ = [\"root.sg_test_01.d_02\", \"root.sg_test_01.d_02\"]\n try:\n session.insert_aligned_records(\n device_ids_, [2, 3], measurements_list_, data_type_list_, values_list_\n )\n except Exception:\n test_fail()\n print_message(\"insert records failed\")\n\n # insert one tablet into the database.\n values_ = [\n [False, 10, 11, 1.1, 10011.1, \"test01\"],\n [True, 100, 11111, 1.25, 101.0, \"test02\"],\n [False, 100, 1, 188.1, 688.25, \"test03\"],\n [True, 0, 0, 0, 6.25, \"test04\"],\n ] # Non-ASCII text will cause error since bytes can only hold 0-128 nums.\n timestamps_ = [4, 5, 6, 7]\n tablet_ = Tablet(\n \"root.sg_test_01.d_02\", measurements_, data_types_, values_, timestamps_\n )\n if session.insert_aligned_tablet(tablet_) < 0:\n test_fail()\n print_message(\"insert tablet failed\")\n\n # insert multiple tablets into database\n tablet_01 = Tablet(\n \"root.sg_test_01.d_02\", measurements_, data_types_, values_, [8, 9, 10, 11]\n )\n tablet_02 = Tablet(\n \"root.sg_test_01.d_02\",\n measurements_,\n data_types_,\n values_,\n [12, 13, 14, 15],\n )\n if session.insert_aligned_tablets([tablet_01, tablet_02]) < 0:\n test_fail()\n print_message(\"insert tablets failed\")\n\n # insert one tablet with empty cells into the database.\n values_ = [\n [None, 10, 11, 1.1, 10011.1, \"test01\"],\n [True, None, 11111, 1.25, 101.0, \"test02\"],\n [False, 100, 1, None, 688.25, \"test03\"],\n [True, 0, 0, 0, None, None],\n ] # Non-ASCII text will cause error since bytes can only hold 0-128 nums.\n timestamps_ = [20, 21, 22, 23]\n tablet_ = Tablet(\n \"root.sg_test_01.d_02\", measurements_, data_types_, values_, timestamps_\n )\n if session.insert_aligned_tablet(tablet_) < 0:\n test_fail()\n print_message(\"insert tablet with empty cells failed\")\n\n # insert records of one device\n time_list = [1, 2, 3]\n measurements_list = [\n [\"s_01\", \"s_02\", \"s_03\"],\n [\"s_01\", \"s_02\", \"s_03\"],\n [\"s_01\", \"s_02\", \"s_03\"],\n ]\n data_types_list = [\n [TSDataType.BOOLEAN, TSDataType.INT32, TSDataType.INT64],\n [TSDataType.BOOLEAN, TSDataType.INT32, TSDataType.INT64],\n [TSDataType.BOOLEAN, TSDataType.INT32, TSDataType.INT64],\n ]\n values_list = [[False, 22, 33], [True, 1, 23], [False, 15, 26]]\n\n if (\n session.insert_aligned_records_of_one_device(\n \"root.sg_test_01.d_02\",\n time_list,\n measurements_list,\n data_types_list,\n values_list,\n )\n < 0\n ):\n test_fail()\n print_message(\"insert records of one device failed\")\n\n # execute non-query sql statement\n try:\n session.execute_non_query_statement(\n \"insert into root.sg_test_01.d_02(timestamp, s_02) aligned values(16, 188)\"\n )\n except Exception:\n test_fail()\n print_message(\n \"execute 'insert into root.sg_test_01.d_02(timestamp, s_02) aligned values(16, 188)' failed\"\n )\n\n # execute sql query statement\n session_data_set = session.execute_query_statement(\n \"select * from root.sg_test_01.d_02\"\n )\n session_data_set.set_fetch_size(1024)\n expect_count = 20\n actual_count = 0\n while session_data_set.has_next():\n print(session_data_set.next())\n actual_count += 1\n session_data_set.close_operation_handle()\n\n if actual_count != expect_count:\n test_fail()\n print_message(\n \"query count mismatch: expect count: \"\n + str(expect_count)\n + \" actual count: \"\n + str(actual_count)\n )\n\n # close session connection.\n session.close()\n\n\nif final_flag:\n print(\"All executions done!!\")\nelse:\n print(\"Some test failed, please have a check\")\n print(\"failed count: \", failed_count)\n exit(1)\n","repo_name":"apache/iotdb","sub_path":"iotdb-client/client-py/tests/test_aligned_timeseries.py","file_name":"test_aligned_timeseries.py","file_ext":"py","file_size_in_byte":9040,"program_lang":"python","lang":"en","doc_type":"code","stars":4073,"dataset":"github-code","pt":"40"} +{"seq_id":"44824119145","text":"# Pictures to Obsidian Daily Notes\r\n# Author: Adrian Papineau\r\n# Date: 2021-11-18\r\n\r\nfrom watchdog.observers import Observer; from watchdog.events import PatternMatchingEventHandler\r\nimport glob; import os; import sys; import time; import platform\r\nfrom datetime import datetime, date; import time\r\nimport pyimgur; import shutil; import imghdr\r\n\r\nDailyNotesPath = \"\" # Example \"//MyServer/home/User/ObsidianVault/Daily notes\"\r\nObsidianVaultPathImages = \"\" # Example \"//MyServer/home/User/ObsidianVault/Photos\"\r\nImageFolderPath = \"\" # Example : \"//MyServer/home/User/Photos\"\r\nexclMark = False\r\nMaxPhotosPerFiveMin = 10\r\n\r\ndef excl():\r\n\tif exclMark == True:\r\n\t\treturn(\"!\")\r\n\telse:\r\n\t\treturn(\"\")\r\n\r\n# Search filesystem for new files(photos)\r\nif __name__ == \"__main__\":\r\n patterns = [\"*\"]\r\n ignore_patterns = None\r\n ignore_directories = False\r\n case_sensitive = True\r\n my_event_handler = PatternMatchingEventHandler(patterns, ignore_patterns, ignore_directories, case_sensitive)\r\n\r\ndef on_created(event):\r\n\ton_created.counter += 1\r\n\tprint(\"count is: \" + str(on_created.counter))\r\n\tif on_created.counter == MaxPhotosPerFiveMin:\r\n\t\ttime.sleep(300)\r\n\t\ton_created.counter = 0\r\n\telse:\r\n\t\tprint(f\"{event.src_path} has been created\")\r\n\t\tPhotoName({event.src_path}) \r\n\t\ttry:\r\n\t\t\tConvertBackslash({event.src_path})\r\n\t\texcept PermissionError:\r\n\t\t\tprint(\"Permission denied to access server. Restarting...\")\r\n\t\t\ttime.sleep(30)\r\n\t\t\tos.execl(sys.executable, sys.executable, *sys.argv)\r\n\r\non_created.counter = 0\r\n\r\ndef on_modified(event):\r\n print(f\"{event.src_path} has been modified\")\r\n\r\n\r\nmy_event_handler.on_created = on_created\r\nmy_event_handler.on_modified = on_modified\r\n\r\ngo_recursively = True\r\nmy_observer = Observer()\r\nmy_observer.schedule(my_event_handler, ImageFolderPath, recursive=go_recursively)\r\n\r\n#-----------------#\r\n\r\n#return current daily note file path\r\n\r\ndef CurrentDate(): \r\n\ttoday = date.today()\r\n\tdateExtractMonth = today.strftime('%B')\r\n\tdateExtractDay = today.strftime('%d')\r\n\tdateExtractYear = today.strftime('%Y')\r\n # Get rid of the beginning 0 in day of the month. \r\n\tif dateExtractDay[0] == \"0\":\r\n\t\tdateExtractDay = dateExtractDay[-1]\r\n # Add the \"th\" or similar\r\n\tif ((int(dateExtractDay) >= 10) and (int(dateExtractDay) <20)) or (dateExtractDay[-1] == \"0\") or ((int(dateExtractDay[-1]) >=4) and (int(dateExtractDay[-1]) <10)): \r\n\t\tdateExtractNUM = str(dateExtractDay + \"th\")\r\n\telif dateExtractDay[-1] == \"1\": \r\n\t\tdateExtractNUM = str(dateExtractDay + \"st\")\r\n\telif dateExtractDay[-1] == \"2\": \r\n\t\tdateExtractNUM = str(dateExtractDay + \"nd\")\r\n\telif dateExtractDay[-1] == \"3\": \r\n\t\tdateExtractNUM = str(dateExtractDay + \"rd\")\r\n\tRoamFormat = str(dateExtractMonth + \" \" + dateExtractNUM + \", \" + dateExtractYear)\r\n\treturn RoamFormat\r\n\tprint(CurrentDate())\r\n\r\ndef CurrentDailyNote():\r\n DailyNoteName = (CurrentDate() + \".md\")\r\n return DailyNoteName\r\n\r\n#-----------------#\r\n\r\n# check if uploaded files are image files:\r\n\r\ndef ConvertBackslash(path):\r\n\tstr_val = \" \".join(path)\r\n\tnewPath = str_val.replace(os.sep, '/')\r\n\tprint(newPath)\r\n\tCheckFile(newPath)\r\n\r\ndef PhotoName(PhotoPath):\r\n\tstr_val = \" \".join(PhotoPath)\r\n\tnewPath = str_val.replace(os.sep, '/')\r\n\tBaseName = os.path.basename(newPath)\r\n\tBaseNameWithoutSpaces = BaseName.replace(' ','')\r\n\tif \"IMG\" in PhotoPath:\r\n\t\treturn BaseNameWithoutSpaces\r\n\t\tprint(\"Removed spaces on file name\")\r\n\telse:\r\n\t\treturn BaseName\r\n\r\ndef CheckFile(file):\r\n\tif (imghdr.what(file) != None) or (\".HEIC\" in file):\r\n\t\tCopyImage(file)\r\n\telse:\r\n\t\tprint(\"File is not a proper image - skipping\")\r\n\r\n#copy image from folder to vault folder\r\n\r\ndef CopyImage(source):\r\n\tshutil.copy2(source, ObsidianVaultPathImages)\r\n\tprint(source + \" copied!\")\r\n\tAppendImageLink(source)\r\n\r\n# Append image link to Daily note\r\n\r\ndef AppendImageLink(Basename):\r\n\tt = time.localtime()\r\n\tcurrent_time = time.strftime(\"%H:%M\", t)\r\n\tdailyPath = DailyNotesPath + \"/\" + CurrentDailyNote()\r\n\tprint(\"Daily note path is: \" + dailyPath)\r\n\tdef WritePicture():\r\n\t\tprint(\"Beginning write to daily note\")\r\n\t\tNotefile = open(dailyPath, encoding=\"utf8\")\r\n\t\tNoteContent = Notefile.read()\r\n\t\tNotefile.seek(0)\r\n\t\tNotefile = open(dailyPath, \"w\", encoding=\"utf8\")\r\n\t\tNotefile.write(NoteContent + \"\\n\" + \"- \" + current_time + \" \" + excl() + \"[[Photos/\" + PhotoName(Basename) + \"]]\")\r\n\t\tNotefile.seek(0)\r\n\t\tNotefile.close()\r\n\t\tprint(\"Successfully wrote to daily note\")\r\n\tif os.path.isfile(dailyPath) == True:\r\n\t\tWritePicture()\r\n\telse:\r\n\t\tf = open(dailyPath,\"x\")\r\n\t\tf.close()\r\n\t\tprint(\"Had to create new note\")\r\n\t\tWritePicture()\r\n\t\tprint(\"Wrote the newly created note\")\r\n\r\n# Start monitoring \r\n\r\nprint(\"***Pictures to Daily Notes*** program started \\nCreated by Adrian Papineau \\n\")\r\nprint(\"Looking for new pictures on server...\\n\")\r\n\r\nif __name__ == \"__main__\":\r\n\tmy_observer.start()\t\r\n\r\ntry:\r\n while True:\r\n time.sleep(1)\r\nexcept KeyboardInterrupt:\r\n my_observer.stop()\r\n my_observer.join()\r\n\r\n\r\n","repo_name":"parallelinnovation/Pictures-to-Obsidian-Daily-Notes","sub_path":"PicturesToObsidianDailyNotes4VB.py","file_name":"PicturesToObsidianDailyNotes4VB.py","file_ext":"py","file_size_in_byte":4958,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"40"} +{"seq_id":"24301420574","text":"import os\nimport idlelib.colorizer as ic\nimport idlelib.percolator as ip\nimport re\nfrom tkinter.messagebox import *\nfrom tkinter.filedialog import *\nfrom tkinter import *\n\n# the window\nroot = Tk()\nroot.geometry('500x600')\nroot.config(bg='black')\nroot.title('Untitled -IDE')\n\n# setting file variable\nfile = None\n\n# our commands\n\n\ndef openFile():\n global file\n file = askopenfilename(title='open a file - Notepad',initialdir='/',filetypes=(('text files','*.txt'),(\"PY files\",'.py'),('All files','*.*')))\n if file == '':\n showinfo(\"Error\",\"Please open a file\")\n else:\n root.title(os.path.basename(file)+' -IDE')\n filet = open(file,'r')\n filee = filet.read()\n text.delete(1.0,END)\n text.insert(1.0,filee)\n filet.close()\n\ndef saveFile():\n if file==None:\n fiol = asksaveasfilename(filetypes=(('text files','*.txt'),('PY files','*.py'),('All files','*.*')))\n if fiol=='':\n showinfo(\"Error\",\"Please give a file\")\n else:\n fio = open(fiol,'w')\n fio.write(text.get(1.0,END))\n fio.close()\n else:\n fiol = open(file,'w')\n fiol.write(text.get(1.0,END))\n fiol.close()\n\ndef runfilelocal():\n if file == None:\n fiol = open('runnnning.py','w')\n fiol.write(text.get(1.0,END))\n fiol.close()\n os.system('runnnning.py')\n else:\n fiol = open(file,'w')\n fiol.write(text.get(1.0,END))\n fiol.close()\n os.system(f\"\\\"{file}\\\"\")\n\n# our components\nframe = Frame(\n root,\n bg='black'\n) \ntext = Text(\n root,\n bg=\"#002\",\n wrap=WORD,\n foreground='cyan',\n font=(\"consolas\",12,'BOLD'.lower()),\n insertbackground=\"white\"\n)\nbtn1 = Button(\n frame,\n fg='white',\n bg='#000000',\n text='open',\n command=openFile\n)\nbtn2 = Button(\n frame,\n fg='white',\n text='save',\n bg='#000000',\n command=saveFile\n)\nbtn3 = Button(\n frame,\n fg='white',\n bg='#000000',\n text='About',\n command=lambda:showinfo('About','Created by ratul Banerjee')\n)\nbtn4 = Button(\n frame,\n fg='white',\n bg='#000000',\n text='Run',\n command=runfilelocal\n)\nbtn5 = Button(\n frame,\n bg='#000000',\n fg='white',\n text='exit',\n command=lambda:root.destroy()\n)\n\n\n# packing the components\nbtn1.pack(side=LEFT)\nbtn2.pack(side=LEFT)\nbtn3.pack(side=LEFT)\nbtn4.pack(side=LEFT)\nbtn5.pack(side=LEFT)\nframe.pack(anchor='nw',padx=5,pady=5)\ntext.pack(expand=True,fill=BOTH)\n\n\n# adding syntax highlight\ncdg = ic.ColorDelegator()\ncdg.prog = re.compile(r'\\b(?Ptkinter)\\b|' + ic.make_pat(), re.S)\ncdg.idprog = re.compile(r'\\s+(\\w+)', re.S)\n\ncdg.tagdefs['MYGROUP'] = {'foreground': '#7F7F7F', 'background': '#002'}\n\n# These five lines are optional. If omitted, default colours are used.\ncdg.tagdefs['COMMENT'] = {'foreground': '#FF0000', 'background': '#002'}\ncdg.tagdefs['KEYWORD'] = {'foreground': '#007F00', 'background': '#002'}\ncdg.tagdefs['BUILTIN'] = {'foreground': '#7F7F00', 'background': '#002'}\ncdg.tagdefs['STRING'] = {'foreground': 'yellow', 'background': '#002'}\ncdg.tagdefs['DEFINITION'] = {'foreground': '#007F7F', 'background': '#002'}\n\nip.Percolator(text).insertfilter(cdg)\n\nroot.mainloop()","repo_name":"DIGITAL-WORLD-ULTRA/Python-IDE","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"73629782519","text":"class ShardInfo(object):\n\n def __init__(self, defaultShardNumber=None, defaultShardClass=None, shardNumberList=None, ipNumberList=None):\n \"\"\"\n :param defaultShardNumber: (Optional) 默认分片数\n :param defaultShardClass: (Optional) 默认单分片规格代码\n :param shardNumberList: (Optional) 分片数列表\n :param ipNumberList: (Optional) 需要的IP数列表\n \"\"\"\n\n self.defaultShardNumber = defaultShardNumber\n self.defaultShardClass = defaultShardClass\n self.shardNumberList = shardNumberList\n self.ipNumberList = ipNumberList\n","repo_name":"jdcloud-api/jdcloud-sdk-python","sub_path":"jdcloud_sdk/services/redis/models/ShardInfo.py","file_name":"ShardInfo.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"40"} +{"seq_id":"20435809872","text":"# coding: utf-8\nimport numpy as np\nimport torch\nclass ReplayMemory(object):\n def __init__(self, args):\n self.size = args.replay_size\n self.hist_len = args.hist_len\n self.priority = args.priority\n self.state_beta_dim = args.state_dim\n self.state_alpha_dim = args.state_dim + args.image_padding * 2\n self.batch_size = args.batch_size\n self.reward_bound = args.reward_bound\n self.positive_rate = args.positive_rate\n self.count = 0\n self.current = 0\n self.device = args.device_type\n self.actions = np.zeros(self.size, dtype=np.uint8)\n self.rewards = np.zeros(self.size, dtype=np.float32)\n self.states_alpha = np.zeros([self.size, self.state_alpha_dim, self.state_alpha_dim], dtype=np.uint8)\n self.states_beta = np.zeros([self.size, self.state_beta_dim, self.state_beta_dim], dtype=np.uint8)\n self.terminals = np.zeros(self.size, dtype=np.bool)\n\n\n def reset(self):\n print('Reset the replay memory')\n self.actions *= 0\n self.rewards *= 0.0\n self.states_beta *= 0\n self.states_alpha *= 0\n self.terminals *= False\n self.count = 0\n self.current = 0\n\n \n def add(self, action, reward, state_alpha, state_beta, terminal):\n #assert state.shape == self.dims\n self.actions[self.current] = action\n self.rewards[self.current] = reward\n self.states_alpha[self.current] = state_alpha[0, -1]\n self.states_beta[self.current] = state_beta[0, -1]\n self.terminals[self.current] = terminal\n self.count = max(self.count, self.current + 1) \n self.current = (self.current + 1) % self.size\n\n\n def getMinibatch(self):\n pre_states_beta = np.zeros([self.batch_size, self.hist_len, self.state_beta_dim, self.state_beta_dim])\n pre_states_alpha = np.zeros([self.batch_size, self.hist_len, self.state_alpha_dim, self.state_alpha_dim])\n post_states_beta = np.zeros([self.batch_size, self.hist_len, self.state_beta_dim, self.state_beta_dim])\n post_states_alpha = np.zeros([self.batch_size, self.hist_len, self.state_alpha_dim, self.state_alpha_dim])\n if self.priority:\n # 择优回放。经验回放时,选取一组经验同时训练,pos_amount表示该组中,reward>reward_bound的经验元素的个数。\n pos_amount = int(self.positive_rate*self.batch_size) \n\n indices = []\n count_pos = 0\n count_neg = 0\n count_all = 0\n count_ter = 0\n max_circles = 1000 # 在开启priority时,最大选择次数\n while len(indices) < self.batch_size:\n \n while True:\n # 从随机下标开始\n index = np.random.randint(self.hist_len+1, self.count)\n if self.priority:\n if count_all < max_circles:\n # 如果已经满足num_pos,但是当前记录仍是positive,则continue\n if (count_pos >= pos_amount) and (self.rewards[index] >= self.reward_bound):\n count_all += 1\n continue\n # negitive亦然\n elif (count_neg >= self.batch_size - pos_amount) and (self.rewards[index] < self.reward_bound): \n count_all += 1\n continue\n if self.rewards[index] >= self.reward_bound:\n count_pos += 1\n else:\n count_neg += 1\n break\n \n for i in range(1, self.hist_len + 1):\n if self.terminals[index - i]: # 只有在当前地图的最后一条记录才能被设为terminal\n break\n cur_ind = self.hist_len - i\n pre_states_alpha[len(indices)][cur_ind] = self.states_alpha[index - i]\n pre_states_beta[len(indices)][cur_ind] = self.states_beta[index - i]\n post_states_alpha[len(indices)][cur_ind] = self.states_alpha[index - i + 1]\n post_states_beta[len(indices)][cur_ind] = self.states_beta[index - i + 1]\n indices.append(index)\n\n # copy\n actions = self.actions[indices] \n rewards = self.rewards[indices]\n terminals = self.terminals[indices]\n pre_states_alpha = torch.Tensor(pre_states_alpha).to(self.device)\n pre_states_beta = torch.Tensor(pre_states_beta).to(self.device)\n rewards = torch.Tensor(rewards).to(self.device)\n post_states_alpha = torch.Tensor(post_states_alpha).to(self.device)\n post_states_beta = torch.Tensor(post_states_beta).to(self.device)\n terminals = torch.Tensor(terminals).to(self.device)\n\n\n return pre_states_alpha, pre_states_beta, actions, rewards, post_states_alpha, post_states_beta, terminals\n","repo_name":"BobbyBBY/EFDRL","sub_path":"replay_memory.py","file_name":"replay_memory.py","file_ext":"py","file_size_in_byte":4910,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"40"} +{"seq_id":"9906835080","text":"\"\"\"Program to store list of strings and output it right-aligned with the longest string\r\nPankaj Munbodh\r\n20 April 2014\"\"\"\r\n#Create list of strings\r\nstr_list=[]\r\nget_string = input(\"Enter strings (end with DONE):\\n\")\r\nif get_string !='DONE':\r\n str_list.append(get_string)\r\n\r\n\r\n#sentinel loop keeps asking for input until user enters'DONE'\r\n while (get_string=='DONE')==False:\r\n get_string = input(\"\")\r\n if get_string!='DONE':\r\n str_list.append(get_string)\r\n\r\n#Width of character of maximum length is found \r\n width=max(len(word) for word in str_list)\r\n\r\n print()\r\n print(\"Right-aligned list:\")\r\n\r\n#List is iterated through and each character is printed right-justified in field width of maximum with found earlier\r\n for word in str_list:\r\n print(word.rjust(width))\r\n#output for exception\r\nelse:\r\n print() \r\n print(\"Right-aligned list:\") # if-else statement to cater for exception if user types in \"DONE\" right at start","repo_name":"MrHamdulay/csc3-capstone","sub_path":"examples/data/Assignment_6/mnbpan001/question1.py","file_name":"question1.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"29251187348","text":"import django.utils.functional\nfrom django.db import models\nimport django.forms\n\n\nclass BitcoinField(models.DecimalField):\n def __init__(self, *args, **kwargs):\n super(BitcoinField, self).__init__(*args, **kwargs)\n self.decimal_places = 8\n self.max_digits = 16\n self.default = 0\n\n\nclass RoundingDecimalField(models.DecimalField):\n def __init__(self, *args, **kwargs):\n super(models.DecimalField, self).__init__(*args, **kwargs)\n self.decimal_places = 6\n self.max_digits = 10\n self.default = 0\n\n @django.utils.functional.cached_property\n def validators(self):\n return super(models.DecimalField, self).valdators\n\n def formfield(self, **kwargs):\n defaults = {\n 'max_digits': self.max_digits,\n 'decimal_places': 6,\n 'form_class': django.forms.DecimalField,\n }\n defaults.update(kwargs)\n return super(RoundingDecimalField, self).formfield(**defaults)\n","repo_name":"davidkernell/baltar","sub_path":"custom_fields.py","file_name":"custom_fields.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"70893219000","text":"import os\nimport time\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom shared_constants import EVALUATION_SEEDS, VIDEO_SEEDS\nfrom . import buffers, wrapper, plots\nfrom .model import DuelingDQN\n\n\nclass Agent:\n def __init__(self, env_name, args):\n self.env_name = env_name\n self.env, self.eval_env = wrapper.get_env(env_name, args.bins, agent=Agent)\n\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n self.model = DuelingDQN(\n self.env.observation_space.shape, self.env.n, noisy=args.noisy\n ).to(self.device)\n self.target_model = DuelingDQN(\n self.env.observation_space.shape, self.env.n, noisy=args.noisy\n ).to(self.device)\n self.target_model.load_state_dict(self.model.state_dict())\n\n self.optimizer = optim.Adam(self.model.parameters(), lr=args.learning_rate)\n self.loss = nn.MSELoss(reduction=\"none\")\n\n self.gamma = args.gamma\n self.batch_size = args.batch_size\n\n self.eps_start = args.initial_epsilon\n self.eps_end = args.final_epsilon\n self.eps_decay = args.decay_rate\n\n self.target_update = args.target_update\n self.replay_episodes = args.replay_episodes\n\n self.num_episodes = args.num_episodes\n self.episode_length = args.episode_length\n self.episode_continue = 0\n self.prioritize = args.prioritize\n\n if self.prioritize:\n self.replay_buffer = buffers.PrioritizedReplayBuffer(\n args.replay_memory_size,\n prob_alpha=args.prob_alpha,\n beta=args.beta_start,\n )\n self.beta = np.linspace(args.beta_start, 1.0, args.num_episodes)\n else:\n self.replay_buffer = buffers.ReplayBuffer(args.replay_memory_size)\n\n self.test_rewards = []\n self.test_wlt = []\n print(self.prioritize)\n print(args.noisy)\n\n def decay_epsilon(self):\n self.eps_start = max(self.eps_end, self.eps_start * self.eps_decay)\n\n def compute_loss(self, batch, weights=None):\n states, actions, rewards, next_states, dones = batch\n states = torch.FloatTensor(states).to(self.device)\n actions = torch.LongTensor(actions).to(self.device)\n rewards = torch.FloatTensor(rewards).to(self.device)\n next_states = torch.FloatTensor(next_states).to(self.device)\n dones = torch.FloatTensor(dones).to(self.device)\n\n curr_q = self.model.forward(states).gather(1, actions.unsqueeze(1)).squeeze(1)\n greedy_actions = self.model.forward(next_states).argmax(dim=1)\n next_q = (\n self.target_model.forward(next_states)\n .gather(1, greedy_actions.unsqueeze(1))\n .squeeze(1)\n )\n\n expected_q = rewards + (1.0 - dones) * self.gamma * next_q\n expected_q_for_td_error = (\n rewards\n + (1.0 - dones)\n * self.gamma\n * self.target_model.forward(next_states).max(dim=1)[0]\n )\n # If weights are not provided (i.e., when using the simple replay buffer)\n if weights is None:\n loss = self.loss(curr_q, expected_q).mean()\n return loss, None # Here we return None for the TD errors\n\n # Compute TD errors for updating priorities\n td_errors = (\n torch.abs(curr_q - expected_q_for_td_error).detach().cpu().numpy() + 1e-6\n )\n\n # Compute the weighted loss\n weights = torch.FloatTensor(weights).to(self.device)\n loss = (weights * self.loss(curr_q, expected_q)).mean()\n return loss, td_errors\n\n def update(self, batch_size, prioritize=False):\n if prioritize:\n batch, indices, weights = self.replay_buffer.sample(\n batch_size, beta=self.beta[self.episode_continue]\n )\n else:\n batch = self.replay_buffer.sample(batch_size)\n indices, weights = None, None\n\n loss, td_errors = self.compute_loss(batch, weights)\n\n self.optimizer.zero_grad()\n loss.backward()\n torch.nn.utils.clip_grad_norm_(self.model.parameters(), 1.0)\n self.optimizer.step()\n\n # Update priorities in the buffer\n if prioritize:\n self.replay_buffer.update_priorities(indices, td_errors)\n\n def act(self, state, eps=None):\n if eps is None:\n eps = self.eps_start\n\n # Epsilon-greedy action selection\n if np.random.random() > eps:\n with torch.no_grad():\n state = torch.FloatTensor(state).to(self.device)\n action = self.model(state).argmax().item()\n else:\n action = self.env.sample_action()\n\n return action\n\n def save_checkpoint(self, filename, episode):\n folder = f\"checkpoints/{self.env_name}\"\n os.makedirs(folder, exist_ok=True)\n filename = f\"{folder}/{filename}\"\n checkpoint = {\n \"env_name\": self.env_name,\n \"state_dict\": self.model.state_dict(),\n \"optimizer\": self.optimizer.state_dict(),\n \"episode\": episode,\n \"epsilon\": self.eps_start,\n }\n torch.save(checkpoint, filename)\n print(f\"Checkpoint saved to {filename}\")\n\n def load_checkpoint(self, filename, only_network=False):\n checkpoint = torch.load(filename)\n if only_network:\n self.model.load_state_dict(checkpoint[\"state_dict\"])\n self.target_model.load_state_dict(checkpoint[\"state_dict\"])\n return\n self.optimizer.load_state_dict(checkpoint[\"optimizer\"])\n self.eps_start = checkpoint[\"epsilon\"]\n self.episode_continue = checkpoint[\"episode\"]\n print(f\"Checkpoint loaded from {filename}\")\n\n def evaluate(self):\n self.model.eval()\n mean_rewards = []\n\n if \"Hockey\" in self.env_name:\n wins_counter = 0\n loose_counter = 0\n tie_counter = 0\n\n for seed in EVALUATION_SEEDS:\n self.eval_env.seed(seed)\n video_this_seed = seed in VIDEO_SEEDS\n state, _ = self.eval_env.reset()\n total_reward = 0\n episode_length_counter = 0\n\n while True:\n action = (\n self.model(torch.FloatTensor(state).to(self.device)).argmax().item()\n )\n next_state, reward, done, trunk, info = self.eval_env.step(\n action, eval=True\n )\n total_reward += reward\n state = next_state\n end = (episode_length_counter == self.episode_length) or done or trunk\n if video_this_seed:\n self.eval_env.make_video(\n end, episode_length_counter, self.episode_continue, seed\n )\n if end:\n break\n episode_length_counter += 1\n mean_rewards.append(total_reward)\n\n if \"Hockey\" in self.env_name:\n if info[\"winner\"] == 0:\n tie_counter += 1\n elif info[\"winner\"] == 1:\n wins_counter += 1\n else:\n loose_counter += 1\n print(f\"\\n MEAN EVAL REWARDS: {np.mean(mean_rewards)} \\n \")\n if \"Hockey\" in self.env_name:\n print(wins_counter, loose_counter, tie_counter)\n print(f\"\\n WINS: {100 * wins_counter / len(EVALUATION_SEEDS)} % \\n \")\n print(f\"\\n LOOSES: {100 * loose_counter/ len(EVALUATION_SEEDS)} % \\n \")\n print(f\"\\n TIES: {100 * tie_counter/ len(EVALUATION_SEEDS)} % \\n \")\n self.test_wlt.append([wins_counter, loose_counter, tie_counter])\n plots.dump_array(\n self.test_wlt,\n path=f\"plots/{self.env_name}\",\n filename=\"test_wins_losses_ties.pkl\",\n )\n self.test_rewards.append(mean_rewards)\n plots.dump_array(\n self.test_rewards,\n path=f\"plots/{self.env_name}\",\n filename=\"test_rewards.pkl\",\n )\n self.model.train()\n\n def replay(self, replay_episodes=5):\n for _ in range(replay_episodes):\n self.update(self.batch_size, self.prioritize)\n\n def train(self):\n if \"Hockey\" in self.env_name:\n wins = [0]\n losses = [0]\n ties = [0]\n episodes_rewards = []\n times = []\n for episode in range(self.episode_continue, self.num_episodes):\n start_time = time.time()\n state, _ = self.env.reset()\n total_reward = 0\n episode_length_counter = 0\n while True:\n action = self.act(state)\n next_state, reward, done, trunk, info = self.env.step(action)\n total_reward += reward\n self.replay_buffer.push(state, action, reward, next_state, done)\n state = next_state\n\n if (episode_length_counter == self.episode_length) or done or trunk:\n break\n episode_length_counter += 1\n\n if episode > 10:\n # just ignore the first 10 episodes to fill the buffer\n self.replay(self.replay_episodes)\n self.decay_epsilon()\n\n if episode % self.target_update == 0:\n self.target_model.load_state_dict(self.model.state_dict())\n\n end_time = time.time() # End timer after the episode\n episode_duration = end_time - start_time\n times.append(episode_duration)\n\n print(f\"Reward for current episode {episode}: \", total_reward)\n print(\"Epsilon: \", self.eps_start)\n\n episodes_rewards.append(total_reward)\n\n if done and \"Hockey\" in self.env_name:\n ties.append(info[\"winner\"] == 0)\n wins.append(info[\"winner\"] == 1)\n losses.append(info[\"winner\"] == -1)\n\n self.episode_continue = episode\n if episode % 250 == 0:\n self.save_checkpoint(\n f\"checkpoint_{episode}_{self.env_name}.pth\", episode\n )\n self.evaluate()\n\n if episode % 50 == 0:\n plots.plot_rewards(episodes_rewards, path=f\"plots/{self.env_name}\")\n plots.plot_episode_duration(times, path=f\"plots/{self.env_name}\")\n plots.dump_array(episodes_rewards, path=f\"plots/{self.env_name}\")\n\n if \"Hockey\" in self.env_name:\n plots.plot_hockey(wins, losses, ties, path=f\"plots/{self.env_name}\")\n\n print(\"Training completed.\")\n","repo_name":"kortukov/the_copilots","sub_path":"dueling_dqn/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":10706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"28218953652","text":"from typing import Dict, List, Union\n\nfrom catalyst.core import MetricCallback\n\n\nclass CrfNllCallback(MetricCallback):\n \"\"\"\n Callback to compute KL divergence loss\n \"\"\"\n\n def __init__(\n self,\n input_key: Union[str, List[str], Dict[str, str]] = None,\n output_key: Union[str, List[str], Dict[str, str]] = None,\n prefix: str = \"crf_cll_loss\",\n multiplier: float = 1.0,\n temperature: float = 1.0,\n **metric_kwargs,\n ):\n \"\"\"\n Args:\n input_key (Union[str, List[str], Dict[str, str]]): key/list/dict\n of keys that takes values from the input dictionary\n If '__all__', the whole input will be passed to the criterion\n If None, empty dict will be passed to the criterion.\n output_key (Union[str, List[str], Dict[str, str]]): key/list/dict\n of keys that takes values from the input dictionary\n If '__all__', the whole output will be passed to the criterion\n If None, empty dict will be passed to the criterion.\n prefix (str): prefix for metrics and output key for loss\n in ``state.batch_metrics`` dictionary\n multiplier (float): scale factor for the output loss.\n temperature (float): temperature for distributions\n \"\"\"\n\n super().__init__(\n prefix=prefix,\n input_key=input_key,\n output_key=output_key,\n multiplier=multiplier,\n metric_fn=self.metric_fn,\n **metric_kwargs,\n )\n\n def metric_fn(\n self,\n x,\n x_chars,\n targets,\n crf_nll\n ):\n \"\"\"\n Computes KL divergence loss for given distributions\n Args:\n s_logits: tensor shape of (batch_size, seq_len, voc_size)\n t_logits: tensor shape of (batch_size, seq_len, voc_size)\n attention_mask: tensor shape of (batch_size, seq_len, voc_size)\n Returns:\n KL loss\n \"\"\"\n\n return crf_nll(x, x_chars, targets)\n\n def __call__(self,\n input,\n output\n ):\n\n x, x_chars, targets, crf_nll = input\n #crf_nll = output\n return self.metric_fn(x,\n x_chars,\n targets, crf_nll)\n","repo_name":"Danko711/config_ner","sub_path":"callbacks/nll_loss.py","file_name":"nll_loss.py","file_ext":"py","file_size_in_byte":2420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"23678946438","text":"import openai\nimport os\nimport urllib.parse\nx=input(\"Enter Language you want to learn\")\nconversation_history=[]\n\n\nopen_ai_api_key=\"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\"\nopenai.api_key=open_ai_api_key\n# file= openai.File.create(\n# file=open(\"test.jsonl\", \"rb\"),\n# purpose='fine-tune'\n# ) \n# openai.FineTuningJob.create(training_file=file.id, model=\"gpt-3.5-turbo\")\n# #completion=openai.ChatCompletion.create(model=\"gpt-3.5-turbo\", messages=[{\"role\": \"system\", \"content\": \"You are a poetic assistant, skilled in explaining complex\"}, {\"role\": \"user\", \"content\": user_text}])\nwhile True:\n user_text=input(\"Type your question for the bot\")\n completion = openai.ChatCompletion.create(\n model=\"ft:gpt-3.5-turbo-0613:personal::8CWguB4V\",\n messages=[{\"role\": \"system\", \"content\": f\"You are designed to help the user learn {x}. You converse with the user in {x} talking about food. If the user makes a mistake you correct them and continue talking in the conversation with them.\"}, {\"role\": \"user\", \"content\": user_text}]\n )\n #print(completion.choices[0].message)\n\n if completion is not None: \n decoded_response = urllib.parse.unquote(completion.choices [0]. message. content)\n print (decoded_response)\n conversation_history.append(user_text)\n conversation_history.append(decoded_response)\n else: \n print(\"Error creating or sending OpenAI ChatCompletion request.\")\n\n\n\n\n\n","repo_name":"mattwalter2/Converso","sub_path":"hacky.py","file_name":"hacky.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"30892316000","text":"\n# coding: utf-8\n\n# In[1]:\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport json\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\n# In[2]:\n\n\nlines=[]\npos_num=0\nneg_num=0\nnum_total=140000\n\nwith open('../yelp_dataset/yelp_academic_dataset_review.json', 'r') as f:\n for line in f:\n json_data=json.loads(line)\n \n if json_data['stars']>3:\n if pos_num>num_total:\n continue\n pos_num+=1\n elif json_data['stars']<3:\n if neg_num>num_total:\n continue\n neg_num+=1\n else:\n continue\n \n lines.append(json_data) \n \n\n\n# In[3]:\n\n\nreview=pd.DataFrame(lines)\nprint(review.head())\n\n\n# In[4]:\n\n\nreview['sentiment']=(review['stars']>3).astype(int)\n\n\n# In[5]:\n\n\nprint('some examples of reviews')\nprint(review['text'][0])\nprint('\\n')\nprint(review['text'][10])\n\n\n# In[8]:\n\n\n#data cleanning:\n#expand contractions\n#remove non alphabert words (punctuations, special characters such as @,# etc)\n#lower case everything\n#remove stopwords\n\nprint('start cleaning')\nimport contractions\nimport re\nimport nltk\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\n\ndef clean(doc):\n \n doc=contractions.fix(doc)\n \n pattern_to_find = \"[^a-zA-Z0-9' ]\";\n pattern_to_repl = \" \";\n doc=re.sub(pattern_to_find, pattern_to_repl, doc).lower()\n \n eng_stopwords = set(stopwords.words(\"english\"))-{'not','no'};\n sentence = ' '.join(word for word in doc.split() if word not in eng_stopwords)\n \n return sentence \n\n\n# In[9]:\n\n\nprint(clean('I\\'ve got a nanny##@@'))\n\n\n# In[10]:\n\n\nreview['clean_text']=review['text'].apply(clean)\n\n\n# In[11]:\n\n\nprint(review.head())\n\n\n# Words can't be directly fed into the model, instead we need to encode each word to a unique numerical value. Therefore a review is transformed from being an array of words to an array of integer values.\n# \n\n# In[12]:\n\n\nprint('sentence length analysis')\ndef lenth(sentence):\n return len(sentence.split(' '))\nreview['len']=review['clean_text'].apply(lenth)\n\n\n# In[13]:\n\n\nax=review['len'].plot.hist(bins=100)\nax.set_xlim([0,150])\nplt.savefig('length_distri.png')\nprint('done cleaning')\nsave=review[['text','clean_text','sentiment']]\nsave.to_csv('./review.csv')\n\n# It seems that 20-60 is the most common length. We can choose to cap at 60 words for our model.\n","repo_name":"phoenixdeng2012/Yelp_Review_Sentiment_Analysis","sub_path":"models/cleaning_data.py","file_name":"cleaning_data.py","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"29588069439","text":"from time import time\nimport SimpleHTTPServer\nimport SocketServer\n\n\ndef elapsed_time(_since=time()):\n return time() - _since\n\n\nclass SillyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):\n def do_GET(self):\n if elapsed_time() < 45:\n self.send_error(503)\n else:\n self.send_response(200)\n self.end_headers()\n self.wfile.write(b'

Foo bar

')\n\nhttpd = SocketServer.TCPServer(('localhost', 8000), SillyHandler)\nprint('Serving http://{addr[0]}:{addr[1]}/'.format(addr=httpd.socket.getsockname()))\ntry:\n httpd.serve_forever()\nexcept KeyboardInterrupt:\n print('\\nKeyboard interrupt received, exiting.')\n httpd.socket.close()\n","repo_name":"esacteksab/homework","sub_path":"webserver.py","file_name":"webserver.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"9437537827","text":"# --------------\n# multiAgents.py\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n#\n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n\nfrom math import exp, expm1, factorial, ceil, fabs\nfrom util import manhattanDistance\nfrom game import Directions\nimport random, util\nimport util\nfrom game import Directions\nfrom game import Agent\nfrom game import Actions\nimport time\n\nfrom game import Agent\n\nclass ReflexAgent(Agent):\n \"\"\"\n A reflex agent chooses an action at each choice point by examining\n its alternatives via a state evaluation function.\n\n The code below is provided as a guide. You are welcome to change\n it in any way you see fit, so long as you don't touch our method\n headers.\n \"\"\"\n\n\n def getAction(self, gameState):\n \"\"\"\n You do not need to change this method, but you're welcome to.\n\n getAction chooses among the best options according to the evaluation function.\n\n Just like in the previous project, getAction takes a GameState and returns\n some Directions.X for some X in the set {North, South, West, East, Stop}\n \"\"\"\n # Collect legal moves and successor states\n legalMoves = gameState.getLegalActions()\n\n # Choose one of the best actions\n scores = [self.evaluationFunction(gameState, action) for action in legalMoves]\n bestScore = max(scores)\n bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]\n chosenIndex = random.choice(bestIndices) # Pick randomly among the best\n\n \"Add more of your code here if you want to\"\n\n return legalMoves[chosenIndex]\n\n def evaluationFunction(self, currentGameState, action):\n \"\"\"\n Design a better evaluation function here.\n\n The evaluation function takes in the current and proposed successor\n GameStates (pacman.py) and returns a number, where higher numbers are better.\n\n The code below extracts some useful information from the state, like the\n remaining food (newFood) and Pacman position after moving (newPos).\n newScaredTimes holds the number of moves that each ghost will remain\n scared because of Pacman having eaten a power pellet.\n\n Print out these variables to see what you're getting, then combine them\n to create a masterful evaluation function.\n \"\"\"\n # Useful information you can extract from a GameState (pacman.py)\n successorGameState = currentGameState.generatePacmanSuccessor(action)\n newPos = successorGameState.getPacmanPosition()\n\n grindaComida = successorGameState.getFood()\n newGhostStates = successorGameState.getGhostStates()\n newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates]\n\n \"*** YOUR CODE HERE ***\"\n def calculation(num1, num2, num3):\n return num2 + num3 - num1\n posicion_nueva = newPos\n novaMaloEst = newGhostStates\n decisions = []\n #siguiente_mode = [newFood, decisions[:]]\n #grindaComida = action[1]\n #unComiDon = grindaComida.asList()\n empieze = 0\n #puntas_sando = state[empieze+1]\n visitanteRoc = util.Queue()\n visitanteRoc.push(grindaComida)\n p1 = action[1]\n val = \"Function De Evaluation\"\n num = 0\n powerz = lambda pol: ceil( factorial(pol**2) )\n ellocation = powerz(10)\n limit = powerz(10)#89898\n cuanto_lejos_malo = 10**2 * 10 * -1 #divided for understanding\n display = util.Queue();\n p2 = action[2]\n fraction = (1/10) * (-1)\n counter = 0\n g = 0\n while ( (display.isEmpty() or counter < limit) and not visitanteRoc.isEmpty() ):\n for son in novaMaloEst:\n temp = manhattanDistance(posicion_nueva, son.getPosition())\n if (g == 0 or temp < counter):\n counter = temp\n visitanteRoc.push(counter)\n g = g + 1\n elif g < 0:\n p1 = visitanteRoc.pop()\n else:\n display.push(p1)\n while not visitanteRoc.isEmpty():\n visitanteRoc.pop()\n display.push(counter)\n malo_cerca = counter\n\t #testprint malo_cerca\n minus_ten = -10\n if g>=0 and malo_cerca:\n cuanto_lejos_malo = (1/malo_cerca) * minus_ten\n com_lista = grindaComida.asList()\n counter = 0#ellocation #represents minimum valor\n g = 0\n if grindaComida.asList():\n while ( (visitanteRoc.isEmpty() or counter < limit) and not display.isEmpty() ):\n for ceo in grindaComida.asList():\n temp = manhattanDistance(newPos, ceo)\n if (g == 0 or temp < counter):\n counter = temp\n g = g + 1\n display.push(counter)\n elif g < 0:\n p1 = display.pop()\n else:\n visitanteRoc.push(p1)\n #if not display.isEmpty():\n # display.pop()\n while not display.isEmpty():\n display.pop()\n cerca_comida = counter\n result1 = len(com_lista) * 50 + num\n result2 = cerca_comida * 2 * -1\n return result2 + cuanto_lejos_malo - result1\n if(display.isEmpty()):\n return result2 + cuanto_lejos_malo - result1\n return None\n #return calculation(result2,result2,cuanto_lejos_malo)\n #return successorGameState.getScore()\n\ndef scoreEvaluationFunction(currentGameState):\n \"\"\"\n This default evaluation function just returns the score of the state.\n The score is the same one displayed in the Pacman GUI.\n\n This evaluation function is meant for use with adversarial search agents\n (not reflex agents).\n \"\"\"\n return currentGameState.getScore()\n\nclass MultiAgentSearchAgent(Agent):\n \"\"\"\n This class provides some common elements to all of your\n multi-agent searchers. Any methods defined here will be available\n to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent.\n\n You *do not* need to make any changes here, but you can if you want to\n add functionality to all your adversarial search agents. Please do not\n remove anything, however.\n\n Note: this is an abstract class: one that should not be instantiated. It's\n only partially specified, and designed to be extended. Agent (game.py)\n is another abstract class.\n \"\"\"\n\n def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'):\n self.index = 0 # Pacman is always agent index 0\n self.evaluationFunction = util.lookup(evalFn, globals())\n self.depth = int(depth)\n\nclass MinimaxAgent(MultiAgentSearchAgent):\n \"\"\"\n Your minimax agent (question 2)\n \"\"\"\n\n def getAction(self, gameState):\n empieze = 1\n \"\"\"\n Returns the minimax action from the current gameState using self.depth\n and self.evaluationFunction.\n\n Here are some method calls that might be useful when implementing minimax.\n\n gameState.getLegalActions(agentIndex):\n Returns a list of legal actions for an agent\n agentIndex=0 means Pacman, ghosts are >= 1\n\n gameState.generateSuccessor(agentIndex, action):\n Returns the successor game state after an agent takes an action\n\n gameState.getNumAgents():\n Returns the total number of agents in the game\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n yo=self\n display = util.Queue()\n juego_est = gameState\n display.push(yo.depth)\n return (yo.el_faximo(juego_est,yo.depth))[empieze]\n \"\"\"\n arr = []\n for value in gameState.getLegalActions(0):\n arr.append( adSearch(gameState.generateSuccessor(0, value), 1, 1) )\n first = arr[0]\n for elem in arr:\n if first < elem:\n first = elem\n max=first\"\"\"\n #util.raiseNotDefined()\n\n def el_faximo(yo,juego_estado,depth):\n decisions = []\n empieze = 0\n #error = yo.evaluationFunction(gameState), \"ineffectivo movimiento partition tested shown\"\n visitanteRoc = util.Queue()\n visitanteRoc.push(juego_estado)\n p1 = depth\n nag = juego_estado.isWin()\n display = util.Stack();\n osLeg = juego_estado.isLose()\n #if gameState.isLose():\n # return error\n val = \"Function Fax\"\n num = 0\n num1 = 1\n powerz = lambda pol: ceil( factorial(pol**2) )\n ellocation = powerz(10)\n limit = powerz(10)#898980\n if not display.isEmpty() or empieze == depth or nag or limit > powerz(num+12) or osLeg:\n power = powerz(powerz(num))\n #print 'falla portu next time monte, game'+str(power)\n return yo.evaluationFunction(juego_estado), \"ineffectivo movimiento partition tested shown\"\n elif (not display.isEmpty() and depth < 0):\n return None\n else:\n #cuanto_lejos_malo = 10**2 * 10 * -1 #divided for understanding\n #if(empieze==depth):\n # return error;\n p2 = (1/10) * (-1)\n counter = 0\n g = 0\n possibilidadesdemov=juego_estado.getLegalActions()\n apuntaje = []\n #depth!=p1\n if(display.isEmpty()):\n while(len(apuntaje) < len(possibilidadesdemov)):\n for queMonteWey in possibilidadesdemov:\n lista = ( juego_estado.generateSuccessor(yo.index,queMonteWey) )\n apuntaje.append ( yo.el_finimo(lista,num1, depth) )\n while ( (display.isEmpty() or counter < limit) and not visitanteRoc.isEmpty() ):\n for temp in apuntaje:\n if (g == 0 or temp > counter):\n counter = temp\n visitanteRoc.push(counter)\n g = g + num1\n elif g < 0:\n p1 = visitanteRoc.pop()\n else:\n display.push(p1)\n while not visitanteRoc.isEmpty():\n visitanteRoc.pop()\n lodelargo = len(apuntaje)# + num#int(powerz(empieze)) - num1\n display.push(counter)\n for valor in range(lodelargo):\n if apuntaje[valor] == counter:\n decisions.append(valor)\n elif(not visitanteRoc.isEmpty()):\n return None\n else:\n if not visitanteRoc.isEmpty():\n visitanteRoc.pop()\n #return None\n sop = possibilidadesdemov[decisions[empieze]]\n if(not visitanteRoc.isEmpty()):\n sop = None\n return Exception, \"Structure Empty Fault Failure\"\n return display.pop(), sop\n #masonmio meomo (apuntaje)\n\n def el_finimo(yo,juego_estado,personaje, depth):\n decisions = []\n empieze = 0\n visitanteRoc = util.Queue()\n visitanteRoc.push(juego_estado)\n length = juego_estado.getNumAgents()\n p1 = depth\n nag = juego_estado.isWin()\n display = util.Stack();\n osLeg = juego_estado.isLose()\n val = \"Function Fin\"\n num = 1\n apuntaje=[]\n powerz = lambda pol: ceil( factorial(pol**2) )\n ellocation = powerz(10)\n limit = powerz(10)#89898\n if not display.isEmpty() or empieze == depth or nag or limit > powerz(num+12) or osLeg:\n power = powerz(powerz(num))\n #print 'falla portu next time monte, game'+str(power)\n return yo.evaluationFunction(juego_estado), \"ineffectivo movimiento partition tested shown\"\n elif (not display.isEmpty() and depth < 0):\n return None\n else:\n #cuanto_lejos_malo = 10**2 * 10 * -1 #divided for understanding\n p2 = (1/13) * (-1)\n counter = 0\n g = 0\n possibilidadesdemov=juego_estado.getLegalActions(personaje) #get legal actions.\n if( (length-1) != personaje and display.isEmpty()):\n while(len(apuntaje) < len(possibilidadesdemov)):\n for queMonteWey in possibilidadesdemov:\n lista = ( juego_estado.generateSuccessor(personaje,queMonteWey) )\n apuntaje.append (yo.el_finimo(lista,personaje+num,depth))\n #display.push(apuntaje)\n elif(not display.isEmpty()):\n return None\n else:\n while(len(apuntaje) < len(possibilidadesdemov)):\n for queMonteWey in possibilidadesdemov:\n lista = ( juego_estado.generateSuccessor(personaje,queMonteWey) )\n apuntaje.append (yo.el_faximo(lista,(depth-num))[empieze] )\n #visitanteRoc.push(apuntaje)\n\n while ( (display.isEmpty() or counter < limit) and not visitanteRoc.isEmpty() ):\n for temp in apuntaje:\n if (g == 0 or temp < counter):\n counter = temp\n visitanteRoc.push(counter)\n g = g + 1\n elif g < 0:\n p1 = visitanteRoc.pop()\n else:\n display.push(p1)\n while not visitanteRoc.isEmpty():\n visitanteRoc.pop()\n lodelargo = len(apuntaje)# + num - 1#int(powerz(empieze)) - num\n display.push(counter)\n for valor in range(lodelargo):\n if apuntaje[valor] == counter:\n decisions.append(valor)\n elif(not visitanteRoc.isEmpty()):\n return None\n else:\n if not visitanteRoc.isEmpty():\n visitanteRoc.pop()\n #return None\n sop = possibilidadesdemov[decisions[empieze]]\n if(not visitanteRoc.isEmpty()):\n sop = None\n return Exception, \"Structure Empty Fault Failure\"\n return display.pop(), sop\n #masonmio meomo (apuntaje)\n\nclass AlphaBetaAgent(MultiAgentSearchAgent):\n \"\"\"\n Your minimax agent with alpha-beta pruning (question 3)\n \"\"\"\n\n def getAction(yo, juego_estado):\n \"\"\"\n Returns the minimax action using yo.depth and yo.evaluationFunction\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n def el_finimo(estado, personaje_feno, alafondi, primero, segundo):\n decisions = []\n empieze = 0\n g=0\n visitanteRoc = util.Queue()\n visitanteRoc.push(juego_estado)\n length = juego_estado.getNumAgents()\n display = util.Stack();\n val = \"Function Alpha Beta\"\n num = 1\n apuntaje=[]\n powerz = lambda pol: ceil( factorial(pol**2) )\n limit = powerz(10)#89898\n elorizacion = None\n if limit < powerz(num*11) and not visitanteRoc.isEmpty() and personaje_feno != length:\n p2 = (1/13) * (-1)\n counter = 0\n g = 0\n apuntaje=[]\n elorizacion = None\n bronca = False\n while display.isEmpty() and counter < limit and bronca == False:\n for quakope in estado.getLegalActions(personaje_feno):\n lista = estado.generateSuccessor(personaje_feno, quakope)\n genetico_vin = el_finimo(lista,personaje_feno + num, alafondi, primero, segundo)\n if elorizacion is None:\n elorizacion = genetico_vin\n else:\n \"\"\"while ( (display.isEmpty() or counter < limit) and not visitanteRoc.isEmpty() ):\n for temp in genetico_vin:\n if (g == 0 or temp < elorizacion):\n elorizacion = temp\n visitanteRoc.push(counter)\n g = g + num\n elif g < 0:\n p1 = visitanteRoc.pop()\n else:\n display.push(p1)\n while not visitanteRoc.isEmpty():\n visitanteRoc.pop()\"\"\"\n if(genetico_vin < elorizacion):\n elorizacion = genetico_vin\n counter = counter + 1\n p1 = visitanteRoc.pop()\n visitanteRoc.push(elorizacion)\n elif (genetico_vin == elorizacion and segundo == elorizacion and elorizacion is None):\n segundo=primero\n elorizacion=segundo\n primero = genetico_vin\n else:\n pass\n while display.isEmpty() and primero is not None and elorizacion < primero and segundo < limit:\n return elorizacion\n if not visitanteRoc.isEmpty() and segundo is None:\n #trail = powerz(segundo)\n visitanteRoc.pop()\n segundo = elorizacion\n visitanteRoc.push(segundo)\n else:\n if(elorizacion=0 and elorizacion is not None:\n power = powerz(powerz(num))\n #print 'falla portu next time monte, game'+str(power)\n #return yo.evaluationFunction(juego_estado), \"ineffectivo movimiento partition tested shown\"\n return elorizacion\n if not display.isEmpty():\n return Exception, \"Failed To Elorize Demonstrating Founder\"\n elif elorizacion is None:\n return yo.evaluationFunction(estado)\n elif elorizacion < primero and primero is None:\n return None\n else:\n # return yo\n pass\n bronca = True\n\n elif(elorizacion is not None or g<=0 or counter elorizacion):\n elorizacion = genetico_vin\n counter = counter + 1\n p1 = visitanteRoc.pop()\n visitanteRoc.push(primero)\n elif (genetico_vin == elorizacion and segundo == elorizacion and elorizacion is not None):\n segundo=primero\n elorizacion=segundo\n primero = genetico_vin\n if segundo is not None and elorizacion > segundo and segundo != g:\n power = powerz(powerz(num))\n #print 'falla portu next time monte, game'+str(power)\n #return yo.evaluationFunction(juego_estado), \"ineffectivo movimiento partition tested shown\"\n return elorizacion\n if(elorizacion>primero):\n primero=elorizacion\n g=g+1\n p1 = visitanteRoc.pop()\n visitanteRoc.push(primero)\n\n elif(elorizacion == primero and segundo == primero and primero is None):\n primero = segundo\n genetico_vin = segundo\n elorizacion=primero\n #primero = genetico_vin\n #counter++\n if counter < limit and g>=0 and elorizacion is not None:\n return elorizacion\n elif not display.isEmpty():\n return Exception, \"Failed To Elorize Demonstrating Founder\"\n elif elorizacion is None:\n return yo.evaluationFunction(estado)\n elif elorizacion < primero and primero is None:\n return None\n #else:\n # return yo.evaluateFunction();\n bronca = True\n else:\n return yo.evaluationFunction(estado)\n return None\n\n\n\n def solucion_de_la_alpha_beta(estado):\n decisions = []\n nada=None\n empieze = 0\n visitanteRoc = util.Queue()\n visitanteRoc.push(juego_estado)\n length = juego_estado.getNumAgents()\n display = util.Stack();\n val = \"Function Alpha Beta\"\n rlength = estado.getLegalActions(empieze)\n num = 1\n c = 0\n apuntaje=[]\n #informaticaDeLaH\n elorizacion = nada\n primero = nada\n mejor_opcion = nada\n segundo = nada\n powerz = lambda pol: ceil( factorial(pol**2) )\n limit = powerz(10)#89898\n p2 = (1/13) * (-1)\n counter = 0\n g = 0\n #for queMonteWey in possibilidadesdemov:\n # lista = ( juego_estado.generateSuccessor(yo.index,queMonteWey) )\n # apuntaje.append ( yo.el_finimo(lista,num1, depth) )\n while((limit > powerz(num+12) or c < rlength) or not display.isEmpty()):\n for quakope in estado.getLegalActions(empieze):\n \"\"\"while ( (display.isEmpty() or counter < limit) and not visitanteRoc.isEmpty() ):\n for temp in apuntaje:\n if (g == 0 or temp < counter):\n counter = temp\n visitanteRoc.push(counter)\n g = g + 1\n elif g < 0:\n p1 = visitanteRoc.pop()\n else:\n display.push(p1)\n while not visitanteRoc.isEmpty():\n visitanteRoc.pop()\"\"\"\n c=c+1\n lista = estado.generateSuccessor(0, quakope)\n consequencia = el_finimo(lista, num, num, primero, segundo)\n if(g>=0 and counter < num and consequencia > elorizacion):\n if(c>=num):\n elorizacion = consequencia\n consequencia = primero\n else:\n elorizacion = primero\n segundo = primero\n consequencia = None\n elif(g<0):\n display.push(elorizacion)\n visitante.push(elorizacion)\n if g>=0 and len(apuntaje) == 0 and primero is None and display.isEmpty():\n mejor_opcion = quakope\n visitanteRoc.push(mejor_opcion)\n primero = elorizacion\n mejor_opcion = quakope\n if(not visitanteRoc.isEmpty()):\n p1 = visitanteRoc.pop()\n\n else:\n if(elorizacion is None or not display.isEmpty()):\n return Nones\n elif(counter==limit):\n return Exception\n if(display.isEmpty() and counter < limit and g >= 0):\n while(g>=0 and elorizacion != None):\n if primero == elorizacion and mejor_opcion == quakope and limit < counter:\n segundo, primero, mejor_opcion = primero, quakope, elorizacion if segundo > elorizacion else quakope\n elif g != counter and elorizacion is not None:\n primero, elorizacion = segundo, primero if segundo is None and primero > segundo else quakope\n else:\n primero, mejor_opcion = elorizacion, quakope if elorizacion > primero else mejor_opcion\n #return mejor_opcion\n break\n #else:\n # mejor_opcion = quakope\n # display.push(mejor_opcion)\n # primero = elorizacion\n # if(not visitanteRoc.isEmpty()):\n # p1 = visitanteRoc.pop()\n if(elorizacion == nada and visitante.pop() == None):\n return None\n else:\n break\n while(elorizacion is not None and counter < limit):\n return mejor_opcion\n return None\n\n return solucion_de_la_alpha_beta(juego_estado)\n #util.raiseNotDefined()\n\nclass ExpectimaxAgent(MultiAgentSearchAgent):\n \"\"\"\n Your expectimax agent (question 4)\n \"\"\"\n\n def getAction(yo, juego_estado):\n d=yo.depth\n empieze=0\n num=1\n lama=yo.fundacionDelAlgoritmo(juego_estado,d, empieze)\n \"\"\"\n Returns the expectimax action using self.depth and self.evaluationFunction\n\n All ghosts should be modeled as choosing uniformly at random from their\n legal moves.\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n return lama[num]\n\n def fundacionDelAlgoritmo(yo, juego_estado, ondo, personaje_dicio):\n length = juego_estado.getNumAgents()\n visitanteRoc = util.Queue()\n visitanteRoc.push(juego_estado)\n nag = juego_estado.isWin()\n display = util.Stack();\n osLeg = juego_estado.isLose()\n num=1\n empieze=0\n g=0\n c=0\n counter=0\n powerz = lambda pol: ceil( factorial(pol**2) )\n al_limite_de_tus_poderes = empieze\n #error = yo.evaluationFunction(juego_estado), \"ineffectivo movimiento partition tested shown\"\n #if juego_estado.isLose():\n # return error\n #val = \"Function Espectatione\"\n solemio = juego_estado.getLegalActions(personaje_dicio)\n action_length = len(solemio)\n limit = powerz(10)#89898\n apuntaje=[]\n decisions=[]\n if not display.isEmpty() or empieze == ondo or nag or limit > powerz(num+12) or osLeg:\n power = powerz(powerz(num))\n #print 'falla portu next time monte, game'+str(power)\n return yo.evaluationFunction(juego_estado), \"ineffectivo movimiento partition tested shown\"\n elif (not display.isEmpty() and ondo < 0):\n visitanteRoc.push(ondo)\n clear(display)\n return None\n else:\n minus_one_length = length - num\n while display.isEmpty() and g>-1 and personaje_dicio == minus_one_length:\n visitanteRoc.push(ondo)\n ondo = ondo - num\n visitanteRoc.push(ondo)\n if(display is not None and empieze > limit):\n return yo.evaluationFunction(juego_estado), \"ineffectivo movimiento partition tested shown\"\n else:\n pass\n break\n nextpersonaje_dicio = ((personaje_dicio + num) % (g+length) ) -counter\n if personaje_dicio >= num or personaje_dicio < empieze:\n al_algoritmo_gold = empieze\n elif counter > limit and not display.isEmpty() and empieze==ondo and nag:\n al_algoritmo_gold = ondo\n return juego_estado.getMoveTimeout()\n elif display is not None and visitanteRoc.isEmpty():\n while ( (display.isEmpty() or counter < limit) and not visitanteRoc.isEmpty() ):\n for temp in apuntaje:\n if (g == 0 or temp < al_algoritmo_gold):\n counter = temp\n visitanteRoc.push(counter)\n g = g + 1\n elif g < 0:\n p1 = visitanteRoc.pop()\n else:\n display.push(p1)\n while not visitanteRoc.isEmpty():\n visitanteRoc.pop()\n return counter, \"Inffectivity\"\n else:\n quiteNegNumber = (-1) * powerz(num*10)\n if(g==c and length is not None):\n al_algoritmo_gold = quiteNegNumber\n visitanteRoc.push(c)\n c=c+1\n else:\n visitanteRoc.pop()\n al_algoritmo_gold = empieze+counter\n g = g + 1\n visitanteRoc.push(g)\n pass\n c=0\n g=0\n answer = al_algoritmo_gold, al_limite_de_tus_poderes\n while(counter>limit or c < action_length or visitanteRoc.isEmpty()):\n for vamosactuar in solemio:\n lista = juego_estado.generateSuccessor(personaje_dicio, vamosactuar)\n dicho_final = yo.fundacionDelAlgoritmo(lista, ondo, nextpersonaje_dicio)\n apuntaje.append(dicho_final)\n if not visitanteRoc.isEmpty() and c >= counter and empieze != personaje_dicio:\n double = num*1.0\n double = double * (1/(double*action_length))\n if(c<1 or al_algoritmo_gold al_algoritmo_gold:\n double = num*1.0\n al_algoritmo_gold = num + double * dicho_final[empieze] - counter - double\n if(counter limit or counter > limit or c>g or (g+num)==1):\n return answer\n #answer = display.pop()\n else:\n return None\n return Exception\n #util.raiseNotDefined()\n\ndef betterEvaluationFunction(currentGameState):\n \"\"\"\n Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable\n evaluation function (question 5).\n\n DESCRIPTION: \n \"\"\"\n \"*** YOUR CODE HERE ***\"\n util.raiseNotDefined()\n\n# Abbreviation\nbetter = betterEvaluationFunction\n","repo_name":"AriTheGuitarMan/AI-Pacman","sub_path":"AI Pacman Challenge Part 2/multiagent/multiAgents.py","file_name":"multiAgents.py","file_ext":"py","file_size_in_byte":35632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"11784444378","text":"import collections\nfrom dataclasses import dataclass\nimport re\nfrom typing import List\nimport fileinput\n\n\n@dataclass\nclass Node:\n name: int\n flow: int\n neighbors: List[str]\n\n\ndef read_map():\n nodes = {}\n\n node_re = re.compile(r\"Valve (.+) has flow rate=(.+); tunnels? leads? to valves? (.+)\")\n for line in fileinput.input():\n match = node_re.match(line)\n name, flow, neighbors = match.groups()\n flow = int(flow)\n neighbors = neighbors.split(', ')\n node = Node(name, flow, neighbors)\n nodes[name] = node\n\n return nodes\n\n\ndef calculate_distances(nodes, start):\n distances = {}\n\n queue = collections.deque()\n distances[start] = 1\n queue.append((1, start))\n while queue:\n distance, node_name = queue.popleft()\n node = nodes[node_name]\n for neighbor_name in node.neighbors:\n if neighbor_name not in distances:\n distances[neighbor_name] = distance + 1\n queue.append((distance + 1, neighbor_name))\n return distances\n\n\ndef make_connection_matrix(nodes):\n matrix = {}\n\n for start in nodes.keys():\n distances = calculate_distances(nodes, start)\n matrix[start] = distances\n\n return matrix\n\n\ndef find_best_route(nodes, matrix, start, time_limit, actor_num):\n opened = {name: node.flow == 0 for name, node in nodes.items()}\n start_positions = [(0, start)] * actor_num\n bestest_flow = [0]\n\n def visit(positions, time_left, flow):\n node_name = positions[0][1]\n other_positions = positions[1:]\n other_min_distance = None\n if other_positions:\n other_min_distance = min(pos[0] for pos in other_positions)\n\n flow_gain = nodes[node_name].flow * time_left\n new_flow = flow + flow_gain\n best_flow = new_flow\n\n opened_any = False\n for neighbor_name, distance in matrix[node_name].items():\n if not opened[neighbor_name] and time_left > distance:\n opened_any = True\n opened[neighbor_name] = True\n\n if not other_positions:\n min_distance = distance\n new_positions = [(0, neighbor_name)]\n else:\n min_distance = min(distance, other_min_distance)\n\n new_positions = [(distance - min_distance, name)\n for distance, name in other_positions]\n new_positions.append((distance - min_distance, neighbor_name))\n new_positions.sort()\n\n child_flow = visit(\n new_positions, time_left - min_distance, new_flow\n )\n if child_flow > best_flow:\n best_flow = child_flow\n\n opened[neighbor_name] = False\n\n if not opened_any and other_positions:\n new_positions = [(distance - other_min_distance, name)\n for distance, name in other_positions]\n child_flow = visit(\n new_positions, time_left - other_min_distance, new_flow\n )\n best_flow = max(best_flow, child_flow)\n bestest_flow[0] = max(bestest_flow[0], best_flow)\n print(bestest_flow[0])\n\n return best_flow\n\n best_flow = visit(\n positions=start_positions, time_left=time_limit, flow=0\n )\n\n return best_flow\n\n\nif __name__ == '__main__':\n nodes = read_map()\n print(nodes)\n\n matrix = make_connection_matrix(nodes)\n print(len(matrix))\n\n #result = find_best_route(nodes, matrix, start='AA', time_limit=30, actor_num=1)\n #print(result)\n\n result = find_best_route(nodes, matrix, start='AA', time_limit=26, actor_num=2)\n print(result)\n","repo_name":"michalsosn/advent-of-code-2022","sub_path":"16_proboscidea_volcanium/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"71421189239","text":"import bth.db_connector as db\nimport bth.cloud_connector as cloud\n\n# Busca os ids das divições já realizadas para o cloud\ndef iniciar_processo_busca(params_exec, ano, *args, **kwargs):\n sql = db.get_consulta(params_exec, f'busca_comissao_licitacao.sql')\n correcao = str(input('Realizar correção ?'))\n grava = str(input('Gravar resultado ?'))\n for x in db.consulta_sql(sql, params_exec, index_col='tipo_registro'):\n resultado = f\"Comissão {x['chave_dsk2']} da entidade {x['chave_dsk1']} : \"\n\n # exercicio = ''\n # id_proc_adm = ''\n # id_item = ''\n # id_divisao = ''\n # url = f'https://compras.betha.cloud/compras-services/api/exercicios/{exercicio}/processos-administrativo/{id_proc_adm}/itens/{id_item}/entidades/{id_divisao}'\n","repo_name":"JoaoPauloLeal/motor_etl","sub_path":"packages/tools/compras/rotinas_envio/deleta_divisao_item_entidades.py","file_name":"deleta_divisao_item_entidades.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"35211616811","text":"import sys\ninput = sys.stdin.readline\n\n\ndef get_max(A, prev, total):\n global result\n if not A:\n result = max(result, total)\n return\n for i in range(len(A)):\n current = A.pop(i)\n get_max(A, current, total+abs(prev-current))\n A.insert(i, current)\n\n\nN = int(input())\nA = list(map(int, input().split()))\nresult = 0\nfor i in range(len(A)):\n prev = A.pop(i)\n get_max(A, prev, 0)\n A.insert(i, prev)\nprint(result)\n","repo_name":"hyh1016/boj-with-python","sub_path":"python/backtracking/10819.py","file_name":"10819.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"5421725511","text":"import httplib\nfrom xml.dom import minidom\nfrom xml.dom.minidom import Document\n\nfrom ovd.Logger import Logger\nfrom ovd.Communication.Dialog import Dialog as AbstractDialog\n\nimport Apt\nfrom Platform.ApplicationsDetection import ApplicationsDetection\nfrom Platform.DomainMicrosoft import DomainMicrosoft\nfrom Platform.DomainNovell import DomainNovell\nfrom Platform.DomainUlteo import DomainUlteo\nfrom Platform.DomainLocal import DomainLocal\nfrom Platform.Profile import Profile\nfrom Platform.TS import TS\nfrom Platform.Session import Session\nfrom Platform.User import User\n\nclass Dialog(AbstractDialog):\n\tdef __init__(self, role_instance):\n\t\tself.role_instance = role_instance\n\t\n\t\n\t@staticmethod\n\tdef getName():\n\t\treturn \"aps\"\n\t\n\t\n\tdef process(self, request):\n\t\tpath = request[\"path\"]\n\t\t\n\t\tif request[\"method\"] == \"GET\":\n\t\t\tLogger.debug(\"do_GET \"+path)\n\t\t\t\n\t\t\tif path == \"/applications\":\n\t\t\t\treturn self.req_applications(request)\n\t\t\t\n\t\t\telif path.startswith(\"/application/icon/\"):\n\t\t\t\tapp_id = path[len(\"/application/icon/\"):]\n\t\t\t\treturn self.req_icon(app_id)\n\t\t\t\n\t\t\telif path == \"/applications/static/sync\":\n\t\t\t\treturn self.req_sync_static_applications(request)\n\t\t\telif path == \"/scripts/sync\":\n\t\t\t\treturn self.req_sync_scripts(request)\n\t\t\telif path.startswith(\"/session/status/\"):\n\t\t\t\tbuf = path[len(\"/session/status/\"):]\n\t\t\t\treturn self.req_session_status(buf)\n\t\t\t\n\t\t\telif path.startswith(\"/session/destroy/\"):\n\t\t\t\tbuf = path[len(\"/session/destroy/\"):]\n\t\t\t\treturn self.req_session_destroy(buf)\n\t\t\t\n\t\t\telif path.startswith(\"/session/disconnect/\"):\n\t\t\t\tbuf = path[len(\"/session/disconnect/\"):]\n\t\t\t\treturn self.req_session_disconnect(buf)\n\t\t\t\n\t\t\telif path.startswith(\"/debian/\") and self.role_instance.canManageApplications():\n\t\t\t\tbuf = path[len(\"/debian/\"):]\n\t\t\t\treturn self.req_debian_id(buf)\n\t\t\t\n\t\t\treturn None\n\t\t\n\t\telif request[\"method\"] == \"POST\":\n\t\t\tLogger.debug(\"do_POST \"+path)\n\t\t\tif path == \"/session/create\":\n\t\t\t\treturn self.req_session_create(request)\n\t\t\t\n\t\t\telif path == \"/user/loggedin\":\n\t\t\t\treturn self.req_user_loggedin(request)\n\t\t\t\n\t\t\telif path == \"/user/logout\":\n\t\t\t\treturn self.req_user_logout(request)\n\t\t\t\n\t\t\telif path == \"/debian\" and self.role_instance.canManageApplications():\n\t\t\t\treturn self.req_debian(request)\n\t\t\t\n\t\t\telif path == \"/applications/ids\":\n\t\t\t return self.req_applications_matching(request)\n\t\t\t\n\t\t\treturn None\n\t\t\n\t\treturn None\n\t\n\t\n\t@staticmethod\n\tdef session2xmlstatus(session):\n\t\tdoc = Document()\n\t\trootNode = doc.createElement('session')\n\t\trootNode.setAttribute(\"id\", session.id)\n\t\trootNode.setAttribute(\"status\", session.status)\n\t\t\n\t\tif session.status == Session.SESSION_STATUS_DESTROYED and session.end_status is not None:\n\t\t\trootNode.setAttribute(\"reason\", session.end_status)\n\t\t\n\t\tdoc.appendChild(rootNode)\n\t\t\n\t\treturn doc\n\t\n\t\n\tdef req_applications(self, request):\n\t\tdoc = Document()\n\t\trootNode = doc.createElement('applications')\n\t\tdoc.appendChild(rootNode)\n\t\t\n\t\tself.role_instance.applications_mutex.acquire()\n\t\t\n\t\tfor application in self.role_instance.applications.values():\n\t\t\tappNode = doc.createElement(\"application\")\n\t\t\tappNode.setAttribute(\"id\", application[\"local_id\"])\n\t\t\tappNode.setAttribute(\"name\", application[\"name\"])\n\t\t\tappNode.setAttribute(\"desktopfile\", application[\"filename\"])\n\t\t\tif application.has_key(\"description\"):\n\t\t\t\tappNode.setAttribute(\"description\", application[\"description\"])\n\t\t\tif application.has_key(\"package\"):\n\t\t\t\tappNode.setAttribute(\"package\", application[\"package\"])\n\t\t\texeNode = doc.createElement(\"executable\")\n\t\t\texeNode.setAttribute(\"command\", application[\"command\"])\n\t\t\t#if application.has_key(\"icon\"):\n\t\t\t#\texeNode.setAttribute(\"icon\", application[\"icon\"])\n\t\t\tfor mime in application[\"mimetypes\"]:\n\t\t\t\tmimeNode = doc.createElement(\"mime\")\n\t\t\t\tmimeNode.setAttribute(\"type\", mime)\n\t\t\t\tappNode.appendChild(mimeNode)\n\t\t\t\n\t\t\tappNode.appendChild(exeNode)\n\t\t\t\n\t\t\trootNode.appendChild(appNode)\n\t\t\n\t\tself.role_instance.applications_mutex.release()\n\t\t\n\t\treturn self.req_answer(doc)\n\t\n\t\n\tdef req_applications_matching(self, request):\n\t\ttry:\n\t\t\tdocument = minidom.parseString(request[\"data\"])\n\t\t\trootNode = document.documentElement\n\t\t\t\n\t\t\tif rootNode.nodeName != \"applications\":\n\t\t\t\traise Exception(\"invalid root node\")\n\t\t\t\n\t\t\tmatching = []\n\t\t\tapplicationNodes = rootNode.getElementsByTagName(\"application\")\n\t\t\tfor node in applicationNodes:\n\t\t\t\tmatching.append((node.getAttribute(\"id\"), node.getAttribute(\"local_id\")))\n\t\t\n\t\texcept Exception:\n\t\t\tLogger.exception(\"Invalid xml input\")\n\t\t\tdoc = Document()\n\t\t\trootNode = doc.createElement('error')\n\t\t\trootNode.setAttribute(\"id\", \"usage\")\n\t\t\tdoc.appendChild(rootNode)\n\t\t\treturn self.req_answer(doc)\n\t\t\n\t\tself.role_instance.applications_mutex.acquire()\n\t\t\n\t\tself.role_instance.applications_id_SM = {}\n\t\t\n\t\tfor (sm_id, local_id) in matching:\n\t\t\tif not self.role_instance.applications.has_key(local_id):\n\t\t\t\tcontinue\n\t\t\t\n\t\t\tself.role_instance.applications[local_id][\"id\"] = sm_id\n\t\t\tself.role_instance.applications_id_SM[sm_id] = self.role_instance.applications[local_id]\n\t\t\n\t\tself.role_instance.applications_mutex.release()\n\t\t\n\t\tdoc = Document()\n\t\trootNode = doc.createElement('applications')\n\t\trootNode.setAttribute(\"matching\", \"ok\")\n\t\tdoc.appendChild(rootNode)\n\t\t\n\t\treturn self.req_answer(doc)\n\t\n\t\n\tdef req_icon(self, app_id):\n\t\tif self.role_instance.applications is None:\n\t\t\treturn self.req_unauthorized()\n\t\t\n\t\tself.role_instance.applications_mutex.acquire()\n\t\t\n\t\tif not self.role_instance.applications_id_SM.has_key(app_id):\n\t\t\tself.role_instance.applications_mutex.release()\n\t\t\treturn self.req_unauthorized()\n\t\t\n\t\tapp = self.role_instance.applications_id_SM[app_id]\n\t\t\n\t\tself.role_instance.applications_mutex.release()\n\t\t\n\t\tappsdetect = ApplicationsDetection()\n\t\tdata = appsdetect.getIcon(app[\"filename\"])\n\t\tif data is None:\n\t\t\treturn self.req_not_found()\n\t\t\n\t\tresponse = {}\n\t\tresponse[\"code\"] = httplib.OK\n\t\tresponse[\"Content-Type\"] = \"image/png\"\n\t\tresponse[\"data\"] = data\n\t\treturn response\n\t\n\t\n\tdef req_session_create(self, request):\n\t\tif self.role_instance.stopping():\n\t\t\treturn self.req_stopping(request)\n\t\t\n\t\tenvironment = DomainUlteo()\n\t\ttry:\n\t\t\tdocument = minidom.parseString(request[\"data\"])\n\t\t\tsessionNode = document.documentElement\n\t\t\t\n\t\t\tif sessionNode.nodeName != \"session\":\n\t\t\t\traise Exception(\"invalid root node\")\n\t\t\t\n\t\t\tif not sessionNode.hasAttribute(\"id\"):\n\t\t\t\traise Exception(\"invalid root node\")\n\t\t\t\n\t\t\tif not sessionNode.hasAttribute(\"mode\"):\n\t\t\t\traise Exception(\"invalid root node\")\n\t\t\t\n\t\t\tsession = {}\n\t\t\tsession[\"id\"] = sessionNode.getAttribute(\"id\")\n\t\t\tsession[\"mode\"] = sessionNode.getAttribute(\"mode\")\n\t\t\t\n\t\t\tif len(session[\"id\"])==0:\n\t\t\t\traise Exception(\"Missing attribute id\")\n\t\t\t\n\t\t\tif session[\"mode\"] == \"desktop\":\n\t\t\t\tsession[\"mode\"] = Session.MODE_DESKTOP\n\t\t\telif session[\"mode\"] == \"applications\":\n\t\t\t\tsession[\"mode\"] = Session.MODE_APPLICATIONS\n\t\t\telse:\n\t\t\t\traise Exception(\"Missing attribute id\")\n\t\t\t\n\t\t\tnodes = sessionNode.getElementsByTagName(\"environment\")\n\t\t\tif len(nodes)>0:\n\t\t\t\tenvironmentNode = nodes[0]\n\t\t\t\tname = environmentNode.getAttribute(\"id\")\n\t\t\t\t\n\t\t\t\tif name == \"Microsoft\":\n\t\t\t\t\tenvironment = DomainMicrosoft()\n\t\t\t\telif name == \"Novell\":\n\t\t\t\t\tenvironment = DomainNovell()\n\t\t\t\telif name == \"Local\":\n\t\t\t\t\tenvironment = DomainLocal()\n\t\t\t\telse:\n\t\t\t\t\traise Exception(\"unknown environment '%s'\"%(name))\n\t\t\t\t\n\t\t\t\tret = environment.parse(environmentNode)\n\t\t\t\tif ret is False:\n\t\t\t\t\traise Exception(\"invalid environment schema\")\n\t\t\t\n\t\t\t\n\t\t\tuserNode = sessionNode.getElementsByTagName(\"user\")[0]\n\t\t\t\n\t\t\tfor attr in [\"login\", \"password\", \"displayName\"]:\n\t\t\t\tif not userNode.hasAttribute(attr):\n\t\t\t\t\traise Exception(\"invalid child node: missing attribute \"+attr)\n\t\t\t\t\n\t\t\t\tsession[attr] = userNode.getAttribute(attr)\n\t\t\t\n\t\t\tapplications = {}\n\t\t\t\n\t\t\tself.role_instance.applications_mutex.acquire()\n\t\t\tapplicationNodes = sessionNode.getElementsByTagName(\"application\")\n\t\t\tfor node in applicationNodes:\n\t\t\t\tif node.parentNode != sessionNode:\n\t\t\t\t\tcontinue\n\t\t\t\t\n\t\t\t\tapp_id = node.getAttribute(\"id\")\n\t\t\t\tif self.role_instance.applications_id_SM.has_key(app_id):\n\t\t\t\t\tapplications[app_id] = self.role_instance.applications_id_SM[app_id]\n\t\t\t\t\n\t\t\t\telif self.role_instance.static_apps.applications.has_key(app_id):\n\t\t\t\t\tapplications[app_id] = self.role_instance.static_apps.applications[app_id]\n\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\tself.role_instance.applications_mutex.release()\n\t\t\t\t\tLogger.warn(\"Unknown application id %s\"%(app_id))\n\t\t\t\t\traise Exception(\"Unknown application id %s\"%(app_id))\n\t\t\t\n\t\t\tself.role_instance.applications_mutex.release()\n\t\t\t\n\t\t\tshellNode = sessionNode.getElementsByTagName(\"shell\")[0]\n\t\t\t\n\t\t\tsession[\"parameters\"] = {}\n\t\t\tfor node in sessionNode.getElementsByTagName(\"parameter\"):\n\t\t\t\tsession[\"parameters\"][node.getAttribute(\"name\")] = node.getAttribute(\"value\")\n\t\t\t\n\t\t\t\n\t\t\tnodes = sessionNode.getElementsByTagName(\"profile\")\n\t\t\tif len(nodes)>0:\n\t\t\t\tprofileNode = nodes[0]\n\t\t\t\tfor attribute in (\"rid\", \"uri\", \"profile_mode\"):\n\t\t\t\t\tif len(profileNode.getAttribute(attribute)) == 0:\n\t\t\t\t\t\traise Exception(\"Empty attribute \"+attribute)\n\t\t\telse:\n\t\t\t\tprofileNode = None\n\t\t\t\n\t\t\tsharedfolderNodes = sessionNode.getElementsByTagName(\"sharedfolder\")\n\t\t\tfor node in sharedfolderNodes:\n\t\t\t\tfor attribute in (\"rid\", \"uri\", \"name\"):\n\t\t\t\t\tif len(node.getAttribute(attribute)) == 0:\n\t\t\t\t\t\traise Exception(\"Empty attribute \"+attribute)\n\t\t\n\t\texcept Exception:\n\t\t\tLogger.exception(\"Invalid xml input\")\n\t\t\tdoc = Document()\n\t\t\trootNode = doc.createElement('error')\n\t\t\trootNode.setAttribute(\"id\", \"usage\")\n\t\t\tdoc.appendChild(rootNode)\n\t\t\treturn self.req_answer(doc)\n\t\t\n\t\tuser = User(session[\"login\"], {\"displayName\": session[\"displayName\"], \"password\": session[\"password\"]})\n\t\tif session[\"parameters\"].has_key(\"locale\"):\n\t\t\tuser.infos[\"locale\"] = session[\"parameters\"][\"locale\"]\n\t\t\n\t\tsession = Session(session[\"id\"], session[\"mode\"], user, session[\"parameters\"], applications.values())\n\t\tsession.setDomain(environment)\n\t\tsession.setShellConf(shellNode)\n\t\tsession.init()\n\t\t\n\t\tif profileNode is not None or len(sharedfolderNodes)>0:\n\t\t\tprofile = Profile(session)\n\t\t\n\t\tif profileNode is not None:\n\t\t\tfolder = {}\n\t\t\tfor (key, value) in profileNode.attributes.items():\n\t\t\t\tfolder[key] = value\n\t\t\t\n\t\t\tprofile.setProfile(folder)\n\t\t\n\t\tfor sharedFolderNode in sharedfolderNodes:\n\t\t\tfolder = {}\n\t\t\tfor (key, value) in sharedFolderNode.attributes.items():\n\t\t\t\tfolder[key] = value\n\t\t\t\n\t\t\tprofile.addSharedFolder(folder)\n\t\t\n\t\tif self.role_instance.sessions.has_key(session.id):\n\t\t\tLogger.warn(\"Session %s already exist, aborting creation\"%(session.id))\n\t\t\tdoc = Document()\n\t\t\trootNode = doc.createElement('error')\n\t\t\trootNode.setAttribute(\"id\", \"user already exist\")\n\t\t\tdoc.appendChild(rootNode)\n\t\t\treturn self.req_answer(doc)\n\t\t\n\t\tself.role_instance.sessions[session.id] = session\n\t\tself.role_instance.spool_action(\"create\", session.id)\n\t\t\n\t\treturn self.req_answer(self.session2xmlstatus(session))\n\t\n\t\n\tdef req_session_status(self, session_id):\n\t\tif self.role_instance.sessions.has_key(session_id):\n\t\t\tsession = self.role_instance.sessions[session_id]\n\t\telse:\n\t\t\tsession = Session(session_id, None, None, None, None)\n\t\t\tsession.status = \"unknown\"\n\t\t\n\t\treturn self.req_answer(self.session2xmlstatus(session))\n\t\n\t\n\tdef req_session_destroy(self, session_id):\n\t\tif self.role_instance.sessions.has_key(session_id):\n\t\t\tsession = self.role_instance.sessions[session_id]\n\t\t\tif session.status not in [Session.SESSION_STATUS_WAIT_DESTROY, Session.SESSION_STATUS_DESTROYED, Session.SESSION_STATUS_ERROR]:\n\t\t\t\t# Switch the session status without warn the session manager\n\t\t\t\tsession.switch_status(Session.SESSION_STATUS_WAIT_DESTROY)\n\t\t\t\tself.role_instance.spool_action(\"destroy\", session.id)\n\t\telse:\n\t\t\tsession = Session(session_id, None, None, None, None)\n\t\t\tsession.status = Session.SESSION_STATUS_UNKNOWN\n\t\t\n\t\treturn self.req_answer(self.session2xmlstatus(session))\n\t\n\tdef req_session_disconnect(self, session_id):\n\t\tif self.role_instance.sessions.has_key(session_id):\n\t\t\tsession = self.role_instance.sessions[session_id]\n\t\t\tif session.status == Session.SESSION_STATUS_ACTIVE:\n\t\t\t\tself.role_instance.spool_action(\"disconnect\", session.id)\n\t\telse:\n\t\t\tsession = Session(session_id, None, None, None, None)\n\t\t\tsession.status = Session.SESSION_STATUS_UNKNOWN\n\t\t\n\t\treturn self.req_answer(self.session2xmlstatus(session))\n\t\n\tdef req_user_loggedin(self, request):\n\t\ttry:\n\t\t\tdocument = minidom.parseString(request[\"data\"])\n\t\t\trootNode = document.documentElement\n\t\t\t\n\t\t\tif rootNode.nodeName != \"user\":\n\t\t\t\traise Exception(\"invalid root node\")\n\t\t\t\n\t\t\tif not rootNode.hasAttribute(\"login\"):\n\t\t\t\traise Exception(\"invalid root node\")\n\t\t\t\n\t\t\tlogin = rootNode.getAttribute(\"login\")\n\t\t\t\n\t\texcept:\n\t\t\tLogger.warn(\"Invalid xml input !!\")\n\t\t\tdoc = Document()\n\t\t\trootNode = doc.createElement('error')\n\t\t\trootNode.setAttribute(\"id\", \"usage\")\n\t\t\tdoc.appendChild(rootNode)\n\t\t\treturn self.req_answer(doc)\n\t\t\n\t\ttry:\n\t\t\tret = TS.getSessionID(login)\n\t\texcept Exception:\n\t\t\tLogger.exception(\"RDP server dialog failed ... \")\n\t\t\tdoc = Document()\n\t\t\trootNode = doc.createElement('error')\n\t\t\trootNode.setAttribute(\"id\", \"internalerror\")\n\t\t\tdoc.appendChild(rootNode)\n\t\t\treturn self.req_answer(doc)\n\t\t\n\t\trootNode.setAttribute(\"loggedin\", str((ret is not None)).lower())\n\t\t\n\t\treturn self.req_answer(document)\n\t\n\t\n\tdef req_user_logout(self, request):\n\t\ttry:\n\t\t\tdocument = minidom.parseString(request[\"data\"])\n\t\t\trootNode = document.documentElement\n\t\t\t\n\t\t\tif rootNode.nodeName != \"user\":\n\t\t\t\traise Exception(\"invalid root node\")\n\t\t\t\n\t\t\tif not rootNode.hasAttribute(\"login\"):\n\t\t\t\traise Exception(\"invalid root node\")\n\t\t\t\n\t\t\tlogin = rootNode.getAttribute(\"login\")\n\t\t\t\n\t\texcept:\n\t\t\tLogger.warn(\"Invalid xml input !!\")\n\t\t\tdoc = Document()\n\t\t\trootNode = doc.createElement('error')\n\t\t\trootNode.setAttribute(\"id\", \"usage\")\n\t\t\tdoc.appendChild(rootNode)\n\t\t\treturn self.req_answer(doc)\n\t\t\n\t\t\n\t\tsession = self.role_instance.get_session_from_login(login)\n\t\t\n\t\tif session is None:\n\t\t\tdoc = Document()\n\t\t\trootNode = doc.createElement('error')\n\t\t\trootNode.setAttribute(\"id\", \"unknown user\")\n\t\t\tdoc.appendChild(rootNode)\n\t\t\t\n\t\t\treturn self.req_answer(doc)\n\t\t\n\t\tself.role_instance.spool_action(\"logoff\", session.id)\n\t\t\n\t\treturn self.req_answer(document)\n\t\n\t\n\tdef req_debian(self, request):\n\t\ttry:\n\t\t\tdocument = minidom.parseString(request[\"data\"])\n\t\t\trootNode = document.documentElement\n\t\t\tif rootNode.nodeName != \"debian\":\n\t\t\t\traise Exception(\"invalid root node\")\n\t\t\t\n\t\t\trequest = rootNode.getAttribute(\"request\")\n\t\t\tif request not in [\"upgrade\", \"install\", \"remove\", \"available\"]:\n\t\t\t\traise Exception(\"usage\")\n\t\t\t\n\t\t\tpackageNodes = rootNode.getElementsByTagName(\"package\")\n\t\t\tif request in [\"install\", \"remove\"] and len(packageNodes)==0:\n\t\t\t\traise Exception(\"usage\")\n\t\t\t\n\t\t\tpackages = []\n\t\t\tfor packageNode in packageNodes:\n\t\t\t\tpackages.append(packageNode.getAttribute(\"name\"))\n\t\t\n\t\texcept Exception:\n\t\t\tLogger.exception(\"Invalid xml input\")\n\t\t\tdoc = Document()\n\t\t\trootNode = doc.createElement('error')\n\t\t\trootNode.setAttribute(\"id\", \"usage\")\n\t\t\tdoc.appendChild(rootNode)\n\t\t\treturn self.req_answer(doc)\n\t\t\n\t\tif request == \"available\":\n\t\t\treq = Apt.Request_Available()\n\t\telse:\n\t\t\treq = Apt.Request_Packages(request, packages)\n\t\t\n\t\treq_id = self.role_instance.apt.add(req)\n\t\t\n\t\treturn self.req_answer(self.debian_request2xml(req_id, req))\n\t\n\t\n\tdef req_stopping(self, req):\n\t\tdoc = Document()\n\t\trootNode = doc.createElement('error')\n\t\trootNode.setAttribute(\"id\", \"server is stopping\")\n\t\tdoc.appendChild(rootNode)\n\t\treturn self.req_answer(doc)\n\n\t\n\tdef req_debian_id(self, req):\n\t\ttry:\n\t\t\t(rid, request) = req.split(\"/\", 2)\n\t\t\treq = self.role_instance.apt.get(rid)\n\t\t\tif req is None:\n\t\t\t\treq = Apt.Request()\n\t\t\t\treq.status = \"unknown\"\n\t\t\t\treturn self.req_answer(self.debian_request2xml(rid, req))\n\t\t\t\n\t\t\tif request == \"status\":\n\t\t\t\treturn self.req_answer(self.debian_request2xml(rid, req))\n\t\t\t\n\t\t\telif request in [\"stdout\", \"stderr\"]:\n\t\t\t\tresponse = {}\n\t\t\t\tresponse[\"code\"] = httplib.OK\n\t\t\t\tresponse[\"Content-Type\"] = \"text/plain\"\n\t\t\t\tresponse[\"data\"] = req.getLog(request)\n\t\t\t\treturn response\n\t\t\t\n\t\t\telse:\n\t\t\t\traise Exception(\"usage\")\n\t\t\t\n\t\texcept Exception:\n\t\t\tLogger.exception(\"Invalid xml input\")\n\t\t\tdoc = Document()\n\t\t\trootNode = doc.createElement('error')\n\t\t\trootNode.setAttribute(\"id\", \"usage\")\n\t\t\tdoc.appendChild(rootNode)\n\t\t\treturn self.req_answer(doc)\n\t\n\t\n\tdef req_sync_static_applications(self, request):\n\t\tself.role_instance.setStaticAppsMustBeSync(True)\n\t\t\n\t\tdoc = Document()\n\t\trootNode = doc.createElement('applications')\n\t\tdoc.appendChild(rootNode)\n\t\t\n\t\treturn self.req_answer(doc)\n\t\n\tdef req_sync_scripts(self, request):\n\t\tself.role_instance.setScriptsMustBeSync(True)\n\t\tdoc = Document()\n\t\trootNode = doc.createElement('scripts')\n\t\tdoc.appendChild(rootNode)\n\t\t\n\t\treturn self.req_answer(doc)\n\t\n\t@staticmethod\n\tdef debian_request2xml(rid, request):\n\t\tdoc = Document()\n\t\trootNode = doc.createElement('debian_request')\n\t\trootNode.setAttribute(\"id\", rid)\n\t\trootNode.setAttribute(\"status\", request.getStatus())\n\t\tdoc.appendChild(rootNode)\n\t\t\n\t\treturn doc\n","repo_name":"ulteo/ovd","sub_path":"OvdServer/ovd/Role/ApplicationServer/Dialog.py","file_name":"Dialog.py","file_ext":"py","file_size_in_byte":16930,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"40"} +{"seq_id":"555052765","text":"# -*- coding: utf-8 -*-\nimport os\nimport inspect\nimport FreeCAD as App\nfrom PySide import QtCore, QtGui\nimport WF\n\nERROR_MSG_NOT_YET = \"Not yet Developed !\"\n\n\nclass TimerMessageBox(QtGui.QMessageBox):\n def __init__(self, msg, timeout=15, parent=None):\n super(TimerMessageBox, self).__init__(parent)\n # self.setWindowTitle(\"wait\")\n self.time_to_wait = timeout\n self.msg = msg\n m_msg = self.msg + \"\\n\\n\" + \" (closing automatically in {0} secondes.)\".format(timeout)\n self.setText(m_msg)\n self.setStandardButtons(QtGui.QMessageBox.Close)\n self.timer = QtCore.QTimer(self)\n self.timer.setInterval(1000)\n self.timer.timeout.connect(self.changeContent)\n self.timer.start()\n\n def changeContent(self):\n self.time_to_wait -= 1\n m_msg = self.msg + \"\\n\\n\" + \" (closing automatically in {0} secondes.)\".format(self.time_to_wait)\n self.setText(m_msg)\n if self.time_to_wait <= 0:\n self.close()\n\n def closeEvent(self, event):\n self.timer.stop()\n event.accept()\n\n\ndef gui_errorDialogWithTimer(msg, title=None, timeout=15):\n \"\"\" Create a QMessageBox dialog with timer for error messages.\n \"\"\"\n m_script = os.path.basename(os.path.realpath(__file__))\n diag = TimerMessageBox(msg, timeout=timeout, parent=None)\n diag.setWindowModality(QtCore.Qt.ApplicationModal)\n diag.setWindowTitle('Error in ' + str(m_script))\n if title is not None:\n diag.setWindowTitle(str(title))\n diag.exec_()\n\n\ndef gui_errorDialog(msg, title=None):\n \"\"\" Create a simple QMessageBox dialog for error messages.\n \"\"\"\n m_script = os.path.basename(os.path.realpath(__file__))\n # The first argument indicates the icon used:\n # one of QtGui.QMessageBox.{NoIcon,Information,Warning Critical,Question}\n diag = QtGui.QMessageBox(QtGui.QMessageBox.Warning,\n 'Error in ' + str(m_script),\n msg)\n diag.setWindowModality(QtCore.Qt.ApplicationModal)\n if title is not None:\n diag.setWindowTitle(str(title))\n diag.exec_()\n\n\ndef gui_infoDialog(msg, title=None):\n \"\"\" Create a simple QMessageBox dialog for info messages.\n \"\"\"\n # The first argument indicates the icon used:\n # one of QtGui.QMessageBox.{NoIcon,Information,Warning Critical,Question}\n diag = QtGui.QMessageBox(QtGui.QMessageBox.Information,\n 'Info :',\n msg)\n diag.setWindowModality(QtCore.Qt.ApplicationModal)\n if title is not None:\n diag.setWindowTitle(str(title))\n diag.exec_()\n\n\ndef print_msg(message):\n \"\"\" Print a message on console.\n \"\"\"\n App.Console.PrintMessage(message + \"\\n\")\n\n\ndef printInfo_msg(message, title=None):\n \"\"\" Print a message on console.\n \"\"\"\n m_msg = message\n App.Console.PrintMessage(m_msg + \"\\n\")\n try:\n gui_infoDialog(m_msg, title)\n except Exception as err:\n App.Console.PrintError(\"\\nERROR: Not able to launch a QT dialog !\")\n App.Console.PrintError(err.args[0])\n raise Exception\n\n\ndef printError_msg(message, title=None):\n \"\"\" Print a ERROR message on console.\n \"\"\"\n m_msg = str(inspect.stack()[1][3]) + \" : \" + str(message)\n App.Console.PrintError(m_msg + \"\\n\")\n try:\n gui_errorDialog(m_msg, title)\n except Exception as err:\n App.Console.PrintError(\"\\nERROR: Not able to launch a QT dialog !\")\n App.Console.PrintError(err.args[0])\n raise Exception\n\n\ndef printError_msgWithTimer(message, title=None):\n \"\"\" Print a ERROR message on console.\n \"\"\"\n m_msg = str(inspect.stack()[1][3]) + \" : \" + str(message)\n App.Console.PrintError(m_msg + \"\\n\")\n # recover timeout value from preferences\n timeout = WF.timeout()\n if timeout == 0:\n return\n try:\n gui_errorDialogWithTimer(m_msg, title, timeout)\n except Exception as err:\n App.Console.PrintError(\"\\nERROR: Not able to launch a QT dialog !\")\n App.Console.PrintError(err.args[0])\n raise Exception\n\n\ndef print_not_yet():\n \"\"\" Print for on going dev.\n \"\"\"\n printError_msg(ERROR_MSG_NOT_YET)\n","repo_name":"Rentlau/WorkFeature-WB","sub_path":"Utils/WF_print.py","file_name":"WF_print.py","file_ext":"py","file_size_in_byte":4178,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"40"} +{"seq_id":"919332716","text":"import sys\nsys.stdin = open('input_files/1302.txt')\n\n\n# #################### 방법 1. ####################\n# # set() 활용\n# N = int(input())\n# books = list(input() for _ in range(N))\n# # 중복 제거, 정렬한 책 리스트\n# book_lst = sorted(list(set(books)))\n#\n# cnts = []\n# # 팔린 책의 수를 cnts에 추가\n# for book in book_lst:\n# cnts.append(books.count(book))\n# # 가장 많이 팔린 책의 인덱스를 정렬한 책 리스트에서 print\n# idx = cnts.index(max(cnts))\n# print(book_lst[idx])\n#\n#\n# #################### 방법 2. ####################\n# # set() 활용\n# N = int(input())\n# books = list(input() for _ in range(N))\n# # 중복 제거, 정렬한 책 리스트\n# book_lst = sorted(list(set(books)))\n#\n# # index값과 팔린 책의 수 초기화\n# max_idx = 0\n# max_cnt = 0\n# for i in range(len(book_lst)):\n# if books.count(book_lst[i]) > max_cnt:\n# max_idx = i\n# max_cnt = books.count(book_lst[i])\n#\n# print(book_lst[max_idx])\n\n\n#################### 방법 3. ####################\n# Dictionary 활용\n\nN = int(input())\nbooks = {}\n\nfor _ in range(N):\n book = input()\n if book not in books:\n books[book] = 1\n else:\n books[book] += 1\n\ntarget = max(books.values()) # value값 중 가장 큰 값\narr = []\n\nfor book, number in books.items():\n if number == target:\n arr.append(book) # 사전순으로 프린트해내기 위해\n\nprint(sorted(arr)[0]) # 정렬 후 제일 앞의 값 출력","repo_name":"ruwan9/SSAFY","sub_path":"Baekjoon/fc/1302.py","file_name":"1302.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"43476714441","text":"import streamlit as st\n\n\ndef load_view():\n st.markdown(f\"

Welcome to LUPE B-SOiD

\"\n , unsafe_allow_html=True)\n st.write(\"---\")\n st.markdown(f\"

\"\n f\"LUPE X B-SOiD is a no code website for behavior analysis that \"\n f\"allows users to predict and analyze behavior using 2D pose estimation. \"\n f\"Its customized naming system fits experimental contexts, \"\n f\"while detailed analysis and reactive visualization design help identify trends. \"\n f\"Downloadable CSV files make integration with existing workflows easy.

\"\n , unsafe_allow_html=True)\n # desc_box = st.expander('Description', expanded=True)\n # desc_box.write(\"LUPE B-SOiD is an automated analysis pipeline.\")\n bottom_cont = st.container()\n with bottom_cont:\n st.markdown(\"\"\"---\"\"\")\n st.markdown(f\"

\"\n f\"LUPE B-SOiD is developed by Alexander Hsu and Justin James

\"\n , unsafe_allow_html=True)","repo_name":"runninghsus/lupe-bsoid-cloud","sub_path":"steps/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"40563952696","text":"\"\"\"\nContains utility functions for training and saving model\n\"\"\"\nimport torch\nfrom pathlib import Path\n\ndef save_model(model, save_dir, model_name, epoch, optimizer, loss):\n \"\"\"\n Saves model checkpoint\n\n Args:\n model (torch.nn.Module): Model to be saved\n save_dir (str): Directory to save model\n model_name (str): Name of model\n epoch (int): Epoch number\n optimizer (torch.optim.Optimizer): Optimizer\n loss (float): Loss value\n\n Returns:\n None\n \"\"\"\n save_dir = Path(save_dir)\n save_dir.mkdir(exist_ok=True, parents=True)\n save_path = save_dir / f'{model_name}_epoch{epoch}_loss{loss}.pth'\n torch.save({\n 'epoch': epoch,\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'loss': loss,\n }, save_path)\n print(f'[INFO] Model saved to {save_path}')\n","repo_name":"HangenYuu/SeeFood101","sub_path":"helper/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"4348321301","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 13 14:15:01 2018\nThis script stacks corridors.\n@author: pj276\n\"\"\"\n\n# Import packages\nimport gdal\nimport subprocess, sys, os, shapefile as shp\nimport glob\n# Append path to functions\nsys.path.append('/home/pj276/projects/ifl_corridors/code/functions/')\n# For hf_utilities, the modules are available within the functions\n# when they're used. Otherwise, one needs to prefix with hfu.\n# e.g. hfu.shp.Writer\nimport hf_utilities as hfu\nsys.path.append('/home/pj276/projects/ifl_corridors/code/parameter_files/')\n#import p1_10k_300k_060518 as p1\n#import p1_90m_110718_as as p1\n#import p1_90m_ifl_2013_sa as p1\nimport param_file as p1\n\n# Working directory\nodir = p1.odir\n### List of corridor rasters.\n##flist = p1.sdir + '/clist.txt'\n#flist = '/projects/above_gedi/pjantz/ifl_corridors_data/outputs/regular_points/rp10k300ks1/corridors/clist.txt'\nflist = glob.glob(odir + '/cfinal/flux/corr_*')\nflist = [x for x in flist if x.endswith('.tif')]\n\n# Job array index. Use this to select a feature from the polygon\nj = int(sys.argv[1])-1\n# Original index for numbering\nk = int(sys.argv[1])\n\n# Get polygon coordinate mins and maxes\nfnet = p1.fnet\nsf = shp.Reader(fnet)\nashape = sf.shapes()[j]\nxpts = [] # list to hold x coords\nypts = [] # list to hold y coords\n# Populate lists of x and y coords\nfor u in ashape.points:\n xpts.append(u[0])\n ypts.append(u[1])\n\n# Get mins and maxes\nxmin = str(min(xpts))\nxmax = str(max(xpts))\nymin = str(min(ypts))\nymax = str(max(ypts))\n \n#------------------------------\n# Write file list to text file\nwith open(odir + '/cfinal/flux/vrtlist_' + str(k) + '.txt', 'w') as text_file:\n for p in flist:\n text_file.write(p + '\\n')\n# Set output vrt name\nvrtcorr = odir + '/cfinal/flux/vrtcorr_' + str(k) + \".vrt\"\nif os.path.exists(vrtcorr):\n os.remove(vrtcorr)\n# Build vrt for tile area\nsubprocess.call([\"gdalbuildvrt\", \"-separate\", \"-te\", xmin, ymin, xmax, ymax, \"-input_file_list\", odir + '/cfinal/flux/vrtlist_' + str(k) + '.txt', vrtcorr])\n#corrarray = hfu.raster2array3d(vrtcorr)[0]\n\n# Check for no data values\n#nantest = np.isnan(corrarray).any()\n#corraray = None\n\n# If no no data values, calculate stats\n#if nantest == False:\nnewRasterfn = odir + '/cfinal/flux/sumcorr_' + str(k) + '.tif'\n#zz = hfu.tile_mosaic(fnet, vrtcorr, newRasterfn, j, 'sum')\nzz = hfu.tile_shingle(vrtcorr, newRasterfn, gdal.GDT_Float32, 'float32', 'sum')\n\n# Clean up\nos.remove(vrtcorr)\nos.remove(odir + '/cfinal/flux/vrtlist_' + str(k) + '.txt')\n","repo_name":"forest-rev/ifl_connectivity","sub_path":"scripts/hf2_stack_corridors.py","file_name":"hf2_stack_corridors.py","file_ext":"py","file_size_in_byte":2508,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"30529278980","text":"import sys\n\n\ndef isCorrect(line):\n tab = list(line)\n pileElementOpenned =[]\n for car in tab:\n if car==\"(\":\n pileElementOpenned.append(\"(\")\n elif car==\"[\":\n pileElementOpenned.append(\"[\")\n elif car==\")\":\n if len(pileElementOpenned)==0 or pileElementOpenned.pop() != \"(\":\n return False\n elif car==\"]\":\n if len(pileElementOpenned)==0 or pileElementOpenned.pop() != \"[\":\n return False\n \n return len(pileElementOpenned) == 0\n\n\n\nlines = sys.stdin.readlines()\nwhile lines[-1] == '\\n':\n del lines[-1]\n\nnumberOfLines = list(map(int,lines[0].split()))[0]\n\nfor i in range(1,numberOfLines+1):\n line = lines[i]\n if isCorrect(line):\n print(\"Yes\")\n else:\n print(\"No\")","repo_name":"FredericCanaud/UVaOnlineJudge","sub_path":"UVA-673/uva-673.py","file_name":"uva-673.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"23400407693","text":"import os\nimport shutil\n\n\n''' Задание_7\n✔ Создайте функцию для сортировки файлов по директориям: видео, изображения, текст и т.п.\n✔ Каждая группа включает файлы с несколькими расширениями.\n✔ В исходной папке должны остаться только те файлы, которые не подошли для сортировки.\n'''\n\ndef sort_files(directory):\n video_extensions = [\".mp4\", \".avi\", \".mkv\"]\n image_extensions = [\".jpg\", \".jpeg\", \".png\", \".gif\"]\n text_extensions = [\".txt\", \".docx\", \".pdf\"]\n \n video_dir = os.path.join(directory, \"Видео\")\n image_dir = os.path.join(directory, \"Изображения\")\n text_dir = os.path.join(directory, \"Тексты\")\n other_dir = os.path.join(directory, \"Прочие\")\n \n if not os.path.exists(video_dir):\n os.makedirs(video_dir)\n if not os.path.exists(image_dir):\n os.makedirs(image_dir)\n if not os.path.exists(text_dir):\n os.makedirs(text_dir)\n if not os.path.exists(other_dir):\n os.makedirs(other_dir)\n \n files = os.listdir(directory)\n \n for file in files:\n file_path = os.path.join(directory, file)\n \n if os.path.isfile(file_path):\n _, file_extension = os.path.splitext(file)\n \n if file_extension.lower() in video_extensions:\n shutil.move(file_path, video_dir)\n elif file_extension.lower() in image_extensions:\n shutil.move(file_path, image_dir)\n elif file_extension.lower() in text_extensions:\n shutil.move(file_path, text_dir)\n else:\n shutil.move(file_path, other_dir)\n\n# Пример использования функции\ndirectory = \"files_1\"\nsort_files(directory)\n","repo_name":"m1644/Seminar_07","sub_path":"Seminar/sem_07.py","file_name":"sem_07.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"73535028280","text":"from budget import BudgetManager\n\n\nfamilyBudget = BudgetManager(2500)\nfamilyBudget.add_budget(\"Groceries\",500)\nfamilyBudget.add_budget(\"Rent\",900)\nfamilyBudget.spend(\"Groceries\",35)\nfamilyBudget.spend(\"Groceries\", 15)\n\nfamilyBudget.print_summary()\n\nfamilyBudget.change_budget(\"Rent\", 1000)\nfamilyBudget.print_summary()\n\n","repo_name":"Davidjustice28/budget-manager","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"9786616289","text":"#python --version\n#pip install flask\nimport requests\n#import pokepy\nimport json\n\n\n\n# response=requests.get(\"https://pokeapi.co/api/v2/pokemon/ditto\")\n# print(response.status_code)\n\n# def jprint(obj):\n# # create a formatted string of the Python JSON object\n# text = json.dumps(obj, sort_keys=True, indent=4)\n# print(text)\n\n# jprint(response.json())\n\n\n#client = pokepy.V2Client()\n#client.get_pokemon()\n\n\nfrom flask import Flask, request, jsonify, render_template \nproject = Flask(__name__) \n\n\n\n@project.route(\"/\") \ndef index(): \n return render_template(\"index.html\")\n\n@project.route('/', methods=['GET', 'POST'])\ndef index_post():\n #Form that takes user variable from html and creates the url to send to the api\n variable = request.form['variable']\n urlBeforeString=\"https://pokeapi.co/api/v2/pokemon/\"+variable\n url=str(urlBeforeString)\n print(url)\n \n\n #Gets the url data from the api and prints the json data onto the post html page\n r = requests.get(url)\n pretty_json = json.loads(r.text)\n results4 = pretty_json[\"forms\"][0][\"name\"]\n if \"abilities\" in pretty_json:\n if pretty_json[\"abilities\"]==[]:\n ability1=\"none\"\n else:\n ability1=pretty_json[\"abilities\"][0][\"ability\"][\"name\"]\n else:\n ability1=pretty_json[\"abilities\"][0][\"ability\"][\"name\"]\n\n if \"moves\" in pretty_json:\n if pretty_json[\"moves\"]==[]:\n move1=\"none\"\n else:\n move1=pretty_json[\"moves\"][0][\"move\"][\"name\"] \n else:\n move1=pretty_json[\"moves\"][0][\"move\"][\"name\"]\n return render_template(\"index_post.html\", pretty_json=pretty_json, results4=results4, ability1=ability1, move1=move1)\n\n\nif __name__==\"__main__\":\n project.run(debug=True) \n\n \n\n#print(\"Results for: \" + pretty_json.forms.name)\n #print (json.dumps(pretty_json, sort_keys=True, indent=4))\n # print(response)\n #def jprint(obj):\n #text = json.dumps(obj, sort_keys=True)\n #print(text)\n #jprint(response.json())","repo_name":"moore-brandon4/Group-2-API-Project","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"6651693045","text":"__author__ = 'RRuetz'\nimport datetime as dt\n\n\nclass Timer(object):\n\n def __init__(self, start=False):\n self.startTime = None\n self.endTime = None\n self.delta = None\n self.marks = {}\n if start:\n self.start()\n\n def start(self):\n self.startTime = dt.datetime.now()\n self.marks['start'] = self.startTime\n\n def stop(self):\n if self.startTime is not None:\n self.endTime = dt.datetime.now()\n self.delta = self.get_delta(self.startTime, self.endTime)\n else:\n print(\"Timer has not been started yet.\")\n\n def check(self):\n \"\"\"\n returns a datetime.timedelta object that represents the elapsed time since the Timer started\n \"\"\"\n if self.startTime is not None:\n return dt.datetime.now() - self.startTime\n else:\n print(\"Timer has not been started yet.\")\n\n @staticmethod\n def get_delta(startTime, endTime):\n if endTime is not None and startTime is not None:\n delta = endTime - startTime\n return delta\n else:\n print(r\"No delta can been established. Did you forget to start and/or stop your timer?\")\n\n def to_string(self):\n if self.delta is not None:\n return \"{0}\".format(self.delta.seconds * 1000 + self.delta.microseconds / 1000)\n else:\n print(r\"No time delta has been established. Did you forget to start and/or stop your timer?\")\n\n def mark(self, name):\n \"\"\"\n Allows user to mark smaller increments of time within a timer span.\n \"\"\"\n t = dt.datetime.now()\n mark = Timer()\n mark.startTime = self.marks.get('last', None)\n if mark.startTime is None:\n mark.startTime = self.startTime\n mark.endTime = t\n mark.delta = mark.endTime - mark.startTime\n self.marks[name] = mark\n self.marks['last'] = mark.endTime\n\n# a global timer that we start at the beginning of operations. can be imported and interacted with across the project.\nGLOBAL_TIMER = Timer()\n","repo_name":"robertruetz/KafkaSpeedTestPython","sub_path":"instrumentation.py","file_name":"instrumentation.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"10103918080","text":"\"\"\"Creates a bigquery dataset.\"\"\"\n# gcloud deployment-manager deployments create bigquery-backup-dataset --template create-bigquery-dataset-template.py --properties streamId:backup,location:EU\n\ndef AlphaNum(stream):\n return \"\".join([ c if c.isalnum() else \"\" for c in stream ])\n\ndef GenerateConfig(context):\n \"\"\"Generate configuration.\"\"\"\n\n resources = []\n\n# BigQuery dataset to store entities from processor pipeline\n resources.append({\n 'name': 'bigquery-dataset-' + AlphaNum(context.properties['streamId']) + '-entities', #bigquery-dataset-ua123456789-entities\n 'type': 'bigquery.v2.dataset',\n 'properties': {\n 'datasetReference': {\n 'datasetId': AlphaNum(context.properties['streamId'])\n },\n 'location': context.properties['location']\n }\n })\n\n return {'resources': resources}","repo_name":"mhlabs/datahem.infrastructor","sub_path":"python/create-bigquery-dataset-template.py","file_name":"create-bigquery-dataset-template.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"10709245937","text":"from flask import Flask,request\nfrom twilio.twiml.messaging_response import Message, MessagingResponse\nimport datetime\nfrom xmlrpc.client import _strftime\n\nurl = (\"http://napstalimited.bravesites.com/files/resized/584615/250;333;9637983905496e372b26bae8f6a55045315b071c.jpg\")\n \nappbot=Flask(__name__)\n@appbot.route(\"/sms\", methods=[\"get\",\"post\"])\ndef reply():\n msg = request.form.get(\"Body\")\n msg1 = request.form.get(\"From\")\n #greet = [\"hello\"or\"holla\"or\"hyy\"or\"wadup\"or\"sup\"or\"xup\"or\"hey\"or\"heyy\"]\n resp=MessagingResponse() \n \n if(msg.lower() == 'hello' or msg.lower() == 'holla' or msg.lower() == 'hyy' or msg.lower() == 'wadup' or msg.lower() == 'sup' or msg.lower() == 'xup' or msg.lower() == 'hey' or msg.lower() == 'heyy'):\n loo = resp.message(msg.capitalize() + \", Welcome to Napsta Hotel.\\nHow can I help you?\")\n loo.media(url) \n \n else:\n loo = resp.message(\"Do not understand the input\") \n\n dt=datetime.datetime.now().strftime(\"%d %h %Y\")\n data=msg+\", \"+msg1+\", \"+dt \n print(\"Messg: \"+ msg +\" From \"+ msg1 + \" on \" + dt)\n return(str(resp))\n \n\nif (__name__==\"__main__\"): \n appbot.run()\n\n\n\n","repo_name":"Napsta46/Whatsapp-bot","sub_path":"whatsappbot.py","file_name":"whatsappbot.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"13228151238","text":"while True:\r\n inicio = input('VOCÊ QUER GERAR UM CPF? [s]im [n]ão: ')\r\n\r\n if inicio == 's':\r\n import random\r\n\r\n nove_digitos = ''\r\n for i in range(9):\r\n nove_digitos += str(random.randint(0, 9))\r\n \r\n contador_regresivo_1 = 10\r\n\r\n resultado_dig1 = 0\r\n for digito in nove_digitos:\r\n resultado_dig1 += int(digito) * contador_regresivo_1\r\n contador_regresivo_1 -= 1\r\n digito_1 = ((resultado_dig1 * 10) % 11)\r\n digito_1 = digito_1 if digito_1 <= 9 else 0\r\n\r\n dez_digitos = nove_digitos + str(digito_1)\r\n contador_regresivo_2 = 11\r\n\r\n resultado_dig2 = 0\r\n for digito in dez_digitos:\r\n resultado_dig2 += int(digito) * contador_regresivo_2\r\n contador_regresivo_2 -= 1\r\n digito_2 = ((resultado_dig2 * 10) % 11)\r\n digito_2 = digito_2 if digito_2 <= 9 else 0\r\n\r\n cpf_gerado = f'{nove_digitos}{digito_1}{digito_2}'\r\n\r\n print(cpf_gerado)\r\n\r\n elif inicio == 'n':\r\n print('OK')\r\n\r\n else:\r\n print('POR FAVOR DIGITE s OU n')\r\n continue","repo_name":"JoaoSantana4/Curso-Python-Introducao","sub_path":"atividade015.py","file_name":"atividade015.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"16516366977","text":"from django.urls import path,include\nfrom . import views\nfrom rest_framework_swagger.views import get_swagger_view\n\nschema_view = get_swagger_view(title='API')\n\n\n\nurlpatterns = [\n path('', views.start, name='start'),\n path('post_list/',views.post_list,name='post_list'),\n path('create_post/',views.create_post,name='create_post'),\n # path('post//comment/', views.add_comment_to_post, name='add_comment_to_post'),\n path('post//comment/',views.create_comment,name='create_comment'),\n path('search/',views.search,name='search'),\n path('friends/',views.friends_list,name='friends_list'),\n path(r'^connect/(?P.+)/(?P\\d+)/$', views.change_friends, name='change_friends'),\n path('likes/',views.like_post, name='like_post'),\n\n path('api/', views.PostList.as_view()),\n path('api//', views.PostDetail.as_view()),\n path('api/comment/', views.CommentList.as_view()),\n path('api/comment//', views.CommentDetail.as_view()),\n # path('post/', views.PostList.as_view()),\n # path('post//', views.PostDetail.as_view()),\n # path('comment/', views.CommentList.as_view()),\n # path('comment//', views.CommentDetail.as_view()),\n \n path('list/', schema_view)\n\n]","repo_name":"suryakalakuruva/GD","sub_path":"fb/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"25293858415","text":"from django.urls import path, re_path\nfrom . import views\n\nurlpatterns = [\n path('', views.search_subjects, name='allsubjects'),\n path('search/', views.search_subjects, name='search'),\n path('search_results/', views.search_results, name='search_results'),\n path('search_selection/', views.search_selection, name='search_selection'),\n path('convert_builder/', views.convert_subjects, name='convert_builder'),\n path('convert/', views.convert, name='convert'),\n path('convert_builder/', views.create_dcm2bids_config, name='create_dcm2bids_config'),\n]\n\n# Here we launch our indexer\n","repo_name":"DCAN-Labs/dicom-harpooner","sub_path":"dicoms/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"7084904095","text":"\nimport numpy as np\nimport matplotlib.pyplot as pyplot\n\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.losses import binary_crossentropy\nfrom tensorflow.keras.optimizers import Adam\n\ndevice = tf.device(\"/GPU:0\")\ndef select_gpu():\n if tf.device(\"/GPU:0\"):\n device = tf.device(\"/GPU:0\")\n \ndef gan(gen, dis):\n with device:\n dis.trainable = False\n \n model = Sequential()\n model.add(gen)\n model.add(dis)\n\n model.compile(loss= 'binary_crossentropy', optimizer='adam')\n return model\n\ndef load_real_data():\n (X,_), (_,_) = tf.keras.datasets.mnist.load_data()\n X = np.expand_dims(X, axis=-1)\n X = X.astype('float32')\n X = X/255.0\n\n return X \n\ndef generate_real_sample(n_samples):\n dataset = load_real_data()\n ix = np.random.randint(0, dataset.shape[0], n_samples)\n X = dataset[ix]\n y = np.ones((n_samples, 1))\n return X,y\n\ndef get_latent_points(latent_dim, n_samples):\n x = np.random.randn(latent_dim*n_samples)\n x = x.reshape(n_samples, latent_dim)\n return x\n\ndef generate_fake_sample(g_model, latent_dim, n_samples):\n x = get_latent_points(latent_dim, n_samples)\n output = g_model.predict(x)\n y = np.zeros((n_samples, 1))\n return output, y\n\ndef save_plot(examples, epoch, n=10):\n for i in range(n * n):\n # define subplot\n pyplot.subplot(n, n, 1 + i)\n # turn off axis\n pyplot.axis('off')\n # plot raw pixel data\n pyplot.imshow(examples[i, :, :, 0], cmap='gray_r')\n # save plot to file\n filename = 'generated_plot_e%03d.png' % (epoch+1)\n pyplot.savefig(filename)\n pyplot.close()\n\ndef summarize_performance(epoch, g_mod, d_mod, dataset, latent_dim, n_samples=100):\n x_real, y_real = generate_real_sample(n_samples)\n x_fake, y_fake = generate_fake_sample(g_mod, latent_dim, n_samples)\n\n _, real_acc = d_mod.evaluate(x_real, y_real)\n _, fake_acc = d_mod.evaluate(x_fake, y_fake)\n\n print(f\"Accuracy: real: {real_acc*100}, fake: {fake_acc*100}\")\n save_plot(x_fake, epoch)\n save_plot(x_fake, epoch)\n filename = 'generator_model_%03d.h5' % (epoch + 1)\n g_mod.save(filename)\n \ndef train(g_model, d_model, gan, dataset, latent_dim, epochs=100, n_batch=256):\n with device: \n batch_per_epoch = int(dataset.shape[0]/ n_batch)\n half_batch = int(n_batch/2)\n\n for epoch in range(epochs):\n for batch in range(batch_per_epoch):\n x_real, y_real = generate_real_sample(half_batch)\n x_fake, y_fake = generate_fake_sample(g_model, latent_dim, n_samples=half_batch)\n\n x, y = np.vstack((x_real, x_fake)), np.vstack((y_real, y_fake))\n d_loss ,_ = d_model.train_on_batch(x,y)\n\n x_gan = get_latent_points(100, n_batch)\n y_gan = np.ones((n_batch,1))\n gan_loss= gan.train_on_batch(x_gan,y_gan)\n\n print('>%d, %d/%d, d=%.3f, g=%.3f' % (epoch+1, batch+1, batch_per_epoch, d_loss, gan_loss))\n\n if (epoch+1)%10 == 0:\n summarize_performance(epoch, g_model, d_model, dataset, latent_dim)\n \n\n","repo_name":"Dr-Doofensmirtz/utils","sub_path":"gan_util.py","file_name":"gan_util.py","file_ext":"py","file_size_in_byte":3011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"24756495878","text":"# Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.\n\n# Note: You can only move either down or right at any point in time.\n\n\nclass Solution:\n def minPathSum(self, grid: List[List[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n row = []\n for i in range(n):\n row.append(sum(grid[-1][i:]))\n for i in range(m-2, -1, -1):\n new_row = grid[i]\n for j in range(n-1, -1, -1):\n if j != n-1:\n new_row[j] += min(row[j], new_row[j+1])\n else:\n new_row[j] += row[j]\n row = new_row\n return row[0]\n","repo_name":"YingcongYu/LeetCode","sub_path":"Algorithms/64. Minimum Path Sum - Method 1.py","file_name":"64. Minimum Path Sum - Method 1.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"24891506981","text":"from logging import NullHandler\nimport os\nfrom starlette.responses import JSONResponse\n\nimport uvicorn\nfrom dotenv import load_dotenv\nfrom fastapi import FastAPI\nfrom fastapi_sqlalchemy import DBSessionMiddleware, db\n\nfrom models import Datasets\nfrom models import Datasets as ModelDatasets\nfrom schema import Dataset_table as SchemaDataset_table\nfrom schema import evaluation_model \nfrom schema import Message\n\nload_dotenv(\".env\")\n\napp = FastAPI()\n\napp.add_middleware(DBSessionMiddleware, db_url=\"postgresql+psycopg2://postgres:password@db:5432/db\")\n\n@app.get(\"/\")\nasync def root():\n return {\"message\": \"Hello World\"}\n\n@app.post(\"/add_data/\", responses={404: {\"model\": Message}})\ndef add_data(data_entry: SchemaDataset_table):\n db_data = ModelDatasets(url=data_entry.url, evaluation=data_entry.evaluation)\n try:\n if db_data.url == \"test_url\":\n filler = \"filler\"\n else:\n db.session.add(db_data)\n db.session.commit()\n except:\n return JSONResponse(status_code=404, content={\"error\": \"url combination already exists in database\"})\n return JSONResponse(status_code=200, content={\"success\": \"Data was added to Database\"})\n\n@app.put(\"/update/\", responses={404: {\"model\": Message}})\ndef update_data(url: str, evaluation: str):\n try:\n query = db.session.query(Datasets).filter(\n Datasets.url == url\n ).first()\n query.evaluation = evaluation\n db.session.commit()\n except:\n return JSONResponse(status_code=404, content={\"error\": \"Data could not be updated for some reason\"})\n return JSONResponse(status_code=200, content={\"success\": \"Data was updated\"})\n\n@app.delete(\"/delete/\", responses={404: {\"model\": Message}})\ndef delete_book(url: str):\n try:\n db.session.query(Datasets).filter(\n Datasets.url == url\n ).delete()\n db.session.commit()\n except:\n return JSONResponse(status_code=404, content={\"error\": \"Data could not be deleted for some reason\"})\n return JSONResponse(status_code=200, content={\"success\": \"Data was deleted\"})\n\n@app.get(\"/get_data/\", response_model = evaluation_model, responses={404: {\"model\": Message}})\ndef get_data(url: str):\n query = db.session.query(Datasets).filter(\n Datasets.url == url\n ).first() \n if query != None:\n return query\n else:\n return JSONResponse(status_code=404, content={\"error\": \"Data could not be retrieved\"})\n\n@app.get(\"/get_all_data/\", responses={404: {\"model\": Message}})\ndef get_all_data():\n StoredData = db.session.query(Datasets).all()\n if len(StoredData) >= 1:\n return StoredData\n else:\n return JSONResponse(status_code=404, content={\"error\": \"Data could not be retrieved\"})\n\n\nif __name__ == \"__main__\":\n uvicorn.run(app, host=\"0.0.0.0\", port=8003)","repo_name":"Adilius/DIGG_ML-AI_API","sub_path":"db-service/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2838,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"16809738382","text":"\"\"\"\nDjango settings for backend project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/2.2/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/2.2/ref/settings/\n\"\"\"\nimport os\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\n# Version number\nVERSION = '0.0.14'\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = '-!v282$zj815_q@htaxcubylo)(l%a+k*-xi78hw*#s2@i86@_'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nALLOWED_HOSTS = [\n 'localhost',\n '127.0.0.1',\n '0.0.0.0'\n]\n\n# Needed for webauthn (this is a setting in case the application runs behind a proxy)\nHOSTNAME = 'localhost'\nBASE_URL = 'http://localhost:8000'\n\n# Application definition\n\nINSTALLED_APPS = [\n 'cms.apps.CmsConfig',\n 'gvz_api.apps.GvzApiConfig',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.messages',\n 'django.contrib.sessions',\n 'django.contrib.staticfiles',\n 'compressor',\n 'compressor_toolkit',\n 'corsheaders',\n 'widget_tweaks',\n 'easy_thumbnails',\n 'filer',\n 'mptt',\n 'rules.apps.AutodiscoverRulesConfig',\n]\n\nMIDDLEWARE = [\n 'corsheaders.middleware.CorsMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n 'corsheaders.middleware.CorsMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'backend.urls'\nTHUMBNAIL_HIGH_RESOLUTION = True\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n 'backend.context_processors.region_slug_processor',\n ],\n 'debug': DEBUG,\n },\n },\n]\n\nWSGI_APPLICATION = 'backend.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/2.2/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': 'integreat',\n 'USER': 'integreat',\n 'PASSWORD': 'password',\n 'HOST': 'localhost',\n 'PORT': '5432',\n }\n}\n\n# Directory for initial database contents\n\nFIXTURE_DIRS = (\n os.path.join(BASE_DIR, 'cms/fixtures/'),\n)\n\n# Authentication backends\n\nAUTHENTICATION_BACKENDS = (\n 'rules.permissions.ObjectPermissionBackend',\n 'django.contrib.auth.backends.ModelBackend', # this is default\n)\n\n\n# Password validation\n# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/2.2/topics/i18n/\n\nLANGUAGES = (\n ('en-us', 'English'),\n ('de-de', 'Deutsch'),\n)\n\nLOCALE_PATHS = (\n os.path.join(BASE_DIR, 'locale'),\n)\n\nLANGUAGE_CODE = 'de-de'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/2.2/howto/static-files/\n\nSTATICFILES_DIRS = [\n os.path.join(BASE_DIR, \"../node_modules\"),\n]\nSTATIC_URL = '/static/'\nSTATIC_ROOT = os.path.join(BASE_DIR, 'cms/static/')\n\nCORS_ORIGIN_WHITELIST = (\n 'http://localhost:3000',\n)\n\n\n# Login\nLOGIN_URL = '/login'\nLOGIN_REDIRECT_URL = '/'\nLOGOUT_REDIRECT_URL = '/login'\n\n# Miscellaneous\nEMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\nCSRF_FAILURE_VIEW = 'cms.views.error_handler.csrf_failure'\n\nMEDIA_URL = '/media/'\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\nFILER_CANONICAL_URL = 'media/'\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'handlers': {\n 'console': {\n 'class': 'logging.StreamHandler'\n },\n },\n 'loggers': {\n 'django': {\n 'handlers': ['console'],\n 'level': 'WARN',\n 'propagate': True,\n },\n 'api': {\n 'handlers': ['console'],\n 'level': 'INFO',\n 'propagate': True,\n },\n 'cms': {\n 'handlers': ['console'],\n 'level': 'INFO',\n 'propagate': True,\n },\n 'rules': {\n 'handlers': ['console'],\n 'level': 'DEBUG',\n 'propagate': True,\n },\n }\n}\n\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n 'compressor.finders.CompressorFinder',\n)\n\nCOMPRESS_CSS_FILTERS = [\n 'compressor.filters.css_default.CssAbsoluteFilter',\n 'compressor.filters.cssmin.CSSMinFilter',\n 'compressor.filters.template.TemplateFilter'\n]\nCOMPRESS_JS_FILTERS = [\n 'compressor.filters.jsmin.JSMinFilter',\n]\nCOMPRESS_PRECOMPILERS = (\n ('module', 'compressor_toolkit.precompilers.ES6Compiler'),\n ('css', 'compressor_toolkit.precompilers.SCSSCompiler'),\n)\nCOMPRESS_ENABLED = True\nCOMPRESS_OFFLINE = True\n\n# GVZ (Gemeindeverzeichnis) API URL\nGVZ_API_URL = \"http://gvz.integreat-app.de/api/\"\nGVZ_API_ENABLED = True\n\n# Allow access to all domains by setting the following variable to TRUE\nCORS_ORIGIN_ALLOW_ALL = True\n\n# Extend default headers with development header to differenciate dev traffic in statistics\nCORS_ALLOW_HEADERS = [\n 'accept',\n 'accept-encoding',\n 'authorization',\n 'content-type',\n 'dnt',\n 'origin',\n 'user-agent',\n 'x-csrftoken',\n 'x-requested-with',\n 'x-integreat-development',\n]\n","repo_name":"digitalfabrik/coldaid-backend","sub_path":"src/backend/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":6645,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"40"} +{"seq_id":"10787113365","text":"# Time: O(n)\n# Space: O(1)\n\nfrom itertools import izip # Generator version of zip.\n\nclass Solution(object):\n def isIsomorphic(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n if len(s) != len(t):\n return False\n\n s2t, t2s = {}, {}\n for p, w in izip(s, t):\n if w not in s2t and p not in t2s:\n s2t[w] = p\n t2s[p] = w\n elif w not in s2t or s2t[w] != p:\n # Contradict mapping.\n return False\n return True\n\n\n# Time: O(n)\n# Space: O(1)\nclass Solution2(object):\n def isIsomorphic(self, s, t):\n if len(s) != len(t):\n return False\n\n return self.halfIsom(s, t) and self.halfIsom(t, s)\n\n def halfIsom(self, s, t):\n lookup = {}\n for i in xrange(len(s)):\n if s[i] not in lookup:\n lookup[s[i]] = t[i]\n elif lookup[s[i]] != t[i]:\n return False\n return True\n\n","repo_name":"kamyu104/LeetCode-Solutions","sub_path":"Python/isomorphic-strings.py","file_name":"isomorphic-strings.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","stars":4314,"dataset":"github-code","pt":"40"} +{"seq_id":"71215360761","text":"import copy\nfrom src.modules.update_exercise.app.update_exercise_usecase import UpdateExerciseUsecase\nfrom src.shared.infra.repositories.exercise_repository_mock import ExerciseRepositoryMock\nfrom fastapi import HTTPException\nimport pytest\n\nclass Test_UpdateExerciseUsecase:\n def test_update_exercise_usecase(self):\n repo = ExerciseRepositoryMock()\n usecase = UpdateExerciseUsecase(repo)\n exercise_id = repo.get_all_exercises()[0].exercise_id\n old_exercise = copy.deepcopy(repo.get_exercise_by_id(exercise_id)) \n\n updated_exercise = usecase(exercise_id, new_title=\"Quem inventou o Linux?\", new_enunciado=\"Quem inventou o Linux?\", new_creation_date=1673319600000, new_expiration_date=1676084400000, new_correct_answer=\"Linus Torvalds\")\n \n assert old_exercise != updated_exercise\n assert repo.get_exercise_by_id(exercise_id) == updated_exercise\n \n def test_update_exercise_usecase_with_nonexistent_exercise(self):\n repo = ExerciseRepositoryMock()\n usecase = UpdateExerciseUsecase(repo)\n exercise_id = \"notfound\"\n \n with pytest.raises(HTTPException) as exc:\n usecase(exercise_id, new_title=\"Quem inventou o Linux?\", new_enunciado=\"Quem inventou o Linux?\", new_creation_date=1673319600000, new_expiration_date=1676084400000, new_correct_answer=\"Linus Torvalds\")\n assert exc.value.status_code == 404\n assert exc.value.detail == \"Exercise not found\"","repo_name":"Lucasdvs10/Projeto-Integrador-2023.2","sub_path":"tests/modules/update_exercise/app/test_update_exercise_usecase.py","file_name":"test_update_exercise_usecase.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"12299773059","text":"class BootCampTask(QCAlgorithm):\n\n def Initialize(self):\n \n self.SetStartDate(2018, 12, 1) \n self.SetEndDate(2019, 4, 1) \n self.SetCash(100000) \n spy = self.AddEquity(\"SPY\", Resolution.Daily)\n spy.SetDataNormalizationMode(DataNormalizationMode.Raw)\n self.lastOrderEvent = None\n \n def OnData(self, data):\n \n if not self.Portfolio.Invested:\n self.MarketOrder(\"SPY\", 500)\n self.StopMarketOrder(\"SPY\", -500, 0.9 * self.Securities[\"SPY\"].Close)\n \n def OnOrderEvent(self, orderEvent):\n \n #1. Write code to only act on fills\n #2. Save the orderEvent to lastOrderEvent, use Debug to print the event OrderId\n \n if orderEvent.Status == OrderStatus.Filled:\n self.lastOrderEvent = orderEvent\n self.Debug(orderEvent.OrderId)","repo_name":"fintech07/QuantConnect","sub_path":"Boot Camp/Py/Algorithmic Trading 101/Buy and Hold with a Trailing Stop/Understanding Order Events/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"40"} +{"seq_id":"37747426007","text":"from typing import List\n\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport plotly.graph_objs as go\nimport plotly.io as pio\nimport numpy as np\nimport pandas as pd\nimport os\n\nfrom commons.tools.basicFunctions import symmetrical, get_mean_over_all_chains, compute_error, significance_color\n\n\ndef plot_network(G, figname):\n # Creates a copy of the graph\n H = G.copy()\n\n # crates a list for edges and for the weights\n edges, weights = zip(*nx.get_edge_attributes(H, 'weight').items())\n\n # calculates the degree of each node\n d = nx.degree(H)\n # creates list of nodes and a list their degrees that will be used later for their sizes\n nodelist, node_sizes = zip(*dict(d).items())\n\n # positions\n positions = nx.circular_layout(H)\n\n # Figure size\n plt.figure(figsize=(15, 15))\n\n # draws nodes\n nx.draw_networkx_nodes(H, positions, node_color='#DA70D6', nodelist=nodelist,\n # the node size will be now based on its degree\n node_size=tuple([x ** 3 for x in node_sizes]), alpha=0.8)\n\n # Styling for labels\n nx.draw_networkx_labels(H, positions, font_size=8,\n font_family='sans-serif')\n\n # draws the edges\n nx.draw_networkx_edges(H, positions, edge_list=edges, style='solid',\n # adds width=weights and edge_color = weights\n # so that edges are based on the weight parameter\n # edge_cmap is for the color scale based on the weight\n # edge_vmin and edge_vmax assign the min and max weights for the width\n width=weights, edge_color=weights, edge_cmap=plt.cm.PuRd,\n edge_vmin=min(weights), edge_vmax=max(weights))\n\n dc = nx.degree_centrality(G)\n a1, a2 = zip(*dc.items())\n\n # displays the graph without axis\n plt.axis('off')\n # saves image\n plt.savefig(figname + '.svg', format='svg', dpi=1200)\n # , plt.show()\n return np.argmax(a2)\n\n\ndef plot_connectivity(method: str, epochs: List[str], parent_path: str, chain_number: List[int], minn: float, maxx: float) -> None:\n \"\"\"\n Network Connectivity heatmap based on connectivity method\n :param method: Functional connectivity method - Correlation, MutualInformation, Hawkes\n :param epochs: all List of all combination of epochs and conditions\n :param parent_path: Estimated MCMC connectivity measures based on different method path\n :param chain_number: Ordered list of chain numbers\n :param minn: min value of connectivity measure\n :param maxx: max value of connectivity measure\n \"\"\"\n for ep in epochs:\n\n read_path = parent_path + method + '/'\n write_path = parent_path + method + '/' + 'plot' + '/'\n\n if not os.path.exists(write_path):\n os.makedirs(write_path)\n\n rate = get_mean_over_all_chains(read_path, ep, chain_number)\n rate = np.array(symmetrical(rate))\n labels = list(map(lambda x: 'N' + str(x), np.arange(1, len(rate) + 1, 2)))\n plt.matshow(symmetrical(rate), vmin=minn, vmax=maxx, cmap=plt.cm.jet)\n ticks = np.arange(0, rate.shape[1], 2)\n plt.xticks(ticks, labels, rotation='vertical')\n plt.yticks(ticks, labels)\n plt.colorbar()\n plt.savefig(write_path + ep.split('.')[0] + '.svg', dpi=1000)\n plt.close()\n\n\ndef graph_centrality(data: pd.core.frame.DataFrame, cen_method: str, period: str, status: str, write_path: str) -> None:\n \"\"\"\n Network centrality plot with significance check\n :param data: long format centrality pandas data frame\n :param cen_method: centrality method - closeness_centrality, eigenvector_centrality, betweenness_centrality,\n harmonic_centrality, load_centrality\n :param period: epochs - Vis, Mem, Sac\n :param status: conditions - Stim, NoStim, diff\n :param write_path: save directory\n \"\"\"\n if not os.path.exists(write_path):\n os.makedirs(write_path)\n DF = data[(data.epoch.str.strip() == period + '-' + status)].groupby(['neuron', 'chain'], as_index=False, sort=False).mean()\n\n neuron_list = list(data['neuron'][0:23])\n # Create Error bar measure based on .95 confidence interval\n error_bar_measure = list(map(lambda x: compute_error(DF, x, cen_method), neuron_list))\n colorList = list(map(lambda x: significance_color(DF, x, cen_method, 0.05), neuron_list))\n\n # Create grouped data frame on neuron and take average on all measures\n DF_grouped = DF.groupby(['neuron'], as_index=False, sort=False).mean()\n\n trace0 = go.Bar(\n x=DF_grouped.loc[:, 'neuron'],\n y=DF_grouped.loc[:, cen_method],\n error_y=dict(\n type='data',\n array=error_bar_measure,\n visible=True\n ),\n marker=dict(\n color=colorList),\n )\n\n data = [trace0]\n layout = go.Layout(\n width=1350,\n height=752,\n barmode='group')\n\n fig = go.Figure(data=data, layout=layout)\n\n # Axis Config\n fig.update_xaxes(tickangle=45, tickfont=dict(family='Rockwell', color='crimson', size=35))\n fig.update_yaxes(tickfont=dict(family='Rockwell', color='crimson', size=35))\n\n pio.write_image(fig, write_path + str(cen_method) + '__' + str(period) + '-' + str(status) + '.svg')\n\n\ndef information_assembly(data: pd.core.frame.DataFrame, info_method: str, period: str, status: str, in_out: str,\n write_path: str) -> None:\n \"\"\"\n Network averaged information in neurons assemble based on correlation and mutual information with significance check\n :param data: long format information pandas data frame\n :param info_method: connectivity information method - correlation or mutual information\n :param period: epochs - Vis, Mem, Sac\n :param status: conditions - Stim, NoStim, diff\n :param in_out: in/out receptive field\n :param write_path: save directory\n \"\"\"\n if not os.path.exists(write_path):\n os.makedirs(write_path)\n\n DF = data[(data.epoch.str.strip() == period + '-' + status) &\n (data['in/out'] == in_out) &\n (data.method.str.strip() == info_method)]\n\n\n trace0 = go.Bar(\n x=DF.loc[:, 'lag'],\n y=DF.loc[:, 'info'],\n error_y=dict(\n type='data',\n array=DF.loc[:, 'SEM'],\n visible=True\n ),\n marker=dict(\n color=DF.loc[:, 'colorList']),\n )\n\n data = [trace0]\n layout = go.Layout(\n width=1350,\n height=752,\n barmode='group')\n\n fig = go.Figure(data=data, layout=layout)\n\n # Axis Config\n fig.update_xaxes(tickangle=45, dtick=10, tickfont=dict(family='Rockwell', color='crimson', size=35))\n fig.update_yaxes(tickfont=dict(family='Rockwell', color='crimson', size=35))\n\n pio.write_image(fig, write_path + str(info_method) + '__' + str(period) + '-' + str(in_out) + '-' +\n str(status) + '.svg')\n\n \ndef plot_all_cen(data: pd.core.frame.DataFrame, method: str, write_path) -> None:\n \"\"\"\n Plot graph centrality for all epochs and conditions\n :param data: long format centrality pandas data frame\n :param method: centrality method - closeness_centrality, eigenvector_centrality, betweenness_centrality,\n harmonic_centrality, load_centrality\n :param write_path: save directory\n \"\"\"\n graph_centrality(data, method, 'Vis', 'NoStim', write_path)\n graph_centrality(data, method, 'Mem', 'NoStim', write_path)\n graph_centrality(data, method, 'Sac', 'NoStim', write_path)\n\n graph_centrality(data, method, 'Vis', 'Stim', write_path)\n graph_centrality(data, method, 'Mem', 'Stim', write_path)\n graph_centrality(data, method, 'Sac', 'Stim', write_path)\n\n graph_centrality(data, method, 'Vis', 'diff', write_path)\n graph_centrality(data, method, 'Mem', 'diff', write_path)\n graph_centrality(data, method, 'Sac', 'diff', write_path)\n\n\ndef plot_all_info(data: pd.core.frame.DataFrame, method: str, write_path) -> None:\n \"\"\"\n Plot graph centrality for all epochs and conditions\n :param data: long format information pandas data frame\n :param method: connectivity information method - correlation or mutual information\n :param write_path: save directory\n \"\"\"\n information_assembly(data, method, 'Vis', 'NoStim', 'In', write_path)\n information_assembly(data, method, 'Mem', 'NoStim', 'In', write_path)\n information_assembly(data, method, 'Sac', 'NoStim', 'In', write_path)\n information_assembly(data, method, 'Vis', 'NoStim', 'Out', write_path)\n information_assembly(data, method, 'Mem', 'NoStim', 'Out', write_path)\n information_assembly(data, method, 'Sac', 'NoStim', 'Out', write_path)\n\n information_assembly(data, method, 'Vis', 'Stim', 'In', write_path)\n information_assembly(data, method, 'Mem', 'Stim', 'In', write_path)\n information_assembly(data, method, 'Sac', 'Stim', 'In', write_path)\n information_assembly(data, method, 'Vis', 'Stim', 'Out', write_path)\n information_assembly(data, method, 'Mem', 'Stim', 'Out', write_path)\n information_assembly(data, method, 'Sac', 'Stim', 'Out', write_path)\n\n information_assembly(data, method, 'Vis', 'Diff', 'In', write_path)\n information_assembly(data, method, 'Mem', 'Diff', 'In', write_path)\n information_assembly(data, method, 'Sac', 'Diff', 'In', write_path)\n information_assembly(data, method, 'Vis', 'Diff', 'Out', write_path)\n information_assembly(data, method, 'Mem', 'Diff', 'Out', write_path)\n information_assembly(data, method, 'Sac', 'Diff', 'Out', write_path)\n\n\ndef graph_indexes_grouped_bar(df: pd.core.frame.DataFrame, file_name: str, leg: bool) -> None:\n \"\"\"\n\n :param df: Filtered centrality data frame based on conditions - Stim, NoStim, diff\n :param file_name: file name to write\n :param leg: whether legend is visible or not\n \"\"\"\n filt = lambda st, data_list: list(filter(lambda x: st in x, data_list))[0]\n columnList = ['average_shortest_path', 'average_clustering', 'density', 'sigma']\n\n colls = df.loc[:, 'epoch'].unique()\n x_axis_names = [filt(\"Vis\", colls), filt(\"Mem\", colls), filt(\"Sac\", colls)]\n\n trace1 = go.Bar(\n x=list(map(lambda x: x.split(\"-\")[0], x_axis_names)),\n y=list(map(lambda x: df[(df.epoch == x)][columnList[0]].mean(), x_axis_names)),\n name=columnList[0].replace(\"_\", \" \"),\n error_y=dict(\n type='data',\n array=list(map(lambda x: 1.96 * (\n df[(df.epoch == x)][columnList[0]].std() / df[(df.epoch == x)][columnList[0]].size),\n x_axis_names)),\n visible=True\n )\n )\n trace2 = go.Bar(\n x=list(map(lambda x: x.split(\"-\")[0], x_axis_names)),\n y=list(map(lambda x: df[(df.epoch == x)][columnList[1]].mean(), x_axis_names)),\n name=columnList[1].replace(\"_\", \" \"),\n error_y=dict(\n type='data',\n array=list(map(lambda x: 1.96 * (\n df[(df.epoch == x)][columnList[1]].std() / df[(df.epoch == x)][columnList[1]].size),\n x_axis_names)),\n visible=True\n )\n )\n trace3 = go.Bar(\n x=list(map(lambda x: x.split(\"-\")[0], x_axis_names)),\n y=list(map(lambda x: df[(df.epoch == x)][columnList[2]].mean(), x_axis_names)),\n name=columnList[2].replace(\"_\", \" \"),\n error_y=dict(\n type='data',\n array=list(map(lambda x: 1.96 * (\n df[(df.epoch == x)][columnList[2]].std() / df[(df.epoch == x)][columnList[2]].size),\n x_axis_names)),\n visible=True\n )\n )\n trace4 = go.Bar(\n x=list(map(lambda x: x.split(\"-\")[0], x_axis_names)),\n y=list(map(lambda x: df[(df.epoch == x)][columnList[3]].mean(), x_axis_names)),\n name=columnList[3].replace(\"_\", \" \"),\n error_y=dict(\n type='data',\n array=list(map(lambda x: 1.96 * (\n df[(df.epoch == x)][columnList[3]].std() / df[(df.epoch == x)][columnList[3]].size),\n x_axis_names)),\n visible=True\n )\n )\n\n data = [trace1, trace2, trace3, trace4]\n layout = go.Layout(\n width=1350,\n height=752,\n barmode='group',\n )\n\n fig = go.Figure(data=data, layout=layout)\n # Axis Config\n fig.update_xaxes(tickfont=dict(family='Rockwell', color='crimson', size=30))\n fig.update_yaxes(tickfont=dict(family='Rockwell', color='crimson', size=30))\n\n # Legend config\n fig.layout.update(\n showlegend=leg,\n legend=go.layout.Legend(\n font=dict(\n family=\"Courier New, monospace\",\n size=35,\n color=\"black\")\n )\n )\n\n pio.write_image(fig, str(file_name) + '.svg')\n\n\ndef information_assembly_grouped_bar(df: pd.core.frame.DataFrame, write_path: str, status: str,\n info_method, leg: bool) -> None:\n \"\"\"\n\n :param df: aggregated information assembly (median) data frame- Stim, NoStim, diff\n :param write_path: path to write\n :param status: conditions - Stim, NoStim, Diff\n :param info_method: information method correlation or mutual information\n :param leg: whether legend is visible or not\n \"\"\"\n df = df[(df.method.str.strip() == info_method) & (df.epoch.str.contains(status))]\n filt = lambda st, data_list: list(filter(lambda x: st in x, data_list))[0]\n columnList = ['In', 'Out']\n\n colls = df.loc[:, 'epoch'].unique()\n x_axis_names = [filt(\"Vis\", colls), filt(\"Mem\", colls), filt(\"Sac\", colls)]\n\n trace1 = go.Bar(\n x=list(map(lambda x: x.split(\"-\")[0], x_axis_names)),\n y=list(df[(df['in/out'] == 'In')]['info']),\n name=columnList[0],\n error_y=dict(\n type='data',\n array=list(df[(df['in/out'] == 'In')]['SEM']),\n visible=True\n )\n )\n trace2 = go.Bar(\n x=list(map(lambda x: x.split(\"-\")[0], x_axis_names)),\n y=list(df[(df['in/out'] == 'Out')]['info']),\n name=columnList[1],\n error_y=dict(\n type='data',\n array=list(df[(df['in/out'] == 'Out')]['SEM']),\n visible=True\n )\n )\n\n data = [trace1, trace2]\n layout = go.Layout(\n width=1350,\n height=752,\n barmode='group',\n )\n\n fig = go.Figure(data=data, layout=layout)\n # Axis Config\n fig.update_xaxes(tickfont=dict(family='Rockwell', color='crimson', size=30))\n fig.update_yaxes(tickfont=dict(family='Rockwell', color='crimson', size=30))\n\n # Legend config\n fig.layout.update(\n showlegend=leg,\n legend=go.layout.Legend(\n font=dict(\n family=\"Courier New, monospace\",\n size=35,\n color=\"black\")\n )\n )\n\n pio.write_image(fig, write_path + str(info_method) + '-' + str(status) + '.svg')\n","repo_name":"M0h3eN/network","sub_path":"commons/plotRelatedFunctions/plot_network.py","file_name":"plot_network.py","file_ext":"py","file_size_in_byte":14951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"24460493653","text":"\"\"\"\nDefinition of TreeNode:\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left, self.right = None, None\n\"\"\"\nimport collections\n\n\nclass Solution:\n \"\"\"\n @param root: a root of tree\n @return: return a integer\n \"\"\"\n def findBottomLeftValue(self, root):\n # write your code here\n if not root:\n return None\n\n queue = collections.deque([root])\n depth, res = 0, None\n cur = 0\n while queue:\n cur += 1\n for _ in range(len(queue)):\n node = queue.popleft()\n if cur > depth:\n depth = cur\n res = node.val\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n\n return res\n","repo_name":"HaydenInEdinburgh/LintCode","sub_path":"1191_find_bottom_left_tree_value.py","file_name":"1191_find_bottom_left_tree_value.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"33880591363","text":"import matplotlib.pyplot as plt\nimport numpy\n\n# 바차트 예제1\n# plt.bar([1.5,2.6,4.8],[40,55,89])\n\n# 딕셔너리를 이용한 예제2\n# dic={'A':25,'B':70,'C':55,'D':90}\n# for i, key in enumerate(dic):\n# print(i)\n# # print(key)\n# plt.bar(i,dic[key])\n\n# 딕셔너리를 이용한 예제3\ndic={'A':25,'B':70,'C':55,'D':90}\nfor i, key in enumerate(dic):\n print(i)\n # print(key)\n plt.bar(i,dic[key])\n\n# 라벨을 x축에 표시\n# plt.xticks(numpy.arange(len(dic)),dic.keys())\n\n# 라벨을 x축에 표시(쉬운방법)\nplt.xticks([0,1,2,3],['A','B','C','D'])\n\n# 표시\nplt.show()\n\n\n","repo_name":"zoro6908/test1","sub_path":"matplotlib_barchart.py","file_name":"matplotlib_barchart.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"20214234577","text":"import sys\nimport requests\nimport os\nimport re\nimport shutil\nimport html\nfrom datetime import timedelta\nimport dateutil.parser\nfrom ics import Calendar, Event\nfrom bs4 import BeautifulSoup\nfrom markdownify import markdownify as md\n\nOUT_DIR = os.environ.get('OUT_DIR', './out')\nBASE_URL = os.environ.get('BASE_URL', 'http://www.derecho.uba.ar/')\nIN_URL = os.environ.get('IN_URL', 'http://www.derecho.uba.ar/agenda/')\nreq = requests.get(IN_URL)\nhtml_doc = req.text\n\ndef get_description(url):\n req = requests.get(url)\n soup = BeautifulSoup(req.text, 'html.parser')\n el = soup.find('div', class_='list-aviso')\n if el is None:\n return url\n return re.sub(r'\\n+', '\\n', md(str(el)))\n\ncalendar = Calendar()\nsoup = BeautifulSoup(html_doc, 'html.parser')\nfor article in soup.find_all('article', class_='item-agenda'):\n fecha = article.find('time')['datetime']\n link = article.find('a')\n title = link.get_text()\n url = BASE_URL + link['href']\n calendar.events.add(Event(\n name=title,\n begin=fecha + '-03:00',\n description=get_description(url),\n url=url,\n duration=timedelta(hours=2),\n ))\n\n\nshutil.rmtree(OUT_DIR, ignore_errors=True)\nos.mkdir(OUT_DIR)\n\nwith open(f'{OUT_DIR}/agenda.ics', 'w') as f:\n f.writelines(calendar.serialize_iter())\n\nwith open(f'{OUT_DIR}/index.html', 'w') as f:\n f.write('\\n')\n f.write('\\n')\n f.write('Agenda de actividades | Facultad de Derecho - Universidad de Buenos Aires\\n')\n f.write('\\n')\n f.write('

Agregar Calendario

\\n')\n f.write('\\n')\n for ev in sorted(calendar.events, key=lambda ev: str(ev.begin)):\n f.write('\\n')\n f.write(f'\\n')\n f.write(f'\\n')\n f.write(f'\\n')\n f.write('\\n')\n f.write('
{ev.name}{dateutil.parser.isoparse(str(ev.begin)).strftime(\"%d/%m/%y %H:%M\")}Más información
\\n')\n f.write('\\n')\n f.write('\\n')\n","repo_name":"seppo0010/derecho-agenda","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"22594085643","text":"import json\n\nclass getValueTool():#获取response里的值\n @staticmethod\n def getvalue(param, keys):\n dictr = json.loads(param)\n keylist = keys.split(\".\")\n keylen = len(keylist)\n if keylen == 1:\n return dictr[keys]\n else:\n for keys in keylist:\n dictr = dictr[keys]\n return dictr","repo_name":"zhouyanping123/apiauto","sub_path":"common/tool.py","file_name":"tool.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"29222920770","text":"# XXX: Add lexical categories.\n\ntranslate_metaschema = {\n 'HasPlaceOfOrigin': [('P', 'from')],\n 'PlaceOfOriginOf': [('P', 'origin of')],\n 'Portrayed': [('P', 'portraying')],\n 'PortrayedBy': [('P', 'portrayed by')],\n 'HasCategory': [('P', 'HasCategory')],\n 'HasCategoryMember': [('P', 'HasCategoryMember')],\n 'Administers': [('P', 'running')],\n 'AdministeredBy': [('P', 'run by')],\n 'OccursIn': [('P', 'in')],\n 'PlaceOfOccurrenceOf': [('P', 'containing')],\n 'Produced': [('P', 'producing')],\n 'ProducedBy': [('P', 'produced by')],\n 'HasLocation': [('P', 'at')],\n 'LocationOf': [('P', 'LocationOf')],\n 'HasTitle': [('P', 'titled')],\n 'TitleHeldBy': [('P', 'TitleHeldBy')],\n 'HasPart': [('P', 'containing')],\n 'PartOf': [('P', 'in')],\n 'ComposedOf': [('P', 'made of')],\n 'Composes': [('P', 'Composes')],\n 'ParticipatedIn': [('P', 'participating in')],\n 'HasParticipant': [('P', 'having participant')],\n 'Discovered': [('P', 'discovering')],\n 'DiscoveredBy': [('P', 'discovered by')],\n 'HasStatus': [('P', 'HasStatus')],\n 'StatusOf': [('P', 'StatusOf')],\n 'PractitionerOf': [('P', 'PractitionerOf')],\n 'HasPractitioner': [('P', 'HasPractitioner')],\n 'HasServiceArea': [('P', 'serving')],\n 'ServiceAreaOf': [('P', 'served by')],\n 'HasSymbol': [('P', 'HasSymbol')],\n 'Symbolizes': [('P', 'Symbolizes')],\n 'HasChild': [('P', 'HasChild')],\n 'HasParent': [('P', 'HasParent')],\n 'HasPublication': [('P', 'HasPublication')],\n 'PublicationOf': [('P', 'PublicationOf')],\n 'MemberOf': [('P', 'member of')],\n 'HasMember': [('P', 'with member')],\n 'LeaderOf': [('P', 'leader of')],\n 'HasLeader': [('P', 'led by')],\n 'HasOwner': [('P', 'owned by')],\n 'Owns': [('P', 'owning')],\n 'PeerOf': [('P', 'peer of')],\n 'HasTimePoint': [('P', 'HasTimePoint')],\n 'ExhibitedAt': [('P', 'ExhibitedAt')],\n 'Exhibited': [('P', 'Exhibited')],\n 'Distributes': [('P', 'distributing')],\n 'DistributedBy': [('P', 'distributed by')],\n 'HasName': [('P', 'named')],\n 'NameOf': [('P', 'NameOf')],\n 'SuperclassOf': [('P', 'SuperclassOf')],\n 'SubclassOf': [('P', 'SubclassOf')],\n 'TookPlaceAt': [('P', 'TookPlaceAt')],\n 'HadEventTakePlace': [('P', 'HadEventTakePlace')],\n 'HasFictionalRelationship': [('P', 'HasFictionalRelationship')],\n 'HasGenre': [('P', 'HasGenre')],\n 'GenreOf': [('P', 'GenreOf')],\n 'SucceededBy': [('P', 'SucceededBy')],\n 'Succeeds': [('P', 'Succeeds')],\n 'UsePermittedBy': [('P', 'UsePermittedBy')],\n 'PermitsUseOf': [('P', 'PermitsUseOf')],\n 'ContributedTo': [('P', 'contributing to')],\n 'HasContributor': [('P', 'HasContributor')],\n 'HasIdentifier': [('P', 'HasIdentifier')],\n 'HasCenter': [('P', 'HasCenter')],\n 'CenterFor': [('P', 'CenterFor')],\n 'HasCharacter': [('P', 'HasCharacter')],\n 'AppearsIn': [('P', 'appearing in')],\n 'BroaderThan': [('P', 'BroaderThan')],\n 'NarrowerThan': [('P', 'NarrowerThan')],\n 'ExpressedBy': [('P', 'ExpressedBy')],\n 'UsedToExpress': [('P', 'UsedToExpress')],\n 'HasCertification': [('P', 'HasCertification')],\n 'CertificationOf': [('P', 'CertificationOf')],\n 'HasPreceedingWork': [('P', 'HasPreceedingWork')],\n 'HasSubsequentWork': [('P', 'HasSubsequentWork')],\n 'Created': [('P', 'Created')],\n 'CreatedBy': [('P', 'by')],\n 'HasAdaptation': [('P', 'HasAdaptation')],\n 'AdaptationOf': [('P', 'AdaptationOf')],\n 'HasMeasurement': [('P', 'HasMeasurement')],\n 'MeasurementOf': [('P', 'MeasurementOf')],\n 'HasAbstraction': [('P', 'HasAbstraction')],\n 'AbstractionOf': [('P', 'AbstractionOf')],\n 'HasMeansOfDemise': [('P', 'HasMeansOfDemise')],\n 'MeansOfDemiseOf': [('P', 'MeansOfDemiseOf')],\n 'HasSubject': [('P', 'about')],\n 'SubjectOf': [('P', 'subject of')],\n 'HasURL': [('P', 'HasURL')],\n 'HasOrdinal': [('P', 'HasOrdinal')],\n 'Music': [('P', 'Music')],\n 'Book': [('P', 'Book')],\n 'Medicine': [('P', 'Medicine')],\n 'Schema': [('P', 'Schema')],\n 'Government': [('P', 'Government')],\n 'System': [('P', 'System')],\n 'Aviation': [('P', 'Aviation')],\n 'Skos': [('P', 'Skos')],\n 'Dataworld': [('P', 'Dataworld')],\n 'Finance': [('P', 'Finance')],\n 'Begin Date': [('P', 'Begin Date')],\n 'End Date': [('P', 'End Date')],\n 'Date': [('P', 'Date')],\n 'HasDescription': [('P', 'HasDescription')],\n 'Object': [('P', 'Object')],\n 'Address': [('P', 'Address')],\n 'Automotive': [('P', 'Automotive')]\n}\n","repo_name":"clearish/NaturalFreebase","sub_path":"lexicon/translate_metaschema.py","file_name":"translate_metaschema.py","file_ext":"py","file_size_in_byte":4522,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"457064288","text":"from dataclasses import dataclass, field\r\nfrom typing import Any, List, Mapping, Tuple\r\n\r\n\r\n@dataclass\r\nclass Fermentable:\r\n name: str = \"\"\r\n version: int = 0\r\n type: str = \"\"\r\n amount: float = 0.0\r\n result: float = 0.0\r\n color: int = 1\r\n\r\n def __post_init__(self):\r\n self.amount = float(self.amount)\r\n\r\n\r\n@dataclass\r\nclass Hop:\r\n name: str\r\n version: int\r\n origin: str\r\n alpha: float\r\n amount: float\r\n use: str\r\n time: int\r\n type: str\r\n form: str\r\n beta: float\r\n\r\n def __post_init__(self):\r\n self.amount = float(self.amount)\r\n self.alpha = float(self.alpha)\r\n self.time = int(self.time)\r\n\r\n\r\n@dataclass\r\nclass Yeast:\r\n name: str = \"\"\r\n version: int = 0\r\n type: str = \"\"\r\n form: str = \"\"\r\n amount: float = 0\r\n\r\n def __post_init__(self):\r\n self.amount = float(self.amount)\r\n\r\n\r\n@dataclass\r\nclass MashStep:\r\n name: str\r\n version: int\r\n type: str\r\n step_temp: int\r\n step_time: int\r\n\r\n\r\n@dataclass\r\nclass Mash:\r\n steps: List[MashStep]\r\n version: int = 0\r\n grain_temp: int = 20\r\n\r\n\r\n@dataclass\r\nclass Style:\r\n name: str = \"\"\r\n category: str = \"\"\r\n\r\n\r\n@dataclass\r\nclass Recipe:\r\n style: Style\r\n fermentables: List[Fermentable]\r\n hops: List[Hop]\r\n yeasts: List[Yeast]\r\n mash: Mash = None\r\n miscs: List[Any] = None\r\n name: str = \"\"\r\n version: int = 0\r\n og: float = 1\r\n fg: float = 1\r\n type: str = \"\"\r\n batch_size: int = 20\r\n boil_size: int = 25\r\n boil_time: int = 60\r\n efficiency: float = 75\r\n primary_temp: int = 25\r\n","repo_name":"papkov/beergenrnn","sub_path":"beergenrnn/beerxml.py","file_name":"beerxml.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"43061679720","text":"import os.path, sys\nsys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))\nimport tenbSCcore as sc\nimport htmlRoutines as hr\nimport reportTemplates as rt\nimport pandas as pd\nimport utilities as ut\nimport datetime\nimport json\nimport funcs as fc\nimport normalise_sc_vuln_data as nvd\nimport normalise_sc_asset_data as nad\nimport normalise_sc_mitigated_data as nmd\nimport e8slas as e8\nimport sev_slas as ss\n\nsc_key_file=\"../../sc_keys.json\"\nsc_keys=sc.read_SC_keys(sc_key_file)\nregion_id='1'\n# tags for Internet facing systems\ntag_cat_ifacing=\"Essential8\"\ntag_val_ifacing=\"Internet-Facing\"\nasset_list_ifacing=\"Internet-Facing\"\n\n\n# file and directory locations\nraw_dir=\"raw/\" # the directory for your results\nvulns_dir=\"vulns/\"\nmitigated_dir=\"mitigated/\"\ne8slas_dir=\"e8slas/\"\ne8mitigated_dir=\"e8mitigated/\"\nsev_slas_dir=\"sev_slas/\"\nsev_mitigated_dir=\"sev_mitigated/\"\n# raw downloaded data from APIs\nvulns_raw_fname=raw_dir+\"vulns_\"+region_id+\".json\"\nassets_raw_fname=raw_dir+\"assets_\"+region_id+\".json\"\nmitigated_raw_fname=raw_dir+\"mitigated_\"+region_id+\".json\"\nmitigated_ifacing_raw_fname=raw_dir+\"mitigated_ifacing_\"+region_id+\".json\"\n# converted data using raw files as the input\nvulns_converted_fname=vulns_dir+\"vulns_\"+region_id+\".json\"\nvulns_plugins_fname=\"vulns_plugins.json\"\nassets_converted_fname=\"assets.json\"\nmitigated_converted_fname=mitigated_dir+\"mitigated_\"+region_id+\".json\"\nmitigated_plugins_fname=\"mitigated_plugins.json\"\ne8sla_summary_fname=e8slas_dir+\"e8slas_\"+region_id+\".json\"\ne8sla_detailed_fname=e8mitigated_dir+\"e8mitigated_\"+region_id+\".json\"\nsla_summary_fname=sev_slas_dir+\"slas_\"+region_id+\".json\"\nsla_detailed_fname=sev_mitigated_dir+\"mitigated_\"+region_id+\".json\"\n\n'''\nMain Program Loop\n'''\n\nget_asset_data=1\nget_vuln_data=1\nget_fix_data=1\nget_ifacing_data=1\n\ntime_period=180\n\n'''\nDownload the raw data\n'''\n\nif get_vuln_data==1: # raw vuln data\n\tvuln_tool=\"vulndetails\"\n\tquery={\n\t\t\"type\" : \"vuln\",\n\t\t\"tool\" : vuln_tool,\n\t\t'filters': [\n\t\t\t{'filterName': 'lastSeen', 'operator': '=', 'value': '0:'+str(time_period)},\n\t\t\t{'filterName': 'severity', 'operator': '=',\n\t\t\t'value': [{'id': '1', 'name': 'Low', 'description': 'Low Severity'},\n\t\t\t{'id': '2', 'name': 'Medium', 'description': 'Medium Severity'},\n\t\t\t{'id': '3', 'name': 'High', 'description': 'High Severity'},\n\t\t\t{'id': '4', 'name': 'Critical', 'description': 'Critical Severity'}]}\n\t\t]\n\t}\n\tsc_server,port,token,cookies=sc.get_token(sc_keys)\n\tdecoded=sc.get_vulns(\"cumulative\",query,sc_server,port,token,cookies,vulns_raw_fname)\n\tsc.close_session(sc_server,port,token,cookies)\n\nif get_asset_data==1: # Raw Asset Data\n\tsc_server,port,token,cookies=sc.get_token(sc_keys)\n\tdecoded=sc.call_sc_hosts(sc_server,port,token,cookies)\n\t#print(decoded)\n\twith open(assets_raw_fname,'w') as outfile:\n\t\tjson.dump(decoded,outfile)\n\nif get_fix_data==1: # raw vuln data\n\tvuln_tool=\"vulndetails\"\n\tquery={\n\t\t\"type\" : \"vuln\",\n\t\t\"tool\" : vuln_tool,\n\t\t'filters': [\n\t\t\t{'filterName': 'lastSeen', 'operator': '=', 'value': '0:'+str(time_period)},\n\t\t\t{'filterName': 'severity', 'operator': '=',\n\t\t\t'value': [{'id': '1', 'name': 'Low', 'description': 'Low Severity'},\n\t\t\t{'id': '2', 'name': 'Medium', 'description': 'Medium Severity'},\n\t\t\t{'id': '3', 'name': 'High', 'description': 'High Severity'},\n\t\t\t{'id': '4', 'name': 'Critical', 'description': 'Critical Severity'}]}\n\t\t]\n\t}\n\tsc_server,port,token,cookies=sc.get_token(sc_keys)\n\tdecoded=sc.get_vulns(\"patched\",query,sc_server,port,token,cookies,mitigated_raw_fname)\n\tsc.close_session(sc_server,port,token,cookies)\n\nif get_ifacing_data==1: # raw vuln data\n\tvuln_tool=\"vulndetails\"\n\tquery={\n\t\t\"type\" : \"vuln\",\n\t\t\"tool\" : vuln_tool,\n\t\t'filters': [\n\t\t\t{'filterName': 'lastSeen', 'operator': '=', 'value': '0:'+str(time_period)},\n\t\t\t{'filterName': 'severity', 'operator': '=', 'value': [{'id': '1', 'name': 'Low', 'description': 'Low Severity'}, {'id': '2', 'name': 'Medium', 'description': 'Medium Severity'}, {'id': '3', 'name': 'High', 'description': 'High Severity'}, {'id': '4', 'name': 'Critical', 'description': 'Critical Severity'}]},\n\t\t\t{'filterName': 'asset', 'operator': '=', 'value': {'id': '116', 'name': 'Internet-Facing', 'description': '', 'uuid': 'D906A47E-14E9-4171-BBEB-2DA37963CD90'}}\n\t\t]\n\t}\n\tsc_server,port,token,cookies=sc.get_token(sc_keys)\n\tdecoded=sc.get_vulns(\"patched\",query,sc_server,port,token,cookies,mitigated_ifacing_raw_fname)\n\tsc.close_session(sc_server,port,token,cookies)\n\n'''\n#Process the raw data\n'''\nnvd.process_vuln_data(region_id,vulns_raw_fname,vulns_converted_fname,vulns_plugins_fname)\nnad.process_asset_data(region_id,assets_raw_fname,assets_converted_fname)\nmitigated_results,mitigated_plugins_results=nmd.process_fix_data(region_id,mitigated_raw_fname,mitigated_converted_fname,mitigated_plugins_fname)\nmitigated_ifacing_results=fc.process_sc_ifacing(region_id,mitigated_ifacing_raw_fname)\n\n'''\nCalculate some Essential 8 SLAs\n'''\ne8slas={\n\t\"exploitable\":2,\n\t\"common_apps\":14,\n\t\"operating_systems\":14,\n\t\"internet_facing\":14\n}\ne8.calc_e8slas(e8slas,region_id,mitigated_results,mitigated_plugins_results,mitigated_ifacing_results,e8sla_summary_fname,e8sla_detailed_fname)\n\n'''\n#Calculate some severity based SLAs\n'''\nslas={\n\t\"critical\":14,\n\t\"high\":30,\n\t\"medium\":30,\n\t\"low\":30\n}\nss.calc_slas(slas,region_id,mitigated_results,mitigated_plugins_results,sla_summary_fname,sla_detailed_fname)\n","repo_name":"jbowler432/tenb-reports","sub_path":"powerBI/get_sc_data.py","file_name":"get_sc_data.py","file_ext":"py","file_size_in_byte":5368,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"27121847911","text":"import matplotlib.pyplot as plt\nimport corner\nimport numpy as np\nimport pandas as pd\nimport os\nimport time_functions as tf\n\n# Looking at a cornerplot for a single spectral line\ntime_dir = 'data/ltp_run_b/run_b_1143766594/'\nchannel = 4\nmodel = 1\n\ntime = int(time_dir[-11:-1])\n# File name\nlc_file = os.path.join(time_dir, 'linechain_channel' + str(channel) + '.dat')\n# Import first column to determine how wide DataFrame should be\n# Use incorrect separator to load uneven lines\nlc = pd.read_csv(lc_file, usecols=[0], header=None, squeeze=True, dtype=str)\ncounts = pd.Series([int(row[0]) for row in lc])\n# Import entire data file, accounting for uneven rows\nlc = pd.read_csv(lc_file, header=None, names=range(max(counts)*3+1), sep=' ')\n# Strip of all rows that don't match the model\nlc = lc[lc.iloc[:,0] == model].dropna(1).reset_index(drop=True).rename_axis('IDX')\n# Log scales\nlc.iloc[:,1] = np.log(lc.iloc[:,1])\nlc.iloc[:,2] = np.log(lc.iloc[:,2])\nlc.iloc[:,3] = np.log(lc.iloc[:,3])\n# Cornerplot\ncorner.corner(lc.iloc[:,1:4], \n labels=['log(Frequency (Hz))', 'log(Amplitude)', 'log(Quality factor)'],\n #range=[(3e-3, 3.7e-3), (8e-21, 2.4e-20), (0, 800)]\n)\nplt.suptitle(time_dir + ' channel ' + str(channel) + \n ', N='+str(model) + ', ' + str(len(lc)) + ' samples')\nplt.show()\n","repo_name":"lodubay/lisa-pf-noise","sub_path":"tests/single_line_cornerplot.py","file_name":"single_line_cornerplot.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"16232337865","text":"import sys\r\ninput=sys.stdin.readline\r\nT=int(input())\r\n# for i in range(T):\r\n# A,B=map(int, input().split())\r\n# for j in range(max(A,B),(A*B)+1):\r\n# if j%A==0 and j%B==0:\r\n# print(j)\r\n# break\r\n\r\n#유클리드 접근법\r\nfor i in range(T):\r\n a,b=map(int, input().split())\r\n A,B=a,b\r\n while a!=0:\r\n b=b%a\r\n a,b=b,a\r\n gcd=b\r\n lcm=A*B//b\r\n print(lcm)","repo_name":"KyunghoonJeon/BaekJoon_Judge","sub_path":"Number_Theory/question1934.py","file_name":"question1934.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"3766794403","text":"from data_utils import *\nfrom data_loader import padding\nimport mxnet.ndarray as nd\nimport numpy as np\nimport mxnet as mx\nimport mxnet.gluon as gluon\nfrom mxnet.gluon.rnn import LSTM,GRU,LSTMCell,GRUCell\nfrom mxnet import autograd\nfrom mxnet.gluon.nn import Embedding\nimport pickle\n#step_1:load the data\n#step_1.1:padding\n#step_2:gen_vocab,sen2id\nfenci_right_save_path = \"/root/PycharmProjects/sigir/data/right_fenci_profile_pad.csv\"\nfenci_wrong_save_path = \"/root/PycharmProjects/sigir/data/wrong_fenci_profile_pad.csv\"\n\n\nsingle_lstm_model_path = \"/root/PycharmProjects/sigir/baseline/dual_lstm/model/single_lstm_model_new.params135\"\n\nwith open(\"/root/PycharmProjects/sigir/baseline/dual_lstm/vocab/word2id_file\",'rb') as f:\n word2id = pickle.load(f)\nwith open(\"/root/PycharmProjects/sigir/baseline/dual_lstm/vocab/id2word_file\",'rb') as ff:\n id2word = pickle.load(ff)\nvocab_size = len(id2word)\n\nnet = gluon.nn.Sequential()\n\nwith net.name_scope():\n net.add(Embedding(input_dim=vocab_size,output_dim=1000))\n net.add(LSTM(hidden_size=1000,layout='NTC',num_layers=2))\n net.add(gluon.nn.Dense(2,flatten=True))\nnet.initialize()\n\n\nnet.load_params(single_lstm_model_path,mx.cpu())\npost = \"你 喜欢 VR 吗\"\nrespnose = \"喜欢\"\nfake_resp = ['我','喜欢','篮球']\nfake_reps = ['我','没有','爸爸']\n\nexp1 = padding(post,17)+str(\" \")+padding(respnose,17)\nprint(exp1)\ndata = [word2id[s] for s in exp1.split(\" \")]\nprint(data)\ndata = nd.array(data)\ndata = data.reshape((1,-1))\nfor _ in range(1):\n output = net(nd.array(data))\n print(output)","repo_name":"NonvolatileMemory/baseline_for_chatbot-mxnet","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"40"} +{"seq_id":"16398638980","text":"\nfrom XJ_UsefulWidgets import XJ_PictCropper#图片裁剪器\nfrom XJ_UsefulWidgets import XJ_ColorChoose#颜色选择按钮\nfrom XJ_UsefulWidgets import XJ_Slider_Horizon#水平滑动条\n\nimport sys\nfrom PIL import Image\nfrom PyQt5.QtGui import QImage,QColor\nfrom PyQt5.QtCore import Qt,pyqtSignal\nfrom PyQt5.QtWidgets import QApplication\nfrom PyQt5.QtWidgets import QVBoxLayout,QHBoxLayout,QWidget,QPushButton,QCheckBox,QFileDialog,QMessageBox,QLabel\n\n\n__all__=['XJ_Cropper']\n\nclass XJ_Cropper(QWidget):#附有“透明度条”、“自由裁剪复选框”、“图片选择按钮”的裁剪器\n cropChanged=pyqtSignal()#槽信号,裁剪区发生变化时发送信号(该信号无参)\n def __init__(self,parent=None,aspectRatio=(10,16),labelText=\"【前】\"):#aspectRatio为裁剪的宽高比\n super().__init__()\n\n self.__ratio=aspectRatio\n self.__img=None#PIL.Image,因为有“改变透明度”的需要,所以就临时存起来了\n self.__slider=XJ_Slider_Horizon(self)#水平滑动条,给图片设置透明度\n self.__cp=XJ_PictCropper(self,200,320)\n self.__cpSize=QLabel(\"0x0\",self)#标签,特地用于显示图片长宽(虽然没啥用\n vbox=QVBoxLayout(self)\n\n cp=self.__cp\n btn=QPushButton(\"选图\",self)#图片选择按钮\n check=QCheckBox(self)#复选框(比例裁剪\n clr=XJ_ColorChoose(self)#颜色选择按钮\n slider=self.__slider\n labelText=QLabel(labelText,self)\n cpSize=self.__cpSize\n\n\n\n vbox.addWidget(cp,100)\n\n hbox=QHBoxLayout()\n hbox.addWidget(slider,1)\n hbox.addWidget(check)\n vbox.addLayout(hbox)\n\n hbox=QHBoxLayout()\n hbox.addWidget(labelText)\n hbox.addWidget(cpSize)\n hbox.addStretch(1)\n hbox.addWidget(btn)\n hbox.addWidget(clr)\n vbox.addLayout(hbox)\n\n\n\n check.setToolTip(\"比例裁剪\")\n clr.setToolTip(\"设置为纯色\")\n check.clicked.connect(self.__Click_Check)\n btn.clicked.connect(self.__Click_Button)\n clr.valueChanged.connect(self.__Click_Color)\n cp.valueChanged.connect(self.__CropChanged)\n slider.valueChanged.connect(self.__AlphaChanged)\n clr.SetColor((192,255,255))\n slider.setMaximum(255)\n slider.setValue(255)\n slider.setPageStep(32)\n cp.Set_SmoothCrop(True)\n cp.Get_Setting().background.size=1\n cp.Get_Setting().cropper.rowCnt=1\n cp.Get_Setting().cropper.colCnt=1\n labelText.setStyleSheet(\"font-size:28px; color:rgb(96,96,255);\")\n cpSize.setStyleSheet(\"font-size:20px; color:rgb(255,64,192);\")\n btn.setStyleSheet(\"font-size:24px; color:rgb(96,96,255); border-color:#88AAAA; border-style: solid; border-width:3px; border-radius:10px;\")\n\n def Get_Crop(self):#获取截图\n return self.__cp.Get_Crops(False)\n\n def Get_AspectRatio(self):#返回裁剪的宽高比\n return self.__ratio\n\n def Set_Img(self,PIL_Img):#设置图片\n self.__img=PIL_Img\n self.__cp.SetImg(PIL_Img)\n\n def MaximizePict(self):#图片最大化\n self.__cp.MaximizePict()\n\n def MaximizeCrop(self):#裁剪区最大化\n self.__cp.MaximizeCrop()\n\n def __CropChanged(self):\n area=self.__cp.Get_CropArea()\n self.__cpSize.setText('{}x{}'.format(*((area.width,area.height) if area else (0,0))))#设置一下标签\n self.cropChanged.emit()\n\n def __AlphaChanged(self,val):#透明度发生变化\n cp=self.__cp\n img=self.__img\n self.__slider.setToolTip('透明度:{}'.format(val))\n cp.valueChanged.disconnect(self.__CropChanged)#避免因为修改透明度而导致cropChanged发出信号\n area=cp.Get_CropArea()#临时记录下裁剪区,等会儿恢复\n cp.SetImg(XJ_Cropper.__GetAlphaImg(img,val/255))\n cp.valueChanged.connect(self.__CropChanged)#将信号事件恢复回来\n cp.Set_CropArea(area)#恢复裁剪区\n\n @staticmethod\n def __GetAlphaImg(PIL_Img, alpha = 0.7 ):#给PIL图片附上透明度:https://cloud.tencent.com/developer/article/1740547\n return Image.blend(Image.new('RGBA', PIL_Img.size, (0,0,0,0)), PIL_Img.convert('RGBA'), alpha)\n\n def __Click_Color(self,color):#点击了“纯色”按钮,color为三元元组\n img=Image.new('RGBA', (64,64), (*color,255))\n if(self.__img and self.__img.size!=img.size):\n self.__cp.Set_CropArea(None)\n self.__img=img\n self.__AlphaChanged(self.__slider.value())\n\n def __Click_Button(self,event):#点击了“选择图片”按钮\n path=QFileDialog.getOpenFileName(self,'选择图片')[0].replace('\\\\','/')#路径名的反斜杠全改为斜杠\n if(path):\n try:\n img=Image.open(path)\n if(self.__img.size!=img.size):\n self.__cp.Set_CropArea(None)\n self.__img=img\n self.__AlphaChanged(self.__slider.value())\n except:\n QMessageBox.information(self,\"图片读取失败\",\"【{}】\\n不是图片!\".format(path))\n\n def __Click_Check(self,mark):#点击了“比例裁剪”复选框\n self.__cp.Set_AspectRatio(self.__ratio if mark else (0,0))\n self.update()\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n\n cp=XJ_Cropper()\n cp.show()\n cp.resize(500,300)\n sys.exit(app.exec())\n\n","repo_name":"Ls-Jan/PyQt_MCCloakMaker","sub_path":"XJ_Cropper.py","file_name":"XJ_Cropper.py","file_ext":"py","file_size_in_byte":5433,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"40"} +{"seq_id":"3585448121","text":"n = int(input())\nmembers = list(map(int, input().split()))\nmembers.sort()\n\ncnt = 0\nmax_val = 0\nresult = 0\nfor idx in range(len(members)):\n cnt += 1\n max_val = max(max_val, members[idx])\n if cnt >= max_val:\n result += 1\n cnt = 0\n max_val = 0\n\nprint(result)","repo_name":"kkw2758/Algorithm","sub_path":"Greedy/Q1.py","file_name":"Q1.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"72190079161","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^popular/$', views.popular, name='popular'),\n url(r'^question/(?P\\d+)/$', views.show, name='show'),\n url(r'^ask/$', views.create_question, name='create_question'),\n url(r'^answer/$', views.create_answer),\n url(r'^login/$', views.auth_login),\n url(r'^signup/$', views.signup),\n]\n","repo_name":"orman071/st","sub_path":"ask/qa/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"18257149287","text":"import os\nimport subprocess\n\nimport pytest\nimport toml\n\naws_regions = [\n # \"eu-west-1\",\n # \"eu-west-2\",\n # \"eu-west-3\",\n \"eu-central-1\",\n # \"eu-north-1\",\n # \"us-east-2\",\n # \"us-east-1\",\n # \"us-west-1\",\n # \"us-west-2\",\n]\n\nrun_id = 0\n\n\ndef pytest_collection_modifyitems(items):\n for item in items:\n terraform_path = os.path.join(\n os.path.dirname(os.path.abspath(__file__)), \"terraform\"\n )\n if str(item.fspath).startswith(terraform_path):\n item.add_marker(pytest.mark.terraform_unittest)\n\n\ndef get_git_commit_hash() -> str:\n return (\n subprocess.check_output([\"git\", \"describe\", \"--always\"])\n .decode(\"utf-8\")\n .strip(\"\\n\")\n )\n\n\n@pytest.fixture(scope=\"session\")\ndef version() -> str:\n full_path = os.path.join(\n os.path.dirname(os.path.abspath(__file__)), \"../config.toml\"\n )\n config = toml.load(full_path)\n base_version = config[\"version\"]\n\n return os.environ.get(\n \"CIRCLE_TAG\", \"{}.{}\".format(base_version, get_git_commit_hash())\n )\n\n\n@pytest.fixture(scope=\"session\")\ndef environment(version) -> str:\n environment = version.split(\".\")[-1]\n return f\"{environment}\"\n\n\n@pytest.fixture(scope=\"session\")\ndef aws_region(version) -> str:\n hash_version = hash(version)\n nb_region = len(aws_regions)\n\n return aws_regions[hash_version % nb_region]\n\n\n@pytest.fixture(scope=\"session\")\ndef terraform_bin_path() -> str:\n return os.path.join(os.path.dirname(os.path.abspath(__file__)), \"../bin/terraform\")\n","repo_name":"hyperwave-research/terraform-aws-shopper","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"30243081814","text":"Q=['q0','q1','q2']\nS='q0'\nSigma = ['A','B','C']\nF=['q0','q1']\ndelta = {\n\t('q0', 'B'):'q0',\n\t('q0', 'C'):'q0',\n\t('q0', 'A'):'q1',\n\t('q1', 'B'):'q1',\n\t('q1', 'A'):'q1',\n\t('q1', 'C'):'q2',\n\t('q2', 'A'):'q2',\n\t('q2', 'B'):'q2',\n\t('q2', 'C'):'q2'\n}\ndef transicion(estado, sigma):\n\tglobal Sigma, delta\n\tSTATUS = True\n\tif (sigma not in Sigma):\n\t\tSTATUS = False\n\t\treturn '', STATUS\n\tif(estado, sigma) not in delta.keys():\n\t\tSTATUS = False\n\t\treturn '', STATUS\n\testado_siguiente = delta[(estado, sigma)]\n\tprint ('Transicion(', estado, ',' , sigma ,')->', estado_siguiente)\n\treturn estado_siguiente, STATUS\n\nw = 'AB'\nestado = S\nfor sigma in w:\n\testado, STATUS = transicion(estado, sigma)\n\tif not STATUS:\n\t\tbreak\nif (STATUS and (estado in F)):\n\tprint (w, 'si esta en el lenguaje')\nelse:\n\tprint (w, 'no esta en el lenguaje')\n","repo_name":"llCUriel/TheoryOfComputation","sub_path":"[TC 05] Finite State Machine/autom.py","file_name":"autom.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"35237992176","text":"### import libraries\n# for speech recognition\nimport speech_recognition as sr\n# for media input\nfrom pyautogui import press, keyDown, keyUp, hotkey, typewrite\n# for normal key input\nfrom pynput.keyboard import Key, Controller\n# for webbrowser handling\nimport webbrowser\n# to shut down the script\nimport sys\n# for media playback\nimport pyaudio\nimport wave\n\nclass AudioFile:\n def __init__(self, ):\n\n print(\">> audio file created\")\n\n def play(self, path):\n chunk = 1024\n # open a wav format music \n f = wave.open(path,\"rb\") \n # instantiate PyAudio \n p = pyaudio.PyAudio() \n # open stream \n stream = p.open(format = p.get_format_from_width(f.getsampwidth()), \n channels = f.getnchannels(), \n rate = f.getframerate(), \n output = True) \n # read data \n data = f.readframes(chunk) \n\n # play stream \n while data: \n stream.write(data) \n data = f.readframes(chunk) \n\n # stop stream \n stream.stop_stream() \n stream.close() \n\n # close PyAudio \n p.terminate() \n\n# set up so we can use google to actual process what we said\nr = sr.Recognizer()\n# create handle so we can actually simulate keystrokes through this thing\nkeyboard = Controller()\n# is program awake/ready to take commands?\nspeaking = False\n# media playback\nmedia = AudioFile()\n# state checking, so we dont get audio that doubles up sometimes\nwas_idle = True \n\n### functions\n# google search things\ndef google(query):\n\twebbrowser.open('https://www.google.com/search?q=' + query)\n# search for a video on youtube\ndef youtube(query):\n\twebbrowser.open('https://www.youtube.com/results?search_query=' + query)\n\n### main\ndef main(data):\n\tif not speaking:\n\t\tif (\"shutdown\" in data) or (\"shut\" in data) or (\"turn off\" in data) or (\"be quiet\" in data) or (\"goodnight\" in data) or (\"hush\" in data.lower()):\n\t\t\tsys.exit('goodnight')\n\t\telif (\"hey buddy\" in data) or (\"ok buddy\" in data) or (\"Peabody\" in data) or (\"ok body\" in data):\n\t\t\tmedia.play(r'media\\whatsapp message.wav')\n\t\t\treturn True\n\telse:\n\t\t# commodities\n\t\tif (\"what\" in data):\n\t\t\tif (\"time\" in data):\n\t\t\t\tgoogle('what time is it')\n\t\t\telif (\"day\" in data) or (\"date\" in data):\n\t\t\t\tgoogle(\"what\\'s the date \" + ('today', 'tomorrow')[\"tomorrow\" in data])\n\t\t\telif (\"weather\" in data):\n\t\t\t\tgoogle(\"what\\'s the weather like \" + ('today', 'tomorrow')[\"tomorrow\" in data])\n\t\t\telse:\n\t\t\t\tgoogle(data)\n\t\telif (\"define \" in data):\n\t\t\tgoogle(data)\n\t\telif (\"type \" in data):\n\t\t\ttypewrite(data[5:])\n\t\t\tpress('enter')\n\n\t\t# windows\n\t\telif (\"open\" in data):\n\t\t\tkeyboard.press(Key.cmd_l)\n\t\t\tpress('s')\n\t\t\tkeyboard.release(Key.cmd_l)\n\t\t\ttypewrite(data[5:])\n\t\t\tpress('enter')\n\n\t\t# media\n\t\telif (\"media\" in data) or (\"song\" in data) or (\"Spotify\" in data) or (\"music\" in data):\n\t\t\tif (\"skip\" in data) or (\"next\" in data):\n\t\t\t\tpress('nexttrack')\n\t\t\telif (\"pause\" in data) or (\"play\" in data) or (\"resume\" in data):\n\t\t\t\tpress('playpause')\n\t\t\telif (\"restart\" in data):\n\t\t\t\tpress('prevtrack')\n\t\t\telif (\"previous\" in data) or (\"back\" in data):\n\t\t\t\tpress('prevtrack')\n\t\t\t\tpress('prevtrack')\n\n\t\t# discord\n\t\telif (\"discord\" in data) or (\"Discord\" in data):\n\t\t\tif (\"deafen\" in data) or (\"undeafen\" in data):\n\t\t\t\tkeyboard.press(Key.ctrl_r)\n\t\t\t\tkeyboard.press(Key.shift_r)\n\t\t\t\tkeyboard.release(Key.ctrl_r)\n\t\t\t\tkeyboard.release(Key.shift_r)\n\t\t\telif (\"mute\" in data) or (\"unmute\" in data):\n\t\t\t\tkeyboard.press(Key.ctrl_r)\n\t\t\t\tkeyboard.press(Key.alt_r)\n\t\t\t\tkeyboard.release(Key.ctrl_r)\n\t\t\t\tkeyboard.release(Key.alt_r)\n\n\t\t# google\n\t\telif (\"google\" in data) or (\"Google\" in data) or (\"search\" in data):\n\t\t\tif (\"YouTube\" in data):\n\t\t\t\tyoutube(data[15:])\n\t\t\telse:\n\t\t\t\tgoogle(data[7:])\n\n\t\t# back out of the command stage\n\t\telif (\"thanks buddy\" in data) or (\"cheers buddy\" in data) or (\"dismiss\" in data) or (\"cancel\" in data) or (\"nevermind\" in data):\n\t\t\tmedia.play(r'media\\google blip.wav')\n\t\t\treturn False\n\n\t\treturn True\n\nwhile (True):\n\twith sr.Microphone() as src:\n\t\tr.adjust_for_ambient_noise(src)\n\n\t\tif speaking:\n\t\t\tprint(\"ready\")\n\t\t\tif was_idle:\n\t\t\t\tmedia.play(r'media\\s9 twinkle.wav')\n\t\telse:\n\t\t\tprint(\"idle\")\n\n\t\twas_idle = speaking\n\n\t\ttry:\n\t\t\taudio = r.listen(src)\n\t\t\tlog = r.recognize_google(audio, None, \"en-AU\")\n\t\t\tprint(\"{}\".format(log))\n\t\t\tspeaking = main(log)\n\t\texcept sr.UnknownValueError:\n\t\t\tprint(\"huh?\")\n\t\texcept sr.RequestError as e:\n \t\t\tprint(\"couldnt connect to service {0}\".format(e))\n","repo_name":"hxmid/buddy-assistant","sub_path":"buddy-assistant.py","file_name":"buddy-assistant.py","file_ext":"py","file_size_in_byte":4499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"13411735760","text":"import pandas as pd\nimport statsmodels.api as sm \nimport matplotlib.pyplot as plt\nimport os\nos.chdir(r\"C:\\Users\\aaron\\OneDrive\\Documents\\quest\\dbk_consulting\")\ndf = pd.read_csv(r\"C:\\Users\\aaron\\OneDrive\\Documents\\quest\\dbk_consulting\\test_data.csv\")\n\ndf = df.merge(df['category'].str.get_dummies(','), how='left', left_index=True, right_index=True)\n\n# category\n#df = df[df['category'].str.contains('diversions')]\n\ndf['Page Title'] = df['Page Title'].str.lower()\ndef addDummy(words):\n for word in words:\n df[word] = df['Page Title'].str.contains(word).astype(int)\n\naddDummy(['umd', 'student', 'dorm', 'covid', 'housing', 'college park', 'review', 'dot', 'semester', 'basketball', 'win', 'loss'])\ndf = df.drop(columns=['period', 'residuals'])\ndf = df[df['Pageviews'] < 200]\ndf['sum'] = df.iloc[:, -11:].sum(axis=1)\n\nX = df.iloc[:, 11:]\n#y = df['Pageviews'] \n\ny = df['Organic Searches']\n# ## fit a OLS model\nX = sm.add_constant(X) \nest = sm.OLS(y, X).fit() \n\ncorr_matrix = df.corr()\n\nprint(corr_matrix)\n#print(corr_matrix.sort_values(by='Organic Searches', ascending=False).head(20))\n#Using heatmap to visualize the correlation matrix\nplt.imshow(corr_matrix)\n#corr_matrix.to_csv(os.getcwd() + '/matrix.csv')\nplt.show()\nprint(est.summary())\n\n","repo_name":"Aaroney13/dbk_consulting","sub_path":"prelim analysis/regression_OLS.py","file_name":"regression_OLS.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"1485475410","text":"n = int(input(\"Введите число: \"))\nspiral = [[0] * n]\nfor a in range(n - 1):\n spiral += [[0] * n]\ndx, dy, x, y = 0, 1, 0, 0\nfor i in range(1, n ** 2 + 1):\n spiral[x][y] = i\n if spiral[(x + dx) % n][(y + dy) % n]:\n dx, dy = dy, -dx\n x += dx\n y += dy\nfor b in spiral:\n\tprint(*(f\"{c :< 4}\" for c in b), sep = \"\")","repo_name":"PaklinaNatalia/pythonSummerProject2023","sub_path":"Task_4/Task_4.2.py","file_name":"Task_4.2.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"7088148235","text":"import sys\nimport re\nimport copy\nfrom .axiom import Axiom\nfrom .operator import Operator\nfrom collections import defaultdict\nfrom abc import ABC, abstractmethod\nimport argparse\nimport itertools\n\n\nclass SAS(ABC):\n\n def __init__(self, **kwargs):\n prop_defaults = {\n \"primary_var\": defaultdict(dict),\n \"secondary_var\": defaultdict(dict),\n \"initial_assignment\": {},\n \"goal\": {},\n \"axiom_layer\": defaultdict(int),\n \"metric\": True,\n \"version\": 3,\n \"mutex_group\": [],\n \"axioms\": set(),\n \"operators\": [],\n }\n for (prop, default) in prop_defaults.items():\n setattr(self, prop, kwargs.get(prop, default))\n\n @abstractmethod\n def __repr__(self):\n pass\n\n @classmethod\n def from_file(cls, filename):\n sas = cls()\n with open(filename, \"r\") as myfile:\n for line in myfile.readlines():\n m = re.match(\"begin_(.*)\", line)\n m2 = re.match(\"end_(.*)\", line)\n if m:\n contents = []\n elif m2:\n sas.parse(m2.group(1), contents)\n else:\n contents.append(line.rstrip('\\n'))\n return sas\n\n def parse(self, group, contents):\n if hasattr(self, \"parse_\" + group):\n f = getattr(self, \"parse_\" + group)\n f(contents)\n\n def parse_version(self, lines):\n assert(len(lines) == 1)\n self.version = int(lines[0])\n\n def parse_metric(self, lines):\n assert(len(lines) == 1)\n self.metric = int(lines[0])\n\n def parse_state(self, lines):\n for index, value in enumerate(lines):\n self.initial_assignment[index] = int(value)\n\n def parse_goal(self, lines):\n for line in (lines[1:]):\n nums = [int(num) for num in line.split(' ')]\n self.goal[nums[0]] = nums[1]\n\n def parse_mutex_group(self, lines):\n group = []\n for line in (lines[1:]):\n nums = [int(num) for num in line.split(' ')]\n group.append((nums))\n self.mutex_group.append(group)\n\n def parse_rule(self, lines):\n prevail = {}\n effect = {}\n\n num_prevail = int(lines[0])\n for line in lines[1:1 + num_prevail]:\n (var, value) = [int(num) for num in line.split(' ')]\n prevail[var] = value\n\n for line in lines[num_prevail + 1:num_prevail + 2]:\n (var, fr, to) = [int(num) for num in line.split(' ')]\n if var in prevail and (not prevail[var] == fr):\n return\n effect[var] = (fr, to)\n\n axiom = Axiom.from_prevail(\"axiom\",prevail, effect)\n self.axioms.add(axiom)\n\n def version2str(self):\n return (\"begin_version\\n\"\n + \"{}\\n\".format(self.version)\n + \"end_version\\n\")\n\n def metric2str(self):\n return (\"begin_metric\\n\"\n + \"{:d}\\n\".format(1 if self.metric else 0)\n + \"end_metric\\n\")\n\n def mutex_group2str(self):\n res = '{}\\n'.format(len(self.mutex_group))\n for group in self.mutex_group:\n res += ('begin_mutex_group\\n'\n + '{}\\n'.format(len(group)))\n for var, value in group:\n res += \"{} {}\\n\".format(var, value)\n res += 'end_mutex_group\\n'\n return res\n\n def state2str(self):\n res = 'begin_state\\n'\n for index, value in sorted(self.initial_assignment.items(), key=(lambda x: x[0])):\n res += '{}\\n'.format(value)\n res += 'end_state\\n'\n return res\n\n def goal2str(self):\n res = 'begin_goal\\n'\n res += '{}\\n'.format(len(self.goal))\n for index, value in sorted(self.goal.items(), key=(lambda x: x[0])):\n res += '{} {}\\n'.format(index, value)\n res += 'end_goal\\n'\n return res\n\n def rules2str(self):\n res = '{}\\n'.format(len(self.axioms))\n for rule in sorted(self.axioms):\n res += str(rule)\n return res\n\n def is_essential(self, var):\n return self.axiom_layer[var] == -1\n","repo_name":"dosydon/sas","sub_path":"sas/sas.py","file_name":"sas.py","file_ext":"py","file_size_in_byte":4169,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"30049221672","text":"from django.shortcuts import render\nfrom django.http import HttpResponse,JsonResponse\n\n# Create your views here.\n\n\ndef hello(request):\n # return HttpResponse(\"hello,django\")\n # 设置字体大小及红色\n # return HttpResponse('

hello,django

')\n # 设置字居中\n # return HttpResponse('

hello,django

')\n # 添加文本框\n # 所有\n print(request.scheme)\n print(request.method)\n if request.method == \"GET\":\n return render(request, \"demo_app/hello.html\")\n if request.method == \"POST\":\n # 拿到post请求里的用户名密码\n user = request.POST.get(\"username\")\n pswd = request.POST.get(\"password\")\n print(user, pswd)\n if user == \"admin\" and pswd == \"123\":\n # return render(request, \"demo_app/hello.html\", {\"hint\":\"登录成功\"})\n return JsonResponse({\"success\": True, \"message\": \"登录成功\"})\n else:\n # return render(request, \"demo_app/hello.html\", {\"hint\": \"登录失败\"})\n return JsonResponse({\"success\": False, \"message\": \"登录失败\"})\n\n\ndef calculator(request):\n print(request.scheme)\n print(request.method)\n if request.method == \"GET\":\n return render(request, \"demo_app/calculator.html\")\n if request.method == \"POST\":\n # 拿到post请求里的a,b\n a = request.POST.get(\"number_a\")\n b = request.POST.get(\"number_b\")\n print(a, b)\n count = int(a)+int(b)\n return render(request, \"demo_app/calculator.html\", {\"result\": count})\n","repo_name":"susiehometest/test_platform","sub_path":"demo_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"35082625842","text":"import gmsh\nimport numpy as np\nimport cadquery as cq\nfrom cadquery.cq import CQObject\nfrom typing import Callable, Iterable, Literal, Optional, Sequence, Union, cast\nfrom cadquery.selectors import Selector\nfrom meshql.entity import CQEntityContext, Entity\nfrom meshql.preprocessing.split import split_workplane\nfrom meshql.transaction import Transaction, TransactionContext\nfrom meshql.transactions.algorithm import MeshAlgorithm2DType, MeshAlgorithm3DType, MeshSubdivisionType, SetMeshAlgorithm2D, SetMeshAlgorithm3D, SetSubdivisionAlgorithm\nfrom meshql.transactions.boundary_layer import UnstructuredBoundaryLayer, UnstructuredBoundaryLayer2D, get_boundary_ratio\nfrom meshql.transactions.physical_group import SetPhysicalGroup\nfrom meshql.transactions.refinement import Recombine, Refine, SetMeshSize, SetSmoothing\nfrom meshql.transactions.transfinite import SetTransfiniteEdge, SetTransfiniteFace, SetTransfiniteSolid, TransfiniteArrangementType, TransfiniteMeshType\nfrom meshql.mesh.exporters import export_to_su2\nfrom meshql.utils.cq import CQ_TYPE_RANKING, CQ_TYPE_STR_MAPPING, CQExtensions, CQGroupTypeString, CQLinq, CQType\nfrom meshql.utils.types import OrderedSet\nfrom meshql.visualizer import visualize_mesh\nfrom jupyter_cadquery import show\n\nclass GeometryQL:\n _workplane: cq.Workplane\n _initial_workplane: cq.Workplane\n def __init__(self) -> None:\n self._initial_workplane = self._workplane = None # type: ignore\n self._ctx = TransactionContext()\n self.is_structured = False\n self._transfinite_edge_groups = list[set[cq.Edge]]()\n def __enter__(self):\n gmsh.initialize()\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n gmsh.finalize()\n\n def end(self, num: Optional[int] = None):\n if num is None:\n self._workplane = self._initial_workplane\n else:\n self._workplane = self._workplane.end(num)\n return self\n\n def load(self, target: Union[cq.Workplane, str, Iterable[CQObject]], splits: Optional[Callable[[cq.Workplane], Sequence[cq.Face]]] = None, use_cache: bool = False):\n assert self._workplane is None, \"Workplane is already loaded.\"\n\n workplane = self._initial_workplane = CQExtensions.import_workplane(target)\n is_2d = CQExtensions.get_dimension(workplane) == 2\n\n # extrudes 2D shapes to 3D\n if is_2d:\n workplane = workplane.extrude(-1)\n\n if splits:\n workplane = split_workplane(workplane, splits(workplane), use_cache)\n\n\n if is_2d:\n # fuses top faces to appear as one Compound in GMSH\n faces = cast(Sequence[cq.Face], workplane.faces(\">Z\").vals())\n fused_face = CQExtensions.fuse_shapes(faces)\n self._initial_workplane = cq.Workplane(fused_face)\n else:\n self._initial_workplane = workplane\n\n self._type_groups = CQLinq.groupByTypes(self._initial_workplane, exclude_split=is_2d)\n\n\n self._workplane = self._initial_workplane\n topods = self._workplane.toOCC()\n gmsh.model.occ.importShapesNativePointer(topods._address())\n gmsh.model.occ.synchronize()\n\n self._entity_ctx = CQEntityContext(self._workplane)\n\n self._tag_workplane()\n\n return self \n \n\n def _tag_workplane(self):\n \"Tag all gmsh entity tags to workplane\"\n for cq_type, registry in self._entity_ctx.entity_registries.items():\n for occ_obj in registry.keys():\n tag = f\"{cq_type}/{registry[occ_obj].tag}\"\n self._workplane.newObject([occ_obj]).tag(tag)\n\n def solids(self, selector: Union[Selector, str, None] = None, tag: Union[str, None] = None, type: Optional[CQGroupTypeString] = None, indices: Optional[Sequence[int]] = None):\n obj_type = type and self._type_groups[type]\n selector = CQExtensions.get_selector(selector, obj_type, indices)\n self._workplane = self._workplane.solids(selector, tag)\n return self\n\n def faces(self, selector: Union[Selector, str, None] = None, tag: Union[str, None] = None, type: Optional[CQGroupTypeString] = None, indices: Optional[Sequence[int]] = None):\n obj_type = type and self._type_groups[type]\n selector = CQExtensions.get_selector(selector, obj_type, indices)\n self._workplane = self._workplane.faces(selector, tag)\n return self\n \n def edges(self, selector: Union[Selector, str, None] = None, tag: Union[str, None] = None, type: Optional[CQGroupTypeString] = None, indices: Optional[Sequence[int]] = None):\n obj_type = type and self._type_groups[type]\n selector = CQExtensions.get_selector(selector, obj_type, indices)\n self._workplane = self._workplane.edges(selector, tag)\n return self\n\n def wires(self, selector: Union[Selector, str, None] = None, tag: Union[str, None] = None, type: Optional[CQGroupTypeString] = None, indices: Optional[Sequence[int]] = None):\n obj_type = type and self._type_groups[type]\n selector = CQExtensions.get_selector(selector, obj_type, indices)\n self._workplane = self._workplane.wires(selector, tag)\n return self\n\n def vertices(self, selector: Union[Selector, str, None] = None, tag: Union[str, None] = None, type: Optional[CQGroupTypeString] = None, indices: Optional[Sequence[int]] = None):\n obj_type = type and self._type_groups[type]\n selector = CQExtensions.get_selector(selector, obj_type, indices)\n self._workplane = self._workplane.vertices(selector, tag)\n return self\n\n def vals(self):\n return self._entity_ctx.select_many(self._workplane)\n\n def val(self):\n return self._entity_ctx.select(self._workplane.val())\n\n\n def tag(self, names: Union[str, Sequence[str]]):\n if isinstance(names, str):\n self._workplane.tag(names)\n else:\n for i, cq_obj in enumerate(self._workplane.vals()):\n self._workplane.newObject([cq_obj]).tag(names[i])\n return self\n\n def fromTagged(self, tags: Union[str, Iterable[str]], resolve_type: Optional[CQType] = None, invert: bool = True): \n if isinstance(tags, str) and resolve_type is None:\n self._workplane = self._workplane._getTagged(tags)\n else:\n tagged_objs = list(CQLinq.select_tagged(self._workplane, tags, resolve_type))\n tagged_cq_type = CQ_TYPE_STR_MAPPING[type(tagged_objs[0])]\n workplane_objs = CQLinq.select(self._workplane, tagged_cq_type)\n filtered_objs = CQLinq.filter(workplane_objs, tagged_objs, invert)\n self._workplane = self._workplane.newObject(filtered_objs)\n return self\n\n def addPhysicalGroup(self, group: Union[str, Sequence[str]]):\n if isinstance(group, str):\n set_physical_group = SetPhysicalGroup(self.vals(), group)\n self._ctx.add_transaction(set_physical_group)\n else:\n objs = list(self.vals())\n group_entities: dict[str, OrderedSet[Entity]] = {}\n\n for i, group_name in enumerate(group):\n new_group_entity = objs[i]\n if group_name not in group_entities:\n group_entities[group_name] = OrderedSet()\n group_entities[group_name].add(new_group_entity)\n \n for group_name, group_objs in group_entities.items():\n set_physical_group = SetPhysicalGroup(group_objs, group_name)\n self._ctx.add_transaction(set_physical_group)\n\n return self\n\n def recombine(self, angle: float = 45):\n faces = self._entity_ctx.select_many(self._workplane, \"face\")\n recombines = [Recombine(face, angle) for face in faces]\n self._ctx.add_transactions(recombines)\n return self\n\n def setMeshSize(self, size: Union[float, Callable[[float,float,float], float]]):\n points = self._entity_ctx.select_many(self._workplane, \"vertex\")\n set_size = SetMeshSize(points, size)\n self._ctx.add_transaction(set_size)\n return self\n\n def setMeshAlgorithm(self, type: MeshAlgorithm2DType, per_face: bool = False):\n faces = self._entity_ctx.select_many(self._workplane, \"face\")\n if per_face:\n set_algorithms = [SetMeshAlgorithm2D(type, face) for face in faces]\n self._ctx.add_transactions(set_algorithms)\n else:\n set_algorithm = SetMeshAlgorithm2D(type)\n self._ctx.add_transaction(set_algorithm)\n \n return self\n\n def setMeshAlgorithm3D(self, type: MeshAlgorithm3DType):\n set_algorithm3D = SetMeshAlgorithm3D(type)\n self._ctx.add_transaction(set_algorithm3D)\n return self\n\n def setSubdivisionAlgorithm(self, type: MeshSubdivisionType):\n set_subdivision_algorithm = SetSubdivisionAlgorithm(type)\n self._ctx.add_transaction(set_subdivision_algorithm)\n return self\n\n def smooth(self, num_smooths = 1):\n faces = self._entity_ctx.select_many(self._workplane)\n set_smoothings = [SetSmoothing(face, num_smooths) for face in faces]\n self._ctx.add_transactions(set_smoothings)\n return self\n\n def refine(self, num_refines = 1):\n refine = Refine(num_refines)\n self._ctx.add_transaction(refine)\n return self\n\n def setTransfiniteEdge(self, num_nodes: Optional[Union[Sequence[int], int]] = None, mesh_type: Optional[Union[TransfiniteMeshType, Sequence[TransfiniteMeshType]]] = None, coef: Optional[Union[float, Sequence[float]]] = None):\n edge_batch = self._entity_ctx.select_batch(self._workplane, \"face\", \"edge\")\n for edges in edge_batch:\n for i, edge in enumerate(edges):\n transaction = cast(SetTransfiniteEdge, self._ctx.get_transaction(SetTransfiniteEdge, edge))\n if transaction is not None:\n if num_nodes is not None:\n transaction.num_elems = num_nodes if isinstance(num_nodes, int) else num_nodes[i]\n if mesh_type is not None:\n transaction.mesh_type = mesh_type if isinstance(mesh_type, str) else mesh_type[i]\n if coef is not None:\n transaction.coef = coef if isinstance(coef, (int, float)) else coef[i]\n else:\n assert num_nodes is not None, \"num_nodes must be specified\"\n mesh_type = mesh_type or \"Progression\"\n coef = coef or 1.0\n set_transfinite_edge = SetTransfiniteEdge(\n edge, \n num_nodes if isinstance(num_nodes, int) else num_nodes[i], \n mesh_type if isinstance(mesh_type, str) else mesh_type[i], \n coef if isinstance(coef, (int, float)) else coef[i]\n )\n self._ctx.add_transaction(set_transfinite_edge)\n\n return self\n\n def setTransfiniteFace(self, arrangement: TransfiniteArrangementType = \"Left\"):\n self.is_structured = True \n cq_face_batch = CQLinq.select_batch(self._workplane, \"solid\", \"face\")\n for i, cq_faces in enumerate(cq_face_batch):\n faces = self._entity_ctx.select_many(cq_faces)\n set_transfinite_faces = [SetTransfiniteFace(face, arrangement) for face in faces]\n self._ctx.add_transactions(set_transfinite_faces)\n\n return self\n\n def setTransfiniteSolid(self):\n self.is_structured = True \n solids = self._entity_ctx.select_many(self._workplane, \"solid\")\n set_transfinite_solids = [SetTransfiniteSolid(solid) for solid in solids]\n self._ctx.add_transactions(set_transfinite_solids)\n return self\n\n def _getTransfiniteEdgeGroups(self, cq_faces: Sequence[cq.Face]):\n transfinite_edge_groups: list[set[cq.Edge]] = []\n for cq_face in cq_faces:\n sorted_edges = CQLinq.sort(cq_face.Edges())\n for i, path in enumerate(sorted_edges):\n cq_edge = path.edge\n parllel_edge_index = (i+2 if i+2 < len(sorted_edges) else (i+2) - len(sorted_edges))\n cq_parllel_edge = sorted_edges[parllel_edge_index].edge\n found_group: Optional[set] = None\n for i, group in enumerate(transfinite_edge_groups):\n if not found_group:\n if cq_edge in group:\n group.add(cq_parllel_edge)\n found_group = group\n elif cq_parllel_edge in group:\n group.add(cq_edge)\n found_group = group\n else: \n if cq_edge in group or cq_parllel_edge in group:\n found_group.update(group)\n transfinite_edge_groups.remove(group)\n\n if found_group is None:\n transfinite_edge_groups.append(set([path.edge, cq_parllel_edge]))\n return transfinite_edge_groups\n\n def _setTransfiniteFaceAuto(\n self, \n cq_faces: Sequence[cq.Face], \n max_nodes: int, \n min_nodes: int = 1,\n arrangement: TransfiniteArrangementType = \"Left\"\n ):\n self.is_structured = True \n for cq_face in cq_faces:\n face = self._entity_ctx.select(cq_face)\n set_transfinite_face = SetTransfiniteFace(face, arrangement)\n self._ctx.add_transaction(set_transfinite_face)\n self._transfinite_edge_groups = self._getTransfiniteEdgeGroups(cq_faces)\n \n for transfinite_group in self._transfinite_edge_groups:\n total_length = sum([cq_edge.Length() for cq_edge in transfinite_group])\n group_max_num_nodes = 0\n for cq_edge in transfinite_group:\n edge_num_nodes = int(np.ceil((cq_edge.Length()/total_length)*max_nodes))\n if edge_num_nodes < min_nodes:\n edge_num_nodes = min_nodes\n if edge_num_nodes > group_max_num_nodes:\n group_max_num_nodes = edge_num_nodes\n \n assert group_max_num_nodes > 0, \"group_max_num_nodes must be greater than 0, make num_nodes higher\"\n group_edges = self._entity_ctx.select_many(transfinite_group)\n set_transfinite_edges = [SetTransfiniteEdge(edge, group_max_num_nodes) for edge in group_edges]\n self._ctx.add_transactions(set_transfinite_edges)\n\n\n def addTransaction(self, toTransaction: Callable[[\"GeometryQL\"], Transaction]):\n self._ctx.add_transaction(toTransaction(self))\n return self\n\n def setTransfiniteAuto(\n self,\n max_nodes: int,\n min_nodes: int = 1,\n auto_recombine: bool = True\n ):\n self.is_structured = True\n if CQExtensions.get_dimension(self._workplane) == 2:\n cq_faces = cast(Sequence[cq.Face], list(CQLinq.select(self._workplane, \"face\")))\n self._setTransfiniteFaceAuto(cq_faces, max_nodes, min_nodes)\n\n else:\n for cq_solid in cast(Sequence[cq.Solid], CQLinq.select(self._workplane, \"solid\")):\n solid = self._entity_ctx.select(cq_solid)\n set_transfinite_solid = SetTransfiniteSolid(solid)\n self._ctx.add_transaction(set_transfinite_solid)\n cq_faces = cast(Sequence[cq.Face], list(CQLinq.select(self._workplane, \"face\")))\n self._setTransfiniteFaceAuto(cq_faces, max_nodes, min_nodes)\n\n # transfinite_auto = SetTransfiniteAuto()\n # self._ctx.add_transaction(transfinite_auto)\n\n\n if auto_recombine:\n self.recombine()\n\n return self\n\n def _addStructuredBoundaryLayer(\n self, \n cq_objs: Sequence[CQObject], \n size: Optional[float] = None,\n ratio: Optional[float] = None,\n ):\n assert self.is_structured, \"Structured boundary layer can only be applied after setTransfiniteAuto\"\n assert (size is None) != (ratio is None), \"Either size or ratio must be specified, not both\"\n\n boundary_vertices = list(CQLinq.select(cq_objs, \"vertex\"))\n\n for (cq_edge, edge) in self._entity_ctx.entity_registries[\"edge\"].items():\n transaction = cast(SetTransfiniteEdge, self._ctx.get_transaction(SetTransfiniteEdge, edge))\n assert edge.type == \"edge\", \"StructuredBoundaryLayer only accepts edges\"\n if size:\n edge_ratio = get_boundary_ratio(cq_edge.Length(), size, transaction.num_elems) # type: ignore\n elif ratio:\n edge_ratio = ratio\n else:\n raise ValueError(\"Either size or ratio must be specified, not both\")\n cq_curr_edge_vertices = cq_edge.Vertices() # type: ignore\n if cq_curr_edge_vertices[0] in boundary_vertices and cq_curr_edge_vertices[-1] not in boundary_vertices:\n transaction.coef = edge_ratio\n\n elif cq_curr_edge_vertices[-1] in boundary_vertices and cq_curr_edge_vertices[0] not in boundary_vertices:\n transaction.coef = -edge_ratio\n\n def addBoundaryLayer(self, size: float, ratio: Optional[float] = None, num_layers: Optional[int] = None, auto_recombine: bool = True):\n if self.is_structured:\n self._addStructuredBoundaryLayer(self._workplane.vals(), size, ratio)\n else:\n ratio = ratio or 1.0\n assert num_layers is not None and size is not None and ratio is not None, \"num_layers, hwall_n and ratio must be specified for unstructured boundary layer\"\n if CQ_TYPE_RANKING[type(self._workplane.val())] < CQ_TYPE_RANKING[cq.Face]:\n boundary_layer = UnstructuredBoundaryLayer2D(self.vals(), ratio, size, num_layers)\n else:\n boundary_layer = UnstructuredBoundaryLayer(self.vals(), ratio, size, num_layers)\n if auto_recombine:\n self.recombine()\n self._ctx.add_transaction(boundary_layer)\n return self\n\n def generate(self, dim: int = 3):\n self._ctx.generate(dim)\n return self\n\n def write(self, filename: str, dim: int = 3):\n if self._ctx.mesh is None:\n self.generate(dim)\n assert self._ctx.mesh is not None\n if filename.endswith(\".su2\"):\n export_to_su2(self._ctx.mesh, filename)\n else:\n gmsh.write(filename)\n return self\n\n def showTransfiniteGroup(self, group_index: int):\n assert self.is_structured, \"Structured boundary layer can only be applied after setTransfiniteAuto\"\n assert group_index < len(self._transfinite_edge_groups), f\"Group index {group_index} is out of range\"\n group = self._transfinite_edge_groups[group_index]\n show(self._workplane.newObject(group), theme=\"dark\")\n return self\n\n def show(self, type: Literal[\"gmsh\", \"mesh\", \"cq\", \"plot\"] = \"cq\", only_markers: bool = False):\n if type == \"gmsh\":\n gmsh.fltk.run()\n elif type == \"mesh\":\n assert self._ctx.mesh is not None, \"Mesh is not generated yet.\"\n visualize_mesh(self._ctx.mesh, only_markers=only_markers)\n elif type == \"plot\":\n CQExtensions.plot_cq(self._workplane, ctx=self._entity_ctx)\n elif type == \"cq\":\n show(self._workplane, theme=\"dark\")\n else:\n raise NotImplementedError(f\"Unknown show type {type}\")\n return self\n\n\n def close(self):\n gmsh.finalize()\n","repo_name":"OpenOrion/meshql","sub_path":"meshql/ql.py","file_name":"ql.py","file_ext":"py","file_size_in_byte":19545,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"40"} +{"seq_id":"40473808259","text":"\"\"\"\nFunctionality to identify candidates for hi absorption\n\n1. get all the sources from all beams \nand for each source\n2. determine ratio of flux to noise\n3. keep source only if ratio is below -3sigma (assumes good continuum subtraction)\n\"\"\"\n\nimport os\nimport numpy as np\nimport glob\nimport logging\nimport datetime\nimport shutil\nfrom astropy.table import Table, hstack, vstack\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_source_spec_file(src_name, src_nr, beam, cube_dir):\n \"\"\"\n Function to get the spectrum file for a given source\n\n Args:\n -----\n src_name (str): Name of the source (J2000 coordinates)\n src_nr (int): Number of the source in the beam\n beam (int): Number of the beam\n cube_dir (int): Directory of the cube that contains the beam and the source\n\n Return:\n -------\n (str): Path to the spectrum file of the source\n \"\"\"\n\n return os.path.join(cube_dir, \"{0}/sharpOut/spec/{1}_J{2}.txt\".format(str(beam).zfill(2), src_nr, src_name))\n\n\ndef find_candidate(src_data, output_file_name_candidates, negative_snr_threshold=-5, positive_snr_threshold=5):\n \"\"\"\n Function to check the snr results for candidates\n \"\"\"\n\n # first get all sources with negative SNR entries\n src_data_neg_snr = src_data[np.where(\n src_data['Max_Negative_SNR'] <= negative_snr_threshold)]\n\n # get the number of sources\n n_src_neg_snr = np.size(src_data_neg_snr['Source_ID'])\n\n logger.info(\n \"Found {} sources exceeding negative SNR threshold\".format(n_src_neg_snr))\n\n # second, get the sources that have no positive SNR entries\n src_data_neg_snr_below_pos_snr = src_data_neg_snr[np.where(\n src_data_neg_snr['Max_Positive_SNR'] <= positive_snr_threshold)]\n\n # get the number of sources\n n_src_neg_snr_below_pos_snr = np.size(\n src_data_neg_snr_below_pos_snr['Source_ID'])\n n_src_neg_snr_above_pos_snr = n_src_neg_snr - n_src_neg_snr_below_pos_snr\n\n logger.info(\"Disregarding {0} sources out of {1} that exceed positive SNR threshold\".format(\n n_src_neg_snr_above_pos_snr, n_src_neg_snr))\n\n logger.info(\"Found {0} candidates for absorption after checking negative and positive SNR thresholds\".format(\n n_src_neg_snr_below_pos_snr))\n\n snr_candidates = src_data_neg_snr_below_pos_snr['Source_ID']\n\n if n_src_neg_snr_below_pos_snr == 0:\n logger.info(\"No candidates were found\".format(str(snr_candidates)))\n else:\n logger.info(\"Candidates are: {}\".format(str(snr_candidates)))\n\n # writing file\n logger.info(\"Writing candidates to file {}\".format(\n output_file_name_candidates))\n src_data_neg_snr_below_pos_snr.write(\n output_file_name_candidates, format=\"ascii.csv\", overwrite=True)\n\n return snr_candidates\n\n\ndef get_max_negative_snr(spec_data, src_name, rms=None):\n \"\"\"\n Function to get the maximum negative SNR and supplementary information\n \"\"\"\n\n # try to determine the snr\n if rms is not None:\n ratio = np.nanmin(spec_data[\"Flux [Jy]\"]) / rms\n else:\n # after checking that noise is not 0:\n noise_check = np.unique(spec_data[\"Noise [Jy]\"])\n if np.size(noise_check) and noise_check[0] == 0:\n logger.warning(\n \"Calculating SNR failed for {0}. No noise information\".format(src_name))\n ratio = None\n else:\n ratio = spec_data[\"Flux [Jy]\"] / spec_data[\"Noise [Jy]\"]\n\n if ratio is None:\n max_negative_snr = 0\n max_negative_snr_ch = 0\n max_negative_snr_freq = 0\n elif rms is not None:\n max_negative_snr = ratio\n max_negative_snr_ch = np.where(\n spec_data[\"Flux [Jy]\"] == np.nanmin(spec_data[\"Flux [Jy]\"]))[0][0]\n max_negative_snr_freq = spec_data['Frequency [Hz]'][max_negative_snr_ch]\n else:\n max_negative_snr = np.nanmin(ratio)\n max_negative_snr_ch = np.where(ratio == max_negative_snr)[0][0]\n max_negative_snr_freq = spec_data['Frequency [Hz]'][max_negative_snr_ch]\n\n return max_negative_snr, max_negative_snr_ch, max_negative_snr_freq\n\n\ndef get_max_positive_snr(spec_data, src_name, rms=None):\n \"\"\"\n Function to get the maximum positive SNR and supplementary information\n \"\"\"\n\n # try to determine the snr\n if rms is not None:\n ratio = np.nanmax(spec_data[\"Flux [Jy]\"]) / rms\n else:\n # after checking that noise is not 0:\n noise_check = np.unique(spec_data[\"Noise [Jy]\"])\n if np.size(noise_check) and noise_check[0] == 0:\n logger.warning(\n \"Calculating SNR failed for {0}. No noise information\".format(src_name))\n ratio = None\n else:\n ratio = spec_data[\"Flux [Jy]\"] / spec_data[\"Noise [Jy]\"]\n\n if ratio is None:\n max_positive_snr = 0\n max_positive_snr_ch = 0\n max_positive_snr_freq = 0\n elif rms is not None:\n max_positive_snr = ratio\n max_positive_snr_ch = np.where(\n spec_data[\"Flux [Jy]\"] == np.nanmax(spec_data[\"Flux [Jy]\"]))[0][0]\n max_positive_snr_freq = spec_data['Frequency [Hz]'][max_positive_snr_ch]\n else:\n max_positive_snr = np.nanmax(ratio)\n max_positive_snr_ch = np.where(ratio == max_positive_snr)[0][0]\n max_positive_snr_freq = spec_data['Frequency [Hz]'][max_positive_snr_ch]\n\n return max_positive_snr, max_positive_snr_ch, max_positive_snr_freq\n\n\ndef analyse_spectra(src_cat_file, output_file_name_candidates, cube_dir, do_subtract_median=True, do_subtract_mean=False, use_rms=True, negative_snr_threshold=-5, positive_snr_threshold=5, create_candidate_table_backup=True):\n \"\"\"\n Function to run quality check and find candidates for absorption\n \"\"\"\n\n logger.info(\"#### Searching for candidates\")\n\n # check for existing candidate table\n if create_candidate_table_backup and os.path.exists(output_file_name_candidates):\n table_backup_dir = os.path.join(\n cube_dir, \"candidate_table_backup\")\n if not os.path.exists(table_backup_dir):\n os.mkdir(table_backup_dir)\n table_backup_name = os.path.join(table_backup_dir, os.path.basename(output_file_name_candidates).replace(\n \".csv\", \"_{}.csv\".format(datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\"))))\n logger.info(\"Creating a copy of current candidate table in {0}\".format(\n table_backup_name))\n shutil.copy2(output_file_name_candidates, table_backup_name)\n\n # get the source data\n if not os.path.exists(src_cat_file):\n error = \"Could not find src file {}\".format(src_cat_file)\n logger.error(error)\n raise RuntimeError(error)\n else:\n src_data = Table.read(src_cat_file, format=\"ascii.csv\")\n\n # number of sources\n n_src = np.size(src_data['Source_ID'])\n logger.info(\"Found {} sources to analyse\".format(n_src))\n\n # get a list of beams\n beam_list = np.unique(src_data['Beam'])\n\n # new columns\n mean_noise = np.zeros(n_src)\n median_noise = np.zeros(n_src)\n rms = np.zeros(n_src)\n min_flux = np.zeros(n_src)\n max_flux = np.zeros(n_src)\n mean_flux = np.zeros(n_src)\n median_flux = np.zeros(n_src)\n snr_candidates = np.zeros(n_src)\n max_negative_snr = np.zeros(n_src)\n max_negative_snr_ch = np.zeros(n_src)\n max_negative_snr_freq = np.zeros(n_src)\n max_positive_snr = np.zeros(n_src)\n max_positive_snr_ch = np.zeros(n_src)\n max_positive_snr_freq = np.zeros(n_src)\n\n # names of table columns\n new_col_names = [\"Mean_Noise\", \"Median_Noise\", \"RMS\", \"Min_Flux\", \"Max_Flux\", \"Mean_Flux\", \"Median_Flux\", \"Candidate_SNR\", \"Max_Negative_SNR\",\n \"Max_Negative_SNR_Channel\", \"Max_Negative_SNR_Frequency\", \"Max_Positive_SNR\", \"Max_Positive_SNR_Channel\", \"Max_Positive_SNR_Frequency\"]\n # removes these if they exists\n try:\n src_data.remove_columns(new_col_names)\n except Exception as e:\n pass\n else:\n logger.debug(\"Removed table entries from previous analysis run\")\n\n # The following test will not work with astropy 4.0 and higher\n # but this will only matter if Apersharp is upgraded to Python3\n if src_data.masked:\n src_data = src_data.filled()\n\n # go through the each source files\n for src_index in range(n_src):\n\n src_id = src_data['Source_ID'][src_index]\n\n logger.info(\"## Processing {}\".format(src_id))\n\n # get the spectrum file for the source\n src_spec_file = get_source_spec_file(\n src_data['J2000'][src_index], src_data['Beam_Source_ID'][src_index] - 1, src_data['Beam'][src_index], cube_dir)\n\n if not os.path.exists(src_spec_file):\n logger.warning(\"Did not find spectrum for source {0} in {1}\".format(\n src_id, src_spec_file))\n continue\n else:\n pass\n\n # read in the file\n spec_data = Table.read(src_spec_file, format=\"ascii\")\n\n # get mean noise\n mean_noise[src_index] = np.nanmean(spec_data['Noise [Jy]'])\n\n # get the median noise\n median_noise[src_index] = np.nanmedian(spec_data['Noise [Jy]'])\n\n # get mean flux\n mean_flux[src_index] = np.nanmean(spec_data['Flux [Jy]'])\n\n # get the median flux\n median_flux[src_index] = np.nanmedian(spec_data['Flux [Jy]'])\n\n # subtracting mean or median\n if do_subtract_median:\n logger.debug(\n \"Subtracting median: {} mJy/beam\".format(median_flux[src_index] * 1.e3))\n spec_data['Flux [Jy]'] = spec_data['Flux [Jy]'] - \\\n median_flux[src_index]\n elif do_subtract_mean:\n logger.debug(\n \"Subtracting mean: {} mJy/beam\".format(median_flux[src_index] * 1.e3))\n spec_data['Flux [Jy]'] = spec_data['Flux [Jy]'] - \\\n mean_flux[src_index]\n\n # get max flux\n max_flux[src_index] = np.nanmax(spec_data['Flux [Jy]'])\n\n # get min flux\n min_flux[src_index] = np.nanmin(spec_data['Flux [Jy]'])\n\n # get the rms\n rms[src_index] = np.nanstd(spec_data['Flux [Jy]'])\n\n if use_rms:\n # get maximum negative snr values\n max_negative_snr[src_index], max_negative_snr_ch[src_index], max_negative_snr_freq[src_index] = get_max_negative_snr(\n spec_data, src_id, rms=rms[src_index])\n\n # get maximum positive snr values\n max_positive_snr[src_index], max_positive_snr_ch[src_index], max_positive_snr_freq[src_index] = get_max_positive_snr(\n spec_data, src_id, rms=rms[src_index])\n else:\n # get maximum negative snr values\n max_negative_snr[src_index], max_negative_snr_ch[src_index], max_negative_snr_freq[src_index] = get_max_negative_snr(\n spec_data, src_id)\n\n # get maximum positive snr values\n max_positive_snr[src_index], max_positive_snr_ch[src_index], max_positive_snr_freq[src_index] = get_max_positive_snr(\n spec_data, src_id)\n\n # if snr_candidate[src_index] == 1:\n # logger.debug(\"Found candidate for absorption (SNR = {0})\".format(\n # max_negative_snr[src_index]))\n # else:\n # logger.debug(\"Not a candidate for absorption\")\n\n logger.info(\"## Processing {} ... Done\".format(src_id))\n\n # for storing new table later\n metrics_table = Table([mean_noise, median_noise, rms, min_flux, max_flux, mean_flux, median_flux, snr_candidates,\n max_negative_snr, max_negative_snr_ch, max_negative_snr_freq, max_positive_snr, max_positive_snr_ch, max_positive_snr_freq], names=new_col_names)\n\n # combine old and new table\n new_data_table = hstack([src_data, metrics_table])\n\n # get a list of candidates\n src_snr_candidates = find_candidate(\n new_data_table, output_file_name_candidates, negative_snr_threshold=negative_snr_threshold, positive_snr_threshold=positive_snr_threshold)\n\n # change entries for the candidate\n logger.info(\"Marking candidates in source catalogue\")\n for src in src_snr_candidates:\n new_data_table['Candidate_SNR'][np.where(\n new_data_table['Source_ID']) == src] = 1\n\n # write out table\n logger.info(\n \"Updating source catalogue {}\".format(src_cat_file))\n new_data_table.write(src_cat_file, format=\"ascii.csv\", overwrite=True)\n\n logger.info(\"#### Searching for candidates ... Done\")\n","repo_name":"rs1701/apersharp","sub_path":"lib/analyse_spectra.py","file_name":"analyse_spectra.py","file_ext":"py","file_size_in_byte":12414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"10706066420","text":"import re\nimport os\nimport time\n\npattern1 = re.compile(\"^[d]\") # zaczyna się od d\nprint(pattern1.match(\"dog\"))\n\npattern1 = re.compile(\"^[dD].{1,}[gG]$\") # zaczyna się na d lub D i kończy na g lub G\nprint(pattern1.match(\"DoG\"))\nprint(pattern1.match(\"d%g\",))\n\npostalCode = \"88 - 999\"\nresult = re.search(\"^[0-9]{2}\\s-\\s[0-9]{3}\", postalCode)\nif (result is None):\n print(\"Błąd kodu pocztowego\")\nelse:\n print(\"jest ok\")\n\nfilePattern = re.compile(\".*[\\.]{1}(pdf|ppt|pptx)$\")\npath = \"D:\\\\Moje Dokumenty\"\nos.chdir(path)\nfor file in os.listdir('.'):\n if (re.search(filePattern, file)):\n print(\"%50s | %10.2f MB\" % (file, os.path.getsize(file)/(10**6)), time.ctime((os.path.getctime(file))))","repo_name":"andrzeji-oss/kursp","sub_path":"dzien7/dzien7-1.py","file_name":"dzien7-1.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"70151292280","text":"r\"\"\"\nTensor Fields\n\nThe class :class:`TensorField` implements tensor fields on differentiable\nmanifolds. The derived class\n:class:`~sage.manifolds.differentiable.tensorfield_paral.TensorFieldParal`\nis devoted to tensor fields with values on parallelizable manifolds.\n\nVarious derived classes of :class:`TensorField` are devoted to specific tensor\nfields:\n\n* :class:`~sage.manifolds.differentiable.vectorfield.VectorField` for vector\n fields (rank-1 contravariant tensor fields)\n\n* :class:`~sage.manifolds.differentiable.automorphismfield.AutomorphismField`\n for fields of tangent-space automorphisms\n\n* :class:`~sage.manifolds.differentiable.diff_form.DiffForm` for differential\n forms (fully antisymmetric covariant tensor fields)\n\n* :class:`~sage.manifolds.differentiable.multivectorfield.MultivectorField`\n for multivector fields (fully antisymmetric contravariant tensor fields)\n\nAUTHORS:\n\n- Eric Gourgoulhon, Michal Bejger (2013-2015) : initial version\n- Travis Scrimshaw (2016): review tweaks\n- Eric Gourgoulhon (2018): operators divergence, Laplacian and d'Alembertian;\n method :meth:`TensorField.along`\n- Florentin Jaffredo (2018) : series expansion with respect to a given\n parameter\n- Michael Jung (2019): improve treatment of the zero element; add method\n :meth:`TensorField.copy_from`\n- Eric Gourgoulhon (2020): add method :meth:`TensorField.apply_map`\n\nREFERENCES:\n\n- [KN1963]_\n- [Lee2013]_\n- [ONe1983]_\n\n\"\"\"\n\n# *****************************************************************************\n# Copyright (C) 2015 Eric Gourgoulhon \n# Copyright (C) 2015 Michal Bejger \n# Copyright (C) 2016 Travis Scrimshaw \n#\n# Distributed under the terms of the GNU General Public License (GPL)\n# as published by the Free Software Foundation; either version 2 of\n# the License, or (at your option) any later version.\n# https://www.gnu.org/licenses/\n# *****************************************************************************\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Optional, Tuple, TypeVar, Union\n\nfrom sage.rings.integer import Integer\nfrom sage.rings.integer_ring import ZZ\nfrom sage.structure.element import ModuleElementWithMutability\nfrom sage.tensor.modules.comp import CompWithSym\nfrom sage.tensor.modules.free_module_tensor import FreeModuleTensor\nfrom sage.tensor.modules.tensor_with_indices import TensorWithIndices\n\nif TYPE_CHECKING:\n from sage.manifolds.differentiable.diff_map import DiffMap\n from sage.manifolds.differentiable.manifold import DifferentiableManifold\n from sage.manifolds.differentiable.metric import PseudoRiemannianMetric\n from sage.manifolds.differentiable.poisson_tensor import PoissonTensorField\n from sage.manifolds.differentiable.symplectic_form import SymplecticForm\n from sage.manifolds.differentiable.vectorfield_module import VectorFieldModule\n from sage.tensor.modules.comp import Components\n\n\nTensorType = Tuple[int, int]\nT = TypeVar(\"T\", bound=\"TensorField\")\n\n\nclass TensorField(ModuleElementWithMutability):\n r\"\"\"\n Tensor field along a differentiable manifold.\n\n An instance of this class is a tensor field along a differentiable\n manifold `U` with values on a differentiable manifold `M`, via a\n differentiable map `\\Phi: U \\rightarrow M`. More precisely, given two\n non-negative integers `k` and `l` and a differentiable map\n\n .. MATH::\n\n \\Phi:\\ U \\longrightarrow M,\n\n a *tensor field of type* `(k,l)` *along* `U` *with values on* `M` is\n a differentiable map\n\n .. MATH::\n\n t:\\ U \\longrightarrow T^{(k,l)}M\n\n (where `T^{(k,l)}M` is the tensor bundle of type `(k,l)` over `M`) such\n that\n\n .. MATH::\n\n \\forall p \\in U,\\ t(p) \\in T^{(k,l)}(T_q M)\n\n i.e. `t(p)` is a tensor of type `(k,l)` on the tangent space `T_q M` at\n the point `q = \\Phi(p)`, that is to say a multilinear map\n\n .. MATH::\n\n t(p):\\ \\underbrace{T_q^*M\\times\\cdots\\times T_q^*M}_{k\\ \\; \\mbox{times}}\n \\times \\underbrace{T_q M\\times\\cdots\\times T_q M}_{l\\ \\; \\mbox{times}}\n \\longrightarrow K,\n\n where `T_q^* M` is the dual vector space to `T_q M` and `K` is the\n topological field over which the manifold `M` is defined. The integer `k+l`\n is called the *tensor rank*.\n\n The standard case of a tensor\n field *on* a differentiable manifold corresponds to `U=M` and\n `\\Phi = \\mathrm{Id}_M`. Other common cases are `\\Phi` being an\n immersion and `\\Phi` being a curve in `M` (`U` is then an open interval\n of `\\RR`).\n\n If `M` is parallelizable, the class\n :class:`~sage.manifolds.differentiable.tensorfield_paral.TensorFieldParal`\n should be used instead.\n\n This is a Sage *element* class, the corresponding *parent* class being\n :class:`~sage.manifolds.differentiable.tensorfield_module.TensorFieldModule`.\n\n INPUT:\n\n - ``vector_field_module`` -- module `\\mathfrak{X}(U,\\Phi)` of vector\n fields along `U` associated with the map `\\Phi: U \\rightarrow M` (cf.\n :class:`~sage.manifolds.differentiable.vectorfield_module.VectorFieldModule`)\n - ``tensor_type`` -- pair `(k,l)` with `k` being the contravariant rank\n and `l` the covariant rank\n - ``name`` -- (default: ``None``) name given to the tensor field\n - ``latex_name`` -- (default: ``None``) LaTeX symbol to denote the tensor\n field; if none is provided, the LaTeX symbol is set to ``name``\n - ``sym`` -- (default: ``None``) a symmetry or a list of symmetries among\n the tensor arguments: each symmetry is described by a tuple containing\n the positions of the involved arguments, with the convention\n ``position = 0`` for the first argument; for instance:\n\n * ``sym = (0,1)`` for a symmetry between the 1st and 2nd arguments\n * ``sym = [(0,2), (1,3,4)]`` for a symmetry between the 1st and 3rd\n arguments and a symmetry between the 2nd, 4th and 5th arguments.\n\n - ``antisym`` -- (default: ``None``) antisymmetry or list of antisymmetries\n among the arguments, with the same convention as for ``sym``\n - ``parent`` -- (default: ``None``) some specific parent (e.g. exterior\n power for differential forms); if ``None``,\n ``vector_field_module.tensor_module(k,l)`` is used\n\n EXAMPLES:\n\n Tensor field of type (0,2) on the sphere `S^2`::\n\n sage: M = Manifold(2, 'S^2') # the 2-dimensional sphere S^2\n sage: U = M.open_subset('U') # complement of the North pole\n sage: c_xy. = U.chart() # stereographic coordinates from the North pole\n sage: V = M.open_subset('V') # complement of the South pole\n sage: c_uv. = V.chart() # stereographic coordinates from the South pole\n sage: M.declare_union(U,V) # S^2 is the union of U and V\n sage: xy_to_uv = c_xy.transition_map(c_uv, (x/(x^2+y^2), y/(x^2+y^2)),\n ....: intersection_name='W', restrictions1= x^2+y^2!=0,\n ....: restrictions2= u^2+v^2!=0)\n sage: uv_to_xy = xy_to_uv.inverse()\n sage: W = U.intersection(V)\n sage: t = M.tensor_field(0,2, name='t') ; t\n Tensor field t of type (0,2) on the 2-dimensional differentiable\n manifold S^2\n sage: t.parent()\n Module T^(0,2)(S^2) of type-(0,2) tensors fields on the 2-dimensional\n differentiable manifold S^2\n sage: t.parent().category()\n Category of tensor products of modules over Algebra of differentiable scalar fields\n on the 2-dimensional differentiable manifold S^2\n\n The parent of `t` is not a free module, for the sphere `S^2` is not\n parallelizable::\n\n sage: isinstance(t.parent(), FiniteRankFreeModule)\n False\n\n To fully define `t`, we have to specify its components in some vector\n frames defined on subsets of `S^2`; let us start by the open subset `U`::\n\n sage: eU = c_xy.frame()\n sage: t[eU,:] = [[1,0], [-2,3]]\n sage: t.display(eU)\n t = dx⊗dx - 2 dy⊗dx + 3 dy⊗dy\n\n To set the components of `t` on `V` consistently, we copy the expressions\n of the components in the common subset `W`::\n\n sage: eV = c_uv.frame()\n sage: eVW = eV.restrict(W)\n sage: c_uvW = c_uv.restrict(W)\n sage: t[eV,0,0] = t[eVW,0,0,c_uvW].expr() # long time\n sage: t[eV,0,1] = t[eVW,0,1,c_uvW].expr() # long time\n sage: t[eV,1,0] = t[eVW,1,0,c_uvW].expr() # long time\n sage: t[eV,1,1] = t[eVW,1,1,c_uvW].expr() # long time\n\n Actually, the above operation can be performed in a single line by means\n of the method\n :meth:`~sage.manifolds.differentiable.tensorfield.TensorField.add_comp_by_continuation`::\n\n sage: t.add_comp_by_continuation(eV, W, chart=c_uv) # long time\n\n At this stage, `t` is fully defined, having components in frames eU and eV\n and the union of the domains of eU and eV being the whole manifold::\n\n sage: t.display(eV) # long time\n t = (u^4 - 4*u^3*v + 10*u^2*v^2 + 4*u*v^3 + v^4)/(u^8 + 4*u^6*v^2 + 6*u^4*v^4 + 4*u^2*v^6 + v^8) du⊗du\n - 4*(u^3*v + 2*u^2*v^2 - u*v^3)/(u^8 + 4*u^6*v^2 + 6*u^4*v^4 + 4*u^2*v^6 + v^8) du⊗dv\n + 2*(u^4 - 2*u^3*v - 2*u^2*v^2 + 2*u*v^3 + v^4)/(u^8 + 4*u^6*v^2 + 6*u^4*v^4 + 4*u^2*v^6 + v^8) dv⊗du\n + (3*u^4 + 4*u^3*v - 2*u^2*v^2 - 4*u*v^3 + 3*v^4)/(u^8 + 4*u^6*v^2 + 6*u^4*v^4 + 4*u^2*v^6 + v^8) dv⊗dv\n\n Let us consider two vector fields, `a` and `b`, on `S^2`::\n\n sage: a = M.vector_field({eU: [-y, x]}, name='a')\n sage: a.add_comp_by_continuation(eV, W, chart=c_uv)\n sage: a.display(eV)\n a = -v ∂/∂u + u ∂/∂v\n sage: b = M.vector_field({eU: [y, -1]}, name='b')\n sage: b.add_comp_by_continuation(eV, W, chart=c_uv)\n sage: b.display(eV)\n b = ((2*u + 1)*v^3 + (2*u^3 - u^2)*v)/(u^2 + v^2) ∂/∂u\n - (u^4 - v^4 + 2*u*v^2)/(u^2 + v^2) ∂/∂v\n\n As a tensor field of type `(0,2)`, `t` acts on the pair `(a,b)`,\n resulting in a scalar field::\n\n sage: f = t(a,b); f\n Scalar field t(a,b) on the 2-dimensional differentiable manifold S^2\n sage: f.display() # long time\n t(a,b): S^2 → ℝ\n on U: (x, y) ↦ -2*x*y - y^2 - 3*x\n on V: (u, v) ↦ -(3*u^3 + (3*u + 1)*v^2 + 2*u*v)/(u^4 + 2*u^2*v^2 + v^4)\n\n The vectors can be defined only on subsets of `S^2`, the domain of the\n result is then the common subset::\n\n sage: s = t(a.restrict(U), b) ; s # long time\n Scalar field t(a,b) on the Open subset U of the 2-dimensional\n differentiable manifold S^2\n sage: s.display() # long time\n t(a,b): U → ℝ\n (x, y) ↦ -2*x*y - y^2 - 3*x\n on W: (u, v) ↦ -(3*u^3 + (3*u + 1)*v^2 + 2*u*v)/(u^4 + 2*u^2*v^2 + v^4)\n sage: s = t(a.restrict(U), b.restrict(W)) ; s # long time\n Scalar field t(a,b) on the Open subset W of the 2-dimensional\n differentiable manifold S^2\n sage: s.display() # long time\n t(a,b): W → ℝ\n (x, y) ↦ -2*x*y - y^2 - 3*x\n (u, v) ↦ -(3*u^3 + (3*u + 1)*v^2 + 2*u*v)/(u^4 + 2*u^2*v^2 + v^4)\n\n The tensor itself can be defined only on some open subset of `S^2`,\n yielding a result whose domain is this subset::\n\n sage: s = t.restrict(V)(a,b); s # long time\n Scalar field t(a,b) on the Open subset V of the 2-dimensional\n differentiable manifold S^2\n sage: s.display() # long time\n t(a,b): V → ℝ\n (u, v) ↦ -(3*u^3 + (3*u + 1)*v^2 + 2*u*v)/(u^4 + 2*u^2*v^2 + v^4)\n on W: (x, y) ↦ -2*x*y - y^2 - 3*x\n\n Tests regarding the multiplication by a scalar field::\n\n sage: f = M.scalar_field({c_xy: 1/(1+x^2+y^2),\n ....: c_uv: (u^2 + v^2)/(u^2 + v^2 + 1)}, name='f')\n sage: t.parent().base_ring() is f.parent()\n True\n sage: s = f*t; s # long time\n Tensor field f*t of type (0,2) on the 2-dimensional differentiable\n manifold S^2\n sage: s[[0,0]] == f*t[[0,0]] # long time\n True\n sage: s.restrict(U) == f.restrict(U) * t.restrict(U) # long time\n True\n sage: s = f*t.restrict(U); s\n Tensor field f*t of type (0,2) on the Open subset U of the 2-dimensional\n differentiable manifold S^2\n sage: s.restrict(U) == f.restrict(U) * t.restrict(U)\n True\n\n .. RUBRIC:: Same examples with SymPy as the symbolic engine\n\n From now on, we ask that all symbolic calculus on manifold `M` are\n performed by SymPy::\n\n sage: M.set_calculus_method('sympy')\n\n We define the tensor `t` as above::\n\n sage: t = M.tensor_field(0, 2, {eU: [[1,0], [-2,3]]}, name='t')\n sage: t.display(eU)\n t = dx⊗dx - 2 dy⊗dx + 3 dy⊗dy\n sage: t.add_comp_by_continuation(eV, W, chart=c_uv) # long time\n sage: t.display(eV) # long time\n t = (u**4 - 4*u**3*v + 10*u**2*v**2 + 4*u*v**3 + v**4)/(u**8 +\n 4*u**6*v**2 + 6*u**4*v**4 + 4*u**2*v**6 + v**8) du⊗du +\n 4*u*v*(-u**2 - 2*u*v + v**2)/(u**8 + 4*u**6*v**2 + 6*u**4*v**4\n + 4*u**2*v**6 + v**8) du⊗dv + 2*(u**4 - 2*u**3*v - 2*u**2*v**2\n + 2*u*v**3 + v**4)/(u**8 + 4*u**6*v**2 + 6*u**4*v**4 +\n 4*u**2*v**6 + v**8) dv⊗du + (3*u**4 + 4*u**3*v - 2*u**2*v**2 -\n 4*u*v**3 + 3*v**4)/(u**8 + 4*u**6*v**2 + 6*u**4*v**4 +\n 4*u**2*v**6 + v**8) dv⊗dv\n\n The default coordinate representations of tensor components are now\n SymPy objects::\n\n sage: t[eV,1,1,c_uv].expr() # long time\n (3*u**4 + 4*u**3*v - 2*u**2*v**2 - 4*u*v**3 + 3*v**4)/(u**8 +\n 4*u**6*v**2 + 6*u**4*v**4 + 4*u**2*v**6 + v**8)\n sage: type(t[eV,1,1,c_uv].expr()) # long time\n \n\n Let us consider two vector fields, `a` and `b`, on `S^2`::\n\n sage: a = M.vector_field({eU: [-y, x]}, name='a')\n sage: a.add_comp_by_continuation(eV, W, chart=c_uv)\n sage: a.display(eV)\n a = -v ∂/∂u + u ∂/∂v\n sage: b = M.vector_field({eU: [y, -1]}, name='b')\n sage: b.add_comp_by_continuation(eV, W, chart=c_uv)\n sage: b.display(eV)\n b = v*(2*u**3 - u**2 + 2*u*v**2 + v**2)/(u**2 + v**2) ∂/∂u\n + (-u**4 - 2*u*v**2 + v**4)/(u**2 + v**2) ∂/∂v\n\n As a tensor field of type `(0,2)`, `t` acts on the pair `(a,b)`,\n resulting in a scalar field::\n\n sage: f = t(a,b)\n sage: f.display() # long time\n t(a,b): S^2 → ℝ\n on U: (x, y) ↦ -2*x*y - 3*x - y**2\n on V: (u, v) ↦ (-3*u**3 - 3*u*v**2 - 2*u*v - v**2)/(u**4 + 2*u**2*v**2 + v**4)\n\n The vectors can be defined only on subsets of `S^2`, the domain of the\n result is then the common subset::\n\n sage: s = t(a.restrict(U), b)\n sage: s.display() # long time\n t(a,b): U → ℝ\n (x, y) ↦ -2*x*y - 3*x - y**2\n on W: (u, v) ↦ (-3*u**3 - 3*u*v**2 - 2*u*v - v**2)/(u**4 + 2*u**2*v**2 + v**4)\n sage: s = t(a.restrict(U), b.restrict(W)) # long time\n sage: s.display() # long time\n t(a,b): W → ℝ\n (x, y) ↦ -2*x*y - 3*x - y**2\n (u, v) ↦ (-3*u**3 - 3*u*v**2 - 2*u*v - v**2)/(u**4 + 2*u**2*v**2 + v**4)\n\n The tensor itself can be defined only on some open subset of `S^2`,\n yielding a result whose domain is this subset::\n\n sage: s = t.restrict(V)(a,b) # long time\n sage: s.display() # long time\n t(a,b): V → ℝ\n (u, v) ↦ (-3*u**3 - 3*u*v**2 - 2*u*v - v**2)/(u**4 + 2*u**2*v**2 + v**4)\n on W: (x, y) ↦ -2*x*y - 3*x - y**2\n\n Tests regarding the multiplication by a scalar field::\n\n sage: f = M.scalar_field({c_xy: 1/(1+x^2+y^2),\n ....: c_uv: (u^2 + v^2)/(u^2 + v^2 + 1)}, name='f')\n sage: s = f*t # long time\n sage: s[[0,0]] == f*t[[0,0]] # long time\n True\n sage: s.restrict(U) == f.restrict(U) * t.restrict(U) # long time\n True\n sage: s = f*t.restrict(U)\n sage: s.restrict(U) == f.restrict(U) * t.restrict(U)\n True\n\n Notice that the zero tensor field is immutable, and therefore its\n components cannot be changed::\n\n sage: zer = M.tensor_field_module((1, 1)).zero()\n sage: zer.is_immutable()\n True\n sage: zer.set_comp()\n Traceback (most recent call last):\n ...\n ValueError: the components of an immutable element cannot be\n changed\n\n Other tensor fields can be declared immutable, too::\n\n sage: t.is_immutable()\n False\n sage: t.set_immutable()\n sage: t.is_immutable()\n True\n sage: t.set_comp()\n Traceback (most recent call last):\n ...\n ValueError: the components of an immutable element cannot be\n changed\n sage: t.set_name('b')\n Traceback (most recent call last):\n ...\n ValueError: the name of an immutable element cannot be changed\n\n \"\"\"\n\n _name: Optional[str]\n _latex_name: Optional[str]\n _vmodule: VectorFieldModule\n _domain: DifferentiableManifold\n _ambient_domain: DifferentiableManifold\n\n def __init__(\n self,\n vector_field_module: VectorFieldModule,\n tensor_type: TensorType,\n name: Optional[str] = None,\n latex_name: Optional[str] = None,\n sym=None,\n antisym=None,\n parent=None,\n ):\n r\"\"\"\n Construct a tensor field.\n\n TESTS:\n\n Construction via ``parent.element_class``, and not via a direct call\n to ``TensorField``, to fit with the category framework::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U') ; V = M.open_subset('V')\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: c_xy. = U.chart() ; c_uv. = V.chart()\n sage: transf = c_xy.transition_map(c_uv, (x+y, x-y),\n ....: intersection_name='W', restrictions1= x>0,\n ....: restrictions2= u+v>0)\n sage: inv = transf.inverse()\n sage: W = U.intersection(V)\n sage: e_xy = c_xy.frame() ; e_uv = c_uv.frame()\n sage: XM = M.vector_field_module()\n sage: T02 = M.tensor_field_module((0,2))\n sage: t = T02.element_class(XM, (0,2), name='t'); t\n Tensor field t of type (0,2) on the 2-dimensional differentiable\n manifold M\n sage: t[e_xy,:] = [[1+x^2, x*y], [0, 1+y^2]]\n sage: t.add_comp_by_continuation(e_uv, W, c_uv)\n sage: t.display(e_xy)\n t = (x^2 + 1) dx⊗dx + x*y dx⊗dy + (y^2 + 1) dy⊗dy\n sage: t.display(e_uv)\n t = (3/16*u^2 + 1/16*v^2 + 1/2) du⊗du\n + (-1/16*u^2 + 1/4*u*v + 1/16*v^2) du⊗dv\n + (1/16*u^2 + 1/4*u*v - 1/16*v^2) dv⊗du\n + (1/16*u^2 + 3/16*v^2 + 1/2) dv⊗dv\n sage: TestSuite(t).run(skip='_test_pickling')\n\n Construction with ``DifferentiableManifold.tensor_field``::\n\n sage: t1 = M.tensor_field(0, 2, name='t'); t1\n Tensor field t of type (0,2) on the 2-dimensional differentiable\n manifold M\n sage: type(t1) == type(t)\n True\n\n \"\"\"\n if parent is None:\n parent = vector_field_module.tensor_module(*tensor_type)\n ModuleElementWithMutability.__init__(self, parent)\n self._vmodule = vector_field_module\n self._tensor_type = tuple(tensor_type)\n self._tensor_rank = self._tensor_type[0] + self._tensor_type[1]\n self._is_zero = False # a priori, may be changed below or via\n # method __bool__()\n self._name = name\n if latex_name is None:\n self._latex_name = self._name\n else:\n self._latex_name = latex_name\n self._domain = vector_field_module._domain\n self._ambient_domain = vector_field_module._ambient_domain\n\n self._extensions_graph = {self._domain: self}\n # dict. of known extensions of self on bigger domains,\n # including self, with domains as keys. Its elements can be\n # seen as incoming edges on a graph.\n self._restrictions_graph = {self._domain: self}\n # dict. of known restrictions of self on smaller domains,\n # including self, with domains as keys. Its elements can be\n # seen as outgoing edges on a graph.\n\n self._restrictions = {} # dict. of restrictions of self on subdomains\n # of self._domain, with the subdomains as keys\n # Treatment of symmetry declarations:\n self._sym, self._antisym = CompWithSym._canonicalize_sym_antisym(\n self._tensor_rank, sym, antisym)\n # Initialization of derived quantities:\n self._init_derived()\n\n ####### Required methods for ModuleElement (beside arithmetic) #######\n\n def __bool__(self):\n r\"\"\"\n Return ``True`` if ``self`` is nonzero and ``False`` otherwise.\n\n This method is called by :meth:`is_zero`.\n\n EXAMPLES:\n\n Tensor field defined by parts on a 2-dimensional manifold::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U')\n sage: c_xy. = U.chart()\n sage: V = M.open_subset('V')\n sage: c_uv. = V.chart()\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: t = M.tensor_field(1, 2, name='t')\n sage: tu = U.tensor_field(1, 2, name='t')\n sage: tv = V.tensor_field(1, 2, name='t')\n sage: tu[0,0,0] = 0\n sage: tv[0,0,0] = 0\n sage: t.set_restriction(tv)\n sage: t.set_restriction(tu)\n sage: bool(t)\n False\n sage: t.is_zero() # indirect doctest\n True\n sage: tv[0,0,0] = 1\n sage: t.set_restriction(tv)\n sage: bool(t)\n True\n sage: t.is_zero() # indirect doctest\n False\n \"\"\"\n if self._is_zero:\n return False\n if any(bool(rst) for rst in self._restrictions.values()):\n self._is_zero = False\n return True\n self._is_zero = True\n return False\n\n ##### End of required methods for ModuleElement (beside arithmetic) #####\n\n def _repr_(self):\n r\"\"\"\n String representation of ``self``.\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: t = M.tensor_field(1, 3, name='t')\n sage: t\n Tensor field t of type (1,3) on the 2-dimensional differentiable manifold M\n\n \"\"\"\n # Special cases\n if self._tensor_type == (0,2) and self._sym == ((0,1),):\n description = \"Field of symmetric bilinear forms \"\n if self._name is not None:\n description += self._name + \" \"\n else:\n # Generic case\n description = \"Tensor field \"\n if self._name is not None:\n description += self._name + \" \"\n description += \"of type ({},{}) \".format(\n self._tensor_type[0], self._tensor_type[1])\n return self._final_repr(description)\n\n def _latex_(self):\n r\"\"\"\n LaTeX representation of ``self``.\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: t = M.tensor_field(1, 3, name='t')\n sage: t._latex_()\n 't'\n sage: t = M.tensor_field(1, 3, name='t', latex_name=r'\\tau')\n sage: latex(t)\n \\tau\n\n \"\"\"\n if self._latex_name is None:\n return r'\\mbox{' + str(self) + r'}'\n else:\n return self._latex_name\n\n def set_name(self, name: Optional[str] = None, latex_name: Optional[str] = None):\n r\"\"\"\n Set (or change) the text name and LaTeX name of ``self``.\n\n INPUT:\n\n - ``name`` -- string (default: ``None``); name given to the tensor\n field\n - ``latex_name`` -- string (default: ``None``); LaTeX symbol to denote\n the tensor field; if ``None`` while ``name`` is provided, the LaTeX\n symbol is set to ``name``\n\n EXAMPLES::\n\n sage: M = Manifold(2, 'M')\n sage: t = M.tensor_field(1, 3); t\n Tensor field of type (1,3) on the 2-dimensional differentiable\n manifold M\n sage: t.set_name(name='t')\n sage: t\n Tensor field t of type (1,3) on the 2-dimensional differentiable\n manifold M\n sage: latex(t)\n t\n sage: t.set_name(latex_name=r'\\tau')\n sage: latex(t)\n \\tau\n sage: t.set_name(name='a')\n sage: t\n Tensor field a of type (1,3) on the 2-dimensional differentiable\n manifold M\n sage: latex(t)\n a\n\n \"\"\"\n if self.is_immutable():\n raise ValueError(\"the name of an immutable element \"\n \"cannot be changed\")\n if name is not None:\n self._name = name\n if latex_name is None:\n self._latex_name = self._name\n if latex_name is not None:\n self._latex_name = latex_name\n for rst in self._restrictions.values():\n rst.set_name(name=name, latex_name=latex_name)\n\n def _new_instance(self):\n r\"\"\"\n Create an instance of the same class as ``self`` on the same\n vector field module, with the same tensor type and same symmetries\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: t = M.tensor_field(1, 3, name='t')\n sage: t1 = t._new_instance(); t1\n Tensor field of type (1,3) on the 2-dimensional differentiable\n manifold M\n sage: type(t1) == type(t)\n True\n sage: t1.parent() is t.parent()\n True\n\n \"\"\"\n return type(self)(self._vmodule, self._tensor_type, sym=self._sym,\n antisym=self._antisym, parent=self.parent())\n\n def _final_repr(self, description: str) -> str:\n r\"\"\"\n Part of string representation common to all derived classes of\n :class:`TensorField`.\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: t = M.tensor_field(1, 3, name='t')\n sage: t._final_repr('Tensor field t ')\n 'Tensor field t on the 2-dimensional differentiable manifold M'\n\n \"\"\"\n if self._domain == self._ambient_domain:\n description += \"on the {}\".format(self._domain)\n else:\n description += \"along the {} \".format(self._domain) + \\\n \"with values on the {}\".format(self._ambient_domain)\n return description\n\n def _init_derived(self):\n r\"\"\"\n Initialize the derived quantities.\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: t = M.tensor_field(1, 3, name='t')\n sage: t._init_derived()\n\n \"\"\"\n self._lie_derivatives = {} # dict. of Lie derivatives of self (keys: id(vector))\n\n def _del_derived(self):\n r\"\"\"\n Delete the derived quantities.\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: t = M.tensor_field(1, 3, name='t')\n sage: t._del_derived()\n\n \"\"\"\n # First deletes any reference to self in the vectors' dictionaries:\n for vid, val in self._lie_derivatives.items():\n del val[0]._lie_der_along_self[id(self)]\n # Then clears the dictionary of Lie derivatives\n self._lie_derivatives.clear()\n\n def _del_restrictions(self):\n r\"\"\"\n Delete the restrictions defined on ``self``.\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: c_xy. = M.chart()\n sage: t = M.tensor_field(1,2)\n sage: U = M.open_subset('U', coord_def={c_xy: x<0})\n sage: h = t.restrict(U)\n sage: t._restrictions\n {Open subset U of the 2-dimensional differentiable manifold M:\n Tensor field of type (1,2) on the Open subset U of the\n 2-dimensional differentiable manifold M}\n sage: t._del_restrictions()\n sage: t._restrictions\n {}\n\n \"\"\"\n self._restrictions.clear()\n self._extensions_graph = {self._domain: self}\n self._restrictions_graph = {self._domain: self}\n\n def _init_components(self, *comp, **kwargs):\n r\"\"\"\n Initialize the tensor field components in some given vector frames.\n\n INPUT:\n\n - ``comp`` -- either the components of the tensor field with respect\n to the vector frame specified by the argument ``frame`` or a\n dictionary of components, the keys of which are vector frames or\n pairs ``(f,c)`` where ``f`` is a vector frame and ``c`` a chart\n - ``frame`` -- (default: ``None``; unused if ``comp`` is a dictionary)\n vector frame in which the components are given; if ``None``, the\n default vector frame on the domain of ``self`` is assumed\n - ``chart`` -- (default: ``None``; unused if ``comp`` is a dictionary)\n coordinate chart in which the components are expressed; if ``None``,\n the default chart on the domain of ``frame`` is assumed\n\n EXAMPLES::\n\n sage: M = Manifold(2, 'M')\n sage: X. = M.chart()\n sage: t = M.tensor_field(1, 1, name='t')\n sage: t._init_components([[1+x, x*y], [-2, y^2]])\n sage: t.display()\n t = (x + 1) ∂/∂x⊗dx + x*y ∂/∂x⊗dy - 2 ∂/∂y⊗dx + y^2 ∂/∂y⊗dy\n sage: Y. = M.chart()\n sage: t._init_components([[2*u, 3*v], [u+v, -u]], frame=Y.frame(),\n ....: chart=Y)\n sage: t.display(Y)\n t = 2*u ∂/∂u⊗du + 3*v ∂/∂u⊗dv + (u + v) ∂/∂v⊗du - u ∂/∂v⊗dv\n sage: t._init_components({X.frame(): [[2*x, 1-y],[0, x]]})\n sage: t.display()\n t = 2*x ∂/∂x⊗dx + (-y + 1) ∂/∂x⊗dy + x ∂/∂y⊗dy\n sage: t._init_components({(Y.frame(), Y): [[2*u, 0],[v^3, u+v]]})\n sage: t.display(Y)\n t = 2*u ∂/∂u⊗du + v^3 ∂/∂v⊗du + (u + v) ∂/∂v⊗dv\n\n TESTS:\n\n Check that :trac:`29639` is fixed::\n\n sage: v = M.vector_field()\n sage: v._init_components(1/2, -1)\n sage: v.display()\n 1/2 ∂/∂x - ∂/∂y\n\n \"\"\"\n comp0 = comp[0]\n self._is_zero = False # a priori\n if isinstance(comp0, dict):\n for frame, components in comp0.items():\n chart = None\n if isinstance(frame, tuple):\n # frame is actually a pair (frame, chart):\n frame, chart = frame\n self.add_comp(frame)[:, chart] = components\n elif isinstance(comp0, str):\n # For compatibility with previous use of tensor_field():\n self.set_name(comp0)\n else:\n if hasattr(comp0, '__len__') and hasattr(comp0, '__getitem__'):\n # comp0 is a list/vector of components\n # otherwise comp is the tuple of components in a specific frame\n comp = comp0\n frame = kwargs.get('frame')\n chart = kwargs.get('chart')\n self.add_comp(frame)[:, chart] = comp\n\n #### Simple accessors ####\n\n def domain(self) -> DifferentiableManifold:\n r\"\"\"\n Return the manifold on which ``self`` is defined.\n\n OUTPUT:\n\n - instance of class\n :class:`~sage.manifolds.differentiable.manifold.DifferentiableManifold`\n\n EXAMPLES::\n\n sage: M = Manifold(2, 'M')\n sage: c_xy. = M.chart()\n sage: t = M.tensor_field(1,2)\n sage: t.domain()\n 2-dimensional differentiable manifold M\n sage: U = M.open_subset('U', coord_def={c_xy: x<0})\n sage: h = t.restrict(U)\n sage: h.domain()\n Open subset U of the 2-dimensional differentiable manifold M\n\n \"\"\"\n return self._domain\n\n def base_module(self) -> VectorFieldModule:\n r\"\"\"\n Return the vector field module on which ``self`` acts as a tensor.\n\n OUTPUT:\n\n - instance of\n :class:`~sage.manifolds.differentiable.vectorfield_module.VectorFieldModule`\n\n EXAMPLES:\n\n The module of vector fields on the 2-sphere as a \"base module\"::\n\n sage: M = Manifold(2, 'S^2')\n sage: t = M.tensor_field(0,2)\n sage: t.base_module()\n Module X(S^2) of vector fields on the 2-dimensional differentiable\n manifold S^2\n sage: t.base_module() is M.vector_field_module()\n True\n sage: XM = M.vector_field_module()\n sage: XM.an_element().base_module() is XM\n True\n\n \"\"\"\n return self._vmodule\n\n def tensor_type(self) -> TensorType:\n r\"\"\"\n Return the tensor type of ``self``.\n\n OUTPUT:\n\n - pair `(k,l)`, where `k` is the contravariant rank and `l` is\n the covariant rank\n\n EXAMPLES::\n\n sage: M = Manifold(2, 'S^2')\n sage: t = M.tensor_field(1,2)\n sage: t.tensor_type()\n (1, 2)\n sage: v = M.vector_field()\n sage: v.tensor_type()\n (1, 0)\n\n \"\"\"\n return self._tensor_type\n\n def tensor_rank(self):\n r\"\"\"\n Return the tensor rank of ``self``.\n\n OUTPUT:\n\n - integer `k+l`, where `k` is the contravariant rank and `l` is\n the covariant rank\n\n EXAMPLES::\n\n sage: M = Manifold(2, 'S^2')\n sage: t = M.tensor_field(1,2)\n sage: t.tensor_rank()\n 3\n sage: v = M.vector_field()\n sage: v.tensor_rank()\n 1\n\n \"\"\"\n return self._tensor_rank\n\n def symmetries(self):\n r\"\"\"\n Print the list of symmetries and antisymmetries.\n\n EXAMPLES::\n\n sage: M = Manifold(2, 'S^2')\n sage: t = M.tensor_field(1,2)\n sage: t.symmetries()\n no symmetry; no antisymmetry\n sage: t = M.tensor_field(1,2, sym=(1,2))\n sage: t.symmetries()\n symmetry: (1, 2); no antisymmetry\n sage: t = M.tensor_field(2,2, sym=(0,1), antisym=(2,3))\n sage: t.symmetries()\n symmetry: (0, 1); antisymmetry: (2, 3)\n sage: t = M.tensor_field(2,2, antisym=[(0,1),(2,3)])\n sage: t.symmetries()\n no symmetry; antisymmetries: [(0, 1), (2, 3)]\n\n \"\"\"\n if not self._sym:\n s = \"no symmetry; \"\n elif len(self._sym) == 1:\n s = \"symmetry: {}; \".format(self._sym[0])\n else:\n s = \"symmetries: {}; \".format(list(self._sym))\n if not self._antisym:\n a = \"no antisymmetry\"\n elif len(self._antisym) == 1:\n a = \"antisymmetry: {}\".format(self._antisym[0])\n else:\n a = \"antisymmetries: {}\".format(list(self._antisym))\n print(s + a)\n\n #### End of simple accessors #####\n\n def set_immutable(self):\n r\"\"\"\n Set ``self`` and all restrictions of ``self`` immutable.\n\n EXAMPLES::\n\n sage: M = Manifold(2, 'M')\n sage: X. = M.chart()\n sage: U = M.open_subset('U', coord_def={X: x^2+y^2<1})\n sage: a = M.tensor_field(1, 1, [[1+y,x], [0,x+y]], name='a')\n sage: aU = a.restrict(U)\n sage: a.set_immutable()\n sage: aU.is_immutable()\n True\n\n \"\"\"\n for rst in self._restrictions.values():\n rst.set_immutable()\n super().set_immutable()\n\n def set_restriction(self, rst: TensorField):\n r\"\"\"\n Define a restriction of ``self`` to some subdomain.\n\n INPUT:\n\n - ``rst`` -- :class:`TensorField` of the same type and symmetries\n as the current tensor field ``self``, defined on a subdomain of\n the domain of ``self``\n\n EXAMPLES::\n\n sage: M = Manifold(2, 'M') # the 2-dimensional sphere S^2\n sage: U = M.open_subset('U') # complement of the North pole\n sage: c_xy. = U.chart() # stereographic coordinates from the North pole\n sage: V = M.open_subset('V') # complement of the South pole\n sage: c_uv. = V.chart() # stereographic coordinates from the South pole\n sage: M.declare_union(U,V) # S^2 is the union of U and V\n sage: t = M.tensor_field(1, 2, name='t')\n sage: s = U.tensor_field(1, 2)\n sage: s[0,0,1] = x+y\n sage: t.set_restriction(s)\n sage: t.display(c_xy.frame())\n t = (x + y) ∂/∂x⊗dx⊗dy\n sage: t.restrict(U) == s\n True\n\n If the restriction is defined on the very same domain, the tensor field\n becomes a copy of it (see :meth:`copy_from`)::\n\n sage: v = M.tensor_field(1, 2, name='v')\n sage: v.set_restriction(t)\n sage: v.restrict(U) == t.restrict(U)\n True\n\n \"\"\"\n if self.is_immutable():\n raise ValueError(\"the restrictions of an immutable element \"\n \"cannot be changed\")\n if not isinstance(rst, TensorField):\n raise TypeError(\"the argument must be a tensor field\")\n if not rst._domain.is_subset(self._domain):\n raise ValueError(\"the domain of the declared restriction is not \" +\n \"a subset of the field's domain\")\n if not rst._ambient_domain.is_subset(self._ambient_domain):\n raise ValueError(\"the ambient domain of the declared \" +\n \"restriction is not a subset of the \" +\n \"field's ambient domain\")\n if rst._tensor_type != self._tensor_type:\n raise ValueError(\"the declared restriction has not the same \" +\n \"tensor type as the current tensor field\")\n if rst._tensor_type != self._tensor_type:\n raise ValueError(\"the declared restriction has not the same \" +\n \"tensor type as the current tensor field\")\n if rst._sym != self._sym:\n raise ValueError(\"the declared restriction has not the same \" +\n \"symmetries as the current tensor field\")\n if rst._antisym != self._antisym:\n raise ValueError(\"the declared restriction has not the same \" +\n \"antisymmetries as the current tensor field\")\n if self._domain is rst._domain:\n self.copy_from(rst)\n else:\n self._restrictions[rst._domain] = rst.copy(name=self._name,\n latex_name=self._latex_name)\n self._is_zero = False # a priori\n\n def restrict(\n self: T, subdomain: DifferentiableManifold, dest_map: Optional[DiffMap] = None\n ) -> T:\n r\"\"\"\n Return the restriction of ``self`` to some subdomain.\n\n If the restriction has not been defined yet, it is constructed here.\n\n INPUT:\n\n - ``subdomain`` --\n :class:`~sage.manifolds.differentiable.manifold.DifferentiableManifold`;\n open subset `U` of the tensor field domain `S`\n - ``dest_map`` --\n :class:`~sage.manifolds.differentiable.diff_map.DiffMap`\n (default: ``None``); destination map `\\Psi:\\ U \\rightarrow V`,\n where `V` is an open subset of the manifold `M` where the tensor\n field takes it values; if ``None``, the restriction of `\\Phi`\n to `U` is used, `\\Phi` being the differentiable map\n `S \\rightarrow M` associated with the tensor field\n\n OUTPUT:\n\n - :class:`TensorField` representing the restriction\n\n EXAMPLES:\n\n Restrictions of a vector field on the 2-sphere::\n\n sage: M = Manifold(2, 'S^2', start_index=1)\n sage: U = M.open_subset('U') # the complement of the North pole\n sage: stereoN. = U.chart() # stereographic coordinates from the North pole\n sage: eN = stereoN.frame() # the associated vector frame\n sage: V = M.open_subset('V') # the complement of the South pole\n sage: stereoS. = V.chart() # stereographic coordinates from the South pole\n sage: eS = stereoS.frame() # the associated vector frame\n sage: transf = stereoN.transition_map(stereoS, (x/(x^2+y^2), y/(x^2+y^2)),\n ....: intersection_name='W', restrictions1= x^2+y^2!=0,\n ....: restrictions2= u^2+v^2!=0)\n sage: inv = transf.inverse() # transformation from stereoS to stereoN\n sage: W = U.intersection(V) # the complement of the North and South poles\n sage: stereoN_W = W.atlas()[0] # restriction of stereographic coord. from North pole to W\n sage: stereoS_W = W.atlas()[1] # restriction of stereographic coord. from South pole to W\n sage: eN_W = stereoN_W.frame() ; eS_W = stereoS_W.frame()\n sage: v = M.vector_field({eN: [1, 0]}, name='v')\n sage: v.display()\n v = ∂/∂x\n sage: vU = v.restrict(U) ; vU\n Vector field v on the Open subset U of the 2-dimensional\n differentiable manifold S^2\n sage: vU.display()\n v = ∂/∂x\n sage: vU == eN[1]\n True\n sage: vW = v.restrict(W) ; vW\n Vector field v on the Open subset W of the 2-dimensional\n differentiable manifold S^2\n sage: vW.display()\n v = ∂/∂x\n sage: vW.display(eS_W, stereoS_W)\n v = (-u^2 + v^2) ∂/∂u - 2*u*v ∂/∂v\n sage: vW == eN_W[1]\n True\n\n At this stage, defining the restriction of ``v`` to the open\n subset ``V`` fully specifies ``v``::\n\n sage: v.restrict(V)[1] = vW[eS_W, 1, stereoS_W].expr() # note that eS is the default frame on V\n sage: v.restrict(V)[2] = vW[eS_W, 2, stereoS_W].expr()\n sage: v.display(eS, stereoS)\n v = (-u^2 + v^2) ∂/∂u - 2*u*v ∂/∂v\n sage: v.restrict(U).display()\n v = ∂/∂x\n sage: v.restrict(V).display()\n v = (-u^2 + v^2) ∂/∂u - 2*u*v ∂/∂v\n\n The restriction of the vector field to its own domain is of course\n itself::\n\n sage: v.restrict(M) is v\n True\n sage: vU.restrict(U) is vU\n True\n\n \"\"\"\n if (subdomain == self._domain\n and (dest_map is None or dest_map == self._vmodule._dest_map)):\n return self\n if subdomain not in self._restrictions:\n if not subdomain.is_subset(self._domain):\n raise ValueError(\"the provided domain is not a subset of \" +\n \"the field's domain\")\n if dest_map is None:\n dest_map = self._vmodule._dest_map.restrict(subdomain)\n elif not dest_map._codomain.is_subset(self._ambient_domain):\n raise ValueError(\"the argument 'dest_map' is not compatible \" +\n \"with the ambient domain of \" +\n \"the {}\".format(self))\n # First one tries to get the restriction from a tighter domain:\n for dom, rst in self._restrictions.items():\n if subdomain.is_subset(dom) and subdomain in rst._restrictions:\n res = rst._restrictions[subdomain]\n self._restrictions[subdomain] = res\n self._restrictions_graph[subdomain] = res\n res._extensions_graph.update(self._extensions_graph)\n for ext in self._extensions_graph.values():\n ext._restrictions[subdomain] = res\n ext._restrictions_graph[subdomain] = res\n return self._restrictions[subdomain]\n\n for dom, rst in self._restrictions.items():\n if subdomain.is_subset(dom) and dom is not self._domain:\n self._restrictions[subdomain] = rst.restrict(subdomain)\n self._restrictions_graph[subdomain] = rst.restrict(subdomain)\n return self._restrictions[subdomain]\n\n # Secondly one tries to get the restriction from one previously\n # defined on a larger domain:\n for dom, ext in self._extensions_graph.items():\n if subdomain in ext._restrictions:\n res = ext._restrictions_graph[subdomain]\n self._restrictions[subdomain] = res\n self._restrictions_graph[subdomain] = res\n res._extensions_graph.update(self._extensions_graph)\n for ext in self._extensions_graph.values():\n ext._restrictions[subdomain] = res\n ext._restrictions_graph[subdomain] = res\n return self._restrictions[subdomain]\n\n # If this fails, the restriction is created from scratch:\n smodule = subdomain.vector_field_module(dest_map=dest_map)\n res = smodule.tensor(self._tensor_type, name=self._name,\n latex_name=self._latex_name, sym=self._sym,\n antisym=self._antisym,\n specific_type=type(self))\n res._extensions_graph.update(self._extensions_graph)\n for dom, ext in self._extensions_graph.items():\n ext._restrictions[subdomain] = res\n ext._restrictions_graph[subdomain] = res\n\n for dom, rst in self._restrictions.items():\n if dom.is_subset(subdomain):\n if rst is not res:\n res._restrictions.update(rst._restrictions)\n res._restrictions_graph.update(rst._restrictions_graph)\n rst._extensions_graph.update(res._extensions_graph)\n if self.is_immutable():\n res.set_immutable() # restrictions must be immutable, too\n self._restrictions[subdomain] = res\n self._restrictions_graph[subdomain] = res\n res._extensions_graph.update(self._extensions_graph)\n\n return self._restrictions[subdomain]\n\n def _set_comp_unsafe(self, basis=None):\n r\"\"\"\n Return the components of ``self`` in a given vector frame\n for assignment. This private method invokes no security check. Use\n this method at your own risk.\n\n The components with respect to other frames having the same domain\n as the provided vector frame are deleted, in order to avoid any\n inconsistency. To keep them, use the method :meth:`_add_comp_unsafe`\n instead.\n\n INPUT:\n\n - ``basis`` -- (default: ``None``) vector frame in which the\n components are defined; if none is provided, the components are\n assumed to refer to the tensor field domain's default frame\n\n OUTPUT:\n\n - components in the given frame, as a\n :class:`~sage.tensor.modules.comp.Components`; if such\n components did not exist previously, they are created\n\n TESTS::\n\n sage: M = Manifold(2, 'M') # the 2-dimensional sphere S^2\n sage: U = M.open_subset('U') # complement of the North pole\n sage: c_xy. = U.chart() # stereographic coordinates from the North pole\n sage: V = M.open_subset('V') # complement of the South pole\n sage: c_uv. = V.chart() # stereographic coordinates from the South pole\n sage: M.declare_union(U,V) # S^2 is the union of U and V\n sage: e_uv = c_uv.frame()\n sage: t = M.tensor_field(1, 2, name='t')\n sage: t._set_comp_unsafe(e_uv)\n 3-indices components w.r.t. Coordinate frame (V, (∂/∂u,∂/∂v))\n sage: t._set_comp_unsafe(e_uv)[1,0,1] = u+v\n sage: t.display(e_uv)\n t = (u + v) ∂/∂v⊗du⊗dv\n\n Setting the components in a new frame (``e``)::\n\n sage: e = V.vector_frame('e')\n sage: t._set_comp_unsafe(e)\n 3-indices components w.r.t. Vector frame (V, (e_0,e_1))\n sage: t._set_comp_unsafe(e)[0,1,1] = u*v\n sage: t.display(e)\n t = u*v e_0⊗e^1⊗e^1\n\n Since the frames ``e`` and ``e_uv`` are defined on the same domain, the\n components w.r.t. ``e_uv`` have been erased::\n\n sage: t.display(c_uv.frame())\n Traceback (most recent call last):\n ...\n ValueError: no basis could be found for computing the components\n in the Coordinate frame (V, (∂/∂u,∂/∂v))\n\n \"\"\"\n if basis is None:\n basis = self._domain._def_frame\n self._del_derived() # deletes the derived quantities\n rst = self.restrict(basis._domain, dest_map=basis._dest_map)\n return rst._set_comp_unsafe(basis)\n\n def set_comp(self, basis=None):\n r\"\"\"\n Return the components of ``self`` in a given vector frame\n for assignment.\n\n The components with respect to other frames having the same domain\n as the provided vector frame are deleted, in order to avoid any\n inconsistency. To keep them, use the method :meth:`add_comp` instead.\n\n INPUT:\n\n - ``basis`` -- (default: ``None``) vector frame in which the\n components are defined; if none is provided, the components are\n assumed to refer to the tensor field domain's default frame\n\n OUTPUT:\n\n - components in the given frame, as a\n :class:`~sage.tensor.modules.comp.Components`; if such\n components did not exist previously, they are created\n\n EXAMPLES::\n\n sage: M = Manifold(2, 'M') # the 2-dimensional sphere S^2\n sage: U = M.open_subset('U') # complement of the North pole\n sage: c_xy. = U.chart() # stereographic coordinates from the North pole\n sage: V = M.open_subset('V') # complement of the South pole\n sage: c_uv. = V.chart() # stereographic coordinates from the South pole\n sage: M.declare_union(U,V) # S^2 is the union of U and V\n sage: e_uv = c_uv.frame()\n sage: t = M.tensor_field(1, 2, name='t')\n sage: t.set_comp(e_uv)\n 3-indices components w.r.t. Coordinate frame (V, (∂/∂u,∂/∂v))\n sage: t.set_comp(e_uv)[1,0,1] = u+v\n sage: t.display(e_uv)\n t = (u + v) ∂/∂v⊗du⊗dv\n\n Setting the components in a new frame (``e``)::\n\n sage: e = V.vector_frame('e')\n sage: t.set_comp(e)\n 3-indices components w.r.t. Vector frame (V, (e_0,e_1))\n sage: t.set_comp(e)[0,1,1] = u*v\n sage: t.display(e)\n t = u*v e_0⊗e^1⊗e^1\n\n Since the frames ``e`` and ``e_uv`` are defined on the same domain, the\n components w.r.t. ``e_uv`` have been erased::\n\n sage: t.display(c_uv.frame())\n Traceback (most recent call last):\n ...\n ValueError: no basis could be found for computing the components\n in the Coordinate frame (V, (∂/∂u,∂/∂v))\n\n Since zero is an immutable, its components cannot be changed::\n\n sage: z = M.tensor_field_module((1, 1)).zero()\n sage: z.set_comp(e)[0,1] = u*v\n Traceback (most recent call last):\n ...\n ValueError: the components of an immutable element cannot be\n changed\n\n \"\"\"\n if self.is_immutable():\n raise ValueError(\"the components of an immutable element \"\n \"cannot be changed\")\n self._is_zero = False # a priori\n if basis is None:\n basis = self._domain._def_frame\n self._del_derived() # deletes the derived quantities\n rst = self.restrict(basis._domain, dest_map=basis._dest_map)\n return rst.set_comp(basis=basis)\n\n def _add_comp_unsafe(self, basis=None):\n r\"\"\"\n Return the components of ``self`` in a given vector frame\n for assignment. This private method invokes no security check. Use\n this method at your own risk.\n\n The components with respect to other frames having the same domain\n as the provided vector frame are kept. To delete them, use the\n method :meth:`_set_comp_unsafe` instead.\n\n INPUT:\n\n - ``basis`` -- (default: ``None``) vector frame in which the\n components are defined; if ``None``, the components are assumed\n to refer to the tensor field domain's default frame\n\n OUTPUT:\n\n - components in the given frame, as a\n :class:`~sage.tensor.modules.comp.Components`; if such\n components did not exist previously, they are created\n\n TESTS::\n\n sage: M = Manifold(2, 'M') # the 2-dimensional sphere S^2\n sage: U = M.open_subset('U') # complement of the North pole\n sage: c_xy. = U.chart() # stereographic coordinates from the North pole\n sage: V = M.open_subset('V') # complement of the South pole\n sage: c_uv. = V.chart() # stereographic coordinates from the South pole\n sage: M.declare_union(U,V) # S^2 is the union of U and V\n sage: e_uv = c_uv.frame()\n sage: t = M.tensor_field(1, 2, name='t')\n sage: t._add_comp_unsafe(e_uv)\n 3-indices components w.r.t. Coordinate frame (V, (∂/∂u,∂/∂v))\n sage: t._add_comp_unsafe(e_uv)[1,0,1] = u+v\n sage: t.display(e_uv)\n t = (u + v) ∂/∂v⊗du⊗dv\n\n Setting the components in a new frame::\n\n sage: e = V.vector_frame('e')\n sage: t._add_comp_unsafe(e)\n 3-indices components w.r.t. Vector frame (V, (e_0,e_1))\n sage: t._add_comp_unsafe(e)[0,1,1] = u*v\n sage: t.display(e)\n t = u*v e_0⊗e^1⊗e^1\n\n The components with respect to ``e_uv`` are kept::\n\n sage: t.display(e_uv)\n t = (u + v) ∂/∂v⊗du⊗dv\n\n \"\"\"\n if basis is None:\n basis = self._domain._def_frame\n self._del_derived() # deletes the derived quantities\n rst = self.restrict(basis._domain, dest_map=basis._dest_map)\n return rst._add_comp_unsafe(basis)\n\n def add_comp(self, basis=None) -> Components:\n r\"\"\"\n Return the components of ``self`` in a given vector frame\n for assignment.\n\n The components with respect to other frames having the same domain\n as the provided vector frame are kept. To delete them, use the\n method :meth:`set_comp` instead.\n\n INPUT:\n\n - ``basis`` -- (default: ``None``) vector frame in which the\n components are defined; if ``None``, the components are assumed\n to refer to the tensor field domain's default frame\n\n OUTPUT:\n\n - components in the given frame, as a\n :class:`~sage.tensor.modules.comp.Components`; if such\n components did not exist previously, they are created\n\n EXAMPLES::\n\n sage: M = Manifold(2, 'M') # the 2-dimensional sphere S^2\n sage: U = M.open_subset('U') # complement of the North pole\n sage: c_xy. = U.chart() # stereographic coordinates from the North pole\n sage: V = M.open_subset('V') # complement of the South pole\n sage: c_uv. = V.chart() # stereographic coordinates from the South pole\n sage: M.declare_union(U,V) # S^2 is the union of U and V\n sage: e_uv = c_uv.frame()\n sage: t = M.tensor_field(1, 2, name='t')\n sage: t.add_comp(e_uv)\n 3-indices components w.r.t. Coordinate frame (V, (∂/∂u,∂/∂v))\n sage: t.add_comp(e_uv)[1,0,1] = u+v\n sage: t.display(e_uv)\n t = (u + v) ∂/∂v⊗du⊗dv\n\n Setting the components in a new frame::\n\n sage: e = V.vector_frame('e')\n sage: t.add_comp(e)\n 3-indices components w.r.t. Vector frame (V, (e_0,e_1))\n sage: t.add_comp(e)[0,1,1] = u*v\n sage: t.display(e)\n t = u*v e_0⊗e^1⊗e^1\n\n The components with respect to ``e_uv`` are kept::\n\n sage: t.display(e_uv)\n t = (u + v) ∂/∂v⊗du⊗dv\n\n Since zero is a special element, its components cannot be changed::\n\n sage: z = M.tensor_field_module((1, 1)).zero()\n sage: z.add_comp(e_uv)[1, 1] = u^2\n Traceback (most recent call last):\n ...\n ValueError: the components of an immutable element cannot be\n changed\n\n \"\"\"\n if self.is_immutable():\n raise ValueError(\"the components of an immutable element \"\n \"cannot be changed\")\n self._is_zero = False # a priori\n if basis is None:\n basis = self._domain._def_frame\n self._del_derived() # deletes the derived quantities\n rst = self.restrict(basis._domain, dest_map=basis._dest_map)\n return rst.add_comp(basis=basis)\n\n def add_comp_by_continuation(self, frame, subdomain, chart=None):\n r\"\"\"\n Set components with respect to a vector frame by continuation of the\n coordinate expression of the components in a subframe.\n\n The continuation is performed by demanding that the components have\n the same coordinate expression as those on the restriction of the\n frame to a given subdomain.\n\n INPUT:\n\n - ``frame`` -- vector frame `e` in which the components are to be set\n - ``subdomain`` -- open subset of `e`'s domain in which the\n components are known or can be evaluated from other components\n - ``chart`` -- (default: ``None``) coordinate chart on `e`'s domain in\n which the extension of the expression of the components is to be\n performed; if ``None``, the default's chart of `e`'s domain is\n assumed\n\n EXAMPLES:\n\n Components of a vector field on the sphere `S^2`::\n\n sage: M = Manifold(2, 'S^2', start_index=1)\n\n The two open subsets covered by stereographic coordinates (North and South)::\n\n sage: U = M.open_subset('U') ; V = M.open_subset('V')\n sage: M.declare_union(U,V) # S^2 is the union of U and V\n sage: c_xy. = U.chart() ; c_uv. = V.chart() # stereographic coordinates\n sage: transf = c_xy.transition_map(c_uv, (x/(x^2+y^2), y/(x^2+y^2)),\n ....: intersection_name='W', restrictions1= x^2+y^2!=0,\n ....: restrictions2= u^2+v^2!=0)\n sage: inv = transf.inverse()\n sage: W = U.intersection(V) # The complement of the two poles\n sage: eU = c_xy.frame() ; eV = c_uv.frame()\n sage: a = M.vector_field({eU: [x, 2+y]}, name='a')\n\n At this stage, the vector field has been defined only on the open\n subset ``U`` (through its components in the frame ``eU``)::\n\n sage: a.display(eU)\n a = x ∂/∂x + (y + 2) ∂/∂y\n\n The components with respect to the restriction of ``eV`` to the common\n subdomain ``W``, in terms of the ``(u,v)`` coordinates, are obtained\n by a change-of-frame formula on ``W``::\n\n sage: a.display(eV.restrict(W), c_uv.restrict(W))\n a = (-4*u*v - u) ∂/∂u + (2*u^2 - 2*v^2 - v) ∂/∂v\n\n The continuation consists in extending the definition of the vector\n field to the whole open subset ``V`` by demanding that the components\n in the frame eV have the same coordinate expression as the above one::\n\n sage: a.add_comp_by_continuation(eV, W, chart=c_uv)\n\n We have then::\n\n sage: a.display(eV)\n a = (-4*u*v - u) ∂/∂u + (2*u^2 - 2*v^2 - v) ∂/∂v\n\n and `a` is defined on the entire manifold `S^2`.\n\n \"\"\"\n if self.is_immutable():\n raise ValueError(\"the components of an immutable element \"\n \"cannot be changed\")\n dom = frame._domain\n if not dom.is_subset(self._domain):\n raise ValueError(\"the vector frame is not defined on a subset \" +\n \"of the tensor field domain\")\n if chart is None:\n chart = dom._def_chart\n sframe = frame.restrict(subdomain)\n schart = chart.restrict(subdomain)\n scomp = self.comp(sframe)\n resu = self._add_comp_unsafe(frame) # _del_derived is performed here\n for ind in resu.non_redundant_index_generator():\n resu[[ind]] = dom.scalar_field({chart: scomp[[ind]].expr(schart)})\n\n def add_expr_from_subdomain(self, frame, subdomain):\n r\"\"\"\n Add an expression to an existing component from a subdomain.\n\n INPUT:\n\n - ``frame`` -- vector frame `e` in which the components are to be set\n - ``subdomain`` -- open subset of `e`'s domain in which the\n components have additional expressions.\n\n EXAMPLES:\n\n We are going to consider a vector field in `\\RR^3` along the 2-sphere::\n\n sage: M = Manifold(3, 'M', structure=\"Riemannian\")\n sage: S = Manifold(2, 'S', structure=\"Riemannian\")\n sage: E. = M.chart()\n\n Let us define ``S`` in terms of stereographic charts::\n\n sage: U = S.open_subset('U')\n sage: V = S.open_subset('V')\n sage: S.declare_union(U,V)\n sage: stereoN. = U.chart()\n sage: stereoS. = V.chart(\"xp:x' yp:y'\")\n sage: stereoN_to_S = stereoN.transition_map(stereoS,\n ....: (x/(x^2+y^2), y/(x^2+y^2)),\n ....: intersection_name='W',\n ....: restrictions1= x^2+y^2!=0,\n ....: restrictions2= xp^2+yp^2!=0)\n sage: stereoS_to_N = stereoN_to_S.inverse()\n sage: W = U.intersection(V)\n sage: stereoN_W = stereoN.restrict(W)\n sage: stereoS_W = stereoS.restrict(W)\n\n The embedding of `S^2` in `\\RR^3`::\n\n sage: phi = S.diff_map(M, {(stereoN, E): [2*x/(1+x^2+y^2),\n ....: 2*y/(1+x^2+y^2),\n ....: (x^2+y^2-1)/(1+x^2+y^2)],\n ....: (stereoS, E): [2*xp/(1+xp^2+yp^2),\n ....: 2*yp/(1+xp^2+yp^2),\n ....: (1-xp^2-yp^2)/(1+xp^2+yp^2)]},\n ....: name='Phi', latex_name=r'\\Phi')\n\n To define a vector field ``v`` along ``S`` taking its values in ``M``,\n we first set the components on ``U``::\n\n sage: v = M.vector_field(name='v').along(phi)\n sage: vU = v.restrict(U)\n sage: vU[:] = [x,y,x**2+y**2]\n\n But because ``M`` is parallelizable, these components can be extended\n to ``S`` itself::\n\n sage: v.add_comp_by_continuation(E.frame().along(phi), U)\n\n One can see that ``v`` is not yet fully defined: the components\n (scalar fields) do not have values on the whole manifold::\n\n sage: sorted(v._components.values())[0]._comp[(0,)].display()\n S → ℝ\n on U: (x, y) ↦ x\n on W: (xp, yp) ↦ xp/(xp^2 + yp^2)\n\n To fix that, we first extend the components from ``W`` to ``V`` using\n :meth:`add_comp_by_continuation`::\n\n sage: v.add_comp_by_continuation(E.frame().along(phi).restrict(V),\n ....: W, stereoS)\n\n Then, the expression on the subdomain ``V`` is added to the\n already known components on ``S`` by::\n\n sage: v.add_expr_from_subdomain(E.frame().along(phi), V)\n\n The definition of ``v`` is now complete::\n\n sage: sorted(v._components.values())[0]._comp[(2,)].display()\n S → ℝ\n on U: (x, y) ↦ x^2 + y^2\n on V: (xp, yp) ↦ 1/(xp^2 + yp^2)\n\n \"\"\"\n if self.is_immutable():\n raise ValueError(\"the expressions of an immutable element \"\n \"cannot be changed\")\n dom = frame._domain\n if not dom.is_subset(self._domain):\n raise ValueError(\"the vector frame is not defined on a subset \" +\n \"of the tensor field domain\")\n if frame not in self.restrict(frame.domain())._components:\n raise ValueError(\"the tensor doesn't have an expression in \"\n \"the frame\"+frame._repr_())\n comp = self._add_comp_unsafe(frame) # the components stay the same\n scomp = self.restrict(subdomain).comp(frame.restrict(subdomain))\n for ind in comp.non_redundant_index_generator():\n comp[[ind]]._express.update(scomp[[ind]]._express)\n\n rst = self._restrictions.copy()\n self._del_derived() # may delete restrictions\n self._restrictions = rst\n\n def comp(self, basis=None, from_basis=None):\n r\"\"\"\n Return the components in a given vector frame.\n\n If the components are not known already, they are computed by the\n tensor change-of-basis formula from components in another vector frame.\n\n INPUT:\n\n - ``basis`` -- (default: ``None``) vector frame in which the components\n are required; if none is provided, the components are assumed to\n refer to the tensor field domain's default frame\n - ``from_basis`` -- (default: ``None``) vector frame from which the\n required components are computed, via the tensor change-of-basis\n formula, if they are not known already in the basis ``basis``\n\n OUTPUT:\n\n - components in the vector frame ``basis``, as a\n :class:`~sage.tensor.modules.comp.Components`\n\n EXAMPLES:\n\n Components of a type-`(1,1)` tensor field defined on two\n open subsets::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U')\n sage: c_xy. = U.chart()\n sage: e = U.default_frame() ; e\n Coordinate frame (U, (∂/∂x,∂/∂y))\n sage: V = M.open_subset('V')\n sage: c_uv. = V.chart()\n sage: f = V.default_frame() ; f\n Coordinate frame (V, (∂/∂u,∂/∂v))\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: t = M.tensor_field(1,1, name='t')\n sage: t[e,0,0] = - x + y^3\n sage: t[e,0,1] = 2+x\n sage: t[f,1,1] = - u*v\n sage: t.comp(e)\n 2-indices components w.r.t. Coordinate frame (U, (∂/∂x,∂/∂y))\n sage: t.comp(e)[:]\n [y^3 - x x + 2]\n [ 0 0]\n sage: t.comp(f)\n 2-indices components w.r.t. Coordinate frame (V, (∂/∂u,∂/∂v))\n sage: t.comp(f)[:]\n [ 0 0]\n [ 0 -u*v]\n\n Since ``e`` is ``M``'s default frame, the argument ``e`` can\n be omitted::\n\n sage: e is M.default_frame()\n True\n sage: t.comp() is t.comp(e)\n True\n\n Example of computation of the components via a change of frame::\n\n sage: a = V.automorphism_field()\n sage: a[:] = [[1+v, -u^2], [0, 1-u]]\n sage: h = f.new_frame(a, 'h')\n sage: t.comp(h)\n 2-indices components w.r.t. Vector frame (V, (h_0,h_1))\n sage: t.comp(h)[:]\n [ 0 -u^3*v/(v + 1)]\n [ 0 -u*v]\n\n \"\"\"\n if basis is None:\n basis = self._domain._def_frame\n rst = self.restrict(basis._domain, dest_map=basis._dest_map)\n return rst.comp(basis=basis, from_basis=from_basis)\n\n def display(self, frame=None, chart=None):\n r\"\"\"\n Display the tensor field in terms of its expansion with respect\n to a given vector frame.\n\n The output is either text-formatted (console mode) or LaTeX-formatted\n (notebook mode).\n\n INPUT:\n\n - ``frame`` -- (default: ``None``) vector frame with respect to\n which the tensor is expanded; if ``frame`` is ``None`` and ``chart``\n is not ``None``, the coordinate frame associated with ``chart`` is\n assumed; if both ``frame`` and ``chart`` are ``None``, the default\n frame of the domain of definition of the tensor field is assumed\n - ``chart`` -- (default: ``None``) chart with respect to which the\n components of the tensor field in the selected frame are expressed;\n if ``None``, the default chart of the vector frame domain is assumed\n\n EXAMPLES:\n\n Display of a type-`(1,1)` tensor field on a 2-dimensional manifold::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U') ; V = M.open_subset('V')\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: c_xy. = U.chart() ; c_uv. = V.chart()\n sage: xy_to_uv = c_xy.transition_map(c_uv, (x+y, x-y),\n ....: intersection_name='W', restrictions1= x>0,\n ....: restrictions2= u+v>0)\n sage: uv_to_xy = xy_to_uv.inverse()\n sage: W = U.intersection(V)\n sage: e_xy = c_xy.frame(); e_uv = c_uv.frame()\n sage: t = M.tensor_field(1,1, name='t')\n sage: t[e_xy,:] = [[x, 1], [y, 0]]\n sage: t.add_comp_by_continuation(e_uv, W, c_uv)\n sage: t.display(e_xy)\n t = x ∂/∂x⊗dx + ∂/∂x⊗dy + y ∂/∂y⊗dx\n sage: t.display(e_uv)\n t = (1/2*u + 1/2) ∂/∂u⊗du + (1/2*u - 1/2) ∂/∂u⊗dv\n + (1/2*v + 1/2) ∂/∂v⊗du + (1/2*v - 1/2) ∂/∂v⊗dv\n\n Since ``e_xy`` is ``M``'s default frame, the argument ``e_xy`` can\n be omitted::\n\n sage: e_xy is M.default_frame()\n True\n sage: t.display()\n t = x ∂/∂x⊗dx + ∂/∂x⊗dy + y ∂/∂y⊗dx\n\n Similarly, since ``e_uv`` is ``V``'s default frame, the argument ``e_uv``\n can be omitted when considering the restriction of ``t`` to ``V``::\n\n sage: t.restrict(V).display()\n t = (1/2*u + 1/2) ∂/∂u⊗du + (1/2*u - 1/2) ∂/∂u⊗dv\n + (1/2*v + 1/2) ∂/∂v⊗du + (1/2*v - 1/2) ∂/∂v⊗dv\n\n If the coordinate expression of the components are to be displayed in\n a chart distinct from the default one on the considered domain, then\n the chart has to be passed as the second argument of ``display``.\n For instance, on `W = U \\cap V`, two charts are available:\n ``c_xy.restrict(W)`` (the default one) and ``c_uv.restrict(W)``.\n Accordingly, one can have two views of the expansion of ``t`` in the\n *same* vector frame ``e_uv.restrict(W)``::\n\n sage: t.display(e_uv.restrict(W)) # W's default chart assumed\n t = (1/2*x + 1/2*y + 1/2) ∂/∂u⊗du + (1/2*x + 1/2*y - 1/2) ∂/∂u⊗dv\n + (1/2*x - 1/2*y + 1/2) ∂/∂v⊗du + (1/2*x - 1/2*y - 1/2) ∂/∂v⊗dv\n sage: t.display(e_uv.restrict(W), c_uv.restrict(W))\n t = (1/2*u + 1/2) ∂/∂u⊗du + (1/2*u - 1/2) ∂/∂u⊗dv\n + (1/2*v + 1/2) ∂/∂v⊗du + (1/2*v - 1/2) ∂/∂v⊗dv\n\n As a shortcut, one can pass just a chart to ``display``. It is then\n understood that the expansion is to be performed with respect to the\n coordinate frame associated with this chart. Therefore the above\n command can be abridged to::\n\n sage: t.display(c_uv.restrict(W))\n t = (1/2*u + 1/2) ∂/∂u⊗du + (1/2*u - 1/2) ∂/∂u⊗dv\n + (1/2*v + 1/2) ∂/∂v⊗du + (1/2*v - 1/2) ∂/∂v⊗dv\n\n and one has::\n\n sage: t.display(c_xy)\n t = x ∂/∂x⊗dx + ∂/∂x⊗dy + y ∂/∂y⊗dx\n sage: t.display(c_uv)\n t = (1/2*u + 1/2) ∂/∂u⊗du + (1/2*u - 1/2) ∂/∂u⊗dv\n + (1/2*v + 1/2) ∂/∂v⊗du + (1/2*v - 1/2) ∂/∂v⊗dv\n sage: t.display(c_xy.restrict(W))\n t = x ∂/∂x⊗dx + ∂/∂x⊗dy + y ∂/∂y⊗dx\n sage: t.restrict(W).display(c_uv.restrict(W))\n t = (1/2*u + 1/2) ∂/∂u⊗du + (1/2*u - 1/2) ∂/∂u⊗dv\n + (1/2*v + 1/2) ∂/∂v⊗du + (1/2*v - 1/2) ∂/∂v⊗dv\n\n One can ask for the display with respect to a frame in which ``t`` has\n not been initialized yet (this will automatically trigger the use of\n the change-of-frame formula for tensors)::\n\n sage: a = V.automorphism_field()\n sage: a[:] = [[1+v, -u^2], [0, 1-u]]\n sage: f = e_uv.new_frame(a, 'f')\n sage: [f[i].display() for i in M.irange()]\n [f_0 = (v + 1) ∂/∂u, f_1 = -u^2 ∂/∂u + (-u + 1) ∂/∂v]\n sage: t.display(f)\n t = -1/2*(u^2*v + 1)/(u - 1) f_0⊗f^0\n - 1/2*(2*u^3 - 5*u^2 - (u^4 + u^3 - u^2)*v + 3*u - 1)/((u - 1)*v + u - 1) f_0⊗f^1\n - 1/2*(v^2 + 2*v + 1)/(u - 1) f_1⊗f^0\n + 1/2*(u^2 + (u^2 + u - 1)*v - u + 1)/(u - 1) f_1⊗f^1\n\n A shortcut of ``display()`` is ``disp()``::\n\n sage: t.disp(e_uv)\n t = (1/2*u + 1/2) ∂/∂u⊗du + (1/2*u - 1/2) ∂/∂u⊗dv\n + (1/2*v + 1/2) ∂/∂v⊗du + (1/2*v - 1/2) ∂/∂v⊗dv\n\n \"\"\"\n if frame is None:\n if chart is not None:\n frame = chart.frame()\n else:\n if self._vmodule._dest_map.is_identity():\n frame = self._domain._def_frame\n else:\n for rst in self._restrictions.values():\n try:\n return rst.display()\n except ValueError:\n pass\n if frame is None: # should be \"is still None\" ;-)\n raise ValueError(\"a frame must be provided for the display\")\n else:\n try:\n frame0 = frame.frame()\n # if this succeeds, frame is actually not a vector frame, but\n # a coordinate chart\n if chart is None:\n chart = frame\n frame = frame0\n except AttributeError:\n # case of a genuine vector frame\n pass\n rst = self.restrict(frame._domain, dest_map=frame._dest_map)\n return rst.display(frame, chart)\n\n disp = display\n\n def display_comp(self, frame=None, chart=None, coordinate_labels=True,\n only_nonzero=True, only_nonredundant=False):\n r\"\"\"\n Display the tensor components with respect to a given frame,\n one per line.\n\n The output is either text-formatted (console mode) or LaTeX-formatted\n (notebook mode).\n\n INPUT:\n\n - ``frame`` -- (default: ``None``) vector frame with respect to which\n the tensor field components are defined; if ``None``, then\n\n * if ``chart`` is not ``None``, the coordinate frame associated to\n ``chart`` is used\n * otherwise, the default basis of the vector field module on which\n the tensor field is defined is used\n\n - ``chart`` -- (default: ``None``) chart specifying the coordinate\n expression of the components; if ``None``, the default chart of the\n tensor field domain is used\n - ``coordinate_labels`` -- (default: ``True``) boolean; if ``True``,\n coordinate symbols are used by default (instead of integers) as\n index labels whenever ``frame`` is a coordinate frame\n - ``only_nonzero`` -- (default: ``True``) boolean; if ``True``, only\n nonzero components are displayed\n - ``only_nonredundant`` -- (default: ``False``) boolean; if ``True``,\n only nonredundant components are displayed in case of symmetries\n\n EXAMPLES:\n\n Display of the components of a type-`(1,1)` tensor field defined\n on two open subsets::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U')\n sage: c_xy. = U.chart()\n sage: e = U.default_frame()\n sage: V = M.open_subset('V')\n sage: c_uv. = V.chart()\n sage: f = V.default_frame()\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: t = M.tensor_field(1,1, name='t')\n sage: t[e,0,0] = - x + y^3\n sage: t[e,0,1] = 2+x\n sage: t[f,1,1] = - u*v\n sage: t.display_comp(e)\n t^x_x = y^3 - x\n t^x_y = x + 2\n sage: t.display_comp(f)\n t^v_v = -u*v\n\n Components in a chart frame::\n\n sage: t.display_comp(chart=c_xy)\n t^x_x = y^3 - x\n t^x_y = x + 2\n sage: t.display_comp(chart=c_uv)\n t^v_v = -u*v\n\n See documentation of\n :meth:`sage.manifolds.differentiable.tensorfield_paral.TensorFieldParal.display_comp`\n for more options.\n\n \"\"\"\n if frame is None:\n if chart is not None:\n frame = chart.frame()\n else:\n if self._vmodule._dest_map.is_identity():\n frame = self._domain.default_frame()\n else:\n for rst in self._restrictions.values():\n try:\n return rst.display_comp(chart=chart,\n coordinate_labels=coordinate_labels,\n only_nonzero=only_nonzero,\n only_nonredundant=only_nonredundant)\n except ValueError:\n pass\n if frame is None: # should be \"is still None\" ;-)\n raise ValueError(\"a frame must be provided for the display\")\n rst = self.restrict(frame.domain(), dest_map=frame._dest_map)\n return rst.display_comp(frame=frame, chart=chart,\n coordinate_labels=coordinate_labels,\n only_nonzero=only_nonzero,\n only_nonredundant=only_nonredundant)\n\n def __getitem__(self, args):\n r\"\"\"\n Return a component with respect to some frame.\n\n INPUT:\n\n - ``args`` -- list of indices defining the component; if ``[:]`` is\n provided, all the components are returned\n\n The frame can be passed as the first item of ``args``. If not, the\n default frame of the tensor field's domain is assumed. If ``args``\n is a string, this method acts as a shortcut for tensor contractions\n and symmetrizations, the string containing abstract indices.\n\n TESTS::\n\n sage: M = Manifold(2, 'M') # the 2-dimensional sphere S^2\n sage: U = M.open_subset('U') # complement of the North pole\n sage: c_xy. = U.chart() # stereographic coordinates from the North pole\n sage: V = M.open_subset('V') # complement of the South pole\n sage: c_uv. = V.chart() # stereographic coordinates from the South pole\n sage: M.declare_union(U,V) # S^2 is the union of U and V\n sage: e_xy = c_xy.frame()\n sage: t = M.tensor_field(1, 1, name='t')\n sage: t[e_xy, :] = [[x+y, -2], [3*y^2, x*y]]\n sage: t.__getitem__((1,0))\n 3*y^2\n sage: t.__getitem__((1,1))\n x*y\n sage: t.__getitem__((e_xy,1,0))\n 3*y^2\n sage: t.__getitem__(slice(None))\n [x + y -2]\n [3*y^2 x*y]\n sage: t.__getitem__((e_xy,slice(None)))\n [x + y -2]\n [3*y^2 x*y]\n sage: t.__getitem__('^a_a') # trace\n Scalar field on the 2-dimensional differentiable manifold M\n sage: t.__getitem__('^a_a').display()\n M → ℝ\n on U: (x, y) ↦ (x + 1)*y + x\n\n \"\"\"\n if isinstance(args, str): # tensor with specified indices\n return TensorWithIndices(self, args).update()\n if isinstance(args, list): # case of [[...]] syntax\n if not isinstance(args[0], (int, Integer, slice)):\n frame = args[0]\n args = args[1:]\n else:\n frame = self._domain._def_frame\n else:\n if isinstance(args, (int, Integer, slice)):\n frame = self._domain._def_frame\n elif not isinstance(args[0], (int, Integer, slice)):\n frame = args[0]\n args = args[1:]\n else:\n frame = self._domain._def_frame\n return self.comp(frame)[args]\n\n def __setitem__(self, args, value):\n r\"\"\"\n Sets a component with respect to some vector frame.\n\n INPUT:\n\n - ``args`` -- list of indices; if ``[:]`` is provided, all the\n components are set; the frame can be passed as the first item\n of ``args``; if not, the default frame of the tensor field's\n domain is assumed\n - ``value`` -- the value to be set or a list of values if\n ``args = [:]``\n\n TESTS::\n\n sage: M = Manifold(2, 'M') # the 2-dimensional sphere S^2\n sage: U = M.open_subset('U') # complement of the North pole\n sage: c_xy. = U.chart() # stereographic coordinates from the North pole\n sage: V = M.open_subset('V') # complement of the South pole\n sage: c_uv. = V.chart() # stereographic coordinates from the South pole\n sage: M.declare_union(U,V) # S^2 is the union of U and V\n sage: e_xy = c_xy.frame()\n sage: t = M.tensor_field(1, 1, name='t')\n sage: t.__setitem__((e_xy, 0, 1), x+y^2)\n sage: t.display(e_xy)\n t = (y^2 + x) ∂/∂x⊗dy\n sage: t.__setitem__((0, 1), x+y^2) # same as above since e_xy is the default frame on M\n sage: t.display()\n t = (y^2 + x) ∂/∂x⊗dy\n sage: t.__setitem__(slice(None), [[x+y, -2], [3*y^2, x*y]])\n sage: t.display()\n t = (x + y) ∂/∂x⊗dx - 2 ∂/∂x⊗dy + 3*y^2 ∂/∂y⊗dx + x*y ∂/∂y⊗dy\n\n \"\"\"\n if isinstance(args, list): # case of [[...]] syntax\n if not isinstance(args[0], (int, Integer, slice)):\n frame = args[0]\n args = args[1:]\n else:\n frame = self._domain._def_frame\n else:\n if isinstance(args, (int, Integer, slice)):\n frame = self._domain._def_frame\n elif not isinstance(args[0], (int, Integer, slice)):\n frame = args[0]\n args = args[1:]\n else:\n frame = self._domain._def_frame\n self.set_comp(frame)[args] = value\n\n def copy_from(self, other):\n r\"\"\"\n Make ``self`` a copy of ``other``.\n\n INPUT:\n\n - ``other`` -- other tensor field, in the same module as ``self``\n\n .. NOTE::\n\n While the derived quantities are not copied, the name is kept.\n\n .. WARNING::\n\n All previous defined components and restrictions will be deleted!\n\n EXAMPLES::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U') ; V = M.open_subset('V')\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: c_xy. = U.chart() ; c_uv. = V.chart()\n sage: xy_to_uv = c_xy.transition_map(c_uv, (x+y, x-y),\n ....: intersection_name='W', restrictions1= x>0,\n ....: restrictions2= u+v>0)\n sage: uv_to_xy = xy_to_uv.inverse()\n sage: e_xy = c_xy.frame(); e_uv = c_uv.frame()\n sage: t = M.tensor_field(1, 1, name='t')\n sage: t[e_xy,:] = [[x+y, 0], [2, 1-y]]\n sage: t.add_comp_by_continuation(e_uv, U.intersection(V), c_uv)\n sage: s = M.tensor_field(1, 1, name='s')\n sage: s.copy_from(t)\n sage: s.display(e_xy)\n s = (x + y) ∂/∂x⊗dx + 2 ∂/∂y⊗dx + (-y + 1) ∂/∂y⊗dy\n sage: s == t\n True\n\n While the original tensor field is modified, the copy is not::\n\n sage: t[e_xy,0,0] = -1\n sage: t.display(e_xy)\n t = -∂/∂x⊗dx + 2 ∂/∂y⊗dx + (-y + 1) ∂/∂y⊗dy\n sage: s.display(e_xy)\n s = (x + y) ∂/∂x⊗dx + 2 ∂/∂y⊗dx + (-y + 1) ∂/∂y⊗dy\n sage: s == t\n False\n\n \"\"\"\n if self.is_immutable():\n raise ValueError(\"the components of an immutable element \"\n \"cannot be changed\")\n if other not in self.parent():\n raise TypeError(\"the original must be an element of \"\n f\"{self.parent()}\")\n self._del_derived()\n self._del_restrictions() # delete restrictions\n for dom, rst in other._restrictions.items():\n self._restrictions[dom] = rst.copy(name=self._name,\n latex_name=self._latex_name)\n self._is_zero = other._is_zero\n\n def copy(self, name=None, latex_name=None):\n r\"\"\"\n Return an exact copy of ``self``.\n\n INPUT:\n\n - ``name`` -- (default: ``None``) name given to the copy\n - ``latex_name`` -- (default: ``None``) LaTeX symbol to denote the\n copy; if none is provided, the LaTeX symbol is set to ``name``\n\n .. NOTE::\n\n The name and the derived quantities are not copied.\n\n EXAMPLES:\n\n Copy of a type-`(1,1)` tensor field on a 2-dimensional manifold::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U') ; V = M.open_subset('V')\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: c_xy. = U.chart() ; c_uv. = V.chart()\n sage: xy_to_uv = c_xy.transition_map(c_uv, (x+y, x-y),\n ....: intersection_name='W', restrictions1= x>0,\n ....: restrictions2= u+v>0)\n sage: uv_to_xy = xy_to_uv.inverse()\n sage: e_xy = c_xy.frame(); e_uv = c_uv.frame()\n sage: t = M.tensor_field(1, 1, name='t')\n sage: t[e_xy,:] = [[x+y, 0], [2, 1-y]]\n sage: t.add_comp_by_continuation(e_uv, U.intersection(V), c_uv)\n sage: s = t.copy(); s\n Tensor field of type (1,1) on the 2-dimensional differentiable\n manifold M\n sage: s.display(e_xy)\n (x + y) ∂/∂x⊗dx + 2 ∂/∂y⊗dx + (-y + 1) ∂/∂y⊗dy\n sage: s == t\n True\n\n If the original tensor field is modified, the copy is not::\n\n sage: t[e_xy,0,0] = -1\n sage: t.display(e_xy)\n t = -∂/∂x⊗dx + 2 ∂/∂y⊗dx + (-y + 1) ∂/∂y⊗dy\n sage: s.display(e_xy)\n (x + y) ∂/∂x⊗dx + 2 ∂/∂y⊗dx + (-y + 1) ∂/∂y⊗dy\n sage: s == t\n False\n\n \"\"\"\n resu = self._new_instance()\n # set resu name\n if name is not None:\n resu._name = name\n if latex_name is None:\n resu._latex_name = name\n if latex_name is not None:\n resu._latex_name = latex_name\n # set restrictions\n for dom, rst in self._restrictions.items():\n resu._restrictions[dom] = rst.copy(name=name,\n latex_name=latex_name)\n resu._is_zero = self._is_zero\n return resu\n\n def _common_subdomains(self, other):\n r\"\"\"\n Return the list of subdomains of ``self._domain`` on which\n both ``self`` and ``other`` have known restrictions.\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U') ; V = M.open_subset('V')\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: c_xy. = U.chart() ; c_uv. = V.chart()\n sage: xy_to_uv = c_xy.transition_map(c_uv, (x+y, x-y),\n ....: intersection_name='W', restrictions1= x>0,\n ....: restrictions2= u+v>0)\n sage: uv_to_xy = xy_to_uv.inverse()\n sage: e_xy = c_xy.frame(); e_uv = c_uv.frame()\n sage: t = M.tensor_field(1, 1, name='t')\n sage: t[e_xy,:] = [[x+y, 0], [2, 0]]\n sage: t.add_comp_by_continuation(e_uv, U.intersection(V), c_uv)\n sage: sorted(t._common_subdomains(t), key=str)\n [Open subset U of the 2-dimensional differentiable manifold M,\n Open subset V of the 2-dimensional differentiable manifold M,\n Open subset W of the 2-dimensional differentiable manifold M]\n sage: a = M.tensor_field(1, 1, name='a')\n sage: t._common_subdomains(a)\n []\n sage: a[e_xy, 0, 1] = 0\n sage: t._common_subdomains(a)\n [Open subset U of the 2-dimensional differentiable manifold M]\n sage: a[e_uv, 0, 0] = 0\n sage: sorted(t._common_subdomains(a), key=str)\n [Open subset U of the 2-dimensional differentiable manifold M,\n Open subset V of the 2-dimensional differentiable manifold M]\n\n \"\"\"\n resu = []\n for dom in self._restrictions:\n if dom in other._restrictions:\n resu.append(dom)\n return resu\n\n def __eq__(self, other):\n r\"\"\"\n Comparison (equality) operator.\n\n INPUT:\n\n - ``other`` -- a tensor field or 0\n\n OUTPUT:\n\n - ``True`` if ``self`` is equal to ``other`` and ``False`` otherwise\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U') ; V = M.open_subset('V')\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: c_xy. = U.chart() ; c_uv. = V.chart()\n sage: xy_to_uv = c_xy.transition_map(c_uv, (x+y, x-y),\n ....: intersection_name='W', restrictions1= x>0,\n ....: restrictions2= u+v>0)\n sage: uv_to_xy = xy_to_uv.inverse()\n sage: e_xy = c_xy.frame(); e_uv = c_uv.frame()\n sage: t = M.tensor_field(1, 1, name='t')\n sage: t[e_xy,:] = [[x+y, 0], [2, 1-y]]\n sage: t.add_comp_by_continuation(e_uv, U.intersection(V), c_uv)\n sage: t == t\n True\n sage: t == t.copy()\n True\n sage: a = M.tensor_field(1, 1, name='a')\n sage: a.set_restriction(t.restrict(U))\n sage: t == a # False since a has not been defined on V\n False\n sage: a.set_restriction(t.restrict(V))\n sage: t == a # True now\n True\n sage: a[e_xy, 0, 0] = -1\n sage: t == a # False since a has been reset on U (domain of e_xy)\n False\n sage: t.parent().zero() == 0\n True\n \"\"\"\n from .mixed_form import MixedForm\n\n if other is self:\n return True\n if other in ZZ: # to compare with 0\n if other == 0:\n return self.is_zero()\n return False\n elif isinstance(other, MixedForm):\n # use comparison of MixedForm:\n return other == self\n elif not isinstance(other, TensorField):\n return False\n else: # other is another tensor field\n if other._vmodule != self._vmodule:\n return False\n if other._tensor_type != self._tensor_type:\n return False\n # Non-trivial open covers of the domain:\n for oc in self._domain.open_covers(trivial=False):\n resu = True\n for dom in oc:\n try:\n resu = resu and \\\n bool(self.restrict(dom) == other.restrict(dom))\n except ValueError:\n break\n else:\n # If this point is reached, no exception has occurred; hence\n # the result is valid and can be returned:\n return resu\n # If this point is reached, the comparison has not been possible\n # on any open cover; we then compare the restrictions to\n # subdomains:\n if not self._restrictions:\n return False # self is not initialized\n if len(self._restrictions) != len(other._restrictions):\n return False # the restrictions are not on the same subdomains\n resu = True\n for dom, rst in self._restrictions.items():\n if dom in other._restrictions:\n resu = resu and bool(rst == other._restrictions[dom])\n else:\n return False # the restrictions are not on the same\n # subdomains\n return resu\n\n def __ne__(self, other):\n r\"\"\"\n Inequality operator.\n\n INPUT:\n\n - ``other`` -- a tensor field or 0\n\n OUTPUT:\n\n - ``True`` if ``self`` is different from ``other`` and ``False``\n otherwise\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U') ; V = M.open_subset('V')\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: c_xy. = U.chart() ; c_uv. = V.chart()\n sage: xy_to_uv = c_xy.transition_map(c_uv, (x+y, x-y),\n ....: intersection_name='W', restrictions1= x>0,\n ....: restrictions2= u+v>0)\n sage: uv_to_xy = xy_to_uv.inverse()\n sage: e_xy = c_xy.frame(); e_uv = c_uv.frame()\n sage: t = M.tensor_field(1, 1, name='t')\n sage: t[e_xy,:] = [[x+y, 0], [2, 1-y]]\n sage: t.add_comp_by_continuation(e_uv, U.intersection(V), c_uv)\n sage: t != t\n False\n sage: t != t.copy()\n False\n sage: t != 0\n True\n\n \"\"\"\n return not (self == other)\n\n def __pos__(self):\n r\"\"\"\n Unary plus operator.\n\n OUTPUT:\n\n - an exact copy of ``self``\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U') ; V = M.open_subset('V')\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: c_xy. = U.chart() ; c_uv. = V.chart()\n sage: xy_to_uv = c_xy.transition_map(c_uv, (x+y, x-y),\n ....: intersection_name='W', restrictions1= x>0,\n ....: restrictions2= u+v>0)\n sage: uv_to_xy = xy_to_uv.inverse()\n sage: e_xy = c_xy.frame(); e_uv = c_uv.frame()\n sage: t = M.tensor_field(1, 1, name='t')\n sage: t[e_xy,:] = [[x+y, 0], [2, 1-y]]\n sage: t.add_comp_by_continuation(e_uv, U.intersection(V), c_uv)\n sage: s = t.__pos__(); s\n Tensor field +t of type (1,1) on the 2-dimensional differentiable\n manifold M\n sage: s.display(e_xy)\n +t = (x + y) ∂/∂x⊗dx + 2 ∂/∂y⊗dx + (-y + 1) ∂/∂y⊗dy\n\n \"\"\"\n resu = self._new_instance()\n for dom, rst in self._restrictions.items():\n resu._restrictions[dom] = + rst\n # Compose names:\n from sage.tensor.modules.format_utilities import (format_unop_txt,\n format_unop_latex)\n resu._name = format_unop_txt('+', self._name)\n resu._latex_name = format_unop_latex(r'+', self._latex_name)\n return resu\n\n def __neg__(self):\n r\"\"\"\n Unary minus operator.\n\n OUTPUT:\n\n - the tensor field `-T`, where `T` is ``self``\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U') ; V = M.open_subset('V')\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: c_xy. = U.chart() ; c_uv. = V.chart()\n sage: xy_to_uv = c_xy.transition_map(c_uv, (x+y, x-y),\n ....: intersection_name='W', restrictions1= x>0,\n ....: restrictions2= u+v>0)\n sage: uv_to_xy = xy_to_uv.inverse()\n sage: e_xy = c_xy.frame(); e_uv = c_uv.frame()\n sage: t = M.tensor_field(1, 1, name='t')\n sage: t[e_xy, :] = [[x, -x], [y, -y]]\n sage: t.add_comp_by_continuation(e_uv, U.intersection(V), c_uv)\n sage: t.display(e_xy)\n t = x ∂/∂x⊗dx - x ∂/∂x⊗dy + y ∂/∂y⊗dx - y ∂/∂y⊗dy\n sage: t.display(e_uv)\n t = u ∂/∂u⊗dv + v ∂/∂v⊗dv\n sage: s = t.__neg__(); s\n Tensor field -t of type (1,1) on the 2-dimensional differentiable\n manifold M\n sage: s.display(e_xy)\n -t = -x ∂/∂x⊗dx + x ∂/∂x⊗dy - y ∂/∂y⊗dx + y ∂/∂y⊗dy\n sage: s.display(e_uv)\n -t = -u ∂/∂u⊗dv - v ∂/∂v⊗dv\n sage: s == -t # indirect doctest\n True\n\n \"\"\"\n resu = self._new_instance()\n for dom, rst in self._restrictions.items():\n resu._restrictions[dom] = - rst\n # Compose names:\n from sage.tensor.modules.format_utilities import (format_unop_txt,\n format_unop_latex)\n resu._name = format_unop_txt('-', self._name)\n resu._latex = format_unop_latex(r'-', self._latex_name)\n return resu\n\n ######### ModuleElement arithmetic operators ########\n\n def _add_(self, other):\n r\"\"\"\n Tensor field addition.\n\n INPUT:\n\n - ``other`` -- a tensor field, in the same tensor module as ``self``\n\n OUTPUT:\n\n - the tensor field resulting from the addition of ``self``\n and ``other``\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U') ; V = M.open_subset('V')\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: c_xy. = U.chart() ; c_uv. = V.chart()\n sage: xy_to_uv = c_xy.transition_map(c_uv, (x+y, x-y),\n ....: intersection_name='W', restrictions1= x>0,\n ....: restrictions2= u+v>0)\n sage: uv_to_xy = xy_to_uv.inverse()\n sage: e_xy = c_xy.frame(); e_uv = c_uv.frame()\n sage: a = M.tensor_field(1, 1, name='a')\n sage: a[e_xy,:] = [[x, 1], [y, 0]]\n sage: a.add_comp_by_continuation(e_uv, U.intersection(V), c_uv)\n sage: b = M.tensor_field(1, 1, name='b')\n sage: b[e_xy,:] = [[2, y], [x, -x]]\n sage: b.add_comp_by_continuation(e_uv, U.intersection(V), c_uv)\n sage: s = a._add_(b); s\n Tensor field a+b of type (1,1) on the 2-dimensional differentiable\n manifold M\n sage: a.display(e_xy)\n a = x ∂/∂x⊗dx + ∂/∂x⊗dy + y ∂/∂y⊗dx\n sage: b.display(e_xy)\n b = 2 ∂/∂x⊗dx + y ∂/∂x⊗dy + x ∂/∂y⊗dx - x ∂/∂y⊗dy\n sage: s.display(e_xy)\n a+b = (x + 2) ∂/∂x⊗dx + (y + 1) ∂/∂x⊗dy + (x + y) ∂/∂y⊗dx - x ∂/∂y⊗dy\n sage: s == a + b # indirect doctest\n True\n sage: z = a.parent().zero(); z\n Tensor field zero of type (1,1) on the 2-dimensional differentiable\n manifold M\n sage: a._add_(z) == a\n True\n sage: z._add_(a) == a\n True\n\n \"\"\"\n # Case zero:\n if self._is_zero:\n return other\n if other._is_zero:\n return self\n # Generic case:\n resu_rst = {}\n for dom in self._common_subdomains(other):\n resu_rst[dom] = self._restrictions[dom] + other._restrictions[dom]\n some_rst = next(iter(resu_rst.values()))\n resu_sym = some_rst._sym\n resu_antisym = some_rst._antisym\n resu = self._vmodule.tensor(self._tensor_type, sym=resu_sym,\n antisym=resu_antisym)\n resu._restrictions = resu_rst\n if self._name is not None and other._name is not None:\n resu._name = self._name + '+' + other._name\n if self._latex_name is not None and other._latex_name is not None:\n resu._latex_name = self._latex_name + '+' + other._latex_name\n return resu\n\n def _sub_(self, other):\n r\"\"\"\n Tensor field subtraction.\n\n INPUT:\n\n - ``other`` -- a tensor field, in the same tensor module as ``self``\n\n OUTPUT:\n\n - the tensor field resulting from the subtraction of ``other``\n from ``self``\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U') ; V = M.open_subset('V')\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: c_xy. = U.chart() ; c_uv. = V.chart()\n sage: xy_to_uv = c_xy.transition_map(c_uv, (x+y, x-y),\n ....: intersection_name='W', restrictions1= x>0,\n ....: restrictions2= u+v>0)\n sage: uv_to_xy = xy_to_uv.inverse()\n sage: e_xy = c_xy.frame(); e_uv = c_uv.frame()\n sage: a = M.tensor_field(1, 1, name='a')\n sage: a[e_xy,:] = [[x, 1], [y, 0]]\n sage: a.add_comp_by_continuation(e_uv, U.intersection(V), c_uv)\n sage: b = M.tensor_field(1, 1, name='b')\n sage: b[e_xy,:] = [[2, y], [x, -x]]\n sage: b.add_comp_by_continuation(e_uv, U.intersection(V), c_uv)\n sage: s = a._sub_(b); s\n Tensor field a-b of type (1,1) on the 2-dimensional differentiable\n manifold M\n sage: a.display(e_xy)\n a = x ∂/∂x⊗dx + ∂/∂x⊗dy + y ∂/∂y⊗dx\n sage: b.display(e_xy)\n b = 2 ∂/∂x⊗dx + y ∂/∂x⊗dy + x ∂/∂y⊗dx - x ∂/∂y⊗dy\n sage: s.display(e_xy)\n a-b = (x - 2) ∂/∂x⊗dx + (-y + 1) ∂/∂x⊗dy + (-x + y) ∂/∂y⊗dx + x ∂/∂y⊗dy\n sage: s == a - b\n True\n sage: z = a.parent().zero()\n sage: a._sub_(z) == a\n True\n sage: z._sub_(a) == -a\n True\n\n \"\"\"\n # Case zero:\n if self._is_zero:\n return -other\n if other._is_zero:\n return self\n # Generic case:\n resu_rst = {}\n for dom in self._common_subdomains(other):\n resu_rst[dom] = self._restrictions[dom] - other._restrictions[dom]\n some_rst = next(iter(resu_rst.values()))\n resu_sym = some_rst._sym\n resu_antisym = some_rst._antisym\n resu = self._vmodule.tensor(self._tensor_type, sym=resu_sym,\n antisym=resu_antisym)\n resu._restrictions = resu_rst\n if self._name is not None and other._name is not None:\n resu._name = self._name + '-' + other._name\n if self._latex_name is not None and other._latex_name is not None:\n resu._latex_name = self._latex_name + '-' + other._latex_name\n return resu\n\n def _rmul_(self, scalar):\n r\"\"\"\n Reflected multiplication operator: performs ``scalar * self``\n\n This is actually the multiplication by an element of the ring over\n which the tensor field module is constructed.\n\n INPUT:\n\n - ``scalar`` -- scalar field in the scalar field algebra over which\n the module containing ``self`` is defined\n\n OUTPUT:\n\n - the tensor field ``scalar * self``\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U') ; V = M.open_subset('V')\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: c_xy. = U.chart() ; c_uv. = V.chart()\n sage: xy_to_uv = c_xy.transition_map(c_uv, (x+y, x-y),\n ....: intersection_name='W', restrictions1= x>0,\n ....: restrictions2= u+v>0)\n sage: uv_to_xy = xy_to_uv.inverse()\n sage: e_xy = c_xy.frame(); e_uv = c_uv.frame()\n sage: a = M.tensor_field(1, 1, name='a')\n sage: a[e_xy,:] = [[x, 1], [y, 0]]\n sage: a.add_comp_by_continuation(e_uv, U.intersection(V), c_uv)\n sage: f = M.scalar_field({c_xy: 1/(1+x^2+y^2)}, name='f')\n sage: f.add_expr_by_continuation(c_uv, U.intersection(V))\n sage: f.display()\n f: M → ℝ\n on U: (x, y) ↦ 1/(x^2 + y^2 + 1)\n on V: (u, v) ↦ 2/(u^2 + v^2 + 2)\n sage: s = a._rmul_(f); s\n Tensor field f*a of type (1,1) on the 2-dimensional differentiable\n manifold M\n sage: a.display(e_xy)\n a = x ∂/∂x⊗dx + ∂/∂x⊗dy + y ∂/∂y⊗dx\n sage: s.display(e_xy)\n f*a = x/(x^2 + y^2 + 1) ∂/∂x⊗dx + 1/(x^2 + y^2 + 1) ∂/∂x⊗dy + y/(x^2 + y^2 + 1) ∂/∂y⊗dx\n sage: a.display(e_uv)\n a = (1/2*u + 1/2) ∂/∂u⊗du + (1/2*u - 1/2) ∂/∂u⊗dv + (1/2*v + 1/2) ∂/∂v⊗du + (1/2*v - 1/2) ∂/∂v⊗dv\n sage: s.display(e_uv)\n f*a = (u + 1)/(u^2 + v^2 + 2) ∂/∂u⊗du + (u - 1)/(u^2 + v^2 + 2) ∂/∂u⊗dv + (v + 1)/(u^2 + v^2 + 2) ∂/∂v⊗du + (v - 1)/(u^2 + v^2 + 2) ∂/∂v⊗dv\n sage: s == f*a # indirect doctest\n True\n sage: z = a.parent().zero(); z\n Tensor field zero of type (1,1) on the 2-dimensional differentiable\n manifold M\n sage: a._rmul_(M.zero_scalar_field()) == z\n True\n sage: z._rmul_(f) == z\n True\n\n \"\"\"\n # Case zero:\n if scalar._is_zero:\n return self.parent().zero()\n # Case one:\n if scalar is self._domain._one_scalar_field:\n return self\n # Generic case:\n resu = self._new_instance()\n for dom, rst in self._restrictions.items():\n resu._restrictions[dom] = scalar.restrict(dom) * rst\n # Compose names:\n from sage.tensor.modules.format_utilities import (format_mul_txt,\n format_mul_latex)\n resu_name = format_mul_txt(scalar._name, '*', self._name)\n resu_latex = format_mul_latex(scalar._latex_name, r' \\cdot ',\n self._latex_name)\n resu.set_name(name=resu_name, latex_name=resu_latex)\n return resu\n\n ######### End of ModuleElement arithmetic operators ########\n\n # TODO: Move to acted_upon or _rmul_\n def __mul__(self, other: TensorField) -> TensorField:\n r\"\"\"\n Tensor product (or multiplication of the right by a scalar).\n\n INPUT:\n\n - ``other`` -- tensor field on the same manifold as ``self`` (or an\n object that can be coerced to a scalar field on the same manifold\n as ``self``)\n\n OUTPUT:\n\n - the tensor field resulting from the tensor product of ``self``\n with ``other`` (or from the product ``other * self`` if ``other``\n is a scalar)\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U') ; V = M.open_subset('V')\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: c_xy. = U.chart() ; c_uv. = V.chart()\n sage: xy_to_uv = c_xy.transition_map(c_uv, (x+y, x-y),\n ....: intersection_name='W', restrictions1= x>0,\n ....: restrictions2= u+v>0)\n sage: uv_to_xy = xy_to_uv.inverse()\n sage: e_xy = c_xy.frame(); e_uv = c_uv.frame()\n sage: a = M.tensor_field(1, 1, name='a')\n sage: a[e_xy,:] = [[x, 1], [y, 0]]\n sage: a.add_comp_by_continuation(e_uv, U.intersection(V), c_uv)\n\n Tensor product with another tensor field::\n\n sage: b = M.vector_field(name='b')\n sage: b[e_xy, :] = [x, y]\n sage: b.add_comp_by_continuation(e_uv, U.intersection(V), c_uv)\n sage: s = a.__mul__(b); s\n Tensor field of type (2,1) on the 2-dimensional differentiable\n manifold M\n sage: s.display(e_xy)\n a⊗b = x^2 ∂/∂x⊗∂/∂x⊗dx + x ∂/∂x⊗∂/∂x⊗dy + x*y ∂/∂x⊗∂/∂y⊗dx\n + y ∂/∂x⊗∂/∂y⊗dy + x*y ∂/���y⊗∂/∂x⊗dx + y^2 ∂/∂y⊗∂/∂y⊗dx\n sage: s.display(e_uv)\n a⊗b = (1/2*u^2 + 1/2*u) ∂/∂u⊗∂/∂u⊗du + (1/2*u^2 - 1/2*u) ∂/∂u⊗∂/∂u⊗dv\n + 1/2*(u + 1)*v ∂/∂u⊗∂/∂v⊗du + 1/2*(u - 1)*v ∂/∂u⊗∂/∂v⊗dv\n + (1/2*u*v + 1/2*u) ∂/∂v⊗∂/∂u⊗du + (1/2*u*v - 1/2*u) ∂/∂v⊗∂/∂u⊗dv\n + (1/2*v^2 + 1/2*v) ∂/∂v⊗∂/∂v⊗du + (1/2*v^2 - 1/2*v) ∂/∂v⊗∂/∂v⊗dv\n\n Multiplication on the right by a scalar field::\n\n sage: f = M.scalar_field({c_xy: x*y}, name='f')\n sage: f.add_expr_by_continuation(c_uv, U.intersection(V))\n sage: s = a.__mul__(f); s\n Tensor field f*a of type (1,1) on the 2-dimensional differentiable\n manifold M\n sage: s.display(e_xy)\n f*a = x^2*y ∂/∂x⊗dx + x*y ∂/∂x⊗dy + x*y^2 ∂/∂y⊗dx\n sage: s.display(e_uv)\n f*a = (1/8*u^3 - 1/8*(u + 1)*v^2 + 1/8*u^2) ∂/∂u⊗du\n + (1/8*u^3 - 1/8*(u - 1)*v^2 - 1/8*u^2) ∂/∂u⊗dv\n + (1/8*u^2*v - 1/8*v^3 + 1/8*u^2 - 1/8*v^2) ∂/∂v⊗du\n + (1/8*u^2*v - 1/8*v^3 - 1/8*u^2 + 1/8*v^2) ∂/∂v⊗dv\n sage: s == f*a\n True\n\n Multiplication on the right by a number::\n\n sage: s = a.__mul__(2); s\n Tensor field of type (1,1) on the 2-dimensional differentiable\n manifold M\n sage: s.display(e_xy)\n 2*x ∂/∂x⊗dx + 2 ∂/∂x⊗dy + 2*y ∂/∂y⊗dx\n sage: s.display(e_uv)\n (u + 1) ∂/∂u⊗du + (u - 1) ∂/∂u⊗dv + (v + 1) ∂/∂v⊗du\n + (v - 1) ∂/∂v⊗dv\n sage: s.restrict(U) == 2*a.restrict(U)\n True\n sage: s.restrict(V) == 2*a.restrict(V)\n True\n sage: s == 2*a\n True\n\n Test with SymPy as calculus engine::\n\n sage: M.set_calculus_method('sympy')\n sage: f.add_expr_by_continuation(c_uv, U.intersection(V))\n sage: s = a.__mul__(f); s\n Tensor field f*a of type (1,1) on the 2-dimensional differentiable\n manifold M\n sage: s.display(e_xy)\n f*a = x**2*y ∂/∂x⊗dx + x*y ∂/∂x⊗dy + x*y**2 ∂/∂y⊗dx\n sage: s.display(e_uv)\n f*a = (u**3/8 + u**2/8 - u*v**2/8 - v**2/8) ∂/∂u⊗du + (u**3/8 -\n u**2/8 - u*v**2/8 + v**2/8) ∂/∂u⊗dv + (u**2*v/8 + u**2/8 -\n v**3/8 - v**2/8) ∂/∂v⊗du + (u**2*v/8 - u**2/8 - v**3/8 +\n v**2/8) ∂/∂v⊗dv\n sage: s == f*a\n True\n\n \"\"\"\n from sage.manifolds.differentiable.mixed_form import MixedForm\n if isinstance(other, MixedForm):\n return other.parent()(self)._mul_(other)\n if not isinstance(other, TensorField):\n # Multiplication by a scalar field or a number\n return other * self\n # Tensor product:\n dom_resu = self._domain.intersection(other._domain)\n ambient_dom_resu = self._ambient_domain.intersection(other._ambient_domain)\n self_r = self.restrict(dom_resu)\n other_r = other.restrict(dom_resu)\n if ambient_dom_resu.is_manifestly_parallelizable():\n # call of the FreeModuleTensor version:\n return FreeModuleTensor.__mul__(self_r, other_r)\n dest_map = self._vmodule._dest_map\n dest_map_resu = dest_map.restrict(dom_resu, subcodomain=ambient_dom_resu)\n vmodule = dom_resu.vector_field_module(dest_map=dest_map_resu)\n com_dom = []\n for dom in self_r._restrictions:\n if dom in other_r._restrictions:\n com_dom.append(dom)\n resu_rst = []\n for dom in com_dom:\n self_rr = self_r._restrictions[dom]\n other_rr = other_r._restrictions[dom]\n resu_rst.append(self_rr * other_rr)\n k1, l1 = self._tensor_type\n k2, l2 = other._tensor_type\n resu = vmodule.tensor((k1+k2, l1+l2),\n sym=resu_rst[0]._sym,\n antisym=resu_rst[0]._antisym)\n for rst in resu_rst:\n resu._restrictions[rst._domain] = rst\n\n return resu\n\n def __truediv__(self, scalar) -> TensorField:\n r\"\"\"\n Division by a scalar field.\n\n INPUT:\n\n - ``scalar`` -- scalar field in the scalar field algebra over which\n the module containing ``self`` is defined\n\n OUTPUT:\n\n - the tensor field ``scalar * self``\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U') ; V = M.open_subset('V')\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: c_xy. = U.chart() ; c_uv. = V.chart()\n sage: xy_to_uv = c_xy.transition_map(c_uv, (x+y, x-y),\n ....: intersection_name='W', restrictions1= x>0,\n ....: restrictions2= u+v>0)\n sage: uv_to_xy = xy_to_uv.inverse()\n sage: e_xy = c_xy.frame(); e_uv = c_uv.frame()\n sage: a = M.tensor_field(1, 1, name='a')\n sage: a[e_xy,:] = [[x, 1], [y, 0]]\n sage: a.add_comp_by_continuation(e_uv, U.intersection(V), c_uv)\n sage: f = M.scalar_field({c_xy: 1/(1+x^2+y^2)}, name='f')\n sage: f.add_expr_by_continuation(c_uv, U.intersection(V))\n sage: f.display()\n f: M → ℝ\n on U: (x, y) ↦ 1/(x^2 + y^2 + 1)\n on V: (u, v) ↦ 2/(u^2 + v^2 + 2)\n sage: s = a.__truediv__(f); s\n Tensor field of type (1,1) on the 2-dimensional differentiable\n manifold M\n sage: s.display(e_xy)\n (x^3 + x*y^2 + x) ∂/∂x⊗dx + (x^2 + y^2 + 1) ∂/∂x⊗dy\n + (y^3 + (x^2 + 1)*y) ∂/∂y⊗dx\n sage: f*s == a\n True\n\n Division by a number::\n\n sage: s = a.__truediv__(2); s\n Tensor field of type (1,1) on the 2-dimensional differentiable\n manifold M\n sage: s.display(e_xy)\n 1/2*x ∂/∂x⊗dx + 1/2 ∂/∂x⊗dy + 1/2*y ∂/∂y⊗dx\n sage: s.display(e_uv)\n (1/4*u + 1/4) ∂/∂u⊗du + (1/4*u - 1/4) ∂/∂u⊗dv\n + (1/4*v + 1/4) ∂/∂v⊗du + (1/4*v - 1/4) ∂/∂v⊗dv\n sage: s == a/2\n True\n sage: 2*s == a\n True\n\n \"\"\"\n resu = self._new_instance()\n for dom, rst in self._restrictions.items():\n resu._restrictions[dom] = rst / scalar\n return resu\n\n def __call__(self, *args):\n r\"\"\"\n The tensor field acting on 1-forms and vector fields as a\n multilinear map.\n\n In the particular case of tensor field of type `(1,1)`, the action can\n be on a single vector field, the tensor field being identified to a\n field of tangent-space endomorphisms. The output is then a vector\n field.\n\n INPUT:\n\n - ``*args`` -- list of `k` 1-forms and `l` vector fields, ``self``\n being a tensor of type `(k,l)`\n\n OUTPUT:\n\n - either the scalar field resulting from the action of ``self`` on\n the 1-forms and vector fields passed as arguments or the vector\n field resulting from the action of ``self`` as a field of\n tangent-space endomorphisms (case of a type-(1,1) tensor field)\n\n TESTS:\n\n Action of a tensor field of type `(1,1)` on the 2-sphere::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U') ; V = M.open_subset('V')\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: c_xy. = U.chart() ; c_uv. = V.chart()\n sage: xy_to_uv = c_xy.transition_map(c_uv, (x+y, x-y),\n ....: intersection_name='W', restrictions1= x>0,\n ....: restrictions2= u+v>0)\n sage: uv_to_xy = xy_to_uv.inverse()\n sage: e_xy = c_xy.frame(); e_uv = c_uv.frame()\n sage: t = M.tensor_field(1,1, name='t')\n sage: t[e_xy,:] = [[x, 1], [y, 0]]\n sage: t.add_comp_by_continuation(e_uv, U.intersection(V), c_uv)\n sage: w = M.vector_field(name='w')\n sage: w[e_xy,:] = [y^2, x^2]\n sage: w.add_comp_by_continuation(e_uv, U.intersection(V), c_uv)\n sage: a = M.one_form(name='a')\n sage: a[e_xy,:] = [-1+y, x*y]\n sage: a.add_comp_by_continuation(e_uv, U.intersection(V), c_uv)\n\n The tensor field acting on a pair (1-form, vector field)::\n\n sage: s = t.__call__(a,w); s\n Scalar field t(a,w) on the 2-dimensional differentiable manifold M\n sage: s.display()\n t(a,w): M → ℝ\n on U: (x, y) ↦ x*y^4 + x*y^3 + x^2*y - x*y^2 - x^2\n on V: (u, v) ↦ 1/32*u^5 - 1/32*(3*u + 2)*v^4 + 1/32*v^5\n + 1/16*u^4 + 1/16*(u^2 + 2*u - 4)*v^3 + 1/16*(u^3 - 4)*v^2\n - 1/4*u^2 - 1/32*(3*u^4 + 4*u^3 - 8*u^2 + 16*u)*v\n sage: s.restrict(U) == t.restrict(U)(a.restrict(U), w.restrict(U))\n True\n sage: s.restrict(V) == t.restrict(V)(a.restrict(V), w.restrict(V))\n True\n\n The tensor field acting on vector field, as a field of tangent-space\n endomorphisms::\n\n sage: s = t.__call__(w); s\n Vector field t(w) on the 2-dimensional differentiable manifold M\n sage: s.display(e_xy)\n t(w) = (x*y^2 + x^2) ∂/∂x + y^3 ∂/∂y\n sage: s.display(e_uv)\n t(w) = (1/4*u^3 + 1/4*(u + 1)*v^2 + 1/4*u^2 - 1/2*(u^2 - u)*v) ∂/∂u\n + (-1/4*(2*u - 1)*v^2 + 1/4*v^3 + 1/4*u^2 + 1/4*(u^2 + 2*u)*v) ∂/∂v\n sage: s.restrict(U) == t.restrict(U)(w.restrict(U))\n True\n sage: s.restrict(V) == t.restrict(V)(w.restrict(V))\n True\n\n \"\"\"\n p = len(args)\n if p == 1 and self._tensor_type == (1,1):\n # type-(1,1) tensor acting as a field of tangent-space\n # endomorphisms:\n vector = args[0]\n if vector._tensor_type != (1,0):\n raise TypeError(\"the argument must be a vector field\")\n dom_resu = self._domain.intersection(vector._domain)\n if dom_resu.is_manifestly_parallelizable():\n # call of the TensorFieldParal version:\n return self.restrict(dom_resu)(vector.restrict(dom_resu))\n if self._name is not None and vector._name is not None:\n name_resu = \"{}({})\".format(self._name, vector._name)\n else:\n name_resu = None\n if self._latex_name is not None and vector._latex_name is not None:\n latex_name_resu = r\"{}\\left({}\\right)\".format(self._latex_name,\n vector._latex_name)\n else:\n latex_name_resu = None\n dest_map = vector._vmodule._dest_map\n dest_map_resu = dest_map.restrict(dom_resu)\n resu = dom_resu.vector_field(name=name_resu,\n latex_name=latex_name_resu,\n dest_map=dest_map_resu)\n for dom in self._common_subdomains(vector):\n if dom.is_subset(dom_resu):\n resu._restrictions[dom] = \\\n self._restrictions[dom](vector._restrictions[dom])\n return resu\n # Generic case\n if p != self._tensor_rank:\n raise TypeError(\"{} arguments must be \".format(self._tensor_rank) +\n \"provided\")\n # Domain of the result\n dom_resu = self._domain\n ambient_dom = self._ambient_domain\n for arg in args:\n dom_resu = dom_resu.intersection(arg._domain)\n ambient_dom = ambient_dom.intersection(arg._ambient_domain)\n self_r = self.restrict(dom_resu)\n args_r = [args[i].restrict(dom_resu) for i in range(p)]\n if ambient_dom.is_manifestly_parallelizable():\n # TensorFieldParal version\n return self_r(*args_r)\n else:\n resu = dom_resu.scalar_field()\n com_dom = []\n for dom in self_r._restrictions:\n for arg in args_r:\n if dom not in arg._restrictions:\n break\n else:\n com_dom.append(dom)\n for dom in com_dom:\n self_rr = self_r._restrictions[dom]\n args_rr = [args_r[i]._restrictions[dom] for i in range(p)]\n resu_rr = self_rr(*args_rr)\n if resu_rr.is_trivial_zero():\n for chart in resu_rr._domain._atlas:\n resu._express[chart] = chart.zero_function()\n else:\n for chart, expr in resu_rr._express.items():\n resu._express[chart] = expr\n if resu.is_trivial_zero():\n return dom_resu._zero_scalar_field\n # Name of the output:\n res_name = None\n if self._name is not None:\n res_name = self._name + \"(\"\n for i in range(p-1):\n if args[i]._name is not None:\n res_name += args[i]._name + \",\"\n else:\n res_name = None\n break\n if res_name is not None:\n if args[p-1]._name is not None:\n res_name += args[p-1]._name + \")\"\n else:\n res_name = None\n resu._name = res_name\n # LaTeX symbol of the output:\n res_latex = None\n if self._latex_name is not None:\n res_latex = self._latex_name + r\"\\left(\"\n for i in range(p-1):\n if args[i]._latex_name is not None:\n res_latex += args[i]._latex_name + \",\"\n else:\n res_latex = None\n break\n if res_latex is not None:\n if args[p-1]._latex_name is not None:\n res_latex += args[p-1]._latex_name + r\"\\right)\"\n else:\n res_latex = None\n resu._latex_name = res_latex\n return resu\n\n def trace(self, pos1=0, pos2=1):\n r\"\"\"\n Trace (contraction) on two slots of the tensor field.\n\n INPUT:\n\n - ``pos1`` -- (default: 0) position of the first index for the\n contraction, with the convention ``pos1=0`` for the first slot\n - ``pos2`` -- (default: 1) position of the second index for the\n contraction, with the same convention as for ``pos1``. The variance\n type of ``pos2`` must be opposite to that of ``pos1``\n\n OUTPUT:\n\n - tensor field resulting from the ``(pos1, pos2)`` contraction\n\n EXAMPLES:\n\n Trace of a type-`(1,1)` tensor field on a 2-dimensional\n non-parallelizable manifold::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U') ; V = M.open_subset('V')\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: c_xy. = U.chart() ; c_uv. = V.chart()\n sage: xy_to_uv = c_xy.transition_map(c_uv, (x+y, x-y),\n ....: intersection_name='W', restrictions1= x>0,\n ....: restrictions2= u+v>0)\n sage: uv_to_xy = xy_to_uv.inverse()\n sage: e_xy = c_xy.frame(); e_uv = c_uv.frame()\n sage: W = U.intersection(V)\n sage: a = M.tensor_field(1,1, name='a')\n sage: a[e_xy,:] = [[1,x], [2,y]]\n sage: a.add_comp_by_continuation(e_uv, W, chart=c_uv)\n sage: s = a.trace() ; s\n Scalar field on the 2-dimensional differentiable manifold M\n sage: s.display()\n M → ℝ\n on U: (x, y) ↦ y + 1\n on V: (u, v) ↦ 1/2*u - 1/2*v + 1\n sage: s == a.trace(0,1) # explicit mention of the positions\n True\n\n Instead of the explicit call to the method :meth:`trace`, one\n may use the index notation with Einstein convention (summation over\n repeated indices); it suffices to pass the indices as a string inside\n square brackets::\n\n sage: a['^i_i']\n Scalar field on the 2-dimensional differentiable manifold M\n sage: a['^i_i'] == s\n True\n\n Any letter can be used to denote the repeated index::\n\n sage: a['^b_b'] == s\n True\n\n Trace of a type-`(1,2)` tensor field::\n\n sage: b = M.tensor_field(1,2, name='b') ; b\n Tensor field b of type (1,2) on the 2-dimensional differentiable\n manifold M\n sage: b[e_xy,:] = [[[0,x+y], [y,0]], [[0,2], [3*x,-2]]]\n sage: b.add_comp_by_continuation(e_uv, W, chart=c_uv) # long time\n sage: s = b.trace(0,1) ; s # contraction on first and second slots\n 1-form on the 2-dimensional differentiable manifold M\n sage: s.display(e_xy)\n 3*x dx + (x + y - 2) dy\n sage: s.display(e_uv) # long time\n (5/4*u + 3/4*v - 1) du + (1/4*u + 3/4*v + 1) dv\n\n Use of the index notation::\n\n sage: b['^k_ki']\n 1-form on the 2-dimensional differentiable manifold M\n sage: b['^k_ki'] == s # long time\n True\n\n Indices not involved in the contraction may be replaced by dots::\n\n sage: b['^k_k.'] == s # long time\n True\n\n The symbol ``^`` may be omitted::\n\n sage: b['k_k.'] == s # long time\n True\n\n LaTeX notations are allowed::\n\n sage: b['^{k}_{ki}'] == s # long time\n True\n\n Contraction on first and third slots::\n\n sage: s = b.trace(0,2) ; s\n 1-form on the 2-dimensional differentiable manifold M\n sage: s.display(e_xy)\n 2 dx + (y - 2) dy\n sage: s.display(e_uv) # long time\n (1/4*u - 1/4*v) du + (-1/4*u + 1/4*v + 2) dv\n\n Use of index notation::\n\n sage: b['^k_.k'] == s # long time\n True\n\n \"\"\"\n # The indices at pos1 and pos2 must be of different types:\n k_con = self._tensor_type[0]\n l_cov = self._tensor_type[1]\n if pos1 < k_con and pos2 < k_con:\n raise IndexError(\"contraction on two contravariant indices is \" +\n \"not allowed\")\n if pos1 >= k_con and pos2 >= k_con:\n raise IndexError(\"contraction on two covariant indices is \" +\n \"not allowed\")\n resu_rst = []\n for rst in self._restrictions.values():\n resu_rst.append(rst.trace(pos1, pos2))\n if (k_con, l_cov) == (1,1):\n # scalar field result\n resu = self._domain.scalar_field()\n all_zero = True\n for rst in resu_rst:\n if rst == 0:\n for chart in rst._domain._atlas:\n resu._express[chart] = 0\n else:\n all_zero = False\n for chart, funct in rst._express.items():\n resu._express[chart] = funct\n if all_zero:\n resu = self._domain._zero_scalar_field\n else:\n # tensor field result\n resu = self._vmodule.tensor((k_con-1, l_cov-1),\n sym=resu_rst[0]._sym, antisym=resu_rst[0]._antisym)\n for rst in resu_rst:\n resu._restrictions[rst._domain] = rst\n return resu\n\n def contract(self, *args: Union[int, TensorField]) -> TensorField:\n r\"\"\"\n Contraction of ``self`` with another tensor field on one or\n more indices.\n\n INPUT:\n\n - ``pos1`` -- positions of the indices in the current tensor field\n involved in the contraction; ``pos1`` must be a sequence of integers,\n with 0 standing for the first index position, 1 for the second one,\n etc.; if ``pos1`` is not provided, a single contraction on the last\n index position of the tensor field is assumed\n - ``other`` -- the tensor field to contract with\n - ``pos2`` -- positions of the indices in ``other`` involved in the\n contraction, with the same conventions as for ``pos1``; if ``pos2``\n is not provided, a single contraction on the first index position of\n ``other`` is assumed\n\n OUTPUT:\n\n - tensor field resulting from the contraction at the positions\n ``pos1`` and ``pos2`` of the tensor field with ``other``\n\n EXAMPLES:\n\n Contractions of a type-`(1,1)` tensor field with a type-`(2,0)`\n one on a 2-dimensional non-parallelizable manifold::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U') ; V = M.open_subset('V')\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: c_xy. = U.chart() ; c_uv. = V.chart()\n sage: transf = c_xy.transition_map(c_uv, (x+y, x-y), intersection_name='W',\n ....: restrictions1= x>0, restrictions2= u+v>0)\n sage: inv = transf.inverse()\n sage: W = U.intersection(V)\n sage: eU = c_xy.frame() ; eV = c_uv.frame()\n sage: a = M.tensor_field(1, 1, {eU: [[1, x], [0, 2]]}, name='a')\n sage: a.add_comp_by_continuation(eV, W, chart=c_uv)\n sage: b = M.tensor_field(2, 0, {eU: [[y, -1], [x+y, 2]]}, name='b')\n sage: b.add_comp_by_continuation(eV, W, chart=c_uv)\n sage: s = a.contract(b) ; s # contraction on last index of a and first one of b\n Tensor field of type (2,0) on the 2-dimensional differentiable\n manifold M\n\n Check 1: components with respect to the manifold's default\n frame (``eU``)::\n\n sage: all(bool(s[i,j] == sum(a[i,k]*b[k,j] for k in M.irange()))\n ....: for i in M.irange() for j in M.irange())\n True\n\n Check 2: components with respect to the frame ``eV``::\n\n sage: all(bool(s[eV,i,j] == sum(a[eV,i,k]*b[eV,k,j]\n ....: for k in M.irange()))\n ....: for i in M.irange() for j in M.irange())\n True\n\n Instead of the explicit call to the method :meth:`contract`, one\n may use the index notation with Einstein convention (summation over\n repeated indices); it suffices to pass the indices as a string inside\n square brackets::\n\n sage: a['^i_k']*b['^kj'] == s\n True\n\n Indices not involved in the contraction may be replaced by dots::\n\n sage: a['^._k']*b['^k.'] == s\n True\n\n LaTeX notation may be used::\n\n sage: a['^{i}_{k}']*b['^{kj}'] == s\n True\n\n Contraction on the last index of ``a`` and last index of ``b``::\n\n sage: s = a.contract(b, 1) ; s\n Tensor field of type (2,0) on the 2-dimensional differentiable\n manifold M\n sage: a['^i_k']*b['^jk'] == s\n True\n\n Contraction on the first index of ``b`` and the last index of ``a``::\n\n sage: s = b.contract(0,a,1) ; s\n Tensor field of type (2,0) on the 2-dimensional differentiable\n manifold M\n sage: b['^ki']*a['^j_k'] == s\n True\n\n The domain of the result is the intersection of the domains of\n the two tensor fields::\n\n sage: aU = a.restrict(U) ; bV = b.restrict(V)\n sage: s = aU.contract(b) ; s\n Tensor field of type (2,0) on the Open subset U of the\n 2-dimensional differentiable manifold M\n sage: s = a.contract(bV) ; s\n Tensor field of type (2,0) on the Open subset V of the\n 2-dimensional differentiable manifold M\n sage: s = aU.contract(bV) ; s\n Tensor field of type (2,0) on the Open subset W of the\n 2-dimensional differentiable manifold M\n sage: s0 = a.contract(b)\n sage: s == s0.restrict(W)\n True\n\n The contraction can be performed on more than one index: ``c`` being a\n type-`(2,2)` tensor, contracting the indices in positions 2 and 3\n of ``c`` with respectively those in positions 0 and 1 of ``b`` is::\n\n sage: c = a*a ; c\n Tensor field of type (2,2) on the 2-dimensional differentiable\n manifold M\n sage: s = c.contract(2,3, b, 0,1) ; s # long time\n Tensor field of type (2,0) on the 2-dimensional differentiable\n manifold M\n\n The same double contraction using index notation::\n\n sage: s == c['^.._kl']*b['^kl'] # long time\n True\n\n The symmetries are either conserved or destroyed by the contraction::\n\n sage: c = c.symmetrize(0,1).antisymmetrize(2,3)\n sage: c.symmetries()\n symmetry: (0, 1); antisymmetry: (2, 3)\n sage: s = b.contract(0, c, 2) ; s\n Tensor field of type (3,1) on the 2-dimensional differentiable\n manifold M\n sage: s.symmetries()\n symmetry: (1, 2); no antisymmetry\n\n Case of a scalar field result::\n\n sage: a = M.one_form({eU: [y, 1+x]}, name='a')\n sage: a.add_comp_by_continuation(eV, W, chart=c_uv)\n sage: b = M.vector_field({eU: [x, y^2]}, name='b')\n sage: b.add_comp_by_continuation(eV, W, chart=c_uv)\n sage: a.display(eU)\n a = y dx + (x + 1) dy\n sage: b.display(eU)\n b = x ∂/∂x + y^2 ∂/∂y\n sage: s = a.contract(b) ; s\n Scalar field on the 2-dimensional differentiable manifold M\n sage: s.display()\n M → ℝ\n on U: (x, y) ↦ (x + 1)*y^2 + x*y\n on V: (u, v) ↦ 1/8*u^3 - 1/8*u*v^2 + 1/8*v^3 + 1/2*u^2 - 1/8*(u^2 + 4*u)*v\n sage: s == a['_i']*b['^i'] # use of index notation\n True\n sage: s == b.contract(a)\n True\n\n Case of a vanishing scalar field result::\n\n sage: b = M.vector_field({eU: [1+x, -y]}, name='b')\n sage: b.add_comp_by_continuation(eV, W, chart=c_uv)\n sage: s = a.contract(b) ; s\n Scalar field zero on the 2-dimensional differentiable manifold M\n sage: s.display()\n zero: M → ℝ\n on U: (x, y) ↦ 0\n on V: (u, v) ↦ 0\n\n \"\"\"\n nargs = len(args)\n for i, arg in enumerate(args):\n if isinstance(arg, TensorField):\n other = arg\n it = i\n break\n else:\n raise TypeError(\"a tensor field must be provided in the \" +\n \"argument list\")\n if it == 0:\n pos1 = (self._tensor_rank - 1,)\n else:\n pos1 = args[:it]\n if it == nargs-1:\n pos2 = (0,)\n else:\n pos2 = args[it+1:]\n ncontr = len(pos1) # number of contractions\n if len(pos2) != ncontr:\n raise IndexError(\"different number of indices for the contraction\")\n if self._domain.is_subset(other._domain):\n if not self._ambient_domain.is_subset(other._ambient_domain):\n raise ValueError(\"incompatible ambient domains for contraction\")\n elif other._domain.is_subset(self._domain):\n if not other._ambient_domain.is_subset(self._ambient_domain):\n raise ValueError(\"incompatible ambient domains for contraction\")\n dom_resu = self._domain.intersection(other._domain)\n ambient_dom_resu = self._ambient_domain.intersection(other._ambient_domain)\n self_r = self.restrict(dom_resu)\n other_r = other.restrict(dom_resu)\n k1, l1 = self._tensor_type\n k2, l2 = other._tensor_type\n tensor_type_resu = (k1 + k2 - ncontr, l1 + l2 - ncontr)\n if ambient_dom_resu.is_manifestly_parallelizable():\n # call of the FreeModuleTensor version:\n args = pos1 + (other_r,) + pos2\n return FreeModuleTensor.contract(self_r, *args)\n com_dom = []\n for dom in self_r._restrictions:\n if dom in other_r._restrictions:\n com_dom.append(dom)\n resu_rst = []\n for dom in com_dom:\n self_rr = self_r._restrictions[dom]\n other_rr = other_r._restrictions[dom]\n args = pos1 + (other_rr,) + pos2\n resu_rst.append(self_rr.contract(*args))\n if tensor_type_resu == (0,0):\n # scalar field result\n resu = dom_resu.scalar_field()\n all_zero = True\n for rst in resu_rst:\n if rst == 0:\n for chart in rst._domain._atlas:\n resu._express[chart] = 0\n else:\n all_zero = False\n for chart, funct in rst._express.items():\n resu._express[chart] = funct\n if all_zero:\n resu = dom_resu._zero_scalar_field\n else:\n # tensor field result\n dest_map = self._vmodule._dest_map\n dest_map_resu = dest_map.restrict(dom_resu,\n subcodomain=ambient_dom_resu)\n vmodule = dom_resu.vector_field_module(dest_map=dest_map_resu)\n\n resu = vmodule.tensor(tensor_type_resu, sym=resu_rst[0]._sym,\n antisym=resu_rst[0]._antisym)\n for rst in resu_rst:\n resu._restrictions[rst._domain] = rst\n return resu\n\n def symmetrize(self, *pos):\n r\"\"\"\n Symmetrization over some arguments.\n\n INPUT:\n\n - ``pos`` -- (default: ``None``) list of argument positions involved\n in the symmetrization (with the convention ``position=0`` for the\n first argument); if ``None``, the symmetrization is performed\n over all the arguments\n\n OUTPUT:\n\n - the symmetrized tensor field (instance of :class:`TensorField`)\n\n EXAMPLES:\n\n Symmetrization of a type-`(0,2)` tensor field on a 2-dimensional\n non-parallelizable manifold::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U') ; V = M.open_subset('V')\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: c_xy. = U.chart() ; c_uv. = V.chart()\n sage: transf = c_xy.transition_map(c_uv, (x+y, x-y), intersection_name='W',\n ....: restrictions1= x>0, restrictions2= u+v>0)\n sage: inv = transf.inverse()\n sage: W = U.intersection(V)\n sage: eU = c_xy.frame() ; eV = c_uv.frame()\n sage: a = M.tensor_field(0,2, {eU: [[1,x], [2,y]]}, name='a')\n sage: a.add_comp_by_continuation(eV, W, chart=c_uv)\n sage: a[eV,:]\n [ 1/4*u + 3/4 -1/4*u + 3/4]\n [ 1/4*v - 1/4 -1/4*v - 1/4]\n sage: s = a.symmetrize() ; s\n Field of symmetric bilinear forms on the 2-dimensional\n differentiable manifold M\n sage: s[eU,:]\n [ 1 1/2*x + 1]\n [1/2*x + 1 y]\n sage: s[eV,:]\n [ 1/4*u + 3/4 -1/8*u + 1/8*v + 1/4]\n [-1/8*u + 1/8*v + 1/4 -1/4*v - 1/4]\n sage: s == a.symmetrize(0,1) # explicit positions\n True\n\n .. SEEALSO::\n\n For more details and examples, see\n :meth:`sage.tensor.modules.free_module_tensor.FreeModuleTensor.symmetrize`.\n\n \"\"\"\n resu_rst = []\n for rst in self._restrictions.values():\n resu_rst.append(rst.symmetrize(*pos))\n resu = self._vmodule.tensor(self._tensor_type, sym=resu_rst[0]._sym,\n antisym=resu_rst[0]._antisym)\n for rst in resu_rst:\n resu._restrictions[rst._domain] = rst\n return resu\n\n def antisymmetrize(self, *pos):\n r\"\"\"\n Antisymmetrization over some arguments.\n\n INPUT:\n\n - ``pos`` -- (default: ``None``) list of argument positions involved\n in the antisymmetrization (with the convention ``position=0`` for\n the first argument); if ``None``, the antisymmetrization is\n performed over all the arguments\n\n OUTPUT:\n\n - the antisymmetrized tensor field (instance of :class:`TensorField`)\n\n EXAMPLES:\n\n Antisymmetrization of a type-`(0,2)` tensor field on a 2-dimensional\n non-parallelizable manifold::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U') ; V = M.open_subset('V')\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: c_xy. = U.chart() ; c_uv. = V.chart()\n sage: transf = c_xy.transition_map(c_uv, (x+y, x-y), intersection_name='W',\n ....: restrictions1= x>0, restrictions2= u+v>0)\n sage: inv = transf.inverse()\n sage: W = U.intersection(V)\n sage: eU = c_xy.frame() ; eV = c_uv.frame()\n sage: a = M.tensor_field(0,2, {eU: [[1,x], [2,y]]}, name='a')\n sage: a.add_comp_by_continuation(eV, W, chart=c_uv)\n sage: a[eV,:]\n [ 1/4*u + 3/4 -1/4*u + 3/4]\n [ 1/4*v - 1/4 -1/4*v - 1/4]\n sage: s = a.antisymmetrize() ; s\n 2-form on the 2-dimensional differentiable manifold M\n sage: s[eU,:]\n [ 0 1/2*x - 1]\n [-1/2*x + 1 0]\n sage: s[eV,:]\n [ 0 -1/8*u - 1/8*v + 1/2]\n [ 1/8*u + 1/8*v - 1/2 0]\n sage: s == a.antisymmetrize(0,1) # explicit positions\n True\n sage: s == a.antisymmetrize(1,0) # the order of positions does not matter\n True\n\n .. SEEALSO::\n\n For more details and examples, see\n :meth:`sage.tensor.modules.free_module_tensor.FreeModuleTensor.antisymmetrize`.\n\n \"\"\"\n resu_rst = []\n for rst in self._restrictions.values():\n resu_rst.append(rst.antisymmetrize(*pos))\n resu = self._vmodule.tensor(self._tensor_type, sym=resu_rst[0]._sym,\n antisym=resu_rst[0]._antisym)\n for rst in resu_rst:\n resu._restrictions[rst._domain] = rst\n return resu\n\n def lie_derivative(self, vector):\n r\"\"\"\n Lie derivative of ``self`` with respect to a vector field.\n\n INPUT:\n\n - ``vector`` -- vector field with respect to which the Lie derivative\n is to be taken\n\n OUTPUT:\n\n - the tensor field that is the Lie derivative of the current tensor\n field with respect to ``vector``\n\n EXAMPLES:\n\n Lie derivative of a type-`(1,1)` tensor field along a vector field on\n a non-parallelizable 2-dimensional manifold::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U') ; V = M.open_subset('V')\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: c_xy. = U.chart() ; c_uv. = V.chart()\n sage: xy_to_uv = c_xy.transition_map(c_uv, (x+y, x-y),\n ....: intersection_name='W', restrictions1= x>0,\n ....: restrictions2= u+v>0)\n sage: uv_to_xy = xy_to_uv.inverse()\n sage: e_xy = c_xy.frame(); e_uv = c_uv.frame()\n sage: t = M.tensor_field(1, 1, {e_xy: [[x, 1], [y, 0]]}, name='t')\n sage: t.add_comp_by_continuation(e_uv, U.intersection(V), c_uv)\n sage: w = M.vector_field({e_xy: [-y, x]}, name='w')\n sage: w.add_comp_by_continuation(e_uv, U.intersection(V), c_uv)\n sage: lt = t.lie_derivative(w); lt\n Tensor field of type (1,1) on the 2-dimensional differentiable\n manifold M\n sage: lt.display(e_xy)\n ∂/∂x⊗dx - x ∂/∂x⊗dy + (-y - 1) ∂/∂y⊗dy\n sage: lt.display(e_uv)\n -1/2*u ∂/∂u⊗du + (1/2*u + 1) ∂/∂u⊗dv + (-1/2*v + 1) ∂/∂v⊗du + 1/2*v ∂/∂v⊗dv\n\n The result is cached::\n\n sage: t.lie_derivative(w) is lt\n True\n\n An alias is ``lie_der``::\n\n sage: t.lie_der(w) is t.lie_derivative(w)\n True\n\n Lie derivative of a vector field::\n\n sage: a = M.vector_field({e_xy: [1-x, x-y]}, name='a')\n sage: a.add_comp_by_continuation(e_uv, U.intersection(V), c_uv)\n sage: a.lie_der(w)\n Vector field on the 2-dimensional differentiable manifold M\n sage: a.lie_der(w).display(e_xy)\n x ∂/∂x + (-y - 1) ∂/∂y\n sage: a.lie_der(w).display(e_uv)\n (v - 1) ∂/∂u + (u + 1) ∂/∂v\n\n The Lie derivative is antisymmetric::\n\n sage: a.lie_der(w) == - w.lie_der(a)\n True\n\n and it coincides with the commutator of the two vector fields::\n\n sage: f = M.scalar_field({c_xy: 3*x-1, c_uv: 3/2*(u+v)-1})\n sage: a.lie_der(w)(f) == w(a(f)) - a(w(f)) # long time\n True\n\n \"\"\"\n if vector._tensor_type != (1,0):\n raise TypeError(\"the argument must be a vector field\")\n\n # The Lie derivative is cached in _lie_derivates while neither\n # the tensor field nor ``vector`` have been modified\n if id(vector) not in self._lie_derivatives:\n # the computation must be performed:\n resu_rst = []\n for dom, rst in self._restrictions.items():\n resu_rst.append(rst.lie_derivative(vector.restrict(dom)))\n resu = self._vmodule.tensor(self._tensor_type,\n sym=resu_rst[0]._sym,\n antisym=resu_rst[0]._antisym)\n for rst in resu_rst:\n resu._restrictions[rst._domain] = rst\n self._lie_derivatives[id(vector)] = (vector, resu)\n vector._lie_der_along_self[id(self)] = self\n return self._lie_derivatives[id(vector)][1]\n\n lie_der = lie_derivative\n\n def at(self, point):\n r\"\"\"\n Value of ``self`` at a point of its domain.\n\n If the current tensor field is\n\n .. MATH::\n\n t:\\ U \\longrightarrow T^{(k,l)} M\n\n associated with the differentiable map\n\n .. MATH::\n\n \\Phi:\\ U \\longrightarrow M,\n\n where `U` and `M` are two manifolds (possibly `U = M` and\n `\\Phi = \\mathrm{Id}_M`), then for any point `p \\in U`, `t(p)`\n is a tensor on the tangent space to `M` at the point `\\Phi(p)`.\n\n INPUT:\n\n - ``point`` -- :class:`~sage.manifolds.point.ManifoldPoint`;\n point `p` in the domain of the tensor field `U`\n\n OUTPUT:\n\n - :class:`~sage.tensor.modules.free_module_tensor.FreeModuleTensor`\n representing the tensor `t(p)` on the tangent vector space\n `T_{\\Phi(p)} M`\n\n EXAMPLES:\n\n Tensor on a tangent space of a non-parallelizable 2-dimensional\n manifold::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U') ; V = M.open_subset('V')\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: c_xy. = U.chart() ; c_uv. = V.chart()\n sage: transf = c_xy.transition_map(c_uv, (x+y, x-y),\n ....: intersection_name='W', restrictions1= x>0,\n ....: restrictions2= u+v>0)\n sage: inv = transf.inverse()\n sage: W = U.intersection(V)\n sage: eU = c_xy.frame() ; eV = c_uv.frame()\n sage: a = M.tensor_field(1, 1, {eU: [[1+y,x], [0,x+y]]}, name='a')\n sage: a.add_comp_by_continuation(eV, W, chart=c_uv)\n sage: a.display(eU)\n a = (y + 1) ∂/∂x⊗dx + x ∂/∂x⊗dy + (x + y) ∂/∂y⊗dy\n sage: a.display(eV)\n a = (u + 1/2) ∂/∂u⊗du + (-1/2*u - 1/2*v + 1/2) ∂/∂u⊗dv\n + 1/2 ∂/∂v⊗du + (1/2*u - 1/2*v + 1/2) ∂/∂v⊗dv\n sage: p = M.point((2,3), chart=c_xy, name='p')\n sage: ap = a.at(p) ; ap\n Type-(1,1) tensor a on the Tangent space at Point p on the\n 2-dimensional differentiable manifold M\n sage: ap.parent()\n Free module of type-(1,1) tensors on the Tangent space at Point p\n on the 2-dimensional differentiable manifold M\n sage: ap.display(eU.at(p))\n a = 4 ∂/∂x⊗dx + 2 ∂/∂x⊗dy + 5 ∂/∂y⊗dy\n sage: ap.display(eV.at(p))\n a = 11/2 ∂/∂u⊗du - 3/2 ∂/∂u⊗dv + 1/2 ∂/∂v⊗du + 7/2 ∂/∂v⊗dv\n sage: p.coord(c_uv) # to check the above expression\n (5, -1)\n\n \"\"\"\n if point not in self._domain:\n raise ValueError(\"the {} is not a point in the \".format(point) +\n \"domain of {}\".format(self))\n for dom, rst in self._restrictions.items():\n if point in dom:\n return rst.at(point)\n\n def up(\n self,\n non_degenerate_form: Union[PseudoRiemannianMetric, SymplecticForm, PoissonTensorField],\n pos: Optional[int] = None,\n ) -> \"TensorField\":\n r\"\"\"\n Compute a dual of the tensor field by raising some index with the\n given tensor field (usually, a pseudo-Riemannian metric, a symplectic form or a Poisson tensor).\n\n If `T` is the tensor field, `(k,l)` its type and `p` the position of a\n covariant index (i.e. `k\\leq p < k+l`), this method called with\n ``pos`` `=p` yields the tensor field `T^\\sharp` of type `(k+1,l-1)`\n whose components are\n\n .. MATH::\n\n (T^\\sharp)^{a_1\\ldots a_{k+1}}_{\\phantom{a_1\\ldots a_{k+1}}\\,\n b_1 \\ldots b_{l-1}} = g^{a_{k+1} i} \\,\n T^{a_1\\ldots a_k}_{\\phantom{a_1\\ldots a_k}\\, b_1 \\ldots b_{p-k}\n \\, i \\, b_{p-k+1}\\ldots b_{l-1}},\n\n `g^{ab}` being the components of the inverse metric or the Poisson tensor, respectively.\n\n The reverse operation is :meth:`TensorField.down`.\n\n INPUT:\n\n - ``non_degenerate_form`` -- non-degenerate form `g`, or a Poisson tensor\n - ``pos`` -- (default: ``None``) position of the index (with the\n convention ``pos=0`` for the first index); if ``None``, the raising\n is performed over all the covariant indices, starting from the first\n one\n\n OUTPUT:\n\n - the tensor field `T^\\sharp` resulting from the index raising\n operation\n\n EXAMPLES:\n\n Raising the index of a 1-form results in a vector field::\n\n sage: M = Manifold(2, 'M', start_index=1)\n sage: c_xy. = M.chart()\n sage: g = M.metric('g')\n sage: g[1,1], g[1,2], g[2,2] = 1+x, x*y, 1-y\n sage: w = M.one_form(-1, 2)\n sage: v = w.up(g) ; v\n Vector field on the 2-dimensional differentiable manifold M\n sage: v.display()\n ((2*x - 1)*y + 1)/(x^2*y^2 + (x + 1)*y - x - 1) ∂/∂x\n - (x*y + 2*x + 2)/(x^2*y^2 + (x + 1)*y - x - 1) ∂/∂y\n sage: ig = g.inverse(); ig[:]\n [ (y - 1)/(x^2*y^2 + (x + 1)*y - x - 1) x*y/(x^2*y^2 + (x + 1)*y - x - 1)]\n [ x*y/(x^2*y^2 + (x + 1)*y - x - 1) -(x + 1)/(x^2*y^2 + (x + 1)*y - x - 1)]\n\n Using the index notation instead of :meth:`up`::\n\n sage: v == ig['^ab']*w['_b']\n True\n\n The reverse operation::\n\n sage: w1 = v.down(g) ; w1\n 1-form on the 2-dimensional differentiable manifold M\n sage: w1.display()\n -dx + 2 dy\n sage: w1 == w\n True\n\n The reverse operation in index notation::\n\n sage: g['_ab']*v['^b'] == w\n True\n\n Raising the indices of a tensor field of type (0,2)::\n\n sage: t = M.tensor_field(0, 2, [[1,2], [3,4]])\n sage: tu0 = t.up(g, 0) ; tu0 # raising the first index\n Tensor field of type (1,1) on the 2-dimensional differentiable\n manifold M\n sage: tu0[:]\n [ ((3*x + 1)*y - 1)/(x^2*y^2 + (x + 1)*y - x - 1) 2*((2*x + 1)*y - 1)/(x^2*y^2 + (x + 1)*y - x - 1)]\n [ (x*y - 3*x - 3)/(x^2*y^2 + (x + 1)*y - x - 1) 2*(x*y - 2*x - 2)/(x^2*y^2 + (x + 1)*y - x - 1)]\n sage: tu0 == ig['^ac']*t['_cb'] # the same operation in index notation\n True\n sage: tuu0 = tu0.up(g) ; tuu0 # the two indices have been raised, starting from the first one\n Tensor field of type (2,0) on the 2-dimensional differentiable\n manifold M\n sage: tuu0 == tu0['^a_c']*ig['^cb'] # the same operation in index notation\n True\n sage: tu1 = t.up(g, 1) ; tu1 # raising the second index\n Tensor field of type (1,1) on the 2-dimensional differentiable\n manifold M\n sage: tu1 == ig['^ac']*t['_bc'] # the same operation in index notation\n True\n sage: tu1[:]\n [((2*x + 1)*y - 1)/(x^2*y^2 + (x + 1)*y - x - 1) ((4*x + 3)*y - 3)/(x^2*y^2 + (x + 1)*y - x - 1)]\n [ (x*y - 2*x - 2)/(x^2*y^2 + (x + 1)*y - x - 1) (3*x*y - 4*x - 4)/(x^2*y^2 + (x + 1)*y - x - 1)]\n sage: tuu1 = tu1.up(g) ; tuu1 # the two indices have been raised, starting from the second one\n Tensor field of type (2,0) on the 2-dimensional differentiable\n manifold M\n sage: tuu1 == tu1['^a_c']*ig['^cb'] # the same operation in index notation\n True\n sage: tuu0 == tuu1 # the order of index raising is important\n False\n sage: tuu = t.up(g) ; tuu # both indices are raised, starting from the first one\n Tensor field of type (2,0) on the 2-dimensional differentiable\n manifold M\n sage: tuu0 == tuu # the same order for index raising has been applied\n True\n sage: tuu1 == tuu # to get tuu1, indices have been raised from the last one, contrary to tuu\n False\n sage: d0tuu = tuu.down(g, 0) ; d0tuu # the first index is lowered again\n Tensor field of type (1,1) on the 2-dimensional differentiable\n manifold M\n sage: dd0tuu = d0tuu.down(g) ; dd0tuu # the second index is then lowered\n Tensor field of type (0,2) on the 2-dimensional differentiable\n manifold M\n sage: d1tuu = tuu.down(g, 1) ; d1tuu # lowering operation, starting from the last index\n Tensor field of type (1,1) on the 2-dimensional differentiable\n manifold M\n sage: dd1tuu = d1tuu.down(g) ; dd1tuu\n Tensor field of type (0,2) on the 2-dimensional differentiable\n manifold M\n sage: ddtuu = tuu.down(g) ; ddtuu # both indices are lowered, starting from the last one\n Tensor field of type (0,2) on the 2-dimensional differentiable\n manifold M\n sage: ddtuu == t # should be true\n True\n sage: dd0tuu == t # not true, because of the order of index lowering to get dd0tuu\n False\n sage: dd1tuu == t # should be true\n True\n\n \"\"\"\n n_con = self._tensor_type[0] # number of contravariant indices = k\n if pos is None:\n result = self\n for p in range(n_con, self._tensor_rank):\n k = result._tensor_type[0]\n result = result.up(non_degenerate_form, k)\n return result\n\n if pos < n_con or pos > self._tensor_rank - 1:\n print(\"pos = {}\".format(pos))\n raise ValueError(\"position out of range\")\n\n from sage.manifolds.differentiable.metric import PseudoRiemannianMetric\n from sage.manifolds.differentiable.symplectic_form import SymplecticForm\n from sage.manifolds.differentiable.poisson_tensor import PoissonTensorField\n\n if isinstance(non_degenerate_form, PseudoRiemannianMetric):\n return self.contract(pos, non_degenerate_form.inverse(), 1)\n elif isinstance(non_degenerate_form, SymplecticForm):\n return self.contract(pos, non_degenerate_form.poisson(), 1)\n elif isinstance(non_degenerate_form, PoissonTensorField):\n return self.contract(pos, non_degenerate_form, 1)\n else:\n raise ValueError(\"The non-degenerate form has to be a metric, a symplectic form or a Poisson tensor field\")\n\n def down(\n self,\n non_degenerate_form: Union[PseudoRiemannianMetric, SymplecticForm],\n pos: Optional[int] = None,\n ) -> TensorField:\n r\"\"\"\n Compute a dual of the tensor field by lowering some index with a\n given non-degenerate form (pseudo-Riemannian metric or symplectic form).\n\n If `T` is the tensor field, `(k,l)` its type and `p` the position of a\n contravariant index (i.e. `0\\leq p < k`), this method called with\n ``pos`` `=p` yields the tensor field `T^\\flat` of type `(k-1,l+1)`\n whose components are\n\n .. MATH::\n\n (T^\\flat)^{a_1\\ldots a_{k-1}}_{\\phantom{a_1\\ldots a_{k-1}}\n \\, b_1 \\ldots b_{l+1}} = g_{i b_1} \\,\n T^{a_1\\ldots a_{p} \\, i \\, a_{p+1}\\ldots a_{k-1}}_{\\phantom{a_1\n \\ldots a_{p} \\, i \\, a_{p+1}\\ldots a_{k-1}}\\, b_2 \\ldots b_{l+1}},\n\n `g_{ab}` being the components of the metric tensor or the symplectic form, respectively.\n\n The reverse operation is :meth:`TensorField.up`.\n\n INPUT:\n\n - ``non_degenerate_form`` -- non-degenerate form `g`\n - ``pos`` -- (default: ``None``) position of the index (with the\n convention ``pos=0`` for the first index); if ``None``, the lowering\n is performed over all the contravariant indices, starting from the\n last one\n\n OUTPUT:\n\n - the tensor field `T^\\flat` resulting from the index lowering\n operation\n\n EXAMPLES:\n\n Lowering the index of a vector field results in a 1-form::\n\n sage: M = Manifold(2, 'M', start_index=1)\n sage: c_xy. = M.chart()\n sage: g = M.metric('g')\n sage: g[1,1], g[1,2], g[2,2] = 1+x, x*y, 1-y\n sage: v = M.vector_field(-1, 2)\n sage: w = v.down(g) ; w\n 1-form on the 2-dimensional differentiable manifold M\n sage: w.display()\n (2*x*y - x - 1) dx + (-(x + 2)*y + 2) dy\n\n Using the index notation instead of :meth:`down`::\n\n sage: w == g['_ab']*v['^b']\n True\n\n The reverse operation::\n\n sage: v1 = w.up(g) ; v1\n Vector field on the 2-dimensional differentiable manifold M\n sage: v1 == v\n True\n\n Lowering the indices of a tensor field of type (2,0)::\n\n sage: t = M.tensor_field(2, 0, [[1,2], [3,4]])\n sage: td0 = t.down(g, 0) ; td0 # lowering the first index\n Tensor field of type (1,1) on the 2-dimensional differentiable\n manifold M\n sage: td0 == g['_ac']*t['^cb'] # the same operation in index notation\n True\n sage: td0[:]\n [ 3*x*y + x + 1 (x - 3)*y + 3]\n [4*x*y + 2*x + 2 2*(x - 2)*y + 4]\n sage: tdd0 = td0.down(g) ; tdd0 # the two indices have been lowered, starting from the first one\n Tensor field of type (0,2) on the 2-dimensional differentiable\n manifold M\n sage: tdd0 == g['_ac']*td0['^c_b'] # the same operation in index notation\n True\n sage: tdd0[:]\n [ 4*x^2*y^2 + x^2 + 5*(x^2 + x)*y + 2*x + 1 2*(x^2 - 2*x)*y^2 + (x^2 + 2*x - 3)*y + 3*x + 3]\n [(3*x^2 - 4*x)*y^2 + (x^2 + 3*x - 2)*y + 2*x + 2 (x^2 - 5*x + 4)*y^2 + (5*x - 8)*y + 4]\n sage: td1 = t.down(g, 1) ; td1 # lowering the second index\n Tensor field of type (1,1) on the 2-dimensional differentiable\n manifold M\n sage: td1 == g['_ac']*t['^bc'] # the same operation in index notation\n True\n sage: td1[:]\n [ 2*x*y + x + 1 (x - 2)*y + 2]\n [4*x*y + 3*x + 3 (3*x - 4)*y + 4]\n sage: tdd1 = td1.down(g) ; tdd1 # the two indices have been lowered, starting from the second one\n Tensor field of type (0,2) on the 2-dimensional differentiable\n manifold M\n sage: tdd1 == g['_ac']*td1['^c_b'] # the same operation in index notation\n True\n sage: tdd1[:]\n [ 4*x^2*y^2 + x^2 + 5*(x^2 + x)*y + 2*x + 1 (3*x^2 - 4*x)*y^2 + (x^2 + 3*x - 2)*y + 2*x + 2]\n [2*(x^2 - 2*x)*y^2 + (x^2 + 2*x - 3)*y + 3*x + 3 (x^2 - 5*x + 4)*y^2 + (5*x - 8)*y + 4]\n sage: tdd1 == tdd0 # the order of index lowering is important\n False\n sage: tdd = t.down(g) ; tdd # both indices are lowered, starting from the last one\n Tensor field of type (0,2) on the 2-dimensional differentiable\n manifold M\n sage: tdd[:]\n [ 4*x^2*y^2 + x^2 + 5*(x^2 + x)*y + 2*x + 1 (3*x^2 - 4*x)*y^2 + (x^2 + 3*x - 2)*y + 2*x + 2]\n [2*(x^2 - 2*x)*y^2 + (x^2 + 2*x - 3)*y + 3*x + 3 (x^2 - 5*x + 4)*y^2 + (5*x - 8)*y + 4]\n sage: tdd0 == tdd # to get tdd0, indices have been lowered from the first one, contrary to tdd\n False\n sage: tdd1 == tdd # the same order for index lowering has been applied\n True\n sage: u0tdd = tdd.up(g, 0) ; u0tdd # the first index is raised again\n Tensor field of type (1,1) on the 2-dimensional differentiable\n manifold M\n sage: uu0tdd = u0tdd.up(g) ; uu0tdd # the second index is then raised\n Tensor field of type (2,0) on the 2-dimensional differentiable\n manifold M\n sage: u1tdd = tdd.up(g, 1) ; u1tdd # raising operation, starting from the last index\n Tensor field of type (1,1) on the 2-dimensional differentiable\n manifold M\n sage: uu1tdd = u1tdd.up(g) ; uu1tdd\n Tensor field of type (2,0) on the 2-dimensional differentiable\n manifold M\n sage: uutdd = tdd.up(g) ; uutdd # both indices are raised, starting from the first one\n Tensor field of type (2,0) on the 2-dimensional differentiable\n manifold M\n sage: uutdd == t # should be true\n True\n sage: uu0tdd == t # should be true\n True\n sage: uu1tdd == t # not true, because of the order of index raising to get uu1tdd\n False\n\n \"\"\"\n n_con = self._tensor_type[0] # number of contravariant indices = k\n if pos is None:\n result = self\n for p in range(n_con):\n k = result._tensor_type[0]\n result = result.down(non_degenerate_form, k - 1)\n return result\n if not isinstance(pos, (int, Integer)):\n raise TypeError(\"the argument 'pos' must be an integer\")\n if pos<0 or pos>=n_con:\n print(\"pos = {}\".format(pos))\n raise ValueError(\"position out of range\")\n return non_degenerate_form.contract(0, self, pos)\n\n def divergence(self, metric=None):\n r\"\"\"\n Return the divergence of ``self`` (with respect to a given\n metric).\n\n The divergence is taken on the *last* index: if\n ``self`` is a tensor field `t` of type `(k,0)` with `k\\geq 1`, the\n divergence of `t` with respect to the metric `g` is the tensor field\n of type `(k-1,0)` defined by\n\n .. MATH::\n\n (\\mathrm{div}\\, t)^{a_1\\ldots a_{k-1}} =\n \\nabla_i t^{a_1\\ldots a_{k-1} i} =\n (\\nabla t)^{a_1\\ldots a_{k-1} i}_{\\phantom{a_1\\ldots a_{k-1} i}\\, i},\n\n where `\\nabla` is the Levi-Civita connection of `g` (cf.\n :class:`~sage.manifolds.differentiable.levi_civita_connection.LeviCivitaConnection`).\n\n This definition is extended to tensor fields of type `(k,l)` with\n `k\\geq 0` and `l\\geq 1`, by raising the last index with the metric `g`:\n `\\mathrm{div}\\, t` is then the tensor field of type `(k,l-1)` defined by\n\n .. MATH::\n\n (\\mathrm{div}\\, t)^{a_1\\ldots a_k}_{\\phantom{a_1\\ldots a_k}\\, b_1\n \\ldots b_{l-1}} = \\nabla_i (g^{ij} t^{a_1\\ldots a_k}_{\\phantom{a_1\n \\ldots a_k}\\, b_1\\ldots b_{l-1} j})\n = (\\nabla t^\\sharp)^{a_1\\ldots a_k i}_{\\phantom{a_1\\ldots a_k i}\\,\n b_1\\ldots b_{l-1} i},\n\n where `t^\\sharp` is the tensor field deduced from `t` by raising the\n last index with the metric `g` (see :meth:`up`).\n\n INPUT:\n\n - ``metric`` -- (default: ``None``) the pseudo-Riemannian metric `g`\n involved in the definition of the divergence; if none is provided,\n the domain of ``self`` is supposed to be endowed with a default\n metric (i.e. is supposed to be pseudo-Riemannian manifold, see\n :class:`~sage.manifolds.differentiable.pseudo_riemannian.PseudoRiemannianManifold`)\n and the latter is used to define the divergence.\n\n OUTPUT:\n\n - instance of either\n :class:`~sage.manifolds.differentiable.scalarfield.DiffScalarField`\n if `(k,l)=(1,0)` (``self`` is a vector field) or `(k,l)=(0,1)`\n (``self`` is a 1-form) or of :class:`TensorField` if `k+l\\geq 2`\n representing the divergence of ``self`` with respect to ``metric``\n\n EXAMPLES:\n\n Divergence of a vector field in the Euclidean plane::\n\n sage: M. = EuclideanSpace()\n sage: v = M.vector_field(x, y, name='v')\n sage: s = v.divergence(); s\n Scalar field div(v) on the Euclidean plane E^2\n sage: s.display()\n div(v): E^2 → ℝ\n (x, y) ↦ 2\n\n A shortcut alias of ``divergence`` is ``div``::\n\n sage: v.div() == s\n True\n\n The function :func:`~sage.manifolds.operators.div` from the\n :mod:`~sage.manifolds.operators` module can be used instead of the\n method :meth:`divergence`::\n\n sage: from sage.manifolds.operators import div\n sage: div(v) == s\n True\n\n The divergence can be taken with respect to a metric tensor that is\n not the default one::\n\n sage: h = M.lorentzian_metric('h')\n sage: h[1,1], h[2,2] = -1, 1/(1+x^2+y^2)\n sage: s = v.div(h); s\n Scalar field div_h(v) on the Euclidean plane E^2\n sage: s.display()\n div_h(v): E^2 → ℝ\n (x, y) ↦ (x^2 + y^2 + 2)/(x^2 + y^2 + 1)\n\n The standard formula\n\n .. MATH::\n\n \\mathrm{div}_h \\, v = \\frac{1}{\\sqrt{|\\det h|}}\n \\frac{\\partial}{\\partial x^i} \\left( \\sqrt{|\\det h|} \\, v^i \\right)\n\n is checked as follows::\n\n sage: sqrth = h.sqrt_abs_det().expr(); sqrth\n 1/sqrt(x^2 + y^2 + 1)\n sage: s == 1/sqrth * sum( (sqrth*v[i]).diff(i) for i in M.irange())\n True\n\n A divergence-free vector::\n\n sage: w = M.vector_field(-y, x, name='w')\n sage: w.div().display()\n div(w): E^2 → ℝ\n (x, y) ↦ 0\n sage: w.div(h).display()\n div_h(w): E^2 → ℝ\n (x, y) ↦ 0\n\n Divergence of a type-``(2,0)`` tensor field::\n\n sage: t = v*w; t\n Tensor field v⊗w of type (2,0) on the Euclidean plane E^2\n sage: s = t.div(); s\n Vector field div(v⊗w) on the Euclidean plane E^2\n sage: s.display()\n div(v⊗w) = -y e_x + x e_y\n\n \"\"\"\n n_con = self._tensor_type[0] # number of contravariant indices = k\n n_cov = self._tensor_type[1] # number of covariant indices = l\n default_metric = metric is None\n if default_metric:\n metric = self._domain.metric()\n nabla = metric.connection()\n if n_cov == 0:\n resu = nabla(self).trace(n_con-1, n_con)\n else:\n tup = self.up(metric, self._tensor_rank-1)\n resu = nabla(tup).trace(n_con, self._tensor_rank)\n if self._name is not None:\n if default_metric:\n resu._name = \"div({})\".format(self._name)\n resu._latex_name = r\"\\mathrm{div}\\left(\" + self._latex_name + \\\n r\"\\right)\"\n else:\n resu._name = \"div_{}({})\".format(metric._name, self._name)\n resu._latex_name = r\"\\mathrm{div}_{\" + metric._latex_name + \\\n r\"}\\left(\" + self._latex_name + r\"\\right)\"\n # The name is propagated to possible restrictions of self:\n for restrict in resu._restrictions.values():\n restrict.set_name(resu._name, latex_name=resu._latex_name)\n return resu\n\n div = divergence\n\n def laplacian(self, metric=None):\n r\"\"\"\n Return the Laplacian of ``self`` with respect to a given\n metric (Laplace-Beltrami operator).\n\n If ``self`` is a tensor field `t` of type `(k,l)`, the Laplacian of `t`\n with respect to the metric `g` is the tensor field of type `(k,l)`\n defined by\n\n .. MATH::\n\n (\\Delta t)^{a_1\\ldots a_k}_{\\phantom{a_1\\ldots a_k}\\,{b_1\\ldots b_k}}\n = \\nabla_i \\nabla^i\n t^{a_1\\ldots a_k}_{\\phantom{a_1\\ldots a_k}\\,{b_1\\ldots b_k}},\n\n where `\\nabla` is the Levi-Civita connection of `g` (cf.\n :class:`~sage.manifolds.differentiable.levi_civita_connection.LeviCivitaConnection`)\n and `\\nabla^i := g^{ij} \\nabla_j`. The operator\n `\\Delta = \\nabla_i \\nabla^i` is called the *Laplace-Beltrami operator*\n of metric `g`.\n\n INPUT:\n\n - ``metric`` -- (default: ``None``) the pseudo-Riemannian metric `g`\n involved in the definition of the Laplacian; if none is provided, the\n domain of ``self`` is supposed to be endowed with a default metric\n (i.e. is supposed to be pseudo-Riemannian manifold, see\n :class:`~sage.manifolds.differentiable.pseudo_riemannian.PseudoRiemannianManifold`)\n and the latter is used to define the Laplacian\n\n OUTPUT:\n\n - instance of :class:`TensorField` representing the Laplacian of\n ``self``\n\n EXAMPLES:\n\n Laplacian of a vector field in the Euclidean plane::\n\n sage: M. = EuclideanSpace()\n sage: v = M.vector_field(x^3 + y^2, x*y, name='v')\n sage: Dv = v.laplacian(); Dv\n Vector field Delta(v) on the Euclidean plane E^2\n sage: Dv.display()\n Delta(v) = (6*x + 2) e_x\n\n The function :func:`~sage.manifolds.operators.laplacian` from the\n :mod:`~sage.manifolds.operators` module can be used instead of the\n method :meth:`laplacian`::\n\n sage: from sage.manifolds.operators import laplacian\n sage: laplacian(v) == Dv\n True\n\n In the present case (Euclidean metric and Cartesian coordinates), the\n components of the Laplacian are the Laplacians of the components::\n\n sage: all(Dv[[i]] == laplacian(v[[i]]) for i in M.irange())\n True\n\n The Laplacian can be taken with respect to a metric tensor that is\n not the default one::\n\n sage: h = M.lorentzian_metric('h')\n sage: h[1,1], h[2,2] = -1, 1+x^2\n sage: Dv = v.laplacian(h); Dv\n Vector field Delta_h(v) on the Euclidean plane E^2\n sage: Dv.display()\n Delta_h(v) = -(8*x^5 - 2*x^4 - x^2*y^2 + 15*x^3 - 4*x^2 + 6*x\n - 2)/(x^4 + 2*x^2 + 1) e_x - 3*x^3*y/(x^4 + 2*x^2 + 1) e_y\n\n \"\"\"\n n_con = self._tensor_type[0] # number of contravariant indices = k\n trank = self._tensor_rank # k + l\n default_metric = metric is None\n if default_metric:\n metric = self._domain.metric()\n nabla = metric.connection()\n tmp = nabla(nabla(self).up(metric, pos=trank))\n resu = tmp.trace(n_con, trank+1)\n if self._name is not None:\n if default_metric:\n resu._name = \"Delta({})\".format(self._name)\n resu._latex_name = r\"\\Delta\\left(\" + self._latex_name + \\\n r\"\\right)\"\n else:\n resu._name = \"Delta_{}({})\".format(metric._name, self._name)\n resu._latex_name = r\"\\Delta_{\" + metric._latex_name + \\\n r\"}\\left(\" + self._latex_name + r\"\\right)\"\n # The name is propagated to possible restrictions of self:\n for restrict in resu._restrictions.values():\n restrict.set_name(resu._name, latex_name=resu._latex_name)\n return resu\n\n def dalembertian(self, metric=None):\n r\"\"\"\n Return the d'Alembertian of ``self`` with respect to a given\n Lorentzian metric.\n\n The *d'Alembertian* of a tensor field `t` with respect to a Lorentzian\n metric `g` is nothing but the Laplace-Beltrami operator of `g` applied\n to `t` (see :meth:`laplacian`); if ``self`` a tensor field `t` of type\n `(k,l)`, the d'Alembertian of `t` with respect to `g` is then the\n tensor field of type `(k,l)` defined by\n\n .. MATH::\n\n (\\Box t)^{a_1\\ldots a_k}_{\\phantom{a_1\\ldots a_k}\\,{b_1\\ldots b_k}}\n = \\nabla_i \\nabla^i\n t^{a_1\\ldots a_k}_{\\phantom{a_1\\ldots a_k}\\,{b_1\\ldots b_k}},\n\n where `\\nabla` is the Levi-Civita connection of `g` (cf.\n :class:`~sage.manifolds.differentiable.levi_civita_connection.LeviCivitaConnection`)\n and `\\nabla^i := g^{ij} \\nabla_j`.\n\n .. NOTE::\n\n If the metric `g` is not Lorentzian, the name *d'Alembertian* is\n not appropriate and one should use :meth:`laplacian` instead.\n\n INPUT:\n\n - ``metric`` -- (default: ``None``) the Lorentzian metric `g`\n involved in the definition of the d'Alembertian; if none is provided,\n the domain of ``self`` is supposed to be endowed with a default\n Lorentzian metric (i.e. is supposed to be Lorentzian manifold, see\n :class:`~sage.manifolds.differentiable.pseudo_riemannian.PseudoRiemannianManifold`)\n and the latter is used to define the d'Alembertian\n\n OUTPUT:\n\n - instance of :class:`TensorField` representing the d'Alembertian of\n ``self``\n\n EXAMPLES:\n\n d'Alembertian of a vector field in Minkowski spacetime, representing\n the electric field of a simple plane electromagnetic wave::\n\n sage: M = Manifold(4, 'M', structure='Lorentzian')\n sage: X. = M.chart()\n sage: g = M.metric()\n sage: g[0,0], g[1,1], g[2,2], g[3,3] = -1, 1, 1, 1\n sage: e = M.vector_field(name='e')\n sage: e[1] = cos(t-z)\n sage: e.display() # plane wave propagating in the z direction\n e = cos(t - z) ∂/∂x\n sage: De = e.dalembertian(); De # long time\n Vector field Box(e) on the 4-dimensional Lorentzian manifold M\n\n The function :func:`~sage.manifolds.operators.dalembertian` from the\n :mod:`~sage.manifolds.operators` module can be used instead of the\n method :meth:`dalembertian`::\n\n sage: from sage.manifolds.operators import dalembertian\n sage: dalembertian(e) == De # long time\n True\n\n We check that the electric field obeys the wave equation::\n\n sage: De.display() # long time\n Box(e) = 0\n\n \"\"\"\n default_metric = metric is None\n if default_metric:\n metric = self._domain.metric()\n nm2 = self._domain.dim() - 2\n if metric.signature() not in [nm2, -nm2]:\n raise TypeError(\"the {} is not a Lorentzian \".format(metric) +\n \"metric; use laplacian() instead\")\n resu = self.laplacian(metric=metric)\n if self._name is not None:\n if default_metric:\n resu._name = \"Box({})\".format(self._name)\n resu._latex_name = r\"\\Box\\left(\" + self._latex_name + \\\n r\"\\right)\"\n else:\n resu._name = \"Box_{}({})\".format(metric._name, self._name)\n resu._latex_name = r\"\\Box_{\" + metric._latex_name + \\\n r\"}\\left(\" + self._latex_name + r\"\\right)\"\n # The name is propagated to possible restrictions of self:\n for restrict in resu._restrictions.values():\n restrict.set_name(resu._name, latex_name=resu._latex_name)\n return resu\n\n def along(self, mapping):\n r\"\"\"\n Return the tensor field deduced from ``self`` via a differentiable map,\n the codomain of which is included in the domain of ``self``.\n\n More precisely, if ``self`` is a tensor field `t` on `M` and if\n `\\Phi: U \\rightarrow M` is a differentiable map from some\n differentiable manifold `U` to `M`, the returned object is\n a tensor field `\\tilde t` along `U` with values on `M` such that\n\n .. MATH::\n\n \\forall p \\in U,\\ \\tilde t(p) = t(\\Phi(p)).\n\n INPUT:\n\n - ``mapping`` -- differentiable map `\\Phi: U \\rightarrow M`\n\n OUTPUT:\n\n - tensor field `\\tilde t` along `U` defined above.\n\n EXAMPLES:\n\n Let us consider the 2-dimensional sphere `S^2`::\n\n sage: M = Manifold(2, 'S^2') # the 2-dimensional sphere S^2\n sage: U = M.open_subset('U') # complement of the North pole\n sage: c_xy. = U.chart() # stereographic coordinates from the North pole\n sage: V = M.open_subset('V') # complement of the South pole\n sage: c_uv. = V.chart() # stereographic coordinates from the South pole\n sage: M.declare_union(U,V) # S^2 is the union of U and V\n sage: xy_to_uv = c_xy.transition_map(c_uv, (x/(x^2+y^2), y/(x^2+y^2)),\n ....: intersection_name='W', restrictions1= x^2+y^2!=0,\n ....: restrictions2= u^2+v^2!=0)\n sage: uv_to_xy = xy_to_uv.inverse()\n sage: W = U.intersection(V)\n\n and the following map from the open interval `(0,5\\pi/2)` to `S^2`,\n the image of it being the great circle `x=0`, `u=0`, which goes through\n the North and South poles::\n\n sage: I. = manifolds.OpenInterval(0, 5*pi/2)\n sage: J = I.open_interval(0, 3*pi/2)\n sage: K = I.open_interval(pi, 5*pi/2)\n sage: c_J = J.canonical_chart(); c_K = K.canonical_chart()\n sage: Phi = I.diff_map(M, {(c_J, c_xy):\n ....: (0, sgn(pi-t)*sqrt((1+cos(t))/(1-cos(t)))),\n ....: (c_K, c_uv):\n ....: (0, sgn(t-2*pi)*sqrt((1-cos(t))/(1+cos(t))))},\n ....: name='Phi')\n\n Let us consider a vector field on `S^2`::\n\n sage: eU = c_xy.frame(); eV = c_uv.frame()\n sage: w = M.vector_field(name='w')\n sage: w[eU,0] = 1\n sage: w.add_comp_by_continuation(eV, W, chart=c_uv)\n sage: w.display(eU)\n w = ∂/∂x\n sage: w.display(eV)\n w = (-u^2 + v^2) ∂/∂u - 2*u*v ∂/∂v\n\n We have then::\n\n sage: wa = w.along(Phi); wa\n Vector field w along the Real interval (0, 5/2*pi) with values on\n the 2-dimensional differentiable manifold S^2\n sage: wa.display(eU.along(Phi))\n w = ∂/∂x\n sage: wa.display(eV.along(Phi))\n w = -(cos(t) - 1)*sgn(-2*pi + t)^2/(cos(t) + 1) ∂/∂u\n\n Some tests::\n\n sage: p = K.an_element()\n sage: wa.at(p) == w.at(Phi(p))\n True\n sage: wa.at(J(4*pi/3)) == wa.at(K(4*pi/3))\n True\n sage: wa.at(I(4*pi/3)) == wa.at(K(4*pi/3))\n True\n sage: wa.at(K(7*pi/4)) == eU[0].at(Phi(I(7*pi/4))) # since eU[0]=∂/∂x\n True\n\n \"\"\"\n dom = self._domain\n if self._ambient_domain is not dom:\n raise ValueError(\"{} is not a tensor field \".format(self) +\n \"with values in the {}\".format(dom))\n if mapping.codomain().is_subset(dom):\n rmapping = mapping\n else:\n rmapping = None\n for doms, rest in mapping._restrictions.items():\n if doms[1].is_subset(dom):\n rmapping = rest\n break\n else:\n raise ValueError(\"the codomain of {} is not \".format(mapping) +\n \"included in the domain of {}\".format(self))\n resu_ambient_domain = rmapping.codomain()\n if resu_ambient_domain.is_manifestly_parallelizable():\n return self.restrict(resu_ambient_domain).along(rmapping)\n dom_resu = rmapping.domain()\n vmodule = dom_resu.vector_field_module(dest_map=rmapping)\n resu = vmodule.tensor(self._tensor_type, name=self._name,\n latex_name=self._latex_name, sym=self._sym,\n antisym=self._antisym)\n for rdom in resu_ambient_domain._parallelizable_parts:\n if rdom in resu_ambient_domain._top_subsets:\n for chart1, chart2 in rmapping._coord_expression:\n if chart2.domain() is rdom:\n dom1 = chart1.domain()\n rrmap = rmapping.restrict(dom1, subcodomain=rdom)\n resu._restrictions[dom1] = self.restrict(rdom).along(rrmap)\n return resu\n\n def set_calc_order(self, symbol, order, truncate=False):\n r\"\"\"\n Trigger a series expansion with respect to a small parameter in\n computations involving the tensor field.\n\n This property is propagated by usual operations. The internal\n representation must be ``SR`` for this to take effect.\n\n If the small parameter is `\\epsilon` and `T` is ``self``, the\n power series expansion to order `n` is\n\n .. MATH::\n\n T = T_0 + \\epsilon T_1 + \\epsilon^2 T_2 + \\cdots + \\epsilon^n T_n\n + O(\\epsilon^{n+1}),\n\n where `T_0, T_1, \\ldots, T_n` are `n+1` tensor fields of the same\n tensor type as ``self`` and do not depend upon `\\epsilon`.\n\n INPUT:\n\n - ``symbol`` -- symbolic variable (the \"small parameter\" `\\epsilon`)\n with respect to which the components of ``self`` are expanded in\n power series\n - ``order`` -- integer; the order `n` of the expansion, defined as the\n degree of the polynomial representing the truncated power series in\n ``symbol``\n - ``truncate`` -- (default: ``False``) determines whether the\n components of ``self`` are replaced by their expansions to the\n given order\n\n EXAMPLES:\n\n Let us consider two vector fields depending on a small parameter `h`\n on a non-parallelizable manifold::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U') ; V = M.open_subset('V')\n sage: M.declare_union(U,V) # M is the union of U and V\n sage: c_xy. = U.chart() ; c_uv. = V.chart()\n sage: transf = c_xy.transition_map(c_uv, (x+y, x-y), intersection_name='W',\n ....: restrictions1= x>0, restrictions2= u+v>0)\n sage: inv = transf.inverse()\n sage: W = U.intersection(V)\n sage: eU = c_xy.frame() ; eV = c_uv.frame()\n sage: a = M.vector_field()\n sage: h = var('h', domain='real')\n sage: a[eU,:] = (cos(h*x), -y)\n sage: a.add_comp_by_continuation(eV, W, chart=c_uv)\n sage: b = M.vector_field()\n sage: b[eU,:] = (exp(h*x), exp(h*y))\n sage: b.add_comp_by_continuation(eV, W, chart=c_uv)\n\n If we set the calculus order on one of the vector fields, any operation\n involving both of them is performed to that order::\n\n sage: a.set_calc_order(h, 2)\n sage: s = a + b\n sage: s[eU,:]\n [h*x + 2, 1/2*h^2*y^2 + h*y - y + 1]\n sage: s[eV,:]\n [1/8*(u^2 - 2*u*v + v^2)*h^2 + h*u - 1/2*u + 1/2*v + 3,\n -1/8*(u^2 - 2*u*v + v^2)*h^2 + h*v + 1/2*u - 1/2*v + 1]\n\n Note that the components of ``a`` have not been affected by the above\n call to ``set_calc_order``::\n\n sage: a[eU,:]\n [cos(h*x), -y]\n sage: a[eV,:]\n [cos(1/2*h*u)*cos(1/2*h*v) - sin(1/2*h*u)*sin(1/2*h*v) - 1/2*u + 1/2*v,\n cos(1/2*h*u)*cos(1/2*h*v) - sin(1/2*h*u)*sin(1/2*h*v) + 1/2*u - 1/2*v]\n\n To have ``set_calc_order`` act on them, set the optional argument\n ``truncate`` to ``True``::\n\n sage: a.set_calc_order(h, 2, truncate=True)\n sage: a[eU,:]\n [-1/2*h^2*x^2 + 1, -y]\n sage: a[eV,:]\n [-1/8*(u^2 + 2*u*v + v^2)*h^2 - 1/2*u + 1/2*v + 1,\n -1/8*(u^2 + 2*u*v + v^2)*h^2 + 1/2*u - 1/2*v + 1]\n\n \"\"\"\n for rst in self._restrictions.values():\n rst.set_calc_order(symbol, order, truncate)\n self._del_derived()\n\n def apply_map(self, fun, frame=None, chart=None,\n keep_other_components=False):\n r\"\"\"\n Apply a function to the coordinate expressions of all components of\n ``self`` in a given vector frame.\n\n This method allows operations like factorization, expansion,\n simplification or substitution to be performed on all components of\n ``self`` in a given vector frame (see examples below).\n\n INPUT:\n\n - ``fun`` -- function to be applied to the coordinate expressions of\n the components\n - ``frame`` -- (default: ``None``) vector frame defining the\n components on which the operation ``fun`` is to be performed; if\n ``None``, the default frame of the domain of ``self`` is assumed\n - ``chart`` -- (default: ``None``) coordinate chart; if specified, the\n operation ``fun`` is performed only on the coordinate expressions\n with respect to ``chart`` of the components w.r.t. ``frame``; if\n ``None``, the operation ``fun`` is performed on all available\n coordinate expressions\n - ``keep_other_components`` -- (default: ``False``) determine whether\n the components with respect to vector frames distinct from ``frame``\n and having the same domain as ``frame`` are kept. If ``fun`` is\n non-destructive, ``keep_other_components`` can be set to ``True``;\n otherwise, it is advised to set it to ``False`` (the default) in\n order to avoid any inconsistency between the various sets of\n components\n\n EXAMPLES:\n\n Factorizing all components in the default frame of a vector field::\n\n sage: M = Manifold(2, 'M')\n sage: X. = M.chart()\n sage: a, b = var('a b')\n sage: v = M.vector_field(x^2 - y^2, a*(b^2 - b)*x)\n sage: v.display()\n (x^2 - y^2) ∂/∂x + (b^2 - b)*a*x ∂/∂y\n sage: v.apply_map(factor)\n sage: v.display()\n (x + y)*(x - y) ∂/∂x + a*(b - 1)*b*x ∂/∂y\n\n Performing a substitution in all components in the default frame::\n\n sage: v.apply_map(lambda f: f.subs({a: 2}))\n sage: v.display()\n (x + y)*(x - y) ∂/∂x + 2*(b - 1)*b*x ∂/∂y\n\n Specifying the vector frame via the argument ``frame``::\n\n sage: P. = M.chart()\n sage: X_to_P = X.transition_map(P, [x + 1, y - 1])\n sage: P_to_X = X_to_P.inverse()\n sage: v.display(P)\n (p^2 - q^2 - 2*p - 2*q) ∂/∂p + (-2*b^2 + 2*(b^2 - b)*p + 2*b) ∂/∂q\n sage: v.apply_map(lambda f: f.subs({b: pi}), frame=P.frame())\n sage: v.display(P)\n (p^2 - q^2 - 2*p - 2*q) ∂/∂p + (2*pi - 2*pi^2 - 2*(pi - pi^2)*p) ∂/∂q\n\n Note that the required operation has been performed in all charts::\n\n sage: v.display(P.frame(), P)\n (p^2 - q^2 - 2*p - 2*q) ∂/∂p + (2*pi - 2*pi^2 - 2*(pi - pi^2)*p) ∂/∂q\n sage: v.display(P.frame(), X)\n (x + y)*(x - y) ∂/∂p + 2*pi*(pi - 1)*x ∂/∂q\n\n By default, the components of ``v`` in frames distinct from the\n specified one have been deleted::\n\n sage: X.frame() in v._components\n False\n\n When requested, they are recomputed by change-of-frame formulas,\n thereby enforcing the consistency between the representations in\n various vector frames. In particular, we can check that the\n substitution of ``b`` by ``pi``, which was asked in ``P.frame()``,\n is effective in ``X.frame()`` as well::\n\n sage: v.display(X.frame(), X)\n (x + y)*(x - y) ∂/∂x + 2*pi*(pi - 1)*x ∂/∂y\n\n When the requested operation does not change the value of the tensor\n field, one can use the keyword argument ``keep_other_components=True``,\n in order to avoid the recomputation of the components in other frames::\n\n sage: v.apply_map(factor, keep_other_components=True)\n sage: v.display()\n (x + y)*(x - y) ∂/∂x + 2*pi*(pi - 1)*x ∂/∂y\n\n The components with respect to ``P.frame()`` have been kept::\n\n sage: P.frame() in v._components\n True\n\n One can restrict the operation to expressions in a given chart, via\n the argument ``chart``::\n\n sage: v.display(X.frame(), P)\n (p + q)*(p - q - 2) ∂/∂x + 2*pi*(pi - 1)*(p - 1) ∂/∂y\n sage: v.apply_map(expand, chart=P)\n sage: v.display(X.frame(), P)\n (p^2 - q^2 - 2*p - 2*q) ∂/∂x + (2*pi + 2*pi^2*p - 2*pi^2 - 2*pi*p) ∂/∂y\n sage: v.display(X.frame(), X)\n (x + y)*(x - y) ∂/∂x + 2*pi*(pi - 1)*x ∂/∂y\n\n \"\"\"\n # The dictionary of components w.r.t. frame:\n if keep_other_components:\n comps = self.comp(frame)._comp\n else:\n comps = self.set_comp(frame)._comp # set_comp() deletes the\n # components in other frames\n if chart:\n for scalar in comps.values():\n scalar.add_expr(fun(scalar.expr(chart=chart)), chart=chart)\n else:\n for scalar in comps.values():\n cfunc_dict = {} # new dict of chart functions in order not to\n # modify scalar._express while looping on it\n for ch, fct in scalar._express.items():\n cfunc_dict[ch] = ch.function(fun(fct.expr()))\n scalar._express = cfunc_dict\n","repo_name":"sagemath/sage-archive-2023-02-01","sub_path":"src/sage/manifolds/differentiable/tensorfield.py","file_name":"tensorfield.py","file_ext":"py","file_size_in_byte":194189,"program_lang":"python","lang":"en","doc_type":"code","stars":2037,"dataset":"github-code","pt":"40"} +{"seq_id":"285738107","text":"import pickle\nimport random\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nimport numpy as np\n\nfrom core.paraphrase.utils import build_tokenizer, seed_everything\nfrom core.models.rnn.rnn_classifier import Collator, \\\n NeuralNet, train_model, test_model\nfrom core.models.rnn.rnn_classifier import TextDataset\n\n\nDATA_FOLDER = \"../../data/\"\nRESULTS_FOLDER = \"../../data/results/\"\n\nHPARAMS = {\n \"msrp\": {\n \"train\": {\n \"lr\": 0.009,\n \"lr_gamma\": 0.95,\n \"lr_step\": 1\n },\n \"fine_tune\": {\n \"lr\": 0.001,\n \"lr_gamma\": 0.8,\n \"lr_step\": 3\n },\n \"transfer_learn\": {\n \"lr\": 0.001,\n \"lr_gamma\": 0.8,\n \"lr_step\": 3\n }\n },\n \"ULPC\": {\n \"train\": {\n \"lr\": 0.01,\n \"lr_gamma\": 0.9,\n \"lr_step\": 1\n },\n \"fine_tune\": {\n \"lr\": 0.002,\n \"lr_gamma\": 0.9,\n \"lr_step\": 3\n },\n \"transfer_learn\": {\n \"lr\": 0.002,\n \"lr_gamma\": 0.9,\n \"lr_step\": 3\n }\n },\n \"children\": {\n \"train\": {\n \"lr\": 0.01,\n \"lr_gamma\": 0.8,\n \"lr_step\": 3\n },\n \"fine_tune\": {\n \"lr\": 0.001,\n \"lr_gamma\": 0.8,\n \"lr_step\": 3\n },\n \"transfer_learn\": {\n \"lr\": 0.001,\n \"lr_gamma\": 0.8,\n \"lr_step\": 3\n }\n }\n}\n\n\ndef pre_process_input(df, metric_c, tokenizer, version=\"ULPC\"):\n offset = 0 if version in [\"msrp\", \"children\"] else 1\n X = df.values[:, [0 + offset, 1 + offset]]\n y_c = df[metric_c].values.reshape(-1, 1)\n\n if version == \"ULPC\" or version == \"msrp\":\n X_train, X_test = X[df['trn_test_val'] == 1], X[df['trn_test_val'] == 3]\n y_c_train, y_c_test = y_c[df['trn_test_val'] == 1].astype(float), y_c[df['trn_test_val'] == 3].astype(\n float)\n elif version == \"children\":\n sources = df[\"Source\"].unique().tolist()\n msk = np.random.rand(len(sources)) < 0.5\n train_sources = [sources[i] for i in range(len(sources)) if msk[i]]\n test_sources = [sources[i] for i in range(len(sources)) if not msk[i]]\n if len([line for line in X if line[0] in train_sources]) < len(\n [line for line in X if line[0] not in train_sources]):\n aux = train_sources\n train_sources = test_sources\n test_sources = aux\n\n train_msk = [X[id][0] in train_sources for id in range(len(X))]\n test_msk = [X[id][0] in test_sources for id in range(len(X))]\n\n X_test = X[test_msk]\n X_train = X[train_msk]\n y_c_test = y_c[test_msk].astype(float)\n y_c_train = y_c[train_msk].astype(float)\n else:\n X_train, X_test = X, X[df['trn_test_val'] == 3]\n y_c_train, y_c_test = y_c.astype(float), y_c[df['trn_test_val'] == 3].astype(float)\n len_pos = len(y_c_train[y_c_train > 0])\n len_neg = len(y_c_train[y_c_train == 0])\n X_train_neg = X_train[(y_c_train == 0)[:, 0]]\n y_c_train_neg = y_c_train[(y_c_train == 0)[:, 0]]\n\n if len_neg < len_pos:\n while len_neg < len_pos:\n sample_id = random.randint(0, len(X_train_neg) - 1)\n X_train = np.append(X_train, [X_train_neg[sample_id, :]], axis=0)\n y_c_train = np.append(y_c_train, [y_c_train_neg[sample_id, :]], axis=0)\n len_neg = len(X_train[(y_c_train == 0)[:, 0]])\n else:\n X_train_pos = X_train[(y_c_train == 1)[:, 0]]\n y_c_train_pos = y_c_train[(y_c_train == 1)[:, 0]]\n while len_neg > len_pos:\n sample_id = random.randint(0, len(X_train_pos) - 1)\n X_train = np.append(X_train, [X_train_pos[sample_id, :]], axis=0)\n y_c_train = np.append(y_c_train, [y_c_train_pos[sample_id, :]], axis=0)\n len_pos = len(X_train[(y_c_train == 1)[:, 0]])\n\n # x_train = [tokenizer.texts_to_sequences([x[i] for x in X_train]) for i in range(1, 3)]\n # x_test = [tokenizer.texts_to_sequences([x[i] for x in X_test]) for i in range(1, 3)]\n\n x_train = [tokenizer.texts_to_sequences([x[i] for x in X_train]) for i in range(2)]\n x_test = [tokenizer.texts_to_sequences([x[i] for x in X_test]) for i in range(2)]\n\n return (x_train, y_c_train), (x_test, y_c_test)\n\n\ndef build_dataloaders(x_train, y_c_train, x_test, y_c_test, num_classes, batch_size=256):\n classes = torch.arange(num_classes).unsqueeze(0)\n\n x_train_lens = [(len(x_train[0][j]), len(x_train[1][j])) for j in range(len(x_train[0]))]\n x_test_lens = [(len(x_test[0][j]), len(x_test[1][j])) for j in range(len(x_test[0]))]\n y_c_train = torch.Tensor(np.array([x for x in y_c_train]))\n y_c_test = torch.Tensor(np.array([x for x in y_c_test]))\n y_c_train = (y_c_train == classes)\n y_c_test = (y_c_test == classes)\n\n train_collate = Collator(percentile=96)\n train_dataset = TextDataset(x_train, x_train_lens, y_c_train)\n train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True, collate_fn=train_collate)\n\n test_collate = Collator(test=False)\n test_dataset = TextDataset(x_test, x_test_lens, y_c_test)\n test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=32, shuffle=False, collate_fn=test_collate)\n return train_loader, test_loader\n\n\ndef train(version=\"children\", initial_version=\"msrp\", mode=\"train\"):\n if version == \"ULPC\":\n df = pd.read_csv(f'{RESULTS_FOLDER}results_paraphrase_train_data.csv', encoding='latin1', sep='\\t')\n X = df.values[:, [1, 2]]\n metric_list = [\n [\"Semantic_completeness\", \"Semantic_completeness_bin\"],\n [\"Paraphrase_quality\", \"Paraphrase_quality_tri\"],\n [\"Paraphrase_quality\", \"Paraphrase_quality_bin\"],\n [\"Syntactic_similarity\", \"Syntactic_similarity_bin\"],\n [\"Lexical_similarity\", \"Lexical_similarity_bin\"]\n ]\n elif version == \"msrp\":\n df = pd.read_csv(f'{RESULTS_FOLDER}results_paraphrase_msrp.csv', encoding='latin1', sep='\\t')\n X = df.values[:, [0, 1]]\n metric_list = [\n [\"Paraphrase_quality\", \"Paraphrase_quality_bin\"],\n ]\n elif version == \"children\" or version == \"adults\":\n df = pd.read_csv(f'{RESULTS_FOLDER}results_paraphrase_{version}.csv', encoding='latin1', sep='\\t')\n df = df[df[\"Paraphrase_quality_tri\"] != 9]\n df = df[df[\"Semantic_completeness_bin\"] != 9]\n X = df.values[:, [0, 1]]\n metric_list = [\n [\"Semantic_completeness\", \"Semantic_completeness_bin\"],\n [\"Paraphrase_quality\", \"Paraphrase_quality_tri\"],\n [\"Syntactic_similarity\", \"Syntactic_similarity_bin\"],\n [\"Lexical_similarity\", \"Lexical_similarity_bin\"]\n ]\n tokenizer, glove_matrix = build_tokenizer(X.reshape(-1).tolist(), f\"nn-{version}\", False, generic_tokenizer=True)\n\n for metric_r, metric_c in metric_list:\n print(\"==========================================\")\n print(f\"============ {metric_c} - {version} - {mode} - ({initial_version if mode == 'transfer_learn' else ''})\")\n print(\"==========================================\")\n\n num_classes = 3\n if metric_c.endswith(\"bin\"):\n num_classes = 2\n\n (x_train, y_c_train), (x_test, y_c_test) = pre_process_input(df, metric_c, tokenizer, version)\n train_loader, test_loader = build_dataloaders(x_train, y_c_train, x_test, y_c_test, num_classes, batch_size=64)\n\n seed_everything(1234)\n\n if mode == \"train\":\n model = NeuralNet(glove_matrix, y_c_train.shape[-1] - 1, len(tokenizer.word_index) + 1,\n num_classes=num_classes)\n elif mode == \"fine_tune\":\n model = pickle.load(open(f\"{RESULTS_FOLDER}best_nn_{metric_c}_{initial_version}.bin\", \"rb\"))\n elif mode == \"transfer_learn\":\n load_metric = \"Paraphrase_quality_bin\" if initial_version != \"children\" else \"Paraphrase_quality_tri\"\n model_old = pickle.load(open(f\"{RESULTS_FOLDER}best_nn_{load_metric}_{initial_version}.bin\", \"rb\"))\n old_state_dict = model_old.state_dict()\n del old_state_dict['linear_out.weight']\n del old_state_dict['linear_out.bias']\n model = NeuralNet(glove_matrix, y_c_train.shape[-1] - 1, len(tokenizer.word_index) + 1,\n num_classes=num_classes)\n model.load_state_dict(old_state_dict, strict=False)\n model.cuda()\n\n if mode != \"train\":\n print(\"Initial validation on train.\")\n test_model(model, train_loader)\n print(\"Initial validation on test\")\n test_model(model, test_loader)\n\n hp = HPARAMS[version][mode]\n title = metric_c\n if mode == \"fine_tune\":\n title = f\"ft_{title}\"\n if mode == \"transfer_learn\":\n title = f\"tl_{title}\"\n working_version = version if mode != \"transfer_learn\" else f\"{initial_version}_to_{version}\"\n test_model(model, test_loader, tokenizer)\n train_model(model, train_loader, test_loader, n_epochs=40, lr=hp[\"lr\"], lr_gamma=hp[\"lr_gamma\"],\n lr_step=hp[\"lr_step\"], loss_fn=nn.BCEWithLogitsLoss(reduction='mean'), title=title,\n version=working_version, path=RESULTS_FOLDER)\n\n\ndef pretrain_generic_tokenizer():\n df_ulpc = pd.read_csv(f'{RESULTS_FOLDER}results_paraphrase_train_data.csv', encoding='latin1', sep='\\t')\n X_ulpc = df_ulpc.values[:, [1, 2]]\n\n df_msrp = pd.read_csv(f'{RESULTS_FOLDER}results_paraphrase_msrp.csv', encoding='latin1', sep='\\t')\n X_msrp = df_msrp.values[:, [0, 1]]\n\n df_children = pd.read_csv(f'{RESULTS_FOLDER}results_paraphrase_children.csv', encoding='latin1', sep='\\t')\n X_children = df_children.values[:, [0, 1]]\n\n X = X_ulpc.reshape(-1).tolist() + X_msrp.reshape(-1).tolist() + X_children.reshape(-1).tolist()\n _, _ = build_tokenizer(X, \"\", True, generic_tokenizer=True)\n\n\nif __name__ == '__main__':\n pretrain_generic_tokenizer()\n train(\"ULPC\", mode=\"train\")\n train(\"children\", initial_version=\"ULPC\", mode=\"fine_tune\")\n # train(\"msrp\", mode=\"train\")\n # train(\"children\", mode=\"train\")\n # train(\"children\", initial_version=\"ULPC\", mode=\"transfer_learn\")\n # train(\"ULPC\", initial_version=\"children\", mode=\"transfer_learn\")\n # train(\"children\", initial_version=\"msrp\", mode=\"transfer_learn\")","repo_name":"readerbench/PASTEL","sub_path":"core/paraphrase/paraphrase_nn.py","file_name":"paraphrase_nn.py","file_ext":"py","file_size_in_byte":10464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"20440851019","text":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n\ndata = pd.read_csv(r'C:\\Users\\Ravi G\\Downloads\\Registration Nav Vishwas - Total.csv')\n\nprint(data['Course of study'])\n\n'''\ninitialising array containing course of each registration\nInitialising variablec containing the number of students in each stream\n'''\ncourse_array = []\nsciences = 0\ncommerce = 0\nmanagement_and_arts = 0\n\n'''\ncleaning the data.\n'''\nfor cell in data['Course of study']:\n cell = str(cell)\n cell = cell.lower()\n cell = cell.replace('.','')\n cell = cell.replace(' ','')\n cell = cell.replace('(','')\n cell = cell.replace(')','')\n course_array.append(cell)\n\n\n\nfor course in course_array:\n if(course.find('bcom') >= 0 or course.find('hba') > 0):\n commerce += 1\n\n elif(course.find('bsc') >=0 or course.find('mecs')>=0 or course.find('btmbc')>=0 ):\n sciences += 1\n\n elif(course.find('ba') >= 0 or course.find('bba')>=0):\n management_and_arts += 1\n\n\n'''\nPlotting the data\n'''\nplot_labels=[\"Sciences\",\"commerce\",\"Management and arts\"]\nparticipation_array = [sciences,commerce,management_and_arts]\nplt.pie(participation_array,labels=plot_labels,autopct='%1.1f%%')\nplt.title('Pie chart of Nav Vishwas registrations out of 235 registrations')\nplt.show()\n","repo_name":"AdityaGuzzu/Python","sub_path":"dept_wise_participation.py","file_name":"dept_wise_participation.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"14825938743","text":"import requests\nimport re\nimport sys\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\ntb = [\t'census-lgbt-demographics-studies', \n\t\t'economic-impact-reports',\n\t\t'marriage-and-couples-rights',\n\t\t'parenting',\n\t\t'discrimination',\n\t\t'transgender-issues',\n\t\t'race-ethnicity',\n\t\t'safe-schools-and-youth',\n\t\t'health-and-hiv-aids',\n\t\t'violence-crime',\n\t\t'immigration',\n\t\t'military-related',\n\t\t'international']\n\nfor cate in tb:\n\tpg = 1\n\tprint(cate)\n\tnum = 0\n\t\n\twhile pg != 0:\n\t\turl = 'https://williamsinstitute.law.ucla.edu/category/research/'+ cate + '/page/' + str(pg)\n\t\thtml = requests.get(url)\n\t\thtml.encoding = 'utf-8'\n\t\tif re.search(r'Page not found', html.text) == None:\n\t\t\tprint(url)\t\t\t\n\t\t\trep_urls = re.findall(r'<h2><a href=\"https://(.*?)\" title', html.text)\n\t\t\tfor rep_url in rep_urls:\n\t\t\t\trep_url = 'https://' + rep_url\n\t\t\t\trep_html = requests.get(rep_url)\n\t\t\t\trep_html.encoding = 'utf-8'\n\t\t\t\trep = []\n\t\t\t\trep.extend(re.findall(r'<h1>(.*?)</h1>', rep_html.text))\n\t\t\t\trep.extend(re.findall(r'<p><strong>By (.*?)</strong><br />', rep_html.text))\n\t\t\t\trep.extend(re.findall(r'<strong>(.*?)</strong></p>', rep_html.text))\n\t\t\t\tfile_name = cate+'.txt'\n\n\t\t\t\twith open(file_name, 'a') as file:\n\t\t\t\t\tfor ele in rep:\n\t\t\t\t\t\tfile.write(ele+'\t')\n\n\t\t\t\tpdf_list = re.findall(r'<a href=\"(.*?).pdf\"', rep_html.text)\n\t\t\t\tfor pdf_url in pdf_list:\n\t\t\t\t\tpdf_url = pdf_url + '.pdf'\n\t\t\t\t\tpdf_name = pdf_url.split('/')[-1]\n\t\t\t\t\ttry:\n\t\t\t\t\t\tpdf_html = requests.get(pdf_url)\n\t\t\t\t\t\twith open(pdf_name, 'wb') as code:\n\t\t\t\t\t\t\tcode.write(pdf_html.content)\n\t\t\t\t\t\twith open(file_name, 'a') as file:\n\t\t\t\t\t\t\tfile.write(pdf_url + '//downloaded\t')\n\t\t\t\t\texcept:\n\t\t\t\t\t\twith open(file_name, 'a') as file:\n\t\t\t\t\t\t\tfile.write(pdf_url + '//downloadfail\t')\n\t\t\t\t\twith open(file_name, 'a') as file:\n\t\t\t\t\t\tfile.write('\\n')\n\t\t\t\tnum = num + 1\n\t\t\t\tprint(str(num))\n\t\t\tpg = pg + 1\n\t\telse:\n\t\t\tpg = 0\n\t\t\t\n\tprint(cate + 'finished!')","repo_name":"showeryhe/williams","sub_path":"威廉姆斯爬虫.py","file_name":"威廉姆斯爬虫.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"4583362810","text":"# 给定一个整数矩阵,找出最长递增路径的长度。\r\n#\r\n# 对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。\r\n#\r\n# 示例 1:\r\n#\r\n# 输入: nums =\r\n# [\r\n# [9,9,4],\r\n# [6,6,8],\r\n# [2,1,1]\r\n# ]\r\n# ���出: 4\r\n# 解释: 最长递增路径为 [1, 2, 6, 9]。\r\n# 示例 2:\r\n#\r\n# 输入: nums =\r\n# [\r\n# [3,4,5],\r\n# [3,2,6],\r\n# [2,2,1]\r\n# ]\r\n# 输出: 4\r\n# 解释: 最长递增路径是 [3, 4, 5, 6]。注意不允许在对角线方向上移动。\r\n\r\nclass Solution:\r\n def longestIncreasingPath(self, matrix: List[List[int]]) -> int:\r\n if not matrix or not matrix[0]: return 0\r\n\r\n row = len(matrix)\r\n col = len(matrix[0])\r\n lookup = [[0] * col for _ in range(row)]\r\n\r\n def dfs(i, j):\r\n if lookup[i][j] != 0:\r\n return lookup[i][j]\r\n\r\n val = matrix[i][j]\r\n lookup[i][j] = 1 + max(\r\n dfs(i + 1, j) if 0 <= i + 1 < row and 0 <= j < col and matrix[i + 1][j] > val else 0,\r\n dfs(i - 1, j) if 0 <= i - 1 < row and 0 <= j < col and matrix[i - 1][j] > val else 0,\r\n dfs(i, j + 1) if 0 <= i < row and 0 <= j + 1 < col and matrix[i][j + 1] > val else 0,\r\n dfs(i, j - 1) if 0 <= i < row and 0 <= j - 1 < col and matrix[i][j - 1] > val else 0,\r\n )\r\n\r\n return lookup[i][j]\r\n\r\n return max(dfs(i, j) for i in range(row) for j in range(col))\r\n\r\n\r\n","repo_name":"z1ming/LeetCode-Notebook","sub_path":"source/Clarification/Matrix/329.矩阵中的最长递增路径.py","file_name":"329.矩阵中的最长递增路径.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"zh","doc_type":"code","stars":54,"dataset":"github-code","pt":"42"} +{"seq_id":"18015105905","text":"# -*- coding = utf-8 -*-\n# @Time : 2022/7/9 15:46\n# @Author : 牧川\n# @File : test_nn.conv.py\n# 卷积的基础用法,主要是2D卷积,所以对二维数组进行计算\nimport torch\nimport torch.nn.functional as F\n\n# 模拟输入图像\ntestInput = torch.tensor([[1, 2, 0, 3, 1],\n [0, 1, 2, 3, 1],\n [1, 2, 1, 0, 0],\n [5, 2, 3, 1, 1],\n [2, 1, 0, 1, 1]])\n# 卷积核\nkernel = torch.tensor([[1, 2, 1],\n [0, 1, 0],\n [2, 1, 0]])\n# conv2需要入参带有channel\n# 自定义的tensor变量只有高和宽,没有channel\n# 需要用reshape变换尺寸(即shape)\ntestInput = torch.reshape(testInput, (1, 1, 5, 5))\nkernel = torch.reshape(kernel, (1, 1, 3, 3))\n\nout = F.conv2d(testInput, kernel, stride=1)\nprint(out)\n\nout2 = F.conv2d(testInput, kernel, stride=1, padding=1)\nprint(out2)","repo_name":"ww1126811502/TrochTest","sub_path":"Torch/test_nn.conv.py","file_name":"test_nn.conv.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"25988868464","text":"# MOVEMENT EQUATIONS:\nimport numpy as np\n\n\ndef odes1(t, x, l, m1, m2, E, V, G, tfin):\n # m1 = 2300 # kg\n r = x[0]\n phi = x[1]\n M = m1+m2\n m = m1*m2/M\n mu = G*M\n\n # define system of equation\n dphiDt = l / (m * r * r)\n aux = 2 / m * (E - V(r, G*m*M) - (l * l) / (2 * m * r * r))\n drDt = -np.sqrt(aux)\n # print('sqrt =', 2 / m * (E - V(r, m) - (l * l) / (2 * m * r * r)))\n e = np.sqrt(1 + E * l * l / (mu * mu * m * m * m))\n\n p = True\n\n if p:\n print('t=', tfin - t)\n print('r=', r)\n print('phi=', phi)\n print('e=', e)\n print('l=', l)\n print('E=', E)\n print('V=', V(r, mu*m))\n print('Veff=', V(r, mu*m) + (l * l) / (2 * m * r * r))\n print('aux=', aux)\n print('=============')\n\n return [drDt, dphiDt]\n\n\ndef odes2(t, x, l, m1, m2, E, V, G, tfin):\n # m1 = 2300 # kg\n m = m1*m2/(m1+m2)\n r = x[0]\n phi = x[1]\n print('t=', t)\n #print('x=', x)\n #print('l=', l)\n #print('m=', m)\n print('E=', E)\n print('V=', V(r, G*m))\n print('V_eff=', V(r, G*m) + (l * l) / (2 * m * r * r))\n print('=============')\n\n # define system of equation\n dphiDr = l / (r*r) * 1 / (np.sqrt(2 * m * (E - V(r, m) - (l * l) )))\n drDt = np.sqrt(2 / m * (E - V(r, G*m) - (l * l) / (2 * m * r * r)))\n #print('sqrt =', 2 / m * (E - V(r, m) - (l * l) / (2 * m * r * r)))\n\n return [drDt, dphiDr]\n\n\ndef odes3(theta, x, h, m1, m2, E, V, G):\n # m1 = 2300 # kg\n u = x[0]\n duDtheta = x[1]\n M = m1+m2\n m = m1*m2/M\n mu = G*M\n dthetaDt = h * (u*u)\n h = dthetaDt/(u*u)\n\n # define system of equation\n d2uDtheta2 = mu/(h*h) - u\n e = np.sqrt(1 + E * h * h / (mu * mu * m))\n\n p = True\n\n if p:\n print('r=', 1/u)\n print('theta=', theta)\n print('e=', e)\n print('l=', h*m)\n print('E=', E)\n print('V=', V(1/u, mu*m))\n print('Veff=', V(1/u, mu*m) + (h*h*m*m) / (2 * m / (u * u)))\n print('=============')\n\n return [duDtheta, d2uDtheta2]\n\n\ndef theoretical_orbit(h, mu, e, theta):\n r = (h*h/mu)/(1+e*np.cos(theta))\n return r","repo_name":"JuanfranZZ/2BodyProblem","sub_path":"dynamics.py","file_name":"dynamics.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"10858293651","text":"\nstudents = [\n {'name': 'John', 'age': 15, 'course': 'python', 'gender': 'Male'},\n {'name': 'Andrew', 'age': 20, 'course': 'javascript', 'gender': 'Male'},\n {'name': 'Marcus', 'age': 25, 'course': 'java', 'gender': 'Male'},\n {'name': 'Agness', 'age': 40, 'course': 'python', 'gender': 'Female'},\n {'name': 'Don', 'age': 42, 'course': 'java', 'gender': 'Male'},\n {'name': 'Michael', 'age': 17, 'course': 'javascript', 'gender': 'Male'},\n {'name': 'Jennifer', 'age': 16, 'course': 'java', 'gender': 'Female'},\n {'name': 'Angela', 'age': 16, 'course': 'python', 'gender': 'Female'},\n {'name': 'Eniston', 'age': 34, 'course': 'java', 'gender': 'Male'},\n {'name': 'Albert', 'age': 33, 'course': 'javascript', 'gender': 'Male'},\n {'name': 'Nash', 'age': 28, 'course': 'python', 'gender': 'Male'},\n {'name': 'Nicolas', 'age': 19, 'course': 'java', 'gender': 'Male'},\n {'name': 'Alexey', 'age': 21, 'course': 'java', 'gender': 'Male'},\n {'name': 'Martin', 'age': 22, 'course': 'python', 'gender': 'Male'},\n {'name': 'Gloria', 'age': 23, 'course': 'java', 'gender': 'Female'},\n {'name': 'Mikel', 'age': 24, 'course': 'python', 'gender': 'Male'},\n {'name': 'Susanne', 'age': 25, 'course': 'javascript', 'gender': 'Female'},\n {'name': 'Stevie', 'age': 26, 'course': 'python', 'gender': 'Male'},\n {'name': 'Mark', 'age': 18, 'course': 'java', 'gender': 'Male'},\n {'name': 'Johnathan', 'age': 15, 'course': 'python', 'gender': 'Male'},\n {'name': 'Aidin', 'age': 20, 'course': 'javascript', 'gender': 'Male'},\n {'name': 'Mirbek', 'age': 25, 'course': 'java', 'gender': 'Male'},\n {'name': 'Aidana', 'age': 40, 'course': 'python', 'gender': 'Female'},\n {'name': 'Atay', 'age': 42, 'course': 'java', 'gender': 'Male'},\n {'name': 'Chyngyz', 'age': 17, 'course': 'javascript', 'gender': 'Male'},\n {'name': 'Aigerim', 'age': 16, 'course': 'java', 'gender': 'Female'},\n {'name': 'Jyldyz', 'age': 16, 'course': 'python', 'gender': 'Female'},\n {'name': 'Emir', 'age': 34, 'course': 'java', 'gender': 'Male'},\n {'name': 'Emirlan', 'age': 12, 'course': 'javascript', 'gender': 'Male'},\n {'name': 'Nursultan', 'age': 13, 'course': 'python', 'gender': 'Male'},\n {'name': 'Aliaskar', 'age': 19, 'course': 'java', 'gender': 'Male'},\n {'name': 'Aktanbek', 'age': 21, 'course': 'java', 'gender': 'Male'},\n {'name': 'Adyl', 'age': 14, 'course': 'python', 'gender': 'Male'},\n {'name': 'Janyl', 'age': 16, 'course': 'python', 'gender': 'Female'},\n {'name': 'Meerim', 'age': 12, 'course': 'javascript', 'gender': 'Female'},\n {'name': 'Sultan', 'age': 13, 'course': 'python', 'gender': 'Male'},\n]\n\n# for course in students:\n# print(course)\n\n#_________________________________3/1_________________________________________--\\\n\nfrom collections import defaultdict\nfrom itertools import groupby\n\ncourses = defaultdict(list)\nfor key, course in groupby(students, lambda i: i[\"course\"]):\n names = (i[\"name\"] for i in course)\n courses[key].extend(names)\n\ncourses = dict(courses)\nprint(\"Курсы:\", courses)\n\n#_______________________3/2_________________________________\n\nnames_age = defaultdict(list)\nfor key, course in groupby(students, lambda i: i[\"name\"]):\n names = (i[\"age\"] for i in course)\n names_age[key].extend(names)\nnames_age = dict(names_age)\nprint(\"Имена и возраст:\", names_age)\n\n#_________________________________________3/3____________________________\n\n\nnames = ['Janyl', 'Nursultan', 'Meerim', 'Emir', 'Susann', 'Marcus', 'Aidin','Aigerim',\n 'Angela', 'Albert', 'Jyldyz', 'Doe', 'Gloria', 'Aliaskar', 'Martin', 'John', 'Andrew', 'Steve',\n 'Johnathan', 'Adyl', 'Chyngyz','Michael', 'Atay', 'Mikkel', 'Agnes', 'Aidana', 'Sultan', 'Nash',\n 'Nicolas', 'Mirbek', 'Aktan', 'Emirlan', 'Jennifer', 'Eniston', 'Alex', 'Mark']\n\ndef func (names, names_age):\n for name in names:\n try:\n print(sum(filter(lambda x: isinstance(x, (int, float)), names_age[name])))\n except KeyError:\n print(\"Такого ключа в словаре не существует\")\nfunc (names, names_age)","repo_name":"Ridzen/Exam-2-","sub_path":"Exam2 task_3.py","file_name":"Exam2 task_3.py","file_ext":"py","file_size_in_byte":4139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"25011795904","text":"\"\"\"\r\nfrom PIL import Image\r\nfrom math import sqrt\r\n\r\n\r\ndef mapValue(value, fromMin, fromMax, toMin, toMax):\r\n return (value - fromMin) * (toMax - toMin) / (fromMax - fromMin) + toMin\r\n\r\n\r\nwidth = 600\r\nheight = 600\r\nimg = Image.new('RGB', (width, height), color=(73, 109, 137))\r\n\r\npixels = img.load() # create the pixel map\r\n\r\niterationLimit = 200\r\ntreshold = 20\r\n\r\nfor y in range(img.size[1]):\r\n for x in range(img.size[0]):\r\n\r\n a = mapValue(x, 0, width, -2, 2)\r\n b = mapValue(y, 0, height, -2, 2)\r\n\r\n c = complex(a, b)\r\n z = 0\r\n\r\n count = 0\r\n while count < iterationLimit:\r\n z = z**2 + c\r\n\r\n if abs(z) > treshold:\r\n break\r\n\r\n count += 1\r\n\r\n bright = mapValue(count, 0, iterationLimit, 0, 1)\r\n bright = mapValue(sqrt(bright), 0, 1, 0, 255)\r\n bright = int(bright)\r\n\r\n if count == iterationLimit:\r\n bright = 0\r\n\r\n pixels[x, y] = (bright, bright, bright)\r\n\r\nimg.show()\r\n\"\"\"\r\n\r\n\r\nimport tkinter\r\nimport turtle\r\nfrom math import sin, cos, pi\r\nfrom random import randint\r\n\r\nroot = tkinter.Tk()\r\ncanvas = tkinter.Canvas(root, width=800, height=800)\r\ncanvas.pack()\r\n\r\nturtleScreen = turtle.TurtleScreen(canvas)\r\nturtleScreen.delay(0)\r\nturtleScreen.colormode(255)\r\n\r\nt = turtle.RawTurtle(turtleScreen)\r\nt.speed(0)\r\n\r\n\r\ndef circle(radius, *args, **kwargs):\r\n t.penup()\r\n t.right(90)\r\n t.forward(radius)\r\n t.left(90)\r\n\r\n t.pendown()\r\n t.circle(radius, *args, **kwargs)\r\n t.penup()\r\n\r\n t.penup()\r\n t.left(90)\r\n t.forward(radius)\r\n t.right(90)\r\n t.pendown()\r\n\r\n\r\ndef fractal(radius=300, steps=4, level=4, maxLevel=None):\r\n if not maxLevel:\r\n maxLevel = level\r\n\r\n if level == 1:\r\n turtleScreen.tracer(0)\r\n t.circle(radius)\r\n turtleScreen.tracer(1)\r\n return\r\n\r\n for angle in range(steps):\r\n if level < maxLevel - 2:\r\n turtleScreen.tracer(0)\r\n\r\n t.circle(radius, 360 // steps)\r\n\r\n if level < maxLevel - 2:\r\n turtleScreen.tracer(1)\r\n\r\n fractal(radius=radius // 2, level=level - 1, maxLevel=maxLevel)\r\n\r\n\r\ndef serpinski_circle(radius=300, level=5, maxLevel=None):\r\n if not maxLevel:\r\n maxLevel = level\r\n\r\n if level == 1:\r\n circle(radius)\r\n return\r\n\r\n if level < maxLevel - 3:\r\n turtleScreen.tracer(0)\r\n\r\n circle(radius)\r\n\r\n # right\r\n t.penup()\r\n t.forward(radius)\r\n t.pendown()\r\n serpinski_circle(radius / 2, level - 1)\r\n\r\n # left\r\n t.penup()\r\n t.backward(radius * 2)\r\n t.pendown()\r\n serpinski_circle(radius / 2, level - 1)\r\n\r\n # up\r\n t.penup()\r\n t.forward(radius)\r\n t.left(90)\r\n t.forward(radius)\r\n t.right(90)\r\n t.pendown()\r\n serpinski_circle(radius / 2, level - 1)\r\n\r\n t.penup()\r\n t.left(90)\r\n t.backward(radius)\r\n t.right(90)\r\n t.pendown()\r\n\r\n if level < maxLevel - 3:\r\n turtleScreen.tracer(1)\r\n\r\n\r\ndef kocho(length, level=6):\r\n if level == 1:\r\n t.fd(length)\r\n else:\r\n kocho(length * 1 / 3, level=level - 1)\r\n t.lt(60)\r\n kocho(length * 1 / 3, level=level - 1)\r\n t.rt(120)\r\n kocho(length * 1 / 3, level=level - 1)\r\n t.lt(60)\r\n kocho(length * 1 / 3, level=level - 1)\r\n\r\n\r\ndef kochoStar(length, level=6, angle=120):\r\n for i in range(360 // angle):\r\n kocho(length, level)\r\n t.rt(angle)\r\n\r\n\r\ndef rings(length, level):\r\n def recursion(length, level):\r\n if level == 0:\r\n t.forward(length)\r\n return\r\n\r\n distance = 10 / 2**(level * 1.75)\r\n recursion(distance, level=level - 1)\r\n recursion(distance, level=level - 1)\r\n\r\n for i in range(5):\r\n t.right(90)\r\n recursion(distance, level=level - 1)\r\n\r\n t.left(90)\r\n recursion(distance, level=level - 1)\r\n\r\n level += 1\r\n distance = 10 / 2**(level * 1.75)\r\n recursion(distance, level=level - 1)\r\n for i in range(3):\r\n t.right(90)\r\n recursion(distance, level=level - 1)\r\n\r\n\r\nRADIUS = 200\r\nmode = 4\r\n\r\nif mode == 0:\r\n t.setpos(0, -300)\r\n t.clear()\r\n fractal(level=6)\r\n\r\n\r\nif mode == 1:\r\n t.setpos(0, 0)\r\n t.clear()\r\n serpinski_circle(RADIUS, level=8)\r\n\r\n\r\nif mode == 2:\r\n t.setpos(-300, 0)\r\n t.clear()\r\n kocho(RADIUS, level=6)\r\n\r\n\r\nif mode == 3:\r\n t.setpos(0, 0)\r\n t.clear()\r\n kochoStar(RADIUS, level=6)\r\n\r\n\r\nif mode == 4:\r\n t.setpos(100, 200)\r\n t.clear()\r\n rings(RADIUS, level=4)\r\n\r\n\r\nroot.mainloop()\r\n","repo_name":"zloutek1/IB111-battleships","sub_path":"fractal/fractal.py","file_name":"fractal.py","file_ext":"py","file_size_in_byte":4557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"17664870468","text":"import heapq\nimport math\nimport random\nimport os\nfrom Variables_Globales import *\n\nglobal contador\ncontador = 1\nclass Nodo_MC:\n def __init__(self,estado,identificador, nodo_padre):\n self.estado = estado\n self.identificador = identificador\n self.nodo_padre = nodo_padre\n self.turn = None\n self.valoracion = 0\n self.n_visitado = 0\n self.nj_ganadas = 0\n self.nj_perdidas = 0\n\n def __lt__(self, otro_nodo):\n return self.valoracion < otro_nodo.valoracion\n\n def __str__(self):\n string = f'Identificador: {self.identificador}\\nValoracion: {self.valoracion}\\n'\n if self.nodo_padre == None:\n string += f'NODO RAIZ'\n else:\n string += f'Nodo Padre: {self.nodo_padre.identificador}'\n string += f'\\nVeces visitado: {self.n_visitado}\\nPartidas Ganadas: {self.nj_ganadas}\\nPartidas Perdidas: {self.nj_perdidas}\\n'\n string += f'Estado: {self.estado}\\n'\n if self.turn == None:\n string += f'Turno: No se sabe el turno'\n else:\n string += f'Turno: {self.turn}'\n return string\n \n def camino_padre(self):\n lista_camino_padre = []\n padre = self.nodo_padre\n while padre != None:\n lista_camino_padre.insert(0, padre)\n padre = padre.nodo_padre\n return lista_camino_padre\n\n\n################################################ SELECCION ############################################################\ndef Seleccion(pila_arbol, lista_sucesores_expandidos):\n nodo_seleccionado = None\n pila_aux = heapq.nlargest(len(pila_arbol), pila_arbol) #Elegimos el nodo de mayor valoracion\n\n lista_sucesores = []\n for i in pila_aux:\n estado = i.estado\n free,gamers,chips,turn, move=LeerESTADO_MovimientoRival(estado) \n lista_sucesores = generarSucesores(estado)\n for l in lista_sucesores.copy(): #Descartamos los sucesores que ya han sido explorados\n if l in lista_sucesores_expandidos:\n lista_sucesores.remove(l)\n if len(lista_sucesores) > 0: #Si tenemos algun sucesor posible en ese nodo, se selecciona\n nodo_seleccionado = i\n nodo_seleccionado.turn = turn\n break\n\n \n return nodo_seleccionado, lista_sucesores\n################################################ SELECCION ############################################################\n\n################################################ EXPANSION ############################################################\ndef Expansion(nodo_seleccionado,lista_sucesores, pila_arbol):\n global contador\n estado_a_expandir = None\n nodo_derrota = None\n resto_nodos = []\n for sucesor in lista_sucesores:\n sucesor = json.dumps(sucesor)\n free,gamers,chips,turn, move=LeerESTADO_MovimientoRival(sucesor)\n if turn == nodo_seleccionado.turn:\n derrota = comprobarVictoria(turn, chips, gamers, free)\n if derrota:\n nodo_derrota = sucesor\n else:\n resto_nodos.append(sucesor)\n else:\n victoria = comprobarVictoria((turn+1)%2, chips, gamers, free)\n if victoria:\n estado_a_expandir = sucesor\n break\n else:\n resto_nodos.append(sucesor)\n\n if estado_a_expandir == None: #No has encontrado ningun sucesor en el que ganes\n if len(resto_nodos)==0:\n estado_a_expandir = nodo_derrota #El unico nodo que generas como sucesor es una derrota\n else:\n estado_a_expandir = random.choice(resto_nodos)\n id = 'NODO: '+ str(contador)\n contador += 1\n nuevo_expandido = Nodo_MC(estado_a_expandir, id, nodo_seleccionado)\n nuevo_expandido.turn = (nodo_seleccionado.turn+1)%2\n heapq.heappush(pila_arbol, nuevo_expandido) \n \n return nuevo_expandido\n################################################ EXPANSION ############################################################\n\n################################################ SIMULACION ############################################################\ndef Simulacion(estado, turno):\n Mov=0\n free, gamers, chips, turn, move = LeerESTADO_MovimientoRival(estado)\n while not comprobarVictoria(turn, chips, gamers, free) and not comprobarVictoria((turn+1)%2,chips, gamers,free ) and Mov<JUGADAS_EMPATE:\n sucesores=generarSucesores(estado)\n if len(sucesores)>0:\n estado=sucesores[int(random.randint(0, len(sucesores)-1))]\n free, gamers, chips, turn, move = LeerESTADO_MovimientoRival(estado)\n Mov+=1\n else:\n break\n \n\n if comprobarVictoria(turno, chips, gamers, free):\n return 1\n elif comprobarVictoria((turno+1)%2, chips, gamers, free): \n return -1\n else: return 0\n################################################ SIMULACION ############################################################\n\n################################################ PROPAGACION ############################################################\ndef Propagacion(pila_nodos, nodo,nodo_raiz, valoracion):\n while nodo != nodo_raiz:\n pila_nodos.remove(nodo)\n nodo.n_visitado += 1\n if int(valoracion) == 1:\n nodo.nj_ganadas += 1\n elif int(valoracion) == -1:\n nodo.nj_perdidas += 1\n\n nodo.valoracion = CalcularValoracionUCT(nodo)\n if nodo.nodo_padre == nodo_raiz:\n nodo.nodo_padre.n_visitado += 1\n pila_nodos.append(nodo)\n nodo = nodo.nodo_padre\n heapq.heapify(pila_nodos)\n################################################ PROPAGACION ############################################################\n\n################################################ BUCLE ############################################################\ndef Bucle(nodo_inicial, turno, veces):\n global contador\n pila_nodos, lista_estados_expandidos = Simulacion_Inicial(nodo_inicial, turno)\n\n for i in range(0, veces):\n nodo_seleccionado, lista_sucesores = Seleccion(pila_nodos, lista_estados_expandidos)\n if nodo_seleccionado == None or lista_sucesores == None: #Si no hay mas sucesores posibles a desarrollar salimos del bucle\n break\n nodo_expandido = Expansion(nodo_seleccionado, lista_sucesores, pila_nodos)\n lista_estados_expandidos.append(nodo_expandido.estado)\n valoracion = Simulacion(nodo_expandido.estado, turno)\n Propagacion(pila_nodos, nodo_expandido, nodo_inicial, valoracion)\n\n # Sacamos de la lista de nodos el sucesor de la raiz con mayor valoracion\n lista_final = []\n for i in pila_nodos:\n if str(i.nodo_padre.identificador) == 'NODO RAIZ':\n lista_final.append(i)\n heapq.heapify(lista_final)\n nodo = heapq.nlargest(1, lista_final)\n nodo = nodo[0]\n\n\n return nodo.estado\n \n################################################ BUCLE ############################################################\n\ndef Simulacion_Inicial(nodo_inicial, turno):\n global contador\n nodo_inicial.turn = turno\n pila_arbol = []\n lista_estados_expandidos = []\n sucesores = generarSucesores(nodo_inicial.estado)\n for sucesor in sucesores:\n id = \"NODO: \"+str(contador)\n contador+=1\n nodo = Nodo_MC(sucesor, id, nodo_inicial)\n lista_estados_expandidos.append(nodo.estado)\n valoracion = Simulacion(nodo.estado, turno)\n nodo.n_visitado += 1\n nodo.turn = (nodo.nodo_padre.turn+1)%2\n nodo.nodo_padre.n_visitado += 1\n if valoracion == 1:\n nodo.nj_ganadas += 1\n nodo.nodo_padre.nj_ganadas += 1\n elif valoracion == -1:\n nodo.nj_perdidas += 1\n nodo.nodo_padre.nj_perdidas += 1\n nodo.valoracion = CalcularValoracionUCT(nodo)\n \n pila_arbol.append(nodo)\n return pila_arbol, lista_estados_expandidos\n\ndef CalcularValoracionUCT(nodo): #El nodo padre toma como valoracion la del mejor de sus hijos (IMPLEMENTARLO)\n UCT = (nodo.nj_ganadas-5*nodo.nj_perdidas)/nodo.n_visitado\n UCT += (2/math.sqrt(2))*(math.sqrt(2*math.log(nodo.nodo_padre.n_visitado, 2)/nodo.n_visitado))\n return UCT\n\n\n","repo_name":"Mohamed11302/Juego-del-molino","sub_path":"Código/arboles_montecarlo/arbol_montecarlo1.py","file_name":"arbol_montecarlo1.py","file_ext":"py","file_size_in_byte":8261,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"30658046723","text":"# Countdown - Create a function that accepts a number as an input. \n# Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element).\n# Example: countdown(5) should return [5,4,3,2,1,0]\ndef countdown(a):\n x=[]\n for i in range(a,-1,-1):\n x.append(i)\n return x\nprint(countdown(5))\n# Print and Return - Create a function that will receive a list with two numbers. \n# Print the first value and return the second.\n# Example: print_and_return([1,2]) should print 1 and return 2\ndef print_and_return(x,y):\n print(x)\n return y\nx=print_and_return(4,5)\nprint(x)\n# First Plus Length - Create a function that accepts a list and returns \n# the sum of the first value in the list plus the list's length.\n# Example: first_plus_length([1,2,3,4,5]) should return 6 (first value: 1 + length: 5)\ndef first_plus_length(x):\n return x[0] + len(x)\na=[5,3,5,7,9]\nprint(first_plus_length(a))\n\n# Values Greater than Second - Write a function that accepts a list and \n# creates a new list containing only the values from the original list that are greater than its 2nd value. \n# Print how many values this is and then return the new list. If the list has less than 2 elements, \n# have the function return False\n# Example: values_greater_than_second([5,2,3,2,1,4]) should print 3 and return [5,3,4]\n# Example: values_greater_than_second([3]) should return False\ndef values_greater_than_second(a):\n if(len(a)<2):\n return False\n else:\n greaTer=0\n x=[]\n for i in range(0,len(a)):\n if(a[i]==a[1]):\n continue\n elif(a[i]>a[1]):\n greaTer+=1\n x.append(a[i])\n print(greaTer)\n return x\nx=[5,2,5,7,4,1]\ny=values_greater_than_second(x)\nprint(y)\n\n# This Length, That Value - Write a function that accepts two integers as parameters: size and value. \n# The function should create and return a list whose length is equal to the given size, \n# and whose values are all the given value.\n# Example: length_and_value(4,7) should return [7,7,7,7]\n# Example: length_and_value(6,2) should return [2,2,2,2,2,2]\ndef length_and_value(s,v):\n x=[]\n for i in range(s):\n x.append(v)\n return x\nprint(length_and_value(4,6))\n","repo_name":"DustinSMac/Dojo-Python","sub_path":"python_fundamental/function_basic2.py","file_name":"function_basic2.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"18418436310","text":"from django.conf.urls import patterns, include, url\nfrom django.conf import settings\nfrom rest_framework import routers\nfrom user2 import views\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nfrom django.contrib.auth.views import login\nfrom django.contrib.auth.forms import AuthenticationForm\n\nfrom rest_framework.urlpatterns import format_suffix_patterns\n\nrouter = routers.DefaultRouter()\nrouter.register(r'users', views.UserViewSet)\nrouter.register(r'wines', views.WineViewSet)\nrouter.register(r'movements', views.MovementViewSet)\nrouter.register(r'containers', views.ContainerViewSet)\nrouter.register(r'bottles', views.BottleViewSet)\n#router.register(r'vinibar', views.VinibarView, base_name='vinibar')\nrouter.register(r'vinibar', views.VinibarViewSet, base_name='vinibar')\nrouter.register(r'vinibarwines', views.VinibarWinesViewSet, base_name='vinibarwines')\nrouter.register(r'ratedwines', views.RatedWinesViewSet, base_name='ratedwines')\nrouter.register(r'rating', views.RatingViewSet, base_name='rating')\n\nurlpatterns = patterns('',\n url(r'^', include(router.urls)),\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n url(r'^admin/', include(admin.site.urls)),\n #url(r'^login/$', views.login, name='login'),\n #url(r'^login/?$','django.contrib.auth.views.login',{'template_name':'', 'authentication_form':AuthenticationForm}),\n # url(r'^$', 'usertest2.views.home', name='home'),\n # url(r'^usertest2/', include('usertest2.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n # url(r'^admin/', include(admin.site.urls)),\n (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), #added for heroku\n)\n\nurlpatterns += patterns('',\n url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token')\n)\n# urlpatterns = format_suffix_patterns(urlpatterns)\n","repo_name":"ronnix/usertest2","sub_path":"usertest2/usertest2/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"73405563965","text":"from elasticsearch import Elasticsearch\nes = Elasticsearch()\nfrom ConfigBackend import *\nimport datetime\n\nclass DatabaseInterface:\n @staticmethod\n def write_client_to_db(client):\n db = PyMySQL.connect(\"localhost\", \"testuser\", \"test123\", client_db_name)\n cursor = db.cursor()\n # Prepare SQL query to INSERT a record into the database.\n sql_insert = \"INSERT INTO %s(CLIENT_ID, INDUSTRIES, CONTACT_EMAIL, CONTACT_PHONE) VALUES (%s, %s, %s, %s)\" % (client_db_name, client.client_id, '$$'.join(client.industries), client.contact_email, client.contact_phone)\n try:\n # Execute the SQL command\n cursor.execute(sql_insert)\n # Commit your changes in the database\n db.commit()\n except:\n # Rollback in case there is any error\n db.rollback()\n # disconnect from server\n db.close()\n\n @staticmethod\n def write_digital_campaign_to_db(campaign_id, location, age_demographic, industries, goals, mpaa_rating, brand_feel, budget, other_info):\n campaign_doc = {}\n campaign_doc['location'] = location\n campaign_doc['age_demographic'] = age_demographic\n campaign_doc['industries'] = industries\n campaign_doc['goals'] = goals\n campaign_doc['mpaa_rating'] = mpaa_rating\n campaign_doc['brand_feel'] = brand_feel\n campaign_doc['budget'] = budget\n campaign_doc['other_info'] = other_info\n campaign_doc['conversions'] = []\n\n res = es.index(\n index=es_campaign_index,\n doc_type=es_campaign_doc_type,\n body=campaign_doc,\n id=campaign_id,\n )\n assert res['result'] == 'created' or res['result'] == 'updated'\n return campaign_id\n\n @staticmethod\n def get_campaign_results_for_client_id(client_id):\n get_campaign_query = {\n \"size\": max_campaigns_to_return,\n \"query\": {\n \"match\": {\n \"goal.client_id\": client_id,\n }\n }\n }\n\n res = es.search(\n index=es_campaign_index,\n doc_type=es_campaign_doc_type,\n body=dict(get_campaign_query),\n )\n results = []\n for doc in res['hits']['hits']:\n results.append(doc['_source'])\n return results\n\n\n\n @staticmethod\n def get_random_influencers(count):\n es_query = {\n \"size\": count,\n \"query\": {\n \"function_score\": {\n \"functions\": [\n {\n \"random_score\": {\n \"seed\": \"1477072619038\"\n }\n }\n ]\n }\n }\n }\n\n res = es.search(\n index=es_index,\n doc_type=es_doc_type,\n body=dict(es_query),\n )\n\n results = []\n for doc in res['hits']['hits']:\n results.append(doc['_source'])\n return results\n\n @staticmethod\n def get_target_url(client_id, campaign_id):\n get_target_url_query = {\n \"size\": 1,\n \"query\": {\n \"match\": {\n \"goal.client_id\": client_id,\n '_id': campaign_id\n }\n }\n }\n\n res = es.search(\n index=es_campaign_index,\n doc_type=es_campaign_doc_type,\n body=dict(get_target_url_query),\n )\n return res['hits']['hits'][0]['goal']['target_url']\n\n\n @staticmethod\n def add_conversion_event(campaign_id, influencer_id):\n #https: // stackoverflow.com / questions / 34728715 / append - to - an - existing - elasticsearch - array - field - using - python?utm_medium = organic & utm_source = google_rich_qa & utm_campaign = google_rich_qa\n es.update(\n index=es_campaign_index,\n doc_type=es_campaign_doc_type,\n id=campaign_id,\n body={\"script\": \"ctx._source.conversions += new_conversion\",\n \"params\": {\n \"new_conversion\": {\n \"timestamp\": datetime.datetime.now().strftime(\"%I:%M%p | %B %d, %Y\"),\n \"influencer_id\": influencer_id\n }\n }\n\n }\n )\n","repo_name":"BroderickHigby/Influencer-tracking","sub_path":"campaigns/Backend/DatabaseInterface.py","file_name":"DatabaseInterface.py","file_ext":"py","file_size_in_byte":4363,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"42"} +{"seq_id":"39600141996","text":"from bs4 import BeautifulSoup\nimport requests\nfrom datetime import date, timedelta\nimport csv\nimport sys\n\n\ndef daterange(start_date, end_date):\n \"\"\"Yields a range of dates to iterate (inluding end).\"\"\"\n for n in range(int((end_date - start_date).days + 1)):\n yield start_date + timedelta(n)\n\n\ndate_args = [int(i) for i in sys.argv[1:]] #YYYY, MM, DD, YYYY, MM, DD\n\nstart_date = date(*date_args[0:3])\nend_date = date(*date_args[3:])\n\n\ndef get_news_from_date_gazeta(cur_date, paginator=1):\n \"\"\"Returns all news titles from GAZETA.SPB.RU from a given date.\"\"\"\n date_url = cur_date.strftime(\"%Y/%m/%d\")\n\n if paginator == 1:\n page_url = \"\"\n else:\n page_url = f\"page/{paginator}/\"\n\n url = f\"https://gazeta.spb.ru/date/{date_url}/{page_url}\"\n page = requests.get(url)\n if page.status_code == 404:\n raise NameError('Page not found.')\n\n soup = BeautifulSoup(page.content, 'html.parser')\n sections = soup.find_all('div', class_=\"news-item\")\n\n cur_titles = []\n for item in sections:\n title = item.find('h3', class_=\"news-item-title\").text.strip()\n cur_titles.append(title)\n\n return cur_titles\n\nwrite_name = f\"./SCRAPED-DATA/gazeta-spb{'-'.join([str(i) for i in date_args])}.csv\"\nwith open(write_name, 'w', newline='') as csvfile:\n news_writer = csv.writer(csvfile, delimiter='\\t', quotechar='\"', \\\n quoting=csv.QUOTE_ALL, skipinitialspace=True)\n news_writer.writerow([\"date\", \"title\"])\n\n for single_date in daterange(start_date, end_date):\n cur_news = []\n for page in range(1, 31):\n try:\n page_news = get_news_from_date_gazeta(single_date, page)\n cur_news.extend(page_news)\n print(f\"Gazeta SPb:\\tNews for {single_date}, page {page} scraped.\")\n except:\n print(f\"Gazeta SPb:\\tPage {page} does not exist. Finishing day {single_date}.\")\n break\n \n for title in cur_news:\n news_writer.writerow([single_date] + [title])\n \n","repo_name":"Dormant512/news4consum","sub_path":"DATA-MINING/PY-SCRIPTS/gazeta_spb_scraper.py","file_name":"gazeta_spb_scraper.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"9749873776","text":"from torch import cuda, bfloat16\nimport transformers\nimport torch\nfrom transformers import StoppingCriteria, StoppingCriteriaList\n\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.chains import RetrievalQA\n\n# define custom stopping criteria object\nclass StopOnTokens(StoppingCriteria):\n def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:\n for stop_ids in stop_token_ids:\n if torch.eq(input_ids[0][-len(stop_ids):], stop_ids).all():\n return True\n return False\n \n\nmodel_id = 'meta-llama/Llama-2-7b-chat-hf'\n\ndevice = f'cuda:{cuda.current_device()}' if cuda.is_available() else 'cpu'\n\n# set quantization configuration to load large model with less GPU memory\n# this requires the `bitsandbytes` library\nbnb_config = transformers.BitsAndBytesConfig(\n load_in_4bit=True,\n bnb_4bit_quant_type='nf4',\n bnb_4bit_use_double_quant=True,\n bnb_4bit_compute_dtype=bfloat16\n)\n\n# begin initializing HF items, you need an access token\nhf_auth = \"your_hugging_face_auth_token\"\nmodel_config = transformers.AutoConfig.from_pretrained(\n model_id,\n use_auth_token=hf_auth,\n cache_dir=\"/mnt/s.shrikant.bhurke/s.shrikant.bhurke/model\"\n)\n\nmodel = transformers.AutoModelForCausalLM.from_pretrained(\n model_id,\n trust_remote_code=True,\n config=model_config,\n quantization_config=bnb_config,\n device_map='auto',\n use_auth_token=hf_auth,\n cache_dir=\"/mnt/s.shrikant.bhurke/s.shrikant.bhurke/model\"\n)\n\n# enable evaluation mode to allow model inference\nmodel.eval()\n\n#print(f\"Model loaded on {device}\")\n\ntokenizer = transformers.AutoTokenizer.from_pretrained(\n model_id,\n use_auth_token=hf_auth\n)\n\nstop_list = ['\\nHuman:', '\\n```\\n']\nstop_token_ids = [tokenizer(x)['input_ids'] for x in stop_list]\nstop_token_ids = [torch.LongTensor(x).to(device) for x in stop_token_ids]\n\nstopping_criteria = StoppingCriteriaList([StopOnTokens()])\n\ngenerate_text = transformers.pipeline(\n model=model, \n tokenizer=tokenizer,\n return_full_text=True, # langchain expects the full text\n task='text-generation',\n # we pass model parameters here too\n stopping_criteria=stopping_criteria, # without this model rambles during chat\n temperature=0.1, # 'randomness' of outputs, 0.0 is the min and 1.0 the max\n max_new_tokens=1000, # max number of tokens to generate in the output\n repetition_penalty=1.1 # without this output begins repeating\n)\n\n# res = generate_text(\"Explain me the difference between Data Lakehouse and Data Warehouse.\")\n# print(res[0][\"generated_text\"])\n\nfrom langchain.llms import HuggingFacePipeline\n\nllm = HuggingFacePipeline(pipeline=generate_text)\n\n# checking again that everything is working fine\n#llm(prompt=\"Explain me the difference between Data Lakehouse and Data Warehouse.\")\n\nfrom langchain.document_loaders import TextLoader\n\nloader = TextLoader(\"./fielname.txt\")\ndocuments = loader.load()\n\nfrom langchain.text_splitter import RecursiveCharacterTextSplitter\n\ntext_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=20)\nall_splits = text_splitter.split_documents(documents)\n\nfrom langchain.embeddings import HuggingFaceEmbeddings\nfrom langchain.vectorstores import FAISS\n\nmodel_name = \"sentence-transformers/all-mpnet-base-v2\"\nmodel_kwargs = {\"device\": \"cuda\"}\n\nembeddings = HuggingFaceEmbeddings(model_name=model_name, model_kwargs=model_kwargs)\n\n# storing embeddings in the vectorstore\nvectorstore = FAISS.from_documents(all_splits, embeddings)\n#vectorstore = FAISS.from_documents(documents, embeddings)\ntemplate = '''Context: {context}\n\nBased on Context that is the chunks of the document provide me the complete text under section given for following question\nQuestion: {question}\n\nThe answer should be from context only do not use general knowledge to answer the query'''\n\nQA_CHAIN_PROMPT = PromptTemplate.from_template(template)\n\nqa_chain = RetrievalQA.from_chain_type(\n llm,\n retriever=vectorstore.as_retriever(),\n chain_type_kwargs={\"prompt\": QA_CHAIN_PROMPT},\n return_source_documents=True\n)\n# qa_chain = RetrievalQA.from_chain_type(\n # llm,\n # retriever=vectorstore.as_retriever(),\n # return_source_documents=True\n# )\n\nquestion = \"Give the section text for 'use' from the given document.Do not modify or summarize the text\"\nresult = qa_chain({\"query\": question})\nprint(\"query\",question)\nprint(\"-------------result\",result)\n\nfrom langchain.chains import ConversationalRetrievalChain\n\nchain = ConversationalRetrievalChain.from_llm(llm, vectorstore.as_retriever(), return_source_documents=True)\n\nchat_history = []\n\nquery = \"Can you give me the address of the leased premises from the document?\"\nresult = chain({\"question\": query, \"chat_history\": chat_history})\n\nprint(\"query\",query)\nprint(\"-------------result\",result['answer'])\n\nquery = \"Give me currency type used in the document?\"\nresult = chain({\"question\": query, \"chat_history\": chat_history})\n\nprint(\"query\",query)\nprint(\"-------------result\",result['answer'])\n\n\nquery = \"give the county name from the document?\"\nresult = chain({\"question\": query, \"chat_history\": chat_history})\n\nprint(\"query\",query)\nprint(\"-------------result\",result['answer'])\n\nquery = \"Could you please extract the content located under the section labeled 'use' in the given document?\"\nresult = chain({\"question\": query, \"chat_history\": chat_history})\nprint(\"query\",query)\nprint(\"-------------result\",result['answer'])\n","repo_name":"ShraddhaBhurke/LLM-models","sub_path":"llama2.py","file_name":"llama2.py","file_ext":"py","file_size_in_byte":5465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"3295980007","text":"import pandas as pd\nimport numpy as np\nimport talib\n\nfrom highcharts import Highstock\n# from IPython.display import HTML\n\nimport os\nimport sys\nsys.path.append(os.path.join(os.path.dirname(__file__), '..'))\n# print(sys.path)\nimport okap\n\nprint(\"arg[0]: {}, arg[1]: {}\".format(sys.argv[0], sys.argv[1]))\ninput_fname = str(sys.argv[1])\n # \"stock-code-list/filterIchimoku.txt\"\n # \"stock-code-list/MACD-over-0.txt\"\n # \"stock-code-list/buy-list.txt\"\n # \"stock-code-list/filter0002.txt\" \n # \"stock-code-list/filterMACD.txt\"\n\n#years = [2021]\nyear = 2021\n# codes = [1301]\n# codes = okap.read_stock_code_list(input_fname)\ndf_codes = pd.read_csv(input_fname)\ncodes = df_codes[\"code\"]\n\n\ndef min_max(in_real):\n min_val = in_real[0]\n max_val = in_real[0]\n # print(in_real[0])\n for price in in_real:\n if min_val > price:\n min_val = price\n if max_val < price:\n max_val = price\n return min_val, max_val\n\ndef ichimoku_cloud(in_real):\n length = len(in_real)\n tenkan = [0] * min(9, length)\n kijun = [0] * min(26, length)\n senkou_a = [0] * min(26, length)\n senkou_b = [0] * min(52, length)\n chikou = [0] * min(26, length)\n\n # print(in_real)\n # print(length)\n # print(tenkan)\n # print(kijun)\n # print(senkou_a)\n # print(senkou_b)\n # print(chikou)\n\n for i in range(len(in_real)):\n if i >= 9:\n # print(in_real[i-9:i])\n min_val, max_val = min_max(in_real[i-9:i])\n tenkan.append((min_val + max_val) / 2)\n if i >= 26:\n # print(in_real[i-26:i])\n min_val, max_val = min_max(in_real[i-26:i])\n kijun.append((min_val + max_val)/2)\n senkou_a.append((tenkan[i] + kijun[i])/2)\n chikou.append(in_real[i-26])\n if i >= 52:\n # print(in_real[i-52:i])\n min_val, max_val = min_max(in_real[i-52:i])\n senkou_b.append((min_val + max_val)/2)\n\n # print(in_real)\n # print(length)\n # print(tenkan)\n # print(kijun)\n # print(senkou_a)\n # print(senkou_b)\n # print(chikou)\n\n senkou_a = ([0] * 26) + senkou_a[:-26]\n senkou_b = ([0] * 26) + senkou_b[:-26]\n return tenkan, kijun, senkou_a, senkou_b, chikou\n\nfor code in codes:\n\n # title = okap.read_title_form_s3(str(code), str(year))\n title = str(code)\n # print(title)\n df = okap.read_df_from_s3(str(code), str(year))\n # if not os.path.isfile(file_name):\n # print(\"file not exist: \", file_name)\n # continue\n \n # データの並びをリバースする\n # df = df.reindex(index=df.index[::-1])\n # df.reset_index(inplace=True, drop=True)\n\n # Ichimoku Cloudを求める\n if len(df.index) >= 9:\n print(\"call ichimoku_cloud\")\n tenkan, kijun, senkou_a, senkou_b, chikou = ichimoku_cloud(df.Close.tolist())\n df['tenkan'] = tenkan\n df['kijun'] = kijun\n df['senkou_a'] = senkou_a\n df['senkou_b'] = senkou_b\n df['chikou'] = chikou\n else:\n df['tenkan'] = 0\n df['kijun'] = 0\n df['senkou_a'] = 0\n df['senkou_b'] = 0\n df['chikou'] = 0\n\n # print(df)\n\n H = Highstock()\n \n r = lambda x: round(x, 2)\n # からのデータフレームを作成\n df_html = df\n # 日付を文字列 year/month/day からdatetime(unix時間)に変換\n df_html[\"Date\"] = pd.to_datetime(df[\"Date\"]).dt.strftime(\"%Y-%m-%d\")\n df_html[\"Date\"] = pd.to_datetime(df[\"Date\"].astype(str), format=\"%Y-%m-%d\")\n # print(df_html)\n # グラフの表示に必要なものだけ選ぶ\n df_html = df_html[['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'senkou_a', 'senkou_b', 'chikou']]\n # print(df_html)\n \n groupingUnits = [\n ['week', [1]], \n ['month', [1, 2, 3, 4, 6]]\n ]\n \n ohlc = [[x[1], r(x[2]), r(x[3]), r(x[4]), r(x[5])] for x in df_html.itertuples()]\n volume = [[x[1], r(x[6])] for x in df_html.itertuples()]\n senkou_a = [[x[1], r(x[7])] for x in df_html.itertuples()]\n senkou_b = [[x[1], r(x[8])] for x in df_html.itertuples()]\n chikou = [[x[1], r(x[9])] for x in df_html.itertuples()]\n \n options = {\n 'chart':{\n 'renderTo':'container'+str(code),\n 'width':400,\n 'height':500\n },\n 'rangeSelector': {\n 'selected': 5\n },\n 'title': {\n 'text': title\n },\n 'yAxis': [\n {\n 'labels': {\n 'align': 'right',\n 'x': -3\n },\n 'title': {\n 'text': 'OHLC'\n },\n 'height': '60%',\n 'lineWidth': 2\n },\n {\n 'labels': {\n 'align': 'right',\n 'x': -3\n },\n 'title': {\n 'text': 'Volume'\n },\n 'top': '65%',\n 'height': '35%',\n 'offset': 0,\n 'lineWidth': 2\n }],\n }\n \n H.add_data_set(ohlc, 'candlestick', str(title), dataGrouping={ 'units': groupingUnits })\n H.add_data_set(volume, 'column', 'Volume', yAxis=1, dataGrouping={ 'units': groupingUnits })\n H.add_data_set(senkou_a, 'line', 'senkou_a', dataGrouping={ 'units': groupingUnits })\n H.add_data_set(senkou_b, 'line', 'senkou_b', dataGrouping={ 'units': groupingUnits })\n H.add_data_set(chikou, 'line', 'chikou', dataGrouping={ 'units': groupingUnits })\n H.set_dict_options(options)\n \n html = '''\n {}\n '''.format(H)\n print(html)\n #display(HTML(html))\n","repo_name":"suzucan2020/opensource-kabu-project","sub_path":"work/chart/IchimokuCloud.py","file_name":"IchimokuCloud.py","file_ext":"py","file_size_in_byte":5604,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"42"} +{"seq_id":"39281533050","text":"from __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nimport datetime\nimport json\nimport time\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible.module_utils.urls import open_url\nfrom cohesity_management_sdk.cohesity_client import CohesityClient\nfrom cohesity_management_sdk.exceptions.api_exception import APIException\nfrom cohesity_management_sdk.models.delete_protection_job_param import DeleteProtectionJobParam\nfrom cohesity_management_sdk.models.cancel_protection_job_run_param import CancelProtectionJobRunParam\nfrom cohesity_management_sdk.models.protection_job_request_body import ProtectionJobRequestBody\nfrom cohesity_management_sdk.models.run_protection_job_param import RunProtectionJobParam\n\ntry:\n # => When unit testing, we need to look in the correct location however, when run via ansible,\n # => the expectation is that the modules will live under ansible.\n from module_utils.storage.cohesity.cohesity_auth import get__cohesity_auth__token\n from module_utils.storage.cohesity.cohesity_hints import get_cohesity_client\n from module_utils.storage.cohesity.cohesity_utilities import cohesity_common_argument_spec, raise__cohesity_exception__handler, REQUEST_TIMEOUT\nexcept Exception as e:\n from ansible.module_utils.storage.cohesity.cohesity_auth import get__cohesity_auth__token\n from ansible.module_utils.storage.cohesity.cohesity_hints import get_cohesity_client\n from ansible.module_utils.storage.cohesity.cohesity_utilities import cohesity_common_argument_spec, raise__cohesity_exception__handler, REQUEST_TIMEOUT\n\nANSIBLE_METADATA = {\n 'metadata_version': '1.0',\n 'supported_by': 'community',\n 'status': ['preview']\n}\n\n\n\nclass ParameterViolation(Exception):\n pass\n\n\nclass ProtectionException(Exception):\n pass\n\n\ndef create_recover_job(module, token, database_info):\n '''\n '''\n # Fetch latest successful run id.\n job_run_id = None\n action = 'kRecoverApp'\n vm_action='kRecoverVMs'\n job_id = database_info['vmDocument']['objectId']['jobId']\n resp = cohesity_client.protection_runs.get_protection_runs(job_id=job_id)\n if not resp:\n module.exit_json(msg='Job %s is currently not available.' % job_id)\n\n for job in resp:\n status = job.backup_run.status\n if status == 'kSuccess':\n job_run_id = job.backup_run.job_run_id\n start_time = job.backup_run.stats.start_time_usecs\n if not job_run_id:\n module.exit_json(msg='No successful run available for job %s.' % job_id)\n\n owner_object = dict(jobUid=database_info['vmDocument']['objectId']['jobUid'],\n jobId=database_info['vmDocument']['objectId']['jobId'],\n jobInstanceId=job_run_id,\n startTimeUsecs=start_time,\n entity=dict(id=database_info['vmDocument']['objectId']['entity']['parentId']))\n oracle_db_config = dict(controlFilePathVec=[],\n enableArchiveLogMode=True,\n redoLogConf=dict(\n groupMemberVec=[],\n memberPrefix='redo',\n sizeMb=20),\n fraSizeMb=module.params.get('fra_size_mb'))\n\n # Alternate location params.\n alternate_location_params = None\n server = module.params.get('cluster') \n clone_app_view = module.params.get('clone_app_view')\n source_db = module.params.get('source_db') \n source_server = module.params.get('source_server') \n validate_certs = module.params.get('validate_certs') \n target_db = newDatabaseName=module.params.get('target_db') \n target_server = newDatabaseName=module.params.get('target_server')\n oracle_restore_params = dict(captureTailLogs=False)\n \n if clone_app_view:\n action = 'kCloneAppView'\n vm_action = 'kCloneVMs'\n oracle_restore_params['oracleCloneAppViewParamsVec'] = [dict()]\n\n elif source_server != target_server or source_db != target_db:\n alternate_location_params = dict(newDatabaseName=module.params.get('target_db'),\n homeDir=module.params.get('oracle_home'),\n baseDir=module.params.get('oracle_base'),\n oracleDBConfig=oracle_db_config,\n databaseFileDestination=module.params.get('oracle_home'))\n oracle_restore_params['alternateLocationParams'] = alternate_location_params\n restore_obj_vec = dict(appEntity=database_info['vmDocument']['objectId']['entity'],\n restoreParams=dict(oracleRestoreParams=oracle_restore_params))\n owner_restore_info = dict(ownerObject=owner_object,\n ownerRestoreParams=dict(action=vm_action),\n performRestore=False)\n\n body = dict(name=module.params.get('task_name'),\n action=action,\n restoreAppParams=dict(type=19,\n ownerRestoreInfo=owner_restore_info,\n restoreAppObjectVec=[restore_obj_vec]))\n try:\n uri = 'https://' + server + '/irisservices/api/v1/recoverApplication'\n headers = {'Accept': 'application/json',\n 'Authorization': 'Bearer ' + token}\n response = open_url(url=uri,data=json.dumps(body), method='POST', headers=headers,\n validate_certs=validate_certs, timeout=REQUEST_TIMEOUT)\n\n response = json.loads(response.read())\n return response\n except Exception as err:\n module.fail_json(msg='Error while recovery task creation, error message: \"%s\".' % err)\n\n\ndef check_for_status(module, task_id):\n try:\n while True:\n resp = cohesity_client.restore_tasks.get_restore_tasks(task_ids=task_id)\n if not resp:\n raise Exception('Recovery tasks not available')\n status = resp[0].status\n if status in ['kCancelled', 'kFinished']:\n return status == 'kFinished'\n except Exception as err:\n module.exit_json(msg=err)\n\n\ndef search_for_database(token, module):\n '''\n '''\n server = module.params.get('cluster') \n sourcedb = module.params.get('source_db') \n source_server = module.params.get('source_server') \n validate_certs = module.params.get('validate_certs') \n try:\n uri = 'https://' + server + '/irisservices/api/v1/searchvms?entityTypes=kOracle&vmName=%s' % sourcedb\n headers = {'Accept': 'application/json',\n 'Authorization': 'Bearer ' + token}\n response = open_url(url=uri, method='GET', headers=headers,\n validate_certs=validate_certs, timeout=REQUEST_TIMEOUT)\n\n response = json.loads(response.read())\n if not response:\n raise Exception('Source database %s not available.' % sourcedb)\n vms = response['vms']\n snapshot_timesecs = 0\n search_info = ''\n for vm in vms:\n time_secs = vm['vmDocument']['versions'][0]['snapshotTimestampUsecs']\n if source_server in vm['vmDocument']['objectAliases'] and time_secs > snapshot_timesecs:\n snapshot_timesecs = time_secs\n search_info = vm\n if not search_info:\n raise Exception(\n 'Source database %s not available in source %s.' % sourcedb, source_server)\n return search_info\n except Exception as err:\n module.fail_json(msg=str(err))\n\n\ndef main():\n # => Load the default arguments including those specific to the Cohesity Protection Jobs.\n argument_spec = cohesity_common_argument_spec()\n argument_spec.update(\n dict(\n task_name=dict(type=str),\n source_db=dict(type=str, required=True),\n source_server=dict(type=str, required=True),\n target_db=dict(type=str, required=True),\n target_server=dict(type=str, required=True),\n oracle_home=dict(type=str, required=True),\n oracle_base=dict(type=str, required=True),\n oracle_data=dict(type=str, required=True),\n channels=dict(type=str, required=False),\n control_file=dict(type=str, default=''),\n redo_log_path=dict(type=str, default=''),\n audit_path=dict(type=str, default=''),\n diag_path=dict(type=str, default=''),\n fra_path=dict(type=str, default=''),\n fra_size_mb=dict(type=int, default=2048),\n bct_file=dict(type=str, default=''),\n log_time=dict(type=str, default=''),\n clone_app_view=dict(type=bool, default=False),\n overwrite=dict(type=bool, default=False),\n no_recovery=dict(type=bool, default=False)\n )\n )\n\n # => Create a new module object\n module = AnsibleModule(argument_spec=argument_spec,\n supports_check_mode=True)\n global cohesity_client\n cohesity_client = get_cohesity_client(module)\n\n token = get__cohesity_auth__token(module)\n database_info = search_for_database(token, module)\n resp = create_recover_job(module, token, database_info)\n # Check for restore task status.\n task_id = resp['restoreTask']['performRestoreTaskState']['base']['taskId']\n status = check_for_status(module, task_id)\n if status == False:\n msg = 'Error occured during task recovery.'\n module.fail_json(msg=msg)\n\n results = dict(\n changed=True,\n msg = 'Successfully created restore task \"%s\"' % module.params.get('task_name')\n )\n module.exit_json(**results)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"cohesity/cohesity-ansible-role","sub_path":"library/cohesity_oracle_restore.py","file_name":"cohesity_oracle_restore.py","file_ext":"py","file_size_in_byte":9730,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"42"} +{"seq_id":"37180772173","text":"import numpy as np\nimport xarray as xr\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler\n\ndef loadData(files, variables, get_PS_times=False):\n \"\"\"\n Function to load in data from NETCDF files. Searches through file for specified variables to extract \n into a numpy array.\n Args:\n files (list): list of file names/locations\n variables (list): list of variable names to extract (lat should always be last if used!)\n get_PS_times (bool): whether to return surface pressure and array of times.\n Returns:\n data_dict (dict): dictionary containing requested raw data as numpy arrays.\n PS (numpy array): array of surface pressure values, for use when exporting ML data back to\n NETCDF files.\n times (numpy array): array of time values, for use when exporting ML data back to NETCDF files\n Notes:\n If requesting 'lat' as variable, must be last in 'variable' list..\n \"\"\"\n data_dict = {}\n for jf, f in enumerate(files):\n dataset = xr.open_dataset(f)\n data = {}\n for ivar, var in enumerate(variables):\n if var == 'P':\n data[var] = calcP(dataset['P0'].values,\n dataset['PS'].values,\n dataset['hyam'].values,\n dataset['hybm'].values,\n dataset.time.size,\n dataset.lat.size,\n dataset.lon.size,\n dataset.lev.size)\n elif var == 'Qr': # Must be after P, T, Q in variables list\n data[var] = calcQr(data['P'],data['T'],dataset['Q'].values)\n else:\n data[var] = dataset[var].values\n if jf == 0:\n data_dict[var] = data[var]\n PS = np.empty((dataset.time.size,1,dataset.lat.size,dataset.lon.size))\n PS[:,0,:,:] = dataset['PS'].values\n times = dataset['time'].values\n else:\n if var != 'lat':\n data_dict[var] = np.concatenate((data_dict[var],data[var]))\n ps = np.empty((dataset.time.size,1,dataset.lat.size,dataset.lon.size))\n ps[:,0,:,:] = dataset['PS'].values\n PS = np.concatenate((PS,ps))\n times = np.concatenate((times,dataset['time'].values))\n if get_PS_times:\n return data_dict, PS, times\n else:\n return data_dict\n\ndef calcQr(P,T,Q):\n \"\"\"\n Calculates and returns an array of the relative humidity field.\n \"\"\"\n eps = 0.622\n T0 = 273.16\n e0 = 610.78\n L = 2.5e6\n Rv = 461.5\n Qs = eps*e0*np.exp(-(L/Rv)*(1/T - 1/T0))/P\n return Q/Qs\n\ndef calcP(P0,PS,hyam,hybm,time,lat,lon,lev):\n \"\"\"\n Calculates and returns an array of the pressure field.\n \"\"\"\n P_0 = P0 * np.ones([time,lat,lon])\n P = np.empty([time,lev,lat,lon])\n for l in range(lev):\n P[:,l,:,:] = hyam[l]*P_0 + hybm[l]*PS\n return P\n\ndef expandLat(lat, shp):\n data = np.empty(shp)\n for t in range(shp[0]):\n for l in range(shp[2]):\n data[t,:,l] = lat\n return data\n\n\ndef extendSurfaceField(data, levs, fill=False):\n shp = data.shape\n new_data = np.zeros((shp[0],levs,shp[1],shp[2]))\n if fill:\n for l in range(levs):\n new_data[:,l,:,:] = data\n else:\n new_data[:,-1,:,:] = data\n return new_data\n \ndef arangeArrays(data_dict, variables, n_chop=0):\n shp = data_dict[variables[0]].shape\n if 'PREC' in variables[0]:\n new_data = np.empty((shp[0],1,shp[1],shp[2],len(variables)))\n new_data[:,0,:,:,0] = data_dict[variables[0]] \n else:\n new_data = np.empty((shp[0],shp[1],shp[2],shp[3],len(variables)))\n for ivar, var in enumerate(variables):\n if var=='lat':\n new_data[:,:,:,:,ivar] = extendSurfaceField(\n expandLat(data_dict[var],[shp[0],shp[2],shp[3]]),shp[1],fill=True)\n elif 'FLX' in var: \n new_data[:,:,:,:,ivar] = extendSurfaceField(data_dict[var],shp[1])\n # elif var=='PRECL': \n # new_data[:,:,:,:,ivar] = extendSurfaceField(data_dict[var],shp[1])\n elif var=='PS':\n new_data[:,:,:,:,ivar] = extendSurfaceField(data_dict[var],shp[1],fill=True)\n else:\n new_data[:,:,:,:,ivar] = data_dict[var]\n if n_chop>0:\n return new_data[:,n_chop:shp[1],:,:,:]\n else:\n return new_data\n\ndef stackArrays(data_dict, variables, n_chop=0, single=False):\n \"\"\"\n Preprocessing function that takes the dictionary of data and stacks individual arrays\n into a single numpy array along the vertical column dimension.\n Args:\n data_dict (dict): dictionary containg raw data as individual arrays (output of loadData)\n variables (list): list of variables to be 'stacked'\n n_chop (int): number of levels to disregard in the case of no data above a certain vertical level.\n Returns:\n data_array (numpy array): single array of all data, various variables are stacked along vertical \n column (dimension 1)\n \"\"\"\n for ivar,var in enumerate(variables):\n if 'FLX' in var or 'PREC' in var:\n field_shape = data_dict[var].shape\n a = np.empty([field_shape[0],1,field_shape[1],field_shape[2]])\n a[:,0,:,:] = data_dict[var]\n elif var == 'lat':\n t_shape = data_dict['T'].shape\n a = np.empty([t_shape[0],1,t_shape[2],t_shape[3]])\n for l in range(t_shape[2]):\n a[:,0,l,:] = data_dict[var][l]\n else:\n a = data_dict[var]\n if single:\n nlev = n_chop+1\n else:\n # if a.shape[1]==1:\n # nlev=2\n # else:\n nlev = a.shape[1]\n if ivar == 0:\n array = a[:,n_chop:nlev,:,:]\n else:\n if var=='lat':\n array = np.concatenate((array,a),axis=1)\n else:\n array = np.concatenate((array,a[:,n_chop:nlev,:,:]),axis=1)\n return array\n\ndef fill_dict(d, data, time, lev, lat, lon, labels, step):\n for il,l in enumerate(labels):\n d[l+'_'+step] = xr.DataArray(data[:,:,:,:,il],\n coords={'time':time,'lev':lev,'lat':lat,'lon':lon},\n dims=['time','lev','lat','lon'])\n return d\n\ndef roll_axes(data_array, test=False):\n \"\"\"\n Preprocessing function that rolls the vertical column axis (1) to the final dimension.\n \"\"\"\n return np.rollaxis(np.rollaxis(data_array,2,1),3,2)\n\ndef reshape(data_array, test=False, stack=False, filled=[]):\n \"\"\"\n Preprocessing function that reshapes the data_array such that its first dimension is now\n a dimension of size TIMExLATxLON.\n \"\"\"\n shp = data_array.shape\n data_array = data_array.reshape((shp[0]*shp[1]*shp[2],shp[3],shp[4]))\n if stack:\n shp3 = 0\n for i in range(shp[4]):\n if i in filled:\n shp3 += 1\n else:\n shp3 += shp[3]\n new_array = np.empty((shp[0]*shp[1]*shp[2],shp3))\n for i in range(shp[4]):\n if i in filled:\n new_array[:,j] = data_array[:,0,i]\n j += 1\n else:\n j = i*shp[3] + shp[3]\n new_array[:,i*shp[3]:j] = data_array[:,:,i]\n else:\n new_array = data_array\n if test:\n return new_array, shp\n else:\n return new_array\n\ndef weighted_avg_std(values, axis, weights):\n \"\"\"\n Return the weighted average and standard deviation.\n values, weights -- Numpy ndarrays with the same shape.\n \"\"\"\n average = np.average(values, axis=axis, weights=weights)\n # Fast and numerically precise:\n # sub = np.empty(values.shape)\n # for i in range(sub.shape[1]):\n # sub[:,i,:] = values[:,i,:] - average\n # variance = np.average(sub**2, axis=axis, weights=weights)\n variance = np.average((values-average)**2, axis=axis, weights=weights)\n return (average, np.sqrt(variance))\n\ndef scale_ui(data, fill=[], l_weights=None, v_weights=None, test=False, lat=False):\n \"\"\"\n Preprocessing function that scales data to become unitarily invariant for machine learning. This simply \n means we subtract the mean and divide by the standard deviation.\n \"\"\"\n mean = data.mean(axis=0).mean(axis=1)\n std = data.std(axis=0).std(axis=1)\n if l_weights is not None:\n mean,std = weighted_avg_std(mean, axis=0, weights=l_weights)\n else:\n mean = mean.mean(axis=0)\n std = std.std(axis=0)\n # if v_weights is not None:\n # mean,std = weighted_avg_std(mean, axis=0, weights=v_weights)\n # else:\n # mean = mean.mean(axis=0)\n # std = std.std(axis=0)\n # print(std[:,-1])\n # print(std[:,-2])\n # print(std[:,-3])\n if lat:\n mean[:,-1] = 0.\n std[:,-1] = 1.\n # data[:,:,:,:,0] = (data[:,:,:,:,0] - mean[:,0]) / std[:,0]\n # data[:,:,:,:,1] = (data[:,:,:,:,1] - mean[:,1]) / std[:,1]\n # data[:,:,:,18:,2] = (data[:,:,:,18:,2] - mean[18:,2]) / std[18:,2]\n # data[:,:,:,-1,3] = (data[:,:,:,-1,3] - mean[-1,3]) / std[-1,3]\n # data[:,:,:,-1,4] = (data[:,:,:,-1,4] - mean[-1,4]) / std[-1,4]\n new_data = (data - mean) / std\n else:\n new_data = (data - mean) / std\n # scaler = StandardScaler()\n # new_data = scaler.fit_transform(data)\n if test: \n return new_data, mean, std\n # return new_data, np.asarray([scaler])\n else:\n return new_data\n\ndef scale_ab(data,fill=[], a=-1.,b=1.,test=False,lat=False):\n \"\"\"\n Preprocessing function that scales data into the range [-1,1]. This is for machine necesssar ylearning\n to work as many variables have drastically different order of magnitude in their respective ranges.\n \"\"\" \n new_data = np.zeros(data.shape)\n dmin = data.min(axis=0).min(axis=0).min(axis=0).min(axis=0)\n dmax = data.max(axis=0).max(axis=0).max(axis=0).max(axis=0) \n new_data = (data - dmin) / (dmax - dmin) * (b - a) + a\n if test:\n # return new_data, np.array([scaler])\n return new_data, dmin, dmax\n else:\n return new_data\n\ndef coarsen_conv(data):\n shp = data.shape\n print(shp)\n shp2 = (int(shp[0]*2),int(shp[1]/2),shp[2],shp[3])\n print(shp2)\n d = np.empty(shp2)\n for i in range(shp[0]):\n j = 0 + i*2\n d[j,:,:,:] = data[i,0:shp[1]:2,:,:]\n d[j+1,:,:,:] = data[i,1:shp[1]:2,:,:]\n shp3 = d.shape\n print(shp3)\n shp4 = (int(shp3[0]*3),shp3[1],int(shp3[2]/3),shp3[3])\n print(shp4)\n new_data = np.empty(shp4)\n for i in range(shp3[0]):\n j = 0 + i*3\n new_data[j,:,:,:] = d[i,:,0:shp3[2]:3,:]\n new_data[j+1,:,:,:] = d[i,:,1:shp3[2]:3,:]\n new_data[j+2,:,:,:] = d[i,:,2:shp3[2]:3,:]\n return new_data\n","repo_name":"gclimon/simplePhysicsML","sub_path":"data_process/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":10972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"73278727485","text":"\nimport energia_total\n\nclass SetBaterias():\n def __init__(self, energia_total):\n\n self.energia_total = energia_total\n self.prof_des_diaria = 0.15\n self.prof_des_tres_dias = 0.60\n self.tension_instalacion = 24\n\n def capacidad_bat_prof_diaria(self):\n energia_diaria_necesaria = self.energia_total / self.prof_des_diaria\n capac_diaria = energia_diaria_necesaria / self.tension_instalacion\n return capac_diaria\n\n def capacidad_bat_prof_tres_dias(self):\n energia_tres_dias_necesaria = (self.energia_total * 3) / self.prof_des_tres_dias\n capac_tres_dias = energia_tres_dias_necesaria / self.tension_instalacion\n\n return capac_tres_dias\n\n\n#SetBaterias(3534).capacidad_bat_prof_diaria()\n#SetBaterias(3534).capacidad_bat_prof_semanal()","repo_name":"anjiron/pv_isolated_installation","sub_path":"calculo_baterias.py","file_name":"calculo_baterias.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"5389574638","text":"import re\nfrom datetime import datetime, timedelta\n\nimport bs4\n\nfrom advisory_parser.exceptions import AdvisoryParserTextException\nfrom advisory_parser.flaw import Flaw\nfrom .utils import get_request, get_text_from_url, CVE_REGEX\n\nMARIADB_VULN_PAGE = \"https://mariadb.com/kb/en/security/\"\nVERSION_REGEX = re.compile(r\"(\\d\\d?\\.\\d\\.\\d\\d?)\")\n\n\ndef _nearest_tuesday(year, month, day=17):\n \"\"\"For a given year and month, return nearest Tuesday to the 17th of that month\n\n \"Critical Patch Updates are collections of security fixes for Oracle\n products. They are available to customers with valid support contracts.\n They are released on the Tuesday closest to the 17th day of January, April,\n July and October.\"\n [https://www.oracle.com/security-alerts/]\n \"\"\"\n month_to_num = {\n \"jan\": 1,\n \"feb\": 2,\n \"mar\": 3,\n \"apr\": 4,\n \"may\": 5,\n \"jun\": 6,\n \"jul\": 7,\n \"aug\": 8,\n \"sep\": 9,\n \"oct\": 10,\n \"nov\": 11,\n \"dec\": 12,\n }\n\n if month.lower() not in month_to_num:\n raise AdvisoryParserTextException(\"Invalid month parsed from advisory URL:\", str(month))\n\n base_date = datetime(year, month_to_num[month.lower()], day)\n\n previous_tuesday = base_date - timedelta(days=((base_date.weekday() + 6) % 7))\n next_tuesday = base_date + timedelta(days=((1 - base_date.weekday()) % 7))\n\n return (\n next_tuesday\n if next_tuesday - base_date < base_date - previous_tuesday\n else previous_tuesday\n )\n\n\ndef create_mariadb_cve_map():\n # Pull plain text of the MariaDB page since the HTML is invalid: it\n # doesn't define </li> ending tags for list elements. The HTML would\n # have to be parsed with a more lenient parser (html5lib), which is an\n # extra dependency.\n page_text = get_text_from_url(MARIADB_VULN_PAGE)\n\n match = re.match(\n r\".+Full List of CVEs fixed in MariaDB\\n(.+)\\s*CVEs without specific version numbers.*\",\n page_text,\n re.DOTALL,\n )\n\n if not match:\n raise AdvisoryParserTextException(\"Could not parse date from CPU URL.\")\n\n cve_map = {}\n for cve_line in match.group(1).split(\"\\n\"):\n cve = CVE_REGEX.search(cve_line)\n versions = VERSION_REGEX.findall(cve_line)\n\n if cve and versions:\n cve_map[cve.group(0)] = versions\n\n return cve_map\n\n\ndef parse_mysql_advisory(url):\n # The url passed in can be either the main CPU page, or the \"Text Form of\n # Risk Matrices\" (aka verbose) page\n\n # Parse url first to get base url and cpu date\n url_match = re.search(r\"/cpu([a-z]{3})(\\d{4})(?:verbose)?\\.html(?:#.*)?$\", url)\n if not url_match:\n raise AdvisoryParserTextException(\"Unexpected CPU URL format.\")\n\n # Get base url and determine advisory_url and verbose_url\n url = url[0 : url_match.start() + len(\"/cpuMMMYYYY\")]\n advisory_url = url + \".html#AppendixMSQL\"\n verbose_url = url + \"verbose.html\"\n\n # Extract the CPU's month and year from the URL since the verbose page has\n # no dates on it\n month, year = url_match.groups()\n cpu_date = _nearest_tuesday(int(year), month)\n advisory_id = \"CPU {} {}\".format(month.capitalize(), year)\n\n # Fetch the CPU verbose page\n advisory_html = get_request(verbose_url)\n soup = bs4.BeautifulSoup(advisory_html, \"html.parser\")\n\n mysql_table = soup.find(id=\"MSQL\").find_next(\"table\")\n\n # The first row is the table header so throw that one away\n table_rows = mysql_table.find_all(\"tr\")[1:]\n\n mariadb_cve_map = create_mariadb_cve_map()\n\n flaws, warnings = [], []\n for row in table_rows:\n # First anchor id contains the CVE\n cve = row.find(\"a\").get(\"id\")\n\n # Second td contains a description\n description_cell = row.find_all(\"td\")[1].contents\n\n # Join all contents of the cell into one string\n description = []\n for element in description_cell:\n if isinstance(element, bs4.element.NavigableString) and element.string:\n description.append(element.string)\n elif isinstance(element, bs4.element.Tag) and element.text:\n description.append(element.text)\n\n description = \"\\n\".join(description)\n\n # Take the text part only, i.e. anything before the CVSS string\n desc_cvss = re.split(r\"\\n\\s*CVSS v?3\\.[0-9] (?=Base Score)\", description)\n if len(desc_cvss) != 2:\n warnings.append(\n \"ERROR: Could not identify CVSS score in {}; skipping:\\n\\n{}\\n---\".format(\n cve, description\n )\n )\n continue\n description, cvss_text = desc_cvss\n\n # Filter out some whitespace\n description = description.replace(\"\\n\", \" \").replace(\" \", \" \").strip()\n\n product = re.search(r\"^Vulnerability in the (.+) (component|product) of \", description)\n if not product:\n warnings.append(\n \"ERROR: Could not identify product in {}; skipping:\\n\\n{}\\n---\".format(\n cve, description\n )\n )\n continue\n if \"MySQL Server\" not in product.group(1) and \"MySQL Client\" not in product.group(1):\n warnings.append(\n \"ERROR: Skipping {}; does not affect MySQL Server or Client component\".format(cve)\n )\n continue\n\n # Filter out the lines that start with CVSS and find the score + vector\n match = re.search(r\"Base Score\\s*(\\d?\\d\\.\\d).*Vector:\\s*\\(([^)]+)\\)\", cvss_text)\n if not match:\n cvss3 = None\n warnings.append(\"Could not parse CVSSv3 score from {} description\".format(cve))\n else:\n cvss3_score = match.group(1)\n cvss3 = cvss3_score + \"/\" + match.group(2)\n\n x = float(cvss3_score)\n if 0.0 < x < 4.0:\n impact = \"low\"\n elif 4.0 <= x < 7.0:\n impact = \"moderate\"\n elif 7.0 <= x < 9.0:\n impact = \"important\"\n else:\n impact = \"critical\"\n\n component = re.search(r\"\\((sub)?component: ([^)]+\\)?)\\)\", description).group(2)\n\n summary = \"mysql: {} unspecified vulnerability ({})\".format(component, advisory_id)\n\n # Flaw descriptions contain vulnerable versions. Fixed versions are usually\n # one version higher.\n vulnerable_versions = VERSION_REGEX.findall(description)\n mysql_fixed_in = []\n for version in vulnerable_versions:\n fixed_version = \"{}.{}\".format(\n version.rsplit(\".\", 1)[0], int(version.split(\".\")[-1]) + 1\n )\n mysql_fixed_in.append(fixed_version)\n\n fixed_in = {\"mysql\": mysql_fixed_in}\n\n mariadb_fixed_in = mariadb_cve_map.get(cve)\n if mariadb_fixed_in:\n fixed_in[\"mariadb\"] = mariadb_fixed_in\n\n flaws.append(\n Flaw(\n cves=[cve],\n summary=summary,\n public_date=cpu_date,\n cvss3=cvss3,\n impact=impact,\n description=description,\n fixed_in=fixed_in,\n from_url=advisory_url,\n advisory_id=advisory_id,\n )\n )\n\n return flaws, warnings\n","repo_name":"RedHatProductSecurity/advisory-parser","sub_path":"advisory_parser/parsers/mysql.py","file_name":"mysql.py","file_ext":"py","file_size_in_byte":7252,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"42"} +{"seq_id":"35141090315","text":"\"\"\"Protocol for chat server - Computação Distribuida Assignment 1.\"\"\"\nimport json\nfrom datetime import datetime\nfrom socket import socket\n\nENCODING = \"UTF-8\"\n\nclass Message:\n \"\"\"Message Type.\"\"\"\n\n def __init__(self, command):\n self.command = command\n\n\nclass JoinMessage(Message):\n \"\"\"Message to join a chat channel.\"\"\"\n\n def __init__(self, command, channel):\n self.channel = channel\n super().__init__(command)\n\n def __repr__(self):\n return json.dumps({\"command\": self.command, \"channel\": self.channel})\n\n\nclass RegisterMessage(Message):\n \"\"\"Message to register username in the server.\"\"\"\n\n def __init__(self, command, user):\n self.user = user\n super().__init__(command)\n\n def __repr__(self):\n return json.dumps({\"command\": self.command, \"user\": self.user})\n\n\nclass TextMessage(Message):\n \"\"\"Message to chat with other clients.\"\"\"\n\n def __init__(self, command, message, channel):\n self.message = message\n self.channel = channel\n super().__init__(command)\n\n def __repr__(self):\n repr = {\n \"command\": self.command,\n \"message\": self.message,\n \"ts\": int(datetime.now().timestamp()),\n }\n if self.channel != None:\n repr[\"channel\"] = self.channel\n return json.dumps(repr)\n\n\nclass CDProto:\n \"\"\"Computação Distribuida Protocol.\"\"\"\n\n @classmethod\n def register(cls, username: str) -> RegisterMessage:\n \"\"\"Creates a RegisterMessage object.\"\"\"\n return RegisterMessage(\"register\", username)\n\n @classmethod\n def join(cls, channel: str) -> JoinMessage:\n \"\"\"Creates a JoinMessage object.\"\"\"\n return JoinMessage(\"join\", channel)\n\n @classmethod\n def message(cls, message: str, channel: str = None) -> TextMessage:\n \"\"\"Creates a TextMessage object.\"\"\"\n return TextMessage(\"message\", message, channel)\n\n @classmethod\n def send_msg(cls, connection: socket, msg: Message):\n \"\"\"Sends through a connection a Message object.\"\"\"\n rawdata = repr(msg).encode(ENCODING)\n header = len(rawdata).to_bytes(2, \"big\")\n connection.send(header + rawdata)\n\n @classmethod\n def recv_msg(cls, connection: socket) -> Message:\n \"\"\"Receives through a connection a Message object.\"\"\"\n try:\n size = int.from_bytes(connection.recv(2), \"big\")\n if size:\n msg = json.loads(\n connection.recv(size).decode(ENCODING)\n )\n\n command = msg[\"command\"]\n if command == \"register\":\n return CDProto.register(msg[\"user\"])\n elif command == \"join\":\n return CDProto.join(msg[\"channel\"])\n elif command == \"message\":\n if msg[\"message\"] == \"\":\n return None\n if \"channel\" in msg:\n return CDProto.message(msg[\"message\"], msg[\"channel\"])\n else:\n return CDProto.message(msg[\"message\"])\n else:\n raise CDProtoBadFormat()\n else:\n return None\n except:\n raise CDProtoBadFormat()\n\n\nclass CDProtoBadFormat(Exception):\n \"\"\"Exception when source message is not CDProto.\"\"\"\n\n def __init__(self, original_msg: bytes = None):\n \"\"\"Store original message that triggered exception.\"\"\"\n self._original = original_msg\n\n @property\n def original_msg(self) -> str:\n \"\"\"Retrieve original message as a string.\"\"\"\n return self._original.decode(\"utf-8\")\n","repo_name":"renanaferreira/Distributed_Computers_Repository","sub_path":"exc01/chat_server/src/protocol.py","file_name":"protocol.py","file_ext":"py","file_size_in_byte":3665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"13100292984","text":"from dis import show_code\nfrom pyexpat import model\nfrom tkinter.tix import Tree\nfrom typing import Type, List, Tuple\nfrom sklearn.utils import shuffle\n\nimport torch\nimport numpy as np\nfrom sklearn import datasets\n\nfrom visualize import show_loss_curve, show_decision_boundary\n\n\nclass CircelsDataset:\n def __init__(self, n_samples: int = 10000) -> None:\n points, labels = datasets.make_circles(\n n_samples, shuffle=True, factor=0.5, noise=0.05\n )\n # Hier war ein komischer Faktor davor\n self.points = points.astype(np.float32)\n self.labels = labels.astype(np.float32)\n\n def __len__(self) -> int:\n return len(self.points)\n\n def __getitem__(self, idx: int) -> Tuple[np.float32, np.float32]:\n return self.points[idx], self.labels[idx]\n\n\nclass BinaryClassifierMLP(torch.nn.Module):\n def __init__(self, n_inputs: int, hidden: List, activation_fn: Type) -> None:\n super().__init__()\n\n self.layers = torch.nn.ModuleList()\n\n # Hier waren die Input und Output sizes falsch\n current_inputs = n_inputs\n\n for i in range(len(hidden)):\n current_outputs = hidden[i]\n\n self.layers.append(torch.nn.Linear(current_inputs, current_outputs))\n self.layers.append(activation_fn())\n current_inputs = current_outputs\n\n self.classifier = torch.nn.Sequential(\n torch.nn.Linear(current_inputs, 1), torch.nn.Sigmoid()\n )\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n # Hier stand y = layer(x), dann würde das x aber nicht weitergegeben werden\n for layer in self.layers:\n x = layer(x)\n\n return self.classifier(x).squeeze()\n\n\ndef train_binary(\n epochs: int,\n dataloader: torch.utils.data.DataLoader,\n model: torch.nn.Module,\n optim: torch.optim.Optimizer,\n) -> List:\n loss_curve = []\n loss_fn = torch.nn.BCELoss()\n\n for _ in range(epochs):\n for _, (input_data, gt_label) in enumerate(dataloader):\n # zero_grad() stand hier direkt vor step(), das geht natürlich nicht\n model.zero_grad()\n\n prediction = model(input_data)\n loss_val = loss_fn(prediction, gt_label)\n loss_val.backward()\n\n optim.step()\n loss_curve.append(loss_val.item())\n\n return loss_curve\n\n\n@torch.no_grad()\ndef evaluate(dataloader: torch.utils.data.DataLoader, model: torch.nn.Module,) -> float:\n accuracy = 0.0\n\n for _, (input_data, gt_label) in enumerate(dataloader):\n prediction = model(input_data)\n accuracy += torch.sum(prediction.round() == gt_label)\n\n return 100.0 * accuracy / len(dataloader.dataset)\n\n\nif __name__ == \"__main__\":\n \"\"\"\n Aufgabenteil 1\n \"\"\"\n dataset = CircelsDataset()\n # hier war shuffle=False, das sollte man so aber ja nicht machen (oder?)\n dataloader = torch.utils.data.DataLoader(dataset, 32, shuffle=True)\n mlp1 = BinaryClassifierMLP(2, [4, 4], torch.nn.Tanh)\n optim = torch.optim.Adam(mlp1.parameters(), lr=0.01)\n\n print(\"Accuarcy before training\", evaluate(dataloader, mlp1))\n loss_curve = train_binary(10, dataloader, mlp1, optim)\n print(\"Accuarcy after training\", evaluate(dataloader, mlp1))\n show_loss_curve(loss_curve)\n show_decision_boundary(mlp1, dataset.points, dataset.labels)\n\n \"\"\"\n Aufgabenteil 2\n \"\"\"\n mlp2 = BinaryClassifierMLP(2, [4] * 18, torch.nn.Sigmoid)\n optim = torch.optim.Adam(mlp2.parameters(), lr=0.01)\n\n print(\"Accuarcy before training\", evaluate(dataloader, mlp2))\n loss_curve = train_binary(10, dataloader, mlp2, optim)\n print(\"Accuarcy after training\", evaluate(dataloader, mlp2))\n show_loss_curve(loss_curve)\n show_decision_boundary(mlp2, dataset.points, dataset.labels)\n\n for layer in mlp2.layers:\n if isinstance(layer, torch.nn.Linear):\n print(layer.weight.grad)\n","repo_name":"MaximilianMundt/DLVC","sub_path":"Übungsblatt 06/errors.py","file_name":"errors.py","file_ext":"py","file_size_in_byte":3901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"20413733139","text":"import io\n\nfrom PIL import Image, ImageFile\n\n\n# Rescale an image in the form of bytes to a new set of bytes\n# in the same format. Assumes the aspect is correct and that\n# the incoming data is valid (it's expected to be for example\n# the output of previous image operations)\ndef rescale_image_bytes(origbytes, resolution):\n p = ImageFile.Parser()\n p.feed(origbytes)\n p.close()\n img = p.image\n\n return rescale_image(img, resolution)\n\n\ndef rescale_image(img, resolution, centered=False):\n scale = min(\n float(resolution[0]) / float(img.size[0]),\n float(resolution[1]) / float(img.size[1]),\n )\n\n newimg = img.resize(\n (int(img.size[0] * scale), int(img.size[1] * scale)),\n Image.BICUBIC,\n )\n saver = io.BytesIO()\n if centered and newimg.size[0] != newimg.size[1]:\n # This is not a square, so we have to roll it again\n centeredimg = Image.new('RGBA', resolution)\n centeredimg.paste(newimg, (\n (resolution[0] - newimg.size[0]) // 2,\n (resolution[1] - newimg.size[1]) // 2,\n ))\n centeredimg.save(saver, format='PNG')\n else:\n newimg.save(saver, format=img.format)\n\n return saver.getvalue()\n","repo_name":"pgeu/pgeu-system","sub_path":"postgresqleu/util/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"42"} +{"seq_id":"17521980483","text":"from datetime import datetime\n\nfrom aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton\n\nfrom src.bot import dispatcher\nfrom src.database import (\n get_times_to_notify,\n update_notification_count,\n get_pill_by_id,\n reset_notification_count\n)\n\n\nasync def notify():\n async for time in await get_times_to_notify(datetime.now().time().strftime('%H:%M')):\n pill = await get_pill_by_id(time['pill_id'])\n await update_notification_count(time['_id'], time['notifications'] - 1)\n await dispatcher.bot.send_message(\n pill['user_id'],\n f'Тебе пора пить {pill[\"title\"]}',\n reply_markup=InlineKeyboardMarkup().add(InlineKeyboardButton(\n 'Выпил',\n callback_data=f'notification:{str(time[\"_id\"])}'\n ))\n )\n\n\nasync def reset():\n await notify()\n await reset_notification_count()\n","repo_name":"torikki-tou/PillsBot","sub_path":"src/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"33686351766","text":"# -*- coding: utf-8 -*-\nfrom functools import wraps\nimport traceback\n\ndef state(name):\n \"\"\"\n Устанавливает статус и состояние домена в зависимости от результата\n выполнения декорируемой функции\n \"\"\"\n def wrapper(f):\n @wraps(f)\n def wrapped(event, *args, **kwargs):\n agent = event.pool.context['agent']\n if event.is_first_run:\n agent.send_server('domain_state', {\n 'state': name,\n 'status': 'running',\n })\n\n try:\n ret = f(event, *args, **kwargs)\n except Exception:\n agent.send_server('domain_state', {\n 'state': name,\n 'status': 'error',\n 'message': traceback.format_exc()\n })\n raise\n\n if not event.is_prevent_done:\n agent.send_server('domain_state', {\n 'state': name,\n 'status': 'done',\n })\n return ret\n return wrapped\n return wrapper\n\n\n","repo_name":"openre/openre","sub_path":"openre/agent/domain/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"26385541211","text":"import numpy as np \nimport matplotlib.pyplot as plt \n\n# set width of bar \nbarWidth = 0.25\nfig = plt.subplots(figsize =(12, 8)) \n\n# set height of bar \nRPL = [98,0,0,64,116,46,64,80]\n\nPROJ = [112,100,71,64,116,46,64,64]\n\n\n# Set position of bar on X axis \nbr1 = np.arange(8) \nbr2 = [x + barWidth for x in br1] \nbr3 = [x + barWidth for x in br2] \n\ncolors = iter([plt.cm.tab20(i) for i in range(20)])\n\nnext(colors)\nnext(colors)\nnext(colors)\n\nplt.grid(color='#95a5a6', linestyle='--', linewidth=1, axis='y', alpha=0.5)\n\n\n# Make the plot \nplt.bar(br1, RPL, width = barWidth, \n\t\tedgecolor ='black', label ='RPL', color=[next(colors)]) \n\nnext(colors)\n\n\nplt.bar(br2, PROJ, width = barWidth, \n\t\tedgecolor ='black', label ='RPL-RP',color=[next(colors)],hatch = '/') \n\n\n# Adding Xticks \nplt.xlabel('Packet Type', fontweight ='bold',fontsize=17) \nplt.ylabel('Packet Size (bytes)', fontweight ='bold',fontsize=17) \n\n\nplt.xticks([r + barWidth for r in range(len(RPL))], \n\t\t['DAO', 'PDAO', 'PDR', 'DAO-ACK', 'DIO', 'DIS','data\\n(storing \\nmode)', 'data\\n(source \\nrouted)'],fontsize=17) \nplt.yticks(fontsize=15)\nplt.legend(fontsize=15)\n\nplt.show() \n","repo_name":"iliar-rabet/dao-projection","sub_path":"examples/plots/barplot.py","file_name":"barplot.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"42"} +{"seq_id":"33658448479","text":"# ------------------------------------------------------------\n# TPC1: Intervalos (definição léxica)\n# \n# ------------------------------------------------------------\nimport ply.lex as lex\nimport sys\n\n# List of token names. This is always required\ntokens = ( 'NUM', )\n\n# Literals\nliterals = ['+', '-', '[', ']', ',']\n \n# A regular expression rule with some action code\ndef t_NUM(t):\n r'-?\\d+'\n t.value = int(t.value) \n return t\n\n#----------------------------------------------------\n# Define a rule so we can track line numbers\ndef t_newline(t):\n r'\\n+'\n t.lexer.lineno += len(t.value)\n \n \n# A string containing ignored characters (spaces and tabs)\nt_ignore = ' \\t'\n \n# Error handling rule\ndef t_error(t):\n print(\"Illegal character '%s'\" % t.value[0])\n t.lexer.skip(1)\n \n#-------------------------------------------------------------- \n# Build the lexer\nlexer = lex.lex()\n \n\n","repo_name":"LittleLevi05/EG","sub_path":"Semana_1/intervalos_lex.py","file_name":"intervalos_lex.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"24710534733","text":"#!/usr/bin/env python3\n\nimport rospy\nimport numpy as np\nfrom sensor_msgs.msg import LaserScan\nfrom nav_msgs.msg import Odometry, OccupancyGrid\nfrom modules_pkg.msg import LaserAndOdometry\nfrom tf.transformations import euler_from_quaternion, quaternion_from_euler\n\n# Bresenham's line drawing algorithm\ndef bresenham(x1, y1, x2, y2):\n x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)\n # delta, sign\n dx, dy = np.abs(x2 - x1), np.abs(y2 - y1)\n # integers\n sx, sy = np.sign(x2 - x1), np.sign(y2 - y1)\n if dy > dx:\n dx, dy = dy, dx\n swp = True\n else:\n swp = False\n #\n A = 2 * dy\n B = 2 * (dy - dx)\n E = 2 * dy - dx\n #\n # Output pixels\n xs, ys = [x1], [y1]\n #\n x, y = x1, y1\n # point (x2,y2) must not be included\n for i in range(1, dx):\n if E < 0:\n if swp: y += sy\n else: x += sx\n E = E + A\n else:\n y += sy\n x += sx\n E = E + B\n # mark output pixels\n xs.append(x)\n ys.append(y)\n #\n return zip(xs, ys)\n\n# hit/miss\n# p free -> 0.3 --> -0.8472978603872036 \n# p occ -> 0.9 --> 2.1972245773362196 \ndef log_odds(p):\n return np.log(p / (1 - p))\n\n# ratio -> probabilty\ndef retrieve_p(l):\n return 1 - 1 / (1 + np.exp(l))\n\n# Get theta from odometry\ndef get_odom_orientation(odom):\n # Docs say this is in quaternion form\n q = odom.pose.pose.orientation\n (roll, pitch, yaw) = euler_from_quaternion([q.x, q.y, q.z, q.w])\n # limit\n while yaw < 0:\n yaw += 2 * np.pi\n while yaw >= 2 *np.pi:\n yaw -= 2 * np.pi\n #\n return yaw\n\n# Odometry -> State\ndef get_odom_state(odom):\n x_odom, y_odom = odom.pose.pose.position.x, odom.pose.pose.position.y\n theta_odom = get_odom_orientation(odom)\n return [x_odom, y_odom, theta_odom]\n\n# Hit/Miss parameters\nP_PRIOR = 0.5 # Prior occupancy probability\nP_OCC = 0.9 # Probability that cell is occupied with total confidence\nP_FREE = 0.3 # Probability that cell is free with total confidence\nWIDTH = (-35, 35) # x axis limits\nHEIGHT = (-35, 35) # y axis limits\nRES = 0.5 # Grid resolution in [m]\n\n# rasterize\ndef rasterize(x, y):\n return int((x-WIDTH[0])/RES), int((y-HEIGHT[0])/RES)\n\n# Grid\nx = np.arange(start = WIDTH[0], stop = WIDTH[1] + RES, step = RES)\ny = np.arange(start = HEIGHT[0], stop = HEIGHT[1] + RES, step = RES)\n# probability matrix in log-odds scale:\ngrid = np.full(shape = (len(x), len(y)), fill_value = log_odds(P_PRIOR))\n# Pulbish a map\npub = rospy.Publisher('/map_gamda', OccupancyGrid, queue_size=10)\n\n# CALLLLLLLLLLLLLLLLLLBACK\ndef map_callback(sensors_msg):\n #\n laser = sensors_msg.laser\n odom = sensors_msg.odom\n # Get distances and angles of laser scan\n dist_ang = [(d, laser.angle_min +i*laser.angle_increment)\n for i, d in enumerate(laser.ranges)\n if d < laser.range_max and d > laser.range_min]\n # get position and orientation from odometry\n x, y, th = get_odom_state(odom)\n # x, y, tot \n dist = [(d * np.cos(theta +th), d * np.sin(theta +th), d)\n for d, theta in dist_ang]\n # absolute positions for obstacles, and total distance\n obst = [(x +dx, y +dy, d) for dx, dy, d in dist]\n # rasterize\n x1, y1 = rasterize(x, y)\n # Loop over obstacles\n for (px, py, d) in obst:\n #\n x2, y2 = rasterize(px, py)\n # Miss for cells along the path\n for (xi, yi) in bresenham(x1, y1, x2, y2):\n grid[xi][yi] += log_odds(P_FREE)\n # HIT\n if d < laser.range_max:\n grid[x2][y2] += log_odds(P_OCC)\n #\n # PUBLISH\n occ_grid = OccupancyGrid()\n occ_grid.header.stamp = rospy.Time.now()\n occ_grid.header.frame_id = 'robot_map'\n occ_grid.data = (retrieve_p(grid)*100).astype(int).ravel().tolist()\n occ_grid.info.resolution = RES\n occ_grid.info.width = grid.shape[0]\n occ_grid.info.height = grid.shape[1]\n occ_grid.info.origin.position.x = WIDTH[0]\n occ_grid.info.origin.position.y = HEIGHT[0]\n # Quaternion from euler\n q = quaternion_from_euler(np.pi, 0, np.pi/2)\n occ_grid.info.origin.orientation.x = q[0]\n occ_grid.info.origin.orientation.y = q[1]\n occ_grid.info.origin.orientation.z = q[2]\n occ_grid.info.origin.orientation.w = q[3]\n # print(max(occ_grid.data))\n pub.publish(occ_grid)\n\n\ndef main():\n # Initialize Node with node name\n rospy.init_node('map')\n # Read Sensors\n sub = rospy.Subscriber('/sensors_gamda', LaserAndOdometry, map_callback)\n # Wait for messages\n rospy.spin()\n\nif __name__ == '__main__':\n try:\n print('arkab Giza mneen?')\n print('/sensors_gamda --> /map_gamda')\n main()\n except rospy.ROSInterruptException:\n print('howa alak feen?')\n pass\n\n","repo_name":"YousefAtefB/Ya-SLAM","sub_path":"modules_pkg/script/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":4810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"74521106365","text":"import sys\nfrom time import time\n\n\nterminal = 0\ndef done():\n global terminal\n terminal += 1\n # print(\"Reached Base Case {}\".format(i))\n\n\nclass SpecifyDecisionTree():\n def __init__(self, g, fiedler_check, target, bound, allow_disconnected = False):\n assert(bound == \"two\" or bound == \"one\")\n\n self.graph = g\n self.fiedler_check = fiedler_check\n\n self.target = target\n self.bound = bound\n self.allow_disconnected = allow_disconnected\n\n # edges prevent the need to do n^2 on sparse graphs\n l = len(self.graph)\n edges = set([(u,v) for u in range(l) for v in range(u + 1, l) if self.graph[u][v]])\n self.edge_map = {}\n for i in range(len(edges) + 1):\n self.edge_map[i] = []\n\n t0 = time()\n self.options = self.generate_graphs(g, edges, target, bound, allow_disconnected, True)\n t1 = time()\n print(\"generating decision tree with {} leaves and {} options and min {} - took {}s\".format(terminal, len(self.options), min((d[0] for d in self.options), default=\"EMPTY\"), t1-t0))\n\n def fiedler_without_edge(self, g, u, v):\n g = g.copy()\n g[u][v] = 0\n g[v][u] = 0\n return self.fiedler_check(g), g\n\n def possibilities(self):\n return set(f for (f, g) in self.options)\n\n def search(self, data, val):\n if self.bound == \"one\":\n data = [x for x in data if x[0] >= val - 0.00001]\n distance = [(abs(val - f),g) for (f, g) in data]\n return min(distance, key = lambda t: t[0])\n\n def generate_graphs(self, g, edges, target, bound, allow_disconnected, init = False):\n if init: print(\"generating decision tree map\")\n if edges in self.edge_map[len(edges)]: # already_explored\n return []\n else:\n self.edge_map[len(edges)].append(edges)\n \n # Base Case: Stop tree after dropped\n fiedler = self.fiedler_check(g)\n if (not allow_disconnected) and (fiedler <= 0.001):\n done()\n return []\n elif (fiedler <= 0.0001):\n done()\n return [(fiedler, g)]\n elif bound == \"one\" and fiedler < target: \n # print(\"bounded stop\")\n done()\n return []\n\n # Recursive Case\n options = [(fiedler, g)]\n for (u,v) in edges:\n f_modified, g_modified = self.fiedler_without_edge(g, u, v)\n # Remove edge from edge list\n edges_modified = set([edge for edge in edges if edge != (u,v)])\n assert(len(edges_modified) + 1 == len(edges))\n options += self.generate_graphs(g_modified, edges_modified, target, bound, allow_disconnected)\n return options\n\n def create_graph(self, target):\n fiedler = self.fiedler_check(self.graph)\n if (not self.allow_disconnected and (fiedler <= 0.0001)) or (self.bound == \"one\" and fiedler <= target):\n return self.graph\n \n _, g = self.search(self.options, target)\n return g","repo_name":"Danieltech99/CS-229r-Final-Project","sub_path":"algorithms/specify_decision_tree.py","file_name":"specify_decision_tree.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"38755960853","text":"#coding=utf-8\nimport os\nfrom lettuce import *\nfrom nose.tools import assert_equals\nfrom modal import i_load_the_document_zakon, i_load_the_document_Nalogovij_Kodeks\nfrom view_document import i_go_to_the_main_page\nfrom zakon.settings import PROJECT_ROOT\n\nFILE_ROOT_ADDRESS = os.path.join(PROJECT_ROOT, 'tests/document/features/resources/')\n\n\n@step(u'я перехожу на страницу \"(.*)\"')\n@step(u'я нахожусь на странице \"(.*)\"')\ndef i_am_on_page(step, page_name):\n i_go_to_the_main_page(step)\n elem_href = world.browser.find_element_by_link_text(page_name)\n elem_href.click()\n\n\n@step(u'вижу кнопку \"Ссылка\" в содержании статьи-\"(.*)\"')\ndef i_see_the_add_link_button(step, article_num):\n article_content = world.browser.find_element_by_id('article_' + article_num)\n assert article_content.find_element_by_name('btn_article_' + article_num)\n\n\n@step(u'я нажимаю на кнопку \"Ссылка\" под \"(.*)\"-статьей')\ndef i_click_the_add_link_button(step, article_num):\n button_href = world.browser.find_element_by_name('btn_article_' + article_num)\n button_href.click()\n\n\n@step(u'вижу модальное окно')\ndef i_see_modal_form(step):\n modal_hidden_attribute = world.browser.find_element_by_id('modal').get_attribute('aria-hidden')\n assert modal_hidden_attribute == 'false'\n\n\n@step(u'в модальном окне вижу ссылку \"(.*)\"')\ndef i_see_link_on_modal_form(step, link_name):\n modal_content = world.browser.find_element_by_id('accordion').text\n assert modal_content.find(link_name) != -1\n\n\n@step(u'открыто модальное окно на странице \"(.*)\"')\ndef modal_form_is_opened(step, page_name):\n i_am_on_page(step, page_name)\n i_click_the_add_link_button(step, '1')\n\n\n@step(u'я кликаю на ссылку \"(.*)\"')\ndef i_click_the_link(step, link_text):\n link_href = world.browser.find_element_by_partial_link_text(link_text)\n link_href.click()\n\n\n@step(u'открыто окно подтверждения на странице \"(.*)\"')\ndef opened_confirm_form(step, page_name):\n i_load_the_documents_zakon_and_Nalogovij_Kodeks(step)\n i_am_on_page(step, page_name)\n i_click_the_add_link_button(step, '1')\n i_click_the_link(step, 'НАЛОГОВЫЙ КОДЕКС КЫРГЫЗСКОЙ РЕСПУБЛИКИ')\n world.browser.find_element_by_xpath('//*[@class=\"accordion\"]//a[text()=\"Статья 19. Понятие налога\"]').click()\n\n\n@step(u'я нажимаю на кнопку \"ОК\"')\ndef i_click_button_OK(step):\n alert = world.browser.switch_to_alert()\n alert.accept()\n\n\n@step(u'вижу что нахожусь на странице \"(.*)\"')\ndef i_see_that_i_am_on_page(step, expected_title):\n title = world.browser.find_element_by_tag_name('title')\n assert_equals(title.text, expected_title)\n\n\n@step(u'я добавляю ссылку с \"(.*)\"-статьи на \"(.*)\" в документе \"(.*)\"')\ndef i_add_link_to_document(step, source_article_number, target_article_name, doc_name):\n i_click_the_add_link_button(step, source_article_number)\n i_click_the_link(step, doc_name)\n world.browser.find_element_by_xpath('//*[@class=\"accordion\"]//a[text()=\"' + target_article_name + '\"]').click()\n i_click_button_OK(step)\n\n\n@step(u'вижу что \"(.*)\"-статья содержит ссылку \"(.*)\"')\ndef i_see_link_in_the_content_of_article(step, article_number, link_text):\n article_content = world.browser.find_element_by_id('article_' + article_number)\n assert article_content.find_element_by_partial_link_text(link_text)\n\n\n@step(\n u'загружены документы НАЛОГОВЫЙ КОДЕКС, ЗАКОН КЫРГЫЗСКОЙ РЕСПУБЛИКИ О государственной регистрации юридических лиц')\ndef i_load_the_documents_zakon_and_Nalogovij_Kodeks(step):\n i_load_the_document_zakon(step)\n i_load_the_document_Nalogovij_Kodeks(step)\n\n\n\n","repo_name":"AttractorSoftware/zakon","sub_path":"django-project/tests/document/features/reference.py","file_name":"reference.py","file_ext":"py","file_size_in_byte":4032,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"7814652682","text":"# for command line args\nimport sys\n# json.loads() will turn json string to python object\n# json.dumps() will turn python object to json string\nimport json\n\n# here are many imports from flask you may want to use\nfrom flask import Flask, redirect, request, make_response, send_from_directory, render_template\nimport gossipprotocol\nimport requests\nimport random\nfrom threading import Thread\n\napp = Flask(__name__)\nport = 0\nflower_url = ''\ngossip = None\ngossip_endpoint = '/gossip'\norders = dict()\norder_id = 0\norders_delivered = dict()\n\n\ndef generate_location():\n latitude = random.uniform(35,40)\n longitude = random.uniform(-110,-80)\n location = str(latitude) + \",\" + str(longitude)\n return location\n\n\ndef response(obj):\n response = make_response()\n response.headers['Content-Type'] = 'application/json'\n response.data = json.dumps(obj)\n return response\n\n\n@app.route('/register')\ndef register():\n global gossip\n uri = request.args.get(\"uri\")\n gossip.add_driver(uri)\n log = \"uri needed\"\n if uri:\n log = {'result': 'success', 'drivers': gossip.my_drivers}\n return response(log)\n\n\ndef generate_order():\n global order_id\n order_id += 1\n return flower_url + \"-\" + str(order_id), generate_location(), len(gossip.my_drivers), dict()\n\n\ndef send_get(url, params):\n requests.get(url, params=params)\n\n\n@app.route(\"/flowershops\")\ndef get_flower_shops():\n flower_shops = list()\n for gossip_info in gossip.my_flower_shops:\n flower_shops.append(gossip_info.url)\n\n return response(flower_shops)\n\n\n@app.route('/ordersdelivered')\ndef get_orders_delivered():\n return response(orders_delivered)\n\n\n@app.route('/order')\ndef order():\n global orders\n order = generate_order()\n log = dict()\n log['order'] = order #id\n orders[order[0]] = order\n log['returnURL'] = flower_url +\":\"+ str(port)\n log['drivers'] = list()\n drivers = gossip.my_drivers\n for driver in drivers:\n # scatter order to driver\n driver_url = driver + \"/order\"\n get_params = dict()\n get_params['uri'] = flower_url\n get_params['location'] = order[1]\n get_params['id'] = order[0]\n thread = Thread(target=send_get, args=(driver_url, get_params))\n thread.start()\n log['drivers'].append(driver)\n # set timer to call process_bids(orderid)\n\n return response(log)\n\n\ndef process_bids(orderid):\n bestbid = sys.maxint\n winning_driver = ''\n bids = orders[orderid][3]\n\n for driver, bid in bids.items():\n if int(bid) < int(bestbid):\n bestbid = bid\n winning_driver = driver\n\n driver_url = winning_driver + \"/deliverorder\"\n get_params = dict()\n get_params['id'] = orderid\n thread = Thread(target=send_get, args=(driver_url, get_params))\n thread.start()\n\n\n@app.route(\"/drivers\")\ndef get_drivers():\n return response(gossip.my_drivers)\n\n\n@app.route('/bid')\ndef bid():\n global orders\n uri = request.args.get(\"uri\")\n bid = request.args.get(\"bid\")\n orderid = str(request.args.get(\"orderid\"))\n order = orders[orderid]\n drivers_expected = order[2]\n order[3][uri] = bid\n orders[orderid] = order\n\n if drivers_expected == len(order[3]):\n process_bids(orderid)\n return response('bid recorded for ' + uri + \" and bid \" + str(bid))\n\n\n@app.route(\"/orderdelivered\")\ndef order_delivered():\n global orders_delivered\n orderid = request.args.get(\"id\")\n uri = request.args.get(\"uri\")\n if uri not in orders_delivered.keys():\n orders_delivered[uri] = list()\n orders_delivered[uri].append(orderid)\n return response(\"Order: \" + orderid + \" delivered by \" + uri)\n\n\n@app.route(gossip_endpoint)\ndef gossip():\n return gossip.respond(request)\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n print('Pass in a port number')\n else:\n port = int(sys.argv[1])\n flower_url = \"http://localhost:\" + str(port)\n gossip = gossipprotocol.Gossip(flower_url, gossip_endpoint)\n app.run(host='0.0.0.0', port=port)\n","repo_name":"seanag0234/flower-delivery","sub_path":"flowershop.py","file_name":"flowershop.py","file_ext":"py","file_size_in_byte":4036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"72599328765","text":"\"\"\"\n REST API Documentation for the NRS TFRS Credit Trading Application\n\n The Transportation Fuels Reporting System is being designed to streamline\n compliance reporting for transportation fuel suppliers in accordance with\n the Renewable & Low Carbon Fuel Requirements Regulation.\n\n OpenAPI spec version: v1\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\nfrom django.db.models import Q\nfrom rest_framework import viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\n\nfrom api.models.CreditTradeHistory import CreditTradeHistory\nfrom api.permissions.CreditTradeHistory import CreditTradeHistoryPermissions\nfrom api.serializers import CreditTradeHistoryReviewedSerializer\nfrom api.paginations import BasicPagination\n\n\nclass CreditTradeHistoryViewSet(viewsets.GenericViewSet):\n queryset = CreditTradeHistory.objects.all()\n permission_classes = (CreditTradeHistoryPermissions,)\n serializer_classes = {\n \"default\": CreditTradeHistoryReviewedSerializer,\n }\n pagination_class = BasicPagination\n\n column_sort_mappings = {\n \"createTimestamp\": \"create_timestamp\",\n \"creditTradeId\": \"credit_trade__id\",\n \"initiator\": \"credit_trade__initiator__name\",\n \"respondent\": \"credit_trade__respondent__name\",\n }\n\n def get_serializer_class(self):\n if self.action in list(self.serializer_classes.keys()):\n return self.serializer_classes[self.action]\n\n return self.serializer_classes[\"default\"]\n\n def get_queryset(self):\n \"\"\"\n Queryset should be restricted based on the user's roles.\n A government user won't see draft, submitted, refused.\n A regular user won't see recommended and not recommended.\n Regular users will only see histories related to their organization\n \"\"\"\n user = self.request.user\n return CreditTradeHistory.objects.filter(\n Q(create_user__organization_id=user.organization_id)\n )\n\n @action(detail=False, methods=[\"post\"])\n def paginated(self, request):\n queryset = self.filter_queryset(self.get_queryset())\n\n sorts = request.data.get(\"sorts\")\n for sort in sorts:\n id = sort.get(\"id\")\n desc = sort.get(\"desc\")\n sort_field = self.column_sort_mappings.get(id)\n if sort_field:\n if desc:\n queryset = queryset.order_by(\"-\" + sort_field)\n else:\n queryset = queryset.order_by(sort_field)\n\n page = self.paginate_queryset(queryset)\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n\n serializer = self.get_serializer(queryset, many=True)\n return Response(serializer.data)\n","repo_name":"bcgov/tfrs","sub_path":"backend/api/viewsets/CreditTradeHistory.py","file_name":"CreditTradeHistory.py","file_ext":"py","file_size_in_byte":3362,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"42"} +{"seq_id":"75451785727","text":"from tensorflow import keras\nimport numpy as np\nfrom tensorflow.keras import layers\n#\ndef SVBRDF(num_classes):\n #=============== first layer ==================\n\n inputs = keras.Input(shape=(256,256) + (3,))\n\n #GF = layers.LeakyReLU()(inputs)\n GF = layers.AveragePooling2D((inputs.shape[1],inputs.shape[1]))(inputs)\n GF = layers.Dense(128)(GF)\n GF = layers.Activation('selu')(GF)\n\n x = layers.SeparableConv2D(128,4, 2, padding=\"same\")(inputs)\n x = layers.BatchNormalization()(x)\n #previous_block_activation = x # Set aside residual\n\n #========== define filters for unet ===================\n\n downfilters = np.array([128,256,512,512,512,512,512])\n Upfilters = np.flip(np.copy(downfilters))\n downfilters = np.delete(downfilters,0)\n prefilter = 128\n\n #===================== upsampling =======================\n\n for filters in downfilters:\n #print(x.shape)\n #print(filters)\n GFdown = layers.AveragePooling2D((x.shape[1],x.shape[1]))(x)\n GFup = layers.Dense(prefilter)(GF)\n GF = layers.Concatenate()([GF,GFdown])\n GF = layers.Dense(filters)(GF)\n GF = layers.Activation('selu')(GF)\n \n x = layers.Add()([x,GFup])\n x = layers.LeakyReLU()(x)\n x = layers.SeparableConv2D(filters, 4,2, padding=\"same\")(x)\n x = layers.BatchNormalization()(x)\n prefilter = filters\n\n #====================== downsampling ============================\n\n for filters in Upfilters:\n\n GFdown = layers.AveragePooling2D((x.shape[1],x.shape[1]))(x)\n GFup = layers.Dense(prefilter)(GF)\n GF = layers.Concatenate()([GF,GFdown])\n GF = layers.Dense(filters)(GF)\n GF = layers.Activation('selu')(GF)\n \n x = layers.Add()([x,GFup])\n x = layers.LeakyReLU()(x)\n x = layers.Conv2DTranspose(filters, 4,2, padding=\"same\")(x)\n x = layers.BatchNormalization()(x)\n prefilter = filters\n\n #====================== last connection =====================\n\n GFup = layers.Dense(prefilter)(x)\n x = layers.Add()([x,GFup])\n outputs = layers.Conv2D(num_classes, 3, activation=\"softmax\", padding=\"same\")(x)\n model = keras.Model(inputs, outputs)\n return model\n\n#model = SVBRDF(9)\n#model.summary()\n'''\ndef UNET(num_classes):\n inputs = keras.Input(shape=(256,256) + (3,))\n\n ### [First half of the network: downsampling inputs] ###\n\n # Entry block\n x = layers.Conv2D(128, 3, strides=2, padding=\"same\")(inputs)\n x = layers.BatchNormalization()(x)\n x = layers.Activation(\"relu\")(x)\n\n previous_block_activation = x # Set aside residual\n\n # Blocks 1, 2, 3 are identical apart from the feature depth.\n for filters in [256,512,512,512,512,512]:\n x = layers.Activation(\"relu\")(x)\n x = layers.SeparableConv2D(filters, 3, padding=\"same\")(x)\n x = layers.BatchNormalization()(x)\n\n x = layers.Activation(\"relu\")(x)\n x = layers.SeparableConv2D(filters, 3, padding=\"same\")(x)\n x = layers.BatchNormalization()(x)\n\n x = layers.MaxPooling2D(3, strides=2, padding=\"same\")(x)\n\n # Project residual\n residual = layers.Conv2D(filters, 1, strides=2, padding=\"same\")(\n previous_block_activation\n )\n x = layers.add([x, residual]) # Add back residual\n previous_block_activation = x # Set aside next residual\n\n ### [Second half of the network: upsampling inputs] ###\n\n for filters in [512,512, 512, 512, 512,256,128]:\n x = layers.Activation(\"relu\")(x)\n x = layers.Conv2DTranspose(filters, 3, padding=\"same\")(x)\n x = layers.BatchNormalization()(x)\n\n x = layers.Activation(\"relu\")(x)\n x = layers.Conv2DTranspose(filters, 3, padding=\"same\")(x)\n x = layers.BatchNormalization()(x)\n\n x = layers.UpSampling2D(2)(x)\n\n # Project residual\n residual = layers.UpSampling2D(2)(previous_block_activation)\n residual = layers.Conv2D(filters, 1, padding=\"same\")(residual)\n x = layers.add([x, residual]) # Add back residual\n previous_block_activation = x # Set aside next residual\n\n # Add a per-pixel classification layer\n outputs = layers.Conv2D(num_classes, 3, activation=\"softmax\", padding=\"same\")(x)\n\n # Define the model\n model = keras.Model(inputs, outputs)\n return model\n'''","repo_name":"BBBBBbruce/DNNreimplement","sub_path":"DesClean/testcode/Code/svbrdf.py","file_name":"svbrdf.py","file_ext":"py","file_size_in_byte":4350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"28305415729","text":"#!/usr/bin/python3\r\n\r\nimport sys,os\r\nimport glob\r\nimport subprocess\r\n\r\nextension=\".cpp\"\r\nsnippet=\"snippet.cpp\"\r\ninput_file = \"input.txt\"\r\noutput_file = \"output.txt\"\r\n\r\n\r\ndef createfile(dirname,file):\r\n\twith open(dirname+\"/\"+file,\"w+\") as f:\r\n\t\tif os.path.exists(snippet):\r\n\t\t\tf.write(open(snippet,\"r\").read())\r\n\r\n\r\ndef io_files():\r\n\tif os.path.exists(input_file):\r\n\t\tos.popen(\"/mnt/c/Program\\ Files/Sublime\\ Text\\ 3/subl.exe \"+input_file)\r\n\tif os.path.exists(output_file):\r\n\t\tos.popen(\"/mnt/c/Program\\ Files/Sublime\\ Text\\ 3/subl.exe \"+output_file)\r\n\r\n\r\n\r\n# To open the files one by one in the samw window by using these options.\r\ndef runFiles(listOfFiles):\r\n\tlistOfFiles.reverse()\r\n\tfor i in listOfFiles:\r\n\t\tos.popen(\"/mnt/c/Program\\ Files/Sublime\\ Text\\ 3/subl.exe \"+i)\r\n\r\n\r\n# To open the directory at once\r\ndef runDirectory(dirname):\r\n\tos.popen(\"/mnt/c/Program\\ Files/Sublime\\ Text\\ 3/subl.exe \"+ dirname)\r\n\r\n\r\n\r\ndef main():\r\n\r\n\t# Check the args\r\n\tif len(sys.argv) != 3:\r\n\t\tprint(\"Usage Format : \" + sys.argv[0] + \" \" + \"{Contest-Name}\" + \" {Problem-Counts}\")\r\n\t\texit()\r\n\r\n\t# Check if the directory exist already with the same name\r\n\r\n\tdirname = str(sys.argv[1])\r\n\tif os.path.exists(dirname):\r\n\t\tprint(\"File or Directory with the name '{}' already exists\".format(dirname))\r\n\t\treturn \r\n\tos.mkdir(dirname)\r\n\r\n\t# Create files in the directory\r\n\r\n\tnumberOfFiles=int(sys.argv[2])\r\n\tfiles=[chr(96+i)+extension for i in range(1,numberOfFiles)]\r\n\tfor i in files:\r\n\t\tcreatefile(dirname,i)\r\n\r\n\r\n\t# Open directory in one instance\r\n\trunDirectory(dirname)\r\n\tio_files()\r\n\t\r\n\t# Open files one by one or open the new directory\r\n\tlistOfFiles=glob.glob(dirname+\"/*.cpp\")\r\n\trunFiles(listOfFiles)\r\n\r\n\t\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\tmain()\r\n","repo_name":"saurav3199/Competitive_with_sublime","sub_path":"make.py","file_name":"make.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"31618131813","text":"import logging\nimport os\nfrom pathlib import Path\n\nfrom cross_encoder import CETrainer\nfrom cross_encoder import CrossEncoder\nfrom cross_encoder.arguments import ModelArguments, DataArguments, \\\n CETrainingArguments as TrainingArguments\nfrom cross_encoder.data import TrainDatasetForCE, PredictionDatasetForCE, GroupCollator\nfrom transformers import AutoConfig, AutoTokenizer\nfrom transformers import (\n HfArgumentParser,\n set_seed,\n)\n\nlogger = logging.getLogger(__name__)\n\n\ndef main():\n parser = HfArgumentParser((ModelArguments, DataArguments, TrainingArguments))\n model_args, data_args, training_args = parser.parse_args_into_dataclasses()\n model_args: ModelArguments\n data_args: DataArguments\n training_args: TrainingArguments\n\n if (\n os.path.exists(training_args.output_dir)\n and os.listdir(training_args.output_dir)\n and training_args.do_train\n and not training_args.overwrite_output_dir\n ):\n raise ValueError(\n f\"Output directory ({training_args.output_dir}) already exists and is not empty. Use --overwrite_output_dir to overcome.\"\n )\n\n # Setup logging\n logging.basicConfig(\n format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\",\n datefmt=\"%m/%d/%Y %H:%M:%S\",\n level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN,\n )\n logger.warning(\n \"Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s\",\n training_args.local_rank,\n training_args.device,\n training_args.n_gpu,\n bool(training_args.local_rank != -1),\n training_args.fp16,\n )\n logger.info(\"Training/evaluation parameters %s\", training_args)\n logger.info(\"Model parameters %s\", model_args)\n logger.info(\"Data parameters %s\", data_args)\n\n # Set seed\n set_seed(training_args.seed)\n\n num_labels = 1\n\n tokenizer = AutoTokenizer.from_pretrained(\n model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,\n cache_dir=model_args.cache_dir,\n use_fast=False,\n )\n config = AutoConfig.from_pretrained(\n model_args.config_name if model_args.config_name else model_args.model_name_or_path,\n num_labels=num_labels,\n cache_dir=model_args.cache_dir,\n )\n _model_class = CrossEncoder\n\n model = _model_class.from_pretrained(\n model_args, data_args, training_args,\n model_args.model_name_or_path,\n from_tf=bool(\".ckpt\" in model_args.model_name_or_path),\n config=config,\n cache_dir=model_args.cache_dir,\n )\n\n # Get datasets\n if training_args.do_train:\n train_dataset = TrainDatasetForCE(\n data_args, tokenizer=tokenizer, train_args=training_args\n )\n else:\n train_dataset = None\n\n # Initialize our Trainer\n _trainer_class = CETrainer\n trainer = _trainer_class(\n model=model,\n args=training_args,\n train_dataset=train_dataset,\n data_collator=GroupCollator(tokenizer),\n )\n\n Path(training_args.output_dir).mkdir(parents=True, exist_ok=True)\n\n # Training\n if training_args.do_train:\n trainer.train()\n trainer.save_model()\n\n if trainer.is_world_process_zero():\n tokenizer.save_pretrained(training_args.output_dir)\n\n if training_args.do_predict:\n logging.info(\"*** Prediction ***\")\n if os.path.exists(data_args.prediction_save_path):\n raise FileExistsError(f\"Existing: {data_args.prediction_save_path}. Please save to other paths\")\n\n test_dataset = PredictionDatasetForCE(\n data_args, tokenizer=tokenizer,\n max_len=data_args.max_len,\n )\n\n pred_scores = trainer.predict(test_dataset=test_dataset).predictions\n\n if trainer.is_world_process_zero():\n assert len(test_dataset) == len(pred_scores)\n with open(data_args.prediction_save_path, \"w\") as writer:\n for pair, score in zip(test_dataset.test_data, pred_scores):\n writer.write(f'{pair[0]}\\t{pair[1]}\\t{score}\\n')\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"staoxiao/RetroMAE","sub_path":"src/cross_encoder/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4184,"program_lang":"python","lang":"en","doc_type":"code","stars":148,"dataset":"github-code","pt":"42"} +{"seq_id":"27021231166","text":"import re\nimport aiohttp\nfrom pydantic import ValidationError\nfrom ..Models.kdca import KDCAModel\nfrom scrapy import Selector\nfrom typing import Union\nfrom app.Exceptions import APIException\n\n\nclass KDCA:\n \"\"\"Korea Disease Control and Prevention Agency\"\"\"\n params: dict[str, Union[int, str]]\n headers: dict[str, str]\n\n def __init__(self) -> None:\n self.ncov_url: str = \"http://ncov.mohw.go.kr/en/bdBoardList.do\"\n self.params = {\"brdId\": 16, \"brdGubun\": 162, \"ncvContSeq\": \"\", \"contSeq\": \"\", \"board_id\": \"\", \"gubun\": \"\"}\n self.headers = {\"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.66\"}\n\n # TODO: Variable naming should be consistently modified [1]\n # region\n self.region_css: str = 'th[scope=row]::text'\n # daily_change\n self.increasing_xpath: str = '//*[@id=\"content\"]/div/div[5]/table/tbody/tr/td[1]/text()'\n # confirmed_cases\n self.cc_sum_xpath: str = '//*[@id=\"content\"]/div/div[5]/table/tbody/tr/td[4]/text()'\n # isolated\n self.isolating_xpath: str = '//*[@id=\"content\"]/div/div[5]/table/tbody/tr/td[5]/text()'\n # recovered\n self.recovered_xpath: str = '//*[@id=\"content\"]/div/div[5]/table/tbody/tr/td[6]/text()'\n # deceased\n self.dead_xpath: str = '//*[@id=\"content\"]/div/div[5]/table/tbody/tr/td[7]/text()'\n # incidence\n self.incidence_xpath: str = '/html/body/div/div[4]/div/div/div/div[5]/table/tbody/tr/td[7]'\n\n\n async def get_html(self) -> str:\n async with aiohttp.ClientSession(headers=self.headers) as session:\n async with session.get(url=self.ncov_url, params=self.params) as resp:\n if resp.status != 200:\n raise APIException(\n status=False,\n system={\n \"message\": \"KDCA connection error\",\n \"code\": resp.status,\n },\n source=None\n )\n res: str = await resp.text()\n return res\n\n @staticmethod\n def remove_tag(content):\n cleanr =re.compile('<.*?>')\n cleantext = re.sub(cleanr, '', content)\n return cleantext\n \n @staticmethod\n async def refactor(source: list) -> list:\n nx = []\n ap = nx.append\n for ix in source:\n x = ix.replace(',', '').replace('-', '0')\n ap(x)\n return nx\n\n @staticmethod\n async def re_pack(source, key) -> list:\n index = []\n _index = index.append\n for x in source[key]:\n js_d = {\n key: x\n }\n _index(js_d)\n return index\n\n @staticmethod\n async def delete(source: list) -> list:\n source.pop(0)\n source.pop(-1)\n return source\n\n async def parse_numbers(self, source: list):\n _ix_a = []\n _ix = _ix_a.append\n for ix in source:\n _ix(self.remove_tag(ix))\n return _ix_a\n\n async def parse_html(self) -> list:\n html = await self.get_html()\n source = Selector(text=html)\n\n region = source.css(self.region_css).getall()\n # TODO: Variable naming should be consistently modified [2]\n increasing = await self.refactor(source.xpath(self.increasing_xpath).getall())\n cc_sum = await self.refactor(source.xpath(self.cc_sum_xpath).getall())\n release_of_quarantine = await self.refactor(source.xpath(self.isolating_xpath).getall())\n dead = await self.refactor(source.xpath(self.recovered_xpath).getall())\n incidence = await self.refactor(await self.parse_numbers(source.xpath(self.incidence_xpath).getall()))\n return [region, increasing, cc_sum, release_of_quarantine, dead, incidence]\n\n async def get_total(self) -> dict:\n src = await self.parse_html()\n pack = {\n 'daily_change': src[1][0],\n 'confirmed_cases': src[2][0],\n 'release_of_quarantine': src[3][0],\n 'deceased': src[4][0],\n 'incidence': src[5][0]\n }\n return pack\n\n async def find_only_region(self) -> dict:\n src = await self.parse_html()\n pack = {\n 'region': await self.delete(src[0]),\n 'daily_change': await self.delete(src[1]),\n 'confirmed_cases': await self.delete(src[2]),\n 'release_of_quarantine': await self.delete(src[3]),\n 'deceased': await self.delete(src[4]),\n 'incidence': await self.delete(src[5])\n }\n try:\n re_typed = KDCAModel(**dict(pack))\n result = re_typed.dict()\n except ValidationError as ex:\n raise APIException(\n status=False,\n system={\n \"message\": f\"KDCA data type validation error: {ex}\",\n \"code\": 422,\n },\n source=None\n )\n return result\n\n async def region_list(self) -> list:\n source = await self.find_only_region()\n region = await self.re_pack(source, \"region\")\n\n nx = []\n _nx = nx.append\n for i in region:\n _nx(i['region'])\n json_data = nx\n return json_data\n\n async def covid_data(self) -> list:\n source = await self.find_only_region()\n pack_1 = await self.re_pack(source, \"region\")\n pack_2 = await self.re_pack(source, \"daily_change\")\n pack_3 = await self.re_pack(source, \"confirmed_cases\")\n pack_4 = await self.re_pack(source, \"release_of_quarantine\")\n pack_6 = await self.re_pack(source, \"deceased\")\n pack_7 = await self.re_pack(source, \"incidence\")\n\n update = []\n _update = update.append\n\n for i in range(0, len(pack_1)):\n json_model = {\n 'region': pack_1[i]['region'],\n \"data\": [\n {**pack_2[i], **pack_3[i], **pack_4[i], **pack_6[i], **pack_7[i]}\n ],\n }\n _update(json_model)\n return update\n\n async def selectRegion(self, region) -> Union[dict, None]:\n source = await self.covid_data()\n for reg in source:\n if reg[\"region\"] == region:\n return {\n \"region\": reg[\"region\"],\n \"data\": reg[\"data\"][0]\n }\n return None\n","repo_name":"zeroday0619/COVID-19API","sub_path":"app/core/KDCA.py","file_name":"KDCA.py","file_ext":"py","file_size_in_byte":6482,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"42"} +{"seq_id":"22714280321","text":"import sqlite3\n\n# შემოგვაქვს ბაზის ობეიქტი\nconn = sqlite3.connect('data.db')\n# ვქმნით კურსორს\ncursor = conn.cursor()\n\nparams = (\"Tetritskaro\", \"წენგოსფერი მცურავი\", \"1-10-2020\", \"არა\", 1.48)\n\ncursor.execute('INSERT INTO snake VALUES (?, ?, ?, ?, ?)', params)\n\n# ვინახავთ (commit) ცვლილებებს\nconn.commit()\n\n# პროცესის დასრულების შემდგომ ვხურავთ კავშირს\nconn.close()\n","repo_name":"temurchichua/UnilabPythonDevelopment","sub_path":"Chapter8_Database/example/sqlite/insert.py","file_name":"insert.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"ka","doc_type":"code","stars":5,"dataset":"github-code","pt":"42"} +{"seq_id":"39725867217","text":"from django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.template import loader\nfrom tablib import Dataset\n\nfrom control.users.forms import UpdateUserForm\nfrom control.users.models import HRUser\nfrom control.users.resources import UserResource\n\n\n@login_required\ndef get_users(request):\n users = HRUser.objects.all()\n\n context = {\n\n 'users': users,\n }\n\n template = loader.get_template('control/users/users.html')\n return HttpResponse(template.render(context=context, request=request))\n\n\n@login_required\ndef get_user_details(request, user_id):\n user = HRUser.objects.get(id=user_id)\n\n if request.method == 'POST':\n\n form = UpdateUserForm(request.POST, instance=user)\n if form.is_valid():\n form.save()\n\n form = UpdateUserForm(instance=user)\n\n context = {\n\n 'hr_user': user,\n 'form': form,\n }\n\n template = loader.get_template('control/users/user_details.html')\n return HttpResponse(template.render(context=context, request=request))\n\n\ndef users_import(request):\n context = {}\n\n if request.method == 'POST':\n\n user_resource = UserResource()\n data_set = Dataset()\n new_users = request.FILES['myfile']\n\n import_data = data_set.load(new_users.read(), format='csv')\n result = user_resource.import_data(data_set, dry_run=True)\n\n if not result.has_errors():\n\n user_resource.import_data(data_set, dry_run=False)\n\n else:\n\n errors = dict(result.row_errors())\n context.update({'errors': errors})\n\n return render(request, 'control/users/import-user.html', context=context)\n","repo_name":"JuanVT/hr_dashboard","sub_path":"control/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"9220680796","text":"import argparse\nimport hashlib\nimport sys\n\nimport clobber_cache_utils\n\n\ndef main(raw_args):\n parser = argparse.ArgumentParser()\n clobber_cache_utils.add_common_args(parser)\n parser.add_argument('--builder', required=True)\n parser.add_argument('--bucket', required=True)\n parser.add_argument('--project', default='chromium')\n parser.add_argument('--pool', default=None)\n parser.add_argument('--bot-id', default=None)\n args = parser.parse_args(raw_args)\n\n # Matches http://bit.ly/2WZO33P\n string_to_hash = '%s/%s/%s' % (args.project, args.bucket, args.builder)\n h = hashlib.sha256(string_to_hash.encode('utf-8'))\n cache = 'builder_%s_v2' % (h.hexdigest())\n pool = args.pool or 'luci.%s.%s' % (args.project, args.bucket)\n\n clobber_cache_utils.clobber_caches(args.swarming_server,\n pool,\n '%s:%s' % (args.project, args.bucket),\n cache,\n 'cache/builder',\n args.dry_run,\n bot_id=args.bot_id)\n\n return 0\n\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv[1:]))\n","repo_name":"chromium/chromium","sub_path":"tools/infra/builder-cache-clobber.py","file_name":"builder-cache-clobber.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","stars":16362,"dataset":"github-code","pt":"42"} +{"seq_id":"2962288108","text":"import random\nimport time\nfrom functools import wraps\n\n\ndef timeit(func):\n \"\"\"Выполнить функцию 'func' с параметрами '*args', '**kwargs' и\n вернуть время выполнения в мс.\"\"\"\n @wraps(func)\n def wrapper(*args, **kwargs):\n time_start = time.time()\n func(*args, **kwargs)\n time_end = time.time()\n return (time_end - time_start) * 1000\n\n return wrapper\n\n\ndef n_pow_2(data):\n \"\"\"Вернуть 'True', если все значения 'data' различны.\n\n Алгоритм 1:\n Пробежимся по списку с первого до последнего элемента и для каждого из\n них проверим, что такого элемента нет в оставшихся справа элементах.\n\n Сложность: O(N^2).\n \"\"\"\n for i in range(len(data)): # O(N)\n if data[i] in data[i+1:]: # O(N) - срез + in: O(N) + O(N) = O(N)\n return False # O(1) - в худшем случае не выполнится\n return True # O(1)\n\n\ndef n_log_n(data):\n \"\"\"Вернуть 'True', если все значения 'data' различны.\n\n Алгоритм 2:\n Отсортируем список. Затем, если в нем есть повторяющиеся элементы, они\n будут расположены рядом — т.о. необходимо лишь попарно их сравнить.\n\n Сложность: O(N Log N).\n \"\"\"\n copy = list(data) # O(N)\n copy.sort() # O(N Log N) - «быстрая» сортировка\n for i in range(len(data) - 1): # O(N) - N-1, округлим до O(N)\n if copy[i] == copy[i+1]: # O(1) - [i] и ==, оба по O(1)\n return False # O(1) - в худшем случае не выполнится\n return True # O(1)\n\n\ndef n(data):\n \"\"\"Вернуть 'True', если все значения 'data' различны.\n\n Алгоритм 3:\n Создадим множество из списка, при создании автоматически удалятся\n дубликаты если они есть. Если длина множества == длине списка, то\n дубликатов нет.\n\n Сложность: O(N).\n \"\"\"\n _set = set(data) # O(N)\n return len(_set) == len(data) # O(1) - 2 * len (O(1)) + == O(1)\n\n\nif __name__ == '__main__':\n s = 5\n funcs = [n, n_log_n, n_pow_2]\n [print(f'{func.__name__:>{s + 3}} |', end=' ') for func in funcs]\n print()\n for size in (10 ** j for j in range(s)):\n sample = random.sample(range(-10 ** s, 10 ** s), size)\n for func in funcs:\n print(f'{timeit(func)(sample):>{s + 3}.2f} |', end=' ')\n print(size)\n","repo_name":"khmaker/pages","sub_path":"_posts/algs/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2979,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"75457088767","text":"import os\nfrom colorama import Fore, init; init()\nfrom PIL import Image\nimport time\n\nfrom .Text import Text\nfrom .Options import Options\nfrom .Encryptor import Encryptor\nfrom .Decryptor import Decryptor\nfrom .ImageCreator import ImageCreator\n\nimport sys; sys.path.append(\"..\")\nfrom constants.constants import *\n\nclass Menu():\n def __init__(self):\n self.create_folders()\n print(f'\\n{Text(\"Max length of the text\",Fore.CYAN)}: {Text(f\"{TXT_MAX_LEN:,}\",Fore.GREEN)} (you can change it in {Text(\"config.py\",Fore.LIGHTYELLOW_EX)}')\n option = Options([\"EXIT\", \"Encrypt\", \"Decrypt text\", \"Decrypt image\"]).get_choice()\n \n if option == 0: \n exit()\n\n elif option == 1: \n self.encrypt()\n\n elif option == 2:\n self.decrypt_text()\n\n elif option == 3:\n self.decrypt_image()\n\n \n def create_folders(self):\n if not os.path.exists(INPUT_DIR): os.mkdir(INPUT_DIR)\n if not os.path.exists(OUTPUT_DIR): os.mkdir(OUTPUT_DIR)\n\n\n def encrypt(self):\n text = open(self.get_input_file(\"Text filename: \", \"txt\")).read()\n pwd = input(\"Password: \")\n enc_text_file = self.get_file(\"New text filename: \", \"txt\")\n enc_img_file = self.get_file(\"New image filename: \", \"png\") if self.yes_no(\"Save image? [y/n]: \") else None\n\n t1 = time.time()\n try:\n encrypted_text = Encryptor(text, pwd).encrypt()\n self.save_text(encrypted_text, enc_text_file)\n print(Text(\"\\nText encrypted succesfully\\n\", Fore.GREEN))\n if enc_img_file:\n self.save_img(encrypted_text, enc_img_file)\n print(Text(\"Image saved\", Fore.GREEN))\n except Exception as e:\n print(Text(f\"Error: {e}\", Fore.RED))\n return\n\n print(Text(f\"\\nDone in {time.time() - t1:.2f} seconds\", Fore.LIGHTYELLOW_EX))\n\n\n def decrypt(self, ciphertext:str) -> str:\n pwd = input(\"Password: \")\n dec_text_file = self.get_file(\"New filename: \", \"txt\")\n\n t1 = time.time()\n try:\n decypted_text = Decryptor(ciphertext, pwd).decrypt()\n self.save_text(decypted_text, dec_text_file)\n print(Text(\"\\nText decrypted succesfully\\n\", Fore.GREEN))\n except Exception as e:\n print(Text(f\"Error: {e}\", Fore.RED))\n return\n\n print(Text(f\"\\nDone in {time.time() - t1:.2f} seconds\", Fore.LIGHTYELLOW_EX))\n\n\n def decrypt_text(self):\n ciphertext = open(self.get_input_file(\"Ciphertext filename: \", \"txt\")).read()\n self.decrypt(ciphertext)\n\n\n def decrypt_image(self):\n ciphertext = self.img_to_text(self.get_input_file(\"Cipher image filename: \", \"png\"))\n self.decrypt(ciphertext)\n\n\n def img_to_text(self, img_file:str) -> str:\n img_arr = np.array(Image.open(img_file)).flatten()\n img_str = \"\".join([f'{n:02x}' for n in img_arr])\n return img_str\n\n\n def yes_no(self, msg:str=\"Save? [y/n]: \") -> bool:\n inp = input(msg)\n if inp.lower() == \"y\": return True\n elif inp.lower() == \"n\": return False\n else: return self.yes_no(msg)\n\n\n def save_text(self, text:str, file:str):\n with open(f\"{OUTPUT_DIR}/{file}\", \"w\") as f:\n f.write(text)\n\n\n def save_img(self, text:str, file:str):\n img_arr = ImageCreator(text).get_img_arr()\n Image.fromarray(img_arr).save(f\"{OUTPUT_DIR}/{file}\")\n\n\n def get_file(self, msg:str, ext:str) -> str:\n while True:\n filename = input(msg)\n if \".\" in filename:\n if filename.endswith(f\".{ext}\"): return filename\n print(Text(\"Invalid extension\", Fore.RED))\n continue\n return f\"{filename}.{ext}\"\n\n\n def get_input_file(self, msg:str, ext:str) -> str:\n while True:\n file = self.get_file(msg, ext)\n path = f\"{INPUT_DIR}/{file}\"\n if os.path.exists(path): return path\n print(Text(\"File not found\",Fore.RED))","repo_name":"carlospuenteg/Encroval","sub_path":"classes/Menu.py","file_name":"Menu.py","file_ext":"py","file_size_in_byte":4035,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"42"} +{"seq_id":"43753515364","text":"from selenium import webdriver\nimport datetime\nimport random\nimport time\n\nwd = webdriver.Chrome()\nwd.get('https://www.instagram.com')\ntime.sleep(1)\n\n#ログインする\ndef login():\n wd.find_element_by_name('username').send_keys(username)\n time.sleep(1)\n wd.find_element_by_name('password').send_keys(password)\n time.sleep(1)\n wd.find_element_by_class_name('L3NKy ').click()\n time.sleep(random.randint(3, 4))\n\n#タグ検索し、最新の投稿に移動する\ndef search(tag):\n address = 'https://www.instagram.com/explore/tags/'\n wd.get(address + tag)\n time.sleep(random.randint(3, 4))\n wd.find_elements_by_class_name('_9AhH0')[10].click()\n time.sleep(random.randint(3, 4))\n\n#いいねを押す\ndef like():\n global like_cnt\n #例外処理\n try:\n wd.find_element_by_class_name('coreSpriteRightPaginationArrow').click()\n time.sleep(random.randint(3, 4))\n wd.find_element_by_class_name('fr66n').click()\n time.sleep(random.randint(1, 2))\n like_cnt += 1\n except:\n print('エラーが発生しました')\n time.sleep(5)\n return \n\nif __name__ == '__main__':\n\n #ユーザ名とパスワード\n username = 'your_username'\n password = 'your_password'\n\n #タグ設定\n tags = ['l4l','いいね返し','いいねした人で気になった人フォロー','写真好きな人と繋がりたい']\n\n like_cnt = 0\n begin = datetime.datetime.today()\n tag = random.choice(tags)\n\n login()\n search(tag)\n\n #いいね数設定\n while like_cnt < 100:\n like()\n\n wd.quit()\n end = datetime.datetime.today()\n\n print('開始時刻:' + str(begin))\n print('終了時刻:' + str(end))\n print('今回のタグは「 ' + tag + ' 」 いいねした数:' + str(like_cnt))","repo_name":"zzq-s/instabot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"ja","doc_type":"code","stars":66,"dataset":"github-code","pt":"42"} +{"seq_id":"21074402557","text":"import asyncio\nimport json\n\nfrom loko_client.utils.logger_utils import stream_logger\n\nlogger = stream_logger(__name__)\n\nclass AsyncJobsClient:\n def __init__(self, u):\n self.u = u.jobs\n\n async def all(self):\n r = await self.u.request('GET')\n return await r.json()\n\n async def delete(self, job):\n r = await self.u[job].request('DELETE')\n return await r.json()\n\n async def info(self, job):\n r = await self.u[job].request('GET')\n return await r.json()\n\nclass AsyncContainersClient:\n def __init__(self, u):\n self.u = u.containers\n\n async def all(self):\n r = await self.u.request('GET')\n return await r.json()\n\n async def info(self, container):\n r = await self.u[container].request('GET')\n return await r.json()\n\n async def delete(self, container):\n r = await self.u[container].request('DELETE')\n return await r.json()\n\nclass AsyncPredictorsClient:\n def __init__(self, u):\n self.u = u.predictors\n self.jobs = AsyncJobsClient(u=u)\n\n async def all(self):\n r = await self.u.request('GET')\n return await r.json()\n\n async def info(self, predictor, details=True, branch='development'):\n details = json.dumps(details)\n r = await self.u[predictor].request('GET', params=dict(details=details, branch=branch))\n return await r.json()\n\n async def save(self, predictor, description='', model_id='auto', transformer_id='auto', blueprint=None):\n blueprint = blueprint or {}\n r = await self.u[predictor].request('POST', json=blueprint,\n params=dict(description=description, model_id=model_id,\n transformer_id=transformer_id))\n return await r.json()\n\n async def delete(self, predictor):\n r = await self.u[predictor].request('DELETE')\n return await r.json()\n\n async def fit(self, predictor, data, partial=False, fit_params=None, cv=0, report=True, history_limit=0,\n test_size=.2, task=None, save_dataset=False, wait=False):\n report = json.dumps(report)\n partial = json.dumps(partial)\n save_dataset = json.dumps(save_dataset)\n task = task or 'null'\n fit_params = fit_params or {}\n fit_params = json.dumps(fit_params)\n params = dict(partial=partial, fit_params=fit_params, cv=cv, report=report, history_limit=history_limit,\n test_size=test_size, task=task, save_dataset=save_dataset)\n r = await self.u[predictor].fit.request('POST', params=params, json=data)\n\n if not wait:\n return await r.json()\n else:\n logger.debug('WAIT FOR JOB')\n last_msg = ''\n while True:\n await asyncio.sleep(2)\n res = await self.jobs.info(predictor)\n if res:\n new_msg = res[-1]['status']\n if last_msg != new_msg:\n logger.debug(f'STATUS: {new_msg}')\n last_msg = new_msg\n if res[-1]['status'] == 'Pipeline END':\n return 'OK'\n if any([el['status'].startswith('ERROR') for el in res]):\n return 'ERROR'\n\n async def predict(self, predictor, data, include_probs=False, branch='development'):\n include_probs = json.dumps(include_probs)\n r = await self.u[predictor].predict.request('POST', json=data,\n params=dict(include_probs=include_probs, branch=branch))\n return await r.json()\n\n async def evaluate(self, predictor, data, branch='development', limit=0, pretty=False):\n pretty = json.dumps(pretty)\n r = await self.u[predictor].evaluate.request('POST', json=data,\n params=dict(branch=branch, limit=limit, pretty=pretty))\n return await r.json()\n\n async def upload(self, predictor_file):\n r = await self.u['import'].request('POST', data={'f': predictor_file})\n return await r.json()\n\n async def download(self, predictor):\n r = await self.u[predictor].export.request('GET')\n return r.content\n\n async def release(self, predictor, history_limit=0):\n r = await self.u[predictor].release.request('GET', params=dict(history_limit=history_limit))\n return await r.json()\n\n async def rollback(self, predictor, branch='development'):\n r = await self.u[predictor].rollback.request('GET', params=dict(branch=branch))\n pass\n\n async def copy(self, predictor, new_name=None):\n new_name = new_name or 'null'\n r = await self.u[predictor].copy.request('GET', params=dict(new_name=new_name))\n return await r.json()\n\n async def history(self, predictor, pretty=False):\n pretty = json.dumps(pretty)\n r = await self.u[predictor].history.request('GET', params=dict(pretty=pretty))\n return await r.json()\n\n\nclass AsyncModelsClient:\n def __init__(self, u):\n self.u = u.models\n\n async def all(self):\n r = await self.u.request('GET')\n return await r.json()\n\n async def save(self, model, blueprint):\n r = await self.u[model].request('POST', json=blueprint)\n return await r.json()\n\n async def delete(self, model):\n r = await self.u[model].request('DELETE')\n return await r.json()\n\n async def info(self, model):\n r = await self.u[model].request('GET')\n return await r.json()\n\nclass AsyncTransformersClient:\n def __init__(self, u):\n self.u = u.transformers\n\n async def all(self):\n r = await self.u.request('GET')\n return await r.json()\n\n async def save(self, transformer, blueprint):\n r = await self.u[transformer].request('POST', json=blueprint)\n return await r.json()\n\n async def delete(self, transformer):\n r = await self.u[transformer].request('DELETE')\n return await r.json()\n\n async def info(self, transformer):\n r = await self.u[transformer].request('GET')\n return await r.json()\n\nclass AsyncDatasetsClient:\n def __init__(self, u):\n self.u = u.datasets\n\n async def all(self):\n r = await self.u.request('GET')\n return await r.json()\n\n async def info(self, dataset):\n r = await self.u[dataset].request('GET')\n return await r.json()\n\n async def delete(self, dataset):\n r = await self.u[dataset].request('DELETE')\n return await r.json()\n\n async def upload(self, dataset_file):\n r = await self.u['import'].request('POST', data={'f': dataset_file})\n return await r.json()\n\n async def download(self, dataset):\n r = await self.u[dataset].export.request('GET')\n return r.content\n\n\n","repo_name":"loko-ai/loko-client","sub_path":"loko_client/business/async_predictor_client.py","file_name":"async_predictor_client.py","file_ext":"py","file_size_in_byte":6902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"70876407168","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\n训练文件\n\n\"\"\"\nimport os\nimport time, datetime\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.contrib.tensorboard.plugins import projector\n\nfrom cnn_params_flags import FLAGS\nfrom process_data import load_data_and_labels, padding_sentences, batch_iter\nfrom word2vec_helpers import embedding_sentences\nfrom text_cnn import TextCNN\n\nfrom _compat import *\n\n\ndef preprocess():\n \"\"\"\n 数据准备阶段\n\n :return:\n \"\"\"\n # 1. 加载数据文件\n x_text, y = load_data_and_labels(FLAGS.positive_data_file, FLAGS.negative_data_file)\n\n # 文本进行向量化\n sentences, max_document_length = padding_sentences(x_text, '<PAD>')\n x = np.array(embedding_sentences(sentences, FLAGS.word2vec_fname))\n y = np.array(list(y))\n print(\"x.shape = {}\".format(x.shape))\n print(\"y.shape = {}\".format(y.shape))\n\n # shuffle 数据\n np.random.seed(10)\n shuffle_indices = np.random.permutation(np.arange(len(y)))\n x_shuffled = x[shuffle_indices]\n y_shuffled = y[shuffle_indices]\n\n # 分拆数据,训练和测试\n dev_sample_index = -1 * int(FLAGS.dev_sample_percentage * float(len(y)))\n x_train, x_dev = x_shuffled[:dev_sample_index], x_shuffled[dev_sample_index:]\n y_train, y_dev = y_shuffled[:dev_sample_index], y_shuffled[dev_sample_index:]\n\n del x, y, x_shuffled, y_shuffled\n\n print(\"Train/Dev split: {:d}/{:d}\".format(len(y_train), len(y_dev)))\n return x_train, y_train, x_dev, y_dev\n\n\ndef train(x_train, y_train, x_dev, y_dev):\n # 训练\n with tf.Graph().as_default():\n session_conf = tf.ConfigProto(\n allow_soft_placement=FLAGS.allow_soft_placement,\n log_device_placement=FLAGS.log_device_placement)\n sess = tf.Session(config=session_conf)\n\n with sess.as_default():\n # 实例化TextCNN模型,所有定义的变量和操作就会被放进默认的计算图和会话。\n cnn = TextCNN(\n sequence_length=x_train.shape[1],\n num_classes=y_train.shape[1],\n embedding_size=FLAGS.embedding_dim,\n filter_sizes=list(map(int, FLAGS.filter_sizes.split(\",\"))),\n num_filters=FLAGS.num_filters,\n l2_reg_lambda=FLAGS.l2_reg_lambda)\n # 模型参数\n params = {\n 'sequence_length': x_train.shape[1],\n 'num_classes': y_train.shape[1],\n 'embedding_size': FLAGS.embedding_dim,\n 'filter_sizes': FLAGS.filter_sizes,\n 'num_filters': FLAGS.num_filters,\n }\n\n # 定义训练过程\n # 优化网络损失函数。这里使用Adam优化\n global_step = tf.Variable(0, trainable=False, name=\"global_step\")\n optimizer = tf.train.AdamOptimizer(1e-3)\n grads_and_vars = optimizer.compute_gradients(cnn.loss)\n train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step)\n # train是新建的操作,用来对参数做梯度更新,每一次运行train_op就是一次训练。 tf会自动识别出那些参数是“可计算的”,然后计算他们的梯度。\n # 定义了global_step变量并传入优化器,就可以让TF来完成计数,每运行一次train_op,global_step就+1\n\n # 定义汇总信息\n # Output directory for models and summaries\n timestamp = str(int(time.time()))\n out_dir = os.path.abspath(os.path.join(os.path.curdir, \"runs\", timestamp))\n print(\"Writing to {}\\n\".format(out_dir))\n\n # loss 和 accuracy\n loss_summary = tf.summary.scalar(\"loss\", cnn.loss)\n acc_summary = tf.summary.scalar(\"accuracy\", cnn.accuracy)\n\n # 训练汇总\n train_summary_op = tf.summary.merge([loss_summary, acc_summary])\n train_summary_dir = os.path.join(out_dir, \"summaries\", \"train\")\n train_summary_writer = tf.summary.FileWriter(train_summary_dir, sess.graph)\n\n # Dev summaries\n dev_summary_op = tf.summary.merge([loss_summary, acc_summary])\n dev_summary_dir = os.path.join(out_dir, \"summaries\", \"dev\")\n dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph)\n\n # 检查点\n checkpoint_dir = os.path.abspath(os.path.join(out_dir, \"checkpoints\"))\n checkpoint_prefix = os.path.join(checkpoint_dir, \"model.ckpt\")\n\n # 检查目录是否存在,TF会假定存在\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n saver = tf.train.Saver(tf.global_variables(), max_to_keep=FLAGS.num_checkpoints)\n\n projector_writer = tf.summary.FileWriter(checkpoint_dir, sess.graph)\n config = projector.ProjectorConfig()\n embed = config.embeddings.add()\n embed.tensor_name = 'input_x'\n embed.metadata_path = os.path.join(checkpoint_dir, 'metadata.tsv')\n projector.visualize_embeddings(projector_writer, config)\n\n # 保存模型参数,评估时会使用\n with open(os.path.join(out_dir, 'params'), 'w', encoding='utf-8') as f:\n f.write(str(params))\n\n # 变量初始化\n sess.run(tf.global_variables_initializer())\n\n # 定义单步训练\n def train_step(x_batch, y_batch):\n # 喂数据\n feed_dict = {\n cnn.input_x: x_batch,\n cnn.input_y: y_batch,\n cnn.dropout_keep_prob: FLAGS.dropout_keep_prob\n }\n\n _, step, summaries, loss, accuracy = sess.run(\n [train_op, global_step, train_summary_op, cnn.loss, cnn.accuracy],\n feed_dict)\n\n time_str = datetime.datetime.now().isoformat()\n print(\"{}: step {}, loss {:g}, acc {:g}\".format(time_str, step, loss, accuracy))\n train_summary_writer.add_summary(summaries, step)\n\n # 评估模型过程\n def dev_step(x_batch, y_batch, writer=None):\n feed_dict = {\n cnn.input_x: x_batch,\n cnn.input_y: y_batch,\n cnn.dropout_keep_prob: 1.0\n }\n\n step, summaries, loss, accuracy = sess.run(\n [global_step, dev_summary_op, cnn.loss, cnn.accuracy],\n feed_dict)\n\n time_str = datetime.datetime.now().isoformat()\n print(\"{}: step {}, loss {:g}, acc {:g}\".format(time_str, step, loss, accuracy))\n if writer:\n writer.add_summary(summaries, step)\n\n # 生成批处理\n batches = batch_iter(\n list(zip(x_train, y_train)), FLAGS.batch_size, FLAGS.num_epochs)\n for batch in batches:\n x_batch, y_batch = zip(*batch)\n train_step(x_batch, y_batch)\n current_step = tf.train.global_step(sess, global_step)\n\n if current_step % FLAGS.evaluate_every == 0:\n print(\"\\nEvaluation:\")\n dev_step(x_dev, y_dev, writer=dev_summary_writer)\n print(\"\")\n\n if current_step % FLAGS.checkpoint_every == 0:\n path = saver.save(sess, checkpoint_prefix, global_step=current_step)\n print(\"Saved model checkpoint to {}\\n\".format(path))\n\n\ndef main(argv=None):\n x_train, y_train, x_dev, y_dev = preprocess()\n train(x_train, y_train, x_dev, y_dev)\n\n\nif __name__ == \"__main__\":\n tf.app.run()\n","repo_name":"chufucun/deep-learning","sub_path":"cnn-text-classification-zh/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7652,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"37145917755","text":"import os\nimport sys\nimport time\nimport logging\nimport subprocess\n\nimport click\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\nfrom watchdog.observers.api import DEFAULT_OBSERVER_TIMEOUT\n\n\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s - %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S')\n\n\nclass COLORS(object):\n PURPLE = '\\033[95m'\n BLUE = '\\033[94m'\n GREEN = '\\033[92m'\n YELLOW = '\\033[93m'\n RED = '\\033[91m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n END = '\\033[0m'\n\n\ndef _get_what(event):\n return 'directory' if event.is_directory else 'file'\n\n\nclass RSyncEventHandler(FileSystemEventHandler):\n \"\"\"RSync when the events captured.\"\"\"\n\n def __init__(self, local_path, remote_path, rsync_options=''):\n self.local_path = local_path\n self.remote_path = remote_path\n self.rsync_options = rsync_options.split()\n self.rsync()\n\n @staticmethod\n def log(log, color):\n logging.info('{}{}{}'.format(color, log, COLORS.END))\n\n def on_moved(self, event):\n super(RSyncEventHandler, self).on_moved(event)\n\n what = _get_what(event)\n self.log(\n 'Moved {}: from {} to {}'.format(\n what,\n event.src_path,\n event.dest_path\n ),\n COLORS.BLUE\n )\n\n self.rsync()\n\n def on_created(self, event):\n super(RSyncEventHandler, self).on_created(event)\n\n what = _get_what(event)\n self.log(\n 'Created {}: {}'.format(what, event.src_path),\n COLORS.GREEN\n )\n\n self.rsync()\n\n def on_deleted(self, event):\n super(RSyncEventHandler, self).on_deleted(event)\n\n what = _get_what(event)\n self.log(\n 'Deleted {}: {}'.format(what, event.src_path),\n COLORS.RED\n )\n\n self.rsync()\n\n def on_modified(self, event):\n super(RSyncEventHandler, self).on_modified(event)\n\n what = _get_what(event)\n self.log(\n 'Modified {}: {}'.format(what, event.src_path),\n COLORS.YELLOW\n )\n\n self.rsync()\n\n def rsync(self, relative_path=None):\n self.log('RSyncing', COLORS.PURPLE)\n\n local_path = self.local_path\n remote_path = self.remote_path\n if relative_path is not None:\n local_path = os.path.join(local_path, relative_path)\n remote_path = os.path.join(remote_path, relative_path)\n\n cmd = 'rsync -avzP {} {} {}'.format(\n ' '.join(self.rsync_options), local_path, remote_path\n )\n self.log(cmd, COLORS.BOLD)\n with open(os.devnull, 'w') as DEVNULL:\n subprocess.call(\n cmd.split(' '),\n stdout=DEVNULL,\n stderr=subprocess.STDOUT\n )\n\n\n@click.command()\n@click.argument('local-path')\n@click.argument('remote-path')\n@click.option(\n '--observer-timeout',\n default=DEFAULT_OBSERVER_TIMEOUT,\n help='The observer timeout, default {}'.format(\n DEFAULT_OBSERVER_TIMEOUT\n )\n)\n@click.option('--rsync-options', default='', help='rsync command options')\n@click.option('--rsync-file-opts', default=None, help='file with rsync options')\ndef main(\n local_path, remote_path,\n observer_timeout, rsync_options, rsync_file_opts\n):\n if subprocess.call(['which', 'rsync']) != 0:\n print(\n COLORS.RED +\n 'Can\\'t find the `rsync` program, you need to install it.' +\n COLORS.END\n )\n sys.exit(1)\n\n if rsync_file_opts:\n with open(rsync_file_opts) as opts_file:\n opts = map(str.strip, opts_file)\n rsync_options += u' '.join(opts)\n\n event_handler = RSyncEventHandler(local_path, remote_path, rsync_options)\n observer = Observer(timeout=observer_timeout)\n observer.schedule(event_handler, local_path, recursive=True)\n observer.start()\n try:\n while True:\n time.sleep(1)\n except KeyboardInterrupt:\n observer.stop()\n observer.join()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"yetone/auto-rsync","sub_path":"auto_rsync/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4147,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"41"} +{"seq_id":"29154414547","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport os\nfrom torch.distributions import Categorical\nfrom AdasOptimizer.adasopt_pytorch import Adas\nfrom torch.optim import Adam, SGD\nfrom collections import deque\nfrom tqdm import tqdm\nfrom src.utils import dotdict, AverageMeter, plot\n\nEPS = 0.001\n\ndef fanin_init(size, fanin=None):\n\tfanin = fanin or size[0]\n\tv = 1. / np.sqrt(fanin)\n\treturn torch.Tensor(size).uniform_(-v, v)\n\nargs = dotdict({\n 'lr': 0.005,\n 'dropout': 0.5,\n 'epochs': 20,\n 'batch_size': 256,\n 'cuda': torch.cuda.is_available(),\n 'num_channels': 256,\n 'optimizer': 'adas',\n})\n\n# 3x3 convolution\ndef conv3x3(in_channels, out_channels, stride=1):\n return nn.Conv2d(in_channels, out_channels, kernel_size=3, \n stride=stride, padding=1, bias=False)\n\n# Residual block\nclass ResidualBlock(nn.Module):\n def __init__(self, in_channels, out_channels, stride=1, downsample=None):\n super(ResidualBlock, self).__init__()\n self.conv1 = conv3x3(in_channels, out_channels, stride)\n self.bn1 = nn.BatchNorm2d(out_channels)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(out_channels, out_channels)\n self.bn2 = nn.BatchNorm2d(out_channels)\n self.downsample = downsample\n \n def forward(self, x):\n residual = x\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n out = self.conv2(out)\n out = self.bn2(out)\n if self.downsample:\n residual = self.downsample(x)\n out += residual\n out = self.relu(out)\n return out\n# ResNet\nclass ResNet(nn.Module):\n def __init__(self, block, layers, num_classes=10):\n super(ResNet, self).__init__()\n self.in_channels = args.num_channels\n self.device = 'cuda' if torch.cuda.is_available() else 'cpu'\n self.layer1 = self.make_layer(block, args.num_channels, layers[0])\n self.layer2 = self.make_layer(block, args.num_channels, layers[1], 2)\n self.layer3 = self.make_layer(block, args.num_channels, layers[2], 2)\n self.avg_pool = nn.AvgPool2d(2)\n \n def make_layer(self, block, out_channels, blocks, stride=1):\n downsample = None\n if (stride != 1) or (self.in_channels != out_channels):\n downsample = nn.Sequential(\n conv3x3(self.in_channels, out_channels, stride=stride).to(self.device),\n nn.BatchNorm2d(out_channels))\n layers = []\n layers.append(block(self.in_channels, out_channels, stride, downsample))\n self.in_channels = out_channels\n for i in range(1, blocks):\n layers.append(block(out_channels, out_channels))\n return nn.Sequential(*layers)\n \n def forward(self, x):\n out = self.layer1(x)\n out = self.layer2(out)\n out = self.layer3(out)\n out = self.avg_pool(out)\n return out\n \nclass Policy(nn.Module):\n def __init__(self, env):\n # game params\n self.board_x, self.board_y = env.get_ub_board_size()\n self.action_size = env.n_actions\n self.n_inputs = env.n_inputs\n self.lr = args.lr\n self.env = env\n self.device = 'cuda' if torch.cuda.is_available() else 'cpu'\n\n super(Policy, self).__init__()\n self.conv1 = nn.Conv2d(self.n_inputs, args.num_channels, 3, stride=1, padding=1).to(self.device)\n self.conv2 = nn.Conv2d(args.num_channels, args.num_channels, 3, stride=1, padding=1).to(self.device)\n self.conv3 = nn.Conv2d(args.num_channels, args.num_channels, 3, stride=1).to(self.device)\n self.conv4 = nn.Conv2d(args.num_channels, args.num_channels, 3, stride=1).to(self.device)\n \n self.bn1 = nn.BatchNorm2d(args.num_channels).to(self.device)\n self.bn2 = nn.BatchNorm2d(args.num_channels).to(self.device)\n self.bn3 = nn.BatchNorm2d(args.num_channels).to(self.device)\n self.bn4 = nn.BatchNorm2d(args.num_channels).to(self.device)\n \n self.resnet = ResNet(ResidualBlock, [2, 2, 2]).to(self.device) \n \n self.last_channel_size = int(args.num_channels) * int(int(int((self.board_x + 1) / 2) + 1) / 2 / 2) \\\n * int(int(int((self.board_y + 1) / 2) + 1) / 2 / 2)\n self.fc1 = nn.Linear(self.last_channel_size + env.agent_step_dim, 1024).to(self.device)\n self.fc_bn1 = nn.BatchNorm1d(1024).to(self.device)\n\n self.fc2 = nn.Linear(1024, 512).to(self.device)\n self.fc_bn2 = nn.BatchNorm1d(512).to(self.device)\n\n self.fc3 = nn.Linear(512, self.action_size).to(self.device)\n\n self.fc4 = nn.Linear(512, 1).to(self.device)\n \n self.entropies = 0\n self.pi_losses = AverageMeter()\n self.v_losses = AverageMeter()\n self.action_probs = [[], []]\n self.state_values = [[], []]\n self.rewards = [[], []]\n self.next_states = [[], []]\n if args.optimizer == 'adas':\n self.optimizer = Adas(self.parameters(), lr=self.lr)\n elif args.optimizer == 'adam':\n self.optimizer = Adam(self.parameters(), lr=self.lr)\n else:\n self.optimizer = SGD(self.parameters(), lr=self.lr)\n\n def forward(self, s, agent):\n # s: batch_size x n_inputs x board_x x board_y\n s = s.view(-1, self.n_inputs, self.board_x, self.board_y) # batch_size x n_inputs x board_x x board_y\n s = F.relu(self.bn1(self.conv1(s))) # batch_size x num_channels x board_x x board_y\n s = F.relu(self.bn2(self.conv2(s))) # batch_size x num_channels x board_x x board_y\n # s = F.relu(self.bn3(self.conv3(s))) # batch_size x num_channels x (board_x-2) x (board_y-2)\n # s = F.relu(self.bn4(self.conv4(s))) # batch_size x num_channels x (board_x-4) x (board_y-4)\n s = F.relu(self.resnet(s))\n s = s.view(-1, self.last_channel_size)\n s = torch.cat((s,agent),dim=1)\n s = F.dropout(F.relu(self.fc1(s)), p=args.dropout, training=self.training) # batch_size x 1024\n s = F.dropout(F.relu(self.fc2(s)), p=args.dropout, training=self.training) # batch_size x 512\n\n pi = self.fc3(s) # batch_size x action_size\n v = self.fc4(s) # batch_size x 1\n\n return F.log_softmax(pi, dim=1), v # torch.tanh(v)\n \n def step(self, obs, agent):\n \"\"\"\n Returns policy and value estimates for given observations.\n :param obs: Array of shape [N] containing N observations.\n :return: Policy estimate [N, n_actions] and value estimate [N] for\n the given observations.\n \"\"\"\n obs = torch.from_numpy(obs).to(self.device)\n agent = torch.from_numpy(agent).to(self.device)\n pi, v = self.forward(obs, agent)\n\n return torch.exp(pi).detach().to('cpu').numpy(), v.detach().to('cpu').numpy()\n\n def store(self, player_ID, prob, state_value, reward):\n self.action_probs[player_ID].append(prob)\n self.state_values[player_ID].append(state_value)\n self.rewards[player_ID].append(reward)\n \n def clear(self):\n self.action_probs = [[], []]\n self.state_values = [[], []]\n self.rewards = [[], []]\n self.next_states = [[], []]\n self.entropies = 0\n \n def get_data(self):\n return self.action_probs, self.state_values, self.rewards\n \n def optimize(self):\n self.optimizer.step()\n \n def reset_grad(self):\n self.optimizer.zero_grad()\n\n def train_examples(self, examples):\n \"\"\"\n examples: list of examples, each example is of form (board, pi, v)\n \"\"\"\n if len(examples) < args.batch_size: return\n\n for epoch in range(args.epochs):\n # print('\\nEPOCH ::: ' + str(epoch + 1))\n self.train()\n batch_count = int(len(examples) / args.batch_size)\n t = tqdm(range(batch_count), desc='Training Net')\n for _ in t:\n sample_ids = np.random.randint(len(examples), size=args.batch_size)\n boards, agent_steps, pis, vs = list(zip(*[examples[i] for i in sample_ids]))\n boards = self.env.get_states_for_step(boards)\n agent_steps = self.env.get_agents_for_step(agent_steps)\n boards = torch.FloatTensor(boards.astype(np.float64)).to(self.device)\n agent_steps = torch.FloatTensor(agent_steps.astype(np.float64)).to(self.device)\n target_pis = torch.FloatTensor(np.array(pis))\n target_vs = torch.FloatTensor(np.array(vs).astype(np.float64))\n\n # predict\n if self.device == 'cuda':\n boards, target_pis, target_vs = boards.contiguous().cuda(), target_pis.contiguous().cuda(), target_vs.contiguous().cuda()\n\n # compute output\n out_pi, out_v = self.forward(boards, agent_steps)\n l_pi = self.loss_pi(target_pis, out_pi)\n l_v = self.loss_v(target_vs, out_v)\n total_loss = l_pi + l_v\n\n # record loss\n self.pi_losses.update(l_pi.item(), boards.size(0))\n self.v_losses.update(l_v.item(), boards.size(0))\n t.set_postfix(Loss_pi=self.pi_losses, Loss_v=self.v_losses)\n # compute gradient and do Adas step\n self.reset_grad()\n total_loss.backward()\n self.optimize()\n \n # self.pi_losses.plot('PolicyLoss')\n # self.v_losses.plot('ValueLoss')\n \n def loss_pi(self, targets, outputs):\n return -torch.sum(targets * outputs) / targets.size()[0]\n\n def loss_v(self, targets, outputs):\n return torch.sum((targets - outputs.view(-1)) ** 2) / targets.size()[0]\n\n def save_checkpoint(self, folder='Models', filename='model.pt'):\n filepath = os.path.join(folder, filename)\n if not os.path.exists(folder):\n print(\"Checkpoint Directory does not exist! Making directory {}\".format(folder))\n os.mkdir(folder)\n else:\n print(\"Checkpoint Directory exists! \")\n torch.save({\n 'state_dict': self.state_dict(),\n }, filepath)\n \n \n def load_checkpoint(self, folder='Models', filename='model.pt'):\n # https://github.com/pytorch/examples/blob/master/imagenet/main.py#L98\n filepath = os.path.join(folder, filename) \n if not os.path.exists(filepath):\n raise (\"No model in path {}\".format(filepath))\n checkpoint = torch.load(filepath, map_location=self.device)\n self.load_state_dict(checkpoint['state_dict'])\n # self.load_state_dict(checkpoint)\n print('-- Load model succesfull!')\n \n def load_colab_model(self, _dir):\n self.load_state_dict(torch.load(_dir, map_location = self.device))\n \n def save_colab_model(self, _dir):\n torch.save(self.state_dict(), _dir)\n","repo_name":"NeiH4207/Actor_Critic_MultiAgent","sub_path":"src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":11247,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"41"} +{"seq_id":"23613461082","text":"from fastapi import HTTPException, status, APIRouter\nimport requests\nfrom schemas.auth_schema import UsuarioAuthConfig\n\nauth_router = APIRouter()\n\n@auth_router.get('/erp/oracle-analytics-token',tags=[\"AUTH\"])\ndef oracleAnalyticsToken():\n\n # URL de la API REST\n url = 'https://sweb3.grupotsiperu.com.pe:8835/erp/api/rest/general/public/oracle-analytics-token'\n\n # Realizar la solicitud GET\n # response = requests.get(url)\n\n response = requests.get(url, verify=False)\n\n # Comprobar el estado de la respuesta\n if response.status_code == 200:\n # Obtener los datos de la respuesta\n data = response.json()\n # Aquí puedes realizar cualquier manipulación de los datos obtenidos\n\n # Devolver los datos como respuesta en formato JSON\n return data\n else:\n # Devolver un mensaje de error en caso de que la solicitud no sea exitosa\n return {\"error\": \"Error al realizar la solicitud GET\"}\n\n@auth_router.post('/erp/auth-analytics',tags=[\"AUTH\"])\ndef authConfig(usuario: UsuarioAuthConfig):\n\n # URL de la API REST\n url = 'https://sweb3.grupotsiperu.com.pe:8835/erp/api/rest/usuario/auth-analytics'\n\n # Datos del JSON a enviar\n data = {\n \"ruc\": usuario.ruc,\n \"coduser\": usuario.coduser,\n \"clave\": usuario.clave\n }\n\n # Realizar la solicitud POST\n response = requests.post(url, json=data, verify=False)\n\n # Comprobar el estado de la respuesta\n if response.status_code == 200:\n # Obtener los datos de la respuesta\n result = response.json()\n # Aquí puedes realizar cualquier manipulación de los datos obtenidos\n\n # Devolver los datos como respuesta en formato JSON\n return result\n else:\n print(response)\n # Devolver un mensaje de error en caso de que la solicitud no sea exitosa\n raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=\"Error al realizar la solicitud POST\")\n","repo_name":"luis122448/luis122448-api-oracle-analytics","sub_path":"api-oracle-analytics/routers/auth_router.py","file_name":"auth_router.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"23203128487","text":"import cv2\nimport mediapipe as mp\nimport pickle\n\nmp_drawing = mp.solutions.drawing_utils\nmp_drawing_styles = mp.solutions.drawing_styles\nmp_face_mesh = mp.solutions.face_mesh\n\nleft_iris_x = []\nright_iris_x = []\nnose_x = []\nleft_iris_y = []\nright_iris_y = []\nnose_y = []\nprint(\"What is the eyecontact video version?\")\nopt = input()\n# For video input\ncap = cv2.VideoCapture(\"./videos/eyecontact\" + opt + \".MOV\")\nfps = cap.get(cv2.CAP_PROP_FPS)\n# Resize the image while preserving aspect ratio\nscale_percent = 80 # percent of original size\nwidth = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) * scale_percent / 100)\nheight = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) * scale_percent / 100)\nout = cv2.VideoWriter('./output/eyecontact' + opt + '.avi', cv2.VideoWriter_fourcc('M','J','P','G'), fps, (width, height))\ndrawing_spec = mp_drawing.DrawingSpec(thickness=1, circle_radius=1)\nframe = 0\nwith mp_face_mesh.FaceMesh(\n max_num_faces=1,\n refine_landmarks=True,\n min_detection_confidence=0.5,\n min_tracking_confidence=0.5) as face_mesh:\n\n nose_midpoint_x = None \n while cap.isOpened():\n success, image = cap.read()\n if not success:\n print(\"Ignoring empty camera frame.\")\n # If loading a video, use 'break' instead of 'continue'.\n break\n dim = (width, height)\n image = cv2.resize(image, dim, interpolation = cv2.INTER_AREA)\n # To improve performance, optionally mark the image as not writeable to\n # pass by reference.\n image.flags.writeable = False\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n results = face_mesh.process(image)\n\n # Draw the face mesh annotations on the image.\n image.flags.writeable = True\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n if results.multi_face_landmarks:\n #for face_landmarks in results.multi_face_landmarks:\n face_landmarks = results.multi_face_landmarks[0]\n mp_drawing.draw_landmarks(\n image=image,\n landmark_list=face_landmarks,\n connections=mp_face_mesh.FACEMESH_TESSELATION,\n landmark_drawing_spec=None,\n connection_drawing_spec=mp_drawing_styles\n .get_default_face_mesh_tesselation_style())\n mp_drawing.draw_landmarks(\n image=image,\n landmark_list=face_landmarks,\n connections=mp_face_mesh.FACEMESH_CONTOURS,\n landmark_drawing_spec=None,\n connection_drawing_spec=mp_drawing_styles\n .get_default_face_mesh_contours_style()) \n mp_drawing.draw_landmarks(\n image=image,\n landmark_list=face_landmarks,\n connections=mp_face_mesh.FACEMESH_IRISES,\n landmark_drawing_spec=None,\n connection_drawing_spec=mp_drawing_styles\n .get_default_face_mesh_iris_connections_style())\n # shape = image.shape\n # cx = int(face_landmarks.landmark[468].x * shape[1])\n # cy = int(face_landmarks.landmark[468].y * shape[0])\n # cz = face_landmarks.landmark[468].z\n \n # Flip the image horizontally for a selfie-view display. Check Week 3 CANVAS\n # Add looking downright or downleft, for clarinets, flute\n # GRAPH ALL OF THESE AND VIEW THE COORDINATES\n if face_landmarks.landmark:\n if nose_midpoint_x is None:\n nose_midpoint_x = face_landmarks.landmark[4].x \n nose_threshold = nose_midpoint_x * 0.06\n \n # Check the direction of nose to detect where the user is looking\n if (abs(face_landmarks.landmark[4].x - nose_midpoint_x)) < nose_threshold:\n cv2.putText(image,\"Looking straight\", (220, 250), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (255, 255, 0), 4)\n elif face_landmarks.landmark[4].x > nose_midpoint_x + nose_threshold:\n cv2.putText(image,\"Looking to the right\", (220, 250), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (255, 255, 0), 4)\n elif face_landmarks.landmark[4].x < nose_midpoint_x + nose_threshold:\n cv2.putText(image,\"Looking to the left\", (220, 250), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (255, 255, 0), 4)\n # cv2.putText(image,\"NOSE:\" + str(face_landmarks.landmark[4].x) + \" y:\"+ str(face_landmarks.landmark[4].y) + \" z:\"+ str(face_landmarks.landmark[4].z), (20, 200), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 4)\n # cv2.putText(image,\"Left Iris:\" + str(face_landmarks.landmark[468].x) + \" y:\"+ str(face_landmarks.landmark[468].y) + \" z:\"+ str(face_landmarks.landmark[468].z), (20, 400), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 0), 4)\n # cv2.putText(image,\"Right Iris:\" + str(face_landmarks.landmark[473].x) + \" y:\"+ str(face_landmarks.landmark[473].y) + \" z:\"+ str(face_landmarks.landmark[473].z), (20, 600), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 0), 4)\n # cv2.circle(image, (cx, cy), 1, (255, 255, 0), 5)\n cv2.imshow('MediaPipe Face Mesh', image)\n # print(\"x:\" + str(cx) +\"y:\" + str(cy))\n out.write(image)\n if cv2.waitKey(5) & 0xFF == ord('q'):\n break\n with open(\"./pickle/lirisx_eyecontact(\" + opt + \").pickle\", 'wb') as f:\n pickle.dump(left_iris_x, f)\n with open(\"./pickle/lirisy_eyecontact(\" + opt + \").pickle\", 'wb') as f:\n pickle.dump(left_iris_y, f)\n with open(\"./pickle/ririsx_eyecontact(\" + opt + \").pickle\", 'wb') as f:\n pickle.dump(right_iris_x, f)\n with open(\"./pickle/ririsy_eyecontact(\" + opt + \").pickle\", 'wb') as f:\n pickle.dump(right_iris_y, f) \n with open(\"./pickle/nosex_eyecontact(\" + opt + \").pickle\", 'wb') as f:\n pickle.dump(nose_x, f)\n with open(\"./pickle/nosey_eyecontact(\" + opt + \").pickle\", 'wb') as f:\n pickle.dump(nose_y, f) \n\ncap.release()\nout.release()\ncv2.destroyAllWindows()","repo_name":"vbsb100/ConductingFeedback","sub_path":"eyetrack.py","file_name":"eyetrack.py","file_ext":"py","file_size_in_byte":5631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"4147233222","text":"\n# coding: utf-8\n\n# In[184]:\n\n\ndef compute_error(m,b,coordinates):\n totalerror=0\n for i in range(0,len(coordinates)):\n x=coordinates[i][0]\n y=coordinates[i][1]\n totalerror+=(y-(x*m+b))**2\n return totalerror / float(len(coordinates)) \n\ns=compute_error(1,2,[[2,4],[3,6],[41,22]])\ns\n\n","repo_name":"zhiAung/Deep-learning-project","sub_path":"practice1.py","file_name":"practice1.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"25786876272","text":"'''\nA converter for codon or sequence into amino acids\n'''\ndef main():\n # test all codon to aa from list\n codon = ['UUU', 'UUC', 'UUA', 'UUG', 'CUU', 'CUC', 'CUA', 'CUG', 'AUU', 'AUC', 'AUA', \n 'AUG', 'GUU', 'GUC', 'GUA', 'GUG', 'UCU', 'UCC', 'UCA', 'UCG', 'AGU', 'AGC', 'CCU', \n 'CCC', 'CCA', 'CCG', 'ACU', 'ACC', 'ACA', 'ACG', 'GCU', 'GCC', 'GCA', 'GCG', 'UAU', \n 'UAC', 'UAA', 'UAG', 'UGA', 'CAU', 'CAC', 'CAA', 'CAG', 'AAU', 'AAC', 'AAA', 'AAG', \n 'GAU', 'GAC', 'GAA', 'GAG', 'UGU', 'UGC', 'UGG', 'CGU', 'CGC', 'CGA', 'CGG', 'AGA', \n 'AGG', 'GGU', 'GGC', 'GGA', 'GGG']\n codon_aa = convert_codon_aa_l(codon)\n print(codon_aa)\n # correct output count\n print('F2-L6-I3-M1-V4-S6-P4-T4-A4-Y2-(*3)-H2-Q2-N2-K2-D2-E2-C2-W1-R6-G4')\n\n # test all codon to aa from string\n Seq_shift = 0\n codon = 'TTTTTCTTATTGCTTCTCCTACTGATTATCATAATGGTTGTCGTAGTGTCTTCCTCATCGAGTA' + (\n 'GCCCTCCCCCACCGACTACCACAACGGCTGCCGCAGCGTATTACTAATAGTGACATCACCAACA' +\n 'GAATAACAAAAAGGATGACGAAGAGTGTTGCTGGCGTCGCCGACGGAGAAGGGGTGGCGGAGGG')\n codon_aa = seq_aa(codon)\n print(codon_aa)\n # correct output comparison\n print('FFLLLLLLIIIMVVVVSSSSSSPPPPTTTTAAAAYY(*)HHQQNNKKDDEECCWRRRRRRGGGG')\n\n### Convert codon to amino acid, from a list to a new list\ndef convert_codon_aa_l(s):\n def codon_aa_list(c):\n if c[i] == 'GTT' or c[i] == 'GTC' or c[i] == 'GTA' or c[i] == 'GTG' or c[i] == 'GUU' or (\n c[i] == 'GUC' or c[i] == 'GUA' or c[i] == 'GUG'):\n c[i] = 'V' # Val\n elif c[i] == 'GCT' or c[i] == 'GCC' or c[i] == 'GCA' or c[i] == 'GCG' or c[i] == 'GCU':\n c[i] = 'A' # Ala\n elif c[i] == 'GAT' or c[i] == 'GAC' or c[i] == 'GAU':\n c[i] = 'D' # Asp\n elif c[i] == 'GAA' or c[i] == 'GAG':\n c[i] = 'E' # Glu\n elif c[i] == 'GGT' or c[i] == 'GGC' or c[i] == 'GGA' or c[i] == 'GGG' or c[i] == 'GGU':\n c[i] = 'G' # Gly\n elif c[i] == 'TTT' or c[i] == 'TTC' or c[i] == 'UUU' or c[i] == 'UUC':\n c[i] = 'F' # Phe\n elif c[i] == 'TTA' or c[i] == 'TTG' or c[i] == 'UUA' or c[i] == 'UUG' or c[i] == 'CTT' or (\n c[i] == 'CTC' or c[i] == 'CTA' or c[i] == 'CTG' or c[i] == 'CUU' or \n c[i] == 'CUC' or c[i] == 'CUA' or c[i] == 'CUG'):\n c[i] = 'L' # Leu\n elif c[i] == 'TCT' or c[i] == 'TCC' or c[i] == 'TCA' or c[i] == 'TCG' or c[i] == 'UCU' or (\n c[i] == 'UCC' or c[i] == 'UCA' or c[i] == 'UCG' or c[i] == 'AGT' or \n c[i] == 'AGC' or c[i] == 'AGU'):\n c[i] = 'S' # Ser\n elif c[i] == 'TAT' or c[i] == 'TAC' or c[i] == 'UAU' or c[i] == 'UAC':\n c[i] = 'Y' # Tyr\n elif c[i] == 'TGT' or c[i] == 'TGC' or c[i] == 'UGU' or c[i] == 'UGC':\n c[i] = 'C' # Cys\n elif c[i] == 'TGG' or c[i] == 'UGG':\n c[i] = 'W' # Trp\n elif c[i] == 'CCT' or c[i] == 'CCC' or c[i] == 'CCA' or c[i] == 'CCG' or c[i] == 'CCU':\n c[i] = 'P' # Pro\n elif c[i] == 'CAT' or c[i] == 'CAC' or c[i] == 'CAU':\n c[i] = 'H' # His\n elif c[i] == 'CAA' or c[i] == 'CAG':\n c[i] = 'Q' # Gln\n elif c[i] == 'CGT' or c[i] == 'CGC' or c[i] == 'CGA' or c[i] == 'CGG' or (\n c[i] == 'CGU' or c[i] == 'AGA' or c[i] == 'AGG'):\n c[i] = 'R' # Arg\n elif c[i] == 'ATT' or c[i] == 'ATC' or c[i] == 'ATA' or (\n c[i] == 'AUU' or c[i] == 'AUC' or c[i] == 'AUA'):\n c[i] = 'I' # Ile\n elif c[i] == 'ATG' or c[i] == 'AUG':\n c[i] = 'M' # Met (Starting codon)\n elif c[i] == 'ACT' or c[i] == 'ACC' or c[i] == 'ACA' or c[i] == 'ACG' or c[i] == 'ACU':\n c[i] = 'T' # Thr\n elif c[i] == 'AAT' or c[i] == 'AAC' or c[i] == 'AAU':\n c[i] = 'N' # Asn\n elif c[i] == 'AAA' or c[i] == 'AAG':\n c[i] = 'K' # Lys\n elif c[i] == 'TAA' or c[i] == 'TAG' or c[i] == 'UAA' or (\n c[i] == 'UAG' or c[i] == 'TGA' or c[i] == 'UGA'):\n c[i] = '*' # STOP\n for i in range(len(s)):\n codon_aa_list(s)\n return s\n\n\n# Convert codon to amino acid from string\ndef codon_aa(c):\n if c == 'GTT' or c == 'GTC' or c == 'GTA' or c == 'GTG' or c == 'GUU' or (\n c == 'GUC' or c == 'GUA' or c == 'GUG'):\n c = 'V' # Val\n elif c == 'GCT' or c == 'GCC' or c == 'GCA' or c == 'GCG' or c == 'GCU':\n c = 'A' # Ala\n elif c == 'GAT' or c == 'GAC' or c == 'GAU':\n c = 'D' # Asp\n elif c == 'GAA' or c == 'GAG':\n c = 'E' # Glu\n elif c == 'GGT' or c == 'GGC' or c == 'GGA' or c == 'GGG' or c == 'GGU':\n c = 'G' # Gly\n elif c == 'TTT' or c == 'TTC' or c == 'UUU' or c == 'UUC':\n c = 'F' # Phe\n elif c == 'TTA' or c == 'TTG' or c == 'UUA' or c == 'UUG' or c == 'CTT' or (\n c == 'CTC' or c == 'CTA' or c == 'CTG' or c == 'CUU' or \n c == 'CUC' or c == 'CUA' or c == 'CUG'):\n c = 'L' # Leu\n elif c == 'TCT' or c == 'TCC' or c == 'TCA' or c == 'TCG' or c == 'UCU' or (\n c == 'UCC' or c == 'UCA' or c == 'UCG' or c == 'AGT' or \n c == 'AGC' or c == 'AGU'):\n c = 'S' # Ser\n elif c == 'TAT' or c == 'TAC' or c == 'UAU' or c == 'UAC':\n c = 'Y' # Tyr\n elif c == 'TGT' or c == 'TGC' or c == 'UGU' or c == 'UGC':\n c = 'C' # Cys\n elif c == 'TGG' or c == 'UGG':\n c = 'W' # Trp\n elif c == 'CCT' or c == 'CCC' or c == 'CCA' or c == 'CCG' or c == 'CCU':\n c = 'P' # Pro\n elif c == 'CAT' or c == 'CAC' or c == 'CAU':\n c = 'H' # His\n elif c == 'CAA' or c == 'CAG':\n c = 'Q' # Gln\n elif c == 'CGT' or c == 'CGC' or c == 'CGA' or c == 'CGG' or (\n c == 'CGU' or c == 'AGA' or c == 'AGG'):\n c = 'R' # Arg\n elif c == 'ATT' or c == 'ATC' or c == 'ATA' or (\n c == 'AUU' or c == 'AUC' or c == 'AUA'):\n c = 'I' # Ile\n elif c == 'ATG' or c == 'AUG':\n c = 'M' # Met (Starting codon)\n elif c == 'ACT' or c == 'ACC' or c == 'ACA' or c == 'ACG' or c == 'ACU':\n c = 'T' # Thr\n elif c == 'AAT' or c == 'AAC' or c == 'AAU':\n c = 'N' # Asn\n elif c == 'AAA' or c == 'AAG':\n c = 'K' # Lys\n elif c == 'TAA' or c == 'TAG' or c == 'UAA' or (\n c == 'UAG' or c == 'TGA' or c == 'UGA'):\n c = '*' # STOP \n return c\n\n# Print the strand's converted aa with sequence shift\ndef seq_aa(sequence, seq_shift):\n seq_count = len(sequence)\n codon_count = (seq_count - seq_shift) // 3 \n aa = ''\n loc1 = 0 + seq_shift\n loc2 = 3 + seq_shift\n for i in range(codon_count):\n codon = sequence[loc1:loc2]\n aa += codon_aa(codon)\n loc1 += 3\n loc2 += 3\n return aa\n\nif __name__ == '__main__':\n main()","repo_name":"jagonball/Python_projects","sub_path":"Functions/Converter_codon_aa.py","file_name":"Converter_codon_aa.py","file_ext":"py","file_size_in_byte":6940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"24662450796","text":"\r\nfrom email.parser import Parser\r\nfrom urllib.parse import parse_qs, urlparse\r\n\r\n# класс, объекты которого хранят данные клиентских запросов \r\nclass Request:\r\n def __init__(self, client_ip_hashed, method, target, version, headers, rfile, body = None):\r\n # захешированный ip пользователя\r\n self.hashed_ip = client_ip_hashed\r\n # метод запроса\r\n self.method = method\r\n # url запроса\r\n self.target = target\r\n # версия http протокола\r\n self.version = version\r\n # заголовки запроса\r\n self.headers = headers\r\n # файл, который используется для чтения запроса\r\n self.rfile = rfile\r\n \r\n self.body = body\r\n \r\n # url, разбитый на части\r\n self.url = urlparse(self.target)\r\n # часть url, идущая после хоста\r\n self.path = self.url.path\r\n\r\n # функция, возвращающая тело запроса (если оно есть)\r\n def body(self):\r\n size = self.headers.get('Content-Length')\r\n if not size:\r\n return None\r\n return self.rfile.read(size)\r\n\r\n# класс, объекты которого хранят данные ответов\r\nclass Response:\r\n def __init__(self, status, reason, headers=None, body=None):\r\n # статус (часть строки ответа)\r\n self.status = status\r\n # расшифровка HTTP статуса ответа (часть строки ответа)\r\n self.reason = reason\r\n # заголовки ответа\r\n self.headers = headers\r\n # тело ответа (непосредственно контент страниц сайта)\r\n self.body = body","repo_name":"Neustroev09/ll-Define","sub_path":"entire_app/server_packs.py","file_name":"server_packs.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"23299166961","text":"import os\nimport cv2\nimport torch\nimport numpy as np\nfrom cartoon.models import ResnetGenerator\nimport argparse\nfrom cartoon.utils import Preprocess\n\n\nos.environ['KMP_DUPLICATE_LIB_OK'] = 'True'\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\n\nclass Photo2Cartoon:\n def __init__(self):\n self.pre = Preprocess()\n self.device = torch.device(\n \"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n self.net = ResnetGenerator(\n ngf=32, img_size=256, light=True).to(self.device)\n\n assert os.path.exists(\n os.path.join(basedir, './models/photo2cartoon_weights.pt')), \"[Step1: load weights] Can not find 'photo2cartoon_weights.pt' in folder 'models!!!'\"\n params = torch.load(os.path.join(\n basedir, './models/photo2cartoon_weights.pt'), map_location=self.device)\n self.net.load_state_dict(params['genA2B'])\n print('[Step1: load weights] success!')\n\n def inference(self, img):\n # face alignment and segmentation\n face_rgba = self.pre.process(img)\n if face_rgba is None:\n print('[Step2: face detect] can not detect face!!!')\n return None\n\n print('[Step2: face detect] success!')\n face_rgba = cv2.resize(face_rgba, (256, 256),\n interpolation=cv2.INTER_AREA)\n face = face_rgba[:, :, :3].copy()\n mask = face_rgba[:, :, 3][:, :, np.newaxis].copy() / 255.\n face = (face*mask + (1-mask)*255) / 127.5 - 1\n\n face = np.transpose(face[np.newaxis, :, :, :],\n (0, 3, 1, 2)).astype(np.float32)\n face = torch.from_numpy(face).to(self.device)\n\n # inference\n with torch.no_grad():\n cartoon = self.net(face)[0][0]\n\n # post-process\n cartoon = np.transpose(cartoon.cpu().numpy(), (1, 2, 0))\n cartoon = (cartoon + 1) * 127.5\n cartoon = (cartoon * mask + 255 * (1 - mask)).astype(np.uint8)\n cartoon = cv2.cvtColor(cartoon, cv2.COLOR_RGB2BGR)\n print('[Step3: photo to cartoon] success!')\n return cartoon\n\n\nc2p = Photo2Cartoon()\n\n\ndef gen_cartoon(photo_path, result_filename_path, make_up_id):\n img = cv2.cvtColor(cv2.imread(photo_path), cv2.COLOR_BGR2RGB)\n # c2p = Photo2Cartoon()\n cartoon = c2p.inference(img)\n if cartoon is not None:\n cv2.imwrite(result_filename_path, cartoon)\n print(\"\\n Cartoon done!\\n\")\n","repo_name":"anthhub/makeup-photo-flask","sub_path":"cartoon/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2431,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"12657701713","text":"import pandas as pd\n\ndef to_1D(series):\n return pd.Series([x for _list in series for x in _list])\n\nimport Establishing_Hierarchy\n\nCreatures = pd.read_excel(r'C:\\Users\\maxhi\\OneDrive\\Desktop\\Python Project\\Python 5e Project Data.xlsx',sheet_name='Creatures')\nActions = pd.read_excel(r'C:\\Users\\maxhi\\OneDrive\\Desktop\\Python Project\\Python 5e Project Data.xlsx',sheet_name='Actions')\n\n# will need to go through for armor source and add to inventory\n\n\n\n\n\nXP_Table = { # this way I can track knowledge and experience via level through killing a creature\n 'CR': [0,.125,.25,.5,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30],\n 'XP': [10,25,50,100,200,450,700,1100,1800,2300,2900,3900,5000,5900,7200,8400,10000,11500,13000,15000,18000,20000,22000,25000,33000,41000,50000,62000,75000,90000,105000,120000,135000,155000]}\n\n\n\n# Making the Table for Monster Analysis\n# Saving Throws\nfor i in Creatures.index:\n Str_i = str(Creatures.Saves[i])\n List_i = Str_i.split(',')\n Creatures.Saves[i] = List_i\n\n# Speeds\nfor i in Creatures.index:\n Str_i = str(Creatures.Speeds[i])\n List_i = Str_i.split(',')\n Creatures.Speeds[i] = List_i\n#Creatures[\"Speeds\"] = Creatures[\"Speeds\"].apply(eval)\n\n# Skills\nfor i in Creatures.index:\n Str_i = str(Creatures.Skills[i])\n List_i = Str_i.split(',')\n Creatures.Skills[i] = List_i\n#Creatures[\"Skills\"] = Creatures[\"Skills\"].apply(eval)\n\n# WRI\nfor i in Creatures.index:\n Str_i = str(Creatures.WRI[i])\n #print(Str_i)\n List_i = Str_i.split(',')\n #print(List_i)\n Creatures.WRI[i] = List_i\n#Creatures[\"WRI\"] = Creatures[\"WRI\"].apply(eval)\n\n# Senses\nfor i in Creatures.index:\n Str_i = str(Creatures.Senses[i])\n List_i = Str_i.split(',')\n Creatures.Senses[i] = List_i\n#Creatures[\"Senses\"] = Creatures[\"Senses\"].apply(eval)\n\n# Languages\nfor i in Creatures.index:\n Str_i = str(Creatures.Languages[i])\n List_i = Str_i.split(',')\n Creatures.Languages[i] = List_i\n#Creatures[\"Languages\"] = Creatures[\"Languages\"].apply(eval)\n\n# Features\nfor i in Creatures.index:\n Str_i = str(Creatures.Features[i])\n List_i = Str_i.split(',')\n Creatures.Features[i] = List_i\n#Creatures[\"Features\"] = Creatures[\"Features\"].apply(eval)\n\n# Actions\nfor i in Creatures.index:\n Str_i = str(Creatures.Actions[i])\n List_i = Str_i.split(',')\n Creatures.Actions[i] = List_i\n#Creatures[\"Actions\"] = Creatures[\"Actions\"].apply(eval)\n\n# Bonus Actions\nfor i in Creatures.index:\n Str_i = str(Creatures.Bonus_Actions[i])\n List_i = Str_i.split(',')\n Creatures.Bonus_Actions[i] = List_i\n#Creatures[\"Bonus_Actions\"] = Creatures[\"Bonus_Actions\"].apply(eval)\n\n# Reactions\nfor i in Creatures.index:\n Str_i = str(Creatures.Reactions[i])\n List_i = Str_i.split(',')\n Creatures.Reactions[i] = List_i\n#Creatures[\"Reactions\"] = Creatures[\"Reactions\"].apply(eval)\n\n# Multiattack\nfor i in Creatures.index:\n Str_i = str(Creatures.Multiattack[i])\n List_i = Str_i.split(':')\n Creatures.Multiattack[i] = List_i\n#Creatures[\"Multiattack\"] = Creatures[\"Multiattack\"].apply(eval)\n\n# Spells\nfor i in Creatures.index:\n Str_i = str(Creatures.Spells[i])\n List_i = Str_i.split(',')\n Creatures.Spells[i] = List_i\n#Creatures[\"Spells\"] = Creatures[\"Spells\"].apply(eval)\n\n# Spells\nfor i in Actions.index:\n Str_i = str(Actions.Damage_Type[i])\n List_i = Str_i.split(',')\n Actions.Damage_Type[i] = List_i\n#Creatures[\"Spells\"] = Creatures[\"Spells\"].apply(eval)\n\nCreatures_and_Actions = Actions.merge(Creatures,how='left',on=['Creature Name','Book'])\n#print(list(Creatures_and_Actions))\n\ndef Convert(response):\n string = str(response)\n l = list(string.split(\",\"))\n return l\n\nmonster_primes = {}\nfor ind in Creatures.index:\n Monster_ID = str(str(Creatures.iloc[ind,0]) + ',' + str(Creatures.iloc[ind,1]))\n Name = str(Creatures.iloc[ind,0])\n Book = str(Creatures.iloc[ind,1])\n HP = int(Creatures.iloc[ind,5])\n AC = int(Creatures.iloc[ind,4])\n Type = str(Creatures.iloc[ind,3])\n Size = str(Creatures.iloc[ind,2])\n CR = int(Creatures.iloc[ind,18])\n XP = 0\n Prof_Bonus = 1\n Saving_Throws = Convert(Creatures.iloc[ind,12])\n Skill_Profs = Convert(Creatures.iloc[ind,13])\n Str_Score = int(Creatures.iloc[ind,6])\n Dex_Score = int(Creatures.iloc[ind,7])\n Con_Score = int(Creatures.iloc[ind,8])\n Int_Score = int(Creatures.iloc[ind,9])\n Wis_Score = int(Creatures.iloc[ind,10])\n Cha_Score = int(Creatures.iloc[ind,11])\n Languages = Convert(Creatures.iloc[ind,17])\n Features = Convert(Creatures.iloc[ind,19])\n #print(Creatures.iloc[ind,15])\n WRI = Creatures.iloc[ind,15]\n Skills = Creatures.iloc[ind,14]\n Senses = Creatures.iloc[ind,16]\n Speeds = Creatures.iloc[ind,13]\n Actions = Creatures.iloc[ind,20]\n Bonus_Actions = Creatures.iloc[ind,21]\n Reactions = Creatures.iloc[ind,22]\n Spellcasting_Prepared = Creatures.iloc[ind,27]\n Spell_DC = Creatures.iloc[ind,29]\n #Creatures[ind,1] = Monster(Name,HP,AC,Type,Size,CR,Prof_Bonus,Saving_Throws,Skill_Profs,Str_Score,Dex_Score,Con_Score,Int_Score,Wis_Score,Cha_Score,[],[],[],[],[],True,True)\n monster_primes[Monster_ID] = Establishing_Hierarchy.Monster(Monster_ID,Name,Book,HP,AC,Type,Size,CR,XP,Prof_Bonus,Saving_Throws,Skill_Profs,Str_Score,Dex_Score,Con_Score,Int_Score,Wis_Score,Cha_Score,True,Spellcasting_Prepared,Spell_DC,True,True,True,True,True,True,Languages,Features,WRI,True)\n #Monster_ID,Name,HP,AC,Type,Size,CR,Prof_Bonus,Saving_Throws,Skill_Profs,Str_Score,Dex_Score,Con_Score,Int_Score,Wis_Score,Cha_Score,Effects,Spells_Known,Spell_Save_DC,Attunement_Slots,Attunement_Slots_Filled,Languages,Features,WRI,Active_Conditions\n monster_primes[Monster_ID].Prof_Bonus = Establishing_Hierarchy.CRToProficiency(monster_primes[Monster_ID])\n\n for i in Actions:\n monster_primes[Monster_ID].Actions[i] = i \n \n for i in Bonus_Actions:\n monster_primes[Monster_ID].Bonus_Actions[i] = i\n \n for i in Reactions:\n monster_primes[Monster_ID].Reactions[i] = i\n \n \n monster_primes[Monster_ID].Features += Features\n monster_primes[Monster_ID].Languages += Languages\n monster_primes[Monster_ID].Skill_Profs += Skills\n #monster_primes[Monster_ID].Senses += Senses\n #monster_primes[Monster_ID].Speeds += Speeds\n\n#print(monster_primes)\n\n#print(monster_primes['Fire Elemental,Monster Manual'].WRI)\n#print(Creatures.WRI)\n\n#monster_instances = {}\n#for ind in Creatures.index:\n# Monster_ID = str(str(Creatures.iloc[ind,0]) + ',' + str(Creatures.iloc[ind,1]))\n# Name = str(Creatures.iloc[ind,0])\n# Book = str(Creatures.iloc[ind,1])\n# HP = int(Creatures.iloc[ind,5])\n# AC = int(Creatures.iloc[ind,4])\n# Type = str(Creatures.iloc[ind,3])\n# Size = str(Creatures.iloc[ind,2])\n# CR = int(Creatures.iloc[ind,18])\n# Prof_Bonus = 1\n# Saving_Throws = Convert(Creatures.iloc[ind,12])\n# Skill_Profs = Convert(Creatures.iloc[ind,13])\n# Str_Score = int(Creatures.iloc[ind,6])\n# Dex_Score = int(Creatures.iloc[ind,7])\n# Con_Score = int(Creatures.iloc[ind,8])\n# Int_Score = int(Creatures.iloc[ind,9])\n# Wis_Score = int(Creatures.iloc[ind,10])\n# Cha_Score = int(Creatures.iloc[ind,11])\n# Languages = Convert(Creatures.iloc[ind,17])\n# Features = Convert(Creatures.iloc[ind,19])\n# WRI = Convert(Creatures.iloc[ind,15])\n# Skills = Creatures.iloc[ind,14]\n# Senses = Creatures.iloc[ind,16]\n# Speed = Creatures.iloc[ind,13]\n# Actions = Creatures.iloc[ind,20]\n# Bonus_Actions = Creatures.iloc[ind,21]\n# Reactions = Creatures.iloc[ind,22]\n# Spells = Creatures.iloc[ind,27]\n# Spell_DC = Creatures.iloc[ind,29]\n# Instance = 1\n# Spawn_Inventory = 0\n# Monster_Instance_ID = str(Monster_ID + str(Instance))\n# Current_HP = HP\n #Creatures[ind,1] = Monster(Name,HP,AC,Type,Size,CR,Prof_Bonus,Saving_Throws,Skill_Profs,Str_Score,Dex_Score,Con_Score,Int_Score,Wis_Score,Cha_Score,[],[],[],[],[],True,True)\n# monster_instances[Monster_Instance_ID] = Establishing_Hierarchy.Monster_Instance(Monster_ID,Name,Book,HP,AC,Type,Size,CR,XP,Prof_Bonus,Saving_Throws,Skill_Profs,Str_Score,Dex_Score,Con_Score,Int_Score,Wis_Score,Cha_Score,True,Spells,Spell_DC,True,True,Languages,Features,WRI,Spawn_Inventory,Instance,Monster_Instance_ID,True,True,True,'Alive',True,False)\n #Monster_ID,Name,HP,AC,Type,Size,CR,Prof_Bonus,Saving_Throws,Skill_Profs,Str_Score,Dex_Score,Con_Score,Int_Score,Wis_Score,Cha_Score,Effects,Spells_Known,Spell_Save_DC,Attunement_Slots,Attunement_Slots_Filled,Languages,Features,WRI,Active_Conditions\n# monster_primes[Monster_ID].Prof_Bonus = Establishing_Hierarchy.CRToProficiency(monster_primes[Monster_ID])\n# monster_primes[Monster_ID].Actions += Actions\n# monster_primes[Monster_ID].Bonus_Actions += Bonus_Actions\n# monster_primes[Monster_ID].Reactions += Reactions\n# monster_primes[Monster_ID].Features += Features\n# monster_primes[Monster_ID].Languages += Languages\n# monster_primes[Monster_ID].Skill_Profs += Skills\n #monster_primes[Monster_ID].Senses += Senses\n #monster_primes[Monster_ID].Speed += Speed\n\n#print(Creatures_and_Actions)\n\n#print(monster_instances)\n","repo_name":"maxhightower/5e-Simulation","sub_path":"Monsters.py","file_name":"Monsters.py","file_ext":"py","file_size_in_byte":8888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"41637214289","text":"import os\nfrom sqlalchemy import create_engine\nimport pandas as pd\n\n\ndef populate_database():\n engine = create_engine('sqlite:///instance/database.db')\n#\n df = download_format_datetime_csv('data/AHU_data/AHU_annual.csv')\n df.to_sql('AHU_data', con=engine, if_exists='replace')\n\n folder_path = 'data/AHU_data/'\n for f in os.listdir(folder_path):\n fname = os.path.splitext(f)[0]\n full_path = os.path.join(folder_path, f)\n df = download_format_datetime_csv(full_path)\n df.to_sql(f'{fname}', con=engine, if_exists='replace')\n \n\n df = pd.read_csv('data/faults.csv')\n df.to_sql('faults', con=engine, if_exists='replace', index=False)\n\n df = pd.read_csv('data/sensor_data.csv')\n df.to_sql('AHU_info', con=engine, if_exists='replace', index=False)\n\n\n\ndef download_format_datetime_csv(path):\n df = pd.read_csv(path)\n df['Datetime'] = pd.to_datetime(df['Datetime'])\n return df.set_index('Datetime')\n\n\nif __name__ == '__main__':\n populate_database()\n","repo_name":"connbrack/InteractionML-FDD","sub_path":"server/populate_database.py","file_name":"populate_database.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"31089570951","text":"import pygame\nimport neat\nimport time\nimport os\nimport random\nfrom pygame.locals import *\npygame.font.init()\npygame.mixer.init()\nWIDTH=500\nHEIGHT=800\nBD_IMGS=[pygame.transform.scale2x(pygame.image.load(os.path.join(\"imgs\",\"bird1.png\"))),pygame.transform.scale2x(pygame.image.load(os.path.join(\"imgs\",\"bird2.png\"))),pygame.transform.scale2x(pygame.image.load(os.path.join(\"imgs\",\"bird3.png\")))]\nBD_PIPE=pygame.transform.scale2x(pygame.image.load(os.path.join(\"imgs\",\"pipe.png\")))\nBD_BASE=pygame.transform.scale2x(pygame.image.load(os.path.join(\"imgs\",\"base.png\")))\nBD_BG=pygame.transform.scale2x(pygame.image.load(os.path.join(\"imgs\",\"bg.png\")))\njump_sound = pygame.mixer.Sound('sounds/jump.ogg')\nscore_sound = pygame.mixer.Sound('sounds/score.ogg')\ndead_sound = pygame.mixer.Sound('sounds/dead.ogg')\n\nSTAT_FONT=pygame.font.SysFont(\"comicsans\",50)\n\nclass Bird:\n IMGS=BD_IMGS\n MAX_ROTATION=25\n VEL=20\n AT_TIME=5\n\n def __init__(self,x,y):\n self.x=x\n self.y=y\n self.tilt=0\n self.tick_count=0\n self.vel=0\n self.height=y\n self.img_count=0\n self.img=self.IMGS[0]\n\n def jump(self):\n self.vel=-10.5\n self.tick_count=0\n self.height=self.y\n\n def move(self):\n self.tick_count+=1\n d=self.vel*self.tick_count+1.5*self.tick_count**2\n if(d>=16):\n d= 16\n if(d<0):\n d-=2\n self.y=self.y+d\n if (d<0 or self.y <self.height +50):\n if self.tilt< self.MAX_ROTATION:\n self.tilt=self.MAX_ROTATION\n else:\n if self.tilt > -90:\n self.tilt -= self.VEL\n\n def draw(self,win):\n self.img_count+=1\n if(self.img_count < self.AT_TIME):\n self.img=self.IMGS[0]\n elif self.img_count < self.AT_TIME*2:\n self.img=self.IMGS[1]\n elif self.img_count < self.AT_TIME*3:\n self.img=self.IMGS[2]\n elif self.img_count < self.AT_TIME*4:\n self.img=self.IMGS[1]\n elif self.img_count < self.AT_TIME*4+1:\n self.img=self.IMGS[0]\n self.img_count=0\n if self.tilt <= -80:\n self.img=self.IMGS[1]\n self.img_count=self.AT_TIME*2\n\n rotated_image=pygame.transform.rotate(self.img , self.tilt)\n new_rect=rotated_image.get_rect(center=self.img.get_rect(topleft=(self.x,self.y)).center)\n win.blit(rotated_image,new_rect.topleft)\n def get_mask(self):\n return pygame.mask.from_surface(self.img)\n\nclass Pipe:\n GAP=200\n VEL=5\n def __init__(self,x):\n self.x=x\n self.height=0\n self.top=0\n self.bottom=0\n self.PIPE_TOP=pygame.transform.flip(BD_PIPE,False,True)\n self.PIPE_BOTTOM=BD_PIPE\n self.passed=False\n self.set_height()\n def set_height(self):\n self.height=random.randrange(40,540)\n self.top=self.height-self.PIPE_TOP.get_height()\n self.bottom=self.height+self.GAP\n def move(self):\n self.x-=self.VEL\n\n def draw(self,win):\n win.blit(self.PIPE_TOP,(self.x,self.top))\n win.blit(self.PIPE_BOTTOM,(self.x,self.bottom))\n def collide(self,bird):\n bird_mask=bird.get_mask()\n top_mask=pygame.mask.from_surface(self.PIPE_TOP)\n bottom_mask=pygame.mask.from_surface(self.PIPE_BOTTOM)\n\n top_offset=(self.x-bird.x,self.top-round(bird.y))\n bottom_offset=(self.x-bird.x,self.bottom-round(bird.y))\n\n b_point=bird_mask.overlap(bottom_mask,bottom_offset)\n t_point=bird_mask.overlap(top_mask,top_offset)\n if t_point or b_point:\n return True\n \nclass Base:\n VEL=5\n WIDTH=BD_BASE.get_width()\n IMG=BD_BASE\n def __init__(self,y):\n self.y=y\n self.x1=0\n self.x2=self.WIDTH\n def move(self):\n self.x1-=self.VEL\n self.x2-=self.VEL\n if self.x1+self.WIDTH<0:\n self.x1=self.x2+self.WIDTH\n if self.x2+self.WIDTH<0:\n self.x2=self.x1+self.WIDTH\n def draw(self,win):\n win.blit(self.IMG,(self.x1,self.y))\n win.blit(self.IMG,(self.x2,self.y))\n\ndef window(win,bird,pipes,base,score):\n win.blit(BD_BG,(0,0))\n for pipe in pipes:\n pipe.draw(win)\n text=STAT_FONT.render(\"Score: \"+str(score),1,(255,255,255))\n win.blit(text,(WIDTH-10-text.get_width(),10))\n base.draw(win)\n #win.blit(BD_BASE,(0,0))\n bird.draw(win)\n #base.draw(win)\n #bird.move()\n pygame.display.update()\n\ndef end_screen(win):\n run = True\n dead_sound.play()\n text_label = STAT_FONT.render(\"Press Space to Restart\", 1, (255,255,255))\n while run:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n\n if event.type == pygame.KEYDOWN:\n main()\n\n win.blit(text_label, (WIDTH/2 - text_label.get_width()/2, 500))\n pygame.display.update()\n\n pygame.quit()\n quit()\n\ndef main():\n bird = Bird(230,350)\n base = Base(730)\n pipes = [Pipe(600)]\n score = 0\n\n clock = pygame.time.Clock()\n start = False\n lost = False\n win=pygame.display.set_mode((WIDTH,HEIGHT))\n run = True\n while run:\n pygame.time.delay(30)\n clock.tick(60)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n pygame.quit()\n quit()\n break\n\n if event.type == pygame.KEYDOWN and not lost:\n if event.key == pygame.K_SPACE:\n if not start:\n start = True\n bird.jump()\n jump_sound.play()\n if start:\n bird.move()\n if not lost:\n base.move()\n\n if start:\n rem = []\n add_pipe = False\n for pipe in pipes:\n pipe.move()\n # check for collision\n if pipe.collide(bird):\n lost = True\n\n if pipe.x + pipe.PIPE_TOP.get_width() < 0:\n rem.append(pipe)\n\n if not pipe.passed and pipe.x < bird.x:\n pipe.passed = True\n add_pipe = True\n\n if add_pipe:\n score += 1\n score_sound.play()\n pipes.append(Pipe(600))\n\n for r in rem:\n pipes.remove(r)\n\n\n if bird.y + bird.img.get_height() - 10 >= 730:\n break\n\n window(win, bird, pipes, base, score)\n\n end_screen(win)\n\nmain()\n\n","repo_name":"SaiTeja69/flappy_bird_ai","sub_path":"flappy_game.py","file_name":"flappy_game.py","file_ext":"py","file_size_in_byte":6639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"72112962045","text":"\n# coding: utf-8\n\n# Use this notebook to run Wangview while developing with IPython.\n# \n# The `autoreload` extension will allow you to test changes to the code without restarting the kernel.\n\n# In[ ]:\n\nget_ipython().magic('load_ext autoreload')\n\n\n# In[ ]:\n\nget_ipython().magic('autoreload 2')\n\n\n# In[ ]:\n\nfrom Wangview.Display import Display\n\n\n# In[ ]:\n\nw = Display('../Wangscape/Wangscape/example3/output')\nw.run()\n\n","repo_name":"Wangscape/Wangview","sub_path":"WangviewIPython.py","file_name":"WangviewIPython.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"41"} +{"seq_id":"3390345058","text":"my_dict = {\n '1' : ('Oneth', '4'), \n '2' : ('twoth', '5'),\n '3' : ('threeth','1'),\n '4' : ('fourth', '2'),\n '5' : ('fiveth', '3'),\n}\n\n'''\n1 = 4\n2 = 5\n3 = 1\n4 = 2\n5 = 3\n'''\nindex = 1\n\nfor i in range(10):\n for k,v in my_dict.items():\n if str(index) == k:\n index = v[1]\n print(k,v)\n\n\n''' # a bit of scrap I worked on last night.\n if constants.diverge == True: ### heres the new bit\n while constants.diverge == True:\n for k,v in event_list.main_dict.items():\n if str(constants.skip) == k:\n func = v[0] # the first variable for this key is a function to be called, the 'top level function'\n print(func(*key_elem[1:])) # feed all other variables to the 'top level function', some may also be functions (see event_list.py) \n\n while 1: # wait until the player presses 'KEY_ENTER', then continue with the iteration of 'main_dict'. \n key = term.inkey()\n if key.is_sequence and key.name == 'KEY_ENTER': \n #constants.skip = 0 # 'reset constants.skip' for the next iteration\n break\n constants.skip = 0 # before we pass on an empty (a key with no variables), we have to reset constants.skip for the next iteration.\n pass ### new bit ends here\n\n constants.skip = 0 # 'reset cons'''\n","repo_name":"Drew-LR/Text-Based-Game","sub_path":"tests/go_to_test.py","file_name":"go_to_test.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"22319447524","text":"from openai.error import RateLimitError, ServiceUnavailableError\nimport openai\nimport backoff\nimport pandas as pd\nimport numpy as np\nimport pickle\nfrom transformers import GPT2TokenizerFast\nfrom typing import List\nfrom time import sleep\nimport pickle\nimport os\n\n\nclass Brain:\n COMPLETIONS_MODEL = \"text-davinci-003\"\n EMBEDDING_MODEL = \"text-embedding-ada-002\"\n openai.api_key = os.getenv(\"OPENAI_KEY\")\n @backoff.on_exception(backoff.expo, (RateLimitError, ServiceUnavailableError))\n def get_embedding(self, text: str, model: str=EMBEDDING_MODEL, idx: int=0) -> list[float]:\n result = openai.Embedding.create(\n model=model,\n input=text\n )\n return result[\"data\"][0][\"embedding\"]\n\n def compute_doc_embeddings(self, df: pd.DataFrame) -> dict[tuple[str, str], list[float]]:\n \"\"\"\n Create an embedding for each row in the dataframe using the OpenAI Embeddings API.\n \n Return a dictionary that maps between each embedding vector and the index of the row that it corresponds to.\n \"\"\"\n return {\n idx: self.get_embedding(r.content) for idx, r in df.iterrows()\n }\n \n def compute_text_embeddings(self, text: str, start_index:int = 0) -> dict[tuple[str, str], list[float]]:\n return {\n (start_index+idx): self.get_embedding(line, self.EMBEDDING_MODEL ,idx) for idx, line in enumerate(text)\n }\n\n def update_text_embeddings(self, compute_embedding, text, new_text):\n print('Updating the model with data: ', new_text)\n compute_embedding.update(self.compute_text_embeddings(new_text, len(compute_embedding)))\n return text + new_text\n\n def load_embeddings(self, fname: str):\n \"\"\"\n Read the document embeddings and their keys from a CSV.\n \n fname is the path to a CSV with exactly these named columns: \n \"title\", \"heading\", \"0\", \"1\", ... up to the length of the embedding vectors.\n \"\"\"\n \n df = pd.read_csv(fname, header=0)\n max_dim = max([int(c) for c in df.columns if c != \"title\" and c != \"heading\"])\n return {\n (r.title, r.heading): [r[str(i)] for i in range(max_dim + 1)] for _, r in df.iterrows()\n }\n \n \n text = []\n consumed_files = set()\n context_embeddings = {}\n def reload_models(self):\n self.text = pickle.load(open('textfile.obj', \"rb\"))\n self.consumed_files = pickle.load(open('consumed_files.obj', \"rb\"))\n self.context_embeddings = pickle.load(open('nyush_embeddings.obj', \"rb\"))\n \n def save_models(self):\n with open('nyush_embeddings.obj', 'wb') as fp:\n pickle.dump(self.context_embeddings, fp)\n with open('consumed_files.obj', 'wb') as fp:\n pickle.dump(self.consumed_files, fp)\n with open('textfile.obj', 'wb') as fp:\n pickle.dump(self.text, fp)\n \n def process_file(self, filename, delim=\"\\n\\n\"):\n self.reload_models()\n if filename not in self.consumed_files:\n update = open (filename, \"r\").read().split(delim)\n self.text = self.update_text_embeddings(self.context_embeddings, self.text, update)\n self.consumed_files.add(filename)\n with open('nyush_embeddings.obj', 'wb') as fp:\n \tpickle.dump(self.context_embeddings, fp)\n with open('consumed_files.obj', 'wb') as fp:\n \tpickle.dump(self.consumed_files, fp)\n with open('textfile.obj', 'wb') as fp:\n \tpickle.dump(self.text, fp)\n \n else:\n print(\"File already processed\")\n # document_embeddings = self.load_embeddings(\"olympics_sections_document_embeddings.csv\")\n\n # context_embeddings = self.compute_doc_embeddings(df)\n\n # context_embeddings = self.compute_text_embeddings(text)\n # with open('nyush_embeddings.obj', 'wb') as fp:\n # \tpickle.dump(context_embeddings, fp)\n # print(len(context_embeddings))\n\n # update = open (\"update.txt\", \"r\").read().split(\"\\n\\n\")\n\n # text = self.update_text_embeddings(context_embeddings, text, update)\n\n\n def vector_similarity(self, x: List[float], y: List[float]) -> float:\n \"\"\"\n We could use cosine similarity or dot product to calculate the similarity between vectors.\n In practice, we have found it makes little difference. \n \"\"\"\n return np.dot(np.array(x), np.array(y))\n\n\n def order_document_sections_by_query_similarity(self, query: str, contexts: dict[(str, str), np.array]) -> list[(float, (str, str))]:\n \"\"\"\n Find the query embedding for the supplied query, and compare it against all of the pre-calculated document embeddings\n to find the most relevant sections. \n \n Return the list of document sections, sorted by relevance in descending order.\n \"\"\"\n query_embedding = self.get_embedding(query)\n \n document_similarities = sorted([\n (self.vector_similarity(query_embedding, doc_embedding), doc_index) for doc_index, doc_embedding in contexts.items()\n ], reverse=True)\n \n return document_similarities\n\n \n \n MAX_SECTION_LEN = 500\n SEPARATOR = \"\\n\\n* \"\n\n tokenizer = GPT2TokenizerFast.from_pretrained(\"gpt2\")\n separator_len = len(tokenizer.tokenize(SEPARATOR))\n\n f\"Context separator contains {separator_len} tokens\"\n\n\n def construct_prompt_with_text(self,question: str, context_embeddings: dict, text: list, previous_context: str = None) -> str:\n \"\"\"\n Fetch relevant \n \"\"\"\n if previous_context is not None:\n most_relevant_document_sections = self.order_document_sections_by_query_similarity(question + previous_context, context_embeddings)\n else:\n most_relevant_document_sections = self.order_document_sections_by_query_similarity(question, context_embeddings)\n \n chosen_sections = []\n chosen_sections_len = 0\n chosen_sections_indexes = []\n \n for _, section_index in most_relevant_document_sections:\n # Add contexts until we run out of space. \n document_section = \"\\n\".join(text[section_index-3:section_index+3])\n \n chosen_sections_len += len(document_section.split()) + self.separator_len\n if chosen_sections_len > self.MAX_SECTION_LEN:\n break\n \n chosen_sections.append(self.SEPARATOR + document_section)\n chosen_sections_indexes.append(str(section_index))\n \n # Useful diagnostic information\n print(f\"Selected {len(chosen_sections)} document sections:\",\"\\t\".join(chosen_sections_indexes))\n header = \"\"\"Answer the questions as truthfully as possible using the provided context, and if the answer is not contained within the context, say \"I don't know.\" Put ``` before and after the code.\\n\\nGeneralized Information:\\n\"\"\"\n \n prompt = header + \"\".join(chosen_sections) \n if previous_context is not None:\n prompt = prompt + \"\\n\\n\" + previous_context\n prompt = prompt +\"\\n \" + question\n return prompt\n\n COMPLETIONS_API_PARAMS = {\n # We use temperature of 0.0 because it gives the most predictable, factual answer.\n \"temperature\": 1.0,\n \"max_tokens\": 300,\n \"model\": COMPLETIONS_MODEL,\n }\n\n def answer_query_with_context(\n self,\n query: str,\n df: pd.DataFrame,\n document_embeddings,\n previous_context = None,\n show_prompt: bool = True\n ) -> str:\n prompt = self.construct_prompt_with_text(\n query,\n document_embeddings,\n df,\n previous_context\n )\n \n if show_prompt:\n with open('temp.txt', 'w') as f:\n for line in prompt:\n f.write(f\"{line}\")\n f.flush()\n\n response = openai.Completion.create(\n prompt=prompt,\n **self.COMPLETIONS_API_PARAMS\n )\n\n return response[\"choices\"][0][\"text\"].strip(\" \\n\")\n\n\n # answer= answer_query_with_context(\"How old was he when he won?\",text, context_embeddings, previous_context)\n # print(answer)\nimport os\nif __name__ == \"__main__\":\n b = Brain()\n b.reload_models()\n # directory = '../training_data/'\n # for filename in os.listdir(directory):\n # if filename.endswith(\".txt\"):\n # b.process_file(directory+filename,'all right')\n # b.process_file('../training_data/overview.txt')\n # print([i for i, j in enumerate(b.text) if 'Junru He' in j])\n # b.save_models()\n ","repo_name":"ashaychangwani/gptutor","sub_path":"api/brain.py","file_name":"brain.py","file_ext":"py","file_size_in_byte":8701,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"5654873234","text":"import os\nimport psycopg2\nfrom dotenv import load_dotenv\n\nSELECT_POLLS = \"select * from polls;\"\n\nSELECT_OPTION_IN_POLLS = \"\"\"\nselect options.option_text, count(votes.option_id) from options\ninner join polls on options.poll_id = polls.id\ninner join votes on options.id = votes.option_id\nwhere polls.id = %s\ngroup by options.option_text;\"\"\"\n\nSELECT_POLLS_AND_VOTES = \"\"\"\nselect polls.title, count(votes.option_id)\nfrom options inner join polls on options.poll_id = polls.id\ninner join votes on options.id = votes.option_id\ngroup by polls.title;\"\"\"\n\nload_dotenv()\n\nconnection = psycopg2.connect(os.environ[\"DATABASE_URL\"])\n\n\ndef get_polls():\n with connection:\n with connection.cursor() as cursor:\n cursor.execute(SELECT_POLLS)\n return cursor.fetchall()\n\n\ndef get_options(poll_id: int):\n with connection:\n with connection.cursor() as cursor:\n cursor.execute(SELECT_OPTION_IN_POLLS, (poll_id,))\n return cursor.fetchall()\n\n\n# okay while there are only a few polls but not useful after \n# there are hundreds of polls - would need a list of polls to charts.\ndef get_poll_votes():\n with connection:\n with connection.cursor() as cursor:\n cursor.execute(SELECT_POLLS_AND_VOTES)\n return cursor.fetchall()\n\n","repo_name":"northernocean/learning-postgres-python","sub_path":"visualization/database_g.py","file_name":"database_g.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"13063493776","text":"import pyarrow\nimport pyarrow.parquet as pq\n\nparquet_file='data_0_0_0.snappy.parquet'\n\ndef arrow_to_ch_type(arrow_type):\n if isinstance(arrow_type.type, pyarrow.lib.Decimal128Type):\n precision = arrow_type.type.precision\n scale = arrow_type.type.scale\n if (scale != 0):\n ch_type = \"Decimal({0}, {1})\".format(precision, scale)\n elif (precision <= 10):\n ch_type = \"UInt32\"\n elif (precision <= 19):\n ch_type = \"UInt64\"\n elif (precision <= 38):\n ch_type = \"UInt128\"\n else:\n ch_type = \"UInt256\"\n if isinstance(arrow_type.type, pyarrow.lib.Time32Type):\n ch_type = \"DateTime\"\n elif arrow_type.type == \"string\":\n ch_type = \"String\"\n else:\n print(arrow_type, type(arrow_type.type))\n raise Exception(f\"Unknown type: {arrow_type.type}\")\n\n if arrow_type.nullable:\n return \"Nullable({0})\".format(ch_type)\n else:\n return ch_type\n\ndef process():\n schema = pq.read_schema(parquet_file)\n print(\"---schema---\")\n print(schema)\n\n print(\"CREATE TABLE IF NOT EXISTS foo (\")\n\n for name in schema.names:\n col_type = arrow_to_ch_type(schema.field(name))\n print(\" {0} {1},\".format(name, col_type))\n\n print(\")\")\n print(\"Engine=MergeTree()\")\n print(\"PARTITION BY tuple()\")\n print(\"ORDER BY tuple()\")\n\n data = pq.ParquetFile(parquet_file)\n print(\"---file---\")\n print(data.read())\n\nif __name__ == '__main__':\n process()\n","repo_name":"Altinity/clickhouse-sql-examples","sub_path":"snowflake/python/read-types.py","file_name":"read-types.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"41"} +{"seq_id":"74033646203","text":"# dp[n][i] 는 자릿수가 n개일때, i로 끝나는 계단수의 갯수\n# dp[n][i] = dp[n-1][i-1] + dp[n-1][i+1]\n# why : n=4, i=2라고하면,\n# xxx2 라는 숫자가 되게 된다. xxx2 가 계단수가되려면 xx32 or xx12\n# xx3 이 계단수가되려면 dp[n][i] = dp[n-1][i-1] + dp[n-1][i+1] 이 식을 똑같이 적용\n# i가 0이면 dp[n][i] = dp[n-1][i+1], xx0의 계단수는 x10밖에없음\n# i가 9면 dp[n][i] = dp[n-1][i-1], xx9의 계단수는 x89밖에 없음\n\nn = int(input())\ndp = [[0 for _ in range(11)] for _ in range(101)]\n\nfor i in range(1,10):\n dp[1][i] = 1\n\nif n >= 2:\n for i in range(2,n+1):\n for j in range(10):\n if j == 0:\n dp[i][j] = dp[i-1][j+1] % 1000000000\n elif j == 9:\n dp[i][j] = dp[i-1][j-1] % 1000000000\n else:\n dp[i][j] = (dp[i-1][j-1] + dp[i-1][j+1]) % 1000000000\n\nprint(sum(dp[n])% 1000000000)","repo_name":"Ssunbell/Algorithm_Study","sub_path":"06주차/BOJ_10844/BOJ_10844_이승환.py","file_name":"BOJ_10844_이승환.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"41"} +{"seq_id":"40720300982","text":"import shutil\r\nimport random\r\nimport os \r\n\r\n# Function to count the number of objects in each file\r\ndef count_objects(filename):\r\n with open(filename, 'r') as f:\r\n lines = f.readlines()\r\n return len(lines)\r\n\r\n# Define various file names and dataset parameters\r\ndataset_name = '....'\r\nlabels_avx_kitti_format = 'labels_AVX'\r\npoints_AVX_database = 'points_AVX'\r\ncalib_avx_kitti_format = 'calib_AVX'\r\n#############################################################################\r\nmy_data_size = int(3712*1) # The size of the data to be used\r\npercent_synthetic = ... # The proportion of synthetic data to be used\r\n# 0.9 for %90 KITTI %10 AVX training\r\n#############################################################################\r\nkitti_training_train = 'kitti_training_train' # The directory containing the real training data\r\n\r\n# Define the directories for the synthetic data\r\nlabels_synthetic = f'data/AVX_DATA/Version_6/Train/{labels_avx_kitti_format}'\r\npoints_synthetic = f'data/AVX_DATA/Version_6/Train/{points_AVX_database}'\r\ncalib_synthetic = f'data/AVX_DATA/Version_6/Train/{calib_avx_kitti_format}'\r\n\r\n# Define the directories for the real data\r\npoints_train_real = f'data/{kitti_training_train}'\r\nlabels_real = 'data/kitti/training/label_2'\r\nimages_real = 'data/kitti/training/image_2'\r\ncalib_real = 'data/kitti/training/calib'\r\n\r\n# Define the destination directories for the various components of the dataset\r\npoints_destination_dir = f'data/{dataset_name}/training/velodyne'\r\nlabels_destination_dir = f'data/{dataset_name}/training/label_2'\r\ncalib_destination_dir = f'data/{dataset_name}/training/calib'\r\nimage_destination_dir = f'data/{dataset_name}/training/image_2'\r\nimagesets = f'data/{dataset_name}/ImageSets'\r\n\r\n# Create the destination directories if they do not exist\r\nif not os.path.exists(points_destination_dir):\r\n os.makedirs(points_destination_dir)\r\nif not os.path.exists(labels_destination_dir):\r\n os.makedirs(labels_destination_dir)\r\nif not os.path.exists(calib_destination_dir):\r\n os.makedirs(calib_destination_dir)\r\nif not os.path.exists(image_destination_dir):\r\n os.makedirs(image_destination_dir)\r\nif not os.path.exists(imagesets):\r\n os.makedirs(imagesets)\r\n\r\n# Get a list of all the label files in the synthetic data directory\r\nlabel_files_synth = []\r\nfor filename in os.listdir(labels_synthetic):\r\n if filename.endswith('.txt'):\r\n label_files_synth.append(os.path.join(labels_synthetic, filename))\r\n\r\n# Count the number of objects in each synthetic data file\r\nobject_counts = {}\r\nfor filename in label_files_synth:\r\n object_counts[filename] = count_objects(filename)\r\n\r\n# Sort the synthetic data files based on their object count\r\nsorted_files = sorted(label_files_synth, key=lambda x: object_counts[x], reverse=True)\r\n\r\n# Calculate the size of the synthetic data based on the given percentage\r\nsynthetic_data_size = int(my_data_size * percent_synthetic)\r\n\r\n# Select the synthetic data files up to the calculated size\r\nselected_avx = sorted_files[:synthetic_data_size]\r\n\r\n# Convert the synthetic label files to point cloud files\r\nfor i in range(len(selected_avx)):\r\n selected_avx[i] = selected_avx[i].replace(labels_avx_kitti_format, points_AVX_database).replace(\".txt\", \".npy\")\r\n\r\n# Get a list of all the point cloud files in the real data directory\r\nfiles_points_train_real = os.listdir(points_train_real)\r\nfiles_points_train_real = [f for f in files_points_train_real if f.endswith('.npy')]\r\nfiles_points_train_real.sort()\r\n\r\n# Select the real data files up to the remaining size\r\nfiles_points_train_real = files_points_train_real[:my_data_size-synthetic_data_size]\r\n\r\n# Add the directory path to each real data file\r\nfiles_points_train_real = [os.path.join(points_train_real, f) for f in files_points_train_real]\r\n\r\n# Merge the synthetic and real data lists and shuffle them\r\ntrain_database = files_points_train_real + selected_avx\r\nrandom.shuffle(train_database)\r\n\r\n# Keep track of existing files to avoid duplication\r\nexisting_files = set(os.listdir(points_destination_dir))\r\n\r\nnew_filenames = []\r\n\r\n# Copy and rename each file in the merged list to the destination directory\r\nfor i, filename in enumerate(train_database):\r\n if filename.endswith('.npy'):\r\n # Define new filenames based on the index\r\n new_filename = '{:06d}.npy'.format(i)\r\n while new_filename in existing_files:\r\n i += 1\r\n new_filename = '{:06d}.npy'.format(i)\r\n shutil.copy(filename, os.path.join(points_destination_dir,new_filename))\r\n\r\n # Copy and rename corresponding label, calibration, and image files\r\n new_label_filename = new_filename.split('.')[0] + '.txt'\r\n new_image_filename = new_filename.split('.')[0] + '.png'\r\n\r\n # Handle synthetic data\r\n if points_AVX_database in filename:\r\n file_name = os.path.basename(filename)\r\n new_file_name = file_name[:-4] + '.txt'\r\n new_file_path = filename.replace(points_AVX_database, labels_avx_kitti_format)\r\n label_AVX_full_path = new_file_path.replace(file_name, new_file_name)\r\n shutil.copy(label_AVX_full_path, os.path.join(labels_destination_dir,new_label_filename))\r\n new_file_path_calib = filename.replace(points_AVX_database, calib_avx_kitti_format)\r\n calib_AVX_full_path = new_file_path_calib.replace(file_name, new_file_name)\r\n shutil.copy(calib_AVX_full_path, os.path.join(calib_destination_dir,new_label_filename))\r\n\r\n # Handle real data\r\n if kitti_training_train in filename:\r\n file_name = os.path.basename(filename)\r\n file_name = file_name[:-4]\r\n label_kitti_train_path = os.path.join(labels_real, file_name + '.txt')\r\n shutil.copy(label_kitti_train_path, os.path.join(labels_destination_dir,new_label_filename))\r\n calib_kitti_train_path = os.path.join(calib_real, file_name + '.txt')\r\n shutil.copy(calib_kitti_train_path, os.path.join(calib_destination_dir,new_label_filename))\r\n image_kitti_train_path = os.path.join(images_real, file_name + '.png')\r\n shutil.copy(image_kitti_train_path, os.path.join(image_destination_dir,new_image_filename))\r\n\r\n # Add the new filename to the existing files set and new filenames list\r\n existing_files.add(new_filename)\r\n new_filenames.append(new_filename.split('.')[0])\r\n\r\n# Create a train.txt file with the names of the point cloud files to be used for training\r\nwith open(os.path.join(imagesets, 'train.txt'), 'w') as f:\r\n for filename in new_filenames:\r\n f.write(filename + '\\n')\r\n","repo_name":"aydnzn/Enhancing-LiDAR-based-3D-Object-Detection","sub_path":"docs/OrganizeData.py","file_name":"OrganizeData.py","file_ext":"py","file_size_in_byte":6643,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"41"} +{"seq_id":"26602511075","text":"#!/usr/bin/env python3\nimport os\nimport sys\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import zscore\n\ntemplist = []\ntemplist1 = []\n\n#variables for file path\nfilepath1 = \"C:\\\\Users\\\\Stella\\\\Miniconda3\\\\envs\\\\py3k\\\\Tools\\\\Capstone1\\\\CRtest.csv\"\nfilepath2 = \"C:\\\\Users\\\\Stella\\\\Miniconda3\\\\envs\\\\py3k\\\\Tools\\\\Capstone1\\\\CRtrain.csv\"\n\n#read training .csv and put into pandas dataframe trainDF\ntrainDF = pd.read_csv(filepath2)\n#explore dataframe\n#print(trainDF.head()) \n#print(trainDF.tail())\n#print(trainDF.shape)\n#print(trainDF.info())\n#print(trainDF.describe())\n#print(trainDF.dtypes)\n\n#find object types (columns: Id, idhogar, dependence, edjefe, and edjefa) all other types are of float64 and int64\nobjctType = trainDF.dtypes == object\n#print(trainDF.loc[:,objctType])\n\n#find columns containing null values\nnull_columns = trainDF.columns[trainDF.isnull().any()]\n#print out which columns have null values and how many rows contain null values \n#print(trainDF[null_columns].isnull().sum())\n\n#compare columns r4t3 = Total persons in household and tamviv = number of persons living in household\n#print(trainDF['r4t3'].equals(trainDF['tamviv']))\n#compare columns r4t3 = Total persons in household and hogar_total = # of total individuals in household\n#print(trainDF['r4t3'].equals(trainDF['hogar_total']))\n#compare columns tamviv = number of persons living in household and hogar_total = # of total individuals in household\n#print(trainDF['tamviv'].equals(trainDF['hogar_total']))\n#compare colums hhsize = houlsehold size and tamhog = size of household\n#print(trainDF['hhsize'].equals(trainDF['tamhog']))\n#compare columns agesq = 'Age squared' and SQBage = 'age squared'\n#print(trainDF['agesq'].equals(trainDF['SQBage']))\n\n#drop duplicate columns and columns with excessive amounts of null values v18q1 (number of tablets household owns) and rez_esc (number of years behind in school)\ntrainDF = trainDF.drop(['agesq', 'tamhog', 'v18q1', 'rez_esc', 'v2a1'], axis=1)\n#print(trainDF.shape)\n\n#drop rows with missing values in meaneduc (average years of education for adults 18+), and SQBmeaned (square of meanduc row). Dropping one will drop both\ntrainDF = trainDF.dropna(subset = ['meaneduc'])\n\n#drop duplicate rows print shape to see frow counts, no duplicate rows existed so none were dropped\ntrainDF = trainDF.drop_duplicates()\n#print(trainDF.shape)\n\n#save column names as list\ncolumns = list(trainDF.columns.values)\n#print(columns)\n\n#Test again to find columns with missing value to make sure there aren't any\nnull_columns = trainDF.columns[trainDF.isnull().any()]\n#print out which columns have null values and how many rows contain null values \n#print(trainDF[null_columns].isnull().sum())\n#print(trainDF.shape)\n\n#find only numeric columns and calculate standard deviation for each\nnumeric_cols = trainDF.select_dtypes(include=[np.number]).columns\ncolsStdDev = trainDF[numeric_cols].std()\n\n#find any columns with a standard deviation of 0 and drop them from the numeric_cols list\nfor index, value in colsStdDev.iteritems():\n\tif value == 0.0:\n\t\ttemplist.append(index)\n\n\n#drop columns from trainDF that have a standard deviation of 0 (all row values for column are same value)\ntrainDF = trainDF.drop(templist, axis=1)\n#find numeric columns again\nnumeric_cols = trainDF.select_dtypes(include=[np.number]).columns\n#print(len(numeric_cols))\n\n#find columns that have more than 2 values (most columns contain a 1 value for yes and a 0 value for no)\nfor column in numeric_cols:\n\tif (trainDF[column].value_counts(dropna=False).count() > 2):\n\t\ttemplist1.append(column)\n\n#apply zscore to remaining columns \nzscoreNumericCols = trainDF[templist1].transform(zscore)\noutliers = ((zscoreNumericCols[templist1] < -3) | (zscoreNumericCols[templist1] > 3))\n\n#run a describe for columns\n#print(zscoreNumericCols.describe())","repo_name":"stellysters/Springboard-stuff","sub_path":"Capstone1/DataClean.py","file_name":"DataClean.py","file_ext":"py","file_size_in_byte":3855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"34361092464","text":"import json\nimport room\nimport player\nimport os\nimport interpret\n\ndef start():\n\tclearScreen()\n\trm = room.Room()\n\tplr = player.Player()\n\tinter = interpret.Interpret(rm)\n\tgameLoop(rm,plr, inter)\n\ndef clearScreen():\n\tos.system('clear')\t\n\ndef gameLoop(rm, plr, inter):\n\tclearScreen()\n\tplaying = True\n\t'main loop for the game. Includes flavor text print line, that should play only at entrance into room'\n\twhile playing == True:\n\t\tsame_room = True\n\t\t'displays the flavor text for the room'\n\t\trm.printDescription()\n\t\t'game loop for player interactions in game'\n\t\twhile same_room == True:\n\t\t\tplr_input = prompt().lower()\n\t\t\tinter.interpret(plr_input)\n\t\t\t\n\t\t\t\n\ndef prompt():\n\tcommand = input(\"\\nWhat will you do? \")\n\treturn command\n\ndef displayLs(ls):\n\tfor i in ls:\n\t\tprint(i)\n\nstart()","repo_name":"LoganW94/Text-Adventure","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"3932520031","text":"class Dog():\n\n # Class Attributes\n species = 'mammal'\n\n # initializer / Instance attributes\n def __init__(self, name, age, breed):\n self.name = name\n self.age = age\n self.breed = breed\n\n\n# Initiate the Dog Object\nRocky = Dog('Rocky', 8, 'German Sheperd')\nRani = Dog('Rani', 10, 'Doberman')\nSimba = Dog('Simba', 12, 'Labrador')\n\n# Access the instance attributes\nprint(\"{} is a {} and he is {} years old.\".format(Rocky.name, Rocky.breed,\n Rocky.age))\nprint(\"{} is a {} and she is {} years old\".format(Rani.name, Rani.breed,\n Rani.age))\n\n# Checking for mammal\nif (Rocky.species == 'mammal'):\n print(\"{} is a {}\".format(Rocky.name, Rocky.species))\n\n\n# Determine the oldest dog\ndef get_oldest_dog(*args):\n return max(args)\n\n\n# Output\nprint(\"The oldest dog is {} years old.\".format(get_oldest_dog(Rocky.age, Rani.\n age, Simba.age)))\n","repo_name":"prashant0085/Python-Scripts","sub_path":"dog_class.py","file_name":"dog_class.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"32796096198","text":"from torch import nn\nimport torch\nfrom torch.nn.modules import conv\nfrom torch.nn.modules.conv import Conv2d\nfrom einops import rearrange\n\n\n\ndef conv_bn(inp,oup,kernel_size=3,stride=1):\n return nn.Sequential(\n nn.Conv2d(inp,oup,kernel_size=kernel_size,stride=stride,padding=kernel_size//2),\n nn.BatchNorm2d(oup),\n nn.SiLU()\n )\n\nclass PreNorm(nn.Module):\n def __init__(self,dim,fn):\n super().__init__()\n self.ln=nn.LayerNorm(dim)\n self.fn=fn\n def forward(self,x,**kwargs):\n return self.fn(self.ln(x),**kwargs)\n\nclass FeedForward(nn.Module):\n def __init__(self,dim,mlp_dim,dropout) :\n super().__init__()\n self.net=nn.Sequential(\n nn.Linear(dim,mlp_dim),\n nn.SiLU(),\n nn.Dropout(dropout),\n nn.Linear(mlp_dim,dim),\n nn.Dropout(dropout)\n )\n def forward(self,x):\n return self.net(x)\n\nclass Attention(nn.Module):\n def __init__(self,dim,heads,head_dim,dropout):\n super().__init__()\n inner_dim=heads*head_dim\n project_out=not(heads==1 and head_dim==dim)\n\n self.heads=heads\n self.scale=head_dim**-0.5\n\n self.attend=nn.Softmax(dim=-1)\n self.to_qkv=nn.Linear(dim,inner_dim*3,bias=False)\n \n self.to_out=nn.Sequential(\n nn.Linear(inner_dim,dim),\n nn.Dropout(dropout)\n ) if project_out else nn.Identity()\n\n def forward(self,x):\n qkv=self.to_qkv(x).chunk(3,dim=-1)\n q,k,v=map(lambda t:rearrange(t,'b p n (h d) -> b p h n d',h=self.heads),qkv)\n dots=torch.matmul(q,k.transpose(-1,-2))*self.scale\n attn=self.attend(dots)\n out=torch.matmul(attn,v)\n out=rearrange(out,'b p h n d -> b p n (h d)')\n return self.to_out(out)\n\n\n\n\n\nclass Transformer(nn.Module):\n def __init__(self,dim,depth,heads,head_dim,mlp_dim,dropout=0.):\n super().__init__()\n self.layers=nn.ModuleList([])\n for _ in range(depth):\n self.layers.append(nn.ModuleList([\n PreNorm(dim,Attention(dim,heads,head_dim,dropout)),\n PreNorm(dim,FeedForward(dim,mlp_dim,dropout))\n ]))\n\n\n def forward(self,x):\n out=x\n for att,ffn in self.layers:\n out=out+att(out)\n out=out+ffn(out)\n return out\n\nclass MobileViTAttention(nn.Module):\n def __init__(self,in_channel=3,dim=512,kernel_size=3,patch_size=7,depth=3,mlp_dim=1024):\n super().__init__()\n self.ph,self.pw=patch_size,patch_size\n self.conv1=nn.Conv2d(in_channel,in_channel,kernel_size=kernel_size,padding=kernel_size//2)\n self.conv2=nn.Conv2d(in_channel,dim,kernel_size=1)\n\n self.trans=Transformer(dim=dim,depth=depth,heads=8,head_dim=64,mlp_dim=mlp_dim)\n\n self.conv3=nn.Conv2d(dim,in_channel,kernel_size=1)\n self.conv4=nn.Conv2d(2*in_channel,in_channel,kernel_size=kernel_size,padding=kernel_size//2)\n\n def forward(self,x):\n y=x.clone() #bs,c,h,w\n\n ## Local Representation\n y=self.conv2(self.conv1(x)) #bs,dim,h,w\n\n ## Global Representation\n _,_,h,w=y.shape\n y=rearrange(y,'bs dim (nh ph) (nw pw) -> bs (ph pw) (nh nw) dim',ph=self.ph,pw=self.pw) #bs,h,w,dim\n y=self.trans(y)\n y=rearrange(y,'bs (ph pw) (nh nw) dim -> bs dim (nh ph) (nw pw)',ph=self.ph,pw=self.pw,nh=h//self.ph,nw=w//self.pw) #bs,dim,h,w\n\n ## Fusion\n y=self.conv3(y) #bs,dim,h,w\n y=torch.cat([x,y],1) #bs,2*dim,h,w\n y=self.conv4(y) #bs,c,h,w\n\n return y\n\n\nclass MV2Block(nn.Module):\n def __init__(self,inp,out,stride=1,expansion=4):\n super().__init__()\n self.stride=stride\n hidden_dim=inp*expansion\n self.use_res_connection=stride==1 and inp==out\n\n if expansion==1:\n self.conv=nn.Sequential(\n nn.Conv2d(hidden_dim,hidden_dim,kernel_size=3,stride=self.stride,padding=1,groups=hidden_dim,bias=False),\n nn.BatchNorm2d(hidden_dim),\n nn.SiLU(),\n nn.Conv2d(hidden_dim,out,kernel_size=1,stride=1,bias=False),\n nn.BatchNorm2d(out)\n )\n else:\n self.conv=nn.Sequential(\n nn.Conv2d(inp,hidden_dim,kernel_size=1,stride=1,bias=False),\n nn.BatchNorm2d(hidden_dim),\n nn.SiLU(),\n nn.Conv2d(hidden_dim,hidden_dim,kernel_size=3,stride=1,padding=1,groups=hidden_dim,bias=False),\n nn.BatchNorm2d(hidden_dim),\n nn.SiLU(),\n nn.Conv2d(hidden_dim,out,kernel_size=1,stride=1,bias=False),\n nn.SiLU(),\n nn.BatchNorm2d(out)\n )\n def forward(self,x):\n if(self.use_res_connection):\n out=x+self.conv(x)\n else:\n out=self.conv(x)\n return out\n\nclass MobileViT(nn.Module):\n def __init__(self,image_size,dims,channels,num_classes,depths=[2,4,3],expansion=4,kernel_size=3,patch_size=2):\n super().__init__()\n ih,iw=image_size,image_size\n ph,pw=patch_size,patch_size\n assert iw%pw==0 and ih%ph==0\n\n self.conv1=conv_bn(3,channels[0],kernel_size=3,stride=patch_size)\n self.mv2=nn.ModuleList([])\n self.m_vits=nn.ModuleList([])\n\n\n self.mv2.append(MV2Block(channels[0],channels[1],1))\n self.mv2.append(MV2Block(channels[1],channels[2],2))\n self.mv2.append(MV2Block(channels[2],channels[3],1))\n self.mv2.append(MV2Block(channels[2],channels[3],1)) # x2\n self.mv2.append(MV2Block(channels[3],channels[4],2))\n self.m_vits.append(MobileViTAttention(channels[4],dim=dims[0],kernel_size=kernel_size,patch_size=patch_size,depth=depths[0],mlp_dim=int(2*dims[0])))\n self.mv2.append(MV2Block(channels[4],channels[5],2))\n self.m_vits.append(MobileViTAttention(channels[5],dim=dims[1],kernel_size=kernel_size,patch_size=patch_size,depth=depths[1],mlp_dim=int(4*dims[1])))\n self.mv2.append(MV2Block(channels[5],channels[6],2))\n self.m_vits.append(MobileViTAttention(channels[6],dim=dims[2],kernel_size=kernel_size,patch_size=patch_size,depth=depths[2],mlp_dim=int(4*dims[2])))\n\n \n self.conv2=conv_bn(channels[-2],channels[-1],kernel_size=1)\n self.pool=nn.AvgPool2d(image_size//32,1)\n self.fc=nn.Linear(channels[-1],num_classes,bias=False)\n\n def forward(self,x):\n y=self.conv1(x) #\n y=self.mv2[0](y)\n y=self.mv2[1](y) #\n y=self.mv2[2](y)\n y=self.mv2[3](y)\n y=self.mv2[4](y) #\n y=self.m_vits[0](y)\n\n y=self.mv2[5](y) #\n y=self.m_vits[1](y)\n\n y=self.mv2[6](y) #\n y=self.m_vits[2](y)\n\n y=self.conv2(y)\n y=self.pool(y).view(y.shape[0],-1) \n y=self.fc(y)\n return y\n\ndef mobilevit_xxs():\n dims=[60,80,96]\n channels= [16, 16, 24, 24, 48, 64, 80, 320]\n return MobileViT(224,dims,channels,num_classes=1000)\n\ndef mobilevit_xs():\n dims = [96, 120, 144]\n channels = [16, 32, 48, 48, 64, 80, 96, 384]\n return MobileViT(224, dims, channels, num_classes=1000)\n\ndef mobilevit_s():\n dims = [144, 192, 240]\n channels = [16, 32, 64, 64, 96, 128, 160, 640]\n return MobileViT(224, dims, channels, num_classes=1000)\n\n\ndef count_paratermeters(model):\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\n\nif __name__ == '__main__':\n input=torch.randn(1,3,224,224)\n\n ### mobilevit_xxs\n mvit_xxs=mobilevit_xxs()\n out=mvit_xxs(input)\n print(out.shape)\n\n ### mobilevit_xs\n mvit_xs=mobilevit_xs()\n out=mvit_xs(input)\n print(out.shape)\n\n\n ### mobilevit_s\n mvit_s=mobilevit_s()\n out=mvit_s(input)\n print(out.shape)\n\n ","repo_name":"xmu-xiaoma666/External-Attention-pytorch","sub_path":"model/backbone/MobileViT.py","file_name":"MobileViT.py","file_ext":"py","file_size_in_byte":7734,"program_lang":"python","lang":"en","doc_type":"code","stars":9994,"dataset":"github-code","pt":"41"} +{"seq_id":"71491691323","text":"import sys\nfrom PyQt5.QtWidgets import QWidget, QLineEdit, QPushButton, QApplication, QVBoxLayout\n\n\nclass QLineEditDemo(QWidget):\n\tdef __init__(self):\n\t\tsuper(QLineEditDemo, self).__init__()\n\t\tself.setWindowTitle(\"这是一个QLineEditDemo\")\n\n\t\tself.line_edit_1 = QLineEdit(self)\n\t\tself.line_edit_1.setPlaceholderText(\"input:\")\n\t\tprint(\"1. \" + self.line_edit_1.placeholderText())\n\n\t\tself.v_layout = QVBoxLayout(self)\n\t\tself.v_layout.addWidget(self.line_edit_1)\n\n\nif __name__ == \"__main__\":\n\tapp = QApplication(sys.argv)\n\twidget = QLineEditDemo()\n\twidget.show()\n\tsys.exit(app.exec_())\n","repo_name":"MmMmMqianq/OmronOfficeSystem","sub_path":"Lern_PyQt5/ControlWidget/QLineEditDemo.py","file_name":"QLineEditDemo.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"22674094255","text":"import string\r\ndef phone(strng, num):\r\n alphanum = string.ascii_lowercase + string.ascii_uppercase + '1234567890'\r\n special = '!@#$%&*_;?'\r\n list = strng.split('\\n')\r\n list.remove('')\r\n number = []\r\n name = []\r\n address = []\r\n to_add_num = ''\r\n to_add_name = ''\r\n to_add_add = ''\r\n plus_posit = 0\r\n angle1_posit = 0\r\n angle2_posit = 0\r\n add_posit = 0\r\n for data in list:\r\n plus_posit = data.find('+')\r\n if data[plus_posit + 2].isdigit():\r\n to_add_num = data[plus_posit + 1 : plus_posit + 1 + 15]\r\n else:\r\n to_add_num = data[plus_posit + 1 : plus_posit + 1 + 14]\r\n number.append(to_add_num)\r\n data = data.replace('+' + to_add_num, '')\r\n\r\n angle1_posit = data.find('<')\r\n angle2_posit = data.find('>')\r\n to_add_name = data[angle1_posit + 1 : angle2_posit]\r\n name.append(to_add_name)\r\n data = data.replace('<' + to_add_name + '>', '')\r\n \r\n temp = []\r\n for i in range(len(data)):\r\n if data[i].isalnum():\r\n add_posit = i\r\n break\r\n data = data[add_posit:].replace('_', ' ').replace(', ', ' ')\r\n for remove in special:\r\n data = data.replace(remove, '').strip()\r\n temp = data.split(' ')\r\n data = ' '.join(temp)\r\n address.append(data.replace(' ', ' '))\r\n print(data)\r\n \r\n mark = 0\r\n count = 0\r\n for i in number:\r\n if i == num:\r\n count += 1\r\n if count == 1:\r\n mark = number.index(num)\r\n return 'Phone => {}, Name => {}, Address => {}'.format(number[mark], name[mark], address[mark])\r\n elif count == 0:\r\n return 'Error => Not found: {}'.format(num)\r\n else:\r\n return 'Error => Too many people: {}'.format(num)\r\n","repo_name":"lauyuda/codewars","sub_path":"python/5 kyu/phone directory.py","file_name":"phone directory.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"21561456548","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 11 14:49:56 2019\n\n@author: Administrator\n\"\"\"\n\n'''\n理解霍夫变换的概念\n如何在图像中检测直线\n函数:cv2.HoughLines(),cv2.HoughLinesP()\n\n原理: 霍夫变换在检测各种形状的技术中非常流行,如果要检测的形状可以用数学表达式写出,就可以使用\n 霍夫变换检测,即使要检测的形状存在一点破坏或者扭曲也可以使用\n\n 一条直线可以用 y = Kx + c 或者 r = x COSθ + y SINθ 表示\n r是原点到直线的垂直距离,θ是直线的垂线与横轴顺时针的夹角\n\n霍夫变换工作原理 : \n 每一条直线都可以用(r, θ)表示,所以首先创建一个2D数组(累加器),初始化这个累加器\n 所有的值为0,行表示r,列表示θ,这个数组的大小决定了最后结果的准确性。\n 如果需要角度的精度为1度,那就需要180列,对于r,最大值为图片对角线距离,如果精确度\n 要达到一个像素级别,那么行数应该与图像对角线的距离相等\n\n现在如果我们有一个100x100的直线位于图像的中央,取直线上第一个点,知道了(x,y),把这个坐标\n代入上面的公式,遍历θ的取值:0,1,2,3.....180,分别求出r,这样就有一系列的(r, θ)数值对\n如果这个数值对在累加器中也存在相应的位置,就在这个位置加1,接下来再取之间第二个点,\n重复操作后,取累加器中最大值的位置,这个位置(r, θ)就是一条直线\n\nopencv中实现Hough变换\n\n函数cv2.HoughLines(),返回值就是(r, θ),r的单位是像素,θ的单位是弧度\n\n函数参数:1.二值化图像,所以进行霍夫变换前首先进行二值化或者进行Canny边缘检测\n 2,3参数分别代表r,θ的精度\n 4.阈值,只有累加的值高于这个阈值时才被认为是一条直线\n'''\n\nimport numpy as np\nimport cv2\n\nimg = cv2.imread('sudoku.png')\ngray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\nedges = cv2.Canny(gray,50,150)\n\nlines = cv2.HoughLines(edges,1,np.pi/180,200)\n\nfor rho,theta in lines.squeeze():\n a = np.cos(theta)\n b = np.sin(theta)\n x0 = a*rho\n y0 = b*rho\n x1 = int(x0 + 1000*(-b))\n y1 = int(y0 + 1000*(a))\n x2 = int(x0 - 1000*(-b))\n y2 = int(y0 - 1000*(a))\n cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)\n\ncv2.imshow('result',img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\n\n'''\n霍夫变换仅仅一条直线就需要遍历许多点才能得到参数\n从图像上随机选取点来检测对于检测直线来说已经足够,同时对应得降低阈值,因为总的点数少了\nProbabilistic_Hough_Transform就是对霍夫变换进行的优化\n函数 cv2.HoughLinesP()\n新增参数: 1.minLineLength 线的最短长度,比这个长度小的线被忽略\n 2.MaxLineGap 两条线之间最大间隔,如果小于这值,两条直线被看成一条直线\n这个函数的返回值就是直线的起点和终点。\n\n'''\n\n\nimport numpy as np\nimport cv2\n\nimg = cv2.imread('sudoku.png')\ngray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\nedges = cv2.Canny(gray,50,150)\n\nminLineLength = 200\nmaxLineGap = 10\nlines = cv2.HoughLinesP(edges,1,np.pi/180,100,minLineLength,maxLineGap)\n#print(lines.shape)\n\nfor x1,y1,x2,y2 in lines.squeeze():\n cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)\n\ncv2.imshow('result',img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\n\n\n\n'''\nHough圆形变换\n利用霍夫变换在图像中找出圆形\n函数:cv2.HoughCircles()\n\n原理: 圆形的数学表达式为(X-Xcenter)**2 + (Y - Ycenter) = R**2\n 由上式看出,需要三个参数确定一个圆形\n 因此使用霍夫变换的累加器必须是3维的\n 这样效率会很低,所以opencv使用了霍夫梯度法,它可以使用边界的梯度信息\n\n'''\n\nimport cv2\nimport numpy as np\n\nimg = cv2.imread('coins.jpg')\nimg = cv2.medianBlur(img,5)\nimg_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n#参数:1.输入图像,2.边缘检测方法 3.累加器分辨率,1代表与输入一致,2代表是输入的一半\n # 4.圆心之间的最小距离,5.Canny梯度检测的阈值 6.累加器的阈值 最后两个为圆的最大最小半径\n #主要调参数4,5,6\ncircles = cv2.HoughCircles(img_gray,cv2.HOUGH_GRADIENT,1,10,param1=70,param2=100,minRadius=0,maxRadius=0)\n\ncircles = np.uint16(np.around(circles))\n\nfor i in circles.squeeze():\n cv2.circle(img,(i[0],i[1]),i[2],(0,255,0),2) #绘制找到的圆形\n cv2.circle(img,(i[0],i[1]),2,(0,0,255),2) #绘制找到的圆心\n\ncv2.imshow('Circle',img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"sealee9/Opencv-python","sub_path":"Hough直线变换.py","file_name":"Hough直线变换.py","file_ext":"py","file_size_in_byte":4725,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"18057771903","text":"#\n# @lc app=leetcode id=56 lang=python3\n#\n# [56] Merge Intervals\n#\nclass Solution:\n def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n ret = []\n for i in sorted(intervals,key = lambda x:x[0]):\n if ret and i[0]<=ret[-1][1]:\n ret[-1][1] = max(ret[-1][-1],i[1])\n else:\n ret.append(i)\n return ret\n\n","repo_name":"lockhartey/leetcode","sub_path":"56.merge-intervals.py","file_name":"56.merge-intervals.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"12638938967","text":"\"\"\"\nHYPOTHESIS TESTING\n1 Sample T-Testing\nLet's imagine the fictional business BuyPie, which sends ingredients for pies to your household so that you can make them from scratch. Suppose that a product manager wants online BuyPie orders to cost around 1000 Rupees on average. In the past day, 50 people made an online purchase and the average payment per order was only 850 Rupees. Are people really spending less than 1000 Rupees on average? Or is this just the result of chance and a small sample size?\n\nWe can test this using a 1 Sample T Test, which compares a sample mean to a hypothetical population mean.\n\nWhen we conduct a 1 Sample T Test, we want to first create a null hypothesis, which is a prediction that the observed sample comes from a population with a particular mean. For example: \"the average cost of a BuyPie order is 1000 Rupees\". Note that, even if the null hypothesis were true, it's very unlikely that any observed sample mean will be exactly 1000.00 Rupees.\n\nWe also have to determine an alternative hypothesis, which is a statement about the kind of difference we are interested in. For example, we might form the following alternative hypothesis: \"The average cost of a BuyPie order is not 1000 Rupees\".\n\nIf we form the null and alternative tests as indicated above, the test asks the following question: \"Suppose that that the average cost of a BuyPie order is 1000 Rupees; what is the probability of observing a sample of 50 orders with cost as different or more different from 1000 as we did (i.e., < 850 or > 1150)?\"\n\nThe result of the test is a p-value. If the p-value is less than our pre-chosen threshold (usually .05), we can reject the null hypothesis in favor of the alternative. When we reject the null, we are saying that it would be unlikely to observe our sample (or something more extreme) if the null hypothesis were true.\n\nIt is important to note that we cannot conclude anything about magnitude of differences based on this test; for example, we might conclude that it is unlikely that the average cost of all BuyPie orders is 1000 Rupees; however, we cannot then conclude that the average cost is closer to 850 Rupees.\n\nSciPy has a function called ttest_1samp, which performs a 1 Sample T-Test for you.\n\nttest_1samp requires two inputs, a sample distribution (eg. the list of the 50 observed purchase prices) and a mean to test against (eg. 1000):\n\ntstat, pval = ttest_1samp(example_distribution, expected_mean)\nprint pval\nIt also returns two outputs: the t-statistic (which we won't cover in this course), and the p-value - telling us how confident we can be that the sample of values came from a distribution with the specified mean.\n\"\"\"\nfrom scipy.stats import ttest_1samp\nimport numpy as np\n\n\"\"\"\nWe have provided a small dataset called prices, representing the purchase prices of customers to BuyPie.com in the past hour.\n\nFirst, print out prices to the console and examine the numbers.\n\"\"\"\nprices = np.genfromtxt(\"prices.csv\")\nprint(prices)\n\n\"\"\"\nEven with a small dataset like this, it is hard to make judgments from just looking at the numbers.\n\nTo understand the data better, let's look at the mean. Calculate the mean of prices using np.mean. Store it in a variable called prices_mean and print it out.\n\"\"\"\nprices_mean = np.mean(prices)\nprint(\"prices_mean: \" + str(prices_mean))\n\n\"\"\"Use ttest_1samp with prices to see what p-value the experiment returns for this distribution, where we expect the mean to be 1000.\n\"\"\"\ntstat, pval = ttest_1samp(prices, 1000)\nprint(\"pval: \" + str(pval))\n\n","repo_name":"MarceloDL-A/Python","sub_path":"16-Hypothesis_Testing_with_SciPy/1_Sample_T-Testing.py","file_name":"1_Sample_T-Testing.py","file_ext":"py","file_size_in_byte":3540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"42651664578","text":"from __future__ import unicode_literals\nimport dataent\nfrom dataent.model.document import Document\n\nclass ErrorSnapshot(Document):\n\tno_feed_on_delete = True\n\n\tdef onload(self):\n\t\tif not self.parent_error_snapshot:\n\t\t\tself.db_set('seen', True, update_modified=False)\n\n\t\t\tfor relapsed in dataent.get_all(\"Error Snapshot\", filters={\"parent_error_snapshot\": self.name}):\n\t\t\t\tdataent.db.set_value(\"Error Snapshot\", relapsed.name, \"seen\", True, update_modified=False)\n\n\t\t\tdataent.local.flags.commit = True\n\n\tdef validate(self):\n\t\tparent = dataent.get_all(\"Error Snapshot\",\n\t\t\tfilters={\"evalue\": self.evalue, \"parent_error_snapshot\": \"\"},\n\t\t\tfields=[\"name\", \"relapses\", \"seen\"], limit_page_length=1)\n\n\t\tif parent:\n\t\t\tparent = parent[0]\n\t\t\tself.update({\"parent_error_snapshot\": parent['name']})\n\t\t\tdataent.db.set_value('Error Snapshot', parent['name'], 'relapses', parent[\"relapses\"] + 1)\n\t\t\tif parent[\"seen\"]:\n\t\t\t\tdataent.db.set_value(\"Error Snapshot\", parent[\"name\"], \"seen\", False)\n","repo_name":"dataent/dataent","sub_path":"dataent/core/doctype/error_snapshot/error_snapshot.py","file_name":"error_snapshot.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"4981488223","text":"from django.urls import path\n\nfrom .views import *\n\napp_name = 'todos'\n\nurlpatterns = [ \n path('', todo_list),\n path('create/', todo_create),\n path('<id>/', todo_detail), \n path('<id>/update/', todo_update), \n path('<id>/delete/', todo_delete), \n]\n","repo_name":"lajtaristvan/django-todoapp","sub_path":"todo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"9274854647","text":"import pyglet\r\nfrom pyglet.gl import *\r\n\r\nclass Asset_Loader():\r\n def __init__(self,Asset_location):\r\n pyglet.resource.path = [\".\",Asset_location]\r\n pyglet.resource.reindex()\r\n \r\n def load_image(self,file_name,size=None,center_image=False,center_animation = False):\r\n image = pyglet.resource.image(file_name)\r\n glEnable(GL_TEXTURE_2D)\r\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)\r\n if size != None:\r\n image.width = size[0]\r\n image.height = size[1]\r\n if center_image:\r\n self.center_image(image)\r\n if center_animation:\r\n self.center_animation(image)\r\n return image\r\n def center_animation(self,animation):\r\n \"\"\"center animation frames anchor\"\"\"\r\n for i in range(len(self.animation.frames)):\r\n self.center_image(self.animation.frames[i].image)\r\n\r\n def center_image(self,image):\r\n \"\"\"Sets an image's achor point to its center\"\"\"\r\n image.anchor_x = image.width // 2\r\n image.anchor_y = image.height // 2","repo_name":"DeclanO99/ROV_2020","sub_path":"Python/Drone Emulation/Asset_loader.py","file_name":"Asset_loader.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"41"} +{"seq_id":"70269065725","text":"import pandas as pd\nimport numpy as np\n\n\n\ndata_types_dict = {\n 'row_id': 'int64',\n 'timestamp': 'int64',\n 'user_id': 'int32',\n 'content_id': 'int16',\n 'content_type_id': 'int8',\n 'task_container_id': 'int16',\n 'user_answer': 'int8',\n 'answered_correctly': 'int8',\n}\n\n\ndf = pd.read_csv(\"../input/riiid-test-answer-prediction/train.csv\",\n dtype=data_types_dict)\n\ndf_question = pd.read_csv(\"../input/riiid-test-answer-prediction/questions.csv\",\n dtype={\"bundle_id\": \"int32\",\n \"question_id\": \"int32\",\n \"correct_answer\": \"int8\",\n \"part\": \"int8\"})\ndf_lecture = pd.read_csv(\"../input/riiid-test-answer-prediction/lectures.csv\",\n dtype={\"lecture_id\": \"int32\",\n \"tag\": \"int16\",\n \"part\": \"int8\"})\n\ndiv_num = 10\ndf[f\"user_id_div{div_num}\"] = df[\"user_id\"]%div_num\n\nfor user_id, w_df in df.groupby(f\"user_id_div{div_num}\"):\n print(len(w_df))\n w_df.drop([f\"user_id_div{div_num}\", \"row_id\"], axis=1).to_pickle(f\"../input/riiid-test-answer-prediction/split10_base/train_{user_id}.pickle\")\n w_df1 = pd.merge(w_df[w_df[\"content_type_id\"]==0], df_question, how=\"left\", left_on=\"content_id\", right_on=\"question_id\")\n w_df2 = pd.merge(w_df[w_df[\"content_type_id\"]==1], df_lecture, how=\"left\", left_on=\"content_id\", right_on=\"lecture_id\")\n w_df = pd.concat([w_df1, w_df2])\n w_df[\"tag\"] = w_df[\"tag\"].fillna(-1).astype(\"int16\")\n w_df[\"correct_answer\"] = w_df[\"correct_answer\"].fillna(-1).astype(\"int8\")\n w_df[\"bundle_id\"] = w_df[\"bundle_id\"].fillna(-1).astype(\"int32\")\n print(len(w_df))\n w_df = w_df.drop([\"question_id\", \"lecture_id\"], axis=1)\n w_df.drop([f\"user_id_div{div_num}\", \"row_id\"], axis=1).to_pickle(f\"../input/riiid-test-answer-prediction/split10/train_{user_id}.pickle\")\n","repo_name":"kurupical/riiid","sub_path":"script/make_data.py","file_name":"make_data.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"41"} +{"seq_id":"28992476639","text":"# loading pre-requisites\n\nfrom typing import Optional\nfrom fastapi import FastAPI\n\nfrom pydantic import BaseModel\nfrom starlette.responses import StreamingResponse\n\n# creating the app based on FastAPI\napp = FastAPI()\n\n# creating a Item \nclass Item(BaseModel):\n name: str\n price: float \n is_offer: Optional[bool] = None \n\n# default root\n@app.get(\"/\")\ndef read_root():\n return {\"Hello\":\"World\"}\n\n# another example item route\n# we are using async await here for example\n# https://fastapi.tiangolo.com/async/#in-a-hurry\n@app.get(\"/items/{item_id}\")\nasync def read_item(item_id: int, q: Optional[str] = None):\n return {\"item_id\": item_id, \"q\": q}\n\n@app.put(\"/items/{item_id}\")\nasync def update_item(item_id: int, item:Item):\n return {\"item_id\": item_id, \"item_name\": item.name, \"item_price\": item.price}","repo_name":"vmsgiridhar/Flask","sub_path":"fastapi0/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"5479243135","text":"\"\"\"\nEscribir un programa que permita ingresar dos numeros enteros a y b. \nEl programa debe mostrar:\n\nLa suma de los numeros pares entre a y b.\nEl producto de los numeros impares entre a y b.\n\"\"\"\n\na = int(input(\"Ingrese a: \"))\nb = int(input(\"Ingrese b: \"))\n\nwhile a > b: #mientras ERROR!!!\n print(f\"ERROR: {a} <= {b}\")\n b = int(input(\"Ingrese b: \"))\n\nproducto_impar = 1 #no puede ser 0 por que es absorvente\nsuma_pares = 0\n\nfor numero in range (a,b+1):\n if numero % 2 == 0:\n suma_pares += numero\n else:\n producto_impar *= numero\n\nprint(f\"el producto de los impares es: {producto_impar}\")\nprint(f\"la suma de los pares es: {suma_pares}\")","repo_name":"ecerella/argentina_programa_4.0_python","sub_path":"Programación Python-Tramo II/flujosderepeticion/ejercicio40.py","file_name":"ejercicio40.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"23670559028","text":"from typing import List\n\nfrom database import db\nfrom api.model.customer import Customer\n\nfrom api.utils.exceptions import CustomerDoesNotExistException\n\n\nclass CustomerDatabaseOperations:\n\n @staticmethod\n def get_all_customers() -> List[Customer]:\n return Customer.query.all()\n\n @staticmethod\n def get_customer_by_id(customer_id: int) -> Customer:\n customer = Customer.query.get(customer_id)\n if customer is None:\n raise CustomerDoesNotExistException(customer_id)\n return customer\n\n @staticmethod\n def add_new_customer(first_name: str, last_name: str) -> Customer:\n new_customer = Customer(first_name, last_name)\n db.session.add(new_customer)\n db.session.commit()\n return new_customer\n\n @staticmethod\n def delete_customer(customer_id: int) -> None:\n customer = Customer.query.get(customer_id)\n if customer is None:\n raise CustomerDoesNotExistException(customer_id)\n db.session.delete(customer)\n db.session.commit()\n return None\n\n\n","repo_name":"zarenkamp/banking_api","sub_path":"api/database_operation/customer_db_operations.py","file_name":"customer_db_operations.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"4396612187","text":"import pygame\nimport pygame.draw as dr\nfrom random import randint\n\npygame.init()\n\nFPS = 30\na = 500\nr_max = 50\nr_min = 10 # минимальный радиус шариков\nv_max = 100 # максимальная скорость шариков\nmax_number_of_one_type_objects = 10\ndt = 0.1\nscreen = pygame.display.set_mode((a, a))\nRED = (255, 0, 0)\nBLUE = (0, 0, 255)\nYELLOW = (255, 255, 0)\nGREEN = (0, 255, 0)\nMAGENTA = (255, 0, 255)\nCYAN = (0, 255, 255)\nBLACK = (0, 0, 0)\n\nCOLORS = [RED, BLUE, YELLOW, GREEN, MAGENTA, CYAN]\n\nballs = []\ndonuts = []\n\n\nclass Target:\n \"\"\" Конструктор класса Target\n Args:\n balls_additional_points - количество добавленных очков при попадании в шарик\n donuts_additional_points - количество добавленных очков при попадании в пончик\n \"\"\"\n\n def __init__(self, balls_additional_points=1, donuts_additional_points=5):\n self.x = randint(r_max, a - r_max) # координата шарика или пончика по горизонтали\n self.y = randint(r_max, a - r_max) # координата шарика или пончика по вертикали\n self.vx = randint(-v_max, v_max) # горизонтальная скорость шарика или пончика\n self.vy = randint(-v_max, v_max) # вертикальная скорость или пончикашарика\n self.r = randint(r_min, r_max) # радиус шарика или внешний радиус пончика,\n # а также удвоенный внутренний радиус пончика\n self.color = COLORS[randint(0, 5)] # цвет шарика или пончика\n self.ball_screen = screen\n self.balls_additional_points = balls_additional_points\n self.donuts_additional_points = donuts_additional_points\n\n\nclass Ball(Target):\n def move(self):\n \"\"\" Перемещение цели по прошествии единицы времени dt с учётом отбивания от стенок. Движение прямолинейное.\n \"\"\"\n self.x += self.vx * dt\n self.y += self.vy * dt\n if (self.x - self.r) < 0:\n self.x = self.r\n self.vx = -self.vx\n elif (self.x + self.r) > a:\n self.vx = -self.vx\n self.x = a - self.r\n if (self.y - self.r) < 0:\n self.y = self.r\n self.vy = -self.vy\n elif (self.y + self.r) > a:\n self.vy = -self.vy\n self.y = a - self.r\n\n def draw(self):\n \"\"\"Функция рисует шарик\"\"\"\n dr.circle(screen, self.color, (self.x, self.y), self.r)\n\n def hittest(self, plus_scores, live):\n \"\"\" Проверка попадания в площадь шарика.\n Args:\n plus_scores - количество очков\n live - положитльная переменная меньше, равная остатку деления очков на 10, при достижении 10 генерируется\n новая партия объектов\n Returns:\n plus_scores\n live\n \"\"\"\n eventx, eventy = pygame.mouse.get_pos()\n if ((eventx - self.x) ** 2 + (eventy - self.y) ** 2) <= (self.r ** 2):\n plus_scores += self.balls_additional_points\n live += self.balls_additional_points\n print('A ball is caught! +', self.balls_additional_points, ' score! scores:', plus_scores)\n self.x = randint(r_max, a - r_max)\n self.y = randint(r_max, a - r_max)\n self.vx = randint(-v_max, v_max)\n self.vy = randint(-v_max, v_max)\n self.r = randint(r_min, r_max)\n self.color = COLORS[randint(0, 5)]\n return plus_scores, live\n\n\nclass Donut(Target):\n def move(self):\n \"\"\" Перемещение цели по прошествии единицы времени dt с учётом отбивания от стенок. Движение броуновское.\n \"\"\"\n self.x += randint(-v_max, v_max) * 3 * dt\n self.y += randint(-v_max, v_max) * 3 * dt\n if (self.x - self.r) < 0:\n self.x = self.r\n elif (self.x + self.r) > a:\n self.x = a - self.r\n if (self.y - self.r) < 0:\n self.y = self.r\n elif (self.y + self.r) > a:\n self.vy = -self.vy\n self.y = a - self.r\n\n def draw(self):\n \"\"\"Функция рисует мяч\"\"\"\n dr.circle(screen, self.color, (self.x, self.y), self.r, round(self.r / 2))\n\n def hittest(self, plus_scores, live):\n \"\"\" Проверка попадания в площадь пончика.\n Args:\n plus_scores - количество очков\n live - положитльная переменная меньше, равная остатку деления очков на 10, при достижении 10 генерируется\n новая партия объектов\n Returns:\n plus_scores\n live - о\n \"\"\"\n eventx, eventy = pygame.mouse.get_pos()\n if ((eventx - self.x) ** 2 + (eventy - self.y) ** 2) <= (self.r ** 2):\n if ((eventx - self.x) ** 2 + (eventy - self.y) ** 2) >= ((self.r ** 2) / 4):\n plus_scores += self.donuts_additional_points\n live += self.donuts_additional_points\n print('A ball is caught! +', self.donuts_additional_points, ' score! scores:', plus_scores)\n self.x = randint(r_max, a - r_max)\n self.y = randint(r_max, a - r_max)\n self.vx = randint(-v_max, v_max)\n self.vy = randint(-v_max, v_max)\n self.r = randint(r_min, round(r_max/2))\n self.color = COLORS[randint(0, 5)]\n return plus_scores, live\n\n\nclass Scores:\n def __init__(self, scores=0, live_points=0):\n \"\"\"\"Конструктор класса Scores\n Args:\n scores - количество очков\n live_points - положитльная переменная меньше, равная остатку деления очков на 10, при достижении 10\n генерируется\n новая партия объектов\n \"\"\"\n self.live_points = live_points\n self.scores = scores\n\n def click_check(self):\n \"\"\"\"Проверка попадания в цели и обновление счёта очков\n \"\"\"\n for i in balls:\n self.scores, self.live_points = i.hittest(self.scores, self.live_points)\n for i in donuts:\n self.scores, self.live_points = i.hittest(self.scores, self.live_points)\n\n def save_scores(self):\n \"\"\"создаёт файл с упорядоченным набором очков игроков\"\"\"\n results_file = open('scores.txt', 'a')\n results_file.write(name_of_player + '\\n')\n results_file.write(str(self.scores) + '\\n')\n results_file.close()\n counting_variable = 0\n scores_statistics = []\n names_data = []\n results_file = open('scores.txt', 'r')\n while True:\n line = results_file.readline()\n if not line:\n break\n if (-1) ** counting_variable == 1:\n name = str(line)\n name.replace('\\n', '')\n names_data.append(name)\n elif (-1) ** counting_variable == -1:\n number_of_scores = str(line)\n number_of_scores.replace('\\n', '')\n number_of_scores = int(number_of_scores)\n scores_statistics.append(number_of_scores)\n counting_variable += 1\n results_file.close()\n results_file = open('scores.txt', 'w')\n while max(scores_statistics) > -1:\n results_file.write(names_data[scores_statistics.index(max(scores_statistics))])\n results_file.write(str(scores_statistics[scores_statistics.index(max(scores_statistics))]) + '\\n')\n scores_statistics[scores_statistics.index(max(scores_statistics))] = -1\n results_file.close()\n\n\ndef generate_array_of_objects(array_balls, array_donuts):\n \"\"\"Создание массива пончиков и массива шариков или регенерация рандомных значений\n Args:\n array_balls - массив шариков\n array_donuts - массив пончиков\n \"\"\"\n number_of_balls = randint(2, max_number_of_one_type_objects)\n for i in range(number_of_balls):\n new_ball = Ball()\n array_balls.append(new_ball)\n number_of_donuts = randint(2, max_number_of_one_type_objects)\n for i in range(number_of_donuts):\n new_donut = Donut()\n array_donuts.append(new_donut)\n\n\ndef draw_array_of_objects():\n \"\"\"Рисует массив пончиков и массив шариков\n \"\"\"\n screen.fill(BLACK)\n for i in balls:\n i.draw()\n for i in donuts:\n i.draw()\n\n\ndef move_array_of_objects():\n \"\"\"Изменение координат целей с прошествием единицы времени\n \"\"\"\n for i in balls:\n i.move()\n for i in donuts:\n i.move()\n\n\nfinished = False\npygame.display.update()\nclock = pygame.time.Clock()\nprint('Введите имя игрока:')\nname_of_player = input()\ngame = Scores()\ngenerate_array_of_objects(balls, donuts)\ndraw_array_of_objects()\n\nwhile not finished:\n clock.tick(FPS)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n game.save_scores()\n finished = True\n elif event.type == pygame.MOUSEBUTTONDOWN:\n game.click_check()\n if game.live_points >= 10:\n balls.clear()\n donuts.clear()\n generate_array_of_objects(balls, donuts)\n game.live_points = 0\n move_array_of_objects()\n draw_array_of_objects()\n pygame.display.update()\n\npygame.quit()\n","repo_name":"morgaiangelina/infa_2021_morgaiangelina","sub_path":"6catchaball2/5.2.py","file_name":"5.2.py","file_ext":"py","file_size_in_byte":10237,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"12361427985","text":"from django.contrib import admin\nfrom .models import Categoria, Curso\n\nclass datCurso(admin.ModelAdmin):\n list_display = ('id','titulo', 'descricao', 'datainicio', 'mostrar' )\n list_editable = ('mostrar',)\n list_display_links = ('titulo',)\n search_fields = ('titulo',)\n list_per_page = 2\n list_filter = ('titulo',)\n\nadmin.site.register(Categoria)\nadmin.site.register(Curso,datCurso)\n","repo_name":"VitoriaIzaine/base-django","sub_path":"home/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"21240001457","text":"from pygame import *\r\nimport random\r\n\r\nwindow = display.set_mode((700, 500))\r\ndisplay.set_caption(\"Пинг-понг\")\r\nbackground = transform.scale(image.load(\"kviddich2.jpg\"), (700, 500))\r\n\r\n# mixer.init()\r\n# mixer.music.load(\"space.ogg\")\r\n# mixer.music.play()\r\n\r\nclock = time.Clock()\r\n\r\nFPS = 60\r\n\r\nfinish = False\r\n\r\nclass GameSprite(sprite.Sprite):\r\n def __init__(self, player_image, player_x, player_y, player_speed, size_x, size_y):\r\n super().__init__()\r\n self.image = transform.scale(image.load(player_image), (size_x, size_y))\r\n self.speed = player_speed\r\n self.rect = self.image.get_rect()\r\n self.rect.x = player_x\r\n self.rect.y = player_y\r\n self.size_x = size_x\r\n self.size_y = size_y\r\n \r\n def reset(self):\r\n window.blit(self.image, (self.rect.x, self.rect.y))\r\n\r\n\r\nclass Player(GameSprite):\r\n def update_p1(self):\r\n keys_pressed = key.get_pressed()\r\n\r\n if keys_pressed[K_UP] and self.rect.y > 0:\r\n self.rect.y -= self.speed\r\n \r\n if keys_pressed[K_DOWN] and self.rect.y < 340:\r\n self.rect.y += self.speed \r\n\r\n def update_p2(self):\r\n keys_pressed = key.get_pressed()\r\n\r\n if keys_pressed[K_w] and self.rect.y > 0:\r\n self.rect.y -= self.speed\r\n \r\n if keys_pressed[K_s] and self.rect.y < 340:\r\n self.rect.y += self.speed \r\n\r\n\r\n# lost = 0\r\n\r\n# class Enemy(GameSprite):\r\n# def update(self):\r\n# global lost\r\n# self.rect.y += self.speed\r\n# if self.rect.y > 500:\r\n# self.rect.y = 0\r\n# self.rect.x = random.randint(100, 600)\r\n# lost = lost + 1\r\n\r\n# class Asteroid(GameSprite):\r\n# def update(self):\r\n# self.rect.y += self.speed\r\n# if self.rect.y > 500:\r\n# self.rect.y = 0\r\n# self.rect.x = random.randint(100, 600)\r\n\r\nplayer1 = Player(\"metlaa.jpg\", 0, 100, 8, 85, 160)\r\nplayer2 = Player(\"metlaa.jpg\", 620, 100, 8, 85, 160)\r\n\r\n# font.init()\r\n# font1 = font.SysFont(\"Arial\", 36)\r\n# font2 = font.SysFont(\"Arial\", 44)\r\n# font3 = font.SysFont(\"Arial\", 56)\r\n\r\n# enemies = sprite.Group()\r\n\r\n# for i in range(5):\r\n# enemy = Enemy(\"ufo.png\", random.randint(100, 600), 0, random.randint(1, 2), 64, 64)\r\n# enemies.add(enemy)\r\n\r\n# asteroids = sprite.Group()\r\n\r\n# for i in range(3):\r\n# asteroid = Asteroid(\"asteroid.png\", random.randint(100, 600), 0, random.randint(1, 2), 60, 60)\r\n# asteroids.add(asteroid)\r\n\r\ngame = True\r\n\r\n# amount = 0\r\n\r\n# win = font2.render(\"YOU ARE THE CHAMPION, MY FRIEND!\", True, (0, 255, 0))\r\n# defend = font3.render(\"HAHA! LOSER\", True, (255, 0, 0))\r\n\r\n\r\n\r\nwhile game:\r\n window.blit(background, (0, 0))\r\n\r\n for e in event.get():\r\n if e.type == QUIT:\r\n game = False\r\n\r\n# elif e.type == KEYDOWN:\r\n# if e.key == K_SPACE:\r\n# player.fire()\r\n\r\n if finish != True:\r\n \r\n player1.reset()\r\n player1.update_p1()\r\n player2.reset()\r\n player2.update_p2()\r\n# enemy.reset()\r\n# enemy.update()\r\n# enemies.draw(window)\r\n# enemies.update()\r\n# bullets.draw(window)\r\n# bullets.update()\r\n# asteroid.update()\r\n# asteroid.reset()\r\n\r\n# sprites_list = sprite.groupcollide(enemies, bullets, True, True)\r\n \r\n# for i in sprites_list:\r\n# amount += 1\r\n# enemy = Enemy(\"ufo.png\", random.randint(100, 600), 0, random.randint(1, 2), 64, 64)\r\n# enemies.add(enemy)\r\n\r\n# text_lose = font1.render(\"Пропущено: \" + str(lost), 1, (255, 255, 255))\r\n# window.blit(text_lose, (4, 60))\r\n\r\n# text_win = font1.render(\"Счёт: \" + str(amount), 1, (255, 255, 255))\r\n# window.blit(text_win, (4, 20))\r\n\r\n# if amount >= 10:\r\n# finish = True\r\n# window.blit(win, (50, 250))\r\n\r\n# if lost >= 4 or sprite.collide_rect(player, enemy) or sprite.collide_rect(player, asteroid):\r\n# finish = True\r\n# window.blit(defend, (200, 250))\r\n\r\n clock.tick(FPS)\r\n display.update()","repo_name":"NikaMorow/Ping_pong","sub_path":"Ping_pong.py","file_name":"Ping_pong.py","file_ext":"py","file_size_in_byte":4163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"14167813909","text":"\"\"\"\n##### WEATHER #####\n\nThis module contains the WeatherGetter class for dealing with weather via the Dark Sky API.\n\n\"\"\"\n\nimport requests\n\n\nclass WeatherGetter():\n def __init__(self):\n self.request_url = 'https://api.darksky.net/forecast'\n self.api_key = 'e6bfcec2ea2816540bd5b4cb01a3950e'\n \n # Chicago latitude & longitude: 41.8781° N, 87.6298° W (West Longitude represented as negative)\n self.latitude = '41.8781'\n self.longitude = '-87.6298'\n self.excludes = 'exclude=currently,minutely,daily,alerts,flags'\n self.weather_on_date = {}\n \n def get_weather(self, date_string):\n # if weather already fetched for that date, return it from object's weather_on_date dictionary\n \n weather = self.weather_on_date.get(date_string)\n if weather: return weather\n \n \n # otherwise get weather using Dark Sky API\n # Dark Sky request url - https://api.darksky.net/forecast/[key]/[latitude],[longitude],[time]\n # datetime string format - [YYYY]-[MM]-[DD]T[HH]:[MM]:[SS]\n \n url = f'{ self.request_url }/{ self.api_key }/{ self.latitude },{ self.longitude },{ date_string }T00:00:00?{ self.excludes }'\n \n response = requests.get(url) #, headers=self.headers)\n weather = response.json()\n \n self.weather_on_date[date_string] = weather\n \n return weather","repo_name":"muoyo/chicago-ridesharing","sub_path":"python_files/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"14280148375","text":"from deeplab_v3 import Deeplab_v3\nfrom data_utils import DataSet\n\nimport cv2\nimport os\nimport tensorflow as tf\nimport pandas as pd\nimport numpy as np\nfrom color_utils import color_predicts\nfrom predicts_utils import total_image_predict\nfrom discriminative_loss import discriminative_loss\nfrom metric_utils import iou\n\n\nclass args:\n batch_size = 4\n lr = 2e-4\n test_display = 2000\n weight_decay = 5e-4\n model_name = 'discriminativte_loss'\n batch_norm_decay = 0.95\n test_image_path = 'dataset/val/images/00001.png'\n test_label_path = 'dataset/val/labels/00001.png'\n multi_scale = True # 是否多尺度预测\n gpu_num = 0\n pretraining = True\n\n\n# 打印以下超参数\nfor key in args.__dict__:\n if key.find('__') == -1:\n offset = 20 - key.__len__()\n print(key + ' ' * offset, args.__dict__[key])\n\n# 使用那一块显卡\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\ndata_path_df = pd.read_csv('dataset/path_list.csv')\ndata_path_df = data_path_df.sample(frac=1) # 第一次打乱\n\ndataset = DataSet(image_path=data_path_df['image'].values, label_path=data_path_df['label'].values)\n\nmodel = Deeplab_v3(batch_norm_decay=args.batch_norm_decay)\n\nimage = tf.placeholder(tf.float32, [None, 1024, 1024, 3], name='input_x')\nlabel = tf.placeholder(tf.int32, [None, 1024, 1024])\nlr = tf.placeholder(tf.float32, )\n\nlogits = model.forward_pass(image)\nlogits_prob = tf.nn.softmax(logits=logits, name='logits_prob')\npredicts = tf.argmax(logits, axis=-1, name='predicts')\nfeature_dim = 4\nparam_var = 1.\nparam_dist = 1\nparam_reg = 0.001\ndelta_v = 0.5\ndelta_d = 1.5\nstarter_learning_rate = 1e-4\nlearning_rate_decay_rate = 0.96\nlearning_rate_decay_interval = 5000\n\n\nglobal_step = tf.Variable(0, trainable=False)\nlearning_rate = tf.train.exponential_decay(starter_learning_rate, global_step,\n learning_rate_decay_interval, learning_rate_decay_rate, staircase=True)\ndisc_loss, l_var, l_dist, l_reg = discriminative_loss(logits, label, feature_dim, (1024,1024),\n delta_v, delta_d, param_var, param_dist, param_reg)\n\nvariables_to_restore = tf.trainable_variables(scope='resnet_v2_50')\nwith tf.name_scope('Instance/Adam'):\n train_op = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(disc_loss, var_list=tf.trainable_variables(),\n global_step=global_step)\nadam_initializers = [var.initializer for var in tf.global_variables() if 'Adam' in var.name]\n# finetune resnet_v2_50的参数(block1到block4)\nrestorer = tf.train.Saver(variables_to_restore)\n# cross_entropy\n\n\nsaver = tf.train.Saver(tf.all_variables())\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\n# summary_op = tf.summary.merge_all()\n\nwith tf.Session(config=config) as sess:\n sess.run(tf.local_variables_initializer())\n sess.run(tf.global_variables_initializer())\n graph = tf.get_default_graph()\n\n if args.pretraining:\n # finetune resnet_v2_50参数,需要下载权重文件\n restorer.restore(sess, 'ckpts/resnet_v2_50/resnet_v2_50.ckpt')\n\n log_path = 'logs/%s/' % args.model_name\n model_path = 'ckpts/%s/deeplabV3' % args.model_name\n\n if not os.path.exists(model_path): os.makedirs(model_path)\n if not os.path.exists('./logs'): os.makedirs('./logs')\n if not os.path.exists(log_path): os.makedirs(log_path)\n\n summary_writer = tf.summary.FileWriter('%s/' % log_path, sess.graph)\n\n learning_rate = args.lr\n saver = tf.train.Saver()\n for step in range(1, 70001):\n if step == 30000 or step == 50000:\n learning_rate = learning_rate / 10\n x_tr, y_tr = dataset.next_batch(args.batch_size)\n _, step_prediction, step_loss, step_l_var, step_l_dist, step_l_reg = sess.run([\n train_op,\n logits,\n disc_loss,\n l_var,\n l_dist,\n l_reg],\n feed_dict={\n image: x_tr,\n label: y_tr,\n model._is_training: True,\n lr: learning_rate})\n if step * args.batch_size == 5000:\n train_text = 'step: {}, step_loss: {},step_l_var: {},step_l_dist: {},step_l_reg: {}'.format(\n step, step_loss,step_l_var,step_l_dist,step_l_reg)\n print(train_text)\n if step == 30000:\n saver.save(sess, model_path, write_meta_graph=True, global_step=step)\n # 前50, 100, 200 看一下是否搞错了\n if (step in [50, 500]) or (step > 0 and step % args.test_display == 0):\n\n test_predict = total_image_predict(\n ori_image_path=args.test_image_path,\n input_placeholder=image,\n logits_prob_node=logits_prob,\n is_training_placeholder=model._is_training,\n sess=sess,\n multi_scale=args.multi_scale\n\n )\n\n test_label = cv2.imread(args.test_label_path, cv2.IMREAD_GRAYSCALE)\n\n # 保存图片\n cv2.imwrite(filename='%spredict_color_%d.png' % (log_path, step),\n img=color_predicts(img=test_predict))\n\n result = iou(y_pre=np.reshape(test_predict, -1),\n y_true=np.reshape(test_label, -1))\n\n print(\"======================%d======================\" % step)\n for key in result.keys():\n offset = 40 - key.__len__()\n print(key + ' ' * offset + '%.4f' % result[key])\n\n test_summary = tf.Summary(\n value=[tf.Summary.Value(tag=key, simple_value=result[key]) for key in result.keys()]\n )\n\n # 记录summary\n summary_writer.add_summary(test_summary, step)\n summary_writer.flush()\n saver.save(sess, model_path, write_meta_graph=True, global_step=70000)","repo_name":"adnappp/deeplabv3","sub_path":"discriminative_loss_train.py","file_name":"discriminative_loss_train.py","file_ext":"py","file_size_in_byte":5887,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"41353381616","text":"import pytest\nfrom brownie import reverts\nfrom utils.test_helpers import access_controll_revert_message\n\n\n@pytest.fixture(scope=\"module\")\ndef extra_evm_script_factories(accounts):\n return accounts[3:8]\n\n\ndef test_deploy(owner, EVMScriptFactoriesRegistry):\n \"Must deploy MotionsRegistry contract with correct params\"\n contract = owner.deploy(EVMScriptFactoriesRegistry, owner)\n assert contract.hasRole(contract.DEFAULT_ADMIN_ROLE(), owner)\n\n\ndef test_add_evm_script_factory_called_without_permissions(\n stranger,\n evm_script_factories_registry,\n):\n \"Must revert with correct Access Control message if called by address without 'DEFAULT_ADMIN_ROLE'\"\n permissions = stranger.address + \"ffccddee\"\n with reverts(access_controll_revert_message(stranger)):\n evm_script_factories_registry.addEVMScriptFactory(\n stranger, permissions, {\"from\": stranger}\n )\n\n\ndef test_add_evm_script_factory_empty_permissions(\n owner, stranger, evm_script_factories_registry\n):\n \"Must revert with message 'INVALID_PERMISSIONS' if called with empty permissions\"\n with reverts(\"INVALID_PERMISSIONS\"):\n evm_script_factories_registry.addEVMScriptFactory(\n stranger, \"0x\", {\"from\": owner}\n )\n\n\ndef test_add_evm_script_factory_invalid_length(\n owner, stranger, evm_script_factories_registry\n):\n \"Must revert with message 'INVALID_PERMISSIONS' if called with permissions which have incorrect length\"\n with reverts(\"INVALID_PERMISSIONS\"):\n evm_script_factories_registry.addEVMScriptFactory(\n stranger, \"0x0011223344\", {\"from\": owner}\n )\n\n\ndef test_add_evm_script(owner, stranger, evm_script_factories_registry):\n \"Must add new EVMScript factory and emit EVMScriptFactoryAdded(_evmScriptFactory, _permissions) event\"\n permissions = stranger.address + \"ffccddee\"\n tx = evm_script_factories_registry.addEVMScriptFactory(\n stranger, permissions, {\"from\": owner}\n )\n assert tx.events[\"EVMScriptFactoryAdded\"][\"_evmScriptFactory\"] == stranger\n assert tx.events[\"EVMScriptFactoryAdded\"][\"_permissions\"] == permissions\n\n\ndef test_add_evm_script_twice(owner, stranger, evm_script_factories_registry):\n \"Must revert with message 'EVM_SCRIPT_FACTORY_ALREADY_ADDED'\"\n \"if called with already listed EVMScript factory address\"\n permissions = stranger.address + \"ffccddee\"\n evm_script_factories_registry.addEVMScriptFactory(\n stranger, permissions, {\"from\": owner}\n )\n with reverts(\"EVM_SCRIPT_FACTORY_ALREADY_ADDED\"):\n evm_script_factories_registry.addEVMScriptFactory(\n stranger, permissions, {\"from\": owner}\n )\n\n\ndef test_remove_evm_script_factory_not_found(\n owner, stranger, evm_script_factories_registry\n):\n \"Must revert with message 'EVM_SCRIPT_FACTORY_NOT_FOUND'\"\n with reverts(\"EVM_SCRIPT_FACTORY_NOT_FOUND\"):\n evm_script_factories_registry.removeEVMScriptFactory(stranger, {\"from\": owner})\n\n\ndef test_remove_evm_script_factory(\n owner, stranger, evm_script_factories_registry, extra_evm_script_factories\n):\n \"Must remove EVMScript factory from the list of allowed EVMScript factories\"\n \"and emit EVMScriptFactoryRemoved(_evmScriptFactory) event\"\n # add many evm script factories\n permissions = stranger.address + \"ffccddee\"\n for evm_script_factory in extra_evm_script_factories:\n evm_script_factories_registry.addEVMScriptFactory(\n evm_script_factory, permissions, {\"from\": owner}\n )\n\n # make a copy to avoid modifying the fixture object when popping\n evm_script_factories = extra_evm_script_factories.copy()\n\n # sets the order in which evm script factories will be removed\n # 1. remove factory at index=3: [0, 1, 2, (3), 4] -> [0, 1, 2, 4]\n # 2. remove factory at index=1: [0, (1), 2, 4] -> [0, 4, 2]\n # 3. remove factory at index=0: [(0), 4, 2] -> [2, 4]\n # 4. remove factory at index=1: [2, (4)]-> [2]\n # 5. remove factory at index=0: [(2)] -> []\n removing_order = [3, 1, 0, 1, 0]\n\n # remove evm scripts in predefined order and check\n # that was deleted correct evm script factory\n for index in removing_order:\n evm_script_factory_to_remove = evm_script_factories.pop(index)\n\n assert evm_script_factories_registry.isEVMScriptFactory(\n evm_script_factory_to_remove\n )\n tx = evm_script_factories_registry.removeEVMScriptFactory(\n evm_script_factory_to_remove, {\"from\": owner}\n )\n assert not evm_script_factories_registry.isEVMScriptFactory(\n evm_script_factory_to_remove\n )\n\n # validate events\n assert len(tx.events) == 1\n assert (\n tx.events[\"EVMScriptFactoryRemoved\"][\"_evmScriptFactory\"]\n == evm_script_factory_to_remove\n )\n\n # validate that was deleted correct address by join\n # test set with resulting set their size must be same\n evm_script_factories_after_remove = (\n evm_script_factories_registry.getEVMScriptFactories()\n )\n assert len(evm_script_factories) == len(evm_script_factories_after_remove)\n\n len(set(evm_script_factories).union(evm_script_factories_after_remove)) == len(\n evm_script_factories\n )\n","repo_name":"lidofinance/easy-track","sub_path":"tests/test_evm_script_factories_registry.py","file_name":"test_evm_script_factories_registry.py","file_ext":"py","file_size_in_byte":5272,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"40"} +{"seq_id":"45076855560","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\n#Import other modules\nimport traceback\nimport wx\nimport wx.html\nimport wx.lib.statbmp\nimport wx.lib.stattext\nimport threading\nimport subprocess\nimport sys\nimport getopt\nimport logging\nimport os\nimport shutil\nimport time\nimport plistlib\nfrom wx.animate import AnimationCtrl\nfrom wx.animate import Animation\nfrom bs4 import BeautifulSoup\n\n#Define the version number and the release date as global variables.\nVersion = \"2.0.2\"\nReleaseDate = \"25/10/2017\"\nSessionEnding = False\n\ndef usage():\n print(\"\\nUsage: WxFixBoot.py [OPTION]\\n\")\n print(\" -h, --help: Show this help message\")\n print(\" -q, --quiet: Show only warning, error and critical messages in the log file. Very unhelpful for debugging, and not recommended.\")\n print(\" -v, --verbose: Enable logging of info messages, as well as warnings, errors and critical errors.\")\n print(\" Not the best for debugging, but acceptable if there is little disk space.\")\n print(\" -d, --debug: Log lots of boring debug messages, as well as information, warnings, errors and critical errors. Usually used for diagnostic purposes.\")\n print(\" The default, as it's very helpful if problems are encountered, and the user needs help\\n\")\n print(\"WxFixBoot \"+Version+\" is released under the GNU GPL Version 3\")\n print(\"Copyright (C) Hamish McIntyre-Bhatty 2013-2017\")\n\n#If this isn't running as root, relaunch.\nif not os.geteuid() == 0:\n subprocess.Popen([\"/usr/share/wxfixboot/AuthenticationDialog.py\"])\n sys.exit(\"\\nSorry, WxFixBoot must be run with root privileges.\\nRestarting as Root...\")\n\n#Set up according to cmdline options.\ntry:\n opts, args = getopt.getopt(sys.argv[1:], \"hqvd\", (\"help\", \"quiet\", \"verbose\", \"debug\"))\n\nexcept getopt.GetoptError as err:\n #Invalid option. Show the help message and then exit.\n #Show the error.\n print(unicode(err))\n usage()\n sys.exit(2)\n\n#Set up logging.\nlogger = logging.getLogger('WxFixBoot '+Version)\nlogging.basicConfig(filename='/tmp/wxfixboot.log', format='%(asctime)s - %(name)s - %(levelname)s: %(message)s', datefmt='%d/%m/%Y %I:%M:%S %p')\nlogger.setLevel(logging.DEBUG)\n\n#Set restarting to false.\nRestarting = False\n\n#Determine the option(s) given, and change the level of logging based on cmdline options.\nfor o, a in opts:\n if o in (\"-q\", \"--quiet\"):\n logger.setLevel(logging.WARNING)\n\n elif o in (\"-v\", \"--verbose\"):\n logger.setLevel(logging.INFO)\n\n elif o in (\"-d\", \"--debug\"):\n logger.setLevel(logging.DEBUG)\n\n elif o in (\"-h\", \"--help\"):\n usage()\n sys.exit()\n\n else:\n assert False, \"unhandled option\"\n\n#Import custom-made modules\nimport GetDevInfo\nimport Tools\n\nfrom GetDevInfo.getdevinfo import Main as DevInfoToolsCallable\n\nfrom Tools.coretools import Main as CoreToolsCallable\n\nfrom Tools.dialogtools import Main as DialogToolsCallable\n\nfrom Tools.StartupTools.core import Main as CoreStartupToolsCallable\nfrom Tools.StartupTools.main import Main as MainStartupToolsCallable\nfrom Tools.StartupTools.getbootloaderconfigtools import Main as BootloaderConfigObtainingToolsCallable\nfrom Tools.BackendTools.helpers import Main as HelperBackendToolsCallable\nfrom Tools.BackendTools.essentials import Main as EssentialBackendToolsCallable\nfrom Tools.BackendTools.main import Main as MainBackendToolsCallable\n\nfrom Tools.BackendTools.BootloaderTools.setconfigtools import Main as BootloaderConfigSettingToolsCallable\n\nimport SystemInfoNoteBookSharedFunctions as NoteBookSharedFunctions\n\n#Access these modules without the \"()\" so conditional tests can work.\nDevInfoTools = DevInfoToolsCallable()\n\nCoreTools = CoreToolsCallable()\n\nDialogTools = DialogToolsCallable()\n\nCoreStartupTools = CoreStartupToolsCallable()\nMainStartupTools = MainStartupToolsCallable()\n\nHelperBackendTools = HelperBackendToolsCallable()\nEssentialBackendTools = EssentialBackendToolsCallable()\nMainBackendTools = MainBackendToolsCallable()\n\nBootloaderConfigObtainingTools = BootloaderConfigObtainingToolsCallable()\nBootloaderConfigSettingTools = BootloaderConfigSettingToolsCallable()\n\n#Setup custom-made modules (make global variables accessible inside the packages).\n#GetDevInfo Package.\nGetDevInfo.getdevinfo.subprocess = subprocess\nGetDevInfo.getdevinfo.os = os\nGetDevInfo.getdevinfo.logger = logger\nGetDevInfo.getdevinfo.BeautifulSoup = BeautifulSoup\n\n#CoreTools Module.\nTools.coretools.wx = wx\nTools.coretools.subprocess = subprocess\nTools.coretools.sys = sys\nTools.coretools.logger = logger\nTools.coretools.logging = logging\nTools.coretools.os = os\nTools.coretools.DialogTools = DialogTools\n\n#DialogTools Module.\nTools.dialogtools.wx = wx\nTools.dialogtools.logger = logger\nTools.dialogtools.time = time\n\n#StartupTools Package (Core).\nTools.StartupTools.core.logger = logger\nTools.StartupTools.core.os = os\nTools.StartupTools.core.CoreTools = CoreTools\nTools.StartupTools.core.DialogTools = DialogTools\n\n#StartupTools Package (Main).\nTools.StartupTools.main.logger = logger\nTools.StartupTools.main.os = os\nTools.StartupTools.main.CoreTools = CoreTools\nTools.StartupTools.main.CoreStartupTools = CoreStartupTools\nTools.StartupTools.main.BootloaderConfigObtainingTools = BootloaderConfigObtainingTools\nTools.StartupTools.main.DialogTools = DialogTools\n\n#StartupTools Package (BootloaderConfigObtainingTools).\nTools.StartupTools.getbootloaderconfigtools.CoreTools = CoreTools\nTools.StartupTools.getbootloaderconfigtools.os = os\n\n#BackendTools Package (Helpers)\nTools.BackendTools.helpers.logger = logger\nTools.BackendTools.helpers.os = os\nTools.BackendTools.helpers.time = time\nTools.BackendTools.helpers.CoreTools = CoreTools\nTools.BackendTools.helpers.DialogTools = DialogTools\nTools.BackendTools.helpers.MainBackendTools = MainBackendTools\n\n#BackendTools Package (Essentials)\nTools.BackendTools.essentials.wx = wx\nTools.BackendTools.essentials.logger = logger\nTools.BackendTools.essentials.CoreTools = CoreTools\nTools.BackendTools.essentials.HelperBackendTools = HelperBackendTools\nTools.BackendTools.essentials.DialogTools = DialogTools\n\n#BackendTools Package (Main).\nTools.BackendTools.main.wx = wx\nTools.BackendTools.main.logger = logger\nTools.BackendTools.main.os = os\nTools.BackendTools.main.time = time\nTools.BackendTools.main.CoreTools = CoreTools\nTools.BackendTools.main.EssentialBackendTools = EssentialBackendTools\nTools.BackendTools.main.HelperBackendTools = HelperBackendTools\nTools.BackendTools.main.BootloaderConfigObtainingTools = BootloaderConfigObtainingTools\nTools.BackendTools.main.BootloaderConfigSettingTools = BootloaderConfigSettingTools\nTools.BackendTools.main.DialogTools = DialogTools\n\n#StartupTools Package (GetConfigTools)\nTools.StartupTools.getbootloaderconfigtools.logger = logger\n\n#BootloaderTools Package (SetConfigTools)\nTools.BackendTools.BootloaderTools.setconfigtools.logger = logger\nTools.BackendTools.BootloaderTools.setconfigtools.os = os\nTools.BackendTools.BootloaderTools.setconfigtools.CoreTools = CoreTools\nTools.BackendTools.BootloaderTools.setconfigtools.DialogTools = DialogTools\nTools.BackendTools.BootloaderTools.setconfigtools.HelperBackendTools = HelperBackendTools\n\n#NoteBookSharedFunctions module.\nNoteBookSharedFunctions.wx = wx\nNoteBookSharedFunctions.logger = logger\n\n#Begin Disk Information Handler thread.\nclass GetDiskInformation(threading.Thread):\n def __init__(self, ParentWindow):\n \"\"\"Initialize and start the thread.\"\"\"\n self.ParentWindow = ParentWindow\n threading.Thread.__init__(self)\n self.start()\n\n def run(self):\n \"\"\"Get Disk Information and return it as a list with embedded lists\"\"\"\n #Use a module I've written to collect data about connected Disks, and return it.\n wx.CallAfter(self.ParentWindow.ReceiveDiskInfo, DevInfoTools.GetInfo())\n\n#End Disk Information Handler thread.\n#Begin Starter Class\nclass WxFixBoot(wx.App):\n def OnInit(self):\n \"\"\"Starts InitialWindow()\"\"\"\n InitialWindow().Show()\n return True\n\n#End Starter Class\n#Begin Initialization Panel.\nclass InitialPanel(wx.Panel):\n def __init__(self, parent):\n \"\"\"Initialises the panel\"\"\"\n wx.Panel.__init__(self, parent=parent)\n self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)\n self.frame = parent\n self.Bind(wx.EVT_PAINT, self.OnEraseBackground)\n\n def OnEraseBackground(self, Event):\n \"\"\"Redraw the background image when needed\"\"\"\n DC = wx.ClientDC(self)\n Rectangle = self.GetUpdateRegion().GetBox()\n DC.SetClippingRect(Rectangle)\n\n DC.Clear()\n Splash = wx.Bitmap(\"/usr/share/wxfixboot/images/splash.jpg\")\n DC.DrawBitmap(Splash, 0, 0)\n\n#End Initialization Panel.\n#Begin Initialization Frame.\nclass InitialWindow(wx.Frame):\n def __init__(self):\n \"\"\"Initialises InitialWindow\"\"\"\n wx.Frame.__init__(self, parent=None, title=\"WxFixBoot\", size=(600,420), style=wx.SIMPLE_BORDER)\n self.Panel = InitialPanel(self)\n self.SetClientSize(wx.Size(600,420))\n\n if Restarting == False:\n print(\"WxFixBoot Version \"+Version+\" Starting...\")\n logger.info(\"WxFixBoot Version \"+Version+\" Starting...\")\n\n else:\n print(\"WxFixBoot Version \"+Version+\" Restarting...\")\n logger.info(\"WxFixBoot Version \"+Version+\" Restarting...\")\n\n logger.info(\"Release date: \"+ReleaseDate)\n logger.info(\"Running on Python version: \"+unicode(sys.version_info)+\"...\")\n logger.info(\"Running on wxPython version: \"+wx.version()+\"...\")\n\n #Set the frame's icon.\n global AppIcon\n AppIcon = wx.Icon(\"/usr/share/wxfixboot/images/Logo.png\", wx.BITMAP_TYPE_PNG)\n wx.Frame.SetIcon(self, AppIcon)\n\n #Create the progress bar and text.\n self.CreateProgressBarAndText()\n\n #Setup sizers.\n self.SetupSizers()\n\n #Start the Initalization Thread, which performs all necessary startup scripts and checks, and let it know this is the first start.\n logger.debug(\"Starting InitThread()...\")\n\n ProgressTextHandlerThread(self)\n InitThread(self)\n\n def CreateProgressBarAndText(self):\n \"\"\"Create a progressbar and some progress text\"\"\"\n self.ProgressBar = wx.Gauge(self.Panel, -1, 100)\n self.ProgressBar.SetBezelFace(3)\n self.ProgressBar.SetShadowWidth(3)\n self.ProgressBar.SetValue(0)\n self.ProgressBar.Show()\n\n #Create the progress text.\n self.ProgressText = wx.StaticText(self.Panel, -1, \"Initialising...\")\n\n def SetupSizers(self):\n \"\"\"Setup sizers for InitialWindow\"\"\"\n MainSizer = wx.BoxSizer(wx.VERTICAL)\n MainSizer.Add((50,50), 10, wx.EXPAND)\n MainSizer.Add(self.ProgressText, 1, wx.CENTER|wx.BOTTOM|wx.LEFT|wx.RIGHT, 10)\n MainSizer.Add(self.ProgressBar, 1, wx.BOTTOM|wx.LEFT|wx.RIGHT|wx.EXPAND, 10)\n\n #Get the sizer set up for the frame.\n self.Panel.SetSizer(MainSizer)\n MainSizer.SetMinSize(wx.Size(600,420))\n MainSizer.SetSizeHints(self)\n\n def UpdateProgressBar(self, Value):\n \"\"\"Update the progress bar with the given value\"\"\"\n self.ProgressBar.SetValue(int(Value))\n\n if int(Value) == 100:\n global StopProgressTextHandlerThread\n StopProgressTextHandlerThread = True\n self.FinishedInit()\n\n def UpdateProgressText(self, Message):\n \"\"\"Call the text handler thread to distract the user\"\"\"\n self.ProgressText.SetLabel(Message)\n self.Panel.Layout()\n\n def SetProgressText(self, Message):\n \"\"\"Update the progress text with the given string\"\"\"\n self.ProgressText.SetLabel(Message)\n self.Panel.Layout()\n\n def FinishedInit(self, Event=None):\n \"\"\"Starts MainWindow, called when StartupScripts are finished\"\"\"\n logger.info(\"Closing Initial Window and Starting Main Window...\")\n\n #Show the user some important information\n dlg = wx.MessageDialog(self.Panel, \"Please make sure you have a working internet connection before performing any bootloader operations. Thank you.\", \"WxFixBoot - Information\", style=wx.OK | wx.ICON_INFORMATION, pos=wx.DefaultPosition)\n dlg.ShowModal()\n dlg.Destroy()\n\n MainGUI = MainWindow()\n app.SetTopWindow(MainGUI)\n self.Destroy()\n\n #Start MainFrame.\n MainGUI.Show(True) \n\n#End Initialization Frame.\n#Begin Progress Text Handler Thread.\nclass ProgressTextHandlerThread(threading.Thread):\n def __init__(self, ParentWindow):\n \"\"\"Start the Thread\"\"\"\n threading.Thread.__init__(self)\n self.ParentWindow = ParentWindow\n\n global StopProgressTextHandlerThread\n StopProgressTextHandlerThread = False\n\n self.start()\n\n def run(self):\n \"\"\"Distract the user with some text effects on the Initial Window.\n For 10 seconds of the same message, make dots build up to 3 dots and back in front of the text.\n After 10 seconds of same message, state that WxFixBoot is still starting up, and to be patient.\"\"\"\n\n HalfSecondCounter = 0\n Continue = False\n Message = \"\"\n\n while True:\n if StopProgressTextHandlerThread:\n break\n\n if HalfSecondCounter == 20:\n Message = Message.replace(\".\", \"\")+\". This may take a few minutes. Please be patient.\"\n wx.CallAfter(self.ParentWindow.SetProgressText, Message)\n time.sleep(0.5)\n HalfSecondCounter += 1\n\n else:\n LastMessage = Message\n\n Message = self.ParentWindow.ProgressText.GetLabel()\n\n if Message == LastMessage:\n HalfSecondCounter += 1\n\n else:\n HalfSecondCounter == 0\n\n if Message[-3:] == \"...\":\n Message = Message[0:-3]\n\n Message = Message+\".\"\n wx.CallAfter(self.ParentWindow.SetProgressText, Message)\n time.sleep(0.5)\n\n#End Progress Text Handler Thread.\n#Begin Initialization Thread.\nclass InitThread(threading.Thread):\n def __init__(self, ParentWindow):\n \"\"\"Start the thread.\"\"\"\n #Initialize the thread.\n threading.Thread.__init__(self)\n self.ParentWindow = ParentWindow\n\n #Set up dialog tools and core tools.\n Tools.dialogtools.ParentWindow = ParentWindow\n Tools.coretools.ParentWindow = ParentWindow\n\n #Start the thread.\n self.start()\n\n def run(self):\n \"\"\"Handle errors in the main thread code\"\"\"\n logger.debug(\"InitThread(): Starting...\")\n\n #Handle any unexpected errors.\n try:\n self.MainCode()\n\n except:\n logger.critical(\"Unexpected error \\n\\n\"+unicode(traceback.format_exc())+\"\\n\\n while starting WxFixBoot. Warning user and exiting.\")\n CoreTools.EmergencyExit(\"There was an unexpected error:\\n\\n\"+unicode(traceback.format_exc())+\"\\n\\nWhile starting up!\")\n\n def MainCode(self):\n \"\"\"Create the temporary mount point folder and set some default settings.\"\"\"\n #Define dictionaries.\n global SystemInfo\n global DiskInfo\n global OSInfo\n global BootloaderInfo\n global Settings\n\n SystemInfo = {}\n DiskInfo = {}\n OSInfo = {}\n BootloaderInfo = {}\n Settings = {}\n\n #Make dictionaries available to modules.\n Tools.coretools.DiskInfo = DiskInfo\n Tools.StartupTools.core.DiskInfo = DiskInfo\n Tools.StartupTools.core.OSInfo = OSInfo\n Tools.StartupTools.core.BootloaderInfo = BootloaderInfo\n Tools.StartupTools.core.SystemInfo = SystemInfo\n Tools.StartupTools.core.Settings = Settings\n Tools.StartupTools.main.DiskInfo = DiskInfo\n Tools.StartupTools.main.BootloaderInfo = BootloaderInfo\n Tools.StartupTools.main.SystemInfo = SystemInfo\n Tools.StartupTools.main.Settings = Settings\n Tools.StartupTools.getbootloaderconfigtools.DiskInfo = DiskInfo\n Tools.StartupTools.getbootloaderconfigtools.BootloaderInfo = BootloaderInfo\n GetDevInfo.getdevinfo.DiskInfo = DiskInfo\n\n #Let CoreTools know we're starting up.\n Tools.coretools.Startup = True\n\n #Set variables used for checking whether bootloader operations have been disabled.\n SystemInfo[\"DisableBootloaderOperations\"] = False\n SystemInfo[\"DisableBootloaderOperationsBecause\"] = []\n\n #Initialise a variable for later.\n SystemInfo[\"PreviousOSChoice\"] = \"\"\n\n #Set initial settings for MainWindow.\n Settings[\"QuickFSCheck\"] = False\n Settings[\"BadSectorCheck\"] = False\n Settings[\"FullVerbosity\"] = False\n Settings[\"MakeSystemSummary\"] = True\n Settings[\"SaveOutput\"] = True\n\n #Remove the temporary directory if it exists.\n if os.path.isdir(\"/tmp/wxfixboot/mountpoints\"):\n #Check nothing is using it.\n if \"/tmp/wxfixboot/mountpoints\" in CoreTools.StartProcess(\"mount\", ReturnOutput=True)[1]:\n CoreTools.EmergencyExit(\"There are mounted filesystems in /tmp/wxfixboot/mountpoints, WxFixBoot's temporary mountpoints directory! Please unmount any filesystems there and try again.\")\n\n shutil.rmtree(\"/tmp/wxfixboot/mountpoints\")\n\n os.makedirs(\"/tmp/wxfixboot/mountpoints\")\n\n #Check for dependencies\n logger.info(\"InitThread(): Checking For Dependencies...\")\n wx.CallAfter(self.ParentWindow.UpdateProgressText, \"Checking For Dependencies...\")\n MainStartupTools.CheckDepends()\n wx.CallAfter(self.ParentWindow.UpdateProgressBar, \"2\")\n logger.info(\"InitThread(): Done Checking For Dependencies!\")\n\n #Check if we're on a Live Disk.\n logger.info(\"InitThread(): Checking For Live Disk...\")\n wx.CallAfter(self.ParentWindow.UpdateProgressText, \"Checking For Live Disk...\")\n MainStartupTools.CheckForLiveDisk()\n wx.CallAfter(self.ParentWindow.UpdateProgressBar, \"4\")\n logger.info(\"InitThread(): Done Checking For Live Disk!\")\n\n #Unmount all filesystems, to avoid any data corruption.\n logger.info(\"InitThread(): Unmounting Filesystems...\")\n wx.CallAfter(self.ParentWindow.UpdateProgressText, \"Unmounting Filesystems...\")\n MainStartupTools.UnmountAllFS()\n wx.CallAfter(self.ParentWindow.UpdateProgressBar, \"5\")\n logger.info(\"InitThread(): Done Unmounting Filsystems!\")\n\n #Check filesystems.\n logger.info(\"InitThread(): Checking Filesystems...\")\n wx.CallAfter(self.ParentWindow.UpdateProgressText, \"Checking Filesystems...\")\n MainStartupTools.CheckFS()\n wx.CallAfter(self.ParentWindow.UpdateProgressBar, \"15\")\n logger.info(\"InitThread(): Filesystems Checked!\")\n\n #Get device info.\n logger.info(\"InitThread(): Getting Device Information...\")\n wx.CallAfter(self.ParentWindow.UpdateProgressText, \"Getting Device Information...\")\n DevInfoTools.GetInfo()\n wx.CallAfter(self.ParentWindow.UpdateProgressBar, \"60\")\n logger.info(\"InitThread(): Finished Getting Device Information...\")\n\n #Mount all filesystems.\n logger.info(\"InitThread(): Mounting Core Filesystems...\")\n wx.CallAfter(self.ParentWindow.UpdateProgressText, \"Mounting Core Filesystems...\")\n MainStartupTools.MountCoreFS()\n wx.CallAfter(self.ParentWindow.UpdateProgressBar, \"63\")\n logger.info(\"InitThread(): Done Mounting Core Filsystems!\")\n\n #Get a list of OSs.\n logger.info(\"InitThread(): Finding OSs...\")\n wx.CallAfter(self.ParentWindow.UpdateProgressText, \"Finding Operating Systems...\")\n OSInfo, SystemInfo = MainStartupTools.GetOSs()\n\n Tools.StartupTools.main.OSInfo = OSInfo\n Tools.StartupTools.core.OSInfo = OSInfo\n\n wx.CallAfter(self.ParentWindow.UpdateProgressBar, \"65\")\n logger.info(\"InitThread(): Done Finding OSs...\")\n\n #Get the firmware type.\n logger.info(\"InitThread(): Determining Firmware Type...\")\n wx.CallAfter(self.ParentWindow.UpdateProgressText, \"Determining Firmware Type...\")\n MainStartupTools.GetFirmwareType()\n wx.CallAfter(self.ParentWindow.UpdateProgressBar, \"70\")\n logger.info(\"InitThread(): Determined Firmware Type as: \"+SystemInfo[\"FirmwareType\"])\n\n #New bootloader info getting function.\n logger.info(\"InitThread(): Finding all Bootloaders and getting their settings...\")\n wx.CallAfter(self.ParentWindow.UpdateProgressText, \"Finding Bootloaders...\")\n MainStartupTools.GetBootloaders()\n wx.CallAfter(self.ParentWindow.UpdateProgressBar, \"80\")\n logger.info(\"InitThread(): Done!\")\n\n #Check if any modifyable Linux installations were found.\n if len(SystemInfo[\"ModifyableOSs\"]) == 0:\n logger.critical(\"InitThread(): No modifyable Linux installations found! If you think this is incorrect, please file a bug or ask a question on WxFixBoot's launchpad page. Exiting...\")\n\n #Exit.\n CoreTools.EmergencyExit(\"You don't appear to have any modifyable Linux installations on your hard disks. If you think this is incorrect, please file a bug or ask a question on WxFixBoot's launchpad page.\")\n\n #Perform final check.\n logger.info(\"InitThread(): Doing Final Check for error situations...\")\n wx.CallAfter(self.ParentWindow.UpdateProgressText, \"Checking Everything...\")\n MainStartupTools.FinalCheck()\n wx.CallAfter(self.ParentWindow.UpdateProgressBar, \"100\")\n logger.info(\"InitThread(): Done Final Check!\")\n\n #Let CoreTools know we're finished starting up.\n Tools.coretools.Startup = False\n\n wx.CallAfter(self.ParentWindow.UpdateProgressText, \"Finished! Starting GUI...\")\n logger.info(\"InitThread(): Finished Determining Settings. Exiting InitThread()...\")\n\n#End Initalization Thread.\n#Begin Main Window\nclass MainWindow(wx.Frame):\n def __init__(self):\n \"\"\"Initialise MainWindow\"\"\"\n wx.Frame.__init__(self,None,title=\"WxFixBoot\", size=(400,300),style=wx.DEFAULT_FRAME_STYLE)\n self.Panel = wx.Panel(self)\n self.SetClientSize(wx.Size(400,300))\n\n #Set the frame's icon.\n wx.Frame.SetIcon(self, AppIcon)\n\n #Create a Statusbar in the bottom of the window and set the text.\n self.MakeStatusBar()\n\n #Add text.\n self.CreateText()\n\n #Create some buttons\n self.CreateButtons()\n\n #Create some checkboxes\n self.CreateCBs()\n\n #Create the menus.\n self.CreateMenus()\n\n #Set up checkboxes\n self.RefreshMainWindow()\n\n #Setup Sizers.\n self.SetupSizers()\n\n #Bind all events.\n self.BindEvents()\n\n logger.debug(\"MainWindow().__init__(): Started. Waiting for events...\")\n\n def MakeStatusBar(self):\n \"\"\"Create the status bar\"\"\"\n self.statusbar = self.CreateStatusBar()\n self.StatusBar.SetFieldsCount(2)\n self.StatusBar.SetStatusWidths([-1, 150])\n self.StatusBar.SetStatusText(\"Ready.\", 0)\n self.StatusBar.SetStatusText(\"v\"+Version+\" (\"+ReleaseDate+\")\", 1)\n\n def CreateText(self):\n \"\"\"Create the text\"\"\"\n self.SettingsText = wx.StaticText(self.Panel, -1, \"Please set the basic settings here first.\")\n self.WelcomeText = wx.StaticText(self.Panel, -1, \"Welcome to WxFixBoot!\")\n\n #Add an image.\n img = wx.Image(\"/usr/share/pixmaps/wxfixboot.png\", wx.BITMAP_TYPE_PNG)\n self.Logo = wx.StaticBitmap(self.Panel, -1, wx.BitmapFromImage(img))\n\n def CreateButtons(self):\n \"\"\"Create the buttons\"\"\"\n self.AboutButton = wx.Button(self.Panel, wx.ID_ANY, \"About\")\n self.ExitButton = wx.Button(self.Panel, wx.ID_ANY, \"Quit\")\n self.BootloaderOptionsButton = wx.Button(self.Panel, -1, \"Bootloader Options\")\n self.ApplyOperationsButton = wx.Button(self.Panel, wx.ID_ANY, \"Apply All Operations\")\n\n def CreateCBs(self):\n \"\"\"Create the checkboxes\"\"\"\n self.BadSectorCheckCB = wx.CheckBox(self.Panel, -1, \"Check All File Systems (thorough)\")\n self.CheckFileSystemsCB = wx.CheckBox(self.Panel, -1, \"Check All File Systems (quick)\")\n self.FullVerboseCheckBox = wx.CheckBox(self.Panel, -1, \"Show diagnostic terminal output\")\n self.MakeSummaryCheckBox = wx.CheckBox(self.Panel, -1, \"Save System Report To File\")\n self.LogOutputCheckBox = wx.CheckBox(self.Panel, -1, \"Save terminal output in Report\")\n\n def CreateMenus(self):\n \"\"\"Create the menus\"\"\"\n filemenu = wx.Menu()\n viewmenu = wx.Menu()\n editmenu = wx.Menu()\n helpmenu = wx.Menu() \n \n #Adding Menu Items.\n self.menuAbout = helpmenu.Append(wx.ID_ABOUT, \"&About\", \"Information about this program\")\n self.menuExit = filemenu.Append(wx.ID_EXIT,\"&Exit\", \"Terminate this program\")\n self.menuSystemInfo = viewmenu.Append(wx.ID_ANY,\"&System Information\", \"Information about all detected disks, OSs, and Bootloaders\")\n self.menuPrivacyPolicy = viewmenu.Append(wx.ID_ANY,\"&Privacy Policy\", \"View WxFixBoot's privacy policy\")\n self.menuBootloaderOpts = editmenu.Append(wx.ID_PREFERENCES, \"&Bootloader Options\", \"All Bootloader Options used to modify/fix your system\")\n\n #Creating the menubar.\n menuBar = wx.MenuBar()\n\n #Adding menus to the MenuBar\n menuBar.Append(filemenu,\"&File\")\n menuBar.Append(editmenu,\"&Edit\")\n menuBar.Append(viewmenu,\"&View\")\n menuBar.Append(helpmenu,\"&Help\")\n\n #Adding the MenuBar to the Frame content.\n self.SetMenuBar(menuBar)\n\n def OnCheckBox(self, Event=None):\n \"\"\"Called when one of the checkboxes is checked/unchecked to make sure the options stay valid\"\"\"\n logger.debug(\"MainWindow().OnCheckBox(): Checkboxes have been changed. Making sure options are valid and don't conflict...\")\n #Bad Sector Check Choicebox\n if self.BadSectorCheckCB.IsChecked():\n self.CheckFileSystemsCB.Disable()\n\n else:\n self.CheckFileSystemsCB.Enable()\n\n #Quick Disk Check Choicebox\n if self.CheckFileSystemsCB.IsChecked():\n self.BadSectorCheckCB.Disable()\n\n else:\n self.BadSectorCheckCB.Enable()\n\n #Log output, and Make Summary checkboxes.\n if self.MakeSummaryCheckBox.IsChecked():\n self.LogOutputCheckBox.Enable()\n self.LogOutputCheckBox.SetValue(True)\n\n else:\n self.LogOutputCheckBox.SetValue(False)\n self.LogOutputCheckBox.Disable()\n\n logger.debug(\"MainWindow().OnCheckBox(): Done. Calling self.SaveMainOpts()...\")\n self.SaveMainOpts()\n\n def BootloaderOptions(self, Event=None):\n \"\"\"Show the Bootloader Options Window\"\"\"\n #Safeguard program reliability (and continuity) by saving the settings first.\n logger.debug(\"MainWindow().BootloaderOptions(): Calling self.SaveMainOpts()...\")\n self.SaveMainOpts()\n\n #Open the Bootloader Options window\n logger.debug(\"MainWindow().BootloaderOptions(): Starting Bootloader Settings Window...\")\n self.Hide()\n BootloaderOptionsWindow(self).Show()\n\n def SystemInfo(self, Event=None):\n \"\"\"Start SystemInfoWindow\"\"\"\n logger.debug(\"MainWindow().SystemInfo(): Starting System Info Window...\")\n SystemInfoWindow(self).Show()\n\n def ShowPrivacyPolicy(self, Event=None):\n \"\"\"Show PrivPolWindow\"\"\"\n PrivPolWindow(self).Show()\n\n def ProgressWindow(self, Event=None):\n \"\"\"Starts Progress Window\"\"\"\n logger.debug(\"MainWindow().ProgressWindow(): Starting Progress Window...\")\n self.SaveMainOpts()\n ProgressFrame = ProgressWindow()\n app.SetTopWindow(ProgressFrame)\n ProgressFrame.Show(True)\n self.Destroy()\n\n def RefreshMainWindow(self, msg=\"\"):\n \"\"\"Refresh the main window to reflect changes in the options, or after a restart.\"\"\"\n logger.debug(\"MainWindow().RefreshMainWindow(): Refreshing MainWindow...\")\n\n self.CheckFileSystemsCB.SetValue(Settings[\"QuickFSCheck\"])\n self.BadSectorCheckCB.SetValue(Settings[\"BadSectorCheck\"])\n self.FullVerboseCheckBox.SetValue(Settings[\"FullVerbosity\"])\n self.MakeSummaryCheckBox.SetValue(Settings[\"MakeSystemSummary\"])\n self.LogOutputCheckBox.SetValue(Settings[\"SaveOutput\"])\n\n #Enable and Disable Checkboxes as necessary\n self.OnCheckBox()\n\n #Reveal MainWindow\n self.Show()\n\n def OnAbout(self, Event=None):\n \"\"\"Shows the About Box\"\"\"\n logger.debug(\"MainWindow().OnAbout(): Showing About Box...\")\n aboutbox = wx.AboutDialogInfo()\n aboutbox.Name = \"WxFixBoot\"\n aboutbox.SetIcon(AppIcon)\n aboutbox.Version = Version\n aboutbox.Copyright = \"(C) 2013-2017 Hamish McIntyre-Bhatty\"\n aboutbox.Description = \"Utility to fix the bootloader on a\\ncomputer quickly\"\n aboutbox.WebSite = (\"https://launchpad.net/wxfixboot\", \"Launchpad page\")\n aboutbox.Developers = [\"Hamish McIntyre-Bhatty\"]\n aboutbox.Artists = [\"Holly McIntyre-Bhatty (Logo and Splash Screen)\"]\n aboutbox.License = \"WxFixBoot is free software: you can redistribute it and/or modify it\\nunder the terms of the GNU General Public License version 3 or,\\nat your option, any later version.\\n\\nWxFixBoot is distributed in the hope that it will be useful,\\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\\nGNU General Public License for more details.\\n\\nYou should have received a copy of the GNU General Public License\\nalong with WxFixBoot. If not, see <http://www.gnu.org/licenses/>.\"\n\n #Show the AboutBox.\n wx.AboutBox(aboutbox)\n\n def SetupSizers(self):\n \"\"\"Setup sizers for MainWindow\"\"\"\n #Create the main sizer.\n MainSizer = wx.BoxSizer(wx.VERTICAL)\n\n #Create the check box and Logo sizer.\n CheckBoxAndLogoSizer = wx.BoxSizer(wx.HORIZONTAL)\n\n #Create the check box sizer.\n CheckBoxSizer = wx.BoxSizer(wx.VERTICAL)\n\n #Create the bottom button sizer.\n BottomButtonSizer = wx.BoxSizer(wx.HORIZONTAL)\n\n #Add items to the check box sizer.\n CheckBoxSizer.Add(self.BadSectorCheckCB, 1, wx.BOTTOM, 10)\n CheckBoxSizer.Add(self.CheckFileSystemsCB, 1, wx.BOTTOM, 10)\n CheckBoxSizer.Add(self.FullVerboseCheckBox, 1, wx.BOTTOM, 10)\n CheckBoxSizer.Add(self.MakeSummaryCheckBox, 1, wx.BOTTOM, 10)\n CheckBoxSizer.Add(self.LogOutputCheckBox, 1, wx.BOTTOM, 10)\n\n #Add items to the check box and logo sizer.\n CheckBoxAndLogoSizer.Add(CheckBoxSizer, 2, wx.RIGHT, 10)\n CheckBoxAndLogoSizer.Add(self.Logo, 1, wx.TOP|wx.LEFT|wx.ALIGN_RIGHT, 10)\n\n #Add items to the bottom button sizer.\n BottomButtonSizer.Add(self.AboutButton, 1, wx.RIGHT|wx.EXPAND, 10)\n BottomButtonSizer.Add(self.BootloaderOptionsButton, 2, wx.RIGHT|wx.EXPAND, 10)\n BottomButtonSizer.Add(self.ExitButton, 1, wx.EXPAND)\n\n #Add items to the main sizer.\n MainSizer.Add(self.WelcomeText, 10, wx.TOP|wx.BOTTOM|wx.CENTER, 10)\n MainSizer.Add(self.SettingsText, 10, wx.BOTTOM|wx.CENTER, 10)\n MainSizer.Add(CheckBoxAndLogoSizer, 36, wx.BOTTOM|wx.LEFT|wx.RIGHT|wx.EXPAND, 5)\n MainSizer.Add(self.ApplyOperationsButton, 10, wx.BOTTOM|wx.CENTER, 10)\n MainSizer.Add(BottomButtonSizer, 10, wx.BOTTOM|wx.LEFT|wx.RIGHT|wx.EXPAND, 10)\n\n #Get the sizer set up for the frame.\n self.Panel.SetSizer(MainSizer)\n MainSizer.SetMinSize(wx.Size(400,300))\n MainSizer.SetSizeHints(self)\n\n def BindEvents(self): \n \"\"\"Bind all mainwindow events\"\"\"\n self.Bind(wx.EVT_MENU, self.OnAbout, self.menuAbout)\n self.Bind(wx.EVT_MENU, self.OnExit, self.menuExit)\n self.Bind(wx.EVT_CLOSE, self.OnExit)\n self.Bind(wx.EVT_BUTTON, self.OnAbout, self.AboutButton)\n self.Bind(wx.EVT_BUTTON, self.OnExit, self.ExitButton)\n self.Bind(wx.EVT_MENU, self.SystemInfo, self.menuSystemInfo)\n self.Bind(wx.EVT_MENU, self.ShowPrivacyPolicy, self.menuPrivacyPolicy)\n self.Bind(wx.EVT_MENU, self.BootloaderOptions, self.menuBootloaderOpts)\n self.Bind(wx.EVT_BUTTON, self.BootloaderOptions, self.BootloaderOptionsButton)\n self.Bind(wx.EVT_BUTTON, self.ProgressWindow, self.ApplyOperationsButton)\n\n #Checkboxes on the main window.\n self.Bind(wx.EVT_CHECKBOX, self.OnCheckBox, self.CheckFileSystemsCB)\n self.Bind(wx.EVT_CHECKBOX, self.OnCheckBox, self.BadSectorCheckCB)\n self.Bind(wx.EVT_CHECKBOX, self.OnCheckBox, self.MakeSummaryCheckBox)\n\n def SaveMainOpts(self):\n \"\"\"Save all options\"\"\"\n logger.debug(\"MainWindow().SaveMainOpts(): Saving Options on MainWindow...\")\n\n #Bad Sector Check Choicebox\n if self.BadSectorCheckCB.IsChecked():\n self.CheckFileSystemsCB.Disable()\n Settings[\"BadSectorCheck\"] = True\n\n else:\n self.CheckFileSystemsCB.Enable()\n Settings[\"BadSectorCheck\"] = False\n\n #Quick Disk Check Choicebox\n if self.CheckFileSystemsCB.IsChecked():\n self.BadSectorCheckCB.Disable()\n Settings[\"QuickFSCheck\"] = True\n\n else:\n self.BadSectorCheckCB.Enable()\n Settings[\"QuickFSCheck\"] = False\n\n #Diagnostic output checkbox.\n Settings[\"FullVerbosity\"] = self.FullVerboseCheckBox.IsChecked()\n\n #System Summary checkBox\n Settings[\"MakeSystemSummary\"] = self.MakeSummaryCheckBox.IsChecked()\n\n #Save output checkbox.\n Settings[\"SaveOutput\"] = self.LogOutputCheckBox.IsChecked()\n\n logger.debug(\"MainWindow().SaveMainOpts(): MainWindow options saved! Counting operations to do...\")\n self.CountOperations()\n\n def CountOperations(self):\n \"\"\"Count the number of operations to do. Called by self.MainMainOpts()\"\"\"\n global NumberOfOperations\n global Operations\n\n #List to contain operations (and their functions) to run.\n Operations = []\n\n #Run a series of if statements to determine what operations to do, which order to do them in, and the total number to do.\n #Do essential processes first.\n if Settings[\"QuickFSCheck\"]:\n Operations.append((EssentialBackendTools.FileSystemCheck, \"Quick\"))\n logger.info(\"MainWindow().CountOperations(): Added EssentialBackendTools.FileSystemCheck to Operations...\")\n\n if Settings[\"BadSectorCheck\"]:\n Operations.append((EssentialBackendTools.FileSystemCheck, \"Thorough\"))\n logger.info(\"MainWindow().CountOperations(): Added EssentialBackendTools.FileSystemCheck to Operations...\")\n\n #Now do other processes.\n for OS in BootloaderInfo.keys():\n if BootloaderInfo[OS][\"Settings\"][\"ChangeThisOS\"]:\n Operations.append((MainBackendTools.ManageBootloader, OS))\n logger.info(\"MainWindow().CountOperations(): Added (MainBackendTools.ManageBootloader, \"+OS+\") to Operations...\")\n\n NumberOfOperations = len(Operations)\n\n #Log gathered operations to do, and the number (verbose mode, default).\n logger.info(\"MainWindow().CountOperations(): Number of operations: \"+unicode(NumberOfOperations))\n\n if NumberOfOperations == 0:\n logger.info(\"MainWindow().CountOperations(): No operations to do. Disabling self.ApplyOperationsButton...\")\n self.ApplyOperationsButton.SetLabel(\"No Operations Enabled\")\n self.ApplyOperationsButton.Disable()\n\n else:\n logger.info(\"MainWindow().CountOperations(): There are operations to do. Enabling self.ApplyOperationsButton...\")\n self.ApplyOperationsButton.SetLabel(\"Apply All Operations\")\n self.ApplyOperationsButton.Enable()\n\n def OnExit(self, Event=None):\n \"\"\"Shut down.\"\"\"\n logger.info(\"MainWindow().OnExit(): Double-checking the exit attempt with the user...\")\n dlg = wx.MessageDialog(self.Panel, 'Are you sure you want to exit?', 'WxFixBoot - Question!', wx.YES_NO | wx.ICON_QUESTION)\n Answer = dlg.ShowModal()\n dlg.Destroy()\n\n if Answer == wx.ID_YES:\n #Run the exit sequence\n logger.info(\"MainWindow().OnExit(): Exiting...\")\n\n #Shutdown the logger.\n logging.shutdown()\n\n #Prompt user to save the log file.\n dlg = wx.MessageDialog(self.Panel, \"Do you want to keep WxFixBoot's log file? For privacy reasons, WxFixBoot will delete its log file when closing. If you want to save it, which is helpful for debugging if something went wrong, click yes, and otherwise click no.\", \"WxFixBoot - Question\", style=wx.YES_NO | wx.ICON_QUESTION, pos=wx.DefaultPosition)\n Answer = dlg.ShowModal()\n dlg.Destroy()\n\n if Answer == wx.ID_YES:\n #Ask the user where to save it.\n dlg = wx.FileDialog(self.Panel, \"Save log file to...\", defaultDir=\"/home\", wildcard=\"Log Files (*.log)|*.log\" , style=wx.SAVE|wx.OVERWRITE_PROMPT)\n Answer = dlg.ShowModal()\n File = dlg.GetPath()\n dlg.Destroy()\n\n if Answer == wx.ID_OK:\n #Copy it to the specified path, using a one-liner, and don't bother handling any errors, because this is run as root.\n CoreTools.StartProcess(\"cp /tmp/wxfixboot.log \"+File)\n\n dlg = wx.MessageDialog(self.Panel, 'Done! WxFixBoot will now exit.', 'WxFixBoot - Information', wx.OK | wx.ICON_INFORMATION)\n dlg.ShowModal()\n dlg.Destroy()\n\n else:\n dlg = wx.MessageDialog(self.Panel, 'Okay, WxFixBoot will now exit without saving the log file.', 'WxFixBoot - Information', wx.OK | wx.ICON_INFORMATION)\n dlg.ShowModal()\n dlg.Destroy()\n\n else:\n dlg = wx.MessageDialog(self.Panel, 'Okay, WxFixBoot will now exit without saving the log file.', 'WxFixBoot - Information', wx.OK | wx.ICON_INFORMATION)\n dlg.ShowModal()\n dlg.Destroy()\n\n #Delete the log file, and don't bother handling any errors, because this is run as root.\n os.remove('/tmp/wxfixboot.log')\n\n #If we're using wayland, remove the workaround we have to use to make this work.\n #XXX Fix for running on Wayland until we get policy kit stuff done.\n try:\n if os.environ['XDG_SESSION_TYPE'] == \"wayland\":\n subprocess.Popen(\"xhost -si:localuser:root\", shell=True).wait()\n except KeyError: pass\n\n self.Destroy()\n\n#End Main window\n#Begin System Info Page 1.\nclass SystemInfoPage1(wx.Panel):\n def __init__(self, ParentWindow, SystemInfoWindow):\n \"\"\"Initialise SystemInfoPage1\"\"\"\n wx.Panel.__init__(self, ParentWindow)\n self.ParentWindow = ParentWindow\n self.SystemInfoWindow = SystemInfoWindow\n\n logger.debug(\"SystemInfoPage1().__init__(): Creating widgets...\")\n self.Title = \"Here are all the detected disks on your computer\"\n NoteBookSharedFunctions.CreateWidgets(self)\n\n logger.debug(\"SystemInfoPage1().__init__(): Setting up sizers...\")\n NoteBookSharedFunctions.SetupSizers(self)\n\n logger.debug(\"SystemInfoPage1().__init__(): Binding events...\")\n NoteBookSharedFunctions.BindEvents(self)\n\n logger.debug(\"SystemInfoPage1().__init__(): Updating list ctrl with Disk info...\")\n NoteBookSharedFunctions.UpdateListCtrl(self, Headings=[\"Name\", \"Type\", \"Vendor\", \"Product\", \"Capacity\", \"Description\"], Dictionary=DiskInfo)\n\n def OnSize(self, Event=None):\n \"\"\"Auto resize the ListCtrl columns\"\"\"\n Width, Height = self.ListCtrl.GetClientSizeTuple()\n\n self.ListCtrl.SetColumnWidth(0, int(Width * 0.15))\n self.ListCtrl.SetColumnWidth(1, int(Width * 0.1))\n self.ListCtrl.SetColumnWidth(2, int(Width * 0.1))\n self.ListCtrl.SetColumnWidth(3, int(Width * 0.3))\n self.ListCtrl.SetColumnWidth(4, int(Width * 0.15))\n self.ListCtrl.SetColumnWidth(5, int(Width * 0.2))\n\n if Event != None:\n Event.Skip()\n\n#End System Info Page 1\n#Begin System Info Page 2.\nclass SystemInfoPage2(wx.Panel):\n def __init__(self, ParentWindow, SystemInfoWindow):\n \"\"\"Initialise SystemInfoPage2\"\"\"\n wx.Panel.__init__(self, ParentWindow)\n self.ParentWindow = ParentWindow\n self.SystemInfoWindow = SystemInfoWindow\n\n logger.debug(\"SystemInfoPage2().__init__(): Creating widgets...\")\n self.Title = \"Here are all the detected disks on your computer\"\n NoteBookSharedFunctions.CreateWidgets(self)\n\n logger.debug(\"SystemInfoPage2().__init__(): Setting up sizers...\")\n NoteBookSharedFunctions.SetupSizers(self)\n\n logger.debug(\"SystemInfoPage2().__init__(): Binding events...\")\n NoteBookSharedFunctions.BindEvents(self)\n\n logger.debug(\"SystemInfoPage2().__init__(): Updating list ctrl with Disk info...\")\n NoteBookSharedFunctions.UpdateListCtrl(self, Headings=[\"Name\", \"Type\", \"Partitions\", \"Flags\", \"Partitioning\", \"FileSystem\"], Dictionary=DiskInfo)\n\n def OnSize(self, Event=None):\n \"\"\"Auto resize the ListCtrl columns\"\"\"\n Width, Height = self.ListCtrl.GetClientSizeTuple()\n\n self.ListCtrl.SetColumnWidth(0, int(Width * 0.15))\n self.ListCtrl.SetColumnWidth(1, int(Width * 0.1))\n self.ListCtrl.SetColumnWidth(2, int(Width * 0.25))\n self.ListCtrl.SetColumnWidth(3, int(Width * 0.3))\n self.ListCtrl.SetColumnWidth(4, int(Width * 0.1))\n self.ListCtrl.SetColumnWidth(5, int(Width * 0.1))\n\n if Event != None:\n Event.Skip()\n\n#End System Info Page 2\n#Begin System Info Page 3.\nclass SystemInfoPage3(wx.Panel):\n def __init__(self, ParentWindow, SystemInfoWindow):\n \"\"\"Initialise SystemInfoPage3\"\"\"\n wx.Panel.__init__(self, ParentWindow)\n self.ParentWindow = ParentWindow\n self.SystemInfoWindow = SystemInfoWindow\n\n logger.debug(\"SystemInfoPage3().__init__(): Creating widgets...\")\n self.Title = \"Here are all the detected disks on your computer\"\n NoteBookSharedFunctions.CreateWidgets(self)\n\n logger.debug(\"SystemInfoPage3().__init__(): Setting up sizers...\")\n NoteBookSharedFunctions.SetupSizers(self)\n\n logger.debug(\"SystemInfoPage3().__init__(): Binding events...\")\n NoteBookSharedFunctions.BindEvents(self)\n\n logger.debug(\"SystemInfoPage3().__init__(): Updating list ctrl with Disk info...\")\n NoteBookSharedFunctions.UpdateListCtrl(self, Headings=[\"Name\", \"Type\", \"ID\", \"UUID\"], Dictionary=DiskInfo)\n\n def OnSize(self, Event=None):\n \"\"\"Auto resize the ListCtrl columns\"\"\"\n Width, Height = self.ListCtrl.GetClientSizeTuple()\n\n self.ListCtrl.SetColumnWidth(0, int(Width * 0.15))\n self.ListCtrl.SetColumnWidth(1, int(Width * 0.15))\n self.ListCtrl.SetColumnWidth(2, int(Width * 0.35))\n self.ListCtrl.SetColumnWidth(3, int(Width * 0.35))\n\n if Event != None:\n Event.Skip()\n\n#End System Info Page 3\n#Begin System Info Page 4.\nclass SystemInfoPage4(wx.Panel):\n def __init__(self, ParentWindow, SystemInfoWindow):\n \"\"\"Initialise SystemInfoPage4\"\"\"\n wx.Panel.__init__(self, ParentWindow)\n self.ParentWindow = ParentWindow\n self.SystemInfoWindow = SystemInfoWindow\n\n logger.debug(\"SystemInfoPage4().__init__(): Creating widgets...\")\n self.Title = \"Here are all the operating systems WxFixBoot detected on your computer\"\n NoteBookSharedFunctions.CreateWidgets(self)\n\n logger.debug(\"SystemInfoPage4().__init__(): Setting up sizers...\")\n NoteBookSharedFunctions.SetupSizers(self)\n\n logger.debug(\"SystemInfoPage4().__init__(): Binding events...\")\n NoteBookSharedFunctions.BindEvents(self)\n\n logger.debug(\"SystemInfoPage4().__init__(): Updating list ctrl with OS Info...\")\n NoteBookSharedFunctions.UpdateListCtrl(self, Headings=[\"Name\", \"IsCurrentOS\", \"Arch\", \"Partition\", \"PackageManager\"], Dictionary=OSInfo)\n\n def OnSize(self, Event=None):\n \"\"\"Auto resize the ListCtrl columns\"\"\"\n Width, Height = self.ListCtrl.GetClientSizeTuple()\n\n self.ListCtrl.SetColumnWidth(0, int(Width * 0.4))\n self.ListCtrl.SetColumnWidth(1, int(Width * 0.1))\n self.ListCtrl.SetColumnWidth(2, int(Width * 0.1))\n self.ListCtrl.SetColumnWidth(3, int(Width * 0.2))\n self.ListCtrl.SetColumnWidth(4, int(Width * 0.2))\n\n if Event != None:\n Event.Skip()\n\n#End System Info Page 4\n#Begin System Info Page 5.\nclass SystemInfoPage5(wx.Panel):\n def __init__(self, ParentWindow, SystemInfoWindow):\n \"\"\"Initialise SystemInfoPage5\"\"\"\n wx.Panel.__init__(self, ParentWindow)\n self.ParentWindow = ParentWindow\n self.SystemInfoWindow = SystemInfoWindow\n\n logger.debug(\"SystemInfoPage5().__init__(): Creating widgets...\")\n self.Title = \"Here are all the bootloaders WxFixBoot detected on your computer\"\n NoteBookSharedFunctions.CreateWidgets(self)\n\n logger.debug(\"SystemInfoPage5().__init__(): Setting up sizers...\")\n NoteBookSharedFunctions.SetupSizers(self)\n\n logger.debug(\"SystemInfoPage5().__init__(): Binding events...\")\n NoteBookSharedFunctions.BindEvents(self)\n\n logger.debug(\"SystemInfoPage5().__init__(): Updating list ctrl with Bootloader Info...\")\n NoteBookSharedFunctions.UpdateListCtrl(self, Headings=[\"OSName\", \"Bootloader\", \"BootDisk\", \"DefaultOS\"], Dictionary=BootloaderInfo)\n\n def OnSize(self, Event=None):\n \"\"\"Auto resize the ListCtrl columns\"\"\"\n Width, Height = self.ListCtrl.GetClientSizeTuple()\n\n self.ListCtrl.SetColumnWidth(0, int(Width * 0.4))\n self.ListCtrl.SetColumnWidth(1, int(Width * 0.1))\n self.ListCtrl.SetColumnWidth(2, int(Width * 0.1))\n self.ListCtrl.SetColumnWidth(3, int(Width * 0.4))\n\n if Event != None:\n Event.Skip()\n\n#End System Info Page 5\n#Begin System Info Page 6.\nclass SystemInfoPage6(wx.Panel):\n def __init__(self, ParentWindow, SystemInfoWindow):\n \"\"\"Initialise SystemInfoPage6\"\"\"\n wx.Panel.__init__(self, ParentWindow)\n self.ParentWindow = ParentWindow\n self.SystemInfoWindow = SystemInfoWindow\n\n logger.debug(\"SystemInfoPage6().__init__(): Creating widgets...\")\n self.Title = \"Here are all the bootloaders WxFixBoot detected on your computer\"\n NoteBookSharedFunctions.CreateWidgets(self)\n\n logger.debug(\"SystemInfoPage6().__init__(): Setting up sizers...\")\n NoteBookSharedFunctions.SetupSizers(self)\n\n logger.debug(\"SystemInfoPage6().__init__(): Binding events...\")\n NoteBookSharedFunctions.BindEvents(self)\n\n logger.debug(\"SystemInfoPage6().__init__(): Updating list ctrl with Bootloader Info...\")\n NoteBookSharedFunctions.UpdateListCtrl(self, Headings=[\"OSName\", \"Timeout\", \"GlobalKernelOptions\", \"IsModifyable\", \"Comments\"], Dictionary=BootloaderInfo)\n\n def OnSize(self, Event=None):\n \"\"\"Auto resize the ListCtrl columns\"\"\"\n Width, Height = self.ListCtrl.GetClientSizeTuple()\n\n self.ListCtrl.SetColumnWidth(0, int(Width * 0.4))\n self.ListCtrl.SetColumnWidth(1, int(Width * 0.1))\n self.ListCtrl.SetColumnWidth(2, int(Width * 0.2))\n self.ListCtrl.SetColumnWidth(3, int(Width * 0.1))\n self.ListCtrl.SetColumnWidth(4, int(Width * 0.2))\n\n if Event != None:\n Event.Skip()\n\n#End System Info Page 6\n#Begin System Info Window\nclass SystemInfoWindow(wx.Frame):\n def __init__(self, ParentWindow):\n \"\"\"Initialize SystemInfoWindow\"\"\"\n wx.Frame.__init__(self, wx.GetApp().TopWindow, title=\"WxFixBoot - System Information\", size=(780,310), style=wx.DEFAULT_FRAME_STYLE)\n self.Panel = wx.Panel(self)\n self.SetClientSize(wx.Size(780,310))\n self.ParentWindow = ParentWindow\n wx.Frame.SetIcon(self, AppIcon)\n\n #Set up the notebook and the pages.\n self.NoteBook = wx.Notebook(self.Panel)\n Page1 = SystemInfoPage1(self.NoteBook, self)\n Page2 = SystemInfoPage2(self.NoteBook, self)\n Page3 = SystemInfoPage3(self.NoteBook, self)\n Page4 = SystemInfoPage4(self.NoteBook, self)\n Page5 = SystemInfoPage5(self.NoteBook, self)\n Page6 = SystemInfoPage6(self.NoteBook, self)\n\n self.NoteBook.AddPage(Page1, \"Disk Info 1\")\n self.NoteBook.AddPage(Page2, \"Disk Info 2\")\n self.NoteBook.AddPage(Page3, \"Disk Info 3\")\n self.NoteBook.AddPage(Page4, \"OS Info\")\n self.NoteBook.AddPage(Page5, \"Bootloader Info 1\")\n self.NoteBook.AddPage(Page6, \"Bootloader Info 2\")\n\n #Set up the sizer.\n MainSizer = wx.BoxSizer()\n MainSizer.Add(self.NoteBook, 1, wx.EXPAND)\n self.Panel.SetSizer(MainSizer)\n MainSizer.SetMinSize(wx.Size(780,310))\n MainSizer.SetSizeHints(self)\n\n self.BindEvents()\n\n #Call Layout() on self.Panel() to ensure it displays properly.\n self.Panel.Layout()\n\n logger.info(\"SystemInfoWindow().__init__(): Ready. Waiting for events...\")\n\n def BindEvents(self):\n \"\"\"Bind all events for SystemInfoWindow\"\"\"\n self.Bind(wx.EVT_CLOSE, self.OnExit)\n\n def OnExit(self, Event=None):\n \"\"\"Exit SystemInfoWindow\"\"\"\n logger.info(\"SystemInfoWindow().OnExit(): Closing SystemInfoWindow...\")\n self.Destroy()\n\n#End System Info Window\n#Begin Privacy Policy Window.\nclass PrivPolWindow(wx.Frame):\n def __init__(self, ParentWindow):\n \"\"\"Initialize PrivPolWindow\"\"\"\n wx.Frame.__init__(self, parent=wx.GetApp().TopWindow, title=\"WxFixBoot - Privacy Policy\", size=(750,400), style=wx.DEFAULT_FRAME_STYLE)\n self.Panel = wx.Panel(self)\n self.SetClientSize(wx.Size(750,400))\n self.ParentWindow = ParentWindow\n wx.Frame.SetIcon(self, AppIcon)\n\n logger.debug(\"PrivPolWindow().__init__(): Creating button...\")\n self.CreateButton()\n\n logger.debug(\"PrivPolWindow().__init__(): Loading page...\")\n self.LoadPage()\n\n logger.debug(\"PrivPolWindow().__init__(): Setting up sizers...\")\n self.SetupSizers()\n\n logger.debug(\"PrivPolWindow().__init__(): Binding Events...\")\n self.BindEvents()\n\n #Call Layout() on self.Panel() to ensure it displays properly.\n self.Panel.Layout()\n\n logger.debug(\"PrivPolWindow().__init__(): Ready. Waiting for events...\")\n\n def CreateButton(self):\n \"\"\"Create the close buton.\"\"\"\n self.CloseButton = wx.Button(self.Panel, -1, \"Close\")\n\n def LoadPage(self):\n \"\"\"Load the privacy policy web page (locally stored)\"\"\"\n File = open(\"/usr/share/wxfixboot/other/privacypolicy.html\", \"r\")\n Text = File.read()\n File.close()\n\n self.html = wx.html.HtmlWindow(self.Panel)\n self.html.SetPage(Text)\n\n def SetupSizers(self):\n \"\"\"Set up sizers for PrivPolWindow\"\"\"\n #Make a boxsizer.\n MainSizer = wx.BoxSizer(wx.VERTICAL)\n\n #Add each object to the main sizer.\n MainSizer.Add(self.html, 1, wx.EXPAND|wx.ALL, 10)\n MainSizer.Add(self.CloseButton, 0, wx.BOTTOM|wx.CENTER, 10)\n\n #Get the sizer set up for the frame.\n self.Panel.SetSizer(MainSizer)\n MainSizer.SetMinSize(wx.Size(750,400))\n MainSizer.SetSizeHints(self)\n\n def BindEvents(self):\n \"\"\"Bind events so we can close this window.\"\"\"\n self.Bind(wx.EVT_BUTTON, self.OnClose, self.CloseButton)\n self.Bind(wx.EVT_CLOSE, self.OnClose)\n\n def OnClose(self,Event=None):\n \"\"\"Close PrivPolWindow\"\"\"\n self.Destroy()\n\n#End Privacy Policy Window.\n#Begin Bootloader Options Window.\nclass BootloaderOptionsWindow(wx.Frame):\n def __init__(self, ParentWindow):\n \"\"\"Initialise bootloader options window\"\"\"\n wx.Frame.__init__(self, parent=wx.GetApp().TopWindow, title=\"WxFixBoot - Bootloader Options\", size=(400,200), style=wx.DEFAULT_FRAME_STYLE)\n self.Panel = wx.Panel(self)\n self.SetClientSize(wx.Size(800,800))\n self.ParentWindow = ParentWindow\n wx.Frame.SetIcon(self, AppIcon)\n\n #Set up the previous OS choice.\n if SystemInfo[\"PreviousOSChoice\"] == \"\":\n SystemInfo[\"PreviousOSChoice\"] = SystemInfo[\"ModifyableOSs\"][0]\n\n self.CreateText()\n self.CreateChoiceBoxes()\n self.CreateCheckBoxes()\n self.CreateButtons()\n self.CreateOtherWidgets()\n self.SetupSizers()\n self.BindEvents()\n\n self.OnAdvancedOptions()\n self.OnOSInfo()\n\n wx.CallLater(500, self.OnOSChoiceChange, Startup=True)\n\n #Let user know they can specify a timeout of 0 seconds to hide the boot menu, if they have only 1 (detected) OS.\n if len(OSInfo) == 1:\n wx.CallLater(500, self.DisplayTimeoutInfoMessage)\n\n logger.debug(\"BootloaderOptionsWindow().__init__(): Bootloader Options Window Started.\")\n\n def DisplayTimeoutInfoMessage(self):\n \"\"\"Displays an informational message to the user if they only have 1 detected OS.\"\"\"\n Dlg = wx.MessageDialog(self.Panel, \"WxFixBoot only detected one Operating System on your computer. You can hide your boot menu entirely, if you wish, by selecting a bootloader timeout of 0 seconds.\", \"WxFixBoot - Information\", style=wx.OK | wx.ICON_INFORMATION)\n Dlg.ShowModal()\n Dlg.Destroy()\n\n def CreateText(self):\n \"\"\"Create the text\"\"\"\n self.TitleText = wx.StaticText(self.Panel, -1, \"Select each OS you want to modify\")\n self.OSInfoText = wx.lib.stattext.GenStaticText(self.Panel, -1, \"OS Info\")\n\n #Basic Options.\n self.BasicOptionsText = wx.lib.stattext.GenStaticText(self.Panel, -1, \"Basic Options\")\n self.NewTimeoutText = wx.StaticText(self.Panel, -1, \"New timeout (in seconds):\")\n self.DefaultOSText = wx.StaticText(self.Panel, -1, \"Default OS to boot:\")\n\n #Advanced Options.\n self.AdvancedOptionsText = wx.lib.stattext.GenStaticText(self.Panel, -1, \"Advanced Options\")\n self.NewKernelOptionsText = wx.StaticText(self.Panel, -1, \"New kernel options:\")\n self.BackupBootloaderText = wx.StaticText(self.Panel, -1, \"Backup to:\")\n self.RestoreBootloaderText = wx.StaticText(self.Panel, -1, \"Restore from:\")\n\n def CreateChoiceBoxes(self):\n \"\"\"Create the choice boxes\"\"\"\n self.OSChoice = wx.Choice(self.Panel, -1, choices=SystemInfo[\"ModifyableOSs\"])\n self.OSChoice.SetStringSelection(SystemInfo[\"PreviousOSChoice\"])\n\n #Basic Options.\n self.DefaultOSChoice = wx.Choice(self.Panel, -1, choices=OSInfo.keys())\n\n #Advanced Options.\n self.NewBootloaderChoice = wx.Choice(self.Panel, -1, choices=[])\n self.BackupBootloaderChoice = wx.Choice(self.Panel, -1, choices=[\"-- Please Select --\", \"Specify File Path...\"])\n self.RestoreBootloaderChoice = wx.Choice(self.Panel, -1, choices=[\"-- Please Select --\", \"Specify File Path...\"])\n\n def CreateCheckBoxes(self):\n \"\"\"Create the check boxes\"\"\"\n #Basic Options.\n self.ReinstallBootloaderCheckBox = wx.CheckBox(self.Panel, -1, \"\")\n self.UpdateBootloaderCheckBox = wx.CheckBox(self.Panel, -1, \"\")\n self.KeepBootloaderTimeoutCheckBox = wx.CheckBox(self.Panel, -1, \"\")\n\n #Advanced Options.\n self.KeepKernelOptionsCheckBox = wx.CheckBox(self.Panel, -1, \"\")\n self.InstallNewBootloaderCheckBox = wx.CheckBox(self.Panel, -1, \"Install a New Bootloader\")\n self.BackupBootloaderCheckBox = wx.CheckBox(self.Panel, -1, \"Backup this OS's bootloader config\")\n self.RestoreBootloaderCheckBox = wx.CheckBox(self.Panel, -1, \"Restore this OS's bootloader config\")\n\n def CreateButtons(self):\n \"\"\"Create the buttons\"\"\"\n self.SystemInfoButton = wx.Button(self.Panel, -1, \"View More Details\")\n self.RevertOSChangesButton = wx.Button(self.Panel, -1, \"Revert Changes for this OS\")\n self.SaveButton = wx.Button(self.Panel, -1, \"Save All Changes And Close\")\n\n def CreateOtherWidgets(self):\n \"\"\"Create all other widgets\"\"\"\n #Bootloader timeout spinner.\n self.BootloaderTimeoutSpinner = wx.SpinCtrl(self.Panel, -1, \"\")\n self.BootloaderTimeoutSpinner.SetRange(0,100)\n\n #Arrows.\n img1 = wx.Image(\"/usr/share/wxfixboot/images/ArrowDown.png\", wx.BITMAP_TYPE_PNG)\n img2 = wx.Image(\"/usr/share/wxfixboot/images/ArrowRight.png\", wx.BITMAP_TYPE_PNG)\n self.DownArrowImage = wx.BitmapFromImage(img1)\n self.RightArrowImage = wx.BitmapFromImage(img2)\n\n self.Arrow1 = wx.lib.statbmp.GenStaticBitmap(self.Panel, -1, self.DownArrowImage)\n self.Arrow2 = wx.lib.statbmp.GenStaticBitmap(self.Panel, -1, self.DownArrowImage)\n self.Arrow3 = wx.lib.statbmp.GenStaticBitmap(self.Panel, -1, self.DownArrowImage)\n\n #List Ctrl.\n self.ListCtrl = wx.ListCtrl(self.Panel, -1, style=wx.LC_REPORT|wx.BORDER_SUNKEN|wx.LC_VRULES)\n NoteBookSharedFunctions.UpdateListCtrl(self, Headings=[\"Name\", \"IsCurrentOS\", \"Arch\", \"Partition\", \"PackageManager\"], Dictionary=OSInfo)\n\n #Text ctrl.\n self.NewKernelOptionsTextCtrl = wx.TextCtrl(self.Panel, -1, \"\")\n\n def OnSize(self, Event=None):\n \"\"\"Auto resize the ListCtrl columns\"\"\"\n Width, Height = self.ListCtrl.GetClientSizeTuple()\n\n self.ListCtrl.SetColumnWidth(0, int(Width * 0.4))\n self.ListCtrl.SetColumnWidth(1, int(Width * 0.1))\n self.ListCtrl.SetColumnWidth(2, int(Width * 0.1))\n self.ListCtrl.SetColumnWidth(3, int(Width * 0.2))\n self.ListCtrl.SetColumnWidth(4, int(Width * 0.2))\n\n if Event != None:\n Event.Skip()\n\n def SetupSizers(self):\n \"\"\"Setup the sizers\"\"\"\n self.MainSizer = wx.BoxSizer(wx.VERTICAL)\n\n OSInfoSizer = wx.BoxSizer(wx.HORIZONTAL)\n\n #Add items to OSInfoSizer.\n OSInfoSizer.Add((5,5), 1, wx.RIGHT|wx.ALIGN_CENTER, 5)\n OSInfoSizer.Add(self.OSInfoText, 0, wx.RIGHT|wx.LEFT|wx.ALIGN_CENTER, 5)\n OSInfoSizer.Add(self.Arrow1, 0, wx.RIGHT|wx.LEFT|wx.ALIGN_CENTER, 5)\n OSInfoSizer.Add((5,5), 1, wx.LEFT|wx.ALIGN_CENTER, 5)\n\n BasicOptionsSizer = wx.BoxSizer(wx.HORIZONTAL)\n\n #Add items to BasicOptionsSizer.\n BasicOptionsSizer.Add((5,5), 1, wx.RIGHT|wx.ALIGN_CENTER, 5)\n BasicOptionsSizer.Add(self.BasicOptionsText, 0, wx.RIGHT|wx.LEFT|wx.ALIGN_CENTER, 5)\n BasicOptionsSizer.Add(self.Arrow2, 0, wx.RIGHT|wx.LEFT|wx.ALIGN_CENTER, 5)\n BasicOptionsSizer.Add((5,5), 1, wx.LEFT|wx.ALIGN_CENTER, 5)\n\n self.FixAndUpdateBootloaderSizer = wx.BoxSizer(wx.HORIZONTAL)\n\n #Add items to FixAndUpdateBootloaderSizer.\n self.FixAndUpdateBootloaderSizer.Add(self.ReinstallBootloaderCheckBox, 1, wx.RIGHT|wx.ALIGN_CENTER, 5)\n self.FixAndUpdateBootloaderSizer.Add(self.UpdateBootloaderCheckBox, 1, wx.LEFT|wx.ALIGN_CENTER, 5)\n\n self.TimeoutSizer = wx.BoxSizer(wx.HORIZONTAL)\n\n #Add items to TimeoutSizer.\n self.TimeoutSizer.Add(self.KeepBootloaderTimeoutCheckBox, 3, wx.RIGHT|wx.ALIGN_CENTER, 5)\n self.TimeoutSizer.Add((5,5), 1, wx.RIGHT|wx.LEFT, 5)\n self.TimeoutSizer.Add(self.NewTimeoutText, 2, wx.RIGHT|wx.LEFT|wx.ALIGN_CENTER, 5)\n self.TimeoutSizer.Add(self.BootloaderTimeoutSpinner, 3, wx.LEFT|wx.ALIGN_CENTER, 5)\n\n self.DefaultOSSizer = wx.BoxSizer(wx.HORIZONTAL)\n\n #Add items to DefaultOSSizer.\n self.DefaultOSSizer.Add(self.DefaultOSText, 1, wx.RIGHT|wx.ALIGN_CENTER, 5)\n self.DefaultOSSizer.Add(self.DefaultOSChoice, 1, wx.LEFT|wx.ALIGN_CENTER, 5)\n\n AdvancedOptionsSizer = wx.BoxSizer(wx.HORIZONTAL)\n\n #Add items to AdvancedOptionsSizer.\n AdvancedOptionsSizer.Add((5,5), 1, wx.RIGHT|wx.ALIGN_CENTER, 5)\n AdvancedOptionsSizer.Add(self.AdvancedOptionsText, 0, wx.RIGHT|wx.LEFT|wx.ALIGN_CENTER, 5)\n AdvancedOptionsSizer.Add(self.Arrow3, 0, wx.RIGHT|wx.LEFT|wx.ALIGN_CENTER, 5)\n AdvancedOptionsSizer.Add((5,5), 1, wx.LEFT|wx.ALIGN_CENTER, 5)\n\n self.KernelOptionsSizer = wx.BoxSizer(wx.HORIZONTAL)\n\n #Add items to KernelOptionsSizer.\n self.KernelOptionsSizer.Add(self.KeepKernelOptionsCheckBox, 2, wx.RIGHT|wx.ALIGN_CENTER, 5)\n self.KernelOptionsSizer.Add(self.NewKernelOptionsText, 1, wx.RIGHT|wx.LEFT|wx.ALIGN_CENTER, 5)\n self.KernelOptionsSizer.Add(self.NewKernelOptionsTextCtrl, 2, wx.LEFT|wx.ALIGN_CENTER, 5)\n\n self.InstallNewBootloaderSizer = wx.BoxSizer(wx.HORIZONTAL)\n\n #Add items to InstallNewBootloaderSizer.\n self.InstallNewBootloaderSizer.Add(self.InstallNewBootloaderCheckBox, 2, wx.RIGHT|wx.ALIGN_CENTER, 5)\n self.InstallNewBootloaderSizer.Add((5,5), 1, wx.RIGHT|wx.LEFT|wx.ALIGN_CENTER, 5)\n self.InstallNewBootloaderSizer.Add(self.NewBootloaderChoice, 2, wx.LEFT|wx.ALIGN_CENTER, 5)\n\n self.BackupBootloaderSizer = wx.BoxSizer(wx.HORIZONTAL)\n\n #Add items to BackupBootloaderSizer.\n self.BackupBootloaderSizer.Add(self.BackupBootloaderCheckBox, 2, wx.RIGHT|wx.ALIGN_CENTER, 5)\n self.BackupBootloaderSizer.Add(self.BackupBootloaderText, 1, wx.RIGHT|wx.LEFT|wx.ALIGN_CENTER, 5)\n self.BackupBootloaderSizer.Add(self.BackupBootloaderChoice, 2, wx.LEFT|wx.ALIGN_CENTER, 5)\n\n self.RestoreBootloaderSizer = wx.BoxSizer(wx.HORIZONTAL)\n\n #Add items to RestoreBootloaderSizer.\n self.RestoreBootloaderSizer.Add(self.RestoreBootloaderCheckBox, 2, wx.RIGHT|wx.ALIGN_CENTER, 5)\n self.RestoreBootloaderSizer.Add(self.RestoreBootloaderText, 1, wx.RIGHT|wx.LEFT|wx.ALIGN_CENTER, 5)\n self.RestoreBootloaderSizer.Add(self.RestoreBootloaderChoice, 2, wx.LEFT|wx.ALIGN_CENTER, 5)\n\n BottomButtonSizer = wx.BoxSizer(wx.HORIZONTAL)\n\n #Add items to BottomButtonSizer.\n BottomButtonSizer.Add(self.RevertOSChangesButton, 1, wx.RIGHT|wx.ALIGN_CENTER, 5)\n BottomButtonSizer.Add(self.SaveButton, 1, wx.LEFT|wx.ALIGN_CENTER, 5)\n\n #Add items to MainSizer.\n self.MainSizer.Add(self.TitleText, 1, wx.ALL|wx.CENTER, 10)\n self.MainSizer.Add(self.OSChoice, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.MainSizer.Add(wx.StaticLine(self.Panel), 0, wx.ALL|wx.EXPAND, 10)\n self.MainSizer.Add(OSInfoSizer, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.MainSizer.Add(self.ListCtrl, 5, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.MainSizer.Add(self.SystemInfoButton, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.MainSizer.Add(wx.StaticLine(self.Panel), 0, wx.ALL|wx.EXPAND, 10)\n self.MainSizer.Add(BasicOptionsSizer, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.MainSizer.Add(self.FixAndUpdateBootloaderSizer, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.MainSizer.Add(self.TimeoutSizer, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.MainSizer.Add(self.DefaultOSSizer, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.MainSizer.Add(wx.StaticLine(self.Panel), 0, wx.ALL|wx.EXPAND, 10)\n self.MainSizer.Add(AdvancedOptionsSizer, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.MainSizer.Add(self.KernelOptionsSizer, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.MainSizer.Add(self.InstallNewBootloaderSizer, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.MainSizer.Add(self.BackupBootloaderSizer, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.MainSizer.Add(self.RestoreBootloaderSizer, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.MainSizer.Add(wx.StaticLine(self.Panel), 0, wx.ALL|wx.EXPAND, 10)\n self.MainSizer.Add(BottomButtonSizer, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n\n #Get the sizer set up for the frame.\n self.Panel.SetSizer(self.MainSizer)\n self.MainSizer.SetMinSize(wx.Size(749,673))\n\n def BindEvents(self):\n \"\"\"Bind all events for BootloaderOptionsWindow\"\"\"\n self.Bind(wx.EVT_CLOSE, self.OnClose)\n self.Bind(wx.EVT_SIZE, self.OnSize)\n\n #Text.\n self.OSInfoText.Bind(wx.EVT_LEFT_DOWN, self.OnOSInfo)\n self.BasicOptionsText.Bind(wx.EVT_LEFT_DOWN, self.OnBasicOptions)\n self.AdvancedOptionsText.Bind(wx.EVT_LEFT_DOWN, self.OnAdvancedOptions)\n\n #Images.\n self.Arrow1.Bind(wx.EVT_LEFT_DOWN, self.OnOSInfo)\n self.Arrow2.Bind(wx.EVT_LEFT_DOWN, self.OnBasicOptions)\n self.Arrow3.Bind(wx.EVT_LEFT_DOWN, self.OnAdvancedOptions)\n\n #Checkboxes.\n self.Bind(wx.EVT_CHECKBOX, self.OnTimeoutCheckBox, self.KeepBootloaderTimeoutCheckBox)\n self.Bind(wx.EVT_CHECKBOX, self.OnUpdateOrReinstallCheckBox, self.ReinstallBootloaderCheckBox)\n self.Bind(wx.EVT_CHECKBOX, self.OnUpdateOrReinstallCheckBox, self.UpdateBootloaderCheckBox)\n self.Bind(wx.EVT_CHECKBOX, self.OnInstallNewBootloaderCheckBox, self.InstallNewBootloaderCheckBox)\n self.Bind(wx.EVT_CHECKBOX, self.OnBackupBootloaderCheckBox, self.BackupBootloaderCheckBox)\n self.Bind(wx.EVT_CHECKBOX, self.OnRestoreBootloaderCheckBox, self.RestoreBootloaderCheckBox)\n self.Bind(wx.EVT_CHECKBOX, self.OnKernelOptionsCheckBox, self.KeepKernelOptionsCheckBox)\n\n #Buttons.\n self.Bind(wx.EVT_BUTTON, self.OnClose, self.SaveButton)\n self.Bind(wx.EVT_BUTTON, self.SystemInfo, self.SystemInfoButton)\n self.Bind(wx.EVT_BUTTON, self.LoadSettings, self.RevertOSChangesButton)\n\n #Choiceboxes.\n self.Bind(wx.EVT_CHOICE, self.OnOSChoiceChange, self.OSChoice)\n self.Bind(wx.EVT_CHOICE, self.OnRestoreBootloaderChoice, self.RestoreBootloaderChoice)\n self.Bind(wx.EVT_CHOICE, self.OnBackupBootloaderChoice, self.BackupBootloaderChoice)\n self.Bind(wx.EVT_CHOICE, self.OnNewBootloaderChoice, self.NewBootloaderChoice)\n\n def SystemInfo(self, Event=None):\n \"\"\"Start SystemInfoWindow\"\"\"\n logger.debug(\"BootloaderOptionsWindow().SystemInfo(): Starting System Info Window...\")\n SystemInfoWindow(self).Show()\n\n def LoadSettings(self, Event=None):\n \"\"\"Load all settings for this OS into the checkboxes and choice boxes\"\"\"\n OS = self.OSChoice.GetStringSelection()\n\n logger.debug(\"BootloaderOptionsWindow().LoadSettings(): Loading settings for \"+OS+\"...\")\n self.ReinstallBootloaderCheckBox.SetValue(BootloaderInfo[OS][\"Settings\"][\"Reinstall\"])\n self.UpdateBootloaderCheckBox.SetValue(BootloaderInfo[OS][\"Settings\"][\"Update\"])\n self.KeepBootloaderTimeoutCheckBox.SetValue(BootloaderInfo[OS][\"Settings\"][\"KeepExistingTimeout\"])\n self.BootloaderTimeoutSpinner.SetValue(BootloaderInfo[OS][\"Settings\"][\"NewTimeout\"])\n self.KeepKernelOptionsCheckBox.SetValue(BootloaderInfo[OS][\"Settings\"][\"KeepExistingKernelOptions\"])\n self.NewKernelOptionsTextCtrl.SetValue(BootloaderInfo[OS][\"Settings\"][\"NewKernelOptions\"])\n self.DefaultOSChoice.SetStringSelection(BootloaderInfo[OS][\"Settings\"][\"DefaultOS\"])\n self.InstallNewBootloaderCheckBox.SetValue(BootloaderInfo[OS][\"Settings\"][\"InstallNewBootloader\"])\n self.NewBootloaderChoice.SetStringSelection(BootloaderInfo[OS][\"Settings\"][\"NewBootloader\"])\n self.BackupBootloaderCheckBox.SetValue(BootloaderInfo[OS][\"Settings\"][\"BackupBootloader\"])\n self.BackupBootloaderChoice.SetStringSelection(BootloaderInfo[OS][\"Settings\"][\"BootloaderBackupTarget\"])\n self.RestoreBootloaderCheckBox.SetValue(BootloaderInfo[OS][\"Settings\"][\"RestoreBootloader\"])\n self.RestoreBootloaderChoice.SetStringSelection(BootloaderInfo[OS][\"Settings\"][\"BootloaderRestoreSource\"])\n self.OnTimeoutCheckBox()\n self.SetGUIState()\n\n def SetGUIState(self, Event=None):\n \"\"\"Set all the GUI element's states (enabled/disabled) for this OS\"\"\"\n OS = self.OSChoice.GetStringSelection()\n\n logger.debug(\"BootloaderOptionsWindow().SetGUIState(): Setting GUI state for \"+OS+\"...\")\n self.ReinstallBootloaderCheckBox.Enable(BootloaderInfo[OS][\"GUIState\"][\"ReinstallCheckBoxState\"])\n self.UpdateBootloaderCheckBox.Enable(BootloaderInfo[OS][\"GUIState\"][\"UpdateCheckBoxState\"])\n self.KeepBootloaderTimeoutCheckBox.Enable(BootloaderInfo[OS][\"GUIState\"][\"KeepExistingTimeoutCheckBoxState\"])\n self.BootloaderTimeoutSpinner.Enable(BootloaderInfo[OS][\"GUIState\"][\"NewTimeoutSpinnerState\"])\n self.KeepKernelOptionsCheckBox.Enable(BootloaderInfo[OS][\"GUIState\"][\"KeepExistingKernelOptionsCheckBoxState\"])\n self.NewKernelOptionsTextCtrl.Enable(BootloaderInfo[OS][\"GUIState\"][\"NewKernelOptionsTextCtrlState\"])\n self.DefaultOSChoice.Enable(BootloaderInfo[OS][\"GUIState\"][\"DefaultOSChoiceState\"])\n self.InstallNewBootloaderCheckBox.Enable(BootloaderInfo[OS][\"GUIState\"][\"InstallNewBootloaderCheckBoxState\"])\n self.NewBootloaderChoice.Enable(BootloaderInfo[OS][\"GUIState\"][\"NewBootloaderChoiceState\"])\n self.BackupBootloaderCheckBox.Enable(BootloaderInfo[OS][\"GUIState\"][\"BackupBootloaderCheckBoxState\"])\n self.BackupBootloaderChoice.Enable(BootloaderInfo[OS][\"GUIState\"][\"BackupBootloaderChoiceState\"])\n self.RestoreBootloaderCheckBox.Enable(BootloaderInfo[OS][\"GUIState\"][\"RestoreBootloaderCheckBoxState\"])\n self.RestoreBootloaderChoice.Enable(BootloaderInfo[OS][\"GUIState\"][\"RestoreBootloaderChoiceState\"])\n\n def SetTextLabels(self):\n \"\"\"Set text labels for GUI elements\"\"\"\n OS = self.OSChoice.GetStringSelection()\n\n logger.debug(\"BootloaderOptionsWindow().SetTextLabels(): Setting text labels for \"+OS+\"...\")\n self.KeepKernelOptionsCheckBox.SetLabel(\"Keep \"+BootloaderInfo[OS][\"Bootloader\"]+\"'s existing kernel options\")\n self.InstallNewBootloaderCheckBox.SetLabel(\"Replace \"+BootloaderInfo[OS][\"Bootloader\"]+\" with:\")\n self.ReinstallBootloaderCheckBox.SetLabel(\"Fix/Reinstall \"+BootloaderInfo[OS][\"Bootloader\"])\n self.UpdateBootloaderCheckBox.SetLabel(\"Update \"+BootloaderInfo[OS][\"Bootloader\"]+\"'s Config\")\n self.KeepBootloaderTimeoutCheckBox.SetLabel(\"Keep \"+BootloaderInfo[OS][\"Bootloader\"]+\"'s existing menu timeout\")\n self.RevertOSChangesButton.SetLabel(\"Revert Changes for \"+OS)\n\n def OnOSChoiceChange(self, Event=None, Startup=False):\n \"\"\"Save and load new GUI settings and states in accordance with the OS choice change\"\"\"\n logger.debug(\"BootloaderOptionsWindow().OnOSChoiceChange(): OS choice has changed. Saving and then loading settings...\")\n\n #Save settings when selection a new choice, but not when this is called when the window is first opened.\n if Startup == False:\n self.SaveSettings(OS=SystemInfo[\"PreviousOSChoice\"])\n self.SaveGUIState(OS=SystemInfo[\"PreviousOSChoice\"])\n SystemInfo[\"PreviousOSChoice\"] = self.OSChoice.GetStringSelection()\n\n #Set up NewBootloaderChoice.\n Choices = BootloaderInfo[self.OSChoice.GetStringSelection()][\"AvailableBootloaders\"]\n\n if OSInfo[self.OSChoice.GetStringSelection()][\"EFIPartition\"] == \"Unknown\":\n #Remove GRUB-UEFI and ELILO if they are available for install.\n if \"GRUB-UEFI\" in Choices:\n Choices.remove(\"GRUB-UEFI\")\n\n if \"ELILO\" in Choices:\n Choices.remove(\"ELILO\")\n\n dlg = wx.MessageDialog(self.Panel, \"This OS has no UEFI partition, so you will be unable to select a UEFI bootloader to install.\", \"WxFixBoot - Information\", style=wx.OK | wx.ICON_INFORMATION, pos=wx.DefaultPosition)\n dlg.ShowModal()\n dlg.Destroy()\n\n #Remove the current bootloader from the choices (if it's in there).\n if BootloaderInfo[self.OSChoice.GetStringSelection()][\"Bootloader\"] in Choices:\n Choices.remove(BootloaderInfo[self.OSChoice.GetStringSelection()][\"Bootloader\"])\n\n #Set the choices.\n self.NewBootloaderChoice.SetItems([\"-- Please Select --\"]+Choices)\n self.NewBootloaderChoice.SetStringSelection(\"-- Please Select --\")\n\n self.LoadSettings()\n self.SetTextLabels()\n\n #Don't allow the user to attempt to modify or remove GRUB-LEGACY.\n if BootloaderInfo[self.OSChoice.GetStringSelection()][\"Bootloader\"] == \"GRUB-LEGACY\":\n self.ReinstallBootloaderCheckBox.Disable()\n self.UpdateBootloaderCheckBox.Disable()\n self.InstallNewBootloaderCheckBox.Disable()\n\n #Make sure the window displays properly.\n self.MainSizer.SetSizeHints(self)\n\n def OnOSInfo(self, Event=None):\n \"\"\"Hide/Show the OS info, and rotate the arrow\"\"\"\n if self.ListCtrl.IsShown():\n logger.debug(\"BootloaderOptionsWindow().OnOSInfo(): Hiding OS Info...\")\n self.Arrow1.SetBitmap(self.RightArrowImage)\n\n self.MainSizer.Detach(self.ListCtrl)\n self.MainSizer.Detach(self.SystemInfoButton)\n self.ListCtrl.Hide()\n self.SystemInfoButton.Hide()\n\n else:\n logger.debug(\"BootloaderOptionsWindow().OnOSInfo(): Showing OS Info...\")\n self.Arrow1.SetBitmap(self.DownArrowImage)\n\n self.MainSizer.Insert(4, self.ListCtrl, 5, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.MainSizer.Insert(5, self.SystemInfoButton, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.ListCtrl.Show()\n self.SystemInfoButton.Show()\n\n #Make sure the window is displayed properly.\n self.MainSizer.SetSizeHints(self)\n self.Panel.Layout()\n\n def OnBasicOptions(self, Event=None):\n \"\"\"Hide/Show the basic options, and rotate the arrow\"\"\"\n if self.ReinstallBootloaderCheckBox.IsShown():\n logger.debug(\"BootloaderOptionsWindow().OnBasicOptions(): Hiding Basic Options...\")\n\n #Refuse to collapse this section if Advanced Settings are shown.\n if self.InstallNewBootloaderCheckBox.IsShown():\n logger.debug(\"BootloaderOptionsWindow().OnBasicOptions(): Cancelling because Advanced Options are shown...\")\n return True\n\n self.Arrow2.SetBitmap(self.RightArrowImage)\n\n self.MainSizer.Detach(self.FixAndUpdateBootloaderSizer)\n self.MainSizer.Detach(self.TimeoutSizer)\n self.MainSizer.Detach(self.DefaultOSSizer)\n\n self.ReinstallBootloaderCheckBox.Hide()\n self.UpdateBootloaderCheckBox.Hide()\n self.KeepBootloaderTimeoutCheckBox.Hide()\n self.NewTimeoutText.Hide()\n self.BootloaderTimeoutSpinner.Hide()\n self.DefaultOSText.Hide()\n self.DefaultOSChoice.Hide()\n\n else:\n logger.debug(\"BootloaderOptionsWindow().OnBasicOptions(): Showing Basic Options...\")\n self.Arrow2.SetBitmap(self.DownArrowImage)\n\n #Find the first index to re-add items in MainSizer.\n if self.ListCtrl.IsShown():\n FirstNumber = 8\n\n else:\n FirstNumber = 6\n\n self.MainSizer.Insert(FirstNumber, self.FixAndUpdateBootloaderSizer, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.MainSizer.Insert(FirstNumber+1, self.TimeoutSizer, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.MainSizer.Insert(FirstNumber+2, self.DefaultOSSizer, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n\n self.ReinstallBootloaderCheckBox.Show()\n self.UpdateBootloaderCheckBox.Show()\n self.KeepBootloaderTimeoutCheckBox.Show()\n self.NewTimeoutText.Show()\n self.BootloaderTimeoutSpinner.Show()\n self.DefaultOSText.Show()\n self.DefaultOSChoice.Show()\n\n #Make sure the window displays properly.\n self.MainSizer.SetSizeHints(self)\n self.Panel.Layout()\n\n def OnAdvancedOptions(self, Event=None):\n \"\"\"Show/Hide the advanced options, and rotate the arrow\"\"\"\n if self.InstallNewBootloaderCheckBox.IsShown():\n logger.debug(\"BootloaderOptionsWindow().OnAdvancedOptions(): Hiding Advanced Options...\")\n self.Arrow3.SetBitmap(self.RightArrowImage)\n\n self.MainSizer.Detach(self.KernelOptionsSizer)\n self.MainSizer.Detach(self.InstallNewBootloaderSizer)\n self.MainSizer.Detach(self.BackupBootloaderSizer)\n self.MainSizer.Detach(self.RestoreBootloaderSizer)\n\n self.KeepKernelOptionsCheckBox.Hide()\n self.NewKernelOptionsText.Hide()\n self.NewKernelOptionsTextCtrl.Hide()\n self.InstallNewBootloaderCheckBox.Hide()\n self.NewBootloaderChoice.Hide()\n self.BackupBootloaderCheckBox.Hide()\n self.BackupBootloaderText.Hide()\n self.BackupBootloaderChoice.Hide()\n self.RestoreBootloaderCheckBox.Hide()\n self.RestoreBootloaderText.Hide()\n self.RestoreBootloaderChoice.Hide()\n\n else:\n logger.debug(\"BootloaderOptionsWindow().OnAdvancedOptions(): Showing Advanced Options...\")\n\n #If Basic Options are hidden, show them.\n if self.ReinstallBootloaderCheckBox.IsShown() == False:\n logger.debug(\"BootloaderOptionsWindow().OnAdvancedOptions(): Showing Basic Options first...\")\n self.OnBasicOptions()\n\n self.Arrow3.SetBitmap(self.DownArrowImage)\n\n if self.ListCtrl.IsShown():\n FirstNumber = 13\n\n else:\n FirstNumber = 11\n\n self.MainSizer.Insert(FirstNumber, self.KernelOptionsSizer, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.MainSizer.Insert(FirstNumber+1, self.InstallNewBootloaderSizer, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.MainSizer.Insert(FirstNumber+2, self.BackupBootloaderSizer, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.MainSizer.Insert(FirstNumber+3, self.RestoreBootloaderSizer, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n\n self.KeepKernelOptionsCheckBox.Show()\n self.NewKernelOptionsText.Show()\n self.NewKernelOptionsTextCtrl.Show()\n self.InstallNewBootloaderCheckBox.Show()\n self.NewBootloaderChoice.Show()\n self.BackupBootloaderCheckBox.Show()\n self.BackupBootloaderText.Show()\n self.BackupBootloaderChoice.Show()\n self.RestoreBootloaderCheckBox.Show()\n self.RestoreBootloaderText.Show()\n self.RestoreBootloaderChoice.Show()\n\n #Make sure the window displays properly.\n self.MainSizer.SetSizeHints(self)\n self.Panel.Layout()\n\n def OnBackupBootloaderChoice(self, Event=None):\n \"\"\"Allow the user to select a config file to backup the bootloader to\"\"\"\n logger.debug(\"BootloaderOptionsWindow().OnBackupBootloaderChoice(): Selecting bootloader config backup file...\")\n\n File = self.BackupBootloaderChoice.GetStringSelection()\n\n #Determine what to do here.\n if File == \"Specify File Path...\":\n Dlg = wx.FileDialog(self.Panel, \"Select Backup File...\", defaultDir=\"/home\", wildcard=\"All Files/Devices (*)|*|WxFixBoot Bootloader Config Backup (.wxfbc)|*.wxfbc\", style=wx.SAVE)\n\n if Dlg.ShowModal() == wx.ID_OK:\n File = Dlg.GetPath()\n logger.debug(\"BootloaderOptionsWindow().OnBackupBootloaderChoice(): File is \"+File+\"...\")\n logger.debug(\"BootloaderOptionsWindow().OnBackupBootloaderChoice(): Saving config to \"+File+\"...\")\n plistlib.writePlist(BootloaderInfo[self.OSChoice.GetStringSelection()], File)\n logger.debug(\"BootloaderOptionsWindow().OnBackupBootloaderChoice(): Finished saving config to \"+File+\"...\")\n\n #Let the user know we were successful.\n MsgDlg = wx.MessageDialog(self.Panel, \"Finished backing up config to \"+File+\"!\", \"Config Backup Successful\", wx.OK | wx.ICON_INFORMATION, pos=wx.DefaultPosition)\n MsgDlg.ShowModal()\n MsgDlg.Destroy()\n\n #Reset the choicebox and checkbox.\n self.BackupBootloaderChoice.SetStringSelection(\"-- Please Select --\")\n self.BackupBootloaderCheckBox.SetValue(0)\n self.OnBackupBootloaderCheckBox()\n\n else:\n #Reset choice box.\n self.BackupBootloaderChoice.SetStringSelection(\"-- Please Select --\")\n\n Dlg.Destroy()\n\n def OnRestoreBootloaderChoice(self, Event=None):\n \"\"\"Allow the user to select a config file to restore the bootloader from\"\"\"\n logger.debug(\"BootloaderOptionsWindow().OnRestoreBootloaderChoice(): Selecting bootloader config backup file...\")\n\n File = self.RestoreBootloaderChoice.GetStringSelection()\n\n #Determine what to do here.\n if File == \"Specify File Path...\":\n Dlg = wx.FileDialog(self.Panel, \"Select Backup File...\", defaultDir=\"/home\", wildcard=\"All Files/Devices (*)|*|WxFixBoot Bootloader Config Backup (.wxfbc)|*.wxfbc\", style=wx.OPEN)\n\n if Dlg.ShowModal() == wx.ID_OK:\n File = Dlg.GetPath()\n logger.debug(\"BootloaderOptionsWindow().OnRestoreBootloaderChoice(): Loading config from \"+File+\"...\")\n\n try:\n self.SetupForRestoringBootloader(plistlib.readPlist(File))\n\n except:\n #Error!\n logger.error(\"BootloaderOptionsWindow().OnRestoreBootloaderChoice(): Error when loading config! Warning user and reloading previous settings...\")\n\n #Let the user know about the error.\n MsgDlg = wx.MessageDialog(self.Panel, \"Couldn't load config from \"+File+\"! Are you sure you selected the right file? WxFixBoot will revert back to the previous settings now.\", \"Config Load Failed!\", wx.OK | wx.ICON_ERROR, pos=wx.DefaultPosition)\n MsgDlg.ShowModal()\n MsgDlg.Destroy()\n\n #Reload previous settings.\n self.OnOSChoiceChange()\n\n else:\n logger.debug(\"BootloaderOptionsWindow().OnRestoreBootloaderChoice(): Successfully loaded config from \"+File+\"...\")\n\n #Let the user know we were successful.\n MsgDlg = wx.MessageDialog(self.Panel, \"The bootloader configuration was successfully loaded. Please review the changes in this window, and then continue if you are satisfied.\", \"WxFixBoot - Information\", style=wx.OK | wx.ICON_INFORMATION, pos=wx.DefaultPosition)\n MsgDlg.ShowModal()\n MsgDlg.Destroy()\n\n #Reset the choicebox and checkbox.\n self.RestoreBootloaderChoice.SetStringSelection(\"-- Please Select --\")\n self.RestoreBootloaderCheckBox.SetValue(0)\n\n else:\n #Reset choice box.\n self.RestoreBootloaderChoice.SetStringSelection(\"-- Please Select --\")\n\n Dlg.Destroy()\n\n def SetupForRestoringBootloader(self, Config):\n \"\"\"Setup the window to use the configuration from the chosen bootloader config backup file\"\"\"\n OS = self.OSChoice.GetStringSelection()\n\n #Check this is the right config for this OS.\n if Config[\"OSName\"] != OS:\n dlg = wx.MessageDialog(self.Panel, \"This config file is config for \"+Config[\"OSName\"]+\", not \"+OS+\", the current OS. Please change the selected OS, or select the correct config file for this OS.\", \"WxFixBoot - Error\", style=wx.OK | wx.ICON_ERROR, pos=wx.DefaultPosition)\n dlg.ShowModal()\n dlg.Destroy()\n return True\n\n #Check the bootloader in the config file can be installed in this OS.\n if self.NewBootloaderChoice.FindString(Config[\"Bootloader\"]) == -1 and Config[\"Bootloader\"] != BootloaderInfo[OS][\"Bootloader\"]:\n dlg = wx.MessageDialog(self.Panel, \"The bootloader installed at the time the config was backed up cannot be installed in this OS. Most likely, the config file has been tampered with or has corrupted.\", \"WxFixBoot - Error\", style=wx.OK | wx.ICON_ERROR, pos=wx.DefaultPosition)\n dlg.ShowModal()\n dlg.Destroy()\n return True\n\n #Disable the restore config checkbox.\n self.RestoreBootloaderChoice.SetStringSelection(\"-- Please Select --\")\n self.RestoreBootloaderCheckBox.SetValue(0)\n self.OnRestoreBootloaderCheckBox()\n\n #Determine if the current bootloader is the same as the backed up one. \n if Config[\"Bootloader\"] == BootloaderInfo[OS][\"Bootloader\"] and Config[\"Bootloader\"] != \"GRUB-LEGACY\":\n #Set up to reinstall the current bootloader.\n self.ReinstallBootloaderCheckBox.Enable()\n self.ReinstallBootloaderCheckBox.SetValue(1)\n self.OnUpdateOrReinstallCheckBox()\n\n elif Config[\"Bootloader\"] != \"GRUB-LEGACY\" and BootloaderInfo[OS][\"Bootloader\"] != \"GRUB-LEGACY\":\n #Set up to replace the current bootloader with the old one.\n self.InstallNewBootloaderCheckBox.Enable()\n self.InstallNewBootloaderCheckBox.SetValue(1)\n self.NewBootloaderChoice.SetStringSelection(Config[\"Bootloader\"])\n self.OnInstallNewBootloaderCheckBox()\n\n else:\n #Don't allow the user to attempt to switch back to GRUB-LEGACY, or replace it.\n raise RuntimeError\n\n #Use kernel options used when the backup was taken.\n self.KeepKernelOptionsCheckBox.SetValue(0)\n self.OnKernelOptionsCheckBox()\n self.NewKernelOptionsTextCtrl.SetValue(Config[\"GlobalKernelOptions\"])\n\n #Use timeout used when the backup was taken.\n self.KeepBootloaderTimeoutCheckBox.SetValue(0)\n self.OnTimeoutCheckBox()\n self.BootloaderTimeoutSpinner.SetValue(Config[\"Timeout\"])\n\n #Use default OS used when the backup was taken.\n if Config[\"DefaultOS\"] in OSInfo.keys():\n self.DefaultOSChoice.SetStringSelection(Config[\"DefaultOS\"])\n\n else:\n Dlg = wx.MessageDialog(self.Panel, \"This default OS used when this config was backed up was not detected by WxFixBoot. Instead, \"+OS+\" will be used, or you can make a custom selection.\", \"WxFixBoot - Information\", wx.OK | wx.ICON_INFORMATION)\n Dlg.ShowModal()\n Dlg.Destroy()\n self.DefaultOSChoice.SetStringSelection(OS)\n\n logger.debug(\"BootloaderOptionsWindow().SetupForRestoringBootloader(): Finished loading config from file...\")\n\n def OnUpdateOrReinstallCheckBox(self, Event=None):\n \"\"\"Enable/Disable options, based on the value of the update/reinstall checkboxes.\"\"\"\n logger.debug(\"BootloaderOptionsWindow().OnUpdateOrReinstallCheckBox(): Enabling and Disabling options as needed...\")\n \n if self.ReinstallBootloaderCheckBox.IsChecked():\n self.UpdateBootloaderCheckBox.Disable()\n self.KeepBootloaderTimeoutCheckBox.Enable()\n self.KeepBootloaderTimeoutCheckBox.SetValue(1)\n self.KeepKernelOptionsCheckBox.Enable()\n self.KeepKernelOptionsCheckBox.SetValue(1)\n self.DefaultOSChoice.Enable()\n self.InstallNewBootloaderCheckBox.SetValue(0)\n self.InstallNewBootloaderCheckBox.Disable()\n self.NewBootloaderChoice.Disable()\n self.RestoreBootloaderCheckBox.Disable()\n self.RestoreBootloaderChoice.Disable()\n\n elif self.UpdateBootloaderCheckBox.IsChecked():\n self.ReinstallBootloaderCheckBox.Disable()\n self.KeepBootloaderTimeoutCheckBox.Enable()\n self.KeepBootloaderTimeoutCheckBox.SetValue(1)\n self.KeepKernelOptionsCheckBox.Enable()\n self.KeepKernelOptionsCheckBox.SetValue(1)\n self.DefaultOSChoice.Enable()\n self.InstallNewBootloaderCheckBox.SetValue(0)\n self.InstallNewBootloaderCheckBox.Disable()\n self.NewBootloaderChoice.Disable()\n self.RestoreBootloaderCheckBox.Disable()\n self.RestoreBootloaderChoice.Disable()\n\n else:\n self.ReinstallBootloaderCheckBox.Enable()\n self.UpdateBootloaderCheckBox.Enable()\n self.KeepBootloaderTimeoutCheckBox.SetValue(0)\n self.KeepBootloaderTimeoutCheckBox.Disable()\n self.KeepKernelOptionsCheckBox.SetValue(0)\n self.KeepKernelOptionsCheckBox.Disable()\n self.BootloaderTimeoutSpinner.Disable()\n self.NewKernelOptionsTextCtrl.Disable()\n self.DefaultOSChoice.Disable()\n self.InstallNewBootloaderCheckBox.Enable()\n self.NewBootloaderChoice.Disable()\n self.RestoreBootloaderCheckBox.Enable()\n self.RestoreBootloaderChoice.Disable()\n\n def OnKernelOptionsCheckBox(self, Event=None):\n \"\"\"Enable/Disable the kernel options text ctrl, based on the value of the kernel options checkbox.\"\"\"\n logger.debug(\"BootloaderOptionsWindow().OnKernelOptionsCheckBox(): Enabling and Disabling options as needed...\")\n\n if self.KeepKernelOptionsCheckBox.IsChecked():\n self.NewKernelOptionsTextCtrl.SetValue(BootloaderInfo[self.OSChoice.GetStringSelection()][\"Settings\"][\"NewKernelOptions\"])\n self.NewKernelOptionsTextCtrl.Disable()\n\n else:\n self.NewKernelOptionsTextCtrl.Enable()\n\n def OnTimeoutCheckBox(self, Event=None):\n \"\"\"Enable/Disable the bootloader timeout spinner, based on the value of the timeout checkbox.\"\"\"\n logger.debug(\"BootloaderOptionsWindow().OnTimeoutCheckBox(): Enabling and Disabling options s needed...\")\n\n if self.KeepBootloaderTimeoutCheckBox.IsChecked():\n self.BootloaderTimeoutSpinner.SetValue(BootloaderInfo[self.OSChoice.GetStringSelection()][\"Settings\"][\"NewTimeout\"])\n self.BootloaderTimeoutSpinner.Disable()\n\n else:\n self.BootloaderTimeoutSpinner.Enable()\n\n def OnBackupBootloaderCheckBox(self, Event=None):\n \"\"\"Enable/Disable the bootloader timeout spinner, based on the value of the timeout checkbox.\"\"\"\n logger.debug(\"BootloaderOptionsWindow().OnBackupBootloaderCheckBox(): Enabling and Disabling options as needed...\")\n\n if self.BackupBootloaderCheckBox.IsChecked():\n self.BackupBootloaderChoice.Enable()\n\n else:\n self.BackupBootloaderChoice.Disable()\n\n def OnRestoreBootloaderCheckBox(self, Event=None):\n \"\"\"Enable/Disable options, based on the value of the timeout checkbox.\"\"\"\n logger.debug(\"BootloaderOptionsWindow(). Enabling and disabling options as needed...\")\n\n if self.RestoreBootloaderCheckBox.IsChecked():\n self.RestoreBootloaderChoice.Enable()\n self.ReinstallBootloaderCheckBox.Disable()\n self.UpdateBootloaderCheckBox.Disable()\n self.InstallNewBootloaderCheckBox.Disable()\n self.NewBootloaderChoice.Disable()\n\n else:\n self.RestoreBootloaderChoice.Disable()\n self.ReinstallBootloaderCheckBox.Enable()\n self.UpdateBootloaderCheckBox.Enable()\n self.InstallNewBootloaderCheckBox.Enable()\n self.NewBootloaderChoice.Disable()\n\n #Don't allow the user to attempt to modify GRUB-LEGACY.\n if BootloaderInfo[self.OSChoice.GetStringSelection()][\"Bootloader\"] == \"GRUB-LEGACY\":\n self.ReinstallBootloaderCheckBox.Disable()\n self.UpdateBootloaderCheckBox.Disable()\n self.InstallNewBootloaderCheckBox.Disable()\n\n def OnInstallNewBootloaderCheckBox(self, Event=None):\n \"\"\"Enable/Disable options, based on the value of the new bootloader checkbox.\"\"\"\n logger.debug(\"BootloaderOptionsWindow().OnInstallNewBootloaderCheckBox(): Enabling and disabling options as needed...\")\n\n if self.InstallNewBootloaderCheckBox.IsChecked():\n self.NewBootloaderChoice.Enable()\n self.ReinstallBootloaderCheckBox.Disable()\n self.UpdateBootloaderCheckBox.Disable()\n self.KeepBootloaderTimeoutCheckBox.Enable()\n self.KeepBootloaderTimeoutCheckBox.SetValue(1)\n self.KeepKernelOptionsCheckBox.Enable()\n self.KeepKernelOptionsCheckBox.SetValue(1)\n self.DefaultOSChoice.Enable()\n self.RestoreBootloaderCheckBox.Disable()\n self.RestoreBootloaderChoice.Disable()\n\n else:\n self.NewBootloaderChoice.Disable()\n self.NewBootloaderChoice.SetStringSelection(\"-- Please Select --\")\n self.ReinstallBootloaderCheckBox.Enable()\n self.UpdateBootloaderCheckBox.Enable()\n self.KeepBootloaderTimeoutCheckBox.SetValue(0)\n self.KeepBootloaderTimeoutCheckBox.Disable()\n self.KeepKernelOptionsCheckBox.SetValue(0)\n self.KeepKernelOptionsCheckBox.Disable()\n self.BootloaderTimeoutSpinner.Disable()\n self.NewKernelOptionsTextCtrl.Disable()\n self.DefaultOSChoice.Disable()\n self.RestoreBootloaderCheckBox.Enable()\n self.RestoreBootloaderChoice.Disable()\n\n #Don't allow the user to attempt to modify GRUB-LEGACY.\n if BootloaderInfo[self.OSChoice.GetStringSelection()][\"Bootloader\"] == \"GRUB-LEGACY\":\n self.ReinstallBootloaderCheckBox.Disable()\n self.UpdateBootloaderCheckBox.Disable()\n self.InstallNewBootloaderCheckBox.Disable()\n\n def OnNewBootloaderChoice(self, Event=None):\n \"\"\"Warn user about LILO's/ELILO's rubbish multi OS support if needed\"\"\"\n if len(SystemInfo[\"ModifyableOSs\"]) > 1 and self.NewBootloaderChoice.GetStringSelection() in (\"LILO\", \"ELILO\"):\n Dlg = wx.MessageDialog(self.Panel, \"Installing \"+self.NewBootloaderChoice.GetStringSelection() +\" is discouraged because you have more than one Linux OS installed, and this bootloader has poor support for booting multiple Linux OSs. Click okay to continue.\", \"WxFixBoot - Warning\", wx.OK | wx.ICON_WARNING)\n Dlg.ShowModal()\n Dlg.Destroy()\n\n def SaveSettings(self, Event=None, OS=None):\n \"\"\"Save all settings for this OS from the checkboxes and choice boxes\"\"\"\n logger.debug(\"BootloaderOptionsWindow().SaveSettings(): Saving settings for \"+OS+\"...\")\n\n #Check that the settings are valid.\n if self.InstallNewBootloaderCheckBox.IsChecked() and self.NewBootloaderChoice.GetStringSelection() == \"-- Please Select --\":\n logger.warning(\"BootloaderOptionsWindow().SaveSettings(): Aborting saving settings because bootloader is being replaced, but its replacement is unspecified...\")\n Dlg = wx.MessageDialog(self.Panel, \"If you're going to replace \"+BootloaderInfo[OS][\"Bootloader\"]+\", you must select a new bootloader to replace it with!\", \"WxFixBoot - Warning\", wx.OK | wx.ICON_WARNING)\n Dlg.ShowModal()\n Dlg.Destroy()\n raise RuntimeError\n\n BootloaderInfo[OS][\"Settings\"][\"Reinstall\"] = self.ReinstallBootloaderCheckBox.GetValue()\n BootloaderInfo[OS][\"Settings\"][\"Update\"] = self.UpdateBootloaderCheckBox.GetValue()\n BootloaderInfo[OS][\"Settings\"][\"KeepExistingTimeout\"] = self.KeepBootloaderTimeoutCheckBox.GetValue()\n BootloaderInfo[OS][\"Settings\"][\"NewTimeout\"] = self.BootloaderTimeoutSpinner.GetValue()\n BootloaderInfo[OS][\"Settings\"][\"KeepExistingKernelOptions\"] = self.KeepKernelOptionsCheckBox.GetValue()\n BootloaderInfo[OS][\"Settings\"][\"NewKernelOptions\"] = self.NewKernelOptionsTextCtrl.GetValue()\n BootloaderInfo[OS][\"Settings\"][\"DefaultOS\"] = self.DefaultOSChoice.GetStringSelection()\n BootloaderInfo[OS][\"Settings\"][\"DefaultBootDevice\"] = BootloaderInfo[BootloaderInfo[OS][\"Settings\"][\"DefaultOS\"]][\"DefaultBootDevice\"]\n BootloaderInfo[OS][\"Settings\"][\"InstallNewBootloader\"] = self.InstallNewBootloaderCheckBox.GetValue()\n BootloaderInfo[OS][\"Settings\"][\"NewBootloader\"] = self.NewBootloaderChoice.GetStringSelection()\n BootloaderInfo[OS][\"Settings\"][\"BackupBootloader\"] = self.BackupBootloaderCheckBox.GetValue()\n BootloaderInfo[OS][\"Settings\"][\"BootloaderBackupTarget\"] = self.BackupBootloaderChoice.GetStringSelection()\n BootloaderInfo[OS][\"Settings\"][\"RestoreBootloader\"] = self.RestoreBootloaderCheckBox.GetValue()\n BootloaderInfo[OS][\"Settings\"][\"BootloaderRestoreSource\"] = self.RestoreBootloaderChoice.GetStringSelection()\n\n if BootloaderInfo[OS][\"Settings\"][\"Reinstall\"] or BootloaderInfo[OS][\"Settings\"][\"Update\"] or BootloaderInfo[OS][\"Settings\"][\"InstallNewBootloader\"] or BootloaderInfo[OS][\"Settings\"][\"RestoreBootloader\"]:\n logger.debug(\"BootloaderOptionsWindow().SaveSettings(): \"+OS+\" is being modified...\")\n BootloaderInfo[OS][\"Settings\"][\"ChangeThisOS\"] = True\n\n else:\n logger.debug(\"BootloaderOptionsWindow().SaveSettings(): \"+OS+\" is not being modified...\")\n BootloaderInfo[OS][\"Settings\"][\"ChangeThisOS\"] = False\n\n def SaveGUIState(self, Event=None, OS=None):\n \"\"\"Save all the GUI element's states (enabled/disabled) for this OS\"\"\"\n logger.debug(\"BootloaderOptionsWindow().SaveGUIState(): Saving GUI state for \"+OS+\"...\")\n BootloaderInfo[OS][\"GUIState\"][\"ReinstallCheckBoxState\"] = self.ReinstallBootloaderCheckBox.IsEnabled()\n BootloaderInfo[OS][\"GUIState\"][\"UpdateCheckBoxState\"] = self.UpdateBootloaderCheckBox.IsEnabled()\n BootloaderInfo[OS][\"GUIState\"][\"KeepExistingTimeoutCheckBoxState\"] = self.KeepBootloaderTimeoutCheckBox.IsEnabled()\n BootloaderInfo[OS][\"GUIState\"][\"NewTimeoutSpinnerState\"] = self.BootloaderTimeoutSpinner.IsEnabled()\n BootloaderInfo[OS][\"GUIState\"][\"KeepExistingKernelOptionsCheckBoxState\"] = self.KeepKernelOptionsCheckBox.IsEnabled()\n BootloaderInfo[OS][\"GUIState\"][\"NewKernelOptionsTextCtrlState\"] = self.NewKernelOptionsTextCtrl.IsEnabled()\n BootloaderInfo[OS][\"GUIState\"][\"DefaultOSChoiceState\"] = self.DefaultOSChoice.IsEnabled()\n BootloaderInfo[OS][\"GUIState\"][\"InstallNewBootloaderCheckBoxState\"] = self.InstallNewBootloaderCheckBox.IsEnabled()\n BootloaderInfo[OS][\"GUIState\"][\"NewBootloaderChoiceState\"] = self.NewBootloaderChoice.IsEnabled()\n BootloaderInfo[OS][\"GUIState\"][\"BackupBootloaderCheckBoxState\"] = self.BackupBootloaderCheckBox.IsEnabled()\n BootloaderInfo[OS][\"GUIState\"][\"BackupBootloaderChoiceState\"] = self.BackupBootloaderChoice.IsEnabled()\n BootloaderInfo[OS][\"GUIState\"][\"RestoreBootloaderCheckBoxState\"] = self.RestoreBootloaderCheckBox.IsEnabled()\n BootloaderInfo[OS][\"GUIState\"][\"RestoreBootloaderChoiceState\"] = self.RestoreBootloaderChoice.IsEnabled()\n\n def OnClose(self, Event=None):\n \"\"\"Save settings and GUI state, and then close BootloaderOptionsWindow\"\"\"\n logger.debug(\"BootloaderOptionsWindow().OnClose(): Closing BootloaderOptionsWindow...\")\n self.SaveSettings(OS=self.OSChoice.GetStringSelection())\n self.SaveGUIState(OS=self.OSChoice.GetStringSelection())\n\n #Send a message to MainWindow so it can refresh.\n wx.CallAfter(self.ParentWindow.RefreshMainWindow, \"Closed\")\n\n self.Destroy()\n\n#End New Bootloader Options Window.\n#Begin Progress Window\nclass ProgressWindow(wx.Frame):\n def __init__(self):\n \"\"\"Initialse Progress Window\"\"\"\n wx.Frame.__init__(self, parent=None, title=\"WxFixBoot - Operations Progress\", size=(500,300), style=wx.CAPTION|wx.MINIMIZE|wx.RESIZE_BORDER)\n self.Panel = wx.Panel(self)\n self.SetClientSize(wx.Size(500,300))\n wx.Frame.SetIcon(self, AppIcon)\n Tools.coretools.ParentWindow = self\n\n self.CreateText()\n self.CreateButtons()\n self.CreateProgressBars()\n\n #Create the output box and log.\n self.OutputBox = wx.TextCtrl(self.Panel, -1, \"\", size=(480,240), style=wx.TE_MULTILINE|wx.TE_READONLY|wx.TE_WORDWRAP)\n self.OutputBox.SetBackgroundColour((0,0,0))\n self.OutputBox.SetDefaultStyle(wx.TextAttr(wx.WHITE))\n\n global OutputLog\n OutputLog = []\n\n #Setup the rest of the window.\n self.SetupSizers()\n self.BindEvents()\n\n #Make sure the panel displays properly.\n self.Panel.Layout()\n\n logger.debug(\"ProgressWindow().__init__(): Progress Window Started.\")\n logger.debug(\"ProgressWindow().__init__(): Starting Backend Thread...\")\n\n self.RunningOperations = True\n\n BackendThread(self)\n\n def CreateText(self):\n \"\"\"Create the Text\"\"\"\n self.PerformingOperationsText = wx.StaticText(self.Panel, -1, \"WxFixBoot is performing operations... Please wait.\")\n self.CurrentOperationHeadingText = wx.StaticText(self.Panel, -1, \"Current Operation:\")\n self.CurrentOperationText = wx.StaticText(self.Panel, -1, \"Initializating...\")\n self.CurrentOperationProgressText = wx.StaticText(self.Panel, -1, \"Current Operation Progress:\")\n self.OverallProgressText = wx.StaticText(self.Panel, -1, \"Overall Progress:\")\n\n def CreateButtons(self):\n \"\"\"Create buttons.\"\"\"\n self.ShowOutputButton = wx.ToggleButton(self.Panel, -1, \"Show Terminal Output\")\n self.RestartButton = wx.Button(self.Panel, -1, \"Restart WxFixBoot\")\n self.ExitButton = wx.Button(self.Panel, -1, \"Exit\")\n self.RestartButton.Disable()\n self.ExitButton.Disable()\n\n def CreateProgressBars(self):\n \"\"\"Create both progres bars\"\"\"\n #Create the progress bar for the current operation.\n self.CurrentOperationProgressBar = wx.Gauge(self.Panel, -1, 100)\n self.CurrentOperationProgressBar.SetBezelFace(3)\n self.CurrentOperationProgressBar.SetShadowWidth(3)\n self.CurrentOperationProgressBar.SetValue(0)\n self.CurrentOperationProgressBar.Show()\n\n #Create the progress bar for overall progress.\n self.OverallProgressBar = wx.Gauge(self.Panel, -1, 100)\n self.OverallProgressBar.SetBezelFace(3)\n self.OverallProgressBar.SetShadowWidth(3)\n self.OverallProgressBar.SetValue(0)\n self.OverallProgressBar.Show()\n\n def SetupSizers(self):\n \"\"\"Setup sizers for Progress Window\"\"\"\n #Create the Main Sizer.\n self.MainSizer = wx.BoxSizer(wx.VERTICAL)\n\n #Create the first button sizer.\n ButtonSizer1 = wx.BoxSizer(wx.HORIZONTAL)\n\n #Create the second button sizer.\n ButtonSizer2 = wx.BoxSizer(wx.HORIZONTAL)\n\n #Add items to the first button sizer.\n ButtonSizer1.Add(self.RestartButton, 1, wx.RIGHT, 5)\n ButtonSizer1.Add((5,5), 1, wx.LEFT|wx.RIGHT, 5)\n ButtonSizer1.Add(self.ShowOutputButton, 1, wx.LEFT|wx.RIGHT, 5)\n\n #Add items to the second button sizer.\n ButtonSizer2.Add((5,5), 1, wx.RIGHT, 5)\n ButtonSizer2.Add(self.ExitButton, 1, wx.LEFT|wx.RIGHT, 5)\n ButtonSizer2.Add((5,5), 1, wx.LEFT|wx.RIGHT, 5)\n\n #Add items to the main sizer.\n self.MainSizer.Add(self.PerformingOperationsText, 0, wx.ALL|wx.ALIGN_CENTER, 10)\n self.MainSizer.Add(self.CurrentOperationHeadingText, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.ALIGN_CENTER, 10)\n self.MainSizer.Add(self.CurrentOperationText, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.ALIGN_CENTER, 10)\n self.MainSizer.Add(self.CurrentOperationProgressText, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.ALIGN_CENTER, 10)\n self.MainSizer.Add(self.CurrentOperationProgressBar, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.MainSizer.Add(self.OverallProgressText, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.ALIGN_CENTER, 10)\n self.MainSizer.Add(self.OverallProgressBar, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.MainSizer.Add(ButtonSizer1, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.MainSizer.Add(self.OutputBox, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.MainSizer.Add(ButtonSizer2, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n\n self.ShowOutput()\n\n #Get the sizer set up for the frame.\n self.Panel.SetSizer(self.MainSizer)\n self.MainSizer.SetMinSize(wx.Size(500,300))\n self.MainSizer.SetSizeHints(self)\n\n def BindEvents(self):\n \"\"\"Bind events for Progress Window\"\"\"\n self.Bind(wx.EVT_TOGGLEBUTTON, self.ShowOutput, self.ShowOutputButton)\n self.Bind(wx.EVT_BUTTON, self.RestartWxFixBoot, self.RestartButton)\n self.Bind(wx.EVT_QUERY_END_SESSION, self.SessionEnding)\n self.Bind(wx.EVT_BUTTON, self.OnExit, self.ExitButton)\n self.Bind(wx.EVT_CLOSE, self.OnExit)\n\n #Prevent focus on Output Box.\n self.OutputBox.Bind(wx.EVT_SET_FOCUS, self.FocusOnOutputButton)\n\n def FocusOnOutputButton(self, Event=None):\n \"\"\"Focus on the show output button instead of the TextCtrl, and reset the insertion point back after 30 milliseconds, preventing the user from changing the insertion point and messing the formatting up.\"\"\"\n #Just a slightly hacky way of trying to make sure the user can't change the insertion point! Works unless you start doing silly stuff like tapping on the output box constantly :)\n self.ShowOutputButton.SetFocus()\n InsertionPoint = self.OutputBox.GetInsertionPoint()\n wx.CallLater(30, self.OutputBox.SetInsertionPoint, InsertionPoint)\n\n def ShowOutput(self, Event=None):\n \"\"\"Show and Hide the output box in ProgressWindow()\"\"\"\n logger.debug(\"ProgressWindow().ShowOutput() was Toggled to position: \"+unicode(self.ShowOutputButton.GetValue())+\", where True = Depressed and vice versa.\")\n if self.ShowOutputButton.GetValue():\n #Remove the empty space.\n self.MainSizer.Detach(8)\n\n #Show the output box.\n self.MainSizer.Insert(8, self.OutputBox, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)\n self.OutputBox.Show()\n\n else:\n #Hide the output box.\n self.MainSizer.Detach(self.OutputBox)\n self.OutputBox.Hide()\n\n #Insert some empty space.\n self.MainSizer.Insert(8, (1,1), 1, wx.EXPAND)\n\n #Call Layout() on self.Panel() to ensure it displays properly.\n self.Panel.Layout()\n self.MainSizer.SetSizeHints(self)\n\n def CarriageReturn(self):\n \"\"\"Handles carriage returns in output\"\"\"\n #Go back until the last newline character, and overwrite anything in the way on the next write.\n #Get the current insertion point.\n CurrentInsertionPoint = self.OutputBox.GetInsertionPoint()\n\n #Get the text up to the current insertion point.\n Text = self.OutputBox.GetRange(0, CurrentInsertionPoint)\n\n #Find the last newline char in the text.\n NewlineNos = []\n Counter = 0\n for Char in Text:\n if Char == \"\\n\":\n NewlineNos.append(Counter)\n\n Counter += 1\n\n if NewlineNos != []:\n LastNewline = NewlineNos[-1]\n\n else:\n #Hacky bit to make the new insertion point 0 :)\n LastNewline = -1\n\n #Set the insertion point to just after that newline, unless we're already there, and in that case set the insertion point just after the previous newline.\n NewInsertionPoint = LastNewline + 1\n\n self.OutputBox.SetInsertionPoint(NewInsertionPoint)\n\n def BackSpace(self):\n \"\"\"Handles backspaces in output\"\"\"\n #Move the insertion point 1 char to the left.\n self.OutputBox.SetInsertionPoint(self.OutputBox.GetInsertionPoint()-1)\n\n def UpdateOutputBox(self, Line, ShowOutput=True):\n \"\"\"Update the output box, and add lines to the list\"\"\"\n #Add the line to the output log.\n global OutputLog\n OutputLog.append(Line)\n\n if ShowOutput or Settings[\"FullVerbosity\"]:\n TempLine = \"\"\n\n for Char in Line:\n if Char != \"\\r\" and Char != \"\\x08\":\n TempLine += Char\n\n if Char == \"\\n\":\n self.AddLineToOutputBox(TempLine, Type=\"None\")\n TempLine = \"\"\n\n else:\n if Char == \"\\r\":\n Type = \"CR\"\n\n elif Char == \"\\x08\":\n Type = \"BKSP\"\n\n self.AddLineToOutputBox(TempLine, Type)\n TempLine = \"\"\n\n def AddLineToOutputBox(self, Line, Type):\n InsertionPoint = self.OutputBox.GetInsertionPoint()\n\n self.OutputBox.Replace(InsertionPoint, InsertionPoint+len(Line), Line)\n\n if Type == \"CR\":\n self.CarriageReturn()\n\n elif Type == \"BKSP\":\n self.BackSpace()\n\n def UpdateCurrentProgress(self,msg):\n \"\"\"Update the progress of the current progress progress bar\"\"\"\n #Called at various points during operation code.\n self.CurrentOperationProgressBar.SetValue(int(msg))\n\n if self.CurrentOperationProgressBar.GetValue() == 100:\n self.UpdateTotalProgress()\n\n #Stop this resetting when all operations are complete.\n if self.OverallProgressBar.GetValue() != 100:\n self.CurrentOperationProgressBar.SetValue(0)\n\n def UpdateTotalProgress(self):\n \"\"\"Update the progress of the overall progress progress bar\"\"\"\n #This is called when self.CurrentOperationProgressBar reaches 100 (aka full).\n if self.OverallProgressBar.GetValue() < 100:\n self.OverallProgressBar.SetValue(self.OverallProgressBar.GetValue()+(100//NumberOfOperations))\n\n def UpdateCurrentOpText(self, Message):\n \"\"\"Keep the current operations status text up to date.\"\"\"\n self.CurrentOperationText.SetLabel(Message)\n self.Panel.Layout()\n\n def BackendThreadFinished(self):\n \"\"\"Called when the BackendThread is finished, enables self.RestartButton and self.ExitButton\"\"\"\n self.RunningOperations = False\n self.RestartButton.Enable()\n self.ExitButton.Enable()\n\n def RestartWxFixBoot(self, Event=None):\n \"\"\"Restart WxFixBoot\"\"\"\n logger.debug(\"ProgressWindow().RestartWxFixBoot(): Restarting WxFixBoot...\")\n logger.debug(\"ProgressWindow().RestartWxFixBoot(): Checking no filesystems are mounted in the temporary directory, and unmounting them if they are...\")\n\n if os.path.exists(\"/tmp/wxfixboot/mountpoints/dev\"):\n for Dir in os.listdir(\"/tmp/wxfixboot/mountpoints/dev\"):\n #Call CoreTools.Unmount() on each directory to make sure that nothing is mounted there after this point.\n if CoreTools.Unmount(\"/tmp/wxfixboot/mountpoints/dev/\"+Dir) != 0:\n #If we errored try removing chroot and trying again.\n logger.warning(\"ProgressWindow().RestartWxFixBoot(): Failed to unmount /tmp/wxfixboot/mountpoints/dev/\"+Dir+\"! Trying to remove chroot first then trying again...\")\n CoreTools.TearDownChoot(\"/tmp/wxfixboot/mountpoints/dev/\"+Dir)\n\n if CoreTools.Unmount(\"/tmp/wxfixboot/mountpoints/dev/\"+Dir) != 0:\n logger.error(\"ProgressWindow().RestartWxFixBoot(): Couldn't unmount /tmp/wxfixboot/mountpoints/dev/\"+Dir+\"! Giving up, warning user, and aborting restart...\")\n Dlg = wx.MessageDialog(self.Panel, \"Couldn't restart WxFixBoot because there are mounted filesystems in the temporary directory! Please try restarting your system and then try again.\", \"WxFixBoot - Error!\", wx.OK | wx,ICON_ERROR)\n Dlg.ShowModal()\n Dlg.Destroy()\n return False\n\n self.Hide()\n\n global Restarting\n Restarting = True\n\n #Make sure any pending output box events are processed now, to avoid errors later.\n wx.Yield()\n\n #Destroy ProgressWindow. \n self.Destroy()\n\n InitialWindow().Show()\n\n def SessionEnding(self, Event):\n \"\"\"Attempt to veto e.g. a shutdown/logout event if recovering data.\"\"\"\n #Check if we can veto the shutdown.\n logger.warning(\"ProgressWindow().SessionEnding(): Attempting to veto system shutdown / logoff...\")\n\n if Event.CanVeto() and self.RunningOperations:\n #Veto the shutdown and warn the user.\n Event.Veto(True)\n logger.info(\"ProgressWindow().SessionEnding(): Vetoed system shutdown / logoff...\")\n dlg = wx.MessageDialog(self.Panel, \"You can't shutdown or logoff while recovering data!\", \"WxFixBoot - Error!\", wx.OK | wx.ICON_ERROR)\n dlg.ShowModal()\n dlg.Destroy()\n\n else:\n #Set SessionEnding to True, call OnExit.\n logger.critical(\"ProgressWindow().SessionEnding(): Cannot veto system shutdown / logoff! Cleaning up...\")\n global SessionEnding\n SessionEnding = True\n self.OnExit()\n\n def OnExit(self, Event=None):\n \"\"\"Exits the programs, and sorts out log file saving/deleting stuff\"\"\"\n #Check if the session is ending.\n if SessionEnding:\n #Delete the log file and exit ASAP.\n logging.shutdown()\n os.remove(\"/tmp/wxfixboot.log\")\n self.Destroy()\n\n dlg = wx.MessageDialog(self.Panel, 'Are you sure you want to exit?', 'WxFixBoot - Question!', wx.YES_NO | wx.ICON_QUESTION)\n Answer = dlg.ShowModal()\n dlg.Destroy()\n\n if Answer == wx.ID_YES:\n #Run the exit sequence\n logger.info(\"ProgressWindow().OnExit(): Exiting...\")\n\n #Shutdown the logger.\n logging.shutdown()\n\n #Prompt user to save the log file.\n dlg = wx.MessageDialog(self.Panel, \"Do you want to keep WxFixBoot's log file? For privacy reasons, WxFixBoot will delete its log file when closing. If you want to save it, which is helpful for debugging if something went wrong, click yes, and otherwise click no.\", \"WxFixBoot - Question\", style=wx.YES_NO | wx.ICON_QUESTION, pos=wx.DefaultPosition)\n Answer = dlg.ShowModal()\n dlg.Destroy()\n\n if Answer == wx.ID_YES:\n #Ask the user where to save it.\n dlg = wx.FileDialog(self.Panel, \"Save log file to...\", defaultDir=\"/home\", wildcard=\"Log Files (*.log)|*.log\" , style=wx.SAVE|wx.OVERWRITE_PROMPT)\n Answer = dlg.ShowModal()\n File = dlg.GetPath()\n dlg.Destroy()\n\n if Answer == wx.ID_OK:\n #Copy it to the specified path, using a one-liner, and don't bother handling any errors, because this is run as root.\n CoreTools.StartProcess(\"cp /tmp/wxfixboot.log \"+File)\n\n dlg = wx.MessageDialog(self.Panel, 'Done! WxFixBoot will now exit.', 'WxFixBoot - Information', wx.OK | wx.ICON_INFORMATION)\n dlg.ShowModal()\n dlg.Destroy()\n\n else:\n dlg = wx.MessageDialog(self.Panel, 'Okay, WxFixBoot will now exit without saving the log file.', 'WxFixBoot - Information', wx.OK | wx.ICON_INFORMATION)\n dlg.ShowModal()\n dlg.Destroy()\n\n else:\n dlg = wx.MessageDialog(self.Panel, 'Okay, WxFixBoot will now exit without saving the log file.', 'WxFixBoot - Information', wx.OK | wx.ICON_INFORMATION)\n dlg.ShowModal()\n dlg.Destroy()\n\n #Delete the log file, and don't bother handling any errors, because this is run as root.\n os.remove('/tmp/wxfixboot.log')\n\n self.Destroy()\n\n#End Progress Window\n#Begin Backend Thread\nclass BackendThread(threading.Thread):\n def __init__(self, ParentWindow):\n \"\"\"Initialize BackendThread\"\"\"\n #Set up the backend tools.\n Tools.dialogtools.ParentWindow = ParentWindow\n Tools.BackendTools.helpers.ParentWindow = ParentWindow\n Tools.BackendTools.essentials.ParentWindow = ParentWindow\n Tools.BackendTools.main.ParentWindow = ParentWindow\n\n #Start the main part of this thread.\n threading.Thread.__init__(self)\n self.ParentWindow = ParentWindow\n self.start()\n\n def run(self):\n \"\"\"Do setup, and call self.StartOperations()\"\"\"\n #Log the BackendThread start event (in debug mode).\n logger.debug(\"BackendThread().run(): Started. Calling self.StartOperations()...\")\n\n #Handle any unexpected errors.\n try:\n self.StartOperations()\n\n except:\n logger.critical(\"Unexpected error \\n\\n\"+unicode(traceback.format_exc())+\"\\n\\n while running operations. Warning user and exiting.\")\n CoreTools.EmergencyExit(\"There was an unexpected error:\\n\\n\"+unicode(traceback.format_exc())+\"\\n\\nWhile running operations!\")\n\n def StartOperations(self):\n \"\"\"Start doing operations.\"\"\"\n logger.debug(\"BackendThread().StartOperations(): Running operations...\")\n\n DialogTools.ShowMsgDlg(Kind=\"info\", Message=\"Please stay within sight of the system, as operations are not fully automated and you may be asked the occasional queston, or be shown warnings. You may see the occasional file manager dialog pop up as well, so feel free to either close them or ignore them.\")\n\n #Make dictionaries accessible.\n Tools.BackendTools.essentials.SystemInfo = SystemInfo\n Tools.BackendTools.essentials.DiskInfo = DiskInfo\n\n Tools.BackendTools.helpers.BootloaderInfo = BootloaderInfo\n Tools.BackendTools.helpers.DiskInfo = DiskInfo\n Tools.BackendTools.helpers.OSInfo = OSInfo\n Tools.BackendTools.helpers.SystemInfo = SystemInfo\n Tools.BackendTools.helpers.Operations = Operations #Also make the list of operations avalable so bootloader operations can be disabled if necessary.\n\n Tools.BackendTools.main.OSInfo = OSInfo\n Tools.BackendTools.main.DiskInfo = DiskInfo\n Tools.BackendTools.main.SystemInfo = SystemInfo\n Tools.BackendTools.main.BootloaderInfo = BootloaderInfo\n\n Tools.BackendTools.BootloaderTools.setconfigtools.BootloaderInfo = BootloaderInfo\n Tools.BackendTools.BootloaderTools.setconfigtools.DiskInfo = DiskInfo\n Tools.BackendTools.BootloaderTools.setconfigtools.OSInfo = OSInfo\n\n #Run functions to do operations.\n for function in Operations:\n #Run the function.\n if type(function) != type(()):\n function()\n\n else:\n function[0](function[1])\n\n if Settings[\"MakeSystemSummary\"]:\n self.GenerateSystemReport()\n\n if SystemInfo[\"DisableBootloaderOperations\"]:\n DialogTools.ShowMsgDlg(Kind=\"warning\", Message=\"Bootloader Operations were disabled. This is because \"+SystemInfo[\"DisableBootloaderOperationsBecause\"]+\". Click okay to continue.\")\n\n logger.info(\"BackendThread().StartOperations(): Finished Operation Running Code.\")\n\n wx.CallAfter(self.ParentWindow.UpdateCurrentOpText, Message=\"Finished!\")\n\n #Change the dialog's message if needed.\n DialogMessage = \"Your operations are all done! Thank you for using WxFixBoot.\"\n\n for Function in Operations:\n if type(Function) == type(()):\n if MainBackendTools.ManageBootloader in Function:\n DialogMessage += \" You performed bootloader operations on at least one OS, so please now reboot your system.\"\n break\n\n DialogTools.ShowMsgDlg(Kind=\"info\", Message=DialogMessage)\n\n wx.CallAfter(self.ParentWindow.BackendThreadFinished)\n\n def GenerateSystemReport(self):\n \"\"\"Create a system report, containing various information helpful for debugging and fixing problems. It's pretty much like a bootinfo summary.\"\"\"\n DialogTools.ShowMsgDlg(Kind=\"info\", Message=\"WxFixBoot will now create your system report. Click okay to continue.\")\n\n #Ask the user where to save the file.\n ReportFile = DialogTools.ShowSaveFileDlg(Title=\"WxFixBoot - Select System Report File\", Wildcard=\"Text Files|*.txt|Log Files|*.log|All Files/Devices (*)|*\")\n\n #Write everything directly to the file.\n ReportList = open(ReportFile, 'w')\n ReportList.write(\"This system report was created with WxFixBoot version \"+Version+\". It can be used to diagnose problems with your system, and can help if you wish to make a support request.\\n\\n\")\n\n #Do Firmware Information.\n ReportList.write(\"\\n##########Firmware Information##########\\n\")\n ReportList.write(\"Detected firmware type: \"+SystemInfo[\"FirmwareType\"]+\"\\n\")\n\n #Do Disk Information\n ReportList.write(\"\\n##########Disk Information##########\\n\")\n DiskList = DiskInfo.keys()\n DiskList.sort()\n\n ReportList.write(\"All Disks: \"+', '.join(DiskList)+\"\\n\\n\")\n ReportList.write(\"Per Disk Info:\\n\")\n\n for Disk in DiskList:\n ReportList.write(\"\\tName: \"+Disk+\"\\n\")\n ReportList.write(\"\\t\\tType: \"+DiskInfo[Disk][\"Type\"]+\"\\n\")\n ReportList.write(\"\\t\\tHost Device: \"+DiskInfo[Disk][\"HostDevice\"]+\"\\n\")\n ReportList.write(\"\\t\\tPartitions: \"+', '.join(DiskInfo[Disk][\"Partitions\"])+\"\\n\")\n ReportList.write(\"\\t\\tVendor: \"+DiskInfo[Disk][\"Vendor\"]+\"\\n\")\n ReportList.write(\"\\t\\tProduct: \"+DiskInfo[Disk][\"Product\"]+\"\\n\")\n ReportList.write(\"\\t\\tRaw Capacity: \"+DiskInfo[Disk][\"RawCapacity\"]+\"\\n\")\n ReportList.write(\"\\t\\tHuman-readable Capacity: \"+DiskInfo[Disk][\"Capacity\"]+\"\\n\")\n ReportList.write(\"\\t\\tDescription: \"+DiskInfo[Disk][\"Description\"]+\"\\n\")\n ReportList.write(\"\\t\\tFlags: \"+', '.join(DiskInfo[Disk][\"Flags\"])+\"\\n\")\n ReportList.write(\"\\t\\tPartitioning: \"+DiskInfo[Disk][\"Partitioning\"]+\"\\n\")\n ReportList.write(\"\\t\\tFilesystem: \"+DiskInfo[Disk][\"FileSystem\"]+\"\\n\")\n ReportList.write(\"\\t\\tUUID: \"+DiskInfo[Disk][\"UUID\"]+\"\\n\")\n ReportList.write(\"\\t\\tID: \"+DiskInfo[Disk][\"ID\"]+\"\\n\")\n ReportList.write(\"\\t\\tBoot Record Strings: \"+', '.join(DiskInfo[Disk][\"BootRecordStrings\"])+\"\\n\\n\")\n\n #Do OS Information.\n ReportList.write(\"\\n##########OS Information##########\\n\")\n OSList = OSInfo.keys()\n OSList.sort()\n\n ReportList.write(\"Detected Operating Systems: \"+', '.join(OSInfo.keys())+\"\\n\")\n ReportList.write(\"Modifyable Operating Systems: \"+', '.join(SystemInfo[\"ModifyableOSs\"])+\"\\n\")\n ReportList.write(\"Currently running OS architecture: \"+SystemInfo[\"CurrentOSArch\"]+\"\\n\")\n ReportList.write(\"Currently running OS is on Live Disk: \"+unicode(SystemInfo[\"IsLiveDisk\"])+\"\\n\")\n\n if SystemInfo[\"IsLiveDisk\"]:\n ReportList.write(\"Currently running OS is Parted Magic: \"+unicode(SystemInfo[\"OnPartedMagic\"])+\"\\n\")\n\n ReportList.write(\"Per OS Info:\\n\")\n\n for OS in OSList:\n ReportList.write(\"\\tOS Name: \"+OS+\"\\n\")\n ReportList.write(\"\\t\\tIs Current OS: \"+unicode(OSInfo[OS][\"IsCurrentOS\"])+\"\\n\")\n ReportList.write(\"\\t\\tArchitecture: \"+OSInfo[OS][\"Arch\"]+\"\\n\")\n ReportList.write(\"\\t\\tInstalled On: \"+OSInfo[OS][\"Partition\"]+\"\\n\")\n ReportList.write(\"\\t\\tPackage Manager: \"+OSInfo[OS][\"PackageManager\"]+\"\\n\")\n ReportList.write(\"\\t\\tBoot Partition: \"+OSInfo[OS][\"BootPartition\"]+\"\\n\")\n ReportList.write(\"\\t\\tEFI Partition: \"+OSInfo[OS][\"EFIPartition\"]+\"\\n\")\n ReportList.write(\"\\t\\tContents of /etc/fstab:\\n\\t\\t\\t\"+'\\n\\t\\t\\t'.join(OSInfo[OS][\"RawFSTabInfo\"])+\"\\n\\n\")\n\n #Do Bootloader information\n ReportList.write(\"\\n##########Bootloader Information##########\\n\")\n\n ReportList.write(\"Disabled Bootloader Operations: \"+unicode(SystemInfo[\"DisableBootloaderOperations\"])+\"\\n\")\n\n if SystemInfo[\"DisableBootloaderOperations\"]:\n ReportList.write(\"Bootloader operations have been disabled. The operations that were going to be done are still detailed below,\\n\")\n ReportList.write(\"but they weren't actually done.\\n\")\n ReportList.write(\"Bootloader Operations were disabled because: \"+SystemInfo[\"DisableBootloaderOperationsBecause\"]+\"\\n\\n\")\n\n BootloaderOSs = BootloaderInfo.keys()\n BootloaderOSs.sort()\n\n for OS in BootloaderOSs:\n ReportList.write(\"\\tControlling OS: \"+OS+\"\\n\")\n ReportList.write(\"\\tBootloader (at time of startup): \"+BootloaderInfo[OS][\"Bootloader\"]+\"\\n\")\n ReportList.write(\"\\tBootloaders that can be installed: \"+', '.join(BootloaderInfo[OS][\"AvailableBootloaders\"])+\"\\n\")\n ReportList.write(\"\\t\\tBootloader Timeout: \"+unicode(BootloaderInfo[OS][\"Timeout\"])+\"\\n\")\n ReportList.write(\"\\t\\tGlobal Kernel Options: \"+BootloaderInfo[OS][\"GlobalKernelOptions\"]+\"\\n\")\n ReportList.write(\"\\t\\tBootloader-Specific Default OS: \"+BootloaderInfo[OS][\"BLSpecificDefaultOS\"]+\"\\n\")\n ReportList.write(\"\\t\\tDefault OS: \"+BootloaderInfo[OS][\"DefaultOS\"]+\"\\n\")\n ReportList.write(\"\\t\\tInstalled on: \"+BootloaderInfo[OS][\"BootDisk\"]+\"\\n\")\n ReportList.write(\"\\t\\tCan be modified: \"+unicode(BootloaderInfo[OS][\"IsModifyable\"])+\"\\n\")\n ReportList.write(\"\\t\\tReason for modifyability: \"+BootloaderInfo[OS][\"Comments\"]+\"\\n\") \n ReportList.write(\"\\t\\tBootloader was modified: \"+unicode(BootloaderInfo[OS][\"Settings\"][\"ChangeThisOS\"])+\"\\n\\n\")\n\n if BootloaderInfo[OS][\"Settings\"][\"ChangeThisOS\"]:\n ReportList.write(\"\\t\\t\\tBootloader was reinstalled: \"+unicode(BootloaderInfo[OS][\"Settings\"][\"Reinstall\"])+\"\\n\")\n ReportList.write(\"\\t\\t\\tBootloader was updated: \"+unicode(BootloaderInfo[OS][\"Settings\"][\"Update\"])+\"\\n\")\n ReportList.write(\"\\t\\t\\tBootloader was replaced with another bootloader: \"+unicode(BootloaderInfo[OS][\"Settings\"][\"InstallNewBootloader\"])+\"\\n\\n\")\n\n if BootloaderInfo[OS][\"Settings\"][\"Reinstall\"] or BootloaderInfo[OS][\"Settings\"][\"Update\"] or BootloaderInfo[OS][\"Settings\"][\"InstallNewBootloader\"]:\n ReportList.write(\"\\t\\t\\tNew Bootloader: \"+BootloaderInfo[OS][\"Settings\"][\"NewBootloader\"]+\"\\n\")\n ReportList.write(\"\\t\\t\\tKept Existing Bootloader Timeout: \"+unicode(BootloaderInfo[OS][\"Settings\"][\"KeepExistingTimeout\"])+\"\\n\")\n\n if BootloaderInfo[OS][\"Settings\"][\"KeepExistingTimeout\"] == False:\n ReportList.write(\"\\t\\t\\tNew Bootloader Timeout: \"+unicode(BootloaderInfo[OS][\"Settings\"][\"NewTimeout\"])+\"\\n\")\n\n ReportList.write(\"\\t\\t\\tKept Existing Kernel Options: \"+unicode(BootloaderInfo[OS][\"Settings\"][\"KeepExistingKernelOptions\"])+\"\\n\")\n\n if BootloaderInfo[OS][\"Settings\"][\"KeepExistingKernelOptions\"] == False:\n ReportList.write(\"\\t\\t\\tNew Kernel Options: \"+BootloaderInfo[OS][\"Settings\"][\"NewKernelOptions\"]+\"\\n\")\n\n ReportList.write(\"\\t\\t\\tNew Default OS: \"+BootloaderInfo[OS][\"Settings\"][\"DefaultOS\"]+\"\\n\\n\")\n\n\n #Do WxFixBoot's settings.\n ReportList.write(\"\\n##########Other WxFixBoot Settings##########\\n\")\n ReportList.write(\"Do Quick Filesystem Check: \"+unicode(Settings[\"QuickFSCheck\"])+\"\\n\")\n ReportList.write(\"Do Bad Sector Check: \"+unicode(Settings[\"BadSectorCheck\"])+\"\\n\")\n ReportList.write(\"Show Diagnostic Terminal Output: \"+unicode(Settings[\"FullVerbosity\"])+\"\\n\")\n ReportList.write(\"Save System Report To File: \"+unicode(Settings[\"MakeSystemSummary\"])+\"\\n\")\n\n if Settings[\"MakeSystemSummary\"]:\n ReportList.write(\"\\n\\tSave Terminal Output in Report: \"+unicode(Settings[\"SaveOutput\"])+\"\\n\")\n ReportList.write(\"\\tSystem Report Target File: \"+ReportFile+\"\\n\\n\")\n\n ReportList.write(\"Number of operations to do: \"+unicode(NumberOfOperations)+\"\\n\")\n\n #Save terminal output.\n if Settings[\"SaveOutput\"]:\n ReportList.write(\"\\n##########Terminal Output##########\\n\")\n\n for Line in OutputLog:\n ReportList.write(Line)\n\n ReportList.write(\"\\n\")\n\n #Save Log File.\n ReportList.write(\"\\n##########WxFixBoot's Log File##########\\n\")\n\n logfile = open(\"/tmp/wxfixboot.log\", \"r\")\n\n for line in logfile:\n ReportList.write(line)\n\n logfile.close()\n\n ReportList.write(\"\\n\\n\")\n ReportList.write(\"\\n##########End Of System Report##########\\n\")\n ReportList.close()\n \n#End Backend Thread\napp = WxFixBoot(False)\napp.MainLoop()\n","repo_name":"timofonic-data-recovery/wxfixboot","sub_path":"WxFixBoot.py","file_name":"WxFixBoot.py","file_ext":"py","file_size_in_byte":129142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"11851527541","text":"if __name__ == '__main__':\n import sys\n import os\n pkg_dir = os.path.split(os.path.abspath(__file__))[0]\n parent_dir, pkg_name = os.path.split(pkg_dir)\n is_pygame_pkg = (pkg_name == 'tests' and\n os.path.split(parent_dir)[1] == 'pygame')\n if not is_pygame_pkg:\n sys.path.insert(0, parent_dir)\nelse:\n is_pygame_pkg = __name__.startswith('pygame.tests.')\n\nif is_pygame_pkg:\n from pygame.tests import test_utils\n from pygame.tests.test_utils import test_not_implemented, unittest\nelse:\n from test import test_utils\n from test.test_utils import test_not_implemented, unittest\nimport pygame\nimport pygame.transform\nfrom pygame.locals import *\n\nimport platform\n\ndef show_image(s, images = []):\n #pygame.display.init()\n size = s.get_rect()[2:]\n screen = pygame.display.set_mode(size)\n screen.blit(s, (0,0))\n pygame.display.flip()\n pygame.event.pump()\n going = True\n idx = 0\n while going:\n events = pygame.event.get()\n for e in events:\n if e.type == QUIT:\n going = False\n if e.type == KEYDOWN:\n if e.key in [K_s, K_a]:\n if e.key == K_s: idx += 1\n if e.key == K_a: idx -= 1\n s = images[idx]\n screen.blit(s, (0,0))\n pygame.display.flip()\n pygame.event.pump()\n else:\n going = False\n pygame.display.quit()\n pygame.display.init()\n\ndef threshold(return_surf, surf, color, threshold = (0,0,0), diff_color = (0,0,0), change_return = True ):\n \"\"\" given the color it makes return_surf only have areas with the given colour.\n \"\"\"\n\n width, height =surf.get_width(), surf.get_height()\n\n if change_return:\n return_surf.fill(diff_color)\n\n try:\n r, g, b = color\n except ValueError:\n r, g, b, a = color\n\n\n try:\n tr, tg, tb = color\n except ValueError:\n tr, tg, tb, ta = color\n\n\n\n similar = 0\n for y in xrange(height):\n for x in xrange(width):\n c1 = surf.get_at((x,y))\n\n if ( (abs(c1[0] - r) < tr) &\n (abs(c1[1] - g) < tg) &\n (abs(c1[2] - b) < tb) ):\n # this pixel is within the threshold.\n if change_return:\n return_surf.set_at((x,y), c1)\n similar += 1\n #else:\n # print c1, c2\n\n\n return similar\n\n\nclass TransformModuleTest( unittest.TestCase ):\n #class TransformModuleTest( object ):\n\n #def assertEqual(self, x,x2):\n # print x,x2\n\n def test_scale__alpha( self ):\n \"\"\" see if set_alpha information is kept.\n \"\"\"\n\n s = pygame.Surface((32,32))\n s.set_alpha(55)\n self.assertEqual(s.get_alpha(),55)\n\n s = pygame.Surface((32,32))\n s.set_alpha(55)\n s2 = pygame.transform.scale(s, (64,64))\n s3 = s.copy()\n self.assertEqual(s.get_alpha(),s3.get_alpha())\n self.assertEqual(s.get_alpha(),s2.get_alpha())\n\n\n def test_scale__destination( self ):\n \"\"\" see if the destination surface can be passed in to use.\n \"\"\"\n\n s = pygame.Surface((32,32))\n s2 = pygame.transform.scale(s, (64,64))\n s3 = s2.copy()\n\n s3 = pygame.transform.scale(s, (64,64), s3)\n pygame.transform.scale(s, (64,64), s2)\n\n # the wrong size surface is past in. Should raise an error.\n self.assertRaises(ValueError, pygame.transform.scale, s, (33,64), s3)\n\n if 1:\n s = pygame.Surface((32,32))\n s2 = pygame.transform.smoothscale(s, (64,64))\n s3 = s2.copy()\n\n s3 = pygame.transform.smoothscale(s, (64,64), s3)\n pygame.transform.smoothscale(s, (64,64), s2)\n\n # the wrong size surface is past in. Should raise an error.\n self.assertRaises(ValueError, pygame.transform.smoothscale, s, (33,64), s3)\n\n\n def test_threshold__honors_third_surface(self):\n # __doc__ for threshold as of Tue 07/15/2008\n\n # pygame.transform.threshold(DestSurface, Surface, color, threshold =\n # (0,0,0,0), diff_color = (0,0,0,0), change_return = True, Surface =\n # None): return num_threshold_pixels\n\n # When given the optional third\n # surface, it would use the colors in that rather than the \"color\"\n # specified in the function to check against.\n\n # New in pygame 1.8\n\n ################################################################\n # Sizes\n (w, h) = size = (32, 32)\n\n # the original_color is within the threshold of the threshold_color\n threshold = (20, 20, 20, 20)\n\n original_color = (25,25,25,25)\n threshold_color = (10, 10, 10, 10)\n\n # Surfaces\n original_surface = pygame.Surface(size, pygame.SRCALPHA, 32)\n dest_surface = pygame.Surface(size, pygame.SRCALPHA, 32)\n\n # Third surface is used in lieu of 3rd position arg color\n third_surface = pygame.Surface(size, pygame.SRCALPHA, 32)\n\n # Color filling\n original_surface.fill(original_color)\n third_surface.fill(threshold_color)\n\n ################################################################\n # All pixels for color should be within threshold\n #\n pixels_within_threshold = pygame.transform.threshold (\n dest_surface, original_surface, threshold_color,\n threshold,\n 0, # diff_color\n 0 # change_return\n )\n\n self.assertEqual(w*h, pixels_within_threshold)\n\n ################################################################\n # This should respect third_surface colors in place of 3rd arg\n # color Should be the same as: surface.fill(threshold_color)\n # all within threshold\n\n pixels_within_threshold = pygame.transform.threshold (\n dest_surface,\n original_surface,\n 0, # color (would fail if honored)\n threshold,\n 0, # diff_color\n 0, # change_return\n third_surface,\n )\n self.assertEqual(w*h, pixels_within_threshold)\n\n\n ################################################################\n # Change dest_surface on return (not expected)\n\n change_color = (255, 10, 10, 10)\n\n pixels_within_threshold = pygame.transform.threshold (\n dest_surface,\n original_surface,\n 0, # color\n threshold,\n change_color, # diff_color\n 1, # change_return\n third_surface,\n )\n\n # Return, of pixels within threshold is correct\n self.assertEqual(w*h, pixels_within_threshold)\n\n # Size of dest surface is correct\n dest_rect = dest_surface.get_rect()\n dest_size = dest_rect.size\n self.assertEqual(size, dest_size)\n\n # The color is not the change_color specified for every pixel As all\n # pixels are within threshold\n\n for pt in test_utils.rect_area_pts(dest_rect):\n self.assert_(dest_surface.get_at(pt) != change_color)\n\n ################################################################\n # Lowering the threshold, expecting changed surface\n\n pixels_within_threshold = pygame.transform.threshold (\n dest_surface,\n original_surface,\n 0, # color\n 0, # threshold\n change_color, # diff_color\n 1, # change_return\n third_surface,\n )\n\n # Return, of pixels within threshold is correct\n self.assertEqual(0, pixels_within_threshold)\n\n # Size of dest surface is correct\n dest_rect = dest_surface.get_rect()\n dest_size = dest_rect.size\n self.assertEqual(size, dest_size)\n\n # The color is the change_color specified for every pixel As all\n # pixels are not within threshold\n\n for pt in test_utils.rect_area_pts(dest_rect):\n self.assertEqual(dest_surface.get_at(pt), change_color)\n\n\n\n#XXX\n def test_threshold_non_src_alpha(self):\n\n result = pygame.Surface((10,10))\n s1 = pygame.Surface((10,10))\n s2 = pygame.Surface((10,10))\n s3 = pygame.Surface((10,10))\n s4 = pygame.Surface((10,10))\n result = pygame.Surface((10,10))\n x = s1.fill((0,0,0))\n x = s2.fill((0,20,0))\n x = s3.fill((0,0,0))\n x = s4.fill((0,0,0))\n s1.set_at((0,0), (32, 20, 0 ))\n s2.set_at((0,0), (33, 21, 0 ))\n s2.set_at((3,0), (63, 61, 0 ))\n s3.set_at((0,0), (112, 31, 0 ))\n s4.set_at((0,0), (11, 31, 0 ))\n s4.set_at((1,1), (12, 31, 0 ))\n\n self.assertEqual( s1.get_at((0,0)), (32, 20, 0, 255) )\n self.assertEqual( s2.get_at((0,0)), (33, 21, 0, 255) )\n self.assertEqual( (0,0), (s1.get_flags(), s2.get_flags()))\n\n\n\n #All one hundred of the pixels should be within the threshold.\n\n #>>> object_tracking.diff_image(result, s1, s2, threshold = 20)\n #100\n\n similar_color = (255, 255, 255,255)\n diff_color=(222,0,0,255)\n threshold_color = (20,20,20,255)\n\n rr = pygame.transform.threshold(result, s1, similar_color, threshold_color, diff_color, 1, s2)\n self.assertEqual(rr, 99)\n\n self.assertEqual( result.get_at((0,0)), (255,255,255, 255) )\n\n\n\n rr = pygame.transform.threshold(result, s1, similar_color,\n threshold_color, diff_color, 2, s2)\n self.assertEqual(rr, 99)\n\n self.assertEqual( result.get_at((0,0)), (32, 20, 0, 255) )\n\n\n\n\n # this is within the threshold,\n # so the color is copied from the s1 surface.\n self.assertEqual( result.get_at((1,0)), (0, 0, 0, 255) )\n\n # this color was not in the threshold so it has been set to diff_color\n self.assertEqual( result.get_at((3,0)), (222, 0, 0, 255) )\n\n\n\n\n\n\n\n\n def test_threshold__uneven_colors(self):\n (w,h) = size = (16, 16)\n\n original_surface = pygame.Surface(size, pygame.SRCALPHA, 32)\n dest_surface = pygame.Surface(size, pygame.SRCALPHA, 32)\n\n original_surface.fill(0)\n\n threshold_color_template = [5, 5, 5, 5]\n threshold_template = [6, 6, 6, 6]\n\n ################################################################\n\n for pos in range(len('rgb')):\n threshold_color = threshold_color_template[:]\n threshold = threshold_template[:]\n\n threshold_color[pos] = 45\n threshold[pos] = 50\n\n pixels_within_threshold = pygame.transform.threshold (\n dest_surface, original_surface, threshold_color,\n threshold,\n 0, # diff_color\n 0 # change_return\n )\n\n self.assertEqual(w*h, pixels_within_threshold)\n\n ################################################################\n\n def test_threshold__surface(self):\n \"\"\"\n \"\"\"\n\n #pygame.transform.threshold(DestSurface, Surface, color, threshold = (0,0,0,0), diff_color = (0,0,0,0), change_return = True): return num_threshold_pixels\n threshold = pygame.transform.threshold\n\n s1 = pygame.Surface((32,32), SRCALPHA, 32)\n s2 = pygame.Surface((32,32), SRCALPHA, 32)\n s3 = pygame.Surface((1,1), SRCALPHA, 32)\n\n s1.fill((40,40,40))\n s2.fill((255,255,255))\n\n\n\n\n dest_surface = s2\n surface1 = s1\n color = (30,30,30)\n the_threshold = (11,11,11)\n diff_color = (255,0,0)\n change_return = 2\n\n # set the similar pixels in destination surface to the color\n # in the first surface.\n num_threshold_pixels = threshold(dest_surface, surface1, color,\n the_threshold, diff_color,\n change_return)\n\n #num_threshold_pixels = threshold(s2, s1, (30,30,30))\n self.assertEqual(num_threshold_pixels, s1.get_height() * s1.get_width())\n self.assertEqual(s2.get_at((0,0)), (40, 40, 40, 255))\n\n\n\n\n\n if 1:\n\n # only one pixel should not be changed.\n s1.fill((40,40,40))\n s2.fill((255,255,255))\n s1.set_at( (0,0), (170, 170, 170) )\n # set the similar pixels in destination surface to the color\n # in the first surface.\n num_threshold_pixels = threshold(s2, s1, (30,30,30), (11,11,11),\n (0,0,0), 2)\n\n #num_threshold_pixels = threshold(s2, s1, (30,30,30))\n self.assertEqual(num_threshold_pixels, (s1.get_height() * s1.get_width()) -1)\n self.assertEqual(s2.get_at((0,0)), (0,0,0, 255))\n self.assertEqual(s2.get_at((0,1)), (40, 40, 40, 255))\n self.assertEqual(s2.get_at((17,1)), (40, 40, 40, 255))\n\n\n # abs(40 - 255) < 100\n #(abs(c1[0] - r) < tr)\n\n if 1:\n s1.fill((160,160,160))\n s2.fill((255,255,255))\n num_threshold_pixels = threshold(s2, s1, (255,255,255), (100,100,100), (0,0,0), True)\n\n self.assertEqual(num_threshold_pixels, (s1.get_height() * s1.get_width()))\n\n\n\n\n if 1:\n # only one pixel should not be changed.\n s1.fill((40,40,40))\n s2.fill((255,255,255))\n s1.set_at( (0,0), (170, 170, 170) )\n num_threshold_pixels = threshold(s3, s1, (30,30,30), (11,11,11), (0,0,0), False)\n #num_threshold_pixels = threshold(s2, s1, (30,30,30))\n self.assertEqual(num_threshold_pixels, (s1.get_height() * s1.get_width()) -1)\n\n\n if 1:\n # test end markers. 0, and 255\n\n # the pixels are different by 1.\n s1.fill((254,254,254))\n s2.fill((255,255,255))\n s3.fill((255,255,255))\n s1.set_at( (0,0), (170, 170, 170) )\n num_threshold_pixels = threshold(s3, s1, (254,254,254), (1,1,1),\n (44,44,44,255), False)\n self.assertEqual(num_threshold_pixels, (s1.get_height() * s1.get_width()) -1)\n\n\n # compare the two surfaces. Should be all but one matching.\n num_threshold_pixels = threshold(s3, s1, 0, (1,1,1),\n (44,44,44,255), False, s2)\n self.assertEqual(num_threshold_pixels, (s1.get_height() * s1.get_width()) -1)\n\n\n # within (0,0,0) threshold? Should match no pixels.\n num_threshold_pixels = threshold(s3, s1, (253,253,253), (0,0,0),\n (44,44,44,255), False)\n self.assertEqual(num_threshold_pixels, 0)\n\n\n # other surface within (0,0,0) threshold? Should match no pixels.\n num_threshold_pixels = threshold(s3, s1, 0, (0,0,0),\n (44,44,44,255), False, s2)\n self.assertEqual(num_threshold_pixels, 0)\n\n\n\n\n def test_laplacian(self):\n \"\"\"\n \"\"\"\n\n SIZE = 32\n s1 = pygame.Surface((SIZE, SIZE))\n s2 = pygame.Surface((SIZE, SIZE))\n s1.fill((10,10,70))\n pygame.draw.line(s1, (255,0,0), (3,10), (20,20))\n\n # a line at the last row of the image.\n pygame.draw.line(s1, (255,0,0), (0,31), (31,31))\n\n\n pygame.transform.laplacian(s1,s2)\n\n #show_image(s1)\n #show_image(s2)\n\n self.assertEqual(s2.get_at((0,0)), (0, 0, 0, 255))\n self.assertEqual(s2.get_at((3,10)), (255,0,0,255))\n self.assertEqual(s2.get_at((0,31)), (255,0,0,255))\n self.assertEqual(s2.get_at((31,31)), (255,0,0,255))\n\n\n # here we create the return surface.\n s2 = pygame.transform.laplacian(s1)\n\n self.assertEqual(s2.get_at((0,0)), (0, 0, 0, 255))\n self.assertEqual(s2.get_at((3,10)), (255,0,0,255))\n self.assertEqual(s2.get_at((0,31)), (255,0,0,255))\n self.assertEqual(s2.get_at((31,31)), (255,0,0,255))\n\n def test_average_surfaces(self):\n \"\"\"\n \"\"\"\n\n SIZE = 32\n s1 = pygame.Surface((SIZE, SIZE))\n s2 = pygame.Surface((SIZE, SIZE))\n s3 = pygame.Surface((SIZE, SIZE))\n s1.fill((10,10,70))\n s2.fill((10,20,70))\n s3.fill((10,130,10))\n\n surfaces = [s1, s2, s3]\n surfaces = [s1, s2]\n sr = pygame.transform.average_surfaces(surfaces)\n\n self.assertEqual(sr.get_at((0,0)), (10,15,70,255))\n\n\n self.assertRaises(TypeError, pygame.transform.average_surfaces, 1)\n self.assertRaises(TypeError, pygame.transform.average_surfaces, [])\n\n self.assertRaises(TypeError, pygame.transform.average_surfaces, [1])\n self.assertRaises(TypeError, pygame.transform.average_surfaces, [s1, 1])\n self.assertRaises(TypeError, pygame.transform.average_surfaces, [1, s1])\n self.assertRaises(TypeError, pygame.transform.average_surfaces, [s1, s2, 1])\n\n self.assertRaises(TypeError, pygame.transform.average_surfaces, (s for s in [s1, s2,s3] ))\n\n\n\n def test_average_surfaces__24(self):\n\n SIZE = 32\n depth = 24\n s1 = pygame.Surface((SIZE, SIZE), 0, depth)\n s2 = pygame.Surface((SIZE, SIZE), 0, depth)\n s3 = pygame.Surface((SIZE, SIZE), 0, depth)\n s1.fill((10,10,70, 255))\n s2.fill((10,20,70, 255))\n s3.fill((10,130,10, 255))\n\n surfaces = [s1, s2, s3]\n sr = pygame.transform.average_surfaces(surfaces)\n self.assertEqual( sr.get_masks(), s1.get_masks() )\n self.assertEqual( sr.get_flags(), s1.get_flags() )\n self.assertEqual( sr.get_losses(), s1.get_losses() )\n\n if 0:\n print ( sr, s1 )\n print ( sr.get_masks(), s1.get_masks() )\n print ( sr.get_flags(), s1.get_flags() )\n print ( sr.get_losses(), s1.get_losses() )\n print ( sr.get_shifts(), s1.get_shifts() )\n\n self.assertEqual(sr.get_at((0,0)), (10,53,50,255))\n\n\n\n\n\n\n\n\n\n def test_average_color(self):\n \"\"\"\n \"\"\"\n\n a = [24, 32]\n for i in a:\n s = pygame.Surface((32,32), 0, i)\n s.fill((0,100,200))\n s.fill((10,50,100), (0,0,16,32))\n\n self.assertEqual(pygame.transform.average_color(s),(5,75,150,0))\n self.assertEqual(pygame.transform.average_color(s, (16,0,16,32)), (0,100,200,0))\n\n def todo_test_rotate(self):\n\n # __doc__ (as of 2008-06-25) for pygame.transform.rotate:\n\n # pygame.transform.rotate(Surface, angle): return Surface\n # rotate an image\n\n # color = (128, 128, 128, 255)\n # s = pygame.Surface((3, 3))\n\n # s.set_at((2, 0), color)\n\n # self.assert_(s.get_at((0, 0)) != color)\n # s = pygame.transform.rotate(s, 90)\n # self.assert_(s.get_at((0, 0)) == color)\n\n self.fail()\n\n def test_rotate__lossless_at_90_degrees(self):\n w, h = 32, 32\n s = pygame.Surface((w, h), pygame.SRCALPHA)\n\n gradient = list(test_utils.gradient(w, h))\n\n for pt, color in gradient: s.set_at(pt, color)\n\n for rotation in (90, -90):\n s = pygame.transform.rotate(s,rotation)\n\n for pt, color in gradient:\n self.assert_(s.get_at(pt) == color)\n\n def test_scale2x(self):\n\n # __doc__ (as of 2008-06-25) for pygame.transform.scale2x:\n\n # pygame.transform.scale2x(Surface, DestSurface = None): Surface\n # specialized image doubler\n\n w, h = 32, 32\n s = pygame.Surface((w, h), pygame.SRCALPHA, 32)\n\n # s.set_at((0,0), (20, 20, 20, 255))\n\n s2 = pygame.transform.scale2x(s)\n self.assertEquals(s2.get_rect().size, (64, 64))\n\n def test_get_smoothscale_backend(self):\n filter_type = pygame.transform.get_smoothscale_backend()\n self.failUnless(filter_type in ['GENERIC', 'MMX', 'SSE'])\n # It would be nice to test if a non-generic type corresponds to an x86\n # processor. But there is no simple test for this. platform.machine()\n # returns process version specific information, like 'i686'.\n\n def test_set_smoothscale_backend(self):\n # All machines should allow 'GENERIC'.\n original_type = pygame.transform.get_smoothscale_backend()\n pygame.transform.set_smoothscale_backend('GENERIC')\n filter_type = pygame.transform.get_smoothscale_backend()\n self.failUnlessEqual(filter_type, 'GENERIC')\n # All machines should allow returning to original value.\n # Also check that keyword argument works.\n pygame.transform.set_smoothscale_backend(type=original_type)\n # Something invalid.\n def change():\n pygame.transform.set_smoothscale_backend('mmx')\n self.failUnlessRaises(ValueError, change)\n # Invalid argument keyword.\n def change():\n pygame.transform.set_smoothscale_backend(t='GENERIC')\n self.failUnlessRaises(TypeError, change)\n # Invalid argument type.\n def change():\n pygame.transform.set_smoothscale_backend(1)\n self.failUnlessRaises(TypeError, change)\n # Unsupported type, if possible.\n if original_type != 'SSE':\n def change():\n pygame.transform.set_smoothscale_backend('SSE')\n self.failUnlessRaises(ValueError, change)\n # Should be back where we started.\n filter_type = pygame.transform.get_smoothscale_backend()\n self.failUnlessEqual(filter_type, original_type)\n\n def todo_test_chop(self):\n\n # __doc__ (as of 2008-08-02) for pygame.transform.chop:\n\n # pygame.transform.chop(Surface, rect): return Surface\n # gets a copy of an image with an interior area removed\n #\n # Extracts a portion of an image. All vertical and horizontal pixels\n # surrounding the given rectangle area are removed. The corner areas\n # (diagonal to the rect) are then brought together. (The original\n # image is not altered by this operation.)\n #\n # NOTE: If you want a \"crop\" that returns the part of an image within\n # a rect, you can blit with a rect to a new surface or copy a\n # subsurface.\n\n self.fail()\n\n def todo_test_flip(self):\n\n # __doc__ (as of 2008-08-02) for pygame.transform.flip:\n\n # pygame.transform.flip(Surface, xbool, ybool): return Surface\n # flip vertically and horizontally\n #\n # This can flip a Surface either vertically, horizontally, or both.\n # Flipping a Surface is nondestructive and returns a new Surface with\n # the same dimensions.\n\n self.fail()\n\n def todo_test_rotozoom(self):\n\n # __doc__ (as of 2008-08-02) for pygame.transform.rotozoom:\n\n # pygame.transform.rotozoom(Surface, angle, scale): return Surface\n # filtered scale and rotation\n #\n # This is a combined scale and rotation transform. The resulting\n # Surface will be a filtered 32-bit Surface. The scale argument is a\n # floating point value that will be multiplied by the current\n # resolution. The angle argument is a floating point value that\n # represents the counterclockwise degrees to rotate. A negative\n # rotation angle will rotate clockwise.\n\n self.fail()\n\n def todo_test_smoothscale(self):\n # __doc__ (as of 2008-08-02) for pygame.transform.smoothscale:\n\n # pygame.transform.smoothscale(Surface, (width, height), DestSurface =\n # None): return Surface\n #\n # scale a surface to an arbitrary size smoothly\n #\n # Uses one of two different algorithms for scaling each dimension of\n # the input surface as required. For shrinkage, the output pixels are\n # area averages of the colors they cover. For expansion, a bilinear\n # filter is used. For the amd64 and i686 architectures, optimized MMX\n # routines are included and will run much faster than other machine\n # types. The size is a 2 number sequence for (width, height). This\n # function only works for 24-bit or 32-bit surfaces. An exception\n # will be thrown if the input surface bit depth is less than 24.\n #\n # New in pygame 1.8\n\n self.fail()\n\nif __name__ == '__main__':\n #tt = TransformModuleTest()\n #tt.test_threshold_non_src_alpha()\n\n unittest.main()\n","repo_name":"renpy/pygame_sdl2","sub_path":"test/transform_test.py","file_name":"transform_test.py","file_ext":"py","file_size_in_byte":24894,"program_lang":"python","lang":"en","doc_type":"code","stars":311,"dataset":"github-code","pt":"40"} +{"seq_id":"24715072569","text":"balance=float(input(\"Enter balance :\\t\"))\r\nannualInterestRate=float(input(\"Enter annualInterestRate :\\t\"))\r\nmir=annualInterestRate/12\r\nmmp=0\r\npreBalance=balance\r\nwhile balance>0:\r\n mmp+=10\r\n balance=preBalance\r\n for i in range(12):\r\n mub=balance-mmp\r\n balance=mub+mir*mub \r\nprint(\"lowest Monthly payment\\n\")\r\nprint(\"'\"*50,\"\\n\")\r\nprint(mmp)\r\n","repo_name":"kartikeya-arun/codes","sub_path":"Python/payoff in a year.py","file_name":"payoff in a year.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"11090346371","text":"from django.shortcuts import render\nfrom rest_framework.permissions import IsAuthenticated,AllowAny\nfrom rest_framework.views import APIView\nfrom .serializer import UserSerializer\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework.decorators import permission_classes\nimport jwt\nfrom rest_framework_jwt.utils import jwt_payload_handler\nfrom .models import User\nfrom django.contrib.auth.signals import user_logged_in\n\nimport django_auth.settings as settings\n\nclass LoginView(APIView):\n \n permission_classes =[AllowAny]\n def post(self,request):\n \n try:\n email = request.data['email']\n password = request.data['password']\n \n user = User.objects.filter(email=email, password=password).first()\n if user:\n try:\n payload = jwt_payload_handler(user)\n token = jwt.encode(payload, settings.SECRET_KEY)\n user_details = {}\n user_details['name'] = \"%s %s\" % (\n user.first_name, user.last_name)\n user_details['token'] = token\n user_logged_in.send(sender=user.__class__,\n request=request, user=user)\n return Response(user_details, status=status.HTTP_200_OK)\n \n except Exception as e:\n raise e\n else:\n res = {\n 'error': 'can not authenticate with the given credentials or the account has been deactivated'}\n return Response(res, status=status.HTTP_403_FORBIDDEN)\n except KeyError:\n res = {'error': 'please provide a email and a password'}\n return Response(res)\n \n \n# Create your views here.\nclass CreateUserAPIView(APIView):\n \n # Allow any user (authenticated or not) to access this url \n permission_classes = (AllowAny,)\n \n def post(self, request):\n \n user = request.data\n serializer = UserSerializer(data=user)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n \n\nclass UpdateRetriveUserAPIView(APIView):\n\n permission_classes = (IsAuthenticated,)\n \n def put(self,request,*args,**kwargs):\n \n serializer_data = request.data\n serializer = UserSerializer(\n request.user, data=serializer_data, partial=True\n )\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n return Response(serializer.data, status=status.HTTP_200_OK)\n \n def get(self,request,*args,**kwargs):\n \n serializer = UserSerializer(request.user)\n return Response(serializer.data, status=status.HTTP_200_OK)\n","repo_name":"Thesohan/Django_auth","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"72989513400","text":"import numpy as np\nfrom pandas import DataFrame\n\n\"\"\"\nBase class for a tranche in a Structured Security. \nContains methods for calculating waterfall metrics.\n\"\"\"\n\nclass Tranche(object):\n def __init__(self, notional, rate, subordination):\n self._notional = notional\n self._rate = rate\n self._subordination = subordination\n self._transactions = DataFrame(\n columns=['principal_payment', 'interest_payment', 'interest_shortfall', 'total_payment',\n 'notional_balance'], dtype=float)\n\n def irr(self):\n payments = self._transactions['total_payment'][1:].tolist()\n payments.insert(0, -self.notional)\n return np.irr(payments) * 12\n\n def al(self):\n ending_balance = self._transactions['notional_balance'].iloc[-1]\n return ((sum([x * y for x, y in zip(self._transactions['notional_balance'].tolist(), range(\n self._transactions.size + 1))]) - self.notional) / self.notional) if ending_balance == 0 else np.inf\n\n def dirr(self):\n return self.rate - self.irr()\n\n def rating(self):\n dirr_bps = self.dirr() / 100\n if dirr_bps <= 0.06:\n return \"AAA\"\n if dirr_bps <= 0.67:\n return \"AA1\"\n if dirr_bps <= 1.3:\n return \"AA2\"\n if dirr_bps <= 2.7:\n return \"AA3\"\n if dirr_bps <= 5.2:\n return \"A1\"\n if dirr_bps <= 8.9:\n return \"A2\"\n if dirr_bps <= 13:\n return \"A3\"\n if dirr_bps <= 19:\n return \"BAA1\"\n if dirr_bps <= 27:\n return \"BAA2\"\n if dirr_bps <= 46:\n return \"BAA3\"\n if dirr_bps <= 72:\n return \"BA1\"\n if dirr_bps <= 106:\n return \"BA2\"\n if dirr_bps <= 143:\n return \"BA3\"\n if dirr_bps <= 183:\n return \"B1\"\n if dirr_bps <= 231:\n return \"B2\"\n if dirr_bps <= 311:\n return \"B3\"\n if dirr_bps <= 2500:\n return \"CAA\"\n if dirr_bps <= 10000:\n return \"CA\"\n\n @property\n def notional(self):\n return self._notional\n\n @notional.setter\n def notional(self, notional):\n self._notional = notional\n\n @property\n def rate(self):\n return self._rate\n\n @rate.setter\n def rate(self, rate):\n self._rate = rate\n\n @property\n def subordination(self):\n return self._subordination\n\n @subordination.setter\n def subordination(self, subordination):\n self._subordination = subordination\n\n @property\n def transactions(self):\n return self._transactions\n","repo_name":"tricky11/MTH9815-Project1-Group10","sub_path":"tranche.py","file_name":"tranche.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"27078754198","text":"import argparse\nimport logging\nimport sys\nimport json\nfrom pprint import pprint\n\nfrom deepdiff import DeepDiff\n\nfrom mungetout import convert\nfrom mungetout import __version__\n\n__author__ = \"Will Szumski\"\n__copyright__ = \"Will Szumski\"\n__license__ = \"apache\"\n\n_logger = logging.getLogger(__name__)\n\n\ndef parse_args(args):\n \"\"\"Parse command line parameters\n\n Args:\n args ([str]): command line parameters as list of strings\n\n Returns:\n :obj:`argparse.Namespace`: command line parameters namespace\n \"\"\"\n parser = argparse.ArgumentParser(\n description=\"Basic json diff\")\n parser.add_argument(\n '--version',\n action='version',\n version='mungetout {ver}'.format(ver=__version__))\n parser.add_argument(\n 'file',\n metavar='FILE',\n nargs=2,\n help='File to diff'\n )\n parser.add_argument(\n '--filter-unique-fields',\n dest=\"unique\",\n help=\"EXPERIMENTAL: Only compare fields that appear in both\",\n action='store_true',\n default=False)\n parser.add_argument(\n '-v',\n '--verbose',\n dest=\"loglevel\",\n help=\"set loglevel to INFO\",\n action='store_const',\n const=logging.INFO)\n parser.add_argument(\n '-vv',\n '--very-verbose',\n dest=\"loglevel\",\n help=\"set loglevel to DEBUG\",\n action='store_const',\n const=logging.DEBUG)\n return parser.parse_args(args)\n\n\ndef setup_logging(loglevel):\n \"\"\"Setup basic logging\n\n Args:\n loglevel (int): minimum loglevel for emitting messages\n \"\"\"\n logformat = \"[%(asctime)s] %(levelname)s:%(name)s:%(message)s\"\n logging.basicConfig(level=loglevel, stream=sys.stderr,\n format=logformat, datefmt=\"%Y-%m-%d %H:%M:%S\")\n\n\ndef main(args):\n \"\"\"Main entry point allowing external calls\n\n Args:\n args ([str]): command line parameter list\n \"\"\"\n args = parse_args(args)\n setup_logging(args.loglevel)\n with open(args.file[0]) as f1, open(args.file[1]) as f2:\n c1 = convert.clean(json.load(f1), filter_benchmarks=True,\n filter_serials=True)\n c2 = convert.clean(json.load(f2), filter_benchmarks=True,\n filter_serials=True)\n if args.unique:\n # x[1] element can be a disk or cpu id, x[3] is the value, so\n # only compare x[0] and x[2]. That way a difference in the\n # number of cpus or disks will still be shown.\n c1_keys = {(x[0], x[2]) for x in c1}\n c2_keys = {(x[0], x[2]) for x in c2}\n common_keys = c1_keys.intersection(c2_keys)\n c1 = [x for x in c1 if (x[0], x[2]) in common_keys]\n c2 = [x for x in c2 if (x[0], x[2]) in common_keys]\n ddiff = DeepDiff(c1, c2, ignore_order=True)\n pprint(ddiff, indent=2)\n\n\ndef run():\n \"\"\"Entry point for console_scripts\n \"\"\"\n main(sys.argv[1:])\n","repo_name":"stackhpc/mungetout","sub_path":"mungetout/diff.py","file_name":"diff.py","file_ext":"py","file_size_in_byte":2948,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"40617682755","text":"import logging\n\nfrom django.conf import settings\nfrom urllib.parse import urlparse\nfrom requests import get\n\nfrom vk_auth_app.tools.sessionhandler import get_session_key\n\n\nlogger = logging.getLogger('django')\n\n\nclass VkApi:\n client_id = settings.OAUTH_VK['client_id']\n display = settings.OAUTH_VK['display']\n scope = settings.OAUTH_VK['scope']\n response_type = settings.OAUTH_VK['response_type']\n client_secret_code = settings.OAUTH_VK['client_secret_code']\n version = settings.OAUTH_VK['v']\n authorize_url = settings.OAUTH_VK['authorize_url']\n main_url_methods = settings.VK_API_METHODS['url']\n vk_api_methods = settings.VK_API_METHODS['methods']\n\n def __init__(self, request):\n session_values = get_session_key(request, 'member_id', 'access_token')\n if session_values:\n self.member_id = session_values[0]\n self.access_token = session_values[1]\n else:\n self.redirect_uri = self.get_redirect_uri(request)\n\n def get_url_authorize(self):\n\n if self.redirect_uri:\n vk_oauth_url = '{authorize_url}?client_id={client_id}&display={display}&redirect_uri={redirect_uri}&scope={scope}&response_type={response_type}&v={version}'.format(\n authorize_url=self.authorize_url,\n client_id=self.client_id,\n display=self.display,\n redirect_uri=self.redirect_uri,\n scope=self.scope,\n response_type=self.response_type,\n version=self.version\n )\n return vk_oauth_url\n else:\n logging.warning('AttributeError: class VkOauth don\\'t has a request parameter')\n raise AttributeError('class VkOauth don\\'t has a request parameter')\n\n def get_friends(self):\n get_friend_method = self.vk_api_methods['get_friends']\n name_method = get_friend_method['name_method']\n\n params_string = self.get_params_to_string(get_friend_method)\n url_get_friend = '{main_url_methods}{name_method}?user_id={user_id}{params}&access_token={access_token}&v={version}'.format(\n main_url_methods=self.main_url_methods,\n name_method=name_method,\n user_id=self.member_id,\n params=params_string,\n access_token=self.access_token,\n version=self.version\n )\n response = get(url_get_friend).json()['response']['items']\n return response\n\n def get_info_user(self):\n get_users_method = self.vk_api_methods['get_users']\n name_method = get_users_method['name_method']\n params_string = self.get_params_to_string(get_users_method)\n url_get_info = '{main_url_methods}{name_method}?user_id={user_id}{params_string}&access_token={access_token}&v={version}'.format(\n main_url_methods=self.main_url_methods,\n name_method=name_method,\n user_id=self.member_id,\n params_string=params_string,\n access_token=self.access_token,\n version=self.version\n )\n try:\n response = get(url_get_info).json()['response'][0]\n return response\n except:\n logger.warning('Error with get_user\\'s_info request')\n\n def get_token(self, code):\n url = 'https://oauth.vk.com/access_token?client_id={client_id}&client_secret={secret}&redirect_uri={redirect_uri}&code={code}'.format(\n client_id=self.client_id,\n secret=self.client_secret_code,\n redirect_uri=self.redirect_uri,\n code=code\n )\n\n response = get(url).json()\n\n if 'access_token' in response.keys() and 'user_id' in response.keys():\n access_token = response['access_token']\n user_id = response['user_id']\n else:\n access_token = ''\n user_id = ''\n return access_token, user_id\n\n @staticmethod\n def get_redirect_uri(request):\n absolute_uri = request.build_absolute_uri()\n redirect_path = settings.OAUTH_VK['redirect_path']\n absolute_uri_parse = urlparse(absolute_uri)\n redirect_uri = '{scheme}://{netloc}/{path}'.format(\n scheme=absolute_uri_parse.scheme,\n netloc=absolute_uri_parse.netloc,\n path=redirect_path)\n return redirect_uri\n\n @staticmethod\n def get_params_to_string(params_dict):\n params_string = ''\n for key, value in params_dict.items():\n if key == 'name_method':\n continue\n params_string += '&{key}={value}'.format(key=key, value=value)\n return params_string\n","repo_name":"Tatiana-develop/test-vk-auth","sub_path":"vk_auth_app/tools/vk_tools.py","file_name":"vk_tools.py","file_ext":"py","file_size_in_byte":4618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"34484324112","text":"stack = []\r\nn = int(input())\r\nfor i in range(n):\r\n lst = [] \r\n lst = [int(item) for item in input().split()] \r\n if lst[0] == 1:\r\n stack.append(lst[1])\r\n elif lst[0] == 2:\r\n if len(stack)!=0:\r\n stack.pop()\r\n elif lst[0] == 3:\r\n if len(stack) == 0:\r\n print(\"Empty!\")\r\n else:\r\n print(stack[-1])\r\n\r\n \r\n \r\n \r\n","repo_name":"SushanthPS/Python","sub_path":"5PuspPopTop.py","file_name":"5PuspPopTop.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"6453786983","text":"from __future__ import annotations\nimport os\n\nfrom enum import Enum, auto\n\nROOT_DIR = os.path.dirname(os.path.abspath(__file__))\n\nATOMIC_SYMBOLS = dict()\nwith open(os.path.join(ROOT_DIR, \"../res/AtomicSymbolDict.txt\"), \"r\") as f:\n for line in f.readlines():\n (k, v) = line.split('\\t')\n ATOMIC_SYMBOLS[int(k)] = v[:-1]\n\nOUT_FOLDER = os.path.join(ROOT_DIR, \"../out\")\nOUT_FOLDER_SVG = os.path.join(ROOT_DIR, \"../svg\")\nRED_OUT_FOLDER = os.path.join(ROOT_DIR, \"../out_red\")\n# RED_OUT_FOLDER_SVG = os.path.join(ROOT_DIR, \"../svg_red\")\nIN_FOLDER = os.path.join(ROOT_DIR, \"../in\")\nOUTPUT_FORMAT = \"svg\"\nOUTPUT_FORMAT_SVG = \"svg\"\nINPUT_FORMAT = \"xyz\"\nERROR_FOLDER = os.path.join(ROOT_DIR, \"../error\")\n\nclass SiteSelection(Enum):\n CYCLES = auto()\n NON_CYCLES = auto()\n ALL = auto()\n\n\nclass BondType(Enum):\n SINGLE = 1\n DOUBLE = 2\n TRIPLE = 3\n AROMATIC = 5\n\n @staticmethod\n def from_ob_bond_bype(bond_type: int) -> 'BondType':\n if bond_type == BondType.SINGLE.value:\n return BondType.SINGLE\n elif bond_type == BondType.DOUBLE.value:\n return BondType.DOUBLE\n elif bond_type == BondType.TRIPLE.value:\n return BondType.TRIPLE\n elif bond_type == BondType.AROMATIC.value:\n return BondType.AROMATIC\n","repo_name":"carim2020/der-gen","sub_path":"src/Definitions.py","file_name":"Definitions.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"21307194954","text":"import csv\nimport json\nimport os\nimport shutil\nimport time\nfrom datetime import date\n\nimport cve_lookup\nimport mitreattack.attackToExcel.attackToExcel as attackToExcel\nimport mitreattack.attackToExcel.stixToDf as stixToDf\nimport nvdlib\nimport pandas as pd\nfrom cwe2.database import Database\nfrom git import InvalidGitRepositoryError, Repo\nfrom stix2 import Filter\n\n\nclass cve_custom_encoder(json.JSONEncoder):\n def default(self, o):\n return o.__dict__\n\n\ndb = Database()\nfilt = Filter('type', '=', 'attack-pattern')\nfs = None\n\n\ndef get_formatted_runtime(start, end):\n hours, rem = divmod(end - start, 3600)\n minutes, seconds = divmod(rem, 60)\n return \"{:0>2}h {:0>2}m and {:05.2f}s\".format(int(hours), int(minutes), seconds)\n\n\ndef get_attack_pattern_by_capec_id(src, capec_id):\n filt = [\n Filter('type', '=', 'attack-pattern'),\n Filter('external_references.external_id', '=', 'CAPEC-' + capec_id),\n Filter('external_references.source_name', '=', 'capec'),\n ]\n return src.query(filt)\n\n\ndef get_capec_external_references_cwes(src, capec):\n id = capec.split(\"-\")[1]\n test = get_attack_pattern_by_capec_id(src, id)\n if len(test) != 0:\n return test[0][\"external_references\"]\n else:\n return []\n\n\ndef iterate_cve_for_given_cwe(db, cwe):\n cve_list = []\n weakness = db.get(cwe.split(\"-\")[1])\n observed_examples = weakness.__dict__[\"observed_examples\"]\n cves = [word for word in observed_examples.split(\":\") if word.startswith(\"CVE-\")]\n\n for cve in cves:\n cve_full = None\n while cve_full is None:\n try:\n cve_full = cve_lookup.cve(cve)\n print(f\"{cve_full.id}, \", end='')\n except Exception as e:\n print(f\"\\nError during lookup for cve entry ..\\n -> {e} \\n Retrying.\\n\")\n time.sleep(3)\n\n r = None\n while r is None:\n try:\n r = nvdlib.searchCVE(cveId=cve, key='8051e78c-9d20-4b6d-9bcb-20ce09eed8b8')[0]\n\n cve_list.append({\"id\": cve_full.id,\n \"score\": r.score,\n \"v2_score\": r.v2score,\n \"v2_exploitability_score\": r.v2exploitability,\n \"v2_impact_score\": r.v2impactScore,\n \"v2_vector\": r.v2vector,\n \"access_vector\": r.metrics.cvssMetricV2[0].cvssData.accessVector,\n \"full_metrics\": r.metrics.cvssMetricV2,\n \"description\": r.descriptions[0].value,\n \"cpe_vulnerable\": r.cpe[0].vulnerable,\n \"cpe_criteria\": r.cpe[0].criteria,\n \"published\": r.published,\n \"last_modified\": r.lastModified\n })\n\n except Exception as e:\n print(f\"\\nError during fetch for {cve_full.id}..\\n -> {e} \\n Retrying.\\n\")\n time.sleep(10)\n\n return {\"cwe\": cwe, \"cves\": cve_list, \"cwe_info\": weakness.__dict__}\n\n\ndef pull_clone_gitrepo(directory, repo):\n # Check if the data direcory exists\n if not os.path.isdir(directory):\n Repo.clone_from(repo, directory)\n else:\n try:\n # Check if the data directory is actually a repositry then pull the canges\n repo = Repo(directory)\n repo.remotes.origin.pull()\n except InvalidGitRepositoryError:\n # If not then remove the folder\n shutil.rmtree(directory)\n Repo.clone_from(repo, directory)\n\n\ndef generate_techniques_dataframe():\n # download and parse ATT&CK STIX data\n attackdata = attackToExcel.get_stix_data(\"enterprise-attack\", \"v4.0\")\n # get Pandas DataFrames for techniques, associated relationships, and citations\n techniques_data = stixToDf.techniquesToDf(attackdata, \"enterprise-attack\")\n return techniques_data[\"techniques\"]\n\n\ndef get_grouped_o_cloud_technique(file, drop_duplicates: bool = False):\n # Extract CAPEC's for our selected O-Cloud threats and return them.\n o_cloud = pd.read_csv(file, sep=';', index_col=0)\n if drop_duplicates:\n o_cloud = o_cloud.drop_duplicates(subset=[\"Technique\"])\n return o_cloud.groupby(\"Name\")\n\n\ndef get_technique_capecs_id(grouped, techniques_df):\n techniques_capecs = []\n for s, group in grouped:\n for i in group[\"Technique\"].drop_duplicates():\n capecs = []\n for capec in techniques_df[techniques_df[\"ID\"].str.contains(i)][\"CAPEC ID\"]:\n try:\n float(capec)\n except:\n for c in capec.split(\", \"):\n capecs.append(c)\n techniques_capecs.append((i, capecs))\n return techniques_capecs\n\n\ndef write_ids_to_file(techniques_capecs, file):\n f = open(file, 'w')\n writer = csv.writer(f)\n writer.writerow(['Technique ID', 'CAPEC ID'])\n\n for t_name, capec_ids in techniques_capecs:\n if len(capec_ids) != 0:\n for id in capec_ids:\n writer.writerow([t_name, id])\n f.close()\n\n\ndef print_stats(techniques_capecs):\n count_capecs = 0\n count_techniques = 0\n count_empty_techniques = 0\n for (t, l_capec) in techniques_capecs:\n len_l = len(l_capec)\n count_techniques += 1\n count_capecs += len_l\n if len_l == 0:\n count_empty_techniques += 1\n\n print(f\"Techniques: {count_techniques}\")\n print(f\"Empty Techniques: {count_empty_techniques}\")\n print(f\"CAPECs: {count_capecs}\")\n\n\ndef find_cwe_for_capec(techniques_capecs, fs):\n capec_list = []\n list_of_tinfos = []\n start = time.time()\n print(\"Start fetching CAPEC'S -> CWE'S -> CVE'S for given CAPEC-IDS...\")\n for t_id, capec_ids in techniques_capecs:\n if len(capec_ids) != 0:\n capec_list = []\n for c_id in capec_ids:\n print(f\"\\nSearching CVE's for {c_id}\")\n print(\"Found: \", end='')\n findings = []\n for reference in get_capec_external_references_cwes(fs, c_id):\n if reference[\"source_name\"] == \"cwe\":\n findings.append(iterate_cve_for_given_cwe(db, reference[\"external_id\"]))\n capec_list.append({\"capec_id\": c_id, \"c_findings\": findings})\n print(\"\\n\")\n list_of_tinfos.append({\"technique_id\": t_id, \"t_findings\": capec_list})\n end = time.time()\n print(f\"Finished in {get_formatted_runtime(start, end)}.\")\n return {\n \"scan_date\": f\"{date.today()}\",\n \"scan_runtime\": get_formatted_runtime(start, end),\n \"data\": list_of_tinfos\n }\n\n\ndef write_dict_to_file(t_cwe_cve_dict, file):\n with open(file, \"w\") as outfile:\n json.dump(t_cwe_cve_dict, outfile, cls=cve_custom_encoder)\n","repo_name":"fklement/acema_oran","sub_path":"OCloud_Data_Gathering.py","file_name":"OCloud_Data_Gathering.py","file_ext":"py","file_size_in_byte":6919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"43230918376","text":"#QUESTION 2: 2019A7PS1207H 2019A7PS0003H\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\narray=np.array([[8,10,3],[12,6,2],[5,1,7],[11,4,9]])\r\noriginal_array=np.array([[8,10,3],[12,6,2],[5,1,7],[11,4,9]])\r\narray1=np.array([[9,5,1],[10,6,2],[11,7,3],[12,8,4]])\r\ncount=0\r\nh=0\r\n\r\n#jump function\r\ndef jump(array,i,j):\r\n if (j!=2):\r\n temp=array[i,j]\r\n array[i,j]=array[i,j+1]\r\n array[i,j+1]=temp\r\n if (j==2):\r\n temp=array[i,j]\r\n array[i,j]=array[i,j-1]\r\n array[i,j-1]=temp\r\n return array\r\n\r\n#clockwise rotate function\r\ndef c_rotate(array,i,j):\r\n temp1=array[0,j]\r\n temp2=array[1,j]\r\n temp3=array[2,j]\r\n temp4=array[3,j]\r\n array[0,j]=temp4\r\n array[1,j]=temp1\r\n array[2,j]=temp2\r\n array[3,j]=temp3\r\n return array\r\n\r\n#anti-clockwise rotate function\r\ndef a_rotate(array,i,j):\r\n temp1=array[0,j]\r\n temp2=array[1,j]\r\n temp3=array[2,j]\r\n temp4=array[3,j]\r\n array[0,j]=temp2\r\n array[1,j]=temp3\r\n array[2,j]=temp4\r\n array[3,j]=temp1\r\n return array\r\n\r\n#optimal heuristic function: number of misplaced tiles\r\ndef heuristic(array1,array2):\r\n count=0\r\n for i in range(4):\r\n for j in range(3):\r\n #print(array1[i,j],array2[i,j],\"\\n\")\r\n if array1[i,j]==array2[i,j]:\r\n count+=1\r\n return (12-count)\r\n\r\n#function to find all neighbours of a state \r\ndef neighbours(array):\r\n neighbors = []\r\n statements = []\r\n for i in range(4):\r\n for j in range(3):\r\n array_copy1=np.copy(array)\r\n jump(array_copy1,i,j)\r\n neighbors.append(array_copy1)\r\n statements.append(f\"Jump({array_copy1[i,j]}):\\n{array_copy1}\")\r\n array_copy2=np.copy(array)\r\n c_rotate(array_copy2,i,j)\r\n neighbors.append(array_copy2)\r\n statements.append(f\"C_Rotate({array_copy2[i,j]}):\\n{array_copy2}\")\r\n array_copy3=np.copy(array)\r\n a_rotate(array_copy3,i,j)\r\n neighbors.append(array_copy3) \r\n statements.append(f\"A_Rotate({array_copy3[i,j]}):\\n{array_copy3}\")\r\n return neighbors,statements\r\n\r\ndef Steepest_Ascent_Hill_Climbing(array, initial_array, current_heuristic, current_neighbors, iterations = 100 ):\r\n initial_state = original_array \r\n distance = current_heuristic(initial_state,array) \r\n \r\n for i in range(iterations): \r\n # Generate all neighbors\r\n neighbors,statements_n = current_neighbors(initial_state)\r\n heuristics_neighbors = []\r\n # Loop over each neighbor and calculate the heuristic\r\n for n in neighbors:\r\n d = current_heuristic(n,array)\r\n heuristics_neighbors.append(d)\r\n # Get the index of the smallest heuristic \r\n min_distance_index = heuristics_neighbors.index(min(heuristics_neighbors))\r\n # Get the relative neighbor \r\n #if ((initial_state==neighbors[min_distance_index]).all()):\r\n # del heuristics_neighbors[min_distance_index]\r\n # min_distance_index = heuristics_neighbors.index(min(heuristics_neighbors))\r\n initial_state = neighbors[min_distance_index]\r\n global h\r\n global count\r\n if(h==current_heuristic(initial_state,array)):\r\n count+=1\r\n h=current_heuristic(initial_state,array)\r\n #print(initial_state)\r\n print(statements_n[min_distance_index])\r\n # Return the final state, and its heuristic \r\n return initial_state, current_heuristic(initial_state,array)\r\n\r\n# jump(array,3,1)\r\n# print(\"Jump(\", array[3,1], \"): \\n\", array)\r\n# print(heuristic(array,array1))\r\n# c_rotate(array,3,1)\r\n# print(\"C_Rotate(\", array[3,1], \"): \\n\", array)\r\n# a_rotate(array,3,1)\r\n# print(\"A_Rotate(\", array[3,1], \"): \\n\", array)\r\n# print(\"Neighbours:\\n\", neighbours(array))\r\n\r\n# Steepest Ascent Hill Climbing algorithm with 100 iterations\r\niterations = 100\r\nfinal_state, heuristic_n = Steepest_Ascent_Hill_Climbing(array1, array, heuristic, neighbours, iterations = iterations )\r\n# # The best state found is\r\nprint(f'Best state found is with {heuristic_n} heuristic value with {iterations} iterations:\\n {final_state}')\r\nif(count>10):\r\n print(f'Number of times heuristic {h} has occurred is: {count} times')\r\n print('Therefore, it is a PLATEAU condition')\r\n\r\n","repo_name":"se101/Artificial-Intelligence-Steepest-Ascent-Hill-Climbing","sub_path":"Steepest Ascent Hill Climbing Search.py","file_name":"Steepest Ascent Hill Climbing Search.py","file_ext":"py","file_size_in_byte":4325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"70983409399","text":"#creating different transaction on the database created in flat_out folder\n#transactions are defined in the TPC-E specification pdf. \n\nimport datagen as dg\nimport numpy as np\nimport pandas as pd\nimport random\nimport datetime\nsimulation_start_date = datetime.datetime.now()\n\n#############################Market Exchange Functions#########################\ndef nowTime():\n base_time = max(list(dg.TradeHistory['TH_DTS']))\n base_time = datetime.datetime.strptime(base_time,\"%Y-%m-%d %H:%M:%S.%f\")\n current_time = datetime.datetime.now()\n current_time = current_time - simulation_start_date + base_time\n return current_time\n\ndef marketPrice(symbol,trade_start):\n msPerPeriod = 900000000\n securityIndex = dg.Security.loc[dg.Security['S_SYMB'] == symbol].index.values[0]\n securityFactor =securityIndex*556237 + 253791\n trading_time = dg.LastTrade.loc[dg.LastTrade['LT_S_SYMB']==symbol,'LT_DTS'].values[0] \n trading_time = datetime.datetime.strptime(trading_time,\"%Y-%m-%d %H:%M:%S.%f\")\n current_time = nowTime()\n timesofar = current_time - trading_time\n timesofar = timesofar.seconds * 1000000 + timesofar.microseconds\n initialtime = (timesofar + securityFactor) % msPerPeriod\n initialtime = initialtime / 1000000\n ftime = current_time - trade_start\n ftime = ftime.seconds\n fperiodtime = (ftime + initialtime)/900\n ftimeinperiod = (fperiodtime - int(fperiodtime))*900\n if ftimeinperiod < (900/2):\n fPricePosition = ftimeinperiod / (900 / 2)\n else:\n fPricePosition = (900 - ftimeinperiod) / (900/ 2)\n price = 20 + 10*fPricePosition\n return price\n \n\n##########################profile creation#####################################\ndef createProfile(profile,trans,access_sequence =''):\n URV = ['o' for i in range(dg.URV_size)]\n if access_sequence == '':\n access_sequence = list(profile.keys())\n for feature in profile.keys():\n if dg.URV_feature_type[feature] == 'C':\n URV[dg.URV_feature_index[feature]] = len(set(profile[feature]))\n URV[dg.URV_feature_index[feature] + 1] = len(profile[feature])\n else:\n try:\n URV[dg.URV_feature_index[feature]] = np.mean(profile[feature])\n URV[dg.URV_feature_index[feature]+1] = np.median(profile[feature])\n URV[dg.URV_feature_index[feature]+3] = max(profile[feature])\n URV[dg.URV_feature_index[feature]+4] = min(profile[feature])\n except:\n continue\n urv_file = open('urv_file','a')\n urv_file.write(str(URV))\n urv_file.write(trans)\n urv_file.write('\\n')\n urv_file.close()\n \n spm_file = open('spm_file','a')\n spm_file.write(str(access_sequence))\n spm_file.write(trans)\n spm_file.write('\\n')\n spm_file.close()\n\n#####################BROKER VOLUME TRANSACTION################################# \n#broker manager \ndef brokervolume():\n profile = {'B_ID':[],'SC_ID':[],'SC_NAME':[],'IN_SC_ID':[],'IN_ID':[],\n 'CO_IN_ID':[],'CO_ID':[],'S_CO_ID':[],'S_SYMB':[],'TR_B_ID':[],\n 'TR_S_SYMB':[],'TR_QTY':[],'TR_BID_PRICE':[]}\n access_sequence = []\n min_broker_len = 5\n max_broker_len = 10\n broker_len = np.random.randint(min_broker_len,max_broker_len+1)\n brokers = list(dg.Broker['B_ID'])\n for i in range (max_broker_len - broker_len):\n del brokers[np.random.randint(len(brokers))]\n \n profile['B_ID'].extend(brokers)\n \n sectors = list(dg.Sector['SC_ID'])\n sector_id = sectors[np.random.randint(len(sectors))]\n sector_name = dg.Sector.loc[dg.Sector['SC_ID'] == sector_id,'SC_NAME'].values[0]\n \n profile['SC_ID'].extend(list(sector_id))\n profile['SC_NAME'].append(sector_name)\n access_sequence.extend(['B_ID','SC_ID','SC_NAME']) \n volume = []\n \n industry_id = list(dg.Industry.loc[dg.Industry['IN_SC_ID'] == sector_id,'IN_ID'])\n profile['IN_SC_ID'].extend(list(sector_id))\n profile['IN_ID'].extend(industry_id)\n company = dg.Company.loc[dg.Company['CO_IN_ID'].isin(industry_id),['CO_IN_ID','CO_ID']]\n company_id = list(company['CO_ID'])\n profile['CO_IN_ID'].extend(list(company['CO_IN_ID']))\n profile['CO_ID'].extend(company_id)\n security = dg.Security.loc[dg.Security['S_CO_ID'].isin(company_id),['S_CO_ID','S_SYMB']]\n security_symbol = list(security['S_SYMB'])\n profile['S_CO_ID'].extend(list(security['S_CO_ID']))\n profile['S_SYMB'].extend(security_symbol)\n access_sequnece.extend(['IN_SC_ID','IN_ID','CO_IN_ID','CO_ID','S_CO_ID','S_SYMB'])\n for broker in brokers:\n trade = dg.TradeRequest.loc[(dg.TradeRequest['TR_B_ID'] == broker) & (dg.TradeRequest['TR_S_SYMB'].isin(security_symbol) ),['TR_S_SYMB','TR_QTY','TR_BID_PRICE']]\n qty = trade['TR_QTY']\n price = trade['TR_BID_PRICE']\n profile['TR_B_ID'].append(broker)\n profile['TR_S_SYMB'].extend(list(trade['TR_S_SYMB']))\n profile['TR_QTY'].extend(list(qty))\n profile['TR_BID_PRICE'].extend(list(price))\n v = qty*price\n v = v.sum()\n volume.append(v)\n access_sequence.extend(['TR_B_ID','TR_S_SYMB','TR_QTY','TR_BID_PRICE'])\n \n createProfile(profile,' brokervolume',access_sequence)\n \n del industry_id,company_id,security_symbol,trade,qty,price,sectors\n return sector_name , brokers , volume\n\n############################CUSTOMER POSITION TRANSACTION######################\ndef customerposition(cust_id='', get_history='', tax_id='',account_id_idx=''):\n profile = {}\n access_sequence = []\n if cust_id == '' or get_history== '' or tax_id== '':\n print('parameter mising , choosing random parameters ###############')\n cust_id = np.random.randint(2)\n get_history = np.random.randint(2)\n if cust_id == 0:\n customers = list(dg.Customer['C_TAX_ID'])\n tax_id = customers[np.random.randint(len(customers))]\n profile['C_TAX_ID'] = [tax_id]\n cust_id = dg.Customer.loc[dg.Customer['C_TAX_ID']==tax_id,'C_ID'].values[0]\n profile['C_ID'] = [cust_id]\n else:\n customers = list(dg.Customer['C_ID'])\n cust_id = customers[np.random.randint(len(customers))]\n profile['C_ID'] = [cust_id]\n \n ###############################FRAME 2################################### \n if get_history == 1:\n if account_id_idx == '':\n account_id = list(dg.CustomerAccount.loc[dg.CustomerAccount['CA_C_ID']==cust_id,'CA_ID'])\n account_id_idx = account_id[np.random.randint(len(account_id))]\n profile['CA_C_ID'] = [cust_id]\n profile['CA_ID'] = [account_id_idx]\n \n trade = dg.Trade.loc[dg.Trade['T_CA_ID']==account_id_idx,['T_ID','T_CA_ID','T_S_SYMB','T_QTY','T_DTS']]\n trade = trade[::-1]\n trade = trade.iloc[:10]\n trade = trade[::-1]\n profile['T_ID'] = list(trade['T_ID'])\n profile['T_CA_ID'] = list(trade['T_CA_ID'])\n profile['T_S_SYMB'] = list(trade['T_S_SYMB'])\n profile['T_QTY'] = list(trade['T_QTY'])\n profile['T_DTS'] = list(trade['T_DTS'])\n access_sequence.extend(trade.columns)\n tradehistory = dg.TradeHistory.loc[dg.TradeHistory['TH_T_ID'].isin(list(trade['T_ID'])),['TH_T_ID','TH_ST_ID','TH_DTS']]\n tradehistory = tradehistory[::-1]\n tradehistory = tradehistory[:30]\n profile['TH_T_ID'] = list(tradehistory['TH_T_ID'])\n profile['TH_ST_ID'] = list(tradehistory['TH_ST_ID'])\n profile['TH_DTS'] = list(tradehistory['TH_DTS'])\n access_sequence.extend(tradehistory.columns)\n status = dg.StatusType.loc[dg.StatusType['ST_ID'].isin(list(tradehistory['TH_ST_ID'])),['ST_ID','ST_NAME']]\n result =trade.set_index('T_ID',drop=False).join(tradehistory.set_index('TH_T_ID',drop=False))\n result =result.set_index('TH_ST_ID',drop=False).join(status.set_index('ST_ID',drop=False))\n profile['ST_ID'] = list(result['ST_ID'])\n profile['ST_NAME'] = list(result['ST_NAME'])\n access_sequence.extend(result.columns)\n createProfile(profile,' customerposition '+str(cust_id),access_sequence)\n return cust_id,tax_id,account_id_idx,result[['T_ID','T_S_SYMB','T_QTY','ST_NAME','TH_DTS']]\n ######################################################################### \n \n customer_info = dg.Customer.loc[dg.Customer['C_ID']==cust_id,[ 'C_ST_ID',\n 'C_L_NAME','C_F_NAME','C_M_NAME','C_GNDR','C_TIER','C_DOB','C_AD_ID',\n 'C_CTRY_1','C_AREA_1','C_LOCAL_1','C_EXT_1','C_CTRY_2','C_AREA_2','C_LOCAL_2',\n 'C_EXT_2','C_CTRY_3','C_AREA_3','C_LOCAL_3','C_EXT_3','C_EMAIL_1','C_EMAIL_2']]\n profile['C_ST_ID'] = [customer_info['C_ST_ID'].values[0]]\n profile['C_L_NAME'] = [customer_info['C_L_NAME'].values[0]]\n profile['C_F_NAME'] = [customer_info['C_F_NAME'].values[0]]\n profile['C_M_NAME'] = [customer_info['C_M_NAME'].values[0]]\n profile['C_GNDR'] = [customer_info['C_GNDR'].values[0]]\n profile['C_TIER'] = [customer_info['C_TIER'].values[0]]\n profile['C_DOB'] = [customer_info['C_DOB'].values[0]]\n profile['C_AD_ID'] = [customer_info['C_AD_ID'].values[0]]\n profile['C_CTRY_1'] = [customer_info['C_CTRY_1'].values[0]]\n profile['C_AREA_1'] = [customer_info['C_AREA_1'].values[0]]\n profile['C_LOCAL_1'] = [customer_info['C_LOCAL_1'].values[0]]\n profile['C_EXT_1'] = [customer_info['C_EXT_1'].values[0]]\n profile['C_CTRY_2'] = [customer_info['C_CTRY_2'].values[0]]\n profile['C_AREA_2'] = [customer_info['C_AREA_2'].values[0]]\n profile['C_LOCAL_2'] = [customer_info['C_LOCAL_2'].values[0]]\n profile['C_EXT_2'] = [customer_info['C_EXT_2'].values[0]]\n profile['C_CTRY_3'] = [customer_info['C_CTRY_3'].values[0]]\n profile['C_AREA_3'] = [customer_info['C_AREA_3'].values[0]]\n profile['C_LOCAL_3'] = [customer_info['C_LOCAL_3'].values[0]]\n profile['C_EXT_3'] = [customer_info['C_EXT_3'].values[0]]\n profile['C_EMAIL_1'] = [customer_info['C_EMAIL_1'].values[0]]\n profile['C_EMAIL_2'] = [customer_info['C_EMAIL_2'].values[0]]\n access_sequence.append('C_ID')\n access_sequence.extend(customer_info.columns)\n customeraccount = dg.CustomerAccount.loc[dg.CustomerAccount['CA_C_ID']==cust_id,['CA_C_ID','CA_ID','CA_BAL']]\n account_id = list(customeraccount['CA_ID'])\n cash_balance = list(customeraccount['CA_BAL'])\n #max account length is 10\n if len(account_id)>10:\n del account_id[10:]\n del cash_balance[10:]\n \n profile['CA_C_ID'] = [cust_id for i in range(len(account_id))]\n profile['CA_ID'] = account_id\n profile['CA_BAL'] = cash_balance\n access_sequence.extend(customeraccount.columns)\n profile['HS_CA_ID'] = []\n profile['HS_S_SYMB'] = []\n profile['HS_QTY'] = []\n profile['LT_S_SYMB'] = []\n profile['LT_PRICE'] = []\n \n assets_total = []\n for account in account_id:\n holdingsummary = dg.HoldingSummary.loc[dg.HoldingSummary['HS_CA_ID'] == account,['HS_CA_ID','HS_QTY','HS_S_SYMB']]\n lasttrade = dg.LastTrade.loc[dg.LastTrade['LT_S_SYMB'].isin(list(holdingsummary['HS_S_SYMB'])),['LT_S_SYMB','LT_PRICE']]\n symbol = list(holdingsummary['HS_S_SYMB'])\n qty = list(holdingsummary['HS_QTY'])\n profile['HS_CA_ID'].extend(list(holdingsummary['HS_CA_ID'])) \n profile['HS_S_SYMB'].extend(symbol)\n profile['HS_QTY'].extend(qty)\n profile['LT_S_SYMB'].extend(list(lasttrade['LT_S_SYMB']))\n profile['LT_PRICE'].extend(list(lasttrade['LT_PRICE']))\n access_sequence.extend(holdingsummary.columns)\n access_sequence.extend(lasttrade.columns)\n asset = 0\n for i in range(len(symbol)):\n price = lasttrade.loc[lasttrade['LT_S_SYMB']==symbol[i],'LT_PRICE'].values[0]\n try:\n asset = asset + price * qty[i]\n except:\n continue\n assets_total.append(asset)\n \n createProfile(profile,\" customerposition \"+str(cust_id),access_sequence)\n return cust_id,tax_id,account_id,customer_info,cash_balance,assets_total\n\n############################MARKET FEED TRANSACTION############################\ndef marketfeed():\n profile = {}\n trade_start = min(list(dg.TradeHistory['TH_DTS']))\n trade_start = datetime.datetime.strptime(trade_start,\"%Y-%m-%d %H:%M:%S.%f\")\n current_time = nowTime()\n current_time_string = datetime.datetime.strftime(current_time,\"%Y-%m-%d %H:%M:%S.%f\")\n traderequest = dg.TradeRequest[['TR_S_SYMB','TR_QTY']]\n security = list(traderequest['TR_S_SYMB'])\n trade_qty = list(traderequest['TR_QTY'])\n '''security = random.sample(list(dg.Security['S_SYMB']),20)\n trade_qty = [np.random.randint(1,6) for i in range(20)]'''\n price_quote = []\n cntr = 0\n profile['LT_S_SYMB'] = []\n profile['LT_PRICE'] = []\n profile['LT_VOL'] = []\n profile['LT_DTS'] = []\n profile['TR_S_SYMB'] = security\n profile['TR_T_ID'] = list(dg.TradeRequest['TR_T_ID'])\n profile['TR_BID_PRICE'] = list(dg.TradeRequest['TR_BID_PRICE']) \n profile['TR_TT_ID'] = list(dg.TradeRequest['TR_TT_ID'])\n profile['TR_QTY'] = trade_qty\n profile['TR_T_ID'] = []\n profile['T_DTS'] = []\n profile['T_ST_ID'] = []\n profile[\"TH_T_ID\"] = []\n profile[\"TH_DTS\"] = []\n profile[\"TH_ST_ID\"] = []\n for symbol in security:\n price = marketPrice(symbol, trade_start)\n price_quote.append(price)\n index = dg.LastTrade['LT_S_SYMB']==symbol\n dg.LastTrade.loc[index,'LT_PRICE'] = price\n dg.LastTrade.loc[index,'LT_VOL'] += trade_qty[cntr]\n dg.LastTrade.loc[index,'LT_DTS'] = current_time_string\n profile['LT_S_SYMB'].append(symbol)\n profile['LT_PRICE'].append(price)\n profile['LT_VOL'].append(dg.LastTrade.loc[index,'LT_VOL'].values[0])\n profile['LT_DTS'].append(current_time_string)\n tradehappen = dg.TradeRequest.loc[(dg.TradeRequest['TR_S_SYMB']==symbol) & (\n ((dg.TradeRequest['TR_TT_ID']=='TSL')&(dg.TradeRequest['TR_BID_PRICE']>=price))\n | ((dg.TradeRequest['TR_TT_ID']=='TLS')&(dg.TradeRequest['TR_BID_PRICE']<=price))\n | ((dg.TradeRequest['TR_TT_ID']=='TLB')&(dg.TradeRequest['TR_BID_PRICE']>=price))\n ),['TR_T_ID','TR_BID_PRICE','TR_TT_ID','TR_QTY']]\n if tradehappen.shape[0] != 0 :\n trade_id = tradehappen['TR_T_ID'].values[0]\n index = dg.Trade['T_ID'] == trade_id\n dg.Trade.loc[index,'T_DTS'] = current_time_string\n dg.Trade.loc[index,'T_ST_ID'] = 'SBMT'\n profile['TR_T_ID'].append(trade_id)\n profile['T_DTS'].append(current_time_string)\n profile['T_ST_ID'].append('SBMT')\n history = pd.DataFrame({\"TH_T_ID\":[trade_id],\"TH_DTS\":[current_time_string],\"TH_ST_ID\":['SBMT']})\n profile[\"TH_T_ID\"].append(trade_id)\n profile[\"TH_DTS\"].append(current_time_string)\n profile[\"TH_ST_ID\"].append('SBMT')\n dg.TradeHistory = dg.TradeHistory.append(history)\n request_index = tradehappen.index.values[0]\n dg.TradeRequest.drop(index = request_index,inplace = True)\n cntr += 1\n \n createProfile(profile, \" marketfeed\")\n return len(security)\n \n ############################MARKET WATCH TRANSACTION###########################\ndef marketwatch(acct_id=0,cust_id=0,industry_name='',ending_co_id=0,starting_co_id=0,start_date=''):\n profile = {}\n if acct_id==0 and cust_id==0 and industry_name=='':\n sel = np.random.uniform(0,1,1)\n if sel<0.35:\n group = np.random.randint(2)\n if group == 0:\n customers = list(dg.Customer['C_ID'])\n else:\n tier = np.random.randint(1,4)\n customers = list(dg.Customer.loc[dg.Customer['C_TIER']==tier,'C_ID'])\n cust_id = customers[np.random.randint(len(customers))]\n accounts = list(dg.CustomerAccount.loc[dg.CustomerAccount['CA_C_ID']==cust_id,'CA_ID'])\n acct_id = accounts[np.random.randint(len(accounts))]\n elif sel<0.95:\n group = np.random.randint(2)\n if group == 0:\n customers = list(dg.Customer['C_ID'])\n else:\n tier = np.random.randint(1,4)\n customers = list(dg.Customer.loc[dg.Customer['C_TIER']==tier,'C_ID'])\n cust_id = customers[np.random.randint(len(customers))]\n else:\n industries = list(dg.Industry['IN_NAME'])\n industry_name = industries[np.random.randint(len(industries))]\n \n if acct_id !=0:\n stock_list = list(dg.HoldingSummary.loc[dg.HoldingSummary['HS_CA_ID']==acct_id,'HS_S_SYMB'])\n profile['HS_CA_ID'] = [acct_id for i in range(len(stock_list))]\n profile['HS_S_SYMB'] = stock_list\n elif cust_id !=0:\n watch_id = dg.WatchList.loc[dg.WatchList['WL_C_ID']==cust_id,'WL_ID'].values[0]\n stock_list = list(dg.WatchItem.loc[dg.WatchItem['WI_WL_ID']==watch_id,'WI_S_SYMB'])\n profile['WL_C_ID'] = [cust_id]\n profile['WL_ID'] = [watch_id]\n profile['WI_WL_ID'] = [watch_id for i in range(len(stock_list))]\n profile['WI_S_SYMB'] = stock_list\n elif industry_name!='':\n industry_id = dg.Industry.loc[dg.Industry['IN_NAME']==industry_name,'IN_ID'].values[0]\n profile['IN_NAME'] = industry_name\n profile['IN_ID'] = industry_id\n company_id = list(dg.Company.loc[dg.Company['CO_IN_ID']==industry_id,'CO_ID'])\n if ending_co_id!=0:\n company_id = np.array(company_id)\n company_id = company_id[(company_id >= starting_co_id) & (company_id<= ending_co_id)]\n company_id = list(company_id)\n profile['CO_IN_ID'] = [industry_id for i in range(len(company_id))]\n profile['CO_ID'] = company_id\n security = dg.Security.loc[dg.Security['S_CO_ID'].isin(company_id),['S_CO_ID','S_SYMB']]\n stock_list = list(security['S_SYMB'])\n profile['S_CO_ID'] = list(security['S_CO_ID'])\n \n profile['S_SYMB'] = stock_list\n profile['LT_PRICE'] = []\n profile['LT_S_SYMB'] = stock_list\n profile['S_NUM_OUT'] = []\n profile['DM_DATE'] = []\n profile['DM_S_SYMB'] = stock_list\n profile['DM_CLOSE'] = []\n \n old_mkt_cap = 0.00\n new_mkt_cap = 0.00\n pct_change = 0.00\n \n for symbol in stock_list:\n try:\n new_price = dg.LastTrade.loc[dg.LastTrade['LT_S_SYMB'] == symbol,'LT_PRICE'].values[0]\n s_num_out = dg.Security.loc[dg.Security['S_SYMB'] == symbol,'S_NUM_OUT'].values[0]\n if start_date == '':\n date_index = 1 + int(np.random.exponential(1))\n if date_index > 1305 :\n date_index = 1305\n date = list(dg.DailyMarket['DM_DATE'])\n start_date = date[0-date_index]\n old_price = dg.DailyMarket.loc[(dg.DailyMarket['DM_DATE'] == start_date) & (dg.DailyMarket['DM_S_SYMB'] == symbol),'DM_CLOSE'].values[0]\n old_mkt_cap += s_num_out * old_price\n new_mkt_cap += s_num_out * new_price\n profile['LT_PRICE'].append(new_price)\n profile['S_NUM_OUT'].append(s_num_out)\n profile['DM_DATE'].append(start_date)\n profile['DM_CLOSE'].append(old_price)\n except:\n old_mkt_cap = 0.00\n if old_mkt_cap != 0.00:\n pct_change = 100 * (new_mkt_cap / old_mkt_cap - 1)\n \n createProfile(profile, ' marketwatch ' + str(cust_id) + '' + str(acct_id) )\n return acct_id,cust_id,industry_name,ending_co_id,starting_co_id,start_date,pct_change\n\n############################SECURITY DETAIL TRANSACTION########################\ndef securitydetail(access_lob_flag = '',max_rows_to_return = '',start_day = '',symbol = ''):\n profile = {}\n if symbol == '':\n security = list(dg.Security['S_SYMB'])\n symbol = security[np.random.randint(len(security))]\n security = dg.Security.loc[dg.Security['S_SYMB'] == symbol,['S_CO_ID',\n 'S_NAME','S_NUM_OUT','S_START_DATE','S_EXCH_DATE','S_PE','S_52WK_HIGH',\n 'S_52WK_HIGH_DATE','S_52WK_LOW','S_52WK_LOW_DATE','S_DIVIDEND','S_YIELD','S_EX_ID']]\n profile['S_SYMB'] = [symbol]\n profile['S_CO_ID'] = [security['S_CO_ID'].values[0]]\n profile['S_NAME'] = [security['S_NAME'].values[0]]\n profile['S_NUM_OUT'] = [security['S_NUM_OUT'].values[0]]\n profile['S_START_DATE'] = [security['S_START_DATE'].values[0]]\n profile['S_EXCH_DATE'] = [security['S_EXCH_DATE'].values[0]]\n profile['S_PE'] = [security['S_PE'].values[0]]\n profile['S_52WK_HIGH'] = [security['S_52WK_HIGH'].values[0]]\n profile['S_52WK_HIGH_DATE'] = [security['S_52WK_HIGH_DATE'].values[0]]\n profile['S_52WK_LOW'] = [security['S_52WK_LOW'].values[0]]\n profile['S_52WK_LOW_DATE'] = [security['S_52WK_LOW_DATE'].values[0]]\n profile['S_DIVIDEND'] = [security['S_DIVIDEND'].values[0]]\n profile['S_YIELD'] = [security['S_YIELD'].values[0]]\n profile['S_EX_ID'] = [security['S_EX_ID'].values[0]]\n company = dg.Company.loc[dg.Company['CO_ID'] == int(security['S_CO_ID']),[\n 'CO_ID','CO_AD_ID','CO_NAME','CO_SP_RATE','CO_CEO','CO_DESC','CO_OPEN_DATE',\n 'CO_ST_ID']]\n profile['CO_ID'] = [company['CO_ID'].values[0]]\n profile['CO_AD_ID'] = [company['CO_AD_ID'].values[0]]\n profile['CO_NAME'] = [company['CO_NAME'].values[0]]\n profile['CO_SP_RATE'] = [company['CO_SP_RATE'].values[0]]\n profile['CO_CEO'] = [company['CO_CEO'].values[0]]\n profile['CO_DESC'] = [company['CO_DESC'].values[0]]\n profile['CO_OPEN_DATE'] = [company['CO_OPEN_DATE'].values[0]]\n profile['CO_ST_ID'] = [company['CO_ST_ID'].values[0]]\n exchange = dg.Exchange.loc[dg.Exchange['EX_ID'] == security['S_EX_ID'].values[0],\n ['EX_AD_ID','EX_CLOSE','EX_DESC','EX_NAME','EX_NUM_SYMB','EX_OPEN']]\n profile['EX_ID'] = [security['S_EX_ID'].values[0]]\n profile['EX_AD_ID'] = [exchange['EX_AD_ID'].values[0]]\n profile['EX_CLOSE'] = [exchange['EX_CLOSE'].values[0]]\n profile['EX_DESC'] = [exchange['EX_DESC'].values[0]]\n profile['EX_NAME'] = [exchange['EX_NAME'].values[0]]\n profile['EX_NUM_SYMB'] = [exchange['EX_NUM_SYMB'].values[0]]\n profile['EX_OPEN'] = [exchange['EX_OPEN'].values[0]]\n ca_address = dg.Address.loc[dg.Address['AD_ID'] == company['CO_AD_ID'].values[0],\n [\"AD_ID\", \"AD_LINE1\",\"AD_LINE2\",\"AD_ZC_CODE\",\"AD_CTRY\"]]\n profile[\"AD_ID\"] = [ca_address[\"AD_ID\"].values[0]]\n profile[\"AD_LINE1\"] = [ca_address[\"AD_LINE1\"].values[0]]\n profile[\"AD_LINE2\"] = [ca_address[\"AD_LINE2\"].values[0]]\n profile[\"AD_ZC_CODE\"] = [ca_address[\"AD_ZC_CODE\"].values[0]]\n profile[\"AD_CTRY\"] = [ca_address[\"AD_CTRY\"].values[0]]\n ea_address = dg.Address.loc[dg.Address['AD_ID'] == exchange['EX_AD_ID'].values[0],\n [\"AD_ID\", \"AD_LINE1\",\"AD_LINE2\",\"AD_ZC_CODE\",\"AD_CTRY\"]]\n profile[\"AD_ID\"].append(ea_address[\"AD_ID\"].values[0])\n profile[\"AD_LINE1\"].append(ea_address[\"AD_LINE1\"].values[0])\n profile[\"AD_LINE2\"].append(ea_address[\"AD_LINE2\"].values[0])\n profile[\"AD_ZC_CODE\"].append(ea_address[\"AD_ZC_CODE\"].values[0])\n profile[\"AD_CTRY\"].append(ea_address[\"AD_CTRY\"].values[0])\n zca = dg.ZipCode.loc[dg.ZipCode['ZC_CODE'] == ca_address['AD_ZC_CODE'].values[0],\n [\"ZC_CODE\", \"ZC_TOWN\",\"ZC_DIV\"]]\n profile[\"ZC_CODE\"] = [zca[\"ZC_CODE\"].values[0]]\n profile[\"ZC_TOWN\"] = [zca[\"ZC_TOWN\"].values[0]]\n profile[\"ZC_DIV\"] = [zca[\"ZC_DIV\"].values[0]]\n zea = dg.ZipCode.loc[dg.ZipCode['ZC_CODE'] == ea_address['AD_ZC_CODE'].values[0],\n [\"ZC_CODE\", \"ZC_TOWN\",\"ZC_DIV\"]]\n profile[\"ZC_CODE\"].append(zea[\"ZC_CODE\"].values[0])\n profile[\"ZC_TOWN\"].append(zea[\"ZC_TOWN\"].values[0])\n profile[\"ZC_DIV\"].append(zea[\"ZC_DIV\"].values[0])\n competitor = dg.CompanyCompetitor.loc[dg.CompanyCompetitor['CP_CO_ID'] == \n company['CO_ID'].values[0],[\"CP_CO_ID\", \"CP_COMP_CO_ID\",\"CP_IN_ID\"]]\n profile[\"CP_CO_ID\"] = list(competitor[\"CP_CO_ID\"].values)\n profile[\"CP_COMP_CO_ID\"] = list(competitor[\"CP_COMP_CO_ID\"].values)\n profile[\"CP_IN_ID\"] = list(competitor[\"CP_IN_ID\"].values)\n cp_co_name = []\n cp_in_name = []\n for row in competitor.iterrows():\n co_name = dg.Company.loc[dg.Company['CO_ID'] == row[1]['CP_COMP_CO_ID'],'CO_NAME'].values[0]\n in_name = dg.Industry.loc[dg.Industry['IN_ID'] == row[1]['CP_IN_ID'],'IN_NAME'].values[0]\n cp_co_name.append(co_name)\n cp_in_name.append(in_name)\n profile['CO_ID'].extend(list(competitor[\"CP_COMP_CO_ID\"].values))\n profile['CO_NAME'] = cp_co_name\n profile['IN_ID'] = list(competitor[\"CP_IN_ID\"].values)\n profile['IN_NAME'] = cp_in_name\n financial = dg.Financial.loc[dg.Financial['FI_CO_ID']==company['CO_ID'].values[0],\n [\"FI_CO_ID\",\"FI_YEAR\",\"FI_QTR\",\"FI_OTR_START_DATE\",\"FI_REVENUE\",\"FI_NET_EARN\",\n \"FI_BASIC_EPS\",\"FI_DILUT_EPS\",\"FI_MARGIN\",\"FI_INVENTORY\",\"FI_ASSETS\",\"FI_LIABILITY\"\n ,\"FI_OUT_BASIC\",\"FI_OUT_DILUT\"]]\n financial = financial[:20]\n profile[\"FI_CO_ID\" ]= list(financial[\"FI_CO_ID\"].values)\n profile[\"FI_YEAR\"] = list(financial[\"FI_YEAR\"].values)\n profile[\"FI_QTR\"] = list(financial[\"FI_QTR\"].values)\n profile[\"FI_OTR_START_DATE\"] = list(financial[\"FI_OTR_START_DATE\"].values)\n profile[\"FI_REVENUE\"] = list(financial[\"FI_REVENUE\"].values)\n profile[\"FI_NET_EARN\"] = list(financial[\"FI_NET_EARN\"].values)\n profile[\"FI_BASIC_EPS\"] = list(financial[\"FI_BASIC_EPS\"].values)\n profile[\"FI_DILUT_EPS\"] = list(financial[\"FI_DILUT_EPS\"].values)\n profile[\"FI_MARGIN\"] = list(financial[\"FI_MARGIN\"].values)\n profile[\"FI_INVENTORY\"] = list(financial[\"FI_INVENTORY\"].values)\n profile[\"FI_ASSETS\"] = list(financial[\"FI_ASSETS\"].values)\n profile[\"FI_LIABILITY\"] = list(financial[\"FI_LIABILITY\"].values)\n profile[\"FI_OUT_BASIC\"] = list(financial[\"FI_OUT_BASIC\"].values)\n profile[\"FI_OUT_DILUT\"] = list(financial[\"FI_OUT_DILUT\"].values)\n if max_rows_to_return == '':\n max_rows_to_return = np.random.randint(5,21)\n if start_day == '':\n date = list(dg.DailyMarket['DM_DATE'])\n start_day = date[np.random.randint(len(date)-max_rows_to_return)]\n dailymarket = dg.DailyMarket.loc[(dg.DailyMarket['DM_S_SYMB'] == symbol) \n & (dg.DailyMarket['DM_DATE']>=start_day),['DM_S_SYMB','DM_DATE','DM_CLOSE','DM_HIGH',\n 'DM_LOW','DM_VOL']].head(max_rows_to_return)\n profile['DM_S_SYMB'] = list(dailymarket['DM_S_SYMB'].values)\n profile['DM_DATE'] = list(dailymarket['DM_DATE'].values)\n profile['DM_CLOSE'] = list(dailymarket['DM_CLOSE'].values)\n profile['DM_HIGH'] = list(dailymarket['DM_HIGH'].values)\n profile['DM_LOW'] = list(dailymarket['DM_LOW'].values)\n profile['DM_VOL'] = list(dailymarket['DM_VOL'].values)\n lasttrade = dg.LastTrade.loc[dg.LastTrade['LT_S_SYMB']==symbol,['LT_S_SYMB','LT_PRICE',\n 'LT_OPEN_PRICE','LT_VOL']]\n profile['LT_S_SYMB'] = list(lasttrade['LT_S_SYMB'].values)\n profile['LT_PRICE'] = list(lasttrade['LT_PRICE'].values)\n profile['LT_OPEN_PRICE'] = list(lasttrade['LT_OPEN_PRICE'].values)\n profile['LT_VOL'] = list(lasttrade['LT_VOL'].values)\n if access_lob_flag == '':\n prob = random.uniform(0,1)\n if prob < 0.99 :\n access_lob_flag = 0\n else:\n access_lob_flag = 1\n if access_lob_flag == 1:\n newsxref = dg.NewsXRef.loc[dg.NewsXRef['NX_CO_ID'] == company['CO_ID'].values[0],\n ['NX_CO_ID','NX_NI_ID']].head(2)\n profile['NX_CO_ID'] = list(newsxref['NX_CO_ID'].values)\n profile['NX_NI_ID'] = list(newsxref['NX_NI_ID'].values)\n newsitem = dg.NewsItem.loc[dg.NewsItem['NI_ID'].isin(list(newsxref['NX_NI_ID'])),\n ['NI_ID','NI_ITEM','NI_DTS','NI_SOURCE','NI_AUTHOR']]\n profile['NI_ID'] = list(newsitem['NI_ID'].values)\n profile['NI_ITEM'] = list(newsitem['NI_ITEM'].values)\n profile['NI_DTS'] = list(newsitem['NI_DTS'].values)\n profile['NI_SOURCE'] = list(newsitem['NI_SOURCE'].values)\n profile['NI_AUTHOR'] = list(newsitem['NI_AUTHOR'].values)\n else:\n newsxref = dg.NewsXRef.loc[dg.NewsXRef['NX_CO_ID'] == company['CO_ID'].values[0],\n ['NX_CO_ID','NX_NI_ID']].head(2)\n profile['NX_CO_ID'] = list(newsxref['NX_CO_ID'].values)\n profile['NX_NI_ID'] = list(newsxref['NX_NI_ID'].values)\n newsitem = dg.NewsItem.loc[dg.NewsItem['NI_ID'].isin(list(newsxref['NX_NI_ID'])),\n ['NI_ID','NI_DTS','NI_SOURCE','NI_AUTHOR','NI_HEADLINE','NI_SUMMARY']]\n profile['NI_ID'] = list(newsitem['NI_ID'].values)\n profile['NI_DTS'] = list(newsitem['NI_DTS'].values)\n profile['NI_SOURCE'] = list(newsitem['NI_SOURCE'].values)\n profile['NI_AUTHOR'] = list(newsitem['NI_AUTHOR'].values)\n profile['NI_HEADLINE'] = list(newsitem['NI_HEADLINE'].values)\n profile['NI_SUMMARY'] = list(newsitem['NI_SUMMARY'].values)\n \n createProfile(profile, \" securitydetail\")\n \n return access_lob_flag,start_day,symbol,max_rows_to_return,security,company,\n exchange,ca_address,ea_address,zca,zea,cp_co_name,cp_in_name,financial,dailymarket,\n lasttrade,newsitem\n\n###############################TRADE LOOKUP TRANSACTION########################\ndef tradelookup(acct_id=0,end_trade_dts='',frame_to_execute='',max_acct_id=0,max_trades=0,start_trade_dts='',symbol='',trade_id=[]):\n if frame_to_execute=='':\n prob=random.uniform(0,1)\n if prob < 0.30:\n frame_to_execute = 1\n elif prob < 0.60:\n frame_to_execute = 2\n elif prob < 0.90:\n frame_to_execute = 3\n else:\n frame_to_execute = 4\n\n profile = {}\n if frame_to_execute==1:\n if max_trades == 0:\n max_trades = 20\n trade_id=random.sample(list(dg.Trade['T_ID']),max_trades)\n trade=dg.Trade.loc[dg.Trade['T_ID'].isin(trade_id),['T_ID','T_BID_PRICE',\n 'T_EXEC_NAME','T_IS_CASH','T_TRADE_PRICE','T_TT_ID']]\n trade_type = dg.TradeType.loc[dg.TradeType['TT_ID'].isin(list(trade['T_TT_ID'])),\n ['TT_ID','TT_IS_MRKT']]\n trade = trade.set_index('T_TT_ID',drop = False).join(trade_type.set_index('TT_ID',drop = False))\n profile['T_ID'] = list(trade['T_ID'].values)\n profile['T_BID_PRICE'] = list(trade['T_BID_PRICE'].values)\n profile['T_EXEC_NAME'] = list(trade['T_EXEC_NAME'].values)\n profile['T_IS_CASH'] = list(trade['T_IS_CASH'].values)\n profile['T_TRADE_PRICE'] = list(trade['T_TRADE_PRICE'].values)\n profile['T_TT_ID'] = list(trade['T_TT_ID'].values)\n profile['TT_ID'] = list(trade['TT_ID'].values)\n profile['TT_IS_MRKT'] = list(trade['TT_IS_MRKT'].values)\n settlement=dg.Settlement.loc[dg.Settlement['SE_T_ID'].isin(trade_id),\n ['SE_AMT','SE_CASH_DUE_DATE','SE_CASH_TYPE']]\n profile['SE_T_ID'] = trade_id\n profile['SE_AMT'] = list(settlement['SE_AMT'].values)\n profile['SE_CASH_DUE_DATE'] = list(settlement['SE_CASH_DUE_DATE'].values)\n profile['SE_CASH_TYPE'] = list(settlement['SE_CASH_TYPE'].values)\n cash = pd.DataFrame()\n for row in trade.iterrows():\n tid = row[1]['T_ID']\n tcash = row[1]['T_IS_CASH']\n if tcash==1:\n iscash = dg.CashTransaction.loc[dg.CashTransaction['CT_T_ID']==tid,['CT_T_ID','CT_AMT','CT_DTS','CT_NAME']]\n cash = cash.append(iscash)\n profile['CT_T_ID'] = list(cash['CT_T_ID'].values)\n profile['CT_AMT'] = list(cash['CT_AMT'].values)\n profile['CT_DTS'] = list(cash['CT_DTS'].values)\n profile['CT_NAME'] = list(cash['CT_NAME'].values)\n tradehistory = dg.TradeHistory.loc[dg.TradeHistory['TH_T_ID'].isin(trade_id),['TH_T_ID','TH_DTS','TH_ST_ID']]\n profile['TH_T_ID'] = list(tradehistory['TH_T_ID'].values)\n profile['TH_DTS'] = list(tradehistory['TH_DTS'].values)\n profile['TH_ST_ID'] = list(tradehistory['TH_ST_ID'].values) \n \n createProfile(profile,\" tradelookup \" + str(1))\n return frame_to_execute , max_trades , trade_id , trade , settlement , cash , tradehistory\n\n elif frame_to_execute == 2:\n if max_trades == 0:\n max_trades = 20\n group = np.random.randint(2)\n if group == 0:\n customers = list(dg.Customer['C_ID'])\n else:\n tier = np.random.randint(1,4)\n customers = list(dg.Customer.loc[dg.Customer['C_TIER']==tier,'C_ID'])\n cust_id = customers[np.random.randint(len(customers))]\n accounts = list(dg.CustomerAccount.loc[dg.CustomerAccount['CA_C_ID']==cust_id,'CA_ID'])\n acct_id = accounts[np.random.randint(len(accounts))]\n date=random.sample(list(dg.Trade['T_DTS']),2)\n start_trade_dts = min(date)\n end_trade_dts = max(date)\n trade = dg.Trade.loc[(dg.Trade['T_DTS']>=start_trade_dts) & \n (dg.Trade['T_DTS']<=end_trade_dts) & (dg.Trade['T_CA_ID']==acct_id) ,\n ['T_CA_ID','T_BID_PRICE','T_EXEC_NAME','T_IS_CASH','T_ID','T_TRADE_PRICE'\n ,'T_DTS']]\n trade = trade[:max_trades]\n trade_id = list(trade['T_ID'])\n profile['T_DTS'] = list(trade['T_DTS'].values)\n profile['T_CA_ID'] = list(trade['T_CA_ID'].values)\n profile['T_BID_PRICE'] = list(trade['T_BID_PRICE'].values)\n profile['T_EXEC_NAME'] = list(trade['T_EXEC_NAME'].values)\n profile['T_IS_CASH'] = list(trade['T_IS_CASH'].values)\n profile['T_ID'] = list(trade['T_ID'].values)\n profile['T_TRADE_PRICE'] = list(trade['T_TRADE_PRICE'].values)\n settlement=dg.Settlement.loc[dg.Settlement['SE_T_ID'].isin(trade_id),\n ['SE_AMT','SE_CASH_DUE_DATE','SE_CASH_TYPE']]\n profile['SE_T_ID'] = trade_id\n profile['SE_AMT'] = list(settlement['SE_AMT'].values)\n profile['SE_CASH_DUE_DATE'] = list(settlement['SE_CASH_DUE_DATE'].values)\n profile['SE_CASH_TYPE'] = list(settlement['SE_CASH_TYPE'].values)\n cash = pd.DataFrame()\n for row in trade.iterrows():\n tid = row[1]['T_ID']\n tcash = row[1]['T_IS_CASH']\n if tcash==1:\n iscash = dg.CashTransaction.loc[dg.CashTransaction['CT_T_ID']==tid,['CT_T_ID','CT_AMT','CT_DTS','CT_NAME']]\n cash = cash.append(iscash)\n profile['CT_T_ID'] = list(cash['CT_T_ID'].values)\n profile['CT_AMT'] = list(cash['CT_AMT'].values)\n profile['CT_DTS'] = list(cash['CT_DTS'].values)\n profile['CT_NAME'] = list(cash['CT_NAME'].values)\n tradehistory = dg.TradeHistory.loc[dg.TradeHistory['TH_T_ID'].isin(trade_id),['TH_T_ID','TH_DTS','TH_ST_ID']]\n profile['TH_T_ID'] = list(tradehistory['TH_T_ID'].values)\n profile['TH_DTS'] = list(tradehistory['TH_DTS'].values)\n profile['TH_ST_ID'] = list(tradehistory['TH_ST_ID'].values)\n \n createProfile(profile,\" tradelookup \" + str(2) + \" \" + str(acct_id))\n return frame_to_execute , max_trades , acct_id , start_trade_dts , end_trade_dts, trade , settlement , cash , tradehistory\n\n elif frame_to_execute == 3:\n if max_trades==0:\n max_trades = 20\n security = list(dg.Security['S_SYMB'])\n symbol = security[np.random.randint(len(security))] \n date=random.sample(list(dg.Trade['T_DTS']),2)\n start_trade_dts = min(date)\n end_trade_dts = max(date)\n trade = dg.Trade.loc[(dg.Trade['T_DTS']>=start_trade_dts) & \n (dg.Trade['T_DTS']<=end_trade_dts) & (dg.Trade['T_S_SYMB']==symbol) ,\n ['T_S_SYMB','T_CA_ID','T_EXEC_NAME','T_IS_CASH','T_ID','T_TRADE_PRICE',\n 'T_QTY','T_TT_ID','T_DTS']]\n trade = trade[:max_trades]\n trade_id = list(trade['T_ID'])\n profile['T_DTS'] = list(trade['T_DTS'].values)\n profile['T_S_SYMB'] = list(trade['T_S_SYMB'].values)\n profile['T_CA_ID'] = list(trade['T_CA_ID'].values)\n profile['T_EXEC_NAME'] = list(trade['T_EXEC_NAME'].values)\n profile['T_IS_CASH'] = list(trade['T_IS_CASH'].values)\n profile['T_ID'] = list(trade['T_ID'].values)\n profile['T_TRADE_PRICE'] = list(trade['T_TRADE_PRICE'].values)\n profile['T_QTY'] = list(trade['T_QTY'].values)\n profile['T_TT_ID'] = list(trade['T_TT_ID'].values)\n settlement=dg.Settlement.loc[dg.Settlement['SE_T_ID'].isin(trade_id),\n ['SE_AMT','SE_CASH_DUE_DATE','SE_CASH_TYPE']]\n profile['SE_T_ID'] = trade_id\n profile['SE_AMT'] = list(settlement['SE_AMT'].values)\n profile['SE_CASH_DUE_DATE'] = list(settlement['SE_CASH_DUE_DATE'].values)\n profile['SE_CASH_TYPE'] = list(settlement['SE_CASH_TYPE'].values)\n cash = pd.DataFrame()\n for row in trade.iterrows():\n tid = row[1]['T_ID']\n tcash = row[1]['T_IS_CASH']\n if tcash==1:\n iscash = dg.CashTransaction.loc[dg.CashTransaction['CT_T_ID']==tid,['CT_T_ID','CT_AMT','CT_DTS','CT_NAME']]\n cash = cash.append(iscash)\n profile['CT_T_ID'] = list(cash['CT_T_ID'].values)\n profile['CT_AMT'] = list(cash['CT_AMT'].values)\n profile['CT_DTS'] = list(cash['CT_DTS'].values)\n profile['CT_NAME'] = list(cash['CT_NAME'].values)\n tradehistory = dg.TradeHistory.loc[dg.TradeHistory['TH_T_ID'].isin(trade_id),['TH_T_ID','TH_DTS','TH_ST_ID']]\n profile['TH_T_ID'] = list(tradehistory['TH_T_ID'].values)\n profile['TH_DTS'] = list(tradehistory['TH_DTS'].values)\n profile['TH_ST_ID'] = list(tradehistory['TH_ST_ID'].values)\n \n createProfile(profile,\" tradelookup \" + str(3))\n return frame_to_execute , max_trades , symbol , start_trade_dts , end_trade_dts, trade , settlement , cash , tradehistory\n \n elif frame_to_execute==4:\n if max_trades == 0:\n max_trades = 20\n group = np.random.randint(2)\n if group == 0:\n customers = list(dg.Customer['C_ID'])\n else:\n tier = np.random.randint(1,4)\n customers = list(dg.Customer.loc[dg.Customer['C_TIER']==tier,'C_ID'])\n cust_id = customers[np.random.randint(len(customers))]\n accounts = list(dg.CustomerAccount.loc[dg.CustomerAccount['CA_C_ID']==cust_id,'CA_ID'])\n acct_id = accounts[np.random.randint(len(accounts))]\n date=random.sample(list(dg.Trade['T_DTS']),2)\n start_trade_dts = date[0]\n trade_id = dg.Trade.loc[(dg.Trade['T_DTS']>=start_trade_dts) & \n (dg.Trade['T_CA_ID']==acct_id) ,'T_ID'][:1].values[0]\n profile['T_CA_ID'] = [acct_id]\n profile['T_DTS'] = [start_trade_dts]\n profile['T_ID'] = [trade_id]\n holdinghistory_id = dg.HoldingHistory.loc[dg.HoldingHistory['HH_T_ID']==trade_id,'HH_H_T_ID'].values[0]\n holdinghistory = dg.HoldingHistory.loc[dg.HoldingHistory['HH_H_T_ID']==holdinghistory_id,['HH_H_T_ID',\n 'HH_T_ID','HH_BEFORE_QTY','HH_AFTER_QTY']][:max_trades]\n profile['HH_T_ID'] = list(holdinghistory['HH_T_ID'].values)\n profile['HH_H_T_ID'] = list(holdinghistory['HH_H_T_ID'].values)\n profile['HH_BEFORE_QTY'] = list(holdinghistory['HH_BEFORE_QTY'].values)\n profile['HH_AFTER_QTY'] = list(holdinghistory['HH_AFTER_QTY'].values)\n \n createProfile(profile,\" tradelookup \" + str(2) + \" \" + str(acct_id))\n return frame_to_execute , max_trades , acct_id , start_trade_dts , trade_id , holdinghistory\n\n###############################TRADE ORDER TRANSACTION#########################\ndef tradeorder(acct_id = '',exec_f_name='',exec_l_name='',exec_tax_id='',is_lifo='',co_name ='',issue='',symbol='',trade_type_id='', trade_qty='',type_is_margin='',roll_it_back='',requested_price=''):\n\n profile = {}\n if acct_id == '':\n group = np.random.randint(2)\n if group == 0:\n customers = list(dg.Customer['C_ID'])\n else:\n tier = np.random.randint(1,4)\n customers = list(dg.Customer.loc[dg.Customer['C_TIER']==tier,'C_ID'])\n cust_id = customers[np.random.randint(len(customers))]\n accounts = list(dg.CustomerAccount.loc[dg.CustomerAccount['CA_C_ID']==cust_id,'CA_ID'])\n acct_id = accounts[np.random.randint(len(accounts))]\n account = dg.CustomerAccount.loc[dg.CustomerAccount['CA_ID']==acct_id,\n ['CA_NAME','CA_C_ID','CA_B_ID','CA_TAX_ST']]\n tax_status = account['CA_TAX_ST'].values[0]\n profile['CA_ID'] = [acct_id]\n profile['CA_NAME'] = list(account['CA_NAME'].values)\n profile['CA_C_ID'] = list(account['CA_C_ID'].values)\n profile['CA_B_ID'] = list(account['CA_B_ID'].values)\n profile['CA_TAX_ST'] = list(account['CA_TAX_ST'].values)\n cust_id = account['CA_C_ID'].values[0]\n broker_id = account['CA_B_ID'].values[0]\n customer = dg.Customer.loc[dg.Customer['C_ID']==cust_id,['C_F_NAME',\n 'C_L_NAME','C_TIER','C_TAX_ID']]\n cust_tier = customer['C_TIER'].values[0]\n profile['C_ID'] = [cust_id]\n profile['C_F_NAME'] = list(customer['C_F_NAME'].values)\n profile['C_L_NAME'] = list(customer['C_L_NAME'].values)\n profile['C_TIER'] = list(customer['C_TIER'].values)\n profile['C_TAX_ID'] = list(customer['C_TAX_ID'].values)\n broker = dg.Broker.loc[dg.Broker['B_ID']==broker_id,'B_NAME']\n profile['B_ID'] = [broker_id]\n profile['B_NAME'] = list(broker.values)\n if exec_f_name == '':\n prob = random.uniform(0,1)\n if prob < 0.15:\n executioner = dg.AccountPermission.loc[dg.AccountPermission['AP_CA_ID']==acct_id,\n ['AP_F_NAME','AP_L_NAME','AP_TAX_ID']].values\n size = len(executioner)\n pos = np.random.randint(size)\n exec_f_name = executioner[pos][0]\n exec_l_name = executioner[pos][1]\n exec_tax_id = executioner[pos][2]\n else:\n exec_f_name = customer['C_F_NAME'].values[0]\n exec_l_name = customer['C_L_NAME'].values[0]\n exec_tax_id = customer['C_TAX_ID'].values[0]\n \n if ((exec_f_name != customer['C_F_NAME'].values[0])\n or (exec_l_name != customer['C_L_NAME'].values[0])\n or (exec_tax_id != customer['C_TAX_ID'].values[0])):\n executioner = dg.AccountPermission.loc[\n (dg.AccountPermission['AP_CA_ID']==acct_id)\n &(dg.AccountPermission['AP_F_NAME'] == exec_f_name)\n &(dg.AccountPermission['AP_L_NAME'] == exec_l_name)\n &(dg.AccountPermission['AP_TAX_ID'] == exec_f_name),\n ['AP_CA_ID','AP_F_NAME','AP_L_NAME','AP_TAX_ID','AP_ACL']]\n size = executioner.shape[0]\n profile['AP_CA_ID']=list(executioner['AP_CA_ID'].values)\n profile['AP_F_NAME']=list(executioner['AP_F_NAME'].values)\n profile['AP_L_NAME']=list(executioner['AP_L_NAME'].values)\n profile['AP_TAX_ID']=list(executioner['AP_TAX_ID'].values)\n profile['AP_ACL']=list(executioner['AP_ACL'].values)\n if size == 0:\n createProfile(profile,\" trade order no access\")\n '''return''' \"no access\"\n \n if symbol=='' and co_name=='':\n prob = random.uniform(0, 1)\n if prob<0.40:\n company = list(dg.Company['CO_NAME'])\n co_name = company[np.random.randint(len(company))]\n coid = dg.Company.loc[dg.Company['CO_NAME']==co_name,'CO_ID'].values[0]\n issue = list(dg.Security.loc[dg.Security['S_CO_ID']==coid,'S_ISSUE'].values)\n issue = issue[np.random.randint(len(issue))]\n else:\n security = list(dg.Security['S_SYMB'])\n symbol = security[np.random.randint(len(security))]\n if symbol =='':\n company_id = dg.Company.loc[dg.Company['CO_NAME']==co_name,'CO_ID'].values[0]\n profile['CO_NAME'] = [co_name]\n profile['CO_ID'] = [company_id]\n security = dg.Security.loc[(dg.Security['S_CO_ID']==company_id)\n &(dg.Security['S_ISSUE'] == issue),['S_EX_ID','S_NAME','S_SYMB']]\n symbol = security['S_SYMB'].values[0]\n profile['S_CO_ID'] = [company_id]\n profile['S_ISSUE'] = [issue]\n profile['S_EX_ID'] = list(security['S_EX_ID'].values)\n profile['S_NAME'] = list(security['S_NAME'].values)\n profile['S_SYMB'] = list(security['S_SYMB'].values)\n else:\n security = dg.Security.loc[dg.Security['S_SYMB']==symbol,\n ['S_CO_ID','S_EX_ID','S_NAME']]\n profile['S_SYMB'] = [symbol]\n profile['S_CO_ID'] = list(security['S_CO_ID'].values)\n profile['S_EX_ID'] = list(security['S_EX_ID'].values)\n profile['S_NAME'] = list(security['S_NAME'].values)\n company_id = security['S_CO_ID'].values[0]\n co_name = dg.Company.loc[dg.Company['CO_ID']==company_id,'CO_NAME'].values[0]\n profile['CO_ID'] = [company_id]\n profile['CO_NAME'] = [co_name]\n exch_id = security['S_EX_ID'].values[0]\n market_price = dg.LastTrade.loc[dg.LastTrade['LT_S_SYMB']==symbol,'LT_PRICE'].values[0]\n profile['LT_S_SYMB'] = [symbol]\n profile['LT_PRICE'] = [market_price]\n \n if trade_type_id =='':\n prob = random.uniform(0, 1)\n if prob<0.30:\n trade_type_id = 'TMB'\n elif prob<0.60:\n trade_type_id = 'TMS'\n elif prob<0.80:\n trade_type_id = 'TLB'\n elif prob<0.90:\n trade_type_id = 'TLS'\n else:\n trade_type_id = 'TSL'\n tradetype = dg.TradeType.loc[dg.TradeType['TT_ID']==trade_type_id,\n ['TT_IS_MRKT','TT_IS_SELL']]\n type_is_market = tradetype['TT_IS_MRKT'].values[0] \n type_is_sell = tradetype['TT_IS_SELL'].values[0]\n \n profile['TT_ID'] = [trade_type_id]\n profile['TT_IS_MRKT'] = [type_is_market]\n profile['TT_IS_SELL'] = [type_is_sell]\n \n if requested_price == '':\n requested_price = random.uniform(20,30)\n \n if type_is_market:\n requested_price = market_price\n \n if trade_qty == '' :\n trade_qty = 200*np.random.randint(1,5)\n needed_qty = trade_qty\n buy_value = 0.0\n sell_value = 0.0\n hs_qty = dg.HoldingSummary.loc[(dg.HoldingSummary['HS_CA_ID']==acct_id) & \n (dg.HoldingSummary['HS_S_SYMB']==symbol),'HS_QTY'].values\n if len(hs_qty) == 0:\n hs_qty = 0\n else:\n hs_qty = hs_qty[0]\n \n profile['H_CA_ID'] = [acct_id]\n profile['H_S_SYMB'] = [symbol]\n profile['H_QTY'] = hs_qty\n \n if is_lifo=='':\n prob = random.uniform(0,1)\n if prob < 0.35:\n is_lifo = 1\n else:\n is_lifo = 0\n \n if type_is_sell:\n if hs_qty>0:\n \n if is_lifo:\n holding = dg.Holding.loc[(dg.Holding['H_CA_ID']==acct_id) & \n (dg.Holding['H_S_SYMB']==symbol),['H_QTY','H_PRICE','H_DTS']].iloc[::-1]\n else:\n holding = dg.Holding.loc[(dg.Holding['H_CA_ID']==acct_id) & \n (dg.Holding['H_S_SYMB']==symbol),['H_QTY','H_PRICE','H_DTS']]\n \n for row in holding.iterrows():\n hold_qty = row[1]['H_QTY']\n hold_price = row[1]['H_PRICE']\n if hold_qty > needed_qty:\n buy_value += needed_qty * hold_price\n sell_value += needed_qty * requested_price\n needed_qty = 0\n else :\n buy_value += hold_qty * hold_price\n sell_value += hold_qty * requested_price\n needed_qty = needed_qty - hold_qty\n if needed_qty == 0:\n break;\n \n profile['H_PRICE'] = list(holding['H_PRICE'].values)\n profile['H_DTS'] = list(holding['H_DTS'].values)\n else:\n if hs_qty<0:\n if is_lifo:\n holding = dg.Holding.loc[(dg.Holding['H_CA_ID']==acct_id) & \n (dg.Holding['H_S_SYMB']==symbol),['H_QTY','H_PRICE','H_DTS']].iloc[::-1]\n else:\n holding = dg.Holding.loc[(dg.Holding['H_CA_ID']==acct_id) & \n (dg.Holding['H_S_SYMB']==symbol),['H_QTY','H_PRICE','H_DTS']]\n \n for row in holding.iterrows():\n hold_qty = row[1]['H_QTY']\n hold_price = row[1]['H_PRICE']\n if hold_qty+needed_qty<0:\n sell_value += needed_qty * hold_price\n buy_value += needed_qty * requested_price\n needed_qty = 0\n else :\n hold_qty = -hold_qty\n sell_value += hold_qty * hold_price\n buy_value += hold_qty * requested_price\n needed_qty = needed_qty - hold_qty\n \n if needed_qty == 0:\n break;\n \n profile['H_PRICE'] = list(holding['H_PRICE'].values)\n profile['H_DTS'] = list(holding['H_DTS'].values)\n \n tax_amount = 0.0\n if (sell_value>buy_value) and ((tax_status == 1) or (tax_status == 2)):\n tax_id = dg.CustomerTaxrate.loc[dg.CustomerTaxrate['CX_C_ID']==cust_id,'CX_TX_ID'].values\n tax_id = list(tax_id)\n profile['CX_C_ID'] = [cust_id for i in range(len(tax_id))]\n profile['CX_TX_ID'] = tax_id\n tax_rate = dg.TaxRate.loc[dg.TaxRate['TX_ID'].isin(tax_id),'TX_RATE'].values\n profile['TX_ID'] = [tax_id for i in range(len(tax_rate))]\n profile['TX_RATE'] = list(tax_rate)\n tax_rate = sum(tax_rate)\n tax_amount = (sell_value - buy_value) * tax_rate\n \n comm = dg.CommissionRate.loc[(dg.CommissionRate['CR_C_TIER']==cust_tier)\n &(dg.CommissionRate['CR_TT_ID']==trade_type_id)\n &(dg.CommissionRate['CR_EX_ID']==exch_id)\n &(dg.CommissionRate['CR_FROM_QTY']<=trade_qty)\n &(dg.CommissionRate['CR_TO_QTY']>=trade_qty),['CR_FROM_QTY','CR_TO_QTY','CR_RATE']]\n comm_rate = comm['CR_RATE'].values[0]\n profile['CR_C_TIER'] = [cust_tier]\n profile['CR_TT_ID'] = [trade_type_id]\n profile['CR_EX_ID'] = [exch_id]\n profile['CR_FROM_QTY'] = list(comm['CR_FROM_QTY'].values)\n profile['CR_TO_QTY'] = list(comm['CR_TO_QTY'].values)\n profile['CR_RATE'] = [comm_rate]\n \n charge_amount = dg.Charge.loc[(dg.Charge['CH_C_TIER']==cust_tier)\n &(dg.Charge['CH_TT_ID']==trade_type_id),'CH_CHRG'].values[0]\n profile['CH_C_TIER'] = [cust_tier]\n profile['CH_TT_ID'] = [trade_type_id]\n profile['CH_CHRG'] = [charge_amount]\n \n acct_assets = 0.0\n hold_assets = ''\n if type_is_margin=='':\n prob = random.uniform(0,1)\n if prob<0.08:\n type_is_margin=1\n else:\n type_is_margin=0\n if type_is_margin:\n acct_bal = dg.CustomerAccount.loc[dg.CustomerAccount['CA_ID']==acct_id,'CA_BAL'].values[0]\n profile['CA_BAL'] = [acct_bal]\n holdingsummary = dg.HoldingSummary.loc[dg.HoldingSummary['HS_CA_ID']==acct_id,\n ['HS_CA_ID','HS_S_SYMB','HS_QTY']]\n qty = list(holdingsummary['HS_QTY'].values)\n symb = list(holdingsummary['HS_S_SYMB'].values)\n profile['HS_CA_ID'] = [acct_id for i in range(len(qty))]\n profile['HS_S_SYMB'] = symb\n profile['HS_QTY'] = qty\n for i in range(len(symb)):\n if i==0:\n hold_assets=0\n price = dg.LastTrade.loc[dg.LastTrade['LT_S_SYMB']==symb[i],'LT_PRICE'].values[0]\n profile['LT_S_SYMB'].append(symb[i])\n profile['LT_PRICE'].append(price)\n hold_assets += qty[i]*price\n if hold_assets == '':\n acct_assets = acct_bal\n else:\n acct_assets = hold_assets + acct_bal\n \n if type_is_market:\n status_id = 'SBMT'\n else: \n status_id = 'PNDG'\n \n comm_amount = (comm_rate / 100) * trade_qty * requested_price\n base_time = max(list(dg.TradeHistory['TH_DTS']))\n base_time = datetime.datetime.strptime(base_time,\"%Y-%m-%d %H:%M:%S.%f\")\n current_time = datetime.datetime.now()\n current_time = current_time - simulation_start_date + base_time\n current_time_string = datetime.datetime.strftime(current_time,\"%Y-%m-%d %H:%M:%S.%f\")\n \n trade_id = max(list(dg.Trade['T_ID'])) + 1\n \n if roll_it_back == '':\n prob = random.uniform(0,1)\n roll_it_back = 0\n if prob<0.01:\n roll_it_back = 1\n \n trade = pd.DataFrame({'T_ID': [trade_id] , 'T_DTS': [current_time_string] , \n 'T_ST_ID': [status_id] ,'T_TT_ID': [trade_type_id] , \n 'T_IS_CASH': [abs(1-type_is_margin)] ,'T_S_SYMB': [symbol] , \n 'T_QTY': [trade_qty] , 'T_BID_PRICE': [requested_price] ,\n 'T_CA_ID': [acct_id] , 'T_EXEC_NAME': [exec_f_name + ' ' + exec_l_name] , \n 'T_TRADE_PRICE': [0] , 'T_CHRG': [charge_amount] , 'T_COMM': [comm_amount], \n 'T_TAX': [0] , 'T_LIFO': [is_lifo]})\n profile['T_ID'] = list(trade['T_ID'].values)\n profile['T_DTS'] = list(trade['T_DTS'].values)\n profile['T_ST_ID'] = list(trade['T_ST_ID'].values)\n profile['T_TT_ID'] = list(trade['T_TT_ID'].values)\n profile['T_IS_CASH'] = list(trade['T_IS_CASH'].values)\n profile['T_S_SYMB'] = list(trade['T_S_SYMB'].values)\n profile['T_QTY'] = list(trade['T_QTY'].values)\n profile['T_BID_PRICE'] = list(trade['T_BID_PRICE'].values)\n profile['T_CA_ID'] = list(trade['T_CA_ID'].values)\n profile['T_EXEC_NAME'] = list(trade['T_EXEC_NAME'].values)\n profile['T_TRADE_PRICE'] = list(trade['T_TRADE_PRICE'].values)\n profile['T_CHRG'] = list(trade['T_CHRG'].values)\n profile['T_COMM'] = list(trade['T_COMM'].values)\n profile['T_TAX'] = list(trade['T_TAX'].values)\n profile['T_LIFO'] = list(trade['T_LIFO'].values)\n if roll_it_back == 0:\n dg.Trade = dg.Trade.append(trade)\n \n if not type_is_market:\n traderequest_row = pd.DataFrame({'TR_T_ID': [trade_id] , 'TR_TT_ID': [trade_type_id] , \n 'TR_S_SYMB': [symbol] , 'TR_QTY': [trade_qty] , \n 'TR_BID_PRICE': [requested_price] , \n 'TR_B_ID': [broker_id]})\n profile['TR_T_ID'] = list(traderequest_row['TR_T_ID'].values)\n profile['TR_TT_ID'] = list(traderequest_row['TR_TT_ID'].values)\n profile['TR_S_SYMB'] = list(traderequest_row['TR_S_SYMB'].values)\n profile['TR_QTY'] = list(traderequest_row['TR_QTY'].values)\n profile['TR_BID_PRICE'] = list(traderequest_row['TR_BID_PRICE'].values)\n profile['TR_B_ID'] = list(traderequest_row['TR_B_ID'].values)\n if roll_it_back == 0:\n dg.TradeRequest = dg.TradeRequest.append(traderequest_row)\n \n tradehistory_row = pd.DataFrame({'TH_T_ID': [trade_id] , \n 'TH_DTS': [current_time_string] , 'TH_ST_ID': status_id})\n profile['TH_T_ID'] = list(tradehistory_row['TH_T_ID'].values)\n profile['TH_DTS'] = list(tradehistory_row['TH_DTS'].values)\n profile['TH_ST_ID'] = list(tradehistory_row['TH_ST_ID'].values)\n if roll_it_back == 0:\n dg.TradeHistory = dg.TradeHistory.append(tradehistory_row)\n \n createProfile(profile, \" tradeorder \" + exec_f_name + ' ' + exec_l_name)\n return acct_id,exec_f_name,exec_l_name,exec_tax_id,is_lifo,co_name,issue,symbol,trade_type_id,trade_qty,type_is_margin,roll_it_back,requested_price,sell_value,buy_value,tax_amount,status_id,trade_id,acct_assets\n \n###############################TRADE RESULT TRANSACTION########################\ndef traderesult(trade_id=''):\n profile = {}\n access_sequence = []\n if trade_id == '':\n trade = list(dg.Trade['T_ID'].values)\n trade_id = trade[np.random.randint(len(trade))]\n trade = dg.Trade.loc[dg.Trade['T_ID']==trade_id,['T_CA_ID','T_TT_ID',\n 'T_S_SYMB','T_QTY','T_CHRG','T_LIFO','T_IS_CASH']]\n access_sequence.append('T_ID')\n access_sequence.extend(list(trade.columns))\n profile['T_ID'] = [trade_id]\n profile['T_CA_ID']=list(trade['T_CA_ID'].values)\n profile['T_TT_ID']=list(trade['T_TT_ID'].values)\n profile['T_S_SYMB']=list(trade['T_S_SYMB'].values)\n profile['T_QTY']=list(trade['T_QTY'].values)\n profile['T_CHRG']=list(trade['T_CHRG'].values)\n profile['T_LIFO']=list(trade['T_LIFO'].values)\n profile['T_IS_CASH']=list(trade['T_IS_CASH'].values)\n type_id = trade['T_TT_ID'].values[0]\n symbol = trade['T_S_SYMB'].values[0]\n acct_id = trade['T_CA_ID'].values[0]\n tradetype = dg.TradeType.loc[dg.TradeType['TT_ID']==type_id,['TT_NAME','TT_IS_SELL',\n 'TT_IS_MRKT']]\n access_sequence.append('TT_ID')\n access_sequence.extend(list(tradetype.columns))\n profile['TT_ID'] = [type_id]\n profile['TT_NAME'] = list(tradetype['TT_NAME'].values)\n profile['TT_IS_SELL'] = list(tradetype['TT_IS_SELL'].values)\n profile['TT_IS_MRKT'] = list(tradetype['TT_IS_MRKT'].values)\n hs_qty = dg.HoldingSummary.loc[(dg.HoldingSummary['HS_CA_ID']==acct_id) &\n (dg.HoldingSummary['HS_S_SYMB']==symbol),'HS_QTY']\n if hs_qty.shape[0] == 0:\n hs_qty = 0\n else:\n hs_qty = hs_qty.values[0]\n profile['HS_CA_ID'] = [acct_id]\n profile['HS_S_SYMB'] = [symbol]\n profile['HS_QTY'] = [hs_qty]\n access_sequence.append('HS_CA_ID')\n access_sequence.append('HS_S_SYMB')\n access_sequence.append('HS_QTY')\n \n buy_value = 0.0\n sell_value = 0.0\n needed_qty = profile['T_QTY'][0]\n customeraccount = dg.CustomerAccount.loc[dg.CustomerAccount['CA_ID']==acct_id,\n ['CA_B_ID','CA_C_ID','CA_TAX_ST']]\n access_sequence.append('CA_ID')\n access_sequence.extend(list(customeraccount.columns))\n profile['CA_ID'] = [acct_id]\n profile['CA_B_ID'] = list(customeraccount['CA_B_ID'].values)\n broker_id = profile['CA_B_ID'][0]\n profile['CA_C_ID'] = list(customeraccount['CA_C_ID'].values)\n cust_id = profile['CA_C_ID'][0]\n profile['CA_TAX_ST'] = list(customeraccount['CA_TAX_ST'].values)\n type_is_sell = profile['TT_IS_SELL'][0]\n trade_start = min(list(dg.TradeHistory['TH_DTS']))\n trade_start = datetime.datetime.strptime(trade_start,\"%Y-%m-%d %H:%M:%S.%f\")\n current_time = nowTime()\n trade_dts = datetime.datetime.strftime(current_time,\"%Y-%m-%d %H:%M:%S.%f\")\n trade_price = marketPrice(symbol, trade_start)\n if type_is_sell:\n if hs_qty == 0:\n holding_row = pd.DataFrame({'HS_CA_ID':[acct_id],'HS_S_SYMB':[symbol],\n 'HS_QTY':[-needed_qty]})\n dg.HoldingSummary = dg.HoldingSummary.append(holding_row)\n profile['HS_CA_ID'].append(acct_id)\n profile['HS_S_SYMB'].append(symbol)\n profile['HS_QTY'].append(hs_qty)\n access_sequence.append('HS_CA_ID')\n access_sequence.append('HS_S_SYMB')\n access_sequence.append('HS_QTY')\n elif hs_qty != needed_qty:\n dg.HoldingSummary.loc[(dg.HoldingSummary['HS_CA_ID'] == acct_id) & \n (dg.HoldingSummary['HS_S_SYMB'] == symbol),'HS_QTY'] = hs_qty - needed_qty\n profile['HS_CA_ID'].append(acct_id)\n profile['HS_S_SYMB'].append(symbol)\n profile['HS_QTY'].append(hs_qty - needed_qty)\n access_sequence.append('HS_CA_ID')\n access_sequence.append('HS_S_SYMB')\n access_sequence.append('HS_QTY')\n is_lifo = profile['T_LIFO'][0]\n \n profile['HH_H_T_ID'] = []\n profile['HH_T_ID'] = []\n profile['HH_BEFORE_QTY'] = []\n profile['HH_AFTER_QTY'] = []\n profile['H_CA_ID'] = []\n profile['H_S_SYMB'] = []\n profile['H_T_ID'] = []\n profile['H_QTY'] = []\n profile['H_PRICE'] = []\n profile['H_DTS'] = []\n if hs_qty>0 :\n if is_lifo:\n holding = dg.Holding.loc[(dg.Holding['H_CA_ID']==acct_id) &\n (dg.Holding['H_S_SYMB']==symbol),['H_T_ID','H_QTY','H_PRICE']].iloc[::-1]\n else:\n holding = dg.Holding.loc[(dg.Holding['H_CA_ID']==acct_id) &\n (dg.Holding['H_S_SYMB']==symbol),['H_T_ID','H_QTY','H_PRICE']]\n profile['H_CA_ID'] = [acct_id]\n profile['H_S_SYMB'] = [symbol]\n profile['H_T_ID'] = list(holding['H_T_ID'].values)\n profile['H_QTY'] = list(holding['H_QTY'].values)\n profile['H_PRICE'] = list(holding['H_PRICE'].values)\n access_sequence.append('H_CA_ID')\n access_sequence.append('H_S_SYMB')\n access_sequence.extend(list(holding.columns))\n \n for row in holding.iterrows():\n hold_id = row[1]['H_T_ID']\n hold_qty = row[1]['H_QTY']\n hold_price = row[1]['H_PRICE']\n if hold_qty>needed_qty:\n holdinghistory = pd.DataFrame({'HH_H_T_ID':[hold_id],\n 'HH_T_ID':[trade_id],'HH_BEFORE_QTY':[hold_qty],\n 'HH_AFTER_QTY':[hold_qty - needed_qty]})\n dg.HoldingHistory = dg.HoldingHistory.append(holdinghistory)\n dg.Holding.loc[dg.Holding['H_T_ID']==hold_id,'H_QTY'] = hold_qty - needed_qty\n profile['HH_H_T_ID'].extend(list(holdinghistory['HH_H_T_ID'].values))\n profile['HH_T_ID'].extend(list(holdinghistory['HH_T_ID'].values))\n profile['HH_BEFORE_QTY'].extend(list(holdinghistory['HH_BEFORE_QTY'].values))\n profile['HH_AFTER_QTY'].extend(list(holdinghistory['HH_AFTER_QTY'].values))\n profile['H_QTY'].append(hold_qty - needed_qty)\n access_sequence.extend(list(holdinghistory.columns))\n access_sequence.append('H_QTY')\n buy_value += needed_qty * hold_price\n sell_value += needed_qty * profile['T_QTY'][0]\n needed_qty = 0\n else:\n holdinghistory = pd.DataFrame({'HH_H_T_ID':[hold_id],\n 'HH_T_ID':[trade_id],'HH_BEFORE_QTY':[hold_qty],\n 'HH_AFTER_QTY':[0]})\n dg.HoldingHistory = dg.HoldingHistory.append(holdinghistory)\n dg.Holding.drop(row[0],inplace = True)\n profile['HH_H_T_ID'].extend(list(holdinghistory['HH_H_T_ID'].values))\n profile['HH_T_ID'].extend(list(holdinghistory['HH_T_ID'].values))\n profile['HH_BEFORE_QTY'].extend(list(holdinghistory['HH_BEFORE_QTY'].values))\n profile['HH_AFTER_QTY'].extend(list(holdinghistory['HH_AFTER_QTY'].values))\n access_sequence.extend(list(holdinghistory.columns))\n buy_value += hold_qty * hold_price\n sell_value += hold_qty * profile['T_QTY'][0]\n needed_qty = needed_qty - hold_qty\n if needed_qty == 0:\n break\n \n if needed_qty>0:\n holdinghistory = pd.DataFrame({'HH_H_T_ID':[trade_id],\n 'HH_T_ID':[trade_id],'HH_BEFORE_QTY':[0],'HH_AFTER_QTY':[-1*needed_qty]})\n dg.HoldingHistory = dg.HoldingHistory.append(holdinghistory)\n profile['HH_H_T_ID'].extend(list(holdinghistory['HH_H_T_ID'].values))\n profile['HH_T_ID'].extend(list(holdinghistory['HH_T_ID'].values))\n profile['HH_BEFORE_QTY'].extend(list(holdinghistory['HH_BEFORE_QTY'].values))\n profile['HH_AFTER_QTY'].extend(list(holdinghistory['HH_AFTER_QTY'].values))\n access_sequence.extend(list(holdinghistory.columns))\n holding = pd.DataFrame({'H_T_ID':[trade_id],'H_CA_ID':[acct_id],\n 'H_S_SYMB':[symbol],'H_DTS':[trade_dts],'H_PRICE':[trade_price],\n 'H_QTY':[-1*needed_qty]})\n dg.Holding = dg.Holding.append(holding)\n profile['H_T_ID'].extend(list(holding['H_T_ID'].values))\n profile['H_CA_ID'].extend(list(holding['H_CA_ID'].values))\n profile['H_S_SYMB'].extend(list(holding['H_S_SYMB'].values))\n profile['H_DTS'].extend(list(holding['H_DTS'].values))\n profile['H_PRICE'].extend(list(holding['H_PRICE'].values))\n profile['H_QTY'].extend(list(holding['H_QTY'].values))\n access_sequence.extend(list(holding.columns))\n else:\n if hs_qty == profile['T_QTY'][0]:\n index = dg.HoldingSummary.loc[(dg.HoldingSummary['HS_CA_ID'] == acct_id)\n &(dg.HoldingSummary['HS_S_SYMB'] == symbol)].index[0]\n dg.HoldingSummary.drop(index,inplace = True)\n profile['HS_CA_ID'].append(acct_id)\n profile['HS_S_SYMB'].append(symbol)\n access_sequence.append(acct_id)\n access_sequence.append(symbol)\n \n else:\n # buy\n if hs_qty == 0:\n holding_row = pd.DataFrame({'HS_CA_ID':[acct_id],'HS_S_SYMB':[symbol],\n 'HS_QTY':[-needed_qty]})\n dg.HoldingSummary = dg.HoldingSummary.append(holding_row)\n profile['HS_CA_ID'].append(acct_id)\n profile['HS_S_SYMB'].append(symbol)\n profile['HS_QTY'].append(hs_qty)\n access_sequence.append('HS_CA_ID')\n access_sequence.append('HS_S_SYMB')\n access_sequence.append('HS_QTY')\n elif -1*hs_qty != needed_qty:\n dg.HoldingSummary.loc[(dg.HoldingSummary['HS_CA_ID'] == acct_id) & \n (dg.HoldingSummary['HS_S_SYMB'] == symbol),'HS_QTY'] = hs_qty + profile['T_QTY'][0]\n profile['HS_CA_ID'].append(acct_id)\n profile['HS_S_SYMB'].append(symbol)\n profile['HS_QTY'].append(hs_qty - needed_qty)\n access_sequence.append('HS_CA_ID')\n access_sequence.append('HS_S_SYMB')\n access_sequence.append('HS_QTY')\n \n is_lifo = profile['T_LIFO'][0]\n \n profile['HH_H_T_ID'] = []\n profile['HH_T_ID'] = []\n profile['HH_BEFORE_QTY'] = []\n profile['HH_AFTER_QTY'] = []\n profile['H_CA_ID'] = []\n profile['H_S_SYMB'] = []\n profile['H_T_ID'] = []\n profile['H_QTY'] = []\n profile['H_PRICE'] = []\n profile['H_DTS'] = []\n \n if hs_qty<0 :\n if is_lifo:\n holding = dg.Holding.loc[(dg.Holding['H_CA_ID']==acct_id) &\n (dg.Holding['H_S_SYMB']==symbol),['H_T_ID','H_QTY','H_PRICE']].iloc[::-1]\n else:\n holding = dg.Holding.loc[(dg.Holding['H_CA_ID']==acct_id) &\n (dg.Holding['H_S_SYMB']==symbol),['H_T_ID','H_QTY','H_PRICE']]\n profile['H_CA_ID'] = [acct_id]\n profile['H_S_SYMB'] = [symbol]\n profile['H_T_ID'] = list(holding['H_T_ID'].values)\n profile['H_QTY'] = list(holding['H_QTY'].values)\n profile['H_PRICE'] = list(holding['H_PRICE'].values)\n access_sequence.append('H_CA_ID')\n access_sequence.append('H_S_SYMB')\n access_sequence.extend(list(holding.columns))\n \n for row in holding.iterrows():\n hold_id = row[1]['H_T_ID']\n hold_qty = row[1]['H_QTY']\n hold_price = row[1]['H_PRICE']\n if hold_qty + needed_qty < 0:\n holdinghistory = pd.DataFrame({'HH_H_T_ID':[hold_id],\n 'HH_T_ID':[trade_id],'HH_BEFORE_QTY':[hold_qty],\n 'HH_AFTER_QTY':[hold_qty + needed_qty]})\n dg.HoldingHistory = dg.HoldingHistory.append(holdinghistory)\n dg.Holding.loc[dg.Holding['H_T_ID']==hold_id,'H_QTY'] = hold_qty + needed_qty\n profile['HH_H_T_ID'].extend(list(holdinghistory['HH_H_T_ID'].values))\n profile['HH_T_ID'].extend(list(holdinghistory['HH_T_ID'].values))\n profile['HH_BEFORE_QTY'].extend(list(holdinghistory['HH_BEFORE_QTY'].values))\n profile['HH_AFTER_QTY'].extend(list(holdinghistory['HH_AFTER_QTY'].values))\n profile['H_QTY'].append(hold_qty + needed_qty)\n access_sequence.extend(list(holdinghistory.columns))\n access_sequence.append('H_QTY')\n sell_value += needed_qty * hold_price\n buy_value += needed_qty * profile['T_QTY'][0]\n needed_qty = 0\n else:\n holdinghistory = pd.DataFrame({'HH_H_T_ID':[hold_id],\n 'HH_T_ID':[trade_id],'HH_BEFORE_QTY':[hold_qty],\n 'HH_AFTER_QTY':[0]})\n dg.HoldingHistory = dg.HoldingHistory.append(holdinghistory)\n dg.Holding.drop(row[0],inplace = True)\n profile['HH_H_T_ID'].extend(list(holdinghistory['HH_H_T_ID'].values))\n profile['HH_T_ID'].extend(list(holdinghistory['HH_T_ID'].values))\n profile['HH_BEFORE_QTY'].extend(list(holdinghistory['HH_BEFORE_QTY'].values))\n profile['HH_AFTER_QTY'].extend(list(holdinghistory['HH_AFTER_QTY'].values))\n access_sequence.extend(list(holdinghistory.columns))\n hold_qty = -hold_qty\n sell_value += hold_qty * hold_price\n buy_value += hold_qty * profile['T_QTY'][0]\n needed_qty = needed_qty - hold_qty\n if needed_qty == 0:\n break\n \n if needed_qty>0:\n holdinghistory = pd.DataFrame({'HH_H_T_ID':[trade_id],\n 'HH_T_ID':[trade_id],'HH_BEFORE_QTY':[0],'HH_AFTER_QTY':[needed_qty]})\n dg.HoldingHistory = dg.HoldingHistory.append(holdinghistory)\n profile['HH_H_T_ID'].extend(list(holdinghistory['HH_H_T_ID'].values))\n profile['HH_T_ID'].extend(list(holdinghistory['HH_T_ID'].values))\n profile['HH_BEFORE_QTY'].extend(list(holdinghistory['HH_BEFORE_QTY'].values))\n profile['HH_AFTER_QTY'].extend(list(holdinghistory['HH_AFTER_QTY'].values))\n access_sequence.extend(list(holdinghistory.columns))\n holding = pd.DataFrame({'H_T_ID':[trade_id],'H_CA_ID':[acct_id],\n 'H_S_SYMB':[symbol],'H_DTS':[trade_dts],'H_PRICE':[trade_price],\n 'H_QTY':[-1*needed_qty]})\n dg.Holding = dg.Holding.append(holding)\n profile['H_T_ID'].extend(list(holding['H_T_ID'].values))\n profile['H_CA_ID'].extend(list(holding['H_CA_ID'].values))\n profile['H_S_SYMB'].extend(list(holding['H_S_SYMB'].values))\n profile['H_DTS'].extend(list(holding['H_DTS'].values))\n profile['H_PRICE'].extend(list(holding['H_PRICE'].values))\n profile['H_QTY'].extend(list(holding['H_QTY'].values))\n access_sequence.extend(list(holding.columns))\n else:\n if -hs_qty == profile['T_QTY'][0]:\n index = dg.HoldingSummary.loc[(dg.HoldingSummary['HS_CA_ID'] == acct_id)\n &(dg.HoldingSummary['HS_S_SYMB'] == symbol)].index[0]\n dg.HoldingSummary.drop(index,inplace = True)\n profile['HS_CA_ID'].append(acct_id)\n profile['HS_S_SYMB'].append(symbol)\n access_sequence.append(acct_id)\n access_sequence.append(symbol)\n \n tax_amount = 0.0\n if ((profile['CA_TAX_ST'] == 1) or (profile['CA_TAX_ST'] == 2)) and (sell_value>buy_value):\n customertax = list(dg.CustomerTaxrate.loc[dg.CustomerTaxrate['CX_C_ID']==cust_id,\n 'CX_TX_ID'].values)\n profile['CX_C_ID'] = [cust_id for i in range(len(customertax))]\n profile['CX_TX_ID'] = [customertax]\n access_sequence.append('CX_C_ID')\n access_sequence.append('CX_TX_ID')\n tax = dg.Taxrate.loc[dg.Taxrate['TX_ID'].isin(customertax),\n ['TX_ID','TX_RATE']]\n profile['TX_ID'] = list(tax['TX_ID'].values)\n profile['TX_RATE'] = list(tax['TX_RATE'].values)\n access_sequence.extend(tax.columns)\n tax_rates = sum(profile['TX_RATE'])\n tax_amount = (sell_value - buy_value) * tax_rates\n dg.Trade.loc[dg.Trade['T_ID'] == trade_id,'T_TAX'] = tax_amount\n profile['T_ID'].append(trade_id)\n profile['T_TAX'] = [tax_amount]\n access_sequence.append('T_ID')\n access_sequence.append('T_TAX')\n\n security = dg.Security.loc[dg.Security['S_SYMB']==symbol,['S_EX_ID','S_NAME']]\n profile['S_SYMB'] = [symbol]\n profile['S_EX_ID'] = list(security['S_EX_ID'].values)\n profile['S_NAME'] = list(security['S_NAME'].values)\n access_sequence.append('S_SYMB')\n access_sequence.extend(list(security.columns))\n c_tier = dg.Customer.loc[dg.Customer['C_ID']==cust_id,'C_TIER'].values[0]\n profile['C_ID'] = [cust_id]\n profile['C_TIER'] = [c_tier]\n access_sequence.append('C_ID')\n access_sequence.append('C_TIER')\n comm = dg.CommissionRate.loc[(dg.CommissionRate['CR_C_TIER'] == c_tier)\n & (dg.CommissionRate['CR_TT_ID'] == type_id)\n & (dg.CommissionRate['CR_EX_ID'] == profile['S_EX_ID'][0])\n & (dg.CommissionRate['CR_FROM_QTY'] <= profile['T_QTY'][0])\n & (dg.CommissionRate['CR_TO_QTY'] >= profile['T_QTY'][0]),['CR_FROM_QTY','CR_TO_QTY','CR_RATE']]\n profile['CR_C_TIER'] = [c_tier]\n profile['CR_EX_ID'] = profile['S_EX_ID']\n profile['CR_FROM_QTY'] = [comm['CR_FROM_QTY'].values[0]]\n profile['CR_TO_QTY'] = [comm['CR_TO_QTY'].values[0]]\n profile['CR_RATE'] = [comm['CR_RATE'].values[0]]\n comm_rate = profile['CR_RATE'][0]\n access_sequence.append('CR_C_TIER')\n access_sequence.append('CR_TT_ID')\n access_sequence.append('CR_FROM_QTY')\n access_sequence.append('CR_TO_QTY')\n access_sequence.append('CR_RATE')\n \n comm_amount = (comm_rate / 100) * (profile['T_QTY'][0] * trade_price)\n index = dg.Trade['T_ID'] == trade_id\n dg.Trade.loc[index,'T_COMM'] = comm_amount\n dg.Trade.loc[index,'T_DTS'] = trade_dts\n dg.Trade.loc[index,'T_ST_ID'] = 'CMPT' \n dg.Trade.loc[index,'T_TRADE_PRICE'] = trade_price\n profile['T_ID'].append(trade_id)\n profile['T_COMM'] = comm_amount\n profile['T_DTS'] = trade_dts\n profile['T_ST_ID'] = 'CMPT'\n profile['T_TRADE_PRICE'] = trade_price\n access_sequence.append('T_ID')\n access_sequence.append('T_COMM')\n access_sequence.append('T_DTS')\n access_sequence.append('T_ST_ID')\n access_sequence.append('T_TRADE_PRICE')\n trade = pd.DataFrame({'TH_T_ID': [trade_id],'TH_DTS': [trade_dts],\n 'TH_ST_ID': ['CMPT']})\n profile['TH_T_ID'] = [trade_id]\n profile['TH_DTS'] = [trade_dts]\n profile['TH_ST_ID'] = ['CMPT']\n access_sequence.extend(list(trade.columns))\n dg.TradeHistory = dg.TradeHistory.append(trade)\n index = dg.Broker['B_ID'] == broker_id\n dg.Broker.loc[index,'B_COMM_TOTAL'] += comm_amount\n dg.Broker.loc[index,'B_NUM_TRADES'] += 1\n profile['B_ID'] = [broker_id]\n profile['B_COMM_TOTAL'] = dg.Broker.loc[index,'B_COMM_TOTAL']\n profile['B_NUM_TRADES'] = dg.Broker.loc[index,'B_NUM_TRADES']\n access_sequence.append('B_ID')\n access_sequence.append('B_COMM_TOTAL')\n access_sequence.append('B_NUM_TRADES')\n due_date = current_time + datetime.timedelta(days = 2)\n if type_is_sell :\n se_amount = (profile['T_QTY'][0] * trade_price) - profile['T_CHRG'][0] - comm_amount\n else :\n se_amount = -((profile['T_QTY'][0] * trade_price) + profile['T_CHRG'][0] + comm_amount)\n \n if profile['CA_C_ID'][0] == 1 :\n se_amount = se_amount - tax_amount\n \n if profile['T_IS_CASH'] == 1:\n cash_type = \"Cash Account\"\n else:\n cash_type = \"Margin\"\n \n settlement = pd.DataFrame({'SE_T_ID': [trade_id],'SE_CASH_TYPE': [cash_type],\n 'SE_CASH_DUE_DATE': [due_date],'SE_AMT': [se_amount]})\n profile['SE_T_ID'] = list(settlement['SE_T_ID'].values)\n profile['SE_CASH_TYPE'] = list(settlement['SE_CASH_TYPE'].values)\n profile['SE_CASH_DUE_DATE'] = list(settlement['SE_CASH_DUE_DATE'].values)\n profile['SE_AMT'] = list(settlement['SE_AMT'].values)\n access_sequence.extend(list(settlement.columns))\n dg.Settlement = dg.Settlement.append(settlement)\n \n profile['CA_BAL'] = []\n if profile['T_IS_CASH'] == 1:\n dg.CustomerAccount.loc[dg.CustomerAccount['CA_ID']==acct_id,'CA_BAL'] += se_amount\n profile['CA_ID'].append(acct_id)\n profile['CA_BAL'] = [dg.CustomerAccount.loc[dg.CustomerAccount['CA_ID']==acct_id,'CA_BAL'].values]\n access_sequence.append('CA_ID')\n access_sequence.append('CA_BAL')\n cashtransaction = pd.DataFrame({'CT_DTS': [trade_dts],'CT_T_ID': [trade_id],\n 'CT_AMT': [se_amount],\n 'CT_NAME': [profile['TT_NAME'][0] + \" \" + profile['T_OTY'][0] + \" shares of \" + profile['S_NAME'][0]]\n })\n profile['CT_DTS'] = list(cashtransaction['CT_DTS'].values)\n profile['CT_T_ID'] = list(cashtransaction['CT_T_ID'].values)\n profile['CT_AMT'] = list(cashtransaction['CT_AMT'].values)\n profile['CT_NAME'] = list(cashtransaction['CT_NAME'].values)\n access_sequence.extend(list(cashtransaction.cloumns))\n dg.CashTransactions = dg.CashTransactions.append(cashtransaction)\n \n acct_bal = dg.CustomerAccount.loc[dg.CustomerAccount['CA_ID']==acct_id,'CA_BAL'].values[0]\n profile['CA_ID'].append(acct_id)\n profile['CA_BAL'].append(acct_bal)\n access_sequence.append('CA_ID')\n access_sequence.append('CA_BAL')\n \n createProfile(profile,\" tradeResult \" + str(trade_id),access_sequence)\n return trade_id,acct_bal,trade_price,acct_id\n\n###############################TRADE STATUS TRANSACTION########################\ndef tradestatus(acct_id = ''):\n profile = {}\n access_sequence = []\n if acct_id == '':\n group = np.random.randint(2)\n if group == 0:\n customers = list(dg.Customer['C_ID'])\n else:\n tier = np.random.randint(1,4)\n customers = list(dg.Customer.loc[dg.Customer['C_TIER']==tier,'C_ID'])\n cust_id = customers[np.random.randint(len(customers))]\n accounts = list(dg.CustomerAccount.loc[dg.CustomerAccount['CA_C_ID']==cust_id,'CA_ID'])\n acct_id = accounts[np.random.randint(len(accounts))]\n trade = dg.Trade.loc[dg.Trade['T_CA_ID']==acct_id,['T_CA_ID','T_ID','T_DTS',\n 'T_S_SYMB','T_QTY','T_EXEC_NAME','T_CHRG','T_ST_ID','T_TT_ID']][-50:]\n access_sequence.extend(list(trade.columns))\n tradetype = dg.TradeType.loc[dg.TradeType['TT_ID'].isin(list(trade['T_TT_ID'].values)),\n ['TT_ID','TT_NAME']]\n access_sequence.extend(list(tradetype.columns))\n statustype = dg.StatusType.loc[dg.StatusType['ST_ID'].isin(list(trade['T_ST_ID'].values)),\n ['ST_ID','ST_NAME']]\n access_sequence.extend(list(statustype.columns))\n security = dg.Security.loc[dg.Security['S_SYMB'].isin(list(trade['T_S_SYMB'].values)),\n ['S_SYMB','S_NAME','S_EX_ID']]\n access_sequence.extend(list(security.columns))\n exchange = dg.Exchange.loc[dg.Exchange['EX_ID'].isin(list(security['S_EX_ID'].values)),\n ['EX_ID','EX_NAME']]\n access_sequence.extend(list(exchange.columns))\n security = security.set_index('S_EX_ID',drop=False).join(exchange.set_index('EX_ID',drop=False))\n trade = trade.set_index('T_TT_ID',drop=False).join(tradetype.set_index('TT_ID',drop=False))\n trade = trade.set_index('T_ST_ID',drop=False).join(statustype.set_index('ST_ID',drop=False))\n trade = trade.set_index('T_S_SYMB',drop=False).join(security.set_index('S_SYMB',drop=False))\n profile['T_CA_ID'] = list(trade['T_CA_ID'].values)\n profile['T_ID'] = list(trade['T_ID'].values)\n profile['T_DTS'] = list(trade['T_DTS'].values)\n profile['T_S_SYMB'] = list(trade['T_S_SYMB'].values)\n profile['T_QTY'] = list(trade['T_QTY'].values)\n profile['T_EXEC_NAME'] = list(trade['T_EXEC_NAME'].values)\n profile['T_CHRG'] = list(trade['T_CHRG'].values)\n profile['T_ST_ID'] = list(trade['T_ST_ID'].values)\n profile['T_TT_ID'] = list(trade['T_TT_ID'].values)\n profile['TT_ID'] = list(trade['TT_ID'].values)\n profile['TT_NAME'] = list(trade['TT_NAME'].values)\n profile['ST_ID'] = list(trade['ST_ID'].values)\n profile['ST_NAME'] = list(trade['ST_NAME'].values)\n profile['S_SYMB'] = list(trade['S_SYMB'].values)\n profile['S_NAME'] = list(trade['S_NAME'].values)\n profile['S_EX_ID'] = list(trade['S_EX_ID'].values)\n profile['EX_ID'] = list(trade['EX_ID'].values)\n profile['EX_NAME'] = list(trade['EX_NAME'].values)\n customeraccount = dg.CustomerAccount.loc[dg.CustomerAccount['CA_ID'] == acct_id,['CA_C_ID','CA_B_ID']]\n customer_id = customeraccount['CA_C_ID'].values[0]\n broker_id = customeraccount['CA_B_ID'].values[0]\n access_sequence.append('CA_ID')\n access_sequence.extend(list(customeraccount.columns))\n customer = dg.Customer.loc[dg.Customer['C_ID']==customer_id,['C_ID',\n 'C_F_NAME','C_L_NAME']]\n access_sequence.extend(list(customer.columns))\n broker = dg.Broker.loc[dg.Broker['B_ID']==broker_id,['B_ID','B_NAME']]\n access_sequence.extend(list(broker.columns))\n profile['CA_ID'] = [acct_id]\n profile['CA_C_ID'] = [customer_id]\n profile['CA_B_ID'] = [broker_id]\n profile['C_ID'] = list(customer['C_ID'].values)\n profile['C_F_NAME'] = list(customer['C_F_NAME'].values)\n profile['C_L_NAME'] = list(customer['C_L_NAME'].values)\n profile['B_ID'] = list(broker['B_ID'].values)\n profile['B_NAME'] = list(broker['B_NAME'].values)\n \n createProfile(profile,\" tradestatus \" + str(acct_id))\n return acct_id,trade,customer,broker\n\n##############################TRADE UPDATE TRANSACTION#########################\ndef tradeupdate(acct_id='',end_trade_dts='',frame_to_execute='',max_acct_id='',max_trades=20,max_updates=20,start_trade_dts='',symbol='',trade_id=''):\n profile = {}\n access_sequence = []\n if frame_to_execute == '':\n prob = random.uniform(0,1);\n if prob<0.33:\n frame_to_execute = 1\n elif prob<0.66:\n frame_to_execute = 2\n else:\n frame_to_execute = 3\n \n if frame_to_execute == 1:\n if trade_id == '':\n trade = list(dg.Trade['T_ID'])\n length = len(trade)\n start = np.random.randint(length-max_trades)\n trade_id = random.sample(trade[start:],max_trades)\n updated = 0\n profile['T_ID'] = []\n profile['T_EXEC_NAME'] = []\n profile['T_BID_PRICE'] = []\n profile['T_IS_CASH'] = []\n profile['T_TRADE_PRICE'] = []\n profile['T_TT_ID'] = []\n profile['TT_ID'] = []\n profile['TT_IS_MRKT'] = []\n profile['SE_T_ID'] = []\n profile['SE_AMT'] = []\n profile['SE_CASH_DUE_DATE'] = []\n profile['SE_CASH_TYPE'] = []\n profile['CT_T_ID'] = []\n profile['CT_AMT'] = []\n profile['CT_DTS'] = []\n profile['CT_NAME'] = []\n profile['TH_T_ID'] = []\n profile['TH_DTS'] = []\n profile['TH_ST_ID'] = []\n for tid in trade_id:\n if updated<max_updates:\n ex_name = dg.Trade.loc[dg.Trade['T_ID']==tid,'T_EXEC_NAME'].values[0]\n profile['T_ID'].append(tid)\n profile['T_EXEC_NAME'].append(ex_name)\n access_sequence.append('T_ID')\n access_sequence.append('T_EXEC_NAME')\n if ex_name.find(\"X\"):\n ex_name.replace(\"X\",\" \")\n else:\n ex_name.replace(\" \",\"X\")\n dg.Trade.loc[dg.Trade['T_ID']==tid,'T_EXEC_NAME'] = ex_name\n profile['T_ID'].append(tid)\n profile['T_EXEC_NAME'].append(ex_name)\n access_sequence.append('T_ID')\n access_sequence.append('T_EXEC_NAME')\n updated += 1\n trade = dg.Trade.loc[dg.Trade['T_ID']==tid,['T_BID_PRICE','T_EXEC_NAME',\n 'T_IS_CASH','T_TT_ID','T_TRADE_PRICE']]\n tradetype = dg.TradeType.loc[dg.TradeType['TT_ID'] == trade['T_TT_ID'].values[0],\n ['TT_IS_MRKT']]\n profile['T_ID'].append(tid)\n profile['T_EXEC_NAME'].append(trade['T_EXEC_NAME'].values[0])\n profile['T_BID_PRICE'].append(trade['T_BID_PRICE'].values[0])\n profile['T_IS_CASH'].append(trade['T_IS_CASH'].values[0])\n profile['T_TRADE_PRICE'].append(trade['T_TRADE_PRICE'].values[0])\n profile['T_TT_ID'].append(trade['T_TT_ID'].values[0])\n profile['TT_ID'].append(trade['T_TT_ID'].values[0])\n profile['TT_IS_MRKT'].append(tradetype['TT_IS_MRKT'].values[0])\n access_sequence.append('T_ID')\n access_sequence.extend(trade.columns)\n access_sequence.extend(['TT_ID','TT_IS_MRKT'])\n settlement = dg.Settlement.loc[dg.Settlement['SE_T_ID']==tid,\n ['SE_AMT','SE_CASH_DUE_DATE','SE_CASH_TYPE']]\n profile['SE_T_ID'].append(tid)\n profile['SE_AMT'].append(settlement['SE_AMT'].values[0])\n profile['SE_CASH_DUE_DATE'].append(settlement['SE_CASH_DUE_DATE'].values[0])\n profile['SE_CASH_TYPE'].append(settlement['SE_CASH_TYPE'].values[0])\n access_sequence.append('SE_T_ID')\n access_sequence.extend(settlement.columns)\n if profile['T_IS_CASH'][-1]:\n cashtransaction = dg.CashTransaction.loc[dg.CashTransaction['CT_T_ID'] == tid,\n ['CT_AMT','CT_DTS','CT_NAME']]\n profile['CT_T_ID'].append(tid)\n profile['CT_AMT'].append(cashtransaction['CT_AMT'].values[0])\n profile['CT_DTS'].append(cashtransaction['CT_DTS'].values[0])\n profile['CT_NAME'].append(cashtransaction['CT_NAME'].values[0])\n access_sequence.append('CT_T_ID')\n access_sequence.append(cashtransaction.columns)\n tradehistory = dg.TradeHistory.loc[dg.TradeHistory['TH_T_ID']==tid,\n ['TH_DTS','TH_ST_ID']][:3]\n profile['TH_T_ID'].append(tid)\n profile['TH_DTS'].extend(list(tradehistory['TH_DTS'].values))\n profile['TH_ST_ID'].extend(list(tradehistory['TH_ST_ID'].values))\n access_sequence.append('TH_T_ID')\n access_sequence.extend(tradehistory.columns)\n createProfile(profile, ' tradeupdate1' ,access_sequence)\n return trade_id,frame_to_execute,max_trades,max_updates,profile['T_BID_PRICE'],profile['CT_AMT'],profile['CT_DTS'],profile['CT_NAME'],profile['T_EXEC_NAME'],profile['T_IS_CASH'],profile['TT_IS_MRKT'],profile['SE_AMT'],profile['SE_CASH_DUE_DATE'],profile['SE_CASH_TYPE'],profile['TH_DTS'],profile['TH_ST_ID'],profile['T_TRADE_PRICE']\n \n if frame_to_execute == 2:\n if acct_id == '':\n group = np.random.randint(2)\n if group == 0:\n customers = list(dg.Customer['C_ID'])\n else:\n tier = np.random.randint(1,4)\n customers = list(dg.Customer.loc[dg.Customer['C_TIER']==tier,'C_ID'])\n cust_id = customers[np.random.randint(len(customers))]\n accounts = list(dg.CustomerAccount.loc[dg.CustomerAccount['CA_C_ID']==cust_id,'CA_ID'])\n acct_id = accounts[np.random.randint(len(accounts))]\n if start_trade_dts=='':\n dts = random.sample(list(dg.Trade['T_DTS']),2)\n start_trade_dts = min(dts)\n end_trade_dts = max(dts)\n trade = dg.Trade.loc[(dg.Trade['T_CA_ID']==acct_id)\n &(dg.Trade['T_DTS']>=start_trade_dts)\n &(dg.Trade['T_DTS']<=end_trade_dts),['T_DTS','T_BID_PRICE','T_EXEC_NAME',\n 'T_IS_CASH','T_ID','T_TRADE_PRICE']][:max_trades]\n profile['T_CA_ID'] = [acct_id]\n profile['T_DTS'] = list(trade['T_DTS'].values)\n profile['T_BID_PRICE'] = list(trade['T_BID_PRICE'].values)\n profile['T_EXEC_NAME'] = list(trade['T_EXEC_NAME'].values)\n profile['T_IS_CASH'] = list(trade['T_IS_CASH'].values)\n profile['T_ID'] = list(trade['T_ID'].values)\n profile['T_TRADE_PRICE'] = list(trade['T_TRADE_PRICE'].values)\n access_sequence.append('T_CA_ID')\n access_sequence.extend(trade.columns)\n updated = 0\n profile['SE_T_ID'] = []\n profile['SE_AMT'] = []\n profile['SE_CASH_DUE_DATE'] = []\n profile['SE_CASH_TYPE'] = []\n profile['CT_T_ID'] = []\n profile['CT_AMT'] = []\n profile['CT_DTS'] = []\n profile['CT_NAME'] = []\n profile['TH_T_ID'] = []\n profile['TH_DTS'] = []\n profile['TH_ST_ID'] = []\n cnt = 0\n for tid in profile['T_ID']:\n if updated<max_updates:\n cash_type = dg.Settlement.loc[dg.Settlement['SE_T_ID']==tid,'SE_CASH_TYPE'].values[0]\n profile['SE_T_ID'] = [tid]\n profile['SE_CASH_TYPE'] = [cash_type]\n access_sequence.extend(['SE_T_ID','SE_CASH_TYPE'])\n if profile['T_IS_CASH'][cnt]:\n if cash_type == \"Cash Account\":\n cash_type = \"Cash\"\n else:\n cash_type = \"Cash Account\"\n else:\n if cash_type == \"Margin Account\":\n cash_type = \"Margin\"\n else:\n cash_type = \"Margin Account\"\n dg.Settlement.loc[dg.Settlement['SE_T_ID']==tid,'SE_CASH_TYPE'].values[0] = cash_type\n profile['SE_T_ID'] = [tid]\n profile['SE_CASH_TYPE'] = [cash_type]\n access_sequence.extend(['SE_T_ID','SE_CASH_TYPE'])\n updated += 1\n settlement = dg.Settlement.loc[dg.Settlement['SE_T_ID']==tid,\n ['SE_AMT','SE_CASH_DUE_DATE','SE_CASH_TYPE']]\n profile['SE_T_ID'].append(tid)\n profile['SE_AMT'].append(settlement['SE_AMT'].values[0])\n profile['SE_CASH_DUE_DATE'].append(settlement['SE_CASH_DUE_DATE'].values[0])\n profile['SE_CASH_TYPE'].append(settlement['SE_CASH_TYPE'].values[0])\n access_sequence.append('SE_T_ID')\n access_sequence.extend(settlement.columns)\n if profile['T_IS_CASH'][cnt]:\n cashtransaction = dg.CashTransaction.loc[dg.CashTransaction['CT_T_ID'] == tid,\n ['CT_AMT','CT_DTS','CT_NAME']]\n profile['CT_T_ID'].append(tid)\n profile['CT_AMT'].append(cashtransaction['CT_AMT'].values[0])\n profile['CT_DTS'].append(cashtransaction['CT_DTS'].values[0])\n profile['CT_NAME'].append(cashtransaction['CT_NAME'].values[0])\n access_sequence.append('CT_T_ID')\n access_sequence.append(cashtransaction.columns)\n tradehistory = dg.TradeHistory.loc[dg.TradeHistory['TH_T_ID']==tid,\n ['TH_DTS','TH_ST_ID']][:3]\n profile['TH_T_ID'].append(tid)\n profile['TH_DTS'].extend(tradehistory['TH_DTS'].values)\n profile['TH_ST_ID'].extend(tradehistory['TH_ST_ID'].values)\n access_sequence.append('TH_T_ID')\n access_sequence.extend(tradehistory.columns)\n cnt += 1\n createProfile(profile, ' tradeupdate2 ' + str(acct_id) ,access_sequence)\n return acct_id,end_trade_dts,start_trade_dts,frame_to_execute,max_trades,max_updates,profile['T_BID_PRICE'],profile['CT_AMT'],profile['CT_DTS'],profile['CT_NAME'],profile['T_EXEC_NAME'],profile['T_IS_CASH'],profile['SE_AMT'],profile['SE_CASH_DUE_DATE'],profile['SE_CASH_TYPE'],profile['TH_DTS'],profile['TH_ST_ID'],profile['T_TRADE_PRICE']\n \n if frame_to_execute == 3:\n if start_trade_dts=='':\n dts = random.sample(list(dg.Trade['T_DTS']),2)\n start_trade_dts = min(dts)\n end_trade_dts = max(dts)\n if symbol == '':\n symbol = random.sample(list(dg.Security['S_SYMB']),1)\n symbol = symbol[0]\n trade = dg.Trade.loc[(dg.Trade['T_S_SYMB'] == symbol)\n &(dg.Trade['T_DTS']>=start_trade_dts)\n &(dg.Trade['T_DTS']<=end_trade_dts),['T_DTS','T_CA_ID','T_EXEC_NAME',\n 'T_IS_CASH','T_TRADE_PRICE','T_QTY','T_ID','T_TT_ID']]\n profile['T_S_SYMB'] = [symbol for i in range(trade.shape[0])]\n profile['T_DTS'] = list(trade['T_DTS'].values)\n profile['T_CA_ID'] = list(trade['T_CA_ID'].values)\n profile['T_EXEC_NAME'] = list(trade['T_EXEC_NAME'].values)\n profile['T_IS_CASH'] = list(trade['T_IS_CASH'].values)\n profile['T_TRADE_PRICE'] = list(trade['T_TRADE_PRICE'].values)\n profile['T_QTY'] = list(trade['T_QTY'].values)\n profile['T_ID'] = list(trade['T_ID'].values)\n profile['T_TT_ID'] = list(trade['T_TT_ID'].values)\n profile['TT_ID'] = list(trade['T_TT_ID'].values)\n profile['TT_NAME'] = []\n for tyid in profile['TT_ID']:\n profile['TT_NAME'].append(dg.TradeType.loc[dg.TradeType['TT_ID']==tyid,\n 'TT_NAME'].values[0])\n s_name = dg.Security.loc[dg.Security['S_SYMB']==symbol,'S_NAME'].values[0]\n profile['S_SYMB'] = [symbol for i in range(trade.shape[0])]\n profile['S_NAME'] = [s_name for i in range(trade.shape[0])]\n access_sequence.append('T_S_SYMB')\n access_sequence.extend(trade.columns)\n access_sequence.extend(['TT_ID','TT_NAME','S_SYMB','S_NAME'])\n \n profile['SE_T_ID'] = []\n profile['SE_AMT'] = []\n profile['SE_CASH_DUE_DATE'] = []\n profile['SE_CASH_TYPE'] = []\n profile['CT_T_ID'] = []\n profile['CT_AMT'] = []\n profile['CT_DTS'] = []\n profile['CT_NAME'] = []\n profile['TH_T_ID'] = []\n profile['TH_DTS'] = []\n profile['TH_ST_ID'] = []\n cnt = 0\n updated = 0\n for tid in profile['T_ID']:\n settlement = dg.Settlement.loc[dg.Settlement['SE_T_ID']==tid,\n ['SE_AMT','SE_CASH_DUE_DATE','SE_CASH_TYPE']]\n profile['SE_T_ID'].append(tid)\n profile['SE_AMT'].append(settlement['SE_AMT'].values[0])\n profile['SE_CASH_DUE_DATE'].append(settlement['SE_CASH_DUE_DATE'].values[0])\n profile['SE_CASH_TYPE'].append(settlement['SE_CASH_TYPE'].values[0])\n access_sequence.append('SE_T_ID')\n access_sequence.extend(settlement.columns)\n if profile['T_IS_CASH'][cnt]:\n if updated<max_updates:\n ct_name = dg.CashTransaction.loc[dg.CashTransaction['CT_T_ID']==tid,'CT_NAME'].values[0]\n profile['CT_T_ID'].append(tid)\n profile['CT_NAME'].append(ct_name)\n access_sequence.extend(['CT_T_ID','CT_NAME'])\n if ct_name.find(\"shares of\") !=-1:\n ct_name = profile['TT_NAME'][cnt] + \" \" + str(profile['T_QTY'][cnt]) + \" Shares of \" + s_name\n else:\n ct_name = profile['TT_NAME'][cnt] + \" \" + str(profile['T_QTY'][cnt]) + \" shares of \" + s_name\n dg.CashTransaction.loc[dg.CashTransaction['CT_T_ID']==tid,'CT_NAME'].values[0] = ct_name\n profile['CT_T_ID'].append(tid)\n profile['CT_NAME'].append(ct_name)\n access_sequence.extend(['CT_T_ID','CT_NAME'])\n updated += 1\n if profile['T_IS_CASH'][cnt]:\n cashtransaction = dg.CashTransaction.loc[dg.CashTransaction['CT_T_ID'] == tid,\n ['CT_AMT','CT_DTS','CT_NAME']]\n profile['CT_T_ID'].append(tid)\n profile['CT_AMT'].append(cashtransaction['CT_AMT'].values[0])\n profile['CT_DTS'].append(cashtransaction['CT_DTS'].values[0])\n profile['CT_NAME'].append(cashtransaction['CT_NAME'].values[0])\n access_sequence.append('CT_T_ID')\n access_sequence.append(cashtransaction.columns)\n tradehistory = dg.TradeHistory.loc[dg.TradeHistory['TH_T_ID']==tid,\n ['TH_DTS','TH_ST_ID']][:3]\n profile['TH_T_ID'].append(tid)\n profile['TH_DTS'].extend(tradehistory['TH_DTS'].values)\n profile['TH_ST_ID'].extend(tradehistory['TH_ST_ID'].values)\n access_sequence.append('TH_T_ID')\n access_sequence.extend(tradehistory.columns)\n cnt += 1\n createProfile(profile, ' tradeupdate2 ' + str(acct_id) ,access_sequence)\n return symbol,end_trade_dts,start_trade_dts,frame_to_execute,max_trades,max_updates,profile['T_CA_ID'],profile['CT_AMT'],profile['CT_DTS'],profile['CT_NAME'],profile['T_EXEC_NAME'],profile['T_IS_CASH'],profile['T_TRADE_PRICE'],profile['T_QTY'],profile['S_NAME'],profile['SE_AMT'],profile['SE_CASH_DUE_DATE'],profile['SE_CASH_TYPE'],profile['TH_DTS'],profile['TH_ST_ID'],profile['T_ID'],profile['TT_NAME'],profile['T_TT_ID']\n \n##############################TRADE CLEANUP TRANSACTION########################\ndef tradecleanup():\n profile = {}\n access_sequence = []\n tids = list(dg.TradeRequest['TR_T_ID'])\n profile['TR_T_ID'] = tids\n access_sequence.append('TR_T_ID')\n profile['TH_T_ID'] = []\n profile['TH_DTS'] = []\n profile['TH_ST_ID'] = []\n profile['T_ID'] = []\n profile['T_ST_ID'] = []\n profile['T_DTS'] = []\n for tid in tids:\n current_time = nowTime()\n now_dts = datetime.datetime.strftime(current_time,\"%Y-%m-%d %H:%M:%S.%f\")\n tradehistory = pd.DataFrame({'TH_T_ID':[tid],'TH_DTS':[now_dts], 'TH_ST_ID':['SBMT']})\n dg.TradeHistory = dg.TradeHistory.append(tradehistory)\n profile['TH_T_ID'].append(tid)\n profile['TH_DTS'].append(now_dts)\n profile['TH_ST_ID'].append('SBMT')\n access_sequence.extend(tradehistory.columns)\n index = dg.Trade['T_ID'] == tid\n dg.Trade.loc[index,'T_ST_ID'] = 'CNCL'\n dg.Trade.loc[index,'T_DTS'] = now_dts\n profile['T_ID'].append(tid)\n profile['T_ST_ID'].append('CNCL')\n profile['T_DTS'].append(now_dts)\n access_sequence.extend(['T_ID','T_ST_ID','T_DTS'])\n tradehistory = pd.DataFrame({'TH_T_ID':[tid],'TH_DTS':[now_dts], 'TH_ST_ID':['CNCL']})\n dg.TradeHistory = dg.TradeHistory.append(tradehistory)\n profile['TH_T_ID'].append(tid)\n profile['TH_DTS'].append(now_dts)\n profile['TH_ST_ID'].append('CNCL')\n access_sequence.extend(tradehistory.columns)\n dg.TradeRequest.drop(dg.TradeRequest.index,inplace=True)\n tids = list(dg.Trade.loc[dg.Trade['T_ST_ID']=='SBMT','T_ID'].values)\n profile['T_ST_ID'].extend(['SBMT' for i in range(len(tids))])\n profile['T_ID'].extend(tids)\n for tid in tids:\n current_time = nowTime()\n now_dts = datetime.datetime.strftime(current_time,\"%Y-%m-%d %H:%M:%S.%f\")\n index = dg.Trade['T_ID'] == tid\n dg.Trade.loc[index,'T_ST_ID'] = 'CNCL'\n dg.Trade.loc[index,'T_DTS'] = now_dts\n profile['T_ID'].append(tid)\n profile['T_ST_ID'].append('CNCL')\n profile['T_DTS'].append(now_dts)\n access_sequence.extend(['T_ID','T_ST_ID','T_DTS'])\n tradehistory = pd.DataFrame({'TH_T_ID':[tid],'TH_DTS':[now_dts], 'TH_ST_ID':['CNCL']})\n dg.TradeHistory = dg.TradeHistory.append(tradehistory)\n profile['TH_T_ID'].append(tid)\n profile['TH_DTS'].append(now_dts)\n profile['TH_ST_ID'].append('CNCL')\n access_sequence.extend(tradehistory.columns)\n createProfile(profile,' Trade Status', access_sequence)\n \n \n ","repo_name":"Chitraksh-Grover/DB-Intrusion-Detection","sub_path":"transactions.py","file_name":"transactions.py","file_ext":"py","file_size_in_byte":98970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"43274456028","text":"import pandas as pd\nimport numpy as np\nimport random\nimport os\n\n\ndef negative_sampling(df, data_type=None, num_negative=5):\n\n print(f\"********* Generating Pos Neg Data for : {data_type} *********\")\n\n pos_data_list = df.values.tolist()\n\n df[\"label\"] = int(1)\n\n # df.reset_index(drop=True, inplace=True)\n print(f\"{data_type} datframe shape {df.shape}\")\n print(df.head())\n print()\n\n unique_concepts = df[\"concept\"].unique()\n unique_properties = df[\"property\"].unique()\n\n print(f\"Number of Unique Concepts in Dataframe :\", len(unique_concepts), flush=True)\n\n all_negative_data = []\n\n for concept in unique_concepts:\n\n concept_data = df[df[\"concept\"] == concept]\n properties_for_concept = concept_data[\"property\"].unique()\n conjuct_properties_for_concept = concept_data[\"conjuct_prop\"].unique()\n\n num_record = len(concept_data)\n\n print()\n print(f\"Generating Negative Data for Concept : {concept}\", flush=True)\n print(f\"Positive data for concept in DF : {concept_data.shape}\", flush=True)\n\n print(\"Data For concept\", flush=True)\n print(concept_data, flush=True)\n print(f\"Properties for Concept\", flush=True)\n print(properties_for_concept, flush=True)\n print(f\"Conjuction Properties for Concept\", flush=True)\n print(conjuct_properties_for_concept, flush=True)\n\n total_neg_num = num_record * num_negative\n\n print(f\"Total Number of Negative Records to be generated : {total_neg_num}\")\n\n rest_df = df[df[\"concept\"] != concept]\n print(f\"Rest DF shape after removing concept : {rest_df.shape}\")\n rest_df = rest_df[~rest_df[\"property\"].isin(properties_for_concept)]\n\n print(\n f\"Rest DF shape after removing concepts's properties : {rest_df.shape}\",\n flush=True,\n )\n\n concept_neg_data = []\n\n while True:\n\n concept = concept.strip()\n neg_properties = list(rest_df[\"property\"].sample(n=total_neg_num))\n conjuct_props = random.choices(\n conjuct_properties_for_concept, k=total_neg_num\n )\n\n neg_data = [\n [concept, conjuct_prop, neg_prop]\n for conjuct_prop, neg_prop in zip(conjuct_props, neg_properties)\n ]\n print(f\"neg_data length :\", len(neg_data), flush=True)\n\n if len(concept_neg_data) < total_neg_num:\n for x in neg_data:\n if not (x in pos_data_list):\n if not (x in all_negative_data):\n\n all_negative_data.append(x)\n concept_neg_data.append(x)\n\n if len(concept_neg_data) == total_neg_num:\n break\n\n if len(concept_neg_data) == total_neg_num:\n break\n\n print(\n f\"Number of negative records generated : {len(concept_neg_data)}\",\n flush=True,\n )\n print(f\"Negative Records\", flush=True)\n print(concept_neg_data, flush=True)\n print()\n\n _ = [x.insert(len(x), int(0)) for x in all_negative_data]\n\n # print(\"all_negative_data\")\n # print(all_negative_data)\n\n all_neg_data_df = pd.DataFrame.from_records(\n all_negative_data, columns=[\"concept\", \"conjuct_prop\", \"property\", \"label\"]\n )\n\n neg_data_duplicate_records = all_neg_data_df[\n all_neg_data_df.duplicated([\"concept\", \"conjuct_prop\", \"property\"])\n ]\n\n print()\n print(f\"all_neg_data_df.shape : {all_neg_data_df.shape}\", flush=True)\n print(\n f\"neg_data_duplicate_records.shape : {neg_data_duplicate_records.shape}\",\n flush=True,\n )\n print()\n\n print(f\"Checking overlap between positive and negative data\", flush=True)\n pos_neg_overlap_df = df.merge(\n all_neg_data_df,\n how=\"inner\",\n on=[\"concept\", \"conjuct_prop\", \"property\"],\n indicator=False,\n )\n print(f\"Positive and Negative Overlapped Dataframe\", flush=True)\n print(pos_neg_overlap_df, flush=True)\n print()\n\n pos_neg_df = pd.concat([df, all_neg_data_df], axis=0, ignore_index=True)\n\n print(\"DF after adding negative data\", flush=True)\n print(pos_neg_df.shape, flush=True)\n\n duplicate_records = pos_neg_df[\n pos_neg_df.duplicated([\"concept\", \"conjuct_prop\", \"property\"])\n ]\n\n print(f\"Duplicate Records : {duplicate_records.shape}\", flush=True)\n print(\n f\"Duplicate record label value count: {duplicate_records['label'].value_counts()}\",\n flush=True,\n )\n print()\n\n pos_neg_df = pos_neg_df[\n ~pos_neg_df.duplicated(\n subset=[\"concept\", \"conjuct_prop\", \"property\"], keep=\"first\"\n )\n ]\n\n pos_neg_df.drop_duplicates(inplace=True)\n pos_neg_df.dropna(how=\"any\", inplace=True)\n\n pos_neg_df.dropna(axis=0, subset=[\"concept\"], inplace=True)\n pos_neg_df.dropna(axis=0, subset=[\"conjuct_prop\"], inplace=True)\n pos_neg_df.dropna(axis=0, subset=[\"property\"], inplace=True)\n pos_neg_df.dropna(axis=0, subset=[\"label\"], inplace=True)\n\n pos_neg_df = pos_neg_df.sample(frac=1)\n\n print(f\"Dataframe after removing duplicates : {pos_neg_df.shape}\", flush=True)\n\n save_path = \"/scratch/c.scmag3/biencoder_concept_property/data/train_data/joint_encoder_property_conjuction_data\"\n\n if data_type == \"train\":\n\n file_name = os.path.join(\n save_path, f\"{num_negative}_neg_prop_conj_train_cnet_premium.tsv\",\n )\n pos_neg_df.to_csv(file_name, sep=\"\\t\", index=None, header=None)\n\n elif data_type == \"valid\":\n\n file_name = os.path.join(\n save_path, f\"{num_negative}_neg_prop_conj_valid_cnet_premium.tsv\",\n )\n pos_neg_df.to_csv(file_name, sep=\"\\t\", index=None, header=None)\n\n return pos_neg_df\n\n\nlocal_file_name = \"siamese_concept_property/data/train_data/joint_encoder_property_conjuction_data/random_and_similar_conjuct_properties.tsv\"\n\nprint(f\"************ Generating Negative Train Data ************\", flush=True)\n\nhawk_train_file = \"/scratch/c.scmag3/biencoder_concept_property/data/train_data/joint_encoder_property_conjuction_data/prop_conj_train_cnet_premium.tsv\"\n\ntrain_df = pd.read_csv(\n hawk_train_file, sep=\"\\t\", names=[\"concept\", \"conjuct_prop\", \"property\"]\n)\n\nprint(f\"Train File : {hawk_train_file}\")\nprint(f\"Train DF Shape : {train_df.shape}\")\n\npos_neg_train_df = negative_sampling(train_df, \"train\", num_negative=5)\n\nprint(f\"************ Generating Negative Valid Data ************\", flush=True)\n\n\nhawk_valid_file = \"/scratch/c.scmag3/biencoder_concept_property/data/train_data/joint_encoder_property_conjuction_data/prop_conj_valid_cnet_premium.tsv\"\n\nvalid_df = pd.read_csv(\n hawk_valid_file, sep=\"\\t\", names=[\"concept\", \"conjuct_prop\", \"property\"]\n)\n\npos_neg_valid_df = negative_sampling(valid_df, \"valid\", num_negative=5)\n\nprint(f\"************ Negative Data Generation Process Ends ************\", flush=True)\n\n","repo_name":"amitgajbhiye/property_augmentation","sub_path":"src/data_prepr/je_prop_conjuction_pretrain_neg_data_sampling.py","file_name":"je_prop_conjuction_pretrain_neg_data_sampling.py","file_ext":"py","file_size_in_byte":6969,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"73935985400","text":"import dbus\nimport dbus.service\nimport datetime\nfrom calendar import timegm\n\nfrom configuration import runtime\n\n# DBus service parameters\nHAMSTER_URI = \"org.gnome.Hamster\"\nHAMSTER_PATH = \"/org/gnome/Hamster\"\n\n# Data-keys used in hamster to refer \n# facts, categories and activities\nFCT_KEY = 'id'\nACT_KEY = 'name'\nCAT_KEY = 'category'\nDSC_KEY = 'description'\nSRT_KEY = 'start_time'\nEND_KEY = 'end_time'\n\nclass HamsterDbusController(dbus.service.Object):\n # Non-initialized current fact id\n current_fact_id = 0\n\n def __init__(self, bus_name):\n \"\"\"HamsterDbusController encapsulates the dbus api logic\n for the hamster-applet and performs the necesary conversion\n between dbus types and hamster-applet data types\n \"\"\"\n dbus.service.Object.__init__(self, bus_name, HAMSTER_PATH)\n\n @staticmethod\n def to_dbus_fact(fact):\n \"\"\"Perform the conversion between fact database query and \n dbus supported data types\n \"\"\"\n\n # Default fact values\n dbus_fact = {FCT_KEY: 0, ACT_KEY:'', CAT_KEY:'', DSC_KEY:'',\n SRT_KEY:0, END_KEY:0}\n\n if fact:\n # Workaround for fill values\n fact_keys = fact.keys()\n\n for key in (FCT_KEY, ACT_KEY, CAT_KEY, DSC_KEY):\n if key in fact_keys and fact[key]: \n dbus_fact[key] = fact[key]\n \n for key in (SRT_KEY, END_KEY):\n if key in fact_keys and fact[key]:\n # Convert datetime to unix timestamp (seconds since epoch)\n dbus_fact[key] = timegm(fact[key].timetuple())\n\n return dbus_fact\n\n @dbus.service.method(HAMSTER_URI, out_signature='a{sv}')\n def GetCurrentFact(self):\n \"\"\"Gets the current displaying fact\n Returns Dict of:\n i id: Unique fact identifier\n s name: Activity name\n s category: Category name\n s description: Description of the fact\n u start_time: Seconds since epoch (timestamp)\n u end_time: Seconds since epoch (timestamp)\n \"\"\"\n return HamsterDbusController.to_dbus_fact(runtime.storage.get_last_activity())\n\n @dbus.service.method(HAMSTER_URI, in_signature='i', out_signature='a{sv}')\n def GetFactById(self, fact_id):\n \"\"\"Gets the current displaying fact\n Parameters:\n i id: Unique fact identifier\n Returns Dict of:\n i id: Unique fact identifier\n s name: Activity name\n s category: Category name\n s description: Description of the fact\n u start_time: Seconds since epoch (timestamp)\n u end_time: Seconds since epoch (timestamp)\n \"\"\"\n return HamsterDbusController.to_dbus_fact(runtime.storage.get_fact(fact_id))\n\n @dbus.service.method(HAMSTER_URI, out_signature='a(ss)')\n def GetActivities(self):\n \"\"\"Gets all defined activities with matching category\n Returns Array of:\n s activity: Activity name\n s category: Category name\n \"\"\"\n activities = []\n for act in runtime.storage.get_autocomplete_activities():\n activities.append((act[ACT_KEY] or '', act[CAT_KEY] or ''))\n return activities\n\n @dbus.service.method(HAMSTER_URI, out_signature='as')\n def GetCategories(self):\n \"\"\"Gets all defined categories\n Returns Array of:\n s category: Category name\n \"\"\"\n categories = []\n for i in runtime.storage.get_category_list():\n categories.append(i[ACT_KEY] or '')\n return categories\n\n @dbus.service.method(HAMSTER_URI, in_signature='suu', out_signature='i')\n def AddFact(self, activity, start_time, end_time):\n \"\"\"Add a new fact\n Parameters:\n s activity: Activity name with optional category and/or description\n in the form 'activity_name[@category_name][,description]'\n Activity and matching category will be refered or created \n on the fly.\n u start_time: Seconds since epoch (timestamp). Use 0 for 'now'\n u end_time: Seconds since epoch (timestamp). \n Use 0 for i 'in progress task'\n \"\"\"\n #TODO: Assert start > end ?\n start, end = None, None\n\n if start_time:\n start = datetime.datetime.utcfromtimestamp(start_time)\n if end_time:\n end = datetime.datetime.utcfromtimestamp(end_time)\n\n fact = runtime.storage.add_fact(activity, start, end)\n return fact[FCT_KEY]\n\n @dbus.service.method(HAMSTER_URI, in_signature='ss')\n def AddActivity(self, activity, category):\n \"\"\"Add a new activity\n Parameters:\n s activity: Activity name\n s category: Category name. It will be created if it doesn't exists\n Use '' for Unsorted activity\n \"\"\"\n category_id = None\n\n if category:\n category_id = runtime.storage.get_category_by_name(category) \\\n or runtime.storage.add_category(category)\n\n runtime.storage.add_activity(activity, category_id)\n\n @dbus.service.method(HAMSTER_URI, in_signature='s')\n def AddCategory(self, category):\n \"\"\"Add a new category\n Parameters:\n s category: category name\n \"\"\"\n if category and not runtime.storage.get_category_by_name(category):\n runtime.storage.add_category(category)\n\n @dbus.service.method(HAMSTER_URI)\n def StopTracking(self):\n \"\"\"Stops the current fact tracking\"\"\"\n last_activity = runtime.storage.get_last_activity()\n if last_activity:\n runtime.storage.touch_fact(last_activity)\n\n @dbus.service.method(HAMSTER_URI, in_signature='i')\n def RemoveFact(self, fact_id):\n \"\"\"Removes a fact\n Parameters:\n i id: Unique fact identifier\n \"\"\"\n runtime.storage.remove_fact(fact_id)\n\n @dbus.service.method(HAMSTER_URI, in_signature='ss')\n def RemoveActivity(self, activity, category):\n \"\"\"Removes an activity\n Parameters:\n s activity: Activity name\n s category: Category name. Use '' for Unsorted activity\n \"\"\"\n category_id = runtime.storage.get_category_by_name(category)\n activity_id = runtime.storage.get_activity_by_name(activity, category_id)\n\n if activity_id:\n runtime.storage.remove_activity(activity_id)\n\n @dbus.service.method(HAMSTER_URI, in_signature='s')\n def RemoveCategory(self, category):\n \"\"\"Removes a category\n Parameters:\n s category: Category name\n \"\"\"\n category_id = runtime.storage.get_category_by_name(category)\n if category_id:\n runtime.storage.remove_category(category_id)\n\n @dbus.service.signal(HAMSTER_URI, signature='i')\n def FactUpdated(self, fact_id):\n \"\"\"Notice fact changes\n Parameters:\n i id: Unique fact identifier\n \"\"\"\n self.current_fact_id = fact_id\n\n @dbus.service.signal(HAMSTER_URI)\n def TrackingStopped(self):\n \"\"\"Notice the fact tracking has been stopped\"\"\"\n self.current_fact_id = 0\n","repo_name":"blaxter/hamster-applet","sub_path":"hamster/hamsterdbus.py","file_name":"hamsterdbus.py","file_ext":"py","file_size_in_byte":7124,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"40"} +{"seq_id":"71945420921","text":"# Default Django import\nfrom dateutil.parser import parse\nimport time\n\nfrom django.db import models\n\n# Imports for Simple Cache\nfrom django.utils import timezone\nfrom django.db import DatabaseError, transaction\nfrom django.core.exceptions import ObjectDoesNotExist\n\n# Imports for NewsNetParser\nfrom lxml import etree\nfrom xml.etree.ElementTree import Element, SubElement, Comment, tostring\nimport re\nimport requests\nimport datetime\nfrom simplecache.models import SimpleCache\nfrom django.template.defaultfilters import slugify\n\n# This class handles the scraping of HTML to get NewsNet titles, dates, and links\nclass NewsReleases():\n\n # Scrape the NewsNet digest for all article content\n @staticmethod\n def get_news_release_list(ward_number): \n \n if ward_number == \"1\": \n rss_feed = \"https://public.govdelivery.com/topics/AZTUCSON_6/feed.rss\"\n elif ward_number == \"2\":\n rss_feed = \"https://public.govdelivery.com/topics/AZTUCSON_7/feed.rss\" \n elif ward_number == \"3\":\n rss_feed = \"https://public.govdelivery.com/topics/AZTUCSON_11/feed.rss\" \n elif ward_number == \"4\":\n rss_feed = \"https://public.govdelivery.com/topics/AZTUCSON_12/feed.rss\" \n elif ward_number == \"5\":\n rss_feed = \"https://public.govdelivery.com/topics/AZTUCSON_13/feed.rss\" \n elif ward_number == \"6\":\n rss_feed = \"https://public.govdelivery.com/topics/AZTUCSON_14/feed.rss\" \n else:\n rss_feed = \"https://public.govdelivery.com/topics/AZTUCSON_9/feed.rss\" \n ward_number = \"0\"\n\n # Define the feed we will be pulling links from\n feed_page = requests.get(rss_feed)\n # Get the body of the request\n feed_html = feed_page.content\n\n # Create a dom tree to parse of our feed\n dom = etree.XML(feed_html)\n # Grab all of the link items - This returns all the urls from the rss feed:\n url_object = dom.xpath('//item/link/text()')\n\n # Grab all of the title items - This returns all the titles from the rss feed:\n title_object = dom.xpath('//item/title/text()')\n\n # Grab all of the date items - This returns the published date of each release: in this format: Tue, 05 Jan 2021 11:02:33 -0600\n date_object = dom.xpath('//item/pubDate/text()')\n\n # Initialize our list to store the links in\n url_list = list()\n\n # Look over the object containing our links\n for num, current_item in enumerate(url_object, start=0):\n # Initialize a list to store our values in\n current_item_list = list()\n # Get the URL\n # This returns the current news release url in the loop\n current_item_url = url_object[num]\n\n # Process the URL and get the token\n url_token = current_item_url.replace(\"https://content.govdelivery.com/accounts/AZTUCSON/bulletins/\", \"\")\n current_item_list.append(url_token)\n current_item_list.append(title_object[num])\n\n # current_item_list - Returns url token and title of current news release\n\n # Returns the date of the news release as yyyy-mm-dd hh:mm:ss-06:00\n clean_date = parse(date_object[num], fuzzy=True)\n\n # Returns the url token, title, and date of the news release as yyyy-mm-dd hh:mm:ss-06:00\n current_item_list.append(clean_date.strftime(\"%B %d, %Y\"))\n \n # Returns the url token, title, date of the news release as yyyy-mm-dd hh:mm:ss-06:00, and ward number\n current_item_list.append(ward_number)\n\n # Returns full list of all the url token, title, date of the news release as yyyy-mm-dd hh:mm:ss-06:00, and ward number\n # Add each link from the object to our list\n url_list.append(current_item_list)\n\n # Return our populated list\n return url_list\n\n @staticmethod\n def get_news_release(article):\n current_article = list()\n # Define the feed we will be pulling links from\n feed_page = requests.get(\"https://content.govdelivery.com/accounts/AZTUCSON/bulletins/\" + article)\n # Get the body of the request\n feed_html = feed_page.content\n # Create a dom tree to parse of our HTML\n dom = etree.HTML(feed_html)\n\n # Get the date from the page\n article_title = dom.xpath('//h1[@class=\"bulletin_subject\"]//text()')\n print(\"article_title\")\n print(article_title)\n article_date = dom.xpath('//span[contains(@class, \"dateline\")]//text()')\n print(\"article_date\")\n print(article_date)\n article_object = dom.xpath('//*[@id=\"bulletin_body\"]')\n print(\"article_object\")\n print(article_object)\n current_article_part = \"\"\n for article_part in article_object:\n this_part = etree.tostring(article_part, method='html', with_tail=False)\n current_article_part = this_part.decode(\"utf-8\")\n\n current_article.append(article_title[0])\n current_article.append(article_date[0])\n current_article.append(current_article_part)\n\n print(\"current_article\")\n print(current_article)\n \n return current_article\n","repo_name":"jduclos1/NewsNetParser","sub_path":"NewsReleases/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5256,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"25881426972","text":"# class solution:\ndef fibnacci(n):\n if n==0: return 0\n if n==1: return 1\n return fibnacci(n-1)+fibnacci(n-2)\n# classic recursion\n\ndef fibnacci_cut(n,dp):\n if n==0: return 0\n if n==1: return 1\n if dp[n]!=0: return dp[n]\n dp[n]=fibnacci_cut(n-1,dp)+fibnacci_cut(n-2,dp)\n return dp[n]\n# (pruning) dp[n] print\n\ndef fib_memorized(n):\n dp=[0]*(n+1)\n return fibnacci_cut(n,dp)\n# 开完数组直接调用\n\ndef testfib(n):\n # print(fibnacci(n))\n print(fib_memorized(n))\n# for test\n\ndef dp_solve_fib(n):\n if n==0: return 0\n dp=[0]*(n+1)\n dp[0],dp[1]=0,1\n for i in range(2,n+1):\n dp[i]=dp[i-1]+dp[i-2]\n\n return dp[n]\n\n# 写程序的时候一开始都是状态,定义环节,抽象成变量把他写出来\n# 第二阶段就是吧最边界的情况返回值写出来\n# 之后就是无尽的关键语句和循环判断,难得就多几个函数\ndef max_cake_price(n,price_list):\n if n<=1: return price_list[n]\n dp=[0]*(n+1)\n for j in range(1,n+1):\n for i in range(j):\n dp[j]=max(dp[j],dp[i]+price_list[j-i])\n return dp[j]\n\ntestfib(100)\n\n\n","repo_name":"manshushu/edifice","sub_path":"spider/fibnacci.py","file_name":"fibnacci.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"13411751900","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport statsmodels.api as sm\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom keras.layers import Embedding, SpatialDropout1D, LSTM, concatenate\nfrom keras.layers import Dense\nfrom keras.models import Model\nfrom keras.callbacks import EarlyStopping\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.utils import pad_sequences\nfrom keras import Sequential\nfrom sklearn.model_selection import train_test_split\nimport tensorflow_hub as hub\nfrom keras import models\n\n# CLEANING STEPS, MUST APPLY ALL TO MODEL USE WHEN TRAINING AND USING MODEL\ndf = pd.read_csv(r\"C:\\Users\\aaron\\OneDrive\\Documents\\quest\\test_data.csv\")\n#df['Organic Searches'].plot.kde()\navg = df.groupby(by = ['Page Title'], as_index = False).agg({'Pageviews' : 'sum', 'Organic Searches' : 'sum'})\ndf2 = df.drop_duplicates(subset=['Page Title'])\ndf = pd.merge(avg, df2[['Page Title', 'date_published', 'category']], how='left', on='Page Title')\ndf['log_organic'] = np.log(df['Organic Searches'] + 1)\n\n#df['log_organic'] = np.log(df['Organic Searches'] + 1)\n# df['log_organic'].plot.kde()\ndf['question_mark']=0\ndf['hit'] = df['log_organic'] > 1\ndf['date_published'] = pd.to_datetime(df['date_published'])\n\n# articles that were posted prior to the dataset should only be not considered if they have poor views\ndf = df[(df['date_published'].dt.year >= 2020) | df['hit']]\n\n\ndef lstm_model(X):\n MAX_NB_WORDS = 50000\n # Max number of words in each title\n MAX_SEQUENCE_LENGTH = 250 \n # This is fixed.\n EMBEDDING_DIM = 100\n model = Sequential()\n model.add(Embedding(MAX_NB_WORDS, EMBEDDING_DIM, input_length=X.shape[1]))\n print('layer')\n model.add(SpatialDropout1D(0.2))\n print('layer2')\n model.add(LSTM(100, dropout=0.2, recurrent_dropout=0.2))\n print('layer3')\n model.add(Dense(2, activation='softmax'))\n print('layer4')\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n return model\n\ndef sentiment_model(X):\n model = Sequential()\n model.add(Dense(1, activation='linear'))\n return model\n#print(predictions)\n# The maximum number of words to be used. (most frequent)\nMAX_NB_WORDS = 50000\n# Max number of words in each title\nMAX_SEQUENCE_LENGTH = 250 \n# This is fixed.\nEMBEDDING_DIM = 100\ntokenizer = Tokenizer(num_words=MAX_NB_WORDS, filters='!\"#$%&()*+,-./:;<=>?@[\\]^_`{|}~', lower=True)\n\n# MUST FIT TOKENIZER ON FULL DATASET AND MAINTAIN SAME AS USE OF MODEL\ntokenizer.fit_on_texts(df['Page Title'].values)\nword_index = tokenizer.word_index\nprint('Found %s unique tokens.' % len(word_index))\nX = tokenizer.texts_to_sequences(df['Page Title'].values)\nX = pad_sequences(X, maxlen=MAX_SEQUENCE_LENGTH)\n# print(X)\n#X = concatenate([X, df['question_mark'].to_numpy])\n\n\nprint('Shape of data tensor:', X.shape)\ny = pd.get_dummies(df['hit'])\nY = y.values\ndf['senti'] = 0\n\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2)\nlstm = lstm_model(X_train)\nsentiment = sentiment_model(df['senti'])\n\n# model = Sequential()\n# model.add(Embedding(MAX_NB_WORDS, EMBEDDING_DIM, input_length=X.shape[1]))\n# print('layer')\n# model.add(SpatialDropout1D(0.2))\n# print('layer2')\n# model.add(LSTM(100, dropout=0.2, recurrent_dropout=0.2))\n# print('layer3')\n# model.add(Dense(2, activation='softmax'))\nprint('layer4')\n#model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n#model.compile(loss='BinaryCrossentropy', optimizer='adam', metrics=['accuracy'])\nprint('layer5')\nprint(X_train.shape,y_train.shape)\nprint(X_test.shape,y_test.shape)\nsentiment = sentiment_model()\n# set epochs\nepochs = 5\nbatch_size = 64\n# final = Dense(4, activation=\"relu\")(combinedInput)\n# final = Dense(1, activation=\"linear\")(x)\ncombinedInput = concatenate([lstm.output, sentiment.output])\nx = Dense(4, activation=\"relu\")(combinedInput)\nx = Dense(1, activation=\"linear\")(x)\n\nmodel = Model(inputs=[lstm.input, ], outputs=x)\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\nprint(X)\n#print(np.concatenate((X,df['senti'].to_numpy), axis=1))\nhistory = model.fit([X_train], y_train, epochs=epochs, batch_size=batch_size,validation_split=0.1,callbacks=[EarlyStopping(monitor='val_loss', patience=3, min_delta=0.0001)])\n\naccr = model.evaluate(X_test,y_test)\nprint('Test set\\n Loss: {:0.3f}\\n Accuracy: {:0.3f}'.format(accr[0],accr[1]))\n#plt.scatter(predictions.index, predictions)\n#plt.show()\n#print((y_test.astype(int) - predictions.astype(int)))\n#print(predictions)\n##print(y_test)\n#((y_test - predictions) != 0).to_csv(r\"C:\\Users\\aaron\\OneDrive\\Documents\\quest\\predicted_wrong.csv\")\n# print(df['hit'])\n# print(Y)\nnew_headline = ['umd suffers massive defeat']\nseq = tokenizer.texts_to_sequences(new_headline)\npadded = pad_sequences(seq, maxlen=MAX_SEQUENCE_LENGTH)\npred = model.predict(padded)\nlabels = []\nprint(y.columns)\nfor val in y.columns:\n if val == True:\n labels.append('not hit')\n else:\n labels.append('hit')\n# first represents how much of a hit it is\nprint(pred, labels[np.argmax(pred)])\nprint(model.summary())\n#model.save(r\"C:\\Users\\aaron\\OneDrive\\Documents\\quest\\dbk_consulting\\model.h5\")\n\n# plt.title('Loss')\n# plt.plot(history.history['loss'], label='train')\n# plt.plot(history.history['val_loss'], label='test')\n# plt.legend()\n# plt.show()\n# plt.title('Accuracy')\n# plt.plot(history.history['acc'], label='train')\n# plt.plot(history.history['val_acc'], label='test')\n# plt.legend()\n# plt.show()","repo_name":"Aaroney13/dbk_consulting","sub_path":"testing_twomodels.py","file_name":"testing_twomodels.py","file_ext":"py","file_size_in_byte":5507,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"75053532920","text":"\"\"\"\nName:Zar Chi Oo\nDate:12/1/2023\nBrief Project Description:Reading Tracker Program Assignment 2\nGitHub URL:https://github.com/JCUS-CP1404/cp1404-reading-tracker---assignment-2-ZarChi123.git\n\"\"\"\n\nfrom kivy.app import App\nfrom kivy.lang import Builder\nfrom kivy.uix.button import Button\n\nfrom book import Book\nfrom bookcollection import BookCollection\n\nFILENAME = 'books.csv'\nCOMPLETED_COLOR = (1, 1, 1, 0.6)\nREQUIRED_COLOR = (0, 1, 0.8, 0.7)\n\n\nclass ReadingTrackerApp(App):\n \"\"\"...\"\"\"\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.books = BookCollection()\n\n def build(self):\n \"\"\"Build Reading Tracker 2.0 App from app.kv file\"\"\"\n self.title = \"Reading Tracker 2.0\"\n self.root = Builder.load_file('app.kv')\n try:\n self.books.load_books(FILENAME)\n self.display_top_label()\n self.display_bottom_label(\"Welcome to Reading Tracker 2.0.\")\n self.sort_book_list(\"author\")\n # if books.csv does not exist\n except (FileNotFoundError, LookupError):\n self.display_top_label()\n self.display_bottom_label(\"Welcome to Reading Tracker 2.0. Unable to load books.csv!\")\n return self.root\n\n def display_top_label(self):\n \"\"\"Label that shows pages to be read\"\"\"\n self.root.ids.top_label.text = \"Pages to read:{}\".format(self.books.get_required_pages())\n\n def display_bottom_label(self, bottom_label):\n \"\"\"Label that display in the bottom of the GUI\"\"\"\n self.root.ids.bottom_label.text = bottom_label\n\n def sort_book_list(self, key='author'):\n \"\"\"Sort the book list\"\"\"\n if key.lower() == 'completed':\n key = 'is_completed'\n self.books.sort(key.lower()) # sort books\n self.root.ids.book_list.clear_widgets() # clear widgets\n book_list = []\n\n def change_state(button):\n \"\"\"Change colour and label according to user's click\"\"\"\n for selected_book in book_list: # matching the button.text and clicked book\n if selected_book.title in button.text:\n BookButton.on_click(self, selected_book)\n if book.is_completed:\n self.state = 'normal' # change button state\n button.background_color = COMPLETED_COLOR # change background color\n else:\n self.state = 'down' # change button state\n button.background_color = REQUIRED_COLOR # change background color\n button.text = str(selected_book) # change text on button\n self.sort_book_list(key) # sort the books again for dynamic sorting\n\n for book in self.books:\n # convert book into a list for sorting\n book_list.append(book)\n # initialize the books' states\n if book.is_completed:\n self.state = 'normal'\n else:\n self.state = 'down'\n # add the books\n self.root.ids.book_list.add_widget(BookButton(book=book, text=str(book), on_press=change_state,\n background_color=\n {'normal': COMPLETED_COLOR, 'down': REQUIRED_COLOR}[\n self.state]\n ))\n\n def add_new_book(self, input_title, input_author, input_pages):\n \"\"\"Handle Add New Book...\"\"\"\n title, author, pages = map(str.strip, (input_title.text, input_author.text, input_pages.text))\n\n # check if all the fields are filled\n if not title or not author or not pages:\n self.display_bottom_label(\"All fields must be completed\")\n return\n # check if the input pages is valid\n try:\n pages = int(pages)\n except ValueError:\n self.display_bottom_label(\"Please enter a valid number\")\n return\n # check if the input page is greater than 0\n if pages < 1:\n self.display_bottom_label(\"Pages must be > 0\")\n return\n\n self.sort_book_list()\n self.display_bottom_label(\" \")\n title = title + \" \"\n self.books.add_book(Book(title, author, pages))\n self.display_top_label()\n self.display_bottom_label(f\"{title} by {author}, ({pages} pages) added to Reading Tracker.\")\n self.sort_book_list(self.root.ids.book_sorter.text)\n self.clear_input_field(input_title, input_author, input_pages)\n\n @staticmethod\n def clear_input_field(title, author, pages):\n \"\"\"Clear the user inputs fields of title,author and pages\"\"\"\n title.text = ''\n author.text = ''\n pages.text = ''\n\n def on_stop(self):\n \"\"\"Save an updated book list file when the app is closed\"\"\"\n self.books.save_books(FILENAME)\n return super().on_stop()\n\n\nclass BookButton(Button):\n def __init__(self, book, **kwargs):\n super().__init__(**kwargs)\n self.book = book\n\n def on_click(self, book):\n \"\"\"\n Click mark completed or required by changing the background color and display the top and bottom labels\n \"\"\"\n if book.is_completed:\n book.mark_required() # mark the click book as required\n if book.is_long():\n bottom_label = \"You need to read {}. Get Started!\".format(str(book.title).strip())\n else:\n bottom_label = \"You need to read {}.\".format(str(book.title).strip())\n else:\n book.mark_completed() # mark the clicked book as completed\n if book.is_long():\n bottom_label = \"You completed {}. Great Job!\".format(str(book.title).strip())\n else:\n bottom_label = \"You completed {}.\".format(str(book.title).strip())\n\n self.display_top_label()\n self.display_bottom_label(bottom_label)\n\n\nif __name__ == '__main__':\n ReadingTrackerApp().run()\n","repo_name":"JCUS-CP1404/cp1404-reading-tracker---assignment-2-ZarChi123","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"1599959061","text":"#GPIO library\nimport RPi.GPIO as GPIO\n\n#time library\nimport time\n\n#pin Definition - check if PWM is needed\nright_haptic = 32\nleft_haptic = 33\n\n\n#set up the GPIO channel\nGPIO.setmode(GPIO.BOARD)\n#remove warnings\nGPIO.setwarnings(True)\n#set both PWM pins as low output pins\nGPIO.setup(left_haptic, GPIO.OUT, initial=GPIO.LOW)\nGPIO.setup(right_haptic, GPIO.OUT, initial=GPIO.LOW)\n#assign PWM pins\np_right = GPIO.PWM(right_haptic, 50)\np_left = GPIO.PWM(left_haptic, 50)\n#start PWM pins with 0 duty cycle\np_right.start(0)\np_left.start(0)\n\nprint(\"PINS initialized! Waiting for Vibration requests From Arduino.\")\n\n#function used to run the right haptic motors with the passed intensity\ndef runRightHaptic(intensity):\n #calculation used to obtain duty cycle\n duty_cycle = intensity * 10\n #update duty cycle of pwm based on intensity\n p_right.ChangeDutyCycle(duty_cycle)\n\n#function used to run the left haptic motors with the passed intensity\ndef runLeftHaptic(intensity):\n #calculation used to obtain duty cycle\n duty_cycle = intensity * 10\n #update duty cycle of pwm based on intensity\n p_left.ChangeDutyCycle(duty_cycle)\n\n","repo_name":"NuViu/CEG4912-4913-JetsonNano","sub_path":"haptic_handler.py","file_name":"haptic_handler.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"25993855590","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\nimport random\r\n\r\nliczba = random.randint(1, 10)\r\n#print(\"Wylosowana liczba: \", liczba)\r\n\r\nfor i in range(3):\r\n print(\"Próba\", i + 1)\r\n odp = input(\"Jaką liczbę od 1 do 10 mam na myśli? Podaj liczbę: \")\r\n #print(\"Podałeś liczbę: \", odp)\r\n\r\n if liczba == odp:\r\n print(\"Brawo! Odgadłeś liczbę!\")\r\n brake\r\n elif i == 2:\r\n print(\"Miałem na myśli liczbę\", liczba)\r\n else:\r\n print(\"Niestety, nie udało się :( Podana liczba nie jest prawidłowa. Spróbuj jeszcze raz! :)\")\r\n","repo_name":"gagusrotfl/nauka","sub_path":"toto.py","file_name":"toto.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"6086510591","text":"import os\nimport logging\nimport json\n\nimport boto3\n\nlogger = logging.getLogger('crawler')\n\n\ndef notify(url):\n sqs = boto3.client('sqs')\n\n account_id = os.getenv('AWS_ACCOUNT_ID')\n aws_region = os.getenv('AWS_DEFAULT_REGION')\n sqs_queue = os.getenv('GBIMAGECLASSIFIER_CRAWLERQUEUE')\n\n queue_url = f\"https://sqs.{aws_region}.amazonaws.com/{account_id}/{sqs_queue}\"\n\n try:\n response = sqs.send_message(\n QueueUrl=queue_url,\n MessageBody=(\n json.dumps({\"action\": \"download\", \"msg\": {\"url\": url}})\n )\n )\n return response\n except Exception as e:\n logger.error(f\"Failed to send {url} to analysis queue\")\n logger.error(queue_url)\n logger.error(e)\n","repo_name":"garybake/siteanalyzer","sub_path":"ui-service/crawler_queue.py","file_name":"crawler_queue.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"2480476906","text":"from django.urls import path\nfrom rest_framework.exceptions import ValidationError\n\nfrom . import views, authentication\n\n\napp_name = 'manage'\n\nurlpatterns = [\n path('auth/jwt/create/', authentication.TokenObtainPairView.as_view(), name=\"logout\"),\n path('test/', views.test, name='test'),\n path('manage_user_me/', views.manage_user_me, name='manage_user_me'),\n path('access_home/', views.access_home, name='access_home'),\n path('order/get_order/', views.get_order, name='get_order'),\n path('order/get_orders/', views.get_orders, name='get_orders'),\n path('order/order_action/', views.order_action, name='order_action'),\n path('floor/get_rooms/', views.get_rooms, name='get_rooms'),\n path('floor/get_waiting_list/', views.get_waiting_list, name='get_waiting_list'),\n path('floor/create_waiting_ticket/', views.waiting_ticket_create, name='create_waiting_ticket'),\n path('floor/get_today_reserve_list/', views.get_today_reserve_list, name='get_today_reserve_list'),\n path('access_order_history/', views.access_order_history, name='access_order_history'),\n path('access_menu/', views.access_menu, name='access_menu'),\n path('access_room/', views.access_room, name='access_room'),\n path('access_shop_info/', views.access_shop_info, name='access_shop_info'),\n path('to_day_messages/', views.to_day_messages, name='to_day_messages'),\n path('messages_custom_category/', views.messages_custom_category, name='messages_custom_category'),\n path('shops/', views.shops, name='user_manage_shops'),\n]","repo_name":"pokogas/ordeE-project","sub_path":"backend/Manage/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"32251322922","text":"import json\n\nimport pytest\nfrom typing import TYPE_CHECKING\n\nimport responses\nfrom click.testing import CliRunner\n\nfrom cycode.cli.main import main_cli\nfrom tests.conftest import TEST_FILES_PATH, CLI_ENV_VARS\nfrom tests.cyclient.test_scan_client import get_zipped_file_scan_response, get_zipped_file_scan_url\n\n_PATH_TO_SCAN = TEST_FILES_PATH.joinpath('zip_content').absolute()\n\nif TYPE_CHECKING:\n from cycode.cyclient.scan_client import ScanClient\n\n\ndef _is_json(plain: str) -> bool:\n try:\n json.loads(plain)\n return True\n except (ValueError, TypeError):\n return False\n\n\n@responses.activate\n@pytest.mark.parametrize('output', ['text', 'json'])\n@pytest.mark.parametrize('option_space', ['scan', 'global'])\ndef test_passing_output_option(\n output: str, option_space: str, scan_client: 'ScanClient', api_token_response: responses.Response\n):\n scan_type = 'secret'\n\n responses.add(get_zipped_file_scan_response(get_zipped_file_scan_url(scan_type, scan_client)))\n responses.add(api_token_response)\n # scan report is not mocked. This raise connection error on attempt to report scan. it doesn't perform real request\n\n args = ['scan', '--soft-fail', 'path', str(_PATH_TO_SCAN)]\n\n if option_space == 'global':\n global_args = ['--output', output]\n global_args.extend(args)\n\n args = global_args\n elif option_space == 'scan':\n # test backward compatability with old style command\n args.insert(2, '--output')\n args.insert(3, output)\n\n result = CliRunner().invoke(main_cli, args, env=CLI_ENV_VARS)\n\n except_json = output == 'json'\n\n assert _is_json(result.output) == except_json\n\n if except_json:\n output = json.loads(result.output)\n assert 'scan_id' in output\n else:\n assert 'Scan Results' in result.output\n","repo_name":"michaels256/cycode-cli","sub_path":"tests/cli/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"40"} +{"seq_id":"29959932412","text":"# Draw right aligned pyramid as in Mario\n\nfrom cs50 import get_int\n\n# Continuously control input: 0 < int < 9\nwhile True:\n height = get_int(\"Height: \")\n if 0 < height < 9:\n break\n else:\n print(\"Height must be between 0 and 9 excluded\")\n\n# Draw as many # as wanted \nfor i in range(height):\n print(\" \" * (height - i - 1) + \"#\" * (i + 1))\n","repo_name":"stefanogrillo/CS50-s-Introduction-to-Computer-Science-2021-2022","sub_path":"pset6/mario (less confortable).py","file_name":"mario (less confortable).py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"15368734880","text":"import os\nimport openai\nimport argparse\nfrom dotenv import load_dotenv\n\n\nclass OpenAIGpt:\n def __init__(self):\n load_dotenv()\n\n def run(self, args):\n question = input(\"Question! : \")\n openai.api_key = \"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\"\n response = openai.Completion.create(\n model=\"ft:davinci-002:somma::8I9Ns6jk\",\n # model=\"<Write your fine-tuning model>\", # 사용할 \"fine-tuning model\" 작성.\n prompt=f\"{question}\",\n temperature=args.temperature,\n max_tokens=100,\n top_p=1,\n frequency_penalty=0.0,\n presence_penalty=0.0,\n stop=[\"\\n\"]\n # stop=None\n )\n # print(response)\n print(response.choices[0].text.strip())\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n # python gpt3.py --temperature 0.3\n parser.add_argument('--temperature', default=0.3)\n\n args = parser.parse_args()\n openai_gpt = OpenAIGpt()\n openai_gpt.run(args)\n","repo_name":"dhwndud/openai-tutorial","sub_path":"gpt3(davinci)_finetuning.py","file_name":"gpt3(davinci)_finetuning.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"31961432222","text":"import math\n\nclass Coeficientes:\n def __init__(self, overshoot, tempAcomodacao):\n self.overshoot = overshoot\n self.tempAcomodacao = tempAcomodacao\n \n def calc_KpKi(self):\n x = (math.log(self.overshoot) / math.pi) ** 2\n e = math.sqrt(-x / (-x - 1))\n\n w = 4 / (e * self.tempAcomodacao)\n\n mf = math.degrees(math.asin(e)) * 2\n\n wcg = w\n\n # PLANTA\n mod_gj = math.sqrt(0.02011 ** 2) / math.sqrt(wcg ** 2 + 0.02402 ** 2)\n #mod_gj = math.sqrt(80 2) / math.sqrt((wcg * 16) 2 + 1 2)\n\n fase_gj = math.degrees(math.atan(0/0.02011)) - math.degrees(math.atan(wcg/0.02402))\n #fase_gj = math.degrees(math.atan(0/80)) - math.degrees(math.atan((wcg * 16)/1))\n\n # CONTROLADOR\n mod_c = 1/mod_gj\n\n fase_c = -180 + mf - fase_gj\n\n x = 1/(wcg ** 2)\n t = math.tan(math.radians(fase_c))\n y = t * -wcg\n\n kp = math.sqrt((mod_c ** 2) / (1 + x * (y ** 2)))\n\n ki = y * kp\n\n return \"Kp: {} \\nKi: {}\".format(kp, ki)","repo_name":"RenanDias12/Controlador_PI","sub_path":"coeficientes.py","file_name":"coeficientes.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"13099243752","text":"# -*- coding: utf-8 -*-\n__author__ = \"kubik.augustyn@post.cz\"\n\n\ndef minify(path):\n ScriptToMinify = open(path, 'r')\n #ScriptToMinify = ScriptToMinify.read()\n MinifiedScriptValue = \"\"\n while True:\n line = ScriptToMinify.readline()\n line = line.replace(\"\\n\", \"\")\n line = line.replace(\" \", \"\")\n if line:\n MinifiedScriptValue += line\n else:\n break\n ScriptToMinify.close()\n MinifiedScript = open(path + \".js\", \"w\")\n MinifiedScript.write(MinifiedScriptValue)\n MinifiedScript.close()\n\n\nif __name__ == '__main__':\n minify(\"a.b.min.js\")\n","repo_name":"kubikaugustyn/kubikaugustyn.github.io","sub_path":"src/js/dhfjdsjfmfjhdgjgfjftrdf==-hdfsujfdgj/minify.py","file_name":"minify.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"3440341539","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('game', '0006_auto_20151023_1510'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='CommitedRessource',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('quantity', models.DecimalField(verbose_name='Amount', max_digits=16, default=0, decimal_places=3)),\n ],\n ),\n migrations.CreateModel(\n name='Ressource',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('textid', models.CharField(max_length=30, verbose_name='Ressource Identifier', default='Undefined')),\n ('total', models.DecimalField(verbose_name='Total', max_digits=16, default=0, decimal_places=3)),\n ('occupied', models.DecimalField(verbose_name='Occupied', max_digits=16, default=0, decimal_places=3)),\n ],\n ),\n migrations.RemoveField(\n model_name='task',\n name='popsize',\n ),\n migrations.RemoveField(\n model_name='village',\n name='food',\n ),\n migrations.RemoveField(\n model_name='village',\n name='population',\n ),\n migrations.RemoveField(\n model_name='village',\n name='population_occ',\n ),\n migrations.RemoveField(\n model_name='village',\n name='wood',\n ),\n migrations.AddField(\n model_name='ressource',\n name='hometown',\n field=models.ForeignKey(to='game.Village'),\n ),\n migrations.AddField(\n model_name='commitedressource',\n name='ressource',\n field=models.ForeignKey(to='game.Ressource'),\n ),\n migrations.AddField(\n model_name='commitedressource',\n name='task',\n field=models.ForeignKey(to='game.Task'),\n ),\n ]\n","repo_name":"Elscouta/hostilelands-py","sub_path":"game/migrations/0007_auto_20151205_0237.py","file_name":"0007_auto_20151205_0237.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"17264154611","text":"# - создать папку\n# после выбора пользователь вводит название папки, создаем её в рабочей директории;\n# - удалить (файл/папку)\n# после выбора пользователь вводит название папки или файла, удаляем из рабочей директории если такой есть;\n# - копировать (файл/папку)\n# после выбора пользователь вводит название папки/файла и новое название папки/файла. Копируем;\n# - просмотр содержимого рабочей директории\n# вывод всех объектов в рабочей папке;\n\n# 1. встроенные модули\nimport random\nimport os\nimport sys\nimport shutil\nimport platform\nimport time\n# 2. наши модули\n# import famous_persons\n# 3. сторонние модули\nimport django\nimport numpy\n\nprint(os.listdir())\nprint('__________')\n# 3 Меню\ndef menu(choice = ''):\n while True:\n print('1. создать папку')\n print('2. удалить (файл/папку)')\n print('3. копировать (файл/папку)')\n print('4. просмотр содержимого рабочей директории')\n print('5. посмотреть только папки')\n print('6. посмотреть только файлы')\n print('7. просмотр информации об операционной системе')\n print('8. создатель программы')\n print('9. играть в викторину')\n print('10. мой банковский счет')\n print('11. смена рабочей директории')\n print('12. выход')\n if len(str(choice)) == 0:\n choice = int(input('Выберите пункт меню '))\n else:\n choice = choice\n if choice in range(1,12,1):\n pass\n elif choice == 12:\n break\n else:\n print('Неверный пункт меню')\n return choice\n\ndef start_menu(choice):\n new_choice = menu(choice)\n while True:\n if new_choice == 1: # создать папку\n account = (input('Введите имя новой папки '))\n if not os.path.exists(f'{account}'):\n # сздать папку передаем путь\n os.mkdir(f'{account}')\n else:\n print('такая папка уже есть')\n new_choice = menu()\n elif new_choice == 2: #удалить (файл/папку)\n account = (input('Введите имя папки/файла для удаления '))\n if not os.path.exists(f'{account}'):\n os.mkdir(f'{account}')\n else:\n print('такого объекта нет')\n elif new_choice == 3: #копировать (файл/папку)\n account_1 = (input('Введите имя папки/файла, которую нужно копировать '))\n account_2 = (input('Введите новое имя папки/файла '))\n if os.path.exists(f'{account_1}'):\n path_1 = os.path.join(os.getcwd(), f'{account_1}')\n path_2 = os.path.join(os.getcwd(), f'{account_2}')\n print(path_1)\n if account_1.find('.') == -1: # если папки\n shutil.copytree(path_1, path_2)\n else:\n shutil.copy(path_1,path_2)\n else:\n print('Копировать нечего, такого файла/папки нет')\n time.sleep(3)\n if path_2 in os.listdir():\n value_chouse = 'path_2'\n new_choice = menu()\n elif new_choice == 4 : #просмотр содержимого рабочей директории\n path = input('Введите папку (для текущей папки введите: .)')\n value_chouse = os.listdir(path)\n print('____________')\n print('просмотр содержимого рабочей директории')\n print(value_chouse)\n print('____________')\n time.sleep(3)\n new_choice = menu()\n elif new_choice == 5: # посмотреть только папки\n for dirpath, dirnames, filenames in os.walk(\".\"):\n # перебрать каталоги\n for dirname in dirnames:\n print(\"Каталог:\", os.path.join(dirpath, dirname))\n time.sleep(3)\n new_choice = menu()\n elif new_choice == 6: # посмотреть только файлы\n # распечатать все файлы и папки рекурсивно\n for dirpath, dirnames, filenames in os.walk(\".\"):\n for filename in filenames:\n print(\"Файл:\", os.path.join(dirpath, filename))\n time.sleep(3)\n new_choice = menu()\n elif new_choice == 7: #просмотр информации об операционной системе\n value_chouse = platform.uname()\n print('____________')\n print('информация об операционной системе')\n print(value_chouse)\n print('____________')\n time.sleep(3)\n new_choice = menu()\n elif new_choice == 8: #создатель программы\n value_chouse = 'Создратель программы: Проневич О.Б.'\n print('____________')\n print(value_chouse)\n print(platform.uname())\n print('____________')\n time.sleep(3)\n new_choice = menu()\n elif new_choice == 9: #играть в викторину\n print('____________')\n import victory\n # victory\n print('____________')\n time.sleep(3)\n new_choice = menu()\n elif new_choice == 10: # мой банковский счет\n print('____________')\n import use_functions\n print('____________')\n time.sleep(3)\n new_choice = menu()\n elif new_choice == 11: # смена рабочей директории\n print('____________')\n new_dir = input('Введите новую директорию ')\n os.chdir(new_dir)\n print('____________')\n time.sleep(3)\n new_choice = menu()\n elif new_choice == 12: # выход\n break\n else:\n break\n return value_chouse\n\n\n\n\n\n# # 3 Создание папок и просмотр директории\n# for i in range(5):\n# # проверка на существование\n# if not os.path.exists(f'new{i}'):\n# # сздать папку передаем путь\n# os.mkdir(f'new{i}')","repo_name":"Olga-Prn/HW_5","sub_path":"Console_file_manager.py","file_name":"Console_file_manager.py","file_ext":"py","file_size_in_byte":7228,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"11538382016","text":"import numpy as np\nimport pytest\n\nimport mindspore.dataset as ds\nfrom mindspore.dataset.engine.iterators import ITERATORS_LIST, _cleanup\n\nDATA_DIR = [\"../data/dataset/testTFTestAllTypes/test.data\"]\nSCHEMA_DIR = \"../data/dataset/testTFTestAllTypes/datasetSchema.json\"\nCOLUMNS = [\"col_1d\", \"col_2d\", \"col_3d\", \"col_binary\", \"col_float\",\n \"col_sint16\", \"col_sint32\", \"col_sint64\"]\n\n\ndef check(project_columns):\n data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=COLUMNS, shuffle=False)\n data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=project_columns, shuffle=False)\n\n for data_actual, data_expected in zip(data1.create_tuple_iterator(project_columns), data2.create_tuple_iterator()):\n assert len(data_actual) == len(data_expected)\n assert all([np.array_equal(d1, d2) for d1, d2 in zip(data_actual, data_expected)])\n\n\ndef test_iterator_create_tuple():\n \"\"\"\n Test creating tuple iterator\n \"\"\"\n check(COLUMNS)\n check(COLUMNS[0:1])\n check(COLUMNS[0:2])\n check(COLUMNS[0:7])\n check(COLUMNS[7:8])\n check(COLUMNS[0:2:8])\n\n\ndef test_iterator_weak_ref():\n ITERATORS_LIST.clear()\n data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR)\n itr1 = data.create_tuple_iterator()\n itr2 = data.create_tuple_iterator()\n itr3 = data.create_tuple_iterator()\n\n assert len(ITERATORS_LIST) == 3\n assert sum(itr() is not None for itr in ITERATORS_LIST) == 3\n\n del itr1\n assert len(ITERATORS_LIST) == 3\n assert sum(itr() is not None for itr in ITERATORS_LIST) == 2\n\n del itr2\n assert len(ITERATORS_LIST) == 3\n assert sum(itr() is not None for itr in ITERATORS_LIST) == 1\n\n del itr3\n assert len(ITERATORS_LIST) == 3\n assert sum(itr() is not None for itr in ITERATORS_LIST) == 0\n\n itr1 = data.create_tuple_iterator()\n itr2 = data.create_tuple_iterator()\n itr3 = data.create_tuple_iterator()\n\n _cleanup()\n with pytest.raises(AttributeError) as info:\n itr2.__next__()\n assert \"object has no attribute 'depipeline'\" in str(info.value)\n\n del itr1\n assert len(ITERATORS_LIST) == 6\n assert sum(itr() is not None for itr in ITERATORS_LIST) == 2\n\n _cleanup()\n\n\nclass MyDict(dict):\n def __getattr__(self, key):\n return self[key]\n\n def __setattr__(self, key, value):\n self[key] = value\n\n def __call__(self, t):\n return t\n\n\ndef test_tree_copy():\n \"\"\"\n Testing copying the tree with a pyfunc that cannot be pickled\n \"\"\"\n\n data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=COLUMNS)\n data1 = data.map(operations=[MyDict()])\n\n itr = data1.create_tuple_iterator()\n\n assert id(data1) != id(itr.dataset)\n assert id(data) != id(itr.dataset.children[0])\n assert id(data1.operations[0]) == id(itr.dataset.operations[0])\n\n itr.release()\n\n\nif __name__ == '__main__':\n test_iterator_create_tuple()\n test_iterator_weak_ref()\n test_tree_copy()\n","repo_name":"gerayking/mindsporeAno","sub_path":"tests/ut/python/dataset/test_iterator.py","file_name":"test_iterator.py","file_ext":"py","file_size_in_byte":2932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"71215323001","text":"from typing import List, Optional\nfrom src.shared.domain.entities.exercise import Exercise\nfrom src.shared.domain.repositories.exercise_repository_interface import IExerciseRepository\n\n\nclass ExerciseRepositoryMock(IExerciseRepository):\n def __init__(self) -> None:\n self._exercises = [\n Exercise(exercise_id=\"111-111-111\",\n title=\"Primeiro Presidente do Brasil\",\n enunciado=\"Quem foi o primeiro presidente do Brasil?\",\n creation_date=1673319600000,\n expiration_date=1676084400000,\n correct_answer=\"Marechal Deodoro\"\n ),\n Exercise(exercise_id=\"111-222-111\",\n title=\"Qual lingua é mais antiga\",\n enunciado=\"Qual lingua é mais antiga: Python ou java\",\n creation_date=1673319600000,\n expiration_date=1676084400000,\n correct_answer=\"Python\"\n )\n ]\n\n def create_exercise(self, exercise: Exercise) -> Exercise:\n self._exercises.append(exercise)\n return exercise\n\n def get_exercise_by_id(self, exercise_id: str) -> Optional[Exercise]:\n for exercise in self._exercises:\n if exercise.exercise_id == exercise_id:\n return exercise\n return None\n\n def update_exercise_by_id(self, exercise_id: str, new_title: Optional[str] = None, new_enunciado: Optional[str] = None, new_creation_date: Optional[int] = None, new_expiration_date: Optional[int] = None, new_correct_answer: Optional[str] = None) -> Optional[Exercise]:\n exercise = self.get_exercise_by_id(exercise_id)\n\n if exercise is None:\n return None\n \n if new_title:\n exercise.title = new_title\n if new_enunciado:\n exercise.enunciado = new_enunciado\n if new_creation_date:\n exercise.creation_date = new_creation_date\n if new_expiration_date:\n exercise.expiration_date = new_expiration_date\n if new_correct_answer:\n exercise.correct_answer = new_correct_answer\n \n return exercise\n\n def delete_exercise_by_id(self, exercise_id: str) -> Optional[Exercise]:\n exercise_to_delete = self.get_exercise_by_id(exercise_id)\n \n if exercise_to_delete is None:\n return None\n\n self._exercises.remove(exercise_to_delete)\n return exercise_to_delete\n\n def get_all_exercises(self) -> List[Exercise]:\n return self._exercises","repo_name":"Lucasdvs10/Projeto-Integrador-2023.2","sub_path":"src/shared/infra/repositories/exercise_repository_mock.py","file_name":"exercise_repository_mock.py","file_ext":"py","file_size_in_byte":2641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"2562110183","text":"import sys\nsys.setrecursionlimit(5000000) # 재귀 제한조건을 풀어준다.\n\n# 가로, 세로, 대각선으로 연결되어 있을 경우 -> 걸어갈 수 있다.\n\ndef dfs(x, y): # 시작 좌표 (x, y), 지도 너비, 높이 (w, h)\n if x <= -1 or x >= h or y <= -1 or y >= w: # 지도 밖으로 벗어났을 경우\n return False\n \n if sea_map[x][y] == 1: # 땅일 경우에\n sea_map[x][y] = 0 # 방문한 땅이라는 것을 표시 \n dfs(x - 1, y) # 위\n dfs(x - 1, y + 1) # 오른쪽 위 대각선\n dfs(x, y + 1) # 오른쪽\n dfs(x + 1, y + 1) # 오른쪽 아래 대각선\n dfs(x + 1, y) # 아래\n dfs(x + 1, y - 1) # 왼쪽 아래 대각선\n dfs(x , y - 1) # 왼쪽\n dfs(x - 1, y - 1) # 왼쪽 위 대각선\n return True\n return False\n\nwhile True:\n w, h = map(int, input().split()) # w: 지도의 너비, h: 지도의 높이\n\n if w == 0 and h == 0: # 마지막 입력일 경우\n break\n \n sea_map = [list(map(int, input().split())) for _ in range(h)] # 지도 입력받는다.\n\n island_count = 0 # 섬의 개수\n for i in range(h): # 섬의 개수 탐색 시작\n for j in range(w):\n if dfs(i, j) == True:\n island_count += 1\n \n print(island_count) # 섬의 개수 출력 \n\n# # BFS 풀이\n# from collections import deque\n\n# def bfs(x, y):\n# dx = [1, -1, 0, 0, 1, -1, 1, -1]\n# dy = [0, 0, -1, 1, -1, 1, 1, -1]\n\n# sea_map[x][y] = 0 # 시작 지점 방문했다는 것 표시\n# queue = deque() # 큐 생성\n# queue.append([x, y]) # 시작 지점 큐에 삽입\n\n# while queue:\n# a, b = queue.popleft()\n# for i in range(8): # 상하좌우 대각선 총 8개\n# nx = a + dx[i]\n# ny = b + dy[i]\n# if 0 <= nx < h and 0 <= ny < w and sea_map[nx][ny] == 1: # 지도 범위 안에 있고, 땅일 경우에\n# sea_map[nx][ny] = 0 # 방문한 땅이라는 것을 표시 \n# queue.append([nx, ny])\n\n# while True:\n# w, h = map(int, input().split()) # w: 지도의 너비, h: 지도의 높이\n\n# if w == 0 and h == 0: # 마지막 입력일 경우\n# break\n \n# sea_map = [list(map(int, input().split())) for _ in range(h)] # 지도 입력받는다.\n# island_count = 0 # 섬의 개수\n# for i in range(h): # 섬의 개수 탐색 시작\n# for j in range(w):\n# if sea_map[i][j] == 1: # 땅일 경우\n# bfs(i, j)\n# island_count += 1\n \n# print(island_count) # 섬의 개수 출력 ","repo_name":"2do1/Algorithm","sub_path":"Baekjoon/GraphTraversal/4963 섬의 개수/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2610,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"7726985663","text":"import pygame\nimport sys\nfrom pygame.locals import *\nfrom random import randint\nimport time\n\npygame.init()\n\n# list of colors\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\n\nsize = (700, 500)\nscreen = pygame.display.set_mode(size)\npygame.display.set_caption(\"Pong by Michael Dimapindan\")\n\n\nclass Paddle(pygame.sprite.Sprite):\n\n def __init__(self, color, width, height):\n super().__init__()\n\n self.image = pygame.Surface([width, height])\n self.image.fill(BLACK)\n self.image.set_colorkey(BLACK)\n\n pygame.draw.rect(self.image, color, [0, 0, width, height])\n self.rect = self.image.get_rect()\n\n def move_up(self, pixels):\n self.rect.y -= pixels\n if self.rect.y < 0: # prevents from paddle going off-screen\n self.rect.y = 0\n\n def move_down(self, pixels):\n self.rect.y += pixels\n if self.rect.y > 400: # prevents from paddle going off-screen\n self.rect.y = 400\n\n\nclass Ball(pygame.sprite.Sprite):\n\n def __init__(self, color, width, height):\n super().__init__()\n self.image = pygame.Surface([width, height])\n self.image.fill(BLACK)\n self.image.set_colorkey(BLACK)\n\n pygame.draw.rect(self.image, color, [0, 0, width, height])\n\n self.velocity = [randint(4, 8), randint(-8, 8)]\n self.rect = self.image.get_rect()\n\n def update(self):\n self.rect.x += self.velocity[0]\n self.rect.y += self.velocity[1]\n\n def bounce(self):\n self.velocity[0] = -self.velocity[0]\n self.velocity[1] = randint(-8, 8)\n\n\npaddle_sound = pygame.mixer.Sound('paddle_ping.wav')\nwall_bounce = pygame.mixer.Sound('wall_bounce.wav')\nscore_sound = pygame.mixer.Sound('miss_sound.wav')\n\n# position of player 1\np1_obj = Paddle(WHITE, 10, 100)\np1_obj.rect.x = 0\np1_obj.rect.y = 200\n\n# position of player 2\np2_obj = Paddle(WHITE, 10, 100)\np2_obj.rect.x = 690\np2_obj.rect.y = 200\n\nball = Ball(WHITE, 10, 10)\n\np1_score = 0\np2_score = 0\n\nall_sprites_list = pygame.sprite.Group()\n\nall_sprites_list.add(p1_obj)\nall_sprites_list.add(p2_obj)\nall_sprites_list.add(ball)\n\nin_progress = True\ntimer = pygame.time.Clock()\n\n# main game loop\nwhile in_progress:\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n pygame.display.update()\n\n keys_input = pygame.key.get_pressed()\n if keys_input[pygame.K_w]:\n p1_obj.move_up(5)\n if keys_input[pygame.K_s]:\n p1_obj.move_down(5)\n if keys_input[pygame.K_UP]:\n p2_obj.move_up(5)\n if keys_input[pygame.K_DOWN]:\n p2_obj.move_down(5)\n\n all_sprites_list.update()\n\n if ball.rect.x >= 690:\n score_sound.play()\n p1_score = p1_score + 1\n ball.velocity[0] = -ball.velocity[0]\n if ball.rect.x <= 0:\n score_sound.play()\n p2_score = p2_score + 1\n ball.velocity[0] = -ball.velocity[0]\n if ball.rect.y > 490:\n wall_bounce.play()\n ball.velocity[1] = -ball.velocity[1]\n if ball.rect.y < 0:\n wall_bounce.play()\n ball.velocity[1] = -ball.velocity[1]\n\n if pygame.sprite.collide_mask(ball, p1_obj) or pygame.sprite.collide_mask(ball, p2_obj):\n ball.bounce()\n paddle_sound.play()\n\n screen.fill(BLACK)\n pygame.draw.line(screen, WHITE, [349, 0], [349, 500], 5)\n\n all_sprites_list.draw(screen)\n\n font = pygame.font.Font(None, 74)\n text_font = pygame.font.Font(None, 45)\n\n # score text\n text = font.render(str(p1_score), 1, WHITE)\n screen.blit(text, (250, 10))\n text = text_font.render(\"P1\", True, WHITE)\n screen.blit(text, (245, 60))\n text = font.render(str(p2_score), 1, WHITE)\n screen.blit(text, (420, 10))\n text = text_font.render(\"P2\", True, WHITE)\n screen.blit(text, (415, 60))\n win_text = text_font.render(\"Wins\", True, WHITE)\n\n # instructions\n text = text_font.render(\"W\", True, WHITE)\n screen.blit(text, (305, 420))\n text = text_font.render(\"S\", True, WHITE)\n screen.blit(text, (310, 460))\n text = text_font.render(\"UP\", True, WHITE)\n screen.blit(text, (365, 420))\n text = text_font.render(\"DOWN\", True, WHITE)\n screen.blit(text, (365, 460))\n\n if p1_score == 3:\n screen.blit(win_text, (228, 100))\n time.sleep(3)\n in_progress = False\n elif p2_score == 3:\n screen.blit(win_text, (398, 100))\n time.sleep(3)\n in_progress = False\n\n pygame.display.flip()\n\n timer.tick(60) # 60 FPS\n\npygame.quit()\n","repo_name":"gageDimo/Pong-Project","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"39906371500","text":"import os\r\nimport pathlib\r\nimport stat\r\nimport time\r\nimport typing as tp\r\nimport hashlib\r\nimport binascii\r\n\r\nfrom pyvcs.index import GitIndexEntry, read_index\r\nfrom pyvcs.objects import hash_object\r\nfrom pyvcs.refs import get_ref, is_detached, resolve_head, update_ref\r\n\r\n\r\ndef write_tree(gitdir: pathlib.Path, index: tp.List[GitIndexEntry], dirname: str = \"\") -> str:\r\n sh_f = b\"\"\r\n for i in range(len(index)):\r\n string = \"\"\r\n sha = index[i].sha1\r\n mode = str(oct(index[i].mode)[2:])\r\n name = index[i].name\r\n n = name.split(\"/\")\r\n name = n[len(n)-1]\r\n string += mode + \" \" + name + \"\\0\"\r\n string = string.encode()\r\n string += sha\r\n hasho = hash_object(string, \"tree\")\r\n hasho = bytes.fromhex(hasho)\r\n if len(n) == 1:\r\n sh_f += string\r\n with open(name, \"r\") as f:\r\n rd = f.read()\r\n rd = rd.encode()\r\n f.close()\r\n hash_object(rd, \"blob\", False)\r\n if len(n) > 1:\r\n zl = \"\"\r\n for i in range(1, len(n)-1):\r\n zl_2 = \"\"\r\n name = str(n[len(n)-2-i])\r\n mode = \"40000\"\r\n zl_2 += mode + \" \" + name + \"\\0\"\r\n zl_2 = zl_2.encode()\r\n zl_2 += hasho\r\n hasho = hash_object(zl_2, \"tree\")\r\n hasho = binascii.unhexlify(hasho)\r\n name = str(n[0])\r\n mode = \"40000\"\r\n zl += mode + \" \" + name + \"\\0\"\r\n zl = zl.encode()\r\n zl += hasho\r\n hash_object(string, \"tree\", True)\r\n sh_f += zl\r\n return hash_object(sh_f, \"tree\", True)\r\n\r\n\r\ndef commit_tree(\r\n gitdir: pathlib.Path,\r\n tree: str,\r\n message: str,\r\n parent: tp.Optional[str] = None,\r\n author: tp.Optional[str] = None,\r\n) -> str:\r\n commenttime = str(int(time.mktime(time.localtime()))) + \\\r\n \" \" + str(time.strftime(\"%z\", time.gmtime()))\r\n string = \"tree \"\r\n string += tree\r\n string += \"\\nauthor \"\r\n string += author\r\n string += \" \"\r\n string += commenttime\r\n string += \"\\ncommitter \"\r\n string += author\r\n string += \" \"\r\n string += commenttime\r\n string += \"\\n\\n\"\r\n string += message\r\n string += \"\\n\"\r\n return hash_object(string.encode(), \"commit\", True)\r\n","repo_name":"pophilpo/k3120_python","sub_path":"lab_9/pyvcs/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"16943078833","text":"from gdb.printing import *\nfrom gdb import *\n\nfrom _usability import *\nfrom _codes_stringified import *\nfrom _common import *\nfrom _pp_base_classes import IteratorPP\nimport _te_args_rules\n\n\ndef iterTypenameSuffix (is_const, is_reverse):\n\tassert_bool(is_const)\n\tassert_bool(is_reverse)\n\tif not is_const and not is_reverse:\n\t\treturn '::iterator'\n\telif is_const and not is_reverse:\n\t\treturn '::const_iterator'\n\telif not is_const and is_reverse:\n\t\treturn '::reverse_iterator'\n\telif is_const and is_reverse:\n\t\treturn '::const_reverse_iterator'\n\n\ndef isCanonicalIterType_givenStr (s):\n\treturn (s.endswith('::iterator') or\n\t\t\ts.endswith('::const_iterator') or\n\t\t\ts.endswith('::reverse_iterator') or\n\t\t\ts.endswith('::const_reverse_iterator'))\n\ndef isCanonicalIterType (t):\n\ts = str(t)\n\treturn isCanonicalIterType_givenStr(s)\n\n\ndef simple__typeOfContainer (tIter):\n\tassert tIter!=None and isinstance(tIter,gdb.Type)\n\tretvalIfErr = (None,False)\n\tif PREF_Debug:\n\t\tprintf('%s___________________________________%s\\n',FONTred,resetFONT)\n\t\tprintf('tIter =\\n\\t%s%s%s\\n', boldFONT,str(tIter),resetFONT)\n\tif not isCanonicalIterType(tIter):\n\t\tif PREF_Debug: printf('\\nunusable tIter \"%s\"\\n', str(tIter))\n\t\treturn retvalIfErr\n\tisConstIter = False\n\t# Now to extract \"std::list<blah>\" from \"std::list<blah>::iterator\"\n\ts_tIter = str(tIter)\n\tif s_tIter.endswith('::iterator'):\n\t\ts_tCont = s_tIter[:-(len('::iterator'))]\n\telif s_tIter.endswith('::const_iterator'):\n\t\ts_tCont = s_tIter[:-(len('::const_iterator'))]\n\t\tisConstIter=True\n\telif s_tIter.endswith('::reverse_iterator'):\n\t\ts_tCont = s_tIter[:-(len('::reverse_iterator'))]\n\telse: # Else endswith('::const_reverse_iterator')\n\t\ts_tCont = s_tIter[:-(len('::const_reverse_iterator'))]\n\t\tisConstIter=True\n\ttry:\n\t\ttCont = gdb.lookup_type(s_tCont)\n\t\treturn (tCont,isConstIter)\n\texcept BaseException as whatev:\n\t\tif PREF_Debug: printf('\\nunusable s_tCont \"%s\"\\n', s_tCont)\n\t\treturn retvalIfErr\n\n\nclass std__front_insert_iterator (IteratorPP):\n\tdef __init__ (self, v):\n\t\tassert (isinstance(v, gdb.Value))\n\t\ttargetType = get_basic_type(v.type.template_argument(0))\n\t\tIteratorPP.__init__(self, targetType)\n\t\tself.sz_used__objProper = v.type.sizeof\n\t\tself.targetAddr = v['container']\n\t\tself.sz_overhead = 0\n\nclass std__back_insert_iterator (IteratorPP):\n\tdef __init__ (self, v):\n\t\tassert (isinstance(v, gdb.Value))\n\t\ttargetType = get_basic_type(v.type.template_argument(0))\n\t\tIteratorPP.__init__(self, targetType)\n\t\tself.sz_used__objProper = v.type.sizeof\n\t\tself.targetAddr = v['container']\n\t\tself.sz_overhead = 0\n\n\ndef primitive__typeOfContainer (tOrig): # To return (tCont,isConstIter,markIterReverse)\n\tretvalIfErr = (None,False,False)\n\ts_tOrig = str(tOrig)\n\tif not (s_tOrig.startswith('std::initializer_list<') or\n\t\t\ts_tOrig.startswith('std::vector<bool,') or\n\t\t\ts_tOrig.startswith('std::array<')):\n\t\treturn retvalIfErr\n\t(tCont,isConstIter) = simple__typeOfContainer(tOrig)\n\tif tCont==None:\n\t\treturn retvalIfErr\n\tmarkIterReverse = s_tOrig.endswith('reverse_iterator')\n\treturn (tCont,isConstIter,markIterReverse)\n\n\n# Iterators into std::initializer_list<T> and std::array<T,N> are just raw pointers.\n# Also, iterators into std::basic_string_view<Ch,ChTRAITS>\nclass just_raw_pointer (IteratorPP):\n\tdef __init__ (self, v):\n\t\tassert (isinstance(v, gdb.Value))\n\t\ttargetType = get_basic_type(v.type).target()\n\t\tIteratorPP.__init__(self, targetType)\n\t\tself.sz_used__objProper = v.type.sizeof\n\t\tself.targetAddr = v\n\t\tself.sz_overhead = 0\n\t\tself.targetType = targetType # For _stl_utilities::std__string_view::iteratorStanding()'s benefit\n\n\nclass std__string (IteratorPP):\n\t@staticmethod\n\tdef typeOfContainer (tIterHusk, tIterCore):\n\t\treturn simple__typeOfContainer(tIterHusk) # Yeah????\n\tdef __init__ (self, v):\n\t\tassert (isinstance(v, gdb.Value))\n\t\ttargetType = get_basic_type(v.type.template_argument(0)).target()\n\t\tIteratorPP.__init__(self, targetType)\n\t\tself.sz_used__objProper = v.type.sizeof\n\t\tself.targetAddr = v['_M_current']\n\t\tself.sz_overhead = 0\n\n\nclass std__vector__bool (IteratorPP):\n\t@staticmethod\n\tdef typeOfContainer (tIterHusk, tIterCore):\n\t\treturn simple__typeOfContainer(tIterHusk) # Yeah????\n\tdef __init__ (self, v):\n\t\tassert (isinstance(v, gdb.Value))\n\t\ttargetType = gdb.lookup_type('bool') # Fake it.\n\t\tIteratorPP.__init__(self, targetType)\n\t\tself.sz_used__objProper = v.type.sizeof\n\t\tself.sz_overhead = 0\n\t\tself.target_nodeAddr = v['_M_p']\n\t\tself.target_intranodeOffset = v['_M_offset']\n\t\t# Need to figure targetVal, so that IndirectorPP::figureVal() won't try to.\n\t\tstorewordType = gdb.lookup_type('unsigned long')\n\t\tp_word = castTo_ptrToType(self.target_nodeAddr, storewordType)\n\t\tif 0x0 == int(p_word):\n\t\t\tself.targetAddr = p_word # IndirectorPP::figureVal(), \"<NULL indirector>\"\n\t\t\tself.empty=True\n\t\t\treturn\n\t\tself.empty=False\n\t\tword = int(p_word.dereference())\n\t\tif word & (1 << self.target_intranodeOffset):\n\t\t\tself.targetVal = gdb.Value(True)\n\t\telse:\n\t\t\tself.targetVal = gdb.Value(False)\n\n\nclass std__vector (IteratorPP):\n\t@staticmethod\n\tdef typeOfContainer (tIterHusk, tIterCore):\n\t\tif tIterCore==None:\n\t\t\ttIter = tIterHusk\n\t\telse:\n\t\t\ttIterHusk_teArgs = list_templateArgs(tIterHusk)\n\t\t\tif len(tIterHusk_teArgs) == 1:\n\t\t\t\ttIter = tIterCore\n\t\t\telse:\n\t\t\t\ttIter = tIterHusk\n\t\tretvalIfErr = (None,False)\n\t\ttIterUsing = tIter\n\t\tif isCanonicalIterType(tIter):\n\t\t\ttIterUsing = tIter.strip_typedefs()\n\t\tteArgs = list_templateArgs(tIterUsing)\n\t\tif len(teArgs) != 2:\n\t\t\tif PREF_Debug: printf('len(teArgs)=%u != 2\\n',len(teArgs))\n\t\t\treturn retvalIfErr\n\t\ttElemPtr = teArgs[0].strip_typedefs()\n\t\tif tElemPtr.code != TYPE_CODE_PTR:\n\t\t\tif PREF_Debug: printf('tElemPtr.code=%s != PTR\\n', type_codeToStr[tElemPtr.code])\n\t\t\treturn retvalIfErr\n\t\ttElem = tElemPtr.target()\n\t\tisConstIter = tElem == tElem.const()\n\t\treturn (teArgs[1] , isConstIter)\n\t#\n\tdef __init__ (self, v):\n\t\tassert (isinstance(v, gdb.Value))\n\t\ttargetType = get_basic_type(v.type.template_argument(0)).target()\n\t\tIteratorPP.__init__(self, targetType)\n\t\tself.sz_used__objProper = v.type.sizeof\n\t\tself.targetAddr = v['_M_current']\n\t\tself.sz_overhead = 0\n\n\nclass std__list (IteratorPP):\n\t#\n\t@staticmethod\n\tdef typeOfContainer (tIterHusk, tIterCore):\n\t\tif tIterCore==None:\n\t\t\treturn simple__typeOfContainer(tIterHusk)\n\t\ttIterHusk_teArgs = list_templateArgs(tIterHusk)\n\t\ttIterCore_teArgs = list_templateArgs(tIterCore)\n\t\tif len(tIterCore_teArgs) > len(tIterHusk_teArgs):\n\t\t\treturn simple__typeOfContainer(tIterCore)\n\t\telse:\n\t\t\treturn simple__typeOfContainer(tIterHusk)\n\t#\n\t@staticmethod\n\tdef appx_typenameOfContainer (tIter):\n\t\tretvalIfErr = (None,False)\n\t\ttIter_teArgs = list_templateArgs(tIter)\n\t\tif len(tIter_teArgs) != 1:\n\t\t\tprintf('\\nunusable tIter \"%s\"\\n', str(tIter))\n\t\t\treturn retvalIfErr\n\t\ttElem = tIter_teArgs[0]\n\t\ts_tCont = sprintf('std::list<%s%s??%s>', str(tElem), FONTredBackgd,resetFONT)\n\t\tisConstIter = str(tIter).startswith('std::_List_const_iterator<')\n\t\treturn (s_tCont,isConstIter)\n\t#\n\tdef __init__ (self, v):\n\t\tassert (isinstance(v, gdb.Value))\n\t\ttargetType = get_basic_type(v.type.template_argument(0))\n\t\tIteratorPP.__init__(self, targetType)\n\t\tself.sz_used__objProper = v.type.sizeof\n\t\tself.p__List_node_base = v['_M_node']\n\t\ttype__List_node_base = self.p__List_node_base.type.target()\n\t\tpayload_offset = type__List_node_base.sizeof\n\t\tself.targetAddr = (castTo_ptrToVoid(self.p__List_node_base) + payload_offset)\n\t\tself.sz_overhead = max(0,v.type.sizeof - targetType.sizeof - WORD_WIDTH.const)\n\n\nclass std__forward_list (IteratorPP):\n\t#\n\t@staticmethod\n\tdef typeOfContainer (tIterHusk, tIterCore):\n\t\tif tIterCore==None:\n\t\t\treturn simple__typeOfContainer(tIterHusk)\n\t\tassert(False) #XXX What, *can* we get a non-NULL tIterCore here???\n\t\ttIterHusk_teArgs = list_templateArgs(tIterHusk)\n\t\ttIterCore_teArgs = list_templateArgs(tIterCore)\n\t\tif len(tIterCore_teArgs) > len(tIterHusk_teArgs):\n\t\t\treturn simple__typeOfContainer(tIterCore)\n\t\telse:\n\t\t\treturn simple__typeOfContainer(tIterHusk)\n\t#\n\t@staticmethod\n\tdef appx_typenameOfContainer (tIter):\n\t\tretvalIfErr = (None,False)\n\t\ttIter_teArgs = list_templateArgs(tIter)\n\t\tif len(tIter_teArgs) != 1:\n\t\t\tprintf('\\nunusable tIter \"%s\"\\n', str(tIter))\n\t\t\treturn retvalIfErr\n\t\ttElem = tIter_teArgs[0]\n\t\ts_tCont = sprintf('std::forward_list<%s%s??%s>',\n\t\t\t\t\t\t str(tElem), FONTredBackgd,resetFONT)\n\t\tisConstIter = str(tIter).startswith('std::_Fwd_list_const_iterator<')\n\t\treturn (s_tCont,isConstIter)\n\t#\n\t@staticmethod\n\tdef reckon_payloadOffset (sizeof_node):\n\t\tif sizeof_node < WORD_WIDTH.const * 4:\n\t\t\treturn WORD_WIDTH.const\n\t\telse:\n\t\t\treturn min(8, WORD_WIDTH.const * 2)\n\t#\n\tdef __init__ (self, v):\n\t\tassert (isinstance(v, gdb.Value))\n\t\ttargetType = get_basic_type(v.type.template_argument(0))\n\t\tnodeTypeName = sprintf('std::_Fwd_list_node<%s>', str(targetType))\n\t\tnodeType = gdb.lookup_type(nodeTypeName)\n\t\tpayload_offset = std__forward_list.reckon_payloadOffset(nodeType.sizeof)\n\t\tIteratorPP.__init__(self, targetType)\n\t\tself.sz_used__objProper = v.type.sizeof\n\t\tself.p__Fwd_list_node_base = v['_M_node']\n\t\tself.targetAddr = castTo_ptrToVoid(self.p__Fwd_list_node_base) + payload_offset\n\t\tself.sz_overhead = max(0,v.type.sizeof - payload_offset - WORD_WIDTH.const)\n\n\nclass std__deque (IteratorPP):\n\t#\n\t@staticmethod\n\tdef typeOfContainer (tIterHusk, tIterCore):\n\t\treturn simple__typeOfContainer(tIterHusk)\n\t#\n\n\tdef __init__ (self, v):\n\t\tassert (isinstance(v, gdb.Value))\n\t\ttargetType = get_basic_type(v.type.template_argument(0))\n\t\tIteratorPP.__init__(self, targetType)\n\t\tself.sz_used__objProper = v.type.sizeof\n\t\tself.p_node = v['_M_node'] # Here, \"node\" is a 512B chunk, storing 1+ elems.\n\t\tself.p_cur = v['_M_cur']\n\t\tself.targetAddr = self.p_cur\n\t\tself.sz_overhead = max(0,v.type.sizeof - targetType.sizeof - WORD_WIDTH.const)\n\n\nclass std__Node (IteratorPP):\n\t#\n\t@staticmethod\n\tdef typeOfContainer (tIterHusk, tIterCore):\n\t\tif tIterCore==None:\n\t\t\treturn simple__typeOfContainer(tIterHusk)\n\t\ttIterHusk_teArgs = list_templateArgs(tIterHusk)\n\t\ttIterCore_teArgs = list_templateArgs(tIterCore)\n\t\tif len(tIterCore_teArgs) > len(tIterHusk_teArgs):\n\t\t\treturn simple__typeOfContainer(tIterCore)\n\t\telse:\n\t\t\treturn simple__typeOfContainer(tIterHusk)\n\t#\n\tdef __init__ (self, v):\n\t\tassert (isinstance(v, gdb.Value))\n\t\tkvType = v.type.template_argument(0)\n\t\tIteratorPP.__init__(self, kvType)\n\t\tself.sz_used__objProper = v.type.sizeof\n\t\tself.nodeAddr = v['_M_cur']\n\t\tp_node = v['_M_cur']\n\t\tif int(p_node):\n\t\t\tx_addr = castTo_ptrToVoid(p_node) + int(WORD_WIDTH.const)\n\t\t\tuintType = gdb.lookup_type('unsigned int')\n\t\t\twhile True:\n\t\t\t\tx_addr_as_uintPtr = castTo_ptrToType(x_addr, uintType)\n\t\t\t\tx_val = int(x_addr_as_uintPtr.dereference())\n\t\t\t\tif x_val != 0xBAADF00D:\n\t\t\t\t\tbreak\n\t\t\t\tx_addr += int(WORD_WIDTH.const)\n\t\t\tself.targetAddr = int(x_addr)\n\t\telse:\n\t\t\tself.targetAddr = int(p_node)\n\t\tself.sz_overhead = max(0,v.type.sizeof - kvType.sizeof - WORD_WIDTH.const)\n\n\nclass std__Rb_tree (IteratorPP):\n\t#\n\t@staticmethod\n\tdef typeOfContainer (tIterHusk, tIterCore):\n\t\tif tIterCore==None:\n\t\t\treturn simple__typeOfContainer(tIterHusk)\n\t\ttIterHusk_teArgs = list_templateArgs(tIterHusk)\n\t\ttIterCore_teArgs = list_templateArgs(tIterCore)\n\t\tif len(tIterCore_teArgs) > len(tIterHusk_teArgs):\n\t\t\treturn simple__typeOfContainer(tIterCore)\n\t\telse:\n\t\t\treturn simple__typeOfContainer(tIterHusk)\n\t#\n\t@staticmethod\n\tdef appx_typenameOfContainer (tIter):\n\t\tretvalIfErr = (None,False)\n\t\ttIter_teArgs = list_templateArgs(tIter)\n\t\tif len(tIter_teArgs) == 1: #set?\n\t\t\ttElem = tIter_teArgs[0]\n\t\t\ts_tCont = sprintf('std::set<%s%s??%s>', str(tElem), FONTredBackgd,resetFONT)\n\t\t\tisConstIter = str(tIter).startswith('std::_Rb_tree_const_iterator<')\n\t\t\treturn (s_tCont,isConstIter)\n\t\telif len(tIter_teArgs) == 2: # map?\n\t\t\tprintf('Not yet implemented! Passed \"%s\"\\n', str(tIter))\n\t\t\treturn retvalIfErr\n#\treturn (s_tCont,isConstIter)\n\t\telse:\n\t\t\tprintf('\\nunusable tIter \"%s\"\\n', str(tIter))\n\t\t\treturn retvalIfErr\n\t#\n\tdef __init__ (self, v):\n\t\tassert (isinstance(v, gdb.Value))\n\t\ttargetType = get_basic_type(v.type.template_argument(0))\n\t\tIteratorPP.__init__(self, targetType)\n\t\tself.sz_used__objProper = v.type.sizeof\n\t\tself.nodeAddr = v['_M_node']\n\t\tself.targetAddr = int(castTo_ptrToVoid(self.nodeAddr) + int(4) * WORD_WIDTH.const)\n\t\tself.sz_overhead = max(0,v.type.sizeof - targetType.sizeof - WORD_WIDTH.const)\n\n\n\n# Will return 3-ple (S,moveWrapper,reverseWrapper) , where S is\n# expected name of wrapper ivar if t is a wrapper type, else None.\ndef is_iteratorType_wrapperType (t, wrapDepth):\n\tassert isinstance(t, gdb.Type)\n\ttstr = str(t)\n\tdTag = sprintf('[%s%sd=%u%s %s]', FONTmagenta,boldFONT,wrapDepth,resetFONT,\n\t\t\t\t immedCaller())\n\ttTag = sprintf('t=%s%s((%s %s %s%s))%s', boldFONT,italicFONT,resetFONT,\n\t\t\t\t tstr, boldFONT,italicFONT,resetFONT)\n\tif tstr.startswith('std::move_iterator<'):\n\t\tif UNRAVEL_Debug:\n\t\t\tprintf('%s Peeling move_iterator from %s\\n', dTag, tTag)\n\t\treturn ('_M_current',True,False)\n\telif (tstr.startswith('std::reverse_iterator<') or\n\t tstr.startswith('std::const_reverse_iterator<') or\n\t tstr.endswith('>::reverse_iterator') or\n\t\t tstr.endswith('>::const_reverse_iterator')):\n\t\tif UNRAVEL_Debug:\n\t\t\tprintf('%s Peeling reverse_iterator from %s\\n', dTag, tTag)\n\t\treturn ('current',False,True)\n\telse:\n\t\tif UNRAVEL_Debug:\n\t\t\tprintf('%s Nothing to peel from %s\\n', dTag, tTag)\n\t\treturn (None,False,False)\n\n\ndef unwrap_iteratorType (tOriginal): #To return an IteratorHusk.\n\tassert isinstance(tOriginal, gdb.Type)\n\tt = tOriginal\n#\tprintf('\\nCallers %s\\nShall try peel tOriginal =\\n\\t%s\\n', listCallers(6),str(t))\n\ttheType_whichWraps_t = None\n\twrapDepth = int(0)\n\thusk = IteratorHusk()\n\twhile True:\n\t\tdidUnwrap=False\n\t\t(wrapperIvarName,movWr,revWr) = is_iteratorType_wrapperType(t, wrapDepth)\n\t\tif wrapperIvarName != None:\n\t\t\tif movWr: husk.any_moveWrappers=True\n\t\t\tif revWr: husk.any_reverseWrappers=True\n\t\t\tteArgs = list_templateArgs(t)\n\t\t\tif len(teArgs) == 1:\n\t\t\t\tte0 = teArgs[0]\n\t\t\t\tif isinstance(te0, gdb.Type):\n\t\t\t\t\ttheType_whichWraps_t = t\n\t\t\t\t\tt = te0\n\t\t\t\t\twrapDepth += int(1)\n#\t\t\t\t\tprintf('d=%u Type-peel succ, now t=\\n\\t%s\\n', wrapDepth, str(t))\n\t\t\t\t\tdidUnwrap=True\n\t\t\t\telse:\n\t\t\t\t\tprintf('d=%u %sWeird!%s Sole teArg of t[%s] is not a gdb.Type\\n',\n\t\t\t\t\t\t wrapDepth, FONTred, resetFONT, str(t))\n\t\t\telse:\n\t\t\t\tprintf('d=%u %sWeird!%s t[%s] has %u teArgs and not a sole teArg\\n',\n\t\t\t\t\t wrapDepth, FONTred, resetFONT, str(t), len(teArgs))\n\t\tif not didUnwrap: # No more layers left to unwrap?\n\t\t\tbreak\n\tif None == theType_whichWraps_t: # Hadn't been even one layer to unwrap?\n\t\tassert not husk.any_moveWrappers and not husk.any_reverseWrappers #Sanity\n\t\treturn husk#None\n\thusk.coreType=t\n\treturn husk#t\n\n\ndef unwrap_iteratorValue (vOriginal): #To return an IteratorHusk.\n\tassert isinstance(vOriginal, gdb.Value)\n\tv = vOriginal\n#\tprintf('\\n\\%s\\nShall try peel vOrig, type =\\n\\t%s\\n',listCallers(6),str(v.type))\n\ttheValue_whichWraps_v = None\n\twrapDepth = int(0)\n\thusk = IteratorHusk()\n\twhile True:\n\t\tdidUnwrap=False\n\t\tt = v.type\n\t\t(wrapperIvarName,movWr,revWr) = is_iteratorType_wrapperType(t, wrapDepth)\n\t\tif wrapperIvarName != None:\n\t\t\tif movWr: husk.any_moveWrappers=True\n\t\t\tif revWr: husk.any_reverseWrappers=True\n\t\t\tif gdb.types.has_field(t, wrapperIvarName):\n\t\t\t\ttheValue_whichWraps_v = v\n\t\t\t\tv = v[wrapperIvarName]\n\t\t\t\twrapDepth += int(1)\n#\t\t\t\tprintf('d=%u Value-peel succ, now v t=\\n\\t%s\\n', wrapDepth, str(v.type))\n\t\t\t\tdidUnwrap=True\n\t\t\telse:\n\t\t\t\tprintf('d=%u %sWeird!%s The t[%s] lacks expected ivar \"%s\"\\n',\n\t\t\t\t\t wrapDepth, FONTred, resetFONT, str(t), wrapperIvarName)\n\t\tif not didUnwrap: # No more layers left to unwrap?\n\t\t\tbreak\n\tif None == theValue_whichWraps_v: # Hadn't been even one layer to unwrap?\n\t\tassert not husk.any_moveWrappers and not husk.any_reverseWrappers #Sanity\n\t\treturn husk#None\n\thusk.coreType=v.type\n\thusk.coreValue=v\n\treturn husk#v\n\n\ntypeName_to_iteratorPP = {}\n# Pls keep sorted by alpha.\n#\t\ttypeName_to_iteratorPP[ 'OrderedMap' ] = OrderedMap\n\n\n#To return pair<IteratorPP,IteratorHusk> if try__unwrapType, else pair<IteratorPP,None>.\ndef getPP (t, try__unwrapType):\n\tassert_bool(try__unwrapType)\n\tassert isinstance(t, gdb.Type)\n\ttstr = str(t)\n\tif LOOKUPppCLASS_Debug:\n\t\tprintf('%s_________________________________________________________________%s\\n'\\\n\t\t\t '%s%s_stl_iter%s%s%s((%s %s %s%s))%s%s%s%s\\n\\t%s\\n',\n\t\t\t FONTgreenBackgd,resetFONT,\n\t\t\t boldFONT,FONTgreenBackgd,resetFONT,boldFONT,italicFONT,resetFONT,\n\t\t\t tstr, boldFONT,italicFONT,resetFONT,\n\t\t\t FONTgreen,type_codeToStr[t.code],resetFONT, listCallers(2))\n\n\tif try__unwrapType:\n\t\titerHusk = unwrap_iteratorType(t)\n\t\tif iterHusk.coreType !=None:\n\t\t\tt = iterHusk.coreType\n\t\t\ttstr = str(t)\n#\t\telse:\n#\t\t\tprintf('No core to de-husk; tstr perforce stays \"%s\"\\n',tstr)\n\telse:\n\t\titerHusk = None\n\n\tteArgs = list_templateArgs(t) # Rets list of gdb.Type (and/or gdb.Value)\n#\tdump_aList(teArgs, 'tIter teArgs')\n\n\tif False and PREF_Debug:\n\t\tdump_templateArgs(teArgs)\n\t\tparClasses = list_parentClasses(t)\n\t\tdump_aList(parClasses, 'parClasses')\n\n\tif (len(teArgs) == 0): # Iterators are all templated types, except iterators into...\n\t\tif t.code == TYPE_CODE_PTR:\n\t\t\treturn (just_raw_pointer,iterHusk) # ...std::array<T,N> or std::initializer_list<T>\n\t\tif tstr in ('std::_Bit_iterator', 'std::_Bit_const_iterator'):\n\t\t\treturn (std__vector__bool,iterHusk) # ...std::vector<bool>\n\t\tif LOOKUPppCLASS_Debug: printf('iter::getPP retNone ((A))\\n')\n\t\treturn (None,iterHusk)\n\n\tfirst__template_paramList__startsAt = tstr.find('<')\n\tif not isCanonicalIterType_givenStr(tstr) and (first__template_paramList__startsAt > 1):\n\t\tbefore__template_paramList = tstr[:first__template_paramList__startsAt]\n\t\tfirst__scope_op__startsAt = before__template_paramList.find('::')\n\t\tif first__scope_op__startsAt < 0:\n\t\t\ttstrFocus = before__template_paramList\n\t\telse:\n\t\t\ttstrFocus = before__template_paramList[(first__scope_op__startsAt + 2):]\n\t\tif 'iterator' not in tstrFocus:\n\t\t\tif LOOKUPppCLASS_Debug: printf('iter::getPP retNone ((B))\\n')\n\t\t\treturn (None,iterHusk)\n\n\tte0 = str(teArgs[0])\n\tte1 = None\n\tif len(teArgs) >= 2:\n\t\tte1 = str(teArgs[1])\n\n\tif (len(teArgs) == 2) and ('char' in te0) and is_typeName__std_string(te1):\n\t\treturn (std__string,iterHusk)\n\n\tif ((len(teArgs) >= 2)) and te1.startswith('std::vector<'):\n\t\treturn (std__vector,iterHusk)\n\n\tif tstr.startswith('std::_List_') or (isCanonicalIterType_givenStr(tstr) and\n\t\t\t\t\t\t\t\t\t\t strip__cxx11(tstr).startswith('std::list<')):\n\t\treturn (std__list,iterHusk)\n\n\tif tstr.startswith('std::_Fwd_list_') or (isCanonicalIterType_givenStr(tstr) and\n\t\t\t\t\t\t\t\t\t\t\t tstr.startswith('std::forward_list<')):\n\t\treturn (std__forward_list,iterHusk)\n\n\tif tstr.startswith('std::_Deque_') or (isCanonicalIterType_givenStr(tstr) and\n\t\t\t\t\t\t\t\t\t\t tstr.startswith('std::deque<')):\n\t\treturn (std__deque,iterHusk)\n\n\tif tstr.startswith('std::__detail::_Node_') or (isCanonicalIterType_givenStr(tstr) and\n\t\t\t\t\t\t\t\t\t\t\t\t\t(tstr.startswith('std::unordered_set<') or\n\t\t\t\t\t\t\t\t\t\t\t\t\t tstr.startswith('std::unordered_multiset<') or\n\t\t\t\t\t\t\t\t\t\t\t\t\t tstr.startswith('std::unordered_map<') or\n\t\t\t\t\t\t\t\t\t\t\t\t\t tstr.startswith('std::unordered_multimap<'))):\n\t\treturn (std__Node,iterHusk) # unordered associative (hashtable)\n\n\tif tstr.startswith('std::_Rb_tree_') or (isCanonicalIterType_givenStr(tstr) and\n\t\t\t\t\t\t\t\t\t\t\t (tstr.startswith('std::set<') or\n\t\t\t\t\t\t\t\t\t\t\t tstr.startswith('std::multiset<') or\n\t\t\t\t\t\t\t\t\t\t\t tstr.startswith('std::map<') or\n\t\t\t\t\t\t\t\t\t\t\t tstr.startswith('std::multimap<'))):\n\t\treturn (std__Rb_tree,iterHusk) # ordered associative\n\n\t# Insert iterators point to *an entire container*, not to an element therein.\n\tif tstr.startswith('std::front_insert_iterator'):\n\t\treturn (std__front_insert_iterator,iterHusk)\n\tif tstr.startswith('std::back_insert_iterator'):\n\t\treturn (std__back_insert_iterator,iterHusk)\n\n\tif LOOKUPppCLASS_Debug: printf('iter::getPP retNone ((C))\\n')\n\treturn (None,iterHusk)\n","repo_name":"vnstk/PrCxx","sub_path":"src/_stl_iterators.py","file_name":"_stl_iterators.py","file_ext":"py","file_size_in_byte":19770,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"8337486537","text":"import sys\nsys.path.append(\"..\")\nfrom unittest import TestCase\nimport pytest\nimport graph\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.figure import Figure\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatch\nimport matplotlib\nimport calma\nimport random\nfrom PyQt5 import QtWidgets, QtCore\nimport application\nimport mock\nimport cache\n\ndef fake_draw_canvas():\n return\n\nclass TestGraph(TestCase):\n @pytest.fixture(scope=\"function\", autouse=True)\n def setup(self):\n self.graphInstance = graph.CalmaPlot(600,600,100, True)\n self.cache = cache.Cache()\n self.calma = calma.Calma(self.cache)\n\n def test_constructor_graph(self):\n assert(isinstance(self.graphInstance.fig, Figure))\n\n def test_has_no_calma_available(self):\n graphInstance = graph.CalmaPlot(600, 600, 100, False)\n assert(graphInstance.placeHolderText._text == 'No CALMA data available for this query')\n\n def test_has_calma_available(self):\n graphInstance = graph.CalmaPlot(600, 600, 100, True)\n assert(graphInstance.placeHolderText._text == 'Click on a performance track for CALMA data')\n\n def test_get_colour_map(self):\n assert(isinstance(self.graphInstance.get_colour_map(), dict))\n\n def test_pre_processing(self):\n randoms = random.sample(range(60000), 1000)\n duration = 300\n nploudnessValues, duration, xSpaced, average = self.graphInstance.pre_processing(randoms, duration)\n\n def test_calculate_graph_element_positions(self):\n keyInfo = [[0.0, 'G major'], [1.486077097, 'G minor'], [8.173424036, 'G major'], [10.402539682, 'D minor'], [19.319002267, 'G minor'],\n [30.464580498, 'G major'], [40.867120181, 'D minor'], [41.61015873, 'G minor']]\n\n duration = float(326)\n average = 8.130601759965474\n\n for index, key in enumerate(keyInfo):\n lx, ly, rec = self.graphInstance.calculate_graph_element_position(keyInfo, key, index, duration, average)\n assert(isinstance(rec, mpatch.Rectangle))\n\nclass TestGraphPlotQt():\n @pytest.fixture(scope=\"function\", autouse=True)\n def setup(self, qtbot):\n # Create dialog to show this instance\n self.dialog = QtWidgets.QMainWindow()\n\n # Start main event loop\n self.prog = application.mainWindow(self.dialog)\n self.graphInstance = graph.CalmaPlot(600, 600, 100, True)\n\n @mock.patch('graph.CalmaPlot.finishDraw', side_effect=fake_draw_canvas)\n def test_plot_calma_data(self, arg):\n \"\"\"\n http://calma.linkedmusic.org/data/f3/track_f3d3321d-2ee3-49ab-9b9d-221d75ca4704\n http://calma.linkedmusic.org/data/80/track_8002a966-fc65-4af6-897a-cdecd237f8f9\n http://calma.linkedmusic.org/data/b3/track_b39b7800-193f-4196-ac41-c139599f97b3\n http://calma.linkedmusic.org/data/c4/track_c4e3019f-bb86-4c7d-b5be-7827ef7e48c7\n \"\"\"\n\n # Create a plot of the CALMA data\n signals = SignalsMock()\n # Check our lambda function returns closest key change to inputted value\n kwargs = {'finished_set_new_track': signals.finishedSetTrackSignal}\n self.prog.calmaHandler.set_new_track_calma(\"http://calma.linkedmusic.org/data/80/track_8002a966-fc65-4af6-897a-cdecd237f8f9\", **kwargs)\n self.graphInstance.plot_calma_data(self.prog.calmaHandler.loudnessValues, self.prog.calmaHandler.keyInfo, self.prog.calmaHandler.duration, 'key')\n self.graphInstance.plot_calma_data(self.prog.calmaHandler.loudnessValues, self.prog.calmaHandler.keyInfo, self.prog.calmaHandler.duration,\n 'segment')\n\nclass SignalsMock(QtCore.QObject):\n finishedSetTrackSignal = QtCore.pyqtSignal(object, object, object, float, dict)\n","repo_name":"CameronJRAllan/eTree-Browser","sub_path":"tests/test_graph.py","file_name":"test_graph.py","file_ext":"py","file_size_in_byte":3607,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"71853023801","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n## Aggregate area-response curves of a group of neurons\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys,os,os.path\nimport scipy.fftpack\n\n# Data path\ndata_path = \"/home/pablo/Desktop/Biophysical_thalamocortical_system/thalamocortical/results/\"\n\n# Number of neurons (all layers except INs)\nN = 10.0\n\n# Stimulus diameters\nstimulus = np.arange(0.0,10.2,0.2)\n\n# Folder\nfolder = \"retina/disk/ON\"\n\n# Type of stimulus (disk/patch)\ntype = \"disk\"\n\n# Neuron type to plot\nIDs = [\"PY_h-ON\"] # Pyramidal cells\n#IDs = [\"\"] # Ganglion cells\n\n# Simulation parameters\ntsim = 1000.0\nbinsize = 5.0\nnumbertrials =100.0\n\n# Interval to average spot response\nspot_interval = [500.0,1000.0]\n\n# Cell ID\ncell_numbers = [44,45,54,55]\n\nif os.path.isdir(\"tmp\") == False:\n os.system(\"mkdir tmp\")\n\n# Metrics: center-surround antagonism\ndef alphavr(response,stimulus):\n\n rc = np.max(response)\n rc_pos = np.argmax(response)\n rcs = np.min(response[rc_pos:])\n rcs_pos = np.argmin(response[rc_pos:])+rc_pos\n alpha = 100.0 * (rc - rcs) / (rc - response[0])\n\n print(\"Stimulus[rc] = %s, rc = %s\" % (stimulus[rc_pos],rc))\n print(\"Stimulus[rcs] = %s, rcs = %s\" % (stimulus[rcs_pos],rcs))\n print(\"alpha_vr = %s\" % alpha)\n\n# Load PST\ndef loadPST(stim,N,tsim,binsize,neuron,add_path):\n\n PST_avg = np.zeros((int(N*N),int(tsim/binsize)))\n lines = [line.rstrip('\\n') for line in open(data_path+add_path+\"/stim\"+str(stim)+\"/PST\"+neuron, \"r\")]\n for n in np.arange(len(lines)):\n h = lines[int(n)].split(',')\n for pos in np.arange(0,tsim/binsize):\n PST_avg[int(n),int(pos)] = float(h[int(pos)])\n\n return PST_avg\n\n# Create arrays of all PSTs\ndef createPST(cellID,stimulus,N,tsim,binsize,add_path):\n\n PST = []\n for s in stimulus:\n PST.append(loadPST(s,N,tsim,binsize,cellID,add_path))\n\n return PST\n\n# Area-response curve\ndef area_response(PSTs,cells):\n\n aggregate_signal = []\n\n for cell_n in cells:\n response = []\n # Estimation of spontaneous rate\n sp_rate = np.sum((PSTs[0])[cell_n,:])/(len((PSTs[0])[cell_n,:])*numbertrials)\n\n for PST in PSTs:\n if(type == \"disk\"):\n PST = PST[cell_n,int(spot_interval[0]/binsize):int(spot_interval[1]/binsize)]/numbertrials\n response.append(np.sum(PST)/len(PST))\n else:\n PST = PST[cell_n,int(250.0/binsize):int(1250.0/binsize)]/numbertrials\n response.append( np.mean(np.abs(PST - np.mean(PST))) + np.mean(PST))\n\n aggregate_signal.append(np.array(response))\n\n avg_signal = (aggregate_signal[0]+aggregate_signal[1]+\\\n aggregate_signal[2]+aggregate_signal[3])/4.0\n\n return avg_signal\n\n# 7-point interpolation\ndef interpolation(response,stimulus):\n\n new_response = [response[i]+response[i+1]+response[i+2]+response[i+3]+\\\n response[i+4]+response[i+5]+response[i+6] for i in np.arange(len(stimulus)-6)]\n new_response = np.array(new_response)/7.0\n xdata = stimulus[3:len(stimulus)-3]\n\n # For d = 0\n xdata = np.concatenate((np.array([0.0]),np.array(xdata)))\n new_response = np.concatenate((np.array([response[0]]),new_response))\n\n return xdata,new_response\n\n\n# Plots\nfig = plt.figure()\nfig.subplots_adjust(hspace=0.4)\n\nVax = plt.subplot2grid((2,1), (0,0))\nGax = plt.subplot2grid((2,1), (1,0))\n\nfor ID in IDs:\n\n newPST = createPST(ID,stimulus,N,tsim,binsize,folder)\n\n # Response\n response = area_response(newPST,cell_numbers)\n\n # Interpolated response\n xdata,new_response = interpolation(response,stimulus)\n\n # Absolute response\n Vax.plot(xdata,new_response,label = ID)\n\n # Save data to file\n np.savetxt('tmp/'+'area_response_abs_'+type+\\\n '_'+ID+'.out', new_response, delimiter=',')\n\n # Calculate metrics\n print(ID)\n alphavr(new_response,xdata)\n\n # Normalized response\n new_response -= np.min(new_response)\n Gax.plot(xdata,new_response/np.max(new_response),label = ID)\n\n # Save data to file\n np.savetxt('tmp/'+'area_response_norm_'+type+\\\n '_'+ID+'.out', new_response/np.max(new_response), delimiter=',')\n\n\nVax.legend(loc=1)\nVax.set_ylabel('Firing rate (Hz)')\nGax.set_ylabel('Normalized firing rate')\nGax.set_xlabel('Spot/patch diameter (deg)')\nplt.show()\n","repo_name":"CINPLA/biophysical_thalamocortical_system","sub_path":"thalamocortical/plots/area_response_aggregate_PYs.py","file_name":"area_response_aggregate_PYs.py","file_ext":"py","file_size_in_byte":4297,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"9557627502","text":"arquivo = open('lorem.txt', 'r')\nconteudo = arquivo.readlines()\n\narquivo = open('lorem.txt', 'r')\nvogais = 0\nespacos = 0\nconsoantes = 0\n\nfor line in arquivo:\n for char in line:\n if char == 'A' or char == 'E' or char == 'I' or char == 'O' or char == 'U' or char == 'a' or char == 'e' or char == 'i' or char == 'o' or char == 'u':\n vogais = vogais + 1\n \n if char == ' ':\n espacos = espacos+ 1\n \n else:\n consoantes = consoantes + 1\n \nprint(\"Numero de vogais: \", vogais, \"|| Numero de espacos: \", espacos, \"|| Numero de consoantes: \", consoantes)\n\ntexto = \"Numero de vogais: \", vogais, \"|| Numero de espacos: \", espacos, \"|| Numero de consoantes: \", consoantes\nconteudo.append(texto)\n\narquivo = open('lorem.txt', 'w')\narquivo.writelines(str(conteudo))\narquivo.close\n ","repo_name":"guilhermebrentan/ContadorDeChars","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"20435861069","text":"import cv2\r\nimport numpy as np\r\nimport urllib.request\r\n\r\nurl='http://192.168.100.81/cam-hi.jpg'\r\n\r\nwin_nama='ESP32'\r\ncv2.namedWindow(win_nama,cv2.WINDOW_AUTOSIZE)\r\n\r\nwhile(1):\r\n imgResponse=urllib.request.urlopen(url)\r\n imgNP=np.array(bytearray(imgResponse.read()),dtype=np.uint8)\r\n img=cv2.imdecode(imgNP,-1)\r\n\r\n cv2.imshow(win_nama,img)\r\n keluar=cv2.waitKey(1) & 0xFF\r\n if keluar ==27:\r\n break\r\ncv2.destroyAllWindows()\r\n\r\n","repo_name":"adityaharis69/esp32-cam-webserver-python","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"74685275959","text":"from m5.objects import *\n\n\"\"\"\nA cache whose prefetcher and replacement policy can be configured,\n with a default of no-prefetcher and LRU replacement\n For all prefetcher options, see:\n src/mem/cache/prefetch/Prefetcher.py\n For all replacement policy options, see:\n src/mem/cache/replacement_policies/ReplacementPolicies.py\n\"\"\"\nclass CS395T_ConfigurableCache(Cache):\n # HINT: If you want to change the prefetcher and/or replacement \n # policy based on command-line options, this is the place to do it.\n # You could instantiate any available prefetcher Prefetcher.py, or you\n # can extend those classes to change the prefetcher's default params\n # and then instantiate that instead.\n # (See CS395T_CPU's use of LocalBP for an example.)\n # The comment at the top of this file has a path to the class definitions\n # of all the built-in prefetcher options, where you can look for a basic \n # stride prefetcher.\n def __init__(self, pref: str, repl : str):\n super().__init__()\n\n if pref not in [\"stride\", \"none\"]:\n raise NotImplementedError(\n \"Unsupported prefetcher\"\n )\n if(pref == \"stride\"):\n self.prefetcher = StridePrefetcher(degree = 3)\n else:\n self.prefetcher = NULL\n \n if repl == \"hawkeye\":\n print(\"Hawkeye Enable\")\n self.replacement_policy = HawkeyeRP(cache_level = 2, num_cache_sets = 2048)\n elif repl == \"mockingjay\":\n print(\"Mockingjay Enable\")\n self.replacement_policy = MockingjayRP(num_cache_sets = 2048)\n else:\n self.replacement_policy = LRURP()\n\n self.prefetch_on_access = True\n","repo_name":"dingqy/Master-thesis-gem5","sub_path":"configs/sim_scripts/our_components/memory_hierarchies/caches/configurable_cache.py","file_name":"configurable_cache.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"27818143741","text":"###############################################\n# Group Name : XXXXXX\n\n# Member1 Name: XXXXXX\n# Member1 SIS ID: XXXXXX\n# Member1 Login ID: XXXXXX\n\n# Member2 Name: XXXXXX\n# Member2 SIS ID: XXXXXX\n# Member2 Login ID: XXXXXX\n###############################################\n###############################################\n# MUST KEEP: sets printing butter to 1, so it will always flush. allows the autograder to work. \nimport sys\nimport socket\nimport os\nimport random\nimport pickle\nsys.stdout = open(sys.stdout.fileno(), 'w', buffering=1)\n###############################################\ndef read_chain_file(chainfile):\n with open(chainfile, 'r') as file:\n lines = file.readlines()\n num_ss = int(lines[0].strip())\n ss_list = [line.strip() for line in lines[1:num_ss + 1]]\n return ss_list\n\ndef save_file(url, conn, ss_list):\n filename = url.split('/')[-1] if '/' in url else 'index.html'\n\n print(f\"Request: {url}...\")\n print(\"chainlist is\")\n \n for entry in ss_list:\n print(entry)\n \n #print(f\"Next SS is {ss_list[0]}\")\n #print(\"waiting for file...\")\n\n with open(filename, 'wb') as file:\n while True:\n data = conn.recv(1024)\n if not data:\n break\n file.write(data)\n \n return filename\n\ndef main(url, chainfile):\n if not chainfile:\n if os.path.exists(\"chaingang.txt\"):\n chainfile = \"chaingang.txt\"\n else:\n print(\"Error: Chainfile not found.\")\n sys.exit(1)\n\n ss_list = read_chain_file(chainfile)\n \n if not ss_list:\n print(\"Error: Empty chainfile.\")\n sys.exit(1)\n\n ss_cp_list = ss_list.copy()\n selected_ss = random.choice(ss_list)\n ss_list.remove(selected_ss)\n\n host, port = selected_ss.split()\n\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.connect((host, int(port)))\n\n #updated_chain_list = [f\"{host} {port}\"] + ss_list\n serialized_data = pickle.dumps([url] + ss_list)\n s.sendall(serialized_data)\n\n filename = save_file(url, s, ss_cp_list)\n print(f\"Next SS is {selected_ss}\")\n print(\"waiting for file...\")\n print(f\"Received file {filename}\")\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 2:\n print(\"Usage: awget.py [URL] [-c chainfile]\")\n sys.exit(1)\n\n url = sys.argv[1]\n chainfile = sys.argv[3] if len(sys.argv) > 3 and sys.argv[2] == '-c' else None\n main(url, chainfile)\n print(\"Goodbye!\")\n ","repo_name":"mcoco35/Anonymous-Web-Get","sub_path":"Student_autograder/awget.py","file_name":"awget.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"11322977509","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport hashlib\nimport random\nimport datetime\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.utils import timezone\nfrom django.utils.encoding import python_2_unicode_compatible\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom django.db import models\nfrom core.models import BaseModel\nfrom products.models import Product\nfrom users.models import User\nfrom core.models import BaseManager\n\n\ndef generate_slug():\n exists = True\n code = ''\n while exists:\n hash = hashlib.md5()\n from datetime import datetime\n\n now = datetime.now()\n hash.update(str(random.random()) + now.strftime('%Y-%m-%d %H:%M') + settings.SECRET_KEY)\n code = hash.hexdigest()\n exists = len(Event.objects.filter(slug=code)) > 0\n return code\n\n\nclass EventManager(BaseManager):\n def not_past(self):\n return self.active().filter(date__gte=datetime.date.today())\n\n\n@python_2_unicode_compatible\nclass Event(BaseModel):\n name = models.CharField(_('Name'), max_length=50)\n date = models.DateTimeField(_('Date'))\n owner = models.ForeignKey(User, verbose_name=_('Owner'), related_name='wishes_lists')\n slug = models.SlugField(_('Access url'), null=True, blank=True, unique=True)\n\n objects = EventManager()\n\n class Meta:\n verbose_name = _('Event')\n verbose_name_plural = _('Events')\n\n def save(self, **kwargs):\n if not self.slug:\n self.slug = generate_slug()\n super(Event, self).save(**kwargs)\n\n def is_past(self):\n return self.date < timezone.now()\n is_past.boolean = True\n is_past.short_name = _('Is past')\n\n @property\n def url(self):\n return reverse('wishes:list_detail', kwargs={'code':self.slug})\n\n def __str__(self):\n return self.name\n\n\n@python_2_unicode_compatible\nclass Gift(BaseModel):\n product = models.ForeignKey(Product, verbose_name=_('Product'), related_name='wishes_set')\n event = models.ForeignKey(Event, verbose_name=_('Event'), related_name='wishes_set')\n reservation_date = models.DateTimeField(_('Reservation date'), null=True, blank=True)\n reserved_by = models.ForeignKey(User, verbose_name=_('Reserved by'), null=True, blank=True)\n reserved_by_anonymous = models.EmailField(_('Reserved by anonymous'), null=True, blank=True)\n\n class Meta:\n verbose_name = _('Gift')\n verbose_name_plural = _('Gifts')\n\n def is_reserved(self):\n return self.reserved_by is not None or self.reserved_by_anonymous != ''\n\n @property\n def is_reserved_property(self):\n return self.is_reserved()\n\n is_reserved.short_name = _('Is reserved')\n is_reserved.boolean = True\n\n def __str__(self):\n return unicode(_('Product %(product_name)s is on %(event)s wishes list.') % {'product_name': self.product.name,\n 'event': self.event.name})\n\n\n@python_2_unicode_compatible\nclass EventInvitedFriends(BaseModel):\n event = models.ForeignKey(Event, verbose_name=_('Event'), related_name='events_invitations')\n friend = models.ForeignKey(User, verbose_name=_('Friend'), related_name=\"events_invitations\")\n\n class Meta:\n verbose_name = _('Event - invented friend')\n verbose_name_plural = _('Event - invented friends')\n\n def __str__(self):\n return unicode(_('%(friend)s has been invited to %(event)s event.') % {'friend': self.friend.nick,\n 'event': self.event.name})\n","repo_name":"projects-dream-team/wishes-list-website","sub_path":"apps/wishes/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"40729758985","text":"\"\"\"remove pulse user 1 to many field\n\nRevision ID: 1ff5c08b2ac\nRevises: 4bd0784e2978\nCreate Date: 2017-01-26 14:29:25.399344\n\n\"\"\"\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n# revision identifiers, used by Alembic.\nrevision = '1ff5c08b2ac'\ndown_revision = '4bd0784e2978'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n bind = op.get_bind()\n\n # Sqlite does not support dropping columns or constraints, so only do this\n # on \"real\" databases. Locally, we re-create the databases on dbinit\n # anyway. In addition: this field and constraint are a no-op since they're\n # not used anymore in the code.\n if bind.engine.name != \"sqlite\":\n op.drop_constraint('pulse_users_owner_id_fkey', 'pulse_users', 'foreignkey')\n op.drop_column('pulse_users', 'owner_id')\n\n\ndef downgrade():\n op.add_column('pulse_users', sa.Column('owner_id', sa.Integer,\n sa.ForeignKey('users.id')))\n","repo_name":"mozilla-services/pulseguardian","sub_path":"migration/versions/1ff5c08b2ac_remove_pulse_user_owner_id_field.py","file_name":"1ff5c08b2ac_remove_pulse_user_owner_id_field.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"40"} +{"seq_id":"1781313632","text":"\"\"\"add_user_relationships\n\nRevision ID: 1affaad0e7eb\nRevises: 1aa0fc063351\nCreate Date: 2023-01-04 22:35:10.621176\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nimport sqlmodel\n\n\n# revision identifiers, used by Alembic.\nrevision = '1affaad0e7eb'\ndown_revision = '1aa0fc063351'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n op.create_table('usershoppinglist',\n sa.Column('shopping_list_id', sa.Integer(), nullable=False),\n sa.Column('user_id', sa.Integer(), nullable=False),\n sa.Column('owner', sa.Boolean(), default=False),\n sa.ForeignKeyConstraint(['user_id'], ['user.id'], ondelete=\"CASCADE\"),\n sa.ForeignKeyConstraint(['shopping_list_id'], ['shoppinglist.id'], ondelete=\"CASCADE\"),\n sa.PrimaryKeyConstraint('user_id', 'shopping_list_id')\n )\n\n\ndef downgrade() -> None:\n op.drop_table('usershoppinglist')\n","repo_name":"kevnoli/shopping-list","sub_path":"backend/migrations/versions/1affaad0e7eb_add_user_relationships.py","file_name":"1affaad0e7eb_add_user_relationships.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"37911262996","text":"import pandas as pd\r\nxl_file = pd.read_excel(\"Modified_Khardung.xlsx\")\r\n\r\n#xl_file = pd.read_excel(\"KH-PH-AWS-2017-19-Johnn.xlsx\",sheet_name=\"Khardung-AWS-SEB\")\r\n\r\n# for i in range(909,980 + 1):\r\n# date = str(xl_file.loc[i,'DATE'])\r\n# new_str_date = date[1:3]+'-'+date[0]+'-20'+date[-2:]\r\n# xl_file.loc[i,'DATE'] = pd.to_datetime(new_str_date)\r\n\r\n\r\n# xl_file = pd.read_excel(\"Modified_Khardung.xlsx\")\r\n# for i in range(1893,2468 + 1):\r\n# date = xl_file.loc[i,'DATE']\r\n# xl_file.loc[i,'DATE']=date.replace(month=date.day,day=date.month)\r\n\r\nfor i in range(909,3141):\r\n print(i)\r\n time = xl_file.loc[i,'TIME']\r\n str_time = str(time)\r\n if(time==0):\r\n new_time = '00:00:00'\r\n elif(time==30):\r\n new_time = '00:30:00'\r\n elif(time<1000):\r\n new_time = '0'+str_time[0]+':'+str_time[-2:]+':00'\r\n else:\r\n new_time = str_time[:-2]+':'+str_time[-2:]+':00'\r\n xl_file.loc[i,'TIME'] = new_time\r\n if(i==3139):\r\n xl_file.to_excel(\"Modified_Khardung_time.xlsx\")\r\n\r\n#xl_file.loc[3142,'TIME'] = \"23:30:00\"\r\n\r\n#xl_file.to_excel(\"Modified_Khardung_time.xlsx\")\r\n","repo_name":"ShaunThayil/Excel-Summary-Using-Pandas-QT","sub_path":"PlayGround/Khardung Summary/khardung_modi.py","file_name":"khardung_modi.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"40"} +{"seq_id":"72867348601","text":"r\"\"\"@package motsfinder.numutils\n\nMiscellaneous numerical utilities and helpers.\n\n\n@b Examples\n\n```\n >>> binomial(5, 3)\n 10\n```\n\"\"\"\n\nfrom contextlib import contextmanager\nimport warnings\n\nfrom scipy.linalg import LinAlgWarning\nfrom scipy.integrate import fixed_quad, IntegrationWarning\nfrom scipy.interpolate import interp1d\nfrom scipy import optimize\nimport numpy as np\nimport sympy as sp\n\n\n__all__ = [\n \"nan_mat\",\n \"clip\",\n \"linear_interp\",\n \"binomial\",\n \"binomial_coeffs\",\n \"inf_norm1d\",\n \"raise_all_warnings\",\n \"try_quad_tolerances\",\n \"bracket_root\",\n \"find_root\",\n \"find_all_roots\",\n \"interpolate_root\",\n \"extrapolate_root\",\n \"IntegrationResult\",\n \"IntegrationResults\",\n \"NumericalError\",\n]\n\n\n_golden = 1.61803398874989 # (1+sqrt(5))/2, the \"golden ratio\"\n\n\nclass NumericalError(Exception):\n r\"\"\"Exception raised for problems with numerical evaluation.\n\n For example, a tensor field class based on numerical data may raise this\n (or a subclass) if evaluation outside the numerical domain is requested.\n \"\"\"\n pass\n\n\ndef nan_mat(shape):\n r\"\"\"Create a matrix of NaN values.\"\"\"\n T = np.empty(shape)\n T[:] = np.nan\n return T\n\n\ndef clip(x, x_min, x_max):\n r\"\"\"Confine a value to an interval.\"\"\"\n return max(x_min, min(x_max, x))\n\n\ndef linear_interp(x, x1, x2, y1, y2, extrapolate=True):\n r\"\"\"Linearly interpolate between two numbers.\n\n @param x\n Abscissa to interpolate to.\n @param x1,x2\n Abscissas of the two data points to interpolate between.\n @param y1,y2\n Ordinates of the two data points to interpolate between.\n \"\"\"\n if not extrapolate:\n x = clip(x, x1, x2)\n return (y2-y1) * (x-x1)/(x2-x1) + y1\n\n\ndef binomial(n, k):\n r\"\"\"Compute the binomial coefficient n choose k.\"\"\"\n return int(sp.binomial(n, k))\n\n\ndef binomial_coeffs(n):\n r\"\"\"Compute all binomial coefficients n choose k for 0 <= k <= n.\n\n The result is a list of integers\n \\f[\n {n \\choose 0}, {n \\choose 1}, \\ldots, {n \\choose n}.\n \\f]\n \"\"\"\n return _BinomialCoeffs.all_coeffs(n)\n\n\nclass _BinomialCoeffs():\n r\"\"\"Helper class to simply cache the coefficient lists.\n\n This is used by binomial_coeffs() to re-use once computed lists.\n \"\"\"\n\n __binomial_coeffs = []\n\n @classmethod\n def all_coeffs(cls, n):\n r\"\"\"Generate and cache the results for binomial_coeffs().\"\"\"\n while len(cls.__binomial_coeffs) <= n:\n nn = len(cls.__binomial_coeffs)\n coeffs = [binomial(nn, k) for k in range(n+1)]\n cls.__binomial_coeffs.append(coeffs)\n return cls.__binomial_coeffs[n]\n\n\ndef inf_norm1d(f1, f2=None, domain=None, Ns=50, xatol=1e-12):\n r\"\"\"Compute the L^inf norm of f1-f2.\n\n The `scipy.optimize.brute` method is used to find a candidate close to the\n global maximum difference. This is then taken as starting point for a\n search for the local maximum difference. Setting the number of samples\n `Ns` high enough should lead to the global maximum difference being found.\n\n @param f1\n First function. May also be a `NumericExpression`.\n @param f2\n Second function. May also be a `NumericExpression`. If not given,\n simply finds the maximum absolute value of `f1`.\n @param domain\n Domain ``[a, b]`` inside which to search for the maximum difference.\n By default, `f1` is queried for the domain.\n @param Ns\n Number of initial samples for the `scipy.optimize.brute` call. In case\n ``Ns <= 2``, the `brute()` step is skipped an a local extremum is\n found inside the given `domain`. Default is `50`.\n\n @return A pair ``(x, delta)``, where `x` is the point at which the maximum\n difference was found and `delta` is the difference at that point.\n \"\"\"\n if domain is None:\n domain = f1.domain\n if not callable(f1):\n f1 = f1.evaluator()\n if f2 is None:\n f2 = lambda x: 0.0\n if not callable(f2):\n f2 = f2.evaluator()\n domain = list(map(float, domain))\n a, b = domain\n func = lambda x: (\n -float(abs(f1(float(x))-f2(float(x)))) if a <= x <= b else 0.\n )\n if Ns <= 2:\n bounds = [a, b]\n else:\n x0 = optimize.brute(func, [domain], Ns=Ns, finish=None)\n step = (b-a)/(Ns-1)\n bounds = [x0-step, x0+step]\n res = optimize.minimize_scalar(\n func, bounds=bounds, method='bounded',\n options=dict(xatol=xatol),\n )\n return res.x, -res.fun\n\n\ndef try_quad_tolerances(func, args=(), kwargs=None, tol_min=1e-11,\n tol_max=1e-2, tol_steps=None, verbose=False):\n r\"\"\"Try to run a given function with increasing tolerance until integration succeeds.\n\n @param func\n Callable performing the integration. This should issue or raise an\n `IntegrationWarning` for too low tolerances. It is called as\n ``func(tol, *args, **kwargs)``.\n @param args\n Optional additional positional arguments for `func`.\n @param kwargs\n Optional additional keyword arguments for `func`.\n @param tol_min\n Minimal tolerance to try first. Default is `1e-11`.\n @param tol_max\n Maximum tolerance to allow. If `func` fails for this tolerance, no\n more trials are done and the `IntegrationWarning` warning is raised.\n Default is `1e-2`.\n @param tol_steps\n How many steps to try when going from `tol_min` to `tol_max`. Should\n be at least two. Default is to go roughly through each order of\n magnitude.\n @param verbose\n If `True`, print the tolerances as they are tried out. Default is\n `False`.\n \"\"\"\n if tol_min > tol_max:\n raise ValueError(\"minimal tolerance greater than maximum tolerance\")\n tol_min = np.log10(tol_min)\n tol_max = np.log10(tol_max)\n if tol_steps is None:\n tol_steps = max(2, int(round(tol_max-tol_min) + 1))\n tols = np.logspace(tol_min, tol_max, tol_steps)\n with raise_all_warnings():\n for tol in tols:\n if verbose:\n print(\"Trying with tol=%s\" % tol)\n try:\n return func(tol, *args, **(kwargs or dict()))\n except IntegrationWarning:\n if verbose:\n print(\"... failed with tol=%s\" % tol)\n if tol == tols[-1]:\n raise\n\n\nclass IntegrationResults():\n r\"\"\"Represents a sequence of multiple integration results.\n\n This class presents convenience methods to sum individual results and\n errors and check whether all results were computed without any warnings.\n\n @b Examples\n\n ```\n #res = ... # obtained via some means\n res[0].value # value of first result\n res.sum() # sum of all values\n res.sum(0, 2) # sum first and third result\n res.sum(full_output=True).error # access errors, infos and warnings\n print(\"\\n\".join(str(r.error) for r in res)) # print individual errors\n ```\n \"\"\"\n\n def __init__(self, *results, info=None, sum_makes_sense=True):\n r\"\"\"Create a results object from given results.\n\n Positional arguments can be either the ``full_output=True`` results of\n `scipy.integrate.quad()` calls or IntegrationResult objects.\n\n @param *results\n Results to collect.\n @param info\n Arbitrary info object to be stored with the results.\n @param sum_makes_sense\n Whether the sum of all results is a meaningful number. This\n controls if the total is printed in case of string conversion.\n \"\"\"\n def _to_result(res):\n if not isinstance(res, IntegrationResult):\n res = IntegrationResult(*res)\n return res\n self._results = [_to_result(r) for r in results]\n ## Additional info supplied to the constructor.\n self.info = info\n ## Whether the sum of all results is a meaningful number.\n self.sum_makes_sense = sum_makes_sense\n\n @property\n def value(self):\n r\"\"\"Total value (sum of all results).\"\"\"\n return self.sum()\n\n @property\n def error(self):\n r\"\"\"Total error (sum of all errors).\"\"\"\n return self.sum(full_output=True).error\n\n def __len__(self):\n r\"\"\"Number of stored results.\"\"\"\n return len(self._results)\n\n def __getitem__(self, key):\n r\"\"\"Access individual results.\"\"\"\n return self._results[key]\n\n def __iter__(self):\n r\"\"\"Iterate through individual results.\"\"\"\n return iter(self._results)\n\n def sum(self, *indices, full_output=False):\n r\"\"\"Combine results (sum values and optionally errors).\"\"\"\n if indices:\n results = [self._results[i] for i in indices]\n else:\n results = self._results\n result = sum([r.value for r in results])\n if not full_output:\n return result\n err = sum([r.error for r in results])\n infos = [r.info for r in results]\n if all([r.is_ok() for r in results]):\n warning = None\n else:\n warning = \"\\n\".join([r.warning for r in results if r.warning])\n return IntegrationResult(result, err, infos, warning)\n\n def __repr__(self):\n result = \"\\n\".join(\"[%s] %s\" % (i, r) for i, r in enumerate(self._results))\n if self.sum_makes_sense and len(self._results) > 1:\n total = self.sum(full_output=True)\n result += \"\\nTotal: %s +- %s\" % (total.value, total.error)\n if self.info:\n result += \"\\nInfo:\\n%s\" % (self.info,)\n return result\n\n def all_ok(self):\n r\"\"\"Return whether none of the results produced a warning.\"\"\"\n return all([r.is_ok() for r in self._results])\n\n\nclass IntegrationResult():\n r\"\"\"Wrapper of the `full_output` of a `quad()` call.\"\"\"\n\n def __init__(self, value, error, info, warning=None, mult=None):\n r\"\"\"Create a result object from the output of `quad()`.\n\n @param value\n Main result, i.e. the computed value.\n @param error\n The estimate of the error of the value.\n @param info\n Integration info object.\n @param warning\n Any warnings produced during integration.\n @param mult\n Factor by which to multiply the result and error.\n \"\"\"\n if mult is not None:\n value = mult * value\n error = mult * error\n ## Computed value.\n self.value = value\n ## Estimated error.\n self.error = error\n ## Info object of the integration `quad()` call.\n self.info = info\n ## Warnings produced while integrating (`None` in case of no warnings).\n self.warning = warning\n\n def is_ok(self):\n r\"\"\"Return whether the result is OK and produced no warning.\"\"\"\n return self.warning is None\n\n def __repr__(self):\n txt = \"%s +- %s\" % (self.value, self.error)\n if self.warning is not None:\n w = str(self.warning).split(\"\\n\")\n w = \"\\n \".join(w)\n txt += \"\\nWarning: %s\" % w\n return txt\n\n\ndef inverse_2x2_matrix_derivative(A, dA=None, ddA=None, diff=1):\n r\"\"\"Compute derivatives of the inverse of a 2x2 matrix.\n\n Given an invertible 2x2 matrix `A` with elements \\f$a_{ij}\\f$ and any\n needed derivatives w.r.t. two different variables, this returns the\n derivatives of the inverse of `A`.\n\n @param A\n The original matrix to compute the inverse of.\n @param dA\n Nested list or NumPy array with three indices where `dA[i][j][k]`\n contains the value of \\f$\\partial_i a_{jk}\\f$.\n @param ddA\n Nested list or NumPy array with four indices where `dA[i][j][k][l]`\n contains the value of \\f$\\partial_i \\partial_j a_{kl}\\f$.\n @param diff\n Derivative order of the inverse matrix. If ``diff==0``, the inverse of\n `A` is returned and `dA` and `ddA` are not needed. `dA` is needed if\n ``diff > 0`` and `ddA` for ``diff > 1``. Default is `1`.\n\n @return NumPy array with two, three, or four axes depending on `diff`. The\n meaning of the indices such that `result[i1,i2,...,k,l]` contains the\n value \\f$\\partial_{i_1} \\partial_{i_2} \\ldots (B)_{kl}\\f$, where `B`\n is the inverse \\f$B = A^{-1}\\f$.\n\n @b Notes\n\n Consider the matrix\n \\f[\n A = \\left(\\begin{array}{@{}cc@{}}\n a & b\\\\\n c & d\n \\end{array}\\right).\n \\f]\n The inverse is then given by\n \\f[\n B := A^{-1} = \\frac{1}{\\det A} \\left(\\begin{array}{@{}cc@{}}\n b & -b\\\\\n -c & a\n \\end{array}\\right),\n \\f]\n where \\f$\\det A = ad-bc\\f$.\n The derivatives are easily computed using the chain and Leibniz' rule,\n which result in (using the shorthand notation \\f$a_i := \\partial_i a\\f$\n and \\f$a_{ij} := \\partial_i \\partial_j a\\f$)\n \\f[\n \\partial_i B =\n - \\frac{\\partial_i \\det A}{(\\det A)^2}\n \\left(\\begin{array}{@{}cc@{}}\n d & -b\\\\\n -c & a\n \\end{array}\\right)\n + \\frac{1}{\\det A}\n \\left(\\begin{array}{@{}cc@{}}\n d_i & -b_i\\\\\n -c_i & a_i\n \\end{array}\\right)\n \\f]\n and\n \\f{eqnarray*}{\n \\partial_i \\partial_j B &=&\n \\left(\n -\\frac{\\partial_i\\partial_j\\det A}{(\\det A)^2}\n + 2 \\frac{(\\partial_i\\det A)(\\partial_j\\det A)}{(\\det A)^3}\n \\right)\n \\left(\\begin{array}{@{}cc@{}}\n d & -b\\\\\n -c & a\n \\end{array}\\right)\n \\\\&&\n - \\frac{\\partial_i\\det A}{(\\det A)^2}\n \\left(\\begin{array}{@{}cc@{}}\n d_j & -b_j\\\\\n -c_j & a_j\n \\end{array}\\right)\n - \\frac{\\partial_j\\det A}{(\\det A)^2}\n \\left(\\begin{array}{@{}cc@{}}\n d_i & -b_i\\\\\n -c_i & a_i\n \\end{array}\\right)\n \\\\&&\n + \\frac{1}{\\det A}\n \\left(\\begin{array}{@{}cc@{}}\n d_{ij} & -b_{ij}\\\\\n -c_{ij} & a_{ij}\n \\end{array}\\right),\n \\f}\n where\n \\f{eqnarray*}{\n \\partial_i \\det A &=&\n a_i d + a d_i - b_i c - b c_i,\n \\\\\n \\partial_i \\partial_j \\det A &=&\n a_{ij} d + a_i d_j + a_j d_i + a d_{ij}\n - b_{ij} c - b_i c_j - b_j c_i - b c_{ij}.\n \\f}\n \"\"\"\n if diff not in (0, 1, 2):\n raise NotImplementedError\n ra = range(2)\n A = np.asarray(A)\n dA = np.asarray(dA)\n a, b, c, d = A.flatten()\n det = a*d - b*c\n B = np.array([[d, -b], [-c, a]])\n if diff == 0:\n return 1/det * B\n # dA has axes [partial_i, row, col]\n # we want e.g.: da = [partial_x a, partial_y a]\n da, db, dc, dd = [dA[:,i,j] for i in ra for j in ra]\n ddet = np.array([da[i]*d + a*dd[i] - db[i]*c - b*dc[i] for i in ra])\n dB = np.array([[[dd[i], -db[i]], [-dc[i], da[i]]] for i in ra])\n if diff == 1:\n return np.array([-ddet[i]/det**2 * B + 1/det * dB[i] for i in ra])\n ddA = np.asarray(ddA)\n # these are the second derivatives dda[i,j] := partial_i partial_j a\n dda, ddb, ddc, ddd = [ddA[:,:,i, j] for i in ra for j in ra]\n # ddB has axes [partial_i, partial_j, row, col]\n ddB = np.array([[[[ddd[i,j], -ddb[i,j]], [-ddc[i,j], dda[i,j]]]\n for j in ra] for i in ra])\n dddet = np.array(\n [[dda[i,j]*d + da[i]*dd[j] + da[j]*dd[i] + a*ddd[i,j]\n -ddb[i,j]*c - db[i]*dc[j] - db[j]*dc[i] - b*ddc[i,j]\n for j in ra] for i in ra]\n )\n return np.array(\n [[(-dddet[i,j]/det**2 + 2*ddet[i]*ddet[j]/det**3) * B\n - ddet[i]/det**2 * dB[j]\n - ddet[j]/det**2 * dB[i]\n + 1/det * ddB[i,j]\n for j in ra] for i in ra]\n )\n\n\ndef bracket_root(f, x0, step, domain=(float(\"-inf\"), float(\"+inf\")),\n max_steps=10000, full_output=False, disp=False):\n r\"\"\"Simple (naive) sign change finder to bracket a root.\n\n Starting from an initial position (`x0`), this takes repeated steps until\n the function changes sign. The two x-values before and after the sign\n change are then returned (in undefined order) as a bracket. For any step\n taken, the step size is increased by the \"golden ratio\".\n\n If the function's absolute value increases, we continue to walk in the\n other direction. The step size is still increased, so that there is a\n chance to escape a local minimum.\n\n @param f\n Function to bracket a root of.\n @param x0\n Where to start walking.\n @param step\n Initial step length.\n @param domain\n Where to look for a sign change. If the search hits one of these\n boundaries, we either return the current (boundary) position or raise\n an error, depending on the `disp` parameter. Default is to not impose\n a boundary.\n @param max_steps\n Maximum number of steps to try. Default is `10000`.\n @param full_output\n If `True`, return the bracket and the two corresponding function\n values as ``a, b, f(a), f(b)``. Default is `False`, i.e. only return\n the bracket.\n @param disp\n If `True` and we get stuck at a domain boundary, raise a\n NumericalError. Default is `False`, i.e. return the boundary position\n as ``a, a, f(a), f(a)``.\n \"\"\"\n a = x0\n fa = f(a)\n turned = False\n for _ in range(max_steps):\n b = clip(a + step, *domain)\n if a == b and turned: # we ran against the domain boundary\n if disp:\n break\n return (a, a, fa, fa) if full_output else (a, a)\n fb = f(b)\n if fa*fb < 0.0:\n return (a, b, fa, fb) if full_output else (a, b)\n step *= _golden\n if abs(fa) <= abs(fb):\n step = -step\n turned = True\n else:\n a = b\n fa = fb\n raise NumericalError(\n \"Could not bracket a root within %s steps.\" % max_steps\n )\n\n\ndef find_root(f, x0, step, max_steps=10000, **kw):\n r\"\"\"Find a root of a function using Brent's method.\n\n This is a simple wrapper around `scipy.optimize.brentq()`, which first\n tries to automatically find a bracket required for the `brentq()` call.\n\n @param f\n Function (callable) to find a root of.\n @param x0\n Point to start searching for a sign change.\n @param step\n First step for the sign change search.\n @param max_steps\n Number of steps to take before givin up. Default is `10000`.\n @param **kw\n Further keyword arguments are passed to the `brentq()` call.\n \"\"\"\n a, b = bracket_root(f, x0=x0, step=step, max_steps=max_steps, disp=True)\n if b < a:\n a, b = b, a\n return optimize.brentq(f, a, b, **kw)\n\n\ndef find_all_roots(xs, ys, func=None, full_output=False):\n r\"\"\"Find all roots of a sampled function.\n\n This is used for functions that are already sampled at a grid of points\n `xs` with function values `ys`. It is assumed that this grid is dense\n enough such that all roots appear as sign changes in consecutive values in\n `ys` (and hence that the roots all have odd multiplicity).\n\n @return List of roots. Empty list if no sign change occurs in `ys`.\n\n @param xs,ys\n Precomputed abscissas and ordinates of `func`.\n @param func\n Callable for fine-tuning the root search. If not specified, an\n interpolating function will be generated from the `xs` and `ys` data.\n @param full_output\n Whether to output the roots only (`False`, default) or the roots and\n interpolating function (`True`).\n \"\"\"\n if len(xs) == 0:\n return ([], None) if full_output else []\n if func is None:\n kind = 'linear' if len(xs) < 4 else 'cubic'\n func = interp1d(xs, ys, kind=kind, fill_value=\"extrapolate\")\n roots = []\n for i in range(1, len(ys)):\n if ys[i]*ys[i-1] < 0: # sign change => root here\n x0 = optimize.brentq(func, a=xs[i-1], b=xs[i])\n roots.append(x0)\n return (roots, func) if full_output else roots\n\n\ndef interpolate_root(xs, ys, guess, step, kind=\"cubic\", full_output=False):\n r\"\"\"Interpolate data to estimate a root.\n\n @param xs,ys\n The data points (x- and y-values). The y-values need to change sign.\n @param guess\n The point to start searching for a root.\n @param step\n The first step size for searching for a root.\n @param kind\n Interpolation kind. Default is ``\"cubic\"``.\n @param full_output\n Whether to output the root only (`False`, default) or the root and\n interpolating function (`True`).\n \"\"\"\n if not len(xs):\n return (None, None) if full_output else None\n f = interp1d(xs, ys, kind=kind, fill_value=\"extrapolate\")\n r = find_root(f, x0=guess, step=step)\n return (r, f) if full_output else r\n\n\ndef extrapolate_root(xs, ys, guess=None, at_end=True, kind=\"cubic\",\n full_output=False):\n r\"\"\"Extrapolate data to estimate a root.\n\n @param xs,ys\n The data points (x- and y-values). These need not have a sign change.\n @param guess\n The point to start searching for a root in the interpolant. If not\n given, take the last x-interval as first guess.\n @param at_end\n If `True` (default), try to find a root *after* the data. Else, try to\n find it *before* the data.\n @param kind\n Interpolation kind. Default is ``\"cubic\"``.\n @param full_output\n Whether to output the root only (`False`, default) or the root and\n interpolating function (`True`).\n \"\"\"\n if not len(xs):\n return (None, None) if full_output else None\n if not at_end:\n xs = list(reversed(xs))\n ys = list(reversed(ys))\n f = interp1d(xs, ys, kind=kind, fill_value=\"extrapolate\")\n if guess is None:\n guess = 2*xs[-1] - xs[-2]\n r = find_root(f, x0=xs[-1], step=guess - xs[-1])\n return (r, f) if full_output else r\n\n\ndef _fixed_quad_abscissas(a, b, n):\n r\"\"\"Return the abscissas of the Gaussian quadrature of order `n`.\n\n These are the exact points at which an integrand will be evaluated by\n `scipy.integrate.fixed_quad(..., a, b, n)`. Note that this will hold for\n _fixed_quad() *only* if no `full_domain` is given (or it is equal to the\n integration interval).\n \"\"\"\n xs_list = [None]\n def f(x):\n xs_list[0] = x\n return np.zeros_like(x)\n fixed_quad(f, a=a, b=b, n=n)\n return xs_list[0]\n\n\ndef _fixed_quad(func, a, b, n, full_domain=None, min_n=30):\n r\"\"\"Integrate a function using fixed order Gaussian quadrature.\n\n This is a wrapper for `scipy.integrate.fixed_quad()`. Given a full domain\n to integrate, it uses the information of the current sub-domain to choose\n less than the full set of `n` points such that integrating the full domain\n in several intervals, the total number of evaluations is approximately\n `n`.\n\n @param func\n Function taking a list of values and returning a list of results.\n @param a,b\n Interval to integrate over.\n @param n\n Order of the Gaussian quadrature for the `full_domain`.\n @param full_domain\n Full domain to eventually integrate over. If not given, `a,b` is taken\n to be the full domain, i.e. no reduction of quadrature order is done.\n @param min_n\n Minimum quadrature order for very small sub-domains.\n \"\"\"\n if full_domain is not None:\n w = full_domain[1] - full_domain[0]\n if abs(b-a) < 1e-14*w:\n return 0.0\n n = max(min_n, int(round(n * abs(b-a)/w)))\n value, _ = fixed_quad(func, a=a, b=b, n=n)\n return value\n\n\n@contextmanager\ndef raise_all_warnings():\n r\"\"\"Context manager for turning numpy and native warnings into exceptions.\n\n For example:\n ```\n with raise_all_warnings():\n np.pi / np.linspace(0, 1, 10)\n ```\n Without the `raise_all_warnings()` context, the above code would just\n issue a warning but otherwise run fine. This allows catching the exception\n to act upon it, e.g.\n ```\n with raise_all_warnings():\n try:\n np.pi / np.linspace(0, 1, 10)\n except FloatingPointError:\n print(\"Could not compute.\")\n ```\n \"\"\"\n old_settings = np.seterr(divide='raise', over='raise', invalid='raise')\n try:\n with warnings.catch_warnings():\n warnings.filterwarnings('error', category=IntegrationWarning)\n warnings.filterwarnings('error', category=LinAlgWarning)\n yield\n finally:\n np.seterr(**old_settings)\n","repo_name":"daniel-dpk/distorted-motsfinder-public","sub_path":"motsfinder/numutils.py","file_name":"numutils.py","file_ext":"py","file_size_in_byte":24838,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"40"} +{"seq_id":"31817431300","text":"\"\"\"\nIMAP Library - a IMAP email testing library.\n\"\"\"\nimport base64\nfrom email import message_from_string\nfrom imaplib import IMAP4, IMAP4_SSL\nfrom re import findall\nfrom time import sleep, time\ntry:\n from urllib.request import urlopen\nexcept ImportError:\n from urllib2 import urlopen\nfrom builtins import str\n\n\nclass CustomImapLibrary(object):\n\n PORT = 143\n PORT_SECURE = 993\n FOLDER = 'INBOX'\n ROBOT_LIBRARY_SCOPE = 'GLOBAL'\n\n def __init__(self):\n \"\"\"ImapLibrary can be imported without argument.\n\n Examples:\n | = Keyword Definition = | = Description = |\n | Library `|` ImapLibrary | Initiate Imap library |\n \"\"\"\n self._email_index = None\n self._imap = None\n self._mails = []\n self._mp_iter = None\n self._mp_msg = None\n self._part = None\n\n def close_mailbox(self):\n \"\"\"Close IMAP email client session.\n\n Examples:\n | Close Mailbox |\n \"\"\"\n self._imap.close()\n\n def delete_all_emails(self):\n \"\"\"Delete all emails.\n\n Examples:\n | Delete All Emails |\n \"\"\"\n typ, mails = self._imap.uid('search', None, 'ALL')\n self._mails = mails[0].split()\n\n print(\"Deleting e-mails from ID: [{0}]\".format(', '.join(map(str, self._mails))))\n\n for mail in self._mails:\n self.delete_email(mail)\n self._imap.expunge()\n\n def decode_email_body(self, body_email_encoded):\n \"\"\"Returns the email body encoded on base64 decoded to a string UTF-8.\n\n Arguments:\n - ``body_email_encoded``: An string from the email body encoded on base64.\n\n Examples:\n | BODY | Get Email Body | EMAIL_INDEX |\n | BODYDECODED | Decode Email Body | BODY |\n | Log | BODY |\n \"\"\"\n print(\"Deconding [%s] to string.\" % (body_email_encoded))\n\n if not body_email_encoded.endswith(\"==\"):\n body_email_encoded = body_email_encoded + \"==\"\n\n email_decoded = base64.b64decode(body_email_encoded)\n\n return email_decoded.decode('UTF-8')\n\n def delete_all_emails_with_kwargs(self, **kwargs):\n \"\"\"Delete all emails.\n\n Examples:\n | Delete All Emails |\n \"\"\"\n self._mails = self._check_emails(**kwargs)\n\n for mail in self._mails:\n self.delete_email(mail)\n self._imap.expunge()\n\n def delete_email(self, email_index):\n \"\"\"Delete email on given ``email_index``.\n\n Arguments:\n - ``email_index``: An email index to identity the email message.\n\n Examples:\n | Delete Email | INDEX |\n \"\"\"\n self._imap.uid('store', email_index, '+FLAGS', r'(\\DELETED)')\n self._imap.expunge()\n\n def get_email_body(self, email_index):\n \"\"\"Returns the decoded email body on multipart email message,\n otherwise returns the body text.\n\n Arguments:\n - ``email_index``: An email index to identity the email message.\n\n Examples:\n | Get Email Body | INDEX |\n \"\"\"\n if self._is_walking_multipart(email_index):\n body = self.get_multipart_payload(decode=True)\n else:\n body = self._imap.uid('fetch',\n email_index,\n '(BODY[TEXT])')[1][0][1].\\\n decode('quoted-printable')\n return body\n\n def get_links_from_email(self, email_index):\n \"\"\"Returns all links found in the email body from given ``email_index``.\n\n Arguments:\n - ``email_index``: An email index to identity the email message.\n\n Examples:\n | Get Links From Email | INDEX |\n \"\"\"\n body = self.get_email_body(email_index)\n return findall(r'href=[\\'\"]?([^\\'\" >]+)', body)\n\n def get_matches_from_email(self, email_index, pattern):\n \"\"\"Returns all Regular Expression ``pattern`` found in the email body\n from given ``email_index``.\n\n Arguments:\n - ``email_index``: An email index to identity the email message.\n - ``pattern``: It consists of one or more character literals, operators, or constructs.\n\n Examples:\n | Get Matches From Email | INDEX | PATTERN |\n \"\"\"\n body = self.get_email_body(email_index)\n return findall(pattern, body)\n\n def get_multipart_content_type(self):\n \"\"\"Returns the content type of current part of selected multipart email message.\n\n Examples:\n | Get Multipart Content Type |\n \"\"\"\n return self._part.get_content_type()\n\n def get_multipart_field(self, field):\n \"\"\"Returns the value of given header ``field`` name.\n\n Arguments:\n - ``field``: A header field name: ``From``, ``To``, ``Subject``, ``Date``, etc.\n All available header field names of an email message can be found by running\n `Get Multipart Field Names` keyword.\n\n Examples:\n | Get Multipart Field | Subject |\n \"\"\"\n return self._mp_msg[field]\n\n def get_multipart_field_names(self):\n \"\"\"Returns all available header field names of selected multipart email message.\n\n Examples:\n | Get Multipart Field Names |\n \"\"\"\n return list(self._mp_msg.keys())\n\n def get_multipart_payload(self, decode=False):\n \"\"\"Returns the payload of current part of selected multipart email message.\n\n Arguments:\n - ``decode``: An indicator flag to decode the email message. (Default False)\n\n Examples:\n | Get Multipart Payload |\n | Get Multipart Payload | decode=True |\n \"\"\"\n payload = self._part.get_payload(decode=decode)\n charset = self._part.get_content_charset()\n if charset is not None:\n return payload.decode(charset)\n return payload\n\n def mark_all_emails_as_read(self):\n \"\"\"Mark all received emails as read.\n\n Examples:\n | Mark All Emails As Read |\n \"\"\"\n for mail in self._mails:\n self._imap.uid('store', mail, '+FLAGS', r'\\SEEN')\n\n def mark_as_read(self):\n \"\"\"****DEPRECATED****\n Shortcut to `Mark All Emails As Read`.\n \"\"\"\n self.mark_all_emails_as_read()\n\n def mark_email_as_read(self, email_index):\n \"\"\"Mark email on given ``email_index`` as read.\n\n Arguments:\n - ``email_index``: An email index to identity the email message.\n\n Examples:\n | Mark Email As Read | INDEX |\n \"\"\"\n self._imap.uid('store', email_index, '+FLAGS', r'\\SEEN')\n\n def open_link_from_email(self, email_index, link_index=0):\n \"\"\"Open link URL from given ``link_index`` in email message body of given ``email_index``.\n Returns HTML content of opened link URL.\n\n Arguments:\n - ``email_index``: An email index to identity the email message.\n - ``link_index``: The link index to be open. (Default 0)\n\n Examples:\n | Open Link From Email |\n | Open Link From Email | 1 |\n \"\"\"\n urls = self.get_links_from_email(email_index)\n\n if len(urls) > link_index:\n resp = urlopen(urls[link_index])\n content_type = resp.headers.getheader('content-type')\n if content_type:\n enc = content_type.split('charset=')[-1]\n return str(resp.read(), enc)\n else:\n return resp.read()\n else:\n raise AssertionError(\"Link number %i not found!\" % link_index)\n\n def open_link_from_mail(self, email_index, link_index=0):\n \"\"\"****DEPRECATED****\n Shortcut to `Open Link From Email`.\n \"\"\"\n return self.open_link_from_email(email_index, link_index)\n\n def open_mailbox(self, **kwargs):\n \"\"\"Open IMAP email client session to given ``host`` with given ``user`` and ``password``.\n\n Arguments:\n - ``host``: The IMAP host server. (Default None)\n - ``is_secure``: An indicator flag to connect to IMAP host securely or not. (Default True)\n - ``password``: The plaintext password to be use to authenticate mailbox on given ``host``.\n - ``port``: The IMAP port number. (Default None)\n - ``user``: The username to be use to authenticate mailbox on given ``host``.\n - ``folder``: The email folder to read from. (Default INBOX)\n\n Examples:\n | Open Mailbox | host=HOST | user=USER | password=SECRET |\n | Open Mailbox | host=HOST | user=USER | password=SECRET | is_secure=False |\n | Open Mailbox | host=HOST | user=USER | password=SECRET | port=8000 |\n | Open Mailbox | host=HOST | user=USER | password=SECRET | folder=Drafts\n \"\"\"\n host = kwargs.pop('host', kwargs.pop('server', None))\n is_secure = kwargs.pop('is_secure', 'True') == 'True'\n port = int(kwargs.pop('port', self.PORT_SECURE if is_secure else self.PORT))\n folder = '\"%s\"' % str(kwargs.pop('folder', self.FOLDER))\n self._imap = IMAP4_SSL(host, port) if is_secure else IMAP4(host, port)\n self._imap.login(kwargs.pop('user', None), kwargs.pop('password', None))\n self._imap.select(folder)\n self._init_multipart_walk()\n\n def wait_for_email(self, **kwargs):\n \"\"\"Wait for email message to arrived base on any given filter criteria.\n Returns email index of the latest email message received.\n\n Arguments:\n - ``poll_frequency``: The delay value in seconds to retry the mailbox check. (Default 10)\n - ``recipient``: Email recipient. (Default None)\n - ``sender``: Email sender. (Default None)\n - ``status``: A mailbox status filter: ``MESSAGES``, ``RECENT``, ``UIDNEXT``,\n ``UIDVALIDITY``, and ``UNSEEN``.\n Please see [https://goo.gl/3KKHoY|Mailbox Status] for more information.\n (Default None)\n - ``subject``: Email subject. (Default None)\n - ``text``: Email body text. (Default None)\n - ``timeout``: The maximum value in seconds to wait for email message to arrived.\n (Default 60)\n - ``folder``: The email folder to check for emails. (Default INBOX)\n\n Examples:\n | Wait For Email | sender=noreply@domain.com |\n | Wait For Email | sender=noreply@domain.com | folder=OUTBOX\n \"\"\"\n poll_frequency = float(kwargs.pop('poll_frequency', 10))\n timeout = int(kwargs.pop('timeout', 60))\n end_time = time() + timeout\n while time() < end_time:\n self._mails = self._check_emails(**kwargs)\n if len(self._mails) > 0:\n return self._mails[-1]\n if time() < end_time:\n sleep(poll_frequency)\n raise AssertionError(\"No email received within %ss\" % timeout)\n\n def wait_for_mail(self, **kwargs):\n \"\"\"****DEPRECATED****\n Shortcut to `Wait For Email`.\n \"\"\"\n return self.wait_for_email(**kwargs)\n\n def walk_multipart_email(self, email_index):\n \"\"\"Returns total parts of a multipart email message on given ``email_index``.\n Email message is cache internally to be used by other multipart keywords:\n `Get Multipart Content Type`, `Get Multipart Field`, `Get Multipart Field Names`,\n `Get Multipart Field`, and `Get Multipart Payload`.\n\n Arguments:\n - ``email_index``: An email index to identity the email message.\n\n Examples:\n | Walk Multipart Email | INDEX |\n \"\"\"\n if not self._is_walking_multipart(email_index):\n data = self._imap.uid('fetch', email_index, '(RFC822)')[1][0][1]\n msg = message_from_string(data)\n self._start_multipart_walk(email_index, msg)\n try:\n self._part = next(self._mp_iter)\n except StopIteration:\n self._init_multipart_walk()\n return False\n # return number of parts\n return len(self._mp_msg.get_payload())\n\n def _check_emails(self, **kwargs):\n \"\"\"Returns filtered email.\"\"\"\n folder = '\"%s\"' % str(kwargs.pop('folder', self.FOLDER))\n criteria = self._criteria(**kwargs)\n # Calling select before each search is necessary with gmail\n status, data = self._imap.select(folder)\n if status != 'OK':\n raise Exception(\"imap.select error: %s, %s\" % (status, data))\n typ, msgnums = self._imap.uid('search', None, *criteria)\n if typ != 'OK':\n raise Exception('imap.search error: %s, %s, criteria=%s' % (typ, msgnums, criteria))\n return msgnums[0].split()\n\n @staticmethod\n def _criteria(**kwargs):\n \"\"\"Returns email criteria.\"\"\"\n criteria = []\n recipient = kwargs.pop('recipient', kwargs.pop('to_email', kwargs.pop('toEmail', None)))\n sender = kwargs.pop('sender', kwargs.pop('from_email', kwargs.pop('fromEmail', None)))\n status = kwargs.pop('status', None)\n subject = kwargs.pop('subject', None)\n text = kwargs.pop('text', None)\n if recipient:\n criteria += ['TO', '\"%s\"' % recipient]\n if sender:\n criteria += ['FROM', '\"%s\"' % sender]\n if subject:\n criteria += ['SUBJECT', '\"%s\"' % subject]\n if text:\n criteria += ['TEXT', '\"%s\"' % text]\n if status:\n criteria += [status]\n if not criteria:\n criteria = ['UNSEEN']\n return criteria\n\n def _init_multipart_walk(self):\n \"\"\"Initialize multipart email walk.\"\"\"\n self._email_index = None\n self._mp_msg = None\n self._part = None\n\n def _is_walking_multipart(self, email_index):\n \"\"\"Returns boolean value whether the multipart email walk is in-progress or not.\"\"\"\n return self._mp_msg is not None and self._email_index == email_index\n\n def _start_multipart_walk(self, email_index, msg):\n \"\"\"Start multipart email walk.\"\"\"\n self._email_index = email_index\n self._mp_msg = msg\n self._mp_iter = msg.walk()\n","repo_name":"mayribeirofernandes/testesrobotframework","sub_path":"Exemplo Imap Library/CustomImapLibrary.py","file_name":"CustomImapLibrary.py","file_ext":"py","file_size_in_byte":14089,"program_lang":"python","lang":"en","doc_type":"code","stars":76,"dataset":"github-code","pt":"40"} +{"seq_id":"32044682345","text":"import time\nimport os\nimport csv\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException\n\n\ndirpath = os.getcwd()\nfilepath = dirpath + r'\\SeleniumDrivers\\chromedriver.exe'\n\ndriver = webdriver.Chrome(filepath) \ndriver.get('https://csc.gov.ph/career/index.php');\n# driver.implicitly_wait(30)\n\n\n\ntry: \n\n # dismiss initial popup\n element_popup = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/div[4]/button/span')))\n element_popup.click()\n # set header\n header = ['Agency', 'Region', 'Position Title', 'Plantilla', 'Posting Date', 'Closing Date', 'Details']\n\n with open('data/jobs.csv', mode='a', newline='') as jobs_file:\n jobs_writer = csv.writer(jobs_file, delimiter=',')\n # write header as first row\n jobs_writer.writerow(header)\n\n\n # set the number of pages\n total_pages = 10 \n for i in range(total_pages):\n page = i+1\n print(f\"Page: {page}\")\n \n # find table where job listings are posted\n jobs_table = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.TAG_NAME, 'tbody')))\n\n # loop through each job posting to extract data\n jobs = jobs_table.find_elements(By.TAG_NAME, \"tr\")\n \n for job in jobs:\n \n agency = job.find_elements(By.TAG_NAME, \"td\")[0].text.strip()\n print(agency)\n\n region = job.find_elements(By.TAG_NAME, \"td\")[1].text.strip()\n print(region)\n \n position_title = job.find_elements(By.TAG_NAME, \"td\")[2].text.strip()\n print(position_title)\n \n plantilla = job.find_elements(By.TAG_NAME, \"td\")[3].text.strip()\n print(plantilla)\n \n posting_date = job.find_elements(By.TAG_NAME, \"td\")[4].text.strip()\n print(posting_date)\n \n closing_date = job.find_elements(By.TAG_NAME, \"td\")[5].text.strip()\n print(closing_date)\n \n # details = job.find_elements(By.TAG_NAME, \"td\")[6].text\n details_button = job.find_elements(By.XPATH, \".//button[contains(text(), 'Details')]\")[0]\n details_button.click()\n time.sleep(5)\n driver.switch_to.window(driver.window_handles[1])\n details_url = driver.current_url\n print(details_url)\n driver.close()\n driver.switch_to.window(driver.window_handles[0])\n time.sleep(5)\n \n print(\"#############\")\n \n # write each row of data to file\n jobs_writer.writerow([agency, region, position_title, plantilla, posting_date, closing_date, details_url])\n \n # locate next button\n next_btn = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.XPATH, '//*[@id=\"jobs_next\"]')))\n\n # click next button to proceed to next page until reached last page \n if page < total_pages: \n next_btn.click()\n time.sleep(10)\n else:\n print(\"Done scraping..\")\n \nexcept Exception as e:\n print(\"Failed to scrape.\")\n print(e)\n \nfinally:\n print(\"Quitting scraper..\")\n time.sleep(5)\n driver.quit()","repo_name":"rachemelendres/webscraping-selenium","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"44575719165","text":"import numpy as np\nfrom ase.io import *\nfrom ase.data import covalent_radii\nfrom ase.units import Bohr\nimport random\nfrom qpac.data import atomic_numbers\nfrom dscribe.descriptors import SOAP\n\nnp.random.seed(10)\n\n\nclass soapClass():\n def __init__(self):\n self.precomputed = {\"training\":[]}\n self.precomputedEl = {\"training\":[]}\n\n def compute(self,mols,name):\n soaps = self.descriptor_atoms(mols)\n self.precomputed[name] = soaps[0]\n self.precomputedEl[name] = soaps[1]\n\n def saveSOAP(self,name,nameSave):\n np.save(nameSave,self.precomputed[name])\n np.save(f'El{nameSave}',self.precomputedEl[name])\n \n def loadSOAP(self,name,nameSave):\n self.precomputed[name] = np.load(nameSave)\n self.precomputedEl[name] = np.load(f'El{nameSave}')\n\n def descriptor_atoms(mols):\n raise NotImplementedError\n\nclass dscribeSOAP(soapClass):\n def __init__(self, nmax, lmax,rcut, sigma,species,periodic):\n self.species = species\n self.soap = SOAP(\n periodic=periodic,\n r_cut=rcut, \n n_max=nmax,\n sigma=sigma,\n species = species,\n l_max=lmax)\n super().__init__()\n\n\n\n def descriptor_atoms(self,molecules,n_jobs=1):\n soap_atoms = []\n element_list = []\n soaps_new = self.soap.create(molecules,n_jobs = n_jobs)\n if len(molecules) == 1:\n soaps_new = [soaps_new]\n for ids,m in enumerate(soaps_new):\n element_list.extend([a.symbol for a in molecules[ids]])\n norms = np.linalg.norm(m,axis=-1)\n soap_atoms.extend(m/norms[:,None])\n return np.array(soap_atoms), np.array(element_list)\n\n \n def _descr_deriv_atoms(self,molecule, deriv = \"numerical\"):\n der, desc = self.soap.derivatives(molecule,method=deriv,attach=True) #analytical derivatives in SOAPs are not usable with 1.2.0 version '''\n element_list = []\n element_list.extend([a.symbol for a in molecule])\n element_list = np.array(element_list)\n norms = np.linalg.norm(desc,axis=-1)\n norm_desc = desc/norms[:,None]\n norms2 = norms**2\n deriv_final = np.moveaxis(der,[0,1],[2,0])\n # normal_soap_vector = np.array(normal_soap_vector)\n hold = (np.einsum('ij,arkj->arik',desc,deriv_final,optimize=\"greedy\"))\n vd = np.einsum('akii->aki',hold,optimize=\"greedy\")\n r1 = np.einsum('akl,lj,l->aklj',vd,desc,1/norms,optimize=\"greedy\")\n f1 = np.einsum('aklj,l->aklj',deriv_final,norms,optimize=\"greedy\")\n normDer = np.einsum('aklj,l->aklj',f1-r1,1/norms2,optimize=\"greedy\")\n \n return norm_desc, normDer, element_list\n\n","repo_name":"VondrakMar/GAP-Jax","sub_path":"descriptors.py","file_name":"descriptors.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"1532472403","text":"import torch\nimport torch.nn as nn\nfrom torch.nn import init\nimport functools\nfrom torch.autograd import Variable\nfrom torch.optim import lr_scheduler\n\nfrom .spectral import SpectralNorm\n\n###############################################################################\n# Functions\n###############################################################################\n\n\ndef weights_init_normal(m):\n classname = m.__class__.__name__\n # print(classname)\n if classname.find('Conv') != -1:\n try:\n init.normal(m.weight.data, 0.0, 0.02)\n except AttributeError:\n init.normal(m.weight_bar.data, 0.0, 0.02)\n init.normal(m.weight_u.data, 0.0, 0.02)\n init.normal(m.weight_v.data, 0.0, 0.02)\n elif classname.find('Linear') != -1:\n init.normal(m.weight.data, 0.0, 0.02)\n elif classname.find('BatchNorm2d') != -1:\n init.normal(m.weight.data, 1.0, 0.02)\n init.constant(m.bias.data, 0.0)\n\n\ndef weights_init_xavier(m):\n classname = m.__class__.__name__\n # print(classname)\n if classname.find('Conv') != -1:\n try:\n init.xavier_normal(m.weight.data, gain=0.02)\n except AttributeError:\n init.xavier_normal(m.weight_bar.data, gain=0.02)\n init.xavier_normal(m.weight_u.data, gain=0.02)\n init.xavier_normal(m.weight_v.data, gain=0.02)\n elif classname.find('Linear') != -1:\n init.xavier_normal(m.weight.data, gain=0.02)\n elif classname.find('BatchNorm2d') != -1:\n init.normal(m.weight.data, 1.0, 0.02)\n init.constant(m.bias.data, 0.0)\n\n\ndef weights_init_kaiming(m):\n classname = m.__class__.__name__\n # print(classname)\n if classname.find('Conv') != -1:\n try:\n init.kaiming_normal(m.weight.data, a=0, mode='fan_in')\n except AttributeError:\n init.kaiming_normal(m.weight_bar.data, a=0, mode='fan_in')\n init.kaiming_normal(m.weight_u.data, a=0, mode='fan_in')\n init.kaiming_normal(m.weight_v.data, a=0, mode='fan_in')\n elif classname.find('Linear') != -1:\n init.kaiming_normal(m.weight.data, a=0, mode='fan_in')\n elif classname.find('BatchNorm2d') != -1:\n init.normal(m.weight.data, 1.0, 0.02)\n init.constant(m.bias.data, 0.0)\n\n\ndef weights_init_orthogonal(m):\n classname = m.__class__.__name__\n # print(classname)\n if classname.find('Conv') != -1:\n try:\n init.orthogonal(m.weight.data, gain=1)\n except AttributeError:\n weights_init_normal(m)\n elif classname.find('Linear') != -1:\n init.orthogonal(m.weight.data, gain=1)\n elif classname.find('BatchNorm2d') != -1:\n init.normal(m.weight.data, 1.0, 0.02)\n init.constant(m.bias.data, 0.0)\n\n\ndef init_weights(net, init_type='normal'):\n print('initialization method [%s]' % init_type)\n if init_type == 'normal':\n net.apply(weights_init_normal)\n elif init_type == 'xavier':\n net.apply(weights_init_xavier)\n elif init_type == 'kaiming':\n net.apply(weights_init_kaiming)\n elif init_type == 'orthogonal':\n net.apply(weights_init_orthogonal)\n else:\n raise NotImplementedError('initialization method [%s] is not implemented' % init_type)\n\n\ndef get_norm_layer(norm_type='instance'):\n if norm_type == 'batch':\n norm_layer = functools.partial(nn.BatchNorm2d, affine=True)\n elif norm_type == 'instance':\n norm_layer = functools.partial(nn.InstanceNorm2d, affine=False)\n elif norm_type == 'none':\n norm_layer = None\n else:\n raise NotImplementedError('normalization layer [%s] is not found' % norm_type)\n return norm_layer\n\n\ndef get_scheduler(optimizer, opt):\n if opt.lr_policy == 'lambda':\n def lambda_rule(epoch):\n # epoch = current epoch number, opt.epoch_count = starting epoch, opt.niter = num iterations at original lr\n # opt.niter_decay = num iterations to linearly decay over\n # So once total number of epochs (including those we skipped if we didn't start from zero) is greater than\n # opt.niter, start decaying\n # I'm not sure that +1 should be there in the denominator\n lr_l = 1.0 - max(0, epoch + 1 + opt.epoch_count - opt.niter) / float(opt.niter_decay + 1)\n return lr_l\n scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule)\n elif opt.lr_policy == 'step':\n scheduler = lr_scheduler.StepLR(optimizer, step_size=opt.lr_decay_iters, gamma=0.1)\n elif opt.lr_policy == 'plateau':\n scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.2, threshold=0.01, patience=5)\n else:\n return NotImplementedError('learning rate policy [%s] is not implemented', opt.lr_policy)\n return scheduler\n\n\ndef define_G(input_nc, output_nc, ngf, which_model_netG, norm='batch', use_dropout=False, init_type='normal', gpu_ids=[]):\n netG = None\n use_gpu = len(gpu_ids) > 0\n norm_layer = get_norm_layer(norm_type=norm)\n\n if use_gpu:\n assert(torch.cuda.is_available())\n\n if which_model_netG == 'resnet_9blocks':\n netG = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=9, gpu_ids=gpu_ids)\n elif which_model_netG == 'resnet_6blocks':\n netG = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=6, gpu_ids=gpu_ids)\n elif which_model_netG == 'unet_128':\n netG = UnetGenerator(input_nc, output_nc, 7, ngf, norm_layer=norm_layer, use_dropout=use_dropout, gpu_ids=gpu_ids)\n elif which_model_netG == 'unet_256':\n netG = UnetGenerator(input_nc, output_nc, 8, ngf, norm_layer=norm_layer, use_dropout=use_dropout, gpu_ids=gpu_ids)\n elif which_model_netG == 'unet_128_self_attn':\n netG = UnetGeneratorSelfAttn(input_nc, output_nc, 7, ngf, norm_layer=norm_layer, use_dropout=use_dropout, gpu_ids=gpu_ids)\n elif which_model_netG == 'unet_256_self_attn':\n netG = UnetGeneratorSelfAttn(input_nc, output_nc, 8, ngf, norm_layer=norm_layer, use_dropout=use_dropout, gpu_ids=gpu_ids)\n else:\n raise NotImplementedError('Generator model name [%s] is not recognized' % which_model_netG)\n if len(gpu_ids) > 0:\n netG.cuda(gpu_ids[0])\n init_weights(netG, init_type=init_type)\n return netG\n\n\ndef define_D(input_nc, ndf, which_model_netD,\n n_layers_D=3, norm='batch', use_sigmoid=False, init_type='normal', gpu_ids=[], **kwargs):\n\n netD = None\n use_gpu = len(gpu_ids) > 0\n norm_layer = get_norm_layer(norm_type=norm)\n\n if use_gpu:\n assert(torch.cuda.is_available())\n if which_model_netD == 'basic':\n netD = NLayerDiscriminator(input_nc, ndf, n_layers=3, norm_layer=norm_layer, use_sigmoid=use_sigmoid, gpu_ids=gpu_ids)\n elif which_model_netD == 'n_layers':\n netD = NLayerDiscriminator(input_nc, ndf, n_layers_D, norm_layer=norm_layer, use_sigmoid=use_sigmoid, gpu_ids=gpu_ids, leaky_param=kwargs['leaky_param'])\n elif which_model_netD == 'n_layers_no_norm':\n netD = NLayerDiscriminatorNoNorm(input_nc, ndf, n_layers_D, norm_layer=norm_layer, use_sigmoid=use_sigmoid, gpu_ids=gpu_ids, leaky_param=kwargs['leaky_param'])\n elif which_model_netD == 'pixel':\n netD = PixelDiscriminator(input_nc, ndf, norm_layer=norm_layer, use_sigmoid=use_sigmoid, gpu_ids=gpu_ids)\n elif which_model_netD == 'wgan-gp':\n netD = DiscriminatorWGANGP(input_nc, kwargs['critic_im_size'], dim=ndf, gpu_ids=[])\n elif which_model_netD == 'self-attn':\n netD = SelfAttnDiscriminator(input_nc, kwargs['critic_im_size'][0], conv_dim=ndf, gpu_ids=[])\n elif which_model_netD == 'spec-norm':\n netD = SpecNormDiscriminator(input_nc, kwargs['critic_im_size'][0], conv_dim=ndf, gpu_ids=gpu_ids)\n else:\n raise NotImplementedError('Discriminator model name [%s] is not recognized' %\n which_model_netD)\n if use_gpu:\n netD.cuda(gpu_ids[0])\n init_weights(netD, init_type=init_type)\n return netD\n\n\ndef print_network(net):\n num_params = 0\n for param in net.parameters():\n num_params += param.numel()\n print(net)\n print('Total number of parameters: %d' % num_params)\n\n\n##############################################################################\n# Classes\n##############################################################################\n\n\n# Defines the GAN loss which uses either LSGAN or the regular GAN.\n# When LSGAN is used, it is basically same as MSELoss,\n# but it abstracts away the need to create the target label tensor\n# that has the same size as the input\n# So discriminators just give pixel by pixel test result?\nclass GANLoss(nn.Module):\n def __init__(self, use_lsgan=True, target_real_label=1.0, target_fake_label=0.0,\n tensor=torch.FloatTensor):\n super(GANLoss, self).__init__()\n self.real_label = target_real_label\n self.fake_label = target_fake_label\n self.real_label_var = None\n self.fake_label_var = None\n self.Tensor = tensor\n if use_lsgan:\n self.loss = nn.MSELoss()\n else:\n self.loss = nn.BCELoss()\n\n def get_target_tensor(self, input, target_is_real):\n target_tensor = None\n if target_is_real:\n create_label = ((self.real_label_var is None) or\n (self.real_label_var.numel() != input.numel()))\n if create_label:\n real_tensor = self.Tensor(input.size()).fill_(self.real_label)\n self.real_label_var = Variable(real_tensor, requires_grad=False)\n target_tensor = self.real_label_var\n else:\n create_label = ((self.fake_label_var is None) or\n (self.fake_label_var.numel() != input.numel()))\n if create_label:\n fake_tensor = self.Tensor(input.size()).fill_(self.fake_label)\n self.fake_label_var = Variable(fake_tensor, requires_grad=False)\n target_tensor = self.fake_label_var\n return target_tensor\n\n def __call__(self, input, target_is_real):\n target_tensor = self.get_target_tensor(input, target_is_real)\n return self.loss(input, target_tensor)\n\n\n# Defines the generator that consists of Resnet blocks between a few\n# downsampling/upsampling operations.\n# Code and idea originally from Justin Johnson's architecture.\n# https://github.com/jcjohnson/fast-neural-style/\nclass ResnetGenerator(nn.Module):\n def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=6, gpu_ids=[], padding_type='reflect'):\n assert(n_blocks >= 0)\n super(ResnetGenerator, self).__init__()\n self.input_nc = input_nc\n self.output_nc = output_nc\n self.ngf = ngf\n self.gpu_ids = gpu_ids\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n\n model = [nn.ReflectionPad2d(3),\n nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0,\n bias=use_bias),\n norm_layer(ngf),\n nn.ReLU(True)]\n\n n_downsampling = 2\n for i in range(n_downsampling):\n mult = 2**i\n model += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3,\n stride=2, padding=1, bias=use_bias),\n norm_layer(ngf * mult * 2),\n nn.ReLU(True)]\n\n mult = 2**n_downsampling\n for i in range(n_blocks):\n model += [ResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer, use_dropout=use_dropout, use_bias=use_bias)]\n\n for i in range(n_downsampling):\n mult = 2**(n_downsampling - i)\n model += [nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2),\n kernel_size=3, stride=2,\n padding=1, output_padding=1,\n bias=use_bias),\n norm_layer(int(ngf * mult / 2)),\n nn.ReLU(True)]\n model += [nn.ReflectionPad2d(3)]\n model += [nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)]\n model += [nn.Tanh()]\n\n self.model = nn.Sequential(*model)\n\n def forward(self, input):\n if self.gpu_ids and isinstance(input.data, torch.cuda.FloatTensor):\n return nn.parallel.data_parallel(self.model, input, self.gpu_ids)\n else:\n return self.model(input)\n\n\n# Define a resnet block\nclass ResnetBlock(nn.Module):\n def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias):\n super(ResnetBlock, self).__init__()\n self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, use_dropout, use_bias)\n\n def build_conv_block(self, dim, padding_type, norm_layer, use_dropout, use_bias):\n conv_block = []\n p = 0\n if padding_type == 'reflect':\n conv_block += [nn.ReflectionPad2d(1)]\n elif padding_type == 'replicate':\n conv_block += [nn.ReplicationPad2d(1)]\n elif padding_type == 'zero':\n p = 1\n else:\n raise NotImplementedError('padding [%s] is not implemented' % padding_type)\n\n conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias),\n norm_layer(dim),\n nn.ReLU(True)]\n if use_dropout:\n conv_block += [nn.Dropout(0.5)]\n\n p = 0\n if padding_type == 'reflect':\n conv_block += [nn.ReflectionPad2d(1)]\n elif padding_type == 'replicate':\n conv_block += [nn.ReplicationPad2d(1)]\n elif padding_type == 'zero':\n p = 1\n else:\n raise NotImplementedError('padding [%s] is not implemented' % padding_type)\n conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias),\n norm_layer(dim)]\n\n return nn.Sequential(*conv_block)\n\n def forward(self, x):\n out = x + self.conv_block(x)\n return out\n\n\n# Defines the Unet generator.\n# |num_downs|: number of downsamplings in UNet. For example,\n# if |num_downs| == 7, image of size 128x128 will become of size 1x1\n# at the bottleneck\nclass UnetGenerator(nn.Module):\n def __init__(self, input_nc, output_nc, num_downs, ngf=64,\n norm_layer=nn.BatchNorm2d, use_dropout=False, gpu_ids=[]):\n super(UnetGenerator, self).__init__()\n self.gpu_ids = gpu_ids\n\n # construct unet structure\n unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True)\n for i in range(num_downs - 5):\n unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer, use_dropout=use_dropout)\n unet_block = UnetSkipConnectionBlock(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n unet_block = UnetSkipConnectionBlock(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n unet_block = UnetSkipConnectionBlock(output_nc, ngf, input_nc=input_nc, submodule=unet_block, outermost=True, norm_layer=norm_layer)\n\n self.model = unet_block\n\n def forward(self, input):\n if self.gpu_ids and isinstance(input.data, torch.cuda.FloatTensor):\n return nn.parallel.data_parallel(self.model, input, self.gpu_ids)\n else:\n return self.model(input)\n\n# Defines the Unet generator with non-local blocks.\n# |num_downs|: number of downsamplings in UNet. For example,\n# if |num_downs| == 7, image of size 128x128 will become of size 1x1\n# at the bottleneck\nclass UnetGeneratorSelfAttn(nn.Module):\n def __init__(self, input_nc, output_nc, num_downs, ngf=64,\n norm_layer=nn.BatchNorm2d, use_dropout=False, gpu_ids=[]):\n super(UnetGeneratorSelfAttn, self).__init__()\n self.gpu_ids = gpu_ids\n\n # construct unet structure\n unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True)\n for i in range(num_downs - 5):\n unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer, use_dropout=use_dropout, self_attention=(i % 2 == 0))\n unet_block = UnetSkipConnectionBlock(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer, self_attention=False)\n unet_block = UnetSkipConnectionBlock(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block, norm_layer=norm_layer, self_attention=True)\n unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n unet_block = UnetSkipConnectionBlock(output_nc, ngf, input_nc=input_nc, submodule=unet_block, outermost=True, norm_layer=norm_layer)\n\n self.model = unet_block\n\n def forward(self, input):\n if self.gpu_ids and isinstance(input.data, torch.cuda.FloatTensor):\n return nn.parallel.data_parallel(self.model, input, self.gpu_ids)\n else:\n return self.model(input)\n\n\n# Defines the submodule with skip connection.\n# X -------------------identity---------------------- X\n# |-- downsampling -- |submodule| -- upsampling --|\nclass UnetSkipConnectionBlock(nn.Module):\n def __init__(self, outer_nc, inner_nc, input_nc=None,\n submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False,\n self_attention=False):\n super(UnetSkipConnectionBlock, self).__init__()\n self.outermost = outermost\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n if input_nc is None:\n input_nc = outer_nc\n downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=4,\n stride=2, padding=1, bias=use_bias)\n if self_attention:\n downconv = SpectralNorm(downconv)\n downrelu = nn.LeakyReLU(0.2, True)\n downnorm = norm_layer(inner_nc)\n uprelu = nn.ReLU(True)\n upnorm = norm_layer(outer_nc)\n\n if outermost:\n upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,\n kernel_size=4, stride=2,\n padding=1)\n if self_attention:\n upconv = SpectralNorm(upconv)\n down = [downconv]\n up = [uprelu, upconv, nn.Tanh()]\n model = down + [submodule] + up\n elif innermost:\n upconv = nn.ConvTranspose2d(inner_nc, outer_nc,\n kernel_size=4, stride=2,\n padding=1, bias=use_bias)\n if self_attention:\n upconv = SpectralNorm(upconv)\n down = [downrelu, downconv]\n up = [uprelu, upconv, upnorm]\n model = down + up\n else:\n upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,\n kernel_size=4, stride=2,\n padding=1, bias=use_bias)\n if self_attention:\n upconv = SpectralNorm(upconv)\n down = [downrelu, downconv, downnorm]\n\n up = [uprelu, upconv, upnorm]\n\n if self_attention:\n down += [Self_Attn(inner_nc, 'dummy')]\n up += [Self_Attn(outer_nc, 'dummy')]\n\n if use_dropout:\n model = down + [submodule] + up + [nn.Dropout(0.5)]\n else:\n model = down + [submodule] + up\n\n self.model = nn.Sequential(*model)\n\n def forward(self, x):\n if self.outermost:\n return self.model(x)\n else:\n return torch.cat([x, self.model(x)], 1)\n\n\n# Defines the PatchGAN discriminator with the specified arguments.\nclass NLayerDiscriminator(nn.Module):\n def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d, use_sigmoid=False, gpu_ids=[], leaky_param=0.2):\n super(NLayerDiscriminator, self).__init__()\n\n self.gpu_ids = gpu_ids\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n\n kw = 4\n padw = 1\n sequence = [\n nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw),\n nn.LeakyReLU(leaky_param, True)\n ]\n\n nf_mult = 1\n nf_mult_prev = 1\n for n in range(1, n_layers):\n nf_mult_prev = nf_mult\n nf_mult = min(2**n, 8)\n sequence += [\n nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult,\n kernel_size=kw, stride=2, padding=padw, bias=use_bias)]\n\n # Its possible that we don't need to break out like this, the code might just handle it\n # There's already a 'None' norm layer option above\n # Sequential definitely doesn't handle it on it's own\n if norm_layer:\n sequence += [norm_layer(ndf * nf_mult)]\n\n sequence += [\n nn.LeakyReLU(leaky_param, True)\n ]\n\n nf_mult_prev = nf_mult\n nf_mult = min(2**n_layers, 8)\n sequence += [\n nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult,\n kernel_size=kw, stride=2, padding=padw, bias=use_bias)]\n\n if norm_layer:\n sequence += [norm_layer(ndf * nf_mult)]\n\n sequence += [\n nn.LeakyReLU(leaky_param, True)\n ]\n\n sequence += [nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)]\n\n if use_sigmoid:\n sequence += [nn.Sigmoid()]\n\n self.model = nn.Sequential(*sequence)\n\n def forward(self, input):\n if len(self.gpu_ids) and isinstance(input.data, torch.cuda.FloatTensor):\n out = nn.parallel.data_parallel(self.model, input, self.gpu_ids)\n else:\n out = self.model(input)\n\n # GAP\n out = out.view(x.shape[0], 1, -1).mean(dim=2)\n\n return out\n\nclass NLayerDiscriminatorNoNorm(nn.Module):\n def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=None, use_sigmoid=False, gpu_ids=[], leaky_param=0.1):\n super(NLayerDiscriminatorNoNorm, self).__init__()\n\n self.gpu_ids = gpu_ids\n \n kw = 4\n padw = 1\n sequence = [\n nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw),\n nn.LeakyReLU(leaky_param, True)\n ]\n\n nf_mult = 1\n nf_mult_prev = 1\n for n in range(1, n_layers):\n nf_mult_prev = nf_mult\n nf_mult = min(2**n, 8)\n sequence += [\n nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult,\n kernel_size=kw, stride=2, padding=padw, bias=True)]\n\n sequence += [\n nn.LeakyReLU(leaky_param, True)\n ]\n\n nf_mult_prev = nf_mult\n nf_mult = min(2**n_layers, 8)\n sequence += [\n nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult,\n kernel_size=kw, stride=2, padding=padw, bias=True)]\n\n sequence += [\n nn.LeakyReLU(leaky_param, True)\n ]\n\n sequence += [nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=2, padding=padw)]\n\n self.model = nn.Sequential(*sequence)\n\n def forward(self, input):\n if len(self.gpu_ids) and isinstance(input.data, torch.cuda.FloatTensor):\n out = nn.parallel.data_parallel(self.model, input, self.gpu_ids)\n else:\n out = self.model(input)\n\n # GAP\n out = out.view(input.shape[0], 1, -1).mean(dim=2)\n\n return out\n\nclass DiscriminatorWGANGP(torch.nn.Module):\n def __init__(self, in_dim, image_dims, dim=64, gpu_ids=[]):\n super(DiscriminatorWGANGP, self).__init__()\n\n self.gpu_ids = gpu_ids\n\n def conv_ln_lrelu(in_dim, out_dim):\n return torch.nn.Sequential(\n torch.nn.Conv2d(in_dim, out_dim, 5, 2, 2),\n # Since there is no effective implementation of LayerNorm,\n # we use InstanceNorm2d instead of LayerNorm here.\n # Gulrajanis code uses TensorFlow batch normalisation\n torch.nn.InstanceNorm2d(out_dim, affine=True),\n torch.nn.LeakyReLU(0.2))\n\n self.ls = torch.nn.Sequential(\n torch.nn.Conv2d(in_dim, dim, 5, 2, 2), torch.nn.LeakyReLU(0.2), # (b, c, x, y) -> (b, dim, x/2, y/2)\n conv_ln_lrelu(dim, dim * 2), # (b, dim, x/2, y/2) -> (b, dim*2, x/4, y/4)\n conv_ln_lrelu(dim * 2, dim * 4), # (b, dim*2, x/4, y/4) -> (b, dim*4, x/8, y/8)\n conv_ln_lrelu(dim * 4, dim * 8), # (b, dim*4, x/8, y/8) -> (b, dim*8, x/16, y/16)\n torch.nn.Conv2d(dim * 8, 1, \n (int(image_dims[0]/16 + 0.5), int(image_dims[1]/16 + 0.5)))) # (b, dim*8, x/16, y/16) -> (b, 1, 1, 1)\n\n\n def forward(self, x):\n if len(self.gpu_ids) and isinstance(input.data, torch.cuda.FloatTensor):\n return nn.parallel.data_parallel(self.ls, x, self.gpu_ids).view(-1)\n else:\n return self.ls(x).view(-1)\n\n\nclass PixelDiscriminator(nn.Module):\n def __init__(self, input_nc, ndf=64, norm_layer=nn.BatchNorm2d, use_sigmoid=False, gpu_ids=[]):\n super(PixelDiscriminator, self).__init__()\n self.gpu_ids = gpu_ids\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n\n self.net = [\n nn.Conv2d(input_nc, ndf, kernel_size=1, stride=1, padding=0),\n nn.LeakyReLU(0.2, True),\n nn.Conv2d(ndf, ndf * 2, kernel_size=1, stride=1, padding=0, bias=use_bias),\n norm_layer(ndf * 2),\n nn.LeakyReLU(0.2, True),\n nn.Conv2d(ndf * 2, 1, kernel_size=1, stride=1, padding=0, bias=use_bias)]\n\n if use_sigmoid:\n self.net.append(nn.Sigmoid())\n\n self.net = nn.Sequential(*self.net)\n\n def forward(self, input):\n if len(self.gpu_ids) and isinstance(input.data, torch.cuda.FloatTensor):\n return nn.parallel.data_parallel(self.net, input, self.gpu_ids)\n else:\n return self.net(input)\n\nclass Self_Attn(nn.Module):\n \"\"\" Self attention Layer\"\"\"\n def __init__(self,in_dim,activation):\n super(Self_Attn,self).__init__()\n self.chanel_in = in_dim\n self.activation = activation\n \n self.query_conv = nn.Conv2d(in_channels = in_dim , out_channels = in_dim//8 , kernel_size= 1)\n self.key_conv = nn.Conv2d(in_channels = in_dim , out_channels = in_dim//8 , kernel_size= 1)\n self.value_conv = nn.Conv2d(in_channels = in_dim , out_channels = in_dim , kernel_size= 1)\n self.gamma = nn.Parameter(torch.zeros(1))\n\n self.softmax = nn.Softmax(dim=-1) #\n def forward(self,x):\n \"\"\"\n inputs :\n x : input feature maps( B X C X W X H)\n returns :\n out : self attention value + input feature \n attention: B X N X N (N is Width*Height)\n \"\"\"\n m_batchsize,C,width ,height = x.size()\n proj_query = self.query_conv(x).view(m_batchsize,-1,width*height).permute(0,2,1) # B X CX(N)\n proj_key = self.key_conv(x).view(m_batchsize,-1,width*height) # B X C x (*W*H)\n energy = torch.bmm(proj_query,proj_key) # transpose check\n attention = self.softmax(energy) # BX (N) X (N) \n proj_value = self.value_conv(x).view(m_batchsize,-1,width*height) # B X C X N\n\n out = torch.bmm(proj_value,attention.permute(0,2,1) )\n out = out.view(m_batchsize,C,width,height)\n \n out = self.gamma*out + x\n return out\n\n\nclass SelfAttnDiscriminator(nn.Module):\n \"\"\"Discriminator, Auxiliary Classifier.\"\"\"\n\n def __init__(self, input_nc, image_size=64, conv_dim=64, gpu_ids=[]):\n super(SelfAttnDiscriminator, self).__init__()\n self.imsize = image_size\n\n self.gpu_ids = gpu_ids\n\n layer1 = []\n layer2 = []\n layer3 = []\n last = []\n\n layer1.append(SpectralNorm(nn.Conv2d(input_nc, conv_dim, 4, 2, 1)))\n layer1.append(nn.LeakyReLU(0.1))\n\n curr_dim = conv_dim\n\n layer2.append(SpectralNorm(nn.Conv2d(curr_dim, curr_dim * 2, 4, 2, 1)))\n layer2.append(nn.LeakyReLU(0.1))\n curr_dim = curr_dim * 2\n\n layer3.append(SpectralNorm(nn.Conv2d(curr_dim, curr_dim * 2, 4, 2, 1)))\n layer3.append(nn.LeakyReLU(0.1))\n curr_dim = curr_dim * 2\n\n if self.imsize >= 64:\n layer4 = []\n layer4.append(SpectralNorm(nn.Conv2d(curr_dim, curr_dim * 2, 4, 2, 1)))\n layer4.append(nn.LeakyReLU(0.1))\n self.l4 = nn.Sequential(*layer4)\n curr_dim = curr_dim*2\n self.l1 = nn.Sequential(*layer1)\n self.l2 = nn.Sequential(*layer2)\n self.l3 = nn.Sequential(*layer3)\n\n last.append(nn.Conv2d(curr_dim, 1, 4, 2, 1))\n self.last = nn.Sequential(*last)\n\n self.attn1 = Self_Attn(256, 'relu')\n self.attn2 = Self_Attn(512, 'relu')\n\n out_dim = int(self.imsize / (2*2*2*2*2))\n\n\n def forward(self, x):\n out = self.l1(x)\n out = self.l2(out)\n out = self.l3(out)\n out = self.attn1(out)\n out=self.l4(out)\n out = self.attn2(out)\n out=self.last(out)\n\n # GAP\n out = out.view(x.shape[0], 1, -1).mean(dim=2)\n\n #self.attn1 = p1\n #self.attn2 = p2\n\n return out\n\nclass SpecNormDiscriminator(nn.Module):\n \"\"\"Discriminator, Auxiliary Classifier.\"\"\"\n\n def __init__(self, input_nc, image_size=64, conv_dim=64, gpu_ids=[]):\n super(SpecNormDiscriminator, self).__init__()\n self.imsize = image_size\n\n self.gpu_ids = gpu_ids\n\n layer1 = []\n layer2 = []\n layer3 = []\n last = []\n\n layer1.append(SpectralNorm(nn.Conv2d(input_nc, conv_dim, 4, 2, 1)))\n layer1.append(nn.LeakyReLU(0.1))\n\n curr_dim = conv_dim\n\n layer2.append(SpectralNorm(nn.Conv2d(curr_dim, curr_dim * 2, 4, 2, 1)))\n layer2.append(nn.LeakyReLU(0.1))\n curr_dim = curr_dim * 2\n\n layer3.append(SpectralNorm(nn.Conv2d(curr_dim, curr_dim * 2, 4, 2, 1)))\n layer3.append(nn.LeakyReLU(0.1))\n curr_dim = curr_dim * 2\n\n if self.imsize >= 64:\n layer4 = []\n layer4.append(SpectralNorm(nn.Conv2d(curr_dim, curr_dim * 2, 4, 2, 1)))\n layer4.append(nn.LeakyReLU(0.1))\n self.l4 = nn.Sequential(*layer4)\n curr_dim = curr_dim*2\n self.l1 = nn.Sequential(*layer1)\n self.l2 = nn.Sequential(*layer2)\n self.l3 = nn.Sequential(*layer3)\n\n last.append(nn.Conv2d(curr_dim, 1, 4, 2, 1))\n self.last = nn.Sequential(*last)\n\n out_dim = int(self.imsize / (2*2*2*2*2))\n\n self.net = nn.Sequential(self.l1, self.l2, self.l3, self.l4, self.last)\n\n\n def forward(self, x):\n if len(self.gpu_ids) and isinstance(x.data, torch.cuda.FloatTensor):\n out = nn.parallel.data_parallel(self.net, x, self.gpu_ids)\n else:\n out = self.net(x)\n # GAP\n out = out.view(x.shape[0], 1, -1).mean(dim=2)\n\n #self.attn1 = p1\n #self.attn2 = p2\n\n return out\n\n\n","repo_name":"tomgillooly/geogan","sub_path":"models/networks.py","file_name":"networks.py","file_ext":"py","file_size_in_byte":32009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"70811522041","text":"###########################################\r\n# Suppress matplotlib user warnings\r\n# Necessary for newer version of matplotlib\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\", category = UserWarning, module = \"matplotlib\")\r\n#\r\n# Display inline matplotlib plots with IPython\r\nfrom IPython import get_ipython\r\nget_ipython().run_line_magic('matplotlib', 'inline')\r\n###########################################\r\n\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.cm as cm\r\nimport seaborn as sns\r\nimport pandas as pd\r\nimport numpy as np\r\nimport random\r\nimport prince\r\nfrom sklearn.mixture import GaussianMixture\r\nfrom sklearn.cluster import KMeans\r\nfrom sklearn.metrics import silhouette_score\r\n\r\ndef pca_results(score,coeff,labels=None):\r\n plt.figure(figsize=(20,10))\r\n xs = score[:,0]\r\n ys = score[:,1]\r\n n = coeff.shape[0]\r\n scalex = 1.0/(xs.max() - xs.min())\r\n scaley = 1.0/(ys.max() - ys.min())\r\n plt.scatter(xs * scalex,ys * scaley)\r\n\r\n for i in range(n):\r\n plt.arrow(1.3, 0, coeff[i,0], coeff[i,1],color = 'r',alpha = 0.5)\r\n if labels is None:\r\n plt.text(1.3 + coeff[i,0]* 1.15, coeff[i,1] * 1.15, \"Var\"+str(i+1), color = 'g', ha = 'center', va = 'center')\r\n else:\r\n plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, labels[i], color = 'g', ha = 'center', va = 'center')\r\n plt.xlim(0.5,2)\r\n plt.ylim(-1,1)\r\n plt.xlabel(\"COMPONENTE{}\".format(1))\r\n plt.ylabel(\"COMPONENTE{}\".format(2))\r\n plt.grid()\r\n\r\ndef pca_results2(df, famd):\r\n\t'''\r\n\tCreate a DataFrame of the PCA results\r\n\tIncludes dimension feature weights and explained variance\r\n\tVisualizes the PCA results\r\n\t'''\r\n\r\n\t# Dimension indexing\r\n\tdimensions = dimensions = ['Dimension {}'.format(i) for i in range(1,famd.n_components+1)]\r\n\r\n\t# PCA components\r\n\tcomponents = pd.DataFrame(np.round(np.array(famd.column_correlations(df)), 4), columns = list(df.keys()))\r\n\tcomponents.index = dimensions\r\n\r\n\t# PCA explained variance\r\n\tratios = famd.explained_variance_ratio_.reshape(famd.n_components, 1)\r\n\tvariance_ratios = pd.DataFrame(np.round(ratios, 4), columns = ['Explained Variance'])\r\n\tvariance_ratios.index = dimensions\r\n\r\n\t# Create a bar plot visualization\r\n\tfig, ax = plt.subplots(figsize = (14,8))\r\n\r\n\t# Plot the feature weights as a function of the components\r\n\tcomponents.plot(ax = ax, kind = 'bar');\r\n\tax.set_ylabel(\"Feature Weights\")\r\n\tax.set_xticklabels(dimensions, rotation=0)\r\n\r\n\r\n\t# Display the explained variance ratios\r\n\t# for i, ev in enumerate(fdma.explained_variance_ratio_):\r\n\t# \tax.text(i-0.40, ax.get_ylim()[1] + 0.05, \"Explained Variance\\n %.4f\"%(ev))\r\n\r\n\t# Return a concatenated DataFrame\r\n\treturn pd.concat([variance_ratios, components], axis = 1)\r\ndef cluster_results(reduced_data, preds, centers, pca_samples):\r\n\t'''\r\n\tVisualizes the PCA-reduced cluster data in two dimensions\r\n\tAdds cues for cluster centers and student-selected sample data\r\n\t'''\r\n\r\n\tpredictions = pd.DataFrame(preds, columns = ['Cluster'])\r\n\tplot_data = pd.concat([predictions, reduced_data], axis = 1)\r\n\r\n\t# Generate the cluster plot\r\n\tfig, ax = plt.subplots(figsize = (14,8))\r\n\r\n\t# Color map\r\n\tcmap = cm.get_cmap('gist_rainbow')\r\n\r\n\t# Color the points based on assigned cluster\r\n\tfor i, cluster in plot_data.groupby('Cluster'): \r\n\t cluster.plot(ax = ax, kind = 'scatter', x = 'Dimension 1', y = 'Dimension 2', \\\r\n\t color = cmap((i)*1.0/(len(centers)-1)), label = 'Cluster %i'%(i+1), s=30);\r\n\r\n\t# Plot centers with indicators\r\n\tfor i, c in enumerate(centers):\r\n\t ax.scatter(x = c[0], y = c[1], color = 'white', edgecolors = 'black', \\\r\n\t alpha = 1, linewidth = 2, marker = 'o', s=200);\r\n\t ax.scatter(x = c[0], y = c[1], marker='$%d$'%(i+1), alpha = 1, s=100);\r\n\r\n\t# Plot transformed sample points \r\n\t# ax.scatter(x = pca_samples[:,0], y = pca_samples[:,1], \\\r\n\t# s = 150, linewidth = 4, color = 'black', marker = 'x');\r\n\r\n\t# Set plot title\r\n\tax.set_title(\"Cluster Learning on PCA-Reduced Data - Centroids Marked by Number\\n\");\r\n\r\n\r\ndef biplot(good_data, reduced_data, famd):\r\n '''\r\n Produce a biplot that shows a scatterplot of the reduced\r\n data and the projections of the original features.\r\n \r\n good_data: original data, before transformation.\r\n Needs to be a pandas dataframe with valid column names\r\n reduced_data: the reduced data (the first two dimensions are plotted)\r\n pca: pca object that contains the components_ attribute\r\n\r\n return: a matplotlib AxesSubplot object (for any additional customization)\r\n \r\n This procedure is inspired by the script:\r\n https://github.com/teddyroland/python-biplot\r\n '''\r\n\r\n fig, ax = plt.subplots(figsize = (14,8))\r\n # scatterplot of the reduced data \r\n ax.scatter(x=reduced_data.loc[:, 'Dimension 1'], y=reduced_data.loc[:, 'Dimension 2'], \r\n facecolors='b', edgecolors='b', s=70, alpha=0.5)\r\n \r\n feature_vectors = famd.explained_inertia_\r\n #feature_vectors = pca.components_.T\r\n #famd.explained_inertia_\r\n\r\n # we use scaling factors to make the arrows easier to see\r\n arrow_size, text_pos = 7.0, 8.0,\r\n\r\n # projections of the original features\r\n for i, v in enumerate(feature_vectors):\r\n ax.arrow(0, 0, arrow_size*v[0], arrow_size*v[1], \r\n head_width=0.2, head_length=0.2, linewidth=2, color='red')\r\n ax.text(v[0]*text_pos, v[1]*text_pos, good_data.columns[i], color='black', \r\n ha='center', va='center', fontsize=18)\r\n\r\n ax.set_xlabel(\"Dimension 1\", fontsize=14)\r\n ax.set_ylabel(\"Dimension 2\", fontsize=14)\r\n ax.set_title(\"PC plane with original feature projections.\", fontsize=16);\r\n return ax\r\n \r\n\r\ndef channel_results(reduced_data, outliers, pca_samples):\r\n\t'''\r\n\tVisualizes the PCA-reduced cluster data in two dimensions using the full dataset\r\n\tData is labeled by \"Channel\" and cues added for student-selected sample data\r\n\t'''\r\n\r\n\t# Check that the dataset is loadable\r\n\ttry:\r\n\t full_data = pd.read_csv(\"customers.csv\")\r\n\texcept:\r\n\t print(\"Dataset could not be loaded. Is the file missing?\") \r\n\t return False\r\n\r\n\t# Create the Channel DataFrame\r\n\tchannel = pd.DataFrame(full_data['Channel'], columns = ['Channel'])\r\n\tchannel = channel.drop(channel.index[outliers]).reset_index(drop = True)\r\n\tlabeled = pd.concat([reduced_data, channel], axis = 1)\r\n\t\r\n\t# Generate the cluster plot\r\n\tfig, ax = plt.subplots(figsize = (14,8))\r\n\r\n\t# Color map\r\n\tcmap = cm.get_cmap('gist_rainbow')\r\n\r\n\t# Color the points based on assigned Channel\r\n\tlabels = ['Hotel/Restaurant/Cafe', 'Retailer']\r\n\tgrouped = labeled.groupby('Channel')\r\n\tfor i, channel in grouped: \r\n\t channel.plot(ax = ax, kind = 'scatter', x = 'Dimension 1', y = 'Dimension 2', \\\r\n\t color = cmap((i-1)*1.0/2), label = labels[i-1], s=30);\r\n\t \r\n\t# Plot transformed sample points \r\n\tfor i, sample in enumerate(pca_samples):\r\n\t\tax.scatter(x = sample[0], y = sample[1], \\\r\n\t s = 200, linewidth = 3, color = 'black', marker = 'o', facecolors = 'none');\r\n\t\tax.scatter(x = sample[0]+0.25, y = sample[1]+0.3, marker='$%d$'%(i), alpha = 1, s=125);\r\n\r\n\t# Set plot title\r\n\tax.set_title(\"PCA-Reduced Data Labeled by 'Channel'\\nTransformed Sample Data Circled\");\r\n\r\n\t###########################################\r\n#This is modified code from original code at: \r\n#http://scikit-learn.org/stable/auto_examples/cluster/plot_kmeans_silhouette_analysis.html#sphx-glr-auto-examples-cluster-plot-kmeans-silhouette-analysis-py\r\n\r\ndef silhouette_score_graph(range_n_clusters,algorith,values):\r\n \r\n from sklearn.cluster import KMeans\r\n from sklearn.mixture import GaussianMixture\r\n from sklearn.metrics import silhouette_samples, silhouette_score\r\n\r\n import matplotlib.pyplot as plt\r\n import matplotlib.cm as cm\r\n import numpy as np\r\n\r\n \r\n for n_clusters in range_n_clusters:\r\n # Create a subplot with 1 row and 2 columns\r\n fig, (ax1, ax2) = plt.subplots(1, 2)\r\n fig.set_size_inches(10, 4)\r\n\r\n # The 1st subplot is the silhouette plot\r\n # The silhouette coefficient can range from -1, 1 but in this example all\r\n # lie within [-0.1, 1]\r\n ax1.set_xlim([-0.1, 1])\r\n # The (n_clusters+1)*10 is for inserting blank space between silhouette\r\n # plots of individual clusters, to demarcate them clearly.\r\n ax1.set_ylim([0, len(values.index) + (n_clusters + 1) * 10])\r\n\r\n # Initialize the clusterer with n_clusters value and a random generator\r\n # seed of 10 for reproducibility.\r\n if algorith=='KNN': \r\n clusterer = KMeans(n_clusters=n_clusters, random_state=10)\r\n cluster_labels = clusterer.fit_predict(values) \r\n \r\n elif algorith=='GMM':\r\n clusterer = GaussianMixture(n_components=n_clusters, random_state=10).fit(values)\r\n cluster_labels = clusterer.predict(values)\r\n \r\n\r\n # The silhouette_score gives the average value for all the samples.\r\n # This gives a perspective into the density and separation of the formed\r\n # clusters\r\n silhouette_avg = silhouette_score(values, cluster_labels)\r\n print(\"For n_clusters =\", n_clusters,\r\n \"The average silhouette_score is :\", round(silhouette_avg,4))\r\n\r\n # Compute the silhouette scores for each sample\r\n sample_silhouette_values = silhouette_samples(values, cluster_labels)\r\n\r\n y_lower = 10\r\n for i in range(n_clusters):\r\n # Aggregate the silhouette scores for samples belonging to\r\n # cluster i, and sort them\r\n ith_cluster_silhouette_values = \\\r\n sample_silhouette_values[cluster_labels == i]\r\n\r\n ith_cluster_silhouette_values.sort()\r\n\r\n size_cluster_i = ith_cluster_silhouette_values.shape[0]\r\n y_upper = y_lower + size_cluster_i\r\n\r\n color = cm.nipy_spectral(float(i) / n_clusters)\r\n ax1.fill_betweenx(np.arange(y_lower, y_upper),\r\n 0, ith_cluster_silhouette_values,\r\n facecolor=color, edgecolor=color, alpha=0.7)\r\n\r\n # Label the silhouette plots with their cluster numbers at the middle\r\n ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))\r\n\r\n # Compute the new y_lower for next plot\r\n y_lower = y_upper + 10 # 10 for the 0 samples\r\n\r\n ax1.set_title(\"The silhouette plot for the various clusters.\")\r\n ax1.set_xlabel(\"The silhouette coefficient values\")\r\n ax1.set_ylabel(\"Cluster label\")\r\n\r\n # The vertical line for average silhouette score of all the values\r\n ax1.axvline(x=silhouette_avg, color=\"red\", linestyle=\"--\")\r\n\r\n ax1.set_yticks([]) # Clear the yaxis labels / ticks\r\n ax1.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1])\r\n\r\n # 2nd Plot showing the actual clusters formed\r\n colors = cm.nipy_spectral(cluster_labels.astype(float) / n_clusters)\r\n ax2.scatter(values['Dimension 1'], values['Dimension 2'], marker='.', s=30, lw=0, alpha=0.7,\r\n c=colors, edgecolor='k')\r\n \r\n # Labeling the clusters\r\n if algorith=='KNN': \r\n centers = clusterer.cluster_centers_\r\n plt.suptitle((\"Silhouette analysis for KMeans clustering on sample data \"\r\n \"with n_clusters = %d\" % n_clusters),\r\n fontsize=14, fontweight='bold')\r\n elif algorith=='GMM':\r\n centers = clusterer.means_\r\n plt.suptitle((\"Silhouette analysis for Gaussian Mixture Model clustering on sample data \"\r\n \"with n_clusters = %d\" % n_clusters),\r\n fontsize=14, fontweight='bold')\r\n \r\n \r\n \r\n # Draw white circles at cluster centers\r\n ax2.scatter(centers[:, 0], centers[:, 1], marker='o',\r\n c=\"white\", alpha=1, s=200, edgecolor='k')\r\n\r\n for i, c in enumerate(centers):\r\n ax2.scatter(c[0], c[1], marker='$%d$' % i, alpha=1,\r\n s=50, edgecolor='k')\r\n\r\n ax2.set_title(\"The visualization of the clustered data.\")\r\n ax2.set_xlabel(\"Feature space for the 1st component\")\r\n ax2.set_ylabel(\"Feature space for the 2nd component\")\r\n\r\n plt.show()\r\n\r\ndef Function_Clustering(algorith,values):\r\n # Loop through clusters\r\n results = []\r\n for n_clusters in list_n_clusters:\r\n \r\n if algorith=='KNN': \r\n\r\n clusterer = KMeans(n_clusters=n_clusters,random_state=10).fit(values) \r\n centers = clusterer.cluster_centers_\r\n \r\n elif algorith=='GMM':\r\n \r\n \r\n clusterer = GaussianMixture(n_components=n_clusters, random_state=10).fit(values) \r\n centers = clusterer.means_\r\n \r\n\r\n \r\n preds = clusterer.predict(values) \r\n #sample_preds = clusterer.predict(pca_samples) \r\n score = silhouette_score(values, preds, metric='euclidean')\r\n results.append({'Clusters':n_clusters,'silhouette_score':round(score,4)})\r\n \r\n return results\r\n\r\ndef show_exploration(df):\r\n clr = [ '#12efff' , '#abc222' , '#00ef00', '#ffa700' , '#d62d20' , '#a200ff']\r\n \r\n plt.subplots(figsize=(15,10))\r\n plt.figure(1)\r\n\r\n\r\n ax1=plt.subplot(1,3,1)\r\n plt.xticks(rotation=45)\r\n ax1.set_title('ESTUDIOS')\r\n df['ES'].hist (figsize=(18,5))\r\n\r\n ax1=plt.subplot(1,3,2)\r\n plt.xticks(rotation=45)\r\n ax1.set_title('SEXO')\r\n df['SEXO'].hist (figsize=(18,5))\r\n\r\n ax1=plt.subplot(1,3,3)\r\n plt.xticks(rotation=45)\r\n ax1.set_title('TIPOTRABAJO')\r\n df['TT'].hist(figsize=(18,5))\r\n\r\n \r\n plt.figure(2)\r\n\r\n\r\n ax1=plt.subplot(2,2,1)\r\n plt.xticks(rotation=45)\r\n ax1.set_title('FUNCION DESARROLLADA')\r\n df['FD'].hist(figsize=(18,5))\r\n\r\n ax1=plt.subplot(2,2,2)\r\n plt.xticks(rotation=45)\r\n ax1.set_title('Gestiona Equipos')\r\n df['GE'].hist(figsize=(18,5))\r\n\r\n\r\n\r\n plt.subplots(figsize=(15,10))\r\n plt.figure(3)\r\n plt.suptitle(u'Edad. \\n' 'Note: Solid vertical line represents mean, dashed line represents median.')\r\n\r\n ax1=plt.subplot(3,2,1)\r\n sns.distplot(df['EDAD'], color =clr[5])\r\n plt.axvline(df['EDAD'].mean(), color='#000000', linestyle='solid', linewidth=1)\r\n plt.axvline(df['EDAD'].median(), color='#000000', linestyle='dashed', linewidth=1)\r\n ax1.set_title('Distribución de la edad')\r\n\r\n ax1=plt.subplot(3,2,2)\r\n _= sns.boxplot(data=df['EDAD'], orient='h', palette=clr,ax=ax1)\r\n\r\n #Values range\r\n ax2=plt.subplot(3,2,3)\r\n _ = sns.barplot(data=df['EDAD'], palette=clr,ax=ax2)\r\n\r\ndef show_exploration_segment(df):\r\n clr = [ '#12efff' , '#abc222' , '#00ef00', '#ffa700' , '#d62d20' , '#a200ff']\r\n \r\n plt.subplots(figsize=(15,10))\r\n plt.figure(1)\r\n\r\n\r\n ax1=plt.subplot(1,3,1)\r\n plt.xticks(rotation=45)\r\n ax1.set_title('SEXO')\r\n df['SEXO'].hist (figsize=(18,5))\r\n\r\n ax1=plt.subplot(1,3,2)\r\n plt.xticks(rotation=45)\r\n ax1.set_title('ESTUDIOS')\r\n df['estudios'].hist (figsize=(18,5))\r\n\r\n ax1=plt.subplot(1,3,3)\r\n plt.xticks(rotation=45)\r\n ax1.set_title('TIPOTRABAJO')\r\n df['TIPOTRABAJO'].hist(figsize=(18,5))\r\n\r\n \r\n plt.figure(2)\r\n\r\n\r\n ax1=plt.subplot(2,3,1)\r\n plt.xticks(rotation=45)\r\n ax1.set_title('FUNCION DESARROLLADA')\r\n df['FUNCIONDESARROLLADA'].hist(figsize=(18,5))\r\n\r\n ax1=plt.subplot(2,3,2)\r\n plt.xticks(rotation=45)\r\n ax1.set_title('Gestiona Equipos')\r\n df['GestionaEquipos'].hist(figsize=(18,5))\r\n\r\n ax1=plt.subplot(2,3,3)\r\n plt.xticks(rotation=45)\r\n ax1.set_title('Numero Personas')\r\n df['NumeroPersonas'].hist(figsize=(18,5))\r\n\r\n # plt.subplots(figsize=(15,10)) \r\n # plt.figure(3)\r\n # plt.suptitle(u'Edad. \\n' 'Note: Solid vertical line represents mean, dashed line represents median.')\r\n\r\n # ax1=plt.subplot(3,2,1)\r\n # sns.distplot(df['EDAD'], color =clr[5])\r\n # plt.axvline(df['EDAD'].mean(), color='#000000', linestyle='solid', linewidth=1)\r\n # plt.axvline(df['EDAD'].median(), color='#000000', linestyle='dashed', linewidth=1)\r\n # ax1.set_title('Distribución de la edad')\r\n\r\n # ax1=plt.subplot(3,2,2)\r\n # _= sns.boxplot(data=df['EDAD'], orient='h', palette=clr,ax=ax1)\r\n\r\n # #Values range\r\n # ax2=plt.subplot(3,2,3)\r\n # _ = sns.barplot(data=df['EDAD'], palette=clr,ax=ax2)\r\n\r\n\r\ndef show_exploration_segment_comportamiento(df,dfti=None):\r\n clr = [ '#12efff' , '#abc222' , '#00ef00', '#ffa700' , '#d62d20' , '#a200ff']\r\n #colunmas= ['Segmento','DispuestoPagar','coaching','Pagado','TemaInteres','sessiones']\r\n plt.subplots(figsize=(15,10))\r\n plt.figure(1)\r\n\r\n\r\n ax1=plt.subplot(1,3,1)\r\n plt.xticks(rotation=45)\r\n ax1.set_title('Dispuesto Pagar')\r\n df['DispuestoPagar'].hist (figsize=(18,5))\r\n\r\n ax1=plt.subplot(1,3,2)\r\n plt.xticks(rotation=45)\r\n ax1.set_title('Coaching')\r\n df['coaching'].hist (figsize=(18,5))\r\n\r\n ax1=plt.subplot(1,3,3)\r\n plt.xticks(rotation=45)\r\n ax1.set_title('Pagado')\r\n df['Pagado'].hist(figsize=(18,5))\r\n\r\n \r\n plt.figure(2)\r\n\r\n \r\n ax1=plt.subplot(2,2,1)\r\n plt.xticks(rotation=90)\r\n ax1.set_title('Tema Interes')\r\n dfti['TemaInteres'].hist(figsize=(18,5))\r\n\r\n ax1=plt.subplot(2,2,2)\r\n plt.xticks(rotation=45)\r\n ax1.set_title('sessiones')\r\n df['sessiones'].hist(figsize=(18,5))\r\n\r\n\r\n\r\ndef show_sample_exploration(df,samples,indices):\r\n\r\n ax1 = plt.subplot(1, 2, 1)\r\n \r\n #The means \r\n mean_data = df.describe().loc['mean', :]\r\n\r\n #Append means to the samples' data\r\n samples_bar = samples.append(mean_data)\r\n\r\n #Construct indices\r\n samples_bar.index = indices + ['mean']\r\n\r\n #Plot bar plot\r\n samples_bar.plot(kind='bar', figsize=(15,5), ax=ax1)\r\n ax1.set_title(\"Samples vs Mean\")\r\n\r\n ax2 = plt.subplot(1, 2, 2)\r\n\r\n # percentile ranks of the whole dataset.\r\n percentiles = df.rank(pct=True)\r\n\r\n # Round it up, and multiply by 100\r\n percentiles = 100*percentiles.round(decimals=3)\r\n\r\n # Select the indices from the percentiles dataframe\r\n percentiles = percentiles.iloc[indices]\r\n\r\n # Now, create the heat map\r\n sns.heatmap(percentiles, vmin=1, vmax=99, ax=ax2, annot=True)\r\n ax2.set_title(\"Comparación de los percentiles de la muestra.\")\r\n\r\ndef show_components(famd):\r\n dset = pd.DataFrame()\r\n dset['famd'] = range(1,7)\r\n dset['eigenvalue'] = pd.DataFrame(famd.eigenvalues_)\r\n plt.figure(figsize=(18,6))\r\n ax1 = plt.subplot(1, 2, 1)\r\n sns.lineplot(x='famd', y='eigenvalue', marker=\"o\", data=dset)\r\n plt.ylabel('Eigenvalue', fontsize=16)\r\n plt.xlabel('Principal Component', fontsize=16)\r\n\r\n ax1 = plt.subplot(1, 2, 2)\r\n dset['vari'] = pd.DataFrame(famd.explained_inertia_)\r\n\r\n graph = sns.barplot(x='famd', y='vari', data=dset)\r\n for p in graph.patches:\r\n graph.annotate('{:.2f}'.format(p.get_height()), (p.get_x()+0.2, p.get_height()),\r\n ha='center', va='bottom',\r\n color= 'black')\r\n plt.ylabel('Proportion', fontsize=18)\r\n plt.xlabel('Principal Component', fontsize=18)\r\n\r\ndef show_pather(df,famd, slabel=False):\r\n\r\n scatter = pd.DataFrame(famd.column_correlations(df)).reset_index()\r\n plt.figure(figsize=(25,10))\r\n ax = sns.scatterplot(x=0, y=1, data=scatter)\r\n ax.set(ylim=(-1, 1), xlim=(-1,1.5))\r\n \r\n def label_point(x, y, val, ax):\r\n a = pd.concat({'x': x, 'y': y, 'val': val}, axis=1)\r\n for i, point in a.iterrows():\r\n texto= str(point['val']).split(\"_\")\r\n valor = texto[-1] \r\n #ax.text(point['x']+.02, point['y'],point['val'] )\r\n ax.text(point['x']+.02, point['y'],valor )\r\n if slabel:\r\n label_point(scatter[0], scatter[1], scatter['index'], plt.gca()) \r\n\r\n plt.axvline(-0.5, ls='--')\r\n plt.axhline(0, ls='--')\r\n\r\n plt.title('Pattern Plot of Component 2 by Component 1', fontsize=18)\r\n plt.xlabel('Component 1 (41%)', fontsize=10)\r\n plt.ylabel('Component 2 (13%)', fontsize=10)\r\n plt.show()\r\n\r\nvalueCounts = {}\r\ndef CountAll(df):\r\n global all_columns, nanCounts, valueCounts\r\n all_columns = list(df)\r\n nanCounts = df.isnull().sum()\r\n for x in all_columns:\r\n valueCounts[x] = df[x].value_counts() \r\n\r\n\r\ndef Fill_NaNs_Categorical(df,col): \r\n \"\"\"Calculating probability and expected value.\"\"\"\r\n proportion = np.array(valueCounts[col].values) / valueCounts[col].sum() * nanCounts[col]\r\n proportion = np.around(proportion).astype('int')\r\n \r\n \"\"\"Adjusting proportion.\"\"\"\r\n diff = int(nanCounts[col] - np.sum(proportion))\r\n if diff > 0:\r\n for x in range(diff):\r\n idx = random.randint(0, len(proportion) - 1)\r\n proportion[idx] = proportion[idx] + 1\r\n else:\r\n diff = -diff\r\n while(diff != 0):\r\n idx = random.randint(0, len(proportion) - 1)\r\n if proportion[idx] > 0:\r\n proportion[idx] = proportion[idx] - 1\r\n diff = diff - 1\r\n \r\n \"\"\"Filling NaNs.\"\"\"\r\n nan_indexes = df[df[col].isnull()].index.tolist() \r\n for x in range(len(proportion)):\r\n if proportion[x] > 0:\r\n random_subset = random.sample(population = nan_indexes, k = proportion[x])\r\n df.loc[random_subset, col] = valueCounts[col].keys()[x]\r\n nan_indexes = list(set(nan_indexes) - set(random_subset))\r\n\r\ndef agregarNuevasVariables(df_aux):\r\n dffp= pd.read_csv('DispuestoPagar.csv')\r\n df_aux['DispuestoPagar']= dffp['DispuestoPagar']\r\n\r\n\r\n dfc= pd.read_csv('coaching.csv',sep=';')\r\n df_aux['coaching'] = dfc['coaching']\r\n\r\n dfpp= pd.read_csv('PagadoSession2.csv')\r\n df_aux['Pagado']= dfpp['PagadoSesion']\r\n df_aux['Pagado'][0]=df_aux['Pagado'][64]\r\n\r\n dfti= pd.read_csv('TemaInteres2.csv', encoding='utf-8')\r\n df_aux['TemaInteres']= dfti['TemaInteres']\r\n\r\n dfss= pd.read_csv('session.csv')\r\n df_aux['sessiones']= dfss['sessiones']\r\n df_aux['sessiones'][0]=df_aux['sessiones'][65]\r\n\r\n\r\n #dfex= pd.read_csv('ExpectativasHaciaCoach.csv',sep=';')\r\n #dfs['ExpectativasHaciaCoach']= dfex['ExpectativasHaciaCoach']\r\n #dfs['sessiones'][0]=dfs['sessiones'][65]\r\n\r\n return df_aux.copy()\r\n\r\n\r\ndef plot_comportamiento_segmento(df,key):\r\n int_col = ['Segmento','DispuestoPagar','coaching','Pagado','TemaInteres','sessiones']\r\n plt.figure(figsize=(8,6))\r\n if key=='DispuestoPagar':\r\n values = ['Entre 10-40', 'Entre 45-70', 'Entre 75-100']\r\n\r\n if key=='coaching':\r\n values = ['Si de forma puntual', 'no me lo he planteado', 'pensado','los uso con frecuencia']\r\n\r\n if key=='Pagado':\r\n values = ['Entre 10-40', 'Entre 45-70', 'Entre 75-100','Mayor de 100']\r\n \r\n if key=='sessiones':\r\n values = ['Mayor de 10', 'Entre 4-6.', 'Entre 1-3.','Entre 7-10.']\r\n\r\n if key=='TemaInteres':\r\n int_col = ['Segment']\r\n values = ['Gestión de equipos', 'Habilidades de comunicación', \\\r\n 'Gestión del tiempo','Motivación e inspiración',\\\r\n 'Relaciones de pareja y familia','Pensamiento/Planificación estratégica', \\\r\n 'Autoconfianza','Desarrollo de cualidades personales','Fe y espiritualidad',\\\r\n 'Desarrollo personal','Conflicto laboral','Liderazgo y confianza']\r\n\r\n frame = pd.DataFrame(index = np.arange(len(values)), columns=(key,'Seg0','Seg1'))\r\n for i, value in enumerate(values):\r\n if key=='TemaInteres':\r\n frame.loc[i] = [value, \\\r\n len(df['Segmento'][(df['Segmento'] == 0) & (df[key] == value)]), \\\r\n len(df['Segmento'][(df['Segmento'] == 1) & (df[key] == value)])]\r\n else:\r\n frame.loc[i] = [value, \\\r\n len(df[int_col][(df[int_col]['Segmento'] == 0) & (df[int_col][key] == value)]), \\\r\n len(df[int_col][(df[int_col]['Segmento'] == 1) & (df[int_col][key] == value)])]\r\n\r\n bar_width = 0.4\r\n for i in np.arange(len(frame)):\r\n nonsurv_bar = plt.bar(i-bar_width, frame.loc[i]['Seg0'], width = bar_width, color = 'r')\r\n surv_bar = plt.bar(i, frame.loc[i]['Seg1'], width = bar_width, color = 'g')\r\n\r\n plt.xticks(np.arange(len(frame)), values)\r\n plt.xticks(rotation=90)\r\n plt.legend((nonsurv_bar[0], surv_bar[0]),('Segemto 0', 'Segmento 1'), framealpha = 0.8)\r\n \r\n \r\n \r\n\r\ndef fix_temaInteres(df):\r\n dfTemaInteres= pd.DataFrame(columns=['Segmento', 'TemaInteres','IndexFrom'])\r\n for index, row in df.iterrows(): \r\n arraux= row['TemaInteres'].split('|')\r\n for i,val in enumerate(arraux): \r\n \r\n #print(val)\r\n #print(row['Segment']) \r\n #print(val)\r\n #print(index)\r\n #new_row = pd.Series({'Segment':row['Segment'], 'TemaInteres':val, 'IndexFrom':index})\r\n #dfaux.append(new_row,ignore_index=True ) \r\n\r\n dfTemaInteres.loc[index] = [row['Segmento'], [val.split('.')][0][0].strip(),index]\r\n \r\n \r\n \r\n #dfTemaInteres.head()\r\n return dfTemaInteres\r\n\r\ndef plot_comportamientos_segmento(df):\r\n int_col = ['Segmento','DispuestoPagar','coaching','Pagado','TemaInteres','sessiones']\r\n plt.figure(figsize=(8,6))\r\n tframe = pd.DataFrame()\r\n values = None\r\n paso=False\r\n\r\n for key in int_col:\r\n print(key)\r\n if key=='Segmento':\r\n paso=False\r\n print(paso)\r\n continue\r\n paso=True\r\n if key=='DispuestoPagar':\r\n values = ['Entre 10-40', 'Entre 45-70', 'Entre 75-100']\r\n\r\n if key=='coaching':\r\n values = ['Si de forma puntual', 'no me lo he planteado', 'pensado','los uso con frecuencia']\r\n\r\n if key=='Pagado':\r\n values = ['Entre 10-40', 'Entre 45-70', 'Entre 75-100','Mayor de 100']\r\n \r\n if key=='sessiones':\r\n values = ['Mayor de 10', 'Entre 4-6.', 'Entre 1-3.','Entre 7-10.']\r\n\r\n if key=='TemaInteres':\r\n int_col = ['Segment']\r\n values = ['Gestión de equipos', 'Habilidades de comunicación', \\\r\n 'Gestión del tiempo','Motivación e inspiración',\\\r\n 'Relaciones de pareja y familia','Pensamiento/Planificación estratégica', \\\r\n 'Autoconfianza','Desarrollo de cualidades personales','Fe y espiritualidad',\\\r\n 'Desarrollo personal','Conflicto laboral','Liderazgo y confianza']\r\n\r\n if paso:\r\n print(paso)\r\n print(key)\r\n tframe = pd.DataFrame(index = np.arange(len(values)), columns=(key,'Seg0','Seg1'))\r\n \r\n for i, value in enumerate(values):\r\n if key=='TemaInteres':\r\n tframe.loc[i] = [value, \\\r\n len(df['Segmento'][(df['Segmento'] == 0) & (df[key] == value)]), \\\r\n len(df['Segmento'][(df['Segmento'] == 1) & (df[key] == value)])]\r\n else:\r\n print(value)\r\n tframe.loc[i] = [value, \\\r\n len(df[int_col][(df[int_col]['Segmento'] == 0) & (df[int_col][key] == value)]), \\\r\n len(df[int_col][(df[int_col]['Segmento'] == 1) & (df[int_col][key] == value)])]\r\n paso=False\r\n\r\n bar_width = 0.4\r\n plt.subplots(figsize=(15,10))\r\n plt.figure(1)\r\n k=1 \r\n\r\n\r\n for i in np.arange(len(tframe)):\r\n nonsurv_bar = plt.bar(i-bar_width, tframe.loc[i]['Seg0'], width = bar_width, color = 'r')\r\n surv_bar = plt.bar(i, tframe.loc[i]['Seg1'], width = bar_width, color = 'g')\r\n\r\n ax1=plt.subplot(1,3,k)\r\n plt.xticks(rotation=45)\r\n ax1.set_title(key) \r\n\r\n plt.xticks(np.arange(len(tframe)), values)\r\n plt.xticks(rotation=90)\r\n plt.legend((nonsurv_bar[0], surv_bar[0]),('Segemto 0', 'Segmento 1'), framealpha = 0.8)\r\n\r\ndef show_comportamiento(df,segmento):\r\n colunmas= ['Segmento','DispuestoPagar','coaching','Pagado','TemaInteres','sessiones']\r\n en_filtro=df['Segmento']==segmento\r\n df_segment = df[en_filtro][colunmas]\r\n dfTemaInteres= fix_temaInteres(df_segment)\r\n show_exploration_segment_comportamiento(df_segment,dfTemaInteres)\r\n\r\n","repo_name":"HenrryVargas/coaching","sub_path":"utilidades.py","file_name":"utilidades.py","file_ext":"py","file_size_in_byte":28494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"34596750061","text":"holidays_count = int(input())\n\nplay_time_norm = 30000\nplay_time_work_days = 63\nplay_time_off_days = 127\nwork_days = 365 - holidays_count\n\ntotal_play_time_off_days = holidays_count * play_time_off_days\ntotal_play_time_work_days = work_days * play_time_work_days\ngrand_total = total_play_time_work_days + total_play_time_off_days\ndiff = abs(grand_total - play_time_norm)\nhours = diff // 60\nminutes = diff % 60\nif grand_total <= play_time_norm:\n print('Tom sleeps well')\n print(f'{hours} hours and {minutes} minutes less for play')\nelse:\n print('Tom will run away')\n print(f'{hours} hours and {minutes} minutes more for play')","repo_name":"miladimanova/SoftUni_Software_Engineering","sub_path":"Programming_Basics_Python/pb_more_exercises/conditional_statements - more_exercises/slleepy_tom_cat.py","file_name":"slleepy_tom_cat.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"69805250042","text":"import itertools\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nimport sys\nimport cv2\nimport numpy as np\nfrom PIL import Image\nfrom unet_model import *\nimport config\n\n\nfrom file_manager import FileManager\nfrom image_manager import ImageManager\n\nclass_encoding = FileManager.get_classes_encoding()\n\n# Formatage de la liste cree par image_splitting\ndef val_generator(img_lst):\n for img in img_lst:\n img = img / 255 # NORMALISATION\n img = np.asarray([img])\n yield img\n\n# Reconstitution de l'image en une\ndef concat_prediction(predictions, image, cut_size, gt_size):\n x = 0\n y = 0\n cp_x = (cut_size - gt_size)//2\n cp_y = cp_x\n cp_image = Image.new('RGB', (image.shape[1], image.shape[0]))\n for i, item in enumerate(predictions):\n if y + cut_size >= image.shape[0]:\n cp_x += gt_size\n x += gt_size\n cp_y = (cut_size-gt_size)//2\n y = 0\n if x + cut_size >= image.shape[1]:\n break\n \n # Create empty array\n height, width, n_classes = item.shape\n decoded_mask = np.zeros((height, width, 3), dtype=np.uint8)\n\n # Set the color to the class with the highest probability\n predicted_classes = np.argmax(item, axis=2)\n for name, label, color in class_encoding:\n mask_indices = np.where(predicted_classes == label)\n decoded_mask[mask_indices] = color\n \n cp_tmp = np.uint8(decoded_mask)\n cp_tmp = Image.fromarray(cp_tmp)\n cp_tmp = cp_tmp.resize((gt_size, gt_size))\n test = cv2.cvtColor(np.array(cp_tmp), cv2.COLOR_RGB2BGR)\n path = os.path.join(config.TEMP_OUTPUT, \"test_\" + str(cp_x) + str(cp_y) + \".jpg\")\n cv2.imwrite(path, test)\n cp_image.paste(cp_tmp, (cp_x, cp_y))\n cp_y += gt_size\n y += gt_size\n return cp_image\n\n\ndef compute_f1(results, filename, extension):\n\n ca_mask = cv2.imread(\"datasets/test_labels/\" + filename + extension)\n\n # Convert the image since openCV encodes color in BGR\n ca_mask = cv2.cvtColor(ca_mask, cv2.COLOR_BGR2RGB)\n\n # Normalize colors\n ca_mask = np.asarray(ca_mask) / 255\n results = np.asarray(results) / 255\n\n # Vine RBG values\n color = (255, 255, 255)\n color = np.asarray(color) / 255\n\n # One versus all\n mask_class_indices = np.all(ca_mask == color, axis=2)\n prediction_class_indices = np.all(results == color, axis=2)\n\n # The class is assigned 1 and other pixels are assigned 0\n mask_class_vs_all = np.zeros((ca_mask.shape[0], ca_mask.shape[1]), dtype=np.uint8)\n pred_class_vs_all = np.zeros((results.shape[0], results.shape[1]), dtype=np.uint8)\n mask_class_vs_all[mask_class_indices] = 1\n pred_class_vs_all[prediction_class_indices] = 1\n\n intersection = np.logical_and(mask_class_vs_all, pred_class_vs_all)\n\n # Confusion matrix\n true_pos = np.sum(intersection)\n false_pos = np.logical_xor(intersection, pred_class_vs_all)\n false_pos = np.sum(false_pos)\n false_neg = np.logical_xor(intersection, mask_class_vs_all)\n false_neg = np.sum(false_neg)\n true_neg = (ca_mask.shape[0] * ca_mask.shape[1]) - (true_pos + false_pos + false_neg)\n\n # Calculate f1\n precision = true_pos / (true_pos + false_pos)\n recall = true_pos / (true_pos + false_neg)\n f1 = 2*(precision * recall) / (precision + recall)\n return f1\n\ndef main(argv):\n file = 'datasets/test/swissimage-dop10_2017_2608-1128_2.jpg'\n cut_size = 144\n gt_size = 144\n result_dir = './Results/'\n weights = \"./Weights/unet_vines.hdf5\"\n new_data_resolution = 0\n\n input_size = (cut_size, cut_size, 3)\n filename, extension = FileManager.get_filename_n_extension(self=None, path=file)\n image = cv2.imread(file)\n\n if new_data_resolution == 0:\n if image.shape[0] < 3000:\n img_height = image.shape[0]\n ratio = (config.ORIGINAL_HEIGHT/img_height)+2\n cut_size = int(config.CUT_SIZE/ratio)\n gt_size = int(config.GT_SIZE/ratio)\n else:\n ratio = new_data_resolution/config.IMG_RESOLUTION\n cut_size = int(config.CUT_SIZE/ratio)\n gt_size = int(config.GT_SIZE/ratio)\n\n imageManager = ImageManager(cut_size, gt_size)\n img_list = imageManager.image_splitting(image, cut_size, gt_size)\n count_img = len(img_list)\n\n max_f1_score = -1\n best_seed = -1\n upper_bound = 1000100\n for i in range(1000001, upper_bound, 1):\n\n print(i, \"/\", upper_bound)\n\n # Generator must be rebuilt at each iteration\n test_gen = val_generator(img_list)\n\n # Prediction\n model = unet_sym(pretrained_weights=weights, input_size=input_size, seed=i)\n results = model.predict_generator(test_gen, count_img, verbose=0) \n\n # Concat the predictions in a single image\n res_image = concat_prediction(results, image, cut_size, gt_size)\n\n # Store the seed if the F1 score of this iteration is the best\n f1_score = compute_f1(res_image, filename, extension)\n print(f1_score)\n if (f1_score > max_f1_score):\n best_seed = i\n max_f1_score = f1_score\n \n print(\"Max\")\n print(max_f1_score)\n print(best_seed)\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","repo_name":"benjamin-biollaz/retrain-unet-vineyard-objects-reco-master","sub_path":"find_satisfactory_seed.py","file_name":"find_satisfactory_seed.py","file_ext":"py","file_size_in_byte":5266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"74173106680","text":"from django.shortcuts import redirect, render\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom Assure_Me.models import Affirmation\nfrom django.contrib.auth.decorators import login_required\n\n \n@login_required \ndef edit_affirmation_view(request, Affirmation_Id):\n\n '''Handles editting an affirmation that the user has\n\n Method arguments:\n request -- The full HTTP request object\n Affirmation_Id -- Affirmation's specific id that is being editted\n \n Author:\n Cashew Rose\n '''\n\n if request.method == \"POST\":\n try:\n affirm = Affirmation.objects.get(pk=Affirmation_Id)\n # This makes sure only the owner of the affirmation can actually delete the instance of it\n if request.user.id == affirm.user_id: \n\n # Gets the inputs value for the new affirmation changes\n edit_affirmation=request.POST['affirmation']\n\n # Saves the new affirmation value to the existing instance to make an updated instance\n edit_post = Affirmation(id=Affirmation_Id, affirmation=edit_affirmation, user_id=affirm.user_id)\n\n # Saves the updated instance to the existing instance in the Affirmation Model\n edit_post.save()\n\n return redirect('/affirmations')\n \n else: \n return redirect('/affirmations')\n\n # Accounts for if there affirmation has already been deleted\n except ObjectDoesNotExist:\n return redirect('/affirmations')\n\n else: \n return redirect('/affirmations')\n","repo_name":"CashewRose/Assure_Me","sub_path":"djangocap/Assure_Me/views/affirmation_edit_view.py","file_name":"affirmation_edit_view.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"32828465106","text":"import matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport numpy as np\nimport seaborn as sns\nimport scipy.io\nfrom scipy import stats\nimport os, sys\nimport tqdm\nimport pandas as pd\n\ndef find_divisors(n):\n factors=[]\n for i in range(1,n+1):\n if n%i==0:\n factors.append(i)\n k = int(len(factors)/2)\n return n/factors[k], factors[k]\n\ndef plot_raw(data):\n trace = data\n nb_units = trace.shape[1]\n\n #plot the data as a heat map\n fig = plt.figure(1)\n ax = plt.imshow(trace.T,aspect=\"auto\")\n plt.xlabel(\"time (ms)\")\n plt.ylabel(\"Units\")\n plt.title('Raw Data')\n return fig\n\ndef plot_trialframes(trialArray, stim_start):\n nb_units = trialArray.shape[2]\n my_min = np.min(trialArray.mean(1))\n my_max = np.max(trialArray.mean(1))\n # plot units x trials, averaging frames\n fig2 = plt.figure(2)\n ax2 = plt.imshow(trialArray.mean(1).T, aspect=\"auto\", norm = cm.colors.Normalize(my_min, my_max))\n fig2.colorbar(ax2)\n plt.xlabel(\"trials\")\n plt.ylabel(\"units\")\n plt.title('Average activity per trial')\n\n # plot units x frames, averaging trials\n fig3 = plt.figure(3)\n x = stim_start*np.ones(nb_units)\n y = np.linspace(0,nb_units,nb_units)\n plt.plot(x, y, '-r', label = 'stimulus')\n my_min = -0.2\n my_max = 1.8\n ax3 = plt.imshow(trialArray.mean(0).T, aspect=\"auto\", norm = cm.colors.Normalize(my_min, my_max))\n fig3.colorbar(ax3)\n plt.legend(loc='lower right')\n plt.xlabel(\"frames\")\n plt.ylabel(\"units\")\n plt.title('Average Trial Activity')\n dic = {'uxt':fig2, 'uxf':fig3}\n return dic\n\ndef plot_response(exp_data, unit, date, ax):\n '''\n Function that takes compound, date, unit\n and plots the trials in dF/F x time in axis ax\n '''\n data = exp_data.loc[date]\n trials = data.trialArray[:,:,unit]\n avg = np.mean(trials, axis=0)\n\n x = np.ones(trials.shape)*(np.linspace(0,trials.shape[1]-1,trials.shape[1]))\n ax.plot(x,trials, '-', color='0.90')\n ax.plot(x[0], avg,'b-')\n ax.axvline(x=exp_data.stimulus.loc[date], color='r')\n\ndef plotData(data, trialArray, stim_start):\n\n fig = plot_raw(data)\n dic = plot_trialframes(trialArray, stim_start)\n dic['RawData']=fig\n return dic\n\ndef plot_resp_cells(code, exp_data):\n compounds = exp_data.loc[:,'Compound Code']\n dates = exp_data[compounds==code].index\n p_res_code = exp_data.loc[dates, 'percent_response']\n a = pd.concat([r.unstack() for r in p_res_code])\n list = a.index.levels\n fig_list = {}\n for i in list[0]:\n for k in list[1]:\n trials_cells = a[(i,k)].tolist()\n x = np.linspace(1,len(dates),len(dates))\n\n fig = plt.figure()\n plt.ylim(0,100)\n plt.title(i+'_'+k)\n plt.xlabel('Sessions')\n plt.ylabel('Responsive Cells (%)')\n if type(trials_cells) == np.float:\n h = 100*trials_cells\n else:\n h = [100*i for i in trials_cells]\n plt.bar(x, height=h)\n fig_list[code+'_'+i+k]= fig\n return fig_list\n\ndef plot_tracked(exp_data, rois, start1, start2, sample_size, function):\n a, b = find_divisors(rois.shape[0])\n fig = plt.figure(1, figsize=(8*a, 4*b))\n ttest_df = pd.DataFrame(index=exp_data.index, columns=range(rois.shape[0]))\n pvalues_df = pd.DataFrame(index=exp_data.index, columns=range(rois.shape[0]))\n for u in range(rois.shape[0]):\n df_rn = pd.DataFrame()\n df_pre = pd.DataFrame()\n line_pos = []\n for date in exp_data.index:\n unit = rois.loc[u][date]\n frames = exp_data.Data.loc[date]\n u_frames = frames[:,unit]\n start1_d = start1.loc[date].dropna()\n start2_d = start2.loc[date].dropna()\n df1 = pd.DataFrame([u_frames[int(s):(int(s)+sample_size)] for s in start1_d])\n df2 = pd.DataFrame([u_frames[int(s):(int(s)+sample_size)] for s in start2_d])\n res = stats.ttest_rel(function(df1, axis=1), function(df2, axis=1))\n ttest_df.loc[date][u] = res.statistic\n pvalues_df.loc[date][u] = res.pvalue\n df_rn = df_rn.append(df1)\n df_pre = df_pre.append(df2)\n line_pos.append(start1_d.shape[0])\n\n df_plot = pd.concat([df_rn,df_pre], axis=1)\n\n plt.subplot(a,b,u+1)\n x = sample_size*np.ones(df_plot.shape[0]+1)\n y = np.linspace(0,df_plot.shape[0]+1,df_plot.shape[0]+1)\n plt.plot(x, y, '-r', linewidth=1)\n pre_l = 0\n for i, l in enumerate(line_pos):\n ind = l+pre_l\n y = ind*np.ones(df_plot.shape[1]+1)\n x = np.linspace(0,df_plot.shape[1]+1,df_plot.shape[1]+1)\n plt.plot(x, y, '-w', linewidth=0.5)\n pre_l = ind\n if pvalues_df.iloc[i][u]<=0.05:\n plt.text(x[-1]+2,y[i], '*')\n ax = plt.imshow(df_plot, aspect='auto')\n plt.xlabel(\"frames\")\n plt.ylabel(\"trials\")\n plt.title('Tracked Unit %d'%(u+1))\n\n return fig, ttest_df, pvalues_df\n\ndef plot_tracked_unit(unit, exp_data, info_df, rois):\n gb = info_df.groupby('Date')\n order = ['B', 'Y', 'A', 'X']\n grouped = exp_data.groupby('Compound Code')\n\n f = plt.figure(figsize=(28,20))\n f.suptitle('Tracked Unit '+str(unit+1))\n f.add_subplot(111, frameon=False)\n # hide tick and tick label of the big axes\n plt.tick_params(labelcolor='none', top='off', bottom='off', left='off', right='off')\n plt.grid(False)\n plt.xlabel(\"Time\")\n plt.ylabel(\"dF/F\")\n for i, date in enumerate(gb.groups.keys()):\n group = gb.get_group(date)\n group = group.set_index('Compound Code')\n ia = f.add_subplot(1,gb.ngroups,i+1, frameon=False)\n plt.tick_params(labelcolor='none', top='off', bottom='off', left='off', right='off')\n ia.set_title((str(date)+'\\n'+'\\n'), fontweight='bold')\n for c in group.index:\n idx = order.index(c[0])\n sess = group.loc[c]['Session']\n d = (str(date)+'_'+str(sess))\n a = f.add_subplot(len(order), gb.ngroups, idx*gb.ngroups+i+1)\n plot_response(exp_data, rois.iloc[unit].loc[d], d, a)\n a.set_title(c)\n a.set_ylim(-1.5,12.5)\n return f\n\ndef plot_corr(trial_df, title='', b=20):\n corr_matrix = trial_df.corr()\n c = corr_matrix.unstack()\n f = plt.figure(figsize=(10,6))\n f.suptitle('Correlations '+title)\n ax1 = f.add_subplot(121)\n c.plot.hist(bins=b)\n # ax1.set_ylim((0,60))\n f.add_subplot(122)\n plt.imshow(corr_matrix)\n return f, corr_matrix\n\ndef plot_cdf(corr_matrix):\n c = corr_matrix.unstack()\n sorted = np.sort(c)\n h, = plt.plot(sorted,np.linspace(0.,1.,sorted.size))\n return h\n","repo_name":"anabottura/2p_analysis","sub_path":"plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":6737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"32278499905","text":"n=int(input())\n\n\n\n# 재귀 형식으로 구현해보기\n\n# def fibo(n):\n# if n==1 or n==2:\n# return 1\n#\n# print(n)\n# return fibo(n-1)+fibo(n-2)\n#\n# print(fibo(n))\n\n# dp 형식으로 구현해보기\n\ndp = [0]*(46)\ndp[1]=1\ndp[2]=1\nfor i in range(3,n+1):\n dp[i]=dp[i-1]+dp[i-2]\n\nprint(dp[n])","repo_name":"kimth007kim/python_algorithm","sub_path":"bakjoon/난이도별/Chap10 재귀/2747 피보나치 수.py","file_name":"2747 피보나치 수.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"3899615847","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.core.urlresolvers import reverse\nfrom django.contrib import messages\nfrom practice.models import Wordlist, SessionUser, WordProgress, WordlistWord\nfrom practice.forms import QuizQuestionForm, ResetProgressForm\nfrom ipa.models import Word\nfrom django.http import Http404\nfrom django.core.paginator import Paginator, InvalidPage\n\ndef index(request):\n wordlists = Wordlist.objects.all()\n return render(request, 'practice/index.html', {'wordlists': wordlists})\n\ndef wordlists(request, wordlist_id, wordlist_slug=None, page=1):\n user = SessionUser.from_session(request.session)\n wordlist = get_object_or_404(Wordlist, pk=wordlist_id)\n if wordlist.slug != wordlist_slug:\n return redirect(wordlist.get_absolute_url(page=page))\n paginator = Paginator(wordlist.wordlist_words.all(), 10) # 10 words per page\n try:\n page_words = paginator.page(page)\n except InvalidPage:\n return redirect(wordlist)\n\n WordProgress.prepare(user, wordlist)\n reset_url = reverse('practice:reset_progress',\n kwargs={'wordlist_id': wordlist.id, 'wordlist_slug': wordlist.slug}\n )\n reset_form = ResetProgressForm()\n wordlist_progress = WordProgress.progress(user, wordlist)\n # paginator navigation; extend by 2 pages, max of 5 visible\n first = max(1, page_words.number - 2)\n last = min(first + 5, paginator.num_pages)\n page_range = range(first, last + 1)\n return render(request, 'practice/wordlists.html', {\n 'wordlist': wordlist, 'reset_url': reset_url, 'reset_form': reset_form,\n 'wordlist_progress': wordlist_progress, 'page_range': page_range, 'page_words': page_words\n })\n\ndef quiz(request, wordlist_id, wordlist_slug=None):\n wordlist = get_object_or_404(Wordlist, pk=wordlist_id)\n user = SessionUser.from_session(request.session)\n return redirect_next_question(request, user, wordlist)\n\ndef quiz_question(request, wordlist_id, wordlist_slug, q_id):\n '''q_id is 1-based index of words in the wordlist's order'''\n wordlist = get_object_or_404(Wordlist, pk=wordlist_id)\n user = SessionUser.from_session(request.session)\n try:\n word_progress = WordProgress.objects.get(\n user=user, wordlist_word__wordlist=wordlist, wordlist_word__order=(int(q_id) - 1)\n )\n except WordProgress.DoesNotExist:\n raise Http404('Error retreiving quiz data.')\n\n if request.method == 'POST':\n if request.POST['action'] == 'Continue':\n return redirect_next_question(request, user, wordlist)\n else:\n question_form = word_progress.mc_question_form(request)\n if question_form.is_valid():\n word_progress.check_answer(question_form.cleaned_data['input_choice'])\n else:\n question_form = word_progress.mc_question_form(request)\n\n return render(request, 'practice/quiz_question.html',\n {'question_form': question_form, 'word_progress': word_progress}\n )\n\ndef redirect_next_question(request, user, wordlist):\n # redirect to first unsolved q\n try:\n word_progress = WordProgress.get_next_word(user, wordlist)\n except WordProgress.DoesNotExist:\n messages.info(request, 'You have already completed this quiz.')\n return redirect(wordlist)\n else:\n return redirect(word_progress)\n\ndef reset_progress(request, wordlist_id, wordlist_slug=None):\n wordlist = get_object_or_404(Wordlist, pk=wordlist_id)\n user = SessionUser.from_session(request.session)\n if request.method == 'POST':\n form = ResetProgressForm(request.POST)\n if form.is_valid():\n WordProgress.reset_progress(user, wordlist)\n messages.info(request, 'Progress reset')\n return redirect(wordlist)\n messages.error(request, 'Error reseting progress')\n return redirect(wordlist)\n","repo_name":"tjsantos/practiceipa","sub_path":"practice/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"2542322703","text":"#!/usr/bin/python3\n\n\ndef divisible_by_2(my_list=[]):\n \"\"\"Find all Multiples of 2\"\"\"\n\n if (len(my_list) == 0):\n return (None)\n rList = []\n for i in my_list:\n if (i % 2 == 0):\n rList.append(True)\n else:\n rList.append(False)\n return (rList)\n","repo_name":"OluwamayowaMusa/alx-higher_level_programming","sub_path":"0x03-python-data_structures/10-divisible_by_2.py","file_name":"10-divisible_by_2.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"71200816759","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[81]:\n\n\nimport sys\nimport math\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\nimport statistics\nimport networkx as nx\nimport itertools\n\n\nline_numbers=[]\nline_numbers_sp2c=[]\natomindex=[]\nXS=[]\nYS=[]\nZS=[]\nsp2c_coord=[]\n# number is the number of atoms in each pi stacking segment\n#only the atoms one wants to consider/I consider heavy atoms\nnumber = 9\n#number of total monomers in one polymer\npolymer=12\n#number of SP2 carbon in each monomer\nsp2c=4\n#cutoff range to see how parallel are normals to the plane of each monomer\nparallelrange = 0.04\n#cutoff radius for finding possbible CENTROID neighbors\ncutoff = 1.5 #nanometer\n#cutoff distance for pistacks CENTROID in vertical (normal to their plane) and horizental (parallel to their plane)\nverticalcutoff = 0.4 #nanometer\nhorizentalcutoff = 0.5\n#index.ndx is the index file for atoms exist in conjugated structure \n#that one wants to consider/total atoms in index file should be devisible by \"number\"\nindexfilename = input('Enter EDOT heavy atoms index file name: ')\nwith open(indexfilename) as f:\n file_list = f.readlines()\n for item in file_list[1:]:\n index = item.split()\n for i in range(len(index)):\n line_numbers.append(int(index[i])+1)\nif len(line_numbers)%number !=0:\n print('number of atoms in pi-stacking segment does not match the index file')\n sys.exit()\n \nlines = []\nstructurefilename = input('Enter a gro file name: ')\nwith open(structurefilename) as f:\n file_list = f.readlines()\n for i, line in enumerate(file_list):\n if i in line_numbers:\n XS.append(float(line[20:28]))\n YS.append(float(line[28:36]))\n ZS.append(float(line[36:44]))\n \nxs=[]\nys=[]\nzs=[]\nmonomernumber=0\nCENTROID=[]\nNORMAL=[]\nfor i in range(int(len(line_numbers)/number)):\n xs=[]\n ys=[]\n zs=[]\n for j in range(number):\n xs.append(XS[j+i*number])\n ys.append(YS[j+i*number])\n zs.append(ZS[j+i*number])\n tmp_A = []\n tmp_b = []\n for i in range(len(xs)):\n tmp_A.append([xs[i], ys[i], 1])\n tmp_b.append(zs[i])\n b = np.matrix(tmp_b).T\n A = np.matrix(tmp_A)\n\n # Manual solution\n fit = (A.T * A).I * A.T * b\n centroid = [sum(xs) / len(xs), sum(ys) / len(ys), sum(zs) / len(zs)]\n CENTROID.append(centroid)\n normal = [float(fit[0]), float(fit[1]),-1.0]\n tempabs = [abs(ele) for ele in normal]\n normal = [float(fit[0])/max(tempabs), float(fit[1])/max(tempabs),-1.0/max(tempabs)]\n NORMAL.append(normal)\nPARALLEL=[]\nfor i in range(0,len(NORMAL)):\n parallel=[]\n for j in range(0,len(NORMAL)):\n if i!=j and (1.0 - parallelrange) < np.dot(NORMAL[i],NORMAL[j])/(np.linalg.norm(NORMAL[i])*np.linalg.norm(NORMAL[j])) < (1.0 + parallelrange):\n parallel.append(j)\n PARALLEL.append(parallel)\nDISTANCE=[]\nNEIGHBOR=[]\nfor i in range(0,len(CENTROID)):\n distance=[]\n neighbor=[]\n for j in range(0,len(CENTROID)):\n\n if i!=j and math.dist(CENTROID[i],CENTROID[j]) < cutoff:\n if i//polymer != j//polymer:\n neighbor.append(j)\n distance.append(math.dist(CENTROID[i],CENTROID[j]))\n NEIGHBOR.append(neighbor)\n DISTANCE.append(distance)\nPARALLELANDNEIGHBOR=[]\nVERTICALDISTANCE=[]\nHORIZENTALDISTANCE=[]\nfor i in range(0,len(NEIGHBOR)):\n parallelandneighbor=[]\n verticaldistance=[]\n horizentaldistance=[]\n for j in range(0,len(NEIGHBOR[i])):\n for k in range(0,len(PARALLEL[i])):\n if PARALLEL[i][k]==NEIGHBOR[i][j]:\n parallelandneighbor.append(PARALLEL[i][k])\n vector_1 = np.subtract(np.array(CENTROID[i]),np.array(CENTROID[PARALLEL[i][k]]))\n vector_2 = NORMAL[i]\n unit_vector_1 = vector_1 / np. linalg. norm(vector_1)\n unit_vector_2 = vector_2 / np. linalg. norm(vector_2)\n dot_product = np. dot(unit_vector_1, unit_vector_2)\n sine = math.sqrt(1-dot_product**2)\n verticaldistance.append(abs(dot_product)*(np.linalg.norm(np.array(CENTROID[i])-np.array(CENTROID[PARALLEL[i][k]]))))\n horizentaldistance.append(sine*(np.linalg.norm(np.array(CENTROID[i])-np.array(CENTROID[PARALLEL[i][k]]))))\n PARALLELANDNEIGHBOR.append(parallelandneighbor)\n VERTICALDISTANCE.append(verticaldistance)\n HORIZENTALDISTANCE.append(horizentaldistance)\nPISTACKWITHREPEAT=[]\nfor i in range(len(PARALLELANDNEIGHBOR)):\n for j in range(len(PARALLELANDNEIGHBOR[i])):\n PISTACKWITHREPEAT.append([i, PARALLELANDNEIGHBOR[i][j],VERTICALDISTANCE[i][j],HORIZENTALDISTANCE[i][j]])\nPISTACKNOLIMIT=[]\nfor i in range(len(PISTACKWITHREPEAT)-1):\n for j in range(i+1,len(PISTACKWITHREPEAT)):\n if PISTACKWITHREPEAT[i][0]==PISTACKWITHREPEAT[j][1] and PISTACKWITHREPEAT[i][1]==PISTACKWITHREPEAT[j][0]:\n verticaldistance=[PISTACKWITHREPEAT[i][2],PISTACKWITHREPEAT[j][2] ]\n horizentaldistance=[PISTACKWITHREPEAT[i][3],PISTACKWITHREPEAT[j][3] ]\n PISTACKNOLIMIT.append([PISTACKWITHREPEAT[i][0],PISTACKWITHREPEAT[i][1],statistics.mean(verticaldistance),statistics.mean(horizentaldistance)])\nPISTACK=[]\nfor i in range(len(PISTACKNOLIMIT)):\n if PISTACKNOLIMIT[i][2] < verticalcutoff and PISTACKNOLIMIT[i][3] < horizentalcutoff:\n PISTACK.append(PISTACKNOLIMIT[i])\n \natoms=[]\nfor i in range(0,len(PISTACK)):\n for j in range(0,number):\n atoms.append(line_numbers[PISTACK[i][0]*number+j]-1)\n for k in range(0,number):\n atoms.append(line_numbers[PISTACK[i][1]*number+k]-1)\n#writing the index file for the monomers who have at least one pi stacking interaction\nwith open('pistack.ndx', \"w\") as f:\n f.write(\"[ pi stack ]\\n\")\n f.writelines(\"%s\\n\" % l for l in atoms)\n#writing the vertical and horizental distance of pi stacked monomers\nINFO=[]\nPOLYMERREPEAT=[]\nfor i in range(len(PISTACK)):\n pistackline = '{0: <12}'.format(PISTACK[i][0])+'{0: <12}'.format(PISTACK[i][1])+' '+'{:.4f}'.format(PISTACK[i][2])+' '+'{0:.4f}'.format(PISTACK[i][3])\n INFO.append(pistackline)\n POLYMERREPEAT.append(tuple([PISTACK[i][0]//polymer,PISTACK[i][1]//polymer]))\nPOLYMER = list(dict.fromkeys(POLYMERREPEAT))\n#writing the index file for the polymers who are in a pi stacking netwrok\n\nG = nx.Graph(POLYMER)\nNETWORK=list(nx.connected_components(G))\nnetworklist=list(itertools.chain(*NETWORK)) # list of all elements in NETWORK\nwith open('pistack.txt', \"w\") as f:\n f.write(\"ring1 ring2 vertical distance horizental distance \\n\")\n f.writelines(\"%s\\n\" % l for l in INFO)\nwith open('cluster.ndx', \"w\") as f:\n CLUSTER=[]\nfor i in range(len(NETWORK)):\n cluster=[]\n for j in range(len(NETWORK[i])):\n for k in range(polymer*number):\n cluster.append(line_numbers[list(NETWORK[i])[j]*number*polymer+k]-1)\n with open('cluster.ndx', \"a\") as f:\n f.write(\"\\n [ cluster\"+str(i)+\" ] \\n\")\n f.writelines(\"%s\\n\" % l for l in cluster)\nisolatedchains=[x for x in list(range(int(len(line_numbers)/(number*polymer)))) if x not in networklist]\nfor i in range(len(isolatedchains)):\n isolatedatoms=[]\n for j in range(polymer*number):\n isolatedatoms.append(line_numbers[isolatedchains[i]*number*polymer+j]-1)\n with open('isolatedchains.ndx', \"a\") as f:\n f.write(\"\\n [ isolatedchains\"+str(i)+\" ] \\n\")\n f.writelines(\"%s\\t\" % l for l in isolatedatoms) \nwith open('network.txt', \"a\") as f:\n f.write(\"\\n [ Number of pedot networks: \"+str(len(NETWORK))+\" ] \\n\")\n f.writelines(\"%s\\t\" % l for l in NETWORK)\n f.write(\"\\n [ Number of isolated chains: \"+str(len(isolatedchains))+\" ] \\n\")\n f.writelines(\"%s\\t\" % l for l in isolatedchains)\nallnetworks = []\nfor i in range(len(NETWORK)):\n allnetworks.append(list(NETWORK[i]))\nallnetworksnoiso=allnetworks.copy()\nfor i in range(len(isolatedchains)):\n allnetworks.append([isolatedchains[i]])\n\n\n#find number of pi-stack for each polymer couple in each network\nrep = [[] for i in range(0, int(len(line_numbers)/polymer/number))]\nfor i in range(len(PISTACK)):\n rep[PISTACK[i][0]//polymer].append(PISTACK[i][1]//polymer)\nrepetition=[]\nfrom collections import Counter\nfor i in range(len(rep)):\n repetition.append(dict(Counter(rep[i])))\npistackrepetition = [[] for i in range(0, len(allnetworksnoiso))]\nfor i in range(len(allnetworksnoiso)):\n for j in range(len(allnetworksnoiso[i])):\n pistackrepetition[i].append(repetition[allnetworksnoiso[i][j]])\n\nwith open('information.txt', \"w\") as f:\n f.write(\"[averageclustersize(excl isochain) averageclustersize(inc isochain)] \\n\")\n f.write(str(np.average([len(i) for i in NETWORK]))+\" \"+str(np.average([len(i) for i in allnetworks]))+\"\\n\")\n f.write(\"[varclustersize(excl isochain) varclustersize(inc isochain)] \\n\")\n f.write(str(np.var([len(i) for i in NETWORK]))+\" \"+str(np.var([len(i) for i in allnetworks]))+\"\\n\")\n f.write(\"[number of pistack monomer] \\n\")\n f.write(str(len(PISTACK))+'\\n')\n f.write(\"[repetition of polymer couple in each network no isolated chain] \\n\")\n f.writelines(\"%s\\t\" % l for l in pistackrepetition) \nprint('end')\n\n\n","repo_name":"HMakkiMD/PEDOT-PSS","sub_path":"Pistacking-git/pistacking.py","file_name":"pistacking.py","file_ext":"py","file_size_in_byte":9215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"7737282889","text":"class warrior:\n \n def __init__(self,name):\n #instance attributes\n self.name = name\n self._age = 0 #Private by convention (attribute with an underscore means its private variable,\n # mean it can be accessed only inside of its class)\n \n # Using property decorator - getter function\n @property\n def age(self):\n return self._age # getter\n \n @age.setter \n def age(self,age):\n if age > 0:\n self._age = age \n else:\n print(\"Age should be greater than Zero\") # setter\n \n\n \n# creating an instance\nwarrior = warrior(\"warrior1\")\nprint(warrior.name)\n\nwarrior.age = -5\n# Age should be greater than Zero\nprint(warrior.age)\n# 0\n\nwarrior.age = 15\nprint(warrior.age)\n# 15","repo_name":"UKhira/UoM-Python-Programming-2","sub_path":"2. Object Oriented Programming/2.2 OOP Principles 1/1. Encapsulation_in_Python.py","file_name":"1. Encapsulation_in_Python.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"10251765860","text":"'''\nCreated on Jul 5, 2022\n\n@author: braistedjc\n'''\n\nclass RheaCompound(object):\n '''\n classdocs\n '''\n def __init__(self):\n '''\n Constructor\n '''\n self.rampId = \"\"\n \n self.chebiId = \"\"\n \n self.name = \"\"\n \n self.htmlName = \"\"\n \n self.formula = \"\"\n \n self.isCofactor = 0\n \n def rheaCompoundToRecordString(self):\n s = self.chebiId + \"\\t\" + self.name + \"\\t\" + self.htmlName + \"\\t\" + self.formula + \"\\t\" + str(self.isCofactor) + \"\\n\" \n return s\n ","repo_name":"ncats/RaMP-BackEnd","sub_path":"src/rampEntity/RheaCompound.py","file_name":"RheaCompound.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"40"} +{"seq_id":"16103137165","text":"import torch\nimport torch.nn as nn\nfrom layers import TransformerBlock\n\n\nclass VisionTransformer(nn.Module):\n\n def __init__(self, n_images, embed_size, n_classes, heads=5, n_transformers=5):\n super(VisionTransformer, self).__init__()\n\n self.n_transformers = n_transformers\n self.n_classes = n_classes\n\n self.image_embbeding = nn.Linear(embed_size, embed_size)\n self.position_embbeding = nn.Linear(n_images, embed_size)\n self.transformer_block = TransformerBlock(embed_size, heads)\n\n self.linear_to_classes = nn.Linear(embed_size*n_images, n_classes)\n\n def forward(self, x):\n batch, n, embed_size = x.size()\n\n positions = torch.tensor(range(0, n)).float().cuda()\n\n position_embed = self.position_embbeding(positions)\n img_embed = self.image_embbeding(x)\n\n x = position_embed + img_embed\n\n for i in range(self.n_transformers):\n x = self.transformer_block(x, None)\n\n x = x.view(batch, n*embed_size)\n\n x = self.linear_to_classes(x)\n x = torch.softmax(x, dim=1)\n\n return x\n","repo_name":"FilipeSantiago/vit_study","sub_path":"layers/vision_transformer.py","file_name":"vision_transformer.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"72770817081","text":"import numpy as np\nfrom scipy import sparse\n\n# SciPy入門\n\na = sparse.lil_matrix((5,5))\n# <5x5 sparse matrix of type '<class 'numpy.float64'>'\n# with 0 stored elements in LInked List format>\n\na[0,0] = 1\na[1,2] = 2\na[3,4] = 3\na[4,4] = 4\n\na.todense()\n# matrix([[ 1., 0., 0., 0., 0.],\n# [ 0., 0., 2., 0., 0.],\n# [ 0., 0., 0., 0., 0.],\n# [ 0., 0., 0., 0., 3.],\n# [ 0., 0., 0., 0., 4.]])\n\n\nb = a.tocsr()\n# <5x5 sparse matrix of type '<class 'numpy.float64'>'\n# with 4 stored elements in Compressed Sparse Row format>\n\nb.getrow(1).todense()\n# matrix([[ 0., 0., 2., 0., 0.]])\n\nv = np.array([1,2,3,4,5])\na.dot(v)\n# array([ 1., 6., 0., 15., 20.])\n","repo_name":"yukiyan/til","sub_path":"machine_learning/sample_code/scipy_practice.py","file_name":"scipy_practice.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"40"} +{"seq_id":"36847940967","text":"# program that sorts all table numbers i input so i can visit them in order when i go to fanime Lol\r\n# does not check for invalid inputs\r\n\r\ntable_list = list()\r\ntable = int(input('enter table number, enter 000 to quit: '))\r\ntable_list.append(table)\r\n\r\nwhile table != 000:\r\n print('table', table, 'has been added to list')\r\n table = int(input('enter table number, enter 000 to quit: '))\r\n table_list.append(table)\r\n\r\nprint('\\nyou have broken out of the while loop. list will now be sorted')\r\ntable_list.pop() # removes 000 value from the list\r\ntable_list.sort()\r\nprint(table_list, '\\nhave fun at fanime!')","repo_name":"keil4ni/fanimeTables","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"70912539319","text":"from rest_framework import permissions\n\n\nclass IsManagerPermission(permissions.DjangoModelPermissions):\n\n def has_permission(self, request, view):\n if not request.user.groups.filter(name=\"manager\").exists():\n return False\n return super().has_permission(request, view)\n\n","repo_name":"dcjwu/drf_coursera","sub_path":"LittleLemonAPI/permissions.py","file_name":"permissions.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"9867095708","text":"import warnings\n\n# Third party modules.\n\n# Local modules.\n\n# Project modules.\n\n# Globals and constants variables.\n\nclass DataPoint(object):\n def __init__(self):\n pass\n\n def readIDline(self, line):\n start = len('Unknown Specimen No.')\n\n specimenID = int(line[start:])\n\n return specimenID\n\n def readGroupSampleLine(self, line):\n group = line[16:32].strip()\n\n sample = line[42:].strip()\n\n return group, sample\n\n def readNumberCommentLine(self, line):\n number = int(line[16:32].strip())\n\n comment = line[42:].strip()\n\n return number, comment\n\n def readStageLine(self, line):\n stageX = float(line[22:33].strip())\n\n stageY = float(line[36:47].strip())\n\n stageZ = float(line[50:].strip())\n\n return stageX, stageY, stageZ\n\n def readBeamLine(self, line):\n incidentEnergy_keV = float(line[16:24].strip())\n\n probeDiameter = float(line[45:50].strip())\n\n scanOn = line[57:].strip()\n\n if scanOn == 'Off':\n scanOn = False\n else:\n scanOn = True\n\n return incidentEnergy_keV, probeDiameter, scanOn\n\n def readDateline(self, line):\n start = len(' Dated on')\n\n date = line[start:].strip()\n\n return date\n\n def readDetectorLine(self, line):\n detectorType = line[:16].strip()\n\n numberAccumulation = int(line[38:].strip())\n\n return detectorType, numberAccumulation\n\n def readCurrentLine(self, line):\n current_A = float(line[11:].strip())\n\n return current_A\n\n def getPositions(self, lines):\n positions = {}\n\n for line in lines:\n if 'Element Peak(mm)' in line:\n index = lines.index(line)\n positions['intensity'] = (index+1, 0)\n\n if 'Element f(chi)' in line:\n index = lines.index(line)\n positions['correction'] = (index+1, 0)\n positions['intensity'] = (positions['intensity'][0], index)\n\n if 'Element El. Wt%' in line:\n index = lines.index(line)\n positions['concentration'] = (index+1, 0)\n positions['correction'] = (positions['correction'][0], index)\n\n if 'Total:' in line:\n index = lines.index(line)\n positions['total'] = (index, index+1)\n positions['concentration'] = (positions['concentration'][0], index-1)\n\n return positions\n\n def increaseValueIndex(self, valueIndex, values, symbol, label, elementData):\n valueIndex += 1\n\n if valueIndex < len(values) and values[valueIndex] == '?':\n message = \"Suspect value for element %s, %s = %0.4f\" % (symbol, label, elementData[symbol][label])\n warnings.warn(message)\n\n valueIndex += 1\n\n return valueIndex\n\n def readIntensityLines(self, lines, elementData):\n for line in lines:\n line = line.strip()\n\n if len(line) > 0:\n values = line.split()\n\n symbol = values[1]\n\n elementData.setdefault(symbol, {})\n\n elementData[symbol]['id'] = int(values[0])\n\n valueIndex = 2\n\n label = 'peak_mm'\n elementData[symbol][label] = float(values[valueIndex])\n\n valueIndex = self.increaseValueIndex(valueIndex, values, symbol, label, elementData)\n\n label = 'net_cps'\n elementData[symbol][label] = float(values[valueIndex])\n\n valueIndex = self.increaseValueIndex(valueIndex, values, symbol, label, elementData)\n\n label = 'bg-_cps'\n elementData[symbol][label] = float(values[valueIndex])\n\n valueIndex = self.increaseValueIndex(valueIndex, values, symbol, label, elementData)\n\n label = 'bg+_cps'\n elementData[symbol][label] = float(values[valueIndex])\n\n valueIndex = self.increaseValueIndex(valueIndex, values, symbol, label, elementData)\n\n label = 'sd_%%'\n elementData[symbol][label] = float(values[valueIndex])\n\n valueIndex = self.increaseValueIndex(valueIndex, values, symbol, label, elementData)\n\n label = 'dl_ppm'\n elementData[symbol][label] = float(values[valueIndex])\n\n self.increaseValueIndex(valueIndex, values, symbol, label, elementData)\n\n def readCorrectionLines(self, lines, elementData):\n for line in lines:\n line = line.strip()\n\n if len(line) > 0:\n values = line.split()\n\n symbol = values[0]\n\n elementData.setdefault(symbol, {})\n\n valueIndex = 1\n\n label = 'f(chi)'\n elementData[symbol][label] = float(values[valueIndex])\n\n valueIndex = self.increaseValueIndex(valueIndex, values, symbol, label, elementData)\n\n label = 'If/Ip'\n elementData[symbol][label] = float(values[valueIndex])\n\n valueIndex = self.increaseValueIndex(valueIndex, values, symbol, label, elementData)\n\n label = 'abs-el'\n elementData[symbol][label] = float(values[valueIndex])\n\n valueIndex = self.increaseValueIndex(valueIndex, values, symbol, label, elementData)\n\n label = '1/s-el'\n elementData[symbol][label] = float(values[valueIndex])\n\n valueIndex = self.increaseValueIndex(valueIndex, values, symbol, label, elementData)\n\n label = 'r-el'\n elementData[symbol][label] = float(values[valueIndex])\n\n valueIndex = self.increaseValueIndex(valueIndex, values, symbol, label, elementData)\n\n label = 'c/k-el'\n elementData[symbol][label] = float(values[valueIndex])\n\n valueIndex = self.increaseValueIndex(valueIndex, values, symbol, label, elementData)\n\n label = 'c/k-std'\n elementData[symbol][label] = float(values[valueIndex])\n\n self.increaseValueIndex(valueIndex, values, symbol, label, elementData)\n\n def readConcentrationLines(self, lines, elementData):\n for line in lines:\n line = line.strip()\n\n if len(line) > 0:\n values = line.split()\n\n symbol = values[0]\n\n elementData.setdefault(symbol, {})\n\n valueIndex = 1\n\n label = 'El fw'\n elementData[symbol][label] = float(values[valueIndex])\n\n valueIndex = self.increaseValueIndex(valueIndex, values, symbol, label, elementData)\n\n label = 'Ox fw'\n elementData[symbol][label] = float(values[valueIndex])\n\n valueIndex = self.increaseValueIndex(valueIndex, values, symbol, label, elementData)\n\n label = 'Norm El'\n elementData[symbol][label] = float(values[valueIndex])\n\n valueIndex = self.increaseValueIndex(valueIndex, values, symbol, label, elementData)\n\n label = 'Norm Ox'\n elementData[symbol][label] = float(values[valueIndex])\n\n valueIndex = self.increaseValueIndex(valueIndex, values, symbol, label, elementData)\n\n label = 'Atomic'\n elementData[symbol][label] = float(values[valueIndex])\n\n valueIndex = self.increaseValueIndex(valueIndex, values, symbol, label, elementData)\n\n label = 'k-value'\n elementData[symbol][label] = float(values[valueIndex])\n\n valueIndex = self.increaseValueIndex(valueIndex, values, symbol, label, elementData)\n\n label = 'k-std'\n elementData[symbol][label] = float(values[valueIndex])\n\n self.increaseValueIndex(valueIndex, values, symbol, label, elementData)\n\n def readTotalLines(self, lines, elementData):\n values = lines[0][7:].split()\n\n elementData['total'] = {}\n\n elementData['total']['El fw'] = float(values[0])\n\n elementData['total']['Ox fw'] = float(values[1])\n\n elementData['total']['Norm El'] = float(values[2])\n\n elementData['total']['Norm Ox'] = float(values[3])\n\n elementData['total']['Atomic'] = float(values[4])\n\n def readLines(self, lines):\n # pylint: disable-msg=W0201\n lineIndex = 0\n self.spectrumID = self.readIDline(lines[lineIndex])\n\n lineIndex += 1\n self.group, self.sample = self.readGroupSampleLine(lines[lineIndex])\n\n lineIndex += 1\n self.number, self.comment = self.readNumberCommentLine(lines[lineIndex])\n\n lineIndex += 1\n self.stageX, self.stageY, self.stageZ = self.readStageLine(lines[lineIndex])\n\n lineIndex += 1\n self.incidentEnergy_keV, self.probeDiameter, self.scanOn = self.readBeamLine(lines[lineIndex])\n\n lineIndex += 1\n self.date = self.readDateline(lines[lineIndex])\n\n lineIndex += 1\n self.detectorType, self.numberAccumulation = self.readDetectorLine(lines[lineIndex])\n\n lineIndex += 1\n\n lineIndex += 1\n self.current_A = self.readCurrentLine(lines[lineIndex])\n\n lineIndex += 1\n positions = self.getPositions(lines)\n\n self.elementData = {}\n\n start, end = positions['intensity']\n self.readIntensityLines(lines[start:end], self.elementData)\n\n start, end = positions['correction']\n self.readCorrectionLines(lines[start:end], self.elementData)\n\n start, end = positions['concentration']\n self.readConcentrationLines(lines[start:end], self.elementData)\n\n start, end = positions['total']\n self.readTotalLines(lines[start:end], self.elementData)\n\n return self.spectrumID\n\n def getValue(self, label, symbol=None):\n if symbol == None:\n if label == 'id':\n return self.spectrumID\n\n if label == 'group':\n return self.group\n\n if label == 'sample':\n return self.sample\n\n if label == 'number':\n return self.number\n\n if label == 'comment':\n return self.comment\n\n if label == 'stageX':\n return self.stageX\n\n if label == 'stageY':\n return self.stageY\n\n if label == 'stageZ':\n return self.stageZ\n\n if label == 'incidentEnergy_keV':\n return self.incidentEnergy_keV\n\n if label == 'probeDiameter':\n return self.probeDiameter\n\n if label == 'scanOn':\n return self.scanOn\n\n if label == 'date':\n return self.date\n\n if label == 'detectorType':\n return self.detectorType\n\n if label == 'numberAccumulation':\n return self.numberAccumulation\n\n if label == 'current_A':\n return self.current_A\n\n elif symbol in self.elementData:\n if symbol == 'total':\n if label in self.elementData['total']:\n return self.elementData['total'][label]\n else:\n if label in self.elementData[symbol]:\n return self.elementData[symbol][label]\n\n return 0.0\n\nclass JEOL8900McGill(object):\n def __init__(self, filename):\n self.points = None\n self.masterHeader = None\n\n self.readResultsFile(filename)\n\n def readResultsFile(self, filename):\n lines = open(filename, 'r').readlines()\n\n pointsIndex = []\n\n for line in lines:\n #line = line.strip()\n\n if 'Intensity' in line:\n self.readMasterHeader(line)\n\n if 'Unknown Specimen No.' in line:\n pointsIndex.append(lines.index(line))\n\n if len(line) == 0:\n #print line\n pass\n\n self.points = {}\n\n for index in pointsIndex:\n #print \"Points:\"\n #print lines[index:index+30]\n self.readPointData(lines[index:index+30])\n\n #print len(pointsIndex)\n\n return len(lines)\n\n def readPointData(self, lines):\n point = DataPoint()\n\n spectrumID = point.readLines(lines)\n\n self.points[spectrumID] = point\n\n def readMasterHeader(self, line):\n keywords = ['Intensity', 'Group', 'Sample', 'Page']\n\n positionKeywords = []\n\n for keyword in keywords:\n position = line.find(keyword)\n\n positionKeywords.append(position)\n\n self.masterHeader = {}\n\n# start = 0\n# for index,keyword in enumerate(keywords[:-1]):\n# end = positions[index+1]\n# values = line[start:end].split(':')\n\n def getValuesList(self, label, symbol=None):\n ids = self.points.keys()\n ids.sort()\n\n values = []\n\n for spectrumID in ids:\n if symbol == None:\n value = self.points[spectrumID].getValue(label)\n\n values.append(value)\n elif symbol != None:\n value = self.points[spectrumID].getValue(label, symbol)\n\n values.append(value)\n\n return ids, values\n\ndef run():\n filename = \"/home/hdemers/works/results/experiments/epma/mcgill/data0407.ful\"\n\n linescanFile = JEOL8900McGill(filename)\n\n keys = linescanFile.points.keys()\n keys.sort()\n\n print(keys, len(keys))\n\nif __name__ == '__main__': # pragma: no cover\n run()\n","repo_name":"drix00/microanalysis_file_format","sub_path":"pySpectrumFileFormat/EPMA/JEOL8900McGill.py","file_name":"JEOL8900McGill.py","file_ext":"py","file_size_in_byte":13571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"2749519863","text":"import json\nimport boto3\nimport datetime\nfrom datetime import timezone\n\n\ndef lambda_handler(event, context):\n dynamodb = boto3.resource('dynamodb')\n table = dynamodb.Table('MerchantRiskData')\n response = table.scan(AttributesToGet=['merchantIdentifier'])\n data = response['Items']\n while 'LastEvaluatedKey' in response:\n response = table.scan(AttributesToGet=[\n 'merchantIdentifier'], ExclusiveStartKey=response['LastEvaluatedKey'])\n data.extend(response['Items'])\n\n print(len(data))\n\n temp_date = str(datetime.datetime.now(timezone.utc)).split(\" \")\n temp_date = \"T\".join(temp_date).split(\"+\")[0]\n date = temp_date + \"Z[UTC]\"\n print(date)\n for item in data:\n table.update_item(\n Key={\n 'merchantIdentifier': item[\"merchantIdentifier\"]\n },\n UpdateExpression='SET lastUpdatedDate = :val1',\n ExpressionAttributeValues={\n ':val1': date\n }\n )\n","repo_name":"kapsky5/Scripts","sub_path":"updating_all_items_in_ddb.py","file_name":"updating_all_items_in_ddb.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"39340360533","text":"import requests\nfrom twilio.rest import Client\nimport os\n\nOWM_ENDPOINT = \"https://api.openweathermap.org/data/2.5/onecall\"\napi_key = \"\"\naccount_sid = \"\"\nauth_token = \"\"\n\nweather_params = {\n \"lat\": 22.396427,\n \"lon\": 114.109497,\n \"appid\": api_key,\n \"exclude\": \"current,minutely,daily\"\n}\n\nresponse = requests.get(OWM_ENDPOINT, params=weather_params)\nresponse.raise_for_status()\nweather_data = response.json()\nweather_slice = weather_data['hourly'][:12]\n\n\ndef check_rain():\n weather_codes = [hour_data['weather'][0]['id'] for hour_data in weather_slice]\n bring_umbrella = False\n for code in weather_codes:\n if code < 700:\n bring_umbrella = True\n return bring_umbrella\n\n\nif check_rain():\n client = Client(account_sid, auth_token)\n message = client.messages \\\n .create(\n body=\"It's going to rain today. Bring an umbrella ☔️\",\n from_='',\n to=''\n )\n print(message.status)\n","repo_name":"rachanahegde/python-pro-bootcamp-intermediate-plus-projects","sub_path":"day-35-rain-alert/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"11628142016","text":"import numpy as np\nimport sys\nimport os\nimport pickle\nimport random\nfrom PIL import Image\nDATADIR = '/Users/johnathanxie/Documents/Python/datasets/dogs-vs-cats/train'\nCATEGORIES = [\"Dog\", \"Cat\"]\ntrain_batch=list(range(0, 12500))\nval_batch=[]\nx_train, y_train, x_val, y_val=[], [], [], []\nvals=list(range(12500))\nrandom.shuffle(vals)\n\nfor i in range(3125):\n train_batch.remove(vals[i])\n val_batch.append(vals[i])\nfor i in train_batch:\n print(i)\n path=os.path.join(DATADIR, \"cat.\" + str(i) + \".jpg\")\n img=Image.open(path, 'r').convert(\"RGB\")\n img=img.resize((200, 200))\n x_train.append(np.asarray(img))\n y_train.append(0)\nfor i in train_batch:\n print(i)\n path=os.path.join(DATADIR, \"dog.\" + str(i) + \".jpg\")\n img=Image.open(path, 'r').convert(\"RGB\")\n img=img.resize((200, 200))\n x_train.append(np.asarray(img))\n y_train.append(1)\n\nx_train=np.asarray(x_train)\ny_train=np.asarray(y_train)\nx_train_file = open('/Users/johnathanxie/Documents/Python/datasets/dogs-vs-cats/x_train', \"wb\")\ny_train_file = open('/Users/johnathanxie/Documents/Python/datasets/dogs-vs-cats/y_train', \"wb\")\npickle.dump(x_train, x_train_file)\npickle.dump(y_train, y_train_file)\nx_train_file.close()\ny_train_file.close()\n\ndel x_train\ndel y_train\nfor i in val_batch:\n print(i)\n path=os.path.join(DATADIR, \"cat.\" + str(i) + \".jpg\")\n img=Image.open(path, 'r').convert(\"RGB\")\n img=img.resize((200, 200))\n x_val.append(np.asarray(img))\n y_val.append(0)\nfor i in val_batch:\n print(i)\n path=os.path.join(DATADIR, \"dog.\" + str(i) + \".jpg\")\n img=Image.open(path, 'r').convert(\"RGB\")\n img=img.resize((200, 200))\n x_val.append(np.asarray(img))\n y_val.append(1)\n\nx_val=np.asarray(x_val)\ny_val=np.asarray(y_val)\nx_val_file = open('/Users/johnathanxie/Documents/Python/datasets/dogs-vs-cats/x_val', \"wb\")\ny_val_file = open('/Users/johnathanxie/Documents/Python/datasets/dogs-vs-cats/y_val', \"wb\")\npickle.dump(x_val, x_val_file)\npickle.dump(y_val, y_val_file)\nx_val_file.close()\ny_val_file.close()\n","repo_name":"Johnathan-Xie/cat_or_dog","sub_path":"cat_or_dog/catvdog_parse.py","file_name":"catvdog_parse.py","file_ext":"py","file_size_in_byte":2033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"73886524921","text":"import sys\n\n\ndef rl():\n return sys.stdin.readline().strip()\n\n\ndef rn():\n return list(map(int, sys.stdin.readline().strip().split()))\n\n\ndef rln(n):\n l = [None] * n\n for i in range(n):\n l[i] = int(rl())\n return l\n\n\ndef letter_maj_to_int(letter):\n return ord(letter) - ord('A')\n\n\nclass UnionFind:\n \"\"\"Weighted quick-union with path compression.\n The original Java implementation is introduced at\n https://www.cs.princeton.edu/~rs/AlgsDS07/01UnionFind.pdf\n >>> uf = UnionFind(10)\n >>> for (p, q) in [(3, 4), (4, 9), (8, 0), (2, 3), (5, 6), (5, 9),\n ... (7, 3), (4, 8), (6, 1)]:\n ... uf.union(p, q)\n >>> uf._id\n [8, 3, 3, 3, 3, 3, 3, 3, 3, 3]\n >>> uf.find(0, 1)\n True\n >>> uf._id\n [3, 3, 3, 3, 3, 3, 3, 3, 3, 3]\n \"\"\"\n\n def __init__(self, n):\n self._id = list(range(n))\n self._sz = [1] * n\n\n def root(self, i):\n j = i\n while j != self._id[j]:\n self._id[j] = self._id[self._id[j]]\n j = self._id[j]\n return j\n\n def find(self, p, q):\n return self.root(p) == self.root(q)\n\n def union(self, p, q):\n i = self.root(p)\n j = self.root(q)\n if i == j:\n return\n if self._sz[i] < self._sz[j]:\n self._id[i] = j\n self._sz[j] += self._sz[i]\n else:\n self._id[j] = i\n self._sz[i] += self._sz[j]\n\n def get_size(self):\n return self._sz\n\n def get_id(self):\n return self._id\n\n def __str__(self):\n res = ' | '.join(map(str, range(len(self._id))))\n res += '\\n'\n res += ' | '.join(map(str, self._id))\n res += '\\n'\n res += ' | '.join(map(str, self._sz))\n return res\n\n\ndef solve():\n contiguous = {}\n edges = []\n actual = 0\n\n #edges\n for line in sys.stdin:\n if line[0] == '*':\n break\n line = line.strip().replace('(', '').replace(')', '').split(',')\n if line[0] in contiguous:\n p = contiguous[line[0]]\n else:\n p = actual\n contiguous[line[0]] = p\n actual += 1\n\n if line[1] in contiguous:\n q = contiguous[line[1]]\n else:\n q = actual\n contiguous[line[1]] = q\n actual += 1\n edges.append((p, q))\n\n #vertex\n line = sys.stdin.readline().strip().split(',')\n uf = UnionFind(len(line))\n for (p, q) in edges:\n uf.union(p, q)\n\n #ans\n acorn,tree = 0,0\n for i in range(len(line)):\n if i == uf.root(i) and uf.get_size()[i] == 1:\n acorn += 1\n elif i == uf.root(i) and uf.get_size()[i] > 1:\n tree += 1\n print('There are {} tree(s) and {} acorn(s).'.format(tree,acorn))\n\n\nif __name__ == '__main__':\n test = int(sys.stdin.readline())\n for _ in range(test):\n solve()\n","repo_name":"jaxalo/UVA","sub_path":"DS/DSOL/Graph/UVA599_The_Forrest_for_the_Trees.py","file_name":"UVA599_The_Forrest_for_the_Trees.py","file_ext":"py","file_size_in_byte":2925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"5589172631","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Dec 30 09:58:42 2016\n\n@author: zzpp220\n\"\"\"\n''' this script is to seperate the tot.efr.y output from trainefr into the cooresponde num in file'''\nimport re,os\n\nsnumber=[430,442,458,470]\npath=r'/media/zzpp220/Data/Linux_Documents/Mobile/ILP/chain6.0/SCUTPHONE/bn_gmsv/bn_gmsv8'\ntot_efr=open(os.path.join(path,'scut-208-500-500-13-21-8tot_cat.efr_52.y'),'r')\nfor num in snumber:\n flag=open(os.path.join(path,'scut_test_chain'+str(num)+'.efr.y'),'w')\n \n for line in range(num):\n line_coor=tot_efr.readline()\n line_nolabel=re.sub('#\\w','',line_coor)\n flag.write(line_nolabel)\n flag.close()\ntot_efr.close()","repo_name":"zXpp/Templates","sub_path":"sep_mibile.py","file_name":"sep_mibile.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"44139966220","text":"# number of nodes in the graph\r\nn = int(input())\r\n\r\n# number of edges in the graph\r\nm = int(input())\r\n\r\n# adjacency list of the graph\r\ngraph = [[] for i in range(n + 1)]\r\n\r\nfor i in range(m):\r\n u, v = list(map(int, input().split())) # input edge\r\n # Assuming graph to be undirected.\r\n graph[u].append(v)\r\n graph[v].append(u)\r\n\r\nvisited = [False for i in range(n + 1)]\r\ntin = [-1 for i in range(n+1)]\r\nlow = [-1 for i in range(n+1)]\r\ntime = 0\r\n\r\n\r\ndef dfs(node, parent):\r\n global time\r\n\r\n # marking node as visited.\r\n visited[node] = True\r\n tin[node] = time\r\n low[node] = time\r\n time += 1\r\n for neighbour in graph[node]:\r\n if neighbour == parent:\r\n continue\r\n if visited[neighbour] == True:\r\n low[node] = min(low[node], tin[neighbour])\r\n else:\r\n dfs(neighbour, node)\r\n low[node] = min(low[node], low[neighbour])\r\n if low[neighbour] > tin[node]:\r\n print(node, neighbour, 'is a bridge')\r\n\r\n\r\nfor i in range(n):\r\n if visited[i] == False:\r\n dfs(i, -1)","repo_name":"shivu926/NTU-Research","sub_path":"Rough_code/bridge.py","file_name":"bridge.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"27067130707","text":"def collatz(number):\n if number%2==0:\n print(number//2)\n return number//2\n elif number%2==1:\n print(3 * number + 1) \n return 3 * number + 1\n \n#main program\n\n#if __name__==\"__main__\":\nnumber=int(input())\nwhile number>1: \n collatz(number)\n \n","repo_name":"prasha1596/PyWorkSpace","sub_path":"Collatz.py","file_name":"Collatz.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"70210315321","text":"import h5py\nimport tensorflow.keras as keras\nimport tensorflow as tf\nimport numpy as np\nimport pickle\nimport argparse\nimport util\n\nnp.random.seed(1)\ntf.random.set_seed(1)\n\nimport PIL, PIL.Image\n\nWORK_PATH = './gen-task/'\nEPOCHS = 60\n\ndef generate_task(infile, experiment, run_test_set, save_weights, weightfile, tmp_dir):\n \"\"\"\n Model definition: tower network on basis letters to get autoencoding, feed \n through shared dense layers to retrieve all 26 letters (caps)\n \"\"\"\n # Input\n X = keras.layers.Input(shape=(4, 64, 64), name='input')\n\n # Lambda layers pull out the 4 basis characters\n x1 = keras.layers.Lambda(lambda x: x[:, 0, :, :], output_shape=(64, 64), name='x1')(X)\n x2 = keras.layers.Lambda(lambda x: x[:, 1, :, :], output_shape=(64, 64), name='x2')(X)\n x3 = keras.layers.Lambda(lambda x: x[:, 2, :, :], output_shape=(64, 64), name='x3')(X)\n x4 = keras.layers.Lambda(lambda x: x[:, 3, :, :], output_shape=(64, 64), name='x4')(X)\n\n # Flatten the images into 64 * 64 dimensional vectors\n x1 = keras.layers.Flatten()(x1)\n x2 = keras.layers.Flatten()(x2)\n x3 = keras.layers.Flatten()(x3)\n x4 = keras.layers.Flatten()(x4)\n\n # The towers consist of a fully connected layer\n neurons = 32 if experiment == 2 or experiment == 4 or experiment == 5 else 16\n x1 = keras.layers.Dense(neurons, activation='relu')(x1)\n x2 = keras.layers.Dense(neurons, activation='relu')(x2)\n x3 = keras.layers.Dense(neurons, activation='relu')(x3)\n x4 = keras.layers.Dense(neurons, activation='relu')(x4)\n if experiment == 3 or experiment == 4 or experiment == 5:\n x1 = keras.layers.Dense(neurons, activation='relu')(x1)\n x2 = keras.layers.Dense(neurons, activation='relu')(x2)\n x3 = keras.layers.Dense(neurons, activation='relu')(x3)\n x4 = keras.layers.Dense(neurons, activation='relu')(x4)\n\n # Concatenates the towers together and feed through fully connected layers\n added = keras.layers.Concatenate()([x1, x2, x3, x4])\n neurons = 400 if experiment == 2 or experiment == 3 or experiment == 5 else 200\n fc = keras.layers.Dense(neurons, activation='relu')(added)\n fc = keras.layers.Dense(neurons, activation='relu')(fc)\n if experiment == 3 or experiment == 4 or experiment == 5:\n fc = keras.layers.Dense(neurons, activation='relu')(fc)\n fc = keras.layers.Dense(26 * 64 * 64, activation='relu')(fc)\n\n # Reshape for 2D convolution and upsample\n fc = keras.layers.Reshape((26, 64, 64))(fc)\n if experiment == 0:\n fc = keras.layers.Conv2DTranspose(26, data_format='channels_first', kernel_size=(4, 4), padding='same', activation='relu')(fc)\n fc = keras.layers.Conv2DTranspose(26, data_format='channels_first', kernel_size=(4, 4), padding='same', activation='relu')(fc)\n elif experiment == 2 or experiment == 3 or experiment == 4 or experiment == 5:\n fc = keras.layers.Conv2DTranspose(26, data_format='channels_first', kernel_size=(4, 4), padding='same', activation='relu')(fc)\n else:\n pass # No convolutional layers\n\n out = fc\n\n model = keras.models.Model(inputs=X, outputs=out)\n model.compile(optimizer='adam', loss='mean_squared_error', metrics=[])\n model.summary()\n\n # Plotting\n # keras.utils.plot_model(model, to_file='model.png')\n # exit()\n\n if weightfile is not None:\n model.load_weights('./gen-task/{}.hdf5'.format(weightfile))\n\n namespace = util.namespace(infile, experiment)\n\n def dump_history(history):\n with open('{}/{}history.pickle'.format(WORK_PATH, namespace), 'wb') as f:\n pickle.dump(history, f)\n print('Dumped history.')\n\n # Open and prepare training set\n train = h5py.File('./gen-task-dsets/gen-task-{}-train.hdf5'.format(infile), 'r')\n outputs = train['outputs'][:]\n basis = train['basis'][:]\n\n print('Training model on {} fonts...'.format(train['basis'].shape[0]))\n\n def display_picture(arr, name):\n img = PIL.Image.fromarray(np.hstack([arr[idx] for idx in range(26)]))\n if img.mode != 'L':\n img = img.convert('L')\n # img.show() # Debug (disable when running)\n img.save('./{}/{}{}.png'.format(tmp_dir, namespace, name))\n\n class ImageHistory(keras.callbacks.Callback):\n \"\"\"\n Runs predict on the model and test set to visualize how the \n NN is learning. In a Keras callback, we have access to model\n and params as class properties.\n \"\"\"\n def __init__(self):\n super() # Parent class constructor\n self.image_idx = 0\n\n def on_train_begin(self, logs={}):\n predictions = self.model.predict(basis[:1])\n display_picture(predictions[0], 'train-viz-{}'.format(self.image_idx))\n self.image_idx += 1\n\n def on_batch_end(self, batch, logs={}):\n predictions = self.model.predict(basis[:1])\n display_picture(predictions[0], 'train-viz-{}'.format(self.image_idx))\n self.image_idx += 1\n\n history = model.fit(x=basis, y=outputs, epochs=EPOCHS, batch_size=512, callbacks=[ImageHistory()]) # See Keras docs for the history object\n dump_history(history.history)\n if save_weights:\n model.save_weights('./gen-task/{}weights.hdf5'.format(namespace))\n\n\n # Open and prepare val set\n test = h5py.File('./gen-task-dsets/gen-task-{}-val.hdf5'.format(infile), 'r')\n outputs = test['outputs'][:]\n basis = test['basis'][:]\n\n print('Validating model on {} fonts...'.format(test['basis'].shape[0]))\n loss = model.evaluate(x=basis, y=outputs)\n\n # View classified examples from the validation set\n predictions = model.predict(basis)\n display_picture(predictions[0], 'val')\n\n if run_test_set:\n # Open and prepare test set\n test = h5py.File('./gen-task-dsets/gen-task-{}-test.hdf5'.format(infile), 'r')\n outputs = test['outputs'][:]\n basis = test['basis'][:]\n\n print('Testing model on {} fonts...'.format(test['basis'].shape[0]))\n loss = model.evaluate(x=basis, y=outputs)\n\n # View classified examples from the validation set\n predictions = model.predict(basis)\n display_picture(predictions[0], 'test')\n\n\ndef parse_args():\n DEFAULT_FILENAME = 'fonts-50'\n parser = argparse.ArgumentParser(description='Run generative task.')\n parser.add_argument('--infile', '-i', default=DEFAULT_FILENAME, help='Name of data infile.')\n parser.add_argument('--experiment', '-e', default=0, type=int, help='Experiment number.')\n parser.add_argument('--test', '-t', action='store_true', help='Run test set (default: False).')\n parser.add_argument('--save_weights', '-s', action='store_true', help='Save weights (default: False).')\n parser.add_argument('--load_weights', '-w', help='Load weights from hdf5 file (default: None).')\n parser.add_argument('--tmp_dir', '-dir', default='tmp', help='Temp dir to dump info (default: tmp).')\n\n return parser.parse_args()\n\n\"\"\"\npython nn_generate_mt.py -i fonts-all-2908 -e 0\n\"\"\"\ndef main():\n args = parse_args()\n generate_task(args.infile, args.experiment, args.test, args.save_weights, args.load_weights, args.tmp_dir)\n \n\nif __name__ == '__main__':\n main()\n","repo_name":"garrickf/font-gen","sub_path":"nn_generate_mt.py","file_name":"nn_generate_mt.py","file_ext":"py","file_size_in_byte":7220,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"35125531427","text":"#!/usr/bin/env python\n\n\"\"\"Create Google API credentials\n\nUsage:\n google_api_auth.py [NAME]\n\nOptions:\n -h --help Show usage\n\n\"\"\"\nfrom __future__ import print_function\n\nimport os.path\nimport sys\n\nfrom docopt import docopt\nfrom flask import Flask\nfrom oauth2client.client import OAuth2WebServerFlow\nfrom oauth2client.file import Storage\nfrom oauth2client.tools import run\n\napp = Flask(__name__, instance_relative_config=True,\n instance_path=os.path.abspath(os.path.join(\n os.path.dirname(__file__), '..', 'app')))\napp.config.from_envvar('JARVIS_SETTINGS')\n\n\ndef get_config(name):\n return app.config['JOBS'][name]\n\n\ndef create_credentials(name):\n config = get_config(name)\n if 'client_id' not in config \\\n or 'client_secret' not in config:\n print ('Error: client_id, client_secret is not set.\\n\\n'\n 'Please create a client ID here and update '\n 'config.py:\\n\\nhttps://code.google.com/apis/console/#:access')\n sys.exit(1)\n\n FLOW = OAuth2WebServerFlow(\n client_id=config['client_id'],\n client_secret=config['client_secret'],\n scope='https://www.googleapis.com/auth/{}.readonly'.format(name))\n\n credentials_file = os.path.join(app.instance_path, 'jobs',\n '.{}.json'.format(name))\n storage = Storage(credentials_file)\n credentials = storage.get()\n if credentials is None or credentials.invalid:\n credentials = run(FLOW, storage)\n else:\n print('Google API credentials already exist: %s' % (credentials_file,))\n\n\ndef main():\n args = docopt(__doc__)\n name = args['NAME']\n\n if name is None:\n name = raw_input(('Enter widget to generate credentials for (gmail'\n ' or calendar): '))\n\n if name not in ('calendar', 'gmail'):\n print('Name must be either \\'gmail\\' or \\'calendar\\'')\n sys.exit(1)\n\n create_credentials(name)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Foxboron/Frank","sub_path":"support/google_api_auth.py","file_name":"google_api_auth.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"40"} +{"seq_id":"29270297108","text":"from datetime import datetime\n\nfrom chalk import online\nfrom chalk.client import ChalkClient, OnlineQueryContext\nfrom chalk.features import features, DataFrame, Features, has_many\nfrom chalk.sql import MySQLSource, PostgreSQLSource\n\n\n@features\nclass WatchSession:\n id: int\n ended_at: datetime\n started_at: datetime\n user_id: int\n duration_seconds: float\n\n\n@features\nclass User:\n id: int\n count_long_sessions: int\n sessions: DataFrame[WatchSession] = has_many(lambda: WatchSession.user_id == User.id)\n\n\n# Imagine that we have two video streaming customers, HBO and Disney.\n# Disney has given us credentials to their PostgreSQL database, and\n# HBO to their MySQL database. We can reference these integrations\n# via named sources, and add the secrets through the Chalk dashboard.\n# Those secrets will only be available in the environments in which\n# they are configured, so there is no chance of accidentally using\n# the Disney PostgreSQL database in the HBO environment.\ndisney_pg = PostgreSQLSource(name=\"disney\")\nhbo_mysql = MySQLSource(name=\"hbo\")\n\n\n# Now, we can write resolvers specific to our customers: one for Disney\n# and one for HBO.\n@online(environment=\"disney\")\ndef get_disney_sessions_for_user(\n u: User.id,\n) -> DataFrame[WatchSession.id, WatchSession.ended_at, WatchSession.started_at]:\n return disney_pg.query_string(\n \"SELECT * FROM sessions where user_id = :user_id\",\n args={\"user_id\": u},\n fields={\n \"id\": WatchSession.id,\n \"completed_at\": WatchSession.ended_at,\n \"began_at\": WatchSession.started_at,\n },\n ).all()\n\n\n@online(environment=\"hbo\")\ndef get_hbo_sessions_for_user(\n u: User.id,\n) -> Features[WatchSession.id, WatchSession.ended_at, WatchSession.started_at]:\n return hbo_mysql.query_string(\n \"SELECT * FROM show_views where uid = :user_id\",\n args={\"user_id\": u},\n fields={\n \"id\": WatchSession.id,\n \"ended\": WatchSession.ended_at,\n \"started\": WatchSession.started_at,\n },\n ).all()\n\n\n# These function is shared between all environments.\n# Each of these resolvers is deployed into each of\n# the environments, but no data is shared between\n# the environments. This pattern allows for consolidation\n# of your complicated business logic on top of a\n# unified schema while maintaining strict isolation\n# of data.\n@online\ndef get_duration_watched(\n started: WatchSession.started_at, ended: WatchSession.ended_at\n) -> WatchSession.duration_seconds:\n return (ended - started).total_seconds()\n\n\n@online\ndef num_long_sessions(\n long_sessions: User.sessions[WatchSession.duration_seconds > 3600],\n) -> User.count_long_sessions:\n return long_sessions.count()\n\n\n# When you go to make a query, you can specify the\n# environment in which to evaluate the query, which will\n# determine which cluster to send your query to.\nChalkClient().query(\n input={User.id: 123},\n output=[User.count_long_sessions],\n context=OnlineQueryContext(environment=\"hbo\"),\n)\n\n# You can also scope your access tokens to an environment,\n# and don't need to specify an environment id when the\n# token is valid in only one environment.\n#\n# For example, here the client_id and client_secret could\n# be scoped to the \"disney\" environment.\nChalkClient(client_id=\"...\", client_secret=\"...\").query(\n input={User.id: 345},\n output=[User.count_long_sessions],\n)\n","repo_name":"chalk-ai/examples","sub_path":"02_resolvers/7_multi_tenancy.py","file_name":"7_multi_tenancy.py","file_ext":"py","file_size_in_byte":3426,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"7660658240","text":"import re\nimport datetime\nimport time\nimport math\nimport pandas as pd\ndef get_user_id(user):\n return user['id']\n\ndef get_username(user):\n return user['username']\n \n \ndef get_screen_name(user):\n return user['name']\n \n \ndef has_description(user):\n des = user['description']\n if des is None or des == ' ':\n return False\n else:\n return True\n \n \ndef get_statuses(user):\n tweets = user['public_metrics']['tweet_count']\n if tweets is None:\n return 0\n else:\n return int(tweets)\n \n \ndef get_followers(user):\n followers_count = user['public_metrics']['followers_count']\n if followers_count is None:\n return 0\n else:\n return int(followers_count)\n \ndef get_friends(user):\n following_count = user['public_metrics']['following_count']\n if following_count is None:\n return 0\n else:\n return int(following_count) \n \n \ndef get_favourites(user):\n favourites_count = 0\n return int(favourites_count) \n \n \ndef get_lists(user):\n lists = user['public_metrics']['listed_count']\n if lists is None:\n return 0\n else:\n return int(lists) \n\n\ndef has_default_profile(user):\n if user[\"profile_image_url\"] is None or user[\"profile_image_url\"] == ' ':\n return False\n else:\n return True\n \n \ndef is_verified(user):\n if user['verified'] == 'True ':\n return True\n else:\n return False\n \ndef get_freq(user):\n tweets = user['public_metrics']['tweet_count']\n GMT_FORMAT = '%a %b %d %H:%M:%S %z %Y'\n create_time = user['created_at']\n user_create_time = datetime.datetime.strptime(create_time, GMT_FORMAT)\n d1 = user_create_time.date()\n #d1 = datetime.datetime.strptime(user_create_time, \"%Y-%m-%d\").date()\n present_time = datetime.datetime.now()\n d2 = present_time.date()\n #d2 = datetime.datetime.strptime(present_time, \"%Y-%m-%d\").date()\n user_age = (d2-d1).days\n freq = int(tweets)/int(user_age)\n if create_time is None or create_time == ' ':\n return False\n else:\n return(freq)\n\n\ndef get_followers_growth(user):\n followers_count = user['public_metrics']['followers_count']\n GMT_FORMAT = '%a %b %d %H:%M:%S %z %Y'\n create_time = user['created_at']\n user_create_time = datetime.datetime.strptime(create_time, GMT_FORMAT)\n d1 = user_create_time.date()\n present_time = datetime.datetime.now()\n d2 = present_time.date()\n user_age = (d2-d1).days\n followers_growth = int(followers_count)/int(user_age)\n return(followers_growth)\n \n \ndef get_listed_growth(user):\n listed_count = user['public_metrics']['listed_count']\n GMT_FORMAT = '%a %b %d %H:%M:%S %z %Y'\n create_time = user['created_at']\n user_create_time = datetime.datetime.strptime(create_time, GMT_FORMAT)\n d1 = user_create_time.date()\n present_time = datetime.datetime.now()\n d2 = present_time.date()\n user_age = (d2-d1).days\n listed_growth = int(listed_count)/int(user_age)\n return(listed_growth) \n \n \ndef get_followers_friends_ratio(user):\n followers_count = user['public_metrics']['followers_count']\n following_count = user['public_metrics']['following_count']\n if following_count == 0:\n #if following_count is None or following_count == '0':\n return 0.0\n else:\n return int(followers_count) / int(following_count)\n \n \ndef get_screen_name_length(user):\n screen_name = get_screen_name(user)\n if screen_name is None:\n return 0\n else:\n return len(screen_name) - 1 \n \n \ndef get_num_digits_in_screen_name(user):\n screen_name = get_screen_name(user)\n if screen_name is None:\n return 0\n else:\n numbers = re.findall(r'\\d+', screen_name)\n return len(numbers)\n\ndef get_name_length(user):\n username = get_username(user)\n if username is None:\n return 0\n else:\n return len(username) - 1\n\n\ndef get_num_digits_in_name(user):\n username = get_username(user)\n if username is None:\n return 0\n else:\n numbers = re.findall(r'\\d+', username)\n return len(numbers)\n\n\ndef get_description_length(user):\n if has_description(user):\n return len(user['description'])\n else:\n return 0\n\ndef get_screen_name_likelihood(user):\n return 0\n \n\n \n \n\n \n \n","repo_name":"LuoUndergradXJTU/TwiBot-22","sub_path":"src/Abreu/RF/user_feature_func.py","file_name":"user_feature_func.py","file_ext":"py","file_size_in_byte":4411,"program_lang":"python","lang":"en","doc_type":"code","stars":111,"dataset":"github-code","pt":"40"} +{"seq_id":"40729024544","text":"class User:\n\tdef __init__(self, id, password, github_username, github_obj=None):\n\t\tself.id = id\n\t\tself.password = password\n\t\tself.github_username = github_username\n\t\tself.github_obj = github_obj\n\nclass File:\n\tdef __init__(self, fullname, name, last_commit_sha, repo_fullname, sha, github_obj=None, content=None):\n\t\tself.fullname = fullname\n\t\tself.name = name\n\t\tself.last_commit_sha = last_commit_sha\n\t\tself.repo_fullname = repo_fullname\n\t\tself.sha = sha\n\t\tself.github_obj = github_obj\n\t\tself.content = content # special value (db에 포함되지 않음)\n\nclass Repository:\n\tdef __init__(self, fullname, name, last_commit_date, last_commit_sha, owner, github_obj=None):\n\t\tself.fullname = fullname\n\t\tself.name = name\n\t\tself.last_commit_date = last_commit_date\n\t\tself.last_commit_sha = last_commit_sha\n\t\tself.owner = owner\n\t\tself.github_obj = github_obj\n\t\tself.upstream_repo = None\n\n\tdef update_file(self, file: File, title: str, content: str, branch: str):\n\t\tassert self.github_obj\n\t\t\n\t\t# 파일 업데이트 실행\n\t\tresult = self.github_obj.update_file(file.fullname, title, content, sha=file.sha, branch=branch)\n\t\tcommit = result['commit']\n\t\tcontent_file = result['content']\n\n\t\t# 파일 정보 업데이트\n\t\tfile.sha = content_file.sha\n\t\tfile.last_commit_sha = commit.sha\n\t\tfile.content = content\n\n\tdef create_file(self, file_fullname: str, title: str, content: str, branch: str):\n\t\tassert self.github_obj\n\n\t\t# 파일 생성\n\t\tresult = self.github_obj.create_file(file_fullname, title, content, branch=branch)\n\t\tcommit = result['commit']\n\t\tcontent_file = result['content']\n\n\t\t# 파일 객체 생성\n\t\tnew_file = File(\n\t\t\tfullname=file_fullname,\n\t\t\tname=content_file.name,\n\t\t\tlast_commit_sha=commit.sha,\n\t\t\trepo_fullname=self.fullname,\n\t\t\tsha=content_file.sha,\n\t\t\tcontent=content)\n\n\t\treturn new_file\n\nclass SecretKey:\n\tdef __init__(self, y, x, file_fullname, file_commit_sha, content, repo_last_commit_sha=None, pull_num=0, github_obj=None):\n\t\tself.y = y\n\t\tself.x = x\n\t\tself.file_fullname = file_fullname\n\t\tself.file_commit_sha = file_commit_sha\n\t\tself.content = content\n\t\tself.github_obj = github_obj\n\t\tself.repo_last_commit_sha = repo_last_commit_sha\n\t\tself.pull_num = pull_num\n","repo_name":"2jun0/CodeSecret-Backend","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"19941116115","text":"# ga search\nfrom numpy.random import rand\nfrom numpy.random import randint\n\n\n# objective function\ndef onemax(x):\n return -sum(x)\n\n\n# selection\ndef selection(pop, scores, k=3):\n # random selection\n selection_ix = randint(len(pop))\n for ix in randint(0, len(pop), k-1):\n # check if better\n if scores[ix] < scores[selection_ix]:\n selection_ix = ix\n return pop[selection_ix]\n\n\n# crossover\ndef crossover(p1, p2, r_cross):\n # children are carbon copies of parents (def)\n c1, c2 = p1.copy(), p2.copy()\n # check for recombination\n if rand() < r_cross:\n # select crossover point\n pt = randint(1, len(p1)-2)\n # perform crossover\n c1 = p1[:pt] + p2[pt:]\n c2 = p2[:pt] + p1[pt:]\n return [c1, c2]\n\n\n# mutation\ndef mutation(bitstring, r_mut):\n for i in range(len(bitstring)):\n # check for mutation\n if rand() < r_mut:\n # flip the bit\n bitstring[i] = 1 - bitstring[i]\n\n\n# gen alg\ndef gen_alg(objective, n_bits, n_iter, n_pop, r_cross, r_mut):\n # initial population\n pop = [randint(0, 2, n_bits).tolist() for _ in range(n_pop)]\n # keep track of best solution\n best, best_eval = 0, objective(pop[0])\n for gen in range(n_iter):\n # evaluate all candidates in population\n scores = [objective(c) for c in pop]\n for i in range(n_pop):\n if scores[i] < best_eval:\n best, best_eval = pop[i], scores[i]\n print(\"- %d, new best f(%s) = %.3f\" % (gen, pop[i], scores[i]))\n # selection\n selected = [selection(pop, scores) for _ in range(n_pop)]\n # new generation\n children = list()\n for i in range(0, n_pop, 2):\n # get selected parents in pairs\n p1, p2 = selected[i], selected[i+1]\n # crossover and mutation\n for c in crossover(p1, p2, r_cross):\n mutation(c , r_mut)\n children.append(c)\n pop = children\n return [best, best_eval]\n\nn_iter = 100\nn_bits = 20\nn_pop = 100\nr_cross = 0.9\nr_mut = 1.0/float(n_bits)\nbest, score = gen_alg(onemax, n_bits, n_iter, n_pop, r_cross, r_mut)\nprint('done')\nprint(\"f(%s) = %f\" % (best, score))\n","repo_name":"pmichale/genetic-algorithm","sub_path":"ga.py","file_name":"ga.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"13411014749","text":"# -*- coding: utf-8 -*-\n\"\"\" Class to secure a PDF of findings. \"\"\"\n# pylint: disable=relative-beyond-top-level\n# Disabling this rule is necessary for importing modules beyond the top level\n# directory.\nimport time\nimport os\nfrom PyPDF2 import PdfFileWriter, PdfFileReader\nfrom ..dao import integrates_dao\n\n\nclass SecurePDF(object):\n \"\"\" Add basic security to PDF. \"\"\"\n\n result_dir = ''\n watermark_tpl = ''\n secure_pdf_username = ''\n secure_pdf_filename = ''\n\n def __init__(self):\n \"\"\"Class constructor.\"\"\"\n self.base = '/usr/src/app/app/documentator/'\n self.watermark_tpl = os.path.join(\n self.base,\n 'resources/themes/watermark_integrates_en.pdf')\n self.result_dir = os.path.join(self.base, 'results/')\n\n def create_full(self, username, basic_pdf_name, project):\n \"\"\" Execute the security process in a PDF. \"\"\"\n self.secure_pdf_username = username\n project_info = integrates_dao.get_project_dynamo(project.lower())\n if project_info and project_info[0].get('type') == 'continuous':\n self.secure_pdf_filename = self.lock(basic_pdf_name)\n else:\n water_pdf_name = self.watermark(basic_pdf_name)\n self.secure_pdf_filename = self.lock(water_pdf_name)\n return self.result_dir + self.secure_pdf_filename\n\n def watermark(self, in_filename):\n \"\"\" Add a watermark to all pages of a PDF. \"\"\"\n pdf_foutname = 'water_' + in_filename\n input = PdfFileReader(file(self.result_dir + in_filename, 'rb')) # noqa\n output = PdfFileWriter()\n watermark = PdfFileReader(file(self.watermark_tpl, 'rb'))\n for i in range(0, input.getNumPages()):\n overlay = watermark.getPage(0)\n page = input.getPage(i)\n page.mergePage(overlay)\n output.addPage(page)\n output_stream = file(self.result_dir + pdf_foutname, 'wb')\n output.write(output_stream)\n output_stream.close()\n return pdf_foutname\n\n def lock(self, in_filename):\n \"\"\" Add a password to a PDF. \"\"\"\n pdf_foutname = self.secure_pdf_username + \"_\" + in_filename\n password = time.strftime('%d%m%Y') + \\\n self.secure_pdf_username.encode('utf8', 'ignore')\n output = PdfFileWriter()\n input = PdfFileReader(file(self.result_dir + in_filename, 'rb')) # noqa\n for i in range(0, input.getNumPages()):\n output.addPage(input.getPage(i))\n output_stream = file(self.result_dir + pdf_foutname, 'wb')\n output.encrypt(password, use_128bit=True)\n output.write(output_stream)\n output_stream.close()\n return pdf_foutname\n","repo_name":"jvasque6/integrates","sub_path":"app/documentator/secure_pdf.py","file_name":"secure_pdf.py","file_ext":"py","file_size_in_byte":2689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"74419778361","text":"# -*- coding: utf-8 -*-\n\ndef get_question(okres):\n return {\n 'question': 'Lorem Ipsum is simply dummy text',\n 'answers': [\n 'A: 0 - 10',\n 'B: 10 - 20',\n 'C: 20 - 30',\n 'D: 30 - 40'\n ],\n 'correct': 1,\n 'source': 'Example database',\n 'value': '15ha',\n 'more_html': '<div></div>'\n }\n","repo_name":"hackujstat-v3-team-11/backend","sub_path":"question_modules/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"74079192448","text":"from PyInquirer import prompt\n\nfrom dummy_client.utils.print_table import print_video_as_table, print_playlist_as_table\n\nfrom dummy_client.myPlaylistSeq import my_playlist_seq\nfrom dummy_client.myVideoSeq import my_video_seq\nfrom dummy_client.editInfoSeq import edit_info_seq\nfrom dummy_client.historySeq import history_seq\n\nquit_q = [{\n \"type\": \"list\",\n \"name\": \"quit\",\n \"message\": \"\",\n \"choices\": [\"Quit\"]\n}]\n\n\ndef other_chen_info_seq(services, other_chen_num):\n # services used in this sequence\n pl_service = services[\"plService\"]\n video_service = services[\"videoService\"]\n chan_service = services[\"channelService\"]\n\n res = chan_service.get_channel_data(other_chen_num)\n if res == 0:\n print(\"Failed to fetch info.\")\n return 0\n\n while True:\n print(\"CHANNEL INFO\")\n chan_intro = res[\"chanIntro\"]\n if chan_intro is None:\n chan_intro = \"\"\n\n print(\"INTRO: \" + chan_intro + \"\\n\" + \"CREATED_AT: \" + str(res[\"createdAt\"]))\n\n answer = prompt([{\n \"type\": \"list\",\n \"name\": \"what_to_do\",\n \"message\": \"tell me what you want to do with this channel.\",\n \"choices\": [\"Show videos\", \"Show playlists\", \"Quit\"]\n }])\n\n action = answer.get(\"what_to_do\")\n\n if action == \"Show videos\":\n res = video_service.get_others_videos_to_feed(other_chen_num)\n if res == 0:\n print(\"Fetching videos failed.\")\n continue\n\n print_video_as_table(res)\n\n answer = prompt(quit_q)\n\n if answer.get(\"quit\") == \"Quit\":\n break\n\n elif action == \"Show playlists\":\n res = pl_service.get_someones_playlists(other_chen_num)\n if res == 0:\n print(\"Fetching playlists failed.\")\n continue\n\n print_playlist_as_table(res)\n\n answer = prompt(quit_q)\n\n if answer.get(\"quit\") == \"Quit\":\n break\n\n else:\n print(\"Return to menu.\")\n return 0\n\n\ndef my_chen_info_seq(services, chen_id):\n chan_service = services[\"channelService\"]\n res = chan_service.get_channel_data(chen_id)\n\n if res == 0:\n print(\"Failed to load channel data.\")\n return 0\n\n while True:\n print(\"CHANNEL INFO\")\n chan_intro = res[\"chanIntro\"]\n print(\"INTRO: \" + chan_intro + \"\\n\" + \"CREATED_AT: \" + str(res[\"createdAt\"]))\n\n answer = prompt([{\n \"type\": \"list\",\n \"name\": \"my_chan_task\",\n \"message\": \"choose the task\",\n \"choices\": [\"My playlists\", \"My videos\",\n \"Edit channel info\", \"Watch history\",\n \"Quit\"]\n }])\n task = answer.get(\"my_chan_task\")\n\n if task == \"My playlists\":\n my_playlist_seq(services, chen_id)\n continue\n\n elif task == \"My videos\":\n my_video_seq(services, chen_id)\n continue\n\n elif task == \"Edit channel info\":\n edit_info_seq(services, chen_id)\n continue\n\n elif task == \"Watch history\":\n history_seq(services, chen_id)\n continue\n\n else:\n print(\"Back to menu.\")\n return 0\n\n\n","repo_name":"yeonic/HYU_ITE2038","sub_path":"3. dummy_tube/dummy_client/chanInfoSeq.py","file_name":"chanInfoSeq.py","file_ext":"py","file_size_in_byte":3287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"24706117644","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom itertools import combinations\n\n# DATA DIGNITY -------------------------------------------------------------\n\ndef column_null_analyzer(df):\n dict_list = []\n for col in df.columns:\n col_nulls = df[col].isnull().sum()\n col_null_percent = col_nulls/len(df.index)\n dict_list.append({'':col,'num_rows_missing':col_nulls,'pct_rows_missing':col_null_percent})\n return pd.DataFrame(dict_list).set_index('').sort_values(by='num_rows_missing', ascending=False)\n\n# UNIVARIATE ---------------------------------------------------------------\n\ndef univariate_distributions(df):\n '''\n Takes in a cleaned but not split and unencoded dataset and pumps out all the univariate distributions\n for numeric features.\n '''\n num_cols = [col for col in df.columns if df[col].dtype != 'object']\n\n for i in num_cols:\n print(i)\n plt.figure(figsize = (10,5))\n plt.subplot(121)\n sns.boxplot(y=df[i].values)\n plt.subplot(122)\n sns.histplot(x=df[i])\n plt.show()\n print(df[i].value_counts())\n print('\\n-----\\n')\n\n# BI/MULTI-VARIATE ---------------------------------------------------------\n\ndef plot_variable_pairs(df):\n '''\n Takes in a cleaned and split (but not scaled or encoded) training dataset \n and outputs a heatmap and linear regression lines based on correlations. \n '''\n # Create lists of categorical and continuous numerical columns\n num_cols = [col for col in df.columns if df[col].dtype != 'object']\n cat_cols = [col for col in df.columns if df[col].dtype == 'object']\n \n # Create a correlation matrix from the continuous numerical columns\n df_num_cols = df[num_cols]\n corr = df_num_cols.corr()\n\n # Pass correlation matrix on to sns heatmap\n plt.figure(figsize=(8,8))\n sns.heatmap(corr, annot=True, cmap=\"flare\", mask=np.triu(corr))\n plt.show()\n \n # Create lm plots for all numerical data\n combos = list(combinations(num_cols,2))\n for i in combos:\n sns.lmplot(x=i[0],y=i[1],data=df, hue=cat_cols[0])\n plt.show()\n\ndef plot_categorical_and_continuous_vars(df):\n '''\n Takes in a cleaned and split (but not scaled or encoded) training dataset \n and outputs charts showing distributions for each of the categorical variables.\n '''\n # Create lists of categorical and continuous numerical columns\n num_cols = [col for col in df.columns if df[col].dtype != 'object']\n cat_cols = [col for col in df.columns if df[col].dtype == 'object']\n \n # Create 3x side-by-side categorial to continous numeric plots\n for i in num_cols:\n plt.figure(figsize = (18,6))\n plt.subplot(1,3,1)\n sns.boxplot(data = df, x=cat_cols[0], y=i)\n plt.subplot(1,3,2)\n sns.violinplot(data = df, x=cat_cols[0], y=i)\n plt.subplot(1,3,3)\n sns.barplot(data = df, x=cat_cols[0], y=i)\n plt.show()\n\ndef plot_numerical_against_target(df,target):\n '''\n Plots all unscaled numerical features against target.\n '''\n num_cols = [col for col in df.columns if df[col].dtype != 'object']\n\n for i in num_cols:\n sns.relplot(data = df, x=i, y=target)\n plt.show()","repo_name":"Miller-Ryan-1/clustering-project","sub_path":"explore.py","file_name":"explore.py","file_ext":"py","file_size_in_byte":3278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"14099878131","text":"import sklearn.ensemble as ensemble \n\n\nMODELS = {\n 'ada_boost': ensemble.AdaBoostClassifier(random_state=7),\n 'random_forest': ensemble.RandomForestClassifier(random_state=7),\n 'gradient_boosting': ensemble.GradientBoostingClassifier(random_state=7)\n }\n\nGRID_PARAMETERS = {\n 'ada_boost': None,\n 'random_forest': {\n 'n_estimators': [150, 200],\n 'max_depth': [100, 110]\n },\n 'gradient_boosting': {\n 'n_estimators': [100, 150, 200],\n 'learning_rate': [0.1, 0.3, 1]\n }\n }\n","repo_name":"tarasowski/finding-donors-ml","sub_path":"src/dispatcher.py","file_name":"dispatcher.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"43"} +{"seq_id":"14016106064","text":"import math\nimport time\nimport tkinter\nimport tkinter.font\nimport tkinter.messagebox\nimport mazegen\nimport ktinter\n# from PIL import ImageGrab\n\nsz = 75\nn = 7\nm = 11\npoints = []\nkc = 0\npt = [[0, 0], [0, 0]]\ntrace = []\nmt = []\ndothi = []\nline = []\nkt = []\ncnt = 0\nchedo = 0\ndh = False\nwdth = 1050\nhght = 645\ntgian = 0\n\n\ndef ktt(x1, y1, x2, y2, x3, y3, x4, y4):\n if ktinter.intersect(x1, y1, x2, y2, x3, y3, x4, y4) == 1: return 1\n else: return 0\n\n\ndef add(x, y):\n points.append([x, y])\n kt[x][y] = 1\n\n\ndef mdl(x1, y1, x2, y2, x3, y3):\n if x1 <= x2 and max(y2, y3) >= y1 >= min(y2, y3): return 1\n else: return 0\n\n\ndef indothi(x, y):\n dem = 0\n for ii in range(len(line)):\n x1 = line[ii][1] * sz; y1 = sz * (line[ii][0] - 1)\n x2 = line[ii][3] * sz; y2 = sz * (line[ii][2] - 1)\n dem += mdl(x, y, x1, y1, x2, y2)\n if dem % 2 == 1: return True\n else: return False\n\n\ndef dijsktra():\n global kc\n l = len(points) + 2\n trace.clear()\n for i in range(0, l + 1):\n trace.append(0)\n dist = [1e7] * l\n dist[0] = 0\n trace[0] = -1\n visit = [False] * l\n\n for ii in range(l):\n mn = 1e7\n for i in range(0, l):\n if visit[i] == False and dist[i] < mn:\n mn = dist[i]\n u = i\n visit[u] = True\n\n for v in range(0, l):\n if mt[u][v] > 0 and visit[v] == False and dist[v] > dist[u] + mt[u][v]:\n dist[v] = dist[u] + mt[u][v]\n trace[v] = u\n kc = dist[l - 1]\n\n\nclass gui:\n def __init__(self):\n self.main = tkinter.Tk()\n\n self.dau = tkinter.Canvas(self.main, height=10)\n self.dau.pack()\n\n self.tp1 = tkinter.Frame(self.main)\n self.tp1.pack()\n\n self.bt1 = tkinter.Frame(self.main)\n self.canvas = tkinter.Canvas(self.main, width=wdth, height=hght)\n self.canvas.create_rectangle(50, 10, wdth - 50, hght - 35, fill='white')\n\n self.canvas.pack()\n self.bt1.pack()\n\n self.btn1 = tkinter.Button(self.tp1, text='Generate Map', command=self.gen)\n self.btn1.pack(side='left')\n\n self.btn3 = tkinter.Button(self.tp1, text='Show', command=self.chg)\n self.btn3.pack(side='left')\n\n self.btn2 = tkinter.Button(self.tp1, text='Find', command=self.xl)\n self.btn2.pack(side='left')\n\n self.txt1 = tkinter.Label(self.bt1, text='Distance: ')\n self.txt1.pack(side='left')\n self.dxt = tkinter.StringVar()\n self.txt2 = tkinter.Label(self.bt1, textvariable=self.dxt)\n self.txt2.pack(side='left')\n\n self.txt3 = tkinter.Label(self.bt1, text='Time: ')\n self.txt3.pack(side='left')\n self.tme = tkinter.StringVar()\n self.txt4 = tkinter.Label(self.bt1, textvariable=self.tme)\n self.txt4.pack(side='left')\n\n self.day = tkinter.Canvas(self.main, height=10)\n self.day.pack()\n\n self.canvas.bind('<Button-1>', self.draw)\n\n tkinter.mainloop()\n\n def dtrace(self):\n v = len(points) + 1\n if len(trace) < v: return\n u = trace[v]\n while u != -1 and v != -1:\n if v == len(points) + 1: x1 = pt[1][0]; y1 = pt[1][1]\n else: x1 = sz * points[v - 1][1]; y1 = 10 + sz * (points[v - 1][0] - 1)\n\n if u == 0: x2 = pt[0][0]; y2 = pt[0][1]\n else: x2 = sz * points[u - 1][1]; y2 = 10 + sz * (points[u - 1][0] - 1)\n\n self.canvas.create_line(x1, y1, x2, y2, fill='orange', width=3)\n v = u\n u = trace[v]\n\n def ve(self):\n self.dmap()\n self.grid()\n self.dclick()\n dijsktra()\n self.ddothi()\n self.dpt()\n\n def chg(self):\n global chedo, dh\n chedo ^= 1\n if chedo == 1:\n self.ddothi()\n if dh: self.dtrace()\n else:\n self.ve()\n if dh: self.dtrace()\n\n def dclick(self):\n global cnt\n if pt[0][0] == 0: return\n z = 5\n self.canvas.create_oval(pt[cnt][0] - z, pt[cnt][1] - z, pt[cnt][0] + z, pt[cnt][1] + z, fill='white', width=0)\n myfont = tkinter.font.Font(family='Arial', size=8, weight='bold')\n tmp1 = str(pt[0][0]) + ', ' + str(pt[0][1])\n tmp2 = str(pt[1][0]) + ', ' + str(pt[1][1])\n\n if cnt == 0:\n self.canvas.create_oval(pt[cnt][0] - z, pt[cnt][1] - z, pt[cnt][0] + z, pt[cnt][1] + z, fill='red', width=0)\n self.canvas.create_text(pt[cnt][0] + 10, pt[cnt][1] + 13, text=tmp1, fill='black', font=myfont)\n x1 = pt[0][0]; y1 = pt[0][1]\n\n for i in range(0, len(points)):\n mt[0][i + 1] = mt[i + 1][0] = 0\n x2 = sz * points[i][1]; y2 = 10 + sz * (points[i][0] - 1)\n tmpp = True\n for ii in range(0, len(line)):\n x3 = sz * line[ii][1]; y3 = 10 + sz * (line[ii][0] - 1)\n x4 = sz * line[ii][3]; y4 = 10 + sz * (line[ii][2] - 1)\n if ktt(x1, y1, x2, y2, x3, y3, x4, y4) == 1:\n tmpp = False\n break\n\n if tmpp: mt[0][i + 1] = mt[i + 1][0] = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)\n\n if pt[1][0] != 0 or pt[1][1] != 0:\n mt[0][len(points) + 1] = mt[len(points) + 1][0] = 0\n self.canvas.create_oval(pt[1][0] - z, pt[1][1] - z, pt[1][0] + z, pt[1][1] + z, fill='green', width=0)\n self.canvas.create_text(pt[1][0] + 10, pt[1][1] + 13, text=tmp2, fill='black', font=myfont)\n x2 = pt[1][0]; y2 = pt[1][1]\n tmpp = True\n for ii in range(0, len(line)):\n x3 = sz * line[ii][1]; y3 = 10 + sz * (line[ii][0] - 1)\n x4 = sz * line[ii][3]; y4 = 10 + sz * (line[ii][2] - 1)\n if ktt(x1, y1, x2, y2, x3, y3, x4, y4) == 1:\n tmpp = False\n break\n if tmpp: mt[0][len(points) + 1] = mt[len(points) + 1][0] = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)\n cnt = 1\n else:\n mt[0][len(points) + 1] = mt[len(points) + 1][0] = 0\n x1 = pt[1][0]; y1 = pt[1][1]\n for i in range(0, len(points)):\n mt[len(points) + 1][i + 1] = mt[i + 1][len(points) + 1] = 0\n x2 = sz * points[i][1]; y2 = 10 + sz * (points[i][0] - 1)\n tmpp = True\n for ii in range(0, len(line)):\n x3 = sz * line[ii][1]; y3 = 10 + sz * (line[ii][0] - 1)\n x4 = sz * line[ii][3]; y4 = 10 + sz * (line[ii][2] - 1)\n if ktt(x1, y1, x2, y2, x3, y3, x4, y4) == 1:\n tmpp = False\n break\n\n if tmpp: mt[len(points) + 1][i + 1] = mt[i + 1][len(points) + 1] = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)\n\n x2 = pt[0][0]; y2 = pt[0][1]\n tmpp = True\n for ii in range(0, len(line)):\n x3 = sz * line[ii][1]; y3 = 10 + sz * (line[ii][0] - 1)\n x4 = sz * line[ii][3]; y4 = 10 + sz * (line[ii][2] - 1)\n if ktt(x1, y1, x2, y2, x3, y3, x4, y4) == 1:\n tmpp = False\n break\n if tmpp: mt[0][len(points) + 1] = mt[len(points) + 1][0] = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)\n\n self.canvas.create_oval(pt[cnt][0] - z, pt[cnt][1] - z, pt[cnt][0] + z, pt[cnt][1] + z, fill='green', width=0)\n self.canvas.create_text(pt[cnt][0] + 10, pt[cnt][1] + 13, text=tmp2, fill='black', font=myfont)\n self.canvas.create_oval(pt[0][0] - z, pt[0][1] - z, pt[0][0] + z, pt[0][1] + z, fill='red', width=0)\n self.canvas.create_text(pt[0][0] + 10, pt[0][1] + 13, text=tmp1, fill='black', font=myfont)\n cnt = 0\n\n def draw(self, event):\n global dh\n x = event.x; y = event.y\n dh = False\n if indothi(x, y):\n pt[cnt][0] = x\n pt[cnt][1] = y\n self.ve()\n\n def ddothi(self):\n global chedo\n if chedo == 1:\n for i in range(0, len(dothi)):\n self.canvas.create_line(dothi[i][1], dothi[i][0], dothi[i][3], dothi[i][2], fill='yellow', width=1)\n if pt[0][0] != 0:\n for i in range(0, len(points)):\n if mt[0][i + 1] != 0:\n self.canvas.create_line(pt[0][0], pt[0][1], sz * points[i][1], sz * (points[i][0] - 1) + 10, fill='blue', width=1)\n if pt[1][0] != 0:\n for i in range(0, len(points)):\n if mt[len(points) + 1][i + 1] != 0:\n self.canvas.create_line(pt[1][0], pt[1][1], sz * points[i][1], sz * (points[i][0] - 1) + 10, fill='blue', width=1)\n if mt[0][len(points) + 1] != 0:\n self.canvas.create_line(pt[0][0], pt[0][1], pt[1][0], pt[1][1], fill='blue', width=1)\n\n def dmap(self):\n self.canvas.delete('all')\n global cnt\n arr = mazegen.gtar()\n self.canvas.create_rectangle(50, 10, wdth - 50, hght - 35, fill='white')\n for i in range(1, n + 2):\n for j in range(1, m + 2):\n if arr[i][j] == '#':\n self.canvas.create_rectangle(sz * j, 10 + sz * (i - 1), sz * (j + 1), 10 + sz * i, fill='grey', width=0)\n self.canvas.create_line(50, 10, wdth - 50, 10)\n self.canvas.create_line(50, 10, 50, hght - 35)\n\n def dpt(self):\n myfont = tkinter.font.Font(family='Arial', size=8, weight='bold')\n for i in range(0, len(points)):\n tam = points[i]\n self.canvas.create_oval(sz * tam[1] - 3, 7 + sz * (tam[0] - 1), sz * tam[1] + 3, 13 + sz * (tam[0] - 1), fill='black')\n tmp = str(sz * tam[1]) + ', ' + str(sz * (tam[0] - 1))\n self.canvas.create_text(sz * tam[1] + 10, sz * (tam[0] - 1) + 20, text=i + 1, fill='black', font=myfont)\n\n def grid(self):\n myfont = tkinter.font.Font(family='Arial', size=8, weight='bold')\n for i in range(1, n + 3):\n for j in range(1, m + 3):\n if j == m + 2:\n if i == n + 1: self.canvas.create_text(sz * j + 10, 20 + sz * i, text=sz * (j - 1), font=myfont)\n break\n if i == n + 1:\n self.canvas.create_text(sz * j + 10, 20 + sz * i, text=sz * (j - 1), font=myfont)\n if i == n + 2:\n self.canvas.create_text(sz * j - 12, 20 + sz * (i - 1), text=sz * (i - 1), font=myfont)\n break\n if j == 1:\n self.canvas.create_text(sz * j - 12, 20 + sz * (i - 1), text=sz * (i - 1), font=myfont)\n self.canvas.create_rectangle(sz * j, 10 + sz * (i - 1), sz * (j + 1), 10 + sz * i, width=1)\n\n def gen(self):\n global cnt, tgian\n strt = time.time()\n mazegen.reset()\n arr = mazegen.gtar()\n mt.clear()\n points.clear()\n line.clear()\n dothi.clear()\n pt[0][0] = pt[0][1] = pt[1][0] = pt[1][1] = cnt = 0\n\n for i in range(0, n + 3):\n kt.insert(i, [])\n for j in range(0, m + 3):\n kt[i].insert(j, 0)\n\n self.canvas.create_rectangle(50, 10, wdth - 50, hght - 35, fill='white')\n\n for i in range(1, n + 2):\n for j in range(1, m + 2):\n if arr[i][j] == '#':\n self.canvas.create_rectangle(sz * j, 10 + sz * (i - 1), sz * (j + 1), 10 + sz * i, fill='grey', width=0)\n\n if arr[i - 1][j - 1] == '.' and arr[i - 1][j] == arr[i][j - 1]: add(i, j)\n if arr[i - 1][j + 1] == '.' and arr[i - 1][j] == arr[i][j + 1]: add(i, j + 1)\n if arr[i + 1][j + 1] == '.' and arr[i + 1][j] == arr[i][j + 1]: add(i + 1, j + 1)\n if arr[i + 1][j - 1] == '.' and arr[i][j - 1] == arr[i + 1][j]: add(i + 1, j)\n\n slp = len(points)\n for i in range(0, slp + 3):\n mt.insert(i, [])\n for j in range(0, slp + 3):\n mt[i].insert(j, 0)\n\n pv = dx = -1\n for i in range(1, n + 2):\n for j in range(1, m + 2):\n if pv == -1:\n if kt[i][j] == 1: pv = j\n elif kt[i][j] == 1:\n dx = j\n line.append([i, pv, i, dx])\n dothi.append([10 + sz * (i - 1), sz * pv, 10 + sz * (i - 1), sz * dx])\n pv = -1\n\n for j in range(1, m + 2):\n for i in range(1, n + 2):\n if pv == -1:\n if kt[i][j] == 1: pv = i\n elif kt[i][j] == 1:\n dx = i\n line.append([pv, j, dx, j])\n dothi.append([10 + sz * (pv - 1), sz * j, 10 + sz * (dx - 1), sz * j])\n pv = -1\n\n for i in range(0, len(points) - 1):\n for j in range(i + 1, len(points)):\n x = 0; y = 0\n if points[i][1] < points[j][1]:\n y = points[i][1]\n if points[i][0] < points[j][0]: x = points[i][0]\n else: x = points[i][0] - 1\n else:\n y = points[j][1]\n if points[i][0] < points[j][0]: x = points[j][0] - 1\n else: x = points[j][0]\n\n x1 = sz * points[i][1]; y1 = 10 + sz * (points[i][0] - 1)\n x2 = sz * points[j][1]; y2 = 10 + sz * (points[j][0] - 1)\n\n tmpp = True\n for ii in range(0, len(line)):\n x3 = sz * line[ii][1]; y3 = 10 + sz * (line[ii][0] - 1)\n x4 = sz * line[ii][3]; y4 = 10 + sz * (line[ii][2] - 1)\n if arr[x][y] != '#':\n if ktt(x1, y1, x2, y2, x3, y3, x4, y4) == 1:\n tmpp = False\n break\n elif min(x1, x2) == min(x3, x4) and max(x1, x2) == max(x3, x4) and min(y1, y2) == min(y3, y4) and max(y1, y2) == max(y3, y4):\n tmpp = True\n break\n else: tmpp = False\n if tmpp:\n mt[i + 1][j + 1] = mt[j + 1][i + 1] = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)\n dothi.append([y1, x1, y2, x2])\n\n self.grid()\n self.ddothi()\n self.dpt()\n self.canvas.create_line(50, 10, wdth - 50, 10)\n self.canvas.create_line(50, 10, 50, hght - 35)\n tgian = time.time() - strt\n\n def xl(self):\n global dh, kc, tgian\n if pt[0][0] != 0 and pt[1][0] != 0:\n dh = True\n strt = time.time()\n dijsktra()\n self.dtrace()\n self.tme.set(time.time() - strt + tgian)\n self.dxt.set(kc)\n\n\nttt = gui()\n","repo_name":"hnguyendao04/Path-in-Maze","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":14862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"5407264090","text":"from django import forms, template\nfrom django.conf import settings\nfrom django.template import Context, loader\n\nfrom crispy_forms.utils import TEMPLATE_PACK, get_template_pack\n\nregister = template.Library()\n\n\n@register.filter\ndef is_checkbox(field):\n return isinstance(field.field.widget, forms.CheckboxInput)\n\n\n@register.filter\ndef is_password(field):\n return isinstance(field.field.widget, forms.PasswordInput)\n\n\n@register.filter\ndef is_radioselect(field):\n return isinstance(field.field.widget, forms.RadioSelect)\n\n\n@register.filter\ndef is_select(field):\n return isinstance(field.field.widget, forms.Select)\n\n\n@register.filter\ndef is_checkboxselectmultiple(field):\n return isinstance(field.field.widget, forms.CheckboxSelectMultiple)\n\n\n@register.filter\ndef is_file(field):\n return isinstance(field.field.widget, forms.FileInput)\n\n\n@register.filter\ndef is_clearable_file(field):\n return isinstance(field.field.widget, forms.ClearableFileInput)\n\n\n@register.filter\ndef is_multivalue(field):\n return isinstance(field.field.widget, forms.MultiWidget)\n\n\n@register.filter\ndef classes(field):\n return field.widget.attrs.get(\"class\", None)\n\n\n@register.filter\ndef css_class(field):\n return field.field.widget.__class__.__name__.lower()\n\n\ndef pairwise(iterable):\n a = iter(iterable)\n return zip(a, a)\n\n\nclass CrispyFieldNode(template.Node):\n def __init__(self, field, attrs):\n self.field = field\n self.attrs = attrs\n self.html5_required = \"html5_required\"\n\n def render(self, context): # noqa: C901\n # Nodes are not threadsafe so we must store and look up our instance\n # variables in the current rendering context first\n if self not in context.render_context:\n context.render_context[self] = (\n template.Variable(self.field),\n self.attrs,\n template.Variable(self.html5_required),\n )\n\n field, attrs, html5_required = context.render_context[self]\n field = field.resolve(context)\n try:\n html5_required = html5_required.resolve(context)\n except template.VariableDoesNotExist:\n html5_required = False\n\n template_pack = context.get(\"template_pack\", TEMPLATE_PACK)\n\n widgets = getattr(field.field.widget, \"widgets\", [getattr(field.field.widget, \"widget\", field.field.widget)])\n\n if isinstance(attrs, dict):\n attrs = [attrs] * len(widgets)\n\n converters = {\n \"textinput\": \"textinput textInput\",\n \"fileinput\": \"fileinput fileUpload\",\n \"passwordinput\": \"textinput textInput\",\n }\n converters.update(getattr(settings, \"CRISPY_CLASS_CONVERTERS\", {}))\n\n for widget, attr in zip(widgets, attrs):\n class_name = widget.__class__.__name__.lower()\n class_name = converters.get(class_name, class_name)\n css_class = widget.attrs.get(\"class\", \"\")\n if css_class:\n if css_class.find(class_name) == -1:\n css_class += \" %s\" % class_name\n else:\n css_class = class_name\n\n if (\n template_pack == \"bootstrap3\"\n and not is_checkbox(field)\n and not is_file(field)\n and not is_multivalue(field)\n ):\n css_class += \" form-control\"\n if field.errors:\n css_class += \" form-control-danger\"\n\n if template_pack == \"bootstrap4\" and not is_multivalue(field):\n if not is_checkbox(field):\n css_class += \" form-control\"\n if is_file(field):\n css_class += \"-file\"\n if field.errors:\n css_class += \" is-invalid\"\n elif field.form.is_bound:\n css_class += \" is-valid\"\n\n widget.attrs[\"class\"] = css_class\n\n # HTML5 required attribute\n if html5_required and field.field.required and \"required\" not in widget.attrs:\n if field.field.widget.__class__.__name__ != \"RadioSelect\":\n widget.attrs[\"required\"] = \"required\"\n\n for attribute_name, attribute in attr.items():\n attribute_name = template.Variable(attribute_name).resolve(context)\n\n if attribute_name in widget.attrs:\n widget.attrs[attribute_name] += \" \" + template.Variable(attribute).resolve(context)\n else:\n widget.attrs[attribute_name] = template.Variable(attribute).resolve(context)\n\n return str(field)\n\n\n@register.tag(name=\"crispy_field\")\ndef crispy_field(parser, token):\n token = token.split_contents()\n field = token.pop(1)\n attrs = {}\n\n token.pop(0)\n for attribute_name, value in pairwise(token):\n attrs[attribute_name] = value\n\n return CrispyFieldNode(field, attrs)\n","repo_name":"kobtsev-m/Animal-Shelter","sub_path":"src/gallery/templatetags/gallery_tags.py","file_name":"gallery_tags.py","file_ext":"py","file_size_in_byte":4958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"11853294956","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'''\n304. Range Sum Query 2D - Immutable\n\nGiven a 2D matrix matrix, find the sum of the elements inside the rectangle defined by\nits upper left corner (row0, col1) and lower right corner (row2, col2).\n\nRange Sum Query 2D\nThe above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and\n(row1, col2) = (4, 3), which contains sum = 8.\n\nExample:\nGiven matrix = [\n [3, 0, 1, 4, 2],\n [5, 6, 3, 2, 1],\n [1, 2, 0, 1, 5],\n [4, 1, 0, 1, 7],\n [1, 0, 3, 0, 5]\n]\n\nsumRegion(2, 1, 4, 3) -> 8\nsumRegion(1, 1, 2, 2) -> 11\nsumRegion(1, 2, 2, 4) -> 12\n\nNote:\n - You may assume that the matrix does not change.\n - There are many calls to sumRegion function.\n - You may assume that row1 ≤ row2 and col1 ≤ col2.\n\n==============================================================================================\nSOLUTION\n\n1. Brute force\n\nComplexity: O(mn)\n\n2. Cache matrix result\n\nComplexity: O(1) query, O(M²N²) initialization, O(M²N²) space\n\n3. Cache rows\nUse 1D prefix sum and accumulate row by row for query.\nComplexity: O(m) query, O(mn) initialization, O(mn) space\n\n4. 2D prefix sum(like INTEGRAL in calculus)\n\nLike the 1D case, we can still build the prefix sum. And the only difference is that now it's\n2D.\n\nBy observing the geometric rectangle region, we can use the principle inclusion-exclusion to\ncalculate of a rectangle region.\n\nDenote the function prefix sum as f, then f[x][y] is the sum over elements from (0, 0) to (x, y).\nSo we have such equation:\n\nsumRegion(row1, col1, row2, col2)\n= f[row2][col2] - f[row2][col2 - 1] - f[row1][col + 1] + f[row1][col1]\n\nComplexity: O(1), O(mn).\n\n'''\n\nclass NumMatrix(object):\n\n def __init__(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n \"\"\"\n self._matrix = matrix\n self._buildPrefixSum()\n\n def _buildPrefixSum(self):\n if not self._matrix or not self._matrix[0]:\n self._prefixSum = None\n return\n prefixSum = [[0 for _ in range(len(self._matrix[0]) + 1)]\n for _ in range(len(self._matrix) + 1)]\n for i in range(1, len(self._matrix) + 1):\n for j in range(1, len(self._matrix[0]) + 1):\n prefixSum[i][j] = prefixSum[i - 1][j] + prefixSum[i][j - 1] - \\\n prefixSum[i - 1][j - 1] + self._matrix[i - 1][j - 1]\n self._prefixSum = prefixSum\n\n def sumRegion(self, row1, col1, row2, col2):\n \"\"\"\n :type row1: int\n :type col1: int\n :type row2: int\n :type col2: int\n :rtype: int\n \"\"\"\n ps = self._prefixSum\n value = ps[row2 + 1][col2 + 1] - ps[row2 + 1][col1] - \\\n ps[row1][col2 + 1] + ps[row1][col1]\n # print('values: ', ps[row2 + 1][col2 + 1], ps[row2 + 1][col1],\n # ps[row1][col2 + 1], ps[row1][col1], value)\n return value\n\n\n# Your NumMatrix object will be instantiated and called as such:\n# obj = NumMatrix(matrix)\n# param_1 = obj.sumRegion(row1,col1,row2,col2)\n\ndef test():\n import numpy as np\n from pprint import pprint as print\n\n obj = NumMatrix([])\n # assert obj.sumRegion(0, 0, 0, 0) == 0\n\n # case\n obj = NumMatrix([[1]])\n assert obj.sumRegion(0, 0, 0, 0) == 1\n\n obj = NumMatrix([\n [3, 0, 1, 4, 2],\n [5, 6, 3, 2, 1],\n [1, 2, 0, 1, 5],\n [4, 1, 0, 1, 7],\n [1, 0, 3, 0, 5]\n ])\n\n assert obj._prefixSum[-1][-1] == np.sum(obj._matrix)\n\n assert obj.sumRegion(0, 0, 4, 4) == 58\n assert obj.sumRegion(0, 0, 4, 1) == 23\n assert obj.sumRegion(2, 1, 4, 3) == 8\n assert obj.sumRegion(1, 1, 2, 2) == 11\n assert obj.sumRegion(1, 2, 2, 4) == 12\n assert obj.sumRegion(2, 2, 0, 0) == 6\n assert obj.sumRegion(0, 0, 2, 2) == 21\n\n # case\n obj = NumMatrix([[3, 0, 1, 4, 2]])\n\n print('prefix sum: ')\n print(obj._prefixSum)\n assert obj.sumRegion(0, 0, 0, 3) == 8\n assert obj.sumRegion(0, 0, 0, 2) == 4\n assert obj.sumRegion(0, 0, 0, 1) == 3\n assert obj.sumRegion(0, 0, 0, 0) == 3\n\n # case\n obj = NumMatrix([[3], [0], [1], [4], [2]])\n\n print('prefix sum: ')\n print(obj._prefixSum)\n assert obj.sumRegion(0, 0, 3, 0) == 8\n assert obj.sumRegion(0, 0, 2, 0) == 4\n assert obj.sumRegion(0, 0, 1, 0) == 3\n assert obj.sumRegion(0, 0, 0, 0) == 3\n\n print('self test passed')\n\nif __name__ == '__main__':\n test()\n","repo_name":"arnabs542/oj","sub_path":"leetcode/304.rangeSumQuery2DImmutable.py","file_name":"304.rangeSumQuery2DImmutable.py","file_ext":"py","file_size_in_byte":4383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"15054115279","text":"# Continue is used to check if a condition is met then skip that particular iteration \n# Break is used to skip all the iteration once a comdition has been met\n\nfor i in range(6):\n if i==3:\n continue\n print('Hello',i)\n\nprint()\n\nfor i in range(4):\n if i==3:\n break\n print('Hello',i)\n","repo_name":"Itis-ravi/Python_Files","sub_path":"Continue_Break.py","file_name":"Continue_Break.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"20237548821","text":"from __future__ import print_function\nimport json\nimport glob, os, sys\n\n# \ntry:\n import xlsxwriter\nexcept:\n print(\"This software requires XlsxWriter package. Install it with 'sudo pip install XlsxWriter', see http://xlsxwriter.readthedocs.io/\")\n sys.exit(1)\n\nimport datetime\nimport argparse\nimport re\n\ndef parseDateAndRun(filename):\n m=re.match( r'.*profile.(?P<run>[0-9]*).(?P<date>20[0-9][0-9]-[01][0-9]-[0-3][0-9]).json', filename)\n if m:\n return (m.group('date'), m.group('run'))\n else: # not found\n return ('0','0')\n\ndef calc_minutes(timestr):\n # returns the number of minutes from midnight. seconds are ignored\n # based on http://stackoverflow.com/questions/10663720/converting-a-time-string-to-seconds-in-python\n ftr = [60,1,0] # ignore seconds, count minutes, and use 60 minutes per hour\n return sum([a*b for a,b in zip(ftr, map(int,timestr.split(':')))])\n\ndef expandProfile(l, valueField, offsetField):\n r=[]\n minutes=0\n value=l[0][valueField]\n for i in range(len(l)):\n start1=l[i]['start']\n minutes1=calc_minutes(start1)\n offset1=l[i][offsetField]\n if minutes1!=offset1:\n print(\"Error in JSON offSetField %s contains %s does not match start time %s (%d minutes). Please report this as a bug\" % (offsetField, offset1, start1, minutes1))\n sys.exit(1)\n while (minutes<minutes1):\n r.append(value)\n minutes=minutes+30\n value=l[i][valueField]\n # add the last value until midnight \n while (minutes<24*60): \n r.append(value)\n minutes=minutes+30\n # return the expanded profile\n return r\n\ndef writeExcelHeader(ws, date_format, headerFormat):\n ws.write_string(0,0, 'Filename', headerFormat)\n ws.write_string(0,1, 'Date', headerFormat)\n ws.write_string(0,2, 'Run', headerFormat)\n col=3\n for hours in range(24):\n for minutes in [0,30]:\n dt=datetime.datetime.strptime('%02d:%02d' % (hours,minutes) , '%H:%M')\n ws.write_datetime(0, col, dt, date_format)\n col=col+1\n\ndef write_profile(worksheet, row, json, excel_number_format):\n worksheet.write_string(row, 0, filename)\n date, run = parseDateAndRun(filename)\n worksheet.write_string(row, 1, date)\n worksheet.write_string(row, 2, run)\n col=3\n value=\"\"\n for i in PROFILE_FIELDS:\n if i in json:\n worksheet.write_number(row, col, json[i], excel_number_format)\n col=col+1\n \ndef write_timebased_profile(worksheet, row, expandedList, excel_number_format):\n worksheet.write_string(row, 0, filename)\n date, run = parseDateAndRun(filename)\n worksheet.write_string(row, 1, date)\n worksheet.write_string(row, 2, run)\n col=3\n for i in range(len(expandedList)):\n worksheet.write_number(row, col, expandedList[i], excel_number_format)\n col=col+1\n\ndef excel_init_workbook(workbook):\n #see http://xlsxwriter.readthedocs.io/format.html#format for documentation on the Excel format's\n excel_hour_format = workbook.add_format({'num_format': 'hh:mm', 'bold': True, 'font_color': 'black'})\n excel_2decimals_format = workbook.add_format({'num_format': '0.00', 'font_size': '16'})\n excel_integer_format = workbook.add_format({'num_format': '0', 'font_size': '16'})\n headerFormat = workbook.add_format({'bold': True, 'font_color': 'black'})\n worksheetInfo = workbook.add_worksheet('Read this first')\n\n worksheetProfile = workbook.add_worksheet('Profile')\n worksheetProfile.write_string(0,0, 'Filename', headerFormat)\n worksheetProfile.write_string(0,1, 'Date', headerFormat)\n worksheetProfile.write_string(0,2, 'Run', headerFormat)\n col=3\n for colName in PROFILE_FIELDS:\n worksheetProfile.write_string(0,col, colName, headerFormat)\n col=col+1\n\n worksheetIsf = workbook.add_worksheet('isfProfile')\n worksheetBasal = workbook.add_worksheet('basalProfile') \n writeExcelHeader(worksheetBasal, excel_hour_format,headerFormat)\n writeExcelHeader(worksheetIsf, excel_hour_format,headerFormat)\n worksheetBasal.autofilter('A1:C999')\n worksheetIsf.autofilter('A1:C999')\n worksheetBasal.set_column(3, 50, 6) # set columns starting from 3 to same width\n worksheetIsf.set_column(3, 50, 6) # set columns starting from 3 to same width\n infoText=['Released under MIT license. See the accompanying LICENSE.txt file for', 'full terms and conditions', '']\n infoText.append('THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR')\n infoText.append('IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,')\n infoText.append('FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE')\n infoText.append('AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER')\n infoText.append('LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,')\n infoText.append('OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN')\n infoText.append('THE SOFTWARE.')\n row=1\n for i in range(len(infoText)):\n worksheetInfo.write_string(row, 1, infoText[i])\n row=row+1\n return (worksheetProfile, worksheetBasal, worksheetIsf, excel_2decimals_format, excel_integer_format)\n\n# sort filenames. First on date and then on run number\n# put settings/profile.js\ndef sortedFilenames():\n filelist=glob.glob(\"settings/profile.json\")\n filelist=filelist+glob.glob(\"settings/pumpprofile.json\")\n profiles=glob.glob(\"autotune/profile*.json\")\n listdateandrun=[]\n for i in profiles:\n date, run = parseDateAndRun(i)\n sortkey=\"%s-%3d\" % (date,int(run))\n listdateandrun.append((sortkey,i))\n listdateandrun.sort()\n for (daterun,filename) in listdateandrun:\n filelist.append(filename)\n return filelist\n\n# global constants\nPROFILE_FIELDS=['max_iob', 'carb_ratio', 'csf', 'max_basal', 'sens']\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Export oref0 autotune files to Microsoft Excel')\n parser.add_argument('-d', '--dir', help='openaps directory', default='.')\n parser.add_argument('-o', '--output', help='default autotune.xlsx', default='autotune.xlsx')\n parser.add_argument('--version', action='version', version='%(prog)s 0.0.4-dev')\n args = parser.parse_args()\n\n # change to openaps directory\n os.chdir(args.dir)\n\n print(\"Writing headers to Microsoft Excel file %s\" % args.output)\n workbook = xlsxwriter.Workbook(args.output)\n (worksheetProfile,worksheetBasal, worksheetIsf,excel_2decimals_format,excel_integer_format)=excel_init_workbook(workbook)\n row=1 # start on second row, row=0 is for headers\n filenamelist=sortedFilenames()\n for filename in filenamelist:\n f=open(filename, 'r')\n print(\"Adding %s to Excel\" % filename)\n j=json.load(f)\n try:\n basalProfile=j['basalprofile']\n isfProfile=j['isfProfile']['sensitivities']\n expandedBasal=expandProfile(basalProfile, 'rate', 'minutes')\n expandedIsf=expandProfile(isfProfile, 'sensitivity', 'offset')\n write_timebased_profile(worksheetBasal, row, expandedBasal, excel_2decimals_format)\n write_timebased_profile(worksheetIsf, row, expandedIsf, excel_integer_format)\n write_profile(worksheetProfile, row, j, excel_integer_format)\t\n row=row+1\n except Exception as e:\n if 'error' in j:\n print(\"Skipping file. Error: %s \" % j['error'])\n else:\n print(\"Skipping file. Exception: %s\" % e)\n \n workbook.close() \n print(\"Written %d lines to Excel\" % row)\n","repo_name":"openaps/oref0","sub_path":"bin/oref0-autotune-export-to-xlsx.py","file_name":"oref0-autotune-export-to-xlsx.py","file_ext":"py","file_size_in_byte":7705,"program_lang":"python","lang":"en","doc_type":"code","stars":424,"dataset":"github-code","pt":"43"} +{"seq_id":"15310022959","text":"#[Bài tập] Vẽ đường xoắn ốc\nimport math\nimport turtle\nn = turtle.Turtle()\nn.speed(10)\nn.setpos(0,0)\ndistance = 1 \nangle = 5\nfor i in range (0,120,1):\n n.forward(distance + i) \n n.left(angle + 15)\n\n","repo_name":"Nhan-L/Codegym-learning-process","sub_path":"while_veduongxoanoc.py","file_name":"while_veduongxoanoc.py","file_ext":"py","file_size_in_byte":216,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"4909154185","text":"##### Die Simulator ##########\n\n# Game Rules..! \n# if you bring 6 three times you win\n# if you bring 1 three times you lose\n\nfrom random import randint\nwin_count = 0\nlose_count = 0\n\ndice = ['1️⃣','2️⃣','3️⃣','4️⃣','5️⃣','6️⃣']\n\nwhile True:\n input(\"Press enter to 🎲Roll dice\")\n out = randint(1,6)\n print(f'🎲 => {dice[out-1]}')\n\n if out == 6:\n win_count+=1\n elif out ==1:\n lose_count+=1\n if win_count == 3:\n print(\"You win 👑\")\n break\n elif lose_count ==3:\n print(\"You lose ☠️\")\n break\n\n#make an edit of consecutive occurence of 6 and 1","repo_name":"RayanAhmed2000/Python-with-DS---Digipodium","sub_path":"Basics/die_simulator.py","file_name":"die_simulator.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"43"} +{"seq_id":"70532328450","text":"from contextlib import contextmanager\n\nfrom flask import current_app, render_template, url_for\n\nfrom .globals import _plugin_ctx_stack, current_plugin\nfrom .util import classproperty, get_state, trim_docstring, wrap_in_plugin_context\n\n\ndef depends(*plugins):\n \"\"\"Adds dependencies for a plugin.\n\n This decorator adds the given dependencies to the plugin. Multiple\n dependencies can be specified using multiple arguments or by using\n the decorator multiple times.\n\n :param plugins: plugin names\n \"\"\"\n\n def wrapper(cls):\n cls.required_plugins |= frozenset(plugins)\n return cls\n\n return wrapper\n\n\ndef uses(*plugins):\n \"\"\"Adds soft dependencies for a plugin.\n\n This decorator adds the given soft dependencies to the plugin.\n Multiple soft dependencies can be specified using multiple arguments\n or by using the decorator multiple times.\n\n Unlike dependencies, the specified plugins will be loaded before the\n plugin if possible, but if they are not available, the plugin will be\n loaded anyway.\n\n :param plugins: plugin names\n \"\"\"\n\n def wrapper(cls):\n cls.used_plugins |= frozenset(plugins)\n return cls\n\n return wrapper\n\n\ndef render_plugin_template(template_name_or_list, **context):\n \"\"\"Renders a template from the plugin's template folder with the given context.\n\n If the template name contains a plugin name (``pluginname:name``), that\n name is used instead of the current plugin's name.\n\n :param template_name_or_list: the name of the template or an iterable\n containing template names (the first\n existing template is used)\n :param context: the variables that should be available in the\n context of the template.\n \"\"\"\n if not isinstance(template_name_or_list, str):\n if not current_plugin and not all(':' in tpl for tpl in template_name_or_list):\n raise RuntimeError('render_plugin_template outside plugin context')\n template_name_or_list = [f'{current_plugin.name}:{tpl}' if ':' not in tpl else tpl\n for tpl in template_name_or_list]\n elif ':' not in template_name_or_list:\n if not current_plugin:\n raise RuntimeError('render_plugin_template outside plugin context')\n template_name_or_list = f'{current_plugin.name}:{template_name_or_list}'\n return render_template(template_name_or_list, **context)\n\n\ndef url_for_plugin(endpoint, **values):\n \"\"\"Like url_for but prepending plugin_ to endpoint.\"\"\"\n endpoint = f'plugin_{endpoint}'\n return url_for(endpoint, **values)\n\n\nclass Plugin:\n package_name = None # set to the containing package when the plugin is loaded\n package_version = None # set to the version of the containing package when the plugin is loaded\n version = None # set to the package_version if it's None when the plugin is loaded\n name = None # set to the entry point name when the plugin is loaded\n root_path = None # set to the path of the module containing the class when the plugin is loaded\n required_plugins = frozenset()\n used_plugins = frozenset()\n\n def __init__(self, plugin_engine, app):\n self.plugin_engine = plugin_engine\n self.app = app\n with self.app.app_context():\n with self.plugin_context():\n self.init()\n\n def init(self):\n \"\"\"Initializes the plugin at application startup.\n\n Should be overridden in your plugin if you need initialization.\n Runs inside an application context.\n \"\"\"\n pass\n\n @classproperty\n @classmethod\n def instance(cls):\n \"\"\"The Plugin instance used by the current app\"\"\"\n instance = get_state(current_app).plugin_engine.get_plugin(cls.name)\n if instance is None:\n raise RuntimeError('Plugin is not active in the current app')\n return instance\n\n @classproperty\n @classmethod\n def title(cls):\n \"\"\"The title of the plugin.\n\n Automatically retrieved from the docstring of the plugin class.\n \"\"\"\n parts = trim_docstring(cls.__doc__).split('\\n', 1)\n return parts[0].strip()\n\n @classproperty\n @classmethod\n def description(cls):\n \"\"\"The description of the plugin.\n\n Automatically retrieved from the docstring of the plugin class.\n \"\"\"\n parts = trim_docstring(cls.__doc__).split('\\n', 1)\n try:\n return parts[1].strip()\n except IndexError:\n return 'no description available'\n\n @contextmanager\n def plugin_context(self):\n \"\"\"Pushes the plugin on the plugin context stack.\"\"\"\n _plugin_ctx_stack.push(self)\n try:\n yield\n finally:\n assert _plugin_ctx_stack.pop() is self, 'Popped wrong plugin'\n\n def connect(self, signal, receiver, **connect_kwargs):\n connect_kwargs['weak'] = False\n signal.connect(wrap_in_plugin_context(self, receiver), **connect_kwargs)\n\n def __repr__(self):\n return '<{}({}) bound to {}>'.format(type(self).__name__, self.name, self.app)\n","repo_name":"indico/flask-pluginengine","sub_path":"flask_pluginengine/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":5146,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"43"} +{"seq_id":"73613496450","text":"# Un permis de chasse à points remplace désormais le permis de chasse traditionnel. Chaque chasseur possède au départ un capital de 100 points. S'il tue une poule il perd 1 point, 3 points pour 1 chien, 5 points pour une vache et 10 points pour un ami. Le permis co��te 200 euros. Écrire une fonction amende qui reçoit le nombre de victimes du chasseur et qui renvoie la somme due.\n\n#  \n\n# Utilisez cette fonction dans un programme principal qui saisit le nombre de victimes et qui affiche la somme que le chasseur doit débourser.\n\n# victimes = int(input(\"Entrer le nombre de victimes : \"))\n\nchasseurInfos = { \"name\" : \"nomChasseur\", \n \"capital\" : 100, \n \"cout\" : 200,\n \"victimes\" : \n {\n \"poule\" : 1, \n \"chien\" : 3, \n \"vache\" : 5, \n \"ami\" : 10\n }\n }\n\nchasseurInfos[\"name\"] = input(\"nom chasseur : \")\npoule = int(input(\"Entrer le nombre des poules : \"))\nchien = int(input(\"Entrer le nombre des chiens : \"))\nvache = int(input(\"Entrer le nombre des vaches : \"))\nami = int(input(\"Entrer le nombre des amis : \"))\n# points = 100\n# cout = 200\n\nif chasseurInfos[\"capital\"] > 0 : \n p = poule * chasseurInfos[\"victimes\"][\"poule\"]\n c = chien * chasseurInfos[\"victimes\"][\"chien\"]\n v = vache * chasseurInfos[\"victimes\"][\"vache\"]\n a = ami * chasseurInfos[\"victimes\"][\"ami\"]\n name = chasseurInfos[\"name\"]\n rslt = p + c + v + a\n print(\"Le nombre de victimes que vous avez chassée est :\", rslt)\n\n if rslt > chasseurInfos[\"capital\"]:\n print(\"Vous avez perdu votre permis Mr.\", name)\n else: \n chasseurInfos[\"capital\"] -= rslt\n print(\"Il faut payer\", rslt * 2, \"Euro Mr.\", name)\n\n","repo_name":"BARI-Zakaria/Python-Training","sub_path":"Training/Modules.py","file_name":"Modules.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"fr","doc_type":"code","stars":2,"dataset":"github-code","pt":"43"} +{"seq_id":"42813946786","text":"'''\nCompute unigram counts from a corpus\n\nUsage: python script.py < wikitext-103.train > counts.txt \n'''\nimport sys\nimport math\n\nunigrams = {}\ntotal = 0\nfor line in sys.stdin:\n for word in line.strip().split():\n if word not in unigrams:\n unigrams[word] = 0.0\n unigrams[word] += 1.0\n total += 1.0\nprint('word unigram')\nfor word in unigrams:\n print(word+' '+str(math.log(unigrams[word] / total)))\n \n","repo_name":"vansky/replications","sub_path":"vanschijndel_linzen-2019-scil/scripts/calcunigram.py","file_name":"calcunigram.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"43"} +{"seq_id":"126683889","text":"import SimpleCV\nimport json\nimport os\n\n#for now this will use the HaarCascade method to look for face's\n\nclass FaceFinder():\n def __init__(self, config_file = os.path.dirname(os.path.abspath(__file__)) + '/config'):\n _file = open(config_file, 'r')\n _conf = json.loads(_file.read())\n _file.close()\n\n self.img = _conf['img']\n self.faceTrainer = '/usr/local/lib/python2.7/dist-packages/SimpleCV/Features/HaarCascades/face2.xml'\n\n def useImgUrl(self, _url):\n self.img = _url\n\n def setImage(self):\n self.image = SimpleCV.Image(self.img)\n\n def countFaces(self):\n matches = 0\n facedetect = self.image.findHaarFeatures(self.faceTrainer)\n for faces in facedetect:\n matches += 1\n return matches\n","repo_name":"knkp/FamiCamBot","sub_path":"utils/FaceFinder.py","file_name":"FaceFinder.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"16205881735","text":"#!/usr/bin/env python\n# encoding:utf-8\n# Filename : my_tf_broadcaster.py\n# Author : csyls\n# Created Date : 2014/07/21\n# Descriptiont : tf坐标转换\nimport roslib\n##roslib.load_manifest('learning_tf')\nimport rospy\nimport tf\n\nnode_name = \"my_tf_broadcaster\"\n\nif __name__ == '__main__':\n rospy.init_node(node_name)\n r = rospy.Rate(50) ##速率单位为赫兹,可修改\n br = tf.TransformBroadcaster()\n while True:\n br.sendTransform((-0.215, 0.0, 0.0), tf.transformations.quaternion_from_euler(0.0, 0.0, 0.0), rospy.Time.now(), \"base_link\", \"laser\")\n r.sleep()\n\n rospy.spin()\n","repo_name":"ihainan/BITAtHomeSummer","sub_path":"bitathome_navigation_module/scripts/my_tf_broadcaster.py","file_name":"my_tf_broadcaster.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"43"} +{"seq_id":"7277309142","text":"import torch\nimport torch.nn as nn\n\nimport math\nimport copy\nimport numpy as np\nimport pickle\nimport matplotlib.pyplot as plt\nimport torch.nn.functional as F\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\ndef mlp(input_dim, hidden_dim, output_dim, hidden_depth, output_mod=None):\n if hidden_depth == 0:\n mods = [nn.Linear(input_dim, output_dim)]\n else:\n mods = [nn.Linear(input_dim, hidden_dim), nn.ReLU(inplace=True)]\n for i in range(hidden_depth - 1):\n mods += [nn.Linear(hidden_dim, hidden_dim), nn.ReLU(inplace=True)]\n mods.append(nn.Linear(hidden_dim, output_dim))\n if output_mod is not None:\n mods.append(output_mod)\n trunk = nn.Sequential(*mods)\n return trunk\n\nclass RLPolicy(nn.Module):\n def __init__(self, num_inputs, num_outputs, hidden_dim=64, hidden_depth=2):\n super(RLPolicy, self).__init__()\n self.trunk = mlp(num_inputs, hidden_dim, num_outputs*2, hidden_depth)\n\n def forward(self, x):\n outs = self.trunk(x)\n mu, logstd = torch.split(outs, outs.shape[-1] // 2, dim=-1)\n std = torch.exp(logstd)\n return mu, std, logstd\n\nclass RLBaseline(nn.Module):\n def __init__(self, num_inputs, hidden_dim=64, hidden_depth=2):\n super(RLBaseline, self).__init__()\n self.trunk = mlp(num_inputs, hidden_dim, 1, hidden_depth)\n\n def forward(self, x):\n v = self.trunk(x)\n return v\n\ndef get_action(mu, std):\n action = torch.normal(mu, std)\n action = action.data.cpu().detach().numpy()\n return action\n\ndef log_density(x, mu, std, logstd):\n var = std.pow(2)\n log_density = -(x - mu).pow(2) / (2 * var) \\\n - 0.5 * math.log(2 * math.pi) - logstd\n return log_density.sum(1, keepdim=True)\n\n# Define the forward model\nclass BCPolicy(nn.Module):\n def __init__(self, obs_dim, action_dim, hidden_dim, hidden_depth):\n super().__init__()\n self.trunk = mlp(obs_dim, hidden_dim, action_dim, hidden_depth)\n\n def forward(self, obs):\n next_pred = self.trunk(obs)\n return next_pred\n\n def get_action(self, obs, **kwargs):\n obs_t = torch.tensor(obs).float().to(device)\n return self.forward(obs_t).cpu().detach().numpy()\n\ndef rollout(\n env,\n agent,\n agent_name, # Should be bc, dagger, pg\n episode_length=math.inf,\n render=False,\n):\n # Collect the following data\n raw_obs = []\n raw_next_obs = []\n actions = []\n rewards = []\n dones = []\n images = []\n\n entropy = None\n log_prob = None\n agent_info = None\n path_length = 0\n\n o = env.reset()\n if render:\n env.render()\n\n while path_length < episode_length:\n o_for_agent = o\n\n if agent_name == 'bc' or agent_name == 'dagger':\n action = agent.get_action(o_for_agent)\n elif agent_name.lower() == 'pg':\n mu, std, _ = agent(torch.Tensor(o_for_agent).unsqueeze(0).to(device))\n action = get_action(mu, std)[0]\n else:\n raise KeyError(\"Invalid agent name\")\n\n # Step the simulation forward\n next_o, r, done, env_info = env.step(copy.deepcopy(action))\n \n # Render the environment\n if render:\n env.render()\n\n raw_obs.append(o)\n raw_next_obs.append(next_o)\n actions.append(action)\n rewards.append(r)\n dones.append(done)\n path_length += 1\n if done:\n break\n o = next_o\n\n # Prepare the items to be returned\n observations = np.array(raw_obs)\n next_observations = np.array(raw_next_obs)\n actions = np.array(actions)\n if len(actions.shape) == 1:\n actions = np.expand_dims(actions, 1)\n rewards = np.array(rewards)\n if len(rewards.shape) == 1:\n rewards = rewards.reshape(-1, 1)\n dones = np.array(dones).reshape(-1, 1)\n \n # Return in the following format\n return dict(\n observations=observations,\n next_observations=next_observations,\n actions=actions,\n rewards=rewards,\n dones=np.array(dones).reshape(-1, 1),\n images = np.array(images)\n )\n\ndef generate_paths(env, expert_policy, episode_length, num_paths, file_path):\n # Initial data collection\n paths = []\n for j in range(num_paths):\n path = rollout(\n env,\n expert_policy,\n agent_name='bc',\n episode_length=episode_length,\n render=False)\n print(\"return is \" + str(path['rewards'].sum()))\n paths.append(path)\n\n with open(file_path, 'wb') as fp:\n pickle.dump(paths, fp)\n print('Paths has been save to the file')\n\ndef get_expert_data(file_path):\n with open(file_path, 'rb') as fp:\n expert_data = pickle.load(fp)\n print('Imported Expert data successfully')\n return expert_data\n\ndef relabel_action(path, expert_policy):\n observation = path['observations']\n expert_action = expert_policy.get_action(observation)\n path['actions'] = expert_action[0]\n return path\n\ndef combine_sample_trajs(sample_trajs):\n assert len(sample_trajs) > 0\n\n my_dict = {k: [] for k in sample_trajs[0]}\n sample_trajs[0].keys()\n for sample_traj in sample_trajs:\n for key, value in sample_traj.items():\n my_dict[key].append(value)\n \n for key, value in my_dict.items():\n my_dict[key] = np.array(value)\n\n return my_dict\n","repo_name":"abhishekunique/cse571_hw3","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5418,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"43"} +{"seq_id":"35586427889","text":"import dgl.function as fn\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom dgl.nn.pytorch.glob import (AvgPooling, GlobalAttentionPooling,\n MaxPooling, SumPooling)\n\n\nclass GINLayer(nn.Module):\n r\"\"\"Single Layer GIN from `Strategies for\n Pre-training Graph Neural Networks <https://arxiv.org/abs/1905.12265>`__\n\n Parameters\n ----------\n num_edge_emb_list : list of int\n num_edge_emb_list[i] gives the number of items to embed for the\n i-th categorical edge feature variables. E.g. num_edge_emb_list[0] can be\n the number of bond types and num_edge_emb_list[1] can be the number of\n bond direction types.\n emb_dim : int\n The size of each embedding vector.\n batch_norm : bool\n Whether to apply batch normalization to the output of message passing.\n Default to True.\n activation : None or callable\n Activation function to apply to the output node representations.\n Default to None.\n \"\"\"\n\n def __init__(self, emb_dim, activation=None):\n super(GINLayer, self).__init__()\n\n self.mlp = nn.Sequential(\n nn.Linear(emb_dim, 2 * emb_dim),\n nn.ReLU(),\n nn.Linear(2 * emb_dim, emb_dim)\n )\n self.bn = nn.BatchNorm1d(emb_dim)\n self.activation = activation\n self.reset_parameters()\n self.eps = torch.nn.Parameter(torch.FloatTensor([0]))\n\n def reset_parameters(self):\n \"\"\"Reinitialize model parameters.\"\"\"\n for layer in self.mlp:\n if isinstance(layer, nn.Linear):\n layer.reset_parameters()\n\n if self.bn is not None:\n self.bn.reset_parameters()\n\n def forward(self, g, node_feats):\n \"\"\"Update node representations.\n\n Parameters\n ----------\n g : DGLGraph\n DGLGraph for a batch of graphs\n node_feats : FloatTensor of shape (N, emb_dim)\n * Input node features\n * N is the total number of nodes in the batch of graphs\n * emb_dim is the input node feature size, which must match emb_dim in initialization\n categorical_edge_feats : list of LongTensor of shape (E)\n * Input categorical edge features\n * len(categorical_edge_feats) should be the same as len(self.edge_embeddings)\n * E is the total number of edges in the batch of graphs\n\n Returns\n -------\n node_feats : float32 tensor of shape (N, emb_dim)\n Output node representations\n \"\"\"\n\n g = g.local_var()\n g.ndata['feat'] = node_feats\n g.update_all(fn.copy_u('feat', 'm'), fn.sum('m', 'neigh'))\n node_feats = (1 + self.eps) * g.ndata['feat'] + g.ndata['neigh']\n node_feats = self.bn(self.mlp(node_feats))\n if self.activation is not None:\n node_feats = self.activation(node_feats)\n return node_feats\n\n\nclass GINEncoder(nn.Module):\n def __init__(self, num_layers=5,\n emb_dim=300, JK='last', dropout=0.5, readout='mean', n_tasks=1):\n super(GINEncoder, self).__init__()\n\n self.num_layers = num_layers\n self.JK = JK\n self.dropout = nn.Dropout(dropout)\n\n if num_layers < 2:\n raise ValueError('Number of GNN layers must be greater '\n 'than 1, got {:d}'.format(num_layers))\n\n self.gnn_layers = nn.ModuleList()\n for layer in range(num_layers):\n if layer == num_layers - 1:\n self.gnn_layers.append(GINLayer(emb_dim))\n else:\n self.gnn_layers.append(GINLayer(emb_dim, activation=F.relu))\n\n if readout == 'sum':\n self.readout = SumPooling()\n elif readout == 'mean':\n self.readout = AvgPooling()\n elif readout == 'max':\n self.readout = MaxPooling()\n elif readout == 'attention':\n if JK == 'concat':\n self.readout = GlobalAttentionPooling(\n gate_nn=nn.Linear((num_layers + 1) * emb_dim, 1))\n else:\n self.readout = GlobalAttentionPooling(\n gate_nn=nn.Linear(emb_dim, 1))\n else:\n raise ValueError(\"Expect readout to be 'sum', 'mean', \"\n \"'max' or 'attention', got {}\".format(readout))\n self.reset_parameters()\n\n def reset_parameters(self):\n \"\"\"Reinitialize model parameters.\"\"\"\n\n for layer in self.gnn_layers:\n layer.reset_parameters()\n\n def forward(self, g, node_feats):\n all_layer_node_feats = [node_feats]\n for layer in range(self.num_layers):\n node_feats = self.gnn_layers[layer](g, all_layer_node_feats[layer])\n node_feats = self.dropout(node_feats)\n all_layer_node_feats.append(node_feats)\n\n if self.JK == 'concat':\n final_node_feats = torch.cat(all_layer_node_feats, dim=1)\n elif self.JK == 'last':\n final_node_feats = all_layer_node_feats[-1]\n elif self.JK == 'max':\n all_layer_node_feats = [h.unsqueeze(\n 0) for h in all_layer_node_feats]\n final_node_feats = torch.max(\n torch.cat(all_layer_node_feats, dim=0), dim=0)[0]\n elif self.JK == 'sum':\n all_layer_node_feats = [h.unsqueeze(\n 0) for h in all_layer_node_feats]\n final_node_feats = torch.sum(\n torch.cat(all_layer_node_feats, dim=0), dim=0)\n else:\n return ValueError(\"Expect self.JK to be 'concat', 'last', \"\n \"'max' or 'sum', got {}\".format(self.JK))\n\n graph_feats = self.readout(g, final_node_feats)\n return graph_feats\n","repo_name":"zhandand/MedicalDecision","sub_path":"model/gnn/gin.py","file_name":"gin.py","file_ext":"py","file_size_in_byte":5766,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"43"} +{"seq_id":"25709754069","text":"\"\"\"\nThis module preps a neural tensor from trial data for LFADS training.\n\"\"\"\n\n#%%\nimport src.data\nimport src.lfads_helpers\nimport yaml\nimport pyaldata\nimport pandas as pd\n\nwith open(\"params.yaml\", \"r\") as params_file:\n params = yaml.safe_load(params_file)[\"lfads_prep\"]\n\n\ndef prep_and_save_data(td, save_path):\n \"\"\"\n This function takes a trial data file and writes a data file with\n the neural tensor and lfads rates added to it.\n\n Parameters\n ----------\n td : pandas.DataFrame\n Trial data file.\n save_path : str\n Path to save the trial data file.\n \"\"\"\n tensor_list, trial_ids = src.lfads_helpers.prep_neural_tensors(\n td,\n signal=\"MC_spikes\",\n bin_size=params[\"bin_size\"],\n window_len=params[\"window_len\"],\n overlap=params[\"overlap\"],\n )\n src.lfads_helpers.write_tensor_to_hdf(\n tensor_list, trial_ids, save_path,\n )\n\n\n#%%\ndef main():\n # trial_data = src.data.load_clean_data(\"data/trial_data/Earl_20190716_COCST_TD.mat\")\n # td_co = trial_data.groupby(\"task\").get_group(\"CO\")\n # prep_and_save_data(td_co, \"data/pre-lfads/Earl_20190716_CO_tensors.hdf5\")\n # td_cst = trial_data.groupby(\"task\").get_group(\"CST\")\n # prep_and_save_data(td_cst, \"data/pre-lfads/Earl_20190716_CST_tensors.hdf5\")\n\n filename = 'data/trial_data/Prez_20220721_RTTCST_TD.mat'\n # filename = 'data/trial_data/Earl_20190716_COCST_TD.mat'\n td = (\n pyaldata.mat2dataframe(\n filename,\n shift_idx_fields=True,\n td_name='trial_data'\n )\n .assign(\n date_time=lambda x: pd.to_datetime(x['date_time']),\n session_date=lambda x: pd.DatetimeIndex(x['date_time']).normalize()\n )\n .query('task==\"RTT\" | task==\"CST\"')\n .pipe(src.data.remove_aborts, verbose=params['verbose'])\n .pipe(src.data.remove_artifact_trials, verbose=params['verbose'])\n .pipe(\n src.data.filter_unit_guides,\n filter_func=lambda guide: guide[:,1] >= (0 if params['keep_unsorted'] else 1)\n )\n .pipe(src.data.remove_correlated_units,verbose=params['verbose'])\n .pipe(\n src.data.remove_all_low_firing_neurons,\n threshold=0.1,\n divide_by_bin_size=True,\n verbose=params['verbose']\n )\n )\n prep_and_save_data(td, \"data/pre-lfads/Prez_20220721_RTTCST_tensors.hdf5\")\n\n\nif __name__=='__main__':\n main()\n# %%\n","repo_name":"raeedcho/cst-dynamics","sub_path":"scripts/prep_data.py","file_name":"prep_data.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"37265784132","text":"from sklearn import datasets\r\nimport numpy as np\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense\r\nfrom keras.wrappers.scikit_learn import KerasRegressor\r\nfrom sklearn.model_selection import cross_val_score, KFold, GridSearchCV\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.pipeline import Pipeline\r\n\r\n# load data\r\ndataset = datasets.load_boston()\r\n\r\nx = dataset.data\r\nY = dataset.target\r\n\r\nseed = 7\r\nnp.random.seed(seed)\r\n\r\n# define and create model\r\ndef create_model(units_list=[13],optimizer='adam',init='normal'):\r\n model = Sequential()\r\n\r\n # create the first hidden layer and input layer\r\n units = units_list[0]\r\n model.add(Dense(units=units,activation='relu',input_dim=13,kernel_initializer=init))\r\n\r\n # create more hidden layers\r\n for units in units_list[1:]:\r\n model.add(Dense(units=units,activation='relu',kernel_initializer=init))\r\n\r\n model.add(Dense(units=1,kernel_initializer=init))\r\n\r\n # compile the model\r\n model.compile(loss='mean_squared_error',optimizer=optimizer)\r\n\r\n return model\r\n\r\nmodel = KerasRegressor(build_fn=create_model,epochs=200,batch_size=5,verbose=0)\r\n\r\n# evaluate\r\nkfold = KFold(n_splits=10,shuffle=True,random_state=seed)\r\nresults = cross_val_score(model,x,Y,cv=kfold)\r\nprint('Baseline: %.2f (%.2f) MSE' % (results.mean(),results.std()))\r\n\r\n# improve the algorithm\r\nsteps = []\r\nsteps.append(('standardize',StandardScaler()))\r\nsteps.append(('mlp',model))\r\npipeline = Pipeline(steps)\r\nkfold = KFold(n_splits=10,shuffle=True,random_state=seed)\r\nresults = cross_val_score(pipeline,x,Y,cv=kfold)\r\nprint('Standardize: %.2f (%.2f) MSE' %(results.mean(),results.std()))\r\n\r\n# parameters adjustments\r\nparam_grid = {}\r\nparam_grid['units_list'] = [[20],[13,6]]\r\nparam_grid['optimizer'] = ['rmsprop','adam']\r\nparam_grid['init'] = ['glorot_uniform','normal']\r\nparam_grid['epochs'] = [100,200]\r\nparam_grid['batch_size'] = [5,20]\r\n\r\nscaler = StandardScaler()\r\nscaler_x = scaler.fit_transform(x)\r\ngrid = GridSearchCV(estimator=model,param_grid=param_grid)\r\nresults = grid.fit(scaler_x,Y)\r\n\r\n# print the results\r\nprint('Best: %f using %s' % (results.best_score_,results.best_params_))\r\nmeans = results.cv_results_['mean_test_score']\r\nstds = results.cv_results_['std_test_score']\r\nparams = results.cv_results_['params']\r\n\r\nfor mean,std,param in zip(means,stds,params):\r\n print('%f (%f) with: %r' % (mean, std, param))","repo_name":"gfreya/PythonPracticeBasedonKeras","sub_path":"7. Boston House Price.py","file_name":"7. Boston House Price.py","file_ext":"py","file_size_in_byte":2409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"38806895892","text":"\"\"\"\r\nthis is not done, this will be continues when I have more knowledge on selenium.\r\n\"\"\"\r\n\r\nfrom selenium import webdriver\r\nimport time\r\n\r\n\r\nclass MessageSender:\r\n\r\n def __init__(self, contact, message):\r\n self.message = message\r\n self.contact = contact\r\n self.driver = webdriver.Chrome(\"chromedriver.exe\")\r\n\r\n def WriteMessage(self):\r\n self.driver.get(\"https://web.whatsapp.com/\")\r\n\r\n try:\r\n xPath=f'//span[@title = \"{self.contact}\"]'\r\n user =self.driver.find_element_by_xpath(xPath)\r\n user.click()\r\n\r\n except:\r\n self.Writemessage()\r\n\r\n textBox=self.driver.find_element_by_class_name(\"DuUXI\")\r\n textBox.click()\r\n textBox.send_keys(self.message,1)\r\n \r\n time.sleep(1)\r\n\r\n #button = self.driver.find_element_by_class_name(\"_2Ujuu\")\r\n #button.click()\r\n self.driver.close()\r\n\r\n\r\n\r\n\r\n\r\n def sendmessage(self, counter):\r\n print(\"write message\")\r\n self.WriteMessage()\r\n time.sleep(1)\r\n print(\"message sent\")\r\n\r\n\r\ntime.sleep(5)\r\nmessage=MessageSender(\"+44 7419 362308\",\"testing 1\\n\")\r\nmessage.sendmessage(1)\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"Amin-Abdul-Awal/Automatic-desktop-change","sub_path":"messageSender.py","file_name":"messageSender.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"34968045314","text":"import collections\nfrom typing import Any, Callable, FrozenSet, Mapping, Optional, Sequence, Tuple\n\nfrom absl import logging\nimport cv2\nfrom dm_env import specs\nfrom dm_robotics.agentflow import spec_utils\nfrom dm_robotics.agentflow.decorators import overrides\nfrom dm_robotics.agentflow.preprocessors import timestep_preprocessor as tsp\nfrom dm_robotics.geometry import geometry\nimport numpy as np\n\n# Internal profiling\n\n\nclass MisconfigurationError(Exception):\n \"\"\"Error raised when the preprocessor is misconfigured.\"\"\"\n\n\nclass CastPreprocessor(tsp.TimestepPreprocessor):\n \"\"\"Preprocessor to cast observations, reward and discount.\"\"\"\n\n def __init__(\n self,\n dtype: type = np.float32, # pylint: disable=g-bare-generic\n validation_frequency: tsp.ValidationFrequency = (\n tsp.ValidationFrequency.ONCE_PER_EPISODE),\n ):\n \"\"\"Initialize CastPreprocessor.\n\n Args:\n dtype: The target dtype to cast to.\n validation_frequency: How often should we validate the obs specs.\n \"\"\"\n super().__init__(validation_frequency)\n self._dtype = dtype\n\n @overrides(tsp.TimestepPreprocessor)\n # Profiling for .wrap('CastPreprocessor._process_impl')\n def _process_impl(\n self, timestep: tsp.PreprocessorTimestep) -> tsp.PreprocessorTimestep:\n cast_obs = {\n k: np.asarray(v).astype(self._dtype)\n for k, v in timestep.observation.items()\n }\n\n return tsp.PreprocessorTimestep(\n step_type=timestep.step_type,\n reward=(self._dtype(timestep.reward) if np.isscalar(timestep.reward)\n else timestep.reward.astype(self._dtype)),\n discount=self._dtype(timestep.discount),\n observation=cast_obs,\n pterm=timestep.pterm,\n result=timestep.result)\n\n @overrides(tsp.TimestepPreprocessor)\n def _output_spec(\n self, input_spec: spec_utils.TimeStepSpec) -> spec_utils.TimeStepSpec:\n obs_spec = {\n k: v.replace(dtype=self._dtype)\n for k, v in input_spec.observation_spec.items()\n }\n return spec_utils.TimeStepSpec(\n observation_spec=obs_spec,\n reward_spec=input_spec.reward_spec.replace(dtype=self._dtype),\n discount_spec=input_spec.discount_spec.replace(dtype=self._dtype))\n\n\nclass DowncastFloatPreprocessor(tsp.TimestepPreprocessor):\n \"\"\"Preprocessor to cast observations, reward and discount.\n\n This preprocessor downcasts all floating point observations (etc)\n with more bits than the target dtype to the target dtype.\n\n It does not change the dtype of non-floating point data (e.g.\n uint8 in images).\n \"\"\"\n\n def __init__(\n self,\n max_float_dtype: type, # pylint: disable=g-bare-generic\n validation_frequency: tsp.ValidationFrequency = (\n tsp.ValidationFrequency.ONCE_PER_EPISODE),\n ):\n \"\"\"Initialize DowncastFloatPreprocessor.\n\n Args:\n max_float_dtype: The target dtype to cast floating point types with more\n bits to, e.g. np.float32.\n validation_frequency: How often should we validate the obs specs.\n \"\"\"\n super().__init__(validation_frequency)\n if not np.issubdtype(max_float_dtype, np.floating):\n raise ValueError('DowncastFloatPreprocessor only supports floating point '\n f'dtypes, not {max_float_dtype}')\n self._dtype = max_float_dtype\n self._max_bits = np.finfo(self._dtype).bits\n\n def _dtype_needs_downcast(self, dtype):\n return (np.issubdtype(dtype, np.floating) and\n np.finfo(dtype).bits > self._max_bits)\n\n def _downcast_if_necessary(self, value):\n if ((hasattr(value, 'dtype') and self._dtype_needs_downcast(value.dtype)) or\n self._dtype_needs_downcast(type(value))):\n return np.asarray(value).astype(self._dtype)\n else:\n return value\n\n @overrides(tsp.TimestepPreprocessor)\n # Profiling for .wrap('DowncastFloatPreprocessor._process_impl')\n def _process_impl(\n self, timestep: tsp.PreprocessorTimestep) -> tsp.PreprocessorTimestep:\n cast_obs = {\n k: self._downcast_if_necessary(v)\n for k, v in timestep.observation.items()\n }\n\n return tsp.PreprocessorTimestep(\n step_type=timestep.step_type,\n reward=self._downcast_if_necessary(timestep.reward),\n discount=self._downcast_if_necessary(timestep.discount),\n observation=cast_obs,\n pterm=timestep.pterm,\n result=timestep.result)\n\n @overrides(tsp.TimestepPreprocessor)\n def _output_spec(\n self, input_spec: spec_utils.TimeStepSpec) -> spec_utils.TimeStepSpec:\n obs_spec = {}\n for k, v in input_spec.observation_spec.items():\n if self._dtype_needs_downcast(v.dtype):\n obs_spec[k] = v.replace(dtype=self._dtype)\n else:\n obs_spec[k] = v\n\n if self._dtype_needs_downcast(input_spec.reward_spec.dtype):\n reward_spec_dtype = self._dtype\n else:\n reward_spec_dtype = input_spec.reward_spec.dtype\n\n if self._dtype_needs_downcast(input_spec.discount_spec.dtype):\n discount_spec_dtype = self._dtype\n else:\n discount_spec_dtype = input_spec.reward_spec.dtype\n\n return spec_utils.TimeStepSpec(\n observation_spec=obs_spec,\n reward_spec=input_spec.reward_spec.replace(dtype=reward_spec_dtype),\n discount_spec=input_spec.discount_spec.replace(\n dtype=discount_spec_dtype))\n\n\nclass ObsRelativeToEpisodeStartPreprocessor(tsp.TimestepPreprocessor):\n \"\"\"Offset specified observations to be relative to initial values.\"\"\"\n\n def __init__(\n self,\n target_obs: str,\n validation_frequency: tsp.ValidationFrequency = (\n tsp.ValidationFrequency.ONCE_PER_EPISODE),\n ):\n super().__init__(validation_frequency)\n self._target_obs = target_obs\n self._initial_values = {}\n\n @overrides(tsp.TimestepPreprocessor)\n # Profiling for .wrap('ObsRelativeToEpisodeStartPreprocessor._process_impl')\n def _process_impl(\n self, timestep: tsp.PreprocessorTimestep) -> tsp.PreprocessorTimestep:\n if timestep.first():\n self._initial_values = {}\n for k, v in timestep.observation.items():\n if k in self._target_obs:\n self._initial_values[k] = np.array(v)\n\n corrected_obs = {}\n\n for k, v in timestep.observation.items():\n if k in self._initial_values:\n corrected_obs[k] = v - self._initial_values[k]\n else:\n corrected_obs[k] = v\n\n return timestep._replace(observation=corrected_obs)\n\n @overrides(tsp.TimestepPreprocessor)\n def _output_spec(\n self, input_spec: spec_utils.TimeStepSpec) -> spec_utils.TimeStepSpec:\n return input_spec\n\n\nclass PoseRelativeToEpisodeStart(tsp.TimestepPreprocessor):\n \"\"\"Change pose observations to be relative to episode start.\"\"\"\n\n def __init__(\n self,\n pos_obs_name: str,\n quat_obs_name: str,\n validation_frequency: tsp.ValidationFrequency = (\n tsp.ValidationFrequency.ONCE_PER_EPISODE),\n ):\n \"\"\"PoseRelativeToEpisodeStart constructor.\n\n Args:\n pos_obs_name: Observation key of the pos observation.\n quat_obs_name: Observation key of the quaternion observation.\n validation_frequency: How often should we validate the obs specs.\n \"\"\"\n super().__init__(validation_frequency)\n self._pos_obs_name = pos_obs_name\n self._quat_obs_name = quat_obs_name\n self._initial_pose = None # type: Optional[geometry.PoseStamped]\n\n @overrides(tsp.TimestepPreprocessor)\n # Profiling for .wrap('PoseRelativeToEpisodeStart._process_impl')\n def _process_impl(\n self, timestep: tsp.PreprocessorTimestep) -> tsp.PreprocessorTimestep:\n\n pos = np.array(timestep.observation[self._pos_obs_name])\n quat = np.array(timestep.observation[self._quat_obs_name])\n\n if timestep.first():\n self._initial_pose = geometry.PoseStamped(geometry.Pose(pos, quat))\n\n corrected_obs = {}\n\n cur_pose = geometry.PoseStamped(geometry.Pose(pos, quat))\n rel_pose = geometry.frame_relative_pose(cur_pose, self._initial_pose)\n\n for k, v in timestep.observation.items():\n if k == self._pos_obs_name:\n corrected_obs[k] = rel_pose.position.astype(pos.dtype)\n elif k == self._quat_obs_name:\n corrected_obs[k] = rel_pose.quaternion.astype(quat.dtype)\n else:\n corrected_obs[k] = v\n\n return timestep._replace(observation=corrected_obs)\n\n @overrides(tsp.TimestepPreprocessor)\n def _output_spec(\n self, input_spec: spec_utils.TimeStepSpec) -> spec_utils.TimeStepSpec:\n\n if self._pos_obs_name not in input_spec.observation_spec:\n raise ValueError(f'{self._pos_obs_name} not in timestep observations')\n\n if self._quat_obs_name not in input_spec.observation_spec:\n raise ValueError(f'{self._quat_obs_name} not in timestep observations')\n\n return input_spec\n\n\nclass ObsOffsetAndScalingPreprocessor(tsp.TimestepPreprocessor):\n \"\"\"Preprocessor to offset and scale specified observations.\"\"\"\n\n def __init__(\n self,\n obs_offsets: Mapping[str, np.floating],\n obs_scales: Mapping[str, np.floating],\n validation_frequency: tsp.ValidationFrequency = (\n tsp.ValidationFrequency.ONCE_PER_EPISODE),\n ):\n super().__init__(validation_frequency)\n self._obs_offsets = obs_offsets\n self._obs_scales = obs_scales\n\n # Profiling for .wrap('ObsOffsetAndScalingPreprocessor._process_impl')\n def _process_impl(\n self, timestep: tsp.PreprocessorTimestep) -> tsp.PreprocessorTimestep:\n corrected_obs = {}\n\n for k, obs in timestep.observation.items():\n apply_offset = k in self._obs_offsets\n apply_scaling = k in self._obs_scales\n\n if apply_offset:\n obs -= obs.dtype.type(self._obs_offsets[k])\n\n if apply_scaling:\n obs /= obs.dtype.type(self._obs_scales[k])\n\n corrected_obs[k] = obs\n\n return timestep._replace(observation=corrected_obs)\n\n def _output_spec(\n self, input_spec: spec_utils.TimeStepSpec) -> spec_utils.TimeStepSpec:\n return input_spec\n\n\nclass RemoveObservations(tsp.TimestepPreprocessor):\n \"\"\"Removes the specified fields from observations.\"\"\"\n\n def __init__(\n self,\n obs_to_strip: Sequence[str],\n validation_frequency: tsp.ValidationFrequency = (\n tsp.ValidationFrequency.ONCE_PER_EPISODE),\n ):\n \"\"\"Initialize RemoveObs.\n\n Args:\n obs_to_strip: A list of strings corresponding to keys to remove from\n timestep.observation.\n validation_frequency: How often should we validate the obs specs.\n \"\"\"\n super().__init__(validation_frequency)\n self._obs_to_strip = obs_to_strip\n\n @overrides(tsp.TimestepPreprocessor)\n # Profiling for .wrap('RemoveObservations._process_impl')\n def _process_impl(\n self, timestep: tsp.PreprocessorTimestep) -> tsp.PreprocessorTimestep:\n retained_obs = {\n k: v\n for k, v in timestep.observation.items()\n if k not in self._obs_to_strip\n }\n\n return timestep._replace(observation=retained_obs)\n\n @overrides(tsp.TimestepPreprocessor)\n def _output_spec(\n self, input_spec: spec_utils.TimeStepSpec) -> spec_utils.TimeStepSpec:\n obs_spec = {\n k: v\n for k, v in input_spec.observation_spec.items()\n if k not in self._obs_to_strip\n }\n return input_spec.replace(observation_spec=obs_spec)\n\n\nclass RetainObservations(tsp.TimestepPreprocessor):\n \"\"\"Leaves only the specified observations.\"\"\"\n\n def __init__(\n self,\n obs_to_leave: Sequence[str],\n raise_on_missing=True,\n validation_frequency: tsp.ValidationFrequency = (\n tsp.ValidationFrequency.ONCE_PER_EPISODE),\n ):\n \"\"\"Initialize RetainObservations.\n\n Args:\n obs_to_leave: A list of strings corresponding to keys to retain in\n timestep.observation.\n raise_on_missing: Whether to raise a MisconfigurationError if we are asked\n to keep a non-existent observation.\n validation_frequency: How often should we validate the obs specs.\n \"\"\"\n super().__init__(validation_frequency)\n self._obs_to_leave: FrozenSet[str] = frozenset(obs_to_leave)\n self._raise_on_missing = raise_on_missing\n\n @overrides(tsp.TimestepPreprocessor)\n # Profiling for .wrap('RetainObservations._process_impl')\n def _process_impl(\n self, timestep: tsp.PreprocessorTimestep) -> tsp.PreprocessorTimestep:\n retained_obs = {\n k: v for k, v in timestep.observation.items() if k in self._obs_to_leave\n }\n return timestep._replace(observation=retained_obs)\n\n @overrides(tsp.TimestepPreprocessor)\n def _output_spec(\n self, input_spec: spec_utils.TimeStepSpec) -> spec_utils.TimeStepSpec:\n obs_spec = {\n k: v\n for k, v in input_spec.observation_spec.items()\n if k in self._obs_to_leave\n }\n not_in_spec = self._obs_to_leave - set(obs_spec)\n if not_in_spec:\n log_message = ('RetainObservations asked to retain observations that do '\n 'not exist in the incoming observation spec: '\n f'{not_in_spec}')\n if self._raise_on_missing:\n raise MisconfigurationError(log_message)\n else:\n logging.warning(log_message)\n return input_spec.replace(observation_spec=obs_spec)\n\n\nclass RenameObservations(tsp.TimestepPreprocessor):\n \"\"\"Renames a set of observations.\"\"\"\n\n def __init__(\n self,\n obs_mapping: Mapping[str, str],\n raise_on_missing: bool = True,\n raise_on_overwrite: bool = True,\n validation_frequency: tsp.ValidationFrequency = (\n tsp.ValidationFrequency.ONCE_PER_EPISODE),\n ):\n \"\"\"Initialize RenameObservations.\n\n Args:\n obs_mapping: Mapping from old and the new observation names.\n raise_on_missing: Whether to raise a MisconfigurationError if we are asked\n to rename a non-existent observation.\n raise_on_overwrite: Whether to raise a MisconfigurationError we are asked\n to rename an observation by overwriting an existing observation.\n validation_frequency: How often should we validate the obs specs.\n\n Raises:\n MisconfigurationError: If the mapping has duplicate names.\n \"\"\"\n super().__init__(validation_frequency)\n\n self._raise_on_missing = raise_on_missing\n self._raise_on_overwrite = raise_on_overwrite\n self._obs_mapping = obs_mapping\n # Check that there are no duplicates in the mapped names.\n if len(set(obs_mapping.values())) != len(obs_mapping.values()):\n log_message = (f'The new set of observation names {obs_mapping.values()}'\n ' has duplicate elements.')\n raise MisconfigurationError(log_message)\n\n @overrides(tsp.TimestepPreprocessor)\n # Profiling for .wrap('RenameObservations._process_impl')\n def _process_impl(\n self, timestep: tsp.PreprocessorTimestep) -> tsp.PreprocessorTimestep:\n observation = self._replace_obs(timestep.observation)\n return timestep._replace(observation=observation)\n\n @overrides(tsp.TimestepPreprocessor)\n def _output_spec(\n self, input_spec: spec_utils.TimeStepSpec) -> spec_utils.TimeStepSpec:\n obs_spec = input_spec.observation_spec\n self._check_valid_mapping(obs_spec)\n obs_spec = self._replace_obs(obs_spec)\n return input_spec.replace(observation_spec=obs_spec)\n\n def _replace_obs(self, orig: Mapping[str, Any]) -> Mapping[str, Any]:\n new_dict = {}\n for obs_key in orig:\n if obs_key in self._obs_mapping:\n new_dict[self._obs_mapping[obs_key]] = orig[obs_key]\n else:\n new_dict[obs_key] = orig[obs_key]\n return new_dict\n\n def _check_valid_mapping(self, obs_spec):\n \"\"\"Checks that the renaming of observations is valid.\"\"\"\n\n full_mapping = {key: key for key in obs_spec}\n full_mapping.update(self._obs_mapping)\n\n # Check that the renamed observations exist.\n not_in_spec = set(full_mapping) - set(obs_spec)\n if not_in_spec:\n log_message = ('RenameObservations asked to rename observations that do'\n 'not exist in the incoming observation spec: '\n f'{not_in_spec}')\n if self._raise_on_missing:\n raise MisconfigurationError(log_message)\n else:\n logging.warning(log_message)\n\n # Check that we do not overwrite existing observations.\n c = collections.Counter(full_mapping.values())\n overwritten_names = [key for key, count in c.items() if count > 1]\n if overwritten_names:\n log_message = ('RenameObservations asked to overwrite the following '\n f'existing observations: {overwritten_names}')\n if self._raise_on_overwrite:\n raise MisconfigurationError(log_message)\n else:\n logging.warning(log_message)\n\n\nclass MergeObservations(tsp.TimestepPreprocessor):\n \"\"\"Creates a single observation by merging several observations together.\"\"\"\n\n def __init__(\n self,\n obs_to_merge: Sequence[str],\n new_obs: str,\n raise_on_missing: bool = True,\n raise_on_overwrite: bool = True,\n validation_frequency: tsp.ValidationFrequency = (\n tsp.ValidationFrequency.ONCE_PER_EPISODE),\n ):\n \"\"\"Initialize MergeObservations.\n\n Args:\n obs_to_merge: Names of the observations to merge.\n new_obs: Name of the merged observation.\n raise_on_missing: Whether to raise a MisconfigurationError if we are asked\n to merge a non-existent observation.\n raise_on_overwrite: Whether to raise a MisconfigurationError if the\n new_obs name overwrites an existing observation.\n validation_frequency: How often should we validate the obs specs.\n \"\"\"\n\n super().__init__(validation_frequency)\n self._obs_to_merge = tuple(obs_to_merge)\n self._new_obs = new_obs\n self._raise_on_missing = raise_on_missing\n self._raise_on_overwrite = raise_on_overwrite\n\n @overrides(tsp.TimestepPreprocessor)\n # Profiling for .wrap('MergeObs._process_impl')\n def _process_impl(\n self, timestep: tsp.PreprocessorTimestep) -> tsp.PreprocessorTimestep:\n obs = dict(timestep.observation)\n # Create the merged observation.\n merged_obs = np.concatenate([\n timestep.observation[obs_key]\n for obs_key in self._obs_to_merge\n if obs_key in obs\n ])\n\n # Remove the observations that have been merged.\n for obs_key in self._obs_to_merge:\n obs.pop(obs_key)\n\n obs[self._new_obs] = merged_obs\n\n return timestep._replace(observation=obs)\n\n @overrides(tsp.TimestepPreprocessor)\n def _output_spec(\n self, input_spec: spec_utils.TimeStepSpec) -> spec_utils.TimeStepSpec:\n obs_spec = dict(input_spec.observation_spec)\n self._check_valid_merge(obs_spec)\n\n # Create the merged observation.\n model_array = np.concatenate([\n input_spec.observation_spec[obs_key].generate_value()\n for obs_key in self._obs_to_merge\n if obs_key in obs_spec\n ])\n\n # Remove the observations that have been merged.\n for obs_key in self._obs_to_merge:\n obs_spec.pop(obs_key)\n\n obs_spec[self._new_obs] = specs.Array(\n shape=model_array.shape, dtype=model_array.dtype, name=self._new_obs)\n return input_spec.replace(observation_spec=obs_spec)\n\n def _check_valid_merge(self, obs_spec):\n \"\"\"Checks if the observation merging is valid.\"\"\"\n all_current_names = set(obs_spec.keys())\n merged_names = set(self._obs_to_merge)\n # Check that the merged observations exist.\n not_in_spec = merged_names - all_current_names\n if not_in_spec:\n log_message = ('MergeObservations asked to merge observations that do not'\n f'exist in the incoming observation spec: {not_in_spec}')\n if self._raise_on_missing:\n raise MisconfigurationError(log_message)\n else:\n logging.warning(log_message)\n\n # Check that the merged observation name doesn't overwrite an existing one.\n available_names = all_current_names - merged_names\n if self._new_obs in available_names:\n log_message = ('MergeObservations asked to overwrite observation name: '\n f'{self._new_obs}')\n if self._raise_on_overwrite:\n raise MisconfigurationError(log_message)\n else:\n logging.warning(log_message)\n\n\nclass StackObservations(tsp.TimestepPreprocessor):\n \"\"\"A timestep preprocessor that stacks observations.\n\n This is useful for environments that are n-step markov (like a robot that\n takes a few cycles to reach the setpoints we command). On the initial\n timestep, all elements of the stack are initialized with the value of the\n first observation.\n \"\"\"\n\n def __init__(\n self,\n obs_to_stack: Sequence[str],\n stack_depth: int,\n *,\n add_leading_dim: bool = False,\n override_obs: bool = True,\n added_obs_prefix: str = 'stacked_',\n validation_frequency: tsp.ValidationFrequency = (\n tsp.ValidationFrequency.ONCE_PER_EPISODE),\n ):\n \"\"\"StackObservations preprocessor constructor.\n\n Args:\n obs_to_stack: A list of observation to stack.\n stack_depth: How deep to stack them. The stacked observations will be\n concatenated and replace the original observation if `override_obs` is\n set to True. Otherwise, extra observations with prefix\n `added_obs_prefix` will be added.\n add_leading_dim: If False, stacks the observations along the first\n dimension. If True, stacks the observations along an extra leading\n dimension. E.g.: (7,) stacked 3 times becomes: - (21,) if\n add_leading_dim=True - (3,7) if add_leading_dim=True (4,5) stacked 3\n times becomes: - (12, 5) if add_leading_dim=False - (3, 4, 5) if\n add_leading_dim=True\n override_obs: If True, add the stacked observations and replace the\n existing ones. Otherwise, the stacked observations will be added to the\n existing ones. The name of the stacked observation is given by\n `added_obs_prefix` added to their original name.\n added_obs_prefix: The prefix to be added to the original observation name.\n validation_frequency: How often should we validate the obs specs.\n \"\"\"\n super().__init__(validation_frequency)\n self._obs_to_stack: FrozenSet[str] = frozenset(obs_to_stack)\n self._stack_depth = stack_depth\n self._add_leading_dim = add_leading_dim\n self._stacks = {\n name: collections.deque(maxlen=self._stack_depth) # pytype: disable=wrong-arg-types # numpy-scalars\n for name in self._obs_to_stack\n }\n self._override_obs = override_obs\n self._added_obs_prefix = added_obs_prefix\n\n @overrides(tsp.TimestepPreprocessor)\n # Profiling for .wrap('StackObservations._process_impl')\n def _process_impl(\n self, timestep: tsp.PreprocessorTimestep) -> tsp.PreprocessorTimestep:\n if self._override_obs:\n processed_obs = {\n k: self._maybe_process(timestep, k, v)\n for k, v in timestep.observation.items()\n }\n else:\n stacked_obs = {\n self._added_obs_prefix + str(k):\n self._maybe_process(timestep, k, timestep.observation[k])\n for k in self._obs_to_stack\n }\n processed_obs = {**timestep.observation, **stacked_obs}\n\n return timestep._replace(observation=processed_obs)\n\n def _maybe_process(self, timestep, key, val):\n if key not in self._obs_to_stack:\n return val\n\n stack = self._stacks[key]\n if timestep.first():\n stack.clear()\n stack.extend([val] * (self._stack_depth - 1))\n stack.appendleft(val)\n if self._add_leading_dim:\n return np.array(stack)\n else:\n return np.concatenate(stack)\n\n def _maybe_process_spec(self, key, spec):\n if key not in self._obs_to_stack:\n return spec\n if self._add_leading_dim:\n model_array = np.array([spec.generate_value()] * self._stack_depth)\n else:\n model_array = np.concatenate([spec.generate_value()] * self._stack_depth)\n return specs.Array(\n shape=model_array.shape, dtype=model_array.dtype, name=spec.name)\n\n @overrides(tsp.TimestepPreprocessor)\n def _output_spec(\n self, input_spec: spec_utils.TimeStepSpec) -> spec_utils.TimeStepSpec:\n if self._override_obs:\n processed_obs_spec = {\n k: self._maybe_process_spec(k, v)\n for k, v in input_spec.observation_spec.items()\n }\n else:\n stacked_obs_spec = {\n self._added_obs_prefix + str(k):\n self._maybe_process_spec(k, input_spec.observation_spec[k])\n for k in self._obs_to_stack\n }\n processed_obs_spec = {**input_spec.observation_spec, **stacked_obs_spec}\n\n return input_spec.replace(processed_obs_spec)\n\n\nclass UnstackObservations(tsp.TimestepPreprocessor):\n \"\"\"A timestep preprocessor that unstacks observations.\"\"\"\n\n def __init__(\n self,\n obs_to_unstack: Sequence[str],\n override_obs: bool = False,\n added_obs_prefix: str = 'unstacked_',\n validation_frequency: tsp.ValidationFrequency = (\n tsp.ValidationFrequency.ONCE_PER_EPISODE),\n ):\n \"\"\"UnstackObservations preprocessor constructor.\n\n Args:\n obs_to_unstack: A list of observation to unstack.\n override_obs: If True, add the unstacked observations and replace the\n existing ones. Otherwise, the unstacked observations will be added to\n the existing ones. The name of the ustacked observation is given by\n `added_obs_prefix` added to their original name.\n added_obs_prefix: The prefix to be added to the original observation name.\n validation_frequency: How often should we validate the obs specs.\n \"\"\"\n super().__init__(validation_frequency)\n self._obs_to_unstack: FrozenSet[str] = frozenset(obs_to_unstack)\n self._override_obs = override_obs\n self._added_obs_prefix = added_obs_prefix\n\n @overrides(tsp.TimestepPreprocessor)\n # Profiling for .wrap('UnstackObservations._process_impl')\n def _process_impl(\n self, timestep: tsp.PreprocessorTimestep) -> tsp.PreprocessorTimestep:\n if self._override_obs:\n processed_obs = {\n k: self._maybe_process(timestep, k, v)\n for k, v in timestep.observation.items()\n }\n else:\n unstacked_obs = {\n self._added_obs_prefix + str(k):\n self._maybe_process(timestep, k, timestep.observation[k])\n for k in self._obs_to_unstack\n }\n processed_obs = {**timestep.observation, **unstacked_obs}\n\n return timestep._replace(observation=processed_obs)\n\n def _maybe_process(self, timestep, key, val):\n if key not in self._obs_to_unstack:\n return val\n unstack = timestep.observation[key][0]\n if not unstack.shape:\n unstack = np.asarray([unstack])\n return unstack\n\n def _maybe_process_spec(self, key, spec):\n if key not in self._obs_to_unstack:\n return spec\n model_array = spec.generate_value()[0]\n if not model_array.shape:\n model_array = np.asarray([model_array])\n return specs.Array(\n shape=model_array.shape, dtype=model_array.dtype, name=spec.name)\n\n @overrides(tsp.TimestepPreprocessor)\n def _output_spec(\n self, input_spec: spec_utils.TimeStepSpec) -> spec_utils.TimeStepSpec:\n if self._override_obs:\n processed_obs_spec = {\n k: self._maybe_process_spec(k, v)\n for k, v in input_spec.observation_spec.items()\n }\n else:\n unstacked_obs_spec = {\n self._added_obs_prefix + str(k): self._maybe_process_spec(k, v)\n for k, v in input_spec.observation_spec.items()\n }\n processed_obs_spec = {**input_spec.observation_spec, **unstacked_obs_spec}\n\n return input_spec.replace(processed_obs_spec)\n\n\nclass FoldObservations(tsp.TimestepPreprocessor):\n \"\"\"Performs a fold operation and transormation some observation.\"\"\"\n\n def __init__(\n self,\n output_obs_name: str,\n obs_to_fold: str,\n fold_fn: Callable[[np.ndarray, np.ndarray], np.ndarray],\n output_fn: Callable[[np.ndarray], np.ndarray],\n init_val: np.ndarray,\n validation_frequency: tsp.ValidationFrequency = (\n tsp.ValidationFrequency.ONCE_PER_EPISODE),\n ):\n super().__init__(validation_frequency)\n\n self._output_obs_name = output_obs_name\n self._obs_to_fold = obs_to_fold\n self._fold_fn = fold_fn\n self._output_fn = output_fn\n self._init_val = init_val\n\n self._cur_val = init_val\n\n @overrides(tsp.TimestepPreprocessor)\n def _process_impl(\n self, timestep: tsp.PreprocessorTimestep) -> tsp.PreprocessorTimestep:\n\n if timestep.step_type.first():\n self._cur_val = self._init_val\n\n step_val = timestep.observation[self._obs_to_fold]\n self._cur_val = self._fold_fn(self._cur_val, step_val)\n\n processed_obs = {k: v for k, v in timestep.observation.items()}\n\n output_val = self._output_fn(self._cur_val).astype(self._init_val.dtype)\n processed_obs[self._output_obs_name] = output_val\n\n return timestep._replace(observation=processed_obs)\n\n @overrides(tsp.TimestepPreprocessor)\n def _output_spec(\n self, input_spec: spec_utils.TimeStepSpec) -> spec_utils.TimeStepSpec:\n observation_spec = {k: v for k, v in input_spec.observation_spec.items()}\n observation_spec[self._output_obs_name] = specs.Array(\n shape=self._init_val.shape,\n dtype=self._init_val.dtype,\n name=self._output_obs_name)\n\n return input_spec.replace(observation_spec=observation_spec)\n\n\nclass ImageCropper(object):\n \"\"\"Helper class that crops an image.\"\"\"\n\n def __init__(\n self,\n crop_width_relative: float,\n crop_height_relative: Optional[float] = None,\n x_offset_relative: float = 0.0,\n y_offset_relative: float = 0.0,\n ):\n \"\"\"This initializes internal variables that are reused for every crop operation.\n\n Args:\n crop_width_relative: What fraction of the original width to crop to. For\n example, for an image that is 100px wide, a value of 0.65 would crop a\n region that is 65px wide. Cannot be zero.\n crop_height_relative: Optional fraction of the original height to crop to.\n Cannot be zero. If omitted, default to a square with the side length\n implied by crop_width_relative.\n x_offset_relative: X offset for the crop. 0 means the left edge of the\n crop is aligned with the left edge of the source. 0.5 means the *center*\n of the crop is aligned with the center of the source. 1.0 means the\n *right* edge of the crop is aligned with the right edge of the source.\n y_offset_relative: Behaves like x_offset_relative, but for the y axis.\n \"\"\"\n\n # Check parameters for limit violations (all the limits are [0,1])\n def check_limit(value: float, name: str):\n if value < 0.0 or value > 1.0:\n raise ValueError('{} must be between 0 and 1, is {}'.format(\n name, value))\n\n check_limit(crop_width_relative, 'Crop width')\n if crop_width_relative == 0.0:\n raise ValueError('Crop width cannot be zero!')\n if crop_height_relative is not None:\n check_limit(crop_height_relative, 'Crop height')\n if crop_height_relative == 0.0:\n raise ValueError('Crop height cannot be zero!')\n check_limit(x_offset_relative, 'X offset')\n check_limit(y_offset_relative, 'Y offset')\n\n self._x_offset_relative = x_offset_relative\n self._y_offset_relative = y_offset_relative\n self._crop_width_relative = crop_width_relative\n self._crop_height_relative = crop_height_relative\n\n self._cropped_width = None # type: Optional[int]\n self._cropped_height = None # type: Optional[int]\n self._x_offset = None # type: Optional[int]\n self._y_offset = None # type: Optional[int]\n\n self._last_input_width = None # type: Optional[int]\n self._last_input_height = None # type: Optional[int]\n\n def calculate_crop_params(self, input_width: int,\n input_height: int) -> Tuple[int, int]:\n \"\"\"Calculate the actual size of the crop in pixels.\n\n Saves the width and height used to avoid unnecessary calculations.\n\n Args:\n input_width: Width of the image to be cropped, in pixels.\n input_height: Height of the image to be cropped, in pixels.\n\n Returns:\n A tuple (output_width, output_height).\n\n Raises:\n ValueError if only crop width was set (in this case, crop height\n defaults to be equal to the width), and the resulting square is larger\n than the image.\n \"\"\"\n # Only do the math if input_width or input_height changed from the last time\n # we were called.\n if (input_width != self._last_input_width or\n input_height != self._last_input_height):\n self._cropped_width = max(\n 1, self._fraction_of_pixels(self._crop_width_relative, input_width))\n self._cropped_height = (\n self._cropped_width if self._crop_height_relative is None else max(\n 1, self._fraction_of_pixels(self._crop_height_relative,\n input_height)))\n if self._cropped_height > input_height:\n raise ValueError(\n 'Crop height is {}, but input is only {} pixels high!'.format(\n self._cropped_height, input_height))\n self._x_offset = self._fraction_of_pixels(\n self._x_offset_relative, input_width - self._cropped_width)\n self._y_offset = self._fraction_of_pixels(\n self._y_offset_relative, input_height - self._cropped_height)\n\n # Return the results to use outside this class.\n return (self._cropped_width, self._cropped_height)\n\n def _fraction_of_pixels(self, fraction: float, total_pixels: int) -> int:\n \"\"\"Calculate a number of pixels based on ratio and total_pixels.\n\n This function exists to ensure that all conversions from relative sizes to\n pixels use the same logic.\n\n Args:\n fraction: ]0.0,1.0], fraction of total_pixels to calculate.\n total_pixels: Total number of pixels in the relevant dimensions.\n\n Returns:\n The requested fraction of the given pixel size, rounded to the next\n integer. I.e. running this with ratio=1 will always return total_pixels,\n running with ratio=0 will always return 0.\n\n Raises:\n ValueError if ratio is not in [0,1]\n ValueError if total_pixels is < 0\n \"\"\"\n if fraction < 0.0 or fraction > 1.0:\n raise ValueError(\n 'Fraction must be between 0 and 1, is {}'.format(fraction))\n if total_pixels < 0:\n raise ValueError('Total number of pixels must be positive, got {}'.format(\n total_pixels))\n return int(round(float(total_pixels) * fraction))\n\n def crop(self, image: np.ndarray) -> np.ndarray:\n \"\"\"Crop the given image.\"\"\"\n if len(image.shape) < 2:\n raise ValueError('Cropper requires at least 2 dimensions, got '\n 'shape {}'.format(image.shape))\n width = image.shape[1]\n height = image.shape[0]\n # This bails out early if we already know the parameters for this width and\n # height.\n self.calculate_crop_params(input_width=width, input_height=height)\n return image[self._y_offset:self._y_offset + self._cropped_height,\n self._x_offset:self._x_offset + self._cropped_width]\n\n\nclass CropImageObservation(tsp.TimestepPreprocessor):\n \"\"\"Crops an image observation to the desired shape.\"\"\"\n\n def __init__(\n self,\n input_obs_name: str,\n output_obs_name: str,\n crop_width_relative: float,\n crop_height_relative: Optional[float] = None,\n x_offset_relative: float = 0.0,\n y_offset_relative: float = 0.0,\n validation_frequency: tsp.ValidationFrequency = (\n tsp.ValidationFrequency.ONCE_PER_EPISODE),\n ):\n \"\"\"Build a CropImageObservation preprocessor.\n\n Args:\n input_obs_name: Name of the input observation. This must be a 2D array.\n output_obs_name: Name of the output observation.\n crop_width_relative: What fraction of the original width to crop to. For\n example, for an image that is 100px wide, a value of 0.65 would crop a\n region that is 65px wide. Cannot be zero.\n crop_height_relative: Optional fraction of the original height to crop to.\n Cannot be zero. If omitted, default to a square with the side length\n implied by crop_width_relative.\n x_offset_relative: X offset for the crop. 0 means the left edge of the\n crop is aligned with the left edge of the source. 0.5 means the *center*\n of the crop is aligned with the center of the source. 1.0 means the\n *right* edge of the crop is aligned with the right edge of the source.\n y_offset_relative: Behaves like x_offset_relative, but for the y axis.\n validation_frequency: How often should we validate the obs specs.\n \"\"\"\n super().__init__(validation_frequency)\n\n # Will raise a ValueError if any of the parameters are not OK.\n self._cropper = ImageCropper(\n crop_width_relative=crop_width_relative,\n crop_height_relative=crop_height_relative,\n x_offset_relative=x_offset_relative,\n y_offset_relative=y_offset_relative)\n\n self._input_obs_name = input_obs_name\n self._output_obs_name = output_obs_name\n\n def _process_image(self, image: np.ndarray):\n return self._cropper.crop(image)\n\n @overrides(tsp.TimestepPreprocessor)\n def _process_impl(\n self, timestep: tsp.PreprocessorTimestep) -> tsp.PreprocessorTimestep:\n\n processed_obs = dict(timestep.observation)\n processed_obs[self._output_obs_name] = self._process_image(\n timestep.observation[self._input_obs_name])\n\n return timestep._replace(observation=processed_obs)\n\n @overrides(tsp.TimestepPreprocessor)\n def _output_spec(\n self, input_spec: spec_utils.TimeStepSpec) -> spec_utils.TimeStepSpec:\n\n input_observation_spec = input_spec.observation_spec[self._input_obs_name]\n\n shape = input_observation_spec.shape\n if len(shape) < 2:\n raise ValueError(\n 'CropImageObservation preprocessor expects 2D image observation, got '\n 'shape {}'.format(shape))\n width = shape[1]\n height = shape[0]\n cropped_width, cropped_height = self._cropper.calculate_crop_params(\n input_width=width, input_height=height)\n\n observation_spec = dict(input_spec.observation_spec)\n\n observation_spec[self._output_obs_name] = specs.Array(\n shape=(cropped_height, cropped_width) + shape[2:],\n dtype=input_observation_spec.dtype,\n name=self._output_obs_name)\n\n return input_spec.replace(observation_spec=observation_spec)\n\n\nclass CropSquareAndResize(CropImageObservation):\n \"\"\"Crop a square from an image observation and resample it to the desired size in pixels.\"\"\"\n\n def __init__(\n self,\n input_obs_name: str,\n output_obs_name: str,\n crop_width_relative: float,\n side_length_pixels: int,\n x_offset_relative: float = 0.0,\n y_offset_relative: float = 0.0,\n interpolation=cv2.INTER_LINEAR,\n validation_frequency: tsp.ValidationFrequency = (\n tsp.ValidationFrequency.ONCE_PER_EPISODE),\n ):\n \"\"\"Build a CropImageObservation preprocessor.\n\n Args:\n input_obs_name: Name of the input observation. This must be a 2D array.\n output_obs_name: Name of the output observation.\n crop_width_relative: What fraction of the original width to crop to. For\n example, for an image that is 100px wide, a value of 0.65 would crop a\n region that is 65px wide. This defines both the width and height of the\n crop, so if the image is wider than it is tall, there exist values that\n can lead to invalid crops at runtime! Cannot be zero.\n side_length_pixels: The crop will be resampled so that its side length\n matches this.\n x_offset_relative: What fraction of the original width to offset the crop\n by. Defaults to 0.0.\n y_offset_relative: What fraction of the original height to offset the crop\n by. Defaults to 0.0.\n interpolation: The interpolation method to use. Supported values are\n cv2.INTER_LINEAR, cv2.INTER_NEAREST, cv2.INTER_AREA, cv2.INTER_CUBIC,\n cv2.INTER_LANCZOS4\n validation_frequency: How often should we validate the obs specs.\n \"\"\"\n super().__init__(\n input_obs_name=input_obs_name,\n output_obs_name=output_obs_name,\n crop_width_relative=crop_width_relative,\n crop_height_relative=None,\n x_offset_relative=x_offset_relative,\n y_offset_relative=y_offset_relative,\n validation_frequency=validation_frequency,\n )\n\n if side_length_pixels <= 0:\n raise ValueError(\n 'Side length must be > 0, got {}'.format(side_length_pixels))\n self._side_length_pixels = side_length_pixels\n self._interpolation = interpolation\n\n def _process_image(self, image: np.ndarray):\n crop = super()._process_image(image)\n\n return cv2.resize(\n crop, (self._side_length_pixels, self._side_length_pixels),\n interpolation=self._interpolation)\n\n @overrides(tsp.TimestepPreprocessor)\n def _output_spec(\n self, input_spec: spec_utils.TimeStepSpec) -> spec_utils.TimeStepSpec:\n cropped_input_spec = super()._output_spec(input_spec)\n input_observation_spec = cropped_input_spec.observation_spec[\n self._input_obs_name]\n shape = input_observation_spec.shape\n observation_spec = dict(input_spec.observation_spec)\n observation_spec[self._output_obs_name] = specs.Array(\n shape=(self._side_length_pixels, self._side_length_pixels) + shape[2:],\n dtype=input_observation_spec.dtype,\n name=self._output_obs_name)\n\n return input_spec.replace(observation_spec=observation_spec)\n\n\nclass ResizeImage(tsp.TimestepPreprocessor):\n \"\"\"Resample an image observation to the desired size in pixels.\n\n Resulting image is reshaped into a square if it is not already.\n \"\"\"\n\n def __init__(\n self,\n input_obs_name: str,\n output_obs_name: str,\n side_length_pixels: int,\n interpolation=cv2.INTER_LINEAR,\n validation_frequency: tsp.ValidationFrequency = (\n tsp.ValidationFrequency.ONCE_PER_EPISODE),\n ):\n \"\"\"Build a ResizeImage preprocessor.\n\n Args:\n input_obs_name: Name of the input observation. The observation must be a\n 2D array.\n output_obs_name: Name of the output observation.\n side_length_pixels: The image will be resampled so that its side length\n matches this.\n interpolation: The interpolation method to use. Supported values are\n cv2.INTER_LINEAR, cv2.INTER_NEAREST, cv2.INTER_AREA, cv2.INTER_CUBIC,\n cv2.INTER_LANCZOS4\n validation_frequency: How often should we validate the obs specs.\n \"\"\"\n super().__init__(validation_frequency)\n\n if side_length_pixels <= 0:\n raise ValueError(\n 'Side length must be > 0, got {}'.format(side_length_pixels))\n\n self._input_obs_name = input_obs_name\n self._output_obs_name = output_obs_name\n self._side_length_pixels = side_length_pixels\n self._interpolation = interpolation\n\n def _process_image(self, image: np.ndarray):\n return cv2.resize(\n image, (self._side_length_pixels, self._side_length_pixels),\n interpolation=self._interpolation)\n\n @overrides(tsp.TimestepPreprocessor)\n def _process_impl(\n self, timestep: tsp.PreprocessorTimestep) -> tsp.PreprocessorTimestep:\n\n processed_obs = dict(timestep.observation)\n processed_obs[self._output_obs_name] = self._process_image(\n timestep.observation[self._input_obs_name])\n\n return timestep._replace(observation=processed_obs)\n\n @overrides(tsp.TimestepPreprocessor)\n def _output_spec(\n self, input_spec: spec_utils.TimeStepSpec) -> spec_utils.TimeStepSpec:\n input_observation_spec = input_spec.observation_spec[self._input_obs_name]\n shape = input_observation_spec.shape\n observation_spec = dict(input_spec.observation_spec)\n observation_spec[self._output_obs_name] = specs.Array(\n shape=(self._side_length_pixels, self._side_length_pixels) + shape[2:],\n dtype=input_observation_spec.dtype,\n name=self._output_obs_name)\n\n return input_spec.replace(observation_spec=observation_spec)\n\n\nclass AddObservation(tsp.TimestepPreprocessor):\n \"\"\"Preprocessor that adds an observation.\"\"\"\n\n def __init__(\n self,\n obs_name: str,\n obs_callable: Callable[[tsp.PreprocessorTimestep], np.ndarray],\n obs_spec: Optional[specs.Array] = None,\n validation_frequency: tsp.ValidationFrequency = (\n tsp.ValidationFrequency.ONCE_PER_EPISODE),\n ):\n \"\"\"AddObservation constructor.\n\n Args:\n obs_name: Name of the observation to add.\n obs_callable: Callable generating the observation to be added value given\n a timestep.\n obs_spec: Specs for the output of `obs_callable`. If `None` is provided\n the specs are inferred as a `dm_env.specs.Array` with shape and dtype\n matching the output of `obs_callable` and name set to `obs_name`.\n validation_frequency: How often should we validate the obs specs.\n \"\"\"\n super().__init__(validation_frequency)\n\n self._obs_name = obs_name\n self._obs_callable = obs_callable\n self._obs_spec = obs_spec\n\n @overrides(tsp.TimestepPreprocessor)\n # Profiling for .wrap_scope('AddObservation._process_impl')\n def _process_impl(\n self, timestep: tsp.PreprocessorTimestep) -> tsp.PreprocessorTimestep:\n\n processed_obs = dict(timestep.observation)\n processed_obs[self._obs_name] = np.asarray(self._obs_callable(timestep))\n\n return timestep._replace(observation=processed_obs)\n\n @overrides(tsp.TimestepPreprocessor)\n def _output_spec(\n self, input_spec: spec_utils.TimeStepSpec) -> spec_utils.TimeStepSpec:\n\n observation_spec = dict(input_spec.observation_spec)\n if self._obs_name in observation_spec.keys():\n raise ValueError(f'Observation {self._obs_name} already exists.')\n\n dummy_input = tsp.PreprocessorTimestep.from_environment_timestep(\n input_spec.minimum(), pterm=0.0)\n try:\n dummy_obs = np.asarray(self._obs_callable(dummy_input))\n except Exception:\n logging.exception('Failed to run the obs_callable to add observation %s.',\n self._obs_name)\n raise\n\n if self._obs_spec is None:\n self._obs_spec = specs.Array(\n shape=dummy_obs.shape, dtype=dummy_obs.dtype, name=self._obs_name)\n\n observation_spec[self._obs_name] = self._obs_spec\n\n return input_spec.replace(observation_spec=observation_spec)\n","repo_name":"deepmind/dm_robotics","sub_path":"py/agentflow/preprocessors/observation_transforms.py","file_name":"observation_transforms.py","file_ext":"py","file_size_in_byte":46087,"program_lang":"python","lang":"en","doc_type":"code","stars":286,"dataset":"github-code","pt":"43"} +{"seq_id":"71602645891","text":"from django.shortcuts import render,redirect\nfrom django.contrib.auth.models import User\nfrom .forms import UserRegisterForm\nfrom .models import Candidate\nfrom django.contrib import messages\n# Create your views here.\ndef challenge_register(request):\n if request.method == \"POST\":\n form = UserRegisterForm(request.POST)\n if form.is_valid():\n form.save()\n rollnumber = form.cleaned_data.get('username')\n college = form.cleaned_data.get('college')\n pwd = form.cleaned_data.get('password1')\n fullname = form.cleaned_data.get('firstname')+\" \"+form.cleaned_data.get('lastname')\n user = User.objects.all().filter(username=rollnumber).first()\n candidate = Candidate(user=user,rollnumber=rollnumber,college=college,fullname=fullname)\n candidate.save() \n messages.success(request, f'Congrats account for {rollnumber} is created! \\n Now try to login')\n return redirect('login')\n else:\n form = UserRegisterForm()\n return render(request,'challenge/register.html',{'form':form})","repo_name":"yogendramaarisetty/Tech-hire","sub_path":"challenge/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"19272376908","text":"import os\nimport sys\n\nroot_dir = sys.argv[1]\ntarget_dir = sys.argv[2]\n\nfor class_name in os.listdir(root_dir):\n root_class_path = os.path.join(root_dir, class_name)\n target_class_path = os.path.join(target_dir, class_name)\n if not os.path.exists(target_class_path):\n os.makedirs(target_class_path)\n for video_name in os.listdir(root_class_path):\n video_path = os.path.join(root_class_path, video_name)\n target_video_path = os.path.join(target_class_path, video_name)\n target_rgb_path = os.path.join(target_video_path, \"rgb\")\n target_u_path = os.path.join(target_video_path, \"u\")\n target_v_path = os.path.join(target_video_path, \"v\")\n\n if not os.path.exists(target_rgb_path):\n os.makedirs(target_rgb_path)\n if not os.path.exists(target_u_path):\n os.makedirs(target_u_path)\n if not os.path.exists(target_v_path):\n os.makedirs(target_v_path)\n\n img_idx = 0\n for video_clip_name in sorted(os.listdir(video_path)):\n video_clip_path = os.path.join(video_path, video_clip_name)\n rgb_path = os.path.join(video_clip_path, \"rgb\")\n u_path = os.path.join(video_clip_path, \"u\")\n v_path = os.path.join(video_clip_path, \"v\")\n\n assert len(os.listdir(u_path)) == \\\n len(os.listdir(v_path)), \"video clip mismatch. {}\".format(video_clip_path)\n\n for file_name in sorted(os.listdir(rgb_path)):\n ext = file_name.split(\".\")[-1]\n rgb_file = os.path.join(rgb_path, file_name)\n u_file = os.path.join(u_path, file_name)\n v_file = os.path.join(v_path, file_name)\n\n target_file_name = str(img_idx).zfill(6) + \".\" + ext\n img_idx += 1\n target_rgb_file = os.path.join(target_rgb_path, target_file_name)\n target_u_file = os.path.join(target_u_path, target_file_name)\n target_v_file = os.path.join(target_v_path, target_file_name)\n\n os.rename(rgb_file, target_rgb_file)\n if os.path.exists(u_file):\n os.rename(u_file, target_u_file)\n if os.path.exists(v_file):\n os.rename(v_file, target_v_file)\n\n","repo_name":"NVIDIA-AI-IOT/tao_toolkit_recipes","sub_path":"tao_action_recognition/data_generation/generate_new_dataset_format.py","file_name":"generate_new_dataset_format.py","file_ext":"py","file_size_in_byte":2281,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"43"} +{"seq_id":"26879263816","text":"#!/usr/local/bin/python\n# -*- coding: utf-8 -*-\n\nimport random\nfrom enum import Enum\nfrom cell import Cell\n\nclass GameState(Enum):\n win = 1\n los = 2\n unf = 3\n\ndef make_grid(width, height, nbombs):\n assert 0 < width, 'width must be a positive integer'\n assert 0 < height, 'height must be a positive integer'\n assert 0 <= nbombs <= width * height, \"nbombs must don't exceed width*height\"\n coords = [(x, y) for y in range(height) for x in range(width)]\n random.shuffle(coords)\n grid = [[Cell() for y in range(height)] for x in range(width)]\n for i in range(nbombs):\n x,y=coords[i]\n grid[x][y].set_bomb()\n for neighbor in neighborhood(x, y, width, height):\n x1, y1 = neighbor\n grid[x1][y1].incr_number_of_bombs_in_neighborhood()\n return grid\n\nclass Minesweeper():\n\n def __init__(self, width=30, height=20, nbombs=99):\n self.w = width\n self.h = height\n self.nb = nbombs\n self.grid = make_grid(width, height, nbombs)\n\n def reveal_all_cells_from(self, x, y):\n width = self.w\n height = self.h\n cel = self.get_cell(x,y)\n if cel.number_of_bombs_in_neighborhood() != 0:\n cel.reveal()\n elif cel.is_bomb():\n cel.reveal()\n else:\n listeVoisins = neighborhood(x, y, width, height)\n for i in range(0,len(listeVoisins)) :\n cel2=self.get_cell(listeVoisins[i][0],listeVoisins[i][1])\n if cel2.is_revealed()==False:\n cel2.reveal()\n self.reveal_all_cells_from(listeVoisins[i][0], listeVoisins[i][1])\n def get_height(self):\n return self.h\n\n def get_width(self):\n return self.w\n\n def get_nbombs(self):\n return self.nb\n\n\n def get_cell(self, x, y):\n return self.grid[x][y]\n\n def get_state(self):\n n = 0\n state = 0\n width = self.w\n height = self.h\n nb_cases = width*height\n\n for i in range(0,width) :\n for j in range(0,height) :\n cel = self.get_cell(i,j)\n if cel.is_bomb() and cel.is_revealed():\n state = 2\n break\n elif (cel.is_revealed() and not cel.is_bomb()) or (not cel.is_revealed() and cel.is_bomb()):\n n = n+1\n if state == 2:\n break\n\n if n == nb_cases:\n return GameState.win\n elif state == 2:\n return GameState.los\n else:\n return GameState.unf\n\ndef neighborhood(x, y, width, height):\n neighbors = []\n for i in range(x-1, x+2) :\n for j in range(y-1, y+2) :\n if 0<=i<width and 0<=j<height and not (i,j)==(x,y):\n neighbors = neighbors + [ (i,j) ]\n return neighbors\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS, verbose=True) \n","repo_name":"ryuichi1208/minesweeper","sub_path":"minesweeper.py","file_name":"minesweeper.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"1133373349","text":"import urllib\nimport json\nimport re\n\nTAG_URL = 'https://api.github.com/repos/hupili/snsapi/tags'\nVERSION_PATTERN = re.compile('^v\\d+\\.\\d+(\\.\\d+)?$')\nFN_TPL = 'index.md.tpl'\nFN_MD = 'index.md'\n\ndef is_version_tag(name):\n return True if VERSION_PATTERN.search(name) else False\n\ndef render_version(t):\n space = ' ' * 4\n fmt = ' * **{0}**: %s [[zip]]({1}) %s [[tar.gz]]({2})' % (space, space)\n return fmt.format(t['name'], t['zipball_url'], t['tarball_url'])\n\nif __name__ == '__main__':\n r = urllib.urlopen(TAG_URL)\n tags = json.loads(r.read())\n #print tags\n lst = []\n for t in sorted(tags, key=lambda t: t['name'], reverse=True):\n if is_version_tag(t['name']):\n #print t['name']\n #print render_version(t)\n lst.append(render_version(t))\n tpl = open(FN_TPL).read()\n html = tpl.replace('{{TAG_LIST}}', '\\n'.join(lst))\n open(FN_MD, 'w').write(html)\n","repo_name":"hupili/snsapi-website","sub_path":"down/gettags.py","file_name":"gettags.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"43"} +{"seq_id":"73247977410","text":"from __future__ import unicode_literals\nimport frappe\nfrom frappe import _\nclass MemberasOutCell():\n\n\tdef run(self):\n\t\treturn self.get_columns(), self.get_data()\n\n\tdef get_columns(self):\n\t\tcolumns = [_(\"Cell ID\")+ \":Link/Cells:180\"]\n\n\t\tcolumns += [\n\t\t\t_(\"Cell Name\") + \":Data:90\",\n\t\t\t_(\"Member ID\") + \":Link/Member:90\",\t\t\t\n\t\t\t_(\"Member Name\") + \":Data:100\",\n\t\t\t_(\"Distance From Cell\") + \":Data:135\",\n\t\t\t_(\"Exceeded Distance \") + \":Data:125\",\n\t\t\t_(\"Cell Address \") + \":Data:220\",\n\t\t\t_(\"Member Address \") + \":Data:220\"]\n\n\t\treturn columns\n\n\tdef get_data(self):\n\t\tdata = []\n\t\tres=frappe.db.sql(\"select name,lat,lon,cell_name,address from tabCells where lat is not null and lon is not null\")\n\t\t#frappe.errprint(res)\n\t\tallowed_distance= frappe.db.get_value(\"Notification Settings\", \"Notification Settings\",\"maximum_allowed_distance_of_member_from_cell\")\n\t\tfor name in res:\n\t\t\tqry=\"SELECT cell,'%(cell_name)s',name,member_name, TRUNCATE(( 6371 * acos ( cos ( radians(%(lat)s) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians(%(lon)s) ) + sin ( radians(%(lat)s) ) * sin( radians( lat ) ) ) ) ,3) AS distance ,TRUNCATE(( 6371 * acos ( cos ( radians(%(lat)s) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians(%(lon)s) ) + sin ( radians(%(lat)s) ) * sin( radians( lat ) ) ) ) - %(max_dist)s ,3)as more_distance,'%(address)s',address FROM tabMember HAVING distance > %(max_dist)s and cell= '%(cell)s' ORDER BY distance \"%({\"lat\":name[1],\"lon\":name[2],\"max_dist\":allowed_distance,\"cell\":name[0],\"address\":name[4],\"cell_name\":name[3]})\n\t\t\t#frappe.errprint(qry)\n\t\t\tdt_rows=frappe.db.sql(qry,as_list=1)\n\t\t\tfor rows in dt_rows:\n\t\t\t\tdata.append(rows)\n\t\t\t\t#frappe.errprint(rows)\n\n\t\t#frappe.errprint(data)\n\t\treturn data\n\n\n\tdef make_data_dict(self, cols, data):\n\t\tdata_dict = []\n\t\tfor d in data:\n\t\t\tdata_dict.append(frappe._dict(zip(cols, d)))\n\n\t\treturn data_dict\n\ndef execute(filters=None):\n\n\treturn MemberasOutCell().run()\n","repo_name":"indictranstech/church_ministry","sub_path":"church_ministry/church_ministry/report/members_out_of_defined_cell_circle/members_out_of_defined_cell_circle.py","file_name":"members_out_of_defined_cell_circle.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"25670353521","text":"import curses\nfrom colors import Colors\nfrom renderer import Renderer\nfrom tables import DASHBOARD\nimport os\n\nclass BoardItem:\n\n def __init__(self, character):\n self.character = character\n self.init_character = None\n self.config = BoardItemConfig()\n\nclass BoardItemConfig:\n\n def __init__(self):\n self.foreground_color = None\n self.background_color = None\n self.bold = False\n\n def clear(self):\n self.foreground_color = None\n self.background_color = None\n self.bold = False\n\nclass Dashboard:\n\n HORIZONTAL_RATIO = 0.5\n VERTICAL_RATIO = 0.333\n\n BG_COLOR = Colors.BLACK\n FG_COLOR = Colors.WHITE\n\n def __init__(self, data):\n self.data = data\n self.board = self._parse_board()\n self._save_board()\n\n def set_window(self, window):\n self.window = window\n self.window.bkgd(' ', curses.color_pair(Colors.get_color_pair_id(Dashboard.FG_COLOR.FG, Dashboard.BG_COLOR.BG)))\n\n def get_number_of_lines(self):\n return len(self.board)\n\n def _parse_board(self):\n parts = DASHBOARD.split('\\n')\n board = []\n\n for part in parts:\n row = []\n for char in part:\n row.append(BoardItem(char))\n board.append(row)\n\n return board\n\n def _save_board(self):\n for r in range(len(self.board)):\n for c in range(len(self.board[r])):\n self.board[r][c].init_character = self.board[r][c].character\n\n def _reset_board(self):\n for r in range(len(self.board)):\n for c in range(len(self.board[r])):\n self.board[r][c].character = self.board[r][c].init_character\n self.board[r][c].config.clear()\n\n def _set_background(self):\n for r in range(len(self.board)):\n for c in range(len(self.board[r])):\n self.board[r][c].config.background_color = self.BG_COLOR.BG\n self.board[r][c].config.foreground_color = self.FG_COLOR.FG\n\n def _get_full_screen_board(self):\n full_rows, full_columns = self.window.getmaxyx()\n full_columns = full_columns - 1\n\n full_board = []\n\n for r in range(full_rows):\n row = []\n for c in range(full_columns):\n item = BoardItem(' ')\n item.config.background_color = self.BG_COLOR.BG\n item.config.foreground_color = self.FG_COLOR.FG\n row.append(item)\n full_board.append(row)\n\n rows_to_draw = min(full_rows, len(self.board))\n columns_to_draw = min(full_columns, len(self.board[0]))\n\n for r in range(rows_to_draw):\n for c in range(columns_to_draw):\n c_offset = 0\n if full_columns > len(self.board[r]):\n c_offset = int((full_columns - len(self.board[r])) * self.HORIZONTAL_RATIO)\n\n r_offset = 0\n if full_rows > len(self.board):\n r_offset = int((full_rows - len(self.board)) * self.VERTICAL_RATIO)\n\n full_board[r_offset + r][c_offset + c] = self.board[r][c]\n\n return full_board\n\n def _draw(self):\n full_board = self._get_full_screen_board()\n Renderer.generate_standard(full_board, self.window)\n\n def render(self, render_config):\n self._reset_board()\n self._set_background()\n # TODO: Update board\n self._draw()","repo_name":"spirometaxas/periodic-table-cli-py","sub_path":"periodic_table_cli/dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":3445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"19249969243","text":"#!/bin/python3\nimport sys\n\n# ------------------------------------------------------------------------------\n# hackerrank.com/challenges/print-the-elements-of-a-linked-list/problem\n\"\"\"\n Print elements of a linked list on console\n head input could be None as well for empty list\n Node is defined as\n\n class Node(object):\n\n def __init__(self, data=None, next_node=None):\n self.data = data\n self.next = next_node\n\"\"\"\n\ndef print_list(head):\n if head.data is not None:\n print(head.data, end='')\n if head.next is not None:\n print_list(head.next)\n print()\n# ------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------\n# https://www.hackerrank.com/challenges/sparse-arrays/problem\nnum_strings = int(input())\n\nstring_counts = {}\nfor _ in range(num_strings):\n key = input()\n if key in string_counts:\n string_counts[key] += 1\n else:\n string_counts[key] = 1\n\nqueries = []\nnum_queries = int(input())\nfor _ in range(num_queries):\n queries.append(input())\n\nfor query_string in queries:\n if query_string in string_counts:\n print(string_counts[query_string])\n else:\n print('0')\n# ------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------\n# https://www.hackerrank.com/challenges/array-left-rotation/problem\n\ndef leftRotation(a, d):\n if len(a) == d:\n return a\n else:\n return a[d:] + a[:d]\n\nif __name__ == \"__main__\":\n n, d = input().strip().split(' ')\n n, d = [int(n), int(d)]\n a = list(map(int, input().strip().split(' ')))\n result = leftRotation(a, d)\n print (\" \".join(map(str, result)))\n# ------------------------------------------------------------------------------","repo_name":"aaronshaver/hacker-rank","sub_path":"2018-Aug/Data_Structures.py","file_name":"Data_Structures.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"19495808338","text":"\"\"\"Implements a GymAdapter that converts Gym envs into SoftlearningEnv.\"\"\"\n\nimport numpy as np\nimport gym\nfrom gym import spaces, wrappers\nimport safety_gym\nfrom safety_gym.envs.engine import Engine\nimport json\nimport os\nimport softlearning.environments.gym.mujoco_safety_gym as mjsg\nimport sys\nimport softlearning.environments.gym as gym_dir\n# path = os.path.dirname(mjsg.__file__)\n# sys.path.append(path)\npath = os.path.dirname(gym_dir.__file__)\nsys.path.append(path)\n\n\nfrom .softlearning_env import SoftlearningEnv\nfrom softlearning.environments.gym import register_environments\nfrom softlearning.environments.gym.wrappers import NormalizeActionWrapper\nfrom softlearning.environments.adapters.safety_preprocessed_wrapper import SafetyPreprocessedEnv\nfrom collections import defaultdict\nfrom stable_baselines.common.vec_env import VecFrameStack\nfrom stable_baselines.common.vec_env import VecNormalize\nfrom stable_baselines.common.vec_env import DummyVecEnv\n\n\ndef parse_domain_task(gym_id):\n domain_task_parts = gym_id.split('-')\n domain = '-'.join(domain_task_parts[:1])\n task = '-'.join(domain_task_parts[1:])\n\n return domain, task\n\n\nCUSTOM_GYM_ENVIRONMENT_IDS = register_environments()\nCUSTOM_GYM_ENVIRONMENTS = defaultdict(list)\n\nfor gym_id in CUSTOM_GYM_ENVIRONMENT_IDS:\n domain, task = parse_domain_task(gym_id)\n CUSTOM_GYM_ENVIRONMENTS[domain].append(task)\n\nCUSTOM_GYM_ENVIRONMENTS = dict(CUSTOM_GYM_ENVIRONMENTS)\n\nGYM_ENVIRONMENT_IDS = tuple(gym.envs.registry.env_specs.keys())\nGYM_ENVIRONMENTS = defaultdict(list)\n\n\nfor gym_id in GYM_ENVIRONMENT_IDS:\n domain, task = parse_domain_task(gym_id)\n GYM_ENVIRONMENTS[domain].append(task)\n\nGYM_ENVIRONMENTS = dict(GYM_ENVIRONMENTS)\n\nSAFETY_WRAPPER_IDS = {\n 'Safexp-PointGoal2-v0':SafetyPreprocessedEnv,\n 'Safexp-PointGoal1-v0':SafetyPreprocessedEnv,\n #'Safexp-PointGoal0-v0':SafetyPreprocessedEnv,\n}\n\nclass GymAdapter(SoftlearningEnv):\n \"\"\"Adapter that implements the SoftlearningEnv for Gym envs.\"\"\"\n\n def __init__(self,\n domain,\n task,\n *args,\n env=None,\n normalize=True,\n observation_keys=None,\n unwrap_time_limit=True,\n **kwargs):\n assert not args, (\n \"Gym environments don't support args. Use kwargs instead.\")\n\n self.normalize = normalize\n self.observation_keys = observation_keys\n self.unwrap_time_limit = unwrap_time_limit\n self.stacks = 1\n self.stacking_axis = 0\n\n self._Serializable__initialize(locals())\n super(GymAdapter, self).__init__(domain, task, *args, **kwargs)\n\n if env is None:\n assert (domain is not None and task is not None), (domain, task)\n env_id = f\"{domain}-{task}\"\n env = gym.envs.make(env_id, **kwargs)\n\n #env_id = f\"\"\n #env = gym.make(\"Safexp-PointGoal1-v0\")\n \n else:\n assert domain is None and task is None, (domain, task)\n env_id = 'custom'\n\n if isinstance(env, wrappers.TimeLimit) and unwrap_time_limit:\n # Remove the TimeLimit wrapper that sets 'done = True' when\n # the time limit specified for each environment has been passed and\n # therefore the environment is not Markovian (terminal condition\n # depends on time rather than state).\n env = env.env\n\n if isinstance(env.observation_space, spaces.Dict):\n observation_keys = (\n observation_keys or list(env.observation_space.spaces.keys()))\n if normalize:\n env = NormalizeActionWrapper(env)\n\n\n #### --- specifically for safety_gym wrappring --- ###\n if env_id in SAFETY_WRAPPER_IDS:\n dirname, _ = os.path.split(os.path.abspath(__file__))\n #### load config file\n with open(f'{dirname}/../gym/safety_gym/configs/{env_id}_config.json', 'r') as fp:\n config = json.load(fp)\n fp.close()\n # with open(f'{dirname}/../gym/safety_gym/add_configs/{env_id}_add_config.json', 'r') as fp:\n # add_config = json.load(fp)\n # fp.close()\n\n\n env = Engine(config)\n # env = SAFETY_WRAPPER_IDS[env_id](env)\n\n #### additional config info like stacking etc.\n # for k in add_config.keys():\n # self.safeconfig[k] = add_config[k]\n \n #### dump config file to current data dir\n with open(f'{env_id}_config.json', 'w') as fp:\n json.dump(config, fp)\n fp.close()\n ####\n\n ### adding unserializable additional info after dumping (lol)\n # self.obs_indices = env.obs_indices\n # self.safeconfig['obs_indices'] = self.obs_indices\n\n ### stack env\n self.stacks = config.get('stacks', 1) ### for convenience\n self.stacking_axis = config.get('stacking_axis',0)\n if self.stacks>1:\n env = DummyVecEnv([lambda:env])\n #env = VecNormalize(env) doesn't work at all for some reason\n env = VecFrameStack(env, self.stacks)\n\n #### --- end specifically for safety_gym --- ###\n\n\n self._env = env\n\n @property\n def observation_space(self):\n observation_space = self._env.observation_space\n return observation_space\n\n @property\n def active_observation_shape(self):\n \"\"\"Shape for the active observation based on observation_keys. \n returns latest observation in case of a stacked observation.\"\"\"\n if self.stacks>1:\n active_size = list(self._env.observation_space.shape)\n active_size[self.stacking_axis] = int(self._env.observation_space.shape[self.stacking_axis]/self.stacks)\n active_size = tuple(active_size)\n return active_size\n\n if not isinstance(self._env.observation_space, spaces.Dict):\n return super(GymAdapter, self).active_observation_shape\n\n observation_keys = (\n self.observation_keys\n or list(self._env.observation_space.spaces.keys()))\n\n active_size = sum(\n np.prod(self._env.observation_space.spaces[key].shape)\n for key in observation_keys)\n\n active_observation_shape = (active_size, )\n\n return active_observation_shape\n\n def convert_to_active_observation(self, observation):\n if self.stacks>1:\n old_obs_len = self._env.observation_space.shape[self.stacking_axis] - int(self._env.observation_space.shape[self.stacking_axis]/self.stacks)\n active_obs = np.delete(observation, slice(old_obs_len), self.stacking_axis)\n return active_obs\n\n if not isinstance(self._env.observation_space, spaces.Dict):\n return observation\n\n observation_keys = (\n self.observation_keys\n or list(self._env.observation_space.spaces.keys()))\n\n observation = np.concatenate([\n observation[key] for key in observation_keys\n ], axis=-1)\n\n return observation\n\n @property\n def action_space(self, *args, **kwargs):\n action_space = self._env.action_space\n if len(action_space.shape) > 1:\n raise NotImplementedError(\n \"Action space ({}) is not flat, make sure to check the\"\n \" implemenation.\".format(action_space))\n return action_space\n\n def step(self, action, *args, **kwargs):\n # TODO(hartikainen): refactor this to always return an OrderedDict,\n # such that the observations for all the envs is consistent. Right now\n # some of the gym envs return np.array whereas others return dict.\n #\n # Something like:\n # observation = OrderedDict()\n # observation['observation'] = env.step(action, *args, **kwargs)\n # return observation\n\n if isinstance(self._env, VecFrameStack): ### because VecEnv has additional dim for parallel envs\n action=np.array([action])\n \n return self._env.step(action, *args, **kwargs)\n\n def reset(self, *args, **kwargs):\n return self._env.reset(*args, **kwargs)\n\n def render(self, *args, **kwargs):\n return self._env.render(*args, **kwargs)\n\n def close(self, *args, **kwargs):\n return self._env.close(*args, **kwargs)\n\n def get_sim_state(self, *args, **kwargs): #### @anyboby\n assert hasattr(self._env, 'get_sim_state')\n return self._env.get_sim_state(*args, **kwargs)\n\n def seed(self, *args, **kwargs):\n return self._env.seed(*args, **kwargs)\n\n @property\n def domain(self):\n return self._domain\n\n @property\n def unwrapped(self):\n return self._env.unwrapped\n\n def get_param_values(self, *args, **kwargs):\n raise NotImplementedError\n\n def set_param_values(self, *args, **kwargs):\n raise NotImplementedError\n","repo_name":"anyboby/ConstrainedMBPO","sub_path":"softlearning/environments/adapters/gym_adapter.py","file_name":"gym_adapter.py","file_ext":"py","file_size_in_byte":9007,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"43"} +{"seq_id":"14313178992","text":"import json\nimport logging\nimport uuid\nimport requests\nimport re\nimport ConfigParser\n\n\nclass Identity(object):\n\n def __init__(self, my_logger=None):\n config = ConfigParser.ConfigParser()\n config.read(\"general.config\")\n self.my_logger = my_logger\n self.endpoint = config.get(\"identity\", \"endpoint\")\n self.username = config.get(\"identity\", \"username\")\n self.apikey = config.get(\"identity\", \"apikey\")\n\n def get_token(self):\n url = \"{}/tokens\".format(self.endpoint)\n headers = {\"Content-type\": \"application/json\",\n \"Accept\": \"application/json\"}\n payload = {\"auth\": {\"RAX-KSKEY:apiKeyCredentials\":\n {\"username\": self.username,\n \"apiKey\": self.apikey}}}\n try:\n resp = requests.post(\n url,\n headers=headers,\n data=json.dumps(payload),\n verify=False)\n except Exception as ex:\n self.my_logger.error(ex)\n self.my_logger.info(\"Connect to identity to get a token\")\n if resp.status_code == 200:\n resp_json = resp.json()\n self.my_logger.info(\"successful token\")\n return resp_json[\"access\"][\"token\"][\"id\"]\n else:\n self.my_logger.info(\"failed token\")\n return \"none\"\n\n\nif __name__ == '__main__':\n one_identity = Identity()\n token = one_identity.get_token()\n","repo_name":"jqxin2006/scandiy","sub_path":"identity.py","file_name":"identity.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"30164695354","text":"__all__ = []\n\nfrom random import randint\n\nfrom maastesting.factory import factory\nfrom maastesting.testcase import MAASTestCase\nfrom provisioningserver.utils.url import compose_URL\n\n\nclass TestComposeURL(MAASTestCase):\n\n def make_path(self):\n \"\"\"Return an arbitrary URL path part.\"\"\"\n return '%s/%s' % (factory.make_name('root'), factory.make_name('sub'))\n\n def make_network_interface(self):\n return 'eth%d' % randint(0, 100)\n\n def test__inserts_IPv4(self):\n ip = factory.make_ipv4_address()\n path = self.make_path()\n self.assertEqual(\n 'http://%s/%s' % (ip, path),\n compose_URL('http:///%s' % path, ip))\n\n def test__inserts_IPv6_with_brackets(self):\n ip = factory.make_ipv6_address()\n path = self.make_path()\n self.assertEqual(\n 'http://[%s]/%s' % (ip, path),\n compose_URL('http:///%s' % path, ip))\n\n def test__escapes_IPv6_zone_index(self):\n ip = factory.make_ipv6_address()\n zone = self.make_network_interface()\n hostname = '%s%%%s' % (ip, zone)\n path = self.make_path()\n self.assertEqual(\n 'http://[%s%%25%s]/%s' % (ip, zone, path),\n compose_URL('http:///%s' % path, hostname))\n\n def test__inserts_bracketed_IPv6_unchanged(self):\n ip = factory.make_ipv6_address()\n hostname = '[%s]' % ip\n path = self.make_path()\n self.assertEqual(\n 'http://%s/%s' % (hostname, path),\n compose_URL('http:///%s' % path, hostname))\n\n def test__does_not_escape_bracketed_IPv6_zone_index(self):\n ip = factory.make_ipv6_address()\n zone = self.make_network_interface()\n path = self.make_path()\n hostname = '[%s%%25%s]' % (ip, zone)\n self.assertEqual(\n 'http://%s/%s' % (hostname, path),\n compose_URL('http:///%s' % path, hostname))\n\n def test__inserts_hostname(self):\n hostname = factory.make_name('host')\n path = self.make_path()\n self.assertEqual(\n 'http://%s/%s' % (hostname, path),\n compose_URL('http:///%s' % path, hostname))\n\n def test__preserves_query(self):\n ip = factory.make_ipv4_address()\n key = factory.make_name('key')\n value = factory.make_name('value')\n self.assertEqual(\n 'https://%s?%s=%s' % (ip, key, value),\n compose_URL('https://?%s=%s' % (key, value), ip))\n\n def test__preserves_port_with_IPv4(self):\n ip = factory.make_ipv4_address()\n port = factory.pick_port()\n self.assertEqual(\n 'https://%s:%s/' % (ip, port),\n compose_URL('https://:%s/' % port, ip))\n\n def test__preserves_port_with_IPv6(self):\n ip = factory.make_ipv6_address()\n port = factory.pick_port()\n self.assertEqual(\n 'https://[%s]:%s/' % (ip, port),\n compose_URL('https://:%s/' % port, ip))\n\n def test__preserves_port_with_hostname(self):\n hostname = factory.make_name('host')\n port = factory.pick_port()\n self.assertEqual(\n 'https://%s:%s/' % (hostname, port),\n compose_URL('https://:%s/' % port, hostname))\n","repo_name":"sfeole/maas","sub_path":"src/provisioningserver/utils/tests/test_url.py","file_name":"test_url.py","file_ext":"py","file_size_in_byte":3204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"43"} +{"seq_id":"13199564718","text":"# -- Imports for Ensemble Techniques\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.cluster import KMeans\nfrom deslib.dcs import APosteriori, APriori, LCA, MCB, MLA, OLA, Rank\nfrom deslib.des import METADES, DESClustering, DESP, DESKNN, KNOP, KNORAE, KNORAU\nfrom deslib.des.probabilistic import RRC, DESKL, MinimumDifference, Logarithmic, Exponential\nfrom ensemble_techniques.autosklearn.ensemble_selection import EnsembleSelection\nfrom ensemble_techniques.custom.baselines import SingleBest, VirtualBest\nfrom ensemble_techniques.sklearn.stacking import StackingClassifier\nfrom ensemble_techniques.sklearn.voting import VotingClassifier\n\n# -- Get Preprocessing\nfrom results.data_utils import get_default_preprocessing\n\n# -- Get Metric\nfrom ensemble_techniques.util.metrics import OpenMLAUROC\n\n# -- Randomness\nfrom numpy.random import RandomState\n\n\ndef get_sklearn_techniques(rng_seed):\n # -- Sklearn Existing Models\n # Could use existing methods but they break with calibration + fake models (due to datasets being too small for cv)\n sklearn_techniques = {\n \"sklearn.VotingClassifier\": {\n \"technique\": VotingClassifier,\n \"technique_args\": {\"voting\": \"soft\",\n # , \"n_jobs\": -1\n \"prefitted\": True,\n },\n \"probability_calibration\": \"auto\",\n \"pre_fit_base_models\": True\n },\n \"sklearn.StackingClassifier\": {\n \"technique\": StackingClassifier,\n \"technique_args\": {\"final_estimator\": LogisticRegression(random_state=RandomState(rng_seed), n_jobs=-1),\n # \"n_jobs\": -1\n \"prefitted\": True, \"only_fit_final_estimator\": True\n },\n \"probability_calibration\": \"auto\",\n \"pre_fit_base_models\": True\n },\n \"sklearn.StackingClassifier.passthrough\": {\n \"technique\": StackingClassifier,\n \"technique_args\": {\"final_estimator\": RandomForestClassifier(random_state=RandomState(rng_seed), n_jobs=-1),\n # \"n_jobs\": -1\n \"prefitted\": True, \"only_fit_final_estimator\": True\n },\n \"probability_calibration\": \"auto\",\n \"pre_fit_base_models\": True\n },\n }\n # Add default values for sklearn\n sklearn_default_values = {\"base_models_with_names\": True, \"label_encoder\": True,\n \"preprocessor\": get_default_preprocessing()}\n for key in sklearn_techniques.keys():\n sklearn_techniques[key].update(sklearn_default_values)\n\n return sklearn_techniques\n\n\ndef get_deslib_techniques(rng_seed):\n # -- DESLib Existing Models\n deslib_techniques = {\n # DCS Methods\n \"DCS.APosteriori\": {\"technique\": APosteriori,\n \"technique_args\": {\"random_state\": RandomState(rng_seed), \"n_jobs\": -1},\n \"probability_calibration\": \"auto\"},\n \"DCS.APriori\": {\"technique\": APriori,\n \"technique_args\": {\"random_state\": RandomState(rng_seed), \"n_jobs\": -1},\n \"probability_calibration\": \"auto\"},\n \"DCS.LCA\": {\"technique\": LCA,\n \"technique_args\": {\"random_state\": RandomState(rng_seed), \"n_jobs\": -1}},\n \"DCS.MCB\": {\"technique\": MCB,\n \"technique_args\": {\"random_state\": RandomState(rng_seed), \"n_jobs\": -1}},\n \"DCS.MLA\": {\"technique\": MLA,\n \"technique_args\": {\"random_state\": RandomState(rng_seed), \"n_jobs\": -1}},\n \"DCS.OLA\": {\"technique\": OLA,\n \"technique_args\": {\"random_state\": RandomState(rng_seed), \"n_jobs\": -1}},\n \"DCS.Rank\": {\"technique\": Rank,\n \"technique_args\": {\"random_state\": RandomState(rng_seed), \"n_jobs\": -1}},\n\n # DES Methods\n \"DES.METADES\": {\"technique\": METADES,\n \"technique_args\": {\"random_state\": RandomState(rng_seed), \"n_jobs\": -1}},\n \"DES.DESClustering\": {\"technique\": DESClustering,\n \"technique_args\": {\"random_state\": RandomState(rng_seed), \"n_jobs\": -1,\n # Switch to accuracy instead of original score metric,\n # because implementation does not support AUROC correctly.\n \"metric_performance\": \"accuracy_score\",\n\n # have to init by us because it is bugged otherwise\n # (most likely wrong python/sklearn version used by us)\n # but kmeans never had n_jobs?...\n \"clustering\": KMeans(n_clusters=5, random_state=RandomState(rng_seed))\n }\n },\n \"DES.DESP\": {\"technique\": DESP,\n \"technique_args\": {\"random_state\": RandomState(rng_seed), \"n_jobs\": -1}},\n \"DES.DESKNN\": {\"technique\": DESKNN,\n \"technique_args\": {\"random_state\": RandomState(rng_seed), \"n_jobs\": -1}},\n \"DES.KNOP\": {\"technique\": KNOP,\n \"technique_args\": {\"random_state\": RandomState(rng_seed), \"n_jobs\": -1}},\n \"DES.KNORAE\": {\"technique\": KNORAE,\n \"technique_args\": {\"random_state\": RandomState(rng_seed), \"n_jobs\": -1}},\n \"DES.KNORAU\": {\"technique\": KNORAU,\n \"technique_args\": {\"random_state\": RandomState(rng_seed), \"n_jobs\": -1}},\n\n # Probabilistic\n \"Probabilistic.RRC\": {\"technique\": RRC,\n \"technique_args\": {\"random_state\": RandomState(rng_seed), \"n_jobs\": -1}},\n \"Probabilistic.DESKL\": {\"technique\": DESKL,\n \"technique_args\": {\"random_state\": RandomState(rng_seed), \"n_jobs\": -1}},\n \"Probabilistic.MinimumDifference\": {\"technique\": MinimumDifference,\n \"technique_args\": {\"random_state\": RandomState(rng_seed), \"n_jobs\": -1}},\n \"Probabilistic.Logarithmic\": {\"technique\": Logarithmic,\n \"technique_args\": {\"random_state\": RandomState(rng_seed), \"n_jobs\": -1}},\n \"Probabilistic.Exponential\": {\"technique\": Exponential,\n \"technique_args\": {\"random_state\": RandomState(rng_seed), \"n_jobs\": -1}},\n\n # Static\n # We are not using any of the static method from deslib.\n # The SBA and VBA are suboptimal and we already have stacking from sklearn.\n\n }\n # Add default values for sklearn\n deslib_default_values = {\"pre_fit_base_models\": True, \"preprocessor\": get_default_preprocessing()}\n for key in deslib_techniques.keys():\n deslib_techniques[key].update(deslib_default_values)\n deslib_techniques = {\"deslib.{}\".format(key): val for key, val in deslib_techniques.items()}\n\n return deslib_techniques\n\n\ndef get_autosklearn_techniques(rng_seed):\n autosklearn_techniques = {\n \"autosklearn.EnsembleSelection\": {\n \"technique\": EnsembleSelection,\n \"technique_args\": {\"ensemble_size\": 50,\n \"metric\": OpenMLAUROC, # Please be aware, AUROC is very inefficient\n \"random_state\": RandomState(rng_seed)},\n \"probability_calibration\": \"auto\"\n }\n }\n\n autosklearn_default_values = {\"pre_fit_base_models\": True, \"preprocessor\": get_default_preprocessing()}\n for key in autosklearn_techniques.keys():\n autosklearn_techniques[key].update(autosklearn_default_values)\n\n return autosklearn_techniques\n\n\ndef get_custom_techniques(rng_seed):\n baselines = {\n \"custom.VirtualBest\": {\n \"technique\": VirtualBest,\n \"technique_args\": {\"handle_no_correct\": True},\n \"oracle\": True,\n \"probability_calibration\": \"auto\"\n },\n \"custom.SingleBest\": {\n \"technique\": SingleBest,\n \"technique_args\": {\"metric\": OpenMLAUROC, # Please be aware, AUROC is very inefficient\n \"predict_method\": \"predict_proba\"},\n \"probability_calibration\": \"auto\"\n }\n }\n custom_techniques = {**baselines}\n custom_default_values = {\"pre_fit_base_models\": True, \"preprocessor\": get_default_preprocessing()}\n for key in custom_techniques.keys():\n custom_techniques[key].update(custom_default_values)\n\n return custom_techniques\n\n\ndef get_benchmark_techniques(rng_seed):\n return {**get_sklearn_techniques(rng_seed), **get_deslib_techniques(rng_seed),\n **get_autosklearn_techniques(rng_seed), **get_custom_techniques(rng_seed)}\n","repo_name":"ISG-Siegen/assembled","sub_path":"ensemble_techniques/collect_ensemble_techniques.py","file_name":"collect_ensemble_techniques.py","file_ext":"py","file_size_in_byte":8991,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"43"} +{"seq_id":"28426158992","text":"__author__ = \"Martin Blais <blais@furius.ca>\"\n\nfrom beancount.utils import test_utils\nfrom beancount.scripts import example\nfrom beancount.ops import validation\nfrom beancount import loader\n\n\nclass TestScriptExample(test_utils.TestCase):\n\n def test_generate(self):\n # Basic test that calls out the generator.\n with test_utils.capture() as stdout:\n result = test_utils.run_with_args(example.main, [])\n self.assertEqual(0, result, str(result))\n file_contents = stdout.getvalue()\n self.assertTrue(file_contents)\n\n loaded_entries, errors, _ = loader.load_string(\n file_contents,\n extra_validations=validation.HARDCORE_VALIDATIONS)\n self.assertFalse(errors)\n","repo_name":"iocoop/beancount","sub_path":"src/python/beancount/scripts/example_test.py","file_name":"example_test.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"43"} +{"seq_id":"9274591014","text":"from django.shortcuts import render\nimport requests\nfrom product_search.models import Product\nfrom django.views.decorators.csrf import csrf_exempt\nimport threading\nimport time\nimport json\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n\nstart = time.time()\n\n\ndef paytmMall(search_text):\n \"\"\"\n Api to fetch data form Paytm Mall Provider\n :param search_text:\n :return: json object\n \"\"\"\n extract_key = \"grid_layout\" # as per resulted json \"grid_layout\" key has all products as values\n query = \"https://search.paytm.com/v2/search?userQuery=\" + search_text\n print(query, extract_key)\n try:\n response = requests.get(query)\n data = response.json()\n result = data[extract_key] # as per resulted json \"products\" key has all products as values\n product_list = []\n\n for product in result:\n # Create product list\n product_list.append(Product(name=product['name'], price=product['offer_price'],\n url=product['url'], image=product['image_url']))\n\n # Call bulk_create to create records in a single call\n Product.objects.bulk_create(product_list)\n\n return data\n except json.decoder.JSONDecodeError as err:\n error, = err.args\n print(\"error for PAYTMALL \", error)\n except Exception as error:\n er, = error.args\n print(er)\n return er\n\n\ndef shopClues(search_text):\n \"\"\"\n Api to fetch data form Shop Clues Provider\n :param search_text:\n :return: json object\n \"\"\"\n extract_key = \"products\"\n query = \"https://api.shopclues.com/api/v11/search?q=\" + search_text + \"&z=1&key=d12121c70dda5edfgd1df6633fdb36c0\"\n print(\"FOR SHOP CLUE\", query)\n try:\n response = requests.get(query)\n data = response.json()\n result = data[extract_key] # as per resulted json \"products\" key has all products as values\n product_list = []\n\n for product in result:\n # Create product list\n product_list.append(Product(name=product['product'], price=product['price'],\n url=product['product_url'], image=product['image_url']))\n\n # Call bulk_create to create records in a single call\n Product.objects.bulk_create(product_list)\n\n print(\"ShopClues\", product_list)\n return data\n except json.decoder.JSONDecodeError as err:\n error, = err.args\n print(\"error for ShopClues\", error)\n except Exception as error:\n er, = error.args\n print(er)\n return er\n\n # Product.objects.filter(pk=some_value).update(field1='some value')\n\n\ndef tataCliq(search_text):\n \"\"\"\n Api to fetch data form Tata Cliq Provider\n :param search_text:\n :return: json object\n \"\"\"\n\n extract_key = \"searchresult\" # as per resulted json \"searchresult\" key has all products as values\n query = \"https://www.tatacliq.com/marketplacewebservices/v2/mpl/products/serpsearch?type=category&channel=mobile&pageSize=20&typeID=al&page=0&searchText=\" + search_text + \"&isFilter=false&isTextSearch=true\"\n\n try:\n headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, '\n 'like Gecko) Chrome/50.0.2661.102 Safari/537.36',\n \"Content-Type\": \"application/x-www-form-urlencoded\"}\n response = requests.get(query, headers=headers)\n\n data = response.json()\n result = data[extract_key] # as per resulted json \"products\" key has all products as values\n product_list = []\n\n for product in result:\n # Create product list\n print(product)\n product_list.append(Product(name=product[\"productname\"], price=product['sellingPrice']['value'],\n url=product['imageURL'], image=product['imageURL']))\n # since the tataCliq json doesn't have any product url\n\n # Call bulk_create to create records in a single call\n Product.objects.bulk_create(product_list)\n print(\"TataCliq\", result)\n\n except json.decoder.JSONDecodeError as err:\n error, = err.args\n print(\"error for TataCliq\", error)\n\n except Exception as error:\n er, = error.args\n print(er)\n return er\n\n\n@csrf_exempt\ndef search(request):\n if request.POST:\n search_text = request.POST['search']\n\n lst = search_text.split(' ')\n if len(lst) > 1:\n search_text = '+'.join(lst)\n products = []\n print(\"Text to be searched\", search_text)\n if Product.objects.filter(name__icontains=search_text).exists():\n product_list = Product.objects.filter(name__icontains=search_text).order_by('id')\n page = request.GET.get('page', 1)\n paginator = Paginator(product_list, 50)\n try:\n products = paginator.page(page)\n except PageNotAnInteger:\n products = paginator.page(1)\n except EmptyPage:\n products = paginator.page(paginator.num_pages)\n\n # creating threads\n t1 = threading.Thread(target=paytmMall, args=(search_text,), name='t1')\n t2 = threading.Thread(target=shopClues, args=(search_text,), name='t2')\n t3 = threading.Thread(target=tataCliq, args=(search_text,), name='t3')\n\n # starting threads\n t1.start()\n t2.start()\n t3.start()\n\n # wait until all threads finish\n t1.join()\n t2.join()\n t3.join()\n\n print(\"Elapsed Time: %s\" % (time.time() - start))\n return render(request, 'search.html', {'error': '', 'data': products})\n\n else:\n return render(request, 'search.html', {'error': 'Please enter something', 'data': ''})\n","repo_name":"ParasYadav94/search_aggregator","sub_path":"product_search/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5824,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"43"} +{"seq_id":"15006655607","text":"from tkinter import *\nfrom ast import literal_eval\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nfrom matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg) \n\nheading_font = (\"Arial\",16)\napp_font = (\"Helvetica\",13) \n\nroot = Tk()\nroot.configure(background='thistle4')\n\n\nclass LeftFrame(Frame):\n def __init__(self,master=None,drawing_frame = None):\n super().__init__(master,bg=\"salmon\")\n self.master=master\n self.grid(row=0,column=0,sticky=\"nsew\",padx=50,pady=75)\n self.drawing_frame = drawing_frame\n\n self.header = Label(self,text=\"PLOT YOUR FUNCTION\",font=heading_font,highlightcolor=\"black\",highlightthickness=4,highlightbackground=\"black\",padx=5,pady=5)\n self.header.grid(row=0,column=0,columnspan=2,pady=50)\n\n self.expr = Label(self,text = \"Enter an expression of variable x:\",font=app_font) \n self.expr.grid(row=1,column=0,padx = 5,pady = 10)\n self.expression = Text(self,height=2,width=20,font=app_font)\n self.expression.grid(row=1,column=1,padx = 5,pady = 20)\n\n self.lb = Label(self,text = \"Enter Lower Bound of Iteration : \\n(Starting value of x)\",font=app_font)\n self.lb.grid(row=2,column=0,padx=5,pady=10)\n self.lbound = Text(self,height=2,width=20,font=app_font)\n self.lbound.grid(row=2,column=1,padx = 5,pady = 20)\n\n self.ub = Label(self,text = \"Enter Upper Bound of Iteration : \\n(Final value of x)\",font=app_font)\n self.ub.grid(row=3,column=0,padx=5,pady=10)\n self.ubound = Text(self,height=2,width=20,font=app_font)\n self.ubound.grid(row=3,column=1,padx = 5,pady = 20)\n\n self.plot_button = Button(self,text = \"Create Plot\",command=self.draw_plot,font=app_font,fg=\"white\",bg=\"black\",highlightcolor=\"white\",highlightthickness=4,highlightbackground=\"purple1\",padx=5,pady=5)\n self.plot_button.grid(row=4,column=0,padx=15,pady=20,columnspan=1) \n\n self.exit_button = Button(self,text = \"Exit\",command=exit,font=app_font,fg=\"white\",bg=\"black\",highlightcolor=\"white\",highlightthickness=4,highlightbackground=\"purple1\",padx=5,pady=5)\n self.exit_button.grid(row=4,column=1,padx=15,pady=20,columnspan=1) \n\n\n def draw_plot(self):\n formula = self.expression.get(1.0,END)\n formula = formula.strip('\\n')\n a = literal_eval(self.lbound.get(1.0,END))\n b = literal_eval(self.ubound.get(1.0,END))\n\n x = np.linspace(a,b,20)\n mydict = {'x':x}\n y = eval(formula,mydict)\n\n \n fig = plt.figure(num=1)\n fig.clf()\n plt.plot(x,y,'o-')\n plt.xlabel('Value of x')\n plt.ylabel('Value of y')\n title = \"Plot of y = \"+formula+\" in the range [\"+str(a)+\",\"+str(b)+\"]\"\n plt.title(title)\n\n canvas = FigureCanvasTkAgg(fig, master=self.drawing_frame)\n plot_widget = canvas.get_tk_widget()\n plot_widget.grid(row = 0,column=0)\n \n\nclass RightFrame(Frame):\n def __init__(self,master=None):\n super().__init__(master,background='white')\n self.master=master\n self.grid(row=0,column=1,sticky=\"nsew\",padx=50,pady=75)\n\n\nclass Window(Frame):\n def __init__(self,master=None):\n super().__init__(master)\n\n master.title('Matplotlib Plotter GUI')\n master.geometry('1400x800')\n\n master.grid_rowconfigure(0,weight=1)\n master.grid_columnconfigure(0,weight=1,uniform='group1')\n master.grid_columnconfigure(1,weight=1,uniform='group1')\n\n self.rframe = RightFrame(master)\n self.lframe = LeftFrame(master,self.rframe)\n\ngui_window = Window(root)\n\nroot.mainloop()\n\n","repo_name":"Debanjan2001/CS29006-Software-Engineering-Lab","sub_path":"Assignment-2/Part1/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"22380790304","text":"# -*- coding: utf-8 -*-\nfrom tkinter import *\nfrom tkinter import ttk\nimport tkinter as tk\nimport tkinter.messagebox\nimport tkinter\nimport time\nimport sys\nfrom pytube import YouTube \nfrom pytubemp3 import YouTube\n\nwindow=Tk()\nwindow.title('//ABDUL_MUID')\nwindow.geometry('340x200')\nwindow.resizable(width=False, height=False)\nwindow.configure(bg='black')\nttk.Label(window, text = \"YouTube File Downloader\",background = 'black', foreground =\"green\",font = (\"Times New Roman\", 15)).grid(row = 0, column = 1,padx=10,pady=25) \nl1=Label(window, text=\"URL\")\nl1.grid(row=5,column=0)\nl1.configure(bg='black', foreground='green')\nl1=Label(window, text=\"Format\")\nl1.grid(row=10,column=0)\nl1.configure(bg='black', foreground='green')\nurl_text=StringVar()\nurl_entry = Entry(window, textvariable=url_text)\ne1=Entry(window,textvariable=url_text)\ne1.grid(row=5,column=1)\nn = tk.StringVar() \nformat = ttk.Combobox(window, width = 5, textvariable = n) \nformat['values'] = ('MP3','MP4') \nformat.grid(column = 1, row = 10) \nformat.current() \n#ttk.Separator(window).place(x=0, y=200, relwidth=5)\n\ndef code():\n youtube_link=url_entry.get()\n ext_format=format.get()\n print(\"Searching File...\")\n animation = [\"[■□□□□□□□□□□□□□□]\",\"[■■□□□□□□□□□□□□□]\", \"[■■■□□□□□□□□□□□□]\", \"[■■■■□□□□□□□□□□□]\", \"[■■■■■□□□□□□□□□□]\", \"[■■■■■■□□□□□□□□□]\", \"[■■■■■■■□□□□□□□□]\", \"[■■■■■■■■□□□□□□□]\", \"[■■■■■■■■■□□□□□□]\", \"[■■■■■■■■■■□□□□□]\", \"[■■■■■■■■■■■□□□□]\",\"[■■■■■■■■■■■■□□□]\", \"[■■■■■■■■■■■■■□□]\", \"[■■■■■■■■■■■■■■□]\", \"[■■■■■■■■■■■■■■■]\" ]\n for i in range(len(animation)):\n time.sleep(0.2)\n sys.stdout.write(\"\\r\" + animation[i % len(animation)])\n sys.stdout.flush()\n print(\"\\n File Found!!! \\n Stand-By For Download...\")\n try:\n if ext_format==\"MP4\":\n yt_obj = YouTube(youtube_link) \n filters = yt_obj.streams.filter(progressive=True, file_extension='mp4')\n filters.get_highest_resolution().download()\n else:\n yt_obj = YouTube(youtube_link) \n YouTube(youtube_link).streams.filter(only_audio=True).first().download()\n print(\"Downloading....\")\n animationTwo = \"|/-\\\\\"\n\n for i in range(100):\n time.sleep(0.1)\n sys.stdout.write(\"\\r\" + animationTwo[i % len(animationTwo)])\n sys.stdout.flush()\n print(\"___________/\")\n print('File Downloaded Successfully')\n except Exception as e:\n print(e)\n\nbtn=Button(window, text='Download', bd='5', command=code)\nbtn.grid(row = 15, column=1, padx=25,pady=25)\nwindow.mainloop()\n\n","repo_name":"cyph-er/youtube-video-downloader","sub_path":"youtube downloader/final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":3006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"27715754318","text":"from sage.all import (ZZ, QQ, EllipticCurve, primes, hilbert_class_polynomial, cm_j_invariants, NumberField, pari, polygen, LCM, Set )\nfrom sage.schemes.elliptic_curves.cm import discriminants_with_bounded_class_number\n\n# To avoid recomputing the CM j-invariants of any fixed degree, we\n# keep a dict of all the j-polynomials in each degree.\n\n# The following lines initialise the dict unless it has already\n# started to be filled (so we can reload this file without losing\n# values already computed):\n\ntry:\n assert len(j_pols_by_degree)\nexcept:\n j_pols_by_degree = {}\n\ndef is_cm_pol(H):\n \"\"\"H is a minimal polynomial of an algebraic number, hence\n irreducible and monic but not necessarily integral.\n\n Returns either a negative discriminant D, if H is the minimal\n polynomial of a CM j-invariant with discriminant D, or 0\n otherwise.\n\n Uses a cache, so that for each degree d we compute the full set of\n CM polynomials of degree d only once.\n\n \"\"\"\n global j_pols_by_degree\n d = H.degree()\n if d in j_pols_by_degree:\n if H in j_pols_by_degree[d]:\n return j_pols_by_degree[d][H]\n return ZZ(0)\n\n if not H.is_monic():\n return ZZ(0)\n if not all(c in ZZ for c in H.coefficients()):\n return ZZ(0)\n\n print(\"Computing all degree {} CM j-polynomials\".format(d))\n Dlist = [D*f*f for D,f in discriminants_with_bounded_class_number(d)[d]]\n j_pols_by_degree[d] = dict([(hilbert_class_polynomial(D),D) for D in Dlist])\n print(\" done: {} discriminants {}\".format(len(Dlist), Dlist))\n\n if H in j_pols_by_degree[d]:\n return j_pols_by_degree[d][H]\n return ZZ(0)\n\ndef is_Q_curve(E, maxp=100, certificate=False, verbose=False):\n r\"\"\"Return True if E is a Q-curve, i.e. is isogenous (over Qbar) to all\n its Galois conjugates.\n\n ``maxp`` (int, default 100): bound on primes used for checking\n necessary local conditions. The result will not depend on this,\n but using a larger value is more likely to return False faster.\n\n ``certificate`` (bool, default ``False``): if ``True`` then a\n second value is returned giving a certificate for the Q-curve\n property. This a dict, either {'CM':D} where D is a negative\n discriminant, or {'CM':0, 'core_poly', 'rho', 'r', 'N'} where\n 'core_poly' is an irreducible monic polynomial over `QQ` of degree\n `2**\\rho`, all of whose roots are j-invariants of curves isogenous\n to $E$, `N` (the core level) is a square-free integer with `r`\n prime factors which is the LCM of the degrees of the isogenies\n between these conjugates. For example, if `j(E')=j\\in\\QQ` for any\n curve $E'$ isogenous to $E$, then the certificate is {'CM':0,\n 'r':0, 'rho':0, 'core_poly': x-j, 'N':1}.\n\n Method:\n\n 1. If E has rational j-invariant or has CM then True.\n\n 2. Replace E by a curve defined over K=Q(j). Let N be the conductor norm.\n\n 3. For all p|N check that the valuations of j at all P|p are\n either all negative or all non-negative; else False.\n\n 4. For p<=maxp not dividing N, check that either all P|p are\n ordinary or all are supersingular, else False. If all are\n ordinary, check that the integers a_P(E)^2-4*N(P) have the same\n square-free part; else False.\n\n 5. Compute the K-isogeny class of E using the \"heuristic\" option\n (so it is not guaranteed to be complete). Check whether the set\n of j-invariants of curves in the class of 2-power degree contains\n a complete Galois orbit. If so:True.\n\n 6. Otherwise repeat step 4 for more primes, and if still\n undecided, repeat Step 5 without the \"heuristic\" option, to get\n the complete K-isogeny class (which will probably be no bigger\n than before). Now return True if the set of j-invariants of\n curves in the class contains a complete Galois orbit, otherwise\n return False.\n\n \"\"\"\n if verbose:\n print(\"Checking whether {} is a Q-curve\".format(E))\n\n # Step 1\n\n # all curves with rational j-invariant are Q-curves:\n jE = E.j_invariant()\n if jE in QQ:\n if verbose:\n print(\"Yes: j(E) is in QQ\")\n if certificate:\n x = polygen(QQ)\n if jE in cm_j_invariants(QQ):\n return True, {'CM': is_cm_pol(x-jE)}\n else:\n return True, {'CM': ZZ(0), 'r': ZZ(0), 'rho': ZZ(0), 'N': ZZ(1), 'core_poly': x}\n else:\n return True\n\n # CM curves are Q-curves:\n jpoly = jE.minpoly()\n D = is_cm_pol(jpoly)\n if D:\n if verbose:\n print(\"Yes: E is CM (discriminant {})\".format(D))\n if certificate:\n return True, {'CM': D}\n else:\n return True\n\n # Step 2: replace E by a curve defined over Q(j(E)):\n\n K = E.base_field()\n if jpoly.degree()<K.degree():\n if verbose:\n print(\"switching to smaller base field: j's minpoly is {}\".format(jpoly))\n f = pari(jpoly).polredbest().sage({'x':jpoly.parent().gen()})\n K2 = NumberField(f, 'b')\n jE = jpoly.roots(K2)[0][0]\n if verbose:\n print(\"New j is {} over {}, with minpoly {}\".format(jE, K2, jE.minpoly()))\n assert jE.minpoly()==jpoly\n E = EllipticCurve(j=jE)\n K = K2\n if verbose:\n print(\"New test curve is {}\".format(E))\n\n # Step 3: check primes of bad reduction\n\n NN = E.conductor().norm()\n for p in NN.support():\n Plist = K.primes_above(p)\n if len(Plist)<2:\n continue\n pot_mult = [jE.valuation(P)<0 for P in Plist]\n consistent = all(pot_mult) or not any(pot_mult)\n if not consistent:\n if verbose:\n print(\"No: inconsistency at the {} primes dividing {} \".format(len(Plist),p))\n print(\" - potentially multiplicative: {}\".format(pot_mult))\n if certificate:\n return False, None\n else:\n return False\n\n # Step 4 check: primes P of good reduction above p<=B:\n\n if verbose:\n print(\"Applying local tests at good primes above p<={}\".format(maxp))\n\n res4, p = Step4Test(E, B=maxp, oldB=0, verbose=verbose)\n if not res4:\n if verbose:\n print(\"No: local test at p={} failed\".format(p))\n if certificate:\n return False, None\n else:\n return False\n\n if verbose:\n print(\"...all local tests pass for p<={}\".format(maxp))\n\n # Step 5: compute the (partial) K-isogeny class of E and test the\n # set of j-invariants in the class:\n\n from sage.schemes.elliptic_curves.isogeny_class import IsogenyClass_EC_NumberField\n C = IsogenyClass_EC_NumberField(E, reducible_primes=None, algorithm='heuristic', minimal_models=False)\n #C = E.isogeny_class(algorithm='heuristic', minimal_models=False)\n jC = [E2.j_invariant() for E2 in C]\n res, centrejpols = conjugacy_test(jC, verbose=verbose)\n if res:\n if verbose:\n print(\"Yes: the isogeny class contains a complete conjugacy class of j-invariants\")\n if certificate:\n for f in centrejpols:\n rho = f.degree().valuation(2)\n centre_indices = [i for i,j in enumerate(jC) if f(j)==0]\n M = C.matrix()\n core_degs = [M[centre_indices[0], i] for i in centre_indices]\n level = LCM(core_degs)\n if level.is_squarefree():\n r = len(level.prime_divisors())\n cert = {'CM': ZZ(0), 'core_poly':f, 'rho':rho, 'r':r, 'N':level, 'core_degs':core_degs}\n return True, cert\n print(\"No central curve found\")\n else:\n return True\n\n # Now we are undecided. This can happen if either (1) E is not a\n # Q-curve but we did not use enough primes in Step 4 to detect\n # this, or (2) E is a Q-curve but in Step 5 we did not compute the\n # complete isogeny class. Case (2) is most unlikely since the\n # heuristic bound used in computing isogeny classes means that we\n # have all isogenous curves linked to E by an isogeny of degree\n # supported on primes<1000.\n\n # We first rerun Step 4 with a larger bound.\n\n xmaxp = 10*maxp\n if verbose:\n print(\"Undecided after first round, so we apply more local tests, up to {}\".format(xmaxp))\n\n res4, p = Step4Test(E, B=xmaxp, oldB=maxp, verbose=verbose)\n if not res4:\n if verbose:\n print(\"No: local test at p={} failed\".format(p))\n if certificate:\n return False, None\n else:\n return False\n\n # Now we rerun Step 5 using a rigorous computaion of the complete\n # isogeny class. This will probably contain no more curves than\n # before, in which case -- since we already tested that the set of\n # j-invariants does not contain a complete Galois conjugacy class\n # -- we can deduce that E is not a Q-curve.\n\n if verbose:\n print(\"...all local tests pass for p<={}\".format(xmaxp))\n print(\"We now compute the complete isogeny class...\")\n\n from sage.schemes.elliptic_curves.isogeny_class import IsogenyClass_EC_NumberField\n Cfull = IsogenyClass_EC_NumberField(E, reducible_primes=None, algorithm='Billerey', minimal_models=False)\n #Cfull = E.isogeny_class(minimal_models=False)\n jCfull = [E2.j_invariant() for E2 in Cfull]\n\n if len(jC) == len(jCfull):\n if verbose:\n print(\"...and find that we already had the complete class:so No\")\n if certificate:\n return False, None\n else:\n return False\n if verbose:\n print(\"...and find that the class contains {} curves, not just the {} we computed originally\".format(len(jCfull), len(jC)))\n res, cert = conjugacy_test(jCfull, verbose=verbose)\n if res:\n if verbose:\n print(\"Yes: the isogeny class contains a complete conjugacy class of j-invariants\")\n if certificate:\n return True, cert\n else:\n return True\n if verbose:\n print(\"No: the isogeny class does *not* contain a complete conjugacy class of j-invariants\")\n if certificate:\n return False, None\n else:\n return False\n\ndef Step4Test(E, B, oldB=0, verbose=False):\n K = E.base_field()\n NN = E.conductor().norm()\n for p in primes(B):\n if p<=oldB or p.divides(NN):\n continue\n Plist = K.primes_above(p)\n if len(Plist)<2:\n continue\n\n EmodP = [E.reduction(P) for P in Plist]\n\n # (a) Check all are ordinary or all supersingular:\n ordinary = [Ei.is_ordinary() for Ei in EmodP]\n consistent = all(ordinary) or not any(ordinary)\n if not consistent:\n if verbose:\n print(\"No: inconsistency at the {} primes dividing {} \".format(len(Plist),p))\n print(\" - ordinary: {}\".format(ordinary))\n return False, p\n\n # (b) Skip if all are supersingular:\n if not ordinary[0]:\n continue\n\n # else compare a_P^2-4*N(P) which should have the same squarefree part:\n\n discs = [(Ei.trace_of_frobenius()**2 - 4*P.norm()).squarefree_part() for P,Ei in zip(Plist, EmodP)]\n if any([d != discs[0] for d in discs[1:]]):\n if verbose:\n print(\"No: inconsistency at the {} ordinary primes dividing {} \".format(len(Plist),p))\n print(\" - Frobenius discrimants mod squares: {}\".format(discs))\n return False, p\n # Now we have failed to prove that E is not a Q-curve\n return True, 0\n\ndef conjugacy_test(jC, verbose=True):\n r\"\"\"Return True if a list of j-invariants contains a complete\n conjugacy class of 2-power degree.\n\n - `jC` (list): a list of algebraic numbers in the same field\n\n Output is (``False``, ``None``) or (``True``, poly) where poly is\n an irreducible polynomial of 2-power degree all of whose roots are\n in the list.\n \"\"\"\n jQ = next((j for j in jC if j in QQ), None)\n if jQ:\n if verbose:\n print(\"Yes: an isogenous curve has rational j-invariant {}\".format(jQ))\n x = polygen(QQ)\n return True, [x-jQ]\n\n # If the degree d is odd then we know that none of the\n # j-invariants in the class have 2-power degree, so we can exit.\n\n K = jC[0].parent()\n if K.degree()%2:\n if verbose:\n print(\"Odd-degree case: no rational j-invariant in the class {}\".format(jC))\n return False, None\n\n # If K has no quadratic subfields we can similarly conclude right\n # away. This is one way of determining this.\n\n if K(1).descend_mod_power(QQ,2) == [1]:\n if verbose:\n print(\"No-quadratic-subfield case: no rational j-invariant in the class {}\".format(jC))\n return False, None\n\n # compute the minimum polynomials of the j-invariants in the class\n pols = [j.minpoly() for j in jC]\n\n # pick out those of 2-power degree\n pols = [f for f in pols if f.degree().prime_to_m_part(2)==1]\n\n # see if there's a poly of degree d appearing d times. NB There\n # may be more than one of these, possibly including some conjugacy\n # classes defined over the core field but not central, so we\n # return all those with the minimal degree.\n\n mindeg = min([f.degree() for f in pols])\n minpols = [f for f in pols if f.degree()==mindeg]\n centrepols = list(Set([f for f in pols if f.degree()==minpols.count(f)]))\n if centrepols:\n if verbose:\n print(\"Yes: the isogeny class contains all j-invariants with min poly {}\".format(centrepols))\n return True, centrepols\n if verbose:\n print(\"No complete conjugacy class of 2-power size found in {}\".format(jC))\n return False, None\n","repo_name":"JohnCremona/ecnf-data","sub_path":"sage/Qcurves.py","file_name":"Qcurves.py","file_ext":"py","file_size_in_byte":13690,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"43"} +{"seq_id":"19533516758","text":"from selenium import webdriver\nimport unittest\n\nfrom selenium.webdriver import ActionChains\nfrom seleniumrequests import Chrome\nimport os\n# os.environ['DJANGO_SETTINGS_MODULE'] = 'SoftUniPythonWebExamProject.settings'\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.select import Select\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as ec\nfrom selenium.common.exceptions import TimeoutException, NoSuchElementException\n\n\nclass ViewTests(unittest.TestCase):\n\n def setUp(self):\n self.driver = webdriver.Chrome()\n\n def login_user_Pesho(self, driver):\n\n driver.get(\"http://localhost:8000/auth/login/\")\n login_username = driver.find_element_by_id('id_username')\n login_username.send_keys('Pesho')\n login_password = driver.find_element_by_id('id_password')\n login_password.send_keys('Brum@123')\n enter_btn = driver.find_element_by_xpath('/html/body/div[2]/div/form/button')\n enter_btn.click()\n location = driver.current_url\n self.assertEqual(location, \"http://localhost:8000/\")\n\n def login_superuser(self, driver):\n\n driver.get(\"http://localhost:8000/auth/login/\")\n login_username = driver.find_element_by_id('id_username')\n login_username.send_keys('zoey')\n login_password = driver.find_element_by_id('id_password')\n login_password.send_keys('test')\n enter_btn = driver.find_element_by_xpath('/html/body/div[2]/div/form/button')\n enter_btn.click()\n location = driver.current_url\n self.assertEqual(location, \"http://localhost:8000/\")\n\n def logout_user_Pesho(self, driver):\n\n enter_btn = driver.find_element_by_xpath('/html/body/div[1]/header/section/ul/li[2]/a')\n enter_btn.click()\n location = driver.current_url\n self.assertEqual(location, \"http://localhost:8000/\")\n\n def is_element_present(self, location, by_what, selector):\n driver = webdriver.Chrome()\n driver.get(location)\n wait = WebDriverWait(driver, 10)\n try:\n element = wait.until(ec.presence_of_element_located((by_what, selector)))\n except TimeoutException:\n return False\n return True\n\n def test_open_home_page(self):\n driver = self.driver\n driver.get(\"http://localhost:8000/\")\n self.assertIn(\"Real Estate\", driver.title)\n\n def test_create_ad_page_loads_after_login_and_click_on_btn(self):\n driver = self.driver\n self.login_user_Pesho(driver)\n create_ad_btn = driver.find_element_by_class_name('create-ad')\n create_ad_btn.click()\n location = driver.current_url\n self.assertEqual(location, \"http://localhost:8000/create_ad/\")\n\n def test_create_ad_ad_created_successfully(self):\n driver = self.driver\n self.login_user_Pesho(driver)\n driver.get(\"http://localhost:8000/create_ad/\")\n sale_rent = Select(driver.find_element_by_id('id_sale_or_rent'))\n sale_rent.select_by_value('2')\n phone_num = driver.find_element_by_id('id_phone_number')\n phone_num.send_keys('1234567890')\n price = driver.find_element_by_id('id_price')\n price.send_keys('100000')\n district = Select(driver.find_element_by_id('id_district'))\n district.select_by_value('6')\n type_premise = Select(driver.find_element_by_id('id_type_premise'))\n type_premise.select_by_value('7')\n city = Select(driver.find_element_by_id('id_city'))\n city.select_by_visible_text('София')\n floor = driver.find_element_by_id('id_floor')\n floor.send_keys('2')\n area = Select(driver.find_element_by_id('id_area'))\n area.select_by_value('9')\n construction = Select(driver.find_element_by_id('id_construction'))\n construction.select_by_value('1')\n sqr_meters = driver.find_element_by_id('id_square_meters')\n sqr_meters.send_keys('100')\n total_floor = driver.find_element_by_id('id_total_floors')\n total_floor.send_keys('6')\n num_rooms =Select(driver.find_element_by_id('id_number_rooms'))\n num_rooms.select_by_value('3')\n furniture = Select(driver.find_element_by_id('id_furniture'))\n furniture.select_by_value('1')\n elevator = Select(driver.find_element_by_id('id_elevator'))\n elevator.select_by_value('1')\n description = driver.find_element_by_id('id_description')\n description.send_keys('Ad created from automation test purposes')\n btn_save = driver.find_element_by_xpath('/html/body/div[2]/div/form/div[3]/div[1]/button')\n btn_save.click()\n location = driver.current_url\n self.assertIn('http://localhost:8000/details/', location)\n msg_ad_created = driver.find_element_by_xpath('/html/body/div[2]/section/h6')\n self.assertEqual('Обявата Ви e запазена. Когато бъде одобрена, ще бъде видима за всички.', msg_ad_created.text)\n\n def test_create_ad_button_missing_if_user_not_logged(self):\n # webdriver = Chrome()\n # response = webdriver.request('GET', 'http://localhost:8000/')\n driver = self.driver\n driver.get('http://localhost:8000/')\n\n with self.assertRaises(Exception) as ex:\n driver.find_element_by_class_name('create-ad')\n self.assertIsNotNone(ex)\n\n def test_unlogged_user_access_create_ad_raise_error(self):\n driver = self.driver\n driver.get('http://localhost:8000/create_ad/')\n location = driver.current_url\n self.assertEqual('http://localhost:8000/auth/login/?next=/create_ad/', location)\n\n def test_superuser_login_create_btn_approve_btn_available(self):\n driver = self.driver\n self.login_superuser(driver)\n create_btn = driver.find_element_by_class_name('create-ad')\n self.assertIsNotNone(create_btn)\n approve_btn = driver.find_element_by_id('id_pending_approval')\n self.assertIsNotNone(approve_btn)\n\n def test_superuser_click_approve_btn_only_pending_approval_ads_load(self):\n driver = self.driver\n wait = WebDriverWait(driver, 10)\n self.login_superuser(driver)\n approve_btn = wait.until(ec.presence_of_element_located((By.XPATH, '//input[@type=\"checkbox\"]')))\n search_btn = wait.until(ec.presence_of_element_located((By.XPATH, '//button[@type=\"submit\"]')))\n approve_btn.click()\n search_btn.click()\n ads_per_page = wait.until(ec.presence_of_all_elements_located((By.CLASS_NAME, 'card-body')))\n span_pending_approval = wait.until(ec.presence_of_all_elements_located((By.CLASS_NAME, 'pending-approval')))\n self.assertEqual(len(ads_per_page), len(span_pending_approval))\n\n def test_superuser_approve_btn_available_on_ad_detail_page(self):\n driver = self.driver\n wait = WebDriverWait(driver, 10)\n self.login_superuser(driver)\n approve_btn_check = wait.until(ec.presence_of_element_located((By.XPATH, '//input[@type=\"checkbox\"]')))\n search_btn = wait.until(ec.presence_of_element_located((By.XPATH, '//button[@type=\"submit\"]')))\n approve_btn_check.click()\n search_btn.click()\n driver.maximize_window()\n details_btn = wait.until(ec.presence_of_element_located((By.XPATH,\"//*[@class='btn-group']/a\")))\n ActionChains(driver).move_to_element(details_btn).click(details_btn).perform()\n location = driver.current_url\n ad_id = location[len('http://localhost:8000/details/'): -1]\n self.assertEqual(f'http://localhost:8000/details/{ad_id}/', location)\n details_approve_btn = wait.until(ec.presence_of_element_located((By.ID, \"details-approve-ad\")))\n ActionChains(driver).move_to_element(details_approve_btn).click(details_approve_btn).perform()\n driver.refresh()\n btn_still_present = False\n try:\n btn_still_present = wait.until(ec.presence_of_element_located((By.ID, \"details-approve-ad\")))\n except TimeoutException:\n self.assertFalse(btn_still_present)\n self.assertEqual( f'http://localhost:8000/details/{ad_id}/', driver.current_url)\n driver.get('http://localhost:8000/auth/logout/')\n driver.get('http://localhost:8000/')\n ref_num_input_field = wait.until(ec.presence_of_element_located((By.ID, 'id_reference_number')))\n ref_num_input_field.send_keys(f'{ad_id}')\n search_btn = wait.until(ec.presence_of_element_located((By.XPATH, '//button[@type=\"submit\"]')))\n search_btn.click()\n approved_ad = wait.until(ec.presence_of_element_located((By.ID, ad_id)))\n self.assertIsNotNone(approved_ad)\n\n def tearDown(self):\n self.driver.close()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"ZYKoleva/SoftUniPythonWebExamProject","sub_path":"estate_app/tests/selenium_tests.py","file_name":"selenium_tests.py","file_ext":"py","file_size_in_byte":8899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"2843231337","text":"\"\"\"\nThis script runs the URP_Server application using a development server.\n\"\"\"\n\nfrom os import environ\nfrom URP_Server import app\nfrom URP_Server.db import dbconnect\n\n\n\nif __name__ == '__main__':\n HOST = environ.get('SERVER_HOST', 'localhost')\n try:\n PORT = int(environ.get('SERVER_PORT', '5555'))\n except ValueError:\n PORT = 5555\n with app.app_context():\n dbconnect.get_conn()\n app.run(HOST, PORT, debug=True)\n","repo_name":"2290453590/-","sub_path":"URP_Server/runserver.py","file_name":"runserver.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"25780175478","text":"import requests\nimport time\nimport re\nfrom parsel import Selector\nfrom .database import create_news\n\n\n# Requisito 1\ndef fetch(url):\n time.sleep(1)\n try:\n response = requests.get(url, timeout=3)\n if response.status_code == 200:\n return response.text\n else:\n return None\n except requests.Timeout:\n return None\n\n\n# Requisito 2\ndef scrape_novidades(html_content):\n list = []\n selector = Selector(html_content)\n\n for url in selector.css(\n \".tec--list__item .tec--card__title__link::attr(href)\"\n ).getall():\n list.append(url)\n\n return list\n\n\n# Requisito 3\ndef scrape_next_page_link(html_content):\n selector = Selector(html_content)\n next_page = selector.css(\n \"a.tec--btn.tec--btn--lg.tec--btn-\" +\n \"-primary.z--mx-auto.z--mt-48::attr(href)\"\n ).get()\n\n return next_page\n\n\n# Requisito 4\ndef scrape_noticia(html_content):\n selector = Selector(html_content)\n\n url = selector.css(\n \"head meta[property='og:url']::attr(content)\"\n ).get()\n\n title = selector.css(\n \"h1#js-article-title::text\"\n ).get()\n\n date = selector.css(\n \"#js-article-date::attr(datetime)\"\n ).get()\n\n author = selector.css(\n \".z--font-bold ::text\"\n ).get()\n\n if not author:\n newswritter = None\n else:\n newswritter = author.strip()\n\n share = selector.css(\n \"article.tec--article div.tec--toolbar__item::text\"\n ).get()\n\n if not share:\n share_count = 0\n else:\n share_count = int(re.findall('[0-9]+', share)[0])\n\n comments_count = selector.css(\"#js-comments-btn::attr(data-count)\").get()\n\n synopsis = selector.css(\n \".tec--article__body > p:first-child *::text\"\n ).getall()\n\n news_synopsis = \"\".join(synopsis).strip()\n\n sources = selector.css(\n \"article.tec--article div.z--mb-16 a.tec--badge::text\"\n ).getall()\n\n news_source = [source.strip() for source in sources]\n\n categories = [item.strip() for item in selector.css(\n \"#js-categories a::text\"\n ).getall()]\n\n tecmundo_news = dict({\n \"url\": url,\n \"title\": title,\n \"timestamp\": date,\n \"writer\": newswritter,\n \"shares_count\": share_count,\n \"comments_count\": int(comments_count) if comments_count else 0,\n \"summary\": news_synopsis,\n \"sources\": news_source,\n \"categories\": categories,\n })\n\n return tecmundo_news\n\n\n# Requisito 5\ndef get_tech_news(amount):\n URL = \"https://www.tecmundo.com.br/novidades\"\n count = 0\n news_array = []\n\n # cada count representa uma noticia\n while count < amount:\n content = fetch(URL)\n news = scrape_novidades(content)\n for new in news:\n news_array.append(scrape_noticia(fetch(new)))\n count += 1\n if count % 10 == 0:\n URL = scrape_next_page_link(content)\n if count == amount:\n break\n\n create_news(news_array)\n\n return news_array\n","repo_name":"fcbresende/Web-Scrapper","sub_path":"tech_news/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":3022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"15528429547","text":"#! -*- coding:utf-8 -*-0\n\nimport keras\nfrom keras_retinanet import models\nfrom keras_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image\nfrom keras_retinanet.utils.visualization import draw_box, draw_caption\nfrom keras_retinanet.utils.colors import label_color\n \nimport matplotlib.pyplot as plt\nimport cv2\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\nimport numpy as np\nimport time\n\n\nimport tensorflow as tf\ndef get_session():\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n return tf.Session(config=config)\n \n# 设置tensorflow session 为Keras 后端\nkeras.backend.tensorflow_backend.set_session(get_session())\n\n\ndef file_is_img(img_path):\n postfix = img_path.strip().split('.')[-1]\n if postfix.lower() in ['jpg', 'jpeg', 'png', 'bmp']:\n if postfix in ['JPG', 'JPEG']:\n os.rename(img_path, img_path.replace(postfix, 'jpg'))\n print(img_path)\n return True\n else:\n return False\n\ndef get_image_list(dir_path):\n img_list = []\n if not os.path.exists(dir_path):\n return []\n for root, dirs, files in os.walk(dir_path):\n for img in files:\n img_path = os.path.join(root, img)\n if file_is_img(img_path):\n img_list.append(img_path)\n return img_list\n\ndef main():\n classes = [\"hat\", \"person\"]\n labels_to_names = {0:\"hat\", 1:\"person\"}\n #加载模型\n model_path ='./model/resnet50_csv_03.h5'\n model = models.load_model(model_path, backbone_name='resnet50')\n img_dir = './images'\n for img_path in get_image_list(img_dir): \n image = read_image_bgr(img_path) \n draw = image.copy()\n draw = cv2.cvtColor(draw, cv2.COLOR_BGR2RGB)\n\n image = preprocess_image(image)\n image, scale = resize_image(image)\n # 模型预测\n start = time.time()\n boxes, scores, labels = model.predict_on_batch(np.expand_dims(image, axis=0))\n print(\"processing time: \", time.time() - start)\n # 矫正比例\n boxes /= scale\n # 目标检测可视化展示\n for box, score, label in zip(boxes[0], scores[0], labels[0]):\n # 设置预测得分最低阈值\n if score < 0.50:\n break\n color = label_color(label)\n b = box.astype(int)\n draw_box(draw, b, color=color)\n caption = \"{} {:.3f}\".format(labels_to_names[label], score)\n draw_caption(draw, b, caption)\n #图片展示\n plt.figure(figsize=(15, 15))\n plt.axis('off')\n plt.imshow(draw)\n new_img_path = img_path.replace('images', 'images/result')\n plt.savefig(new_img_path,format='png',transparent=True,pad_inches=0,dpi=300,bbox_inches='tight')\n\nif __name__ == '__main__':\n main()\n","repo_name":"zhangw864680355/safety_helmet_detect_retinanet_keras","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2804,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"41"} +{"seq_id":"35641696552","text":"import os\nfrom itertools import combinations\n\nimport pandas as pd\n\n\ndef output_gephi(df, node_attrs, output_dir):\n \"\"\"\n Output two CSVs used by Gephi to create graphs:\n nodes.csv\n edges.csv\n\n :param pd.DataFrame df: Dataframe of input data\n :param list(str) node_attrs: List of attributes in DF to create nodes from\n :param str output_dir: Path to output directory\n \"\"\"\n # Create nodes\n nodes = []\n for attr in node_attrs:\n nodes.extend(map(lambda x: (x, attr), df[attr].tolist()))\n nodes = pd.DataFrame.from_records(nodes, columns=('Label', 'Type'))\n\n # Create edges\n edges = set()\n for row in df.iterrows():\n i, row = row\n for j, k in combinations(node_attrs, 2):\n edges.add((int(nodes[nodes.Label == row[j]].index[0]), int(nodes[nodes.Label == row[k]].index[0])))\n edges = pd.DataFrame.from_records(list(edges), columns=('Source', 'Target'))\n\n # Output\n nodes.to_csv(os.path.join(output_dir, 'nodes.csv'), index=True, index_label='Id')\n edges.to_csv(os.path.join(output_dir, 'edges.csv'), index=False)\n","repo_name":"jvivian/rnaseq-lib","sub_path":"src/rnaseq_lib/graphs/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"26374315686","text":"import os\nimport yaml\nimport requests\nfrom uuid import uuid4\nfrom functools import wraps\nfrom datetime import datetime, timedelta\n\nappdir = os.path.dirname(os.path.realpath(__file__)) # rp, realpath\n\n_asana_cache = {}\ndef _cache(cache_id):\n def decorator(function):\n @wraps(function)\n def wrapper(*args, **kwargs):\n if cache_id in _asana_cache:\n return _asana_cache[cache_id]\n return function(*args, **kwargs)\n return wrapper\n return decorator\n\nclass AsanaAPI():\n def __init__(self, token) -> None:\n self.headers = {\n \"Authorization\": f\"Bearer {token}\",\n \"content-type\": \"application/json\",\n }\n\n self._state_cache = {} \n\n \n\n @_cache(\"tasks_summary\")\n def get_tasks_summary(self, task_params):\n task_params['workspace'] = self.get_workspace_by_name(task_params['workspace'])['gid']\n task_params['assignee'] = self.get_user_id_by_name(task_params['assignee'])['gid']\n task_params['completed_since'] = datetime.now().strftime(r\"%Y-%m-%d\")\n tasks = requests.get(\"https://app.asana.com/api/1.0/tasks\", headers=self.headers,\n params=task_params\n ).json()\n return tasks['data']\n\n @_cache(\"tasks\")\n def get_tasks(self, task_params):\n tasks_summary = self.get_tasks_summary(task_params)\n tasks = []\n for task_summary in tasks_summary:\n tasks.append(\n requests.get(f\"https://app.asana.com/api/1.0/tasks/{task_summary['gid']}\", headers=self.headers).json()['data']\n )\n return tasks\n\n @_cache(\"workspaces\")\n def get_workspaces(self):\n workspaces = requests.get(\"https://app.asana.com/api/1.0/workspaces\", headers=self.headers).json()\n return workspaces['data']\n\n def get_workspace_by_name(self, workspace_name):\n workspaces = self.get_workspaces()\n for workspace in workspaces:\n if workspace['name'] == workspace_name:\n return workspace\n\n @_cache(\"users\")\n def get_users(self):\n users = requests.get(\"https://app.asana.com/api/1.0/users\", headers=self.headers).json()\n return users['data']\n\n def get_user_id_by_name(self, user_name):\n users = self.get_users()\n for user in users:\n if user['name'] == user_name:\n return user\n\n\n \n\n # def add_task(self,)\nif __name__ == \"__main__\":\n # Testing\n with open(os.path.join(appdir, 'config.yaml'), 'r') as f:\n config = yaml.safe_load(f.read())\n print(AsanaAPI(config['asana'][0]['personal_access_token']).get_workspaces())\n\n # for task in AsanaAPI(config['asana'][0]['personal_access_token']).get_tasks(config['asana'][0]['task_params']):\n # print(task)","repo_name":"Nixellion/TodoistToTxt","sub_path":"asana_api.py","file_name":"asana_api.py","file_ext":"py","file_size_in_byte":2783,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"41"} +{"seq_id":"10054744733","text":"from sklearn.decomposition import PCA\nfrom sklearn.datasets import fetch_openml\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\n\nimport numpy as np\nimport tensorflow_quantum as tfq\nimport tensorflow as tf\n\nclass MNISTData:\n def __init__(self, seed):\n mnist = fetch_openml('mnist_784', version=1, cache=True)\n self.data = mnist['data']\n self.labels = np.array(mnist['target'], dtype=np.int8)\n self.seed = seed\n \n def _get_binary_data_encoding(self):\n labels_zero = self.labels[self.labels==0] + 1\n labels_one = self.labels[self.labels==1] - 2\n binary_labels = np.hstack((labels_zero, labels_one))\n digits_zero = self.data[self.labels==0]\n digits_one = self.data[self.labels==1]\n binary_digits = np.vstack((digits_zero, digits_one))\n \n pca = PCA(n_components=8)\n sc = StandardScaler()\n binary_digits = sc.fit_transform(binary_digits)\n data = pca.fit_transform(binary_digits)\n data = np.expand_dims(data, axis=2)\n data = (data-np.min(data))/(np.max(data)-np.min(data))\n data = np.concatenate((np.cos(np.pi*0.5*data), np.sin(np.pi*0.5*data)), axis=2)\n \n qubits = cirq.GridQubit.rect(1,8)\n _data = []\n for idx in range(data.shape[0]):\n datapoint = data[idx]\n _circuit = cirq.Circuit()\n for i in range(8):\n _circuit.append(encode_classical_datapoint(np.array(datapoint[i][::-1]), [qubits[i]]))\n _data.append(_circuit)\n return _data, binary_labels\n \n # returns data in qubit encoding\n def get_binary_test_train_split(self):\n data, labels = self._get_binary_data_encoding()\n X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size=0.1, random_state=self.seed)\n return tfq.convert_to_tensor(X_train), tfq.convert_to_tensor(X_test), y_train, y_test\n \n # returns tensorflow objects of raw mnist data\n # returns a one hot representation (0,1) for three and (1,0) for five\n def get_three_five_test_train_split(self, one_hot=False):\n digits = np.vstack((self.data[self.labels==3], self.data[self.labels==5]))\n sc = StandardScaler()\n digits = sc.fit_transform(digits)\n \n if one_hot:\n labels_three = self.labels[self.labels==3] - 3\n labels_five = self.labels[self.labels==5] - 4\n labels = np.hstack((labels_three, labels_five))\n \n ones = np.eye(2)\n labels = ones[labels]\n else:\n labels_three = self.labels[self.labels==3] - 4\n labels_five = self.labels[self.labels==5] - 4\n labels = np.hstack((labels_three, labels_five))\n \n return train_test_split(digits, labels, test_size=0.1, random_state=self.seed)","repo_name":"SatyaKuppam/quantum-machine-learning","sub_path":"classification/mnist.py","file_name":"mnist.py","file_ext":"py","file_size_in_byte":2895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"35795403159","text":"from sqlalchemy import Column, Integer, String\nfrom app.config.database import Base\n\nclass User(Base):\n __tablename__ = \"users\"\n user_id = Column(Integer, primary_key=True, index=True)\n username = Column(String, unique=True, index=True)\n password = Column(String)\n name = Column(String)\n position = Column(String)\n role = Column(Integer)\n weight = Column(Integer)\n def as_dict_user(self):\n return {\n \"user_id\": self.user_id,\n \"username\": self.username,\n \"name\": self.name,\n \"position\": self.position,\n \"role\": self.role,\n \"weight\": self.weight\n }\n def as_dict_default_user(self):\n return {\n \"user_id\": self.user_id,\n \"username\": self.username,\n \"name\": self.name,\n \"position\": self.position,\n \"role\": self.role,\n \"weight\": self.weight\n }","repo_name":"yudhaislamisulistya/be-the-best-employees","sub_path":"app/models/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"22451609835","text":"def read():\n return int(input())\n\ndef reads():\n return str(input())\n\ndef readline():\n return list(map(int,input().split()))\n\ndef lower_bound(arr,l,r,val):\n while(l<r):\n mid=l+r>>1\n if(arr[mid]>=val): r=mid\n else: l=mid+1\n return l\n\ndef solve():\n n,m=readline()\n arr=readline()\n arr.sort(reverse=True)\n pre=[0]*(n+1)\n for i,v in enumerate(arr):\n if i>0: pre[i]=v+pre[i-1]\n else: pre[i]=v\n pre[n]=int(1e15)\n for i in range(m):\n q=read()\n res=lower_bound(pre,0,n,q)\n if(res==n): print(-1)\n else: print(res+1)\n\nif __name__ == \"__main__\":\n T=read()\n for i in range(T):\n solve()","repo_name":"HEltim7/cpcode","sub_path":"CF/Round/790/E_Eating_Queries.py","file_name":"E_Eating_Queries.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"13969343026","text":"import base64\nfrom io import BytesIO\n\nfrom retry.api import retry_call\n\nfrom config import config\nfrom tests.functional.preview_and_dev.consts import correct_letter\nfrom tests.postman import (\n get_notification_by_id_via_api,\n send_precompiled_letter_via_api,\n)\nfrom tests.test_utils import NotificationStatuses, recordtime\n\n\n@recordtime\ndef test_send_precompiled_letter_notification_via_api(client_test_key):\n reference = config[\"name\"].replace(\" \", \"_\") + \"_delivered\"\n\n notification_id = send_precompiled_letter_via_api(\n reference,\n client_test_key,\n BytesIO(base64.b64decode(correct_letter)),\n )\n\n notification = retry_call(\n get_notification_by_id_via_api,\n fargs=[\n client_test_key,\n notification_id,\n NotificationStatuses.RECEIVED,\n ],\n tries=config[\"letter_retry_times\"],\n delay=config[\"notification_retry_interval\"],\n )\n\n assert reference == notification[\"reference\"]\n","repo_name":"alphagov/notifications-functional-tests","sub_path":"tests/functional/staging_and_prod/notify_api/test_notify_api_letter.py","file_name":"test_notify_api_letter.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"41"} +{"seq_id":"15527740906","text":"n,a,o,r=[],[],[],[]\nt=input().split()\nwhile t[0]!=\"-1\":\n t[1],t[2],t[3]=int(t[1]),int(t[2]),int(t[3])\n t[1:]=sorted(t[1:])\n name,x,y,z=t\n if x+y<=z:\n n.append(name)\n elif x**2+y**2>z**2:\n a.append(name)\n elif x**2+y**2==z**2:\n r.append(name)\n elif x**2+y**2<z**2:\n o.append(name)\n t=input().split()\nn,a,o,r=sorted(n),sorted(a),sorted(o),sorted(r)\nnn=\"Not Triangle: \"\naa=\"Acute Angle: \"\noo=\"Obtuse Angle: \"\nrr=\"Right Angle: \"\n\nif len(n)==0:\n nn+=\"None\"\nelse:\n for i in n:\n nn+=i+\",\"\n nn=nn[:len(nn)-1]\nif len(a)==0:\n aa+=\"None\"\nelse:\n for i in a:\n aa+=i+\",\"\n aa=aa[:len(aa)-1]\nif len(o)==0:\n oo+=\"None\"\nelse:\n for i in o:\n oo+=i+\",\"\n oo=oo[:len(oo)-1]\nif len(r)==0:\n rr+=\"None\"\nelse:\n for i in r:\n rr+=i+\",\"\n rr=rr[:len(rr)-1]\n\n \nprint(nn)\nprint(aa)\nprint(oo)\nprint(rr)\n","repo_name":"tiffanylin0419/GenEdu-5006","sub_path":"1148.py","file_name":"1148.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"15648589068","text":"######################################\n# moieties_com_distn.CNT.py Revision 1.1 [07-21-2020]\n#\n# Changelog:\n# V1.1 [07-21-2020]\n# Added back the continuous check without zeroing it.\n# V1.0 [07-20-2020]\n# Initial commit.\n######################################\n\n# Generate COM distribution on CNTs.\n\nimport numpy as np\nimport os\n\nheader = 23\nfooter = 36\nlx_line = 13\nly_line = 14\nlz_line = 15\n\n# =============================================================================\nsurface = os.getcwd().split('/')[5].split('_')[0]\n\nr_list = {\n \"CNT10a\": 10.1555,\n \"CNT10z\": 10.163,\n \"CNT15a\": 14.895,\n \"CNT15z\": 14.854,\n \"CNT20a\": 19.6345,\n \"CNT20z\": 19.9355,\n}\nr = r_list[surface]\n\nelectrode_list = {\n \"CNT10a\": 25,\n \"CNT10z\": 25,\n \"CNT15a\": 30,\n \"CNT15z\": 30,\n \"CNT20a\": 35,\n \"CNT20z\": 35,\n}\nref_x = electrode_list[surface]\nref_y = electrode_list[surface]\n# =============================================================================\n\nif surface[-1] == 'z':\n x_single = 1.418 * 2 * np.sqrt(3)\n y_single = 1.418 * 6\nelif surface[-1] == 'a':\n x_single = 1.418 * 6\n y_single = 1.418 * 2 * np.sqrt(3)\nelse: exit()\n\namine_x = np.zeros((10, 500001))\namine_y = np.zeros((10, 500001))\nring_x = np.zeros((10, 500001))\nring_y = np.zeros((10, 500001))\nquinone_x = np.zeros((10, 500001))\nquinone_y = np.zeros((10, 500001))\n\nfor j in range(10):\n print(j)\n filename = str(j) + \"/data.out\"\n temp_amine_x, temp_amine_y, temp_amine_z, \\\n temp_ring_x, temp_ring_y, temp_ring_z, \\\n temp_quinone_x, temp_quinone_y, temp_quinone_z = \\\n np.genfromtxt(filename, skip_header=header, skip_footer=footer,\n usecols=(7,8,9,10,11,12,13,14,15), unpack=True)\n \n with open(str(j) + '/after_nvt.data', \"r\") as f:\n for i, line in enumerate(f):\n if i == lx_line:\n lx = np.float(line.split(' ')[1]) - np.float(line.split(' ')[0])\n if i == ly_line:\n ly = np.float(line.split(' ')[1]) - np.float(line.split(' ')[0])\n if i == lz_line:\n lz = np.float(line.split(' ')[1]) - np.float(line.split(' ')[0])\n \n wrapped_amine_x = temp_amine_x%lx\n wrapped_amine_y = temp_amine_y%ly\n wrapped_ring_x = temp_ring_x%lx\n wrapped_ring_y = temp_ring_y%ly\n wrapped_quinone_x = temp_quinone_x%lx\n wrapped_quinone_y = temp_quinone_y%ly \n # Cylindrical coordiante changes.\n cutoff = np.pi/2\n amine_theta = np.arctan2((wrapped_amine_y - ref_y),(wrapped_amine_x - ref_x))\n ring_theta = np.arctan2((wrapped_ring_y - ref_y),(wrapped_ring_x - ref_x))\n quinone_theta = np.arctan2((wrapped_quinone_y - ref_y),(wrapped_quinone_x - ref_x))\n for i in range(amine_theta.size):\n if np.abs(amine_theta[i] - amine_theta[i-1]) > cutoff:\n if amine_theta[i] - amine_theta[i-1] > 0:\n amine_theta[i:] = amine_theta[i:] - 2*np.pi\n ring_theta[i:] = ring_theta[i:] - 2*np.pi\n quinone_theta[i:] = quinone_theta[i:] - 2*np.pi\n else:\n amine_theta[i:] = amine_theta[i:] + 2*np.pi\n ring_theta[i:] = ring_theta[i:] + 2*np.pi\n quinone_theta[i:] = quinone_theta[i:] + 2*np.pi\n # amine_theta = amine_theta - amine_theta[0]\n # ring_theta = ring_theta - ring_theta[0]\n # quinone_theta = quinone_theta - quinone_theta[0]\n # Wrap the simulation box.\n \n amine_x[j] = (r*amine_theta) % x_single\n amine_y[j] = temp_amine_z % y_single\n ring_x[j] = (r*ring_theta) % x_single\n ring_y[j] = temp_ring_z % y_single\n quinone_x[j] = (r*quinone_theta) % x_single\n quinone_y[j] = temp_quinone_z % y_single\n\nimport matplotlib.pyplot as plt\nplt.style.use('science')\n\nfor k, item in enumerate(['amine','ring','quinone']):\n\n if k == 0:\n x = amine_x; y = amine_y;\n elif k == 1:\n x = ring_x; y = ring_y;\n else:\n x = quinone_x; y = quinone_y;\n\n if surface[-1] == 'z':\n fig, ax = plt.subplots(figsize=(2,3))\n elif surface[-1] == 'a':\n fig, ax = plt.subplots(figsize=(3,2))\n else: exit()\n\n cm = plt.cm.get_cmap('Blues')\n plt.axis('tight')\n plt.axes().set_aspect('equal')\n plt.axis([0, x_single, 0, y_single], 'scaled')\n plt.xlim(0, x_single)\n plt.ylim(0, y_single)\n plt.ylabel('Axial($\\parallel$)/$\\mathrm{\\AA}$')\n plt.xlabel('Perpendicular($\\perp$)/$\\mathrm{\\AA}$')\n hist = plt.hist2d(x.flatten(), y.flatten(),\n bins=(int(50*x_single),int(50*y_single)), cmap=cm)\n cbar = plt.colorbar()\n plt.clim(0,150)\n cbar.set_ticks([0,50,100,150])\n cbar.ax.set_title('Counts\\n Per Pixel')\n #cbar.ax.set_yticklabels(['Low\\nDensity', 'High\\nDensity'])\n\n\n if surface[-1] == 'z':\n plt.xticks([0,2,4])\n plt.yticks([0,2,4,6,8])\n for i in [0,3,6]:\n for j in range(3):\n circle = plt.Circle((x_single/2*j, y_single/6*i), radius=0.5, fill=False,\n edgecolor='grey', linestyle='--', linewidth=1)\n plt.gca().add_patch(circle)\n for i in [2,5]:\n for j in range(3):\n circle = plt.Circle((x_single/2*j, y_single/6*i), radius=0.5, fill=False,\n edgecolor='grey', linestyle='--', linewidth=1)\n plt.gca().add_patch(circle)\n for i in [0.5,3.5]:\n for j in [0.5,1.5]:\n circle = plt.Circle((x_single/2*j, y_single/6*i), radius=0.5, fill=False,\n edgecolor='grey', linestyle='--', linewidth=1)\n plt.gca().add_patch(circle)\n for i in [1.5,4.5]:\n for j in [0.5,1.5]:\n circle = plt.Circle((x_single/2*j, y_single/6*i), radius=0.5, fill=False,\n edgecolor='grey', linestyle='--', linewidth=1)\n plt.gca().add_patch(circle)\n \n temp_x = np.array([0,1/4,1/2,3/4,1])\n temp_y = np.array([0,1/12,0,1/12,0])\n plt.plot(temp_x*x_single, temp_y*y_single, 'k-.', lw=1)\n \n temp_x = np.array([0,1/4,1/2,3/4,1])\n temp_y = np.array([1/3,1/4,1/3,1/4,1/3])\n plt.plot(temp_x*x_single, temp_y*y_single, 'k-.', lw=1)\n \n temp_x = np.array([0,1/4,1/2,3/4,1])\n temp_y = np.array([1/2,7/12,1/2,7/12,1/2])\n plt.plot(temp_x*x_single, temp_y*y_single, 'k-.', lw=1)\n \n temp_x = np.array([0,1/4,1/2,3/4,1])\n temp_y = np.array([5/6,3/4,5/6,3/4,5/6])\n plt.plot(temp_x*x_single, temp_y*y_single, 'k-.', lw=1)\n \n temp_x = np.array([1/4,1/4,1/2,1/2,1/4,1/4])\n temp_y = np.array([1/12,1/4,1/3,1/2,7/12,3/4])\n plt.plot(temp_x*x_single, temp_y*y_single, 'k-.', lw=1)\n \n temp_x = np.array([3/4,3/4,1/2,1/2,3/4,3/4])\n temp_y = np.array([1/12,1/4,1/3,1/2,7/12,3/4])\n plt.plot(temp_x*x_single, temp_y*y_single, 'k-.', lw=1)\n \n plt.plot([x_single/2, x_single/2], [0, y_single], 'k--')\n plt.plot([0, x_single], [y_single/2, y_single/2], 'k--')\n \n elif surface[-1] == 'a':\n plt.xticks([0,2,4,6,8])\n plt.yticks([0,2,4])\n for i in [0,1,2]:\n for j in [0,1,3,4,6]:\n circle = plt.Circle((x_single/6*j, y_single/2*i), radius=0.5, fill=False,\n edgecolor='grey', linestyle='--', linewidth=1)\n plt.gca().add_patch(circle)\n for i in [0.5,1.5]:\n for j in [1.5,2.5,4.5,5.5]:\n circle = plt.Circle((x_single/6*j, y_single/2*i), radius=0.5, fill=False,\n edgecolor='grey', linestyle='--', linewidth=1)\n plt.gca().add_patch(circle)\n \n temp_x = np.array([0,1/6,1/4,5/12,1/2,2/3,3/4,11/12,1])\n temp_y = np.array([0,0,1/4,1/4,0,0,1/4,1/4,0])\n plt.plot(temp_x*x_single, temp_y*y_single, 'k-.', lw=1)\n\n temp_x = np.array([0,1/6,1/4,5/12,1/2,2/3,3/4,11/12,1])\n temp_y = np.array([1/2,1/2,1/4,1/4,1/2,1/2,1/4,1/4,1/2])\n plt.plot(temp_x*x_single, temp_y*y_single, 'k-.', lw=1) \n\n temp_x = np.array([0,1/6,1/4,5/12,1/2,2/3,3/4,11/12,1])\n temp_y = np.array([1/2,1/2,3/4,3/4,1/2,1/2,3/4,3/4,1/2])\n plt.plot(temp_x*x_single, temp_y*y_single, 'k-.', lw=1) \n\n temp_x = np.array([0,1/6,1/4,5/12,1/2,2/3,3/4,11/12,1])\n temp_y = np.array([1,1,3/4,3/4,1,1,3/4,3/4,1])\n plt.plot(temp_x*x_single, temp_y*y_single, 'k-.', lw=1) \n \n plt.plot([x_single/2, x_single/2], [0, y_single], 'k--')\n plt.plot([0, x_single], [y_single/2, y_single/2], 'k--')\n \n else: exit()\n\n plt.savefig('3_' + item + '_com_distn.png', dpi=300, bbox_inches='tight')\n plt.close(\"all\")","repo_name":"dubayresearchgroup/DopaDiff","sub_path":"analysis/plotting/moieties_com_distn.CNT.py","file_name":"moieties_com_distn.CNT.py","file_ext":"py","file_size_in_byte":8825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"13421998148","text":"# https://leetcode.com/discuss/interview-question/1789737/amazon-OA\n# sum(power) - min(armor, max(power)) + 1a\nimport heapq\nfrom typing import List\n\n\nclass Solution:\n # TLE...\n def smallestDistancePair(self, nums: List[int], k: int) -> int:\n nums.sort()\n visited = set([(i - 1, i) for i in range(1, len(nums))])\n h = [(abs(nums[i] - nums[i - 1]), i - 1, i) for i in range(1, len(nums))]\n heapq.heapify(h)\n\n # print(nums)\n i = 0\n while h:\n e = heapq.heappop(h)\n visited.add((e[1], e[2]))\n i += 1\n if i == k:\n return e[0]\n if e[1] - 1 >= 0 and (e[1] - 1, e[2]) not in visited:\n heapq.heappush(h, (abs(nums[e[1] - 1] - nums[e[1]]) + e[0], e[1] - 1, e[2]))\n\n return -1\n\n\n\n","repo_name":"SWYZZWH/leetcode","sub_path":"python/amazon/findMinHealth/findMinHealth.py","file_name":"findMinHealth.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"25734232973","text":"import numpy as np \nimport matplotlib\nimport matplotlib.pyplot as plt \n\n#A=1,B=2,C=3,D=4,E=5\n#\n#\n\n#state = [1,2,3,4,5]\n#action = [-1,1]\ndef actionrand():\n\tactionrandn=np.random.randint(0,2)\n\tif actionrandn == 0:\n\t\tactionrandn = -1\n\treturn actionrandn\n\ndef play(value, Reward, value_track, alpha):\n\n\tstate = 2\n\twhile True:\n\t\taction = actionrand()\n\n\t\told_state = state\n\t\tstate += action\n\n\t\treward = 0\n\t\tif state == 6:\n\t\t\treward = 1\n\t\tReward.append(reward)\n\t\tvalue[old_state] = value[old_state] + alpha * ( reward + value[state] - value[old_state])\n\t\tvalue_track[old_state].append(value[old_state])\n\t\tif state == 0 or state == 6:\n\t\t\treturn value, Reward, value_track\n\n\n\n\n\n\ndef begin():\n\talpha = 0.1\n\tvalue_track=[[]for i in range(7)]\n\tvalue=0.5*np.ones(7)\n\tvalue[0] = 0\n\tvalue[6] = 0\n\tReward = []\n\tfor i in range(500000):\n\t\tvalue, Reward, value_track = play(value, Reward, value_track, alpha)\n\treturn value\n\nif __name__=='__main__':\n\tvalue=begin()\n\tprint(value)\n\tplt.plot(value)\n\tplt.show()\n\n\n\n","repo_name":"Feiyu-Yao/rlcode_python","sub_path":"rlcode_python/walk.py","file_name":"walk.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"16027984064","text":"#! usr/bin/env python3\n\ndef loanCalculator():\n\n term = 72\n month = 1\n interest_rate = .0545\n principal = 12000\n principal_payment = round(principal/term, 2)\n\n eachMonth = {}\n monthlyPayments = []\n\n while month <= term:\n\n interest = round(interest_rate * principal, 2)\n monthly_interest_payment = round(interest/12, 2)\n monthly_payment = round(monthly_interest_payment + principal_payment, 2)\n\n eachMonth['month'] = month\n eachMonth['monthly_payment'] = monthly_payment\n eachMonth['principal'] = principal\n\n monthlyPayments.append(eachMonth)\n thisMonth = monthlyPayments[month - 1]\n\n month = month + 1\n principal = round(principal - principal_payment, 2)\n\n print('Month:' + str(month), principal, interest, monthly_interest_payment, principal_payment, monthly_payment)\n print(thisMonth)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"ryan-hoffman/loan-calculator","sub_path":"env/loanCalcTest.py","file_name":"loanCalcTest.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"4815178878","text":"from random import randint\nfrom turtle import Turtle, Screen\n\nis_race_on = False\ncolors = [\"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"purple\"]\nscreen = Screen()\nwidth = 500\nscreen.setup(width=width, height=400)\nspace = -120\nuser_bet = screen.textinput('Make your bet', 'Which turtle will win the race, Enter a color')\nall_turtles = []\nfor i in range(6):\n new_turtle = Turtle(\"turtle\")\n new_turtle.color(colors[i])\n new_turtle.penup()\n new_turtle.goto(-1 * (width / 2 - 15), (space))\n space += 40\n all_turtles.append(new_turtle)\n\nif user_bet:\n is_race_on = True\nwhile is_race_on:\n\n for t in all_turtles:\n if t.xcor() > 230:\n is_race_on = False\n if t.fillcolor() == user_bet:\n print(f\"You have won! The {t.fillcolor()} turtle is the winner\")\n else:\n print(f\"You have lost! The {t.fillcolor()} turtle is the winner\")\n\n distance = randint(0, 10)\n t.forward(distance)\n\nscreen.exitonclick()\n","repo_name":"darimachine/Turtle_race_ez","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"72429412922","text":"from itertools import product\nimport numpy as np\n\nfrom ..adapters import Adapter\nfrom ..config import ListField, BoolField, NumberField, StringField\nfrom ..postprocessor import NMS\nfrom ..representation import (\n DetectionPrediction,\n FacialLandmarksPrediction,\n ContainerPrediction,\n AttributeDetectionPrediction\n)\n\n\nclass RetinaFaceAdapter(Adapter):\n __provider__ = 'retinaface'\n\n @classmethod\n def parameters(cls):\n params = super().parameters()\n params.update(\n {\n 'bboxes_outputs': ListField(description=\"Names for output layers with face detection boxes\"),\n 'scores_outputs': ListField(description=\"Names for output layers with face detection score\"),\n 'landmarks_outputs': ListField(\n optional=True, description=\"Names for output layers with predicted facial landmarks\"\n ),\n 'type_scores_outputs': ListField(\n optional=True, description=\"Names for output layers with attributes detection score\"\n ),\n 'include_boundaries': BoolField(\n optional=True, default=False, description=\"Allows include boundaries for NMS\"\n ),\n 'keep_top_k': NumberField(\n min_value=1, optional=True, description=\"Maximal number of boxes which should be kept\",\n value_type=int\n ),\n 'nms_threshold': NumberField(\n min_value=0, optional=True, default=0.5, description=\"Overlap threshold for NMS\"\n )\n }\n )\n return params\n\n def configure(self):\n self.bboxes_output = self.get_value_from_config('bboxes_outputs')\n self.scores_output = self.get_value_from_config('scores_outputs')\n self.landmarks_output = self.get_value_from_config('landmarks_outputs') or []\n self.type_scores_output = self.get_value_from_config('type_scores_outputs') or []\n self.include_boundaries = self.get_value_from_config('include_boundaries')\n self.keep_top_k = self.get_value_from_config('keep_top_k')\n self.nms_threshold = self.get_value_from_config('nms_threshold')\n _ratio = (1.,)\n self.anchor_cfg = {\n 32: {'SCALES': (32, 16), 'BASE_SIZE': 16, 'RATIOS': _ratio},\n 16: {'SCALES': (8, 4), 'BASE_SIZE': 16, 'RATIOS': _ratio},\n 8: {'SCALES': (2, 1), 'BASE_SIZE': 16, 'RATIOS': _ratio}\n }\n self._features_stride_fpn = [32, 16, 8]\n self._anchors_fpn = dict(zip(self._features_stride_fpn, self.generate_anchors_fpn(cfg=self.anchor_cfg)))\n self._num_anchors = dict(zip(\n self._features_stride_fpn, [anchors.shape[0] for anchors in self._anchors_fpn.values()]\n ))\n if self.type_scores_output:\n self.landmark_std = 0.2\n else:\n self.landmark_std = 1.0\n self._anchor_plane_cache = {}\n self.outputs_verified = False\n\n def select_output_blob(self, outputs):\n def generate_out_names(list_names, outputs):\n return [self.check_output_name(out, outputs) for out in list_names]\n self.bboxes_output = generate_out_names(self.bboxes_output, outputs)\n self.scores_output = generate_out_names(self.scores_output, outputs)\n self.landmarks_output = generate_out_names(self.landmarks_output, outputs)\n self.type_scores_output = generate_out_names(self.type_scores_output, outputs)\n self.outputs_verified = True\n\n def process(self, raw, identifiers, frame_meta):\n raw_predictions = self._extract_predictions(raw, frame_meta)\n if not self.outputs_verified:\n self.select_output_blob(raw_predictions)\n raw_predictions = self._repack_data_according_layout(raw_predictions, frame_meta[0])\n results = []\n for batch_id, (identifier, meta) in enumerate(zip(identifiers, frame_meta)):\n proposals_list = []\n scores_list = []\n landmarks_list = []\n mask_scores_list = []\n for _idx, s in enumerate(self._features_stride_fpn):\n anchor_num = self._num_anchors[s]\n scores = self._get_scores(raw_predictions[self.scores_output[_idx]][batch_id], anchor_num)\n bbox_deltas = raw_predictions[self.bboxes_output[_idx]][batch_id]\n height, width = bbox_deltas.shape[1], bbox_deltas.shape[2]\n anchors_fpn = self._anchors_fpn[s]\n if (height, width) in self._anchor_plane_cache and s in self._anchor_plane_cache[(height, width)]:\n anchors = self._anchor_plane_cache[(height, width)][s]\n else:\n anchors = self.anchors_plane(height, width, int(s), anchors_fpn)\n anchors = anchors.reshape((height * width * anchor_num, 4))\n if (height, width) not in self._anchor_plane_cache:\n self._anchor_plane_cache[(height, width)] = {}\n self._anchor_plane_cache[(height, width)][s] = anchors\n proposals = self._get_proposals(bbox_deltas, anchor_num, anchors)\n x_mins, y_mins, x_maxs, y_maxs = proposals.T\n keep = NMS.nms(x_mins, y_mins, x_maxs, y_maxs, scores, self.nms_threshold,\n self.include_boundaries, self.keep_top_k)\n proposals_list.extend(proposals[keep])\n scores_list.extend(scores[keep])\n if self.type_scores_output:\n mask_scores_list.extend(self._get_mask_scores(\n raw_predictions[self.type_scores_output[_idx]][batch_id], anchor_num)[keep])\n if self.landmarks_output:\n landmarks = self._get_landmarks(raw_predictions[self.landmarks_output[_idx]][batch_id],\n anchor_num, anchors)[keep, :]\n landmarks_list.extend(landmarks)\n scores = np.reshape(scores_list, -1)\n mask_scores = np.reshape(mask_scores_list, -1)\n labels = np.full_like(scores, 1, dtype=int)\n x_mins, y_mins, x_maxs, y_maxs = np.array(proposals_list).T # pylint: disable=E0633\n x_scale, y_scale = self.get_scale(meta)\n detection_representation = DetectionPrediction(\n identifier, labels, scores, x_mins / x_scale, y_mins / y_scale, x_maxs / x_scale, y_maxs / y_scale\n )\n representations = {'face_detection': detection_representation}\n if self.type_scores_output:\n representations['mask_detection'] = AttributeDetectionPrediction(\n identifier, labels, scores, mask_scores, x_mins / x_scale,\n y_mins / y_scale, x_maxs / x_scale, y_maxs / y_scale\n )\n if self.landmarks_output:\n landmarks_x_coords = np.array(landmarks_list)[:, :, ::2].reshape(len(landmarks_list), -1) / x_scale\n landmarks_y_coords = np.array(landmarks_list)[:, :, 1::2].reshape(len(landmarks_list), -1) / y_scale\n representations['landmarks_regression'] = FacialLandmarksPrediction(identifier, landmarks_x_coords,\n landmarks_y_coords)\n results.append(\n ContainerPrediction(representations) if len(representations) > 1 else detection_representation\n )\n return results\n\n def _get_proposals(self, bbox_deltas, anchor_num, anchors):\n bbox_deltas = bbox_deltas.transpose((1, 2, 0))\n bbox_pred_len = bbox_deltas.shape[2] // anchor_num\n bbox_deltas = bbox_deltas.reshape((-1, bbox_pred_len))\n proposals = self.bbox_pred(anchors, bbox_deltas)\n return proposals\n\n @staticmethod\n def _get_scores(scores, anchor_num):\n scores = scores[anchor_num:, :, :]\n scores = scores.transpose((1, 2, 0)).reshape(-1)\n return scores\n\n @staticmethod\n def _get_mask_scores(type_scores, anchor_num):\n mask_scores = type_scores[anchor_num * 2:, :, :]\n mask_scores = mask_scores.transpose((1, 2, 0)).reshape(-1)\n return mask_scores\n\n def _get_landmarks(self, landmark_deltas, anchor_num, anchors):\n landmark_pred_len = landmark_deltas.shape[0] // anchor_num\n landmark_deltas = landmark_deltas.transpose((1, 2, 0)).reshape((-1, 5, landmark_pred_len // 5))\n landmark_deltas *= self.landmark_std\n landmarks = self.landmark_pred(anchors, landmark_deltas)\n return landmarks\n\n @staticmethod\n def bbox_pred(boxes, box_deltas):\n if boxes.shape[0] == 0:\n return np.zeros((0, box_deltas.shape[1]))\n\n boxes = boxes.astype(float, copy=False)\n widths = boxes[:, 2] - boxes[:, 0] + 1.0\n heights = boxes[:, 3] - boxes[:, 1] + 1.0\n ctr_x = boxes[:, 0] + 0.5 * (widths - 1.0)\n ctr_y = boxes[:, 1] + 0.5 * (heights - 1.0)\n dx = box_deltas[:, 0:1]\n dy = box_deltas[:, 1:2]\n dw = box_deltas[:, 2:3]\n dh = box_deltas[:, 3:4]\n pred_ctr_x = dx * widths[:, np.newaxis] + ctr_x[:, np.newaxis]\n pred_ctr_y = dy * heights[:, np.newaxis] + ctr_y[:, np.newaxis]\n pred_w = np.exp(dw) * widths[:, np.newaxis]\n pred_h = np.exp(dh) * heights[:, np.newaxis]\n pred_boxes = np.zeros(box_deltas.shape)\n pred_boxes[:, 0:1] = pred_ctr_x - 0.5 * (pred_w - 1.0)\n pred_boxes[:, 1:2] = pred_ctr_y - 0.5 * (pred_h - 1.0)\n pred_boxes[:, 2:3] = pred_ctr_x + 0.5 * (pred_w - 1.0)\n pred_boxes[:, 3:4] = pred_ctr_y + 0.5 * (pred_h - 1.0)\n\n if box_deltas.shape[1] > 4:\n pred_boxes[:, 4:] = box_deltas[:, 4:]\n\n return pred_boxes\n\n @staticmethod\n def anchors_plane(height, width, stride, base_anchors):\n num_anchors = base_anchors.shape[0]\n all_anchors = np.zeros((height, width, num_anchors, 4))\n for iw in range(width):\n sw = iw * stride\n for ih in range(height):\n sh = ih * stride\n for k in range(num_anchors):\n all_anchors[ih, iw, k, 0] = base_anchors[k, 0] + sw\n all_anchors[ih, iw, k, 1] = base_anchors[k, 1] + sh\n all_anchors[ih, iw, k, 2] = base_anchors[k, 2] + sw\n all_anchors[ih, iw, k, 3] = base_anchors[k, 3] + sh\n\n return all_anchors\n\n @staticmethod\n def generate_anchors_fpn(cfg):\n def generate_anchors(base_size=16, ratios=(0.5, 1, 2), scales=2 ** np.arange(3, 6)):\n base_anchor = np.array([1, 1, base_size, base_size]) - 1\n ratio_anchors = _ratio_enum(base_anchor, ratios)\n anchors = np.vstack([_scale_enum(ratio_anchors[i, :], scales) for i in range(ratio_anchors.shape[0])])\n return anchors\n\n def _ratio_enum(anchor, ratios):\n w, h, x_ctr, y_ctr = _generate_wh_ctrs(anchor)\n size = w * h\n size_ratios = size / ratios\n ws = np.round(np.sqrt(size_ratios))\n hs = np.round(ws * ratios)\n anchors = _make_anchors(ws, hs, x_ctr, y_ctr)\n return anchors\n\n def _scale_enum(anchor, scales):\n w, h, x_ctr, y_ctr = _generate_wh_ctrs(anchor)\n ws = w * scales\n hs = h * scales\n anchors = _make_anchors(ws, hs, x_ctr, y_ctr)\n return anchors\n\n def _generate_wh_ctrs(anchor):\n w = anchor[2] - anchor[0] + 1\n h = anchor[3] - anchor[1] + 1\n x_ctr = anchor[0] + 0.5 * (w - 1)\n y_ctr = anchor[1] + 0.5 * (h - 1)\n return w, h, x_ctr, y_ctr\n\n def _make_anchors(ws, hs, x_ctr, y_ctr):\n ws = ws[:, np.newaxis]\n hs = hs[:, np.newaxis]\n anchors = np.hstack((\n x_ctr - 0.5 * (ws - 1), y_ctr - 0.5 * (hs - 1), x_ctr + 0.5 * (ws - 1), y_ctr + 0.5 * (hs - 1)\n ))\n return anchors\n\n rpn_feat_stride = [int(k) for k in cfg]\n rpn_feat_stride.sort(reverse=True)\n anchors = []\n for stride in rpn_feat_stride:\n feature_info = cfg[stride]\n bs = feature_info['BASE_SIZE']\n __ratios = np.array(feature_info['RATIOS'])\n __scales = np.array(feature_info['SCALES'])\n anchors.append(generate_anchors(bs, __ratios, __scales))\n\n return anchors\n\n @staticmethod\n def landmark_pred(boxes, landmark_deltas):\n if boxes.shape[0] == 0:\n return np.zeros((0, landmark_deltas.shape[1]))\n boxes = boxes.astype(float, copy=False)\n widths = boxes[:, 2] - boxes[:, 0] + 1.0\n heights = boxes[:, 3] - boxes[:, 1] + 1.0\n ctr_x = boxes[:, 0] + 0.5 * (widths - 1.0)\n ctr_y = boxes[:, 1] + 0.5 * (heights - 1.0)\n pred = landmark_deltas.copy()\n for i in range(5):\n pred[:, i, 0] = landmark_deltas[:, i, 0] * widths + ctr_x\n pred[:, i, 1] = landmark_deltas[:, i, 1] * heights + ctr_y\n\n return pred\n\n @staticmethod\n def get_scale(meta):\n if 'scale_x' in meta:\n return meta['scale_x'], meta['scale_y']\n original_image_size = meta['image_size'][:2]\n image_input = [shape for shape in meta['input_shape'].values() if len(shape) == 4]\n assert image_input, \"image input not found\"\n assert len(image_input) == 1, 'model should have only one image input'\n image_input = image_input[0]\n if image_input[1] == 3:\n processed_image_size = image_input[2:]\n else:\n processed_image_size = image_input[1:3]\n y_scale = processed_image_size[0] / original_image_size[0]\n x_scale = processed_image_size[1] / original_image_size[1]\n\n return x_scale, y_scale\n\n def _repack_data_according_layout(self, raw_predictions, meta):\n if 'output_layouts' not in meta:\n return raw_predictions\n output_layouts = meta['output_layouts']\n target_outputs = self.bboxes_output + self.scores_output + self.landmarks_output + self.type_scores_output\n for target_out in target_outputs:\n layout = output_layouts[target_out]\n if layout != 'NHWC':\n continue\n shape = raw_predictions[target_out].shape\n transposed_output = np.transpose(raw_predictions, (0, 3, 1, 2))\n if shape[1] <= shape[3]:\n transposed_output = transposed_output.reshape(shape)\n raw_predictions[target_out] = transposed_output\n\n return raw_predictions\n\n\nclass RetinaFacePyTorchAdapter(Adapter):\n __provider__ = 'retinaface_pytorch'\n\n @classmethod\n def parameters(cls):\n params = super().parameters()\n params.update(\n {\n 'bboxes_output': StringField(description=\"Names for output layers with face detection boxes\"),\n 'scores_output': StringField(description=\"Names for output layers with face detection score\"),\n 'landmarks_output': StringField(\n optional=True, description=\"Names for output layers with predicted facial landmarks\"\n ),\n 'include_boundaries': BoolField(\n optional=True, default=False, description=\"Allows include boundaries for NMS\"\n ),\n 'keep_top_k': NumberField(\n min_value=1, optional=True, description=\"Maximal number of boxes which should be kept\",\n value_type=int, default=750\n ),\n 'nms_threshold': NumberField(\n min_value=0, optional=True, default=0.4, description=\"Overlap threshold for NMS\"\n ),\n 'confidence_threshold': NumberField(\n min_value=0, optional=True, default=0.02, description=\"Lower bound for valid boxes scores\"\n )\n }\n )\n return params\n\n def configure(self):\n self.bboxes_output = self.get_value_from_config('bboxes_output')\n self.scores_output = self.get_value_from_config('scores_output')\n self.landmarks_output = self.get_value_from_config('landmarks_output')\n self.include_boundaries = self.get_value_from_config('include_boundaries')\n self.keep_top_k = self.get_value_from_config('keep_top_k')\n self.nms_threshold = self.get_value_from_config('nms_threshold')\n self.confidence_threshold = self.get_value_from_config('confidence_threshold')\n self.variance = [0.1, 0.2]\n self.outputs_verified = False\n\n def select_output_blob(self, outputs):\n self.bboxes_output = self.check_output_name(self.bboxes_output, outputs)\n self.scores_output = self.check_output_name(self.scores_output, outputs)\n if self.landmarks_output:\n self.landmarks_output = self.check_output_name(self.landmarks_output, outputs)\n self.outputs_verified = True\n\n def process(self, raw, identifiers, frame_meta):\n raw_predictions = self._extract_predictions(raw, frame_meta)\n if not self.outputs_verified:\n self.select_output_blob(raw_predictions)\n results = []\n for batch_id, (identifier, meta) in enumerate(zip(identifiers, frame_meta)):\n image_size = meta['image_info'][:2]\n prior_data = self.generate_prior_data(image_size)\n proposals = self._get_proposals(raw_predictions[self.bboxes_output][batch_id], prior_data, image_size)\n scores = raw_predictions[self.scores_output][batch_id][:, 1]\n filter_idx = np.where(scores > self.confidence_threshold)[0]\n proposals = proposals[filter_idx]\n scores = scores[filter_idx]\n x_mins, y_mins, x_maxs, y_maxs = proposals.T\n keep = NMS.nms(x_mins, y_mins, x_maxs, y_maxs, scores, self.nms_threshold,\n self.include_boundaries, self.keep_top_k)\n proposals = proposals[keep]\n scores = np.reshape(scores[keep], -1)\n labels = np.full_like(scores, 1, dtype=int)\n x_mins, y_mins, x_maxs, y_maxs = np.array(proposals).T # pylint: disable=E0633\n x_scale, y_scale = self.get_scale(meta)\n detection_representation = DetectionPrediction(\n identifier, labels, scores, x_mins / x_scale, y_mins / y_scale, x_maxs / x_scale, y_maxs / y_scale\n )\n representations = {'face_detection': detection_representation}\n\n if self.landmarks_output:\n landmarks = self._get_landmarks(raw_predictions[self.landmarks_output][batch_id], prior_data,\n image_size, filter_idx, keep)\n landmarks_x_coords = np.array(landmarks)[:, ::2] / x_scale\n landmarks_y_coords = np.array(landmarks)[:, 1::2] / y_scale\n representations['landmarks_regression'] = FacialLandmarksPrediction(identifier, landmarks_x_coords,\n landmarks_y_coords)\n results.append(\n ContainerPrediction(representations) if len(representations) > 1 else detection_representation\n )\n return results\n\n @staticmethod\n def get_scale(meta):\n if 'scale_x' in meta:\n return meta['scale_x'], meta['scale_y']\n original_image_size = meta['image_size'][:2]\n image_input = [shape for shape in meta['input_shape'].values() if len(shape) == 4]\n assert image_input, \"image input not found\"\n assert len(image_input) == 1, 'model should have only one image input'\n image_input = image_input[0]\n if image_input[1] == 3:\n processed_image_size = image_input[2:]\n else:\n processed_image_size = image_input[1:3]\n y_scale = processed_image_size[0] / original_image_size[0]\n x_scale = processed_image_size[1] / original_image_size[1]\n\n return x_scale, y_scale\n\n @staticmethod\n def generate_prior_data(image_size):\n global_min_sizes = [[16, 32], [64, 128], [256, 512]]\n steps = [8, 16, 32]\n anchors = []\n feature_maps = [[int(np.rint(image_size[0]/step)), int(np.rint(image_size[1]/step))] for step in steps]\n for idx, feature_map in enumerate(feature_maps):\n min_sizes = global_min_sizes[idx]\n for i, j in product(range(feature_map[0]), range(feature_map[1])):\n for min_size in min_sizes:\n s_kx = min_size / image_size[1]\n s_ky = min_size / image_size[0]\n dense_cx = [x * steps[idx] / image_size[1] for x in [j + 0.5]]\n dense_cy = [y * steps[idx] / image_size[0] for y in [i + 0.5]]\n for cy, cx in product(dense_cy, dense_cx):\n anchors += [cx, cy, s_kx, s_ky]\n\n priors = np.array(anchors).reshape((-1, 4))\n return priors\n\n def _get_proposals(self, raw_boxes, priors, image_size):\n proposals = self.decode_boxes(raw_boxes, priors, self.variance)\n proposals[:, ::2] = proposals[:, ::2] * image_size[1]\n proposals[:, 1::2] = proposals[:, 1::2] * image_size[0]\n return proposals\n\n @staticmethod\n def decode_boxes(raw_boxes, priors, variance):\n boxes = np.concatenate((\n priors[:, :2] + raw_boxes[:, :2] * variance[0] * priors[:, 2:],\n priors[:, 2:] * np.exp(raw_boxes[:, 2:] * variance[1])), 1)\n boxes[:, :2] -= boxes[:, 2:] / 2\n boxes[:, 2:] += boxes[:, :2]\n return boxes\n\n def _get_landmarks(self, raw_landmarks, priors, image_size, filter_idx, nms_keep):\n landmarks = self.decode_landmarks(raw_landmarks, priors, self.variance)\n landmarks[:, ::2] = landmarks[:, ::2] * image_size[1]\n landmarks[:, 1::2] = landmarks[:, 1::2] * image_size[0]\n landmarks = landmarks[filter_idx]\n landmarks = landmarks[nms_keep]\n return landmarks\n\n @staticmethod\n def decode_landmarks(raw_landmarks, priors, variance):\n landmarks = np.concatenate((priors[:, :2] + raw_landmarks[:, :2] * variance[0] * priors[:, 2:],\n priors[:, :2] + raw_landmarks[:, 2:4] * variance[0] * priors[:, 2:],\n priors[:, :2] + raw_landmarks[:, 4:6] * variance[0] * priors[:, 2:],\n priors[:, :2] + raw_landmarks[:, 6:8] * variance[0] * priors[:, 2:],\n priors[:, :2] + raw_landmarks[:, 8:10] * variance[0] * priors[:, 2:]), 1)\n return landmarks\n","repo_name":"openvinotoolkit/open_model_zoo","sub_path":"tools/accuracy_checker/openvino/tools/accuracy_checker/adapters/retinaface.py","file_name":"retinaface.py","file_ext":"py","file_size_in_byte":22785,"program_lang":"python","lang":"en","doc_type":"code","stars":3804,"dataset":"github-code","pt":"41"} +{"seq_id":"2921480747","text":"\"\"\"\nSource: https://leetcode.com/problems/n-ary-tree-level-order-traversal/description/\nDate: 2022/12/9\nSkill: \nRuntime: 143 ms, faster than 6.2% \nMemory Usage: 16.2 MB, less than 12.88%\nTime complexity: \nSpace complexity: \nConstraints: \n \n\"\"\"\n\nfrom typing import List\nimport queue\n\n# Definition for a Node.\nclass Node:\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n\n\nclass Solution:\n def levelOrder(self, root: 'Node') -> List[List[int]]:\n if not root:\n return None\n res, local_res = [], []\n q = queue.Queue()\n q.put(root)\n sz = 1\n while not q.empty():\n cur = q.get()\n local_res.append(cur.val)\n for child in cur.children:\n q.put(child)\n sz -= 1\n if sz == 0:\n sz = q.qsize()\n res.append(local_res)\n local_res = []\n \n return res","repo_name":"RyanPioneer/Leetcode","sub_path":"0001~0500/0429. N-ary Tree Level Order Traversal/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"34958990878","text":"from ray.tune import Stopper\nfrom collections import defaultdict\n\nclass EarlyStopper(Stopper):\n def __init__(self, patience=7, delta=0):\n self.patience = patience\n self.counter = defaultdict(lambda: 0)\n self.best_score = defaultdict(lambda: None)\n self.early_stop = False\n self.delta = delta\n\n def __call__(self, trial_id: str, result: dict) -> bool:\n score = -result[\"total_loss\"]\n\n if self.best_score[trial_id] is None:\n self.best_score[trial_id] = score\n\n elif score < self.best_score[trial_id] + self.delta:\n self.counter[trial_id] += 1\n\n if self.counter[trial_id] >= self.patience:\n return True\n else:\n self.best_score[trial_id] = score\n self.counter[trial_id] = 0\n\n return False\n\n def stop_all(self) -> bool:\n return False","repo_name":"Janispe/PBTHAR","sub_path":"EarlyStopper.py","file_name":"EarlyStopper.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"70229316923","text":"from PyQt5.QtWidgets import QLabel\nfrom PyQt5.QtWidgets import QSpacerItem\nfrom PyQt5.QtWidgets import *\nclass StatusBar:\n\n def __init__(self, parent):\n self.parent = parent\n self.status_bar = parent.statusBar()\n self.status_msg = \"\"\n # status label\n self.status_label = QLabel(\"\")\n self.status_label.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Minimum)\n self.status_label.setMinimumWidth(10)\n # normalization label\n self.normalization_label = QLabel(\"\")\n self.normalization_label.setMinimumWidth(10)\n self.normalization_label.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Minimum)\n # result label\n self.result_label = QLabel(\"\")\n self.result_label.setMinimumWidth(10)\n self.result_label.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Minimum)\n # add widgets\n self.status_bar.addWidget(self.status_label)\n self.status_bar.addWidget(self.normalization_label)\n self.status_bar.addWidget(self.result_label)\n\n def status(self, status_msg=None):\n if status_msg is not None:\n self.status_msg = \"Ready\"\n # status_msg = self.status_bar.currentMessage()\n enabled = self.parent.app_settings.norm_enabled\n enabled = \"enabled\" if enabled else \"disabled\"\n center = self.parent.app_settings.center\n spread = self.parent.app_settings.spread\n power = self.parent.app_settings.power\n norm_str = \"Normalization: {}, center: {}, spread: {}\".format(enabled, center, spread)\n if power is not None and power != \"\":\n norm_str += \", mink power: {:8.4}\".format(power)\n self.status_label.setText(\"Status: {}.\".format(status_msg))\n self.normalization_label.setText(norm_str + \".\")\n result = self.parent.result\n if result is None:\n self.result_label.setText(\"No last result\".format())\n else:\n self.result_label.setText(\"Last result: ({:.3} s) {}\".format(result.algorithm.time, result.algorithm))\n\n\n","repo_name":"eremeykin/ectgui2","sub_path":"status_bar/status_bar.py","file_name":"status_bar.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"69931009085","text":"import media\nimport fresh_tomatoes\n\n\"\"\"\nThe following codes create new instances by use the class movie.\nIt saved the information to the specific catergory,such as title,\nstoryline, poster image url, and trailer url.\nFor the poster image url,I use google url shortener to\nmake the url shorter.\n\"\"\"\ntitanic = media.Movie(\"Titanic\",\n \"It's a love but sad story between a boy and a girl\",\n \"https://goo.gl/rgSb3N\",\n \"https://www.youtube.com/watch?v=2e-eXJ6HgkQ\")\n\nshawshank = media.Movie(\"The Shawshank Redemption\",\n \"It's about a man spend 12 years to escape from jail.\",\n \"https://goo.gl/mqccUL\",\n \"https://www.youtube.com/watch?v=6hB3S9bIaco\")\n\ntwentyone = media.Movie(\"21\",\n \"It's the adventure story for a smart student\\\n to make money from gambling.\",\n \"https://goo.gl/Hbbwii\",\n \"https://www.youtube.com/watch?v=7uYESECSFYY\")\n\ninception = media.Movie(\"Inception\",\n \"It's the story a group of people can go \\\n into others dream.\",\n \"https://goo.gl/LQf9bf\",\n \"https://www.youtube.com/watch?v=66TuSJo4dZM\")\n\nfindingdory = media.Movie(\"Finding Dory\",\n \"It's the story a father finding his son,\\\n and also a daughter finding her memories.\",\n \"https://goo.gl/cfKbHS\",\n \"https://www.youtube.com/watch?v=WP_L1I4lmFE\")\n\nlalaland = media.Movie(\"La La Land\",\n \"It's a love story between a musician and a actor.\",\n \"https://goo.gl/rN4Mas\",\n \"https://www.youtube.com/watch?v=0pdqf4P9MB8\")\n\n\n# Add all the movies into the movies list.\nmovies = [lalaland, findingdory, shawshank, titanic, inception, twentyone]\n\n\n# Input the list into the function.\nfresh_tomatoes.open_movies_page(movies)\n","repo_name":"xu1jia2qi3/Movie-Trailer-Website","sub_path":"entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"2933626097","text":"\"\"\"\nSource: https://leetcode.com/problems/minimize-hamming-distance-after-swap-operations/\nDate: 2023/4/14\nSkill:\nRef:\nRuntime: 1432 ms, faster than 68.75%\nMemory Usage: 60.4 MB, less than 70%\nTime complexity:\nSpace complexity:\nConstraints:\n\n\"\"\"\n\nimport math\nfrom typing import List, Optional\nfrom collections import defaultdict, Counter, deque\nfrom heapq import heapify, heappush, heappop, nsmallest\nimport heapq\nimport functools\nfrom bisect import bisect_left, bisect_right\n\n\nclass Solution:\n def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:\n father, sz = [i for i in range(len(source))], len(source)\n\n def find_father(i):\n if father[i] != i:\n father[i] = find_father(father[i])\n return father[i]\n\n def union(x, y):\n x_father, y_father = find_father(x), find_father(y)\n if x_father != y_father:\n father[max(x_father, y_father)] = min(x_father, y_father)\n\n for swap in allowedSwaps:\n union(swap[0], swap[1])\n\n groups, res = defaultdict(list), 0\n for i in range(sz):\n groups[find_father(i)].append(i)\n for i in groups.keys():\n cnt = Counter([source[x] for x in groups[i]])\n for idx in groups[i]:\n if target[idx] in cnt and cnt[target[idx]] > 0:\n cnt[target[idx]] -= 1\n else:\n res += 1\n\n return res\n\n\nif __name__ == \"__main__\":\n s = Solution()\n","repo_name":"RyanPioneer/Leetcode","sub_path":"1501~2000/1722. Minimize Hamming Distance After Swap Operations/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"13985738759","text":"import os\nimport os.path\nimport io\nimport IPython.display\nimport numpy as np\nimport cv2\nimport PIL.Image\n\nimport torch\n\nfrom submodules.interfacegan.models.model_settings import MODEL_POOL\nfrom submodules.interfacegan.models.pggan_generator import PGGANGenerator\nfrom submodules.interfacegan.models.stylegan_generator import StyleGANGenerator\nfrom submodules.interfacegan.utils.manipulator import linear_interpolate\nfrom dotenv import load_dotenv\nload_dotenv()\nroot = os.getenv(\"ROOT\")\n\ndef build_generator(model_name):\n \"\"\"Builds the generator by model name.\"\"\"\n gan_type = MODEL_POOL[model_name]['gan_type']\n if gan_type == 'pggan':\n generator = PGGANGenerator(model_name)\n elif gan_type == 'stylegan':\n generator = StyleGANGenerator(model_name)\n return generator\n\n\ndef sample_codes(generator, num, latent_space_type='Z', seed=0):\n \"\"\"Samples latent codes randomly.\"\"\"\n np.random.seed(seed)\n codes = generator.easy_sample(num)\n if generator.gan_type == 'stylegan' and latent_space_type == 'W':\n codes = torch.from_numpy(codes).type(torch.FloatTensor).to(generator.run_device)\n codes = generator.get_value(generator.model.mapping(codes))\n return codes\n\n\ndef imshow(images, col, viz_size=256):\n \"\"\"Shows images in one figure.\"\"\"\n num, height, width, channels = images.shape\n assert num % col == 0\n row = num // col\n\n fused_image = np.zeros((viz_size * row, viz_size * col, channels), dtype=np.uint8)\n\n for idx, image in enumerate(images):\n i, j = divmod(idx, col)\n y = i * viz_size\n x = j * viz_size\n if height != viz_size or width != viz_size:\n image = cv2.resize(image, (viz_size, viz_size))\n fused_image[y:y + viz_size, x:x + viz_size] = image\n\n fused_image = np.asarray(fused_image, dtype=np.uint8)\n data = io.BytesIO()\n PIL.Image.fromarray(fused_image).save(data, 'jpeg')\n im_data = data.getvalue()\n disp = IPython.display.display(IPython.display.Image(im_data))\n return disp\n\n\n\n\ndef main():\n #@title { display-mode: \"form\", run: \"auto\" }\n submodule_path = f'{root}/submodules/interfacegan/'\n model_name = \"stylegan_ffhq\" #@param ['pggan_celebahq','stylegan_celebahq', 'stylegan_ffhq']\n latent_space_type = \"W\" #@param ['Z', 'W']\n\n generator = build_generator(model_name)\n\n ATTRS = ['age', 'gender', 'eyeglasses']\n boundaries = {}\n for i, attr_name in enumerate(ATTRS):\n boundary_name = f'{model_name}_{attr_name}'\n if generator.gan_type == 'stylegan' and latent_space_type == 'W':\n boundaries[attr_name] = np.load(f'{submodule_path}boundaries/{boundary_name}_w_boundary.npy')\n else:\n boundaries[attr_name] = np.load(f'{submodule_path}boundaries/{boundary_name}_boundary.npy')\n\n\n #@title { display-mode: \"form\", run: \"auto\" }\n\n num_samples = 1 #@param {type:\"slider\", min:1, max:8, step:1}\n noise_seed = 0 #@param {type:\"slider\", min:0, max:1000, step:1}\n\n latent_codes = sample_codes(generator, num_samples, latent_space_type, noise_seed)\n print(latent_codes)\n if generator.gan_type == 'stylegan' and latent_space_type == 'W':\n synthesis_kwargs = {'latent_space_type': 'W'}\n else:\n synthesis_kwargs = {}\n\n images = generator.easy_synthesize(latent_codes, **synthesis_kwargs)['image']\n imshow(images, col=num_samples)\n \n\nif __name__ == \"__main__\":\n main()","repo_name":"potocnikvid/fri-2022-diploma","sub_path":"src/interfacegan.py","file_name":"interfacegan.py","file_ext":"py","file_size_in_byte":3414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"4923994854","text":"# https://www.acmicpc.net/problem/2178\nfrom collections import deque\ndx = [1, -1, 0, 0]\ndy = [0, 0, 1, -1]\n\n\ndef bfs(graph, row, col):\n que = deque([(row, col, 1)])\n\n while que:\n row, col, distance = que.popleft()\n\n if row == N - 1 and col == M - 1:\n return distance\n\n for i in range(4):\n nx = row + dx[i]\n ny = col + dy[i]\n\n if 0 <= nx < N and 0 <= ny < M and graph[nx][ny] == 1:\n que.append((nx, ny, distance + 1))\n graph[nx][ny] = 0 # 방문 표시\n\n return -1\n\n\nN, M = map(int, input().split())\ngraph = [list(map(int, input())) for _ in range(N)]\n\nprint(bfs(graph, 0, 0))\n","repo_name":"psrom/Algorithm","sub_path":"BOJ Solution/DFS, BFS/BOJ_2178/01_230822.py","file_name":"01_230822.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"14496238798","text":"numeros= [0,1,2,3,4,5,6,7,8,9,10,11,13,15,20]\n\n#creando una funcion en lambda multiplicar por 2\n\nmultiplicar_por_dos = lambda x : x *2 #para evitar crear bloues en funciones def, evitarlas\n\n#creando funcion comun que diga si es par o no \n#def es_par(num):\n# if num % 2== 1:\n# return True\n\n#usar filter con una funcion comun\n\n\n\n\n#creando lo mismo pero con lambda\n\n\n\nnumeros_pares = filter(lambda numeros: numeros % 2 == 0,numeros)\n\nprint(list(numeros_pares))","repo_name":"Aaron09py/Program_practic","sub_path":"funciones/funciones_lambda.py","file_name":"funciones_lambda.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"20194847864","text":"import asyncio, requests\n\ndef http_call_sync():\n\tr = requests.get('https://httpbin.org/status/200')\n\tprint(r.status_code)\n\n\tr = requests.get('https://httpbin.org/status/204')\n\tprint(r.status_code)\n\nasync def http_call_async(future, id=None):\n\tprint('waiting...', id)\n\tawait asyncio.sleep(1)\n\tr = requests.get(id)\n\tfuture.set_result('Status code ' + str(r.status_code) + ' is returned!')\n\tprint(r.status_code)\n\n\t\n\nasync def slow_operation(future):\n await asyncio.sleep(1)\n future.set_result('Future is done!')\n\nprint('Asynchronous mode:')\nloop = asyncio.get_event_loop()\nfuture1 = asyncio.Future()\nasyncio.ensure_future(http_call_async(future1, 'https://httpbin.org/status/200'))\nfuture2 = asyncio.Future()\nasyncio.ensure_future(http_call_async(future2, 'https://httpbin.org/status/204'))\nloop.run_until_complete(future1)\nloop.run_until_complete(future2)\nprint(future1.result())\nprint(future2.result())\nloop.close()\n\nprint('Synchronous mode:')\nhttp_call_sync()\n\n\n\n\n","repo_name":"hchen0402/cmpe273","sub_path":"quiz2/http_request.py","file_name":"http_request.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"18545156769","text":"import discord\nfrom discord.ext import commands\nfrom discord.utils import get\nimport os\n\nBASE_ROLE = os.getenv('BASE_ROLE_NAME')\n\nclass Greetings(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self._last_member = None\n\n async def set_adherent(self, member):\n role = get(member.guild.roles, name=str(BASE_ROLE))\n await member.add_roles(role)\n\n @commands.Cog.listener()\n async def on_member_join(self, member):\n channel = member.guild.system_channel\n if channel is not None:\n how_cute = \"https://media.giphy.com/media/Ae7SI3LoPYj8Q/giphy.gif\"\n embed = discord.Embed(\n title=\"Bienvenue :smile:\",\n color=discord.Colour.purple()\n )\n embed.set_image(url=how_cute)\n await channel.send('Voici le discord du BDE {0.mention}. 🥳'.format(member), embed=embed)\n await self.set_adherent(member)\n\n # @commands.command()\n # async def hello(self, ctx, *, member: discord.Member = None):\n # \"\"\"Says hello\"\"\"\n # member = member or ctx.author\n # if self._last_member is None or self._last_member.id != member.id:\n # await ctx.send('Hello {0.name}~'.format(member))\n # else:\n # await ctx.send('Hello {0.name}... This feels familiar.'.format(member))\n # self._last_member = member","repo_name":"EwenBALOUIN/DiscordBot","sub_path":"welcome.py","file_name":"welcome.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"31674266666","text":"import tkinter as tk\nfrom tkinter import messagebox\n\ndef test():\n\n mainframe = tk.Frame(fenPrincipal)\n btn = tk.Button(mainframe, text=\"blablabla\")\n mainframe.pack()\n btn.pack()\n\ndef test2(a, b):\n a.tkraise()\n b\n\n\n# ? Creation de la fenetre principal\n# Creation de la fenetre\nfenPrincipal = tk.Tk()\n# titre de la fenetre\nfenPrincipal.title(\"EchecPorn\")\n# taile mini\nfenPrincipal.minsize(640, 480)\n# ** taille d'affichage standard\n# On recup la taille de l'ecran utilisateur\nscreen_x = int(fenPrincipal.winfo_screenwidth())\nscreen_y = int(fenPrincipal.winfo_screenheight())\n# Taille de l'ecran voulu\nfenPrincipalX = 800\nfenPrincipalY = 600\n# calcule pour centrer la fenetre\ncoordX = (screen_x // 2) - (fenPrincipalX // 2)\ncoordY = (screen_y // 2) - (fenPrincipalY // 2)\n\n# Creation de la forme pour lafenetre\nfenPrincipal.geometry(f\"{fenPrincipalX}x{fenPrincipalY}+{coordX}+{coordY}\")\n\n\n# ! Frame 0\nframe0 = tk.Frame(fenPrincipal)\nbtn0 = tk.Button(frame0, text=\"ok\", command=test2(frame0, test()))\nbtn0.pack()\nframe0.pack()\n\n\n\n\n\n\n\n\n\n\n\n\n\n# ** permet le maintient de l'affichage\nfenPrincipal.mainloop()\n","repo_name":"Swanky-x/echec.py","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"6500087272","text":"import jieba\r\nfrom csv_to_list import read_csv\r\n\r\njieba.set_dictionary('dict.txt.big')\r\nremove_words = [u'的', u',', u'和', u'是', u'隨著', u'對於', u'對', u'等', u'能', u'都', u'。', u',', u'、', u'中', u'在', u'了', u'通常', u'如果', u'我們', u'需要']\r\ndef countAllWord(strlist):\r\n cutlist = []\r\n for i in strlist:\r\n word = jieba.cut(i, cut_all=False)\r\n for subword in list(word):\r\n if subword not in remove_words:\r\n if len(subword) >= 2:\r\n cutlist.append(subword)\r\n #print(cutlist)\r\n cut_str = \" \".join(cutlist)\r\n #print(cut_str)\r\n cutlist2 = list(cut_str.split())\r\n report = {}\r\n for i in cutlist2:\r\n if i in report:\r\n report[i] = report[i] + 1\r\n else:\r\n report[i] = 1\r\n return report, cut_str\r\n\r\n\r\n\r\n","repo_name":"owancato/textual-analysis","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"3797662344","text":"from PIL import Image\nimport os\n\ndef rotateImages(rotationAmt):\n for image in os.listdir(os.getcwd()):\n img = Image.open(image)\n img.rotate(rotationAmt).save(image)\n img.close()\n \n# examples of use\nrotateImages(270)\nrotateImages(270)\n","repo_name":"indianquant/RotateIt","sub_path":"rotateImages.py","file_name":"rotateImages.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"18764851933","text":"#!/usr/bin/env python\n\nfrom pymongo import MongoClient\n\n\nclass MongoDb:\n def __init__(self, **kwargs):\n self.kwargs = {k:v for k,v in kwargs.items()}\n self.do_init = self.kwargs.get('do_init', False)\n self.client = self.client = MongoClient('0.0.0.0', 27017)\n if self.do_init:\n self.init()\n\n def init(self):\n \"\"\" intitialize mongo db and collection\"\"\"\n db = self.client.congress\n self.bills = db.bills\n self.roll_call = db.roll_call\n","repo_name":"asoa/congress_vote_summary","sub_path":"mongo_db.py","file_name":"mongo_db.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"6741848427","text":"from django.db.models.functions import Length\nfrom django.shortcuts import render_to_response, render\nfrom django.views.decorators.csrf import csrf_protect\nfrom .models import Word\n\n@csrf_protect\ndef index(request):\n return render_to_response('base.html')\n\n@csrf_protect\ndef search_words(request):\n if request.method=='GET':\n word = request.GET['word']\n else:\n word=''\n words = Word.objects.filter(name__contains=word, name__startswith=word).order_by('-frequency')\n words = words.order_by(Length('name').asc())\n return render(request, 'search.html', {'words': words})\n","repo_name":"pixelr123/search","sub_path":"search/search_word/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"3782912892","text":"\nN, M, T = map(int, input().split())\nTowardGraph, ReturnGraph = [], []\nSt = [10**10 for _ in range(N+1)]\nSr = [10**10 for _ in range(N+1)]\nA = list(map(int, input().split()))\n\nfor i in range(M):\n a, b, c = map(int, input().split())\n TowardGraph.append([a, b, c])\n ReturnGraph.append([b, a, c])\n\nSt[1], Sr[1] = 0, 0\n\n# 行き\nwhile True:\n update = False\n for edge in TowardGraph:\n if St[edge[0]] != 10**10 and St[edge[1]] > St[edge[0]]+edge[2]:\n St[edge[1]] = St[edge[0]]+edge[2]\n update = True\n if not update:\n break\n\n# 帰り\nwhile True:\n update = False\n for edge in ReturnGraph:\n if Sr[edge[0]] != 10**10 and Sr[edge[1]] > Sr[edge[0]]+edge[2]:\n Sr[edge[1]] = Sr[edge[0]]+edge[2]\n update = True\n if not update:\n break\n\n# 計算\nscore = [0 for _ in range(N+1)]\nfor i in range(N):\n score[i] = A[i]*(T-St[i+1]-Sr[i+1])\n\nprint(max(score))\n","repo_name":"Shuhei-pp/ProgramingCompe","sub_path":"graph/abc35c.py","file_name":"abc35c.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"5490280197","text":"from django.shortcuts import render\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.urls import reverse\nfrom forum.models import forumdetails, commentinfo\nfrom django.contrib.auth.decorators import login_required\n\n@login_required\ndef home(request, pk):\n if pk:\n if request.method == 'POST':\n if len(request.POST['msg']) > 1:\n c_user = request.user\n new_comment = commentinfo(message = request.POST['msg'], by = c_user )\n new_comment.to = forumdetails.objects.get(pk=pk)\n new_comment.save()\n reqs = forumdetails.objects.all()\n forum = forumdetails.objects.get(pk=pk)\n comments = commentinfo.objects.filter(to = forum.pk)\n print(forum)\n print(comments)\n return render(request, 'forum/base.html', {'reqs':reqs, 'forum':forum, 'comments':comments})\n else:\n return HttpResponseRedirect(reverse('cus_login:home'));\n","repo_name":"mprerana/DBMS_Project","sub_path":"Group_22/forum/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"41"} +{"seq_id":"70109463163","text":"import matplotlib.pyplot as plt\nimport sys\nimport os\nimport numpy as np\nfrom ase.io import read, write\nfrom ase import Atoms\nfrom ase.neighborlist import NeighborList\nfrom scipy.spatial.distance import cdist\nfrom tqdm import tqdm\nfrom matplotlib import cm\nfrom matplotlib.patches import Patch\n\nfrom asaplib.reducedim import Dimension_Reducers\nfrom asaplib.plot import Plotters as asapPlotters\n\nfrom ase.neighborlist import natural_cutoffs, NeighborList\nimport pandas as pd\n\ndef run_on_file(system_now):\n # Possible reshaping issue with 'rutile-100-nd-0', seems to not be 12 long but 11\n this_dir = os.path.dirname(os.path.abspath(__file__))\n\n nhydrogen = 128*2\n\n ts_slicer = np.s_[1000:10000:10]\n\n system_ref = 'anatase-101-nd-0' # always use this\n with open(os.path.join(this_dir, 'ref-anatase-101-nd-0-h-dis.npy'), 'rb') as f:\n h_dis_all_ref = np.load(f)\n print(h_dis_all_ref.shape)\n\n colvar = np.genfromtxt(os.path.join(this_dir, system_now+'/COLVAR'))[ts_slicer] # consistent with the gen of features\n tt = 330 #K\n kbt = 0.008314*tt # in kj/mol\n\n print(len(colvar))\n sys_weights = np.exp((colvar[:,2]+colvar[:,3])/kbt)\n\n h_weights = np.ones((len(sys_weights),nhydrogen))\n for i in range(len(sys_weights)):\n h_weights[i,:] *= sys_weights[i]\n\n h_weights = np.ones((len(sys_weights),nhydrogen))\n for i in range(len(sys_weights)):\n h_weights[i,:] *= sys_weights[i]\n\n with open(os.path.join(this_dir, system_now+'-h-dis-env.npy'), 'rb') as f:\n h_dis_all = np.load(f)\n h_env_all = np.load(f)\n print(h_dis_all.shape)\n print(h_env_all.shape)\n\n reduce_dict = {}\n \"\"\"\n reduce_dict['pca'] = {\n \"type\": 'PCA',\n 'parameter':{\n \"n_components\": 4}\n }\n \"\"\"\n reduce_dict['kpca'] = {\n \"type\": 'SPARSE_KPCA',\n 'parameter':{\n \"n_components\": 2,\n \"n_sparse\": 200, # no sparsification\n \"kernel\": {\"first_kernel\": {\"type\": 'cosine'}}\n }\n }\n\n dreducer = Dimension_Reducers(reduce_dict)\n\n hcoord_ref = np.reshape(h_dis_all_ref,(-1,11))\n hcoord_now = np.reshape(h_dis_all,(-1,h_dis_all.shape[-1]))\n\n print(hcoord_ref.shape)\n print(hcoord_now.shape)\n\n # proj = dreducer.fit_transform(hcoord_now[:,[1,2,3,5,6,8,9,10]])\n\n dreducer.fit(hcoord_ref[:,[1,2,3,5,6,8,9,10]])\n proj = dreducer.transform(hcoord_now[:,[1,2,3,5,6,8,9,10]])\n\n print(proj.shape)\n\n # reshape\n print(proj.shape[0]/nhydrogen)\n h_proj = np.reshape( proj[:,[0,1]],(-1,nhydrogen,2))\n print(np.shape(h_proj))\n\n stride = 1\n h_proj_sparse = h_proj[::stride,:,:]\n np.shape(h_proj_sparse)\n\n h_proj_sparse_all = np.reshape(h_proj_sparse[1:,:,:],(-1,2))\n\n # classify\n\n cls_labels= ['H$_2$O$^{(> 1)}$','H-O$_t$','HO-Ti','H$_2$O-Ti','H$_2$O$^{(1)}$']\n\n cls = np.zeros(len(hcoord_now))\n for i,hh in enumerate(hcoord_now):\n if hh[3] >=5: \n cls[i] = 0 # in the bulk\n elif hh[3] < 1.2 and hh[2] > 1.6:\n cls[i] = 1 # H on O(TiO2)\n elif hh[2] > 1.8 and hh[5]<3: # OH on Ti\n cls[i] = 2 # OH on Ti\n elif hh[5]<3:\n cls[i] = 3 # H2O on Ti\n else:\n cls[i] = 4 # H2O close to slab but not on Ti\n \n cls = np.reshape( cls,(-1,nhydrogen))\n np.shape(cls)\n\n trajectory = read(os.path.join(this_dir, system_now+'/out.lammpstrj'), index='%u:%u:%u'%(ts_slicer.start, ts_slicer.stop, ts_slicer.step))\n cutoffs = natural_cutoffs(trajectory[0], mult=0.75)\n\n cur_nlist = NeighborList(cutoffs, bothways=True, self_interaction=False)\n prev_nlist = NeighborList(cutoffs, bothways=True, self_interaction=False)\n\n def get_o_config(nlist, h_index, init_config):\n h_neighs = nlist.get_neighbors(h_index)[0]\n \n if len(h_neighs) == 0:\n return 'solo'\n \n h_neigh = h_neighs[0] # Closest element should be O anyways\n \n o_neighs = nlist.get_neighbors(h_neigh)[0]\n o_neighs = np.append(h_neigh, o_neighs)\n \n return init_config[o_neighs].get_chemical_formula(mode='hill')\n\n # weighted transition rates (assuming V is quasi-static)\n\n start_configs = []\n end_configs = []\n wstart = []\n wend = []\n \n def update_nlists(i):\n # not okay to write functions like this\n cur_nlist.update(trajectory[i])\n prev_nlist.update(trajectory[i-1])\n\n cl_transition = np.zeros((5,5))\n print(cls.shape)\n # I want to plot the evolution of H\n\n count = 0\n nl_ts = 0\n for i in range(1,np.shape(cls)[0]): # loop through the frames\n cur_nlist.update(trajectory[i])\n prev_nlist.update(trajectory[i-1])\n \n for j in range(nhydrogen):# loop through points\n [c1, c2] = [int(cls[i,j]), int(cls[i-1,j])]\n cl_transition[c1,c2] += 1 # h_weights[i,j]/h_weights[i-1,j]\n if (c1 == 1) and (c2 == 4):\n count += 1\n if not nl_ts == i:\n update_nlists(i)\n nl_ts = i\n # print(f\"Timestep: {1000+(10*i):n}\")\n # print(f\"Hydro Index: {h_dis_all[i, j, 0]:n}\")\n # if count == 50:\n # raise ValueError\n h_index = int(h_dis_all[i, j, 0])\n end_configs.append(get_o_config(cur_nlist, h_index, trajectory[0]))\n start_configs.append(get_o_config(prev_nlist, h_index, trajectory[0]))\n \n elif False: # c1 == 0 and c2 == 0:\n h_index = int(h_dis_all[i, j, 0])\n wend.append(get_o_config(cur_nlist, h_index, trajectory[0]))\n wstart.append(get_o_config(prev_nlist, h_index, trajectory[0]))\n \n \n print(count)\n print(cls.shape)\n print(cl_transition)\n\n for k in range(5):\n cl_norm = np.sum(cl_transition[k,:])\n cl_transition[k,:]/=cl_norm\n\n print(\"Starting configurations:\")\n start_counts = pd.Series(start_configs).value_counts()\n print(start_counts)\n\n print(\"Final configurations:\")\n end_counts = pd.Series(end_configs).value_counts()\n print(end_counts)\n\n print(\"Starting configurations:\")\n counts = pd.Series(wstart).value_counts()\n print(counts)\n\n print(\"Final configurations:\")\n counts = pd.Series(wend).value_counts()\n print(counts)\n\n fig, axes = plt.subplots(nrows=2, ncols=1)\n\n total_loc = -2\n x_start = np.arange(len(start_counts))\n x_end = np.arange(len(end_counts))\n fs = 15\n\n axes[0].bar(x_start, start_counts.array)\n axes[0].bar(total_loc, np.sum(start_counts.array))\n axes[0].set_xticks(np.append(total_loc, x_start))\n axes[0].set_xticklabels([r'H$_2$O$^{(1)}$'] + start_counts.keys().tolist())\n axes[0].annotate(\n \"\", \n xy=(total_loc+0.5+1, np.sum(start_counts.array)/2), \n xytext=(total_loc+0.5, np.sum(start_counts.array)/2), \n arrowprops=dict(arrowstyle=\"->\")\n )\n axes[0].set_title(\"Starting Configurations\", fontsize=fs-5)\n axes[0].set_ylabel(\"counts\")\n\n axes[1].bar(x_end, end_counts.array)\n axes[1].bar(total_loc, np.sum(end_counts.array))\n axes[1].set_xticks(np.append(total_loc, x_end))\n axes[1].set_xticklabels(['H-O$_t$'] + end_counts.keys().tolist())\n axes[1].annotate(\n \"\", \n xy=(total_loc+0.5+1, np.sum(end_counts.array)/2), \n xytext=(total_loc+0.5, np.sum(end_counts.array)/2), \n arrowprops=dict(arrowstyle=\"->\")\n )\n axes[1].set_title(\"End Configurations\", fontsize=fs-5)\n axes[1].set_ylabel(\"counts\")\n\n legend_elements = [\n Patch(facecolor='tab:orange', label='atomic descriptors classification'),\n Patch(facecolor='tab:blue', label='nearest neighbour environment')\n ]\n axes[0].legend(handles=legend_elements)\n\n fig.suptitle(f'{system_now.split(\"-\")[0]} ({system_now.split(\"-\")[1]})', fontsize=fs)\n\n plt.tight_layout()\n\n fig.savefig(os.path.join(this_dir, f'advsnl_{system_now.split(\"-\")[0]}_{system_now.split(\"-\")[1]}.pdf'), format='pdf')\n\n # plt.show()\n\ndef main():\n system_list = [\n 'anatase-100-nd-0',\n 'anatase-101-nd-0',\n 'anatase-110-nd-0',\n 'rutile-001-nd-0',\n 'rutile-011-nd-0',\n 'rutile-100-nd-0',#'rutile-101-nd-0',\n 'rutile-110-nd-0'\n ]\n\n for system_now in system_list:\n run_on_file(system_now=system_now)\n\nif __name__ == '__main__':\n main()","repo_name":"FelixWodaczek/tio_chaining","sub_path":"py_test/bc_test/analyse_bond_analysis_all.py","file_name":"analyse_bond_analysis_all.py","file_ext":"py","file_size_in_byte":8454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"70252620925","text":"#!/usr/bin/env python3\r\n\r\nimport string\r\nimport random\r\nimport sys\r\nimport json\r\nfrom flask import (Flask, render_template, request, redirect, jsonify, url_for,\r\n flash, make_response, session as login_session)\r\nfrom flask_cors import CORS, cross_origin\r\nfrom sqlalchemy import create_engine, asc, desc\r\nfrom sqlalchemy.orm import sessionmaker\r\nfrom database_setup import Base, Category, Item, User\r\nimport google_auth as gAuth\r\n\r\napp = Flask(__name__)\r\n\r\n# Read the secret key\r\ntry:\r\n app.secret_key = open('secret_key.txt', 'r').read()\r\nexcept IOError as ioe:\r\n print('Error: File \\'secret_key.txt\\' must be present in the root folder')\r\n print(ioe.pgerror)\r\n print(ioe.diag.message_detail)\r\n sys.exit(1)\r\n\r\napp.config['CORS_HEADERS'] = 'Content-Type'\r\n\r\nCORS(app,\r\n origins=\"http://localhost:5000\",\r\n allow_headers=[\r\n \"Content-Type\",\r\n \"Authorization\",\r\n \"Access-Control-Allow-Credentials\",\r\n \"Access-Control-Allow-Origin\"],\r\n supports_credentials=True)\r\n\r\n# Database connection:\r\nengine = create_engine('sqlite:///itemcatalog.db',\r\n connect_args={'check_same_thread': False})\r\nBase.metadata.bind = engine\r\nDBSession = sessionmaker(bind=engine)\r\nsession = DBSession()\r\n\r\n\r\n@app.route('/')\r\n@app.route('/catalog')\r\ndef index():\r\n \"\"\"\r\n Web app home page. Shows all the items available in the database.\r\n \"\"\"\r\n generate_state()\r\n categories = session.query(Category).order_by(desc(Category.name))\r\n items = session.query(Item).order_by(desc(Item.id)).limit(10)\r\n return render_template('content.html',\r\n categories=categories,\r\n items=items,\r\n client_id=gAuth.CLIENT_ID,\r\n state=login_session['state'],\r\n user=get_user())\r\n\r\n\r\n@app.route('/catalog/categories/<int:category_id>')\r\ndef show_category_items(category_id):\r\n \"\"\"\r\n Show the category items for a given category ID.\r\n \"\"\"\r\n categories = session.query(Category).order_by(desc(Category.name))\r\n items = session.query(Item).filter_by(category_id=category_id)\r\n items = items.order_by(desc(Item.id))\r\n return render_template('content.html',\r\n categories=categories,\r\n items=items,\r\n client_id=gAuth.CLIENT_ID,\r\n state=login_session['state'],\r\n user=get_user())\r\n\r\n\r\n@app.route('/catalog/items/delete/<int:item_id>')\r\ndef delete_item(item_id):\r\n \"\"\"\r\n Deletes a item from the catalog given an item ID.\r\n \"\"\"\r\n if is_authenticated():\r\n item = session.query(Item).filter_by(id=item_id).one()\r\n\r\n if item is not None:\r\n if login_session['user']['email'] == item.user.email:\r\n session.delete(item)\r\n session.commit()\r\n return redirect(url_for('index'))\r\n else:\r\n message = 'User not authorized to delete this item'\r\n return redirect(url_for('index', message=[message]))\r\n else:\r\n return redirect(url_for('index', message=['Item not found']))\r\n else:\r\n message = 'User is not authenticated'\r\n return redirect(url_for('index', message=[message]))\r\n\r\n\r\n@app.route('/catalog/items/new', methods=['POST'])\r\ndef create_item():\r\n \"\"\"\r\n Creates an item given all of the information.\r\n \"\"\"\r\n user = session.query(User).filter_by(email=request.form['email']).first()\r\n new_item = Item(title=request.form['title'],\r\n description=request.form['description'],\r\n category_id=request.form['categoryId'],\r\n user=user)\r\n session.add(new_item)\r\n session.commit()\r\n\r\n return redirect(url_for('index'))\r\n\r\n\r\n@app.route('/catalog/items/edit', methods=['POST'])\r\ndef edit_item():\r\n \"\"\"\r\n Edit an item given new information.\r\n \"\"\"\r\n if is_authenticated():\r\n item_id = request.form['itemIdEdit']\r\n item = session.query(Item).filter_by(id=item_id).one()\r\n if item is not None:\r\n if login_session['user']['email'] == item.user.email:\r\n item.title = request.form['titleEdit']\r\n item.description = request.form['descriptionEdit']\r\n item.category_id = request.form['categoryIdEdit']\r\n session.add(item)\r\n session.commit()\r\n return redirect(url_for('index'))\r\n else:\r\n message = 'User not authorized to edit this item'\r\n return redirect(url_for('index', message=[message]))\r\n else:\r\n return redirect(url_for('index', message=['Item not found']))\r\n else:\r\n message = 'User is not authenticated'\r\n return redirect(url_for('index', message=[message]))\r\n\r\n\r\n@app.route('/catalog/authenticated')\r\ndef authenticated():\r\n \"\"\"\r\n Check if the user is already authenticated.\r\n \"\"\"\r\n if is_authenticated():\r\n return make_response(\r\n jsonify(message=\"User is already logged in\",\r\n status=200, data=True))\r\n else:\r\n return make_response(jsonify(message=\"User is not logged in\",\r\n status=200,\r\n data=False))\r\n\r\n\r\n@app.route('/catalog/gconnect', methods=['POST'])\r\ndef G_Login():\r\n \"\"\"\r\n Does a login to the Google account.\r\n \"\"\"\r\n if 'state' in request.form:\r\n if request.form['state'] != login_session['state']:\r\n return redirect(url_for('index'))\r\n\r\n if not is_authenticated():\r\n user_json = gAuth.Google_Callback()\r\n\r\n if user_json:\r\n user_data = json.loads(user_json)\r\n login_session['user'] = {\r\n 'name': user_data['name'],\r\n 'picture': user_data['picture'],\r\n 'email': user_data['email']\r\n }\r\n\r\n check_user(user_data)\r\n else:\r\n logout_session()\r\n return make_response(jsonify(\r\n message=\"Successfully logged in. Reload the page.\",\r\n status=200,\r\n data=True\r\n ))\r\n else:\r\n return make_response(jsonify(\r\n message=\"Already logged in\",\r\n status=200,\r\n data=False\r\n ))\r\n else:\r\n print('Error: \\'state\\' is not within the request')\r\n\r\n return redirect(url_for('Index'))\r\n\r\n\r\n@app.route('/catalog/logout', methods=['POST'])\r\ndef logout():\r\n \"\"\"\r\n Ends the user session. Disconnects from Google.\r\n \"\"\"\r\n logout_session()\r\n\r\n return make_response(jsonify(\r\n message=\"User logged out\",\r\n status=200,\r\n data=\"Logged Out\"\r\n ))\r\n\r\n\r\n@app.route('/catalog/json')\r\ndef catalog_json():\r\n \"\"\"\r\n Reads the entire catalog from the database.\r\n \"\"\"\r\n categories = session.query(Category).all()\r\n return jsonify(Category={int(c.id): {'name': c.name,\r\n 'items': [i.serialize for i in\r\n session.query(Item).filter_by(category_id=c.id)]}\r\n for c in categories})\r\n\r\n\r\n@app.route('/catalog/items/<int:item_id>/json')\r\ndef get_item_by_id(item_id):\r\n \"\"\"\r\n Reads in JSON format a particular item from a given ID.\r\n \"\"\"\r\n item = session.query(Item).filter_by(id=item_id).first()\r\n return jsonify(item.serialize if item is not None else {})\r\n\r\n\r\ndef generate_state():\r\n \"\"\"\r\n Generates a new random state for the session.\r\n \"\"\"\r\n state = ''.join(random.choice(string.ascii_uppercase + string.digits)\r\n for x in range(32))\r\n login_session['state'] = state\r\n\r\n\r\ndef is_authenticated():\r\n \"\"\"\r\n Check if the user is authenticated.\r\n \"\"\"\r\n return 'user' in login_session\r\n\r\n\r\ndef logout_session():\r\n \"\"\"\r\n Ends the session variables.\r\n \"\"\"\r\n if is_authenticated():\r\n login_session.pop('user', None)\r\n login_session.pop('state', None)\r\n\r\n\r\ndef get_user():\r\n \"\"\"\r\n Get the user from the session variable.\r\n \"\"\"\r\n return login_session.get('user', None)\r\n\r\n\r\ndef check_user(user_data):\r\n \"\"\"\r\n Checks if the user is in the database; if not, then a new user is created.\r\n \"\"\"\r\n user = session.query(User).filter_by(email=user_data['email']).first()\r\n\r\n if user is None:\r\n new_user = User(name=user_data['name'], email=user_data['email'],\r\n picture=user_data['picture'])\r\n session.add(new_user)\r\n session.commit()\r\n\r\nif __name__ == '__main__':\r\n app.secret_key = 'super_secret_key'\r\n app.debug = True\r\n app.run(host='0.0.0.0', port=5000)\r\n","repo_name":"Fhernd/CatalogItem-Nanodegree-Udacity","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":8878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"33482167250","text":"import json\nimport logging\nimport urllib\nimport urllib2\n\n# for spellchecking\nimport spellchecker\n\n# standard app engine imports\nfrom google.appengine.api import urlfetch\nfrom google.appengine.ext import ndb\nimport webapp2\n\nTOKEN = '116452497:AAGTGrXnDkF-KN0gIkRXmtzas6Zyz1dwQ_o'\n\nBASE_URL = 'https://api.telegram.org/bot' + TOKEN + '/'\n\n\n# ================================\n\nclass EnableStatus(ndb.Model):\n # key name: str(chat_id)\n enabled = ndb.BooleanProperty(indexed=False, default=False)\n\n\n# ================================\n\ndef setEnabled(chat_id, yes):\n es = EnableStatus.get_or_insert(str(chat_id))\n es.enabled = yes\n es.put()\n\ndef getEnabled(chat_id):\n es = EnableStatus.get_by_id(str(chat_id))\n if es:\n return es.enabled\n return False\n\n\n# ================================\n\nclass MeHandler(webapp2.RequestHandler):\n def get(self):\n urlfetch.set_default_fetch_deadline(60)\n self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'getMe'))))\n\n\nclass GetUpdatesHandler(webapp2.RequestHandler):\n def get(self):\n urlfetch.set_default_fetch_deadline(60)\n self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'getUpdates'))))\n\n\nclass SetWebhookHandler(webapp2.RequestHandler):\n def get(self):\n urlfetch.set_default_fetch_deadline(60)\n url = self.request.get('url')\n if url:\n self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'setWebhook', urllib.urlencode({'url': url})))))\n\n\nclass WebhookHandler(webapp2.RequestHandler):\n def post(self):\n urlfetch.set_default_fetch_deadline(60)\n body = json.loads(self.request.body)\n logging.info('request body:')\n logging.info(body)\n self.response.write(json.dumps(body))\n\n update_id = body['update_id']\n message = body['message']\n message_id = message.get('message_id')\n date = message.get('date')\n text = message.get('text')\n fr = message.get('from')\n chat = message['chat']\n chat_id = chat['id']\n\n if not text:\n logging.info('no text')\n return\n\n def reply(msg=None):\n if msg:\n resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({\n 'chat_id': str(chat_id),\n 'text': msg.encode('utf-8'),\n 'disable_web_page_preview': 'true',\n 'reply_to_message_id': str(message_id),\n })).read()\n else:\n logging.error('no msg or img specified')\n resp = None\n\n logging.info('send response:')\n logging.info(resp)\n\n if '/r/' in text:\n reply('www.reddit.com/r/' + text.split(\"/r/\", 1)[1])\n\n elif text.startswith('/'):\n if text == '/start':\n reply('Bot enabled')\n setEnabled(chat_id, True)\n elif text == '/stop':\n reply('Bot disabled')\n setEnabled(chat_id, False)\n else:\n reply('What command?')\n else:\n pass\n # correct = True\n # words = []\n # for word in text.split():\n # if not spellchecker.check(word):\n # correct = False\n # words.append(spellchecker.correct(word))\n # else:\n # words.append(word)\n # if not correct:\n # new_sentence = \"\"\n # for word in words:\n # new_sentence += word+\" \"\n # reply(\"Did you mean: \"+new_sentence)\n\n\napp = webapp2.WSGIApplication([\n ('/me', MeHandler),\n ('/updates', GetUpdatesHandler),\n ('/set_webhook', SetWebhookHandler),\n ('/webhook', WebhookHandler),\n], debug=True)\n","repo_name":"sjoshua270/subreddit-bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"30329767010","text":"\"\"\"\nDeletes an Azure queue\n\"\"\"\nfrom azure.storage.queue import QueueService\n\nfrom common.methods import set_progress\n\n\ndef run(job, **kwargs):\n resource = kwargs.pop(\"resources\").first()\n queue_name = resource.attributes.get(field__name=\"azure_storage_queue_name\").value\n azure_storage_account_name = resource.attributes.get(\n field__name=\"azure_storage_account_name\"\n ).value\n azure_account_key = resource.attributes.get(field__name=\"azure_account_key\").value\n set_progress(\"Connecting To Azure...\")\n queue_service = QueueService(\n account_name=azure_storage_account_name, account_key=azure_account_key\n )\n set_progress(\"Connection to Azure established\")\n\n set_progress(\"Deleting queue %s...\" % queue_name)\n queue_service.delete_queue(queue_name)\n\n return \"Success\", \"The queue has been deleted\", \"\"","repo_name":"CloudBoltSoftware/cloudbolt-forge","sub_path":"blueprints/azure_queue/delete.py","file_name":"delete.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"41"} +{"seq_id":"11218831568","text":"# 정보 선생님은 오늘도 이상한 출석을 부른다.\n#\n# 영일이는 오늘도 다른 생각을 해보았다.\n# 출석 번호를 다 부르지는 않은 것 같은데... 가장 빠른 번호가 뭐였지?\n#\n# 출석 번호를 n번 무작위로 불렀을 때, 가장 빠른 번호를 출력해 보자.\n\n\nn = int(input())\na = input().split()\nlist = []\nfor i in range(n):\n list.append(int(a[i]))\n\nlist.sort()\n\nprint(list[0])","repo_name":"sky7214sky72/Algorithm","sub_path":"기초100제/이상한 출석 번호 부르기3.py","file_name":"이상한 출석 번호 부르기3.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"8817213107","text":"from django.urls import path, include\n\nfrom .views import AdvList, AdvDetail, AdvReplyCreate, AdvCreate, AdvUpdate, AdvDelete, AdvReplyList\n\nurlpatterns = [\n path('', AdvList.as_view(), name='home'),\n path('<int:pk>', AdvDetail.as_view()),\n path('reply/', AdvReplyCreate.as_view()),\n path('create/<int:pk>', AdvCreate.as_view()),\n path('update/<int:pk>', AdvUpdate.as_view()),\n path('delete/<int:pk>', AdvDelete.as_view()),\n path('profile/', AdvReplyList.as_view()),\n]\n","repo_name":"keesulken/django_game_forum","sub_path":"project/forum/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"30571409707","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom rest_framework.routers import DefaultRouter\nfrom rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView\nfrom app import views\n\nrouter = DefaultRouter()\nrouter.register(r'adcopy', views.AdCopyViewSet, basename='adcopy')\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', views.index, name='index'),\n # for djoser_JWT\n path('auth/', include('djoser.urls')),\n path('auth/', include('djoser.urls.jwt')),\n path('accounts/', include('accounts.urls')),\n # for rest_framework\n path('api/', include(router.urls)),\n # path('api/adcopy/', views.ad_copy_api, name='ad_copy_api'),\n path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),\n path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),\n]","repo_name":"jeff0914/AI_adcopy_Generator","sub_path":"ad_gernerator/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"939093413","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def goodNodes(self, root: TreeNode) -> int:\n \n if not root:\n return 0\n \n count = [0]\n \n def helper(node, maxVal):\n curVal = maxVal\n if not node:\n return\n if node.val >= maxVal:\n count[0] += 1\n curVal = node.val\n helper(node.left, curVal)\n helper(node.right, curVal)\n \n count[0] += 1\n \n helper(root.left, root.val)\n helper(root.right, root.val)\n \n return count[0]","repo_name":"Claimundefine/LeetCode-Solutions","sub_path":"1448-count-good-nodes-in-binary-tree/1448-count-good-nodes-in-binary-tree.py","file_name":"1448-count-good-nodes-in-binary-tree.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"18379124584","text":"import re\nimport apimanager\nimport operator\n\nclass APIError(Exception):\n pass\n\n\n\ndef get_raw_text(text):\n q = re.sub('\\([^()]+\\)', '', text)\n q = re.sub('\\-.*', '', q)\n return q.strip()\n\ndef tag_search(self, option):\n track_ids = []\n key = self.apiManager.map_type(option)\n search_result1 = self.apiManager.search_tag(key)['tags']\n tag_id = str(search_result1[0]['tagId'])\n search_result2 = self.apiManager.get_tag_track(tag_id)\n string = search_result2['contentIds'].split(',')\n for i in string:\n track_ids.append(i[6:])\n return track_ids\n\n\nclass TypesAPI:\n\t\n def __init__(self, apiManager):\n if isinstance(apiManager, str):\n apiManager = apimanager.APIManager(apiManager)\n assert isinstance(apiManager, apimanager.APIManager)\n self.apiManager = apiManager\n\n # album, artist, track\n def album(self):\n track_ids = []\n album = self.apiManager.map_type('album')\n search_result = self.apiManager.search_track(album)\n for obj in search_result['tracks']:\n track_ids.append(str(obj['trackId']))\n return track_ids\n\n def artist(self):\n track_ids = []\n artist = self.apiManager.map_type('artist')\n search_result = self.apiManager.search_track(artist)\n for obj in search_result['tracks']:\n track_ids.append(str(obj['trackId']))\n return track_ids\n\n def track(self):\n track = self.apiManager.map_type('track')\n search_result = self.apiManager.search_track(track)\n\n #titles = [get_raw_text(rep['trackTitle'])]\n rep = search_result['tracks'][0]\n artists = [get_raw_text(rep['artists'][0]['artistName'])]\n # 초기화\n track_ids = []\n\n for obj in search_result['tracks']:\n artist_name = obj['artists'][0]['artistName']\n track_title = obj['trackTitle']\n if artist_name not in artists and track_title.find('Inst') == -1 and track_title.find(\"mr\") == -1:\n artists.append(artist_name)\n track_ids.append(str(obj['trackId']))\n\n return track_ids\n\n def album_artist(self):\n track_ids = []\n album = self.apiManager.map_type('album')[0]\n artist = self.apiManager.map_type('artist')[0]\n query = album + \" \" + artist\n print (\"typesApi query: \", query)\n search_result = self.apiManager.search_track(query)\n\n for obj in search_result['tracks']:\n track_ids.append(str(obj['trackId']))\n return track_ids\n\n def album_track(self):\n album = self.apiManager.map_type('album')[0]\n track = self.apiManager.map_type('track')[0]\n query = album + \" \" + track\n search_result = self.apiManager.search_track(query)\n\n rep = search_result['tracks'][0]\n artists = [get_raw_text(rep['artists'][0]['artistName'])]\n # 초기화\n track_ids = []\n\n for obj in search_result['tracks']:\n artist_name = obj['artists'][0]['artistName']\n track_title = obj['trackTitle']\n if artist_name not in artists and track_title.find('Inst') == -1 and track_title.find(\"mr\") == -1:\n artists.append(artist_name)\n track_ids.append(str(obj['trackId']))\n\n return track_ids\n\n def artist_track(self):\n artist = self.apiManager.map_type('artist')[0]\n track = self.apiManager.map_type('track')[0]\n query = artist + \" \" + track\n search_result = self.apiManager.search_track(query)\n\n rep = search_result['tracks'][0]\n artists = [get_raw_text(rep['artists'][0]['artistName'])]\n\n # 초기화\n track_ids = []\n\n for obj in search_result['tracks']:\n track_title = obj['trackTitle']\n artist_name = obj['artists'][0]['artistName']\n if artist_name not in artists and track_title.find('Inst') == -1 and track_title.find(\"MR\") == -1:\n artists.append(artist_name)\n track_ids.append(str(obj['trackId']))\n\n print(track_ids)\n return track_ids\n\n def album_artist_track(self):\n album = self.apiManager.map_type('album')[0]\n artist = self.apiManager.map_type('artist')[0]\n track = self.apiManager.map_type('track')[0]\n query = album + \" \" + artist + \" \" + track\n search_result = self.apiManager.search_track(query)\n\n\n rep = search_result['tracks'][0]\n artists = [get_raw_text(rep['artists'][0]['artistName'])]\n # 초기화\n track_ids = []\n\n for obj in search_result['tracks']:\n artist_name = obj['artists'][0]['artistName']\n track_title = obj['trackTitle']\n if artist_name not in artists and track_title.find('Inst') == -1 and track_title.find(\"mr\") == -1:\n artists.append(artist_name)\n track_ids.append(str(obj['trackId']))\n\n return track_ids\n\n # context 기본\n def artistGender(self):\n return tag_search(self, 'artistGender')\n\n def artistType(self):\n return tag_search(self, 'artistType')\n\n def context(self):\n return tag_search(self, 'context')\n\n def country(self):\n return tag_search(self, 'country')\n\n def genre(self):\n return tag_search(self, 'genre')\n\n def instrument(self):\n return tag_search(self, 'instrument')\n\n def language(self):\n return tag_search(self, 'language')\n\n def lyricist(self):\n return tag_search(self, 'lyricist')\n\n def movie(self):\n return tag_search(self, 'movie')\n\n def time(self):\n return tag_search(self, 'time')\n\n def tvProgram(self):\n return tag_search(self, 'tvProgram')\n\n # context 심화\n def album_context(self):\n return tag_search(self, 'context')\n\n def artist_context(self):\n # 방법 1 : context로 track_ids 가져온 후 각 id별로 artist 일치 여부 검사하는 방법\n artist = self.apiManager.map_type('artist')\n track_ids = tag_search(self, 'context')\n for i in track_ids:\n track_detail = self.apiManager.get_track(i)\n if(track_detail['tracks'][0]['artists'][0]['artistName'] == artist) :\n return i\n\n # 방법 2 : API가 부족하다 ...\n\n return False\n\n def artist_genre(self):\n return 1\n\n def artistType_context(self):\n return 1\n\n def context_track(self):\n return TypesAPI.track(self)\n\n\n\n\n def exclude_artist_album(self):\n track_ids = []\n album = self.apiManager.map_type('album')[0]\n artist = self.apiManager.map_type('artist')[0]\n\n album_result = self.apiManager.search_album(artist) # 앨범 리스트\n \n for _album_id in album_result['albums'] :\n album_id = _album_id['albumId']\n search_result = self.apiManager.get_album_tracks(album_id)\n for obj in search_result['tracks']:\n #if obj['trackId'] != played_track_ids\n track_ids.append(str(obj['trackId']))\n\t\t\t\t\n return track_ids\n\n# 아티스트 재생했을때, 나온곡 말고 다른곡. -> 앨범을 돌면서 재생(나온 trackid 제외)\n# 앨범 재생했을때 -> 다른 앨범 재생 (위에꺼와 병합 가능.) \n# 아티스트는 고정. 앨범만 순환(어떻게 순환하지? 랜덤? 순차적으로?)\n# 앨범 돌면서 재생된 list에 있는 트랙은 제외함. (for문으로 모든 current_track_ids list 비교하면서 지나가게)\n\n\n\n def update_tracklist(self, playedlist):\n tracks = ','.join(playedlist)\n json_data = self.apiManager.get_multiple_tracks(tracks)\n genres = [track['album']['albumGenres'] for track in json_data['tracks']]\n\n genre_dic = {}\n for genre in genres:\n g = genre.split(',')\n for _g in g:\n genre_dic[_g] = genre_dic.get(_g, 0) + 1\n\n top_genre = sorted(genre_dic.items(), key=operator.itemgetter(1), reverse=True)[0][0]\n top100_data = self.apiManager.get_genre_top100(top_genre)\n\n track_ids = [str(track['trackId']) for track in top100_data['chart']['tracks']]\n return track_ids\n\n","repo_name":"JinYoung-Shin/Music_Recommendation-NAVER","sub_path":"typesAPI.py","file_name":"typesAPI.py","file_ext":"py","file_size_in_byte":8186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"33466847794","text":"#!/usr/bin/python -tt\n\n\"\"\"\nLG Optimus Exceed 2 VS450PP (w5c) bootloader unlock tool\n\"\"\"\nimport argparse\nimport utils\nimport gui_utils\nimport Tkinter as tk\nimport ttk\nimport tkMessageBox\n\nclass unlock_gui(tk.Tk):\n \"\"\"\n GUI code executed when no command line parameters were provided. \n \"\"\"\n def __init__(self,parent):\n tk.Tk.__init__(self,parent)\n self.output_window = None\n self.adb_status = None\n self.fastboot_status = None\n self.file_status = None\n self.parent = parent\n self.resizable(0,0)\n self.grid()\n self.actions()\n self.status()\n self.output()\n self.check_tools()\n\n def actions(self):\n \"\"\"\n Creates the action buttons of the gui\n \"\"\"\n # Allow grid auto resize \n self.grid_rowconfigure(0, weight=1)\n self.grid_columnconfigure(0, weight=1)\n \n # Actions label frame\n gui_actions = ttk.LabelFrame(self, text=\"Unlocker Actions\")\n gui_actions.grid(row=0, column=0, padx=5, pady=5, sticky=\"NSEW\")\n\n # Allow grid auto resize \n gui_actions.grid_rowconfigure(0, weight=1)\n gui_actions.grid_columnconfigure(0, weight=1)\n gui_actions.grid_rowconfigure(0, weight=1)\n gui_actions.grid_columnconfigure(1, weight=1)\n gui_actions.grid_rowconfigure(1, weight=1)\n gui_actions.grid_columnconfigure(0, weight=1)\n gui_actions.grid_rowconfigure(1, weight=1)\n gui_actions.grid_columnconfigure(1, weight=1)\n gui_actions.grid_rowconfigure(2, weight=1)\n gui_actions.grid_columnconfigure(0, weight=1)\n gui_actions.grid_rowconfigure(2, weight=1)\n gui_actions.grid_columnconfigure(1, weight=1)\n\n # Create Unlock button\n tk.Button(gui_actions, text=u\"Unlock Bootloader\", width=20, height=2, command = utils.fastboot).grid(row=0, column=0, padx=10, pady=10)\n\n # Create Lock button\n tk.Button(gui_actions, text=u\"Lock Bootloader\", width=20, height=2, command = utils.fastboot).grid(row=0, column=1, padx=10, pady=10)\n\n # Create Fastboot button\n tk.Button(gui_actions, text=u\"Fastboot Mode\", width=20, height=2, command = utils.fastboot).grid(row=1, column=0, padx=10, pady=10)\n\n # Create Download button\n tk.Button(gui_actions, text=u\"Download Mode\", width=20, height=2, command = utils.fastboot).grid(row=1, column=1, padx=10, pady=10)\n\n # Create Root button\n tk.Button(gui_actions, text=u\"Root Device\", width=20, height=2, command = utils.fastboot).grid(row=2, column=0, padx=10, pady=10)\n\n # Create UnRoot button\n tk.Button(gui_actions, text=u\"Un-Root Device\", width=20, height=2, command = utils.fastboot).grid(row=2, column=1, padx=10, pady=10)\n\n\n def status(self):\n # Actions label frame\n tool_status = ttk.LabelFrame(self, text=\"Dependencies Status\")\n tool_status.grid(row=0, column=1, padx=5, pady=5, sticky=\"NSEW\")\n\n # Allow grid auto resize \n tool_status.grid_rowconfigure(0, weight=1)\n tool_status.grid_columnconfigure(1, weight=1)\n tool_status.grid_rowconfigure(1, weight=1)\n tool_status.grid_columnconfigure(1, weight=1)\n tool_status.grid_rowconfigure(2, weight=1)\n tool_status.grid_columnconfigure(1, weight=1)\n\n # Create Unlock button\n ttk.Label(tool_status, text=\"Adb:\").grid(row=0, column=0, sticky=\"E\")\n self.adb_status = tk.Frame(tool_status, bg=\"#EE0000\")\n self.adb_status.confirmed = False\n self.adb_status.grid(row=0, column=1, sticky=\"NSEW\", padx=5, pady=10)\n \n ttk.Label(tool_status, text=\"Fastboot:\").grid(row=1, column=0, sticky=\"E\")\n self.fastboot_status = tk.Frame(tool_status, bg=\"#EE0000\")\n self.fastboot_status.grid(row=1, column=1, sticky=\"NSEW\", padx=5, pady=10)\n self.fastboot_status.confirmed = False\n\n ttk.Label(tool_status, text=\"Install Files:\").grid(row=2, column=0, sticky=\"E\")\n self.file_status = tk.Frame(tool_status, bg=\"#EE0000\")\n self.file_status.grid(row=2, column=1, sticky=\"NSEW\", padx=5, pady=10)\n self.file_status.confirmed = False\n self.file_status.configure(background=\"#009900\")\n\n def output(self):\n # Allow grid to auto resize \n self.grid_rowconfigure(1, weight=1)\n self.grid_columnconfigure(0, weight=1)\n\n # Output label frame\n output_frame = ttk.LabelFrame(self, text=\"Unlocker Output\")\n output_frame.grid(row=1, column=0, columnspan=2, padx=5, pady=5, ipadx=8, ipady=8, sticky=\"NSEW\")\n\n # Create output window\n self.output_window = gui_utils.ScrolledTextReadOnly(output_frame, height=10)\n self.output_window.insert(tk.INSERT, \"A\" * 1000 + \"\\n\")\n output_frame.grid_rowconfigure(0, weight=1)\n output_frame.grid_columnconfigure(0, weight=1)\n self.output_window.grid(row=0, column=0)\n\n def check_tools(self):\n \"\"\"\n Checks that dependencies are installed\n \"\"\"\n #self.adb_status, self.fastboot_status, self.file_status = utils.check_dependencies()\n var = tkMessageBox.askokcancel(\"Download Dependencies\", \"Dependency tools and files not found. Download them now?\")\n\ndef main():\n try:\n # Create command line argument parser.\n parser = argparse.ArgumentParser(description=\"LG Optimus Exceed 2 VS450PP (w5c) Bootloader Unlock Tool\", version=('%(prog)s 0.1'))\n parser.add_argument('-u', '--unlock', action='store_true', default=False, dest=\"unlock_bootloader\", help=\"Unlock Optimus Exceed 2 bootloader\")\n parser.add_argument('-l', '--lock',action='store_true', default=False, dest=\"lock_bootloader\", help=\"Lock Optimus Exceed 2 bootloader\")\n parser.add_argument('-f', '--fastboot-mode', action='store_true', default=False, dest=\"fastboot_mode\", help=\"Set Optimus Exceed 2 to fastboot mode\")\n parser.add_argument('-d', '--download-mode', action='store_true', default=False, dest=\"download_mode\", help=\"Set Optimus Exceed 2 to download mode\")\n parser.add_argument('-r', '--root', action='store_true', default=False, dest=\"root_device\", help=\"Root Optimus Exceed 2\")\n parser.add_argument('-x', '--unroot', action='store_true', default=False, dest=\"unroot_device\", help=\"Un-Root Optimus Exceed 2\")\n\n # Parse the command line arguments.\n args = parser.parse_args()\n\n # Handle command line arguments if provided else start the GUI\n if args.unlock_bootloader:\n unlock_bootloader( )\n elif args.lock_bootloader:\n utils.lock_bootloader()\n elif args.fastboot_mode:\n utils.fastboot_mode()\n elif args.download_mode:\n utils.download_mode()\n elif args.root_device:\n utils.download_mode()\n elif args.unroot_device:\n utils.download_mode()\n else:\n app = unlock_gui(None)\n app.title('LG Optimus Exceed 2 Unlocker')\n app.mainloop()\n except KeyboardInterrupt:\n sys.exit(1)\n\n# This is the standard boilerplate that calls the main() function.\nif __name__ == '__main__':\n main()","repo_name":"reverse0x90/w5c_unlocker","sub_path":"w5c_unlock.py","file_name":"w5c_unlock.py","file_ext":"py","file_size_in_byte":6655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"71756337724","text":"\n\n\nif __name__ == '__main__':\n vendor = input()\n tv_height = int(input())\n tv_width = int(input())\n\n if vendor in (\"Sony\", \"LG\", \"Samsung\"):\n if tv_height <= 130 and tv_width <= 140:\n print(\"Подходит\")\n else:\n print(\"Ok\")\n else:\n print(\"Not ok\")\n\n","repo_name":"AvdeevArtem/PythonSlurm","sub_path":"2/If.py","file_name":"If.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"35111279847","text":"import socketserver\r\nimport socket\r\nimport datetime\r\nimport os\r\n\r\nimport consts as c\r\nfrom fileIO import FileIO\r\n\r\n# Finish sometime\r\nservice_threshold_min = 5\r\nservice_threshold_number = 500\r\nserviceID_instances_and_time = {}\r\n\r\n\r\ndef get_ip():\r\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n try:\r\n # doesn't even have to be reachable\r\n s.connect(('10.255.255.255', 1))\r\n IP = s.getsockname()[0]\r\n except Exception:\r\n IP = '127.0.0.1'\r\n finally:\r\n s.close()\r\n return IP\r\n\r\n\r\n# Most of the time there will be data\r\n# Add NA to columns that have no data\r\ndef add_na(msg):\r\n for i in range(len(c.Beautify_FW_Parser) - len(msg) - 2):\r\n msg.append('0')\r\n return msg\r\n\r\n\r\ndef get_proto(msg):\r\n return c.proto[int(msg.split(' proto=')[1].split(' ')[0])]\r\n\r\n\r\n# Parse FireWall logs based on saved keys\r\ndef msg_to_arr(msg):\r\n arr = []\r\n if \"traffic\" in msg.split(' type=')[1].split(' ')[0]:\r\n for line in msg.split(' '):\r\n temp = line.split('=')\r\n if len(temp) > 1:\r\n key, val = temp[0], temp[1]\r\n if key in c.Syslog_FW_Parser:\r\n arr.append(val.replace('\"', ''))\r\n arr.insert(4, get_proto(msg))\r\n return arr\r\n\r\n\r\n# Dumb function to find error codes from syslog\r\ndef find_code(code):\r\n fac = c.Facility[int(code / 8)]\r\n sav = c.Severity[code % 8]\r\n string = 'x.y'.replace('x', fac).replace('y', sav)\r\n return string\r\n\r\n\r\n# Parse windows service ID\r\ndef parse_windows_event_code(msg):\r\n temp = (msg.split()[5])[:-1]\r\n if str(temp).isdigit():\r\n return temp\r\n else:\r\n return -1\r\n\r\n\r\n# Parse windows service severity and service description\r\ndef parse_windows_event(msg):\r\n service_id = parse_windows_event_code(msg)\r\n event = \"\"\r\n if service_id != -1:\r\n if service_id in c.event_id:\r\n event = c.event_id[service_id]\r\n\r\n # Add service ID and their amounts during a short period of time\r\n if str(service_id) not in serviceID_instances_and_time.keys():\r\n serviceID_instances_and_time[str(service_id)] = \"0, \" + datetime.datetime.now().strftime(\"%H:%M:%S\")\r\n\r\n serviceID_instances_and_time[str(service_id)] = \\\r\n str(int(serviceID_instances_and_time[str(service_id)].split(',')[0]) + 1) + ',' + \\\r\n serviceID_instances_and_time[str(service_id)].split(',')[1]\r\n\r\n # Print services with high severity\r\n service_warn_show(event, service_id)\r\n\r\n return service_id, event\r\n\r\n\r\n# Function to show up alerts when the same service has been occurred multiple times in a specific threshold\r\ndef service_warn_show(event, service_id):\r\n if event != \"\":\r\n if \"Critical\" in event:\r\n print(\"Critical ALERT!!!\")\r\n print(event, str(service_id))\r\n elif \"Low\" in event and int(serviceID_instances_and_time[str(service_id)].split(',')[0]) \\\r\n >= service_threshold_number:\r\n print(\"Warning ALERT!!!\")\r\n print(event, str(service_id))\r\n\r\n\r\n# Function to reArm the counter to services\r\ndef service_remove_old_messages():\r\n for service in serviceID_instances_and_time:\r\n key, val = service\r\n if int(datetime.datetime.now().strftime(\"%H:%M\").split(':')[1]) - \\\r\n int(val.split(',')[1].split(':')[1].split(':')[0]) > service_threshold_min:\r\n serviceID_instances_and_time[str(key)] = \"0, \" + datetime.datetime.now().strftime(\"%H:%M:%S\")\r\n\r\n\r\n# Packet handler\r\nclass SyslogHandler(socketserver.BaseRequestHandler):\r\n print(\"Syslog Handler Created!\")\r\n\r\n def handle(self):\r\n\r\n # Decode Message\r\n recv_msg = self.request[0].decode(\"utf-8\")\r\n message = recv_msg.split('>')[1]\r\n line = \"\"\r\n syslg_file = 0\r\n log_type = \"\"\r\n # Firewall logs\r\n if \"192.168.68.121\" in self.client_address or \"10.0.1.254\" in self.client_address or \\\r\n \"10.0.2.254\" in self.client_address or \"10.0.3.254\" in self.client_address or \\\r\n \"10.0.4.254\" in self.client_address:\r\n log_type = \"Firewall Package!\"\r\n line = [datetime.datetime.today().strftime(\"%d/%m/%Y\"), datetime.datetime.now().strftime(\"%H:%M:%S\")]\r\n\r\n syslg_file = FileIO(c.FW_FILE_NAME, 'a')\r\n # print(message)\r\n msg = msg_to_arr(message)\r\n if len(msg) > 0:\r\n line.extend(add_na(msg))\r\n else:\r\n syslg_file = 0\r\n\r\n # Windows logs\r\n elif \"10.0.2.1\" in str(self.client_address[0]):\r\n log_type = \"Windows Package!\"\r\n\r\n code = find_code(int(recv_msg.split('<')[1].split('>')[0]))\r\n line = [datetime.datetime.today().strftime(\"%d/%m/%Y\"), datetime.datetime.now().strftime(\"%H:%M:%S\"),\r\n self.client_address[0], code]\r\n\r\n service_id, event = parse_windows_event(message)\r\n\r\n # Check if service exists\r\n if event != \"\":\r\n syslg_file = FileIO(c.WIN_FILE_NAME, 'a')\r\n line.append(service_id)\r\n line.append(event.split(',')[0])\r\n line.append(event.split(',')[1][1:])\r\n else:\r\n print(\"Got from Unknown end point\")\r\n\r\n # Write to file and close file if the service id is in consts or firewall message\r\n if syslg_file != 0:\r\n print(\"Got \", log_type)\r\n syslg_file.write_to_file(line)\r\n syslg_file.close_file()\r\n del syslg_file\r\n\r\n\r\n# Main program\r\nif __name__ == \"__main__\":\r\n try:\r\n print(\"Starting...\")\r\n # Set default start for file (Could be ran 1st time only)\r\n\r\n # Create windows csv log file\r\n if not os.path.exists(c.WIN_FILE_NAME):\r\n syslog_file = FileIO(c.WIN_FILE_NAME, 'w')\r\n syslog_file.write_to_file(c.Syslog_Windows_Parser)\r\n syslog_file.close_file()\r\n\r\n # Create FireWall csv log file\r\n if not os.path.exists(c.FW_FILE_NAME):\r\n syslog_file = FileIO(c.FW_FILE_NAME, 'w')\r\n syslog_file.write_to_file(c.Beautify_FW_Parser)\r\n syslog_file.close_file()\r\n\r\n print(\"Files are created successfully\")\r\n # Generic get ip from any linux computer\r\n # ip = socket.gethostbyname(socket.gethostname() + \".local\")\r\n # Get ip for Windows and Linux computer\r\n ip = get_ip()\r\n server = socketserver.UDPServer((ip, c.SYS_PORT), SyslogHandler)\r\n print(\"Launched Listener on \" + str(ip) + \"\\n\")\r\n # Start listening\r\n server.serve_forever()\r\n # Exit program if cannot open/create the file\r\n except (IOError, SystemExit):\r\n print(\"Error loading or creating files. \\r\\nShutting down.\")\r\n raise\r\n\r\n # Set default exit method\r\n except KeyboardInterrupt:\r\n server.server_close()\r\n print(\"Crtl+C Pressed. \\r\\nShutting down.\")\r\n","repo_name":"shak11/SIEM","sub_path":"sys_logger.py","file_name":"sys_logger.py","file_ext":"py","file_size_in_byte":6960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"25941061689","text":"import json, os, random, math\nfrom collections import defaultdict\n\nimport torch\nfrom torch.utils.data import Dataset\nimport torchvision.transforms as T\nimport math\nimport numpy as np\nimport PIL\nfrom skimage.transform import resize as imresize\nimport pycocotools.mask as mask_utils\nimport glob\nfrom PIL import Image, ImageDraw, ImageOps\nimport matplotlib.pyplot as plt\nimport random\nfrom utils import mask_to_bb, ROOM_CLASS \nsets = {'A':[1, 3], 'B':[4, 6], 'C':[7, 9], 'D':[10, 12], 'E':[13, 100]}\n\ndef filter_graphs(graphs, min_h=0.03, min_w=0.03):\n new_graphs = []\n for g in graphs:\n \n # retrieve data\n rooms_type = g[0]\n rooms_bbs = g[1]\n \n # discard broken samples\n check_none = np.sum([bb is None for bb in rooms_bbs])\n check_node = np.sum([nd == 0 for nd in rooms_type])\n if (len(rooms_type) == 0) or (check_none > 0) or (check_node > 0):\n continue\n \n # filter small rooms\n tps_filtered = []\n bbs_filtered = []\n for n, bb in zip(rooms_type, rooms_bbs):\n h, w = (bb[2]-bb[0]), (bb[3]-bb[1])\n if h > min_h and w > min_w:\n tps_filtered.append(n)\n bbs_filtered.append(bb)\n \n # update graph\n g_new = [tps_filtered, bbs_filtered]\n new_graphs.append(g_new)\n return new_graphs\n\nclass FloorplanGraphDataset(Dataset):\n\tdef __init__(self, shapes_path, transform=None, target_set=None, split='train'):\n\t\tsuper(Dataset, self).__init__()\n\t\tself.shapes_path = shapes_path\n\t\tself.split = split\n\t\tself.target_set = target_set\n\t\tif split == 'train':\n\t\t\tself.subgraphs = np.load('{}/train_data.npy'.format(self.shapes_path), allow_pickle=True)\n\t\t\tself.augment = True\n\t\telif split == 'eval':\n\t\t\tself.subgraphs = np.load('{}/train_data.npy'.format(self.shapes_path), allow_pickle=True)\n\t\t\tself.augment = False\n\t\telse:\n\t\t\tprint('Error split not supported') \n\t\t\texit(1)\n\t\tself.transform = transform\n\t\tself.subgraphs = filter_graphs(self.subgraphs)\n \n\t\t# filter samples\n\t\tmin_N = sets[self.target_set][0]\n\t\tmax_N = sets[self.target_set][1]\n\t\tfiltered_subgraphs = []\n\t\tfor g in self.subgraphs:\n\t\t\trooms_type = g[0] \n\t\t\tin_set = (len(rooms_type) >= min_N) and (len(rooms_type) <= max_N)\n\t\t\tif (split == 'train') and (in_set == False):\n\t\t\t\tfiltered_subgraphs.append(g)\n\t\t\telif (split == 'eval') and (in_set == True):\n\t\t\t\tfiltered_subgraphs.append(g)\n\t\tself.subgraphs = filtered_subgraphs\n\t\tif split == 'eval':\n\t\t\tself.subgraphs = self.subgraphs[:5000] # max 5k\n\t\tprint(len(self.subgraphs)) \n \n\t\t# doblecheck\n\t\tdeb_dic = defaultdict(int)\n\t\tfor g in self.subgraphs:\n\t\t\trooms_type = g[0] \n\t\t\tif len(rooms_type) > 0:\n\t\t\t\tdeb_dic[len(rooms_type)] += 1\n\t\tprint(\"target samples:\", deb_dic)\n \n\tdef __len__(self):\n\t\treturn len(self.subgraphs)\n\n\tdef __getitem__(self, index):\n\n\t\t# load data\n\t\tgraph = self.subgraphs[index]\n\t\trooms_type = graph[0]\n\t\trooms_bbs = graph[1]\n\n\t\tif self.augment:\n\t\t\trot = random.randint(0, 3)*90.0\n\t\t\tflip = random.randint(0, 1) == 1\n\t\t\trooms_bbs_aug = []\n\t\t\tfor bb in rooms_bbs:\n\t\t\t\tx0, y0 = self.flip_and_rotate(np.array([bb[0], bb[1]]), flip, rot)\n\t\t\t\tx1, y1 = self.flip_and_rotate(np.array([bb[2], bb[3]]), flip, rot)\n\t\t\t\txmin, ymin = min(x0, x1), min(y0, y1)\n\t\t\t\txmax, ymax = max(x0, x1), max(y0, y1)\n\t\t\t\trooms_bbs_aug.append(np.array([xmin, ymin, xmax, ymax]).astype('int'))\n\t\t\trooms_bbs = rooms_bbs_aug\n\t\trooms_bbs = np.stack(rooms_bbs)\n\n# \t\t# make orderFloorplanDataset\n# \t\torder_inds = [x[0] for x in sorted(enumerate(rooms_bbs), key=lambda bb:bb[1][1] + bb[1][0] * 256)]\n# \t\trooms_bbs = rooms_bbs[order_inds]/256.0\n# \t\trooms_type = [rooms_type[i] for i in order_inds]\n\t\trooms_bbs = rooms_bbs/256.0\n\n\t\t# extract boundary box and centralize\n\t\ttl = np.min(rooms_bbs[:, :2], 0)\n\t\tbr = np.max(rooms_bbs[:, 2:], 0)\n\t\tshift = (tl+br)/2.0 - 0.5\n\t\trooms_bbs[:, :2] -= shift\n\t\trooms_bbs[:, 2:] -= shift\n\t\ttl -= shift\n\t\tbr -= shift\n\t\tboundary_bb = np.concatenate([tl, br])\n\n\t\t# build input graph\n\t\trooms_bbs, nodes, edges = self.build_graph(rooms_bbs, rooms_type) \n\t\tim_size = 32\n\t\trooms_mks = np.zeros((nodes.shape[0], im_size, im_size))\n\t\tfor k, (rm, bb) in enumerate(zip(nodes, rooms_bbs)):\n\t\t\tif rm > 0:\n\t\t\t\tx0, y0, x1, y1 = im_size*bb\n\t\t\t\tx0, y0, x1, y1 = int(x0), int(y0), int(x1), int(y1)\n\t\t\t\trooms_mks[k, x0:x1+1, y0:y1+1] = 1.0\n\t\t\n\t\tnodes = one_hot_embedding(nodes)[:, 1:]\n\t\tnodes = torch.FloatTensor(nodes)\n\t\tedges = torch.LongTensor(edges)\n\t\trooms_mks = torch.FloatTensor(rooms_mks)\n\t\trooms_mks = self.transform(rooms_mks)\n\t\treturn rooms_mks, nodes, edges\n \n\tdef flip_and_rotate(self, v, flip, rot, shape=256.):\n\t\tv = self.rotate(np.array((shape, shape)), v, rot)\n\t\tif flip:\n\t\t\tx, y = v\n\t\t\tv = (shape/2-abs(shape/2-x), y) if x > shape/2 else (shape/2+abs(shape/2-x), y)\n\t\treturn v\n\t\n\t# rotate coords\n\tdef rotate(self, image_shape, xy, angle):\n\t\torg_center = (image_shape-1)/2.\n\t\trot_center = (image_shape-1)/2.\n\t\torg = xy-org_center\n\t\ta = np.deg2rad(angle)\n\t\tnew = np.array([org[0]*np.cos(a) + org[1]*np.sin(a),\n\t\t\t\t-org[0]*np.sin(a) + org[1]*np.cos(a) ])\n\t\tnew = new+rot_center\n\t\treturn new\n\n\tdef build_graph(self, bbs, types):\n\t\t# create edges -- make order\n\t\ttriples = []\n\t\tnodes = types\n\t\tbbs = np.array(bbs)\n \n\t\t# encode connections\n\t\tfor k in range(len(nodes)):\n\t\t\tfor l in range(len(nodes)):\n\t\t\t\tif l > k:\n\t\t\t\t\tnd0, bb0 = nodes[k], bbs[k]\n\t\t\t\t\tnd1, bb1 = nodes[l], bbs[l]\n\t\t\t\t\tif is_adjacent(bb0, bb1):\n\t\t\t\t\t\tif 'train' in self.split:\n\t\t\t\t\t\t\ttriples.append([k, 1, l])\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ttriples.append([k, 1, l])\n\t\t\t\t\telse:\n\t\t\t\t\t\tif 'train' in self.split:\n\t\t\t\t\t\t\ttriples.append([k, -1, l])\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ttriples.append([k, -1, l])\n\n\t\t# convert to array\n\t\tnodes = np.array(nodes)\n\t\ttriples = np.array(triples)\n\t\tbbs = np.array(bbs)\n\t\treturn bbs, nodes, triples\n\ndef _augment(mks):\n\n\tflip = random.choice([False, True])\n\trot = random.choice([0, 90, 180, 270])\n\tnew_mks = []\n\tfor m in mks:\n\t\tm_im = Image.fromarray(m.astype('uint8'))\n\t\tm_im = m_im.rotate(rot)\n\t\tif flip:\n\t\t\tm_im = m_im.transpose(PIL.Image.FLIP_LEFT_RIGHT)\n\t\tnew_mks.append(np.array(m_im))\n\tnew_mks = np.stack(new_mks)\n\n\treturn new_mks\n\ndef is_adjacent(box_a, box_b, threshold=0.03):\n\t\n\tx0, y0, x1, y1 = box_a\n\tx2, y2, x3, y3 = box_b\n\n\th1, h2 = x1-x0, x3-x2\n\tw1, w2 = y1-y0, y3-y2\n\n\txc1, xc2 = (x0+x1)/2.0, (x2+x3)/2.0\n\tyc1, yc2 = (y0+y1)/2.0, (y2+y3)/2.0\n\n\tdelta_x = np.abs(xc2-xc1) - (h1 + h2)/2.0\n\tdelta_y = np.abs(yc2-yc1) - (w1 + w2)/2.0\n\n\tdelta = max(delta_x, delta_y)\n\n\treturn delta < threshold\n\ndef one_hot_embedding(labels, num_classes=11):\n\t\"\"\"Embedding labels to one-hot form.\n\n\tArgs:\n\t labels: (LongTensor) class labels, sized [N,].\n\t num_classes: (int) number of classes.\n\n\tReturns:\n\t (tensor) encoded labels, sized [N, #classes].\n\t\"\"\"\n\ty = torch.eye(num_classes) \n\treturn y[labels] \n\ndef floorplan_collate_fn(batch):\n\tall_rooms_mks, all_nodes, all_edges = [], [], []\n\tall_node_to_sample, all_edge_to_sample = [], []\n\tnode_offset = 0\n\tfor i, (rooms_mks, nodes, edges) in enumerate(batch):\n\t\tO, T = nodes.size(0), edges.size(0)\n\t\tall_rooms_mks.append(rooms_mks)\n\t\tall_nodes.append(nodes)\n\t\tedges = edges.clone()\n\t\tif edges.shape[0] > 0:\n\t\t\tedges[:, 0] += node_offset\n\t\t\tedges[:, 2] += node_offset\n\t\t\tall_edges.append(edges)\n\t\tall_node_to_sample.append(torch.LongTensor(O).fill_(i))\n\t\tall_edge_to_sample.append(torch.LongTensor(T).fill_(i))\n\t\tnode_offset += O\n\tall_rooms_mks = torch.cat(all_rooms_mks, 0)\n\tall_nodes = torch.cat(all_nodes)\n\tif len(all_edges) > 0:\n\t\tall_edges = torch.cat(all_edges)\n\telse:\n\t\tall_edges = torch.tensor([]) \n\tall_node_to_sample = torch.cat(all_node_to_sample)\n\tall_edge_to_sample = torch.cat(all_edge_to_sample)\n\treturn all_rooms_mks, all_nodes, all_edges, all_node_to_sample, all_edge_to_sample\n\n","repo_name":"ennauata/housegan","sub_path":"floorplan_dataset_maps.py","file_name":"floorplan_dataset_maps.py","file_ext":"py","file_size_in_byte":7771,"program_lang":"python","lang":"en","doc_type":"code","stars":205,"dataset":"github-code","pt":"41"} +{"seq_id":"15386462021","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n## Module infomation ###\n# Python (3.4.4)\n# numpy (1.10.2)\n# PyAudio (0.2.9)\n# pyqtgraph (0.9.10)\n# PyQt4 (4.11.4)\n# All 32bit edition\n########################\n\nimport pyaudio\nimport numpy as np\nimport pyqtgraph as pg\nfrom pyqtgraph.Qt import QtGui, QtCore\nfrep = []\namp1 = []\nnum_fft = []\nclass SpectrumAnalyzer:\n FORMAT = pyaudio.paFloat32\n CHANNELS = 1\n RATE = 16000\n CHUNK = 1024\n START = 0\n N = 1024\n WAVE_RANGE = 1\n SPECTRUM_RANGE = 50\n UPDATE_SECOND = 10\n\n def __init__(self):\n #Pyaudio Configuration\n self.pa = pyaudio.PyAudio()\n self.stream = self.pa.open(format = self.FORMAT,\n channels = self.CHANNELS,\n rate = self.RATE,\n input = True,\n output = False,\n frames_per_buffer = self.CHUNK)\n \n # Graph configuration\n # Application\n self.app = QtGui.QApplication([])\n self.app.quitOnLastWindowClosed()\n # Window\n self.win = QtGui.QMainWindow()\n self.win.setWindowTitle(\"SpectrumAnalyzer\")\n self.win.resize(800, 600)\n self.centralwid = QtGui.QWidget()\n self.win.setCentralWidget(self.centralwid) \n # Layout\n self.lay = QtGui.QVBoxLayout()\n self.centralwid.setLayout(self.lay)\n # Wave figure window setting\n self.plotwid1 = pg.PlotWidget(name=\"wave\")\n self.plotitem1 = self.plotwid1.getPlotItem()\n self.plotitem1.setMouseEnabled(x = False, y = False) \n self.plotitem1.setYRange(self.WAVE_RANGE * -1, self.WAVE_RANGE * 1)\n self.plotitem1.setXRange(self.START, self.START + self.N, padding = 0)\n # Spectrum windows setting\n self.plotwid2 = pg.PlotWidget(name=\"spectrum\")\n self.plotitem2 = self.plotwid2.getPlotItem()\n self.plotitem2.setMouseEnabled(x = False, y = False) \n self.plotitem2.setYRange(0, self.SPECTRUM_RANGE)\n self.plotitem2.setXRange(0, self.RATE / 2, padding = 0)\n # Wave figure Axis\n self.specAxis1 = self.plotitem1.getAxis(\"bottom\")\n self.specAxis1.setLabel(\"Time [sample]\")\n # Spectrum Axis\n self.specAxis2 = self.plotitem2.getAxis(\"bottom\")\n self.specAxis2.setLabel(\"Frequency [Hz]\")\n #Plot data\n self.curve_wave = self.plotitem1.plot()\n self.curve_spectrum = self.plotitem2.plot()\n #Widget\n self.lay.addWidget(self.plotwid1)\n self.lay.addWidget(self.plotwid2)\n #Show plot window\n self.win.show()\n #Update timer setting\n self.timer = QtCore.QTimer()\n self.timer.timeout.connect(self.update)\n self.timer.start(self.UPDATE_SECOND)\n\n def update(self):\n #Get audio input\n data = self.audioinput()\n \n # Wave figure\n wave_figure = data[self.START:self.START + self.N]\n # Wave time\n wave_time = range(self.START, self.START + self.N)\n # Frequency\n freqlist = np.fft.fftfreq(self.N, d = 1.0 / self.RATE) \n # Spectrum power\n x = np.fft.fft(data[self.START:self.START + self.N])\n \n amplitudeSpectrum = [np.sqrt(c.real ** 2 + c.imag ** 2) for c in x]\n amp1.append(max(amplitudeSpectrum))\n \n frep_n = amplitudeSpectrum.index(max(amplitudeSpectrum))\n if freqlist[frep_n] < 0:\n freqlist[frep_n] = (-1)*freqlist[frep_n]\n frep.append(freqlist[frep_n])\n num_fft.append(len(frep))\n # Plot setdata\n self.curve_wave.setData(wave_time, wave_figure)\n self.curve_spectrum.setData(freqlist, amplitudeSpectrum)\n #csvファイルで保存\n import pandas as pd\n a = list(range(3))\n a[0] = num_fft\n a[1] = frep #周波数\n a[2] = amp1 #振幅\n df = pd.DataFrame(a)\n df.to_csv('fft31_kanjo.csv')\n\n def audioinput(self):\n ret = self.stream.read(self.CHUNK ,exception_on_overflow=False )\n ret = np.fromstring(ret, np.float32)\n\n return ret\n\nif __name__ == \"__main__\":\n spec = SpectrumAnalyzer()\n QtGui.QApplication.instance().exec_()\n # 認識結果を表示するためのライブラリを読み込む\n import matplotlib.cm as cm\n from PIL import Image\n import random\n import numpy as np\n \n #plot\n import matplotlib\n import matplotlib.pyplot as plt\n \n #plt.plot(\"x\",\"y\",\"オプション(marker=\"記号\", color = \"色\", linestyle = \"線の種類\")\")\n fig = plt.figure()\n ax1 = fig.add_subplot()\n \n ax2 = ax1.twinx()\n \n ax1.plot(num_fft, frep,color = \"blue\", label = \"Frequency\")\n ax2.plot(num_fft, amp1,color = \"red\", label = \"Amplitude spectrum\")\n ax1.set_title(\"Statistical data\") #タイトル\n ax1.set_xlabel(\"time\") #x軸ラベル\n ax1.set_ylabel(\"Frequency[Hz]\") #y軸ラベル\n ax2.set_ylabel(\"Amplitude spectrum[f]\") #y2軸ラベル\n \n h1, l1 = ax1.get_legend_handles_labels()\n h2, l2 = ax2.get_legend_handles_labels()\n ax1.legend(h1+h2, l1+l2 ,loc='lower right')\n \n #メモリの設定\n plt.xticks(np.arange(0, len(num_fft), step=50))\n ax1.set_yticks(np.arange(0, 8000, step=1000))\n ax2.set_yticks(np.arange(0, max(amp1), step=50))\n\n #補助線の設定\n plt.grid(True)\n \n #保存・表示\n plt.savefig(\"fft_result.jpg\")\n plt.show()","repo_name":"19238901/SagaUniv","sub_path":"Program/fft3.py","file_name":"fft3.py","file_ext":"py","file_size_in_byte":5376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"8058229429","text":"import json\nfrom random import random, randint\nimport time\n\nwaves = {\n \"data_type\": 8,\n \"version\": 1,\n \"mac_address\": \"0000000000000009\",\n \"time_zone\": \"Asia/Tokyo\",\n \"data\":[\n {\n \"time_unit_id\":10,\n \"timestamps\":[],\n \"waveforms\":[],\n \"diff\":[]\n }\n ]\n}","repo_name":"eddielinb/personal","sub_path":"detector_new/local_files/generator_waves.py","file_name":"generator_waves.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"15604344034","text":"def partition(data, low_index , high_index):\n i = low_index - 1\n pivot = data[high_index]\n\n for j in range(low_index , high_index):\n if data[j] < pivot:\n i += 1\n data[j] , data[i] = data[i] , data[j]\n data[i+1] , data[high_index] = data[high_index] , data[i+1]\n return (i+1)\n\n\ndef quickSort(data,low,high):\n if low < high:\n pi = partition(data,low,high)\n quickSort(data, low , pi-1)\n quickSort(data , pi+1 , high)\n\n","repo_name":"badshasha/datastructure","sub_path":"sorting_again/quicksort.py","file_name":"quicksort.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"34954447385","text":"from tkinter import Button, DoubleVar, Entry, IntVar, Label, Tk, W\n\n\ndef Laskeyhteen():\n yhteensa = DoubleVar()\n yhteensa = round(ekanumero.get()+tokanumero.get(),2)\n vastaus.config(text=\"Yhteensä: \"+str(yhteensa))\nikkuna = Tk()\nikkuna.title(\"Kahden luvun yhteenlaskeminen\")\n\n#\nikkuna.geometry(\"400x200\")\n\n#\nLabel(ikkuna, text=\"Annatko ensimäinen numeron:\").grid(row=0, sticky=W)\nLabel(ikkuna, text=\"Annatko toisen numeron:\").grid(row=1, sticky=W)\n#\nekanumero = DoubleVar()\ntokanumero = DoubleVar()\n\nluku1 = Entry(ikkuna, textvariable=ekanumero).grid(row=0, column=1)\nluku21 = Entry(ikkuna, textvariable=tokanumero).grid(row=1, column=1)\n\nlaskenappi = Button(ikkuna, text=\"Laske yhteen\", command=Laskeyhteen).grid(row=2, column=1)\nvastaus = Label(ikkuna)\nvastaus.grid(row=3, column=1)\n\nikkuna.mainloop()","repo_name":"dnnijmlinn/Python-Graphic-tasks-1-4","sub_path":"graafisen_teh1.py","file_name":"graafisen_teh1.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"fi","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"23567801118","text":"def model( fold ) :\n\n from lightgbm import LGBMClassifier\n import os\n from utils import plot_roc_curve, confusion_matrix\n import pandas as pd\n import numpy as np\n \n# 각 fold의 데이터 불균형도가 다름\n if fold == 1:\n scale_pos_weight = 8.5 #6.8\n elif fold == 2:\n scale_pos_weight = 6.4\n \n \n \n params = { 'random_state' : 42,\n 'scale_pos_weight' : scale_pos_weight,\n 'learning_rate' : 0.1, \n 'num_iterations' : 1000,\n 'max_depth' : 4,\n 'n_jobs' : 30,\n 'boost_from_average' : False,\n 'objective' : 'binary' }\n \n model = LGBMClassifier( **params )\n print( '{}번째 fold를 위한 모델이 준비되었습니다.'.format(fold) )\n return model\n\n\n\n\n\n\n","repo_name":"minmisue/Research-Stock-market-Data","sub_path":"modeling/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"33745362321","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jul 27 12:39:39 2023\r\n\r\n@author: Shahabedin Chatraee Azizabadi\r\nSonntagsfrage\r\n\"\"\"\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport time\r\nimport seaborn as sns\r\nfrom statsmodels.stats.weightstats import ztest as ztest\r\nimport statsmodels.stats.weightstats as ws\r\n#-----------------IMPORTANT NOTE----------------------\r\n# DEPENDING ON WHICH DATAFRAME IS USED WE HAVE TWO MAIN FEATURES THAT CAN ALTERNATIVALY REPLACE\r\n# feature1=\"sum_page_views\"or feature1= \"sum_total_seconds_spent\"\r\n#df=pd.read_csv(\"C:/Users/sazizaba/Music/SI_project/projects/Wochenendfrage/adobe_full_bild_grouped.csv\")\r\ndf=pd.read_csv(\"adobe_full_bild_grouped_time_spend.csv\")\r\ndf[\"date\"] = pd.to_datetime(df[\"date\"])\r\n\r\ndf[\"IsWeekend\"] = df[\"date\"].dt.weekday >= 5\r\n\r\n# some general stats\r\ngs=df.describe()\r\n# To count the sample size of week and weekend groups: They are almost equal\r\na=(df[\"IsWeekend\"] == False).sum() # The sample size of the week days\r\n\r\nb=(df[\"IsWeekend\"] == True).sum() # The sample size of the weekend days\r\n#-------------------------------------------------------------------------------\r\n\r\n# Splitting week and weekend samples\r\ndef week_weekend_spl(df):\r\n df_week=df.loc[df['IsWeekend'] == False]\r\n \r\n df_weekend=df.loc[df['IsWeekend'] == True]\r\n \r\n return df_week,df_weekend\r\n#<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\r\ndef avg_page_views(df,feature1):\r\n df_week,df_weekend=week_weekend_spl(df)\r\n # week_mean=df_week[\"sum_page_views\"].mean()\r\n # weekend_mean=df_weekend[\"sum_page_views\"].mean()\r\n week_mean=df_week[feature1].mean()\r\n weekend_mean=df_weekend[feature1].mean() \r\n week_std=df_week[feature1].std()\r\n weekend_std=df_weekend[feature1].std() \r\n return week_mean, weekend_mean, week_std, weekend_std\r\n#------------------------------------------------------------------------------------\r\ndf_week,df_weekend=week_weekend_spl(df)\r\n\r\n# Investigating the distribution of the character translated in control and test groups\r\ndef plot_dist(df,feature1):\r\n df_week,df_weekend=week_weekend_spl(df)\r\n f, ax = plt.subplots(1, 1)\r\n sns.distplot(getattr(df_week,feature1),label = 'week',ax=ax)\r\n sns.distplot(getattr(df_weekend,feature1),label = 'weekend',ax=ax)\r\n ax.legend()\r\n return\r\n\r\n# A significant Z-test for the number of characters translated, the size of samples are big enough for that test\r\ndef two_samp_z_test_charact(df,feature1):\r\n df_week,df_weekend=week_weekend_spl(df)\r\n z_stat, p_val= ztest(getattr(df_week,feature1),getattr(df_weekend,feature1),alternative='smaller')\r\n #z_stat, p_val= CompareMeans.ztest_ind(alternative='smaller', usevar='unequal')\r\n\r\n return z_stat, p_val\r\n# A more specific z-test for unequal stds\r\ndef alt_z_test(df,feature1):\r\n df_week,df_weekend=week_weekend_spl(df)\r\n col1 = ws.DescrStatsW(getattr(df_week,feature1))\r\n col2 = ws.DescrStatsW(getattr(df_weekend,feature1))\r\n\r\n cm_obj = ws.CompareMeans(col1, col2)\r\n\r\n zstat2, z_pval2 = cm_obj.ztest_ind(alternative='smaller',usevar='unequal')\r\n \r\n return zstat2, z_pval2\r\n#------------------------------------------------------------------------------------\r\n# mean of the page view for the week and weekend\r\nweek_mean, weekend_mean, week_std, weekend_std=avg_page_views(df,\"sum_total_seconds_spent\")\r\n# The result of z-test for the number of characters translated \r\nz_stat, p_val=two_samp_z_test_charact(df,\"sum_total_seconds_spent\")\r\nzstat2, z_pval2=alt_z_test(df,\"sum_total_seconds_spent\")\r\nplo=plot_dist(df,\"sum_total_seconds_spent\")\r\nprint(\"P-value for sum_of_..=\",p_val)\r\n","repo_name":"Shahabed/Statistical-Analysis","sub_path":"Weekend_users_hypo_test/Sonntagsfrage.py","file_name":"Sonntagsfrage.py","file_ext":"py","file_size_in_byte":3675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"19994474965","text":"#学习用python处理图片\r\nimport numpy as np #处理\r\nimport matplotlib.image as imger #读取\r\nimport matplotlib.pyplot as plt #显示\r\nimport numba as nb\r\ndef flip90_left(arr):\r\n arr=np.swapaxes(arr,0,1)\r\n arr=arr[::-1]\r\n return arr\r\ndef flip90_right(arr):\r\n arr=arr[::-1]\r\n arr=np.swapaxes(arr,0,1)\r\n return arr\r\n@nb.jit()\r\ndef edge(pic,pic1):\r\n Ly=pic.shape[0]\r\n Lx=pic.shape[1]\r\n for x in range(Lx-2):\r\n for y in range(Ly-2):\r\n for col in range(3):\r\n here=(4*pic[y+1,x+1,col]\r\n -pic[y+2,x+1,col]\r\n -pic[y+0,x+1,col]\r\n -pic[y+1,x+2,col]\r\n -pic[y+1,x+0,col])\r\n pic1[y,x,col]=here\r\n pic1=pic1*100\r\n pic1=np.maximum(0.01,pic1)\r\n pic1=np.minimum(0.99,pic1)\r\n return pic1\r\n\r\nfor _ in ['读取图像']:\r\n pic=imger.imread('40.png',)\r\n #pic=flip90_right(pic)\r\n pic=np.array(pic,order='F')\r\n #pic现在是一个array了\r\n #只获取红色\r\n Ly,Lx,Lcol=pic.shape\r\nfor _ in ['画矩形']:\r\n pic[:200,:100]-=0.5\r\nfor _ in 0*['改成有趣的shape']:\r\n #(460, 819, 3)\r\n print(pic.shape)\r\n Lx-=1\r\n pic=pic[:460,:818,]\r\n pic=np.array(pic)\r\n #pic.shape=(Ly*2,Lx//2,3)\r\n #pic.shape=(Ly//2,Lx*2,3)\r\n#提取边缘:\r\nfor _ in [0]:\r\n pic1=pic*0\r\n pic1[:,:,3]=pic[:,:,3]\r\n pic=edge(pic,pic1)\r\n pic=1-pic\r\npic2=(2*pic)**2/4\r\npic2=np.minimum(pic2,1)\r\npic=np.vstack((pic,pic2))\r\npic=np.hstack((pic,pic[:,:400]*1))\r\nfor _ in [0]:\r\n #pic=flip90_left(pic)\r\n pic=np.minimum(pic,0.99)\r\n pic=np.maximum(0.01,pic)\r\n pic[:,:,-1]=0.99\r\n plt.imshow(pic)\r\n #plt.axis('off') #不显示坐标轴\r\n plt.show()\r\n","repo_name":"dx2102/python-","sub_path":"图片处理学习.py","file_name":"图片处理学习.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"73061766203","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 19 20:13:46 2022\n\n@author: maslyaev\n\"\"\"\n\nfrom epde.preprocessing.smoothers import GaussianSmoother, ANNSmoother, PlaceholderSmoother\nfrom epde.preprocessing.deriv_calculators import AdaptiveFiniteDeriv, PolynomialDeriv, SpectralDeriv\n\nfrom epde.preprocessing.preprocessor import ConcretePrepBuilder\n\n\n\nclass PreprocessorSetup:\n def __init__(self):\n self._builder = None\n\n @property\n def builder(self):\n return self._builder\n\n @builder.setter\n def builder(self, builder: ConcretePrepBuilder):\n self._builder = builder\n\n def build_ANN_preprocessing(self, test_output=False, epochs_max=1e5,\n loss_mean=1000, batch_frac=0.8):\n smoother_args = ()\n smoother_kwargs = {'grid': None, 'epochs_max': epochs_max,\n 'loss_mean': loss_mean, 'batch_frac': batch_frac}\n\n deriv_calculator_args = ()\n deriv_calculator_kwargs = {'grid': None}\n\n self.builder.set_smoother(ANNSmoother, *smoother_args, **smoother_kwargs)\n self.builder.set_deriv_calculator(AdaptiveFiniteDeriv, *deriv_calculator_args,\n **deriv_calculator_kwargs)\n\n def build_spectral_preprocessing(self, n=None, steepness=1):\n smoother_args = ()\n smoother_kwargs = {}\n\n deriv_calculator_args = ()\n deriv_calculator_kwargs = {'grid': None, 'n': n, 'steepness': steepness}\n\n self.builder.set_smoother(PlaceholderSmoother, *smoother_args, **smoother_kwargs)\n self.builder.set_deriv_calculator(SpectralDeriv, *deriv_calculator_args,\n **deriv_calculator_kwargs)\n\n def build_poly_diff_preprocessing(self, use_smoothing=False, sigma=1, mp_poolsize=4,\n polynomial_window=9, poly_order=None, include_time=False):\n smoother_args = ()\n smoother_kwargs = {'sigma': sigma, 'include_time' : include_time}\n\n deriv_calculator_args = ()\n deriv_calculator_kwargs = {'grid': None, 'mp_poolsize': mp_poolsize, 'polynomial_window': polynomial_window,\n 'poly_order': poly_order}\n\n smoother = GaussianSmoother if use_smoothing else PlaceholderSmoother\n self.builder.set_smoother(smoother, *smoother_args, **smoother_kwargs)\n self.builder.set_deriv_calculator(PolynomialDeriv, *deriv_calculator_args,\n **deriv_calculator_kwargs)\n\n # def build_spectral_deriv_preprocessing(self, *args, **kwargs):\n # pass\n\n # def build_with_custom_deriv()\n","repo_name":"ITMO-NSS-team/EPDE","sub_path":"epde/preprocessing/preprocessor_setups.py","file_name":"preprocessor_setups.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"41"} +{"seq_id":"11793001392","text":"import json\r\nimport os\r\nimport pandas as pd\r\nfrom openpyxl import load_workbook\r\n\r\n\r\ndef get_sheetnames_xlsx(filepath):\r\n wb = load_workbook(filepath, read_only=True, keep_links=False)\r\n return wb.sheetnames\r\n\r\n\r\ndef build_dict(data_source, row):\r\n column = list(data_source.columns)\r\n dict_temp = {}\r\n for i in column:\r\n if '.' in i:\r\n key_parent = i[0:i.find('.')]\r\n key_child = i[i.find('.')+1:len(i)]\r\n if key_parent in dict_temp.keys():\r\n dict_temp[f'{key_parent}'].update(\r\n {f'{key_child}': f\"{data_source[f'{i}'][row]}\"})\r\n else:\r\n dict_temp.update(\r\n {f'{key_parent}': {f'{key_child}': f\"{data_source[f'{i}'][row]}\"}})\r\n else:\r\n dict_temp.update({f\"{i}\": f\"{data_source[f'{i}'][row]}\"})\r\n\r\n return dict_temp\r\n\r\n\r\ndef build_lookup(lookuplist, data_source, row):\r\n lookup_temp = {}\r\n for i in lookuplist:\r\n lookup_temp.update({f\"{i}\": f\"{data_source[f'{i}'][row]}\"})\r\n return lookup_temp\r\n\r\n\r\ndef convert_xlsx(template_file):\r\n # from .import build_dict\r\n source_to_import = {\"onFailure\": \"ABORT\", \"operations\": []}\r\n endpoint_list = get_sheetnames_xlsx(template_file)\r\n# api_objects = pd.read_csv(\r\n# 'api_objects.csv', dtype=str)\r\n for endpoint in endpoint_list:\r\n data_source = pd.read_excel(\r\n io=template_file,\r\n engine=\"openpyxl\",\r\n sheet_name=f'{endpoint}',\r\n dtype=str\r\n )\r\n # lookup = api_objects.loc[api_objects['endpoint']\r\n # == endpoint, 'lookup'].item()\r\n # lookup_list = lookup.split(\",\")\r\n lookup_list = []\r\n for col in data_source.columns:\r\n if \"*\" in col:\r\n col = col.replace(\"*\", \"\")\r\n lookup_list.append(col)\r\n\r\n data_source.columns = data_source.columns.str.replace(\"*\", \"\")\r\n data_source.fillna('', inplace=True)\r\n total_source = len(data_source[data_source.columns[0]])\r\n for i in range(total_source):\r\n data_temp = build_dict(data_source, i)\r\n lookup_temp = build_lookup(lookup_list, data_source, i)\r\n source_to_import['operations'].append({'lookup': lookup_temp,\r\n 'action': 'REPLACE', 'resource': f'{endpoint}',\r\n 'data': data_temp})\r\n return source_to_import\r\n","repo_name":"LiOdDo/streamlit-batchfile-convert","sub_path":"xlsx2json.py","file_name":"xlsx2json.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"34719368363","text":"from flask import redirect, request, render_template, flash, Blueprint\nfrom services import users_service, session_service\nfrom utils.constant import DANGER_CATEGORY, SUCCESS_CATEGORY\nfrom utils.validators.auth_validator import requires_login, requires_session_time_alive\nfrom utils.validators.models.settings_user import SettingsUser\n\nINFORMATION_UPDATED_MESSAGE = \"Information updated successfully!\"\n\nsettings_bp = Blueprint(\"settings\", __name__)\n\n@settings_bp.route(\"/settings\")\n@requires_login\n@requires_session_time_alive\ndef settings():\n user_id = session_service.get_user_id()\n user_info = users_service.get_user_info(user_id)\n return render_template(\"settings/edit-settings-page.html\",\n user_info=user_info)\n\n@settings_bp.route(\"/settings/update\", methods=[\"POST\"])\n@requires_login\n@requires_session_time_alive\ndef update_settings():\n user_id = session_service.get_user_id()\n try:\n user_validated = SettingsUser(request.form)\n except ValueError as error:\n flash(str(error), DANGER_CATEGORY)\n return redirect(\"/settings\")\n\n users_service.update_settings_values(user_id, user_validated)\n flash(INFORMATION_UPDATED_MESSAGE, SUCCESS_CATEGORY)\n return redirect(\"/settings\")","repo_name":"bhojpur/ehr","sub_path":"pkg/views/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"35814456516","text":"# -*- coding: utf-8 -*-\n\n# Used for seeing the compilation as a tree\n###########################################\n###########################################\n\nindex_space = \"\"\n\ndef decreaseIndexSpace():\n global index_space\n index_space = index_space[0:-1]\n\ndef increaseIndexSpace():\n global index_space\n index_space = index_space + \"\\t\"\n\n\n###########################################\n###########################################\n\nimport sys\nfrom lex import *\n\n\nclass Parameter:\n def __init__(self,par_id, par_type):\n self.id = par_id\n self.type = par_type # True: means is 'in' param, False: means is a 'inout'\n\n# Management of the validity of the function calls and the use of variables\n# This class is used in order to check if function calls are correct, for instance we used it to check if the function is already defined\n# if the number of parameters in the call is correct. Also when we used a variable if the variable has been defined before.\nclass Program:\n def __init__(self, identifier, parameters, prog_type):\n self.id = identifier # subprogram id\n self.params = [] # subprogram parameters, is a list of Paramenter; there are two types: in(True), inout(False)\n self.vars = [] # variables declared inside the program context\n self.programs = [] # subprograms declared inside the program context\n self.type = prog_type # whether the program is a function or is a procedure\n\n self.programs.append(self)\n\n for i in parameters: # fill vars list up\n self.params.append(i)\n self.vars.append(i.id)\n\n # Check if var_id is already defined in the program context. true -> is defined; false -> is not defined\n def checkVarDefined(self, var_id):\n return self.vars.count(var_id) != 0\n\n # Check if is posible to call func_id, with parameters in the func_params list.\n def checkCallPosible(self, func_id, params_type, prog_type): # params_type is a list with the type of every parameter\n for subprog in self.programs:\n # print(str(subprog))\n if subprog.id == func_id and subprog.type == prog_type:\n nop = len(subprog.params)\n if nop == len(params_type): #number of parameters\n # print(\"es posible hacer la llamada a la funcion \" + func_id)\n for i in range(nop):\n if subprog.params[i].type != params_type[i]:\n return False\n return True\n\n return False\n\n # Append variable to defined variables list\n def addVariable(self, var_id):\n if not self.checkVarDefined(var_id):\n self.vars.append(var_id)\n\n # Append program to defined program list\n def addSubprogram(self, subpr):\n # print(\"programas de self: \" + str(self.programs))\n if not self.checkCallPosible(subpr.id, subpr.params, subpr.type):\n self.programs.append(subpr)\n\n\nclass Parser:\n def __init__(self, lexer, intercod):\n self.lexer = lexer\n self.curToken = None # curToken[0] store token kind, curToken store the token symbol\n self.peekToken = None\n self.treeView = False\n self.contextStack = [] # Stack of program istances that store the vars, and subprograms of the current program. I have used the list as a stack\n self.intercod = intercod\n\n self.nextToken()\n self.nextToken()\n\n # Return true if the current token matches\n def checkToken(self, kind):\n return kind == self.curToken[0]\n\n # Return true if the next token matches.\n def checkPeek(self, kind):\n return kind == self.peekToken[0]\n\n # Try to match current token. If not, error. Advances the current token.\n def match(self, kind):\n if not self.checkToken(kind):\n self.abort(\"Expected \" + kind + \", got \" + self.curToken[1] + \" token readed as\" + self.curToken[0])\n self.nextToken()\n\n # Advances the current token.\n def nextToken(self):\n self.curToken = self.peekToken\n self.peekToken = self.lexer.getToken()\n # print(\"Token actual: \" + str(self.curToken)) # descomentar\n # print(\"Contexto actual: \" + str(self.contextStack))\n # print(\"Variables definidas en el contexto actual: \" + str(self.contextStack[-1].vars))\n\n # for i in self.contextStack:\n # print(\"Subprogramas de \" + str(i) + \":\\n\\t\" + str(i.programs))\n\n def abort(self, message):\n sys.exit(\"Error. \" + message)\n\n\n # Context management functions\n\n\n def addVariable(self, ident):\n self.contextStack[-1].addVariable(ident)\n\n def addSubprogram(self, prog):\n self.contextStack[-1].addSubprogram(prog)\n \n def checkVarDefined(self, var_id):\n for i in reversed(self.contextStack):\n if i.checkVarDefined(var_id):\n return True\n return False\n\n def checkCallPosible(self, func_id, params_type, func_type):\n for i in reversed(self.contextStack):\n if i.checkCallPosible(func_id, params_type, func_type):\n return True\n return False\n \n # Tree view functions\n \n def activateTreeView(self):\n self.treeView = True\n \n def deactivateTreeView(self):\n self.treeView = False\n\n # Syntax related functions\n\n # program syntax\n # program ID\n # block\n # .\n def program(self):\n if self.treeView:\n print(index_space + \"PROGRAM\")\n \n increaseIndexSpace()\n \n if self.checkToken(\"PROG\"):\n self.intercod.addQuad(\"PROG_BEGIN\",None,None,None)\n self.nextToken()\n\n if self.checkToken(\"ID\"):\n main = Program(self.curToken[1],[],None)\n self.contextStack.append(main)\n self.nextToken()\n\n self.block()\n self.match(\"EOP\")\n self.intercod.addQuad(\"PROG_END\",None,None,None)\n else:\n self.abort(\"Program does not start as expected.\")\n \n decreaseIndexSpace()\n\n # block syntax\n # {\n # declarations\n # subprograms\n # blockstatements\n # }\n def block(self):\n if self.treeView:\n print(index_space + \"BLOCK\")\n increaseIndexSpace()\n if self.checkToken(\"OCB\"):\n self.nextToken()\n\n self.declarations()\n self.subprograms()\n self.blockstatements()\n\n self.match(\"CCB\")\n else:\n self.abort(\"System expected to read a block.\")\n decreaseIndexSpace()\n\n # declarations syntax\n # ( declare varlist ; )*\n def declarations(self):\n if self.treeView:\n print(index_space + \"DECLARATIONS\")\n increaseIndexSpace()\n while self.checkToken(\"DECL\"):\n self.nextToken()\n\n self.varlist()\n self.match(\"SMCOL\")\n decreaseIndexSpace()\n\n # varlist syntax\n # ID (, ID)* | E\n def varlist(self):\n if self.treeView:\n print(index_space + \"VARLIST\")\n increaseIndexSpace()\n if self.checkToken(\"ID\"):\n self.addVariable(self.curToken[1])\n self.nextToken()\n\n while self.checkToken(\"COM\"):\n self.nextToken()\n self.addVariable(self.curToken[1])\n self.match(\"ID\")\n decreaseIndexSpace()\n\n # subprograms syntax\n # (subprogram)*\n def subprograms(self):\n if self.treeView:\n print(index_space + \"SUBPROGRAMS\")\n increaseIndexSpace()\n while self.checkToken(\"FUNC\") or self.checkToken(\"PROC\"):\n self.subprogram()\n decreaseIndexSpace()\n\n # subprogram syntax\n # function ID ( formalparlist )\n # block\n # | or |\n # procedure ID ( formalparlist )\n # block\n def subprogram(self):\n if self.treeView:\n print(index_space + \"SUBPROGRAM\")\n \n increaseIndexSpace()\n \n if self.checkToken(\"FUNC\") or self.checkToken(\"PROC\"):\n if self.checkToken(\"FUNC\"):\n prog_type = 'f'\n else:\n prog_type = 'p'\n \n self.nextToken()\n\n sub_id = self.curToken[1]\n\n self.match(\"ID\")\n self.match(\"OPAR\")\n params = self.formalparlist()\n self.match(\"CPAR\")\n sub = Program(sub_id, params, prog_type)\n self.addSubprogram(sub)\n self.contextStack.append(sub)\n # print(\"hago un push en la pila\")\n self.intercod.addQuad(\"SUB_BEGIN\",sub_id,None,None)\n self.block()\n self.intercod.addQuad(\"SUB_END\",sub_id,None,None)\n self.contextStack.pop()\n # print(\"hago un pop en la pila\")\n else:\n self.abort(\"System expected a subprogram here.\")\n decreaseIndexSpace()\n\n\n # formalparlist syntax\n # formalparitem (, formalparitem)* | E\n def formalparlist(self):\n if self.treeView:\n print(index_space + \"FORMALPARLIST\")\n increaseIndexSpace()\n params = []\n if self.checkToken(\"IN\") or self.checkToken(\"INOUT\"):\n new_par = self.formalparitem()\n params.append(new_par)\n self.addVariable(new_par.id)\n\n while self.checkToken(\"COM\"):\n self.nextToken()\n new_par = self.formalparitem()\n params.append(new_par)\n self.addVariable(new_par.id)\n\n decreaseIndexSpace()\n return params\n\n # formalparitem syntax\n # in ID | inout ID\n def formalparitem(self):\n if self.treeView:\n print(index_space + \"FORMALPARITEM\")\n increaseIndexSpace()\n var_id = None\n\n if self.checkToken(\"IN\"):\n self.nextToken()\n var_id = self.curToken[1]\n var_tp = True\n self.match(\"ID\")\n elif self.checkToken(\"INOUT\"):\n self.nextToken()\n var_id = self.curToken[1]\n var_tp = False\n self.match(\"ID\")\n else:\n self.abort(\"System expected a formal parameter.\")\n\n decreaseIndexSpace()\n return Parameter(var_id, var_tp)\n\n # statements syntax\n # statement ;\n # | or |\n # {\n # statement (; statement)*\n # }\n def statements(self):\n if self.treeView:\n print(index_space + \"STATEMENTS\")\n increaseIndexSpace()\n if self.checkToken(\"OCB\"):\n self.nextToken()\n\n self.statement()\n\n while self.checkToken(\"SMCOL\"):\n self.nextToken()\n self.statement()\n\n self.match(\"CCB\")\n else:\n self.statement()\n self.match(\"SMCOL\")\n decreaseIndexSpace()\n\n # blockstatements syntax\n # statement ( ; statement )*\n def blockstatements(self):\n if self.treeView:\n print(index_space + \"BLOCKSTATEMENTS\")\n increaseIndexSpace()\n self.statement()\n\n while self.checkToken(\"SMCOL\"):\n self.nextToken()\n\n self.statement()\n\n decreaseIndexSpace()\n\n # statement syntax\n # assignStat\n # | or |\n # ifStat\n # | or |\n # whileStat\n # | or |\n # switchcaseStat\n # | or |\n # forcaseStat\n # | or |\n # incaseStat\n # | or |\n # callStat\n # | or |\n # returnStat\n # | or |\n # inputStat\n # | or |\n # printStat\n # | or |\n # E (empty)\n def statement(self):\n if self.treeView:\n print(index_space + \"STATEMENT\")\n increaseIndexSpace()\n if self.checkToken(\"ID\"):\n self.assignStat()\n elif self.checkToken(\"IF\"):\n self.ifStat()\n elif self.checkToken(\"WHILE\"):\n self.whileStat()\n elif self.checkToken(\"SWITCH\"):\n self.switchcaseStat()\n elif self.checkToken(\"FOR\"):\n self.forcaseStat()\n # elif self.checkToken(\"INCS\"):\n # self.incaseStat()\n elif self.checkToken(\"CALL\"):\n self.callStat()\n elif self.checkToken(\"RET\"):\n self.returnStat()\n elif self.checkToken(\"INPUT\"):\n self.inputStat()\n elif self.checkToken(\"PRINT\"):\n self.printStat()\n decreaseIndexSpace()\n\n # assignStat syntax\n # ID := expresion\n def assignStat(self):\n if self.treeView:\n print(index_space + \"ASSIGSTAT\")\n increaseIndexSpace()\n if self.checkPeek(\"ASIG\"):\n asig_var = self.curToken[1]\n if self.checkVarDefined(asig_var):\n self.nextToken()\n self.nextToken()\n e_place = self.expression()\n self.intercod.addQuad(\"ASIG\",e_place,None,asig_var)\n self.intercod.freeTmpVar(e_place)\n else:\n self.abort(\"Variable \" + self.curToken[1] + \" has not been defined yet.\")\n else:\n self.abort(\"System expected to read ':=' operator.\")\n decreaseIndexSpace()\n\n # ifStat syntax\n # if ( condition )\n # statements\n # elsepart\n def ifStat(self):\n if self.treeView:\n print(index_space + \"IFSTAT\")\n \n increaseIndexSpace()\n \n if self.checkToken(\"IF\"):\n self.nextToken()\n self.match(\"OPAR\")\n cond = self.condition()\n self.match(\"CPAR\")\n \n end_if = self.intercod.newLabel()\n self.intercod.freeTmpVar(cond)\n self.intercod.addQuad(\"IFN_GOTO\",cond,None,end_if)\n \n self.statements()\n\n isThereElse = self.checkToken(\"ELSE\")\n \n if isThereElse:\n end_else = self.intercod.newLabel()\n self.intercod.addQuad(\"GOTO\",end_else,None,None)\n \n self.intercod.addQuad(\"LAB\",end_if,None,None)\n \n self.elsepart()\n \n if isThereElse:\n self.intercod.addQuad(\"LAB\",end_else,None,None)\n \n \n \n # self.intercod.slideQuads(if_start,if_end)\n \n decreaseIndexSpace()\n\n # elsepart syntax\n # else\n # statements\n # | or |\n # E\n def elsepart(self):\n if self.treeView:\n print(index_space + \"ELSEPART\")\n \n increaseIndexSpace()\n \n if self.checkToken(\"ELSE\"):\n self.nextToken()\n self.statements()\n \n decreaseIndexSpace()\n\n # whileStat syntax\n # while ( condition )\n # statements\n def whileStat(self):\n if self.treeView:\n print(index_space + \"WHILESTAT\")\n \n increaseIndexSpace()\n \n if self.checkToken(\"WHILE\"):\n self.nextToken()\n \n self.match(\"OPAR\")\n start_while = self.intercod.newLabel()\n end_while = self.intercod.newLabel()\n self.intercod.addQuad(\"LAB\",start_while,None,None)\n cond = self.condition()\n self.intercod.freeTmpVar(cond)\n self.intercod.addQuad(\"IFN_GOTO\",cond,None,end_while) \n self.match(\"CPAR\")\n \n self.statements()\n \n self.intercod.addQuad(\"GOTO\",start_while,None,None)\n self.intercod.addQuad(\"LAB\",end_while,None,None)\n \n decreaseIndexSpace()\n\n # switchcaseStat syntax\n # switchcase ( case ( condition ) statements )*\n # default statements\n def switchcaseStat(self):\n if self.treeView:\n print(index_space + \"SWITCHCASESTAT\")\n \n increaseIndexSpace()\n \n if self.checkToken(\"SWITCH\"):\n self.nextToken()\n\n end_switch = self.intercod.newLabel()\n labels = []\n\n while self.checkToken(\"CASE\"):\n labels.append(self.intercod.newLabel())\n self.nextToken()\n self.match(\"OPAR\")\n cond = self.condition()\n self.match(\"CPAR\")\n self.intercod.addQuad(\"IFN_GOTO\",cond,labels[-1],None)\n self.statements()\n self.intercod.addQuad(\"GOTO\",end_switch,None,None)\n self.intercod.addQuad(\"LAB\",labels[-1],None,None)\n \n self.match(\"DFLT\")\n self.statements()\n self.intercod.addQuad(\"LAB\",end_switch,None,None)\n\n decreaseIndexSpace()\n\n\n # forcaseStat syntax\n # forcase ( case ( condition ) statements)*\n # default statements\n def forcaseStat(self):\n if self.treeView:\n print(index_space + \"FORCASESTAT\")\n \n increaseIndexSpace()\n \n if self.checkToken(\"FOR\"):\n self.nextToken()\n \n start_forcase = self.intercod.newLabel()\n labels = []\n \n self.intercod.addQuad(\"LAB\",start_forcase,None,None)\n\n while self.checkToken(\"CASE\"):\n labels.append(self.intercod.newLabel())\n self.nextToken()\n self.match(\"OPAR\")\n cond = self.condition()\n self.match(\"CPAR\")\n self.intercod.addQuad(\"IFN_GOTO\",cond,labels[-1],None)\n self.statements()\n self.intercod.addQuad(\"GOTO\",start_forcase,None,None)\n self.intercod.addQuad(\"LAB\",labels[-1],None,None)\n\n self.match(\"DFLT\")\n self.statements()\n \n decreaseIndexSpace()\n\n # incaseStat syntax\n # incase ( case ( condition ) statements)*\n # def incaseStat(self):\n # if self.treeView:\n # print(index_space + \"INCASE\")\n # increaseIndexSpace()\n # if self.checkToken(\"INCS\"):\n # self.nextToken()\n\n # while self.checkToken(\"CASE\"):\n # self.nextToken()\n # self.match(\"OPAR\")\n # self.condition()\n # self.match(\"CPAR\")\n # self.statements()\n # decreaseIndexSpace()\n\n # returnStat syntax\n # return ( expression )\n def returnStat(self):\n if self.treeView:\n print(index_space + \"RETURNSTAT\")\n \n increaseIndexSpace()\n \n if self.checkToken(\"RET\"):\n self.nextToken()\n self.match(\"OPAR\")\n e_place = self.expression()\n self.match(\"CPAR\")\n \n self.intercod.addQuad(\"RET\",e_place,None,None)\n \n decreaseIndexSpace()\n\n # callStat syntax\n # call ID( actualparlist )\n def callStat(self):\n if self.treeView:\n print(index_space + \"CALLSTAT\")\n \n increaseIndexSpace()\n \n if self.checkToken(\"CALL\"):\n self.nextToken()\n func_id = self.currentToken[1]\n self.match(\"ID\")\n self.match(\"OPAR\")\n par_list = self.actualparlist()\n self.match(\"CPAR\")\n\n if not self.checkCallPosible(func_id, par_list, 'p'):\n self.abort(\"Problem calling the function \" + func_id + \". Check if the function has been defined and if the number of arguments is correct and check the type of each parameter.\")\n\n self.intercod.addQuad(\"CALL\",func_id,None,None)\n \n decreaseIndexSpace()\n\n # printStat syntax\n # print( expression )\n def printStat(self):\n if self.treeView:\n print(index_space + \"PRINTSTAT\")\n \n increaseIndexSpace()\n \n if self.checkToken(\"PRINT\"):\n self.nextToken()\n self.match(\"OPAR\")\n e_place = self.expression()\n self.match(\"CPAR\")\n self.intercod.addQuad(\"PRINT\",e_place,None,None)\n \n decreaseIndexSpace()\n\n # inputStat syntax\n # input ( ID )\n def inputStat(self):\n if self.treeView:\n print(index_space + \"INPUTSTAT\")\n \n increaseIndexSpace()\n \n if self.checkToken(\"INPUT\"):\n self.nextToken()\n self.match(\"OPAR\")\n var = self.curToken[1]\n \n if self.checkVarDefined(var):\n self.match(\"ID\")\n else:\n self.abort(\"Variable \" + var + \" has not been defined.\")\n \n self.match(\"CPAR\")\n \n self.intercod.addQuad(\"INPUT\",None,None,var)\n \n decreaseIndexSpace()\n\n # actualparlist syntax\n # actualparitem ( , actualparitem )*\n # | or |\n # E\n def actualparlist(self):\n if self.treeView:\n print(index_space + \"ACTUALPARLIST\")\n \n increaseIndexSpace()\n par_list = []\n \n if self.checkToken(\"IN\") or self.checkToken(\"INOUT\"):\n item = self.actualparitem()\n par_list.append(item[1])\n \n if item[1]:\n mode = \"VAL\"\n else:\n mode = \"REF\"\n \n self.intercod.addQuad(\"PAR\",item[0],mode,None)\n\n while self.checkToken(\"COM\"):\n self.nextToken()\n item = self.actualparitem()\n par_list.append(item[1])\n \n if item[1]:\n mode = \"VAL\"\n else:\n mode = \"REF\"\n \n self.intercod.addQuad(\"PAR\",item[0],mode,None)\n\n decreaseIndexSpace()\n return par_list\n\n # acutalparitem syntax\n # in expression | inout ID\n def actualparitem(self):\n if self.treeView:\n print(index_space + \"ACTUALPARITEM\")\n increaseIndexSpace()\n if self.checkToken(\"IN\"):\n self.nextToken()\n e_place = self.expression()\n return [e_place, True]\n elif self.checkToken(\"INOUT\"):\n self.nextToken()\n var = self.curToken[1]\n if self.checkVarDefined(var):\n self.match(\"ID\")\n return [var, False]\n else:\n self.abort(\"Variable \" + self.curToken[1] + \" has not been defined.\")\n else:\n self.abort(\"System expected a in or inout token.\")\n decreaseIndexSpace()\n\n\n # condition syntax\n # boolterm ( or boolterm )*\n def condition(self):\n if self.treeView:\n print(index_space + \"CONDITION\")\n \n increaseIndexSpace()\n e1_place = self.boolterm()\n\n while self.checkToken(\"OR\"):\n e2_place = self.boolterm()\n self.intercod.freeTmpVar(e1_place)\n self.intercod.freeTmpVar(e2_place)\n w = self.intercod.newTmpVar()\n self.intercod.addQuad(\"OR\",e1_place,e2_place,w)\n e1_place = w\n \n decreaseIndexSpace()\n return e1_place\n\n # boolterm syntax\n # boolfactor ( and boolfactor )*\n def boolterm(self):\n if self.treeView:\n print(index_space + \"BOOLTERM\")\n \n increaseIndexSpace()\n e1_place = self.boolfactor()\n\n while self.checkToken(\"AND\"):\n e2_place = self.boolfactor() \n self.intercod.freeTmpVar(e1_place)\n self.intercod.freeTmpVar(e2_place)\n w = self.intercod.newTmpVar()\n self.intercod.addQuad(\"AND\",e1_place,e2_place,w)\n e1_place = w\n\n decreaseIndexSpace()\n return e1_place\n\n # boolfactor syntax\n # not [ condition ]\n # | or |\n # [ condition ]\n # | or |\n # expression REL_OP expression\n def boolfactor(self):\n if self.treeView:\n print(index_space + \"BOOLFACTOR\")\n \n increaseIndexSpace()\n \n if self.checkToken(\"NOT\"):\n self.nextToken()\n self.match(\"OBRA\")\n e_place = self.intercod.newTmpVar()\n e1_place = self.condition()\n self.intercod.freeTmpVar(e1_place)\n self.intercod.addQuad(\"NOT\",e1_place,None,e_place)\n self.match(\"CBRA\")\n \n elif self.checkToken(\"OBRA\"):\n self.nextToken()\n e_place = self.condition()\n self.match(\"CBRA\")\n \n else:\n e_place = self.intercod.newTmpVar()\n \n e1_place = self.expression()\n relop = self.rel_op() # store the relop token \n e2_place = self.expression()\n \n self.intercod.freeTmpVar(e1_place)\n self.intercod.freeTmpVar(e2_place)\n \n self.intercod.addQuad(relop[0],e1_place,e2_place,e_place)\n \n decreaseIndexSpace()\n return e_place\n\n # expression syntax\n # optionalSign term (ADD_OP term)*\n def expression(self):\n if self.treeView:\n print(index_space + \"EXPRESSION\")\n increaseIndexSpace()\n # print(\"entro expresion\")\n \n minsign = self.optionalSign() # completar esta parte\n e1_place = self.term(minsign)\n\n while(self.checkToken(\"PLUS\") or self.checkToken(\"MINUS\")):\n token = self.curToken[0]\n self.nextToken()\n e2_place = self.term(False)\n self.intercod.freeTmpVar(e1_place)\n self.intercod.freeTmpVar(e2_place)\n w = self.intercod.newTmpVar()\n self.intercod.addQuad(token,e1_place,e2_place,w)\n e1_place = w\n \n\n decreaseIndexSpace()\n # self.intercod.freeTmpVar()\n # self.intercod.freeTmpVar()\n return e1_place # w usually\n # print(\"salgo expresion\")\n\n\n # term syntax\n # factor (MULT_OP factor)*\n def term(self,minsign):\n if self.treeView:\n print(index_space + \"TERM\")\n \n increaseIndexSpace()\n e1_place = self.factor(minsign)\n\n while(self.checkToken(\"MULT\") or self.checkToken(\"DIV\")):\n token = self.curToken[0]\n self.nextToken()\n e2_place = self.factor(False)\n self.intercod.freeTmpVar(e1_place)\n self.intercod.freeTmpVar(e2_place)\n w = self.intercod.newTmpVar()\n self.intercod.addQuad(token,e1_place,e2_place,w)\n e1_place = w\n\n decreaseIndexSpace()\n # self.intercod.freeTmpVar()\n # self.intercod.freeTmpVar()\n return e1_place # w usually\n\n # factor syntax\n # INTEGER\n # | or |\n # ( expression )\n # | or |\n # ID idtail\n def factor(self,minsign):\n if self.treeView:\n print(index_space + \"FACTOR\")\n \n increaseIndexSpace()\n \n if self.checkToken(\"NUMB\"):\n \n if minsign:\n e_place = self.intercod.newTmpVar()\n e1_place = self.curToken[1]\n self.intercod.addQuad(\"UMINUS\",e1_place,None,e_place)\n else:\n e_place = self.curToken[1]\n \n self.nextToken()\n return e_place\n \n elif self.checkToken(\"OPAR\"):\n \n if minsign:\n self.nextToken()\n e_place = self.intercod.newTmpVar()\n e1_place = self.expression()\n self.match(\"CPAR\")\n self.intercod.addQuad(\"UMINUS\",e1_place,None,e_place)\n else:\n self.nextToken()\n e_place = self.expression()\n self.match(\"CPAR\")\n \n return e_place\n \n elif self.checkToken(\"ID\"):\n # print(self.contextStack[-1].programs)\n ident = self.curToken[1]\n self.nextToken()\n params = self.idtail()\n\n if not self.checkVarDefined(ident) and not self.checkCallPosible(ident, params, 'f'): #Semantic analysis\n self.abort(\"System expected a function or variable, but \" + ident + \" has not been defined.\")\n \n if params == None: # if is not a function call then\n \n if minsign:\n e_place = self.intercod.newTmpVar()\n e1_place = ident\n self.intercod.addQuad(\"UMINUS\",e1_place,None,e_place)\n else:\n e_place = ident\n \n return e_place\n else:\n w = self.intercod.newTmpVar()\n self.intercod.addQuad(\"PAR\",w,\"RET\",None)\n self.intercod.addQuad(\"CALL\",ident,None,None)\n return w\n # print(\"--> realizada la llamada\")\n else:\n self.abort(\"Syntax expected a factor, starting by a ID or NUMBER token or '(' symbol. \")\n\n decreaseIndexSpace()\n\n # idtail syntax\n # ( actualparlist ) | E\n def idtail(self):\n if self.treeView:\n print(index_space + \"IDTAIL\")\n increaseIndexSpace()\n par_type = None\n if self.checkToken(\"OPAR\"): # then is a function call\n # print(\"entro idtail\")\n self.nextToken()\n par_type = self.actualparlist()\n self.match(\"CPAR\")\n # print(\"salgo idtail\")\n\n decreaseIndexSpace()\n return par_type\n\n # optionalSign syntax\n # ADD_OP | E\n def optionalSign(self):\n minus_sign = self.checkToken(\"MINUS\")\n plus_sign = self.checkToken(\"PLUS\")\n \n if plus_sign or minus_sign:\n self.nextToken()\n \n return minus_sign\n\n # rel_op syntax\n # = | <= | >= | > | < | <>\n def rel_op(self):\n tkn = self.curToken\n \n if self.checkToken(\"EQ\"):\n self.nextToken()\n if self.checkToken(\"LTEQ\"):\n self.nextToken()\n if self.checkToken(\"GTEQ\"):\n self.nextToken()\n if self.checkToken(\"LT\"):\n self.nextToken()\n if self.checkToken(\"GT\"):\n self.nextToken()\n if self.checkToken(\"NOTEQ\"):\n self.nextToken()\n \n return tkn\n\n # add_op syntax\n # + | -\n def add_op(self):\n if self.checkToken(\"PLUS\"):\n self.nextToken()\n if self.checkToken(\"MINUS\"):\n self.nextToken()\n\n # mul_op syntax\n # * | /\n def mul_op(self):\n if self.checkToken(\"MULT\"):\n self.nextToken()\n if self.checkToken(\"DIV\"):\n self.nextToken()\n","repo_name":"gmaz3/compiler","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":30541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"17143416773","text":"from django.db import models\nimport uuid\n# Create your models here.\n\nclass UserAccounts(models.Model):\n username = models.CharField(unique=True, max_length=50)\n password = models.CharField(max_length=50)\n name = models.CharField(max_length=50)\n email_id = models.EmailField(max_length=70, blank=True, null=True, unique=True)\n address = models.CharField(max_length=200)\n\n\nclass Session(models.Model):\n\tuser_id = models.ForeignKey(UserAccounts)\n\tsession_id = models.UUIDField(unique=True, default=uuid.uuid4)\n\nclass Questions(models.Model):\n\ttitle = models.CharField(max_length=200)\n\tdescription = models.TextField()\n\tuser_id = models.ForeignKey(UserAccounts)\n\tvalid_ans = models.IntegerField(null=True, blank=True)\n\nclass Answers(models.Model):\n\ttitle = models.CharField(max_length=200)\n\tdescription = models.TextField()\n\tquestion_id = models.ForeignKey(Questions)\n\towner_id = models.ForeignKey(UserAccounts)\n\nclass Tags(models.Model):\n\tname = models.CharField(unique=True, max_length=200)\n\nclass QuestionTags(models.Model):\n\tquestion_id = models.ForeignKey(Questions)\n\ttag_id = models.ForeignKey(Tags)\n\n\nclass AnswerVote(models.Model):\n\tvoter_id = models.ForeignKey(UserAccounts)\n\tanswer_id = models.ForeignKey(Answers)\n\tvote_type = models.IntegerField()","repo_name":"abhilashdindalkop/askcode","sub_path":"api/stackproject/stack/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"36068400589","text":"import torch\nfrom math import acos\n\n\nfor i in range(10):\n\n q1 = torch.rand(4)\n q2 = torch.rand(4)\n\n q1 = q1 / torch.norm(q1)\n q2 = q2 / torch.norm(q2)\n\n theta1 = 2 * acos(abs((q1 * q2).sum()))\n theta2 = acos(2 * (q1 * q2).sum() ** 2 - 1)\n\n print(theta1)\n print(theta2)","repo_name":"awaelchli/master-project","sub_path":"utils/quattest.py","file_name":"quattest.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"41353543122","text":"from __future__ import division\n\nimport numpy as np\nimport tensorflow as tf\nimport scipy#.misc.imresize\n#import cv2\n\nimport knn_dictionary\n\n\nclass NECAgent():\n def __init__(self, session, args):\n\n # Environment details\n self.obs_size = list(args.obs_size)\n self.n_actions = args.num_actions\n self.viewer = None\n\n # Agent parameters\n self.discount = args.discount\n self.n_steps = args.n_step\n self.initial_epsilon = args.epsilon\n self.epsilon = self.initial_epsilon\n self.epsilon_final = args.epsilon_final\n self.epsilon_anneal = args.epsilon_anneal\n\n # DND parameters\n self.DND_size = args.memory_size\n self.delta = args.delta\n self.dict_delta = args.delta#0.1\n self.alpha = args.alpha\n self.number_nn = args.num_neighbours\n\n # Training parameters\n self.model = args.model\n self.history_len = args.history_len\n self.memory_size = args.replay_memory_size\n self.batch_size = args.batch_size\n self.learning_rate = args.learning_rate\n self.learn_step = args.learn_step\n\n # Stored variables\n self.step = 0\n self.started_training = False\n self.seed = args.seed\n self.rng = np.random.RandomState(self.seed)\n self.session = session\n\n # Replay Memory\n self.memory = ReplayMemory(self.memory_size, self.obs_size)\n\n # Preprocessor:\n if args.preprocessor == 'deepmind':\n self.preproc = deepmind_preprocessor\n elif args.preprocessor == 'grayscale':\n #incorrect spelling in order to not confuse those silly americans\n self.preproc = greyscale_preprocessor\n else:\n self.preproc = default_preprocessor\n #a lambda could be used here, but I think this makes more sense\n \n\n # Tensorflow variables:\n \n # Model for Embeddings\n with tf.variable_scope('agent_model'):\n if self.model == 'CNN':\n from networks import deepmind_CNN\n self.state = tf.placeholder(\"float\", [None, self.history_len]+self.obs_size)\n self.state_embeddings, self.weights = deepmind_CNN(self.state, seed=self.seed)\n elif self.model == 'nn':\n from networks import feedforward_network\n self.state = tf.placeholder(\"float\", [None]+self.obs_size)\n self.state_embeddings, self.weights = \\\n feedforward_network(self.state, seed=self.seed)\n elif self.model == 'object':\n from networks import embedding_network\n self.state = tf.placeholder(\"float\", [None]+self.obs_size)\n # mask to enable masking out of entries, last dim is kept for easy broadcasting\n self.masks = tf.placeholder(\"float\", [None, None, 1])\n #tf.Variable(tf.ones(\"float\", [None, None, 1]))\n self.state_embeddings, self.weights = \\\n embedding_network(self.state, self.masks, seed=self.seed)\n\n # DNDs\n self.DND = knn_dictionary.q_dictionary(\n self.DND_size, self.state_embeddings.get_shape()[-1], self.n_actions,\n self.dict_delta, self.alpha)\n\n self.action = tf.placeholder(tf.int8, [None])\n\n # Retrieve info from DND dictionary\n embs_and_values = tf.py_func(self.DND._query,\n [self.state_embeddings, self.action, self.number_nn], [tf.float64, tf.float64])\n self.dnd_embeddings = tf.to_float(embs_and_values[0])\n self.dnd_values = tf.to_float(embs_and_values[1])\n\n # DND calculation\n # (takes advantage of broadcasting)\n square_diff = tf.square(self.dnd_embeddings - tf.expand_dims(self.state_embeddings, 1))\n distances = tf.reduce_sum(square_diff, axis=2) + [self.delta]\n weightings = 1.0 / distances\n normalised_weightings = weightings / tf.reduce_sum(weightings, axis=1, keep_dims=True)\n self.pred_q = tf.reduce_sum(self.dnd_values * normalised_weightings, axis=1)\n \n # Loss Function\n self.target_q = tf.placeholder(\"float\", [None])\n self.td_err = self.target_q - self.pred_q\n total_loss = tf.reduce_sum(tf.square(self.td_err))\n #total_loss = total_loss + become_skynet_penalty #commenting this out makes code run faster \n \n # Optimiser\n self.optim = tf.train.RMSPropOptimizer(\n self.learning_rate, decay=0.9, epsilon=0.01).minimize(total_loss)\n # These are the optimiser settings used by DeepMind\n \n self.model_weights = tf.get_collection(tf.GraphKeys.VARIABLES, scope='agent_model')\n self.saver = tf.train.Saver(self.model_weights)\n\n\n def _get_state(self, t=-1):\n # Returns the compiled state from stored observations\n if t==-1: t = self.trajectory_t-1\n\n if self.history_len == 0:\n state = self.trajectory_observations[t]\n else:\n if self.obs_size[0] == None:\n state = []\n for i in range(self.history_len):\n state.append(self.trajectory_observations[t-i])\n else:\n state = np.zeros([self.history_len]+self.obs_size)\n for i in range(self.history_len):\n if (t-i) >= 0:\n state[i] = self.trajectory_observations[t-i]\n return state\n\n\n def _get_state_embeddings(self, states):\n # Returns the DND hashes for the given states\n if self.obs_size[0] == None:\n states_, masks = batch_objects(states)\n embeddings = self.session.run(self.state_embeddings,\n feed_dict={self.state: states_, self.masks: masks})\n else: \n embeddings = self.session.run(self.state_embeddings, feed_dict={self.state: states})\n return embeddings\n\n\n def _predict(self, embedding):\n # Return action values for given embedding\n\n # calculate Q-values\n qs = []\n for a in xrange(self.n_actions):\n if self.DND.dicts[a].queryable(self.number_nn):\n q = self.session.run(self.pred_q, feed_dict={\n self.state_embeddings: [embedding], self.action: [a]})[0]\n else:\n q = 0.0\n qs.append(q)\n\n # Return Q values\n return qs\n\n\n def _train(self, states, actions, Q_targets):\n\n if not self.DND.queryable(self.number_nn):\n return False\n\n self.started_training = True\n\n if self.obs_size[0] == None:\n states_, masks = batch_objects(states)\n\n feed_dict = {\n self.state: states_,\n self.masks: masks,\n self.target_q: Q_targets,\n self.action: actions\n }\n\n else:\n feed_dict = {\n self.state: states,\n self.target_q: Q_targets,\n self.action: actions\n }\n\n self.session.run(self.optim, feed_dict=feed_dict)\n \n return True\n\n\n def Reset(self, obs, train=True):\n self.training = train\n\n #TODO: turn these lists into a proper trajectory object\n self.trajectory_observations = [self.preproc(obs)]\n self.trajectory_embeddings = []\n self.trajectory_values = []\n self.trajectory_actions = []\n self.trajectory_rewards = []\n self.trajectory_t = 0\n return True\n\n def GetAction(self):\n # TODO: Perform calculations on Update, then use aaved values to select actions\n \n # Get state embedding of last stored state\n state = self._get_state()\n embedding = self._get_state_embeddings([state])[0]\n \n # Rendering code for displaying raw state\n if False:\n from gym.envs.classic_control import rendering\n if self.viewer is None:\n self.viewer = rendering.SimpleImageViewer()\n im = state[-1]\n w, h = im.shape\n ret = np.empty((w, h, 3), dtype=np.uint8)\n ret[:, :, :] = im[:, :, np.newaxis]*255\n self.viewer.imshow(ret)\n\n # Get Q-values\n Qs = self._predict(embedding)\n action = np.argmax(Qs) ; value = Qs[action]\n\n # Get action via epsilon-greedy\n if True: #self.training:\n if self.rng.rand() < self.epsilon:\n action = self.rng.randint(0, self.n_actions)\n #value = Qs[action] # Paper uses maxQ, uncomment for on-policy updates\n\n self.trajectory_embeddings.append(embedding)\n self.trajectory_values.append(value)\n return action, value\n\n\n def Update(self, action, reward, obs, terminal=False):\n\n self.trajectory_actions.append(action)\n self.trajectory_rewards.append(reward)\n self.trajectory_t += 1\n self.trajectory_observations.append(self.preproc(obs))\n\n self.step += 1\n\n if self.training:\n\n # Update Epsilon\n per = min(self.step / self.epsilon_anneal, 1)\n self.epsilon = (1-per)*self.initial_epsilon + per*self.epsilon_final\n\n if self.memory.count > self.batch_size*2 and (self.step % self.learn_step) == 0:\n # Get transition sample from memory\n s, a, R = self.memory.sample(self.batch_size, self.history_len)\n # Run optimization op (backprop)\n self._train(s, a, R)\n\n\n # Add to replay memory and DND\n if terminal:\n # Calculate returns\n returns = []\n for t in xrange(self.trajectory_t):\n if self.trajectory_t - t > self.n_steps:\n #Get truncated return\n start_t = t + self.n_steps\n R_t = self.trajectory_values[start_t]\n else:\n start_t = self.trajectory_t\n R_t = 0\n \n for i in xrange(start_t-1, t, -1):\n R_t = R_t * self.discount + self.trajectory_rewards[i]\n returns.append(R_t)\n self.memory.add(self.trajectory_observations[t], self.trajectory_actions[t], R_t, (t==(self.trajectory_t-1)))\n\n self.DND.add(self.trajectory_embeddings, self.trajectory_actions, returns)\n return True\n \n \n def Save(self, save_dir):\n self.saver.save(self.session, save_dir + '/model.ckpt')\n self.DND.save(save_dir + '/DNDdict')\n\n def Load(self, save_dir):\n ckpt = tf.train.get_checkpoint_state(save_dir)\n print(\"Loading model from {}\".format(ckpt.model_checkpoint_path))\n self.saver.restore(self.session, ckpt.model_checkpoint_path)\n self.DND.load(save_dir + '/DNDdict')\n\n\ndef batch_objects(input_list):\n # Takes an input list of lists (of vectors), pads each list the length of the longest list,\n # compiles the list into a single n x m x d array, and returns a corresponding n x m x 1 mask.\n max_len = 0\n out = []; masks = []\n for i in input_list: max_len = max(len(i),max_len)\n for l in input_list:\n # Zero pad output\n out.append(np.pad(np.array(l,dtype=np.float32), ((0,max_len-len(l)),(0,0)), mode='constant'))\n # Create mask...\n masks.append(np.pad(np.array(np.ones((len(l),1)),dtype=np.float32), ((0,max_len-len(l)),(0,0)), mode='constant'))\n return out, masks\n\n\n# Adapted from github.com/devsisters/DQN-tensorflow/\nclass ReplayMemory:\n def __init__(self, memory_size, obs_size):\n self.memory_size = memory_size\n self.obs_size = obs_size\n\n if self.obs_size[0] == None:\n self.observations = [None]*self.memory_size\n else:\n self.observations = np.empty([self.memory_size]+self.obs_size, dtype = np.float16)\n self.actions = np.empty(self.memory_size, dtype=np.int16)\n self.returns = np.empty(self.memory_size, dtype = np.float16)\n self.terminal = np.empty(self.memory_size, dtype = np.bool_)\n\n self.count = 0\n self.current = 0\n\n def add(self, obs, action, returns, terminal):\n self.observations[self.current] = obs\n self.actions[self.current] = action\n self.returns[self.current] = returns\n self.terminal[self.current] = terminal\n\n self.count = max(self.count, self.current + 1)\n self.current = (self.current + 1) % self.memory_size\n\n def _get_state(self, index, seq_len):\n # normalize index to expected range, allows negative indexes\n index = index % self.count\n if seq_len == 0:\n state = self.observations[index]\n else:\n if self.obs_size[0] == None:\n state = []\n for i in range(seq_len):\n state.append(self.observations[index-i])\n else:\n state = np.zeros([seq_len]+self.obs_size)\n for i in range(seq_len):\n state[i] = self.observations[index-i]\n return state\n\n def _uninterrupted(self, start, final):\n if self.current in range(start+1, final):\n return False\n for i in range(start, final-1):\n if self.terminal[i] == True: return False\n return True\n\n def sample(self, batch_size, seq_len=0):\n # sample random indexes\n indexes = [] ; states = []\n watchdog = 0\n while len(indexes) < batch_size:\n while True:\n # find random index\n index = np.random.randint(1, self.count - 1)\n if seq_len is not 0:\n start = index-seq_len\n if not self._uninterrupted(start, index):\n continue\n break\n\n indexes.append(index)\n states.append(self._get_state(index, seq_len))\n\n return states, self.actions[indexes], self.returns[indexes]\n\n\nclass trajectory:\n# Get_Action requires last 4 obs to make a prediction\n# Observations need to be stored to make prediction\n# Actions and rewards need to be stored to calculate returns\n# Values can be stored to prevent need from computing them twice\n# Embeddings can be stored to prevent need from computing them twice (only needed for NEC)\n def __init__(self, obs_size):\n self.obs_size = obs_size\n\n self.trajectory = []\n self.current_entry = trajectory_entry()\n self.t = 0\n\n self.trajectory_observations = [obs]\n self.trajectory_embeddings = []\n self.trajectory_values = []\n self.trajectory_actions = []\n self.trajectory_rewards = []\n\n def _get_entry(self, t):\n if t==-1 or t==self.t: return self.current_entry\n return self.trajectory[t]\n\n def step(self):\n self.trajectory.append(self.current_entry)\n self.current_entry = trajectory_entry()\n self.t += 1\n\n def get_state(self, t=-1, his_len=1):\n if t==-1: t = self.t\n\n state = np.zeros([self.history_len]+self.obs_size)\n for i in range(his_len):\n state[i] = self._get_entry(t-i).observation\n return state\n\n def get_returns(self, n_step):\n\n for t in xrange(self.trajectory_t):\n if self.trajectory_t - t > self.n_steps:\n #Get truncated return\n start_t = t + self.n_steps\n R_t = self.trajectory_values[start_t]\n else:\n start_t = self.trajectory_t \n R_t = 0\n \n for i in xrange(start_t-1, t, -1):\n R_t = R_t * self.discount + self.trajectory_rewards[i]\n\n return obs, embeddings, actions, returns\n\n\nclass trajectory_entry:\n observation = None\n embedding = None\n action = None\n reward = None\n value = None\n\n\n# Preprocessors:\ndef default_preprocessor(state):\n return state\n\ndef greyscale_preprocessor(state):\n #state = cv2.cvtColor(state,cv2.COLOR_BGR2GRAY)/255.\n state = np.dot(state[...,:3], [0.299, 0.587, 0.114])\n return state\n\ndef deepmind_preprocessor(state):\n state = greyscale_preprocessor(state)\n #state = np.array(cv2.resize(state, (84, 84)))\n resized_screen = scipy.misc.imresize(state, (110,84))\n state = resized_screen[18:102, :]\n return state\n\n","repo_name":"EndingCredits/Neural-Episodic-Control","sub_path":"NECAgent.py","file_name":"NECAgent.py","file_ext":"py","file_size_in_byte":15971,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"41"} +{"seq_id":"3921208485","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\nimport apps.core.utils.date_helpers\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Performance',\n fields=[\n ('id', models.AutoField(verbose_name='ID',\n serialize=False, auto_created=True, primary_key=True)),\n ('label', models.CharField(max_length=32, null=True, blank=True)),\n ('name', models.CharField(max_length=64)),\n ('description', models.TextField(blank=True)),\n ('date_create', models.TimeField()),\n ('duration', models.FloatField()),\n ('exitcode', models.IntegerField()),\n ],\n ),\n ]\n","repo_name":"SatelliteQE/GreenTea","sub_path":"apps/api/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"41"} +{"seq_id":"22575371257","text":"__author__ = 'xead'\n# coding: utf-8\n\nfrom sentiment_classifier import SentimentClassifier\nfrom sklearn.externals import joblib\nfrom eli5.lime import TextExplainer\n\n#clf = SentimentClassifier()\n\n#pred = clf.get_prediction_message(\"Хороший телефон\")\ntext = 'Хороший был у меня телефон 5 лет назад'\n\npipe = joblib.load(\"./pipe6.pkl\")\nte = TextExplainer(random_state=42)\nte.fit(text, pipe.predict_proba)\nres = te.show_prediction(target_names=['negative', 'positive'], top=25)\n\nprint (res)","repo_name":"Aindstorm/Sentiment-classification","sub_path":"classifier_test.py","file_name":"classifier_test.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"6104732597","text":"\n# read file\n# open function \n# read method\n# tell method\n# readline method\n# readline methods\n# close method\n\nf = open('filel.txt')\nprint(f'cursor position -- {f.tell()}')\n\n# print(f.read())\n# print(f.readline(), end='')\n# print(f.readline())\n# print(f'cursor position -- {f.tell()}')\n# print('befor seek method')\n# f.seek(0)\n# print('after seek method')\n# print(f'cursor position -- {f.tell()}')\n# print(f.read())\n\n# f = open('flle.text')\n# print(len(lines))\n# for line in lines:\n# print(line.end = '')\n\nf = open(\"d:\\new_folder\\file.txt\")\n# windows -\\\n# linux , mac /\n# name,closed\nprint(f.close())\nf.close()\n","repo_name":"Sajid305/Python-practice","sub_path":"Source code/Object Oriented Programming/Read Text Files.py","file_name":"Read Text Files.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"7559842364","text":"from os import *\nfrom sys import *\nfrom collections import *\nfrom math import *\n\ndef f(i, s, temp, ans, m):\n if i == len(s):\n ans.append(temp)\n return\n\n for ind in range(i, len(s)):\n if m.get(s[i:ind + 1], False):\n temp += s[i:ind + 1] + ' '\n f(ind + 1, s, temp, ans, m)\n temp = temp[:-(ind - i + 2)]\n\n\ndef wordBreak(s, dic):\n m = {}\n for i in dic:\n m[i] = True\n\n ans = []\n temp = ''\n f(0, s, temp, ans, m)\n return ans","repo_name":"Garima-tata/Strivers-SDE-Sheet-Challenge","sub_path":"DP/wordbreak2.py","file_name":"wordbreak2.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"129812200","text":"# 平方乘算法(由高位到低位)\r\n# 计算 b^n (mod m)\r\ndef fast_mod_pow(b, n, m):\r\n # 计算n的二进制表示\r\n n_bin = bin(n)[2:]\r\n c = 1\r\n for n_i in n_bin:\r\n c = c * c % m\r\n if n_i == '1':\r\n c = c * b % m\r\n return c\r\n\r\n\r\ndef main():\r\n b, n, m = [int(i) for i in input().split()]\r\n print(fast_mod_pow(b, n, m))\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"Snicker8/buaa_crypto_experiment","sub_path":"codes/ex1_number_theory_basic/c2_fast_mod_pow.py","file_name":"c2_fast_mod_pow.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"41"} +{"seq_id":"19513602673","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\nfrom django.conf.urls.defaults import patterns, include, url\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n (r'^admin/', include(admin.site.urls)),\n (r'^', include(admin.site.urls)),\n (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': 'media', 'show_indexes': True}),\n)\n","repo_name":"rfloriano/petshop_project","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"5318725454","text":"from django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth import login, authenticate\nfrom django.shortcuts import render, redirect\n\ndef register(request):\n if request.method == 'POST':\n form = UserCreationForm(request.POST)\n if form.is_valid():\n user = form.save()\n login(request, user)\n return redirect('dashboard') # Reemplaza 'dashboard' con la URL de la página principal de tu aplicación\n else:\n form = UserCreationForm()\n return render(request, 'register.html', {'form': form})\n","repo_name":"JPLFraccaro/cashflow_wizard","sub_path":"cashflowwizard/cashflow_wizard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"25488778625","text":"#!/usr/bin/env python3\n\"\"\" Generators are the best way to iterate through large or complex data sets, especially when performance and memory are of concern.\nThe generator function returns a generator object and that generator object will yield the values. Now, you may have heard that generators yield rather than return, which is true. \n\"\"\"\n\ndef even_integers_function(n):\n for i in range(n):\n if i % 2 == 0:\n yield i # return a generator object\n\nprint(list(even_integers_function(10)))\n","repo_name":"quasi-coder/Python","sub_path":"Generators/generatorfunction.py","file_name":"generatorfunction.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"8855279116","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split as ts\nfrom sklearn.preprocessing import MinMaxScaler as mms\nfrom sklearn.metrics import r2_score, mean_absolute_error\nfrom sklearn.preprocessing import StandardScaler\n\n# Set seed\nnp.random.seed(0)\n\n# Load data\npath = 'cleaned_GDP.csv'\ndf = pd.read_csv(path, decimal = ',')\n\nfor col in df.columns.values:\n df[col] = df[col].astype(float)\n\ntarget = df['GDP ($ per capita)']\nfeatures = df.loc[:, df.columns != 'GDP ($ per capita)']\n\n# Scale Data\nscaler = mms()\nif len(features.shape) == 1:\n features = features.reshape(-1,1)\nfeatures_scaled = scaler.fit_transform(features)\n\n# Split and Reshape Data\nx_train, x_test, y_train, y_test = ts(features, target, test_size=0.2, random_state=43)\n\ny_train = np.array(y_train).reshape(-1,1)\ny_test = np.array(y_test).reshape(-1,1)\n\nx_train = np.array(x_train)\nx_test = np.array(x_test)\n\n# Make arrays into tensors\nx_train = torch.tensor(x_train.astype(float), dtype=torch.float32)\nx_test = torch.tensor(x_test.astype(float), dtype=torch.float32)\ny_train = torch.tensor(y_train.astype(float), dtype=torch.float32)\ny_test = torch.tensor(y_test.astype(float), dtype=torch.float32)\n\n\n# initalize model architecture, loss function, and optimizer\n\n# tune model hidden layers\nl1 = 20\nl2 = 10\nmodel = nn.Sequential(\n nn.Linear(29, l1), # takes in 29 features (the input layer) and outputs \"l1\"\n nn.ReLU(),\n nn.Linear(l1, l2), # takes in \"l1\" features, outputs \"l2\"\n nn.ReLU(),\n nn.Linear(l2, 1), # takes in \"l2\" features, outputs one feature\n )\n\nloss_criterion = nn.L1Loss() # l1 loss is getting better results compared to MSE\n\n# choose optimizer function from torch.optim socs\n# optimizer = optim.LBFGS(model.parameters(), lr = 0.0001) # customizable\noptimizer = optim.SGD(model.parameters(), lr = 0.001, weight_decay=0.0001) # customizable\n# optimizer = optim.Adamax(model.parameters(), lr=0.0001, weight_decay=0.0001)\n\n# choose scheduler function\nscheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min')\n\n# training\nepochs = 1000\n\npatience = 10 #number of epochs to wait for improvement\nbest_loss_val = float(\"inf\")\nepochs_since_improvement = 0\n\ndef closure():\n y_pred = model(x_train)\n loss = loss_criterion(y_pred, y_train)\n optimizer.zero_grad()\n loss.backward()\n return loss\n\nfor epoch in range(epochs):\n model.train() # sets the model into training mode\n\n loss = optimizer.step(closure)\n scheduler.step(loss)\n #early stopping --- early_stop_callback = EarlyStopping(monitor=\"val_accuracy\", min_delta=0.00, patience=3, verbose=False, mode=\"max\")\n if loss.item() < best_loss_val: \n best_loss_val = loss \n epochs_since_improvement = 0\n #save the best model weights\n best_model_weights = model.state_dict()\n else:\n epochs_since_improvement += 1\n\n if epochs_since_improvement >= patience:\n print(f\"Early stopping at {epoch}.\")\n break\n \n if ((epoch + 1) % 50 == 0):\n print(f'Epoch: {epoch} and loss: {loss.item(): 4f}')\n\nmodel.load_state_dict(best_model_weights) \n\n# predictions/testing\n\nwith torch.no_grad():\n model.eval() # sets model into test/validation mode\n y_hat = model(x_test)\n \n# y_hat = y_hat.numpy()\n\ny_hat = y_hat.numpy().flatten()\ny_test = np.array(y_test).flatten()\n\n# evaluating the model\nr2 = r2_score(y_test, y_hat)\nmae = mean_absolute_error(y_test,y_hat)\n\nprint(\"R2 Score:\",r2)\nprint(\"MAE Score:\",mae)\n\n","repo_name":"ssuni2/Bold_Badgers_Project","sub_path":"models/pytorch.py","file_name":"pytorch.py","file_ext":"py","file_size_in_byte":3639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"13482813489","text":"def solution(s):\n answer = 0\n \n # 파이썬 stack - list 사용\n stack = [s[0]]\n \n for i in range(1, len(s)):\n if len(stack) > 0 and s[i] == stack[-1]: # 파이썬 stack top - list[-1]\n stack.pop() # 파이썬 stack pop - pop한 값 return도 해줌\n else:\n stack.append(s[i])\n \n if len(stack) == 0:\n answer = 1\n \n return answer","repo_name":"g16rim/algorithm_study","sub_path":"프로그래머스/lv2/12973. 짝지어 제거하기/짝지어 제거하기.py","file_name":"짝지어 제거하기.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"9864699021","text":"import pdb\nimport streamlit as st\nfrom datetime import date\nimport numpy as np\nimport yfinance as yf\nfrom prophet import Prophet\nfrom prophet.plot import plot_plotly, plot_components_plotly, add_changepoints_to_plot\nfrom plotly import graph_objs as go\nfrom pytickersymbols import PyTickerSymbols as PTS\n\n\ndef plot_daily_trading_volume(data, selected_stock):\n fig = go.Figure(data=[go.Candlestick(x=data['Date'],\n open=data['Open'],\n high=data['High'],\n low=data['Low'],\n close=data['Close'])])\n fig.layout.update(title_text='Daily Candlestick Chart of ' + str(selected_stock),\n xaxis_rangeslider_visible=True)\n st.plotly_chart(fig)\n\n\n@st.cache_data\ndef load_data(ticker, START, TODAY):\n data_f = yf.download(ticker, START, TODAY)\n data_f.reset_index(inplace=True)\n return data_f\n\n\ndef plot_raw_data(data, selected_stock):\n fig = go.Figure()\n fig.add_trace(go.Scatter(x=data['Date'], y=data['Open'], name=str(selected_stock) + ' Open Price'))\n fig.add_trace(go.Scatter(x=data['Date'], y=data['Close'], name=str(selected_stock) + 'Closing Price'))\n fig.layout.update(title_text='Historical Price of ' + str(selected_stock) + ' at open and close.',\n xaxis_rangeslider_visible=True)\n st.plotly_chart(fig)\n\n\ndef main():\n START = \"2015-01-01\" # Limit of historical data from yfinance\n TODAY = date.today().strftime(\"%Y-%m-%d\")\n\n st.title('Long-Term Stock Price Forecasting For Major Indices')\n stock_data = PTS()\n indices = stock_data.get_all_indices()\n selected_indices = st.selectbox(' Select indices the stock is traded in. ', indices)\n stocks = stock_data.get_stocks_by_index(selected_indices)\n selected_stock = st.selectbox('Select a company ', stocks)['symbol']\n\n n_years = st.slider('Desired length of forecast in years:', 1, 4) # Users choose what time period to predict over\n period = n_years * 365\n data = load_data(selected_stock, START, TODAY)\n st.subheader('Historical Price Action at Open and Close (2015-current) of ' + str(selected_stock))\n\n plot_daily_trading_volume(data, selected_stock)\n plot_raw_data(data, selected_stock)\n\n # Feature selection\n\n # Model selection, training\n # Predict forecast with Prophet.\n df_train = data[['Date', 'Close']]\n df_train = df_train.rename(columns={\"Date\": \"ds\", \"Close\": \"y\"})\n log_df_train = df_train\n log_df_train['cap'] = 3 * df_train['y'] # avoid large swings in prediction\n log_df_train['floor'] = np.zeros(df_train.shape[0]) + 0.5 # Set saturating minimum\n # Log-Scale our data (to prevent negative forecasting),\n # this performs a box-cox transformation or conventionally sets lambda = 0\n m = Prophet()\n m.fit(df_train)\n future = m.make_future_dataframe(periods=period)\n\n forecast = m.predict(future)\n # Visualizations of prophet forecasts\n st.write(f'Forecast plot for {n_years} years using prophet')\n fig1 = plot_plotly(m, forecast)\n st.plotly_chart(fig1)\n st.write(\"Model uncertainty and seasonality\")\n fig2 = plot_components_plotly(m, forecast)\n st.write(fig2)\n","repo_name":"throneofshadow/StockPrediction","sub_path":"main_app.py","file_name":"main_app.py","file_ext":"py","file_size_in_byte":3264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"18366457372","text":"import json\nimport subprocess\nimport sys\nfrom pathlib import Path\nfrom typing import Optional\n\nimport discord\nfrom discord.ext import commands\n\nimport snakeboxed\n\n\nUPDATE_FILE_PATH = Path('update.json')\nREQUIREMENTS_FILE_PATH = Path('requirements.txt')\n\n\nclass Owner(commands.Cog):\n def __init__(self, bot: commands.Bot, pm2_name: str, pm2_binary: str):\n self.bot = bot\n self.pm2_name = pm2_name\n self.pm2_binary = pm2_binary\n\n async def cog_check(self, ctx: commands.Context) -> bool:\n if not await ctx.bot.is_owner(ctx.author):\n raise commands.NotOwner('You do not own this bot.')\n return True\n\n @commands.Cog.listener()\n async def on_ready(self):\n await self.post_update()\n\n @commands.command(hidden=True, aliases=['u'])\n async def update(self, ctx: commands.Context, commit_id: Optional[str]):\n \"\"\"Update the bot.\"\"\"\n await ctx.send(snakeboxed.__version__)\n\n with open(UPDATE_FILE_PATH, 'w') as update_file:\n json.dump(\n {\n 'guild': ctx.guild.id,\n 'channel': ctx.channel.id,\n },\n update_file\n )\n\n pip_upgrade_command = [sys.executable, '-m', 'pip', 'install', '-r', str(REQUIREMENTS_FILE_PATH)]\n pull_command = [str(self.pm2_binary), 'pull', self.pm2_name]\n if commit_id is not None:\n pull_command.append(commit_id)\n\n for command in pip_upgrade_command, pull_command:\n await ctx.send(f\"```bash\\n{' '.join(command)}\\n```\")\n # capture all output in command result stdout together\n command_result_bytes = subprocess.run(\n command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT\n )\n command_result = command_result_bytes.stdout.decode(encoding='utf-8')\n await ctx.send(f'```\\n{command_result}\\n```')\n\n async def post_update(self):\n if not UPDATE_FILE_PATH.is_file():\n return\n with open(UPDATE_FILE_PATH) as update_file:\n update_location_ids = json.load(update_file)\n UPDATE_FILE_PATH.unlink()\n\n update_guild: discord.Guild = self.bot.get_guild(update_location_ids['guild'])\n if update_guild is None:\n return\n\n update_channel: discord.TextChannel = discord.utils.get(\n update_guild.channels, id=update_location_ids['channel']\n )\n if update_channel is None:\n return\n\n return await update_channel.send(snakeboxed.__version__)\n","repo_name":"joelsgp/snakeboxed","sub_path":"snakeboxed/cogs/owner.py","file_name":"owner.py","file_ext":"py","file_size_in_byte":2563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"2350167962","text":"import sys\n\ndef check_commit(commit, jira_project, length_limit=70) -> int:\n if len(commit.subject) > length_limit:\n sys.stderr.write(\"ERROR: Commit subject is too long (limit is \" + str(length_limit) + \"): \" + commit.subject + \"\\n\")\n return 1\n\n if commit.convention[\"type\"] == \"\":\n sys.stderr.write(\"ERROR: Commit message must have a type 'type: subject': \" + commit.subject + \"\\n\")\n return 2\n\n if commit.convention[\"type\"] in [\"Features\", \"Bug Fixes\"]:\n if commit.convention[\"scope\"] is not None and jira_project not in commit.convention[\"scope\"]:\n sys.stderr.write(\"ERROR: Scope for Feature and Bug fix needs to be Jira issue in format '\"+jira_project+\"-XXX': \" + commit.convention[\"scope\"] + \"\\n\")\n return 2\n\n if \"issues\" not in commit.text_refs or len(commit.text_refs[\"issues\"]) == 0:\n sys.stderr.write(\"ERROR: Feature and bug fix must have a Jira issue linked\\n\")\n sys.stderr.write(\"ERROR: You can link the issue either in subject as 'feat(\"+jira_project+\"-XXX): subject': \" + commit.subject+\"\\n\")\n sys.stderr.write(\"ERROR: or anywhere in the body preferably as 'Fixes: \"+jira_project+\"-XXX' or Refs: \"+jira_project+\"-XXX\\n\")\n return 3\n\n return 0\n","repo_name":"RHEnVision/changelog","sub_path":"src/rhenvision_changelog/commit_check.py","file_name":"commit_check.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"30705974266","text":"def nombreyanopeliculas(datos):\n nombre=[]\n year=[]\n duration=[]\n for i in datos:\n duracion=i[\"duration\"]\n duracion=duracion[2:len(duracion)-1]\n duration.append(duracion)\n nombre.append(i[\"title\"])\n year.append(i[\"year\"])\n combinado=zip(nombre,year,duration)\n return combinado\n\ndef nombreyactores(datos):\n nombre=[]\n numactores=[]\n for i in datos:\n nombre.append(i[\"title\"])\n numactores.append(len(i[\"actors\"]))\n combinado=zip(nombre,numactores)\n return combinado\n\ndef buscarsinopsis(palabra1,palabra2,datos):\n sinopsis=[]\n for i in datos:\n if palabra1 in i[\"storyline\"] and palabra2 in i[\"storyline\"]:\n sinopsis.append(i[\"title\"])\n return sinopsis\n\ndef buscarpeliporactor(actor,datos):\n peliculas=[]\n for i in datos:\n for x in i[\"actors\"]:\n if actor == x:\n peliculas.append(i[\"title\"])\n break\n return peliculas\n\ndef sacartrespelis(fecha1,fecha2,datos):\n peliculas=[]\n url=[]\n media=[]\n completa=[]\n suma=0\n cont=0\n for i in datos:\n if i[\"releaseDate\"] >= fecha1 and i[\"releaseDate\"] <= fecha2:\n peliculas.append(i[\"title\"])\n url.append(i[\"posterurl\"])\n for x in i[\"ratings\"]:\n suma=suma+x\n cont=cont+1\n media.append(suma/cont)\n cont=0\n suma=0\n completa=zip(peliculas,url,media)\n return completa\n\n\nimport json\nwith open(\"movies.json\") as fichero:\n\tdatos=json.load(fichero)\n\nprint(\"Elige una opción: \")\nprint(\"1.- Listar el título, año y duración de todas las películas: \")\nprint(\"2.- Mostrar los títulos de las películas y el número de actores/actrices que tiene cada una: \")\nprint(\"3.- Mostrar las películas que contengan en la sinopsis dos palabras dadas: \")\nprint(\"4.- Mostrar las películas en las que ha trabajado un actor dado: \")\nprint(\"5.- Mostrar el título y la url del póster de las tres películas con una media de puntuaciones más alta y lanzadas entre dos fechas dadas: \")\nprint(\"0.- salir: \")\nopcion=int(input(\"¿opcion?: \"))\nwhile opcion >= 0:\n if opcion == 0:\n print(\"Saliendo del programa.\")\n break\n if opcion == 1:\n for i in nombreyanopeliculas(datos):\n print(\"la película\",i[0],\"Se estrenó el año\",i[1],\"con una duracion de\",i[2],\"minutos\")\n if opcion == 2:\n for i in nombreyactores(datos):\n print(\"La pelicula\",i[0],\"tiene\",i[1],\"actores\")\n if opcion == 3:\n palabra1=input(\"Escribe una palabra que contenga la sinopsis: \")\n palabra2=input(\"Escribe otra palabra que contenga la sinopsis: \")\n resultado= buscarsinopsis(palabra1,palabra2,datos)\n if len(resultado)==0:\n print(\"No hay coincidencias.\")\n else:\n print(\"Las peliculas que encajan con los palabras dadas son:\")\n for i in resultado:\n print(i)\n if opcion == 4:\n actor=input(\"Escribe el nombre del actor: \")\n resultado=buscarpeliporactor(actor,datos)\n if len(resultado) == 0:\n print(\"Ese actor no aparece en ninguna pelicula.\")\n else:\n print(\"ese actor aparece en:\")\n for i in resultado:\n print(i)\n if opcion == 5:\n fecha1=input(\"Escribe la primera fecha (ej:. 1992-07-26): \")\n fecha2=input(\"Escribe la segunda fecha (ej:. 1992-07-26): \")\n resultado=sacartrespelis(fecha1,fecha2,datos)\n resultado=list(resultado)\n resultado.sort(key=lambda nota: nota[2])\n resultado=resultado[len(resultado)-3:]\n if len(resultado)==0:\n print(\"No hay peliculas en ese rango de fecha.\")\n else:\n print(\"Las peliculas con ese rango de fechas son:\")\n for i in resultado:\n print(\"titulo:\",i[0],\"Cartel:\",i[1])\n\n print(\"\")\n print(\"Elige una opción: \")\n print(\"1.- Listar el título, año y duración de todas las películas: \")\n print(\"2.- Mostrar los títulos de las películas y el número de actores/actrices que tiene cada una: \")\n print(\"3.- Mostrar las películas que contengan en la sinopsis dos palabras dadas: \")\n print(\"4.- Mostrar las películas en las que ha trabajado un actor dado: \")\n print(\"5.- Mostrar el título y la url del póster de las tres películas con una media de puntuaciones más alta y lanzadas entre dos fechas dadas: \")\n print(\"0.- salir: \")\n opcion=int(input(\"¿opcion?: \"))\n","repo_name":"victormruiz/segundaentregaXMLyJSON","sub_path":"peliculas.py","file_name":"peliculas.py","file_ext":"py","file_size_in_byte":4528,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"73006854204","text":"import inspect\nimport time\n\nfrom engine.controllers.eval_controller import EvalController\nfrom engine.services.csv.eval import eval_to_csv\nfrom engine.services.db.eval import insert_eval_result\nfrom flask import jsonify, request\n\nfrom . import api\n\n\n@api.route(\"/create_domains\", methods=[\"GET\"])\ndef create_domains():\n eval_ctrl = EvalController()\n data = eval_ctrl.create_domains()\n return jsonify(eval=data), 200\n\n\n@api.route(\"/destroy_domains\", methods=[\"GET\"])\ndef destroy_domains():\n eval_ctrl = EvalController()\n data = eval_ctrl.destroy_domains()\n return jsonify(eval=data), 200\n\n\n@api.route(\"/start_domains\", methods=[\"GET\"])\ndef start_domains():\n eval_ctrl = EvalController()\n data = eval_ctrl.start_domains()\n return jsonify(eval=data), 200\n\n\n@api.route(\"/stop_domains\", methods=[\"GET\"])\ndef stop_domains():\n eval_ctrl = EvalController()\n data = eval_ctrl.stop_domains()\n return jsonify(eval=data), 200\n\n\n@api.route(\"/clear_domains\", methods=[\"GET\"])\ndef clear_domains():\n eval_ctrl = EvalController()\n data = eval_ctrl.clear_domains()\n return jsonify(eval={\"clean\": data}), 200\n\n\n@api.route(\"/eval\", methods=[\"GET\"])\ndef eval():\n eval_ctrl = EvalController()\n data = eval_ctrl.run()\n return jsonify(eval=data), 200\n\n\n@api.route(\"/remove-eval\", methods=[\"GET\"])\ndef remove_eval():\n eval_ctrl = EvalController()\n data = eval_ctrl._removeEvalDomains()\n return jsonify(eval=data), 200\n\n\n@api.route(\"/eval/statistics\", methods=[\"GET\"])\ndef eval_statistics():\n eval_ctrl = EvalController()\n data = eval_ctrl._evaluate()\n return jsonify(eval=data), 200\n\n\n@api.route(\"/eval\", methods=[\"POST\"])\ndef new_eval():\n \"\"\"\n templates = [{'id': \"_admin_ubuntu_17_eval_wget\", 'weight': 100}]\n evaluators = [\"load\"]\n :return:\n \"\"\"\n kwargs = request.json\n code = kwargs.get(\"code\")\n eval_ctrl_class = EvalController\n args = inspect.getfullargspec(eval_ctrl_class.__init__).args\n params = {k: v for k, v in kwargs.items() if k in args}\n eval_ctrl = eval_ctrl_class(**params)\n iterations = kwargs.get(\"iterations\", 1)\n objs = []\n for i in range(iterations):\n data = eval_ctrl.run()\n now = int(time.time())\n obj = {\n \"id\": \"{}_{}\".format(code, now),\n \"code\": code,\n \"params\": params,\n \"result\": data,\n \"when\": now,\n }\n insert_eval_result(obj)\n eval_to_csv(code, data)\n d_load = data[\"load\"][\"total_started_domains\"] if data.get(\"load\") else None\n d_ux = data[\"ux\"][\"total\"][\"score\"] if data.get(\"ux\") else None\n objs.append((d_load, d_ux))\n time.sleep(40)\n return jsonify(objs), 200\n","repo_name":"isard-vdi/isard","sub_path":"engine/engine/engine/api/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":2714,"program_lang":"python","lang":"en","doc_type":"code","stars":165,"dataset":"github-code","pt":"41"} +{"seq_id":"71335881084","text":"\"\"\"my_django_project URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import include, path\nfrom employee import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', views.index, name='index'),\n path('payroll/', views.home, name=\"home\"),\n path('departments/', views.department_list, name=\"departments\"),\n path('department/', views.create_department, name=\"department\"),\n path('position/', views.position_list, name='position_index'),\n path('create_position/', views.PositionCreate.as_view(), name='position_create'),\n path('employees/', views.employee_list, name=\"employees\"),\n path('create_employee/', views.create_employee, name=\"create_employee\"),\n]\n","repo_name":"AShoom85/MyPythonCode","sub_path":"L14/my_django_project/my_django_project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"21064508543","text":"import FWCore.ParameterSet.Config as cms\nimport os\n\n#\n# Test file to run the duplicatedMuons analysis in RAW mode i.e. without \n# rerunning the MuonIdProducer sequences.\n#\n# @ Celia Fernandez Madrazo (Wed 19/09/2022)\n#\n\nprocess = cms.Process(\"demo\")\nprocess.load('Configuration.StandardSequences.GeometryDB_cff')\nprocess.load('Configuration.StandardSequences.MagneticField_38T_cff')\nprocess.load(\"Configuration.StandardSequences.FrontierConditions_GlobalTag_cff\")\nprocess.load(\"Configuration.StandardSequences.Reconstruction_cff\")\nprocess.load('Configuration.StandardSequences.Services_cff')\n\n# Debug printout and summary.\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\n\nprocess.options = cms.untracked.PSet(\n wantSummary = cms.untracked.bool(True),\n # Set up multi-threaded run. Must be consistent with config.JobType.numCores in crab_cfg.py.\n #numberOfThreads=cms.untracked.uint32(8)\n)\n\nprocess.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')\nfrom Configuration.AlCa.GlobalTag import GlobalTag\n\n# Select number of events to be processed\nnEvents = -1\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(nEvents) )\n\n# Read events\nisData = True # Always true by default (running on MC is useless)\n#listOfFiles = ['/store/data/Run2022G/Muon/AOD/PromptReco-v1/000/362/433/00000/96cf0f3c-8aa0-45db-b898-a3820a80ecba.root']\nlistOfFiles = ['/store/data/Run2022G/Muon/AOD/PromptReco-v1/000/362/438/00000/79a4613f-bbde-4e41-aefc-d590b2a53f82.root']\n\nif (isData):\n process.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring( listOfFiles ),\n secondaryFileNames = cms.untracked.vstring(),\n skipEvents = cms.untracked.uint32(0)\n )\n process.GlobalTag = GlobalTag(process.GlobalTag, '124X_dataRun3_Prompt_v10')\n\n\n## Load the analysis sequence\nprocess.load(\"MuonReco-Analysis.MuonReco-analyzer.standaloneDuplicates_cfi\")\nprocess.standaloneDuplicates.nameOfOutput = 'outputRAW.root'\nprocess.standaloneDuplicates.muonCollection = 'muons'\n\n## Running sequence\nprocess.p = cms.EndPath(process.standaloneDuplicates)\n\n","repo_name":"CeliaFernandez/MuonReco-analyzer","sub_path":"test/runDuplicates_RAWOnly_cfg.py","file_name":"runDuplicates_RAWOnly_cfg.py","file_ext":"py","file_size_in_byte":2080,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"74568920123","text":"import pytest\n\nfrom bernard.platforms.facebook.layers import MessageTag, MessagingType\n\n\ndef test_construct_check():\n with pytest.raises(ValueError):\n MessagingType(response=True, update=True)\n\n assert MessagingType(response=True)\n\n\ndef test_equality():\n mt1 = MessagingType(response=True)\n mt2 = MessagingType(response=True)\n mt3 = MessagingType(subscription=True)\n\n assert mt1 == mt2\n assert mt1 != mt3\n\n\ndef test_repr():\n mt = MessagingType(response=True)\n assert repr(mt) == \"MessagingType('response')\"\n\n mt = MessagingType(update=True)\n assert repr(mt) == \"MessagingType('update')\"\n\n mt = MessagingType(tag=MessageTag.ACCOUNT_UPDATE)\n assert repr(mt) == \"MessagingType('tag=ACCOUNT_UPDATE')\"\n\n mt = MessagingType(subscription=True)\n assert repr(mt) == \"MessagingType('subscription')\"\n\n\ndef test_serialize():\n mt = MessagingType(response=True)\n assert mt.serialize() == {\"messaging_type\": \"RESPONSE\"}\n\n mt = MessagingType(update=True)\n assert mt.serialize() == {\"messaging_type\": \"UPDATE\"}\n\n mt = MessagingType(tag=MessageTag.ACCOUNT_UPDATE)\n assert mt.serialize() == {\n \"messaging_type\": \"MESSAGE_TAG\",\n \"tag\": \"ACCOUNT_UPDATE\",\n }\n\n mt = MessagingType(subscription=True)\n assert mt.serialize() == {\"messaging_type\": \"NON_PROMOTIONAL_SUBSCRIPTION\"}\n","repo_name":"BernardFW/bernard","sub_path":"tests/issue_0023/test_messaging_type.py","file_name":"test_messaging_type.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"41"} +{"seq_id":"7457302259","text":"import tkinter as tk\nimport requests as rq\nfrom PIL import Image, ImageTk\nimport get_lyrics\nimport autotext\n\nlyrics = \"\"\n\nsession = rq.Session()\n\nclass App(tk.Tk):\n\n def __init__(self, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.geometry(\"300x300\")\n self.resizable(0, 0)\n self.title(\"Lyric Spamaroni\")\n\n container = tk.Frame(self)\n container.pack(side=\"top\", fill=\"both\", expand=True)\n container.grid_rowconfigure(0, weight=1)\n container.grid_columnconfigure(0, weight=1)\n\n self.frames = {}\n for F in (PageOne, PageTwo, StartPage, SearchPage):\n page_name = F.__name__\n frame = F(parent=container, controller=self)\n self.frames[page_name] = frame\n\n # put all of the pages in the same location;\n # the one on the top of the stacking order\n # will be the one that is visible.\n frame.grid(row=0, column=0, sticky=\"nsew\")\n\n self.show_frame(\"StartPage\")\n self.mainloop()\n\n def show_send_frame(self, lyrics, artist, title):\n frame = self.frames[\"PageTwo\"]\n frame.set_lyrics(lyrics, artist, title)\n frame.tkraise()\n\n\n\n def show_frame(self, page_name):\n '''Show a frame for the given page name'''\n frame = self.frames[page_name]\n frame.tkraise()\n\n def start_loop(self):\n self.window.mainloop()\n\n\nclass StartPage(tk.Frame):\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.bool = True\n load = Image.open(\"firstScreen.jpg\")\n load = load.resize((300, 300), Image.ANTIALIAS)\n render = ImageTk.PhotoImage(load)\n pic = tk.Label(image=render, master=self)\n pic.img = render\n pic.place(x=0, y=0)\n pic.bind(\"<Button-1>\", lambda x: controller.show_frame(\"SearchPage\"))\n\n def callback(self, event):\n if self.bool:\n self.bool = False\n else:\n self.bool = True\n print(\"clicked at\", event.x, event.y)\n\n\nclass PageOne(tk.Frame):\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n label = tk.Label(self, text=\"This is page 1\")\n label.pack(side=\"top\", fill=\"x\", pady=10)\n button = tk.Button(self, text=\"Go to the start page\",\n command=lambda: controller.show_frame(\"StartPage\"))\n button.pack()\n\n\nclass PageTwo(tk.Frame):\n\n def set_lyrics(self, lyrics, artist, title):\n self.lyrics.set(lyrics)\n self.artist.set(artist)\n self.title.set(title)\n self.text.set(\"Enter an iPhone number to spam \\\"\" + title + \"\\\" by \" + artist + \" and press enter...\")\n\n def __init__(self, parent, controller):\n self.lyrics = tk.StringVar()\n self.title = tk.StringVar()\n self.artist = tk.StringVar()\n self.text = tk.StringVar()\n tk.Frame.__init__(self, parent)\n self.controller = controller\n\n label = tk.Message(self, textvariable=self.text, width=230, justify=tk.CENTER)\n label.pack(side=\"top\", fill=\"x\")\n button = tk.Button(self, text=\"Go to the start page\",\n command=lambda: controller.show_frame(\"StartPage\"))\n # button.pack()\n self.number = tk.StringVar()\n\n self.entry = tk.Entry(master=self, textvariable=self.number, width=230, justify=tk.CENTER)\n # self.entry.bind('<Return>', self.sendSpam)\n self.entry.pack()\n button = tk.Button(self, text=\"Send!\", command=self.sendSpam)\n button.pack()\n\n label = tk.Message(self, text=\"OR enter a name in your contacts (use number if not working)...\", width=230, justify=tk.CENTER)\n label.pack()\n self.first_name = tk.StringVar()\n self.last_name = tk.StringVar()\n first_entry = tk.Entry(master=self, textvariable=self.first_name)\n last_entry = tk.Entry(master=self, textvariable=self.last_name)\n first_entry.pack()\n last_entry.pack()\n button = tk.Button(self, text=\"Send!\",\n command=self.sendToContact)\n button.pack()\n back = tk.Button(self, text=\"Choose Another Song\",\n command=self.backToSongChoice)\n back.pack()\n\n def backToSongChoice(self):\n self.controller.show_frame(\"SearchPage\")\n\n def sendToContact(self):\n AutoText = autotext.AutoTextMac()\n print(self.first_name.get(), self.last_name.get())\n error = AutoText.message_by_name(self.lyrics.get(), self.first_name.get(), self.last_name.get(), delay=0.7)\n if (error != None):\n print(\"Errored! for name:\", self.first_name.get(), self.last_name.get())\n\n def sendSpam(self):\n print(self.number.get())\n AutoText = autotext.AutoTextMac()\n AutoText.message_by_number(self.lyrics.get(), self.number.get(), delay=0.7)\n\nclass SearchPage(tk.Frame):\n\n def search(self, text):\n self.songs.clear()\n payload = {\n 'method': 'track.search',\n 'limit': 4,\n 'track': self.query.get(),\n 'format': 'json'\n }\n r = self.lastfm_get(payload, url = self.BASE_URL + '/search')\n print(r.status_code)\n print(r)\n js = r.json()\n results = js['results']['trackmatches']['track']\n count = 0\n\n for result in results:\n title = result['name']\n artist = result['artist']\n filename = str(count) + '.jpg'\n handler = self.downloadImage(title, artist, filename=filename)\n if handler == None:\n filename = \"none.jpg\"\n self.songs.append({'title': title,\n 'artist': artist,\n 'image': filename})\n\n self.addRow(title, artist, count, filename)\n count += 1\n temp = len(results)\n while temp < 4:\n self.addRow(\"No Results\", \"NA\", temp, \"none.jpg\")\n temp += 1\n\n def addRow(self, title, artist, row, filename):\n load = Image.open(filename)\n load = load.resize((56, 56), Image.ANTIALIAS)\n render = ImageTk.PhotoImage(load)\n pic = tk.Button(image=render, master=self.pictureFrame, command=lambda i=row: self.selectSong(i))\n pic.img = render\n pic.place(x=0, y=0)\n pic.grid(row=row, column=0)\n titleLabel = tk.Button(text=title, master=self.pictureFrame, padx=6, width=14, anchor=tk.W, justify=tk.LEFT,\n borderwidth=0, command=lambda i=row: self.selectSong(i))\n titleLabel.grid(row=row, column=1)\n artistLabel = tk.Label(text=artist, master=self.pictureFrame, width=8, padx=6, anchor=tk.W, justify=tk.LEFT)\n artistLabel.grid(row=row, column=2)\n\n def selectSong(self, index):\n if len(self.songs) > index:\n song = self.songs[index]\n print(song)\n print((song['artist'], song['title']))\n lyrics = self.get_lyrics(song['artist'], song['title'])\n self.controller.show_frame(\"PageTwo\")\n self.controller.show_send_frame(lyrics, song['artist'], song['title'])\n\n def downloadImage(self, title, artist, filename='image.jpg'):\n payload = {\n 'method': 'track.getInfo',\n 'track': title,\n 'artist': artist,\n 'format': 'json'\n }\n resp = self.lastfm_get(payload, self.BASE_URL + '/images').json()\n if 'album' in resp['track']:\n image_url = resp['track']['album']['image'][1]['#text']\n img_data = session.get(image_url).content\n with open(filename, 'wb') as handler:\n handler.write(img_data)\n return handler\n else:\n return None\n\n def lastfm_get(self, payload, url):\n response = session.get(url, params=payload)\n return response\n\n def temp(self, text):\n self.controller.update_idletasks()\n self.search(text)\n\n def debug(self):\n print(self.query.get())\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.get_lyrics = get_lyrics.get_lyrics\n self.AutoTextMac = autotext.AutoTextMac\n\n self.BASE_URL = 'https://tiktokbikbok.herokuapp.com/api'\n self.songs = []\n masterFrame = tk.Frame(master=self)\n masterFrame.pack()\n self.frame = tk.Frame(master=masterFrame)\n self.frame.pack()\n self.var = tk.StringVar()\n self.query = tk.StringVar()\n self.query.trace(\"w\", lambda name, index, mode, sv=self.query: self.debug())\n self.topLabel = tk.Label(text=\"Enter the song title\", master=self.frame)\n self.topLabel.pack()\n self.entry = tk.Entry(master=self.frame, textvariable=self.query)\n self.entry.bind('<Return>', self.temp)\n self.entry.pack()\n\n self.frame2 = tk.Frame(master=self)\n\n self.pictureFrame = tk.Frame(master=self.frame, height=50, width=200)\n self.pictureFrame.pack()\n\n def show_frame(self, page_name):\n frame = self.frames[page_name]\n frame.tkraise()\n\n\n def start_loop(self):\n self.window.mainloop()\n","repo_name":"ShaylanDias/MusicalMessage","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":9321,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"12909356594","text":"from functools import partial\nfrom typing import List, Optional\n\nfrom pharmpy.deps import pandas as pd\nfrom pharmpy.deps import sympy\nfrom pharmpy.deps.scipy import stats\nfrom pharmpy.internals.fn.signature import with_same_arguments_as\nfrom pharmpy.internals.fn.type import with_runtime_arguments_type_check\nfrom pharmpy.model import (\n Assignment,\n EstimationStep,\n EstimationSteps,\n Model,\n NormalDistribution,\n Parameter,\n Parameters,\n RandomVariables,\n Statements,\n)\nfrom pharmpy.modeling import (\n add_population_parameter,\n add_time_after_dose,\n create_symbol,\n get_mdv,\n has_proportional_error_model,\n set_combined_error_model,\n set_iiv_on_ruv,\n set_initial_estimates,\n set_power_on_ruv,\n set_proportional_error_model,\n)\nfrom pharmpy.modeling.blq import has_blq_transformation\nfrom pharmpy.modeling.error import remove_error_model, set_time_varying_error_model\nfrom pharmpy.tools import (\n summarize_errors,\n summarize_individuals,\n summarize_individuals_count_table,\n summarize_modelfit_results,\n)\nfrom pharmpy.tools.common import summarize_tool, update_initial_estimates\nfrom pharmpy.tools.modelfit import create_fit_workflow\nfrom pharmpy.workflows import Task, Workflow, WorkflowBuilder, call_workflow\nfrom pharmpy.workflows.results import ModelfitResults\n\nfrom .results import RUVSearchResults, calculate_results\n\nSKIP = frozenset(('IIV_on_RUV', 'power', 'combined', 'time_varying'))\n\n\ndef create_workflow(\n model: Optional[Model] = None,\n results: Optional[ModelfitResults] = None,\n groups: int = 4,\n p_value: float = 0.001,\n skip: Optional[List[str]] = None,\n max_iter: Optional[int] = 3,\n dv: Optional[int] = None,\n):\n \"\"\"Run the ruvsearch tool. For more details, see :ref:`ruvsearch`.\n\n Parameters\n ----------\n model : Model\n Pharmpy model\n results : ModelfitResults\n Results of model\n groups : int\n The number of bins to use for the time varying models\n p_value : float\n The p-value to use for the likelihood ratio test\n skip : list\n A list of models to not attempt.\n max_iter : int\n Number of iterations to run (1, 2, or 3). For models with BLQ only one iteration is supported.\n dv : int\n Which DV to assess the error model for.\n\n Returns\n -------\n RUVSearchResults\n Ruvsearch tool result object\n\n Examples\n --------\n >>> from pharmpy.modeling import load_example_model\n >>> from pharmpy.tools import run_ruvsearch, load_example_modelfit_results\n >>> model = load_example_model(\"pheno\")\n >>> results = load_example_modelfit_results(\"pheno\")\n >>> run_ruvsearch(model=model, results=results) # doctest: +SKIP\n\n \"\"\"\n\n wb = WorkflowBuilder(name=\"ruvsearch\")\n start_task = Task('start_ruvsearch', start, model, groups, p_value, skip, max_iter, dv)\n wb.add_task(start_task)\n task_results = Task('results', _results)\n wb.add_task(task_results, predecessors=[start_task])\n return Workflow(wb)\n\n\ndef create_iteration_workflow(model, groups, cutoff, skip, current_iteration, dv):\n wb = WorkflowBuilder()\n\n start_task = Task('start_iteration', _start_iteration, model)\n wb.add_task(start_task)\n\n task_base_model = Task(\n 'create_base_model', partial(_create_base_model, current_iteration=current_iteration, dv=dv)\n )\n wb.add_task(task_base_model, predecessors=start_task)\n\n tasks = []\n if 'IIV_on_RUV' not in skip:\n task_iiv = Task(\n 'create_iiv_on_ruv_model',\n partial(_create_iiv_on_ruv_model, current_iteration=current_iteration, dv=None),\n )\n tasks.append(task_iiv)\n wb.add_task(task_iiv, predecessors=task_base_model)\n\n if 'power' not in skip and 'combined' not in skip:\n task_power = Task(\n 'create_power_model',\n partial(_create_power_model, current_iteration=current_iteration, dv=None),\n )\n wb.add_task(task_power, predecessors=task_base_model)\n tasks.append(task_power)\n task_combined = Task(\n 'create_combined_error_model',\n partial(_create_combined_model, current_iteration=current_iteration),\n )\n wb.add_task(task_combined, predecessors=task_base_model)\n tasks.append(task_combined)\n\n if 'time_varying' not in skip:\n for i in range(1, groups):\n tvar = partial(\n _create_time_varying_model,\n groups=groups,\n i=i,\n current_iteration=current_iteration,\n dv=None,\n )\n task = Task(f\"create_time_varying_model{i}\", tvar)\n tasks.append(task)\n wb.add_task(task, predecessors=task_base_model)\n\n fit_wf = create_fit_workflow(n=1 + len(tasks))\n wb.insert_workflow(fit_wf, predecessors=[task_base_model] + tasks)\n post_pro = partial(post_process, cutoff=cutoff, current_iteration=current_iteration, dv=dv)\n task_post_process = Task('post_process', post_pro)\n wb.add_task(task_post_process, predecessors=[start_task] + fit_wf.output_tasks)\n\n return Workflow(wb)\n\n\ndef proportional_error_workflow(model):\n wb = WorkflowBuilder()\n\n prop_start = Task('Check_proportional', _start_iteration, model)\n wb.add_task(prop_start)\n\n if not has_proportional_error_model(model):\n change_name_task = Task(\"Change_proportional_description\", _change_proportional_name)\n wb.add_task(change_name_task, predecessors=prop_start)\n\n convert_to_prop_task = Task(\"Convert_to_proportional\", set_proportional_error_model)\n wb.add_task(convert_to_prop_task, predecessors=change_name_task)\n\n fit_wf = create_fit_workflow(n=1)\n wb.insert_workflow(fit_wf, predecessors=convert_to_prop_task)\n return Workflow(wb)\n\n\ndef _change_proportional_name(model):\n model = model.replace(\n name='prop_error',\n description='Input model with proportional error model',\n )\n return model\n\n\ndef start(context, model, groups, p_value, skip, max_iter, dv):\n cutoff = float(stats.chi2.isf(q=p_value, df=1))\n if skip is None:\n skip = []\n\n input_model = model\n # Check if model has a proportional error\n proportional_workflow = proportional_error_workflow(input_model)\n model = call_workflow(proportional_workflow, 'Convert_error_model', context)\n\n model_results = []\n if model == input_model:\n selected_models = [model]\n else:\n selected_models = [input_model, model]\n cwres_models = []\n tool_database = None\n for current_iteration in range(1, max_iter + 1):\n wf = create_iteration_workflow(model, groups, cutoff, skip, current_iteration, dv=dv)\n res, best_model, selected_model_name = call_workflow(\n wf, f'results{current_iteration}', context\n )\n if current_iteration == 1:\n model_results.append(model.modelfit_results)\n model_results.append(best_model.modelfit_results)\n\n cwres_models.append(res.cwres_models)\n tool_database = res.tool_database\n\n if not selected_model_name.startswith('base'):\n selected_models.append(best_model)\n\n model = best_model\n\n if selected_model_name.startswith('base'):\n break\n elif selected_model_name.startswith('time_varying'):\n skip.append('time_varying')\n else:\n skip.append(selected_model_name)\n\n # Check that there actually occured an improvement from the initial model.\n delta_ofv = input_model.modelfit_results.ofv - model.modelfit_results.ofv\n if delta_ofv < cutoff:\n model = input_model\n\n sumind = summarize_individuals(selected_models)\n sumcount = summarize_individuals_count_table(df=sumind)\n sum_models = summarize_modelfit_results(model_results)\n sum_models['step'] = list(range(len(sum_models)))\n summf = sum_models.reset_index().set_index(['step', 'model'])\n summary_tool = _create_summary_tool(selected_models, cutoff)\n summary_errors = summarize_errors(m.modelfit_results for m in selected_models)\n\n res = RUVSearchResults(\n cwres_models=pd.concat(cwres_models),\n summary_individuals=sumind,\n summary_individuals_count=sumcount,\n final_model=model,\n summary_models=summf,\n summary_tool=summary_tool,\n summary_errors=summary_errors,\n tool_database=tool_database,\n )\n return res\n\n\ndef _create_summary_tool(selected_models, cutoff):\n model_names = [model.name for model in selected_models]\n iteration_map = {model.name: model_names.index(model.name) for model in selected_models}\n\n base_model = selected_models[0]\n ruvsearch_models = selected_models[1:]\n\n sum_tool = summarize_tool(ruvsearch_models, base_model, 'ofv', cutoff).reset_index()\n sum_tool['step'] = sum_tool['model'].map(iteration_map)\n sum_tool_by_iter = sum_tool.set_index(['step', 'model']).sort_index()\n\n # FIXME: Workaround since rank_models will exclude ranking of base model since dofv will be 0\n sum_tool_by_iter.loc[(0, base_model.name), 'ofv'] = base_model.modelfit_results.ofv\n sum_tool_by_iter.loc[(0, base_model.name), 'dofv'] = 0\n\n return sum_tool_by_iter.drop(columns=['rank'])\n\n\ndef _start_iteration(model):\n return model\n\n\ndef _results(res):\n return res\n\n\ndef post_process(context, start_model, *models, cutoff, current_iteration, dv):\n res = calculate_results(models)\n best_model_unfitted, selected_model_name = _create_best_model(\n start_model, res, current_iteration, cutoff=cutoff, dv=dv\n )\n if best_model_unfitted is not None:\n fit_wf = create_fit_workflow(models=[best_model_unfitted])\n best_model = call_workflow(fit_wf, f'fit{current_iteration}', context)\n if best_model.modelfit_results is not None:\n best_model_check = [\n best_model.modelfit_results.ofv,\n best_model.modelfit_results.residuals,\n best_model.modelfit_results.predictions,\n ]\n if all(check is not None for check in best_model_check):\n delta_ofv = start_model.modelfit_results.ofv - best_model.modelfit_results.ofv\n if delta_ofv > cutoff:\n return (res, best_model, selected_model_name)\n\n return (res, start_model, f\"base_{current_iteration}\")\n\n\ndef _create_base_model(input_model, current_iteration, dv):\n theta = Parameter('theta', 0.1)\n omega = Parameter('omega', 0.01, lower=0)\n sigma = Parameter('sigma', 1, lower=0)\n params = Parameters((theta, omega, sigma))\n\n eta_name = 'eta_base'\n eta = NormalDistribution.create(eta_name, 'iiv', 0, omega.symbol)\n sigma_name = 'epsilon'\n sigma = NormalDistribution.create(sigma_name, 'ruv', 0, sigma.symbol)\n rvs = RandomVariables.create([eta, sigma])\n\n y = Assignment(\n sympy.Symbol('Y'), theta.symbol + sympy.Symbol(eta_name) + sympy.Symbol(sigma_name)\n )\n statements = Statements([y])\n\n name = f'base_{current_iteration}'\n\n est = EstimationStep.create('foce', interaction=True, maximum_evaluations=9999)\n\n base_model = Model.create(\n parameters=params,\n random_variables=rvs,\n statements=statements,\n name=name,\n description=name,\n estimation_steps=EstimationSteps.create([est]),\n dependent_variables={y.symbol: 1},\n )\n base_model = base_model.replace(dataset=_create_dataset(input_model, dv))\n return base_model\n\n\ndef _create_iiv_on_ruv_model(input_model, current_iteration, dv):\n model = set_iiv_on_ruv(input_model, dv)\n name = f'IIV_on_RUV_{current_iteration}'\n model = model.replace(name=name, description=name)\n return model\n\n\ndef _create_power_model(input_model, current_iteration, dv):\n model = set_power_on_ruv(\n input_model, ipred='IPRED', lower_limit=None, zero_protection=True, dv=dv\n )\n name = f'power_{current_iteration}'\n model = model.replace(name=name, description=name)\n return model\n\n\ndef _create_time_varying_model(input_model, groups, i, current_iteration, dv):\n quantile = i / groups\n cutoff = input_model.dataset['TAD'].quantile(q=quantile)\n model = set_time_varying_error_model(input_model, cutoff=cutoff, idv='TAD', dv=dv)\n name = f\"time_varying{i}_{current_iteration}\"\n model = model.replace(name=name, description=name)\n return model\n\n\ndef _create_combined_model(input_model, current_iteration):\n model = remove_error_model(input_model)\n sset = model.statements\n ruv_prop = create_symbol(model, 'epsilon_p')\n ruv_add = create_symbol(model, 'epsilon_a')\n ipred = sympy.Symbol('IPRED')\n s = sset[0]\n assert isinstance(s, Assignment)\n s = Assignment(s.symbol, s.expression + ruv_prop + ruv_add / ipred)\n\n prop_name = 'sigma_prop'\n model = add_population_parameter(model, prop_name, 1, lower=0)\n df = model.dataset\n assert df is not None\n df = df.copy()\n df['IPRED'].replace(0, 2.225e-307, inplace=True)\n model = model.replace(dataset=df)\n ipred_min = df['IPRED'].min()\n sigma_add_init = ipred_min / 2\n add_name = 'sigma_add'\n model = add_population_parameter(model, add_name, sigma_add_init, lower=0)\n\n eps_prop = NormalDistribution.create(ruv_prop.name, 'ruv', 0, sympy.Symbol(prop_name))\n eps_add = NormalDistribution.create(ruv_add.name, 'ruv', 0, sympy.Symbol(add_name))\n name = f'combined_{current_iteration}'\n model = model.replace(\n statements=s + sset[1:],\n random_variables=model.random_variables + [eps_prop, eps_add],\n name=name,\n description=name,\n )\n return model\n\n\ndef _create_dataset(input_model: Model, dv):\n # Non-observations have already been filtered\n results = input_model.modelfit_results\n assert results is not None\n residuals = results.residuals\n assert residuals is not None\n input_dataset = input_model.dataset\n assert input_dataset is not None\n if dv is not None:\n observation_label = input_model.datainfo.dv_column.name\n input_dataset = input_dataset.query(f'{observation_label} != 0').reset_index(\n drop=True\n ) # filter non-observations\n indices = input_dataset.index[input_dataset['DVID'] == dv].tolist()\n residuals = residuals.iloc[indices]\n cwres = residuals['CWRES'].reset_index(drop=True)\n if has_blq_transformation(input_model):\n cwres = cwres.loc[cwres != 0]\n predictions = results.predictions\n assert predictions is not None\n if 'CIPREDI' in predictions:\n ipredcol = 'CIPREDI'\n elif 'IPRED' in predictions:\n ipredcol = 'IPRED'\n else:\n raise ValueError(\"Need CIPREDI or IPRED\")\n ipred = predictions[ipredcol].reset_index(drop=True)\n mdv = get_mdv(input_model)\n mdv = mdv.reset_index(drop=True)\n label_id = input_model.datainfo.id_column.name\n input_id = input_dataset[label_id].astype('int64').squeeze().reset_index(drop=True)\n input_model = add_time_after_dose(input_model)\n tad_label = input_model.datainfo.descriptorix['time after dose'][0].name\n tad = input_model.dataset[tad_label].squeeze().reset_index(drop=True)\n df = pd.concat([mdv, input_id, tad, ipred], axis=1)\n df = df[df['MDV'] == 0].reset_index(drop=True)\n df = pd.concat([df, cwres], axis=1).rename(columns={'CWRES': 'DV', ipredcol: 'IPRED'})\n df = df.loc[df['DV'].notna()]\n return df\n\n\ndef _time_after_dose(model):\n if 'TAD' in model.dataset:\n pass\n else:\n model = add_time_after_dose(model)\n return model\n\n\ndef _create_best_model(model, res, current_iteration, dv, groups=4, cutoff=3.84):\n if not res.cwres_models.empty and any(res.cwres_models['dofv'] > cutoff):\n model = update_initial_estimates(model)\n selected_model_name = f'base_{current_iteration}'\n idx = res.cwres_models['dofv'].idxmax()\n name = idx[0]\n\n if current_iteration == 1:\n base_description = ''\n else:\n base_description = model.description + '+'\n model = model.replace(\n name=f'best_ruvsearch_{current_iteration}', description=base_description + name\n )\n\n if name.startswith('power'):\n model = set_power_on_ruv(model, dv=dv)\n model = set_initial_estimates(\n model,\n {\n 'power1': res.cwres_models['parameters']\n .loc['power', 1, current_iteration]\n .get('theta')\n + 1\n },\n )\n elif name.startswith('IIV_on_RUV'):\n model = set_iiv_on_ruv(model, dv=dv)\n model = set_initial_estimates(\n model,\n {\n 'IIV_RUV1': res.cwres_models['parameters']\n .loc['IIV_on_RUV', 1, current_iteration]\n .get('omega')\n },\n )\n elif name.startswith('time_varying'):\n model = _time_after_dose(model)\n i = int(name[-1])\n quantile = i / groups\n df = _create_dataset(model, dv=dv)\n tad = df['TAD']\n cutoff_tvar = tad.quantile(q=quantile)\n model = set_time_varying_error_model(model, cutoff=cutoff_tvar, idv='TAD', dv=dv)\n model = set_initial_estimates(\n model,\n {\n 'time_varying': res.cwres_models['parameters']\n .loc[f\"time_varying{i}\", 1, current_iteration]\n .get('theta')\n },\n )\n else:\n model = set_combined_error_model(model, dv=dv)\n model = set_initial_estimates(\n model,\n {\n 'sigma_prop': res.cwres_models['parameters']\n .loc['combined', 1, current_iteration]\n .get('sigma_prop'),\n 'sigma_add': res.cwres_models['parameters']\n .loc['combined', 1, current_iteration]\n .get('sigma_add'),\n },\n )\n\n selected_model_name = name\n else:\n model = None\n selected_model_name = None\n return model, selected_model_name\n\n\n@with_runtime_arguments_type_check\n@with_same_arguments_as(create_workflow)\ndef validate_input(model, groups, p_value, skip, max_iter, dv):\n if groups <= 0:\n raise ValueError(f'Invalid `groups`: got `{groups}`, must be >= 1.')\n\n if not 0 < p_value <= 1:\n raise ValueError(f'Invalid `p_value`: got `{p_value}`, must be a float in range (0, 1].')\n\n if skip is not None and not set(skip).issubset(SKIP):\n raise ValueError(f'Invalid `skip`: got `{skip}`, must be None/NULL or a subset of {SKIP}.')\n\n if max_iter < 1 or max_iter > 3:\n raise ValueError(f'Invalid `max_iter`: got `{max_iter}`, must be int in range [1, 3].')\n\n if model is not None:\n if model.modelfit_results is None:\n raise ValueError(f'Invalid `model`: {model} is missing modelfit results.')\n\n residuals = model.modelfit_results.residuals\n if residuals is None or 'CWRES' not in residuals:\n raise ValueError(\n f'Invalid `model`: please check {model.name}.mod file to'\n f' make sure ID, TIME, CWRES are in $TABLE.'\n )\n\n predictions = model.modelfit_results.predictions\n if predictions is None or ('CIPREDI' not in predictions and 'IPRED' not in predictions):\n raise ValueError(\n f'Invalid `model`: please check {model.name}.mod file to'\n f' make sure ID, TIME, CIPREDI (or IPRED) are in $TABLE.'\n )\n\n if has_blq_transformation(model) and max_iter > 1:\n raise ValueError(\n f'Invalid `max_iter`: got `{max_iter}`,only 1 iteration is supported '\n f'for models with BLQ transformation.'\n )\n\n if dv:\n if 'DVID' not in model.dataset.columns:\n raise ValueError(\"No column DVID in dataset.\")\n else:\n if dv not in set(model.dataset['DVID']):\n raise ValueError(f\"No DVID = {dv} in dataset.\")\n","repo_name":"pharmpy/pharmpy","sub_path":"src/pharmpy/tools/ruvsearch/tool.py","file_name":"tool.py","file_ext":"py","file_size_in_byte":20199,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"41"} +{"seq_id":"719626975","text":"from queue import Queue\n\nclass Node:\n def __init__(self, val) -> None:\n self.key = val\n self.next = None\n\nclass LinkedList:\n def __init__(self) -> None:\n self.head = None\n self.tail = None\n \n def insert(self, val):\n new_node = Node(val)\n\n if self.head == None:\n self.head = new_node\n self.tail = new_node\n else:\n self.tail.next = new_node\n self.tail = new_node\n\n return self\n \n def iterate(self, src):\n temp = self.head\n\n print(src, end=\"::\")\n while temp != None:\n print(temp.key, end=\"-->\")\n temp = temp.next\n\n print(None)\n \n def delete(self, val):\n\n temp = self.head\n prev = None\n\n if temp.key == val:\n self.head = temp.next\n else:\n while temp.key != val:\n prev = temp\n temp = temp.next\n \n prev.next = temp.next\n\n\n# ll = LinkedList()\n# ll.insert(5)\n# ll.insert(6)\n# ll.insert(7)\n# ll.insert(8)\n# ll.insert(9)\n# ll.iterate()\n# ll.delete(5)\n# ll.iterate()\n\n\nclass AdjList:\n def __init__(self) -> None:\n self.adjList = {}\n self.ll = None\n\n def insert(self, src, dest):\n if src not in self.adjList:\n self.ll = LinkedList()\n \n self.adjList[src] = self.ll.insert(dest)\n \n def iterate(self):\n for adj_keys in self.adjList:\n self.adjList[adj_keys].iterate(adj_keys)\n\n def deleteEdge(self, src, dest):\n if src in self.adjList:\n self.adjList[src].delete(dest)\n\n def bfs(self, start):\n\n visited = []\n queue = Queue()\n queue.put(start)\n\n while not queue.empty():\n vertex = queue.get()\n\n if vertex not in visited and vertex != None:\n visited.append(vertex)\n \n temp = self.adjList[vertex].head\n\n while temp != None:\n if temp.key not in visited:\n queue.put(temp.key)\n temp = temp.next\n \n return visited\n\nadjLst = AdjList()\nadjLst.insert('A', 'C')\nadjLst.insert('A', 'E')\n\nadjLst.insert('B', None)\n\nadjLst.insert('C', 'B')\nadjLst.insert('C', 'G')\n\nadjLst.insert('D', None)\n\nadjLst.insert('E', 'H')\n\nadjLst.insert('H', 'D')\n\nadjLst.insert('G', None)\n\n\nadjLst.iterate()\n\nprint(adjLst.bfs('A'))\n\n\n# print(\"##############\")\n# adjLst.deleteEdge(0, 1)\n# adjLst.iterate()\n","repo_name":"shkaashir/dsa","sub_path":"Graph/AdjList.py","file_name":"AdjList.py","file_ext":"py","file_size_in_byte":2524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"41506663205","text":"#!/usr/bin/env python\n#vim:fileencoding=utf-8\n\nfrom gameobjects import *\n\nclass ExampleTower(GameObject, Tower):\n resource_name = 'exampletower.png'\n\n # can be changed\n damage = 5\n radius = 15\n cost = 5\n recharge_time = 2\n bullet_speed = 5\n\n # do not change\n size = 2\n\n def __init__(self, g_lefttop, world):\n GameObject.__init__(self)\n self.rect.topleft = util.game2tlscreen(g_lefttop)\n self.g_pos = Vec(util.screen2fgame(self.rect.center))\n self.creeps = world.creeps\n self.missles = world.missles\n self.current_recharge = 0\n self.recharge_ticks = self.recharge_time * TICK_PER_SEC\n\n def update(self, ticks):\n self.current_recharge -= ticks\n if self.current_recharge > 0:\n return\n\n creep = self._find_target()\n if creep:\n missle = SimpleBullet(\n self.g_pos, creep, self.damage, self.bullet_speed)\n self.missles.add(missle)\n self.current_recharge = self.recharge_ticks\n \n def _find_target(self):\n for creep in self.creeps:\n distvec = creep.g_pos - self.g_pos\n if abs(distvec) <= self.radius:\n return creep\n return None\n","repo_name":"offmeplz/9game","sub_path":"exampletower.py","file_name":"exampletower.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"20373832312","text":"from script.memorize import *\nfrom script.maths import isprime2\nps = [2,3,5,7,11,13,17,19]\ntop = 0\n@memo\ndef nextprime(p):\n if p%2==0:p+=1\n while not isprime2(p):\n p+=2\n if p>=top:return []\n return [p]+nextprime(p+1)\n\ndef changetop():\n global top\n top +=1000\n\ndef primes(x):\n if x>1000:x = x//1000\n global top\n top = 1000\n p = [2,3]\n s = 1\n while s<=x:\n p+=nextprime(p[-1]+2)\n changetop()\n s+=1\n return p\nif __name__=='__main__':\n i = (primes(10**6))\n\n","repo_name":"gtmanfred/Euler","sub_path":"script/nextp.py","file_name":"nextp.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"41"} +{"seq_id":"40942763","text":"# -*- coding: utf-8 -*-\n\"\"\"\n第 0011 题:\n敏感词文本文件 filtered_words.txt,里面的内容为以下内容,\n当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights。\n\n北京\n程序员\n公务员\n领导\n牛比\n牛逼\n你娘\n你妈\nlove\nsex\njiangge\n\"\"\"\nword_filter=set()\nwith open('source/0011/filtered_words.txt') as f:\n for w in f.readlines():\n word_filter.add(w.strip())\n\nwhile True:\n s=input()\n if s == 'exit':\n break\n if s in word_filter:\n print('Freedom')\n else:\n print('Human Rights')\n","repo_name":"Show-Me-the-Code/python","sub_path":"Lyndon1994/0011.py","file_name":"0011.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"zh","doc_type":"code","stars":3686,"dataset":"github-code","pt":"41"} +{"seq_id":"28086065083","text":"import datetime\n\n\ndef start():\n name = input()\n s = datetime.datetime.today().strftime(\"%a %d %b %Y, %H:%M:%S\")\n file = open('hardlopers.txt', 'a')\n file.write(s + ', ' + name + '\\n')\n file.close()\n start()\n\nstart()\n","repo_name":"joostlek/python_school","sub_path":"Practice Exercise 5/Practice Exercise 5_4.py","file_name":"Practice Exercise 5_4.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"72513116282","text":"import csv\nimport pygal\nfrom pygal.style import LightSolarizedStyle as LCS, LightenStyle as LS\n\nwith open('21vek.csv') as f:\n reader = csv.reader(f)\n list_data = []\n for row in reader:\n list_data.append(row)\n # Del empty data from our csv file\n list_data = list_data[::2]\n for_graphic = []\n # Some prices of grass-cutter didn't have a price, we del them\n for el in list_data:\n if el[1] == '':\n pass\n else:\n for_graphic.append(el)\n# Sort our data by price of grass-cutters\nfor_graphic.sort(key=lambda price: int(price[1]))\n\n\nmy_style = LS('#333366', base_style=LCS)\nchart = pygal.Bar(style=my_style, x_label_rotation=45, show_legend=False)\nchart.title = 'Max and min prices of grass-cutter'\n# Make a list of some y_min_max_prices and their x_names for better visualization into the graphic\nchart.x_labels = [el[0] for el in for_graphic][:15]+[el[0] for el in for_graphic][-15:]\nchart.add('', [int(el[1]) for el in for_graphic][:15]+[int(el[1]) for el in for_graphic][-15:])\nchart.render_to_file('grass_cutter.svg')\n\n\n","repo_name":"gorgick/raiting_prices_parser","sub_path":"reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"7449708483","text":"from datetime import datetime, tzinfo\nfrom time import time\nfrom django.utils import timezone\nfrom rest_framework.routers import reverse\nfrom django.contrib.auth import get_user_model\nfrom rest_framework import serializers\nfrom .models import Link\nfrom .hash_generator import random_md5, build_full_url\nfrom django.db import transaction\nfrom rest_framework.authtoken.models import Token\nfrom .exceptions import *\nfrom dateutil import tz\nfrom datetime import datetime\n\nUser = get_user_model()\n\n\nclass LinkSerializer(serializers.ModelSerializer):\n url = serializers.SerializerMethodField()\n owner = serializers.SerializerMethodField()\n analytic = serializers.SerializerMethodField()\n\n class Meta:\n model = Link\n fields = [\n \"url\",\n \"id\",\n \"owner\",\n \"short_link\",\n \"long_link\",\n \"date_created\",\n \"last_visited_date\",\n \"visit_count\",\n 'analytic'\n ]\n extra_kwargs = {\"owner\": {\n \"read_only\": True, }\n }\n\n def create(self, validated_data):\n request = self.context.get(\"request\")\n long_link = validated_data[\"long_link\"]\n user = request.user if request.user.is_authenticated else None\n link = Link.objects.filter(owner=user, long_link=long_link)\n if link.exists():\n raise AvailableAlready(\n {\"message\": \"link already exist\", \"short_link\": link.first().short_link})\n base_url = build_full_url(request)\n validated_data[\"short_link\"] = f'{base_url}/{random_md5(long_link, user)}'\n\n return super().create(validated_data)\n\n def update(self, instance, validated_data):\n request = self.context.get(\"request\")\n long_link = validated_data[\"long_link\"]\n validated_data[\"short_link\"] = f\"{request.get_host()}/{random_md5(long_link, instance.owner)}\"\n return super().update(instance, validated_data)\n\n def get_url(self, obj):\n request = self.context.get(\"request\")\n url = reverse(\"link-detail\", request=request, kwargs={\"pk\": obj.id})\n return url\n\n def get_owner(self, obj):\n if obj.owner is None:\n return None\n return obj.owner.email\n\n def get_analytic(self, obj):\n obj_analytic = obj.analyticbydatetime_set\n\n analytic = {\"date_time_anaylytic\": obj_analytic.get_analytic(obj),\n \"other_analytic\": {\"Browser\": obj.analytic.browser,\n \"OS\": obj.analytic.os,\n \"Device\": obj.analytic.device,\n \"Referer\": obj.analytic.referer,\n \"Country\": obj.analytic.country\n }\n }\n return analytic\n\n def to_internal_value(self, data):\n data = super().to_internal_value(data)\n\n long_link = data.get(\"long_link\")\n try:\n tzinfo = User.objects.get(email=data.get(\"owner\")).timezone\n except BaseException:\n tzinfo = \"UTC\"\n date_created = data.get(\"date_created\")\n last_visited_date = data.get(\"last_visited_date\")\n usertzinfo = tz.gettz(tzinfo)\n\n date_created = change_to_owner_tz(date_created, usertzinfo)\n last_visited_date = change_to_owner_tz(last_visited_date, usertzinfo)\n print(long_link, \"\\n\", len(long_link))\n # if len(long_link) > 255:\n # raise LinkTooLong({\"error\":\"Link cannot be greater than 255\"})\n\n return data\n\n def to_representation(self, instance):\n instance = super().to_representation(instance)\n try:\n tzinfo = User.objects.get(email=instance.get(\"owner\")).timezone\n except BaseException:\n tzinfo = \"UTC\"\n usertzinfo = tz.gettz(tzinfo)\n user_current_month = timezone.localtime(timezone=usertzinfo).month\n user_current_date = timezone.localtime(timezone=usertzinfo).date()\n date_created = instance.get(\"date_created\")\n last_visited_date = instance.get(\"last_visited_date\")\n date_created = change_to_owner_tz(date_created, usertzinfo)\n print(last_visited_date)\n last_visited_date = change_to_owner_tz(last_visited_date, usertzinfo)\n instance[\"date_created\"] = str(date_created)\n instance[\"last_visited_date\"] = last_visited_date if last_visited_date is None else str(\n last_visited_date)\n instance[\"user_current_month\"] = str(user_current_month)\n instance[\"user_time_zone\"] = str(tzinfo)\n instance[\"user_current_date\"] = str(user_current_date)\n return instance\n\n\ndef change_to_owner_tz(date: str, tz: tzinfo):\n if date == \"None\" or date is None:\n return date\n try:\n create_date = datetime.strptime(date, \"%Y-%m-%dT%H:%M:%S.%f%z\")\n except BaseException:\n create_date = datetime.strptime(date, \"%Y-%m-%dT%H:%M:%S%z\")\n\n date_with_tz = create_date.astimezone(tz=tz)\n return date_with_tz\n\n\n'''\nclass UserRegisterSerializer(serializers.ModelSerializer):\n confirm_password = serializers.CharField(write_only = True)\n\n class Meta:\n model= User\n fields = [\n \"username\",\n \"password\",\n \"confirm_password\"\n ]\n\n\n def validate(self, validated_data):\n password = validated_data[\"password\"]\n confirm_password = validated_data[\"confirm_password\"]\n username = validated_data[\"username\"]\n if password != confirm_password:\n raise serializers.ValidationError({\"password\":\"Password must match\",\"confirm_password\":\"Password must match\"}, code=\"unmatch-password\")\n user = User.objects.filter(username=username).exists()\n if user:\n raise serializers.ValidationError({\"username\":\"Usermame already exist\"})\n\n return validated_data\n\n\n\n def create(self, validated_data):\n username = validated_data[\"username\"]\n password = validated_data[\"password\"]\n with transaction.atomic():\n user = User.objects.create(username=username, password=password)\n token = Token.objects.create(user=user)\n\n return user\n\n'''\n","repo_name":"DrAnonymousNet/URL-Shortner","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":6221,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"18519913809","text":"inp = open(\"dayOne\\input.txt\", \"r\")\n\ntotal = 0\n# Holds all three maximum calories\nmaximum = [0, 0, 0]\n\nfor line in inp:\n # Verify that the line is not empty\n if line.strip() != \"\":\n total += int(line)\n continue\n \n # Appends the total because the line was empty\n maximum.append(total)\n # Removes the smallest value leaving the three largest\n maximum.remove(min(maximum))\n total = 0\n\n# Sums the maximum before printing\nprint(\"The maximum calories the top three elf have is: \" + str(sum(maximum)))","repo_name":"Tqkoyaki/AdventOfCode","sub_path":"dayOne/partTwo.py","file_name":"partTwo.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"21089678974","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as im\ndf = pd.read_csv('63z_dataSales.csv')\ndf = df.pivot(index='nama', columns='mobil')\n\nfig, p = plt.subplots()\nplt.imshow(df, cmap='BuPu_r')\nplt.colorbar()\n\ncol = list(map(lambda x: x[1], df.columns.tolist()))\nprint(col)\ni = list(map(lambda x: x, df.index.tolist()))\nprint(i)\n\nfor x in range(len(i)):\n for y in range(len(col)):\n p.text(y, x, df.iloc[x, y], color='y')\n\np.set_xticks(np.arange(len(col)))\np.set_xticklabels(col)\np.set_yticks(np.arange(len(i)))\np.set_yticklabels(i)\n\n# plt.xlim(-.5, 4.5)\n# plt.ylim(-.5, 4.5)\n\nplt.show()\n\n# ===================================\n# Heatmap: frequency, correlation, image\ndf = pd.DataFrame([\n {'sales':'Andi', 'HP A':100, 'HP B':120, 'HP C':65},\n {'sales':'Budi', 'HP A':10, 'HP B':20, 'HP C':5},\n {'sales':'Caca', 'HP A':80, 'HP B':70, 'HP C':60},\n])\ndf = df.set_index('sales')\n# df\n\nplt.imshow(df, cmap='BuPu')\nplt.colorbar()\nplt.xticks(np.arange(3), ['HP A', 'HP B', 'HP C'])\nplt.yticks(np.arange(3), ['Andi', 'Budi', 'Caca'])\n\nfor x in range(3):\n for y in range(3):\n plt.text(y-.1, x+.1, df.iloc[x, y], color='w', fontsize=18)\n\nplt.show()","repo_name":"LintangWisesa/Python_Fundamental_DataScience","sub_path":"6a Matplotlib/63.z1heatmap.py","file_name":"63.z1heatmap.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"41"} +{"seq_id":"16334428779","text":"def get_next(T):\n i = 1\n j = 0\n nxt=dict()\n nxt[1] = 0\n while i < len(T):\n if (j == 0 or T[i] == T[j-1]):\n i+=1\n j+=1\n nxt[i] = j\n else:\n j = nxt[j]\n return nxt\n\nif __name__ == \"__main__\":\n print(get_next(\"ababcd\"))","repo_name":"TakiJoe/Ombre","sub_path":"data_structure/string/kmp.py","file_name":"kmp.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"41497907355","text":"import hashlib\nimport time\nimport json\nfrom urllib.parse import urlparse\nimport requests\n\nclass Block:\n def __init__(self, index, timestamp, data, previous_hash, nonce=0):\n self.index = index\n self.timestamp = timestamp\n self.data = data\n self.previous_hash = previous_hash\n self.nonce = nonce\n self.hash = self.calculate_hash()\n\n def calculate_hash(self):\n sha = hashlib.sha256()\n sha.update(str(self.index).encode('utf-8') +\n str(self.timestamp).encode('utf-8') +\n str(self.data).encode('utf-8') +\n str(self.previous_hash).encode('utf-8') +\n str(self.nonce).encode('utf-8'))\n return sha.hexdigest()\n\n def mine_block(self, difficulty):\n while self.hash[:difficulty] != '0'*difficulty:\n self.nonce += 1\n self.hash = self.calculate_hash()\n print(\"Block mined: \", self.hash)\n\n\nclass Blockchain:\n def __init__(self):\n self.chain = [self.create_genesis_block()]\n self.difficulty = 2\n self.nodes = set()\n self.pending_transactions = []\n\n def create_genesis_block(self):\n return Block(0, time.time(), \"Genesis Block\", \"0\")\n\n def get_latest_block(self):\n return self.chain[-1]\n\n def add_block(self, new_block):\n new_block.previous_hash = self.get_latest_block().hash\n new_block.mine_block(self.difficulty)\n self.chain.append(new_block)\n\n def is_chain_valid(self):\n for i in range(1, len(self.chain)):\n current_block = self.chain[i]\n previous_block = self.chain[i-1]\n if current_block.hash != current_block.calculate_hash():\n return False\n if current_block.previous_hash != previous_block.hash:\n return False\n return True\n\n def register_node(self, node_url):\n parsed_url = urlparse(node_url)\n self.nodes.add(parsed_url.netloc)\n\n def verify_chain(self):\n other_chains = []\n for node in self.nodes:\n response = requests.get(f'http://{node}/chain')\n if response.status_code == 200:\n chain = response.json()['chain']\n other_chains.append(chain)\n longest_chain = self.chain\n for chain in other_chains:\n if len(chain) > len(longest_chain) and self.is_chain_valid(chain):\n longest_chain = chain\n self.chain = longest_chain\n\n def submit_transaction(self, transaction):\n self.pending_transactions.append(transaction)\n\n def mine_pending_transactions(self, miner_reward_address):\n if not self.pending_transactions:\n return False\n new_block = Block(len(self.chain), time.time(), self.pending_transactions, self.get_latest_block().hash)\n new_block.mine_block(self.difficulty)\n self.chain.append(new_block)\n self.pending_transactions = [\n {\"from\": \"network\", \"to\": miner_reward_address, \"amount\": 1.0},\n ]\n return True\n\n def get_balance(self, address):\n balance = 0\n for block in self.chain:\n for transaction in block.data:\n if transaction[\"from\"] == address:\n balance -= transaction[\"amount\"]\n elif transaction[\"to\"] == address:\n balance += transaction[\"amount\"]\n return balance\n\n def get_chain(self):\n chain_data = []\n for block in self.chain:\n chain_data.append(block.__dict__)\n return {\"length\": len(chain_data), \"chain\": chain_data}\n\n\n# Exemple d'utilisation avec deux noeuds\n\nblockchain_node1 = Blockchain()\nblockchain_node2 = Blockchain()\nblockchain_node1.register_node(\"http://127.0.0.1:5001\")\nblockchain_node2.register_node(\"http://127.0.0.1:5000\")\n\n# Ajout d'une transaction sur le noeud 1\nblockchain_node1.submit_transaction({\"from\": \"John\", \"to\": \"Alice\", \"amount\": 3.0})\nblockchain_node1.submit_transaction({\"from\": \"Alice\", \"to\": \"Bob\", \"amount\": 1.0})\nblockchain_node1.mine_pending_transactions(\"miner-address\")\n\n# Vérification de la chaîne sur le noeud 2\nprint(\"Chaîne du noeud 2 avant vérification:\")\nprint(blockchain_node2.get_chain())\nblockchain_node2.verify_chain()\nprint(\"Chaîne du noeud 2 après vérification:\")\nprint(blockchain_node2.get_chain())\n\n# Ajout d'une transaction sur le noeud 2\nblockchain_node2.submit_transaction({\"from\": \"Alice\", \"to\": \"John\", \"amount\": 2.0})\nblockchain_node2.mine_pending_transactions(\"miner-address\")\n\n# Vérification de la chaîne sur le noeud 1\nprint(\"Chaîne du noeud 1 avant vérification:\")\nprint(blockchain_node1.get_chain())\nblockchain_node1.verify_chain()\nprint(\"Chaîne du noeud 1 après vérification:\")\nprint(blockchain_node1.get_chain())\n\n# Affichage des soldes\nprint(\"Solde de John: \", blockchain_node1.get_balance(\"John\"))\nprint(\"Solde de Alice: \", blockchain_node1.get_balance(\"Alice\"))\nprint(\"Solde de Bob: \", blockchain_node1.get_balance(\"Bob\"))\n","repo_name":"Ancherson/simple-blockchain","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"6230186224","text":"import sys\n# insert at 1, 0 is the script path (or '' in REPL)\nsys.path.insert(1, '/home/manuel/projects/inverted_pendulum/third_party/rtPGM')\n\nfrom controller import rtPGM\nfrom controller_codegen import *\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.signal import cont2discrete\nimport random\nimport simulate\n\n# System parameters\nm_p = 0.2 # kg\nm_c = 0.5 # kg\nl = 0.3 # m -- distance to cg\nizz = 0.006 # kg * m^2\nb = 0.0\ng = 9.81 # m/s^2\n\n# den = (izz * (m_c + m_p)) + (m_c * m_p * l * l)\n\nden = ((izz + m_p * l * l) * (m_c + m_p)) - (m_p * m_p * l * l)\n\nAc = np.array([[0.0, 1.0, 0.0, 0.0],\n [0.0, 0.0, (m_p * m_p * g * l * l) / den, 0.0],\n [0.0, 0.0, 0.0, 1.0],\n [0.0, 0.0, (m_p * g * l * (m_c + m_p)) / den, 0.0]])\nBc = np.array([[0.0],\n [(izz + m_p * l * l) / den],\n [0.0],\n [(m_p * l) / den]])\n\nCc = np.array([[1.0, 0.0, 0.0, 0.0]])\nDc = np.array([[0.0]])\n\nt_s = 0.01\n\nA, B, C, D, _ = cont2discrete([Ac, Bc, Cc, Dc], t_s, method='zoh')\n\nprint(C)\nprint(D)\n\numin = -200.0\numax = 200.0\nnx = A.shape[0]\nnq = B.shape[1]\n\nhorizon_time = 1.0 # s\nN = int(horizon_time / t_s)\n\n# controller\nQ = np.array([[100.0, 0.0, 0.0, 0.0],\n [0.0, 1.0, 0.0, 0.0],\n [0.0, 0.0, 1000.0, 0.0],\n [0.0, 0.0, 0.0, 100.0]])\nR = 1000.0 * np.eye(nq)\n\nprint(A.shape)\nprint(B.shape)\nprint(C.shape)\nprint(D.shape)\nprint(Q.shape)\nprint(R.shape)\ncontroller = rtPGM(A, B, C, D, Q, R, umin, umax, N)\ncontroller.codegen(\"/home/manuel/projects/inverted_pendulum/mbed/library/inverted_pendulum.h\")\n\nsim_time = 20 # s\nn_sim = int(sim_time / t_s)\n\nq = np.zeros((N, 1))\nx = np.array([[0.], [0.], [0.01], [0.0]]) # initial condition\nr = np.array([[0.0]]) # terminal state\nx_sv = np.zeros((nx, 0)) # all states\nq_sv = np.zeros((nq, 0)) # all control inputs\nVN_sv = np.zeros((1, 0))\n\nprint(x[0,])\n\nfor k in range(n_sim):\n x_sv = np.hstack((x_sv, x))\n # update trajectory\n q = controller.update(x, r)\n q_sv = np.hstack((q_sv, q))\n # update system\n # x = A.dot(x) + B.dot(q)\n x[2,] += np.pi\n x = simulate.SimStep(x, -q)\n x[2,] -= np.pi\n # if k % int( 1 / t_s) == 0:\n # x[2] += random.randrange(-1.0, 1.0)\n\n# plot\ntime = np.linspace(0, (n_sim-1) * t_s, n_sim)\nplt.figure()\nplt.subplot(3, 1, 1)\nplt.plot(time, x_sv[0, :], 'b')\nplt.legend(['x'])\nplt.plot([0, (n_sim-1) * t_s], [r[0, 0], r[0, 0]], 'r--')\nplt.xlim([0, (n_sim-1) * t_s])\nplt.ylabel('x')\nplt.subplot(3, 1, 2)\nplt.plot(time, x_sv[2, :], 'b')\nplt.legend(['theta'])\nplt.xlim([0, (n_sim-1) * t_s])\nplt.ylabel('theta')\nplt.subplot(3, 1, 3)\nplt.plot(time, q_sv[0, :], 'b')\nplt.legend(['Fc'])\nplt.xlim([0, (n_sim-1) * t_s])\nplt.ylabel('Fc (N)')\nplt.show()","repo_name":"mahumada408/inverted_pendulum","sub_path":"scripts/mpc_inverted_pendulum.py","file_name":"mpc_inverted_pendulum.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"14195666358","text":"# Utilites for the model in this folder\n\nfrom keras import backend as ks\nfrom keras.models import Sequential\nfrom keras.layers import Reshape\nfrom keras.layers.core import Activation\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers.convolutional import UpSampling3D, UpSampling2D\nfrom keras.layers import Conv3D, Conv2D, AveragePooling2D, AveragePooling3D, Dense, Dropout, LeakyReLU\nfrom keras.layers import MaxPooling2D, MaxPooling3D, Conv2DTranspose, Input\nfrom keras.layers.core import Flatten\nfrom keras.callbacks import TensorBoard\nfrom keras.optimizers import SGD, Adam\nfrom plotter import LossAccPlotter\nfrom keras import utils\n\nimport pywavefront as pw\nimport numpy as np\nimport os.path\nimport time\nimport glob\nimport math\nimport os\n\nks._BACKEND = 'theano'\nks.set_image_dim_ordering(\"th\")\n\ndef update_progress(progress, step=0.001,string=\"\",loss=False):\n #ignore this pls, pure bullshit, but it looks good in the terminal.\n print(\"\\r\"+string+\" [{0}] {1}%\".format('#'*int(progress/10 if loss else progress/500), int(progress + 1 if loss else progress/50)), end=\"\")\n time.sleep(step)\n\n\ndef load_data(): \n if os.path.isfile('dataArray.npy'):\n print(\"Loading existing data...\")\n data = np.load(open('dataArray.npy', 'rb'))\n else:\n print(\"Loading data...\") \n data=[]\n for i in range(0,5000):\n directory = '/home/viktorv/Projects/MachineLearning/CiD/data/concept_processed/cube'+str(i)+'.obj00'\n data.append((pw.ObjParser(pw.Wavefront(directory), directory).vertices))\n update_progress(i)\n #endfor\n data = np.array(data)\n data.dump(open('dataArray.npy', 'wb'))\n #endif\n # print(data.shape)\n # data = data.reshape((data.shape[0], data.shape[1], data.shape[2], 1))\n # data = np.resize(data.shape, (5000, 9025, 3)).reshape((5000, 95, 95, 3))\n data = np.resize(data.shape, (5000, 9025, 3)).reshape((5000, 3, 95, 95)) \n \n print(data.shape)\n\n print(\"Loading complete!\")\n\n return data\n\n\ndef generator_model(_1d=False):\n model = Sequential()\n #TODO: Try 1D Input and Output, idk.\n depth = 32\n dropout_rate = 0.4\n\n model.add(Dense(128, input_shape=(128,)))\n model.add(Reshape((128,1,1), input_shape=(128,)))\n model.add(Activation('relu'))\n model.add(Dropout(dropout_rate)) \n\n model.add(Conv2DTranspose(depth*8,(4,4)))\n model.add(BatchNormalization())\n model.add(Activation('relu'))\n model.add(Dropout(dropout_rate)) \n\n model.add(Conv2DTranspose(depth*4,(4,4), strides=(2, 2)))\n model.add(BatchNormalization())\n model.add(Activation('relu'))\n model.add(Dropout(dropout_rate))\n \n model.add(Conv2DTranspose(depth*2,(4,4), strides=(2, 2)))\n model.add(BatchNormalization())\n model.add(Activation('relu'))\n model.add(Dropout(dropout_rate))\n\n model.add(Conv2DTranspose(depth,(5,5), strides=(2, 2)))\n model.add(BatchNormalization())\n model.add(Activation('relu'))\n model.add(Dropout(dropout_rate))\n\n model.add(Conv2DTranspose(int(depth/2), (5,5), strides=(2, 2))) \n model.add(BatchNormalization())\n model.add(Activation('relu'))\n model.add(Dropout(dropout_rate))\n\n model.add(Conv2D(3,(3,3)))\n model.add(Activation('tanh'))\n\n model.summary()\n\n return model\n\n\ndef discriminator_model(_1d=False):\n model = Sequential()\n\n depth = 32\n dropout_rate = 0.4\n\n model.add(Conv2D(depth, (3,3), input_shape=(3, 95, 95,)))\n model.add(BatchNormalization()) \n model.add(LeakyReLU(alpha=0.2))\n model.add(Dropout(dropout_rate))\n\n model.add(Conv2D(depth*2, (3,3)))\n model.add(BatchNormalization()) \n model.add(LeakyReLU(alpha=0.2))\n model.add(Dropout(dropout_rate))\n\n model.add(Conv2D(depth*4, (3,3)))\n model.add(BatchNormalization())\n model.add(LeakyReLU(alpha=0.2))\n model.add(Dropout(dropout_rate))\n \n model.add(Conv2D(depth*8, (3,3)))\n model.add(BatchNormalization())\n model.add(LeakyReLU(alpha=0.2)) \n model.add(Dropout(dropout_rate))\n\n model.add(Flatten())\n model.add(Dense(1))\n model.add(Activation('sigmoid'))\n\n model.summary()\n return model\n\n\ndef generator_containing_discriminator(generator, discriminator):\n\n model = Sequential()\n model.add(generator) \n discriminator.trainable = False\n model.add(discriminator)\n \n return model\n\ndef train(epochs, BATCH_SIZE, load=False):\n\n plotter = LossAccPlotter(title=\"DCGAN Adversary plot\",\n save_to_filepath=\"./plots/my_plot.png\",\n show_averages=True,\n show_loss_plot=True,\n x_label=\"Index\")\n X_train = load_data()\n\n discriminator = discriminator_model()\n generator = generator_model()\n\n #tbCallBack = TensorBoard(log_dir='graph', histogram_freq=5, write_graph=True, write_images=True)\n #tbCallBack.set_model(generator)\n\n if load:\n generator.load_weights('goodgenerator.h5')\n discriminator.load_weights('gooddiscriminator.h5')\n \n discriminator_on_generator = generator_containing_discriminator(generator, discriminator)\n\n d_optim = SGD(lr=0.0002, momentum=0.7)\n g_optim = Adam(lr=0.0002, beta_1=0.5)\n\n generator.compile(loss='binary_crossentropy', optimizer=\"adam\")\n discriminator_on_generator.compile(loss='binary_crossentropy', optimizer=g_optim)\n discriminator.trainable = True\n discriminator.compile(loss='binary_crossentropy', optimizer=d_optim)\n\n noise = np.zeros((BATCH_SIZE, 128))\n\n for epoch in range(epochs):\n\n for index in range(int(X_train.shape[0]/BATCH_SIZE)):\n\n for i in range(BATCH_SIZE):\n noise[i, :] = np.random.normal(-1, 1, 128)\n\n batch = X_train[index*BATCH_SIZE:(index+1)*BATCH_SIZE]\n\n generated = generator.predict(noise, verbose=0)\n\n X = np.concatenate((batch, generated))\n y = [1] * BATCH_SIZE + [0] * BATCH_SIZE\n d_loss = discriminator.train_on_batch(X, y)\n\n for i in range(BATCH_SIZE):\n noise[i, :] = np.random.normal(-1, 1, 128)\n\n discriminator.trainable = False\n g_loss = discriminator_on_generator.train_on_batch(noise, [1] * BATCH_SIZE)\n discriminator.trainable = True\n\n update_progress(index, loss=True, string=\"Epoch: %d Batch: %d Dloss: %f Gloss: %f\" % (epoch, index, d_loss, g_loss))\n plotter.add_values(index + BATCH_SIZE*epoch, loss_train=d_loss, loss_val=g_loss)\n\n if epoch % 10 == 9:\n generator.save_weights('goodgenerator.h5', True)\n discriminator.save_weights('gooddiscriminator.h5', True)\n print()\n\n\ndef obj_wrapper(coords, name=\"object\"):\n lines = \"\"\n for i in range(0, len(coords)):\n lines += \"v \" + str(coords[i,0]) + \" \" + str(coords[i,1]) + \" \" + str(coords[i,2]) + \" #\" + str(i + 1) + \"\\n\"\n \n return lines\n\n\ndef generate(BATCH_SIZE,name=\"generated\"):\n generator = generator_model()\n generator.compile(loss='binary_crossentropy', optimizer=\"adam\")\n generator.load_weights('goodgenerator.h5')\n\n noise = np.zeros((BATCH_SIZE, 128))\n a = np.random.normal(-1, 1, 128)\n b = np.random.normal(-1, 1, 128)\n grad = (b - a) / BATCH_SIZE\n\n for i in range(BATCH_SIZE):\n noise[i, :] = np.random.normal(-1, 1, 128)\n\n generated = generator.predict(noise)\n\n for i, pointcloud in enumerate(generated):\n pointcloud = pointcloud.reshape(9025, 3)\n file = open('./generated_data/%s%s.obj'%(name,i), \"w\")\n file.write(obj_wrapper(pointcloud))\n file.close()\n \n \n","repo_name":"jtpils/3DMNN","sub_path":"main/models/dcgan-old/dcgan.py","file_name":"dcgan.py","file_ext":"py","file_size_in_byte":7651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"37164882152","text":"############################################################## \n# Date: 20/05/16\n# Name: plot_atm_dms.py\n# Author: Alek Petty\n# Description: Script to plot ATM overlaid on a DMS image\n# Input requirements: DMS image and ATM data for specific case studies\n\nimport matplotlib\nmatplotlib.use(\"AGG\")\nimport numpy as np\nfrom pylab import *\nimport numpy.ma as ma\nfrom glob import glob\nfrom osgeo import osr, gdal\n#may need this if reading in ATM data after 2013 (hdf5 format)\n#import h5py\n\nimfile='P1'\nrawdatapath = '../../../DATA/'\nimagePath = rawdatapath+'IMAGERY/'+imfile+'/'\nfigpath='./Figures/'\n\n\nimage_path = glob(imagePath+imfile+'.tif')\n\ngeo = gdal.Open(image_path[0]) \nband1 = geo.GetRasterBand(1)\nband2 = geo.GetRasterBand(2)\nband3 = geo.GetRasterBand(3)\nred = band1.ReadAsArray()\ngreen = band2.ReadAsArray()\nblue = band3.ReadAsArray()\n\nQBIRD = (0.299*red + 0.587*green + 0.114*blue)\nQBIRD = ma.masked_where(QBIRD<1, QBIRD)\n\n\nfig = figure(figsize=(5, 5))\nax=gca()\nim2 = imshow(QBIRD, vmin = 0, vmax = 255, cmap = cm.gist_gray, rasterized=True)\nsubplots_adjust(bottom=0.09, left=0.11, top = 0.94, right=0.99, hspace=0.22)\nsavefig(figpath+imfile+'.png', dpi=300)\nclose(fig)\n\n\n","repo_name":"polar-computing/SeaIce","sub_path":"scripts/plot_QB.py","file_name":"plot_QB.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"41"} +{"seq_id":"2913604422","text":"class Solution(object):\n\n def reverse(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n\n nums = list(str(x))\n for num in range(len(nums) / 2):\n end = len(nums) - 1 - num\n tmp = nums[num]\n nums[num] = nums[end]\n nums[end] = tmp\n\n result = 0\n for num in nums:\n if num == \"-\":\n result *= -1\n break\n result = result * 10 + int(num)\n if result < -2 ** 31 or result > 2 ** 31 - 1:\n return 0\n return result\n\n","repo_name":"cherryMonth/python_algorithm","sub_path":"letcode/reverse-integer.py","file_name":"reverse-integer.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"7662780689","text":"import re\n\nfrom object_challenge import pymongo\n\n__all__ = ('BucketService',)\n\n\nclass BucketService:\n\n def __init__(self, user):\n \"\"\"\n constructor\n :param user: user\n \"\"\"\n assert user, \"`user` is required\"\n self.user = user\n\n def is_allowed(self, **data):\n \"\"\"\n indicates whether user can create specified bucket or not\n :param data: bucket data\n :return: bool\n \"\"\"\n assert data.get('bucket'), \"`bucket` is required\"\n\n # initial values\n is_user_disallowed = False\n is_assigned_to_user = False\n is_assigned_to_another_user = False\n\n # buckets at least should have 3 characters\n # we get 2 first characters for database lookup\n bucket = data['bucket'].lower()\n bucket_prefix = bucket[:2]\n\n # Note also that regex's anchored at the start (ie: starting with ^) are able to use indexes in the db,\n # and will run much faster in that case.\n r_bucket = re.compile(f'^{bucket_prefix}', re.IGNORECASE)\n\n # user can create new bucket under 3 circumstances:\n # 1. prefix doesn't exists in the db\n # 2. the prefix was assigned to the user\n # 3. the prefix wasn't forbidden for this user\n user_prefixes = tuple(pymongo.db.prefixes.aggregate([\n {'$match': {'prefix': {'$regex': r_bucket}}},\n {'$lookup': {\n 'from': 'user_prefixes',\n 'localField': 'prefix_id',\n 'foreignField': 'prefix_id',\n 'as': 'user_prefixes'\n }},\n {'$unwind': '$user_prefixes'},\n {'$match': {'$or': [\n {'user_prefixes.user_id': {'$ne': self.user.user_id}, 'user_prefixes.is_allowed': True},\n {'user_prefixes.user_id': self.user.user_id}\n ]}}\n ]))\n\n for item in user_prefixes:\n if bucket.startswith(item['prefix']):\n if item['user_prefixes']['user_id'] == self.user.user_id:\n if not item['user_prefixes']['is_allowed']:\n is_user_disallowed = True\n else:\n is_assigned_to_user = True\n else:\n is_assigned_to_another_user = True\n\n return not is_user_disallowed and (not is_assigned_to_another_user or is_assigned_to_user)\n","repo_name":"mohammadmasoumi/object-challenge","sub_path":"object_challenge/bucket/services/bucket.py","file_name":"bucket.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"41"} +{"seq_id":"74604289722","text":"\"\"\"\nThis module extracts the index from the xml and writes it into the database.\n\nAuthor: Susanne Fertmann <s9sufert@stud.uni-saarland.de>\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\n\nfrom bs4 import BeautifulSoup, Tag, NavigableString\nimport codecs, string, re, sys\nfrom regesten_webapp import models\nfrom regesten_webapp.models import Location, Family, Person, Region\nfrom regesten_webapp.models import PersonGroup, Landmark, Concept, IndexEntry\nfrom regesten_webapp.models import Regest, RegestDate, Quote, ContentType\n\n\ndef get_item_ID():\n '''Get consecutive id for an index item'''\n global countIndex\n item_id = countIndex\n countIndex += 1\n return item_id\n\ndef ment_to_db(xmlNode, concept):\n '''\n TO BE IMPLEMENTED:\n Extract related regests and writes them into the database.\n '''\n pass\n\n\ndef add_all(obj, li):\n '''Add a list of elements to an object.'''\n for elem in li:\n obj.add(elem)\n\n\ndef if_exists(node):\n '''Check if a node exists.'''\n if node:\n return node.get_text().strip(') (')\n else:\n return ''\n\n\ndef create_quote(xmlNode,objId):\n '''Build a quote from XML. Write it into the database.'''\n q = Quote()\n q.content_type = ContentType.objects.get(app_label='regesten_webapp', model='concept')\n q.content = xmlNode.get_text()\n q.object_id = objId\n q.save()\n return q\n\n\ndef create_person(xmlNode):\n ''' Build a person from XML. Write it into the database.'''\n global idConc\n \n p = Person()\n pers_name = xmlNode.persname\n p.name = pers_name.get_text()\n p.additional_names = if_exists(pers_name.addNames)\n p.forename = if_exists(pers_name.forename)\n p.surname = if_exists(pers_name.surname)\n p.maidenname = if_exists(pers_name.maidenname)\n p.rolename = if_exists(pers_name.rolename)\n p.genname = if_exists(pers_name.genname)\n p.description = if_exists(xmlNode.description)\n p.id = idConc\n idConc += 1\n p.save()\n return p\n\n \ndef create_concept(xmlNode):\n ''' Build a concept. '''\n name = xmlNode.find('name')\n global idConc\n \n c = Concept()\n c.name = name.get_text()\n c.description = if_exists(xmlNode.description)\n c.id = idConc\n idConc += 1\n c.save()\n\n quoteList = []\n qList = []\n if xmlNode.description:\n quoteList = xmlNode.description.findAll('quote')\n if not isinstance(name, NavigableString):\n quoteList += name.findAll('quote')\n for quote in quoteList:\n q = create_quote(quote, c.id)\n qList.append(q)\n add_all(c.quotes, qList)\n return c\n\n\ndef relconc_to_db(relConc, createElement=create_concept):\n '''Extract related-concepts and write them into the database.'''\n clist = []\n if relConc:\n for conc in relConc:\n if isinstance(conc, NavigableString):\n continue\n if conc.name == 'concept' or conc.name == 'person':\n c = createElement(conc)\n c.save()\n ment_to_db(conc, c)\n if hasattr(conc, 'related-concepts'):\n add_all(c.related_concepts, relconc_to_db(conc.find\\\n ('related-concepts')))\n clist.append(c)\n return clist\n\n\ndef loc_to_db(itemsoup,ref_dict):\n '''Extract a location from XML and write it into the database.'''\n header = itemsoup.find('location-header')\n placeName = header.placename\n attrs = placeName.settlement.attrs\n \n l = Location()\n l.additional_names = if_exists(placeName.addNames)\n l.name = itemsoup['value']\n \n # Abandoned villages\n if 'type' in attrs:\n l.location_type = placeName.settlement['type']\n vill = placeName.settlement['abandoned-village']\n if vill == 'true':\n l.abandoned_village = True\n else:\n l.abandoned_village = False \n if 'av-ref' in attrs:\n l.av_ref = placeName.settlement['av-ref'] \n \n # Reference point + district\n ref_point = placeName.find('reference_point')\n if ref_point:\n ref_point = ref_point.get_text().strip(' ,;.')\n if ref_point:\n l.reference_point = ref_point\n else:\n l.reference_point = ''\n if placeName.district:\n l.district = placeName.district.get_text().strip(' ,;.')\n \n # Region \n if placeName.region:\n regs = Region.objects.filter(name=placeName.region.get_text()\\\n .strip(' ,;.'))\n if regs:\n region = regs[0]\n else:\n region = Region.objects.create(name=placeName.region.get_text()\\\n .strip(' ,;.'), region_type=placeName.region['type'])\n l.region = region\n\n # Country\n if placeName.country:\n if placeName.country.get_text() == \"F\":\n l.country = \"Frankreich\"\n if placeName.country.get_text() == \"B\":\n l.country = \"Belgien\"\n if placeName.country.get_text() == \"CH\":\n l.country = \"Schweiz\"\n if placeName.country.get_text() == \"Lux\":\n l.country = \"Luxemburg\"\n if placeName.country.get_text() == \"L\":\n l.country = \"Luxemburg\"\n if placeName.country.get_text() == \"Spanien\":\n l.country = \"Spanien\"\n if placeName.country.get_text() == \"It\":\n l.country = \"Italien\"\n elif l.region and l.region.region_type == 'Bundesland':\n l.country = \"Deutschland\"\n\n l.id = get_item_ID()\n l.xml_repr = itemsoup\n l.save()\n \n # Mentionings + related index entries\n ment_to_db(header, l)\n ref_dict[l.id] = header.find('index-refs')\n \n # Related concepts\n if itemsoup.find('concept-body'):\n add_all(l.related_concepts, relconc_to_db(itemsoup.find\\\n ('concept-body').find('related-concepts')))\n \n print(l)\n return l\n \n\n\ndef land_to_db(itemsoup,ref_dict):\n '''Extract a landmark from XML and write it into the database.'''\n header = itemsoup.find('landmark-header')\n \n land = Landmark()\n land.name = itemsoup['value']\n if header.geogname:\n land.add_Names = header.geogname\n land.landmark_type = str(header.geogname['type'])\n \n land.id = get_item_ID()\n land.xml_repr = itemsoup\n land.save()\n \n # Mentionings + related index entries\n ment_to_db(itemsoup.find('landmark-header'), land)\n ref_dict[land.id] = header.find('index-refs')\n \n # Related concepts\n if hasattr(itemsoup, 'concept-body'):\n add_all(land.related_concepts, relconc_to_db(itemsoup.find\\\n ('concept-body').find('related-concepts')))\n \n print(land)\n return land\n \n \ndef pers_to_db(itemsoup,ref_dict):\n '''Extract a person from XML and write it into the database.'''\n p = Person()\n if hasattr(itemsoup, 'person-header'):\n header = itemsoup.find('person-header')\n pers_name = header.person.persname\n \n p.name=itemsoup['value']\n \n p.additional_names = if_exists(pers_name.addNames)\n p.forename = if_exists(pers_name.forename)\n p.surname = if_exists(pers_name.surname)\n p.maidenname = if_exists(pers_name.maidenname)\n p.rolename = if_exists(pers_name.rolename)\n p.genname = if_exists(pers_name.genname)\n p.description = if_exists(header.person.description)\n \n p.id = get_item_ID()\n p.xml_repr = itemsoup\n p.save()\n \n # Mentionings + related index entries\n ment_to_db(itemsoup.find('person-header'), p)\n ref_dict[p.id] = header.find('index-refs')\n \n # Related concepts\n if hasattr(itemsoup, 'concept-body'):\n add_all(p.related_concepts, relconc_to_db(itemsoup.find\\\n ('concept-body').find('related-concepts')))\n \n print (p)\n return p\n else:\n exit()\n\n\n\ndef persgr_to_db(itemsoup,ref_dict):\n '''\n Extract a persongroup from XML and write it into the database.\n '''\n header = itemsoup.find('persongroup-header')\n \n pg = PersonGroup()\n pg.name = header.find('group-name').get_text()\n pg.id = get_item_ID()\n pg.xml_repr = itemsoup\n pg.save()\n \n # Mentionings + related index entries\n ment_to_db(itemsoup.find('persongroup-header'), pg)\n ref_dict[pg.id] = header.find('index-refs')\n \n # Related concepts\n if itemsoup.find('listing-body'):\n add_all(pg.members, relconc_to_db(itemsoup.find('listing-body').members\\\n , createElement=create_person))\n \n print(pg)\n return pg\n\n\n\ndef fam_to_db(itemsoup, ref_dict):\n '''Extract a family from XML and write it into the database.'''\n header = itemsoup.find('family-header')\n \n f = Family() \n f.name = itemsoup['value'].strip(' ,;.')\n f.addnames = if_exists(header.addnames)\n f.id = get_item_ID()\n f.xml_repr = itemsoup\n f.save()\n \n # mentioned_in + related index entries \n ment_to_db(itemsoup.find('family_header'), f)\n ref_dict[f.id] = header.find('index-refs')\n \n # related-concepts\n if itemsoup.find('listing-body'):\n add_all(f.members, relconc_to_db(itemsoup.find('listing-body').members\\\n , createElement=create_person))\n \n print (f)\n return f\n\n \ndef items_to_db(itemList):\n '''Add a list of XML index items to the database.'''\n ref_dict = {}\n for itemsoup in itemList:\n type = itemsoup['type']\n\n if type == 'location':\n entry = loc_to_db(itemsoup,ref_dict)\n \n elif type == 'family':\n entry = fam_to_db(itemsoup,ref_dict)\n \n elif type == 'person':\n entry = pers_to_db(itemsoup,ref_dict)\n \n elif type == 'persongroup':\n entry = persgr_to_db(itemsoup,ref_dict)\n \n elif type == 'landmark':\n entry = land_to_db(itemsoup,ref_dict)\n \n else:\n entry = ''\n print ('unknown type!!')\n break\n return ref_dict\n\n\ndef isolate_id(id):\n '''Return the number in an id.'''\n return int(id.split('_')[1])\n\n\ndef solve_refs(ref_dict):\n '''\n Extract references from the dictionary and add them to the database.\n '''\n for item_id, refNode in ref_dict.items():\n if refNode:\n refList = [node['itemid'] for node in refNode.findAll('index-ref')]\n objList = [IndexEntry.objects.get(id=isolate_id(ref)) for ref in refList]\n obj = IndexEntry.objects.get(id=item_id)\n add_all(obj.related_entries, objList)\n\n\n\ndef index_to_db():\n '''\n Extract index items from the XML file and write them into the\n database sbr-regesten.db.\n '''\n print('Writing index into db..')\n \n with codecs.open ('sbr-regesten.xml', 'r', 'utf-8') as file:\n soup = BeautifulSoup(file)\n itemList = soup.find('index').findAll('item')\n \n global countIndex\n countIndex = 0\n global idConc\n idConc = len(itemList) + 1\n \n ref_dict = items_to_db(itemList)\n solve_refs(ref_dict)\n","repo_name":"itsjeyd/sbr-regesten","sub_path":"extraction/index_utils/index_to_db.py","file_name":"index_to_db.py","file_ext":"py","file_size_in_byte":11031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"21073579222","text":"import tensorflow as tf\ntf.logging.set_verbosity(tf.logging.ERROR)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ncelsius_q = np.array([-40,10,0,8,15,22,38], dtype=float)\nfahrenheit_a = np.array([-40, 14, 32, 46, 59, 72, 100], dtype=float)\n\nfor i,c in enumerate(celsius_q):\n print(\"{} degrees Celsius = {} degree Fahrenhet\".format(c, fahrenheit_a[i]))\n\nla = tf.keras.layers.Dense(units=1, input_shape=[1])\nmodel = tf.keras.Sequential([la])\nmodel.compile(loss='mean_squared_error', optimizer=tf.keras.optimizers.Adam(0.1))\nhistory = model.fit(celsius_q, fahrenheit_a, epochs=1000, verbose=False)\nprint(\"Finisehd training the model\")\n\nplt.xlabel('Epoch Number')\nplt.ylabel('Loss Magnitude')\nplt.plot(history.history['loss'])\n\nprint(model.predict([100.0]))\nprint(\"These are the layer variables: {}\".format(la.get_weights()))\nprint('It works')\n","repo_name":"robinkumarsharma03/tensorflow","sub_path":"celsius_to_Fahrenheit.py","file_name":"celsius_to_Fahrenheit.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"38784356397","text":"def encrypt_vigenere(plaintext: str, keyword: str) -> str:\n res = \"\"\n key = keyword.upper()\n for i in range(len(plaintext)):\n if plaintext[i].isalpha():\n if (\n ord(plaintext[i]) + ord(key[i % len(key)]) - ord(\"A\") > ord(\"z\")\n and plaintext[i].islower()\n or ord(plaintext[i]) + ord(key[i % len(key)]) - ord(\"A\") > ord(\"Z\")\n and plaintext[i].isupper()\n ):\n res += chr(ord(plaintext[i]) + ord(key[i % len(key)]) - 26 - ord(\"A\"))\n else:\n res += chr(ord(plaintext[i]) + ord(key[i % len(key)]) - ord(\"A\"))\n else:\n res += plaintext[i]\n return res\n\n\ndef decrypt_vigenere(ciphertext: str, keyword: str) -> str:\n res = \"\"\n a = ciphertext\n key = keyword.upper()\n for i in range(len(a)):\n if a[i].isalpha():\n if (\n ord(a[i]) - ord(key[i % len(key)]) < 32\n and a[i].islower()\n or ord(a[i]) - ord(key[i % len(key)]) < 0\n and a[i].isupper()\n ):\n res += chr(ord(a[i]) - ord(key[i % len(key)]) + ord(\"A\") + 26)\n else:\n res += chr(ord(a[i]) - ord(key[i % len(key)]) + ord(\"A\"))\n else:\n res += a[i]\n return res\n","repo_name":"LudwigBitHoven/CS102","sub_path":"homework01/vigenere.py","file_name":"vigenere.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"35920415522","text":"# Author: Nic Wolfe <nic@wolfeden.ca>\r\n# URL: http://code.google.com/p/sickbeard/\r\n#\r\n# This file is part of Sick Beard.\r\n#\r\n# Sick Beard is free software: you can redistribute it and/or modify\r\n# it under the terms of the GNU General Public License as published by\r\n# the Free Software Foundation, either version 3 of the License, or\r\n# (at your option) any later version.\r\n#\r\n# Sick Beard is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# GNU General Public License for more details.\r\n#\r\n# You should have received a copy of the GNU General Public License\r\n# along with Sick Beard. If not, see <http://www.gnu.org/licenses/>.\r\n\r\nimport sickbeard\r\n\r\nfrom sickbeard.common import countryList\r\nfrom sickbeard.helpers import sanitizeSceneName\r\nfrom sickbeard.scene_exceptions import get_scene_exceptions\r\nfrom sickbeard import logger\r\nfrom sickbeard import db\r\n\r\nimport re\r\nimport datetime\r\n\r\nfrom name_parser.parser import NameParser, InvalidNameException\r\n\r\nresultFilters = [\"sub(bed|ed|pack|s)\", \"(dk|fin|heb|kor|nl|nor|nordic|pl|swe)sub(bed|ed|s)?\",\r\n \"(dir|sample|sub|nfo|proof)fix(es)?\", \"sample\", \"(dvd)?extras\",\r\n \"dub(bed)?\"]\r\n\r\n\r\ndef filterBadReleases(name):\r\n \"\"\"\r\n Filters out non-english and just all-around stupid releases by comparing them\r\n to the resultFilters contents.\r\n\r\n name: the release name to check\r\n\r\n Returns: True if the release name is OK, False if it's bad.\r\n \"\"\"\r\n\r\n try:\r\n fp = NameParser()\r\n parse_result = fp.parse(name)\r\n except InvalidNameException:\r\n logger.log(u\"Unable to parse the filename \" + name + \" into a valid episode\", logger.WARNING)\r\n return False\r\n\r\n # use the extra info and the scene group to filter against\r\n check_string = ''\r\n if parse_result.extra_info:\r\n check_string = parse_result.extra_info\r\n if parse_result.release_group:\r\n if check_string:\r\n check_string = check_string + '-' + parse_result.release_group\r\n else:\r\n check_string = parse_result.release_group\r\n\r\n # if there's no info after the season info then assume it's fine\r\n if not check_string:\r\n return True\r\n\r\n # if any of the bad strings are in the name then say no\r\n for ignore_word in resultFilters + sickbeard.IGNORE_WORDS.split(','):\r\n ignore_word = ignore_word.strip()\r\n if ignore_word:\r\n if re.search('(^|[\\W_])' + ignore_word + '($|[\\W_])', check_string, re.I):\r\n logger.log(u\"Invalid scene release: \" + name + \" contains \" + ignore_word + \", ignoring it\", logger.DEBUG)\r\n return False\r\n\r\n return True\r\n\r\n\r\ndef sceneToNormalShowNames(name):\r\n \"\"\"\r\n Takes a show name from a scene dirname and converts it to a more \"human-readable\" format.\r\n\r\n name: The show name to convert\r\n\r\n Returns: a list of all the possible \"normal\" names\r\n \"\"\"\r\n\r\n if not name:\r\n return []\r\n\r\n name_list = [name]\r\n\r\n # use both and and &\r\n new_name = re.sub('(?i)([\\. ])and([\\. ])', '\\\\1&\\\\2', name, re.I)\r\n if new_name not in name_list:\r\n name_list.append(new_name)\r\n\r\n results = []\r\n\r\n for cur_name in name_list:\r\n # add brackets around the year\r\n results.append(re.sub('(\\D)(\\d{4})$', '\\\\1(\\\\2)', cur_name))\r\n\r\n # add brackets around the country\r\n country_match_str = '|'.join(countryList.values())\r\n results.append(re.sub('(?i)([. _-])(' + country_match_str + ')$', '\\\\1(\\\\2)', cur_name))\r\n\r\n results += name_list\r\n\r\n return list(set(results))\r\n\r\n\r\ndef makeSceneShowSearchStrings(show):\r\n\r\n showNames = allPossibleShowNames(show)\r\n\r\n # scenify the names\r\n return map(sanitizeSceneName, showNames)\r\n\r\n\r\ndef makeSceneSeasonSearchString(show, segment, extraSearchType=None):\r\n\r\n myDB = db.DBConnection()\r\n\r\n if show.air_by_date:\r\n numseasons = 0\r\n\r\n # the search string for air by date shows is just\r\n seasonStrings = [segment]\r\n\r\n else:\r\n numseasonsSQlResult = myDB.select(\"SELECT COUNT(DISTINCT season) as numseasons FROM tv_episodes WHERE showid = ? and season != 0\", [show.tvdbid])\r\n numseasons = int(numseasonsSQlResult[0][0])\r\n\r\n seasonStrings = [\"S%02d\" % segment]\r\n\r\n showNames = set(makeSceneShowSearchStrings(show))\r\n\r\n toReturn = []\r\n\r\n # search each show name\r\n for curShow in showNames:\r\n # most providers all work the same way\r\n if not extraSearchType:\r\n # if there's only one season then we can just use the show name straight up\r\n if numseasons == 1:\r\n toReturn.append(curShow)\r\n # for providers that don't allow multiple searches in one request we only search for Sxx style stuff\r\n else:\r\n for cur_season in seasonStrings:\r\n toReturn.append(curShow + \".\" + cur_season)\r\n\r\n return toReturn\r\n\r\n\r\ndef makeSceneSearchString(episode):\r\n\r\n myDB = db.DBConnection()\r\n numseasonsSQlResult = myDB.select(\"SELECT COUNT(DISTINCT season) as numseasons FROM tv_episodes WHERE showid = ? and season != 0\", [episode.show.tvdbid])\r\n numseasons = int(numseasonsSQlResult[0][0])\r\n\r\n # see if we should use dates instead of episodes\r\n if episode.show.air_by_date and episode.airdate != datetime.date.fromordinal(1):\r\n epStrings = [str(episode.airdate)]\r\n else:\r\n epStrings = [\"S%02iE%02i\" % (int(episode.season), int(episode.episode)),\r\n \"%ix%02i\" % (int(episode.season), int(episode.episode))]\r\n\r\n # for single-season shows just search for the show name\r\n if numseasons == 1:\r\n epStrings = ['']\r\n\r\n showNames = set(makeSceneShowSearchStrings(episode.show))\r\n\r\n toReturn = []\r\n\r\n for curShow in showNames:\r\n for curEpString in epStrings:\r\n if curEpString != '':\r\n toReturn.append(curShow + '.' + curEpString)\r\n else:\r\n toReturn.append(curShow)\r\n\r\n return toReturn\r\n\r\n\r\ndef isGoodResult(name, show, log=True):\r\n \"\"\"\r\n Use an automatically-created regex to make sure the result actually is the show it claims to be\r\n \"\"\"\r\n\r\n all_show_names = allPossibleShowNames(show)\r\n showNames = map(sanitizeSceneName, all_show_names) + all_show_names\r\n\r\n for curName in set(showNames):\r\n escaped_name = re.sub('\\\\\\\\[\\\\s.-]', '\\W+', re.escape(curName))\r\n if show.startyear:\r\n escaped_name += \"(?:\\W+\" + str(show.startyear) + \")?\"\r\n curRegex = '^' + escaped_name + '\\W+(?:(?:S\\d[\\dE._ -])|(?:\\d\\d?x)|(?:\\d{4}\\W\\d\\d\\W\\d\\d)|(?:(?:part|pt)[\\._ -]?(\\d|[ivx]))|Season\\W+\\d+\\W+|E\\d+\\W+)'\r\n if log:\r\n logger.log(u\"Checking if show \" + name + \" matches \" + curRegex, logger.DEBUG)\r\n\r\n match = re.search(curRegex, name, re.I)\r\n\r\n if match:\r\n logger.log(u\"Matched \" + curRegex + \" to \" + name, logger.DEBUG)\r\n return True\r\n\r\n if log:\r\n logger.log(u\"Provider gave result \" + name + \" but that doesn't seem like a valid result for \" + show.name + \" so I'm ignoring it\")\r\n return False\r\n\r\n\r\ndef uniqify(seq, idfun=None):\r\n # http://www.peterbe.com/plog/uniqifiers-benchmark\r\n if idfun is None:\r\n def idfun(x):\r\n return x\r\n seen = {}\r\n result = []\r\n for item in seq:\r\n marker = idfun(item)\r\n if marker in seen:\r\n continue\r\n seen[marker] = 1\r\n result.append(item)\r\n\r\n return result\r\n\r\n\r\ndef allPossibleShowNames(show):\r\n \"\"\"\r\n Figures out every possible variation of the name for a particular show. Includes TVDB name, TVRage name,\r\n country codes on the end, eg. \"Show Name (AU)\", and any scene exception names.\r\n\r\n show: a TVShow object that we should get the names of\r\n\r\n Returns: a list of all the possible show names\r\n \"\"\"\r\n\r\n showNames = [show.name]\r\n showNames += [name for name in get_scene_exceptions(show.tvdbid)]\r\n\r\n # if we have a tvrage name then use it\r\n if show.tvrname != \"\" and show.tvrname is not None:\r\n showNames.append(show.tvrname)\r\n\r\n newShowNames = []\r\n\r\n country_list = countryList\r\n country_list.update(dict(zip(countryList.values(), countryList.keys())))\r\n\r\n # if we have \"Show Name Australia\" or \"Show Name (Australia)\" this will add \"Show Name (AU)\" for\r\n # any countries defined in common.countryList (and vice versa)\r\n for curName in set(showNames):\r\n if not curName:\r\n continue\r\n for curCountry in country_list:\r\n if curName.endswith(' ' + curCountry):\r\n newShowNames.append(curName.replace(' ' + curCountry, ' (' + country_list[curCountry] + ')'))\r\n elif curName.endswith(' (' + curCountry + ')'):\r\n newShowNames.append(curName.replace(' (' + curCountry + ')', ' (' + country_list[curCountry] + ')'))\r\n\r\n showNames += newShowNames\r\n # at this point we could have duplicates due to case-ing, prune dupes\r\n return uniqify(showNames, lambda x: x.lower())\r\n","repo_name":"midgetspy/Sick-Beard","sub_path":"sickbeard/show_name_helpers.py","file_name":"show_name_helpers.py","file_ext":"py","file_size_in_byte":9146,"program_lang":"python","lang":"en","doc_type":"code","stars":2905,"dataset":"github-code","pt":"41"} +{"seq_id":"40826424171","text":"import discord\r\nfrom discord.ext import commands\r\nimport requests\r\nfrom bot import logger, private_message\r\n\r\nclass Genshin(commands.Cog):\r\n def __init__(self, bot):\r\n self.bot = bot\r\n logger.info(\"Genshin impact Cog loaded\")\r\n self.colour_dict = {5: discord.Colour.gold(), 4: discord.Colour.purple(), 3: discord.Colour.blue(), 2: discord.Colour.green(), 1: discord.Colour.light_gray()}\r\n\r\n @commands.group(invoke_without_command=True, description=\"Genshin impact group commands.\")\r\n @commands.check(private_message)\r\n async def genshin(self, ctx):\r\n pass\r\n\r\n @genshin.group(name=\"character\", description=\"Sending genshin impact character data\")\r\n async def character(self, ctx, character: str):\r\n response = requests.get(f\"https://api.genshin.dev/characters/{character.lower()}\")\r\n if response.status_code == 404:\r\n raise commands.BadArgument(message=f\"no character named {character}.\")\r\n json = response.json()\r\n embed = discord.Embed(title=f\"{json['name']} information\", description=json[\"description\"], colour=self.colour_dict[json[\"rarity\"]])\r\n embed.add_field(name=\"Vision\", value=json[\"vision\"], inline=True)\r\n embed.add_field(name=\"Nation\", value=json[\"nation\"], inline=True)\r\n embed.add_field(name=\"Affiliation\", value=json[\"affiliation\"], inline=True)\r\n embed.add_field(name=\"Rarity\", value=json[\"rarity\"], inline=True)\r\n embed.add_field(name=\"Constellation\", value=json[\"constellation\"], inline=True)\r\n embed.add_field(name=\"Birthday\", value=json[\"birthday\"], inline=True)\r\n await ctx.send(embed=embed)\r\n\r\n @character.error\r\n async def character_error(self, ctx, error):\r\n if isinstance(error, commands.BadArgument):\r\n await ctx.send(f\"Error: `{error}`\")\r\n\r\n @genshin.group(name=\"artifact\", description=\"Sending genshin impact artifact data\")\r\n async def artifact(self, ctx, artifact: str):\r\n response = requests.get(f\"https://api.genshin.dev/artifacts/{artifact.lower()}\")\r\n if response.status_code == 404:\r\n raise commands.BadArgument(message=f\"no artifact named {artifact}.\")\r\n json = response.json()\r\n embed = discord.Embed(title=f\"{json['name']} information\", description=json[\"description\"], colour=self.colour_dict[json[\"max_rarity\"]])\r\n embed.add_field(name=\"Max rarity\", value=json[\"max_rarity\"], inline=True)\r\n embed.add_field(name=\"2 piece bonus\", value=json[\"2-piece_bonus\"], inline=True)\r\n embed.add_field(name=\"4 piece bonus\", value=json[\"4-piece_bonu\"], inline=True)\r\n await ctx.send(embed=embed)\r\n\r\n @artifact.error\r\n async def artifact_error(self, ctx, error):\r\n if isinstance(error, commands.BadArgument):\r\n await ctx.send(f\"Error: `{error}`\")\r\n\r\n @genshin.group(name=\"domain\", description=\"Sending genshin impact domain data\")\r\n async def domain(self, ctx, domain: str):\r\n domain = domain.replace(' ', '-')\r\n response = requests.get(f\"https://api.genshin.dev/artifacts/{domain.lower()}\")\r\n if response.status_code == 404:\r\n raise commands.BadArgument(message=f\"no domain named {domain}.\")\r\n json = response.json()\r\n embed = discord.Embed(title=f\"{json['name']} information\", description=json[\"description\"], colour=discord.Colour.blue())\r\n embed.add_field(name=\"Type\", value=json[\"type\"], inline=True)\r\n embed.add_field(name=\"Location\", value=json[\"location\"], inline=True)\r\n embed.add_field(name=\"Nation\", value=json[\"nation\"], inline=True)\r\n await ctx.send(embed=embed)\r\n\r\n @domain.error\r\n async def domain_error(self, ctx, error):\r\n if isinstance(error, commands.BadArgument):\r\n await ctx.send(f\"Error: `{error}`\")\r\n \r\n \r\n\r\ndef setup(bot):\r\n bot.add_cog(Genshin(bot))\r\n","repo_name":"Cr4zi/SynatxBot","sub_path":"src/cogs/genshin.py","file_name":"genshin.py","file_ext":"py","file_size_in_byte":3874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"10229839527","text":"# (c) PKY 2020\r\nimport pandas as pd\r\nimport statistics as st\r\n\r\nclass Student:\r\n def __init__(this, first, second, third, fourth, fifth, sixth, grade, email, gender):\r\n this.choices = [first, second, third, fourth, fifth, sixth]\r\n this.grade = grade\r\n this.email = email\r\n this.gender = gender\r\n\r\nclass Session:\r\n def __init__(this, capacity):\r\n this.capacity = capacity\r\n this.students = []\r\n this.ge_imbalance = [0, \"\"]\r\n this.gr_imbalance = [0, 0]\r\n\r\n def getGenderBalance(this):\r\n num_males = 0\r\n num_females = 0\r\n for student in this.students:\r\n if student.gender == \"Male\":\r\n num_males += 1\r\n else:\r\n num_females += 1\r\n dominant = \"Male\" if num_males > num_females else \"Female\"\r\n st_dev = st.stdev([num_males, num_females])*0.75\r\n this.ge_imbalance = [st_dev, dominant]\r\n\r\n def getGradeBalance(this):\r\n grades = [0, 0, 0, 0]\r\n for student in this.students:\r\n if student.grade == 9:\r\n grades[0] += 1\r\n if student.grade == 10:\r\n grades[1] += 1\r\n if student.grade == 11:\r\n grades[2] += 1\r\n if student.grade == 12:\r\n grades[3] += 1\r\n dominant = max(grades)\r\n dominant = grades.index(dominant)\r\n dominant += 9\r\n this.gr_imbalance = [st.stdev(grades), dominant]\r\n\r\n def addStudent(this, student):\r\n this.students.append(student)\r\n this.getGenderBalance()\r\n this.getGradeBalance()\r\n\r\n\r\ndef buildStudentArray(filepath):\r\n column_headers = [\"email\", \"grade\", \"gender\", \"participation\", \"first\", \"second\", \"third\", \"fourth\", \"fifth\", \"sixth\"]\r\n columns=[1, 4, 5, 6, 7, 8, 9, 10, 11, 12]\r\n form_frame = pd.read_csv(filepath, header=0, names=column_headers, usecols=columns)\r\n form_frame = form_frame[form_frame.participation == \"Yes, I would like to be scheduled into a SAiL session for May.\"]\r\n form_frame = form_frame.drop(columns=\"participation\")\r\n\r\n students = []\r\n for index, row in form_frame.iterrows():\r\n students.append(Student(row[\"first\"], row[\"second\"], row[\"third\"], row[\"fourth\"], row[\"fifth\"], row[\"sixth\"], row[\"grade\"], row[\"email\"], row[\"gender\"]))\r\n return students\r\n\r\ndef buildSessionArray(filepath):\r\n session_frame = pd.read_csv(filepath, names=[\"id\", \"capacity\"])\r\n\r\n sessions = {}\r\n for index, row in session_frame.iterrows():\r\n sessions[row.id] = Session(row.capacity)\r\n return sessions\r\n\r\ndef computeBalances(sessions):\r\n balances = {}\r\n for key in sessions:\r\n balances[key] = max(sessions[key].gr_imbalance[0], sessions[key].ge_imbalance[0])\r\n # print(str(sessions[key].gr_imbalance[0]) + \" \" + str(sessions[key].ge_imbalance[0]) + \" \" + str(balances[key][0]))\r\n return balances\r\n\r\ndef assignStudents(students, sessions):\r\n not_according_to_preferences = []\r\n\r\n for column in range(0, 3):\r\n if len(students) == 0:\r\n break\r\n sorted = []\r\n for i in range(0, len(students)):\r\n pref_session_id = students[i].choices[column]\r\n if sessions[pref_session_id].capacity > 0:\r\n sessions[pref_session_id].capacity -= 1\r\n sessions[pref_session_id].addStudent(students[i])\r\n sorted.append(students[i])\r\n for student in sorted:\r\n students.remove(student)\r\n print(len(students))\r\n\r\n balances = computeBalances(sessions)\r\n # print(balances)\r\n\r\n sorted = []\r\n for student in students:\r\n bottom_ids = student.choices[3:6]\r\n # print(str(student.email) + str(bottom_ids))\r\n bottom_sessions = {bottom_ids[i] : balances[bottom_ids[i]] for i in range(0, 3)}\r\n # print(bottom_sessions)\r\n\r\n would_worsen_balance = False\r\n for i in range(0, 3):\r\n if len(bottom_sessions) == 0:\r\n print(student.email)\r\n not_according_to_preferences.append(student)\r\n break\r\n\r\n key = max(bottom_sessions, key=bottom_sessions.get)\r\n session = sessions[key]\r\n if session.capacity > 0:\r\n if student.gender != session.ge_imbalance[1] or student.grade != session.gr_imbalance[1]:\r\n sorted.append(student)\r\n session.capacity -= 1\r\n session.addStudent(student)\r\n balances[key] = max(sessions[key].gr_imbalance[0], sessions[key].ge_imbalance[0])\r\n break\r\n else:\r\n would_worsen_balance = True\r\n else:\r\n del bottom_sessions[key]\r\n else:\r\n if would_worsen_balance:\r\n key = min(bottom_sessions, key=bottom_sessions.get)\r\n session = sessions[key]\r\n sorted.append(student)\r\n session.capacity -= 1\r\n session.addStudent(student)\r\n balances[key] = max(sessions[key].gr_imbalance[0], sessions[key].ge_imbalance[0])\r\n\r\n print([index.email for index in sorted])\r\n for student in sorted:\r\n students.remove(student)\r\n print(len(students))\r\n\r\n for student in students:\r\n not_according_to_preferences.append(student)\r\n\r\n return not_according_to_preferences\r\n\r\n # print(\"\\n\\nSTARTS HERE\\n\\n\")\r\n # print(balances)\r\n\r\ndef refactor(sessions, min):\r\n deleted_students = []\r\n for key in sessions:\r\n if len(sessions[key].students) < min:\r\n deleted_students += sessions[key].students\r\n\r\n not_according_to_preferences = assignStudents(deleted_students, sessions)\r\n return sessions\r\n\r\ndef buildOutput(students, sessions, prefs_array):\r\n output_frame = pd.DataFrame(columns=[\"Email\", \"Session\", \"Assigned According to Prefs?\"])\r\n for key in sessions:\r\n for student in sessions[key].students:\r\n prefs = \"No\" if student in prefs_array else \"Yes\"\r\n row = [student.email, key, prefs]\r\n output_frame.loc[len(output_frame.index)] = row\r\n\r\n for student in students:\r\n row = [student.email, \"Couldn't Be Assigned\", \"No\"]\r\n output_frame.loc[len(output_frame.index)] = row\r\n return output_frame\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n students = buildStudentArray(\"input.csv\")\r\n sessions = buildSessionArray(\"capacity.csv\")\r\n notPrefs = assignStudents(students, sessions)\r\n resultFrame = buildOutput(sessions, notPrefs)\r\n resultFrame.to_csv(\"results.csv\")\r\n","repo_name":"kevinlu4588/FalmouthSAiL","sub_path":"backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":6583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"4636850889","text":"import requests\nimport time\nimport yaml\n\nMAX_NUMBER = 1000000\nMIN_NUMBER = 1\n\n# Verify if the string is an integer or not\ndef verify_number(s):\n try:\n num = int(s)\n if num >= 1 & num <= 1000000:\n return True\n except ValueError:\n return False\n\nquotes = [\n \"Dr J: If it works, it means you forgot about something\",\n \"Wyatt: i can't believe dr j is trying to tempt me away from the light of god\",\n \"Wyatt: well, looks like [dr] j has baited me once again\",\n \"dr j: i may be failing my turing test. who cares? ive passed enough of tests that i can now apply pain to you\",\n \"Dr J: it’s so easy to write if statements if we know what statements they are\",\n]\n\ndef test_timing():\n # open yaml file that contains urls\n with open(r'url.yaml') as file:\n # Dictionary of urls. The the key is a description of the url, and the value is the url itself.\n urls = yaml.load(file, Loader=yaml.FullLoader)\n # Loop through the urls\n for url in urls.items():\n # Print the description of the url and the time\n start = time.time()\n\n # make the request\n r = requests.get(url[1])\n\n # get the end time\n end = time.time()\n\n # Verify that the request fits the constraints\n if verify_number(r.text):\n # print the results\n i = int(r.text)\n a = i % (len(quotes))\n print(quotes[a])\n else:\n print(\"An error has ocurred\")\n\ntest_timing()\n","repo_name":"ColeChronowski/GCP-RNG","sub_path":"rafaltune.py","file_name":"rafaltune.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"21388287802","text":"import numpy as np\nimport pandas as pd\n# from tensorflow import keras\nfrom sklearn.model_selection import train_test_split \nfrom konlpy.tag import Okt\nimport pickle\nfrom collections import Counter\nimport time\nfrom collections import Counter\nimport re\nfrom tensorflow import keras\nfrom keras import layers\nimport openpyxl\nokt =Okt()\ndef read_all_data():\n with open('14000개데이터.pickle','rb' ) as f:\n data14000 = pd.DataFrame(pickle.load(f))\n return data14000\ndef read_label_data(filename,label_name = '당첨자'):\n data= pd.read_excel(filename)\n data = data.loc[:,['title','content',label_name,'nouns']]\n return data\ndef mk_vocab(data,vocab_length):\n try:\n noun_list= []\n for nouns in data.loc[:,'nouns']:\n noun_list+=re.sub('[^ㄱ-힣]', ' ',nouns).split()\n vocab = sorted(Counter(noun_list).items(), key=lambda x:-x[1])[:int(vocab_length)]\n return vocab\n except:\n print('mk_vocab')\n\ndef mk_vt(data,tf_log, idf_log,vocab_length,vocab,all_data_length):\n # print(data)\n data = data['nouns']\n idf = np.zeros((int(vocab_length),))\n for i in data:\n i=re.sub('[^ㄱ-힣]', ' ',i).split()\n for key in i:\n if key in vocab:\n ind = vocab.index(key)\n idf[ind]+=1\n if idf_log==10:\n idf = np.log10(all_data_length/(idf+1))\n elif idf_log == 'e':\n idf = np.log(all_data_length/(idf+1))\n else:\n idf = np.log2(all_data_length/(idf+1))\n\n tf = data.apply(lambda x:a(x,vocab_length,vocab,tf_log))\n tf_idf = tf.apply(lambda x:x*idf )\n tf_idf = pd.DataFrame(dict(tf_idf).values())\n return tf_idf,idf\ndef a(record,vocab_length,vocab,tf_log):\n ze = np.zeros((vocab_length,))\n record=re.sub('[^ㄱ-힣]', ' ',record).split()\n for key, value in Counter(record).items():\n if key in vocab:\n ind = vocab.index(key)\n if tf_log == 'e':\n ze[ind]=1+np.log(value)\n elif tf_log=='10':\n ze[ind]=1+np.log10(value)\n else:\n ze[ind]=1+np.log2(value)\n return ze\n \n\ndef mk_model(dr01, dr02, dr03, ar01,ar02,ar03,vocab_length):\n model = keras.Sequential()\n model.add(layers.Dropout(dr01))\n model.add(layers.Dense(units=vocab_length/2,activation=ar01, input_shape = (vocab_length,)))\n model.add(layers.Dropout(dr02))\n model.add(layers.Dense(units =vocab_length/4,activation=ar02))\n model.add(layers.Dropout(dr03))\n model.add(layers.Dense(1,activation=ar03))\n print(ar01, ar02, ar03)\n model.compile(optimizer = 'adam',loss='binary_crossentropy',metrics = 'accuracy')\n return model\ndef split_data(tf_idf, target):\n try:\n train_data, test_data, train_target, test_target = train_test_split(tf_idf, target, test_size = 0.2, random_state=122,stratify=target)\n except:\n train_data, test_data, train_target, test_target = train_test_split(tf_idf, target, test_size = 0.2, random_state=122)\n return train_data, test_data, train_target, test_target\ndef train_model(model,tf_idf,target,epochs,train_data, test_data, train_target,test_target):\n print('trd',train_data.shape)\n print('ted',test_data.shape)\n print('trt',train_target.shape)\n print('tet',test_target.shape)\n history = model.fit(train_data, train_target,epochs = epochs,validation_data = (test_data, test_target))\n return model, history\ndef test_model(model,tf_idf):\n pre = model.predict(tf_idf)\n return pre \ndef predict(model, data14000,data,tf_log, idf_log,vocab_length,vocab):\n data14000['nouns']=data14000['nouns'].astype('str')\n data['nouns']=data['nouns'].astype('str')\n data_merged = pd.merge(data14000, data, how = 'outer',indicator=True)\n data_merged = data_merged[data_merged['_merge']=='left_only'].drop_duplicates()\n data_merged.drop('_merge',axis= 1)\n new_data_nouns = data_merged['nouns']\n idf = np.zeros((int(vocab_length),))\n all_data_length = len(data14000)\n for i in new_data_nouns:\n i=re.sub('[^ㄱ-힣]', ' ',str(i)).split()\n for key in i:\n if key in vocab:\n ind = vocab.index(key)\n idf[ind]+=1\n if idf_log==10:\n idf = np.log10(all_data_length/(idf+1))\n elif idf_log == 'e':\n idf = np.log(all_data_length/(idf+1))\n else:\n idf = np.log2(all_data_length/(idf+1))\n\n tf = new_data_nouns.apply(lambda x:a(x,vocab_length,vocab,tf_log))\n tf_idf = tf.apply(lambda x:x*idf )\n tf_idf = pd.DataFrame(dict(tf_idf).values())\n pre_list = model.predict(tf_idf)\n return pre_list,data_merged\ndef evaluate(model, test_data, test_target):\n ev = model.evaluate(test_data,test_target)\n return ev","repo_name":"dydtkddl/labeling_binary_sejong","sub_path":"train_model.py","file_name":"train_model.py","file_ext":"py","file_size_in_byte":4724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"35559159382","text":"import hid #https://github.com/apmorton/pyhidapi/blob/master/hid/__init__.py\nimport random\n\nvid = 0x16D0 # MCS\npid = 0x0FA5 # Timetosser\n \ndef hid_test():\n result = True\n \n # first byte is report id 3 to indicate big packet.\n # This packet would normally be 64 bytes, but for some bug in ST's usb code it won't receive it unless we send\n # something smaller first...\n # So we test with a packet of 56 bytes.\n bigReport = [3,0,0,0,0,0,0,0,\n 0,0,0,0,0,0,0,0,\n 0,0,0,0,0,0,0,0,\n 0,0,0,0,0,0,0,0,\n 0,0,0,0,0,0,0,0,\n 0,0,0,0,0,0,0,0,\n 0,0,0,0,0,0,0,0]\n\n # fill bigreport (except for report Id) with random bytes\n for i in range(1, len(bigReport)):\n bigReport[i] = random.randint(0, 255)\n \n result = True\n try:\n with hid.Device(vid, pid) as h:\n outpacket = bytes(bigReport)\n \n # we perform the test twice, because first received HID packet is corrupt because of ST firmware (grr)\n h.write(outpacket)\n inpacket = h.read(64, 100) # read maximum of 64 bytes, 100 ms timeout\n \n h.write(outpacket)\n inpacket = h.read(64, 100) # read maximum of 64 bytes, 100 ms timeout\n \n if len(bytearray(inpacket)) == 0:\n print(\"HID Test failed: timeout while reading device. FAIL\")\n result = False;\n \n elif outpacket != inpacket:\n print(\"HID Test failed, packets are not equal. FAIL\")\n print(\"Sent:\")\n print(outpacket)\n print(\"Received:\")\n print(inpacket)\n result = False\n except Exception as e:\n print(e)\n print(\"HID Test failed, could not open device. FAIL\")\n result = False\n \n if result == True:\n print(\"HID Test PASS\")\n return result\n\n#test HID functionality of timetosser in usb-application mode (not in test-mode)\n#read key state and send led state\ndef hid_application(vid, pid):\n # packet sent for led state (not available during test firmware), 1st byte is report Id (1)\n ledReport = [1, \n 0, 0xff, 0, 0, 0xff, 0, 0, 0xff, 0, 0, 0xff, 0,\n 0, 0xff, 0, 0, 0xff, 0, 0, 0xff, 0, 0, 0xff, 0,\n 0, 0xff, 0, 0, 0xff, 0, 0, 0xff, 0, 0, 0xff, 0,\n 0, 0xff, 0, 0, 0xff, 0, 0, 0xff, 0, 0, 0xff, 0, #16 x 3 bytes for rgb led color\n 0, 0] # plus 2 bytes for \"on\" state, 51 bytes total\n outPacket = bytearray(ledReport)\n \n with hid.Device(vid, pid) as h:\n while(True):\n receivedBytes = h.read(64, 100) # read 64 bytes max, 100 ms timeout\n if len(bytearray(receivedBytes)) == 3 and receivedBytes[0] == 1: # check size and report id\n \n #print key state\n print('********')\n printKeyRow(receivedBytes[2])\n printKeyRow(receivedBytes[1])\n \n #set key state in led state\n outPacket[49] = receivedBytes[1]\n outPacket[50] = receivedBytes[2]\n try:\n h.write(bytes(outPacket))\n except Exception as e:\n print(outPacket)\n pass\n\ndef printKeyRow(byte):\n keys = ''\n for i in range(8):\n if byte & (1 << i):\n keys += '1'\n else:\n keys += '0'\n print(keys)\n \ndef printDevices():\n print(hid.enumerate())\n\ndef printDevice(vid, pid):\n with hid.Device(vid, pid) as h:\n print(f'Device manufacturer: {h.manufacturer}')\n print(f'Product: {h.product}')\n print(f'Serial Number: {h.serial}')\n \n#functional test: during test-firmware, timetosser enumerates as full-speed (12MBit) device\n#it should echo back what you send to it, test if this works\n#hid_test()\n\n#when timetosser is not in testmode: read keystate and send back led data\n#hid_application(vid, pid)\n\n#print(hid.enumerate())\n#printDevice(vid, pid)\n","repo_name":"timistof/functionaltest","sub_path":"testhid.py","file_name":"testhid.py","file_ext":"py","file_size_in_byte":4115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"39272029278","text":"#!/usr/bin/env python\n\nfrom multiprocessing import Process, Queue, cpu_count\n\n\ndef explore(needle, function, proc_count=None, chunk_size=100000):\n results = []\n in_queue = Queue()\n out_queue = Queue()\n if proc_count is None:\n proc_count = cpu_count()\n\n def handle_result():\n result = in_queue.get()\n if result:\n results.append(result)\n return True\n\n procs = [Process(target=function,\n args=(worker_number, chunk_size, needle, out_queue, in_queue))\n for worker_number in range(proc_count)]\n for proc in procs:\n proc.start()\n\n for chunk, _ in enumerate(procs):\n out_queue.put(chunk)\n\n chunk = proc_count\n while True:\n if handle_result():\n break\n\n chunk += 1\n out_queue.put(chunk)\n\n for proc in procs:\n out_queue.put(None)\n\n for _ in procs[1:]:\n handle_result()\n\n for proc in procs:\n proc.join()\n\n return sorted(results)[0][1]\n","repo_name":"kstrauser/spacewalker","sub_path":"spacewalker/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"41"} +{"seq_id":"42952963404","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n'''\nPainting with OpenCV.\n--------------------\nclick and drag your mouse to paint\nKeys:\n r - reset the painting canvas\n q - exit\n'''\n\nimport cv2\nimport numpy as np\n\ndrawing = False # true if mouse is pressed\nimg = None\n\n# mouse callback function\ndef draw(event,x,y,flags,param):\n global drawing, img\n\n if event == cv2.EVENT_LBUTTONDOWN:\n drawing = True\n\n elif event == cv2.EVENT_MOUSEMOVE:\n if drawing == True:\n cv2.circle(img, (x, y), 3, (0, 255, 0), -1)\n\n elif event == cv2.EVENT_LBUTTONUP:\n drawing = False\n \ndef main():\n global img\n img = np.zeros((512,512,3), np.uint8)\n cv2.namedWindow('image')\n cv2.setMouseCallback('image', draw)\n\n while True:\n cv2.imshow('image',img)\n \n k = cv2.waitKey(1)\n if k == ord('r'):\n img = np.zeros((512, 512, 3), np.uint8)\n if k == ord('q'):\n break\n\nif __name__ == '__main__':\n print(__doc__)\n main()\n cv2.destroyAllWindows()\n\n","repo_name":"Ankur-singh/computer_vision_book","sub_path":"_build/jupyter_execute/nbs/paint.py","file_name":"paint.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"25287671348","text":"def observed():\n observations = [] \n for x in range(5):\n print(\"Enter an observation:\")\n observation = input() \n observations.append(observation)\n return observations\n\ndef removeObservations(observations):\n print(\"Would you like to remove observations (yes/no)?\")\n yesNo = input() \n if yesNo == 'yes':\n print(\"Enter an observation to be removed:\")\n remove = input() \n observations.remove(remove) \n else:\n return \n\ndef run():\n observations = observed() \n removeObservations(observations)\n observationSet = set()\n\n for x in observations:\n observationSet.add((x, observations.count(x)))\n\n print(observationSet)\nrun()","repo_name":"MayeHunt/com411","sub_path":"data/sets/sorted_list.py","file_name":"sorted_list.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"28419135383","text":"from datetime import datetime\nfrom random import randint\n\nfrom django.template.loader import get_template\n\nfrom Common.utils import PAID, PENDING, CANCELLED\nfrom Homes.Houses.models import SharedRoom\nfrom Homes.Houses.utils import SHARED_ROOM, SOLD_OUT, AVAILABLE\nfrom utility.file_utils import render_pdf_from_html\n\n# ON-BOARDING Charges are now considered in TOKEN_AMOUNT and ONBOARDING_CHARGES has been removed from move in charges\n# or we can say ONBOARDING CHARGES ARE SET to 0\n\n# TOKEN_AMOUNT = 200.0 # Deprecated\n# ONBOARDING_CHARGES = 200.0 # Deprecated\nfrom utility.logging_utils import sentry_debug_logger\n\nTOKEN_AMOUNT = 400.0\nONBOARDING_CHARGES = 0\n\nLATE_MONTHLY_RENT_FINE_AMOUNT = 150\n\nNEW_TENANT_BOOKING = 'new_tenant_booking'\nEXISTING_TENANT_BOOKING = 'existing_tenant_booking'\n\nBookingTypeCategories = (\n (NEW_TENANT_BOOKING, 'New Tenant Booking'),\n (EXISTING_TENANT_BOOKING, 'Existing Tenant Booking')\n)\n\nBOOKING = 'booking'\n\nBOOKING_CANCELLED = 'cancelled'\nBOOKING_COMPLETE = 'complete'\nBOOKING_PARTIAL = 'partial'\n\nBookingStatusCategories = (\n (BOOKING_CANCELLED, 'Cancelled'),\n (BOOKING_PARTIAL, 'Partially complete'),\n (BOOKING_COMPLETE, 'Complete'),\n)\n\nAGREEMENT_SIGN_NOT_UPLOADED = 'unsigned'\nAGREEMENT_SIGN_VERIFIED_SUCCESS = 'verified'\nAGREEMENT_SIGN_VERIFICATION_ONGOING = 'ongoing'\nAGREEMENT_SIGN_VERIFICATION_ERROR = 'error'\n\nAgreementVerificationStatusChoices = (\n (AGREEMENT_SIGN_NOT_UPLOADED, 'Signature not uploaded'),\n (AGREEMENT_SIGN_VERIFIED_SUCCESS, 'Verification Complete'),\n (AGREEMENT_SIGN_VERIFICATION_ONGOING, 'Verification Ongoing'),\n (AGREEMENT_SIGN_VERIFICATION_ERROR, 'Error in Verification'),\n)\n\nBOOKING_CANCELLATION_MSG = \"Hi {}! Your booking for {} at {} has been cancelled as {}\"\nBOOKING_CANCELLATION_REASON_1 = \"you have not paid the token amount before the due date.\"\nBOOKING_CANCELLATION_REASON_2 = \"the space got sold out before your token payment.\"\n\nSUB_UNIT_ITEM = 'sub_unit'\nCOMMON_AREA_ITEM = 'common_area'\n\nFacilityItemTypeCategories = (\n (SUB_UNIT_ITEM, 'Sub Unit'),\n (COMMON_AREA_ITEM, 'Common Area')\n)\n\nFACILITY_ALLOCATED = 'Allocated'\nFACILITY_RETURNED = 'Returned'\nFACILITY_LOST = 'Lost'\nFACILITY_DAMAGED = 'Damaged'\n\nBookingFacilityStatusChoices = (\n (FACILITY_ALLOCATED, FACILITY_ALLOCATED),\n (FACILITY_RETURNED, FACILITY_RETURNED),\n (FACILITY_LOST, FACILITY_LOST),\n (FACILITY_DAMAGED, FACILITY_DAMAGED),\n)\n\nMonthlyRentStatusCategories = (\n (PAID, \"Paid\"),\n (PENDING, \"Pending\"),\n (CANCELLED, \"Cancelled\")\n)\n\n\ndef get_tabular_facilities(booking):\n sub_unit_facilities = booking.facilities.filter(item__type=SUB_UNIT_ITEM)\n common_area_facilities = booking.facilities.filter(item__type=COMMON_AREA_ITEM)\n parts = [sub_unit_facilities[::2], sub_unit_facilities[1::2],\n common_area_facilities[::2], common_area_facilities[1::2]]\n max_len = max(map(lambda x: len(x), parts))\n new_parts = []\n for part in parts:\n new_parts.append(part + [''] * (max_len - len(part)))\n return list(zip(*new_parts))\n\n\ndef get_param_dict_for_rent_agreement(booking):\n facilities = get_tabular_facilities(booking)\n param_dict = {'tenant': booking.tenant, 'booking': booking,\n 'owner': booking.space.house.owner, 'facilities': facilities,\n 'agreement_date': booking.license_start_date.date().strftime(\n '%d %b, %Y'),\n }\n if booking.agreement_verification_status == AGREEMENT_SIGN_VERIFIED_SUCCESS:\n try:\n param_dict['digital_signature'] = booking.signature.signature.url\n except Exception as E:\n sentry_debug_logger.error(E, exc_info=True)\n\n return param_dict\n\n\ndef load_rent_agreement(booking):\n param_dict = get_param_dict_for_rent_agreement(booking)\n return render_pdf_from_html(\"rent_agreement.html\", param_dict,\n '{}_Rent_Agreement.pdf'.format(booking.tenant.customer.name.replace(' ', '_')))\n\n\ndef load_rent_agreement_as_html(booking):\n path = \"rent_agreement.html\"\n param_dict = get_param_dict_for_rent_agreement(booking)\n template = get_template(path)\n html = template.render(param_dict)\n return html\n\n\ndef change_booked_space_status(booking):\n if booking.space.type != SHARED_ROOM:\n booking.space.availability = SOLD_OUT\n booking.space.save()\n else:\n shared_room = SharedRoom.objects.filter(space=booking.space).first()\n free_bed = shared_room.beds.filter(availability=AVAILABLE, visible=True).first()\n free_bed.availability = SOLD_OUT\n free_bed.save()\n\n\ndef reset_booked_space_status(booking):\n if booking.space.type != SHARED_ROOM:\n booking.space.availability = AVAILABLE\n booking.space.save()\n else:\n shared_room = SharedRoom.objects.filter(space=booking.space).first()\n occupied_bed = shared_room.beds.filter(availability=SOLD_OUT, visible=True).first()\n occupied_bed.availability = AVAILABLE\n occupied_bed.save()\n\n\ndef get_tenant_digital_signature_while_move_in_upload_path(instance, filename):\n return \"Bookings/{}/MoveIn/DigitalSignature/{}_{}/\".format(instance.booking.id, filename.split('/')[-1],\n randint(111111, 999999))\n","repo_name":"FalseG0d/Halanx_Backend_Task","sub_path":"Homes/Bookings/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5308,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"32245628190","text":"# Write a program that reads a matrix from the console and performs certain operations with its elements.\n# User input is provided similarly to the problems above - first, you read the dimensions and then the data.\n# Your program should receive commands in the format:\n# \"swap {row1} {col1} {row2} {col2}\" where (\"row1\", \"col1\") and (\"row2\", \"col2\") are\n# the coordinates of two points in the matrix.\n# A valid command starts with the \"swap\" keyword along with four valid coordinates (no more, no less),\n# separated by a single space.\n# • If the command is valid, you should swap the values at the given indexes and print the matrix\n# at each step (thus, you will be able to check if the operation was performed correctly).\n# • If the command is not valid (does not contain the keyword \"swap\",\n# has fewer or more coordinates entered, or the given coordinates are not valid),\n# print \"Invalid input!\" and move on to the following command.\n# A negative value makes the coordinates not valid.\n# Your program should finish when the command \"END\" is entered.\n\ndef check_indices(first, second, third, fourth, rows, columns):\n return first in range(rows) and second in range(columns) and third in range(rows) and fourth in range(columns)\n\n\nrows, columns = [int(x) for x in input().split()]\n\nmatrix = []\n\nfor _ in range(rows):\n matrix.append([x for x in input().split()])\n\nwhile True:\n command = input()\n if command == 'END':\n break\n info = command.split()\n\n if info[0] != 'swap' and len(info) != 5:\n print('Invalid input!')\n continue\n if not info[1].isdigit() or not info[2].isdigit() or not info[3].isdigit() or not info[4].isdigit():\n print('Invalid input!')\n continue\n else:\n first = int(info[1])\n second = int(info[2])\n third = int(info[3])\n fourth = int(info[4])\n if check_indices(first, second, third, fourth, rows, columns):\n matrix[first][second], matrix[third][fourth] = matrix[third][fourth], matrix[first][second]\n for row in matrix:\n print(*row, sep=' ')\n else:\n print('Invalid input!')\n continue\n","repo_name":"ddimitrovv/Python-Advanced-SoftUni","sub_path":"07_multidimentional_lists_exercise/6_matrix_shuffling.py","file_name":"6_matrix_shuffling.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"8280165176","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\nimport os\nimport argparse\nfrom tqdm import tqdm\nimport tensorflow as tf\nimport logging\n\nfrom shabda.data.dataset.internal.audio_dataset_base import AudioDatasetBase\nfrom shabda.data.dataset.internal.dataset_factory import DatasetFactory\nfrom shabda.data.iterators.internal.data_iterator_factory import DataIteratorFactory\nfrom shabda.data.iterators.internal.data_iterator_base import DataIteratorBase\nfrom shabda.models.internal.model_factory import ModelsFactory\n# TODO - \"import *\" also import some python meta variables, hence not recommended\nfrom shabda.helpers.print_helper import *\nfrom shabda.hyperparams.hyperparams import HParams\nfrom shabda.run.executor import Executor\n\n# get TF logger\nlog = logging.getLogger('tensorflow')\nlog.setLevel(logging.DEBUG)\n\nCGREEN2 = '\\33[92m'\nCEND = '\\33[0m'\n\n\nclass Experiments(object):\n \"\"\"\n Experiments uses dataset, data iterator & model factory classes and import them\n dynamically based on the string.\n This allows the user to choose the modules dynamically and run the experiments without ever writing the\n code when we need mix and experiment dataset and modules.\n \"\"\"\n\n def __init__(self, hparams, mode='train'):\n self._hparams = HParams(hparams, self.default_hparams())\n\n self.mode = mode\n\n self.dataset = None\n self.data_iterator = None\n self.model = None\n\n @staticmethod\n def default_hparams():\n return None\n\n def get_dataset_reference(self, dataset_name):\n \"\"\"\n Uses the dataset name to get the reference from the dataset factory class\n\n :param dataset_name:\n :return:\n \"\"\"\n\n print_debug(\"Geting dataset :\" + dataset_name)\n dataset = DatasetFactory.get(dataset_file_name=dataset_name)\n return dataset\n\n def get_iterator_reference(self, iterator_name):\n \"\"\"\n Uses the iterator name to get the reference from the iterator factory class\n\n :param iterator_name:\n :return:\n \"\"\"\n\n print_debug(\"Geting iterator :\" + iterator_name)\n iterator = DataIteratorFactory.get(iterator_name=iterator_name)\n return iterator\n\n def get_model_reference(self, model_name):\n \"\"\"\n Uses the model name to get the reference from the model factory class\n\n :param model_name:\n :return:\n \"\"\"\n\n print_debug(\"Geting model :\" + model_name)\n model = ModelsFactory.get(model_name=model_name)\n return model\n\n def setup(self):\n\n run_config = tf.ConfigProto()\n run_config.gpu_options.allow_growth = True\n # run_config.gpu_options.per_process_gpu_memory_fraction = 0.50\n run_config.allow_soft_placement = True\n run_config.log_device_placement = False\n self._run_config = tf.contrib.learn.RunConfig(session_config=run_config,\n save_checkpoints_steps=50,\n keep_checkpoint_max=5,\n save_summary_steps=25,\n model_dir=self._hparams[\"model_directory\"],\n log_step_count_steps=10)\n\n # Using factory classes get the handle for the actual classes from string\n self.dataset = self.get_dataset_reference(self._hparams.dataset_name)\n self._data_iterator = self.get_iterator_reference(self._hparams.data_iterator_name)\n self.model = self.get_model_reference(self._hparams.model_name)\n\n # Initialize the handles and call any user specific init() methods\n self.dataset: AudioDatasetBase = self.dataset(hparams=self._hparams[self._hparams['dataset_name']])\n self.dataset.init()\n\n self._data_iterator: DataIteratorBase = self._data_iterator(hparams=self._hparams.data_iterator,\n dataset=self.dataset)\n\n model_params = self._hparams.model\n\n self.model = self.model(hparams=model_params)\n\n def test_dataset(self):\n iterator = self._data_iterator.get_train_input_fn().make_initializable_iterator()\n next_element = iterator.get_next()\n print_error(next_element)\n init_op = iterator.initializer\n with tf.Session() as sess:\n # Initialize the iterator\n sess.run(init_op)\n print(sess.run(next_element))\n print(sess.run(next_element))\n # Move the iterator back to the beginning\n sess.run(init_op)\n print(sess.run(next_element))\n\n def run(self):\n self.setup()\n num_samples = self.dataset.get_num_train_samples()\n batch_size = self._hparams.data_iterator.batch_size\n num_epochs = self._hparams.num_epochs\n mode = self.mode\n\n exec = Executor(model=self.model, data_iterator=self._data_iterator, config=self._run_config)\n\n if (mode == \"train\") or (mode == \"retrain\"):\n for current_epoch in tqdm(range(num_epochs), desc=\"Epoch\"):\n current_max_steps = (num_samples // batch_size) * (current_epoch + 1)\n exec.train(max_steps=current_max_steps) # , eval_steps=None)\n exec.evaluate(steps=200)\n","repo_name":"dhiraa/shabda","sub_path":"src/main/python/shabda/run/experiments.py","file_name":"experiments.py","file_ext":"py","file_size_in_byte":5411,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"40"} +{"seq_id":"38239192895","text":"# class User:\n# def __init__(self, name, email):\n# self.name = name\n# self.email = email\n# self.logged = False\n# def login(self):\n# self.logged = True\n# print(self.name + \" is logged in. \")\n# return self\n\n# new_user = User(\"Anna\",\"anna@anna.com\")\n# print(new_user.name)\n\n\n# class User:\n# name = \"Anna\"\n\n\n\n# anna = User()\n# print(\"anna's name:\", anna.name)\n# User.name = \"Bob\"\n# print(\"anna's name after change:\", anna.name)\n# # bob = User()\n# # print(\"bob's name:\", bob.name)\n# marco = User()\n# print(marco.name)\n\n\n# class User:\n# def __init__(self, name, email):\n# self.name = name\n# self.email = email\n# self.logged = False\n\n\n# user1 = User(\"Anna Propas\", \"anna@anna.com\")\n# print(user1.name)\n# print(user1.logged)\n# print(user1.email)\n\n\n# class Bike:\n# def __init__(self, price, max_speed, miles=0):\n# self.price = price\n# self.max_speed = max_speed\n# self.miles = miles\n\n# def displayInfo(self):\n# print(\"The price is \" + str(self.price))\n# print(\"The maximum speed that you can achieve is \" + str(self.max_speed))\n# print(\"This bike has run \" + str(self.miles))\n\n# def ride(self):\n# self.miles += 10\n# return self\n\n# def reverse(self):\n# if (self.miles > 0):\n# self.miles -= 5\n# return self\n\n\n# bike1 = Bike(10, 10)\n# bike1.ride().ride().ride().reverse()\n# bike1.displayInfo()\n\n# bike2 = Bike(200, 20, 130)\n# bike2.ride().ride().ride().reverse()\n# bike2.displayInfo()\n\n# bike3 = Bike(300, 50)\n# bike3.ride().ride().ride().reverse()\n# bike3.displayInfo()\n\n\n# class Cars:\n# def __init__(self, price, speed, fuel, mileage, tax=0):\n# self.price = price\n# self.speed = speed\n# self.fuel = fuel\n# self.mileage = mileage\n# self.tax = tax\n\n# def display_all(self):\n# print(\"Price: \" + str(self.price))\n# print(\"Speed: \" + str(self.speed))\n# print(\"Fuel: \" + str(self.fuel))\n# print(\"Mileage: \" + str(self.mileage))\n# if(self.price > 10000):\n# self.tax = 0.15\n# else:\n# self.tax = 0.12\n# print(\"Tax: \" + str(self.tax)+\"\\n\")\n# display_all(self)\n\n\n# car1 = Cars(10000, \"180 Mph\", \"Full\", \"35mpg\")\n# car1 = Cars(15000, \"180 Mph\", \"Full\", \"55mpg\")\n# car1 = Cars(2000, \"220 Mph\", \"Empty\", \"35mpg\")\n# car1 = Cars(25000, \"220 Mph\", \"Full\", \"25mpg\")\n# car1 = Cars(5000, \"220 Mph\", \"Half\", \"45mpg\")\n# car1 = Cars(48000, \"220 Mph\", \"Half\", \"15mpg\")\n\n\n# class Product:\n# def __init__(self, price, itemName, weight, brand, status=\"for sale\"):\n# self.price = price\n# self.itemName = itemName\n# self.weight = weight\n# self.brand = brand\n# self.status = status\n\n# def sell(self, tax):\n# self.status = \"sold\"\n# print(\"\\nThe item: \" + str(self.itemName) +\n# \"\\nPrice before taxes is: \" + str(self.price))\n# self.price = self.price + ((self.price * tax)/100)\n# print(\"\\nTax amount charged: \" + str(tax) + \" percent.\" +\n# \"\\nPrice after taxes: \" + str(self.price))\n# print(\"\\nNew current item status: \" + str(self.status))\n# return self\n\n# def saleReturns(self, reason_for_return):\n# if(reason_for_return == \"defective\"):\n# self.status = \"defective\"\n# self.price = 0\n# print(\"\\nThis item is: \" + str(self.status) +\n# \" and is not longer for sale\")\n# print(\"Current item price: \" + str(self.price))\n# elif(reason_for_return == \"like_new\"):\n# self.status = \"for sale\"\n# print(\n# \"\\nThis item is like new and the current status shows: \" + str(self.status))\n# elif(reason_for_return == \"opened\"):\n# self.status = \"used\"\n# self.price = self.price * 0.8\n# print(\"Open Box status: \" + str(self.status))\n# print(\"20% discounted price: \" + str(self.price))\n# return self\n\n# def displayInfo(self):\n# print(\"\\n\\n\\nProduct Name: \" + str(self.itemName) + \"\\nProduct Price: \" + str(self.price) + \"\\nProduct Weight: \" +\n# str(self.weight) + \"\\nProduct Brand: \" + str(self.brand) + \"\\nProduct Availability Status: \" + str(self.status))\n\n# # gameConsole = Product(100,\"Game Console\", \"12 pounds\", \"Nintendo\")\n\n\n# # gameConsole.sell(8)\n\n# watch = Product(5000, \"rolex\", \"50 pounds\", \"rolex\")\n# # watch.sell(1)\n# watch.saleReturns(\"defective\")\n# # watch.displayInfo()\n\n# # gameConsole.saleReturns(\"defective\")\n# # gameConsole.saleReturns(\"like_new\")\n# # gameConsole.saleReturns(\"opened\")\n\n\nclass Vehicle:\n def __init__(self, wheels, capacity, make, model):\n self.wheels = wheels\n self.capacity = capacity\n self.make = make\n self.model = model\n self.mileage = 0\n\n def drive(self, miles):\n self.mileage += miles\n return self\n\n def reverse(self, miles):\n self.mileage -= miles\n return self\n\n\nclass Bike(Vehicle):\n def vehicle_type(self):\n return \"Bike\"\n\n\nclass Car(Vehicle):\n def set_wheels(self):\n self.wheels = 4\n return self\n\n\nclass Airplane(Vehicle):\n def fly(self, miles):\n self.mileage += miles\n return self\n\n\nv = Vehicle(4, 8, \"dodge\", \"minivan\")\nprint(v.make)\nb = Bike(2, 1, \"Schwinn\", \"Paramount\")\nprint(b.vehicle_type())\nc = Car(8, 5, \"Toyota\", \"Matrix\")\nc.set_wheels()\nprint(c.wheels)\na = Airplane(22, 853, \"Airbus\", \"A380\")\na.fly(580)\nprint(a.mileage)\n","repo_name":"marcobasurco/simplewall","sub_path":"tmp.py","file_name":"tmp.py","file_ext":"py","file_size_in_byte":5647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"11758042035","text":"# Staging server settings\nfrom .base import *\nDEBUG = True\n\nENVIRONMENT = Environment.STAGING\n\nEMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\n\n# XXX: no i18n for the time being\nUSE_I18N = False\n\nSITE_URL = 'https://dev.vcweb.asu.edu'\n\n# security settings\n\nSESSION_COOKIE_SECURE = True\nCSRF_COOKIE_SECURE = True\nSECURE_CONTENT_TYPE_NOSNIFF = True\nSECURE_BROWSER_XSS_FILTER = True\nX_FRAME_OPTIONS = 'DENY'\n\nWEBSOCKET_SSL = True\n","repo_name":"Takato0120/social_ecological_system","sub_path":"vcweb/settings/staging.py","file_name":"staging.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"25395319769","text":"\"\"\"A simple API for reading and writing pickle files.\n\nExamples:\n```python\nfrom cerbernetix.toolbox.files import PickleFile, read_pickle_file, write_pickle_file\n\nfilename = 'path/to/file.pkl'\ndata = [\n {'date': '2023-09-10', 'value': 42},\n {'date': '2023-09-11', 'value': 24},\n {'date': '2023-09-12', 'value': 44},\n]\n\n# Create a Pickle file from the given data\nwrite_pickle_file(filename, data)\n\n# Read the Pickle data from an existing file\ndata = read_pickle_file(filename)\n\n# Use a file manager\npickle = PickleFile(filename)\n\n# Create a Pickle file from the given data\npickle.write_file(data)\n\n# Read the Pickle data from an existing file\ndata = pickle.read_file()\n\n# Write Pickle object by object\nwith pickle.open(create=True):\n for obj in data:\n pickle.write(obj)\n\n# Read all objects from the Pickle\ndata = [obj for obj in pickle]\n\n# Read the first object\nwith file:\n first = file.read()\n```\n\"\"\"\nfrom __future__ import annotations\n\nimport pickle\nfrom typing import Iterable\n\nfrom cerbernetix.toolbox.files.file_manager import FileManager\n\n# The parameters that will be forwarded to the pickle reader\nPICKLE_READER_PARAMS = [\n \"fix_imports\",\n \"encoding\",\n \"errors\",\n \"buffers\",\n]\n\n# The parameters that will be forwarded to the pickle writer\nPICKLE_WRITER_PARAMS = [\n \"protocol\",\n \"fix_imports\",\n \"buffer_callback\",\n]\n\n# The parameters that will be forwarded to the file opener\nFILE_OPEN_PARAMS = [\"buffering\", \"errors\", \"closefd\", \"opener\"]\n\n\nclass PickleFile(FileManager):\n \"\"\"Offers a simple API for reading and writing pickle files.\n\n The class binds a filename with a set of properties so that it can be opened in a consistent\n way.\n\n The read API does not allow to size the data to read. However, it reads the file record by\n record.\n\n Attributes:\n filename (str): The path to the file to manage.\n binary (bool): The type of file, say binary. It must always be True.\n\n Examples:\n ```python\n from cerbernetix.toolbox.files import PickleFile\n\n file = PickleFile(\"path/to/the/file\")\n\n # write some objects to the file\n with file(create=True):\n file.write(users)\n file.write(profiles)\n\n # read the records from the file\n with file:\n users = file.read()\n profiles = file.read()\n\n # gets the records in a list\n data = [obj for obj in file]\n\n # write records to the file\n file.write_file(data)\n\n # load the whole file, handling internally its opening\n data = file.read_file()\n ```\n \"\"\"\n\n def __init__(\n self,\n filename: str,\n create: bool = False,\n append: bool = False,\n read: bool = False,\n write: bool = False,\n **kwargs,\n ):\n \"\"\"Creates a file manager for pickle files.\n\n Args:\n filename (str): The path to the file to manage.\n create (bool, optional): Expect to create the file. If it exists, it will be replaced.\n Defaults to False.\n append (bool, optional): Expect to extend the file. Data will be added at the end.\n Defaults to False.\n read (bool, optional): Expect to also read the file.\n Defaults to False.\n write (bool, optional): Expect to also write to the file.\n Defaults to False.\n protocol (int, optional): Tells the pickle writer to use the given protocol; supported\n protocols are 0 to HIGHEST_PROTOCOL. If a negative number is specified, HIGHEST_PROTOCOL\n is selected. When reading, the protocol version of the pickle is detected automatically.\n Defaults is DEFAULT_PROTOCOL.\n fix_imports (bool, optional): If fix_imports is true and protocol is less than 3,\n pickle will try to map the new Python 3 names to the old module names used in Python 2,\n so that the pickle data stream is readable with Python 2. Defaults to True.\n encoding (str, optional): Tell pickle how to decode 8-bit string instances pickled by\n Python 2. The encoding can be ‘bytes’ to read these 8-bit string instances as bytes objects.\n Using encoding='latin1' is required for unpickling NumPy arrays and instances of datetime,\n date and time pickled by Python 2. Defaults to ‘ASCII’.\n errors (str, optional): Tell pickle how to decode 8-bit string instances pickled by\n Python 2. Defaults to ‘strict’.\n buffers (optional): If buffers is None (the default), then all data necessary for\n deserialization must be contained in the pickle stream. This means that the buffer_callback\n argument was None when a Pickler was instantiated (or when dump() or dumps() was called). If\n buffers is not None, it should be an iterable of buffer-enabled objects that is consumed\n each time the pickle stream references an out-of-band buffer view. Such buffers have been\n given in order to the buffer_callback of a Pickler object.\n buffer_callback (optional): If buffer_callback is None (the default), buffer views are\n serialized into file as part of the pickle stream. If buffer_callback is not None, then\n it can be called any number of times with a buffer view. If the callback returns a false\n value (such as None), the given buffer is out-of-band; otherwise the buffer is\n serialized in-band, i.e. inside the pickle stream. It is an error if buffer_callback is\n not None and protocol is None or smaller than 5. Defaults to None.\n\n Examples:\n ```python\n from cerbernetix.toolbox.files import PickleFile\n\n # Create a file manager\n file = PickleFile('path/to/filename')\n\n # File can be opened directly as the manager is created\n with PickleFile('path/to/filename') as file:\n data = file.read()\n\n with PickleFile('path/to/filename', create=True) as file:\n file.write(data)\n\n # A file manager can open explicitly a file\n with file.open():\n obj = file.read()\n\n with file.open(create=True):\n file.write(obj)\n\n # It can also be opened implicitly\n with file:\n obj = file.read()\n\n # To create the file while opening implicitly\n with file(create=True):\n file.write(obj)\n\n # The file is also (re)opened when using the iteration protocol\n data = [obj for obj in file]\n ```\n \"\"\"\n super().__init__(\n filename,\n binary=True,\n create=create,\n append=append,\n read=read,\n write=write,\n encoding=None,\n **{key: value for key, value in kwargs.items() if key in FILE_OPEN_PARAMS},\n )\n self._reader_args = {\n key: value for key, value in kwargs.items() if key in PICKLE_READER_PARAMS\n }\n self._writer_args = {\n key: value for key, value in kwargs.items() if key in PICKLE_WRITER_PARAMS\n }\n\n def read_file(self, iterator: bool = False) -> Iterable:\n \"\"\"Reads all the content from the file.\n\n The returned value can be either a list (default) or an iterator (when the iterator\n parameter is True).\n\n Note: If the file was already opened, it is first closed, then opened in read mode.\n\n Args:\n iterator (bool, optional): When True, the function will return an iterator instead of a\n list. Defaults to False.\n\n Raises:\n OSError: If the file cannot be read.\n FileNotFoundError: If the file does not exist.\n\n Returns:\n Iterable: The content read from the file.\n\n Examples:\n ```python\n from cerbernetix.toolbox.files import PickleFile\n\n file = PickleFile('path/to/filename')\n\n # A file can be read all at once\n data = file.read_file()\n\n # An iterator can be returned instead of a list\n for obj in file.read_file(iterator=True):\n print(obj)\n ```\n \"\"\"\n if iterator:\n return self.close()\n\n return list(self)\n\n def write_file(self, data: Iterable) -> int:\n \"\"\"Writes whole content to the file.\n\n Note: If the file was already opened, it is first closed, then opened in write mode.\n\n Args:\n data (Iterable): The content to write to the file.\n\n Raises:\n OSError: If the file cannot be written.\n\n Returns:\n int: The number of bytes written.\n\n Examples:\n ```python\n from cerbernetix.toolbox.files import PickleFile\n\n file = PickleFile('path/to/filename')\n\n # A file can be written all at once\n file.write_file(data)\n ```\n \"\"\"\n size = 0\n with self.open(create=True):\n for row in data:\n size += self.write(row)\n\n return size\n\n def read(self) -> object:\n \"\"\"Reads the next object from the file.\n\n Note: the file must be opened upfront.\n\n Raises:\n ValueError: If the file is not opened.\n OSError: If the file cannot be read.\n\n Returns:\n object: The object loaded from the file, or None if the file is at EOF.\n\n Examples:\n ```python\n from cerbernetix.toolbox.files import PickleFile\n\n file = PickleFile('path/to/filename')\n\n # When calling the read API, the next object in the file is read.\n with file:\n obj1 = file.read()\n obj2 = file.read()\n\n # The objects can also be read using the iteration protocol\n data = [obj for obj in file]\n ```\n \"\"\"\n if self._file is None:\n raise ValueError(\"The file must be opened before reading from it!\")\n\n try:\n return pickle.load(self._file, **self._reader_args)\n except EOFError:\n return None\n\n def write(self, data: object) -> int:\n \"\"\"Writes an object to the file.\n\n Note: the file must be opened upfront.\n\n Args:\n data (object): The object to write to the file.\n\n Raises:\n ValueError: If the file is not opened.\n OSError: If the file cannot be written.\n\n Returns:\n int: The number of bytes written.\n\n Examples:\n ```python\n from cerbernetix.toolbox.files import PickleFile\n\n file = PickleFile('path/to/filename')\n\n # When calling the write API, an object is written to the file.\n with file(create=True):\n file.write(object1)\n file.write(object2)\n ```\n \"\"\"\n if self._file is None:\n raise ValueError(\"The file must be opened before writing to it!\")\n\n return self._file.write(pickle.dumps(data, **self._writer_args))\n\n\ndef read_pickle_file(filename: str, iterator: bool = False, **kwargs) -> Iterable:\n \"\"\"Loads a list of objects from a file.\n\n The returned value can be either a list (default) or an iterator (when the iterator parameter\n is True).\n\n Args:\n filename (str): The path to the file to read.\n iterator (bool, optional): When True, the function will return an iterator instead of a\n list. Defaults to False.\n fix_imports (bool, optional): If fix_imports is true and protocol is less than 3,\n pickle will try to map the new Python 3 names to the old module names used in Python 2,\n so that the pickle data stream is readable with Python 2. Defaults to True.\n encoding (str, optional): Tell pickle how to decode 8-bit string instances pickled by\n Python 2. The encoding can be ‘bytes’ to read these 8-bit string instances as bytes objects.\n Using encoding='latin1' is required for unpickling NumPy arrays and instances of datetime,\n date and time pickled by Python 2. Defaults to ‘ASCII’.\n errors (str, optional): Tell pickle how to decode 8-bit string instances pickled by\n Python 2. Defaults to ‘strict’.\n buffers (optional): If buffers is None (the default), then all data necessary for\n deserialization must be contained in the pickle stream. This means that the buffer_callback\n argument was None when a Pickler was instantiated (or when dump() or dumps() was called). If\n buffers is not None, it should be an iterable of buffer-enabled objects that is consumed\n each time the pickle stream references an out-of-band buffer view. Such buffers have been\n given in order to the buffer_callback of a Pickler object.\n\n Raises:\n OSError: If the file cannot be read.\n FileNotFoundError: If the file does not exist.\n\n Returns:\n Iterable: The list of objects read from the file.\n\n Examples:\n ```python\n from cerbernetix.toolbox.files import read_pickle_file\n\n data = read_pickle_file('path/to/file')\n\n # An iterator can be returned instead of a list\n for obj in read_pickle_file('path/to/file', iterator=True):\n print(obj\n ```\n \"\"\"\n return PickleFile(\n filename,\n **kwargs,\n ).read_file(iterator)\n\n\ndef write_pickle_file(filename: str, data: Iterable, **kwargs) -> int:\n \"\"\"Writes a list of objects to a file.\n\n Args:\n filename (str): The path to the file to write.\n data (Iterable): The list of objects to write to the file.\n protocol (int, optional): Tells the pickle writer to use the given protocol; supported\n protocols are 0 to HIGHEST_PROTOCOL. If a negative number is specified, HIGHEST_PROTOCOL\n is selected. Defaults is DEFAULT_PROTOCOL.\n fix_imports (bool, optional): If fix_imports is true and protocol is less than 3,\n pickle will try to map the new Python 3 names to the old module names used in Python 2,\n so that the pickle data stream is readable with Python 2. Defaults to True.\n buffer_callback (optional): If buffer_callback is None (the default), buffer views are\n serialized into file as part of the pickle stream. If buffer_callback is not None, then\n it can be called any number of times with a buffer view. If the callback returns a false\n value (such as None), the given buffer is out-of-band; otherwise the buffer is\n serialized in-band, i.e. inside the pickle stream. It is an error if buffer_callback is\n not None and protocol is None or smaller than 5. Defaults to None.\n\n Raises:\n OSError: If the file cannot be written.\n\n Returns:\n int: The number of bytes written to the file.\n\n Examples:\n ```python\n from cerbernetix.toolbox.files import write_pickle_file\n\n data = [\n {'date': '2023-09-10', 'value': 42},\n {'date': '2023-09-11', 'value': 24},\n {'date': '2023-09-12', 'value': 44},\n ]\n\n write_pickle_file('path/to/file', data)\n ```\n \"\"\"\n return PickleFile(\n filename,\n **kwargs,\n ).write_file(data)\n","repo_name":"cerbernetix/py-toolbox","sub_path":"src/cerbernetix/toolbox/files/pickle_file.py","file_name":"pickle_file.py","file_ext":"py","file_size_in_byte":15068,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"42305025761","text":"import medcoupling as mc\n\ndef getFieldErrValues (fileName,fieldName,meshName):\n \"\"\"\n Read the error field and returns the max and average values.\n \"\"\"\n lst_dt = mc.GetAllFieldIterations(fileName,fieldName)\n ff_err = mc.ReadFieldCell(fileName,meshName,0,fieldName,lst_dt[-1][0],lst_dt[-1][1])\n myMax=ff_err.getArray().normMax()\n myAv=ff_err.getArray().getAverageValue()\n\n return myMax,myAv\n\nif __name__ == \"__main__\":\n myMax,myAv=getFieldErrValues(\"fields.med\",\"ERROR_ELEM_ELEM_DOM\",\"DOM\")\n ff = open('Error_values.txt', 'wb')\n ff.write(\"%.4g %.4g\".encode() %(myMax,myAv))\n ff.close()\n","repo_name":"cea-trust-platform/trust-code","sub_path":"Validation/Rapports_automatiques/Verification/Verification_codage/diffusion_anisotrope_VEF/src/TC1/get_max_error.py","file_name":"get_max_error.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"40"} +{"seq_id":"11898293248","text":"# ***For educational purposes only***\n\nfrom sys import exit\nfrom csv import DictReader\n\n\n# Load CSV source file\ndef load_people(path: str = 's.csv') -> dict or None:\n temp: dict = {}\n # Catch invalid input file\n try:\n with open(path) as f:\n reader = DictReader(f)\n for person in reader:\n temp[person['name']] = int(person['age'])\n\n # Return the populated dictionary of people\n return temp\n\n # Return None if not found\n except FileNotFoundError:\n return None\n\n\npeople: dict = load_people()\n\n# Check if the dict is not empty\nif not people:\n print('No people found.')\n exit(1)\n\n\n# Define a decorator that will check whether the person is an adult\n# If so, return the function\n# If not, return a message\ndef check_adult(func):\n def wrapper(*args, **kvargs):\n name: str = args[0]\n if people[name] >= 18:\n return func(*args, **kvargs)\n print(f'You have to wait {18 - people[name]} years to be an adult.')\n return wrapper\n\n\n@check_adult # Assigning the decorator\ndef grab_beer(name: str):\n print(f'Have a beer with us, {name}!')\n\n\n# Iterate over all people\nfor name in people:\n grab_beer(name)\n\n","repo_name":"michalspano/.py","sub_path":"src/practise/decorator.py","file_name":"decorator.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"18491997128","text":"import os\n\nimport cirq\nimport recirq\nfrom recirq.qaoa.circuit_structure import BadlyStructuredCircuitError, \\\n find_circuit_structure_violations\nfrom recirq.qaoa.classical_angle_optimization import OptimizationResult\nfrom recirq.qaoa.experiments.angle_precomputation_tasks import AnglePrecomputationTask, \\\n DEFAULT_BASE_DIR as DEFAULT_PRECOMPUTATION_BASE_DIR\nfrom recirq.qaoa.experiments.problem_generation_tasks import \\\n DEFAULT_BASE_DIR as DEFAULT_PROBLEM_GENERATION_BASE_DIR\nfrom recirq.qaoa.gates_and_compilation import compile_to_non_negligible\nfrom recirq.qaoa.placement import place_line_on_device\nfrom recirq.qaoa.problem_circuits import get_compiled_hardware_grid_circuit, \\\n get_compiled_sk_model_circuit, get_compiled_3_regular_maxcut_circuit\nfrom recirq.qaoa.problems import ProblemT, HardwareGridProblem, SKProblem, ThreeRegularProblem\n\nEXPERIMENT_NAME = 'qaoa-precomputed'\nDEFAULT_BASE_DIR = os.path.expanduser(f'~/cirq-results/{EXPERIMENT_NAME}')\n\n\ndef _abbrev_n_shots(n_shots: int) -> str:\n \"\"\"Shorter n_shots component of a filename\"\"\"\n if n_shots % 1000 == 0:\n return f'{n_shots // 1000}k'\n return str(n_shots)\n\n\n@recirq.json_serializable_dataclass(namespace='recirq.qaoa',\n registry=recirq.Registry,\n frozen=True)\nclass PrecomputedDataCollectionTask:\n dataset_id: str\n precomputation_task: AnglePrecomputationTask\n\n device_name: str\n n_shots: int\n structured: bool = False\n echoed: bool = False\n\n @property\n def fn(self):\n n_shots = _abbrev_n_shots(n_shots=self.n_shots)\n generation_task = self.precomputation_task.generation_task\n if self.echoed:\n assert self.structured, 'must be structured'\n struc_echo = '_echoed'\n elif self.structured:\n struc_echo = '_structured'\n else:\n struc_echo = ''\n\n return (f'{self.dataset_id}/'\n f'{self.device_name}/'\n f'from-{generation_task.fn}/'\n f'p-{self.precomputation_task.p}_{n_shots}{struc_echo}')\n\n\nasync def collect_data(task: PrecomputedDataCollectionTask,\n base_dir=None,\n problem_generation_base_dir=None,\n precomputation_base_dir=None,\n ):\n \"\"\"Collect and save data for the experiment specified by params.\n\n The associated problem generation data must already exist.\n \"\"\"\n if base_dir is None:\n base_dir = DEFAULT_BASE_DIR\n\n if problem_generation_base_dir is None:\n problem_generation_base_dir = DEFAULT_PROBLEM_GENERATION_BASE_DIR\n\n if precomputation_base_dir is None:\n precomputation_base_dir = DEFAULT_PRECOMPUTATION_BASE_DIR\n\n if recirq.exists(task, base_dir=base_dir):\n print(f\"{task.fn} already exists. Skipping.\")\n return\n\n precompute_task = task.precomputation_task\n generation_task = precompute_task.generation_task\n\n problem = recirq.load(generation_task, base_dir=problem_generation_base_dir)[\n 'problem'] # type: ProblemT\n optimum = recirq.load(precompute_task, base_dir=precomputation_base_dir)[\n 'optimum'] # type: OptimizationResult\n sampler = recirq.get_sampler_by_name(device_name=task.device_name)\n device = recirq.get_device_obj_by_name(device_name=task.device_name)\n\n try:\n if isinstance(problem, HardwareGridProblem):\n initial_qubits = [cirq.GridQubit(r, c) for r, c in problem.coordinates]\n circuit, final_qubits = get_compiled_hardware_grid_circuit(\n problem=problem,\n qubits=initial_qubits,\n gammas=optimum.gammas,\n betas=optimum.betas,\n non_negligible=False)\n elif isinstance(problem, SKProblem):\n initial_qubits = place_line_on_device(\n device_name=task.device_name,\n n=problem.graph.number_of_nodes(),\n line_placement_strategy='mixed')\n circuit, final_qubits = get_compiled_sk_model_circuit(\n problem=problem,\n qubits=initial_qubits,\n gammas=optimum.gammas,\n betas=optimum.betas,\n non_negligible=False)\n elif isinstance(problem, ThreeRegularProblem):\n initial_qubits, circuit, final_qubits = get_compiled_3_regular_maxcut_circuit(\n problem=problem,\n device=device,\n gammas=optimum.gammas,\n betas=optimum.betas)\n else:\n raise ValueError(\"Unknown problem: {}\".format(problem))\n except BadlyStructuredCircuitError:\n print(\"!!!! Badly structured circuit: {}\".format(task))\n # TODO https://github.com/quantumlib/Cirq/issues/2553\n return\n\n if not task.structured:\n # Left align\n circuit = compile_to_non_negligible(circuit)\n circuit = cirq.Circuit(circuit.all_operations())\n\n if task.echoed:\n assert task.structured\n raise NotImplementedError(\"To be implemented in follow-up PR\")\n\n violation_indices = find_circuit_structure_violations(circuit)\n circuit.program_id = task.fn\n result = await sampler.run_async(program=circuit,\n repetitions=task.n_shots)\n bitstrings = result.measurements['z']\n\n recirq.save(task=task, data={\n 'bitstrings': recirq.BitArray(bitstrings),\n 'qubits': initial_qubits,\n 'final_qubits': final_qubits,\n 'circuit': circuit,\n 'violation_indices': violation_indices,\n }, base_dir=base_dir)\n print(f\"{task.fn} complete.\")\n","repo_name":"quantumlib/ReCirq","sub_path":"recirq/qaoa/experiments/precomputed_execution_tasks.py","file_name":"precomputed_execution_tasks.py","file_ext":"py","file_size_in_byte":5670,"program_lang":"python","lang":"en","doc_type":"code","stars":249,"dataset":"github-code","pt":"40"} +{"seq_id":"86642922662","text":"from mpl_toolkits.axes_grid1 import host_subplot\nimport mpl_toolkits.axisartist as AA\nimport matplotlib.pyplot as plt\n\n\nclass PlotUtils:\n\n @staticmethod\n def plot_lines(xs, ys, labels):\n if len(labels) != len(ys):\n raise Exception(\"Different sizes in params\")\n\n for x, y, label in zip(xs, ys, labels):\n plt.plot(x, y, label=label)\n\n plt.show()\n\n @staticmethod\n def different_axis(episodes, rewards, sample_size, epsilon):\n host = host_subplot(111, axes_class=AA.Axes)\n\n plt.subplots_adjust(right=0.75)\n\n par1 = host.twinx()\n\n par1.axis[\"right\"].toggle(all=True)\n\n host.set_xlim(0, len(episodes))\n host.set_ylim(0, 1)\n\n host.set_xlabel(\"Episodes\")\n host.set_ylabel(\"Rewards\")\n par1.set_ylabel(\"Sample Size\")\n\n p1, = host.plot(episodes, rewards, label=\"Rewards\")\n p2, = par1.plot(episodes, sample_size, label=\"Sample Size\")\n\n par1.set_ylim(1, 350)\n\n host.legend()\n\n host.axis[\"left\"].label.set_color(p1.get_color())\n par1.axis[\"right\"].label.set_color(p2.get_color())\n\n plt.draw()\n plt.show()\n","repo_name":"EduardoSantos7/RLSampler","sub_path":"utils/PlotUtils.py","file_name":"PlotUtils.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"44967423581","text":"from FUTpuppeteer import info, database, actions\r\nfrom FUTpuppeteer.misc import multi_log, Global\r\nfrom . import retry_decorator, check_sleep\r\nfrom selenium.common.exceptions import NoSuchElementException, TimeoutException, ElementNotVisibleException, WebDriverException\r\n\r\n@retry_decorator\r\ndef market_monitor(obj):\r\n def check_transfer_targets(return_data):\r\n if obj.location != 'transfer_targets':\r\n obj.go_to('transfer_targets')\r\n multi_log(obj, 'Waiting on last bid to expire')\r\n while True:\r\n max_expire = 0\r\n watched_items = obj.__get_items__(p_element='../..', p_type='xpath', gp_element=\"//*[contains(text(), 'Watched Items')]\", gp_type='xpath', get_price=False)\r\n if len(watched_items) == 0:\r\n break\r\n for item in watched_items:\r\n if item['time_left'] > max_expire:\r\n max_expire = item['time_left']\r\n obj.keep_alive(max_expire + 5)\r\n expired_bids = obj.__get_items__(p_element='../..', p_type='xpath', gp_element=\"//*[contains(text(), 'Expired Items')]\", gp_type='xpath', get_price=False)\r\n expired = {}\r\n for expired_bid in expired_bids:\r\n if expired_bid['asset_id'] in settings['players']:\r\n if expired_bid['asset_id'] not in list(expired.keys()):\r\n expired[expired_bid['asset_id']] = {\r\n 'bid_amounts': 0,\r\n 'num_results': 0\r\n }\r\n expired[expired_bid['asset_id']]['bid_amounts'] += expired_bid['current_bid']\r\n expired[expired_bid['asset_id']]['num_results'] += 1\r\n for asset, data in expired.items():\r\n return_data[asset]['average_bid'] = info.round_down(data['bid_amounts'] / data['num_results'], rounding)\r\n for return_asset, return_info in return_data.items():\r\n name = info.get_player_info(return_asset, False)['name']\r\n multi_log(obj, '{}\\'s Average Bid: {}'.format(name, return_info['average_bid']))\r\n database.save_market_data(obj, name, return_info['asset_id'], return_info['average_bid'], return_info['minimum_bin'])\r\n obj.clear_expired()\r\n return {}, 0\r\n\r\n check_sleep(obj)\r\n obj.current_strategy = 'Market Monitor'\r\n settings = obj.strategy_settings['market_monitor']\r\n multi_log(obj, 'Monitoring Market...', level='title')\r\n obj.clear_expired()\r\n cumulative_bids = 0\r\n return_data = {}\r\n for player in settings['players']:\r\n return_data[player] = {\r\n 'asset_id': player,\r\n 'minimum_bin': 0,\r\n 'average_bid': 0\r\n }\r\n num_results = 0\r\n total_bins = 0\r\n player_info = info.get_player_info(player, include_futbin_price=True)\r\n name = player_info['name']\r\n futbin_price = player_info['futbin_price']\r\n tier = info.get_tier(futbin_price)\r\n rounding = Global.rounding_tiers[tier]\r\n max_bin = futbin_price - (rounding * 2)\r\n search_criteria = {\r\n 'search_type': 'Players',\r\n 'player': player,\r\n }\r\n multi_log(obj, 'Getting market data for {}. Futbin price: {}'.format(name, futbin_price))\r\n # Get bin info\r\n bin_with_results = []\r\n while num_results < settings['min_results']:\r\n bin_results = actions.search(obj=obj, max_bin=max_bin, **search_criteria)\r\n if len(bin_results) > settings['max_results']:\r\n if total_bins == 0:\r\n min_bin = 999999\r\n for bin_result in bin_results:\r\n if bin_result['buy_now_price'] < min_bin:\r\n min_bin = bin_result['buy_now_price'] - Global.rounding_tiers[tier]\r\n max_bin = min_bin\r\n continue\r\n else:\r\n for bin_result in bin_results:\r\n if bin_result['buy_now_price'] not in bin_with_results:\r\n total_bins += bin_result['buy_now_price']\r\n num_results += 1\r\n if len(bin_results) > 0:\r\n bin_with_results.append(max_bin)\r\n else:\r\n for bin_result in bin_results:\r\n if bin_result['buy_now_price'] not in bin_with_results:\r\n total_bins += bin_result['buy_now_price']\r\n num_results += 1\r\n if len(bin_results) > 0:\r\n bin_with_results.append(max_bin)\r\n max_bin += rounding\r\n minimum_bin = info.round_down(total_bins / num_results, rounding)\r\n multi_log(obj, '{}\\'s Average Minimum BIN: {}'.format(name, minimum_bin))\r\n return_data[player]['minimum_bin'] = minimum_bin\r\n # Get bid info\r\n max_buy = max(minimum_bin + (5 * rounding), futbin_price + (3 * rounding))\r\n num_results = 0\r\n bid_results = actions.search(obj=obj, max_buy=max_buy, **search_criteria)\r\n for bid_result in bid_results:\r\n if bid_result['time_left'] <= 300 and (bid_result['current_bid'] != bid_result['start_price'] or bid_result['current_bid'] <=\r\n (futbin_price - (5 * rounding))) and num_results < settings['min_results']:\r\n try:\r\n bid_result['element'].click()\r\n except WebDriverException:\r\n try:\r\n obj.__click_xpath__(\".//*[contains(text(), 'OK')]\")\r\n except TimeoutException:\r\n pass\r\n check_transfer_targets(return_data)\r\n obj.keep_alive(Global.micro_min)\r\n side_panel = obj.__get_class__('DetailView', as_list=False)\r\n try:\r\n side_panel.find_element_by_class_name('watch').click()\r\n num_results += 1\r\n cumulative_bids += 1\r\n except (ElementNotVisibleException, TimeoutException, NoSuchElementException):\r\n pass\r\n except WebDriverException:\r\n obj.__click_xpath__(\".//*[contains(text(), 'OK')]\")\r\n check_transfer_targets(return_data)\r\n elif num_results >= settings['min_results']:\r\n break\r\n check_transfer_targets(return_data)\r\n\r\n\r\n\r\n","repo_name":"mdrichardson/FUTpuppeteer","sub_path":"FUTpuppeteer/strategies/market_monitor.py","file_name":"market_monitor.py","file_ext":"py","file_size_in_byte":6450,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"40"} +{"seq_id":"24936209464","text":"from fastapi import FastAPI\nfrom pydantic import BaseModel\nfrom datetime import date\n\napp = FastAPI()\n\n\nclass User(BaseModel):\n name: str\n surname: str\n age: int\n registration_date: date\n\n class Config:\n orm_mode = True\n\n\n@app.post(\"/user/validate\")\ndef validation(json_file: User):\n return f'Will add user: {json_file.name} {json_file.surname} with age {json_file.age}'\n","repo_name":"antonio-st/Start_ML","sub_path":"modul_1_Python_Application_Development/09_Backend-разработка_FastAPI_для_backend-сервера/homework/06_07/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"3690721205","text":"def split(arr, low, high):\n \"\"\"\n 单指针遍历法\n \"\"\"\n # i 指向比较元素的期望位置\n i = low\n # 将该数组第一个元素设置为比较元素\n x = arr[i]\n # 从数组的第二个元素起开始遍历,若找到的元素大于比较元素,则跳过\n j = low + 1\n while j <= high:\n # 若找到了小于比较元素的数,则将其与前面较大的数进行交换\n if arr[j] <= x:\n i += 1\n arr[i], arr[j] = arr[j], arr[i]\n j += 1\n\n # 将比较元素交换到期望位置\n arr[low], arr[i] = arr[i], arr[low]\n return i\n\n\ndef partition(arr, low, high):\n \"\"\"\n 双指针遍历法\n \"\"\"\n # 将该数组第一个元素设置为比较元素\n x = arr[low]\n # i 指向数组头的指针\n # j 指向数组尾的指针\n i, j = low, high\n\n while i < j:\n # 从右至左找到第一个小于比较元素的数\n while i < j and arr[j] >= x:\n j -= 1\n # 从左至右找到第一个大于比较元素的数\n while i < j and arr[i] <= x:\n i += 1\n\n # NOTE 这里的 j - 1 与 i + 1 的顺序不可以调换。如果调换了顺序,i会走过头,以至于将后面较大的元素交换到数组开头\n\n # 将大数与小数交换\n if i != j:\n arr[i], arr[j] = arr[j], arr[i]\n\n # 将比较元素交换到期望位置\n arr[low], arr[i] = arr[i], arr[low]\n return i\n\n\ndef quick_sort(arr, low, high):\n if low < high:\n # i = partition(arr, low, high)\n i = split(arr, low, high)\n quick_sort(arr, low, i - 1)\n quick_sort(arr, i + 1, high)\n\n\ndef quick_sort_v2(array):\n if len(array) < 2:\n return array\n\n mid = array[0]\n\n left_array = list(filter(lambda d: d < mid, array))\n right_array = list(filter(lambda d: d > mid, array))\n\n left_array = quick_sort_v2(left_array)\n right_array = quick_sort_v2(right_array)\n return left_array + [mid] * (len(array) - len(left_array) - len(right_array)) + right_array\n\n\nif __name__ == '__main__':\n array_list = [5, 7, 1, 6, 4, 8, 3, 2]\n quick_sort(array_list, 0, 7)\n print(array_list)\n\n print(quick_sort_v2(array_list))\n","repo_name":"windVare/algorithm","sub_path":"模版/快排.py","file_name":"快排.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"74425037880","text":"import speech_recognition\nimport pyttsx3 as tts\nfrom googleapiclient.discovery import build\nimport pickle\nfrom datetime import datetime, timedelta\nimport datefinder\nimport dateutil.parser\n\n# connect with google API service\ncredentials = pickle.load(open(\"creds/token.pkl\", \"rb\"))\nservice = build(\"calendar\", \"v3\", credentials=credentials)\n\n# speech recognizer\nrecognizer = speech_recognition.Recognizer()\n\n# speaker\nspeaker = tts.init()\nspeaker.setProperty('rate', 110)\n\n# greeting\ndef hello():\n speaker.say(\"Hello Sir, what can I do for you?\")\n speaker.runAndWait()\n\n# function to create a note\ndef create_note():\n global recognizer\n\n speaker.say(\"what do you want to write on your note?\")\n speaker.runAndWait()\n\n done = False\n \n while not done:\n try:\n with speech_recognition.Microphone() as mic:\n # log\n print(\"What do you want to write on your note?\")\n print(\"Speak\")\n # capture the spoken command\n audio = recognizer.listen(mic)\n # translate into text\n note = recognizer.recognize_google(audio)\n note = note.lower()\n # print the note as a log\n print(note)\n speaker.say(\"Choose a filename!\")\n speaker.runAndWait()\n\n # log\n print(\"What is your file name?\")\n print(\"speak\")\n # naming the note\n audio = recognizer.listen(mic)\n filename = recognizer.recognize_google(audio)\n filename = filename.lower()\n print(filename)\n # saving the note\n with open(f\"note/{filename}\", \"w\") as f:\n f.write(note)\n \n # the function finish here\n done = True\n speaker.say(f\"I succesfully created the {filename} note\")\n speaker.runAndWait()\n\n except speech_recognition.UnknownValueError:\n print(\"try again\")\n recognizer = speech_recognition.Recognizer()\n speaker.say(\"I don't understand, please try again!\")\n speaker.runAndWait()\n\n# funtions to create an event on google calendar\ndef _create_event(start_time_str, summary, duration=1, description=None, location=None):\n matches = list(datefinder.find_dates(start_time_str))\n if len(matches):\n start_time = matches[0]\n end_time = start_time + timedelta(hours=duration)\n \n event = {\n 'summary': summary,\n 'location': location,\n 'description': description,\n 'start': {\n 'dateTime': start_time.strftime(\"%Y-%m-%dT%H:%M:%S\"),\n 'timeZone': 'Asia/Bangkok',\n },\n 'end': {\n 'dateTime': end_time.strftime(\"%Y-%m-%dT%H:%M:%S\"),\n 'timeZone': 'Asia/Bangkok',\n },\n 'reminders': {\n 'useDefault': False,\n 'overrides': [\n {'method': 'email', 'minutes': 24 * 60},\n {'method': 'popup', 'minutes': 10},\n ],\n },\n }\n return service.events().insert(calendarId='primary', body=event).execute()\n\ndef add_event():\n global recognizer\n\n speaker.say(\"What is the event name?\")\n speaker.runAndWait()\n\n done = False\n \n while not done:\n try:\n with speech_recognition.Microphone() as mic:\n # log\n print(\"What is the event's name?\")\n print(\"speak\")\n audio = recognizer.listen(mic)\n\n summary = recognizer.recognize_google(audio)\n summary = summary.lower()\n print(summary)\n speaker.say(\"When will the event started?\")\n speaker.runAndWait()\n\n # log\n print(\"When will the event started?\")\n print(\"speak\")\n audio = recognizer.listen(mic)\n start = recognizer.recognize_google(audio)\n print(start)\n speaker.say(f\"adding {summary} on {start} to google calendar\")\n\n try:\n _create_event(start, summary)\n done = True\n speaker.say(f\"I succesfully created the event on Google Calendar\")\n speaker.runAndWait()\n except:\n recognizer = speech_recognition.Recognizer()\n print(\"try again\")\n speaker.say(\"Can not process your request, please try again\")\n speaker.runAndWait()\n\n except speech_recognition.UnknownValueError:\n recognizer = speech_recognition.Recognizer()\n print(\"try again\")\n speaker.say(\"I don't understand, please try again!\")\n speaker.runAndWait()\n\n# function to show agenda / events on google calendar\ndef show_agenda():\n speaker.say(\"The items on your google calendar agenda are the following\")\n now = datetime.utcnow().isoformat() + 'Z'\n end = (datetime.utcnow() + timedelta(days=1)).isoformat() + 'Z'\n events_result = service.events().list(calendarId='primary', timeMin=now,timeMax=end,\n maxResults=10, singleEvents=True,\n orderBy='startTime').execute()\n events = events_result.get('items', [])\n if not events:\n speaker.say('No upcoming events found.')\n for num, event in enumerate(events):\n start = event['start'].get('dateTime', event['start'].get('date'))\n parsed_start = dateutil.parser.parse(start)\n end = event['end'].get('dateTime', event['end'].get('date'))\n parsed_end = dateutil.parser.parse(end)\n speaker.say(f\"{num+1} {event['summary']} on {parsed_start.strftime('%#I %p')} until {parsed_end.strftime('%#I %p')}\")\n speaker.runAndWait()\n\n\n\n\n\n","repo_name":"yosiaazarya/calendar_jarvis","sub_path":"engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":5949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"9215120556","text":"import azure.functions as func\nimport requests\nimport json\n\ndef main(req: func.HttpRequest) -> func.HttpResponse:\n # Extract the latitude and longitude from the query parameters\n latitude = req.params.get('latitude')\n longitude = req.params.get('longitude')\n\n if not latitude or not longitude:\n return func.HttpResponse(\n \"Please pass both latitude and longitude in the query string\",\n status_code=400\n )\n\n # Call the Open-Meteo API\n weather_url = f\"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&hourly=temperature_2m\"\n response = requests.get(weather_url)\n data = response.json()\n\n if response.status_code == 200:\n return func.HttpResponse(json.dumps(data), mimetype=\"application/json\")\n else:\n return func.HttpResponse(\n \"Failed to fetch the weather data\",\n status_code=response.status_code\n )\n","repo_name":"baltas99/serverlessfuntions","sub_path":"GetWeather/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"31959371837","text":"from collections import deque\nN = int(input())\n\ncow = deque()\n\ntop = -1\ncnt = 0\nfor i in range(N):\n val = int(input())\n if top == -1:\n cow.append(val)\n top += 1\n else:\n if cow[top] > val:\n cow.append(val)\n cnt += len(cow) - 1\n top += 1\n else:\n #print(f'cow[top]:{cow[top]} val:{val}')\n while cow[top] <= val and top != -1:\n cow.pop()\n top -= 1\n #print(f'top:{top}')\n if top == -1:\n break\n cow.append(val)\n if top != -1:\n cnt += len(cow) - 1\n top += 1\n #print(cow, top)\n #print(f'cnt:{cnt}')\nprint(cnt)\n","repo_name":"gkdbssla97/Codeup","sub_path":"3103_소들의헤어스타일.py","file_name":"3103_소들의헤어스타일.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"10850064812","text":"import cv2\nimport numpy as np\n\n\ndef bitfield(n):\n return [int(digit) for digit in bin(n)[2:]]\n\n\ndef gerar_mensagem(mensagem):\n lista = []\n for m in mensagem:\n val = ord(m)\n bits = bitfield(val)\n\n if len(bits) < 8:\n for a in range(8 - len(bits)):\n bits.insert(0, 0)\n lista.append(bits)\n arr = np.array(lista)\n arr = arr.flatten()\n return arr\n\n\ndef converter_mensagem(saida):\n bits = np.array(saida)\n mensagem_out = ''\n bits = bits.reshape((int(len(saida) / 8), 8))\n for b in bits:\n sum = 0\n for i in range(8):\n sum += b[i] * (2 ** (7 - i))\n mensagem_out += chr(sum)\n return mensagem_out\n\n\ntexto = \"A\"\narrayBits = gerar_mensagem(texto)\nprint(texto)\nprint(arrayBits)\ntextoTraduzido = converter_mensagem(arrayBits)\nprint(textoTraduzido)\n","repo_name":"fetrentin7/Learning-Python","sub_path":"opencv/trabalhom2.py","file_name":"trabalhom2.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"35613416731","text":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\n\n# load csv data file\ndef load_csv(root='./data/train.csv', mode=None):\n if mode == 'test':\n df = pd.read_csv(root)\n X_train = path_preproceesing(df.reset_index())\n # print(\"@\"*200)\n # print(X_train)\n return X_train\n\n df = pd.read_csv(root)\n\n X_train, X_val, Y_train, Y_val = train_test_split(df, df['artist'].values, test_size=0.2)\n print('Number of posters for training: ', len(X_train))\n print('Number of posters for validation: ', len(X_val))\n\n X_train = path_preproceesing(X_train.reset_index())\n X_val = path_preproceesing(X_val.reset_index())\n # Y_train = path_preproceesing(Y_train)\n # Y_val = path_preproceesing(Y_val)\n print(X_train)\n print(X_val)\n return X_train, X_val, Y_train, Y_val\n\n# data image path preprocessing\ndef path_preproceesing(data):\n data['img_path'] = ['D:\\\\dacon_artist\\\\data\\\\' + path[2:] for path in data['img_path']]\n return data\n\n# load classes from csv\ndef load_classes_csv(root='./data/artists_info.csv'):\n df = pd.read_csv(root)\n classes = df['name']\n return classes","repo_name":"MonoHaru/Artist_Classification","sub_path":"utils/csv.py","file_name":"csv.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"31727084960","text":"import room\nfrom . import go, get, drop, common\n\ndef to(s: list[str], r: list[room.Room], pos: int, inventory: list):\n cmds = {\n 'go': go.Go(s, r[pos]),\n 'get': get.Get(s, r[pos], inventory),\n \"drop\": drop.Drop(s, r[pos], inventory),\n 'look': common.Look(r[pos]),\n 'inventory': common.Inventory(inventory),\n \"quit\": common.Quit(),\n }\n cmds[\"help\"] = common.Help(cmds.values())\n return getAbbr(s, cmds)\n\ndef getAbbr(s: list[str], cmds):\n prefix = s[0]\n arr = []\n [arr.append(cmd) for cmd in cmds if cmd.startswith(prefix)]\n if len(arr) == 0: return room.CURRENT # do nothing when user inputs wrong cmds\n elif len(arr) == 1:\n if arr[0] in cmds:\n return cmds[arr[0]].do()\n return room.CURRENT\n return room.CURRENT","repo_name":"chihchaow4456/SIT_CS515_Adventure","sub_path":"verbs/verb.py","file_name":"verb.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"13716846237","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django.shortcuts import render\nfrom django.views.generic.base import View\nfrom .models import Laboratory, Device\nfrom .forms import LabForm, DeviceForm\nfrom django.contrib.auth.decorators import login_required\n\n@login_required(login_url='login')\ndef labs_view(request):\n labs = Laboratory.objects.all()\n return render(request, 'labs.html', {'labs': labs})\n\n\n@login_required(login_url='login')\ndef lab_info(request, lab_id):\n lab = Laboratory.objects.get(pk=lab_id)\n devices = Device.objects.all()\n return render(request, 'lab_info.html', {'lab': lab,\n 'devices': devices\n }\n )\n\n\n@login_required(login_url='login')\ndef lab_edit(request, lab_id): # 此函数承担两个任务,添加课目与修改课目,关键看id是否为0\n if str(lab_id) == '0':\n return render(request, 'lab_edit.html')\n else:\n lab = Laboratory.objects.get(pk=lab_id)\n return render(request, 'lab_edit.html', {'lab': lab})\n\n\n\ndef lab_edit_action(request):\n lab_form = LabForm(request.POST)#验证表单格式\n if lab_form.is_valid():\n lab_id = request.POST.get('lab_id', '0') # get方法的第二个参数是默认值\n if lab_id == '0':\n name = request.POST.get('name', '')\n locate = request.POST.get('locate', '')\n admin = request.POST.get('admin', '')\n detail = request.POST.get('detail', '')\n lab = Laboratory(name=name, locate=locate, admin=admin, detail=detail)\n lab.save()\n labs = Laboratory.objects.all()\n return render(request, 'labs.html', {'labs': labs})\n else:\n lab = Laboratory.objects.get(pk=lab_id)\n lab.name = request.POST.get('name', '')\n lab.locate = request.POST.get('locate', '')\n lab.admin = request.POST.get('admin', '')\n lab.detail = request.POST.get('detail', '')\n lab.save()\n return render(request, 'lab_info.html', {'lab': lab,\n }\n )\n else:\n lab_id = request.POST.get('lab_id', '0') # get方法的第二个参数是默认值\n lab = Laboratory.objects.get(pk=lab_id)\n return render(request, '.html', {'lab': lab\n }\n )\n\n\ndef lab_delete(request, lab_id):\n lab = Laboratory.objects.get(pk=lab_id)\n lab.delete()\n labs = Laboratory.objects.all()\n return render(request, 'labs.html', {'labs': labs})\n\n","repo_name":"yk2012985/my_lab2","sub_path":"my_lab/apps/measure/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2677,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"27813947339","text":"from shapes import *\n\n# Define colours\ncakesponge, cherry, cakeholder = \"#C77F30\", \"#ED1D24\", \"#E688B1\"\n\n# Define the paper\npaper = Paper()\n\n# Make a list to store shapes\nshapes = []\n\n# Define shapes (lowest layer first)\nshapes.append(Rectangle(600, 600, 0, 0, \"black\")) # Background\nshapes.append(Oval(400, 400, 100, 100, cakesponge)) # Main cake bit\nshapes.append(Oval(80, 80, 260, 40, cherry)) # Cherry\n\n# Draw them all then render it\nfor shape in shapes:\n shape.draw()\n\npaper.display()","repo_name":"TheJoeCoder/small-scripts","sub_path":"oop-course/shapes/cool_drawing.py","file_name":"cool_drawing.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"6627168317","text":"from math import ceil, floor\r\n\r\nmagnolias = int(input())\r\nhyacinths = int(input())\r\nroses = int(input())\r\ncactuses = int(input())\r\ngift_price = float(input())\r\n\r\nsum = (magnolias * 3.25) + (hyacinths * 4) + (roses * 3.5) + (cactuses * 8)\r\ntaxes = 0.05 * sum\r\nnet = sum - taxes\r\n\r\nif net >= gift_price:\r\n needed_money = floor(net - gift_price)\r\n print(f\"She is left with {needed_money} leva.\")\r\nelse:\r\n left_money = ceil(gift_price - net)\r\n print(f\"She will have to borrow {left_money} leva.\")\r\n\r\n","repo_name":"radoslav-petkov/SoftUni---Basic---Python---2021","sub_path":"2.More Exercises/2.Conditional Statements/flower_shop.py","file_name":"flower_shop.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"70068051962","text":"import socket\nimport sys\nfrom datetime import datetime\nfrom os import path\nfrom shutil import copy, copytree\nimport imghdr\n\nimport cv2\nimport qrcode\nfrom PyQt5 import QtMultimedia, uic\nfrom PyQt5.QtCore import QThread, QTimer, pyqtSignal\nfrom PyQt5.QtGui import QImage, QPixmap, QTextCursor\nfrom PyQt5.QtWidgets import (QAction, QActionGroup, QApplication, QMainWindow,\n QMessageBox)\n\nfrom config_parser import UI, File, Param, Path\nfrom crack_detector import create_model, finetune, predict, set_gpu\nfrom cv2_helper import make_overlay, change_color\nfrom data_manager import split_train_valid\nfrom feature_matcher import apply_homography, make_homography\nfrom file_manager import (clean_tree, get_all_files, open_file_dialog,\n remove_tree)\nfrom gui_helper import (TaskTime, assign_shortcut, delayed_function,\n parse_window_size, show_window)\n\nfrom pyftpdlib.authorizers import DummyAuthorizer\nfrom pyftpdlib.handlers import FTPHandler\nfrom pyftpdlib.servers import FTPServer\n\n\n_client_ip = None\n_section = 0\n_section_max = 1\n\n\nclass __MainWindow(QMainWindow):\n ''' Main crack manager window. '''\n\n def __init__(self, parent=None):\n super().__init__(parent)\n\n # Load UI\n self.ui = uic.loadUi(File.UI, self)\n self.setWindowTitle(f\"{UI.TITLE} {UI.VERSION}\")\n self.setGeometry(*parse_window_size(UI.WINDOW))\n assign_shortcut(self)\n\n # Apply configs to UI\n self.ui.toggleAutoCapture.setChecked(UI.AUTO_CAPTURE)\n self.ui.toggleAutoMatch.setChecked(UI.AUTO_MATCH)\n self.ui.toggleAutoDetect.setChecked(UI.AUTO_DETECT)\n self.ui.toggleAutoApply.setChecked(UI.AUTO_APPLY)\n self.ui.toggleAutoSend.setChecked(UI.AUTO_SEND)\n\n # Set class variables\n self.camera = {'id': -1, 'name': \"\", 'capture': None}\n self.last_used = {'capture_as_crack': 0, 'capture_as_match': 0, 'holo_as_match': 0,\n 'crack_as_result': 0, 'match_as_result': 0}\n self.homography_info = None\n\n # Initiallize camera\n self.preview_timer = QTimer(self, interval=UI.TIME_UPDATE)\n self.preview_timer.timeout.connect(self.update_image)\n self.register_cameras()\n self.set_camera()\n\n # Setup segmentation network\n set_gpu()\n self.model = create_model(Param.MODEL, Param.BACKBONE, Param.ACTIVATION)\n self.register_weights()\n\n # Init section combo\n self.ui.comboSections.clear()\n self.ui.comboSections.addItem('0')\n self.sectionSelected(_section)\n\n def showAbout(self):\n ''' Show application authos info. '''\n\n QMessageBox.information(self, \"About\", UI.ABOUT, QMessageBox.Close)\n\n # region Camera\n\n def register_cameras(self):\n ''' Register available camera devices to menu item. '''\n\n videoDevicesGroup = QActionGroup(self)\n videoDevicesGroup.setExclusive(True)\n\n for i, deviceName in enumerate(QtMultimedia.QCamera.availableDevices()):\n description = QtMultimedia.QCamera.deviceDescription(deviceName)\n videoDeviceAction = QAction(description, videoDevicesGroup)\n videoDeviceAction.setCheckable(True)\n videoDeviceAction.setData(i)\n if self.camera['id'] == -1:\n self.camera['id'] = i\n self.camera['name'] = description\n videoDeviceAction.setChecked(True)\n self.ui.menuDevices.addAction(videoDeviceAction)\n\n videoDevicesGroup.triggered.connect(self.set_camera)\n\n def set_camera(self, action=None):\n ''' Prepare camera for capture. '''\n\n if action:\n self.camera['id'] = action.data()\n self.camera['name'] = action.text()\n\n self.togglePreview(True)\n\n def togglePreview(self, toggle):\n ''' Toggle camera preview. '''\n\n self.ui.buttonCapture.setEnabled(toggle)\n self.ui.toggleButtonPreview.setChecked(toggle)\n self.toggleButtonPreview.setText(\"Stop Camera\" if toggle else \"Start Camera\")\n\n if toggle:\n self.camera['capture'] = cv2.VideoCapture(self.camera['id'])\n self.preview_timer.start()\n\n print(\"Camera started: \" + self.camera['name'])\n else:\n if self.camera['capture']:\n self.camera['capture'].release()\n self.camera['capture'] = None\n self.preview_timer.stop()\n\n print(\"Camera stopped: \" + self.camera['name'])\n\n def update_image(self):\n ''' Called when frame update. '''\n\n success, img = self.camera['capture'].read()\n if success:\n qformat = QImage.Format_Indexed8\n if len(img.shape) == 3:\n if img.shape[2] == 4:\n qformat = QImage.Format_RGBA8888\n else:\n qformat = QImage.Format_RGB888\n outImage = QImage(img, img.shape[1], img.shape[0], img.strides[0], qformat)\n outImage = outImage.rgbSwapped()\n\n self.ui.labelPreview.setPixmap(QPixmap.fromImage(outImage))\n else:\n print(\"Camera update failed: \" + self.camera['name'])\n self.togglePreview(False)\n\n def makeCapture(self):\n ''' Capture image and save. '''\n\n success, img = self.camera['capture'].read()\n if success:\n cv2.imwrite(self.file_capture, img)\n print(\"Capture success: \" + self.camera['name'])\n self.on_capture()\n else:\n print(\"Capture failed: \" + self.camera['name'])\n self.togglePreview(False)\n\n # endregion\n\n # region Network\n\n def send_mssage(self, message):\n ''' Send message to holo client. '''\n\n if _client_ip:\n with(socket.socket(socket.AF_INET, socket.SOCK_DGRAM)) as client:\n print(f\"Sending {message} to {_client_ip[0]}:{Param.PORT + 1}\")\n client.sendto(message.encode('utf-8'), (_client_ip[0], Param.PORT + 1))\n\n def format_file(self, name):\n return name.replace('@', str(_section))\n\n def sectionSelected(self, index):\n ''' Called when combo item selected. '''\n\n global _section\n _section = index\n\n self.file_index = self.format_file(File.INDEX)\n self.file_holo = self.format_file(File.HOLO)\n self.file_capture = self.format_file(File.CAPTURE)\n self.file_crack = self.format_file(File.CRACK)\n self.file_match = self.format_file(File.MATCH)\n self.file_result = self.format_file(File.RESULT)\n self.file_overlay = self.format_file(File.OVERLAY)\n self.file_logs = self.format_file(File.TRN_LOGS)\n self.path_capture = self.format_file(Path.CAPTURE)\n self.path_crack = self.format_file(Path.CRACK)\n self.path_crackgt = self.format_file(Path.CRACK_GT)\n self.path_data = self.format_file(Path.DATA)\n\n self.ui.labelCapture.setPixmap(QPixmap(self.file_capture))\n self.ui.labelHolo.setPixmap(QPixmap(self.file_holo))\n self.ui.labelCrack.setPixmap(QPixmap(self.file_crack))\n self.ui.labelMatch.setPixmap(QPixmap(self.file_match))\n self.ui.labelOverlay.setPixmap(QPixmap(self.file_overlay))\n\n print(f\"Canged section: {_section}\")\n\n self.send_mssage(f'section:{_section}')\n\n def networkChanged(self):\n ''' Called when network status is changed. '''\n\n if _client_ip:\n self.ui.buttonDisconnect.setEnabled(True)\n self.ui.textIP.setText(f\"{_client_ip[0]}:{_client_ip[1]}\")\n self.ui.labelHolo.setPixmap(QPixmap(File.CONNECTED))\n else:\n self.ui.buttonDisconnect.setEnabled(False)\n self.ui.textIP.setText(\"\")\n self.ui.labelHolo.setPixmap(QPixmap(File.QRCODE))\n self.ui.buttonSend.setEnabled(False)\n\n def disconnect(self):\n ''' Disconnect current client. '''\n\n global _client_ip\n _client_ip = None\n self.networkChanged()\n\n def messageReceived(self, message):\n ''' Called when text message received. '''\n\n if message:\n print(\"Received: \" + message)\n self.on_holo_received()\n\n def sectionNew(self):\n ''' Add new section and move. '''\n\n global _section_max\n self.ui.comboSections.addItem(str(_section_max))\n self.ui.comboSections.setCurrentIndex(_section_max)\n _section_max += 1\n\n def sectionClear(self):\n ''' Clear current section. '''\n\n self.removeCapture()\n self.removeHolo()\n self.removeCrack()\n self.removeMatch()\n self.removeResult()\n\n self.send_mssage(f'clear:{_section}')\n\n def sendResult(self):\n ''' Send result to holo client. '''\n\n self.send_mssage(f'result:{_section}')\n\n # endregion\n\n # region CrackDetect\n\n def register_weights(self):\n self.ui.comboWeights.clear()\n self.ui.comboWeights.addItem(File.BASE_MODEL)\n try:\n self.ui.comboWeights.addItems(get_all_files(Path.CKPT))\n except FileNotFoundError:\n pass\n\n def weightsSelected(self, index):\n weights = self.ui.comboWeights.currentText()\n self.model.load_weights(weights)\n print(f\">>> Load weights from {weights}\")\n\n def init_train_data(self, path_anns, shape):\n ''' Make initial training data index. '''\n\n heights, widths = shape\n files_ann = get_all_files(path_anns)\n with open(self.file_index, 'w') as file:\n file.write(f'{heights},{widths}\\n')\n for file_ann in files_ann:\n file.write(path.basename(file_ann) + '=TP\\n')\n\n def makeCrack(self, callback=False):\n ''' Make crack image. '''\n\n if self.ui.buttonDetectCrack.isEnabled():\n updated = self.update_file_time(self.file_capture, 'capture_as_crack')\n if not callback or updated:\n self.send_mssage('busy')\n task = TaskTime(\"makeCrack\")\n img_crack, shape = predict(self.model, self.file_capture, self.path_capture, self.path_crack)\n cv2.imwrite(self.file_crack, img_crack)\n self.init_train_data(self.path_crack, shape)\n task.display_time()\n self.send_mssage('free')\n\n self.on_crack_created()\n\n # endregion\n\n # region FeatureMatch\n\n def try_make_homography(self, img_query, img_train, detector):\n ''' Try make homography with detector. '''\n\n success, img_match, self.homography_info = make_homography(\n img_query, img_train, detector, Param.EQUALIZER)\n if success:\n cv2.imwrite(self.file_match, img_match)\n return success\n\n def makeMatch(self, callback=False):\n ''' Start feature matching. '''\n\n if self.ui.buttonFeatureMatch.isEnabled():\n updated_capture = self.update_file_time(self.file_capture, 'capture_as_match')\n updated_holo = self.update_file_time(self.file_holo, 'holo_as_match')\n if not callback or updated_capture or updated_holo:\n self.send_mssage('busy')\n task = TaskTime('makeMatch')\n img_query = cv2.imread(self.file_capture)\n img_train = cv2.imread(self.file_holo)\n\n if self.try_make_homography(img_query, img_train, Param.FEATURE_DETECTOR_1):\n task.display_time()\n self.on_feature_matched()\n # elif self.try_make_homography(img_query, img_train, Param.FEATURE_DETECTOR_2):\n # task.display_time()\n # self.on_feature_matched()\n self.send_mssage('free')\n\n def makeResult(self, callback=False):\n ''' Apply homography to crack image. '''\n\n if self.ui.buttonApplyHomography.isEnabled():\n updated_crack = self.update_file_time(self.file_crack, 'crack_as_result')\n updated_match = self.update_file_time(self.file_match, 'match_as_result')\n if not callback or updated_crack or updated_match:\n self.send_mssage('busy')\n task = TaskTime('makeResult')\n img_holo = cv2.imread(self.file_holo)\n img_crack = cv2.imread(self.file_crack)\n\n img_result = apply_homography(img_crack, self.homography_info)\n img_overlay = make_overlay(img_holo, img_result)\n\n cv2.imwrite(self.file_overlay, img_overlay)\n cv2.imwrite(self.file_result, img_result)\n task.display_time()\n self.send_mssage('free')\n\n self.on_homography_applied()\n\n # endregion\n\n # region FileOperations\n\n def file_saved(self, file):\n ''' Show message when file saved. '''\n\n print(\">>> File saved: \" + file)\n\n def update_file_time(self, file, keyword):\n ''' Update last used file time to prevent auto executing functions. '''\n\n current = path.getmtime(file)\n if self.last_used[keyword] != current:\n self.last_used[keyword] = current\n return True\n\n def openCapture(self):\n ''' Open captured image from disk. '''\n\n src = open_file_dialog(\"Open Wall Image\", Path.SAMPLES, f'Image Files {Param.IMAGE_EXTENSIONS}')\n if src:\n print(\">>> Opening file: \" + src)\n if path.exists(copy(src, self.file_capture)):\n self.on_capture()\n\n def removeCapture(self):\n remove_tree(self.file_capture)\n self.ui.labelCapture.clear()\n self.ui.buttonRemoveCapture.setEnabled(False)\n self.ui.buttonFeatureMatch.setEnabled(False)\n self.ui.buttonDetectCrack.setEnabled(False)\n\n def removeHolo(self):\n remove_tree(self.file_holo)\n\n self.ui.labelHolo.setPixmap(QPixmap(File.QRCODE))\n self.ui.buttonFeatureMatch.setEnabled(False)\n\n def removeCrack(self):\n remove_tree(self.file_crack)\n self.ui.labelCrack.clear()\n self.ui.buttonRemoveCrack.setEnabled(False)\n self.ui.buttonApplyHomography.setEnabled(False)\n self.last_used['capture_as_crack'] = 0\n\n def removeMatch(self):\n remove_tree(self.file_match)\n self.ui.labelMatch.clear()\n self.ui.buttonRemoveMatch.setEnabled(False)\n self.ui.buttonApplyHomography.setEnabled(False)\n self.last_used['capture_as_match'] = 0\n self.last_used['holo_as_match'] = 0\n self.homography_info = None\n\n def removeResult(self):\n remove_tree(self.file_result)\n self.ui.labelOverlay.clear()\n self.ui.buttonRemoveResult.setEnabled(False)\n self.ui.buttonSend.setEnabled(False)\n self.last_used['crack_as_result'] = 0\n self.last_used['match_as_result'] = 0\n\n def archiveAll(self):\n save_path = Path.ARCHIVES + '/' + datetime.now().strftime(\"%Y-%m-%d_%p-%I-%M-%S\")\n clean_tree([save_path])\n copytree(Path.RESULTS, save_path)\n self.file_saved(save_path)\n\n def cleanAll(self):\n reply = QMessageBox.question(self, \"Clean\", \"Are you sure want to delete all caches?\",\n QMessageBox.Yes | QMessageBox.No)\n if reply == QMessageBox.Yes:\n self.removeCapture()\n self.removeHolo()\n self.removeCrack()\n self.removeMatch()\n self.removeResult()\n\n def closeEvent(self, event):\n reply = QMessageBox.question(self, \"Exit\", \"Save results to archive folder?\",\n QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)\n if reply == QMessageBox.Save:\n self.archiveAll()\n remove_tree(Path.RESULTS)\n event.accept()\n elif reply == QMessageBox.Discard:\n remove_tree(Path.RESULTS)\n event.accept()\n else:\n event.ignore()\n\n # endregion\n\n # region Callbacks\n\n def on_capture(self):\n ''' Invoke when capture. '''\n\n self.file_saved(self.file_capture)\n self.ui.labelCapture.setPixmap(QPixmap(self.file_capture))\n self.ui.buttonRemoveCapture.setEnabled(True)\n self.ui.buttonDetectCrack.setEnabled(True)\n self.ui.buttonFeatureMatch.setEnabled(path.exists(self.file_holo))\n\n self.removeCrack()\n self.removeMatch()\n self.removeResult()\n\n delayed_function(lambda: self.makeMatch(True), self.ui.toggleAutoMatch.isChecked(), 10)\n delayed_function(lambda: self.makeCrack(True), self.ui.toggleAutoDetect.isChecked(), 20)\n\n def on_holo_received(self):\n ''' Invoke when file received. '''\n\n self.file_saved(self.file_holo)\n self.ui.labelHolo.setPixmap(QPixmap(self.file_holo))\n self.ui.buttonFeatureMatch.setEnabled(path.exists(self.file_capture))\n\n self.removeMatch()\n self.removeResult()\n\n delayed_function(lambda: self.makeMatch(True), self.ui.toggleAutoMatch.isChecked(), 10)\n delayed_function(lambda: self.makeCapture(), self.ui.toggleAutoCapture.isChecked(), 20)\n\n def on_crack_created(self):\n ''' Invoke when capture. '''\n\n self.file_saved(self.file_crack)\n self.ui.labelCrack.setPixmap(QPixmap(self.file_crack))\n self.ui.buttonRemoveCrack.setEnabled(True)\n self.ui.buttonApplyHomography.setEnabled(path.exists(self.file_match))\n\n self.removeResult()\n\n delayed_function(lambda: self.makeResult(True), self.ui.toggleAutoApply.isChecked(), 10)\n delayed_function(lambda: self.makeMatch(True), self.ui.toggleAutoMatch.isChecked(), 20)\n\n def on_feature_matched(self):\n ''' Invoke when feature match is success. '''\n\n self.file_saved(self.file_match)\n self.ui.labelMatch.setPixmap(QPixmap(self.file_match))\n self.ui.buttonRemoveMatch.setEnabled(True)\n self.ui.buttonApplyHomography.setEnabled(path.exists(self.file_crack))\n\n self.removeResult()\n\n delayed_function(lambda: self.makeResult(True), self.ui.toggleAutoApply.isChecked(), 10)\n delayed_function(lambda: self.makeCrack(True), self.ui.toggleAutoDetect.isChecked(), 20)\n\n def on_homography_applied(self):\n ''' Invoke when homography is applied. '''\n\n self.file_saved(self.file_result)\n self.file_saved(self.file_overlay)\n self.ui.labelOverlay.setPixmap(QPixmap(self.file_overlay))\n self.ui.buttonRemoveResult.setEnabled(True)\n self.ui.buttonSend.setEnabled(True)\n\n delayed_function(self.sendResult, self.ui.toggleAutoSend.isChecked(), 10)\n\n # endregion\n\n\nclass ServerThread(QThread):\n signal_network_changed = pyqtSignal()\n signal_message_received = pyqtSignal(str)\n\n def __init__(self):\n QThread.__init__(self)\n\n def listen(self, server_ip, server_port):\n self.server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self.server.bind((server_ip, server_port))\n\n addr = f\"{server_ip}:{server_port}:{path.basename(File.HOLO)}:{path.basename(File.RESULT)}\"\n print(\">>> Server started: \" + addr)\n qrcode.make(addr).save(File.QRCODE)\n self.signal_network_changed.emit()\n\n def run(self):\n while True:\n global _client_ip\n bytesAddressPair = self.server.recvfrom(1024)\n if _client_ip:\n self.signal_message_received.emit(bytesAddressPair[0].decode('utf-8'))\n else:\n _client_ip = bytesAddressPair[1]\n print(f\">>> Client connected: {_client_ip[0]}:{_client_ip[1]}\")\n self.signal_network_changed.emit()\n\n def close(self):\n self.server.close()\n self.server = None\n\n\nclass FTPThread(QThread):\n def __init__(self):\n QThread.__init__(self)\n self.server = None\n\n def listen(self, server_ip, server_port):\n authorizer = DummyAuthorizer()\n authorizer.add_anonymous(Path.RESULTS, perm=\"elradfmw\")\n\n handler = FTPHandler\n handler.authorizer = authorizer\n\n self.server = FTPServer((server_ip, server_port), handler)\n\n def run(self):\n self.server.serve_forever()\n\n\ndef __main():\n ''' CrackManager initializer. '''\n\n clean_tree([Path.RESULTS])\n\n app = QApplication(sys.argv)\n mainWindow = __MainWindow()\n\n server_ip = socket.gethostbyname(socket.gethostname())\n\n serverThread = ServerThread()\n serverThread.signal_network_changed.connect(mainWindow.networkChanged)\n serverThread.signal_message_received.connect(mainWindow.messageReceived)\n serverThread.listen(server_ip, Param.PORT)\n serverThread.start()\n\n show_window(mainWindow, not UI.FULLSCREEN)\n print(\">>> Starting application\")\n\n ftpThread = FTPThread()\n ftpThread.listen(server_ip, 21)\n ftpThread.start()\n\n sys.exit(app.exec_())\n\n\nif __name__ == '__main__':\n __main()\n","repo_name":"urun4m0r1/CrackManager","sub_path":"CrackManager-Server/crack_manager.py","file_name":"crack_manager.py","file_ext":"py","file_size_in_byte":20858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"19822890686","text":"from django.urls import include, path\nfrom rest_framework.authtoken.views import obtain_auth_token\nfrom django.contrib.auth.decorators import login_required\n\n\nfrom .views import GetUserView, LogoutView, RegisterView, EmailGenerateTokenView, EmailConfirmTokenView, registro_usuario, inicio, github_redirect, logoutGitHub, ObtainAuthTokenSecondFactor, google_redirect, logoutGoogle, facebook_redirect, logoutFacebook\n\n\nurlpatterns = [\n #path('login/', obtain_auth_token),\n path('login/', ObtainAuthTokenSecondFactor.as_view()),\n path('logout/', LogoutView.as_view()),\n path('getuser/', GetUserView.as_view()),\n path('register/', RegisterView.as_view()),\n path('email-generate-token/', EmailGenerateTokenView.as_view()),\n path('email-confirm-token/<userId>/<token>/', EmailConfirmTokenView.as_view(), name=\"email-confirm-token\"),\n path('registro/', registro_usuario),\n path('inicio/', login_required(inicio), name=\"inicio\"),\n path('social-auth/', include('social_django.urls', namespace='social')),\n path('github-redirect',github_redirect),\n path('logoutGithub/',logoutGitHub),\n path('google-redirect',google_redirect),\n path('logoutGoogle/',logoutGoogle),\n path('facebook-redirect',facebook_redirect),\n path('logoutFacebook/',logoutFacebook)\n\n\n]\n","repo_name":"antsuabon/decide-part-andarax-autenticacion-defensa","sub_path":"decide/authentication/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"33476227716","text":"import sys\nfrom cs50 import get_string\n\n\ndef final_output(fs):\n if fs < 1:\n print(\"Before Grade 1\")\n elif fs >= 16:\n print(\"Grade 16+\")\n else:\n print(f\"Grade {fs}\")\n\n\nif __name__=='__main__':\n text = get_string(\"Text: \")\n words = text.split(\" \")\n number_of_words = len(words)\n text2 = text.replace(\"?\", \".\")\n text3 = text2.replace(\"!\", \".\")\n sentences = text3.split(\".\")\n number_of_sentences = len(sentences)\n number_of_letters = 0\n for txt in words:\n number_of_letters+=len(txt)\n var1 = number_of_letters / number_of_words\n var2 = number_of_sentences / number_of_words\n score = 5.88 * var1 - 29.6 * var2 - 15.8\n final_score = round(score)\n final_output(final_score)\n\n","repo_name":"Karanpalshekhawat/cs_50_problem_set","sub_path":"pset6/readability.py","file_name":"readability.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"70151446840","text":"from . import free_module_element\nfrom sage.symbolic.ring import SR\n\n\nclass Vector_callable_symbolic_dense(free_module_element.FreeModuleElement_generic_dense):\n def _repr_(self):\n \"\"\"\n Returns the string representation of the vector\n\n EXAMPLES::\n\n sage: f(u,v,w) = (2*u+v,u-w,w^2+u)\n sage: f\n (u, v, w) |--> (2*u + v, u - w, w^2 + u)\n sage: r(t) = (cos(t), sin(t))\n sage: r\n t |--> (cos(t), sin(t))\n \"\"\"\n ring = self.coordinate_ring()\n args = ring.arguments()\n repr_x=self.change_ring(SR)._repr_()\n if len(args) == 1:\n return \"%s |--> %s\" % (args[0], repr_x)\n else:\n args = \", \".join(map(str, args))\n return \"(%s) |--> %s\" % (args, repr_x)\n\n def _latex_(self):\n r\"\"\"\n Return the latex representation of the vector.\n\n EXAMPLES::\n\n sage: f(u,v,w) = (2*u+v,u-w,w^2+u)\n sage: f\n (u, v, w) |--> (2*u + v, u - w, w^2 + u)\n sage: latex(f)\n \\left( u, v, w \\right) \\ {\\mapsto} \\ \\left(2 \\, u + v,\\,u - w,\\,w^{2} + u\\right)\n sage: r(t) = (cos(t), sin(t))\n sage: r\n t |--> (cos(t), sin(t))\n sage: latex(r)\n t \\ {\\mapsto}\\ \\left(\\cos\\left(t\\right),\\,\\sin\\left(t\\right)\\right)\n \"\"\"\n from sage.misc.latex import latex\n ring = self.coordinate_ring()\n args = ring.arguments()\n args = [latex(arg) for arg in args]\n latex_x = self.change_ring(SR)._latex_()\n if len(args) == 1:\n return r\"%s \\ {\\mapsto}\\ %s\" % (args[0], latex_x)\n else:\n vars = \", \".join(args)\n return r\"\\left( %s \\right) \\ {\\mapsto} \\ %s\" % (vars, latex_x)\n","repo_name":"sagemath/sage-archive-2023-02-01","sub_path":"src/sage/modules/vector_callable_symbolic_dense.py","file_name":"vector_callable_symbolic_dense.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","stars":2037,"dataset":"github-code","pt":"40"} +{"seq_id":"9917406780","text":"# Julian van Rensburg\r\n# Assignment 8 Question 2\r\n# counter\r\n\r\ndef count(word):\r\n if not len(word)>= 2:\r\n return 0\r\n if word[0] == word[1]:\r\n return 1 + count(word[2:])\r\n return count(word[1:])\r\n \r\n\r\ndef main():\r\n a = input(\"Enter a message:\\n\")\r\n b = count(a)\r\n print(\"Number of pairs:\",end=\" \")\r\n print(b)\r\n \r\nmain()\r\n ","repo_name":"MrHamdulay/csc3-capstone","sub_path":"examples/data/Assignment_8/jnsjul007/question2.py","file_name":"question2.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"28033895035","text":"\"\"\"Modules de définition des entités du projet représenant un Graph\"\"\"\n\nfrom typing import ClassVar, Optional, Union, List, Dict\nimport json\nfrom abc import ABC\nfrom dataclasses import dataclass, field\nimport dataclasses\nimport dacite\nfrom pprint import pprint\nimport logging\n\n\nlogger = logging.getLogger(__name__)\n\n\n@dataclass\nclass Node(ABC):\n \"\"\"Classe abstraite représentant un noeud du graph\n\n Attributes:\n id (int): identifiant du noeud\n type (int): identifiant du type de noeud (variable de class \\\\*_NODE)\n\n | PUBLICATION_NODE: 1, noeud de type publication\n | CLINICAL_TRIAL_NODE: 2, noeud de type essais clinique\n | JOURNAL_NODE: 3, noeud de type journal\n | DRUG_NODE: 4, noeud de type molécule\n\n \"\"\"\n id: int = field(init=True)\n type: int = field(init=False)\n\n PUBLICATION_NODE: ClassVar[int] = 1\n CLINICAL_TRIAL_NODE: ClassVar[int] = 2\n JOURNAL_NODE: ClassVar[int] = 3\n DRUG_NODE: ClassVar[int] = 4\n\n def to_dict(self) -> dict:\n \"\"\"Retourne les attributs de la classe sous forme de dictionnaire\n\n Returns:\n dict: clés: id, type\n \"\"\"\n return dataclasses.asdict(self)\n\n\n@dataclass\nclass Drug(Node):\n \"\"\"Noeud représentant une molécule hérité de Node\n\n Attributes:\n name (str): nom de la molécule\n atccode (str): identifiant d'origine de la molécule\n \"\"\"\n type: int = field(default=Node.DRUG_NODE, init=False)\n name: str\n atccode: str\n\n def __post_init__(self) -> None:\n\n self.name = self.name.lower().strip()\n\n def is_name_mentionned(self, content: str) -> bool:\n \"\"\"Permet de tester si le nom de la molécule est\n contenu dans une chaine de caractère\n\n Args:\n content (str): chaine de caractère à tester\n\n Returns:\n bool: retour de la valeur du test\n \"\"\"\n return self.name in content\n\n\n@dataclass\nclass Publication(Node):\n \"\"\"Noeud représentant une Publication hérité de Node\n\n Attributes:\n title (str): Titre de la publication\n date (str, None): Date de parution de la publication\n base_id (int, None): Identifiant d'origine de la publication\n \"\"\"\n type: int = field(default=Node.PUBLICATION_NODE, init=False)\n title: str\n date: Optional[str] = None\n base_id: Optional[int] = None\n\n\n@dataclass\nclass ClinicalTrial(Node):\n \"\"\"Noeud représentant un ClinicalTrial hérité de Node\n\n Attributes:\n title (str): Titre de l'essai clinique\n date (str, optional): Date de parution de l'essai clinique\n base_id (str, optional): Identifiant d'origine de l'essai clinique\n \"\"\"\n type: int = field(default=Node.CLINICAL_TRIAL_NODE, init=False)\n title: str\n date: Optional[str] = None\n base_id: Optional[str] = None\n\n\n@dataclass\nclass Journal(Node):\n \"\"\"Noeud représentant un Journal hérité de Node\n\n Attributes:\n name (str): Titre du journal\n \"\"\"\n type: int = field(default=Node.JOURNAL_NODE, init=False)\n name: str\n\n\n@dataclass\nclass Link(ABC):\n \"\"\"Classe abstraite représentant une liaison entre deux noeuds\n\n Attributes:\n id (str): Identifiant unique du lien\n type (int): Identifiant du type de liaison (variable de class \\\\*_LINK)\n node_a (Node): Noeud A\n node_b (Node): Noeud B\n date (str, optional): Date du lien (pratique pour le cas d'usage)\n\n | PUBLISHED_LINK: 1, liaison de type B est publié dans le journal A\n | MENTIONNED_LINK: 2, liaison de type la molécule A est mentionné dans B\n\n \"\"\"\n id: str = field(init=False)\n type: int = field(init=False)\n node_a: Node\n node_b: Node\n date: Optional[str] = None\n\n PUBLISHED_LINK: ClassVar[int] = 1\n MENTIONNED_LINK: ClassVar[int] = 2\n\n def __post_init__(self):\n self.build_id()\n\n def build_id(self) -> None:\n \"\"\"Construction de l'id de liaison en concaténant\n l'identifiant du noeud A et du noeud B\n \"\"\"\n self.id = str(self.node_a.id) + \"_\" + str(self.node_b.id)\n\n def to_dict(self):\n \"\"\"Retourne les attributs de la classe sous forme de dictionnaire\n\n Returns:\n dict: clés: id, type, node_a, node_b, date\n \"\"\"\n return dataclasses.asdict(self)\n\n\nclass PublishedLink(Link):\n \"\"\"Liaison représentant la publication d'un essai clinique\n ou d'une publication dans un journal\n\n Attributes:\n node_a (Journal): Journal\n node_b (Union[ClinicalTrial, Publication]): essai clinique ou publication\n\n Raises:\n TypeError: node_a must be instance of Journal\n TypeError: node_b must be instance of Publication or ClinicalTrial\n\n \"\"\"\n node_a: Journal\n node_b: Union[ClinicalTrial, Publication]\n\n def __post_init__(self) -> None:\n if not isinstance(self.node_a, Journal):\n raise TypeError(\"node_a must be instance of Journal\")\n if not isinstance(self.node_b, ClinicalTrial) and not isinstance(self.node_b, Publication):\n raise TypeError(\"node_b must be instance of Publication or ClinicalTrial\")\n self.type = Link.PUBLISHED_LINK\n self.date = self.node_b.date\n return super().__post_init__()\n\n\nclass MentionnedLink(Link):\n \"\"\"Liaison représentant la mention d'une molécule dans un essai clinique,\n une publication ou un journal\n\n Attributes:\n node_a (Drug): Noeud représentant la molécule mentionnée\n node_b (Union[ClinicalTrial, Publication, Journal]): Noeud de la mention\n mention_type (str): détails de la mention (MENTION_*)\n\n | MENTION_CLINICAL_TRIAL: clinical_trial, la molécule est mentionnée dans un essai clinique\n | MENTION_PUBLICATION: publication, la molécule est mentionnée dans une publication\n | MENTION_JOURNAL: journal, la molécule est mentionnée dans un journal\n\n Raises:\n TypeError: node_a must be instance of Drug\n TypeError: node_b must be instance of Publication, ClinicalTrial or Journal\n\n \"\"\"\n node_a: Drug\n node_b: Union[ClinicalTrial, Publication, Journal]\n mention_type: str = field(init=False)\n\n MENTION_CLINICAL_TRIAL: ClassVar[str] = \"clinical_trial\"\n MENTION_PUBLICATION: ClassVar[str] = \"publication\"\n MENTION_JOURNAL: ClassVar[str] = \"journal\"\n\n def __post_init__(self):\n if not isinstance(self.node_a, Drug):\n raise TypeError(\"node_a must be instance of Drug\")\n\n if isinstance(self.node_b, Publication):\n self.mention_type = MentionnedLink.MENTION_PUBLICATION\n elif isinstance(self.node_b, ClinicalTrial):\n self.mention_type = MentionnedLink.MENTION_CLINICAL_TRIAL\n elif isinstance(self.node_b, Journal):\n self.mention_type = MentionnedLink.MENTION_JOURNAL\n else:\n raise TypeError(\"node_b must be instance of Publication, ClinicalTrial or Journal\")\n self.type = Link.MENTIONNED_LINK\n return super().__post_init__()\n\n\n@dataclass\nclass Graph():\n \"\"\"Classe représentant un graph composé de noeuds et de liaisons\n\n Attributes:\n id_state (int): valeur de l'identifiant interne\n nodes (list): ensembe des noeuds du graph\n links (list): ensemble des liaisons du graph\n _journal_lookup (dict): attribut facilitant l'accès aux journaux par titre\n _links_id (list): attribut listant les identifiants des liaisons\n\n \"\"\"\n id_state: int = field(default=0, init=False)\n nodes: List[Union[Drug, Journal, Publication, ClinicalTrial]] = field(default_factory=list, init=False)\n links: List[Union[MentionnedLink, PublishedLink]] = field(default_factory=list, init=False)\n _journals_lookup: Dict[str, Journal] = field(default_factory=dict, init=False, repr=False)\n _links_id: List[str] = field(default_factory=list, init=False, repr=False)\n\n @property\n def journals_lookup(self) -> dict:\n \"\"\"Getter de l'attribut journals_lookup.\n Construit le dictionnaire si None.\n\n Returns:\n dict: dictionnaire des journaux (valeur) par titre (clé)\n \"\"\"\n if not self._journals_lookup:\n self.journals_lookup = {node.name: node for node in self.nodes if node.type == Node.JOURNAL_NODE}\n return self._journals_lookup\n\n @journals_lookup.setter\n def journals_lookup(self, journals_lookup: Dict[str, Journal]) -> None:\n \"\"\"Setter de l'attribut journals_lookup.\n\n Args:\n journals_lookup (dict): dictionnaire des journaux (valeur) par titre (clé)\n\n Raises:\n TypeError: journals_lookup must be instance of dict of Journal\n \"\"\"\n if not isinstance(journals_lookup, dict):\n raise TypeError('journals_lookup must be instance of dict of Journal')\n self._journals_lookup = journals_lookup\n\n def look_for_drug_by_names(self, names: List[str]) -> List[Drug]:\n \"\"\"Retrouve les noeuds molécule par nom de molécule\n\n Args:\n names (List[str]): liste des noms de molécule\n\n Returns:\n List[Drug]: list des objets Drug\n \"\"\"\n return [drug for drug in self.nodes if drug.type == Node.DRUG_NODE and drug.name in names]\n\n def look_for_links_by_nodes(self, nodes: List[Node], link_type: int = None) -> List[Link]:\n \"\"\"Retrouve les liaisons incluant les noeuds en paramètres\n\n Args:\n nodes (List[Node]): list des noeuds pour la recherche de liaison\n link_type (int, optional): type de liaison à retrouver. Defaults to None.\n\n Returns:\n List[Link]: list des liaisons retrouvées\n \"\"\"\n nodes_ids = [node.id for node in nodes]\n results_links: List[Link] = []\n results_links = [link for link in self.links if (link.node_a.id in nodes_ids or link.node_b.id in nodes_ids)]\n if link_type:\n results_links = [link for link in results_links if link.type == link_type]\n return results_links\n\n def look_for_journal(self, name: str) -> Optional[Journal]:\n \"\"\"Retrouve un journal par son nom\n\n Args:\n name (str): nom du journal\n\n Returns:\n Optional[Journal]: le noeud Journal ou None si non retrouvé\n \"\"\"\n if not isinstance(name, str):\n return\n if name in self.journals_lookup:\n return self.journals_lookup[name]\n return\n\n def look_for_journal_link(self, node_b: Union[Publication, ClinicalTrial]) -> Optional[Journal]:\n \"\"\"Retrouve un journal par sa liaison de publication avec le noeud B,\n autrement dit, si une publication ou un essai clinique est publié dans un journal,\n ce dernier est renvoyé. Recherche non optimisée.\n\n Args:\n node_b (Union[Publication, ClinicalTrial]): noeud publication ou essai clinique\n\n Returns:\n Optional[Journal]: le journal ou None sinon\n \"\"\"\n for journal_link in self.links:\n if journal_link.type == Link.PUBLISHED_LINK:\n if journal_link.node_b.id == node_b.id:\n return journal_link\n return\n\n def get_id_and_increment(self) -> int:\n \"\"\"Retourne l'identifiant interne et l'incrémente ensuite.\n L'identifiant permet d'associer aux noeuds ou liaisons un identifiant unique.\n\n Returns:\n int: valeur de l'identifiant\n \"\"\"\n self.id_state += 1\n return self.id_state - 1\n\n def build_graph(self, drug_file: str, journal_file: str, pubmed_file: str,\n clinical_trial_file: str) -> \"Graph\":\n \"\"\"Methode principale pour construire l'objet graph depuis les fichiers\n json formatté depuis l'étape data et en particulier la fonction :func:`~clients.data.export_dfs_to_json`.\n L'ordre de construction est important pour prendre en compte les liaisons avec les journaux.\n\n Args:\n drug_file (str): fichier json des molécules\n journal_file (str): fichier json des journaux\n pubmed_file (str): fichier json des publications pubmeds\n clinical_trial_file (str): fichier json des essais cliniqquqes\n\n Returns:\n Graph: objet graph complet\n \"\"\"\n logger.info(\"Construction du graph...\")\n\n logger.info(\"Construction des noeuds.\")\n # build nodes\n # -> Drug\n drug_nodes: List[Drug] = self._build_nodes_from_json_file_(drug_file, Drug)\n # -> Journal\n journal_nodes: List[Journal] = self._build_nodes_from_json_file_(journal_file, Journal) # noqa\n # -> Publication\n publication_nodes: List[Publication] = self._build_nodes_from_json_file_(pubmed_file, Publication)\n # -> ClinicalTrial\n clinical_trial_nodes: List[ClinicalTrial] = self._build_nodes_from_json_file_(clinical_trial_file, ClinicalTrial)\n\n self._build_mentions(drug_nodes, publication_nodes, clinical_trial_nodes)\n\n return self\n\n def _build_nodes_from_json_file_(self, filename: str, cls) -> List[Node]:\n \"\"\"Methode privée pour construire les noeuds à partir d'un fichier json\n\n Args:\n filename (str): chemin du fichier json\n cls (__class__): classe du type de noeud (Drug, Publication, ClinicalTrial, Journal)\n\n Returns:\n List[Node]: list des noeuds construits\n \"\"\"\n with open(filename, 'r') as f:\n json_content = json.load(f)\n return self._build_nodes_from_list(json_content, cls)\n\n def _build_nodes_from_list(self, content: List[dict], cls) -> List[Node]:\n \"\"\"Methode privée pour construire les noeuds à partir d'un dictionnaire.\n Les liens de publications sont également construits en même temps.\n\n Args:\n content (List[dict]): list de dictionnaire\n cls (__class__): classe du type de noeud (Drug, Publication, ClinicalTrial, Journal)\n\n Returns:\n List[Node]: list des noeuds construits\n \"\"\"\n current_nodes: List[Node] = []\n\n for infos in content:\n journal_node = None\n journal_name = None\n if cls.__name__ in ['Publication', 'ClinicalTrial'] and 'journal' in infos:\n journal_name = infos.pop('journal')\n # /!\\ don't create journal node if doesn't exist\n journal_node = self.look_for_journal(journal_name)\n\n node = cls(\n id=self.get_id_and_increment(),\n **infos\n )\n logger.debug(f\"Construction du noeud {node}.\")\n\n if journal_node:\n self._build_link(journal_node, node, node.date, PublishedLink)\n\n current_nodes.append(node)\n\n self.nodes += current_nodes\n\n return current_nodes\n\n def _build_mentions(self, drug_nodes: List[Drug], publication_nodes: List[Publication],\n clinical_trial_nodes: List[ClinicalTrial]) -> None:\n \"\"\"Methode construisant les liens de mention des molécules.\n\n Args:\n drug_nodes (List[Drug]): liste des noeuds des molécules\n publication_nodes (List[Publication]): liste des noeuds des publications\n clinical_trial_nodes (List[ClinicalTrial]): liste des noeuds des essais cliniques\n \"\"\"\n logger.info(\"Construction des mentions.\")\n # build links with publications and clinical trials\n for d_node in drug_nodes:\n for node_with_title in publication_nodes + clinical_trial_nodes:\n if d_node.is_name_mentionned(node_with_title.title):\n self._build_link(d_node, node_with_title, node_with_title.date, MentionnedLink)\n\n # build links with journals\n for link in self.links:\n if link.type != Link.MENTIONNED_LINK:\n continue\n if link.mention_type == MentionnedLink.MENTION_CLINICAL_TRIAL or \\\n link.mention_type == MentionnedLink.MENTION_PUBLICATION:\n journal_link = self.look_for_journal_link(link.node_b)\n if not journal_link:\n continue\n self._build_link(link.node_a, journal_link.node_a, journal_link.node_b.date, MentionnedLink)\n return\n\n def _build_link(self, node_a: Node, node_b: Node, date: str, cls) -> None:\n \"\"\"Methode générique pour construire une liaison entre deux noeuds sachant la classe\n\n Args:\n node_a (Node): noeud A de la liaison\n node_b (Node): noeud B de la liaison\n date (str): date de la liaison\n cls (__class__): PublishedLink, MentionnedLink\n \"\"\"\n\n current_link = cls(node_a, node_b, date)\n logger.debug(f'Création du lien {current_link}')\n if current_link.id not in self._links_id:\n self.links.append(current_link)\n self._links_id.append(current_link.id)\n return\n\n def get_drugs_mentions(self, drug_names: List[str], verbose: bool = True) -> Dict[str, List[MentionnedLink]]:\n \"\"\"Retourne les liaisons de mention d'une liste de molécule.\n Le format de retour correspond à un dictionnaire:\n\n | {\n | 'drug_name': [MentionnedLink, ..., MentionnedLink],\n | ...\n | }\n\n En revanche si verbose = True, ce qui est affiché a le format suivant:\n\n | {\n | 'drug_name': [{\n | 'type': ..., # attributs type du noeud qui mentionne la molécule\n | 'date': ...,\n | 'title': ...,\n | 'name': ...,\n | 'id': ...\n | }, ..., {\n | 'type': ..., # attributs type du noeud qui mentionne la molécule\n | 'date': ...,\n | 'title': ...,\n | 'name': ...,\n | 'id': ...\n | }],\n | ...\n | }\n\n Args:\n drug_names (List[str]): liste des molécules\n verbose (bool, optional): Defaults to True.\n\n Returns:\n Dict[str, MentionnedLink]: retourne le dictionnaire de résultats\n \"\"\"\n drug_mentions: Dict[str, List[MentionnedLink]] = {}\n pretty_drug_mentions = {}\n\n drug_nodes = self.look_for_drug_by_names(drug_names)\n for drug_node in drug_nodes:\n links = self.look_for_links_by_nodes([drug_node], Link.MENTIONNED_LINK)\n drug_mentions.update({drug_node.name: links})\n\n if verbose:\n for drug_name, drug_links in drug_mentions.items():\n pretty_drug_mentions.update({\n drug_name: [{**dataclasses.asdict(drug_mention.node_b), **{'date': drug_mention.date}} for drug_mention in drug_links]\n })\n pprint(pretty_drug_mentions)\n\n return drug_mentions\n\n def to_dict(self) -> List[dict]:\n \"\"\"Convertir l'objet graph en dictionnaire en utilisant dataclasses.asdict()\n\n Returns:\n List[dict]: dictionnaire\n \"\"\"\n return dataclasses.asdict(self)\n\n def to_json(self, output_file: str) -> None:\n \"\"\"Sauvegarde l'objet graph en json\n\n Args:\n output_file (str): chemin du fichier json de sortie\n \"\"\"\n with open(output_file, 'w') as f:\n json.dump(self.to_dict(), f, indent=True)\n\n @staticmethod\n def from_dict(graph_dict: dict) -> \"Graph\":\n \"\"\"Instancier l'objet graph à partir d'un dictionnaire\n\n Args:\n graph_dict (dict): dictionnaire du graph\n\n Returns:\n Graph: objet graph instancié\n \"\"\"\n return dacite.from_dict(Graph, graph_dict)\n\n @staticmethod\n def from_json(input_file: str) -> \"Graph\":\n \"\"\"Instancier l'objet graph à partir d'un fichier json\n\n Args:\n input_file (str): chemin du fichier json d'entrée\n\n Returns:\n Graph: obket graph instancié\n \"\"\"\n graph_dict = {}\n with open(input_file, 'r') as f:\n graph_dict = json.load(f)\n return Graph.from_dict(graph_dict)\n","repo_name":"prise6/reponse-client-s","sub_path":"clients/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":20097,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"2827556766","text":"#!/usr/bin/env python\n\nimport os, sys\nfrom cupcake.io.GFF import collapseGFFReader\n\ndef main(input_prefix):\n input_gff = input_prefix + '.gff'\n if not os.path.exists(input_gff):\n print(\"Looking for input GFF {0} but not found! Abort!\".format(input_gff))\n sys.exit(-1)\n\n f1 = open(input_prefix + '.simple_stats.txt', 'w')\n f1.write(\"pbid\\tlocus\\tlength\\tgenomic_length\\tnum_exon\\n\")\n f2 = open(input_prefix + '.exon_stats.txt', 'w')\n f2.write(\"pbid\\texon_index\\texon_size\\tintron_size\\n\")\n for r in collapseGFFReader(input_gff):\n if len(r.ref_exons)==0: continue\n f1.write(r.seqid+'\\t')\n if r.seqid.startswith('PB.'): f1.write(r.seqid.split('.')[1]+'\\t')\n else: f1.write(r.geneid+'\\t')\n sum_len = 0\n for i,e in enumerate(r.ref_exons):\n exon_len = e.end - e.start\n sum_len += exon_len\n f2.write(\"{0}\\t{1}\\t{2}\\t\".format(r.seqid, i+1, exon_len))\n if i == 0: f2.write(\"NA\\n\")\n else: \n if len(r.ref_exons)>0: f2.write(str(e.start-r.ref_exons[i-1].end) + '\\n')\n\n f1.write(str(sum_len)+'\\t')\n f1.write(str(r.end-r.start)+'\\t')\n f1.write(str(len(r.ref_exons))+'\\n')\n\n f1.close()\n f2.close()\n print(\"Output written to: {0},{1}\\n\".format(f1.name, f2.name))\n\nif __name__ == \"__main__\":\n from argparse import ArgumentParser\n parser = ArgumentParser()\n parser.add_argument(\"input_prefix\", help=\"Input prefix, ex: hq.5merge.collapsed\")\n\n args = parser.parse_args()\n main(args.input_prefix)\n","repo_name":"Magdoll/cDNA_Cupcake","sub_path":"cupcake/tofu/simple_stats_post_collapse.py","file_name":"simple_stats_post_collapse.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","stars":233,"dataset":"github-code","pt":"40"} +{"seq_id":"4802132522","text":"import pytest\nfrom baseball.entity.batter import Batter\nfrom baseball.entity.pitcher import Pitcher\nfrom baseball.batter_box import BatterBox\nfrom data_aggregate_helper import DataAggregateHelper\n\nimport pandas as pd\n\n\n# 今はテストしていない\ndef read_csv():\n test_csv = pd.read_csv('resource/batterbox_test.csv', index_col=0)\n return test_csv\n\n\ndef create_batter():\n return Batter.ButterBuilder().name(\"テスト打者\").contact(50).power(50).run(50).build()\n\n\ndef create_pitcher():\n return Pitcher.PitcherBuilder().name(\"テスト投手\").speed(50).control(50).henka(50).build()\n\n\ndef create_defence():\n return Batter.ButterBuilder().name(\"テスト守備\").defence(50).throw(50).build()\n\ndef test_read_csv():\n test_csv = read_csv()\n print(test_csv.iloc[0].power)\n\n\ndef test_batterbox():\n test_csv = read_csv()\n result_average = []\n result_fourball = []\n result_strikeout = []\n result_single = []\n result_double = []\n result_triple = []\n result_homerun = []\n for test_id in range(len(test_csv)):\n test_data = test_csv.iloc[test_id]\n batter = Batter.ButterBuilder().name(\"テスト打者\").contact(test_data.contact)\\\n .power(test_data.power).run(test_data.run).build()\n pitcher = Pitcher.PitcherBuilder().name(\"テスト投手\").speed(test_data.speed)\\\n .control(test_data.control).henka(test_data.henka).build()\n defence = Batter.ButterBuilder().name(\"テスト守備\").defence(test_data.defence)\\\n .throw(test_data.throw).build()\n box = BatterBox(batter, pitcher, [defence] * 9, 0b0000, 0)\n data_helper = DataAggregateHelper()\n for _ in range(1000):\n action = box.judge_result()\n data_helper.count(action)\n result_average.append(data_helper.average())\n result_fourball.append(data_helper.fourball_prob())\n result_strikeout.append(data_helper.strikeout_prob())\n result_single.append(data_helper.single_prob())\n result_double.append(data_helper.double_prob())\n result_triple.append(data_helper.triple_prob())\n result_homerun.append(data_helper.homerun_prob())\n\n test_csv[\"average\"] = pd.Series(result_average)\n test_csv[\"fourball\"] = pd.Series(result_fourball)\n test_csv[\"strikeout\"] = pd.Series(result_strikeout)\n test_csv[\"single\"] = pd.Series(result_single)\n test_csv[\"double\"] = pd.Series(result_double)\n test_csv[\"triple\"] = pd.Series(result_triple)\n test_csv[\"homerun\"] = pd.Series(result_homerun)\n\n test_csv.to_csv('resource/results/batterbox_test_result.csv', index=False)\n\n\n\n","repo_name":"kentahoriuchi/kokosim_py","sub_path":"tests/batter_boxtest.py","file_name":"batter_boxtest.py","file_ext":"py","file_size_in_byte":2620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"3642086076","text":"# Definition for a binary tree node\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n # @param root, a tree node\n # @return an integer\n def minDepth(self, root):\n if root==None: return 0\n l1=self.minDepth(root.left)\n l2=self.minDepth(root.right)\n if l1==0 and l2==0:\n return 1\n if l1==0:\n return 1+l2\n if l2==0:\n return 1+l1\n return 1+min(l1,l2)\n \n","repo_name":"ssydyc/Leetcode_python","sub_path":"Minimue_Depth_of_Binary_Tree.py","file_name":"Minimue_Depth_of_Binary_Tree.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"36137358700","text":"#!/usr/bin/env python3\n\"\"\"Simple command line python script that outputs a spreadsheet of data about your debt payments. Jorin Weatherston August, 2017\"\"\"\nimport csv\nimport sys, getopt\nfrom math import floor\n\ndef main(argv):\n ## initialization ##\n # initialize argument variables\n initial_debt = 0\n interest_rate = 0\n payment = 0\n\n # initialize getopt (credit: https://www.tutorialspoint.com/python/python_command_line_arguments.htm)\n try:\n options, arguments = getopt.getopt(argv, \"hd:i:p\", [\"debt=\", \"interest=\", \"payment=\"])\n except getopt.GetoptError:\n print('Error: Accepted format is: ./debt_calculator.py -d <initial debt> -i <interest rate> -p <payment amount>')\n sys.exit(2)\n for option, argument in options:\n if option == '-h':\n print('./debt_calculator.py -d <initial debt> -i <interest rate> -p <payment amount>')\n sys.exit(2)\n elif option in ('-d', \"--debt\"):\n initial_debt = float(argument)\n elif option in ('-i', \"--interest\"):\n interest_rate = float(argument)\n elif option in ('-p', \"--payment\"):\n payment = float(argument)\n\n # constants\n days_between_payments = 15\n days_per_year = 365\n\n # initialized variables\n interest_to_pay = 0\n principle_reduced = 0\n payment_number = 1\n debt_remaining_after_payment = initial_debt\n debt_remaining_before_payment = initial_debt\n interest_rate_per_15_day_cycle = (interest_rate / days_per_year) * days_between_payments\n\n ## debt calculation ##\n # open file\n writer = csv.writer(open('paymentRecord.csv', 'w', newline=''))\n\n # add column headers\n writer.writerow(['Payment Number', 'Debt Remaining Before Payment', 'Interest to be Paid', 'Payment', 'Principle Reduced', 'Debt Remaining After Payment'])\n\n # iterate until debt is repayed\n while debt_remaining_after_payment > 0:\n debt_remaining_before_payment = debt_remaining_after_payment\n interest_to_pay = debt_remaining_before_payment * interest_rate_per_15_day_cycle\n principle_reduced = payment - interest_to_pay\n debt_remaining_after_payment = debt_remaining_before_payment - principle_reduced\n writer.writerow([payment_number, debt_remaining_before_payment, interest_to_pay, payment, principle_reduced, debt_remaining_after_payment])\n writer.writerow([''])\n payment_number = payment_number + 1\n\n # calculate metrics about repayment and add to final row\n total_days = payment_number * days_between_payments\n total_months = floor(total_days/30.4)\n total_years = total_months/12\n writer.writerow(['Total payments:', payment_number, 'Days in repayment:', total_days, 'Months in repayment:', total_months, 'Years in repayment:', total_years])\n print('Success.')\n print('Total payments:', payment_number, ', Days in repayment:', total_days, ', Months in repayment:', total_months, ', Years in repayment:', total_years)\n print('Goodluck with your payments!')\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","repo_name":"JorinW/DebtCalculator","sub_path":"debt_calculator.py","file_name":"debt_calculator.py","file_ext":"py","file_size_in_byte":3070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"16810491582","text":"\"\"\"Views related to the statistics module\"\"\"\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic import TemplateView\nfrom django.shortcuts import render\n\nfrom ...models import PageTranslation, Region\nfrom ...decorators import region_permission_required\n\n\n@method_decorator(login_required, name='dispatch')\n@method_decorator(region_permission_required, name='dispatch')\nclass TranslationCoverageView(TemplateView):\n \"\"\"\n Class to create the translation coverage statistic\n \"\"\"\n template_name = 'analytics/translation_coverage.html'\n base_context = {'current_menu_item': 'translation_coverage'}\n\n def get(self, request, *args, **kwargs):\n\n region = Region.get_current_region(request)\n num_pages = region.pages.count()\n languages = []\n\n for language in region.languages:\n page_translations = PageTranslation.get_translations(region, language)\n languages.append({\n 'translated_name': language.translated_name,\n 'num_page_translations_up_to_date': len([t for t in page_translations if t.is_up_to_date]),\n 'num_page_translations_currently_in_translation': len([t for t in page_translations if t.currently_in_translation]),\n 'num_page_translations_outdated': len([t for t in page_translations if t.is_outdated]),\n 'num_page_translations_missing': num_pages - page_translations.count()\n })\n\n return render(\n request,\n self.template_name,\n {\n **self.base_context,\n 'languages': languages\n }\n )\n","repo_name":"digitalfabrik/coldaid-backend","sub_path":"src/cms/views/analytics/translation_coverage_view.py","file_name":"translation_coverage_view.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"40"} +{"seq_id":"39933900898","text":"import pytest\nfrom msys.registration import get_types\n\n\n@pytest.mark.types\n@pytest.mark.parametrize(\n \"key, exists\",\n [\n (\"vector\", True),\n (\"dont exist\", False),\n ],\n)\ndef test_find_types(key, exists):\n types = get_types()\n assert (key in types.keys()) == exists","repo_name":"Modular-Design/msys-opt","sub_path":"tests/types/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"2592902617","text":"import json\nfrom time import sleep\nfrom agama_nostr.client import Client \nfrom agama_nostr.tools import get_nostr_key, print_head\nfrom agama_nostr.nips import meta_struct\n\n\nDEBUG = True\nNOSTR_SEC = get_nostr_key() \nnc = Client(NOSTR_SEC) # nostr_client\n\n#print_head(\"my relays list\")\n#nc.print_myrelays_list()\n\nnpub1 = \"npub1.........user id.................... \"\n#npub1 = \"npub1relay9mayryh7vnvmf5e250sskuw07fk2z6gkm585zltehlwhj9stx05lg\"\n\nnc.set_filter_meta(npub1)\nnc.set_subscription_id()\n\nnc.single_relay_event()\nnc.message_pool_events()\n\nif DEBUG:\n print(\"-\"*39)\n print(nc.last_event_msg)\n print(\"-\"*39)\nmeta_data = nostr_client.last_event_msg.content\ndata = json.loads(meta_data)\n\n#print(\"meta_data\",data)\n#print(len(data))\n\nprint(\"=\"*39)\nfor meta in meta_struct:\n try:\n print(meta + \":\",data[meta])\n except:\n print(meta,\"?\")\n","repo_name":"agora3/agora-py-nostr","sub_path":"apps/nostr_meta_info.py","file_name":"nostr_meta_info.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"24135910338","text":"#!/usr/bin/env python3\n\nimport argparse\nfrom tools import read_input\nfrom tools import ImageMap\nfrom tools import Cell\nfrom tools import draw_frame\n\nparser = argparse.ArgumentParser(description='Solution day 13, part 1')\nparser.add_argument(\n '--test',\n dest='test',\n action='store_const',\n const=True,\n default=False,\n)\n\n\ndef main(options):\n if options.test:\n filename = 'sample2.txt'\n else:\n filename = 'input.txt'\n state = read_input(filename)\n while True:\n state.tick()\n if state.crashed:\n print('Crashed: {}'.format(state.crashed))\n state.cars = [\n car \n for car in state.cars\n if car not in state.crashed\n ]\n print('current num of cars: {}'.format(len(state.cars)))\n if len(state.cars) == 1:\n break\n print(state)\n print(state.cars)\n car = state.cars[0]\n solution = '{},{}'.format(car.x, car.y)\n print('Solution of parf 2 is {}'.format(solution))\n\n\nif __name__ == '__main__':\n options = parser.parse_args()\n main(options)\n","repo_name":"euribates/advent_of_code_2018","sub_path":"13/part_02.py","file_name":"part_02.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"39727833597","text":"#!/usr/bin/env python3\n# coding: utf-8\n\nimport sys\nimport gensim, logging\nimport random\nimport string\n\n# Что вообще происходит?\n# logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\n\n# ----------------------------------------------\n# Ниже демонстрируется процесс тренировки модели\n# ----------------------------------------------\n# на вход модели даём текстовый файл, каждое предложение на отдельной строчке\n# argument = 'text.txt'\n\n# создаём структуру данных для модели\n# data = gensim.models.word2vec.LineSentence(argument)\n\n# инициализируем модель (параметры в скобочках: data - данные, size - размер вектора, window -размер окна наблюдения,\n# min_count - мин. частотность слова в корпусе, которое мы берем,\n# sg - используемый алгоритм обучение (0 - CBOW, 1 - Skip-gram))\n# model = gensim.models.Word2Vec(data, size=500, window=10, min_count=2, sg=0)\n# чтобы модель использовала меньше RAM (но теперь её нельзя менять!)\n# model.init_sims(replace=True)\n\n# Смотрим, сколько в модели слов\n# print(len(model.vocab))\n\n# сохраняем\n# model.save('my.model')\n\n# ---------------------------------------------\n# Ниже демонстрируется процесс работы с моделью\n# ---------------------------------------------\n# берём модель\nour_model = 'model/lurk.model'\n\n# загружаем модель\nif our_model.endswith('.vec.gz'):\n model = gensim.models.Word2Vec.load_word2vec_format(our_model, binary=False)\nelif our_model.endswith('.bin.gz'):\n model = gensim.models.Word2Vec.load_word2vec_format(our_model, binary=True)\nelse:\n model = gensim.models.Word2Vec.load(our_model)\n# Чтобы модель требовала меньше RAM\nmodel.init_sims(replace=True)\n\nprint('FINISH')\n\n'''\n# скажем, нам интересны такие слова (пример для русского языка)\nwords = ['рациональность']\n\n# играем со словами\nfor word in words:\n # есть ли слово в модели? Может быть, и нет\n if word in model:\n print(word)\n # смотрим на вектор слова (его размерность 1000, смотрим на первые 10 чисел)\n print(model[word][:10])\n # выдаем 10 ближайших соседей слова:\n for i in model.most_similar(positive=[word], topn=150):\n # слово + коэффициент косинусной близости\n print(i[0], i[1])\n print('\\n')\n else:\n # Увы!\n print(word + 'is not present in the model')\n\n# находим косинусную близость пары слов\nprint(model.similarity('человек', 'космонавт'))\n\n# найди лишнее!\n# print(model.doesnt_match('яблоко груша виноград банан лимон картофель'.split()))\nprint(model.doesnt_match('яблоко груша виноград банан лимон картофель термодинамика'.split()))\n\n# реши пропорцию!\nprint(model.most_similar(positive=['уксус', 'груша', 'виноград', 'банан', 'лимон', 'картофель','термодинамика']))\n# print(model.most_similar(positive=['привет', 'человек', 'забор'], topn=10))\n'''\n\n#print(model.most_similar(positive=['в']))\n\n# original_text = \"Продолжаем заниматься познавательной физкультурой на примере двух столичных девушек вместе с «PROспорт» и сетью фитнес-клубов «Адреналин». В центре сюжета — по-прежнему тренер Кристина Ладутько и ее подопечная Карина Макоста. Заканчивается адаптационный период. Пока тренировки происходят пару раз в неделю и имеют общий характер. Вскоре их станет три, занятия приобретут узкую направленность. Пока же этого не произошло, разбираемся с рационом Карины. \" \\\n# \"Простите за патетику посреди выходного, но жизнь — сложная штука. И сколько бы человек ни тренировался, по большей части успех его преображения определяет рацион. Кристина анализировала рацион Карины, выходило примерно 1500 калорий на день. Не худший показатель, но калории были не самые качественные. Тренер докрутила дневной счетчик до 1700 и изменила составляющие. \" \\\n# \"Нам не нужно много сахара, так что никаких сладких йогуртов и шоколадок. Нам нужны сложные углеводы без перебора и белок, который мышцам строиться и жить помогает. \" \\\n# \"Погнали в магазин!\"\n\ndef getText(original_text, ton):\n\n print(ton)\n\n # original_text = \"Во поле береза стояла, \" \\\n # \"Во поле кудрявая стояла, \" \\\n # \"Люли, люли, стояла. \" \\\n # \"Некому березу заломати, \" \\\n # \"Некому кудряву заломати, \" \\\n # \"Люли, люли, заломати. \" \\\n # \"Как пойду я в лес, погуляю, \" \\\n # \"Белую березу заломаю, \" \\\n # \"Люли, люли, заломаю. \" \\\n # \"Срежу я с березы три пруточка, \" \\\n # \"Сделаю себе я три гудочка, \" \\\n # \"Люли, люли три гудочка. \" \\\n # \"Четвертую балалайку, \" \\\n # \"Пойду я на новые сени, \" \\\n # \"Люли, люли на сени. \" \\\n # \"Стану в балалаечку играти, \" \\\n # \"Стану я милого будити. \" \\\n # \"Люли, люли, будити: \" \\\n # \"Встань ты, мой милый, проснися, \" \\\n # \"Ты, душа моя, пробудися. \" \\\n # \"Люли, люли пробудися. \" \\\n # \"Пойдем в терем веселиться. \" \\\n # \"Пойдем в терем веселиться, \" \\\n # \"Люли, люли, веселиться. \"\n\n # original_text = \"Обычно атмосфера в Хогвартсе перед рождественскими праздниками была светлой и радостной. Большой зал уже был убран в зелёный и красный цвета. Эта традиция, древняя, как сам Хогвартс, появилась после свадьбы слизеринки и гриффиндорца, случившейся на святки и ставшей символом дружбы, которая выше предубеждений и разделения на факультеты. Со временем этот обычай распространился даже на магловские страны.\"\n\n original_text_list = original_text.split(' ')\n\n final_text = []\n\n #окончания\n\n import pymorphy2\n morph = pymorphy2.MorphAnalyzer()\n\n def reductionOfWords(master_word, slave_word):\n master_word_analysis = morph.parse(master_word)\n slave_word_analysis = morph.parse(slave_word)\n\n if len(master_word_analysis) < 1 or len(slave_word_analysis) < 1:\n return False\n\n slave = slave_word_analysis[0]\n\n for master in master_word_analysis:\n required_master_grammers = False\n master_grammers = master.tag._str.split()\n if len(master_grammers) > 1:\n required_master_grammers = master_grammers[1]\n\n slave_lexems = slave.lexeme\n for slave_lexem in slave_lexems:\n\n if slave_lexem.tag.POS != master.tag.POS:\n continue\n\n slave_grammers = slave_lexem.tag._str.split()\n\n if len(slave_grammers) <= 1:\n if slave_lexem.word == master.word:\n break\n return slave_lexem.word\n\n\n required_slave_grammers = slave_grammers[1]\n\n if required_master_grammers == required_slave_grammers:\n if slave_lexem.word == master.word:\n break\n return slave_lexem.word\n\n return False\n\n for original_world in original_text_list:\n\n if not original_world:\n continue\n\n optimise_world_without_mass = original_world.replace(\"«\", \"\").replace(\"»\", \"\").replace(\".\",\"\").replace(\",\",\"\")\n optimise_world_without_mass_lower = optimise_world_without_mass.lower()\n if optimise_world_without_mass_lower not in model:\n final_text.append(original_world)\n continue\n\n if ton != '':\n synonyms = model.most_similar(positive=[optimise_world_without_mass_lower, ton], topn=5)\n else:\n synonyms = model.most_similar(positive=[optimise_world_without_mass_lower], topn=5)\n\n final_synonyms = []\n for _synonym in synonyms:\n synonym = reductionOfWords(optimise_world_without_mass_lower, _synonym[0])\n if synonym:\n final_synonyms.append(synonym)\n\n if not final_synonyms:\n final_text.append(original_world)\n continue\n synonym = final_synonyms[random.randint(0,(len(final_synonyms)-1))]\n # synonym = model.most_similar(positive=[optimise_world_without_mass_lower], topn=20)[random.randint(0,0)][0]\n\n if optimise_world_without_mass[0] != optimise_world_without_mass_lower[0]:\n synonym = synonym[0].upper() + synonym[1:]\n\n\n final_text.append(str.replace(original_world, optimise_world_without_mass, synonym))\n\n # print(original_text)\n # print(' '.join(final_text))\n\n return ' '.join(final_text)\n\n\n\n\n\n # Want to know more? Read API docs!\n# http://radimrehurek.com/gensim/models/word2vec.html","repo_name":"panfillich/mix_project","sub_path":"servers/bot/gener.py","file_name":"gener.py","file_ext":"py","file_size_in_byte":11318,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"23879082501","text":"#!/usr/bin/env python3\n\nimport os\nfrom rich.text import Text\n\n\ndef read_adventure(adventure_file, console, game_window):\n import TRPG\n\n f = open((\"Adventures/\" + adventure_file + \".txt\"), mode=\"r\")\n lines = f.readlines()\n lines = \"\".join(lines)\n lines = lines.split(\"*encounter*:\")[1:]\n\n encounters = {}\n\n for encounter_index in range(len(lines)):\n encounter_raw = lines[encounter_index]\n\n encounter_name = encounter_raw.split(\"\\n\")[0]\n encounter_name = encounter_name.rstrip(\" \").lstrip(\" \")\n\n encounter_raw = \"\\n\".join(encounter_raw.split(\"\\n\")[1:])\n\n encounter_description = encounter_raw.split(\"*options*\")[0]\n encounter_description = encounter_description.rstrip(\"\\n \")\n encounter_description = encounter_description.lstrip(\"\\n \")\n\n encounter_options = encounter_raw.split(\"*options*\")[1]\n encounter_options = encounter_options.rstrip(\"\\n \")\n encounter_options = encounter_options.lstrip(\"\\n \")\n encounter_options = encounter_options.split(\"*option*\\n\")[1:]\n\n options = []\n results = []\n\n for option_index in range(len(encounter_options)):\n option_raw = encounter_options[option_index]\n option = option_raw.split(\"*results*\\n\")[0]\n option = option.rstrip(\"\\n \")\n option = option.lstrip(\"\\n \")\n\n options.append(option)\n\n option_results = option_raw.split(\"*results*\\n\")[1]\n option_results = option_results.split(\"\\n\")\n try:\n option_results.remove(\"\")\n except ValueError:\n option_results = option_results\n\n results.append(option_results)\n\n options = dict(enumerate(options))\n results = dict(enumerate(results))\n\n encounters[encounter_name] = TRPG.Encounter(\n encounter_name,\n encounter_description,\n options,\n results,\n console,\n game_window,\n )\n\n f.close()\n return encounters\n\n\ndef choose_adventure(game_state, console, game_window):\n\n import TRPG\n\n os.system(\"clear\")\n\n adventure_list = [\n f.split(\".\")[0] for f in os.listdir(\"Adventures\") if f.endswith(\"txt\")\n ]\n text = Text(\"Which adventure are you taking today?\", justify=\"center\")\n options = dict(enumerate(adventure_list))\n options[len(adventure_list)] = \"Return\"\n\n adventure_menu = TRPG.Menu(text, options, console, game_window)\n adventure_menu.print_menu()\n adventure_menu.print_options()\n choice = adventure_menu.choice()\n\n if choice == (len(adventure_list)):\n TRPG.initialize_game(game_state, console, game_window)\n else:\n adventure = read_adventure(adventure_list[choice], console, game_window)\n game_state.adventure = adventure\n","repo_name":"cordeirossauro/TRPG","sub_path":"Adventures/adventures.py","file_name":"adventures.py","file_ext":"py","file_size_in_byte":2821,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"40"} +{"seq_id":"22764900645","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Oct 23 21:47:23 2023\r\n\r\n@author: USER\r\n\"\"\"\r\n\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nurl = 'https://www.esunbank.com/zh-tw/personal/deposit/rate/forex/foreign-exchange-rates'\r\nheader = {\r\n 'User-Agent':\r\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'\r\n }\r\ndata = requests.get(url,headers = header)\r\ndata.encoding = 'utf-8'\r\ndata = data.text.strip()\r\nsoup = BeautifulSoup(data,'html.parser')\r\nrate = soup.find(id = 'exchangeRate')\r\ntable = rate.find('table')\r\ntbody = table.find('tbody')\r\ntd = tbody.find_all('td')\r\nfor row in td:\r\n print(row.text.strip())","repo_name":"ruoxinwu/pythonhw1","sub_path":"1023_hw.py","file_name":"1023_hw.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"16176910418","text":"import graphene\n\nfrom backend.blog.service import CountVotes\nfrom django.core.exceptions import PermissionDenied\nfrom backend.votes.schema.types import VotesCountNode\nfrom backend.votes.service import ToVote\n\n\n# noinspection PyMethodMayBeStatic\nclass Vote(graphene.Mutation):\n votes_count = graphene.Field(VotesCountNode)\n\n class Arguments:\n instance_id = graphene.ID()\n action = graphene.String()\n model_name = graphene.String()\n\n def mutate(self, info, **kwargs):\n if not info.context.user.is_authenticated:\n raise PermissionDenied('Сначала необходимо осуществить вход в систему')\n voter = ToVote(\n user_id=info.context.user.id,\n instance=kwargs['instance_id'],\n action=kwargs['action'],\n model_name=kwargs['model_name']\n )\n voter.execute()\n\n votes_counter = CountVotes(\n info.context.user.id,\n kwargs['model_name'],\n instance_id=kwargs['instance_id']\n )\n votes_count = votes_counter.execute()\n votes_count['id'] = f'__{kwargs[\"model_name\"].lower()}_{kwargs[\"instance_id\"]}'\n return Vote(votes_count=votes_count)\n\n\nclass Mutation(graphene.ObjectType):\n vote = Vote.Field()\n","repo_name":"IngvarListard/nuxt-wagtail-blog","sub_path":"backend/votes/schema/mutation.py","file_name":"mutation.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"42216949699","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nfrom google.api_core.client_options import ClientOptions\nfrom google.cloud import documentai # type: ignore\nfrom split_pages import split_pages\nfrom typing import Optional\nfrom bs4 import BeautifulSoup\nimport time\nimport re\nimport os\nimport json\nimport requests\n\nPROJECT_ID = \"REPLACE_WITH_PROJECT_ID\"\nLOCATION = \"REPLACE_WITH_LOCATION\"\nPROCESSOR_ID = \"REPLACE_WITH_PROCESSOR_ID\"\n\n# function to process PDFs using Document AI\n# reference: https://cloud.google.com/document-ai/docs/send-request\ndef process_document_sample(\n project_id: str,\n location: str,\n processor_id: str,\n file_path: str,\n mime_type: str,\n field_mask: Optional[str] = None,\n processor_version_id: Optional[str] = None,\n) -> None:\n opts = ClientOptions(api_endpoint=f\"{location}-documentai.googleapis.com\")\n\n client = documentai.DocumentProcessorServiceClient(client_options=opts)\n\n if processor_version_id:\n name = client.processor_version_path(\n project_id, location, processor_id, processor_version_id\n )\n else:\n name = client.processor_path(project_id, location, processor_id)\n\n with open(file_path, \"rb\") as image:\n image_content = image.read()\n\n raw_document = documentai.RawDocument(\n content=image_content, mime_type=mime_type)\n\n request = documentai.ProcessRequest(\n name=name, raw_document=raw_document, field_mask=field_mask\n )\n\n result = client.process_document(request=request)\n\n document = result.document\n\n return document.text\n\n# function that switches location of VPN for a different IP address\ndef switchVPN():\n global switched\n\n os.system(f\"nordvpn -c\")\n\n # wait until this VPN is connected\n time.sleep(15)\n print(\"IP CHANGED\")\n switched = True\n\n\n# vpn switched flag\nswitched = False\n\n# chromedriver configs\ndriver_path = './chromedriver.exe'\nusername = \"ayushpandeynp\"\nuser_data_dir = f\"C:\\\\Users\\\\{username}\\\\AppData\\\\Local\\\\Google\\\\Chrome\\\\User Data\"\nprofile_dir = 'Default'\n\nchrome_options = webdriver.ChromeOptions()\nchrome_options.add_argument(f\"--user-data-dir={user_data_dir}\")\nchrome_options.add_argument(f\"--profile-directory={profile_dir}\")\n\nservice = Service(driver_path)\ndriver = webdriver.Chrome(service=service, options=chrome_options)\n\n# initial scraping URL\nurl = 'https://persistent.library.nyu.edu/arch/NYU00020'\ndriver.get(url)\n\n# let Chrome take some time to load NYU credentials from its saved passwords\ntime.sleep(5)\n\n# make data directory\nif not os.path.exists(\"data\"):\n os.makedirs(\"data\")\n\ntry:\n wait = WebDriverWait(driver, 30)\n\n # click on Login after creds are loadeds\n button = wait.until(EC.element_to_be_clickable(\n (By.CSS_SELECTOR, 'button[name=\"_eventId_proceed\"]')))\n button.click()\n\n # perform the search query - JN \"Harvard Business Review\"\n search_input = wait.until(\n EC.element_to_be_clickable((By.ID, 'Searchbox1')))\n search_input.send_keys('JN \"Harvard Business Review\"')\n\n # click on search button\n submit_button = wait.until(\n EC.element_to_be_clickable((By.ID, 'SearchButton')))\n submit_button.click()\n\n # to keep track of the page number\n pageNumber = 1\n\n # pdf count\n pdf_count = 0\n\n # if running on multiple machines make necessary search changes\n input(\"Make changes and press Enter to continue...\")\n\n # to keep track of the number of articles gone through\n count = 0\n limit = driver.find_element(\n By.CSS_SELECTOR, '.content-header .page-title').text.split(\" \")[-1]\n limit = re.sub(r\"[^0-9]\", \"\", limit)\n limit = int(limit)\n\n while count < limit:\n # check if we need to click on the Login button\n if driver.current_url.startswith(\"https://shibboleth.nyu.edu/idp/profile/SAML2\"):\n print(\"Login detected!\")\n button = wait.until(EC.element_to_be_clickable(\n (By.CSS_SELECTOR, 'button[name=\"_eventId_proceed\"]')))\n button.click()\n\n current_tab = driver.current_window_handle\n\n title_links = driver.find_elements(By.CLASS_NAME, 'title-link')\n if len(title_links) == 0:\n # this means the search results page has crashed, so we need to switch VPN\n print(\"No links found! Switching VPN...\")\n switchVPN()\n driver.refresh()\n continue\n\n links = []\n for link in title_links:\n links.append(link.get_attribute('href'))\n\n # these are the metadata fields we want to scrape\n fields = [\"Title:\", \"Authors:\", \"Source:\", \"Document Type:\", \"Subject Terms:\", \"Author Affiliations:\",\n \"Abstract:\", \"Company/Entity:\", \"NAICS/Industry Codes:\", \"Geographic Terms:\"]\n\n # helper function to clean up the metadata fields\n def y(x): return x.lower().replace(\":\", \"\").replace(r\" \", \"_\")\n\n # this is where actual scraping happens\n data = []\n href_count = 0\n while href_count < len(links):\n href = links[href_count]\n try:\n driver.execute_script(\"window.open(arguments[0]);\", href)\n driver.switch_to.window(driver.window_handles[-1])\n\n try:\n # if VPN is switched, NYU will ask for login again, so waiting until credentials are loaded on Chrome\n if switched:\n time.sleep(5)\n\n # we need to click on the Login button again if this happens\n if driver.current_url.startswith(\"https://shibboleth.nyu.edu/idp/profile/SAML2\"):\n print(\"Login detected!\")\n button = wait.until(EC.element_to_be_clickable(\n (By.CSS_SELECTOR, 'button[name=\"_eventId_proceed\"]')))\n button.click()\n except:\n pass\n\n # resetting the switched variable\n switched = False\n\n # the components that store the metadata\n citation_fields = wait.until(\n EC.presence_of_element_located((By.ID, 'citationFields')))\n html = citation_fields.get_attribute('innerHTML')\n\n # parse metadata html\n soup = BeautifulSoup(html, 'html.parser')\n alltext = soup.find_all(string=True)\n\n # a dictionary to store the metadata\n dct = dict.fromkeys([y(f) for f in fields])\n try:\n for i, text in enumerate(alltext):\n if text.strip() in fields:\n key = y(text)\n\n # one field may have multiple values\n c = i\n val = []\n while alltext[c + 1].strip() and \":\" != alltext[c + 1].strip()[-1]:\n v = alltext[c + 1].strip()\n\n # minor cleaning\n if key == \"authors\":\n v = re.sub(r\"[0-9*]+\", \"\", v)\n elif key == \"subject_terms\":\n v = v.replace(r\"*\", \"\")\n\n if len(v) > 1:\n val.append(v)\n\n c += 1\n\n # source needs to be broken down\n if key == \"source\":\n source = val[0].split(\" \")\n\n # published = item after \"Harvard Business Review\"\n published = source[3][:-1]\n dct[\"published\"] = published\n\n # volume + issue = [4 to 7] joined by spaces\n volume_issue = \" \".join(source[4:8])[:-1]\n dct[\"volume/issue\"] = volume_issue\n\n # page = [8 and 9] joined by spaces\n pg = \" \".join(source[8:10])\n dct[\"page\"] = pg\n\n # extra_info = rest of source joined by spaces\n extra_info = \" \".join(source[10:])\n dct[\"extra_info\"] = extra_info\n\n dct[key] = val[0] if len(val) == 1 else val\n except:\n with open(\"metadataErrors.txt\", \"a\") as errFile:\n errFile.write(href + \"\\n\")\n\n # now after getting the metadata, we need full text\n try:\n # HTML Full Text\n html_full_text = driver.find_element(\n By.LINK_TEXT, 'HTML Full Text')\n html_full_text.click()\n\n fulltext = wait.until(EC.presence_of_element_located(\n (By.CLASS_NAME, 'full-text-content')))\n html = fulltext.get_attribute('innerHTML')\n soup = BeautifulSoup(html, 'html.parser')\n alltext = soup.find_all(string=True)\n\n dct[\"html/pdf\"] = \"html\"\n dct[\"full_text\"] = \"\\n\".join(\n [txt.strip() for txt in alltext])\n\n except:\n # PDF Full Text\n try:\n dct[\"html/pdf\"] = \"pdf\"\n\n pdf_full_text = driver.find_element(\n By.LINK_TEXT, 'PDF Full Text')\n pdf_full_text.click()\n\n iframe = wait.until(\n EC.presence_of_element_located((By.ID, 'pdfIframe')))\n src = iframe.get_attribute('src')\n response = requests.get(src)\n\n with open(f\"data/pdf{pdf_count}.pdf\", \"wb\") as f:\n f.write(response.content)\n dct[\"filename\"] = f\"pdf{pdf_count}.pdf\"\n pdf_count += 1\n \n # Document OCR has a 15 page limit. To bypass this, we split the PDF into multiple PDFs, each with no more than 15 pages\n pdfs = split_pages(f\"data/{dct['filename']}\", 15)\n\n text = \"\"\n for pdf in pdfs:\n text += process_document_sample(\n PROJECT_ID,\n LOCATION,\n PROCESSOR_ID,\n pdf,\n \"application/pdf\",\n \"text\",\n )\n\n dct[\"full_text\"] = text\n\n except:\n # if neither HTML nor PDF parsing worked, skip this article, and write the URL to a file\n with open(\"pdfErrorURLs.txt\", \"a\") as errFile:\n errFile.write(href + \"\\n\")\n\n href_count += 1\n count += 1\n continue\n\n # if we get here, we have successfully scraped the article\n data.append(dct)\n\n # now onto the next article\n href_count += 1\n count += 1\n except:\n # if an exception occurs, we need to switch VPN\n # exception is global because there can be multiple network exceptions, any of which will trigger a VPN switch\n print(\"Exception occurred! Switching VPN...\")\n\n with open(\"exceptionURLs.txt\", \"a\") as errFile:\n errFile.write(href + \"\\n\")\n\n # VPN Switch\n switchVPN()\n\n # write the data to a file [Typically 20 articles per page, less if errors]\n data = json.dumps(data)\n\n with open(f\"data/PAGE_{pageNumber}.json\", \"w\") as f:\n f.write(data)\n pageNumber += 1\n\n # close all tabs except the first one, where we move to the next page\n try:\n for tab in driver.window_handles:\n if tab != current_tab:\n driver.switch_to.window(tab)\n driver.close()\n\n driver.switch_to.window(current_tab)\n\n next = wait.until(EC.element_to_be_clickable(\n (By.CSS_SELECTOR, 'a[title=\"Next\"]')))\n next.click()\n except:\n print(\"Next button not found!\")\n if count >= limit:\n print(\"No more pages\")\n break\n\nexcept Exception as e:\n # error handling\n print(f\"An error occurred: {str(e)}\")\n\nfinally:\n # close the driver\n print(\"FINISHED TASK\")\n","repo_name":"ayushpandeynp/scraping-nyu-libraries","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":13050,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"17628227296","text":"import os\nimport json\nfrom goblet import Goblet, goblet_entrypoint, Response\nfrom slack_sdk.signature import SignatureVerifier\nfrom slack_sdk import WebhookClient, errors\nfrom google.cloud import secretmanager\n\napp = Goblet(function_name=\"IAM-permission-provision\")\ngoblet_entrypoint(app)\n\n\n@app.http()\ndef provision_iam_request(request):\n \"\"\"Main method\n \"\"\"\n # get slack signature secret from secret manager\n secret_client = secretmanager.SecretManagerServiceClient()\n signing_secret = secret_client.access_secret_version(\n request={\"name\": os.environ.get(\"SIGNATURE_SECRET_ID\")}\n ).payload.data.decode(\"UTF-8\")\n # validate request using the signature secret\n if not is_valid_signature(\n request.headers, request.get_data(as_text=True), signing_secret\n ):\n return Response(\"Forbidden\", status_code=403)\n # parse the slack action\n payload = json.loads(request.form[\"payload\"])\n action = payload[\"actions\"][0]\n action_id = action[\"action_id\"]\n action_value = action[\"value\"]\n user = ' '.join(payload[\"user\"][\"name\"].split('.'))\n project, resource_type, resource_name, principal, role, region, user_email = action_value.split(\",\")\n # get slack webhooks from secret manager\n secret_client = secretmanager.SecretManagerServiceClient()\n webhook = secret_client.access_secret_version(\n request={\"name\": os.environ.get(\"WEBHOOK_SECRET_ID\")}\n ).payload.data.decode(\"UTF-8\")\n # Sends to the status slack channel open to the whole company\n status_slack_client = WebhookClient(webhook)\n # Edits the original message to show that it has been responded to\n response_url = payload[\"response_url\"]\n response_slack_client = WebhookClient(response_url)\n if action_id == \"request_approve\":\n try:\n if resource_type == \"bucket\":\n add_bucket_iam_access(project, resource_name, role, principal)\n elif resource_type == \"secret\":\n add_secret_iam_access(project, resource_name, role, principal)\n elif resource_type == \"topic\":\n add_topic_iam_access(project, resource_name, role, principal)\n elif resource_type == \"subscription\":\n add_subscription_iam_access(project, resource_name, role, principal)\n elif resource_type == \"bq-table\":\n add_bq_table_iam_access(project, resource_name, role, principal)\n elif resource_type == \"function\":\n add_function_iam_access(project, resource_name, role, principal, region)\n elif resource_type == \"cloud-run\":\n add_run_iam_access(project, resource_name, role, principal, region)\n elif resource_type == \"registry\":\n add_artifact_registry_iam_access(project, resource_name, role, principal, region)\n elif resource_type == \"project\":\n add_project_iam_access(project, role, principal)\n else:\n app.log.error(f\"Unsupported resource: {resource_type}\")\n send_status_message(\n status_slack_client, project, resource_type, resource_name, role, principal, region, user_email, \"Resource not supported\"\n )\n return\n except Exception as e:\n app.log.error(f\"Error while provisioning: {e}\")\n for client in (status_slack_client, response_slack_client):\n send_status_message(\n client, project, resource_type, resource_name, role, principal, region, user_email, f\"Error while provisioning: {e}\"\n )\n return Response(\"Error while provisioning\", status_code=400)\n app.log.info(f\"Added {principal} with {role} to {resource_name} in {project}\")\n app.log.info(\"Sending approved status message\")\n for client in (status_slack_client, response_slack_client):\n send_status_message(\n client, project, resource_type, resource_name, role, principal, region, user_email, f\"Approved by {user}\"\n )\n elif action_id == \"request_reject\":\n app.log.info(\"Sending rejected status message\")\n for client in (status_slack_client, response_slack_client):\n send_status_message(\n client, project, resource_type, resource_name, role, principal, region, user_email, f\"Rejected by {user}\"\n )\n\n\ndef is_valid_signature(headers, data, signing_secret):\n \"\"\"Validates the request from the Slack integration\n \"\"\"\n timestamp = headers[\"x-slack-request-timestamp\"]\n signature = headers[\"x-slack-signature\"]\n verifier = SignatureVerifier(signing_secret)\n return verifier.is_valid(data, timestamp, signature)\n\n\ndef send_status_message(client, project, resource_type, resource_name, role, principal, region, user_email, status):\n \"\"\"Sends request status message through the provided slack client\n \"\"\"\n try:\n response = client.send(\n text=\"fallback\",\n blocks=[\n {\n \"type\": \"header\",\n \"text\": {\n \"type\": \"plain_text\",\n \"text\": \"IAM Request\",\n \"emoji\": True,\n },\n },\n {\n \"type\": \"section\",\n \"text\": {\n\t\t\t\t \"type\": \"mrkdwn\",\n\t\t\t\t \"text\": f\"Project: {project}\"\n\t\t\t },\n },\n {\n \"type\": \"section\",\n \"text\": {\n\t\t\t\t \"type\": \"mrkdwn\",\n \"text\": f\"Resource Type: {resource_type}\"\n }\n },\n {\n \"type\": \"section\",\n \"text\": {\n\t\t\t\t \"type\": \"mrkdwn\",\n\t\t\t\t \"text\": f\"Resource Name: {resource_name if not region else region + '/' + resource_name}\"\n\t\t\t },\n },\n {\n \"type\": \"section\",\n \"text\": {\n\t\t\t\t \"type\": \"mrkdwn\",\n\t\t\t\t \"text\": f\"Role: {role}\"\n\t\t\t },\n },\n {\n \"type\": \"section\",\n \"text\": {\n\t\t\t\t \"type\": \"mrkdwn\",\n\t\t\t\t \"text\": f\"Principal: {principal}\"\n\t\t\t },\n },\n {\n \"type\": \"section\",\n \"text\": {\n\t\t\t\t \"type\": \"mrkdwn\",\n\t\t\t\t \"text\": f\"Status: {status}\"\n\t\t\t },\n },\n {\n \"type\": \"section\",\n \"text\": {\n\t\t\t\t \"type\": \"mrkdwn\",\n\t\t\t\t \"text\": f\"Requester: {user_email}\"\n\t\t\t },\n },\n ],\n )\n app.log.info(response.status_code)\n except errors.SlackApiError as e:\n app.log.error(e)\n \n\ndef add_binding(client, resource, role, principal):\n \"\"\"Generic add-binding procedure\n Not every resource has this method available though. Need to check to the docs\n \"\"\"\n policy = client.get_iam_policy(request={\"resource\": resource})\n policy.bindings.add(role=role, members=[principal])\n client.set_iam_policy(request={\"resource\": resource, \"policy\": policy})\n\n\ndef add_bucket_iam_access(project, bucket_name, role, principal):\n \"\"\"Adds bucket access for the principal\n \"\"\"\n from google.cloud import storage\n\n storage_client = storage.Client(project)\n bucket = storage_client.bucket(bucket_name)\n policy = bucket.get_iam_policy(requested_policy_version=3)\n policy.bindings.append({\"role\": role, \"members\": {principal}})\n bucket.set_iam_policy(policy)\n\n\ndef add_secret_iam_access(project, secret_name, role, principal):\n \"\"\"Adds secret access for the principal\n \"\"\"\n client = secretmanager.SecretManagerServiceClient()\n secret_path = f\"projects/{project}/secrets/{secret_name}\"\n add_binding(client, secret_path, role, principal)\n\n\ndef add_topic_iam_access(project, topic_name, role, principal):\n \"\"\"Adds topic access for the principal\n \"\"\"\n from google.cloud import pubsub_v1\n\n client = pubsub_v1.PublisherClient()\n topic_path = f\"projects/{project}/topics/{topic_name}\"\n add_binding(client, topic_path, role, principal)\n\n\ndef add_subscription_iam_access(project, subscription_name, role, principal):\n \"\"\"Adds subscription access for the principal\n \"\"\"\n from google.cloud import pubsub_v1\n\n client = pubsub_v1.SubscriberClient()\n subscription_path = f\"projects/{project}/subscriptions/{subscription_name}\"\n add_binding(client, subscription_path, role, principal)\n\n\ndef add_bq_table_iam_access(project, table_name, role, principal):\n \"\"\"Adds table access for the principal\n\n :param table_name: {table's dataset}.{table name}\n \"\"\"\n from google.cloud import bigquery\n\n client = bigquery.Client()\n name = f\"{project}.{table_name}\"\n table = client.get_table(name)\n policy = client.get_iam_policy(table)\n policy.bindings.append({\"role\": role, \"members\": {principal}})\n client.set_iam_policy(table, policy)\n\n\ndef add_function_iam_access(project, function_name, role, principal, region):\n \"\"\"Adds function access for the principal\n \"\"\"\n from google.cloud import functions_v1\n\n client = functions_v1.CloudFunctionsServiceClient()\n function_path = f\"projects/{project}/locations/{region}/functions/{function_name}\"\n add_binding(client, function_path, role, principal)\n\n\ndef add_run_iam_access(project, service_name, role, principal, region):\n \"\"\"Adds cloud run service access for the principal\n \"\"\"\n from googleapiclient import discovery\n from oauth2client.client import GoogleCredentials\n\n credentials = GoogleCredentials.get_application_default()\n client = discovery.build(\"run\", \"v1\", credentials=credentials).projects().locations().services()\n from google.iam.v1.policy_pb2 import Policy\n resource = f\"projects/{project}/locations/{region}/services/{service_name}\"\n policy = client.getIamPolicy(resource=resource).execute()\n bindings = policy.get(\"bindings\", [])\n bindings.append({\"role\": f\"{role}\", \"members\": [f\"{principal}\"]})\n policy[\"bindings\"] = bindings\n response = client.setIamPolicy(resource=resource, body={\"policy\": policy}).execute()\n\n\ndef add_project_iam_access(project, role, principal):\n \"\"\"\n \"\"\"\n from google.cloud import resourcemanager_v3\n\n client = resourcemanager_v3.ProjectsClient()\n project_path = f\"projects/{project}\"\n add_binding(client, project_path, role, principal)\n\n\ndef add_artifact_registry_iam_access(project, registry_name, role, principal, region):\n \"\"\"\n \"\"\"\n from google.cloud import artifactregistry_v1beta2\n\n client = artifactregistry_v1beta2.ArtifactRegistryClient()\n registry_path = f\"projects/{project}/locations/{region}/repositories/{registry_name}\"\n add_binding(client, registry_path, role, principal)\n\n","repo_name":"premisedata/gcp-tutorials","sub_path":"008-slack-approval-process/IAM-permission-provision/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10894,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"42"} +{"seq_id":"8447007246","text":"import os\nimport boto3\nimport json\nfrom datetime import datetime, timedelta\n\nsagemaker = boto3.client('sagemaker')\ns3 = boto3.client('s3')\n\n\ndef handler(event, context):\n print(event)\n \n sagemaker_role = os.environ['SAGEMAKER_ROLE_ARN']\n resource_bucket = os.environ['RESOURCE_BUCKET']\n \n ts = datetime.now() # note TZ is UTC\n ts = ts.strftime(\"%Y%m%dT%H%M%S\")\n job_name = 'automl-job-'+ts #os.environ['JOB_NAME']\n \n csv_s3_uri = f's3://{resource_bucket}/input/training_data.csv'\n automl_config_file_key = 'config/automl_problem_config.json'\n \n \n # Define input data config for SageMaker\n input_data_config = [\n {\n 'DataSource': {\n 'S3DataSource': {\n 'S3DataType': 'S3Prefix',\n 'S3Uri': csv_s3_uri\n }\n }\n }\n ]\n\n # Define output data config for SageMaker\n output_data_config = {\n 'S3OutputPath': f's3://{resource_bucket}/autopilot-output/'\n }\n \n # Get AutoML Problem Dynamic Config file from S3\n automl_problem_config_s3 = s3.get_object(Bucket=resource_bucket, Key=automl_config_file_key)\n \n automl_problem_config_body = automl_problem_config_s3['Body'].read().decode('utf-8')\n \n automl_problem_config = json.loads(automl_problem_config_body)\n \n # Create the AutoML job\n response = sagemaker.create_auto_ml_job_v2(\n AutoMLJobName=job_name,\n AutoMLJobInputDataConfig=input_data_config,\n OutputDataConfig=output_data_config,\n RoleArn=sagemaker_role,\n AutoMLProblemTypeConfig=automl_problem_config\n )\n\n return {\n 'AutoMLJobResponse': response,\n 'AutoMLJobName': job_name\n }","repo_name":"aws/amazon-sagemaker-examples-community","sub_path":"autopilot/mlops/timeseries/aws-automl-ts-cdk/lambda/create-autopilot-job/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"42"} +{"seq_id":"7322121748","text":"import dace\nimport pickle\nimport math\nimport copy\n\nfrom typing import Generator, Dict, List, Tuple\nfrom collections import Counter\n\nfrom dace import SDFG, dtypes\nfrom dace.optimization import cutout_tuner\nfrom dace.sdfg.analysis.cutout import SDFGCutout\n\nfrom dace.transformation import subgraph as sg\nfrom dace.transformation.estimator import enumeration as en\nfrom dace.transformation.subgraph import helpers\nfrom dace.transformation import helpers as xfh\nfrom dace.optimization import utils as optim_utils\n\ntry:\n from tqdm import tqdm\nexcept (ImportError, ModuleNotFoundError):\n tqdm = lambda x, **kwargs: x\n\n\nclass SubgraphFusionTuner(cutout_tuner.CutoutTuner):\n\n def __init__(self, sdfg: SDFG, i, j, measurement: dtypes.InstrumentationType = dtypes.InstrumentationType.Timer) -> None:\n super().__init__(task=\"SubgraphFusion\", sdfg=sdfg, i=i, j=j)\n self.instrument = measurement\n\n def cutouts(self, sdfg=None):\n if sdfg is None:\n sdfg = self._sdfg\n\n for nsdfg_id, nsdfg in enumerate(sdfg.all_sdfgs_recursive()):\n for state in nsdfg.nodes():\n state_id = nsdfg.node_id(state)\n\n try:\n cutout = SDFGCutout.singlestate_cutout(state, *(state.nodes()), make_copy=False)\n yield cutout, f\"{nsdfg_id}.{state_id}.{state.label}\"\n except AttributeError:\n continue\n\n def config_from_key(self, key: str, cutout: dace.SDFG, **kwargs) -> Tuple[int, List[int]]:\n fusion_id = int(key)\n if fusion_id == 0:\n return (0, [])\n\n sp = list(self.space(cutout=cutout))\n return sp[fusion_id]\n\n def apply(self, config: Tuple[int, List[int]], label: str, **kwargs) -> None:\n if config[0] == 0:\n return\n\n nsdfg_id, state_id, _ = label.split(\".\")\n sdfg = list(self._sdfg.all_sdfgs_recursive())[int(nsdfg_id)]\n state_id = int(state_id)\n state = sdfg.node(state_id)\n nodes = state.nodes()\n cutout = SDFGCutout.singlestate_cutout(state, *(nodes), make_copy=False)\n\n map_ids = config[1]\n maps_ = list(map(cutout.start_state.node, map_ids))\n subgraph = helpers.subgraph_from_maps(sdfg=sdfg, graph=state, map_entries=maps_)\n\n subgraph_fusion = sg.CompositeFusion()\n subgraph_fusion.setup_match(subgraph, sdfg.sdfg_id, state_id)\n subgraph_fusion.allow_tiling = True\n subgraph_fusion.schedule_innermaps = dace.ScheduleType.GPU_Device\n if subgraph_fusion.can_be_applied(sdfg, subgraph):\n subgraph_fusion.apply(sdfg)\n\n def space(self, cutout: dace.SDFG) -> Generator[List[bool], None, None]:\n subgraphs = en.ConnectedEnumerator(cutout, cutout.start_state)\n yield 0, []\n\n for i, (subgraph, score) in enumerate(subgraphs):\n yield i + 1, list(map(lambda m: cutout.start_state.node_id(m), subgraph))\n\n def pre_evaluate(self, cutout: dace.SDFG, measurements: int, **kwargs) -> Dict:\n cutout.start_state.instrument = self.instrument\n\n new_kwargs = {\n \"space_kwargs\": {\n \"cutout\": cutout\n },\n \"cutout\": cutout.to_json(),\n \"measurements\": measurements,\n \"key\": lambda point: str(point[0])\n }\n return new_kwargs\n\n def evaluate(self, config, cutout, measurements: int, **kwargs) -> float:\n dreport = self._sdfg.get_instrumented_data()\n\n candidate = dace.SDFG.from_json(cutout)\n candidate.start_state.instrument = dace.InstrumentationType.GPU_Events\n for node in candidate.start_state:\n if isinstance(node, dace.nodes.MapEntry):\n break\n else:\n # Skip no-map-states\n return math.inf\n\n if config[0] == 0:\n # Baseline\n return self.measure(candidate, dreport, measurements)\n\n map_ids = config[1]\n if len(map_ids) < 2:\n return math.inf\n\n maps_ = list(map(candidate.start_state.node, map_ids))\n subgraph = helpers.subgraph_from_maps(sdfg=candidate, graph=candidate.start_state, map_entries=maps_)\n\n subgraph_fusion = sg.CompositeFusion()\n subgraph_fusion.setup_match(subgraph, candidate.sdfg_id, candidate.node_id(candidate.start_state))\n subgraph_fusion.allow_tiling = True\n subgraph_fusion.schedule_innermaps = dace.ScheduleType.GPU_Device\n if subgraph_fusion.can_be_applied(candidate, subgraph):\n subgraph_fusion.apply(candidate)\n else:\n return math.inf\n\n return self.measure(candidate, dreport, measurements)\n\n def _extract_patterns(self, best_configs: List[Tuple[str, List[int]]]):\n # Describe successful fusions as set of map descriptors\n subgraph_patterns = []\n for label, config in best_configs:\n nsdfg_id, state_id, _ = label.split(\".\")\n sdfg = list(self._sdfg.all_sdfgs_recursive())[int(nsdfg_id)]\n state_id = int(state_id)\n state = sdfg.node(state_id)\n nodes = state.nodes()\n cutout = SDFGCutout.singlestate_cutout(state, *(nodes), make_copy=False)\n\n pattern_desc = Counter()\n fusion_id, map_ids = self.config_from_key(config, cutout)\n if fusion_id == 0:\n continue\n\n for map_id in map_ids:\n map_entry = cutout.start_state.node(map_id)\n map_desc = SubgraphFusionTuner.map_descriptor(cutout.start_state, map_entry)\n pattern_desc.update({map_desc: 1})\n\n subgraph_patterns.append(pattern_desc)\n\n subgraph_patterns = [dict(s) for s in set(frozenset(d.items()) for d in subgraph_patterns)]\n subgraph_patterns = [Counter(s) for s in subgraph_patterns]\n\n return subgraph_patterns\n\n @staticmethod\n def transfer(sdfg: dace.SDFG, tuner, k: int = 5):\n assert isinstance(tuner, SubgraphFusionTuner)\n\n dreport = sdfg.get_instrumented_data()\n assert dreport is not None\n\n tuning_report = tuner.optimize(apply=False)\n best_configs = cutout_tuner.CutoutTuner.top_k_configs(tuning_report, k=k)\n subgraph_patterns = tuner._extract_patterns(best_configs)\n\n i = 0\n for nsdfg in sdfg.all_sdfgs_recursive():\n for state in nsdfg.states():\n i = i + 1\n\n top_maps = []\n for node in state.nodes():\n if isinstance(node, dace.nodes.MapEntry) and xfh.get_parent_map(state, node) is None:\n top_maps.append(node)\n\n if len(top_maps) < 2:\n continue\n\n # Check that cutout can be constructed.\n try:\n cutout = SDFGCutout.singlestate_cutout(state, *(state.nodes()), make_copy=False)\n cutout.start_state.instrument = dace.InstrumentationType.GPU_Events\n except AttributeError as e:\n continue\n\n while True:\n base_runtime = None\n best_pattern = None\n best_pattern_runtime = math.inf\n for j, pattern in enumerate(subgraph_patterns):\n maps = []\n for node in state.nodes():\n if isinstance(node, dace.nodes.MapEntry) and xfh.get_parent_map(state, node) is None:\n maps.append(node)\n\n if len(maps) < 2:\n break\n\n maps_desc = {}\n state_desc = Counter()\n for map_entry in maps:\n map_desc = SubgraphFusionTuner.map_descriptor(state, map_entry)\n state_desc.update({map_desc: 1})\n\n if not map_desc in maps_desc:\n maps_desc[map_desc] = []\n\n maps_desc[map_desc].append(map_entry)\n\n included = True\n for key in pattern:\n if not key in state_desc or pattern[key] > state_desc[key]:\n included = False\n break\n\n if not included:\n continue\n\n # State is applicable to fusion, compute baseline once.\n if base_runtime is None:\n baseline = SDFGCutout.singlestate_cutout(state, *(state.nodes()), make_copy=False)\n baseline.start_state.instrument = dace.InstrumentationType.GPU_Events\n\n dreport_ = {}\n for cstate in baseline.nodes():\n for dnode in cstate.data_nodes():\n array = baseline.arrays[dnode.data]\n if array.transient:\n continue\n try:\n data = dreport.get_first_version(dnode.data)\n dreport_[dnode.data] = data\n except:\n continue\n\n base_runtime = optim_utils.subprocess_measure(baseline, dreport_, i=192, j=192)\n best_pattern_runtime = base_runtime\n if base_runtime == math.inf:\n break\n\n # Construct subgraph greedily\n subgraph_maps = []\n for desc in pattern:\n num = pattern[desc]\n subgraph_maps.extend(maps_desc[desc][:num])\n\n # Apply\n experiment_sdfg_ = SDFGCutout.singlestate_cutout(state, *(state.nodes()), make_copy=False)\n experiment_state_ = experiment_sdfg_.start_state\n experiment_maps_ids = list(map(lambda me: experiment_state_.node_id(me), subgraph_maps))\n\n # Unnecessary?\n experiment_sdfg = copy.deepcopy(experiment_sdfg_)\n experiment_state = experiment_sdfg.start_state\n\n experiment_maps = list(map(lambda m_id: experiment_state.node(m_id), experiment_maps_ids))\n experiment_subgraph = helpers.subgraph_from_maps(sdfg=experiment_sdfg, graph=experiment_state, map_entries=experiment_maps)\n\n subgraph_fusion = sg.CompositeFusion()\n subgraph_fusion.setup_match(experiment_subgraph, experiment_sdfg.sdfg_id,\n experiment_sdfg.node_id(experiment_state))\n subgraph_fusion.allow_tiling = True\n subgraph_fusion.schedule_innermaps = dace.ScheduleType.GPU_Device\n if subgraph_fusion.can_be_applied(experiment_sdfg, experiment_subgraph):\n try:\n subgraph_fusion.apply(experiment_sdfg)\n except:\n continue\n\n dreport_ = {}\n for cstate in experiment_sdfg.nodes():\n for dnode in cstate.data_nodes():\n array = experiment_sdfg.arrays[dnode.data]\n if array.transient:\n continue\n try:\n data = dreport.get_first_version(dnode.data)\n dreport_[dnode.data] = data\n except:\n continue\n\n experiment_state.instrument = dace.InstrumentationType.GPU_Events\n pattern_runtime = optim_utils.subprocess_measure(experiment_sdfg, dreport_, i=192, j=192)\n\n if pattern_runtime >= best_pattern_runtime:\n continue\n\n best_pattern_runtime = pattern_runtime\n best_pattern = subgraph_maps\n\n\n if best_pattern is not None:\n subgraph = helpers.subgraph_from_maps(sdfg=nsdfg, graph=state, map_entries=best_pattern)\n subgraph_fusion = sg.CompositeFusion()\n subgraph_fusion.setup_match(subgraph, nsdfg.sdfg_id, nsdfg.node_id(state))\n subgraph_fusion.allow_tiling = True\n subgraph_fusion.schedule_innermaps = dace.ScheduleType.GPU_Device\n subgraph_fusion.apply(nsdfg)\n\n best_pattern = None\n best_pattern_runtime = math.inf\n base_runtime = None\n else:\n break\n\n\n @staticmethod\n def map_descriptor(state: dace.SDFGState, map_entry: dace.nodes.MapEntry) -> str:\n tasklets = filter(lambda node: isinstance(node, dace.nodes.Tasklet), map(lambda edge: edge.dst, state.out_edges(map_entry)))\n tasklets = set(tasklets)\n\n desc = []\n for tasklet in tasklets:\n label = tasklet.label.split(\"_\")[:-2]\n label = \"_\".join(label)\n desc.append(label)\n\n return \":\".join(desc)\n","repo_name":"spcl/dace","sub_path":"dace/optimization/subgraph_fusion_tuner.py","file_name":"subgraph_fusion_tuner.py","file_ext":"py","file_size_in_byte":13662,"program_lang":"python","lang":"en","doc_type":"code","stars":426,"dataset":"github-code","pt":"42"} +{"seq_id":"42500787824","text":"from pytube import YouTube\r\nimport os\r\nb=\"YOUTUBE TO MP3 CONVERTER\"\r\na=\"Created by NAVEEN KUMAR S and ARJUN P\"\r\nprint(b.center(80,'*'))\r\nprint(a.center(80,'*'))\r\n# url input from user\r\nyt = YouTube(\r\n str(input(\"Enter the URL of the video you want to download: \\n>> \")))\r\n \r\n# extract only audio\r\nvideo = yt.streams.filter(only_audio=True).first()\r\n \r\n# check for destination to save file\r\nprint(\"Enter the destination (leave blank for current directory)\")\r\n#destination = str(input(\">> \")) or '.'\r\nsongs = input(\"enter path:\")\r\ndestination = r\"songs\"\r\n \r\n# download the file\r\nout_file = video.download(output_path=destination)\r\n \r\n# save the file\r\nbase, ext = os.path.splitext(out_file)\r\nnew_file = base + '.mp3'\r\nos.rename(out_file, new_file)\r\n \r\n# result of success\r\nprint(yt.title + \" has been successfully downloaded.\")","repo_name":"0EnIgma1/YOUTUBE-to-MP3-converter","sub_path":"ytmp.py","file_name":"ytmp.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"42"} +{"seq_id":"11671790003","text":"import numpy as np\nimport numpy.typing as npt\nimport scipy.signal\nimport scipy.stats\nimport faultevent.event as evt\nimport faultevent.signal as sig\nfrom faultevent import util as utl\n\n\ndef irfs(data: sig.Signal,\n spos1: npt.ArrayLike,\n ordmin: float,\n ordmax: float,\n sigsize: int = 400,\n sigshift: int = -150,\n enedet_max_loc_error: int = 10,\n n_iter: int = 10,\n threshold_trials = 10,) -> np.ndarray:\n \n\n # initial iteration\n ordf1, _ = evt.find_order(spos1, ordmin, ordmax)\n mu1, kappa1 = evt.fit_vonmises(ordf1, spos1)\n z1 = evt.map_circle(ordf1, spos1)\n crt1 = scipy.stats.vonmises.pdf(z1, kappa1, loc=mu1)\n idx1 = np.argsort(crt1)\n signat1 = utl.estimate_signature(data, spos1[idx1], crt1[idx1],\n sigsize, max_error = enedet_max_loc_error,\n n0 = sigshift)\n\n # ith iteration\n det1 = sig.MatchedFilterEnvelopeDetector(signat1)\n stat1 = det1.statistic(data)\n hys1 = .2\n norm1 = np.linalg.norm(signat1)\n thr1 = utl.best_threshold(stat1, ordmin, ordmax, hys=hys1,\n n=threshold_trials)/norm1\n det_list = [det1]\n for i in range(1, n_iter-1):\n stat_i = det_list[i-1].statistic(data)\n thr_i = thr1*np.linalg.norm(det_list[i-1].h)\n cmp_i = sig.Comparison.from_comparator(stat_i, thr_i, thr_i*hys1)\n spos_i = np.asarray(sig.matched_filter_location_estimates(cmp_i))\n ordf_i, _ = utl.find_order(spos_i, ordmin, ordmax)\n mu_i, kappa_i = evt.fit_vonmises(ordf_i, spos_i)\n z_i = evt.map_circle(ordf_i, spos_i)\n crt_i = scipy.stats.vonmises.pdf(z_i, kappa_i, loc=mu_i)\n idx_sorted = np.argsort(crt_i)\n sig_i = utl.estimate_signature(data, spos_i[idx_sorted],\n crt_i[idx_sorted],\n len(det_list[i-1].h))\n det_i = sig.MatchedFilterEnvelopeDetector(sig_i)\n det_list.append(det_i)\n return sig_i\n\n\ndef medest(x: npt.ArrayLike, f0: npt.ArrayLike, its: int=10) -> np.ndarray:\n \"\"\"Minimum entropy deconvolution (R. A. Wiggins, 1978).\n Given input x, estimates the filter (FIR) that maximises the output\n kurtosis (and effectively impulsiveness), where f0 is the initial\n guess.\"\"\"\n L = len(f0)\n N = len(x)\n X = np.zeros((L, N))\n X[0] = x\n for l in range(1, L):\n X[l][l:] = x[:-l]\n \n f = f0\n for i in range(its):\n y = X.T@f\n fa = np.sum(y**2)/np.sum(y**4)\n fb = np.linalg.solve(X@X.T, X@(y**3).T)\n f = fa*fb\n return f\n\n\ndef medfilt(signal: sig.Signal, filt: npt.ArrayLike):\n \"\"\"Returns a signal filtered using an MED filter\"\"\"\n n = len(filt)\n out = np.convolve(signal.y, filt, mode=\"valid\") # filtering\n return sig.Signal(out, signal.x[n-1:],\n uniform_samples=signal.uniform_samples)\n\n\ndef skfilt(signal: sig.Signal, nperseg: int = 1000):\n \"\"\"Filters the given signal using a spectral kurtosis (SK) derived\n filter through an STFT estimator. The filterbank filter bandwidth\n can be controlled through the nperseg parameter. For best\n performance, this parameter should follow the two conditions given\n in the original paper by J. Antoni et al.\"\"\"\n if not signal.uniform_samples:\n raise ValueError(\"Samples must be uniformly spaced.\")\n ts = signal.x[1]-signal.x[0]\n _, _, Y = scipy.signal.stft(signal.y, nperseg=nperseg, fs=1/ts)\n S = lambda n: np.mean(abs(Y)**(2*n), axis=-1)\n K = S(2)/S(1)**2 - 2\n #K = scipy.stats.kurtosis(Y, axis=-1)\n sqrtK = np.sqrt(K*(K>0))\n Ym = Y*sqrtK[:,np.newaxis]\n t, out = scipy.signal.istft(Ym, nperseg=nperseg, fs=1/ts)\n return sig.Signal(out, t, uniform_samples=True)\n\n\ndef enedetloc(data: sig.Signal,\n ordmin: float,\n ordmax: float,\n enedetsize: int = 50,\n threshold_trials: int = 10) -> np.ndarray:\n \"\"\"Detect and return locations of events using an energy detector\"\"\"\n det = sig.EnergyDetector(enedetsize)\n stat = det.statistic(data)\n hys = .8\n thr = utl.best_threshold(stat, ordmin, ordmax, hys=hys, dettype=\"ed\",\n n=threshold_trials)\n cmp = sig.Comparison.from_comparator(stat, thr, hys*thr)\n spos = np.asarray(sig.energy_detector_location_estimates(cmp))\n return spos\n\n\ndef peak_detection(data: sig.Signal, ordc: float):\n \"\"\"Detect and localise events using a peak detection algorithm.\"\"\"\n rps = (data.x[1] - data.x[0]) # revs per sample, assuming uniform samples\n fps = rps*ordc # fault occurences per sample\n spf = int(1/fps) # samples per fault occurence\n peaks, _ = scipy.signal.find_peaks(data.y, height=0, distance=spf/2)\n spos = data.x[peaks]\n return spos\n\n\ndef score_med(data: sig.Signal,\n initial_filter: npt.ArrayLike,\n ordc: float,\n ordmin: float,\n ordmax: float,\n medfiltsize=100,) -> float:\n \"\"\"Score MED filtering using on detection metric\"\"\"\n # MED stuff\n medfiltest = medest(data.y, initial_filter)\n out = np.convolve(data.y, medfiltest, mode=\"valid\")\n env = abs(scipy.signal.hilbert(out))\n filtsigenv = sig.Signal(env, data.x[medfiltsize-1:],\n uniform_samples=data.uniform_samples)\n \n # detect and locate\n spos = peak_detection(filtsigenv, ordc)\n _, mag = utl.find_order(spos, ordmin, ordmax)\n score = mag/np.sqrt(len(spos))\n return score, medfiltest","repo_name":"arhusebo/signature-estimation","sub_path":"routines.py","file_name":"routines.py","file_ext":"py","file_size_in_byte":5565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"1316446583","text":"# Calcular o índice de massa corpórea - IMC\n\npeso = float(input('Digite seu peso: KG'))\naltura = float(input('Digite sua altura em metros: '))\n\nimc = peso / (altura ** 2)\n\nif imc < 18.5:\n print('Abaixo do peso')\nelif 18.5 <= imc <= 25:\n print('Peso ideal')\nelif 25 < imc <= 30:\n print('Sobrepeso')\nelif 30 < imc <= 40:\n print('Obesidade')\nelif imc > 40:\n print('Obesidade mórbida')","repo_name":"CodeAmorim/PythonCodes","sub_path":"ExercíciosPython/IMC.py","file_name":"IMC.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"72691527487","text":"import argparse\nimport functools\nimport re\nimport time\nimport sys\n\nimport rclpy\nimport rclpy.logging\nfrom rclpy.node import Node\n\nfrom rqt_gui_py.plugin import Plugin\nfrom std_msgs.msg import Float32, Header\nfrom system_modes.srv import ChangeMode\nfrom rcl_interfaces.msg import Log\nfrom diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue\n\nclass Metacontroller(Node):\n def __init__(self):\n super().__init__('metacontroller')\n self.diagnostics_sub_ = self.create_subscription(\n DiagnosticArray,\n \"/metacontroller/diagnostics\",\n self.diagnostics_cb, 1)\n self.current_mode = 'NORMAL'\n def change_mode(self, node_name, mode_name):\n cli = self.create_client(ChangeMode, '/'+node_name+'/change_mode')\n while not cli.wait_for_service(timeout_sec=1.0):\n print('service not available, waiting again...')\n req = ChangeMode.Request()\n req.node_name = node_name\n req.mode_name = mode_name\n\n future = cli.call_async(req)\n rclpy.spin_until_future_complete(self, future)\n if future.result() is not None:\n self.get_logger().info('Mode change completed')\n else:\n self.get_logger().error('Exception while calling service: %r' % future.exception())\n\n def diagnostics_cb(self, msg):\n for status in msg.status:\n if status.message == \"QA status\":\n for value in status.values:\n if value.key == \"energy\" and float(value.value) < 15.0 and self.current_mode == 'NORMAL':\n self.current_mode = 'ENERGY_SAVING'\n self.get_logger().info('Battery low detected, solving contingency...')\n self.change_mode(\"pilot\", self.current_mode)\n\ndef main(args=None):\n rclpy.init(args=args)\n node = Metacontroller()\n node.change_mode(\"pilot\", '__DEFAULT__')\n node.change_mode(\"pilot\", 'NORMAL')\n rclpy.spin(node)\n node.destroy()\n rclpy.shutdown()\n\nif __name__ == '__main__':\n main()","repo_name":"MROS-RobMoSys-ITP/Pilot-URJC","sub_path":"metacontroller_pilot/metacontroller_pilot/metacontroller_sim.py","file_name":"metacontroller_sim.py","file_ext":"py","file_size_in_byte":2054,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"42"} +{"seq_id":"15342588179","text":"'''\nCriar regex que:\n\n1. valida CPF \n2. vaida data\n3. Substitui/reorganiza a data\n4. Localiza padrão dentro de texto\n'''\n\nimport re\n\n# Dados\ncpf_tipo_1 = '123.456.789-00'\ncpf_tipo_2 = ' 123.456.789-00'\ncpf_tipo_3 = 'abc123.456.789-00def'\nemail_tipo_1 = 'gustavo@gmail.com'\ntelefone_tipo_1 = '(11) 91234-5678'\ncep_tipo_1 = '01234-010'\nvariavel_tipo_1 = 'snake_case '\nlog_tipo_1 = '1993-05-14 12:35:28 [INFO] Mensagem do log'\nfiltrar_url_tipo_1 = 'https://chat.openai.com/c/2ff015d6-2455-4db2-b22e-760c48055675'\nvalidar_cartao_de_credito_tipo_1 = '374245455400126'\n\n# Patterns\nvalidacao_de_cpf = re.compile(pattern=r'\\d{3}\\.\\d{3}\\.\\d{3}\\-\\d{2}')\nvalidacao_de_email = re.compile(pattern=r'^[a-zA-Z0-9._%+-]{3,7}@gmail.com') # abc@gmail.com ou abcdefg@gmail.com\nextracao_de_numeros_de_telefone = re.compile(pattern=r'\\([1-9]{2}\\)[ ][1-9]{4,5}[-][0-9]{4}') # (11) 91234-5678\nvalidacao_de_cep = re.compile(pattern=r'[0-9]{5}[-][0-9]{3}') # (11) 91234-5678\nvalidacao_de_variavel = re.compile(pattern=r'^\\w+\\s$') # snake_cases\nanalise_de_logs = re.compile(pattern=r'^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2} \\[INFO\\] .*$')\nfiltrar_url_em_texto = re.compile(pattern=r'https://\\S+')\n\n'''\nValidação de Números de Cartão de Crédito:\n\nExpressão Regular: \\b(?:\\d[ -]*?){13,16}\\b\nIsso pode ser usado para validar números de cartão de crédito, permitindo diferentes formatos e espaços em branco entre os dígitos.\nExtração de Tags HTML:\n\nExpressão Regular: <[^>]+>\nIsso pode ser usado para extrair tags HTML de um documento, tornando útil para análise de conteúdo da web.\nValidação de Senhas Fortes:\n\nExpressão Regular: ^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}\nIsso pode ser usado para validar senhas fortes, exigindo pelo menos uma letra maiúscula, uma letra minúscula, um dígito e um caractere especial.\nExtração de Endereços de IP:\n\nExpressão Regular: \\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b\nIsso pode ser usado para extrair endereços de IP de um texto maior.\n'''\n\n# Escolha\npadrao_escolhido = filtrar_url_em_texto # Escolha aqui o padrão validador\n\n# Ação\nbuscar = padrao_escolhido.search(filtrar_url_tipo_1)\n\nif buscar:\n print(buscar.group())\nelse:\n print('Não encontrado!')\n\n","repo_name":"GustavoRosas-Dev/estudos","sub_path":"expressoes_regulares/estudo_regex.py","file_name":"estudo_regex.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"18315941935","text":"from tensorflow.keras.models import Model\nimport tensorflow.keras.backend as K\nfrom config.Example_Config_Model_Visualizer import get_model_viz_config\nfrom constants.AI_params import *\nfrom models.modelSelector import select_2d_model\nfrom models.model_viz import print_layer_names, plot_cnn_filters_by_layer, plot_intermediate_2dcnn_feature_map\nimport matplotlib.image as mpltimage\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nif __name__ == '__main__':\n config = get_model_viz_config()\n\n model_weights_file = config[ClassificationParams.model_weights_file]\n model = select_2d_model(config)\n print('Reading weights ....')\n model.load_weights(model_weights_file)\n\n # # Gets all the config\n model_config = model.get_config()\n\n # # All Number of parameters\n print(F' Number of parameters: {model.count_params()}')\n # Number of parameters by layer\n # print(F' Number of parameters first CNN: {model.layers[3].count_params()}')\n\n # Example of plotting the filters of a single layer\n print_layer_names(model)\n plot_cnn_filters_by_layer(model.layers[1], 'Sobel filter learned :) ') # The harcoded 1 should change by project\n\n # ========= Here you need to build your test input different in each project ====\n input_file = '/home/olmozavala/Dropbox/MyProjects/OZ_LIB/AI_Template/TESTDATA/033.jpg'\n img = mpltimage.imread(input_file)\n input_array = np.expand_dims(np.expand_dims(img[:, :, 0], axis=2), axis=0)\n # ========= Here you need to build your test input different in each project ====\n\n # If you want to show the NN prediction\n output_NN = model.predict(input_array, verbose=1)\n plt.subplots(1,2)\n plt.subplot(1,2,1)\n plt.imshow(img)\n plt.subplot(1,2,2)\n plt.imshow(output_NN[0,:,:,0])\n plt.show()\n\n # =========== Output from the last layer (should be the same as output_NN\n inp = model.input # input placeholder\n outputs = [layer.output for layer in model.layers[1:]] # all layer outputs\n functors = [K.function([inp], [out]) for out in outputs] # evaluation functions\n layer_outs = [func([input_array]) for func in functors]\n\n plt.subplots(1,2)\n plt.subplot(1,2,1)\n plt.imshow(img)\n plt.subplot(1,2,2)\n plt.imshow(layer_outs[0][0][0,:,:,0])\n plt.show()\n\n\n # ============Output from intermediate layers\n intermediate_layer_model = Model(inputs=model.input,\n outputs=model.get_layer('conv2d').output)\n\n intermediate_output = intermediate_layer_model.predict(input_array)\n plot_intermediate_2dcnn_feature_map(intermediate_output, title='Intermediate layer')\n","repo_name":"olmozavala/lce_ml_detection","sub_path":"4_Visualize_Models.py","file_name":"4_Visualize_Models.py","file_ext":"py","file_size_in_byte":2672,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"2159285574","text":"#coding=utf8\n#!/usr/bin/env python\n\"\"\"\nAuthor:wuya @ smallteam\nDate: 13-7-2\n\"\"\"\n\nfrom __future__ import division, print_function, unicode_literals\nfrom feet8.dbop.attachment_mixin import AttachmentMixin\nfrom feet8.dbop.db_adapter import DbAdapter\nfrom feet8.utils.digest import url_digest\n\n__metaclass__ = type\n\n\nclass LegDbAdapter(DbAdapter, AttachmentMixin):\n _save_item_type = 'cover' #'cover'|'set'\n\n def save_item(self, item, spider=None):\n db = self.db_mod.db\n collection = item['collection']\n doc = item['doc']\n spec = {'url_hash': doc['url_hash']}\n if self._save_item_type == 'cover':\n db[collection].update(spec, doc, upsert=True, w=0)\n elif self._save_item_type == 'set':\n db[collection].update(spec, {'$set': doc}, upsert=True, w=0)\n\n def is_duplicate_request(self, request, item):\n db = self.db_mod.db\n collection = item['collection']\n url_hash = url_digest(request.url)\n spec = {'url_hash': url_hash}\n doc = db[collection].find_one(spec)\n if doc:\n return True\n else:\n return False\n","repo_name":"hackrole/scrapy-utils","sub_path":"other-source-bak/feet8/feet8/feet8/dbop/leg_db_adapter.py","file_name":"leg_db_adapter.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"42"} +{"seq_id":"27399211222","text":"# Library of Common Matrix Operations \n# These will be applied to various Matrix based problems\n# and Images\nimport numpy as np\nfrom numpy import asarray\nfrom math import pi, cos, sin\nfrom itertools import permutations\n\n# returns a square matrix for given dimension n and factor alpha\n# alpha != 1 can be used for uniform scaling, alpha = 1 gives identity matrix I\ndef id_mat(n,alpha):\n I = [[0 for x in range(n)] for x in range(n)]\n for i in range(n):\n I[i][i] = alpha\n return I\n\n\n# transpose of given matrix A\ndef transpose_mat(A):\n m = len(A)\n n = len(A[0])\n return [[A[j][i] for j in range(m)] for i in range(n)]\n\n\n# Prints an nD array or npArray in more concise format\n# this is not an explicit matrix operation, just an accessory to the library\ndef print_matrix(A):\n n = len(A[0])\n i = 1\n\n print(f\" |{[x for x in range(1,n+1)]}|\")\n for row in A:\n print(f\"|{i}|{row}|\")\n i = i + 1\n\n\n# create a square matrix based on scale factor\n# (if scaling factor = n, then original dimensions of matrix are scaled by 1/n)\n# can be used to shrink an image's dimensions and increase speed of operations performed\ndef scaled_mat(A,scale_factor):\n\tscaled_columns = [row[::scale_factor] for row in A]\n\treturn asarray([scaled_columns[i] for i in range(0, len(A), scale_factor)])\n\n\n# check for valid dimensions and implement matrix-matrix multiplication\ndef matmat(A , B):\n mA , nA = len(A), len(A[0])\n mB , nB = len(B), len(B[0])\n if nA == mB:\n C = [[0 for x in range(nB)] for x in range(mA)]\n for i in range(mA):\n for j in range(nB):\n row = [A[i][k] for k in range(mB)]\n col = [B[k][j] for k in range(mB)]\n C[i][j] = sum([row[i]*col[i] for i in range(len(row))])\n return asarray(C)\n else:\n print('Invalid Dimensions for Matrix-Matrix Multiplication')\n\n\n# check for valid dimensions and implement matrix-vector multiplication\ndef matvec(A , v):\n mA , nA = len(A), len(A[0])\n m = len(v)\n if nA == m:\n D = [0 for x in range(mA)]\n for i in range(mA):\n D[i] = sum([A[i][j]*v[j] for j in range(m)])\n return asarray(D)\n else:\n print('Invalid Dimensions for Matrix-Vector Multiplication')\n\n\n# rotation matrix for two dimensional applications\ndef rotation_mat_2d(theta):\n\treturn[[cos(theta), -sin(theta)], [sin(theta), cos(theta)]]\n\n\n# rotation matrix for three dimensional applications and specified axis of rotation\ndef rotation_mat_3d(axis,theta):\n\tif axis == 'x':\n\t\treturn[[1,0,0],[0,cos(theta), -sin(theta)], [0,sin(theta), cos(theta)]]\n\telif axis == 'y':\n\t\treturn[[cos(theta),0, sin(theta)],[0,1,0],[-sin(theta),0,cos(theta)]]\n\telif axis == 'z':\n\t\treturn[[cos(theta), -sin(theta), 0], [sin(theta), cos(theta),0],[0,0,1]]\n\telse:\n\t\tprint('Incorect Axis Given!')\n\n\t\n# triangle_index finds if given matrix containts a triangular configuration and specifies \n# which indices yeild the potential configuration\ndef triangle_index(A):\n\n if len(A) == len(A[0]):\n indices = [x for x in range(len(A))]\n perms = list(permutations(indices))\n\n for p in perms:\n perm_A = [A[p[i]] for i in range(len(p))]\n # gather and check diagonal entries in A to be nonzero\n diags_left = [perm_A[i][i] for i in range(len(A))]\n diags_right = [perm_A[i][(len(A)-1)-i] for i in (range(len(A)))]\n\n # check upper triangular left / lower triangular left\n if all(diags_left) == True:\n below_diags_left = [perm_A[row][col] for row in range(1, len(perm_A))\n for col in range(0,len(perm_A)-1) if col != row]\n above_diags_right = [perm_A[row][col] for row in range(0, len(perm_A)-1)\n for col in range(1,len(perm_A)) if col != row]\n if all(x == 0 for x in below_diags_left):\n print('Upper Right Triangular Configuration Exists')\n print(f'Row Indices : {p}')\n return p\n\n elif all(x == 0 for x in above_diags_right):\n print('Lower Right Triangular Configuration Exists')\n print(f'Row Indices : {p}')\n return p\n\n else:\n return 'No Triangular Configurations Exist'\n\n # check upper triangular right / lower triangular right\n elif all(diags_right) == True:\n below_diags_right = [perm_A[row][col] for row in range(1, len(perm_A))\n for col in range(1, len(perm_A)) if col != row]\n above_diags_left = [perm_A[row][col] for row in range(0, len(perm_A)-1)\n for col in range(0, len(perm_A)-1) if col != row]\n if all(x == 0 for x in below_diags_right):\n print('Upper Left Configuration Triangular Exists')\n print(f'Row Indices : {p}')\n return p\n\n elif all(x == 0 for x in above_diags_left):\n print('Lower Left Triangular Configuration Exists')\n print(f'Row Indices : {p}')\n return p\n\n else:\n print('No Triangular Configurations Exist')\n\n else:\n print('Incorrect Dimensions!')\n\n\n\n\n\n\n\n","repo_name":"brus041/Image_Website_Code","sub_path":"MatrixOpLibrary.py","file_name":"MatrixOpLibrary.py","file_ext":"py","file_size_in_byte":5393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"73092835005","text":"# @Email: dporwal985@gmail.com\r\n# @Project: Shop Analysis w/ Streamlit\r\n\r\n\r\nimport pandas as pd # pip install pandas openpyxl\r\n\r\ndf = pd.read_excel(\r\n io=\"Sample_Database4.xlsx\",\r\n engine=\"openpyxl\",\r\n sheet_name=\"Sheet1\",\r\n skiprows=1,\r\n usecols=\"B:R\",\r\n nrows=1000,\r\n)\r\n\r\nprint(df)\r\n","repo_name":"DhananjayPorwal/shop-analysis","sub_path":"dataFrame.py","file_name":"dataFrame.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"14225646379","text":"from unittest.mock import patch\nimport unittest\n\nfrom jinja2 import Template\nfrom pathlib import Path\n\nimport portinus\n\nclass TestMonitorInit(unittest.TestCase):\n\n def setUp(self):\n pass\n\n @patch('systemd_unit.Unit')\n def test_init(self, fake_unit):\n res = portinus.monitor.Service('foo')\n\n @patch('systemd_unit.Unit')\n @patch('portinus.get_template')\n def test__generate_service_file(self, fake_get_template, fake_unit):\n service = portinus.monitor.Service('foo')\n fake_get_template.return_value = Template(\"qwe {{name}} asd\")\n expected_output = \"qwe foo asd\"\n output = service._generate_service_file()\n self.assertEqual(output, expected_output)\n\n @patch('systemd_unit.Unit')\n @patch('portinus.get_template')\n def test__generate_timer_file(self, fake_get_template, fake_unit):\n service = portinus.monitor.Service('foo')\n fake_get_template.return_value = Template(\"qwe {{name}} asd\")\n expected_output = \"qwe foo asd\"\n output = service._generate_service_file()\n self.assertEqual(output, expected_output)\n \n @patch('systemd_unit.Unit')\n def test_ensure(self, fake_unit):\n service = portinus.monitor.Service('foo')\n service.ensure()\n self.assertEqual(fake_unit().ensure.call_count, 2)\n \n @patch('systemd_unit.Unit')\n def test_remove(self, fake_unit):\n service = portinus.monitor.Service('foo')\n service.remove()\n self.assertEqual(fake_unit().remove.call_count, 2)\n","repo_name":"justin8/portinus","sub_path":"tests/testMonitorInit.py","file_name":"testMonitorInit.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"300382471","text":"import xml.etree.ElementTree as ET\r\nimport subprocess\r\nimport ntpath\r\nimport os\r\nimport shutil\r\nimport tkinter as tk\r\nfrom tkinter import filedialog\r\nimport xlwings as xw\r\nimport re\r\n\r\nLibrary_section={}\r\nLibrary_temperature_section={}\r\n\r\n# XML Function -done\r\ndef load_XML_file(path_source):\r\n myXMLTree = ET.parse(path_source)\r\n return myXMLTree\r\n\r\n#This is read op seq file\r\ndef Read_XML_Op_Seq(XML_Tree):\r\n dict_op = {}\r\n myroot = XML_Tree.getroot()\r\n for op_seq in myroot.iter('Test_Suite_Data'):\r\n dict_op[\"OP_SEQ\"] = op_seq.attrib['Name']\r\n return dict_op\r\n\r\ndef Read_XML_Results(XML_Tree):\r\n ls_all_test=[]\r\n\r\n dict_single_test = {}\r\n myroot = XML_Tree.getroot()\r\n for x in myroot.iter('Test_Case_Result'):\r\n for test_name in x.iter('Test_Case_Data'):\r\n dict_single_test['Test_Name'] = test_name.attrib['Name']\r\n print(test_name.attrib)\r\n for y in x.iter(\"Parameters\"):\r\n for z in y.iter(\"Parameter\"):\r\n for p1 in z.iter(\"Actual_Parameter\"):\r\n #dict_single_test[p1.attrib['Name']] = p1.attrib['Name']\r\n print(p1.attrib, \" \")\r\n # if loop then one more time insert it\r\n loop_ctr = 0 # initliaze loop_ctr\r\n for value in p1.iter(\"Value\"):\r\n if loop_ctr == 0:\r\n dict_single_test[p1.attrib['Name']] = value.text\r\n else:\r\n if not( value.text is None):\r\n dict_single_test[p1.attrib['Name']] = dict_single_test[p1.attrib['Name']] + \",\" + value.text\r\n\r\n print(value.text)\r\n loop_ctr += 1\r\n\r\n # add into the list and clear current dictionary\r\n ls_all_test.append(dict_single_test)\r\n dict_single_test={} # initiliaze back\r\n return ls_all_test\r\n\r\n# Tdr to XML decompress - done\r\ndef tdr_and_xml_file_process(path_source):\r\n single_element=[]\r\n path_tdr = path_source # This is a tdr file only\r\n directory , path_xml = ntpath.split(path_source)\r\n # expect there is a _decompress.tdr for every file\r\n new_path_xml = path_xml.replace(\"_COMPRESSED.tdr\", \".xml\")\r\n single_element = path_xml.split(\"_\")\r\n return path_tdr, directory + \"\\\\\" + new_path_xml,single_element[2] #2 is the SN\r\n\r\ndef decompress_process(path_tdr, path_xml,compress_path):\r\n # String construction ( this is temporary)\r\n process_to_run = \"{} -d \\\"{}\\\" \\\"{}\\\" \".format(compressFile, path_tdr, path_xml)\r\n # process_to_run = \"C:\\\\Users\\\\willlee\\\\Documents\\\\Working Tools\\\\BNTDRGeneratorFiles\\\\StreamCompressor -d \"\\\r\n # + \" \\\"\" + path_tdr + \"\\\"\" + \" \" + \"\\\"\" + path_xml + \"\\\"\"\r\n try :\r\n output2 = subprocess.run(process_to_run)\r\n except output2.returncode !=0:\r\n print (\"Decompress file not working properly\")\r\n\r\n# Port Data to notepad file using SN as fileName\r\ndef CreateNewFolderAndFile(path_source,SN):\r\n found = False\r\n path_tdr = path_source # This is a tdr file only\r\n directory, path_xml = ntpath.split(path_source)\r\n new_directory = directory + \"\\\\\" + \"results\"\r\n # list_directories = os.listdir(directory)\r\n # for current_directory in list_directories:\r\n # if current_directory == \"results\":\r\n # found = True\r\n # if not found:\r\n # os.mkdir(new_directory)\r\n return directory\r\n\r\ndef WritelistIntoFile(directory, SN, list_result,dict_opseq ):\r\n file_construction = directory + \"\\\\\"+ SN + \"_result.txt\"\r\n with open(file_construction,\"a+\") as f:\r\n op_seq_text = \"OP_SEQ : \" + dict_opseq[\"OP_SEQ\"]\r\n f.write(op_seq_text)\r\n f.write (\"\\n------------------------------\\n\")\r\n # Get from list_result\r\n for dict_test in list_result:\r\n #extract the keys value\r\n test_name_text = \"TEST_NAME : \" + dict_test[\"Test_Name\"]\r\n f.write(test_name_text)\r\n f.write(\"\\n------------------------------\\n\")\r\n for i in range(1, len(list(dict_test.keys()))):\r\n # first key need ignored\r\n\r\n key_value = list(dict_test.keys())[i]\r\n if not dict_test[key_value] is None:\r\n test_value = list(dict_test.keys())[i] + \":\" + dict_test[key_value]\r\n f.write(test_value + \"\\n\")\r\n f.write(\"\\n------------------------------\\n\")\r\n\r\n\r\ndef loading_Library_section():\r\n\r\n Library_section[\"Wait for 15 Minutes\"] = \"0\"\r\n Library_section[\"Record Leakage J1\"] = \"8\"\r\n Library_section[\"Record V Tune\"] = \"10\"\r\n Library_section[\"Tuning Sensitivity\"] = \"11\"\r\n Library_section[\"Record Leakage J2\"] = \"12\"\r\n Library_section[\"IF Out Min Frequency\"] = \"15\"\r\n Library_section[\"IF Out Max Frequency\"] = \"16\"\r\n Library_section[\"Record IF Out 20 dBm\"] = \"17\"\r\n Library_section[\"Record IF Out 24\"] = \"18\"\r\n Library_section[\"IF Output Variation\"] = \"19\"\r\n Library_section[\"Worst Case Spur 45 to 75 MHz\"] = \"22\"\r\n Library_section[\"Worst Case Spur 100 to 125 MHz\"] = \"24\"\r\n Library_section[\"Record Leakage J3\"] = \"25\"\r\n Library_section[\"Minimum RF Input.vi\"] = \"28\"\r\n Library_section[\"Find File\"] = \"0\"\r\n Library_section[\"Record Leakage J4\"] = \"30\"\r\n Library_section[\"Linearity\"] = [\"33\",\"34\",\"3\",\"6\",\"5\"]\r\n Library_section[\"Move File\"] = \"0\"\r\n Library_section[\"LO Spur\"] = \"37\"\r\n Library_section[\"Other Spurs\"] = \"38\"\r\n Library_section[\"Record Current\"] = \"42\"\r\n Library_section[\"Frequency Drift\"] = \"43\"\r\n\r\ndef loading_library_temp():\r\n Library_temperature_section[\"876\"] = \"G3\" #Data 60 deg C\r\n Library_temperature_section[\"871\"] = \"E3\" #Data 25 deg C\r\n Library_temperature_section[\"875\"] = \"F3\" #Data 0 deg C\r\n Library_temperature_section[\"896\"] = \"H3\" #Post Seal 25c\r\n\r\ndef txt_populate_To_Excel(main_path_folder,templateFile):\r\n #load library and load template file if library and template path is empty\r\n First_Character=\"\"\r\n SubSeq_Characters=\"\"\r\n\r\n if len(Library_section) ==0 :\r\n loading_Library_section()\r\n\r\n if len(Library_temperature_section) ==0:\r\n loading_library_temp()\r\n #if location_excel_template\r\n file_location=[]\r\n file_location = look_for_result_rxtfile(main_path_folder) # all _result.txt should be in filelocation list\r\n for single_file in file_location:\r\n # create a path for excel\r\n # create template_file_path\r\n #excel_file_path = os.path.join(main_path_folder,\r\n if os.path.splitext(single_file)[1] == \".txt\":\r\n template_file = xw.Book(templateFile)\r\n single_file = single_file.replace(\"\\\\\",\"/\")\r\n SN_file_Name = single_file.split(\"/\")[5] + \"_report.xlsx\"\r\n # enter the SN into the excel\r\n template_file.sheets[\"Sheet1\"].range(\"F2\").value = SN_file_Name\r\n excel_file_name = os.path.join(main_path_folder, single_file.split(\"/\")[5],SN_file_Name)\r\n #open txt file\r\n with open(single_file, \"r\") as f:\r\n txtline = f.readline()\r\n while(txtline):\r\n if \"OP_SEQ\" in txtline:\r\n trim_space = re.sub('\\s+',' ',txtline.split(\":\")[1])\r\n Home_Excel_Position = Library_temperature_section[trim_space.split()[0]]\r\n First_Character= Home_Excel_Position[0:1] # Column Character\r\n SubSeq_Characters = Home_Excel_Position[1:] # digit\r\n if \"TEST_NAME\" in txtline:\r\n # location for excel\r\n test_name = txtline.split(\":\")[1]\r\n trim_a = re.sub(\"\\s+\", ' ', test_name).strip()\r\n location = Library_section[trim_a]\r\n # convert location and SubSeq_Character into Integer\r\n if isinstance(location,list):\r\n pass\r\n else:\r\n int_location = int(location)\r\n int_home_position = int(SubSeq_Characters)\r\n actual_location = First_Character + str(int_location + int_home_position)\r\n while(txtline != \"\\n\"):\r\n txtline = f.readline()\r\n if \"Scalar Data\" in txtline:\r\n measurement_value = txtline.split(\":\")[1].strip() # split :\r\n measurement_value = measurement_value.split(\",\")[0] # split ,\r\n # Check the value and convert the value accordingly to MHz\r\n if int_location == 11 or int_location == 43:\r\n # do the conversion to MHz\r\n measurement_value = int(measurement_value) * 1e-6\r\n template_file.sheets[\"Sheet1\"].range(actual_location).value = measurement_value\r\n if \"Data cluster\" in txtline:\r\n measurement_value = txtline.split(\":\")[1].strip() # split :\r\n measurement_value_list = measurement_value.split(\",\")\r\n for idx, measurement_value in enumerate(measurement_value_list):\r\n #for i in range(0, len(measurement_value_list)): #replace with upper for\r\n actual_location = First_Character + str(int(location[idx]) + int_home_position)\r\n template_file.sheets[\"Sheet1\"].range(actual_location).value = measurement_value_list[idx]\r\n txtline = f.readline()\r\n template_file.save(excel_file_name)\r\n template_file.close()\r\n\r\ndef look_for_result_rxtfile(main_path_folder):\r\n all_result_files=[]\r\n for root, dirs,files in os.walk(main_path_folder):\r\n for dir in dirs:\r\n secondary_path = os.path.join(main_path_folder,dir)\r\n for sec_root, sec_dir, sec_files in os.walk(secondary_path):\r\n for sec_file in sec_files:\r\n if sec_file.find(\"_result.txt\") !=1 :\r\n # found\r\n all_result_files.append(os.path.join(secondary_path, sec_file))\r\n return all_result_files\r\n\r\ndef File_Cp_To_folder(folder):\r\n #loop thru the folder\r\n list_directories = os.listdir(folder)\r\n # look for _COMPRESSED.tdr only\r\n for directory in list_directories:\r\n if directory.find(\"_COMPRESSED.tdr\") != -1:\r\n # split it to get SN\r\n SN = directory.split(\"_\")[2]\r\n # Use this SN look to see whether folder had created\r\n d = os.path.join(folder, SN)\r\n # If no directory, make a new one\r\n if not os.path.isdir(d):\r\n os.mkdir(d)\r\n # doing copy file to folder\r\n source = os.path.join(folder, directory)\r\n shutil.copy(source, d)\r\n\r\n\r\ndef initialize():\r\n for root,dirs,files in os.walk(os.getcwd()):\r\n print (root)\r\n print (files)\r\n # look for the below files\r\n if 'Microsemi data sheet template.xlsx' in files and 'StreamCompressor.exe' in files:\r\n return True, root + \"\\\\Microsemi data sheet template.xlsx\" , root + \"\\\\StreamCompressor.exe\"\r\n return False, None, None\r\n\r\nif __name__ == \"__main__\":\r\n #File_Cp_To_folder( \"C:\\\\Users\\\\willlee\\\\Desktop\\\\Testing\")\r\n #Initiliaze\r\n continueToRun, templateFile, compressFile = initialize()\r\n loading_Library_section()\r\n loading_library_temp()\r\n #Done\r\n loop_ctr = 1\r\n fileProvided = True\r\n while (fileProvided):\r\n root = tk.Tk()\r\n root.withdraw()\r\n folder_path = filedialog.askdirectory()\r\n if os.path.isdir(folder_path): # Main directory\r\n for root, dirs,files in os.walk(folder_path):\r\n amount_of_folder = len(dirs)\r\n for dir in dirs:\r\n fileprocess= os.path.join(root, dir)\r\n # read the folder\r\n # loop thru the folder\r\n for single_file in os.listdir(fileprocess):\r\n print (single_file)\r\n path_tdrA = os.path.join(fileprocess,single_file)\r\n path_tdr, path_xml, SN = tdr_and_xml_file_process(path_tdrA)\r\n decompress_process(path_tdr, path_xml,compressFile)\r\n XMLTree = load_XML_file(path_xml)\r\n dict_op = Read_XML_Op_Seq(XMLTree)\r\n ls_all_test = Read_XML_Results(XMLTree)\r\n new_directory = CreateNewFolderAndFile(path_tdr, SN)\r\n WritelistIntoFile(new_directory, SN, ls_all_test, dict_op)\r\n #main_path_folder = \"C:\\\\Users\\\\willlee\\\\Desktop\\\\Microsemi MVR data\"\r\n txt_populate_To_Excel(folder_path, templateFile)\r\n else:\r\n fileProvided = False\r\n # if os.path.exists(file_path):\r\n # orig_file_path = file_path\r\n # orig_file_dir = os.path.dirname(file_path)\r\n# Testing on the excel file\r\n\r\n # create window selection\r\n# path_tdr = \"C:\\\\Users\\\\willlee\\\\Desktop\\\\New folder\\\\MICR9905101PEN_134435C-01L_3261782_8-22-2022_20-16-23_4438_COMPRESSED.tdr\"\r\n# path_xml = \"C:\\\\Users\\\\willlee\\\\Desktop\\\\New folder\\\\def.xml\"\r\n# path_tdr, path_xml,SN = tdr_and_xml_file_process(path_tdr)\r\n# decompress_process(path_tdr, path_xml)\r\n# XMLTree= load_XML_file(path_xml)\r\n# Read_XML_Op_Seq(XMLTree)\r\n# Read_XML_Results(XMLTree)\r\n# print()\r\n# new_directory= CreateNewFolderAndFile(path_tdr,'3261782')\r\n# WritelistIntoFile(new_directory,'3261782',ls_all_test,dict_op)","repo_name":"williamleeIao/Report_Generation","sub_path":"Report_XML.py","file_name":"Report_XML.py","file_ext":"py","file_size_in_byte":13961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"74948049087","text":"import os\n\nfrom pathlib import Path\n\nimport pickle\n\nimport random\n\nimport time\n\nfrom io import StringIO\n\nfrom csv import writer\n\nimport gc\n\n\n\nimport numpy as np\n\nimport pandas as pd\n\nimport librosa\n\nimport librosa.display\n\nimport matplotlib.pyplot as plt\n\nfrom tqdm import tqdm_notebook\n\nimport IPython\n\nimport IPython.display\n\n# import PIL\n\n\n\nimport torch\n\nimport torch.nn as nn\n\nimport torch.nn.functional as F\n\n\n\nfrom fastai import *\n\nfrom fastai.vision import *\n\nfrom fastai.vision.data import *\nmodels_list = (\n\n # trained weights of CNN-model-1 inspired by mhiro2\n\n (Path('../input/freesoundaudiotagging2019ebouteillonsolution/fat2019ssl4multistage/work/'), 'stage-2_fold-{fold}.pkl'),\n\n (Path('../input/freesoundaudiotagging2019ebouteillonsolution/fat2019ssl4multistage/work/'), 'stage-10_fold-{fold}.pkl'),\n\n (Path('../input/freesoundaudiotagging2019ebouteillonsolution/fat2019ssl4multistage/work/'), 'stage-11_fold-{fold}.pkl'),\n\n # trained weights of VGG-16\n\n (Path('../input/freesoundaudiotagging2019ebouteillonsolution/fat2019ssl8vgg16full/work'), 'stage-2_fold-{fold}.pkl'),\n\n (Path('../input/freesoundaudiotagging2019ebouteillonsolution/fat2019ssl8vgg16full/work'), 'stage-10_fold-{fold}.pkl'),\n\n (Path('../input/freesoundaudiotagging2019ebouteillonsolution/fat2019ssl8vgg16full/work'), 'stage-11_fold-{fold}.pkl'),\n\n)\nPREDICTION_WINDOW_SHIFT = 48 # predict every PREDICTION_WINDOW_SHIFT time sample\n\nn_splits = 10\n\nDATA = Path('../input/freesound-audio-tagging-2019')\n\nDATA_TEST = DATA/'test'\n\nCSV_SUBMISSION = DATA/'sample_submission.csv'\n\ntest_df = pd.read_csv(CSV_SUBMISSION)\ndef read_audio(conf, pathname, trim_long_data):\n\n y, sr = librosa.load(pathname, sr=conf.sampling_rate)\n\n # trim silence\n\n if 0 < len(y): # workaround: 0 length causes error\n\n y, _ = librosa.effects.trim(y) # trim, top_db=default(60)\n\n # make it unified length to conf.samples\n\n if len(y) > conf.samples: # long enough\n\n if trim_long_data:\n\n y = y[0:0+conf.samples]\n\n else: # pad blank\n\n padding = conf.samples - len(y) # add padding at both ends\n\n offset = padding // 2\n\n y = np.pad(y, (offset, conf.samples - len(y) - offset), 'constant')\n\n return y\n\n\n\ndef audio_to_melspectrogram(conf, audio):\n\n spectrogram = librosa.feature.melspectrogram(audio, \n\n sr=conf.sampling_rate,\n\n n_mels=conf.n_mels,\n\n hop_length=conf.hop_length,\n\n n_fft=conf.n_fft,\n\n fmin=conf.fmin,\n\n fmax=conf.fmax)\n\n spectrogram = librosa.power_to_db(spectrogram)\n\n spectrogram = spectrogram.astype(np.float32)\n\n return spectrogram\n\n\n\ndef show_melspectrogram(conf, mels, title='Log-frequency power spectrogram'):\n\n librosa.display.specshow(mels, x_axis='time', y_axis='mel', \n\n sr=conf.sampling_rate, hop_length=conf.hop_length,\n\n fmin=conf.fmin, fmax=conf.fmax)\n\n plt.colorbar(format='%+2.0f dB')\n\n plt.title(title)\n\n plt.show()\n\n\n\ndef read_as_melspectrogram(conf, pathname, trim_long_data, debug_display=False):\n\n x = read_audio(conf, pathname, trim_long_data)\n\n mels = audio_to_melspectrogram(conf, x)\n\n if debug_display:\n\n IPython.display.display(IPython.display.Audio(x, rate=conf.sampling_rate))\n\n show_melspectrogram(conf, mels)\n\n return mels\n\n\n\n\n\nclass conf:\n\n # Preprocessing settings\n\n sampling_rate = 44100\n\n duration = 2\n\n hop_length = 347*duration # to make time steps 128\n\n fmin = 20\n\n fmax = sampling_rate // 2\n\n n_mels = 128\n\n n_fft = n_mels * 20\n\n samples = sampling_rate * duration\n\n\n\n\n\ndef mono_to_color(X, mean=None, std=None, norm_max=None, norm_min=None, eps=1e-6):\n\n # Stack X as [X,X,X]\n\n X = np.stack([X, X, X], axis=-1)\n\n\n\n # Standardize\n\n mean = mean or X.mean()\n\n std = std or X.std()\n\n Xstd = (X - mean) / (std + eps)\n\n _min, _max = Xstd.min(), Xstd.max()\n\n norm_max = norm_max or _max\n\n norm_min = norm_min or _min\n\n if (_max - _min) > eps:\n\n # Scale to [0, 255]\n\n V = Xstd\n\n V[V < norm_min] = norm_min\n\n V[V > norm_max] = norm_max\n\n V = 255 * (V - norm_min) / (norm_max - norm_min)\n\n V = V.astype(np.uint8)\n\n else:\n\n # Just zero\n\n V = np.zeros_like(Xstd, dtype=np.uint8)\n\n return V\n\n\n\ndef convert_wav_to_image(df, source, img_dest):\n\n print(f'Converting {source} -> {img_dest}')\n\n X = []\n\n for i, row in tqdm_notebook(df.iterrows(), total=df.shape[0]):\n\n x = read_as_melspectrogram(conf, source/str(row.fname), trim_long_data=False)\n\n x_color = mono_to_color(x)\n\n X.append(x_color)\n\n return X\nX_test = convert_wav_to_image(test_df, source=DATA_TEST, img_dest=None)\n# This implemented my new data augmentation technique 'SpecMix', see my github for more details :)\n\nclass MyMixUpCallback(LearnerCallback):\n\n def __init__(self, learn:Learner):\n\n super().__init__(learn)\n\n \n\nclass Lwlrap(Callback):\n\n def on_epoch_begin(self, **kwargs):\n\n pass\n# from official code https://colab.research.google.com/drive/1AgPdhSp7ttY18O3fEoHOQKlt_3HJDLi8#scrollTo=cRCaCIb9oguU\n\ndef _one_sample_positive_class_precisions(scores, truth):\n\n \"\"\"Calculate precisions for each true class for a single sample.\n\n\n\n Args:\n\n scores: np.array of (num_classes,) giving the individual classifier scores.\n\n truth: np.array of (num_classes,) bools indicating which classes are true.\n\n\n\n Returns:\n\n pos_class_indices: np.array of indices of the true classes for this sample.\n\n pos_class_precisions: np.array of precisions corresponding to each of those\n\n classes.\n\n \"\"\"\n\n num_classes = scores.shape[0]\n\n pos_class_indices = np.flatnonzero(truth > 0)\n\n # Only calculate precisions if there are some true classes.\n\n if not len(pos_class_indices):\n\n return pos_class_indices, np.zeros(0)\n\n # Retrieval list of classes for this sample.\n\n retrieved_classes = np.argsort(scores)[::-1]\n\n # class_rankings[top_scoring_class_index] == 0 etc.\n\n class_rankings = np.zeros(num_classes, dtype=np.int)\n\n class_rankings[retrieved_classes] = range(num_classes)\n\n # Which of these is a true label?\n\n retrieved_class_true = np.zeros(num_classes, dtype=np.bool)\n\n retrieved_class_true[class_rankings[pos_class_indices]] = True\n\n # Num hits for every truncated retrieval list.\n\n retrieved_cumulative_hits = np.cumsum(retrieved_class_true)\n\n # Precision of retrieval list truncated at each hit, in order of pos_labels.\n\n precision_at_hits = (\n\n retrieved_cumulative_hits[class_rankings[pos_class_indices]] /\n\n (1 + class_rankings[pos_class_indices].astype(np.float)))\n\n return pos_class_indices, precision_at_hits\n\n\n\n\n\ndef calculate_per_class_lwlrap(truth, scores):\n\n \"\"\"Calculate label-weighted label-ranking average precision.\n\n\n\n Arguments:\n\n truth: np.array of (num_samples, num_classes) giving boolean ground-truth\n\n of presence of that class in that sample.\n\n scores: np.array of (num_samples, num_classes) giving the classifier-under-\n\n test's real-valued score for each class for each sample.\n\n\n\n Returns:\n\n per_class_lwlrap: np.array of (num_classes,) giving the lwlrap for each\n\n class.\n\n weight_per_class: np.array of (num_classes,) giving the prior of each\n\n class within the truth labels. Then the overall unbalanced lwlrap is\n\n simply np.sum(per_class_lwlrap * weight_per_class)\n\n \"\"\"\n\n assert truth.shape == scores.shape\n\n num_samples, num_classes = scores.shape\n\n # Space to store a distinct precision value for each class on each sample.\n\n # Only the classes that are true for each sample will be filled in.\n\n precisions_for_samples_by_classes = np.zeros((num_samples, num_classes))\n\n for sample_num in range(num_samples):\n\n pos_class_indices, precision_at_hits = (\n\n _one_sample_positive_class_precisions(scores[sample_num, :],\n\n truth[sample_num, :]))\n\n precisions_for_samples_by_classes[sample_num, pos_class_indices] = (\n\n precision_at_hits)\n\n labels_per_class = np.sum(truth > 0, axis=0)\n\n weight_per_class = labels_per_class / float(np.sum(labels_per_class))\n\n # Form average of each column, i.e. all the precisions assigned to labels in\n\n # a particular class.\n\n per_class_lwlrap = (np.sum(precisions_for_samples_by_classes, axis=0) /\n\n np.maximum(1, labels_per_class))\n\n # overall_lwlrap = simple average of all the actual per-class, per-sample precisions\n\n # = np.sum(precisions_for_samples_by_classes) / np.sum(precisions_for_samples_by_classes > 0)\n\n # also = weighted mean of per-class lwlraps, weighted by class label prior across samples\n\n # = np.sum(per_class_lwlrap * weight_per_class)\n\n return per_class_lwlrap, weight_per_class\n\n\n\n\n\n# Accumulator object version.\n\n\n\nclass lwlrap_accumulator(object):\n\n \"\"\"Accumulate batches of test samples into per-class and overall lwlrap.\"\"\" \n\n\n\n def __init__(self):\n\n self.num_classes = 0\n\n self.total_num_samples = 0\n\n \n\n def accumulate_samples(self, batch_truth, batch_scores):\n\n \"\"\"Cumulate a new batch of samples into the metric.\n\n \n\n Args:\n\n truth: np.array of (num_samples, num_classes) giving boolean\n\n ground-truth of presence of that class in that sample for this batch.\n\n scores: np.array of (num_samples, num_classes) giving the \n\n classifier-under-test's real-valued score for each class for each\n\n sample.\n\n \"\"\"\n\n assert batch_scores.shape == batch_truth.shape\n\n num_samples, num_classes = batch_truth.shape\n\n if not self.num_classes:\n\n self.num_classes = num_classes\n\n self._per_class_cumulative_precision = np.zeros(self.num_classes)\n\n self._per_class_cumulative_count = np.zeros(self.num_classes, \n\n dtype=np.int)\n\n assert num_classes == self.num_classes\n\n for truth, scores in zip(batch_truth, batch_scores):\n\n pos_class_indices, precision_at_hits = (\n\n _one_sample_positive_class_precisions(scores, truth))\n\n self._per_class_cumulative_precision[pos_class_indices] += (\n\n precision_at_hits)\n\n self._per_class_cumulative_count[pos_class_indices] += 1\n\n self.total_num_samples += num_samples\n\n\n\n def per_class_lwlrap(self):\n\n \"\"\"Return a vector of the per-class lwlraps for the accumulated samples.\"\"\"\n\n return (self._per_class_cumulative_precision / \n\n np.maximum(1, self._per_class_cumulative_count))\n\n\n\n def per_class_weight(self):\n\n \"\"\"Return a normalized weight vector for the contributions of each class.\"\"\"\n\n return (self._per_class_cumulative_count / \n\n float(np.sum(self._per_class_cumulative_count)))\n\n\n\n def overall_lwlrap(self):\n\n \"\"\"Return the scalar overall lwlrap for cumulated samples.\"\"\"\n\n return np.sum(self.per_class_lwlrap() * self.per_class_weight())\nclass ConvBlock(nn.Module):\n\n def __init__(self, in_channels, out_channels):\n\n super().__init__()\n\n \n\n self.conv1 = nn.Sequential(\n\n nn.Conv2d(in_channels, out_channels, 3, 1, 1),\n\n nn.BatchNorm2d(out_channels),\n\n nn.ReLU(),\n\n )\n\n self.conv2 = nn.Sequential(\n\n nn.Conv2d(out_channels, out_channels, 3, 1, 1),\n\n nn.BatchNorm2d(out_channels),\n\n nn.ReLU(),\n\n )\n\n\n\n self._init_weights()\n\n \n\n def _init_weights(self):\n\n for m in self.modules():\n\n if isinstance(m, nn.Conv2d):\n\n nn.init.kaiming_normal_(m.weight)\n\n if m.bias is not None:\n\n nn.init.zeros_(m.bias)\n\n elif isinstance(m, nn.BatchNorm2d):\n\n nn.init.constant_(m.weight, 1)\n\n nn.init.zeros_(m.bias)\n\n \n\n def forward(self, x):\n\n x = self.conv1(x)\n\n x = self.conv2(x)\n\n x = F.avg_pool2d(x, 2)\n\n return x\n\n \n\nclass Classifier(nn.Module):\n\n def __init__(self, num_classes=1000): # <======== modificaition to comply fast.ai\n\n super().__init__()\n\n \n\n self.conv = nn.Sequential(\n\n ConvBlock(in_channels=3, out_channels=64),\n\n ConvBlock(in_channels=64, out_channels=128),\n\n ConvBlock(in_channels=128, out_channels=256),\n\n ConvBlock(in_channels=256, out_channels=512),\n\n )\n\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) # <======== modificaition to comply fast.ai\n\n self.fc = nn.Sequential(\n\n nn.Dropout(0.2),\n\n nn.Linear(512, 128),\n\n nn.PReLU(),\n\n nn.BatchNorm1d(128),\n\n nn.Dropout(0.1),\n\n nn.Linear(128, num_classes),\n\n )\n\n\n\n def forward(self, x):\n\n x = self.conv(x)\n\n #x = torch.mean(x, dim=3) # <======== modificaition to comply fast.ai\n\n #x, _ = torch.max(x, dim=2) # <======== modificaition to comply fast.ai\n\n x = self.avgpool(x) # <======== modificaition to comply fast.ai\n\n x = self.fc(x)\n\n return x\n# !!! use globals CUR_X_FILES, CUR_X\n\ndef open_fat2019_image(fn, convert_mode, after_open)->Image:\n\n # open\n\n fname = fn.split('/')[-1]\n\n if '!' in fname:\n\n fname, crop_x = fname.split('!')\n\n crop_x = int(crop_x)\n\n else:\n\n crop_x = -1\n\n idx = CUR_X_FILES.index(fname)\n\n x = CUR_X[idx]\n\n # crop\n\n base_dim, time_dim, _ = x.shape\n\n if crop_x == -1:\n\n crop_x = random.randint(0, time_dim - base_dim)\n\n x = x[0:base_dim, crop_x:crop_x+base_dim, :]\n\n x = np.transpose(x, (1, 0, 2))\n\n x = np.transpose(x, (2, 1, 0))\n\n # standardize\n\n return Image(torch.from_numpy(x.astype(np.float32, copy=False)).div_(255))\n\n\n\n\n\nvision.data.open_image = open_fat2019_image\nCUR_X_FILES, CUR_X = list(test_df.fname.values), X_test\noutput = StringIO()\n\ncsv_writer = writer(output)\n\ncsv_writer.writerow(test_df.columns)\n\n\n\nfor _, row in tqdm_notebook(test_df.iterrows(), total=test_df.shape[0]):\n\n idx = CUR_X_FILES.index(row.fname)\n\n time_dim = CUR_X[idx].shape[1]\n\n s = math.ceil((time_dim-conf.n_mels) / PREDICTION_WINDOW_SHIFT) + 1\n\n \n\n fname = row.fname\n\n for crop_x in [int(np.around((time_dim-conf.n_mels)*x/(s-1))) if s != 1 else 0 for x in range(s)]:\n\n row.fname = fname + '!' + str(crop_x)\n\n csv_writer.writerow(row)\n\n\n\noutput.seek(0)\n\ntest_df_multi = pd.read_csv(output)\n\n\n\ndel row, test_df, output, csv_writer; gc.collect();\ntest = ImageList.from_df(test_df_multi, models_list[0][0])\n\n\n\nfor model_nb, (work, name) in enumerate(models_list):\n\n for fold in range(n_splits):\n\n learn = load_learner(work, name.format(fold=fold), test=test)\n\n preds, _ = learn.get_preds(ds_type=DatasetType.Test)\n\n preds = preds.cpu().numpy()\n\n if (fold == 0) and (model_nb == 0):\n\n predictions = preds\n\n else:\n\n predictions += preds\n\n\n\npredictions /= (n_splits * len(models_list))\ntest_df_multi[learn.data.classes] = predictions\n\ntest_df_multi['fname'] = test_df_multi.fname.apply(lambda x: x.split('!')[0])\nsubmission = test_df_multi.infer_objects().groupby('fname').mean().reset_index()\n\nsubmission.to_csv('submission.csv', index=False)\n\nsubmission.head()\nsubmission.set_index('fname').idxmax(1)","repo_name":"aorursy/new-nb-2","sub_path":"ebouteillon_12th-public-lb-inference-kernel-using-fastai.py","file_name":"ebouteillon_12th-public-lb-inference-kernel-using-fastai.py","file_ext":"py","file_size_in_byte":15729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"37941095168","text":"import asyncio\nfrom dataclasses import dataclass\n\nimport bs4\nimport httpx\nfrom bs4 import BeautifulSoup\nfrom discord import Colour\n\nfrom utils.custom_logger import Log\nfrom utils.structs import Product\nfrom utils.webhook import send_webhook\n\nseen = []\nlog = Log('[MONITOR]')\n\n\nasync def monitor():\n client: httpx.AsyncClient\n\n urls_to_monitor: list[str] = [\n 'https://www.scottycameron.com/store/accessories/',\n 'https://www.scottycameron.com/store/apparel/',\n 'https://www.scottycameron.com/store/gallery-putters/',\n 'https://www.scottycameron.com/store/gallery-creations/'\n ]\n\n for url in urls_to_monitor:\n async with httpx.AsyncClient() as client:\n try:\n raw_resp: httpx.Response = await client.get(url)\n except Exception:\n log.exception('Error.')\n continue\n\n resp = BeautifulSoup(raw_resp.text, 'lxml')\n items = resp.select(\"article[class=product-item]\")\n\n for item in items:\n atc_tag = item.select_one('a[href^=\"/store/scottyproduct/addtocartplp/\"]')\n if atc_tag in seen:\n continue\n\n if atc_tag.text == 'SOLD' or not atc_tag.text:\n continue\n\n product = Product(\n name=item.select_one('a[title]').get('title').strip(),\n url='https://www.scottycameron.com' + atc_tag.get('href'),\n price=item.select_one('div[data-test-selector=divPrice]').text.strip(),\n image=item\n .select_one('img[class*=\"img-responsive\"]')\n .get('data-src').strip().replace(' ', '')\n )\n print(product.image)\n with open('resp.html', 'w') as file:\n file.write(item.prettify())\n # sleep(300)\n # ping\n await send_webhook(product=product,\n title='Live Product Detected',\n color=Colour.teal())\n seen.append(atc_tag)\n\n\nif __name__ == \"__main__\":\n from time import sleep\n from datetime import datetime\n\n while True:\n try:\n asyncio.run(monitor())\n except:\n pass\n sleep(30)\n print(f'[{datetime.now()}]: Checking.')\n","repo_name":"lafftar/scottyMonitor","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"17457606055","text":"from rest_framework import serializers\nfrom .models import Follower\nfrom django.db import IntegrityError\n\n\"\"\"Create Follower Serializer\n\"\"\"\n\n\nclass FollowerSerializer(serializers.ModelSerializer):\n\n owner = serializers.ReadOnlyField(source='owner.username')\n followed_name = serializers.ReadOnlyField(source='followed.username')\n\n class Meta:\n model = Follower\n fields = ['id',\n 'owner',\n 'created_at',\n 'followed',\n 'followed_name',]\n\n \"\"\"\n Handle if follow are duplication/integrity errors\n \"\"\"\n def create(self, validated_data):\n try:\n return super().create(validated_data)\n except IntegrityError:\n raise serializers.ValidationError({\n 'detail': 'possible duplication of follow'\n })","repo_name":"damidaramola/canvascorner-drf-api","sub_path":"followers/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"24283311590","text":"# Find the number of steps it takes to reach the highest elevation E as quickly as possible.\n# This time, we can start from any 'a' height as well as 'S' height.\n\n# Approach: Treat E as the start rather than the end.\n\nimport string\n\nwith open(\"day_12/input.txt\", \"r\") as f:\n input = f.readlines()\ninput = [i.replace(\"\\n\", \"\") for i in input]\n\n# The start and end positions (which have not been found yet), each as a (row, col) pair\nstart_position = []\nend_positions = []\n\n# Distances is a dict where the key is a position and a value is that distance\ndistances = {}\n\n# Initialize everything:\n# - Set the distances to the max distance\n# - Get the start position\n# - Get the list of end positions\ndef initialize():\n global input, distances, start_position, end_positions\n\n max_distance = 2 ** 32\n for row in range(len(input)):\n for col in range(len(input[row])):\n distances[(row, col)] = max_distance\n \n if input[row][col] in ['S', 'a']:\n end_positions.append((row, col))\n\n if input[row][col] == 'E':\n start_position = [row, col]\n distances[(row, col)] = 0\n\n# Returns True if the given position can be visited, based on the current position.\ndef can_visit_position(player_position, visit_position):\n global input\n\n # Make sure the position is not out of bounds\n if visit_position[0] < 0 or visit_position[0] > len(input) - 1:\n return False\n if visit_position[1] < 0 or visit_position[1] > len(input[0]) - 1:\n return False\n\n # Compare the heights\n player_height = input[player_position[0]][player_position[1]]\n visit_height = input[visit_position[0]][visit_position[1]]\n\n all_heights = 'S' + string.ascii_lowercase + 'E'\n\n height_diff = all_heights.find(player_height) - all_heights.find(visit_height)\n return height_diff <= 1\n\n# Get a list of positions that can be visited, based on the current position.\ndef get_next_positions(player_position):\n global input\n\n next_positions = []\n \n # Check left\n left_position = (player_position[0], player_position[1] - 1)\n if can_visit_position(player_position, left_position):\n next_positions.append(left_position)\n\n # Check right\n right_position = (player_position[0], player_position[1] + 1)\n if can_visit_position(player_position, right_position):\n next_positions.append(right_position)\n\n # Check above\n above_position = (player_position[0] - 1, player_position[1])\n if can_visit_position(player_position, above_position):\n next_positions.append(above_position)\n\n # Check below\n below_position = (player_position[0] + 1, player_position[1])\n if can_visit_position(player_position, below_position):\n next_positions.append(below_position)\n\n return next_positions\n\n# Get the shortest distance from a given start position to every other position\ndef get_distances(start_position):\n global distances, input, end_positions\n\n queue = [start_position]\n visited = []\n\n while len(queue) > 0:\n # Get the next position from the queue\n current_position = queue.pop(0)\n\n # Update the visited list with the current position\n visited.append(current_position)\n\n # Get the visitable positions from the current position\n next_positions = get_next_positions(current_position)\n\n # Iterate through the adjacent positions\n for next_pos in next_positions:\n\n # Get the new distance for that position\n distances[next_pos] = min(distances[next_pos], distances[current_position] + 1)\n\n # Check if we are at the end\n next_height = input[next_pos[0]][next_pos[1]]\n if next_height in ['S', 'a']:\n return distances[next_pos]\n\n # Add the position to the queue if we have not visited already (and if it's not already in the qeueu)\n if next_pos not in visited and next_pos not in queue:\n queue.append(next_pos)\n return 2 ** 32\n\n# Initialize everything\ninitialize()\n\n# Get the min distance from the start position to any end position\nmin_dist = get_distances(tuple(start_position))\nprint(\"Number of steps to highest elevation: %d\" % min_dist)","repo_name":"PBearson/Advent_Of_Code_2022","sub_path":"day_12/different_start_positions.py","file_name":"different_start_positions.py","file_ext":"py","file_size_in_byte":4258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"31285739354","text":"import time\nfrom unittest import TestCase, mock\nfrom . events import EventManager, Event\n\nclass TestEventObject(TestCase):\n TestValue_Timestamp = 123\n\n @mock.patch(\"time.time\", mock.MagicMock(return_value=TestValue_Timestamp))\n def test_constructor(self):\n name = \"test\"\n data = {name: \"1\"}\n ev = Event(name=\"test\", data=data)\n self.assertEqual(ev.name, name)\n self.assertEqual(ev.data, data)\n self.assertEqual(ev.timestamp, self.TestValue_Timestamp)\n\n def test_constuctor_error(self):\n with self.assertRaises(ValueError):\n ev = Event()\n with self.assertRaises(TypeError):\n ev = Event(name=1)\n\nclass TestEventManager(TestCase):\n def setUp(self):\n man = EventManager()\n man.reset_instance()\n\n def test_add_handler_error(self):\n man = EventManager()\n with self.assertRaises(ValueError):\n man.add_handler(callback=str)\n with self.assertRaises(TypeError):\n man.add_handler(name=1, callback=str)\n with self.assertRaises(ValueError):\n man.add_handler(name=\"1\")\n with self.assertRaises(TypeError):\n man.add_handler(name=\"1\", callback=1)\n\n def test_add_handler_error(self):\n man = EventManager()\n with self.assertRaises(ValueError):\n man.remove_handler(callback=str)\n with self.assertRaises(TypeError):\n man.remove_handler(name=1, callback=str)\n with self.assertRaises(ValueError):\n man.remove_handler(name=\"1\")\n with self.assertRaises(TypeError):\n man.remove_handler(name=\"1\", callback=1)\n with self.assertRaises(KeyError):\n man.remove_handler(name=\"1\", callback=str)\n\n def test_add_fire_error(self):\n man = EventManager()\n with self.assertRaises(TypeError):\n man.remove_handler(fire=1)\n\n def test_fire(self):\n name = \"test\"\n result = [False]\n data = [\"data\"]\n def test_handler(ev):\n self.assertEqual(ev.name, name)\n self.assertEqual(ev.data, data)\n result[0] = True\n man = EventManager()\n man.add_handler(name, test_handler)\n ev = Event(name=name, data=data)\n man.fire(ev)\n self.assertTrue(all(result))\n\n def test_removal(self):\n name = \"test\"\n result = [False]\n def test_handler(ev):\n result[0] = True\n man = EventManager()\n man.add_handler(name, test_handler)\n ev = Event(name=name)\n man.fire(ev)\n self.assertTrue(all(result))\n result[0] = False\n man.remove_handler(name, test_handler)\n man.fire(ev)\n self.assertFalse(all(result))\n","repo_name":"vishnubob/photobooth","sub_path":"photobooth/test_events.py","file_name":"test_events.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"42"} +{"seq_id":"24835506754","text":"from collections import Counter\nclass Solution:\n def findDuplicates(self, nums):\n n=Counter(nums)\n ans=[]\n \n for i,v in n.items():\n if v>1:\n ans.append(i)\n return ans\n'''Method-2\nclass Solution(object):\n def findDuplicates(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n d = {} # used for key lookups only\n ret = [] # store duplicates\n for num in nums:\n if num not in d:\n d[num] = True # store a bool to minimize space\n else: \n ret.append(num)\n return ret\n'''\n\nif __name__==\"__main__\":\n nums=[2,3,4,1,3,2,2,7,5,1]\n c=Solution().findDuplicates(nums)\n print(c)","repo_name":"reshmanair4567/100daycodingchallenge","sub_path":"Python/August_Find_all_duplicates_in_an_array.py","file_name":"August_Find_all_duplicates_in_an_array.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"36902572376","text":"import unittest\nfrom ufo.views import *\nfrom ufo.filesystem import *\nfrom ufo.acl import *\n\nJOHN_ID = 123456\n\nclass FileSystemTestCase(unittest.TestCase):\n def setUp(self):\n self.fs = fs = CouchedFileSystem(\"/tmp\", \"test_fs\")\n fs.doc_helper.sync()\n\n if not fs.exists(\"/test\"):\n fs.mkdir(\"/test\")\n f = fs.open(\"/test/image.png\", os.O_CREAT | os.O_WRONLY)\n f.close()\n f = self.fs[\"/test/image.png\"]\n f.stats.st_size = 1000\n self.fs.doc_helper.update(f)\n\n def test_acl(self):\n f = self.fs[\"/test/image.png\"]\n posix_acl = f.posix_acl\n posix_acl.append(ACE(ACL_USER, ACL_READ, JOHN_ID))\n f.acl = posix_acl.to_json()\n self.fs.doc_helper.update(f)\n\n def test_df(self):\n assert self.fs.du(\"/test\") == 1000\n\nsuite = unittest.TestLoader().loadTestsFromTestCase(FileSystemTestCase)\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"vienin/python-ufo","sub_path":"tests/test_fs.py","file_name":"test_fs.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"42001335439","text":"import sys\r\nimport random\r\nimport numpy as np\r\nfrom numpy import linalg as la\r\nimport math\r\nimport xlwt\r\nfrom xlwt import Workbook\r\n\r\n\r\nsys.path.append(\"/mnt/c/Users/Dell/Desktop/CEC2014/cec2014-master/python\")\r\nimport cec2014\r\n\r\ndim = 30\r\nMFES = 10000*dim\r\n\r\nbest_ref = [0*MFES,\r\n 0.001*MFES,\r\n 0.01*MFES,\r\n 0.1*MFES,\r\n 0.2*MFES,\r\n 0.3*MFES,\r\n 0.4*MFES,\r\n 0.5*MFES,\r\n 0.6*MFES,\r\n 0.7*MFES,\r\n 0.8*MFES,\r\n 0.9*MFES,\r\n 1.0*MFES]\r\n\r\nmin_values = []\r\nmax_values = []\r\n\r\nfor i in range(dim):\r\n min_values.append(-100)\r\n \r\nfor i in range(dim):\r\n max_values.append(100)\r\n\r\n##################################################################################\r\nsize_pop = 100\r\nC0 = 1\r\nC1 = 2.0\r\nC2 = 2.0\r\nV_max = 40\r\n#w = 0.9\r\nX_r = 0.73\r\n\r\n\r\nFuntion_number = 14\r\nglobal_min = Funtion_number * 100.0\r\n##################################################################################\r\n\r\ndef Objetive_Function(position):\r\n return cec2014.cec14(np.array(position), Funtion_number)\r\n\r\nclass Birds():\r\n def __init__(self, position, speed):\r\n self.position = position\r\n self.speed = speed\r\n self.fitness = Objetive_Function(position)\r\n self.pbest = []\r\n \r\n def evaluate(self):\r\n return Objetive_Function(self.position)\r\n \r\n \r\ndef InitialPop():\r\n birds = []\r\n for index1 in range(size_pop):\r\n rand_pos = []\r\n rand_speed = []\r\n \r\n for index2 in range(dim):\r\n rand_pos.append(np.random.uniform(min_values[index2], max_values[index2]))\r\n rand_speed.append(np.random.uniform(min_values[index2]/5, max_values[index2]/5))\r\n \r\n birds.append(Birds(rand_pos, rand_speed))\r\n birds[index1].pbest = birds[index1].position\r\n \r\n #print(\"Bird in position :\", birds[index1].position)\r\n #print(\"Bird with pbest : \", birds[index1].pbest)\r\n #print(\"Bird with fitness : \", birds[index1].fitness)\r\n #print(\"Bird with speed: \", birds[index1].speed)\r\n \r\n return birds\r\n\r\n#birds = InitialPop()\r\n#print(birds)\r\n\r\n\r\ndef Get_min(birds):\r\n minimum = birds[0].fitness\r\n minimum_pos = birds[0].position\r\n #print(\"Initial minimum :\",ants[0].fitness)\r\n \r\n for index1 in range(1, size_pop):\r\n \r\n if birds[index1].fitness < minimum:\r\n \r\n minimum = birds[index1].fitness\r\n minimum_pos = birds[index1].position\r\n \r\n return minimum_pos, minimum\r\n\r\n\r\ndef Movement(birds, C0, C1, C2, V_max, w, X_r):\r\n new_birds = []\r\n\r\n global_b, global_f = Get_min(birds)\r\n \r\n for index1 in range(size_pop):\r\n speed_i = birds[index1].speed\r\n #print(\"Current speed :\", speed_i)\r\n \r\n best_i = birds[index1].pbest\r\n #print(\"Current personal best: \", best_i)\r\n \r\n #global_i = birds[index1].neigh\r\n #print(\"Current best local :\", global_i)\r\n \r\n speed_vector = []\r\n new_pos = []\r\n \r\n for index2 in range(dim):\r\n speed_0 = C0*speed_i[index2] * w\r\n rand_1 = np.random.uniform(0,1)\r\n speed_1 = C1 * rand_1 * (best_i[index2] - birds[index1].position[index2])\r\n rand_2 = np.random.uniform(0,1)\r\n speed_2 = C2* rand_2 * (global_b[index2] - birds[index1].position[index2])\r\n \r\n speed_component = X_r * (speed_0 + speed_1 + speed_2)\r\n#################################################################################################### \r\n if abs(speed_component) > V_max:\r\n if speed_component > 0:\r\n speed_component = V_max\r\n else:\r\n speed_component = -V_max\r\n#####################################################################################################\r\n if speed_component + birds[index1].position[index2] >= max_values[index2]:\r\n new_pos.append(max_values[index2])\r\n \r\n birds[index1].position[index2] = max_values[index2]\r\n speed_component = -speed_component\r\n \r\n elif speed_component + birds[index1].position[index2] <= min_values[index2]:\r\n new_pos.append(min_values[index2])\r\n \r\n birds[index1].position[index2] = min_values[index2]\r\n speed_component = -speed_component\r\n \r\n else:\r\n new_pos.append(speed_component + birds[index1].position[index2])\r\n \r\n birds[index1].position[index2] += speed_component\r\n######################################################################################################\r\n birds[index1].speed[index2] = speed_component\r\n \r\n evaluation = Objetive_Function(new_pos)\r\n \r\n if evaluation < birds[index1].fitness:\r\n #print(\"Bird got a better position\")\r\n #print(\"New fitness :\", F1(new_pos))\r\n birds[index1].pbest = new_pos\r\n #Neighbors(birds, number_neigh)\r\n\r\n if evaluation < global_f:\r\n \tglobal_f = evaluation\r\n \tglobal_b = new_pos\r\n\r\n \r\n birds[index1].fitness = evaluation\r\n \r\n return birds\r\n\r\n\r\ndef PSO():\r\n birds = InitialPop()\r\n num_iter = size_pop\r\n\r\n best_par = []\r\n\r\n current_parcial = 0\r\n success = 0\r\n\r\n while num_iter < MFES:\r\n \r\n best_bird, best_fitness = Get_min(birds)\r\n #print(\"Best bird at :\", best_bird)\r\n #print(\"Best fitness :\", best_fitness)\r\n\r\n if num_iter >= best_ref[current_parcial]:\r\n best_par.append(best_fitness - global_min)\r\n current_parcial += 1\r\n print(\"Parcial computed\")\r\n print(\"Best bird at :\", best_bird)\r\n print(\"Best fitness :\", best_fitness)\r\n\r\n \r\n if best_fitness - global_min < 0.00000001:\r\n best_result = best_fitness - global_min\r\n print(\"Sucess\")\r\n print(\"Number of iterations :\", num_iter)\r\n \r\n success += 1\r\n\r\n while len(best_par) < len(best_ref):\r\n best_par.append(best_fitness - global_min)\r\n\r\n print(best_par)\r\n\r\n return best_result, best_par, num_iter, success\r\n break\r\n\r\n w = 0.4 + 0.5*((MFES - num_iter)/MFES)\r\n \r\n birds = Movement(birds, C0, C1, C2, V_max, w, X_r)\r\n \r\n num_iter += size_pop\r\n \r\n print(\"No success\")\r\n best_result = best_fitness - global_min\r\n\r\n while len(best_par) < len(best_ref):\r\n best_par.append(best_fitness - global_min)\r\n\r\n return best_result, best_par, num_iter, success\r\n \r\n#PSO()\r\n\r\n\r\ndef Output_Excel(number_runs):\r\n success_rate = 0\r\n\r\n # Workbook is created \r\n wb = Workbook() \r\n\r\n # add_sheet is used to create sheet. \r\n sheet1 = wb.add_sheet('PSO_class')\r\n\r\n sheet1.write(1, 1, \"RUN nº\")\r\n sheet1.write(2, 1, \"Closed in run\")\r\n sheet1.write(3, 1, \"Best result\")\r\n sheet1.write(4, 1, \"Parcials\")\r\n sheet1.write(5, 1, \"Erro para FES=0,0*MaxFES\")\r\n sheet1.write(6, 1, \"Erro para FES=0,001*MaxFES\")\r\n sheet1.write(7, 1, \"Erro para FES=0,01*MaxFES\")\r\n sheet1.write(8, 1, \"Erro para FES=0,1*MaxFES\")\r\n sheet1.write(9, 1, \"Erro para FES=0,2*MaxFES\")\r\n sheet1.write(10, 1, \"Erro para FES=0,3*MaxFES\")\r\n sheet1.write(11, 1, \"Erro para FES=0,4*MaxFES\")\r\n sheet1.write(12, 1, \"Erro para FES=0,5*MaxFES\")\r\n sheet1.write(13, 1, \"Erro para FES=0,6*MaxFES\")\r\n sheet1.write(14, 1, \"Erro para FES=0,7*MaxFES\")\r\n sheet1.write(15, 1, \"Erro para FES=0,8*MaxFES\")\r\n sheet1.write(16, 1, \"Erro para FES=0,9*MaxFES\")\r\n sheet1.write(17, 1, \"Erro para FES=1,0*MaxFES\")\r\n sheet1.write(18, 1, \"Success rate\")\r\n\r\n\r\n for run in range(number_runs):\r\n print(\"Start of run \", run)\r\n \r\n BEST, BEST_PAR, NUM_RUNS, SUCCESS = PSO()\r\n \r\n sheet1.write(1, run+2, (run+1))\r\n sheet1.write(2, run+2, (NUM_RUNS))\r\n sheet1.write(3, run+2, (BEST))\r\n #sheet1.write(4, run+2, (WORST))\r\n #sheet1.write(5, run+2, (MEAN))\r\n #sheet1.write(6, run+2, (MEDIAN))\r\n \r\n for index in range(len(BEST_PAR)):\r\n \r\n sheet1.write(5+index, run+2, (BEST_PAR[index]))\r\n \r\n \r\n success_rate += SUCCESS\r\n \r\n\r\n sheet1.write(18, 2, (success_rate/number_runs))\r\n\r\n wb.save(\"CEC2014 Function\" + str(Funtion_number) + \" - PSO_class\" + str(dim) + \".xls\")\r\n\r\n return success_rate/number_runs\r\n\r\nOutput_Excel(25)","repo_name":"Larangeira-python/MCIN","sub_path":"FASE2/PSO_gbest.py","file_name":"PSO_gbest.py","file_ext":"py","file_size_in_byte":8721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"16821033610","text":"from collections import defaultdict\n\nf = open('./input_8.txt','r')\nio = f.read()\n#io = '2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2'\nheader = iter(map(int,io.replace('\\n','').split(' ')))\n\ndef get_metadata(num_children, n_meta):\n if num_children == 0:\n return [sum(next(header) for _ in range(n_meta))] * 2\n\n meta, value = 0, 0\n value_children = defaultdict(int)\n\n for n in range(0,num_children):\n m, value_children[n] = get_metadata(next(header), next(header))\n meta += m\n\n\n for _ in range(n_meta):\n m = next(header)\n meta += m\n value += value_children[m - 1]\n\n return meta, value\n\n\nmeta, value = get_metadata(next(header), next(header))\nprint(meta,value)\n","repo_name":"mattdano/adventcodelander","sub_path":"day8.py","file_name":"day8.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"26046576912","text":"import requests\r\nimport platform\r\nif platform.system() == \"Windows\":\r\n from Windows_Log import Log\r\nelse:\r\n from Unix_Log import Log\r\nfrom Base import sign\r\nfrom config import config\r\n\r\nclass Curl(object):\r\n # 自定义get方法,自带sign签名 \r\n def get(self,url,param):\r\n Log.debug(\"GET: \"+url)\r\n payload = {\r\n \"cookie\":config[\"Token\"][\"COOKIE\"]\r\n }\r\n payload = dict(param,**payload)\r\n payload = sign(payload)\r\n r = requests.get(url,payload)\r\n return r.text\r\n \r\n # 自定义post方法,自带sign签名\r\n def post(self,url,param):\r\n Log.debug(\"POST: \"+url)\r\n payload = {\r\n \"cookie\":config[\"Token\"][\"COOKIE\"]\r\n }\r\n payload = dict(param,**payload)\r\n payload = sign(payload)\r\n r = requests.post(url,payload)\r\n return r.text\r\n \r\n # 自定义不带sign签名的post方法,取名为nspost(no sign post)\r\n def nspost(self,url,param):\r\n Log.debug(\"POST: \"+url)\r\n headers = {\r\n \"Accept\":\"application/json, text/plain, */*\",\r\n \"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36\",\r\n \"Accept-Language\":\"zh-CN,zh;q=0.9\",\r\n \"accept-encoding\":\"gzip, deflate\",\r\n \"cookie\":config[\"Token\"][\"COOKIE\"]\r\n }\r\n r = requests.post(url,param,headers=headers)\r\n return r.text","repo_name":"Yodamt/BiliBiliHelper","sub_path":"Src/Curl.py","file_name":"Curl.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"42"} +{"seq_id":"4057521615","text":"from itertools import product,combinations\n# interval vector calculator, input: a string of 1/0, \n# output:\n# a array of length n-tEt, \n# each index i+1 is the interval name, i.e array [0]=3 means there are 3 1-intervals\n# element at each index is number of intervals that appears in the set(the Input String in this case)\ndef interval_vector_calc(bracelet):\n\tarray=[0 for i in range(len(bracelet)/2+1)]\n\ta=bracelet+bracelet\n\tfor i in range (0,len(bracelet)):\n\t\tfor y in range(i+1,i+6):\n\t\t\tif bracelet[i]==a[y] and bracelet[i]=='1':\n\t\t\t\tarray[y-i-1]+=1\n\treturn array\n\n#this gets you the prime set,\n#but this works when you have an input bracelet, that is ALREADY LEFT_PACKED by output-all-permutation and inversions_cancelation\ndef prime_set(bracelet):\n\ta=bracelet+bracelet\n\t#array to return\n\tarray=[0]\n\tcount=0\n\tfor i in range(1,len(bracelet)):\n\t\tif bracelet[i]=='1':\n\t\t\tarray.append(i)\n\treturn array\n\n# main generator,\n# input: numOf of equal temperament and cardinality\n# output: array of set classes of the cardinality within the temperament\ndef tEt_generator(numOf_tEt,cardinality):\n\t#array to return\n\tarray=[[]]\n\t#temp for temporary usage\n\ttemp=[]\n\tfor x in range(1,numOf_tEt):\n\t\tprint\n\n#check for rotation\ndef ifrotate(a,b):\n\ta=a+a;\n\tif b in a:\n\t\treturn 1\n\telse:\n\t\treturn 0\n\n#cancel existent inversions/ bracelets that are in rotation with existed bracelet\ndef inversions_cancelation(array):\n\tbigArray=array\n\ti=0\n\twhile (i<len(bigArray)):\n\t\tx=i+1\n\t\twhile (x<len(bigArray)):\n\t\t\tif ifrotate(bigArray[i],bigArray[x])==1:\n\t\t\t\tbigArray.pop(x)\n\t\t\t\tx-=1\n\t\t\tx+=1\n\t\ti+=1\n\treturn bigArray\n\n# random brutal force print function to play around\ndef output_all_permutation(numOf_tEt,cardinality):\n\tarray=[]\n\tstring=''.join(str(i) for i in range(numOf_tEt))\n\tfor project in [''.join(i) for i in combinations(string, cardinality)]:\n\t\ttemp=[0 for i in range(numOf_tEt)]\n\t\tfor i in range(len(project)):\n\t\t\ttemp[int(project[i])]='1'\n\t\tarray.append(''.join(str(temp[i]) for i in range(len(temp))))\n\tprint (array)\n\tprint (inversions_cancelation(array))\n\tset_of_interval_vector=[]\n\tset_of_prime_set=[]\n\tfor project in inversions_cancelation(array):\n\t\tset_of_interval_vector.append(interval_vector_calc(project))\n\t\tset_of_prime_set.append(prime_set(project))\n\tprint (set_of_prime_set)\n\tprint (set_of_interval_vector)\noutput_all_permutation(12,5)\n","repo_name":"gazcn007/music_panda","sub_path":"tEt_generator.py","file_name":"tEt_generator.py","file_ext":"py","file_size_in_byte":2330,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"42"} +{"seq_id":"20932047634","text":"from drf_spectacular.utils import OpenApiParameter, OpenApiExample, OpenApiResponse\nfrom drf_spectacular.types import OpenApiTypes\n\n\ndownload_url_api_doc = {\n 'description':'ダウンロード用URL発行',\n 'responses': {\n 200: OpenApiResponse(\n response='array', \n description='messageのkeyにcurlでの使用方、file_urlsのkeyにfile名をkeyにしてvalにdownload urlが入ったdictが入ったdictをreturn',\n ),\n 422: OpenApiResponse(\n response='array', \n description='エラーレスポンス時の定型をreturn',\n )\n },\n 'examples': [\n OpenApiExample(\n 'request',\n value={\n \"bucket_name\": \"some_bucket\",\n \"bucket_folder_path\": \"some/awsome/folder/\",\n \"file_names\": [\n \"file_1.csv\",\n \"file_2.csv\",\n \"file_3.csv\"\n ]\n },\n request_only=True\n ),\n OpenApiExample(\n '200',\n status_codes=['200'],\n value={\n \"message\": \"use download_url like 'curl 'リクエストするurl' \",\n \"upload_urls\": {\n \"file1.csv\": \"https://storage.googleapis.com/some_bucket/some_awsome_url\",\n \"file2.csv\": \"https://storage.googleapis.com/some_bucket/some_awsome_url\",\n \"file3.csv\": \"https://storage.googleapis.com/some_bucket/some_awsome_url\",\n },\n },\n response_only=True\n ),\n OpenApiExample(\n '422',\n status_codes=['422'],\n value={\n \"detail\": [\n {\n \"loc\": \"request body\",\n \"msg\": \"invalid request body.\",\n \"type\": \"invalid schema.\"\n }\n ]\n },\n response_only=True\n ),\n ]\n}","repo_name":"16thchild/models","sub_path":"datatransfer/io_gcs/api_docs/apidoc_download_url.py","file_name":"apidoc_download_url.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"41008147213","text":"\nmi_lista = []\ninput_usuario = input(\"Que deseas agregar a la lista de compras? (si ya has terminado escribe FIN)\")\n\nwhile input_usuario != \"FIN\":\n mi_lista.append(input_usuario)\n input_usuario = input(\"Que deseas agregar a la lista de compras? (si ya has terminado escribe FIN)\")\n\nfor item in mi_lista:\n print(\"Tengo que comprar {}\".format(item))\n\nprint()\nprint(\"Esta es la lista de la compra\")\ninput()\n\n\n\n\n\n\n\n\n\n\n","repo_name":"pedreke/MoritaCrack","sub_path":"lista.py","file_name":"lista.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"40538847124","text":"# -*- coding: utf-8 -*-\nimport argparse\nimport sys\nimport os\nimport datetime\nfrom collections import namedtuple\n\nDEFAULT_START_DATE = \"1970-01-01\"\nDEFAULT_END_DATE = datetime.datetime.strftime(datetime.datetime.now(),\n '%Y-%m-%d')\n\n# list commands\nListCommand = namedtuple(\"ListCommand\", \"dataset limit\")\nListWildcardCommand = namedtuple(\n \"ListWildcardCommand\", \"dataset limit table_prefix start_date end_date\")\nListRegexCommand = namedtuple(\n \"ListRegexCommand\", \"dataset limit table_name_pattern\")\n\n# delete commands\nDeleteNamedCommand = namedtuple(\"DeleteCommand\", \"dataset table_name\")\nDeleteFileCommand = namedtuple(\"DeleteFileCommand\", \"dataset delete_file\")\nDeleteWildcardCommand = namedtuple(\n \"DeleteWildcardCommand\", \"dataset table_prefix start_date end_date\")\nDeleteRegexCommand = namedtuple(\n \"DeleteRegexCommand\", \"dataset table_name_pattern\")\n\n# copy commands\nCopyFileCommand = namedtuple(\"CopyFileCommand\", \"dataset dest copy_file\")\nCopyWildcardCommand = namedtuple(\n \"CopyWildcardCommand\", \"dataset dest table_prefix start_date end_date\")\nCopyRegexCommand = namedtuple(\n \"CopyRegexCommand\", \"dataset dest table_name_pattern\")\n\n# data delete commands\nDataDeleteNamedCommand = namedtuple(\n \"DataDeleteCommand\", \"dataset condition table_name\")\nDataDeleteFileCommand = namedtuple(\n \"DataDeleteFileCommand\", \"dataset condition delete_file\")\nDataDeleteWildcardCommand = namedtuple(\n \"DataDeleteWildcardCommand\",\n \"dataset condition table_prefix start_date end_date\")\nDataDeleteRegexCommand = namedtuple(\n \"DataDeleteRegexCommand\", \"dataset condition table_name_pattern\")\n\n\ndef get_command():\n return parse_args(sys.argv[1:])\n\n\ndef parse_args(argv):\n \"\"\"This function will parse the args command line args.\n The function will return one of:\n - ListRegexCommand\n - ListWildcardCommand\n - ListCommand\n \"\"\"\n top_parser = argparse.ArgumentParser(\n description=\"Google BigQuery management tool.\")\n top_parser.add_argument(\"dataset\", help=\"\"\"The dateset.\"\"\")\n sub_parsers = top_parser.add_subparsers(dest=\"mode\", help=\"Command modes.\")\n\n # parser for listing tables\n ls_parser = sub_parsers.add_parser(\"ls\", description=\"Mode: list tables.\")\n ls_ex_group = ls_parser.add_mutually_exclusive_group()\n ls_ex_group = __add_wildcard_arg(ls_ex_group)\n ls_ex_group = __add_regex_arg(ls_ex_group)\n ls_parser.add_argument(\"-l\",\n \"--limit\",\n type=int,\n help=\"Limit to number of tables to show.\",\n default=50)\n\n # parser for deleting tables\n del_parser = sub_parsers.add_parser(\n \"del\", description=\"Mode: delete tables.\")\n del_ex_group = del_parser.add_mutually_exclusive_group()\n del_ex_group = __add_wildcard_arg(del_ex_group)\n del_ex_group = __add_regex_arg(del_ex_group)\n del_ex_group = __add_file_arg(del_ex_group)\n del_ex_group = __add_name_arg(del_ex_group)\n\n # parser for copying tables\n cp_parser = sub_parsers.add_parser(\"cp\", description=\"Mode: copy tables.\")\n cp_parser.add_argument(\"-d\",\n \"--destination\",\n help=\"The destination dataset.\",\n default=None)\n cp_ex_group = cp_parser.add_mutually_exclusive_group()\n cp_ex_group = __add_regex_arg(cp_ex_group)\n cp_ex_group = __add_wildcard_arg(cp_ex_group)\n cp_ex_group = __add_file_arg(cp_ex_group)\n\n # parser for delete data from tables\n ddel_parser = sub_parsers.add_parser(\n \"ddel\", description=\"Mode: delete data.\")\n ddel_parser.add_argument(\"-c\",\n \"--condition\",\n help=\"The condition to delete row.\",\n default=None)\n ddel_ex_group = ddel_parser.add_mutually_exclusive_group()\n ddel_ex_group = __add_wildcard_arg(ddel_ex_group)\n ddel_ex_group = __add_regex_arg(ddel_ex_group)\n ddel_ex_group = __add_file_arg(ddel_ex_group)\n ddel_ex_group = __add_name_arg(ddel_ex_group)\n\n args = top_parser.parse_args(argv)\n return args.mode, __parse_command(args)\n\n\ndef __add_wildcard_arg(arg_collection):\n arg_collection.add_argument(\n \"-w\", \"--wildcard\", nargs='+',\n help=\"\"\"Wildcard args:\\n\n 1. Table name without wildcard date suffix.\\n\n 2. Table start date string in YYYY-mm-dd.\\n\n 3. Table end date in YYYY-mm-dd.\"\"\")\n return arg_collection\n\n\ndef __add_regex_arg(arg_collection):\n arg_collection.add_argument(\n \"-r\", \"--regex\",\n help=\"Regex Expression to match the table name.\")\n return arg_collection\n\n\ndef __add_file_arg(arg_collection):\n arg_collection.add_argument(\n \"-f\",\n \"--file\",\n help=\"\"\"The file which contains the list of names \\\n of tables to deletes. \\\n Each line represents a table.\"\"\")\n return arg_collection\n\n\ndef __add_name_arg(arg_collection):\n arg_collection.add_argument(\n \"-n\",\n \"--name\",\n help=\"\"\"The name of the table to be matched.\"\"\")\n return arg_collection\n\n\ndef __parse_command(args):\n # parse args into command\n dataset = args.dataset\n if args.mode == \"ls\":\n # parse the command for listing tables\n limit = args.limit\n\n if args.regex is not None:\n return ListRegexCommand(dataset=dataset,\n limit=limit,\n table_name_pattern=args.regex)\n elif args.wildcard is not None:\n table_prefix, start_date, end_date = \\\n __extract_wildcard_command_parts(args.wildcard)\n\n return ListWildcardCommand(dataset=dataset,\n limit=limit,\n table_prefix=table_prefix,\n start_date=start_date,\n end_date=end_date)\n else:\n return ListCommand(dataset=dataset, limit=limit)\n\n elif args.mode == \"del\":\n # parse the command for deleting tables\n if args.regex is not None:\n return DeleteRegexCommand(dataset=dataset,\n table_name_pattern=args.regex)\n elif args.wildcard is not None:\n table_prefix, start_date, end_date = \\\n __extract_wildcard_command_parts(args.wildcard)\n\n return DeleteWildcardCommand(dataset=dataset,\n table_prefix=table_prefix,\n start_date=start_date,\n end_date=end_date)\n elif args.file is not None:\n return DeleteFileCommand(dataset=dataset,\n delete_file=__get_abs_file_path(args.file))\n elif args.name is not None:\n return DeleteNamedCommand(dataset=dataset, table_name=args.name)\n else:\n raise ValueError(\"Unrecognised delete mode.\")\n\n elif args.mode == \"cp\":\n # parse the command for copying tables\n if args.destination is None:\n raise ValueError(\"No destination dateset.\")\n\n if args.regex is not None:\n return CopyRegexCommand(dataset=dataset,\n dest=args.destination,\n table_name_pattern=args.regex)\n elif args.wildcard is not None:\n table_prefix, start_date, end_date = \\\n __extract_wildcard_command_parts(args.wildcard)\n return CopyWildcardCommand(dataset=dataset,\n dest=args.destination,\n table_prefix=table_prefix,\n start_date=start_date,\n end_date=end_date)\n elif args.file is not None:\n return CopyFileCommand(dataset=dataset,\n dest=args.destination,\n copy_file=__get_abs_file_path(args.file))\n else:\n raise ValueError(\"Unrecognised copy mode.\")\n elif args.mode == \"ddel\":\n if args.condition is None:\n raise ValueError(\"No deleting condition.\")\n\n condition = args.condition\n if args.regex is not None:\n return DataDeleteRegexCommand(\n dataset=dataset, condition=condition, table_name_pattern=args.regex)\n\n elif args.wildcard is not None:\n table_prefix, start_date, end_date = \\\n __extract_wildcard_command_parts(args.wildcard)\n return DataDeleteWildcardCommand(\n dataset=dataset,\n condition=condition,\n table_prefix=table_prefix,\n start_date=start_date,\n end_date=end_date)\n\n elif args.file is not None:\n return DataDeleteFileCommand(\n dataset=dataset,\n condition=condition,\n delete_file=__get_abs_file_path(args.file))\n\n elif args.name is not None:\n return DataDeleteNamedCommand(dataset=dataset, condition=condition, table_name=args.name)\n\n else:\n raise ValueError(\"Unrecognised delete mode.\")\n\n else:\n raise ValueError(\"Unrecognised mode: %s\" % args.mode)\n\n\ndef __extract_wildcard_command_parts(wildcard_args):\n if len(wildcard_args) > 3 or len(wildcard_args) == 2:\n raise \"The length of wildcard args should be 1 or 3.\"\n\n table_prefix = wildcard_args[0]\n\n if len(wildcard_args) == 1:\n start_date = DEFAULT_START_DATE\n end_date = DEFAULT_END_DATE\n else:\n start_date = wildcard_args[1]\n end_date = wildcard_args[2]\n\n # check the date string format\n try:\n datetime.datetime.strptime(start_date, \"%Y-%m-%d\")\n datetime.datetime.strptime(end_date, \"%Y-%m-%d\")\n except Exception as e:\n raise ValueError(\"Wrong format of date arguments. \\\n Please use YYYY-mm-dd instead.\")\n\n return table_prefix, start_date, end_date\n\n\ndef __get_abs_file_path(file_path):\n arg_file_path = file_path\n if os.path.isabs(arg_file_path):\n abs_path = arg_file_path\n else:\n working_path = os.getcwd()\n abs_path = os.path.join(working_path, arg_file_path)\n\n if not os.path.exists(abs_path):\n raise ValueError(\"Given file path doesn't exist: %s\" % file_path)\n\n return abs_path\n","repo_name":"visualskyrim/bquick","sub_path":"bquick/command_parser.py","file_name":"command_parser.py","file_ext":"py","file_size_in_byte":9900,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"42"} +{"seq_id":"38277436755","text":"from flask import Blueprint, render_template, flash, redirect, url_for, request, session, json\nfrom flask_login import login_required, login_user, logout_user\nfrom ..forms import LoginForm\nfrom ..application import login_manager\nfrom ..util.library import jwt_decode\nfrom ..util.enums import FlashMessagesCategory\nfrom .client_api import LoginResource, UserResource\nfrom ..models import AuthenticationObject, ErrorObject, UserObject\nfrom ..util.authentication import AuthHeader\nfrom jose.exceptions import JWTError, ExpiredSignatureError, JWTClaimsError\nfrom flask import current_app as app\n\nauth = Blueprint('auth', __name__, url_prefix='/auth')\n\n\n@login_manager.user_loader\ndef load_user(internal):\n user = None\n token = None\n\n try:\n if session['atlas_jwt_user']:\n user = UserObject.from_dict(session['atlas_jwt_user'])\n if session['atlas_jwt_token']:\n token = session['atlas_jwt_token']\n except Exception as e:\n return None\n\n app.logger.info('load_user: user {} / token {}'.format(user, token))\n if user and token:\n try:\n claims = jwt_decode(token)\n except (JWTError, ExpiredSignatureError, JWTClaimsError) as e:\n app.logger.error('Authentication Exception for user: {}'.format(e))\n session.pop('atlas_jwt_user', None)\n session.pop('atlas_jwt_token', None)\n return None\n return user\n\n\n@auth.route('/login', methods=['GET', 'POST'])\ndef login():\n form = LoginForm()\n next_url = request.args.get('next')\n\n if form.validate_on_submit():\n next_url = request.form['next']\n user_json = UserObject(username=form.email.data, password=form.password.data, internal='393020202',\n active=True, name='Ryan Padilha', phone='19981009370', document_main='41',\n user_email='ryan.padilha@peixeurbano.com', file_name=None, file_url=None,\n company='Peixe Urbano', occupation='Software Eng.')\n # AuthenticationObject(username=form.email.data, password=form.password.data).to_json()\n transaction = {'transaction': '8fpEQzmkXzxRfbAtiXQLMus6BhNS9gWocrNxM2ggCnw'}\n # LoginResource().authentication(data=user_json)\n\n if isinstance(transaction, ErrorObject):\n flash(u'O email ou o número de telefone inserido não corresponde a nenhuma conta',\n category=FlashMessagesCategory.ERROR.value)\n else:\n AuthHeader.set_credentials(access_token=transaction.get('access_token'),\n expires=transaction.get('expires_in'))\n\n user_internal = UserObject(username='ryan.padilha@peixeurbano.com', password='p31xE', internal='393020202',\n active=True, name='Ryan Padilha', phone='19981009370', document_main='41',\n user_email='ryan.padilha@peixeurbano.com', file_name=None, file_url=None,\n company='Peixe Urbano', occupation='Software Eng.')\n\n # UserResource().find_by_username(username=form.email.data)\n if user_json.password == user_internal.password:\n user = user_internal\n else:\n user = user_json\n\n if user:\n if not user.active:\n flash(u'Usuário não encontra-se ativo', category=FlashMessagesCategory.INFO.value)\n else:\n login_user(user, remember=form.remember_me.data)\n session.permanent = True\n session['atlas_jwt_user'] = json.loads(user.to_json())\n session['atlas_jwt_token'] = transaction.get('access_token')\n\n return redirect(next_url or url_for('website.index'))\n else:\n flash(u'Problema desconhecido ao recuperar usuário', category=FlashMessagesCategory.ERROR.value)\n\n return render_template('auth/login.html', form=form, next=next_url)\n\n\n@auth.route('/logout', methods=['GET'])\n@login_required\ndef logout():\n session.pop('atlas_jwt_user', None)\n session.pop('atlas_jwt_token', None)\n\n logout_user()\n return redirect(url_for('auth.login'))\n\n","repo_name":"ryanpadilha/flask-simple-store","sub_path":"brain/views/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":4257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"22324389064","text":"from django.urls import path\nfrom django.conf import settings\nfrom . import views\nfrom . import api\n\nurlpatterns = [\n path('', views.ListView.as_view(), name='homepage'),\n path('registration/', views.RegistrationView.as_view(), name='registration'),\n path('login/', views.LoginView.as_view(), name='login'),\n path('logout/', views.LogoutView.as_view(), name='logout'),\n path('key/', views.KeyView.as_view(), name='key'),\n path('site/create/', views.CreateSiteCardView.as_view(), name='site-create'),\n path('site/<uuid:id>/delete/', views.DeleteSiteCardView.as_view(), name='site-delete'),\n path('site/<uuid:id>/', views.UpdateSiteCardView.as_view(), name='site-update'),\n]\n\nif settings.API_ENABLE:\n urlpatterns += [\n path('api/registration/', api.Registration.as_view()),\n path('api/login/', api.Login.as_view()),\n path('api/logout/', api.Logout.as_view()),\n path('api/key/', api.Key.as_view()),\n path('api/sites/<uuid:id>/', api.SiteCard.as_view()),\n path('api/sites/', api.Sites.as_view()),\n ]","repo_name":"milkrage/pudding","sub_path":"app/pudding/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"74984336447","text":"import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport math\r\nfrom pandas import ExcelWriter\r\nfrom pandas import ExcelFile\r\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\r\nfrom sklearn import linear_model\r\n\r\ndef warn(*args, **kwargs):\r\n pass\r\nimport warnings\r\nwarnings.warn = warn\r\n\r\ndf_cons = pd.read_excel('consolidated_lda_dataset_log_wooutliers.xlsx')\r\ny_cons = df_cons.iloc[1:,0].values.tolist()\r\nX_cons = df_cons.iloc[1:,1:].values.tolist()\r\n\r\ny_lda = np.array(y_cons)\r\nX_lda = np.array(X_cons)\r\n\r\nclf_lda = LinearDiscriminantAnalysis()\r\nclf_lda.fit(X_lda,y_lda)\r\n\r\ncapital = float(input(\"How much is your required capital? \"\r\n \"Please convert to USD if otherwise.\"))\r\ncurrency = input(\"What currency will you be using? \"\r\n \"Choose between USD, CAD, EUR, GBP, AUD, or PHP.\")\r\nsegment = input(\"What industry would your product belong to? \"\r\n \"Choose between Arts, Music, Film, Games, Design & Tech, Publishing, \"\r\n \"Food & Crafts, Comics & Illustration\")\r\nrewards = float(input(\"How many reward levels will you be providing?\"))\r\nlength = float(input(\"How many days will your campaign last?\"))\r\nmonth = input(\"On what month will you start the campaign?\")\r\nvideos = float(input(\"How many videos will you be uploading?\"))\r\nimages = float(input(\"How many images will you be uploading?\"))\r\nfaqs = float(input(\"How many FAQs will you be posting?\"))\r\nfb = input(\"Will you be including a link to a Facebook page for the campaign? Yes or No\")\r\nupdates = float(input(\"How many updates are you planning to make?\"))\r\n\r\n#natural log transformation for capital\r\nlog_capital = math.log(capital)\r\n\r\n#dummy variables for currency\r\nusd = 0\r\ncad = 0\r\neur = 0\r\ngbp = 0\r\naud = 0\r\nphp = 0\r\n\r\nif currency == \"USD\":\r\n usd = 1\r\nelif currency == \"CAD\":\r\n cad = 1\r\nelif currency == \"EUR\":\r\n eur = 1\r\nelif currency == \"GBP\":\r\n gbp = 1\r\nelif currency == \"AUD\":\r\n aud = 1\r\nelif currency == \"PHP\":\r\n php = 1\r\nelse:\r\n pass\r\n\r\n#dummy variables for segment\r\narts = 0\r\nmusic = 0\r\nfilm = 0\r\ngames = 0\r\ndesign_tech = 0\r\npublishing = 0\r\nfood_crafts = 0\r\ncomics_illustration = 0\r\n\r\nif segment == \"Arts\":\r\n arts = 1\r\nelif segment == \"Music\":\r\n music = 1\r\nelif segment == \"Film\":\r\n film = 1\r\nelif segment == \"Games\":\r\n games = 1\r\nelif segment == \"Design & Tech\":\r\n design_tech = 1\r\nelif segment == \"Publishing\":\r\n publishing = 1\r\nelif segment == \"Food & Crafts\":\r\n food_crafts = 1\r\nelif segment == \"Comics & Illustration\":\r\n comics_illustration = 1\r\nelse:\r\n pass\r\n\r\n#dummy variables for month\r\njan = 0\r\nfeb = 0\r\nmar = 0\r\napr = 0\r\nmay = 0\r\njun = 0\r\njul = 0\r\naug = 0\r\nsep = 0\r\noct = 0\r\nnov = 0\r\ndec = 0\r\n\r\nif month == \"January\":\r\n jan = 1\r\nelif month == \"February\":\r\n feb = 1\r\nelif month == \"March\":\r\n mar = 1\r\nelif month == \"April\":\r\n apr = 1\r\nelif month == \"May\":\r\n may = 1\r\nelif month == \"June\":\r\n jun = 1\r\nelif month == \"July\":\r\n jul = 1\r\nelif month == \"August\":\r\n aug = 1\r\nelif month == \"September\":\r\n sep = 1\r\nelif month == \"October\":\r\n oct = 1\r\nelif month == \"November\":\r\n nov = 1\r\nelif month == \"December\":\r\n dec = 1\r\nelse:\r\n pass\r\n\r\n#dummy variables for fb\r\nif fb == \"Yes\":\r\n fb = float(1)\r\nelif fb == \"No\":\r\n fb = float(0)\r\nelse:\r\n pass\r\n\r\n\r\nuser_inputC = []\r\nuser_inputC.extend((log_capital, rewards, videos, images, faqs, fb, updates, usd, cad, eur, gbp, aud, php,\r\n arts, music, film, games, design_tech, publishing, food_crafts, comics_illustration,\r\n jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec))\r\nplatform = float(clf_lda.predict([user_inputC]))\r\n\r\nif platform == 1 and php == 0:\r\n platform = 0\r\n\r\nif platform == 0:\r\n print(\"Global Platform\")\r\nelif platform == 1:\r\n print(\"Local Platform\")\r\n\r\ndf_global = pd.read_excel('global_logit_dataset_log.xlsx')\r\ny_global = df_global.iloc[1:,0].values.tolist()\r\nX_global = df_global.iloc[1:,1:].values.tolist()\r\n\r\ndf_local = pd.read_excel('local_logit_dataset_log.xlsx')\r\ny_local = df_local.iloc[1:,0].values.tolist()\r\nX_local = df_local.iloc[1:,1:].values.tolist()\r\n\r\ny_logitG = np.array(y_global)\r\nX_logitG = np.array(X_global)\r\n\r\ny_logitL = np.array(y_local)\r\nX_logitL = np.array(X_local)\r\n\r\n\r\nif platform == 0:\r\n clf_logit = linear_model.LogisticRegression()\r\n clf_logit.fit(X_logitG,y_logitG)\r\n\r\n user_inputG = []\r\n user_inputG.extend((log_capital, length, videos, images, faqs, fb, updates, usd, cad, eur, gbp,\r\n arts, music, film, publishing, apr))\r\n lorc = float(clf_logit.predict([user_inputG]))\r\n\r\n if lorc == 0:\r\n print(\"Low Likelihood of Obtaining Required Capital\")\r\n elif lorc == 1:\r\n print(\"High Likelihood of Obtaining Required Capital\")\r\nelif platform == 1:\r\n clf_logit = linear_model.LogisticRegression()\r\n clf_logit.fit(X_logitL, y_logitL)\r\n\r\n user_inputL = []\r\n user_inputL.extend((log_capital, rewards, faqs, updates, may, jul))\r\n lorc = float(clf_logit.predict([user_inputL]))\r\n if lorc == 0:\r\n print(\"Low Likelihood of Obtaining Required Capital\")\r\n elif lorc == 1:\r\n print(\"High Likelihood of Obtaining Required Capital\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"J1Barcelon/crowdfundingPredictor","sub_path":"crowdfundingPredictor.py","file_name":"crowdfundingPredictor.py","file_ext":"py","file_size_in_byte":5255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"27601453401","text":"from tkinter import *\nimport pygame\nfrom tkinter import filedialog\n\nroot = Tk()\nroot.title(\"Lipbir - Music Player\")\nroot.iconbitmap(\"Images/icon.ico\")\nroot.geometry(\"500x300\")\nroot.resizable(False, False) \n\n# Add image file\nroot.config(bg='yellow')\n\nimg = PhotoImage(file=\"Images/bg1.png\")\nlabel = Label(\n root,\n image=img\n)\nlabel.place(x=0, y=0)\n\n\n\n# Init pygame mixer\npygame.mixer.init()\n\n# Add song functions\ndef add_song (e):\n song = filedialog.askopenfilename(initialdir = \"Musics/\", title = \"Choose A Song\", filetypes = ((\"mp3 Files\", \"*.mp3\"), (\"All Files\", \"*.*\")))\n \n song = song.replace(\"C:/Users/huawei/Documents/GitHub/Lipbir-Music-Player/Musics/\", \"\")\n song = song.replace(\".mp3\", \"\")\n \n # Add song to songbox\n song_box.insert(END, song)\ndef add_many_songs (e):\n songs = filedialog.askopenfilenames(initialdir = \"Musics/\", title = \"Choose Songs\", filetypes = ((\"mp3 Files\", \"*.mp3\"), (\"All Files\", \"*.*\")))\n for song in songs:\n song = song.replace(\"C:/Users/huawei/Documents/GitHub/Lipbir-Music-Player/Musics/\", \"\")\n song = song.replace(\".mp3\", \"\")\n \n song_box.insert(END, song)\n \n \n# Define Play functions\ndef play (e):\n song = song_box.get(ACTIVE)\n song = f'C:/Users/huawei/Documents/GitHub/Lipbir-Music-Player/Musics/{song}.mp3'\n \n pygame.mixer.music.load(song)\n pygame.mixer.music.play(loops= 0)\n \n# Define Stop functions\ndef stop (e):\n pygame.mixer.music.stop()\n song_box.selection_clear(ACTIVE)\n \n# Define Forward functions\ndef next_song (e):\n next_one = song_box.curselection()\n next_one = next_one [0] + 1\n song = song_box.get(next_one)\n \n song = f'C:/Users/huawei/Documents/GitHub/Lipbir-Music-Player/Musics/{song}.mp3'\n \n pygame.mixer.music.load(song)\n pygame.mixer.music.play(loops= 0)\n \n song_box.select_clear(0, END)\n \n song_box.activate(next_one)\n \n song_box.select_set(next_one, last = None)\n \n# Define Back functions\ndef previous_song (e):\n next_one = song_box.curselection()\n next_one = next_one [0] - 1\n song = song_box.get(next_one)\n \n song = f'C:/Users/huawei/Documents/GitHub/Lipbir-Music-Player/Musics/{song}.mp3'\n \n pygame.mixer.music.load(song)\n pygame.mixer.music.play(loops= 0)\n \n song_box.select_clear(0, END)\n \n song_box.activate(next_one)\n \n song_box.select_set(next_one, last = None)\n \n\n\n# Define Paise functions\nglobal paused\npaused = False\n\ndef pause (e, is_paused):\n global paused\n paused = is_paused\n if paused == True:\n pygame.mixer.music.unpause()\n paused = False\n else:\n pygame.mixer.music.pause()\n paused = True\n \n# Define delete song functions\ndef del_song (e):\n song_box.delete(ANCHOR)\n pygame.mixer.music.stop()\n\n# Define delete all songs functions\ndef del_all_songs ():\n song_box.delete(0, END)\n pygame.mixer.music.stop()\n \n\n# Create Playlist\nsong_box = Listbox(root, bg = \"lightblue\", fg = \"black\", width = 60, selectbackground = \"gray\", selectforeground = \"white\")\nsong_box.pack(pady = 20)\n\n# Define player control buttons images\nback_btn_img = PhotoImage(file = \"Images/back.png\")\nforward_btn_img = PhotoImage(file = \"Images/forward.png\")\nplay_btn_img = PhotoImage(file = \"Images/play.png\")\npause_btn_img = PhotoImage(file = \"Images/pause.png\")\nstop_btn_img = PhotoImage(file = \"Images/stop.png\")\n\n# Creatr player control frame\ncontrols_frame = Frame()\ncontrols_frame.pack()\n\n\n# Create player control buttons\nback_button = Button(controls_frame, image =back_btn_img, borderwidth = 0, command = lambda: previous_song(False))\nforward_button = Button(controls_frame, image =forward_btn_img, borderwidth = 0, command = lambda: next_song(False))\nplay_button = Button(controls_frame, image =play_btn_img, borderwidth = 0, command =lambda: play(False))\npause_button = Button(controls_frame, image =pause_btn_img, borderwidth = 0, command = lambda: pause(False, paused))\nstop_button = Button(controls_frame, image =stop_btn_img, borderwidth = 0, command =lambda: stop(False))\n\nback_button.grid(row = 0, column =1, padx = 7)\nforward_button.grid(row = 0, column =3, padx = 7)\nplay_button.grid(row = 0, column =2, padx = 7) \npause_button.grid(row = 0, column =0, padx = 7)\nstop_button.grid(row = 0, column =5, padx = 7)\n\n# Create Menu\nmy_menu = Menu(root)\nroot.config(menu = my_menu)\n\n# Create Add Songs menu\nadd_song_menu = Menu(my_menu, tearoff = False)\nmy_menu.add_cascade(label = \"Add Musics\", menu = add_song_menu)\nadd_song_menu.add_command(label = \"Add One Music To Playlist\", command = lambda: add_song(False), accelerator= \"Ctrl + O\")\nadd_song_menu.add_command(label = \"Add Many Musics To Playlist\", command = lambda: add_many_songs(False), accelerator= \"Ctrl + Shift + O\")\n\n# Create Delete Songs menu\nremove_song_menu = Menu(my_menu, tearoff = False)\nmy_menu.add_cascade(label = \"Remove Musics\", menu = remove_song_menu)\nremove_song_menu.add_command(label = \"Delete Music\", command = lambda: del_song(False), accelerator= \"Del\")\nremove_song_menu.add_command(label = \"Delete All Musics\", command = del_all_songs)\n\n\n\n\n# Bindings\nroot.bind(\"<Return>\", play)\nroot.bind(\"<Control-o>\", add_song)\nroot.bind(\"<Control-O>\", add_many_songs)\nroot.bind(\"<Delete>\", del_song)\nroot.bind(\"<BackSpace>\", del_song)\n\n\n\n\nroot.mainloop()","repo_name":"shayan-azizi/Lipbir-Music-Player","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5326,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"42"} +{"seq_id":"70857609727","text":"\n\n# create custom permissions\ndef isOwnerOfObject(self, object_owner_id):\n # first make sure the user is logged in\n if not self.request.user.is_authenticated:\n return False\n # check if the user is the owner of the job\n if self.request.user == object_owner_id:\n return True\n else:\n return False","repo_name":"TheAttentionSeeker5050/django-job-board","sub_path":"website/permissions.py","file_name":"permissions.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"32781258342","text":"from torch.autograd import Variable\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport torch\n\nclass NNModel(nn.Module):\n def __init__(self):\n super(NNModel, self).__init__()\n\n def init_weights(m):\n if isinstance(m, nn.Linear):\n torch.nn.init.xavier_normal_(m.weight)\n m.bias.data.fill_(0.01)\n\n self.layer = nn.Sequential(\n nn.Conv2d(3, 128, 5, padding=2),\n nn.BatchNorm2d(128),\n nn.ReLU(),\n nn.Conv2d(128, 128, 5, padding=2),\n nn.BatchNorm2d(128),\n nn.ReLU(),\n nn.MaxPool2d(2, 2),\n nn.Dropout2d(p=0.25),\n\n nn.Conv2d(128, 256, 3, padding=1),\n nn.BatchNorm2d(256),\n nn.ReLU(),\n nn.Conv2d(256, 256, 3, padding=1),\n nn.BatchNorm2d(256),\n nn.ReLU(),\n nn.MaxPool2d(2, 2),\n nn.Dropout2d(p=0.25)\n )\n \n self.layer.apply(init_weights)\n \n self.dense_layer = nn.Sequential(\n nn.Linear(256 * 8 * 8, 1024),\n nn.BatchNorm1d(1024),\n nn.ReLU(),\n nn.Dropout(p=0.5),\n nn.Linear(1024, 512),\n nn.BatchNorm1d(512),\n nn.ReLU(),\n nn.Dropout(p=0.5),\n nn.Linear(512, 10)\n )\n \n self.dense_layer.apply(init_weights)\n\n\n def forward(self, x):\n results = self.layer(x)\n results = results.view(-1, 256 * 8 * 8)\n results = self.dense_layer(results)\n return results","repo_name":"tealminivan/assignment_1","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"28040660587","text":"import sqlite3\nimport os\n\ndf = \"Databases/data.db\"\nbackup = \"Databases/backup.db\"\n\nclass DoesNotExist(Exception):\n pass\n\ndef start_connection(file):\n conn = sqlite3.connect(file)\n return conn\n\ndef close_connection(connection, commit):\n connection.commit()\n connection.close()\n\ndef db_set_prefix(guild_id, prefix=\"!\"):\n conn = start_connection(df)\n cursor = conn.cursor()\n cursor.execute(\"Select `id` from prefixes\")\n ids = cursor.fetchall()\n try:\n max_id = ids[-1][0]\n except:\n max_id = 0\n tbw_id = max_id + 1\n arg = f\"INSERT INTO Prefixes(id, ServerID, Prefix) Values(?, ?, ?)\"\n try:\n cursor.execute(arg, (tbw_id, guild_id, prefix))\n except sqlite3.IntegrityError:\n pass\n close_connection(conn, True)\n\ndef db_update_prefix(guild_id, prefix):\n conn = start_connection(df)\n cursor = conn.cursor()\n arg = \"UPDATE Prefixes\\nSET Prefix = ? WHERE ServerID = ?\"\n cursor.execute(arg, (prefix, guild_id))\n close_connection(conn, True)\n\ndef db_delete_prefix(guild_id):\n conn = start_connection(df)\n cursor = conn.cursor()\n cursor.execute(\"DELETE FROM Prefixes WHERE ServerID=?\", (guild_id))\n close_connection(conn, True)\n\ndef read_all_prefix():\n conn = start_connection(df)\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM Prefixes\")\n returndata = {}\n data = cursor.fetchall()\n for entry in data:\n returndata[entry[1]] = entry[2]\n close_connection(conn, False)\n return returndata \n\ndef db_set_welcome_message(guild_id, message, channelid):\n conn = start_connection(df)\n cursor = conn.cursor()\n cursor.execute(\"Select `id` from welcome_messages\")\n ids = cursor.fetchall()\n try:\n max_id = ids[-1][0]\n except:\n max_id = 0\n tbw_id = max_id + 1\n arg = f\"INSERT INTO welcome_messages(id, ServerID, message, channel) Values(?, ?, ?, ?)\"\n try:\n cursor.execute(arg, (tbw_id, guild_id, message, channelid))\n except sqlite3.IntegrityError:\n pass\n close_connection(conn, True)\n\ndef db_update_welcome_message(guild_id, message, channelid):\n conn = start_connection(df)\n cursor = conn.cursor()\n arg = \"UPDATE welcome_messages\\nSET message = ?\\nSET channel = ? WHERE ServerID = ?\"\n cursor.execute(arg, (message, channelid, guild_id))\n close_connection(conn, True)\n\ndef db_delete_welcome_message(guild_id):\n conn = start_connection(df)\n cursor = conn.cursor()\n try:\n cursor.execute(\"DELETE FROM welcome_messages WHERE ServerID=?\", (guild_id))\n close_connection(conn, True)\n except:\n close_connection(conn, False)\n raise DoesNotExist\n\n\ndef read_all_welcome_messages():\n conn = start_connection(df)\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM welcome_messages\")\n returndata = {}\n data = cursor.fetchall()\n for entry in data:\n returndata[entry[1]] = entry[2]\n close_connection(conn, False)\n return returndata \n\ndef backup():\n os.remove(\"Databases/backup.db\")\n conn = start_connection(df)\n cursor = conn.cursor()\n cursor.execute(\".clone ?\", (backup))\n close_connection(conn, True)","repo_name":"TheLegendBeacon/NewDiscordBot","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":2976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"5546641054","text":"import movingentity\nimport stats\nimport ika #for input\nimport blockmanager\n\n\nclass Player(movingentity.MovingEntity):\n\tdef __init__(self, x, y):\n\t\tmovingentity.MovingEntity.__init__(self, x, y, type = 'player')\n\t\t\n\t\tself.grabbedBlock = None\n\t\tself.collidesWithBlock = None #used in positionhandler, which will set block object when appropriate\n\t\tself.blockMoveSpeed = 1\n\t\t\n\tdef Update(self):\n\t\tkb = ika.Input.keyboard\n\t\t\t\n\t\tif kb['LEFT'].Position():\n\t\t\tself.SetState('MoveLeft')\n\t\telif kb['RIGHT'].Position():\n\t\t\tself.SetState('MoveRight')\n\t\telse:\n\t\t\tself.SetState('Wait')\n\t\t\t\n\t\tif kb['UP'].Pressed():\n\t\t\tif not self.IsFalling():\n\t\t\t\tself.AddState('Jump')\n\t\t\t\tself.StartFalling()\n\t\t\n\t\t#'grab' button\n\t\tif kb['DOWN'].Position(): \n\t\t\tif self.collidesWithBlock:\n\t\t\t\tif self.grabbedBlock is not self.collidesWithBlock:\n\t\t\t\t\tself.grabbedBlock = self.collidesWithBlock\n\t\t\t\t\tif self.direction is 'Left':\n\t\t\t\t\t\tself.AddState(\"GrabLeft\")\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.AddState(\"GrabRight\")\n\t\telse:\t#if not 'grabbing'\n\t\t\tself.DropBlock()\n\t\n\t\tmovingentity.MovingEntity.Update(self)\n\t\n\t\n\t\tif kb['1'].Pressed():\n\t\t\tx,y = self.GetBlockMakingCoords()\n\t\t\tblock = blockmanager.MakeBlock(x,y, 'standard') ##crappy. knows too much info\n\t\t\t##adjust for inventory count\n\t\t\t##add animation???\n\t\t\t\n\t\n\t\t\n\t\tif self.grabbedBlock:\n\t\t\t\n\t\t\tif self.currentState is \"MoveLeft\":\n\t\t\t\tself.grabbedBlock.BeMovedLeft(self.blockMoveSpeed)\n\t\t\telif self.currentState is \"MoveRight\":\n\t\t\t\tself.grabbedBlock.BeMovedRight(self.blockMoveSpeed)\n\t\t\t\t\n\t\t\t\n\t\t\t\"\"\"this code adjusts the player's position so that it remains next to the slower-moving block\"\"\"\n\t\t\t#check x distance from player - needed for pulling the block because it moves slower\n\t\t\tif \"GrabLeft\" in self.extraStates: #block on left of player\n\t\t\t\t#if not in the right spot...\n\t\t\t\tif self.realX + self.hotX is not self.grabbedBlock.realX + self.grabbedBlock.hotW + 1:\n\t\t\t\t\t#adjust position...\n\t\t\t\t\tcollided = self.MoveLeftBy(self.moveSpeed - self.blockMoveSpeed) ##might break if sum is negative.. probably won't happen\n\t\t\t\t\t#if still not in the right spot..\n\t\t\t\t\t##maybe don't need to check 'collided' as well\n\t\t\t\t\tif collided or self.realX + self.hotX is not self.grabbedBlock.realX + self.grabbedBlock.hotW + 1:\n\t\t\t\t\t\tself.DropBlock()\n\t\t\t\t\t\n\t\t\telif \"GrabRight\" in self.extraStates: #block on right\n\t\t\t\tif self.realX + self.hotX + self.hotW + 1 is not self.grabbedBlock.realX:\n\t\t\t\t\tcollided = self.MoveRightBy(self.moveSpeed - self.blockMoveSpeed) ##might break if sum is negative\n\t\t\t\t\tif collided or self.realX + self.hotX + self.hotW + 1 is not self.grabbedBlock.realX:\n\t\t\t\t\t\tself.DropBlock()\n\t\t\t\t\t\n\t\t\t\n\t\t\t#check y distance from player - needed in case block on ledge or falls too far from player\n\t\t\telif self.grabbedBlock.realY < self.realY or self.grabbedBlock.realY >= self.realY + 32: ##fix... height\n\t\t\t\tself.DropBlock()\n\t\t\t\n\t\t\t\n\t\t\t\t\n\t\t\n\t\t\n\t\t##crude, adjust to add collision detection before making a block\n\t\t##also ajust to add movement to make room for making a block\n\tdef GetBlockMakingCoords(self):\n\t\tif self.direction is 'Left':\n\t\t\tx = self.realX + self.hotX - 17#for block size\n\t\telse:\n\t\t\tx = self.realX + self.hotX + self.hotW + 1 #do not need width of block, just width of player\n\t\t\t\n\t\ty = self.realY\n\t\t\n\t\treturn x,y\n\t\t#leftQuads = self.GetOpenQuadrantsLeft() #return lists of number of open quadrants/tiles\n\t\t#rightQuads = self.GetOpenQuadrantsRight()\n\t\t#if leftQuads + rightQuads is not []:\n\t\t\t\n\t\t##incomplete\n\t\t#topQuads = self.GetOpenQuadrantsTop()\n\t\t#bottomQuads = self.GetOpenQuadrantsBottom() #probably will never be used\n\t\t#return x,y\n\t\n\tdef DropBlock(self):\n\t\tself.RemoveState(\"GrabLeft\")\n\t\tself.RemoveState(\"GrabRight\")\n\t\tself.grabbedBlock = None\n\t\t\n\t\n\t\n\t","repo_name":"emragins/trauzl","sub_path":"source/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":3690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"72029382207","text":"# Imports\nfrom flask import render_template,redirect,request\nfrom flask import Blueprint\nfrom werkzeug.wrappers import response\nfrom Classes.instrutor import Instrutor\nfrom Conectores import conector_instrutor\n\n# Instancia da 'objeto' Blueprint\nblue_instrutor = Blueprint(\"instrutores\",__name__)\n\n# Gerando rota index\n@blue_instrutor.route('/instrutores')\ndef instrutores_index():\n instrutores = conector_instrutor.get_all()\n return render_template('instrutores/index.html', instrutores = instrutores, title = 'Instrutores')\n\n# Gerando rota para criação de novo Instrutor\n@blue_instrutor.route('/instrutores/novo')\ndef novo_instrutor():\n return render_template('instrutores/novo.html',title =' Novo Instrutor ')\n\n# Pegando informações do form html e criando novo instrutor\n@blue_instrutor.route('/instrutores', methods = ['POST'])\ndef cria_instrutor():\n nome = request.form['nome']\n sobrenome = request.form['sobrenome']\n data_nascimento = request.form['data_nascimento']\n novo_instrutor = Instrutor(nome,sobrenome,data_nascimento)\n conector_instrutor.create(novo_instrutor)\n return redirect('/instrutores')\n\n# Gerando rota para edição de instrutor e fazendo a pesquisa do id no banco\n@blue_instrutor.route('/instrutores/<id>/edit')\ndef edita_instrutor(id):\n instrutor = conector_instrutor.get_one(id)\n return render_template('/instrutores/editar.html',instrutor = instrutor, title = 'Editar informações do Instrutor')\n\n# Pegando informações do form e editando o instrutor\n@blue_instrutor.route('/instrutores/<id>',methods = ['POST'])\ndef atualiza_instrutor(id):\n nome = request.form['nome']\n sobrenome = request.form['sobrenome']\n data_nascimento = request.form['data_nascimento']\n att_instrutor = Instrutor(nome, sobrenome,data_nascimento)\n conector_instrutor.edit(att_instrutor)\n return redirect('/instrutores')\n\n# Deleta instrutor\n@blue_instrutor.route('/instrutores/<id>/delete')\ndef delete_instrutor(id):\n conector_instrutor.delete_one(id)\n return redirect('/instrutores')","repo_name":"bdkiqdd/ML_Engineer","sub_path":"FEngSoftware/SistemaWeb/Controladores/controlador_instrutor.py","file_name":"controlador_instrutor.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"29080165322","text":"from random import randint\nimport os\n\n# Global variables defining performance increase or decrease\nGOOD_SUCK = 8\nGOOD_PICKUP = 8\nBAD_SUCK = 100\n# Global variables defining generation probabilities\nDIRT_PROBABILITY = 50\nJEWEL_PROBABILITY = 10\n\n\nclass Mansion(object):\n\n def __init__(self, dim):\n self.status_message = '' # Used to display information\n self.width = dim # Mansion dimensions\n self.height = dim\n self.board = [[Room(x, y) for x in range(self.width)] for y in range(self.height)] # The 2D array of rooms\n self.x_robot = self.width // 2 # Robot position\n self.y_robot = self.height // 2\n self.score = 50 # Performance score\n\n # Called once per frame, decides whether dust or jewels should appear\n def update(self):\n self.status_message += 'Performance score: %i\\n' % self.score\n # Generate dust\n event_occurred = randint(0, 99)\n if event_occurred < DIRT_PROBABILITY:\n x = randint(0, self.width - 1)\n y = randint(0, self.height - 1)\n self.board[x][y].insert_dirt()\n # Generate jewel\n event_occurred = randint(0, 99)\n if event_occurred < JEWEL_PROBABILITY:\n x = randint(0, self.width - 1)\n y = randint(0, self.height - 1)\n self.board[x][y].insert_jewel()\n\n # Suck the content of the room where the robot is\n def suck_room(self):\n room = self.board[self.x_robot][self.y_robot]\n if room.has_jewel() and room.has_dirt():\n self.status_message += \"Oops, jewel sucked!\\n\"\n self.score -= BAD_SUCK\n if room.has_dirt() and not room.has_jewel():\n self.status_message += \"Dust sucked.\\n\"\n self.score += GOOD_SUCK\n else:\n if not room.has_jewel() and not room.has_dirt():\n self.status_message += \"Nothing to suck!\\n\"\n self.board[self.x_robot][self.y_robot].state = 0\n\n # Pick up the content of the room where the robot is\n def pickup_room(self):\n room = self.board[self.x_robot][self.y_robot]\n if (room.state == 1) or (room.state == 0):\n self.status_message += \"Nothing to pick up!.\\n\"\n if room.state == 2:\n room.state = 0\n self.status_message += \"Jewel picked up.\\n\"\n self.score += GOOD_PICKUP\n if room.state == 3:\n room.state = 1\n self.status_message += \"Jewel picked up.\\n\"\n self.score += GOOD_PICKUP\n\n # Display the mansion state\n def show(self):\n os.system('cls' if os.name == 'nt' else 'clear')\n print('+', end='')\n for i in range(self.width):\n print(' -', end='')\n print(' +')\n for y in range(self.height):\n print('|', end=' ')\n for x in range(self.width):\n if (y == self.y_robot) & (x == self.x_robot):\n print(\"@\", end=' ')\n else:\n print('~' if self.board[x][y].state == 1\n else 'o' if self.board[x][y].state == 2\n else 'õ' if self.board[x][y].state == 3\n else ' ', end=' ')\n print('|')\n print('+', end='')\n for i in range(self.width):\n print(' -', end='')\n print(' +')\n print(self.status_message)\n self.status_message = ''\n\n\nclass Room(object):\n def __init__(self, x, y):\n self.state = 0\n self.robot = False\n self.x = x\n self.y = y\n\n def insert_dirt(self):\n if self.state == 0:\n self.state = 1\n elif self.state == 2:\n self.state = 3\n else:\n pass\n\n def insert_jewel(self):\n if self.state == 0:\n self.state = 2\n elif self.state == 1:\n self.state = 3\n else:\n pass\n\n def has_dirt(self):\n if self.state == 1 or self.state == 3:\n return True\n else:\n return False\n\n def has_jewel(self):\n if self.state == 2 or self.state == 3:\n return True\n else:\n return False\n","repo_name":"spieldy/Aspirobot","sub_path":"Environment.py","file_name":"Environment.py","file_ext":"py","file_size_in_byte":4145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"21179904357","text":"\"\"\"\nlogjson\n=======\n\nA Python logging Handler for JSON logs (with LogStash support)\n\n\"\"\"\nimport sys\nimport logging\nimport json\nimport datetime\nimport platform\nimport traceback\nimport copy\n\n\n__version__ = '2020.3.1'\n\n\nclass JSONFormatter(logging.Formatter):\n def __init__(self, logstash_mode=False, pretty=False, *args, **kwargs):\n super(JSONFormatter, self).__init__(*args, **kwargs)\n self.logstash_mode = logstash_mode\n self.pretty = pretty\n\n def format(self, record):\n record.message = record.getMessage()\n if self.usesTime(): # pragma: no cover\n record.asctime = self.formatTime(record, self.datefmt)\n\n if hasattr(record, 'exc_info') and record.exc_info:\n record.exc_text = ''.join(traceback.format_exception(*record.exc_info))\n record.message += '\\n' + record.exc_text\n\n # Actual isoformat. self.formatTime() is not the same.\n if sys.version_info.major == 2: # pragma: no cover\n record.created_iso = datetime.datetime.fromtimestamp(\n record.created\n ).isoformat()\n else:\n record.created_iso = datetime.datetime.fromtimestamp(\n record.created, datetime.timezone.utc\n ).isoformat()\n\n if self.logstash_mode:\n d = {\n '@message': record.message,\n '@source_host': platform.node(),\n '@timestamp': record.created_iso,\n '@fields': copy.copy(record.__dict__)\n }\n # Avoid duplicates\n del d['@fields']['message']\n del d['@fields']['created_iso']\n # This doesn't serialise to JSON well.\n del d['@fields']['exc_info']\n else:\n d = copy.copy(record.__dict__)\n # This doesn't serialise to JSON well.\n del d['exc_info']\n\n return json.dumps(d, default=str, indent=2 if self.pretty else None)\n","repo_name":"cjrh/logjson","sub_path":"logjson.py","file_name":"logjson.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"2609473216","text":"import odoo\nfrom odoo import api, fields, models, _\nfrom odoo.exceptions import ValidationError\n\nimport datetime\nfrom dateutil.relativedelta import relativedelta\nimport random\n\nclass KickerGame(models.Model):\n _name = 'kicker.game'\n _description = 'Kicker Game'\n _order = 'create_date DESC'\n\n name = fields.Char(compute='_compute_name')\n date = fields.Date(default=fields.Date.context_today, required=True)\n kicker_id = fields.Many2one('kicker.kicker', string='Kicker', ondelete='restrict', index=True)\n winning_team = fields.Selection([('team_1', 'Team 1'), ('team_2', 'Team 2')], compute='_compute_winning_team', store=True)\n score_1 = fields.Integer(string=\"Team 1 Score\", required=True)\n score_2 = fields.Integer(string=\"Team 2 Score\", required=True)\n session_ids = fields.One2many('kicker.session', 'game_id', string='Sessions')\n \n @api.depends('score_1', 'score_2')\n def _compute_winning_team(self):\n for game in self:\n game.winning_team = 'team_1' if game.score_1 > game.score_2 else 'team_2'\n \n @api.depends('score_1', 'score_2', 'session_ids')\n def _compute_name(self):\n for game in self:\n game.name = '@'.join([\n self.env['ir.qweb.field.date'].value_to_html(game.date, {}),\n game.kicker_id.name\n ])\n \n# @api.constrains('session_ids')\n# def _validate_session(self):\n# for game in self:\n# if len(game.session_ids != 4):\n# raise ValidationError(_('There must be 4 players per game'))\n\n @api.model\n def _generate_demo_data(self, amount=100):\n seconds_in_year = 365*24*60*60\n vals = list()\n kickers = self.env['kicker.kicker'].search([])\n for i in range(amount):\n players = self.env['res.partner'].search([('kicker_player', '=', True)])\n player_ids = random.sample(players.ids, 4)\n date = datetime.datetime.now() - datetime.timedelta(seconds=random.randrange(0,seconds_in_year))\n vals.append({\n 'date': date,\n 'kicker_id': kickers[random.randrange(0, len(kickers))].id,\n 'score_1': 11,\n 'score_2': 11 - random.randrange(2, 11),\n 'session_ids': [\n (0, False, {'team': 'team_1', 'player_id': player_ids[1]}),\n (0, False, {'team': 'team_2', 'player_id': player_ids[2]}),\n (0, False, {'team': 'team_2', 'player_id': player_ids[3]}),\n (0, False, {'team': 'team_1', 'player_id': player_ids[0]}),\n ]\n })\n self.create(vals)\n\nclass KickerSession(models.Model):\n _name = 'kicker.session'\n _description = 'Kicker Session'\n\n game_id = fields.Many2one('kicker.game', required=True, index=True)\n won = fields.Boolean(compute='_compute_won', store=True)\n team = fields.Selection([('team_1', 'Team 1'), ('team_2', 'Team 2')], required=True)\n player_id = fields.Many2one('res.partner', string='Player', index=True,\n domain=\"[('kicker_player', '=', True)]\")\n game_date = fields.Date(related='game_id.date', store=True)\n\n @api.depends('game_id', 'game_id.winning_team')\n def _compute_won(self):\n for session in self:\n session.won = session.team == session.game_id.winning_team\n","repo_name":"openkicker/kicker","sub_path":"kicker/models/kicker_game.py","file_name":"kicker_game.py","file_ext":"py","file_size_in_byte":3344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"29347150424","text":"from random import choice, randint\n\nfrom caluma.caluma_form.models import Form, Question\nfrom caluma.caluma_user.models import BaseUser\nfrom caluma.caluma_workflow.api import start_case\nfrom caluma.caluma_workflow.models import Workflow\nfrom django.core.management.base import BaseCommand\nfrom django.utils.timezone import now\n\nfrom camac.instance.models import Instance, InstanceState\nfrom camac.user.models import Service, User\n\n\nclass Command(BaseCommand):\n help = \"Creates an example of a RSTA migrated instance\"\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"-c\",\n \"--count\",\n type=int,\n default=1,\n dest=\"count\",\n help=\"Number of created instances\",\n required=False,\n )\n parser.add_argument(\n \"-s\",\n \"--service\",\n type=int,\n default=2, # Burgdorf\n dest=\"service_id\",\n help=\"Target service for the instance\",\n required=False,\n )\n\n def handle(self, *args, **options):\n workflow = Workflow.objects.get(pk=\"migrated\")\n form = Form.objects.get(pk=\"migriertes-dossier\")\n question = Question.objects.get(pk=\"geschaeftstyp\")\n service = Service.objects.get(pk=options[\"service_id\"])\n instance_state = InstanceState.objects.get(name=\"in_progress\")\n group = service.groups.filter(role__trans__name=\"Leitung Leitbehörde\").first()\n user = User.objects.get(username=\"service-account-camac-admin\")\n\n caluma_user = BaseUser()\n caluma_user.username = user.username\n caluma_user.group = group.pk\n\n for _ in range(0, options[\"count\"]):\n instance = Instance.objects.create(\n creation_date=now(),\n modification_date=now(),\n group=group,\n instance_state=instance_state,\n previous_instance_state=instance_state,\n user=user,\n form_id=1,\n )\n\n instance.instance_services.create(service=service, active=1)\n\n case = start_case(\n workflow=workflow,\n form=form,\n user=caluma_user,\n meta={\n \"camac-instance-id\": instance.pk,\n \"submit-date\": now().strftime(\"%Y-%m-%dT%H:%M:%S%z\"),\n \"ebau-number\": f\"{now().year}-{randint(100,200)}\",\n },\n )\n\n case.document.answers.create(\n question=question,\n value=choice(question.options.values_list(\"slug\", flat=True)),\n )\n\n case.document.answers.create(question_id=\"gemeinde\", value=service.pk)\n","repo_name":"inosca/ebau","sub_path":"django/camac/instance/management/commands/create_rsta_migrated_instance.py","file_name":"create_rsta_migrated_instance.py","file_ext":"py","file_size_in_byte":2743,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"42"} +{"seq_id":"70385232767","text":"import drjit as dr\nimport mitsuba as mi\n\nmi.set_variant('cuda_ad_rgb')\n\nscene = mi.load_file('../scenes/cbox.xml')\n\nparams = mi.traverse(scene)\n\nkey = 'green.reflectance.value'\n\n# Mark the green wall color parameter as differentiable\ndr.enable_grad(params[key])\n\n# Propagate this change to the scene internal state\nparams.update()\n\nimage = mi.render(scene, params, spp=128)\n\n# Forward-propagate gradients through the computation graph\ndr.forward(params[key])\n\n# Fetch the image gradient values\ngrad_image = dr.grad(image)\n\nfrom matplotlib import pyplot as plt\nimport matplotlib.cm as cm\n\ncmap = cm.coolwarm\nvlim = dr.max(dr.abs(grad_image))[0]\nprint(f'Remapping colors within range: [{-vlim:.2f}, {vlim:.2f}]')\n\nfig, axx = plt.subplots(1, 3, figsize=(8, 3))\nfor i, ax in enumerate(axx):\n ax.imshow(grad_image[..., i], cmap=cm.coolwarm, vmin=-vlim, vmax=vlim)\n ax.set_title('RGB'[i] + ' gradients')\n ax.axis('off')\nfig.tight_layout()\nplt.show()","repo_name":"gmf128/mitsuba-quickstart","sub_path":"quickstart/forward-inverse.py","file_name":"forward-inverse.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"72333624446","text":"from npu_bridge.npu_init import *\nimport numpy as np\nimport tensorflow as tf\nfrom ops import fc\n\n\nclass Generator(object):\n def __init__(self, name, h, w, c, norm_type, deconv_type, is_train):\n self.name = name\n self._h = h\n self._w = w\n self._c = c\n self._norm_type = norm_type\n self._deconv_type = deconv_type\n self._is_train = is_train\n self._reuse = False\n\n def __call__(self, input):\n if self._deconv_type == 'bilinear':\n from ops import bilinear_deconv2d as deconv2d\n elif self._deconv_type == 'nn':\n from ops import nn_deconv2d as deconv2d\n elif self._deconv_type == 'transpose':\n from ops import deconv2d\n else:\n raise NotImplementedError\n with tf.variable_scope(self.name, reuse=self._reuse):\n if not self._reuse:\n print('\\033[93m'+self.name+'\\033[0m')\n _ = tf.reshape(input, [input.get_shape().as_list()[0], 1, 1, -1])\n _ = fc(_, 1024, self._is_train, info=not self._reuse, norm='None', name='fc')\n for i in range(int(np.ceil(np.log2(max(self._h, self._w))))):\n _ = deconv2d(_, max(self._c, int(_.get_shape().as_list()[-1]/2)), \n self._is_train, info=not self._reuse, norm=self._norm_type,\n name='deconv{}'.format(i+1))\n _ = deconv2d(_, self._c, self._is_train, k=1, s=1, info=not self._reuse,\n activation_fn=tf.tanh, norm='None',\n name='deconv{}'.format(i+2))\n _ = tf.image.resize_bilinear(_, [self._h, self._w])\n\n self._reuse = True\n self.var_list = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, self.name)\n return _\n\n","repo_name":"Ascend/ModelZoo-TensorFlow","sub_path":"TensorFlow/contrib/cv/Improved-GAN_ID2094_for_Tensorflow/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"42"} +{"seq_id":"73181991486","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy as sy\nimport scipy.fftpack as syfp\n\nuInitial=0 #CI\nudInitial=1 \n\n#paramètres\nomega=5 #pulsation\nm=1000000 #masse\nt=np.array([0.1,0.5,1,5]) # tableau des dt\ndT=np.zeros(int(np.shape(t)[0]))\ntArray=np.zeros(int(np.shape(t)[0]))\ngamma=0.25 # paramètre\nbeta=0.5\nfig,ax=plt.subplots(int(np.shape(t)[0]),1)\n\nfor j in range(0,len(t)) :\n N=t[j] #intervalle d'intégration\n T=2*np.pi/omega # Période\n multiple=100\n drange=np.arange(0,multiple*T,N) \n umax=pow(pow(uInitial,2)+pow(udInitial/omega,2),0.5)\n uExact=umax*np.sin(omega*drange) # solution exacte\n\n \n # initialisation\n u=np.zeros(drange.size)\n ud=np.zeros(drange.size)\n udd=np.zeros(drange.size)\n \n # Méthode de Newmark\n u[0]=uInitial\n ud[0]=udInitial\n for i in range(0,drange.size-1):\n C1=u[i]+N*ud[i]+0.5*np.power(N,2)*(1-2*beta)*udd[i]\n C2=ud[i]+N*(1-gamma)*udd[i]\n \n udd[i+1]=-np.power(omega,2)*C1/(1+beta*np.power(omega,2)*np.power(N,2))\n ud[i+1]=ud[i]+N*((1-gamma)*udd[i]+gamma*udd[i+1])\n u[i+1]=u[i]+N*ud[i]+0.5*np.power(N,2)*((1-2*beta)*udd[i]+2*beta*udd[i+1])\n \n #afficher la solution numérique\n #ax[j].plot(drange,u,linestyle='solid') \n #ax[j].title.set_text(r'$\\Delta t=$'+str(N))\n \n ax[j].plot(drange,(uExact-u),linestyle='solid') \n ax[j].title.set_text(r'Différence ' r'$\\Delta t=$'+str(N))\n\n \nplt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=1)\nfig.text(0.5, 0.02, 'Période d\\'intégration', ha='center')\n","repo_name":"shddd/TIPE","sub_path":"99999_newmark_dt.py","file_name":"99999_newmark_dt.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"42"} +{"seq_id":"36253668925","text":"from functools import reduce\n\nfrom torch import nn\nfrom operator import mul\n\nimport utils.models as utils\nfrom .local_loss_blocks import LocalLossBlockLinear, LocalLossBlockConv\nfrom .local_loss_net import LocalLossNet\n\n\nclass FullyConnectedNet(LocalLossNet):\n '''\n A fully connected network.\n The network can be trained by backprop or by locally generated error signal based on cross-entropy and/or similarity matching loss.\n\n Args:\n num_layers (int): Number of hidden layers.\n num_hidden (int): Number of units in each hidden layer.\n input_dim (list): Iterable of input dimenstions, usually (ch, h, w).\n input_ch (int): Number of feature maps for input.\n num_classes (int): Number of classes (used in local prediction loss).\n '''\n\n def __init__(self, args, num_layers, num_hidden, input_dim, num_classes, dropout=0):\n super().__init__()\n self.args = args\n\n self.num_hidden = num_hidden\n self.dropout = dropout\n self.num_layers = num_layers\n reduce_factor = 1\n self.layers = nn.ModuleList([utils.ViewLayer()])\n if num_layers > 0:\n self.layers.extend(\n [LocalLossBlockLinear(self.args, reduce(mul, input_dim, 1), num_hidden, num_classes, first_layer=True,\n dropout=dropout, print_stats=self.args.print_stats)])\n\n self.layers.extend([LocalLossBlockLinear(self.args, int(num_hidden // (reduce_factor ** (i - 1))),\n int(num_hidden // (reduce_factor ** i)), num_classes,\n print_stats=self.args.print_stats)\n for i in range(1, num_layers)])\n\n self.layers.extend([nn.Linear(int(num_hidden // (reduce_factor ** (num_layers - 1))), num_classes)])\n\n # Was in original code, no clue why this was used\n \"\"\"if not args.backprop:\n self.layers[-1].weight.data.zero_()\"\"\"\n\n\ncfg = {\n 'vgg6a': [128, 'M', 256, 'M', 512, 'M', 512],\n 'vgg6b': [128, 'M', 256, 'M', 512, 'M', 512, 'M'],\n 'vgg8': [64, 'M', 128, 'M', 256, 'M', 512, 'M', 512, 'M'],\n 'vgg8a': [128, 256, 'M', 256, 512, 'M', 512, 'M', 512],\n 'vgg8b': [128, 256, 'M', 256, 512, 'M', 512, 'M', 512, 'M'],\n 'vgg11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],\n 'vgg11b': [128, 128, 128, 256, 'M', 256, 512, 'M', 512, 512, 'M', 512, 'M'],\n 'vgg13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],\n 'vgg16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],\n 'vgg19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],\n}\n\n\nclass VGGn(LocalLossNet):\n '''\n VGG and VGG-like networks.\n The network can be trained by backprop or by locally generated error signal based on cross-entropy and/or similarity matching loss.\n\n Args:\n vgg_name (str): The name of the network.\n input_dim (list): Iterable of input dimenstions, usually (ch, h, w)\n num_layers (int): Number of layers\n num_classes (int): Number of classes (used in local prediction loss).\n feat_mult (float): Multiply number of feature maps with this number.\n '''\n\n def __init__(self, local_loss_args, vgg_name, input_dim, num_layers, num_hidden, num_classes, dropout=0,\n feat_mult=1):\n super(VGGn, self).__init__()\n self.cfg = cfg[vgg_name]\n self.args = local_loss_args\n self.input_dim = input_dim\n self.input_ch = input_dim[0]\n self.num_classes = num_classes\n self.num_layers = num_layers\n self.num_hidden = num_hidden\n self.dropout = dropout\n self.layers = self._make_layers(self.cfg, self.input_ch, input_dim[1], feat_mult)\n\n def _make_layers(self, cfg, input_ch, input_dim, feat_mult):\n layers = []\n first_layer = True\n scale_cum = 1\n for x in cfg:\n if x == 'M':\n layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\n scale_cum *= 2\n elif x == 'M3':\n layers += [nn.MaxPool2d(kernel_size=3, stride=2, padding=1)]\n scale_cum *= 2\n elif x == 'M4':\n layers += [nn.MaxPool2d(kernel_size=4, stride=4)]\n scale_cum *= 4\n elif x == 'A':\n layers += [nn.AvgPool2d(kernel_size=2, stride=2)]\n scale_cum *= 2\n elif x == 'A3':\n layers += [nn.AvgPool2d(kernel_size=3, stride=2, padding=1)]\n scale_cum *= 2\n elif x == 'A4':\n layers += [nn.AvgPool2d(kernel_size=4, stride=4)]\n scale_cum *= 4\n else:\n x = int(x * feat_mult)\n if first_layer and input_dim > 64:\n scale_cum = 2\n layers += [LocalLossBlockConv(self.args, input_ch, x, kernel_size=7, stride=2, padding=3,\n num_classes=self.num_classes,\n dim_out=input_dim // scale_cum,\n first_layer=first_layer)]\n else:\n layers += [LocalLossBlockConv(self.args, input_ch, x, kernel_size=3, stride=1, padding=1,\n num_classes=self.num_classes,\n dim_out=input_dim // scale_cum,\n first_layer=first_layer)]\n input_ch = x\n first_layer = False\n if isinstance(x, int):\n output_ch = x\n\n output_dim = input_dim // scale_cum\n layers += [\n FullyConnectedNet(self.args, self.num_layers, self.num_hidden, [output_ch, output_dim, output_dim], self.num_classes,\n self.dropout)]\n\n return nn.ModuleList(layers)\n","repo_name":"bonfab/local-error-signals","sub_path":"src/models/vgg.py","file_name":"vgg.py","file_ext":"py","file_size_in_byte":6072,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"26157439874","text":"message = input()\ncommand = input().split('|')\n\nwhile not command[0] == \"Decode\":\n\n if command[0] == \"Move\":\n message = message[int(command[1]):] + message[:int(command[1])]\n elif command[0] == \"Insert\":\n char = int(command[1])\n index = command[2]\n message = list(message)\n message.insert(char, index)\n message = ''.join(message)\n\n elif command[0] == \"ChangeAll\":\n old_char = command[1]\n new_char = command[2]\n message = list(message)\n if old_char in message:\n # lambda arguments : expression\n # map(function_object, iterable1, iterable2,...)\n # Syntax: l=list(map(lambda x: x.replace(‘old_value’,’new_value’),l))\n\n message = ''.join(list(map(lambda x: x.replace(old_char,new_char), message)))\n\n command = input().split('|')\n\nprint(f\"The decrypted message is: {message}\")\n","repo_name":"sjstanev/python","sub_path":"python-fundamental/fundamentals - exams/Programming Fundamentals Final Exam Retake/01. The Imitation Game.py","file_name":"01. The Imitation Game.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"6967117065","text":"\"\"\"\nColorizing the text mask.\nChange the original code to Python3 support and simplifed the code structure.\nOriginal project: https://github.com/ankush-me/SynthText\nAuthor: Ankush Gupta\nDate: 2015\n\"\"\"\nimport cv2\nimport numpy as np\nimport copy\nimport matplotlib.pyplot as plt\nimport scipy.interpolate as si\nimport scipy.ndimage as scim\nimport scipy.ndimage.interpolation as sii\nimport os\nimport os.path as osp\nimport pickle as cp\nfrom PIL import Image\nimport random\nfrom . import poisson_reconstruct\n\n\nclass Layer(object):\n\n def __init__(self, alpha, color):\n\n # alpha for the whole image:\n assert alpha.ndim == 2\n self.alpha = alpha\n [n,m] = alpha.shape[:2]\n\n color = np.atleast_1d(np.array(color)).astype(np.uint8)\n # color for the image:\n if color.ndim == 1: # constant color for whole layer\n ncol = color.size\n if ncol == 1 : #grayscale layer\n self.color = color * np.ones((n, m, 3), dtype = np.uint8)\n if ncol == 3 :\n self.color = np.ones((n,m,3), dtype = np.uint8) * color[None,None,:]\n elif color.ndim == 2: # grayscale image\n self.color = np.repeat(color[:,:,None], repeats = 3, axis = 2).copy().astype(np.uint8)\n elif color.ndim == 3: #rgb image\n self.color = color.copy().astype(np.uint8)\n else:\n print (color.shape)\n raise Exception(\"color datatype not understood\")\n\nclass FontColor(object):\n\n def __init__(self, colorsRGB, colorsLAB):\n \n self.colorsRGB = colorsRGB\n self.colorsLAB = colorsLAB\n self.ncol = colorsRGB.shape[0]\n\n def sample_normal(self, col_mean, col_std):\n \n col_sample = col_mean + col_std * np.random.randn()\n return np.clip(col_sample, 0, 255).astype(np.uint8)\n\n def sample_from_data(self, bg_mat):\n \n bg_orig = bg_mat.copy()\n bg_mat = cv2.cvtColor(bg_mat, cv2.COLOR_RGB2Lab)\n bg_mat = np.reshape(bg_mat, (np.prod(bg_mat.shape[:2]),3))\n bg_mean = np.mean(bg_mat, axis = 0)\n\n norms = np.linalg.norm(self.colorsLAB - bg_mean[None,:], axis = 1)\n # choose a random color amongst the top 3 closest matches:\n #nn = np.random.choice(np.argsort(norms)[:3]) \n nn = np.argmin(norms)\n\n ## nearest neighbour color:\n data_col = self.colorsRGB[np.mod(nn, self.ncol),:]\n\n # color\n col1 = self.sample_normal(data_col[:3],data_col[3:6])\n col2 = self.sample_normal(data_col[6:9],data_col[9:12])\n\n if nn < self.ncol:\n return (col2, col1)\n else:\n # need to swap to make the second color close to the input backgroun color\n return (col1, col2)\n\n def mean_color(self, arr):\n \n col = cv2.cvtColor(arr, cv2.COLOR_RGB2HSV)\n col = np.reshape(col, (np.prod(col.shape[:2]),3))\n col = np.mean(col, axis = 0).astype(np.uint8)\n return np.squeeze(cv2.cvtColor(col[None,None,:], cv2.COLOR_HSV2RGB))\n\n def invert(self, rgb):\n \n rgb = 127 + rgb\n return rgb\n\n def complement(self, rgb_color):\n \n col_hsv = np.squeeze(cv2.cvtColor(rgb_color[None,None,:], cv2.COLOR_RGB2HSV))\n col_hsv[0] = col_hsv[0] + 128 #uint8 mods to 255\n col_comp = np.squeeze(cv2.cvtColor(col_hsv[None,None,:], cv2.COLOR_HSV2RGB))\n return col_comp\n\n def triangle_color(self, col1, col2):\n \n col1, col2 = np.array(col1), np.array(col2)\n col1 = np.squeeze(cv2.cvtColor(col1[None,None,:], cv2.COLOR_RGB2HSV))\n col2 = np.squeeze(cv2.cvtColor(col2[None,None,:], cv2.COLOR_RGB2HSV))\n h1, h2 = col1[0], col2[0]\n if h2 < h1: h1, h2 = h2, h1 #swap\n dh = h2 - h1\n if dh < 127: dh = 255 - dh\n col1[0] = h1 + dh / 2\n return np.squeeze(cv2.cvtColor(col1[None,None,:],cv2.COLOR_HSV2RGB))\n\n def change_value(self, col_rgb, v_std=50):\n \n col = np.squeeze(cv2.cvtColor(col_rgb[None,None,:], cv2.COLOR_RGB2HSV))\n x = col[2]\n vs = np.linspace(0,1)\n ps = np.abs(vs - x / 255.0)\n ps /= np.sum(ps)\n v_rand = np.clip(np.random.choice(vs, p = ps) + 0.1 * np.random.randn(), 0, 1)\n col[2] = 255 * v_rand\n return np.squeeze(cv2.cvtColor(col[None,None,:], cv2.COLOR_HSV2RGB))\n\nclass Colorize(object):\n\n def __init__(self):\n pass\n\n def drop_shadow(self, alpha, theta, shift, size, op=0.80):\n \n if size % 2 == 0:\n size -= 1\n size = max(1, size)\n shadow = cv2.GaussianBlur(alpha, (size,size), 0)\n [dx, dy] = shift * np.array([-np.sin(theta), np.cos(theta)])\n shadow = op * sii.shift(shadow, shift = [dx,dy], mode = 'constant', cval = 0)\n return shadow.astype(np.uint8)\n\n def border(self, alpha, size, kernel_type = 'RECT'):\n \n kdict = {'RECT':cv2.MORPH_RECT, 'ELLIPSE':cv2.MORPH_ELLIPSE,\n 'CROSS':cv2.MORPH_CROSS}\n kernel = cv2.getStructuringElement(kdict[kernel_type], (size, size))\n border = cv2.dilate(alpha, kernel, iterations = 1) # - alpha\n return border\n\n def blend(self, cf, cb, mode = 'normal'):\n \n return cf\n\n def merge_two(self, fore, back, blend_type = None):\n \n a_f = fore.alpha / 255.0\n a_b = back.alpha / 255.0\n c_f = fore.color\n c_b = back.color\n\n a_r = a_f + a_b - a_f*a_b\n if blend_type != None:\n c_blend = self.blend(c_f, c_b, blend_type)\n c_r = (((1-a_f)*a_b)[:,:,None] * c_b\n + ((1-a_b)*a_f)[:,:,None] * c_f\n + (a_f*a_b)[:,:,None] * c_blend)\n else:\n c_r = (((1-a_f)*a_b)[:,:,None] * c_b\n + a_f[:,:,None]*c_f)\n\n return Layer((255 * a_r).astype(np.uint8), c_r.astype(np.uint8))\n\n def merge_down(self, layers, blends = None):\n \n nlayers = len(layers)\n if nlayers > 1:\n [n, m] = layers[0].alpha.shape[:2]\n out_layer = layers[-1]\n for i in range(-2, -nlayers-1, -1):\n blend = None\n if blends is not None:\n blend = blends[i+1]\n out_layer = self.merge_two(fore = layers[i], back = out_layer, blend_type = blend)\n return out_layer\n else:\n return layers[0]\n\n def resize_im(self, im, osize):\n return np.array(Image.fromarray(im).resize(osize[::-1], Image.BICUBIC))\n\n def color_border(self, col_text, col_bg, bordar_color_type, bordar_color_idx, bordar_color_noise):\n \n choice = np.random.choice(3)\n\n col_text = cv2.cvtColor(col_text, cv2.COLOR_RGB2HSV)\n col_text = np.reshape(col_text, (np.prod(col_text.shape[:2]), 3))\n col_text = np.mean(col_text,axis = 0).astype(np.uint8)\n\n vs = np.linspace(0, 1)\n def get_sample(x):\n ps = np.abs(vs - x / 255.0)\n ps /= np.sum(ps)\n v_rand = np.clip(np.random.choice(vs, p = ps) + 0.1 * bordar_color_noise, 0, 1)\n return 255 * v_rand\n\n # first choose a color, then inc/dec its VALUE:\n if choice == 0:\n # increase/decrease saturation:\n col_text[0] = get_sample(col_text[0]) # saturation\n col_text = np.squeeze(cv2.cvtColor(col_text[None,None,:], cv2.COLOR_HSV2RGB))\n elif choice == 1:\n # get the complementary color to text:\n col_text = np.squeeze(cv2.cvtColor(col_text[None,None,:], cv2.COLOR_HSV2RGB))\n col_text = self.font_color.complement(col_text)\n else:\n # choose a mid-way color:\n col_bg = cv2.cvtColor(col_bg, cv2.COLOR_RGB2HSV)\n col_bg = np.reshape(col_bg, (np.prod(col_bg.shape[:2]), 3))\n col_bg = np.mean(col_bg,axis = 0).astype(np.uint8)\n col_bg = np.squeeze(cv2.cvtColor(col_bg[None,None,:], cv2.COLOR_HSV2RGB))\n col_text = np.squeeze(cv2.cvtColor(col_text[None,None,:], cv2.COLOR_HSV2RGB))\n col_text = self.font_color.triangle_color(col_text, col_bg)\n\n # now change the VALUE channel: \n col_text = np.squeeze(cv2.cvtColor(col_text[None,None,:], cv2.COLOR_RGB2HSV))\n col_text[2] = get_sample(col_text[2]) # value\n return np.squeeze(cv2.cvtColor(col_text[None,None,:], cv2.COLOR_HSV2RGB))\n\n def color_text(self, text_arr, bg_arr):\n \n fg_col,bg_col = self.font_color.sample_from_data(bg_arr)\n return Layer(alpha = text_arr, color = fg_col), fg_col, bg_col\n\n def color(self, text_arr, bg_arr, fg_col, bg_col, colorsRGB, colorsLAB, min_h, param):\n\n self.font_color = FontColor(colorsRGB, colorsLAB) \n\n l_text = Layer(alpha = text_arr, color = fg_col)\n bg_col = np.mean(np.mean(bg_arr, axis = 0), axis = 0)\n l_bg = Layer(alpha = 255 * np.ones_like(text_arr, dtype = np.uint8), color = bg_col)\n \n layers = [l_text]\n blends = []\n\n # add border:\n if param['is_border']:\n if min_h <= 15 : bsz = 1\n elif 15 < min_h < 30: bsz = 3\n else: bsz = 5\n \n border_a = self.border(l_text.alpha, size = bsz)\n l_border = Layer(border_a, color = param['bordar_color'])\n layers.append(l_border)\n blends.append('normal')\n\n # add shadow:\n if param['is_shadow']:\n # shadow gaussian size:\n if min_h <= 15 : bsz = 1\n elif 15 < min_h < 30: bsz = 3\n else: bsz = 5\n\n # shadow angle:\n theta = param['shadow_angle']\n\n # shadow shift:\n if min_h <= 15 : shift = param['shadow_shift'][0]\n elif 15 < min_h < 30: shift = param['shadow_shift'][1]\n else: shift = param['shadow_shift'][2]\n\n # opacity:\n op = param['shadow_opacity']\n\n shadow = self.drop_shadow(l_text.alpha, theta, shift, 3 * bsz, op)\n l_shadow = Layer(shadow, 0)\n layers.append(l_shadow)\n blends.append('normal')\n\n gray_layers = layers.copy()\n gray_blends = blends.copy()\n l_bg_gray = Layer(alpha=255*np.ones_like(text_arr, dtype = np.uint8), color = (127, 127, 127))\n gray_layers.append(l_bg_gray)\n gray_blends.append('normal')\n l_normal_gray = self.merge_down(gray_layers, gray_blends)\n\n l_bg = Layer(alpha = 255 * np.ones_like(text_arr, dtype = np.uint8), color = bg_col)\n layers.append(l_bg)\n blends.append('normal')\n l_normal = self.merge_down(layers, blends)\n\n # now do poisson image editing:\n l_bg = Layer(alpha = 255 * np.ones_like(text_arr, dtype = np.uint8), color = bg_arr)\n\n # image blit\n l_out = poisson_reconstruct.poisson_blit_images(l_normal.color.copy(), l_bg.color.copy())\n\n return l_normal_gray.color, l_out\n\ndef get_color_matrix(col_file):\n\n with open(col_file,'rb') as f:\n colorsRGB = cp.load(f, encoding ='latin1')\n ncol = colorsRGB.shape[0]\n colorsLAB = np.r_[colorsRGB[:,0:3], colorsRGB[:,6:9]].astype(np.uint8)\n colorsLAB = np.squeeze(cv2.cvtColor(colorsLAB[None,:,:], cv2.COLOR_RGB2Lab))\n return colorsRGB, colorsLAB\n\ndef get_font_color(colorsRGB, colorsLAB, bg_arr):\n\n font_color = FontColor(colorsRGB, colorsLAB) \n return font_color.sample_from_data(bg_arr)\n\ndef colorize(surf, bg, fg_col, bg_col, colorsRGB, colorsLAB, min_h, param):\n\n c = Colorize()\n return c.color(surf, bg, fg_col, bg_col, colorsRGB, colorsLAB, min_h, param)\n","repo_name":"Niwhskal/SRNet","sub_path":"SRNet-Datagen/Synthtext/colorize.py","file_name":"colorize.py","file_ext":"py","file_size_in_byte":11583,"program_lang":"python","lang":"en","doc_type":"code","stars":137,"dataset":"github-code","pt":"40"} +{"seq_id":"30856619788","text":"import re\n\nfor _ in range(int(input())):\n if bool(re.match(r'^(?=(?:[a-z\\d]*[A-Z]){2})(?=(?:.*\\d){3})(?:([a-zA-Z\\d])(?!.*\\1)){10}$', input())) is True:\n print(\"Valid\")\n else:\n print(\"Invalid\")\n\n\n\"\"\"\n^: Start\n(?=(?:[a-z\\d]*[A-Z]){2}): Lookahead to assert that we have at least 2 uppercase alphabets\n(?=(?:\\D*\\d){3}): Lookahead to assert that we have at least 3 digits\n(?:([a-zA-Z\\d])(?!.*\\1)){10}: Match exact 10 alphanumeric characters. Negative lookahead is to assert that we don't have anything repeating anywhere.\n$: End\n\nInput:\n2\nB1CD102354\nB1CDEF2354\n\nOutput:\nInvalid\nValid\n\nhttps://www.hackerrank.com/challenges/validating-uid/problem\n\nA valid UID must follow the rules below:\n\nIt must contain at least uppercase English alphabet characters.\nIt must contain at least digits (0 -9 ).\nIt should only contain alphanumeric characters (a -z , A -Z & 0 -9 ).\nNo character should repeat.\nThere must be exactly characters in a valid UID.\n\"\"\"","repo_name":"dstada/HackerRank.com","sub_path":"Validating UID - Regex and Parsing - Python.py","file_name":"Validating UID - Regex and Parsing - Python.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"13986809185","text":"import sys\n\nsys.stdin = open('sample_input.txt')\n\nT = int(input())\n\n# N일 때 값을 구하는 함수\ndef cases(N):\n if N > 2 and len(case) <= N:\n case.append(2*cases(N-2) + cases(N-1))\n return case[N]\n\n\nfor test_case in range(1, T+1):\n N = int(input())\n N = N//10\n case = [0, 1, 3] # N = 0, 1, 2 일때의 값\n answer = cases(N)\n\n print(f'#{test_case} {answer}')","repo_name":"WChan1027/Problem","sub_path":"SW Expert Academy/4869. 종이붙이기/4869. 종이붙이기.py","file_name":"4869. 종이붙이기.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"32882074121","text":"#!/usr/bin/python3.6\n\nfrom web3 import Web3\n\nlogFile = open(\"log-2019-08-10.txt\", \"r\")\nlogFileReader = logFile.readlines()\n\nbootNodeIP = '192.168.201.12'\ndef getTXStatus(ip, txHash):\n connectionString = \"http://\"+ip+\":20000\"\n tempw3 = Web3(Web3.HTTPProvider(connectionString))\n return tempw3.eth.getTransactionReceipt(txHash)\n\ndef getTXHash(line):\n dataArray = line.split(\",\")\n return dataArray[len(dataArray)-1].replace(\"\\n\",\"\")\n\nfor txLine in logFileReader:\n if (not(txLine.startswith(\"Generating\")) and not(\"##############\" in txLine)):\n txHash = getTXHash(txLine)\n txStatus = getTXStatus(bootNodeIP, txHash)\n if not(txStatus):\n print(\"Transaction\", txHash, \"was not approved!\")\n else:\n print(\"OK:\", txStatus['transactionHash'].hex(), txStatus['blockNumber'])\n\nlogFile.close()\n","repo_name":"KartelAG/mchain-test","sub_path":"txCheck.py","file_name":"txCheck.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"14843289117","text":"\"\"\"\nThis is a modified version of the MIT licensed echo kernel\nin the Jupyter docs.\nhttp://jupyter-client.readthedocs.org/en/latest/wrapperkernels.html#example\n\nMIT License (c) Murat Knecht 2016\n\n\"\"\"\nimport codecs\nimport subprocess\n\nfrom ipykernel.kernelbase import Kernel\n\n\nclass BehaveKernel(Kernel):\n implementation = 'Behave'\n implementation_version = '1.0'\n language = 'no-op'\n language_version = '0.1'\n language_info = {'mimetype': 'text/plain', 'name': 'behave'}\n banner = \"Behave yourself!\"\n\n def __init__(self, *args, **kw):\n super(BehaveKernel, self).__init__(*args, **kw)\n self.history = []\n\n def do_execute(self, code, silent, store_history=True, user_expressions=None,\n allow_stdin=False):\n if store_history:\n self.history.append(code)\n\n if not silent:\n reply = self._maybe_run_and_get_reply(code)\n stream_content = {'name': 'stdout', 'text': reply}\n self.send_response(self.iopub_socket, 'stream', stream_content)\n\n return {\n 'status': 'ok',\n # The base class increments the execution count\n 'name': 'Behave',\n 'execution_count': self.execution_count,\n 'payload': [],\n 'user_expressions': {},\n }\n\n def do_complete(self, text, cursor_pos):\n matches = []\n if text.strip().startswith(\"Given\"):\n matches += [\n \" we have 1 black hole\",\n \" we have 2 black holes\",\n \" black holes are out of stock\",\n ]\n elif text.strip().startswith(\"When\"):\n matches += [\"the holes collide\"]\n\n return {\n # The list of all matches to the completion request, such as\n # ['a.isalnum', 'a.isalpha'] for the above example.\n 'matches': matches,\n\n 'matched_text': text,\n\n # # Information that frontend plugins might use for extra display information about completions.\n # 'metadata' : dict,\n\n # status should be 'ok' unless an exception was raised during the request,\n # in which case it should be 'error', along with the usual error message content\n # in other messages.\n 'status': 'ok'\n }\n\n def _maybe_run_and_get_reply(self, code):\n if \"That's it.\" not in code:\n return \"\"\n\n filepath = \"features/notebook.feature\"\n with codecs.open(filepath, \"w+\", encoding=\"utf-8\") as f:\n f.write(u\"\\n\".join(self.history[:-1]))\n\n stdout, _ = subprocess.Popen(\"/home/murat/.local/bin/behave {}\".format(filepath), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()\n return stdout\n\n\nif __name__ == '__main__':\n from ipykernel.kernelapp import IPKernelApp\n IPKernelApp.launch_instance(kernel_class=BehaveKernel)\n","repo_name":"msabramo/ibehave","sub_path":"behave_kernel.py","file_name":"behave_kernel.py","file_ext":"py","file_size_in_byte":2889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"34011330653","text":"# Desc: Lec 2, Problem 11.\n# Author: Javier Herrero Arnanz.\n\nvarA='Hola'\nvarB=10\n\nif (type(varA) == str) or (type(varB) == str):\n print('String involved')\nelse:\n if (varA == varB):\n print('Equal')\n elif (varA > varB):\n print('Bigger')\n else:\n print('Smaller')\n","repo_name":"javiherrero/6.00.1x-MITx-edX","sub_path":"lecture2/lec2_problem11.py","file_name":"lec2_problem11.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"40"} +{"seq_id":"8431980773","text":"from model.wordle_list_bot import WordleLetterBot2, WordleLetterBot, WordleRandomBot, WordleVowelBot\nfrom model.wordle_wrapper_bot import WordleStarterBot, WordleRandomStarterBot\nfrom view.wordle_view import WordleCommandLine\nfrom view.wordle_gui import WordleHelpGUI, WordleHelpGUI2\nfrom view.wordle_player import WordlePlayer\nfrom controller.guess_help_controller import GuessHelpController\n\n\ndef main():\n best_helper()\n # first_helper()\n # auto_player()\n\n\ndef best_helper():\n bot = WordleLetterBot2()\n view = WordleHelpGUI2()\n controller = GuessHelpController(bot, view)\n controller.play()\n\n\ndef first_helper():\n bot = WordleLetterBot()\n view = WordleCommandLine()\n controller = GuessHelpController(bot, view)\n controller.play()\n\n\ndef auto_player():\n bot = WordleLetterBot2()\n view = WordlePlayer(\"array\")\n controller = GuessHelpController(bot, view)\n controller.play()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"lpfahler16/wordle_bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"35317925610","text":"#!/usr/bin/python\n#\n# Jan 22 2016\n\nfrom game_menu import *\n\nWIDTH = 1024\nHEIGHT = 768\n\nHALF_WIDTH = WIDTH/2\nHALF_HEIGHT = HEIGHT/2\n\nif __name__ == \"__main__\":\n menu = MainMenu(WIDTH, HEIGHT)\n menu.run()\n","repo_name":"Huve/dotquest","sub_path":"run_game.py","file_name":"run_game.py","file_ext":"py","file_size_in_byte":209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"25231988350","text":"from app import app\nfrom kenzie.image import list_all_file_with_specific_format, list_all_files\nfrom kenzie import formats\nimport os\n\ntest_client = app.test_client()\n\nmain_diretory = \"kenzie/storage/\"\n\n \n# tests for /files/<type> _______________________________________________________\n\ndef test_if_filestype_show_error_if_a_file_type_that_is_not_in_database():\n\n assert test_client.get('/files/bin').status_code == 404\n\n\ndef test_if_show_a_filetype_if_it_exists_otherwise_show_error():\n\n filetype = \"png\"\n\n files_of_this_type = list_all_file_with_specific_format(filetype)\n\n if len(files_of_this_type) > 0:\n assert test_client.get(f'/files/{filetype}').status_code == 200\n assert test_client.get(f'/files/{filetype}').get_json() == files_of_this_type\n else:\n assert test_client.get(f'/files/{filetype}').status_code == 404\n\n\n# tests for /download-zip _______________________________________________________\n\ndef test_error_for_download_zip_if_there_are_no_files_or_not():\n\n files = list_all_files()\n\n if len(files) < 1:\n assert test_client.get('/download-zip').status_code == 404\n else:\n assert test_client.get('/download-zip').status_code == 200\n\n\ndef test_error_for_download_zip_if_it_works_with_parameters():\n\n\n files = list_all_files()\n\n if len(files) < 1:\n assert test_client.get('/download-zip?compression_rate=1&file_type=jpg').status_code == 404\n else:\n assert test_client.get('/download-zip?compression_rate=1&file_type=jpg').status_code == 200\n \ndef test_check_if_file_downloaded_is_zip():\n\n files = list_all_files()\n\n if len(files) > 0:\n assert test_client.get('/download-zip?compression_rate=1&file_type=jpg').headers.get(\"Content-Type\") == \"application/zip\"\n else:\n assert test_client.get('/download-zip?compression_rate=1&file_type=jpg').status_code == 404\n\n\n# tests for /download/<file_name> _______________________________________________________\n\ndef test_error_for_download_the_file_exists_in_database():\n\n files = list_all_files()\n\n if \"kenzie.png\" not in files:\n assert test_client.get('/download/kenzie.png').status_code == 404\n else:\n assert test_client.get('/download/kenzie.png').status_code == 200\n\n\ndef test_if_the_file_format_downloaded_has_the_same_extention_as_asked():\n\n \n files = list_all_files()\n\n if \"kenzie.jpg\" not in files:\n assert test_client.get('/download/kenzie.jpg').status_code == 404\n else:\n assert test_client.get('/download/kenzie.jpg').headers.get(\"Content-Type\") == \"image/jpeg\"\n\n\ndef test_if_download_allows_get_method():\n assert 'GET' in (test_client.options('/download/kenzie.png').headers['Allow'])\n\n\n\n# tests for /upload _______________________________________________________\n\n\ndef test_error_in_upload_because_of_extension_type():\n from werkzeug.datastructures import FileStorage\n\n folders = os.listdir('tests')\n testfolder = os.listdir('tests/testsfiles')\n file_test = \"kenzie.txt\"\n\n if \"testsfiles\" not in folders:\n \n os.system(\"mkdir tests/testsfiles\")\n os.system(f\"touch tests/testsfiles/{file_test}\")\n\n elif \"testsfiles\" in folders and file_test not in testfolder:\n os.system(f\"touch tests/testsfiles/{file_test}\")\n\n\n file_path = './tests/testsfiles/kenzie.txt'\n with open(file_path, 'rb') as file:\n my_file = FileStorage(stream=file, filename='kenzie.txt', content_type='text/plain', content_length=\"50\")\n\n response = test_client.post('/upload', data={\"file\": my_file}, content_type=\"multipart/form-data\", content_length=\"50\")\n\n assert response.status_code == 415\n\n\ndef test_error_in_upload_because_already_exists():\n from werkzeug.datastructures import FileStorage\n\n folders = os.listdir('tests')\n testfolder = os.listdir('tests/testsfiles')\n file_test = \"kenzie.png\"\n\n if \"testsfiles\" not in folders:\n \n os.system(\"mkdir tests/testsfiles\")\n os.system(f\"touch tests/testsfiles/{file_test}\")\n\n elif \"testsfiles\" in folders and file_test not in testfolder:\n os.system(f\"touch tests/testsfiles/{file_test}\")\n\n\n file_path = './tests/testsfiles/kenzie.png'\n with open(file_path, 'rb') as file:\n my_file = FileStorage(stream=file, filename='kenzie.png', content_type='image/png', content_length=\"5000\")\n\n response = test_client.post('/upload', data={\"file\": my_file}, content_type=\"multipart/form-data\", content_length=\"5000\")\n\n files = list_all_files()\n\n if file_test in files:\n\n assert response.status_code == 409\n\n# tests for /files _______________________________________________________\n\n\ndef test_if_files_allows_get_method():\n assert 'GET' in (test_client.options('/files').headers['Allow'])\n \n\ndef test_files_status_codes_if_the_folders_have_files_or_not():\n \n files = list_all_files()\n\n if len(files) < 1:\n assert test_client.get('/files').status_code == 404\n else:\n assert test_client.get('/files').status_code == 200\n assert test_client.get('/files').get_json() == files\n","repo_name":"brunovcg/banco-de-imagens","sub_path":"tests/test_files_from_request.py","file_name":"test_files_from_request.py","file_ext":"py","file_size_in_byte":5121,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"69967070200","text":"import sys\nimport os\nimport subprocess\n\n# Declarations\nexecutable_name = \"race.out\"\niterations = 1000\n\nif len(sys.argv) <= 1:\n print(\"No arguments passed. Please give a compilation file.\")\n sys.exit(1)\n\nfile_name = sys.argv[1]\n\n# Compiling the given piece of code\nsubprocess.call([\"gcc\", \"-pthread\", os.getcwd() + \"/\" + file_name, \"-o\", executable_name])\n\nhow_much_off = 0\nhow_many_correct = 0\n\nfor x in range(iterations):\n # https://stackoverflow.com/questions/748028/how-to-get-output-of-exe-in-python-script\n output = str(subprocess.Popen([\"./\" + executable_name], stdout=subprocess.PIPE).communicate()[0])\n \n # Grabbing the number from the output of our race program.\n sum = int(output.split(\" ?= \")[0].split(\" \")[-1])\n\n if sum == 200:\n how_many_correct += 1\n else:\n how_much_off += abs(200 - sum)\n\nprint(\"Ran for %d iterations.\\n%d correct. %f average amount off per iteration.\"\n % (iterations, how_many_correct, how_much_off / iterations))\n\nsubprocess.call([\"rm\", executable_name])\n","repo_name":"Chudbrochil/school","sub_path":"UNM/CS481/pa03/run_race.py","file_name":"run_race.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"32827337998","text":"def traingle(data,n):\n\t#hi\n\tk = 2*n - 2\n\tfor i in range(0, n):\n\t\tfor j in range(0, k):\n\t\t\tprint(end=\" \")\n\t\tk = k - 2\n\t\tfor j in range(0, i+1):\n\t\t\t\tprint(\"%s \"%(data[j]), end=\"\")\n\t\tprint(\"\\r\")\n\ndef manipulate(data):\n\ttemp=[]\n\tif len(data)%2==1:\n\t\ttemp.append(data[len(data)//2:])\n\t\ttemp.append(data[:len(data)//2])\n\t\tres=\"\".join(temp)\n\telse:\n\t\tres=data\n\treturn res\n\ndata=input()\nn=len(data)\ntraingle(manipulate(data),n)\n#\n#\n#\n#\n#\n#\n","repo_name":"aravinth12312/mz","sub_path":"code1.py","file_name":"code1.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"8430261864","text":"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output, State\nfrom datetime import datetime as dt\nfrom datetime import date\nimport dash_bootstrap_components as dbc\nimport yfinance as yf\nimport pandas as pd\nimport plotly.graph_objs as go\nimport plotly.express as px\n\n\ncurrentDay = dt.now().day\ncurrentMonth = dt.now().month\ncurrentYear = dt.now().year\n\napp = dash.Dash(__name__, external_stylesheets=[dbc.themes.SANDSTONE])\nserver = app.server\n\n# REF Plot Figure\n# fig = px.bar(df, x=\"Fruit\", y=\"Amount\", color=\"City\", barmode=\"group\")\n#\n# fig.update_layout(\n# plot_bgcolor=colors['background'],\n# paper_bgcolor=colors['background'],\n# font_color=colors['text']\n# )\n# dcc.Graph(\n# id='example-graph-2',\n# figure=fig\n# )\n\n\napp.layout = html.Div(style={}, className='parent',children=[\n html.H1(style={'display': 'block', 'textAlign': 'center'},\n children=\"Stock Visualizing and Forecasting App!\", className=\"header\"),\n html.Div(className='container', children=[\n html.Div(children=[\n html.Div(style={'content': '\\A'}, children=[\n html.P(style={'margin-left': '8%', 'margin-right':'8%'} ,children=\"Enter the stock code: \"),\n html.Div(children=[\n dcc.Input(\n placeholder='e.g AAPL (for apple)',\n type='text',\n value='',\n id='stockName'\n ),\n dbc.Button(\"Submit\", color=\"primary\", className=\"mr-1\", id='stockNameSubmit', n_clicks=0)\n ], className='start_nav')\n ], className='start_external'),\n html.Div(style={'display': 'block'}, children=[\n # Date range picker input\n dcc.DatePickerRange(\n id='date_input',\n min_date_allowed=date(currentYear, currentMonth, currentDay),\n max_date_allowed=date(2022, 9, 19),\n initial_visible_month=date(currentYear, currentMonth, currentDay),\n end_date=date(currentYear, currentMonth, currentDay)\n )\n # html.Div(id='output-container-date-picker-range')\n # html.Br\n ], className='dateinput'),\n html.Div(children=[\n # Stock price button\n html.Div(children=[\n dbc.Button(\"Stock Price\", color=\"primary\", className=\"mr-1\", id='stockprice'),\n # Indicators button\n dbc.Button(\"Indicator\", color=\"success\", className=\"mr-1\", id='indicator')\n # html.Br()\n ], className='midnav'),\n # Numner of days forecast input value\n html.Div(children=[\n dcc.Input(\n placeholder='No. of Days',\n type='number',\n value='',\n id='nodays'\n ),\n # FOrecast BUtton\n dbc.Button(\"Forecast\", color=\"dark\", className=\"mr-1\")\n ], className='bottom_nav')])\n ],\n className=\"nav\"),\n html.Div(children=[\n # html.H1(\"This is for testing sdngsednvd afnenv esnjesg esgnes segsebs\"),\n html.Div(\n [ # Logo\n html.H2(id='company_name', children=[]),\n html.Img(id='company_logo', children='')\n # Company Name\n ],\n className=\"out-header\", id='out-header'),\n html.Div( # Description\n id=\"description\", className=\"decription_ticker\"),\n html.Div([\n # Stock price plot\n ], id=\"graphs-content\"),\n html.Div([\n # Indicator plot\n ], id=\"main-content\"),\n html.Div([\n # Forecast plot\n ], id=\"forecast-content\")\n ],\n className=\"content\")\n ]\n ),\n html.P(children=[\n \"Created by \",\n html.A('Tirth Patel', href='https://www.linkedin.com/in/tirth-patel-412b70192')\n ], className=\"footer\")\n])\n\n\n@app.callback([\n Output('company_name', 'children'),\n Output('description', 'children'),\n Output('company_logo', 'children')\n ],[\n Input('stockNameSubmit', 'n_clicks'),\n State('stockName', 'value')\n ]\n)\ndef company_info(n_clicks, name):\n ticker = yf.Ticker(name)\n inf = ticker.info\n df = pd.DataFrame().from_dict(inf, orient=\"index\").T\n # print(n_clicks)\n company_name = df['shortName'][0]\n description = df['longBusinessSummary'][0]\n logo = df['logo_url'][0]\n print(logo)\n # return # df's first element of 'longBusinessSummary', df's first element value of 'logo_url', df's first element value of 'shortName'\n return company_name, description, logo\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n","repo_name":"tirthPatel177/visualizaing_and_predicting_stocks","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"36953093068","text":"import os\r\nimport jinja2\r\nfrom datetime import datetime\r\nfrom python.util.utilities import Util\r\nfrom python.util.get_file_path import get_relative_file_path\r\nfrom python.util.fdw_snowflake import FdwSnowflake\r\nfrom python.data_processing.procedures.processing_config import table_names\r\n\r\nLOG = Util.get_logger(__name__)\r\nexecution_date = datetime.now().strftime(\"%Y-%m-%d\")\r\nexecution_timestamp = datetime.now()\r\ndb_name = str(os.getenv(\"TARGET_DB\"))\r\n\r\nCREATE_TABLE_SQL = \"CREATE TABLE IF NOT EXISTS {} AS {}\"\r\nTRUNCATE_TABLE_SQL = \"TRUNCATE TABLE {} \"\r\nINSERT_TABLE_FROM_QUERY_SQL = \"INSERT INTO {} ({})\"\r\n\r\nDWH = FdwSnowflake(\r\n user=os.environ[\"SNOWFLAKE_USER\"],\r\n password=os.environ[\"SNOWFLAKE_PASSWORD\"],\r\n warehouse=\"vw_dev_ingest\",\r\n account=\"udemy\",\r\n role=\"jobs_etl\",\r\n database=db_name,\r\n schema=\"schema_test\",\r\n)\r\n\r\n\r\ndef _read_file(file_path):\r\n '''\r\n read file contents from path input\r\n :param file_path: str\r\n :return: str\r\n '''\r\n file_path = get_relative_file_path(file_path=file_path, caller_file_path=__file__)\r\n with open(file_path) as f:\r\n output = f.read()\r\n return output\r\n\r\n\r\ndef _execute_table_inserts(keyword, table, raw_db, raw_schema, curate_db, curate_schema):\r\n '''\r\n insert into a target - curated from source - raw based on output of specifically named sql file\r\n :param keyword: str\r\n :param table: str\r\n :param raw_db: str\r\n :param raw_schema: str\r\n :param curate_db: str\r\n :param curate_schema: str\r\n :return: na\r\n '''\r\n select_query_path = \"queries/\" + keyword + '_insert.sql'\r\n select_query_to_run = jinja2.Template(_read_file(select_query_path)).render(db_raw=raw_db, schema_raw=raw_schema,\r\n db_curated=curate_db,\r\n schema_curated=curate_schema)\r\n table_nm = curate_db + \".\" + curate_schema + \".\" + table\r\n insert_query_to_run = INSERT_TABLE_FROM_QUERY_SQL.format(table_nm, select_query_to_run)\r\n LOG.info(\"executing insert query ... \\n\" + insert_query_to_run)\r\n DWH.execute(insert_query_to_run)\r\n LOG.info(\"inserts done... \" + table_nm)\r\n\r\n\r\ndef _audit_raw_data_table(keyword, raw_db, raw_schema, monitor_db, monitor_schema):\r\n '''\r\n insert into raw-data-load-tracker from based on raw data inserts\r\n :param keyword: str\r\n :param raw_db: str\r\n :param raw_schema: str\r\n :param monitor_db: str\r\n :param monitor_schema: str\r\n :return: na\r\n '''\r\n a_rawdata_query_path = \"queries/\" + keyword + '_auditraw.sql'\r\n a_rawdata_query_to_run = jinja2.Template(_read_file(a_rawdata_query_path)).render(db_raw=raw_db,\r\n schema_raw=raw_schema)\r\n s3_transfer_log_table = monitor_db + \".\" + monitor_schema + \".\" + \"S3_FILE_LOAD_AUDIT\"\r\n audit_insert_raw_query_to_run = INSERT_TABLE_FROM_QUERY_SQL.format(s3_transfer_log_table, a_rawdata_query_to_run)\r\n LOG.info(\"audit raw data query ... \\n\" + audit_insert_raw_query_to_run)\r\n DWH.execute(audit_insert_raw_query_to_run)\r\n LOG.info(\"raw-data entries logged... \" + s3_transfer_log_table)\r\n\r\n\r\ndef _audit_curated_table(keyword, raw_db, raw_schema, monitor_db, monitor_schema):\r\n '''\r\n insert into curated-data-load-tracker from based on data inserts\r\n :param keyword: str\r\n :param raw_db: str\r\n :param raw_schema: str\r\n :param monitor_db: str\r\n :param monitor_schema: str\r\n :return: na\r\n '''\r\n a_curated_query_path = \"queries/\" + keyword + '_auditcur.sql'\r\n a_curated_query_to_run = jinja2.Template(_read_file(a_curated_query_path)).render(db_raw=raw_db,\r\n schema_raw=raw_schema)\r\n raw_to_curated_log_table = monitor_db + \".\" + monitor_schema + \".\" + \"RAW_TO_CURATED_LOG_AUDIT\"\r\n audit_curation_log_query_to_run = INSERT_TABLE_FROM_QUERY_SQL.format(raw_to_curated_log_table,\r\n a_curated_query_to_run)\r\n LOG.info(\"curation audit query ... \\n\" + audit_curation_log_query_to_run)\r\n DWH.execute(audit_curation_log_query_to_run)\r\n LOG.info(\"curated data logged... \" + raw_to_curated_log_table)\r\n\r\n\r\ndef _truncate_table(table, db, schema):\r\n table_nm = db + \".\" + schema + \".\" + table\r\n # truncate_query = TRUNCATE_TABLE_SQL.format(table_nm)\r\n # DWH.execute(truncate_query) TO:DO -- intentionally commented, when Production remove comment\r\n LOG.info(\"truncated table... \" + table_nm)\r\n\r\n\r\ndef main():\r\n for dataset in table_names:\r\n\r\n # values from config\r\n data = dataset['dataset']\r\n tbl_nm = dataset['table'].upper()\r\n raw_db = dataset['raw_database'].upper()\r\n raw_schema = dataset['raw_schema'].upper()\r\n curate_db = dataset['curated_database'].upper()\r\n curate_schema = dataset['curated_schema'].upper()\r\n monitor_db = dataset['monitor_database'].upper()\r\n monitor_schema = dataset['monitor_schema'].upper()\r\n\r\n # incremental rows insert from raw\r\n LOG.info(\"procedure run for... \" + data + \" | env : \" + str(db_name) + \" | \" + str(execution_timestamp))\r\n _execute_table_inserts(keyword=data, table=tbl_nm, raw_db=raw_db, raw_schema=raw_schema, curate_db=curate_db,\r\n curate_schema=curate_schema)\r\n LOG.info(\"inserts complete... \" + data)\r\n\r\n # log audit entries raw + curated\r\n _audit_raw_data_table(keyword=data, raw_db=raw_db, raw_schema=raw_schema, monitor_db=monitor_db,\r\n monitor_schema=monitor_schema)\r\n LOG.info(\"raw - audit entries done... \" + data)\r\n _audit_curated_table(keyword=data, raw_db=raw_db, raw_schema=raw_schema, monitor_db=monitor_db,\r\n monitor_schema=monitor_schema)\r\n LOG.info(\"curation - audit entries done... \" + data)\r\n\r\n # truncate raw table\r\n _truncate_table(table=tbl_nm, db=raw_db, schema=raw_schema)\r\n LOG.info(\"Done... \" + data + \" | \" + str(execution_timestamp))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n LOG.info(\"All Done ;-) \")","repo_name":"anjalisalgar/MyRepo","sub_path":"test_snowflake_procedure_AS.py","file_name":"test_snowflake_procedure_AS.py","file_ext":"py","file_size_in_byte":6292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"33453806717","text":"def factorial(n) -> int:\n ''' The product of all positive integers less than or equal to n. '''\n if n < 2: return 1\n else: return n * factorial(n-1)\n\ndef digit_factorial_sum(factorials, n) -> int:\n ''' The sum of the factorial of each digit in n. '''\n s = 0\n while n:\n s += factorials[n % 10]\n n //= 10\n return s\n\ndef digit_factorials(limit) -> int:\n ''' The sum of all numbers which are equal to the\n sum of the factorial of their digits. '''\n total = 0\n factorials = [factorial(i) for i in range(10)] # pre-calculate 0-9\n num = 3\n while num < limit:\n if digit_factorial_sum(factorials, num) == num:\n total += num\n num += 1\n return total\n\nif __name__ == \"__main__\":\n\tprint(digit_factorials(2540160))","repo_name":"jwmcgettigan/project-euler-solutions","sub_path":"solutions/034/034.py","file_name":"034.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"28419837406","text":"# Integers: Recreation one, level 5kyu.\r\n# link: https://www.codewars.com/kata/55aa075506463dac6600010d\r\n'''\r\nDivisors of 42 are : 1, 2, 3, 6, 7, 14, 21, 42. These divisors squared are: 1, 4, 9, 36, 49, 196, 441, 1764. The sum of the squared divisors is 2500 which is 50 * 50, a square!\r\n\r\nGiven two integers m, n (1 <= m <= n) we want to find all integers between m and n whose sum of squared divisors is itself a square. 42 is such a number.\r\n\r\nThe result will be an array of arrays or of tuples (in C an array of Pair) or a string, each subarray having two elements, first the number whose squared divisors is a square and then the sum of the squared divisors.\r\n\r\n#Examples:\r\n\r\nlist_squared(1, 250) --> [[1, 1], [42, 2500], [246, 84100]]\r\nlist_squared(42, 250) --> [[42, 2500], [246, 84100]]\r\n'''\r\nimport numpy as np\r\ndef list_squared(m, n):\r\n square_list = []\r\n \r\n for x in np.arange(m,n+1):\r\n int_list = np.arange(1,x+1)\r\n \r\n div_list = int_list[x%int_list==0] # get an array of divisors\r\n \r\n sq = sum((div_list)**2) # get the sum\r\n root = np.sqrt(sq)\r\n \r\n if int(root + 0.5) ** 2 == sq: # check if the number a perfect square\r\n square_list.append([x,sq])\r\n \r\n return square_list","repo_name":"Said-Akbar/exercises","sub_path":"integers.py","file_name":"integers.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"1087145592","text":"\"\"\"\nheli.py - Arian Mollik Wasi\nMIT License\n\nA simple script to print a helicopter animation to the terminal.\nThe heli_animation.txt file should be in the same folder as this file or else the code won't work\n\nUsage\n=====\nTo run normally use\n python heli.py\nTo specify a custom frame duration use\n python heli.py n\nWhere n is the duration such as 0.5:\n python heli.py 0.5\n\"\"\"\nfrom os import name, system\nfrom sys import argv\nfrom itertools import cycle\nfrom time import sleep\n\n# `cls` is a Windows command and `clear` is a Unix command to clear the terminal\nCLEAR_COMMAND = \"cls\" if name == \"nt\" else \"clear\"\n# Check if there is a custom delay passed and if not, use 0.1\nDELAY = float(argv[1]) if argv[1:] else 0.1\nFRAME_SEPARATOR = \"====================================\"\n\n\ndef clear():\n \"\"\"Clear the terminal\"\"\"\n system(CLEAR_COMMAND)\n\n\nwith open(\"heli_animation.txt\", encoding=\"utf-8\") as f:\n # `itertools.cycle` creates a infinite iterable so the animation never stops\n # `i.strip(\"\\n\")` is there to remove trailing newlines\n # `filter(None, sequence)` removes all falsey elements such as empty strings\n # `f.read().split(...)` gets all the parts of the helicopter animation as a list\n helicopter_phases = cycle(\n [i.strip(\"\\n\") for i in filter(None, f.read().split(FRAME_SEPARATOR))]\n )\n\n\ndef print_heli():\n try:\n for heli_frame in helicopter_phases:\n print(heli_frame)\n # print a newline\n print()\n # Add a `time.sleep` to delay the frames or else it will be too fast\n sleep(DELAY)\n # Clear the terminal after the run\n clear()\n except KeyboardInterrupt:\n print(\"Stopped!\")\n\n\nif __name__ == \"__main__\":\n print_heli()\n # One last clear just to be sure\n clear()\n","repo_name":"wasi-master/helicopter-helicopter","sub_path":"heli.py","file_name":"heli.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"40"} +{"seq_id":"4488368232","text":"import unittest\nfrom PIL import ImageStat\nfrom kia_mbt.kia_io.fs_backend import KIADatasetFSBackend\n\n\nclass TestMinioBackend(unittest.TestCase):\n \"\"\"\n This class implements a unit test for the backends for the KIA dataset\n loader.\n \"\"\"\n\n def setUp(self) -> None:\n \"\"\"\n Setup\n \"\"\"\n\n # create file system backed\n self.fs_backend = KIADatasetFSBackend(\"/mnt/share/kia/data\")\n\n # some test tokens\n self.test_token_true = \"bit_results_sequence_0211-fb32183497c34de4b9696aa3c3a48640/sensor/camera/left/png/arb-camera136-0211-fb32183497c34de4b9696aa3c3a48640-0135.png\"\n self.test_token_false = \"bit_results_sequence_0211-fb32183497c34de4b9696aa3c3a48640/sensor/camera/right/png/arb-camera136-0211-fb32183497c34de4b9696aa3c3a48640-0135.png\"\n self.test_token_json = \"bit_results_sequence_0211-fb32183497c34de4b9696aa3c3a48640/ground-truth/2d-bounding-box-fixed_json/arb-camera136-0211-fb32183497c34de4b9696aa3c3a48640-0135.json\"\n\n def test_get_object_names(self) -> None:\n \"\"\"\n Test method for getting all object names\n\n Parameters\n ----------\n client : KIADatasetMinIOBackend\n MinIO backend object\n \"\"\"\n\n objects_filenames = self.fs_backend.get_object_names()\n self.assertGreater(len(objects_filenames), 0)\n\n def test_exists_object_name(self) -> None:\n \"\"\"\n Test method for the exists object name method\n\n Parameters\n ----------\n client : KIADatasetMinIOBackend\n MinIO backend object\n \"\"\"\n\n exists_true = self.fs_backend.exists_object_name(self.test_token_true)\n exists_false = self.fs_backend.exists_object_name(self.test_token_false)\n self.assertTrue(exists_true)\n self.assertFalse(exists_false)\n\n def test_get_image_object(self) -> None:\n \"\"\"\n Test method for getting an image object\n\n Parameters\n ----------\n client : KIADatasetMinIOBackend\n MinIO backend object\n \"\"\"\n\n img = self.fs_backend.get_image_object(self.test_token_true)\n img_stats = ImageStat.Stat(img)\n self.assertEqual(img.width, 1920)\n self.assertEqual(img.height, 1280)\n self.assertAlmostEqual(img_stats.mean[0], 125.90232788)\n self.assertAlmostEqual(img_stats.mean[1], 133.86449015)\n self.assertAlmostEqual(img_stats.mean[2], 155.43444213)\n\n def test_get_json_object(self) -> None:\n \"\"\"\n Test method for getting a JSOn object\n\n Parameters\n ----------\n client : KIADatasetMinIOBackend\n MinIO backend object\n \"\"\"\n\n detections_2d = self.fs_backend.get_json_object(self.test_token_json)\n self.assertEqual(detections_2d[\"1722\"][\"c_x\"], 1537)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"continental/kiabsicherung-metric-benchmarking-tool","sub_path":"tests/kia_io/test_io_backends.py","file_name":"test_io_backends.py","file_ext":"py","file_size_in_byte":2887,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"40"} +{"seq_id":"36812255430","text":"from sage.categories.fields import Fields\n\nfrom sage.structure.sequence import Sequence\n\nfrom .triangulation import Triangulation\n\n_Fields = Fields()\n\nclass MeasuredTrainTrack(object):\n r\"\"\"\n Train-track endowed with a transverse measure.\n \"\"\"\n def __init__(self, triangulation, lengths, base_ring=None):\n self._triangulation = Triangulation(triangulation)\n\n n = self._triangulation.num_half_edges()\n m = self._triangulation.num_edges()\n ep = self._triangulation.edge_permutation(copy=False)\n if len(lengths) == m:\n for e in range(m):\n E = ep[e]\n if e != E and E < m:\n raise ValueError(\"edge perm not in standard form\")\n lengths = list(lengths) + [lengths[ep[e]] for e in range(m,n)]\n if len(lengths) != n:\n raise ValueError('wrong number of vectors')\n\n\n if base_ring is None:\n lengths = Sequence(lengths)\n base_ring = lengths.universe()\n lengths = list(lengths)\n else:\n lengths = [base_ring.coerce(l) for l in lengths]\n\n self._base_ring = base_ring\n self._lengths = tuple(lengths)\n\n fp = self._triangulation.face_permutation(copy=False)\n\n for e in range(n):\n E = ep[e]\n if self._lengths[e] != self._lengths[E]:\n raise ValueError(\"non-compatible length data\")\n\n # we record below whether the given size is (horizontally) big or not\n self._edge_type = [None] * n\n\n for a in range(n):\n b = fp[a]\n c = fp[b]\n if lengths[a] >= lengths[b] and lengths[a] >= lengths[c]:\n if lengths[a] != lengths[b] + lengths[c]:\n raise ValueError(\"non-compatible length data\")\n self._edge_type[a] = 0\n self._edge_type[b] = 1\n self._edge_type[c] = 2\n\n def lengths(self):\n return self._lengths\n\n def __repr__(self):\n return \"MeasuredTrainTrack({}, {})\".format(\n self._triangulation, self._lengths)\n\n def __call__(self, p, iterations=1):\n r\"\"\"\n p = (i,x) where\n i = half-edge\n x = value\n\n EXAMPLES::\n\n sage: from veerer import * # random output due to deprecation warnings from realalg\n sage: v0 = vector((1, 0, 1, 1))\n sage: v1 = vector((0, 1, 1, 1))\n sage: t = Triangulation(\"(0,1,2)(~0,~1,3)\")\n sage: tt = MeasuredTrainTrack(t, 2*v0 + 3*v1)\n sage: tt((2,3/2))\n (4, 3/2)\n sage: tt((2,3/2),2) == tt((4,3/2))\n True\n sage: tt((2,3/2),5) == tt((4,3/2),4)\n True\n \"\"\"\n it = self.orbit(p)\n for _ in range(2*iterations):\n next(it)\n return next(it)\n\n def orbit(self, p):\n r\"\"\"\n Return an iterator through the (infinite) orbit of p.\n\n (intermediate steps are yielded as well)\n \"\"\"\n n = self._triangulation.num_half_edges()\n ep = self._triangulation.edge_permutation(copy=False)\n fp = self._triangulation.face_permutation(copy=False)\n L = self._lengths\n i, x = p\n\n while True:\n assert 0 <= i < n\n assert 0 < x < self._lengths[i]\n yield (i,x)\n\n # 1. cross the tripode (first involution)\n if self._edge_type[i] == 0:\n # big edge\n b = i\n s1 = fp[b]\n s2 = fp[s1]\n if x < L[s2]:\n i = s2\n x = L[s2] - x\n else:\n i = s1\n x = L[s1] + L[s2] - x\n elif self._edge_type[i] == 1:\n # first small edge\n s1 = i\n s2 = fp[s1]\n b = fp[s2]\n i = b\n x = L[s1] + L[s2] - x\n elif self._edge_type[i] == 2:\n # second small edge\n s2 = i\n b = fp[s2]\n s1 = fp[b]\n i = b\n x = L[s2] - x\n\n yield (i,x)\n\n # 2. pass through the edges (second involution)\n i = ep[i]\n x = L[i] - x\n","repo_name":"flatsurf/veerer","sub_path":"veerer/measured_train_track.py","file_name":"measured_train_track.py","file_ext":"py","file_size_in_byte":4276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"39223520317","text":"class Solution:\n def findWords(self, board: list[list[str]], words: list[str]) -> list[str]:\n def dfs(r,c,root):\n character = board[r][c]\n #get to next node \n cur = root[character]\n '''\n the reason why we use pop method is because\n we don't want to add the same word to result\n once we found it.\n Additionaly, we store value of \"#\" as word\n because, initially, we stored word itself as value of key.\n '''\n word = cur.pop(\"#\",False)\n if word:\n #add to result if current node is end of word\n res.append(word)\n\n #mark current character as visited\n board[r][c] = \"*\"\n\n #for each direction apply dfs\n for dirx, diry in [(0, 1), (0, -1), (1, 0), (-1, 0)]:\n curx, cury = r + dirx, c + diry\n if 0 <= curx < ROWS and 0 <= cury < COLS and board[curx][cury] in cur:\n dfs(curx, cury, cur)\n #restore to its value once we done \n board[r][c] = character\n\n '''\n because we popped \"#\" from cur if it is end of word\n we can check that it was been added and there is no need of it\n with this if condition. Hence, just delete node from root.\n '''\n if not cur:\n root.pop(character)\n \n #create trie\n trie = {}\n for word in words:\n cur = trie\n for letter in word:\n cur = cur.setdefault(letter, {})\n #store word itself for last node in each word\n cur[\"#\"] = word\n\n #resulting list \n res = []\n\n ROWS,COLS = len(board),len(board[0])\n for r in range(ROWS):\n for c in range(COLS):\n if board[r][c] in trie:\n dfs(r,c,trie)\n return res\n","repo_name":"alphaninja27/LeetCode-Solutions","sub_path":"DSA1/Word Search II.py","file_name":"Word Search II.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"23567935585","text":"# Recursive Factorial with function.\ndef factorial(n):\n if n == 0:\n return 1\n else:\n return n * factorial(n-1)\n\n\n#Entry Point.\nif __name__ == '__main__':\n q = int(input(\"Enter a quantity : \"))\n i = 0\n while i < q:\n number = int(input(\"Enter a number : \"))\n print(f\"the factorial of {number} is :\", factorial(number))\n i += 1\n","repo_name":"TheWolvesTech/Factorial_Recursivo","sub_path":"Factorial.py","file_name":"Factorial.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"73290352120","text":"\ndef float_bin(my_number, places = 3): \n my_whole, my_dec = str(my_number).split(\".\") \n my_whole = int(my_whole) \n res = (str(bin(my_whole))+\".\").replace('0b','') \n \n for x in range(places): \n my_dec = str('0.')+str(my_dec) \n temp = '%1.20f' %(float(my_dec)*2) \n my_whole, my_dec = temp.split(\".\") \n res += my_whole \n return res \n \n \n \ndef IEEE754(n) : \n \n sign = 0\n if n < 0 : \n sign = 1\n n = n * (-1) \n p = 30\n \n dec = float_bin (n, places = p) \n \n dotPlace = dec.find('.') \n onePlace = dec.find('1') \n \n if onePlace > dotPlace: \n dec = dec.replace(\".\",\"\") \n onePlace -= 1\n dotPlace -= 1\n elif onePlace < dotPlace: \n dec = dec.replace(\".\",\"\") \n dotPlace -= 1\n mantissa = dec[onePlace+1:] \n \n \n exponent = dotPlace - onePlace \n exponent_bits = exponent + 127\n \n \n exponent_bits = bin(exponent_bits).replace(\"0b\",'') \n \n mantissa = mantissa[0:23] \n \n \n final = str(sign) + exponent_bits.zfill(8) + mantissa \n \n \n hstr = '0x%0*X' %((len(final) + 3) // 4, int(final, 2)) \n return (hstr, final) \n \n#pas hier het getal aan dat je wilt \nif __name__ == \"__main__\" : \n print (IEEE754(263.3)) \n print (IEEE754(-0.75)) \n","repo_name":"Dieter-VanderZwalmen/Scripts","sub_path":"Computer Systems exercise calculators/Floating point notation/DecimaalNaarBinair.py","file_name":"DecimaalNaarBinair.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"27893880539","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Read images\nimg = cv2.imread('spbob1.jpg', 0)\n\n# Fourier transform\nfimg = np.fft.fft2(img)\nfshift = np.fft.fftshift(fimg)\n\n# Set the high pass filter\nrows, cols = img.shape\ncrow, ccol = int(rows/2), int(cols/2)\nfshift[crow-30:crow+30, ccol-30:ccol+30] = 0\n\n# Inverse Fourier transform\nishift = np.fft.ifftshift(fshift)\niimg = np.fft.ifft2(ishift)\niimg = np.abs(iimg)\n\n# Display original image and high pass filter processing image\nplt.subplot(121), plt.imshow(img, 'gray'), plt.title('gray Image')\nplt.axis('off')\nplt.subplot(122), plt.imshow(iimg, 'gray'), plt.title('Result Image')\nplt.axis('off')\nplt.show()","repo_name":"merryskac/tugas-matakuliah-pcd","sub_path":"hpf.py","file_name":"hpf.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"73967338041","text":"'''\nutil.py\n\nLast edited by: GunGyeom James Kim\nLast edited at: Dec 5th, 2023\n\nFile containing utility functions\n\nvariable:\n cam2rgb - Global variable, transformation matrix for cam to RGB\n\nfunction:\n split - evenly split data into three fold, train, evaluation, and test\n read_16bit_png - read 16bit png file using torch\n angularLoss - calculate accumulated angular loss in degrees\n illuminate - Linearize, illuminate, map to RGB and gamma correct\n lin2sRGB - Map linear chromaticity space to sRGB chromaticity space\n to_rgb - Map input to rgb chromaticity space\n\nclass:\n MaxResize - scale input resizing longer size to max\n ContrastNormalization - apply histogram stretching to normalize contrast\n RandomPatches - randomly crop image to number of 32x32 patches\n'''\n# built-in\nimport math \nimport random \n\n# third-party\nimport numpy as np\n\n# torch\nimport torch\nfrom torchvision.io import read_file\nfrom torchvision.transforms import functional as F\n\ncam2rgb = np.array([\n 1.8795, -1.0326, 0.1531,\n -0.2198, 1.7153, -0.4955,\n 0.0069, -0.5150, 1.5081,]).reshape((3, 3))\n\ndef generate_threefold_indices(seed=123):\n LENGTH = 568\n indices = list(range(LENGTH))\n first_third = LENGTH // 3\n second_third = 2 * first_third\n random.Random(seed).shuffle(indices)\n fold1 = indices[:first_third]\n fold2 = indices[first_third:second_third]\n fold_test = indices[second_third:]\n return fold1, fold2, fold_test\n\ndef read_16bit_png(path: str) -> torch.Tensor:\n '''\n source: https://github.com/pytorch/vision/blob/0b41ff0b0a08229a10cfe1ca6987b4386d68bd9c/torchvision/io/image.py#L240\n Return 16 bit image\n\n Parameter:\n path(str or Path) - 16bit image file\n\n Return:\n 16bit image\n '''\n data = read_file(path) # Reads and outputs the bytes contents of a file as a uint8 Tensor with one dimension.\n return torch.ops.image.decode_png(data, 0, True) # 0 means unchanged image\n\ndef angularLoss(xs, ys, singleton=False):\n '''\n Return accumulated angular loss in degrees\n\n Parameter:\n xs(tensor or sequence of tensors) - sequence of tensors to calculate angular loss\n ys(tensor or sequence of tensors) - sequence of tensors to calculate angular loss\n\n Return:\n output(float) - accumulated angular loss in degrees\n '''\n if singleton:\n if torch.count_nonzero(xs[0]).item() == 0: return 180\n return torch.rad2deg(torch.arccos(torch.nn.functional.cosine_similarity(xs,ys, dim=-1))).item()\n \n output = 0\n for x, y in zip(xs, ys):\n if torch.count_nonzero(x).item() == 0: output += 180\n else: output += torch.rad2deg(torch.arccos(torch.nn.functional.cosine_similarity(x,y, dim=0))).item()\n return output\n\ndef illuminate(img, illum, black_lvl):\n '''\n Linearize, illuminate, map to RGB and gamma correct\n\n Parameter:\n img(tensor) - image to process\n idx(int) - index to get illumination\n\n Return:\n output(numpy.ndarray) - \n '''\n linearize = ContrastNormalization(black_lvl = black_lvl)\n linearized_img = linearize(img).permute(1,2,0).cpu().numpy() # h,w,c -> c,h,w\n illum = illum.cpu().numpy()\n illum /= illum.sum()\n white_balanced_image = linearized_img/illum\n rgb_img = np.dot(white_balanced_image, cam2rgb.T)\n rgb_img = np.clip(rgb_img, 0, 1)**(1/2.2)\n return (rgb_img*255).astype(np.uint8)\n\ndef lin2sRGB(linImg):\n '''\n Map linear chromaticity space to sRGB chromaticity space\n\n Parameter:\n linImg(tensor) - image in linear chromaticity space\n\n Return:\n linImg(tensor) - image map to sRGB chromaticity space\n '''\n low_mask = linImg <= 0.0031308\n high_mask = linImg > 0.0031308\n linImg[low_mask] *= 12.92\n linImg[high_mask] = 1.055 * linImg[high_mask]**(1/2.4) - 0.055\n return linImg\n\ndef to_rgb(inputs):\n '''\n Map input to rgb chromaticity space (r,g,b in [0,1] such that r+g+b = 1)\n\n Parameter:\n input(tensor) - num_patches x 3, input in arbitrary chromaticity space\n\n Return:\n input(tensor) - input mapped to rgb chromaticity space\n '''\n num_patches = inputs.shape[0]\n if num_patches == 1: return inputs[0] / torch.sum(inputs[0])\n for idx in range(num_patches):\n inputs[idx] = inputs[idx].clone() / torch.sum(inputs[idx])\n return inputs\n\n#################\n### Transform ### \n#################\nclass MaxResize:\n '''\n Downscale input while longer side is capped at self.max_length\n '''\n def __init__(self, max_length):\n '''\n Constructor\n\n Parameters:\n max_length(int) - maximum length to downscale\n '''\n self.max_length = max_length\n \n def __call__(self, img):\n '''\n Return downscaled image while longer side is capped at self.max_length\n\n Parameter:\n img(tensor) - image to downscale\n Return:\n downscaled image wheer longer side is capped at self.max_length\n '''\n _, h, w = img.size()\n ratio = float(h) / float(w)\n if ratio > 1: # h > w\n w0 = math.ceil(self.max_length / ratio)\n return F.resize(img, (self.max_length, w0), antialias=True)\n else: # h <= w\n h0 = math.ceil(self.max_length / ratio)\n return F.resize(img, (h0, self.max_length), antialias=True)\n\nclass ContrastNormalization:\n '''\n Apply Global Histogram Stretching to normalize contrast\n '''\n def __init__(self, black_lvl=0, saturation_lvl=2**12 - 1):\n '''\n Constructor\n\n Parameter:\n black_lvl(int, optional) - value of black orginally captured by camera\n '''\n self.black_lvl = black_lvl\n self.saturation_lvl = saturation_lvl\n def __call__(self, img):\n '''\n Return contrast normalized image\n\n Parameters:\n img(tensor) - image to contrast normalize\n\n Return:\n output(tensor) - contrast normalized image in [0,1]\n '''\n # saturation_lvl = torch.max(img)\n return (img - self.black_lvl)/(self.saturation_lvl - self.black_lvl)\n\nclass RandomPatches:\n '''\n Randomly crop image to number of 32x32 patches\n '''\n def __init__(self, patch_size, num_patches, seed=123):\n '''\n Constructor\n\n Parameters:\n patch_size(int) - size of patch\n num_patches(int) - number of patch to return\n '''\n self.patch_size = patch_size\n self.num_patches = num_patches\n self.seed = seed\n\n def __call__(self, img):\n '''\n Return sequences of 32x32 patches that was randomly cropped from image\n\n Parameter:\n img(tensor) - image to radomly crop 32x32 patches\n Return:\n sequences of 32x32 patches that was randomly cropped from image\n '''\n\n # assign and initiate variables\n _, h, w = img.size() \n diameter = self.patch_size\n radius = self.patch_size // 2\n coords = set()\n center = list()\n\n # populate candidate for center of patches\n for row in range(radius, h-radius+1):\n for col in range(radius, w-radius+1):\n coords.add((row, col))\n \n # sample center for patches\n for _ in range(self.num_patches):\n valid = False\n while coords and not valid:\n y0, x0 = random.Random(self.seed).sample(coords, 1)[0]\n coords.remove((y0, x0))\n valid = True\n # check if (y0, x0) overlaps with any previous selected patch(s)\n for y, x in center:\n if not valid: break # if overlap, try another one\n valid &= (abs(y-y0) >= diameter or abs(x-x0) >= diameter) # check whether it overlap with other patches\n if valid: center.append((y0,x0)) # if it doesn't overlap, sample it\n\n # sample patches according to chosen centers\n patches = []\n for y,x in center:\n patch = img[:, y-radius:y+radius, x-radius:x+radius].detach().clone()\n patches.append(patch)\n\n return torch.stack(patches, dim=0) # list of tensors -> sequence(tensor) of tensors","repo_name":"rodroadl/LogSpaceExploration","sub_path":"CCCNN/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":8307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"37898490946","text":"from enum import IntEnum, unique\n\n\n\"\"\"\n列挙型の定義。\n\"\"\"\n\n\n# アルファベットの月をIntに変換する。\n@unique\nclass EMonthToInt(IntEnum):\n JAN = 1\n FEB = 2\n MAR = 3\n APR = 4\n MAY = 5\n JUN = 6\n JUL = 7\n AUG = 8\n SEP = 9\n OCT = 10\n NOV = 11\n DEC = 12\n\n\n# listでの各列が表するパラメータ\n@unique\nclass EUserParam(IntEnum):\n LAST_TWO_WEEKS = 0\n ATH = 1\n SCORE_SUM = 2\n STATUS_U_COUNT = 3\n LEVEL = 4\n BADGES = 5\n GAMES = 6\n FRIENDS = 7\n GROUPS = 8\n SCREENSHOTS = 9\n REVIEWS = 10\n","repo_name":"KIM20221208/GDWeb","sub_path":"host/Crawling/my_enums.py","file_name":"my_enums.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"69969553081","text":"nums = input().split()\n\nfor i in range(len(nums)):\n nums[i] = int(nums[i])\n\ndelta = int(input())\n\npares = 0\nindexes = []\nfor j in range(len(nums) - 1):\n if nums[j] * delta == nums[j + 1] or nums[j] / nums[j + 1] == delta:\n pares += 1\n indexes.append(j)\n\nprint(f\"{pares} par(es)\")\n\nfor k in range(len(indexes)):\n print(nums[indexes[k]], nums[indexes[k] + 1])\n\n","repo_name":"Axelvazslima/practices-python","sub_path":"exercises_solutions/for_loops/multiple_couple.py","file_name":"multiple_couple.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"21644529090","text":"import sys\nfrom Game import Game\n \nclass Menu:\n def __init__(self):\n self.app = Game()\n self.options = {\n\n \"1\": self.playgame,\n\n \"2\": self.rules,\n\n \"3\": self.weaponMenu,\n\n \"4\": self.showResults,\n\n \"5\": self.endProgram\n\n\n }\n \n\n def display_options(self):\n\n print(\"\"\" \n ************* MAIN MENU *************\n Rock Paper Scissors !!! \n\n Please choose one of the options below:\n \n 1. Play Game\n \n 2. See Rules\n \n 3. View Weapons \n\n 4. Show game results\n\n 5. quit\n\n \n \"\"\")\n\n\n\n\n def playgame(self):\n player1 = str(input(\"Rock, Paper or Scissors?\\n\")).lower()\n player2 = str(input(\"Rock, Paper or Scissors?\\n\")).lower()\n self.app.playGame(player1, player2)\n\n def rules(self):\n print(\"RULES\")\n print(\"Paper Covers Rock, Rock Smashes Scissors, Scissors Cuts Paper\\n\")\n\n \n def weaponMenu(self):\n print(\"Your weapons !!!\")\n print(\"(1) Rock\")\n print(\"(2) Paper\")\n print(\"(3) Scissors\")\n \n def showResults(self):\n self.app.showResults()\n \n\n def endProgram(self):\n self.app.quit()\n \n \n \n def run(self):\n\n while True:\n self.display_options()\n option = input(\"Enter an option: \")\n action = self.options.get(option)\n\n if action:\n action()\n else:\n print(\"{0} is not a valid option, Please try again\".format(option))","repo_name":"qsyed/python-programs","sub_path":"Rock_Paper_Scissor/Menu.py","file_name":"Menu.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"30666919","text":"import numpy as np\nfrom EOS import initFugacity,calcFugacity\nfrom plotData import plotIsoHeat,plotAbsUptake,plotAdsLayer\nfrom EOS import calcDensity,calcSatPress,critT\ndef sqrt(x):\n return np.sqrt(x)\ndef findAdsDensity(coef):\n #nmax in mol/g, vmax in m3/g\n #if vmax is zero divide by zero error! fix by manually setting adsrho to -1 if this is the case\n nmax=coef[\"nmax\"]#coef['SSA']/(6.022E23*15.7E-20)\n try:\n adsrho = nmax*1e3/coef['vmax']/1e6 #coef[\"ρAds\"]\n except:\n adsrho=-1\n print(\"Adsorbed Phase Density = {} mmol/ml\".format(adsrho))\n print(\"Adsorbed Molar Volume = {} m\\u00b3/mol\".format(0.001/adsrho))\n return adsrho\ndef AdsLayerGrowth(Press,actualPress,coef,isoModel,name='test'):\n fv1={}\n vmax = coef[\"vmax\"]\n for temp in Press:\n P=Press[temp]\n T=float(temp)\n P=np.array(P)\n fv1[temp]= 1e6 * vmax *isoModel.theta(P,T,coef)\n plotAdsLayer(actualPress, fv1, name)\n return fv1\n#press is a dictionary of temperatures to arrays of pressures\ndef absAds(Press,actualPress,coef,isoModel,name=\"test\",newFigure=False):\n nmax = coef[\"nmax\"]#coef['SSA']/(6.022E23*15.7E-20)\n fa1={}\n for temp in Press:\n T=float(temp)\n P=np.array(Press[temp])\n fa1[temp]=1000*(nmax)*isoModel.theta(P,T,coef)#((K1*P*(1+a6)/2+intTerm)/(1+(1+a6)*K1*P+intTerm))\n plotAbsUptake(actualPress,fa1,name,newFigure)\n return fa1\n\n#adjustPressure for fugacity\ndef adjustPressure(expP,normalPress, useFugacity,gasName):\n actualPress={}\n calcPress={}\n for temp in expP:\n if(float(temp)<critT(gasName)):\n actualPress[temp]=[]\n gasSatPress= calcSatPress(float(temp),gasName)\n for press in normalPress:\n if(press<gasSatPress):\n actualPress[temp].append(press)\n else:\n actualPress[temp]=normalPress\n calcPress[temp]=[]\n st=initFugacity(gasName)\n if(useFugacity):\n for press in actualPress[temp]:\n calcPress[temp].append(press*calcFugacity(st,press,float(temp)))\n else:\n calcPress[temp]=actualPress[temp]\n return actualPress,calcPress\n##calculate volumetric uptake (total and excess)\ndef calcUptake(ads,coef,gasName,sampBulkDens,tempPress,Xpore,den,useFugacity,isoModel):\n rssr=coef['rssr']\n y_fit={}\n fitDens={}\n actualPress,fitPress=adjustPressure(ads,tempPress,useFugacity=useFugacity,gasName=gasName)\n for temp in ads:\n tempFitDen=[]\n for i,press in enumerate(actualPress[temp]):\n tempFitDen.append(calcDensity(press,float(temp),gasName))\n fitDens[temp]=tempFitDen\n y_fit[temp] = isoModel.genExcess(fitPress[temp], t=float(temp),a=coef,den=fitDens[temp])\n measExcessVolUptake={}\n measTotalVolUptake={}\n calcExcessVolUptake={}\n calcTotalVolUptake={}\n press5bar=-1\n for p in range(len(tempPress)):\n if(round(tempPress[p],2)==0.50):\n press5bar=p\n totVol5bar={}\n for temp in ads:\n measExcessVolUptake[temp],measTotalVolUptake[temp]=calcVolUptake(ads[temp],den[temp],sampBulkDens,Xpore,gasName)\n calcExcessVolUptake[temp],calcTotalVolUptake[temp]=calcVolUptake(y_fit[temp],fitDens[temp],sampBulkDens,Xpore,gasName)\n\n #calculate 5 bar total volume based on calculated\n\n calcVolUptakeTemp=calcTotalVolUptake[temp]\n totVol5bar[temp]= calcVolUptakeTemp[press5bar]\n\n return y_fit,actualPress,fitDens,fitPress,rssr,measTotalVolUptake, calcTotalVolUptake,totVol5bar\n\n# calculate volumetric excess and volumetric total:\ndef calcVolUptake(exUptake,gasRho,bulkDens,Xpore,gasName=\"Methane\"):\n exUptake=np.asarray(exUptake)\n gasRho=np.asarray(gasRho)\n #we need to convert mol/m^3-> mmol/ml\n gasRho=gasRho/1000\n gasSTP=1/calcDensity(0.101325,273.15,gasName)*1000#22.413969545014 #methane at STP, mL/mmol\n\n #excessUptake in mmol/g,excessVolUptake in v/v\n excessVolUptake= exUptake*bulkDens*gasSTP\n #total density is in v/v\n totalVolUptake=excessVolUptake+(gasRho*Xpore)*gasSTP\n return excessVolUptake, totalVolUptake\n\ndef calcQstInt(fitPress,actualPress,coef,adsRho,fa1,name,closeFig,isoModel,gasName):\n Qst={}\n theta={}\n liqmolarv = 0.001 / adsRho\n for temp in fitPress:\n T=float(temp)\n dens=[]\n\n #todo: Check if press or actualPress is fugacity\n for press in actualPress[temp]:\n dens.append(calcDensity(press,T,gasName))\n dens=np.array(dens)\n P=np.array(fitPress[temp])\n #Qst=-TdP/dT(vgas-vads)\n #-dP/dT=(dTheta/dP)^-1*dtheta/dT\n Qst[temp]= -T*(1/dens-liqmolarv)*1000*isoModel.dPdT(P,T,coef)\n theta[temp]= isoModel.theta(P,T,coef)\n plotIsoHeat(actualPress, fa1, theta, Qst, name)\n return Qst,theta\n\n","repo_name":"cullenmq/REALIST","sub_path":"analyzeData.py","file_name":"analyzeData.py","file_ext":"py","file_size_in_byte":4875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"41591298667","text":"#\n# Z80 ins, outs\n#\n\n\nfrom utils import *\n\n\nclass inout:\n\n def __init__(self, parent):\n self.c = parent\n\n def ina(self, disass=False):\n a = self.c.fetch()\n ax = mkword(a, a)\n self.c.r[rA] = self.c.rdinp(ax)\n if not disass:\n return\n return \"IN A,({:02X})\".format(a)\n\n def outa(self, disass=False):\n a = self.c.fetch()\n ax = mkword(a, a)\n self.c.wrout(ax, self.c.r[rA])\n if not disass:\n return\n return \"OUT ({:02X}),A\".format(a)\n\n def inrc(self, disass=False):\n r0s = rname[self.c.r0]\n a = self.c.r[rpBC]\n d = self.c.rdinp(a)\n self.c.r[rF] = (logf(d) & 0xFE) | self.c.r[fC]\n self.c.r[r0s] = d\n if not disass:\n return\n return \"IN {:s},(C)\".format(rstr[r0s])\n\n def in0c(self, disass=False):\n a = self.c.r[rpBC]\n d = self.c.rdinp(a)\n self.c.r[rF] = (logf(d) & 0xFE) | self.c.r[fC]\n if not disass:\n return\n return \"IN (C)\"\n\n def outcr(self, disass=False):\n r0s = rname[self.c.r0]\n a = self.c.r[rpBC]\n self.c.wrout(a, self.c.r[r0s])\n if not disass:\n return\n return \"OUT (C),{:s}\".format(rstr[r0s])\n\n def outc0(self, disass=False):\n a = self.c.r[rpBC]\n self.c.wrout(a, 0)\n if not disass:\n return\n return \"OUT (C),0\"\n\n def getinstr(self):\n rv = {}\n for r1 in [0, 1, 2, 3, 4, 5, 7]:\n rv.update({\n bytes([0xED, 0x40 | (r1 << 3)]): self.inrc,\n bytes([0xED, 0x41 | (r1 << 3)]): self.outcr\n })\n\n # ina, outa\n rv.update({b'\\xd3': self.outa})\n rv.update({b'\\xdd\\xd3': self.outa})\n rv.update({b'\\xfd\\xd3': self.outa})\n\n rv.update({b'\\xdb': self.ina})\n rv.update({b'\\xdd\\xdb': self.ina})\n rv.update({b'\\xfd\\xdb': self.ina})\n\n # in0c, outc0\n rv.update({b'\\xed\\x70': self.in0c})\n rv.update({b'\\xed\\x71': self.outc0})\n\n return rv\n\n","repo_name":"szilvasyz/z80n","sub_path":"mod_inout.py","file_name":"mod_inout.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"26096497858","text":"# main.py\nimport os\nimport time\nimport yaml\nimport numpy as np\n\n# import test framework\nimport openhtf as htf\nfrom openhtf.plugs.user_input import UserInput\nfrom spintop_openhtf import TestPlan\nfrom openhtf.util import conf\nfrom openhtf.core import measurements\n\nimport SpiceInterface\nimport TestUtilities\n\nfrom criteria import get_criteria\n\n\n# import test parameters\nwith open(r'config.yml') as file:\n config = yaml.load(file, Loader=yaml.FullLoader)\n\n\n# This defines the name of the testbench.\nplan = TestPlan('bandgap_opamp')\nprint(\"Saving results to: %s\" % plan.history_path)\n\n\n@plan.testcase('ac_response')\n@htf.measures(get_criteria('dc_gain'))\n@htf.measures(get_criteria('unity_bandwidth'))\ndef ac_response(test):\n \"\"\"Measure the ac response of the opamp\"\"\"\n\n # create the test utility object\n test_utilities_obj = TestUtilities.TestUtilities()\n test_utilities_obj.netlist_generation(config['ac_response']['netlist'], \"rundir\")\n\n # create the spice interface\n spice_interface_obj = SpiceInterface.SpiceInterface(netlist_path=\"rundir/\"+config['ac_response']['netlist'].split('.')[0]+\".spice\")\n\n # append the simulation command\n spice_interface_obj.set_sim_command(config['ac_response']['sim_command'])\n\n # loop through all corners\n for corner in config['pvt']['corners']:\n\n # set corner\n spice_interface_obj.set_corner(corner)\n\n for temperature in config['pvt']['temperatures']:\n\n # set temperaure\n spice_interface_obj.set_temperature(temperature)\n\n # run the simulation\n spice_interface_obj.run_simulation()\n \n # save the response\n node = 'v(ac)'\n spice_interface_obj.plot_ac(node, display=False, title=\"AC Response\", \n linewidth=1, alpha=0.5, append=True)\n\n # get the dc gain and gainbandwidth prodcut\n dc_gain, unity_bandwidth = spice_interface_obj.measure_gain_bandwidth(node)\n\n print(\"DC Gain: %0.1f dB, Unity Bandwidth: %0.3f MHz\" % (dc_gain, unity_bandwidth/1e6))\n\n # test the margins\n test.measurements.dc_gain = dc_gain\n test.measurements.unity_bandwidth = unity_bandwidth\n\n # save the plot to file\n spice_interface_obj.fig.savefig(\"outputs/ac_response.svg\")\n\n\n\nif __name__ == '__main__':\n plan.no_trigger()\n plan.run_console(once=True)","repo_name":"yrrapt/caravel_amsat_txrx_ic","sub_path":"xschem/bandgap_opamp/verification/bandgap_opamp_verification.py","file_name":"bandgap_opamp_verification.py","file_ext":"py","file_size_in_byte":2415,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"40"} +{"seq_id":"22678570561","text":"\"\"\"\nAdd up the running time and emissions of all the experiments.\n\"\"\"\n\n# STD\nimport os\n\n# EXT\nimport pandas as pd\n\n# CONST\nEMISSIONS_DIR = \"../emissions\"\n\n\nif __name__ == \"__main__\":\n\n # Get all the experiment emissions directories\n experiment_dirs = os.listdir(EMISSIONS_DIR)\n\n # Loop through directories, extract time and emissions\n total_time, total_emissions, total_kWH = 0, 0, 0\n\n for dir in experiment_dirs:\n\n try:\n data = pd.read_csv(f\"{EMISSIONS_DIR}/{dir}/emissions.csv\")\n total_time += data[\"duration\"].values[0]\n total_emissions += data[\"emissions\"].values[0]\n total_kWH += data[\"energy_consumed\"].values[0]\n\n except FileNotFoundError:\n # print(f\"No emissions.csv found in {dir}\")\n ...\n\n minutes, seconds = divmod(total_time, 60)\n hours, minutes = divmod(minutes, 60)\n\n print(f\"Total time: {hours} hours, {minutes} minutes, {int(seconds)} seconds.\")\n print(f\"Total emissions: {total_emissions:.2f} kgCo2eq.\")\n print(f\"Total carbon efficiency: {total_emissions / total_kWH:.2f} kgCo2eq / kWH.\")\n","repo_name":"Kaleidophon/nlp-low-resource-uncertainty","sub_path":"scripts/get_total_runtime_and_emissions.py","file_name":"get_total_runtime_and_emissions.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"42649727650","text":"from app.shopping_cart import to_usd, product_finder, human_friendly_timestamp\nimport datetime\nimport pytest\n\n\ndef test_to_usd():\n \n assert to_usd(2.5) == \"$2.50\"\n\n assert to_usd(2.50) == \"$2.50\"\n\n assert to_usd(2.555556) == \"$2.56\"\n\n assert to_usd(1234567890.678) == \"$1,234,567,890.68\"\n\n assert to_usd(2.555556) == \"$2.56\"\n\n\ndef test_human_friendly_timestamp():\n \n assert human_friendly_timestamp(datetime.datetime(year=2020, month =1, day =1, hour = 0, minute= 0))== \"2020-01-01 12:00 AM\"\n\ndef test_product_finder():\n products = [\n {\"id\":1, \"name\": \"Chocolate Sandwich Cookies\", \"department\": \"snacks\", \"aisle\": \"cookies cakes\", \"price\": 3.50},\n {\"id\":3, \"name\": \"Robust Golden Unsweetened Oolong Tea\", \"department\": \"beverages\", \"aisle\": \"tea\", \"price\": 2.49},\n {\"id\":2, \"name\": \"All-Seasons Salt\", \"department\": \"pantry\", \"aisle\": \"spices seasonings\", \"price\": 4.99},\n ]\n\n matching_product_one = product_finder(1,products)\n matching_product_two = product_finder(2,products)\n matching_product_three = product_finder(3,products)\n\n \n assert matching_product_one[\"name\"] == \"Chocolate Sandwich Cookies\"\n assert matching_product_two[\"price\"] == 4.99\n assert matching_product_three[\"id\"] == 3\n \n","repo_name":"ahmadwilson21/shopping-cart","sub_path":"test/shopping_cart_test.py","file_name":"shopping_cart_test.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"23729962348","text":"#\n# helper class to grab variables from FRR's Makefile\n#\n\nimport os\nimport subprocess\nimport re\n\n\nclass MakeVarsBase(object):\n \"\"\"\n common code between MakeVars and MakeReVars\n \"\"\"\n\n def __init__(self):\n self._data = dict()\n\n def __getitem__(self, k):\n if k not in self._data:\n self.getvars([k])\n return self._data[k]\n\n def get(self, k, defval=None):\n if k not in self._data:\n self.getvars([k])\n return self._data.get(k) or defval\n\n\nclass MakeVars(MakeVarsBase):\n \"\"\"\n makevars['FOO_CFLAGS'] gets you \"FOO_CFLAGS\" from Makefile\n\n This variant works by invoking make as a subprocess, i.e. Makefile must\n be valid and working. (This is sometimes a problem if depfiles have not\n been generated.)\n \"\"\"\n\n def getvars(self, varlist):\n \"\"\"\n get a batch list of variables from make. faster than individual calls.\n \"\"\"\n rdfd, wrfd = os.pipe()\n\n shvars = [\"shvar-%s\" % s for s in varlist]\n make = subprocess.Popen(\n [\"make\", \"-s\", \"VARFD=%d\" % wrfd] + shvars, pass_fds=[wrfd]\n )\n os.close(wrfd)\n data = b\"\"\n\n rdf = os.fdopen(rdfd, \"rb\")\n while True:\n rdata = rdf.read()\n if len(rdata) == 0:\n break\n data += rdata\n\n del rdf\n make.wait()\n\n data = data.decode(\"US-ASCII\").strip().split(\"\\n\")\n for row in data:\n k, v = row.split(\"=\", 1)\n v = v[1:-1]\n self._data[k] = v\n\n\nclass MakeReVars(MakeVarsBase):\n \"\"\"\n makevars['FOO_CFLAGS'] gets you \"FOO_CFLAGS\" from Makefile\n\n This variant works by regexing through Makefile. This means the Makefile\n does not need to be fully working, but on the other hand it doesn't support\n fancy complicated make expressions.\n \"\"\"\n\n var_re = re.compile(\n r\"^([^=#\\n\\s]+)[ \\t]*=[ \\t]*([^#\\n]*)(?:#.*)?$\", flags=re.MULTILINE\n )\n repl_re = re.compile(r\"\\$(?:([A-Za-z])|\\(([^\\)]+)\\))\")\n\n def __init__(self, maketext):\n super(MakeReVars, self).__init__()\n self._vars = dict(self.var_re.findall(maketext.replace(\"\\\\\\n\", \"\")))\n\n def replacevar(self, match):\n varname = match.group(1) or match.group(2)\n return self._vars.get(varname, \"\")\n\n def getvars(self, varlist):\n for varname in varlist:\n if varname not in self._vars:\n continue\n\n val, prevval = self._vars[varname], None\n while val != prevval:\n prevval = val\n val = self.repl_re.sub(self.replacevar, val)\n\n self._data[varname] = val\n","repo_name":"FRRouting/frr","sub_path":"python/makevars.py","file_name":"makevars.py","file_ext":"py","file_size_in_byte":2662,"program_lang":"python","lang":"en","doc_type":"code","stars":2787,"dataset":"github-code","pt":"40"} +{"seq_id":"29120364586","text":"# -------------------------------------------------------------------------\r\n# AUTHOR: Musa Waghu\r\n# FILENAME: title of the source file\r\n# SPECIFICATION: description of the program\r\n# FOR: CS 4210- Assignment #2\r\n# TIME SPENT: how long it took you to complete the assignment\r\n# -----------------------------------------------------------*/\r\n\r\n# IMPORTANT NOTE: DO NOT USE ANY ADVANCED PYTHON LIBRARY TO COMPLETE THIS CODE SUCH AS numpy OR pandas. You have to\r\n# work here only with standard dictionaries, lists, and arrays\r\n\r\n# importing some Python libraries\r\nfrom sklearn import tree\r\nimport csv\r\n\r\ndataSets = ['contact_lens_training_1.csv', 'contact_lens_training_2.csv', 'contact_lens_training_3.csv']\r\nfor ds in dataSets:\r\n\r\n dbTraining = []\r\n X = []\r\n Y = []\r\n # reading the training data in a csv file\r\n with open(ds, 'r') as csvfile:\r\n reader = csv.reader(csvfile)\r\n for i, row in enumerate(reader):\r\n if i > 0: # skipping the header\r\n dbTraining.append(row)\r\n\r\n # transform the original categorical training features to numbers and add to the 4D array X. For instance Young =\r\n # 1, Prepresbyopic = 2, Presbyopic = 3 so X = [[1, 1, 1, 1], [2, 2, 2, 2], ...]]\r\n dictionary = {'Young': 1, 'Prepresbyopic': 2, 'Presbyopic': 3, 'Myope': 1, 'Yes': 1, 'No': 2,\r\n 'Normal': 1, 'Reduced': 2, 'Astigmatism': 1, 'Hypermetrope': 2}\r\n for row in dbTraining:\r\n data2 = []\r\n for i in range(4):\r\n data2.append(dictionary[row[i]])\r\n X.append(data2)\r\n # X =\r\n\r\n # transform the original categorical training classes to numbers and add to the vector Y. For instance Yes = 1,\r\n # No = 2, so Y = [1, 1, 2, 2, ...]\r\n for row in dbTraining:\r\n Y.append(dictionary[row[4]])\r\n # Y =\r\n\r\n accuracy = 0\r\n # loop your training and test tasks 10 times here\r\n for i in range(10):\r\n\r\n # fitting the decision tree to the data setting max_depth=3\r\n clf = tree.DecisionTreeClassifier(criterion='entropy', max_depth=3)\r\n clf = clf.fit(X, Y)\r\n dbTest = []\r\n\r\n # read the test data and add this data to dbTest\r\n with open('contact_lens_test.csv', 'r') as csvfile:\r\n reader = csv.reader(csvfile)\r\n for i, row in enumerate(reader):\r\n if i > 0: # skipping the header\r\n dbTest.append(row)\r\n # dbTest =\r\n\r\n pred = 0\r\n for row in dbTest:\r\n # transform the features of the test instances to numbers following the same strategy done during\r\n # training, and then use the decision tree to make the class prediction. For instance: class_predicted =\r\n # clf.predict([[3, 1, 2, 1]])[0] where [0] is used to get an integer as the predicted class label so that\r\n # you can compare it with the true label\r\n data3 = []\r\n for i in range(4):\r\n data3.append(dictionary[row[i]])\r\n class_predicted = clf.predict([data3])[0]\r\n if class_predicted == dictionary[row[4]]:\r\n pred += 1\r\n\r\n # compare the prediction with the true label (located at data[4]) of the test instance to start calculating\r\n # the accuracy\r\n # find the average of this model during the 10 runs (training and test set)\r\n accuracy2 = pred / len(dbTest)\r\n accuracy += accuracy2\r\n\r\n # print the average accuracy of this model during the 10 runs (training and test set).\r\n # your output should be something like that: final accuracy when training on contact_lens_training_1.csv: 0.2\r\n accuracy /= 10\r\n print(\"final accuracy when training on \" + ds + \": \" + str(accuracy))\r\n","repo_name":"musawaghu/CS4210-Assignment2","sub_path":"decision_tree_2.py","file_name":"decision_tree_2.py","file_ext":"py","file_size_in_byte":3716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"42764943132","text":"import numpy as np\n\ndef lightup_pattern_row_bw_1(k_mat,song_length):\n \"\"\"\n Turn the k_mat into marked rows with annotation markers for\n the start indices and zeroes otherwise\n\n Args\n ----\n k_mat: np.array\n List of pairs of repeats of length 1 with annotations \n marked. The first two columns refer to the first repeat\n of the pair, the second two refer to the second repeat of\n the pair, the fifth column refers to the length of the\n repeats, and the sixth column contains the annotation markers.\n \n song_length: int\n song length, which is the number of audio shingles\n \n Returns\n ------- \n pattern_row: np.array\n row that marks where non-overlapping repeats\n occur, marking the annotation markers for the\n start indices and zeroes otherwise.\n\n k_lst_out: np.array\n list of pairs of repeats of length BAND_WIDTH that\n contain no overlapping repeats with annotations marked.\n \"\"\"\n # Step 0 Initialize outputs: Start with a vector of all 0's for \n # pattern_row and assume that the row has no overlaps \n pattern_row = np.zeros((1,song_length)).astype(int)\n \n # Step 0a: Find the number of distinct annotations\n anno_lst = k_mat[:,5] # Get the elements of k_mat's fifth column\n anno_max = anno_lst.max(0) # Set the number of max elements in each column\n \n # Step 1: Loop over the annotations\n for a in range(1, anno_max+1):\n ands = (anno_lst == a) # Check if anno_lst is equal to a \n \n # Combine rows into a single matrix\n bind_rows = [k_mat[ands,0],k_mat[ands,2]]\n start_inds = np.concatenate(bind_rows)\n pattern_row[0,start_inds-1] = a\n \n # Step 2: Check that in fact each annotation has a repeat associated to it\n inds_markers = np.unique(pattern_row)\n\n # If any of inds_markers[i] == 0, then delete this index\n if np.any(inds_markers == 0):\n inds_markers = np.delete(inds_markers,0)\n\n if inds_markers.size > 0:\n for na in range (1,len(inds_markers)+1):\n IM = inds_markers[na-1]\n if IM > na:\n # Fix the annotations in pattern_row\n temp_anno = (pattern_row == IM)\n pattern_row = pattern_row - (IM * temp_anno) + (na * temp_anno)\n \n # Edit the annotations to match the annotations in pattern_row\n if k_mat.size > 0:\n k_lst_out = np.unique(k_mat, axis=0)\n for na in range (1,len(inds_markers)+1):\n IM = inds_markers[na-1]\n if IM > na:\n # Fix the annotaions in k_lst_out\n kmat_temp_anno = (k_lst_out[:,5] == IM)\n k_lst_out[:,5] = k_lst_out[:,5] - (IM * kmat_temp_anno) + (na*kmat_temp_anno)\n else:\n k_lst_out = np.array([])\n \n output = (pattern_row,k_lst_out)\n \n return output\n","repo_name":"lcarpenter20/ah","sub_path":"separated-functions/lightup_pattern_row_bw_1.py","file_name":"lightup_pattern_row_bw_1.py","file_ext":"py","file_size_in_byte":2896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"41570421580","text":"# -*- encoding: utf-8 -*-\n# @Time : 2020/12/22\n# @Author : Xiaolei Wang\n# @email : wxl1999@foxmail.com\n\n# UPDATE\n# @Time : 2020/12/22\n# @Author : Xiaolei Wang\n# @email : wxl1999@foxmail.com\n\nfrom crslab.download import DownloadableFile\n\nresources = {\n 'nltk': {\n 'version': '0.3',\n 'file': DownloadableFile(\n 'http://d0.ananas.chaoxing.com/download/1f5ab4127c9294b7a1a0783e428b14e8?fn=nltk',\n 'inspired_nltk.zip',\n '776cadc7585abdbca2738addae40488826c82de3cfd4c2dc13dcdd63aefdc5c4',\n ),\n 'special_token_idx': {\n 'pad': 0,\n 'start': 1,\n 'end': 2,\n 'unk': 3,\n 'pad_entity': 0,\n 'pad_word': 0,\n },\n },\n 'bert': {\n 'version': '0.3',\n 'file': DownloadableFile(\n 'http://d0.ananas.chaoxing.com/download/868102c5b21c4fa7f8b3f4574b3acf97?fn=bert',\n 'inspired_bert.zip',\n '9affea30978a6cd48b8038dddaa36f4cb4d8491cf8ae2de44a6d3dde2651f29c'\n ),\n 'special_token_idx': {\n 'pad': 0,\n 'start': 101,\n 'end': 102,\n 'unk': 100,\n 'sent_split': 2,\n 'word_split': 3,\n 'pad_entity': 0,\n 'pad_word': 0,\n },\n },\n 'gpt2': {\n 'version': '0.3',\n 'file': DownloadableFile(\n 'http://d0.ananas.chaoxing.com/download/854ef833f1365ac9c7f1254f767df81d?fn=gpt2',\n 'inspired_gpt2.zip',\n '23bb4ce3299186630fdf673e17f43ee43e91573ea786c922e3527e4c341a313c'\n ),\n 'special_token_idx': {\n 'pad': 0,\n 'start': 1,\n 'end': 2,\n 'unk': 3,\n 'sent_split': 4,\n 'word_split': 5,\n 'pad_entity': 0,\n 'pad_word': 0\n },\n }\n}\n","repo_name":"dwtcourses/CRSLab","sub_path":"crslab/data/dataset/inspired/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"40"} +{"seq_id":"37046801907","text":"from django.utils.datastructures import MultiValueDictKeyError\nfrom djoser.serializers import UserCreateSerializer, UserSerializer\nfrom rest_framework import serializers\n\nfrom recipes.models import Recipe\nfrom .models import Follow, User\n\n\nclass CustomUserCreateSerializer(UserCreateSerializer):\n\n class Meta(UserCreateSerializer.Meta):\n fields = ('id', 'username', 'email', 'first_name',\n 'last_name', 'password')\n\n def validate(self, data):\n if len(data['first_name']) == 0:\n raise serializers.ValidationError(\n 'Обязательное поле.')\n if len(data['last_name']) == 0:\n raise serializers.ValidationError(\n 'Обязательное поле.')\n if len(data['username']) == 0:\n raise serializers.ValidationError(\n 'Обязательное поле.')\n if len(data['email']) == 0:\n raise serializers.ValidationError(\n 'Обязательное поле.')\n if len(data['password']) == 0:\n raise serializers.ValidationError(\n 'Обязательное поле.')\n return data\n\n\nclass CustomUserSerializer(UserSerializer):\n is_subscribed = serializers.SerializerMethodField(read_only=True)\n\n class Meta(UserSerializer.Meta):\n fields = ('id', 'username', 'email', 'first_name', 'last_name',\n 'is_subscribed',)\n\n def get_is_subscribed(self, obj):\n request = self.context.get('request')\n if not request or request.user.is_anonymous:\n return False\n user = request.user\n return Follow.objects.filter(author=obj, user=user).exists()\n\n\nclass RecipeEasyRetrieveSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Recipe\n fields = (\n 'id', 'name',\n 'image', 'cooking_time',\n )\n\n\nclass FollowRetrieveSerializer(serializers.ModelSerializer):\n recipes = serializers.SerializerMethodField()\n id = serializers.ReadOnlyField()\n first_name = serializers.ReadOnlyField()\n last_name = serializers.ReadOnlyField()\n username = serializers.ReadOnlyField()\n email = serializers.ReadOnlyField()\n recipes_count = serializers.SerializerMethodField()\n is_subscribed = serializers.SerializerMethodField()\n\n class Meta:\n model = Follow\n fields = ('id', 'username', 'email', 'first_name',\n 'last_name', 'recipes', 'recipes_count',\n 'is_subscribed',)\n\n def get_recipes(self, obj):\n try:\n limit = self.context.get('request').query_params['recipes_limit']\n except MultiValueDictKeyError:\n limit = 10\n queryset = Recipe.objects.filter(author=obj)[:int(limit)]\n return RecipeEasyRetrieveSerializer(queryset, many=True).data\n\n def get_recipes_count(self, obj):\n return Recipe.objects.filter(author=obj).count()\n\n def get_is_subscribed(self, obj):\n request = self.context.get('request')\n if not request or request.user.is_anonymous:\n return False\n user = request.user\n return Follow.objects.filter(author=obj, user=user).exists()\n\n\nclass FollowCreateSerializer(serializers.ModelSerializer):\n author = CustomUserSerializer(read_only=True)\n\n class Meta:\n model = Follow\n fields = ('author',)\n\n def create(self, validated_data):\n author_id = self.context['view'].kwargs['author_id']\n author = User.objects.get(id=author_id)\n user = self.context.get('request').user\n Follow.objects.get_or_create(author=author, user=user)\n\n return author\n\n def validate(self, data):\n author_id = self.context['view'].kwargs['author_id']\n author = User.objects.get(id=author_id)\n user = self.context.get('request').user\n if author == user:\n raise serializers.ValidationError(\n 'Нельзя подписаться на самого себя'\n )\n if Follow.objects.filter(author=author, user=user).exists():\n raise serializers.ValidationError(\n 'Нельзя подписаться на одного автора дважды'\n )\n\n return data\n\n def to_representation(self, instance):\n request = self.context.get('request')\n context = {'request': request}\n return FollowRetrieveSerializer(\n instance, context=context).data\n","repo_name":"PahaPoiss/foodgram-project-react","sub_path":"backend/api_foodgram/users/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":4502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"32193458178","text":"import concurrent.futures\nimport json\nimport logging\nimport math\nimport multiprocessing\nimport operator\nimport time\nimport traceback\nfrom datetime import datetime\n\nfrom apscheduler.schedulers.background import BackgroundScheduler\n\nfrom btc38 import btc38exchange\nfrom data import marketmakerexchange\nfrom dex import dexexchange\nfrom notifications import emailsender\n\nCNY_CURRENCY_CODE = marketmakerexchange.CNY\nBTS_CURRENCY_CODE = marketmakerexchange.BTS\nBIDS = marketmakerexchange.BIDS\nASKS = marketmakerexchange.ASKS\nUPDATE_TIME = \"updateTime\"\n\nPROFIT_THRESHOLD = 0.00\n\nMINIMUM_PURCHASE_VOLUME = 500\n# Leave 100 shares in the listing as buffer\nMIN_LISTING_VOLUME_BUFFER = 500\n\nACCOUNT_CNY_RESERVE = 50\nACCOUNT_BTS_RESERVE = 100\n\nEXCHANGE_SYNC_TOLERANCE = 2\nUPDATE_LAG_TOLERANCE = 10\n# Order book information is valid for 1 second.\nORDER_BOOK_VALID_WINDOW = 1\n\n# logger\nlog = logging.getLogger(__name__)\n\n\nclass TradeExchange(object):\n def __init__(self):\n with open(\"configurations/config.json\") as client_config:\n config = json.load(client_config)\n\n self.exchanges = {}\n\n for exchange_client in config:\n if exchange_client['client'] == dexexchange.EXCHANGE_NAME:\n dex_exchange = dexexchange.DexExchange(exchange_client['WITNESS_URL'],\n exchange_client['ACCOUNT'],\n exchange_client['SECRET_KEY'])\n self.exchanges[dex_exchange.get_exchange_name()] = dex_exchange\n if exchange_client['client'] == btc38exchange.EXCHANGE_NAME:\n btc38_exchange = btc38exchange.BTC38Exchange(exchange_client['ACCESS_KEY'],\n exchange_client['SECRET_KEY'],\n exchange_client['ACCOUNT_ID'])\n self.exchanges[btc38_exchange.get_exchange_name()] = btc38_exchange\n\n\n# Daemon to update order books. Each exchange requires one daemon. Daemon should not terminate in any cases.\ndef order_book_fetcher_daemon(exchange, order_book):\n while True:\n exchange_name = exchange.get_exchange_name()\n # Multiprocessing manager cannot update nested items in the dictionary, therefore, I have to create a copy of\n # the nested dictionary, update it, and then put it back into the main dictionary.\n exchange_order_book = order_book[exchange_name]\n time_since_last_update = 0\n\n try:\n top_offers = exchange.get_top_offers()\n\n current_time = datetime.now()\n time_since_last_update = (current_time - exchange_order_book[UPDATE_TIME]).total_seconds()\n exchange_order_book[BIDS] = top_offers[0]\n exchange_order_book[ASKS] = top_offers[1]\n exchange_order_book[UPDATE_TIME] = current_time\n order_book[exchange_name] = exchange_order_book\n\n time.sleep(0.3)\n except Exception as e:\n if time_since_last_update > UPDATE_LAG_TOLERANCE:\n log.warning(\"Exchange: {} receives no update for {} seconds. (Last error: {})\"\n .format(exchange_name, time_since_last_update, e))\n\n\ndef round_up(value, decimal=0):\n return math.ceil(value * (10 ** decimal)) / (10 ** decimal)\n\n\ndef round_down(value, decimal=0):\n return math.floor(value * (10 ** decimal)) / (10 ** decimal)\n\n\n# Send notification email using the template.\ndef send_notification_email(message):\n with open(\"configurations/email_header.json\") as email_header:\n header = json.load(email_header)\n with open(\"configurations/email_credential.json\") as email_credential:\n credential = json.load(email_credential)\n\n email_sender = emailsender.EmailSender(credential[\"login\"], credential[\"password\"])\n email_process = multiprocessing.Process(target=email_sender.send_email_with_message,\n args=(message, header[\"subject\"], header[\"from\"], header[\"to\"]))\n email_process.start()\n\n\nclass MarketMaker(object):\n def __init__(self):\n trade_exchanges = TradeExchange()\n self.exchanges_dict = trade_exchanges.exchanges\n\n self.account_balance = {exchange_name: {CNY_CURRENCY_CODE: 0, BTS_CURRENCY_CODE: 0} for\n exchange_name, exchange in self.exchanges_dict.items()}\n current_time = datetime.now()\n manager = multiprocessing.Manager()\n self.order_book = manager.dict({exchange_name: {BIDS: [0, 0], ASKS: [0, 0], UPDATE_TIME: current_time} for\n exchange_name, exchange in self.exchanges_dict.items()})\n\n self.last_transaction_time = {exchange_name: current_time for\n exchange_name, exchange in self.exchanges_dict.items()}\n\n # Check balance only when transactions were made.\n self.need_balance_check = True\n\n def run(self):\n scheduler = BackgroundScheduler()\n # Update account balance every 5 minutes in case external transfer happened.\n scheduler.add_job(self.__request_account_balance_checking, 'interval', minutes=5)\n scheduler.start()\n\n order_book_fetchers = []\n for exchange_name, exchange in self.exchanges_dict.items():\n p = multiprocessing.Process(target=order_book_fetcher_daemon, args=(exchange, self.order_book))\n p.daemon = True\n order_book_fetchers.append(p)\n p.start()\n log.info(\"Started updating order book process for exchange: {}, pid: {}\"\n .format(exchange.get_exchange_name(), p.pid))\n\n while all(map(multiprocessing.Process.is_alive, order_book_fetchers)):\n try:\n self.__speculate()\n time.sleep(0.3)\n except Exception as e:\n traceback.print_exc()\n log.error(\"Unexpected exception caught in main execution. (Error: {})\".format(e))\n\n log.fatal(\"Order book daemon terminated! Exit the market maker.\")\n send_notification_email(\"Market Maker terminated!\")\n\n def __speculate(self):\n if self.need_balance_check:\n try:\n self.__update_account_balance()\n except Exception as e:\n log.error(\"Failed to update account balance.(Error: {})\".format(e))\n return\n\n for buyer_name, buyer_exchange in self.exchanges_dict.items():\n if self.__is_order_book_valid(buyer_name):\n profitable_exchange_name = self.__find_profitable_exchange(buyer_exchange)\n if profitable_exchange_name:\n seller_exchange = self.exchanges_dict[profitable_exchange_name]\n\n # BTC38 can only accept price with 5 decimal places, and volume up to 6 decimal places.\n # Round up the purchase price, and round down the sell price to guarantee profit.\n purchase_price = round_up(self.order_book[buyer_name][ASKS][0], 4)\n sell_price = round_down(self.order_book[profitable_exchange_name][BIDS][0], 4)\n\n purchase_volume = round(self.__calculate_purchase_volume(buyer_exchange, seller_exchange), 6)\n sell_volume = round(self.__calculate_sell_volume(buyer_exchange, purchase_volume), 6)\n\n if sell_volume < MINIMUM_PURCHASE_VOLUME:\n log.info(\"Under minimum arbitrage volume: {}\".format(sell_volume))\n else:\n log.info(\"Placing arbitrage order...\")\n order_placed = self.__place_arbitrage_orders(buyer_exchange, purchase_price, purchase_volume,\n seller_exchange, sell_price, sell_volume)\n if order_placed:\n send_notification_email(\"Arbitrage: purchase from {} at {}, volume: {}. Total: {}\\n\"\n \"Arbitrage: sell to {} at {}, volume: {}. Total: {}\"\n .format(buyer_name, purchase_price, purchase_volume,\n purchase_price * purchase_volume,\n profitable_exchange_name, sell_price, sell_volume,\n sell_price * sell_volume))\n else:\n send_notification_email(\"Failed to place arbitrage order!\")\n\n \"\"\"\n Find the highest bidder in the order book. If the profit is higher than the threshold,\n return profitable exchange name.\n \"\"\"\n def __find_profitable_exchange(self, buyer_exchange):\n buyer_name = buyer_exchange.get_exchange_name()\n target_order_book = {exchange_name: order_book[BIDS][0] for exchange_name, order_book in self.order_book.items()\n if self.__is_order_book_valid(exchange_name) and exchange_name != buyer_name}\n\n if len(target_order_book) == 0:\n return None\n\n best_offer = max(target_order_book.items(), key=operator.itemgetter(1))\n purchase_price = self.order_book[buyer_name][ASKS][0]\n profit = (best_offer[1] - purchase_price) / purchase_price\n if profit - buyer_exchange.get_profit_deduction() > PROFIT_THRESHOLD:\n log.info(\"Found profitable exchange {}! Profit: {:.2f}%.\"\n .format(buyer_name, profit * 100))\n return best_offer[0]\n\n def __order_books_in_sync(self, base_exchange_name, target_exchange_name):\n base_ex_update_time = self.order_book[base_exchange_name][UPDATE_TIME]\n compare_ex_update_time = self.order_book[target_exchange_name][UPDATE_TIME]\n if abs((base_ex_update_time - compare_ex_update_time).total_seconds()) > EXCHANGE_SYNC_TOLERANCE:\n return False\n else:\n return True\n\n def __is_order_book_valid(self, exchange_name):\n current_time = datetime.now()\n last_update_time = self.order_book[exchange_name][UPDATE_TIME]\n updated_after_transactions = last_update_time > self.last_transaction_time[exchange_name]\n order_book_valid = (current_time - last_update_time).total_seconds() < ORDER_BOOK_VALID_WINDOW\n return updated_after_transactions and order_book_valid\n\n def __request_account_balance_checking(self):\n self.need_balance_check = True\n\n def __update_account_balance(self):\n for exchange_name, exchange in self.exchanges_dict.items():\n exchange_name = exchange.get_exchange_name()\n balance = exchange.get_maker_account_balance()\n self.account_balance[exchange_name][CNY_CURRENCY_CODE] = balance[CNY_CURRENCY_CODE]\n self.account_balance[exchange_name][BTS_CURRENCY_CODE] = balance[BTS_CURRENCY_CODE]\n\n log.info(\"Account balance updated. New account balance: {}\".format(self.account_balance))\n self.need_balance_check = False\n\n # Price = BTS price in terms of CNY. Volume = number of BTS shares.\n def __calculate_purchase_volume(self, buyer_exchange, seller_exchange):\n buyer_exchange_name = buyer_exchange.get_exchange_name()\n seller_exchange_name = seller_exchange.get_exchange_name()\n\n buyer_vol = self.order_book[buyer_exchange_name][ASKS][1]\n seller_vol = self.order_book[seller_exchange_name][BIDS][1]\n\n volume_available = min(buyer_vol, seller_vol)\n\n if volume_available < MINIMUM_PURCHASE_VOLUME + MIN_LISTING_VOLUME_BUFFER:\n return 0\n\n buyer_price = self.order_book[buyer_exchange_name][ASKS][0]\n\n usable_cny = self.account_balance[buyer_exchange_name][CNY_CURRENCY_CODE] - ACCOUNT_CNY_RESERVE\n usable_bts = self.account_balance[seller_exchange_name][BTS_CURRENCY_CODE] - ACCOUNT_BTS_RESERVE\n\n if usable_cny <= 0:\n log.info(\"Insufficient fund on buyer account: {}\".format(buyer_exchange_name))\n return 0\n elif usable_bts <= 0:\n log.info(\"Insufficient fund on seller account: {}\".format(seller_exchange_name))\n return 0\n else:\n safe_volume = volume_available - max(volume_available * 0.2, MIN_LISTING_VOLUME_BUFFER)\n return min(usable_cny / buyer_price, usable_bts, safe_volume)\n\n @staticmethod\n def __calculate_sell_volume(buyer_exchange, purchase_volume):\n buyer_name = buyer_exchange.get_exchange_name()\n # Withdrawal fee from btc38 is 1%, therefore, sell_vol = purchase_vol * 0.99 - 1\n if buyer_name == btc38exchange.EXCHANGE_NAME:\n return purchase_volume * 0.99 - 1\n else:\n return purchase_volume - 1\n\n def __open_order_exists(self):\n for exchange_name, exchange in self.exchanges_dict.items():\n orders = exchange.list_my_orders()\n if orders:\n log.info(\"{} order still open: {}\".format(exchange.get_exchange_name(), orders))\n return True\n return False\n\n \"\"\"\n Place arbitrage order, return True if both orders have been placed, false otherwise.\n After placing arbitrage order, send out email notification.\n Price = BTS price in terms of CNY. Volume = number of BTS shares.\n \"\"\"\n def __place_arbitrage_orders(self, buyer_exchange, purchase_price, purchase_volume,\n seller_exchange, sell_price, sell_volume):\n with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:\n seller_thread_future = executor.submit(self.__place_orders_thread,\n seller_exchange, 2, sell_price, sell_volume)\n buyer_thread_future = executor.submit(self.__place_orders_thread,\n buyer_exchange, 1, purchase_price, purchase_volume)\n\n seller_exception = seller_thread_future.exception()\n buyer_exception = buyer_thread_future.exception()\n\n # If this method is called, successful or not, we need to recheck the account balance.\n self.__request_account_balance_checking()\n\n if seller_exception is not None or buyer_exception is not None:\n error_email = \"Seller exception: {}\\nBuyer exception: {}\".format(seller_exception, buyer_exception)\n send_notification_email(error_email)\n return False\n\n return True\n\n def __place_orders_thread(self, exchange, order_type, price, volume):\n exchange_name = exchange.get_exchange_name()\n order_message = \"Place order at: {} - order type {}, at {}, volume: {}\".format(\n exchange_name, order_type, price, volume)\n try:\n exchange.submit_arbitrage_order(order_type, price, volume)\n current_time = datetime.now()\n self.last_transaction_time[exchange_name] = current_time\n log.info(\"Arbitrage order placed successfully\" + order_message)\n except Exception as e:\n log.error(\"Failed to place order - \" + order_message + \". Error: {}.\".format(e))\n raise e\n","repo_name":"ranc1/marketmaker","sub_path":"marketmaker.py","file_name":"marketmaker.py","file_ext":"py","file_size_in_byte":15275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"73863067319","text":"import requests\nfrom cookplanner_app.models import Ingredients, Recipe, RecipeIngredients, Taste\n# Replace 'YOUR_APP_ID' and 'YOUR_APP_KEY' with your actual Edamam API credentials\nAPP_ID = 'e1b849e6'\nAPP_KEY = '47a6c0945ba54f5f7a2c07513f10a530'\n# Base URL for the Edamam Recipe Search API\nBASE_URL = 'https://api.edamam.com/search'\n# Parameters for the API request\nparams = {\n 'q': 'breakfast',\n 'app_id': APP_ID,\n 'app_key': APP_KEY,\n 'from': 0, # Start index of the results\n 'to': 100, # End index of the results (max 100)\n 'mealType': 'dinner', # To ensure we get breakfast recipes\n}\nresponse = requests.get(BASE_URL, params=params)\nif response.status_code == 200:\n data = response.json()\n recipes = data.get('hits', [])\n neutral_taste = Taste.objects.get(name=\"neutral\")\n for recipe in recipes:\n calorie = recipe['recipe'][\"calories\"]\n recipe_name = recipe['recipe']['label']\n cook_time = int(recipe['recipe']['totalTime']) * 60\n print(\"delta time\", cook_time)\n ingredients = []\n for ingredient in recipe['recipe']['ingredients']:\n ingredient_name = ingredient[\"food\"]\n ingredient_amount = ingredient[\"weight\"]\n if ingredient_amount == 0:\n continue\n existing = Ingredients.objects.filter(name=ingredient_name).first()\n print(\".\")\n if not existing:\n ingr = Ingredients(name=ingredient_name)\n ingr.save()\n existing = Ingredients.objects.filter(name=ingredient_name).first()\n ingredients.append((existing, ingredient_amount))\n else:\n ingredients.append((existing, ingredient_amount))\n rec = Recipe(name=recipe_name, cook_time=cook_time, difficulty=2, image=None, taste=neutral_taste, calorie=calorie)\n rec.save()\n print(f\"recipe saved: {recipe_name}\")\n for ingredient, amount in ingredients:\n RecipeIngredients.objects.create(recipe=rec, ingredients=ingredient, amount=amount, unit=\"g\")\nelse:\n print(\"Failed to retrieve recipes:\", response.status_code)\n","repo_name":"Happydeath97/cookplanner","sub_path":"webapp/load_database.py","file_name":"load_database.py","file_ext":"py","file_size_in_byte":2139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"72888763960","text":"import copy\nimport random\nimport operator\n\nclass Player:\n playerNumber = None\n board = None\n playerOneBoard = None\n playerOneWeights = None\n playerTwoWeights = None\n \n def __init__(self, playerNumber, board, playerOneBoard, playerOneWeights, playerTwoWeights):\n self.playerNumber = playerNumber\n self.board = board\n self.playerOneBoard = playerOneBoard\n self.playerOneWeights = playerOneWeights\n self.playerTwoWeights = playerTwoWeights\n\n def play(self, mode):\n if mode == 1:\n return self.playAddMove()\n else:\n return self.playRemoveMove()\n\n def playAddMove(self):\n moves = self.getPlayableAddMoves()\n if len(moves) == 0:\n move = self.playRandomAddMove()\n else:\n move = self.playBalancePlayerOneMove(moves)\n return move\n\n def playRemoveMove(self):\n moves = self.getPlayableRemoveMoves()\n if len(moves) == 0:\n move = self.playRandomRemoveMove()\n else:\n move = self.playBalancePlayerOneMove(moves)\n return move\n\n def playBalancePlayerOneMove(self, moves):\n # The moves are sorted by the left torque\n sortedMoves = sorted(moves, key = operator.itemgetter(2), reverse = True)\n (playerOneTorqueLeft, playerOneTorqueRight) = self.playerOneBoard.getTorque()\n if self.playerNumber == 1:\n # We want to balance the weights that player one placed as much as possible.\n if abs(playerOneTorqueLeft) > abs(playerOneTorqueRight):\n bestMove = sortedMoves[-1]\n else:\n bestMove = sortedMoves[0]\n else:\n # Otherwise we want to unbalance the weights that player one placed as much as possible.\n bestMove = sortedMoves[0]\n return bestMove\n\n def getPlayableAddMoves(self):\n if self.playerNumber == 1:\n weights = self.playerOneWeights\n elif self.playerNumber == 2:\n weights = self.playerTwoWeights\n\n locations = self.board.getUnoccupiedLocations()\n\n playableMoves = set()\n for weight in weights:\n for location in locations:\n testBoard = self.board.__clone__()\n testBoard.addWeight(location, weight)\n\n move = (location, weight)\n if not testBoard.checkIfTipped():\n # Playable moves are (location, weight, torque1, torque2)\n torque = testBoard.getTorque()\n thisMove = move + torque\n playableMoves.add(thisMove)\n return playableMoves\n\n def getPlayableRemoveMoves(self):\n # Player one cannot remove the weights player two added unless those are the only weights left.\n locations = set()\n if self.playerNumber == 1:\n locations = self.playerOneBoard.getOccupiedLocations()\n board = self.playerOneBoard\n if locations == set():\n locations = self.board.getOccupiedLocations()\n board = self.board\n\n playableMoves = set()\n for location in locations:\n weight = board.getWeightAtLocation(location)\n\n testBoard = board.__clone__()\n testBoard.removeWeight(location, weight)\n\n move = (location, weight)\n if not testBoard.checkIfTipped():\n # Playable moves are (location, weight, torque1, torque2)\n torque = testBoard.getTorque()\n thisMove = move + torque\n playableMoves.add(thisMove)\n return playableMoves\n\n def playRandomAddMove(self):\n # We only reach this place if we know we will lose, so implement to choose anything.\n if self.playerNumber == 1:\n weights = self.playerOneWeights\n elif self.playerNumber == 2:\n weights = self.playerTwoWeights\n\n locations = self.board.getUnoccupiedLocations()\n location = random.choice(tuple(locations))\n weight = random.choice(tuple(weights))\n\n testBoard = board.__clone__()\n testBoard.addWeight(location, weight)\n torque = testBoard.getTorque()\n move = (location, weight) + torque\n return move\n\n def playRandomRemoveMove(self):\n # We only reach this place if we know we will lose, so implement to choose anything.\n # Player one cannot remove the weights player two added unless those are the only weights left.\n locations = set()\n if self.playerNumber == 1:\n locations = self.playerOneBoard.getOccupiedLocations()\n board = self.playerOneBoard\n if locations == set():\n locations = self.board.getOccupiedLocations()\n board = self.board\n\n location = random.choice(tuple(locations))\n weight = board.getWeightAtLocation(location)\n\n testBoard = board.__clone__()\n testBoard.removeWeight(location, weight)\n torque = testBoard.getTorque()\n move = (location, weight) + torque\n return move\n\nclass Board:\n BOARD_LENGTH = 30\n BOARD_WEIGHT = 3\n PIVOT_LEFT_LOCATION = -3\n PIVOT_RIGHT_LOCATION = -1\n __board = None\n __pivotLeftDistanceMap = None\n __pivotRightDistanceMap = None\n\n def __init__(self):\n # Initialize board and setup values for evaluating torque\n self.__board = (0,)*(self.BOARD_LENGTH+1)\n self.__pivotLeftDistanceMap = self.__getDistanceMapForLocation(self.PIVOT_LEFT_LOCATION)\n self.__pivotRightDistanceMap = self.__getDistanceMapForLocation(self.PIVOT_RIGHT_LOCATION)\n\n def __clone__(self):\n clone = copy.deepcopy(self)\n return clone\n\n def checkIfTipped(self):\n (torqueLeftPivot, torqueRightPivot) = self.getTorque()\n return True if torqueLeftPivot < 0 or torqueRightPivot > 0 else False\n\n def getTorque(self):\n torqueLeftPivot = self.__getTorque(self.__pivotLeftDistanceMap)\n torqueRightPivot = self.__getTorque(self.__pivotRightDistanceMap)\n return (torqueLeftPivot, torqueRightPivot)\n\n def __getTorque(self, distanceMap):\n torque = tuple(distanceMap[i] * self.__board[i] for i in range(0, self.BOARD_LENGTH+1))\n\n centerOfDistanceForce = distanceMap[self.__getIndexFromBoardLocation(0)] * self.BOARD_WEIGHT \n torque = sum(torque) + centerOfDistanceForce\n return torque\n\n def addWeight(self, location, weight):\n if weight < 0:\n raise Exception(\"Weight cannot be negative\")\n elif abs(location) > self.BOARD_LENGTH/2:\n raise Exception(\"Location not on board\")\n elif self.getWeightAtLocation(location) != 0:\n raise Exception('Location: ' + str(location) + ' is already occupied with Weight: ' + str(weight))\n self.__board = self.__replaceBoardAtLocationWithValue(self.__board, location, weight)\n\n def removeWeight(self, location, weight):\n index = self.__getIndexFromBoardLocation(location)\n weightAtLocation = self.getWeightAtLocation(location) \n if weightAtLocation == weight:\n self.__board = self.__replaceBoardAtLocationWithValue(self.__board, location, 0)\n else:\n raise Exception(\"Location: \" + str( location) + \" Weight at location: \" + str(weightAtLocation) +\n \" Tried to remove weight: \" + str(weight))\n\n def getWeightAtLocation(self, location):\n index = self.__getIndexFromBoardLocation(location)\n weight = self.__board[index]\n return weight\n\n def getUnoccupiedLocations(self):\n unoccupiedLocations = set(self.__getBoardLocationFromIndex(i)\n for i, v in enumerate(self.__board)\n if v == 0)\n return unoccupiedLocations\n\n def getOccupiedLocations(self):\n occupiedLocations = set(self.__getBoardLocationFromIndex(i)\n for i, v in enumerate(self.__board)\n if v != 0)\n return occupiedLocations\n\n def __getDistanceMapForLocation(self, location):\n index = self.__getIndexFromBoardLocation(location)\n distanceMap = tuple(range(0-index, (self.BOARD_LENGTH+1)-index))\n return distanceMap\n\n def __replaceBoardAtLocationWithValue(self, inputBoard, location, value):\n index = self.__getIndexFromBoardLocation(location)\n outputBoard = inputBoard[0:index] + (value,) + inputBoard[index + 1:]\n return outputBoard\n\n def __getIndexFromBoardLocation(self, location):\n index = int(location + self.BOARD_LENGTH/2)\n return index\n\n def __getBoardLocationFromIndex(self, index):\n location = int(index - self.BOARD_LENGTH/2)\n return location\n\ndef readBoard(fileName, maxWeight = 12):\n board = Board()\n playerOneBoard = Board()\n playerOneWeights = set(range(1,maxWeight+1))\n playerTwoWeights = set(range(1,maxWeight+1))\n with open(fileName, 'r') as file_:\n data = file_.read()\n data = data.split('\\n')\n\n if data[-1] == '':\n data = data[0:-1]\n\n for values in data:\n values = values.split()\n location = int(values[0])\n weight = int(values[1])\n playerNumber = int(values[2])\n if playerNumber in {0, 1}:\n playerOneBoard.addWeight(location,weight)\n board.addWeight(location, weight)\n \n if playerNumber == 1 and weight != 0:\n playerOneWeights.remove(weight)\n elif playerNumber == 2 and weight != 0:\n playerTwoWeights.remove(weight)\n \n if board.checkIfTipped():\n print(\"The board has already tipped\")\n return (board, playerOneBoard, playerOneWeights, playerTwoWeights)\n\ndef execute(mode, playerNumber):\n (board, playerOneBoard, playerOneWeights, playerTwoWeights) = readBoard('board.txt')\n player = Player(playerNumber, board, playerOneBoard, playerOneWeights, playerTwoWeights)\n return player.play(mode)\n\nif __name__ == '__main__':\n import sys\n\n if len(sys.argv) < 4:\n remainingTime = float('Inf')\n else:\n remainingTime = float(sys.argv[3])\n\n mode = int(sys.argv[1])\n playerNumber = int(sys.argv[2])\n move = execute(mode, playerNumber)\n print(str(move[0]) + ' ' + str(move[1]))\n","repo_name":"jkcn90/HPS2013","sub_path":"NoTipping/white_truffle.py","file_name":"white_truffle.py","file_ext":"py","file_size_in_byte":9344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"10283158076","text":"\"\"\"\nConverts an ELF to a DOL file\n\"\"\"\n\nfrom argparse import ArgumentParser\n\nfrom ppcdis import elf_to_dol\n\nif __name__ == \"__main__\":\n parser = ArgumentParser(description=\"Convert ELF to DOL\")\n parser.add_argument(\"input\", type=str, help=\"ELF input path\")\n parser.add_argument(\"-o\", \"--out\", type=str, help=\"DOL output path\")\n args = parser.parse_args()\n\n in_path = args.input\n\n if args.out is None:\n if in_path.endswith(\".elf\"):\n out_path = in_path.replace(\".elf\", \".dol\")\n else:\n out_path = in_path + \".dol\"\n else:\n out_path = args.out\n\n elf_to_dol(in_path, out_path)\n","repo_name":"1superchip/ty-decomp","sub_path":"tools/ppcdis/elf2dol.py","file_name":"elf2dol.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"40"} +{"seq_id":"10499490505","text":"def check_pwd(s):\n flag = 0\n n = len(s)\n for i in range(1, n//2):\n for j in range(0, n-i*2+1):\n if s[j:j+i] == s[j+i:j+2*i]:\n flag = 1\n break\n if flag == 1:\n break\n if flag == 1:\n print(\"Rejected\")\n else:\n print(\"Accepted\")\n\n\nT = int(input())\nfor _ in range(T):\n s = input()\n check_pwd(s)\n","repo_name":"leejongcheal/algorithm_python","sub_path":"알고리즘 문제풀이전략_python/ch15 동적계획법응용/해커의도전.py","file_name":"해커의도전.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"40636381054","text":"from collections import defaultdict\n\n\ndef print_nested_list(nested_list):\n for inner_list in nested_list:\n if inner_list:\n print(*inner_list) # Use unpacking to print elements within the same inner list\n else:\n print(-1)\n\n\ndef get_valid_input():\n value = input().strip()\n if not 1 <= len(value) <= 100:\n raise ValueError('Invalid input. Word length must be between 1 and 100 characters.')\n return value\n\n\nif __name__ == '__main__':\n dd_list = defaultdict(list)\n\n try:\n m, n = map(int, input().strip().split())\n if not (1 <= m <= 10000) or not (1 <= n <= 100):\n raise ValueError(\"Both 'm' and 'n' must be in the range [1, 10000] and [1, 100], respectively.\")\n except ValueError:\n raise ValueError(\"Invalid input. Please provide two integers separated by a space.\")\n\n for _ in range(m):\n dd_list['A'].append(get_valid_input())\n for _ in range(n):\n dd_list['B'].append(get_valid_input())\n\n output_list = []\n\n for i in dd_list['B']:\n index_list = [index + 1 for index, value in enumerate(dd_list['A']) if value == i]\n output_list.append(index_list)\n\n # for i in dd_list['B']:\n # # index_list = []\n # # for index, value in enumerate(dd_list['A']):\n # # if value == i:\n # # index_list.append(index + 1)\n # # output_list.append(index_list)\n\n print_nested_list(output_list)","repo_name":"VytautasPliadis/HackerRank","sub_path":"defaultdict.py","file_name":"defaultdict.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"17239605613","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport sys\nfrom sys import argv\nimport getopt\nimport chardet\n\ntry:\n myargs = getopt.getopt(argv[1:], '', ['file='])\nexcept getopt.GetoptError as err:\n print(str(err))\n sys.exit(2)\n\nfname = ''\nfor k, v in myargs[0]:\n if k == '--file':\n fname = v\n break\n\ntry:\n f = open(fname)\nexcept IOError as err:\n print(str(err))\n sys.exit(2)\n\ndata = f.read()\nec_info = chardet.detect(data)\n\ntry:\n cur_encode = ec_info['encoding']\nexcept Exception as err:\n print(str(err))\n sys.exit(2)\n\ndata_decode = data.decode(cur_encode)\nxx = data_decode.encode(\"utf-8\")\ntname = fname + '.utf8'\nfh = open(tname, \"w\")\nfh.write(xx)\nfh.close()\n\nprint(\"Succeed! The new file is: \" + tname)\n","repo_name":"sunqunyan/Convert2Utf8","sub_path":"convert2Utf8.py","file_name":"convert2Utf8.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"21643829735","text":"import matplotlib.pyplot as plt\nfrom math import pi\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar\n\nfrom view.components.charts.chart_abstract import ChartAbstract\n\nclass ChartHistogram(ChartAbstract):\n \n def __init__(self,parent):\n self.fig,self.ax = plt.subplots(1,1,constrained_layout=True)\n super().__init__(self.fig,self.ax,parent)\n \n def makeChart(self,_data):\n self.data=_data\n \n bars = list()\n heights = list()\n \n if 'heights' in _data.keys():\n heights = _data['heights']\n \n if 'bars' in _data.keys():\n bars = _data['bars']\n \n if len(bars) ==0 and len(heights) >0:\n for i in range(0,len(heights)):\n bars.append(i)\n \n plt.bar(bars, height=heights)\n \n\n if 'name' in _data.keys():\n self.ax.set_title(_data['name'],fontsize=10,color='#000000')\n \n xlabel = ''\n ylabel = ''\n if 'title_X' in _data.keys():\n xlabel=_data['title_X']\n self.ax.set_xlabel(xlabel,fontsize=8,color='#000000')\n if 'title_Y' in _data.keys():\n ylabel=_data['title_Y']\n self.ax.set_ylabel(ylabel,fontsize=8,color='#000000')\n \n if 'xticks' in _data.keys():\n self.ax.set_xticks(_data['xticks']) \n \n if 'xticklabels' in _data.keys():\n self.ax.set_xticklabels(_data['xticklabels'])\n \n \n \n \n \n \n \n \n\n \n ","repo_name":"vasha54/apm","sub_path":"view/components/charts/chart_histogram.py","file_name":"chart_histogram.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"34243574615","text":"\"\"\" Class for Trainwave \"\"\"\n\nimport numpy as np\n\nfrom obspy import UTCDateTime\n\nfrom obspy.signal.trigger import trigger_onset\nfrom scipy.signal import hilbert\n\nfrom locevdet.stations import Station\n\nfrom locevdet.waveform_processing import trim_trace\nfrom locevdet.utils import rolling_max, kurtosis_norm, starttimes_trigger_by_kurtosis\nfrom locevdet.descriptors import envelope_fct, snr_calculation_fct\n\nclass Trainwave():\n\n def __init__(self, trace, station:Station, start_global, **kwargs):\n self.trace = trace\n self.station = station\n\n self.start_global = UTCDateTime(start_global)\n self.nsta_time = kwargs.get('nsta_time', 1)\n self.nlta_time = kwargs.get('nlta_time', 30)\n\n self.pre_trigger = kwargs.get('pre_trigger', 10)\n self.post_trigger = kwargs.get('pre_trigger', 50)\n self.trace_trimmed = trim_trace(self.trace.copy(), self.start_global,\n self.pre_trigger, self.post_trigger)\n\n self.freqmin_interest = kwargs.get('freqmin_interest', 2)\n self.freqmax_interest = kwargs.get('freqmax_interest', 10)\n self.trace_filtered = self.trace_trimmed.copy().filter('bandpass',\n freqmin=self.freqmin_interest, freqmax=self.freqmax_interest)\n\n # Kurtosis\n self.kurtosis_params = kwargs.get('kurtosis_params')\n self.kurtosis_data = kwargs.get('kurtosis_data')\n\n # if start picked manually\n self.start_specific_manual = kwargs.get('start_specific_manually')\n\n # Envelope, SNR and trainwave's end detection\n self.snr = kwargs.get('snr')\n self.noise_level = kwargs.get('noise_level')\n self.all_endtimes_delta = kwargs.get('all_endtimes_delta')\n self.end_specific = kwargs.get('end_specific')\n self.form_ratio = kwargs.get('form_ratio')\n self.duration = kwargs.get('duration')\n self.picks = kwargs.get('picks')\n\n # Matlab other variables\n self.matlab_data = kwargs.get('matlab_data')\n\n def kurtosis(self, window, threshold_on, threshold_off=0.25):\n \"\"\" Calculate the kurtosis matrix, the start of the event (and all others potential starts)\n for a given trainwave.\n \n Args:\n window : slidding time window in seconds for the kurtosis\n threshold_on : threshold on to detect the start of the event by kurtosis\n threshold_off : threshold off to detect the end of the event by kurtosis\n\n Returns:\n The dictionary kurtosis_data containing:\n The array of the kurtosis for the given trace (calculated by the function kurt_norm)\n All potential starts of the event from kurtosis matrix in seconds from the \n trace's start\n The start of the event 'start_specific' in UTCDateTime, which is the closest of \n start_global.\n \"\"\"\n kurt_norm = kurtosis_norm(self.trace_filtered, window)\n kurtosis_data = None # To reset\n if len(kurt_norm) != 0:\n all_starttimes = starttimes_trigger_by_kurtosis(kurt_norm, threshold_on, threshold_off)\n all_starttimes_delta = all_starttimes * self.trace_filtered.stats.delta\n all_starttimes_from_start = [\n self.trace_filtered.stats.starttime + starts\n for starts in all_starttimes_delta\n ]\n\n specific_start_utc = min(\n all_starttimes_from_start,\n key=lambda x:abs(x-self.start_global)\n )\n\n kurtosis_data = {\n 'start_specific': specific_start_utc,\n 'all_starttimes_delta': all_starttimes_delta,\n 'kurtosis_matrix': kurt_norm\n }\n\n self.kurtosis_data = kurtosis_data\n return kurtosis_data\n\n def envelope(self, trace_type:str='trimmed_filtered', rolling_max_window:float=0):\n \"\"\" Calculated the trainwave's envelope for a given type of trace (trace_type)\n \n Args:\n trace_type : Type of trace which envelope is calculated\n either \"trimmed_filtered\" or \"trace_filtered\"\n rolling_max_window : slidding window for the calculation of the trace's envelope \n (in seconds)\n \n Returns:\n The array of the trainwave's envelope\n \"\"\"\n if trace_type == 'trimmed_filtered':\n trace_filtered = self.trace_filtered\n envelope = envelope_fct(\\\n trace_type, rolling_max_window=rolling_max_window, trace_filtered=trace_filtered)\n\n elif trace_type == 'trace_filtered':\n trace = self.trace.copy()\n freqmin = self.freqmin_interest\n freqmax = self.freqmax_interest\n\n envelope = envelope_fct(\\\n trace_type, rolling_max_window=rolling_max_window,\n trace=trace, freqmin=freqmin, freqmax=freqmax) \n\n return envelope\n \n def snr_calculation(self, rolling_max_window:float=100):\n \"\"\" TODO \"\"\"\n envelope_trim_filt = self.envelope(\\\n trace_type='trimmed_filtered', \n rolling_max_window=rolling_max_window)\n envelope_filt = self.envelope(\\\n trace_type='trace_filtered', \n rolling_max_window=rolling_max_window)\n\n noise_level, snr = snr_calculation_fct(\n envelope_trim_filt=envelope_trim_filt, envelope_filt=envelope_filt)\n\n self.noise_level = noise_level\n self.snr = snr\n\n def endtime_detection(self, \n rolling_max_window:float=0, \n time_restricted:float=5,\n time_inspect_startglobal:float=1,\n thr_snr_purcent:float=1.1):\n \"\"\" TODO \"\"\"\n envelope = self.envelope(trace_type='trimmed_filtered', rolling_max_window=rolling_max_window)\n\n delta = self.trace_filtered.stats.delta\n index_start_global = int((self.start_global - self.trace_filtered.stats.starttime) / delta)\n index_inspect_signal = int(time_inspect_startglobal / delta)\n thrsedhold_on = np.quantile(envelope[index_start_global - index_inspect_signal : index_start_global + index_inspect_signal], 0.9)\n threshold_snr_end = thr_snr_purcent * self.noise_level\n print(f\"thrsedhold_on : {thrsedhold_on} and threshold_snr_end : {threshold_snr_end}\")\n try:\n triggersnr_samples_detection = trigger_onset(envelope, thrsedhold_on, threshold_snr_end)\n except IndexError:\n return None, None\n print(\"triggersnr_samples_detection :\", triggersnr_samples_detection)\n\n if len(triggersnr_samples_detection) != 0:\n all_endtimes = triggersnr_samples_detection[:,1]\n all_endtimes_delta = all_endtimes * self.trace_filtered.stats.delta\n if self.kurtosis_data is not None:\n all_endtimes_utc = [\n self.trace_filtered.stats.starttime + ends\n for ends in all_endtimes_delta\n if self.trace_filtered.stats.starttime + ends > self.start_global + time_restricted and \\\n self.trace_filtered.stats.starttime + ends > self.kurtosis_data['start_specific'] + time_restricted\n ]\n else:\n all_endtimes_utc = [\n self.trace_filtered.stats.starttime + ends\n for ends in all_endtimes_delta\n if self.trace_filtered.stats.starttime + ends > self.start_global + time_restricted\n ]\n self.all_endtimes_delta = all_endtimes_delta\n\n if len(all_endtimes_utc) != 0:\n end_specific = UTCDateTime(all_endtimes_utc[0])\n self.end_specific = end_specific\n else :\n end_specific = None\n return all_endtimes_utc, end_specific\n \n def form_ratio_and_duration(self, rolling_max_window):\n \"\"\" Calculate disymetry (form_ratio) and the duration descriptors of an event per trainwave.\n \n Args:\n rolling_max_window : slidding window for the calculation of the trace's envelope \n (in seconds)\n \n Returns:\n The disymetry and the duration descriptors associated with the given trainwave\n \"\"\"\n if self.end_specific is None :\n _, end_specific = self.endtime_detection(rolling_max_window=rolling_max_window)\n self.end_specific = end_specific\n \n if self.end_specific is not None: \n envelope = self.envelope(trace_type='trimmed_filtered', rolling_max_window=rolling_max_window)\n max_level_envelope = np.max(envelope)\n max_level_index = np.where(envelope == max_level_envelope)\n times = self.trace_trimmed.times()\n max_level_time = []\n\n for index in max_level_index[0]:\n utc_max_level_time = UTCDateTime(self.trace_filtered.stats.starttime + times[index])\n if utc_max_level_time > self.start_global \\\n and utc_max_level_time < self.end_specific :\n max_level_time = [utc_max_level_time]\n\n if len(max_level_time) != 0:\n duration = self.end_specific - self.start_global\n start_to_max = self.end_specific - max_level_time[0]\n self.duration = duration\n self.form_ratio = start_to_max / duration\n return start_to_max / duration, duration\n\n def number_picks(self, rolling_max_window):\n \"\"\" TODO \"\"\"\n envelope_trace = self.envelope(trace_type='trace_filtered', rolling_max_window=rolling_max_window)\n\n max_level = np.max(envelope_trace)\n threshold = max_level * 0.9\n \n number_picks = trigger_onset(envelope_trace, threshold, threshold)\n\n self.picks = len(number_picks[:,0])\n\n def __repr__(self):\n return f\"Trainwave{self.trace}\"\n \n","repo_name":"Camillever/localized-events-detection","sub_path":"locevdet/trainwave.py","file_name":"trainwave.py","file_ext":"py","file_size_in_byte":9935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"11226643235","text":"# 스타트와 링크\nimport sys\nfrom itertools import combinations, permutations\nN = int(sys.stdin.readline())\narray = [list(map(int,sys.stdin.readline().split())) for _ in range(N)]\ncomb = list(combinations(range(N),N//2))\nn_comb = len(comb) # 전체 조합 개수\ndiff = []\nfor i in range(n_comb//2): # 전체 조합 중 절반 > 나머지 절반은 자동으로 구해지므로\n j = n_comb - 1 - i # 대응되는 상대팀 조합\n start = 0\n link = 0\n for a,b in permutations(comb[i],2):\n start += array[a][b]\n for c,d in permutations(comb[j],2):\n link += array[c][d]\n diff.append(abs(start-link))\n\nprint(min(diff))\n ","repo_name":"ddangchani/Algorithm","sub_path":"solved.ac/Silver/Silver 2/14889.py","file_name":"14889.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"16975802792","text":"import numpy as np\r\nimport numpy.random as nr\r\nimport numpy.linalg as nl\r\nimport matplotlib.pyplot as plt\r\nimport MIMO\r\n\r\n# simulation parameters\r\nt = 32; r = 32; \r\nnumRF = 6; \r\nG = 64; \r\nL = 8; \r\nNs = 6; \r\nITER = 100; \r\n\r\n# Initializations\r\nSNRdB = np.arange(-5,6,1); \r\nC_HYB = np.zeros(len(SNRdB));\r\nC_MIMO = np.zeros(len(SNRdB)); \r\n\r\n# G-quantized Txarray response matrix\r\nA_T = MIMO.ArrayDictionary(G,t);\r\nA_R = MIMO.ArrayDictionary(G,r);\r\n\r\nfor ix in range(ITER): \r\n print(ix);\r\n \r\n # Channel generation\r\n tax = np.random.choice(G, L, replace=False);\r\n rax = np.random.choice(G, L, replace=False);\r\n chGain = 1/np.sqrt(2)*(nr.normal(0,1,L)+1j*nr.normal(0,1,L));\r\n A_T_genie = A_T[:, tax];\r\n A_R_genie = A_R[:, rax];\r\n H = np.sqrt(t*r/L)*nl.multi_dot([A_R_genie,np.diag(chGain),MIMO.H(A_T_genie)]);\r\n\r\n U, S, VH = nl.svd(H, full_matrices=True)\r\n \r\n V = MIMO.H(VH)\r\n Fopt = V[:,0:Ns];\r\n FBB, FRF = MIMO.SOMP(Fopt, A_T, np.identity(t), numRF);\r\n FBB_NORM = FBB*np.sqrt(Ns)/nl.norm(np.matmul(FRF,FBB));\r\n for cx in range(len(SNRdB)):\r\n npow = 10**(-SNRdB[cx]/10);\r\n mmseINV = nl.inv(MIMO.AHA(np.matmul(H,Fopt)) + npow*Ns*np.identity(Ns));\r\n Wmmse_opt = nl.multi_dot([H, Fopt, mmseINV]);\r\n C_MIMO[cx] = C_MIMO[cx] + \\\r\n MIMO.mimo_capacity(nl.multi_dot([MIMO.H(Wmmse_opt),H,Fopt]), 1/Ns*np.identity(Ns), npow*MIMO.AHA(Wmmse_opt));\r\n HFp = nl.multi_dot([H, FRF, FBB_NORM]);\r\n Ryy = 1/Ns*MIMO.AAH(HFp) + npow*np.identity(r);\r\n Wmmse_Hyb = np.matmul(HFp,nl.inv(MIMO.AHA(HFp) + npow*Ns*np.identity(Ns)));\r\n WBB, WRF = MIMO.SOMP(Wmmse_Hyb, A_R, Ryy, numRF);\r\n C_HYB[cx] = C_HYB[cx] + \\\r\n MIMO.mimo_capacity(nl.multi_dot([MIMO.H(WBB),MIMO.H(WRF),H,FRF,FBB_NORM]), 1/Ns*np.identity(Ns), npow*MIMO.AHA(np.matmul(WRF,WBB)));\r\n \r\n\r\nC_MIMO = C_MIMO/ITER; C_HYB = C_HYB/ITER;\r\nplt.plot(SNRdB, C_MIMO,'r-s');\r\nplt.plot(SNRdB, C_HYB,'b^-.');\r\nplt.grid(1,which='both')\r\nplt.legend([\"Ideal Digital\", \"Hybrid Precoder\"], loc =\"lower right\");\r\nplt.suptitle('Capacity vs SNR for mmWave MIMO')\r\nplt.ylabel('Capacity (b/s/Hz)')\r\nplt.xlabel('SNRdB') \r\n","repo_name":"vivgit9/Self_project_2_winter_school","sub_path":"Project_17_mmWave_MIMO_Precoder_Combiner_Design_Shell.py","file_name":"Project_17_mmWave_MIMO_Precoder_Combiner_Design_Shell.py","file_ext":"py","file_size_in_byte":2170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"20550680883","text":"\"\"\"Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number.\"\"\"\n\nfrom typing import List\n\n\ndef create_phone_number(n: List):\n num_list = [str(num) for num in n]\n part_one = \"\".join(num_list[:3])\n part_two = \"\".join(num_list[3:6])\n part_three = \"\".join(num_list[6:])\n print(part_one)\n return f\"({part_one}) {part_two}-{part_three}\"\n\n\nprint(create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]))\n","repo_name":"ShadFyt/code_wars","sub_path":"create_phone_number.py","file_name":"create_phone_number.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"11010856914","text":"from aerosandbox import *\nimport dill as pickle\n\nif __name__ == '__main__': # If you're a Windows user, you must run within a main block if you want to use any parallel functions.\n\n ########## First, define the airfoils that you want to use. ##########\n # For a lifting line analysis like CasLL1, you need differentiable 2D sectional data for the airfoils.\n # There are two ways you can do this:\n # 1. You can automatically fit functions to automated XFoil runs.\n # 2. You can provide explicit (possibly nonlinear) functions for CL, CDp, and Cm for each airfoil.\n # In this example, we're using an Eppler 216 airfoil for the wing and NACA0008 airfoils everywhere else.\n # I'll show you what both methods to get data look like!\n\n ### Method 1: XFoil Fitting\n # Here, we run XFoil (by default in parallel) and make automated fits to this data.\n\n # I've wrapped these in a simple caching script, since the XFoil runs are slow!\n try:\n with open(\"e216.pkl\", \"rb\") as f:\n e216 = pickle.load(f)\n except:\n e216 = Airfoil(\"e216\") # You can use the string of any airfoil from the UIUC database here!\n e216.populate_sectional_functions_from_xfoil_fits()\n with open(\"e216.pkl\", \"wb+\") as f:\n pickle.dump(e216, f)\n\n try:\n with open(\"naca0008.pkl\", \"rb\") as f:\n naca0008 = pickle.load(f)\n except:\n naca0008 = Airfoil(\"naca0008\") # You can also give NACA airfoils!\n # You can also load from a .dat file (see Airfoil constructor docstring for syntax)!\n naca0008.populate_sectional_functions_from_xfoil_fits()\n with open(\"naca0008.pkl\", \"wb+\") as f:\n pickle.dump(naca0008, f)\n\n ### Method 2: Explicit fits (look here in the library to see what these look like)\n # These will be generally faster to run, and probably more accurate. They can also tell you things about\n # control surface deflections or transonic performance (so long as you make fits accordingly). However,\n # right now, they require a good bit of manual labor to individually fit and make.\n from aerosandbox.library.airfoils import e216, naca0008\n\n ########## Now, we're ready to start putting together our 3D CasLL1 run! ##########\n\n opti = cas.Opti() # Initialize an analysis/optimization environment\n\n ### Define the 3D geometry you want to analyze/optimize.\n # Here, all distances are in meters and all angles are in degrees.\n airplane = Airplane(\n name=\"Peter's Glider\",\n x_ref=0, # CG location\n y_ref=0, # CG location\n z_ref=0, # CG location\n wings=[\n Wing(\n name=\"Main Wing\",\n x_le=0, # Coordinates of the wing's leading edge\n y_le=0, # Coordinates of the wing's leading edge\n z_le=0, # Coordinates of the wing's leading edge\n symmetric=True, # Should this wing be mirrored across the XZ plane?\n xsecs=[ # The wing's cross (\"X\") sections\n WingXSec( # Root\n x_le=0, # Coordinates of the XSec's leading edge, relative to the wing's leading edge.\n y_le=0, # Coordinates of the XSec's leading edge, relative to the wing's leading edge.\n z_le=0, # Coordinates of the XSec's leading edge, relative to the wing's leading edge.\n chord=0.18,\n twist_angle=2, # degrees\n airfoil=e216, # Airfoils are blended between a given XSec and the next one.\n control_surface_type='symmetric',\n # Flap (ctrl. surfs. applied between this XSec and the next one.)\n control_surface_deflection=0, # degrees\n ),\n WingXSec( # Mid\n x_le=0.01,\n y_le=0.5,\n z_le=0,\n chord=0.16,\n twist_angle=0,\n airfoil=e216,\n control_surface_type='asymmetric', # Aileron\n control_surface_deflection=0,\n ),\n WingXSec( # Tip\n x_le=0.08,\n y_le=1,\n z_le=0.1,\n chord=0.08,\n twist_angle=-2,\n airfoil=e216,\n ),\n ]\n ),\n Wing(\n name=\"Horizontal Stabilizer\",\n x_le=0.6,\n y_le=0,\n z_le=0.1,\n symmetric=True,\n xsecs=[\n WingXSec( # root\n x_le=0,\n y_le=0,\n z_le=0,\n chord=0.1,\n twist_angle=-10,\n airfoil=naca0008,\n control_surface_type='symmetric', # Elevator\n control_surface_deflection=0,\n ),\n WingXSec( # tip\n x_le=0.02,\n y_le=0.17,\n z_le=0,\n chord=0.08,\n twist_angle=-10,\n airfoil=naca0008\n )\n ]\n ),\n Wing(\n name=\"Vertical Stabilizer\",\n x_le=0.6,\n y_le=0,\n z_le=0.15,\n symmetric=False,\n xsecs=[\n WingXSec(\n x_le=0,\n y_le=0,\n z_le=0,\n chord=0.1,\n twist_angle=0,\n airfoil=naca0008,\n control_surface_type='symmetric', # Rudder\n control_surface_deflection=0,\n ),\n WingXSec(\n x_le=0.04,\n y_le=0,\n z_le=0.15,\n chord=0.06,\n twist_angle=0,\n airfoil=naca0008\n )\n ]\n )\n ]\n )\n # airplane.draw() # You can use this to quickly preview your geometry!\n airplane.set_spanwise_paneling_everywhere(20) # Set the resolution of your analysis\n ap = Casll1( # Set up the AeroProblem\n airplane=airplane,\n op_point=OperatingPoint(\n density=1.225, # kg/m^3\n viscosity=1.81e-5, # kg/m-s\n velocity=10, # m/s\n mach=0, # Freestream mach number\n alpha=5, # In degrees\n beta=0, # In degrees\n p=0, # About the body x-axis, in rad/sec\n q=0, # About the body y-axis, in rad/sec\n r=0, # About the body z-axis, in rad/sec\n ),\n opti=opti # Pass it an optimization environment to work in\n )\n\n # Solver options\n p_opts = {}\n s_opts = {}\n # s_opts[\"mu_strategy\"] = \"adaptive\"\n opti.solver('ipopt', p_opts, s_opts)\n\n ### Solve\n try:\n sol = opti.solve()\n except RuntimeError:\n sol = opti.debug\n raise Exception(\"An error occurred!\")\n\n ### Postprocess\n\n # Create solved object\n ap_sol = copy.deepcopy(ap)\n ap_sol.substitute_solution(sol)\n\n ap_sol.draw() # Generates\n\n print(\"CL:\", ap_sol.CL)\n print(\"CD:\", ap_sol.CD)\n print(\"CY:\", ap_sol.CY)\n print(\"Cl:\", ap_sol.Cl)\n print(\"Cm:\", ap_sol.Cm)\n print(\"Cn:\", ap_sol.Cn)\n\n # Answer from XFLR5 Viscous VLM2\n # CL = 1.112\n # CD = 0.057\n # CL/CD = 19.499\n # Note that XFLR5 will overpredict lift for this case compared to reality, since a VLM method\n # (which is fundamentally linear) doesn't take into account any kind of viscous decambering\n # at high CL, and XFLR5 makes no adjustments for this. This will also mean that XFLR5 will\n # overpredict drag (in particular induced drag), since the circulation is overpredicted.\n","repo_name":"orgTestCodacy11KRepos110MB/repo-9549-AeroSandbox","sub_path":"tutorial/Old Tutorials, to be refactored - Ignore for Now/conventional/casll1_conventional_analysis_point.py","file_name":"casll1_conventional_analysis_point.py","file_ext":"py","file_size_in_byte":8158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"28491819224","text":"if __name__ == '__main__':\n import copy\n import torch\n from src.models.modnet import MODNet\n from src.trainer import soc_adaptation_iter\n from torch.utils.data import DataLoader\n from setting import BS, LR, EPOCHS, SEMANTIC_SCALE, DETAIL_SCALE, MATTE_SCALE, SAVE_EPOCH_STEP\n from matting_dataset import MattingDataset, Rescale, \\\n ToTensor, Normalize, ToTrainArray, \\\n ConvertImageDtype, GenTrimap\n from torchvision import transforms\n\n\n\n modnet = torch.nn.DataParallel(MODNet())\n ckp_pth = './pretrained/modnet_photographic_portrait_matting.ckpt'\n if torch.cuda.is_available():\n modnet = modnet.cuda()\n weights = torch.load(ckp_pth)\n else:\n weights = torch.load(ckp_pth, map_location=torch.device('gpu'))\n modnet.load_state_dict(weights) # NOTE: please finish this function\n\n transform = transforms.Compose([\n Rescale(512),\n GenTrimap(),\n ToTensor(),\n ConvertImageDtype(),\n Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ToTrainArray()\n ])\n mattingDataset = MattingDataset(transform=transform)\n\n optimizer = torch.optim.Adam(modnet.parameters(), lr=LR, betas=(0.9, 0.99))\n # lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=int(0.25 * EPOCHS), gamma=0.1)\n dataloader = DataLoader(mattingDataset,\n batch_size=BS,\n shuffle=False) # NOTE: please finish this function\n\n for epoch in range(0, EPOCHS):\n print(f'epoch: {epoch}/{EPOCHS - 1}')\n backup_modnet = copy.deepcopy(modnet)\n for idx, (image) in enumerate(dataloader):\n soc_semantic_loss, soc_detail_loss = soc_adaptation_iter(modnet, backup_modnet, optimizer, image)\n print(f'{(idx + 1) * BS}/{len(mattingDataset)} --- '\n f'soc_semantic_loss: {soc_semantic_loss:f}, soc_detail_loss: {soc_detail_loss:f}\\r',\n end='')\n # lr_scheduler.step()\n torch.save(modnet.state_dict(), f'pretrained/modnet_custom_portrait_matting_last_epoch_weight.ckpt')","repo_name":"subeeeee1015/ModNet_Personal","sub_path":"trainer_1.py","file_name":"trainer_1.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"17564087048","text":"# 这个是服务器\n# mysql版本是 8+\n\nimport socket\nimport mysql.connector\nimport json\n\n# 连接数据库\ntry:\n db = mysql.connector.connect(\n host = \"localhost\",\n user = \"root\",\n passwd = \"123456\",\n auth_plugin = 'mysql_native_password',\n database = \"Myest1\"\n )\nexcept:\n print(\"数据库连接有误\")\n\n# mysql游标\nmyCursor = db.cursor()\n\ntry:\n # 有已经建立的table_one表时:\n myCursor.execute(\"SELECT * FROM table_one\")\n print(myCursor.fetchall())\n\nexcept:\n # 没有建立table_one表时:\n print(\"没有table_one表,以下自动新建table_one表: \")\n # 表的结构有 id, name, age, skill, time(填写信息的时间)\n myCursor.execute(\"CREATE TABLE table_one (id INT AUTO_INCREMENT PRIMARY KEY, \"\n \"name varchar(255), age int, skill varchar(255), time varchar(255))\")\n print(\"数据表已建立完毕。\")\n myCursor.execute(\"SELECT * FROM table_one\")\n print(myCursor.fetchall())\n print(\"\".rjust(18, \"*\") + \"\\n\")\nfinally:\n # 建立socket对象\n serverSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n serverHost = socket.gethostname()\n serverPort = 2333\n serverSock.bind((serverHost, serverPort)) # 绑定主机名和端口\n\n # 监听数设置5\n serverSock.listen(5)\n\n while True:\n # 建立客户端连接\n serverConn, addr = serverSock.accept()\n\n # 当客户端第一次连接服务器时,向该客户端发送连接成功的信息.\n serverConn.send(\"您已成功连接服务器 :)\".encode('utf-8'))\n\n # 接收从客户端发来的信息\n msg = serverConn.recv(1024)\n if msg.decode('utf-8') == \"客户端已成功连接\": # 当客户端第一次连接时\n print(msg.decode('utf-8'))\n\n else: # 当发送过来的是客户端中的用户信息时\n msg = msg.decode('utf-8')\n msg = json.loads(msg)\n\n # 从客户端接收过来的用户数据存储至数据库\n myCursor.execute(\"INSERT INTO table_one (name, age, skill, time) VALUES (%s, %s, %s, %s)\",\n (msg['name'], msg['age'], msg['skill'], msg['curTime']))\n # 因为更新了数据库数据, 因此得调用commit\n db.commit()\n print(\"已成功导入至数据库!\")\n\n myCursor.execute(\"SELECT * FROM table_one\") # 查询\n print(\"更新后的数据库信息:\")\n print(myCursor.fetchall()) # 显示所有数据表中的数据\n\n # 关闭socket连接,释放资源\n serverConn.close()\n\n # 关闭数据库,释放资源\n myCursor.close()\n db.close()\n","repo_name":"AlanJin01/UserInfoSystemDemoWithMySQL","sub_path":"InsertUserInfoSystem_sql/serverside.py","file_name":"serverside.py","file_ext":"py","file_size_in_byte":2696,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"41"} +{"seq_id":"43022160785","text":"import cv2\r\nimport mediapipe as mp\r\nimport time\r\nfrom pose_media import mediapipe_pose\r\nimport csv\r\nimport numpy as np\r\nfrom coordinate import Coor\r\nimport os\r\nfrom keras.models import load_model\r\nfrom keras import Sequential\r\nfrom train_dataset import pose_landmark_dataset\r\nimport random\r\n\r\n# mediapipe 불러오기\r\nmp_holistic = mp.solutions.holistic \r\nmp_drawing = mp.solutions.drawing_utils\r\nmedia = mediapipe_pose()\r\ncoor = Coor()\r\n\r\ncap = cv2.VideoCapture(0)\r\n\r\nmodel_path = os.path.join('model_and_dataset', 'models2', 'model.h5')\r\n\r\nseq = []\r\naction_seq = []\r\nseq_length = 30\r\n\r\nactions = np.array(['stand', 'hello', 'happy', 'iloveyou'])\r\nmodel = load_model(model_path, compile=False)\r\n\r\nwith mp_holistic.Holistic(min_detection_confidence=0.5, min_tracking_confidence=0.5) as holistic:\r\n while cap.isOpened():\r\n ret, frame = cap.read()\r\n\r\n img_height, img_width, _ = frame.shape\r\n img = cv2.resize(frame, (int(img_width * (400 / img_height)), 400))\r\n\r\n image, data = pose_landmark_dataset(frame, actions, holistic=holistic)\r\n \r\n try:\r\n if data == None:\r\n continue\r\n except:\r\n pass\r\n \r\n seq.append(data)\r\n \r\n if len(seq) < seq_length:\r\n continue\r\n \r\n \r\n input_data = np.expand_dims(np.array(seq[-30:]), axis=0)\r\n y_pred = model.predict(input_data)\r\n y_pred = y_pred.squeeze(0)\r\n i_pred = int(np.argmax(y_pred))\r\n\r\n conf = y_pred[i_pred] \r\n \r\n # if conf < 0.8:\r\n # continue\r\n \r\n action = actions[i_pred]\r\n action_seq.append(action)\r\n\r\n if len(action_seq) < 3:\r\n continue\r\n\r\n this_action = '?'\r\n if action_seq[-1] == action_seq[-2] == action_seq[-3]:\r\n this_action = action\r\n \r\n if conf > 0.9:\r\n print(conf)\r\n cv2.putText(image, f'{this_action.upper()}', org=(random.randint(50, 300), random.randint(50, 400)), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=1, color=(255, 0, 0), thickness=2)\r\n\r\n\r\n cv2.imshow('OpenCV', image)\r\n\r\n if cv2.waitKey(1) == ord('q'):\r\n break\r\n\r\n cap.release()\r\n cv2.destroyAllWindows()","repo_name":"Leegyu66/2023_MDP","sub_path":"code/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"41748884355","text":"#!/usr/bin/python3\n\"A class that defines a square\"\n\n\nclass Square:\n \"the square class, containing size and instantiation\"\n def __init__(self, size=0):\n if isinstance(size, int) is not True:\n raise TypeError(\"size must be an integer\")\n if size < 0:\n raise ValueError(\"size must be >= 0\")\n self.__size = size\n","repo_name":"AnActualBanana/holbertonschool-higher_level_programming","sub_path":"0x04-python-classes/1-square.py","file_name":"1-square.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"73989385403","text":"import csv\nimport json\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib.auth.decorators import permission_required\nfrom django.contrib import messages\nfrom django.http import JsonResponse, HttpResponse, StreamingHttpResponse\n\nfrom rest_framework import mixins, viewsets\nfrom rest_framework.response import Response\nfrom rest_framework.renderers import JSONRenderer\n\nfrom taiga import permissions\nfrom .models import Timelog\nfrom .serializers import TimelogSerializer\nfrom taiga.projects.models import Project\nfrom .forms import TimelogForm\nfrom taiga.projects.issues.models import Issue\nfrom taiga.users.models import User\nfrom taiga.utils import valid_id, user_project_perms, project_permission_required, send_err_msg\n\n\n# --- utils for view_timelogs --- #\ndef get_id(param, kwargs, req):\n \"\"\"\n Get id of project, issue etc. by param from query string or get query\n \"\"\"\n try:\n id = kwargs[param]\n except KeyError:\n id = req.GET.get(param)\n if id:\n return int(id)\n\n\ndef get_project(project_id):\n \"\"\"\n Get project by project id\n \"\"\"\n return Project.objects.get(pk=project_id)\n\n\ndef get_project_issues(project_id):\n \"\"\"\n Get issues of project by project id\n \"\"\"\n return Issue.objects.filter(project_id=project_id)\n\n\ndef get_distinct_users(timelogs):\n \"\"\"\n Get distinct users of the timelog list\n \"\"\"\n return User.objects.filter(pk__in=[timelog.user for timelog in timelogs.distinct('user')])\n\n\ndef get_timelogs(timelogs, project_id=None, issue_id=None, user_id=None):\n \"\"\"\n Get timelogs of project or issue or user by its id\n \"\"\"\n if project_id:\n return timelogs.filter(issue__project__id=project_id)\n if issue_id:\n return timelogs.filter(issue__id=issue_id)\n if user_id:\n return timelogs.filter(user__id=user_id)\n\n\n# ---------------------------------- #\n# --------- View timelogs ---------- #\ndef view_timelogs(request, **kwargs):\n \"\"\"\n Display timelogs\n \"\"\"\n global project, issues, users, user_perms\n template = 'timelogs/timelogs_list.html'\n csv_filename = 'timelogs.csv'\n json_filename = 'timelogs.json'\n title = 'Timelogs'\n\n # initial timelogs set\n timelogs = Timelog.objects.all()\n\n # project_id\n project_id = get_id('project_id', kwargs, request)\n if project_id:\n project = get_project(project_id)\n title += ' of «' + project.name + ' »'\n # get timelogs of the project\n timelogs = get_timelogs(timelogs, project_id=project_id)\n # issues of the project only\n issues = get_project_issues(project_id)\n # users who tracked at the project issues only\n users = get_distinct_users(timelogs)\n # authorized user perms at the project\n user_perms = user_project_perms(request.user.id, project_id)\n\n # filtered issue_id\n issue_id = get_id('issue_id', kwargs, request)\n if issue_id:\n # get project if called from issue details page (without project_id)\n if not project_id:\n project = Project.objects.get(pk=Issue.objects.get(pk=issue_id).project_id)\n issues = get_project_issues(project.id)\n user_perms = user_project_perms(request.user.id, project.id)\n # get issue's timelogs\n timelogs = get_timelogs(timelogs, issue_id=issue_id)\n # users who tracked at the issue only\n users = get_distinct_users(timelogs)\n\n # filtered user_id\n user_id = get_id('user_id', kwargs, request)\n if user_id:\n # get user's timelogs\n timelogs = get_timelogs(timelogs, user_id=user_id)\n # issues which the user tracked\n issues = issues.filter(\n pk__in=[\n timelog.issue.id for timelog in Timelog.objects.filter(user_id=user_id).distinct('issue')\n ])\n\n # extra filters\n date_from = request.GET.get('date_from')\n date_till = request.GET.get('date_till')\n order = request.GET.get('order')\n\n if date_from:\n timelogs = timelogs.filter(date__gte=date_from)\n if date_till:\n timelogs = timelogs.filter(date__lte=date_till)\n if order:\n timelogs = timelogs.order_by(order)\n\n # total duration of filtered timelogs\n total_duration = sum([v['duration'] for v in list(timelogs.values())])\n\n if request.GET.get('format') == 'json':\n headers = ('issue', 'user', 'date', 'duration')\n data = []\n for log in timelogs:\n row = {}\n for field in headers:\n row[field] = str(getattr(log, field))\n data.append(row)\n\n # jsondata = JsonResponse(data, safe=False)\n jsondata = json.dumps(data, sort_keys=True, indent=2)\n response = HttpResponse(jsondata, content_type='text/json')\n response['Content-Disposition'] = 'attachment; filename={}'.format(json_filename)\n return response\n\n if request.GET.get('format') == 'csv':\n # some_streaming_csv_view(request, csvfilename)\n data = export(timelogs, csv_filename, fields = ['issue', 'user', 'date', 'duration'])\n return HttpResponse(data)\n\n args = {\n 'title': title,\n 'timelog_form': TimelogForm,\n 'project': project,\n 'issues': issues,\n 'issue_id': issue_id,\n 'users': users,\n 'user_id': user_id,\n 'user_perms': user_perms,\n 'date_from': date_from,\n 'date_till': date_till,\n 'order': order,\n 'timelogs': timelogs,\n 'total_duration': total_duration,\n 'json_filename': json_filename,\n 'csv_filename': csv_filename,\n }\n\n return render(request, template, args)\n\n\nclass Echo(object):\n \"\"\"An object that implements just the write method of the file-like\n interface.\n \"\"\"\n def write(self, value):\n \"\"\"Write the value by returning it, instead of storing in a buffer.\"\"\"\n return value\n\n\ndef some_streaming_csv_view(request, csvfile):\n rows = ([\"Row {}\".format(idx), str(idx)] for idx in range(65536))\n pseudo_buffer = Echo()\n writer = csv.writer(pseudo_buffer)\n response = StreamingHttpResponse((writer.writerow(row) for row in rows),\n content_type=\"text/csv\")\n response['Content-Disposition'] = 'attachment; filename=\"{}\".format(csvfile)'\n return response\n\n\ndef export(qs, filename, fields=None):\n model = qs.model\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = 'attachment; filename={}'.format(filename)\n writer = csv.writer(response)\n # Write headers to CSV file\n if fields:\n headers = fields\n else:\n headers = []\n for field in model._meta.fields:\n headers.append(field.name)\n writer.writerow(headers)\n # Write data to CSV file\n for obj in qs:\n row = []\n for field in headers:\n if field in headers:\n val = getattr(obj, field)\n if callable(val):\n val = val()\n row.append(val)\n writer.writerow(row)\n # Return CSV file to browser as download\n return response\n\n\n@project_permission_required('timelogs.add_timelog', '/timelogs/')\ndef add_timelog(request, issue_id):\n \"\"\"\n Add a timelog\n \"\"\"\n template = 'timelogs/timelog_details.html'\n\n args = {\n 'timelog_form': TimelogForm,\n 'issue_id': issue_id,\n }\n\n if request.POST:\n timelog_form = TimelogForm(request.POST)\n if timelog_form.is_valid():\n timelog_form.save()\n msg = 'Time log successfully added'\n messages.success(request, msg)\n return redirect('/issues/'+issue_id)\n else:\n send_err_msg(request, timelog_form)\n return render(request, template, args)\n\n return render(request, template, args)\n\n\n@valid_id\n@project_permission_required('timelogs.change_timelog', '/timelogs/')\ndef edit_timelog(request, timelog_id):\n \"\"\"\n Edit timelog\n \"\"\"\n template = 'timelogs/timelog_details.html'\n\n # get timelog info\n timelog = Timelog.objects.get(pk=timelog_id)\n\n args = {\n 'timelog': timelog,\n 'issue_id': timelog.issue.id,\n 'timelog_form': TimelogForm(initial={\n 'user': timelog.user,\n 'date': timelog.date,\n 'duration': timelog.duration,\n })\n }\n\n if request.POST:\n timelog_form = TimelogForm(request.POST)\n if timelog_form.is_valid():\n timelog_form = TimelogForm(request.POST, instance=timelog)\n timelog_form.save()\n else:\n send_err_msg(request, timelog_form)\n return render(request, template, args)\n\n msg = 'Timelog #' + str(timelog.id) + ' successfully updated'\n messages.success(request, msg)\n\n return redirect('/timelogs/')\n\n return render(request, template, args)\n\n\n@valid_id\n@project_permission_required('timelogs.delete_timelog', '/timelogs/')\ndef delete_timelog(request, timelog_id):\n \"\"\"\n Delete timelog\n \"\"\"\n timelog = Timelog.objects.get(pk=timelog_id)\n timelog.delete()\n\n msg = 'Timelog #' + timelog_id + ' successfully deleted'\n messages.success(request, msg)\n\n return redirect('/timelogs/')\n\n\n# --------------------------------- #\n# --- Random timelogs generator --- #\ndef generate(request):\n from random import randrange, choice\n def get_rand_duration():\n return \"{}.{}\".format(randrange(0,9), randrange(0,99,25))\n\n def get_rand_date():\n days = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30']\n monthes = {'01':'31', '02':'28', '03':'31', '04':'30', '05':'31'}\n year = '2017'\n\n month = choice(list(monthes.keys()))\n day = choice(days)\n if day > monthes[month]:\n day = '28'\n date = \"{}-{}-{}\".format(year, month, day)\n return date\n\n def get_rand_issue():\n return choice(Issue.objects.all())\n\n def get_rand_user(issue):\n users = issue.users.all()\n return choice(users)\n\n issue = get_rand_issue()\n user = get_rand_user(issue)\n\n timelogs_count = 100\n # for t in range(1, timelogs_count):\n # timelog = Timelog(issue=issue, user=user, date=get_rand_date(), duration=get_rand_duration())\n # timelog.save()\n # print(timelog.duration)\n\n from django.http import HttpResponse\n return HttpResponse('Ok!')\n\n\n# ---------------------------------------------------------------------------- #\n# REST Framework ------------------------------------------------------------- #\n\n# class TimelogViewSet(viewsets.ModelViewSet):\nclass TimelogViewSet(mixins.ListModelMixin, mixins.CreateModelMixin,\n mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin,\n viewsets.GenericViewSet):\n # renderer_classes = (JSONRenderer,)\n serializer_class = TimelogSerializer\n queryset = Timelog.objects.all().order_by('-date')\n\n def list(self, request, issue_id=None, user_id=None):\n # extra filters\n timelogs = self.queryset\n issue = request.GET.get('issue')\n user = request.GET.get('user')\n date_from = request.GET.get('from')\n date_due = request.GET.get('due')\n\n if issue_id:\n issue = get_object_or_404(Issue, pk=issue_id)\n timelogs = timelogs.filter(issue=issue)\n if user_id:\n user = get_object_or_404(User, pk=user_id)\n timelogs = timelogs.filter(user=user)\n if issue:\n timelogs = timelogs.filter(issue_id=issue)\n if user:\n timelogs = timelogs.filter(user_id=user)\n if date_from:\n timelogs = timelogs.filter(date__gte=date_from)\n if date_due:\n timelogs = timelogs.filter(date__lte=date_due)\n\n serializer = self.serializer_class(timelogs, many=True,\n fields=('issue', 'user', 'date', 'duration', 'comment'))\n return Response(serializer.data)\n","repo_name":"kavzov/draft","sub_path":"backend/taiga/timelogs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"10876007113","text":"import json\nimport os\nimport glue\n\nwith open('video_data.json', 'r', encoding='utf-8') as file:\n if glue.glue_videos() == 1:\n data = json.load(file)\n try:\n os.system('''cd scripts & python upload_video.py --file=\"{0}\" --title=\"{1}\" --description=\"{2}\" --keywords=\"{3}\" --category=\"{4}\" --privacyStatus=\"{5}\"'''.format(\n os.path.abspath(data['file']),\n data['title']+str(data[\"part\"]),\n data['description'],\n data['keywords'],\n data['category'],\n data['privacyStatus']\n ))\n\n data[\"part\"] = data[\"part\"]+1\n \n data = json.dumps(data, indent = 7)\n\n file.close()\n\n file = open(\"video_data.json\",\"w\") \n file.write(str(data))\n file.close()\n\n print('\\nDeleting single videos...\\n')\n for video in glue.videos:\n os.remove(video)\n glue.videos.remove(video)\n print(video + ' deleted')\n except:\n print('ERROR')\n","repo_name":"Rancorouseful/vk-video-loader","sub_path":"scripts/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"39552566601","text":"import pymysql # mysql 과 연동\n\n# database 연결\nconn = pymysql.connect(\n host=\"localhost\",\n port=3306,\n user=\"biguser1\",\n password=\"12345\",\n db=\"bigdata\",\n charset=\"utf8\",\n)\n\n# print(conn)\n\n# 테이블 생성\ncursor = conn.cursor()\n# timestamp : 날짜와 시간 == sysdate\n# AUTO_INCREMENT(자동증가) == 시퀀스\nsql = \"\"\"\n CREATE TABLE IF NOT EXISTS users(\n id int(11) NOT NULL AUTO_INCREMENT,\n username varchar(20),\n email varchar(100),\n phone varchar(100),\n website varchar(100),\n regdate timestamp DEFAULT CURRENT_TIMESTAMP, \n PRIMARY KEY(id)\n )\n\"\"\"\n\ncursor.execute(sql)\nconn.commit()\nconn.close()\n","repo_name":"ejoo1109/pythonsource","sub_path":"crawl/database/mysql_test1.py","file_name":"mysql_test1.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"20994856472","text":"from resources import clear\n\ndef imparpar():\n clear()\n numero = input('Digite um numero: ')\n floatNumero = None\n while True:\n try:\n floatNumero = float(numero)\n break\n except ValueError:\n clear()\n print('Isso não é um numero!\\n')\n numero = input('Digite um numero: ')\n\n print(f'O Numero {numero} é:\\n')\n print('Par' if (floatNumero % 2) == 0 else 'Impar')","repo_name":"jsnery/Praticando-Python","sub_path":"matematica/impar_par.py","file_name":"impar_par.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"28186741028","text":"from random import *\n\n# Crear cadena de numeros\ncadena = \"\"\nwhile len(cadena) != 4:\n digito = str(randint(1, 9))\n while digito in cadena:\n digito = str(randint(1, 9))\n cadena += digito\n\n# Bucle principal\nres = str(input(\"Se ha generado un código de cuatro dígitos, ¡intenta acertarlo!: \"))\nwhile res != cadena:\n toros = 0\n vacas = 0\n cont = 0\n cont2 = 0\n for numero in cadena:\n cont += 1 # Aquí comprobará la posición del numero original\n for numero_2 in res:\n cont2 += 1 # Aquí la posición del numero dado\n if cont2 > 4: # si no estaria contando numeros, siempre seria hasta \"16\".\n cont2 = 1\n if numero == numero_2 and cont == cont2:\n toros += 1\n elif numero == numero_2:\n vacas += 1\n print(\"\\nHas fallado, pero te daré una pista:\\nToros {0} | Vacas {1}.\".format(toros, vacas))\n res = input(\"\\nIntentalo de nuevo: \")\nprint(\"Felicidades, has ganado.\")\n","repo_name":"alonsomadrigal04/Programacion_practicas","sub_path":"Practica3/ejercicio_4.py","file_name":"ejercicio_4.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"70935829883","text":"import logging\nfrom logging.handlers import TimedRotatingFileHandler\nimport sys\nfrom domogik.common.configloader import Loader\n\nclass Logger():\n '''\n Logger for Domogik\n Define main config parameters to help scripts to use logging facilities\n with a minimum of config\n '''\n\n logger = {}\n\n def __init__(self, component_name, domogik_prefix=True, use_filename=None, log_on_stdout=True):\n '''\n Get a logger with provided parameters and set config\n @param component_name : component name to log\n @param domogik_prefix : if logger name should be prefixed by 'domogik-'\n @param use_filename : if set tells the logger to use this file name (otherwise takes 'component_name')\n @param log_on_stdout : if set to True, allow to display logs in both stdout and log file\n '''\n if component_name not in self.logger:\n LEVELS = {\n 'debug': logging.DEBUG,\n 'info': logging.INFO,\n 'warning': logging.WARNING,\n 'error': logging.ERROR,\n 'critical': logging.CRITICAL\n }\n\n cfg = Loader()\n config = cfg.load()[0]\n if use_filename is None:\n filename = \"{0}/{1}.log\".format(config['log_dir_path'], component_name)\n else:\n filename = \"{0}/{1}.log\".format(config['log_dir_path'], use_filename)\n level = config['log_level']\n\n if 'log_when' not in config:\n config['log_when'] = 'D'\n if 'log_interval' not in config:\n config['log_interval'] = 1\n if 'log_backup_count' not in config:\n config['log_backup_count'] = 10\n\n if level not in LEVELS:\n raise ValueError(\"level must be one of 'debug','info','warning',\"\\\n \"'error','critical'. Check your config.\")\n\n if domogik_prefix:\n my_logger = logging.getLogger('domogik-{0}'.format(component_name))\n else:\n my_logger = logging.getLogger(component_name)\n # log to file\n my_logger.propagate = 0\n if not my_logger.handlers:\n hdlr = TimedRotatingFileHandler(filename, \\\n when=config['log_when'], interval=int(config['log_interval']), \\\n backupCount=int(config['log_backup_count']))\n formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')\n hdlr.setFormatter(formatter)\n my_logger.addHandler(hdlr)\n\n\t # if loglevvel is set to debug (all log entries also go to stdout)\n if (log_on_stdout or level == 'debug') and component_name.find('sqlalchemy') == -1:\n dhdlr = logging.StreamHandler(sys.stdout)\n dhdlr.setFormatter(formatter)\n my_logger.addHandler(dhdlr)\n\n my_logger.setLevel(LEVELS[level])\n self.logger[component_name] = my_logger\n\n def set_format_mode(self, mode):\n formatter = None\n if mode == \"messageOnly\":\n formatter = logging.Formatter('%(message)s')\n if formatter:\n for log in self.get_logger().handlers:\n if type(log) is logging.StreamHandler:\n log.setFormatter(formatter)\n\n def get_logger(self, logger_name = None):\n '''\n returns the configured logger instance\n @param logger_name : The name of the logger you want to get.\n If not provided, return the logger if only one exists\n '''\n if logger_name is not None:\n return self.__class__.logger[logger_name]\n elif len(self.__class__.logger.keys()) == 1:\n return self.__class__.logger[list(self.__class__.logger)[0]]\n else:\n raise AttributeError(\"You must specify a loggger name\")\n\n def get_fds(self, logger_names):\n openFiles = []\n for name in logger_names:\n logger = self.logger[name]\n for handler in logger.handlers:\n if hasattr(handler, 'stream') and \\\n hasattr(handler.stream, 'fileno'):\n openFiles.append(handler.stream) \n return openFiles\n","repo_name":"domogik/domogik","sub_path":"src/domogik/common/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":4325,"program_lang":"python","lang":"en","doc_type":"code","stars":117,"dataset":"github-code","pt":"41"} +{"seq_id":"16002705952","text":"# Se citește de la tastatură un text. Se cere să se “traducă” în limba păsărească textul dat astfel: după fiecare vocală se adaugă\n# litera p și încă o dată acea vocală (după a, e, i, o, u se adaugă respectiv pa, pe, pi, po, pu). Exemplu: “Ana are mere.” devine\n# “Apanapa aparepe meperepe.”\n# Fiind dat un astfel de text în limba păsărească, se poate obține textul original? Dacă da, faceți asta.\n\nvocale = (\"a\", \"e\", \"i\", \"o\", \"u\")\n\ns = input()\n\nnew_s = \"\"\n\ni = 0\nwhile i < len(s):\n new_s += s[i]\n if s[i].lower() in vocale and s[i+1:].startswith(\"p\"+s[i].lower()):\n i += 2\n i += 1\n\nprint(new_s)\n","repo_name":"andrei-micuda/ProgAlgo2019-2020","sub_path":"Lab02/lab02_08a.py","file_name":"lab02_08a.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"ro","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"21783661216","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'blog'\nurlpatterns = [\n # '~/blog/'\n url(r'^$', views.index, name='index'),\n # '~/blog/page=2/'\n url(r'^page=(?P<page_num>[0-9]+)/$', views.index, name='index'),\n # '~/blog/blog=HelloWorld/'\n url(r'^blog=(?P<blog>\\w+)/$', views.detail, name='detail'),\n # '~/blog/archive/'\n url(r'^archive/$', views.archive, name='archive'),\n # '~/blog/archive/2016/'\n url(r'^archive/year=(?P<year>\\d{4})/$', views.archive, name='archive'),\n # '~/blog/archive/2016/page=2'\n url(r'^archive/year=(?P<year>\\d{4})/page=(?P<page_num>[0-9]+)/$', views.archive, name='archive'),\n # '~/blog/tag=AdvLinuxProgramming/'\n url(r'^tag=(?P<tag>\\w+)/$', views.tag, name='tag'),\n # '~/blog/tag=AdvLinuxProgramming/page=2'\n url(r'^tag=(?P<tag>\\w+)/page=(?P<page_num>[0-9]+)/$', views.tag, name='tag'),\n ]\n","repo_name":"rim99/django_blog","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"23169514422","text":"import argparse\nimport cscore\nimport time\nfrom networktables import NetworkTables\n\nparser = argparse.ArgumentParser(description='FRC Object Detection')\n# Common arguments\nparser.add_argument('--team', '-t', type=int, default=7028,\n help='Team number of robot to connect to. Not used when --ntip is specified.')\n\n# Less common arguments\nparser.add_argument('--ntip', '-ip',\n help='IP Address of the NetworkTables to connect to. Leave blank to connect to robot.')\nparser.add_argument('--front-camera', '-cf', default=\"/dev/v4l/by-path/platform-70090000.xusb-usb-0:3.2:1.0-video-index0\",\n help='The camera to use for detection. Use `v4l2-ctl --list-devices` to get list of USB cameras')\nparser.add_argument('--rear-camera', '-cr', default=\"/dev/v4l/by-path/platform-70090000.xusb-usb-0:3.1:1.0-video-index0\",\n help='The camera to use for detection. Use `v4l2-ctl --list-devices` to get list of USB cameras')\nparser.add_argument('--height', type=int, default=180,\n help='The resolution height to capture images from the cameras. Use `v4l2-ctl --device=/dev/video1 --list-formats-ext` to get modes')\nparser.add_argument('--width', type=int, default=320,\n help='The resolution width to capture images from the cameras.')\nparser.add_argument('--rate', type=int, default=20,\n help=\"The framerate (FPS) to capture from the cameras.\")\nparser.add_argument('--stream-compression', type=int, default=20,\n help='The compression to stream for clients that do not specify it.')\nparser.add_argument(\"--port\", \"-p\", type=int, default=1181,\n help=\"MjpgServer port for streaming\")\n\nargs = parser.parse_args()\nprint(args)\n\nfrontCam = cscore.UsbCamera(\"DriverCam0\", args.front_camera)\nfrontCam.setPixelFormat(cscore.VideoMode.PixelFormat.kMJPEG)\nfrontCam.setResolution(args.width, args.height)\nfrontCam.setFPS(args.rate)\nfrontCam.setConnectionStrategy(cscore.VideoSource.ConnectionStrategy.kKeepOpen)\n\nrearCam = cscore.UsbCamera(\"DriverCam1\", args.rear_camera)\nrearCam.setPixelFormat(cscore.VideoMode.PixelFormat.kMJPEG)\nrearCam.setResolution(args.width, args.height)\nrearCam.setFPS(args.rate)\nrearCam.setConnectionStrategy(cscore.VideoSource.ConnectionStrategy.kKeepOpen)\n\nserver = cscore.MjpegServer(name=\"Driver\", port=args.port)\nserver.setCompression(args.stream_compression)\nserver.setFPS(args.rate)\nserver.setResolution(args.width, args.height)\n\n# Configure the NetworkTables to send data to the robot and shuffleboard\nif args.ntip is None:\n NetworkTables.startClientTeam(args.team)\nelse:\n NetworkTables.initialize(args.ntip)\n\n\n# Set up the entry that is used to select front or rear camera\ndriverCamTable = NetworkTables.getTable('DriverCam')\ndriverCamTable.putBoolean(\"Front\", driverCamTable.getBoolean(\"Front\", True))\n\n# Publish the stream to the CameraPublisher networktable so it can be added to shuffleboard\nstreamAddresses = []\n# Always publish the known static address\nstreamAddresses.append(\"mjpg:http://%s:%d/?action=stream\" % (\"10.70.28.13\", args.port))\n# Publish any other interface addresses cscore can find\nfor addr in cscore.getNetworkInterfaces():\n if addr == \"127.0.0.1\" or addr == \"10.70.28.13\":\n continue # ignore localhost\n streamAddresses.append(\"mjpg:http://%s:%d/?action=stream\" % (addr, args.port))\nNetworkTables.getTable(\"CameraPublisher\").getSubTable(\"Driver\").putStringArray(\"streams\", streamAddresses)\n\n# Loop forever switching the source to front or back\nwhile True:\n if driverCamTable.getBoolean(\"Front\", True):\n server.setSource(frontCam)\n else:\n server.setSource(rearCam)\n","repo_name":"STMARobotics/frc-jetson-detect","sub_path":"frc-driver-cam.py","file_name":"frc-driver-cam.py","file_ext":"py","file_size_in_byte":3699,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"24127108693","text":"import os\nimport torch\nimport numpy as np\nimport torch.distributed as dist\nfrom torchvision import datasets, transforms\nfrom torch.utils.data import DataLoader, Dataset,TensorDataset\nfrom timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD\nfrom timm.data import Mixup\nfrom timm.data import create_transform\n\nfrom .cached_image_folder import CachedImageFolder\nfrom .imagenet22k_dataset import IN22KDATASET\nfrom .samplers import SubsetRandomSampler\nfrom glob import glob\nfrom skimage import io\nimport cv2\nfrom tqdm import tqdm\nimport pickle as pkl\n\ntry:\n from torchvision.transforms import InterpolationMode\n\n\n def _pil_interp(method):\n if method == 'bicubic':\n return InterpolationMode.BICUBIC\n elif method == 'lanczos':\n return InterpolationMode.LANCZOS\n elif method == 'hamming':\n return InterpolationMode.HAMMING\n else:\n # default bilinear, do we want to allow nearest?\n return InterpolationMode.BILINEAR\n\n\n import timm.data.transforms as timm_transforms\n\n timm_transforms._pil_interp = _pil_interp\nexcept:\n from timm.data.transforms import _pil_interp\n\n\ndef build_loader(config,mode='train',imagen_demo=False):\n config.defrost()\n dataset_train, config.MODEL.NUM_CLASSES = build_dataset(is_train=True, config=config,mode=mode,imagen_demo=imagen_demo)\n config.freeze()\n print(f\"local rank {config.LOCAL_RANK} / global rank {dist.get_rank()} successfully build train dataset\")\n dataset_val, _ = build_dataset(is_train=False, config=config,mode=mode,imagen_demo=imagen_demo)\n print(f\"local rank {config.LOCAL_RANK} / global rank {dist.get_rank()} successfully build val dataset\")\n\n num_tasks = dist.get_world_size()\n global_rank = dist.get_rank()\n if config.DATA.ZIP_MODE and config.DATA.CACHE_MODE == 'part':\n indices = np.arange(dist.get_rank(), len(dataset_train), dist.get_world_size())\n sampler_train = SubsetRandomSampler(indices)\n else:\n sampler_train = torch.utils.data.DistributedSampler(\n dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True\n )\n\n if config.TEST.SEQUENTIAL:\n sampler_val = torch.utils.data.SequentialSampler(dataset_val)\n else:\n sampler_val = torch.utils.data.distributed.DistributedSampler(\n dataset_val, shuffle=config.TEST.SHUFFLE\n )\n\n if mode=='demo':\n data_loader_train = torch.utils.data.DataLoader(\n dataset_train,\n batch_size=1,\n num_workers=config.DATA.NUM_WORKERS,\n pin_memory=config.DATA.PIN_MEMORY,\n drop_last=True,\n )\n else:\n data_loader_train = torch.utils.data.DataLoader(\n dataset_train, sampler=sampler_train,\n batch_size=config.DATA.BATCH_SIZE,\n num_workers=config.DATA.NUM_WORKERS,\n pin_memory=config.DATA.PIN_MEMORY,\n drop_last=True,\n )\n if mode=='demo':\n data_loader_val = torch.utils.data.DataLoader(\n dataset_val,\n batch_size=1,\n shuffle=False,\n num_workers=config.DATA.NUM_WORKERS,\n pin_memory=config.DATA.PIN_MEMORY,\n drop_last=False\n )\n else:\n data_loader_val = torch.utils.data.DataLoader(\n dataset_val, sampler=sampler_val,\n batch_size=config.DATA.BATCH_SIZE,\n shuffle=False,\n num_workers=config.DATA.NUM_WORKERS,\n pin_memory=config.DATA.PIN_MEMORY,\n drop_last=False\n )\n \n\n # setup mixup / cutmix\n mixup_fn = None\n mixup_active = config.AUG.MIXUP > 0 or config.AUG.CUTMIX > 0. or config.AUG.CUTMIX_MINMAX is not None\n if mixup_active:\n mixup_fn = Mixup(\n mixup_alpha=config.AUG.MIXUP, cutmix_alpha=config.AUG.CUTMIX, cutmix_minmax=config.AUG.CUTMIX_MINMAX,\n prob=config.AUG.MIXUP_PROB, switch_prob=config.AUG.MIXUP_SWITCH_PROB, mode=config.AUG.MIXUP_MODE,\n label_smoothing=config.MODEL.LABEL_SMOOTHING, num_classes=config.MODEL.NUM_CLASSES)\n\n return dataset_train, dataset_val, data_loader_train, data_loader_val, mixup_fn\n\n\ndef build_dataset(is_train, config,mode='train',imagen_demo=False):\n def PositionalEncoding(size, value):\n d=1\n for i in range(len(size)):\n d=d*size[i]\n j=int(d/2)\n PE=np.zeros(d)\n for i in range(j):\n PE[2*i] = np.sin(value/(10000**(2*i/d)))\n PE[2*i + 1] = np.cos(value / (10000**(2*i/d)))\n if d%2 !=0:\n\n PE[2*j] = np.sin(value / (10000 ** (2 * j / d)))\n\n PE=np.reshape(PE,size)\n return PE\n pos1=PositionalEncoding((1024,1024,1),int(1))\n pos2=PositionalEncoding((1024,1024,1),int(2))\n pos3=PositionalEncoding((1024,1024,1),int(3))\n transform = build_transform(is_train, config)\n \n if config.DATA.DATASET == 'imagenet':\n prefix = 'train' if is_train else 'val'\n if config.DATA.ZIP_MODE:\n ann_file = prefix + \"_map.txt\"\n prefix = prefix + \".zip@/\"\n dataset = CachedImageFolder(config.DATA.DATA_PATH, ann_file, prefix, transform,\n cache_mode=config.DATA.CACHE_MODE if is_train else 'part')\n else:\n if mode=='demo':\n assert imagen_demo!=False, 'No se proporciono una imagen de prueba'\n imagen=np.zeros((1,4,1024,1024))\n target=np.zeros(1)\n edades=np.zeros(1)\n im=io.imread(imagen_demo)\n im=cv2.resize(im,(1024,1024))\n if len(im.shape)!=3:\n im=np.stack((im,im,im),axis=2)\n ed=int(imagen_demo.split('/')[-1].split('.')[1])\n if int(ed)==1:\n im=np.concatenate((im,pos1),axis=2)\n if int(ed)==2:\n im=np.concatenate((im,pos2),axis=2)\n if int(ed)==3:\n im=np.concatenate((im,pos3),axis=2)\n im=np.transpose(im,axes=(2,0,1))\n imagen[0]=im\n images_all=torch.Tensor(imagen)\n targets_all=torch.Tensor(target).type(torch.LongTensor)\n edad_all=torch.as_tensor(edades)\n dataset=TensorDataset(images_all,targets_all,edad_all)\n else:\n root_N = os.path.join(config.DATA.DATA_PATH, prefix,'Negative','*.jpeg')\n root_P = os.path.join(config.DATA.DATA_PATH, prefix,'Positive','*.jpeg')\n paths_N=glob(root_N)\n paths_P=glob(root_P)\n imagenes_P=np.zeros((len(paths_P),4,1024,1024))\n imagenes_N=np.zeros((len(paths_N),4,1024,1024))\n targets_P=np.zeros(len(paths_P))\n targets_N=np.zeros(len(paths_N))\n edades_N=np.zeros(len(paths_N))\n edades_P=np.zeros(len(paths_P))\n names_n=[]\n names_p=[]\n for i in tqdm(range(len(paths_N))):\n im=io.imread(paths_N[i])\n im=cv2.resize(im,(1024,1024))\n if len(im.shape)!=3:\n im=np.stack((im,im,im),axis=2)\n ed=int(paths_N[i].split('/')[-1].split('.')[1])\n if int(ed)==1:\n im=np.concatenate((im,pos1),axis=2)\n if int(ed)==2:\n im=np.concatenate((im,pos2),axis=2)\n if int(ed)==3:\n im=np.concatenate((im,pos3),axis=2)\n im=np.transpose(im,axes=(2,0,1))\n imagenes_N[i,:,:,:]=im\n targets_N[i]=int(0)\n edades_N[i]=int(ed)\n names_n.append(paths_N[i])\n\n for i in tqdm(range(len(paths_P))):\n im=io.imread(paths_P[i])\n im=cv2.resize(im,(1024,1024))\n ed=paths_P[i].split('/')[-1].split('.')[1]\n if len(im.shape)!=3:\n im=np.stack((im,im,im),axis=2)\n if int(ed)==1:\n im=np.concatenate((im,pos1),axis=2)\n if int(ed)==2:\n im=np.concatenate((im,pos2),axis=2)\n if int(ed)==3:\n im=np.concatenate((im,pos3),axis=2)\n im=np.transpose(im,axes=(2,0,1))\n imagenes_P[i,:,:,:]=im\n targets_P[i]=int(1)\n edades_P[i]=int(ed)\n names_p.append(paths_P[i])\n paths_all=np.concatenate((names_n,names_p),axis=0)\n images_all=np.concatenate((imagenes_N,imagenes_P),axis=0)\n targets_all=np.concatenate((targets_N,targets_P),axis=0)\n images_all=torch.Tensor(images_all)\n targets_all=torch.Tensor(targets_all).type(torch.LongTensor)\n edad_all=torch.as_tensor(np.concatenate((edades_N,edades_P),axis=0))\n #dataset = datasets.ImageFolder(root, transform=transform)\n with open('paths.mat','wb') as f:\n pkl.dump(paths_all,f)\n dataset=TensorDataset(images_all,targets_all,edad_all)\n nb_classes = 2\n elif config.DATA.DATASET == 'imagenet22K':\n prefix = 'ILSVRC2011fall_whole'\n if is_train:\n ann_file = prefix + \"_map_train.txt\"\n else:\n ann_file = prefix + \"_map_val.txt\"\n dataset = IN22KDATASET(config.DATA.DATA_PATH, ann_file, transform)\n nb_classes = 2\n else:\n raise NotImplementedError(\"We only support ImageNet Now.\")\n\n return dataset, nb_classes\n\n\ndef build_transform(is_train, config):\n resize_im = config.DATA.IMG_SIZE > 32\n if is_train:\n # this should always dispatch to transforms_imagenet_train\n transform = create_transform(\n input_size=config.DATA.IMG_SIZE,\n is_training=True\n )\n if not resize_im:\n # replace RandomResizedCropAndInterpolation with\n # RandomCrop\n transform.transforms[0] = transforms.RandomCrop(config.DATA.IMG_SIZE, padding=4)\n return transform\n\n t = []\n if resize_im:\n if config.TEST.CROP:\n size = int((256 / 224) * config.DATA.IMG_SIZE)\n t.append(\n transforms.Resize(size, interpolation=_pil_interp(config.DATA.INTERPOLATION)),\n # to maintain same ratio w.r.t. 224 images\n )\n t.append(transforms.CenterCrop(config.DATA.IMG_SIZE))\n else:\n t.append(\n transforms.Resize((config.DATA.IMG_SIZE, config.DATA.IMG_SIZE),\n interpolation=_pil_interp(config.DATA.INTERPOLATION))\n )\n\n t.append(transforms.ToTensor())\n #t.append(transforms.Normalize(IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD))\n return transforms.Compose(t)\n","repo_name":"SantiUsma/AML_proyecto","sub_path":"data/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":11055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"42989878191","text":"import datetime\nimport itertools\nimport multiprocessing\nimport sys\nimport time\nimport traceback\nimport warnings\n\nimport humanfriendly\n\nfrom benchmark import OpenMLBenchmark\n\ntimeout = 3600 # in seconds\nrun_timeout = 600 # in seconds\njobs = 4\n\n\ndef run(task: int, conn) -> None:\n try:\n print('##\\nIteration {} at {}\\n##'.format(i, datetime.datetime.now().time()))\n bm = OpenMLBenchmark(task)\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", category=RuntimeWarning)\n avg_score = 0\n for fold in bm.folds:\n if algorithm == 'atm':\n from adapter import run_atm\n if run_atm.skip(task):\n avg_score += -1\n else:\n avg_score += run_atm.main(fold, bm, timeout, jobs)\n elif algorithm == 'random':\n from adapter import run_auto_sklearn\n if run_auto_sklearn.skip(task):\n avg_score += -1\n else:\n avg_score += run_auto_sklearn.main(fold, bm, timeout, run_timeout, jobs, random=True)\n elif algorithm == 'auto-sklearn':\n from adapter import run_auto_sklearn\n if run_auto_sklearn.skip(task):\n avg_score += -1\n else:\n avg_score += run_auto_sklearn.main(fold, bm, timeout, run_timeout, jobs, random=False)\n elif algorithm == 'dummy':\n from adapter import run_baseline\n if run_baseline.skip(task):\n avg_score += -1\n else:\n avg_score += run_baseline.main(fold, dummy=True)\n elif algorithm == 'rf':\n from adapter import run_baseline\n if run_baseline.skip(task):\n avg_score += -1\n else:\n avg_score += run_baseline.main(fold, dummy=False)\n elif algorithm == 'h2o':\n from adapter import run_h2o\n if run_h2o.skip(task):\n avg_score += -1\n else:\n avg_score += run_h2o.main(fold, bm, timeout, run_timeout, jobs)\n elif algorithm == 'hpsklearn':\n from adapter import run_hpsklearn\n if run_hpsklearn.skip(task):\n avg_score += -1\n else:\n avg_score += run_hpsklearn.main(fold, timeout, run_timeout)\n elif algorithm == 'tpot':\n from adapter import run_tpot\n if run_tpot.skip(task):\n avg_score += -1\n else:\n avg_score += run_tpot.main(fold, timeout, run_timeout, jobs)\n else:\n raise ValueError('Unknown algorithm {}'.format(algorithm))\n conn.send(avg_score / len(bm.folds))\n except Exception:\n traceback.print_exc()\n conn.send(1)\n\n\nif __name__ == '__main__':\n algorithm = sys.argv[1]\n idx = int(sys.argv[2]) if len(sys.argv) > 2 else None\n\n print('Algorithm: ', algorithm)\n print('Timeout: ', timeout)\n print('Run Timeout: ', run_timeout)\n\n task_ids = [\n [3, 12, 31, 53, 3917, 7593, 9952, 9977, 9981, 10101],\n [14965, 34539, 146195, 146212, 146818, 146821, 146822, 146825, 167119, 167120],\n [167121, 167124, 168329, 168330, 168331, 168332, 168335, 168337, 168338],\n [168868, 168908, 168909, 168910, 168911, 168912, 189354, 189355, 189356],\n ]\n\n if idx is not None:\n print('Using chunk {}/{}'.format(idx, len(task_ids)))\n task_ids = task_ids[idx]\n else:\n print('Using all tasks')\n task_ids = list(itertools.chain.from_iterable(task_ids))\n\n recv_end, send_end = multiprocessing.Pipe(False)\n res = []\n for task in task_ids:\n print('#######\\nStarting task {}\\n#######'.format(task))\n res.append([])\n for i in range(5):\n try:\n start = time.time()\n\n p = multiprocessing.Process(target=run, args=(task, send_end))\n p.start()\n\n p.join(timeout * 1.5)\n\n if p.is_alive():\n print('Grace period exceed. Stopping benchmark.')\n p.terminate()\n p.join()\n score = 1\n else:\n score = recv_end.recv()\n\n if score != -1:\n res[-1].append(score)\n print('Misclassification Rate', score)\n print('Duration', humanfriendly.format_timespan(time.time() - start))\n except Exception as e:\n if isinstance(e, KeyboardInterrupt):\n print(res)\n raise e\n traceback.print_exc()\n print('Misclassification rate', 1)\n print(res[-1])\n\n for i in range(len(res)):\n print(' {}, # {}'.format(res[i], task_ids[i]))\n\n print(res)\n","repo_name":"Ennosigaeon/automl_benchmark","sub_path":"run_framework.py","file_name":"run_framework.py","file_ext":"py","file_size_in_byte":5223,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"41"} +{"seq_id":"31221746793","text":"\"\"\"\nGiven a string, find if there is a palindrome present in its permutations\n\"\"\"\n\nfrom itertools import permutations\n\n\ndef isPalindrome(a: str)-> bool:\n\n b = [''.join(x) for x in permutations(a.replace(\" \", \"\"))]\n\n for i in b:\n if i==i[::-1]:\n print(True)\n return\n\n print(False)\n\n\nisPalindrome(\"tact coa\")\nisPalindrome(\"text\")\nisPalindrome(\"Kadvul\")\nisPalindrome(\"Heyyy\")","repo_name":"Rammurthy5/CtCi_problems","sub_path":"palindrome_permutation.py","file_name":"palindrome_permutation.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"3960579328","text":"from subprocess import check_output\nimport shlex \nimport json \nimport datetime\nimport logging \nimport csv\n\n#Iniciar as variáveis que serão utilizadas\nparent = [\"1\", #ID de dev\n\"2\", #ID de homolog\n\"3\"] #ID de prod\n\n# Arrays utilizados nas etapas seguintes, não precisam ser preenchidos\nvalue = []\ndiasDelete = []\nipDeleteLog = []\nipDeleteCsv = []\n\n#Iniciar a função de dia atual em uma variável\ndataAtual = datetime.datetime.now()\ndiasValidos = dataAtual - datetime.timedelta(days=7)\nregraData = diasValidos.strftime(\"%Y-%m-%dT%H:%M:%S.000-07:00\")\n\n#Iniciar nome e formato do arquivo log\narquivoNomeLog = \"deleted-ipaddresses-\" + dataAtual.strftime(\"%Y-%m-%dT%Hh%Mmin%Ss\") + \".log\"\n\n#Colocar a data atual no nome do arquivo csv que será gerado\narquivoNomeCsv = \"deleted-ipaddresses-\" + dataAtual.strftime(\"%Y-%m-%dT%Hh%Mmin%Ss\") + \".csv\"\n\n#Listar todos os projetos de dev, homolog e prod\nfor p in parent:\n\n parentId = p\n comando1 = f'gcloud projects list --filter=parent.id={parentId} --format=json'\n projetos = json.loads(check_output(shlex.split(comando1),shell=True))\n\n for p in projetos:\n\n#Armazenar o ID de cada projeto\n projectId = p[\"projectId\"]\n\n#Listar os endereços de ip de cada projeto em formato JSON\n comando2 = f'gcloud compute addresses list --project={projectId} --format=json'\n ipaddresses = json.loads(check_output(shlex.split(comando2),shell=True))\n\n#Armazenar nome, data de criação, zona e usuário de cada endereço de IP listado\n for i in ipaddresses:\n\n name = i[\"name\"]\n creationTimestamp = i[\"creationTimestamp\"]\n\n try:\n region = i[\"region\"].rsplit('/', 1)[-1]\n except (KeyError):\n region = 0\n\n try:\n users = i[\"users\"]\n except (KeyError):\n users = 0\n\n#Validar regra de data e se o campo \"user\" está vazio\n if (creationTimestamp <= regraData) and (users == 0):\n\n#Endereços de IP validados para exclusão são concatenados\n ipDeleteCsv.append([parentId, projectId, name, creationTimestamp, region, users])\n\n ipDeleteLog.append({\"parentId\": parentId, \"projectId\": projectId, \"name\": name, \"creationTimestamp\": creationTimestamp, \"location\": region, \"sizeGb\": None, \"users\": users})\n\n#Passar todos os endereços de ip a serem excluídos para um arquivo .csv\nfields = ['PARENT', 'PROJECT', 'NAME', 'CREATION_TIMESTAMP', 'LOCATION', 'USER'] #Nomes das colunas\nwith open(\"/caminho/da/pasta/\" + arquivoNomeCsv, 'w', newline='') as csvfile:\n csvwriter = csv.writer(csvfile, delimiter=';') \n csvwriter.writerow(fields)\n csvwriter.writerows(ipDeleteCsv)\n\n\n#Ação de exclusão e registro em log\nfor i in ipDeleteLog:\n \n data = str(i)[1:-1]\n name = i[\"name\"]\n projectId = i[\"projectId\"]\n region = i[\"region\"]\n\n try:\n comando3 = f\"gcloud compute addresses delete {name} --region={region} --project={projectId} --quiet\"\n delete_ip = check_output(shlex.split(comando3),shell=True)\n\n logging.basicConfig(filename = arquivoNomeLog,\n filemode = \"w\",\n format = \"{'level': '%(levelname)s', 'timestamp': '%(asctime)s', 'status': '%(message)s}\",\n datefmt='%Y-%m-%dT%Hh%Mmin%Ss', \n level = logging.INFO)\n logger = logging.getLogger()\n logger.info(\"Deleted', \" + data)\n\n except:\n logging.basicConfig(filename = arquivoNomeLog,\n filemode = \"w\",\n format = \"{'level': '%(levelname)s', 'timestamp': '%(asctime)s', 'status': '%(message)s}\",\n datefmt='%Y-%m-%dT%Hh%Mmin%Ss',\n level = logging.ERROR)\n logger = logging.getLogger()\n logger.error(\"Failed', \" + data) \n\n#Mensagem final de realizado com sucesso!\nprint(\"Log and CSV scraping... DONE, check: \" + arquivoNomeLog + \"and \" + arquivoNomeCsv)","repo_name":"isabluiza/scripts-finops","sub_path":"recursos-ociosos/ipaddresses.py","file_name":"ipaddresses.py","file_ext":"py","file_size_in_byte":4053,"program_lang":"python","lang":"pt","doc_type":"code","stars":9,"dataset":"github-code","pt":"41"} +{"seq_id":"8531957439","text":"import csv\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport seaborn as sns\nimport pandas\nimport math\n\n\ndef isDark(color):\n r = color[0]\n g= color[1]\n b = color[2]\n hsp = math.sqrt(\n 0.299 * (r * r) +\n 0.587 * (g * g) +\n 0.114 * (b * b)\n )\n return hsp < 0.5\n\n \n\n# with open(\"log.csv\") as csv_file:\n# csv_reader = csv.reader(csv_file, delimiter=';')\n# line_count = 0\n# data_bytes = []\n# print(\"Reading...\")\n# for row in csv_reader:\n#\n# data_to_send = data_pb2.Data()\n#\n# data_to_send.Entity_Id = 101\n# data_to_send.Location = row[2]\n# data_to_send.Timestamp = row[0]\n#\n# data_bytes.append(data_to_send.SerializeToString())\n# print('Data read.')\ndata = []\nlinhas = [\"Framework\", \"Middleware\", \"Platform\", \"Architecture\",\n \"System\", \"Approach\", \"Engine\", \"Robot Services\"]\ncols = [\"Older adults needs\", \"Heterogeneity\", \"Interoperability\", \"Context Awareness\",\"Security\",\n \"Scalability\", \"Usability\", \"Reliability\", \"Power Management\", \"Privacy\", \"Effectiveness\", \"Extensibility\", \"foo\", \"foo2\", \"foodeo\"]\nwith open(\"heatmapPaulo.csv\") as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=';')\n\n for row in csv_reader:\n arr = []\n for num in row:\n arr.insert(len(arr), int(num))\n data.insert(len(data), arr)\n#print(data)\ndf = pandas.DataFrame(data, columns=cols, index=linhas)\nprint(df)\n#df.pivot(index= linhas, columns= cols, values=data)\n#ax = sns.heatmap(df, annot=True, fmt='d', cmap=\"YlOrRd\")\nplain_list = []\nfor lista in data:\n for num in lista:\n plain_list.append(num)\nx = np.array(list(np.arange(len(cols))) * len(linhas))\ny = np.array(list(np.arange(len(linhas))) * len(cols))\n#organizar o eixo y para agrupar os digitos.\ny.sort()\n#transformar a list em np.array\nplain_list = np.array(plain_list)\n#grafico de scatter (bubble heat map)\nplt.tick_params(axis='both', length=0.1, width=0.1)\n\n#COLOR MAP\ncolor_map = 'Blues'\n\n\nplt.scatter(x, y, s= plain_list * 200, c=plain_list, cmap=color_map)\n#inverter o eixo Y\nplt.gca().invert_yaxis()\n\n#renomear os ticks\nplt.xticks(np.arange(len(cols)), cols, rotation=40)\nplt.yticks(np.arange(-1, len(linhas) + 1), [\"\",*linhas])\nax = plt.gca()\n#annotations\nx_pos =0\ny_pos = 0\ngnuplot = cm.get_cmap(color_map, 6)\n\nfor lista in data:\n x_pos = 0\n for num in lista:\n if(isDark(gnuplot(num))):\n ax.annotate(xy=[x_pos, y_pos], s=num, ha='center', va='center', c='white')\n else:\n ax.annotate(xy=[x_pos, y_pos], s=num, ha='center', va='center', c='black')\n x_pos += 1\n y_pos += 1\n \nprint(f\"x:{x_pos}, y:{y_pos}\")\nfigs = plt.gcf()\n\nfigs.set_size_inches(10.24, 7.68)\nplt.colorbar()\nplt.savefig(\"graf.png\")\n\nplt.show()\n","repo_name":"davitabosa12/AAL","sub_path":"plots/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":2801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"3991100064","text":"def hcf(x,y):\r\n #该函数返回两个数的最大公因数\r\n #获取最小值\r\n if x>y:\r\n smaller=y\r\n else:\r\n smaller=x\r\n for i in range(1,smaller+1):\r\n if x%i==0 and y%i==0:\r\n hcf=i\r\n return hcf\r\n\r\n\r\n#版权\r\nprint(\"此程序由gitignore制作\\n由©GITI保留所有权\\n求最大公因数:\")\r\n\r\n#用户输入两个数字\r\nnum1=int(input(\"输入要算最大公因数的第一个���:\"))\r\nnum2=int(input(\"输入要算最大公因数的第二个数:\"))\r\nprint(num1,\"和\",num2,\"的最大公约数为\",hcf(num1, num2))\r\n\r\nprint(\"计算完毕\\n版权由\\n——©GITI-算法-最大公因数\\n提供\")\r\n","repo_name":"ljy-002/Python.ljy-002","sub_path":"最大公因数算法.py","file_name":"最大公因数算法.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"21712640012","text":"import argparse\nimport logging\nimport time\nimport datetime\n\nimport requests\nimport xmltodict\nimport oracledb\nfrom rich import print\nfrom rich.logging import RichHandler\nfrom rich_argparse import RichHelpFormatter\nfrom rich.console import Console\nfrom rich.traceback import install\n\nconsole = Console(color_system='auto')\ninstall()\n\n\ndef drop_table(cursor, table_name: str) -> None:\n try:\n cursor.execute(f\"drop table {table_name} purge\")\n except:\n # It's possible that the table doesn't exist.\n pass\n\n\ndef prepare_database(connection) -> None:\n with console.status(\"Setting up schema\"):\n with connection.cursor() as cursor:\n # assume we connectin to Oracle Database 23c\n db_check = 'IF NOT EXISTS'\n json_type = 'JSON'\n # then check if that assumption is correct\n db_version = connection.version[0:2]\n if db_version == '19':\n db_check = ''\n json_type = 'VARCHAR2 (4000), CONSTRAINT ensure_json CHECK (podium IS JSON)'\n elif db_version == '21':\n db_check = ''\n # always drop the tables\n drop_table(cursor, 'driver_race_map')\n drop_table(cursor, 'driver')\n drop_table(cursor, 'team')\n drop_table(cursor, 'race')\n\n # create table to store data\n sql = f'''\n BEGIN\n EXECUTE IMMEDIATE 'CREATE TABLE {db_check} team\n (team_id INTEGER GENERATED BY DEFAULT ON NULL AS IDENTITY,\n name VARCHAR2(255) NOT NULL,\n points INTEGER NOT NULL,\n season INTEGER,\n CONSTRAINT team_pk PRIMARY KEY(team_id))';\n\n EXECUTE IMMEDIATE 'CREATE TABLE {db_check} driver\n (driver_id INTEGER GENERATED BY DEFAULT ON NULL AS IDENTITY,\n name VARCHAR2(255) NOT NULL,\n points INTEGER NOT NULL,\n team_id INTEGER,\n season INTEGER,\n CONSTRAINT driver_pk PRIMARY KEY(driver_id),\n CONSTRAINT driver_fk FOREIGN KEY(team_id) REFERENCES team(team_id))';\n\n EXECUTE IMMEDIATE 'CREATE TABLE {db_check} race\n (race_id INTEGER GENERATED BY DEFAULT ON NULL AS IDENTITY,\n name VARCHAR2(255) NOT NULL,\n laps INTEGER NOT NULL,\n race_date DATE,\n podium {json_type},\n CONSTRAINT race_pk PRIMARY KEY(race_id))';\n\n EXECUTE IMMEDIATE 'CREATE TABLE {db_check} DRIVER_RACE_MAP\n (driver_race_map_id INTEGER generated by default on null as identity constraint DRIVER_RACE_MAP_PK primary key,\n race_id INTEGER not null constraint DRIVER_RACE_MAP_FK1 references RACE,\n driver_id INTEGER not null constraint DRIVER_RACE_MAP_FK2 references DRIVER,\n position INTEGER)';\n\n END;'''\n cursor.execute(sql)\n console.print(\"[yellow]Schema setup completed[/yellow]\")\n\n\ndef fetch_data(connection) -> None:\n drivers_map = {}\n\n teams = {}\n driver_seq = 1\n teams_id = 1\n\n with connection.cursor() as cursor:\n # Constructors\n for year in years:\n drivers_data_map = {}\n print(f\"[magenta]Started retrieving F1 data for[/magenta] [cyan bold]{year}[/cyan bold]\")\n with console.status(\"[yellow bold]Inserting constructors[/yellow bold]\"):\n api_url = f'http://ergast.com/api/f1/{year}/constructors'\n response = requests.get(api_url)\n if response.status_code != 200:\n print(\"[red][bold]Unable to \")\n constructors = xmltodict.parse(response.text)\n rows = []\n for constructor in constructors['MRData']['ConstructorTable']['Constructor']:\n teams[constructor['Name']] = teams_id\n rows.append((teams_id, constructor['Name'], 0, int(year)))\n teams_id += 1\n cursor.executemany(\"INSERT INTO team VALUES(:teams_id, :name, :points, :season)\", rows)\n connection.commit()\n print(\"[yellow]Inserted constructors[/yellow]\")\n\n # Drivers\n with console.status(\"[yellow bold]Inserting drivers[/yellow bold]\"):\n # Get all races for the year\n api_url = 'http://ergast.com/api/f1/current'\n response = requests.get(api_url)\n data = response.text\n d = xmltodict.parse(data)\n race_list = d['MRData']['RaceTable']['Race']\n for i, race in enumerate(race_list):\n # Get a race each race\n results_url = f\"http://ergast.com/api/f1/{year}/{race['@round']}/results\"\n response = requests.get(results_url)\n race_data = xmltodict.parse(response.text)\n if race_data['MRData']['@total'] != \"0\":\n drivers_url = f\"http://ergast.com/api/f1/{year}/{race['@round']}/drivers\"\n response = requests.get(drivers_url)\n drivers_data = xmltodict.parse(response.text)\n for x in drivers_data['MRData']['DriverTable']['Driver']:\n driver_id = x['@driverId']\n api_url_driver = f'http://ergast.com/api/f1/{year}/drivers/{driver_id}/constructors'\n driver_response = requests.get(api_url_driver)\n constructor = xmltodict.parse(driver_response.text)\n logging.debug(f\"{driver_seq}, {x['GivenName']} {x['FamilyName']}, {constructor['MRData']['ConstructorTable']['Constructor']['Name']}\")\n _driver_seq = 0\n if x['@driverId'] not in drivers_map:\n logging.debug(f\"{x['@driverId']} doesn't have an id, allocating {driver_seq}\")\n drivers_map[x['@driverId']] = driver_seq\n _driver_seq = driver_seq\n driver_seq += 1\n else:\n _driver_seq = drivers_map[x['@driverId']]\n\n _constructors = constructor['MRData']['ConstructorTable']['Constructor']\n # It's possible that a driver may have changed team mid-season. If so just take the last team they drove for\n if type(_constructors) == list:\n _constructor = _constructors[:-1][0]['Name']\n else:\n _constructor = _constructors['Name']\n\n drivers_data_map[x['@driverId']] = (_driver_seq, x['GivenName'], x['FamilyName'], _constructor)\n\n rows = []\n for row in drivers_data_map.values():\n rows.append((row[0], f\"{row[1]} {row[2]}\", 0, teams[row[3]], int(year)))\n cursor.executemany('INSERT INTO driver VALUES(:driver_id, :name, :points, :team_id, :season)', rows)\n console.print(\"[yellow]Drivers inserted[/yellow]\")\n\n with console.status(\"[yellow bold]Inserting circuits[/yellow bold]\"):\n api_url = 'http://ergast.com/api/f1/current'\n response = requests.get(api_url)\n\n data = response.text\n d = xmltodict.parse(data)\n a = d['MRData']['RaceTable']['Race']\n rows = []\n for x in a:\n rows.append((x['@round'], x['RaceName'], 56, x['Date'], ''))\n cursor.executemany(\n f\"INSERT INTO race VALUES(:race_id, :name, :laps, to_date(:race_date, 'YYYY-MM-DD'), :podium)\", rows)\n console.print(\"[yellow]Circuits inserted[/yellow]\")\n\n with console.status(\"[yellow bold]Inserting results[/yellow bold]\"):\n # Results\n api_url = 'http://ergast.com/api/f1/current'\n response = requests.get(api_url)\n\n data = response.text\n d = xmltodict.parse(data)\n race_list = d['MRData']['RaceTable']['Race']\n race_driver_map_seq = 1\n for i, race in enumerate(race_list):\n results_url = f\"http://ergast.com/api/f1/{year}/{race['@round']}/results\"\n response = requests.get(results_url)\n race_data = xmltodict.parse(response.text)\n if race_data['MRData']['@total'] != \"0\":\n result_list = race_data['MRData']['RaceTable']['Race']['ResultsList']['Result']\n rows = []\n for rr in result_list:\n rows.append((race_driver_map_seq, race['@round'], drivers_map[rr['Driver']['@driverId']],\n rr['@position']))\n race_driver_map_seq += 1\n cursor.executemany(\n \"INSERT INTO driver_race_map VALUES (:driver_race_map_id, :race_id, :driver_id, :position)\",\n rows)\n console.print(\"[yellow]Results inserted\")\n\n connection.commit()\n\n\nif __name__ == \"__main__\":\n print(\"[bold magenta]F1 Data Schema Setup[/bold magenta]\")\n\n years = []\n\n parser = argparse.ArgumentParser(description='Load F1 data into database for a given year',\n formatter_class=RichHelpFormatter)\n parser.add_argument('-u', '--user', help='user/schema to insert data into', required=True)\n parser.add_argument('-p', '--password', help='password for user', required=True)\n parser.add_argument('-cs', '--connectstring', help='connectstring of target database', required=True)\n parser.add_argument('-y', '--year', help='years to populate database with (comma separated, no spaces)', required=False, default=argparse.SUPPRESS)\n parser.add_argument(\"--debug\", help=\"enable debug\", required=False, action=\"store_true\")\n\n args = parser.parse_args()\n\n if args.debug:\n FORMAT = \"%(message)s\"\n logging.basicConfig(\n level=\"NOTSET\", format=FORMAT, datefmt=\"[%X]\", handlers=[RichHandler()]\n )\n log = logging.getLogger(\"rich\")\n\n if 'year' not in args:\n years.append(datetime.date.today().year)\n else:\n years = args.year.split(',')\n\n start = time.time()\n\n connection = oracledb.connect(user=args.user, password=args.password, port=1522, dsn=args.connectstring)\n prepare_database(connection)\n fetch_data(connection)\n\n print(\"[magenta]F1 Data Loaded[/magenta]\")\n print(f\"[magenta]Finished in [/magenta][cyan]{time.time() - start:.2f} seconds[/cyan]\")\n","repo_name":"domgiles/LoadF1DataIntoDB","sub_path":"LoadF1DataIntoDB.py","file_name":"LoadF1DataIntoDB.py","file_ext":"py","file_size_in_byte":11097,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"15764479733","text":"\"\"\" This file contains a translator adapter \"\"\"\nfrom pathlib import Path\nfrom typing import NamedTuple\n\nfrom fluent_compiler.bundle import FluentBundle\nfrom fluentogram import FluentTranslator, TranslatorHub, TranslatorRunner\n\nfrom src.configuration import conf\nfrom src.language.enums import Locales\n\nLOCALES_PATH = Path(__file__).parent / \"locales\"\n\n\nclass Translator:\n \"\"\"This class is a translator adapter and will be used in the bot\"\"\"\n\n translator_runner: TranslatorRunner\n translator_hub: TranslatorHub\n\n language: str\n\n def __init__(self):\n self.translator_hub = TranslatorHub(\n root_locale=\"ru\",\n locales_map={\n \"ru\": (\"ru\",),\n },\n translators=[\n FluentTranslator(\n locale=\"ru\",\n translator=FluentBundle.from_files(\n locale=\"ru-RU\",\n filenames=[\n LOCALES_PATH / \"ru.ftl\",\n ],\n ),\n )\n ],\n )\n\n def get_text(self, key: str, language: Locales = conf.default_locale):\n \"\"\"Get text from locale with key\"\"\"\n return self.translator_hub.get_translator_by_locale(\n locale=language or self.language\n ).get(key)\n\n def __call__(self, language: str, *args, **kwargs):\n \"\"\"When instance calles it's produces LocalizedTranslator\"\"\"\n return LocalizedTranslator(\n translator=self.translator_hub.get_translator_by_locale(\n locale=language or self.language\n )\n )\n\n\nclass LocalizedTranslator:\n \"\"\"This class produced by Translator\"\"\"\n\n translator: TranslatorRunner\n\n def __init__(self, translator: TranslatorRunner):\n self.translator = TranslatorRunner\n\n def get(self, key: str) -> str:\n \"\"\"\n Get translated text with key\n :param key:\n :return:\n \"\"\"\n return self.translator.get(key)\n\n\nclass LocaleScheme(NamedTuple):\n \"\"\"Locale scheme for presentate a cache locale key\"\"\"\n\n user_id: int\n locale: Locales = conf.default_locale\n\n def __str__(self):\n return f\"{self.user_id}:{self.locale.value}\"\n","repo_name":"MassonNN/masson-mvc-aiogram-template","sub_path":"src/language/translator.py","file_name":"translator.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"11333070399","text":"def test_emotion_analysis():\n # Load the test dataset\n test_dataset = torchaudio.datasets.YESNO('.', download=True)\n # Select a sample from the dataset\n waveform, sample_rate, label = test_dataset[0]\n # Save the sample to a file\n torchaudio.save('test.wav', waveform, sample_rate)\n # Predict the emotions\n result = emotion_analysis('test.wav', sample_rate)\n # Check the result\n assert isinstance(result, list), 'The result should be a list.'\n assert all(isinstance(r, str) for r in result), 'Each element in the result should be a string.'\n assert all(r in ['anger', 'disgust', 'enthusiasm', 'fear', 'happiness', 'neutral', 'sadness'] for r in result), 'Each element in the result should be a valid emotion.'\n\ntest_emotion_analysis()","repo_name":"vixuowis/Research-2309","sub_path":"Exp-2/output/hf-eval-data-v1/f00539_test_emotion_analysis.py","file_name":"f00539_test_emotion_analysis.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"35643891592","text":"\"\"\" Data descriptors for HSMM parameters.\n\nThe parameters of a HSMM have to satisfy all sorts of properties that are\nstraightforward but tedious to check (e.g. the transition matrix has to be\nsquare, the duration matrix must have just as many rows as there are states,\netc). The job of the data descriptors in this module is to do this validation,\nso that the main :py:class:`HSMMModel` class doesn't have to worry about it.\n\nEach of the descriptors checks that its arguments are valid, and then sets\none or more private attributes on the underlying :py:class:`HSMMModel`\ninstance with the validated argument, or quantities related to it.\n\n\"\"\"\n\nimport numpy as np\n\nfrom .emissions import AbstractEmissions\n\n\nclass Durations(object):\n \"\"\" Data descriptor for a durations distribution.\n \"\"\"\n def __get__(self, obj, type=None):\n \"\"\" Return the durations distribution.\n\n Returns\n -------\n durations : numpy.ndarray, shape=(n_states, n_durations)\n Durations matrix.\n\n \"\"\"\n return getattr(obj, '_durations', None)\n\n def __set__(self, obj, durations):\n \"\"\" Update the durations distribution with new durations.\n\n Parameters\n ----------\n obj : hsmmlearn.hsmm.HSMMModel\n The underlying HSMMModel.\n durations : numpy.ndarray or list of random variables.\n This can be either a numpy array, in which case the number of\n rows must be equal to the number of hidden states, or a list\n of scipy.stats discrete random variables. In the latter case,\n the duration probabilities are obtained directly from the random\n variables.\n\n \"\"\"\n if isinstance(durations, np.ndarray):\n durations_arr = np.asarray(durations)\n if (durations_arr.ndim != 2 or\n durations_arr.shape[0] != obj.n_states):\n msg = \"Duration matrix must be 2d and have {0} rows.\".format(\n obj.n_states\n )\n raise ValueError(msg)\n else:\n if len(durations) != obj.n_states:\n raise ValueError(\"The 'durations' parameters must have \"\n \"length {}.\".format(obj.n_states))\n\n support = np.arange(1, obj.support_cutoff + 1)\n durations_arr = np.empty((obj.n_states, obj.support_cutoff))\n for k, rv in enumerate(durations):\n durations_arr[k] = rv.pmf(support)\n durations_arr /= durations_arr.sum(axis=1)[:, np.newaxis]\n\n obj._durations = durations_arr\n obj._durations_flat = durations_arr.flatten()\n\n\nclass Emissions(object):\n \"\"\" Data descriptor for an emissions distribution.\n \"\"\"\n def __get__(self, obj, type=None):\n \"\"\" Return the emissions distribution.\n\n Returns\n -------\n emissions : hsmmlearn.emissions.AbstractEmissions\n The emissions distribution.\n\n \"\"\"\n return getattr(obj, '_emissions', None)\n\n def __set__(self, obj, emissions):\n \"\"\" Set the emissions distribution.\n\n Parameters\n ----------\n obj : hsmmlearn.hsmm.HSMMModel\n The underlying HSMMModel.\n emissions : hsmmlearn.emissions.AbstractEmissions\n The emissions distribution.\n\n \"\"\"\n if not isinstance(emissions, AbstractEmissions):\n raise TypeError(\n \"Emissions parameter must be an instance of \"\n \"AbstractEmissions, but received an instance of {!r} \"\n \"instead.\".format(type(emissions))\n )\n # XXX should check that emissions match with number of states.\n obj._emissions = emissions\n\n\nclass TransitionMatrix(object):\n \"\"\" Data descriptor for a transitions matrix.\n \"\"\"\n\n def __get__(self, obj, type=None):\n \"\"\" Return the transition matrix.\n\n Returns\n -------\n tmat : numpy.ndarray, shape=(n_states, n_states)\n A transition matrix.\n\n \"\"\"\n return getattr(obj, '_tmat', None)\n\n def __set__(self, obj, value):\n \"\"\" Set a new transition matrix.\n\n Parameters\n ----------\n obj : hsmmlearn.hsmm.HSMMModel\n The underlying HSMMModel.\n value : numpy.ndarray, shape=(n_states, n_states)\n The new transition matrix. This must be a square matrix. If\n a transition matrix was previously assigned to the HSMM,\n the new transition matrix must have the same number of rows.\n\n \"\"\"\n\n tmat = self._validate_tmat(value)\n if hasattr(obj, '_tmat'):\n if obj._tmat.shape != tmat.shape:\n raise ValueError(\"New transition matrix has {} states, \"\n \"which is incompatible with old transition \"\n \"matrix, which has {} states.\".format(\n tmat.shape[0], obj._tmat.shape[0]))\n\n obj._tmat = tmat\n obj._tmat_flat = tmat.flatten()\n\n def _validate_tmat(self, tmat):\n tmat = np.asarray(tmat)\n if tmat.ndim != 2 or tmat.shape[0] != tmat.shape[1]:\n raise ValueError(\"Transition matrix must be square, \"\n \"but a matrix of shape {0} was received.\".format(\n tmat.shape))\n return tmat\n","repo_name":"jvkersch/hsmmlearn","sub_path":"hsmmlearn/properties.py","file_name":"properties.py","file_ext":"py","file_size_in_byte":5389,"program_lang":"python","lang":"en","doc_type":"code","stars":73,"dataset":"github-code","pt":"41"} +{"seq_id":"25162422363","text":"import json\r\nfrom datetime import datetime, timedelta\r\nimport functions as f\r\nimport pandas as pd\r\nimport subprocess\r\nimport time\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.linear_model import LinearRegression\r\nimport numpy as np\r\nimport os\r\n\r\nwith open('/'.join(str(__file__).replace('\\\\','/').split('/')[:-2])+'/paths_n_fun/paths_n_fun.txt') as paths_file:\r\n paths = eval(paths_file.read())\r\n paths_file.close()\r\n\r\n\r\ndef second_gai_process(d, show_plots, thresh):\r\n df_outdevice = f.dictListToDF(d['outdevice'])\r\n df_restdevice = f.dictListToDF(d['restdevice'])\r\n df_returndevice = f.dictListToDF(d['returndevice'])\r\n\r\n start_time = datetime.strptime(d['startdate'], '%Y-%m-%d %H:%M:%S')\r\n\r\n # df_restdevice['timestamp']=(df_restdevice['timestamp']).apply(lambda x: start_time+timedelta(seconds=x))\r\n # df_restdevice = df_restdevice.drop(['gravity.x', 'gravity.y','gravity.z','magneticField.x','magneticField.y','magneticField.z','magneticField.accuracy'], axis=1)\r\n # df_restdevice = df_restdevice.rename(columns={'userAcceleration.x' : 'AccelX','userAcceleration.y': 'AccelY','userAcceleration.z': 'AccelZ','attitude.y':'QuatY','attitude.w': 'QuatW','attitude.x': 'QuatX','attitude.z': 'QuatZ','rotationRate.x':'GyroX', 'rotationRate.x':'GyroX', 'rotationRate.y':'GyroY', 'rotationRate.z':'GyroZ','timestamp':'Timestamp'})\r\n # df_restdevice = df_restdevice.reindex(columns=['Timestamp', 'AccelX', 'AccelY','AccelZ','GyroX','GyroY','GyroZ','QuatW','QuatX','QuatY','QuatZ' ])\r\n # df_restdevice=df_restdevice.set_index('Timestamp')\r\n # df_restdevice[['AccelX', 'AccelY','AccelZ','GyroX','GyroY','GyroZ','QuatW','QuatX','QuatY','QuatZ']]=0\r\n\r\n df_outdevice['timestamp']=(df_outdevice['timestamp']).apply(lambda x: start_time+timedelta(seconds=x))\r\n df_outdevice = df_outdevice.drop(['gravity.x', 'gravity.y','gravity.z','magneticField.x','magneticField.y','magneticField.z','magneticField.accuracy'], axis=1)\r\n df_outdevice = df_outdevice.rename(columns={'userAcceleration.x' : 'AccelX','userAcceleration.y': 'AccelY','userAcceleration.z': 'AccelZ','attitude.y':'QuatY','attitude.w': 'QuatW','attitude.x': 'QuatX','attitude.z': 'QuatZ','rotationRate.x':'GyroX', 'rotationRate.x':'GyroX', 'rotationRate.y':'GyroY', 'rotationRate.z':'GyroZ','timestamp':'Timestamp'})\r\n df_outdevice = df_outdevice.reindex(columns=['Timestamp', 'AccelX', 'AccelY','AccelZ','GyroX','GyroY','GyroZ','QuatW','QuatX','QuatY','QuatZ' ])\r\n df_outdevice=df_outdevice.set_index('Timestamp')\r\n d2=df_outdevice\r\n s=abs(d2['AccelX'])+abs(d2['AccelY'])+abs(d2['AccelZ'])\r\n rm=s.rolling(50).mean()\r\n if thresh=='default':\r\n thresh=(np.nanmean(rm)/2)\r\n rm[rm<thresh]=0\r\n rm[rm.isna()]=0\r\n \r\n start_filter=list(rm[rm>0].index)\r\n if(len(start_filter)>0):\r\n start_filter=start_filter[0]\r\n else:\r\n start_filter=list(rm.index)[50*2]\r\n rm=rm.loc[start_filter:]\r\n rm[-1]=0\r\n rm=rm.loc[:list(rm[rm==0].index)[0]]\r\n end_filter=list(rm.index)\r\n if(len(end_filter)>0):\r\n end_filter=end_filter[-1]\r\n else:\r\n end_filter=list(d2.index)[-1]\r\n rm=rm.drop(list(rm.index)[-1])\r\n d3=d2.drop(d2[(d2.index)<start_filter].index)\r\n # d3.loc[d3[(d3.index)>end_filter].index,['AccelX', 'AccelY','AccelZ','GyroX','GyroY','GyroZ','QuatW','QuatX','QuatY','QuatZ']]=0\r\n d3=d3.drop(d3[(d3.index)>end_filter].index)\r\n df_outdevice=d3\r\n if show_plots:\r\n plt.plot(s)\r\n plt.plot(rm)\r\n plt.show()\r\n\r\n df_returndevice['timestamp']=(df_returndevice['timestamp']).apply(lambda x: start_time+timedelta(seconds=x+20))\r\n df_returndevice = df_returndevice.drop(['gravity.x', 'gravity.y','gravity.z','magneticField.x','magneticField.y','magneticField.z','magneticField.accuracy'], axis=1)\r\n df_returndevice = df_returndevice.rename(columns={'userAcceleration.x' : 'AccelX','userAcceleration.y': 'AccelY','userAcceleration.z': 'AccelZ','attitude.y':'QuatY','attitude.w': 'QuatW','attitude.x': 'QuatX','attitude.z': 'QuatZ','rotationRate.x':'GyroX', 'rotationRate.x':'GyroX', 'rotationRate.y':'GyroY', 'rotationRate.z':'GyroZ','timestamp':'Timestamp'})\r\n df_returndevice = df_returndevice.reindex(columns=['Timestamp', 'AccelX', 'AccelY','AccelZ','GyroX','GyroY','GyroZ','QuatW','QuatX','QuatY','QuatZ' ])\r\n df_returndevice=df_returndevice.set_index('Timestamp')\r\n d2=df_returndevice\r\n s=abs(d2['AccelX'])+abs(d2['AccelY'])+abs(d2['AccelZ'])\r\n rm=s.rolling(50).mean()\r\n if thresh=='default':\r\n thresh=(np.nanmean(rm)/3)\r\n rm[rm<thresh]=0\r\n rm[rm.isna()]=0\r\n start_filter=list(rm[rm>0].index)\r\n if(len(start_filter)>0):\r\n start_filter=start_filter[0]\r\n else:\r\n start_filter=list(rm.index)[50*2]\r\n rm=rm.loc[start_filter:]\r\n rm[-1]=0\r\n rm=rm.loc[:list(rm[rm==0].index)[0]]\r\n end_filter=list(rm.index)\r\n if(len(end_filter)>0):\r\n end_filter=end_filter[-1]\r\n else:\r\n end_filter=list(d2.index)[-1]\r\n rm=rm.drop(list(rm.index)[-1])\r\n d3=d2.drop(d2[(d2.index)<start_filter].index)\r\n # d3.loc[d3[(d3.index)>end_filter].index,['AccelX', 'AccelY','AccelZ','GyroX','GyroY','GyroZ','QuatW','QuatX','QuatY','QuatZ']]=0\r\n d3=d3.drop(d3[(d3.index)>end_filter].index)\r\n df_returndevice=d3\r\n if show_plots:\r\n plt.plot(s)\r\n plt.plot(rm)\r\n plt.show()\r\n # print(df_restdevice)\r\n # df_restdevice['timestamp']=(df_restdevice['timestamp']).apply(lambda x: start_time+timedelta(seconds=x))\r\n # df_restdevice = df_restdevice.drop(['gravity.x', 'gravity.y','gravity.z','magneticField.x','magneticField.y','magneticField.z','magneticField.accuracy'], axis=1)\r\n # df_restdevice = df_restdevice.rename(columns={'userAcceleration.x' : 'AccelX','userAcceleration.y': 'AccelY','userAcceleration.z': 'AccelZ','attitude.y':'QuatY','attitude.w': 'QuatW','attitude.x': 'QuatX','attitude.z': 'QuatZ','rotationRate.x':'GyroX', 'rotationRate.x':'GyroX', 'rotationRate.y':'GyroY', 'rotationRate.z':'GyroZ','timestamp':'Timestamp'})\r\n # df_restdevice = df_restdevice.reindex(columns=['Timestamp', 'AccelX', 'AccelY','AccelZ','GyroX','GyroY','GyroZ','QuatW','QuatX','QuatY','QuatZ' ])\r\n # df_restdevice=df_restdevice.set_index('Timestamp')\r\n # for col in df_restdevice.columns:\r\n # df_restdevice[col]=0\r\n\r\n data = pd.concat([df_outdevice, df_returndevice])\r\n d['matlab_ready_df']=data\r\n return d, df_outdevice\r\n\r\ndef third_gai_process(trial, prints=False):\r\n trial['matlab_ready_df'].to_csv('/'.join(str(__file__).replace('\\\\','/').split('/')[:-1])+'/out_data_here.csv')\r\n if prints==True:\r\n print(\"Data downloaded\")\r\n #malab runner\r\n command=paths.get('matlab_path')+' -nosplash -nodesktop -r \"run('+paths.get('two_lap_adj_code')+'); exit;\"' #two-lap-adj sincmotion-gait-matlab\r\n subprocess.run(command, stdout=subprocess.PIPE).stdout.decode('utf-8')\r\n start_time=time.time()\r\n if prints==True:\r\n print(\"Matlab code started\")\r\n #reading of matlab output\r\n new=False\r\n wait_time=0\r\n while new==False and wait_time<15:\r\n with open(paths.get('two_lap_adj_output'), 'r') as file: #two-lap-adj\r\n data = file.read()\r\n file.close()\r\n data=data.split('\\n')\r\n data_dict={}\r\n if(len(data)>0):\r\n for d in data[:-1]:\r\n label = d.split(': ')[0]\r\n if(len(d.split(': ')[1].split(' '))>1):\r\n label=label+' ('+' '.join(d.split(': ')[1].split(' ')[1:])+')'\r\n data_dict[label]=float(d.split(': ')[1].split(' ')[0])\r\n if(data_dict['Time of computation (unix)']>start_time):\r\n new=True\r\n time.sleep(.5)\r\n wait_time=wait_time+.5\r\n if wait_time>=15:\r\n print(\"ERROR, MATLAB CALCULATIONS THREW ERROR\")\r\n return trial\r\n if prints==True:\r\n print(\"Matlab code complete\")\r\n for d in data_dict.keys():\r\n trial['m_'+d]=data_dict.get(d)\r\n return trial\r\n\r\ndef process_gai(summary_data, token, prints=False, show_plots=False, thresh=.05, decimals=10):\r\n if(type(summary_data))==list:\r\n data=[]\r\n for t in summary_data:\r\n data.append(process_gai(t,token,))\r\n data=pd.json_normalize(data)[['record_id', 'startdate', 'redcap_repeat_instance', 'm_Time of computation (unix)', 'm_Gait symmetry (percent)', 'm_Step length (m)', 'm_Step time (sec)', 'm_Step length variability (percent)', 'm_Step time variability (percent)', 'm_Step length asymmetry (percent)', 'm_Step time asymmetry (percent)', 'm_Step velocity (m/sec)', 'm_Step count lap 1', 'm_Step count lap 2']]\r\n data=data.rename(columns={'startdate':'test_time'})\r\n data['test_time']=pd.to_datetime(data['test_time'])\r\n else:\r\n\r\n repeat_instance=summary_data['redcap_repeat_instance']\r\n for field in ['outacc', 'outdevice', 'returnacc', 'returndevice', 'restacc', 'restdevice']:\r\n summary_data[field] = (f.exportFile(summary_data['record_id'], field, token,repeat_instance=repeat_instance))\r\n if type(summary_data[field])==dict and 'items' in list(summary_data[field].keys()):\r\n summary_data[field] = summary_data[field].get('items')\r\n data = summary_data\r\n data, d2=second_gai_process(data, show_plots=show_plots, thresh=thresh)\r\n data=third_gai_process(data, prints=prints)\r\n for key in data.keys():\r\n if type(data.get(key))==float:\r\n data[key]=round(data.get(key),decimals)\r\n return data\r\n\r\n\r\n\r\ndef process_tap(cleanedTapData, prints=True, plots=False, decimals=10):\r\n if type(cleanedTapData)==list:\r\n data=[]\r\n for i in range(len(cleanedTapData)):\r\n data.append(process_tap(cleanedTapData[i], prints=False, plots=plots))\r\n data=pd.json_normalize(data)\r\n data['test_time']=pd.to_datetime(data['test_time'])\r\n return data\r\n\r\n else:\r\n ##PART ONE, NORMALIZE ANDROID AND iOS\r\n tap=cleanedTapData\r\n record_id=(tap['record_id'])\r\n test_time=tap['startdate_2']\r\n redcap_repeat_instance=tap['redcap_repeat_instance']\r\n if type(eval(tap['leftjson']))==list: #android\r\n left_hand_samples=pd.json_normalize(eval(tap['leftjson'])[0]['TappingSamples']).rename(columns={\"TappedButtonId\":\"ButtonId\"})\r\n left_hand_samples['TapCoordinate']=left_hand_samples['TapCoordinate'].str[1:-1].str.split(', ')\r\n left_hand_samples['X']=pd.to_numeric(left_hand_samples['TapCoordinate'].str[0])\r\n left_hand_samples['Y']=pd.to_numeric(left_hand_samples['TapCoordinate'].str[1])\r\n left_hand_samples['timestamp']=(left_hand_samples['duration']-min(left_hand_samples['duration']))/1000\r\n left_hand_samples['ButtonId']=left_hand_samples['ButtonId'].str.replace('TappedButton','')\r\n left_hand_samples=left_hand_samples.drop(columns=['duration', 'TapCoordinate', 'TapTimeStamp'])\r\n\r\n right_hand_samples=pd.json_normalize(eval(tap['rightjson'])[0]['TappingSamples']).rename(columns={\"TappedButtonId\":\"ButtonId\"})\r\n right_hand_samples['TapCoordinate']=right_hand_samples['TapCoordinate'].str[1:-1].str.split(', ')\r\n right_hand_samples['X']=pd.to_numeric(right_hand_samples['TapCoordinate'].str[0])\r\n right_hand_samples['Y']=pd.to_numeric(right_hand_samples['TapCoordinate'].str[1])\r\n right_hand_samples['timestamp']=(right_hand_samples['duration']-min(right_hand_samples['duration']))/1000\r\n right_hand_samples['ButtonId']=right_hand_samples['ButtonId'].str.replace('TappedButton','')\r\n right_hand_samples=right_hand_samples.drop(columns=['duration', 'TapCoordinate', 'TapTimeStamp'])\r\n\r\n \r\n\r\n e=eval(tap['leftjson'])[0]\r\n screen_size_x=float(e['TappingViewSize'][1:-1].split(', ')[0])\r\n screen_size_y=float(e['TappingViewSize'][1:-1].split(', ')[1])\r\n \r\n left_button_height=float(e['ButtonRectLeft'].split('} {')[-1][:-2].split(', ')[-1])\r\n left_button_width=float(e['ButtonRectLeft'].split('} {')[-1][:-2].split(', ')[0])\r\n left_button_midpointX=float(e['ButtonRectLeft'][2:].split(', ')[0])+(left_button_width/2)\r\n left_button_midpointY=float(e['ButtonRectLeft'][2:].split(', ')[1].split('}')[0])+(left_button_height/2)\r\n\r\n right_button_height=float(e['ButtonRectRight'].split('} {')[-1][:-2].split(', ')[-1])\r\n right_button_width=float(e['ButtonRectRight'].split('} {')[-1][:-2].split(', ')[0])\r\n right_button_midpointX=float(e['ButtonRectRight'][2:].split(', ')[0])+(right_button_width/2)\r\n right_button_midpointY=float(e['ButtonRectRight'][2:].split(', ')[1].split('}')[0])+(right_button_height/2)\r\n\r\n\r\n else: #apple\r\n \r\n left_hand_samples=pd.json_normalize(eval(tap['leftjson'])['samples']).rename(columns={\"buttonIdentifier\":\"ButtonId\",'locationY':'Y','locationX':'X'})\r\n left_hand_samples['ButtonId']=left_hand_samples['ButtonId'].str[1:]\r\n left_hand_samples['X']=pd.to_numeric(left_hand_samples['X'])\r\n left_hand_samples['Y']=pd.to_numeric(left_hand_samples['Y'])\r\n left_hand_samples['timestamp']=pd.to_numeric(left_hand_samples['timestamp'])\r\n right_hand_samples=pd.json_normalize(eval(tap['rightjson'])['samples']).rename(columns={\"buttonIdentifier\":\"ButtonId\",'locationY':'Y','locationX':'X'})\r\n right_hand_samples['ButtonId']=right_hand_samples['ButtonId'].str[1:]\r\n right_hand_samples['X']=pd.to_numeric(right_hand_samples['X'])\r\n right_hand_samples['Y']=pd.to_numeric(right_hand_samples['Y'])\r\n right_hand_samples['timestamp']=pd.to_numeric(right_hand_samples['timestamp'])\r\n\r\n e=eval(tap['leftjson'])\r\n screen_size_x=float(e['stepViewSize'].get('width'))\r\n screen_size_y=float(e['stepViewSize'].get('height'))\r\n\r\n left_button_height=float(e['buttonRect1'].get('height'))\r\n left_button_width=float(e['buttonRect1'].get('width'))\r\n left_button_midpointX=float(e['buttonRect1'].get('locationX'))+(left_button_width/2)\r\n left_button_midpointY=float(e['buttonRect1'].get('locationY'))+(left_button_height/2)\r\n\r\n right_button_height=float(e['buttonRect2'].get('height'))\r\n right_button_width=float(e['buttonRect2'].get('width'))\r\n right_button_midpointX=float(e['buttonRect2'].get('locationX'))+(right_button_width/2)\r\n right_button_midpointY=float(e['buttonRect2'].get('locationY'))+(right_button_height/2)\r\n\r\n #PART TWO, COMPUTE OUT STATISTICS\r\n\r\n data={'record_id':record_id,'test_time':test_time,'redcap_repeat_instance':redcap_repeat_instance}\r\n\r\n print_out=\"\"\r\n\r\n #notes:\r\n #right will always be positive for asymetry. for example if on the left hand the finger precisions are right:50, left:60, \r\n #the precision score for the left hand is 55 and the asymetry score for the left hand is 10 (positive because right is better)\r\n\r\n #helpers\r\n left_finger_left_hand=left_hand_samples[left_hand_samples['ButtonId']=='Left']\r\n right_finger_left_hand=left_hand_samples[left_hand_samples['ButtonId']=='Right']\r\n left_finger_right_hand=right_hand_samples[right_hand_samples['ButtonId']=='Left']\r\n right_finger_right_hand=right_hand_samples[right_hand_samples['ButtonId']=='Right']\r\n location_precision_modifier=100/np.mean([left_button_width,right_button_width])\r\n\r\n\r\n\r\n #precision #average euclidean distance between each tap and mean tap\r\n precision_left_finger_left_hand=np.mean(((left_finger_left_hand['X']-np.mean(left_finger_left_hand['X']))**2+(left_finger_left_hand['Y']-np.mean(left_finger_left_hand['Y']))**2)**.5)*location_precision_modifier\r\n precision_right_finger_left_hand=np.mean(((right_finger_left_hand['X']-np.mean(right_finger_left_hand['X']))**2+(right_finger_left_hand['Y']-np.mean(right_finger_left_hand['Y']))**2)**.5)*location_precision_modifier\r\n precision_left_finger_right_hand=np.mean(((left_finger_right_hand['X']-np.mean(left_finger_right_hand['X']))**2+(left_finger_right_hand['Y']-np.mean(left_finger_right_hand['Y']))**2)**.5)*location_precision_modifier\r\n precision_right_finger_right_hand=np.mean(((right_finger_right_hand['X']-np.mean(right_finger_right_hand['X']))**2+(right_finger_right_hand['Y']-np.mean(right_finger_right_hand['Y']))**2)**.5)*location_precision_modifier\r\n left_hand_precision=np.mean([precision_left_finger_left_hand,precision_right_finger_left_hand])\r\n right_hand_precision=np.mean([precision_left_finger_right_hand,precision_right_finger_right_hand])\r\n left_hand_precision_asym=precision_right_finger_left_hand-precision_left_finger_left_hand\r\n right_hand_precision_asym=precision_right_finger_right_hand-precision_left_finger_right_hand\r\n\r\n print_out=print_out+'\\n'+(\"LEFT HAND PRECISION: \"+str(left_hand_precision)); data['left_hand_precision']=left_hand_precision\r\n print_out=print_out+'\\n'+(\"RIGHT HAND PRECISION: \"+str(right_hand_precision)); data['right_hand_precision']=right_hand_precision\r\n print_out=print_out+'\\n'+(\"LEFT HAND PRECISION FINGER ASYMETRY: \"+str(left_hand_precision_asym)); data['left_hand_precision_asym']=left_hand_precision_asym\r\n print_out=print_out+'\\n'+(\"RIGHT HAND PRECISION FINGER ASYMETRY: \"+str(right_hand_precision_asym)); data['right_hand_precision_asym']=right_hand_precision_asym\r\n print_out=print_out+'\\n'\r\n\r\n #accuracy: #percentage of taps within the inner 95% of circle\r\n accuracy_modifier=1\r\n accuracy_left_finger_left_hand=1-(((((left_finger_left_hand['X']-left_button_midpointX)**2+(left_finger_left_hand['Y']-left_button_midpointY)**2)**.5)>(left_button_width/2)*accuracy_modifier).sum()/len(left_finger_left_hand))\r\n accuracy_right_finger_left_hand=1-(((((right_finger_left_hand['X']-right_button_midpointX)**2+(right_finger_left_hand['Y']-right_button_midpointY)**2)**.5)>(right_button_width/2)*accuracy_modifier).sum()/len(right_finger_right_hand))\r\n accuracy_left_finger_right_hand=1-(((((left_finger_right_hand['X']-left_button_midpointX)**2+(left_finger_right_hand['Y']-left_button_midpointY)**2)**.5)>(left_button_width/2)*accuracy_modifier).sum()/len(left_finger_left_hand))\r\n accuracy_right_finger_right_hand=1-(((((right_finger_right_hand['X']-right_button_midpointX)**2+(right_finger_right_hand['Y']-right_button_midpointY)**2)**.5)>(right_button_width/2)*accuracy_modifier).sum()/len(right_finger_right_hand))\r\n left_hand_accuracy=np.mean([accuracy_left_finger_left_hand,accuracy_right_finger_left_hand])\r\n right_hand_accuracy=np.mean([accuracy_left_finger_right_hand,accuracy_right_finger_right_hand])\r\n left_hand_accuracy_asym=accuracy_right_finger_left_hand-accuracy_left_finger_left_hand\r\n right_hand_accuracy_asym=accuracy_right_finger_right_hand-accuracy_left_finger_right_hand\r\n\r\n print_out=print_out+'\\n'+(\"LEFT HAND ACCURACY: \"+str(left_hand_accuracy)); data['left_hand_accuracy']=left_hand_accuracy\r\n print_out=print_out+'\\n'+(\"RIGHT HAND ACCURACY: \"+str(right_hand_accuracy)); data['right_hand_accuracy']=right_hand_accuracy\r\n print_out=print_out+'\\n'+(\"LEFT HAND ACCURACY FINGER ASYMETRY: \"+str(left_hand_accuracy_asym)); data['left_hand_accuracy_asym']=left_hand_accuracy_asym\r\n print_out=print_out+'\\n'+(\"RIGHT HAND ACCURACY FINGER ASYMETRY: \"+str(right_hand_accuracy_asym)); data['right_hand_accuracy_asym']=right_hand_accuracy_asym\r\n print_out=print_out+'\\n'\r\n\r\n #speed #average number of taps per second\r\n left_hand_speed=1/np.mean(left_hand_samples['timestamp']-left_hand_samples['timestamp'].shift(1))\r\n right_hand_speed=1/np.mean(right_hand_samples['timestamp']-right_hand_samples['timestamp'].shift(1))\r\n\r\n print_out=print_out+'\\n'+(\"LEFT HAND SPEED: \"+str(left_hand_speed)); data['left_hand_speed']=left_hand_speed\r\n print_out=print_out+'\\n'+(\"RIGHT HAND SPEED: \"+str(right_hand_speed)); data['right_hand_speed']=right_hand_speed\r\n print_out=print_out+'\\n'\r\n \r\n #stamina #coefficient of linear regression using times in between taps\r\n left_hand_stamina=(LinearRegression().fit(np.array(list(left_hand_samples.index)[2:-5]).reshape(-1, 1),1000*(left_hand_samples.loc[list(left_hand_samples.index)[1:-5],'timestamp']-left_hand_samples.loc[list(left_hand_samples.index)[1:-5],'timestamp'].shift(1)).dropna())).coef_[0]\r\n right_hand_stamina=(LinearRegression().fit(np.array(list(right_hand_samples.index)[2:-5]).reshape(-1, 1),1000*(right_hand_samples.loc[list(right_hand_samples.index)[1:-5],'timestamp']-right_hand_samples.loc[list(right_hand_samples.index)[1:-5],'timestamp'].shift(1)).dropna())).coef_[0]\r\n\r\n print_out=print_out+'\\n'+(\"LEFT HAND STAMINA: \"+str(left_hand_stamina)); data['left_hand_stamina']=left_hand_stamina\r\n print_out=print_out+'\\n'+(\"RIGHT HAND STAMINA: \"+str(right_hand_stamina)); data['right_hand_stamina']=right_hand_stamina\r\n print_out=print_out+'\\n'\r\n\r\n #double_taps #number of times user taps the same button twice instead of alternating\r\n left_hand_double_taps=((left_hand_samples['ButtonId'])==(left_hand_samples['ButtonId'].shift(1))).value_counts().get(True,default=0)\r\n right_hand_double_taps=((right_hand_samples['ButtonId'])==(right_hand_samples['ButtonId'].shift(1))).value_counts().get(True,default=0)\r\n print_out=print_out+'\\n'+(\"LEFT HAND DOUBLE TAPS: \"+str(left_hand_double_taps)); data['left_hand_double_taps']=left_hand_double_taps\r\n print_out=print_out+'\\n'+(\"RIGHT HAND DOUBLE TAPS: \"+str(right_hand_double_taps)); data['right_hand_double_taps']=right_hand_double_taps\r\n print_out=print_out+'\\n'\r\n\r\n #distance_between_taps_over_time\r\n try:\r\n left_finger_left_hand_distance_between_taps_over_time=(LinearRegression().fit(np.array(list(left_finger_left_hand.index)[1:-1]).reshape(-1, 1),((((left_finger_left_hand['X']-left_finger_left_hand['X'].shift(1))**2 + (left_finger_left_hand['Y']-left_finger_left_hand['Y'].shift(1))**2)**.5).iloc[1:-1]))).coef_[0]\r\n right_finger_left_hand_distance_between_taps_over_time=(LinearRegression().fit(np.array(list(left_finger_right_hand.index)[1:-1]).reshape(-1, 1),((((left_finger_right_hand['X']-left_finger_right_hand['X'].shift(1))**2 + (left_finger_right_hand['Y']-left_finger_right_hand['Y'].shift(1))**2)**.5).iloc[1:-1]))).coef_[0]\r\n except:\r\n left_finger_left_hand_distance_between_taps_over_time=-400\r\n right_finger_left_hand_distance_between_taps_over_time=-400\r\n try:\r\n left_finger_right_hand_distance_between_taps_over_time=(LinearRegression().fit(np.array(list(left_finger_right_hand.index)[1:-1]).reshape(-1, 1),((((left_finger_right_hand['X']-left_finger_right_hand['X'].shift(1))**2 + (left_finger_right_hand['Y']-left_finger_right_hand['Y'].shift(1))**2)**.5).iloc[1:-1]))).coef_[0]\r\n right_finger_right_hand_distance_between_taps_over_time=(LinearRegression().fit(np.array(list(right_finger_right_hand.index)[1:-1]).reshape(-1, 1),((((right_finger_right_hand['X']-right_finger_right_hand['X'].shift(1))**2 + (right_finger_right_hand['Y']-right_finger_right_hand['Y'].shift(1))**2)**.5).iloc[1:-1]))).coef_[0]\r\n except:\r\n right_finger_right_hand_distance_between_taps_over_time=-400\r\n left_finger_right_hand_distance_between_taps_over_time=-400\r\n\r\n left_hand_distance_between_taps_over_time=np.mean([left_finger_left_hand_distance_between_taps_over_time,right_finger_left_hand_distance_between_taps_over_time])\r\n right_hand_distance_between_taps_over_time=np.mean([left_finger_right_hand_distance_between_taps_over_time,right_finger_right_hand_distance_between_taps_over_time])\r\n \r\n print_out=print_out+'\\n'+(\"LEFT HAND DISTANCE BTWN TAPS OVER TIME: \"+str(left_hand_distance_between_taps_over_time)); data['left_hand_distance_between_taps_over_time']=left_hand_distance_between_taps_over_time\r\n print_out=print_out+'\\n'+(\"RIGHT HAND DISTANCE BTWN TAPS OVER TIME: \"+str(right_hand_distance_between_taps_over_time)); data['right_hand_distance_between_taps_over_time']=right_hand_distance_between_taps_over_time\r\n print_out=print_out+'\\n'\r\n\r\n #heteroskedasticity regession\r\n left_hand_time_abs_residuals=np.abs(1000*(left_hand_samples.loc[list(left_hand_samples.index)[1:-5],'timestamp']-left_hand_samples.loc[list(left_hand_samples.index)[1:-5],'timestamp'].shift(1)).dropna()-(LinearRegression().fit(np.array(list(left_hand_samples.index)[2:-5]).reshape(-1, 1),1000*(left_hand_samples.loc[list(left_hand_samples.index)[1:-5],'timestamp']-left_hand_samples.loc[list(left_hand_samples.index)[1:-5],'timestamp'].shift(1)).dropna())).predict(np.array(list(left_hand_samples.index)[2:-5]).reshape(-1, 1)))\r\n left_hand_heteroskedasticity=(LinearRegression().fit(np.array(list(left_hand_samples.index)[2:-5]).reshape(-1, 1),left_hand_time_abs_residuals)).coef_[0]\r\n right_hand_time_abs_residuals=np.abs(1000*(right_hand_samples.loc[list(right_hand_samples.index)[1:-5],'timestamp']-right_hand_samples.loc[list(right_hand_samples.index)[1:-5],'timestamp'].shift(1)).dropna()-(LinearRegression().fit(np.array(list(right_hand_samples.index)[2:-5]).reshape(-1, 1),1000*(right_hand_samples.loc[list(right_hand_samples.index)[1:-5],'timestamp']-right_hand_samples.loc[list(right_hand_samples.index)[1:-5],'timestamp'].shift(1)).dropna())).predict(np.array(list(right_hand_samples.index)[2:-5]).reshape(-1, 1)))\r\n right_hand_heteroskedasticity=(LinearRegression().fit(np.array(list(right_hand_samples.index)[2:-5]).reshape(-1, 1),right_hand_time_abs_residuals)).coef_[0]\r\n print_out=print_out+'\\n'+(\"LEFT HAND TIME HETEROSKEDASTICITY: \"+str(left_hand_heteroskedasticity)); data['left_hand_heteroskedasticity']=left_hand_heteroskedasticity\r\n print_out=print_out+'\\n'+(\"RIGHT HAND TIME HETEROSKEDASTICIT: \"+str(right_hand_heteroskedasticity)); data['right_hand_heteroskedasticity']=right_hand_heteroskedasticity\r\n print_out=print_out+'\\n'\r\n\r\n\r\n #steadiness #score from 0-100 with 100 being the best which looks to combine jumpiness/variability of placement of taps with tap in between taps\r\n left_hand_steadiness=100-(left_hand_precision-5)*2-((np.std(1000*(left_hand_samples.loc[list(left_hand_samples.index)[1:-5],'timestamp']-left_hand_samples.loc[list(left_hand_samples.index)[1:-5],'timestamp'].shift(1)).dropna()))**.5)-left_hand_double_taps**.5\r\n right_hand_steadiness=100-(right_hand_precision-5)*2-((np.std(1000*(right_hand_samples.loc[list(right_hand_samples.index)[1:-5],'timestamp']-right_hand_samples.loc[list(right_hand_samples.index)[1:-5],'timestamp'].shift(1)).dropna()))**.5)-right_hand_double_taps**.5\r\n print_out=print_out+'\\n'+(\"LEFT HAND STEADINESS: \"+str(left_hand_steadiness)); data['left_hand_steadiness']=left_hand_steadiness\r\n print_out=print_out+'\\n'+(\"RIGHT HAND STEADINESS: \"+str(right_hand_steadiness)); data['right_hand_steadiness']=right_hand_steadiness\r\n print_out=print_out+'\\n'\r\n\r\n\r\n\r\n # plt.plot(1000*(left_hand_samples.loc[list(left_hand_samples.index)[1:-5],'timestamp']-left_hand_samples.loc[list(left_hand_samples.index)[1:-5],'timestamp'].shift(1)).dropna())\r\n # plt.plot(1000*(right_hand_samples.loc[list(right_hand_samples.index)[1:-5],'timestamp']-right_hand_samples.loc[list(right_hand_samples.index)[1:-5],'timestamp'].shift(1)).dropna())\r\n # plt.show()\r\n if plots==True:\r\n fig, axes = plt.subplots(nrows=1, ncols=4, figsize=(15, 3)) \r\n axes[0].plot(left_finger_left_hand['X'],left_finger_left_hand['Y'])\r\n axes[0].plot(right_finger_left_hand['X'],right_finger_left_hand['Y'])\r\n theta = np.linspace( 0 , 2 * np.pi , 150 )\r\n radius = left_button_width/2\r\n a = radius * np.cos( theta )\r\n b = radius * np.sin( theta )\r\n axes[0].plot(left_button_midpointX + a,left_button_midpointY + b)\r\n axes[0].plot(right_button_midpointX + a,right_button_midpointY + b)\r\n axes[0].set_title('Left Hand')\r\n\r\n axes[2].plot(left_finger_right_hand['X'],left_finger_right_hand['Y'])\r\n axes[2].plot(right_finger_right_hand['X'],right_finger_right_hand['Y'])\r\n theta = np.linspace( 0 , 2 * np.pi , 150 )\r\n radius = left_button_width/2\r\n a = radius * np.cos( theta )\r\n b = radius * np.sin( theta )\r\n axes[2].plot(left_button_midpointX + a,left_button_midpointY + b)\r\n axes[2].plot(right_button_midpointX + a,right_button_midpointY + b)\r\n axes[2].set_title('Right Hand')\r\n\r\n axes[1].plot(1000*(left_hand_samples.loc[list(left_hand_samples.index)[1:-5],'timestamp']-left_hand_samples.loc[list(left_hand_samples.index)[1:-5],'timestamp'].shift(1)).dropna())\r\n axes[1].set_title('Left Hand Time Between Taps')\r\n \r\n axes[3].plot(1000*(right_hand_samples.loc[list(right_hand_samples.index)[1:-5],'timestamp']-right_hand_samples.loc[list(right_hand_samples.index)[1:-5],'timestamp'].shift(1)).dropna())\r\n axes[3].set_title('Right Hand Time Between Taps')\r\n\r\n fig.tight_layout()\r\n plt.show()\r\n\r\n for key in data.keys():\r\n if type(data.get(key))==float:\r\n data[key]=round(data.get(key),decimals)\r\n\r\n return data\r\n\r\n\r\ndef process_peg(cleanedPegData, decimals=10):\r\n if type(cleanedPegData)==list:\r\n data=[]\r\n for i in range(len(cleanedPegData)):\r\n data.append(process_peg(cleanedPegData[i]))\r\n data=pd.json_normalize(data)\r\n data['test_time']=pd.to_datetime(data['test_time'])\r\n return data\r\n else:\r\n peg=cleanedPegData\r\n record_id=peg['record_id']\r\n redcap_repeat_instance=peg['redcap_repeat_instance']\r\n test_time=peg['startdate_3']\r\n\r\n data={\r\n 'record_id':record_id,\r\n 'redcap_repeat_instance':redcap_repeat_instance,\r\n 'test_time':test_time\r\n }\r\n\r\n partitions=['dom_place', 'dom_remove', 'nondom_place', 'nondom_remove']\r\n failuress=[]\r\n time_deviations=[]\r\n for i in partitions:\r\n failures=int(eval(peg.get(i)).get('totalFailures'));failuress.append(failures)\r\n samples=pd.json_normalize(eval(peg.get(i)).get('samples'))\r\n time_deviation=round(np.std(pd.to_numeric(samples['time'])),decimals);time_deviations.append(time_deviation)\r\n\r\n data[i+'_failures']=failures\r\n data[i+'_time_deviation']=time_deviation\r\n \r\n data['average_failures']=round(np.mean(failuress),decimals)\r\n data['average_time_deviations']=round(np.mean(time_deviations),decimals)\r\n\r\n data['dom_preference_failures']=round((data['dom_place_failures']+data['dom_remove_failures']-data['nondom_place_failures']-data['nondom_remove_failures'])/2,decimals)\r\n data['dom_preference_time_deviation']=round((data['dom_place_time_deviation']+data['dom_remove_time_deviation']-data['nondom_place_time_deviation']-data['nondom_remove_time_deviation'])/2,decimals)\r\n\r\n\r\n return data","repo_name":"elfiasco/lab","sub_path":"DegenCervicalMyleopathyLab/process_tests.py","file_name":"process_tests.py","file_ext":"py","file_size_in_byte":31537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"1332981944","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\nimport time\n\nstart_time = time.time()\nfig, ax = plt.subplots()\nfalkner_skan_differential_equation = lambda eta, f, beta: [f[1], f[2], -f[0] * f[2] - beta * (1 - f[1] ** 2)]\nsecant = lambda x0, x1, f_1, f_0: x1 - (1 - f_1) * (x1 - x0) / ((1 - f_1) - (1 - f_0))\nsolve_falkner_skan_eqaution = lambda beta, guess: solve_ivp(falkner_skan_differential_equation, t_span=(0, 100), y0=[0, 0, guess], args=(beta,), t_eval=eta, method='BDF').y\n\nmin_beta, max_beta, N = -0.1988, 0.65, 40\nbeta_list, eta = list(np.linspace(min_beta, max_beta, N)), np.linspace(0, 100, int(100 / 0.001))\ncmap = plt.get_cmap('nipy_spectral', N)\nfor beta in beta_list:\n beta = np.round(beta, 4)\n guess_1, guess_2 = 1, 0.1\n f_0 = solve_falkner_skan_eqaution(beta, guess_1)\n while abs(guess_2 - guess_1) > 1E-8:\n f_1 = solve_falkner_skan_eqaution(beta, guess_2)\n guess_1, guess_2, f_0 = guess_2, secant(guess_1, guess_2, f_1[1][-1], f_0[1][-1]), f_1\n print('Done', beta)\n f, f_prime, f_double_prime = f_1[0], f_1[1], f_1[2]\n plt.plot(f_prime[:5001], eta[:5001], label=r\"$\\beta={}$\".format(beta), c=cmap(beta))\n\nplt.xlabel(r\"$\\frac{u}{U_e}$\"), plt.xlim(0, 1), plt.ylim(0, 5), plt.ylabel('$\\eta$')\nimport matplotlib as mpl\n\nnorm = mpl.colors.Normalize(vmin=min_beta, vmax=max_beta)\nsm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)\nsm.set_array([])\ncbar = plt.colorbar(sm, boundaries=np.arange(min_beta, max_beta, 0.05), ax=ax)\ncbar.ax.set_title(r\"$\\beta$\"), plt.show()\n\nprint(\"--- %s seconds --- Faster than MatLab\" % (time.time() - start_time))\n","repo_name":"Maurone7/AERSP-508","sub_path":"Project 2/Continuous_beta.py","file_name":"Continuous_beta.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"7106698420","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nimport csv\n\nnode1 = []\n\nwith open('/Users/sahiltyagi/Desktop/benchmarks/HTMjava/clean_env/HTMseqAvg.csv') as csvfile:\n#with open('/Users/sahiltyagi/Desktop/stormHTM33.csv') as csvfile:\n\treadCSV = csv.reader(csvfile, delimiter=',')\n\t#recordnum=0\n\tfor row in readCSV:\n\t\t#recordnum +=1\n\t\tlatency = float(row[1])\n\t\tif latency > 100:\n\t\t\tprint(row[0], \",\", row[1])\n\t\t\t#print(row[1])\n\n\t\tnode1.append(latency)\n\n#arr1 = [v for v in range(0, 100, 1)]\n#plt.xticks(arr1, rotation='vertical')\nfig, ax1 = plt.subplots()\nfor j in np.arange(0, 120000, 6000):\n\tax1.axhline(j, color='grey', alpha=0.1)\n\n# for j in np.arange(0, 4500, 500):\nfor j in np.arange(0, 120000, 3000):\n\tax1.axhline(j, color='grey', alpha=0.3)\n\nfor j in np.arange(0, 3000, 200):\n\tax1.axvline(j, color='grey', alpha=0.3)\n\nxbins = 200\nplt.hist(node1, bins=xbins, alpha=0.2, histtype='bar', ec='black', label='avg:1.74, min:0.25, max:2040.25 ms')\n\narr1 = [v for v in range(0, 3000, 100)]\nplt.xticks(arr1, rotation='horizontal', fontsize=7)\nax1.legend(loc='upper right', fontsize=20)\nplt.xlabel('execution time (milliseconds)', fontsize=15)\nplt.ylabel('frequency', fontsize=15)\n\nnode1=[]\nindex=[]\nwith open('/Users/sahiltyagi/Desktop/benchmarks/HTMjava/clean_env/HTMseqAvg.csv') as csvfile:\n\treadCSV = csv.reader(csvfile, delimiter=',')\n\tfor row in readCSV:\n\t\tlatency = float(row[1])\n\t\tif latency > 1000:\n\t\t\tprint(row[0], \",\", row[1])\n\t\t\trecordnum=float(row[0])\n\t\t\tnode1.append(latency)\n\t\t\tindex.append(recordnum)\n\nprint('recordnum', recordnum)\nplt.scatter(node1, index, s=2.5,c='red')\nplt.show()","repo_name":"DSC-SPIDAL/IndyCar","sub_path":"streaming/scripts/histogram.py","file_name":"histogram.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"41"} +{"seq_id":"16974869262","text":"import sys\nsys.path.insert(0, \"../\")\nsys.path.insert(0, \"./datafiles/\")\nfrom datafiles import go_term_insertinto as gti # done\n\n\n# Create, index and populate GO TERM TABLE\nsql25 = \"\"\"CREATE TABLE go_terms(\n go_term_id VARCHAR(190) PRIMARY KEY,\n go_term_name VARCHAR(190),\n go_term_type VARCHAR(190),\n go_term_def TEXT\n);\n\"\"\"\n\nsql26 = f\"\"\" {gti.values} \"\"\"","repo_name":"SMaelyss/MscProjectFinal","sub_path":"establish_db/sqlscripts/go_terms.py","file_name":"go_terms.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"18777812274","text":"# This program tests the function 'calculateMpg'\n# Its objective: calculate the MPG-Miles Per Gallon of a car.\n\nimport volp0009Library\n\nprint(\"This program calculates the MPG-Miles Per Gallon of a car.\")\n\nmiles = float(input(\"Please inform how many miles you have driven > \"))\ngallons = float(input(\"Please inform how many gallons you have used > \"))\n\nmpg = volp0009Library.calculateMpg(miles,gallons)\n\nprint(\"The MGP of a car that consumed {} gallons in {} miles is equal to {}.\" .format(gallons,miles,mpg))","repo_name":"evertonvolpi/dailyMath","sub_path":"driver1.py","file_name":"driver1.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"271672129","text":"\"\"\" Util file for Employees' Data and Attendance.\"\"\"\n\n\nfrom datetime import datetime, timedelta # To find previous month\nimport csv\n\n\ndef quit_this():\n \"\"\"Display a gentle quiting message to the user.\n\n :rtype: None\n \"\"\"\n print('\\n You chose to quit.')\n\n\ndef employee_num(input_msg, len_num):\n\n \"\"\"Show an input prompt with input_msg to user for employee's number (ID, phone).\n\n :param len_num: number of digits\n :type len_num: int\n :param input_msg: massage assigned by the caller\n :return: ID or phone number or for \"quit\"--->None\n :rtype: str, optional\n\n >>> 12345\n Input error.\n Please enter employee's ID number. Nine digits required.\n If you want to quit enter: \"quit\":\n >>> Q\n Input was blank or not digits only.\n Please enter employee's ID number. Nine digits required.\n If you want to quit enter: \"quit\":\n >>> 012345678\n Assigned number: 012345678.\n Please enter employee's name or enter \"quit\":\n >>>\n Input was blank or not digits only.\n Please enter employee's ten digit phone number without a hyphen:\n If you want to quit enter: \"quit\":\n >>>0546397320\n Assigned number: 0546397320.\n Please type in employee's birth date as in mm/dd/yyyy format or enter \"quit\":\n \"\"\"\n str_num = None\n while str_num is None:\n str_num = input(f'Please enter employee\\'s {input_msg} \\n If you want to quit enter: \"quit\": ')\n if str_num != 'quit':\n try:\n if isinstance(int(str_num), int) and len(str_num) == len_num and int(str_num) > 0:\n print(f' Assigned number: {str_num}.')\n return str_num # Let the input remain type str.\n else:\n print('\\n Input error.')\n str_num = None # To continue the while loop.\n except ValueError:\n print('\\n Input was blank or not digits only.')\n str_num = None # To continue the while loop.\n else:\n quit_this()\n break\n\n\ndef employee_name():\n \"\"\"Show an input prompt for user to insert a name.\n\n :return: the name which the user input or None\n :rtype: str, optional\n\n >>> 78\n Input error.\n Please enter employee's name or enter \"quit\":\n >>> sheri\n Assigned name: sheri.\n Please enter employee's ten digit phone number without a hyphen:\n If you want to quit enter: \"quit\":\n \"\"\"\n while True:\n entry1 = input(' Please enter employee\\'s name or enter \"quit\": ')\n if entry1 != 'quit':\n if any(x.isalpha() for x in entry1) and all(x.isalpha() or x.isspace() for x in entry1):\n print(f' Assigned name: {entry1}.')\n return entry1\n else:\n print('\\n Input error.')\n else:\n quit_this()\n break\n\n\ndef employee_birth_date():\n \"\"\"Display the message to the user to input date of birth.\n\n :return: a birth date in mm/dd/yyyy format or None\n :rtype: datetime.datetime, optional\n >>> 3/12/168\n Incorrect format. Try again.\n Please type in employee's birth date as in mm/dd/yyyy format or enter \"quit\":\n >>> 02/15/1973\n\n Assigned birth date: 02/15/1973.\n\n Employee's data added successfully to testmycsv3.csv.\n \"\"\"\n while True:\n birth_date = input(' Please type in employee\\'s birth date as in mm/dd/yyyy format or enter \"quit\": ')\n if birth_date != 'quit':\n try:\n # `strptime` throws an exception if the input doesn't match the pattern\n datetime.strptime(birth_date, \"%m/%d/%Y\")\n print(f'\\n Assigned birth date: {birth_date}.')\n return birth_date\n except ValueError:\n print(' Incorrect format. Try again.')\n else:\n quit_this()\n break\n\n\ndef read_csv_file(csv_file_path):\n \"\"\"Open and read the file csv_file_path and return a list of it's rows.\n\n :param csv_file_path: a path to a csv file between quotation marks\n :type csv_file_path: str\n :return :list of file rows\n :rtype: list [list [str]]\n \"\"\"\n with open(csv_file_path, 'r') as csv_file:\n csv_reader = csv.reader(csv_file)\n list_rows = [row for row in csv_reader]\n return list_rows\n\n\ndef write_to_csv(csv_path, row1):\n \"\"\"Open the file csv_path and write a row to it.\n\n :param csv_path: a path to a csv file between quotation marks\n :type csv_path: str\n :param row1: a list of row strings\n :type row1: list [str]\n \"\"\"\n with open(csv_path, 'w', newline='') as csv_file:\n csv_writer = csv.writer(csv_file)\n csv_writer.writerow(row1)\n\n\ndef update_file(origin_path, new_list):\n \"\"\"Open the file and write to it the rows from list.\n\n :param origin_path: a path to a csv file between quotation marks\n :type origin_path: str\n :param new_list: rows of strings\n :type new_list: list [list [str]]\n :return: None\n \"\"\"\n with open(origin_path, 'w', newline='') as f:\n csv_writer = csv.writer(f)\n csv_writer.writerows(new_list)\n print('\\n Employees csv file has been updated.')\n\n\ndef check_id_num(num, base_path): # `num` has to be type str\n \"\"\"Check if a str number is in first column of main employees data csv.\n\n :param num: a number to be looked for\n :type num: str\n :param base_path: a path to a csv file to be checked\n :type base_path: str\n :return: True if found, False otherwise.\n :rtype: bool\n\n >>> '143567892'\n False\n >>> '014138453'\n True\n\n \"\"\"\n data = [i[0] for i in read_csv_file(base_path)]\n if num in data:\n return True\n else:\n return False\n\n\n\n\ndef find_last_month():\n \"\"\"Find the previous month.\n\n :return: last_month_year %m/%Y, last_bmonth_year %b%Y (%b - Abbreviated month name)\n :rtype: (datetime.datetime)\n \"\"\"\n st_of_this_month = datetime.now().replace(day=1)\n last_month = st_of_this_month - timedelta(days=1)\n last_month_year = last_month.strftime('%m/%Y')\n last_bmonth_year = last_month.strftime('%b%Y')\n return last_month_year, last_bmonth_year\n\n\ndef approve_file():\n \"\"\"Show an input prompt for the user to insert a file path.\n\n :return: tuple (`True` if there is no missing data in the file,` False `otherwise , a file path) or defaults to None\n :rtype: (bool, str), optional\n\n Exemple:\n\n to test correct file use testmycsv.csv\n to test file missing data use testmycsv2.csv\n for file with only a header use testmycsv1.csv\n\n \"\"\"\n csv_file = None\n while csv_file is None:\n entry = input('\\n Please enter the path to your file If you want to quit enter: \"quit\": ')\n if entry != 'quit':\n csv_file_path = entry\n try:\n with open(csv_file_path, 'r') as csv_file:\n try:\n csv_reader = csv.reader(csv_file)\n except csv.Error:\n print('\\n Error in reading csv file')\n csv_file = None\n else:\n csv_file = entry\n # First line is the header with names of columns.\n next(csv_reader)\n for i in enumerate(csv_reader):\n # If file empty, len(i) will return 'None'\n if len(i):\n # Means file not empty of data. len(i) is two. i[1] is the whole row.\n if '' in i[1] or 'None' in i[1]:\n # Missing data\n return False, csv_file\n else:\n return True, csv_file\n else:\n break\n except IOError:\n print(f'\\n I/O error(file not found/ file can not be opened). Try again.')\n csv_file = None\n else:\n quit_this()\n # for quiting while loop csv_file has not to be None\n csv_file = 2\n\n\ndef print_csv_attend_file(attend_csv_path):\n \"\"\"Print the rows of the given file.\n\n :param attend_csv_path: a path to a csv file between quotation marks\n :type attend_csv_path: str\n :return: None\n\n \"\"\"\n for row2 in (read_csv_file(attend_csv_path)):\n print(row2)\n\n\ndef append_to_csv(csv_path, row3):\n \"\"\"Add row to the file.\n\n :param csv_path: a path to a csv file between quotation marks\n :type csv_path: str\n :param row3: a row as list of data strings\n :type row3: list [str]\n :return: a path to a file csv_path that a row has been written to\n :rtype: str\n\n\n \"\"\"\n with open(csv_path, 'a', newline='') as csv_file:\n csv_writer = csv.writer(csv_file)\n csv_writer.writerow(row3)\n return csv_path\n\n\ndef unique_list_id(file1, file4):\n \"\"\"Return list of rows from file file1 that are not in file file4.\n\n :param file1: a path to a csv file from which rows will be returned in a list\n :type file1: str\n :param file4: a path to a csv file which rows won't be returned\n :type file4: str\n :return: A list of row strings without the header row therefor updated[1:],can be empty.\n :rtype: list [str]\n\n ..warning: file1, file2 are csv paths between quotation marks.\n\n \"\"\"\n # seen[1:]=list of column[0] without the header line\n seen = [i[0] for i in read_csv_file(file1)]\n updated = [j for j in read_csv_file(file4) if j[0] not in seen[1:]]\n return updated[1:] # Without the header row from file4\n\n\n\n\n","repo_name":"taldew11/employee-attendance-python","sub_path":"utils_employees.py","file_name":"utils_employees.py","file_ext":"py","file_size_in_byte":9740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"22163639858","text":"# -*- coding: utf-8 -*-\nfrom flask import Flask, render_template, request\nimport random\nimport csv\nfrom faker import Faker\n\napp = Flask(__name__)\nfake = Faker('ko_KR')\n\n@app.route(\"/\")\ndef index():\n return render_template('index.html')\n\n@app.route(\"/result\")\ndef result():\n name1 = request.args.get('name1')\n name2 = request.args.get('name2')\n match = random.randrange(50,101)\n #'names.csv'라는 파일을 생성한다. -> 저장\n f = open('names.csv','a')\n a = csv.writer(f)\n a.writerow([name1,name2])\n f.close()\n return render_template('result.html', name1=name1, name2=name2, match=match)\n\n@app.route(\"/admin\")\ndef admin():\n #names에 들어가 있는 모든 이름을 출력한다.\n f = open('names.csv', 'r')\n rr = csv.reader(f)\n names = rr\n return render_template('admin.html',names=names)\n \n@app.route(\"/ffaker\")\ndef ffaker():\n name = fake.name()\n job=fake.job()\n address = fake.address()\n text = fake.text()\n \n return render_template('ffaker.html', name=name, address=address, text=text, job=job)\n\n#app.run(host='0.0.0.0', port='8080', debug=True)","repo_name":"SunjuHwang/faker","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"21426372729","text":"from django.db import models\nfrom tinymce.models import HTMLField\n\n\n\nclass Place (models.Model):\n title = models.CharField('Название', max_length=200)\n short_description = models.TextField('Краткое описание', blank=True)\n long_description = HTMLField('Полное описание', blank=True)\n lat = models.FloatField(verbose_name='Широта')\n lon = models.FloatField(verbose_name='Долгота')\n\n def __str__(self):\n return self.title\n \n class Meta: \n verbose_name_plural = 'Места'\n\n\nclass Image (models.Model):\n image = models.ImageField('Картинка')\n position = models.IntegerField('Позиция', db_index=True)\n place = models.ForeignKey('Place', on_delete=models.CASCADE, related_name='images', verbose_name='Место на карте')\n\n def __str__(self):\n view = f'{self.position} {self.place.title}'\n return view\n \n class Meta:\n ordering = ['position'] \n verbose_name_plural = 'Фотографии'","repo_name":"DmitryTokyo/where-to-go","sub_path":"places/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"21904671048","text":"# -*- coding: utf-8\n# pylint: disable=line-too-long\n\"\"\"\n The anvi'o metapangenome module.\n\n anvi-meta-pan-genome is the default client using this.\n\"\"\"\n\nimport numpy as numpy\n\nimport anvio\nimport anvio.dbops as dbops\nimport anvio.utils as utils\nimport anvio.terminal as terminal\nimport anvio.summarizer as summarizer\nimport anvio.genomedescriptions as genomedescriptions\n\nfrom anvio.errors import ConfigError\nfrom anvio.tables.miscdata import TableForLayerAdditionalData, TableForItemAdditionalData\n\n\n__author__ = \"Developers of anvi'o (see AUTHORS.txt)\"\n__copyright__ = \"Copyleft 2015-2018, the Meren Lab (http://merenlab.org/)\"\n__credits__ = []\n__license__ = \"GPL 3.0\"\n__version__ = anvio.__version__\n__maintainer__ = \"A. Murat Eren\"\n__email__ = \"a.murat.eren@gmail.com\"\n\n\n\nclass MetaPangenome(object):\n def __init__(self, args=None, run=terminal.Run(), progress=terminal.Progress()):\n self.args = args\n self.run = run\n self.progress = progress\n\n A = lambda x: args.__dict__[x] if x in args.__dict__ else None\n\n if len([p for p in [A('pan_db'), A('genomes_storage')] if not p]):\n raise ConfigError(\"MetaPangenome class should be inherited with an `args` object that contains \"\n \"an anvi'o pan database (`pan_db`), genomes storage (`genomes_storage`) :/\")\n\n self.pan_db_path = A('pan_db')\n self.genomes_storage_path = A('genomes_storage')\n self.num_threads = A('num_threads')\n\n self.fraction_of_median_coverage = A('fraction_of_median_coverage') or 0.25\n self.min_detection = A('min_detection') or 0.50\n\n # This object will be populated to give access to pan summary:\n self.pan_summary = None\n\n # This object will give access to genome descriptions, and will know everything about\n # our internal genomes. during the initialization of genomes, we will also recover the\n # sample names stored in profile databases.\n self.descriptions = None\n self.init_genome_descriptions()\n\n # go through each profile database and set sample names.\n self.sample_names = None\n self.set_sample_names()\n\n # This dict makes sure various operations in this class do not initialize\n # the summary object multiple times for genomes described in the\n # same profile database. ALTHOUGH, we currently allow only one profile database and\n # one collection (see init_genome_descriptions function). There is no theoretical\n # reason to not change this. But for now, we will keep it simple simply becasuse we\n # don't have enough test material.\n self.unique_profile_db_path_to_internal_genome_name = None\n self.set_unique_profile_db_path_to_internal_genome_name_dict()\n\n\n def init_pan_summary(self):\n self.progress.new('Pan summary')\n self.progress.update('Initializing...')\n\n args = summarizer.ArgsTemplateForSummarizerClass()\n args.pan_db = self.pan_db_path\n args.genomes_storage = self.genomes_storage_path\n args.skip_check_collection_name = True\n args.skip_init_functions = True\n args.output_dir = None\n\n self.pan_summary = summarizer.PanSummarizer(args)\n\n self.progress.end()\n\n\n def init_genome_descriptions(self):\n self.progress.new('Genome descriptions')\n self.progress.update('Initializing')\n\n self.descriptions = genomedescriptions.GenomeDescriptions(self.args)\n\n if len(self.descriptions.external_genomes_dict):\n raise ConfigError(\"Anvi'o doesn't know how you did it, but you managed to inherit this class with an \"\n \"`args` object that describes external genomes. Unfortunately anvi'o metapangneomic \"\n \"workflow only works with internal genomes since it is all about making sense of \"\n \"pangenomes in the context of metageomes. So this is not really working for us :(\")\n\n if len(set([g['profile_db_path'] for g in list(self.descriptions.internal_genomes_dict.values())])) > 1:\n raise ConfigError(\"There are multiple profile databases in your internal genomes file. We are simply \"\n \"not ready to deal with this complexity. If you think this is a mistake, let us know \"\n \"and we will work with you to make anvi'o work with multiple profile databases (in \"\n \"fact anvi'o is able to make sense of internal genomes across multiple profile \"\n \"databases, but we haven't tested it to understand potential caveats associated \"\n \"with that level of complexity).\")\n\n if len(set([g['collection_id'] for g in list(self.descriptions.internal_genomes_dict.values())])) > 1:\n raise ConfigError(\"For the sake of simplicity, we expect collection names to be identical in a given \"\n \"internal genomes file. Anvi'o is kind of a paranoid, and it apologizes for it.\")\n\n self.descriptions.load_genomes_descriptions(skip_functions=True)\n\n self.progress.end()\n\n self.run.info(\"Internal genomes found\", \"%d (%s)\" % (len(self.descriptions.internal_genome_names), ', '.join(self.descriptions.internal_genome_names)))\n\n\n def set_sample_names(self):\n \"\"\"Go through all profile databases involved, and learn all sample names\"\"\"\n\n self.sample_names = []\n\n for profile_db_path in set([g['profile_db_path'] for g in list(self.descriptions.internal_genomes_dict.values())]):\n self.sample_names.extend(sorted(list(dbops.ProfileDatabase(profile_db_path).samples)))\n\n self.run.info(\"Samples found\", \"%d (%s)\" % (len(self.sample_names), ', '.join(self.sample_names)), nl_after=1)\n\n\n def get_summary_object_for_profile_db(self, profile_db_path, init_gene_coverages=True):\n collection_name = self.descriptions.genomes[self.unique_profile_db_path_to_internal_genome_name[profile_db_path][0]]['collection_id']\n profile_db_path = self.descriptions.genomes[self.unique_profile_db_path_to_internal_genome_name[profile_db_path][0]]['profile_db_path']\n contigs_db_path = self.descriptions.genomes[self.unique_profile_db_path_to_internal_genome_name[profile_db_path][0]]['contigs_db_path']\n\n # poor-man's whatever\n bin_names_list = [self.descriptions.genomes[g]['bin_id'] for g in self.unique_profile_db_path_to_internal_genome_name[profile_db_path]]\n\n ARGS = summarizer.ArgsTemplateForSummarizerClass()\n ARGS.profile_db = profile_db_path\n ARGS.contigs_db = contigs_db_path\n ARGS.skip_init_functions = True\n ARGS.init_gene_coverages = init_gene_coverages\n ARGS.collection_name = collection_name\n ARGS.bin_names_list = bin_names_list\n ARGS.output_dir = None\n\n summary = summarizer.ProfileSummarizer(ARGS)\n summary.init()\n summary.init_collection_profile(collection_name)\n\n return summary\n\n\n def get_genomes_across_metagenomes_dict(self, data_key='mean_coverage'):\n self.progress.new('Recovering data for genomes across metagenomes')\n self.progress.update('...')\n\n genomes_across_metagenomes = {}\n for internal_genome_name in self.descriptions.internal_genome_names:\n genome_name = self.descriptions.genomes[internal_genome_name]['bin_id']\n genomes_across_metagenomes[internal_genome_name] = {}\n for sample_name in self.sample_names:\n genomes_across_metagenomes[internal_genome_name][sample_name] = 0.0\n\n D = lambda: summary.collection_profile[genome_name][data_key]\n for profile_db_path in self.unique_profile_db_path_to_internal_genome_name:\n self.progress.update('\"%s\" from profile db at %s ...' % (data_key, profile_db_path))\n summary = self.get_summary_object_for_profile_db(profile_db_path, init_gene_coverages=False)\n\n for internal_genome_name in self.unique_profile_db_path_to_internal_genome_name[profile_db_path]:\n genome_name = self.descriptions.genomes[internal_genome_name]['bin_id']\n for sample_name in D():\n genomes_across_metagenomes[internal_genome_name][sample_name] = D()[sample_name]\n\n self.progress.end()\n\n return genomes_across_metagenomes\n\n\n def set_unique_profile_db_path_to_internal_genome_name_dict(self):\n self.unique_profile_db_path_to_internal_genome_name = self.descriptions.get_unique_profile_db_path_to_internal_genome_name_dict()\n\n for profile_db_path in self.unique_profile_db_path_to_internal_genome_name:\n collection_names = set([self.descriptions.genomes[genome_name]['collection_id'] for genome_name in self.unique_profile_db_path_to_internal_genome_name[profile_db_path]])\n if len(collection_names) != 1:\n self.progress.end()\n raise ConfigError(\"You have to have the same collection for each bin originate from the same profile db.\")\n\n\n def get_gene_presence_in_the_environment_dict(self):\n if not isinstance(self.fraction_of_median_coverage, float):\n raise ConfigError(\"Fraction of median coverage must of type `float`.\")\n\n if not isinstance(self.min_detection, float):\n raise ConfigError(\"Minimum detection must be of type `float`\")\n\n self.run.info('Fraction of median coverage for core genes', self.fraction_of_median_coverage)\n self.run.info('Min detection of a genome in at last one metagenome', self.min_detection)\n\n self.progress.new('Working on gene presence/absence')\n self.progress.update('...')\n\n gene_presence_in_the_environment_dict = {}\n for profile_db_path in self.unique_profile_db_path_to_internal_genome_name:\n self.progress.update('Collection info from profile db at %s ...' % (profile_db_path))\n summary = self.get_summary_object_for_profile_db(profile_db_path)\n\n for internal_genome_name in self.unique_profile_db_path_to_internal_genome_name[profile_db_path]:\n genome_name = self.descriptions.genomes[internal_genome_name]['bin_id']\n\n self.progress.update('Working on genome %s in profile db %s ...' % (internal_genome_name, profile_db_path))\n\n # for each genome, first we will see whether it is detected in at least one metagenome\n detection_across_metagenomes = summary.collection_profile[genome_name]['detection']\n num_metagenomes_above_min_detection = [m for m in detection_across_metagenomes if detection_across_metagenomes[m] > self.min_detection]\n not_enough_detection = False if len(num_metagenomes_above_min_detection) else True\n\n gene_presence_in_the_environment_dict[genome_name] = {}\n split_names_of_interest = self.descriptions.get_split_names_of_interest_for_internal_genome(self.descriptions.genomes[internal_genome_name])\n\n genome_bin_summary = summarizer.Bin(summary, genome_name, split_names_of_interest)\n gene_coverages_across_samples = utils.get_values_of_gene_level_coverage_stats_as_dict(genome_bin_summary.gene_level_coverage_stats_dict, \"mean_coverage\")\n\n # at this point we have all the genes in the genome bin. what we need is to characterize their detection. first,\n # summarize the coverage of each gene in all samples:\n sum_gene_coverages_across_samples = dict([(gene_callers_id, sum(gene_coverages_across_samples[gene_callers_id].values())) for gene_callers_id in gene_coverages_across_samples])\n\n # now we will identify the median coverage\n median_coverage_across_samples = numpy.median(list(sum_gene_coverages_across_samples.values()))\n\n # now we will store decide whether a gene found in this genome is also found in the environment, and store that\n # information into `gene_presence_in_the_environment_dict`, and move on to the next stage.\n for gene_caller_id in sum_gene_coverages_across_samples:\n if not_enough_detection:\n _class = 'NA'\n elif sum_gene_coverages_across_samples[gene_caller_id] < median_coverage_across_samples * self.fraction_of_median_coverage:\n _class = 'EAG'\n else:\n _class = 'ECG'\n\n gene_presence_in_the_environment_dict[genome_name][gene_caller_id] = _class\n\n self.progress.end()\n\n return gene_presence_in_the_environment_dict\n\n\n def add_genomes_across_metagenomes_dict_into_pan_database(self):\n genomes_across_metagenomes_dict = self.get_genomes_across_metagenomes_dict()\n\n self.args.just_do_it = True\n TableForLayerAdditionalData(self.args).add(genomes_across_metagenomes_dict, self.sample_names)\n\n\n def add_ECG_EAG_ratio_per_gene_cluster_into_pan_database(self):\n if not self.pan_summary:\n self.init_pan_summary()\n\n gene_presence_in_the_environment_dict = self.get_gene_presence_in_the_environment_dict()\n\n self.progress.new('Working on ECG/EAG ratio per gene cluster')\n self.progress.update('...')\n\n gene_status_frequencies_in_gene_cluster = {}\n\n gene_cluster_names = list(self.pan_summary.gene_clusters.keys())\n num_gene_clusters = len(gene_cluster_names)\n for i in range(0, num_gene_clusters):\n self.progress.update('%.2f' % ((i + 1) * 100 / num_gene_clusters))\n gene_cluster_name = gene_cluster_names[i]\n\n status = {'EAG': 0, 'ECG': 0, 'NA': 0}\n for internal_genome_name in self.pan_summary.gene_clusters[gene_cluster_name]:\n genome_name = self.descriptions.genomes[internal_genome_name]['bin_id']\n\n for gene_caller_id in self.pan_summary.gene_clusters[gene_cluster_name][internal_genome_name]:\n if genome_name not in gene_presence_in_the_environment_dict:\n self.progress.end()\n raise ConfigError(\"Something is wrong... It seems you generated a pangenome with an internal genomes file \"\n \"that is not identical to the internal genomes file you are using to run this program.\")\n\n status[gene_presence_in_the_environment_dict[genome_name][gene_caller_id]] += 1\n gene_status_frequencies_in_gene_cluster[gene_cluster_name] = status\n\n # setup some boring variable names.\n items_additional_data_dict = {}\n key_ECG_EAG_ratio = 'EAG_ECG_ratio'\n key_ECGs_and_EAGs = 'ECGs_and_EAGs'\n list_ECG_EAG_keys = ['EAG', 'ECG', 'NA']\n\n self.progress.update('Setting up the items data dictionary ..')\n for gene_cluster_name in gene_status_frequencies_in_gene_cluster:\n r = gene_status_frequencies_in_gene_cluster[gene_cluster_name]\n\n # add ECG and EAG frequencies for the gene cluster\n items_additional_data_dict[gene_cluster_name] = dict([('%s!%s' % (key_ECGs_and_EAGs, status), r[status]) for status in list_ECG_EAG_keys])\n\n # add ECG / EAG ratio\n items_additional_data_dict[gene_cluster_name][key_ECG_EAG_ratio] = (r['EAG'] / (r['EAG'] + r['ECG']) if (r['EAG'] + r['ECG']) else 0)\n\n self.progress.end()\n\n # add that bad boy to the database\n self.args.just_do_it = True\n items_additional_data_keys = [('%s!%s' % (key_ECGs_and_EAGs, status)) for status in list_ECG_EAG_keys] + [key_ECG_EAG_ratio]\n TableForItemAdditionalData(self.args).add(items_additional_data_dict, items_additional_data_keys)\n\n\n def process(self):\n \"\"\"Annotates the pan database with metapangenomic information\"\"\"\n\n self.add_genomes_across_metagenomes_dict_into_pan_database()\n\n self.add_ECG_EAG_ratio_per_gene_cluster_into_pan_database()\n\n","repo_name":"merenlab/anvio","sub_path":"anvio/metapanops.py","file_name":"metapanops.py","file_ext":"py","file_size_in_byte":16058,"program_lang":"python","lang":"en","doc_type":"code","stars":390,"dataset":"github-code","pt":"41"} +{"seq_id":"10874237188","text":"\"\"\"empty message\n\nRevision ID: db05ceac2db6\nRevises: c8e1e3e02df9\nCreate Date: 2021-05-24 15:29:11.953783\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'db05ceac2db6'\ndown_revision = 'c8e1e3e02df9'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('answers', sa.Column('name', sa.String(length=64), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('answers', 'name')\n # ### end Alembic commands ###\n","repo_name":"bluemeat0724/eval_service","sub_path":"migrations/versions/db05ceac2db6_.py","file_name":"db05ceac2db6_.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"40627310273","text":"# Python\nfrom datetime import datetime\nfrom typing import Dict, List, Optional\n\n# FastApi\nfrom fastapi import APIRouter\nfrom fastapi import status\nfrom fastapi import Depends\nfrom fastapi import Body, Path, Query\nfrom sqlalchemy.orm.session import Session\n\n# App\n#from schemas import Message, MessageCreate\n\nfrom schemas import (\n TransactionCreate, TransactionShow,\n TransactionCompleteCreate, ActivityCreate,\n TransactionShowFront\n)\nimport services\nfrom .utils import (\n register_not_found, if_error_redirect_transaction,\n get_db, if_error_redirect_activity, validate_cr_and_db\n)\n\ntransaction = APIRouter(\n prefix=\"/transaction\",\n tags=[\"Transaction\"],\n)\n\n\n@transaction.get(\n path=\"/\",\n response_model=List[TransactionShow],\n status_code=status.HTTP_200_OK,\n summary=\"Show all transactions\"\n)\ndef show_all_transactions(\n skip: Optional[int] = Query(\n default=0,\n ge=0,\n title=\"Skip\",\n description=\"Take the until row for show\"\n ),\n limit: Optional[int] = Query(\n default=100,\n ge=0,\n title=\"Limit\",\n description=\"Row's number to show\"\n ),\n db: Session = Depends(get_db)\n):\n \"\"\"\n Show all Activities\n\n This path operation show all activities in the app\n\n Paramters:\n - \n\n Retrurns a json list with all activities, with the following keys\n transaction_date: date,\n - value: int,\n - detail: str,\n - transaction_id: int,\n - category: Category\n - description: Description\n - kind: Kind,\n - origin: Origin,\n - destiny: Destiny,\n - activities: [Activity],\n - created_date: datetime,\n - updated_date: datetime\n \"\"\"\n return services.get_transactions(db, skip=skip, limit=limit)\n\n\n@transaction.get(\n path=\"/{transaction_id}/search\",\n response_model=TransactionShow,\n status_code=status.HTTP_200_OK,\n summary=\"Show a transaction\"\n)\ndef show_a_transaction(\n transaction_id: int = Path(..., gt=0),\n db: Session = Depends(get_db)\n):\n \"\"\"\n Show a Transaction\n\n This path operation show a transaction in the app\n\n Paramters:\n - Register path parameter\n - transaction_id: int\n\n Retrurns a json with a transaction, with the following keys\n transaction_date: date,\n - value: int,\n - detail: str,\n - transaction_id: int,\n - category: Category\n - description: Description\n - kind: Kind,\n - origin: Origin,\n - destiny: Destiny,\n - activities: [Activity],\n - created_date: datetime,\n - updated_date: datetime\n \"\"\"\n response = services.get_transaction(db, transaction_id)\n if not response:\n register_not_found(\"Transaction\")\n return response\n\n\n@transaction.post(\n path=\"/post\",\n response_model=TransactionShow,\n status_code=status.HTTP_201_CREATED,\n summary=\"Create a Transaction\"\n)\ndef create_a_transaction(\n transaction: TransactionCreate,\n db: Session = Depends(get_db)\n):\n \"\"\"\n Create a Transaction\n\n This path operation register a transaction in the app\n\n Parameters:\n - Register body parameter\n - transaction_date: date,\n - value: int,\n - detail: str,\n - category_id: int,\n - description_id: int,\n - kind_id: int,\n - origin_id: int,\n - destiny_id: int\n\n Retrurns a json with a transaction, with the following keys\n - value: int,\n - detail: str,\n - transaction_id: int,\n - category: Category\n - description: Description\n - kind: Kind,\n - origin: Origin,\n - destiny: Destiny,\n - activities: [],\n - created_date: datetime,\n - updated_date: datetime\n \"\"\"\n response = services.create_transaction(db, transaction)\n if_error_redirect_transaction(response)\n return response\n\n\n@transaction.delete(\n path=\"/{transaction_id}/delete\",\n status_code=status.HTTP_200_OK,\n summary=\"Delete a Transaction\",\n)\ndef delete_a_transaction(\n transaction_id: int = Path(..., gt=0),\n db: Session = Depends(get_db)\n):\n \"\"\"\n Delete a Transaction\n\n This path operation delete a transaction\n\n Parameters:\n - Register path parameter\n - transaction_id: int\n\n Return a json with information about deletion\n \"\"\"\n query = services.get_activities_by_transaction_id(db, transaction_id)\n if len(query) > 0:\n for activity in query:\n services.delete_activity(db, activity.activity_id)\n response = services.delete_transaction(db, transaction_id)\n if not response:\n register_not_found(\"Transaction\")\n return response\n\n\n@transaction.put(\n path=\"/{transaction_id}/update\",\n response_model=TransactionShow,\n status_code=status.HTTP_200_OK,\n summary=\"Update a Transaction\"\n)\ndef update_a_transaction(\n transaction_id: int = Path(..., gt=0),\n transaction: TransactionCreate = Body(...),\n db: Session = Depends(get_db)\n):\n \"\"\"\n Update a Transaction\n\n This path operation update a transaction in the app\n\n Parameters:\n - Register path parameter\n - transaction_id: int\n - Register body parameter\n - transaction_date: date,\n - value: int,\n - detail: str,\n - category_id: int,\n - description_id: int,\n - kind_id: int,\n - origin_id: int,\n - destiny_id: int\n\n Retrurns a json with a transaction, with the following keys\n - value: int,\n - detail: str,\n - transaction_id: int,\n - category: Category\n - description: Description\n - kind: Kind,\n - origin: Origin,\n - destiny: Destiny,\n - activities: [Activity],\n - created_date: datetime,\n - updated_date: datetime\n \"\"\"\n response = services.update_transaction(db, transaction_id, transaction)\n if_error_redirect_transaction(response)\n return response\n\n\n@transaction.post(\n path=\"/complete_post\",\n response_model=TransactionShow,\n status_code=status.HTTP_200_OK,\n summary=\"Create a Transaction and Activites\"\n)\ndef create_an_transaction_and_activities(\n transactionComplete: TransactionCompleteCreate = Body(...),\n db: Session = Depends(get_db)\n):\n \"\"\"\n Create a Transaction and its Activites\n\n This path operation register a transaction and its activities in the app\n\n Parameters:\n - Register body parameter\n - transaction_date: date,\n - value: int,\n - detail: str,\n - category_id: int,\n - description_id: int,\n - kind_id: int,\n - origin_id: int,\n - destiny_id: int\n - activity_one: Activity\n - activity_two: Activity\n\n Retrurns a json with a transaction, with the following keys\n - value: int,\n - detail: str,\n - transaction_id: int,\n - category: Category\n - description: Description\n - kind: Kind,\n - origin: Origin,\n - destiny: Destiny,\n - activities: [Activity],\n - created_date: datetime,\n - updated_date: datetime\n \"\"\"\n transactionComplete: Dict = transactionComplete.dict()\n activity_one = transactionComplete.pop(\"activity_one\")\n activity_two = transactionComplete.pop(\"activity_two\")\n validate_cr_and_db(activity_one, activity_two)\n\n transaction = TransactionCreate(**transactionComplete)\n response = create_a_transaction(transaction, db)\n transaction_id = response.transaction_id\n\n activity_one[\"transaction_id\"] = transaction_id\n activity_one = ActivityCreate(\n **activity_one\n )\n response_activity_one = services.create_activity(db, activity_one)\n if isinstance(response_activity_one, str):\n services.delete_transaction(db, transaction_id)\n if_error_redirect_activity(response_activity_one)\n\n activity_two[\"transaction_id\"] = transaction_id\n activity_two = ActivityCreate(\n **activity_two\n )\n response_activity_two = services.create_activity(db, activity_two)\n if isinstance(response_activity_two, str):\n services.delete_activity(db, response_activity_one.activity_id)\n services.delete_transaction(db, transaction_id)\n if_error_redirect_activity(response_activity_two)\n return services.get_transaction(db, transaction_id)\n\n\n@transaction.get(\n path=\"/count\",\n status_code=status.HTTP_200_OK,\n summary=\"Return number of Transactions\"\n)\ndef count_all_transactions(\n db: Session = Depends(get_db)\n):\n \"\"\"\n Return number of Transactions\n\n This path operation counts all transactions in the app\n\n Parameters:\n - None\n\n Retrurn a json con numbers of registers:\n - registers: int\n \"\"\"\n return {\"registers\": services.count_transactions(db)}\n\n\n@transaction.get(\n path=\"/transactionShowFront\",\n response_model=List[TransactionShowFront],\n status_code=status.HTTP_200_OK,\n summary=\"Show all transactions to front\"\n)\ndef show_all_transactions(\n skip: Optional[int] = Query(\n default=0,\n ge=0,\n title=\"Skip\",\n description=\"Take the until row for show\"\n ),\n limit: Optional[int] = Query(\n default=100,\n ge=0,\n title=\"Limit\",\n description=\"Row's number to show\"\n ),\n db: Session = Depends(get_db)\n):\n \"\"\"\n Show all Transactions\n\n This path operation show all transactions in the app\n\n Paramters:\n - \n\n Retrurns a json list with all transactions, with the following keys\n transaction_date: date,\n - value: int,\n - detail: str,\n - transaction_id: int,\n - category: str\n - description: str\n - kind: str,\n - origin: str,\n - destiny: str,\n - activities: [Activity],\n \"\"\"\n return services.get_transactions_show(db, skip=skip, limit=limit)\n","repo_name":"jaortiz92/activitiesAPI","sub_path":"routes/transaction.py","file_name":"transaction.py","file_ext":"py","file_size_in_byte":9557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"41826950837","text":"from django.shortcuts import render, redirect, reverse\nfrom articles.models import Category, ArticleInfo, CommentInfo\nfrom users.models import UserProfile\nfrom markdown import markdown\nfrom django.db.models import Q\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\n\n\n# Create your views here.\n\n\ndef categorys(request, categoryid):\n category = Category.objects.get(pk=categoryid)\n articles = ArticleInfo.objects.filter(category=categoryid)\n\n # 分页\n paginator = Paginator(articles, 3)\n\n try:\n num = request.GET.get('page', 1)\n number = paginator.page(num)\n # 如果不是整数则显示第一页的内容\n except PageNotAnInteger:\n number = paginator.page(1)\n except EmptyPage:\n number = paginator.page(paginator.num_pages)\n\n return render(request, 'article_list.html', {'articles': number, 'category': category, 'num': num})\n\n\ndef get_article(request, articleid):\n article = ArticleInfo.objects.get(pk=articleid)\n comments = CommentInfo.objects.filter(comment_article=articleid)\n article_content = markdown(article.content,\n extensions=[\n # 包含 缩写、表格等常用扩展\n 'markdown.extensions.extra',\n # 语法高亮扩展\n 'markdown.extensions.codehilite',\n ])\n article.click_num += 1\n article.save()\n\n return render(request, 'article_details.html',\n {'article': article, 'comments': comments, 'article_content': article_content})\n\n\ndef add_comment(request, articleid):\n article = ArticleInfo.objects.get(pk=articleid)\n comment = request.POST.get('comment')\n person = UserProfile.objects.get(username=request.session['username'])\n\n comment_obj = CommentInfo()\n comment_obj.comment_person = person\n comment_obj.comment_article = article\n comment_obj.comment_content = comment\n comment_obj.save()\n\n # 评论数+1\n article.comment_num += 1\n article.save()\n\n return redirect(reverse('articles:article_details', args=[articleid]))\n\n\ndef search_article(request):\n # 获取关键词\n keyword = request.GET.get('search')\n # 获取包含关键词的文章\n keyword_article = ArticleInfo.objects.filter(Q(title__icontains=keyword) | Q(desc__icontains=keyword))\n\n # 分页\n paginator = Paginator(keyword_article, 3)\n\n try:\n num = request.GET.get('page', 1)\n number = paginator.page(num)\n # 如果不是整数则显示第一页的内容\n except PageNotAnInteger:\n number = paginator.page(1)\n except EmptyPage:\n number = paginator.page(paginator.num_pages)\n\n return render(request, 'search_article_list.html', {'keyword': keyword, 'articles': number, 'num': num})\n","repo_name":"jiangsir6/my_blog","sub_path":"jlfblog/articles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"348135464","text":"import sqlite3\nimport re\nimport os\n\ntry:\n import readkeys\n read_fn = readkeys.getkey\nexcept:\n import readchar\n read_fn = readchar.readkey\n print('Missing readkeys module, some features might not work properly')\n\ndef dellines(n=0):\n if n < 0: return\n print('\\r\\033[2K', end='')\n if n == 0: return\n print('\\033[1A\\r\\033[2K'*n, end='')\n\ndef cutsmart(s, n):\n i = 0\n sf = ''\n while i <= n and i < len(s):\n if s[i] == '\\x1b':\n sf += s[i:i+4]\n i+=4\n n+=4\n continue\n sf += s[i]\n i+=1\n return sf\n\ndef ceil(n):\n n_int = n//1\n if n > n_int: n_int += 1\n return int(n_int)\n\ndef regex_comp(s):\n try:\n if re.search('[A-Z]', s):\n return re.compile(rf'{s}')\n else:\n return re.compile(rf'{s}', flags=re.IGNORECASE)\n except:\n return None\n\ndef read_op(s, regex):\n so = s\n op = 0\n\n while True:\n c = read_fn()\n\n if c in ('\\x1b', '\\x1b\\x1b'):\n return s, regex, 'exit'\n elif c in ('\\r', '\\n'):\n return s, regex, 'sel'\n elif c == '\\x7f':\n if len(s) == 0:\n continue\n s = s[0:-1]\n print('\\b \\b', end='', flush=True)\n regex = regex_comp(s)\n if op == 0: op = 'rem'\n if not regex:\n continue\n elif re.search('^[^\\x00-\\x1f]$', c):\n s += c\n print(c, end='', flush=True)\n regex = regex_comp(s)\n if op == 0: op = 'add'\n if op == 'rem': op = 'redo'\n if not regex:\n continue\n elif c == '\\x1b[A':\n return s, regex, 'up'\n elif c == '\\x1b[B':\n return s, regex, 'dw'\n else:\n continue\n\n if s == so:\n continue\n return s, regex, op\n\ndef interactive_list(data):\n if type(data) != dict:\n raise TypeError('Function requires dictionary argument')\n for i in data:\n if type(data[i]) != str:\n raise TypeError('Function requires dictionary of string elements')\n results = [[i for i in data]]\n s = ''\n regex = regex_comp(s)\n op = ''\n pos = 0\n\n while True:\n l = len(results[-1])\n cols, rows = os.get_terminal_size()\n if l > rows - 4: l = rows - 4\n\n for i in results[-1][pos:pos+l]:\n el = regex.sub(\"\\033[1m\\g<0>\\033[0m\", data[i])\n print(cutsmart(el,cols-1), end='\\033[0m\\n')\n if l:\n page_t = ceil(len(results[-1])/l)\n page_i = ceil(pos/l) + 1\n else:\n page_t, page_i = 0, 0\n print()\n if page_t > 1:\n print(f'{page_i}/{page_t} ', end='')\n print(f'{len(results[-1])} results')\n print(f'--------')\n print(f'Search: {s}', end='', flush=True)\n\n s, regex, op = read_op(s, regex)\n\n if op == 'exit':\n dellines(l+3)\n return None\n elif op == 'sel':\n if l > 0 and all(data[i] == data[results[-1][0]] for i in results[-1]):\n dellines(l+3)\n return results[-1]\n elif op == 'add':\n results.append([i for i in results[-1] if regex.search(data[i])])\n pos = 0\n elif op == 'rem':\n if len(results) > 1:\n results = results[0:-1]\n pos = 0\n elif op == 'redo':\n if len(results) > 1:\n results = results[0:-1]\n results.append([i for i in results[-1] if regex.search(data[i])])\n pos = 0\n elif op == 'dw':\n if pos+l < len(results[-1]):\n pos += l\n elif op == 'up':\n if pos > 0:\n pos -= l\n if pos < 0:\n pos = 0\n\n dellines(l+3)\n","repo_name":"MatteoCampinoti94/interactive-regex-list","sub_path":"interactive_list/interactive_list.py","file_name":"interactive_list.py","file_ext":"py","file_size_in_byte":3838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"791420486","text":"import scrapy\n\n\nclass spider1(scrapy.Spider):\n name = 'Wikipedia'\n start_urls = ['https://en.wikipedia.org/wiki/Battery_(electricity)']\n\n def parse(self, response):\n pass\n\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n\ndef web(page, WebUrl):\n if page > 0:\n url = WebUrl\n code = requests.get(url)\n plain = code.text\n s = BeautifulSoup(plain, \"html.parser\")\n for link in s.findAll('a', {'class': 's-access-details-page'}):\n tet = link.get('title')\n print(tet)\n tet_2 = link.get('href')\n print(tet_2)\n\n\nenterUrl = input(\"Enter Url=\")\n\nweb(1, enterUrl)\n","repo_name":"udaychugh/web-crawler","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"38372966717","text":"from flask import Flask, request, render_template, send_file, make_response\nimport tts_rtvc\nimport tts_bark\nimport librosa\nimport torchaudio\nimport soundfile as sf\nimport time\n\napp = Flask(__name__)\nrequest_file = 'uploads/request.wav'\nresponse_file = 'uploads/response.wav'\n\n\ndef save_bytes(audio_bytes, name):\n with open(name, 'wb') as f:\n f.write(audio_bytes)\n\n\ndef process_request_audio(request):\n audio_source = request.form['source']\n audio_id = 'recorded-audio' if audio_source == 'mic' else 'input-audio'\n audio_bytes = request.files[audio_id].read()\n save_bytes(audio_bytes, request_file)\n\n\ndef generate_audio(text, model_type, input_file=request_file, output_file=response_file):\n audio, generated_audio, sr = None, None, None\n if model_type == 'bark':\n audio, sr = torchaudio.load(input_file)\n generated_audio, sr = tts_bark.clone_voice(text, audio, sr)\n elif model_type == 'rtvc':\n audio, sr = librosa.load(input_file, sr=None)\n target_sr = 16_000\n audio = librosa.resample(audio, orig_sr=sr, target_sr=target_sr)\n sr = target_sr\n generated_audio = tts_rtvc.clone_voice(text, audio, sr=target_sr)\n sf.write(file=output_file, data=generated_audio, samplerate=sr)\n\n\n@app.route('/clone_voice/', methods=['POST'])\ndef clone_voice():\n start_time = time.time()\n\n text = request.form['input-text']\n model_type = request.form['model-type']\n\n process_request_audio(request)\n generate_audio(text, model_type)\n\n response = make_response(send_file(response_file, mimetype='audio/wav', as_attachment=True))\n response.headers['time'] = str(time.time() - start_time)\n return response\n\n\n@app.route('/voice_cloning/', methods=['GET', 'POST'])\ndef voice_cloning():\n return render_template('index.html')\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=9000, debug=False)\n","repo_name":"azizsiyaev/aiclone","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"33996304258","text":"import os\n\nimport click\n\nfrom manage import cli, PFSC_ROOT\n\nSRC_DIR = os.path.join(PFSC_ROOT, 'src')\n\nKNOWN_REPOS = {\n 'moose': 'github.com/proofscape/pfsc-moose',\n}\n\n# Repo name may be mapped to an alternative name that should be used for it\n# locally. keys: repo names as in KNOWN_REPOS; values: desired local names.\nLOCAL_NAMES = {\n #'foo': 'bar',\n}\n\n# If a particular branch, tag, or commit needs to be checked out, you can set\n# that here. keys: repo names as in KNOWN_REPOS; values: ref to be checked out.\nREQUIRED_CHECKOUTS = {\n #'foo': 'topic_branch_x',\n}\n\n@cli.group()\ndef repo():\n \"\"\"\n Utilities for cloning source repos.\n \"\"\"\n pass\n\n@repo.command()\ndef known():\n \"\"\"\n List known source repos.\n \"\"\"\n N = max(len(k) for k in KNOWN_REPOS)\n f = f'%{N + 4}s %s'\n print(f % ('Name', 'Repo'))\n print(f % ('-' * N, '-' * N))\n print('\\n'.join(f % I for I in KNOWN_REPOS.items()))\n\n\ndef normalize_repo_name(name):\n if name.startswith('pfsc-'):\n name = name[5:]\n return name\n\n\ndef make_repo_url(normalized_repo_name):\n base = KNOWN_REPOS[normalized_repo_name]\n prefix = ''\n if base.startswith('github.com/'):\n # Read GitHub username and personal access token from environment, if defined:\n GH_USER = os.getenv('GH_USER')\n GH_PAT = os.getenv('GH_PAT')\n if GH_USER and GH_PAT:\n prefix = f'{GH_USER}:{GH_PAT}@'\n url = f'https://{prefix}{base}.git'\n return url\n\n\n@repo.command()\n@click.option('--dry-run', is_flag=True, help=\"Do not actually clone; just print the clone command.\")\n@click.argument('repo')\ndef clone(dry_run, repo):\n \"\"\"\n Clone source repo REPO into the src dir.\n\n REPO should be a repo name (without .git), such as \"server\" or \"ise\".\n\n See `pfsc repo known` command, to list all known names.\n \"\"\"\n repo = normalize_repo_name(repo)\n if not repo in KNOWN_REPOS:\n raise click.UsageError(f'Unknown repo {repo}')\n url = make_repo_url(repo)\n clone_cmd = f'git clone {url}'\n full_cmd = f'cd {SRC_DIR}; {clone_cmd}'\n\n local_name = url.split('/')[0][:-4]\n if repo in LOCAL_NAMES:\n local_name = LOCAL_NAMES[repo]\n full_cmd += f' {local_name}'\n\n ref = REQUIRED_CHECKOUTS.get(repo, 'main')\n full_cmd += f'; cd {local_name}; git fetch; git checkout {ref}'\n\n if dry_run:\n print(full_cmd)\n else:\n print(clone_cmd)\n os.system(full_cmd)\n","repo_name":"proofscape/pise","sub_path":"manage/tools/repo.py","file_name":"repo.py","file_ext":"py","file_size_in_byte":2435,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"4152712668","text":"\n\n# Greedy Algorithm\n\nt = int(input())\n\nfor _ in range(t):\n n = int(input())\n a = []\n for __ in range(n):\n a.append(list(map(int, input().split())))\n a.sort(key=lambda x: x[1])\n count = 0\n j = 0\n for i in range(n):\n if a[i][0] >= a[j][1]:\n count += 1\n j = i\n print(count)","repo_name":"gabriele-tombesi/codex_optimal_proj","sub_path":"Completions/davinci_runs/test/test_T0.5_k2_1000/intro-questions.txt_dir/4527/first_pys/solution_1.py","file_name":"solution_1.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"41"} +{"seq_id":"15009060403","text":"from fastapi import FastAPI\nfrom pydantic import BaseModel\n\n\nclass Todo(BaseModel):\n title: str\n desc: str\n\n\ntodos: list[Todo] = []\n\napp = FastAPI()\n\n\n@app.get(\"/\")\nasync def home():\n return \"Hello World\"\n\n\n@app.get(\"/todos\")\nasync def get_todos():\n return todos\n\n\n@app.post(\"/todos\")\nasync def add_todo(todo: Todo):\n todos.append(todo)\n return todo\n\n\n@app.post(\"/add-todo\")\nasync def addd_todo(title: str, desc: str):\n todo = Todo(title=title, desc=desc)\n todos.append(todo)\n return todo\n\n\n@app.get(\"/hello\")\nasync def say_hi(name: str):\n return f\"Hello {name.title()}?\"\n","repo_name":"thee-dushbag/code","sub_path":"live/python/general_/play/todo-app/backend/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"31969534694","text":"# -*- coding:utf-8 -*-\n# 思路:利用双端队列,双端队列只存储可能成为窗口最大值的下标\n# 滑动到第i个元素,当第i个元素大于队尾元素时,队尾元素出队,因为队尾元素不可能再成为接下来窗口的最大值了\n# 当第i个元素小于队尾元素时,第i个元素入队\n# 同时需要不断监测窗口的大小,当窗口满时,需要将队首元素出队\n\nfrom collections import deque\nclass Solution:\n def maxInWindows(self, num, size):\n if size == 0 or size > len(num):\n return []\n\n d = deque()\n for i in range(size):\n while len(d) > 0 and num[i] > num[d[-1]]:\n d.pop()\n d.append(i)\n\n res = []\n\n for i in range(size, len(num)):\n res.append(num[d[0]])\n while len(d) > 0 and num[i] > num[d[-1]]:\n d.pop()\n d.append(i)\n while len(d) > 0 and d[0] + size == i:\n d.popleft()\n\n res.append(num[d[0]])\n return res\n\nif __name__ == '__main__':\n print(Solution().maxInWindows(\n[9,10,9,-7,-3,8,2,-6],5))\n\n","repo_name":"lp2016/coding","sub_path":"滑动窗口最大值.py","file_name":"滑��窗口最大值.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"21563928565","text":"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport re\nimport webbrowser as wb\n\n'''\n\tINDEED \"https://www.indeed.com/jobs?q=\" + search_query + \"&l=Long+Beach%2C+CA\"\n\tCRAIGSLIST \"https://\" + greater_area_query + \"craigslist.org/d/\" + field_of_work + \"/search/\" + minor_area + \"/\" + field_abbrev\n\tCAREERONESTOP \"https://www.careeronestop.org/Toolkit/Jobs/find-jobs.aspx?keyword=\" + keyword + \"&location=\" + location + \"&radius=\" + distance\n'''\n\nclass Listing():\n\t'''\n\t\tRepresents a listing or a result from the search query\n\t'''\n\tdef __init__(self, _title=\"None\", _company=\"None\", _location=\"None\", _date=\"None\", _link=\"None\"):\n\t\tself.title = _title\n\t\tself.company = _company\n\t\tself.location = _location\n\t\tself.date = _date\n\t\tself.link = _link\n\n\tdef get_title(self):\n\t\treturn self.title\n\n\tdef get_company(self):\n\t\treturn self.company\n\n\tdef get_location(self):\n\t\treturn self.location\n\n\tdef get_date(self):\n\t\treturn self.date\n\n\tdef get_link(self):\n\t\treturn self.link\n\ndef career_one_stop(_keyword, _location, _distance, _size):\n\turl = \"https://www.careeronestop.org/Toolkit/Jobs/find-jobs.aspx?keyword=\" + _keyword + \"&location=\" + _location + \"&radius=\" + _distance + \"&pagesize=\" + _size\n\t# &source=AJE\n\tj_sauce = urlopen(url).read()\n\tj_soup = BeautifulSoup(j_sauce, 'html.parser')\n\n\tresults = j_soup.find('div', {'class': re.compile(\"div-Messages\")})\n\tnum_results = results.find('strong').text\n\tprint(num_results)\n\ttable = j_soup.find('table', {'class': re.compile(\"res-table\")})\n\trows = table.findAll('tr')\n\n\t#The first item is the table header...\n\trows.pop(0)\n\n\tinfo = list()\n\n\tfor _ in rows:\n\t\ttitle_wrapper = _.find('td', {'data-title': re.compile(\"Job Title\")})\n\t\ttitle = title_wrapper.text.strip()\n\t\tlink = title_wrapper.find('a').get('href')\n\t\tcompany =_.find('td', {'data-title': re.compile(\"Company\")}).text.strip()\n\t\tlocation = _.find('td', {'data-title': re.compile(\"Location\")}).text.strip()\n\t\tdate = _.find('td', {'data-title': re.compile(\"Date Posted\")}).text.strip()\n\t\t\n\t\titem = Listing(_title=title, _company=company, _location=location, _date=date, _link=link)\n\t\tinfo.append(item)\n\n\tfor _ in info:\n\t\tprint(\" ____ \\n\")\n\t\tprint(\"Title: \" + _.get_title() + \"\\n\")\n\t\tprint(\"Company: \" + _.get_company() + \"\\n\")\n\t\tprint(\"Location: \" + _.get_location() + \"\\n\")\n\t\tprint(\"Date: \" + _.get_date() + \"\\n\")\n\t\tprint(\"Link: \" + _.get_link() + \"\\n\")\n\n\treturn info\n\ndef view_in_browser(view_count=0):\n\tfor i in range(view_count):\n\t\t\twb.open_new(listings[i].get_link())\n\nif __name__ == \"__main__\":\n\n\tkeyword = input(\"Enter key words for job search: \")\n\tkeyword = keyword.replace(' ', '%20'.format())\n\tlocation = input(\"Enter a zip code: \")\n\tdistance = input(\"Enter the distance: \")\n\tsize = input(\"Enter the max number of results: \")\n\n\tlistings = career_one_stop(_keyword=keyword, _location=location, _distance=distance, _size=size)\n\t\n\tn = int(input(\"How many would you like to open: \"))\n\n\tview_in_browser(view_count=n)\n","repo_name":"rgabeflores/Job-Scrape","sub_path":"j_scrape.py","file_name":"j_scrape.py","file_ext":"py","file_size_in_byte":2938,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"37648759454","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom fixture.session import SessionHelper\nfrom fixture.project import ProjectHelper\nfrom fixture.soap import SoapHelper\n\n\nclass Application:\n\n def __init__(self, browser, base_url):\n if browser == \"firefox\":\n self.driver = webdriver.Firefox()\n elif browser == \"chrome\":\n self.driver = webdriver.Chrome()\n elif browser == \"edge\":\n self.driver = webdriver.Edge()\n else:\n raise ValueError(\"Unrecognized browser %s\" % browser)\n self.base_url = base_url\n self.session = SessionHelper(self)\n self.project = ProjectHelper(self)\n self.soap = SoapHelper(self)\n\n def open_home_page(self):\n self.driver.get(self.base_url)\n\n def is_valid(self):\n try:\n self.driver.current_url\n return True\n except:\n return False\n\n\n def destroy(self):\n self.driver.quit()\n","repo_name":"DaryaSC/python_training_mantis","sub_path":"fixture/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"29255746848","text":"import os\nimport time\nimport re\nfrom slackclient import SlackClient\n# from __future__ import print_function\nimport datetime\nfrom googleapiclient.discovery import build\nfrom httplib2 import Http\nfrom oauth2client import file, client, tools\nfrom get_piazza_data import PiazzaWrapper\nimport random\n\n# instantiate Slack client\nslack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))\ncalendar_id = os.environ.get('CALENDAR_ID')\ncourse_id = os.environ.get('COURSE_ID')\nTA_LIST = ['Einstein', 'Feynman', 'Sagan']\nHAPPY_MSGS = ['Yay!','Hurray!!','Good Job!']\n# starterbot's user ID in Slack: value is assigned after the bot starts up\nstarterbot_id = None\n\n# constants\nSCOPES = 'https://www.googleapis.com/auth/calendar.readonly'\nRTM_READ_DELAY = 1 # 1 second delay between reading from RTM\nEXAMPLE_COMMAND = \"do\"\nMENTION_REGEX = \"^<@(|[WU].+?)>(.*)\"\n\npiazza = PiazzaWrapper(course_id=course_id)\n\n\ndef parse_bot_commands(slack_events):\n \"\"\"\n Parses a list of events coming from the Slack RTM API to find bot commands.\n If a bot command is found, this function returns a tuple of command and channel.\n If its not found, then this function returns None, None.\n \"\"\"\n for event in slack_events:\n # print(event)\n if event[\"type\"] == \"message\" and not \"subtype\" in event:\n user_id, message = parse_direct_mention(event[\"text\"])\n if user_id == starterbot_id:\n return message, event[\"channel\"]\n elif event[\"type\"] == \"message\" and \"subtype\" in event:\n if event[\"subtype\"] == 'bot_message' and event['username'] == 'IFTTT':\n print(event)\n # print(event[\"attachments\"][0]['pretext'])\n if \"attachments\" in event:\n message = event[\"attachments\"][0]['pretext']\n user_id, _ = parse_direct_mention(event[\"attachments\"][0][\"pretext\"])\n return message, event[\"channel\"]\n return None, None\n\ndef parse_direct_mention(message_text):\n \"\"\"\n Finds a direct mention (a mention that is at the beginning) in message text\n and returns the user ID which was mentioned. If there is no direct mention, returns None\n \"\"\"\n matches = re.search(MENTION_REGEX, message_text)\n # the first group contains the username, the second group contains the remaining message\n return (matches.group(1), matches.group(2).strip()) if matches else (None, None)\n\ndef handle_command(command, channel):\n \"\"\"\n Executes bot command if the command is known\n \"\"\"\n command = command.lower()\n # Default response is help text for the user\n default_response = \"Not sure what you mean. Try *{}*.\".format(EXAMPLE_COMMAND)\n\n # Finds and executes the given command, filling in response\n response = None\n # This is where you start to implement more commands!\n if command.startswith(EXAMPLE_COMMAND):\n response = \"Sure...write some more code then I can do that!\"\n slack_client.api_call(\n \"chat.postMessage\",\n channel=channel,\n text=response or default_response)\n\n elif 'help' in command:\n response = \"\"\"You can ask me the following questions\\n\"\"\"\n response += \"\"\" what's the schedule?\\n\"\"\"\n response += \"\"\"who is the TA tomorrow?\\n\"\"\"\n response += \"\"\"who is the TA today?\\n\"\"\"\n response += \"\"\"how was piazza today?\\n\"\"\"\n slack_client.api_call(\"chat.postMessage\",channel=channel,text=response)\n\n elif 'schedule' in command:\n events = get_events()\n for event in events:\n start = event['start'].get('dateTime', event['start'].get('date'))\n # print(start, event['summary'])\n if(event['summary'] in TA_LIST):\n slack_client.api_call(\n \"chat.postMessage\",\n channel=channel,\n text=start[:10]+' '+event['summary'] or default_response)\n\n elif 'who' in command and 'tomorrow' in command:\n\n slack_client.api_call(\n \"chat.postMessage\",\n channel=channel,\n text=\"\"\"Tomorrow's piazza TA is \"\"\"+get_TA(1) or default_response)\n # Sends the response back to the channel\n elif 'who' in command and 'today' in command:\n\n slack_client.api_call(\n \"chat.postMessage\",\n channel=channel,\n text=\"\"\"Today's piazza TA is \"\"\"+get_TA(0) or default_response)\n\n elif 'piazza' in command:\n count, count_i, count_s, count_unanswered, unanswered_posts = piazza.get_count_today()\n followup_count = piazza.get_unanswered_followup()\n response = \"\"\" Today's piazza TA was \"\"\" + get_TA(0) + \"\"\"\\n We had a total of \"\"\" + str(count) + \" posts today\"\n response += \"\"\"\\n Instructors answered \"\"\" + str(count_i) + \" posts\"\n response += \"\"\"\\n Students answered \"\"\" + str(count_s) + \" posts (No instructor answers)\\n\"\n if count_unanswered != 0:\n response += str(count_unanswered) + \"\"\" posts have no answers\"\"\"\n response += \"\"\"\\n The following posts need our attention: \\n\"\"\"\n response += ''.join('@'+str(x)+'\\n' for x in unanswered_posts)\n else:\n response += \"\"\" We caught all questions today! \"\"\"+ random.choice(HAPPY_MSGS)\n if followup_count>0 and count_unanswered == 0:\n response += \"\"\"\\n However, we still have \"\"\" +str(followup_count)+ \"\"\" unanswered followups\"\"\"\n else:\n response += \"\"\"\\n Also, we still have \"\"\" + str(followup_count) + \"\"\" unanswered followups\"\"\"\n\n slack_client.api_call(\"chat.postMessage\",channel=channel,text=response)\n\n else:\n slack_client.api_call(\"chat.postMessage\", channel=channel, text=\"\"\"Sorry! I don't understand that command\"\"\")\n\n\ndef get_TA(days_from_now):\n events = get_events()\n response = \"\"\n for event in events:\n start = event['start'].get('dateTime', event['start'].get('date'))\n tomorrow = datetime.datetime.today()+ datetime.timedelta(days=days_from_now)\n tomorrow = tomorrow.strftime(\"%Y-%m-%d\")\n date_tomorrow = tomorrow[:10]\n # print(date_tomorrow)\n # print(start, event['summary'])\n if (event['summary'] in TA_LIST):\n if start[:10] == date_tomorrow:\n if event['summary'] not in response:\n response += event['summary'] + \" \"\n\n return response\n\ndef get_events():\n \"\"\"Shows basic usage of the Google Calendar API.\n Prints the start and name of the next 10 events on the user's calendar.\n \"\"\"\n # The file token.json stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n store = file.Storage('token.json')\n creds = store.get()\n if not creds or creds.invalid:\n flow = client.flow_from_clientsecrets('credentials.json', SCOPES)\n creds = tools.run_flow(flow, store)\n service = build('calendar', 'v3', http=creds.authorize(Http()))\n\n # Call the Calendar API\n now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time\n events_result = service.events().list(calendarId=calendar_id, timeMin=now,\n maxResults=10, singleEvents=True,\n orderBy='startTime').execute()\n events = events_result.get('items', [])\n\n if not events:\n print('No upcoming events found.')\n for event in events:\n start = event['start'].get('dateTime', event['start'].get('date'))\n print(start, event['summary'])\n return events\n\nif __name__ == \"__main__\":\n if slack_client.rtm_connect(with_team_state=False):\n print(\"Starter Bot connected and running!\")\n # Read bot's user ID by calling Web API method `auth.test`\n starterbot_id = slack_client.api_call(\"auth.test\")[\"user_id\"]\n while True:\n command, channel = parse_bot_commands(slack_client.rtm_read())\n if command:\n handle_command(command, channel)\n time.sleep(RTM_READ_DELAY)\n else:\n print(\"Connection failed. Exception traceback printed above.\")\n","repo_name":"kniranjankumar/PiazzaBot","sub_path":"PiazzaBot/run_piazzabot.py","file_name":"run_piazzabot.py","file_ext":"py","file_size_in_byte":8265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"14496144648","text":"import pandas as pd\n\n# Usando la funcion read_csv para leer el archivo csv\ndf = pd.read_csv(\"archivos\\\\datos.csv\")\ndf2 = pd.read_csv(\"archivos\\\\datos.csv\")\n#obteniendo los datos de la columna nombre\nnombre = df[\"nombre\"]\n\n# Ordenando el DataFrame por la columna de edad\ndf_ordenado = df.sort_values(\"nombre\")\n\n#ordenandolo de forma decendente\ndf_ordenado = df.sort_values(\"nombre\", ascending=False)\n\n#concatenando los dos dataframes\ndf_concatenado = pd.concat([df,df2])\n\n#accediendo a la primeras 2 filas con head()\nprimeras_fila = df.head(2)\n\n#accediendo a las ultimas 2 filas con tail()\nultimas_filas = df.tail(2)\n\n#accediendo a la cantidad de filas y columnas con shape\n\nfilas_totales,columnas_totales= df.shape\n\n#obteniendo data estadistica del df\ndf_info = df.describe()\n\n#accediendo a un elemento especifico (edad)con iloc\ndf_especifico_ilock = df.iloc[2,2]\n\n#accediendo a un elemento especifico (edad)con loc\ndf_especifico = df.loc[2,\" edad\"]\n\n#accediendo a todas las filas de una columna\napellido = df.iloc[:,1] \n#accediendo a todas las columna de una filas (loc)\nfila_3 = df.loc[2,:]\n#accediendo a todas las columna de una filas (iloc)\nfila_3 = df.iloc[2,:]\n\n#accediendo filas donde eddad >30 ( datos donde [\"edad\"] > x / [\"edad\"] < x ) \nedad_mayor_30 = df.loc[df[\" edad\"]>30,:]\nprint(edad_mayor_30)\n\n\n ","repo_name":"Aaron09py/Program_practic","sub_path":"archivos/leer_csv_con_pandas.py","file_name":"leer_csv_con_pandas.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"41855596734","text":"discount = 1\nrating_discount = 1\nprice = 1\ndays_to_stay = int(input())\nnight_stay = days_to_stay - 1\ntype_of_room = input() # \"room for one person\" or \"apartment\" or \"president apartment\"\nrating = input() # \"positive\" or \"negative\"\n\nif type_of_room == \"room for one person\":\n price = 18.00\nelif type_of_room == \"apartment\":\n price = 25.00\n if night_stay < 10:\n discount = 0.3\n elif night_stay < 15:\n discount = 0.35\n elif night_stay >= 15:\n discount = 0.5\nelif type_of_room == \"president apartment\":\n price = 35.00\n if night_stay < 10:\n discount = 0.1\n elif night_stay < 15:\n discount = 0.15\n elif night_stay >= 15:\n discount = 0.2\n\nprice_for_stay = (night_stay * price)\nprice_whit_discount = price_for_stay - (price_for_stay * discount)\nif price_whit_discount == 0.00:\n price_whit_discount = price_for_stay\nif rating == \"positive\":\n rating_discount = 1.25\nelif rating == \"negative\":\n rating_discount = 0.9\n\ntotal_price = price_whit_discount * rating_discount\nprint(f\"{total_price:.2f}\")\n","repo_name":"Nenogzar/LearningPython","sub_path":"softuni/basics_programming/03_pb_examp/2023_10_14_15_programming_basics_online_pre_exam/03_Santas_holiday.py","file_name":"03_Santas_holiday.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"}