diff --git "a/2808.jsonl" "b/2808.jsonl" new file mode 100644--- /dev/null +++ "b/2808.jsonl" @@ -0,0 +1,124 @@ +{"seq_id":"74793562","text":"# Problem 1\ndef greatest(a, b, c):\n if a > b and a > c:\n return a\n elif b > a and b > c:\n return b\n else:\n return c\n\nprint(greatest(2,9,5))\n\n# Problem 2\ndef forenheight(celcius):\n return (celcius * 9/5) + 32\nn = 37\nconverted = forenheight(n)\nprint(F\"The converted foreinheit of {n} is {converted}\")\n\n# Problem 3\nfor i in range(5):\n print(\"hello there \", end=\"\")\n\n# Problem 4\nn = 8\ndef sumOfNaturalNumbers(n):\n if n <= 1:\n return 1\n else:\n return n + sumOfNaturalNumbers(n-1)\nsumO = sumOfNaturalNumbers(n)\nprint(f\"The sum of first {n} natural numbers is {sumO}\")\n\n# Problem 5\n\ndef lines(n):\n for i in range(n, 0, -1):\n print(\"*\" * i)\n\nlines(9)\n\n# Problem 6 \ndef centi(incles):\n return incles * 2.54\nn = 12\nconverted = centi(n)\nprint(F\"The converted centimeter of {n} inch is {converted}\")\n\n# Problem 7 # string strip: \" Harry k \" => strip le extra space remove gardinchha\nthis = \" Harry k \"\nprint(this)\nprint(this.strip())\n\ndef removeStrip(string, word):\n newStr = string.replace(word, \"\")\n return newStr.strip()\n\nstring = \" Harry is a good boy \"\nword = \"good\"\nprint(removeStrip(string, word))\n\n\ndef multiTable(n):\n for i in range(10):\n print(f\"{n} x {i+1} = {n*(i+1)}\")\n\nmultiTable(15)\n\n","repo_name":"deepson1996/python-tutorial","sub_path":"chapter8/05_practice_set.py","file_name":"05_practice_set.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"71818082662","text":"from math import sqrt #Quadratwurzel-Funktion, um den Satz des Pythagoras anwenden zu können.\nimport os #Ich verwende dieses Modul, um die Anzahl von vorhandenen Beispieldateien zu ermitteln.\n\nn_Dateien=len(os.listdir(\"Beispieldateien\")) #Dateianzahl wird ermittelt.\n\nwhile True: #Es wird so lange nach einem input gefragt, bis eine Zahl eingegeben wurde, die zwischen 1 und n_Dateien liegt.\n try:\n datei_nummer=int(input(\"Welche Beispieldatei soll verwendet werden? \"))\n if not datei_nummer in range(1,n_Dateien+1):\n raise Exception\n break\n except:\n print(\"Bitte gebe eine Zahl von 1 bis \"+str(n_Dateien)+\" ein.\\n\")\n\nwith open(\"Beispieldateien\\\\\"+os.listdir(\"Beispieldateien\")[datei_nummer-1]) as file: #Die entsprechende Textdatei wird geöffnet, wobei vom Index 1 abgezogen wird, weil es mit 0 statt 1 beginnt.\n Zeilen=file.readlines() #Eine Liste aus den einzelnen Zeilen wird erstellt.\n n_Häuser=int(Zeilen[0].split(\" \")[0]) #Die Anzahlen der Häuser und Windräder werden ausgelesen, indem die beiden Zahlen mit Leerzeichen als Separator in eine Liste aus zwei Integern konveriert werden.\n n_Windräder=int(Zeilen[0].split(\" \")[1].strip()) #Damit die Umwandlung in eine Ganzzahl funktioniert, muss hier noch das \"unsichtbare\" Zeilenendezeichen \"\\n\" mit strip() entfernt werden.\n del Zeilen[0] #Die erste Zeile wird nun nicht mehr benötigt.\n for i in range(len(Zeilen)): #Alle übrigen Zeilen werden in dieser for-Schleife wie oben in Listen umgewandelt, die in diesem Fall jeweils den x- und den y-Wert enthalten.\n Zeilen[i]=Zeilen[i].split(\" \")\n for i2 in range(len(Zeilen[i])):\n Zeilen[i][i2]=int(Zeilen[i][i2].strip())\n Häuser=Zeilen[0:n_Häuser] #Die Liste wird aufgeteilt in eine Liste für die Häuser-Positionen und eine für die Windrad-Positionen.\n Windräder=Zeilen[n_Häuser:]\n\nmax_höhen=[]\nfor w in Windräder:\n am_nächsten=None\n for h in Häuser:\n x_abstand=abs(w[0]-h[0]) #Es werden der x- und der y-Abstand zwischen dem Haus und dem Windrad berechnet.\n y_abstand=abs(w[1]-h[1])\n abstand=sqrt(x_abstand**2+y_abstand**2) #Nun wird mithilfe des Satzes des Pythagoras der genaue Abstand zwischen Haus und Windrad berechnet.\n if am_nächsten==None: #Wenn die Variable am_nächsten noch nicht verglichen wurde, also None beträgt, darf sie nicht direkt mit einer Zahl verglichen werden. Daher habe ich hier auf ein logisches \"Oder\" verzichtet.\n am_nächsten=abstand\n elif abstand0:\n print(\"maximal \"+str(max_höhen[n])+\" m hoch sein.\\n\")\n else:\n print(\"nicht gebaut werden.\\n\")\n ausgabe_liste.append(str((Windräder[n][0],Windräder[n][1]))+\": \"+str(max_höhen[n])+\" m\")\n\nausgabe_liste=str(ausgabe_liste).replace(\"'\",\"\") #Aus Schönheitsgründen werden alle Anführungszeichen aus dem String der Liste entfernt.\nprint(\"Als Liste:\\n\"+ausgabe_liste)\nwhile True:\n pass\n","repo_name":"LennartEnns/BwInf-40-Round-1","sub_path":"Junioraufgabe 1/Zum_Winde_verweht.py","file_name":"Zum_Winde_verweht.py","file_ext":"py","file_size_in_byte":3520,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"44413633038","text":"# create a function that takes a number,\n# divides ten with it,\n# and prints the result.\n# it should print \"fail\" if the parameter is 0\n\ndef divides_with_ten():\n try:\n num = int(input(\"Give me a nmber:\"))\n result = 10 / num\n print(result)\n except ZeroDivisionError:\n print(\"FAIL\")\n\n \ndivides_with_ten()\n \n","repo_name":"green-fox-academy/Tofiz","sub_path":"week-03/day-01/divide_by_zero.py","file_name":"divide_by_zero.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"37700579415","text":"# File input & output!\n# Use to talk between the two apps.\n\n# Here's a good site with lots of practice data like the below:\n# https://github.com/plotly/datasets\n\nimport pandas as pd\n\n# 1) Read a CSV from URL\ndf = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')\n\n# 2) Save a CSV\ndf.to_csv('aaxxxpl_data.csv')\n\n# 3) Read a CSV from file\nnother_csv = pd.read_csv('aapl_data.csv')\n\n# 4) Make a dictionary\naction = 'BUY'\ntrade_currency = 'EURUSD'\ntrade_amt = 20000\n\n# trade_order is a dictionary -- you can retrieve its different elements as shown below.\ntrade_order = {\n \"action\": action,\n \"trade_currency\": trade_currency,\n \"trade_amt\": trade_amt\n}\n\nprint(trade_order)\n\n# Retrieve elements from the dictionary:\n# Retrieve the action\nprint(trade_order['action'])\n# Retrieve the trade_currency\nprint(trade_order['trade_currency'])\n# Retrieve the trade amount\nprint(trade_order['trade_amt'])\n\n# 5) Save that dictionary.\n# We'll need another module...\nimport pickle\n\npickle.dump(trade_order, open(\"trade_order.p\", \"wb\"))\n\n# 6) Read the pickle back...\nsome_var_w_pickle_data = pickle.load(open(\"trade_order.p\", \"rb\"))\nprint(some_var_w_pickle_data)\n\n# 7) Write a text file\nsome_var_that_I_want_to_write_as_text = \"Jake^2\"\nfile_to_write_to = open(\"file_w_jakes.txt\", \"w\")\nfile_to_write_to.write(some_var_that_I_want_to_write_as_text)\nfile_to_write_to.close()\n\n# 8) Read from a text file\nfile_to_read_from = open('file_w_jakes.txt', 'r')\ninfo_from_file=file_to_read_from.read()\nprint(info_from_file)\nfile_to_read_from.close()\n\n# 9) Working with directories\nimport os\n\n# Print everything in the current directory\nprint(os.listdir())\n\nprint('file_w_jakes.txt' in os.listdir())\n\n# 10) Delete a file\nos.remove(\"file_w_jakes.txt\")\n\nprint(os.listdir())\n\nprint('file_w_jakes.txt' in os.listdir())\n\n\n","repo_name":"farukuslu/Connecting-Dash-to-an-Execution-System-on-Interactive-Brokers-App","sub_path":"file_input_n_output.py","file_name":"file_input_n_output.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"30135737203","text":"from collections import Hashable\nfrom functools import partial\nfrom itertools import islice\nfrom typing import Iterable, Tuple, TypeVar\nfrom types import GeneratorType\n\n# pylint: disable=invalid-name\nT = TypeVar(\"T\")\n\ndef chunk(iterable, chunk_size):\n \"\"\"Make an iterator that returns 'chunk_size'-ed chunks of 'iterable'.\"\"\"\n # The purpose of this is to support both __iter__ and __getitem__ things.\n iterable_wrapper = iter(iterable)\n # This works by taking `chunk_size` slices out of the iterable,\n # this form of iter() keeps calling the function until the sentinel\n # value is reached, which in this case is the empty tuple. Hence\n # we keep slicing iterable until there are no values left.\n return iter(lambda: tuple(islice(iterable_wrapper, chunk_size)), ())\n\n\ndef lookahead(iterable: Iterable[T]) -> Iterable[Tuple[T, bool]]:\n \"\"\"Iterate over iterable yielding the value and if it is the last value.\"\"\"\n iterable_wrapper = iter(iterable)\n\n # At least return a single value, even if it is None\n try:\n result = next(iterable_wrapper)\n except StopIteration:\n return\n\n for value in iterable_wrapper:\n yield result, False\n result = value\n yield result, True\n\n\ndef lookaround(iterable):\n \"\"\"Iterate over iterable yielding the value and if it is a border value.\"\"\"\n iterable_wrapper = iter(iterable)\n\n # At least return a single value, even if it is None\n try:\n result = next(iterable_wrapper)\n except StopIteration:\n return\n\n first = True\n last = False\n\n for value in iterable_wrapper:\n yield result, first, last\n first = False\n result = value\n\n last = True\n yield result, first, last\n\n\ndef window(seq, n=2): # pylint: disable=invalid-name\n \"\"\"Return a sliding window over data from the iterable.\n\n Example:\n ```s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...```\n See: https://docs.python.org/release/2.3.5/lib/itertools-example.html\n \"\"\"\n iterable_wrapper = iter(seq)\n result = tuple(islice(iterable_wrapper, n))\n if len(result) == n:\n yield result\n elif result:\n missing_count = n - len(result)\n yield tuple(result) + tuple([None] * missing_count)\n for elem in iterable_wrapper:\n result = result[1:] + (elem,)\n yield result\n\n\ndef deep_get(indexable, indexes, default=None):\n \"\"\"Repeatedly index into an object.\n\n Continues to index into 'indexable' using the indexes in 'indexes',\n until a final value is reached, or an error occurs in which case\n the 'default' or None is returned.\n \"\"\"\n curr = indexable\n for index in indexes:\n if curr is None:\n return default\n try:\n curr = curr[index]\n except (KeyError, IndexError):\n return default\n return curr\n\n\ndef deep_set(indexable, indexes, value):\n \"\"\"Set a value at a nested index.\"\"\"\n def _collection_for_index(index):\n return [None] * index if isinstance(index, int) else {}\n\n def _value_at_index_is_collection(collection, index):\n try:\n value_at_index = collection[index]\n return isinstance(value_at_index, (dict, list))\n except (KeyError, IndexError):\n return False\n\n def _padd_list(collection, to_length):\n collection.extend([None] * (to_length - len(collection)))\n\n def _collection_supports_index(collection, index):\n if isinstance(collection, list) and isinstance(index, int):\n return True\n if isinstance(collection, dict) and isinstance(index, Hashable):\n return True\n return False\n\n curr = indexable\n for (now_index, next_index), is_last in lookahead(window(indexes, n=2)):\n if isinstance(curr, list):\n _padd_list(curr, now_index + 1)\n\n if not _collection_supports_index(curr, now_index):\n raise ValueError(\n f\"\"\"Unsupported index {now_index} for collection {curr}\"\"\"\n )\n\n if next_index is not None:\n if not _value_at_index_is_collection(curr, now_index):\n curr[now_index] = _collection_for_index(next_index)\n curr = curr[now_index]\n if isinstance(curr, list):\n _padd_list(curr, next_index + 1)\n\n if is_last:\n if next_index is None:\n curr[now_index] = value\n else:\n curr[next_index] = value\n\n return indexable\n\n\ndef pluralise(value, collection_types=(GeneratorType, list)):\n \"\"\"If value is singular return a collection containing it.\"\"\"\n if isinstance(value, collection_types):\n return value\n if value is not None:\n return [value]\n\n return []\n\n\ndef hasattrs(obj, names):\n \"\"\"Return whether the object has an attribute with the given name(s).\"\"\"\n _hasattr = partial(hasattr, obj)\n if isinstance(names, str):\n return _hasattr(names)\n return all(map(_hasattr, names))\n","repo_name":"HennyH/animeu","sub_path":"animeu/common/iter_helpers.py","file_name":"iter_helpers.py","file_ext":"py","file_size_in_byte":4966,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"35"} +{"seq_id":"3720192762","text":"\n\nclass Node:\n def __init__(self, value=None):\n self.previous = None\n self.value = value\n self.next = None\n \nclass DobulyLinkedList:\n def __init__(self):\n self.head = None\n self.tail = None\n \n def __iter__(self):\n node = self.head\n while node:\n yield node\n node = node.next\n \n # CREATION OF DOUBLY LINKED LIST\n def create(self, nodeValue):\n node = Node(nodeValue)\n self.head,self.tail = node,node\n print('Double Linked List created!')\n \n # Insert new Node \n def insert(self, nodeValue,nodeLocation):\n if not self.head: return print('Double Linked List does not exist!')\n newNode = Node(nodeValue)\n if nodeLocation == 0:\n newNode.next = self.head\n self.head.previous = newNode\n self.head = newNode\n elif nodeLocation == -1:\n newNode.previous = self.tail\n self.tail.next = newNode\n self.tail = newNode\n else:\n previousNode = self.head\n for i in range(nodeLocation-1):\n previousNode = previousNode.next\n \n newNode.previous,newNode.next = previousNode,previousNode.next\n previousNode.next,newNode.next.previous = newNode, newNode\n \n # Traverse through doubly linked list\n def traverse(self, reverse=False):\n if not self.head: return print('List is empty!')\n node = self.head if not reverse else self.tail\n while node:\n print(node.value)\n node = node.next if not reverse else node.previous\n \n # Searching node inside doubly linked list\n def search(self, nodeValue):\n if not self.head: return print('List is empty!')\n node = self.head\n while node:\n if node.value == nodeValue: return print(f'{nodeValue} is inside list')\n node = node.next\n print(f'{nodeValue} is not inside list')\n \n # DELETING NODE FROM DOUBLY LINKED LIST\n def delete(self, nodeLocation):\n if not self.head: return print('List is empty!')\n if nodeLocation == 0:\n if self.head == self.tail:\n self.head,self.tail = None, None\n else:\n self.head = self.head.next\n self.head.previous = None\n elif nodeLocation == -1:\n if self.head == self.tail:\n self.head,self.tail = None, None\n else:\n self.tail = self.tail.previous\n self.tail.next = None\n else:\n node = self.head\n for i in range(nodeLocation - 1):\n node = node.next\n node.next = node.next.next\n node.next.previous = node\n \n \n # Clear entire list \n def clear(self):\n if not self.head: return print('List is empty!')\n node = self.head\n while node:\n node.previous,node.next,node = None,None,node.next\n self.head,self.tail = None,None\n\n\n# Create doubly linked list \ndoublyLinkedList = DobulyLinkedList()\ndoublyLinkedList.create(4)\n\nprint([node.value for node in doublyLinkedList])\n\n# Insert new element into doublyLinkedList\ndoublyLinkedList.insert(2,0)\ndoublyLinkedList.insert(3,-1)\ndoublyLinkedList.insert(7,1)\nprint([[None if not node.previous else node.previous.value ,node.value, None if not node.next else node.next.value] for node in doublyLinkedList])\n\n# Traverse through list\ndoublyLinkedList.traverse()\ndoublyLinkedList.traverse(reverse=True)\n\n# Search if node is inside list\ndoublyLinkedList.search(1)\n\n# Delete node from list\n# doublyLinkedList.delete(-1)\n# print([[None if not node.previous else node.previous.value ,node.value, None if not node.next else node.next.value] for node in doublyLinkedList])\n\n# Clear list\ndoublyLinkedList.clear()\nprint([node.value for node in doublyLinkedList])\n\n","repo_name":"LilJack118/Algorithms-and-Data-Structures","sub_path":"Linked List/Doubly_Linked_List/doublylinkedlist.py","file_name":"doublylinkedlist.py","file_ext":"py","file_size_in_byte":3940,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"15617605459","text":"from typing import Dict, Any\n\nimport asyncio\nimport json\nimport logging\nimport urllib.parse\n\nimport logic\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n\ndef lambda_handler(event: Dict[str, Any], _: Any) -> Dict[str, Any]:\n\n resource_name = event.get(\"resource\", \"\")\n logging.info(\"Resource: %s\", resource_name)\n logging.info(\"Path parameters: %s\", event.get(\"pathParameters\"))\n\n status_code = 200\n\n if resource_name == \"/dataset_names\":\n try:\n response = json.dumps(asyncio.run(logic.dataset_names()))\n except Exception as exception:\n logging.exception(exception)\n logging.exception(exception)\n status_code = 400\n response = str(exception)\n\n elif resource_name == \"/query/{dataset}/{query}\":\n try:\n response = json.dumps(\n asyncio.run(\n logic.process_query(\n dataset=urllib.parse.unquote(\n event[\"pathParameters\"][\"dataset\"]\n ),\n query=urllib.parse.unquote(\n event[\"pathParameters\"][\"query\"]\n ),\n )\n )\n )\n except Exception as exception:\n logging.exception(exception)\n logging.exception(exception)\n status_code = 400\n response = str(exception)\n\n elif resource_name == \"/publish_file/{dataset}/{filename}\":\n try:\n response = json.dumps(\n asyncio.run(\n logic.publish_file_for_5_minutes_and_return_url(\n dataset=urllib.parse.unquote(\n event[\"pathParameters\"][\"dataset\"]\n ),\n filename=urllib.parse.unquote(\n event[\"pathParameters\"][\"filename\"]\n ),\n )\n )\n )\n except Exception as exception:\n logging.exception(exception)\n status_code = 400\n response = str(exception)\n else:\n status_code = 400\n response = \"Unknown route\"\n\n return {\n \"statusCode\": status_code,\n \"body\": response,\n \"headers\": {\"Access-Control-Allow-Origin\": \"*\"},\n }\n","repo_name":"osauldmy/FIT","sub_path":"VWM/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":2351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"42018645341","text":"# 1. socket (연결)\n# 2. bind (open)\n# 3. listen(Client로 부터 요청이 있을 때 까지 계속 listen)\n# 4. accept (Client로 부터 온 요청을 처리)\n# 5. close (종료)\n\nfrom socket import *\n\ns_ip = 'localhost'\ns_port = 9999\n\nc_sock = socket(AF_INET, SOCK_STREAM)\nc_sock.connect( (s_ip, s_port) )\n\ndata1 = 'Thank you for connecting'\nprint(data1, c_sock.recv(1024).decode('utf-8'))\ndata2 = '안녕하세요 이것은 소켓 프로그래밍입니다.'\nc_sock.send(data2.encode('utf-8'))\n\nc_sock.close()\n","repo_name":"YangYubin12/TIL","sub_path":"network/client-server/tcp_client.py","file_name":"tcp_client.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"ko","doc_type":"code","stars":4,"dataset":"github-code","pt":"35"} +{"seq_id":"40018038538","text":"from tkinter import *\nimport math\n\nroot = Tk()\n\ncanvas = Canvas(root, width = 600, height = 600)\ncanvas.pack()\n\n\ndef draw_polygon(x,y,s):\n h = math.sqrt(3) / 2 * s\n canvas.create_polygon(x, y, x + s, y, x + s / 2, y + h , fill='olive', outline='black')\n\ndef draw_fractal(x, y, s):\n h = math.sqrt(3) / 2 * s\n draw_polygon(x, y, s)\n half = s // 2\n if s < 5:\n pass\n else:\n draw_fractal(x, y, half)\n draw_fractal(x + half, y, half)\n draw_fractal(x + half / 2, y + h / 2, half)\n\ndraw_fractal(1, 1, 600)\nroot.mainloop()\n","repo_name":"greenfox-velox/DDL","sub_path":"week-04/day7/triangle.py","file_name":"triangle.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"3448104641","text":"#on command line: python setup.py build\n\nimport sys\nfrom cx_Freeze import setup, Executable\n\nexe = Executable(\n script=\"Facepager.py\",\n base=\"Win32GUI\",\n icon=\"../icons/icon_facepager.ico\",\n copyDependentFiles = True,\n targetDir=\"build\",\n compress=True,\n appendScriptToExe=True,\n appendScriptToLibrary=False\n )\n\nincludes = [\"sqlite3\",\"dateutil\",\"atexit\",\"PySide.QtNetwork\"]\nincludefiles = ['presets/','docs/']\n\n\nbuildoptions = {\n 'includes':includes,\n \"packages\":[\"sqlalchemy\",\"sqlalchemy.dialects.sqlite\",\"zlib\",\"dateutil\"],\n 'excludes' : [\"collections.abc\"],\n 'include_files':includefiles\n}\n\nsetup(\n name = \"Facepager 3\",\n version = \"3.6\",\n description = \"The Facebook Page Crawler\",\n options = {'build_exe': buildoptions},\n executables = [exe]\n )\n\n\n","repo_name":"Gurleen-Singh/Facepage-Connected-to-MySQL","sub_path":"src/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"19596021222","text":"\"\"\" Simple MQTT client\n\"\"\"\n\nimport logging\nfrom dataclasses import dataclass\nfrom typing import Callable\nfrom urllib.parse import urlparse\n\nimport paho.mqtt.client as mqtt\n\nlogger = logging.getLogger(\"drift-mqtt\")\n\n\n@dataclass\nclass Subscription:\n \"\"\"Subscription config\"\"\"\n\n topic: str\n quality_service: int\n handler: Callable\n\n\nclass MQTTClient:\n \"\"\"Wrapper around `paho.mqtt.Client`\n * correctly handles subscription after reconnect\n * supports connection strings (i.e. protocol://domain:port)\n * supports routing on different message handlers\n \"\"\"\n\n def __init__(self, uri: str, client_id: str = \"drift-mqtt-client\"):\n \"\"\"Init\n :param uri - ://:\n :param client_id - must be unique! if not - will cause disconnects\n \"\"\"\n self._uri = urlparse(uri)\n self._transport = \"websockets\" if self._uri.scheme == \"ws\" else \"tcp\"\n # TODO: check if we need v311 or v5 # pylint: disable=fixme\n self._client = mqtt.Client(client_id=client_id, transport=self._transport)\n self._client.on_connect = self.on_connect\n self._client.on_disconnect = self.on_disconnect\n self._client.on_subscribe = self.on_subscribe\n self._client.on_message = self.on_message\n self._client.reconnect_delay_set(min_delay=1, max_delay=30)\n self._client.enable_logger()\n self._subscriptions = []\n\n def on_message(self, _client, _userdata, message: mqtt.MQTTMessage):\n \"\"\"Message read callback\"\"\"\n for sub in self._subscriptions:\n if message.topic.startswith(sub.topic):\n try:\n sub.handler(message)\n except Exception: # pylint: disable=broad-except\n logger.exception(\"Error in a message handler\")\n\n def __getattr__(self, item):\n \"\"\"Forward unknown methods to MQTT client\"\"\"\n return getattr(self._client, item)\n\n def connect(self):\n \"\"\"Connect to mqtt, blocking call, will wait until response.\n It is safe to call subscribe after this.\n \"\"\"\n self._client.connect(host=self._uri.hostname, port=self._uri.port)\n while not self._client.is_connected():\n self._client.loop()\n\n def on_connect(self, _client, _userdata, _flags, return_code, _properties=None):\n \"\"\"Callback on mqtt connected\"\"\"\n if return_code == mqtt.MQTT_ERR_SUCCESS:\n logger.info(\"Connected to MQTT\")\n self._subscribe()\n else:\n logger.error(\n \"Connection to MQTT refused, code: %d, %s\",\n return_code,\n mqtt.error_string(return_code),\n )\n\n @staticmethod\n def on_disconnect(_client, _userdata, return_code):\n \"\"\"Callback on mqtt disconnected\"\"\"\n # this is a bug in paho, return_code 1 is a general error\n # (connection lost in this case)\n if return_code == mqtt.MQTT_ERR_NOMEM:\n return_code = mqtt.MQTT_ERR_CONN_LOST\n\n if return_code == mqtt.MQTT_ERR_SUCCESS:\n logger.info(\"Disconnected from MQTT, as requested\")\n else:\n logger.info(\n \"Disconnected from MQTT (%s), reconnecting\",\n mqtt.error_string(return_code),\n )\n\n @staticmethod\n def on_subscribe(_client, _userdata, _mid, _granted_qos, _properties=None):\n \"\"\"Subscribe callback, just log for now\"\"\"\n logger.info(\"Subscribed\")\n\n def _subscribe(self):\n \"\"\"Subscribe all pending subscriptions\"\"\"\n subs = [(sub.topic, sub.quality_service) for sub in self._subscriptions]\n if subs:\n self._client.subscribe(subs)\n\n def subscribe(self, topic, handler: Callable, quality_service=0):\n \"\"\"Subscription proxy to delay subscription until we connect to broker\"\"\"\n self._subscriptions.append(\n Subscription(topic=topic, quality_service=quality_service, handler=handler)\n )\n if self._client.is_connected():\n self._subscribe()\n","repo_name":"panda-official/DriftPythonClient","sub_path":"pkg/drift_client/mqtt_client.py","file_name":"mqtt_client.py","file_ext":"py","file_size_in_byte":4047,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"35"} +{"seq_id":"43041219249","text":"from flask import Blueprint, render_template, request,redirect, url_for,flash, Flask,session\nimport re\nfrom flask_login import login_user,login_required,logout_user,current_user\nfrom app import *\nimport braintree\nimport os\nfrom os.path import join, dirname\nfrom dotenv import load_dotenv\nfrom gateway import generate_client_token, transact, find_transaction\n\n\nbraintree_blueprint = Blueprint('braintree',\n __name__,\n template_folder='templates')\n\ndotenv_path = join(dirname(__file__), '.env')\nload_dotenv(dotenv_path)\napp.secret_key = os.environ.get('APP_SECRET_KEY')\n\n\nTRANSACTION_SUCCESS_STATUSES = [\n braintree.Transaction.Status.Authorized,\n braintree.Transaction.Status.Authorizing,\n braintree.Transaction.Status.Settled,\n braintree.Transaction.Status.SettlementConfirmed,\n braintree.Transaction.Status.SettlementPending,\n braintree.Transaction.Status.Settling,\n braintree.Transaction.Status.SubmittedForSettlement\n]\n\n\n@braintree_blueprint.route('/', methods=['GET'])\ndef new_checkout():\n client_token = generate_client_token()\n return render_template('braintree/new.html', client_token=client_token)\n\n\n@braintree_blueprint.route('/checkouts/result', methods=['POST'])\ndef create_checkout():\n result = transact({\n 'amount': request.form['amount'],\n 'payment_method_nonce': request.form['payment_method_nonce'],\n 'options': {\n \"submit_for_settlement\": True\n }\n })\n amount = int(request.form.get('amount'))\n\n\n if result.is_success or result.transaction:\n \n return redirect(url_for('braintree.show_checkout',transaction_id=result.transaction.id))\n else:\n for x in result.errors.deep_errors: flash('Error: %s: %s' % (x.code, x.message))\n return redirect(url_for('braintree.new_checkout'))\n\n\n\n\n@braintree_blueprint.route('/checkouts/', methods=['GET'])\ndef show_checkout(transaction_id):\n transaction = find_transaction(transaction_id)\n result = {}\n if transaction.status in TRANSACTION_SUCCESS_STATUSES:\n result = {\n 'header': 'Sweet Success!',\n 'icon': 'success',\n 'message': 'Your test transaction has been successfully processed. See the Braintree API response and try again.'\n }\n else:\n result = {\n 'header': 'Transaction Failed',\n 'icon': 'fail',\n 'message': 'Your test transaction has a status of ' + transaction.status + '. See the Braintree API response and try again.'\n }\n\n return render_template('braintree/show.html', transaction=transaction, result=result)","repo_name":"jasongohcy/dosbag_master","sub_path":"dosbag_web/blueprints/braintree/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"31476522008","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n path(\"get_presence\", views.get_presence, name=\"get_presence\"),\n path(\"update_presence\", views.update_presence, name=\"update_presence\"),\n path(\"submit_pad\", views.submit_pad, name=\"submit_pad\"),\n]\n","repo_name":"jonathanhacker/flatpad","sub_path":"flatpad/core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"35"} +{"seq_id":"74557626660","text":"import datetime\nfrom random import choice\n\nfrom adapt.intent import IntentBuilder\nfrom appdaemon.appapi import AppDaemon\nfrom pymorphy2 import MorphAnalyzer\n\n\nclass SayWeekday(AppDaemon):\n\n def initialize(self):\n self.context_sensitive = True\n self.answers = [\"{now} {weekday}.\",\n \"{weekday}.\",\n \"{weekday} вроде бы.\"]\n self.times = {\"сегодня\": 0, \"завтра\": 1, \"послезавтра\": 2}\n\n self.morph = MorphAnalyzer()\n\n engine = self.get_app(\"brain\").engine\n keyword = [\"день\", \"число\"]\n day = [\"сегодня\", \"завтра\", \"послезавтра\"]\n question = [\"какой\"]\n for k in keyword:\n engine.register_entity(k, \"SayWeekdayKeyword\")\n for d in day:\n engine.register_entity(d, \"SayWeekdayDay\")\n for q in question:\n engine.register_entity(q, \"SayWeekdayQuestion\")\n sayweekday_intent = IntentBuilder(\"sayweekday\").\\\n require(\"SayWeekdayKeyword\").optionally(\n \"SayWeekdayDay\").optionally(\"SayWeekdayQuestion\").build()\n engine.register_intent_parser(sayweekday_intent)\n\n print(\"sayweekday initialized\")\n\n def handle(self, intent_dict):\n offset = intent_dict.get(\"SayWeekdayDay\", \"сегодня\")\n action = intent_dict[\"SayWeekdayKeyword\"]\n mydate = datetime.datetime.now() + \\\n datetime.timedelta(days=self.times[offset])\n if action == \"день\":\n res = self.weekday(mydate)\n else:\n res = self.date(mydate)\n\n ans = choice(self.answers)\n print(ans)\n print(res)\n print(offset)\n fans = ans.format(weekday=res, now=offset)\n if ans[0] == \"{\":\n fans = fans.capitalize()\n return fans\n\n def weekday(self, dt):\n weekdays = {0: \"понедельник\", 1: \"вторник\", 2: \"среда\",\n 3: \"четверг\", 4: \"пятница\", 5: \"суббота\", 6: \"воскресение\"}\n return weekdays[dt.weekday()]\n\n def date(self, dt):\n months = {1: \"январь\",\n 2: \"февраль\",\n 3: \"март\",\n 4: \"апрель\",\n 5: \"май\",\n 6: \"июнь\",\n 7: \"июль\",\n 8: \"август\",\n 9: \"сентябрь\",\n 10: \"октябрь\",\n 11: \"ноябрь\",\n 12: \"декабрь\"}\n print(dt.day)\n print(dt.day.__class__)\n\n return str(dt.day) + \" \" + self.morph.parse(months[dt.month])[0].make_agree_with_number(dt.day).word\n","repo_name":"jumper047/yuki","sub_path":"plugins/dandt/dandt.py","file_name":"dandt.py","file_ext":"py","file_size_in_byte":2751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"6162693959","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\nfrom __future__ import division\n\nimport os\nimport sys\nimport time\nimport json\nimport copy\nimport random\n\n\nclass Access(dict):\n def __init__(self, pid):\n dict.__init__(self)\n self.path = '/proc/%s/fd/0' % pid\n self.loaded = {}\n self.load()\n\n def load(self):\n with open('state') as f:\n self.loaded = json.load(f)\n self.clear()\n self.update(copy.deepcopy(self.loaded))\n\n def senddata(self, content):\n with open(self.path, 'w') as f:\n f.write(json.dumps(content))\n\n def save(self):\n tosend = {}\n for k in self:\n if self[k] != self.loaded.get(k):\n tosend[k] = self[k]\n self.senddata(tosend)\n self.loaded = copy.deepcopy(self)\n\n\ndef getpid():\n return os.popen('pgrep -nf \"python.*vimim\"', 'r').read().strip()\n\n\ndef connect():\n pid = getpid()\n if not pid: raise OSError('vimim process not found')\n return Access(pid)\n","repo_name":"TomiBelan/ksp-vimim","sub_path":"access.py","file_name":"access.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"36681018336","text":"from pathlib import Path\n\nfrom setuptools import find_namespace_packages, setup\n\n\ndef requirements():\n BASE_DIR = Path(__file__).parent\n with open(Path(BASE_DIR, \"requirements.txt\"), \"r\") as file:\n required_packages = [ln.strip() for ln in file.readlines()]\n return [required_packages]\n\n\nsetup(\n name=\"Ontology Pretraining - codebase\",\n version=0.1,\n author=\"Simone Scaboro, Beatrice Portelli\",\n author_email=\"scaboro.simone@gmail.com\",\n python_requires=\">=3.8\",\n packages=find_namespace_packages(),\n install_requires=requirements(),\n extras_require={\"dev\": [\"black\", \"flake8\", \"isort\"]},\n)\n","repo_name":"AilabUdineGit/ontology-pretraining-code","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"35"} +{"seq_id":"40015273218","text":"\"\"\"Module for managing load modeling: take data from the platform,\nmanipulate it, then perform a ZIP fit.\n\"\"\"\n# Standard library:\nimport logging\nfrom datetime import timedelta\nimport time\nimport multiprocessing as mp\nimport threading\nimport queue\n\n# Third party:\nimport numpy as np\nimport pandas as pd\n\n# pyvvo:\nfrom pyvvo.gridappsd_platform import PlatformManager\nfrom pyvvo import utils, timeseries, zip\n\nLOG = logging.getLogger(__name__)\n\n# The GridLAB-D triplex loads (from the platform) start with ld_ while\n# the loads straight from CIM do not.\nTRIPLEX_LOAD_PREFIX = 'ld_'\n# In CIM, triplex loads come in as 208V, when they should be 120.\n# This is a known issue that won't be fixed.\nCIM_TRIPLEX_VOLTAGE = 208\n# At some point, the platform started keeping separate EnergyConsumer\n# objects for each triplex load phase. These seem to be suffixed with\n# 'a' and 'b'.\nCIM_TRIPLEX_SUFFIX_SET = {'a', 'b'}\n# For fitting, we need to use a nominal voltage.\nFIT_NOMINAL_VOLTAGE = 240\n\n# Get the configuration. TODO: We may want to load this dynamically.\nCONFIG = utils.read_config()\n\n\nclass QueueFeeder:\n\n def __init__(self, load_measurements: pd.DataFrame, simulation_id: str,\n data_queue: mp.Queue,\n initial_n: int, subsequent_n: int, meas_per_load: int = 4,\n starttime=None, endtime=None,\n ):\n\n \"\"\"\n Class to continuously feed a queue with historic load data\n from the platform. After initialization, attach a thread to\n the object's \"run\" method. This class's singular purpose is to\n get load data from the platform and put it into a queue.\n However, it does so in a way that is memory friendly - we don't\n go and ask for data for all loads at once.\n\n :param load_measurements: DataFrame as would come from\n sparql.SPARQLManager.query_load_measurements()\n :param simulation_id:\n :param data_queue: Multiprocessing queue to put data into.\n :param initial_n: Initial number of\n :param subsequent_n:\n :param meas_per_load: Number of measurements per load. Will always\n be 4 for triplex loads (one VA and one PNV measurement per\n phase).\n :param starttime: Passed directly to\n gridappsd_platform.PlatformManager.get_simulation_output\n :param endtime: Passed directly to\n gridappsd_platform.PlatformManager.get_simulation_output\n \"\"\"\n # Ensure we have the correct number of measurements per load.\n if (load_measurements.groupby('eqid').size() != meas_per_load).all():\n raise ValueError(f'Given DataFrame does not have {meas_per_load} '\n 'measurements per load!')\n\n # Initialize logger.\n self.log = logging.getLogger(self.__class__.__name__)\n\n # Simply set some attributes equal to inputs.\n self.simulation_id = simulation_id\n self.q = data_queue\n self.initial_n = initial_n\n self.subsequent_n = subsequent_n\n self.meas_per_load = meas_per_load\n self.starttime = starttime\n self.endtime = endtime\n\n # Our queue will change by initial_n - subsequent_n before any\n # more work is done.\n self.q_threshold = self.initial_n - subsequent_n\n\n # Initialize a signal queue for flagging each time _load_queue\n # is called. This is really to make testing/debugging easier.\n self.signal_queue = queue.Queue()\n self.load_count = 0\n\n # Initialize a platform manager.\n self.mgr = PlatformManager()\n\n # Sort data by energy consumer ID so we can use iloc to slice up\n # the DataFrame\n self.df = load_measurements.copy(deep=True).sort_values(by='eqid')\n\n # Number of measurements to query initially.\n self.initial_meas = self.initial_n * self.meas_per_load\n\n if self.initial_meas > self.df.shape[0]:\n self.log.warning(\n 'The number of measurements to query for initially, '\n f'{self.initial_meas}, is > the total number of measurements, '\n f'{self.df.shape[0]}. All measurements will be extracted at '\n 'once.')\n self.initial_meas = self.df.shape[0]\n self.subsequent_meas = 0\n else:\n # Number of measurements to query subsequently.\n self.subsequent_meas = self.subsequent_n * self.meas_per_load\n\n # Set flag for when we're done.\n self.done = False\n\n def run(self, timeout=15):\n # Initialize indices.\n s = 0\n e = self.initial_meas\n\n # Load up the queue initially.\n self._load_queue(self.df.iloc[s:e])\n\n # Compute the remaining measurements to query for.\n remaining = self.df.shape[0] - self.initial_meas\n\n # Nothing more to do. Job complete.\n if remaining == 0:\n return None\n\n # Determine how many loop iterations we need to run to fill get\n # through all the measurements.\n n = int(np.ceil(remaining / self.subsequent_meas))\n for i in range(n):\n # Update our indices for this iteration.\n s = e\n e = s + self.subsequent_meas\n\n # Wait until the queue size has reduced adequately.\n t = 0\n while (self.q.qsize() > self.q_threshold) and (t < timeout):\n time.sleep(0.1)\n t += 0.1\n\n # Raise a timeout error if necessary.\n if t >= timeout:\n raise TimeoutError('The queue did not reduce in size '\n f'within {timeout} seconds.')\n\n # Extract measurement MRIDs and load up the queue.\n # Note that Pandas will not throw an error here if we\n # exceed the index, so it'll naturally go to the end\n # without the need to try/except IndexError.\n self._load_queue(self.df.iloc[s:e])\n\n # Flag completion.\n self.done = True\n\n def _load_queue(self, df_in):\n # Update the counter\n self.load_count += 1\n\n # Query platform.\n data = self.mgr.get_simulation_output(\n simulation_id=self.simulation_id,\n query_measurement='gridappsd-sensor-simulator',\n measurement_mrid=df_in['id'].tolist(), index_by_time=False,\n starttime=self.starttime, endtime=self.endtime\n )\n\n # Map the data and group by equipment.\n grouped = _drop_merge_group(map_df=df_in, data_df=data)\n\n # Put each group in the queue.\n for _, group in grouped:\n self.q.put(group)\n\n # Flag that we've put data into the queue.\n self.signal_queue.put(self.load_count)\n\n\ndef _drop_merge_group(map_df, data_df):\n \"\"\"Helper to take simulation output data from the platform, drop\n columns we don't care about, merge with a DataFrame which maps\n equipment MRIDs, measurement MRIDs, and measurement types, and\n finally group by equipment ID. This helper should only be used\n by the QueueFeeder, and is separated out like this to ease testing.\n\n :param map_df: DataFrame as would come from\n sparql.SPARQLManager.query_load_measurements()\n :param data_df: DataFrame as would come from\n gridappsd_platform.PlatformManager.get_simulation_output, with\n the index_by_time parameter set to False.\n \"\"\"\n # Drop the instance_id, hasSimulationMessageType, and simulation_id\n # columns.\n data_df.drop(columns=['instance_id', 'hasSimulationMessageType',\n 'simulation_id'], inplace=True)\n\n # Merge with the map DataFrame.\n merged = data_df.merge(right=map_df[['meas_mrid', 'eqid', 'meas_type']],\n how='left', left_on='measurement_mrid',\n right_on='meas_mrid', copy=False).drop(columns=['meas_mrid'])\n\n # Return the merged DataFrame grouped by equipment ID.\n return merged.groupby(by='eqid')\n\n\nclass LoadModelManager:\n \"\"\"Class for managing our load models.\"\"\"\n\n def __init__(self, load_nominal_voltage, load_measurements,\n load_names_glm):\n \"\"\"Map and filter the given data down to a single DataFrame with\n relevant information.\n\n :param load_nominal_voltage: Pandas DataFrame, should come from\n sparql.SPARQLManager.query_load_nominal_voltage()\n :param load_measurements: Pandas DataFrame, should come from\n sparql.SPARQLManager.query_load_measurements()\n :param load_names_glm: List of strings of the triplex load names\n within a GridLAB-D model. The simplest way to obtain this is\n through a glm.GLMManager object ('mgr' in this example):\n list(mgr.get_items_by_type(item_type='object',\n object_type='triplex_load').keys())\n :param simulation_id: ID of simulation for which we're managing\n load models.\n \"\"\"\n # Initialize the log.\n self.log = logging.getLogger(self.__class__.__name__)\n\n # Store reference to the load measurements.\n self.load_measurements = load_measurements\n\n # Map our inputs together, resulting in a single DataFrame.\n self._load_df = self._map_names_to_measurements(load_nominal_voltage,\n load_measurements,\n load_names_glm)\n\n # Group by equipment ID.\n self.load_df_grouped = self.load_df.groupby(by='eqid')\n\n # Log success.\n self.log.info('GridLAB-D load names successfully mapped to CIM '\n 'measurements.')\n\n # Get a PlatformManager for weather queries.\n self._platform = PlatformManager()\n self.log.info('PlatformManager initialized.')\n\n # Initialize queues to be used for creating load models in\n # parallel.\n self._input_queue = mp.JoinableQueue()\n self._output_queue = mp.Queue()\n self._logging_queue = mp.Queue()\n\n # Later, we'll initialize a QueueFeeder.\n self.feeder = None\n\n # Start the logging thread.\n self._logging_thread = \\\n threading.Thread(target=_logging_worker,\n kwargs={'logging_queue': self.logging_queue})\n self.log.info('Logging thread started.')\n\n self.logging_thread.start()\n\n # Initialize processes to be None.\n self._processes = None\n\n # Determine how many processes to run.\n # TODO: We'll want to make this configurable in the future.\n self._n_jobs = mp.cpu_count() - 1\n self.log.info('Initialization complete.')\n\n @property\n def load_df(self):\n \"\"\"Pandas DataFrame with four columns: meas_type, meas_mrid,\n eqid, and load_name.\n \"\"\"\n return self._load_df\n\n @property\n def input_queue(self):\n \"\"\"Multiprocessing JoinableQueue which provides input to the\n _get_data_and_fit_worker method.\n \"\"\"\n return self._input_queue\n\n @property\n def output_queue(self):\n \"\"\"Multiprocessing Queue where output from\n _get_data_and_fit_worker is placed.\n \"\"\"\n return self._output_queue\n\n @property\n def logging_queue(self):\n \"\"\"Multiprocessing Queue where logging information from\n _get_data_and_fit_worker is placed.\n \"\"\"\n return self._logging_queue\n\n @property\n def logging_thread(self):\n \"\"\"threading.Thread object targeted at _logging_worker.\n \"\"\"\n return self._logging_thread\n\n @property\n def processes(self):\n \"\"\"list of multiprocessing.Process objects, targeted at\n _get_data_and_fit_worker.\n \"\"\"\n return self._processes\n\n @property\n def n_jobs(self):\n \"\"\"Integer number of processes/jobs to run.\"\"\"\n return self._n_jobs\n\n @property\n def platform(self):\n \"\"\"gridappsd_platform.PlatformManager object, intended for\n getting weather data.\n \"\"\"\n return self._platform\n\n def _map_names_to_measurements(self, load_nominal_voltage,\n load_measurements, load_names_glm):\n \"\"\"Initialization helper to create the load_df attribute.\n \"\"\"\n\n # For starters, ensure we actually have triplex loads from the\n # GridLAB-D model.\n if len(load_names_glm) < 1:\n raise ValueError('load_names_glm cannot be empty.')\n\n # Start by merging the load_nominal_voltage and\n # load_measurements DataFrames.\n merged = load_measurements.merge(right=load_nominal_voltage,\n left_on='load', right_on='name')\n self.log.debug('load_measurements and load_nominal_voltage merged.')\n\n # Drop columns we don't need.\n # Notes:\n # name_x: This is the EnergyConsumer name in CIM - who cares.\n # phases_y: We've shown this is duplicated/unnecessary\n # name_y: We've shown this is duplicated/unnecessary.\n merged = merged.drop(columns=['name_x', 'phases_y', 'name_y'])\n\n # Rename the 'phases_x' column for simplicity/clarity\n merged.rename(columns={'phases_x': 'phases'}, inplace=True)\n\n # For now, we're only working with 120/240V loads. Filter.\n nom_v_filter = merged['basev'] == CIM_TRIPLEX_VOLTAGE\n\n # Log if it's not all 208.\n if not nom_v_filter.all():\n self.log.warning('Not all given loads have a base voltage of '\n '{:.0f}V.'.format(CIM_TRIPLEX_VOLTAGE))\n\n # We only care about the 208V loads. To avoid \"settingwithcopy\"\n # issues in Pandas, create a copy and delete our old frame.\n merged_208 = merged.loc[nom_v_filter, :].copy(deep=True)\n del merged\n self.log.debug('Merged DataFrame filtered by nominal voltage.')\n\n # Now, strip the last character from the load names IFF it's an\n # 'a' or a 'b'. This will ONLY strip the character if it's\n # there, just like the fix_load_name function.\n merged_208.loc[:, 'load'].replace(regex=True, inplace=True,\n to_replace=r'[ab]$', value='')\n\n # Group by load name, measurement type, and load phases to\n # ensure that we have all the expected measurements for each\n # load.\n grouped = merged_208.groupby(['load', 'type', 'phases'])\n\n # For starters, we should have four times the number of groups\n # as triplex loads in the model, because each load should have\n # four measurements.\n if len(grouped) != (len(load_names_glm) * 4):\n raise ValueError('The number of triplex loads in load_nominal_'\n 'voltage/load_measurements does not match the '\n 'number of loads in load_names_glm. This could '\n 'be due to mismatched names during merging, miss'\n 'ing measurements, or a similar issue.')\n\n # Now, all groups should be size 1 (essentially checking that\n # for each phase of each load we have a PNV and VA measurement).\n if not (grouped.size() == 1).all():\n raise ValueError('Each load should have four measurements, but '\n 'that is not the case.')\n\n # Fix the load_names_glm so they match what's in the 'load'\n # column of merged_208.\n fixed_names = [n for n in map(fix_load_name, load_names_glm)]\n\n # Ensure the fixed_names matches the 'load' column.\n diff = set(fixed_names) ^ set(merged_208['load'])\n if not (len(diff) == 0):\n raise ValueError('The load names given in load_nominal_voltage/loa'\n 'd_measurements do not align with the load names '\n 'in load_names_glm.')\n # Log success.\n self.log.debug('All expected measurements are present, and they match '\n 'up with load_names_glm.')\n\n # Now that we've confirmed everything matches, we can add a\n # column to our DataFrame.\n name_df = pd.DataFrame({'fixed_name': fixed_names,\n 'load_names_glm': load_names_glm})\n final_df = merged_208.merge(right=name_df, left_on='load',\n right_on='fixed_name',\n validate='many_to_one')\n\n # Finally, clean up our DataFrame to keep only the things we\n # care about.\n final_df.drop(columns=['class', 'node', 'phases', 'load',\n 'trmid', 'bus', 'basev', 'conn',\n 'fixed_name'], inplace=True)\n\n # Rename columns for clarity.\n final_df.rename(columns={'type': 'meas_type', 'id': 'meas_mrid',\n 'load_names_glm': 'load_name'}, inplace=True,\n errors='raise'\n )\n\n # The final test: ensure we don't have any NaNs.\n if final_df.isna().any().any():\n raise ValueError('Our final DataFrame has NaNs in it!')\n\n return final_df\n\n def _start_processes(self):\n \"\"\"Helper to start up processes for fitting.\"\"\"\n # If the processes have already been started, log and do\n # nothing.\n if self.processes is not None:\n self.log.warning('_start_processes called when the processes '\n 'attribute is not None! Doing nothing.')\n return\n\n # Overwrite self._processes to be a list.\n self._processes = []\n for n in range(self.n_jobs):\n # Initialize process, attaching it to the _evaluate_worker\n # method.\n p = mp.Process(target=_get_data_and_fit_worker, name=str(n),\n kwargs={'input_queue': self.input_queue,\n 'output_queue': self.output_queue,\n 'logging_queue': self.logging_queue})\n\n # Add this process to the list.\n self.processes.append(p)\n # Start this process.\n p.start()\n\n # All done.\n self.log.info('Processes started.')\n\n def _stop_processes(self):\n \"\"\"Helper to stop all our processes.\n\n It will be assumed that the input_queue has been cleared out.\n \"\"\"\n if self.processes is None:\n self.log.warning('_stop_processes called, but self.processes '\n 'is None! Doing nothing.')\n return\n\n # Send in the termination signal.\n for _ in range(len(self.processes)):\n self.input_queue.put(None)\n\n # Wait for all the process functions to return.\n for p in self.processes:\n p.join(timeout=None)\n p.close()\n\n # Set the processes property to None.\n self._processes = None\n\n self.log.info('Processes closed.')\n\n def fit_for_all(self, sim_id, starttime, endtime, feeder_kwargs):\n \"\"\"\"\"\"\n # Initialize a QueueFeeder.\n self.feeder = QueueFeeder(load_measurements=self.load_measurements,\n data_queue=self._input_queue,\n simulation_id=sim_id,\n starttime=starttime, endtime=endtime,\n **feeder_kwargs)\n\n # Fire up processes.\n self._start_processes()\n\n # Get weather data.\n # TODO: Could this weather data be resampled ahead of time?\n # Or is it best to leave it as is so that Pandas can do its\n # magic when joining with the load data and then\n # interpolating?\n weather_data = self.platform.get_weather(start_time=starttime,\n end_time=endtime)\n\n # Initialize get_data_for_load arguments.\n gdfl_kwargs = {'sim_id': sim_id, 'starttime': starttime,\n 'endtime': endtime}\n\n # Initialize fit_for_load arguments.\n # TODO: Add options for selection_data and prediction_datetime.\n ffl_kwargs = {'weather_data': weather_data}\n\n # Fill up queue by looping over loads.\n grouped = self.load_df.groupby('load_name')\n\n for g in grouped:\n # The DataFrame is in entry 1 of the tuple, and the name\n # is in entry 0.\n self.input_queue.put(\n {'gdfl_kwargs': {'meas_data': g[1], **gdfl_kwargs},\n 'ffl_kwargs': ffl_kwargs,\n 'load_name': g[0]})\n pass\n\n\ndef fix_load_name(n):\n \"\"\"Strip quotes, remove prefix, and remove suffix from load names.\n\n Load names in a GridLAB-D model from the platform are quoted and\n start with a prefix when compared to the name in the CIM. Make the\n GridLAB-D model version look like what's in the CIM, but also\n remove the one character suffix (which must be either 'a' or 'b').\n The once character 'a'/'b' suffix does not have to be present.\n\n :param n: String, name for triplex load to be fixed.\n\n :returns: n without quotes at the beginning or end, the\n TRIPLEX_LOAD_PREFIX removed, and the one character ('a' or 'b')\n suffix removed.\n \"\"\"\n # Ensure our string does indeed start and end with quotes.\n if not (n.startswith('\"') and n.endswith('\"')):\n raise ValueError('Input to fix_load_name must start and end with a '\n 'double quote.')\n\n # Exclude the first and last characters.\n tmp = n[1:-1]\n # Ensure the remaining string starts with TRIPLEX_LOAD_PREFIX.\n if not tmp[0:len(TRIPLEX_LOAD_PREFIX)] == TRIPLEX_LOAD_PREFIX:\n raise ValueError('Once double quotes are removed, input to fix_load'\n '_name must start with {}.'\n .format(TRIPLEX_LOAD_PREFIX))\n\n # If the last character is either 'a' or 'b', strip it. Else, do\n # nothing.\n if (tmp[-1] == 'a') or (tmp[-1] == 'b'):\n tmp = tmp[:-1]\n\n # Strip off the prefix and suffix and return.\n return tmp[len(TRIPLEX_LOAD_PREFIX):]\n\n\ndef transform_data_for_load(meas_data: pd.DataFrame):\n \"\"\"Given load measurement data from a QueueFeeder's queue, combine\n VA and PNV measurements as appropriate, create DataFrame with v,\n p, and q for load modeling.\n\n :param meas_data: Pandas DataFrame which comes from a QueueFeeder.\n It represents data for a SINGLE load over a given time\n horizon. IMPORTANT: Right now, we're assuming this is a\n triplex load and simply summing PNV measurements for the\n same timestamp and also summing VA measurements for the\n same timestamp.\n\n :returns: pandas DataFrame with three columns, 'v', 'p', and 'q'.\n Indexed by time as returned by\n gridappsd_platform.PlatformManager.get_simulation_output.\n \"\"\"\n # Get complex numbers for angle and magnitude.\n meas_data['cplx'] = utils.get_complex(r=meas_data['magnitude'],\n phi=meas_data['angle'],\n degrees=True)\n\n # Sum PNV and VA measurements that occur at the same time.\n grouped = meas_data.loc[:, ['cplx', 'time', 'meas_type']].groupby(\n by=['time', 'meas_type']).sum().reset_index()\n\n # Extract PNV and VA measurements.\n pnv_mask = grouped['meas_type'] == 'PNV'\n va_mask = grouped['meas_type'] == 'VA'\n\n pnv = grouped.loc[pnv_mask, ['cplx', 'time']].set_index(\n 'time').rename(columns={'cplx': 'pnv'})\n va = grouped.loc[va_mask, ['cplx', 'time']].set_index(\n 'time').rename(columns={'cplx': 'va'})\n\n # Ensure they're the same length.\n assert pnv.shape == va.shape\n assert pnv.shape[0] + va.shape[0] == meas_data.shape[0] / 2\n\n # Combine.\n df = pnv.join(va)\n\n # Create v, p, and q columns.\n df['v'] = df['pnv'].abs()\n df['p'] = df['va'].values.real\n df['q'] = df['va'].values.imag\n\n # Return a DataFrame with the 'v', 'p', and 'q' columns needed for\n # ZIP fitting.\n return df.loc[:, ['v', 'p', 'q']]\n\n\ndef fit_for_load(load_data, weather_data, selection_data=None,\n prediction_datetime=None):\n \"\"\"Combine load and weather data, filter by time (day of week and\n time of day), and then get a ZIP model by calling\n pyvvo.zip.get_best_fit_from_clustering.\n\n :param load_data: Pandas DataFrame. Return from get_data_for_load.\n :param weather_data: Pandas DataFrame which has originated from\n gridappsd_platform.PlatformManager.get_weather. The data is\n already assumed to be cleaned, e.g. it has already been passed\n through timeseries.fix_ghi.\n :param selection_data: Pandas Series, used as the point in space to\n which cluster distances are measured. Passed directly to\n zip.get_best_fit_from_clustering. Note all values of the index\n must be columns in either load_data or weather_data, and voltage\n ('v') is not allowed. If None, the last 'temperature' and 'ghi'\n values after DataFrame merging and interpolation will be used.\n :param prediction_datetime: Optional. datetime.datetime object,\n representing the starting time of the interval for which the\n load model will be used to make predictions. If not provided,\n it will be inferred from the last entry in either load_data or\n weather_data, whichever has the later time.\n\n NOTE 1: It's assumed that load_data and weather_data were pulled\n using the same starting and ending times.\n\n NOTE 2: These two DataFrames will be merged, and any resulting\n NaN values will be filled by simple linear interpolation. Thus,\n it's the caller's responsibility to ensure reasonable alignment\n between the indices of the DataFrames.\n\n :returns: output from pyvvo.zip.get_best_fit_from_clustering.\n\n TODO: Should this filtering and joining be moved? It seems like it\n could be excessive to do this for every single load. Maybe it\n would be better to create one big DataFrame with all the load\n data?\n\n Back of the napkin:\n 2000 loads * 15 minutes * 4 intervals/hour * 24 hour/day\n * 7 days/week * 2 weeks * 3 parameters * 8 bytes/parameter\n * 1 MB/1,000,000 bytes = 968 MB.\n\n We may not want to suck that into memory. We could \"chunk\" it\n somehow. Well, we'll cross that bridge later.\n\n \"\"\"\n # Join our load_data and weather_data, fill gaps via time-based\n # linear interpolation.\n df = load_data.join(weather_data, how='outer').interpolate(method='time')\n\n # If the indices didn't line up, we'll backfill and forward fill\n # the rest. If this is ever necessary, it should just be for the\n # first and last rows.\n df.fillna(method='backfill', inplace=True)\n df.fillna(method='ffill', inplace=True)\n\n # Get interval string from the configuration.\n interval_str = CONFIG['load_model']['averaging_interval']\n\n # At this point, our df may not have an evenly spaced index. So,\n # we need to determine if we're upsampling or downsampling.\n # noinspection PyUnresolvedReferences\n f1 = pd.tseries.frequencies.to_offset(\n pd.infer_freq(weather_data.index))\n # noinspection PyUnresolvedReferences\n f2 = pd.tseries.frequencies.to_offset(pd.infer_freq(load_data.index))\n\n if (f1 is None) and (f2 is not None):\n min_f = f2\n elif (f1 is not None) and (f2 is None):\n min_f = f1\n elif (f1 is not None) and (f2 is not None):\n min_f = min(f1, f2)\n else:\n raise ValueError('Neither the given load_data nor weather_data '\n 'have an evenly spaced index. This makes resampling '\n 'impossible, and is not acceptable.')\n\n # Determine if we're upsampling or downsampling.\n method = timeseries.up_or_down_sample(orig_interval=min_f,\n new_interval=interval_str)\n\n if method is not None:\n df = timeseries.resample_timeseries(ts=df, method=method,\n interval_str=interval_str)\n\n # If not given selection_data, use the last weather values.\n if selection_data is None:\n selection_data = df.iloc[-1][['temperature', 'ghi']]\n\n # If not given prediction_time, infer it from the end of the index.\n if prediction_datetime is None:\n prediction_datetime = df.index[-1]\n\n if timeseries.is_weekday(prediction_datetime):\n df_dow = timeseries.filter_by_weekday(df)\n else:\n df_dow = timeseries.filter_by_weekend(df)\n\n # Filter data by time. Start by getting some time ranges.\n t = prediction_datetime.time()\n td = timedelta(minutes=CONFIG['load_model']['filtering_interval_minutes'])\n t_start = utils.add_timedelta_to_time(t=t, td=-td)\n t_end = utils.add_timedelta_to_time(t=t, td=td)\n df_dow_t = timeseries.filter_by_time(t_start=t_start, t_end=t_end,\n data=df_dow)\n\n # Now that our data's ready, let's perform the fit.\n output = zip.get_best_fit_from_clustering(\n data=df_dow_t, zip_fit_inputs={'v_n': FIT_NOMINAL_VOLTAGE},\n selection_data=selection_data\n )\n\n return output\n\ndef get_data_for_load (gdfl_kwargs):\n # Get the data from sensor-service, manipulate it, and return\n measmrid = gdfl_kwargs['meas_data']['meas_mrid']\n start_time = gdfl_kwargs['starttime']\n end_time = gdfl_kwargs['endtime']\n simulation_id = gdfl_kwargs['sim_id']\n platform_manager = gdfl_kwargs['platform_manager']\n data = platform_manager.get_simulation_output(\n simulation_id=simulation_id,\n query_measurement='gridappsd-sensor-simulator',\n measurement_mrid=measmrid.tolist(), index_by_time=False,\n starttime=start_time, endtime=end_time\n )\n # Call the Queue private method here\n result = _drop_merge_group (gdfl_kwargs['meas_data'], data)\n data = transform_data_for_load(result)\n return data\n\n# noinspection SpellCheckingInspection\ndef get_data_and_fit(gdfl_kwargs, ffl_kwargs):\n \"\"\"Get data via get_data_for_load, perform ZIP fit via fit_for_load.\n\n :param gdfl_kwargs: Keyword arguments to pass to get_data_for_load.\n :param ffl_kwargs: Keyword arguments to pass to fit_for_load, except\n load_data. The load_data comes from get_data_for_load.\n\n :returns: result from calling fit_for_load. See that docstring for\n more details.\n \"\"\"\n # Get data.\n load_data = get_data_for_load(gdfl_kwargs)\n\n # Perform the fit for this load and return.\n return fit_for_load(load_data=load_data, **ffl_kwargs)\n\n\ndef _get_data_and_fit_worker(input_queue, output_queue, logging_queue):\n \"\"\"Method designed to be used with threading/multiprocessing to run\n get_data_and_fit.\n\n :param input_queue: Multiprocessing.JoinableQueue instance. The\n objects in the queue should be dictionaries with three fields:\n 'gdfl_kwargs,' 'ffl_kwargs,' and 'load_name'. gdfl_kwargs and\n ffl_kwargs will be passed to get_data_and_fit. Putting None in\n the queue is used as the termination signal for the worker,\n causing this method to return.\n :param output_queue: Multiprocessing.Queue instance. The output from\n calling get_data_and_fit will be placed in the output_queue.\n Note that a 'load_name' field will also be added.\n :param logging_queue: Multiprocessing.Queue instance. Dictionaries\n with the following fields will be placed into this queue:\n - load_name: Name of the load in question.\n - time: Total time to get data and perform the ZIP fit.\n - clusters: Number of clusters used in the fitting.\n - data_samples: Number of data samples used to create the fit.\n - sol: scipy.optimize.OptimizeResult object.\n\n :returns: None\n \"\"\"\n # Initialize a PlatformManager.\n platform_manager = PlatformManager()\n\n # Loop until the termination signal is received.\n while True:\n # Grab data from the queue.\n d = input_queue.get(block=True, timeout=None)\n\n # None is the termination signal.\n if d is None:\n return\n\n # Do the work.\n t0 = time.time()\n result = get_data_and_fit(\n gdfl_kwargs={'platform_manager': platform_manager,\n **d['gdfl_kwargs']},\n ffl_kwargs=d['ffl_kwargs'])\n t1 = time.time()\n\n # Dump information into the logging queue.\n logging_queue.put({'load_name': d['load_name'],\n 'time': t1 - t0, 'clusters': result['k'],\n 'data_samples': result['data_len'],\n 'sol': result['sol']})\n\n # Add a load_name field to the result.\n result['load_name'] = d['load_name']\n\n # Put the result in the output queue.\n output_queue.put(result)\n\n # Mark task as complete.\n input_queue.task_done()\n\n\ndef _logging_worker(logging_queue):\n \"\"\"Method to do the logging for _get_data_and_fit_worker. This\n should be used with a thread.\n\n :param logging_queue: Multiprocessing.Queue object, which will have\n dictionaries put in it by _get_data_and_fit_worker. For a full\n description of the fields, check that function's docstring and\n code. A None input will be the termination signal.\n\n :returns: None\n \"\"\"\n\n # Loop.\n while True:\n d = logging_queue.get(block=True, timeout=None)\n\n # None is the termination signal.\n if d is None:\n return\n\n # Log.\n if d['sol'].success:\n # TODO: Should this be debug instead of info?\n LOG.info('Fit for load {} complete in {:.2f} seconds, including '\n 'data retrieval from the platform.'\n .format(d['load_name'], d['time']))\n else:\n # Warn on failure.\n LOG.warning('Fit for load {} FAILED. Solver status: {}. Solver'\n ' message: {}'.format(d['load_name'], d['sol'].status,\n d['sol'].message))\n\n # Add detailed debugging information.\n LOG.debug('Fit details for load {}:\\n\\tNumber of clusters: {}'\n '\\n\\tNumber of data samples: {}\\n\\tOptimizeResult:\\n{}'\n .format(d['load_name'], d['clusters'], d['data_samples'],\n str(d['sol'])))\n\n # That's all, folks.\n","repo_name":"GRIDAPPSD/pyvvo","sub_path":"pyvvo/load_model.py","file_name":"load_model.py","file_ext":"py","file_size_in_byte":34656,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"35"} +{"seq_id":"10902804796","text":"from flask import Flask, render_template, request, jsonify\r\nfrom main import ice_breaker\r\n\r\napp=Flask(__name__)\r\n\r\n@app.route(\"/process\", methods=['POST'])\r\ndef process():\r\n name =request.form['name']\r\n person_info, profile_pic_url=ice_breaker(name=name)\r\n\r\n\r\n return jsonify({\"summary\":person_info.summary,\r\n \"interests\":person_info.topics_of_interest,\r\n \"facts\":person_info.facts,\r\n \"ice_breaker\":person_info.ice_breakers,\r\n \"profile_picture\":profile_pic_url})\r\n\r\n\r\nif __name__==\"main\":\r\n app.run(host=\"0.0.0.0\", debug=True)\r\n","repo_name":"lakshitgosain/LangChain-LinkedinProject","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"71659458980","text":"import cv2\r\nimport numpy as np\r\nimport os\r\nfrom keras_preprocessing.image import img_to_array, ImageDataGenerator\r\n\r\n#Pętla po zdjęciach w danym folderze:\r\nfor filename in os.listdir('/Users/kubab/PycharmProjects/ProjektInd/Domino/'):\r\n filename2=('/Users/kubab/PycharmProjects/ProjektInd/Domino/' + filename)\r\n\r\n#OPERACJA NR 1 : BLUR.\r\n img = cv2.imread(filename2)\r\n rows, cols, ch = img.shape\r\n#ZAKRES OZNACZA ZARÓWNO ILOŚĆ POWSTAŁYCH NOWYCH ZDJĘĆ\r\n#JAK RÓWNIEŻ POZIOM WPROWADZANYCH ZNIEKSZTAŁCEŃ\r\n for i in range(3,10):\r\n blur = cv2.blur(img, (i*1, i*1))\r\n cv2.imwrite('/Users/kubab/PycharmProjects/ProjektInd/obrot/blur'+i.__str__()+filename, blur)\r\n\r\n#INICJALIZACJA ZMIENNYCH POTRZEBNYCH DO DALSZYCH OPERACJI\r\n data = img_to_array(img)\r\n samples = np.expand_dims(data, 0)\r\n datagen = ImageDataGenerator(brightness_range=[0.2, 1.7])\r\n datagenZ = ImageDataGenerator(zoom_range=[0.6, 1.1])\r\n it = datagen.flow(samples, batch_size=1)\r\n itZ = datagenZ.flow(samples, batch_size=1)\r\n datagenR = ImageDataGenerator(rotation_range=75)\r\n itR = datagenR.flow(samples, batch_size=1)\r\n\r\n#pĘTLA WYKONUJĄCA OPERACJĘ NR 2 - ZMIANE JASNOŚCI\r\n#ZAKRES OZNACZA ILOŚĆ POWSTAŁYCH ZDJĘĆ\r\n for i in range(8):\r\n batch = it.next()\r\n image = batch[0].astype('uint8')\r\n cv2.imwrite('/Users/kubab/PycharmProjects/ProjektInd/obrot/light' + i.__str__() + filename, image)\r\n\r\n# PĘTLA WYKONUJĄCA OPERACJĘ NR 3 - ZOOM\r\n# ZAKRES OZNACZA ILOŚĆ POWSTAŁYCH ZDJĘĆ\r\n for i in range(10):\r\n batchZ = itZ.next()\r\n # convert to unsigned integers for viewing\r\n imageZ = batchZ[0].astype('uint8')\r\n # plot raw pixel data\r\n cv2.imwrite('/Users/kubab/PycharmProjects/ProjektInd/obrot/zoom' + i.__str__() + filename, imageZ)\r\n\r\n# PĘTLA WYKONUJĄCA OPERACJĘ NR 3 - ZOOM\r\n# ZAKRES OZNACZA ILOŚĆ POWSTAŁYCH ZDJĘĆ\r\n for i in range(10):\r\n # generate batch of images\r\n batchR = itR.next()\r\n # convert to unsigned integers for viewing\r\n imageR = batchR[0].astype('uint8')\r\n cv2.imwrite('/Users/kubab/PycharmProjects/ProjektInd/obrot/rotC' + i.__str__() + filename, imageR)\r\n\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()\r\n","repo_name":"JakubBelka/FaceRecognition","sub_path":"Data_aug.py","file_name":"Data_aug.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"pl","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"37060604209","text":"import random\nimport csv \nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\ndef preprocess(paths):\n \n images = []\n steering_measurements = []\n lines = []\n correction = .2\n for path in paths: \n with open(path) as csvfile:\n reader = csv.reader(csvfile)\n for line in reader:\n lines.append(line)\n \n \n \n i = 0\n j = 0\n\n REGION_15_17 = 0\n for line in lines :\n j += 1\n if (abs(float(line[3])) <= 0.0001):\n i += 1\n \n if(i%24):\n continue\n \n \n \n elif (abs(float(line[3])) > 0.135 and abs(float(line[3])) < 0.18):\n REGION_15_17 +=1 \n if (REGION_15_17 % 4):\n continue\n \n# print(line[0])\n# print(line[1])\n# print(line[2])\n center_image = cv2.imread(line[0])\n center_image = cv2.cvtColor(center_image,cv2.COLOR_BGR2RGB)\n left_image = cv2.imread(line[1])\n left_image = cv2.cvtColor(left_image,cv2.COLOR_BGR2RGB)\n right_image = cv2.imread(line[2])\n right_image = cv2.cvtColor(right_image,cv2.COLOR_BGR2RGB)\n \n# cv2.imshow(\"center\",center_image)\n# cv2.imshow(\"left\",left_image)\n# cv2.imshow(\"right\",right_image)\n# cv2.waitKey(0)\n# \n images.append(center_image)\n steering_measurements.append(float(line[3]))\n \n\n images.append(left_image)\n steering_measurements.append(float(line[3]) + correction)\n \n images.append(right_image)\n steering_measurements.append(float(line[3]) - correction)\n \n \n images.append(np.fliplr(center_image))\n steering_measurements.append(float(line[3]) * -1)\n\n images.append(np.fliplr(left_image))\n steering_measurements.append(float(line[3]) * -1 - correction)\n\n images.append(np.fliplr(right_image))\n steering_measurements.append(float(line[3]) * -1 + correction)\n\n plt.figure()\n plt.hist(steering_measurements, bins=50)\n plt.title(\"Training dataset Steering command Histogram\")\n plt.xlabel(\"Value\")\n plt.ylabel(\"Frequency\")\n plt.savefig(r'./data_histogram.png')\n plt.show('Training dataset Steering command Histogram.png')\n\n X_train = np.array(images)\n Y_train = np.array(steering_measurements)\n \n \n return X_train, Y_train\n\n\ndef filter(X = [], Y = [] , number_of_items = 500, number_of_pins = 20):\n \n\n dataset = list(zip(X, Y))\n \n random.shuffle(dataset)\n \n X_filtered, Y_filtered = zip(*dataset)\n X_filtered = list(X_filtered)\n Y_filtered = list(Y_filtered)\n \n \n max_val = max(Y_filtered)\n \n offset = max_val/number_of_pins\n #print (\"offset = \"+ str(offset))\n number_of_items_list = [0] * (number_of_pins + 1)\n \n number_of_deleted_items = 0\n for i in range(len(Y_filtered)) :\n temp_offset = 0;\n i = i - number_of_deleted_items\n for j in range(number_of_pins + 1):\n temp_offset +=offset\n #print(\"temp_offset = \"+ str(temp_offset))\n #print(\"size of len(Y_filtered) = \"+ str(len(Y_filtered))+ \"i = \"+ str(i))\n if(abs(Y_filtered[i]) <= temp_offset):\n if(number_of_items_list[j] >= number_of_items):\n del X_filtered[i]\n del Y_filtered[i]\n number_of_deleted_items += 1\n else:\n number_of_items_list[j] +=1\n break\n #print (number_of_items_list) \n #for i in range(len(X_filtered)):\n #cv2.imshow(\"img\",X_filtered[i])\n #print(Y_filtered[i])\n #cv2.waitKey(0)\n \n \n \n return np.array(X_filtered),np.array(Y_filtered)\n\n \n\nif __name__ == '__main__':\n\n dataset_paths = []\n dataset_paths.append(r'./driving_log.csv')\n #train_generator = generator.dataset_generator(paths = dataset_paths, correction = 0.15, batch_size=250)\n \n print(\"Dataset Preprocessing ....\")\n X_train , Y_train = preprocess(dataset_paths)\n \n #X_train = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5]\n #Y_train = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5]\n \n #print (X_train)\n #Y_train = range(1,20)\n x_out, y_out =filter(X_train,Y_train , number_of_items=1000)\n \n plt.figure()\n plt.hist(y_out, bins=50)\n plt.title(\"Training dataset Steering command Histogram\")\n plt.xlabel(\"Value\")\n plt.ylabel(\"Frequency\")\n plt.savefig(r'./data_histogram.png')\n plt.show('Training dataset Steering command Histogram.png')\n\n print(\"Dataset Preprocessing Done!\")\n ","repo_name":"SamerSaber/CarND-Behavioral-Cloning-P3_Solution","sub_path":"dataset_preparator.py","file_name":"dataset_preparator.py","file_ext":"py","file_size_in_byte":4675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"35113025380","text":"#Sort the following string alphabetically, from z to a, and assign it to the variable sorted_letters.\n\n\nletters = \"alwnfiwaksuezlaeiajsdl\"\nsorted_letters = sorted(letters, reverse = True) \n\n#sorted function expects a sequence ,but we have passed a string ,so it will convert it into a list whose elements are character of the string, letters.\n\n\nprint(sorted_letters)\n","repo_name":"github-mohsinalam/Python","sub_path":"Sorting/sorted_letters.py","file_name":"sorted_letters.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"30404137250","text":"import numpy as np\nimport scipy.ndimage as ni\n\nfrom matplotlib.figure import Figure\nfrom mpl_toolkits.axes_grid1 import Grid\n\n# slit_length_arcsec = 10.\n\n\ndef _rebin(x, y, bins):\n bx, _ = np.histogram(x, bins=bins, weights=y)\n bn, _ = np.histogram(x, bins=bins)\n\n return 0.5 * (bins[:-1] + bins[1:]), bx / bn\n\n\ndef _measure_height_width(xxm, yym, bg_percentile=50):\n\n bg = np.nanpercentile(yym, bg_percentile)\n\n yym = yym - bg\n yym[yym < 0] = 0.\n\n max_indx = np.argmax(yym)\n max_x = xxm[max_indx]\n height = yym[max_indx]\n\n # height_mask = yym > 0.5 * height\n # weighted_x = np.sum(xxm[height_mask] * yym[height_mask]) \\\n # / np.sum(yym[height_mask])\n\n bin_dx = xxm[1:] - xxm[:-1]\n bin_height = .5 * (yym[1:] + yym[:-1])\n equivalent_width = np.sum(bin_height * bin_dx) / height\n\n return bg, max_x, height, equivalent_width\n\n\ndef do_ql_stellar(hdu, calib):\n\n order_map = calib.order_map\n ap = calib.ap\n\n slit_length_arcsec = calib.slit_length_arcsec\n\n inimage = hdu\n\n # TODO : should include destriping here\n\n min_order = order_map[order_map > 0].min()\n max_order = order_map.max()\n\n yi, xi = np.indices(inimage.data.shape)\n\n x1, x2 = 1024 - 200, 1024 + 200\n xmask = (x1 < xi) & (xi < x2)\n\n smoothed_profiles = []\n\n for o in range(min_order + 2, max_order - 2):\n # o = 112\n\n omask = order_map == o\n msk = omask & xmask\n\n yc = ap(o, ap.xi, 0.5)\n yh = np.abs(ap(o, ap.xi, 0.) - ap(o, ap.xi, 1.))\n # yic = np.ma.array((yi - yc), mask=~msk).filled(np.nan)\n\n xx, yy = ((yi - yc) / yh)[msk], inimage.data[msk]\n indx = np.argsort(xx)\n\n slit_length_in_pixel = yh[int(len(yh)*0.5)]\n\n xxm = xx[indx]\n n = int(len(xxm) / 100.)\n yym = ni.median_filter(yy[indx], n)\n\n r = dict(x=xxm, y=yym,\n smoothing_length=n,\n slit_length_arcsec=slit_length_arcsec)\n\n smoothed_profiles.append((o, r))\n\n per_order = dict(slit_length_arcsec=slit_length_arcsec)\n\n l = per_order[\"50%\"] = []\n\n for o, xy in smoothed_profiles:\n\n xxm, yym = xy[\"x\"], xy[\"y\"]\n n = xy[\"smoothing_length\"]\n\n r = dict(x_sampled=xxm[::n],\n y_sampled=yym[::n])\n\n (bg, max_x, height,\n equivalent_width) = _measure_height_width(xxm, yym, 50)\n\n r.update(bg=bg,\n height=height,\n equivalent_width=equivalent_width,\n slit_length_in_pixel=slit_length_in_pixel)\n\n l.append((o, r))\n\n bins = np.linspace(-0.5, 0.5, 128)\n\n ww = []\n for o, xy in smoothed_profiles:\n\n xxm, yym = xy[\"x\"], xy[\"y\"]\n _, w = _rebin(xxm, yym, bins)\n ww.append(w)\n\n ww0 = np.array(ww).sum(axis=0)\n\n bins0 = 0.5 * (bins[1:] + bins[:-1])\n (bg, max_x, height,\n equivalent_width) = _measure_height_width(bins0, ww0, 50)\n\n stacked = dict(slit_length_arcsec=slit_length_arcsec)\n\n r = dict(bg=bg, max_x=max_x * slit_length_arcsec,\n height=height,\n equivalent_width=equivalent_width * slit_length_arcsec,\n xx=bins0 * slit_length_arcsec, yy=ww0)\n\n stacked[\"50%\"] = r\n\n return dict(smoothed_profiles=smoothed_profiles,\n stacked=stacked,\n per_order=per_order)\n\n\ndef do_figure_stacked_profile(jo, calib, fig=None):\n\n stacked = jo[\"stacked\"][\"50%\"]\n\n if fig is None:\n fig = Figure(figsize=(4, 4))\n\n ax1 = fig.add_subplot(111)\n\n ax1.axhline(0, color=\"0.8\", ls=\"--\")\n ax1.plot(stacked[\"xx\"], stacked[\"yy\"] - stacked[\"bg\"])\n\n ax1.errorbar([stacked[\"max_x\"]], [.5*stacked[\"height\"]],\n xerr=.5*stacked[\"equivalent_width\"],\n yerr=.5*stacked[\"height\"])\n\n ax1.set_xlabel(\"slit length\")\n ax1.set_ylabel(\"count / pixel\")\n ax1.tick_params(labelleft=False)\n\n return fig\n\n\ndef do_figure_profile_per_order(jo, calib, fig=None):\n\n # smoothed_profiles = jo[\"smoothed_profiles\"]\n stats = jo[\"per_order\"][\"50%\"]\n\n slit_length_arcsec = calib.slit_length_arcsec\n\n if fig is None:\n fig = Figure(figsize=(8, 4))\n\n ax1 = fig.add_subplot(111)\n\n bins = np.linspace(-0.5, 0.5, 128)\n\n for o, k in stats:\n bin_center, w = _rebin(k[\"x_sampled\"], k[\"y_sampled\"], bins)\n m = np.isfinite(w)\n ax1.plot(bin_center[m] * slit_length_arcsec,\n w[m] - k[\"bg\"], \"-\", label=o)\n\n ax1.set_xlabel(\"slit length\")\n ax1.set_ylabel(\"count / pixel\")\n\n return fig\n\n\ndef do_figure_stat_per_order(jo, calib, fig=None):\n\n # smoothed_profiles = jo[\"smoothed_profiles\"]\n stats = jo[\"per_order\"][\"50%\"]\n\n slit_length_arcsec = calib.slit_length_arcsec\n\n if fig is None:\n fig = Figure(figsize=(8, 4))\n\n grid = Grid(fig, 111, (3, 1), share_y=False, axes_pad=0.15)\n\n ax31 = grid[0]\n ax32 = grid[1]\n ax33 = grid[2]\n\n for o, k in stats:\n ax31.plot(o, k[\"height\"], \"o\")\n\n bg_line, = ax31.plot([o for (o, _) in stats],\n [_[\"bg\"] for (o, _) in stats], color=\"0.8\",\n ls=\"--\")\n ax31.legend([bg_line], [\"background\"], loc=1)\n\n for o, k in stats:\n ax32.plot(o, k[\"equivalent_width\"] * slit_length_arcsec, \"o\")\n\n for o, k in stats:\n v = (k[\"height\"] * k[\"equivalent_width\"]\n * k[\"slit_length_in_pixel\"] * 3.5)\n ax33.plot(o, v**.5, \"o\")\n\n ax33.set_xlabel(\"order number\")\n\n ax31.set_ylabel(\"peak count\\n/ piexl\")\n ax32.set_ylabel(\"FWHM [\\\"]\")\n ax33.set_ylabel(\"(total counts\\nper RE)^1/2\")\n\n return fig\n\n\n__all__ = [\"do_ql_stellar\",\n \"do_figure_stacked_profile\",\n \"do_figure_profile_per_order\", \"do_figure_stat_per_order\"]\n\n\nif __name__ == \"__main__\":\n class Calib(object):\n def __init__(self, band, slit_length_arcsec):\n\n self.slit_length_arcsec = slit_length_arcsec\n\n from load_calib import get_calibs\n\n ap, order_map, slitposmap = get_calibs(band)\n self.ap = ap\n self.order_map = order_map[0].data\n self.slitposmap = slitposmap[0]\n\n band = \"K\"\n calib = Calib(band, 10.)\n\n import astropy.io.fits as pyfits\n fn = \"/media/igrins128/jjlee/igrins/20170903/SDCK_20170903_0151.fits\"\n f = pyfits.open(fn)\n r = do_ql_stellar(f[0], calib)\n\n import matplotlib.pyplot as plt\n if 1:\n fig = plt.figure(figsize=(5, 4))\n fig.subplots_adjust(wspace=0.3)\n\n do_figure_stacked_profile(r, calib, fig=fig)\n\n if 1:\n fig = plt.figure(figsize=(5, 4))\n do_figure_profile_per_order(r, calib, fig=fig)\n\n if 1:\n fig = plt.figure(figsize=(5, 4))\n do_figure_stat_per_order(r, calib, fig=fig)\n\n plt.show()\n","repo_name":"leejjoon/igr-ql-py","sub_path":"quicklook_stellar.py","file_name":"quicklook_stellar.py","file_ext":"py","file_size_in_byte":6738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"31305631576","text":"import pandas as pd\nfrom sklearn.cluster import AgglomerativeClustering\nimport numpy as np\nfrom scipy.cluster.hierarchy import dendrogram\nimport matplotlib.pyplot as plt\nfrom plotly.tools import FigureFactory as FF\nfrom scipy.cluster.hierarchy import linkage\nimport plotly.plotly as py\n\ndef plot_dendrogram(model, **kwargs):\n children = model.children_\n distance = np.arange(children.shape[0])\n no_of_observations = np.arange(2, children.shape[0] + 2)\n linkage_matrix = np.column_stack([children, distance, no_of_observations]).astype(float)\n dendrogram(linkage_matrix, **kwargs)\n\ndef min_max(x):\n # Formula for min-max normalization : (by discount price)\n # newvalue= (max'-min')/(max-min)*(value-max)+max'\n max_x = x.max()\n min_x = x[x != -1].min()\n x = x.apply(lambda v: -1 if np.isnan(v) else\n (100-0)/(max_x-min_x)*(v-max_x)+100)\n\n return x\n\nif __name__ == \"__main__\":\n df = pd.read_csv(\"Hotels_data_Changed.csv\")\n df.set_index('Unnamed: 0', inplace=True)\n new_df = df.groupby('Hotel Name')['Hotel Name'].count().reset_index(name='count').\\\n sort_values(['count'], ascending=False).head(150)\n new_df = pd.merge(new_df[['Hotel Name']], df, on='Hotel Name', how='left')\n\n new_df_1 = new_df.groupby('Checkin Date')['Checkin Date'].count().reset_index(name='count_checkin').\\\n sort_values(['count_checkin'],ascending=False).head(40)\n\n new_df_1 = pd.merge(new_df_1[['Checkin Date']], new_df, on='Checkin Date', how='left')\n\n se = new_df_1.groupby(['Hotel Name', 'Checkin Date', 'Discount Code'])['Discount Price'].min()\n new_df_2 = pd.DataFrame(se)\n new_df_2.reset_index(inplace=True)\n\n new_df_2['Checkin and code'] = new_df_2['Checkin Date'].astype(str) + ' && ' + new_df_2['Discount Code'].astype(str)\n\n new_df_3 = new_df_2.pivot(index='Hotel Name', columns='Checkin and code', values='Discount Price')\n\n new_df_3.columns.name = None\n new_df_3 = new_df_3.apply(min_max,axis=1).fillna(-1)\n #new_df_3.reset_index(inplace=True)\n\n new_df_3.to_csv(\"Hotels_data_for_clustering.csv\")\n\n ## Put in a new file!!!\n\n model = AgglomerativeClustering(n_clusters=4, compute_full_tree=False)\n model = model.fit(new_df_3.head(20)) # Remove the head!!\n plt.title('Hierarchical Clustering Dendrogram')\n plot_dendrogram(model, labels=model.labels_)\n plt.show()\n\n ##figure = FF.create_dendrogram(model, orientation='bottom', labels=model.labels_, linkagefun=lambda x: linkage(model, 'ward', metric='euclidean'))\n ##figure = FF.create_dendrogram(new_df_3, orientation='bottom',linkagefun=lambda x: linkage(new_df_3, 'ward', metric='euclidean'))\n ##py.iplot(figure, filename='dendrogram_with_labels')\n\n\n\n\n\n","repo_name":"tsyael/DS-Final-Project","sub_path":"Step3.py","file_name":"Step3.py","file_ext":"py","file_size_in_byte":2719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"21056815077","text":"#!/usr/bin/python3\n\"\"\" write a function that adds 2 integers\"\"\"\n\n\ndef add_integer(a, b=98):\n \"\"\" display a message if there is an error otherwise add a + b\"\"\"\n if not isinstance(a, int) and not isinstance(a, float):\n raise TypeError(\"a must be an integer\")\n elif not isinstance(b, int) and not isinstance(b, float):\n raise TypeError(\"b must be an integer\")\n else:\n return int(a) + int(b)\n","repo_name":"rania3103/holbertonschool-higher_level_programming","sub_path":"python-test_driven_development/0-add_integer.py","file_name":"0-add_integer.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"39966632639","text":"from flask import Flask, request, jsonify\nfrom flask_restplus import Resource, Api\n\nimport logging.config\nlogging.config.fileConfig(fname='SwaggerExample/ExternalLogger/file.conf', disable_existing_loggers=False)\nlogger = logging.getLogger('sLogger')\n\n\n\napp = Flask(__name__) # Create a Flask WSGI application\napi = Api(app) # Create a Flask-RESTPlus API\n\ntasks = [\n {\n 'id': 1,\n 'title': u'Shopping book',\n 'description': u'shop a book for cooking with Milk, Cheese, Pizza, Fruit, Oil',\n 'done': False\n },\n {\n 'id': 2,\n 'title': u'Reading book after purchase',\n 'description': u'Find a book I like and Read',\n 'done': False\n }]\n\n@api.route('/simpleGet') # Create a URL route to this resource\nclass HelloWorld(Resource): # Create a RESTful resource\n def get(self): # Create GET endpoint\n myName = 'Yuntao'\n logger.info('| Sender = %s | RequestType = %s | Request = %s | Response = %s' % (\n myName, 'GET', 'GetRequest', {'tasks': tasks}))\n print(\" program name is %s\",__name__)\n return {'hello': 'world', 'name':myName, 'errors': {'per_page': 'results not found'}}\n\n@api.route('/simplePost/')\nclass HelloWorldPost(Resource): # Create a RESTful resource\n def post(self, senderName):\n message = jsonify({'tasks': tasks})\n thisRequest = request.json\n logger.info('| Sender = %s | RequestType = %s | Request = %s | Response = %s' % ( senderName, 'POST', thisRequest,{'tasks':tasks}) )\n return jsonify({'tasks':tasks})\n\n\nclass TestingFunc:\n def __init__(self,x,y):\n self.x = x\n self.y = y\n self.multi=0\n def getMultiple(self):\n self.multi = self.x * self.y\n return self.multi\n\n\n\nif __name__ == '__main__':\n app.run(debug=True) # Start a development server","repo_name":"liuyuntao-geek-hub/MicroServiceWithSwagger","sub_path":"SwaggerExample/SwaggerExample/simple.py","file_name":"simple.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"30365428239","text":"import functools\nimport math\nfrom time import sleep\nfrom piui import PiUi\n\nglobal flightMode\nflightMode = 0\nglobal squibDeployed\nsquibDeployed = 0\n\nclass RocketPiUi(object):\n\n def __init__(self):\n self.title = None\n self.txt = None\n self.img = None\n self.ui = PiUi()\n\n def main_page(self):\n self.page = self.ui.new_ui_page(title=\"VC Rocketry Live Update\")\n\n self.page.add_textbox(\"Location\", \"h1\")\n update1 = self.page.add_textbox(\"0.0, 0.0\", \"p\")\n self.page.add_element(\"hr\")\n\n self.page.add_textbox(\"Speed and Acceleration\", \"h1\")\n update2 = self.page.add_textbox(\"Speed: 0.0, Acceleration: 0.0\", \"p\")\n self.page.add_element(\"hr\")\n\n self.page.add_textbox(\"Rocket Mode\", \"h1\")\n update3 = self.page.add_textbox(\"Prechecks\")\n self.page.add_element(\"hr\")\n\n self.page.add_textbox(\"Squib Status\", \"h1\")\n update4 = self.page.add_textbox(\"Not Deployed\")\n self.page.add_element(\"hr\")\n\n self.page.add_textbox(\"9 Volt Current Flowing\", \"h1\")\n update5 = self.page.add_textbox(\"False\")\n self.page.add_element(\"hr\")\n\n for i in range(0, 50):\n # latitude = frame[-1][\"latitude\"]\n # longitude = frame[-1][\"longitude\"]\n # speed = frame[-1][\"speed\"]\n # acceleration = math.sqrt((frame[-1][\"a_x\"]*9.81)**2 + (frame[-1][\"a_y\"]*9.81)**2 + (frame[-1][\"a_z\"]*9.81)**2)\n # global flightMode\n # global squibDeployed\n # current = frame[-1][\"current_1\"]\n\n # This is dummy data, remove these varibales and uncomment the ones above for real testing\n # You will, of course, have to remove this code from the for loop\n flightMode = i\n squibDeployed = i\n x = float(i)\n latitude = x\n longitude = x\n speed = x\n acceleration = x\n current = x\n\n update1.set_text(str(latitude) + \", \" + str(longitude))\n\n update2.set_text(\"Speed: \" + str(speed) + \" ft/s\" + \", Acceleration: \" + str(acceleration) + \" m/s^2\")\n\n if flightMode == 0:\n update3.set_text(\"Pre-Check 1\")\n elif flightMode == 1:\n update3.set_text(\"Pre-Check 2\")\n elif flightMode == 2:\n update3.set_text(\"Flight\")\n elif flightMode == 3:\n update3.set_text(\"Descent\")\n elif flightMode == 4:\n update3.set_text(\"Recovery\")\n\n if squibDeployed == 1:\n update4.set_text(\"Deployed\")\n\n if (current > 0.0):\n update5.set_text(\"True\")\n else:\n update5.set_text(\"False\")\n sleep(1)\n\n self.ui.done()\n\n def main(self):\n self.main_page()\n self.ui.done()\n\ndef main():\n piui = RocketPiUi()\n piui.main()\n\nif __name__ == '__main__':\n main()\n\n# for i in range(0, 50):\n# # latitude = frame[-1][\"latitude\"]\n# # longitude = frame[-1][\"longitude\"]\n# # speed = frame[-1][\"speed\"]\n# # acceleration = math.sqrt((frame[-1][\"a_x\"]*9.81)**2 + (frame[-1][\"a_y\"]*9.81)**2 + (frame[-1][\"a_z\"]*9.81)**2)\n# # global flightMode\n# # global squibDeployed\n# # current = frame[-1][\"current_1\"]\n# x = float(i)\n# latitude = x\n# longitude = x\n# speed = x\n# acceleration = x\n# current = x\n#\n# update1.set_text(str(latitude) + \", \" + str(longitude))\n#\n# update2.set_text(\"Speed: \" + str(speed) + \" ft/s\" + \", Acceleration: \" + str(acceleration) + \" m/s^2\")\n#\n# if flighMode == 0:\n# update3.set_text(\"Pre-Check 1\")\n# elif flighMode == 1:\n# update3.set_text(\"Pre-Check 2\")\n# elif flighMode == 2:\n# update3.set_text(\"Flight\")\n# elif flighMode == 3:\n# update3.set_text(\"Descent\")\n# elif flighMode == 4:\n# update3.set_text(\"Recovery\")\n#\n# if squibDeployed == 1:\n# update4.set_text(\"Deployed\")\n#\n# if (current > 0.0):\n# update5.set_text(\"True\")\n# else:\n# update5.set_text(\"False\")\n# sleep(1)\n","repo_name":"raghav-kapoor/VC-Rocketry","sub_path":"testing/piui/DummyDataDisplay.py","file_name":"DummyDataDisplay.py","file_ext":"py","file_size_in_byte":4126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"11951894073","text":"import os\nimport uuid\nimport time\nimport logging\nimport shutil\nfrom arjuna import ArjunaOption\n\n\nfrom arjuna.tpi.config import Configuration\n\nfrom arjuna.configure.configurator import TestConfigurator\nfrom arjuna.drive.invoker.databroker import TestSessionDataBrokerHandler\nfrom arjuna.interact.gui.gom.guimgr import GuiManager\n\nclass TestSessionController:\n \n def __init__(self):\n self.__id = uuid.uuid4()\n self.__DEF_CONF_NAME = \"ref\"\n self.__default_ref_config = None\n self.__config_map = {}\n self.__cli_central_config = None\n self.__cli_test_config = None\n self.__configurator = None\n self.__project_config_loaded = False\n self.__guimgr = None\n self.__session = None\n\n @property\n def id(self):\n return self.__id\n\n @property\n def configurator(self):\n return self.__configurator\n\n @property\n def data_broker(self):\n return self.__data_broker \n\n @property\n def gui_manager(self):\n return self.__guimgr\n\n def init(self, root_dir, cli_config=None, run_id=None):\n self.__configurator = TestConfigurator(root_dir, cli_config, run_id)\n ref_config = self.__configurator.ref_config\n data_env_confs = self.__configurator.file_confs\n self.__guimgr = GuiManager(ref_config)\n ref_conf = self.__create_config(ref_config)\n self.__add_to_map(ref_conf)\n for run_env_conf in [self.__create_config(econf, name=name) for name, econf in data_env_confs.items()]:\n self.__add_to_map(run_env_conf)\n\n def get_src_file_path(src):\n return os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), src))\n\n def get_proj_target_path(dest):\n return os.path.join(ref_conf.value(ArjunaOption.PROJECT_ROOT_DIR), dest)\n\n def copy_file(src, dest):\n shutil.copyfile(get_src_file_path(src), get_proj_target_path(dest))\n\n f = open(get_src_file_path(\"../res/conftest.txt\"), \"r\")\n contents = f.read().format(project=ref_conf.value(ArjunaOption.PROJECT_NAME))\n f.close()\n f = open(get_proj_target_path(\"test/conftest.py\"), \"w\")\n f.write(contents)\n f.close()\n\n return ref_conf\n\n def __msession_config(self, ref_conf_name):\n from arjuna import Arjuna\n if ref_conf_name is None:\n ref_conf_name = \"ref\"\n return Arjuna.get_config(ref_conf_name)\n\n def load_tests(self, *, dry_run=False, ref_conf_name=None, rules=None):\n from arjuna import Arjuna\n from arjuna.engine.session import MagicTestSession, YamlTestSession\n \n session_name = Arjuna.get_config().value(ArjunaOption.RUN_SESSION_NAME).lower()\n if session_name == \"msession\":\n ref_config = self.__msession_config(ref_conf_name)\n self.__session = MagicTestSession(ref_config, dry_run=dry_run, rules=rules)\n else:\n self.__session = YamlTestSession(session_name, ref_conf_name, dry_run=dry_run)\n\n def load_tests_for_stage(self, *, stage_name, dry_run=False, ref_conf_name=None):\n ref_config = self.__msession_config(ref_conf_name)\n from arjuna.engine.session import MagicTestSessionForStage\n self.__session = MagicTestSessionForStage(stage_name, ref_config, dry_run=dry_run)\n\n def load_tests_for_group(self, *, group_name, dry_run=False, ref_conf_name=None):\n ref_config = self.__msession_config(ref_conf_name)\n from arjuna.engine.session import MagicTestSessionForGroup\n self.__session = MagicTestSessionForGroup(group_name, ref_config, dry_run=dry_run)\n\n def run(self):\n self.__session.run()\n\n def __create_config(self, config, name=None):\n config = Configuration(\n self,\n name and name or self.__DEF_CONF_NAME,\n config\n )\n return config\n\n def finish(self):\n pass\n\n def __add_to_map(self, config):\n from arjuna import Arjuna\n Arjuna.register_config(config)\n\n def load_options_from_file(self, fpath):\n return self.configurator.load_options_from_file(fpath)\n\n def register_config(self, name, arjuna_options, user_options, parent_config=None):\n config = self.configurator.register_new_config(arjuna_options, user_options, parent_config)\n conf = self.__create_config(config, name=name)\n self.__add_to_map(conf)\n return conf\n\n def create_file_data_source(self, record_type, file_name, *arg_pairs):\n response = self._send_request(\n ArjunaComponent.DATA_SOURCE,\n DataSourceActionType.CREATE_FILE_DATA_SOURCE,\n *arg_pairs\n )\n return response.get_data_source_id()\n\n def define_gui(self, automator, label=None, name=None, qual_name=None, def_file_path=None):\n return self.gui_manager.define_gui(automator, label=label, name=name, qual_name=qual_name, def_file_path=def_file_path)\n","repo_name":"VinodKumbar/arjuna","sub_path":"arjuna/engine/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":4954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"35"} +{"seq_id":"20830801283","text":"import socket\nfrom datetime import datetime\n# from System.IO import MemoryStream # Test mit MemoryStream. Wohl eleganteste Lösung\n\ns = socket.socket() # Socket Objekt. Übernimmt das Verbinden\nhost = 'Drohne' # Name des RasPi im Netzwerk. Funktioniert. Braucht prinzipiell keine stat. IP\nport = 5892 # Random Name\n\nloop = True\ns.connect((host, port))\n\nwhile loop:\n # Bilddatei in die die empfangenen Daten geschrieben werden # wb: write binary\n f = open('empfangen.bmp', 'wb')\n # m = MemoryStream()\n start = datetime.now() # Startzeit. Zeigt die Zeit zum empfangen eines Frames an\n\n # Sendet anforderung Bild zu senden. Wird weg müssen (Server wartet auf anforderung)\n s.send(str.encode('bild'))\n print(\"Empfängt\")\n size = s.recv(32) # Dateigröße empfangen. Bild ist gerade ein byte (sowas in der Art)\n size = int(size, 2) # konvertierung zu einer ganzen Zahl\n print('empfängt ' + str(size) + ' bytes daten')\n empfangen = size # Speichert die Dateigröße\n chunksize = 1024 # Wie viele Daten werden maximal empfangen. Sollte mit Buffer size im Bildserver übereinstimmen\n while size > 0: # Solange es noch Daten zum empfagnen gibt\n if size < chunksize: # Wenn weniger Daten übrig bleiben als die erwartete Blockgröße ist\n chunksize = size\n data = s.recv(chunksize) # Empfängt daten (max. chunksize)\n f.write(data) # Daten in Datei. Muss bald im Arbeitsspeicher passieren\n size -= len(data) # von den erwarteten Daten die Empfangenen abziehen\n # m.write(data)\n\n f.close() # Dateibearbeiten beenden\n diff = datetime.now() - start # Zeitdifferenz von Start zu jetzt\n print(str(empfangen / 1000) + \"KB Empfangen in \" + str((diff.microseconds / 1000)) + \" ms. \")\n loop = False # Loop variable, damit das Programm nach einem durchlauf beendet. Final wird das nicht mehr so sein\n","repo_name":"KoehlerT/Drohne","sub_path":"Basis/Steuerung_py/bildclient.py","file_name":"bildclient.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"40176441998","text":"from bbot.modules.base import BaseModule\n\n\nclass IP2Location(BaseModule):\n \"\"\"\n IP2Location.io Geolocation API.\n \"\"\"\n\n watched_events = [\"IP_ADDRESS\"]\n produced_events = [\"GEOLOCATION\"]\n flags = [\"passive\", \"safe\"]\n meta = {\"description\": \"Query IP2location.io's API for geolocation information. \", \"auth_required\": True}\n options = {\"api_key\": \"\", \"lang\": \"\"}\n options_desc = {\n \"api_key\": \"IP2location.io API Key\",\n \"lang\": \"Translation information(ISO639-1). The translation is only applicable for continent, country, region and city name.\",\n }\n scope_distance_modifier = 1\n _priority = 2\n suppress_dupes = False\n\n base_url = \"http://api.ip2location.io\"\n\n async def setup(self):\n await self.require_api_key()\n self.lang = self.config.get(\"lang\", \"\")\n return True\n\n async def ping(self):\n url = self.build_url(\"8.8.8.8\")\n r = await self.request_with_fail_count(url)\n resp_content = getattr(r, \"text\", \"\")\n assert getattr(r, \"status_code\", 0) == 200, resp_content\n\n def build_url(self, data):\n url = f\"{self.base_url}/?key={self.api_key}&ip={data}&format=json&source=bbot\"\n if self.lang:\n url = f\"{url}&lang={self.lang}\"\n return url\n\n async def handle_event(self, event):\n try:\n url = self.build_url(event.data)\n result = await self.request_with_fail_count(url)\n if result:\n geo_data = result.json()\n if not geo_data:\n self.verbose(f\"No JSON response from {url}\")\n else:\n self.verbose(f\"No response from {url}\")\n except Exception:\n self.verbose(f\"Error retrieving results for {event.data}\", trace=True)\n return\n\n geo_data = {k: v for k, v in geo_data.items() if v is not None}\n if geo_data:\n self.emit_event(geo_data, \"GEOLOCATION\", event)\n elif \"error\" in geo_data:\n error_msg = geo_data.get(\"error\").get(\"error_message\", \"\")\n if error_msg:\n self.warning(error_msg)\n","repo_name":"blacklanternsecurity/bbot","sub_path":"bbot/modules/ip2location.py","file_name":"ip2location.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","stars":2889,"dataset":"github-code","pt":"35"} +{"seq_id":"24322017659","text":"# This script gets all variations of NDC codes\nimport sys, sqlite3;\n\nconn_in = sqlite3.connect(sys.argv[1]);\nconn_in.text_factory = str;\nconn_in.row_factory = sqlite3.Row;\nc_in = conn_in.cursor();\nconn_out = sqlite3.connect(sys.argv[2]);\nconn_out.text_factory = str;\nconn_out.row_factory = sqlite3.Row;\nc_out = conn_out.cursor();\n\nfor row in c_in.execute(\"SELECT DISTINCT ATV, RXCUI FROM RXNSAT WHERE ATN='NDC'\"):\n ndc_code = row[0];\n rxcui = row[1];\n ndc_digits = ndc_code.replace(\"-\", \"\");\n\n if ndc_digits.find(\"*\") == -1:\n c_out.execute(\"INSERT INTO NDC (RXCUI, NDC_DIGITS) VALUES (?, ?)\", (rxcui, ndc_digits));\n else:\n # This only deals with the case where we have one * in the NDC CODE\n for i in range(0, 9):\n ndc_digits_i = ndc_digits.replace(\"*\", str(i));\n c_out.execute(\"INSERT INTO NDC (RXCUI, NDC_DIGITS) VALUES (?, ?)\", (rxcui, ndc_digits_i));\n\nconn_in.commit();\nconn_in.close();\nconn_out.commit();\nconn_out.close();\n","repo_name":"ringful/RxParser","sub_path":"python/generate_ndc_rep.py","file_name":"generate_ndc_rep.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"28403939447","text":"import gym\nimport numpy\nfrom gym import spaces\nfrom py4j.java_gateway import JavaGateway, CallbackServerParameters\n\nENVIROMENT = 'CarRacing-v0'\n\n\nclass ScoreFunction(object):\n def __init__(self):\n self.done = False\n self.observation = env.reset()\n self.score = 0.0\n self.steps = 0\n\n def createNew(self):\n return ScoreFunction()\n\n def getMaxThreads(self):\n return 1\n\n def flushBetween(self):\n return True\n\n def realTimeProcessing(self):\n return True\n\n def generateInput(self):\n j_inputs = None\n if not self.done:\n env.render()\n j_inputs = gateway.new_array(gateway.jvm.float, INPUTS)\n # for x in range(0, 12):\n # for y in range(0, 12):\n # for z in range(0, 3):\n # j_inputs[x*36 + y*3 + z] = float(self.observation[x*8 + 4][y*8 + 4][z])\n\n return j_inputs\n\n def acceptOutput(self, output):\n #action = [(float(output[0]) * 2.0) - 1.0, float(output[1]), float(output[2])]\n action = env.action_space.sample()\n # self.observation, reward, self.done, _ = env.step(action)\n env.step(action)\n self.score += float(reward)\n self.steps += 1\n\n def getScore(self):\n return self.score\n\n def isWinner(self):\n return self.score >= WINNING_SCORE\n\n class Java:\n implements = ['plu.teamtwo.rtm.neat.ScoringFunction']\n\n\nif __name__ == '__main__':\n gateway = JavaGateway(callback_server_parameters=CallbackServerParameters())\n\n env = gym.make(ENVIROMENT)\n #INPUT_SIZE = env.observation_space.shape[0]\n #DISCRETE = isinstance(env.action_space, spaces.Discrete)\n\n DISCRETE = False\n\n INPUTS = 432\n INPUT_SIZE = gateway.new_array(gateway.jvm.int, 3)\n INPUT_SIZE[0] = INPUT_SIZE[1] = 12\n INPUT_SIZE[2] = 3\n\n HIDDEN_SIZE = gateway.new_array(gateway.jvm.int, 2)\n HIDDEN_SIZE[0] = HIDDEN_SIZE[1] = 12\n\n OUTPUT_SIZE = gateway.new_array(gateway.jvm.int, 1)\n OUTPUT_SIZE[0] = 3\n\n WINNING_SCORE = 1000.0 if env.spec.reward_threshold is None else env.spec.reward_threshold\n\n #print(\"Inputs: {}, Outputs: {}, Discrete: {}, Winning Score: {}\".format(INPUT_SIZE, OUTPUT_SIZE, DISCRETE, WINNING_SCORE))\n\n gateway.entry_point.init(gateway.jvm.plu.teamtwo.rtm.genome.graph.MultilayerSubstrateEncodingBuilder()\n .inputs(INPUT_SIZE).outputs(OUTPUT_SIZE).addLayer(HIDDEN_SIZE))\n\n controller = gateway.entry_point.getController()\n controller.createFirstGeneration()\n\n for _ in range(0, 500):\n found_winner = controller.assesGeneration(ScoreFunction())\n best = controller.getBestIndividual()\n print('Gen {:d}: {:.2f}, {:.1f}'\n .format(controller.getGenerationNum(), controller.getFitness(), best.getFitness()))\n # print('generation')\n if found_winner:\n gson = gateway.jvm.com.google.gson.GsonBuilder().setPrettyPrinting().create()\n print(gson.toJson(best))\n\n controller.nextGeneration()\n\n gateway.shutdown()\n","repo_name":"mattiecnvr/race-the-machine","sub_path":"python/openai_gym_hyperneat.py","file_name":"openai_gym_hyperneat.py","file_ext":"py","file_size_in_byte":3086,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"37987295787","text":"import argparse\nimport pprint\n\n\ndef main(argv=None):\n parser = argparse.ArgumentParser()\n\n \"\"\"\n # positional\n parser.add_argument(\"vm_name\", help=\"Name of virtual machine to be created\")\n # help (can be accessed by --help)\n \n # optional (short vs long)\n # optional with default and types\n # type check\n parser.add_argument(\"-c\", \"--cpu\", type=int, default=4, help=\"Number of cpu to use. Default to %(default)s cores\")\n parser.add_argument(\"-m\", \"--memory\", type=int, default=8, help=\"Amount of memory to use in GB. Default to %(default)s GB\")\n \n # count\n parser.add_argument(\"-v\", \"--verbose\", action=\"count\", default=0, help=\"Amount of verbosity in log.\")\n \n # flag or boolean\n parser.add_argument(\"-f\", \"--force\", action=\"store_true\", help=\"Force creation without confirmation.\")\n \n # append\n parser.add_argument(\"-t\", \"--tags\", action=\"append\", default=[], help=\"Tags for the VM (can be specified multiple times).\")\n \n # choice\n parser.add_argument(\"--vm-type\", choices=['linux', 'windows'], required=True, help=\"Type of VM (linux or windows).\")\n \"\"\"\n\n # subcommand\n subparsers = parser.add_subparsers(dest=\"cmd\", required=True)\n\n add_parser = subparsers.add_parser(\n \"add\", help=\"git-add - Add file contents to the index\"\n )\n add_parser.add_argument(\n \"path\", help=\"Files or directory to add to add content from\"\n )\n\n commit_parser = subparsers.add_parser(\n \"commit\", help=\"git-commit - Record changes to the repository\"\n )\n commit_parser.add_argument(\n \"-a\",\n \"--all\",\n action=\"store_true\",\n help=\"Tell the command to automatically stage files that have been modified and deleted, but new files you have not told Git about are not affected.\",\n )\n commit_parser.add_argument(\n \"-m\",\n \"--message\",\n help=\"Use the given as the commit message. If multiple -m options are given, their values are concatenated as separate paragraphs.\",\n )\n\n args = parser.parse_args(argv)\n\n pprint.pprint(vars(args))\n return 0\n\n\nif __name__ == \"__main__\":\n exit(main())\n","repo_name":"debakarr/intermediate-python","sub_path":"content/08_argparse/09_argparse_end.py","file_name":"09_argparse_end.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"35"} +{"seq_id":"73679879459","text":"from django.shortcuts import render\nfrom frontend.models import *\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.contrib import messages\n\n# SEND MAIL IMPORTS STARTS HERE\nfrom django.core import mail\nfrom django.template.loader import render_to_string\nfrom django.utils.html import strip_tags\n# SEND MAIL IMPORTS ENDS HERE\n\n# Create your views here.\n\ndef index(request):\n post = Post.objects.order_by('-created')[:3]\n about = AboutModel.objects.all()[:3]\n context = {\n 'pt':post,\n 'ab':about\n }\n return render(request, 'frontend/index.html', context)\n\ndef about(request):\n about = AboutModel.objects.all()\n return render(request, 'frontend/about.html', {'abt':about})\n\ndef about_detail(request, abt_id):\n detail = AboutModel.objects.get(id=abt_id)\n return render(request, 'frontend/detail.html', {'det':detail})\n\ndef users(request):\n return render(request, 'frontend/users.html')\n\ndef blog(request):\n post = Post.objects.all()\n return render(request, 'frontend/post-list.html', {'pst':post})\n\n# The code below displayspost from a category\ndef post_from_category(request, cat_id):\n count_post_cat = Post.objects.filter(category__id=cat_id).count()\n category = Category.objects.get(id=cat_id)\n post_cat = Post.objects.filter(category__id=cat_id)\n context = {\n 'pst': post_cat, \n 'ct': count_post_cat,\n 'category':category\n }\n\n return render(request, 'frontend/post-cat.html', context)\n\ndef single_blog(request, post_id):\n try:\n single = Post.objects.get(id=post_id)\n except:\n return render(request, 'frontend/404.html')\n return render(request, 'frontend/single-blog.html', {'sin':single})\n\ndef services(request):\n return render(request, 'frontend/services.html')\n\ndef contact(request):\n if request.method == 'POST':\n name = request.POST.get('name')\n phone = request.POST.get('phoneNo')\n email = request.POST.get('email')\n referer = request.POST.get('referer')\n gender = request.POST.get('gender')\n message = request.POST.get('message')\n subject = 'Contact Us Form'\n context = {\n 'name':name,\n 'phone':phone,\n 'email':email,\n 'referer':referer,\n 'gender':gender,\n 'message': message,\n }\n html_message = render_to_string('frontend/mail-template.html', context)\n plain_message = strip_tags(html_message)\n from_email = 'From '\n email_send = mail.send_mail(subject, plain_message, from_email, [\n 'uwazie.benedict@alabiansolutions.com', 'adeloyeadeyemi@gmail.com'], \n html_message=html_message)\n save_contact = ContactModel(name=name, phone_no=phone, email=email, referer=referer, gender=gender)\n save_contact.save()\n if email_send:\n messages.success(request, 'Email is sent')\n else:\n messages.error(request, 'Email is not sent')\n \n return render(request, 'frontend/contact.html')\n","repo_name":"Benwaz78/yemi_repo","sub_path":"frontend/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"71184341221","text":"# Print the formated string\n\nstrnew = '''Dear <|name|>,\n This is to inform you that you are selected!!!!\n Date: <|date|>''';\nname = input(\"Enter the name : \");\ndate = input(\"Enter the Date : \");\n\nstrnew = strnew.replace(\"<|name|>\", name);\nstrnew = strnew.replace(\"<|date|>\", date);\n\nprint(strnew);","repo_name":"dhananjaypuri/python","sub_path":"strings/02_format.py","file_name":"02_format.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"12749118582","text":"from pages.base_page import BasePage\nfrom pages.locators import ProductPageLocators\nimport time\nfrom pages.locators import BasketPageLocators\n\n\nclass ProductPage(BasePage):\n def take_the_goods_to_basket(self):\n add_to_basket = self.browser.find_element(*ProductPageLocators.BUTTON_BASKET)\n add_to_basket.click()\n # self.solve_quiz_and_get_code()\n\n def message_about_added_to_basket(self):\n find_the_name_of_book = self.browser.find_element(*ProductPageLocators.NAME_OF_BOOK)\n find_the_message = self.browser.find_element(*ProductPageLocators.ADD_TO_CART_MESSAGE)\n # print(find_the_message.text.encode(\"utf-8\"))\n # print(find_the_name_of_book.text.encode(\"utf-8\"))\n the_message = \"{} has been added to your basket.\".format(find_the_name_of_book.text)\n assert find_the_message.text == the_message, \"The message does not match with correct message!\"\n print(\"message_about_added_to_basket --- success\")\n\n def message_about_cost_of_basket(self):\n find_the_cost_of_book = self.browser.find_element(*ProductPageLocators.PRICE_OF_BOOK)\n find_the_sum_of_basket = self.browser.find_element(*ProductPageLocators.BASKET_TOTAL)\n assert find_the_cost_of_book.text.encode(\"utf-8\") in find_the_sum_of_basket.text.encode(\"utf-8\"), \\\n \"In the cost does not have the price of current book\"\n print(\"message_about_cost_of_basket --- success\")\n\n def should_not_be_success_message(self):\n assert self.is_not_element_present(*ProductPageLocators.SUCCESS_MESSAGE), \\\n \"Success message is presented, but should not be\"\n\n def should_be_success_message(self):\n assert self.is_disappeared(*ProductPageLocators.SUCCESS_MESSAGE), \\\n \"Success message is presented, but should not be\"\n","repo_name":"IvanKonyaev56/stepick_final_project","sub_path":"pages/product_page.py","file_name":"product_page.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"22288332022","text":"import pandas as pd\nimport requests\nimport json\nimport math\nimport numpy as np\nimport random\n\ncategory = pd.read_csv('category.csv')\n\n\"\"\"\ndf = pd.read_csv('shop.csv')\n#유니크 벨류 세기\npd.value_counts(df['업종코드'].str.get(i=0))\ndf\n#새로운 컬럼 추가\ndf['code'] = np.nan\n\n# pandas 반복문\nfor i in df.index:\n code = df['업종코드'][i]\n for j in category.index:\n if code == category['code'][j]:\n df['code'][i] = category['code'][j]\n break\n\ndf.info()\n\nhasnotCode = df[df['code'].isnull()]\nhasnotCode.shape\n\nhasCode = df[df['code'].notnull()]\npd.value_counts(hasCode['업종코드'].str.get(i=0))\n\n# 인덱스 리셋\n# drop=True 옵션 ; 인덱스를 컬럼에 추가하지 않는다\n# pandas dataframe to csv\n# index=False 옵션 ; 인덱스를 컬럼에 추가하지 않는다\nstores = hasCode.reset_index(drop=True)\nstores.to_csv('filtering_stores.csv',index=False)\n\n\"\"\"\n\nstores = pd.read_csv('filtering_stores.csv')\npd.value_counts(stores['업종코드'].str.get(i=0))\nstores.columns\n\ngangnam = stores[stores['시군구명']=='강남구']\nprint(gangnam.shape)\npd.value_counts(gangnam['업종코드'].str.get(i=0))\nprint(pd.value_counts(gangnam['code']))\n\n# 상권 구분 테이블\narea = pd.read_csv('area.csv')\narea.head()\n\nstores = gangnam\nstores['y'] = np.nan\nstores['x'] = np.nan\nheaders = {\n 'Authorization': 'KakaoAK a8e53fbbc3a4e197e7b7ce41ed995517',\n}\nfor i in stores.index:\n WGS_y = stores['위도'][i]\n WGS_x = stores['경도'][i]\n params = (\n ('x', WGS_x),\n ('y', WGS_y),\n ('input_coord', 'WGS84'),\n ('output_coord', 'WTM'),\n )\n response = requests.get('https://dapi.kakao.com/v2/local/geo/transcoord.json', headers=headers, params=params)\n j = json.loads(response.text)\n WTM_y = j.get(\"documents\")[0].get(\"y\")\n WTM_x = j.get(\"documents\")[0].get(\"x\")\n stores['y'][i]=WTM_y\n stores['x'][i]=WTM_x\n###stores.to_csv('filtering_gangnam.csv')\n\nstores['area_code'] = np.nan\nfor i in stores.index:\n MIN = 99999999\n index = -1\n for j in area.index:\n if(stores['행정동코드'][i]/100 == area['행정동_코드'][j]):\n x = area['x'][j]\n y = area['y'][j]\n temp =math.pow(stores['x'][i]-x,2) +math.pow(stores['y'][i]-y,2)\n if temp region[0]) & (x < region[1]) & (y > region[2]) & (y < region[3]))\n\n # find the minimum and maximum distance from the origin\n\n dd = x*x+y*y\n\n ind1 = np.where(dd == dd.max())\n ind2 = np.where(dd == dd.min())\n\n # calculate the angle of rotation wrt Y axis\n\n angle = np.arctan2((y[ind1]-y[ind2]), (x[ind1]-x[ind2]))-np.pi/4.\n\n return x[ind2], y[ind2], angle\n\n\ndef scaleCentroids(x, y, x1, y1, scale):\n \"\"\"\n\n scale the centroids to mm at mask, and shift to the origin\n\n input\n\n x1,y1: lower left spot\n x,y: coordinates of centroids\n scale: scale factor\n\n returns: transformed x,y\n\n \"\"\"\n\n xc = (x-x1)/scale\n yc = (y-y1)/scale\n\n return xc, yc\n\n\ndef scaleMask(xx, yy, angle, flip):\n \"\"\"\n\n rotate the mask as needed\n\n input\n\n xx,yy: hole positions\n angle: rotation angle\n flip: set to 1 to rotate by 90 degrees\n\n returns: transformed x,y\n\n \"\"\"\n\n # apply any rotation (for matching purposes only)\n\n # add 90 degrees to rotation\n\n if(flip == 1):\n angle = angle+np.pi/2\n\n # shift to centre, rotate, shift back\n xx = xx-168\n yy = yy-168\n\n xnew = xx*np.cos(angle)-yy*np.sin(angle)\n ynew = xx*np.sin(angle)+yy*np.cos(angle)\n\n xx = xnew+168\n yy = ynew+168\n\n return xx, yy\n\n\ndef maskImage(infile, outfile, x1, y1, x2, y2):\n\n image = pf.getdata(infile)\n image[0:x1, :] = 0\n image[x2:, :] = 0\n image[:, 0:y1] = 0\n image[:, y2:] = 0\n pf.writeto(outfile, image, clobber=True)\n","repo_name":"Subaru-PFS/ics_mcsActor","sub_path":"python/mcsActor/Visualization/vis_obsolete.py","file_name":"vis_obsolete.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"73554817379","text":"import copy\nimport math\n\nimport torch\nfrom torch.distributions import normal\n\n\ndef model_sharpness(model):\n \"\"\"\n Calculates sharpness of a model by adding a perturbation to each module.\n The \"add_gauss_perturbation\" function can be substituted with another perturbation generator.\n Args:\n model: model to be evaluated\n\n Returns:\n sharpness value\n \"\"\"\n result = 0\n for child in model.children():\n module_name = child._get_name()\n if module_name in ['Linear', 'Conv1d', 'Conv2d', 'Conv3d']:\n result += add_gauss_perturbation(child)\n else:\n result += model_sharpness(child)\n\n\ndef l_norm(model, p=2, q=2.0):\n \"\"\"\n Calculates a l-norm for a model.\n Args:\n model: model for which the norm should be calculated\n p: p-value\n q: p-value\n\n Returns:\n\n \"\"\"\n result = 0\n for child in model.children():\n module_name = child._get_name()\n if module_name in ['Linear', 'Conv1d', 'Conv2d', 'Conv3d']:\n result += math.log(norm(child, p, q))\n else:\n result += l_norm(child, p, q)\n\n return result\n\n\ndef spectral(model, p=float('Inf')):\n \"\"\"\n Calculates the spectral norm for a model.\n Args:\n model: model for which the norm should be calculated.\n p: p-value\n\n Returns:\n\n \"\"\"\n result = 0\n for child in model.children():\n module_name = child._get_name()\n if module_name in ['Linear', 'Conv1d', 'Conv2d', 'Conv3d']:\n result += math.log(spectral_norm(child, p))\n else:\n result += spectral(child, p)\n\n return result\n\n\ndef path_norm(model, device, p=2, input_size=[3, 32, 32]):\n \"\"\"\n calculates the path norm of a weight matrix of a module.\n Args:\n model: module for which the norm should be calculated\n device: cuda device\n p: p value for norm\n input_size: input dimension of the model\n\n Returns:\n norm value\n \"\"\"\n tmp_model = copy.deepcopy(model)\n tmp_model.eval()\n for param in tmp_model.parameters():\n if param.requires_grad:\n param.abs_().pow_(p)\n data_ones = torch.ones(input_size).to(device)\n return (tmp_model(data_ones).sum() ** (1 / p)).item()\n\n\ndef add_gauss_perturbation(module, alpha=5e-4):\n \"\"\"\n Adds a randomly drawn gaussian perturbation to the weight matrix of a module.\n Args:\n module: module for which the perturbation should be added\n alpha: perturbation bound\n\n \"\"\"\n std = alpha * (10 * torch.abs(torch.mean(module.weight.data)) + 1)\n m = normal.Normal(0, std)\n perturbation = m.sample((1))\n module.weight.data = module.weight.data + perturbation\n\n\ndef norm(module, p=2, q=2):\n \"\"\"\n Calculates the l-norm of the weight matrix of a module\n Args:\n module: module for which the norm should be calculated\n p: p value for norm\n q: q value for norm\n\n Returns:\n norm value\n\n \"\"\"\n reshaped = module.weight.view(module.weight.size(0), -1)\n return reshaped.norm(p=p, dim=1).norm(q).item()\n\n\ndef spectral_norm(module, p=float('Inf')):\n \"\"\"\n Calculates the norm of eigen values of a module\n Args:\n module: module for which the norm should be calculated\n p: p value for norm\n\n Returns:\n norm value\n \"\"\"\n reshaped = module.weight.view(module.weight.size(0), -1)\n _, S, _ = reshaped.svd()\n return S.norm(p).item()\n\n\n\n\n\n","repo_name":"christina-aigner/exploring-generalization","sub_path":"src/measures/measures.py","file_name":"measures.py","file_ext":"py","file_size_in_byte":3463,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"35"} +{"seq_id":"71688361700","text":"\"\"\" Compute source model and leadfield for the child template brain.\"\"\"\n# %% Import necessary modules\nimport os\nimport mne\nfrom core.params import *\n\n\ndef coregistration(\n fname_electrodes, subj=PARCELLATION_SUBJ, mri_folder=MRI_FOLDER):\n \"\"\"Coregister electrodes to MRI. This function opens a GUI in which the\n user can manually adjust the position of the electrodes. You should save\n the trans file in the GUI as fonov-trans.fif for the rest of the pipeline\n to work.\n\n Parameters\n ----------\n fname_electrodes : str\n Path to file containing electrode positions.\n subj : str\n Subject name.\n mri_folder : str\n Path to MRI folder.\n \"\"\"\n # Make directory if necessary\n os.makedirs(mri_folder, exist_ok=True)\n\n # perform co-registration with gui\n mne.viz.set_3d_backend('pyvistaqt')\n mne.gui.coregistration(\n inst=fname_electrodes, subjects_dir=mri_folder, subject=subj,\n mark_inside=True, head_opacity=0.5, block=True)\n\n\ndef verify_coregistration(\n mri_folder=MRI_FOLDER, subj=PARCELLATION_SUBJ,\n trans_fname=LF_TRANS_FNAME):\n \"\"\"Verify that coregistration is accurate.\n\n Parameters\n ----------\n mri_folder : str\n Path to MRI folder.\n subj : str\n Subject name.\n trans_fname : str\n Path to trans file created in coregistration step.\n \"\"\"\n # Read in trans file\n trans = mne.read_trans(trans_fname)\n\n # Verify that the trans-file is doing its job and electrodes are aligned\n # with Freesurfer computed surfaces\n _ = mne.viz.plot_alignment(\n raw.info, trans=trans, subject=subj, dig=False,\n eeg=[\"original\", \"projected\"], coord_frame=\"head\",\n subjects_dir=mri_folder)\n\n\ndef setup_source(\n subj=PARCELLATION_SUBJ, mri_folder=MRI_FOLDER, spacing=SOURCE_SPACING):\n \"\"\"Setup source model.\n\n Parameters\n ----------\n subj : str\n Subject name.\n mri_folder : str\n Path to MRI folder.\n spacing : str\n Source spacing.\n\n Returns\n -------\n src : mne.SourceSpaces\n Source model.\n \"\"\"\n # Setup source model\n src_fname = f\"{mri_folder}/eeg_src.fif\"\n\n # Load if already exists\n if os.path.exists(src_fname):\n return mne.read_source_spaces(src_fname)\n\n # Setup if necessary and save\n src = mne.setup_source_space(\n subj, spacing=spacing, add_dist=False, subjects_dir=mri_folder)\n src.save(src_fname, overwrite=True)\n return src\n\n\ndef compute_bem(subj=PARCELLATION_SUBJ, mri_folder=MRI_FOLDER):\n \"\"\"Compute boundary element model.\n\n Parameters\n ----------\n subj : str\n Subject name.\n mri_folder : str\n Path to MRI folder.\n\n Returns\n -------\n bem : mne.BemSolution\n Boundary element model.\n \"\"\"\n # Compute boundary element model\n bem_fname = f\"{mri_folder}/eeg_bem.fif\"\n\n # Load if already exists\n if os.path.exists(bem_fname):\n return mne.read_bem_solution(bem_fname)\n\n # Calculate and save if necessary\n model = mne.make_bem_model(subject=subj, subjects_dir=mri_folder)\n bem = mne.make_bem_solution(model)\n mne.write_bem_solution(bem_fname, bem, overwrite=True)\n return bem\n\n\ndef compute_leadfield(\n raw, src, bem, mri_folder=MRI_FOLDER, trans_fname=LF_TRANS_FNAME):\n \"\"\"Compute leadfield from set-up source model and boundary element model\n (BEM). Source model and BEM must be computed before running this function.\n\n Parameters\n ----------\n raw : mne.io.Raw\n Raw EEG data.\n src : mne.SourceSpaces\n Source model.\n bem : mne.BemSolution\n Boundary element model.\n mri_folder : str\n Path to folder containing MRI data.\n trans_fname : str\n Path to trans file created in coregistration step.\n \"\"\"\n # Read in trans file\n trans = mne.read_trans(trans_fname)\n\n # Compute lead field\n fwd_fname = f\"{mri_folder}/eeg_fwd.fif\"\n fwd = mne.make_forward_solution(\n raw.info, trans, src, bem, mindist=5.0, meg=False)\n mne.write_forward_solution(fwd_fname, fwd, overwrite=True)\n\n # save the forward model with the dipoles fixed to normal surces\n fwd_fixed = mne.convert_forward_solution(fwd, force_fixed=True)\n mne.write_forward_solution(fwd_fname, fwd_fixed, overwrite=True)\n\n\nif __name__ == '__main__':\n # Download fsaverage files\n mne.set_config('SUBJECTS_DIR', MRI_FOLDER)\n\n # Read in electrode positions from a file\n fname_electrodes = f'{MNE_RAW_FOLDER}/NDARAA075AMK-raw.fif'\n raw = mne.io.read_raw_fif(fname_electrodes)\n\n # %% Perform coregistration\n coregistration(fname_electrodes)\n\n # %% Verify that coregistration is accurate\n verify_coregistration()\n\n # %% Set up source model\n src = setup_source()\n\n # %% Compute BEM\n bem = compute_bem()\n\n # %% Compute leadfield\n compute_leadfield(raw, src, bem)\n","repo_name":"nschawor/eeg-mu-alpha-development","sub_path":"code/source/proc_source_3_compute_leadfield.py","file_name":"proc_source_3_compute_leadfield.py","file_ext":"py","file_size_in_byte":4887,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"71216231780","text":"import cv2 as cv\nimport numpy as np \n\nimg = cv.imread('photos/glass.jpeg')\ncv.imshow('Glass', img)\n\ndef translate(img, x, y):\n # Create shifting Matrix \n # M = [[1, 0, x],\n # [0, 1, y]]\n # -x -> left\n # -y -> up\n # x -> right \n # y -> down \n transMat = np.float32([[1,0,x],[0,1,y]])\n # Image dimension\n dimensions = (img.shape[1], img.shape[0])\n return cv.warpAffine(img, transMat, dimensions)\n\ndef rotate(img, angle, rotPoint=None):\n # Rotate image with angle, at rotPoint\n (height, width) = img.shape[:2]\n \n # if not specify rotation point, using center \n if rotPoint is None:\n rotPoint = (width//2, height//2)\n \n # create rotation matrix \n rotMat = cv.getRotationMatrix2D(rotPoint, angle, 1.0)\n dimensions = (width, height)\n\n return cv.warpAffine(img, rotMat, dimensions)\n\n\ntranslated = translate(img, 100, 100) # shifting image to right 100, down 100\ncv.imshow('Translated', translated)\n\nrotated = rotate(img, 45)\ncv.imshow('Rotated', rotated)\n\nflip = cv.flip(img, -1) # flipping image with flip code, 0 is horizontal flip, 1 is vertical flip, -1 is horizontal + vertical flip\ncv.imshow('Flip', flip)\n\ncv.waitKey(0)","repo_name":"BankNatchapol/OpenCV-Basic-Funtions","sub_path":"transformations.py","file_name":"transformations.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"870140366","text":"import requests\nfrom bs4 import BeautifulSoup\n\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.65 Safari/535.11\"\n}\n\n\ndef get_img_url():\n start_url = \"https://www.douyu.com/g_yz\"\n response = requests.get(start_url, headers)\n soup = BeautifulSoup(response.text, 'html.parser')\n yz_list = soup.select('div[class=\"DyImg avatar\"]')\n for yz in yz_list:\n y_list = yz.select('li')\n for li in y_list:\n yield li.img['src']\n\n\nif __name__ == '__main__':\n img_url = get_img_url()\n for num, img in enumerate(img_url):\n img_response = requests.get(img)\n # print(img_response)\n img = img_response.content\n # img_path = './pic/%s.png' % num\n # with open(img_path, \"wb\") as file:\n # file.write(img)\n","repo_name":"jiaxiaochu/spider","sub_path":"practice_spider/bs4_douyu_pic.py","file_name":"bs4_douyu_pic.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"31339697853","text":"# 给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。\n#\n# 有效 二叉搜索树定义如下:\n#\n# 节点的左子树只包含 小于 当前节点的数。\n# 节点的右子树只包含 大于 当前节点的数。\n# 所有左子树和右子树自身必须也是二叉搜索树。\n\n\n# Definition for a binary tree node.\nfrom typing import Optional\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n # 根据搜索二叉树中序遍历递增特性,判断是不是二叉搜索树\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n prev = float('-inf')\n is_valid = True\n\n def dfs(node):\n nonlocal prev, is_valid\n if not is_valid:\n return\n\n if node.left:\n dfs(node.left)\n\n if node.val <= prev:\n is_valid = False\n\n prev = node.val\n\n if node.right:\n dfs(node.right)\n\n\n dfs(root)\n\n return is_valid\n\n # 迭代中序遍历\n def iter_isValidBST(self, root: Optional[TreeNode]) -> bool:\n stack = []\n prev = float('-inf')\n\n while stack or root:\n while root:\n stack.append(root)\n root = root.left\n root = stack.pop()\n if root.val <= prev:\n return False\n prev = root.val\n root = root.right\n\n return True\n\n # 二叉搜索树左子树不为空,则左子树上所有节点的值均小于它的根节点的值\n # 右子树不为空,则右子树上所有节点的值均大于它的根结点的值\n # 设计一个带参数的递归函数来判断,low,upper,如果root节点的值不在l,r的范围内说明不满足条件,直接返回\n # 根据二叉搜索树的性质,在递归调用左子树的时候,把上界upper改为root.val\n # 右子树的时候,把下界改为root.val\n # 递归的调用入口 l,r为-inf和inf\n def rec_isValidBST(self, root: Optional[TreeNode]) -> bool:\n def helper(node, lower, uppper):\n if not node:\n return True\n\n if node.val <= lower or node.val >= uppper:\n return False\n\n if not helper(node.left, lower, node.val):\n return False\n if not helper(node.right, node.val, uppper):\n return False\n\n return True\n\n return helper(root, float('-inf'), float('inf'))\n\n\n\nnode1 = TreeNode(1)\nnode3 = TreeNode(3)\nnode2 = TreeNode(2, node1, node3)\n\na = Solution().isValidBST(node2)\nprint(a)","repo_name":"cnmasami/leetcode","sub_path":"code/validate_binary_search_tree.py","file_name":"validate_binary_search_tree.py","file_ext":"py","file_size_in_byte":2725,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"43053152092","text":"# checking if an object is equal to none\n\nx = None\nassert x is None\n\nx = 1\nassert x is not None\n\n# another case where short-circuiting\n# allows you to handle cases where\n# you want to avoid accidentally comparing\n# a null variable to an integer\nx = 5\ny = x is not None and x < 10 # y is True\n\nx = None\ny = x is not None and x < 10 # y is False\n\nx = None\ny = x < 10 # generates a TypeError exception","repo_name":"g-deoliveira/python_for_data_analysis_columbia","sub_path":"boolean_operations/is_none.py","file_name":"is_none.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"32574935055","text":"def code(invoerstring):\n i = 0\n integers = []\n character_list = []\n word = None\n while i < len(invoerstring):\n integers.append(ord(invoerstring[i]))\n i += 1\n i = 0\n while i < len(integers):\n character_list.append(chr(int(integers[i] + 3)))\n i += 1\n word = ''.join(character_list)\n print(word)\n\nachternaam = input('Geef uw achternaam: ')\nbeginstation = input('geef uw beginstation: ')\neindstation = input('Geef uw eindstation: ')\nstring = achternaam + beginstation + eindstation\ncode(string)","repo_name":"JakeHU1/Programming","sub_path":"Containers (Sets and Chars) (les 10)/3. ASCII.py","file_name":"3. ASCII.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"29118704695","text":"from time import sleep\n\ncores = [\n '\\033[m', # 0 - Sem cor\n '\\033[31m', # 1 - Vermelho\n '\\033[32m', # 2 - Verde\n '\\033[33m', # 3 - Amarelo\n '\\033[34m', # 4 - Azul\n '\\033[35m', # 5 - Lilás\n '\\033[36m', # 6 - Ciano\n '\\033[37m', # 7 - Cinza\n]\n\n\ndef linha(tmn=35, simb='=', corSimb=0):\n print(f'{cores[corSimb]}{simb}{cores[0]}' * tmn)\n\n\ndef titulo(msg, simb='=', corMsg=0, corSimb=0, tmn=35):\n linha(tmn, simb, corSimb)\n print(cores[corMsg] + msg.center(tmn) + cores[0])\n linha(tmn, simb, corSimb)\n\n sleep(0.8)\n\n\ndef msgErro(msg):\n print(f'\\n{cores[1]}{msg}{cores[0]}\\n')\n sleep(1)\n\n\ndef opcoes(*opcoes, corNum=0, corLinha, tmn=35):\n while True:\n # Listar as opções\n linha(corSimb=corLinha)\n for c, opcao in enumerate(opcoes, start=1):\n print(f' {cores[corNum]}{c}{cores[0]} - {opcao}')\n sleep(0.25)\n sleep(0.75)\n linha(corSimb=corLinha, tmn=tmn)\n\n try:\n opcao = int(input(f'O que deseja fazer? ').strip())\n\n except ValueError:\n msgErro('ERRO: Digite um número inteiro.')\n\n except (KeyboardInterrupt, InterruptedError):\n msgErro('ERRO: Programa interrompido pelo usuário.')\n else:\n if opcao < 1 or opcao > len(opcoes):\n msgErro('ERRO: Digite uma opção válida.')\n\n else:\n break\n\n return opcao\n","repo_name":"Henrique-Sc/Cadastro-de-usuario","sub_path":"main/lib/interface/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"9147940173","text":"from django.conf.urls import patterns, url\n\nfrom Centar import views\n\nurlpatterns = patterns('',\n url(r'^$', views.index, name='index'),\n url(r'^register/$', views.register, name='register'),\n url(r'^user/(?P\\d+)/$', views.user, name='user'),\n url(r'^teren/(?P\\d+)/$', views.teren, name='teren'),\n url(r'^out/$', views.out, name='out'),\n url(r'^superadmin/(?P\\d+)/$', views.superadmin, name='superadmin'),\n url(r'^uspjeh/$', views.uspjeh, name='uspjeh'),\n url(r'^kor_edit/(?P\\d+)/$', views.kor_edit, name='kor_edit'),\n url(r'^superadmin/centar/(?P\\d+)/$', views.centar, name='centar'),\n url(r'^employee/(?P\\d+)/$', views.employee, name='employee'),\n url(r'^employee/(?P\\d+)/termini/$', views.emp_termini, name='emp_termini'),\n url(r'^employee/(?P\\d+)/korisnici/$', views.emp_korisnici, name='emp_korisnici'),\n url(r'^employee/(?P\\d+)/tereni/$', views.emp_tereni, name='emp_tereni'),\n url(r'^employee/teren/(?P\\d+)/termini/neiskoristeni/$', views.emp_termini_neiskor, name='emp_termini_neiskor'),\n url(r'^employee/teren/(?P\\d+)/termini/pregled/$', views.emp_termini_pregled, name='emp_termini_pregled'),\n)","repo_name":"nedo99/TS","sub_path":"Centar/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"40567379696","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('courses', views.get_sections, name='courses'),\n path('submitted', views.register, name='register'),\n path('resubscribe/', views.resubscribe, name='resubscribe'),\n path('webhook', views.accept_webhook, name='webhook'),\n]\n","repo_name":"pennlabs/penn-course-alert","sub_path":"pca/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"35"} +{"seq_id":"5182358312","text":"# coding: utf-8\n####################################################\n# Learning and save build model\n\nimport os, sys\ncurrent_path = os.path.abspath(os.path.dirname(__file__))\nbase_path = current_path + \"/..\"\nsys.path.append(base_path)\nsys.path.append(base_path + \"/lib\")\nsys.path.append(base_path + \"/obj\")\nsys.path.append(base_path + \"/lstm_lib\")\n\nfrom mysql_connector import MysqlConnector\nfrom datetime import timedelta, datetime\nfrom logging import getLogger\n\nimport traceback\nimport subprocess\nimport pandas as pd\npd.set_option(\"display.max_colwidth\", 2000)\npd.set_option(\"display.max_columns\", None)\npd.set_option(\"display.max_rows\", None)\n\nimport numpy as np\nnp.set_printoptions(threshold=np.inf)\nimport matplotlib.pyplot as plt\nplt.switch_backend(\"agg\")\n\nfrom keras.models import Sequential\nfrom keras.layers import Activation, Dense\nfrom keras.layers import LSTM\nfrom keras.layers import Dropout\nfrom keras.models import model_from_json\n\nfrom sklearn.preprocessing import MinMaxScaler\nimport json\n\n\ninstrument = sys.argv[0]\ninstrument = \"GBP_JPY\"\nmysql_connector = MysqlConnector()\n\ndef get_original_dataset(target_time, table_type, span, direct):\n daily_target_time = target_time - timedelta(days=1)\n target_time = target_time.strftime(\"%Y-%m-%d %H:%M:%S\")\n daily_target_time = daily_target_time.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n if direct == \"ASC\" or direct == \"asc\":\n train_original_sql = \"select end_price, sma20, sma40, sma80, sma100, insert_time, uppersigma3, lowersigma3 from %s_%s_TABLE where insert_time >= \\'%s\\' order by insert_time %s limit %s\" % (instrument, table_type, target_time, direct, span)\n else:\n train_original_sql = \"select end_price, sma20, sma40, sma80, sma100, insert_time, uppersigma3, lowersigma3 from %s_%s_TABLE where insert_time < \\'%s\\' order by insert_time %s limit %s\" % (instrument, table_type, target_time, direct, span)\n\n response = mysql_connector.select_sql(train_original_sql)\n\n print(\"#### sql ####\")\n print(train_original_sql)\n print(target_time)\n end_price_list = []\n sma20_list = []\n sma40_list = []\n sma80_list = []\n sma100_list = []\n insert_time_list = []\n uppersigma3_list = []\n lowersigma3_list = []\n\n for res in response:\n end_price_list.append(res[0])\n sma20_list.append(res[1])\n sma40_list.append(res[2])\n sma80_list.append(res[3])\n sma100_list.append(res[4])\n insert_time_list.append(res[5])\n uppersigma3_list.append(res[6])\n lowersigma3_list.append(res[7])\n\n if direct == \"DESC\" or direct == \"desc\":\n end_price_list.reverse()\n sma20_list.reverse()\n sma40_list.reverse()\n sma80_list.reverse()\n sma100_list.reverse()\n insert_time_list.reverse()\n uppersigma3_list.reverse()\n lowersigma3_list.reverse()\n\n\n daily_train_original_sql = \"select max_price, min_price, uppersigma2, lowersigma2, end_price from %s_%s_TABLE where insert_time < \\'%s\\' order by insert_time desc limit 1\" % (instrument, table_type, daily_target_time)\n response = mysql_connector.select_sql(train_original_sql)\n daily_max_price = response[0][0]\n daily_min_price = response[0][1]\n daily_uppersigma2 = response[0][2]\n daily_lowersigma2 = response[0][3]\n daily_end_price = response[0][4]\n\n tmp_original_dataset = {\"end_price\": end_price_list,\n \"sma20\": sma20_list,\n \"sma40\": sma40_list,\n \"sma80\": sma80_list,\n \"uppersigma3\": uppersigma3_list,\n \"lowersigma3\": lowersigma3_list,\n \"insert_time\": insert_time_list}\n\n\n\n\n tmp_dataframe = pd.DataFrame(tmp_original_dataset)\n tmp_dataframe[\"sma20\"] = tmp_dataframe[\"end_price\"] - tmp_dataframe[\"sma20\"]\n tmp_dataframe[\"sma40\"] = tmp_dataframe[\"end_price\"] - tmp_dataframe[\"sma40\"]\n tmp_dataframe[\"sma80\"] = tmp_dataframe[\"end_price\"] - tmp_dataframe[\"sma80\"]\n tmp_dataframe[\"uppersigma3\"] = tmp_dataframe[\"end_price\"] - tmp_dataframe[\"uppersigma3\"]\n tmp_dataframe[\"lowersigma3\"] = tmp_dataframe[\"end_price\"] - tmp_dataframe[\"lowersigma3\"]\n tmp_dataframe[\"daily_max_price\"] = tmp_dataframe[\"end_price\"] - daily_max_price\n tmp_dataframe[\"daily_min_price\"] = tmp_dataframe[\"end_price\"] - daily_min_price\n tmp_dataframe[\"daily_uppersigma2\"] = tmp_dataframe[\"end_price\"] - daily_uppersigma2\n tmp_dataframe[\"daily_lowersigma2\"] = tmp_dataframe[\"end_price\"] - daily_lowersigma2\n tmp_dataframe[\"daily_end_price\"] = tmp_dataframe[\"end_price\"] - daily_end_price\n\n #print(tmp_dataframe)\n\n print(tmp_dataframe[\"insert_time\"])\n\n return tmp_dataframe\n\ndef build_to_normalization( dataset):\n tmp_df = pd.DataFrame(dataset)\n np_list = np.array(tmp_df)\n scaler = MinMaxScaler(feature_range=(0,1))\n scaler.fit_transform(np_list)\n\n return scaler\n\ndef change_to_normalization( model, dataset):\n tmp_df = pd.DataFrame(dataset)\n np_list = np.array(tmp_df)\n normalization_list = model.transform(np_list)\n\n return normalization_list\n\n\ndef create_train_dataset( dataset, learning_span, window_size):\n input_train_data = []\n for i in range(0, (learning_span-window_size)):\n temp = dataset[i:i+window_size].copy()\n model = build_to_normalization(temp)\n temp = change_to_normalization(model, temp)\n input_train_data.append(temp)\n\n input_train_data = np.array(input_train_data)\n\n return input_train_data\n\ndef build_learning_model( inputs, output_size, neurons, activ_func=\"linear\", dropout=0.25, loss=\"mae\", optimizer=\"adam\"):\n model = Sequential()\n model.add(LSTM(neurons, input_shape=(inputs.shape[1], inputs.shape[2])))\n model.add(Dropout(dropout))\n model.add(Dense(units=output_size))\n model.add(Activation(activ_func))\n model.compile(loss=loss, optimizer=optimizer)\n\n return model\n\ndef change_to_ptime( time):\n return datetime.strptime(time, \"%Y-%m-%d %H:%M:%S\")\n\ndef decideConditions( table_type, target_time):\n # パーフェクトオーダーが出てるときだけを教師データとして入力する\n sql = \"select sma20, sma40, sma80 from %s_%s_TABLE where insert_time < \\'%s\\' order by insert_time desc limit 1\" % (instrument, table_type, target_time)\n response = mysql_connector.select_sql(sql)\n sma20 = response[0][0]\n sma40 = response[0][1]\n sma80 = response[0][2]\n flag = False\n if (sma20 > sma40 > sma80) or (sma20 < sma40 < sma80):\n flag = True\n\n return flag\n\ndef decideTerm( hour):\n term = None\n if 5 <= hour < 13:\n term = \"morning\"\n if 13 <= hour < 21:\n term = \"daytime\"\n if 21 <= hour or hour < 6:\n term = \"night\"\n\n return term\n\ndef train_save_model(window_size, output_train_index, table_type, figure_filename, model_filename, weights_filename, start_time, end_time, term):\n command = \"ls ../model/ | grep -e %s -e %s | wc -l\" % (model_filename, weights_filename)\n out = subprocess.getoutput(command)\n if int(out) < 2:\n start_ptime = change_to_ptime(start_time)\n end_ptime = change_to_ptime(end_time)\n\n target_time = start_ptime\n\n train_input_dataset = []\n train_output_dataset = []\n train_time_dataset = []\n input_max_price = []\n input_min_price = []\n\n while target_time < end_ptime:\n hour = target_time.hour\n\n if decideTerm(hour) == term or term == \"all\":\n #if decideConditions(\"1h\", target_time):\n if 1==1:\n print(\"term=%s, target_time=%s\" % (term, target_time))\n # 未来日付に変えて、教師データと一緒にまとめて取得\n if table_type == \"1h\":\n tmp_target_time = target_time - timedelta(hours=1)\n elif table_type == \"5m\":\n tmp_target_time = target_time + timedelta(minutes=5)\n elif table_type == \"day\":\n tmp_target_time = target_time + timedelta(days=1)\n else:\n raise\n\n tmp_dataframe = get_original_dataset(target_time, table_type, span=window_size, direct=\"DESC\")\n tmp_output_dataframe = get_original_dataset(target_time, table_type, span=output_train_index, direct=\"ASC\")\n\n tmp_dataframe = pd.concat([tmp_dataframe, tmp_output_dataframe])\n tmp_time_dataframe = tmp_dataframe.copy()[\"insert_time\"]\n input_max_price.append(max(tmp_dataframe[\"end_price\"]))\n input_min_price.append(min(tmp_dataframe[\"end_price\"]))\n\n del tmp_dataframe[\"insert_time\"]\n\n tmp_time_dataframe = pd.DataFrame(tmp_time_dataframe)\n tmp_time_input_dataframe = tmp_time_dataframe.iloc[:window_size, 0]\n tmp_time_output_dataframe = tmp_time_dataframe.iloc[-1, 0]\n\n #print(\"=========== train list ============\")\n #print(tmp_time_input_dataframe)\n #print(\"=========== output list ============\")\n #print(tmp_time_output_dataframe)\n\n tmp_np_dataset = tmp_dataframe.values\n normalization_model = build_to_normalization(tmp_np_dataset)\n tmp_np_normalization_dataset = change_to_normalization(normalization_model, tmp_np_dataset)\n tmp_dataframe = pd.DataFrame(tmp_np_normalization_dataset)\n\n tmp_input_dataframe = tmp_dataframe.copy().iloc[:window_size, :]\n tmp_output_dataframe = tmp_dataframe.copy().iloc[-1, 0]\n\n tmp_input_dataframe = tmp_input_dataframe.values\n #tmp_output_dataframe = tmp_output_dataframe.values\n\n\n train_time_dataset.append(tmp_time_output_dataframe)\n train_input_dataset.append(tmp_input_dataframe)\n train_output_dataset.append(tmp_output_dataframe)\n #print(\"shape = %s\" % str(tmp_input_dataframe.shape))\n if table_type == \"1h\":\n target_time = target_time + timedelta(hours=1)\n elif table_type == \"5m\":\n target_time = target_time + timedelta(minutes=5)\n elif table_type == \"day\":\n target_time = target_time + timedelta(days=1)\n else:\n raise\n\n train_input_dataset = np.array(train_input_dataset)\n train_output_dataset = np.array(train_output_dataset)\n\n learning_model = build_learning_model(train_input_dataset, output_size=1, neurons=500)\n history = learning_model.fit(train_input_dataset, train_output_dataset, epochs=100, batch_size=1, verbose=2, shuffle=False)\n #history = learning_model.fit(train_input_dataset, train_output_dataset, epochs=1, batch_size=1, verbose=2, shuffle=False)\n train_predict = learning_model.predict(train_input_dataset)\n\n # 正規化戻しする\n paint_train_predict = []\n paint_train_output = []\n\n for i in range(len(input_max_price)):\n paint_train_predict.append((train_predict[i][0]*(input_max_price[i]-input_min_price[i])) + input_min_price[i])\n paint_train_output.append((train_output_dataset[i]*(input_max_price[i]-input_min_price[i])) + input_min_price[i])\n\n ### paint predict train data\n fig, ax1 = plt.subplots(1,1)\n ax1.plot(train_time_dataset, paint_train_predict, label=\"Predict\", color=\"blue\")\n ax1.plot(train_time_dataset, paint_train_output, label=\"Actual\", color=\"red\")\n\n plt.savefig(figure_filename)\n\n # モデルの保存\n model_filename = \"../model/%s\" % model_filename\n weights_filename = \"../model/%s\" % weights_filename\n json_string = learning_model.to_json()\n open(model_filename, \"w\").write(json_string)\n learning_model.save_weights(weights_filename)\n\n return learning_model\n\n\ndef predict_value(base_time, learning_model, window_size, table_type, output_train_index):\n# window_size = 24 # 24時間単位で区切り\n# table_type = \"1h\"\n# output_train_index = 8 # 8時間後をラベルにする\n predict_value = 0\n\n if table_type == \"1h\":\n target_time = base_time - timedelta(hours=1)\n elif table_type == \"5m\":\n target_time = base_time - timedelta(minutes=5)\n elif table_type == \"day\":\n target_time = base_time - timedelta(days=1)\n else:\n raise\n\n # パーフェクトオーダーが出てるときだけを教師データとして入力する\n #if decideConditions(table_type, target_time):\n# if decideConditions(\"1h\", target_time):\n if 1==1:\n tmp_dataframe = get_original_dataset(target_time, table_type, span=window_size, direct=\"DESC\")\n\n # 正規化を戻したいので、高値安値を押さえておく\n output_max_price = max(tmp_dataframe[\"end_price\"])\n output_min_price = min(tmp_dataframe[\"end_price\"])\n\n # 正規化したいのでtimestampを落とす\n del tmp_dataframe[\"insert_time\"]\n test_dataframe_dataset = tmp_dataframe.copy().values\n\n # outputは別のモデルで正規化する\n model = build_to_normalization(test_dataframe_dataset)\n test_normalization_dataset = change_to_normalization(model, test_dataframe_dataset)\n\n # データが1セットなので空配列に追加してndarrayに変換する\n test_input_dataset = []\n test_input_dataset.append(test_normalization_dataset)\n test_input_dataset = np.array(test_input_dataset)\n\n# print(test_input_dataset.shape)\n test_predict = learning_model.predict(test_input_dataset)\n predict_value = test_predict[0][0]\n predict_value = (predict_value*(output_max_price-output_min_price))+output_min_price\n print(\"predict_value = %s\" % predict_value)\n\n # 答え合わせ\n #if table_type == \"1h\":\n # target_right_time = base_time + timedelta(hours=output_train_index)\n #elif table_type == \"5m\":\n # target_right_time = base_time + timedelta(minutes=(output_train_index*5))\n #elif table_type == \"day\":\n # target_right_time = base_time + timedelta(days=output_train_index)\n #else:\n # raise\n\n #sql = \"select end_price, insert_time from %s_%s_TABLE where insert_time < \\'%s\\' order by insert_time desc limit 1\" % (instrument, table_type, target_right_time)\n #response = mysql_connector.select_sql(sql)\n #right_price = response[0][0]\n #right_time = response[0][1]\n #current_price = (ask_price + bid_price)/2\n\n\n #debug_logger.info(\"table_type, target_time, current_price, predict_value, right_time, right_price\")\n #debug_logger.info(\"%s, %s, %s, %s, %s, %s\" % (table_type, base_time, current_price, predict_value, target_right_time, right_price))\n\n #debug_logger.info(\"%s, %s, %s, %s, %s, %s\" % (table_type, base_time, current_price, predict_value, target_right_time, right_price))\n\n return predict_value\n\n","repo_name":"tomoyanp/oanda_dev3.5.2","sub_path":"lstm_lib/old/lstm_model_wrapper_bk.py","file_name":"lstm_model_wrapper_bk.py","file_ext":"py","file_size_in_byte":15192,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"22003068313","text":"\"\"\"\nleetcode 2333: minimum sum of squared difference\n\nWe are given two positive integer arrays 'nums1' and 'nums2', both of length n.\n\nThe of squared difference of arrays nums1 and nums2 is defined as the sum of\n(nums1[i] - nums2[i])^2 for each 0 <= i < n.\n\nWe are also given two positive integers k1 and k2. We can modify any of the\nelements of nums1 by +1 or -1 at most k1 times. Similarly for nums2 elements\nand k2.\n\nReturn the minimum squared difference after modifying array nums1 at most k1\ntimes and modifying array nums2 at most k2 times.\n\nWe are allowed to modify the array elements to become negative integers.\n\"\"\"\n\nimport heapq\n\n\ndef min_sum(nums1, nums2, k1, k2):\n \"\"\"\n \"\"\"\n diff = [-abs(nums1[i] - nums2[i]) for i in range(len(nums1))]\n heapq.heapify(diff)\n k = k1 + k2\n s = -sum(diff)\n if s < k:\n return 0\n while k > 0:\n maxi = -heapq.heappop(diff)\n gap = max(k // len(nums1), 1)\n if k < gap:\n k = 0\n else:\n k -= gap\n maxi -= gap\n heapq.heappush(diff, -maxi)\n return sum(i**2 for i in diff)\n\n\ndef test1():\n assert min_sum([1, 2, 3, 4], [2, 10, 20, 19], 0, 0) == 579\n print(\"test 1 successful\")\n\n\ndef test2():\n assert min_sum([1, 4, 10, 12], [5, 8, 6, 9], 1, 1) == 43\n print(\"test 2 successful\")\n\n\ndef main():\n test1()\n test2()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jschnab/leetcode","sub_path":"arrays/min_sum_squared_diff.py","file_name":"min_sum_squared_diff.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"18951884699","text":"from gui_builder import make_gui\nfrom PyQt4.QtCore import QTimer\nfrom numpy import linspace, sin, cos, tan\n\n@make_gui\nclass Window(object):\n def make_plot_gb_button(self):\n f = gb_get_float_frequency(3)\n start = gb_get_float_start(0)\n stop = gb_get_float_stop(10)\n steps = gb_get_int_step(100)\n x = linspace(start, stop, steps)\n y = sin(f * x)\n gb_plot_xy_sinusoid_sin(x, sin(f*x))\n gb_plot_xy_sinusoid_cos(x, cos(f*x))\n gb_plot_xy_trig_tan(x, tan(f*x))\n\n def recurring_plot_gb_button(self):\n self.timer = QTimer()\n self.recurring_plot()\n\n def recurring_plot(self):\n f = gb_get_float_frequency()\n gb_set_float_frequency(f+1)\n self.make_plot_gb_button()\n if gb_get_bool_halt(False):\n gb_set_bool_halt(False)\n else:\n self.timer.singleShot(1000, self.recurring_plot)\n\nif __name__ == '__main__':\n Window()\n","repo_name":"PhilReinhold/gui_builder","sub_path":"gui_builder_example.py","file_name":"gui_builder_example.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"21477248631","text":"flag=False\r\nmy_players=[\"d-bee\",\"alok.orion\",\"k\",\"chrono\"]\r\nu = input(\"search: \")\r\nfor i in range(0,4):\r\n if my_players[i]==u :\r\n flag=True\r\n\r\nif flag==True:\r\n print(\"found\")\r\nelse:\r\n print(\"not found\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"a3372djan/python-learning-level2","sub_path":"search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"29991015209","text":"# Check for requirements:\nimport os\nimport subprocess\n# [1] Freesurfer, freeview\nfs_cmd_list = ['freeview', 'mri_convert']\nfor cmd in fs_cmd_list:\n cmd_out = subprocess.getstatusoutput(f\"command -v {cmd}\")[1]\n if cmd_out=='':\n print(f'Could not find path for {cmd}, is freesurfer accessible from here?')\n\n# ************************** SPECIFY FS_LICENSE HERE **************************\nos.environ['FS_LICENSE'] = '/data1/projects/dumoulinlab/Lab_members/Marcus/programs/linescanning/misc/license.txt'\nif 'FS_LICENSE' in os.environ.keys():\n if not os.path.exists(os.environ['FS_LICENSE']):\n print('Could not find FS_LICENSE, set using os.environ above')\nelse:\n print('Could not find FS_LICENSE')\n print('Uncomment line below and specify path to FS_LICENSE')\n\n# # [2] Nibabel\n# try:\n# from nibabel.freesurfer.io import write_morph_data \n# except ImportError:\n# print('Error importing nibabel... Not a problem unless you want to use FSMaker')\n\n# [3] pycortex\ntry: \n import cortex \nexcept ImportError:\n print('Error importing pycortex... Not a problem unless you want to use pycortex stuff')\n\n\n\n# ************************** SPECIFY BLENDER PATH HERE **************************\nos.environ['BLENDER'] = '/data1/projects/dumoulinlab/Lab_members/Marcus/programs/blender-3.5.1-linux-x64/blender'\nif not 'BLENDER' in os.environ.keys():\n # Check for command:\n blender_cmd = subprocess.getstatusoutput(f\"command -v blender\")[1]\n if blender_cmd == '':\n print('could not find blender command, specify in __init__ file')\n else:\n os.environ['BLENDER'] = blender_cmd\nelif not os.path.exists(os.environ['BLENDER']): \n print('Could not find blender, specify location in __init__ file')\n print('only a problem if you want to use blender...')","repo_name":"mdaghlian/dag_prf_utils","sub_path":"dag_prf_utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"30017129641","text":"from graphics import *\nfrom random import randrange\n\n##\n## Problem 15\n##\n\ndef p15():\n \"\"\"This function displays the student grade data in a horizontal bar chart\"\"\"\n infile = open(\"exam-scores.dat\")\n num_scores = int(infile.readline())\n print(\"There are\", num_scores, \" scores\")\n \n #\n # Define some variables used in sizing and placement\n #\n student_data_height = 40\n inter_data_spacing = 10\n left_spacing = 10\n top_spacing = 25\n name_width = 50\n bar_width = 200\n bar_height = 10\n \n #\n # Dynamically sized window\n #\n win = GraphWin(\"Student Scores\", left_spacing + name_width + inter_data_spacing + bar_width + left_spacing, \n (student_data_height + inter_data_spacing) * (num_scores -1))\n \n # \n # Starting y position for placing the score information\n #\n data_y_position = top_spacing\n \n #\n # Counter used to draw the score info\n #\n index = 0\n \n #\n # Process each line in the file\n #\n for line in infile:\n # Extract the name and score\n name, score_str = line.split()\n score = float(score_str)\n\n # Set the y position for this score data by using the\n y_pos = top_spacing + index * student_data_height\n \n name_text = Text(Point(name_width / 2 + left_spacing, y_pos + 5), name)\n name_text.setSize(10)\n name_text.draw(win)\n index = index + 1\n \n bar_x_pos = left_spacing + name_width + inter_data_spacing\n Rectangle(Point(bar_x_pos, y_pos), \n Point(bar_x_pos + (score / 100) * 200, y_pos + bar_height)).draw(win)\n \n pt = win.getMouse()\n win.close()\n infile.close()\n\n##\n## Problem 16\n##\n\ndef generate_data(num_points):\n outfile = open(\"quiz-scores.dat\", \"w\")\n for i in range(0, num_points):\n value = randrange(0, 11)\n print(value, file=outfile)\n outfile.close()\n\ndef p16():\n \"\"\"This function displays the student quiz grade data in a histogram\"\"\"\n infile = open(\"quiz-scores.dat\", \"r\")\n\n #\n # Create the initial count list\n #\n score_list = []\n for i in range(0, 11):\n score_list.append(0)\n\n #\n # Update the counts\n #\n total_possible_count = 0\n for line in infile:\n score = int(line)\n score_list[score] = score_list[score] + 1\n total_possible_count = total_possible_count + 1\n \n print(\"Counted score list\", score_list)\n\n #\n # Define some variables used in sizing and placement\n #\n bar_width = 20\n left_spacing = 10\n right_spacing = 10\n bottom_spacing = 10\n top_spacing = 10\n inter_bar_spacing = 10\n bar_height = 100\n label_height = 10\n \n #\n # Dynamically sized window\n #\n window_height = bottom_spacing + bar_height + top_spacing + label_height\n win = GraphWin(\"Student Scores\", left_spacing + (bar_width + inter_bar_spacing) * 10 + right_spacing, \n window_height)\n \n #\n # Display the labels and bars\n #\n for i in range(0, 11):\n x_pos = left_spacing + (bar_width + inter_bar_spacing) * i\n y_pos = window_height - 10 - (label_height / 2)\n label = Text(Point(x_pos, y_pos), str(i))\n label.setSize(10)\n label.draw(win)\n \n x_pos = left_spacing + (bar_width + inter_bar_spacing) * i\n y_pos = y_pos - label_height / 2 - inter_bar_spacing\n Rectangle(Point(x_pos, y_pos), \n Point(x_pos + bar_width, y_pos - (100 * score_list[i] / total_possible_count))).draw(win)\n\n # Mouse click to close\n pt = win.getMouse()\n win.close()\n infile.close()\n ","repo_name":"Oklahoma-Baptist-University/cis-3703-spring-2021-hw5","sub_path":"HW5.py","file_name":"HW5.py","file_ext":"py","file_size_in_byte":3648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"10987886719","text":"# -*- coding: utf-8 -*-\nimport asyncio\nimport logging\n\nimport scapy.all as scapy\n\nfrom cbpi.api import *\nfrom cbpi.api import parameters, Property, action\nfrom cbpi.api.step import StepResult, CBPiStep\nfrom cbpi.api.timer import Timer\nfrom cbpi.api.dataclasses import NotificationType\n\nlogger = logging.getLogger(__name__)\n\nTIMOUT_INTERVAL = 0.5\n\n\ndef extract_unit(data):\n ### Xiaomi V1 Scale ###\n measunit = data[4:6]\n unit = \"fault\"\n if data.startswith('1d18'):\n if measunit.startswith(('03', 'a3')):\n unit = 'lbs'\n if measunit.startswith(('12', 'b2')):\n unit = 'jin'\n if measunit.startswith(('22', 'a2', '02')):\n unit = 'kg'\n\n ### Xiaomi V2 Scale ###\n if data.startswith('1b18'):\n if measunit == \"03\":\n unit = 'lbs'\n if measunit == \"02\":\n unit = 'kg'\n\n return unit\n\n\ndef extract_weight(data):\n ### Xiaomi V1 Scale ###\n measured = -1\n if data.startswith('1d18'):\n measured = int((data[8:10] + data[6:8]), 16) * 0.01\n\n ### Xiaomi V2 Scale ###\n if data.startswith('1b18'):\n measured = int((data[28:30] + data[26:28]), 16) * 0.01\n\n return measured / 2\n\n\nclass BluetoothListener(scapy.BluetoothHCISocket):\n def __init__(self, dev_mac):\n super(BluetoothListener, self).__init__(0)\n self.dev_mac = dev_mac\n self.__sr_hci_msg(scapy.HCI_Cmd_LE_Set_Scan_Parameters(type=1))\n\n def __sr_hci_msg(self, msg):\n return self.sr(scapy.HCI_Hdr() / scapy.HCI_Command_Hdr() / msg, timeout=0.001)\n\n def __ble_listen(self):\n self.__sr_hci_msg(scapy.HCI_Cmd_LE_Set_Scan_Enable(enable=True, filter_dups=False))\n adverts = self.sniff(lfilter=lambda p: scapy.HCI_LE_Meta_Advertising_Reports in p, timeout=TIMOUT_INTERVAL)\n # todo change timeout to min\n self.__sr_hci_msg(scapy.HCI_Cmd_LE_Set_Scan_Enable(enable=False))\n return adverts\n\n def __get_clean_packet(self, report):\n if report.addr == self.dev_mac.lower():\n for pkt in report.data:\n if pkt.type == 0x16: # 0x16 == svc_data_16_bit_uuid\n yield scapy.hexdump(pkt[1], True).replace(\" \", \"\").lower()[\n 4:34] # pkt[1] is the layer containing the data\n continue\n\n def read_unit(self):\n data = self.__ble_listen()\n\n for pkt in data:\n reports = pkt[scapy.HCI_LE_Meta_Advertising_Reports].reports\n for report in reports:\n for pkt_data in self.__get_clean_packet(report):\n return extract_unit(pkt_data)\n\n def read_info(self):\n data = self.__ble_listen()\n\n for pkt in data[::-1]:\n reports = pkt[scapy.HCI_LE_Meta_Advertising_Reports].reports\n for report in reports[::-1]:\n for pkt_data in self.__get_clean_packet(report):\n return extract_weight(pkt_data)\n\n\n@parameters([Property.Text(label=\"Scale mac\", configurable=True, default_value=\"\",\n description=\"The mac address of the Xiaomi scale.\"),\n Property.Number(label=\"Offset\", configurable=True, default_value=0,\n description=\"The difference between the measured 0 and actual 0.\"),\n Property.Number(label=\"Gravity\", configurable=True, default_value=1.000,\n description=\"The Gravity of the liquid.\"),\n Property.Select(label=\"Display type\", options=[\"Volume\", \"Weight\"],\n description=\"The desired unit type to display (default=Volume)\"),\n Property.Select(label=\"Disable Sensor\", options=[\"Enable\", \"Disable\"],\n description=\"The desired unit type to display (default=Volume)\")])\nclass XiaomiScale(CBPiSensor):\n\n def __init__(self, cbpi, id, props):\n super(XiaomiScale, self).__init__(cbpi, id, props)\n self.enabled = self.props.get(\"Disable Sensor\", \"Enable\") == \"Enable\"\n self.scale_mac = self.props.get(\"Scale mac\", \"XX:XX:XX:XX:XX:XX\")\n self.orig_offset = self.props.get(\"Offset\", 0)\n self.gravity = float(self.props.get(\"Gravity\", 1))\n if self.gravity == 0:\n logging.warning(f\"{self.gravity} is an illegal gravity value, setting gravity to 1\")\n self.gravity = 1\n self.disp_unit = self.cbpi.config.get(\"Water volume unit\", \"L\")\n self.disp_vol = self.props.get(\"Display type\", \"Volume\") == \"Volume\"\n\n self.weight = 0\n self.value = 0\n self.offset = float(self.orig_offset)\n\n if self.enabled:\n self.bt_soc = BluetoothListener(self.scale_mac)\n self.weight_unit = self.bt_soc.read_unit()\n\n @action(key=\"Tare\", parameters=[])\n async def tare(self, offset=None, **kwargs):\n logging.info(\"Tare\")\n if offset is not None:\n logging.info(f\"Offset {offset} was given\")\n self.offset += float(offset)\n else:\n self.offset += self.weight\n logger.info(\"Tare Performed\")\n\n @action(key=\"Change Gravity\", parameters=[Property.Number(label=\"gravity\", configurable=True, default_value=1,\n description=\"Gravity in SG\")])\n async def change_gravity(self, gravity=1, **kwargs):\n if gravity == 0:\n logger.warning(f\"Illegal gravity value, gravity remained {self.gravity}\")\n return\n self.gravity = float(gravity)\n logger.info(f\"Gravity Changed to {self.gravity}\")\n\n @action(key=\"Reset\", parameters=[])\n async def reset(self):\n logging.info(\"reset\")\n self.offset = float(self.orig_offset)\n if self.enabled:\n self.bt_soc = BluetoothListener(self.scale_mac)\n\n @action(key=\"Toggle State\", parameters=[])\n async def toggle_state(self):\n if self.enabled:\n logging.info(\"Disabled\")\n else:\n logging.info(\"Enabled\")\n self.enabled = not self.enabled\n await self.reset()\n\n def get_unit(self):\n return self.weight_unit\n\n def weight2kg(self):\n if self.weight_unit == \"lbs\":\n return self.weight * 0.4535924\n if self.weight_unit == \"jin\":\n return self.weight * 0.5\n return self.weight\n\n def convert(self, weight):\n vol = weight / self.gravity\n if self.disp_unit == \"gal(us)\":\n vol *= 0.264172052\n elif self.disp_unit == \"gal(uk)\":\n vol *= 0.219969157\n elif self.disp_unit == \"qt\":\n vol *= 1.056688\n return vol\n\n async def run(self):\n while self.running:\n if self.enabled:\n reading = self.bt_soc.read_info()\n if reading is not None:\n self.weight = float(reading) - self.offset\n if self.disp_vol:\n volume = self.convert(self.weight2kg())\n self.value = float(volume)\n else:\n self.value = self.weight\n self.push_update(self.value)\n await asyncio.sleep(0.5)\n\n def get_state(self):\n return dict(value=self.value)\n\n\n@parameters([Property.Number(label=\"Volume\", description=\"Volume limit for this step\", configurable=True),\n Property.Actor(label=\"Actor\", description=\"Actor to switch media flow on and off\"),\n Property.Sensor(label=\"Sensor\"),\n Property.Select(label=\"Reset\", options=[\"Yes\", \"No\"], description=\"Reset Sensor when done\")])\nclass FillStep(CBPiStep):\n\n async def on_timer_done(self, timer):\n self.summary = \"\"\n self.cbpi.notify(self.name,\n 'Step finished. Transferred {} {}.'.format(round(self.current_volume, 2), self.unit),\n NotificationType.SUCCESS)\n if self.resetsensor == \"Yes\":\n self.sensor.instance.reset()\n\n if self.actor is not None:\n await self.actor_off(self.actor)\n await self.next()\n\n async def on_timer_update(self, timer, seconds):\n await self.push_update()\n\n async def on_start(self):\n self.unit = self.cbpi.config.get(\"Water volume unit\", \"L\")\n self.actor = self.props.get(\"Actor\", None)\n if self.actor is not None:\n await self.actor_off(self.actor)\n\n self.target_volume = float(self.props.get(\"Volume\", 0))\n self.vol_sensor = self.props.get(\"Sensor\", None)\n self.sensor = self.get_sensor(self.vol_sensor)\n self.resetsensor = self.props.get(\"Reset\", \"Yes\")\n self.sensor.instance.reset()\n self.start_weight = self.sensor.instance.value\n if self.timer is None:\n self.timer = Timer(1, on_update=self.on_timer_update, on_done=self.on_timer_done)\n\n async def on_stop(self):\n if self.timer is not None:\n await self.timer.stop()\n self.summary = \"\"\n if self.actor is not None:\n await self.actor_off(self.actor)\n await self.push_update()\n\n async def reset(self):\n self.timer = Timer(1, on_update=self.on_timer_update, on_done=self.on_timer_done)\n if self.actor is not None:\n await self.actor_off(self.actor)\n if self.resetsensor == \"Yes\":\n self.sensor.instance.reset()\n\n async def run(self):\n if self.actor is not None:\n await self.actor_on(self.actor)\n self.summary = \"\"\n await self.push_update()\n while self.running:\n self.current_volume = self.get_sensor_value(self.vol_sensor).get(\"value\")\n self.summary = \"Volume: {:.3f}\".format(self.current_volume)\n await self.push_update()\n\n if self.current_volume >= self.target_volume and self.timer.is_running is not True:\n self.timer.start()\n self.timer.is_running = True\n\n await asyncio.sleep(0.2)\n\n return StepResult.DONE\n\n\ndef setup(cbpi):\n cbpi.plugin.register(\"XiaomiScale\", XiaomiScale)\n cbpi.plugin.register(\"FillStep\", FillStep)\n","repo_name":"madhatguy/cbpi4-XiaomiScale","sub_path":"cbpi4-XiaomiScale/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":10101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"26776849787","text":"import time\nimport subprocess\nimport pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import Select\n\ndriver = webdriver.Chrome()\n\nstates = [\n 'AL', 'MO', 'AK', 'MT', 'AZ', 'NE', 'AR', 'NV', 'CA', 'NH', \n 'CO', 'NJ', 'CT', 'NM', 'DE', 'NY', 'NC', 'FL', 'ND', 'GA', \n 'OH', 'HI', 'OK', 'ID', 'OR', 'IL', 'PA', 'IN', 'RI', 'IA', \n 'SC', 'KS', 'SD', 'KY', 'TN', 'LA', 'TX', 'ME', 'UT', 'MD', \n 'VT', 'MA', 'VA', 'MI', 'WA', 'MN', 'WV', 'MS', 'WI', 'WY' \n ]\n\nitems = ['zebra', 'lion', 'elephant', 'giraffe']\n\n\n\n@pytest.mark.parametrize('state', states)\ndef test_correct_page(state):\n driver.get('https://jungle-socks.herokuapp.com/')\n if state == states[0]:\n time.sleep(2)\n else:\n time.sleep(.5)\n title = driver.title\n sub = driver.find_element_by_name('commit')\n zebra = driver.find_element_by_id('line_item_quantity_zebra').send_keys('1')\n select = Select(driver.find_element_by_name('state'))\n select.select_by_value(state)\n sub.click()\n time.sleep(.2)\n subtotal = driver.find_element_by_id('subtotal').text.strip('$')\n taxes = driver.find_element_by_id('taxes').text.strip('$')\n\n rate = float(taxes)/float(subtotal)\n rate = round(rate, 2)\n\n if state == 'NY':\n assert rate == 0.06\n elif state == 'CA':\n assert rate == 0.08\n elif state == 'MN':\n assert rate == 0.00\n else:\n assert rate == 0.05\n\n\n\n\n@pytest.mark.parametrize('item', items) \ndef test_prices(item):\n driver.get('https://jungle-socks.herokuapp.com/')\n if item == items[0]:\n time.sleep(2)\n else:\n time.sleep(.5)\n title = driver.title\n sub = driver.find_element_by_name('commit')\n\n if item == 'zebra':\n zebra = driver.find_element_by_id('line_item_quantity_zebra').send_keys('1')\n elif item == 'lion':\n lion = driver.find_element_by_id('line_item_quantity_lion').send_keys('1')\n elif item == 'elephant':\n elephant = driver.find_element_by_id('line_item_quantity_elephant').send_keys('1')\n elif item == 'giraffe':\n giraffe = driver.find_element_by_id('line_item_quantity_giraffe').send_keys('1')\n\n select = Select(driver.find_element_by_name('state'))\n select.select_by_value('NY')\n sub.click()\n time.sleep(.2)\n\n price = driver.find_element_by_id('subtotal').text.strip('$')\n price = float(price)\n\n if item == 'zebra':\n assert price == 13.00\n elif item == 'lion':\n assert price == 20.00\n elif item == 'elephant':\n assert price == 35.00\n elif item == 'giraffe':\n assert price == 17.00\n\n if item == items[-1]:\n driver.quit()","repo_name":"JoshGuarino/SN_code_test","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"38761738598","text":"\nimport numpy as np\n\n\nclass TwoClassesLinearDataset():\n '''\n class of dataset\n two class, each class contain 50 points (dim = 2)\n Args:\n - data_num: number of sample points\n - dim: dimensionality of sample points\n - save_img_path: the path save the figure of sample points\n '''\n\n def __init__(self, data_num, dim, save_img_path):\n \n self.data_num = data_num\n self.dim = dim\n self.save_img_path = save_img_path\n\n self.data_X = None\n self.data_y = None\n \n self.X_cls_1 = None\n self.y_cls_1 = None\n self.X_cls_2 = None\n self.y_cls_2 = None\n \n \n def make_data(self):\n\n self.X_cls_1 = np.random.randn(self.dim, self.data_num)\n self.y_cls_1 = np.ones((1, self.data_num))\n self.X_cls_1 = np.add(self.X_cls_1, [[np.random.randint(1,4)],[np.random.randint(8,10)]])\n\n self.X_cls_2 = np.random.randn(self.dim, self.data_num)\n self.y_cls_2 = -np.ones((1, self.data_num))\n self.X_cls_2 = np.add(self.X_cls_2, [[np.random.randint(7,10)],[np.random.randint(0,5)]])\n \n \n def add_data(self):\n \n self.data_X = np.concatenate((self.X_cls_1, self.X_cls_2), 1)\n self.data_y = np.concatenate((self.y_cls_1, self.y_cls_2), 1)\n\n\n def info(self):\n\n print('Data Shape: {}'.format(self.data_X.shape))\n print('Label Shape: {}'.format(self.data_y.shape))\n print('Class Num: {}'.format(2))\n","repo_name":"keyork/mc2022spring-perceptron","sub_path":"dataset/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"6460783505","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nimport time\r\n\r\n\r\npage = 1\r\n\r\n# initialize variables for total number of results and number of results scraped\r\nresults_scraped = 0\r\n\r\nurl = f\"https://www.amazon.com/s?k=Acer+Chromebook+Enterprise+Spin+714&page=4&crid=1UE647NGJBQAH&qid=1679758022&sprefix=acer+chromebook+enterprise+spin+714&ref=sr_pg_1\"\r\nHEADERS = ({'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',\r\n 'Accept-Language': 'en-US, en;q=0.5'})\r\n\r\nresponse = requests.get(url, headers=HEADERS)\r\nprint(response)\r\nsoup = BeautifulSoup(response.text, \"html.parser\")\r\n\r\ntotal_results_elem = soup.find(\r\n \"div\", {\"class\": \"a-section a-spacing-small a-spacing-top-small\"})\r\ntotal_results_span = total_results_elem.find_all(\"span\")[0]\r\ntotal_results_text = total_results_span.text.strip()\r\ntotal_results = int(total_results_text.split()[2].replace(\",\", \"\"))\r\nprint(f\"Total search results: {total_results}\")\r\n\r\n\r\nwhile True:\r\n url1 = f\"https://www.amazon.com/s?k=Acer+Chromebook+Enterprise+Spin+714&page={page}&crid=1UE647NGJBQAH&qid=1679758022&sprefix=acer+chromebook+enterprise+spin+714&ref=sr_pg_{page}\"\r\n response = requests.get(url1, headers=HEADERS)\r\n print(f\"Scraping page {page}...\")\r\n\r\n if response.status_code == 200:\r\n soup1 = BeautifulSoup(response.text, \"html.parser\")\r\n\r\n results = soup1.find_all(\r\n \"div\", {\"data-component-type\": \"s-search-result\"})\r\n\r\n final_results = results[2:]\r\n\r\n # loop through each search result on the page\r\n for result in final_results:\r\n name = result.find(\r\n \"span\", {\"class\": \"a-size-medium a-color-base a-text-normal\"}).text.strip()\r\n price = result.find(\"span\", {\"class\": \"a-price-whole\"})\r\n if price:\r\n price = price.text.strip()\r\n else:\r\n price = \"N/A\"\r\n\r\n url1 = \"http://127.0.0.1:3000/chrome_books\"\r\n headers = {\"Content-Type\": \"application/json; charset=utf-8\"}\r\n data = {\r\n \"name\": name,\r\n \"price\": price\r\n }\r\n response1 = requests.post(url1, headers=headers, json=data)\r\n print(\"Status Code\", response1.status_code)\r\n # print(\"JSON Response \", response1.json())\r\n # print(f\"Product name: {name}\")\r\n # print(f\"Price: {price}\")\r\n\r\n # increment the counter for the number of results scraped\r\n results_scraped += 1\r\n print(results_scraped)\r\n # check if we have scraped all the search results\r\n # if results_scraped >= total_results:\r\n # print(\"Finished scraping all search results.\")\r\n # break\r\n\r\n # break the loop if we have scraped all the search results\r\n if results_scraped >= total_results:\r\n break\r\n\r\n else:\r\n print(\r\n f\"Failed to scrape page {page} with status code {response.status_code}.\")\r\n\r\n # add a delay between requests to avoid getting blocked\r\n time.sleep(2)\r\n\r\n # increment page counter\r\n page += 1\r\n","repo_name":"katherine84522/AmazonScraper","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"13322575465","text":"import paho.mqtt.client as mqtt # Gör ett alias för paho.mqtt.client \n\nmqttBroker = \"test.mosquitto.org\" # Tilldelar mqttbroker samma brokerserver som ESP.\nclient = mqtt.Client(\"Android_Smartphone\") # Tilldelar variabeln client till mqtt-clienten. Hittar också på ett namn till client.\nclient.connect(mqttBroker) # Uppkopplar min client på samma server som ESPn genom inbygdda connectfunktion från paho.mqtt.client\n\ndef on_message(client, userdata, message): # Skriver ut meddelandet från ämnet som skickades till MQTTbrokerservern. \n print(\"-------------------------------------------\")\n print(\"[MESSAGE] :\", str(message.payload.decode(\"utf-8\")), \"\\nFrom the topic -\", message.topic)\n\n\"\"\"\nClient & Userdata argumenten behöver inte tas hänsyn till i detta fall. Det viktiga är meddelandet. \nSkriver ut payload av meddelandet och avkodar det samt vilket topic/ämne det handlar om. \n\"\"\"\n\nclient.subscribe(\"TheUnStoppAbleForce/BUTTON\") # Se nedan.\nclient.on_message = on_message \nclient.loop_forever() \n\n\"\"\" \nSubbar till samma topic/ämne som ESPn.\n.on_message funktionen från paho.mqtt.client tilldelas till min on_message-callback-funktion. \nSå länge vi får ett meddelande i topic/ämnet medans vi subscribar kommer on_message-funktionen att köras. \nloop_forever() är en del av paho.mqtt.client och körs tills användaren stänger ned programmet.\n\"\"\"","repo_name":"niklasmanzen/Small-Projects","sub_path":"Industrial IT & Comm/subESP.py","file_name":"subESP.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"sv","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"33859334769","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport time\nimport logging\nfrom typing import Dict, Any, List # noqa: F401\n\nfrom testing_config import BaseTestConfig\n\nfrom xrpld_netgen.network import (\n create_network_binary,\n update_node_binary,\n enable_node_amendment,\n)\n\nlogger = logging.getLogger(\"app\")\n\n\nclass TestINetGen(BaseTestConfig):\n def test_create_xahau_network(cls):\n create_network_binary(\n \"ED6ACA9949FC56CB07574C5AC9D29C8E62EB9D0752954F4D8953380EDB3EC46DC3\",\n \"ED74D4036C6591A4BDF9C54CEFA39B996A5DCE5F86D11FDA1874481CE9D5A1CDC1\",\n \"87BAB1FB62F8F665F58DD1C8293B11A4E20DA1E5C1C41CE65FAEB3A1E110B6D8\",\n \"JAAAAAFxIe1qyplJ/FbLB1dMWsnSnI5i650HUpVPTYlTOA7bPsRtw3Mh7VyccqnOn1TaZC6UI1WMJD4sH3HqEzvJkPDoEVRWGdowdkArhkDIKzi+W4+/8ry4RyGnsSC7bMZzKw4/TM70esOQTr9TZKhF1FaePva/Aitt3l2KnORLIALBVmZ1x3yAYr4CcBJA67ISzEFSkOIoyNvLWPdetIdN/xEekPJNp2hyhodt2cu0sr46wdXPMjIFO/cFfxTndxTyTW/R/29U92Dcly8nAg==\",\n \"xahau\", # protocol\n 4, # num validators\n 1, # num peers\n 21336, # network id\n \"https://build.xahau.tech\", # image host\n \"2023.11.9-dev+540\", # image name\n True,\n 3,\n )\n\n def _test_update_node(cls):\n update_node_binary(\n \"2023.11.9-dev+540-cluster\", # network name\n \"1\", # node id\n \"validator\", # node type\n \"https://build.xahau.tech\", # build server\n \"2023.12.1-dev+610\", # build version\n )\n\n def _test_enable_amendment(cls):\n enable_node_amendment(\n \"2023.11.9-dev+540-cluster\", # network name\n \"fix1623\", # amendment name\n \"2\", # node id\n \"validator\", # node type\n )\n","repo_name":"Transia-RnD/xrpld-network-gen","sub_path":"tests/integration/test_network.py","file_name":"test_network.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"26993034418","text":"from invman.nn.policy_net import PolicyNet\nfrom invman.env.lost_sales import get_model_fitness\nfrom invman.heuristics.lost_sales_heuristics import get_heuristic_policy_cost\nfrom invman.es_mp import train\n\n\ndef run(args):\n model = PolicyNet(input_dim=args.lead_time, hidden_dim=[20, 10], output_dim=args.max_order_size,\n activation=args.activation)\n print(\"Training started\", args.desc)\n model, fitness_hist = train(model=model, get_model_fitness=get_model_fitness, args=args)\n\n\nif __name__ == \"__main__\":\n from invman.config import get_config\n args = get_config()\n env_svbs, svbs_tc, state_action_svbs = get_heuristic_policy_cost(args, heuristic=\"standard_vector_base_stock\",\n seed=1234)\n max_order_size = max(state_action_svbs.values()) + 1\n desc = args.desc\n args.sigma_init = 5\n for env_horizon in [1e2, 5e2, 1e3, 5e3, 1e4]:\n args.horizon = int(env_horizon)\n for activation in [\"gelu\", 'selu']:\n args.activation = activation\n for order_ub in [max_order_size, 2*max_order_size, 3*max_order_size]:\n args.max_order_size = int(order_ub)\n args.desc = desc + f\"_lead_time_{args.lead_time}_{activation}\" + f'_{env_horizon}' + f'_order_ub_{order_ub}'\n args.exp_des = args.desc\n run(args)\n print(f\"finished {args.desc}\")","repo_name":"NimaMan/invman_public","sub_path":"scripts/lost_sales_exp.py","file_name":"lost_sales_exp.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"72671873382","text":"# 简单的替换使用replace\n# 复杂的使用re模块的sub()函数\nimport re\nfrom calendar import month_abbr\ntext3 = 'Today is 09/08/2018, tomorrow is 09/10/2018'\nresult = re.sub(r'(\\d+)/(\\d+)/(\\d+)', r'\\3-\\1-\\2', text3)\nprint(result)\n\n\n# 更加复杂的(比如要格式化输出),使用回调函数\ndef change_date(m):\n mon_name = month_abbr[int(m.group(1))]\n return '{} {} {}'.format(m.group(2), mon_name, m.group(3))\n\n\npattern = re.compile(r'(\\d+)/(\\d+)/(\\d+)')\nresult2 = pattern.sub(change_date, text3)\nprint(result2)","repo_name":"dalq/python-cookbook","sub_path":"cookbook/two/5FindAndReplace.py","file_name":"5FindAndReplace.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"42465607669","text":"import unittest\nfrom main import Solution\n\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass TestSolutionMethods(unittest.TestCase):\n\n\tsolution = Solution()\n\tdef test_mergeTwoLists(self):\n\t\t# leetcode test 1\n\t\tl1 = ListNode(1)\n\t\tl1.next = ListNode(2)\n\t\tl1.next.next = ListNode(4)\n\t\tl2 = ListNode(1)\n\t\tl2.next = ListNode(3)\n\t\tl2.next.next = ListNode(4)\n\t\tl3 = self.solution.mergeTwoLists(l1, l2)\n\t\tself.assertEqual(l3, l1)\n\t\twhile l3 != None:\n\t\t\tprint(str(l3.val) + '-->')\n\t\t\tl3 = l3.next\n\t\tprint(\"----------------------------\")\n\t\t# leetcode test 2\n\t\tl1 = ListNode(2)\n\t\tl2 = ListNode(1)\n\t\tl3 = self.solution.mergeTwoLists(l1, l2)\n\t\tself.assertEqual(l3, l2)\n\t\twhile l3 != None:\n\t\t\tprint(str(l3.val) + '-->')\n\t\t\tl3 = l3.next\n\n\t\t# customized test\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"seLain/codesnippets","sub_path":"python3/hackerrank_leetcode/merge_two_sorted_lists/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"2666226465","text":"import utils\n\n# Anzahl aller Knoten im Netzwerk\nnodes_number = 64\n# Anzahl der korrumpierten Knoten\ncorrupted_number = 32\n# Anzahl der Cluster im Netzwerk\ncluster_number = 16\n# Anzahl der ausgewählten Nodes pro Cluster\npicked_nodes_number = 4\n# Anzahl der Iterationen für die Simulation\niteration_number = 1000\n# Anzahl der gleichen Ergebnisse im gesamten Quorum\nthreshold = 0.5\n# Anzahl der gleichen Ergebnisse im Nested Quorum\nnested_threshold = 0.5\n\ndebug = False\n\nfor t in [[0.25,0.25], [0.25,0.5], [0.25,0.75], [0.5,0.5], [0.5,0.75], [0.75,0.25], [0.75,0.5], [0.75,0.75]]:\n\n successful_corrupted_number = 0\n threshold = t[0]\n nested_threshold = t[1]\n\n for _ in range(iteration_number):\n # Create clusters\n clusters = utils.create_clusters(nodes_number, cluster_number)\n if debug:\n print('clusters:' + str(clusters))\n\n # Create corrupted nodes\n corrupted_clusters = utils.create_equaly_corrupted_clusters(clusters, corrupted_number)\n if debug:\n print('corrupted clusters:' + str(corrupted_clusters))\n\n corrupted_clusters_after_selection = utils.select_nodes_in_clusters(corrupted_clusters, picked_nodes_number, debug)\n if debug:\n print('corrupted clusters after selection:' + str(corrupted_clusters_after_selection))\n\n successful_corrupted_cluster_number = 0\n for cluster in corrupted_clusters_after_selection:\n if sum(cluster) > (nested_threshold * picked_nodes_number):\n successful_corrupted_cluster_number += 1\n\n successful_corrupted_ratio = successful_corrupted_cluster_number / cluster_number\n if successful_corrupted_ratio > threshold:\n successful_corrupted_number += 1\n\n success_rate = successful_corrupted_number / iteration_number\n\n print('Picked nodes in cluster: ' + str(picked_nodes_number))\n print('Successful corrupted: ' + str(successful_corrupted_number))\n print('Successful corrupted ratio: ' + str(success_rate))\n print('-'*100)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"wake-0/accumulator-aggregations","sub_path":"simulation-nested-quorum-variable-network.py","file_name":"simulation-nested-quorum-variable-network.py","file_ext":"py","file_size_in_byte":2053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"42942856794","text":"def int_to_roman(num):\n values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]\n symbols = [\"M\", \"CM\", \"D\", \"CD\", \"C\", \"XC\", \"L\", \"XL\", \"X\", \"IX\", \"V\", \"IV\", \"I\"]\n\n result = \"\"\n for value, symbol in zip(values, symbols):\n while num >= value:\n result += symbol\n num -= value\n\n return result\n\nnum = 121\noutput = int_to_roman(num)\n\nprint(output)","repo_name":"Pavan1831/Rampup_Python","sub_path":"Task10.py","file_name":"Task10.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"33842976765","text":"from abc import ABC, abstractmethod\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import gridspec\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\nfrom ppprint.visualization.plot import Plot\nfrom ppprint.visualization.plot_extras import (\n val_per_bin,\n ci_per_bin,\n plot_errorbars,\n kl_via_binning,\n plot_kl,\n)\n\n\nclass PLengthDistributionPlot(Plot):\n PLOT_NAME = \"Protein Length Distribution\"\n SOURCE_TYPE = \"mdisorder pbased\"\n FILE_NAME = \"p_length_hist\"\n\n def _run(self, df: pd.DataFrame):\n # Add KL-heatmap to histogram\n gs = gridspec.GridSpec(nrows=1, ncols=2, width_ratios=[2, 1])\n ax1 = plt.subplot(gs[0])\n ax2 = plt.subplot(gs[1])\n fig = plt.gcf()\n fig.set_size_inches(9.5, 4.5)\n\n arg = \"protein length\"\n bins = np.arange(start=0, stop=2540, step=40)\n ax1 = sns.histplot(\n data=df,\n x=arg,\n hue=\"proteome\",\n palette=self.get_color_scheme(),\n kde=True,\n kde_kws={\n \"bw_adjust\": 0.3,\n \"gridsize\": 2000,\n },\n line_kws={\"lw\": 1.5},\n bins=bins,\n common_norm=False,\n stat=\"proportion\",\n alpha=0.5,\n edgecolor=(1.0, 1.0, 1.0, 0.5),\n linewidth=1.0,\n ax=ax1,\n )\n self.add_mean_to_legend(df, \"protein length\", ax1)\n ax1.set_xlim(-10, 2500)\n ax1.set_ylim(0.0, 0.12)\n\n # Calculate CIs and their positions\n all_cis = ci_per_bin(df, arg, bins)\n all_ys = val_per_bin(df, arg, bins)\n\n # Calculate centers of bins for plotting\n half = float(bins[1] - bins[0]) / 2\n bin_centers = [i + half for i in bins]\n\n # Plot the errorbars\n plot_errorbars(all_cis, bin_centers, all_ys, self.get_color_scheme(), ax1)\n\n # Calculate and plot KL\n df_kl = kl_via_binning(df, arg, bins)\n plot_kl(df_kl, self.get_proteome_names(), ax2)\n\n # Set true plot title\n ax1.set_title(self.PLOT_NAME)\n\n fig.tight_layout()\n\n def set_title(self):\n \"\"\"Overwrites title function for plots including a KL part.\"\"\"\n pass\n\n\nclass RLengthDistributionPlot(Plot):\n RELATIVE: bool = True\n MINLENGTH: float = -0.02\n MAXLENGTH: float = 1.0\n STEPSIZE: int = 0.02\n BW_ADJUST: float = 0\n\n # Maybe move down to child classes\n def _run(self, df: pd.DataFrame):\n # Add KL-heatmap to histogram\n gs = gridspec.GridSpec(nrows=1, ncols=2, width_ratios=[2, 1])\n ax1 = plt.subplot(gs[0])\n ax2 = plt.subplot(gs[1])\n fig = plt.gcf()\n fig.set_size_inches(9.5, 4.5)\n\n arg = \"rel reg length\" if self.RELATIVE else \"reg length\"\n bins = np.arange(\n start=0, stop=self.MAXLENGTH + (0.5 * self.STEPSIZE), step=self.STEPSIZE\n )\n df = df.loc[df[arg] <= self.MAXLENGTH]\n\n ax1 = sns.histplot(\n data=df,\n x=arg,\n hue=\"proteome\",\n palette=self.get_color_scheme(),\n bins=bins,\n kde=True,\n kde_kws={\n \"bw_adjust\": self.BW_ADJUST,\n \"gridsize\": 100,\n \"clip\": (self.MINLENGTH, self.MAXLENGTH),\n },\n common_norm=False,\n stat=\"proportion\",\n edgecolor=(1.0, 1.0, 1.0, 0.5),\n linewidth=1.0,\n alpha=0.4,\n discrete=False,\n ax=ax1,\n )\n\n self.add_mean_to_legend(df, arg, ax1)\n ylim = ax1.get_ylim()\n ax1.set_xlabel(\"Relative Region Length\" if self.RELATIVE else \"Region Length\")\n ax1.set_xlim(0, self.MAXLENGTH)\n ax1.set_ylim(bottom=0.0, top=(ylim[1] + 0.08))\n\n # Calculate CIs and their positions\n all_cis = ci_per_bin(df, arg, bins)\n all_ys = val_per_bin(df, arg, bins)\n\n # Calculate centers of bins for plotting\n half = float(bins[1] - bins[0]) / 2\n bin_centers = [i + half for i in bins]\n\n # Plot the errorbars\n plot_errorbars(all_cis, bin_centers, all_ys, self.get_color_scheme(), ax1)\n\n # Calculate and plot KL\n df_kl = kl_via_binning(df, arg, bins)\n plot_kl(df_kl, self.get_proteome_names(), ax2)\n\n # Set true plot title\n ax1.set_title(self.PLOT_NAME)\n\n fig.tight_layout()\n\n def set_title(self):\n \"\"\"Overwrites title function for plots including a KL part.\"\"\"\n pass\n\n\nclass RLengthDistributionPlotAbsMdisorder(RLengthDistributionPlot):\n PLOT_NAME = \"Disordered Region Length Distribution\"\n SOURCE_TYPE = \"mdisorder rbased\"\n FILE_NAME = \"mdisorder_r_length_hist_abs\"\n RELATIVE = False\n MINLENGTH = 30\n MAXLENGTH = 250\n STEPSIZE = 7\n BW_ADJUST: float = 0.3\n\n\nclass RLengthDistributionPlotAbsTmseg(RLengthDistributionPlot):\n PLOT_NAME = \"TMH Length Distribution\"\n SOURCE_TYPE = \"tmseg rbased\"\n FILE_NAME = \"tmseg_r_length_hist_abs\"\n RELATIVE = False\n MINLENGTH = 12\n MAXLENGTH = 35\n STEPSIZE = 1\n BW_ADJUST: float = 1.0\n\n\nclass RLengthDistributionPlotAbsProna(RLengthDistributionPlot):\n PLOT_NAME = \"Binding Region Length Distribution\"\n SOURCE_TYPE = \"prona rbased\"\n FILE_NAME = \"prona_r_length_hist_abs\"\n RELATIVE = False\n MINLENGTH = 6\n MAXLENGTH = 50\n STEPSIZE = 1\n BW_ADJUST: float = 0.7\n\n\nclass RLengthDistributionPlotRelMdisorder(RLengthDistributionPlot):\n PLOT_NAME = \"Relative Disordered Region Length Distribution\"\n SOURCE_TYPE = \"mdisorder rbased\"\n FILE_NAME = \"mdisorder_r_length_hist_rel\"\n BW_ADJUST: float = 0.6\n\n\nclass RLengthDistributionPlotRelTmseg(RLengthDistributionPlot):\n PLOT_NAME = \"Relative TMH Length Distribution\"\n SOURCE_TYPE = \"tmseg rbased\"\n FILE_NAME = \"tmseg_r_length_hist_rel\"\n BW_ADJUST: float = 0.8\n\n\nclass RLengthDistributionPlotRelProna(RLengthDistributionPlot):\n PLOT_NAME = \"Relative Binding Region Length Distribution\"\n SOURCE_TYPE = \"prona rbased\"\n FILE_NAME = \"prona_r_length_hist_rel\"\n BW_ADJUST: float = 0.8\n\n\nclass RLengthsPlotAbsMdisorderProna(Plot):\n PLOT_NAME = \"Distribution of Lengths of Disordered PBRs\"\n SOURCE_TYPE = \"mdisorder rbased\"\n FILE_NAME = \"mixed_mdis_prona_r_dpbr_lengths\"\n BW_ADJUST: float = 0.2\n RELATIVE = False\n MINLENGTH = 6\n MAXLENGTH = 51\n STEPSIZE = 5\n\n def overlap_for_pbr(self, df: pd.DataFrame):\n # One protein in this df -> step through/check for each PBR\n # Note: (1) this far, we used PBR length as number of residues to count (here we have RI)\n # (2) any overlap counts\n df_pbr = df[df[\"feature\"] == \"prona\"]\n df_dr = df[df[\"feature\"] == \"mdisorder\"]\n num_res_in_drs = 0\n res_in_drs_list = []\n for i in df_pbr.index:\n start = df_pbr.at[i, \"start\"]\n end = df_pbr.at[i, \"end\"]\n num_overlap = len(df_dr[~((df_dr[\"start\"] > end) | (df_dr[\"end\"] < start))])\n if num_overlap > 0:\n valid_length = end - start + 1\n num_res_in_drs += valid_length\n res_in_drs_list.append(valid_length)\n return num_res_in_drs\n\n def _run(self, df_mdisorder: pd.DataFrame):\n fig, ax1 = plt.subplots()\n\n df_prona = self.dataframes[\"prona rbased\"]\n df_sizes = (\n self.dataframes[\"mdisorder pbased\"][[\"proteome\", \"protein length\"]]\n .groupby(\"proteome\")\n .sum()\n )\n\n # Fraction of residues in DRs\n\n df_mdisorder_counts = (\n df_mdisorder[[\"proteome\", \"reg length\"]].groupby([\"proteome\"]).sum()\n )\n df_mdisorder_counts = df_mdisorder_counts.join(\n df_sizes, on=\"proteome\", how=\"left\"\n )\n df_mdisorder_counts[\"mdisorder content\"] = (\n df_mdisorder_counts[\"reg length\"] / df_mdisorder_counts[\"protein length\"]\n )\n\n # Fraction of disordered residues used in protein binding\n\n df_mdisorder[\"feature\"] = [\"mdisorder\"] * len(df_mdisorder)\n df_prona[\"feature\"] = [\"prona\"] * len(df_prona)\n df_all = pd.concat([df_mdisorder, df_prona])\n df_all[\"start\"], df_all[\"end\"] = zip(*df_all[\"region\"])\n\n # Calculate number of overlapping residues for each proteome\n grouped = df_all.groupby([\"proteome\", \"protein\"])\n\n overlap_series = grouped.apply(func=self.overlap_for_pbr)\n overlap_series.name = \"overlap\"\n hue = \"proteome\"\n dpbrs = overlap_series[overlap_series.notnull()]\n dpbrs = (\n dpbrs.apply(pd.Series)\n .reset_index()\n .melt(id_vars=[\"proteome\", \"protein\"])\n .dropna()[[\"proteome\", \"protein\", \"value\"]]\n )\n\n # bins = [6, 11, 16, 21, 26, 31, 41, 51, 101, max(111, max(dpbrs[\"value\"]))]\n bins = np.arange(\n start=0, stop=self.MAXLENGTH + (0.5 * self.STEPSIZE), step=self.STEPSIZE\n )\n dpbrs = dpbrs.loc[dpbrs[\"value\"] <= self.MAXLENGTH]\n\n ax1 = sns.histplot(\n data=dpbrs,\n x=\"value\",\n hue=hue,\n palette=self.get_color_scheme(),\n bins=bins,\n # kde=True,\n kde_kws={\n \"bw_adjust\": self.BW_ADJUST,\n \"bw_method\": \"scott\",\n \"gridsize\": 3000,\n \"clip\": (self.MINLENGTH, self.MAXLENGTH),\n # \"common_grid\": True, # not working\n },\n # common_grid=True, # not working\n common_norm=False,\n stat=\"proportion\",\n # edgecolor=(1.0, 1.0, 1.0, 0.5),\n alpha=0.8,\n fill=False,\n edgecolor=\"k\",\n linewidth=1.5,\n # cumulative=True,\n ax=ax1,\n )\n\n ax1.set_title(\"Distribution of Lengths of Disordered PBRs\")\n ax1.set_xlabel(\"Binding Region Length\")\n ax1.set_xlim(right=self.MAXLENGTH) # absolute lengths\n ylim = ax1.get_ylim()\n ax1.set_ylim(bottom=0.0, top=(ylim[1] + 0.01))\n ax1.set_xticks(bins)\n # self.rename_legend(ax1)\n self.add_mean_to_legend(dpbrs, \"value\", ax1)\n","repo_name":"isjuao/ppprint","sub_path":"ppprint/visualization/plot_length_distribution.py","file_name":"plot_length_distribution.py","file_ext":"py","file_size_in_byte":10165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"36372012626","text":"from django.urls import path\nfrom . import views\nfrom django.contrib.auth.views import LogoutView\n\nurlpatterns = [\n path('', views.store, name=\"store\"),\n path('cart/', views.cart, name=\"cart\"),\n path('checkout/', views.checkout, name=\"checkout\"),\n path('update_Item/', views.updateItem, name=\"update_Item\"),\n path('process_order/', views.processOrder, name=\"process_order\"),\n path('login/', views.LoginView.as_view(), name=\"login\"),\n path('login/register/', views.RegisterPage.as_view(), name=\"register\"),\n path('logout/', LogoutView.as_view(next_page='home'), name='logout'),\n \n]","repo_name":"Jibekxoxo/E-com","sub_path":"store/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"17778181180","text":"import aiodocker\nimport aiohttp.web\nimport asyncio\nimport logging\nimport typing\n\nimport interactive_widgets.backend.shield\nimport interactive_widgets.backend.contexts.context\nimport interactive_widgets.backend.rooms.get\nimport interactive_widgets.backend.rooms.room\n\n\n# Test Cases (xC = WebSocket x connected, xD = WebSocket x disconnected, IN = Instantiated, TD = Torn-Down):\n# - 1C, IN, 1D, TD\n# - 1C, 1D, IN, TD\n# - 1C, IN, 2C, 2D, 1D, TD\n# - 1C, 2C, IN, 2D, 1D, TD\n# - 1C, 2C, 2D, IN, 1D, TD\n# - 1C, IN, 2C, 1D, 2D, TD\n# - 1C, 2C, IN, 1D, 2D, TD\n# - 1C, IN, 1D, 2C, 2D, TD\n# - 1C, 1D, IN, 2C, 2D, TD\n# - 1C, 2C, 1D, IN, 2D, TD\n# - 1C, 1D, 2C, IN, 2D, TD\n# - 1C, 2C, 2D, 1D, IN, TD\n# - 1C, 2C, 1D, 2D, IN, TD\n# - 1C, 1D, 2C, 2D, IN, TD\n# - 1C, IN, 1D, TD, 2C, IN, 2D, TD\n# - 1C, 1D, IN, TD, 2C, IN, 2D, TD\n# - 1C, IN, 1D, 2C, TD, IN, 2D, TD\n# - 1C, 1D, IN, 2C, TD, IN, 2D, TD\n# - 1C, IN, 1D, TD, 2C, 2D, IN, TD\n# - 1C, 1D, IN, TD, 2C, 2D, IN, TD\n\n\nclass RoomConnection:\n\n def __init__(self, context: interactive_widgets.backend.contexts.context.Context, configuration: dict, rooms: typing.Dict[str, interactive_widgets.backend.rooms.room.Room], room_name: str, websocket: aiohttp.web.WebSocketResponse):\n self.context = context\n self.configuration = configuration\n self.rooms = rooms\n self.room_name = room_name\n self.websocket = websocket\n self.logger = logging.getLogger(\n self.configuration['logger_name_room_connection'])\n\n async def __aenter__(self):\n # The context manager in this class manages the instantiation and tear down of rooms.\n # It has been designed carefully s.t. no asynchronous race conditions can happen.\n # The first part ensures that a constructed (not necessarily instantiated) room exists\n # and is registered in the page's room dictionary (self.rooms). The new websocket of\n # this room connection is added to the room, resulting in either 1 websocket for new\n # rooms or more than 1 websockets for existing rooms. Since no asynchronous context\n # switch can happen, the room management and websocket attachment is asynchronously\n # atomic.\n try:\n room = self.rooms[self.room_name]\n self.logger.debug(f'Using existing room {self.room_name}...')\n except KeyError:\n self.logger.debug(f'Creating room {self.room_name}...')\n room = interactive_widgets.backend.rooms.get.get(\n self.configuration['type'],\n )(\n self.context,\n self.configuration,\n self.room_name,\n self._send_message,\n )\n self.rooms[self.room_name] = room\n\n self.logger.debug(f'Attaching websocket {id(self.websocket)}...')\n room.attach_websocket(self.websocket)\n try:\n await room.update()\n except:\n await interactive_widgets.backend.shield.shield(self._detach(room))\n raise\n\n return room\n\n async def __aexit__(self, *args, **kwargs):\n await interactive_widgets.backend.shield.shield(self._detach(self.rooms[self.room_name]))\n\n async def _detach(self, room: interactive_widgets.backend.rooms.room.Room):\n self.logger.debug(f'Detaching websocket {id(self.websocket)}...')\n room.detach_websocket(self.websocket)\n try:\n await room.update()\n finally:\n if room in self.rooms.values() and room.is_emtpy():\n self.logger.debug('Deleting room...')\n del self.rooms[self.room_name]\n\n async def _send_message(self, message):\n self.logger.debug('Sending message to all attached websockets...')\n for websocket in self.rooms[self.room_name].attached_websockets:\n self.logger.debug(\n f'Sending message to websocket {id(websocket)}...')\n await websocket.send_json(message)\n","repo_name":"h3ndrk/interactive-widgets-backend","sub_path":"interactive_widgets/backend/rooms/room_connection.py","file_name":"room_connection.py","file_ext":"py","file_size_in_byte":3941,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"35"} +{"seq_id":"30226314883","text":"# Wait for DB to be available\nimport time\nfrom psycopg2 import OperationalError as Psycopg2Error\n\nfrom django.db.utils import OperationalError\nfrom django.core.management.base import BaseCommand\n\n\nclass Command(BaseCommand):\n def handle(self, *args, **opitons):\n self.stdout.write(self.style.WARNING(\"Waiting for database...\"))\n db_up = False\n while db_up is False:\n try:\n self.check(databases=[\"default\"])\n db_up = True\n except (Psycopg2Error, OperationalError):\n self.stdout.write(\n self.style.WARNING(\"Database unavailable,waiting one second...\")\n )\n time.sleep(1)\n self.stdout.write(self.style.SUCCESS(\"Database connected!\"))\n","repo_name":"mehmethalis/scout","sub_path":"app/core/management/commands/wait_db.py","file_name":"wait_db.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"73226242660","text":"from django.core.management.base import BaseCommand, CommandError\nfrom googleads import adwords\nfrom wad_Campaign.models import Campaign\nimport suds\n\nclass Command ( BaseCommand ):\n help = 'Clear all shared Campaigns from AdWords.'\n \n def add_arguments ( self, parser ):\n pass\n# parser.add_argument( \n# '--sync',\n# action='store_true',\n# dest='syncvar',\n# default=False,\n# help='Sync database data with AdWords API for all campaigns.')\n \n \n def handle ( self, *args, **options ):\n\n client = adwords.AdWordsClient.LoadFromStorage()\n\n client.partial_failure = True\n\n # request a service object from the client object\n service = Campaign.serviceobj ( client )\n \n mutatestring_dellst = []\n \n # get a list of the campaigns\n campaigns = Campaign.listcampaigns ( client )\n \n # create a list of delete dictionaries\n for campaign in campaigns:\n mutatestring_dellst.append ( Campaign.deldict ( campaign['id'] ) )\n \n # if there are no campaigns in aw with status != remove, return\n if ( len ( mutatestring_dellst ) == 0 ):\n print ( 'Nothing to delete.' )\n return\n \n # call mutate for the list of deletes\n rslts = service.mutate ( mutatestring_dellst )\n \n # removes partial failure errors from rslts['value']\n rsltsvaluelst = []\n for campaignsuccess in rslts['value']:\n if campaignsuccess != \"\":\n rsltsvaluelst.append( campaignsuccess )\n rslts['value'] = rsltsvaluelst\n \n # prints the results of the clear operation\n print ( 'Campaign clear complete. Removed %s campaigns.' % len ( rslts['value'] ) )\n print ( 'Removed: ' )\n \n # prints each campaign that was successfully removed\n for campaignsuccess in rslts['value']:\n if campaignsuccess != \"\":\n print ( '%s %s Status: %s' % ( campaignsuccess['id'],\n campaignsuccess['name'],\n campaignsuccess['status'] ) )\n \n if 'partialFailureErrors' in rslts:\n # prints each campaign that threw an error\n print ( 'Failed to remove: ' )\n for campaignerror in rslts['partialFailureErrors']:\n print ( '%s %s Reason: %s' % ( campaigns[ int ( campaignerror['fieldPath'][11:12] ) ]['campaignId'],\n campaigns[ int ( campaignerror['fieldPath'][11:12] ) ]['name'],\n campaignerror['errorString'] ) )\n \n \n \n \n \n \n \n \n \n","repo_name":"btardio/wad","sub_path":"wad_Campaign/management/commands/campaign_aw_clear.py","file_name":"campaign_aw_clear.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"15541465042","text":"from __future__ import annotations\n\nimport math\nimport os\n\nimport pytest\n\nfrom scitbx import matrix\n\n\nclass SpotPredictor:\n def __init__(self, dials_regression):\n import dxtbx\n from iotbx.xds import integrate_hkl, xparm\n from rstbx.cftbx.coordinate_frame_converter import coordinate_frame_converter\n\n from dials.algorithms.spot_prediction import (\n IndexGenerator,\n ScanStaticRayPredictor,\n ray_intersection,\n )\n from dials.util import ioutil\n\n # The XDS files to read from\n integrate_filename = os.path.join(\n dials_regression, \"data\", \"sim_mx\", \"INTEGRATE.HKL\"\n )\n gxparm_filename = os.path.join(dials_regression, \"data\", \"sim_mx\", \"GXPARM.XDS\")\n\n # Read the XDS files\n self.integrate_handle = integrate_hkl.reader()\n self.integrate_handle.read_file(integrate_filename)\n self.gxparm_handle = xparm.reader()\n self.gxparm_handle.read_file(gxparm_filename)\n\n # Get the parameters we need from the GXPARM file\n models = dxtbx.load(gxparm_filename)\n self.beam = models.get_beam()\n self.gonio = models.get_goniometer()\n self.detector = models.get_detector()\n self.scan = models.get_scan()\n\n assert len(self.detector) == 1\n\n # print self.detector\n\n # Get crystal parameters\n self.space_group_type = ioutil.get_space_group_type_from_xparm(\n self.gxparm_handle\n )\n cfc = coordinate_frame_converter(gxparm_filename)\n a_vec = cfc.get(\"real_space_a\")\n b_vec = cfc.get(\"real_space_b\")\n c_vec = cfc.get(\"real_space_c\")\n self.unit_cell = cfc.get_unit_cell()\n self.ub_matrix = matrix.sqr(a_vec + b_vec + c_vec).inverse()\n\n # Get the minimum resolution in the integrate file\n self.d_min = self.detector[0].get_max_resolution_at_corners(self.beam.get_s0())\n\n # Get the number of frames from the max z value\n xcal, ycal, zcal = zip(*self.integrate_handle.xyzcal)\n self.scan.set_image_range(\n (\n self.scan.get_image_range()[0],\n self.scan.get_image_range()[0] + int(math.ceil(max(zcal))),\n )\n )\n\n # Create the index generator\n generate_indices = IndexGenerator(\n self.unit_cell, self.space_group_type, self.d_min\n )\n\n s0 = self.beam.get_s0()\n m2 = self.gonio.get_rotation_axis()\n fixed_rotation = self.gonio.get_fixed_rotation()\n setting_rotation = self.gonio.get_setting_rotation()\n UB = self.ub_matrix\n dphi = self.scan.get_oscillation_range(deg=False)\n\n # Create the ray predictor\n self.predict_rays = ScanStaticRayPredictor(\n s0, m2, fixed_rotation, setting_rotation, dphi\n )\n\n # Predict the spot locations\n self.reflections = self.predict_rays(generate_indices.to_array(), UB)\n\n # Calculate the intersection of the detector and reflection frames\n success = ray_intersection(self.detector, self.reflections)\n self.reflections.select(success)\n\n\n@pytest.fixture(scope=\"session\")\ndef spotpredictor(dials_regression):\n return SpotPredictor(dials_regression)\n\n\ndef test_dmin(spotpredictor):\n \"\"\"Ensure calculated d_min < d_min in integrate file\"\"\"\n d = [spotpredictor.unit_cell.d(h) for h in spotpredictor.integrate_handle.hkl]\n d_min = min(d)\n assert spotpredictor.d_min <= d_min\n\n\ndef test_miller_index_set(spotpredictor):\n \"\"\"Ensure we have the whole set of miller indices\"\"\"\n gen_hkl = {}\n for r in spotpredictor.reflections.rows():\n gen_hkl[r[\"miller_index\"]] = True\n for hkl in spotpredictor.integrate_handle.hkl:\n assert gen_hkl[hkl]\n\n\ndef test_rotation_angles(spotpredictor):\n \"\"\"Ensure the rotation angles agree with XDS\"\"\"\n\n # Create a dict of lists of xy for each hkl\n gen_phi = {}\n for r in spotpredictor.reflections.rows():\n hkl = r[\"miller_index\"]\n phi = r[\"phi\"]\n try:\n a = gen_phi[hkl]\n a.append(phi)\n gen_phi[hkl] = a\n except KeyError:\n gen_phi[hkl] = [phi]\n\n for hkl, xyz in zip(\n spotpredictor.integrate_handle.hkl, spotpredictor.integrate_handle.xyzcal\n ):\n\n xds_phi = (\n spotpredictor.scan.get_oscillation(deg=False)[0]\n + xyz[2] * spotpredictor.scan.get_oscillation(deg=False)[1]\n )\n\n # Select the nearest xy to use if there are 2\n my_phi = gen_phi[hkl]\n if len(my_phi) == 2:\n my_phi0 = my_phi[0]\n my_phi1 = my_phi[1]\n diff0 = abs(xds_phi - my_phi0)\n diff1 = abs(xds_phi - my_phi1)\n if diff0 < diff1:\n my_phi = my_phi0\n else:\n my_phi = my_phi1\n else:\n my_phi = my_phi[0]\n\n assert xds_phi == pytest.approx(my_phi, abs=0.1)\n\n\ndef test_beam_vectors(spotpredictor):\n \"\"\"Ensure |s1| == |s0|\"\"\"\n s0_length = matrix.col(spotpredictor.beam.get_s0()).length()\n for r in spotpredictor.reflections.rows():\n s1 = r[\"s1\"]\n s1_length = matrix.col(s1).length()\n assert s0_length == pytest.approx(s1_length, abs=1e-7)\n\n\ndef test_image_coordinates(spotpredictor):\n \"\"\"Ensure the image coordinates agree with XDS\"\"\"\n # Create a dict of lists of xy for each hkl\n gen_xy = {}\n for r in spotpredictor.reflections.rows():\n hkl = r[\"miller_index\"]\n xy = r[\"xyzcal.mm\"][0:2]\n xy = spotpredictor.detector[0].millimeter_to_pixel(xy)\n try:\n a = gen_xy[hkl]\n a.append(xy)\n gen_xy[hkl] = a\n except KeyError:\n gen_xy[hkl] = [xy]\n\n for hkl, xyz in zip(\n spotpredictor.integrate_handle.hkl, spotpredictor.integrate_handle.xyzcal\n ):\n\n xds_xy = (xyz[0] - 0.5, xyz[1] - 0.5)\n\n # Select the nearest xy to use if there are 2\n my_xy = gen_xy[hkl]\n if len(my_xy) == 2:\n my_xy0 = my_xy[0]\n my_xy1 = my_xy[1]\n diff0 = (matrix.col(xds_xy) - matrix.col(my_xy0)).length()\n diff1 = (matrix.col(xds_xy) - matrix.col(my_xy1)).length()\n if diff0 < diff1:\n my_xy = my_xy0\n else:\n my_xy = my_xy1\n else:\n my_xy = my_xy[0]\n\n assert xds_xy[0] == pytest.approx(my_xy[0], abs=0.1), (xds_xy, gen_xy[hkl])\n assert xds_xy[1] == pytest.approx(my_xy[1], abs=0.1), (xds_xy, gen_xy[hkl])\n","repo_name":"dials/dials","sub_path":"tests/algorithms/spot_prediction/test_spot_prediction.py","file_name":"test_spot_prediction.py","file_ext":"py","file_size_in_byte":6553,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"35"} +{"seq_id":"35348742038","text":"AIName = \"Buffalolololo\"\nAIAuthor = \"L G T Y Q Z\"\nAITargetCharacter = \"Edgewardo\"\n\nimport random\ncounter = 0\nattackMode = \"ranged\"\ndef loop(player, enemy):\n global counter\n global attackMode\n horizDistance = abs(player.getX() - enemy.getX())\n vertDistance = abs(player.getY() - enemy.getY())\n if attackMode == \"ranged\":\n if counter % 20 == 0:\n player.jump()\n if vertDistance < 0.75 and horizDistance > 3:\n if counter % 5 == 0:\n if player.getX() > enemy.getX():\n player.moveLeft()\n else:\n player.moveRight()\n player.proj()\n else:\n if player.getX() > enemy.getX() and player.getX() < 11:\n player.moveLeft()\n elif player.getX() < enemy.getX() and player.getX() > 3:\n player.moveRight()\n elif vertDistance < 0.75 and horizDistance > 1:\n if player.getX() > enemy.getX():\n player.moveLeft()\n else:\n player.moveRight()\n if enemy.getDamage() < 100:\n player.tilt()\n else:\n attackMode = \"melee\"\n elif vertDistance < 1 and horizDistance < 1:\n attackMode = \"melee\"\n elif 5 > (enemy.getY() + (enemy.getYVel() ** 2)/2) - \\\n player.getY() > 4 and horizDistance < 1:\n # Lookin' for that elusive explosion kill\n player.recover()\n elif attackMode == \"melee\":\n if player.getX() > enemy.getX():\n player.moveLeft()\n else:\n player.moveRight()\n if player.getY() > enemy.getY():\n player.jump()\n if vertDistance < 0.75 and horizDistance < 1.2:\n if random.random() < 0.5:\n player.jab()\n else:\n player.smash()\n elif horizDistance > 3:\n attackMode = \"ranged\"\n elif attackMode == \"recovery\":\n if player.getX() > 7:\n player.moveLeft()\n else:\n player.moveRight()\n if not player.jumped():\n player.jump()\n elif not player.recovered():\n player.recover()\n else:\n player.tilt()\n \n if abs(7 - player.getX()) < 4 and player.getY() <= 6:\n attackMode = \"ranged\"\n counter += 1\n if player.getY() > 6 or abs(player.getX() - 7) > 5:\n attackMode = \"recovery\"\n #print(\"THE POLICE\")\n","repo_name":"HHSProgrammingClub/smash-my-buttons","sub_path":"src/resources/sample AIs/EdgyZoningAI.py","file_name":"EdgyZoningAI.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"35"} +{"seq_id":"1359230872","text":"#September 12, 2018\n#This program will tell you what day of the week a date is when you put in the month, day and year.\n#0=Sunday, 1=Monday, and so forth.\n#Sources: none\n\nimport sys \nmonth = sys.argv[1] \nday = sys.argv [2]\nyear = sys.argv [3]\n\ny0 = int(year) - int((14 - int(month)) / 12)\nx = y0 + int(y0/4) - int(y0/100) + int(y0/400)\nm0 = int(month) + 12 * int((14 - int(month)) / 12) - 2\nresult = (int(day) + x + (31*m0) / 12) % 7\n\nprint (int(result))\n","repo_name":"kaki1104/Su-CS550","sub_path":"basic operations/calender.py","file_name":"calender.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"6049937198","text":"\"\"\"\nTests for meetups operations\n\"\"\"\n\nimport unittest\nimport json\nfrom ... import create_app\n\n\nclass MeetupTest(unittest.TestCase):\n \"\"\"class representing the meetups test case\"\"\"\n\n def setUp(self):\n '''initialize the app and define test variable'''\n self.app = create_app(config_name=\"testing\")\n self.client = self.app.test_client()\n self.app_context = self.app\n\n self.meetup = {\n \"created_on\": \"Thu, 10 Jan 2019 18:17:59 GMT\",\n \"host\": \"jkamz\",\n \"location\": \"Nairobi\",\n \"meetupId\": \"1\",\n \"occuring_on\": \"28th Jan\",\n \"summary\": \"Getting to know python\",\n \"tags\": \"python pythonista flask\",\n \"topic\": \"python\"\n }\n\n self.rsvp = {\n \"userId\": \"1\",\n \"response\": \"yes\"\n }\n\n def test_create_meetup(self):\n '''test the endpoint of creating new meetup'''\n\n res = self.client.post(\"api/v1/create_meetup\", data=json.dumps(self.meetup),\n content_type=\"application/json\")\n response_data = json.loads(res.data.decode())\n self.assertEqual(res.status_code, 200)\n self.assertTrue(response_data[\"data\"])\n self.assertIn(\"Meetup created successfully\", str(response_data))\n\n def test_get_one_meetup(self):\n '''test the endpoint for getting one meetup'''\n\n # first post/ create a meetup\n res = self.client.post(\"api/v1/create_meetup\", data=json.dumps(self.meetup),\n content_type=\"application/json\")\n self.assertEqual(res.status_code, 200)\n\n # get one meetup by id\n get_res = self.client.get(\"api/v1/meetups/1\")\n get_res_data = json.loads(get_res.data.decode())\n self.assertEqual(get_res.status_code, 200)\n self.assertEqual(get_res_data[\"meetup\"][1][\"message\"], \"success\")\n\n def test_non_existent_meetup(self):\n '''test when the given meetup id is non existent'''\n get_res = self.client.get(\"api/v1/meetups/353\")\n get_res_data = json.loads(get_res.data.decode())\n self.assertEqual(get_res.status_code, 404)\n self.assertEqual(get_res_data[\"message\"], \"meetup not found\")\n\n def test_get_all_meetups(self):\n '''test the endpoint for getting all meetups'''\n res = self.client.get(\"api/v1/meetups\")\n res_data = json.loads(res.data.decode())\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res_data[\"message\"], \"success\")\n\n def test_meetup_rsvp(self):\n '''test the endpoint for meetup rsvp'''\n res = self.client.post(\"api/v1/meetups/1/rsvps\", data=json.dumps(self.rsvp),\n content_type='application/json')\n res_data = json.loads(res.data.decode())\n self.assertEqual(res.status_code, 200)\n self.assertIn(\"attendance status confirmed\", str(res_data))\n","repo_name":"Ryan-Kabia/Questioner-1","sub_path":"app/tests/v1/test_meetups.py","file_name":"test_meetups.py","file_ext":"py","file_size_in_byte":2917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"2049353087","text":"import requests\nfrom lxml import etree\n\nprofile_url = \"https://anipython.com/user/profile/\"\n\n# 下面设置的 sessionid 以你自己实际获取的为准\nheaders = {\n \"Cookie\": \"sessionid=f11pwkldxclkjx3kt5tzixl4uyf5d3y2\"\n}\n\n# headers -> Cookie -> sessionid\n# dajngo 后端通过 sessionid 检验用户\nresponse = requests.get(url=profile_url, headers=headers)\nelement = etree.HTML(response.text)\nresult = element.xpath('//h3//text()')\nprint(result)\n# 输出: ['AniPython', '\\xa0的个人中心']\n","repo_name":"AniPython/ani","sub_path":"apps/crawler/code/crawler7_1.py","file_name":"crawler7_1.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"31574015566","text":"import os\nimport openai\nimport argparse\n\nMAX_INPUT_LENGTH = 50\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--input\", \"-i\", type=str, required=True)\n args = parser.parse_args()\n user_input = args.input\n\n print(f\"User input: {user_input}\")\n if user_input and len(user_input) < MAX_INPUT_LENGTH:\n get_movie_recommendation(user_input)\n else:\n raise ValueError(\n f\"Input length is too long. Must be under {MAX_INPUT_LENGTH}. Submitted input is {user_input}\"\n )\n\ndef get_movie_recommendation(prompt: str) -> str:\n # Load your API key from an environment variable or secret management service\n openai.api_key = os.getenv(\"OPENAI_API_KEY\")\n # export OPENAI_API_KEY=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\n enriched_prompt = f\"Recommend 3 movies with the topics of {prompt} with links to netflix\"\n print(enriched_prompt)\n\n response = openai.Completion.create(\n engine=\"text-davinci-003\", prompt=enriched_prompt, max_tokens=4000\n )\n\n # Extract output text.\n movie_list: str = response[\"choices\"][0][\"text\"]\n\n # Strip whitespace.\n movie_list = movie_list.strip()\n\n print(f\"Snippet: {movie_list}\")\n return movie_list\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"yolandamckee/you-favorite-AI-book-shelf","sub_path":"app/movie.py","file_name":"movie.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"32658637093","text":"from typing import Dict, Optional, Sequence, Tuple, Union\n\nfrom google.api_core.exceptions import NotFound\nfrom google.api_core.retry import Retry\nfrom google.cloud.redis_v1 import CloudRedisClient\nfrom google.cloud.redis_v1.gapic.enums import FailoverInstanceRequest\nfrom google.cloud.redis_v1.types import FieldMask, InputConfig, Instance, OutputConfig\nfrom google.protobuf.json_format import ParseDict\n\nfrom airflow import AirflowException, version\nfrom airflow.gcp.hooks.base import CloudBaseHook\n\n\nclass CloudMemorystoreHook(CloudBaseHook):\n \"\"\"\n Hook for Google Cloud Memorystore APIs.\n\n All the methods in the hook where project_id is used must be called with\n keyword arguments rather than positional.\n\n :param gcp_conn_id: The connection ID to use when fetching connection info.\n :type gcp_conn_id: str\n :param delegate_to: The account to impersonate, if any.\n For this to work, the service account making the request must have\n domain-wide delegation enabled.\n :type delegate_to: str\n \"\"\"\n\n def __init__(self, gcp_conn_id: str = \"google_cloud_default\", delegate_to: Optional[str] = None):\n super().__init__(gcp_conn_id, delegate_to)\n self._client = None # type: Optional[CloudRedisClient]\n\n def get_conn(self,):\n \"\"\"\n Retrieves client library object that allow access to Cloud Memorystore service.\n\n \"\"\"\n if not self._client:\n self._client = CloudRedisClient(credentials=self._get_credentials())\n return self._client\n\n @staticmethod\n def _append_label(instance: Instance, key: str, val: str) -> Instance:\n \"\"\"\n Append labels to provided Instance type\n\n Labels must fit the regex ``[a-z]([-a-z0-9]*[a-z0-9])?`` (current\n airflow version string follows semantic versioning spec: x.y.z).\n\n :param instance: The proto to append resource_label airflow\n version to\n :type instance: google.cloud.container_v1.types.Cluster\n :param key: The key label\n :type key: str\n :param val:\n :type val: str\n :return: The cluster proto updated with new label\n \"\"\"\n val = val.replace(\".\", \"-\").replace(\"+\", \"-\")\n instance.labels.update({key: val})\n return instance\n\n @CloudBaseHook.fallback_to_default_project_id\n def create_instance(\n self,\n location: str,\n instance_id: str,\n instance: Union[Dict, Instance],\n project_id: Optional[str] = None,\n retry: Optional[Retry] = None,\n timeout: Optional[float] = None,\n metadata: Optional[Sequence[Tuple[str, str]]] = None,\n ):\n \"\"\"\n Creates a Redis instance based on the specified tier and memory size.\n\n By default, the instance is accessible from the project's `default network\n `__.\n\n :param location: The location of the Cloud Memorystore instance (for example europe-west1)\n :type location: str\n :param instance_id: Required. The logical name of the Redis instance in the customer project with the\n following restrictions:\n\n - Must contain only lowercase letters, numbers, and hyphens.\n - Must start with a letter.\n - Must be between 1-40 characters.\n - Must end with a number or a letter.\n - Must be unique within the customer project / location\n :type instance_id: str\n :param instance: Required. A Redis [Instance] resource\n\n If a dict is provided, it must be of the same form as the protobuf message\n :class:`~google.cloud.redis_v1.types.Instance`\n :type instance: Union[Dict, google.cloud.redis_v1.types.Instance]\n :param project_id: Project ID of the project that contains the instance. If set\n to None or missing, the default project_id from the GCP connection is used.\n :type project_id: str\n :param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be\n retried.\n :type retry: google.api_core.retry.Retry\n :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if\n ``retry`` is specified, the timeout applies to each individual attempt.\n :type timeout: float\n :param metadata: Additional metadata that is provided to the method.\n :type metadata: Sequence[Tuple[str, str]]\n \"\"\"\n client = self.get_conn()\n parent = CloudRedisClient.location_path(project_id, location)\n instance_name = CloudRedisClient.instance_path(project_id, location, instance_id)\n try:\n instance = client.get_instance(\n name=instance_name, retry=retry, timeout=timeout, metadata=metadata\n )\n self.log.info(\"Instance exists. Skipping creation.\")\n return instance\n except NotFound:\n self.log.info(\"Instance not exists.\")\n\n if isinstance(instance, dict):\n instance = ParseDict(instance, Instance())\n elif not isinstance(instance, Instance):\n raise AirflowException(\"instance is not instance of Instance type or python dict\")\n\n self._append_label(instance, \"airflow-version\", \"v\" + version.version)\n\n result = client.create_instance(\n parent=parent,\n instance_id=instance_id,\n instance=instance,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n result.result()\n self.log.info(\"Instance created.\")\n return client.get_instance(name=instance_name, retry=retry, timeout=timeout, metadata=metadata)\n\n @CloudBaseHook.fallback_to_default_project_id\n def delete_instance(\n self,\n location: str,\n instance: str,\n project_id: Optional[str] = None,\n retry: Optional[Retry] = None,\n timeout: Optional[float] = None,\n metadata: Optional[Sequence[Tuple[str, str]]] = None,\n ):\n \"\"\"\n Deletes a specific Redis instance. Instance stops serving and data is deleted.\n\n :param location: The location of the Cloud Memorystore instance (for example europe-west1)\n :type location: str\n :param instance: The logical name of the Redis instance in the customer project.\n :type instance: str\n :param project_id: Project ID of the project that contains the instance. If set\n to None or missing, the default project_id from the GCP connection is used.\n :type project_id: str\n :param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be\n retried.\n :type retry: google.api_core.retry.Retry\n :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if\n ``retry`` is specified, the timeout applies to each individual attempt.\n :type timeout: float\n :param metadata: Additional metadata that is provided to the method.\n :type metadata: Sequence[Tuple[str, str]]\n \"\"\"\n client = self.get_conn()\n name = CloudRedisClient.instance_path(project_id, location, instance)\n self.log.info(\"Fetching Instance: %s\", name)\n instance = client.get_instance(name=name, retry=retry, timeout=timeout, metadata=metadata)\n\n if not instance:\n return\n\n self.log.info(\"Deleting Instance: %s\", name)\n result = client.delete_instance(name=name, retry=retry, timeout=timeout, metadata=metadata)\n result.result()\n self.log.info(\"Instance deleted: %s\", name)\n\n @CloudBaseHook.fallback_to_default_project_id\n def export_instance(\n self,\n location: str,\n instance: str,\n output_config: Union[Dict, OutputConfig],\n project_id: Optional[str] = None,\n retry: Optional[Retry] = None,\n timeout: Optional[float] = None,\n metadata: Optional[Sequence[Tuple[str, str]]] = None,\n ):\n \"\"\"\n Export Redis instance data into a Redis RDB format file in Cloud Storage.\n\n Redis will continue serving during this operation.\n\n :param location: The location of the Cloud Memorystore instance (for example europe-west1)\n :type location: str\n :param instance: The logical name of the Redis instance in the customer project.\n :type instance: str\n :param output_config: Required. Specify data to be exported.\n\n If a dict is provided, it must be of the same form as the protobuf message\n :class:`~google.cloud.redis_v1.types.OutputConfig`\n :type output_config: Union[Dict, google.cloud.redis_v1.types.OutputConfig]\n :param project_id: Project ID of the project that contains the instance. If set\n to None or missing, the default project_id from the GCP connection is used.\n :type project_id: str\n :param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be\n retried.\n :type retry: google.api_core.retry.Retry\n :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if\n ``retry`` is specified, the timeout applies to each individual attempt.\n :type timeout: float\n :param metadata: Additional metadata that is provided to the method.\n :type metadata: Sequence[Tuple[str, str]]\n \"\"\"\n client = self.get_conn()\n name = CloudRedisClient.instance_path(project_id, location, instance)\n self.log.info(\"Exporting Instance: %s\", name)\n result = client.export_instance(\n name=name, output_config=output_config, retry=retry, timeout=timeout, metadata=metadata\n )\n result.result()\n self.log.info(\"Instance exported: %s\", name)\n\n @CloudBaseHook.fallback_to_default_project_id\n def failover_instance(\n self,\n location: str,\n instance: str,\n data_protection_mode: FailoverInstanceRequest.DataProtectionMode,\n project_id: Optional[str] = None,\n retry: Optional[Retry] = None,\n timeout: Optional[float] = None,\n metadata: Optional[Sequence[Tuple[str, str]]] = None,\n ):\n \"\"\"\n Initiates a failover of the master node to current replica node for a specific STANDARD tier Cloud\n Memorystore for Redis instance.\n\n :param location: The location of the Cloud Memorystore instance (for example europe-west1)\n :type location: str\n :param instance: The logical name of the Redis instance in the customer project.\n :type instance: str\n :param data_protection_mode: Optional. Available data protection modes that the user can choose. If\n it's unspecified, data protection mode will be LIMITED_DATA_LOSS by default.\n :type data_protection_mode: google.cloud.redis_v1.gapic.enums.FailoverInstanceRequest\n .DataProtectionMode\n :param project_id: Project ID of the project that contains the instance. If set\n to None or missing, the default project_id from the GCP connection is used.\n :type project_id: str\n :param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be\n retried.\n :type retry: google.api_core.retry.Retry\n :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if\n ``retry`` is specified, the timeout applies to each individual attempt.\n :type timeout: float\n :param metadata: Additional metadata that is provided to the method.\n :type metadata: Sequence[Tuple[str, str]]\n \"\"\"\n client = self.get_conn()\n name = CloudRedisClient.instance_path(project_id, location, instance)\n self.log.info(\"Failovering Instance: %s\", name)\n\n result = client.failover_instance(\n name=name,\n data_protection_mode=data_protection_mode,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n result.result()\n self.log.info(\"Instance failovered: %s\", name)\n\n @CloudBaseHook.fallback_to_default_project_id\n def get_instance(\n self,\n location: str,\n instance: str,\n project_id: Optional[str] = None,\n retry: Optional[Retry] = None,\n timeout: Optional[float] = None,\n metadata: Optional[Sequence[Tuple[str, str]]] = None,\n ):\n \"\"\"\n Gets the details of a specific Redis instance.\n\n :param location: The location of the Cloud Memorystore instance (for example europe-west1)\n :type location: str\n :param instance: The logical name of the Redis instance in the customer project.\n :type instance: str\n :param project_id: Project ID of the project that contains the instance. If set\n to None or missing, the default project_id from the GCP connection is used.\n :type project_id: str\n :param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be\n retried.\n :type retry: google.api_core.retry.Retry\n :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if\n ``retry`` is specified, the timeout applies to each individual attempt.\n :type timeout: float\n :param metadata: Additional metadata that is provided to the method.\n :type metadata: Sequence[Tuple[str, str]]\n \"\"\"\n client = self.get_conn()\n name = CloudRedisClient.instance_path(project_id, location, instance)\n result = client.get_instance(name=name, retry=retry, timeout=timeout, metadata=metadata)\n self.log.info(\"Fetched Instance: %s\", name)\n return result\n\n @CloudBaseHook.fallback_to_default_project_id\n def import_instance(\n self,\n location: str,\n instance: str,\n input_config: Union[Dict, InputConfig],\n project_id: Optional[str] = None,\n retry: Optional[Retry] = None,\n timeout: Optional[float] = None,\n metadata: Optional[Sequence[Tuple[str, str]]] = None,\n ):\n \"\"\"\n Import a Redis RDB snapshot file from Cloud Storage into a Redis instance.\n\n Redis may stop serving during this operation. Instance state will be IMPORTING for entire operation.\n When complete, the instance will contain only data from the imported file.\n\n :param location: The location of the Cloud Memorystore instance (for example europe-west1)\n :type location: str\n :param instance: The logical name of the Redis instance in the customer project.\n :type instance: str\n :param input_config: Required. Specify data to be imported.\n\n If a dict is provided, it must be of the same form as the protobuf message\n :class:`~google.cloud.redis_v1.types.InputConfig`\n :type input_config: Union[Dict, google.cloud.redis_v1.types.InputConfig]\n :param project_id: Project ID of the project that contains the instance. If set\n to None or missing, the default project_id from the GCP connection is used.\n :type project_id: str\n :param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be\n retried.\n :type retry: google.api_core.retry.Retry\n :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if\n ``retry`` is specified, the timeout applies to each individual attempt.\n :type timeout: float\n :param metadata: Additional metadata that is provided to the method.\n :type metadata: Sequence[Tuple[str, str]]\n \"\"\"\n client = self.get_conn()\n name = CloudRedisClient.instance_path(project_id, location, instance)\n self.log.info(\"Importing Instance: %s\", name)\n result = client.import_instance(\n name=name, input_config=input_config, retry=retry, timeout=timeout, metadata=metadata\n )\n result.result()\n self.log.info(\"Instance imported: %s\", name)\n\n @CloudBaseHook.fallback_to_default_project_id\n def list_instances(\n self,\n location: str,\n page_size: int,\n project_id: Optional[str] = None,\n retry: Optional[Retry] = None,\n timeout: Optional[float] = None,\n metadata: Optional[Sequence[Tuple[str, str]]] = None,\n ):\n \"\"\"\n Lists all Redis instances owned by a project in either the specified location (region) or all\n locations.\n\n :param location: The location of the Cloud Memorystore instance (for example europe-west1)\n\n If it is specified as ``-`` (wildcard), then all regions available to the project are\n queried, and the results are aggregated.\n :type location: str\n :param page_size: The maximum number of resources contained in the underlying API response. If page\n streaming is performed per- resource, this parameter does not affect the return value. If page\n streaming is performed per-page, this determines the maximum number of resources in a page.\n :type page_size: int\n :param project_id: Project ID of the project that contains the instance. If set\n to None or missing, the default project_id from the GCP connection is used.\n :type project_id: str\n :param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be\n retried.\n :type retry: google.api_core.retry.Retry\n :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if\n ``retry`` is specified, the timeout applies to each individual attempt.\n :type timeout: float\n :param metadata: Additional metadata that is provided to the method.\n :type metadata: Sequence[Tuple[str, str]]\n \"\"\"\n client = self.get_conn()\n parent = CloudRedisClient.location_path(project_id, location)\n result = client.list_instances(\n parent=parent, page_size=page_size, retry=retry, timeout=timeout, metadata=metadata\n )\n self.log.info(\"Fetched instances\")\n return result\n\n @CloudBaseHook.fallback_to_default_project_id\n def update_instance(\n self,\n update_mask: Union[Dict, FieldMask],\n instance: Union[Dict, Instance],\n location: Optional[str] = None,\n instance_id: Optional[str] = None,\n project_id: Optional[str] = None,\n retry: Optional[Retry] = None,\n timeout: Optional[float] = None,\n metadata: Optional[Sequence[Tuple[str, str]]] = None,\n ):\n \"\"\"\n Updates the metadata and configuration of a specific Redis instance.\n\n :param update_mask: Required. Mask of fields to update. At least one path must be supplied in this\n field. The elements of the repeated paths field may only include these fields from ``Instance``:\n\n - ``displayName``\n - ``labels``\n - ``memorySizeGb``\n - ``redisConfig``\n\n If a dict is provided, it must be of the same form as the protobuf message\n :class:`~google.cloud.redis_v1.types.FieldMask`\n :type update_mask: Union[Dict, google.cloud.redis_v1.types.FieldMask]\n :param instance: Required. Update description. Only fields specified in ``update_mask`` are updated.\n\n If a dict is provided, it must be of the same form as the protobuf message\n :class:`~google.cloud.redis_v1.types.Instance`\n :type instance: Union[Dict, google.cloud.redis_v1.types.Instance]\n :param location: The location of the Cloud Memorystore instance (for example europe-west1)\n :type location: str\n :param instance_id: The logical name of the Redis instance in the customer project.\n :type instance_id: str\n :param project_id: Project ID of the project that contains the instance. If set\n to None or missing, the default project_id from the GCP connection is used.\n :type project_id: str\n :param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be\n retried.\n :type retry: google.api_core.retry.Retry\n :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if\n ``retry`` is specified, the timeout applies to each individual attempt.\n :type timeout: float\n :param metadata: Additional metadata that is provided to the method.\n :type metadata: Sequence[Tuple[str, str]]\n \"\"\"\n client = self.get_conn()\n\n if isinstance(instance, dict):\n instance = ParseDict(instance, Instance())\n elif not isinstance(instance, Instance):\n raise AirflowException(\"instance is not instance of Instance type or python dict\")\n\n if location and instance_id:\n name = CloudRedisClient.instance_path(project_id, location, instance_id)\n instance.name = name\n\n self.log.info(\"Updating instances: %s\", instance.name)\n result = client.update_instance(\n update_mask=update_mask, instance=instance, retry=retry, timeout=timeout, metadata=metadata\n )\n result.result()\n self.log.info(\"Instance updated: %s\", instance.name)\n","repo_name":"a0x8o/airflow","sub_path":"airflow/gcp/hooks/cloud_memorystore.py","file_name":"cloud_memorystore.py","file_ext":"py","file_size_in_byte":21580,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"35"} +{"seq_id":"33842312454","text":"import numpy as np\nimport argparse\nimport pysrt\nimport nltk\nimport os\nimport matplotlib.pyplot as plt\nfrom collections import Counter\n\n#from os import listdir, mkdir\n#from os.path import isfile, join, exists\n\nparser = argparse.ArgumentParser(description='The Embedded Topic Model')\nparser.add_argument('--srtPath', type=str, default='./../Data/AEC/SRT/SRT_SIGN/', help='Path where per-line files are located')\nparser.add_argument('--inputName', type=str, default='', help='Input File Name')\nparser.add_argument('--outputVideoPath', type=str, default='./../Data/AEC/Videos/Segmented_gestures/', help='Path where per-line files are located')\n#parser.add_argument('--fpsOutput', type=int, default=25, metavar='fpsO',help='Frames per second for the output file')\nparser.add_argument('--flgGesture', type=int, default=1, metavar='FLGES',help='Frames per second for the output file')\n\n\nargs = parser.parse_args()\n\nsrtPath = args.srtPath\ninputName = args.inputName\noutputVideoPath = args.outputVideoPath\n#fpsOutput = args.fpsOutput\nflgGesture = args.flgGesture\n\n\n\n### When defining VideoWriter (width, height)\n### When cropping the frames (height, width)\nvideoWidth = 220\nvideoHeight = 220\n\n\n### X1,Y1 .... X2, Y1\n### X1,Y2 .... X2, Y2\nx1 = 380\nx2 = x1 + videoHeight + 1#601\ny1 = 988\ny2 = y1 + videoWidth + 1\n\ncount = 0\n#Set begining of reading\n#cap.set(cv2.CAP_PROP_POS_MSEC,1000)\n\n\nif inputName == '':\n listFile = [ file for file in os.listdir(srtPath) if os.path.isfile(srtPath+file)]\nelse:\n listFile = [inputName]\n\n\nprint(srtPath,inputName,listFile)\n\ndictSigns = {}\nwords = []\nsignNumber = 0\n\n\nfor filePath in listFile:\n\n inputName = os.path.basename(filePath) # to get only the name without the path\n inputName = os.path.splitext(inputName)[0]\n outputFolder = outputVideoPath+inputName\n\n # Read SRT\n srtOriginal = pysrt.open(srtPath+inputName+'.srt', encoding='utf-8')#, encoding='iso-8859-1'\n\n ### Iterate over the SRT\n \n for line in srtOriginal:\n words.append(line.text)\n #print(dictSigns.keys())\n if line.text in dictSigns.keys():\n dictSigns[line.text]+=1\n else:\n dictSigns[line.text] = 1\n\n signNumber+=1\n\ncnt = Counter(words)\n\nprint(\"Unique signs \", len(dictSigns), \" total signs\", signNumber)\nprint(cnt)\n\nplt.hist(dictSigns.values(),bins=10)\nplt.xlabel(\"Number of instances\")\nplt.ylabel(\"Frequency\")\nplt.title(\"Instances per unique sign\")\nplt.show()\n\nwith open('stats.csv', 'w') as f:\n for key in dictSigns.keys():\n f.write(\"%s,%d\\n\"%(key,dictSigns[key]))","repo_name":"gissemari/PeruvianSignLanguage","sub_path":"0.Analysis/statsSRT.py","file_name":"statsSRT.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"35"} +{"seq_id":"41298045447","text":"\"\"\"\nЗадача 1. Машина 2\nМодернизируйте класс Toyota из прошлого урока. Атрибуты остаются такими же:\nцвет машины (например, красный),\nцена (один миллион),\nмаксимальная скорость (200),\nтекущая скорость (ноль).\n\nДобавьте два метода класса:\nОтображение информации об объекте класса.\nМетод, который позволяет устанавливать текущую скорость машины.\nПроверьте работу этих методов.\n\nЗадача 2. Семья\nРеализуйте класс «Семья», который состоит из атрибутов «Имя», Деньги» и «Наличие дома» и\nобъекты которого могут выполнять следующие действия:\nОтобразить информацию о себе.\nЗаработать денег (подаётся число, которое прибавляется к текущему значению денег).\nКупить дом (подаётся стоимость дома и необязательный аргумент «Скидка»). Вывести соответствующее сообщение об\nуспешной/неуспешной покупке дома.\nСоздайте как минимум один экземпляр класса и проверьте работу методов.\n\nПример работы программы (вывод информации, покупка дома, заработок, очередная покупка):\nFamily name: Common family\nFamily funds: 100000\nHaving a house: False\n\nTry to buy a house\nNot enough money!\n\nEarned 800000 money! Current value: 900000\nTry to buy a house again\nHouse purchased! Current money: 0.0\n\nFamily name: Common family\nFamily funds: 0.0\nHaving a house: True\n\"\"\"\n\ntask = int(input('Выберите какую задачу выполнить (1, 2, 3): '))\n\nif task == 1:\n # Задача 1\n print('=' * 40)\n\n import random\n\n class MyAuto():\n color = 'Red'\n price = '1600000'\n speed_max = '220'\n speed_curron = '100'\n\n def info_auto(self):\n print('Цвет: {color}\\nСтои��ост: {price}\\nМаксимальная скорость: {max_speed}\\nТекущая скорость: {cur_speed}'.format(\n color = self.color,\n price = self.price,\n max_speed = self.speed_max,\n cur_speed = self.speed_curron\n ))\n\n def curron(self):\n self.speed_curron = random.randint(0, 200)\n\n\n auto_1 = MyAuto()\n auto_2 = MyAuto()\n auto_1.curron()\n auto_1.info_auto()\n auto_2.info_auto()\n\n\n\n\n\nelif task == 2:\n # Задача 2\n print('=' * 40)\n print('Задача 2')\n\n\n class Family():\n surmane = 'Surname'\n money = 100000\n house = False\n\n def incom(self, salary):\n self.money += int(salary)\n print('Вы смогли отложить {} на дом. Сумма ваших накопдений {}'.format(salary, self.money))\n\n def bay_house(self, price, sale=0):\n price_house = price * sale / 100\n if price_house <= self.money:\n self.money -= price_house\n self.house = True\n print('Вы купили дом поздравляю за {} рублей. У Вас осталось денег {}'.format(price_house, self.money))\n else:\n print('Вы не купили дом за {} рублей. У Вас осталось денег {}'.format(price_house, self.money))\n\n def info_surname(self):\n print('Фамилия: {}\\nКапитал:{}\\nНаличие дома:{}\\n\\n'.format(self.surmane, self.money, self.house))\n\n\n family_1 = Family()\n family_2 = Family()\n family_1.surmane = 'Зиновкины'\n family_2.surmane = 'Петровы'\n family_1.info_surname()\n family_2.info_surname()\n family_1.incom(19 ** 6)\n family_1.bay_house(16 ** 6, 28)\n family_1.info_surname()\n family_2.incom(9 ** 5)\n family_2.bay_house(12 ** 5, 9)\n family_2.info_surname()\n\n\n\n\n\nelif task == 3:\n # Задача 3\n print('=' * 40)\n print('Задача 3')\n\nelse:\n print('Выберите задачу заново.')","repo_name":"ZinovkinIgor/-Skillbox","sub_path":"Модуль 24/Практика/lesson 24.3.py","file_name":"lesson 24.3.py","file_ext":"py","file_size_in_byte":4509,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"75197142820","text":"# Session3 - Operators and Conditions: Example 7.5.1 - Circle Going to The Right\n# SCRP\n# Daryl Dang\n\n# GLOBAL VARIABLES\nscreen_width = 500\nscreen_height = 500\ndiameter = 100\n\ndefault_inc_value = 5 # Default increment value\ninitial_x = diameter / 2\ninitial_y = diameter / 2\nx_pos = initial_x # Initial x position of circle\nx_inc_value = default_inc_value # Initial x increment value\ny_pos = initial_y # Initial y position of circle\n\ndef setup():\n size(screen_width, screen_height)\n background(0)\n \ndef draw():\n global x_pos, y_pos, x_inc_value\n\n # Redraw background\n background(0) # Black\n\n # Draw the circle\n circle(x_pos, y_pos, diameter)\n\n # Increment the position of the circle\n x_pos += x_inc_value\n","repo_name":"dellod/processing_examples","sub_path":"Session3 - Operators and Conditions/example7_5_1_circle_going_to_right/example7_5_1_circle_going_to_right.pyde","file_name":"example7_5_1_circle_going_to_right.pyde","file_ext":"pyde","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"71085231462","text":"import requests\nfrom bs4 import BeautifulSoup\nimport tqdm\nimport time\n\n\ndef get_people_links(url):\n response = requests.get(url)\n soup = BeautifulSoup(response.text, 'html.parser')\n \n base_url = 'https://en.wikipedia.org'\n\n people_links = []\n all_links = soup.find_all('a', href=True)\n\n for link in tqdm.tqdm(all_links):\n if '/wiki/' in link['href'] and ':' not in link['href']:\n time.sleep(0.3)\n possible_person_link = base_url + link['href']\n possible_person_page = requests.get(possible_person_link)\n soup_person = BeautifulSoup(possible_person_page.text, 'html.parser')\n bday = soup_person.find('span', {'class' : 'bday'})\n if bday:\n people_links.append(possible_person_link)\n \n return people_links\n\n\nif __name__ == '__main__': \n url = input(\"Enter a wikipedia url: \")\n links = get_people_links(url)\n with open(\"links.txt\", \"w\") as f:\n for link in links:\n f.write(link + \"\\n\")\n\n","repo_name":"calsaviour/longevity","sub_path":"modelling/dataset_generation/links.py","file_name":"links.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"4420031261","text":"#! /usr/bin/python3\n\nimport csv\nimport os\nimport urllib3\nimport requests\nimport re\nimport gzip\nimport shutil\nimport time\nconfig = dotenv_values(\".env\")\n\n\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\nYOU_TRACK_TOKEN = config.get(\"YOU_TRACK_TOKEN\")\nYOU_TRACK_PROJECT_ID = config.get(\"YOU_TRACK_PROJECT_ID\")\nYOU_TRACK_BASE_URL = config.get(\"YOU_TRACK_BASE_URL\")\nfilename = \"DATA.csv\"\nfileout = \"DATA1.csv\"\nbuffer = \"tar.csv.gz\"\n\n\ndef get_data_file():\n data_link = \"https://epss.cyentia.com/epss_scores-current.csv.gz\"\n response = requests.get(data_link)\n with open(buffer, 'wb') as f:\n f.write(response.content)\n with gzip.open(buffer, 'rb') as f_in:\n with open(filename, 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n\n\ndef info_data(filename):\n with open(filename) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n my_file = open(fileout, \"w\")\n for row in csv_reader:\n try:\n epss = str(round(float(str(100 / (1 / float(row[1])))[0:5]), 2))\n data = str(row[0] + ',' + epss + '\\n')\n my_file.write(data)\n except:\n pass\n my_file.close()\n\n\ndef payload(procent, id):\n headers = {\n \"Accept\": \"application/json\",\n \"Authorization\": \"Bearer {}\".format(YOU_TRACK_TOKEN),\n \"Content-Type\": \"application/json\"\n }\n request_payload = {\n \"project\": {\n \"id\": YOU_TRACK_PROJECT_ID\n },\n \"customFields\": [\n {\n \"name\": \"EPSS\",\n \"$type\": \"SimpleIssueCustomField\",\n \"value\": float(procent)\n }\n ]\n }\n url_differences = f'{YOU_TRACK_BASE_URL}/issues/{id}'\n diff = requests.post(url_differences, headers=headers, json=request_payload)\n print(diff.status_code) #DEBUG\n\n\n#--------------------------------------------MAIN-----------------------------------------------------------------------\nget_data_file()\ninfo_data(filename)\ncve_line = []\nprocent_line = []\nwith open(fileout) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n for row in csv_reader:\n cve_line.append(row[0])\n procent_line.append(row[1])\n\nmain_url = config.get(\"main_url\")\nheaders = {\n \"Accept\": \"application/json\",\n \"Authorization\": \"Bearer {}\".format(YOU_TRACK_TOKEN),\n \"Content-Type\": \"application/json\"\n}\nlist_summary = requests.get(main_url, headers=headers).json() # Получение задач с YouTrack\n\nbuff_cve_list = []\nbuff_id_list = []\nfor i in range(len(list_summary)):\n regex = re.search(r'CVE-\\d{4}-\\d{4,6}', str(list_summary[i]['summary']))\n if regex != None:\n buff_cve_list.append(str(regex.group()))\n buff_id_list.append(list_summary[i]['id'])\n\ncve_list = []\nprocent_list = []\nid_list = []\nfor i in range(len(cve_line)):\n for j in range(len(buff_cve_list)):\n if cve_line[i] == buff_cve_list[j]:\n cve_list.append(cve_line[i])\n procent_list.append(procent_line[i])\n id_list.append(buff_id_list[j])\n\nfor i in range(len(cve_list)):\n payload(procent_list[i], id_list[i])\n\n#----------------------------------REMOVE_BUFFER_FILES------------------------------------------------------------------\ntime.sleep(5)\nos.remove(filename)\nos.remove(fileout)\nos.remove(buffer)\n","repo_name":"eeenvik1/parsing_OpenCVE_for_YouTrack","sub_path":"app/adding_epss.py","file_name":"adding_epss.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"35"} +{"seq_id":"74694590499","text":"import pandas as pd\r\nimport re\r\nfrom rdflib import Graph\r\nimport numpy as np\r\n\r\ndata=pd.read_csv(\"claimreviews_db2.csv\",index_col=0)\r\n##Dropping non-str rows\r\nfilter=list(map(lambda x:type(x)!=str,data['rating_name']))\r\ndata.drop(data[filter].index,inplace=True)\r\n# data=data.loc[data['fact_checkerID']>1].reset_index(drop=True)\r\n# print(data.groupby('fact_checkerID').count())\r\ntrueregex=re.compile(r'(?i)^true|^correct$|^mostly true$|^geppetto checkmark$')\r\nfalseregex=re.compile(r'(?i)^false|^mostly false|^pants on fire$|^four pinocchios$|^no\\ |^no:|^distorts the facts|^wrong$')\r\ntrueind=data['rating_name'].apply(lambda x:trueregex.match(x)!=None)\r\ntrueclaims=list(data.loc[trueind]['claimID'])\r\nfalseind=data['rating_name'].apply(falseregex.match).apply(lambda x:x!=None)\r\nfalseclaims=list(data.loc[falseind]['claimID'])\r\n# data['label']=\"0\"\r\n# data.loc[trueind,'label']=True\r\n# data.loc[falseind,'label']=False\r\n# data2=data.filter(items=['label', 'claim_text'], axis=1)\r\n# data2=data2[data2['label']!=\"0\"]\r\n# data2.columns=[\"label\",\"text\"]\r\n# data2false=data2[data2['label']==False]\r\n# data2true=data2[data2['label']==True]\r\n# print(len(data2false))\r\n# n=len(data2true)\r\n# print(n)\r\n\r\n# data2false=data2false.sample(n=n, random_state=1)\r\n# frames=[data2true,data2false]\r\n# result = pd.concat(frames)\r\n# result.to_csv(\"claim_classify2.csv\",index=None)\r\ngraph = Graph()\r\ntruerror=[]\r\nfalserror=[]\r\nfor t in trueclaims:\r\n\tfilename=str(t)+\".rdf\"\r\n\ttry:\r\n\t\tgraph.parse(filename,format='application/rdf+xml')\r\n\texcept:\r\n\t\ttruerror.append(t)\r\ngraph.serialize(destination='truegraph.rdf', format='application/rdf+xml')\r\nprint(\"True Total:\",len(trueclaims))\r\nprint(\"True Errors:\",len(truerror))\r\nprint(\"True Delta:\",len(trueclaims)-len(truerror))\r\n\r\ngraph = Graph()\r\n\r\nfor f in falseclaims:\r\n\tfilename=str(f)+\".rdf\"\r\n\ttry:\r\n\t\tgraph.parse(filename,format='application/rdf+xml')\r\n\texcept:\r\n\t\tfalserror.append(f)\r\ngraph.serialize(destination='falsegraph.rdf', format='application/rdf+xml')\r\nprint(\"False Total:\",len(falseclaims))\r\nprint(\"False Errors:\",len(falserror))\r\nprint(\"False Delta:\",len(falseclaims)-len(falserror))\r\n\r\nnp.save(\"truerror_claimID.npy\",truerror)\r\nnp.save(\"falserror_claimID.npy\",truerror)\r\n# data=np.load(\"Error500_claimID.npy\")\r\n# print(len(data))\r\n\r\n# file=open(\"rnn final project.txt\",\"r\").readlines()\r\n# # test=list(map(lambda x: re.match(r\".*(TEST.*acc )(.*)\",x).group(2),file))\r\n# test=[]\r\n# dev=[]\r\n# for x in file:\r\n# \ttry:\r\n# \t\ttest.append(float(re.match(r\".*(TEST.*acc )(.*)\",x).group(2)))\r\n# \texcept:\r\n# \t\tcontinue\r\n# for x in file:\r\n# \ttry:\r\n# \t\tdev.append(float(re.match(r\".*(DEV.*acc )(.*)\",x).group(2)))\r\n# \texcept:\r\n# \t\tcontinue\r\n# print(len(test))\r\n# print(len(dev))\r\n# print(dev)\r\n# print(test)\r\n# plt.plot(test)\r\n# plt.title(\"Accuracy over Epochs for RNN\")\r\n# plt.xlabel(\"Epochs\")\r\n# plt.ylabel(\"Accuracy\")\r\n# plt.axhline(y=0.5,color=\"red\",label=\"random probability\")\r\n# plt.show()\r\n","repo_name":"Zoher15/Zoher-Python-Scripts","sub_path":"truefalse_separator.py","file_name":"truefalse_separator.py","file_ext":"py","file_size_in_byte":2921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"19035874542","text":"# # 네이버 검색 API예제는 블로그를 비롯 전문자료까지 호출방법이 동일하므로 blog검색만 대표로 예제를 올렸습니다.\n# # 네이버 검색 Open API 예제 - 블로그 검색\n# import os\n# import sys\n# import urllib.request\n#\n# def getPlaceInfo():\n# client_id = \"DpSDdXesQSkH8xftnxC1\"\n# client_secret = \"sAXJc9T_aI\"\n# encText = urllib.parse.quote(\"브레드박스 목동점\")\n# url = \"https://openapi.naver.com/v1/search/local?query=\" + encText # json 결과\n# request = urllib.request.Request(url)\n# request.add_header(\"X-Naver-Client-Id\",client_id)\n# request.add_header(\"X-Naver-Client-Secret\",client_secret)\n# response = urllib.request.urlopen(request)\n# rescode = response.getcode()\n# if(rescode==200):\n# response_body = response.read()\n# print(response_body.decode('utf-8'))\n# else:\n# print(\"Error Code:\" + rescode)\n#\n# getPlaceInfo()\n\n\nimport requests\nimport urllib, openpyxl, time\n\ndef placeInfo():\n # place = ['오늘은 지은다방', '장군집', '목동버거', '유진참치', '강고집해물품은찜', '원할머니보쌈족발 신정점']\n place = ['목동역 음식점']\n places = []\n for i in place:\n keyword = i\n\n url_keyword = urllib.parse.quote(keyword)\n\n try:\n\n for p in range(1, 45):\n response = requests.get(\n f'https://map.naver.com/v5/api/search?caller=pcweb&query={url_keyword}&type=all&page={p}&displayCount=10&lang=ko',\n headers={\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'}).json()\n\n numbers = response['result']['place']['list']\n # print(numbers[0])\n\n for i in range(0, len(numbers)):\n name = response['result']['place']['list'][i]['name']\n\n address = response['result']['place']['list'][i]['roadAddress']\n\n tel = response['result']['place']['list'][i]['telDisplay']\n\n menuinfo = response['result']['place']['list'][i]['menuInfo']\n\n description = response['result']['place']['list'][i]['description']\n link = response['result']['place']['list'][i]['link']\n\n # print(name, address, tel, menuinfo)\n print(link)\n\n places.append([name, address, tel, menuinfo])\n\n time.sleep(1)\n\n except:\n print('끝났습니다.')\n\n return places\n\n\nresult = placeInfo()\nprint(len(result))\n","repo_name":"iyk3333/crawlingServer","sub_path":"getPlaceListNaver.py","file_name":"getPlaceListNaver.py","file_ext":"py","file_size_in_byte":2666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"73701006499","text":"class Node:\n def __init__(self, value, next=None, prev=None):\n self.value = value\n self.next = next\n self.prev = prev\n\n\nclass DoublyLinkedList:\n def __init__(self):\n self.head = None\n self.tail = None\n self.size = 0\n\n def get_size(self):\n return self.size\n\n def is_empty(self):\n return self.size == 0\n\n def search_value(self, target):\n if self.is_empty():\n print(\"Linked List is Empty\")\n return\n node = self.head\n for i in range(self.size):\n if node.value == target:\n return i\n node = node.next\n return None\n\n def search_idx(self, idx):\n if self.is_empty():\n print(\"Linked List is Empty\")\n return\n elif idx < 0 or idx >= self.size:\n raise IndexError(\"Linked List index out of range\")\n else:\n if idx <= self.size // 2:\n node = self.head\n for i in range(idx):\n node = node.next\n else:\n node = self.tail\n for i in range(idx):\n node = node.prev\n return node.value\n\n def add_last(self, value):\n node = Node(value)\n if not self.head:\n self.head = node\n self.tail = node\n else:\n self.tail.next = node\n node.prev = self.tail\n self.tail = node\n self.size += 1\n\n def add_first(self, value):\n node = Node(value)\n if not self.head:\n self.head = node\n self.tail = node\n else:\n self.head.prev = node\n node.next = self.head\n self.head = node\n self.size += 1\n\n def insert(self, idx, value):\n if idx < 0 or idx > self.size:\n raise IndexError(\"Linked List index out of range\")\n if idx == 0:\n return self.add_first(value)\n elif idx == self.size:\n return self.add_last(value)\n else:\n new_node = Node(value)\n if idx <= self.size // 2:\n node = self.head\n for i in range(idx):\n node = node.next\n else:\n node = self.tail\n for i in range(self.size - (idx + 1)):\n node = node.prev\n new_node.prev = node.prev\n new_node.next = node\n node.prev = new_node\n new_node.prev.next = new_node\n self.size += 1\n\n def delete_last(self):\n if self.is_empty():\n raise IndexError(\"Linked List is Empty\")\n if self.get_size() == 1:\n self.head = None\n self.tail = None\n else:\n self.tail = self.tail.prev\n self.tail.next = None\n self.size -= 1\n\n def delete_first(self):\n if self.is_empty():\n raise IndexError(\"Linked List is Empty\")\n if self.get_size() == 1:\n self.head = None\n self.tail = None\n else:\n self.head = self.head.next\n self.head.prev = None\n self.size -= 1\n\n def remove(self, idx):\n if idx < 0 or idx > self.size:\n raise IndexError(\"Linked List assignment index out of range\")\n if idx == 0:\n return self.delete_first()\n elif idx == self.size:\n return self.delete_last()\n else:\n if idx <= self.size // 2:\n node = self.head\n for i in range(idx):\n node = node.next\n else:\n node = self.tail\n for i in range(self.size - (idx + 1)):\n node = node.prev\n node.prev.next = node.next\n node.next.prev = node.prev\n node.next = None\n node.prev = None\n self.size -= 1\n\n def reverse(self):\n temp = None\n node = self.head\n self.tail = node\n while node is not None:\n temp = node.prev\n node.prev = node.next\n node.next = temp\n node = node.prev\n if temp is not None:\n self.head = temp.prev\n\n def traverse(self):\n if self.is_empty():\n print(\"Linked List is Empty\")\n return\n node = self.head\n while node.value:\n print('data >', node.value)\n node = node.next\n if node == self.tail.next:\n break\n\n\nif __name__ == '__main__':\n d_list = DoublyLinkedList()\n print(d_list.is_empty())\n d_list.insert(0, 5)\n d_list.add_last(12)\n d_list.add_last(23)\n d_list.add_first(3)\n d_list.add_first(8)\n d_list.insert(1, 9)\n d_list.delete_last()\n d_list.remove(1)\n d_list.traverse()\n print(d_list.search_idx(2))\n print(d_list.search_value(12))\n d_list.reverse()\n d_list.traverse()\n print(d_list.head.value, d_list.tail.value)\n\n# True\n# data > 8\n# data > 3\n# data > 5\n# data > 12\n# 5\n# 3\n# data > 12\n# data > 5\n# data > 3\n# data > 8\n# 12 8\n","repo_name":"toutelajourn6e/Data-Structures","sub_path":"Data Structures/Linked List/Doubly Linked List/Doubly_LL.py","file_name":"Doubly_LL.py","file_ext":"py","file_size_in_byte":5063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"20604833173","text":"#######################################################################\n# This script compares the speed of the computation of a polynomial\n# for different libraries: numpy, numexpr and numba.\n#\n# Author: Francesc Alted\n# Date: 2013-09-04\n# Updated: 2016-09-01\n#######################################################################\n\nimport math\nfrom numba import double, jit\nfrom time import time\nimport numpy as np\nimport numexpr as ne\n\n\nN = 100*1000*1000 # number of points to evaluate\nx = np.linspace(-10, 10, N) # vector x in range [-1, 1]\n\n# The different expressions supported\nexpr = [\n \".25*x**3 + .75*x**2 - 1.5*x - 2\", # 0) the polynomial to compute\n \"((.25*x + .75)*x - 1.5)*x - 2\", # 1) a computer-friendly polynomial\n \"x\", # 2) the identity function\n \"sin(x)**2 + cos(x)**2\", # 3) a transcendental function\n ]\n\n# Set here the index of the expression to compute\nto_compute = 1\n\nne.set_num_threads(4) # the number of threads for numexpr\n\n# A function that is going to be accelerated by numba\ndef poly(x):\n y = np.empty(N, dtype=np.float64)\n if to_compute == 0:\n for i in range(N):\n y[i] = 0.25*x[i]**3 + 0.75*x[i]**2 + 1.5*x[i] - 2\n elif to_compute == 1:\n for i in range(N):\n y[i] = ((0.25*x[i] + 0.75)*x[i] + 1.5)*x[i] - 2\n elif to_compute == 2:\n for i in range(N):\n y[i] = x[i]\n elif to_compute == 3:\n for i in range(N):\n y[i] = math.sin(x[i])**2 + math.cos(x[i])**2\n return y\n\n\nprint(\"Using expression: %s\" % expr[to_compute], \"with:\", N, \"points\")\nprint()\nprint(\"*** Running numpy!\")\nstart = time()\nif \"sin\" in expr[to_compute]:\n y = np.sin(x)**2 + np.cos(x)**2\nelif \"x\" == expr[to_compute]:\n # Trick to force a copy with NumPy\n y = x.copy()\nelse:\n y = eval(expr[to_compute])\ntnumpy = time() - start\nprint(\"Result from numpy is %s in %s sec\" % (y, round(tnumpy,3)))\n\nprint()\nprint(\"*** Running numexpr!\")\nstart = time()\ny = ne.evaluate(expr[to_compute], optimization='aggressive')\ntnumexpr = time() - start\nprint(\"Result from numexpr is %s in %s sec\" % (y, round(tnumexpr, 3)))\n\nprint()\nprint(\"*** Running numba!\")\nstart = time()\ncpoly = jit(double[:](double[:]))(poly)\ntcompile = time() - start\nprint(\"Compilation time for numba:\", round(tcompile, 3))\n\nstart = time()\ncpoly(x)\ntnumba = time() - start\nprint(\"Result from numba is %s in %s sec\" % (y, round(tnumba,3)))\n\n# print()\n# print(\"*** Running poly with native python!\")\n# start = time()\n# poly(x)\n# tpython = time() - start\n# print(\"Result from python is %s in %s sec\" % (y, round(tpython, 3)))\n\n\nprint()\nprint(\"*** Speedup summary:\")\nprint(\"numexpr vs numpy speedup is %s\" % (tnumpy / tnumexpr))\nprint(\"numba vs numpy speedup is %s\" % (tnumpy / (tcompile + tnumba)))\n#print(\"numba vs python speedup is %s\" % (tpython / tnumpy))\nprint()\n","repo_name":"FrancescAlted/ASPP-2016","sub_path":"MemoryBoundComputation/exercises/poly-numba.py","file_name":"poly-numba.py","file_ext":"py","file_size_in_byte":2887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"17545267527","text":"import numpy as np\r\ndef load_car():\r\n # Import MNIST data\r\n fac = 0.99 / 4\r\n data = np.loadtxt(\"CarBinary.csv\",delimiter=\",\",max_rows=1000)\r\n # Training data, only\r\n X = np.asfarray(data[:, 1:7]) * fac + 0.01\r\n y = [int(x[0]) for x in np.asfarray(data[:, 7:])]\r\n # change y [1D] to Y [2D] sparse array coding class\r\n n_examples = len(y)\r\n labels = np.unique(y)\r\n Y = np.zeros((n_examples, len(labels)))\r\n for ix_label in range(len(labels)):\r\n # Find examples with with a Label = lables(ix_label)\r\n ix_tmp = np.where(y == labels[ix_label])[0]\r\n Y[ix_tmp, ix_label] = 1\r\n return X, Y, labels, y\r\n\r\n","repo_name":"omergencer/Multi-LayerPerceptron","sub_path":"read_car.py","file_name":"read_car.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"25489932361","text":"import numpy as np\nfrom numpy import loadtxt\nimport os\nimport math\nimport matplotlib.pyplot as plt\nimport emcee\nimport scipy.ndimage.filters as filters\nfrom params_MOT import MOT_image\nimport pandas as pd\nfrom scipy.optimize import curve_fit\nfrom params_MOT.model import *\n\ndef gaussian_1d(z, center_z, sigma_z, amplitude):\n '''\n Gaussian function in 1D\n \n\tReturns a standard Gaussian function with a single peak.\n \n Keyword arguments:\n z\t\t\t-- Input\n\tcenter_z\t-- mean\n\tsigma_z\t\t-- standard deviation\n\tamplitude\t-- amplitude\n '''\n return amplitude*np.exp(-(z-center_z)**2/(2*sigma_z**2))\n\ndef gaussian_2d(x, y, center_x, center_y, amplitude, sigma_x, sigma_y):\n '''\n Gaussian function in 2D\n \n\tReturns a product of two gaussians, one in x and one in y. Uses the function gaussian_1d defined before.\n \n Keyword arguments:\n x,y\t\t\t\t\t-- Inputs\n\tcenter_x, center_y\t-- means\n\tsigma_x, sigma_y\t-- standard deviation\n\tamplitude\t\t\t-- amplitude\n '''\n return amplitude*gaussian_1d(x, center_x, sigma_x, 1)*gaussian_1d(y,center_y,sigma_y,1)\n\ndef Image_with_CCD_readout_charge(image, readout_charge):\n '''\n\tFunction to add CCD readout image noise to an image of a captured MOT.\n\tThis noise is accumulated vertically, which is why the array image is flipped over when calculating the variable charge.\n\t\n\tKeyword arguments:\n\timage\t\t\t-- Input image, in the form of a 2D arrays\n\treadout_charge\t-- parameter controling amount of noise\n\t'''\n charge=(np.cumsum(image[::-1],axis=0)/readout_charge)\n return image + charge[::-1]\n\ndef MOT_bare_model(x, y, theta):\n '''\n\tFunction to unpack the parameter array theta and insert them into the Gaussian 2D model.\n\tThis gives the \"bare\" or perfect model of the MOT without any noise.\n\tAlso adds a background offset.\n\t\n\tKeyword arguments:\n\ttheta\t-- model parameter array (center_x, center_y, amplitude, sigma_x, sigma_y, background_offset, sigma_m, sigma_g).\n These are parameters for the function gaussian_2d (see above) plus background offset, which is a general offset added to the overall data.\n\t'''\n center_x, center_y, amplitude, sigma_x, sigma_y, background_offset, sigma_m, readout_charge = theta\n\t\n return gaussian_2d(x, y, center_x, center_y, amplitude, sigma_x, sigma_y) + background_offset\n\ndef background(image_size,offset,scattered_light):\n '''\n\tFunction to generate background, which will be processed later using params_MOT.detected\n\t\n\tKeyword arguments:\n\timage_size\t\t-- size of image data, usually 50*50 in our experiment\n\toffset\t\t\t-- overall offset to be added \n\tscattered_light\t-- parameter characterizing magnitude of scattered light on CCD\n\t'''\n N=image_size\n return np.add([[scattered_light for i in range(N)] for j in range(N)],offset)\n\t\ndef detected(model):\n '''\n Function to add random Poissonian noise to the MOT model.\n\n Keyword arguments:\n model\t-- image of MOT, consisting of a 2D array size 50*50\n '''\n return np.random.poisson(model)\n\n\n# Functions for Bayesian inference:\n\t\ndef log_likelihood(theta, x, y, data):\n '''\n Function to define log-likelihood for Bayesian inference.\n \n Keyword arguments:\n x, y\t-- independent data (arrays of size 50 for the 50x50 pixel image size)\n data\t-- measurements (brightness of pixel), consisting of 2D array of size image_size*image_size\n theta\t-- model parameter array (center_x, center_y, amplitude, sigma_x, sigma_y, background_offset, sigma_m, sigma_g).\n '''\n center_x, center_y, amplitude, sigma_x, sigma_y, background_offset, sigma_m, readout_charge = theta\n MOT_model = Image_with_CCD_readout_charge(MOT_bare_model(x, y, theta), readout_charge) # Model is the bare model plus some CCD noise added on.\n\t\n \n return np.sum(-0.5*(data - MOT_model)**2/(sigma_m**2) - 0.5*np.log(2*np.pi*(sigma_m**2)))\n \ndef log_prior(theta):\n \"\"\"\n Function to return log of prior probability distribution.\n \n Keyword arguments:\n theta\t-- model parameter array (center_x, center_y, amplitude, sigma_x, sigma_y, background_offset, sigma_m, sigma_g).\n \"\"\"\n # unpack the model parameters\n center_x, center_y, amplitude, sigma_x, sigma_y, background_offset, sigma_m, readout_charge = theta\n\n # Work with a generally uninformative prior:\n # This means simply impose boundaries that make physical sense (amplitude > 0 or readout_charge > 1)\n # or limited by the apparatus (in a sense also physical; for example the centers or sigmas should be within the confines of the\n # CCD camera, i.e., smaller than image_size, which is taken to be 50)\n\n # TO DO: have a set of parameters that describe the apparatus also gets passed along, like theta. This way we can set limits on\n # the priors in a more general way (for ex, use the image_size variable to define the limits of the centers or sigmas)\n\n # NOTE: In practice we observed occasional \"bad\" sigma fits if we actually choose the range [0, 50]. Go with [3, 40] instead.\n\n if center_x > 40 or center_x < 3: # Limited by CCD size\n return -math.inf\n if center_y > 40 or center_y < 3: # Limited by CCD size\n return -math.inf\n if amplitude > 1000 or amplitude < 0: # Limited CCD saturation limit\n return -math.inf\n if sigma_x > 40 or sigma_x < 3: # Limited by CCD size\n return -math.inf\n if sigma_y > 40 or sigma_y < 3: # Limited by CCD size\n return -math.inf\n if sigma_m > 1000 or sigma_m < -1000: # Limited CCD saturation limit\n return -math.inf\n if background_offset > 450 or background_offset < -500: # Limited CCD saturation limit\n return -math.inf\n if readout_charge > 2000 or readout_charge < 1: # Limited CCD saturation limit\n return -math.inf\n \n return 0\n \ndef log_posterior(theta, x, y, data):\n '''\n Function to return log of posterior probability distribution. From Bayes' theorem we obtain that the posterior probability is the product of the prior and likelihood, so for the log posterior we sum the log of the prior and log of the likelihood.\n\t\n Keyword arguments:\n x, y\t-- independent data (arrays of size 50 for the 50x50 pixel image size)\n data\t-- measurements (brightness of pixel), consisting of 2D array of size image_size*image_size\n theta\t-- model parameter array (center_x, center_y, amplitude, sigma_x, sigma_y, background_offset, sigma_m, sigma_g).\n '''\n \n center_x, center_y, amplitude, sigma_x, sigma_y, background_offset, sigma_m, readout_charge = theta\n \n return log_prior(theta) + log_likelihood(theta, x, y, data)\n\n# For emcee\n\ndef sampler(data, ndim, nwalkers, nsteps, image_size, initial_guess):\n '''\n Function which runs the MCMC sampler for parameter search.\n\t\n Keyword arguments:\n data\t\t-- measurements (brightness of pixel), consisting of 2D array of size 50*50\n ndim\t\t-- number of dimensions in MCMC, corresponding to number of parameters being marginalized over.\n nwalkers\t-- number of walkers in MCMC.\n nsteps\t\t-- number of steps in MCMC\n image_size\t-- size of image in data.\n init_guess\t-- initial guess for optimal parameters, an array of length 8 consisting of (center_x, center_y, amplitude, sigma_x, sigma_y, background_offset, sigma_m, sigma_g). This is the same structure as variable theta in other functions in this package.\n '''\n # Set up the data\n x = np.linspace(1, image_size, image_size)\n y = np.linspace(1, image_size, image_size)\n x, y = np.meshgrid(x, y)\n\n ndim = ndim\n nwalkers = nwalkers\n nsteps = nsteps\n\n starting_positions = [initial_guess + 1e-1*np.random.randn(ndim) for i in range(nwalkers)]\n \n # set up the sampler object\n sampler = emcee.EnsembleSampler(nwalkers, ndim, log_posterior, args=(x, y, data))\n \n # run the sampler. We use iPython's %time directive to tell us \n # how long it took (in a script, you would leave out \"%time\")\n sampler.run_mcmc(starting_positions, nsteps)\n \n return sampler\n\ndef func_quad(x, b, m):\n '''\n Function which defines a quadratic equation (without the linear term)\n\n Keyword arguments:\n m, b\t\t-- constants.\n x\t\t -- variable.\n '''\n return m * x**2 + b\n\ndef print_results_quad(b, m, covarianceM):\n '''\n Function that prints a quadratic equation, including uncertainties, given its constants and covariance matrix\n\n Keyword arguments:\n m, b\t\t-- constants.\n covarianceM -- covariance matrix.\n '''\n print (\"The covariance matrix is \\n\",covarianceM)\n print(\"\\n\")\n print (\"The fitted model, including uncertainties is (%0.4f +- %0.4f)x^2 + (%0.0f +- %0.0f)\"\n %(m, np.sqrt(covarianceM[1][1]), b, np.sqrt(covarianceM[0][0])))\n print(\"\\n\")\n\ndef quad_fit(data, x_name = \"time\", y_name = \"sigma_x\", suppressMessages = True):\n '''\n Function that does the fitting to a quadratic function (without the linear part)\n\n Keyword arguments:\n data\t\t-- panda data frame containing the relevant data\n x_name -- the name of the column containing the x data\n y_name -- the name of the column containing the y data\n suppressMessages\t\t-- Boolean which indicates whether or not messages, including plots, should be output.\n '''\n x = data[x_name].as_matrix()\n y = data[y_name].as_matrix()\n sigma = data['sigma_' + y_name].as_matrix()\n\n popt, cov = curve_fit(func_quad, xdata = x, ydata = y, sigma = sigma, method='lm')\n\n b, m = popt\n if(not suppressMessages):\n print_results_quad(b, m, cov)\n\n return [b, m]\n\ndef find_MOT_temp (q, pixel_distance_ratio, time_conversion_ratio, max_power, suppressMessages):\n '''\n Function that returns the temperatures corresponding to each direction, as well as a total temperature.\n\n Keyword arguments:\n q\t\t -- array containing MOT_object and fitted sigma_x and sigma_y, as returned by find_params_MOT(s)\n pixel_distance_ratio -- value giving the conversion ratio between pixel and physical distance\n time_conversion_ratio -- value scaling time\n max_power -- maximum power; Note that the number as given by the MOT_image power attribute is a fraction of this max_power\n suppressMessages\t\t -- Boolean which indicates whether or not messages, including plots, should be output.\n '''\n\n # Create a pandas data frame storing the relevant information\n dataMOT = pd.DataFrame(columns=['time', 'power', 'sigma_x', 'sigma_sigma_x', 'sigma_y', 'sigma_sigma_y'])\n\n for i in range(len(q)):\n dataMOT.loc[i] = [time_conversion_ratio * float(q[i][0].time), max_power/float(q[i][0].power),\n pixel_distance_ratio * q[i][1]['sigma_x'][0.50], \\\n pixel_distance_ratio * np.abs(\n q[i][1]['sigma_x'][0.50] - (q[i][1]['sigma_x'][0.16] + q[i][1]['sigma_x'][0.84]) / 2), \\\n pixel_distance_ratio * q[i][1]['sigma_y'][0.50], \\\n pixel_distance_ratio * np.abs(\n q[i][1]['sigma_y'][0.50] - (q[i][1]['sigma_y'][0.16] + q[i][1]['sigma_y'][0.84]) / 2)]\n\n\n dataMOT['sigma_x_squared'] = dataMOT['sigma_x']**2\n dataMOT['sigma_sigma_x_squared'] = dataMOT['sigma_sigma_x']**2\n dataMOT['sigma_y_squared'] = dataMOT['sigma_y']**2\n dataMOT['sigma_sigma_y_squared'] = dataMOT['sigma_sigma_y']**2\n\n if(not suppressMessages):\n print(dataMOT)\n\n quad_fit_sigma_x = quad_fit(dataMOT, x_name = \"time\", y_name='sigma_x_squared', suppressMessages = suppressMessages)\n quad_fit_sigma_y = quad_fit(dataMOT, x_name=\"time\", y_name='sigma_y_squared', suppressMessages=suppressMessages)\n\n # Output plots for the fits\n if(not suppressMessages):\n dataMOT.iloc[:].plot(x='time', y='sigma_x_squared', kind='scatter', yerr='sigma_sigma_x_squared', s=30)\n _ = plt.xlabel('time (s)')\n _ = plt.ylabel('sigma_x^2 (m^2)')\n _ = plt.ylim([0.0000001, 0.000015])\n _ = plt.xlim([0, 0.005])\n _ = plt.plot(np.linspace(0, 0.005, 10), quad_fit_sigma_x[1] * np.linspace(0, 0.005, 10) ** 2 + quad_fit_sigma_x[0])\n _ = plt.title(\"Quadratic fit to data for sigma_x\")\n _ = plt.show()\n\n dataMOT.iloc[:].plot(x='time', y='sigma_y_squared', kind='scatter', yerr='sigma_sigma_y_squared', s=30)\n _ = plt.xlabel('time (s)')\n _ = plt.ylabel('sigma_y^2 (m^2)')\n _ = plt.ylim([0.0000001, 0.000015])\n _ = plt.xlim([0, 0.005])\n _ = plt.plot(np.linspace(0, 0.005, 10), quad_fit_sigma_y[1] * np.linspace(0, 0.005, 10) ** 2 + quad_fit_sigma_y[0])\n _ = plt.title(\"Quadratic fit to data for sigma_y\")\n _ = plt.show()\n\n # Define constants\n m = 9.80 * 10 ** (-26)\n K_b = 1.38 * 10 ** (-23)\n\n # The temperatures:\n T_x = quad_fit_sigma_x[1]*m/K_b\n T_y = quad_fit_sigma_y[1]*m/K_b\n T = T_x**(2/3) * T_y**(1/3)\n\n if(not suppressMessages):\n print(\"The fitted temepratures: T_x = %f mK, T_y = %f mK, T = %f mK\" %(10**3 * T_x, 10**3 * T_y, 10**3 * T))\n\n return [T_x, T_y, T]\n\ndef separate_files_power(data_files):\n '''\n Function that takes an array of data file names and groups them according to the power used.\n\n Keyword arguments:\n data_files -- array of data file names\n\n '''\n data_files_power = [[0 for x in range(1)] for y in range(1000)] #1000 should be larger than any other power fraction we choose\n\n for f in data_files:\n try:\n f_power = int((f.split('_')[2]).split('power')[0])\n except IndexError:\n raise ValueError('Check that your data file name respects the convention.')\n\n if data_files_power[f_power] == [0]:\n data_files_power[f_power] = [f]\n else:\n data_files_power[f_power].append(f)\n\n return [list(row) for row in data_files_power if any(x is not 0 for x in row)]\n\n\ndef temp_vs_power(data_files, data_dir = 'data', image_size = 50, mc_params=(200, 1500, 500), initial_guess=[25, 25, 400, 6.6667, 5.5556, 100, 20, 20], suppressMessages=True):\n '''\n Function that takes an array of data file names and returns temperatures as a function of the laser power used.\n\n Keyword arguments:\n data_files -- array of data file names\n data_dir\t -- String denoting name of data directory\n\t\t image_size\t -- Size of MOT image (which is assumed to be a square).\n\t\t mc_params\t -- triplet of MCMC parameters: (number of walkers, number of steps, burn_in_steps).\n\t\t\t\t\t\t -- walkers = individual traces in the Monte Carlo algorithm\n\t\t\t\t\t\t -- steps = length of said traces\n\t\t\t\t\t\t -- burn_in_steps = steps after which the trace settles around a value\n\t\t initial_guess\t\t-- tuple of initial MCMC guesses, consisting of (center_x, center_y, amplitude, sigma_x, sigma_y, background_offset, sigma_m, sigma_g).\n\t\t suppressMessages -- Boolean which indicates whether or not messages, including plots, should be output.\n\n '''\n\n\n # TO DO: Again, have a set of parameters that describe the appartus (like theta) that we automatically pass around\n # this way max power doesn't need to be set inside the package (and should be variable)\n max_power = 60 * 10 ** (-3)\n dataPowerTemp = pd.DataFrame(columns=['power', 'T_x', 'T_y', 'T'])\n\n\n for i in range(len(data_files)):\n q = find_params_MOTs(data_files[i], data_dir, image_size, mc_params, initial_guess, suppressMessages = True)\n power = max_power / float(q[0][0].power)\n temp = find_MOT_temp(q, pixel_distance_ratio=0.4 * 10 ** (-3), time_conversion_ratio=10 ** (-3), max_power=60 * 10 ** (-3), suppressMessages=True)\n\n dataPowerTemp.loc[i] = [power, temp[0], temp[1], temp[2]]\n\n return dataPowerTemp\n\n\n\n\n\n","repo_name":"phys201/params_MOT","sub_path":"params_MOT/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":15730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"75292313699","text":"import os\n\nimport pytest\n\nimport geckopy\nfrom geckopy.experimental.molecular_weights import extract_proteins\n\n\ndef test_read_geckopy_from_file(path_ecoli_core):\n \"\"\"Read model directly from file.\"\"\"\n model = geckopy.io.read_sbml_ec_model(path_ecoli_core)\n assert len(model.proteins) == 55\n\n\ndef test_copy_geckopy(ec_model_core):\n \"\"\"Check that deepcopy works.\"\"\"\n copied = ec_model_core.copy()\n assert len(copied.proteins) == len(ec_model_core.proteins)\n assert len(copied.reactions) == len(ec_model_core.reactions)\n assert len(copied.metabolites) == len(ec_model_core.metabolites)\n\n\ndef test_parsing_captures_naming_convention(dummy_ec_model):\n \"\"\"Check proteins rely on the naming convention prot_UNIPROT are parsed.\"\"\"\n assert dummy_ec_model.proteins.query(\"prot_P0A805\")\n\n\ndef test_parsing_captures_protein_group(dummy_ec_model):\n \"\"\"Check members of Protein group are parsed as proteins.\"\"\"\n assert dummy_ec_model.groups.query(\"Protein\")\n assert dummy_ec_model.proteins.query(\"prot_P0A825\")\n assert dummy_ec_model.proteins.query(\"dummy_prot\")\n\n\ndef test_protein_parsing_does_not_get_normal_metabolites(dummy_ec_model):\n \"\"\"Check normal metabolites are not parsed as proteins.\"\"\"\n assert not dummy_ec_model.proteins.query(\"normal_met\")\n assert dummy_ec_model.metabolites.query(\"normal_met\")\n mets = set(dummy_ec_model.metabolites)\n prots = set(dummy_ec_model.proteins)\n assert mets ^ prots == mets | prots\n\n\ndef test_serialized_model_grows(slim_solution_core, ec_model_core):\n \"\"\"Check that deserialized model grows at the same rate.\"\"\"\n geckopy.io.write_sbml_ec_model(ec_model_core, \"_tmpfull.xml\")\n redeserialized = geckopy.io.read_sbml_ec_model(\n \"_tmpfull.xml\", hardcoded_rev_reactions=False\n )\n assert pytest.approx(redeserialized.slim_optimize()) == pytest.approx(\n slim_solution_core\n )\n os.remove(\"_tmpfull.xml\")\n\n\ndef test_writing_with_mw_kcat_produces_same_solution(slim_solution_core, ec_model_core):\n \"\"\"Check that deserialized model with GECKO 3.0 grows at the same rate.\"\"\"\n df = extract_proteins(ec_model_core)\n for row in df.itertuples():\n ec_model_core.proteins.get_by_id(row[2]).mw = row[3]\n geckopy.io.write_sbml_ec_model(\n ec_model_core,\n \"_tmpfull_mwkcat.xml\",\n ec_stoichiometry=geckopy.io.EcStoichiometry.MW_KCAT,\n )\n redeserialized = geckopy.io.read_sbml_ec_model(\n \"_tmpfull_mwkcat.xml\",\n hardcoded_rev_reactions=False,\n ec_stoichiometry=geckopy.io.EcStoichiometry.MW_KCAT,\n )\n assert pytest.approx(redeserialized.slim_optimize()) == pytest.approx(\n slim_solution_core\n )\n os.remove(\"_tmpfull_mwkcat.xml\")\n\n\ndef test_serialized_model_has_concentrations(dummy_ec_model):\n \"\"\"Check that concentrations are properly saved on SBML serialization.\"\"\"\n dummy_ec_model.proteins.prot_P0A825.concentration = 123\n geckopy.io.write_sbml_ec_model(dummy_ec_model, \"_tmp.xml\")\n redeserialized = geckopy.io.read_sbml_ec_model(\n \"_tmp.xml\", hardcoded_rev_reactions=False\n )\n assert redeserialized.proteins.prot_P0A825.concentration == 123\n os.remove(\"_tmp.xml\")\n\n\ndef test_proteins_are_grouped_on_write(dummy_ec_model):\n \"\"\"Check that grouped proteins not following naming are properly handled.\"\"\"\n dummy_ec_model.add_proteins([geckopy.Protein(\"my_unconventional_protein\")])\n\n assert (\n dummy_ec_model.proteins.prot_P0A805\n not in dummy_ec_model.groups.get_by_id(\"Protein\").members\n )\n geckopy.io.write_sbml_ec_model(\n dummy_ec_model, \"_tmp_auto_grouping.xml\", group_untyped_proteins=True # default\n )\n # proteins that were not grouped but follow the conventions are not grouped\n assert (\n dummy_ec_model.proteins.prot_P0A805\n not in dummy_ec_model.groups.get_by_id(\"Protein\").members\n )\n redeserialized = geckopy.io.read_sbml_ec_model(\n \"_tmp_auto_grouping.xml\", hardcoded_rev_reactions=False\n )\n assert (\n redeserialized.proteins.my_unconventional_protein.id\n == \"my_unconventional_protein\"\n )\n os.remove(\"_tmp_auto_grouping.xml\")\n\n\ndef test_grouped_proteins_are_correctly_deserialized(ec_model_core):\n \"\"\"Check that deepcopy works.\"\"\"\n copied = ec_model_core.copy()\n copied.reactions.NH4t.add_protein(\"W\", 60)\n geckopy.io.write_sbml_ec_model(\n copied, \"_tmp_with_prot.xml\", group_untyped_proteins=True # default\n )\n model = geckopy.io.read_sbml_ec_model(\"_tmp_with_prot.xml\")\n assert pytest.approx(model.proteins.W.kcats[\"NH4t\"]) == 60\n os.remove(\"_tmp_with_prot.xml\")\n\n\ndef test_gene_and_proteins_point_to_each_other(ec_model_core):\n \"\"\"Check that annotating genes and proteins point to each other.\"\"\"\n geckopy.io.standard.annotate_gene_protein_rules(ec_model_core)\n assert ec_model_core.genes.get_by_id(\n \"b1241\"\n ).protein == ec_model_core.proteins.get_by_id(\"prot_P0A9Q7\")\n assert (\n ec_model_core.proteins.get_by_id(\"prot_P0A9Q7\")\n == ec_model_core.genes.get_by_id(\"b1241\").protein\n )\n # all proteins in the EC core model are in a gene\n assert sum(gene.protein is not None for gene in ec_model_core.genes) == len(\n ec_model_core.proteins\n )\n","repo_name":"ginkgobioworks/geckopy","sub_path":"tests/test_unit/test_io.py","file_name":"test_io.py","file_ext":"py","file_size_in_byte":5255,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"35"} +{"seq_id":"17405444052","text":"import socket\nfrom ctypes import *\n\nlib = cdll.LoadLibrary('./DLL2.dll') \n\nBUFSIZE = 1024\nip_port = ('0.0.0.0', 9999)\nserver = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nserver.bind(ip_port)\nwhile True:\n msg,client= server.recvfrom(BUFSIZE)\n lib.get_rdtsc.restype = c_longlong\n end = lib.get_rdtsc()\n data = int (msg.decode().split(\" \")[-1].split(\"]\")[0])\n print(data)\n diff = end - data\n print(diff)\nserver.close()\n","repo_name":"kingfisherht/rdtsc_python","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"42908602254","text":"import pygame\n\n\n\n# définire une classe qui va s'occuper des animations\n\nclass AnimateSprite(pygame.sprite.Sprite):\n\t# définir les choses à faire à la création de l'entité\n\tdef __init__(self, sprite_name, size=(200, 200)):\n\n\t\tsuper().__init__()\n\t\tself.size = size\n\t\tself.image = pygame.image.load(f'assets/{sprite_name}.png')\n\t\tself.image = pygame.transform.scale(self.image, size)\n\t\tself.current_image = 0 # commencer l'anim à l'image 0\n\t\tself.images = animations.get(sprite_name)\n\t\tself.animations = False\n\n\t# définire une méthode pour démarré l'animation\n\tdef start_animation(self):\n\t\tself.animations = True\n\n\t# definire une methode pour animer le sprite\n\tdef animate(self, loop = False):\n\n\t\t# verifier si l'anim est active \n\t\tif self.animations:\n\n\t\t\t# passer à l'image suivante\n\t\t\tself.current_image += 1\n\n\t\t\t# verifier si on à attient la fin de l'anim\n\t\t\tif self.current_image >= len(self.images):\n\t\t\t\t# remettre l'anim au départ\n\t\t\t\tself.current_image = 0\n\n\t\t\t\t# vérifier si l'animation n'est pas en mode boucle\n\t\t\t\tif loop is False:\n\n\t\t\t\t\t# désactiver l'anim\n\t\t\t\t\tself.animations = False\n\n\t\t\t# modifier l'image précedente par la suivante\n\t\t\tself.image = self.images[self.current_image]\n\t\t\tself.image = pygame.transform.scale(self.image, self.size)\n\n# definire une fonction pour charger les image d'un sprite\n\ndef load_animation_images(sprite_name):\n\n\t# charger les 24 images de ce sprite dans le dossier correspondant\n\timages = []\n\t# récupérer le chemin du dossier pour ce sprite \n\tpath = f\"assets/{sprite_name}/{sprite_name}\"\n\n\t# boucler sur chaque image ce dossier pour les ajouter à la liste\n\tfor num in range(1, 24):\n\t\timage_path = path+str(num)+'.png'\n\t\timages.append(pygame.image.load(image_path))\n\n\t# renvoyer le contenu de la liste d'image\n\n\treturn images\n\n# definir un dictionnaire qui va contenir les images chargées de chaque sprite\n# mummy -> [...mummy1.png, ...mummy2.png, ...]\n# player -> [...player1.png, ...player2.png, ...]\n\nanimations = {\n\t'mummy': load_animation_images('mummy'),\n\t'player': load_animation_images('player'),\n\t'alien': load_animation_images('alien')\n\n}","repo_name":"amk-7/Tkinter","sub_path":"game/animation.py","file_name":"animation.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"21791650450","text":"from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union\n\nfrom ethpm_types import ContractType\nfrom ethpm_types.abi import ConstructorABI, EventABI, MethodABI\n\nfrom ape.api import Address, AddressAPI, ProviderAPI, ReceiptAPI, TransactionAPI\nfrom ape.exceptions import (\n ArgumentsLengthError,\n ContractError,\n ProviderNotConnectedError,\n TransactionError,\n)\nfrom ape.logging import logger\nfrom ape.types import AddressType\nfrom ape.utils import dataclass\n\nif TYPE_CHECKING:\n from ape.managers.converters import ConversionManager\n from ape.managers.networks import NetworkManager\n\n\n@dataclass\nclass ContractConstructor:\n deployment_bytecode: bytes\n abi: ConstructorABI\n provider: ProviderAPI\n converter: \"ConversionManager\"\n\n def __post_init__(self):\n if len(self.deployment_bytecode) == 0:\n logger.warning(\"Deploying an empty contract (no bytecode)\")\n\n def __repr__(self) -> str:\n return self.abi.signature if self.abi else \"constructor()\"\n\n def _convert_tuple(self, v: tuple) -> tuple:\n return self.converter.convert(v, tuple)\n\n def encode(self, *args, **kwargs) -> TransactionAPI:\n args = self._convert_tuple(args)\n kwargs = dict(\n (k, v)\n for k, v in zip(\n kwargs.keys(),\n self._convert_tuple(tuple(kwargs.values())),\n )\n )\n return self.provider.network.ecosystem.encode_deployment(\n self.deployment_bytecode, self.abi, *args, **kwargs\n )\n\n def __call__(self, *args, **kwargs) -> ReceiptAPI:\n if \"sender\" in kwargs:\n sender = kwargs[\"sender\"]\n txn = self.encode(*args, **kwargs)\n return sender.call(txn)\n\n txn = self.encode(*args, **kwargs)\n return self.provider.send_transaction(txn)\n\n\n@dataclass\nclass ContractCall:\n abi: MethodABI\n address: AddressType\n provider: ProviderAPI\n converter: \"ConversionManager\"\n\n def __repr__(self) -> str:\n return self.abi.signature\n\n def _convert_tuple(self, v: tuple) -> tuple:\n return self.converter.convert(v, tuple)\n\n def encode(self, *args, **kwargs) -> TransactionAPI:\n kwargs = dict(\n (k, v)\n for k, v in zip(\n kwargs.keys(),\n self._convert_tuple(tuple(kwargs.values())),\n )\n )\n return self.provider.network.ecosystem.encode_transaction(\n self.address, self.abi, *args, **kwargs\n )\n\n def __call__(self, *args, **kwargs) -> Any:\n txn = self.encode(*args, **kwargs)\n txn.chain_id = self.provider.network.chain_id\n\n raw_output = self.provider.send_call(txn)\n tuple_output = self.provider.network.ecosystem.decode_calldata( # type: ignore\n self.abi,\n raw_output,\n )\n\n # NOTE: Returns a tuple, so make sure to handle all the cases\n if len(tuple_output) < 2:\n return tuple_output[0] if len(tuple_output) == 1 else None\n\n # TODO: Handle struct output\n return tuple_output\n\n\n@dataclass\nclass ContractCallHandler:\n provider: ProviderAPI\n converter: \"ConversionManager\"\n contract: \"ContractInstance\"\n abis: List[MethodABI]\n\n def __repr__(self) -> str:\n abis = sorted(self.abis, key=lambda abi: len(abi.inputs or [])) # type: ignore\n return abis[-1].signature\n\n def _convert_tuple(self, v: tuple) -> tuple:\n return self.converter.convert(v, tuple)\n\n def __call__(self, *args, **kwargs) -> Any:\n if not self.contract.is_contract:\n network = self.provider.network.name\n raise _get_non_contract_error(self.contract.address, network)\n\n args = self._convert_tuple(args)\n selected_abi = _select_abi(self.abis, args)\n if not selected_abi:\n raise ArgumentsLengthError(len(args))\n\n return ContractCall( # type: ignore\n abi=selected_abi,\n address=self.contract.address,\n provider=self.provider,\n converter=self.converter,\n )(*args, **kwargs)\n\n\ndef _select_abi(abis, args):\n args = args or []\n selected_abi = None\n for abi in abis:\n inputs = abi.inputs or []\n if len(args) == len(inputs):\n selected_abi = abi\n\n return selected_abi\n\n\n@dataclass\nclass ContractTransaction:\n abi: MethodABI\n address: AddressType\n provider: ProviderAPI\n converter: \"ConversionManager\"\n\n def __repr__(self) -> str:\n return self.abi.signature\n\n def _convert_tuple(self, v: tuple) -> tuple:\n return self.converter.convert(v, tuple)\n\n def encode(self, *args, **kwargs) -> TransactionAPI:\n kwargs = dict(\n (k, v)\n for k, v in zip(\n kwargs.keys(),\n self._convert_tuple(tuple(kwargs.values())),\n )\n )\n return self.provider.network.ecosystem.encode_transaction(\n self.address, self.abi, *args, **kwargs\n )\n\n def __call__(self, *args, **kwargs) -> ReceiptAPI:\n if \"sender\" in kwargs:\n sender = kwargs[\"sender\"]\n txn = self.encode(*args, **kwargs)\n return sender.call(txn)\n\n raise TransactionError(message=\"Must specify a `sender`.\")\n\n\n@dataclass\nclass ContractTransactionHandler:\n provider: ProviderAPI\n converter: \"ConversionManager\"\n contract: \"ContractInstance\"\n abis: List[MethodABI]\n\n def __repr__(self) -> str:\n abis = sorted(self.abis, key=lambda abi: len(abi.inputs or [])) # type: ignore\n return abis[-1].signature\n\n def _convert_tuple(self, v: tuple) -> tuple:\n return self.converter.convert(v, tuple)\n\n def __call__(self, *args, **kwargs) -> ReceiptAPI:\n if not self.contract.is_contract:\n network = self.provider.network.name\n raise _get_non_contract_error(self.contract.address, network)\n\n args = self._convert_tuple(args)\n selected_abi = _select_abi(self.abis, args)\n if not selected_abi:\n raise ArgumentsLengthError(len(args))\n\n return ContractTransaction( # type: ignore\n abi=selected_abi,\n address=self.contract.address,\n provider=self.provider,\n converter=self.converter,\n )(*args, **kwargs)\n\n\n@dataclass\nclass ContractLog:\n name: str\n data: Dict[str, Any]\n\n\n@dataclass\nclass ContractEvent:\n provider: ProviderAPI\n converter: \"ConversionManager\"\n contract: \"ContractInstance\"\n abis: List[EventABI]\n cached_logs: List[ContractLog] = []\n\n\nclass ContractInstance(AddressAPI):\n \"\"\"\n An interactive instance of a smart contract.\n After you deploy a contract using the :class:`~ape.api.accounts.AccountAPI.deploy` method,\n you get back a contract instance.\n\n Usage example::\n\n from ape import accounts, project\n\n a = accounts.load(\"alias\") # Load an account by alias\n contract = a.deploy(project.MyContract) # The result of 'deploy()' is a ContractInstance\n \"\"\"\n\n _address: AddressType\n _converter: \"ConversionManager\"\n _contract_type: ContractType\n\n def __repr__(self) -> str:\n contract_name = self._contract_type.name or \"\"\n return f\"<{contract_name} {self.address}>\"\n\n @property\n def address(self) -> AddressType:\n \"\"\"\n The address of the contract.\n\n Returns:\n ``AddressType``\n \"\"\"\n return self._address\n\n def __dir__(self) -> List[str]:\n \"\"\"\n Display methods to IPython on ``c.[TAB]`` tab completion.\n\n Returns:\n List[str]\n \"\"\"\n return list(super(AddressAPI, self).__dir__()) + [\n abi.name for abi in self._contract_type.abi if isinstance(abi, (MethodABI, EventABI))\n ]\n\n def __getattr__(self, attr_name: str) -> Any:\n \"\"\"\n Access a method or property on the contract using ``.`` access.\n\n Usage example::\n\n result = contract.vote() # Implies a method named \"vote\" exists on the contract.\n\n Args:\n attr_name (str): The name of the method or property to access.\n\n Returns:\n any: The return value from the contract call, or a transaction receipt.\n \"\"\"\n\n def name_matches(abi):\n return abi.name == attr_name\n\n selected_view_methods = list(filter(name_matches, self._contract_type.view_methods))\n has_matching_view_methods = len(selected_view_methods) > 0\n\n selected_mutable_methods = list(filter(name_matches, self._contract_type.mutable_methods))\n has_matching_mutable_methods = len(selected_mutable_methods) > 0\n\n selected_events = list(filter(name_matches, self._contract_type.events))\n has_matching_events = len(selected_events) > 0\n\n num_matching_conditions = sum(\n [\n has_matching_view_methods,\n has_matching_mutable_methods,\n has_matching_events,\n ]\n )\n\n if num_matching_conditions == 0:\n # Didn't find anything that matches\n # NOTE: `__getattr__` *must* raise `AttributeError`\n name = self._contract_type.name or self.__class__.__name__\n raise AttributeError(f\"'{name}' has no attribute '{attr_name}'.\")\n\n elif num_matching_conditions > 1:\n # ABI should not contain a mix of events, mutable and view methods that match\n # NOTE: `__getattr__` *must* raise `AttributeError`\n raise AttributeError(f\"{self.__class__.__name__} has corrupted ABI.\")\n\n kwargs = {\n \"provider\": self.provider,\n \"converter\": self._converter,\n \"contract\": self,\n }\n\n # Handle according to the proper abi type handler\n if has_matching_events:\n kwargs[\"abis\"] = selected_events\n handler = ContractEvent\n\n elif has_matching_view_methods:\n kwargs[\"abis\"] = selected_view_methods\n handler = ContractCallHandler # type: ignore\n\n elif has_matching_mutable_methods:\n kwargs[\"abis\"] = selected_mutable_methods\n handler = ContractTransactionHandler # type: ignore\n\n try:\n return handler(**kwargs) # type: ignore\n\n except Exception as e:\n # NOTE: Just a hack, because `__getattr__` *must* raise `AttributeError`\n raise AttributeError(str(e)) from e\n\n\n@dataclass\nclass ContractContainer:\n \"\"\"\n A wrapper around the contract type that has access to the provider.\n When you import your contracts from the :class:`ape.managers.project.ProjectManager`, you\n are using this class.\n\n Usage example::\n\n from ape import project\n\n contract_container = project.MyContract # Assuming there is a contract named \"MyContract\"\n \"\"\"\n\n contract_type: ContractType\n \"\"\"The type of the contract.\"\"\"\n\n _provider: Optional[ProviderAPI]\n # _provider is only None when a user is not connected to a provider.\n\n _converter: \"ConversionManager\"\n\n def __repr__(self) -> str:\n return f\"<{self.contract_type.name}>\"\n\n def at(self, address: str) -> ContractInstance:\n \"\"\"\n Get a contract at the given address.\n\n Usage example::\n\n from ape import project\n\n my_contract = project.MyContract.at(\"0xAbC1230001112223334445566611855443322111\")\n\n Args:\n address (str): The address to initialize a contract.\n **NOTE**: Things will not work as expected if the contract is not actually\n deployed to this address or if the contract at the given address has\n a different ABI than :attr:`~ape.contracts.ContractContainer.contract_type`.\n\n Returns:\n :class:`~ape.contracts.ContractInstance`\n \"\"\"\n\n return ContractInstance( # type: ignore\n _address=address,\n _provider=self._provider,\n _converter=self._converter,\n _contract_type=self.contract_type,\n )\n\n def __call__(self, *args, **kwargs) -> TransactionAPI:\n args = self._converter.convert(args, tuple)\n constructor = ContractConstructor( # type: ignore\n abi=self.contract_type.constructor,\n provider=self._provider,\n converter=self._converter,\n deployment_bytecode=self.contract_type.get_deployment_bytecode() or b\"\",\n )\n\n args_length = len(args)\n inputs_length = (\n len(constructor.abi.inputs) if constructor.abi and constructor.abi.inputs else 0\n )\n if inputs_length != args_length:\n raise ArgumentsLengthError(args_length, inputs_length=inputs_length)\n\n return constructor.encode(*args, **kwargs)\n\n\ndef _Contract(\n address: Union[str, AddressAPI, AddressType],\n networks: \"NetworkManager\",\n converters: \"ConversionManager\",\n contract_type: Optional[ContractType] = None,\n) -> AddressAPI:\n \"\"\"\n Function used to triage whether we have a contract type available for\n the given address/network combo, or explicitly provided. If none are found,\n returns a simple ``Address`` instance instead of throwing (provides a warning)\n \"\"\"\n provider = networks.active_provider\n if not provider:\n raise ProviderNotConnectedError()\n\n converted_address: AddressType = converters.convert(address, AddressType)\n\n # Check contract cache (e.g. previously deployed/downloaded contracts)\n # TODO: Add ``contract_cache`` dict-like object to ``NetworkAPI``\n # network = provider.network\n # if not contract_type and address in network.contract_cache:\n # contract_type = network.contract_cache[address]\n\n # Check explorer API/cache (e.g. publicly published contracts)\n # TODO: Store in ``NetworkAPI.contract_cache`` to reduce API calls\n explorer = provider.network.explorer\n if not contract_type and explorer:\n contract_type = explorer.get_contract_type(converted_address)\n\n # We have a contract type either:\n # 1) explicitly provided,\n # 2) from network cache, or\n # 3) from explorer\n if contract_type:\n return ContractInstance( # type: ignore\n _address=converted_address,\n _provider=provider,\n _converter=converters,\n _contract_type=contract_type,\n )\n\n else:\n # We don't have a contract type from any source, provide raw address instead\n logger.warning(f\"No contract type found for {address}\")\n return Address( # type: ignore\n _address=converted_address,\n _provider=provider,\n )\n\n\ndef _get_non_contract_error(address: str, network_name: str) -> ContractError:\n raise ContractError(\n f\"Unable to make contract call. \"\n f\"'{address}' is not a contract on network '{network_name}'.\"\n )\n","repo_name":"fselmo/ape","sub_path":"src/ape/contracts/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":14912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"35"} +{"seq_id":"41528462783","text":"import PySimpleGUIQt as sg\n\n\"\"\"\n Allows you to \"browse\" through the Theme settings. Click on one and you'll see a\n Popup window using the color scheme you chose. It's a simple little program that also demonstrates\n how snappy a GUI can feel if you enable an element's events rather than waiting on a button click.\n In thYaelTheme = {'BACKGROUND': '#F99FC9',\n 'TEXT': 'black',\n 'INPUT': '#DDE0DE',\n 'SCROLL': '#E3E3E3',\n 'TEXT_INPUT': 'black',\n 'BUTTON': ('white', '#85c7e3'),\n 'PROGRESS': 'blue',\n 'BORDER': 1,\n 'SLIDER_DEPTH': 0,\n 'PROGRESS_DEPTH': 0}\n\nsg.LOOK_AND_FEEL_TABLE['YaelTheme'] = YaelTheme\nsg.theme('YaelTheme')is program, as soon as a listbox entry is clicked, the read returns.\n\"\"\"\n\n\nlayout = [[sg.Text('Theme Browser')],\n [sg.Text('Click a Theme color to see demo window')],\n [sg.Listbox(values=sg.theme_list(), size=(20, 12), key='-LIST-', enable_events=True)],\n [sg.Button('Exit')]]\n\nwindow = sg.Window('Theme Browser', layout)\n\nwhile True: # Event Loop\n event, values = window.read()\n if event in (sg.WIN_CLOSED, 'Exit'):\n break\n sg.theme(values['-LIST-'][0])\n sg.popup_get_text('This is {}'.format(values['-LIST-'][0]))\n\nwindow.close()","repo_name":"Seraph18/Cats","sub_path":"Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"3677303427","text":"from django.conf.urls import url\n\nfrom . import views\n\napp_name = 'switches'\nurlpatterns = [\n # ex: /switches/\n url(r'^$', views.index, name='index'),\n # ex: /switches/5/toggle/\n url(r'^(?P[0-9]+)/toggle/$', views.toggle, name='toggle'),\n]","repo_name":"ajhyndman/christmas_pi","sub_path":"www/switches/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"16085592739","text":"import datetime\nfrom calendar import month\nfrom datetime import datetime\n\ndef ask_for_birthdate():\n year = int(input(\"Please enter the year of birth: \"))\n month = int(input(\"Please enter the month of birth: \"))\n day = int(input(\"Please enter the day of birth: \"))\n birthdate = datetime(year,month,day)\n return birthdate\n\ndef calculate_days(birth_date):\n today = datetime.today()\n number_of_days = today - birth_date\n return number_of_days.days\n\ndef main():\n birthdate = ask_for_birthdate()\n number_of_days = calculate_days(birthdate)\n print(f'\\n You are living {number_of_days} days!')\n\nif __name__ ==\"__main__\":\n main()\n \n","repo_name":"matiwan3/PYTHON-main","sub_path":"python/2022.10/C_how_many_days_calculator/birthday days.py","file_name":"birthday days.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"35"} +{"seq_id":"72725432740","text":"\n# this one works\n\nimport socket\nimport numpy as np\nimport time\nfrom pyqtgraph.Qt import QtCore\n\nfrom pyqtgraph.widgets.RawImageWidget import RawImageGLWidget\n\nfrom PIL import Image\n\n# my lib\nfrom myConfigLib import MyConfig\n\nclass CameraThread(QtCore.QThread):\n \n _cameraSignal = QtCore.pyqtSignal(str)\n _cameraDataSignal = QtCore.pyqtSignal(list)\n\n def __init__(self, config:MyConfig):\n super().__init__()\n\n self._config = config\n self._ip = self._config.cameraIp()\n self._port = self._config.cameraPort()\n self._imgHight = self._config.imageHight()\n self._imgWidth = self._config.imageWidth()\n\n self._client = None # client socket handler\n\n def run(self):\n # self._client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # self._cameraSignal.emit('start connecting to camera server!')\n\n # self._client.connect((self._ip, self._port))\n\n # self._cameraSignal.emit('connected with camera Server!')\n # self._cameraSignal.emit('start recving images from the camera.')\n\n # self.recvStreamImg()\n\n # self.imageShowTest()\n pass\n\n def imageShowTest(self):\n while True:\n print('----')\n print('read image time: {}'.format(time.time()))\n # imgdataTest = Image.open('/home/yys/yys/code/PyKinect2-PyQtGraph-PointClouds-master/img/image_1.png')\n # imgdataTest = imgdataTest.convert('RGB')\n # imgdataTest = imgdataTest.resize((300, 200))\n\n # imgdataTest = np.array(imgdataTest)\n\n # print(imgdataTest.shape)\n \n # imgdataTest.show(0)\n\n\n\n # print(imgdataTest)\n\n # imgdataTest = np.random.uniform((300, 200, 3))\n # imgdataTest = np.array(imgdataTest)\n\n # print('read done time: {}'.format(time.time()))\n # self._cameraDataSignal.emit(imgdataTest.tolist())\n # print('send image time: {}'.format(time.time()))\n time.sleep(0.01)\n self._cameraSignal.emit('oneImageDone')\n\n\n def recvLongData(self, client, recvDataLength):\n buf = b''\n c = 0\n partlen = 6000\n\n while c < recvDataLength:\n if recvDataLength - c >= partlen:\n new_buf = client.recv(partlen)\n else: \n leftlen = recvDataLength - c\n new_buf = client.recv(leftlen)\n\n if not new_buf: return None\n buf += new_buf\n c += len(new_buf)\n\n return buf\n\n def recvOneImg(self):\n w = self._imgWidth\n h = self._imgHight\n data = self.recvLongData(self._client, w*h*3)\n\n rowimg = np.frombuffer(data, dtype = 'uint8')\n rowimgreshape = rowimg.reshape((h, w, 3))\n\n rowimgreshape = np.array(rowimgreshape)\n\n self._cameraDataSignal.emit(rowimgreshape.tolist()) # update image on the widget\n\n self._client.send(b'3')\n\n time.sleep(0.01)\n\n\n def recvStreamImg(self):\n while True:\n flg = self._client.recv(1)\n flgvalue = flg.decode('utf-8')\n if flgvalue == '1':\n self._client.send(b'2')\n\n self.recvOneImg()\n\n\n","repo_name":"YoungRainy/python_qt_gui_robotG1","sub_path":"MyCameraLib.py","file_name":"MyCameraLib.py","file_ext":"py","file_size_in_byte":3216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"1494341532","text":"def rgbMixer(color1, color2):\n color1 = color1.lower()\n color2 = color2.lower()\n colorProduct = \"\"\n \n if color1 == \"red\":\n if color2 == \"red\":\n colorProduct = \"red\"\n elif color2 == \"blue\":\n colorProduct = \"purple\"\n elif color2 == \"yellow\":\n colorProduct = \"orange\"\n \n elif color1 == \"blue\":\n if color2 == \"red\":\n colorProduct = \"purple\"\n elif color2 == \"blue\":\n colorProduct = \"blue\"\n elif color2 == \"yellow\":\n colorProduct = \"green\"\n \n elif color1 == \"yellow\":\n if color2 == \"red\":\n colorProduct = \"orange\"\n elif color2 == \"blue\":\n colorProduct = \"green\"\n elif color2 == \"yellow\":\n colorProduct = \"yellow\"\n\n return colorProduct\n\nprint()\nprint(\"Let's mix some colors!\")\nprint(\"**Red, Blue, or Yellow only**\")\nprint()\n\ncolor1 = input(\"What first color to mix? \")\ncolor2 = input(\"What's the other color? \")\nproduct = rgbMixer(color1, color2)\nprint()\n\nprint(color1.upper(),\" and \", color2.upper(), \" makes \", product.upper(), \"!\",sep=\"\")\n","repo_name":"daniel-mcbride/CS1_Files","sub_path":"Extra Problems/extra1.py","file_name":"extra1.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"32631419680","text":"# -*- coding: utf-8 -*-\n# File: cocostuff.py\n\nimport cv2\nimport numpy as np\nimport os, sys\nfrom termcolor import colored\nfrom tabulate import tabulate\n\nimport tensorflow as tf\nfrom tensorpack.utils import logger\nfrom tensorpack.utils.timer import timed_operation\nfrom tensorpack.utils.argtools import log_once\n\nfrom config import config as cfg\n\nfrom dataset.dataset_utils import load_from_cache, save_to_cache\n\n\nclass COCOSTUFFSegmentation(object):\n def __init__(self, basedir, name):\n # assert name in DSSMeta.INSTANCE_TO_BASEDIR.keys(), name\n self.name = name\n\n self._basedir = basedir\n assert os.path.isdir(self._basedir), self._basedir\n # self._imgdir = os.path.abspath(os.path.join(dbdir, 'leftImg8bit'))\n # assert os.path.isdir(self._imgdir), self._imgdir\n # self._anndir = os.path.abspath(os.path.join(dbdir, 'gtFine'))\n # assert os.path.isdir(self._anndir), self._anndir\n\n fn_imageset = os.path.join(basedir, 'imageLists', name.split('_')[1] + '.txt')\n with open(fn_imageset, 'r') as fh:\n list_all = [l.strip() for l in fh.readlines()]\n self._imageset = [(l + '.jpg', l + '.mat') for l in list_all]\n\n logger.info(\"Image list loaded from {}.\".format(fn_imageset))\n\n def load(self, add_gt=True):\n \"\"\"\n Args:\n add_gt: whether to add ground truth bounding box annotations to the dicts\n\n Returns:\n a list of dict, each has keys including:\n 'height', 'width', 'id', 'file_name',\n and (if add_gt is True) 'boxes', 'class', 'is_crowd', and optionally\n 'segmentation'.\n \"\"\"\n assert add_gt == True, 'Temporal, add_gt must be true for now'\n\n with timed_operation('Load images and labels for {}'.format(self.name)):\n # first try to load from cache\n try:\n imgs = load_from_cache(self.name, ctime=os.path.getmtime(__file__))\n logger.info('Loaded from cache {}'.format(self.name + '.pkl'))\n except IOError:\n imgs = [{'fn_img': f[0], 'fn_label': f[1]} for f in self._imageset]\n valid_imgs = []\n for img in imgs:\n try:\n self._use_absolute_file_name(img)\n except IOError:\n logger.info('skipping {}'.format(img['file_name']))\n continue\n valid_imgs.append(img)\n imgs, valid_imgs = valid_imgs, imgs\n save_to_cache(imgs, self.name)\n return imgs\n\n def _use_absolute_file_name(self, img):\n \"\"\"\n Change relative filename to abosolute file name.\n \"\"\"\n fn_img, fn_label = img['fn_img'], img['fn_label']\n\n img['id'] = fn_img.split('_')[-1].split('.')[0]\n # img['id'] = '_'.join(os.path.split(fn_img)[-1].split('_')[:3])\n img['fn_img'] = os.path.join(self._basedir, 'images', fn_img)\n img['fn_label'] = os.path.join(self._basedir, 'annotations', fn_label)\n\n if not os.path.isfile(img['fn_img']):\n raise IOError\n if not os.path.isfile(img['fn_label']):\n raise IOError\n\n # def print_class_histogram(self, imgs):\n # nr_class = len(DSSMeta.class_names)\n # hist_bins = np.arange(nr_class + 1)\n #\n # # Histogram of ground-truth objects\n # gt_hist = np.zeros((nr_class,), dtype=np.int)\n # for entry in imgs:\n # # filter crowd?\n # gt_inds = np.where(\n # (entry['class'] > 0) & (entry['difficult'] == 0))[0]\n # gt_classes = entry['class'][gt_inds]\n # gt_hist += np.histogram(gt_classes, bins=hist_bins)[0]\n # data = [[DSSMeta.class_names[i], v] for i, v in enumerate(gt_hist)]\n # data.append(['total', sum([x[1] for x in data])])\n # table = tabulate(data, headers=['class', '#box'], tablefmt='pipe')\n # logger.info(\"Ground-Truth Boxes:\\n\" + colored(table, 'cyan'))\n\n @staticmethod\n def load_many(basedir='', names=[], add_gt=True):\n \"\"\"\n Load and merges several instance files together.\n\n Returns the same format as :meth:`DSSDetection.load`.\n \"\"\"\n # to simplify things\n if not basedir:\n basedir = cfg.DATA.COCOSTUFF.BASEDIR\n if isinstance(names, str) and names in ('train', 'test'):\n names = getattr(cfg.DATA.COCOSTUFF, names.upper())\n\n if not isinstance(names, (list, tuple)):\n names = [names]\n ret = []\n for n in names:\n db = COCOSTUFFSegmentation(basedir, n)\n ret.extend(db.load(add_gt))\n return ret\n\n\nif __name__ == '__main__':\n basedir = os.path.expanduser('~/dataset/cityscapes')\n names = ['cityscapes_train']\n annots = COCOSTUFFSegmentation.load_many(basedir, names)\n\n # c = DSSDetection(cfg.DATA.BASEDIR, 'train2014')\n # gt_boxes = c.load(add_gt=True, add_mask=True)\n # print(\"#Images:\", len(gt_boxes))\n # c.print_class_histogram(gt_boxes)\n","repo_name":"eldercrow/segmentation-tf","sub_path":"dataset/cocostuff.py","file_name":"cocostuff.py","file_ext":"py","file_size_in_byte":5086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"37825344311","text":"#!/usr/bin/env python3\nimport argparse\nimport os\nimport string\nimport shutil\n\nclass Polygon:\n def __init__(self, no_of_sides):\n self.n = no_of_sides\n self.sides = [0 for i in range(no_of_sides)]\n\n def inputSides(self):\n self.sides = [float(input(\"Enter side \"+str(i+1)+\" : \")) for i in range(self.n)]\n\n def dispSides(self):\n for i in range(self.n):\n print(\"Side\",i+1,\"is\",self.sides[i])\n\nclass Triangle(Polygon):\n def __init__(self):\n Polygon.__init__(self,3)\n\n def findArea(self):\n a, b, c = self.sides\n # calculate the semi-perimeter\n s = (a + b + c) / 2\n area = (s*(s-a)*(s-b)*(s-c)) ** 0.5\n print('The area of the triangle is %0.2f' %area)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('number_of_sides', type=int, help='Enter a number of sides of a Polygon')\n args = parser.parse_args()\n square = Polygon(args.number_of_sides)\n square.inputSides()\n square.dispSides()\n t = Triangle()\n t.inputSides()\n t.findArea()","repo_name":"Rick374/python_scripts","sub_path":"class_example3.py","file_name":"class_example3.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"9062508581","text":"import sys\nimport subprocess\nimport os\nimport re\nimport threading\nimport drm4g.communicators\nfrom drm4g.communicators import ComException\nfrom drm4g.utils.url import urlparse\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nimport stat\nexecution_permissions = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH\n\nclass Communicator(drm4g.communicators.Communicator):\n \"\"\"\n Interact with local resources using shell commands\n \"\"\"\n _lock = threading.Lock()\n\n def connect(self):\n logger.debug( \"Your are using the local communicator\" )\n\n def execCommand(self, command, input=None ):\n command_proc = subprocess.Popen(command,\n shell = True,\n stdin = subprocess.PIPE,\n stdout = subprocess.PIPE,\n stderr = subprocess.PIPE,\n env = os.environ)\n if input :\n for line in input.split():\n command_proc.stdin.write(\"%s\\n\" % line)\n command_proc.stdin.flush()\n stdout, stderr = command_proc.communicate(\"%s\\n\" % line)\n else :\n stdout, stderr = command_proc.communicate()\n return stdout.decode() , stderr.decode()\n\n def mkDirectory(self, url):\n to_dir = self._set_dir(urlparse(url).path)\n out, err = self.execCommand(\"mkdir -p %s\" % to_dir )\n if err:\n output = \"Could not create %s directory: %s \" % ( to_dir , ' '.join( err.split( '\\n' ) ) )\n logger.error( output )\n raise ComException( output )\n\n def copy(self, source_url, destination_url, execution_mode):\n with self._lock:\n if 'file://' in source_url:\n from_dir = urlparse(source_url).path\n to_dir = self._set_dir(urlparse(destination_url).path)\n else:\n from_dir = self._set_dir(urlparse(source_url).path)\n to_dir = urlparse(destination_url).path\n out, err = self.execCommand(\"cp -r %s %s\" % (from_dir,to_dir))\n if err:\n output = \"Could not copy from %s to %s : %s\" % ( from_dir, to_dir , ' '.join( err.split( '\\n' ) ) )\n logger.error( output )\n raise ComException( output )\n if execution_mode == 'X':\n os.chmod(to_dir, execution_permissions )\n\n def rmDirectory(self, url):\n to_dir = self._set_dir(urlparse(url).path)\n out, err = self.execCommand(\"rm -rf %s\" % to_dir )\n if err:\n output = \"Could not remove %s directory: %s \" % ( to_dir , ' '.join( err.split( '\\n' ) ) )\n logger.error( output )\n raise ComException( output )\n\n def checkoutLock(self, url):\n to_dir = self._set_dir(urlparse(url).path)\n return os.path.isfile( '%s/.lock' % to_dir )\n\n def close(self):\n pass\n\n\n #internal\n def _set_dir(self, path):\n work_directory = os.path.expanduser( self.work_directory )\n return re.compile( r'^~' ).sub( work_directory , path )\n\n\n","repo_name":"SantanderMetGroup/DRM4G","sub_path":"drm4g/communicators/local.py","file_name":"local.py","file_ext":"py","file_size_in_byte":3058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"74252142500","text":"from address import *\nfrom payroll import *\nfrom productivity import *\n\n\nclass Employee(AsDictionaryMixin):\n def __init__(self, id, name, address, role, payroll):\n self.id = id\n self.name = name\n self.address = address\n self._role = role\n self._payroll = payroll\n\n def work(self, hours):\n duties = self._role.perform_duties(hours)\n print('Employee', self.id, self.name)\n print(duties)\n self._payroll.track_work(hours)\n\n def calculate_payroll(self):\n return self._payroll.calculate_payroll()\n\n\nclass EmployeeDatabase:\n def __init__(self):\n self._employees = [\n {\n 'id': 1,\n 'name': 'Ivan Ivanov',\n 'role': 'manager'\n },\n {\n 'id': 2,\n 'name': 'Petr Petrov',\n 'role': 'secretary'\n },\n {\n 'id': 3,\n 'name': 'Sidr Sidorov',\n 'role': 'sales'\n },\n {\n 'id': 4,\n 'name': 'Roman Grushenkov',\n 'role': 'factory'\n }\n ]\n self.productivity = ProductivitySystem()\n self.payroll = PayrollSystem()\n self.employee_addresses = AddressBook()\n\n @property\n def employees(self):\n return [self._create_employee(**data) for data in self._employees]\n\n def _create_employee(self, id, name, role):\n address = self.employee_addresses.get_employee_address(id)\n employee_role = self.productivity.get_role(role)\n payroll_policy = self.payroll.get_policy(id)\n return Employee(id, name, address, employee_role, payroll_policy)","repo_name":"Disi13/work_system","sub_path":"employees/employee.py","file_name":"employee.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"26751779107","text":"def main():\n with open(\"input.txt\") as f:\n input = f.readline()\n\n # #### Puzzle 1 #### #\n\n marker = find_marker(input, 4)\n print(\"Packet marker at:\", marker)\n\n # #### Puzzle 2 #### #\n\n marker = find_marker(input, 14)\n print(\"Message marker at:\", marker)\n\n\ndef find_marker(input: str, length: int) -> int:\n for i, c in enumerate(input):\n if i < length-1:\n continue\n marker_list = input[i-(length-1):i+1]\n if len(marker_list) == len(set(marker_list)):\n return i + 1\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"pkemkes/advent-of-code","sub_path":"2022/06/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"16260442739","text":"# -*- coding: utf-8 -*-\nimport pandas as pd\nimport pandas.io.data as web\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mticker\nimport matplotlib.dates as mdates\nfrom matplotlib.dates import date2num\nimport matplotlib\nfrom matplotlib.finance import candlestick_ochl\nmatplotlib.rcParams.update({'font.size':9})\n\n# from pandas import DataFrame\n\ndef Graph(code, start_date, end_date):\n\n# DB = web.DataReader(code + str('.KS'), \"yahoo\", start_date, end_date)\n# DB['MA20'] = pd.stats.moments.rolling_mean(DB['Adj Close'], 20)\n# DB['MA200'] = pd.stats.moments.rolling_mean(DB['Adj Close'], 200)\n# DB.to_csv(code + str('.csv'))\n\n DB = pd.read_csv(code + str('.csv'))\n\n CandleData = []\n DateIndex = []\n for index, row in DB.iterrows():\n date = datetime.strptime(row['Date'], \"%Y-%m-%d\")\n DateIndex.append(date2num(date))\n append_me = date2num(date), row['Open'], row['High'], row['Low'], row['Close'], row['Volume']\n CandleData.append(append_me)\n\n\n #t = datetime.strptime(row['Date'], \"%Y-%m-%d\")\n #DateIndex.append( t.strftime(\"%Y%m%d\") )\n\n\n # Display Chart\n scale = 1.0\n fig = plt.figure(figsize=(6 * scale, 4 * scale), facecolor='#07000d')\n\n #chart1 = plt.subplot(2, 1, 1)\n chart1 = plt.subplot2grid((5,4), (0,0), rowspan=4, colspan=4, axisbg='#07000d')\n chart1.plot_date(DateIndex, DB['Adj Close'], '-', color='#808080', linewidth=1.0, label='Close')\n chart1.plot_date(DateIndex, DB['MA20'], '-', color='#FF0000', linewidth=2.0, label='MA20')\n chart1.plot_date(DateIndex, DB['MA200'], '-', color='#0000FF', linewidth=2.0, label='MA200')\n #candlestick_ochl(chart1, CandleData, width=0.4, colorup='#77d879', colordown='#db3f3f')\n\n\n chart1.xaxis.set_major_locator(mticker.MaxNLocator(10))\n chart1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))\n chart1.yaxis.label.set_color('#FFFFFF')\n chart1.spines['bottom'].set_color('#5998FF')\n chart1.spines['top'].set_color('#5998FF')\n chart1.spines['left'].set_color('#5998FF')\n chart1.spines['right'].set_color('#5998FF')\n #chart1.grid(False, color='#FFFFFF')\n\n plt.ylabel('Stock price')\n plt.axhline(y=0.0, xmin=0, xmax=1, hold=None)\n plt.title(code)\n plt.legend()\n plt.xticks(rotation=45)\n plt.setp(chart1.get_xticklabels(), visible=False)\n\n\n #chart2 = plt.subplot(2, 1, 2, sharex=chart1)\n chart2 = plt.subplot2grid((5,4), (4,0), sharex=chart1, rowspan=1, colspan=4, axisbg='#07000d')\n chart2.bar(DateIndex, DB['Volume'])\n #chart2.plot_date(DateIndex, DB['Volume'], '-', color='#808080', linewidth=1.0, label='Close')\n chart2.xaxis.set_major_locator(mticker.MaxNLocator(10))\n chart2.axes.yaxis.set_ticklabels([])\n chart2.grid(False)\n chart2.spines['bottom'].set_color('#5998FF')\n chart2.spines['top'].set_color('#5998FF')\n chart2.spines['left'].set_color('#5998FF')\n chart2.spines['right'].set_color('#5998FF')\n\n plt.ylabel('Price')\n plt.xticks(rotation=45)\n plt.xlabel('Date')\n plt.subplots_adjust(left=0.09, bottom=0.05, right=0.96, top=0.96, wspace=0.2, hspace=0)\n\n plt.show()\n fig.savefig(code, dpi=600)\n\n\nif __name__ == \"__main__\":\n code = '003490' # 003490, 005930\n start_date = datetime(2011, 1, 1)\n end_date = datetime.now()\n\n Graph(code, start_date, end_date)","repo_name":"bskang7777/python","sub_path":"08.Graph/Graph.py","file_name":"Graph.py","file_ext":"py","file_size_in_byte":3368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"36093718675","text":"def distinct_crashIDs(spark):\n vehicle_df = spark.read.csv(path=\"src/datasets/Units_use.csv\", sep=\",\", header=True, quote='\"', inferSchema=True)\n damages_df = spark.read.csv(path=\"src/datasets/Damages_use.csv\", sep=\",\", header=True, quote='\"', inferSchema=True)\n\n joined_vehicle_damages_df = vehicle_df.join(damages_df, vehicle_df.CRASH_ID == damages_df.CRASH_ID, 'inner').drop(vehicle_df.CRASH_ID)\n\n arr_vehicle_damage_scl = ['DAMAGED 5', 'DAMAGED 6', 'DAMAGED 7 HIGHEST']\n filter_df_from_vehDamageScl = joined_vehicle_damages_df.filter(joined_vehicle_damages_df.VEH_DMAG_SCL_1_ID.isin(arr_vehicle_damage_scl)).filter(joined_vehicle_damages_df.VEH_DMAG_SCL_2_ID.isin(arr_vehicle_damage_scl)).select('CRASH_ID', 'VEH_BODY_STYL_ID', 'FIN_RESP_TYPE_ID')\n df_filtered_crashIDs_from_insurance = filter_df_from_vehDamageScl.select('CRASH_ID', 'FIN_RESP_TYPE_ID').where((filter_df_from_vehDamageScl.FIN_RESP_TYPE_ID == 'LIABILITY INSURANCE POLICY') | (filter_df_from_vehDamageScl.FIN_RESP_TYPE_ID == 'PROOF OF LIABILITY INSURANCE'))\n\n count_of_CrashIDs = df_filtered_crashIDs_from_insurance.distinct().count()\n\n return count_of_CrashIDs","repo_name":"maxkashyap41/BCG_CaseStudy","sub_path":"src/count_distinct_crashIDs_7.py","file_name":"count_distinct_crashIDs_7.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"751099792","text":"from replit import db\nimport json\nimport string\nimport random\nimport os\nimport threading\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\n\nclass WebserverHandler(BaseHTTPRequestHandler):\n def _set_response(self):\n self.send_response(200)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n def do_POST(self):\n content_length = int(self.headers['Content-Length']) \n post_data = self.rfile.read(content_length)\n self._set_response()\n \n if self.path == \"/api\":\n try:\n data = json.loads(post_data.decode('utf-8'))\n LINK = data[\"link\"]\n except:\n message = \"{'message': 'Failed.'}\"\n self.wfile.write(bytes(message, \"utf8\"))\n return 0\n s = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(100))\n db[f\"{s}\"] = LINK\n Outputlink = f'https://AEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAE-1.mewhenamongusss.repl.co/{s}'\n message = \"{'message': 'Success.', 'link': '\",Outputlink,\"'}\"\n message = list(message)\n message = \"\".join(message)\n \n else:\n message = 'bruh its /api not this one'\n self.wfile.write(bytes(message, \"utf8\"))\n def do_GET(self):\n self._set_response()\n if self.path == '/':\n message = 'Made by the worlds most based man - Walter#8951'\n else:\n message = \"\"\n try:\n replaced = self.path.replace('/', '')\n if db[replaced]:\n message += f\"\"\n except:\n message += 'Hello.'\n self.wfile.write(bytes(message, \"utf8\"))\n def log_message(self, format, *args):\n pass\ndef run(server_class=HTTPServer, handler_class=WebserverHandler, port=8080):\n server_address = ('', port)\n httpd = server_class(server_address, handler_class)\n print(\"starting http server..\")\n try:\n httpd.serve_forever()\n except KeyboardInterrupt:\n pass\n httpd.server_close()\n print('stopping http server...')\nrun()\n","repo_name":"ProYT303/AEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEAE-server","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"42582095513","text":"import io\nfrom tqdm import tqdm\n\npath = \"D:\\\\Drive\\\\__TCC__Reranker\\\\Reranker\\\\common_data\\\\04-inference_files\\\\dev.d100.tsv\"\n\nnew_lines = list()\n\n\nwith io.open(path, \"r\", encoding='utf8') as f:\n for line in tqdm(f):\n fields = line.split(\"\\t\")\n query_id = fields[0]\n doc_id = fields[2]\n new_line = f\"{query_id}\\t0\\t{doc_id}\\n\"\n new_lines.append(new_line)\nprint(len(new_lines))\n\noutput = \"D:\\\\Drive\\\\__TCC__Reranker\\\\Reranker\\\\common_data\\\\eval\\\\reference_file.tsv\"\nwith io.open(output,'w',encoding='utf8') as f:\n for line in new_lines:\n f.write(line)","repo_name":"Valerieps/Preprocessing-techniques-with-Reranker","sub_path":"common_scripts/5_make_reference_file.py","file_name":"5_make_reference_file.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"27853288346","text":"class GameSettings():\n\n def __init__(self):\n self.main_options = [\n {\n \"text\": \"I'm new in town, is there any work to be had?\",\n \"input_key\": \"1\"\n },\n {\n \"text\": \"I'd like to browse your wares, inkeep\",\n \"input_key\": \"2\"\n },\n {\n \"text\": \"Have you heard any rumors of interest lately?\",\n \"input_key\": \"3\"\n },\n {\n \"text\": \"I must be on my way. Fare the well\",\n \"input_key\": \"4\"\n },\n ]\n","repo_name":"tedirland/oop","sub_path":"GameSettings.py","file_name":"GameSettings.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"422981661","text":"# 生成学科领域的节点csv文件\n# 主键为'name',内容为学科领域名字\n# 学科领域从论文详情页抽取,人才详情页其实也有,暂时不抽取\n\nimport csv\nimport os\nimport file_util\nimport base_generator\n\nclass SubjectGenerator(base_generator.BaseGenerator):\n\n @property\n def output_filename(self):\n return \"../data_output/node_subjects.csv\"\n\n @property\n def header(self):\n return ['name:ID(Subject-ID)', ':LABEL']\n\n def __init__(self, input_path):\n super().__init__(input_path)\n\n def generate_one_file(self, input_filename):\n num = 0 # 生成的节点或关系数\n actual_filename = self.input_path + '/' + input_filename\n with open(actual_filename, 'r', encoding='utf-8') as fin:\n reader = csv.DictReader(fin)\n with open(self.output_filename, 'a+', encoding='utf-8', newline='') as fout:\n writer = csv.DictWriter(fout, self.header)\n for row in reader:\n subjects_str = row['subject']\n if len(subjects_str) < 1:\n continue\n # 得到subject列表\n subjects = subjects_str.split(';')\n subject_row = {} #待存入的一行subject的信息\n for subject in subjects:\n subject_row[':LABEL'] = 'Subject' # 打上subject的node标签\n # 提取出subject的名字,并作为唯一id\n subject_row['name:ID(Subject-ID)'] = subject.strip()\n writer.writerow(subject_row)\n num += 1\n return num\n\n\nif __name__ == '__main__':\n g = SubjectGenerator('../data_input')\n g.generate_one_file('2021_journal.csv')","repo_name":"aFlyBird0/data_import","sub_path":"src/node_subject.py","file_name":"node_subject.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"40396516164","text":"from keras.models import load_model\r\nimport os\r\nimport cv2\r\nimport numpy as np\r\nfrom PIL import Image\r\nimport csv\r\nimport sys\r\n\r\nif len(sys.argv) < 2:\r\n sys.exit(__doc__)\r\nmodel_name = sys.argv[1]\r\n\r\nmodel = load_model(os.path.join('saved_models\\\\', model_name))\r\nprint(\"Model \" + model_name + \" loaded\")\r\n\r\nTEST_PATH = 'test'\r\nROTATED_PATH = 'test_rotated'\r\n\r\nPREDICTIONS = {0: 'upright', 1: 'upside_down', 2: 'rotated_right', 3: 'rotated_left'}\r\n# Rotations in degrees needed for each class\r\nROTATIONS = {0: 0, 1: 180, 2: 90, 3: 270}\r\n\r\nX = []\r\n\r\n# Reading test set images\r\nfor img in os.listdir('test'):\r\n img = cv2.imread(os.path.join(TEST_PATH, img))\r\n X.append(np.array(img))\r\n\r\n# Predicting classes\r\nprint(\"Making predictions...\")\r\ny = model.predict_classes(np.array(X))\r\n\r\ncorrected = []\r\n\r\n# Correcting images rotation and mounting predictions csv file\r\nprint(\"Rotating images...\")\r\nwith open('test.preds.csv', mode='w') as csv_file:\r\n writer = csv.writer(csv_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL, lineterminator = '\\n')\r\n writer.writerow(['fn', 'label'])\r\n for idx, img in enumerate(os.listdir('test_rotated')):\r\n pill_img = Image.open(os.path.join(ROTATED_PATH, img))\r\n rotated_img = pill_img.rotate(ROTATIONS[y[idx]])\r\n rotated_img.save(os.path.join(ROTATED_PATH, img))\r\n corrected.append(np.array(rotated_img))\r\n writer.writerow([img, PREDICTIONS[y[idx]]])\r\n\r\nnp.save('corrected_imgs', corrected)\r\n","repo_name":"gsbevilaqua83/faces-orientation-correction","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"866482048","text":"class Student():\n def __init__(self, Name, Age):\n self.name = Name\n self.age = Age \n \n\nn = int(input(\"Input number of students: \"))\nstudent = []\n\nfor i in range(n):\n name = input(\"Input name of the \" + str(i + 1) + \"st student: \")\n age = int(input(\"Input age of the \" + str(i + 1) + \"st student: \"))\n student.append(Student(name, age))\n\nprint(\"------------------------------------------------\\n\")\nfor i in range(n):\n print(\"The information of the \" + str(i + 1) + \"st student is: \")\n print(\"Name: \", student[i].name)\n print(\"Age: \", student[i].age)\n\n","repo_name":"giang09101999/giang09101999","sub_path":"Python/OOP/Input and print information of students.py","file_name":"Input and print information of students.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"20185491802","text":"from pyvips import Image as VipsImage\nfrom tifffile import astype\n\nfrom pims.cache import cached_property\nfrom pims.formats import AbstractFormat\nfrom pims.formats.utils.abstract import CachedDataPath\nfrom pims.formats.utils.engines.tifffile import TifffileChecker, TifffileParser, cached_tifffile\nfrom pims.formats.utils.histogram import DefaultHistogramReader\nfrom pims.formats.utils.structures.metadata import ImageMetadata, MetadataStore\nfrom pims.formats.utils.structures.pyramid import Pyramid\nfrom pims.utils.types import parse_float, parse_int\nfrom pims_plugin_format_openslide.utils.engine import OpenslideVipsReader\n\n\nclass NDPIChecker(TifffileChecker):\n @classmethod\n def match(cls, pathlike: CachedDataPath) -> bool:\n try:\n if super().match(pathlike):\n tf = cls.get_tifffile(pathlike)\n return tf.is_ndpi\n return False\n except RuntimeError:\n return False\n\n\nclass NDPIParser(TifffileParser):\n @cached_property\n def _parsed_ndpi_tags(self) -> dict:\n tags = self.baseline.ndpi_tags\n\n comments = tags.get(\"Comments\", None)\n if comments:\n # Comments tag (65449): ASCII key=value pairs (not always present)\n lines = comments.split('\\n')\n for line in lines:\n key, value = line.split('=')\n tags[key.strip()] = astype(value.strip())\n del tags[\"Comments\"]\n return tags\n\n def parse_known_metadata(self) -> ImageMetadata:\n imd = super().parse_known_metadata()\n ndpi_metadata = self._parsed_ndpi_tags\n\n # Magnification extracted by OpenSlide: nominal_magnification\n # Magnification extracted by BioFormats: calibrated_magnification\n imd.objective.nominal_magnification = parse_float(\n ndpi_metadata.get(\"Magnification\")\n )\n imd.objective.calibrated_magnification = parse_float(\n ndpi_metadata.get(\"Objective.Lens.Magnificant\") # noqa\n ) # Not a typo!\n\n imd.microscope.model = ndpi_metadata.get(\"Model\")\n\n # NDPI series: Baseline, Macro, Map\n for series in cached_tifffile(self.format).series:\n name = series.name.lower()\n if name == \"macro\":\n associated = imd.associated_macro\n else:\n continue\n page = series[0]\n associated.width = page.imagewidth\n associated.height = page.imagelength\n associated.n_channels = page.samplesperpixel\n\n imd.is_complete = True\n return imd\n\n def parse_raw_metadata(self) -> MetadataStore:\n store = super().parse_raw_metadata()\n\n skipped_tags = ('McuStarts', '65439')\n for key, value in self._parsed_ndpi_tags.items():\n if key not in skipped_tags:\n store.set(key, value, namespace=\"HAMAMATSU\")\n return store\n\n def parse_pyramid(self) -> Pyramid:\n # Tifffile is inconsistent with Openslide\n # https://github.com/cgohlke/tifffile/issues/41\n openslide = VipsImage.openslideload(str(self.format.path))\n\n pyramid = Pyramid()\n for level in range(parse_int(openslide.get('openslide.level-count'))):\n prefix = f'openslide.level[{level}].'\n pyramid.insert_tier(\n parse_int(openslide.get(prefix + 'width')),\n parse_int(openslide.get(prefix + 'height')),\n (parse_int(openslide.get(prefix + 'tile-width')),\n parse_int(openslide.get(prefix + 'tile-height')))\n )\n\n return pyramid\n\n\nclass NDPIFormat(AbstractFormat):\n \"\"\"\n Hamamatsu NDPI.\n\n References\n https://openslide.org/formats/hamamatsu/\n https://docs.openmicroscopy.org/bio-formats/6.5.1/formats/hamamatsu-ndpi.html\n\n \"\"\"\n checker_class = NDPIChecker\n parser_class = NDPIParser\n reader_class = OpenslideVipsReader\n histogram_reader_class = DefaultHistogramReader\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._enabled = True\n\n @classmethod\n def get_name(cls):\n return \"Hamamatsu NDPI\"\n\n @classmethod\n def is_spatial(cls):\n return True\n\n @cached_property\n def need_conversion(self):\n return False\n","repo_name":"Cytomine-ULiege/pims-plugin-format-openslide","sub_path":"pims_plugin_format_openslide/ndpi.py","file_name":"ndpi.py","file_ext":"py","file_size_in_byte":4304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"39220311053","text":"# -*- coding: utf-8 -*-\n# SPDX-License-Identifier: MIT\n\n\"\"\"Read from tar format archives.\n\nThis module provides only a simple interface for iterating\nthe entries of a tar archive, and provides no direct means of extracting\nthose entries directly to disk.\n\nAdditionally, this module operates as a stream from the tar archive\nand does not provide a means to directly extract a single entry.\n\n >>> with open('archive.tar', 'rb') as f:\n found = None\n for entry in iter_tar(f):\n if str(entry.name) == 'sentinel.txt':\n found = entry\n if found is None:\n raise KeyError('sentinel.txt')\n with found.name.open(mode='wb') as out:\n shutil.copyfileobj(found, out)\n out.seek(found.size)\n out.truncate()\n found.name.chmod(found.mode)\n os.chown(found.name, found.uid, found.gid)\n\n\"\"\"\n\nimport array as _array\nimport collections.abc as _collections_abc\nimport io as _io\nimport mmap as _mmap\nimport pathlib as _pathlib\nimport re as _re\nimport sys as _sys\nimport tarfile as _tarfile\nimport threading as _threading\nimport typing as _typing\nfrom struct import unpack_from as _unpack_from\nfrom tarfile import nti as _tarfile_nti # type: ignore\nfrom tarfile import nts as _tarfile_nts # type: ignore\n\n__version__ = '0.0.1'\n__all__ = ('TarEntry', 'iter_tar')\n\n_ENCODING = _sys.getfilesystemencoding()\n_ERRORS = 'surrogateescape'\n\n_EXT_HEADERS = frozenset((\n _tarfile.XHDTYPE, _tarfile.XGLTYPE, _tarfile.SOLARIS_XHDTYPE,\n _tarfile.GNUTYPE_LONGNAME, _tarfile.GNUTYPE_LONGLINK,\n))\n_GNU_LONG_HEADERS = frozenset((\n _tarfile.GNUTYPE_LONGNAME, _tarfile.GNUTYPE_LONGLINK\n))\n_PAX_HEADER_RE = _re.compile(br'(\\d+) ([^=]+)=([^\\n]+)\\n')\n_PAX_HDRCHARSET_RE = _re.compile(br'\\d+ hdrcharset=([^\\n]+)\\n')\n_PAX_OVERRIDE_FIELDS = frozenset((\n 'uname',\n 'gname',\n 'size',\n 'mtime',\n 'uid',\n 'gid',\n))\n\n_TypingBytesLike = _typing.Union[\n bytes,\n bytearray,\n memoryview,\n _array.array,\n _mmap.mmap,\n]\n\n\nclass TarEntry:\n \"\"\"Object that holds information about a particular entry in a tar archive\n \"\"\"\n def __init__(\n self,\n fp: _typing.BinaryIO,\n header: bytes,\n lock: _threading.Lock,\n pax_headers: _typing.Optional[dict[str, str]] = None,\n gnu_long: _typing.Optional[dict[str, str]] = None,\n ):\n\n self._fp = fp\n self._header = header\n self._lock = lock\n self.pax_headers: dict[str, str] = pax_headers or {}\n self._gnu_long: dict[str, str] = gnu_long or {}\n\n self._name: _typing.Optional[str] = None\n self.mode: int = _tarfile_nti(header[100:108])\n self.uid: int = _tarfile_nti(header[108:116])\n self.gid: int = _tarfile_nti(header[116:124])\n self._size: int = _tarfile_nti(header[124:136])\n self.mtime: int = _tarfile_nti(header[136:148])\n # TODO: Validate checksum here?\n self.checksum: int = _tarfile_nti(header[148:156])\n self.type: bytes = header[156:157]\n self._linkname: str = _tarfile_nts(header[157:257], _ENCODING, _ERRORS)\n self.uname: str = _tarfile_nts(header[265:297], _ENCODING, _ERRORS)\n self.gname: str = _tarfile_nts(header[297:329], _ENCODING, _ERRORS)\n self.devmajor: int = _tarfile_nti(header[329:337])\n self.devminor: int = _tarfile_nti(header[337:345])\n\n with self._lock:\n self._position = fp.tell()\n\n def __getattribute__(\n self,\n name: str,\n ) -> _typing.Union[str, int, float]:\n\n if name not in _PAX_OVERRIDE_FIELDS:\n # Not overridden by PaxHeader\n return object.__getattribute__(self, name)\n\n try:\n value = self.pax_headers[name]\n except KeyError:\n # No override by PaxHeader\n return object.__getattribute__(self, name)\n\n try:\n return _tarfile.PAX_NUMBER_FIELDS[name](value)\n except ValueError:\n return 0\n except KeyError:\n return value\n\n def gnu_sparse(\n self,\n name: str,\n ) -> _typing.Optional[str]:\n \"\"\"Helper method for fetching ``GNU.sparse.*`` PAX headers\n \"\"\"\n return self.pax_headers.get(f'GNU.sparse.{name}')\n\n @property\n def name(self) -> _pathlib.Path:\n \"\"\"Name of the entry in the tarfile\n \"\"\"\n if self._name:\n return _pathlib.Path(self._name)\n\n sparse_name = self.pax_headers.get('GNU.sparse.name')\n long_name = self._gnu_long.get('name')\n pax_name = self.pax_headers.get('path')\n\n prefix: _typing.Optional[str]\n name: str\n\n if sparse_name:\n prefix = None\n name = sparse_name\n elif long_name:\n prefix = None\n name = long_name\n elif pax_name:\n prefix = None\n name = pax_name\n else:\n prefix = _tarfile_nts(self._header[345:500], _ENCODING, _ERRORS)\n name = _tarfile_nts(self._header[0:100], _ENCODING, _ERRORS)\n\n if self.type not in _tarfile.GNU_TYPES and prefix:\n self._name = f'{prefix}/{name}'\n else:\n self._name = name\n\n return _pathlib.Path(self._name)\n\n @property\n def linkname(self) -> _typing.Optional[_pathlib.Path]:\n \"\"\"Link name of the entry in the tarfile\n \"\"\"\n longlink: _typing.Optional[str] = self._gnu_long.get('linkname')\n linkpath: _typing.Optional[str] = self.pax_headers.get('linkpath')\n linkname: _typing.Optional[str] = (\n longlink or linkpath or self._linkname\n )\n if linkname:\n return _pathlib.Path(linkname)\n return None\n\n @property\n def size(self) -> int:\n \"\"\"Size of the entry in the tarfile\n \"\"\"\n size = self._size\n pax_size: _typing.Optional[str] = self.pax_headers.get('size')\n sparse_size: _typing.Optional[str] = (\n self.gnu_sparse('size') or self.gnu_sparse('realsize')\n )\n return int(sparse_size or pax_size or size)\n\n def is_checksum_valid(self) -> bool:\n \"\"\"Determine ff the checksum of the header is valid\n \"\"\"\n checksums: tuple[int, int] = (\n 256 + sum(_unpack_from('148B8x356B', self._header)), # unsigned\n 256 + sum(_unpack_from('148b8x356b', self._header)) # signed\n )\n return self.checksum in checksums\n\n def is_dir(self) -> bool:\n \"\"\"Determine if the entry type is a directory\n \"\"\"\n return self.type == _tarfile.DIRTYPE\n\n def is_file(self) -> bool:\n \"\"\"Determine if the entry type is a regular file\n \"\"\"\n return self.type in _tarfile.REGULAR_TYPES\n\n def is_symlink(self) -> bool:\n \"\"\"Determine if the entry type is a symlink\n \"\"\"\n return self.type == _tarfile.SYMTYPE\n\n def is_sparse(self) -> bool:\n \"\"\"Determine if the entry type is a sparse file\n \"\"\"\n return any((\n self.type == _tarfile.GNUTYPE_SPARSE,\n self.pax_headers.get('GNU.sparse.realsize'),\n ))\n\n def is_char_device(self) -> bool:\n \"\"\"Determine if the entry type is a CHR device\n \"\"\"\n return self.type == _tarfile.CHRTYPE\n\n def is_block_device(self) -> bool:\n \"\"\"Determine if the entry type is a BLK device\n \"\"\"\n return self.type == _tarfile.BLKTYPE\n\n def is_fifo(self) -> bool:\n \"\"\"Determine if the entry type is a FIFO\n \"\"\"\n return self.type == _tarfile.FIFOTYPE\n\n def seek(\n self,\n offset: int,\n whence: int = _io.SEEK_SET,\n ) -> int:\n \"\"\"Move to new file position.\n\n Argument offset is a byte count. Optional argument whence defaults to\n io.SEEK_SET or 0 (offset from start of entry, offset should be >= 0);\n other values are io.SEEK_CUR or 1 (move relative to current position,\n positive or negative), and io.SEEK_END or 2 (move relative to end of\n entry, must be negative, does not allow seeking beyond the end of an\n entry).\n \"\"\"\n with self._lock:\n return self._seek(offset, whence)\n\n def _seek(\n self,\n offset: int,\n whence: int = _io.SEEK_SET,\n ) -> int:\n\n end = self._position + self._size\n cur = self._fp.tell()\n new = cur + offset\n conditions = (\n whence == _io.SEEK_SET and offset > self._size,\n whence == _io.SEEK_CUR and new > end,\n whence == _io.SEEK_CUR and new < self._position,\n whence == _io.SEEK_END and offset > 0,\n whence == _io.SEEK_END and new < self._position,\n )\n\n if any(conditions):\n raise ValueError(\n f'seek cannot exceed entry size: {self._size}'\n )\n\n if whence == _io.SEEK_SET:\n offset = self._position + offset\n elif whence == _io.SEEK_END:\n offset = end + offset\n whence = _io.SEEK_SET\n elif whence != _io.SEEK_CUR:\n offset = self._position + offset\n\n return self._fp.seek(offset, whence) - self._position\n\n def tell(self) -> int:\n \"\"\"Return an int indicating the current stream position.\n \"\"\"\n with self._lock:\n return self._tell()\n\n def _tell(self) -> int:\n end = self._position + self._size\n cur = self._fp.tell()\n relative = cur - self._position\n if cur > end or relative < 0:\n raise OSError('position outside of entry bounds')\n return relative\n\n def read(\n self,\n size: _typing.Optional[int] = -1,\n ) -> bytes:\n \"\"\"Read up to size bytes of the tar entry as specified by the entry\n header and return them. As a convenience, if size is unspecified\n or -1, all bytes until the end of this tar entry are returned.\n\n This method will seek to the start of the entry in the underlying\n file handle if the current position lies outside of the location in\n the tar entry. If the position lies inside of the location in the\n tar entry, the stream position is unmodified before reading, allowing\n for multiple calls to retrieve partial bytes of the entry to\n conserve memory.\n \"\"\"\n with self._lock:\n return self._read(size)\n\n def _read(\n self,\n size: _typing.Optional[int] = -1,\n ) -> bytes:\n\n end = self._position + self._size\n cur = self._fp.tell()\n if cur < self._position or cur > end:\n self._fp.seek(self._position)\n cur = self._position\n\n remaining = end - cur\n\n if size is None or size == -1 or size > remaining:\n size = remaining\n\n return self._fp.read(size)\n\n def readinto(\n self,\n b: _TypingBytesLike,\n ) -> int:\n \"\"\"Read bytes into a pre-allocated, writable bytes-like object b,\n and return the number of bytes read. For example, b might be a\n bytearray.\n \"\"\"\n with self._lock:\n return self._readinto(b)\n\n def _readinto(\n self,\n b: _TypingBytesLike,\n ) -> int:\n\n m = memoryview(b).cast('B')\n data = self.read(len(m))\n n = len(data)\n m[:n] = data\n return n\n\n def __repr__(self) -> str:\n return f'<{self.__class__.__name__} {self.name!r} at {id(self):#x}>'\n\n\ndef _parse_pax_headers(\n entry: TarEntry,\n headers: _typing.Optional[dict[str, str]] = None,\n) -> _typing.Optional[dict[str, str]]:\n\n if not entry.is_checksum_valid():\n return headers\n\n if headers is None:\n headers = {}\n else:\n headers = headers.copy()\n\n header = entry.read()\n hdrcharset = _PAX_HDRCHARSET_RE.search(header)\n if hdrcharset:\n encoding = hdrcharset.group(1).decode('utf-8', 'strict')\n if encoding == 'BINARY':\n encoding = _ENCODING\n else:\n encoding = 'utf-8'\n for length, key, value in _PAX_HEADER_RE.findall(header):\n if not int(length):\n # TODO: Exception?\n continue\n key = key.decode('utf-8', _ERRORS)\n value = value.decode(encoding, _ERRORS)\n headers[key] = value\n\n return headers\n\n\ndef _parse_gnu_headers(\n entry: TarEntry,\n headers: _typing.Optional[dict[str, str]] = None,\n) -> _typing.Optional[dict[str, str]]:\n\n if not entry.is_checksum_valid():\n return headers\n\n if headers is None:\n headers = {}\n else:\n headers = headers.copy()\n\n if entry.type == _tarfile.GNUTYPE_LONGNAME:\n key = 'name'\n elif entry.type == _tarfile.GNUTYPE_LONGLINK:\n key = 'linkname'\n headers[key] = _tarfile_nts(entry.read(), _ENCODING, _ERRORS)\n\n return headers\n\n\ndef _is_binary_fileobj(\n obj: _typing.IO,\n) -> bool:\n\n return isinstance(obj, (_io.RawIOBase, _io.BufferedIOBase))\n\n\ndef iter_tar(\n f: _typing.BinaryIO,\n) -> _collections_abc.Generator[TarEntry, None, None]:\n \"\"\"Iterate over a file handle for a tar archive, and yield ``TarEntry``\n objects representing individual entries.\n\n tar archives allows a path to appear multiple times, with the last one\n having precedence.\n \"\"\"\n if not _is_binary_fileobj(f):\n raise TypeError('binary file object required')\n\n lock = _threading.Lock()\n global_headers: _typing.Optional[dict[str, str]] = None\n pax_headers: _typing.Optional[dict[str, str]] = None\n gnu_long: _typing.Optional[dict[str, str]] = None\n while True:\n with lock:\n header = f.read(512)\n header_end = f.tell()\n\n if not header:\n break\n\n if header.count(b'\\0') == 512:\n continue\n\n entry = TarEntry(\n f,\n header,\n lock,\n pax_headers=pax_headers,\n gnu_long=gnu_long,\n )\n\n if entry.type == _tarfile.XGLTYPE:\n global_headers = _parse_pax_headers(entry)\n elif entry.type in (_tarfile.XHDTYPE, _tarfile.SOLARIS_XHDTYPE):\n pax_headers = _parse_pax_headers(entry, global_headers)\n elif entry.type in _GNU_LONG_HEADERS:\n gnu_long = _parse_gnu_headers(entry)\n else:\n pax_headers = None\n gnu_long = None\n\n if entry.type not in _EXT_HEADERS and entry.name:\n yield entry\n\n end = header_end + entry._size\n mod = end % 512\n with lock:\n if mod:\n f.seek(end + 512 - mod)\n else:\n f.seek(end)\n","repo_name":"sivel/iter_tar","sub_path":"src/iter_tar/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":14638,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"37429075056","text":"from contextlib import contextmanager\nfrom uuid import UUID\n\nfrom sqlalchemy import create_engine, Column, DateTime\nfrom sqlalchemy.orm import sessionmaker, scoped_session\nfrom sqlalchemy_serializer import SerializerMixin\n\nfrom log import logger\nfrom settings import DB_URI\n\nengine = create_engine(DB_URI)\nsession_factory = sessionmaker(bind=engine)\nSession = scoped_session(session_factory)\n\n\nclass CustomSerializerMixin(SerializerMixin):\n serialize_types = ((UUID, lambda x: str(x)),)\n\n\n@contextmanager\ndef context_session() -> 'Session':\n session = Session()\n try:\n yield session\n session.commit()\n session.flush()\n except Exception as e:\n logger.error(e)\n session.rollback()\n raise\n\n\nclass BaseModel(CustomSerializerMixin):\n created_at = Column(DateTime, nullable=False)\n\n def save(self):\n with context_session() as session:\n session.add(self)\n return self\n\n def delete(self):\n with context_session() as session:\n session.delete(self)\n return self\n","repo_name":"rdmsilva/reseller-api","sub_path":"app/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"2241405522","text":"import roslib\nroslib.load_manifest('pandora_end_effector_controller')\nimport rospy\n\nfrom smach import State\nfrom smach_ros import SimpleActionState\nfrom pandora_end_effector_controller.msg import MoveEndEffectorAction, MoveEndEffectorGoal\nfrom pandora_sensor_orientation_controller.msg import MoveSensorAction, MoveSensorGoal\nfrom pandora_linear_actuator_controller.msg import MoveLinearActuatorAction, MoveLinearActuatorGoal\nfrom topics import move_end_effector_controller_topic, move_kinect_topic, \\\n move_head_topic, linear_actuator_movement_topic\n\n\nclass EndEffectorcontrollerState(State):\n\n def __init__(self):\n State.__init__(self, outcomes=['TEST_PARK_TRACK', 'SCAN'],\n input_keys=['move_end_effector_msg'],\n output_keys=['move_end_effector_msg'])\n\n def execute(self, userdata):\n if userdata.move_end_effector_msg.command == \\\n MoveEndEffectorGoal.SCAN:\n return 'SCAN'\n else:\n return 'TEST_PARK_TRACK'\n\n\nclass KinectOrientationState(SimpleActionState):\n\n def __init__(self):\n SimpleActionState.__init__(self, move_kinect_topic,\n MoveSensorAction,\n goal_cb=self.goal_cb,\n outcomes=['succeeded',\n 'aborted',\n 'preempted'],\n input_keys=['move_end_effector_msg'],\n output_keys=['move_end_effector_msg'])\n\n def goal_cb(self, userdata, goal):\n goal = MoveSensorGoal()\n goal.command = userdata.move_end_effector_msg.command\n goal.point_of_interest = \\\n userdata.move_end_effector_msg.point_of_interest\n return goal\n\n\n# class HeadOrientationState(SimpleActionState):\n\n# def __init__(self):\n# SimpleActionState.__init__(self, move_head_topic,\n# MoveSensorAction,\n# goal_cb=self.goal_cb,\n# outcomes=['succeeded',\n# 'aborted',\n# 'preempted'],\n# input_keys=['move_end_effector_msg'],\n# output_keys=['move_end_effector_msg'])\n\n# def goal_cb(self, userdata, goal):\n# goal = MoveSensorGoal()\n# goal.command = userdata.move_end_effector_msg.command\n# goal.point_of_interest = \\\n# userdata.move_end_effector_msg.point_of_interest\n# return goal\n\n\n# class LinearActuatorState(SimpleActionState):\n\n# def __init__(self):\n# SimpleActionState.__init__(self, linear_actuator_topic,\n# MoveLinearActuatorAction,\n# goal_cb=self.goal_cb,\n# outcomes=['succeeded',\n# 'aborted',\n# 'preempted'],\n# input_keys=['move_end_effector_msg'],\n# output_keys=['move_end_effector_msg'])\n\n # def goal_cb(self, userdata, goal):\n # goal = MoveLinearActuatorGoal()\n # goal.command = userdata.move_end_effector_msg.command\n # goal.point_of_interest = \\\n # userdata.move_end_effector_msg.point_of_interest\n # goal.center_point = userdata.move_end_effector_msg.center_point\n # return goal\n","repo_name":"pandora-auth-ros-pkg/pandora_ros_pkgs","sub_path":"pandora_control/pandora_end_effector_controller/src/pandora_end_effector_controller/old/states.py","file_name":"states.py","file_ext":"py","file_size_in_byte":3619,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"35"} +{"seq_id":"29517836051","text":"import logging\nimport os\n\n\ndef get_my_logger(model_name):\n logger = logging.getLogger(model_name+\"_logger\")\n if not os.path.exists(\"log\"):\n os.mkdir(\"log\")\n file_handler = logging.FileHandler(os.path.join(\"log\", model_name+\".log\"))\n stdout_handler = logging.StreamHandler()\n formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')\n file_handler.setFormatter(formatter)\n file_handler.setLevel(logging.DEBUG)\n stdout_handler.setFormatter(formatter)\n stdout_handler.setLevel(logging.INFO)\n logger.addHandler(file_handler)\n logger.addHandler(stdout_handler)\n logger.setLevel(logging.DEBUG)\n\n return logger\n","repo_name":"ZhihaoDU/du2020dan","sub_path":"utils/my_logger.py","file_name":"my_logger.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"35"} +{"seq_id":"41112513464","text":"from pathlib import Path\nimport re\nimport itertools\nfrom urllib import request\n\nimport pytest\n\n\n@pytest.fixture\ndef docs_path():\n return Path('/home/alexandre/projects/neuro/neuro_pypes/docs/')\n\n\n@pytest.fixture\ndef docs_contents(docs_path):\n doc_files = docs_path.glob('**/*.md')\n yield (doc.read_text() for doc in doc_files)\n\n\n@pytest.fixture\ndef docs_urls(docs_contents):\n name_pattern = \"[^]]+\"\n url_pattern = \"http[s]?://[^)]+\"\n markup_pattern = '\\[({0})]\\(\\s*({1})\\s*\\)'.format(name_pattern, url_pattern)\n http_regex = re.compile(markup_pattern, re.IGNORECASE)\n\n doc_urls = (http_regex.findall(content) for content in docs_contents)\n yield itertools.chain(*(url_group for url_group in doc_urls if url_group))\n\n\ndef test_urls(docs_urls):\n for url in docs_urls:\n _test_url(url[1])\n\n\ndef _test_url(url):\n print(url)\n response = request.urlopen(url)\n assert response.status == 200\n","repo_name":"Neurita/pypes","sub_path":"docs/tests/test_links.py","file_name":"test_links.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"35"} +{"seq_id":"74103258979","text":"import numpy as np\nimport cv2\nfrom chessboard_location.chessboard_finder import get_chessboard_intersections\nfrom piece_detection.utils_chess import create_chessboard_from_board_array\nfrom piece_detection.utils_corners import create_chessboard_array_from_assignments, denormalize_piece_info, get_squares_from_corners, is_top_left_white, match_pieces_with_squares\nfrom piece_detection.utils_yolo import predict_image\n\ndef return_board_from_image(img, model, log = True, isRoboflow = False):\n\n if log:\n print(\"-----------------------\")\n print(\"YOLOv5 detecting img...\")\n print(\"-----------------------\")\n # prediction = predict_image(img, model)\n # model_output_denormalized = denormalize_piece_info(prediction, img.shape[1], img.shape[0])\n\n if log:\n print(\"-----------------------\")\n print(\"Getting chessboard intersections...\")\n print(\"-----------------------\")\n corners = get_chessboard_intersections(img)\n if corners is None:\n return None\n \n np.save(\"cornersmb\", corners)\n print(\"array corners saved to file 'cornersmb'\")\n print()\n \n ########### inserted some lines to print out outer corners and save the corner array to a file ###########\n # corners clockwise starting upper left (yx values)\n c1 = corners[0][0]\n c2 = corners[8][0]\n c3 = corners[8][8]\n c4 = corners[0][8]\n\n ### if needed invert corners (xy):\n c1inv = c1[::-1]\n c2inv = c2[::-1] \n c3inv = c3[::-1]\n c4inv = c4[::-1]\n\n print(\"corner 1 x,y\", c1[::-1])\n print(\"corner 2 x,y\", c2[::-1])\n print(\"corner 3 x,y\", c3[::-1])\n print(\"corner 4 x,y\", c4[::-1])\n\n img = cv2.circle(img, (c1[1], c1[0]), radius=5, color=(0, 255, 0), thickness= -1)\n img = cv2.circle(img, (c2[1], c2[0]), radius=5, color=(0, 255, 0), thickness= -1)\n img = cv2.circle(img, (c3[1], c3[0]), radius=5, color=(0, 255, 0), thickness= -1)\n img = cv2.circle(img, (c4[1], c4[0]), radius=5, color=(0, 255, 0), thickness= -1)\n\n cv2.imshow(\"img\", img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n \n #################\n return ##########\n #################\n \n squares = get_squares_from_corners(corners)\n\n assigned_squares_list = match_pieces_with_squares(squares, model_output_denormalized)\n chessboard_array = create_chessboard_array_from_assignments(assigned_squares_list)\n\n fix_color = False # No need for current dataset\n if fix_color and not is_top_left_white(img, squares):\n chessboard_array = np.rot90(chessboard_array, 1, (0, 1))\n\n chessboard = create_chessboard_from_board_array(chessboard_array, isRoboflow)\n\n return chessboard\n","repo_name":"Laterunner/Chess_Game_Tracker","sub_path":"chess_state_recognition/piece_detection/chessboard_detector.py","file_name":"chessboard_detector.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"71496698341","text":"import requests, re, csv\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\nURL = 'https://imsdb.com/all-scripts.html'\nURL_BASE = 'https://www.imsdb.com/scripts/'\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_0) \\\n AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.146 Safari/537.36'\n }\n# save all home page scripts\ndef scrap_list(url):\n response = requests.get(url, headers=headers)\n with open('data/IMSDB_script_list', \"w\") as f:\n f.write(response.text)\nscrap_list(URL)\n\n# create list of movie titles and script urls and saves in csv\ndef movie_list():\n with open('data/IMSDB_script_list', \"r\") as f:\n data = f.read()\n soup = BeautifulSoup(data, features=\"lxml\")\n movies_list = soup.select('p a')\n list_urls = []\n for movie in movies_list:\n #get clean movie title\n clean_title = movie.text\n #get filepath movie title\n movie_title = movie['title']\n movie_title = movie_title.replace(' ', '-')\n movie_title = re.sub(r'\\:', '', movie_title)\n movie_title = re.sub(r'-Script', '', movie_title)\n movie_url = URL_BASE + movie_title + '.html'\n list_urls.append([movie_title, movie_url, clean_title])\n with open('data/movie_titles.csv', 'w', newline='') as f:\n wr = csv.writer(f)\n wr.writerows(list_urls)\n return list_urls\n\n# for each movie url, save script content in a .txt file (and identifies errors)\ndef scrap_script(title, url, clean_title):\n response = requests.get(url, headers=headers)\n soup = BeautifulSoup(response.text, features=\"lxml\")\n tags = soup.select('pre')\n non_scraped = []\n if len(tags) != 0:\n script = tags[-1]\n with open(f'IMSDB_scripts/{title}.txt', \"w\", encoding='utf-8', errors='ignore') as f:\n f.write(clean_title)\n f.write('\\n')\n f.write(script.text)\n else:\n non_scraped.append(title)\n return non_scraped\n\n# create all .txt files\nfor movie in movie_list():\n scrap_script(movie[0], movie[1], movie[2])\n","repo_name":"Yasser-Lahlou/Bechdel-test","sub_path":"scripts_parser.py","file_name":"scripts_parser.py","file_ext":"py","file_size_in_byte":2083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"27633542246","text":"from math import log10\nimport index\n\nk1 = 1.2\nk2 = 100\nb = 0.75\n\n\ndef calcBM25Scores(termCount, myindex, query, coder):\n \"\"\"BM25 Retrieval Model\"\"\"\n \n notTerms = query.get('NOT', [])\n andTerms = query.get('AND', [])\n orTerms = query.get('OR', [])\n\n termIndex = {}\n docids = []\n # Select all docs from OR and AND terms\n terms = orTerms[:]\n terms.extend(andTerms)\n for term in terms:\n tc = index.getTermContent(myindex, term, coder)\n termIndex[term] = tc\n docids.extend(tc.get('docs', []).keys())\n \n # Remove docs from NOT \n exdocids = []\n for term in notTerms:\n tc = index.getTermContent(myindex, term, coder)\n exdocids.extend(tc.get('docs', []).keys())\n \n # Get docs in AND \n indocids = []\n for term in andTerms:\n indocids.extend(termIndex[term].get('docs', []).keys())\n \n # Calc term frequency in query\n qFreq = {}\n for term in terms:\n qFreq[term] = qFreq.setdefault(term, 0) + 1\n \n scores = []\n for docID in docids:\n if docID in exdocids:\n continue\n \n if len(indocids) > 0 and docID not in indocids:\n continue\n \n K = k1 * ((1 - b) + (b * termCount.get(docID) / termCount.get('average')))\n docScore = 0.0\n for term in terms:\n tempScore = log10((termCount['totalDocs'] - termIndex[term].get('count', 0) + 0.5)\n / (termIndex[term].get('count', 0) + 0.5))\n \n tempScore = tempScore * ((k1 + 1) * termIndex[term]['docs'].get(docID, 0.0)) / (K + termIndex[term]['docs'].get(docID, 0.0))\n \n tempScore = tempScore * (((k2 + 1) * qFreq[term]) / (k2 + qFreq[term]))\n docScore = docScore + tempScore\n scores.append([docID, docScore])\t\n return scores,indocids,exdocids\n","repo_name":"bhadresh/dqp","sub_path":"rm/bm25.py","file_name":"bm25.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"35"} +{"seq_id":"2602261042","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"selenium-simplified\",\n version=\"0.18\",\n author=\"rajnish kumar\",\n author_email=\"raajrajnish@gmail.com\",\n description=\"A free, open-source web automation library for the Chrome browser using Selenium Python\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/raajrajnish/SeleniumSimplified.git\",\n packages=setuptools.find_packages(),\n install_requires=['selenium','bs4'],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n)","repo_name":"raajrajnish/SeleniumSimplified","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"16178209440","text":"# -*- coding: utf-8 -*-\n#\n# 写真説明API用メッセージ\n#\n# @author: Hiroki Wakabayashi \n# @version: 0.0.1\n\nimport cloudrobotics.message as message\n\nPROCESSING_ID_PICTURECOGNITION = 'RbAppVisionApi'\n\n# 初期化メッセージ\n#\nclass InitMessage(message.CRFXMessage):\n\n def __init__(self):\n super(InitMessage, self).__init__()\n\n self.header['RoutingType'] = message.ROUTING_TYPE_CALL\n self.header['AppProcessingId'] = PROCESSING_ID_PICTURECOGNITION\n self.header['MessageId'] = 'init'\n\n self.body = {}\n\n# 分析メッセージ\n#\nclass AnalyzeMessage(message.CRFXMessage):\n\n def __init__(self, visitor, file_name, delete_file='true'):\n super(AnalyzeMessage, self).__init__()\n\n self.header['RoutingType'] = message.ROUTING_TYPE_CALL\n self.header['AppProcessingId'] = PROCESSING_ID_PICTURECOGNITION\n self.header['MessageId'] = 'analyze'\n\n self.body = {\n 'visitor': visitor,\n 'blobFileName': file_name,\n 'deleteFile': delete_file\n }\n\n","repo_name":"anzhong70/cloud-robotics-fx-v2","sub_path":"CloudRoboticsApi/ClientCode_Pepper/JBS/PepperCode1/lib/cloudrobotics/picturerecognition/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"41865277800","text":"import paho.mqtt.client as mqtt\nimport serial\nimport time\n\n# Configurações do MQTT Broker\nbroker_address = \"192.168.1.8\" # Substitua pelo endereço do seu servidor MQTT\nport = 1883\ntopic = \"rssi\" # Substitua pelo tópico desejado\nclient_id = \"python-script\"\n\n# Configurações da porta serial\nserial_port = \"/dev/ttyACM0\" # Substitua pelo seu dispositivo serial (exemplo para Linux)\nbaud_rate = 9600\n\n# Função para publicar dados no tópico MQTT\ndef publish_data(client, topic, data):\n client.publish(topic, data)\n print(f\"Dados publicados no tópico {topic}: {data}\")\n\n# Cria um cliente MQTT\nclient = mqtt.Client(client_id)\nclient.connect(broker_address, port)\n\n# Abre a porta serial\nser = serial.Serial(serial_port, baud_rate)\n\ntry:\n while True:\n # Lê dados da porta serial\n data = ser.readline().decode().strip() # Suponha que os dados sejam uma linha de texto\n data = data[15:len(data)]\n try:\n data = int(data)\n if data:\n publish_data(client, topic, data)\n except:\n continue\n\nexcept KeyboardInterrupt:\n ser.close() # Fecha a porta serial\n client.disconnect()\n print(\"Desconectado do servidor MQTT\")\n","repo_name":"pablolucas890/rssi_receiver","sub_path":"send.py","file_name":"send.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"15273839596","text":"from django.shortcuts import get_object_or_404, render, redirect\nfrom django.urls import reverse\nfrom django.utils.deprecation import MiddlewareMixin\nfrom django.contrib.auth.models import Group\n\nfrom Escolas.models import Escola\nfrom usuarios.models import Classificacao\n\n\nclass AuthRequiredMiddleware(MiddlewareMixin):\n def process_request(self, request):\n # REDIRECIONA PARA O INDEX\n # SE O USUÁRIO NÃO ESTIVER AUTENTICADO\n if request.path.startswith('/login/'): # Se estiver no LOGIN, não recebe o redirecionamento de autenticação\n pass\n else: # Qualquer outro caminho, recebe o redirecionamento de autenticação\n if request.user.is_authenticated == False:\n while not (request.path == reverse('fazendo_login')):\n return redirect(reverse('fazendo_login'))\n\n # MIDDLEWARE QUE ANALISA SE É SUPERUSER\n # ADICIONA AO GRUPO DA SECRETARIA\n # SE NÃO HOUVER GRUPO, CRIA GRUPO SECRETARIA E DEPOIS ASSOCIA\n if request.user.is_superuser:\n if not request.user.groups.exists():\n if Group.objects.filter(name='Secretaria').exists():\n grupo = get_object_or_404(Group, name='Secretaria')\n request.user.groups.add(grupo)\n else:\n Group.objects.create(name='Secretaria')\n grupo = get_object_or_404(Group, name='Secretaria')\n request.user.groups.add(grupo)\n print('criou grupo Secretaria')\n # Gerra um SIGNAL que irá criar os outros grupos\n\n # CRIA MATRIZ (ESCOLAR) \"SECRETARIA DA EDUCAÇÃO\" CASO AINDA NAO EXISTA\n # CRIA CLASSIFICACAO DO USUARIO \"SECRETARIA\" CASO AINDA NAO EXISTA\n if request.user.is_superuser:\n if not Escola.objects.filter(nome='Secretaria da educação').exists():\n suprot = Escola.objects.create(nome='Secretaria da educação', objeto_suprot=True)\n if not Classificacao.objects.filter(user=request.user).exists():\n Classificacao.objects.create(\n user=request.user,\n escola=suprot,\n tipo_de_acesso='Secretaria',\n matriz='Secretaria da educação')\n \n\n\n \n # pass\n\n\n\n # def __init__(self, get_response):\n # self.get_response = get_response \n \n \n # def __call__(self, request):\n # # Code to be executed for each request before\n # # the view (and later middleware) are called.\n\n \n\n # response = self.get_response(request)\n # if not request.user.is_authenticated:\n # print(request.user.is_authenticated)\n\n # # Code to be executed for each request/response after\n # # the view is called.\n\n # return response\n\n # def __call__(self, request):\n # # Here I call login if not authenticated and request is not login page\n # if request.user.is_authenticated == False and request.path != reverse('fazendo_login'):\n # return redirect(reverse('fazendo_login'))\n # response = self.get_response(request)\n # return response","repo_name":"JoseNascimento16/ProjetoPA","sub_path":"SetupPrincipal/middlewares.py","file_name":"middlewares.py","file_ext":"py","file_size_in_byte":3222,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"31234341195","text":"from django.contrib.auth import get_user_model\nfrom django.test import TestCase, Client\nfrom django.urls import reverse\nfrom django.conf import settings\nfrom django.core.cache import cache\n\nfrom posts.models import Group, Post\n\nUser = get_user_model()\n\nOFFSET = settings.AMOUNT_POST - 1\n\n\nclass PaginatorViewsTests(TestCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.user = User.objects.create_user(username='test')\n cls.group = Group.objects.create(\n title='test_group',\n slug='test_slug',\n description='test_descript',\n )\n for _ in range(OFFSET + settings.AMOUNT_POST):\n cls.post = Post.objects.create(\n author=cls.user,\n text='test_text',\n group=cls.group,\n )\n\n def setUp(self):\n cache.clear()\n self.authorized_client = Client()\n self.authorized_client.force_login(self.user)\n\n def test_first_page_contains_ten_records(self):\n templates_pages_names = [\n reverse('posts:index'),\n reverse('posts:profile', kwargs={\n 'username': 'test'\n }),\n reverse('posts:group_list', kwargs={\n 'slug': 'test_slug'\n }),\n ]\n for address in templates_pages_names:\n with self.subTest(address=address):\n response = self.authorized_client.get(reverse('posts:index'))\n self.assertEqual(\n len(response.context['page_obj']),\n settings.AMOUNT_POST\n )\n\n def test_second_page_contains_nine_records(self):\n templates_pages_names = [\n reverse('posts:index'),\n reverse('posts:profile', kwargs={\n 'username': 'test'\n }),\n reverse('posts:group_list', kwargs={\n 'slug': 'test_slug'\n }),\n ]\n for address in templates_pages_names:\n with self.subTest(address=address):\n response = self.authorized_client.get(\n reverse('posts:index') + '?page=2'\n )\n self.assertEqual(len(response.context['page_obj']), OFFSET)\n","repo_name":"EmilAbushaev/hw05_final","sub_path":"yatube/posts/tests/test_paginator.py","file_name":"test_paginator.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"}