diff --git "a/4774.jsonl" "b/4774.jsonl"
new file mode 100644--- /dev/null
+++ "b/4774.jsonl"
@@ -0,0 +1,140 @@
+{"seq_id":"32105322762","text":"from typing import Tuple\n\nimport tensorflow as tf\nimport pandas as pd\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.models import Sequential\nimport pickle\n\n\ndef premier_modele():\n dataset = tf.keras.preprocessing.image_dataset_from_directory(\n \"data/01_raw/Images\")\n\n # set the breed of dogs that the program will be classifying\n breeds = dataset.class_names\n\n # Set the arguments for the tensorflow instance\n args = {\n 'labels': 'inferred', # Infers the name of the dog by the name of the directory the picture is in\n 'label_mode': 'categorical', # Each breed is one category\n 'batch_size': 32, # how many images are loaded and processed at once by neural network\n 'image_size': (224, 224), # resize all images to the same size\n 'seed': 1, # set seed for reproducability\n 'validation_split': .2, # split training and testing : 80% train and 20% test\n 'class_names': breeds # name of the categories\n }\n\n # Training data\n\n train = tf.keras.utils.image_dataset_from_directory( # Loads images from directory into tensorflow training dataset\n \"data/01_raw/Images\",\n subset='training',\n **args\n )\n\n # Test Data\n\n test = tf.keras.utils.image_dataset_from_directory( # Loads images from directory into tensorflow testing dataset\n \"data/01_raw/Images\",\n subset='validation',\n **args\n )\n train = train.cache().prefetch(\n buffer_size=tf.data.AUTOTUNE) # Caches pictures in memory rather than hard disk to make algorithm more\n # efficient\n test = test.cache().prefetch(\n buffer_size=tf.data.AUTOTUNE) # Caches pictures in memory rather than hard disk to make algorithm more\n # efficient\n\n model = Sequential ([\n layers.Rescaling(1./255), # Pixels in numpy array are from 0 - 255, so we rescale the pixels into numbers between 0-1 in order to help neural network be more efficient\n layers.Conv2D(16,3,padding='same',activation='relu',input_shape=(224,224,3)), # Create a convulutional layer that scans images and generates new matrices with features from the images, will do this 16 times, looking at 3x3 pixels nat a time(window)\n layers.Flatten(),\n layers.Dense(128,activation='relu'), # dense network will take flattened layer and help facilitate predictions\n layers.Dense(64,activation='relu'),\n #layers.Dense(len(breeds)),\n layers.Dense(len(breeds), activation='softmax')\n])\n\n # Compile the model\n model.compile(optimizer='adam', loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True), metrics=[\n 'accuracy']) # optimizer tells model how to predict error and how to iterate, and loss function calculates\n # error\n\n # fit the model\n history = model.fit(\n train,\n validation_data=test,\n epochs=10,\n verbose=1\n )\n data = {\n \"train\": train,\n \"test\": test,\n }\n flat_data = list(data.values())\n packed_data = tf.nest.pack_sequence_as(tf.nest.flatten(data), flat_data)\n unpacked_data = tf.nest.map_structure(lambda x: list(x.as_numpy_iterator()), packed_data)\n variable_retourne = (breeds, unpacked_data)\n f1 = open('node1tonode2picklefile', 'wb')\n pickle.dump(variable_retourne, f1)\n f1.close()\n history_df = pd.DataFrame.from_dict(history.history)\n return history_df\n","repo_name":"Mikamikaz/methodologie-pour-la-science-des-donnees","sub_path":"kedro/kedro-image-classification-dogs/src/kedro_image_classification_dogs/pipelines/data_science/nodes_packages/code1.py","file_name":"code1.py","file_ext":"py","file_size_in_byte":3376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"14807673187","text":"from tap_tester import connections, runner\nfrom base import TestPendoBase\nfrom datetime import datetime\n\nclass PendoChildStreamStartDateTest(TestPendoBase):\n\n def name(self):\n return \"pendo_child_stream_start_date_test\"\n\n def test_run(self):\n\n streams_to_test = {\"guides\", \"guide_events\"}\n\n conn_id = connections.ensure_connection(self)\n\n found_catalogs = self.run_and_verify_check_mode(conn_id)\n\n # table and field selection\n test_catalogs_all_fields = [catalog for catalog in found_catalogs\n if catalog.get('tap_stream_id') in streams_to_test]\n\n self.perform_and_verify_table_and_field_selection(conn_id,test_catalogs_all_fields)\n\n record_count_by_stream = self.run_and_verify_sync(conn_id)\n synced_records = runner.get_records_from_target_output()\n\n # check if all streams have collected records\n for stream in streams_to_test:\n self.assertGreater(record_count_by_stream.get(stream, -1), 0,\n msg=\"failed to replicate any data for stream : {}\".format(stream))\n\n # collect \"guide\" and \"guide_events\" data\n guides = synced_records.get(\"guides\")\n guide_events = synced_records.get(\"guide_events\")\n\n # find the first guide's id\n first_guide_id = guides.get(\"messages\")[0].get(\"data\").get(\"id\")\n\n first_guide_ids_events = []\n rest_guide_events = []\n\n # seperate guide events based on guide id\n for guide_event in guide_events.get(\"messages\"):\n if guide_event.get(\"data\").get(\"guide_id\") == first_guide_id:\n first_guide_ids_events.append(guide_event.get(\"data\"))\n else:\n rest_guide_events.append(guide_event.get(\"data\"))\n\n replication_key_for_guide_events = next(iter(self.expected_replication_keys().get(\"guide_events\")))\n\n # find the maximun bookmark date for first guide's events\n sorted_first_guide_ids_events = sorted(first_guide_ids_events, key=lambda i: i[replication_key_for_guide_events], reverse=True)\n max_bookmark = sorted_first_guide_ids_events[0].get(replication_key_for_guide_events)\n\n # used for verifying if we synced guide events before\n # than the maximum bookmark of first guide's events\n synced_older_data = False\n for rest_guide_event in rest_guide_events:\n event_time = datetime.strptime(rest_guide_event.get(replication_key_for_guide_events), \"%Y-%m-%dT%H:%M:%S.%fZ\")\n max_bookmark_time = datetime.strptime(max_bookmark, \"%Y-%m-%dT%H:%M:%S.%fZ\")\n if event_time < max_bookmark_time:\n synced_older_data = True\n break\n\n self.assertTrue(synced_older_data)\n","repo_name":"alisa-aylward-toast/tap-pendo","sub_path":"tests/tap_tester/test_child_stream_start_date.py","file_name":"test_child_stream_start_date.py","file_ext":"py","file_size_in_byte":2759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"}
+{"seq_id":"26187508458","text":"\"\"\"Модель настроек категорий для городов.\"\"\"\nfrom django.db import models\n\n\nclass CategoriesSettings(models.Model):\n \"\"\"Настройки категорий для городов.\"\"\"\n\n category = models.ForeignKey(\n 'Category',\n on_delete=models.CASCADE,\n )\n city = models.ForeignKey(\n 'City',\n on_delete=models.CASCADE,\n )\n radius = models.IntegerField(\n verbose_name='Радиус действия категории в метрах',\n )\n","repo_name":"andruwwwka/rebus-geo-rost","sub_path":"geo_data/models/categories_settings.py","file_name":"categories_settings.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"ru","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"}
+{"seq_id":"20544552977","text":"import re\nfrom decimal import Decimal\nimport xml.etree.ElementTree as et\n\nfrom scrapy.spider import BaseSpider\nfrom scrapy.selector import HtmlXPathSelector\nfrom scrapy.http import Request, FormRequest\nfrom scrapy.utils.url import urljoin_rfc\nfrom scrapy.utils.response import get_base_url\n\nfrom product_spiders.items import Product, ProductLoaderWithNameStrip as ProductLoader\n\n\nclass BathroomsSDSpider(BaseSpider):\n name = 'bathroomsandshowersdirect.co.uk'\n allowed_domains = ['bathroomsandshowersdirect.co.uk']\n #user_agent = 'Googlebot/2.1 (+http://www.google.com/bot.html)'\n start_urls = ('http://www.bathroomsandshowersdirect.co.uk',)\n\n download_delay = 0.1\n\n url = 'http://www.bathroomsandshowersdirect.co.uk/AfcTool/Ajax/AjaxProductSearchGet.cfm'\n\n tries = {}\n max_tries = 10\n\n formdata = {'ChannelCode': '3076',\n 'CurrentBuyIcon': '2007NXtMedBuyButtonBig.png',\n 'CurrentLA': 'En',\n 'CurrentPriceColor': 'fa0000',\n 'bFirstSearch':'true',\n 'cfs': '',\n 'cst':'338',\n 'iPriceFrom': '',\n 'iPriceTo':'0',\n 'iSearchSortBy':'0',\n 'iStartRow':'1',\n 'sChannels': '',\n 'sSearchWord':'-',\n 'sTopics':''}\n\n def start_requests(self):\n req = FormRequest(self.url, method='POST', dont_filter=True, formdata=self.formdata, meta={'start_row': 1})\n yield req\n\n def parse(self, response):\n hxs = HtmlXPathSelector(response)\n base_url = get_base_url(response)\n meta = response.meta\n\n body = response.body\n tree = et.fromstring(body)\n items = tree.findall('item')\n if items:\n for item in items:\n urls = item.findall('link')\n for url in urls:\n yield Request(urljoin_rfc(base_url, url.text), callback=self.parse_product)\n start_row = meta.get('start_row') + 40\n formdata = self.formdata\n formdata['iStartRow'] = str(start_row)\n\n yield FormRequest(self.url, dont_filter=True, formdata=formdata, meta={'start_row': start_row}, callback=self.parse)\n \n def parse_product(self, response):\n hxs = HtmlXPathSelector(response)\n base_url = get_base_url(response)\n\n hxs = HtmlXPathSelector(response)\n loader = ProductLoader(item=Product(), response=response)\n loader.add_xpath('image_url', '//img[@id=\"img1\"]/@src')\n try:\n brand, text, sku, category = hxs.select('//title/text()').extract()[0].split(' | ')\n except:\n brand, sku, category = ['', '', '']\n\n sku = hxs.select('//div[contains(text(), \"Product Code\")]/text()').extract()\n if sku:\n sku = sku[0].strip().replace('Product Code: ', '')\n else:\n sku = ''\n if category:\n category = category.split(' - ')[0]\n\n loader.add_value('category', category)\n loader.add_value('brand', brand)\n loader.add_value('url', response.url)\n loader.add_xpath('name', '//h1/text()')\n identifier = hxs.select('//div[contains(@class, \"priceCSS\") and div[@class=\"THT369\"]]/@class').extract()\n price = hxs.select('//div[contains(@class, \"price\")]/div/span/text()').extract()\n if price:\n price = price[0]\n\n if not identifier:\n identifier = hxs.select('//div[contains(@class, \"priceCSS\") and div[@class=\"THT364\"]]/@class').extract()\n price = hxs.select('//div[contains(@class, \"priceCSS\")]/div[@class=\"THT364\"]/text()').extract()\n if price:\n price = price[0].split(u'\\xa3')[-1].split()[0]\n\n if not identifier:\n if not response.url in self.tries:\n self.tries[response.url] = 0\n self.tries[response.url] += 1\n if self.tries[response.url] < self.max_tries:\n r = Request(response.url, callback=self.parse_product, dont_filter=True)\n yield r\n return\n\n identifier = identifier[0].replace('priceCSS', '')\n \n if not price:\n price = '0.0'\n\n loader.add_value('identifier', identifier)\n loader.add_value('sku', sku.replace(' ', ''))\n loader.add_value('price', self.calculate_price(price))\n yield loader.load_item()\n\n\n def calculate_price(self, value):\n res = re.search(r'[.0-9]+', value)\n if res:\n price = Decimal(res.group(0))\n self.log(\"Price: %s\" % price)\n return round((price) / Decimal('1.2'), 2) # 20% EXC VAT\n else:\n return None\n","repo_name":"Godsoo/scraping","sub_path":"e-commerce/CompetitorMonitor/product_spiders/spiders/tapoutlet/bathroomsandshowersdirect_spider.py","file_name":"bathroomsandshowersdirect_spider.py","file_ext":"py","file_size_in_byte":4697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"37433295559","text":"#!/usr/bin/env python\n# _____ _ _ _____ _ _ _\n# | __||_| _____ ___ | | _ _ | __| _ _ | |_ | ||_| _____ ___\n# |__ || || || . || || | ||__ || | || . || || || || -_|\n# |_____||_||_|_|_|| _||_||_ ||_____||___||___||_||_||_|_|_||___|\n# |_| |___|\nimport requests\nimport json\n\n\ndef searchMovie(searchterm, apiKey, url, sortingMode):\n \"\"\"Searchs for movie via string and return a list dictionaties containing the resulting movie\n matches after being ran through duplicates()\n\n Arguments:\n searchterm {str} -- Movie to search for.\n apiKey {int} -- Radarr's API key.\n url {str} -- Radarr's web url.\n\n Returns:\n [list] -- Returns a list dictionaties containing the resulting movie\n matches after being ran through duplicates()\n \"\"\"\n # Replace spaces from search term\n searchterm = searchterm.replace(\" \", \"%20\")\n # Makes API request and return data\n radarr = requests.get(url + \"/api/movie/lookup/?term=\" +\n searchterm + \"&apikey=\" + str(apiKey))\n results = radarr.json()\n\n return duplicates(results, sortingMode)\n\n\ndef radarrTest(url):\n try:\n requests.get(url + \"/api\")\n return(True)\n except requests.exceptions.RequestException as e:\n print(e)\n return(False)\n\n\ndef duplicates(results_json, sortingMode):\n results = []\n\n for i in results_json:\n results.append({\n \"title\": i[\"title\"],\n \"year\": i[\"year\"],\n \"tmdbId\": i[\"tmdbId\"],\n \"rating\": i[\"ratings\"][\"value\"],\n \"poster\": i[\"remotePoster\"],\n },)\n\n\n results = sorted(results, key=lambda k: k[sortingMode], reverse=True)\n #x = json.dumps(results, indent=4)\n #print(x)\n return results\n\n\n#searchMovie(\"Black Hawk Down\", \"22833f986d5543ce94ea197a1d21dfb8\", \"https://radarr.atriox.io\", \"rating\")\n\n\n\n\ndef addMovie(tmdbId, apiKey, profile, monitored, autosearch, url):\n \"\"\"Adds a series to Sonarr via its tvdbId number.\n\n Arguments:\n tmdbId {int} -- The tmdbId ID of the movie to add.\n apiKey {str} -- Radarr's API key.\n profile {int} -- The quality profile number.\n monitored {boolean} -- Whether or not monitor the movie after adding.\n autosearch {boolean} -- Whether or not to automatically search for movie after.\n url {str} -- Radarr's URL including the https/http\n \"\"\"\n\n result = requests.get(url + \"/api/movie/lookup/tmdb?tmdbId=\" +\n str(tmdbId) + \"&apikey=\" + str(apiKey))\n result = result.json()\n\n post_data = {\n \"qualityProfileId\": profile,\n \"rootFolderPath\": \"/data/media/movies/\",\n \"monitored\": monitored,\n \"addOptions\": {\"searchForMovie\": autosearch},\n }\n\n for dictkey in [\"tmdbId\", \"title\", \"titleSlug\", \"images\", \"year\"]:\n post_data.update({dictkey: result[dictkey]})\n\n status = requests.post(url + \"/api/movie?apikey=\" +\n str(apiKey), json=post_data)\n status = status.status_code\n\n \"\"\"\n 400 = exists\n 201 = added\n 404 = no route\n \"\"\"\n return status\n","repo_name":"senpaiSubby/alexa-subwatch","sub_path":"subwatch/backends/radarr.py","file_name":"radarr.py","file_ext":"py","file_size_in_byte":3162,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"32"}
+{"seq_id":"9341472313","text":"import cbor2\nimport pycose.keys\nfrom pycose.messages import Sign1Message\n\nimport merkle_proofs.tree_algorithms as ta\n\nCOSE_TREE_ALG_LABEL = \"treealg\"\nCOSE_TREE_SIZE_LABEL = \"treesize\"\n\ndef sign_tree_root(root: bytes, tree_alg: ta.TreeAlgorithm, key, alg, tree_size=None, detached=False) -> bytes:\n phdr = {}\n phdr[pycose.headers.Algorithm] = alg\n phdr[COSE_TREE_ALG_LABEL] = tree_alg.IDENTIFIER\n if tree_size is not None:\n if not isinstance(tree_size, int):\n raise TypeError(\"tree_size must be an integer\")\n phdr[COSE_TREE_SIZE_LABEL] = tree_size\n \n msg = Sign1Message(phdr=phdr, payload=root)\n msg.key = key\n signed = msg.encode(tag=True)\n if not detached:\n return signed\n detached = detach_cose_sign1_payload(signed)\n return detached\n\n\ndef detach_cose_sign1_payload(msg):\n # pycose doesn't support detached payloads yet, see:\n # https://github.com/TimothyClaeys/pycose/pull/110\n decoded = cbor2.loads(msg)\n assert decoded.tag == Sign1Message.cbor_tag\n [phdr, uhdr, _, signature] = decoded.value\n\n detached = cbor2.CBORTag(Sign1Message.cbor_tag, [\n phdr,\n uhdr,\n None,\n signature,\n ])\n return cbor2.dumps(detached)\n\ndef attach_cose_sign1_payload(msg, payload):\n # pycose doesn't support detached payloads yet, see:\n # https://github.com/TimothyClaeys/pycose/pull/110\n decoded = cbor2.loads(msg)\n assert decoded.tag == Sign1Message.cbor_tag\n [phdr, uhdr, _, signature] = decoded.value\n\n detached = cbor2.CBORTag(Sign1Message.cbor_tag, [\n phdr,\n uhdr,\n payload,\n signature,\n ])\n return cbor2.dumps(detached)\n","repo_name":"ietf-scitt/cose-merkle-tree-proofs","sub_path":"python/merkle_proofs/smtr.py","file_name":"smtr.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"}
+{"seq_id":"73997370331","text":"class Solution:\r\n def subsets(self, nums):\r\n \"\"\"\r\n :type nums: List[int]\r\n :rtype: List[List[int]]\r\n \"\"\"\r\n ans=[]\r\n ans.append([])\r\n self.dfs(ans,nums,[])\r\n return ans\r\n\r\n def dfs(self,ans,nums,tmpList):\r\n \tif(len(nums)==0):\r\n \t\treturn\r\n \tnewtmpList1=tmpList[:]\r\n \tself.dfs(ans,nums[1:],newtmpList1)\r\n \tnewtmpList2=tmpList[:]\r\n \tnewtmpList2.append(nums[0])\r\n \tans.append(newtmpList2)\r\n \tself.dfs(ans,nums[1:],newtmpList2)\r\n\r\nprint(Solution().subsets([1,2,3]))","repo_name":"Leputa/Leetcode","sub_path":"python/78.Subsets.py","file_name":"78.Subsets.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"33758526816","text":"# Configuration file for the Sphinx documentation builder.\n#\n# This file only contains a selection of the most common options. For a full\n# list see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\n# -- Path setup --------------------------------------------------------------\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#\nimport os\nimport sys\n\nsys.path.insert(0, os.path.abspath('..'))\n\n\n# -- Project information -----------------------------------------------------\n\nproject = 'PyASTrX'\ncopyright = '2022, Bruno Messias'\nauthor = 'Bruno Messias'\n\n\n# -- General configuration ---------------------------------------------------\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\n 'sphinx.ext.autodoc',\n 'sphinx.ext.napoleon',\n ]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path.\nexclude_patterns = []\n\n\n# -- Options for HTML output -------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\n#\nhtml_theme = 'sphinx_material'\nhtml_sidebars = {\n \"**\": [\"logo-text.html\", \"globaltoc.html\", \"localtoc.html\", \"searchbox.html\"]\n}\nhtml_show_sourcelink = False\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']\n\n\n\n# Material theme options (see theme.conf for more information)\nhtml_theme_options = {\n\n # Set the name of the project to appear in the navigation.\n #'nav_title': 'Project Name',\n\n # Set you GA account ID to enable tracking\n 'html_minify': False,\n 'css_minify': False,\n\n # Specify a base_url used to generate sitemap.xml. If not\n # specified, then no sitemap will be built.\n 'base_url': 'https://pyastrx.readthedocs.io/',\n\n # Set the color and the accent color\n 'color_primary': 'blue',\n 'color_accent': 'light-blue',\n\n # Set the repo location to get a badge with stats\n 'repo_url': 'https://github.com/pyastrx/pyastrx/',\n 'repo_name': 'pyastrx',\n\n # Visible levels of the global TOC; -1 means unlimited\n 'globaltoc_depth': 3,\n # If False, expand all TOC entries\n 'globaltoc_collapse': False,\n # If True, show hidden TOC entries\n 'globaltoc_includehidden': False,\n 'nav_links': [\n {'title': 'How to use', 'href': 'cli', 'internal': True},\n {'title': 'Examples', 'href': 'examples', 'internal': True},\n {\n 'title': 'Who I am? Bruno Messias',\n 'href': 'https://devmessias.github.io', 'internal': False},\n {\n 'title': 'Need help?',\n 'href': 'https://github.com/pyastrx/pyastrx/issues/new',\n 'internal': False\n },\n ]\n}\n","repo_name":"pyastrx/pyastrx","sub_path":"docs/source/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":3383,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"32"}
+{"seq_id":"23514479674","text":"from typing import List\n\nclass Solution:\n def rob(self, nums: List[int]) -> int:\n if len(nums) == 0:\n return 0\n\n dp = [0 for _ in range(len(nums)+1)]\n dp[0] = 0\n dp[1] = nums[0]\n\n for i in range(2, len(nums)+1):\n dp[i] = max(dp[i-1], dp[i-2]+nums[i-1])\n \n return dp[-1]\n\n\ndef testRob():\n test_case = [\n [1,2,3,1],\n [2,7,9,3,1]\n ]\n\n print('----------------- Test ------------------')\n solu = Solution()\n for item in test_case:\n rst = solu.rob(item)\n print('{}, result = {}\\n'.format(item, rst))\n\n\nif __name__ == '__main__':\n testRob()","repo_name":"imzhuhl/leetcode-problem","sub_path":"python3/0198.py","file_name":"0198.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"4225670491","text":"# https://leetcode.com/problems/boats-to-save-people/submissions/927275125/\n# Date of Submission: 2023-04-03\n\n# Runtime: 1008 ms, faster than 5.5% of Python3 online submissions for Boats to Save People.\n# Memory Usage: 19 MB, less than 99.82% of Python3 online submissions for Boats to Save People.\n\n# Problem:\n# You are given an array people where people[i] is the weight of the ith person, and an \n# infinite number of boats where each boat can carry a maximum weight of limit. Each \n# boat carries at most two people at the same time, provided the sum of the weight \n# of those people is at most limit.\n# \n# Return the minimum number of boats to carry every given person.\n\nclass Solution:\n def numRescueBoats(self, people: List[int], limit: int) -> int:\n people.sort()\n i = len(people) - 1\n numBoats = 0\n\n if len(people) == 1:\n return 1\n\n while len(people) > 1:\n if people[i] < limit and people[0] <= limit - people[i]: #remove pair\n people.pop()\n people.pop(0)\n i-=1\n else:\n people.pop()\n i-=1\n numBoats+=1\n\n return numBoats + len(people)","repo_name":"Retroflux/playground","sub_path":"LeetCodeSolutions/Python/0881-Boats_to_Save_People/memory_optimized.py","file_name":"memory_optimized.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"15668274124","text":"from serial import Serial, SerialException, SerialTimeoutException\nfrom time import time, sleep\nimport re\nimport threading\n\n\nclass Printer:\n def __init__(self, port: str):\n self.port = port # 串口号\n self.baud_rate = 115200 # 波特率\n self.name = 'unknown' # 打印机名字,暂时没什么用\n self.serial = None # 串口对象\n self.timeout = 5 # 连接超时时间\n self.data_update_timeout = 5 # 数据更新超时时间\n\n self.run = False # 线程开关\n\n self.updater_t = threading.Thread(target=self.read_data) # 数据更新线程\n self.updater_t.setDaemon(True) # 守护线程\n\n self._command_received = True # 命令收到标志,打印过程中基本无效,因为会大量输出ok\n self.t_received = True # 温度是否读取\n self.p_received = True # 位置是否读取\n\n # 以下变量按照协议命名,其中0e不是打印进度,是输出的E:xx.xx\n self.t1 = '0.00'\n self.t2 = '0.00'\n self.t3 = '0.00'\n\n self.x = '0.00'\n self.y = '0.00'\n self.z = '0.00'\n self.e = '0.00'\n\n def __del__(self): # 对象被清除时停止线程关闭串口\n if self.serial is not None:\n self.serial.close()\n self.run = False\n\n def connect(self, baud_rate=None):\n # 初始化\n if self.serial: # 如果正在运行则先停止线程关闭串口\n self.run = False\n self.serial.close()\n if baud_rate is not None: # 如果输入波特率则存为成员变量,没有则保持默认115200\n self.baud_rate = baud_rate\n try: # 连接串口\n self.serial = Serial(self.port, self.baud_rate, timeout=self.timeout, writeTimeout=self.timeout) #获取串口信息\n except SerialException as e:\n print(str(e))\n return False\n # 下面所有都是基于CURA里面的代码改的\n sleep(10) # CURA:Ensure that we are not talking to the boot loader. 1.5 seconds seems to be the magic number\n # 上面是为了跳过启动时一大堆输出而延时\n successful_responses = 0 # 成功计数\n\n self.serial.write(b\"\\n\") # CURA:Ensure we clear out previous responses\n self.serial.write(b\"M105\\n\") # 发温度询问由于测试连接\n\n timeout_t = time() + self.timeout\n\n while timeout_t > time(): # 在超时时间内反复连接\n line = self.serial.readline() # 串口读一行\n print(line) # 输出这一行便于调试\n if b\"ok T:\" in line or b\"ok == T:\" in line: # 有回复温度则继续发,ok==T是为了适配武汉的板子\n successful_responses += 1\n self.serial.write(b\"M105\\n\")\n if successful_responses >= 3: # 三次成功就判定为连接成功\n self.run = True\n self.updater_t.start() # 启动线程\n self.sendCommand('M105') # 询问温度,因为后面是回了才发,发了才回,如此循环,前面必须有个触发\n self.sendCommand('M114') # 询问位置,因为后面是回了才发,发了才回,如此循环,前面必须有个触发\n return True\n\n self.serial.close() # 连接不成功就把痕迹清除\n self.serial = None\n return False\n\n # Send a command to printer.接收平台的指令发送给打印机\n def sendCommand(self, command: str):\n if self.serial is None: # 串口没连上直接作为失败\n return 'fail'\n command = command.encode() # 将命令字符串变为字节流\n if not command.endswith(b\"\\n\"): # 命令必须回车才有效,没有则自动添加\n command += b\"\\n\"\n\n timeout_t = time() + self.timeout\n self.serial.write(command) # 发送命令\n self._command_received = False\n\n while timeout_t > time(): # 在超时时间内命令发送成功则返回success否则返回fail\n if self._command_received:\n return 'success'\n self._command_received = True # 无论命令是否收到都置位标志量\n return 'fail'\n\n # 接收打印机数据,并解析\n def read_data(self):\n temperature_t = time() # 初始化上一次收到温度数据的时间\n position_t = time() # 初始化上一次收到位置数据的时间\n while self.run:\n try: # 串口读行\n line = self.serial.readline()\n print(line)\n except:\n continue\n # 如果距离上一次收到温度数据的时间超过data_update_timeout则询问以防回了才发,发了才回的循环断开\n if time() - temperature_t > self.data_update_timeout:\n self.sendCommand('M105')\n # 如果距离上一次收到位置数据的时间超过data_update_timeout则询问以防回了才发,发了才回的循环断开\n if time() - position_t > self.data_update_timeout:\n self.sendCommand('M114')\n # 正则表达式取温度信息\n if line.startswith(b\"ok T\") or line.startswith(b\"T:\")\\\n or line.startswith(b\"ok == T:\") or line.startswith(b\" == T:\"):\n temperature_t = time() # 更新上一次获取温度信息的时间\n line1 = line.decode()\n if 'B:' in line1:\n res = re.findall(\"B: ?([\\-\\d\\.]+)\", line1)\n self.t3 = res[0]\n if 'T:' in line1:\n res = re.findall(\"T: ?([\\-\\d\\.]+)\", line1)\n self.t1 = res[0]\n else:\n res = re.findall(\"T0: ?([\\-\\d\\.]+)\", line1)\n self.t1 = res[0]\n # 在升温过程中是主动发送没有ok不用询问(line.startswith(b\"T:\" or b\" == T:\"))\n if line.startswith(b\"ok T\") or line.startswith(b\"ok == T:\"):\n self.sendCommand('M105')\n # 正则表达式取位置信息\n if line.startswith(b\"X:\"):\n position_t = time()\n line1 = line.decode()\n res = re.findall(\"X: ?([\\d\\.]+)\", line1)\n self.x = res[0]\n res = re.findall(\"Y: ?([\\d\\.]+)\", line1)\n self.y = res[0]\n res = re.findall(\"Z: ?([\\d\\.]+)\", line1)\n self.z = res[0]\n res = re.findall(\"E: ?([\\-\\d\\.]+)\", line1)\n self.e = res[0]\n self.sendCommand('M114')\n\n if b\"ok\" in line: # 命令是否获取成功的标志量置位\n self._command_received = True\n\n\n# 用于单元测试\nif __name__ == '__main__':\n p = Printer('COM5')\n ret = False\n while not ret:\n print('connecting\\n'+str(ret))\n ret = p.connect(250000)\n if ret:\n break\n sleep(5)\n while True:\n print(p.t1)\n print(p.t3)\n sleep(1)\n","repo_name":"VASIMRLJJ/3DP2","sub_path":"printer.py","file_name":"printer.py","file_ext":"py","file_size_in_byte":7098,"program_lang":"python","lang":"zh","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"}
+{"seq_id":"28625299526","text":"#\n# Purpose:\n#\n# 1. select references where relevanceStatus = \"Not Specified\" (70594668)\n#\n# 2. creates input file for relenvace classifier/predicter\n#\n# Data transformations include:\n# replacing non-ascii chars with ' '\n# replacing FIELDSEP and RECORDSEP chars in the doc text w/ ' '\n#\n# Outputs: \n#\n# Delimited file to ${NOTSPECIFIED_RELEVANCE}\n# See sampleDataLib.PrimTriageUnClassifiedSample for output format\n#\n\nimport sys\nimport os\nimport re\nimport db\nimport sampleDataLib\nimport ExtractedTextSet\n\ndb.setTrace()\n\nsampleObjType = sampleDataLib.PrimTriageUnClassifiedSample\noutputSampleSet = sampleDataLib.SampleSet(sampleObjType=sampleObjType)\n\nRECORDEND = outputSampleSet.getRecordEnd()\nFIELDSEP = sampleObjType.getFieldSep()\n\n# match non-ascii chars\nnonAsciiRE = re.compile(r'[^\\x00-\\x7f]')\t\n\n# depends on \"tmp_refs\" temp table\ncmd = '''\ncreate temporary table tmp_refs as\nselect r._refs_key, c.mgiid, r.title, r.abstract\n from bib_refs r, bib_citation_cache c, bib_workflow_relevance wr\n where r._refs_key = c._refs_key\n and r._refs_key = wr._refs_key\n and wr._relevance_key = 70594668\n and wr.isCurrent = 1;\n'''\n\n#\n# clean the text fields\n#\ndef cleanUpTextField(rcd, textFieldName):\n\n # 2to3 note: rcd is not a python dict,\n # it has a has_key() method\n if rcd.has_key(textFieldName): \n text = str(rcd[textFieldName])\n else:\n text = ''\n\n # remove RECORDEND and FIELDSEP from text (replace w/ ' ')\n text = text.replace(RECORDEND, ' ').replace(FIELDSEP, ' ')\n\n # remove non ascii\n text = nonAsciiRE.sub(' ', text)\n\n return text\n\n#\n# MAIN\n#\n\nfp = open(os.getenv('NOTSPECIFIED_RELEVANCE'), 'w')\n\n# get results\ndb.sql(cmd, None)\ndb.sql('create index tmp_idx1 on tmp_refs(_refs_key)', None)\nresults = db.sql('select * from tmp_refs', 'auto')\n\n# get extracted text & add it to results\nextTextSet = ExtractedTextSet.getExtractedTextSetForTable(db, 'tmp_refs')\nextTextSet.joinRefs2ExtText(results, allowNoText=True)\n\n# create records and add to outputSampleSet\nfor r in results:\n\n newR = {}\n newR['ID'] = str(r['mgiid'])\n newR['title'] = cleanUpTextField(r, 'title')\n newR['abstract'] = cleanUpTextField(r, 'abstract')\n newR['extractedText'] = cleanUpTextField(r, 'ext_text')\n\n newSample = sampleObjType()\n newSample.setFields(newR)\n outputSampleSet.addSample(newSample)\n\n# write sample file\n#outputSampleSet.setMetaItem('host', os.getenv('MGD_DBSERVER'))\n#outputSampleSet.setMetaItem('db', os.getenv('MGD_DBNAME'))\noutputSampleSet.write(fp)\nfp.close()\ndb.commit()\n\n","repo_name":"mgijax/littriageload","sub_path":"bin/makePredicted.py","file_name":"makePredicted.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"71048050971","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nC APDCAM10G Firmware test\nreated on Mon Jul 2 15:46:13 2018\n\n@author: apdcam\n\"\"\"\n\n\ndef firmware_test(card=8) :\n import APDCAM10G_control\n \n c = APDCAM10G_control.APDCAM10G_regCom()\n \n\n ret = c.startReceiveAnswer()\n if ret != \"\" :\n print(\"Could not start UDP read. (err:%s)\" % ret)\n del c\n return\n err, data = c.readPDI(card,0,7,arrayData=1)\n if (err != \"\") :\n print(\"Error: %s\" % err)\n return\n data = data[0]\n if ((data[0] & 0xE0) != 0x20) :\n print(\"No ADC found at address %d\" % card)\n return\n mc_version = \"{:d}.{:d}\".format(data[1],data[2])\n fw_version = \"{:d}.{:d}\".format(data[5],data[6])\n print(\"ADC versions, MC:{:s}, FW:{:s}\".format(mc_version,fw_version))\n \n apdcam_data = APDCAM10G_control.APDCAM10G_data()\n apdcam_data.stopStream(c)\n # Samplediv\n err = c.sendCommand(APDCAM10G_regCom.OP_PROGRAMSAMPLEDIVIDER,bytes([0,5]),sendImmediately=False)\n # samples\n err = c.sendCommand(APDCAM10G_regCom.OP_SETSAMPLECOUNT,bytes([0,0,0,1,0,0]),sendImmediately=True)\n #apdcam_data.setOctet(1000)\n apdcam_data.startReceive(c,[True, False, False, False])\n apdcam_data.startStream(c,[True, False, False, False])\n counter = 1\n while 1 :\n err,data = apdcam_data.getData(0)\n if (err ==\"\") :\n if (counter == 1):\n print(\"First packet\")\n packet_counter = int.from_bytes(data[8:14],'big') \n if (packet_counter != counter) :\n print(\"Error in packet counter: %d (exp: %d)\" % (int.from_bytes(data[8:14],'big'), counter))\n counter = counter+1 \n else :\n #print(\"Error: %s\" % err)\n break\n print(\"Received %d packets\" % counter) \n del apdcam_data\n\n \n \n \n del c\n \n \n \nfirmware_test()\n\n","repo_name":"fusion-flap/flap_apdcam","sub_path":"apdcam_control/APDCAM10G_firmware_test.py","file_name":"APDCAM10G_firmware_test.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"}
+{"seq_id":"19093467272","text":"import os\n\nfrom flask import Blueprint, Response, current_app, request\nfrom pydantic import BaseModel, StrictStr, ValidationError\nfrom werkzeug.exceptions import BadRequest\n\nfrom deployer.config import Config\nfrom deployer.deployer import Deployer\nfrom deployer.lock import ServiceLocks\n\n\nclass DeployRequest(BaseModel):\n service: StrictStr\n attributes: dict[StrictStr, StrictStr]\n\n\ndef text_response(value, status):\n return Response(value, mimetype=\"text/plain\", status=status)\n\n\napi = Blueprint(\"api\", __name__)\n\n\n@api.route(\"/deploy\", methods=[\"POST\"])\ndef deploy(service_locks: ServiceLocks, config: Config, deployer: Deployer):\n authz = request.headers.get(\"authorization\")\n if authz is None or not authz.lower().startswith(\"bearer \"):\n return text_response(\"Missing auth\", 401)\n token = authz[7:]\n if token not in config.valid_tokens:\n return text_response(\"Token not found\", 401)\n\n current_app.logger.info(\"Process pid: {}\".format(os.getpid()))\n\n if request.content_length is None or request.content_length == 0:\n return text_response(\"Missing contents\\n\", 400)\n\n if request.content_type != \"application/json\":\n return text_response(\"Expected content type of application/json\\n\", 400)\n\n try:\n body = request.get_json()\n except BadRequest:\n return text_response(\"Invalid JSON\", 400)\n\n current_app.logger.info(\"Received data: {}\".format(body))\n\n try:\n model = DeployRequest.parse_obj(body)\n except ValidationError as e:\n current_app.logger.info(f\"Invalid model: {e}\")\n return text_response(\"Invalid model\", 400)\n\n if model.service not in config.services:\n return text_response(\"Unknown service\", 400)\n\n service = config.services[model.service]\n\n for key in model.attributes.keys():\n if key not in service.mappings:\n return text_response(f\"Unknown attribute: '{key}'\", 400)\n\n with service_locks.hold_lock(\"test\"):\n deployer.handle(\n service=service,\n attributes=model.attributes,\n )\n\n return text_response(\"OK\\n\", 200)\n\n\n@api.route(\"/\")\ndef hello():\n return \"https://github.com/blindern/deployer\"\n","repo_name":"blindern/deployer","sub_path":"deployer/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"36712418600","text":"# 삼성 A형 코딩 테스트 기출 : 톱니바퀴\ndef solve(idx, di):\n if idx < 0 or idx > 3 or visited[idx]: # 종료조건\n return\n visited[idx] = 1\n left = idx - 1\n right = idx + 1\n if di == 1: # 시계 방향으로 돌 때\n gear[idx] = gear[idx][7:8] + gear[idx][0:7]\n if right < 4:\n if gear[idx][3] != gear[idx+1][6]: # 오른쪽 톱니바퀴와 다른 극일 경우\n solve(idx+1, -1)\n if left > -1:\n if gear[idx][7] != gear[idx-1][2]: # 왼쪽 톱니바퀴와 다른 극일 경우\n solve(idx-1, -1)\n else:\n gear[idx] = gear[idx][1:8] + gear[idx][0:1]\n if right < 4:\n if gear[idx][1] != gear[idx+1][6]: # 오른쪽 톱니바퀴와 다른 극일 경우\n solve(idx+1, 1)\n if left > -1:\n if gear[idx][5] != gear[idx-1][2]: # 왼쪽 톱니바퀴와 다른 극일 경우\n solve(idx-1, 1)\n\n\ngear = [list(input()) for _ in range(4)]\nfor i in range(int(input())):\n index, direction = map(int, input().split())\n visited = [0, 0, 0, 0]\n solve(index-1, direction)\nresult = 0\nfor j in range(4):\n if gear[j][0] == '1':\n result += pow(2, j)\nprint(result)","repo_name":"ketkat001/BaekJoon","sub_path":"14891.py","file_name":"14891.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"18650303217","text":"import numpy as np\nimport warnings\nimport ta\nfrom sklearn.linear_model import LinearRegression\nwarnings.filterwarnings(\"ignore\")\n\nclass StockAnalysis:\n def __init__(self, asset):\n self.__history = asset.getPriceHistory().copy()\n self.__history = self.__history.dropna()\n\n self.__indexies = []\n\n def sma(self, first_period, second_period):\n df_copy = self.__history.copy()\n\n first_index = 'SMA ' + str(first_period)\n second_index = 'SMA ' + str(second_period)\n\n df_copy[first_index] = df_copy[['close']].rolling(first_period).mean().shift(1)\n df_copy[second_index] = df_copy[['close']].rolling(second_period).mean().shift(1)\n\n return df_copy\n\n def msd(self, first_period, second_period):\n df_copy = self.__history.copy()\n df_copy['returns'] = df_copy['close'].pct_change(1)\n\n first_index = 'MSD ' + str(first_period)\n second_index = 'MSD ' + str(second_period)\n\n df_copy[first_index] = df_copy[['returns']].rolling(first_period).std().shift(1)\n df_copy[second_index] = df_copy[['returns']].rolling(second_period).std().shift(1)\n\n print(df_copy.columns)\n\n return df_copy\n\n def RSI(self, save=None):\n df_copy = self.__history.copy()\n RSI = ta.momentum.RSIIndicator(df_copy['close'], window=14, fillna=False)\n df_copy['rsi'] = RSI.rsi()\n\n return df_copy\n\n def feature_engineering(self, sma_first_period, sma_second_period,\n msd_first_period, msd_second_period):\n df_copy = self.__history.copy()\n df_copy['returns'] = df_copy['close'].pct_change(1)\n\n first_index = 'SMA ' + str(sma_first_period)\n second_index = 'SMA ' + str(sma_second_period)\n third_index = 'MSD ' + str(msd_first_period)\n fourth_index = 'MSD ' + str(msd_second_period)\n\n self.__indexies = [first_index, second_index, third_index, fourth_index]\n\n # create SMAs\n df_copy[first_index] = df_copy[['close']].rolling(sma_first_period).mean().shift(1)\n df_copy[second_index] = df_copy[['close']].rolling(sma_second_period).mean().shift(1)\n\n df_copy[third_index] = df_copy[['returns']].rolling(msd_first_period).std().shift(1)\n df_copy[fourth_index] = df_copy[['returns']].rolling(msd_second_period).std().shift(1)\n\n RSI = ta.momentum.RSIIndicator(df_copy['close'], window=14, fillna=False)\n df_copy['rsi'] = RSI.rsi()\n\n return df_copy.dropna()\n\n def lin_reg_trading(self, day1, day2, day3, day4):\n df = self.feature_engineering(day1, day2, day3, day4)\n # percentage train set\n split = int(0.80 * len(df))\n\n # train set creation\n X_train = df[self.indexies].iloc[:split]\n y_train = df[['returns']].iloc[:split]\n\n # test set creation\n X_test = df[self.indexies].iloc[split:]\n y_test = df[['returns']].iloc[split:]\n\n linear = LinearRegression()\n linear.fit(X_train, y_train)\n\n # create predictions for the whole dataset\n X = np.concatenate((X_train, X_test), axis=0)\n df[\"prediction\"] = linear.predict(X)\n print(df['prediction'])\n # compute the position\n df['position'] = np.sign(df['prediction'])\n print(df['prediction'])\n # compute the returns\n df['strategy'] = df['returns'] * df['position'].shift(1)\n\n return df\n\n","repo_name":"Nelasar/practice","sub_path":"linearregression.py","file_name":"linearregression.py","file_ext":"py","file_size_in_byte":3421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"21275893951","text":"from time import sleep\nc=('\\033[m', #0-sem cor\n '\\033[0;30;41m', #1-vermelho\n '\\033[0;30;42m', #2-verde\n '\\033[0;30;43m', #3-amarelo\n '\\033[0;30;44m', #4-azul\n '\\033[0;30;45m', #5-roxo\n '\\033[47m' #6-branco\n );\n\n\ndef ajuda(com):\n titulo(f'Acessando o manual do comando \\'{com}\\'', 5)\n print(c[6])\n help(com)\n print(c[0])\n sleep(2)\n\n\ndef titulo(msg, cor=0):\n tamanho=len(msg)+4\n print(c[cor])\n print('='*tamanho)\n print(f'{ msg}')\n print('='*tamanho)\n print(c[0])\n sleep(1)\n\n\ncomando=''\nwhile True:\n titulo('SISTEMA DE AJUDA PYHELP', 2)\n comando=str(input('Função ou biblioteca (Digite FIM caso queira encerrar o programa.) >'))\n if comando.upper() == 'FIM':\n break\n else:\n ajuda(comando)\ntitulo('ATÉ LOGO!', 1)\n","repo_name":"Jorgemartin2/Pequenos_projetos","sub_path":"Projetos/sistemainterativo.py","file_name":"sistemainterativo.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"9378949214","text":"from app.models import db, ServerMember, Server, User\nimport random\n\ndef seed_server_members():\n demo1 = ServerMember(\n user_id = 1,\n server_id = 1,\n permission_id = 3,\n )\n demo3 = ServerMember(\n user_id = 1,\n server_id = 3,\n permission_id = 1,\n )\n\n marnie1 = ServerMember(\n user_id = 2,\n server_id = 1,\n permission_id = 1,\n )\n\n marnie2 = ServerMember(\n user_id = 2,\n server_id = 2,\n permission_id = 3\n )\n\n bobbie3 = ServerMember(\n user_id = 3,\n server_id = 3,\n permission_id = 3\n )\n bobbie1 = ServerMember(\n user_id = 3,\n server_id = 1,\n permission_id = 1\n )\n\n db.session.add(demo1)\n db.session.add(demo3)\n db.session.add(marnie1)\n db.session.add(marnie2)\n db.session.add(bobbie1)\n db.session.add(bobbie3)\n\n #! loop through all servers --->\n #! create a set with at least 5-10 unique members from userIds 1-43\n #! cast set into an array ---> iterate through array of user ids ---> have ids join serverId with permission of 1.\n servers = Server.query.all()\n # users = User.query.all()\n for server in servers:\n\n userSet = set()\n for j in range(0, random.randint(3,9)):\n userSet.add(random.randint(1,43))\n userArr = list(userSet)\n for userId in userArr:\n server_member = ServerMember(\n user_id = userId,\n server_id = server.id,\n permission_id = 1\n )\n db.session.add(server_member)\n\n\n\n db.session.commit()\n\ndef undo_server_members():\n db.session.execute('DELETE from server_members;')\n db.session.commit()\n","repo_name":"AlanDeleon88/leet-cord","sub_path":"app/seeds/server_members.py","file_name":"server_members.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"}
+{"seq_id":"71497982811","text":"from http.server import BaseHTTPRequestHandler, HTTPServer\nfrom urllib.parse import urlparse, parse_qsl\nimport argparse\nimport json\n\nfrom xplan import display_cursor\n\n\nclass XPlanHTTPRequestHandler(BaseHTTPRequestHandler):\n def do_GET(self):\n self.send_response(200)\n self.send_header('Content-type', 'text/javascript')\n self.end_headers()\n if str.startswith(self.path, '/xplan?'):\n message = gen_xplan_response(self.path)\n self.wfile.write(bytes(message, \"utf8\"))\n else:\n self.wfile.write(bytes('', \"utf8\"))\n return\n\n\ndef run(server_host='127.0.0.1', server_port=8080, server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):\n print('starting server...')\n server_address = (server_host, server_port)\n httpd = server_class(server_address, handler_class)\n print('running server...')\n httpd.serve_forever()\n\n\ndef parse_path_args(path):\n o = urlparse(path)\n return dict(parse_qsl(o.query))\n\n\ndef gen_xplan_response(path):\n url_args = parse_path_args(path)\n sql_id = url_args[\"sql_id\"]\n child_number = url_args[\"child\"]\n db_name = url_args[\"db_name\"]\n inst = url_args[\"inst\"]\n name = \"%s-%s\" % (db_name, inst)\n dsn = get_config()[name]\n xplan = display_cursor(dsn, sql_id, child_number).to_str()\n return \"callback(%s)\" % json.dumps({\"xplan\": xplan})\n\n\ndef get_config():\n dsns = {}\n with open(config_file) as f:\n dsns = json.loads(f.read())\n return dsns\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('-cf', '--config_file', help=\"data source file path\", required=True)\n return parser.parse_args()\n\n\ndef main(args):\n global config_file\n config_file = args.config_file\n run(server_host='0.0.0.0', handler_class=XPlanHTTPRequestHandler)\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n main(args)\n","repo_name":"shinhwagk/oracle_exporter_xplan","sub_path":"grafana_xplan.py","file_name":"grafana_xplan.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"}
+{"seq_id":"37255456875","text":"'''\r\nCreated on May 15, 2018\r\n\r\n@author: kjnether\r\n'''\r\n# -*- coding: utf-8 -*-\r\nfrom __future__ import unicode_literals\r\n\r\nfrom django.contrib.auth.models import User\r\nfrom django.test import TestCase\r\nfrom api.models.ReplicationJobs import ReplicationJobs\r\nfrom api.models.Destinations import Destinations\r\nfrom api.models.FieldMap import FieldMap\r\nfrom api.models.Transformers import Transformers\r\nfrom api.models.Sources import Sources\r\nfrom api.models.DataTypes import FMEDataTypes\r\nfrom api.models.JobStatistics import JobStatistics\r\n\r\nimport pytz\r\nimport datetime\r\n\r\n\r\n# Create your tests here.\r\nclass ModelTestCase(TestCase):\r\n \"\"\"\r\n This class defines the test suite for the bucketlist model.\r\n \"\"\"\r\n\r\n def setUp(self):\r\n \"\"\"\r\n Define the test client and other test variables.\r\n \"\"\"\r\n self.jobid = \"1\"\r\n self.user = 'spock'\r\n self.user = User.objects.create(username=\"spock\")\r\n fixtures = ['Destination_Keywords.json']\r\n\r\n self.job = ReplicationJobs(jobid=self.jobid, owner=self.user)\r\n\r\n def test_model_can_create_a_job(self):\r\n \"\"\"\r\n Test the ReplicationJobs model can create a ReplicationJobs.\r\n \"\"\"\r\n # self.assertEqual(1, 1, \"one doesn't equal 1\")\r\n old_count = ReplicationJobs.objects.count()\r\n self.job.save()\r\n new_count = ReplicationJobs.objects.count()\r\n self.assertNotEqual(old_count, new_count)\r\n\r\n def test_model_can_create_a_FGDB_source(self):\r\n \"\"\"\r\n Test the sources model can create a source.\r\n \"\"\"\r\n old_count = Sources.objects.count()\r\n job = ReplicationJobs(jobid=self.jobid)\r\n sources = Sources(jobid=job, sourceTable='fgdbTable',\r\n sourceType='FGDB', sourceDBSchema='',\r\n sourceDBName=None, sourceDBHost=None,\r\n sourceDBPort=None,\r\n sourceFilePath=r'c:\\dir\\dir2\\somwhere\\src.fgdb')\r\n sources.save()\r\n new_count = Sources.objects.count()\r\n self.assertNotEqual(old_count, new_count)\r\n\r\n def test_model_can_create_a_destination(self):\r\n \"\"\"\r\n Test the Destination model can create a Destination.\r\n \"\"\"\r\n old_count = Destinations.objects.count()\r\n# job = ReplicationJobs(jobid=self.jobid)\r\n dests = Destinations(dest_key='DLV2', dest_service_name='ServName',\r\n dest_host='dest_host', dest_port=None,\r\n dest_type=r'dbase')\r\n dests.save()\r\n new_count = Destinations.objects.count()\r\n self.assertNotEqual(old_count, new_count)\r\n allDest = Destinations.objects.all()\r\n for dest in allDest:\r\n print(f'dest: {dest}')\r\n\r\n def test_model_can_create_a_fieldmap(self):\r\n \"\"\"\r\n Test the Fieldmap model can create a Fieldmap.\r\n \"\"\"\r\n old_count = FieldMap.objects.count()\r\n dataType = FMEDataTypes(fieldType='testchar',\r\n Description='testing description')\r\n dataType.save()\r\n print(f'dataType: {dataType}') \r\n \r\n job = ReplicationJobs(jobid=self.jobid)\r\n\r\n #fieldmaps = FieldMap.objects.all()\r\n \r\n #print 'fieldmaps', fieldmaps\r\n\r\n fieldMap = FieldMap(\r\n jobid=job,\r\n sourceColumnName='COL_A', destColumnName='COL_1',\r\n fmeColumnType=dataType, whoCreated=self.user,\r\n whoUpdated=self.user)\r\n\r\n fieldMap.save()\r\n new_count = FieldMap.objects.count()\r\n self.assertNotEqual(old_count, new_count)\r\n \r\n def test_model_can_create_a_transformer(self):\r\n \"\"\"\r\n Test the Transformers model can create a Transformers.\r\n \"\"\"\r\n old_count = Transformers.objects.count()\r\n job = ReplicationJobs(jobid=self.jobid)\r\n transformer = Transformers(jobid=job,\r\n transformer_type='counter',\r\n ts1_name = 'param1', \r\n ts1_value = 'value1',\r\n ts2_name = 'param2', \r\n ts2_value = 'value2',\r\n ts3_name = 'param3', \r\n ts3_value = 'value3',\r\n ts4_name = 'param4', \r\n ts4_value = 'value4',\r\n ts5_name = 'param5', \r\n ts5_value = 'value5',\r\n ts6_name = 'param6', \r\n ts6_value = 'value6',\r\n whoCreated=self.user,\r\n whoUpdated=self.user)\r\n\r\n transformer.save()\r\n new_count = Transformers.objects.count()\r\n self.assertNotEqual(old_count, new_count)\r\n\r\n def test_model_can_create_a_FMEDataType(self):\r\n \"\"\"\r\n Test the DataType model can create a FMEDataType.\r\n \"\"\"\r\n old_count = FMEDataTypes.objects.count()\r\n dataType = FMEDataTypes(fieldType='testchar',\r\n Description='testing description')\r\n dataType.save()\r\n new_count = FMEDataTypes.objects.count()\r\n self.assertNotEqual(old_count, new_count)\r\n dataTypes = FMEDataTypes.objects.all()\r\n for datatype in dataTypes:\r\n print(f'type: {datatype}')\r\n\r\n def test_model_can_create_a_JobStatistic(self):\r\n \"\"\"\r\n Test the Jobstatistics model can create a jobstatistic.\r\n \"\"\"\r\n old_count = JobStatistics.objects.count()\r\n dataType = JobStatistics(jobStatus='WORKING',\r\n fmeServerJobId=100232,\r\n jobStarted=datetime.datetime.now(pytz.UTC),\r\n jobCompleted=datetime.datetime.now(pytz.UTC))\r\n dataType.save()\r\n new_count = JobStatistics.objects.count()\r\n self.assertNotEqual(old_count, new_count)\r\n\r\n# def test_model_can_create_a_DestinationKeyword(self):\r\n# old_count = JobStatistics.objects.count()\r\n# dataType = JobStatistics(jobStatus='WORKING',\r\n# fmeServerJobId=100232,\r\n# jobStarted=datetime.datetime.now(pytz.UTC),\r\n# jobCompleted=datetime.datetime.now(pytz.UTC))\r\n# dataType.save()\r\n# new_count = JobStatistics.objects.count()\r\n# self.assertNotEqual(old_count, new_count)\r\n","repo_name":"bcgov/kirk","sub_path":"src/backend/api/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":6627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"26969138977","text":"class Solution(object):\n def minCut(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n self.palindromes = self.getPalindrome(s)\n minCutHere = [0] * len(s)\n for i in range(1,len(s)):\n minCutHere[i] = minCutHere[i-1] + 1\n for j in range(0,i):\n if self.isPalindrome(j,i):\n if j == 0:\n minCutHere[i] = 0\n else:\n minCutHere[i] = min(minCutHere[j-1] + 1,minCutHere[i])\n return minCutHere[-1]\n\n def getPalindrome(self,s):\n s1 = \"#\" + \"#\".join(s) + \"#\"\n id,mx = 0,0\n p = [1] * len(s1)\n for i in range(len(s1)):\n if mx > i:\n p[i] = min(p[2*id - i],mx-i)\n while i - p[i] >= 0 and i + p[i] < len(s1) and s1[i - p[i]] == s1[i + p[i]]:\n p[i] += 1\n if p[i] > mx:\n mx = i\n id = i\n return p\n def isPalindrome(self,left,right):\n if self.palindromes[left+right+1] > (right - left):\n return True\n return False\n\n","repo_name":"FengFengHan/LeetCode","sub_path":"Palindrome Partitioning II.py","file_name":"Palindrome Partitioning II.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"19230261933","text":"#!/usr/bin/python3\n\n'''\nPython script that takes in a URL, sends a request to he URL\n then displays he body of he response\nIf the HTTP status code is greater than or equals to 400:\n print: Error code, followed by status code\nUse the packages requests and sys\n'''\n\nimport requests\nimport sys\n\nif __name__ == \"__main__\":\n url = sys.argv[1]\n r = requests.get(url)\n if r.status_code >= 400:\n print(\"Error code: {}\".format(r.status_code))\n else:\n print(r.text)\n","repo_name":"Nobby-code/alx-higher_level_programming","sub_path":"0x11-python-network_1/7-error_code.py","file_name":"7-error_code.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"36756182299","text":"# The app will:\n\n# Ask the user to input a subtotal.\n# Calculate the tax owed using some(hard-coded) tax rate. This can be whatever you want, like 0.25.\n# Print out a message with the amount of tax owed.\n# Print out another message with the total owed including tax.\n\nsubtotal = float(input(\"Please add subtotal here => \"))\ntaxRate = 0.14\ntax = subtotal * taxRate\ntotal = subtotal + tax\n\nprint('The taxed owed is ' + str(tax))\nprint(\"The total amount including tax is \" + str(total))\n","repo_name":"lighthouse-labs/learn_python","sub_path":"taxCalculator.py","file_name":"taxCalculator.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"29976174307","text":"\ndef greatest_impact(lst):\n if all(row[0]==10 for row in lst):\n return 'Nothing'\n \n factors = [{'name':'Weather', 'weighted':lambda v:10-v, 'impact':0},\n {'name':'Meals', 'weighted':lambda v:3-v, 'impact':0},\n {'name':'Sleep', 'weighted':lambda v:10-v, 'impact':0}]\n for mood, *row in lst:\n for i, value in enumerate(row):\n factors[i]['impact'] += factors[i]['weighted'](value)\n return max(factors,key=lambda x: x['impact']/len(lst))['name']\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"bmYrX5N9DBF27Fx63_12.py","file_name":"bmYrX5N9DBF27Fx63_12.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"70651232731","text":"import gym\nimport numpy as np\n\nclass VideoWrapper(gym.Wrapper):\n def __init__(self, \n env, \n mode='rgb_array',\n enabled=True,\n steps_per_render=1,\n **kwargs\n ):\n super().__init__(env)\n \n self.mode = mode\n self.enabled = enabled\n self.render_kwargs = kwargs\n self.steps_per_render = steps_per_render\n\n self.frames = list()\n self.step_count = 0\n\n def reset(self, **kwargs):\n obs = super().reset(**kwargs)\n self.frames = list()\n self.step_count = 1\n if self.enabled:\n frame = self.env.render(\n mode=self.mode, **self.render_kwargs)\n assert frame.dtype == np.uint8\n self.frames.append(frame)\n return obs\n \n def step(self, action):\n result = super().step(action)\n self.step_count += 1\n if self.enabled and ((self.step_count % self.steps_per_render) == 0):\n frame = self.env.render(\n mode=self.mode, **self.render_kwargs)\n assert frame.dtype == np.uint8\n self.frames.append(frame)\n return result\n \n def render(self, mode='rgb_array', **kwargs):\n return self.frames\n","repo_name":"columbia-ai-robotics/diffusion_policy","sub_path":"diffusion_policy/gym_util/video_wrapper.py","file_name":"video_wrapper.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","stars":193,"dataset":"github-code","pt":"32"}
+{"seq_id":"7329825670","text":"\"\"\"\nAsynchronous Advantage Actor Critic (A3C) with discrete action space, Reinforcement Learning.\n\nThe Cartpole example using distributed tensorflow + multiprocessing.\n\nView more on my tutorial page: https://morvanzhou.github.io/\n\n\"\"\"\n\nimport multiprocessing as mp\nimport tensorflow as tf\nimport numpy as np\nimport gym, time\nimport matplotlib.pyplot as plt\n\n\nUPDATE_GLOBAL_ITER = 10\nGAMMA = 0.9\nENTROPY_BETA = 0.001\nLR_A = 0.001 # learning rate for actor\nLR_C = 0.001 # learning rate for critic\n\nenv = gym.make('CartPole-v0')\nN_S = env.observation_space.shape[0]\nN_A = env.action_space.n\n\n\nclass ACNet(object):\n sess = None\n\n def __init__(self, scope, opt_a=None, opt_c=None, global_net=None):\n if scope == 'global_net': # get global network\n with tf.variable_scope(scope):\n self.s = tf.placeholder(tf.float32, [None, N_S], 'S')\n self.a_params, self.c_params = self._build_net(scope)[-2:]\n else:\n with tf.variable_scope(scope):\n self.s = tf.placeholder(tf.float32, [None, N_S], 'S')\n self.a_his = tf.placeholder(tf.int32, [None, ], 'A')\n self.v_target = tf.placeholder(tf.float32, [None, 1], 'Vtarget')\n\n self.a_prob, self.v, self.a_params, self.c_params = self._build_net(scope)\n\n td = tf.subtract(self.v_target, self.v, name='TD_error')\n with tf.name_scope('c_loss'):\n self.c_loss = tf.reduce_mean(tf.square(td))\n\n with tf.name_scope('a_loss'):\n log_prob = tf.reduce_sum(\n tf.log(self.a_prob) * tf.one_hot(self.a_his, N_A, dtype=tf.float32),\n axis=1, keep_dims=True)\n exp_v = log_prob * tf.stop_gradient(td)\n entropy = -tf.reduce_sum(self.a_prob * tf.log(self.a_prob + 1e-5),\n axis=1, keep_dims=True) # encourage exploration\n self.exp_v = ENTROPY_BETA * entropy + exp_v\n self.a_loss = tf.reduce_mean(-self.exp_v)\n\n with tf.name_scope('local_grad'):\n self.a_grads = tf.gradients(self.a_loss, self.a_params)\n self.c_grads = tf.gradients(self.c_loss, self.c_params)\n\n self.global_step = tf.train.get_or_create_global_step()\n with tf.name_scope('sync'):\n with tf.name_scope('pull'):\n self.pull_a_params_op = [l_p.assign(g_p) for l_p, g_p in zip(self.a_params, global_net.a_params)]\n self.pull_c_params_op = [l_p.assign(g_p) for l_p, g_p in zip(self.c_params, global_net.c_params)]\n with tf.name_scope('push'):\n self.update_a_op = opt_a.apply_gradients(zip(self.a_grads, global_net.a_params), global_step=self.global_step)\n self.update_c_op = opt_c.apply_gradients(zip(self.c_grads, global_net.c_params))\n\n def _build_net(self, scope):\n w_init = tf.random_normal_initializer(0., .1)\n with tf.variable_scope('actor'):\n l_a = tf.layers.dense(self.s, 200, tf.nn.relu6, kernel_initializer=w_init, name='la')\n a_prob = tf.layers.dense(l_a, N_A, tf.nn.softmax, kernel_initializer=w_init, name='ap')\n with tf.variable_scope('critic'):\n l_c = tf.layers.dense(self.s, 100, tf.nn.relu6, kernel_initializer=w_init, name='lc')\n v = tf.layers.dense(l_c, 1, kernel_initializer=w_init, name='v') # state value\n a_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=scope + '/actor')\n c_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=scope + '/critic')\n return a_prob, v, a_params, c_params\n\n def choose_action(self, s): # run by a local\n prob_weights = self.sess.run(self.a_prob, feed_dict={self.s: s[np.newaxis, :]})\n action = np.random.choice(range(prob_weights.shape[1]),\n p=prob_weights.ravel()) # select action w.r.t the actions prob\n return action\n\n def update_global(self, feed_dict): # run by a local\n self.sess.run([self.update_a_op, self.update_c_op], feed_dict) # local grads applies to global net\n\n def pull_global(self): # run by a local\n self.sess.run([self.pull_a_params_op, self.pull_c_params_op])\n\n\ndef work(job_name, task_index, global_ep, lock, r_queue, global_running_r):\n # set work's ip:port\n cluster = tf.train.ClusterSpec({\n \"ps\": ['localhost:2220', 'localhost:2221',],\n \"worker\": ['localhost:2222', 'localhost:2223', 'localhost:2224', 'localhost:2225',]\n })\n server = tf.train.Server(cluster, job_name=job_name, task_index=task_index)\n if job_name == 'ps':\n print('Start Parameter Sever: ', task_index)\n server.join()\n else:\n t1 = time.time()\n env = gym.make('CartPole-v0').unwrapped\n print('Start Worker: ', task_index)\n with tf.device(tf.train.replica_device_setter(\n worker_device=\"/job:worker/task:%d\" % task_index,\n cluster=cluster)):\n opt_a = tf.train.RMSPropOptimizer(LR_A, name='opt_a')\n opt_c = tf.train.RMSPropOptimizer(LR_C, name='opt_c')\n global_net = ACNet('global_net')\n\n local_net = ACNet('local_ac%d' % task_index, opt_a, opt_c, global_net)\n # set training steps\n hooks = [tf.train.StopAtStepHook(last_step=100000)]\n with tf.train.MonitoredTrainingSession(master=server.target,\n is_chief=True,\n hooks=hooks,) as sess:\n print('Start Worker Session: ', task_index)\n local_net.sess = sess\n total_step = 1\n buffer_s, buffer_a, buffer_r = [], [], []\n while (not sess.should_stop()) and (global_ep.value < 1000):\n s = env.reset()\n ep_r = 0\n while True:\n # if task_index:\n # env.render()\n a = local_net.choose_action(s)\n s_, r, done, info = env.step(a)\n if done: r = -5.\n ep_r += r\n buffer_s.append(s)\n buffer_a.append(a)\n buffer_r.append(r)\n\n if total_step % UPDATE_GLOBAL_ITER == 0 or done: # update global and assign to local net\n if done:\n v_s_ = 0 # terminal\n else:\n v_s_ = sess.run(local_net.v, {local_net.s: s_[np.newaxis, :]})[0, 0]\n buffer_v_target = []\n for r in buffer_r[::-1]: # reverse buffer r\n v_s_ = r + GAMMA * v_s_\n buffer_v_target.append(v_s_)\n buffer_v_target.reverse()\n\n buffer_s, buffer_a, buffer_v_target = np.vstack(buffer_s), np.array(buffer_a), np.vstack(\n buffer_v_target)\n feed_dict = {\n local_net.s: buffer_s,\n local_net.a_his: buffer_a,\n local_net.v_target: buffer_v_target,\n }\n local_net.update_global(feed_dict)\n buffer_s, buffer_a, buffer_r = [], [], []\n local_net.pull_global()\n s = s_\n total_step += 1\n if done:\n if r_queue.empty(): # record running episode reward\n global_running_r.value = ep_r\n else:\n global_running_r.value = .99 * global_running_r.value + 0.01 * ep_r\n r_queue.put(global_running_r.value)\n\n print(\n \"Task: %i\" % task_index,\n \"| Ep: %i\" % global_ep.value,\n \"| Ep_r: %i\" % global_running_r.value,\n \"| Global_step: %i\" % sess.run(local_net.global_step),\n )\n with lock:\n global_ep.value += 1\n break\n\n print('Worker Done: ', task_index, time.time()-t1)\n\n\nif __name__ == \"__main__\":\n # use multiprocessing to create a local cluster with 2 parameter servers and 2 workers\n global_ep = mp.Value('i', 0)\n lock = mp.Lock()\n r_queue = mp.Queue()\n global_running_r = mp.Value('d', 0)\n\n jobs = [\n ('ps', 0), ('ps', 1),\n ('worker', 0), ('worker', 1), ('worker', 2), ('worker', 3)\n ]\n ps = [mp.Process(target=work, args=(j, i, global_ep, lock, r_queue, global_running_r), ) for j, i in jobs]\n [p.start() for p in ps]\n [p.join() for p in ps[2:]]\n\n ep_r = []\n while not r_queue.empty():\n ep_r.append(r_queue.get())\n plt.plot(np.arange(len(ep_r)), ep_r)\n plt.title('Distributed training')\n plt.xlabel('Step')\n plt.ylabel('Total moving reward')\n plt.show()\n\n\n\n","repo_name":"MorvanZhou/Reinforcement-learning-with-tensorflow","sub_path":"contents/10_A3C/A3C_distributed_tf.py","file_name":"A3C_distributed_tf.py","file_ext":"py","file_size_in_byte":9199,"program_lang":"python","lang":"en","doc_type":"code","stars":8390,"dataset":"github-code","pt":"32"}
+{"seq_id":"20571216081","text":"# Import all definitions from the lexer, parser and semantic_analyser code\nfrom lexer import *\nfrom parser_ import *\nfrom semantic_analyser import *\n\n# Custom exception class for code generation errors\nclass CodeGenerationError(Exception):\n def __init__(self, message=\"An error occurred during code generation.\"):\n self.message = message\n super().__init__(self.message)\n\nclass PixIRCodeGenerator:\n def __init__(self, ast):\n # The abstract syntax tree to be traversed\n self.ast = ast\n # List of generated code lines\n self.code = []\n # Offset to track the relative position of variables in memory\n self.frame_offset = 0\n # Dictionary to store variables and their corresponding offsets\n self.variables = {} \n \n #---------------------------------------------------------------------------------------------------------------------------------------\n \n def visit(self, node):\n # Check if the node is a tuple. If so, it's a node we can visit.\n if isinstance(node, tuple):\n # Generate method name for visiting this node type\n method_name = f'visit_{node[0]}'\n # Try to get the method from the current instance, if it doesn't exist, use generic_visit method\n visitor = getattr(self, method_name, self.generic_visit)\n # Call the method and return its result\n return visitor(node)\n else:\n # If the node is not a tuple, raise an error indicating the node type is unsupported\n raise CodeGenerationError(f\"Unsupported node type '{type(node).__name__}'.\")\n \n #---------------------------------------------------------------------------------------------------------------------------------------\n \n def generic_visit(self, node):\n # If a specific visit method for a node type is not implemented, this method is called.\n # Raise an error indicating the node type is unsupported.\n raise CodeGenerationError(f\"No visit method implemented for node type '{node[0]}'.\")\n \n #---------------------------------------------------------------------------------------------------------------------------------------\n \n def get_var_offset(self, name):\n # Check if the variable has been declared\n if name not in self.variables:\n # If not, raise an error\n raise CodeGenerationError(f\"Variable '{name}' has not been declared.\")\n # If the variable has been declared, return its offset\n return self.variables[name]\n \n #---------------------------------------------------------------------------------------------------------------------------------------\n \n def visit_DECLARATION(self, node):\n # Unpack the node, which contains the data type, name and expression of the variable to be declared\n _, data_type, name, expression = node\n \n # Visit the expression node to evaluate its value\n self.visit(expression)\n \n # Generate PixIR code to allocate memory for the variable\n self.code.append(\"push 1\")\n self.code.append(\"alloc\")\n\n # Generate PixIR code to store the evaluated value in the allocated memory\n self.code.append(f\"push {self.frame_offset}\")\n self.code.append(\"push 0\")\n self.code.append(\"st\")\n\n # Save the frame offset of the declared variable in the variables dictionary\n self.variables[name] = self.frame_offset\n\n # Increment the frame offset for the next variable\n self.frame_offset += 1\n \n #---------------------------------------------------------------------------------------------------------------------------------------\n\n def visit_ASSIGNMENT(self, node):\n # Unpack the node, which contains the name and expression of the variable to be assigned\n _, name, expression = node\n \n # Visit the expression node to evaluate its value\n self.visit(expression)\n\n # Get the frame offset of the variable to be assigned\n var_offset = self.get_var_offset(name)\n\n # Generate PixIR code to store the evaluated value in the memory location of the variable\n self.code.append(f\"push {var_offset}\")\n self.code.append(\"push 0\")\n self.code.append(\"st\")\n \n #---------------------------------------------------------------------------------------------------------------------------------------\n\n def visit_PLUS(self, node):\n # Visit the nodes of the operands of the plus operation to evaluate their values\n self.visit(node[1])\n self.visit(node[2])\n\n # Generate PixIR code to perform the addition operation\n self.code.append(\"add\")\n\n def visit_MUL(self, node):\n # Visit the nodes of the operands of the multiplication operation to evaluate their values\n self.visit(node[1])\n self.visit(node[2])\n\n # Generate PixIR code to perform the multiplication operation\n self.code.append(\"mul\")\n\n #--------------------------------------------------------------------------------------------------------------------------------------- \n \n def visit_VARIABLE(self, node):\n # Unpack the node, which contains the name of the variable\n _, name = node\n \n # Get the frame offset of the variable\n var_offset = self.get_var_offset(name)\n\n # Generate PixIR code to load the value of the variable from memory\n self.code.append(f\"push {var_offset}\")\n self.code.append(\"push 0\")\n self.code.append(\"ld\")\n \n #---------------------------------------------------------------------------------------------------------------------------------------\n\n def visit_INTEGER_LITERAL(self, node):\n # Unpack the node, which contains the integer value\n _, value = node\n \n # Generate PixIR code to push the integer value onto the stack\n self.code.append(f\"push {value}\")\n \n #---------------------------------------------------------------------------------------------------------------------------------------\n\n def visit_FLOAT_LITERAL(self, node):\n # Unpack the node, which contains the float value\n _, value = node\n \n # Generate PixIR code to push the float value onto the stack\n self.code.append(f\"push {value}\")\n \n #---------------------------------------------------------------------------------------------------------------------------------------\n\n def visit_BOOLEAN_LITERAL(self, node):\n # Unpack the node, which contains the boolean value\n _, value = node\n \n # Generate PixIR code to push the boolean value (converted to an integer) onto the stack\n self.code.append(f\"push {int(value)}\")\n \n #---------------------------------------------------------------------------------------------------------------------------------------\n\n def visit_COLOR_LITERAL(self, node):\n # Unpack the node, which contains the color value\n _, value = node\n \n # Generate PixIR code to push the color value onto the stack\n self.code.append(f\"push {value}\")\n \n #---------------------------------------------------------------------------------------------------------------------------------------\n\n def visit_STRING_LITERAL(self, node):\n # Unpack the node, which contains the string value\n _, value = node\n \n # Encode the string value into a comma-separated string of ordinal values\n encoded_string = \",\".join(str(ord(char)) for char in value)\n \n # Generate PixIR code to push the encoded string onto the stack\n self.code.append(f'push \"{encoded_string}\"')\n \n #---------------------------------------------------------------------------------------------------------------------------------------\n\n def visit_PRINT(self, node):\n # Unpack the node, which contains the expression to be printed\n _, expression = node\n \n # Visit the expression node to evaluate its value\n self.visit(expression)\n \n # Generate PixIR code to print the evaluated value\n self.code.append(\"print\")\n \n #---------------------------------------------------------------------------------------------------------------------------------------\n\n def visit_DELAY(self, node):\n # Unpack the node, which contains the delay node\n _, delay_node = node\n \n # Visit the delay node to evaluate its value\n self.visit(delay_node)\n \n # Generate PixIR code to perform a delay operation\n self.code.append(\"delay\")\n\n #---------------------------------------------------------------------------------------------------------------------------------------\n \n def visit_PIXEL_STATEMENT(self, node):\n # Unpack the node, which contains arguments for the pixel statement\n _, arguments = node\n x, y, color = arguments\n\n # Visit the nodes for x, y, and color to evaluate their values\n self.visit(x) \n self.visit(y) \n self.visit(color)\n\n # Generate PixIR code to perform a pixel operation\n self.code.append(\"pixel\")\n\n def visit_PIXELR_STATEMENT(self, node):\n # Unpack the node, which contains arguments for the pixelr statement\n _, arguments = node\n x, y, color, radius, end_color = arguments\n\n # Visit the nodes for x, y, color, radius, and end_color to evaluate their values\n self.visit(x)\n self.visit(y)\n self.visit(color)\n self.visit(radius)\n self.visit(end_color)\n\n # Generate PixIR code to perform a pixelr operation\n self.code.append(\"pixelr\")\n \n #---------------------------------------------------------------------------------------------------------------------------------------\n\n def visit_WIDTH(self, node):\n # Unpack the node, which contains the width node\n _, width_node = node\n self.visit(width_node) # Visit the width node to evaluate its value\n\n # Generate PixIR code to perform a width operation\n self.code.append(\"width\")\n \n def visit_HEIGHT(self, node):\n # Unpack the node, which contains the height node\n _, height_node = node\n self.visit(height_node) # Visit the height node to evaluate its value\n\n # Generate PixIR code to perform a height operation\n self.code.append(\"height\")\n \n #---------------------------------------------------------------------------------------------------------------------------------------\n\n def visit_READ_STATEMENT(self, node):\n # Unpack the node, which contains arguments for the read statement\n _, arguments = node\n x, y = arguments\n\n # Visit the nodes for x and y to evaluate their values\n self.visit(x)\n self.visit(y)\n\n # Generate PixIR code to perform a read operation\n self.code.append(\"read\")\n \n #---------------------------------------------------------------------------------------------------------------------------------------\n\n def visit_IDENTIFIER(self, node):\n # Unpack the node, which contains the name of the identifier\n _, name = node\n var_offset = self.get_var_offset(name)\n\n # Generate PixIR code to load the value of the identifier from memory\n self.code.append(f\"push {var_offset}\")\n self.code.append(\"push 0\")\n self.code.append(\"ld\")\n \n #---------------------------------------------------------------------------------------------------------------------------------------\n\n def visit_RANDI_STATEMENT(self, node):\n # Unpack the node, which contains the expression for the randi statement\n _, expression = node\n self.visit(expression) # Visit the expression node to evaluate its value\n\n # Generate PixIR code to perform a randi operation\n self.code.append(\"irnd\")\n \n #---------------------------------------------------------------------------------------------------------------------------------------\n \n def visit_RELATIONAL_OPERATOR(self, node):\n # Unpack the node, which contains the left and right expressions for the relational operator\n _, left_expr, right_expr = node\n\n # Determine the type of the operator based on the types of the left and right expressions\n if left_expr[0] == \"IDENTIFIER\" and right_expr[0] == \"INTEGER_LITERAL\":\n operator = \">\"\n elif left_expr[0] == \"INTEGER_LITERAL\" and right_expr[0] == \"IDENTIFIER\":\n operator = \"<\"\n else:\n raise CodeGenerationError(f\"Unsupported relational operator between {left_expr[0]} and {right_expr[0]}.\")\n\n # Visit the left and right expression nodes to evaluate their values\n self.visit(left_expr)\n self.visit(right_expr)\n\n # Add the appropriate operation to the code based on the operator\n if operator == \"<\":\n self.code.append(\"lt\")\n elif operator == \"<=\":\n self.code.append(\"le\")\n elif operator == \">\":\n self.code.append(\"gt\")\n elif operator == \">=\":\n self.code.append(\"ge\")\n elif operator == \"==\":\n self.code.append(\"eq\")\n elif operator == \"!=\":\n self.code.append(\"neq\")\n else:\n raise CodeGenerationError(f\"Unsupported relational operator '{operator}'.\")\n \n #---------------------------------------------------------------------------------------------------------------------------------------\n\n def visit_WHILE(self, node):\n # Unpack the node, which contains the condition and body for the while loop\n _, condition, body = node\n\n # Generate PixIR code to mark the start of the loop\n self.code.append(\".WHILE_START\") \n\n # Visit the condition node to evaluate its value\n self.visit(condition)\n\n # Generate PixIR code to jump to the end of the loop if the condition is false\n self.code.append(\"cjmp .WHILE_END\")\n\n # Visit the body node to generate PixIR code for the body of the loop\n self.visit(body)\n\n # Generate PixIR code to jump back to the start of the loop\n self.code.append(\"jmp .WHILE_START\")\n\n # Generate PixIR code to mark the end of the loop\n self.code.append(\".WHILE_END\")\n \n #---------------------------------------------------------------------------------------------------------------------------------------\n\n def visit_BLOCK(self, node):\n # Unpack the node, which contains the statements for the block\n _, statements = node\n\n # Visit each statement node to generate PixIR code for each statement\n for statement in statements:\n self.visit(statement)\n \n #---------------------------------------------------------------------------------------------------------------------------------------\n\n def visit_IF(self, node):\n # Unpack the node, which contains the condition, if block, and else block for the if statement\n _, condition, if_block, *else_block = node\n\n # Visit the condition node to evaluate its value\n self.visit(condition)\n\n # Generate PixIR code to jump to the else block if the condition is false\n self.code.append(\"cjmp .ELSE\")\n\n # Visit the if block node to generate PixIR code for the if block\n self.visit(if_block)\n\n # Generate PixIR code to jump to the end of the if statement if the if block was executed\n self.code.append(\"jmp .ENDIF\")\n\n # If there is an else block, visit the else block node to generate PixIR code for the else block\n if else_block:\n self.visit(else_block[0])\n\n # Generate PixIR code to mark the end of the if statement\n self.code.append(\".ENDIF\")\n \n def visit_ELSE(self, node):\n _, _, else_block = node\n\n # This label will be jumped to if the condition in the IF statement was false\n self.code.append(\".ELSE\")\n\n # Visit the ELSE block\n self.visit(else_block)\n\n #---------------------------------------------------------------------------------------------------------------------------------------\n \n def visit_FUNCTION_DEF(self, node):\n _, function_name, parameters, return_type, body = node\n\n # Generate a label for the function name\n self.code.append(f\".{function_name}\")\n\n # Add parameters to the variable environment and adjust the frame offset\n for parameter in parameters:\n name, type_ = parameter\n self.variables[name] = self.frame_offset\n self.frame_offset += 1\n\n # Generate code for the function body\n self.visit(body)\n\n # Add a return statement if not already present in the body\n if body[-1][0] != \"RETURN\":\n self.code.append(\"ret\")\n\n def visit_RETURN(self, node):\n _, expression = node\n if expression is not None:\n # Generate code to load the value of the returned variable onto the stack\n name = expression[1]\n var_offset = self.get_var_offset(name)\n self.code.append(f\"push {var_offset}\")\n self.code.append(\"push 0\")\n self.code.append(\"ld\")\n\n self.code.append(\"ret\")\n\n #---------------------------------------------------------------------------------------------------------------------------------------\n \n # ToDo For loop \n \n #---------------------------------------------------------------------------------------------------------------------------------------\n\n def generate(self):\n # Loop over each node in the abstract syntax tree (AST)\n for node in self.ast:\n # Call the visit method to generate PixIR code for each node\n self.visit(node)\n \n # Append the 'ret' instruction to the end of the code to mark the end of the program\n self.code.append(\"ret\")\n\n # Join all the PixIR code lines with new line characters and return the result\n return \"\\n\".join(self.code)\n \n###########################################################################################################################################\n\n# Usage:\n\n# Specify the name of the file\nfilename = 'input.txt'\n\n# Open the file and read the contents into a string\nwith open(filename, 'r') as file:\n source_code = file.read()\n\ntry:\n # Tokenization\n lexer = Lexer(source_code)\n tokens = lexer.tokenize()\n\n # Parsing\n parser = Parser(tokens)\n ast = parser.parse()\n \n # Semantic Analysis\n semantic_analyzer = SemanticAnalyzer(ast)\n for node in ast:\n semantic_analyzer.visit(node)\n\n # PixIR Code Generation\n code_generator = PixIRCodeGenerator(ast)\n pixir_code = code_generator.generate()\n print(\"\\nGenerated PixIR code:\\n\")\n print(pixir_code)\n print(\"\\n\"+\"-\"*100)\n\nexcept LexerError as e:\n print(f\"Error: {e}\")\nexcept ParserError as e:\n print(f\"Error: {e}\")\nexcept SemanticError as e:\n print(f\"Error: {e}\")\nexcept CodeGenerationError as e:\n print(f\"Error: {e}\")","repo_name":"markdingli18/Compiler_CPS2000_Assignment","sub_path":"compiler_assignment/compiler_code/code_generation.py","file_name":"code_generation.py","file_ext":"py","file_size_in_byte":19372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"32043910237","text":"import requests\r\nimport json\r\n\r\nurl = 'http://localhost:8080/alarm/create_rule'\r\n\r\ndata = {\r\n\t'ruleName': \"CPU占用率过s高\",\r\n\t'target': \"CpuUtilization\",\r\n\t'valueType': \"average\",\r\n\t'compare': \">\",\r\n\t'threshold': 0.6,\r\n\t'count': 3,\r\n\t'r_target': \"CpuUtilization\",\r\n\t'r_valueType': \"average\",\r\n\t'r_compare': \"<\",\r\n\t'r_threshold': 0.6,\r\n\t'r_count': 3,\r\n}\r\n\r\nresponse = requests.post(url, data=data)\r\n\r\nprint(response.text)\r\n","repo_name":"DaydreamAndLife/EsperApplication","sub_path":"some scripts/test_for_create_Alarm.py","file_name":"test_for_create_Alarm.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"19780130122","text":"# https://programmers.co.kr/learn/courses/30/lessons/49189\nfrom collections import deque\n\n\n# bfs 하면서 거리 저장\n# 그래프 인접행렬로 표현했는데 시간초과. 인접리스트로 변경\ndef solution(n, edge):\n # 방문 겸 거리 저장 리스트\n distance = [-1] * (n + 1)\n ad_list = [[] for _ in range(n + 1)]\n\n # 인접 리스트 만들기, 인덱스가 노드 번호\n for a, b in edge:\n ad_list[a].append(b)\n ad_list[b].append(a)\n\n # bfs\n dq = deque()\n dq.append(1)\n distance[1] = 0\n\n while dq:\n v = dq.popleft()\n # 방문하지 않은 인접 노드 처리 후, 큐에 추가\n for i in ad_list[v]:\n if distance[i] == -1:\n distance[i] = distance[v] + 1\n dq.append(i)\n\n return distance.count(max(distance))\n","repo_name":"YAEJIN-JEONG/Algorithm","sub_path":"프로그래머스/Lv3. 가장 먼 노드/경진/Lv3. 가장 먼 노드.py","file_name":"Lv3. 가장 먼 노드.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"32"}
+{"seq_id":"12868570552","text":"import json\nimport csv\nimport os\nimport pandas as pd\nimport sqlite3\nimport glob\nimport sqlalchemy\nfrom lor_deckcodes import LoRDeck, CardCodeAndCount\nimport sys\n\ndef get_dataframe():\n\tfiles = glob.glob('card_data/*.json')\n\n\tdata = []\n\tfor file in files:\n\t\tdata.append(pd.read_json(file))\n\n\tdata = pd.concat(data)\n\tdata = data[['cardCode', 'name', 'region', 'attack', 'cost', 'health', 'rarity']]\n\tfunc = lambda x: False if 'T' in x[-3:] else True\n\tmask = data['cardCode'].apply(func)\n\tdata = data[mask]\n\n\t## This will be changed to grab the wins and losses from database\n\t# data['winrate'] = 0\n\tdata = data.reset_index(drop=True)\n\treturn data\n\n# Simple 'save csv file to the database'\ndef importToDatabase(filename):\n\tfile = 'card_data/' + filename + '.csv' # CSV file to import into database\n\tconnection = sqlite3.connect('card_data/stattracker.db')\n\n\t# Reading csv file to database\n\tdata = pd.read_csv(file)\n\tdel data[\"DeckCode\"] # deletes the column with the deck code\n\tdel data[\"Unnamed: 0\"] # deletes that extra column at the beginning\n\tdata.to_sql(filename, connection, if_exists='replace', index=False)\n\tos.remove(file)\n\n# Adds a list of decks from excel file to databse\n# Changes the names of the decks to the deck codes\ndef addDeckDB(filename):\n\tfile = \"card_data/\" + filename + \".xlsx\"\n\tdeckList = pd.read_excel(file, sheet_name=None)\n\n\tfor x in deckList.keys():\n\t\ttemp = pd.read_excel(file, sheet_name=x)\n\t\tdeckName = temp.iloc[0]['DeckCode']\n\t\ttemp.to_csv('card_Data/' + deckName + '.csv', header=True)\n\t\timportToDatabase(deckName)\n\n# adds stats from a game to database\n# deckName = deck code\n# gameStates = an array with\n# - Win/Losses - W or L\n# - Opponent Regions - String (Region1 / Region2)\n# - Opponent Champs - String (Champion1 / Champion2 / Champion3 / ...)\ndef addGameDB(deckname, gameStats):\n\tconnection = sqlite3.connect('card_data/stattracker.db')\n\tc = connection.cursor()\n\n\toutcome = gameStats [0]\n\tregions = gameStats [1]\n\tchampions = gameStats [2]\n\twith connection:\n\t\tc.execute(\"CREATE TABLE IF NOT EXISTS \" + deckname + \" ('Win/Loss', 'Opponent Regions', 'Opponent Champs')\")\n\t\tc.execute(\"INSERT INTO \" + deckname + \" VALUES(?, ?, ?)\", (outcome, regions, champions))\n\n# Grabs a deck from the database and returns it\ndef getDeck(deckname):\n\tconnection = sqlite3.connect('card_data/stattracker.db')\n\tc = connection.cursor()\n\twith connection:\n\t\tc.execute(\"CREATE TABLE IF NOT EXISTS \" + deckname + \" ('Win/Loss', 'Opponent Regions', 'Opponent Champs')\")\n\t\tc.execute(\"SELECT * FROM \" + deckname)\n\t\treturn c.fetchall()\n\n# checks if user exists\n# if not adds them to database and returns true\n# if yes, returns false\ndef createUser(name):\n\t# create an connection\n\tconnection = sqlite3.connect('card_data/usersdecks.db')\n\tc = connection.cursor()\n\n\twith connection:\n\t\tc.execute(\"SELECT count(*) FROM sqlite_master WHERE type='table' AND name='\" + name + \"'\")\n\t\tif c.fetchone()[0] == 1:\n\t\t\treturn True # user already exists\n\t\tc.execute(\"CREATE TABLE IF NOT EXISTS \" + name + \" ('Deckname', 'Deckcode')\")\n\n\treturn False # returns that it didn't exist\n\n# user = name of user\n# stats = deckname (from user), deckcode\n# ^^ is an array so it's easier if in the future we want to save more information about the user\ndef addUserDeck(user, stats):\n\t# create connection\n\tconnection = sqlite3.connect('card_data/usersdecks.db')\n\tc = connection.cursor()\n\twith connection:\n\t\tc.execute(\"SELECT EXISTS (SELECT 1 FROM \" + user + \" WHERE Deckcode='\" + stats[1] + \"')\")\n\t\texisting = c.fetchone()[0]\n\t\tif existing:\n\t\t\treturn True\n\t\telse:\n\t\t\tc.execute(\"INSERT INTO \" + user + \" VALUES(?, ?)\", (stats[0], stats[1]))\n\t\t\tc.close()\n\n\tmastConnection = sqlite3.connect('card_data/stattracker.db')\n\tc = mastConnection.cursor()\n\tc.execute(\"CREATE TABLE IF NOT EXISTS \" + stats[1] + \" ('Win/Loss', 'Opponent Regions', 'Opponent Champs')\")\n\tc.close()\n\treturn False # used for display an error message\n\n# grabs the users deckname and corresponding deck codes\ndef grabUsersDecks(user):\n\tconnection = sqlite3.connect('card_data/usersdecks.db')\n\tc = connection.cursor()\n\n\twith connection:\n\t\tc.execute(\"SELECT Deckname, Deckcode FROM \" + user)\n\n\treturn c.fetchall()\n\ndef get_champs():\n\tdata = get_dataframe()\n\treturn data[data['rarity'] == 'Champion']['name'].to_list()\n\n## Takes in a valid card code and returns a pandas dataframe with\ndef buildFromCode(code):\n\tdata = get_dataframe()\n\tdeck = LoRDeck.from_deckcode(code)\n\n\t# codes = [(card.card_code, card.count) for card in deck.cards]\n\tnewDeck = pd.DataFrame(columns=data.columns)\n\n\tfor i, card in enumerate(deck.cards):\n\t\trow = data.loc[data['cardCode'] == card.card_code]\n\t\tnewDeck = newDeck.append(row, ignore_index=True)\n\t\tnewDeck.loc[i, 'count'] = int(card.count)\n\tnewDeck['count'] = newDeck['count'].astype(int)\n\treturn newDeck\n\n## Creates a code from deck\ndef exportCode(deck):\n\tcol = deck['count'].apply(int).apply(str) + ':' + deck['cardCode']\n\tdeck = LoRDeck(col.to_list())\n\treturn deck.encode()\n\nif __name__ == '__main__':\n\tdata = get_dataframe() # do not delete\n\n\t# getDeck(\"temp\")\n\n\tdeck = buildFromCode('CICACAYABYBAEBQFCYBAEAAGBEDQCAABBEFR2JJHGMBACAIACUAQEAAHAA')\n\tprint(deck)\n\tprint(exportCode(deck))","repo_name":"COSC481W-2020Fall/cosc481w-581-2020-fall-stattracker","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"17074272657","text":"from sqlalchemy import BIGINT, Boolean, Column, DateTime, Float, ForeignKey, Integer, String, UniqueConstraint, func\nfrom sqlalchemy.orm import relationship\n\nfrom .base import Base\n\n\nclass TelegramChannel(Base):\n __tablename__ = \"telegram_channels\"\n\n _id = Column(Integer, primary_key=True)\n\n channel_name = Column(String, nullable=False)\n telegram = Column(BIGINT, nullable=False)\n max_price = Column(Float, nullable=False)\n message_thread_id = Column(Integer, nullable=True)\n\n spec_id = Column(Integer, ForeignKey(\"specs._id\"), nullable=False)\n spec = relationship(\"Spec\", uselist=False)\n product_spec_value = Column(String, nullable=False)\n\n created_at = Column(DateTime, server_default=func.now())\n updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())\n deleted = Column(Boolean, server_default=\"False\")\n\n UniqueConstraint(telegram, spec_id, product_spec_value, name=\"u_telegram_spec_id_product_spec_value\")\n","repo_name":"MDaniel592/StockFinderModels","sub_path":"TelegramChannel.py","file_name":"TelegramChannel.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"35335561019","text":"# https://adventofcode.com/2020/day/12\n\nimport numpy as np\n\nDIR = 'ESWN'\nDELTA = {\n 'E': np.array([1, 0]), 'W': np.array([-1, 0]),\n 'N': np.array([0, 1]), 'S': np.array([0, -1])\n}\n\ndef parse(line): return line[0], int(line[1:])\n\ndef fst_star(instructions): \n pos, d = np.zeros(2, int), 0\n for action, value in instructions:\n if action in 'LR': \n cw = [-1, 1][action == 'R']\n d = (d + value//90 * cw) % 4\n if action == 'F': pos += DELTA[DIR[d]] * value\n if action in DIR: pos += DELTA[action] * value\n return sum(map(abs, pos))\n\ndef snd_star(instructions):\n def rotate(v, action, value):\n cw = [-1, 1][action == 'R']\n n = (value//90 * cw) % 4\n for _ in range(n): v = v[1], -v[0]\n return np.array(v)\n\n ship, v = np.zeros(2, int), np.array([10, 1])\n for action, value in instructions:\n if action in 'LR': v = rotate(v, action, value)\n if action == 'F': ship += v * value\n if action in DIR: v += DELTA[action] * value\n return sum(map(abs, ship))\n\nTEST = '''\\\nF10\nN3\nF7\nR90\nF11'''.splitlines()\n\nif __name__ == '__main__':\n assert fst_star(map(parse, TEST)) == 25\n assert snd_star(map(parse, TEST)) == 286\n instructions = [*map(parse, open('data/day12.in'))]\n print(fst_star(instructions))\n print(snd_star(instructions))","repo_name":"andy1li/adventofcode","sub_path":"2020/day12_manhattan.py","file_name":"day12_manhattan.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"}
+{"seq_id":"5859869788","text":"#Ejercicio 2.17\n#Crear una función contar_vocales(), que reciba una palabra y cuente cuantas letras \"a\"\n#tiene, cuantas letras \"e\" tiene y así hasta completar todas las vocales.\n#Se puede hacer que el usuario sea quien elija la palabra.\n\npalabra = input(\"inserte palabra para contar vocales: \")\n\ndef contar_vocales(palabra):\n conteo = 0\n numero = 0\n for character in palabra:\n if character in [\"a\", \"e\", \"i\", \"o\", \"u\"]:\n numero+=1\n conteo=+numero\n\n print(conteo)\n\ncontar_vocales(palabra)\n\n","repo_name":"doggymux/P01-PPS","sub_path":"Ejercicios/Parte2/Ejercicio2-17.py","file_name":"Ejercicio2-17.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"20800705359","text":"import tensorflow as tf\r\ntf.compat.v1.enable_eager_execution()\r\n#sess=tf.InteractiveSession()\r\n\r\nds = tf.data.Dataset.from_tensor_slices([[1,2,3],[4,5,6],[7,8,9]])\r\n\r\nds_flatmap = ds.flat_map(lambda x: tf.data.Dataset.from_tensor_slices(x + 1))\r\niter=ds_flatmap.make_initializable_iterator()\r\nprint(tf.keras.__version__)\r\n# tf.print\r\n# sess.run(iter.initializer)\r\n# data=sess.run(iter.get_next())\r\n#\r\n# for x in data:\r\n# print(x)","repo_name":"FengJunJian/tutorials_for_demo","sub_path":"tf2/data_test1.py","file_name":"data_test1.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"73058513370","text":"import sys\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\nurls = []\n\ndef set_proxy(driver, http_addr='', http_port=0, ssl_addr='', ssl_port=0, socks_addr='', socks_port=0):\n driver.execute(\"SET_CONTEXT\", {\"context\": \"chrome\"})\n\n try:\n driver.execute_script(\"\"\"\n Services.prefs.setIntPref('network.proxy.type', 1);\n Services.prefs.setCharPref(\"network.proxy.http\", arguments[0]);\n Services.prefs.setIntPref(\"network.proxy.http_port\", arguments[1]);\n Services.prefs.setCharPref(\"network.proxy.ssl\", arguments[2]);\n Services.prefs.setIntPref(\"network.proxy.ssl_port\", arguments[3]);\n Services.prefs.setCharPref('network.proxy.socks', arguments[4]);\n Services.prefs.setIntPref('network.proxy.socks_port', arguments[5]);\n \"\"\", http_addr, http_port, ssl_addr, ssl_port, socks_addr, socks_port)\n\n finally:\n driver.execute(\"SET_CONTEXT\", {\"context\": \"content\"})\n\n\ndef get_range_by_asn(driver, url):\n driver.get('https://ipinfo.io/{}'.format(url))\n # try:\n if driver.title.__contains__('Too Many Requests'):\n print(\"[*] change proxy\")\n set_proxy(driver, http_addr=\"127.0.0.1\", http_port=8082) # socks5 service \n driver.get('https://ipinfo.io/{}'.format(url))\n try:\n driver.find_element(By.XPATH, '//*[@id=\"ipv4-data\"]/div/a').click()\n except:\n pass\n\n range_list = driver.find_elements(By.XPATH, '//*[@id=\"ipv4-data\"]')\n for ip in range_list:\n print(ip.text) # save data to neo4j\n\n file = open('ra-{}-ip.txt'.format(url), 'w')\n for ip in range_list:\n file.write(ip.text + '\\n')\n file.close()\n\ndef get_asn_by_country(driver):\n driver.get('https://ipinfo.io/countries/gb') # change country code\n try:\n next = driver.find_elements(By.XPATH, \"//td[@class='p-3']\")\n for i in next:\n if (i.text.find('AS')) == 0 and len(i.text) <= 9:\n urls.append(i.text)\n print('[+] ASN: {}'.format(i.text)) # save asn to neo4j\n\n except:\n pass\n\n\nif __name__ == \"__main__\":\n # proxy = \"127.0.0.1:8082\"\n # chrome_options = webdriver.ChromeOptions()\n # chrome_options.add_argument('--proxy-server=%s' % proxy)\n driver = webdriver.Chrome(service_log_path='message.log') # options=chrome_options\n\n get_asn_by_country(driver)\n\n file = open('at-asn.txt', 'w')\n for url in urls:\n file.write(url + '\\n')\n file.close()\n\n for url in urls:\n get_range_by_asn(driver, url)\n\n driver.close()\n","repo_name":"core1impact/pywitness","sub_path":"ipinfo.py","file_name":"ipinfo.py","file_ext":"py","file_size_in_byte":2564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"8461729162","text":"from actions.action import Action\nfrom agents.wolf_sheep_grass.sheep import Sheep\n\n\nclass EatSheep(Action):\n\n def act(self, wolf, env):\n cell = env.cells[wolf.x][wolf.y]\n for sheep_candidate in cell.agents:\n if isinstance(sheep_candidate, Sheep):\n self.wolf_eat_sheep(wolf, sheep_candidate, env)\n break\n\n @staticmethod\n def wolf_eat_sheep(wolf, sheep, env):\n wolf.energy += wolf.gain_from_food\n env.remove_agent(sheep)\n","repo_name":"Matin-Noohnezhad/agent_based_modeling","sub_path":"actions/wolf_sheep_grass/eat_sheep.py","file_name":"eat_sheep.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"72991645532","text":"from googleapiclient.discovery import build\r\nimport json\r\nimport pandas as pd\r\nimport creds\r\n\r\nyt = build('youtube', 'v3', developerKey=creds.api_key)\r\nreq = yt.channels().list(\r\n part='id, statistics, snippet',\r\n forUsername='nprmusic' # sample username from schafer\r\n)\r\nres = req.execute()\r\n#print(res)\r\n#print(json.dumps(res, indent=0)) \r\n#this does organization in json format\r\n\r\nuser_username = input()\r\ndef getID(yt, forUsername):\r\n req = yt.channels().list(\r\n part='id, statistics, snippet',\r\n forUsername=user_username # sample username from schafer\r\n )\r\n res = req.execute()\r\n for item in res['items']:\r\n new_id = item['id']\r\n return new_id\r\n\r\n#new_channelID = getID(yt, user_username) #extension on the URL\r\n#print(new_channelID)\r\n\r\ndef getVideosId(youtube, channelId):\r\n videosIdList = []\r\n nextPageToken = None\r\n\r\n while True:\r\n request = youtube.search().list(\r\n part=\"snippet\",\r\n channelId=channelId,\r\n maxResults=100,\r\n regionCode='US',\r\n pageToken=nextPageToken,\r\n )\r\n response = request.execute()\r\n\r\n for item in response['items']:\r\n if item['id']['kind'] == \"youtube#video\":\r\n videosIdList.append(item['id']['videoId'])\r\n\r\n nextPageToken = response.get('nextPageToken')\r\n if not nextPageToken:\r\n break\r\n\r\n return videosIdList\r\n\r\nprint('Enter Username to show all links to Videos and channel info: ')\r\nuser_username = input()\r\nlist_vids = getVideosId(yt, getID(yt, user_username))\r\n\r\nlinks = []\r\nfor ids in list_vids:\r\n newlink = 'https://www.youtube.com/watch?v=' + ids\r\n links.append(newlink)\r\nchart = pd.DataFrame(links)\r\nprint(chart)","repo_name":"thielt/YoutubeChannelLinks","sub_path":"youtube.py","file_name":"youtube.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"25490580653","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Source: https://leetcode.com/problems/maximum-subarray-min-product/\n# Author: Miao Zhang\n# Date: 2021-06-14\n\nclass Solution:\n def maxSumMinProduct(self, nums: List[int]) -> int:\n kMod = 10 ** 9 + 7\n n = len(nums)\n left = [0 for _ in range(n)]\n right = [n - 1 for _ in range(n)]\n stack = []\n for i in range(n):\n while stack and nums[stack[-1]] >= nums[i]:\n right[stack[-1]] = i - 1\n stack.pop()\n if stack:\n left[i] = stack[-1] + 1\n stack.append(i)\n sums = [0 for _ in range(n + 1)]\n for i in range(1, n + 1):\n sums[i] = sums[i - 1] + nums[i - 1]\n res = 0\n for i in range(n):\n res = max(res, (sums[right[i] + 1] - sums[left[i]]) * nums[i])\n return res % kMod\n \n","repo_name":"MichelleZ/leetcode","sub_path":"algorithms/python/maximumSubarrayMin-Product/maximumSubarrayMin-Product.py","file_name":"maximumSubarrayMin-Product.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"}
+{"seq_id":"8013048007","text":"import random\n\n## a list with 5 fruits\n\nword_list = [\"apple\", \"orange\", \"banana\", \"pear\", \"strawberry\"]\n\nprint(word_list)\n\n## assigning a random word to variable \"word\"\nword = random.choice(word_list)\n\nprint(word)\n\n## asking user for input\n\nguess = input('Enter a character: ')\n\nif len(guess) == 1 and guess.isalpha() == True:\n print(\"Good guess\")\nelse: \n print(\"Oops! That is not a valid input\")\n\n","repo_name":"alexaguileralopez/hangman","sub_path":"milestone_2.py","file_name":"milestone_2.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"35371870456","text":"import turtle as t\nimport random\n\nt.speed(0)\nt.color('red')\n\ndef drawStar(size):\n for i in range(5):\n t.fd(size)\n t.rt(144)\n\nt.begin_fill()\ndrawStar(200)\nt.end_fill()\n\n\n\n\n \n\n","repo_name":"minsuklee80/aggie","sub_path":"turtle/turtle_별그리기.py","file_name":"turtle_별그리기.py","file_ext":"py","file_size_in_byte":191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"72680634650","text":"lines = [line for line in open('input').read().split('\\n')]\nlines.sort(key=lambda line: line[6:17])\n\ndef determine_guard():\n sleeping_times = {}\n\n current_num = 0\n start = 0\n for l in lines:\n log = l[19:]\n if '#' in log:\n current_num = int(log[7:7+log[7:].index(' ')])\n else:\n minute = int(l[15:17])\n if 'asleep' in log:\n start = minute\n else: # awakening\n sleeping_times[current_num] = sleeping_times.get(current_num, 0) + (minute - start)\n m = max(sleeping_times.values())\n for k, v in sleeping_times.items():\n if v == m:\n return k\n\n\ndef choose_minute(guard):\n proper_guard = False\n mins = {m: 0 for m in range(0, 60)}\n start = 0\n for l in lines:\n if '#' + str(guard) in l:\n proper_guard = True\n elif '#' in l:\n proper_guard = False\n elif proper_guard:\n minute = int(l[15:17])\n if 'asleep' in l:\n start = minute\n else:\n for m in range(start, minute):\n mins[m] = mins.get(m) + 1\n ms = list(mins.items())\n ms.sort(key=lambda x: x[1], reverse=True)\n return ms[0][0]\n\n\nif __name__ == '__main__':\n guard = determine_guard()\n m = choose_minute(guard)\n print(m * guard)\n","repo_name":"belamenso/AOC_2018","sub_path":"4/4_1.py","file_name":"4_1.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"8200081021","text":"from ..database import Column, STRING, INTEGER, Relationship, DataBase, Model\nimport json\n\n\nclass Module(Model):\n db = DataBase(\n \"module\",\n Column(\"name\", STRING, unique=True, nullable=False),\n Column(\"text\", STRING, nullable=False),\n Column(\"description\", STRING),\n Column(\"sending_data\", STRING),\n )\n\n def __init__(self, *args, **kwargs):\n super(Module, self).__init__(**kwargs)\n","repo_name":"dmitriyVasilievich1986/flask_server","sub_path":"automation/modules/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"40837420702","text":"import sys\n# from math import *\nimport math\nfrom vanilla import *\nfrom mojo.UI import *\nfrom fontParts.world import CurrentFont, RGlyph\nfrom defconAppKit.windows.baseWindow import BaseWindowController\nfrom mojo.drawingTools import *\nfrom mojo.glyphPreview import GlyphPreview\nfrom fontTools.pens.cocoaPen import CocoaPen\nfrom mojo.canvas import Canvas\nfrom defconAppKit.controls.glyphCollectionView import GlyphCollectionView\nfrom AppKit import *\nfrom mojo.drawingTools import *\n# from lib.UI.fontOverView.speedGlyphCollectionView import SpeedGlyphCollectionView\nfrom mojo.events import addObserver, removeObserver\n\nfrom mojo.canvas import Canvas\n\nfrom mojo.drawingTools import *\n# from robofab.world import CurrentFont\n# from vanilla.nsSubclasses import getNSSubclass\nfrom defconAppKit.windows import *\n\nimport importlib\nimport tdGroupViews\nimportlib.reload(tdGroupViews)\nfrom tdGroupViews import TDGroupViewStacked\n\nimport tdKernToolEssentials\nimportlib.reload(tdKernToolEssentials)\nfrom tdKernToolEssentials import *\n\n\n#\n\ndef calculateHeightOfControl(font, groupname, baseHeight = 101):\n\ta = len(font.groups[groupname])\n\ty1 = 0\n\tif a > 10:\n\t\ty1 = ((a - 10) / 10)\n\t\t# print y1\n\t\td, v = math.modf(y1)\n\t\t# print d , int(v)\n\t\ty1 = int(v) * 100\n\t\tif d <= .5:\n\t\t\ty1 += 50\n\t\telif d > .5:\n\t\t\ty1 += 100\n\tbaseHeight += y1\n\treturn baseHeight\n\n\nclass TDGroupViewCell(VanillaBaseObject):\n\tnsViewClass = NSView\n\n\t# def __init__ (self, posSize, font=None, groupname=None, groupsChangedCallback = None):\n\tdef __init__ (self, posSize, groupsChangedCallback = None, selectionCallback = None):\n\n\t\txw, yw, tx, ty = posSize\n\t\ty = 101\n\t\tself._posSize = (xw, yw, tx, y)\n\t\tself._setupView(self.nsViewClass, (xw, yw, tx, y)) #101)) # (0, 0, -0, 106)\n\n\t\tself.groupsChangedCallback = groupsChangedCallback\n\t\tself.selectionCallback = selectionCallback\n\t\tself.groupname = None\n\t\tself.heightOfControl = y\n\t\txpos = -110\n\t\txGC = 0\n\t\txm = -105\n\n\t\tself.keyGlyphView = TDGroupViewStacked((xpos, 0, 100, 101),selectionCallback = self.selectGroupView, liveupdate = True, sizeStyle = 'big')\n\t\tdropSettings = dict(callback = self.groupsDropCallback)\n\t\tself.groupView = GlyphCollectionView((xGC, 0, xm-17, y-1 ), #117),\n\t\t showModePlacard = False,\n\t\t cellRepresentationName = \"doodle.GlyphCell\",\n\t\t # initialMode = \"cell\",\n\t\t listColumnDescriptions = None,\n\t\t listShowColumnTitles = False,\n\t\t showPlacard = False,\n\t\t placardActionItems = None,\n\t\t allowDrag = True,\n\t\t selfWindowDropSettings = dropSettings,\n\t\t selfApplicationDropSettings = dropSettings,\n\t\t selfDropSettings = dropSettings,\n\t\t otherApplicationDropSettings = dropSettings,\n\t\t doubleClickCallback = self.doubleClickCallback,\n\t\t selectionCallback = self.selectGroupView\n\n\t\t)\n\n\t\tself.groupView.setCellRepresentationArguments(drawHeader = True) # , drawMetrics = True\n\t\tself.groupView.setCellSize((46, 49))\n\t\t# self.groupView.getNSScrollView().setHasVerticalScroller_(False)\n\t\t# self.groupView.getNSScrollView().setHasHorizontalScroller_(False)\n\t\t#\n\t\t# self.groupView.getNSScrollView().setAutohidesScrollers_(False)\n\t\t# self.groupView.getNSScrollView().setDrawsBackground_(False)\n\t\t# self.groupView.getNSScrollView().setBackgroundColor_(NSColor.whiteColor())\n\n\t\t# self.groupView.getNSScrollView().setBorderType_(NSNoBorder)\n\n\n\n\tdef selectGroupView(self, info):\n\t\tif self.selectionCallback:\n\t\t\tself.selectionCallback(self.groupname)\n\n\n\tdef selected(self, selected = False):\n\t\tself.keyGlyphView.selected(selected)\n\t\tif not selected:\n\t\t\tself.groupView.setSelection([])\n\n\n\tdef doubleClickCallback(self, sender):\n\t\tglist = []\n\t\tfor gindex in self.groupView.getSelection():\n\t\t\tglist.append(self.groupView[gindex].name)\n\t\tw = OpenSpaceCenter(CurrentFont())\n\t\tw.set(glist)\n\n\n\tdef groupsDropCallback (self, sender, dropInfo):\n\t\t# print sender, dropInfo\n\t\t# groupper(sender, dropInfo)\n\t\tif dropInfo['isProposal']: pass\n\t\telse:\n\t\t\tdest = sender.id\n\t\t\tsource = dropInfo['source']\n\t\t\ttry:\n\t\t\t\tsourceid = source.id\n\t\t\texcept:\n\t\t\t\tprint (source)\n\t\t\t\tsourceid = None\n\t\t\tglist = []\n\t\t\tfor glyph in dropInfo['data']:\n\t\t\t\tglist.append(glyph.name) #= dropInfo['data']\n\n\t\t\tupdateGroups = False\n\t\t\tgroupsChanged = []\n\t\t\tif sourceid != dest:\n\t\t\t\tif sourceid == 'fontview' and dest != 'fontview':\n\t\t\t\t\taddGlyphsToGroup(self._font, dest, glist)\n\t\t\t\t\tgroupsChanged = [ dest, sourceid ]\n\t\t\t\t\tupdateGroups = True\n\n\t\t\t\telif sourceid != 'fontview' and dest == 'fontview':\n\t\t\t\t\tdelGlyphsFromGroup(self._font, sourceid, glist)\n\t\t\t\t\tgroupsChanged = [ dest, sourceid ]\n\t\t\t\t\tupdateGroups = True\n\n\t\t\t\telif sourceid != 'fontview' and dest != 'fontview':\n\t\t\t\t\tdelGlyphsFromGroup(self._font, sourceid, glist)\n\t\t\t\t\taddGlyphsToGroup(self._font, dest, glist)\n\t\t\t\t\tgroupsChanged = [ sourceid, dest ]\n\t\t\t\t\tupdateGroups = True\n\n\t\t\telif sourceid == dest:\n\t\t\t\tidx = dropInfo['rowIndex']\n\t\t\t\trepositionGlyphsInGroup(self._font, dest, idx, glist)\n\t\t\t\tgroupsChanged = [ dest, sourceid ]\n\t\t\t\tupdateGroups = True\n\n\t\t\tif updateGroups and self.groupsChangedCallback:\n\t\t\t\tself.groupsChangedCallback(groupsChanged)\n\n\t\treturn True\n\n\n\tdef setFont(self, font):\n\t\tself._font = font\n\n\n\tdef setPositionY(self,posSize):\n\t\ty = calculateHeightOfControl(self._font, groupname = self.groupname, baseHeight = 101) + 16\n\t\txw, yw, tx, ty = posSize\n\t\tself.setPosSize((xw, yw, tx, y))\n\t\tself.groupView.setPosSize((0, 0, -105 - 17, y - 17))\n\t\tself.heightOfControl = y\n\n\n\tdef setGroupView (self, font, groupname):\n\t\tself.setFont(font)\n\t\tself.groupname = groupname\n\t\tself.direction = getDirection(groupname)\n\t\tself.groupView.id = groupname\n\n\t\tself.setPositionY(self._posSize)\n\n\t\tself.keyGlyphView.setFont(self._font)\n\t\tself.keyGlyphView.setGroupStack(self.groupname)\n\t\tself.groupView.set(self.keyGlyphView.glyphsToDisplay)\n\t\t# print (self.keyGlyphView.glyphsToDisplay)\n\n\t\t# d = []\n\t\t# for g in self.keyGlyphView.glyphsToDisplay:\n\t\t# \td.append(g)\n\t\t# self.groupView.set(d)\n\t\t# self.setPositionY(self._posSize)\n\n\tdef clear (self):\n\t\tself.groupView.set([])\n\n\n\n\nclass TDGroupsCollectionView(VanillaBaseObject):\n\tnsViewClass = NSView\n\n\tdef __init__ (self, posSize, font=None, direction='L',\n\t groupsChangedCallback = None, selectionCallback = None,\n\t groupPrefix = ID_KERNING_GROUP):\n\t\txw, yw, tx, ty = posSize\n\t\tself._tx = tx\n\t\tself._setupView(self.nsViewClass, posSize) # (0, 0, -0, 106)\n\t\tself._font = font\n\t\tself.groupPrefix = groupPrefix\n\t\tself.groupsChangedCallback = groupsChangedCallback\n\t\tself.selectionCallback = selectionCallback\n\t\tself._listObjGroups = {}\n\t\tself._buildingView = True\n\n\t\tself.groupsList = []\n\t\tself.direction = direction\n\t\tself.currentGroupName = None\n\n\t\tself.view = Group((0, 0, -0, 1000000))\n\t\tself.scroll = ScrollView((0, 30, -5, -20), self.view.getNSView())\n\t\t# self.progressBar = ProgressBar((0,-15,-5,-5),sizeStyle = 'small',isIndeterminate = True)\n\t\t# self.progressBar.show(False)\n\t\tself.buildView(self.direction)\n\n\n\tdef buildView(self, direction):\n\n\t\tif self.direction != direction:\n\t\t\tself.clear()\n\n\t\tself.direction = direction\n\t\ty = 5\n\t\tself._buildingView = True\n\t\t# totalgroups = len(self._font.groups)\n\t\t# perc = totalgroups / 100\n\t\t# pairsCountProgress = 0\n\t\t# self.progressBar.set(0)\n\t\t# self.progressBar.start()\n\t\t# self.progressBar.show(True)\n\n\t\tself.view.show(False)\n\t\t# groupList = sortGroupsByGlyphOrder(self._font,self.direction)\n\t\tfor idx, groupname in enumerate(sorted(self._font.groups.keys())):\n\t\t# for idx, groupname in enumerate(groupList):\n\n\t\t\t# pairsCountProgress += 1\n\t\t\t# if round(perc, 0) == pairsCountProgress:\n\t\t\t# \t# self.progressBar.increment()\n\t\t\t# \tpairsCountProgress = 0\n\t\t\tif groupname.startswith(self.groupPrefix):\n\t\t\t\tif (self.direction == 'L' and ID_GROUP_DIRECTION_POSITION_LEFT in groupname) \\\n\t\t\t\t\t\tor (self.direction == 'R' and ID_GROUP_DIRECTION_POSITION_RIGHT in groupname):\n\t\t\t\t\tif groupname not in self._listObjGroups:\n\t\t\t\t\t\tobjName = \"grCtrl_%s\" % getUniqName()\n\t\t\t\t\t\tsetattr(self.view, objName,\n\t\t\t\t\t\t TDGroupViewCell((5, y, self._tx - 33, 0),\n\t\t\t\t\t\t groupsChangedCallback = self.groupsChanged,\n\t\t\t\t\t\t selectionCallback = self.selectedGroup))\n\t\t\t\t\t\tself.view.__getattribute__(objName).setGroupView(self._font, groupname)\n\t\t\t\t\t\t# self.groupsList.append(getDisplayNameGroup(groupname))\n\t\t\t\t\t\tself._listObjGroups[groupname] = {'nameObj': objName,\n\t\t\t\t\t\t 'posY': y,\n\t\t\t\t\t\t 'shortNameGroup': getDisplayNameGroup(groupname),\n\t\t\t\t\t\t 'direction': direction}\n\t\t\t\t\t# obj = getattr(self.view, self._listObjNames[idx])\n\t\t\t\t\t# obj.setGroupView(self._font, groupname)\n\t\t# self.groupsList = sorted(self.groupsList) #sortGroupsByGlyphOrder(self._font,self.direction, shortnames = True)\n\t\tself._buildingView = False\n\t\tself.view.show(True)\n\t\tself.repositionGroupViews()\n\t\t# self.progressBar.set(0)\n\t\t# self.progressBar.show(False)\n\t\t# self.progressBar.stop()\n\n\tdef deleteGroupViewByName(self, groupname):\n\t\tif groupname in self._listObjGroups:\n\t\t\tprevIdx = 0\n\t\t\tidx = 0\n\t\t\t# for gname in sortGroupsByGlyphOrder(self._font,self.direction):\n\t\t\tfor gname, obj in sorted(self._listObjGroups.items()):\n\t\t\t\tif gname == groupname:\n\t\t\t\t\tdelattr(self.view, self._listObjGroups[gname]['nameObj'])\n\t\t\t\t\tself._listObjGroups.pop(groupname)\n\t\t\t\t\tdel self._font.groups[groupname]\n\n\t\t\t\t\tprevIdx = idx - 1\n\t\t\t\t\tif prevIdx < 0:\n\t\t\t\t\t\tprevIdx = 0\n\n\t\t\t\t\tself.buildView(self.direction)\n\t\t\t\tidx += 1\n\t\t\tidx = 0\n\n\t\t\t# for gname in sortGroupsByGlyphOrder(self._font, self.direction):\n\t\t\tfor gname, obj in sorted(self._listObjGroups.items()):\n\t\t\t\tif idx == prevIdx:\n\t\t\t\t\tself.scrollToGroup(gname)\n\t\t\t\t\tself.currentGroupName = gname\n\t\t\t\t\tself.groupsChangedCallback(self)\n\t\t\t\t\treturn\n\t\t\t\tidx +=1\n\n\t\t# for objname in self._listObjGroups:\n\t\t# \tif self.view.__getattribute__(objname).groupname == groupname:\n\t\t# \t\tdelattr(self.view, objname)\n\t\t# \t\tself._listObjNames.remove(objname)\n\t\t# \t\tself._listController.pop(groupname)\n\t\t# \t\tself.groupsList.remove(getDisplayNameGroup(groupname))\n\t\t# \t\treturn\n\n\n\tdef clear(self):\n\t\tif self._listObjGroups:\n\t\t\tfor gN, obj in self._listObjGroups.items():\n\t\t\t\tself.view.__getattribute__(obj['nameObj']).clear()\n\t\t\t\tdelattr(self.view, obj['nameObj'])\n\t\t\tself._listObjGroups = {}\n\t\t\tself.groupsList = []\n\n\n\tdef scrollToGroup (self, groupName=None):\n\t\tif groupName:\n\t\t\tif groupName in self._listObjGroups.keys():\n\t\t\t\tpoint = NSPoint(0, self._listObjGroups[groupName]['posY'])\n\t\t\telse:\n\t\t\t\tgroupName = None\n\t\t\t\tpoint = NSPoint(0, 0)\n\t\telse:\n\t\t\tpoint = NSPoint(0, 0)\n\t\tself.scroll.getNSScrollView().contentView().scrollToPoint_(point)\n\t\tself.scroll.getNSScrollView().reflectScrolledClipView_(self.scroll.getNSScrollView().contentView())\n\t\tself.currentGroupName = groupName\n\n\n\tdef repositionGroupViews(self):\n\t\ty = 5\n\t\t# for gN in sortGroupsByGlyphOrder(self._font, self.direction):\n\t\t# \t# obj = self._listObjGroups[gN]\n\t\t# \tself.view.__getattribute__(self._listObjGroups[gN]['nameObj']).setPositionY((5, y, self._tx - 33, 0))\n\t\t# \tself._listObjGroups[gN]['posY'] = (0 - y) + 5\n\t\t# \ty += self.view.__getattribute__(self._listObjGroups[gN]['nameObj']).heightOfControl - 5\n\t\tgl = []\n\t\tfor gN, obj in sorted(self._listObjGroups.items()):\n\t\t\tself.view.__getattribute__(obj['nameObj']).setPositionY((5,y,self._tx - 33, 0))\n\t\t\tself._listObjGroups[gN]['posY'] = (0 - y) + 5\n\t\t\tgl.append(getDisplayNameGroup(gN))\n\t\t\ty += self.view.__getattribute__(obj['nameObj']).heightOfControl -5\n\n\t\tself.groupsList = gl\n\t\tself.view.setPosSize((0, 0, -0, y))\n\t\tframe = self.scroll.getNSScrollView().contentView().frame()\n\t\tself.view._setFrame(frame)\n\t\tself.scrollToGroup(self.currentGroupName)\n\n\n\tdef selectedGroup(self, info):\n\t\tif self._buildingView: return\n\t\tfor gN, obj in self._listObjGroups.items():\n\t\t\tif gN == info:\n\t\t\t\tself.view.__getattribute__(obj['nameObj']).selected(True)\n\t\t\t\tself.currentGroupName = info\n\t\t\telse:\n\t\t\t\tself.view.__getattribute__(obj['nameObj']).selected(False)\n\t\tif self.selectionCallback:\n\t\t\tself.selectionCallback(info)\n\n\n\tdef groupsChanged(self, info):\n\t\tif info:\n\t\t\tself.currentGroupName = info[0]\n\t\t\tfor groupname in info:\n\t\t\t\tif groupname in self._listObjGroups:\n\t\t\t\t\tself.view.__getattribute__(self._listObjGroups[groupname]['nameObj']).setGroupView(self._font, groupname)\n\t\t\tself.repositionGroupViews()\n\t\t\tself.selectedGroup(self.currentGroupName)\n\t\t\tself.groupsChangedCallback(self)\n\n\tdef updateGroupView(self, groupname):\n\t\tif groupname:\n\t\t\tself.groupsChanged([groupname])\n\n\tdef refresh(self):\n\t\tself.buildView(self.direction)\n\t\tself.groupsChangedCallback(self)\n\n\nclass TDFontView(VanillaBaseObject):\n\tnsViewClass = NSView\n\tdef __init__ (self, posSize, font=None, hideGrouped = True, direction = 'L',\n\t groupsChangedCallback = None, groupPrefix = '.MRX'):\n\t\txw, yw, tx, ty = posSize\n\t\tself._setupView(self.nsViewClass, posSize) # (0, 0, -0, 106)\n\t\tself._font = font\n\t\tself.groupsChangedCallback = groupsChangedCallback\n\t\txpos = 0\n\t\txGC = 105\n\t\txm = -0\n\t\tself.hideGrouped = hideGrouped\n\t\tself.direction = direction\n\t\tself.groupPrefix = groupPrefix\n\t\tdropSettings = dict(callback = self.groupsDropCallback)\n\t\tself.hashKernDic = TDHashKernDic(font)\n\n\t\tself.fontView = GlyphCollectionView((xpos, yw, tx, ty),\n\t\t showModePlacard = False,\n\t\t cellRepresentationName = \"doodle.GlyphCell\",\n\t\t # initialMode = \"cell\",\n\t\t listColumnDescriptions = None,\n\t\t listShowColumnTitles = False,\n\t\t showPlacard = False,\n\t\t placardActionItems = None,\n\t\t allowDrag = True,\n\t\t selfWindowDropSettings = dropSettings,\n\t\t selfApplicationDropSettings = dropSettings,\n\t\t selfDropSettings = dropSettings,\n\t\t otherApplicationDropSettings = dropSettings,\n\t\t doubleClickCallback = self.doubleClickCallback\n\t\t )\n\t\tself.fontView.id = 'fontview'\n\n\t\tself.fontView.setCellRepresentationArguments(drawHeader = True, drawMetrics = True) # , drawMetrics = True\n\t\t# self.fontView.getNSScrollView().setHasVerticalScroller_(True)\n\t\t# self.fontView.getNSScrollView().setHasHorizontalScroller_(False)\n\t\t#\n\t\t# self.fontView.getNSScrollView().setAutohidesScrollers_(False)\n\t\t# self.fontView.getNSScrollView().setBackgroundColor_(NSColor.whiteColor())\n\t\t# self.fontView.getNSScrollView().setBorderType_(NSNoBorder)\n\t\t# addObserver(self.fontView, \"draw\", \"glyphCellDraw\")\n\t\tself.fontView.setCellSize((70,70))\n\t\tself.setFontView()\n\n\n\tdef doubleClickCallback(self, sender):\n\t\tw = OpenSpaceCenter(CurrentFont())\n\t\tw.set(self.getSelectedGlyphs())\n\n\n\tdef groupsDropCallback (self, sender, dropInfo):\n\t\tif dropInfo['isProposal']: pass\n\t\telse:\n\t\t\tdest = sender.id\n\t\t\tsource = dropInfo['source']\n\t\t\ttry:\n\t\t\t\tsourceid = source.id\n\t\t\texcept:\n\t\t\t\tprint (source)\n\t\t\t\tsourceid = None\n\t\t\tglist = []\n\t\t\tfor glyph in dropInfo['data']:\n\t\t\t\tglist.append(glyph.name) # = dropInfo['data']\n\n\t\t\tupdateGroups = False\n\t\t\tgroupName = None\n\t\t\tif sourceid != dest:\n\t\t\t\t# if sourceid == 'fontview' and dest != 'fontview':\n\t\t\t\t# \taddGlyphsToGroup(self._font, dest, glist)\n\t\t\t\t# \tprint 'fontview F G', dest, sourceid\n\t\t\t\t#\n\t\t\t\t# \tgroupName = dest\n\t\t\t\t# \tupdateGroups = True\n\n\t\t\t\tif sourceid != 'fontview' and dest == 'fontview':\n\t\t\t\t\t# WORKS ONLY ONE\n\t\t\t\t\tdelGlyphsFromGroup(self._font, sourceid, glist)\n\t\t\t\t\t# print 'fontview G F', dest, sourceid\n\t\t\t\t\tgroupName = sourceid\n\t\t\t\t\tupdateGroups = True\n\t\t\t\t#\n\t\t\t\t# elif sourceid != 'fontview' and dest != 'fontview':\n\t\t\t\t# \tdelGlyphsFromGroup(self._font, sourceid, glist)\n\t\t\t\t# \taddGlyphsToGroup(self._font, dest, glist)\n\t\t\t\t# \tprint 'fontview G G', dest, sourceid\n\t\t\t\t# \tgroupName = dest\n\t\t\t\t# \tupdateGroups = True\n\n\t\t\tif updateGroups and self.groupsChangedCallback:\n\t\t\t\tself.groupsChangedCallback(groupName)\n\t\treturn True\n\n\n\tdef isGlyphNotInGroups(self, glyphname):\n\t\tfor group, content in self._font.groups.items():\n\t\t\tif group.startswith(self.groupPrefix):\n\t\t\t\tif self.direction == 'L' and ID_GROUP_DIRECTION_POSITION_LEFT in group:\n\t\t\t\t\tif glyphname in content:\n\t\t\t\t\t\treturn False\n\t\t\t\tif self.direction == 'R' and ID_GROUP_DIRECTION_POSITION_RIGHT in group:\n\t\t\t\t\tif glyphname in content:\n\t\t\t\t\t\treturn False\n\t\treturn True\n\n\n\tdef setFontView(self):\n\t\tglyphs = []\n\t\tfor glyphname in self._font.glyphOrder:\n\t\t\tif self.hideGrouped:\n\t\t\t\tif self.isGlyphNotInGroups(glyphname):\n\t\t\t\t\tglyphs.append(self._font[glyphname])\n\t\t\telse:\n\t\t\t\tglyphs.append(self._font[glyphname])\n\t\tself.fontView.set(glyphs)\n\n\tdef getSelectedGlyphs(self):\n\t\tglist = []\n\t\tfor gindex in self.fontView.getSelection():\n\t\t\tglist.append(self.fontView[gindex].name)\n\t\treturn glist\n\n\tdef clear(self):\n\t\tself.fontView.set([])\n\n\nif __name__ == \"__main__\":\n\tclass MyW(object):\n\t\tdef __init__ (self):\n\n\t\t\tself.w = Window((995, 600), \"KernGroups\", minSize = (995, 400), maxSize = (995,2500))\n\t\t\tself.groupPrefix = ID_KERNING_GROUP\n\t\t\tself.direction = 'L'\n\t\t\tself.font = CurrentFont()\n\t\t\tself.w.cbGroupsList = PopUpButton((-240, 5, -5, 21), {}, callback = self.cbGroupsListCallback, sizeStyle = 'regular')\n\n\t\t\tself.w.fontView = TDFontView((5,15,580,-50),\n\t\t\t font = self.font,\n\t\t\t groupsChangedCallback = self.groupsChanged,\n\t\t\t groupPrefix = self.groupPrefix)\n\t\t\tself.w.groupsView = TDGroupsCollectionView((590, 0, 405, -0),\n\t\t\t font = CurrentFont(),\n\t\t\t direction = self.direction,\n\t\t\t groupsChangedCallback = self.hideGroupedCallback,\n\t\t\t groupPrefix = self.groupPrefix,\n\t\t\t selectionCallback = self.selectionGroup\n\t\t\t )\n\t\t\tsegments = [{'width': 54, 'title': 'Left'}, {'width': 54, 'title': 'Right'}]\n\t\t\tself.w.btnSwitchLeftRight = SegmentedButton((590, 3, 120, 23),\n\t\t\t segmentDescriptions = segments,\n\t\t\t selectionStyle = 'one', # sizeStyle = 'mini', #48\n\t\t\t callback = self.btnSwitchLeftRightCallback,\n\t\t\t sizeStyle = 'regular')\n\t\t\t# self.modeLeftRight = 0\n\t\t\tself.w.btnSwitchLeftRight.set(0)\n\n\t\t\typos = -90\n\t\t\tself.w.btnMakeGroup = Button((10, ypos, 150, 21),title = 'Make Group', callback = self.makeGroup)\n\t\t\tself.w.btnMakeGroups = Button((10, ypos + 25, 150, 21),title = 'Make Groups', callback = self.makeGroups)\n\n\t\t\t# self.w.btnFixMarginsGlobal = Button((420, ypos, 150, 21), title = 'Fix Margins', callback = self.fixMarginsGlobal)\n\t\t\t# ypos += 25\n\t\t\tself.w.btnDeleteGroup = Button((420, ypos , 150, 21), title = 'Delete Group', callback = self.deleteGroup)\n\n\t\t\tself.w.btnRefresh = Button((420, ypos + 25, 150, 21), title = 'Refresh', callback = self.refreshCallback)\n\t\t\tself.w.chbHideGrouped = CheckBox((10,-30, 150, 21),\n\t\t\t title = 'Hide grouped',\n\t\t\t value = True, callback = self.hideGroupedCallback)\n\t\t\tself.w.cbGroupsList.setItems(self.w.groupsView.groupsList)\n\t\t\tself.w.bind('close', self.windowCloseCallback)\n\t\t\tself.w.open()\n\n\t\tdef windowCloseCallback(self, sender):\n\t\t\tself.w.groupsView.clear()\n\t\t\tself.w.fontView.clear()\n\n\t\tdef hideGroupedCallback(self, sender):\n\n\t\t\tself.w.fontView.direction = self.direction\n\t\t\tself.w.fontView.hideGrouped = self.w.chbHideGrouped.get()\n\t\t\tself.w.fontView.groupPrefix = self.groupPrefix\n\t\t\tself.w.fontView.setFontView()\n\n\t\tdef selectionGroup(self, info):\n\t\t\tif info:\n\t\t\t\tself.w.cbGroupsList.setItem(getDisplayNameGroup(info))\n\n\n\t\tdef directionChangedCallback(self, sender):\n\t\t\tself.hideGroupedCallback(self.w.chbHideGrouped)\n\n\n\t\tdef cbGroupsListCallback(self, sender):\n\t\t\tgroupname = getGroupNameFromDisplayName(sender.getItems()[sender.get()],direction = self.direction)\n\t\t\tself.w.groupsView.scrollToGroup(groupname)\n\t\t\tself.w.groupsView.selectedGroup(groupname)\n\t\t\t# self.w.cbGroupsList.setItem(sender.getItems()[sender.get()])\n\n\n\t\tdef btnSwitchLeftRightCallback(self, sender):\n\t\t\tif sender.get() == 0:\n\t\t\t\tself.direction = 'L'\n\t\t\telif sender.get() == 1:\n\t\t\t\tself.direction = 'R'\n\n\t\t\tself.hideGroupedCallback(self.w.chbHideGrouped)\n\t\t\tself.w.groupsView.clear()\n\t\t\tself.w.groupsView.buildView(self.direction)\n\t\t\tself.w.cbGroupsList.setItems(self.w.groupsView.groupsList)\n\n\n\t\tdef createGroup(self, font, glist):\n\t\t\tif len(glist) != 0:\n\t\t\t\tkeyGlyph = glist[0]\n\t\t\t\tmask1 = ID_KERNING_GROUP.replace('.kern', '') + ID_GROUP_DIRECTION_POSITION_LEFT\n\t\t\t\tmask2 = ID_KERNING_GROUP.replace('.kern', '') + ID_GROUP_DIRECTION_POSITION_RIGHT\n\t\t\t\tif self.direction == 'L':\n\t\t\t\t\tgroupname = '%s%s' % (mask1, keyGlyph)\n\t\t\t\telif self.direction == 'R':\n\t\t\t\t\tgroupname = '%s%s' % (mask2, keyGlyph)\n\t\t\t\telse: return\n\t\t\t\t# groupname = '%s_%s_%s' % (self.groupPrefix, self.direction, keyGlyph)\n\t\t\t\t# if not font.groups.has_key(groupname):\n\t\t\t\t# \tfont.groups[groupname] = []\n\t\t\t\t# \tfor gname in glist:\n\t\t\t\t# \t\tfont.groups[groupname].append(gname)\n\t\t\t\taddGlyphsToGroup(self.font,groupname,glist)\n\t\t\t\tself.refresh(groupname)\n\t\t\t\tself.w.groupsView.scrollToGroup(groupname)\n\t\t\t\tself.w.groupsView.selectedGroup(groupname)\n\n\n\t\tdef createGroupsByList(self, font, glist):\n\t\t\tfor glyphname in glist:\n\t\t\t\tself.createGroup(font, [glyphname])\n\n\n\t\tdef refreshCallback(self, sender):\n\t\t\tself.w.groupsView.clear()\n\t\t\tself.w.groupsView.buildView(self.direction)\n\t\t\tself.hideGroupedCallback(self.w.chbHideGrouped)\n\t\t\tself.w.cbGroupsList.setItems(self.w.groupsView.groupsList)\n\n\t\tdef groupsChanged(self, groupname):\n\t\t\tself.w.groupsView.groupPrefix = self.groupPrefix\n\t\t\tself.w.groupsView.currentGroupName = groupname\n\t\t\tself.w.groupsView.updateGroupView(groupname)\n\t\t\tself.hideGroupedCallback(self.w.chbHideGrouped)\n\n\n\t\tdef refresh(self, sender):\n\t\t\tself.w.groupsView.groupPrefix = self.groupPrefix\n\t\t\tself.w.groupsView.currentGroupName = sender\n\t\t\tself.w.groupsView.refresh()\n\t\t\tself.hideGroupedCallback(self.w.chbHideGrouped)\n\t\t\tself.w.cbGroupsList.setItems(self.w.groupsView.groupsList)\n\n\n\t\tdef makeGroup(self, sender):\n\t\t\tglist = self.w.fontView.getSelectedGlyphs()\n\t\t\tself.createGroup(self.font, glist)\n\n\n\t\tdef makeGroups(self, sender):\n\t\t\tglist = self.w.fontView.getSelectedGlyphs()\n\t\t\tself.createGroupsByList(self.font, glist)\n\n\t\tdef deleteGroup(self, sender):\n\t\t\tself.w.groupsView.deleteGroupViewByName(self.w.groupsView.currentGroupName)\n\t\t\tself.w.cbGroupsList.setItems(self.w.groupsView.groupsList)\n\t\t\tself.w.cbGroupsList.setItem(getDisplayNameGroup(self.w.groupsView.currentGroupName))\n\n\t# fix layer color for GlyphCollectionView\n\t# CurrentFont().getLayer('foreground').color = (0, 0, 0, 1)\n\n\tMyW()\n","repo_name":"typedev/KernTool3","sub_path":"source/KernGroups.py","file_name":"KernGroups.py","file_ext":"py","file_size_in_byte":23439,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"}
+{"seq_id":"9190756818","text":"import typing\nimport argparse\nimport collections\nimport sys\nimport platform\nimport requests\nimport consts\nfrom config import configure, load_conf, validate_command, conf_get, get_yaneuraou_command, get_fairy_command, get_engine_dir, get_key, validate_cores, validate_memory, validate_threads, get_endpoint\nimport util\nimport errors\nfrom worker import Worker\nfrom progressReporter import ProgressReporter\nimport signals\nfrom logger import log\nfrom systemd import systemd\nfrom intro import intro\nfrom cpuid import cpuid\n\n\ndef cmd_run(args: typing.Any) -> int:\n conf = load_conf(args)\n\n yane_command = validate_command(\n conf_get(conf, \"YaneuraOuCommand\"), conf)\n if not yane_command:\n yane_command = get_yaneuraou_command(conf)\n\n fairy_command = validate_command(\n conf_get(conf, \"FairyCommand\"), conf)\n if not fairy_command:\n fairy_command = get_fairy_command(conf)\n\n print()\n print(\"### Checking configuration ...\")\n print()\n print(\"Python: %s (with requests %s)\" %\n (platform.python_version(), requests.__version__))\n print(\"EngineDir: %s\" % get_engine_dir(conf))\n print(\"YaneuraOuCommand: %s\" % yane_command)\n print(\"FairyCommand: %s\" % fairy_command)\n print(\"Key: %s\" % ((\"*\" * len(get_key(conf))) or \"(none)\"))\n\n cores = validate_cores(conf_get(conf, \"Cores\"))\n print(\"Cores: %d\" % cores)\n\n threads = validate_threads(conf_get(conf, \"Threads\"), conf)\n instances = max(1, cores // threads)\n print(\"Engine processes: %d (each ~%d threads)\" % (instances, threads))\n memory = validate_memory(conf_get(conf, \"Memory\"), conf)\n print(\"Memory: %d MB\" % memory)\n endpoint = get_endpoint(conf)\n warning = \"\" if endpoint.startswith(\n \"https://\") else \" (WARNING: not using https)\"\n print(\"Endpoint: %s%s\" % (endpoint, warning))\n print(\"FixedBackoff: %s\" %\n util.parse_bool(conf_get(conf, \"FixedBackoff\")))\n print()\n\n if conf.has_section(\"Stockfish\") and conf.items(\"Stockfish\"):\n print(\"Using custom USI options is discouraged:\")\n for name, value in conf.items(\"Stockfish\"):\n if name.lower() == \"hash\":\n hint = \" (use --memory instead)\"\n elif name.lower() == \"threads\":\n hint = \" (use --threads-per-process instead)\"\n else:\n hint = \"\"\n print(\" * %s = %s%s\" % (name, value, hint))\n print()\n\n print(\"### Starting workers ...\")\n print()\n\n buckets = [0] * instances\n for i in range(0, cores):\n buckets[i % instances] += 1\n\n progress_reporter = ProgressReporter(len(buckets) + 4, conf)\n progress_reporter.daemon = True\n progress_reporter.start()\n\n workers = [Worker(conf, bucket, memory // instances,\n progress_reporter) for bucket in buckets]\n\n # Start all threads\n for i, worker in enumerate(workers):\n worker.set_name(\"><> %d\" % (i + 1))\n worker.daemon = True\n worker.start()\n\n # Wait while the workers are running\n try:\n # Let SIGTERM and SIGINT gracefully terminate the program\n handler = signals.SignalHandler()\n\n try:\n while True:\n # Check worker status\n for _ in range(int(max(1, consts.STAT_INTERVAL / len(workers)))):\n for worker in workers:\n worker.finished.wait(1.0)\n if worker.fatal_error:\n raise worker.fatal_error\n\n # Log stats\n log.info(\"[shoginet v%s] Analyzed %d positions, crunched %d million nodes\",\n consts.SN_VERSION,\n sum(worker.positions for worker in workers),\n int(sum(worker.nodes for worker in workers) / 1000 / 1000))\n\n except errors.ShutdownSoon:\n handler = signals.SignalHandler()\n\n if any(worker.job for worker in workers):\n log.info(\n \"\\n\\n### Stopping soon. Press ^C again to abort pending jobs ...\\n\")\n\n for worker in workers:\n worker.stop_soon()\n\n for worker in workers:\n while not worker.finished.wait(0.5):\n pass\n except (errors.Shutdown, errors.ShutdownSoon):\n if any(worker.job for worker in workers):\n log.info(\"\\n\\n### Good bye! Aborting pending jobs ...\\n\")\n else:\n log.info(\"\\n\\n### Good bye!\")\n finally:\n handler.ignore = True\n\n # Stop workers\n for worker in workers:\n worker.stop()\n\n progress_reporter.stop()\n\n # Wait\n for worker in workers:\n worker.finished.wait()\n\n return 0\n\n\ndef cmd_configure(args: typing.Any) -> int:\n configure(args)\n return 0\n\n\ndef cmd_systemd(args: typing.Any) -> int:\n systemd(args)\n return 0\n\n\ndef cmd_cpuid(argv: typing.Any) -> int:\n cpuid()\n return 0\n\n\ndef main(argv: typing.Any) -> int:\n # Parse command line arguments\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument(\"--verbose\", \"-v\", default=0,\n action=\"count\", help=\"increase verbosity\")\n parser.add_argument(\"--version\", action=\"version\",\n version=\"shoginet v{0}\".format(consts.SN_VERSION))\n\n g = parser.add_argument_group(\"configuration\")\n g.add_argument(\"--auto-update\", action=\"store_true\",\n help=\"automatically install available updates\")\n g.add_argument(\"--conf\", help=\"configuration file\")\n g.add_argument(\"--no-conf\", action=\"store_true\",\n help=\"do not use a configuration file\")\n g.add_argument(\"--key\", \"--apikey\", \"-k\", help=\"shoginet api key\")\n\n g = parser.add_argument_group(\"resources\")\n g.add_argument(\n \"--cores\", help=\"number of cores to use for engine processes (or auto for n - 1, or all for n)\")\n g.add_argument(\n \"--memory\", help=\"total memory (MB) to use for engine hashtables\")\n\n g = parser.add_argument_group(\"advanced\")\n g.add_argument(\n \"--endpoint\", help=\"lishogi https endpoint (default: %s)\" % consts.DEFAULT_ENDPOINT)\n g.add_argument(\"--engine-dir\", help=\"engine working directory\")\n g.add_argument(\"--yaneuraou-command\",\n help=\"YaneuraOu command (default: YaneuraOu-by-gcc)\")\n g.add_argument(\"--fairy-command\",\n help=\"Fairy stockfish command (default: fairy-stockfish-largeboard_x86-64)\")\n g.add_argument(\"--threads-per-process\", \"--threads\", type=int, dest=\"threads\",\n help=\"hint for the number of threads to use per engine process (default: %d)\" % consts.DEFAULT_THREADS)\n g.add_argument(\"--fixed-backoff\", action=\"store_true\", default=None,\n help=\"fixed backoff (only recommended for move servers)\")\n g.add_argument(\"--no-fixed-backoff\", dest=\"fixed_backoff\",\n action=\"store_false\", default=None)\n g.add_argument(\"--setoptionYaneuraou\", nargs=2, action=\"append\", default=[],\n metavar=(\"NAME\", \"VALUE\"), help=\"set a custom usi option for YaneuraOu\")\n g.add_argument(\"--setoptionFairy\", nargs=2, action=\"append\", default=[],\n metavar=(\"NAME\", \"VALUE\"), help=\"set a custom usi option for Fairy Stockfish\")\n\n commands = collections.OrderedDict([\n (\"run\", cmd_run),\n (\"configure\", cmd_configure),\n (\"systemd\", cmd_systemd),\n (\"cpuid\", cmd_cpuid),\n ])\n\n parser.add_argument(\"command\", default=\"run\",\n nargs=\"?\", choices=commands.keys())\n\n args = parser.parse_args(argv[1:])\n\n # Show intro\n if args.command not in [\"systemd\"]:\n print(intro())\n sys.stdout.flush()\n\n # Run\n try:\n sys.exit(commands[args.command](args))\n except errors.ConfigError:\n log.exception(\"Configuration error\")\n return 78\n except (KeyboardInterrupt, errors.Shutdown, errors.ShutdownSoon):\n return 0\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","repo_name":"WandererXII/shoginet","sub_path":"shoginet.py","file_name":"shoginet.py","file_ext":"py","file_size_in_byte":8119,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"32"}
+{"seq_id":"72248749850","text":"import configparser\n\nimport spotipy\nfrom spotipy.oauth2 import SpotifyOAuth\n\nconfig = configparser.ConfigParser()\nconfig.read('config.cfg')\nclient_id=\"2d0aa7b1e8e34e6db2bbcc9e35fd4db5\"\nclient_secret=\"264330e29b1143f28800cc39b0ab8007\"\nscope = \"user-read-playback-state,user-modify-playback-state,streaming\"\n\nauth = SpotifyOAuth(\n client_id=\"2d0aa7b1e8e34e6db2bbcc9e35fd4db5\",\n client_secret=\"264330e29b1143f28800cc39b0ab8007\",\n redirect_uri=\"http://google.com/\",\n scope=scope)\n\ntoken = auth.get_access_token(as_dict=False)\nspotify = spotipy.Spotify(auth=token)\n\ndevices = spotify.devices()\ndevice_id = devices['devices'][0]['id']\n\nsearch_result = spotify.search(input('Track: '))['tracks']['items'][0]\ntrack = search_result['uri']\nartist = search_result['artists'][0]['uri']\n# print(track)\n# print(artist)\nprint(search_result)\n# recommendation = spotify.recommendations(seed_artists=artist, seed_tracks=track)\n# print(recommendation)\n\nspotify.start_playback(uris=[track], device_id=device_id)","repo_name":"Adog64/LotusTimer","sub_path":"testing/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"70185352413","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\n\n#class TutorialPipeline(object):\n# def process_item(self, item, spider):\n# return item\n\nfrom w3lib.html import remove_tags\nimport re\nimport string\n\ndef clense(text, space_replacer = ' ', to_lower = True, remove_punc = True):\n # remove HTML comments first as suggested in https://stackoverflow.com/questions/28208186/how-to-remove-html-comments-using-regex-in-python\n text = re.sub(\"()\", \"\", text, flags=re.DOTALL)\n text = remove_tags(text)\n text = re.sub(r'[^\\x00-\\x7F]+',' ', text) #remove non-ascii characters\n text = text.replace(\"&\", \"and\")\n text = text.replace(\"&\", \"and\")\n text.strip()\n text.rstrip()\n text = text.replace(\"\\r\\n\", \"\")\n if to_lower:\n text = text.lower()\n\n if remove_punc:\n # from https://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string-in-python\n text = re.sub(r'[^\\w\\s]', '', text) #remove punctuation marks and non-word\n text = text.replace(\",\", \"\")\n\n text = re.sub(' +', space_replacer, text)\n text = text.replace(\"\\\"\", \"\")\n #if all(ord(char) < 128 for char in text) == False:\n # text = ''\n ''.join(i for i in text if ord(i)<128)\n return text\n\nclass BHRRCPipeline(object):\n\n def process_item(self, item, spider):\n i = 0\n new_content = ''\n new_summary = ''\n for content in item['content']:\n content = clense(content,to_lower=False,remove_punc=False)\n if i==0:\n new_summary = content.strip()\n if i>0:\n new_content = new_content + \" \" + content\n i = i+1\n item['content'] = new_content.strip()\n item['summary'] = new_summary.strip()\n\n new_title = ''\n for title in item['title']:\n new_title = new_title + clense(title,to_lower=False,remove_punc=False)\n item['title'] = new_title.strip()\n\n new_author = ''\n for author in item['author']:\n new_author = new_author + clense(author,to_lower=False,remove_punc=False)\n\n new_author = new_author[8:]\n new_author = new_author[:-17]\n item['author'] = new_author.strip()\n\n return item\n","repo_name":"ashitpatel/cs341","sub_path":"scrapy_program/tutorial/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"7563417286","text":"\nfrom kivy.uix.screenmanager import Screen\nfrom Classes.database import Database\nfrom kivy.metrics import dp\nfrom kivymd.uix.datatables import MDDataTable\n\nclass StoreScreen(Screen):\n def __init__(self, **kwargs):\n super(StoreScreen, self).__init__(**kwargs)\n self.dialog = None\n\n self.db = Database()\n\n self.create_datatable()\n self.reload_data_table()\n \n\n #Dodawanie danych\n def insert_data(self):\n description = self.ids['item_name'].text\n price = self.ids['price_field'].text\n date = self.ids['date_field'].text\n category = self.ids['item_category_label'].text\n\n self.db.create_entry(description, price , date , category)\n self.reload_data_table()\n\n self.clear_text()\n\n\n #Utworzenie tabeli\n def create_datatable(self):\n self.data_table= MDDataTable(\n size_hint=(1, 1),\n elevation= 2,\n use_pagination=True,\n check=True, \n column_data=[\n (\"Id\", dp(20)), \n (\"Nazwa produktu\", dp(45)), \n (\"Cena (zł)\", dp(25)), \n (\"Data dostawy\", dp(25)), \n (\"Rodzaj produktu\", dp(50)),\n ],\n row_data = [],\n\n )\n self.data_table.bind(on_check_press=self.on_check_press)\n self.ids['table'].add_widget(self.data_table)\n\n #Odświeżenie tabeli\n def reload_data_table(self):\n self.remove_datatable()\n data = self.db.get_product()\n if data is not None:\n self.create_datatable()\n self.data_table.row_data = data\n else:\n\n self.create_datatable()\n self.data_table.row_data = []\n\n\n #Usunięcie tabeli\n def remove_datatable(self):\n self.ids[\"table\"].remove_widget(self.data_table)\n \n #Czyszczenie pól tekstowych\n def clear_text(self):\n self.ids[\"item_name\"].text = ''\n self.ids[\"price_field\"].text = ''\n self.ids[\"date_field\"].text = ''\n self.ids[\"item_category_label\"].text = 'Brak kategorii'\n self.ids[\"search\"].text = ''\n\n #Aktualizacja przedmiotu\n def update(self):\n checked_rows = self.data_table.get_row_checks()\n if not checked_rows:\n print(\"Nie wybrałeś żadnego produktu.\")\n return\n id = checked_rows[0][0]\n \n description = self.ids['item_name'].text\n price = self.ids['price_field'].text\n date = self.ids['date_field'].text\n category = self.ids['item_category_label'].text\n\n self.db.update_product(id, description, price, date, category)\n self.reload_data_table()\n self.clear_text()\n\n #Usunięcie przedmiotu\n def delete(self):\n rows = [i[0] for i in self.data_table.get_row_checks()]\n if rows != []:\n for id in rows:\n self.db.delete_product(id)\n self.reload_data_table()\n self.clear_text()\n else:\n print(\"Nie wybrano produktu\")\n\n #Zaznaczenie wiersza\n def on_check_press(self, instance_table, current_row):\n self.ids[\"item_name\"].text = current_row[1]\n self.ids[\"price_field\"].text = current_row[2]\n self.ids[\"date_field\"].text = current_row[3]\n self.ids[\"item_category_label\"].text = current_row[4]\n print(current_row[0])\n\n\n def cancel(self):\n self.reload_data_table()\n self.clear_text()\n \n #Wyszukiwanie produktów\n def search(self):\n id_check = self.ids['id_check']\n item_check = self.ids['item_check']\n\n if id_check.active and not item_check.active:\n try:\n self.data_table.row_data = self.db.search_by_id(int(self.ids['search'].text))\n except:\n pass\n elif not id_check.active and item_check.active:\n self.data_table.row_data = self.db.search_by_name(str(self.ids['search'].text))\n else:\n print(\"wybierz jedno pole\")\n\n","repo_name":"bindasp/StoreApp","sub_path":"Classes/Store.py","file_name":"Store.py","file_ext":"py","file_size_in_byte":3995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"27230631279","text":"__author__ = 'zehaeva'\n\ntest_cases = ['5;0,1,2,3,0', '20;0,1,10,3,2,4,5,7,6,8,11,9,15,12,13,4,16,18,17,14']\n\nfor test in test_cases:\n my_test = test.strip().split(';')\n my_n = my_test[0]\n my_list = my_test[1].split(',')\n my_list.sort()\n last_seen = my_list[0]\n for i in range(1, len(my_list)):\n if my_list[i] == last_seen:\n break\n else:\n last_seen = my_list[i]\n print(last_seen)","repo_name":"zehaeva/codeeval","sub_path":"ArrayAbsurdity.py","file_name":"ArrayAbsurdity.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"41122302379","text":"# SPDX-License-Identifier: Apache-2.0\n\n# https://click.palletsprojects.com/en/7.x/setuptools/\n\nfrom setuptools import setup, find_packages\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetup(\n name='wataash_utils',\n version='0.5.0',\n url='https://github.com/wataash/wataash_utils_py',\n author='Wataru Ashihara',\n author_email='wataash@wataash.com',\n classifiers=[\n 'License :: OSI Approved :: Apache Software License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9',\n ],\n license='Apache-2.0',\n description='wataash\\'s personal utilities',\n long_description=long_description,\n keywords='wataash_utils',\n install_requires=[\n 'click>=8.0.1',\n 'logzero>=1.6.3',\n # 'selenium>=4.1.0',\n 'wcwidth>=0.2.5',\n ],\n packages=find_packages(),\n)\n","repo_name":"wataash/wataash_utils_py","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"14722402969","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass MatrixFactorization(torch.nn.Module):\n def __init__(self, num_users, num_movies, n_factors=20):\n super().__init__()\n # create user embeddings\n self.user_emb = torch.nn.Embedding(num_users, n_factors)\n # create item embeddings\n self.movie_emb = torch.nn.Embedding(num_movies, n_factors)\n\n def forward(self, x):\n user = x[0]\n movie = x[1]\n # matrix multiplication\n return (self.user_emb(user)*self.movie_emb(movie)).sum(1)\n\n \nclass DenseNet(nn.Module):\n def __init__(self, num_users, num_movies, H1=64, n_factors=20, embedding_dropout=0.02, dropouts=0.5):\n super().__init__()\n # user and item embedding layers\n self.user_emb = torch.nn.Embedding(num_users, n_factors)\n self.movie_emb = torch.nn.Embedding(num_movies, n_factors)\n self.emb_drop = nn.Dropout(embedding_dropout)\n self.drop1 = nn.Dropout(dropouts)\n #self.drop2 = nn.Dropout(dropouts)\n # linear layers\n self.linear1 = torch.nn.Linear(n_factors*2, H1)\n #self.linear2 = torch.nn.Linear(H1, H1)\n self.linear_out = torch.nn.Linear(H1, 1)\n\n def forward(self, x):\n users = x[0]\n movies = x[1]\n users_embedding = self.user_emb(users)\n movies_embedding = self.movie_emb(movies) \n # concatenate user and item embeddings to form input\n x = torch.cat([users_embedding, movies_embedding], dim=1) \n x = self.emb_drop(x)\n h1_relu = self.drop1(F.relu(self.linear1(x)))\n #h2_relu = self.drop2(F.relu(self.linear2(h1_relu)))\n output_scores = self.linear_out(h1_relu).squeeze(-1) \n return output_scores\n","repo_name":"leonardoaraujosantos/RecommenderSystem","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"15422203778","text":"\nimport yaml\nfrom M3uParse import M3uParse\n\nclass ExtractGroups:\n\n def __init__(self, fileName,groups=\"groups.yaml\"):\n self.m3uParse = M3uParse(fileName)\n self.groups = groups\n self.exportToYaml()\n\n def deleteUrl(self,channel):\n _channel= dict(channel)\n del _channel['url']\n return _channel\n\n def exportToYaml(self):\n with open(self.groups, 'w') as file:\n mapChannels = map(self.deleteUrl, self.m3uParse.channelsInfo)\n documents= yaml.dump(list(mapChannels),file)\n\n","repo_name":"redhaam/SMART-IPTV-m3u-playlist-editor","sub_path":"extractGroups.py","file_name":"extractGroups.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"}
+{"seq_id":"33041682263","text":"import unittest\nimport mock\nimport tempfile\nfrom rdflib import URIRef, Graph\nfrom rdfdb.graphfile import GraphFile\n\n\nclass TestGraphFileOutput(unittest.TestCase):\n\n def testMaintainsN3PrefixesFromInput(self):\n tf = tempfile.NamedTemporaryFile(suffix='_test.n3')\n tf.write(b'''\n @prefix : .\n @prefix n: .\n :foo n:bar :baz .\n ''')\n tf.flush()\n\n def getSubgraph(uri):\n return Graph()\n\n gf = GraphFile(mock.Mock(), tf.name.encode('ascii'), URIRef('uri'),\n mock.Mock(), getSubgraph, {}, {})\n gf.reread()\n\n newGraph = Graph()\n newGraph.add((URIRef('http://example.com/boo'),\n URIRef('http://example.com/n/two'),\n URIRef('http://example.com/other/ns')))\n gf.dirty(newGraph)\n gf.flush()\n wroteContent = open(tf.name, 'rb').read()\n self.assertEqual(\n b'''@prefix : .\n@prefix n: .\n@prefix rdf: .\n@prefix rdfs: .\n@prefix xml: .\n@prefix xsd: .\n\n:boo n:two .\n''', wroteContent)\n","repo_name":"drewp/rdfdb","sub_path":"rdfdb/graphfile_test.py","file_name":"graphfile_test.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"43040030277","text":"from rich import print\n\ncal = open('input.txt', 'r', encoding='utf-8').read().strip()\n\nvDir = [x for x in cal]\n\nvRocks = [['@@@@'], [' @', '@@@', ' @'], [\n ' @', ' @', '@@@'], ['@', '@', '@', '@'], ['@@', '@@']]\n\nArena = ['#' * 7]\nnRock = 0\nnDir = 0\nnTop = 0\n\n\ndef MostraArena():\n global Arena\n for lin in Arena[::-1]:\n print('|' + lin[::-1] + '|')\n print()\n\n\ndef AddArena(Rock):\n global Arena\n for lin in Rock[::-1]:\n Arena.append(lin[::-1])\n\n\ndef Ajusta(xRock):\n vRet = []\n for x in xRock:\n vRet.append((' ' * 2 + x + ' ' * 7)[0:7])\n return vRet\n\n\ndef Troca(Rock):\n global Arena\n global nTop\n for z in range(len(Rock)):\n Arena[-(z + nTop)] = Arena[-(z + nTop)].replace('@', '#')\n\n\ndef PodeDescer(Rock):\n global Arena\n global nTop\n for z in range(len(Rock)):\n for k in range(7):\n if Arena[-(z + nTop)][k] == '@':\n if Arena[-(z + nTop + 1)][k] == '#':\n Troca(Rock)\n return False\n\n for z in range(len(Rock) - 1, -1, -1):\n for k in range(7):\n if Arena[-(z + nTop)][k] == '@':\n Arena[-(z + nTop + 1)] = Arena[-(z + nTop + 1)][0:k] + \\\n '@' + Arena[-(z + nTop + 1)][k + 1:]\n Arena[-(z + nTop)] = Arena[-(z + nTop)][0:k] + \\\n ' ' + Arena[-(z + nTop)][k + 1:]\n if Arena[-1].strip() == '':\n Arena.pop()\n else:\n nTop += 1\n\n return True\n\n\nnCut = 100\n\n\ndef Lasts():\n global Arena\n s = ''\n for x in range(1, 31):\n s += Arena[-x]\n if x == len(Arena):\n break\n return s\n\n\ndef JaExiste():\n global Arena\n if len(Arena) < 100:\n return False\n\n for x in range(1, 31):\n if Arena[x] != Arena[len(Arena) - 31 + x]:\n return False\n return True\n\n\ndef Teste(nMax):\n global Arena, nRock, nDir, nTop\n Arena = ['#' * 7]\n\n vSave = []\n vPos = []\n\n nRock = 0\n nDir = 0\n nArenaCut = 0\n x = 0\n while x < nMax:\n Rock = Ajusta(vRocks[nRock])\n\n for y in range(4):\n bMove = True\n if vDir[nDir] == '>':\n for z in Rock:\n if z[-1] != ' ':\n bMove = False\n break\n if bMove:\n for z in range(len(Rock)):\n Rock[z] = ' ' + Rock[z][0:-1]\n else:\n for z in Rock:\n if z[0] != ' ':\n bMove = False\n break\n if bMove:\n for z in range(len(Rock)):\n Rock[z] = Rock[z][1:] + ' '\n\n nDir = (nDir+1) % len(vDir)\n\n nTop = 1\n AddArena(Rock)\n\n while True:\n if PodeDescer(Rock):\n bMove = True\n # Atention: The Move is inverted, because the array is inverted\n if vDir[nDir] == '<':\n for z in range(len(Rock)):\n sLin = Arena[-(z + nTop)] + '#'\n for k in range(7):\n if sLin[k] == '@':\n if sLin[k + 1] == '#':\n bMove = False\n break\n if bMove:\n for z in range(len(Rock)):\n sLin = Arena[-(z + nTop)]\n for k in range(6, -1, -1):\n if sLin[k] == '@':\n sLin = sLin[0:k] + ' @' + sLin[k+2:]\n Arena[-(z + nTop)] = sLin\n else:\n for z in range(len(Rock)):\n sLin = '#' + Arena[-(z + nTop)]\n for k in range(1, 8):\n if sLin[k] == '@':\n if sLin[k - 1] == '#':\n bMove = False\n break\n if bMove:\n for z in range(len(Rock)):\n sLin = Arena[-(z + nTop)]\n for k in range(7):\n if sLin[k] == '@':\n sLin = sLin[0:k - 1] + '@ ' + sLin[k+1:]\n Arena[-(z + nTop)] = sLin\n nDir = (nDir+1) % len(vDir)\n else:\n break\n\n # MostraArena()\n\n nRock = (nRock+1) % len(vRocks)\n\n # Save the Directions Position, the Rocks Position, last 30 lines\n xPos = str(nDir) + ',' + str(nRock) + ',' + Lasts()\n # if Find this configuration in vSave, multiply the difference. Without this, the procedure will consume all memory\n if xPos in vSave:\n oldX, oldLen = vPos[vSave.index(xPos)]\n difTop = len(Arena) - oldLen\n difX = x - oldX\n nMult = (nMax - x) // difX\n nArenaCut += nMult * difTop\n x += nMult * difX\n # Clear to not find again, because lasts a few steps\n vSave = []\n vPos = []\n\n vSave.append(xPos)\n vPos.append([x, len(Arena)])\n\n x += 1\n\n # MostraArena()\n return nArenaCut + len(Arena) - 1\n\n\nprint('Turn 1: ', Teste(2022)) # 3188\nprint('Turn 2: ', Teste(1000000000000)) # 1591977077342\n","repo_name":"robertohbr1/adventofcode","sub_path":"2022/17/t.py","file_name":"t.py","file_ext":"py","file_size_in_byte":5432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"11522160989","text":"import pandas as pd\nimport pytest\n\nfrom evalml.data_checks import (\n DataCheckActionCode,\n DataCheckActionOption,\n DataCheckMessageCode,\n DataCheckWarning,\n SparsityDataCheck,\n)\n\nsparsity_data_check_name = SparsityDataCheck.name\n\n\ndef test_sparsity_data_check_init():\n sparsity_check = SparsityDataCheck(\"multiclass\", threshold=4 / 15)\n assert sparsity_check.threshold == 4 / 15\n\n sparsity_check = SparsityDataCheck(\"multiclass\", threshold=0.2)\n assert sparsity_check.unique_count_threshold == 10\n\n sparsity_check = SparsityDataCheck(\n \"multiclass\",\n threshold=0.1,\n unique_count_threshold=5,\n )\n assert sparsity_check.unique_count_threshold == 5\n\n with pytest.raises(\n ValueError,\n match=\"Threshold must be a float between 0 and 1, inclusive.\",\n ):\n SparsityDataCheck(\"multiclass\", threshold=-0.1)\n with pytest.raises(\n ValueError,\n match=\"Threshold must be a float between 0 and 1, inclusive.\",\n ):\n SparsityDataCheck(\"multiclass\", threshold=1.1)\n\n with pytest.raises(\n ValueError,\n match=\"Sparsity is only defined for multiclass problem types.\",\n ):\n SparsityDataCheck(\"binary\", threshold=0.5)\n with pytest.raises(\n ValueError,\n match=\"Sparsity is only defined for multiclass problem types.\",\n ):\n SparsityDataCheck(\"time series binary\", threshold=0.5)\n with pytest.raises(\n ValueError,\n match=\"Sparsity is only defined for multiclass problem types.\",\n ):\n SparsityDataCheck(\"regression\", threshold=0.5)\n with pytest.raises(\n ValueError,\n match=\"Sparsity is only defined for multiclass problem types.\",\n ):\n SparsityDataCheck(\"time series regression\", threshold=0.5)\n\n with pytest.raises(\n ValueError,\n match=\"Unique count threshold must be positive integer.\",\n ):\n SparsityDataCheck(\"multiclass\", threshold=0.5, unique_count_threshold=-1)\n with pytest.raises(\n ValueError,\n match=\"Unique count threshold must be positive integer.\",\n ):\n SparsityDataCheck(\"multiclass\", threshold=0.5, unique_count_threshold=2.3)\n\n\ndef test_sparsity_data_check_sparsity_score():\n # Application to a Series\n # Here, only 0 exceedes the count_threshold of 3. 0 is 1/3 unique values. So the score is 1/3.\n data = pd.Series([x % 3 for x in range(10)]) # [0,1,2,0,1,2,0,1,2,0]\n scores = SparsityDataCheck.sparsity_score(data, count_threshold=3)\n assert round(scores, 6) == round(1 / 3, 6), \"Sparsity Series check failed.\"\n\n # Another application to a Series\n # Here, 1 exceeds the count_threshold of 3. 1 is 1/1 unique values, so the score is 1.\n data = pd.Series([1, 1, 1, 1, 1, 1, 1, 1])\n scores = SparsityDataCheck.sparsity_score(data, count_threshold=3)\n assert scores == 1\n\n # Another application to a Series\n # Here, 1 does not exceed the count_threshold of 10. 1 is 1/1 unique values, so the score is 0.\n data = pd.Series([1, 1, 1, 1, 1, 1, 1, 1])\n scores = SparsityDataCheck.sparsity_score(data, count_threshold=10)\n assert scores == 0\n\n # Application to an entire DataFrame\n data = pd.DataFrame(\n {\n \"most_sparse\": [float(x) for x in range(10)], # [0,1,2,3,4,5,6,7,8,9]\n \"more_sparse\": [x % 5 for x in range(10)], # [0,1,2,3,4,0,1,2,3,4]\n \"sparse\": [x % 3 for x in range(10)], # [0,1,2,0,1,2,0,1,2,0]\n \"less_sparse\": [x % 2 for x in range(10)], # [0,1,0,1,0,1,0,1,0,1]\n \"not_sparse\": [float(1) for x in range(10)],\n },\n ) # [1,1,1,1,1,1,1,1,1,1]\n sparsity_score = SparsityDataCheck.sparsity_score\n scores = data.apply(sparsity_score, count_threshold=3)\n ans = pd.Series(\n {\n \"most_sparse\": 0.000000,\n \"more_sparse\": 0.000000,\n \"sparse\": 0.333333,\n \"less_sparse\": 1.000000,\n \"not_sparse\": 1.000000,\n },\n )\n assert scores.round(6).equals(ans), \"Sparsity DataFrame check failed.\"\n\n\ndef test_sparsity_data_check_warnings():\n data = pd.DataFrame(\n {\n \"most_sparse\": [float(x) for x in range(10)], # [0,1,2,3,4,5,6,7,8,9]\n \"more_sparse\": [x % 5 for x in range(10)], # [0,1,2,3,4,0,1,2,3,4]\n \"sparse\": [x % 3 for x in range(10)], # [0,1,2,0,1,2,0,1,2,0]\n \"less_sparse\": [x % 2 for x in range(10)], # [0,1,0,1,0,1,0,1,0,1]\n \"not_sparse\": [float(1) for x in range(10)],\n },\n ) # [1,1,1,1,1,1,1,1,1,1]\n\n sparsity_check = SparsityDataCheck(\n problem_type=\"multiclass\",\n threshold=0.4,\n unique_count_threshold=3,\n )\n assert sparsity_check.validate(data) == [\n DataCheckWarning(\n message=\"Input columns ('most_sparse', 'more_sparse', 'sparse') for multiclass problem type are too sparse.\",\n data_check_name=sparsity_data_check_name,\n message_code=DataCheckMessageCode.TOO_SPARSE,\n details={\n \"columns\": [\"most_sparse\", \"more_sparse\", \"sparse\"],\n \"sparsity_score\": {\n \"most_sparse\": 0,\n \"more_sparse\": 0,\n \"sparse\": 0.3333333333333333,\n },\n },\n action_options=[\n DataCheckActionOption(\n DataCheckActionCode.DROP_COL,\n data_check_name=sparsity_data_check_name,\n metadata={\"columns\": [\"most_sparse\", \"more_sparse\", \"sparse\"]},\n ),\n ],\n ).to_dict(),\n ]\n","repo_name":"alteryx/evalml","sub_path":"evalml/tests/data_checks_tests/test_sparsity_data_check.py","file_name":"test_sparsity_data_check.py","file_ext":"py","file_size_in_byte":5609,"program_lang":"python","lang":"en","doc_type":"code","stars":664,"dataset":"github-code","pt":"32"}
+{"seq_id":"101281963","text":"\"\"\"\nDependency management for tools.\n\"\"\"\n\nimport json\nimport logging\nimport os.path\nimport shutil\nfrom collections import OrderedDict\n\nfrom galaxy.util import (\n hash_util,\n plugin_config\n)\nfrom galaxy.util.oset import OrderedSet\nfrom .container_resolvers import ContainerResolver\nfrom .dependencies import ToolInfo\nfrom .requirements import (\n ContainerDescription,\n ToolRequirement,\n ToolRequirements\n)\nfrom .resolvers import (\n ContainerDependency,\n NullDependency,\n)\nfrom .resolvers.conda import CondaDependencyResolver\nfrom .resolvers.galaxy_packages import GalaxyPackageDependencyResolver\nfrom .resolvers.tool_shed_packages import ToolShedPackageDependencyResolver\n\nlog = logging.getLogger(__name__)\n\nCONFIG_VAL_NOT_FOUND = object()\n\n\ndef build_dependency_manager(config):\n if getattr(config, \"use_tool_dependencies\", False):\n dependency_manager_kwds = {\n 'default_base_path': config.tool_dependency_dir,\n 'conf_file': config.dependency_resolvers_config_file,\n 'app_config': config,\n }\n if getattr(config, \"use_cached_dependency_manager\", False):\n dependency_manager = CachedDependencyManager(**dependency_manager_kwds)\n else:\n dependency_manager = DependencyManager(**dependency_manager_kwds)\n else:\n dependency_manager = NullDependencyManager()\n\n return dependency_manager\n\n\nclass DependencyManager(object):\n \"\"\"\n A DependencyManager attempts to resolve named and versioned dependencies by\n searching for them under a list of directories. Directories should be\n of the form:\n\n $BASE/name/version/...\n\n and should each contain a file 'env.sh' which can be sourced to make the\n dependency available in the current shell environment.\n \"\"\"\n\n def __init__(self, default_base_path, conf_file=None, app_config={}):\n \"\"\"\n Create a new dependency manager looking for packages under the paths listed\n in `base_paths`. The default base path is app.config.tool_dependency_dir.\n \"\"\"\n if not os.path.exists(default_base_path):\n log.warning(\"Path '%s' does not exist, ignoring\", default_base_path)\n if not os.path.isdir(default_base_path):\n log.warning(\"Path '%s' is not directory, ignoring\", default_base_path)\n self.__app_config = app_config\n self.default_base_path = os.path.abspath(default_base_path)\n self.resolver_classes = self.__resolvers_dict()\n self.dependency_resolvers = self.__build_dependency_resolvers(conf_file)\n self._enabled_container_types = []\n self._destination_for_container_type = {}\n\n def set_enabled_container_types(self, container_types_to_destinations):\n \"\"\"Set the union of all enabled container types.\"\"\"\n self._enabled_container_types = [container_type for container_type in container_types_to_destinations.keys()]\n # Just pick first enabled destination for a container type, probably covers the most common deployment scenarios\n self._destination_for_container_type = container_types_to_destinations\n\n def get_destination_info_for_container_type(self, container_type, destination_id=None):\n if destination_id is None:\n return next(iter(self._destination_for_container_type[container_type])).params\n else:\n for destination in self._destination_for_container_type[container_type]:\n if destination.id == destination_id:\n return destination.params\n\n @property\n def enabled_container_types(self):\n \"\"\"Returns the union of enabled container types.\"\"\"\n return self._enabled_container_types\n\n def get_resolver_option(self, resolver, key, explicit_resolver_options={}):\n \"\"\"Look in resolver-specific settings for option and then fallback to global settings.\n \"\"\"\n default = resolver.config_options.get(key)\n config_prefix = resolver.resolver_type\n global_key = \"%s_%s\" % (config_prefix, key)\n value = explicit_resolver_options.get(key, CONFIG_VAL_NOT_FOUND)\n if value is CONFIG_VAL_NOT_FOUND:\n value = self.get_app_option(global_key, default)\n\n return value\n\n def get_app_option(self, key, default=None):\n value = CONFIG_VAL_NOT_FOUND\n if isinstance(self.__app_config, dict):\n value = self.__app_config.get(key, CONFIG_VAL_NOT_FOUND)\n else:\n value = getattr(self.__app_config, key, CONFIG_VAL_NOT_FOUND)\n if value is CONFIG_VAL_NOT_FOUND and hasattr(self.__app_config, \"config_dict\"):\n value = self.__app_config.config_dict.get(key, CONFIG_VAL_NOT_FOUND)\n if value is CONFIG_VAL_NOT_FOUND:\n value = default\n return value\n\n def dependency_shell_commands(self, requirements, **kwds):\n requirements_to_dependencies = self.requirements_to_dependencies(requirements, **kwds)\n ordered_dependencies = OrderedSet(requirements_to_dependencies.values())\n return [dependency.shell_commands() for dependency in ordered_dependencies if not isinstance(dependency, ContainerDependency)]\n\n def requirements_to_dependencies(self, requirements, **kwds):\n \"\"\"\n Takes a list of requirements and returns a dictionary\n with requirements as key and dependencies as value caching\n these on the tool instance if supplied.\n \"\"\"\n requirement_to_dependency = self._requirements_to_dependencies_dict(requirements, **kwds)\n\n if 'tool_instance' in kwds:\n kwds['tool_instance'].dependencies = [dep.to_dict() for dep in requirement_to_dependency.values()]\n\n return requirement_to_dependency\n\n def _requirements_to_dependencies_dict(self, requirements, search=False, **kwds):\n \"\"\"Build simple requirements to dependencies dict for resolution.\"\"\"\n requirement_to_dependency = OrderedDict()\n index = kwds.get('index')\n install = kwds.get('install', False)\n resolver_type = kwds.get('resolver_type')\n require_exact = kwds.get('exact', False)\n return_null_dependencies = kwds.get('return_null', False)\n\n resolvable_requirements = requirements.resolvable\n tool_info = ToolInfo(requirements=resolvable_requirements)\n\n for i, resolver in enumerate(self.dependency_resolvers):\n\n if index is not None and i != index:\n continue\n\n if resolver_type is not None and resolver.resolver_type != resolver_type:\n continue\n\n _requirement_to_dependency = OrderedDict([(k, v) for k, v in requirement_to_dependency.items() if not isinstance(v, NullDependency)])\n\n if len(_requirement_to_dependency) == len(resolvable_requirements):\n # Shortcut - resolution complete.\n break\n\n if resolver.resolver_type.startswith('build_mulled') and not install:\n # don't want to build images here\n continue\n\n # Check requirements all at once\n all_unmet = len(_requirement_to_dependency) == 0\n if hasattr(resolver, \"resolve_all\"):\n resolve = resolver.resolve_all\n elif isinstance(resolver, ContainerResolver):\n if not resolver.resolver_type.startswith(('cached', 'explicit')) and not (search or install):\n # These would look up available containers using the quay API,\n # we only want to do this if we search for containers\n continue\n resolve = resolver.resolve\n else:\n resolve = None\n if all_unmet and resolve is not None:\n # TODO: Handle specs.\n dependencies = resolve(requirements=resolvable_requirements,\n enabled_container_types=self.enabled_container_types,\n destination_for_container_type=self.get_destination_info_for_container_type,\n tool_info=tool_info,\n **kwds)\n if dependencies:\n if isinstance(dependencies, ContainerDescription):\n dependencies = [ContainerDependency(dependencies, name=r.name, version=r.version) for r in resolvable_requirements]\n assert len(dependencies) == len(resolvable_requirements)\n for requirement, dependency in zip(resolvable_requirements, dependencies):\n log.debug(dependency.resolver_msg)\n requirement_to_dependency[requirement] = dependency\n\n # Shortcut - resolution complete.\n break\n\n if not isinstance(resolver, ContainerResolver):\n\n # Check individual requirements\n for requirement in resolvable_requirements:\n if requirement in _requirement_to_dependency:\n continue\n\n dependency = resolver.resolve(requirement, **kwds)\n if require_exact and not dependency.exact:\n continue\n\n if not isinstance(dependency, NullDependency):\n log.debug(dependency.resolver_msg)\n requirement_to_dependency[requirement] = dependency\n elif return_null_dependencies:\n log.debug(dependency.resolver_msg)\n dependency.version = requirement.version\n requirement_to_dependency[requirement] = dependency\n\n return requirement_to_dependency\n\n def uses_tool_shed_dependencies(self):\n return any(map(lambda r: isinstance(r, ToolShedPackageDependencyResolver), self.dependency_resolvers))\n\n def find_dep(self, name, version=None, type='package', **kwds):\n log.debug('Find dependency %s version %s' % (name, version))\n requirements = ToolRequirements([ToolRequirement(name=name, version=version, type=type)])\n dep_dict = self._requirements_to_dependencies_dict(requirements, **kwds)\n if len(dep_dict) > 0:\n return next(iter(dep_dict.values())) # get first dep\n else:\n return NullDependency(name=name, version=version)\n\n def __build_dependency_resolvers(self, conf_file):\n if not conf_file:\n return self.__default_dependency_resolvers()\n if not os.path.exists(conf_file):\n log.debug(\"Unable to find config file '%s'\", conf_file)\n return self.__default_dependency_resolvers()\n plugin_source = plugin_config.plugin_source_from_path(conf_file)\n return self.__parse_resolver_conf_xml(plugin_source)\n\n def __default_dependency_resolvers(self):\n return [\n ToolShedPackageDependencyResolver(self),\n GalaxyPackageDependencyResolver(self),\n CondaDependencyResolver(self),\n GalaxyPackageDependencyResolver(self, versionless=True),\n CondaDependencyResolver(self, versionless=True),\n ]\n\n def __parse_resolver_conf_xml(self, plugin_source):\n \"\"\"\n \"\"\"\n extra_kwds = dict(dependency_manager=self)\n return plugin_config.load_plugins(self.resolver_classes, plugin_source, extra_kwds)\n\n def __resolvers_dict(self):\n import galaxy.tools.deps.resolvers\n return plugin_config.plugins_dict(galaxy.tools.deps.resolvers, 'resolver_type')\n\n\nclass CachedDependencyManager(DependencyManager):\n def __init__(self, default_base_path, conf_file=None, app_config={}, tool_dependency_cache_dir=None):\n super(CachedDependencyManager, self).__init__(default_base_path=default_base_path, conf_file=conf_file, app_config=app_config)\n self.tool_dependency_cache_dir = self.get_app_option(\"tool_dependency_cache_dir\")\n\n def build_cache(self, requirements, **kwds):\n resolved_dependencies = self.requirements_to_dependencies(requirements, **kwds)\n cacheable_dependencies = [dep for dep in resolved_dependencies.values() if dep.cacheable]\n hashed_dependencies_dir = self.get_hashed_dependencies_path(cacheable_dependencies)\n if os.path.exists(hashed_dependencies_dir):\n if kwds.get('force_rebuild', False):\n try:\n shutil.rmtree(hashed_dependencies_dir)\n except Exception:\n log.warning(\"Could not delete cached dependencies directory '%s'\" % hashed_dependencies_dir)\n raise\n else:\n log.debug(\"Cached dependencies directory '%s' already exists, skipping build\", hashed_dependencies_dir)\n return\n [dep.build_cache(hashed_dependencies_dir) for dep in cacheable_dependencies]\n\n def dependency_shell_commands(self, requirements, **kwds):\n \"\"\"\n Runs a set of requirements through the dependency resolvers and returns\n a list of commands required to activate the dependencies. If dependencies\n are cacheable and the cache does not exist, will try to create it.\n If cached environment exists or is successfully created, will generate\n commands to activate it.\n \"\"\"\n resolved_dependencies = self.requirements_to_dependencies(requirements, **kwds)\n cacheable_dependencies = [dep for dep in resolved_dependencies.values() if dep.cacheable]\n hashed_dependencies_dir = self.get_hashed_dependencies_path(cacheable_dependencies)\n if not os.path.exists(hashed_dependencies_dir) and self.get_app_option(\"precache_dependencies\", False):\n # Cache not present, try to create it\n self.build_cache(requirements, **kwds)\n if os.path.exists(hashed_dependencies_dir):\n [dep.set_cache_path(hashed_dependencies_dir) for dep in cacheable_dependencies]\n commands = [dep.shell_commands() for dep in resolved_dependencies.values()]\n return commands\n\n def hash_dependencies(self, resolved_dependencies):\n \"\"\"Return hash for dependencies\"\"\"\n resolved_dependencies = [(dep.name, dep.version, dep.exact, dep.dependency_type) for dep in resolved_dependencies]\n hash_str = json.dumps(sorted(resolved_dependencies))\n return hash_util.new_secure_hash(hash_str)[:8] # short hash\n\n def get_hashed_dependencies_path(self, resolved_dependencies):\n \"\"\"\n Returns the path to the hashed dependencies directory (but does not evaluate whether the path exists).\n\n :param resolved_dependencies: list of resolved dependencies\n :type resolved_dependencies: list\n\n :return: path\n :rtype: str\n \"\"\"\n req_hashes = self.hash_dependencies(resolved_dependencies)\n return os.path.abspath(os.path.join(self.tool_dependency_cache_dir, req_hashes))\n\n\nclass NullDependencyManager(DependencyManager):\n\n def __init__(self, default_base_path=None, conf_file=None, app_config={}):\n self.__app_config = app_config\n self.resolver_classes = set()\n self.dependency_resolvers = []\n self._enabled_container_types = []\n self._destination_for_container_type = {}\n\n def uses_tool_shed_dependencies(self):\n return False\n\n def dependency_shell_commands(self, requirements, **kwds):\n return []\n\n def find_dep(self, name, version=None, type='package', **kwds):\n return NullDependency(version=version, name=name)\n","repo_name":"galaxyproject/galaxy-lib","sub_path":"galaxy/tools/deps/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":15491,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"32"}
+{"seq_id":"71026114973","text":"# -*- coding: utf-8 -*-\nfrom django.shortcuts import render\nfrom util.pre_load import neo4jconn\n\nimport json\n\n\ndef search_all_events(request):\n entityRelation = neo4jconn.get_all_event()\n return render(request, 'event_search.html', {'entityRelation': json.dumps(entityRelation, ensure_ascii=False)})\n\n\ndef search_all_headmaster(request):\n entityRelation = neo4jconn.get_all_headmaster()\n return render(request, 'headmaster_search.html', {'entityRelation': json.dumps(entityRelation, ensure_ascii=False)})\n\n\ndef search_entity(request):\n ctx = {}\n if request.GET:\n entity = request.GET['user_text']\n entity = entity.strip()\n entity = entity.lower()\n entity = ''.join(entity.split())\n\n entityRelation = neo4jconn.get_entity_info(entity)\n if len(entityRelation) == 0:\n # 若数据库中无法找到该实体,则返回数据库中无该实体\n ctx = {'title': '知识库中暂未添加该实体'}\n return render(request, 'entity_search.html', {'ctx': json.dumps(ctx, ensure_ascii=False)})\n else:\n return render(request, 'entity_search.html',\n {'entityRelation': json.dumps(entityRelation, ensure_ascii=False)})\n # 需要进行类型转换\n return render(request, 'entity_search.html', {'ctx': ctx})\n\n\n# 关系查询\ndef search_relation(request):\n ctx = {}\n if (request.GET):\n # 实体1\n entity1 = request.GET['entity1_text']\n entity1 = entity1.strip()\n entity1 = entity1.lower()\n entity1 = ''.join(entity1.split())\n\n # 关系\n relation = request.GET['relation_name_text']\n # 将关系名转为大写\n relation = relation.upper()\n\n # 实体2\n entity2 = request.GET['entity2_text']\n entity2 = entity2.strip()\n entity2 = entity2.lower()\n entity2 = ''.join(entity2.split())\n\n # 1.若只输入entity1,则输出与entity1有直接关系的实体和关系\n if len(entity1) != 0 and len(relation) == 0 and len(entity2) == 0:\n searchResult = neo4jconn.findRelationByEntity1(entity1)\n if len(searchResult) > 0:\n return render(request, 'relation.html', {'searchResult': json.dumps(searchResult, ensure_ascii=False)})\n\n # 2.若只输入entity2则,则输出与entity2有直接关系的实体和关系\n if len(entity2) != 0 and len(relation) == 0 and len(entity1) == 0:\n searchResult = neo4jconn.findRelationByEntity2(entity2)\n if len(searchResult) > 0:\n return render(request, 'relation.html', {'searchResult': json.dumps(searchResult, ensure_ascii=False)})\n\n # 3.若输入entity1和relation,则输出与entity1具有relation关系的其他实体\n if len(entity1) != 0 and len(relation) != 0 and len(entity2) == 0:\n searchResult = neo4jconn.findOtherEntities(entity1, relation)\n if len(searchResult) > 0:\n return render(request, 'relation.html', {'searchResult': json.dumps(searchResult, ensure_ascii=False)})\n\n # 4.若输入entity2和relation,则输出与entity2具有relation关系的其他实体\n if len(entity2) != 0 and len(relation) != 0 and len(entity1) == 0:\n searchResult = neo4jconn.findOtherEntities2(entity2, relation)\n if len(searchResult) > 0:\n return render(request, 'relation.html', {'searchResult': json.dumps(searchResult, ensure_ascii=False)})\n\n # 5.若输入entity1和entity2,则输出entity1和entity2之间的关系\n if len(entity1) != 0 and len(relation) == 0 and len(entity2) != 0:\n searchResult = neo4jconn.findRelationByEntities(entity1, entity2)\n if len(searchResult) > 0:\n return render(request, 'relation.html', {'searchResult': json.dumps(searchResult, ensure_ascii=False)})\n\n # 6.若输入entity1,entity2和relation,则输出entity1、entity2是否具有相应的关系\n if len(entity1) != 0 and len(entity2) != 0 and len(relation) != 0:\n print(relation)\n searchResult = neo4jconn.findEntityRelation(entity1, relation, entity2)\n if len(searchResult) > 0:\n return render(request, 'relation.html', {'searchResult': json.dumps(searchResult, ensure_ascii=False)})\n\n # 7.若全为空\n if len(entity1) != 0 and len(relation) != 0 and len(entity2) != 0:\n pass\n\n ctx = {'title': '暂未找到相应的匹配
'}\n return render(request, 'relation.html', {'ctx': ctx})\n\n return render(request, 'relation.html', {'ctx': ctx})\n","repo_name":"Yazmin-y/tju_history_kg","sub_path":"tju_history_kg/history_kg/relation_view.py","file_name":"relation_view.py","file_ext":"py","file_size_in_byte":4655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"31582107088","text":"#coding: utf8\n#author: Tian Xia (SummerRainET2008@gmail.com)\n\nfrom pa_nlp.classifiers.textcnn.trainer import *\nfrom pa_nlp.chinese import split_and_norm_string\nfrom pa_nlp.common import *\n\nif __name__ == '__main__':\n data_path = os.path.join(\n get_module_path(\"common\"),\n \"classifiers/textcnn/test_data\"\n )\n\n train_file = os.path.join(data_path, \"data.1.train.pydict\")\n vali_file = os.path.join(data_path, \"data.1.test.pydict\")\n \n train_norm_file = normalize_data_file(train_file, split_and_norm_string)\n vali_norm_file = normalize_data_file(vali_file, split_and_norm_string)\n\n param = create_parameter(\n train_file=train_norm_file,\n vali_files=[vali_norm_file],\n num_classes=45,\n vob_file=\"vob.data\",\n neg_sample_ratio=1,\n max_seq_length=32,\n epoch_num=5,\n batch_size=32,\n embedding_size=128,\n kernels=\"1,2,3,4,5\",\n filter_num=128,\n dropout_keep_prob=0.5,\n learning_rate=0.001,\n l2_reg_lambda=0,\n evaluate_frequency=100,\n remove_OOV=False,\n GPU=-1\n )\n\n create_vocabulary(param[\"train_file\"], 1, param[\"vob_file\"])\n \n Trainer(param).train()\n print(\"Training is Done\")\n","repo_name":"YingtongBu/insight_nlp","sub_path":"pa_nlp/classifiers/textcnn/trainer_TEST.py","file_name":"trainer_TEST.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"23372778443","text":"import collections\nimport math\nimport numpy as np\n\n# 3rd party imports\ntry:\n from matplotlib.cm import viridis as DEFAULT_CMAP\nexcept ImportError:\n from matplotlib.cm import jet as DEFAULT_CMAP\nfrom matplotlib.gridspec import GridSpec\nfrom matplotlib.legend import Legend\n\n# local imports\nfrom mantid.api import AnalysisDataService, MatrixWorkspace\nfrom mantid.kernel import Logger\nfrom mantid.plots import MantidAxes\nfrom mantidqt.plotting.figuretype import figure_type, FigureType\nfrom mantid.py3compat import is_text_string, string_types\nfrom mantidqt.dialogs.spectraselectordialog import get_spectra_selection\n\n# -----------------------------------------------------------------------------\n# Constants\n# -----------------------------------------------------------------------------\nPROJECTION = 'mantid'\n# See https://matplotlib.org/api/_as_gen/matplotlib.figure.SubplotParams.html#matplotlib.figure.SubplotParams\nSUBPLOT_WSPACE = 0.5\nSUBPLOT_HSPACE = 0.5\nLOGGER = Logger(\"workspace.plotting.functions\")\n\n\n# -----------------------------------------------------------------------------\n# Decorators\n# -----------------------------------------------------------------------------\n\ndef manage_workspace_names(func):\n \"\"\"\n A decorator to go around plotting functions.\n This will retrieve workspaces from workspace names before\n calling the plotting function\n :param func: A plotting function\n :return:\n \"\"\"\n def inner_func(workspaces, *args, **kwargs):\n workspaces = _validate_workspace_names(workspaces)\n return func(workspaces, *args, **kwargs)\n return inner_func\n\n\n# -----------------------------------------------------------------------------\n# 'Public' Functions\n# -----------------------------------------------------------------------------\n\ndef can_overplot():\n \"\"\"\n Checks if overplotting on the current figure can proceed\n with the given options\n\n :return: A 2-tuple of boolean indicating compatability and\n a string containing an error message if the current figure is not\n compatible.\n \"\"\"\n compatible = False\n msg = \"Unable to overplot on currently active plot type.\\n\" \\\n \"Please select another plot.\"\n fig = current_figure_or_none()\n if fig is not None:\n figtype = figure_type(fig)\n if figtype is FigureType.Line or figtype is FigureType.Errorbar:\n compatible, msg = True, None\n\n return compatible, msg\n\n\ndef current_figure_or_none():\n \"\"\"If an active figure exists then return it otherwise return None\n\n :return: An active figure or None\n \"\"\"\n import matplotlib.pyplot as plt\n if len(plt.get_fignums()) > 0:\n return plt.gcf()\n else:\n return None\n\n\ndef figure_title(workspaces, fig_num):\n \"\"\"Create a default figure title from a single workspace, list of workspaces or\n workspace names and a figure number. The name of the first workspace in the list\n is concatenated with the figure number.\n\n :param workspaces: A single workspace, list of workspaces or workspace name/list of workspace names\n :param fig_num: An integer denoting the figure number\n :return: A title for the figure\n \"\"\"\n\n def wsname(w):\n return w.name() if hasattr(w, 'name') else w\n\n if is_text_string(workspaces) or not isinstance(workspaces, collections.Sequence):\n # assume a single workspace\n first = workspaces\n else:\n assert len(workspaces) > 0\n first = workspaces[0]\n\n return wsname(first) + '-' + str(fig_num)\n\n\ndef plot_from_names(names, errors, overplot, fig=None):\n \"\"\"\n Given a list of names of workspaces, raise a dialog asking for the\n a selection of what to plot and then plot it.\n\n :param names: A list of workspace names\n :param errors: If true then error bars will be plotted on the points\n :param overplot: If true then the add to the current figure if one\n exists and it is a compatible figure\n :param fig: If not None then use this figure object to plot\n :return: The figure containing the plot or None if selection was cancelled\n \"\"\"\n if fig and len(fig.axes) > 1:\n LOGGER.warning(\"Cannot plot workspace on top of Matplotlib subplots.\")\n return None\n\n workspaces = AnalysisDataService.Instance().retrieveWorkspaces(names, unrollGroups=True)\n try:\n selection = get_spectra_selection(workspaces)\n except Exception as exc:\n LOGGER.warning(format(str(exc)))\n selection = None\n\n if selection is None:\n return None\n\n return plot(selection.workspaces, spectrum_nums=selection.spectra,\n wksp_indices=selection.wksp_indices,\n errors=errors, overplot=overplot, fig=fig)\n\n\ndef get_plot_fig(overplot=None, ax_properties=None, window_title=None):\n \"\"\"\n Create a blank figure and axes, with configurable properties.\n :param overplot: If true then plotting on figure will plot over previous plotting\n :param ax_properties: A doict of axes properties. E.g. {'yscale': 'log'} for log y-axis\n :param window_title: A string denoting the name of the GUI window which holds the graph\n :return: Matplotlib fig and axes objects\n \"\"\"\n import matplotlib.pyplot as plt\n if overplot:\n ax = plt.gca(projection=PROJECTION)\n fig = ax.figure\n else:\n fig = plt.figure()\n ax = fig.add_subplot(111, projection=PROJECTION)\n if ax_properties:\n ax.set(**ax_properties)\n if window_title:\n fig.canvas.set_window_title(window_title)\n\n return fig, ax\n\n\n@manage_workspace_names\ndef plot(workspaces, spectrum_nums=None, wksp_indices=None, errors=False,\n overplot=False, fig=None, plot_kwargs=None, ax_properties=None,\n window_title=None):\n \"\"\"\n Create a figure with a single subplot and for each workspace/index add a\n line plot to the new axes. show() is called before returning the figure instance. A legend\n is added.\n\n :param workspaces: A list of workspace handles\n :param spectrum_nums: A list of spectrum number identifiers (general start from 1)\n :param wksp_indices: A list of workspace indexes (starts from 0)\n :param errors: If true then error bars are added for each plot\n :param overplot: If true then overplot over the current figure if one exists\n :param fig: If not None then use this Figure object to plot\n :param plot_kwargs: Arguments that will be passed onto the plot function\n :param ax_properties: A dict of axes properties. E.g. {'yscale': 'log'}\n :param window_title: A string denoting name of the GUI window which holds the graph\n :return: The figure containing the plots\n \"\"\"\n if plot_kwargs is None:\n plot_kwargs = {}\n _validate_plot_inputs(workspaces, spectrum_nums, wksp_indices)\n if spectrum_nums is not None:\n kw, nums = 'specNum', spectrum_nums\n else:\n kw, nums = 'wkspIndex', wksp_indices\n\n if fig is None:\n # get/create the axes to hold the plot\n fig, ax = get_plot_fig(overplot, ax_properties, window_title)\n else:\n ax = fig.gca()\n\n if not isinstance(ax, MantidAxes):\n # Convert to a MantidAxes if it isn't already. Ignore legend since\n # a new one will be drawn later\n ax = MantidAxes.from_mpl_axes(ax, ignore_artists=[Legend])\n\n # do the plotting\n plot_fn = ax.errorbar if errors else ax.plot\n for ws in workspaces:\n for num in nums:\n plot_kwargs[kw] = num\n plot_fn(ws, **plot_kwargs)\n\n ax.legend().draggable()\n if not overplot:\n title = workspaces[0].name()\n ax.set_title(title)\n fig.canvas.set_window_title(figure_title(workspaces, fig.number))\n fig.canvas.draw()\n fig.show()\n return fig\n\n\ndef pcolormesh_from_names(names, fig=None):\n \"\"\"\n Create a figure containing pcolor subplots\n\n :param names: A list of workspace names\n :param fig: An optional figure to contain the new plots. Its current contents will be cleared\n :returns: The figure containing the plots\n \"\"\"\n try:\n return pcolormesh(AnalysisDataService.retrieveWorkspaces(names, unrollGroups=True),\n fig=fig)\n except Exception as exc:\n LOGGER.warning(format(str(exc)))\n return None\n\n\ndef use_imshow(ws):\n y = ws.getAxis(1).extractValues()\n difference = np.diff(y)\n try:\n commonLogBins = hasattr(ws, 'isCommonLogBins') and ws.isCommonLogBins()\n return np.all(np.isclose(difference[:-1], difference[0])) and not commonLogBins\n except IndexError:\n return False\n\n\n@manage_workspace_names\ndef pcolormesh(workspaces, fig=None):\n \"\"\"\n Create a figure containing pcolor subplots\n\n :param workspaces: A list of workspace handles\n :param fig: An optional figure to contain the new plots. Its current contents will be cleared\n :returns: The figure containing the plots\n \"\"\"\n # check inputs\n _validate_pcolormesh_inputs(workspaces)\n\n # create a subplot of the appropriate number of dimensions\n # extend in number of columns if the number of plottables is not a square number\n workspaces_len = len(workspaces)\n fig, axes, nrows, ncols = _create_subplots(workspaces_len, fig=fig)\n\n row_idx, col_idx = 0, 0\n for subplot_idx in range(nrows * ncols):\n ax = axes[row_idx][col_idx]\n if subplot_idx < workspaces_len:\n ws = workspaces[subplot_idx]\n ax.set_title(ws.name())\n if use_imshow(ws):\n pcm = ax.imshow(ws, cmap=DEFAULT_CMAP, aspect='auto', origin='lower')\n else:\n pcm = ax.pcolormesh(ws, cmap=DEFAULT_CMAP)\n for lbl in ax.get_xticklabels():\n lbl.set_rotation(45)\n if col_idx < ncols - 1:\n col_idx += 1\n else:\n row_idx += 1\n col_idx = 0\n else:\n # nothing here\n ax.axis('off')\n\n # Adjust locations to ensure the plots don't overlap\n fig.subplots_adjust(wspace=SUBPLOT_WSPACE, hspace=SUBPLOT_HSPACE)\n fig.colorbar(pcm, ax=axes.ravel().tolist(), pad=0.06)\n fig.canvas.set_window_title(figure_title(workspaces, fig.number))\n fig.canvas.draw()\n fig.show()\n return fig\n\n\n# ----------------- Compatability functions ---------------------\n\n\ndef plotSpectrum(workspaces, indices, distribution=None, error_bars=False,\n type=None, window=None, clearWindow=None,\n waterfall=False):\n \"\"\"\n Create a figure with a single subplot and for each workspace/index add a\n line plot to the new axes. show() is called before returning the figure instance\n\n :param workspaces: Workspace/workspaces to plot as a string, workspace handle, list of strings or list of\n workspaces handles.\n :param indices: A single int or list of ints specifying the workspace indices to plot\n :param distribution: ``None`` (default) asks the workspace. ``False`` means\n divide by bin width. ``True`` means do not divide by bin width.\n Applies only when the the workspace is a MatrixWorkspace histogram.\n :param error_bars: If true then error bars will be added for each curve\n :param type: curve style for plot (-1: unspecified; 0: line, default; 1: scatter/dots)\n :param window: Ignored. Here to preserve backwards compatibility\n :param clearWindow: Ignored. Here to preserve backwards compatibility\n :param waterfall:\n \"\"\"\n if type == 1:\n fmt = 'o'\n else:\n fmt = '-'\n\n return plot(workspaces, wksp_indices=indices,\n errors=error_bars, fmt=fmt)\n\n\n# -----------------------------------------------------------------------------\n# 'Private' Functions\n# -----------------------------------------------------------------------------\ndef _raise_if_not_sequence(value, seq_name, element_type=None):\n \"\"\"\n Raise a ValueError if the given object is not a sequence\n\n :param value: The value object to validate\n :param seq_name: The variable name of the sequence for the error message\n :param element_type: An optional type to provide to check that each element\n is an instance of this type\n :raises ValueError: if the conditions are not met\n \"\"\"\n accepted_types = (list, tuple, range)\n if type(value) not in accepted_types:\n raise ValueError(\"{} should be a list or tuple, \"\n \"instead found '{}'\".format(seq_name,\n value.__class__.__name__))\n if element_type is not None:\n def raise_if_not_type(x):\n if not isinstance(x, element_type):\n raise ValueError(\"Unexpected type: '{}'\".format(x.__class__.__name__))\n\n # Map in Python3 is an iterator, so ValueError will not be raised unless the values are yielded.\n # converting to a list forces yielding\n list(map(raise_if_not_type, value))\n\n\ndef _validate_plot_inputs(workspaces, spectrum_nums, wksp_indices):\n \"\"\"Raises a ValueError if any arguments have the incorrect types\"\"\"\n if spectrum_nums is not None and wksp_indices is not None:\n raise ValueError(\"Both spectrum_nums and wksp_indices supplied. \"\n \"Please supply only 1.\")\n\n _raise_if_not_sequence(workspaces, 'workspaces', MatrixWorkspace)\n\n if spectrum_nums is not None:\n _raise_if_not_sequence(spectrum_nums, 'spectrum_nums')\n\n if wksp_indices is not None:\n _raise_if_not_sequence(wksp_indices, 'wksp_indices')\n\n\ndef _validate_workspace_names(workspaces):\n \"\"\"\n Checks if the workspaces passed into a plotting function are workspace names, and\n retrieves the workspaces if they are.\n This function assumes that we do not have a mix of workspaces and workspace names.\n :param workspaces: A list of workspaces or workspace names\n :return: A list of workspaces\n \"\"\"\n try:\n _raise_if_not_sequence(workspaces, 'workspaces', string_types)\n except ValueError:\n return workspaces\n else:\n return AnalysisDataService.Instance().retrieveWorkspaces(workspaces, unrollGroups=True)\n\n\ndef _validate_pcolormesh_inputs(workspaces):\n \"\"\"Raises a ValueError if any arguments have the incorrect types\"\"\"\n _raise_if_not_sequence(workspaces, 'workspaces', MatrixWorkspace)\n\n\ndef _create_subplots(nplots, fig=None):\n \"\"\"\n Create a set of subplots suitable for a given number of plots. A stripped down\n version of plt.subplots that can accept an existing figure instance.\n\n :param nplots: The number of plots required\n :param fig: An optional figure. It is cleared before plotting the new contents\n :return: A 2-tuple of (fig, axes)\n \"\"\"\n import matplotlib.pyplot as plt\n square_side_len = int(math.ceil(math.sqrt(nplots)))\n nrows, ncols = square_side_len, square_side_len\n if square_side_len * square_side_len != nplots:\n # not a square number - square_side_len x square_side_len\n # will be large enough but we could end up with an empty\n # row so chop that off\n if nplots <= (nrows - 1) * ncols:\n nrows -= 1\n\n if fig is None:\n fig = plt.figure()\n else:\n fig.clf()\n # annoyling this repl\n nplots = nrows * ncols\n gs = GridSpec(nrows, ncols)\n axes = np.empty(nplots, dtype=object)\n ax0 = fig.add_subplot(gs[0, 0], projection=PROJECTION)\n axes[0] = ax0\n for i in range(1, nplots):\n axes[i] = fig.add_subplot(gs[i // ncols, i % ncols],\n projection=PROJECTION)\n axes = axes.reshape(nrows, ncols)\n\n return fig, axes, nrows, ncols\n","repo_name":"antonyvam/mantid","sub_path":"qt/python/mantidqt/plotting/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":15638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"}
+{"seq_id":"3213345572","text":"import os.path\nimport libvirt\n\nfrom ovirt.node import base\n\n\ndef hardware_is_available():\n \"\"\"Determins if virtualization hardware is available.\n This does not mean that virtualization is also enabled.\n\n Returns:\n True if there is hardware virtualization hardware available\n \"\"\"\n is_available = False\n\n with open(\"/proc/cpuinfo\") as cpuinfo:\n for line in cpuinfo:\n if line.startswith(\"flags\"):\n if \"vmx\" in line or \"svm\" in line:\n is_available = True\n return is_available\n\n\ndef hardware_is_enabled():\n \"\"\"Determins if virtualization hardware is available and enabled.\n\n Returns:\n True if there is hardware virtualization hardware available and enabled\n \"\"\"\n is_enabled = False\n\n if hardware_is_available():\n has_module = False\n with open(\"/proc/modules\") as modules:\n for line in modules:\n has_module = (line.startswith(\"kvm_intel\") or\n line.startswith(\"kvm_amd\"))\n if has_module:\n break\n\n if has_module and os.path.exists(\"/dev/kvm\"):\n is_enabled = True\n\n return is_enabled\n\n\ndef hardware_status():\n \"\"\"Status of virtualization on this machine.\n\n Returns:\n Status of hardware virtualization support on this machine as a human\n read-able string\n \"\"\"\n return _hardware_status(hardware_is_available(),\n hardware_is_enabled(),\n is_libvirtd_reachable())\n\n\ndef _hardware_status(hardware_is_available, hardware_is_enabled,\n is_libvirtd_reachable):\n \"\"\"\n >>> _hardware_status(True, True, True)\n 'Virtualization hardware was detected and is enabled'\n\n >>> _hardware_status(True, True, False)\n 'Virtualization hardware was detected and is enabled\\\\n\\\n(Failed to Establish Libvirt Connection)'\n\n >>> _hardware_status(True, False, True)\n 'Virtualization hardware was detected but is disabled'\n\n >>> _hardware_status(False, False, True)\n 'No virtualization hardware was detected on this system'\n \"\"\"\n\n msg = \"No virtualization hardware was detected on this system\"\n\n if hardware_is_available:\n msg = \"Virtualization hardware was detected but is disabled\"\n if hardware_is_enabled:\n msg = \"Virtualization hardware was detected and is enabled\"\n\n if not is_libvirtd_reachable:\n msg += \"\\n(Failed to Establish Libvirt Connection)\"\n\n return msg\n\n\ndef is_libvirtd_reachable():\n reachable = True\n try:\n with LibvirtConnection() as l:\n l.getCapabilities()\n except:\n reachable = False\n return reachable\n\n\ndef number_of_domains():\n # FIXME solve this more general\n num_domains = None\n try:\n with LibvirtConnection() as con:\n num_domains = str(con.numOfDomains())\n except libvirt.libvirtError:\n pass\n # warning(\"Error while working with libvirt: %s\" % e.message)\n return num_domains\n\n\nclass LibvirtConnection(base.Base):\n con = None\n\n def __init__(self, readonly=True):\n super(LibvirtConnection, self).__init__()\n self.connect(readonly)\n\n def connect(self, readonly):\n if readonly:\n self.con = libvirt.openReadOnly(None)\n else:\n raise Exception(\"Not supported\")\n\n def __enter__(self, *args, **kwargs):\n return self.con\n\n def __exit__(self, *args, **kwargs):\n self.con.close()\n","repo_name":"oVirt/ovirt-node","sub_path":"src/ovirt/node/utils/virt.py","file_name":"virt.py","file_ext":"py","file_size_in_byte":3507,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"32"}
+{"seq_id":"37055493035","text":"import os\nimport shutil\n\nPRE_BUILD_ROOT = '/home3/xieyunwei/ShapeNet.build.direct_remove/'\nDATASET_PATH = '/home2/xieyunwei/occupancy_networks/data/ShapeNet.update_lst/'\nOUTPUT_LST_ROOT = '/home2/xieyunwei/occupancy_networks/data/ShapeNet.update_lst.remove.intersect/'\n\nCLASSES = [\n '03001627',\n '02958343',\n '04256520',\n '02691156',\n '03636649',\n '04401088',\n '04530566',\n '03691459',\n '02933112',\n '04379243',\n '03211117',\n '02828884',\n '04090263',\n]\n\nSPLIT = ['train', 'val', 'test']\n\nif not os.path.exists(OUTPUT_LST_ROOT):\n os.mkdir(OUTPUT_LST_ROOT)\n\nfor c in CLASSES:\n onet_class_root = os.path.join(DATASET_PATH, c)\n output_class_root = os.path.join(OUTPUT_LST_ROOT, c)\n\n if not os.path.exists(output_class_root):\n os.mkdir(output_class_root)\n else:\n shutil.rmtree(output_class_root)\n os.mkdir(output_class_root)\n\n info = {}\n\n for sp in SPLIT:\n onet_lst = os.path.join(onet_class_root, '%s.lst' % sp)\n with open(onet_lst, 'r') as f:\n onet_lst_modelnames = f.readlines()\n\n onet_lst_modelnames = list(filter(lambda x: len(x) > 5, onet_lst_modelnames))\n onet_lst_modelnames = list(map(lambda x: x.strip(), onet_lst_modelnames))\n\n output_lst = os.path.join(output_class_root, '%s.lst' % sp)\n\n drop_count = 0\n insert_list = []\n with open(output_lst, 'w') as f:\n for modelname in onet_lst_modelnames:\n check_path = os.path.join(PRE_BUILD_ROOT, c, '4_pointcloud_direct', '%s.npz' % modelname)\n\n if os.path.exists(check_path):\n #f.write('%s\\n' % modelname)\n insert_list.append(modelname)\n else:\n #print('%s doesn\\'t exists' % check_path)\n drop_count += 1\n\n f.write('\\n'.join(insert_list))\n\n total_count = len(onet_lst_modelnames)\n remain_count = total_count - drop_count\n print('%s %s drop: %d/%d, remains: %d/%d' % (c, sp, drop_count, total_count, remain_count, total_count))\n\n info[sp] = drop_count / total_count\n\n print('Drop ratio train/val/test: %f/%f/%f' % (info['train'], info['val'], info['test']))","repo_name":"AlexsaseXie/occnet-depth","sub_path":"scripts/checking/rearrange_lst.py","file_name":"rearrange_lst.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"70149129372","text":"lista = []\r\nwhile True:\r\n n = int(input(f'Gostaria de colocar um numero na lista?\\nNumeros atuais >>{lista}<<\\nDigite aqui: '))\r\n lista.append(n)\r\n resp = str(input('Quer continuar? [S/N]'))\r\n if resp in 'Nn':\r\n break\r\n while resp not in 'SsNn':\r\n print('Tente novamente')\r\n resp = str(input('Quer continuar? [S/N]'))\r\nlista.sort(reverse=True)\r\nif 5 in lista:\r\n print(f'O numero 5 esta na lista, ele aparece pela primeira vez na posição {lista.index(5)+1}')\r\nelse:\r\n print(\"Não temos o numero 5 na lista :'( \")\r\nprint(lista)\r\nprint(f'Esta lista possui {len(lista)} numeros')","repo_name":"lcsllima/C-digos-em-Python---Kivy","sub_path":"ex081.py","file_name":"ex081.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"}
+{"seq_id":"29633301528","text":"# -*- coding: utf-8 -*-\n\nimport logging\nfrom launcher import app\n\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import QWidget\n\n\nclass MonitorWidget(QWidget):\n def __init__(self, parent = None):\n super().__init__(parent)\n self._isBeingDragged = False\n self._dragOffset = None\n self.setWindowFlags(Qt.FramelessWindowHint |\n Qt.ToolTip |\n Qt.WindowStaysOnTopHint)\n\n def mousePressEvent(self, qMouseEvent):\n if qMouseEvent.button() == Qt.LeftButton:\n self._isBeingDragged = True\n self._dragOffset = qMouseEvent.pos()\n\n def mouseMoveEvent(self, qMouseEvent):\n if self._isBeingDragged:\n self.move(qMouseEvent.globalPos() - self._dragOffset)\n\n def mouseReleaseEvent(self, qMouseEvent):\n if qMouseEvent.button() == Qt.LeftButton:\n self._isBeingDragged = False\n self._dragOffset = None\n\n def mouseDoubleClickEvent(self, qMouseEvent):\n app.mainWin.restore()\n","repo_name":"Xinkai/XwareDesktop","sub_path":"src/frontend/Widgets/MonitorWidget/MonitorWidget.py","file_name":"MonitorWidget.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","stars":907,"dataset":"github-code","pt":"32"}
+{"seq_id":"26414579430","text":"import re\nfrom dateutil.parser import parse\n\ndelimiter = \"(\\.| |-||/)\"\npatterns_list = [#14-digit delimited sequence in the following order (4-2-2 2:2:2.6)\n #The first two digit sequence is recognised automatically as a month\n \"\\d{4}\"+delimiter+\"\\d{2}\"+delimiter+\"\\d{2} (\\d\\d:){2}\\d{2}.\\d{6}\",\n #14-digit delimited sequence in the following order (2-2-4 2:2:2.6)\n #The first two digits are recognised automatically as a month\n \"\\d{2}\"+delimiter+\"\\d{2}\"+delimiter+\"\\d{4} (\\d\\d:){2}\\d{2}.\\d{6}\",\n #8-digit delimited (4-2-2) sequence\n \"\\d{4}\"+delimiter+\"\\d{2}\"+delimiter+\"\\d{2}\",\n #8-digit delimited (4-2-2) sequence\n \"\\d{2}\"+delimiter+\"\\d{2}\"+delimiter+\"\\d{4}\",\n ]\n\ndef extract_date_from_str(patterns_list, string):\n \"\"\"\n This function extracts a date from a string using a list of regex patterns\n For the patterns extracted from string look at the patterns_list variable\n For strings recognized as dates in the dateutil.parser module, take a look at https://stackabuse.com/converting-strings-to-datetime-in-python/\n :param patterns_list: list of regex date patterns\n :param string: str\n :return: datetime.date or False\n \"\"\"\n for pt in patterns_list:\n match = re.search(pt, string)\n if match:\n match = match[0]\n try:\n return parse(match)\n except:\n print(f\"String {match} was not recognised as date. Check date patterns\")\n return None","repo_name":"chrispcharlton/trufflepig","sub_path":"src/date_extraction.py","file_name":"date_extraction.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"32"}
+{"seq_id":"32971311767","text":"import json\n\nclass Books:\n def __init__(self):\n try:\n with open (\"books.json\", \"r\", encoding = \"UTF-8\") as f:\n self.library = json.load(f)\n except FileNotFoundError:\n self.library = []\n\n def all(self):\n return self.library\n\n def get(self,id):\n book = [book for book in self.all() if book['id'] == id]\n if book:\n return book[0]\n return []\n \n def create(self, data):\n self.library.append(data)\n self.save_all()\n\n def save_all(self):\n with open(\"books.json\", \"w\", encoding=\"UTF-8\")as f:\n json.dump(self.library, f, ensure_ascii=False)\n\n def delete(self, id):\n book = self.get(id)\n if book:\n self.library.remove(book)\n self.save_all()\n return True\n return False \n\n def update(self, id, data):\n book = self.get(id)\n if book:\n index = self.library.index(book)\n self.library[index] = data\n self.save_all()\n return True\n return False\n\nbooks = Books()","repo_name":"AgnieszkaNowotna/Home_library-1.0","sub_path":"API/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"73560975450","text":"# from flask import Flask, request\n# \n# app = Flask(__name__)\n\n\n# @app.route('/', methods=['POST'])\n# def result():\n # print(request.form['foo'])\n # ocr = ddddocr.DdddOcr(beta=True)\n # with open(\"https://lds.yphs.tp.edu.tw/tea/validatecode.aspx\", 'rb') as f:\n # image = f.read()\n # res = ocr.classification(image)\n # return res.upper() # response to your request.\n\nfrom http.server import BaseHTTPRequestHandler,HTTPServer\nimport ddddocr\nimport requests\nfrom urllib.parse import urlparse\nclass HandleRequests(BaseHTTPRequestHandler):\n def _set_headers(self):\n self.send_response(200)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n\n def do_GET(self):\n # try:\n self._set_headers()\n \n query = urlparse(self.path).query\n # query_components = dict(qc.split(\"=\") for qc in query.split(\"&\"))\n # cookie = query_components[\"cookie\"]\n print(query)\n ocr = ddddocr.DdddOcr(beta=True)\n response = requests.get(\"https://lds.yphs.tp.edu.tw/tea/validatecode.aspx\")\n res = ocr.classification(response.content)\n self.wfile.write(res.upper().encode())\n # except:\n # self._set_headers()\n # self.wfile.write(\"error\".encode())\nhttpd = HTTPServer(('localhost', 8080), HandleRequests)\nhttpd.serve_forever()","repo_name":"HippoInWindow20/YPValidate","sub_path":"api/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"2275049364","text":"import discord\r\nfrom discord.ext import commands\r\nimport random as randint\r\n\r\nclass moderation(commands.Cog):\r\n def __init__(self, client):\r\n self.client = client\r\n \r\n @commands.has_permissions(ban_members=True)\r\n @commands.guild_only()\r\n @commands.command()\r\n async def ban(self, ctx, user: discord.Member, *, reason=None):\r\n \"\"\"Bans the specified user. An optional reason can be specified.\"\"\"\r\n guild = ctx.guild\r\n if user in guild.users:\r\n embed=discord.Embed(color=0x80ffff)\r\n embed.add_field(name=\"You have been banned from {}\", value=guild.name)\r\n embed.add_field(name=\"**Reason**\", value=reason)\r\n await guild.ban(user, reason=reason)\r\n else:\r\n await ctx.send(\"User not found.\")\r\n\r\n @commands.has_permissions(kick_members=True)\r\n @commands.guild_only()\r\n @commands.command()\r\n async def kick(self, ctx, user: discord.Member, *, reason=None):\r\n \"\"\"Kicks the specified user. An optional reason can be specified.\"\"\"\r\n guild = ctx.guild\r\n if user in guild.members:\r\n guild.kick(user, reason=reason)\r\n\r\n @commands.has_permissions(manage_messages=True)\r\n @commands.command()\r\n async def purge(self, ctx, amount, channel: discord.TextChannel=None):\r\n \"\"\"Format: !purge amount #channel | Deletes the specified amount of messages from the channel. If an channel wasn't specified, the messages will be deleted from the current channel\"\"\"\r\n if channel == None:\r\n channel = ctx.channel\r\n deleted = await channel.purge(limit=int(amount))\r\n await ctx.send(\"{} messages deleted from {}.\".format(len(deleted), channel.mention), delete_after=20)\r\n else:\r\n deleted = await channel.purge(limit=int(amount))\r\n await ctx.send(\"{} messaged deleted.\".format(len(deleted)), delete_after=20)\r\n\r\n @commands.bot_has_permissions(manage_roles=True)\r\n @commands.has_permissions(manage_roles=True)\r\n @commands.command()\r\n async def role(self, ctx, user: discord.Member=None, *, role):\r\n \"\"\"Gives roles to the specified user. Adding a minus(-) before the role will remove the specified role from the user.\"\"\"\r\n guild = ctx.guild\r\n roles = guild.roles\r\n author = ctx.author\r\n if role == None:\r\n user = author\r\n pass\r\n if role.startswith(\"-\"):\r\n role = role.split(\"-\")[1]\r\n role = discord.utils.get(roles, name=role)\r\n await user.remove_roles(role)\r\n await ctx.send(\"{}-role removed from {}.\".format(role, user))\r\n else:\r\n role = discord.utils.get(roles, name=role)\r\n await user.add_roles(role)\r\n await ctx.send(\"{}-role added to {}\".format(role, user))\r\n await ctx.message.add_reaction(\"✅\")\r\n\r\n\r\ndef setup(client):\r\n client.add_cog(moderation(client))","repo_name":"timanttikuutio/Discord-Hackweek-bot","sub_path":"commands/moderation.py","file_name":"moderation.py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"23379516893","text":"from __future__ import (absolute_import, division, unicode_literals)\n\nfrom mantid.api import AnalysisDataService, WorkspaceFactory, WorkspaceGroup\nfrom mantid.kernel import FloatTimeSeriesProperty\nfrom mantid.py3compat import string_types\nimport numpy as np\n\nfrom Muon.GUI.Common.observer_pattern import GenericObserver\n\n# Constants\nDEFAULT_TABLE_NAME = 'ResultsTable'\nALLOWED_NON_TIME_SERIES_LOGS = (\"run_number\", \"run_start\", \"run_end\", \"group\",\n \"period\", \"sample_temp\", \"sample_magn_field\")\n# This is not a particularly robust way of ignoring this as it\n# depends on how Fit chooses to output the name of that value\nRESULTS_TABLE_COLUMNS_NO_ERRS = ['Cost function value']\n\n\nclass ResultsTabModel(object):\n \"\"\"Captures the data and operations\n for the results tab\"\"\"\n\n def __init__(self, fitting_context):\n \"\"\"\n Construct a model around the given FitContext object\n\n :param fitting_context: A FitContext detailing the outputs from the\n fitting\n \"\"\"\n self._fit_context = fitting_context\n self._results_table_name = DEFAULT_TABLE_NAME\n self._selected_fit_function = None\n\n self._update_selected_fit_function()\n self._new_fit_observer = GenericObserver(self._on_new_fit_performed)\n fitting_context.new_fit_notifier.add_subscriber(self._new_fit_observer)\n\n def results_table_name(self):\n \"\"\"Return the current name of the results table\"\"\"\n return self._results_table_name\n\n def set_results_table_name(self, name):\n \"\"\"Set the name of the output table\n\n :param name: A new name for the table\n \"\"\"\n self._results_table_name = name\n\n def selected_fit_function(self):\n \"\"\"Return the name of the selected fit function\"\"\"\n return self._selected_fit_function\n\n def set_selected_fit_function(self, name):\n \"\"\"Set the name of the selected fit_function\n\n :param name: The name of the selected function\n \"\"\"\n self._selected_fit_function = name\n\n def fit_functions(self):\n \"\"\"\n :return: The list of fit functions known to have been fitted\n \"\"\"\n return self._fit_context.fit_function_names()\n\n def fit_selection(self, existing_selection):\n \"\"\"\n Combine the existing selection state of workspaces with the workspace names\n of fits stored here. New workspaces are always checked for inclusion.\n :param existing_selection: A dict defining any current selection model. The\n format matches that of the ListSelectorPresenter class' model.\n :return: The workspaces that have had fits performed on them along with their selection status. The\n format matches that of the ListSelectorPresenter class' model.\n \"\"\"\n selection = {}\n for index, fit in enumerate(self._fit_context.fit_list):\n if fit.fit_function_name != self.selected_fit_function():\n continue\n name = _result_workspace_name(fit)\n if name in existing_selection:\n checked = existing_selection[name][1]\n else:\n checked = True\n selection[name] = [index, checked, True]\n\n return selection\n\n def log_selection(self, existing_selection):\n \"\"\"\n Combine the existing selection state of log values with the the set for the current\n workspace at the top of the list\n :param existing_selection: A dict defining any current selection model. The\n format matches that of the ListSelectorPresenter class' model.\n :return: The logs in the first workspace along with their selection status. The\n format matches that of the ListSelectorPresenter class' model.\n \"\"\"\n selection = {}\n fits = self._fit_context.fit_list\n if not fits:\n return selection\n\n logs = log_names(fits[0].input_workspace)\n for index, name in enumerate(logs):\n if name in existing_selection:\n checked = existing_selection[name][1]\n else:\n checked = False\n selection[name] = [index, checked, True]\n\n return selection\n\n # Ideally log_selection and model_selection would be part of this model but the ListSelectorPresenter\n # contains the model and it's not yet trivial to share that\n def create_results_table(self, log_selection, results_selection):\n \"\"\"Create a TableWorkspace with the fit results and logs combined. The format is\n a single row per workspace with columns:\n |workspace_name|selected_log_1|selected_log_2|...|param1_|param1_err|param2|param2_err|...|\n Any time-series log values are averaged.\n The workspace is added to the ADS with the name given by results_table_name\n\n :param log_selection: The current selection of logs as a list\n It is assumed this is ordered as it should be displayed. It can be empty.\n :param results_selection: The current selection of result workspaces as a list of 2-tuple\n [(workspace, fit_position),...]\n It is assumed this is not empty and ordered as it should be displayed.\n \"\"\"\n results_table = self._create_empty_results_table(\n log_selection, results_selection)\n fit_list = self._fit_context.fit_list\n for _, position in results_selection:\n fit = fit_list[position]\n row_dict = {'workspace_name': fit.parameter_name}\n # logs first\n if len(log_selection) > 0:\n workspace = _workspace_for_logs(fit.input_workspace)\n ws_run = workspace.run()\n for log_name in log_selection:\n try:\n log_value = ws_run.getPropertyAsSingleValue(log_name)\n except Exception:\n log_value = np.nan\n row_dict.update({log_name: log_value})\n # fit parameters\n parameter_dict = fit.parameter_workspace.workspace.toDict()\n for name, value, error in zip(parameter_dict['Name'],\n parameter_dict['Value'],\n parameter_dict['Error']):\n row_dict.update({name: value})\n if name not in RESULTS_TABLE_COLUMNS_NO_ERRS:\n row_dict.update({name + 'Error': error})\n\n try:\n results_table.addRow(row_dict)\n except ValueError:\n msg = \"Incompatible fits for results table:\\n\"\n msg += \" fit 1 and {} have a different parameters\".format(position + 1)\n raise RuntimeError(msg)\n\n AnalysisDataService.Instance().addOrReplace(self.results_table_name(),\n results_table)\n return results_table\n\n def _create_empty_results_table(self, log_selection, results_selection):\n \"\"\"\n Create an empty table workspace to store the results.\n :param log_selection: See create_results_table\n :param results_selection: See create_results_table\n :return: A new TableWorkspace\n \"\"\"\n table = WorkspaceFactory.Instance().createTable()\n table.addColumn('str', 'workspace_name')\n for log_name in log_selection:\n table.addColumn('float', log_name)\n # assume all fit functions are the same in fit_selection and take\n # the parameter names from the first fit.\n parameters = self._first_fit_parameters(results_selection)\n for name in parameters['Name']:\n table.addColumn('float', name)\n if name not in RESULTS_TABLE_COLUMNS_NO_ERRS:\n table.addColumn('float', name + 'Error')\n return table\n\n # Private API\n def _on_new_fit_performed(self):\n \"\"\"Called when a new fit has been added to the context.\n The function name is set to the name fit if it is the first time\"\"\"\n if self.selected_fit_function() is None:\n self._update_selected_fit_function()\n\n def _update_selected_fit_function(self):\n \"\"\"\n If there are fits present then set the selected function name or else\n clear it\n \"\"\"\n if len(self._fit_context) > 0:\n function_name = self._fit_context.fit_list[0].fit_function_name\n else:\n function_name = None\n\n self.set_selected_fit_function(function_name)\n\n def _first_fit_parameters(self, results_selection):\n \"\"\"\n Return the first fit in the selected list.\n\n :param results_selection: The list of selected results\n :return: The parameters of the first fit\n \"\"\"\n first_fit = self._fit_context.fit_list[results_selection[0][1]]\n return first_fit.parameter_workspace.workspace.toDict()\n\n\n# Public helper functions\ndef log_names(workspace_name):\n \"\"\"\n Return a list of log names from the given workspace.\n\n :param workspace: A string name of a workspace in the ADS. If the name points to\n a group then the logs of the first workspace are returned\n :return: A list of sample log names\n :raises KeyError: if the workspace does not exist in the ADS\n \"\"\"\n workspace = _workspace_for_logs(workspace_name)\n all_logs = workspace.run().getLogData()\n return [log.name for log in all_logs if _log_should_be_displayed(log)]\n\n\n# Private helper functions\ndef _workspace_for_logs(name_or_names):\n \"\"\"Return the workspace handle to be used to access the logs.\n We assume workspace_name is a string or a list of strings\n :param name_or_names: The name or list of names in the ADS\n \"\"\"\n if not isinstance(name_or_names, string_types):\n name_or_names = name_or_names[0]\n\n workspace = AnalysisDataService.retrieve(name_or_names)\n if isinstance(workspace, WorkspaceGroup):\n workspace = workspace[0]\n\n return workspace\n\n\ndef _log_should_be_displayed(log):\n \"\"\"Returns true if the given log should be included in the display\"\"\"\n return isinstance(log, FloatTimeSeriesProperty) or \\\n log.name in ALLOWED_NON_TIME_SERIES_LOGS\n\n\ndef _result_workspace_name(fit):\n \"\"\"\n Return the result workspace name for a given FitInformation object. The fit.input_workspace\n can be a list of workspaces or a single value. If a list is found then the\n first workspace is returned.\n :param fit: A FitInformation object describing the fit\n :return: A workspace name to be used in the fit results\n \"\"\"\n name_or_names = fit.input_workspace\n if isinstance(name_or_names, string_types):\n return name_or_names\n else:\n return _create_multi_domain_fitted_workspace_name(\n name_or_names, fit.fit_function_name)\n\n\ndef _create_multi_domain_fitted_workspace_name(input_workspaces, function):\n \"\"\"Construct a name for a result workspace from the input list and function\n\n :param input_workspaces: The list of input workspaces used for the fit\n :param function: The fit function name\n :return: A string result name\n \"\"\"\n return input_workspaces[0] + '+ ...; Fitted; ' + function\n","repo_name":"antonyvam/mantid","sub_path":"scripts/Muon/GUI/Common/results_tab_widget/results_tab_model.py","file_name":"results_tab_model.py","file_ext":"py","file_size_in_byte":11161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"32"}
+{"seq_id":"40227325837","text":"from pptx import Presentation\n\nppt = Presentation()\n\nslide = ppt.slides.add_slide(ppt.slide_layouts[10])\n\nfor shape in slide.shapes:\n print(type(shape), shape.shape_type, shape.is_placeholder)\n\nfor placeholder in slide.placeholders:\n print(placeholder.shape_type, placeholder.name)\n phf = placeholder.placeholder_format\n print(phf.idx, phf.type)","repo_name":"yasenstar/python_with_office","sub_path":"part2_Use-Python-in-Office/ch08_work-with-PPT/8-6_use-placeholders/8-6-2_8-6-3_retrieve-placeholder.py","file_name":"8-6-2_8-6-3_retrieve-placeholder.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"}
+{"seq_id":"35729032514","text":"# task: Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements\n# https://www.codewars.com/kata/54e6533c92449cc251001667/\ndef unique_in_order(iterable):\n result = [] # empty list for the result\n last = None #\n\n for item in iterable: # going over the array\n if item == last: # if the value is equal to the previous term\n continue #we do nothing\n else:\n #if current item is different then previous one\n result.append(item) # add the item into results\n last = item #and set previous item to current one\n\n return result\n\nnum = [1,2,2,3,3]\nprint(unique_in_order(num)) # should be [1,2,3]\naab = 'AAAABBBCCDAABBB'\nprint(unique_in_order(aab)) # should be ['A', 'B', 'C', 'D', 'A', 'B']\naab = 'AAAABBBCCDAABBB'\nab = 'ABBCcAD'\nprint(unique_in_order(ab)) # should be ['A', 'B', 'C', 'c', 'A', 'D']\n","repo_name":"ishanzo/weekly_programming","sub_path":"unique_in_order.py","file_name":"unique_in_order.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"18772924275","text":"from bs4 import BeautifulSoup, formatter\r\nimport os\r\n\r\ndef read_file_content(file_path):\r\n try:\r\n f = open(file_path, \"r\", encoding=\"latin-1\")\r\n content = f.read()\r\n f.close()\r\n except Exception as e:\r\n return False, \"Read file exception, \" + str(e)\r\n \r\n return True, content\r\n\r\ndef write_file(file_path, content):\r\n f = open(file_path, \"w\", encoding=\"latin-1\")\r\n f.write(content)\r\n f.close()\r\n return True, True\r\n\r\n","repo_name":"hopan/budsas","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"70298197211","text":"'''\n--------------------\nModule: debug_module\n--------------------\nDescription: \n - when some debugging info is required this module\n can be used to gather some run-time data.\n this module is simply 8 counters that get incremented\n when active signal is asserted.\n--------------------\nInput: \n - 8 activate signals.\n--------------------\nOutput:\n - 8 counters.\n--------------------\ntiming:\n - No need for time analysis for this module.\n--------------------\nNotes :\n - this module is optional and can only be\n used with axi lite module to access theses\n counters from PS.\n--------------------\n'''\n\nfrom nmigen import *\nfrom nmigen.cli import main\nfrom nmigen.back import *\nimport clk_domains\n\nclass DebugModule(Elaboratable):\n\n\tdef __init__(self):\n\n\t\tself.registers = Array(Signal(32) for _ in range(8))\n\t\tself.regs_en = Signal(8)\n\n\t\tself.ios = \\\n\t\t\t[reg for reg in self.registers] + \\\n\t\t\t[self.regs_en]\n\n\n\tdef elaborate(self, platform):\n\n\t\tm = Module()\n\n\t\tclk_domains.load_clk(m)\n\n\t\tfor i in range(8):\n\t\t\twith m.If(self.regs_en[i]):\n\t\t\t\tm.d.full += self.registers[i].eq(self.registers[i] + 1)\n\n\t\treturn m\n\n\nif __name__ == \"__main__\":\n\td = DebugModule()\n\tmain(d, ports=d.ios)","repo_name":"FaresMehanna/JPEG-1992-lossless-encoder-core","sub_path":"migen_src/debug_module.py","file_name":"debug_module.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"32"}
+{"seq_id":"13524667110","text":"import argparse\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom astropy import units as u\nfrom astropy.visualization import ImageNormalize, AsinhStretch, LinearStretch\nfrom iti.data.editor import LoadMapEditor, NormalizeRadiusEditor, AIAPrepEditor\nfrom sunpy.visualization.colormaps import cm\n\nfrom sunerf.utilities.reprojection import transform\n\nsdo_img_norm = ImageNormalize(vmin=0, vmax=1, stretch=LinearStretch(), clip=True)\n\n# !stretch is connected to NeRF!\nsdo_norms = {171: ImageNormalize(vmin=0, vmax=8600, stretch=AsinhStretch(0.005), clip=False),\n 193: ImageNormalize(vmin=0, vmax=9800, stretch=AsinhStretch(0.005), clip=False),\n 195: ImageNormalize(vmin=0, vmax=9800, stretch=AsinhStretch(0.005), clip=False),\n 211: ImageNormalize(vmin=0, vmax=5800, stretch=AsinhStretch(0.005), clip=False),\n 284: ImageNormalize(vmin=0, vmax=5800, stretch=AsinhStretch(0.005), clip=False),\n 304: ImageNormalize(vmin=0, vmax=8800, stretch=AsinhStretch(0.005), clip=False), }\n\npsi_norms = {171: ImageNormalize(vmin=0, vmax=22348.267578125, stretch=AsinhStretch(0.005), clip=True),\n 193: ImageNormalize(vmin=0, vmax=50000, stretch=AsinhStretch(0.005), clip=True),\n 211: ImageNormalize(vmin=0, vmax=13503.1240234375, stretch=AsinhStretch(0.005), clip=True), }\n\nso_norms = {304: ImageNormalize(vmin=0, vmax=300, stretch=AsinhStretch(0.005), clip=False),\n 174: ImageNormalize(vmin=0, vmax=300, stretch=AsinhStretch(0.005), clip=False)}\n\nsdo_cmaps = {171: cm.sdoaia171, 174: cm.sdoaia171, 193: cm.sdoaia193, 211: cm.sdoaia211, 304: cm.sdoaia304}\n\n\ndef loadAIAMap(file_path, resolution=1024, map_reproject=False):\n \"\"\"Load and preprocess AIA file to make them compatible to ITI.\n\n\n Parameters\n ----------\n file_path: path to the FTIS file.\n resolution: target resolution in pixels of 2.2 solar radii.\n map_reproject: apply preprocessing to remove off-limb (map to heliographic map and transform back to original view).\n\n Returns\n -------\n the preprocessed SunPy Map\n \"\"\"\n s_map, _ = LoadMapEditor().call(file_path)\n assert s_map.meta['QUALITY'] == 0, f'Invalid quality flag while loading AIA Map: {s_map.meta[\"QUALITY\"]}'\n s_map = NormalizeRadiusEditor(resolution).call(s_map)\n s_map = AIAPrepEditor(calibration='auto').call(s_map)\n if map_reproject:\n s_map = transform(s_map, lat=s_map.heliographic_latitude,\n lon=s_map.heliographic_longitude, distance=1 * u.AU)\n return s_map\n\n\ndef loadMap(file_path, resolution=1024, map_reproject=False):\n \"\"\"Load and resample a FITS file (no pre-processing).\n\n\n Parameters\n ----------\n file_path: path to the FTIS file.\n resolution: target resolution in pixels of 2.2 solar radii.\n map_reproject: apply preprocessing to remove off-limb (map to heliographic map and transform back to original view).\n\n Returns\n -------\n the preprocessed SunPy Map\n \"\"\"\n s_map, _ = LoadMapEditor().call(file_path)\n s_map = s_map.resample((resolution, resolution) * u.pix)\n if map_reproject:\n s_map = transform(s_map, lat=s_map.heliographic_latitude,\n lon=s_map.heliographic_longitude, distance=1 * u.AU)\n return s_map\n\n\ndef loadMapStack(file_paths, resolution=1024, remove_nans=True, map_reproject=False, aia_preprocessing=True):\n \"\"\"Load a stack of FITS files, resample ot specific resolution, and stackt hem.\n\n\n Parameters\n ----------\n file_paths: list of files to stack.\n resolution: target resolution in pixels of 2.2 solar radii.\n remove_off_limb: set all off-limb pixels to NaN (optional).\n\n Returns\n -------\n numpy array with AIA stack\n \"\"\"\n load_func = loadAIAMap if aia_preprocessing else loadMap\n s_maps = [load_func(file, resolution=resolution, map_reproject=map_reproject) for file in file_paths]\n stack = np.stack([sdo_norms[s_map.wavelength.value](s_map.data) for s_map in s_maps]).astype(np.float32)\n\n if remove_nans:\n stack[np.isnan(stack)] = 0\n stack[np.isinf(stack)] = 0\n\n return stack.data\n\n\ndef str2bool(v):\n \"\"\"converts string to boolean\n\n arguments\n ----------\n v: string\n string to convert to boolean\n\n Returns\n -------\n a boolean value based on the string placed\n \"\"\"\n if isinstance(v, bool):\n return v\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Boolean value expected.')\n\n\nif __name__ == '__main__':\n # test code\n o_map = loadAIAMap('/mnt/aia-jsoc/171/aia171_2010-05-13T00:00:07.fits')\n o_map.plot()\n plt.savefig('/home/robert_jarolim/results/original_map.jpg')\n plt.close()\n\n s_map = loadAIAMap('/mnt/aia-jsoc/171/aia171_2010-05-13T00:00:07.fits', map_reproject=True)\n s_map.plot(**o_map.plot_settings)\n plt.savefig('/home/robert_jarolim/results/projected_map.jpg')\n plt.close()\n","repo_name":"RobertJaro/SuNeRF","sub_path":"sunerf/data/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5080,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"}
+{"seq_id":"14616126534","text":"from utils import inputInt\nfrom utils import inputYN\n\nn = inputInt(\"n을 입력하시오: \")\nflag = inputYN(\"대상을 지정하시겠습니까? (y/n) \")\narray = list()\nif(flag == \"y\") :\n a = 0\n while(a > -1) :\n a = inputInt(\"대상 후보를 입력하시오(끝내려면 -1을 입력하시오): \")\n if(a != -1) :\n array.append(a)\nelse :\n a = 1\n while( a < 10):\n array.append(a)\n a = a + 1\nsumValue = inputInt(\"합계를 입력하시오: \")\n\nresult = list()\n\ndef getCombination(parent, count, target):\n temp = target.copy()\n while len(temp) :\n t = temp.pop()\n if count > 1 :\n tempParent = parent.copy()\n tempParent.append(t)\n getCombination(tempParent, count - 1, temp)\n else :\n tempParent = parent.copy()\n tempParent.append(t)\n if(sum(tempParent) == sumValue) :\n result.append(tempParent)\n\ngetCombination(list(), n, array)\n\nprint(\"*****result*****\")\nprint(result)","repo_name":"gzeromin/sumCombination","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"74027069211","text":"# n=int(input(\"enter number\"))\n# if n>0:\n# print(\"positive hai\")\n# elif n<0:\n# print(\"negative hai\")\n# elif n==0:\n# print(\"zero hai\")\n# else:\n# print(\"rest of the code\")\n\n\n\n\n\n\n\n# number=1\n# Number=int((number+(number+100)/2)*100)\n# if number<=100:\n# print(Number,\"sum of the number\")\n# else:\n# print(\"nothing\")\n\n\n\nnumber=1\nNumber=int((number+(number+10)/2)*10)/9\nif number<=10:\n print(Number,\"average of the number\")\nelse:\n print(\"nothing\")","repo_name":"Jayshri-Rathod/if_else","sub_path":"sum.py","file_name":"sum.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"7539158784","text":"import matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sys\nimport os\n\nsingle = False\n\nprefix = '../../cascading_generation_model/simulation/'\nsuffix = '.detail'\npath = '../../cascading_generation_model/722911_twolevel_neighbor_cascades/single_user_post/'\nusers = 7268\n\nts = 1321286400 #start timestamps\nte = 1322150400 #end timestamps\nmid = (ts + te) / 2\nte = mid\n\nnamelist = os.listdir(path)\npoints_post = {}\npoints = {}\nauthordic = {}\nrealdata = list()\nfor name in namelist:\n\tif single and name.startswith(str(filename) + '_'):\n\t\tfr = open(path+name, 'r')\n\t\trealdata = fr.readlines()\n\t\tfr.close()\n\t\tbreak\n\tif not single:\n\t\tfr = open(path+name, 'r')\n\t\trealdata.extend(fr.readlines())\n\t\tfr.close()\n\nn = len(realdata)\ni = 0\nwhile i < n:\n\ttemp = realdata[i].split('\\t')\n\tnumber = int(temp[1]) + 1\n\ttm = int(realdata[i+1].split('\\t')[2])\n\tif tm > mid:\n\t\ti += number\n\t\tcontinue\n\troot = temp[0]\n\troot_tweet = 0\n\tcasdic = {}\n\tfor j in range(i+1, i+number):\n\t\tinfo = realdata[j][:-1].split('\\t')\n\t\tif int(info[2]) > mid:\n\t\t\tcontinue\n\t\tauthordic[info[0]] = info[1]\n\t\tcasdic[info[0]] = 0\n\t\tif not info[3] == '-1':\n\t\t\t#if not casdic.has_key(info[3]):\n\t\t\t#\tcasdic[info[3]] = 1\n\t\t\t#else:\n\t\t\tif info[3] == root:\n\t\t\t\troot_tweet += 1\n\t\t\telse:\n\t\t\t\tcasdic[info[3]] += 1\n\tfor key in casdic:\n\t\tauthor = authordic[key]\n\t\tif not points.has_key(author):\n\t\t\tpoints[author] = {}\n\t\tif not points[author].has_key(casdic[key]):\n\t\t\tpoints[author][casdic[key]] = 1\n\t\telse:\n\t\t\tpoints[author][casdic[key]] += 1\n\tauthor = authordic[root]\n\tif not points_post.has_key(author):\n\t\tpoints_post[author] = {}\n\tif not points_post[author].has_key(root_tweet):\n\t\tpoints_post[author][root_tweet] = 1\n\telse:\n\t\tpoints_post[author][root_tweet] += 1\n\ti += number\n\nfw = open('../../cascading_generation_model/722911_twolevel_neighbor_cascades/PofK_5.detail', 'w')\nfor key in points:\n\tfw.write(key)\n\tnum = sorted(points[key].keys())\n\ts = sum(points[key].values())\n\tfor item in num:\n\t\tfw.write('\\t')\n\t\tfw.write(str(item))\n\t\tfw.write(':')\n\t\tfw.write(str(points[key][item] * 1.0 / s))\n\tfw.write('\\n')\nfw.close()\n\nfw = open('../../cascading_generation_model/722911_twolevel_neighbor_cascades/PofK_5_post.detail', 'w')\nfor key in points_post:\n\tfw.write(key)\n\tnum = sorted(points_post[key].keys())\n\ts = sum(points_post[key].values())\n\tfor item in num:\n\t\tfw.write('\\t')\n\t\tfw.write(str(item))\n\t\tfw.write(':')\n\t\tfw.write(str(points_post[key][item] * 1.0 / s))\n\tfw.write('\\n')\nfw.close()\n","repo_name":"december/ManlabSocialNetwork","sub_path":"getPofK.py","file_name":"getPofK.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"13719904614","text":"# -*- coding: utf-8 -*-\n# -*- Python Version: 2.7 -*-\n\n\"\"\"HBPH Heating Objects\"\"\"\n\nimport sys\n\ntry:\n from typing import Any, Optional, Sequence\nexcept ImportError:\n pass # IronPython 2.7\n\nfrom honeybee_energy_ph.hvac import _base, fuels\n\n\nclass UnknownPhHeatingTypeError(Exception):\n def __init__(self, _heater_types, _received_type):\n # type: (list[str], str) -> None\n self.msg = 'Error: Unknown HBPH-Heating-SubSystem type? Got: \"{}\" but only types: {} are allowed?'.format(\n _received_type, _heater_types\n )\n super(UnknownPhHeatingTypeError, self).__init__(self.msg)\n\n\nclass PhHeatingSystem(_base._PhHVACBase):\n \"\"\"Base class for all PH-Heating Systems (elec, boiler, etc...)\"\"\"\n\n def __init__(self):\n super(PhHeatingSystem, self).__init__()\n self.heating_type = self.__class__.__name__\n self.percent_coverage = 1.0\n\n def to_dict(self):\n # type: () -> dict\n d = super(PhHeatingSystem, self).to_dict()\n d[\"heating_type\"] = self.heating_type\n d[\"percent_coverage\"] = self.percent_coverage\n return d\n\n def base_attrs_from_dict(self, _input_dict):\n # type: (PhHeatingSystem, dict) -> PhHeatingSystem\n self.identifier = _input_dict[\"identifier\"]\n self.display_name = _input_dict[\"display_name\"]\n self.user_data = _input_dict[\"user_data\"]\n self.heating_type = _input_dict[\"heating_type\"]\n self.percent_coverage = _input_dict[\"percent_coverage\"]\n return self\n\n def check_dict_type(self, _input_dict):\n # type: (dict) -> None\n \"\"\"Check that the input dict type is correct for the Heating System being constructed.\"\"\"\n heating_type = _input_dict[\"heating_type\"]\n msg = (\n \"Error creating Heating System from dict. Expected '{}' but got '{}'\".format(\n self.__class__.__name__, heating_type\n )\n )\n assert heating_type == str(self.__class__.__name__), msg\n return None\n\n @classmethod\n def from_dict(cls, _input_dict):\n raise NotImplementedError(\"Error: from_dict() called on BaseClass.\")\n\n def __lt__(self, other):\n # type: (PhHeatingSystem) -> bool\n return self.identifier < other.identifier\n\n\n# -----------------------------------------------------------------------------\n# Heating Types\n\n\nclass PhHeatingDirectElectric(PhHeatingSystem):\n \"\"\"Heating via direct-electric (resistance heating).\"\"\"\n\n def __init__(self):\n super(PhHeatingDirectElectric, self).__init__()\n\n def to_dict(self):\n # type: () -> dict[str, Any]\n d = super(PhHeatingDirectElectric, self).to_dict()\n return d\n\n @classmethod\n def from_dict(cls, _input_dict):\n # type: (dict[str, Any]) -> PhHeatingDirectElectric\n new_obj = cls()\n new_obj.check_dict_type(_input_dict)\n new_obj.base_attrs_from_dict(_input_dict)\n return new_obj\n\n\nclass PhHeatingFossilBoiler(PhHeatingSystem):\n \"\"\"Heating via boiler using fossil-fuel (gas, oil)\"\"\"\n\n def __init__(self):\n super(PhHeatingFossilBoiler, self).__init__()\n self.fuel = fuels.NATURAL_GAS\n self.condensing = True\n self.in_conditioned_space = True\n self.effic_at_30_percent_load = 0.98\n self.effic_at_nominal_load = 0.94\n self.avg_rtrn_temp_at_30_percent_load = 30\n self.avg_temp_at_70C_55C = 41\n self.avg_temp_at_55C_45C = 35\n self.avg_temp_at_32C_28C = 24\n\n def to_dict(self):\n # type: () -> dict[str, Any]\n d = super(PhHeatingFossilBoiler, self).to_dict()\n\n d[\"fuel\"] = self.fuel\n d[\"condensing\"] = self.condensing\n d[\"in_conditioned_space\"] = self.in_conditioned_space\n d[\"effic_at_30_percent_load\"] = self.effic_at_30_percent_load\n d[\"effic_at_nominal_load\"] = self.effic_at_nominal_load\n d[\"avg_rtrn_temp_at_30_percent_load\"] = self.avg_rtrn_temp_at_30_percent_load\n d[\"avg_temp_at_70C_55C\"] = self.avg_temp_at_70C_55C\n d[\"avg_temp_at_55C_45C\"] = self.avg_temp_at_55C_45C\n d[\"avg_temp_at_32C_28C\"] = self.avg_temp_at_32C_28C\n\n return d\n\n @classmethod\n def from_dict(cls, _input_dict):\n # type: (dict[str, Any]) -> PhHeatingFossilBoiler\n new_obj = cls()\n new_obj.check_dict_type(_input_dict)\n new_obj.base_attrs_from_dict(_input_dict)\n\n new_obj.fuel = _input_dict[\"fuel\"]\n new_obj.condensing = _input_dict[\"condensing\"]\n new_obj.in_conditioned_space = _input_dict[\"in_conditioned_space\"]\n new_obj.effic_at_30_percent_load = _input_dict[\"effic_at_30_percent_load\"]\n new_obj.effic_at_nominal_load = _input_dict[\"effic_at_nominal_load\"]\n new_obj.avg_rtrn_temp_at_30_percent_load = _input_dict[\n \"avg_rtrn_temp_at_30_percent_load\"\n ]\n new_obj.avg_temp_at_70C_55C = _input_dict[\"avg_temp_at_70C_55C\"]\n new_obj.avg_temp_at_55C_45C = _input_dict[\"avg_temp_at_55C_45C\"]\n new_obj.avg_temp_at_32C_28C = _input_dict[\"avg_temp_at_32C_28C\"]\n\n return new_obj\n\n\nclass PhHeatingWoodBoiler(PhHeatingSystem):\n \"\"\"Heating via boiler using wood (log, pellet).\"\"\"\n\n def __init__(self):\n super(PhHeatingWoodBoiler, self).__init__()\n self.fuel = fuels.WOOD_LOG\n self.in_conditioned_space = True\n self.effic_in_basic_cycle = 0.6\n self.effic_in_const_operation = 0.7\n self.avg_frac_heat_output = 0.4\n self.temp_diff_on_off = 30\n self.rated_capacity = 15 # kW\n self.demand_basic_cycle = 1 # kWh\n self.power_stationary_run = 1 # W\n self.power_standard_run = None # type: Optional[float]\n self.no_transport_pellets = None # type: Optional[bool]\n self.only_control = None # type: Optional[bool]\n self.area_mech_room = None # type: Optional[float]\n\n @property\n def useful_heat_output(self):\n return 0.9 * self.rated_capacity # kWH\n\n @property\n def avg_power_output(self):\n return 0.5 * self.rated_capacity # kW\n\n def to_dict(self):\n # type: () -> dict\n d = super(PhHeatingWoodBoiler, self).to_dict()\n\n d[\"fuel\"] = self.fuel\n d[\"in_conditioned_space\"] = self.in_conditioned_space\n d[\"effic_in_basic_cycle\"] = self.effic_in_basic_cycle\n d[\"effic_in_const_operation\"] = self.effic_in_const_operation\n d[\"avg_frac_heat_output\"] = self.avg_frac_heat_output\n d[\"temp_diff_on_off\"] = self.temp_diff_on_off\n d[\"rated_capacity\"] = self.rated_capacity\n d[\"demand_basic_cycle\"] = self.demand_basic_cycle\n d[\"power_stationary_run\"] = self.power_stationary_run\n d[\"power_standard_run\"] = self.power_standard_run\n d[\"no_transport_pellets\"] = self.no_transport_pellets\n d[\"only_control\"] = self.only_control\n d[\"area_mech_room\"] = self.area_mech_room\n\n return d\n\n @classmethod\n def from_dict(cls, _input_dict):\n # type: (dict) -> PhHeatingWoodBoiler\n\n new_obj = cls()\n new_obj.check_dict_type(_input_dict)\n new_obj.base_attrs_from_dict(_input_dict)\n\n new_obj.fuel = _input_dict[\"fuel\"]\n new_obj.in_conditioned_space = _input_dict[\"in_conditioned_space\"]\n new_obj.effic_in_basic_cycle = _input_dict[\"effic_in_basic_cycle\"]\n new_obj.effic_in_const_operation = _input_dict[\"effic_in_const_operation\"]\n new_obj.avg_frac_heat_output = _input_dict[\"avg_frac_heat_output\"]\n new_obj.temp_diff_on_off = _input_dict[\"temp_diff_on_off\"]\n new_obj.rated_capacity = _input_dict[\"rated_capacity\"]\n new_obj.demand_basic_cycle = _input_dict[\"demand_basic_cycle\"]\n new_obj.power_stationary_run = _input_dict[\"power_stationary_run\"]\n new_obj.no_transport_pellets = _input_dict[\"no_transport_pellets\"]\n new_obj.only_control = _input_dict[\"only_control\"]\n new_obj.area_mech_room = _input_dict[\"area_mech_room\"]\n\n return new_obj\n\n\nclass PhHeatingDistrict(PhHeatingSystem):\n \"\"\"Heating via district-heat.\"\"\"\n\n def __init__(self):\n super(PhHeatingDistrict, self).__init__()\n self.fuel = fuels.GAS_CGS_70_PHC\n self.util_factor_of_heat_transfer_station = 0.5\n\n def to_dict(self):\n # type: () -> dict\n d = super(PhHeatingDistrict, self).to_dict()\n d[\"fuel\"] = self.fuel\n d[\n \"util_factor_of_heat_transfer_station\"\n ] = self.util_factor_of_heat_transfer_station\n return d\n\n @classmethod\n def from_dict(cls, _input_dict):\n # type: (dict) -> PhHeatingDistrict\n new_obj = cls()\n new_obj.check_dict_type(_input_dict)\n new_obj.base_attrs_from_dict(_input_dict)\n\n new_obj.fuel = _input_dict[\"fuel\"]\n new_obj.util_factor_of_heat_transfer_station = _input_dict[\n \"util_factor_of_heat_transfer_station\"\n ]\n return new_obj\n\n\nclass PhHeatingHeatPumpAnnual(PhHeatingSystem):\n def __init__(self):\n super(PhHeatingHeatPumpAnnual, self).__init__()\n self.annual_COP = 2.5\n self.total_system_perf_ratio = 0.4\n\n def to_dict(self):\n # type: () -> dict\n d = super(PhHeatingHeatPumpAnnual, self).to_dict()\n d[\"annual_COP\"] = self.annual_COP\n d[\"total_system_perf_ratio\"] = self.total_system_perf_ratio\n return d\n\n @classmethod\n def from_dict(cls, _input_dict):\n # type: (dict) -> PhHeatingHeatPumpAnnual\n new_obj = cls()\n new_obj.check_dict_type(_input_dict)\n new_obj.base_attrs_from_dict(_input_dict)\n\n new_obj.annual_COP = _input_dict[\"annual_COP\"]\n new_obj.total_system_perf_ratio = _input_dict[\"total_system_perf_ratio\"]\n return new_obj\n\n\nclass PhHeatingHeatPumpRatedMonthly(PhHeatingSystem):\n \"\"\"Heating via electric heat-pump.\"\"\"\n\n def __init__(self):\n super(PhHeatingHeatPumpRatedMonthly, self).__init__()\n self.COP_1 = 2.5\n self.ambient_temp_1 = -8.333 # =17F\n self.COP_2 = 2.5\n self.ambient_temp_2 = 8.333 # =47F\n\n @property\n def monthly_COPS(self):\n return [self.COP_1, self.COP_2]\n\n @monthly_COPS.setter\n def monthly_COPS(self, _cops):\n # type: (Sequence[float]) -> None\n self.COP_1 = _cops[0]\n try:\n self.COP_2 = _cops[1]\n except IndexError:\n self.COP_2 = _cops[0]\n return\n\n @property\n def monthly_temps(self):\n return [self.ambient_temp_1, self.ambient_temp_2]\n\n @monthly_temps.setter\n def monthly_temps(self, _cops):\n # type: (Sequence[float]) -> None\n self.ambient_temp_1 = _cops[0]\n try:\n self.ambient_temp_2 = _cops[1]\n except IndexError:\n self.ambient_temp_2 = _cops[0]\n return\n\n def to_dict(self):\n # type: () -> dict[str, Any]\n d = super(PhHeatingHeatPumpRatedMonthly, self).to_dict()\n d[\"COP_1\"] = self.COP_1\n d[\"ambient_temp_1\"] = self.ambient_temp_1\n d[\"COP_2\"] = self.COP_2\n d[\"ambient_temp_2\"] = self.ambient_temp_2\n return d\n\n @classmethod\n def from_dict(cls, _input_dict):\n # type: (dict[str, Any]) -> PhHeatingHeatPumpRatedMonthly\n new_obj = cls()\n new_obj.check_dict_type(_input_dict)\n new_obj.base_attrs_from_dict(_input_dict)\n\n new_obj.COP_1 = _input_dict[\"COP_1\"]\n new_obj.ambient_temp_1 = _input_dict[\"ambient_temp_1\"]\n new_obj.COP_2 = _input_dict[\"COP_2\"]\n new_obj.ambient_temp_2 = _input_dict[\"ambient_temp_2\"]\n return new_obj\n\n\nclass PhHeatingHeatPumpCombined(PhHeatingSystem):\n def __init__(self):\n raise NotImplementedError()\n\n\n# -----------------------------------------------------------------------------\n\n\nclass PhHeatingSystemBuilder(object):\n \"\"\"Constructor class for PH-HeatingSystems\"\"\"\n\n @classmethod\n def from_dict(cls, _input_dict):\n # type: (dict[str, Any]) -> PhHeatingSystem\n \"\"\"Find the right appliance constructor class from the module based on the 'type' name.\"\"\"\n valid_class_types = [\n nm for nm in dir(sys.modules[__name__]) if nm.startswith(\"Ph\")\n ]\n\n heating_type = _input_dict[\"heating_type\"]\n if heating_type not in valid_class_types:\n raise UnknownPhHeatingTypeError(valid_class_types, heating_type)\n heating_class = getattr(sys.modules[__name__], heating_type)\n new_equipment = heating_class.from_dict(_input_dict)\n return new_equipment\n\n def __str__(self):\n return \"{}()\".format(self.__class__.__name__)\n\n def __repr__(self):\n return str(self)\n\n def ToString(self):\n return str(self)\n","repo_name":"PH-Tools/honeybee_ph","sub_path":"honeybee_energy_ph/hvac/heating.py","file_name":"heating.py","file_ext":"py","file_size_in_byte":12712,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"32"}
+{"seq_id":"2108691696","text":"from django.shortcuts import redirect\nfrom django.urls import path\nfrom . import views\n\napp_name = 'quiz'\nurlpatterns = [\n path('', lambda req: redirect('/home/')),\n path('home/', views.QuizListView.as_view(), name='quiz_list'),\n path('/', views.QuizDetailView.as_view(), name='quiz_detail'),\n path('first//', views.QuestionDetailView.as_view(), name='question_detail'),\n path('//', views.QuestionNextDetailView.as_view(), name='next_question_detail'),\n path('/results/', views.QuestionNextDetailView.as_view(), name='next_question_detail'),\n]\n","repo_name":"DmitriyBul/Quiz","sub_path":"quiz/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"31328515497","text":"#https://leetcode.com/problems/combination-sum/\n\ndef solve(dp, li, n, s):\n if(s==0):\n dp[n][s] = 1\n return 1\n if(n==0):\n dp[n][s] = 0\n return 0\n if(dp[n][s]!=-1):\n return dp[n][s]\n if(li[n-1]>s):\n dp[n][s] = solve(dp, li, n-1, s)\n return dp[n][s]\n else:\n dp[n][s] = solve(dp, li, n, s-li[n-1]) + solve(dp, li, n-1, s)\n return dp[n][s]\n\ndef pr(dp, li, n, s, sol, tmp):\n if(s==0):\n sol.append(tmp)\n return \n if(n<=0):\n return \n if(li[n-1]>s):\n pr(dp, li, n-1, s, sol, tmp)\n else:\n if(dp[n][s-li[n-1]]>0):\n pr(dp, li, n, s-li[n-1], sol, tmp+[li[n-1]])\n if(n>0 and dp[n-1][s]>0):\n pr(dp, li, n-1, s, sol, tmp)\n\n\nclass Solution:\n def combinationSum(self, li, t):\n n = len(li)\n dp = [[-1 for j in range(t+1)]for i in range(n+1)]\n ans = solve(dp, li, n, t)\n #print(ans)\n sol = []\n tmp =[]\n pr(dp, li, n, t, sol, tmp)\n return sol\n\n\nif __name__==\"__main__\":\n c = Solution()\n li = [2,3,5]\n t = 8\n ans = c.combinationSum(li,t)\n print(ans)\n \n \n \n \n \n ","repo_name":"Ritapravo/cpp","sub_path":"random/py/17.combination_sum.py","file_name":"17.combination_sum.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"32"}
+{"seq_id":"20718859419","text":"import tensorflow as tf\n\n# ======建立模型(開始)======\n\n# 建立權重張量的函數\ndef weight(shape):\n return tf.Variable(tf.truncated_normal(shape, stddev=0.1), name='W')\n\n# 建立偏差張量的函數\ndef bias(shape):\n return tf.Variable(tf.constant(0.1, shape=shape), name='b')\n\n# 建立卷積層的函數\ndef conv2d(x, W):\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n\n# 建立池化層的函數\ndef max_pool_2x2(x):\n return tf.nn.max_pool(x, strides=[1, 2, 2, 1], ksize=[1, 2, 2, 1], padding='SAME')\n\n\n# inference 是推論的意思\ndef inference(images, batchSize, nClasses):\n # 建立輸入層\n # x_input = tf.placeholder(shape=[None, 160, 160, 3], dtype=tf.float32, name='x')\n\n # 建立卷積層 1\n W1 = weight([4, 4, 3, 30])\n b1 = bias([30])\n C1_Conv = tf.nn.relu(conv2d(images, W1) + b1)\n\n # 建立池化層 1\n C1_Pool = max_pool_2x2(C1_Conv)\n\n # 建立卷積層 2\n W2 = weight([4, 4, 30, 60])\n b2 = bias([60])\n C2_Conv = tf.nn.relu(conv2d(C1_Pool, W2) + b2)\n\n # 建立池化層 2\n C2_Pool = max_pool_2x2(C2_Conv)\n\n # 建立卷積層 3\n W3 = weight([4, 4, 60, 90])\n b3 = bias([90])\n C3_Conv = tf.nn.relu(conv2d(C2_Pool, W3) + b3)\n\n # 建立池化層 3\n C3_Pool = max_pool_2x2(C3_Conv)\n\n # 建立卷積層 4\n W4 = weight([4, 4, 90, 120])\n b4 = bias([120])\n C4_Conv = tf.nn.relu(conv2d(C3_Pool, W4) + b4)\n\n # 建立池化層 4\n C4_Pool = max_pool_2x2(C4_Conv)\n\n # 建立平坦層\n D_Flat = tf.reshape(C4_Pool, shape=[batchSize, -1])\n dim = D_Flat.shape[1].value\n\n # 建立隱藏層 1\n W5 = weight([dim, 300])\n b5 = bias([300])\n D_Hidden1 = tf.nn.relu(tf.matmul(D_Flat, W5) + b5)\n D_Hidden1_Dropout = tf.nn.dropout(D_Hidden1, keep_prob=1)\n\n # 建立隱藏層 2\n W6 = weight([300, 250])\n b6 = bias([250])\n D_Hidden2 = tf.nn.relu(tf.matmul(D_Hidden1_Dropout, W6) + b6)\n D_Hidden2_Dropout = tf.nn.dropout(D_Hidden2, keep_prob=1)\n\n # 建立輸出層\n W7 = weight([250, nClasses])\n b7 = bias([nClasses])\n y_predict = tf.add(tf.matmul(D_Hidden2_Dropout, W7), b7, name='y_output')\n\n return y_predict\n\n# ======建立模型(結束)======\n\n\n\n# ======定義誤差函數(開始)======\ndef losses(y_predict, y_label):\n loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y_predict, labels=y_label))\n return loss\n# ======定義誤差函數(結束)======\n\n\n\n# ========定義訓練方式(開始)========\ndef trainning(loss, learning_rate):\n # 定義優化方法\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)\n return optimizer\n# ========定義訓練方式(結束)========\n\n\n\n# ========定義評估模型準確率的方法(開始)========\ndef evaluation(y_predict, y_label):\n # 拿預測結果和標籤做比較,計算是否判斷正確\n correct_prediction = tf.equal(tf.arg_max(y_predict, 1),\n tf.arg_max(y_label, 1))\n\n # 計算預測正確結果的平均,計算預測準確率\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, dtype=tf.float32))\n return accuracy\n# ========定義評估模型準確率的方法(結束)========","repo_name":"Wecan-Huang0602/Emotion_Chatbot","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"}
+{"seq_id":"29966557557","text":"\ndef legalbacklog(cases, m):\n lst = sorted(v for k, v in cases.items())\n len_lst = len(lst)\n days = 0\n while sum(lst) > 0:\n for idx in range(len_lst - 1, max(len_lst - m - 1, -1), -1):\n if lst[idx]:\n lst[idx] -= 1\n lst.sort()\n days += 1\n return days\n\n","repo_name":"daniel-reich/ubiquitous-fiesta","sub_path":"XmQjSjbsfLg3y33ES_4.py","file_name":"XmQjSjbsfLg3y33ES_4.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"73129913052","text":"class Solution():\n def __init__(self, test=False) -> None:\n self.test = test\n self.filename = \"testinput.txt\" if self.test else \"input.txt\"\n self.data = open(self.filename).read()\n self.directions = {\"<\": (-1, 0), \"^\": (0, 1), \">\": (1, 0), \"v\": (0, -1)}\n \n def part1(self):\n x, y = 0, 0\n visited = set()\n visited.add((x, y))\n for c in self.data:\n x += self.directions[c][0]\n y += self.directions[c][1]\n visited.add((x, y))\n return len(visited)\n \n def part2(self):\n x1, y1 = 0, 0\n x2, y2 = 0, 0\n visited = set()\n visited.add((0, 0))\n for i in range(len(self.data)):\n c = self.data[i]\n if i % 2 == 0:\n x1 += self.directions[c][0]\n y1 += self.directions[c][1]\n visited.add((x1, y1))\n else:\n x2 += self.directions[c][0]\n y2 += self.directions[c][1]\n visited.add((x2, y2)) \n return len(visited)\n \n \ndef main():\n s = Solution(test=True)\n print(\"---TEST---\")\n print(f\"part 1: {s.part1()}\")\n print(f\"part 2: {s.part2()}\\n\")\n \n s = Solution()\n print(\"---MAIN---\")\n print(f\"part 1: {s.part1()}\")\n print(f\"part 2: {s.part2()}\")\n \nmain()","repo_name":"martinhova01/advent-of-code","sub_path":"15/03/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"44220082170","text":"# Based on 01_Main_Menu_v4.py\n# This is the first version of the Help GUI. It has the addition of a command\n# to the help button which will open the Help GUI in the next version.\n# Lines (70-78)\nfrom tkinter import *\nimport random\nfrom tkinter.ttk import Separator\n\n\nclass Menu:\n def __init__(self):\n # Formatting variables of the GUI\n background_color = \"#89B4E5\"\n\n # Main Menu GUI\n self.main_menu_frame = Frame(width=375, height=300,\n bg=background_color)\n self.main_menu_frame.grid()\n\n # Main Menu heading (row 0)\n self.main_menu_label = Label(self.main_menu_frame,\n text=\"Main Menu\", font=\"Arial 18 bold\",\n bg=background_color, padx=10, pady=10)\n self.main_menu_label.grid(row=0)\n\n # Get name label (row 1)\n self.get_name_label = Label(self.main_menu_frame,\n text=\"Enter your name and press one of \"\n \"the buttons below\",\n font=\"Arial 10 italic\", wrap=250, pady=10,\n bg=background_color)\n self.get_name_label.grid(row=1)\n\n # Name entry box (row 2)\n self.get_name_entry = Entry(self.main_menu_frame, width=17,\n font=\"Arial 12\")\n self.get_name_entry.grid(row=2)\n\n # Buttons Frame\n self.buttons_frame = Frame(self.main_menu_frame, pady=10, padx=10,\n width=200, bg=background_color)\n self.buttons_frame.grid(row=3)\n # Countries button (column 0) shows a button to open countries mode\n self.countries_button = Button(self.buttons_frame, text=\"Countries\",\n font=\"Arial 14 bold\", width=10,\n bg=\"blue\", fg=\"snow\")\n self.countries_button.grid(row=0, column=0, padx=5, pady=10)\n\n # Capitals button (column 1) shows a button to open capitals mode\n self.capitals_button = Button(self.buttons_frame, text=\"Capitals\",\n font=\"Arial 14 bold\", width=10,\n bg=\"forest green\",\n fg=\"snow\")\n self.capitals_button.grid(row=0, column=1, padx=5, pady=10)\n\n # Separator (row 1) should produce a line inside the buttons frame\n # that separates the top 2 buttons from the bottom 2\n self.frame_separator = Separator(self.buttons_frame,\n orient=\"horizontal\")\n self.frame_separator.grid(row=1, sticky=\"ew\", columnspan=2)\n\n # History button (row 2, column 0) shows a button on the GUI to go to history\n self.history_button = Button(self.buttons_frame,\n text=\"Answer Record History\", wrap=150,\n font=\"Arial 12 bold\", bg=\"light grey\",\n width=12)\n self.history_button.grid(row=2, column=0, padx=5, pady=10)\n\n # Help Button (row 2, column 1) shows a button to open help window\n self.help_button = Button(self.buttons_frame, text=\"Help\", width=12,\n font=\"Arial 12 bold\", bg=\"light grey\",\n height=2, command=self.help)\n self.help_button.grid(row=2, column=1, padx=5, pady=10)\n\n def help(self):\n print(\"You asked for help\")\n get_help = Help()\n get_help.help_text.configure(text=\"Help text goes here\")\n\n\n# main routine\nif __name__ == \"__main__\":\n root = Tk()\n root.title(\"Geographical Quiz Game\")\n something = Menu()\n root.mainloop()\n","repo_name":"NathanM3/Quiz-Program","sub_path":"02_Help_GUI_v1.py","file_name":"02_Help_GUI_v1.py","file_ext":"py","file_size_in_byte":3791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"74433275931","text":"import pandas as pd \nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport sys\n\ndef cleanCSV(df):\n arr_col = []\n for col in df.columns:\n if df[col].isna().all():\n print(\"Column\", col, \"contains only NaN values.\")\n arr_col.append(col)\n df_cleaned = df.drop(columns=arr_col)\n df_cleaned = df_cleaned.replace('---', 0)\n return df_cleaned\n\ndef sortDf(df):\n if 'TIMESTAMP' in df.columns:\n df = df.sort_values('TIMESTAMP',ascending=True)\n df.index = range(len(df))\n else:\n print(\"Column TIMESTAMP is not in the dataframe.\")\n return None\n return df\n\ndef resampleDf(df,datetime):\n if 'dt' in df.columns:\n df.set_index('dt', inplace=True)\n df_noNan = df.ffill()\n df_resampled = df_noNan.resample(datetime).ffill()\n df_resampled = df_resampled.replace('---', 0)\n return df_resampled\n \ndef checkFileInFolder(folder, file):\n if file in os.listdir(folder):\n return True\n return False\n\ndef getUniques(df):\n cols = df.columns\n dict_unique = dict.fromkeys(cols,None)\n for col in cols:\n dict_unique[col] = df[col].unique()\n return dict_unique\n\ndef getBooelan(dict):\n arr = []\n for key, value in dict.items():\n if len(value) < 4:\n b = True\n for v in value:\n # print(v,pd.isna(v))\n if pd.isna(v)==False:\n if int(v) != 0 and int(v) != 1:\n # print('ciao')\n b = False\n break\n # print(value,b)\n if b:\n arr.append(key)\n return arr\n\ndef printUniques(dict,tp):\n booleans = getBooelan(dict)\n for key, value in dict.items():\n counts = []\n if key in booleans and tp ==1:\n print(key, value)\n elif tp==2 and len(value) > 4 :\n print(key, value[0:5])\n\ndef countOccurences(df,dict):\n booleans = getBooelan(dict)\n counters = dict.fromkeys(booleans,None)\n for key, value in dict.items():\n if key in booleans:\n value = value[1:]\n counts = dict.fromkeys(value,None)\n for v in value:\n if not pd.isna(v):\n counts[v]= df[key].value_counts()[v]\n counters[key] = counts\n # print(key, counts, max(counts))\n return counters\n \ndef getMax(dict):\n maxs = dict.fromkeys(dict.keys(),None)\n for key, value in dict.items():\n # print(key, value)\n for k, v in value.items():\n if v == max(value.values()):\n maxs[key] = k\n return maxs\n\ndef plotColumn(df,col):\n if col not in df.columns:\n print(\"Column\", col, \"is not in the dataframe.\")\n return None\n df_toPlot = df[col]\n plt.plot(df_toPlot)\n try: \n plt.ylim(0, max(df_toPlot.unique())+1)\n except:\n pass\n\n plt.show()\n\ndef reversedMax(dizionario):\n for key, value in dizionario.items():\n if value == 1:\n dizionario[key] = 0\n else:\n dizionario[key] = 1\n return dizionario\n\ndef getGeneralBooleans(df1,df2,df3):\n b1 = getBooelan(getUniques(df1))\n b2 = getBooelan(getUniques(df2))\n b3 = getBooelan(getUniques(df3))\n intersection = list(set(b1) & set(b2) & set(b3))\n intersection.sort()\n return intersection\n\ndef fillBooleans(df,booleans,dizionario):\n for key in booleans:\n if key != 'Modalità Estate/Inverno (solo scrittura)' and key in dizionario.keys():\n # print(f'{key}: {dizionario[key]}') \n df[key] = df[key].replace(np.nan,dizionario[key])\n return df\n\ndef fillOthers(df,sample):\n col_s = sample.index\n booleani = getBooelan(getUniques(df))\n for col in df.columns:\n # print(col)\n if col == 'Anomalia #1':\n df[col] = df[col].replace(np.nan,sample[col])\n if col not in booleani and col in col_s:\n # print('in')\n df[col] = df[col].replace(np.nan,sample[col])\n return df\n\ndef getResampledDf(df,file_path):\n if not checkFileInFolder(folder ='last12months/12months',file=file_path):\n df_sorted = sortDf(df)\n df_sorted = cleanCSV(df_sorted)\n df_resampled = resampleDf(df_sorted,'30s')\n df_resampled.to_csv('last12months/12months/' + file_path)\n return df_sorted, df_resampled\n else:\n df_resampled = pd.read_csv('last12months/12months/'+ file_path)\n return None, df_resampled\n \ndef getLastValues(df):\n d_sample = df.iloc[-1]\n dictionary = dict.fromkeys(df.columns,None)\n\n for col in df.columns:\n if col in d_sample.index:\n dictionary[col] = d_sample[col]\n\n return dictionary\n\nif __name__ == '__main__':\n\n parameter_list = sys.argv\n\n\n if '--file1'in parameter_list:\n file1 = os.path.abspath(sys.argv[parameter_list.index(\"--file1\")+1])\n else:\n print(\"Mandatory parameter --file1 not found please check input parameters\")\n sys.exit()\n if '--file2'in parameter_list:\n file2 = os.path.abspath(sys.argv[parameter_list.index(\"--file1\")+1])\n else:\n print(\"Mandatory parameter --file1 not found please check input parameters\")\n sys.exit()\n if '--file3'in parameter_list:\n file3 = os.path.abspath(sys.argv[parameter_list.index(\"--file1\")+1])\n else:\n print(\"Mandatory parameter --file1 not found please check input parameters\")\n sys.exit()\n if '--makeFinalFile'in parameter_list:\n makeFinalFile = bool(os.path.abspath(sys.argv[parameter_list.index(\"--file1\")+1]))\n else:\n makeFinalFile = False\n \n\n # file1 = sys.argv[1]\n # file2 = sys.argv[2]\n # file3 = sys.argv[3]\n\n df = pd.read_csv(file1) \n df2 = pd.read_csv(file2)\n df3 = pd.read_csv(file3)\n\n df['dt'] = pd.to_datetime(df['TIMESTAMP'],unit='ms')\n df2['dt'] = pd.to_datetime(df2['TIMESTAMP'],unit='ms')\n df3['dt'] = pd.to_datetime(df3['TIMESTAMP'],unit='ms')\n\n df_sorted, df_resampled = getResampledDf(df,'204300479_resampled30s.csv')\n df2_sorted, df2_resampled = getResampledDf(df2,'220330932_resampled30s.csv')\n df3_sorted, df3_resampled = getResampledDf(df3,'224228487_resampled30s.csv')\n \n\n if 'last_20Row_204300479.csv' in os.listdir('last12months/12months'):\n df1_last20 = pd.read_csv('last12months/12months/last_20Row_204300479.csv')\n\n if 'd_test_filled.csv' in os.listdir('last12months/12months') and makeFinalFile == False:\n d_test_filled = pd.read_csv('last12months/12months/d_test_filled.csv')\n else:\n print('Filling....')\n d1 = pd.read_csv('last12months/20230721-153054/204300479_LUNA IN PLUS AIR.csv')\n print(\"Cleaning 204300479_LUNA IN PLUS AIR.csv...\") \n d1 = cleanCSV(d1)\n print(\"Cleaned!\")\n d1['dt'] = pd.to_datetime(d1['TIMESTAMP'],unit='ms')\n d1_sorted = sortDf(d1)\n d1_resampled = resampleDf(d1_sorted,'30s')\n d1_resampled = d1_resampled.replace('---', 0)\n if 'd1.csv' not in os.listdir('last12months'):\n d1_resampled.tail(50).to_csv('last12months/d1.csv')\n if 'df1.csv' not in os.listdir('last12months'):\n df_resampled.head(50).to_csv('last12months/df1.csv')\n\n\n dictionary = getLastValues(d1_resampled.tail())\n generalBooleans = getGeneralBooleans(df_resampled,df2_resampled,df3_resampled)\n d_test_fB = fillBooleans(df_resampled,generalBooleans,dictionary)\n d_campione = d1_resampled.iloc[-1]\n d_test_filled = fillOthers(d_test_fB,d_campione)\n # print('Cleaning Final dataset...')\n # d_test_filled = cleanCSV(d_test_filled)\n # print('Cleaned!')\n\n d_test_filled.to_csv('last12months/12months/d_test_filled.csv')\n print('Done!')\n # d_finale20 = df_resampled.head(20)\n # d_finale20.to_csv('last12months/12months/last_20Row_204300479.csv') \n\n # if 'last_20Row_204300479.xlsx' not in os.listdir('last12months/12months'):\n # d_finale20.to_excel('last12months/12months/last_20Row_204300479.xlsx')","repo_name":"leonardozecchin/anomaly_detection","sub_path":"codes/resampler.py","file_name":"resampler.py","file_ext":"py","file_size_in_byte":8053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"13356937360","text":"import cv2\nimport numpy as np\nimport uuid\nfrom PIL import Image\n\n\n\n \n\"\"\"FUNCTION TO SHOW THE IMAGE\"\"\"\ndef show_img(img_list):\n for j, img in enumerate(img_list):\n cv2.imshow(str(j), img)\n cv2.waitKey()\n\n\"\"\"FUNCTION TO READ THE IMAGE\"\"\"\n\ndef Resize_and_read(crt_imgs):\n for i, im in enumerate(crt_imgs):\n\n #im = cv2.imread(im, -1)\n height, width, *_ = im.shape\n im = cv2.resize(im, None, fx=2, fy=2,\n interpolation=cv2.INTER_CUBIC)\n crt_imgs[i] = im\n\n\"\"\"FUNCTION TO CONVERT THE IMAGE INTO GRAY SCALE\"\"\"\n\ndef convert_gray(crt_images, Gray):\n for i, img in enumerate(crt_images):\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n Gray.append(img)\n\n\"\"\"FUNCTION TO SMOOTHEN THE IMAGE\"\"\"\n\ndef smoothen_image(gray_img, smooth_img):\n for j, img in enumerate(gray_img):\n img = cv2.resize(img, None, fx=0.25, fy=0.25,\n interpolation=cv2.INTER_CUBIC)\n img = cv2.medianBlur(img, 7)\n smooth_img.append(img)\n\n\"\"\"FUNCTION TO DETECT THE EDGES\"\"\"\n\ndef edge_image(smooth_img, edge_img):\n for j, img in enumerate(smooth_img):\n img = cv2.Canny(img, 25, 200)\n img = cv2.resize(img, None, fx=4, fy=4,\n interpolation=cv2.INTER_CUBIC)\n edge_img.append(img)\n\n\"\"\"TO FIND THE CONTOURS OF THE IMAGE\"\"\"\n\ndef find_img_contours(edge_list, contours_list):\n for img in edge_list:\n contours, hierarchy = cv2.findContours(\n img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n contours_list.append(contours)\n\n\"\"\"TO DRAW THE REQUIRED CONTOURS\"\"\"\n\ndef draw_img_contours(all_cnts, imgs, requi_coordinates):\n for j, cnts in enumerate(all_cnts):\n req_cnt = None\n\n cnts = sorted(cnts, key=cv2.contourArea, reverse=True)\n\n for cnt in cnts:\n peri = cv2.arcLength(cnt, True)\n approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)\n\n if len(approx) == 4:\n req_cnt = approx\n requi_coordinates.append(req_cnt)\n break\n cv2.drawContours(imgs[j], [req_cnt], -1, (255, 0, 255), 4)\n\n\"\"\"FUNCTION TO PREPROCESS THE REQUIRED CO-ORDINATES\"\"\"\n\ndef req_coor_pre(r_c, r_c_l):\n for k, co in enumerate(r_c):\n a_x = co[0][0][0]\n a_y = co[0][0][1]\n a = [a_x, a_y]\n\n b_x = co[1][0][0]\n b_y = co[1][0][1]\n b = [b_x, b_y]\n\n c_x = co[2][0][0]\n c_y = co[2][0][1]\n c = [c_x, c_y]\n\n d_x = co[3][0][0]\n d_y = co[3][0][1]\n d = [d_x, d_y]\n\n lst = [a, b, c, d]\n lst = sorted(lst, key=lambda x: x[0])\n if lst[0][1] <= lst[1][1]:\n top_left = lst[0]\n bottom_left = lst[1]\n else:\n top_left = lst[1]\n bottom_left = lst[0]\n\n if lst[2][1] <= lst[3][1]:\n top_right = lst[2]\n bottom_right = lst[3]\n else:\n top_right = lst[3]\n bottom_right = lst[2]\n\n r_c_l.append([top_left, top_right, bottom_left, bottom_right])\n\n\"\"\"FUNCTION TO FIND HEIGHT AND WIDTH OF NEW WINDOW\"\"\"\n\ndef new_window(cor_list, n_h_a_w):\n for cor in cor_list:\n width = cor[1][0] - cor[0][0]\n height = cor[2][1] - cor[0][1]\n new_width = (width / (width + height)) * 2000\n new_height = (height / (width + height)) * 2000\n n_h_a_w.append([int(new_height), int(new_width)])\n\n\"\"\"FUNCTION TO CHANGE PERSPECTIVE\"\"\"\n\ndef perspective_change(ori_img, cors, hei_and_wid, new_img):\n for j, img in enumerate(ori_img):\n pt_1 = np.float32(cors[j])\n pt_2 = np.float32(\n [[0, 0], [hei_and_wid[j][1], 0], [0, hei_and_wid[j][0]], [hei_and_wid[j][1], hei_and_wid[j][0]]])\n matrix = cv2.getPerspectiveTransform(pt_1, pt_2)\n result = cv2.warpPerspective(\n ori_img[j], matrix, (hei_and_wid[j][1], hei_and_wid[j][0]))\n new_img.append(result)\n\n\"\"\"FUNCTION TO SHARPEN THE IMAGE\"\"\"\n\ndef sharp_image(img_list, sh_img_list):\n for img in img_list:\n filter = np.array(\n [[-1 / 8, -1 / 8, -1 / 8], [-1 / 8, 16 / 8, -1 / 8], [-1 / 8, -1 / 8, -1 / 8]])\n s_img = cv2.filter2D(img, -1, filter)\n sh_img_list.append(s_img)\n\n\"\"\"FUNCTION FOR ADAPTIVE THRESHOLDING\"\"\"\n\ndef adaptive_threshold_image(img_list, res_img):\n for img in img_list:\n thres_img = cv2.adaptiveThreshold(\n img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 101, 20)\n res_img.append(thres_img)\n\n\"\"\"FUNCTION TO CONVERT THE LIST OF ARRAYS INTO IMAGE\"\"\"\n\ndef pil_convert(array, img_list):\n for img in array:\n im = Image.fromarray(img)\n img_list.append(im)\n\n\"\"\"FUNCTION TO CONVERT THE LIST OF IMAGES TO PDF AND SAVE THE PDF FILE\"\"\"\n\ndef img_to_pdf(img_list):\n im1 = img_list[0]\n fileName= uuid.uuid4()\n if len(img_list) > 1:\n im1.save(f'{fileName}.pdf', save_all=True,append_images=img_list[1:]) \n else:\n im1.save(f'{fileName}.pdf')\n \n return fileName\nasync def convert_to_pdf(imageFiles):\n \n \"\"\"GETTING THE IMAGES FROM THE USER\"\"\" \n \n correct_images = []\n for imageFile in imageFiles:\n content = await imageFile.read()\n nparray = np.fromstring(content, np.uint8)\n img = cv2.imdecode(nparray, cv2.IMREAD_COLOR)\n #image= Image.fromarray(img)\n correct_images.append(img)\n \"\"\"1.READ IMAGE\"\"\"\n\n Resize_and_read(correct_images)\n # show_img(correct_images)\n correct_images_copy = []\n sharp_image(correct_images, correct_images_copy)\n # show_img(correct_images_copy)\n\n \"\"\"2.CONVERTING THE IMAGE INTO GREY SCALE\"\"\"\n\n Gray_img_list = []\n convert_gray(correct_images_copy, Gray_img_list)\n # show_img(Gray_img_list)\n\n \"\"\"3.SMOOTHENING THE IMAGE\"\"\"\n\n smooth_img_list = []\n smoothen_image(Gray_img_list, smooth_img_list)\n # show_img(smooth_img_list)\n\n \"\"\"4.DETECTING EDGES\"\"\"\n\n edge_img_list = []\n edge_image(smooth_img_list, edge_img_list)\n # show_img(edge_img_list)\n\n \"\"\"5.FINDING CONTOURS\"\"\"\n All_contours = []\n edge_copied_img_list = edge_img_list.copy()\n find_img_contours(edge_copied_img_list, All_contours)\n\n \"\"\"6.DRAW THE CONTOURS\"\"\"\n required_cordinates = []\n draw_img_contours(All_contours, correct_images_copy,\n required_cordinates)\n # show_img(correct_images_copy)\n\n \"\"\"7.PREPROCESSING THE REQUIRED CO-ORDINATE\"\"\"\n req_coor_list = []\n req_coor_pre(required_cordinates, req_coor_list)\n\n \"\"\"8.FINDING THE NEW WINDOW'S HEIGHT AND WIDTH\"\"\"\n new_hei_and_wid = []\n new_window(req_coor_list, new_hei_and_wid)\n\n \"\"\"9.sharpening the image\"\"\"\n sharpened_image = []\n sharp_image(Gray_img_list, sharpened_image)\n # show_img(sharpened_image)\n\n \"\"\"10.ADAPTIVE THRESHOLDING\"\"\"\n threshold_image = []\n adaptive_threshold_image(sharpened_image, threshold_image)\n # show_img(result_image)\n\n \"\"\"11.CHANGING PERSPECTIVE AND ASKING FOR USER'S OPTION\"\"\"\n transformed_image = []\n\n # option = input(\"Enter your option: 1. original 2. black and white \")\n\n \n # perspective_change(correct_images, req_coor_list,\n # new_hei_and_wid, transformed_image)\n \n perspective_change(threshold_image, req_coor_list,\n new_hei_and_wid, transformed_image)\n\n\n # show_img(transformed_image)\n\n \"\"\"12.CONVERTING INTO PIL OBJECT\"\"\"\n final_img_list = []\n pil_convert(transformed_image, final_img_list)\n\n \"\"\"13.CONVERTING INTO PDF AND SAVING\"\"\"\n return img_to_pdf(final_img_list)\n \n \n","repo_name":"mithunsai/document-scanner-be","sub_path":"pdf_converter.py","file_name":"pdf_converter.py","file_ext":"py","file_size_in_byte":7604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"34686474688","text":"import re\nimport string\nimport os\nimport random\n\n#Save all the LCRs in one big array:\n# key: genename\n# value:[array_of_LCR_positions, chromosome]\n\ndef get_LCR():\n LCR_dict = {}\n inputfile = open(\"/home/xiaoyu/protein/all_gene/result/Homo.withintronSNP\", \"r\")\n pattern = re.compile(\">GeneInformation:(.*)@GeneName:(\\S+)@Chromosome:(\\S+)@Strand:(\\S+)@LCRpos:(\\S+)#@LCR_SNP:\")\n for line in inputfile:\n LCR = []\n line = string.strip(line)\n match = pattern.match(line)\n if match != None:\n gene_name = match.group(2)\n chromosome = match.group(3)\n LCRpos_string = match.group(5)\n LCRpos_raw_array = LCRpos_string.split(\"#\")\n for i in LCRpos_raw_array:\n array = i.split(\",\")\n LCR.append(array[0])\n LCR_dict[gene_name] = [LCR, chromosome]\n inputfile.close()\n return LCR_dict\n\n#Sample from the LCR dictionary in the format of(position, codon, chromosome, gene_name)\ndef sample_LCR_pos(gene_name_array, LCR_dict, size):\n result = []\n for i in range(size):\n name = random.choice(gene_name_array)\n\n length = len(LCR_dict[name][0])\n amino_length = length / 3\n rand = random.randint(0, amino_length - 1)\n\n position1 = LCR_dict[name][0][rand * 3]\n position2 = LCR_dict[name][0][rand * 3 + 1]\n position3 = LCR_dict[name][0][rand * 3 + 2]\n\n result.append([position1, str(1), LCR_dict[name][1], name])\n result.append([position2, str(2), LCR_dict[name][1], name])\n result.append([position3, str(3), LCR_dict[name][1], name])\n\n return result\n\n#Save all the cdexons positions in one big array:\n#now I change the format of saving all the big codon in the format of:\n# key : [gene_name]\n# value : [array_of_LCR_positions, chromosome]\ndef get_All_cde_pos():\n all_cde_pos_dict = {}\n inputfile = open(\"/home/xiaoyu/protein/all_gene/result/Homo.withintronSNP\", \"r\")\n pattern = re.compile(\">GeneInformation:(.*)@GeneName:(\\S+)@Chromosome:(\\S+)@Strand:(\\S+)@CDExons:(\\S+)#@LCRpos:(\\S+)#@LCR_SNP:\")\n for line in inputfile:\n cnt = 0\n all_pos = []\n line = string.strip(line)\n match = pattern.match(line)\n if match != None:\n gene_name = match.group(2)\n chromosome = match.group(3)\n all_pos_string = match.group(5)\n all_pos_raw_array = all_pos_string.split(\"#\")\n for i in all_pos_raw_array:\n array = i.split(\"~\")\n begin = int(array[0])\n end = int(array[1])\n exon_pos = range(begin, end)\n for i in exon_pos:\n all_pos.append(str(i))\n cnt += 1\n all_cde_pos_dict[gene_name] = [all_pos, chromosome]\n inputfile.close()\n return all_cde_pos_dict\n\n#Save all the cdexons position in one big array(non_dict)\ndef sample_non_LCR_pos(gene_name_array, LCR_dict, non_dict, size):\n result = []\n while len(result) < 3 * size:\n name = random.choice(gene_name_array)\n position_array = non_dict[name][0]\n chromosome = non_dict[name][1]\n\n length = len(non_dict[name][0])\n amino_length = length / 3\n rand = random.randint(0, amino_length - 1)\n\n position1 = non_dict[name][0][rand * 3]\n\n if position1 in LCR_dict[name][0]:\n continue\n else:\n position2 = non_dict[name][0][rand * 3 + 1]\n position3 = non_dict[name][0][rand * 3 + 2]\n result.append([position1, str(1), chromosome, name])\n result.append([position2, str(2), chromosome, name])\n result.append([position3, str(3), chromosome, name])\n return result\n\n\ndirectory = \"/home/xiaoyu/protein/all_gene/result/simulation_gene_based/\"\ngene_inputfile = open(\"/home/xiaoyu/protein/all_gene/result/Homo.withintronSNP\", \"r\")\npattern = re.compile(\">GeneInformation:(.*)@GeneName:(\\S+)@Chromosome:(\\S+)@Strand:(\\S+)@CDExons:(\\S+)#@LCRpos:(\\S+)#@LCR_SNP:(\\S+)\")\n\n#This array saves all of the gene name for pick\ngene_name_array = []\n\nfor line in gene_inputfile:\n line = string.strip(line)\n match = pattern.match(line)\n if match != None:\n gene_name_array.append(match.group(2))\ngene_inputfile.close()\n\nLCR = get_LCR()\nALL = get_All_cde_pos()\n#input size here:~\nfor i in range(1001):\n file = directory + str(i) + \".simulation_gene_based\"\n outputfile = open(file, \"w\")\n\n lcr_sample = sample_LCR_pos(gene_name_array, LCR, 5000)\n non_lcr_sample = sample_non_LCR_pos(gene_name_array, LCR, ALL, 5000)\n\n outputfile.write(\"LCR_positions:\")\n\n for element in lcr_sample:\n outputfile.write(element[0] + \",\" + element[1] + \",\" + element[2] + \",\" + element[3] + \"#\")\n outputfile.write(\"\\n\")\n\n\n outputfile.write(\"non_LCR_positions:\")\n\n for element in non_lcr_sample:\n outputfile.write(element[0] + \",\" + element[1] + \",\" + element[2] + \",\" + element[3] + \"#\")\n outputfile.write(\"\\n\")\n outputfile.close()\n","repo_name":"maxmu/Lab","sub_path":"simulation/sample_gene_based_2.py","file_name":"sample_gene_based_2.py","file_ext":"py","file_size_in_byte":5033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"43079414655","text":"from PIL import Image\n#按像素缩放图片\nimg1= Image.open('bjsxt.png')\n# img1.show()\n#.将每个像素都扩大2倍\n# Image.eval(img1,lambda x:x*2).show()\n\n#按尺寸进行缩放图片\n#复制图片\nimg2=img1.copy()\nprint(img2.size)\nimg1.show()\nimg2.thumbnail((200,160))\nimg2.show()","repo_name":"qq4215279/study_python","sub_path":"py_tea_code/18.pillow/04缩放图像.py","file_name":"04缩放图像.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"20893518430","text":"# Define a function to read a file all at once\n# As a parameter use a name of a file\ndef read_txt(fn):\n with open(fn) as f: # Open a file\n print(f.read())\n\n# Define a function to read a file line by line\ndef read_txt_by_line(fn):\n with open(fn) as f:\n lines = f.readlines() # Read each line in the file\n for line in lines:\n print(line, end=\"\")\n line = f.readline()\n\n# Define a function to write to a text file\n# Text file as a parameter and the string that we want to write to the file\ndef write_new_txt(fn, str):\n with open(fn, \"w\", encoding=\"utf-8\") as f: # Open and write to the file. Use utf-8 as an encoding type\n f.write(str) # Write to the file, pass the string to write to the file\n\n# Define a function to append new line to a file\ndef append_line_txt(fn, str):\n with open (fn, \"a\", encoding=\"utf-8\") as f: # Oppen a file in append mode\n f.write(\"\\n\") # Write to a file\n f.write(str)\n\nread_txt(\"\")\nread_txt_by_line(\"\")\nwrite_new_txt(\"\", \"\")\nappend_line_txt(\"\", \"\")","repo_name":"qnmx/Python_code","sub_path":"Code_to_Reuse/Working_with_Files/Reading_and_Writing_Files/Working_with_Text_Files.py","file_name":"Working_with_Text_Files.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"4871181899","text":"class Clase1():\n def funcion(self):\n yield 'hola'\nclass Clase2():\n def funcion(self):\n return 'hola'\n\ncorrect = Clase1().funcion()\ncorrect2 = correct\nnext(correct2)\n#si hago correct2 = correct() no lo detecta como assign pero aparece en calls la linea 9\nincorrect = Clase2().funcion()\nnext(incorrect)","repo_name":"ADCenterNetwork/discern","sub_path":"tests/pruebas_assign.py","file_name":"pruebas_assign.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"}
+{"seq_id":"71486125530","text":"#!/usr/bin/python3\nimport re\n\ndef Read_file(file):\n fh = open(file,\"r\")\n err = 0\n warn = 0\n for line in fh:\n line = line.strip()\n if re.match(r'^$',line): continue\n if re.match(r'^\\#',line): continue\n print (line)\n if re.match(r'error',line,re.I):\n #print (line) \n pass\n aa = re.search(r'(^error)',line,re.I);\n if aa:\n #print (aa.group()) \n err +=1\n bb = re.search(r'(^warn.*)',line,re.I);\n if bb:\n #print (bb.group())\n warn +=1\n print (\"no of error in a file :\",err)\n print (\"no of warn in a file : \",warn)\n\n fh.close()\n\nRead_file(\"error.txt\")\n","repo_name":"KSrinuvas/ALL","sub_path":"aa/PYT/PRAC/errot_ff.py","file_name":"errot_ff.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"12968705796","text":"import pandas as pd\r\nimport numpy as np\r\nimport glob,os\r\nimport csv\r\n\r\n# Select point (x,y) satisfying\r\n# group 2: 713>x>625 & 378>y>295\r\n# person 3: 680>x>614 & 280>y>178\r\n# person 13: 602>x>455 & 440>y>280\r\n# wakeboard 10: 705>x>485 & 361>y>214\r\n# car 10: 695>x>541 & 531>y>326\r\n\r\npath = r'D:\\Pycharm\\Project\\plot_all_data\\output_fixation\\car10_data'\r\nfile = glob.glob(os.path.join(path, \"*.csv\"))\r\ninput_df = []\r\n# Produce datasets for input\r\nfor f1 in file:\r\n input_df.append(pd.read_csv(f1, usecols=[3,4,5]))\r\n\r\nnum_input = len(input_df)\r\ncounter = np.arange(0,num_input)\r\n\r\n# Data type of input_df: list; input_df[1]: dataframe\r\nindex = []\r\nfor i in counter:\r\n reader_in = input_df[i]\r\n df_nan = input_df[i].fillna(0) # replace NaN by 0\r\n reader = df_nan.astype(int) # transfer data type\r\n # # group2\r\n # select = reader[(reader['endx'] >= 625) & (reader['endx']<713) &\r\n # (reader['endy'] >= 295) & (reader['endy']<378)]\r\n # # person3\r\n # select = reader[(reader['endx'] >= 614) & (reader['endx']<680) &\r\n # (reader['endy'] >= 178) & (reader['endy']<280)]\r\n # # person13\r\n # select = reader[(reader['endx'] >= 455) & (reader['endx']<602) &\r\n # (reader['endy'] >= 280) & (reader['endy']<440)]\r\n # # wakeboard10\r\n # select = reader[(reader['endx'] >= 485) & (reader['endx']<705) &\r\n # (reader['endy'] >= 214) & (reader['endy']<361)]\r\n # car10\r\n select = reader[(reader['endx'] >= 541) & (reader['endx']<695) &\r\n (reader['endy'] >= 326) & (reader['endy']<531)]\r\n\r\n #print(select)\r\n total_time = (reader['etime'].iloc[-1] - reader['etime'].iloc[1]) / 1000\r\n dwelling_time = (select['etime'].iloc[-1]-select['etime'].iloc[1])/1000\r\n #print('The Dwelling Time is %f s' % dwelling_time)\r\n\r\n time_raw = reader_in['etime'].iloc[1]\r\n time_select = select['etime'].iloc[1]\r\n Reaction = (time_select - time_raw)\r\n #print('The Reaction time is %f ms' % Reaction)\r\n\r\n row_select = select.shape[0]\r\n row_raw = reader_in.shape[0]\r\n hit_num = row_select\r\n #print('The Number of fixation points in the ROI is %f' % hit_num)\r\n\r\n index_temp = [dwelling_time,Reaction,hit_num]\r\n index.append(index_temp)\r\n\r\nwith open('D:\\Pycharm\\Project\\plot_all_data\\output_index\\ car10_14obs.csv', 'w') as file:\r\n csvwriter = csv.writer(file, lineterminator='\\n')\r\n csvwriter.writerows(index)\r\n","repo_name":"Carloslee96/EyetrackingAnalysis-","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"21737750895","text":"from digital_twin.communication.rabbitmq_protocol import ROUTING_KEY_SELF_ADAPTATION_TRIGGER\nfrom incubator.communication.server.rabbitmq import Rabbitmq\nfrom incubator.config.config import config_logger, load_config\nfrom mock_plant.mock_connection import MOCK_G_BOX\n\n\ndef send_G_box_config(config, G_box):\n with Rabbitmq(**config) as rabbitmq:\n rabbitmq.send_message(MOCK_G_BOX, {\n \"G_box\": G_box\n })\n\n\nif __name__ == '__main__':\n config_logger(\"logging.conf\")\n config = load_config(\"startup.conf\")\n\n with Rabbitmq(**config[\"rabbitmq\"]) as rabbitmq:\n rabbitmq.send_message(ROUTING_KEY_SELF_ADAPTATION_TRIGGER, {})\n","repo_name":"INTO-CPS-Association/example_digital-twin_incubator","sub_path":"software/cli/trigger_self_adaptation.py","file_name":"trigger_self_adaptation.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"24528803351","text":"from language_modelling.out_of_vocabulary_rate_calculator import OutOfVocabularyRateCalculator\nfrom language_modelling.corpus import Corpus\n\n\nclass TestOutOfVocabularyRateCalculator:\n training_corpus = [\n ['how', 'many', 'roads', 'must', 'a', 'man', 'walk', 'down'],\n ['before', 'you', 'call', 'him', 'a', 'man'],\n ['how', 'many', 'seas', 'must', 'a', 'white', 'dove', 'sail'],\n ['before', 'she', 'sleeps', 'in', 'the', 'sand']\n ]\n test_corpus = [\n ['yes', 'and', 'how', 'many', 'times', 'must', 'the', 'cannon', 'balls', 'fly'],\n ['before', \"they're\", 'forever', 'banned'],\n ['the', 'answer', 'my', 'friend', 'is', \"blowin'\", 'in', 'the', 'wind'],\n ['the', 'answer', 'is', \"blowin'\", 'in', 'the', 'wind']\n ]\n\n calculator = OutOfVocabularyRateCalculator()\n\n def test_calculate_out_of_vocabulary_rate(self):\n assert 19/30 == self.calculator.calculate_out_of_vocabulary_rate(Corpus(self.training_corpus),\n Corpus(self.test_corpus))\n","repo_name":"swigder/language_modelling","sub_path":"language_modelling/test/test_out_of_vocabulary_rate_calculator.py","file_name":"test_out_of_vocabulary_rate_calculator.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"}
+{"seq_id":"38362015374","text":"\nfrom django.urls import path,include\nfrom .views import touslesHopital,UnseulHopital,getNearHospital,AddingArticle,GetAllArticles,AddHospita\nfrom rest_framework import routers\n\n\nroute=routers.DefaultRouter()\n\napi1=\"tousleshopitaux/\"\napi6=\"addhospital\"\napi2=\"unseulHopital//\"\napihp=\"hp///\"\napi4=\"addarticle/\"\napi5=\"getallarticles/\"\n\n\nurlpatterns = [\n\n path(api1,touslesHopital().as_view()),\n path(api2,UnseulHopital().as_view()),\n path(apihp,getNearHospital),\n path(api4,AddingArticle.as_view()),\n path(api5,GetAllArticles().as_view()),\n path(api6,AddHospita.as_view())\n ]\n","repo_name":"Njuci/ptyhonanywareSosdolkta","sub_path":"SOS/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"28920817463","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# https://github.com/Leryan/leryan.types/tree/v0.0.17\n\nfrom __future__ import unicode_literals\n\nimport os\nimport tempfile\nimport unittest\nfrom canopsis.common import root_path\nfrom canopsis.confng.helpers import cfg_to_array, cfg_to_bool\nfrom canopsis.confng.simpleconf import SimpleConf\nfrom canopsis.confng import Configuration\nfrom canopsis.confng import Ini, Json\nimport xmlrunner\n\n\nclass ConfigurationTest(unittest.TestCase):\n \"\"\"Test the configuration ng module.\n \"\"\"\n def setUp(self):\n self.iniconf = \"\"\"[sec1]\nk1 = val\nk2 = 2\n\n[sec2]\nk1 = v\nk2 = 3\"\"\"\n\n self.iniconf_interp = \"\"\"[vars]\nv1 = val\nv2 = 2\nv3 = 3\nv4 = v\n\n[sec1]\nk1 = ${vars:v1}\nk2 = ${vars:v2}\n\n[sec2]\nk1 = ${vars:v4}\nk2 = ${vars:v3}\"\"\"\n\n self.jsonconf = '{\"sec1\": {\"k1\": \"val\", \"k2\": \"2\"}, \"sec2\": {\"k1\": \"v\", \"k2\": \"3\"}}'\n\n def test_cfg_to_array(self):\n fd, conf_file = tempfile.mkstemp()\n content = \"\"\"[SECTION]\nkey = un, tableau, separe, par,des,virgules\"\"\"\n\n with open(conf_file, 'w') as f:\n f.write(content)\n\n self.config = Configuration.load(conf_file, Ini)\n\n r = cfg_to_array(self.config['SECTION']['key'])\n\n self.assertTrue(isinstance(r, list))\n self.assertEqual(len(r), 6)\n self.assertEqual(r[3], 'par')\n\n def test_cfg_to_bool(self):\n self.assertTrue(cfg_to_bool(True))\n self.assertFalse(cfg_to_bool(False))\n\n fd, conf_file = tempfile.mkstemp()\n content = \"\"\"[SECTION]\nvol = true\ncape = vrai\nblond = FALSE\"\"\" # = superman\n\n with open(conf_file, 'w') as f:\n f.write(content)\n\n self.config = Configuration.load(conf_file, Ini)\n\n self.assertTrue(cfg_to_bool(self.config['SECTION']['vol']))\n self.assertFalse(cfg_to_bool(self.config['SECTION']['blond']))\n with self.assertRaises(ValueError):\n cfg_to_bool(self.config['SECTION']['cape'])\n\n def _check_conf(self, sc):\n self.assertEqual(sc['sec1']['k1'], 'val')\n self.assertEqual(sc['sec1']['k2'], '2')\n self.assertEqual(sc['sec2']['k1'], 'v')\n self.assertEqual(sc['sec2']['k2'], '3')\n\n def _open_fd_check_conf(self, sconf, driver_cls, func_check_conf, *args, **kwargs):\n fd, name = tempfile.mkstemp()\n os.write(fd, sconf.encode('utf-8'))\n os.close(fd)\n\n exception = None\n\n try:\n sc = SimpleConf.export(driver_cls(name, *args, **kwargs))\n func_check_conf(sc)\n\n except Exception as ex:\n exception = ex\n\n finally:\n os.unlink(name)\n\n if exception is not None:\n raise exception\n\n def test_ini_fh(self):\n self._open_fd_check_conf(self.iniconf, Ini, self._check_conf)\n\n def test_ini_interpolate_fh(self):\n self._open_fd_check_conf(\n self.iniconf_interp, Ini, self._check_conf, with_interpolation=True)\n\n def test_ini_str(self):\n sc = SimpleConf.export(Ini(sconf=self.iniconf))\n self._check_conf(sc)\n\n def test_json_fh(self):\n self._open_fd_check_conf(self.jsonconf, Json, self._check_conf)\n\n\nif __name__ == '__main__':\n output = root_path + \"/tmp/tests_report\"\n unittest.main(\n testRunner=xmlrunner.XMLTestRunner(output=output),\n verbosity=3)\n","repo_name":"capensis/canopsis","sub_path":"community/sources/canopsis/test/confng/test_confng.py","file_name":"test_confng.py","file_ext":"py","file_size_in_byte":3318,"program_lang":"python","lang":"en","doc_type":"code","stars":95,"dataset":"github-code","pt":"32"}
+{"seq_id":"8942523622","text":"import unittest\nfrom logging.handlers import TimedRotatingFileHandler\nimport logging\nfrom Pages.zapisatsya import Zapisatsya\nfrom teamcity import is_running_under_teamcity\nfrom teamcity.unittestpy import TeamcityTestRunner\nfrom webium.driver import get_driver\n\nformat = '%(asctime)s - %(name)s - [%(levelname)s] - %(message)s'\nlogging.basicConfig(format=format, level=logging.INFO, filename='/home/dbr13/Itracker/Logs/dbr.log', filemode='a')\nlogger = logging.getLogger('Test_suite_ZapisatsyaPage')\nhandler = TimedRotatingFileHandler(filename='/home/dbr13/Itracker/Logs/dbr.log', when=\"D\", interval=1, backupCount=3)\nlogger.addHandler(handler)\n\nclass TestSuiteZapisatsyaPage(unittest.TestCase, Zapisatsya):\n def setUp(self):\n self.zapis = Zapisatsya()\n\n def tearDown(self):\n self.zapis.close_page()\n\n def test_get_success_msg(self):\n try:\n self.zapis.open()\n self.zapis.select_dd_course('Android')\n self.zapis.type_email('dober.uk@gmail.com')\n self.zapis.type_first_name('Denys')\n self.zapis.type_last_name('DDD')\n self.zapis.type_phone('0933559988')\n self.zapis.type_skype('d.bortovets')\n self.zapis.click_button_kupit()\n self.success_message()\n logger.info('{0} - {1}'.format(self._testMethodName, 'Passed'))\n except Exception as exc:\n logger.error('{0} - {1}'.format(self._testMethodName, 'Failed'))\n raise exc\n\nif __name__=='__main__':\n if is_running_under_teamcity():\n runner = TeamcityTestRunner()\n else:\n runner = unittest.TextTestRunner()\n unittest.main(testRunner=runner)\n","repo_name":"dbr13/itra","sub_path":"Pages/test_suite_zapisatsya_page.py","file_name":"test_suite_zapisatsya_page.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"22935424977","text":"from erpbrasil.base.fiscal import cnpj_cpf, ie\n\nfrom odoo import _, api, fields, models\nfrom odoo.exceptions import ValidationError\n\n\nclass Partner(models.Model):\n _name = \"res.partner\"\n _inherit = [_name, \"l10n_br_base.party.mixin\"]\n\n vat = fields.Char(related=\"cnpj_cpf\")\n\n is_accountant = fields.Boolean(string=\"Is accountant?\")\n\n crc_code = fields.Char(string=\"CRC Code\", size=18)\n\n crc_state_id = fields.Many2one(comodel_name=\"res.country.state\", string=\"CRC State\")\n\n rntrc_code = fields.Char(string=\"RNTRC Code\", size=12)\n\n cei_code = fields.Char(string=\"CEI Code\", size=12)\n\n union_entity_code = fields.Char(string=\"Union Entity code\")\n\n pix_key_ids = fields.One2many(\n string=\"Pix Keys\",\n comodel_name=\"res.partner.pix\",\n inverse_name=\"partner_id\",\n help=\"Keys for Brazilian instant payment (pix)\",\n )\n\n show_l10n_br = fields.Boolean(\n compute=\"_compute_show_l10n_br\",\n help=\"Indicates if Brazilian localization fields should be displayed.\",\n )\n\n @api.constrains(\"cnpj_cpf\", \"inscr_est\")\n def _check_cnpj_inscr_est(self):\n for record in self:\n domain = []\n\n # permite cnpj vazio\n if not record.cnpj_cpf:\n return\n\n if self.env.context.get(\"disable_allow_cnpj_multi_ie\"):\n return\n\n allow_cnpj_multi_ie = (\n record.env[\"ir.config_parameter\"]\n .sudo()\n .get_param(\"l10n_br_base.allow_cnpj_multi_ie\", default=True)\n )\n\n if record.parent_id:\n domain += [\n (\"id\", \"not in\", record.parent_id.ids),\n (\"parent_id\", \"not in\", record.parent_id.ids),\n ]\n\n domain += [(\"cnpj_cpf\", \"=\", record.cnpj_cpf), (\"id\", \"!=\", record.id)]\n\n # se encontrar CNPJ iguais\n if record.env[\"res.partner\"].search(domain):\n if cnpj_cpf.validar_cnpj(record.cnpj_cpf):\n if allow_cnpj_multi_ie == \"True\":\n for partner in record.env[\"res.partner\"].search(domain):\n if (\n partner.inscr_est == record.inscr_est\n and not record.inscr_est\n ):\n raise ValidationError(\n _(\n \"There is already a partner record with this \"\n \"Estadual Inscription !\"\n )\n )\n else:\n raise ValidationError(\n _(\"There is already a partner record with this CNPJ !\")\n )\n else:\n raise ValidationError(\n _(\"There is already a partner record with this CPF/RG!\")\n )\n\n @api.constrains(\"cnpj_cpf\", \"country_id\")\n def _check_cnpj_cpf(self):\n result = True\n for record in self:\n disable_cnpj_ie_validation = record.env[\n \"ir.config_parameter\"\n ].sudo().get_param(\n \"l10n_br_base.disable_cpf_cnpj_validation\", default=False\n ) or self.env.context.get(\n \"disable_cpf_cnpj_validation\"\n )\n if not disable_cnpj_ie_validation:\n if record.country_id:\n country_code = record.country_id.code\n if country_code:\n if record.cnpj_cpf and country_code.upper() == \"BR\":\n if record.is_company:\n if not cnpj_cpf.validar(record.cnpj_cpf):\n result = False\n document = \"CNPJ\"\n elif not cnpj_cpf.validar(record.cnpj_cpf):\n result = False\n document = \"CPF\"\n if not result:\n raise ValidationError(_(\"{} Invalid!\").format(document))\n\n @api.constrains(\"inscr_est\", \"state_id\")\n def _check_ie(self):\n \"\"\"Checks if company register number in field insc_est is valid,\n this method call others methods because this validation is State wise\n\n :Return: True or False.\n\n :Parameters:\n \"\"\"\n for record in self:\n result = True\n\n disable_ie_validation = record.env[\"ir.config_parameter\"].sudo().get_param(\n \"l10n_br_base.disable_ie_validation\", default=False\n ) or self.env.context.get(\"disable_ie_validation\")\n if not disable_ie_validation:\n if record.inscr_est == \"ISENTO\":\n return\n if record.inscr_est and record.is_company and record.state_id:\n state_code = record.state_id.code or \"\"\n uf = state_code.lower()\n result = ie.validar(uf, record.inscr_est)\n if not result:\n raise ValidationError(_(\"Estadual Inscription Invalid !\"))\n\n @api.constrains(\"state_tax_number_ids\")\n def _check_state_tax_number_ids(self):\n \"\"\"Checks if field other insc_est is valid,\n this method call others methods because this validation is State wise\n :Return: True or False.\n \"\"\"\n for record in self:\n for inscr_est_line in record.state_tax_number_ids:\n state_code = inscr_est_line.state_id.code or \"\"\n uf = state_code.lower()\n valid_ie = ie.validar(uf, inscr_est_line.inscr_est)\n if not valid_ie:\n raise ValidationError(_(\"Invalid State Tax Number!\"))\n if inscr_est_line.state_id.id == record.state_id.id:\n raise ValidationError(\n _(\n \"There can only be one state tax\"\n \" number per state for each partner!\"\n )\n )\n duplicate_ie = record.search(\n [\n (\"state_id\", \"=\", inscr_est_line.state_id.id),\n (\"inscr_est\", \"=\", inscr_est_line.inscr_est),\n ]\n )\n if duplicate_ie:\n raise ValidationError(\n _(\"State Tax Number already used {}\").format(duplicate_ie.name)\n )\n\n @api.model\n def _address_fields(self):\n \"\"\"Returns the list of address\n fields that are synced from the parent.\"\"\"\n return super()._address_fields() + [\"district\"]\n\n @api.onchange(\"city_id\")\n def _onchange_city_id(self):\n self.city = self.city_id.name\n\n def _compute_show_l10n_br(self):\n \"\"\"\n Defines when Brazilian localization fields should be displayed.\n \"\"\"\n for rec in self:\n if rec.company_id and rec.company_id.country_id != self.env.ref(\"base.br\"):\n rec.show_l10n_br = False\n else:\n rec.show_l10n_br = True\n","repo_name":"OCA/l10n-brazil","sub_path":"l10n_br_base/models/res_partner.py","file_name":"res_partner.py","file_ext":"py","file_size_in_byte":7244,"program_lang":"python","lang":"en","doc_type":"code","stars":196,"dataset":"github-code","pt":"32"}
+{"seq_id":"14934678945","text":"import networkx as nx\nimport matplotlib.pyplot as plt\nimport operator\nimport keras\nimport numpy as np\nimport metric as met\nimport random\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense,Activation\n\n\nG = nx.Graph()\nG.add_edges_from([('A','B'),('A','D'),('A','C'),('B','F'),('C','G'),('D','G'),('G','H')])\n\nclass InputTensor(object):\n\n def __init__(self,metrics=[]):\n self.metrics = metrics\n\n def format_function(self,function, netx=False):\n if netx:\n return lambda G: [i[2] for i in function(G)]\n else:\n return lambda G: [function(G,e[0],e[1]) for e in nx.non_edges(G)]\n\n def evaluate(self,graph=None):\n arr = []\n if graph:\n for func in self.metrics:\n arr.append(func(graph))\n return np.array(arr).transpose()\n\n\ntn = InputTensor()\ntn.metrics=[tn.format_function(met.vecinos_comunes),\n tn.format_function(nx.jaccard_coefficient,netx=True),\n tn.format_function(nx.resource_allocation_index,netx=True),\n tn.format_function(nx.adamic_adar_index,netx=True),\n tn.format_function(nx.preferential_attachment,netx=True)]\n\nX_train = tn.evaluate(G)\n\nY_train = np.array([random.randint(0,2) for i in range(len(X_train))])\n\nmodel = Sequential([\n Dense(32, input_shape=(len(tn.metrics),),activation='relu'),\n Dense(10),\n Dense(1,activation='sigmoid')\n])\n\nmodel.compile(loss='binary_crossentropy',\n optimizer='rmsprop',\n metrics=['binary_accuracy'])\n\nmodel.fit(X_train, Y_train, \n batch_size=len(X_train), epochs=10, verbose=1)","repo_name":"Efrainq07/datathon-test","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"16460350009","text":"import openpyxl\nfrom openpyxl.styles import Alignment, Font, PatternFill\nimport os\n\n# Exporta los resultados a un archivo Excel\ndef exportar_a_excel(trafico_por_usuario, trafico_maximo):\n workbook = openpyxl.Workbook() #Creamos el archivo excel\n sheet = workbook.active\n sheet.title = \"Resultados\"\n\n # Encabezados\n encabezados = [\"Usuario\", \"Tráfico (bytes)\"]\n for col, encabezado in enumerate(encabezados, start=1):\n celda = sheet.cell(row=1, column=col)\n celda.value = encabezado\n celda.font = Font(bold=True) #Texto en negrita\n celda.alignment = Alignment(horizontal=\"center\")\n\n # Datos\n for row, (usuario, trafico) in enumerate(trafico_por_usuario.items(), start=2):\n sheet.cell(row=row, column=1, value=usuario)\n sheet.cell(row=row, column=2, value=trafico)\n\n # Resaltar el usuario con más tráfico\n for row in sheet.iter_rows(min_row=2, max_row=sheet.max_row, min_col=2, max_col=2):\n for cell in row:\n if cell.value == trafico_maximo:\n cell.fill = PatternFill(start_color='6DC36D', end_color='6DC36D', fill_type='solid')\n\n # Guardar archivo\n archivo_salida = \"resultados_trafico.xlsx\"\n\n # Luego de terminar, verifica si el archivo existe y elimínalo si es necesario\n if os.path.exists(archivo_salida):\n os.remove(archivo_salida)\n \n workbook.save(archivo_salida)","repo_name":"santino-rosso/Automatas-Gramaticas","sub_path":"exportarExcel.py","file_name":"exportarExcel.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"28963801057","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nfrom flask import Flask\nfrom flask_jwt_extended import JWTManager\nfrom flask_sqlalchemy import SQLAlchemy\n\ndb = SQLAlchemy()\n\n\ndef create_app():\n app = Flask(__name__)\n app.config.from_object('auth.settings.app.Configuration')\n\n db.init_app(app)\n\n jwt = JWTManager(app)\n\n from auth.api.users import users_blueprint\n app.register_blueprint(users_blueprint)\n\n if app.debug:\n print('Running in debug mode')\n else:\n print('NOT running in debug mode')\n\n @app.before_first_request\n def create_tables():\n db.create_all()\n\n return app\n\n","repo_name":"jbalmant/auth","sub_path":"auth/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"14643900700","text":"from flask import jsonify\nfrom api import anilist, exceptions, presenters\nfrom helpers import latest_chapter_by_anilist\n\ndef manga_lastest_chapter(anilist_manga_id):\n anilist_data = None\n mangaupdates_data = None\n chapters = 0\n\n try:\n anilist_manga = anilist.get_manga(anilist_manga_id)\n anilist_data = {\n \"title\": anilist_manga[\"title\"][\"romaji\"],\n \"id\": anilist_manga_id\n }\n except exceptions.APIException as exception:\n return jsonify({\"error\": str(exception)}), exception.status_code\n\n media = presenters.MediaPresenter(anilist_manga)\n\n if media.status == \"FINISHED\":\n return jsonify(build_data(anilist_data, mangaupdates_data, media.chapters))\n\n chapters, mangaupdates_data = latest_chapter_by_anilist(media)\n\n return jsonify(build_data(anilist_data, mangaupdates_data, chapters))\n\n\ndef build_data(anilist_data, mangaupdates_data, chapters):\n return {\n \"anilist\": anilist_data,\n \"mangaupdates\": mangaupdates_data,\n \"chapters\": chapters\n }\n","repo_name":"crxssed7/reviews","sub_path":"src/apps/manga/routes/latest_chapter.py","file_name":"latest_chapter.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"29898842284","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\nfrom scipy import misc\nfrom skimage import color\nfrom skimage import io\nfrom scipy.misc import toimage\nfrom skimage.filters import roberts, sobel, scharr, prewitt\n\npath1 = 'attachments/'\n\nlisting = os.listdir(path1) \nfor file in listing:\n\tinit_image = misc.imread(path1 + file)\n\ttoimage(init_image).show()\n\n\timage = color.rgb2gray(io.imread(path1 + file));\n\tedge_roberts = roberts(image)\n\tedge_sobel = sobel(image)\n\n\tprint(edge_roberts.shape)\n\tprint(edge_sobel.shape)\n\n\tfig, ax = plt.subplots(ncols=3, sharex=True, sharey=True,\n\t figsize=(8, 4))\n\n\tax[0].imshow(edge_roberts, cmap=plt.cm.gray)\n\tax[0].set_title('Roberts Edge Detection')\n\n\tax[1].imshow(edge_sobel, cmap=plt.cm.gray)\n\tax[1].set_title('Sobel Edge Detection')\n\n\tax[2].imshow(image, cmap=plt.cm.gray)\n\tax[2].set_title('Initial Image')\n\n\tfor a in ax:\n\t a.axis('off')\n\n\tplt.tight_layout()\n\n\tplt.show()","repo_name":"vagad/Computer-Vision-Testing-of-Jewelry","sub_path":"edge_test.py","file_name":"edge_test.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"}
+{"seq_id":"27076631554","text":"from stable_baselines3 import PPO\nfrom env import SneakEnv\nfrom stable_baselines3.common.env_checker import check_env\n\n# create a virtual env for snake game\nenv = SneakEnv(rending=True, dim=500, time_speed=0.1)\nenv.reset()\n\n# check if the env is working\n#check_env(env)\n\n# load a model\nmodels_dir = f\"results/ppo/learning_rate=3e-05_batch_size=64_n_epochs=10_gamma=0.99_gae_lambda=0.95_normalize_advantage=True_ent_coef=0_vf_coef=0.5_max_grad_norm=0.5_seed=None\"\nmodel_path = f\"{models_dir}/100000.zip\"\nmodel = PPO.load(model_path, env=env)\n\n\n# number of simulations\nepisodes = 10\n\n# simulate the model\nfor ep in range(episodes):\n obs = env.reset()\n done = False\n while not done:\n action, _states = model.predict(obs)\n obs, rewards, done, info = env.step(action)\n #env.render()\n #print(rewards)\n\n\nenv.close()\n","repo_name":"vrige/SnakeGame","sub_path":"loading.py","file_name":"loading.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"20586950063","text":"class emptyandfill():\n\n\n #takes the start and goal and the capacity from the run file\n # chs is a flag that determines either just vessels or has 2 vessels and a sink and a tap\n def choose(self, startdiff, goaldiff, capacitydiff, chs):\n self.startdiff = startdiff\n self.goaldiff = goaldiff\n self.capacitydiff = capacitydiff\n self.chs = chs\n\n def start(self):\n # returns the start state that was given from the run file\n return self.startdiff\n\n def goal(self, node):\n # if the node given is equal to the goal it will return True otherwise False\n return self.goaldiff == node\n\n def succ(self, node):\n\n if self.chs == 1:# that means its only vessels\n # two for loops to loop through the vessels\n for key1, value1 in node.items():\n for key2, value2 in node.items():\n\n if (key1 != key2) and (value1 != 0):# when the loops not pointing on the same vessel and the first point is not 0\n newnode = node.copy()\n # self.capacitydiff[(list(newnode.keys()).index(key2))] - value2)\n # this gets the capacity by taking the index of the vessel list and using it in the capacity list...\n # ...then we - the value so we can get the empty space.\n if (value1 <= (self.capacitydiff[(list(newnode.keys()).index(key2))] - value2)):\n # if the empty space in vessel 2 is more than whats in vessel 1 we will just pour\n newnode[key2] = value2 + value1\n newnode[key1] = value1 - value1\n\n yield newnode\n\n elif (value2 != (self.capacitydiff[(list(newnode.keys()).index(key2))])):\n cap = self.capacitydiff[(list(newnode.keys()).index(key2))]\n # we will pour from vessel 1 to vessel 2 until vessel 2 is full or vessel 1 is empty\n newnode[key2] = value2 + (cap - value2)\n newnode[key1] = value1 - (cap - value2)\n\n yield newnode\n\n elif self.chs ==0: # that means that it contains a sink and tap\n # the first part has the same code as the first\n for key1, value1 in node.items():\n for key2, value2 in node.items():\n if (value1 != 0):\n newnode2 = node.copy()\n if (value1 <= (self.capacitydiff[(list(newnode2.keys()).index(key2))] - value2)):\n\n newnode2[key2] = value2 + value1\n newnode2[key1] = value1 - value1\n\n yield newnode2\n\n elif (value2 != (self.capacitydiff[(list(newnode2.keys()).index(key2))])):\n cap = self.capacitydiff[(list(newnode2.keys()).index(key2))]\n\n newnode2[key2] = value2 + (cap - value2)\n newnode2[key1] = value1 - (cap - value2)\n\n yield newnode2\n # this part is for the tap so it fills till full\n newnode2 = node.copy()\n if value1 != (self.capacitydiff[(list(newnode2.keys()).index(key1))]) :\n newnode2[key1] = self.capacitydiff[(list(newnode2.keys()).index(key1))]\n yield newnode2\n # this is the sink so it drains all the water\n newnode2 = node.copy()\n if value1 != 0:\n newnode2[key1] = 0\n yield newnode2\n\n","repo_name":"anasr91/Water_jugs_Python","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"71522933851","text":"\"\"\"\nLow-level relational database / sqlalchemy interaction.\n\nThe actual schemas for database tables are implemented in other files in this subpackage.\n\"\"\"\nfrom __future__ import division, print_function\n\nimport os, sys, io, time, json, threading, gc, re, weakref\nfrom datetime import datetime\nfrom collections import OrderedDict\nimport numpy as np\ntry:\n import queue\nexcept ImportError:\n import Queue as queue\n\nimport sqlalchemy\nfrom distutils.version import LooseVersion\nif LooseVersion(sqlalchemy.__version__) < '1.2':\n raise Exception('requires at least sqlalchemy 1.2')\n\nimport sqlalchemy.inspection\nfrom sqlalchemy import create_engine, Column, Integer, BigInteger, String, Boolean, Float, Date, DateTime, LargeBinary, ForeignKey\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.dialects.postgresql import JSONB\nfrom sqlalchemy.orm import relationship, deferred, sessionmaker, reconstructor\nfrom sqlalchemy.types import TypeDecorator\nfrom sqlalchemy.sql.expression import func\n\n\nfrom .. import config\n\n\nclass NDArray(TypeDecorator):\n \"\"\"For marshalling arrays in/out of binary DB fields.\n \"\"\"\n impl = LargeBinary\n hashable = False\n \n def process_bind_param(self, value, dialect):\n if value is None:\n return b'' \n buf = io.BytesIO()\n np.save(buf, value, allow_pickle=False)\n return buf.getvalue()\n \n def process_result_value(self, value, dialect):\n if value == b'':\n return None\n buf = io.BytesIO(value)\n return np.load(buf, allow_pickle=False)\n\n\nclass JSONObject(TypeDecorator):\n \"\"\"For marshalling objects in/out of json-encoded text.\n \"\"\"\n impl = String\n hashable = False\n \n def process_bind_param(self, value, dialect):\n return json.dumps(value)\n \n def process_result_value(self, value, dialect):\n if value is None:\n return None\n return json.loads(value)\n\n\nclass FloatType(TypeDecorator):\n \"\"\"For marshalling float types (including numpy).\n \"\"\"\n impl = Float\n \n def process_bind_param(self, value, dialect):\n if value is None:\n return None\n return float(value)\n \n #def process_result_value(self, value, dialect):\n #buf = io.BytesIO(value)\n #return np.load(buf, allow_pickle=False)\n\n\ncolumn_data_types = {\n 'int': Integer,\n 'bigint': BigInteger,\n 'float': FloatType,\n 'bool': Boolean,\n 'str': String,\n 'date': Date,\n 'datetime': DateTime,\n 'array': NDArray,\n# 'object': JSONB, # provides support for postges jsonb, but conflicts with sqlite\n 'object': JSONObject,\n}\n\n\ndef make_table_docstring(table):\n \"\"\"Introspect ORM table class to generate a nice docstring.\n \"\"\"\n docstr = ['Sqlalchemy model for \"%s\" database table.\\n' % table.__name__]\n comment = table.__table_args__.get('comment', None)\n if comment is not None:\n docstr.append(comment.strip() + '\\n')\n \n \n insp = sqlalchemy.inspection.inspect(table)\n \n docstr.append(\"Attributes\\n----------\")\n for name, prop in insp.relationships.items():\n docstr.append(\"%s : relationship\" % name)\n if hasattr(prop, 'entity'):\n # entity attribute only available in recent sqlalchemy (>=1.3 ?)\n docstr.append(\" Reference to %s.%s\" % (prop.entity.primary_key[0].table.name, prop.entity.primary_key[0].name))\n for name, col in insp.columns.items():\n typ_str = str(col.type)\n docstr.append(\"%s : %s\" % (name, typ_str))\n if col.comment is not None:\n docstr.append(\" \" + col.comment)\n \n return '\\n'.join(docstr)\n\n\ndef make_table(ormbase, name, columns, base=None, **table_args):\n \"\"\"Generate an ORM mapping class from a simplified schema format.\n\n Columns named 'id' (int) and 'meta' (object) are added automatically.\n\n Parameters\n ----------\n ormbase : ORMBase instance\n The sqlalchemy ORM base on which to create this table.\n name : str\n Name of the table, used to set __tablename__ in the new class\n base : class or None\n Base class on which to build the new table class\n table_args : keyword arguments\n Extra keyword arguments are used to set __table_args__ in the new class\n columns : list of tuple\n List of column specifications. Each column is given as a tuple:\n ``(col_name, data_type, comment, {options})``. Where *col_name* and *comment* \n are strings, *data_type* is a key in the column_data_types global, and\n *options* is a dict providing extra initialization arguments to the sqlalchemy\n Column (for example: 'index', 'unique'). Optionally, *data_type* may be a 'tablename.id'\n string indicating that this column is a foreign key referencing another table.\n \"\"\"\n class_name = ''.join([part.title() for part in name.split('_')])\n\n props = {\n '__tablename__': name,\n '__table_args__': table_args,\n 'id': Column(Integer, primary_key=True),\n }\n\n for column in columns:\n colname, coltype = column[:2]\n \n # avoid weird sqlalchemy issues with case handling\n assert colname == colname.lower(), \"Column names must be all lowercase (got %s.%s)\" % (name, colname)\n \n kwds = {} if len(column) < 4 else column[3]\n kwds['comment'] = None if len(column) < 3 else column[2]\n defer_col = kwds.pop('deferred', False)\n ondelete = kwds.pop('ondelete', None)\n\n if coltype not in column_data_types:\n if not coltype.endswith('.id'):\n raise ValueError(\"Unrecognized column type %s\" % coltype)\n # force indexing on all foreign keys; otherwise deletes can become vrey slow\n kwds['index'] = True\n props[colname] = Column(Integer, ForeignKey(coltype, ondelete=ondelete), **kwds)\n else:\n ctyp = column_data_types[coltype]\n props[colname] = Column(ctyp, **kwds)\n\n if defer_col:\n props[colname] = deferred(props[colname])\n\n props['meta'] = Column(column_data_types['object'])\n\n if base is None:\n new_table = type(class_name, (ormbase,), props)\n else:\n # need to jump through a hoop to allow __init__ on table classes;\n # see: https://docs.sqlalchemy.org/en/latest/orm/constructors.html\n if hasattr(base, '_init_on_load'):\n @reconstructor\n def _init_on_load(self, *args, **kwds):\n base._init_on_load(self)\n props['_init_on_load'] = _init_on_load\n new_table = type(class_name, (base, ormbase), props)\n\n return new_table\n\n\nclass Database(object):\n \"\"\"Methods for doing relational database maintenance via sqlalchemy.\n \n Supported backends: postgres, sqlite.\n \n Features:\n \n * Automatically build/dispose ro and rw engines (especially after fork)\n * Generate ro/rw sessions on demand\n * Methods for creating / dropping databases\n * Clone databases across backends\n \"\"\"\n _all_dbs = weakref.WeakSet()\n default_app_name = (' '.join(sys.argv))[-63:]\n\n def __init__(self, ro_host, rw_host, db_name, ormbase):\n self.ormbase = ormbase\n self._mappings = {}\n \n self.ro_host = ro_host\n self.rw_host = rw_host\n self.db_name = db_name\n self._ro_engine = None\n self._rw_engine = None\n self._maint_engine = None\n self._engine_pid = None # pid of process that created these engines.\n self._ro_sessionmaker = None\n self._rw_sessionmaker = None\n\n self.ro_address = self.db_address(ro_host, db_name)\n self.rw_address = None if rw_host is None else self.db_address(rw_host, db_name)\n self._all_dbs.add(self)\n \n self._default_session = None\n\n @property\n def default_session(self):\n self._check_engines()\n if self._default_session is None:\n self._default_session = self.session(readonly=True)\n return self._default_session\n\n def query(self, *args, **kwds):\n return self.default_session.query(*args, **kwds)\n\n def _find_mappings(self):\n mappings = {cls.__tablename__:cls for cls in self.ormbase.__subclasses__()}\n order = [t.name for t in self.ormbase.metadata.sorted_tables]\n self._mappings = OrderedDict([(t, mappings[t]) for t in order if t in mappings])\n\n def __getattr__(self, attr):\n try:\n # pretty sure I'll regret this later: I want to be able to ask for db.TableName\n # and return the ORM object for a table.\n \n # convert CamelCase to snake_case (credit: https://stackoverflow.com/a/12867228/643629)\n table = re.sub(r'((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))', r'_\\1', attr).lower()\n if table not in self._mappings:\n self._find_mappings()\n return self._mappings[table]\n except Exception:\n return object.__getattribute__(self, attr)\n\n def __repr__(self):\n return \"<%s %s (%s)>\" % (type(self).__name__, self.ro_address, 'ro' if self.rw_address is None else 'rw')\n\n def __str__(self):\n # str(engine) does a nice job of masking passwords\n s = str(self.ro_engine)[7:]\n s = s.rstrip(')')\n s = s.partition('?')[0]\n return s\n\n @property\n def backend(self):\n \"\"\"Return the backend used by this database (sqlite, postgres, etc.)\n \"\"\"\n # maybe ro_engine.name instead?\n return self.ro_host.partition(':')[0]\n\n @classmethod\n def db_address(cls, host, db_name=None, app_name=None):\n \"\"\"Return a complete address for DB access given a host (like postgres://user:pw@host) and database name.\n\n Appends an app name to postgres addresses.\n \"\"\"\n if host.startswith('postgres'):\n app_name = app_name or cls.default_app_name\n return \"{host}/{db_name}?application_name={app_name}\".format(host=host, db_name=db_name, app_name=app_name)\n else:\n # for sqlite, db_name is the file path\n if not host.endswith('/'):\n host = host + '/'\n return host + db_name\n\n def get_database(self, db_name):\n \"\"\"Return a new Database object with the same hosts and orm base, but different db name\n \"\"\"\n return Database(self.ro_host, self.rw_host, db_name, self.ormbase)\n \n def dispose_engines(self):\n \"\"\"Dispose any existing DB engines. This is necessary when forking to avoid accessing the same DB\n connection simultaneously from two processes.\n \"\"\"\n if self._ro_engine is not None:\n self._ro_engine.dispose()\n if self._rw_engine is not None:\n self._rw_engine.dispose()\n if self._maint_engine is not None:\n self._maint_engine.dispose()\n self._ro_engine = None\n self._ro_sessionmaker = None\n self._rw_engine = None\n self._rw_sessionmaker = None\n self._maint_engine = None\n self._engine_pid = None \n self._default_session = None\n \n # collect now or else we might try to collect engine-related garbage in forked processes,\n # which can lead to \"OperationalError: server closed the connection unexpectedly\"\n # Note: if this turns out to be flaky as well, we can just disable connection pooling.\n gc.collect()\n\n @classmethod\n def dispose_all_engines(cls):\n \"\"\"Dispose engines on all Database instances.\n \"\"\"\n for db in cls._all_dbs:\n db.dispose_engines()\n\n def _check_engines(self):\n \"\"\"Dispose engines if they were built for a different PID\n \"\"\"\n if os.getpid() != self._engine_pid:\n # In forked processes, we need to re-initialize the engine before\n # creating a new session, otherwise child processes will\n # inherit and muck with the same connections. See:\n # https://docs.sqlalchemy.org/en/latest/faq/connections.html#how-do-i-use-engines-connections-sessions-with-python-multiprocessing-or-os-fork\n if self._engine_pid is not None:\n print(\"Making new session for subprocess %d != %d\" % (os.getpid(), self._engine_pid))\n self.dispose_engines()\n\n @property\n def ro_engine(self):\n \"\"\"The read-only database engine.\n \"\"\"\n self._check_engines()\n if self._ro_engine is None:\n if self.backend == 'postgresql':\n # use echo=True to log all db queries for debugging\n opts = {'echo': False, 'pool_size': 10, 'max_overflow': 40, 'isolation_level': 'AUTOCOMMIT'}\n else:\n opts = {} \n self._ro_engine = create_engine(self.ro_address, **opts)\n self._engine_pid = os.getpid()\n return self._ro_engine\n \n @property\n def rw_engine(self):\n \"\"\"The read-write database engine.\n \"\"\"\n self._check_engines()\n if self._rw_engine is None:\n if self.rw_address is None:\n return None\n if self.backend == 'postgresql':\n opts = {'pool_size': 10, 'max_overflow': 40}\n else:\n opts = {} \n self._rw_engine = create_engine(self.rw_address, **opts)\n self._engine_pid = os.getpid()\n return self._rw_engine\n \n @property\n def maint_engine(self):\n \"\"\"The maintenance engine.\n \n For postgres DBs, this connects to the \"postgres\" database.\n \"\"\"\n self._check_engines()\n if self._maint_engine is None:\n if self.backend == 'postgresql':\n opts = {'pool_size': 10, 'max_overflow': 40}\n else:\n # maybe just return rw engine for postgres?\n raise Exception(\"no maintenance connection for DB %s\" % self)\n maint_addr = self.db_address(self.rw_host, 'postgres')\n self._maint_engine = create_engine(maint_addr, **opts)\n self._engine_pid = os.getpid()\n return self._maint_engine\n\n # external users should create sessions from here.\n def session(self, readonly=True):\n \"\"\"Create and return a new database Session instance.\n \n If readonly is True, then the session is created using read-only credentials and has autocommit enabled.\n This prevents idle-in-transaction timeouts that occur when GUI analysis tools would otherwise leave transactions\n open after each request.\n \"\"\"\n if readonly:\n if self._ro_sessionmaker is None:\n self._ro_sessionmaker = sessionmaker(bind=self.ro_engine, query_cls=DBQuery)\n return self._ro_sessionmaker()\n else:\n if self.rw_engine is None:\n raise RuntimeError(\"Cannot start read-write DB session; no write access engine is defined (see config.synphys_db_host_rw)\")\n if self._rw_sessionmaker is None:\n self._rw_sessionmaker = sessionmaker(bind=self.rw_engine, query_cls=DBQuery)\n return self._rw_sessionmaker()\n\n def reset_db(self):\n \"\"\"Drop the existing database and initialize a new one.\n \"\"\"\n self.dispose_engines()\n \n self.drop_database()\n self.create_database()\n \n self.create_tables()\n self.grant_readonly_permission()\n\n def list_databases(self):\n engine = self.maint_engine\n with engine.begin() as conn:\n conn.connection.set_isolation_level(0)\n return [rec[0] for rec in conn.execute('SELECT datname FROM pg_catalog.pg_database;')]\n\n @property\n def exists(self):\n \"\"\"Bool indicating whether this DB exists yet.\n \"\"\"\n if self.backend == 'sqlite':\n return os.path.isfile(self.db_name)\n else:\n return self.db_name in self.list_databases()\n\n def drop_database(self):\n if self.backend == 'sqlite':\n if os.path.isfile(self.db_name):\n os.remove(self.db_name)\n elif self.backend == 'postgresql':\n engine = self.maint_engine\n with engine.begin() as conn:\n conn.connection.set_isolation_level(0)\n try:\n conn.execute('drop database %s' % self.db_name)\n except sqlalchemy.exc.ProgrammingError as err:\n if 'does not exist' not in err.args[0]:\n raise\n else:\n raise TypeError(\"Unsupported database backend %s\" % self.backend)\n\n def create_database(self):\n if self.backend == 'sqlite':\n return\n elif self.backend == 'postgresql':\n # connect to postgres db just so we can create the new DB\n engine = self.maint_engine\n with engine.begin() as conn:\n conn.connection.set_isolation_level(0)\n conn.execute('create database %s' % self.db_name)\n # conn.execute('ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO %s;' % ro_user)\n else:\n raise TypeError(\"Unsupported database backend %s\" % self.backend)\n\n def grant_readonly_permission(self):\n if self.backend == 'sqlite':\n return\n elif self.backend == 'postgresql':\n ro_user = config.synphys_db_readonly_user\n\n # grant readonly permissions\n with self.rw_engine.begin() as conn:\n conn.connection.set_isolation_level(0)\n for cmd in [\n ('GRANT CONNECT ON DATABASE %s TO %s' % (self.db_name, ro_user)),\n ('GRANT USAGE ON SCHEMA public TO %s' % ro_user),\n ('GRANT SELECT ON ALL TABLES IN SCHEMA public to %s' % ro_user)]:\n conn.execute(cmd)\n else:\n raise TypeError(\"Unsupported database backend %s\" % self.backend)\n\n def orm_tables(self):\n \"\"\"Return a dependency-sorted of ORM mapping objects (tables) that are described by the ORM base for this database.\n \"\"\"\n # need to re-run every time because we can't tell when a new mapping has been added.\n self._find_mappings()\n return self._mappings\n\n def metadata_tables(self):\n \"\"\"Return an ordered dictionary (dependency-sorted) of {name:Table} pairs, one for \n each table in the sqlalchemy metadata for this database.\n \"\"\"\n return OrderedDict([(t.name, t) for t in self.ormbase.metadata.sorted_tables])\n\n def table_names(self):\n \"\"\"Return a list of the names of tables in this database.\n \n May contain names that are not present in metadata_tables or orm_tables.\n \"\"\"\n return self.ro_engine.table_names()\n\n def create_tables(self, tables=None):\n \"\"\"Create tables in the database from the ORM base specification.\n \n A list of the names of *tables* may be optionally specified to \n create a subset of known tables.\n \"\"\"\n # Create all tables\n meta_tables = self.metadata_tables()\n if tables is not None:\n tables = [meta_tables[t] for t in tables]\n self.ormbase.metadata.create_all(bind=self.rw_engine, tables=tables)\n self.grant_readonly_permission()\n\n def drop_tables(self, tables=None):\n \"\"\"Drop a list of tables (or all ORM-defined tables, if no list is given) from this database.\n \"\"\"\n drops = []\n meta_tables = self.metadata_tables()\n db_tables = self.table_names()\n for k in meta_tables:\n if tables is not None and k not in tables:\n continue\n if k in db_tables:\n drops.append(k)\n if len(drops) == 0:\n return\n \n if self.backend == 'sqlite':\n for table in drops:\n self.rw_engine.execute('drop table %s' % table)\n else:\n self.rw_engine.execute('drop table %s cascade' % (','.join(drops)))\n\n # Seems to be not working correctly \n # def enable_triggers(self, enable):\n # \"\"\"Enable or disable triggers for all tables in this group.\n # \n # This can be used to temporarily disable constraint checking on tables that are under development,\n # allowing the rest of the pipeline to continue operating (for example, if removing an object from \n # the pipeline would violate a foreign key constraint, disabling triggers will allow this constraint\n # to go unchecked).\n # \"\"\"\n # s = Session(readonly=False)\n # enable = 'enable' if enable else 'disable'\n # for table in self.tables.keys():\n # s.execute(\"alter table %s %s trigger all;\" % (table, enable))\n # s.commit()\n\n def vacuum(self, tables=None):\n \"\"\"Cleans up database and analyzes table statistics in order to improve query planning.\n Should be run after any significant changes to the database.\n \"\"\"\n with self.rw_engine.begin() as conn:\n if self.backend == 'postgresql':\n conn.connection.set_isolation_level(0)\n if tables is None:\n conn.execute('vacuum analyze')\n else:\n for table in tables:\n conn.execute('vacuum analyze %s' % table)\n else:\n conn.execute('vacuum')\n\n def bake_sqlite(self, sqlite_file, **kwds):\n \"\"\"Dump a copy of this database to an sqlite file.\n \"\"\"\n sqlite_db = Database(ro_host=\"sqlite:///\", rw_host=\"sqlite:///\", db_name=sqlite_file, ormbase=self.ormbase)\n sqlite_db.create_tables()\n \n last_size = 0\n for table in self.iter_copy_tables(self, sqlite_db, **kwds):\n size = os.stat(sqlite_file).st_size\n diff = size - last_size\n last_size = size\n print(\" sqlite file size: %0.4fGB (+%0.4fGB for %s)\" % (size*1e-9, diff*1e-9, table))\n\n def clone_database(self, dest_db_name=None, dest_db=None, overwrite=False, **kwds):\n \"\"\"Copy this database to a new one.\n \"\"\"\n if dest_db_name is not None:\n assert isinstance(dest_db_name, str), \"Destination DB name bust be a string\"\n assert dest_db is None, \"Only specify one of dest_db_name or dest_db, not both\"\n dest_db = Database(self.ro_host, self.rw_host, dest_db_name, self.ormbase) \n \n if dest_db.exists:\n if overwrite:\n dest_db.drop_database()\n else:\n raise Exception(\"Destination database %s already exists.\" % dest_db)\n\n dest_db.create_database()\n dest_db.create_tables()\n \n for table in self.iter_copy_tables(self, dest_db, **kwds):\n pass\n\n @staticmethod\n def iter_copy_tables(source_db, dest_db, tables=None, skip_tables=(), skip_columns={}, skip_errors=False, vacuum=True):\n \"\"\"Iterator that copies all tables from one database to another.\n \n Yields each table name as it is completed.\n \n This function does not create tables in dest_db; use db.create_tables if needed.\n \"\"\"\n read_session = source_db.session(readonly=True)\n write_session = dest_db.session(readonly=False)\n \n for table_name, table in source_db.metadata_tables().items():\n if (table_name in skip_tables) or (tables is not None and table_name not in tables):\n print(\"Skipping %s..\" % table_name)\n continue\n print(\"Cloning %s..\" % table_name)\n \n # read from table in background thread, write to table in main thread.\n skip_cols = skip_columns.get(table_name, [])\n reader = TableReadThread(source_db, table, skip_columns=skip_cols)\n i = 0\n for i,rec in enumerate(reader):\n try:\n # Note: it is allowed to write `rec` directly back to the db, but\n # in some cases (json columns) we run into a sqlalchemy bug. Converting\n # to dict first is a workaround.\n rec = {k:getattr(rec, k) for k in rec.keys()}\n \n write_session.execute(table.insert(rec))\n except Exception:\n if skip_errors:\n print(\"Skip record %d:\" % i)\n sys.excepthook(*sys.exc_info())\n else:\n raise\n if i%1000 == 0:\n print(\"%d/%d %0.2f%%\\r\" % (i, reader.max_id, (100.0*(i+1.0)/reader.max_id)), end=\"\")\n sys.stdout.flush()\n \n print(\" committing %d rows.. \" % i)\n write_session.commit()\n read_session.rollback()\n \n yield table_name\n\n if vacuum:\n print(\"Optimizing database..\")\n dest_db.vacuum()\n print(\"All finished!\")\n\n\nclass DBQuery(sqlalchemy.orm.Query):\n def dataframe(self):\n \"\"\"Return a pandas dataframe constructed from the results of this query.\n \"\"\"\n import pandas\n return pandas.read_sql(self.statement, self.session.bind)\n \n\nclass TableReadThread(threading.Thread):\n \"\"\"Iterator that yields records (all columns) from a table.\n \n Records are queried chunkwise and queued in a background thread to enable more efficient streaming.\n \"\"\"\n def __init__(self, db, table, chunksize=1000, skip_columns=()):\n threading.Thread.__init__(self)\n self.daemon = True\n \n self.db = db\n self.table = table\n self.chunksize = chunksize\n self.skip_columns = skip_columns\n self.queue = queue.Queue(maxsize=5)\n self.max_id = db.session().query(func.max(table.columns['id'])).all()[0][0] or 0\n self.start()\n \n def run(self):\n try:\n session = self.db.session()\n table = self.table\n chunksize = self.chunksize\n all_columns = [col for col in table.columns if col.name not in self.skip_columns]\n for i in range(0, self.max_id, chunksize):\n query = session.query(*all_columns).filter((table.columns['id'] >= i) & (table.columns['id'] < i+chunksize))\n records = query.all()\n self.queue.put(records)\n self.queue.put(None)\n session.rollback()\n session.close()\n except Exception as exc:\n sys.excepthook(*sys.exc_info())\n self.queue.put(exc)\n raise\n \n def __iter__(self):\n while True:\n recs = self.queue.get()\n if recs is None:\n break\n if isinstance(recs, Exception):\n raise recs\n for rec in recs:\n yield rec\n","repo_name":"timjarsky/aisynphys","sub_path":"aisynphys/database/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":26984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"27869629929","text":"'''\nimage processing opencv PyQt\nhttps://www.youtube.com/watch?v=6zkOrq9YVik&list=PLCC34OHNcOtpmCA8s_dpPMvQLyHbvxocY&index=30\nhttps://github.com/flatplanet/pyqt5_youtube_playlist/blob/main/image.py\n2:37\n'''\n\nimport getpass\nimport cv2 as cv\nimport numpy as np\nfrom PIL import ImageQt\nfrom PyQt5.QtWidgets import QMainWindow, QApplication, QLabel, QFileDialog, QPushButton, \\\n QMenu, QAction, QSlider\n# noinspection PyUnresolvedReferences\nfrom PyQt5 import uic, QtGui, Qt, QtCore # Add the above line so uic is imported\nfrom PyQt5.QtGui import QPixmap, QIcon\nimport sys\n\nimgName = '1.jpg'\nclass UI(QMainWindow):\n def __init__(self):\n super(UI, self).__init__()\n self.disply_width = 1740\n self.display_height = 1580\n # Load the ui file\n uic.loadUi(\"loadImage.ui\", self)\n\n # Define Our Widgets\n self.imagelabel = self.findChild(QLabel, \"imageLabel\")\n self.resizeImgbutton = self.findChild(QPushButton, \"resizeButton\")\n self.featureImgbutton = self.findChild(QPushButton, \"featuresButton\")\n\n\n ####contrast slider\n self.contrastLabel = self.findChild(QLabel, \"contrastLabel\")\n self.contrsSlider = self.findChild(QSlider, \"contrsSlider\")\n self.contrsSlider.valueChanged[int].connect(self.contrsSliderClk)\n self.contrsSlider.sliderReleased.connect(self.sliderReleased)\n\n ####ThresholdlSlider slider\n self.Thrholdlabel = self.findChild(QLabel, \"Thrholdlabel\")\n self.ThresholdlSlider = self.findChild(QSlider, \"ThresholdlSlider\")\n self.ThresholdlSlider.valueChanged[int].connect(self.ThresholdlSliderClk)\n self.ThresholdlSlider.sliderReleased.connect(self.sliderReleased)\n\n #maxCornerSlider\n self.maxCorner=50\n self.maxCornerlabel = self.findChild(QLabel, \"maxCornerlabel\")\n self.maxCornerSlider = self.findChild(QSlider, \"maxCornerSlider\")\n self.maxCornerSlider.valueChanged[int].connect(self.maxCornerSliderClk)\n\n #blockSizeSlider\n\n self.blockSize = 10\n self.blockSizelabel = self.findChild(QLabel, \"blockSizelabel\")\n self.blockSizeSlider = self.findChild(QSlider, \"blockSizeSlider\")\n self.blockSizeSlider.valueChanged[int].connect(self.blockSizeSliderClk)\n\n # minDistSlider\n self.minDistance = 15\n self.minDistlabel = self.findChild(QLabel, \"minDistlabel\")\n self.minDistSlider = self.findChild(QSlider, \"minDistSlider\")\n self.minDistSlider.valueChanged[int].connect(self.minDistSliderClk)\n\n # qualitySlider\n self.qualityLevel = 0.001\n self.qualitylabel = self.findChild(QLabel, \"qualitylabel\")\n self.qualitySlider = self.findChild(QSlider, \"qualitySlider\")\n self.qualitySlider.valueChanged[int].connect(self.qualitySliderClk)\n\n\n ######################### Main Menu #######################\n # main menu Edit\n self.menuEdit = self.findChild(QMenu, \"menuEdit\")\n #Brightness\n brightAction = QAction(QIcon('bright.png'), 'bright', self)\n self.menuEdit.addAction(brightAction)\n brightAction.triggered.connect(self.brightclk)\n #hsv\n hsvAction = QAction(QIcon('hsv.png'), 'hsv', self)\n self.menuEdit.addAction(hsvAction)\n hsvAction.triggered.connect(self. hsvclk)\n\n # main menu File\n self.menuFile = self.findChild(QMenu, \"menuFile\")\n\n #Load Image\n openAction = QAction(QIcon('open.png'), 'Open', self)\n openAction.setShortcut('Ctrl+o')\n openAction.setStatusTip('Load Image')\n self.menuFile.addAction(openAction)\n openAction.triggered.connect(self.loadImbclk)\n\n # Save Image\n saveAction = QAction(QIcon('save.png'), 'Save', self)\n saveAction.setShortcut('Ctrl+s')\n self.menuFile.addAction(saveAction)\n saveAction.triggered.connect(self.saveImbclk)\n\n\n\n\n #Load default image\n\n self.img00 = cv.imread(self.readImagePath() + imgName, cv.IMREAD_COLOR)\n self.img01 = self.convert_cv_qt(self.img00)\n self.imageLabel.setPixmap(self.img01)\n\n # Do something\n self.resizeImgbutton.clicked.connect(self.resizeImbclk)\n self.featureImgbutton.clicked.connect(self.featureImbclk)\n # Show The App\n self.show()\n #################### end of def __init__(self):################\n def minDistSliderClk(self,distance):\n self.minDistance = distance\n c = str(round( self.minDistance, 2))\n self.minDistlabel.setText(\"Dist \" + c)\n self.featureImbclk()\n\n\n def qualitySliderClk(self,qulity):\n self.qualityLevel = qulity/10000\n c = str(round( self.qualityLevel, 2))\n self.qualitylabel.setText(\"qual \" + c)\n self.featureImbclk()\n\n def blockSizeSliderClk(self,bsize):\n self.blockSize = bsize\n c = str(round(bsize, 2))\n self.blockSizelabel.setText(\"bsize \" + c)\n self.featureImbclk()\n\n def maxCornerSliderClk(self, maxC ):\n\n self.maxCorner = maxC*4\n c = str(round( self.maxCorner, 2))\n\n self.maxCornerlabel.setText(\"maxCor \" + c)\n self.featureImbclk()\n\n\n def featureImbclk(self):\n print (self.minDistance, self.qualityLevel )\n\n\n im = self.img00.copy()\n gray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)\n # Find the top corners using the cv2.goodFeaturesToTrack()\n corners = cv.goodFeaturesToTrack(gray, self.maxCorner, self.qualityLevel,\n self.minDistance,self.blockSize)\n print(self.blockSize)\n corners = np.int0(corners)\n for i in corners:\n x, y = i.ravel()\n cv.circle(im, (x, y), 5, (0, 250, 5), -1)\n\n qt_img = self.convert_cv_qt(im)\n self.imageLabel.setPixmap(qt_img)\n\n\n\n\n\n\n\n def ThresholdlSliderClk(self, Threshold):\n\n retval, self.img01 = cv.threshold(self.img00, Threshold, 255, cv.THRESH_BINARY)\n qt_img = self.convert_cv_qt(self.img01)\n self.imageLabel.setPixmap(qt_img)\n\n c = str(round(Threshold, 2))\n self.Thrholdlabel.setText(\"Thres \" + c) # Print contrast value\n\n def contrsSliderClk(self, contrst):\n contrst = 0.01 + contrst/20\n\n matrix1 = np.ones(self.img00.shape) * (contrst)\n #self.img01 = np.uint8(cv.multiply(np.float64(self.img00), matrix1))\n self.img01 = np.uint8(np.clip(cv.multiply(np.float64(self.img00), matrix1), 0, 255))\n qt_img = self.convert_cv_qt(self.img01)\n self.imageLabel.setPixmap(qt_img)\n c= str(round(contrst, 2))\n self.contrastLabel.setText(\"Contrs \" + c) # Print contrast value\n\n\n def sliderReleased(self):\n\n self.img00 = self.img01.copy()\n\n\n def brightclk(self):\n\n matrix = np.ones( self.img00.shape, dtype=\"uint8\") * 50\n self.img00 = cv.add( self.img00, matrix)\n qt_img = self.convert_cv_qt(self.img00)\n self.imageLabel.setPixmap(qt_img)\n\n def resizeImbclk(self):\n\n self.img00 = cv.resize(self.img00, None, fx=2, fy=2)\n qt_img = self.convert_cv_qt(self.img00)\n self.imageLabel.setPixmap(qt_img)\n\n\n\n def hsvclk(self):\n if(len(self.img00.shape) == 3):\n img_hsv = cv.cvtColor(self.img00, cv.COLOR_BGR2HSV)\n h, s, v = cv.split(img_hsv)\n self.img00 = v\n qt_img = self.convert_cv_qt(self.img00)\n self.imageLabel.setPixmap(qt_img)\n\n\n\n def loadImbclk(self):\n\n fname = QFileDialog.getOpenFileName(self, \"Open File\", self.readImagePath(),\n \"All Files (*);;PNG Files (*.png);;Jpg Files (*.jpg)\")\n\n if (fname[0]!= '') :\n self.img00 = cv.imread(fname[0], cv.IMREAD_COLOR)\n qt_img = self.convert_cv_qt( self.img00)\n self.imageLabel.setPixmap(qt_img)\n\n\n\n def convert_cv_qt(self, cv_img):\n \"\"\"Convert from an opencv image to QPixmap\"\"\"\n\n rgb_image = cv.cvtColor(cv_img, cv.COLOR_BGR2RGB)\n h, w, ch = rgb_image.shape\n bytes_per_line = ch * w\n\n Qt_format = QtGui.QImage(rgb_image.data, w, h, bytes_per_line, QtGui.QImage.Format_RGB888)\n keep_aspect_ratio =2\n p = Qt_format.scaled(self.display_height, self.disply_width, keep_aspect_ratio)\n return QPixmap.fromImage(p)\n\n\n def saveImbclk(self):\n\n image = ImageQt.fromqpixmap(self.imagelabel.pixmap())\n fname = QFileDialog.getSaveFileName(self, 'Save File', self.readImagePath(),\n \"All Files (*);;PNG Files (*.png);;Jpg Files (*.jpg)\")\n image.save(fname[0])\n\n\n def readImagePath(self):\n BASE_FOLDER = 'C:/Users/' + getpass.getuser()\n BASE_FOLDER = BASE_FOLDER + '/Pictures/Saved Pictures/'\n path = BASE_FOLDER\n return path\n\n# Initialize The App\napp = QApplication(sys.argv)\nUIWindow = UI()\napp.exec_()\n\n","repo_name":"danizalm05/python01","sub_path":"PyQt/image/readImg.py","file_name":"readImg.py","file_ext":"py","file_size_in_byte":8814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"27289208721","text":"# -*- coding: utf-8 -*-\n\nfrom pymongo import MongoClient\nfrom bson.objectid import ObjectId\nfrom leselys.backends.storage._storage import Storage\n\n\nclass Mongodb(Storage):\n def __init__(self, **kwargs):\n self.database = kwargs.get('database') or 'leselys'\n\n if kwargs.get('database'):\n del kwargs['database']\n self.connection = MongoClient(**kwargs)\n\n self.db = self.connection[self.database]\n\n def get_password(self):\n password = self.get_setting('password')\n if password:\n return password\n return False\n\n def set_password(self, password):\n return self.set_setting('password', self._hash_string(password))\n\n def set_feed_setting(self, feed_id, setting_type, value):\n setting = self.db.feedsettings.find_one({'feed_id': feed_id, 'setting_type': setting_type})\n if setting and setting.get('_id'):\n self.db.feedsettings.save({\n '_id': settings['_id'],\n 'feed_id': feed_id,\n 'setting_type': setting_type,\n 'value': value\n })\n self.db.feedsettings.save({'feed_id': feed_id, 'setting_type': setting_type, 'value': value})\n\n\n def get_feed_setting(self, feed_id, setting_type):\n setting = self.db.feedsettings.find_one({'feed_id': feed_id, 'setting_type': setting_type})\n if setting:\n setting['_id'] = str(setting['_id'])\n return setting\n\n def set_setting(self, key, value):\n self.db.settings.remove({key: {'$exists': True}})\n return str(self.db.settings.save({key: value}))\n\n def get_setting(self, key):\n setting = self.db.settings.find_one({key: {'$exists': True}})\n if setting:\n return setting[key]\n return False\n\n def get_settings(self):\n settings = {}\n for setting in self.db.settings.find():\n settings.update(setting)\n if settings:\n del settings['_id']\n return settings\n\n def add_feed(self, content):\n return str(self.db.feeds.save(content))\n\n def remove_feed(self, _id):\n self.db.feeds.remove(ObjectId(_id))\n for entry in self.db.stories.find({'feed_id': _id}):\n self.db.stories.remove(entry['_id'])\n for setting in self.db.feedsettings.find({'feed_id': _id}):\n self.db.feedsettings.remove(setting['_id'])\n\n def get_feed_by_id(self, _id):\n feed = self.db.feeds.find_one(ObjectId(_id))\n if feed:\n feed['_id'] = str(feed['_id'])\n return feed\n\n def get_feed_by_title(self, title):\n feed = self.db.feeds.find_one({'title': title})\n if feed:\n feed['_id'] = str(feed['_id'])\n return feed\n\n def update_feed(self, _id, content):\n if content['_id']:\n if not isinstance(content['_id'], ObjectId):\n try:\n content['_id'] = ObjectId(content['_id'])\n except:\n raise Exception('Update feed failed, cant find _id')\n return str(self.db.feeds.save(content))\n\n def get_feeds(self):\n res = []\n for feed in self.db.feeds.find():\n feed['_id'] = str(feed['_id'])\n res.append(feed)\n return res\n\n def all_stories(self, ordering, start, stop):\n res = []\n feeds = {}\n for feed in self.db.feeds.find():\n feeds[str(feed['_id'])] = feed['title']\n\n if ordering == \"unreaded\":\n for story in self.db.stories.find({\"read\": False}).sort('last_update', -1).skip(start).limit(stop - start):\n story['_id'] = str(story['_id'])\n story['feed_title'] = feeds[story['feed_id']]\n res.append(story)\n nb_read = len(res)\n if (stop - start) - nb_read <= 0 and stop - start != 0:\n return res\n for story in self.db.stories.find({\"read\": True}).sort('last_update', -1).limit((stop - start) - nb_read):\n story['_id'] = str(story['_id'])\n story['feed_title'] = feeds[story['feed_id']]\n res.append(story)\n elif ordering == \"published\":\n for story in self.db.stories.find().sort('last_update', -1).skip(start).limit(stop - start):\n story['_id'] = str(story['_id'])\n story['feed_title'] = feeds[story['feed_id']]\n res.append(story)\n\n return res\n\n def add_story(self, content):\n return str(self.db.stories.save(content))\n\n def remove_story(self, _id):\n self.db.stories.remove(ObjectId(_id))\n\n def update_story(self, _id, content):\n if content['_id']:\n if not isinstance(content['_id'], ObjectId):\n try:\n content['_id'] = ObjectId(content['_id'])\n except:\n raise Exception('Update story failed, cant find _id')\n return str(self.db.stories.save(content))\n\n def get_story_by_guid(self, feed_id, guid):\n story = self.db.stories.find_one({'guid': guid, 'feed_id': feed_id})\n if story:\n story['_id'] = str(story['_id'])\n return story\n\n def get_story_by_id(self, _id):\n story = self.db.stories.find_one({'_id': ObjectId(_id)})\n if story:\n story['_id'] = str(story['_id'])\n return story\n\n def get_story_by_title(self, feed_id, title):\n story = self.db.stories.find_one({'title': title, 'feed_id': feed_id})\n if story:\n story['_id'] = str(story['_id'])\n return story\n\n def get_feed_unread(self, feed_id):\n res = []\n for feed in self.db.stories.find({'feed_id': feed_id, 'read': False}).sort('last_update', -1):\n feed['_id'] = str(feed['_id'])\n res.append(feed)\n return res\n\n def get_feed_unread_count(self, feed_id=False):\n if not feed_id:\n return self.db.stories.find({'read': False}).count()\n return self.db.stories.find({'feed_id': feed_id, 'read': False}).count()\n\n def get_stories(self, feed_id, ordering, start, stop):\n res = []\n if ordering == \"unreaded\":\n for story in self.db.stories.find({\"feed_id\": feed_id, \"read\": False}).sort('last_update', -1).skip(start).limit(stop - start):\n story['_id'] = str(story['_id'])\n res.append(story)\n nb_read = len(res)\n if (stop - start) - nb_read <= 0 and stop - start != 0:\n return res\n for story in self.db.stories.find({\"feed_id\": feed_id, \"read\": True}).sort('last_update', -1).limit((stop-start)-nb_read):\n story['_id'] = str(story['_id'])\n res.append(story)\n elif ordering == \"published\":\n for story in self.db.stories.find({\"feed_id\": feed_id}).sort('last_update', -1).skip(start).limit(stop - start):\n story['_id'] = str(story['_id'])\n res.append(story)\n\n return res\n","repo_name":"toxinu/leselys","sub_path":"leselys/backends/storage/_mongodb.py","file_name":"_mongodb.py","file_ext":"py","file_size_in_byte":7004,"program_lang":"python","lang":"en","doc_type":"code","stars":228,"dataset":"github-code","pt":"32"}
+{"seq_id":"34367343936","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'''\n@author: Jeff Gould\n\n@description: log operation functions for black lists.\n'''\n\nfrom functions import *\n\ndef parse_lin_logs():\n\n for linlog in os.listdir(lin_log_location):\n\n lin_csv_file = linlog + '_raw_log.csv'\n\n log_path = os.path.join(lin_log_location, linlog)\n csv_out = os.path.join(created_logs_dir, lin_csv_file)\n\n clean_log = clean_logs(log_path, csv_out)\n\n split_by_date(clean_log, linlog)\n\n\n\ndef split_by_date(df, log):\n\n for i in range(3,stop_day):\n\n #print(i)\n fetch_date = datetime.date(2019,7,i)\n\n df_by_date = df[df['Date'] == fetch_date]\n\n #print(df_by_date)\n\n server = log + '_' + str(fetch_date)\n\n #print(server)\n\n file_ops(df_by_date, server)\n\n #find_location(server)\n\n\n\ndef getlogs(log):\n\n try:\n\n if os.path.exists(data_dir):\n log_read = subprocess.run(log,\n timeout=1440,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n if log_read.returncode:\n logging.error('From getlogs(): Error * log not read')\n\n else:\n logging.info(\"From getlogs(): The Log % has Been read.\",\n log[1])\n\n else:\n logging.error('From getlogs(): Directory %s does not exist',\n data_dir)\n sys.exit('EXITING Log Files Not Read')\n\n except Exception as e:\n logging.error('From getlogs(): ' + str(e))\n\n# read in log and clean up data frame\ndef clean_logs(log, server):\n\n headers = ['IP', 'D1', 'D2', 'Date', 'D3',\n 'Options', 'Code', 'Bytes', 'M1', 'M2']\n\n try:\n raw_logs = pd.read_csv(log, sep=\" \", header=None,\n names=headers)\n logging.info('From clean_logs(): Log % has been Loaded to a Pandas DF',\n log)\n\n except Exception as e:\n logging.debug(e)\n\n raw_logs.to_csv(server, index=False)\n\n raw_logs['Date'] = raw_logs['Date'].map(lambda x: str(x)[1:])\n raw_logs['Date'] = pd.to_datetime(raw_logs['Date'],\n format='%d/%b/%Y:%H:%M:%S') #:%H:%M:%S\n\n ip_strip = raw_logs[~raw_logs['IP'].astype(str).str.startswith(':')]\n\n ip_strip['Date'] = ip_strip['Date'].apply(lambda x: x.date())\n\n # strip all irrelvant columns\n stripped_log = ip_strip.drop(ip_strip.columns[[1, 2, 4, 8, 9]],\n axis=1)\n\n logging.info('From clean_logs() Log %s has been cleaned and prepped ' % (log))\n\n return stripped_log\n","repo_name":"Gould25/IPprojoct3113","sub_path":"functions/log_ops.py","file_name":"log_ops.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"72342003930","text":"import requests\n\n__author__ = 'hanson'\n\n\nclass MobSMS:\n def __init__(self):\n self.appkey = '5aec12823819'\n self.verify_url = 'https://api.sms.mob.com:8443/sms/verify'\n\n def verify_sms_code(self, zone, phone, code):\n data = {'appkey': self.appkey, 'phone': phone, 'zone': zone, 'code': code}\n req = requests.post(self.verify_url, data=data, verify=False)\n return req.status_code == 200","repo_name":"qujianxin/LostThingsServer","sub_path":"api/util/check_authentication.py","file_name":"check_authentication.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"26624049817","text":"def find_primes(n):\n # Create a list of integers from 2 to n\n primes = [True] * (n + 1)\n\n # Set 0 and 1 to not be prime\n primes[0] = primes[1] = False\n\n for i in range(2, n + 1):\n if primes[i]:\n for j in range(i * i, n + 1, i):\n primes[j] = False\n\n return [i for i in range(2, n + 1) if primes[i]]\n","repo_name":"adimyth/async-process-using-celery-redis-postgres","sub_path":"celery_app/prime.py","file_name":"prime.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"36797409232","text":"from Scopuli.Interfaces.WEB.Module import WebModule\nfrom Scopuli.Interfaces.MySQL.Schema.Core.Login import Login as dbLogin\n\nfrom flask import request, session, abort, redirect\nfrom werkzeug.local import LocalProxy\n\n\nclass WebAccount(WebModule):\n _instance_name = \"Account\"\n _template_name = \"\"\n _routes = {}\n _dependency = ['Session']\n \n _mode = \"login\" # login | logout | account | restore\n \n \n @property\n def robots_disallow(self):\n return [self._page.url]\n \n \n def load(self):\n self._template_name = \"/account/module.html\"\n self._routes = {\n \"{}\".format(self._page.url) : 'render_account',\n \"{}/settings\".format(self._page.url): 'render_settings',\n \"{}/login\".format(self._page.url) : 'render_login',\n \"{}/logout\".format(self._page.url) : 'render_logout',\n \"{}/restore\".format(self._page.url) : 'render_restore'\n }\n \n \n def render_account(self, caller=None):\n if request._4g_session:\n if request._4g_session.cd_user is None:\n self._mode = \"login\"\n else:\n self._mode = \"account\"\n else:\n abort(1001)\n \n return self.render()\n \n \n def render_settings(self, caller=None):\n if request._4g_session:\n if request._4g_session.cd_user is None:\n self._mode = \"login\"\n else:\n self._mode = \"settings\"\n else:\n abort(1001)\n \n return self.render()\n \n \n def render_login(self, caller=None):\n if request._4g_session:\n if request._4g_session.cd_user is None:\n if str(request.method).lower() == \"post\":\n frm_login = self._form.get('login-form-username', 'email', True, \"\")\n frm_password = self._form.get('login-form-password', 'string', True, \"\")\n frm_remember_me = self._form.get('login-form-remember-me', 'boolean', False, False)\n \n if self.login(login=frm_login, password=frm_password, remember_me=frm_remember_me):\n login_page_url = \"{}/login\".format(self._page.url)\n \n if str(request.referrer)[-(len(login_page_url)):] != login_page_url:\n return redirect(request.referrer)\n else:\n return redirect(self._page.url)\n else:\n return redirect(\"{}/login\".format(self._page.url))\n else:\n self._mode = \"login\"\n else:\n self._mode = \"account\"\n else:\n abort(1001)\n \n return self.render()\n \n \n def render_logout(self, caller=None):\n if request._4g_session:\n if request._4g_session.cd_user is not None:\n self.logout()\n else:\n pass\n \n return redirect(\"/\")\n else:\n abort(1001)\n \n return self.render()\n \n \n def render_restore(self, caller=None):\n if request._4g_session:\n if request._4g_session.cd_user is None:\n if request.method == 'GET':\n self._mode = \"restore\"\n else:\n self._mode = \"account\"\n else:\n abort(1001)\n \n return self.render()\n \n \n @property\n def render_mode(self):\n \"\"\"\n\n :return:\n \"\"\"\n return self._mode\n \n \n def login(self, login, password, remember_me=True):\n \"\"\"\n Функция авторизации пользователя и внесения всех изменений в сессию.\n\n :param login: Логин пользователя, или EMail, или телефон\n :type login: String\n :param password:\n :type password: String\n :param remember_me: Запоминать ли пользователя более чем на 10 мин.\n :type remember_me: Boolean\n :return: True авторизация прошла, иначе False\n :rtype: Boolean\n \"\"\"\n query_user = self._database.query(dbLogin)\n # query_user = query_user.filter(Schema.Login.)\n \n self._database.begin_nested()\n \n try:\n request._4g_session.cd_user = 1\n \n self._database.commit()\n except:\n self._database.rollback()\n \n return True\n \n \n def logout(self):\n \"\"\"\n Функция выхода пользователя, очищаем сессию.\n\n :return: None\n \"\"\"\n self._database.begin_nested()\n \n try:\n request._4g_session.cd_user = None\n \n self._database.commit()\n except:\n self._database.rollback()\n \n \n def restore(self):\n pass","repo_name":"MaxOnNet/scopuli-core-web","sub_path":"Scopuli/WEB/Modules/Account/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"6031817190","text":"from justredis import Redis, Error\n\n\ndef example():\n # Let's connect to localhost:6379 and decode the string results as utf-8 strings.\n r = Redis(decoder=\"utf8\")\n assert r(\"set\", \"a\", \"b\") == \"OK\"\n assert r(\"get\", \"a\") == \"b\"\n assert r(\"get\", \"a\", decoder=None) == b\"b\" # But this can be changed on the fly\n\n with r.modify(database=1) as r1:\n assert r1(\"get\", \"a\") == None # In this database, a was not set to b\n\n # Here we can use a transactional set of commands\n with r.connection(key=\"a\") as c: # Notice we pass here a key from below (not a must if you never plan on connecting to a cluster)\n c(\"multi\")\n c(\"set\", \"a\", \"b\")\n c(\"get\", \"a\")\n assert c(\"exec\") == [\"OK\", \"b\"]\n\n # Or we can just pipeline them.\n with r.connection(key=\"a\") as c:\n result = c((\"multi\",), (\"set\", \"a\", \"b\"), (\"get\", \"a\"), (\"exec\",))[-1]\n assert result == [\"OK\", \"b\"]\n\n # Here is the famous increment example\n # Notice we take the connection inside the loop, this is to make sure if the cluster moved the keys, it will still be ok.\n while True:\n with r.connection(key=\"counter\") as c:\n c(\"watch\", \"counter\")\n value = int(c(\"get\", \"counter\") or 0)\n c(\"multi\")\n c(\"set\", \"counter\", value + 1)\n if c(\"exec\") is None:\n continue\n value += 1 # The value is updated if we got here\n break\n\n # Let's show some publish & subscribe commands, here we use a push connection (where commands have no direct response)\n with r.connection(push=True) as p:\n p(\"subscribe\", \"hello\")\n assert p.next_message() == [\"subscribe\", \"hello\", 1]\n assert p.next_message(timeout=0.1) == None # Let's wait 0.1 seconds for another result\n r(\"publish\", \"hello\", \", World !\")\n assert p.next_message() == [\"message\", \"hello\", \", World !\"]\n\n\nif __name__ == \"__main__\":\n example()\n","repo_name":"tzickel/justredis","sub_path":"tests/test_example.py","file_name":"test_example.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"32"}
+{"seq_id":"18927911395","text":"\"\"\"Coordinator class for the C3 panel entities.\"\"\"\nimport asyncio\nimport logging\nfrom datetime import timedelta\nfrom typing import Any, TypeVar\n\nimport async_timeout\nimport requests\nfrom c3 import C3, rtlog\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.const import (\n CONF_SCAN_INTERVAL,\n MAJOR_VERSION,\n MINOR_VERSION,\n Platform,\n)\nfrom homeassistant.core import HomeAssistant\nfrom homeassistant.helpers import device_registry as dr\nfrom homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed\n\nfrom .const import (\n CONF_AUX_ON_DURATION,\n CONF_UNLOCK_DURATION,\n DATA_C3_COORDINATOR,\n DEFAULT_AUX_ON_DURATION,\n DEFAULT_POLL_INTERVAL,\n DEFAULT_UNLOCK_DURATION,\n DOMAIN,\n MANUFACTURER,\n)\n\n_DataT = TypeVar(\"_DataT\")\n_LOGGER = logging.getLogger(__name__)\n\n\nclass C3Coordinator(DataUpdateCoordinator):\n \"\"\"ZKAccess C3 panel coordinator.\"\"\"\n\n def __init__(\n self,\n hass: HomeAssistant,\n config_entry: ConfigEntry,\n host: str,\n port: int,\n password: str,\n ) -> None:\n \"\"\"Initialize C3 coordinator.\"\"\"\n super().__init__(\n hass,\n _LOGGER,\n # Name of the data. For logging purposes.\n name=f\"ZKAccess C3 @ {host}:{port}\",\n # Polling interval. Will only be polled if there are subscribers.\n update_interval=timedelta(\n seconds=config_entry.options.get(CONF_SCAN_INTERVAL)\n or DEFAULT_POLL_INTERVAL\n ),\n )\n\n self._password = password\n self._poll_timeout_count = 0\n self._entry_id = config_entry.entry_id\n self._attr_unique_id = self._entry_id\n\n self._status = rtlog.DoorAlarmStatusRecord()\n self._door_events: dict[rtlog.EventRecord, Any] = {}\n self.unlock_duration: int = (\n config_entry.options.get(CONF_UNLOCK_DURATION) or DEFAULT_UNLOCK_DURATION\n )\n self.aux_on_duration: int = (\n config_entry.options.get(CONF_AUX_ON_DURATION) or DEFAULT_AUX_ON_DURATION\n )\n\n config_entry.async_on_unload(\n config_entry.add_update_listener(self._update_options_listener)\n )\n\n self.c3_panel: C3 = C3(host, port)\n if self.c3_panel.connect(password):\n hass.data[DOMAIN][self._entry_id] = {\n DATA_C3_COORDINATOR: self,\n Platform.LOCK: list(range(1, self.c3_panel.nr_of_locks + 1)),\n Platform.SWITCH: list(range(1, self.c3_panel.nr_aux_out + 1)),\n Platform.BINARY_SENSOR: list(range(1, self.c3_panel.nr_aux_in + 1)),\n }\n\n device_registry = dr.async_get(hass)\n device_info = {\n \"config_entry_id\": self._entry_id,\n \"identifiers\": {(DOMAIN, self.c3_panel.serial_number)},\n \"manufacturer\": MANUFACTURER,\n \"model\": \"C3/inBio\",\n \"name\": (self.c3_panel.device_name if not \"?\" else \"\")\n or config_entry.title,\n \"sw_version\": self.c3_panel.firmware_version,\n }\n if MAJOR_VERSION >= 2023 and MINOR_VERSION >= 11:\n device_info[\"serial_number\"] = self.c3_panel.serial_number\n device_registry.async_get_or_create(**device_info)\n else:\n raise UpdateFailed(f\"Connection to C3 {host} failed.\")\n\n @property\n def status(self) -> rtlog.DoorAlarmStatusRecord:\n \"\"\"Return the last received Door/Alarm status.\"\"\"\n return self._status\n\n def last_door_event(self, door_id: int) -> rtlog.EventRecord:\n \"\"\"Return the last received Event.\"\"\"\n return (\n self._door_events[door_id]\n if door_id in self._door_events\n else rtlog.EventRecord()\n )\n\n async def _update_options_listener(\n self, hass: HomeAssistant, config_entry: ConfigEntry\n ):\n \"\"\"Handle options update.\"\"\"\n self.update_interval = timedelta(\n seconds=config_entry.options.get(CONF_SCAN_INTERVAL)\n or DEFAULT_POLL_INTERVAL\n )\n self.unlock_duration = (\n config_entry.options.get(CONF_UNLOCK_DURATION) or DEFAULT_UNLOCK_DURATION\n )\n self.aux_on_duration = (\n config_entry.options.get(CONF_AUX_ON_DURATION) or DEFAULT_AUX_ON_DURATION\n )\n\n def _poll_rt_log(self) -> _DataT:\n \"\"\"Fetch RT log from C3.\"\"\"\n try:\n if not self.c3_panel.is_connected():\n self.c3_panel.connect(self._password)\n except ValueError as ex:\n raise UpdateFailed(f\"Invalid response received: {ex}\") from ex\n except Exception as ex:\n raise UpdateFailed(f\"Error communicating with API: {ex}\") from ex\n\n updated = False\n\n try:\n last_record_is_status = False\n while not last_record_is_status:\n logs = self.c3_panel.get_rt_log()\n for log in logs:\n if isinstance(log, rtlog.DoorAlarmStatusRecord):\n self._status = log\n last_record_is_status = True\n elif isinstance(log, rtlog.EventRecord):\n if log.door_id > 0:\n self._door_events[log.door_id] = log\n updated = True\n except ConnectionError as ex:\n _LOGGER.error(\"Realtime log update failed: %s\", ex)\n\n if updated:\n self._poll_timeout_count = 0\n else:\n # Disconnect explicitly, so a re-connect can be performed at the next attempt\n try:\n self.c3_panel.disconnect()\n finally:\n pass\n\n return updated\n\n async def _async_update_data(self) -> _DataT:\n \"\"\"Fetch RT log with handling of timeouts.\n\n The RT logs are retrieved, with a small timeout of 5 seconds.\n When multiple consecutive fetch actions fail, the connection to the panel\n is actively disconnected to reset the connection at the next poll attempt.\n \"\"\"\n try:\n async with async_timeout.timeout(5):\n return self._poll_rt_log()\n except (asyncio.TimeoutError, requests.exceptions.Timeout):\n self._poll_timeout_count = self._poll_timeout_count + 1\n if self._poll_timeout_count > 5:\n # Disconnect explicitly, so a re-connect can be performed at the next attempt\n try:\n self.c3_panel.disconnect()\n finally:\n pass\n raise\n","repo_name":"vwout/hass-zkaccess_c3","sub_path":"custom_components/zkaccess_c3/coordinator.py","file_name":"coordinator.py","file_ext":"py","file_size_in_byte":6646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"73419510171","text":"from math import *\nfrom ploting_utilities import *\nimport numpy as np\n\nDEFAULT_KEY = -1\nSTART_KEY = 0\n\n# !! NB_EVAL_PTS > NB_COEFF !!\nNB_COEFF = 3\nNB_EVAL_PTS = 5\n\nconditionsPowered = []\npreviousKey = START_KEY\n\n\n\n\n\n\ndef FFT(samples):\n\n n = len(samples)\n\n if n==1:\n return samples\n\n fourierTransform = [10] * n\n\n a = [s for s in range(0,n,2)]\n b = [s for s in range(1,n,2)]\n\n A = FFT(a)\n B = FFT(b)\n\n omegaN = exp(-2*pi/n)\n omega = 1\n\n for k in range(0,int(n/2)):\n fourierTransform[k] = A[k] + omega*B[k]\n fourierTransform[int(n/2)+k] = A[k] - omega*B[k]\n omega *= omegaN\n\n return fourierTransform\n\n\ndef tests():\n sample = []\n for i in range(0,100):\n sample.append(cos(i))\n\n plot2D(range(0,100),sample)\n\n fft = FFT(sample)\n plot2D(range(0,100),fft)\n print(len(fft))\n\n pause()\n\ndef powerConditions(currentConditions, nbCoeff=NB_COEFF, key=DEFAULT_KEY):\n\n global previousKey\n global conditionsPowered\n\n if previousKey == key:\n return conditionsPowered\n\n powered = np.array([1]*len(currentConditions))\n poweredOne = np.array([currentConditions[x] for x in range(len(currentConditions))])\n powered = np.vstack( (powered.T, poweredOne) ).T\n\n for i in range(2,nbCoeff):\n raiseCoeff = lambda x: x[1]*x[-1]\n newColumn = [raiseCoeff(x) for x in powered]\n powered = np.vstack( (powered.T, newColumn) ).T\n return powered\n\ndef testExpectedOffset():\n t= np.array([[10,\t20,\t101],\n [11,\t30,\t105],\n [12,\t40,\t108]])\n d= powerConditions([2,3,4])\n print(sum(sum(np.dot(d,t))))\n\n\ndef getExpectedOffset(currentConditions, interpolationMatrix, key=DEFAULT_KEY):\n\n conditionsPowered = powerConditions(currentConditions,NB_COEFF,key)\n return sum(sum(np.multiply(conditionsPowered,interpolationMatrix)))\n\n\ndef getCoeff(x,y):\n\n n = len(x)\n coeffs = []\n C = powerConditions(x,len(x))\n invC = np.linalg.inv(C)\n coeffs = np.dot(invC,y)\n return coeffs\n\n\ndef getXs(rangeC, xToChange):\n\n xS = []\n delta = rangeC[1]-rangeC[0]\n offset = delta/(NB_EVAL_PTS - 1)\n current = rangeC[0]\n for i in range(NB_EVAL_PTS):\n currentMod = current\n if current-offset < xToChange and current+offset > xToChange:\n if xToChange > current:\n currentMod = (xToChange - current + offset) / 2 + (current - offset)\n else:\n currentMod = (current + offset) - (current + offset - xToChange) / 2\n\n xS.append(currentMod)\n current += offset\n\n return xS\n\n\ndef recomputeInterpolationMatrix(currentCondition, newValue, interpolationMatrix, ranges):\n\n for i in range(len(interpolationMatrix)):\n xValueToChange = currentCondition[i]\n currentCoeffs = interpolationMatrix[i]\n currentRange = ranges[i]\n currentXs = getXs(currentRange,xValueToChange)\n currentYs = []\n for x in currentXs:\n y = getExpectedOffset([x],[currentCoeffs])\n currentYs.append(y)\n\n currentXs.append(xValueToChange)\n currentYs.append(newValue)\n\n interpolationMatrix[i] = getCoeff(currentXs,currentYs)\n\n return interpolationMatrix\n\n\ndef correctInterpolationMatrix(currentCondition, offsetRecorded, interpolationMatrix, ranges):\n # Compute expected offset\n offsetExpected = getExpectedOffset(currentCondition,interpolationMatrix)\n\n # Make the difference with the recorded offset\n newValueCurrent = (offsetExpected + offsetRecorded) / 2\n\n return interpolationMatrix\n\n#recomputeInterpolationMatrix([2],2,[[1,0,0]],[[0,3]])\n\n# This algorithm comes from a nice article of http://blog.ivank.net/\n# Spline computation\ndef evaluateSpline(x, xs, ys, ks):\n\n i=1\n while ivali:\n i_max = i\n vali = A[i][k]\n swapRows(A, k, i_max)\n\n if A[i_max][k] == 0:\n print(\"matrix is singular!\")\n\n # for all rows below pivot\n for i in range(k+1, m, 1):\n for j in range(k+1, m+1, 1):\n A[i][j] = A[i][j] - A[k][j] * (A[i][k] / A[k][k])\n A[i][k] = 0\n\n for i in range(m-1,0,-1):\n v = A[i][m] / A[i][i]\n x[i] = v\n for j in range(i-1,0,-1):\n A[j][m] -= A[j][i] * v\n A[j][i] = 0\n\n return x\n\ndef getDerivatives(xs, ys):\n\n n= len(xs)-1\n A = [[0]*(n+2) for i in range(n+1)]\n\n for i in range(1,n):\n\n A[i][i-1] = 1/(xs[i] - xs[i-1])\n A[i][i] = 2 * (1/(xs[i] - xs[i-1]) + 1/(xs[i+1] - xs[i]))\n\n A[i][i+1] = 1/(xs[i+1] - xs[i])\n\n A[i][n+1] = 3*( (ys[i]-ys[i-1])/ ((xs[i] - xs[i-1])*(xs[i] - xs[i-1]))\n +(ys[i+1]-ys[i])/ ((xs[i+1] - xs[i])*(xs[i+1] - xs[i])))\n\n A[0][0 ] = 2/(xs[1] - xs[0])\n A[0][1 ] = 1/(xs[1] - xs[0])\n A[0][n+1] = 3 * (ys[1] - ys[0]) / ((xs[1]-xs[0])*(xs[1]-xs[0]))\n\n A[n][n-1] = 1/(xs[n] - xs[n-1])\n A[n][n ] = 2/(xs[n] - xs[n-1])\n A[n][n+1] = 3 * (ys[n] - ys[n-1]) / ((xs[n]-xs[n-1])*(xs[n]-xs[n-1]))\n\n return solve(A)\n\ndef standardRange():\n tab = list(range(-200,201,40))\n return tab\n\ndef modifyStandardRange(xn):\n\n j = 0\n xs = standardRange()\n for i in range(len(xs)):\n if abs(xs[i]-xn) < 20:\n xs[i] = xn\n j= i\n\n return xs,j\n\ndef goodCondition(condition):\n\n if condition > 200:\n current = 200\n elif condition < -200:\n current = -200\n else:\n current = condition\n return current\n\n\ndef getNewIdentity(currentConditions, offsetRecorded, oldIdentity):\n\n for i in range(len(currentConditions)):\n itemConditionCurrent = goodCondition(currentConditions[i])\n\n (xs,j) = modifyStandardRange(itemConditionCurrent)\n ks = getDerivatives(xs,oldIdentity[i])\n valuesSpline = []\n for k in xs:\n currentOffset = evaluateSpline(itemConditionCurrent,xs,oldIdentity[i],ks)\n valuesSpline.append(currentOffset)\n\n\n newValue = (offsetRecorded + valuesSpline[j]) / 2\n valuesSpline[j] = newValue\n\n newValuesSpin = []\n ks = getDerivatives(xs,valuesSpline)\n for k in standardRange():\n currentOffset = evaluateSpline(k,xs,valuesSpline,ks)\n newValuesSpin.append(currentOffset)\n\n oldIdentity[i] = newValuesSpin\n\n return oldIdentity\n\ndef evaluateOffset(currentConditions, identity):\n\n sumOffset = 0\n\n for i in range(len(currentConditions)):\n condition = goodCondition(currentConditions[i])\n\n ks = getDerivatives(standardRange(), identity[i])\n sumOffset += evaluateSpline(condition,standardRange(),identity[i],ks)\n\n return sumOffset / len(currentConditions)\n\n'''xs = [0,1,2]\nys = [1,2,1]\nks = getDerivatives(xs,ys)\nfor i in range(0,20,1):\n print(str(i/10.0)+' '+str(evaluateSpline(i/10.0,xs,ys,ks)))'''\n","repo_name":"DamienGallet/stockForecast","sub_path":"interpolationEngine.py","file_name":"interpolationEngine.py","file_ext":"py","file_size_in_byte":7337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"25544767839","text":"#Camren Mawhinney\n#Final Project\n#Sept 2021\n\nfrom tkinter import *\nroot = Tk()\nroot.title(\"Camren's Pizza\") #Window title Camren's Pizza\nv = DoubleVar()\nmenubar = Menu(root)\nlabel_1 = Label(root, text=\"Name\") #input name and address\nlabel_2 = Label(root, text=\"Address\")\nx=StringVar()\ny=StringVar()\nentry_1 = Entry(root,textvariable=x)\nentry_2 = Entry(root,textvariable=y)\nlabel_1.pack(anchor=N, side=LEFT, fill=X, expand=YES)\nentry_1.pack(side=TOP, anchor=W, fill=X, expand=YES)\nlabel_2.pack(side=LEFT,anchor=N, fill=X, expand=YES)\nentry_2.pack(side=TOP, anchor=W, fill=X, expand=YES)\nc = Checkbutton(root, text = \"Save my order for future use\")\nc.pack(side=BOTTOM)\nsz = Label(root, text=\"Select the pizza size\", bg=\"black\", fg=\"white\")\nsz.pack(side=TOP, anchor=W, expand=YES)\nsmall = Radiobutton(root, text=\"Small ($7.95)\", variable=v, value=7.95).pack(anchor=W)\nmedium = Radiobutton(root, text=\"Medium ($9.95)\", variable=v, value=9.95).pack(anchor=W)\nlarge = Radiobutton(root, text=\"Large ($13.99)\", variable=v, value=13.99).pack(anchor=W)\ntp = Label(root, text=\"Select toppings. ($0.75 each)\", bg=\"black\", fg=\"white\")\ntp.pack(anchor=W)\nToppings = {\"Pepperoni\":1, \"Extra Cheese\":2, \"Olives\":3, \"Tomatoes\":4, \"Grilled chicken\":5,\"Bacon\":6}\ns = StringVar()\ns.set(\"Toppings\")\nc=IntVar()\nar=[]\nfor i in range (6):\n ar.append(DoubleVar()) # creating an array of DoubleVar to store radiobtn values\ni=0\nfor te in Toppings:\n b = Radiobutton(root, text=te, variable=ar[i],value=0.75) # setting the radio btns\n b.pack()\n i+=1\n #var1 = te+ str(int)\n #var1 = IntVar()\n\n #Checkbutton(root, text=te, variable=var1).pack()\n \n \na=StringVar()\ntip = Label(root, text=\"Tip amount\").pack()\nEntry(root,textvariable=a).pack()\ndef display():\n name=x.get()\n adress=y.get()\n p_cost=v.get()\n s=0\n for i in ar: # calculating topping bill\n s+=i.get()\n tip=int(a.get())\n total=s+p_cost+tip\n Label(root,text=\"...bill...\", bg=\"black\", fg=\"white\").pack()\n Label(root, text=\"Name - \"+name).pack()\n Label(root, text=\"Address - \"+adress).pack()\n Label(root, text=\"Pizza cost - \"+str(p_cost)).pack()\n Label(root, text=\"Topping cost - \"+str(s)).pack()\n Label(root, text=\"Tip - \"+str(tip)).pack()\n Label(root, text=\"Total - \"+str(total)).pack()\nbutton1=Button(root,text=\"submit\",command=display,width=10).pack()\nroot.mainloop()\n","repo_name":"CamrenMawhinney/Final-Project","sub_path":"FinalProject.py","file_name":"FinalProject.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"35530491779","text":"#! /usr/bin/env python3\n''' A simple pygame intro example '''\nimport pygame\n\npygame.init()\n\nsize = width, height = 1024, 768\nspeed = [3,2]\nblack = (0, 0, 0)\n\nscreen = pygame.display.set_mode(size)\npygame.display.set_caption('Logo Bouncer')\nlogo = pygame.image.load('pygame_logo.gif')\nlogo_width, logo_height = logo.get_size()\nlogo_x = logo_y = 0\n\nrunning = True\nwhile running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n \n logo_x += speed[0]\n logo_y += speed[1]\n \n if logo_x < 0 or logo_x + logo_width > width:\n speed[0] = -speed[0]\n if logo_y < 0 or logo_y + logo_height > height:\n speed[1] = -speed[1]\n \n screen.fill(black)\n screen.blit(logo, (logo_x, logo_y))\n pygame.display.flip()\n","repo_name":"SimiaoZhao/test","sub_path":"code/intro1.py","file_name":"intro1.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"74910885850","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport scipy.stats as ss\nabspath = os.path.abspath(__file__)\ndname = os.path.dirname(abspath)\nos.chdir(dname)\nos.chdir('../..')\n\n#ATTENTION!!!!! If switching from ploting the densities of noise to speech, please copy paste the folder which contains the previously generated\n#plots to somewhere else. Basically, this file overwrites the existing plots. ATTENTION!!!\n\n# Change to 'Others/Creating-Figures/LTA_PSD_SPEECH.txt' if the univariate GMM density of speech is desired. LTA stands for long term average.\nLTA_file = open(\"Others/Creating-Figures/LTA_PSD_NOISE.txt\", \"r\") #make sure this is at the same location as this file\nLTA_lines = LTA_file.readlines()\nLTA_file.close()\n\n\n#Change to 'Models-Setup/GAN-Setup/Speech_GMM_Component_probabilities.txt' and similar if the GMMs of speech are required.\nMeans_file = open('Models-Setup/GAN-Setup/Noise_GMM_codebook.txt','r')\nMeans_lines = Means_file.readlines()\nMeans_file.close()\n\nCovariances_file = open('Models-Setup/GAN-Setup/Noise_GMM_Component_variance.txt','r')\nCovariances_lines = Covariances_file.readlines()\nCovariances_file.close()\n\nComponent_probs_file = open('Models-Setup/GAN-Setup/Noise_GMM_Component_probabilities.txt','r')\nComponent_probs_lines = Component_probs_file.readlines()\nComponent_probs_file.close()\n\nos.makedirs('Others/Creating-Figures/GMM_Density_Plots',exist_ok=True)\n\nstring_list = LTA_lines[0].split()\nMeans_list = Means_lines[0].split()\nCovariances_list = Covariances_lines[0].split()\nComponent_probs_list = Component_probs_lines[0].split()\nLong_term_average_accross_all_data = np.zeros((len(LTA_lines),len(string_list)))\nMeans = np.zeros((len(Means_lines),len(Means_list)))\nCovariances = np.zeros((len(Covariances_lines),len(Covariances_list)))\nComponent_probs = np.zeros((len(Component_probs_lines),len(Component_probs_list)))\n\nfor frequency_bin in range (0,len(Means_lines)):\n Means_list = Means_lines[frequency_bin].split()\n for component in range (0, len(Means_list)):\n if Means_list[component] == \"nan\":\n Means[frequency_bin,component] = 0\n else:\n Means[frequency_bin,component] = float(Means_list[component])\n\n\nfor frequency_bin in range (0,len(Covariances_lines)):\n Covariances_list = Covariances_lines[frequency_bin].split()\n for component in range (0, len(Covariances_list)):\n if Covariances_list[component] == \"nan\":\n Covariances[frequency_bin,component] = 0\n else:\n Covariances[frequency_bin,component] = float(Covariances_list[component])\n\n\nfor frequency_bin in range (0,len(Component_probs_lines)):\n Component_probs_list = Component_probs_lines[frequency_bin].split()\n for component in range (0, len(Component_probs_list)):\n if Component_probs_list[component] == \"nan\":\n Component_probs[frequency_bin,component] = 0\n else:\n Component_probs[frequency_bin,component] = float(Component_probs_list[component])\n\n\n\nfor frequency_bin in range (0,len(LTA_lines)):\n string_list = LTA_lines[frequency_bin].split()\n for component in range (0, len(string_list)):\n if string_list[component] == \"nan\":\n Long_term_average_accross_all_data[frequency_bin,component] = 0\n else:\n Long_term_average_accross_all_data[frequency_bin,component] = float(string_list[component])\n\n\n\nfor frequency_bin in range (0,len(LTA_lines)):\n Mean_PSD_per_frequency_bin = Long_term_average_accross_all_data[frequency_bin,:]\n GMM_Means_per_frequency_bin = Means[frequency_bin,:]\n GMM_Covariances_per_frequency_bin = Covariances[frequency_bin,:]\n GMM_Component_probs_per_frequency_bin = Component_probs[frequency_bin,:]\n Minimum_PSD_val = min(Mean_PSD_per_frequency_bin)\n Maximum_PSD_val = max(Mean_PSD_per_frequency_bin)\n\n x = np.linspace(Minimum_PSD_val-Minimum_PSD_val,Maximum_PSD_val, 10000)\n pdfs = [p * ss.norm.pdf(x, mu, sd) for mu, sd, p in zip(GMM_Means_per_frequency_bin, GMM_Covariances_per_frequency_bin, GMM_Component_probs_per_frequency_bin)]\n density = np.sum(np.array(pdfs), axis=0)\n #Adjust the figure size as required.\n plt.figure(figsize=(15,10))\n plt.plot(x,density)\n plt.plot(Mean_PSD_per_frequency_bin,np.zeros_like(Mean_PSD_per_frequency_bin),marker='+',c='blue',lw=0)\n plt.xlabel('LTA PSD')\n plt.ylabel(\"Density\")\n plt.xscale('log')\n plt.yscale('log')\n plt.savefig('Others/Creating-Figures/GMM_Density_Plots/'+'Frequency_bin'+str(frequency_bin)+'_GMM_Density'+'.png')\n plt.close()\n pass\n\n\n","repo_name":"echa548/Speech-enhancement-through-a-CNN-driven-codebook-GAN","sub_path":"Compendium/Others/Creating-Figures/Plot_GMMs.py","file_name":"Plot_GMMs.py","file_ext":"py","file_size_in_byte":4377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"72353311451","text":"#!/usr/bin/env python\n\nimport plotly\nimport sys\nimport pandas as pd\nimport geocoder\nimport plotly.plotly as py\nimport plotly.graph_objs as go\nimport plotly.offline as offline\nimport plotly.tools as tls\n# custom module\nsys.path.append(\"tools\")\nimport preprocess\n\n# set online credentials for plotly\nplotly.tools.set_credentials_file(username='ddewitz',\n api_key='0UJR1yePEy3DEI3Z3grC')\n\n\ndef main():\n # load cleaned data set\n crime_df = preprocess.preprocess(clean=True)\n\n # make the map - save html to local machine\n make_college_crime_map(crime_df, online=True, local=True)\n\n\ndef make_college_crime_map(df, local=False, online=False):\n '''create plotly bubble map\n\n Args:\n df: clean dataset ready to map\n local: True, write to local html\n online: True, write to Plotly portfolio\n\n Local and Online maps also have slightly different designs,\n which is the reason for a special arg\n '''\n # these are the crimes I'm mapping\n crime_list = ['Robbery', 'Fondling', 'Assault', 'Rape']\n\n # will append each crime category, or trace, to this list\n crime_traces = []\n\n # set colors for crime ledgend - indexed in for loop\n colors = [\"rgb(166,206,227)\",\"rgb(233,194,125)\",\"rgb(31,120,180)\",\"rgb(116,97,26)\"]\n\n for i, crime in enumerate(crime_list):\n\n # set crime specific attributes\n if crime == 'Rape':\n hover_text = 'RAPE16_hover_text'\n opacity_attr = 1\n\n if crime == 'Fondling':\n hover_text = 'FONDL16_hover_text'\n opacity_attr = 0.9\n\n if crime == 'Robbery':\n hover_text = 'ROBBE16_hover_text'\n opacity_attr = 0.6\n\n if crime == 'Assault':\n hover_text = 'AGG_A16_hover_text'\n opacity_attr = 0.6\n\n # subset df where school equals sector cd\n df_sub = df[['INSTNM', 'lat', 'long', crime, hover_text]]\n\n # do not show school if a crime has not occured on its campus\n df_sub = df_sub[df_sub[crime] > 0]\n\n crime_bubbles = dict(\n type = 'scattergeo',\n locationmode = 'USA-states',\n lon = df_sub[\"long\"],\n lat = df_sub[\"lat\"],\n text = df_sub[hover_text],\n opacity = opacity_attr,\n name = crime,\n marker = dict(\n size = df_sub[crime] * 20,\n color = colors[i],\n line = dict(width=0.5, color='rgb(40,40,40)'),\n sizemode = 'area'\n ),\n )\n # appended trace to list of traces\n crime_traces.append(crime_bubbles)\n\n # the legend and annotations between the local\n # html and the more sharable plotly iframe are pretty\n # different, so that's the reason for this if statement\n if online:\n layout = dict(\n autosize = True,\n showlegend = True,\n legend = dict(\n traceorder='normal',\n orientation=\"h\",\n # xanchor=\"left\",\n # yanchor=\"top\",\n # x=0,\n y=1.06,\n font = dict(\n size=25\n )\n ),\n geo = dict(\n scope='usa',\n projection=dict(type='albers usa'),\n showland = True,\n landcolor = 'rgb(217, 217, 217)',\n subunitwidth=1,\n countrywidth=1,\n subunitcolor=\"rgb(255, 255, 255)\",\n countrycolor=\"rgb(255, 255, 255)\"\n )\n )\n\n # create plotly figure\n fig = dict(data=crime_traces, layout=layout)\n py.plot(fig, filename='college_crime_map.html')\n\n # create local version\n if local:\n layout = dict(\n showlegend = True,\n legend = dict(\n traceorder='normal',\n orientation=\"h\",\n x=0.147,\n y=1.13\n ),\n geo = dict(\n scope='usa',\n projection=dict(type='albers usa'),\n showland = True,\n landcolor = 'rgb(217, 217, 217)',\n subunitwidth=1,\n countrywidth=1,\n subunitcolor=\"rgb(255, 255, 255)\",\n countrycolor=\"rgb(255, 255, 255)\"\n ),\n annotations=[\n dict(\n x=0.155,\n y=1.06,\n text=\"click legend to toggle crimes\",\n showarrow=False,\n font = dict(\n family=\"Arial\",\n color=\"rgb(105,105,105)\"\n )\n )\n ]\n )\n\n # create plotly figure\n fig = dict(data=crime_traces, layout=layout)\n offline.plot(fig, filename='college_crime_map.html')\n # tls.get_embed('https://plot.ly/~ddewitz/69')\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"dan-dewitz/college_crime_map","sub_path":"build_college_crime_map.py","file_name":"build_college_crime_map.py","file_ext":"py","file_size_in_byte":4991,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"}
+{"seq_id":"36482092641","text":"\"\"\"Defines behaviors for scraping and modeling aerospace systems data from the\n site astronautix.com\n\"\"\"\n\nimport requests\nimport bs4\nimport google\nimport copy\nimport sys\nimport pprint\nimport re\nimport urlparse\nfrom os import path\n\nurl = ''\n\ndef _resolveLink(href, baseUrl=None):\n if baseUrl is None:\n baseUrl = url\n absUrl = ''\n pr = urlparse.urlparse(baseUrl)\n pth,_ = path.split(pr.path)\n parts = pth.split('/')\n if href.startswith('..'):\n pre = href.split('/')\n n = 0\n while n < len(pre) and pre[n] == '..':\n n += 1\n parts = parts[0:-n]\n parts = [p for p in parts if len(p) > 0]\n href = '/'.join(pre[n:])\n absUrl = pr.netloc + '/' + '/'.join(parts) + '/' + href\n elif href.startswith('.'):\n href = href[1:]\n absUrl = pr.netloc + '/' + '/'.join(parts) + '/' + href\n elif re.match('https?://', href):\n return href\n else:\n absUrl = pr.netloc + '/' + '/'.join(parts) + '/' + href\n return pr.scheme + '//' + absUrl.replace('//', '/')\n \ndef _getTitle(article):\n # BS4 will parse the title string into a br tag\n header = article.find('h1')\n return header.find('br').text.strip()\n \ndef _getSummary(article):\n # The article summary is the \n hr = article.find('hr')\n ns = [ch for ch in hr.children if type(ch) is bs4.element.NavigableString]\n return ns[-1].strip().encode('ascii', 'ignore')\n\ndef _getContent(article):\n paragraphs = []\n hr = article.find('hr')\n p = hr.find('p')\n while p is not None:\n txt = next(p.children).strip()\n if len(txt) > 0:\n paragraphs.append(txt.encode('ascii', 'ignore'))\n p = p.find('p')\n return '\\n\\n'.join(paragraphs)\n\ndef _getSpecs(article):\n s = []\n p = article.find('p')\n pp = None\n specs = {}\n k = ''\n v = ''\n while p is not None:\n i = p.find_all('i', recursive=False)\n if i is not None and len(i) > 0:\n for ch in p.children:\n if ch.name == 'i':\n k = ch.text\n else:\n if len(k) > 0:\n v = ch.strip().encode('ascii', 'ignore')\n v = re.sub('^:|[:\\.]$', '', v)\n k = re.sub('^:|[:\\.]$', '', k)\n specs[k] = v\n k = ''\n pp = p\n p = p.find('p')\n p = pp.find('br')\n while p is not None:\n i = p.find_all('i', recursive=False)\n if i is not None and len(i) > 0:\n for ch in p.children:\n if ch.name == 'i':\n k = ch.text\n else:\n if len(k) > 0:\n v = ch.strip().encode('ascii', 'ignore')\n v = re.sub('^:|[:\\.]$', '', v)\n k = re.sub('^:|[:\\.]$', '', k)\n specs[k] = v\n k = ''\n p = p.find('br') \n return specs\n \ndef _isAssoc(tag):\n return tag.name in ['hr','b','ul']\n \ndef _getAssoc(article):\n tags = article.find_all(_isAssoc)\n assocs = {}\n k = ''\n v = ''\n for ndx, tag in enumerate(tags):\n if tag.name == 'b' and tags[ndx-1].name == 'hr':\n k = tag.text.strip().encode('ascii', 'ignore')\n k = re.sub('^Associated\\s*', '', k)\n k = re.sub('^Bibliography$', '', k) # To re-enable sources, replace with a non-zero-length string\n k = re.sub('^See also$', 'Topics', k)\n assocs[k] = []\n else:\n if tag.name == 'ul' and len(k) > 0:\n try:\n name = tag.find('a').text\n link = _resolveLink(tag.find('a').attrs['href'])\n assocs[k].append({name:link})\n except Exception as e:\n print('Failed to parse association value from \"%s\"' % str(tag))\n return assocs\n \narticleModelMap = {\n 'title': _getTitle,\n 'summary': _getSummary,\n 'content': _getContent,\n 'specifications': _getSpecs,\n 'associations': _getAssoc\n}\n\ndef resolve(term):\n return google.lucky('site:astronautix.com ' + term)\n\ndef query(url):\n res = requests.get(url)\n soup = bs4.BeautifulSoup(res.content, 'html.parser')\n article = soup.find('div', attrs={'id':'col1'})\n data = copy.deepcopy(articleModelMap)\n for k,v in articleModelMap.iteritems():\n data[k] = v(article)\n return data\n\ndef getValue(model, key):\n value = model['specifications'][key]\n try:\n value = re.sub('\\(.+\\)', '', value)\n value = re.sub('[^\\d\\.e\\+\\-]', '', value)\n value = float(value)\n except:\n pass\n return value\n","repo_name":"Tythos/scrapese","sub_path":"astronautix.py","file_name":"astronautix.py","file_ext":"py","file_size_in_byte":4716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"2796035109","text":"import test1 as a\n\n#step1.telegram 패키지의 Updater, CommandHandler 모듈 import\nfrom telegram.ext import Updater\nfrom telegram.ext import CommandHandler\n\nchat_id = 5342881340\n#step2.Updater(��저의 입력을 계속 모니터링하는 역할), Dispatcher\nupdater = Updater(token='5366296136:AAF9B_3YXH5fAEAefJDnkAJUC08gGTY1mX8', use_context=True)\ndispatcher = updater.dispatcher\n\n#step3./start 명령어가 입력되었을 때의 함수 정의\ndef coin1(update, context):\n context.bot.send_message(chat_id=update.effective_chat.id, text=\"비트코인과 관련된 뉴스 기사들입니다.\")\n a.send_links()\n\n#step4.위에서 정의한 함수를 실행할 CommandHandler 정의\nstart_handler = CommandHandler('비트코인', coin1) #('명렁어',명령 함수)\n\n#step5.Dispatcher에 Handler를 추가\ndispatcher.add_handler(start_handler)\n\n#step6.Updater 실시간 입력 모니터링 시작(polling 개념)\nupdater.start_polling()","repo_name":"junhyeon0325/telegram_News","sub_path":"test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"72981733851","text":"# Internal\nimport unittest\nfrom asyncio import CancelledError, sleep, ensure_future, get_running_loop\n\n# External\nfrom async_tools import safe_gather\n\n\nasync def immediate(ret):\n return ret\n\n\nasync def sleep_then_fail(sec, exc):\n await sleep(sec)\n raise exc\n\n\nasync def sleep_then_return(sec, ret):\n await sleep(sec)\n return ret\n\n\nasync def ignore_cancel():\n loop = get_running_loop()\n future = loop.create_future()\n\n while True:\n try:\n await future\n except CancelledError:\n future.set_result(True)\n\n\nclass TestSafeGather(unittest.TestCase):\n async def test_simple(self) -> None:\n self.assertListEqual(\n await safe_gather(immediate(1), immediate(2), immediate(3), immediate(4)), [1, 2, 3, 4]\n )\n\n async def test_time(self) -> None:\n self.assertListEqual(\n await safe_gather(\n sleep_then_return(0, 1),\n sleep_then_return(0.1, 2),\n sleep_then_return(0.5, 3),\n sleep_then_return(1, 4),\n ),\n [1, 2, 3, 4],\n )\n\n async def test_all_done(self) -> None:\n tasks = tuple(\n map(\n ensure_future,\n [\n sleep_then_return(0, 1),\n sleep_then_return(0.1, 2),\n sleep_then_return(0.5, 3),\n sleep_then_return(1, 4),\n ],\n )\n )\n self.assertListEqual(await safe_gather(*tasks), [1, 2, 3, 4])\n self.assertTrue(all(map(lambda fut: fut.done(), tasks)))\n\n async def test_fail_1(self) -> None:\n tasks = tuple(\n map(\n ensure_future,\n [\n sleep_then_return(0.1, 1),\n sleep_then_return(0.2, 2),\n sleep_then_return(0.3, 3),\n sleep_then_return(0.4, 4),\n ],\n )\n )\n with self.assertRaisesRegex(RuntimeError, \"###test###\"):\n await safe_gather(sleep_then_fail(0, RuntimeError(\"###test###\")), *tasks)\n\n self.assertTrue(all(map(lambda fut: fut.cancelled(), tasks)))\n\n async def test_fail_2(self) -> None:\n done = tuple(map(ensure_future, [sleep_then_return(0, 1), sleep_then_return(0.1, 2)]))\n cancel = tuple(map(ensure_future, [sleep_then_return(1, 3), sleep_then_return(2, 4)]))\n with self.assertRaisesRegex(RuntimeError, \"###test###\"):\n await safe_gather(*done, sleep_then_fail(0.5, RuntimeError(\"###test###\")), *cancel)\n\n self.assertTrue(all(map(lambda fut: fut.done() and not fut.cancelled(), done)))\n self.assertTrue(all(map(lambda fut: fut.cancelled(), cancel)))\n\n async def test_base_exception(self) -> None:\n tasks = tuple(\n map(\n ensure_future,\n [\n sleep_then_return(0.1, 1),\n sleep_then_return(0.2, 2),\n sleep_then_return(0.3, 3),\n sleep_then_return(0.4, 4),\n ],\n )\n )\n\n with self.assertRaisesRegex(BaseException, \"###test###\"):\n await safe_gather(sleep_then_fail(0, BaseException(\"###test###\")), *tasks)\n\n with self.assertRaises(CancelledError):\n await safe_gather(sleep_then_fail(0, CancelledError()), *tasks)\n\n self.assertTrue(all(map(lambda fut: not fut.done(), tasks)))\n self.assertListEqual(await safe_gather(*tasks), [1, 2, 3, 4])\n\n async def test_fail_ignore(self) -> None:\n tasks = tuple(\n map(\n ensure_future,\n [\n sleep_then_return(0.1, 1),\n sleep_then_return(0.2, 2),\n sleep_then_return(0.3, 3),\n sleep_then_return(0.4, 4),\n ],\n )\n )\n ignore = ensure_future(ignore_cancel())\n with self.assertRaisesRegex(RuntimeError, \"###test###\"):\n await safe_gather(sleep_then_fail(0, RuntimeError(\"###test###\")), *tasks, ignore)\n\n self.assertTrue(all(map(lambda fut: fut.cancelled(), tasks)))\n self.assertTrue(ignore.done() and not ignore.cancelled() and ignore.result())\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"HeavenVolkoff/async_tools","sub_path":"tests/test_safe_gather.py","file_name":"test_safe_gather.py","file_ext":"py","file_size_in_byte":4304,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"32"}
+{"seq_id":"33638372763","text":"#Embedded file name: c:/depot/games/branches/release/EVE-TRANQUILITY/eve/client/script/ui/services/skillQueueSvc.py\nimport service\nimport blue\nimport uthread\nimport util\nimport types\nimport form\nimport skillUtil\nimport sys\nimport uix\nimport uiconst\nimport uiutil\nimport localization\n\nclass SkillQueueService(service.Service):\n __exportedcalls__ = {}\n __guid__ = 'svc.skillqueue'\n __servicename__ = 'skillqueue'\n __displayname__ = 'Skill Queue Client Service'\n __dependencies__ = ['godma', 'skills', 'machoNet']\n __notifyevents__ = ['OnGodmaSkillTrained',\n 'OnGodmaSkillStartTraining',\n 'OnGodmaSkillTrainingStopped',\n 'OnSkillQueueForciblyUpdated']\n\n def __init__(self):\n service.Service.__init__(self)\n self.skillQueue = []\n self.serverSkillQueue = []\n self.skillQueueCache = None\n self.skillPrerequisiteAttributes = [ 'requiredSkill%d' % x for x in (1, 2, 3, 4, 5, 6) ]\n self.cachedSkillQueue = None\n self.timeCutoff = DAY\n\n def Run(self, memStream = None):\n self.skillQueue, freeSkillPoints = self.godma.GetSkillHandler().GetSkillQueueAndFreePoints()\n self.skillQueueCache = None\n if freeSkillPoints is not None and freeSkillPoints > 0:\n sm.GetService('skills').SetFreeSkillPoints(freeSkillPoints)\n\n def BeginTransaction(self):\n sendEvent = False\n if self.cachedSkillQueue is not None:\n sendEvent = True\n self.LogWarn('New skill queue transaction being opened - skill queue being overwritten!')\n self.skillQueueCache = None\n self.skillQueue, freeSkillPoints = self.godma.GetSkillHandler().GetSkillQueueAndFreePoints()\n if freeSkillPoints > 0:\n self.skills.SetFreeSkillPoints(freeSkillPoints)\n self.cachedSkillQueue = self.GetQueue()\n if sendEvent:\n sm.ScatterEvent('OnSkillQueueRefreshed')\n\n def RollbackTransaction(self):\n if self.cachedSkillQueue is None:\n self.LogError('Cannot rollback a skill queue transaction - no transaction was opened!')\n return\n self.skillQueue = self.cachedSkillQueue\n self.skillQueueCache = None\n self.cachedSkillQueue = None\n\n def CommitTransaction(self):\n if self.cachedSkillQueue is None:\n self.LogError('Cannot commit a skill queue transaction - no transaction was opened!')\n return\n self.PrimeCache(True)\n cachedQueueCache = {}\n i = 0\n for queueSkillID, queueSkillLevel in self.cachedSkillQueue:\n if queueSkillID not in cachedQueueCache:\n cachedQueueCache[queueSkillID] = {}\n cachedQueueCache[queueSkillID][queueSkillLevel] = i\n i += 1\n\n hasChanges = False\n for skillTypeID, skillLevel in self.cachedSkillQueue:\n if skillTypeID not in self.skillQueueCache:\n hasChanges = True\n break\n elif skillLevel not in self.skillQueueCache[skillTypeID]:\n hasChanges = True\n break\n\n if not hasChanges:\n for skillTypeID, skillLevel in self.skillQueue:\n position = self.skillQueueCache[skillTypeID][skillLevel]\n if skillTypeID not in cachedQueueCache:\n hasChanges = True\n elif skillLevel not in cachedQueueCache[skillTypeID]:\n hasChanges = True\n elif position != cachedQueueCache[skillTypeID][skillLevel]:\n hasChanges = True\n if hasChanges:\n break\n\n scatterEvent = False\n try:\n if hasChanges:\n self.TrimQueue()\n skillHandler = sm.StartService('godma').GetSkillHandler()\n skillHandler.SaveSkillQueue(self.skillQueue)\n scatterEvent = True\n elif self.skillQueue is not None and len(self.skillQueue) and sm.StartService('skills').SkillInTraining() is None:\n skillHandler = sm.StartService('godma').GetSkillHandler()\n skillHandler.CharStartTrainingSkillByTypeID(self.skillQueue[0][0])\n scatterEvent = True\n except UserError as e:\n if e.msg == 'UserAlreadyHasSkillInTraining':\n scatterEvent = True\n raise \n finally:\n self.cachedSkillQueue = None\n if scatterEvent:\n sm.ScatterEvent('OnSkillQueueRefreshed')\n\n def CheckCanInsertSkillAtPosition(self, skillTypeID, skillLevel, position, check = 0):\n if position is None or position < 0 or position > len(self.skillQueue):\n raise UserError('QueueInvalidPosition')\n self.PrimeCache()\n mySkills = self.GetGodmaSkillsSet()\n ret = True\n try:\n skillObj = mySkills.get(skillTypeID, None)\n if skillObj is None:\n raise UserError('QueueSkillNotUploaded')\n if skillObj.skillLevel >= skillLevel:\n raise UserError('QueueCannotTrainPreviouslyTrainedSkills')\n if skillObj.skillLevel >= 5:\n raise UserError('QueueCannotTrainPastMaximumLevel', {'typeName': (TYPEID, skillTypeID)})\n if skillTypeID in self.skillQueueCache:\n for lvl, lvlPosition in self.skillQueueCache[skillTypeID].iteritems():\n if lvl < skillLevel and lvlPosition >= position:\n raise UserError('QueueCannotPlaceSkillLevelsOutOfOrder')\n elif lvl > skillLevel and lvlPosition < position:\n raise UserError('QueueCannotPlaceSkillLevelsOutOfOrder')\n\n else:\n godmaType = self.godma.GetType(skillTypeID)\n for attributeName in self.skillPrerequisiteAttributes:\n attributeVal = getattr(godmaType, attributeName, None)\n attributeLevel = getattr(godmaType, attributeName + 'Level', None)\n if attributeVal and attributeLevel is not None:\n skillObj = mySkills.get(attributeVal, None)\n if skillObj is None or attributeLevel > skillObj.skillLevel:\n raise UserError('QueuePrerequisitesNotMet', {'skill': attributeVal,\n 'level': attributeLevel})\n\n if position > 0:\n if self.GetTrainingLengthOfQueue(position) > self.timeCutoff:\n raise UserError('QueueTooLong')\n except UserError as ue:\n if check and ue.msg in ('QueueTooLong', 'QueuePrerequisitesNotMet', 'QueueCannotPlaceSkillLevelsOutOfOrder', 'QueueCannotTrainPreviouslyTrainedSkills', 'QueueSkillNotUploaded'):\n sys.exc_clear()\n ret = False\n else:\n raise \n\n return ret\n\n def AddSkillToQueue(self, skillTypeID, skillLevel, position = None):\n if self.FindInQueue(skillTypeID, skillLevel) is not None:\n raise UserError('QueueSkillAlreadyPresent')\n skillQueueLength = len(self.skillQueue)\n if skillQueueLength >= const.skillQueueMaxSkills:\n raise UserError('QueueTooManySkills', {'num': const.skillQueueMaxSkills})\n newPos = position if position is not None and position >= 0 else skillQueueLength\n self.CheckCanInsertSkillAtPosition(skillTypeID, skillLevel, newPos)\n if newPos == skillQueueLength:\n self.skillQueue.append((skillTypeID, skillLevel))\n self.AddToCache(skillTypeID, skillLevel, newPos)\n else:\n if newPos > skillQueueLength:\n raise UserError('QueueInvalidPosition')\n self.skillQueueCache = None\n self.skillQueue.insert(newPos, (skillTypeID, skillLevel))\n self.TrimQueue()\n return newPos\n\n def RemoveSkillFromQueue(self, skillTypeID, skillLevel):\n self.PrimeCache()\n if skillTypeID in self.skillQueueCache:\n for cacheLevel in self.skillQueueCache[skillTypeID]:\n if cacheLevel > skillLevel:\n raise UserError('QueueCannotRemoveSkillsWithHigherLevelsStillInQueue')\n\n self.InternalRemoveFromQueue(skillTypeID, skillLevel)\n\n def FindInQueue(self, skillTypeID, skillLevel):\n self.PrimeCache()\n if skillTypeID not in self.skillQueueCache:\n return None\n if skillLevel not in self.skillQueueCache[skillTypeID]:\n return None\n return self.skillQueueCache[skillTypeID][skillLevel]\n\n def MoveSkillToPosition(self, skillTypeID, skillLevel, position):\n self.CheckCanInsertSkillAtPosition(skillTypeID, skillLevel, position)\n self.PrimeCache()\n currentPosition = self.skillQueueCache[skillTypeID][skillLevel]\n if currentPosition < position:\n position -= 1\n self.InternalRemoveFromQueue(skillTypeID, skillLevel)\n return self.AddSkillToQueue(skillTypeID, skillLevel, position)\n\n def GetQueue(self):\n return self.skillQueue[:]\n\n def GetServerQueue(self):\n if self.cachedSkillQueue is not None:\n return self.cachedSkillQueue[:]\n else:\n return self.GetQueue()\n\n def GetNumberOfSkillsInQueue(self):\n return len(self.skillQueue)\n\n def GetTrainingLengthOfQueue(self, position = None):\n if position is not None and position < 0:\n raise RuntimeError('Invalid queue position: ', position)\n trainingTime = 0\n currentAttributes = self.GetPlayerAttributeDict()\n playerTheoreticalSkillPoints = {}\n godmaSkillSet = self.GetGodmaSkillsSet()\n currentIndex = 0\n finalIndex = position\n if finalIndex is None:\n finalIndex = len(self.skillQueue)\n for queueSkillTypeID, queueSkillLevel in self.skillQueue:\n if currentIndex >= finalIndex:\n break\n currentIndex += 1\n if queueSkillTypeID not in playerTheoreticalSkillPoints:\n skillObj = godmaSkillSet.get(queueSkillTypeID, None)\n playerTheoreticalSkillPoints[queueSkillTypeID] = self.GetSkillPointsFromSkillObject(skillObj)\n addedSP, addedTime = self.GetTrainingParametersOfSkillInEnvironment(queueSkillTypeID, queueSkillLevel, playerTheoreticalSkillPoints[queueSkillTypeID], currentAttributes)\n trainingTime += addedTime\n playerTheoreticalSkillPoints[queueSkillTypeID] += addedSP\n\n return trainingTime\n\n def GetTrainingEndTimeOfQueue(self):\n return blue.os.GetWallclockTime() + self.GetTrainingLengthOfQueue()\n\n def GetTrainingLengthOfSkill(self, skillTypeID, skillLevel, position = None):\n if position is not None and (position < 0 or position > len(self.skillQueue)):\n raise RuntimeError('GetTrainingLengthOfSkill received an invalid position.')\n trainingTime = 0\n currentAttributes = self.GetPlayerAttributeDict()\n currentIndex = 0\n targetIndex = position\n addedSP = 0\n addedTime = 0\n if targetIndex is None:\n targetIndex = self.FindInQueue(skillTypeID, skillLevel)\n if targetIndex is None:\n targetIndex = len(self.skillQueue)\n playerTheoreticalSkillPoints = {}\n godmaSkillSet = self.GetGodmaSkillsSet()\n for queueSkillTypeID, queueSkillLevel in self.skillQueue:\n if currentIndex >= targetIndex:\n break\n elif queueSkillTypeID == skillTypeID and queueSkillLevel == skillLevel and currentIndex < targetIndex:\n currentIndex += 1\n continue\n currentIndex += 1\n if queueSkillTypeID not in playerTheoreticalSkillPoints:\n skillObj = godmaSkillSet.get(queueSkillTypeID, None)\n playerTheoreticalSkillPoints[queueSkillTypeID] = self.GetSkillPointsFromSkillObject(skillObj)\n addedSP, addedTime = self.GetTrainingParametersOfSkillInEnvironment(queueSkillTypeID, queueSkillLevel, playerTheoreticalSkillPoints[queueSkillTypeID], currentAttributes)\n trainingTime += addedTime\n playerTheoreticalSkillPoints[queueSkillTypeID] += addedSP\n\n if skillTypeID not in playerTheoreticalSkillPoints:\n skillObj = godmaSkillSet.get(skillTypeID, None)\n if skillObj is not None:\n playerTheoreticalSkillPoints[skillTypeID] = skillObj.skillPoints\n else:\n playerTheoreticalSkillPoints[skillTypeID] = 0\n addedSP, addedTime = self.GetTrainingParametersOfSkillInEnvironment(skillTypeID, skillLevel, playerTheoreticalSkillPoints[skillTypeID], currentAttributes)\n trainingTime += addedTime\n return (trainingTime, addedTime)\n\n def GetTrainingParametersOfSkillInEnvironment(self, skillTypeID, skillLevel, existingSkillPoints = 0, playerAttributeDict = None):\n skillTimeConstant = 0\n primaryAttributeID = 0\n secondaryAttributeID = 0\n playerCurrentSP = existingSkillPoints\n skillTimeConstant = self.godma.GetTypeAttribute(skillTypeID, const.attributeSkillTimeConstant)\n primaryAttributeID = self.godma.GetTypeAttribute(skillTypeID, const.attributePrimaryAttribute)\n secondaryAttributeID = self.godma.GetTypeAttribute(skillTypeID, const.attributeSecondaryAttribute)\n if existingSkillPoints is None:\n skillObj = self.GetGodmaSkillsSet().get(skillTypeID, None)\n if skillObj is not None:\n playerCurrentSP = skillObj.skillPoints\n else:\n playerCurrentSP = 0\n if skillTimeConstant is None:\n self.LogWarn('GetTrainingLengthOfSkillInEnvironment could not find skill type ID:', skillTypeID, 'via Godma')\n return 0\n skillPointsToTrain = skillUtil.GetSPForLevelRaw(skillTimeConstant, skillLevel) - playerCurrentSP\n if skillPointsToTrain <= 0:\n return (0, 0)\n attrDict = playerAttributeDict\n if attrDict is None:\n attrDict = self.GetPlayerAttributeDict()\n playerPrimaryAttribute = attrDict[primaryAttributeID]\n playerSecondaryAttribute = attrDict[secondaryAttributeID]\n if playerPrimaryAttribute <= 0 or playerSecondaryAttribute <= 0:\n raise RuntimeError('GetTrainingLengthOfSkillInEnvironment found a zero attribute value on character', session.charid, 'for attributes [', primaryAttributeID, secondaryAttributeID, ']')\n trainingRate = skillUtil.GetSkillPointsPerMinute(playerPrimaryAttribute, playerSecondaryAttribute)\n trainingTimeInMinutes = float(skillPointsToTrain) / float(trainingRate)\n return (skillPointsToTrain, trainingTimeInMinutes * MIN)\n\n def TrimQueue(self):\n trainingTime = 0\n currentAttributes = self.GetPlayerAttributeDict()\n playerTheoreticalSkillPoints = {}\n godmaSkillSet = self.GetGodmaSkillsSet()\n cutoffIndex = 0\n for queueSkillTypeID, queueSkillLevel in self.skillQueue:\n cutoffIndex += 1\n if queueSkillTypeID not in playerTheoreticalSkillPoints:\n skillObj = godmaSkillSet.get(queueSkillTypeID, None)\n playerTheoreticalSkillPoints[queueSkillTypeID] = self.GetSkillPointsFromSkillObject(skillObj)\n addedSP, addedTime = self.GetTrainingParametersOfSkillInEnvironment(queueSkillTypeID, queueSkillLevel, playerTheoreticalSkillPoints[queueSkillTypeID], currentAttributes)\n trainingTime += addedTime\n playerTheoreticalSkillPoints[queueSkillTypeID] += addedSP\n if trainingTime > self.timeCutoff:\n break\n\n if cutoffIndex < len(self.skillQueue):\n removedSkills = self.skillQueue[cutoffIndex:]\n self.skillQueue = self.skillQueue[:cutoffIndex]\n self.skillQueueCache = None\n sm.ScatterEvent('OnSkillQueueTrimmed', removedSkills)\n\n def GetAllTrainingLengths(self):\n trainingTime = 0\n currentAttributes = self.GetPlayerAttributeDict()\n resultsDict = {}\n playerTheoreticalSkillPoints = {}\n godmaSkillSet = self.GetGodmaSkillsSet()\n for queueSkillTypeID, queueSkillLevel in self.skillQueue:\n if queueSkillTypeID not in playerTheoreticalSkillPoints:\n skillObj = godmaSkillSet.get(queueSkillTypeID, None)\n playerTheoreticalSkillPoints[queueSkillTypeID] = self.GetSkillPointsFromSkillObject(skillObj)\n addedSP, addedTime = self.GetTrainingParametersOfSkillInEnvironment(queueSkillTypeID, queueSkillLevel, playerTheoreticalSkillPoints[queueSkillTypeID], currentAttributes)\n trainingTime += addedTime\n playerTheoreticalSkillPoints[queueSkillTypeID] += addedSP\n resultsDict[queueSkillTypeID, queueSkillLevel] = (trainingTime, addedTime)\n\n return resultsDict\n\n def InternalRemoveFromQueue(self, skillTypeID, skillLevel):\n skillPosition = self.FindInQueue(skillTypeID, skillLevel)\n if skillPosition is None:\n raise UserError('QueueSkillNotPresent')\n if skillPosition == len(self.skillQueue):\n del self.skillQueueCache[skillTypeID][skillLevel]\n self.skillQueue.pop()\n else:\n self.skillQueueCache = None\n self.skillQueue.pop(skillPosition)\n\n def ClearCache(self):\n self.skillQueueCache = None\n\n def AddToCache(self, skillTypeID, skillLevel, position):\n self.PrimeCache()\n if skillTypeID not in self.skillQueueCache:\n self.skillQueueCache[skillTypeID] = {}\n self.skillQueueCache[skillTypeID][skillLevel] = position\n\n def GetGodmaSkillsSet(self):\n return self.skills.GetMyGodmaItem().skills\n\n def GetPlayerAttributeDict(self):\n charItem = self.godma.GetItem(session.charid)\n attrDict = {}\n for each in charItem.displayAttributes:\n attrDict[each.attributeID] = each.value\n\n return attrDict\n\n def PrimeCache(self, force = False):\n if force:\n self.skillQueueCache = None\n if self.skillQueueCache is None:\n i = 0\n self.skillQueueCache = {}\n for queueSkillID, queueSkillLevel in self.skillQueue:\n self.AddToCache(queueSkillID, queueSkillLevel, i)\n i += 1\n\n def GetSkillPointsFromSkillObject(self, skillObject):\n if skillObject is None:\n return 0\n else:\n skillTrainingEnd, spHi, spm = skillObject.skillTrainingEnd, skillObject.spHi, skillObject.spm\n if skillTrainingEnd is not None and spHi is not None:\n secs = (skillTrainingEnd - blue.os.GetWallclockTime()) / SEC\n return min(spHi - secs / 60.0 * spm, spHi)\n return skillObject.skillPoints\n\n def OnGodmaSkillTrained(self, skillID):\n skill = sm.GetService('godma').GetItem(skillID)\n skillTypeID = skill.typeID\n level = skill.skillLevel\n if (skillTypeID, level) in self.skillQueue:\n try:\n self.InternalRemoveFromQueue(skillTypeID, level)\n sm.ScatterEvent('OnSkillFinished', skillID, skillTypeID, level)\n except UserError as ue:\n sys.exc_clear()\n\n if self.cachedSkillQueue and (skillTypeID, level) in self.cachedSkillQueue:\n self.cachedSkillQueue.remove((skillTypeID, level))\n\n def OnGodmaSkillStartTraining(self, skillID, ETA):\n skill = sm.GetService('godma').GetItem(skillID)\n level = skill.skillLevel + 1\n if (skill.typeID, level) not in self.skillQueue:\n self.AddSkillToQueue(skill.typeID, level, 0)\n else:\n self.MoveSkillToPosition(skill.typeID, level, 0)\n sm.ScatterEvent('OnSkillStarted', skill.typeID, level)\n\n def OnGodmaSkillTrainingStopped(self, skillID, silent):\n sm.ScatterEvent('OnSkillPaused', skillID)\n\n def OnSkillQueueTrimmed(self, removedSkills):\n eve.Message('skillQueueTrimmed', {'num': len(removedSkills)})\n\n def TrainSkillNow(self, skillID, toSkillLevel, *args):\n inTraining = sm.StartService('skills').SkillInTraining()\n if inTraining and eve.Message('ConfirmSkillTrainingNow', {'name': inTraining.type.typeName,\n 'lvl': inTraining.skillLevel + 1}, uiconst.OKCANCEL) != uiconst.ID_OK:\n return\n self.BeginTransaction()\n commit = True\n try:\n if self.FindInQueue(skillID, toSkillLevel) is not None:\n self.MoveSkillToPosition(skillID, toSkillLevel, 0)\n eve.Message('SkillQueueStarted')\n else:\n self.AddSkillToQueue(skillID, toSkillLevel, 0)\n text = localization.GetByLabel('UI/SkillQueue/Skills/SkillNameAndLevel', skill=skillID, amount=toSkillLevel)\n if inTraining:\n eve.Message('AddedToQueue', {'skillname': text})\n else:\n eve.Message('AddedToQueueAndStarted', {'skillname': text})\n except UserError as RuntimeError:\n commit = False\n raise \n finally:\n if commit:\n self.CommitTransaction()\n else:\n self.RollbackTransaction()\n\n def AddSkillToEnd(self, skillID, current, nextLevel = None):\n queueLength = self.GetNumberOfSkillsInQueue()\n if queueLength >= const.skillQueueMaxSkills:\n eve.Message('CustomNotify', {'notify': localization.GetByLabel('UI/SkillQueue/QueueIsFull')})\n return\n totalTime = self.GetTrainingLengthOfQueue()\n if totalTime > const.skillQueueTime:\n eve.Message('CustomNotify', {'notify': localization.GetByLabel('UI/SkillQueue/QueueIsFull')})\n return\n if nextLevel is None:\n queue = self.GetServerQueue()\n nextLevel = self.FindNextLevel(skillID, current, queue)\n self.AddSkillToQueue(skillID, nextLevel)\n try:\n sm.StartService('godma').GetSkillHandler().AddToEndOfSkillQueue(skillID, nextLevel)\n text = localization.GetByLabel('UI/SkillQueue/Skills/SkillNameAndLevel', skill=skillID, amount=nextLevel)\n if sm.StartService('skills').SkillInTraining():\n eve.Message('AddedToQueue', {'skillname': text})\n else:\n eve.Message('AddedToQueueAndStarted', {'skillname': text})\n except UserError:\n self.RemoveSkillFromQueue(skillID, nextLevel)\n raise \n\n sm.ScatterEvent('OnSkillStarted')\n\n def FindNextLevel(self, skillID, current, list = None):\n if list is None:\n list = self.GetServerQueue()\n nextLevel = None\n for i in xrange(1, 7):\n if current >= i:\n continue\n inQueue = bool((skillID, i) in list)\n if inQueue is False:\n nextLevel = i\n break\n\n return nextLevel\n\n def OnSkillQueueForciblyUpdated(self):\n if self.skillQueueCache is not None:\n self.BeginTransaction()\n\n def IsQueueWndOpen(self):\n return form.SkillQueue.IsOpen()\n\n def GetAddMenuForSkillEntries(self, skill):\n m = []\n if skill is None:\n return m\n skillLevel = skill.skillLevel\n if skillLevel is not None:\n sqWnd = form.SkillQueue.GetIfOpen()\n if skillLevel < 5:\n queue = self.GetQueue()\n nextLevel = self.FindNextLevel(skill.typeID, skill.skillLevel, queue)\n if skill.flagID == const.flagSkill:\n trainingTime, totalTime = self.GetTrainingLengthOfSkill(skill.typeID, skill.skillLevel + 1, 0)\n takesText = ''\n if trainingTime <= 0:\n takesText = localization.GetByLabel('UI/SkillQueue/Skills/CompletionImminent')\n else:\n takesText = localization.GetByLabel('UI/SkillQueue/Skills/SkillTimeLeft', timeLeft=long(trainingTime))\n if sqWnd:\n if nextLevel < 6 and self.FindInQueue(skill.typeID, skill.skillLevel + 1) is None:\n trainText = uiutil.MenuLabel('UI/SkillQueue/AddSkillMenu/AddToFrontOfQueueTime', {'takes': takesText})\n m.append((trainText, sqWnd.AddSkillsThroughOtherEntry, (skill.typeID,\n 0,\n queue,\n nextLevel,\n 1)))\n else:\n trainText = uiutil.MenuLabel('UI/SkillQueue/AddSkillMenu/TrainNowWithTime', {'skillLevel': skill.skillLevel + 1,\n 'takes': takesText})\n m.append((trainText, self.TrainSkillNow, (skill.typeID, skill.skillLevel + 1)))\n if nextLevel < 6:\n if sqWnd:\n label = uiutil.MenuLabel('UI/SkillQueue/AddSkillMenu/AddToEndOfQueue', {'nextLevel': nextLevel})\n m.append((label, sqWnd.AddSkillsThroughOtherEntry, (skill.typeID,\n -1,\n queue,\n nextLevel,\n 1)))\n else:\n label = uiutil.MenuLabel('UI/SkillQueue/AddSkillMenu/TrainAfterQueue', {'nextLevel': nextLevel})\n m.append((label, self.AddSkillToEnd, (skill.typeID, skill.skillLevel, nextLevel)))\n if sm.GetService('skills').GetFreeSkillPoints() > 0:\n diff = skill.spHi + 0.5 - skill.skillPoints\n m.append((uiutil.MenuLabel('UI/SkillQueue/AddSkillMenu/ApplySkillPoints'), self.UseFreeSkillPoints, (skill.typeID, diff)))\n if skill.flagID == const.flagSkillInTraining:\n m.append((uiutil.MenuLabel('UI/SkillQueue/AddSkillMenu/AbortTraining'), sm.StartService('skills').AbortTrain, (skill,)))\n if m:\n m.append(None)\n return m\n\n def UseFreeSkillPoints(self, skillTypeID, diff):\n if sm.StartService('skills').SkillInTraining():\n eve.Message('CannotApplyFreePointsWhileQueueActive')\n return\n freeSkillPoints = sm.StartService('skills').GetFreeSkillPoints()\n text = localization.GetByLabel('UI/SkillQueue/AddSkillMenu/UseSkillPointsWindow', skill=skillTypeID, skillPoints=int(diff))\n caption = localization.GetByLabel('UI/SkillQueue/AddSkillMenu/ApplySkillPoints')\n ret = uix.QtyPopup(maxvalue=freeSkillPoints, caption=caption, label=text)\n if ret is None:\n return\n sp = int(ret.get('qty', ''))\n currentSkillPoints = sm.GetService('skills').GetSkillPoints()\n sm.StartService('skills').ApplyFreeSkillPoints(skillTypeID, sp)","repo_name":"alexcmd/eve","sub_path":"eve-8.21.494548/eve/client/script/ui/services/skillQueueSvc.py","file_name":"skillQueueSvc.py","file_ext":"py","file_size_in_byte":26867,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"32"}
+{"seq_id":"36393855348","text":"# coding=utf-8\nfrom unittest import TestCase\nfrom click.testing import CliRunner\n\nimport os\nimport yoda\n\n\nclass TestGrepSingleFile(TestCase):\n \"\"\"\n Test for the following commands:\n\n | Module: dev\n | command: grep\n \"\"\"\n\n def __init__(self, methodName=\"runTest\"):\n super(TestGrepSingleFile, self).__init__()\n self.runner = CliRunner()\n\n def runTest(self):\n with self.runner.isolated_filesystem():\n with open(\"inputfile.txt\", \"w\") as outfile:\n outfile.write(\n \"test should match\\ntesT should match\\nThistestshouldmatch\\n\"\n )\n result = self.runner.invoke(\n yoda.cli, [\"dev\", \"grep\", \"test\", \"inputfile.txt\", \"-i\", \"True\"]\n )\n output_string = result.output\n expected_output = (\n \"test should match\\ntesT should match\\nThistestshouldmatch\\n\"\n )\n self.assertTrue(output_string == expected_output)\n\n\nclass TestGrepEntireFolder(TestCase):\n \"\"\"\n Test for the following commands:\n\n | Module: dev\n | command: grep\n \"\"\"\n\n def __init__(self, methodName=\"runTest\"):\n super(TestGrepEntireFolder, self).__init__()\n self.runner = CliRunner()\n\n def runTest(self):\n with self.runner.isolated_filesystem():\n with open(\"inputfile1.txt\", \"w\") as outfile1:\n outfile1.write(\"tesT should not match\\ntest should match\")\n with open(\"inputfile2.txt\", \"w\") as outfile2:\n outfile2.write(\"Thistestshouldmatch\\n\")\n\n result = self.runner.invoke(yoda.cli, [\"dev\", \"grep\", \"test\", os.getcwd()])\n output_string = result.output\n # Order changes from between machines. Need to either both possibilities.\n self.assertTrue(\n output_string == \"Thistestshouldmatch\\ntest should match\"\n or output_string == \"test should matchThistestshouldmatch\\n\"\n )\n","repo_name":"yoda-pa/yoda","sub_path":"tests/dev/test_grep.py","file_name":"test_grep.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","stars":722,"dataset":"github-code","pt":"32"}
+{"seq_id":"3722320556","text":"\nimport unittest\n\nfrom kraken.core.maths import Math_degToRad\nfrom kraken.core.maths.vec3 import Vec3\nfrom kraken.core.maths.xfo import Xfo\nfrom kraken.core.maths.quat import Quat\nfrom kraken.core.maths.mat44 import Mat44\n\n\nclass TestXfo(unittest.TestCase):\n\n def testString(self):\n xfo = Xfo()\n\n self.assertEquals(str(xfo),\n \"Xfo(Vec3(0.0, 0.0, 0.0), Quat(Vec3(0.0, 0.0, 0.0), 1.0), Vec3(1.0, 1.0, 1.0))\")\n\n def testGetPropertyValues(self):\n xfo = Xfo(tr=Vec3(0.0, 1.0, 0.0), ori=Quat(), sc=Vec3(1.0, 2.0, 1.0))\n\n self.assertEquals(xfo.tr, Vec3(0.0, 1.0, 0.0))\n self.assertEquals(xfo.ori, Quat())\n self.assertEquals(xfo.sc, Vec3(1.0, 2.0, 1.0))\n\n def testSetPropertyValues(self):\n xfo = Xfo()\n\n xfo.tr = Vec3(0.0, 1.0, 0.0)\n xfo.ori = Quat(Vec3(0, 1, 0), 1.0)\n xfo.sc = Vec3(2.0, 1.0, 1.0)\n\n self.assertEquals(xfo.tr, Vec3(0.0, 1.0, 0.0))\n self.assertEquals(xfo.ori, Quat(Vec3(0, 1, 0), 1.0))\n self.assertEquals(xfo.sc, Vec3(2.0, 1.0, 1.0))\n\n def testEquals(self):\n xfo1 = Xfo(tr=Vec3(0.0, 1.0, 0.0), ori=Quat(), sc=Vec3(1.0, 2.0, 1.0))\n xfo2 = Xfo(tr=Vec3(0.0, 1.0, 0.0), ori=Quat(), sc=Vec3(1.0, 2.0, 1.0))\n\n self.assertEqual(xfo1, xfo2)\n\n def testNotEquals(self):\n xfo1 = Xfo(tr=Vec3(0.0, 1.0, 3.0), ori=Quat(), sc=Vec3(1.0, 2.0, 1.0))\n xfo2 = Xfo(tr=Vec3(2.0, 1.0, 0.0), ori=Quat(), sc=Vec3(1.0, 5.0, 1.0))\n\n self.assertNotEqual(xfo1, xfo2)\n\n def testMultiply(self):\n xfo1 = Xfo(tr=Vec3(0.0, 1.0, 3.0), ori=Quat(), sc=Vec3(1.0, 1.0, 1.0))\n xfo2 = Xfo(tr=Vec3(2.0, 1.0, 0.0), ori=Quat(), sc=Vec3(1.0, 1.0, 1.0))\n\n xfo = xfo1 * xfo2\n result = Xfo(tr=Vec3(2.0, 2.0, 3.0), ori=Quat(), sc=Vec3(1.0, 1.0, 1.0))\n\n self.assertEqual(xfo.tr, result.tr)\n self.assertEqual(xfo.ori, result.ori)\n self.assertEqual(xfo.sc, result.sc)\n\n def testClone(self):\n xfo1 = Xfo(tr=Vec3(0.0, 1.0, 3.0), ori=Quat(), sc=Vec3(1.0, 2.0, 1.0))\n xfo2 = xfo1.clone()\n\n self.assertIsNot(xfo1, xfo2)\n\n self.assertEqual(xfo1, xfo2)\n\n def testSet(self):\n xfo = Xfo()\n\n xfo.set(Vec3(0.0, 1.0, 3.0), Quat(), Vec3(1.0, 2.0, 1.0))\n self.assertEquals(xfo.tr, Vec3(0.0, 1.0, 3.0))\n self.assertEquals(xfo.ori, Quat())\n self.assertEquals(xfo.sc, Vec3(1.0, 2.0, 1.0))\n\n def testSetIdentity(self):\n xfo = Xfo(tr=Vec3(0.0, 1.0, 3.0), ori=Quat(), sc=Vec3(1.0, 2.0, 1.0))\n\n xfo.setIdentity()\n\n self.assertEquals(xfo.tr, Vec3())\n self.assertEquals(xfo.ori, Quat())\n self.assertEquals(xfo.sc, Vec3(1, 1, 1))\n\n def testSetFromMat44(self):\n xfo = Xfo()\n mat44 = Mat44()\n mat44.setTranslation(Vec3(0, 1, 0))\n xfo.setFromMat44(mat44)\n\n self.assertTrue(mat44.translation, xfo.tr)\n\n def testToMat44(self):\n xfo = Xfo(tr=Vec3(0.0, 1.0, 3.0), ori=Quat(), sc=Vec3(1.0, 2.0, 1.0))\n\n mat44 = xfo.toMat44()\n\n self.assertEquals(mat44.row0.t, 0.0)\n self.assertEquals(mat44.row1.t, 1.0)\n self.assertEquals(mat44.row2.t, 3.0)\n self.assertEquals(mat44.row1.y, 2.0)\n\n def testTransformVector(self):\n ori = Quat().setFromAxisAndAngle(Vec3(0, 1, 0), Math_degToRad(-90))\n\n xfo = Xfo(tr=Vec3(0.0, 1.0, 3.0), ori=ori, sc=Vec3(1.0, 1.0, 1.0))\n vec = Vec3(0, 0, 1)\n\n result = xfo.transformVector(vec)\n\n self.assertEquals(round(result.x, 2), -1.0)\n self.assertEquals(result.y, 1.0)\n self.assertEquals(result.z, 3.0)\n\n def testInverse(self):\n xfo = Xfo(tr=Vec3(0.0, 1.0, 3.0), ori=Quat(), sc=Vec3(1.0, 1.0, 1.0))\n\n result = xfo.inverse()\n\n self.assertEqual(Vec3(0.0, -1.0, -3.0), result.tr)\n self.assertEqual(Quat(), result.ori)\n self.assertEqual(Vec3(1.0, 1.0, 1.0), result.sc)\n\n def testInverseTransformVector(self):\n ori = Quat().setFromAxisAndAngle(Vec3(0, 1, 0), Math_degToRad(-90))\n\n xfo = Xfo(tr=Vec3(0.0, 1.0, 3.0), ori=ori, sc=Vec3(1.0, 1.0, 1.0))\n vec = Vec3(0, 0, 1)\n\n result = xfo.inverseTransformVector(vec)\n\n self.assertEquals(round(result.x, 2), -2.0)\n self.assertEquals(round(result.y, 2), -1.0)\n self.assertEquals(result.z, 0.0)\n\n def testLinearInterpolate(self):\n ori = Quat().setFromAxisAndAngle(Vec3(0, 1, 0), Math_degToRad(90))\n\n xfo1 = Xfo(tr=Vec3(0.0, 0.0, 0.0), ori=Quat(), sc=Vec3(1.0, 1.0, 1.0))\n xfo2 = Xfo(tr=Vec3(0.0, 5.0, 0.0), ori=ori, sc=Vec3(2.0, 2.0, 2.0))\n\n result = xfo1.linearInterpolate(xfo2, 0.5)\n resultOri = Quat(Vec3(0.0, 0.382683426142, 0.0), 0.923879563808)\n\n self.assertEqual(result.tr, Vec3(0, 2.5, 0))\n self.assertEqual(result.ori, resultOri)\n self.assertEqual(result.sc, Vec3(1.5, 1.5, 1.5))\n\n def testSetFromVectors(self):\n xfo = Xfo()\n\n xfo.setFromVectors(Vec3(1, 0, 0),\n Vec3(0, 1, 0),\n Vec3(0, 0, 1),\n Vec3(2, 3, 4))\n\n self.assertEqual(xfo.tr, Vec3(2, 3, 4))\n self.assertEqual(xfo.ori, Quat())\n self.assertEqual(xfo.sc, Vec3(1, 1, 1))\n\n\ndef suite():\n return unittest.TestLoader().loadTestsFromTestCase(TestXfo)\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n","repo_name":"yoann01/Kraken","sub_path":"unittests/core/maths/test_xfo.py","file_name":"test_xfo.py","file_ext":"py","file_size_in_byte":5385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"36479058321","text":"\"\"\"Streamlined reader of .INI config files, based on built-in *configparser*\r\n\"\"\"\r\n\r\nimport re\r\nimport warnings\r\nimport configparser\r\n\r\ndef read(fIni):\r\n \"\"\"Reads an *.INI file object and returns a two-level dict of\r\n section: key: value collections.\r\n \"\"\"\r\n parser = configparser.ConfigParser()\r\n parser.read_file(fIni)\r\n config = {}\r\n for section in parser.sections():\r\n fields = parser[section]\r\n config[section] = {}\r\n for k, v in fields.items():\r\n if re.match(r\"^\\d+$\", v):\r\n config[section][k] = int(v)\r\n elif re.match(r\"^\\\".+\\\"$\", v):\r\n config[section][k] = v[1:-1]\r\n elif re.match(r\"^(true|false)$\", v.lower()):\r\n config[section][k] = v.lower() == \"true\"\r\n else:\r\n warnings.warn(\"Unparsable value for key '%s', skipping\" % k)\r\n return config\r\n\r\ndef update(config1, config2):\r\n \"\"\"Merges configs 1 and 2 by section, which (unlike dict.update()) ensures\r\n no fields in overlapping sections are lost. Result is in effect the\r\n union of settings from both files, with settings from config2 overriding\r\n those in config1. Does not modify either original config dictionary.\r\n \"\"\"\r\n config3 = config1.copy()\r\n for section in config2.keys():\r\n if section in config3:\r\n config3[section].update(config2[section])\r\n else:\r\n config3[section] = config2[section]\r\n return config3\r\n\r\ndef toTable(config):\r\n \"\"\"Transforms a two-level dictionary of configuration options into a\r\n list-of-dictionaries, each with the following fields:\r\n * section\r\n * field\r\n * value\r\n \"\"\"\r\n table = []\r\n for section in config.keys():\r\n for k, v in config[section].items():\r\n table.append({\r\n \"section\": section,\r\n \"field\": k,\r\n \"value\": v\r\n })\r\n return table\r\n","repo_name":"Tythos/inirdr","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"33758599446","text":"\"\"\"A state machine with context using the State Pattern.\n\nThe state machine is responsible for the flow of the PyASTrX command\nline interface (CLI).\n\nA image diagram of the state machine can be found in the\n`state_machine.png` file.\n\n\"\"\"\nfrom abc import ABC, abstractmethod\nfrom pathlib import Path\nfrom typing import Dict, List, Tuple, Type, Union\nfrom prompt_toolkit import PromptSession, prompt\nfrom prompt_toolkit.auto_suggest import AutoSuggestFromHistory\nfrom prompt_toolkit.completion import FuzzyWordCompleter\nfrom prompt_toolkit.filters import completion_is_selected, has_completions\nfrom prompt_toolkit.history import FileHistory\nfrom prompt_toolkit.key_binding import KeyBindings\nfrom prompt_toolkit.key_binding.key_processor import KeyPressEvent\nfrom prompt_toolkit.shortcuts import checkboxlist_dialog\nfrom prompt_toolkit.styles import Style\nfrom rich import print as rprint\n\nfrom pyastrx import __info__\nfrom pyastrx.axml.python.things2ast import txt2ASTtxt\nfrom pyastrx.config import _prompt_dialog_style\nfrom pyastrx.data_typing import Config\nfrom pyastrx.folder_utils import get_location_and_create\nfrom pyastrx.frontend.manager import Manager\nfrom pyastrx.report.stdout import paging_lxml, rich_paging\nfrom pyastrx.search import Repo\nfrom pyastrx.xml.misc import el_lxml2str\n\n# prompt dialog auto suggest history\nif not Path(\".pyastrx\").exists():\n Path(\".pyastrx\").mkdir()\n_PromptSessionExpr: PromptSession[str] = PromptSession(\n history=FileHistory('.pyastrx/history_new_expr.txt'))\n_PromptSessionRules: PromptSession[str] = PromptSession(\n history=FileHistory('.pyastrx/history_rules.txt'))\n\n\nchar2color = {\n \"s\": \"red1\",\n \"c\": \"bright_red\",\n \"l\": \"purple\",\n \"h\": \"yellow2\",\n \"q\": \"bright_red\",\n \"n\": \"spring_green2\",\n \"a\": \"magenta1\",\n \"t\": \"turquoise2\",\n \"o\": \"magenta1\",\n \"r\": \"orange_red1\",\n \"f\": \"purple\",\n \"x\": \"bright_green\",\n}\n\n\nclass State(ABC):\n \"\"\"A abstract base class to represent a state in the state machine.\n\n Note:\n We are using the forward reference to deal with the\n circular type Context and State.\n \"\"\"\n def __init__(self) -> None:\n self.title = \"\"\n self._context: \"Context\"\n\n @property\n def context(self) -> \"Context\":\n return self._context\n\n @context.setter\n def context(self, context: \"Context\") -> None:\n self._context = context\n\n @abstractmethod\n def run(self) -> None:\n pass\n\n def __del__(self) -> None:\n pass\n\n\nPromptOpt = List[Tuple[str, str, Union[Type[State], str]]]\n\n\nclass StateInterface(State):\n \"\"\"A abstract base class to represent a state interface\n in the state machine.\n\n Note:\n We are using the forward reference to deal with the\n circular type Context and State.\n \"\"\"\n def __init__(self, title: str = \"\", help_text: str = \"\") -> None:\n self.title = title\n self.help_text = help_text\n self.pheader()\n\n @staticmethod\n def poptions(items: List[Tuple[str, str]]) -> None:\n for description, char in items:\n if char == \"-\":\n print(f\"{char*50}\")\n continue\n color = \"white\"\n if char in char2color:\n color = char2color[char]\n rprint(f\"{' '*3}[bold {color}]{char}-{description}[/]\")\n\n def default_prompt(\n self,\n options: PromptOpt) -> None:\n txt_opt, chars, states = zip(*options)\n command2state = {}\n valid_commands = []\n for _, char, state in zip(txt_opt, chars, states):\n if char == \"-\":\n continue\n command2state[char] = state\n valid_commands.append(char)\n command = None\n while command not in valid_commands:\n self.poptions(list(zip(txt_opt, chars)))\n command = prompt(\":\")\n command = command.lower()\n self.context.set_state(command2state[command])\n\n def pheader(self) -> None:\n \"\"\"Print a header representing the current state in the stdout\"\"\"\n s = len(self.title)\n if s == 0:\n return\n rprint(f\"\\n{'='*s}\\n{self.title}\\n{'-'*s}\")\n if self.help_text:\n rprint(self.help_text)\n print(\"-\" * 20)\n\n\nclass Context(Manager):\n def __init__(\n self, initial_state: Type[State],\n config: Config, repo: Repo) -> None:\n # super init manager\n super().__init__(config, repo)\n self._search_interface: Type[StateInterface] = InterfaceMain\n self.set_state(initial_state)\n\n @property\n def search_interface(self) -> Type[StateInterface]:\n return self._search_interface\n\n @search_interface.setter\n def search_interface(self, state: Type[StateInterface]) -> None:\n self._search_interface = state\n\n def set_state(\n self,\n state: Union[Type[State], Type[StateInterface]],\n **kwargs: str) -> None:\n state.context = self # type: ignore\n self._state = state(**kwargs)\n\n\nclass StartState(State):\n def run(self) -> None:\n __info__()\n self.context.set_state(LoadFiles)\n\n\nclass LoadFiles(State):\n def run(self) -> None:\n self.context.load_specitications()\n self.context.set_state(\n InterfaceMain)\n\n\nclass Exit(State):\n def __init__(self, exit_code: int = 0) -> None:\n super().__init__()\n self.exit_code = exit_code\n\n def run(self) -> None:\n exit(self.exit_code)\n # if not self.context.interactive:\n # exit()\n # while True:\n # rprint(\"Are you sure [bold red]you want to exit?[/](y/n)\")\n # command = prompt(':')\n # if command.lower() == \"y\":\n # exit()\n # elif command.lower() == \"n\":\n # self.context.set_state(InterfaceMain())\n # break\n\n\nclass InterfaceMain(StateInterface):\n def __init__(\n self, title: str = \"Main interface\",\n help_text: str = \"\") -> None:\n super().__init__(title=title, help_text=help_text)\n\n def run(self) -> None:\n self.context.resset_custom_expression()\n self.context.search_interface = InterfaceMain\n options: PromptOpt = [\n (\"search using All rules\", \"a\", SearchState),\n (\"search using a Specific rule\", \"s\", InterfaceRules),\n (\"search using a selection of rules\", \"l\", InterfaceSelectRules),\n (\"search using a New expression\", \"n\", InterfaceNewRule),\n ]\n if self.context.is_unique_file():\n options += [\n (\"-\", \"-\", \"\"),\n (\"show XML\", \"x\", ShowXML),\n (\"show AST\", \"t\", ShowAST),\n (\"Open code\", \"o\", ShowCode),\n ]\n else:\n options += [\n (\"-\", \"-\", \"\"),\n (\"show Files\", \"f\", InterfaceFiles),\n ]\n options += [\n (\"-\", \"-\", \"\"),\n (\"Export AST and aXML\", \"e\", InterfaceExport),\n (\"-\", \"-\", \"\"),\n (\"Reload files\", \"r\", LoadFiles),\n (\"Reload YAML\", \"y\", ReloadYAML),\n (\"Help\", \"h\", InterfaceHelp),\n (\"Quit\", \"q\", Exit)\n ]\n self.default_prompt(options)\n\n\nclass ReloadYAML(State):\n def run(self) -> None:\n self.context.reload_yaml()\n self.context.set_state(\n InterfaceMain)\n\n\nclass InterfaceExport(StateInterface):\n def __init__(self) -> None:\n self.title = \"Export current files\"\n super().__init__(title=self.title)\n\n def run(self) -> None:\n options: PromptOpt = [\n (\"Export all aXML\", \"x\", ExportXML),\n (\"Export all AST\", \"t\", ExportAST),\n (\"Cancel\", \"q\", InterfaceMain)\n ]\n self.default_prompt(options)\n\n\nclass InterfaceSelectRules(StateInterface):\n def get_options(self) -> Tuple[\n List[Tuple[int, str]],\n Dict[int, str],\n List[int]]:\n rules = self.context.config.rules\n options = []\n opt2xpath = {}\n default_values = []\n for i, (expression, info) in enumerate(rules.items()):\n spec_name = info.specification_name\n name = info.name\n description = info.description\n why = info.why\n severity = info.severity\n\n str_info = f\"[ {spec_name} ]\" \\\n + f\"| {severity} |\" \\\n + f\" {name}\"\n if why:\n str_info += f\"( {why} )\"\n str_info += f\"\\n{description}\"\n options.append((i, str_info))\n opt2xpath[i] = expression\n check = expression in self.context.selected_rules\n if check:\n default_values.append(i)\n return options, opt2xpath, default_values\n\n def run(self) -> None:\n options, opt2xpath, default_values = self.get_options()\n style = Style.from_dict(_prompt_dialog_style)\n if len(options) == 0:\n self.context.set_state(InterfaceMain)\n rprint(\n \"\\n[bold yellow]These rules will not match any pattern \"\n + \" in the provide files[/]\\n\")\n return\n dialog_text = \"Choose which rules to use for the search. \"\\\n \"The pattern is:\\n\" \\\n + \"\\n [specification]|severity| name(?why)\\nDescription\"\n dialog = checkboxlist_dialog(\n title=\"Rules selection\",\n text=dialog_text,\n values=options,\n default_values=default_values,\n style=style\n )\n selected = dialog.run()\n selected = [] if selected is None else selected\n if len(selected) == 0:\n self.context.selected_rules = []\n self.context.set_state(InterfaceMain)\n return\n self.context.set_xpath_selection([opt2xpath[i] for i in selected])\n\n state = SearchState\n self.context.search_interface = InterfaceSelectRules\n\n self.context.set_state(state)\n\n\nclass InterfaceRules(StateInterface):\n def __init__(self) -> None:\n title = \"Select a rule\"\n help_text = \"Type anything related to the rule\"\\\n + \"or [bold red]q[/] to cancel\"\n super().__init__(title=title, help_text=help_text)\n\n def get_humanized_rules(self) -> Tuple[List[str], Dict[str, str]]:\n self.context.search_interface = InterfaceRules\n\n rules = self.context.config.rules\n rules_str = []\n str2expression = {}\n for expression, info in rules.items():\n spec_name = info.specification_name\n name = info.name\n why = info.why\n description = info.description\n str_info = f\"[ {spec_name} ]\" \\\n + name \\\n + f\"( {why} )\" \\\n + f\": {description}\"\n rules_str.append(str_info)\n str2expression[str_info] = expression\n return rules_str, str2expression\n\n def run(self) -> None:\n key_bindings = KeyBindings()\n filter = has_completions & ~completion_is_selected\n\n @key_bindings.add(\"enter\", filter=filter)\n def _(event: KeyPressEvent) -> None:\n event.current_buffer.go_to_completion(0)\n event.current_buffer.validate_and_handle()\n\n rules_str, str2expression = self.get_humanized_rules()\n rules_str = [\"q\"] + rules_str\n completer = FuzzyWordCompleter(rules_str)\n while True:\n command = _PromptSessionRules.prompt(\n \":\",\n completer=completer,\n auto_suggest=AutoSuggestFromHistory(),\n complete_while_typing=True,\n key_bindings=key_bindings,\n )\n state: Type[State] = InterfaceMain\n if command == \"q\":\n break\n if command in str2expression:\n success = self.context.set_rule(str2expression[command])\n if success:\n state = SearchState\n break\n self.context.set_state(state)\n\n\nclass InterfaceNewRule(StateInterface):\n def __init__(self) -> None:\n title = \"Search using a New expression\"\n help_text = \"Type a xpath expression\"\\\n + \" and press enter to search\"\\\n + \" or type [bold red]q[/] to cancel\\n\"\n super().__init__(title=title, help_text=help_text)\n\n def run(self) -> None:\n self.context.search_interface = InterfaceNewRule\n while True:\n command = _PromptSessionExpr.prompt(\n \":\",\n auto_suggest=AutoSuggestFromHistory()\n )\n state: Type[State] = InterfaceMain\n if command == \"q\":\n break\n self.context.set_rule(command)\n state = SearchState\n break\n self.context.set_state(state)\n\n\nclass AvailableRules(State):\n def run(self) -> None:\n rules = self.context.config.rules\n for rule_info in rules.values():\n # list all attributes of the rule object\n for attr in dir(rule_info):\n if attr.startswith(\"_\"):\n continue\n rprint(f\"{' '*3}{attr}: {getattr(rule_info, attr)}\")\n rprint(\"\\n\")\n self.context.set_state(InterfaceMain)\n\n\nclass InterfaceHelp(StateInterface):\n def __init__(self) -> None:\n title = \"Help\"\n super().__init__(title=title)\n\n def run(self) -> None:\n options: PromptOpt = [\n (\"available Rules\", \"r\", AvailableRules),\n (\"Cancel\", \"q\", InterfaceMain)\n ]\n self.default_prompt(options)\n\n\nclass InterfaceFiles(StateInterface):\n def __init__(self) -> None:\n title = \"Available Files\"\n help_text = \"Select a file to open\"\\\n + \" or [bold red]q[/] to cancel\"\n super().__init__(title=title, help_text=help_text)\n\n def run(self) -> None:\n key_bindings = KeyBindings()\n filter = has_completions & ~completion_is_selected\n\n @key_bindings.add(\"enter\", filter=filter)\n def _(event: KeyPressEvent) -> None:\n event.current_buffer.go_to_completion(0)\n event.current_buffer.validate_and_handle()\n commands = [\"q\"] + self.context.repo.get_files()\n\n completer = FuzzyWordCompleter(commands)\n command = prompt(\n \":\",\n completer=completer,\n complete_while_typing=True,\n key_bindings=key_bindings,\n )\n if command == \"q\":\n self.context.set_state(InterfaceMain)\n file = command\n try:\n self.context.set_current_file(file)\n help_text = f\"{file}\"\n self.context.set_state(InterfaceFile, file=help_text)\n except KeyError:\n self.context.set_state(InterfaceMain)\n\n\nclass InterfaceFile(StateInterface):\n def __init__(\n self, title: str = \"File Options\", file: str = \"\") -> None:\n super().__init__(\n title=title,\n help_text=f\"[bold red]File[/]: {file}\"\n )\n\n def run(self) -> None:\n\n options: PromptOpt = [\n (\"show XML\", \"x\", ShowXML),\n (\"show AST\", \"t\", ShowAST),\n (\"Open file\", \"o\", ShowCode),\n (\"Cancel\", \"q\", InterfaceMain)\n ]\n self.default_prompt(options)\n\n\nclass ShowCode(State):\n def run(self) -> None:\n code = self.context.current_fileinfo.txt\n rich_paging(code)\n self.context.set_state(FileCond)\n\n\nclass ShowXML(State):\n def run(self) -> None:\n axml = self.context.current_fileinfo.axml\n paging_lxml(axml)\n self.context.set_state(FileCond)\n\n\nclass ShowAST(State):\n def run(self) -> None:\n if self.context.current_fileinfo.filename.endswith(\".py\"):\n ast_txt = txt2ASTtxt(\n self.context.current_fileinfo.txt,\n normalize_ast=True)\n rich_paging(ast_txt)\n self.context.set_state(FileCond)\n\n\nclass FileCond(State):\n def run(self) -> None:\n state: Type[State] = InterfaceFiles\n if self.context.is_unique_file():\n state = InterfaceMain\n self.context.set_state(state)\n\n\nclass ExportXML(State):\n def run(self) -> None:\n files = self.context.repo.get_files()\n for filename in files:\n file_info = self.context.repo.cache.get(filename)\n axml = file_info.axml\n axml_str = el_lxml2str(axml)\n export_location = get_location_and_create(\n \".pyastrx/export_data/axml/\", filename, \".xml\")\n with open(export_location, \"w\") as f:\n f.write(axml_str)\n self.context.set_state(InterfaceMain)\n\n\nclass ExportAST(State):\n def run(self) -> None:\n files = self.context.repo.get_files()\n for filename in files:\n file_info = self.context.repo.cache.get(filename)\n if file_info.language == \"python\":\n txt = file_info.txt\n ast_txt = txt2ASTtxt(\n txt,\n normalize_ast=True\n )\n export_location = get_location_and_create(\n \".pyastrx/export_data/ast/\", filename)\n\n with open(export_location, \"w\") as f:\n f.write(ast_txt)\n self.context.set_state(InterfaceMain)\n\n\nclass SearchState(State):\n def run(self) -> None:\n\n _, str_by_file, filter_rules = self.context.search()\n num_files = len(str_by_file)\n\n if not self.context._search_interface == InterfaceNewRule:\n self.context.filter_rules(filter_rules)\n interactive_files = self.context.config.interactive_files and num_files > 1 # noqa\n if not interactive_files:\n self.context.set_state(self.context._search_interface)\n return\n style = Style.from_dict(_prompt_dialog_style)\n selected_files: List[int] = []\n while True:\n options = [\n (i, filename)\n for i, (filename, _) in str_by_file.items()\n ]\n dialog = checkboxlist_dialog(\n title=f\"Files selection: ({num_files} files matched the rules)\", # noqa\n text=\"To disable this dialog, set interactive_files to False in pyastrx.yaml\", # noqa\n values=options,\n default_values=selected_files,\n style=style\n )\n selected = dialog.run()\n selected = [] if selected is None else selected\n if len(selected) == 0:\n break\n selected_files = selected\n output_str = \"\".join(\n str_by_file[i][1] for i in selected\n )\n if self.context.config.pagination:\n rich_paging(output_str)\n else:\n rprint(output_str)\n self.context.set_state(self.context.search_interface)\n","repo_name":"pyastrx/pyastrx","sub_path":"pyastrx/frontend/state_machine.py","file_name":"state_machine.py","file_ext":"py","file_size_in_byte":18968,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"32"}
+{"seq_id":"21285238917","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport multiprocessing, time, os, configparser, binascii, subprocess as sp, smtplib, json, boto3, MySQLdb, requests \nfrom smtplib import SMTPException\nfrom multiprocessing import Pool, TimeoutError\nfrom iron_mq import *\n\n# We'll initialize the config variable.\nconfig = configparser.ConfigParser()\n\n# We'll instruct the config to read the .ini file.\nconfig_file = os.path.join(os.path.dirname(__file__), 'config.ini')\nconfig.read(config_file)\nprint (\"Ejecutando Worker\")\nprint (\"Ejecutando Worker1\")\n\n# We will read the connection configuration to the Amazon RDS Service.\ndb_host = config['db.amazon']['host']\ndb_port = config['db.amazon']['port']\ndb_user = config['db.amazon']['user']\ndb_passw = config['db.amazon']['passw']\ndb_name = config['db.amazon']['db']\n\nironmq = IronMQ(host=os.environ['IRON_HOST'], project_id=os.environ['IRON_ID'], token=os.environ['IRON_TOKEN'])\nqueue = ironmq.queue(os.environ['IRON_QUEUE'])\n\n# We create a connection to the database and create a cursor\ndbConnection = MySQLdb.connect(\n\thost = db_host,\n\tport = int(db_port),\n\tuser = db_user, \n\tpasswd = db_passw,\n\tdb = db_name)\ndbCursor = dbConnection.cursor()\n\ndynamodb = boto3.resource('dynamodb', region_name=os.environ['AWS_REGION'], aws_access_key_id=os.environ['AWS_ACCESS_KEY_ID'], aws_secret_access_key=os.environ['AWS_SECRET_ACCESS_KEY'])\ns3 = boto3.resource('s3', region_name=os.environ['S3_REGION'], aws_access_key_id=os.environ['S3_ACCESS_KEY_ID'], aws_secret_access_key=os.environ['S3_SECRET_ACCESS_KEY'])\nsqs = boto3.resource('sqs', region_name=os.environ['AWS_REGION'], aws_access_key_id=os.environ['AWS_ACCESS_KEY_ID'], aws_secret_access_key=os.environ['AWS_SECRET_ACCESS_KEY'])\nbucket = s3.Bucket(config['DEFAULT']['bucketS3'])\ntable = dynamodb.Table('videos')\n#queue = sqs.get_queue_by_name(QueueName='smts-videos-queue')\nfolder = config['DEFAULT']['folder']\nfolder_s3 = config['DEFAULT']['folderS3']\n# We read the email conf.\ne_address = config['smtp.amazon']['address']\ne_port = config['smtp.amazon']['port']\ne_user = config['smtp.amazon']['user']\ne_passw = config['smtp.amazon']['passw']\ne_domain = config['DEFAULT']['domain']\n\ndef main():\n\twhile True:\n\t\tprint (\"hi\")\n\t\tcpu_count = multiprocessing.cpu_count()\n\t\tprint (cpu_count)\n\t\tvideos = get_videos_to_convert(cpu_count)\n\t\twith multiprocessing.Pool(cpu_count) as pool:\n\t\t\tpool.map(convert_video, videos)\n\t\ttime.sleep(50)\n\t\ndef get_videos_to_convert(cpu_count):\n\tvideos = []\n\t#messages = queue.receive_messages(MaxNumberOfMessages=cpu_count)\n\tmsgs = queue.reserve(max=cpu_count, timeout=None, wait=0, delete=False)\n\tmessags = msgs['messages']\n\tfor message in messags:\n\t\tvideo_inf = message['body'] + ';' + message['reservation_id'] + ';' + message['id'] \n\t\tvideos.append(video_inf)\n\treturn videos\n\ndef convert_video(video):\n\tvideo_id, video_concurso_id, video_name, message_reservation_id, message_id = video.split(';')\n\tprint (video_id)\n\tprint (video_concurso_id)\n\tprint (video_name)\n\tprint (folder+video_name)\n\tprint (folder_s3+video_name)\n\tprint (message_reservation_id)\n\tprint (message_id)\n\t\n\t# do all prints\n\tbucket.download_file(folder_s3+video_name, folder+video_name)\n\tvideo_output_name = video_name.rsplit('.', 1)[0]+\".mp4\"\n\tcommand = \"ffmpeg -i {0}{1} -f mp4 -vcodec h264 -c:a aac -strict -2 {0}{2} -y\"\n\tos.system(command.format(folder, video_name, video_output_name))\n\tbucket.upload_file(folder+video_output_name, folder_s3+video_output_name)\n\tdbCursor.execute(\"UPDATE videos SET estado=1 WHERE video_source='{0}'\".format(video_name))\n\tkey = os.environ['MAIL_KEY']\n\tsandbox = os.environ['MAIL_SANDBOX']\n\trecipient = 'smarttoolsg5@gmail.com'\n\n\trequest_url = 'https://api.mailgun.net/v3/{0}/messages'.format(sandbox)\n\trequest = requests.post(request_url, auth=('api', key), data={\n\t 'from': 'smarttoolsg5@gmail.com',\n\t 'to': recipient,\n\t 'subject': 'Video Convertido',\n\t 'text': 'Su video ha sido convertido de manera exitosa. Puedes verlo ingresando a la página del concurso.'\n\t})\n\tqueue.delete(message_id, message_reservation_id)\n\t# We send the email\n\ttry:\n\t\t# Create the message to be sent once the convertion is finished.\n\t\tmessage = \"\"\"\n\t\tSubject: Conversión de video\n\n\t\tSu video ha sido convertido de manera exitosa. Puedes verlo ingresando a la página del concurso.\n\t\t\"\"\"\n\n\t\t# Create the message variables\n\t\tsender = 'smarttoolsg5@gmail.com'\n\t\treceivers = ['smarttoolsg5v2@gmail.com']\n\t\tsmtpObj = smtplib.SMTP(e_address, int(e_port), e_domain)\n\t\tsmtpObj.set_debuglevel(1)\n\t\tsmtpObj.starttls()\n\t\tsmtpObj.login(e_user, e_passw)\n\t\tsmtpObj.sendmail(sender, receivers, message)\n\t\tsmtpObj.quit()\n\t\tprint (\"Successfully sent email\")\n\t\t\n\t\t'''queue.delete_messages(\n\t\t\tEntries=[\n\t\t \t{\n\t\t \t\t'Id': str(int(round(time.time() * 1000))),\n\t\t\t\t\t'ReceiptHandle': message_receipt_handler\n\t\t\t\t},\n\t\t\t]\n\t\t)'''\n\texcept SMTPException:\n\t\tprint (\"Error: unable to send email\")\n\n\nif __name__ == \"__main__\":\n\tmain()\n","repo_name":"datorresr/smtsworker","sub_path":"worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":4937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"4604707629","text":"import numpy.matlib as nm\nfrom gecatsim.pyfiles.CommonTools import *\n\ndef Spectrum(cfg):\n '''\n Read spectral information from a file and return a structure specifying the spectrum.\n The returned spectrum is resampled to new Evec and is scaled to mA and view time.\n The order is Ebin->row->, the dim is python is [col, row, Ebin], i.e. [pixel, Ebin]\n \n Mingye Wu, GE Research\n \n '''\n \n viewTime = cfg.protocol.rotationTime/cfg.protocol.viewsPerRotation/cfg.sim.subViewCount*cfg.protocol.dutyRatio\n specScale = cfg.protocol.spectrumScaling*cfg.protocol.mA*viewTime\n \n if not cfg.spec:\n #if not hasattr(cfg, 'spec'):\n cfg.spec = CFG()\n \n ###------------- monochromatic\n if cfg.physics.monochromatic>0:\n cfg.spec.nEbin = 1\n cfg.spec.Evec = np.array(cfg.physics.monochromatic, dtype=np.single)\n cfg.spec.Ivec = 1.2e6*np.ones([cfg.det.totalNumCells, 1], dtype=np.single)*specScale\n cfg.sim.Evec = cfg.spec.Evec\n return cfg\n \n ###------------- polychromatic\n # Rescale to match CatSim's unit\n # Spectrum is in unit: photons/sec// at 1-m distance\n # CatSim uses mm and mA, but some spectrum files use cm or A\n if not cfg.protocol.spectrumUnit_mm:\n specScale *= 1e-2\n if not cfg.protocol.spectrumUnit_mA:\n specScale *= 1e-3\n \n # Read spectrum file\n cfg.protocol.spectrumFilename = my_path.find(\"spectrum\", cfg.protocol.spectrumFilename, \"\")\n Evec0, Ivec0, takeOffAngle = spectrum_read(cfg.protocol.spectrumFilename)\n Ivec0 *= specScale\n \n Emin = Evec0[0]-0.5*(Evec0[1]-Evec0[0])\n Emax = Evec0[-1]+0.5*(Evec0[-1]-Evec0[-2])\n nEbin = cfg.physics.energyCount\n Ebin = (Emax-Emin)/nEbin\n \n # resample to new Ebin vector\n Evec1 = np.linspace(Emin+Ebin/2, Emax-Ebin/2, nEbin)\n Ivec1 = overlap(Evec0, Ivec0, Evec1)\n inputEnergy = Evec0 @ Ivec0\n outputEnergy = Evec1 @ Ivec1\n Ivec1 *= inputEnergy/outputEnergy\n \n # change dtype\n Evec1 = Evec1.astype(np.float32)\n Ivec1 = Ivec1.astype(np.float32)\n \n # repeat to all pixels\n Ivec1 = nm.repmat(Ivec1, cfg.det.totalNumCells, 1)\n\n cfg.spec.nEbin = nEbin\n cfg.spec.Evec = Evec1\n cfg.spec.Ivec = Ivec1\n cfg.sim.Evec = cfg.spec.Evec\n\n return cfg\n\n\ndef spectrum_read(spectrumFile):\n '''\n Read the spectrum file.\n The output Evec and Ivec are 2-D numpy array with shape [nEbin, 1]\n \n '''\n d0 = []\n for line in open(spectrumFile, 'r'):\n line = line[:-1] # remove the end '\\n'\n if line and line[0].isdigit():\n d0.append(line)\n \n nEbin = int(d0[0])\n Evec = []\n Ivec = []\n for ii in range(1, nEbin+1):\n tmp = [float(x.strip()) for x in d0[ii].split(',')]\n Evec.append(tmp[0])\n Ivec.append(tmp[1])\n\n Evec = np.array(Evec, dtype='single')\n Ivec = np.array(Ivec, dtype='single')\n \n if len(d0)>nEbin+1:\n takeOffAngle = float(d0[nEbin+1])\n else:\n takeOffAngle = 0\n \n return Evec, Ivec, takeOffAngle\n\n\nif __name__ == \"__main__\":\n\n cfg = source_cfg(\"./cfg/default.cfg\")\n \n cfg.det.totalNumCells = 5;\n \n cfg.protocol.spectrumFilename = \"tungsten_tar7_120_unfilt.dat\"\n cfg.physics.energyCount = 10\n cfg.protocol.spectrumScaling = 1\n cfg.physics.monochromatic = -1\n \n cfg.protocol.mA = 200\n cfg.protocol.rotationTime = 1\n cfg.protocol.viewsPerRotation = 984\n \n cfg.sim.subViewCount = 1\n cfg.protocol.dutyRatio = 1\n \n #Evec, Ivec, takeOffAngle = spectrum_read(cfg.protocol.spectrumFilename)\n #check_value(Evec)\n #check_value(Ivec)\n #check_value(takeOffAngle)\n \n cfg = Spectrum(cfg)\n check_value(cfg.spec.nEbin)\n check_value(cfg.spec.Evec)\n check_value(cfg.spec.Ivec)\n \n","repo_name":"xcist/main","sub_path":"gecatsim/pyfiles/Spectrum.py","file_name":"Spectrum.py","file_ext":"py","file_size_in_byte":3813,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"32"}
+{"seq_id":"40743044567","text":"def solution(numbers, target):\n\tanswer = []\n\n\tdef bfs(val, depth):\n\t\tif depth == len(numbers):\n\t\t\tif val == target:\n\t\t\t\tanswer.append(1) # answer += 1 은 할당이라 안된다.. global도 안된다..\n\t\t\t\treturn\n\t\telse:\n\t\t\tbfs(val + numbers[depth], depth + 1)\n\t\t\tbfs(val - numbers[depth], depth + 1)\n\n\tbfs(0, 0)\n\treturn len(answer)\n\n#\nanswer = 0\n\ndef bfs(arr, val, depth, k, tg):\n global answer\n if depth == k:\n if val == tg:\n answer += 1\n return\n else:\n bfs(arr, val + arr[depth], depth + 1, k, tg)\n bfs(arr, val - arr[depth], depth + 1, k, tg)\n\ndef solution(numbers, target):\n global answer\n bfs(numbers, 0, 0, len(numbers), target)\n return answer","repo_name":"soulgchoi/Algorithm","sub_path":"Programmers/Level 2/타겟 넘버.py","file_name":"타겟 넘버.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"}
+{"seq_id":"13738718473","text":"__author__ = \"Sudarat tokampang\"\n\n# standard libraries\nfrom datetime import datetime\nimport os\nimport sys\nimport unittest\n\nsys.path.append(os.path.join(\"..\", \"..\", \"src\", \"app\"))\n# local files\nfrom src.app import display\n\n\nclass TestDisplay(unittest.TestCase):\n def test_update_line(self):\n \"\"\" Test that calling the update_line method\n in display.Display works correctly \"\"\"\n _display = display.Display(None)\n time = [datetime(2023, 1, 24, 10, 50, 12)]\n temps = [5]\n label = \"device 2 temp\"\n _display.update_line(time, temps, label)\n print(\"getting x y data\")\n print(_display.lines[label].get_xydata())\n self.assertListEqual(_display.lines[label].get_xydata().tolist(),\n [[19381.45152777778, 5.0]])\n\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"itssudaratmookii/IoT_rpi","sub_path":"test/unit_tests/test_display.py","file_name":"test_display.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"}
+{"seq_id":"33638458843","text":"#Embedded file name: c:/depot/games/branches/release/EVE-TRANQUILITY/eve/client/script/ui/shared/container.py\nimport xtriui\nimport uix\nimport uiutil\nimport blue\nimport lg\nimport uthread\nimport listentry\nimport base\nimport service\nimport uiconst\nimport uicls\nimport log\nimport localization\nimport trinity\nimport invCtrl\nimport util\nimport localizationUtil\nimport telemetry\nfrom math import pi, fabs\ncolMargin = rowMargin = 12\n\nclass InvContViewBtns(uicls.ContainerAutoSize):\n __guid__ = 'uicls.InvContViewBtns'\n default_name = 'InvContViewBtns'\n default_align = uiconst.TOPLEFT\n default_height = 16\n\n def ApplyAttributes(self, attributes):\n uicls.ContainerAutoSize.ApplyAttributes(self, attributes)\n self.controller = attributes.controller\n self.viewMode = None\n self.btnViewModeIcons = uicls.ButtonIcon(texturePath='res:/UI/Texture/Icons/38_16_188.png', parent=self, width=self.height, align=uiconst.TOLEFT, func=self.SetViewModeIcons, hint=localization.GetByLabel('UI/Inventory/Icons'))\n self.btnViewModeIconList = uicls.ButtonIcon(texturePath='res:/UI/Texture/Icons/38_16_189.png', parent=self, align=uiconst.TOLEFT, width=self.height, func=self.SetViewModeIconList, hint=localization.GetByLabel('UI/Inventory/Details'))\n self.btnViewModeList = uicls.ButtonIcon(texturePath='res:/UI/Texture/Icons/38_16_190.png', parent=self, align=uiconst.TOLEFT, width=self.height, func=self.SetViewModeList, hint=localization.GetByLabel('UI/Inventory/List'))\n\n def SetViewModeIcons(self):\n self._SetViewMode(0)\n\n def SetViewModeIconList(self):\n self._SetViewMode(1)\n\n def SetViewModeList(self):\n self._SetViewMode(2)\n\n def _SetViewMode(self, viewMode):\n self.viewMode = viewMode\n self.UpdateButtons(viewMode)\n self.controller.SetInvContViewMode(viewMode)\n\n def UpdateButtons(self, viewMode):\n self.btnViewModeIcons.SetActive(viewMode == 0)\n self.btnViewModeIconList.SetActive(viewMode == 1)\n self.btnViewModeList.SetActive(viewMode == 2)\n\n\nclass InvContQuickFilter(uicls.Container):\n __guid__ = 'uicls.InvContQuickFilter'\n default_align = uiconst.TOPLEFT\n default_height = 20\n default_width = 100\n\n def ApplyAttributes(self, attributes):\n uicls.Container.ApplyAttributes(self, attributes)\n self.invCont = attributes.invCont\n self.inputThread = None\n self.quickFilterInputBox = uicls.SinglelineEdit(name='quickFilterInputBox', parent=self, align=uiconst.CENTER, width=self.width, top=0, OnChange=self.SetQuickFilterInput, hinttext=localization.GetByLabel('UI/Inventory/Filter'))\n self.quickFilterInputBox.ShowClearButton(hint=localization.GetByLabel('UI/Inventory/Clear'))\n self.quickFilterInputBox.SetHistoryVisibility(0)\n if self.invCont:\n self.SetInvCont(self.invCont)\n\n def SetInvCont(self, invCont):\n self.invCont = invCont\n if not settings.user.ui.Get('keepInvQuickFilterInput', False):\n self.quickFilterInputBox.SetText(u'')\n self.quickFilterInputBox.SetHintText(localization.GetByLabel('UI/Inventory/Filter'))\n\n def GetQuickFilterInput(self):\n return self.quickFilterInputBox.GetText()\n\n def SetQuickFilterInput(self, txt):\n if self.inputThread:\n return\n self.inputThread = uthread.new(self._SetQuickFilterInput, txt)\n\n def ClearFilter(self):\n self.quickFilterInputBox.SetValue('')\n\n def _SetQuickFilterInput(self, txt):\n if txt:\n blue.synchro.SleepWallclock(300)\n if self.invCont:\n self.invCont.SetQuickFilterInput(self.quickFilterInputBox.GetValue())\n self.inputThread = None\n\n\nclass InvContCapacityGauge(uicls.Container):\n __guid__ = 'uicls.InvContCapacityGauge'\n __notifyevents__ = ['OnItemChange']\n default_align = uiconst.TOPLEFT\n default_state = uiconst.UI_NORMAL\n default_clipChildren = True\n COLOR_SECONDARY = (0.0, 0.52, 0.67)\n COLOR_PRIMARY = (0.0, 0.31, 0.4)\n BG_OPACITY_NORMAL = 0.8\n BG_OPACITY_PINNED = 0.2\n\n def ApplyAttributes(self, attributes):\n uicls.Container.ApplyAttributes(self, attributes)\n sm.RegisterNotify(self)\n invCont = attributes.invCont\n self.secondaryVolume = 0.0\n self.additionalVolume = 0.0\n self.refreshGaugesThread = None\n self.resetPending = False\n self.capacityText = uicls.EveLabelSmall(name='capacityText', parent=self, align=uiconst.CENTER, top=1)\n self.bg = uicls.Fill(bgParent=self, color=util.Color.GetGrayRGBA(0.0, self.BG_OPACITY_NORMAL))\n uicls.Frame(parent=self, color=(0.5, 0.5, 0.5, 0.05))\n self.capacityGaugeParentSec = uicls.Container(name='capacityGaugeParent', parent=self, align=uiconst.TOALL, state=uiconst.UI_DISABLED)\n self.capacityGaugeSec = uicls.GradientSprite(parent=self.capacityGaugeParentSec, align=uiconst.TOLEFT_PROP, rotation=-pi / 2, rgbData=[(0, self.COLOR_SECONDARY)], alphaData=[(0, 0.7), (0.5, 1.0), (1.0, 0.7)])\n self.capacityGaugeParent = uicls.Container(name='capacityGaugeParent', parent=self, align=uiconst.TOALL, state=uiconst.UI_DISABLED)\n self.capacityGauge = uicls.GradientSprite(parent=self.capacityGaugeParent, align=uiconst.TOLEFT_PROP, rotation=-pi / 2, rgbData=[(0, self.COLOR_PRIMARY)], alphaData=[(0, 0.7), (0.5, 1.0), (1.0, 0.7)])\n self.capacityGaugeParentAdd = uicls.Container(name='capacityGaugeParentAdd', parent=self, align=uiconst.TOALL, state=uiconst.UI_DISABLED)\n self.capacityGaugeAdd = uicls.GradientSprite(parent=self.capacityGaugeParent, align=uiconst.TOLEFT_PROP, rotation=-pi / 2, rgbData=[(0, self.COLOR_SECONDARY)], alphaData=[(0, 0.7), (0.5, 1.0), (1.0, 0.7)])\n if invCont:\n self.SetInvCont(invCont)\n else:\n self.invCont = None\n\n def LiteMode(self, isOn):\n if isOn:\n self.bg.opacity = self.BG_OPACITY_PINNED\n else:\n self.bg.opacity = self.BG_OPACITY_NORMAL\n\n def SetInvCont(self, invCont):\n self.invCont = invCont\n self.SetSecondaryVolume()\n self.SetAdditionalVolume()\n self.RefreshCapacity()\n self.bg.display = self.invCont.invController.hasCapacity\n\n @telemetry.ZONE_METHOD\n def RefreshCapacity(self):\n if not self.invCont:\n return\n self.UpdateLabel()\n proportion = 0.0\n if self.invCont.invController.hasCapacity:\n cap = self.invCont.invController.GetCapacity()\n if cap.capacity:\n proportion = min(1.0, max(0.0, cap.used / float(cap.capacity)))\n currWidth = self.capacityGauge.width\n duration = 0.5 * fabs(currWidth - proportion) ** 0.3\n uicore.animations.MorphScalar(self.capacityGauge, 'width', currWidth, proportion, duration=duration)\n\n def UpdateLabel(self):\n if self.invCont.invController.hasCapacity:\n cap = self.invCont.invController.GetCapacity()\n volume = cap.used + self.additionalVolume\n text = localization.GetByLabel('UI/Inventory/ContainerQuantityAndCapacity', quantity=volume, capacity=cap.capacity)\n else:\n volume = 0.0\n for item in self.invCont.invController.GetItems():\n volume += cfg.GetItemVolume(item)\n\n text = localization.GetByLabel('UI/Inventory/ContainerCapacity', capacity=volume)\n if self.secondaryVolume:\n if text:\n text = '(%s) ' % localizationUtil.FormatNumeric(self.secondaryVolume, useGrouping=True, decimalPlaces=1) + text\n self.capacityText.text = text\n\n def HideLabel(self):\n self.capacityText.Hide()\n\n def ShowLabel(self):\n self.capacityText.Show()\n\n def GetHint(self):\n return self.capacityText.text\n\n @telemetry.ZONE_METHOD\n def SetAdditionalVolume(self, items = []):\n if not self.invCont:\n return\n volume = 0\n for item in items:\n volume += cfg.GetItemVolume(item)\n\n self.additionalVolume = volume\n value = self.GetVolumeProportion(volume)\n animValue = min(value, 1.0 - self.capacityGauge.width)\n currWidth = self.capacityGaugeAdd.width\n duration = 0.5 * fabs(currWidth - animValue) ** 0.3\n uicore.animations.MorphScalar(self.capacityGaugeAdd, 'width', currWidth, animValue, duration=duration)\n color = self.COLOR_SECONDARY\n if self.invCont.invController.hasCapacity:\n cap = self.invCont.invController.GetCapacity()\n if cap.capacity and volume + cap.used > cap.capacity:\n color = (0.6, 0, 0)\n self.capacityGaugeAdd.SetGradient(colorData=[(0.0, color)])\n self.UpdateLabel()\n\n @telemetry.ZONE_METHOD\n def SetSecondaryVolume(self, items = []):\n volume = 0\n for item in items:\n volume += cfg.GetItemVolume(item)\n\n self.secondaryVolume = volume\n value = self.GetVolumeProportion(volume)\n currWidth = self.capacityGaugeSec.width\n duration = 0.5 * fabs(currWidth - value) ** 0.3\n uicore.animations.MorphScalar(self.capacityGaugeSec, 'width', currWidth, value, duration=duration)\n self.UpdateLabel()\n\n def GetVolumeProportion(self, volume):\n if self.invCont and self.invCont.invController.hasCapacity:\n cap = self.invCont.invController.GetCapacity()\n if cap.capacity:\n return min(1.0, volume / cap.capacity)\n return 0\n\n def OnItemChange(self, item = None, change = None):\n if not self.invCont:\n return\n if item.itemID == util.GetActiveShip():\n return\n if item.locationID == self.invCont.invController.itemID:\n self.ResetGauges()\n if const.ixLocationID in change:\n if change[const.ixLocationID] == self.invCont.invController.itemID:\n self.ResetGauges()\n\n def ResetGauges(self):\n self.resetPending = True\n if self.refreshGaugesThread:\n return\n self.refreshGaugesThread = uthread.new(self._ResetGauges)\n\n def _ResetGauges(self):\n try:\n while self.resetPending:\n self.RefreshCapacity()\n nodes = self.invCont.scroll.GetSelected()\n self.SetSecondaryVolume([ node.item for node in nodes ])\n self.SetAdditionalVolume()\n self.resetPending = False\n blue.synchro.Sleep(500)\n\n finally:\n self.refreshGaugesThread = None\n\n\nclass _InvContBase(uicls.Container):\n __guid__ = 'invCont._InvContBase'\n default_name = 'InventoryContainer'\n default_showControls = False\n __notifyevents__ = ['OnPostCfgDataChanged', 'OnInvTempFilterChanged']\n __invControllerClass__ = None\n\n def ApplyAttributes(self, attributes):\n uicls.Container.ApplyAttributes(self, attributes)\n sm.RegisterNotify(self)\n self.itemID = attributes.itemID\n self.displayName = attributes.displayName\n self.activeFilters = attributes.get('activeFilters', [])\n showControls = attributes.get('showControls', self.default_showControls)\n self.quickFilterInput = attributes.Get('quickFilterInput', None)\n self.invController = self._GetInvController(attributes)\n self.items = []\n self.cols = None\n self.droppedIconData = (None, None)\n self.iconWidth = 64\n self.iconHeight = 92\n self.sr.resizeTimer = None\n self.scrollTimer = None\n self.tmpDropIdx = {}\n self.refreshingView = False\n self.reRefreshView = False\n self.changeViewModeThread = None\n self.hintText = None\n self.dragStart = None\n self.previouslyHighlighted = None\n self.dragContainer = None\n self.itemChangeThread = None\n self.initialized = False\n self.numFilteredItems = 0\n if showControls:\n self.topCont = uicls.Container(parent=self, align=uiconst.TOTOP, height=22)\n uicls.InvContViewBtns(parent=self.topCont, align=uiconst.CENTERLEFT, controller=self)\n uicls.InvContQuickFilter(parent=self.topCont, align=uiconst.CENTERRIGHT, invCont=self)\n self.scroll = uicls.Scroll(parent=self, state=uiconst.UI_PICKCHILDREN)\n self.scroll.sr.id = 'containerWnd_%s' % self.invController.GetName()\n self.scroll.OnNewHeaders = self.OnNewHeadersSet\n self.scroll.allowFilterColumns = 1\n self.scroll.SetColumnsHiddenByDefault(uix.GetInvItemDefaultHiddenHeaders())\n self.scroll.dad = self\n self.scroll.Copy = self.Copy\n self.scroll.Cut = self.Cut\n self.scroll.Paste = self.Paste\n content = self.content = self.scroll.GetContentContainer()\n content.OnDragEnter = self.OnDragEnter\n content.OnDragExit = self.OnDragExit\n content.OnDropData = self.OnScrollContentDropData\n content.GetMenu = lambda : GetContainerMenu(self)\n content.OnMouseUp = self.scroll.OnMouseUp = self.OnScrollMouseUp\n content.OnMouseDown = self.scroll.OnMouseDown = self.OnScrollMouseDown\n self.invSvcCookie = sm.GetService('inv').Register(self)\n self.sortIconsBy, self.sortIconsDir = settings.user.ui.Get('containerSortIconsBy_%s' % self.name, ('type', 0))\n self.viewMode = settings.user.ui.Get('containerViewMode_%s' % self.name, 'icons')\n uthread.new(self.ChangeViewMode, ['icons', 'details', 'list'].index(self.viewMode))\n\n def _GetInvController(self, attributes):\n return self.__invControllerClass__(itemID=attributes.itemID)\n\n def SetInvContViewMode(self, value):\n self.ChangeViewMode(value)\n\n def SetQuickFilterInput(self, filterTxt = ''):\n if len(filterTxt) > 0:\n self.quickFilterInput = filterTxt.lower()\n self.Refresh()\n else:\n prefilter = self.quickFilterInput\n self.quickFilterInput = None\n if prefilter != None:\n self.Refresh()\n self.hintText = None\n\n def QuickFilter(self, item):\n name = uix.GetItemName(item).lower()\n typename = cfg.invtypes.Get(item.typeID).name.lower()\n input = self.quickFilterInput.lower()\n return name.find(input) + 1 or typename.find(input) + 1\n\n def OnInvTempFilterChanged(self):\n self.Refresh()\n\n def SetFilters(self, filters):\n self.activeFilters = filters\n self.Refresh()\n\n def FilterOptionsChange(self, combo, label, value, *args):\n if combo and combo.name == 'filterCateg':\n if value is None:\n ops = [(localization.GetByLabel('UI/Inventory/All'), None)]\n else:\n ops = sm.GetService('marketutils').GetFilterops(value)\n self.sr.filterGroup.LoadOptions(ops)\n settings.user.ui.Set('containerCategoryFilter%s' % self.name.title(), value)\n elif combo and combo.name == 'filterGroup':\n settings.user.ui.Set('containerGroupFilter%s' % self.name.title(), value)\n self.Refresh()\n\n def OnPostCfgDataChanged(self, what, data):\n if what == 'evelocations':\n itemID = data[0]\n for each in self.scroll.GetNodes():\n if each and getattr(each, 'item', None) and each.item.itemID == itemID:\n each.name = None\n uix.GetItemLabel(each.item, each, 1)\n if each.panel:\n each.panel.UpdateLabel()\n return\n\n def _OnClose(self, *args):\n if self.itemChangeThread:\n self.itemChangeThread.kill()\n\n def ChangeViewMode(self, viewMode = 0):\n if self.changeViewModeThread:\n self.changeViewModeThread.kill()\n self.changeViewModeThread = uthread.new(self._ChangeViewMode, viewMode)\n\n def _ChangeViewMode(self, viewMode = 0):\n if self.destroyed:\n return\n self.viewMode = ['icons', 'details', 'list'][viewMode]\n settings.user.ui.Set('containerViewMode_%s' % self.name, self.viewMode)\n self.items = self.invController.GetItems()\n self.invController.OnItemsViewed()\n self.PrimeItems([ item for item in self.items if item is not None ])\n if self.items:\n self.items = self.FilterItems(self.items)\n self.UpdateHint()\n try:\n if self.viewMode == 'icons':\n self.SortIconsBy(self.sortIconsBy, self.sortIconsDir)\n else:\n self.RefreshView()\n except UserError:\n self.Close()\n if self.sr.Get('cookie', None):\n sm.GetService('inv').Unregister(self.invSvcCookie)\n raise \n\n def FilterItems(self, items):\n oldNum = len(items)\n if self.quickFilterInput:\n items = uiutil.NiceFilter(self.QuickFilter, items)\n for filter in self.activeFilters:\n items = sm.GetService('itemFilter').FilterItems(items, filter)\n\n if self.invController.filtersEnabled:\n items = sm.GetService('itemFilter').ApplyTempFilter(items)\n self.numFilteredItems = oldNum - len(items)\n return items\n\n def UpdateHint(self):\n if len(self.items) == 0:\n if self.numFilteredItems:\n self.hintText = localization.GetByLabel('UI/Inventory/NothingFoundFiltered', numFilters=self.numFilteredItems)\n elif not self.invController.CheckCanQuery():\n self.hintText = localization.GetByLabel('UI/Inventory/NoAccessHint')\n else:\n self.hintText = localization.GetByLabel('UI/Common/NothingFound')\n else:\n self.hintText = ''\n self.scroll.ShowHint(self.hintText)\n\n def Refresh(self):\n self.ChangeViewMode(['icons', 'details', 'list'].index(self.viewMode))\n\n def SortIconsBy(self, sortby, direction):\n self.sortIconsBy = sortby\n self.sortIconsDir = direction\n settings.user.ui.Set('containerSortIconsBy_%s' % self.name, (sortby, direction))\n sortData = []\n for rec in self.items:\n if rec is None:\n continue\n name = uix.GetItemName(rec).lower()\n type = uix.GetCategoryGroupTypeStringForItem(rec).lower()\n id = rec.itemID\n qty = 0\n if not (rec.singleton or rec.typeID in (const.typeBookmark,)):\n qty = rec.stacksize\n if sortby == 'name':\n sortKey = (name,\n type,\n qty,\n id,\n rec)\n elif sortby == 'qty':\n sortKey = (qty,\n type,\n name,\n id,\n rec)\n elif sortby == 'type':\n sortKey = (type,\n name,\n qty,\n id,\n rec)\n else:\n log.LogError('Unknown sortkey used in container sorting', sortby, direction)\n continue\n sortData.append((sortKey, rec))\n\n sorted = uiutil.SortListOfTuples(sortData)\n if direction:\n sorted.reverse()\n self.items = sorted\n self.RefreshView()\n\n def _OnSizeChange_NoBlock(self, *args):\n if self.initialized:\n self.sr.resizeTimer = base.AutoTimer(250, self.OnEndScale_)\n\n def OnEndScale_(self, *etc):\n self.sr.resizeTimer = None\n oldcols = self.cols\n self.RefreshCols()\n if self.viewMode == 'icons':\n if self.refreshingView:\n self.reRefreshView = True\n return\n if oldcols != self.cols:\n uthread.new(self.RefreshView)\n\n @telemetry.ZONE_METHOD\n def AddItem(self, rec, index = None, fromWhere = None):\n if self.quickFilterInput:\n if not self.QuickFilter(rec):\n return\n if not self.FilterItems([rec]):\n return\n lg.Info('vcont', 'AddItem', fromWhere, rec.stacksize, cfg.invtypes.Get(rec.typeID).name)\n for node in self.scroll.sr.nodes:\n if self.viewMode in ('details', 'list'):\n if node is not None and node.Get('item', None) and node.item.itemID == rec.itemID:\n lg.Warn('vcont', 'Tried to add an item that is already there??')\n self.UpdateItem(node.item)\n return\n else:\n for internalNode in node.internalNodes:\n if internalNode is not None and internalNode.item.itemID == rec.itemID:\n lg.Warn('vcont', 'Tried to add an item that is already there??')\n self.UpdateItem(internalNode.item)\n return\n\n if self.viewMode in ('details', 'list'):\n self.items.append(rec)\n self.scroll.AddEntries(-1, [listentry.Get('InvItem', data=uix.GetItemData(rec, self.viewMode, self.invController.viewOnly, container=self, scrollID=self.scroll.sr.id))])\n self.UpdateHint()\n else:\n if index is not None:\n while index < len(self.items):\n if self.items[index] is None:\n return self.SetItem(index, rec)\n index += 1\n\n while index >= len(self.scroll.sr.nodes) * self.cols:\n self.AddRow()\n\n return self.SetItem(index, rec)\n if len(self.items) and None in self.items:\n idx = self.tmpDropIdx.get(rec.itemID, None)\n if idx is None:\n idx = self.items.index(None)\n return self.SetItem(idx, rec)\n if not self.cols:\n self.RefreshCols()\n if index >= len(self.scroll.sr.nodes) * self.cols:\n self.AddRow()\n return self.SetItem(0, rec)\n\n @telemetry.ZONE_METHOD\n def UpdateItem(self, rec, *etc):\n lg.Info('vcont', 'UpdateItem', rec and '[%s %s]' % (rec.stacksize, cfg.invtypes.Get(rec.typeID).name))\n if self.viewMode in ('details', 'list'):\n idx = 0\n for each in self.items:\n if each.itemID == rec.itemID:\n self.items[idx] = rec\n break\n idx += 1\n\n for entry in self.scroll.sr.nodes:\n if entry.item.itemID == rec.itemID:\n newentry = uix.GetItemData(rec, self.viewMode, self.invController.viewOnly, container=self, scrollID=self.scroll.sr.id)\n for key, value in newentry.iteritems():\n entry[key] = value\n\n if entry.panel:\n entry.panel.Load(entry)\n self.UpdateHint()\n return\n\n else:\n i = 0\n for rowNode in self.scroll.sr.nodes:\n for entry in rowNode.internalNodes:\n if entry is not None and entry.item and entry.item.itemID == rec.itemID:\n self.SetItem(i, rec)\n return\n i += 1\n\n lg.Warn('vcont', 'Tried to update an item that is not there??')\n\n @telemetry.ZONE_METHOD\n def RemoveItem(self, rec):\n lg.Info('vcont', 'RemoveItem', rec and '[%s %s]' % (rec.stacksize, cfg.invtypes.Get(rec.typeID).name))\n if self.viewMode in ('details', 'list'):\n for entry in self.scroll.sr.nodes:\n if entry.item.itemID == rec.itemID:\n self.scroll.RemoveEntries([entry])\n break\n\n for item in self.items:\n if item.itemID == rec.itemID:\n self.items.remove(item)\n\n else:\n i = 0\n for rowNode in self.scroll.sr.nodes:\n si = 0\n for entry in rowNode.internalNodes:\n if entry and entry.item and entry.item.itemID == rec.itemID:\n self.SetItem(i, None)\n rowNode.internalNodes[si] = None\n break\n si += 1\n i += 1\n\n i = 0\n for item in self.items:\n if item and item.itemID == rec.itemID:\n self.items[i] = None\n i += 1\n\n self.CleanupRows()\n\n @telemetry.ZONE_METHOD\n def CleanupRows(self):\n rm = []\n for rowNode in self.scroll.sr.nodes:\n internalNodes = rowNode.Get('internalNodes', [])\n if internalNodes == [None] * len(internalNodes):\n rm.append(rowNode)\n else:\n rm = []\n\n if rm:\n self.scroll.RemoveEntries(rm)\n\n @telemetry.ZONE_METHOD\n def AddRow(self):\n self.items += [None] * self.cols\n self.scroll.AddEntries(-1, [listentry.Get('VirtualContainerRow', {'lenitems': len(self.scroll.sr.nodes) * self.cols,\n 'rec': [None] * self.cols,\n 'internalNodes': [None] * self.cols,\n 'parentWindow': self,\n 'hilightable': False,\n 'container': self})])\n self.scroll.UpdatePosition()\n\n @telemetry.ZONE_METHOD\n def StackAll(self):\n self.invController.StackAll()\n uthread.new(self.Refresh)\n\n def OnScrollContentDropData(self, dragObj, nodes):\n idx = None\n if self.viewMode == 'icons' and self.cols:\n l, t = self.scroll.GetAbsolutePosition()\n idx = self.cols * len(self.scroll.sr.nodes) + (uicore.uilib.x - l) // (64 + colMargin)\n sm.ScatterEvent('OnInvContDragExit', self.invController.GetInvID(), [])\n self.OnDropDataWithIdx(nodes, idx)\n\n def OnDragEnter(self, dragObj, nodes):\n sm.ScatterEvent('OnInvContDragEnter', self.invController.GetInvID(), nodes)\n\n def OnDragExit(self, dragObj, nodes):\n sm.ScatterEvent('OnInvContDragExit', self.invController.GetInvID(), nodes)\n\n def OnDropData(self, dragObj, nodes):\n return self.OnDropDataWithIdx(nodes)\n\n def Cut(self):\n items = self.scroll.GetSelected()\n sm.GetService('inv').SetItemClipboard(items)\n\n def Copy(self):\n if bool(session.role & service.ROLE_PROGRAMMER):\n items = self.scroll.GetSelected()\n sm.GetService('inv').SetItemClipboard(items, copy=True)\n return uicls.Scroll.Copy(self.scroll)\n\n def Paste(self, value):\n items, copy = sm.GetService('inv').PopItemClipboard()\n if copy and bool(session.role & service.ROLE_PROGRAMMER):\n import param\n for item in items:\n itemID = sm.GetService('slash').cmd_createitem(param.ParamObject('%s %s' % (item.rec.typeID, item.rec.stacksize)))\n if itemID:\n invController = invCtrl.StationItems() if session.stationid else invCtrl.ShipCargo()\n blue.synchro.SleepWallclock(100)\n newItem = invController.GetItem(itemID)\n self.invController.AddItems([newItem])\n\n else:\n self.invController.OnDropData(items)\n\n @telemetry.ZONE_METHOD\n def OnDropDataWithIdx(self, nodes, idx = None):\n self.scroll.ClearSelection()\n if len(nodes) and getattr(nodes[0], 'scroll', None) and not nodes[0].scroll.destroyed:\n nodes[0].scroll.ClearSelection()\n if nodes and getattr(nodes[0], 'item', None) in self.invController.GetItems() and not uicore.uilib.Key(uiconst.VK_SHIFT):\n if getattr(nodes[0], 'scroll', None) != self.scroll:\n return\n if idx is not None:\n for i, node in enumerate(nodes):\n self.tmpDropIdx[node.itemID] = idx + i\n\n for node in nodes:\n idx = self.tmpDropIdx.get(node.itemID, None)\n if idx is None:\n if None in self.items:\n idx = self.items.index(None)\n else:\n idx = len(self.items)\n self.OnItemDrop(idx, node)\n\n return\n return self.invController.OnDropData(nodes)\n\n @telemetry.ZONE_METHOD\n def OnItemDrop(self, index, node):\n if self.viewMode not in ('details', 'list'):\n self.RemoveItem(node.item)\n self.AddItem(node.item, index)\n\n @telemetry.ZONE_METHOD\n def SetItem(self, index, rec):\n lg.Info('vcont', 'SetItem', index, rec and '[%s %s]' % (rec.stacksize, cfg.invtypes.Get(rec.typeID).name))\n if not self or self.destroyed:\n return\n if index < len(self.items) and rec and self.items[index] is not None and self.items[index].itemID != rec.itemID:\n while index < len(self.items) and self.items[index] is not None:\n index += 1\n\n if self.cols:\n rowIndex = index // self.cols\n else:\n rowIndex = 0\n while rowIndex >= len(self.scroll.sr.nodes):\n self.AddRow()\n uiutil.Update(self, 'Container::SetItem')\n\n while index >= len(self.items):\n self.items += [None]\n\n self.items[index] = rec\n try:\n self.scroll.sr.nodes[rowIndex].rec[index % self.cols] = rec\n self.UpdateHint()\n node = None\n if rec:\n node = uix.GetItemData(rec, self.viewMode, self.invController.viewOnly, container=self, scrollID=self.scroll.sr.id)\n if not self or self.destroyed:\n return\n node.scroll = self.scroll\n node.panel = None\n node.idx = index\n node.__guid__ = 'xtriui.InvItem'\n self.scroll.sr.nodes[index // self.cols].internalNodes[index % self.cols] = node\n except IndexError:\n return\n\n icon = self.GetIcon(index)\n if icon:\n if rec is None:\n icon.state = uiconst.UI_HIDDEN\n icon.sr.node = None\n else:\n icon.state = uiconst.UI_NORMAL\n node.panel = icon\n node.viewOnly = self.invController.viewOnly\n icon.Load(node)\n\n @telemetry.ZONE_METHOD\n def RefreshCols(self):\n w = self.scroll.GetContentWidth()\n self.cols = max(1, w // (64 + colMargin))\n\n def PrimeItems(self, itemlist):\n locations = []\n vouchers = []\n for rec in itemlist:\n if rec.categoryID == const.categoryStation and rec.groupID == const.groupStation:\n locations.append(rec.itemID)\n locations.append(rec.locationID)\n if rec.singleton and (rec.categoryID == const.categoryShip or rec.groupID in (const.groupWreck,\n const.groupCargoContainer,\n const.groupSecureCargoContainer,\n const.groupAuditLogSecureContainer,\n const.groupFreightContainer,\n const.groupBiomass)):\n locations.append(rec.itemID)\n if rec.typeID == const.typeBookmark:\n vouchers.append(rec.itemID)\n\n if vouchers:\n sm.GetService('voucherCache').PrimeVoucherNames(vouchers)\n if locations:\n cfg.evelocations.Prime(locations)\n\n def OnNewHeadersSet(self, *args):\n self.RefreshView()\n\n @telemetry.ZONE_METHOD\n def RefreshView(self, *args):\n if self.refreshingView:\n return\n self.refreshingView = 1\n try:\n if self.viewMode in ('details', 'list'):\n self.scroll.sr.id = 'containerWnd_%s' % self.invController.GetName()\n self.scroll.hiliteSorted = 1\n scrolllist = []\n for rec in self.items:\n if rec:\n id = self.scroll.sr.id\n theData = uix.GetItemData(rec, self.viewMode, self.invController.viewOnly, container=self, scrollID=id)\n list = listentry.Get('InvItem', data=theData)\n scrolllist.append(list)\n\n hdr = uix.GetInvItemDefaultHeaders()\n scrll = self.scroll.GetScrollProportion()\n theSc = self.scroll\n theSc.Load(contentList=scrolllist, headers=hdr, scrollTo=scrll)\n else:\n if not self.cols:\n self.RefreshCols()\n while self.items and self.items[-1] is None:\n self.items = self.items[:-1]\n\n content = []\n selectedItems = [ node.item for node in self.scroll.GetSelected() ]\n for i in xrange(len(self.items)):\n blue.pyos.BeNice()\n if not i % self.cols:\n entry = [None] * self.cols\n nodes = [None] * self.cols\n content.append(listentry.Get('VirtualContainerRow', {'lenitems': i,\n 'rec': entry,\n 'internalNodes': nodes,\n 'parentWindow': self,\n 'hilightable': False,\n 'container': self}))\n if self.items[i]:\n node = uix.GetItemData(self.items[i], self.viewMode, self.invController.viewOnly, container=self)\n node.scroll = self.scroll\n node.panel = None\n node.__guid__ = 'xtriui.InvItem'\n node.idx = i\n node.selected = node.item in selectedItems\n nodes[i % self.cols] = node\n entry[i % self.cols] = self.items[i]\n\n self.scroll.sr.sortBy = None\n self.scroll.sr.id = None\n self.scroll.Load(fixedEntryHeight=self.iconHeight + rowMargin, contentList=content, scrollTo=self.scroll.GetScrollProportion())\n self.CleanupRows()\n self.UpdateHint()\n self.initialized = True\n sm.ScatterEvent('OnInvContRefreshed', self)\n finally:\n if not self.destroyed:\n if self.viewMode == 'details':\n self.scroll.sr.minColumnWidth = {localization.GetByLabel('UI/Common/Name'): 44}\n self.scroll.UpdateTabStops()\n else:\n self.scroll.sr.minColumnWidth = {}\n self.refreshingView = 0\n if self.reRefreshView:\n self.reRefreshView = False\n self.RefreshCols()\n uthread.new(self.RefreshView)\n\n def SelectAll(self):\n if not self.destroyed:\n self.scroll.SelectAll()\n\n def InvertSelection(self):\n if not self.destroyed:\n self.scroll.ToggleSelected()\n\n def GetIcons(self):\n return [ icon for row in self.scroll.GetContentContainer().children for icon in row.sr.icons if icon.state == uiconst.UI_NORMAL ]\n\n def OnScrollMouseDown(self, *args):\n if args[0] == uiconst.MOUSELEFT:\n self.dragStart = (uicore.uilib.x - self.scroll.GetContentContainer().absoluteLeft, uicore.uilib.y - self.scroll.GetContentContainer().absoluteTop)\n if uicore.uilib.Key(uiconst.VK_CONTROL) or uicore.uilib.Key(uiconst.VK_SHIFT):\n self.previouslyHighlighted = [ x.panel for x in self.scroll.GetSelected() ]\n else:\n self.previouslyHighlighted = []\n dragContainer = getattr(self, 'dragContainer', None)\n if dragContainer is None or dragContainer.destroyed:\n self.dragContainer = uicls.Container(parent=self.scroll.GetContentContainer(), align=uiconst.TOPLEFT, idx=0)\n dragFrame = uicls.Frame(parent=self.dragContainer, color=(1, 1, 1, 0.3), frameConst=uiconst.FRAME_BORDER1_CORNER3)\n dragFill = uicls.Fill(parent=self.dragContainer, color=(1, 1, 1, 0.15), frameConst=uiconst.FRAME_FILLED_CORNER3)\n self.dragContainer.Hide()\n uthread.new(self.RubberbandSelection_thread)\n\n def RubberbandSelection_thread(self, *args):\n while self.dragStart and uicore.uilib.leftbtn and trinity.app.IsActive():\n startX, startY = self.dragStart\n currentX, currentY = uicore.uilib.x - self.scroll.GetContentContainer().absoluteLeft, uicore.uilib.y - self.scroll.GetContentContainer().absoluteTop\n if startX > currentX:\n temp = currentX\n currentX = startX\n startX = temp\n if startY > currentY:\n temp = currentY\n currentY = startY\n startY = temp\n left = max(startX, 0)\n width = min(currentX, self.scroll.GetContentContainer().width) - max(startX, 0)\n top = max(startY, 0)\n height = min(currentY, self.scroll.GetContentContainer().height) - max(startY, 0)\n self.dragContainer.left = left\n self.dragContainer.top = top\n self.dragContainer.width = width\n self.dragContainer.height = height\n self.dragContainer.Show()\n if not self.scrollTimer:\n self.scrollTimer = base.AutoTimer(250, self.ScrollTimer)\n for each in self.scroll.GetContentContainer().children:\n if isinstance(each, listentry.VirtualContainerRow):\n if each.top >= startY and each.top + each.height <= currentY or each.top + each.height >= startY and each.top <= currentY:\n for icon in each.sr.icons:\n if icon.left >= startX and icon.left + icon.width <= currentX or icon.left + icon.width >= startX and icon.left <= currentX:\n if icon in self.previouslyHighlighted:\n if uicore.uilib.Key(uiconst.VK_SHIFT):\n icon.Select()\n elif uicore.uilib.Key(uiconst.VK_CONTROL):\n icon.Deselect()\n else:\n icon.Select()\n elif icon not in self.previouslyHighlighted:\n icon.Deselect()\n else:\n icon.Select()\n\n else:\n for icon in each.sr.icons:\n if icon not in self.previouslyHighlighted:\n icon.Deselect()\n else:\n icon.Select()\n\n elif isinstance(each, listentry.InvItem):\n if each.top >= startY and each.top + each.height <= currentY or each.top + each.height >= startY and each.top <= currentY:\n each.Select()\n if each in self.previouslyHighlighted:\n if uicore.uilib.Key(uiconst.VK_SHIFT):\n each.Select()\n elif uicore.uilib.Key(uiconst.VK_CONTROL):\n each.Deselect()\n else:\n each.Select()\n elif each not in self.previouslyHighlighted:\n each.Deselect()\n else:\n each.Select()\n\n blue.pyos.synchro.SleepSim(10)\n\n self.scrollTimer = None\n self.dragStart = None\n self.previouslyHighlighted = None\n self.scrollTimer = None\n self.dragContainer.Hide()\n\n def OnScrollMouseUp(self, *args):\n if self.dragStart and args[0] == uiconst.MOUSELEFT:\n startX, startY = self.dragStart\n endX, endY = uicore.uilib.x - self.scroll.GetContentContainer().absoluteLeft, uicore.uilib.y - self.scroll.GetContentContainer().absoluteTop\n if startX > endX:\n temp = endX\n endX = startX\n startX = temp\n if startY > endY:\n temp = endY\n endY = startY\n startY = temp\n preSelectedNodes = self.scroll.GetSelected() if uicore.uilib.Key(uiconst.VK_CONTROL) or uicore.uilib.Key(uiconst.VK_SHIFT) else []\n selectedNodes = []\n for each in self.scroll.GetContentContainer().children:\n if isinstance(each, listentry.VirtualContainerRow):\n if each.top >= startY and each.top + each.height <= endY or each.top + each.height >= startY and each.top <= endY:\n for icon in each.sr.icons:\n if icon.left >= startX and icon.left + icon.width <= endX or icon.left + icon.width >= startX and icon.left <= endX:\n if icon.sr.node:\n selectedNodes.append(icon.sr.node)\n\n elif isinstance(each, listentry.InvItem):\n if each.top >= startY and each.top + each.height <= endY or each.top + each.height >= startY and each.top <= endY:\n selectedNodes.append(each.sr.node)\n\n if uicore.uilib.Key(uiconst.VK_SHIFT):\n selectedNodes.extend(preSelectedNodes)\n elif uicore.uilib.Key(uiconst.VK_CONTROL):\n newSelectedNodes = [ item for item in selectedNodes if item not in preSelectedNodes ]\n newSelectedNodes.extend([ item for item in preSelectedNodes if item not in selectedNodes ])\n selectedNodes = newSelectedNodes\n uthread.new(self.scroll.SelectNodes, selectedNodes)\n self.dragStart = None\n self.previouslyHighlighted = None\n self.scrollTimer = None\n self.dragContainer.Hide()\n\n def ScrollTimer(self):\n if not self.dragStart:\n self.scrollTimer = None\n return\n aL, aT, aW, aH = self.scroll.GetAbsolute()\n if uicore.uilib.y < aT + 10:\n self.scroll.Scroll(1)\n elif uicore.uilib.y > aT + aH - 10:\n self.scroll.Scroll(-1)\n\n def GetIcon(self, index):\n for each in self.scroll.GetContentContainer().children:\n if getattr(each, 'index', -1) == index // self.cols * self.cols:\n lg.Info('vcont', 'GetIcon(', index, ') returns', each.sr.icons[index % self.cols].name)\n return each.sr.icons[index % self.cols]\n\n lg.Info('vcont', 'GetIcon(', index, ') found nothing')\n\n def RegisterSpecialActionButton(self, button):\n pass\n\n\nclass Row(uicls.SE_BaseClassCore):\n __guid__ = 'listentry.VirtualContainerRow'\n\n def Startup(self, dad):\n self.dad = dad.dad\n self.initialized = False\n self.sr.icons = []\n\n @telemetry.ZONE_METHOD\n def Load(self, node):\n if self.initialized:\n return\n self.initialized = True\n self.sr.node = node\n self.index = node.lenitems\n for i in range(len(self.sr.icons), len(node.internalNodes)):\n icon = xtriui.InvItem(parent=self)\n icon.top = rowMargin\n icon.left = colMargin + (icon.width + colMargin) * i\n icon.height = 92\n self.sr.icons.append(icon)\n\n for icon in self.sr.icons[self.dad.cols:]:\n icon.sr.node = None\n icon.subnodeIdx = None\n\n i = 0\n for subnode in node.internalNodes:\n icon = self.sr.icons[i]\n if subnode is None:\n icon.state = uiconst.UI_HIDDEN\n icon.sr.node = None\n icon.subnodeIdx = None\n else:\n subnode.panel = icon\n icon.Load(subnode)\n icon.state = uiconst.UI_NORMAL\n icon.subnodeIdx = subnode.idx = self.index + i\n i += 1\n\n def GetMenu(self):\n return GetContainerMenu(self.dad)\n\n def OnDropData(self, dragObj, nodes):\n l, t, w, h = self.GetAbsolute()\n index = self.index + (uicore.uilib.x - l) // (64 + colMargin)\n self.dad.OnDropDataWithIdx(nodes, index)\n\n def OnDragEnter(self, dragObj, nodes):\n self.sr.node.container.OnDragEnter(dragObj, nodes)\n\n def OnDragExit(self, dragObj, nodes):\n self.sr.node.container.OnDragExit(dragObj, nodes)\n\n def OnMouseDown(self, *etc):\n if self.dad.scroll:\n self.dad.scroll.OnMouseDown(*etc)\n\n def OnMouseUp(self, *etc):\n if self.dad.scroll:\n self.dad.scroll.OnMouseUp(*etc)\n\n def OnMouseMove(self, *etc):\n if self.dad.scroll:\n self.dad.scroll.OnMouseMove(*etc)\n\n def ShowSelected(self, *args):\n pass\n\n\ndef GetContainerMenu(containerWindow):\n m = []\n if eve.rookieState:\n return m\n m += [(uiutil.MenuLabel('UI/Common/SelectAll'), containerWindow.SelectAll), (uiutil.MenuLabel('UI/Inventory/InvertSelection'), containerWindow.InvertSelection)]\n if eve.session.role & (service.ROLE_GML | service.ROLE_WORLDMOD):\n m += [(uiutil.MenuLabel('UI/Commands/Refresh'), containerWindow.Refresh)]\n if containerWindow.viewMode == 'icons':\n m += [(uiutil.MenuLabel('UI/Common/SortBy'), [(uiutil.MenuLabel('UI/Common/Name'), containerWindow.SortIconsBy, ('name', 0)),\n (uiutil.MenuLabel('UI/Inventory/NameReversed'), containerWindow.SortIconsBy, ('name', 1)),\n None,\n (uiutil.MenuLabel('UI/Inventory/ItemQuantity'), containerWindow.SortIconsBy, ('qty', 0)),\n (uiutil.MenuLabel('UI/Inventory/QuantityReversed'), containerWindow.SortIconsBy, ('qty', 1)),\n None,\n (uiutil.MenuLabel('UI/Common/Type'), containerWindow.SortIconsBy, ('type', 0)),\n (uiutil.MenuLabel('UI/Inventory/TypeReversed'), containerWindow.SortIconsBy, ('type', 1))])]\n if containerWindow.invController.viewOnly:\n return m\n containerItem = containerWindow.invController.GetInventoryItem()\n containerOwnerID = containerItem.ownerID\n myOwnerIDs = (session.charid, session.corpid, session.allianceid)\n containerSlim = sm.GetService('michelle').GetItem(containerItem.itemID)\n stackAll = containerItem.groupID in (const.groupStation, const.groupPlanetaryCustomsOffices) or containerOwnerID in myOwnerIDs or session.corpid == getattr(containerSlim, 'corpID', None) or session.allianceid and session.allianceid == getattr(containerSlim, 'allianceID', None)\n if stackAll:\n m += [(uiutil.MenuLabel('UI/Inventory/StackAll'), containerWindow.StackAll)]\n return m\n\n\nclass MiniButton(uicls.Icon):\n __guid__ = 'xtriui.MiniButton'\n\n def ApplyAttributes(self, attributes):\n self.idleIcon = attributes.icon\n uicls.Icon.ApplyAttributes(self, attributes)\n self.selectedIcon = attributes.selectedIcon\n self.mouseOverIcon = attributes.mouseOverIcon\n self.groupID = attributes.groupID\n self.func = attributes.func\n self.selected = False\n self.keepselection = True\n\n def OnMouseEnter(self, *args):\n self.LoadIcon(self.mouseOverIcon, ignoreSize=True)\n\n def OnMouseExit(self, *args):\n if self.selected:\n self.LoadIcon(self.selectedIcon, ignoreSize=True)\n else:\n self.LoadIcon(self.idleIcon, ignoreSize=True)\n\n def OnMouseDown(self, *args):\n self.LoadIcon(self.selectedIcon, ignoreSize=True)\n\n def OnMouseUp(self, *args):\n if uicore.uilib.mouseOver is self:\n self.LoadIcon(self.mouseOverIcon, ignoreSize=True)\n\n def OnClick(self, *args):\n if self.keepselection:\n self.Select()\n else:\n self.Deselect()\n self.Click()\n\n def Click(self, *args):\n self.func()\n\n def Deselect(self):\n self.selected = 0\n self.LoadIcon(self.idleIcon, ignoreSize=True)\n\n def Select(self):\n if self.groupID:\n for child in self.parent.children:\n if child == self:\n continue\n if isinstance(child, xtriui.MiniButton) and child.groupID == self.groupID:\n child.Deselect()\n\n self.selected = True\n elif self.selected:\n self.Deselect()\n else:\n self.selected = True\n if self.selected:\n self.LoadIcon(self.selectedIcon, ignoreSize=True)","repo_name":"alexcmd/eve","sub_path":"eve-8.21.494548/eve/client/script/ui/shared/container.py","file_name":"container.py","file_ext":"py","file_size_in_byte":48259,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"32"}
+{"seq_id":"4844602004","text":"#PyBoss Script\n#Import modules\nimport os\nimport csv\n\n#Request path and filename of data file\ncsvpath = input('Please enter path and filename of data file (e.g. \"datafolder/datafile.csv\"): ')\n\n#Declare variables to store data\nemp_id = []\nfirst_name = []\nlast_name = []\nssn = []\ndob = []\nstate = []\n\n#Dictionary for state abbreviations\nus_state_abbrev = {\n 'Alabama': 'AL',\n 'Alaska': 'AK',\n 'Arizona': 'AZ',\n 'Arkansas': 'AR',\n 'California': 'CA',\n 'Colorado': 'CO',\n 'Connecticut': 'CT',\n 'Delaware': 'DE',\n 'Florida': 'FL',\n 'Georgia': 'GA',\n 'Hawaii': 'HI',\n 'Idaho': 'ID',\n 'Illinois': 'IL',\n 'Indiana': 'IN',\n 'Iowa': 'IA',\n 'Kansas': 'KS',\n 'Kentucky': 'KY',\n 'Louisiana': 'LA',\n 'Maine': 'ME',\n 'Maryland': 'MD',\n 'Massachusetts': 'MA',\n 'Michigan': 'MI',\n 'Minnesota': 'MN',\n 'Mississippi': 'MS',\n 'Missouri': 'MO',\n 'Montana': 'MT',\n 'Nebraska': 'NE',\n 'Nevada': 'NV',\n 'New Hampshire': 'NH',\n 'New Jersey': 'NJ',\n 'New Mexico': 'NM',\n 'New York': 'NY',\n 'North Carolina': 'NC',\n 'North Dakota': 'ND',\n 'Ohio': 'OH',\n 'Oklahoma': 'OK',\n 'Oregon': 'OR',\n 'Pennsylvania': 'PA',\n 'Rhode Island': 'RI',\n 'South Carolina': 'SC',\n 'South Dakota': 'SD',\n 'Tennessee': 'TN',\n 'Texas': 'TX',\n 'Utah': 'UT',\n 'Vermont': 'VT',\n 'Virginia': 'VA',\n 'Washington': 'WA',\n 'West Virginia': 'WV',\n 'Wisconsin': 'WI',\n 'Wyoming': 'WY',\n}\n\n#Open CSV file and perform operations\nwith open(csvpath, newline=\"\") as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',')\n header = next(csvreader) \n \n for row in csvreader:\n emp_id.append(row[0])\n \n #Split full name into parts\n full_name = row[1].split(' ')\n first_name.append(full_name[0])\n last_name.append(full_name[1])\n \n #Reformat date of birth\n orig_dob = row[2].split('-')\n dob.append(f'{orig_dob[1]}/{orig_dob[2]}/{orig_dob[0]}')\n \n #Mask first five digits of SSN\n orig_ssn = row[3].split('-')\n ssn.append(f'***-**-{orig_ssn[2]}')\n \n #Convert state name to abbreviation\n state.append(us_state_abbrev[row[4]])\n\n#Create reformated Employee Table\nemployees = zip(emp_id, first_name, last_name, dob, ssn, state)\n\n#Request filename for CSV file\noutputfile = input('Please type filename of new employee file (e.g. \"employee_table.csv\"): ')\n\n#Write Employee Table to new CSV file\nwith open(outputfile, 'w', newline = \"\") as table:\n writer = csv.writer(table)\n \n # Write the header row\n writer.writerow([\"Emp ID\", \"First Name\", \"Last Name\", \"DOB\", \"SSN\", \"State\"])\n\n # Write in zipped rows\n writer.writerows(employees)\n\n","repo_name":"smjedael/python-challenge","sub_path":"PyBoss/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"9579270925","text":"import logging\n\nfrom typing import Any, Dict, Optional\n\n# https://chat-gateway.veld.dev/swagger/\nimport aiohttp\n\nfrom .models import Channel, Embed, Message\n\nlog = logging.getLogger(__name__)\n\n\nclass HTTPException(Exception):\n \"\"\"Generic exception when a HTTP operation failed.\"\"\"\n\n pass\n\n\nclass HTTPClient:\n def __init__(self) -> None:\n self.session = aiohttp.ClientSession()\n self.token: Optional[str] = None\n\n # /api/v1/channels\n async def create_channel(self, name: str) -> Channel:\n \"\"\"\n Creates a new channel.\n \"\"\"\n async with self.session.post(\n \"https://chat-gateway.veld.dev/api/v1/channels\",\n json={\"name\": name},\n headers={\"Authorization\": f\"Bearer {self.token}\"},\n ) as req:\n if req.status != 200:\n body = await req.text()\n log.debug(f\"HTTP Response code {req.status}, body is {body}\")\n raise HTTPException()\n json = await req.json()\n return Channel.from_dict(json)\n\n # /api/v1/channels/id/join\n async def join_channel(self, channel_id: int) -> bool:\n \"\"\"\n Joins a channel\n \"\"\"\n async with self.session.post(\n f\"https://chat-gateway.veld.dev/api/v1/channels/{channel_id}/join\",\n headers={\"Authorization\": f\"Bearer {self.token}\"},\n ) as req:\n if req.status != 204:\n body = await req.text()\n log.debug(f\"HTTP Response code {req.status}, body is {body}\")\n raise HTTPException()\n return True\n\n # /api/v1/channels/id/messages\n async def send_message(\n self,\n channel_id: int,\n content: Optional[str] = None,\n embed: Optional[Embed] = None,\n ) -> Message:\n \"\"\"\n Sends a message to a channel\n \"\"\"\n if content is None and embed is None:\n raise ValueError(\"Either content or embed must be supplied\")\n\n data: Dict[str, Any] = {\"content\": content}\n if embed is not None:\n data[\"embed\"] = embed.to_dict()\n async with self.session.post(\n f\"https://chat-gateway.veld.dev/api/v1/channels/{channel_id}/messages\",\n json=data,\n headers={\"Authorization\": f\"Bearer {self.token}\"},\n ) as req:\n if req.status != 204:\n body = await req.text()\n log.debug(f\"HTTP Response code {req.status}, body is {body}\")\n raise HTTPException()\n return Message.from_dict(data)\n","repo_name":"Gelbpunkt/veldpy","sub_path":"veldpy/http.py","file_name":"http.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"32"}
+{"seq_id":"69968730332","text":"import argparse\nfrom concurrent import futures\nimport grpc\nfrom grpc import StatusCode\n\nimport nlm_pb2\nimport nlm_pb2_grpc\n\nfrom py2neo.database import Graph\n\n\nfrom nlm import NLMLayer\n\nfrom utils.utils import raise_grpc_error, deco_log_error\nfrom utils.utils import convert_request_to, convert_graphobj_to_dict\n\nfrom schemes.extractor import ExtractorInput, RawString\nfrom schemes.graph import GraphNode, GraphRelation\n\nfrom configs.config import neo_sche, neo_host, neo_port, neo_user, neo_pass\nfrom configs.config import logger\n\n\nparser = argparse.ArgumentParser(\n description='Setup your NLM Server.')\nparser.add_argument(\n '-fn', dest='fuzzy_node', type=bool, default=False,\n help='Whether to use fuzzy node to query. \\\n If is, the props will never update.')\nparser.add_argument(\n '-ai', dest='add_inexistence', type=bool, default=False,\n help='Whether to add an inexistent Node or Relation.')\nparser.add_argument(\n '-up', dest='update_props', type=bool, default=False,\n help='Whether to update props of a Node or Relation.')\nargs = parser.parse_args()\n\n\ngraph = Graph(scheme=neo_sche, host=neo_host, port=neo_port,\n user=neo_user, password=neo_pass)\nmem = NLMLayer(graph=graph,\n fuzzy_node=args.fuzzy_node,\n add_inexistence=args.add_inexistence,\n update_props=args.update_props)\n\n\nclass NLMService(nlm_pb2_grpc.NLMServicer):\n\n @raise_grpc_error(Exception, StatusCode.INTERNAL)\n @deco_log_error(logger)\n @convert_request_to(GraphNode)\n def NodeRecall(self, request, context):\n result = mem(request)\n gn = result[0] if result else request\n dctgn = convert_graphobj_to_dict(gn)\n return nlm_pb2.GraphNode(**dctgn)\n\n @raise_grpc_error(Exception, StatusCode.INTERNAL)\n @deco_log_error(logger)\n @convert_request_to(GraphRelation)\n def RelationRecall(self, request, context):\n result = mem(request)\n gr = result[0] if result else request\n dctgr = convert_graphobj_to_dict(gr)\n return nlm_pb2.GraphRelation(**dctgr)\n\n @raise_grpc_error(Exception, StatusCode.INTERNAL)\n @deco_log_error(logger)\n @convert_request_to(RawString)\n def StrRecall(self, request, context):\n result = mem(request)\n go = result[0] if result else None\n if isinstance(go, GraphNode):\n dctgn = convert_graphobj_to_dict(go)\n gop = nlm_pb2.GraphNode(**dctgn)\n elif isinstance(go, GraphRelation):\n dctgr = convert_graphobj_to_dict(go)\n gop = nlm_pb2.GraphRelation(**dctgr)\n else:\n gop = nlm_pb2.GraphNode(**{})\n return nlm_pb2.GraphOutput(gn=gop)\n\n @raise_grpc_error(Exception, StatusCode.INTERNAL)\n @deco_log_error(logger)\n @convert_request_to(ExtractorInput)\n def NLURecall(self, request, context):\n result = mem(request)\n go = result[0] if result else None\n if isinstance(result, GraphNode):\n dctgn = convert_graphobj_to_dict(result)\n gop = nlm_pb2.GraphNode(**dctgn)\n elif isinstance(go, GraphRelation):\n dctgr = convert_graphobj_to_dict(result)\n gop = nlm_pb2.GraphRelation(**dctgr)\n else:\n gop = nlm_pb2.GraphNode(**{})\n return nlm_pb2.GraphOutput(gn=gop)\n\n\ndef serve(host, port):\n server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))\n nlm_pb2_grpc.add_NLMServicer_to_server(NLMService(), server)\n server.add_insecure_port('{}:{}'.format(host, port))\n server.start()\n server.wait_for_termination()\n\n\nif __name__ == '__main__':\n serve(\"localhost\", 8080)\n","repo_name":"hscspring/nlm","sub_path":"nlm/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3630,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"32"}
+{"seq_id":"32705865257","text":"#!/usr/bin/env python\n\nfrom bs4 import BeautifulSoup as bs\nimport requests as req\nimport os\nfrom shutil import rmtree\nimport tarfile as t\nfrom sys import argv\n\nhomeDir = \"/home/sharpcdf/\"\nmaxComp = 4\ncurrentComp = 0\n\ndef updateOdin():\n global maxComp, currentComp\n odinVer = bs(req.get(\"https://github.com/odin-lang/Odin/releases/latest/\").content, 'html.parser').find_all('h1', 'd-inline mr-3')[0].string\n print(\"Removing current Odin compiler...\")\n if os.path.exists(homeDir + \"Odin\"):\n rmtree(homeDir + \"Odin\")\n print(\"Downloading Odin compiler...\")\n os.system(\"git clone https://github.com/odin-lang/Odin \" + homeDir + \"/Odin\")\n print(\"Building Odin compiler...\")\n os.system(\"cd \" + homeDir + \"Odin && make\")\n print(\"Done!\")\n print(\"Building stb...\")\n os.system(\"cd \" + homeDir + \"Odin/vendor/stb/src && make\")\n print(\"Done!\")\n currentComp += 1\n print(f\"Finished updating Odin compiler, version {odinVer} [{currentComp}/{maxComp}]\\n\")\n\ndef updateNim():\n global maxComp, currentComp\n print(\"Removing current Nim compiler...\")\n if os.path.exists(homeDir + \"Nim\"):\n rmtree(homeDir + \"Nim\")\n print(\"Downloading Nim compiler...\")\n nimVer = bs(req.get(\"https://nim-lang.org\").content, 'html.parser').find_all('a', 'pure-button pure-button-primary')[0].string.removeprefix(\"Install Nim \")\n nimComp = req.get(\"https://nim-lang.org/download/nim-\" + nimVer + \"-linux_x64.tar.xz\")\n if not nimComp.ok:\n print(\"Error downloading Nim compiler, exiting...\")\n exit()\n open(homeDir + \"nim.tar.xz\", 'wb').write(nimComp.content)\n print(\"Extracting Nim compiler...\")\n tar = t.open(homeDir + \"nim.tar.xz\")\n tar.extractall(homeDir)\n tar.close()\n print(\"Cleaning up...\")\n os.remove(homeDir + \"nim.tar.xz\")\n os.rename(homeDir + \"nim-\" + nimVer, homeDir + \"Nim\")\n currentComp += 1\n print(f\"Finished updating Nim compiler, version {nimVer} [{currentComp}/{maxComp}]\\n\")\n\n\ndef updateGo():\n global maxComp, currentComp\n print(\"Removing current Go compiler...\")\n if os.path.exists(homeDir + \"Go\"):\n rmtree(homeDir + \"Go\")\n print(\"Downloading Go compiler...\")\n goVer = bs(req.get(\"https://go.dev/dl/\").content, 'html.parser').find_all('span', 'filename')[0].string.removeprefix(\"go\").removesuffix(\".windows-amd64.msi\")\n goComp = req.get(\"https://go.dev/dl/go\" + goVer + \".linux-amd64.tar.gz\")\n if not goComp.ok:\n print(\"Error downloading Go compiler, exiting...\")\n exit()\n open(homeDir + \"go.tar.gz\", 'wb').write(goComp.content)\n print(\"Extracting Go compiler...\")\n tar = t.open(homeDir + \"go.tar.gz\")\n tar.extractall(homeDir)\n tar.close()\n print(\"Cleaning up...\")\n os.remove(homeDir + \"go.tar.gz\")\n os.rename(homeDir + \"go\", homeDir + \"Go\")\n currentComp += 1\n print(f\"Finished updating Go compiler, version {goVer} [{currentComp}/{maxComp}]\\n\")\n\ndef updateD():\n global maxComp, currentComp\n print(\"Removing current D compiler...\")\n if os.path.exists(homeDir + \"LDC2\"):\n rmtree(homeDir + \"LDC2\")\n dVer = bs(req.get(\"https://github.com/ldc-developers/ldc\").content, 'html.parser').find_all('span', 'css-truncate css-truncate-target text-bold mr-2')[0].string.removeprefix(\"LDC \")\n print(\"Updating D compiler...\")\n dScript = req.get(\"https://dlang.org/install.sh\")\n if not dScript.ok:\n print(\"Error downloading D compiler, exiting...\")\n exit()\n open(\"d.sh\", 'wb').write(dScript.content)\n os.system(\"chmod +x d.sh\")\n os.system(\"./d.sh install ldc -p \" + homeDir)\n print(\"Cleaning up...\")\n os.remove(homeDir + \"d-keyring.gpg\")\n os.remove(homeDir + \"install.sh\")\n os.remove(\"d.sh\")\n os.rename(homeDir + \"ldc-\" + dVer, homeDir + \"LDC2\")\n currentComp += 1\n print(f\"Finished updating D compiler, version {dVer} [{currentComp}/{maxComp}]\\n\")\nif len(argv) > 1:\n #print(argv[1])\n if argv[1].lower() == \"all\":\n updateOdin()\n updateNim()\n updateGo()\n updateD()\n elif argv[1].lower() == \"odin\":\n updateOdin()\n elif argv[1].lower() == \"nim\":\n updateNim()\n elif argv[1].lower() == \"go\":\n updateGo()\n elif argv[1].lower() == \"d\":\n updateD()\nelse:\n updateOdin()\n updateNim()\n updateGo()\n updateD()\nprint(\"Done updating compilers!\")\n","repo_name":"kevspau/update_compilers","sub_path":"update_compilers.py","file_name":"update_compilers.py","file_ext":"py","file_size_in_byte":4339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"7262322894","text":"numbers = { 'data1' : 100, 'data2' : 54, 'data3' : 247 }\n\nsum = 0\n\n#sum = sum(numbers.values())\n\nitem = len(numbers)\n\nfor x in numbers:\n sum += numbers[x]\n\naverage = sum / item\naverage = round(average, 2)\n\nprint(\"Sum: \", sum)\nprint(\"Average: \", average)\n\n\n\n\n","repo_name":"priyankarnd/Python-Training","sub_path":"python-exercises/data-structures/dictionaries.py","file_name":"dictionaries.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"30355200783","text":"import time\nimport logging\nimport requests\n\ndef rate_limit(f):\n \"\"\"\n A decorator to handle rate limiting from the Twitter API. If\n a rate limit error is encountered we will sleep until we can\n issue the API call again.\n \"\"\"\n def new_f(*args, **kwargs):\n errors = 0\n #print (\"current_token is \", args[0].current_token)\n \n while True:\n \n args[0].current_token = -1\n \n ## Get the next available token\n next_available_second = args[0].token_availability[0]\n now = time.time()\n for x in range(0, 9):\n \n # Keep track of next available time in case they are all taken\n if args[0].token_availability[x] < next_available_second:\n next_available_second = args[0].token_availability[x]\n \n # If there exists a token which is now available, take it\n if now > args[0].token_availability[x]:\n args[0].current_token = x\n break\n \n # If no tokens are available, sleep until the next one is\n if args[0].current_token == -1:\n seconds = next_available_second - now + 10\n logging.warn(\"All 9 tokens used: sleeping %s secs\", seconds)\n time.sleep(seconds)\n \n # Execute the function with the appropriate token\n resp = f(*args, **kwargs)\n \n \n ## Error handling\n # If done\n if resp.status_code == 200:\n errors = 0\n return resp\n \n # If reached the request limit\n elif resp.status_code == 429:\n \n # Get the absolute second when rate limit resets and set it as the next available time for the token\n args[0].token_availability[args[0].current_token] = int(resp.headers['x-rate-limit-reset'])\n \n # If some other error\n elif resp.status_code >= 500:\n errors += 1\n if errors > 30:\n logging.warn(\"too many errors from Twitter, giving up\")\n resp.raise_for_status()\n seconds = 60 * errors\n logging.warn(\"%s from Twitter API, sleeping %s\",\n resp.status_code, seconds)\n time.sleep(seconds)\n else:\n resp.raise_for_status()\n return new_f\n\n\ndef catch_conn_reset(f):\n \"\"\"\n A decorator to handle connection reset errors even ones from pyOpenSSL\n until https://github.com/edsu/twarc/issues/72 is resolved\n \"\"\"\n try:\n import OpenSSL\n ConnectionError = OpenSSL.SSL.SysCallError\n except:\n ConnectionError = None\n\n def new_f(self, *args, **kwargs):\n # Only handle if pyOpenSSL is installed.\n if ConnectionError:\n try:\n return f(self, *args, **kwargs)\n except ConnectionError as e:\n logging.warn(\"caught connection reset error: %s\", e)\n self.connect()\n return f(self, *args, **kwargs)\n else:\n return f(self, *args, **kwargs)\n return new_f\n\n\ndef catch_timeout(f):\n \"\"\"\n A decorator to handle read timeouts from Twitter.\n \"\"\"\n def new_f(self, *args, **kwargs):\n print(self.arg_keys)\n print(self.consumer_key[self.arg_keys])\n print(self.consumer_secret[self.arg_keys])\n print(self.access_token[self.arg_keys])\n print(self.access_token_secret[self.arg_keys])\n \n try:\n return f(self, *args, **kwargs)\n except requests.exceptions.ReadTimeout as e:\n logging.warn(\"caught read timeout: %s\", e)\n self.connect()\n return f(self, *args, **kwargs)\n return new_f\n\n\ndef catch_gzip_errors(f):\n \"\"\"\n A decorator to handle gzip encoding errors which have been known to\n happen during hydration.\n \"\"\"\n def new_f(self, *args, **kwargs):\n try:\n return f(self, *args, **kwargs)\n except requests.exceptions.ContentDecodingError as e:\n logging.warn(\"caught gzip error: %s\", e)\n self.connect()\n return f(self, *args, **kwargs)\n return new_f\n\n\ndef interruptible_sleep(t, event=None):\n \"\"\"\n Sleeps for a specified duration, optionally stopping early for event.\n \n Returns True if interrupted\n \"\"\"\n logging.info(\"sleeping %s\", t)\n total_t = 0\n while total_t < t and (event is None or not event.is_set()):\n time.sleep(1)\n total_t += 1\n\n return True if event and event.is_set() else False\n\n\n","repo_name":"shasaur/multi-twarc","sub_path":"twarc/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":4742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"21077605887","text":"import copy\nimport random\n\n\ndef codeToBoard(code):\n \"\"\"Static method to convert a string of Sudoku game to a board (array)\"\"\"\n board = [[0] * 9 for _ in range(9)]\n for row in range(9):\n for col in range(9):\n board[row][col] = int(code[0])\n code = code[1:]\n return board\n\n\nclass Board:\n\n def __init__(self, code=None):\n \"\"\"Initialise the board object\"\"\"\n self.__resetBoard()\n\n if code: # create a board from the code inputted\n self.code = code\n\n for row in range(9):\n for col in range(9):\n self.sudokuBoard[row][col] = int(code[0])\n code = code[1:]\n else:\n self.code = None\n\n def boardToCode(self, input_board=None):\n \"\"\"boardToCode [input_board (optional): list]:\n Convert a board represented by a list into a string representation\"\"\"\n if input_board:\n _code = ''.join([str(i) for j in input_board for i in j])\n return _code\n else:\n self.code = ''.join([str(i) for j in self.sudokuBoard for i in j])\n return self.code\n\n def findSpaces(self):\n \"\"\"findSpaces []: Finds the first empty space, represented by a 0, on the current board\"\"\"\n for row in range(len(self.sudokuBoard)):\n for col in range(len(self.sudokuBoard[0])):\n if self.sudokuBoard[row][col] == 0:\n return row, col\n\n return False\n\n def checkSpace(self, num, space):\n \"\"\"checkSpace [num: integer, space: tuple]: Returns a bool, depending if the number passed in can exist in a space on the current board, provided by the tuple argument\"\"\"\n if not self.sudokuBoard[space[0]][space[1]] == 0: # check to see if space is a number already\n return False\n\n for col in self.sudokuBoard[space[0]]: # check to see if number is already in row\n if col == num:\n return False\n\n for row in range(len(self.sudokuBoard)): # check to see if number is already in column\n if self.sudokuBoard[row][space[1]] == num:\n return False\n\n _internalBoxRow = space[0] // 3\n _internalBoxCol = space[1] // 3\n\n for i in range(3): # check to see if internal box already has number\n for j in range(3):\n if self.sudokuBoard[i + (_internalBoxRow * 3)][j + (_internalBoxCol * 3)] == num:\n return False\n\n return True\n\n def solve(self):\n \"\"\"solve []: Solves the current board using backtracking\"\"\"\n _spacesAvailable = self.findSpaces()\n\n if not _spacesAvailable:\n return True\n else:\n row, col = _spacesAvailable\n\n for n in range(1, 10):\n if self.checkSpace(n, (row, col)):\n self.sudokuBoard[row][col] = n\n\n if self.solve():\n return self.sudokuBoard\n\n self.sudokuBoard[row][col] = 0\n\n return False\n\n def solveForCode(self):\n \"\"\"solveForCode []: Calls the solve method and returns the solved board in a string code format\"\"\"\n return self.boardToCode(self.solve())\n\n def generateQuestionBoardCode(self, difficulty):\n \"\"\"generateQuestionBoardCode [difficulty: integer]: Calls the generateQuestionBoard method and returns a question board and its solution in code format\"\"\"\n self.sudokuBoard, _solution_board = self.generateQuestionBoard(self.__generateRandomCompleteBoard(), difficulty)\n return self.boardToCode(), self.boardToCode(_solution_board)\n\n def generateQuestionBoard(self, fullBoard, difficulty):\n \"\"\"generateQuestionBoard [fullBoard: list, difficulty: integer]: Returns a randomly generated question board and the solution to the same board, the difficulty represents the number of number squares removed from the board\"\"\"\n self.sudokuBoard = copy.deepcopy(fullBoard)\n\n if difficulty == 0:\n _squares_to_remove = 48\n elif difficulty == 1:\n _squares_to_remove = 60\n elif difficulty == 2:\n _squares_to_remove = 72\n else:\n return\n\n _counter = 0\n while _counter < 4:\n _rRow = random.randint(0, 2)\n _rCol = random.randint(0, 2)\n if self.sudokuBoard[_rRow][_rCol] != 0:\n self.sudokuBoard[_rRow][_rCol] = 0\n _counter += 1\n\n _counter = 0\n while _counter < 4:\n _rRow = random.randint(3, 5)\n _rCol = random.randint(3, 5)\n if self.sudokuBoard[_rRow][_rCol] != 0:\n self.sudokuBoard[_rRow][_rCol] = 0\n _counter += 1\n\n _counter = 0\n while _counter < 4:\n _rRow = random.randint(6, 8)\n _rCol = random.randint(6, 8)\n if self.sudokuBoard[_rRow][_rCol] != 0:\n self.sudokuBoard[_rRow][_rCol] = 0\n _counter += 1\n\n _squares_to_remove -= 12\n _counter = 0\n while _counter < _squares_to_remove:\n _row = random.randint(0, 8)\n _col = random.randint(0, 8)\n\n if self.sudokuBoard[_row][_col] != 0:\n n = self.sudokuBoard[_row][_col]\n self.sudokuBoard[_row][_col] = 0\n\n if len(self.findNumberOfSolutions()) != 1:\n self.sudokuBoard[_row][_col] = n\n continue\n\n _counter += 1\n\n return self.sudokuBoard, fullBoard\n\n def __generateRandomCompleteBoard(self):\n \"\"\"__generateRandomCompleteBoard []: Returns a full randomly generated board\"\"\"\n\n self.__resetBoard()\n\n _l = list(range(1, 10))\n for row in range(3):\n for col in range(3):\n _num = random.choice(_l)\n self.sudokuBoard[row][col] = _num\n _l.remove(_num)\n\n _l = list(range(1, 10))\n for row in range(3, 6):\n for col in range(3, 6):\n _num = random.choice(_l)\n self.sudokuBoard[row][col] = _num\n _l.remove(_num)\n\n _l = list(range(1, 10))\n for row in range(6, 9):\n for col in range(6, 9):\n _num = random.choice(_l)\n self.sudokuBoard[row][col] = _num\n _l.remove(_num)\n\n return self.__generateCont()\n\n def __generateCont(self):\n \"\"\"__generateCont []: Uses recursion to finish generating a full board, whilst also making sure the board is solvable by calling the solve method\"\"\"\n\n for row in range(len(self.sudokuBoard)):\n for col in range(len(self.sudokuBoard[row])):\n if self.sudokuBoard[row][col] == 0:\n _num = random.randint(1, 9)\n\n if self.checkSpace(_num, (row, col)):\n self.sudokuBoard[row][col] = _num\n\n if self.solve():\n self.__generateCont()\n return self.sudokuBoard\n\n self.sudokuBoard[row][col] = 0\n\n return False\n\n def findNumberOfSolutions(self):\n \"\"\"findNumberOfSolutions []: Finds the number of solutions to the current board and returns a list of all the solutions in code format\"\"\"\n _z = 0\n _list_of_solutions = []\n\n for row in range(len(self.sudokuBoard)):\n for col in range(len(self.sudokuBoard[row])):\n if self.sudokuBoard[row][col] == 0:\n _z += 1\n\n for i in range(1, _z + 1):\n _board_copy = copy.deepcopy(self)\n\n _row, _col = self.__findSpacesToFindNumberOfSolutions(_board_copy.sudokuBoard, i)\n _board_copy_solution = _board_copy.__solveToFindNumberOfSolutions(_row, _col)\n\n _list_of_solutions.append(self.boardToCode(input_board=_board_copy_solution))\n\n return list(set(_list_of_solutions))\n\n def __findSpacesToFindNumberOfSolutions(self, board, h):\n \"\"\"__findSpacesToFindNumberOfSolutions [board: list, h: integer]: Finds the first empty space in the board given as the argument, used within the findNumberOfSolutions method\"\"\"\n _k = 1\n for row in range(len(board)):\n for col in range(len(board[row])):\n if board[row][col] == 0:\n if _k == h:\n return (row, col)\n\n _k += 1\n\n return False\n\n # solves the board using recursion, is used within the findNumberOfSolutions method\n def __solveToFindNumberOfSolutions(self, row, col):\n \"\"\"__solveToFindNumberOfSolutions [row: integer, col: interger]: Solves the current board using recursion by starting at the position determined by the row and col, used within the findNumberOfSolutions method\"\"\"\n for n in range(1, 10):\n if self.checkSpace(n, (row, col)):\n self.sudokuBoard[row][col] = n\n\n if self.solve():\n return self.sudokuBoard\n\n self.sudokuBoard[row][col] = 0\n\n return False\n\n # resets the board to an empty state\n def __resetBoard(self):\n \"\"\"__resetBoard []:Resets the current board to an empty state\"\"\"\n self.sudokuBoard = [\n [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0],\n ]\n\n return self.sudokuBoard\n\n def isFull(self):\n \"\"\"checks if there's empty spaces in the board\"\"\"\n for row in range(len(self.sudokuBoard)):\n for col in range(len(self.sudokuBoard[row])):\n if self.sudokuBoard[row][col] == 0:\n return False\n\n return True\n\n def addValueToBoard(self, num, space):\n \"\"\"adds value to the board object\"\"\"\n if self.checkSpace(num, space):\n self.sudokuBoard[space[0]][space[1]] = num\n return True\n else:\n return False\n\n def showBoard(self):\n \"\"\"prints a visual representation of Sudoku\"\"\"\n print(\" 0, 1, 2, 3, 4, 5, 6, 7, 8 \")\n print(\" ---------------------------\")\n for row in range(0, self.sudokuBoard.__len__()):\n print(row, \": \", self.sudokuBoard[row])\n\n def play(self):\n \"\"\"abstract method to be implemented in different modes classes\"\"\"\n raise NotImplementedError(\"Must choose mod of play\")\n","repo_name":"alaahmad01/Sudoku-Game-implementaion","sub_path":"Board.py","file_name":"Board.py","file_ext":"py","file_size_in_byte":10689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"72623488410","text":"import itertools\nfrom random import choice, shuffle\nfrom copy import deepcopy\n\ndef score(prop,guess):\n #test all possible guesses and see\n #which have the same color pattern as the guess\n ret = \"\"\n for a in range(8):\n if colors[a] == 'B' and guess[a] not in guess[0:a]:\n black.add(guess[a])\n if guess[a] == prop[a]:\n ret += 'G'\n elif guess[a] in prop:\n ret += 'P'\n else:\n ret += 'B'\n for b in range(8):\n if prop[b] in black:\n return False\n if ret == colors:\n return True\n return False \n\n#open and clean the potential guesses\nwith open(\"sortedoptions.txt\",'r') as f:\n options = f.read().split('\\n')\noptions = list(set(options))\noptions = [i for i in options if i]\noptions = [sub.replace('==', '=') for sub in options]\n\n\n#initialize and select the first guess\nbest = 0\nguess = \"\"\nshuffle(options)\nfor a in options:\n if len(set(a)) > best:\n best = len(set(a))\n guess = a\nprint(guess)\n\npurple = set()\nblack = set()\nwhile True:\n best = 0\n guesses = []\n colors = input(\"Enter colors, G for Green, P for Purple, B for Black: \")\n for opt in options:\n #print(opt,guess,score(opt,guess))\n #input(\"\")\n if score(opt, guess):\n guesses.append(opt)\n shuffle(guesses)\n for a in guesses:\n if len(set(a)) > best:\n best = len(set(a))\n guess = a\n print(guess,len(guesses),\"Odds of guessing are : \"+str(1/len(guesses)*100)[0:4]+\"%\")\n if input(\"Continue? (y/n): \").lower() == 'n':\n break\n","repo_name":"davecons/nerdle","sub_path":"nerdle6.py","file_name":"nerdle6.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"74581980890","text":"\"\"\"\nGiven an array of integers where each number represents a sock's color, the \nfunction calculates the number of matching sock pairs. Each pair consists \nof two socks of the same color. The function takes the total number of socks \nand an array of their colors as input, and returns the total number of \nmatching pairs.\n\nInput Parameters:\n- int n: Number of socks in the pile.\n- int arr[n]: Array representing the colors of each sock.\n\nOutput:\n- int: The total number of matching sock pairs.\n\nConstraints:\n- 1 ≤ n ≤ 100\n- 1 ≤ arr[i] ≤ 100 where 0 ≤ i < n\n\"\"\"\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\ndef pair_counter(n, arr):\n countMap = {}\n\n for el in arr:\n if el in countMap:\n countMap[el] += 1\n else:\n countMap[el] = 1\n\n countPairs = 0\n\n for el in countMap.values():\n countPairs += el // 2\n\n return int(countPairs)\n\n\nif __name__ == \"__main__\":\n n = int(input().strip())\n arr = list(map(int, input().rstrip().split()))\n result = pair_counter(n, arr)\n print(str(result))\n","repo_name":"szkjn/algorithmic-playground","sub_path":"Python/scripts/pair_counter.py","file_name":"pair_counter.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}
+{"seq_id":"8433532669","text":"while True:\n age = int(input('How old are you?'))\n if age <= 7:\n print('Free of charge.')\n break\n elif 8 <= age <= 18:\n print('Please pay 4 dollars.')\n elif 60 <= age <=100:\n print('Free of charge.')\n else:\n continue\n \n\ni = int(input('Enter random number.'))\nwhile True:\n if i > 0:\n print('This is a positive integer')\n break\n elif i < 0:\n print('This is a negative integer.')\n elif i == 0:\n print('This is an integer.')\n else:\n print('Please enter a supported number.')\n continue\n\n\ndef describe_city(city, state, nation):\n print(city + ' is located in ' + state + ', ' + nation + '.')\n\ndescribe_city(city = 'Des Moines', state = 'Iowa', nation = 'United States')\n\n\ndef make_shirt(shirt_size, shirt_words):\n print('The shirt is sized ' + shirt_size + '.')\n print('The words on this shirt says: ' + shirt_words + '.')\n\nmake_shirt(shirt_size = '04', shirt_words = 'Life is like a box of chocolates')\n\n\ndef get_formatted_name(first_name, middle_name, last_name):\n full_name = first_name + ' ' + middle_name + ' ' + last_name\n return full_name.title()\n\ncelebrity = get_formatted_name('Johnathan', 'Cutler', 'Beckett')\nprint(celebrity)\n\n\noriginal_magicians = ['John', 'Moffat', 'Mark']\nnew_magicians = []\nfor magician in original_magicians:\n magician = 'The great ' + magician\n new_magicians.append(magician)\nprint(new_magicians)\n\ndef show_magicians():\n print('The great ' + str(new_magicians[0:3]) + '.')\n\nshow_magicians()\n\n\npizza_toppings = []\ndef make_pizza(size, pizza_toppings):\n print('\\nMaking a -' + str(size) + 'inch pizza with the following toppings:' + pizza_topping)\n\nfor pizza_topping in pizza_toppings:\n print('- ' + pizza_topping)\n\nimport make_pizza as mp\nmp.make(16, 'pepperoni')\nmp.make(12, 'ketchup')\n\nimport make_pizza as mp\nmp.clear()\n\n\n","repo_name":"zpl2020/python-learning","sub_path":"example08.py","file_name":"example08.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"32"}